From 11473b21f8bd3953ed911550fc7c3399d237c425 Mon Sep 17 00:00:00 2001 From: CJKmkp <2564608840@qq.com> Date: Sun, 29 Nov 2026 18:01:17 +0800 Subject: [PATCH 1/5] =?UTF-8?q?feat(UInk):=20=E5=8D=87=E7=BA=A7=E5=88=B0?= =?UTF-8?q?=20UInk=201.1=20=E5=B9=B6=E8=AE=BE=E4=B8=BA=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E4=BF=9D=E5=AD=98=E6=A0=BC=E5=BC=8F=20(#834)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 格式与读写 - 按 UInk 1.1 规范读写:Header version=11,可读 10–19;有界分帧、两遍式 Canvas 索引, 精确数值与 FILE/SAVE/CANVAS/TYPE 各项校验;损坏尾部与中段可恢复。 - 事务保存:备份恢复、资源并集、CRC 校验,主文件与 .extra 按 EXTRA-12..17 顺序提交; 保存、清理与读取共用跨进程目标锁,保证主文件与 .extra 成对。 - 公共字段优先,ICC 私有信息写入 extra;只保证存储正确,外来文件中 ICC 不支持的显示 按规范回退并提示另存,不新增渲染器。 映射与加载性能 - 页面投影、坐标/DPI/viewport 映射、WPF 笔宽公式、线性撤回历史回放; 单页 100 万点 Release 加载约 0.6–0.8 s(原 6.7 s),分配从约 1.2 GB 降到 236 MB。 - 后台保存队列(书写时推迟、合并定时保存,退出时排空),翻页时后台准备媒体。 内容类型 - 媒体:图片/PDF/音视频按原生布局往返,视频私有布局还原,资源缺失显示占位符。 - 图形:ICC 自产几何写成 Shape(复合图形用 object 组合),导出时校验并可还原为原生笔画; 手写识别字形按实际轮廓写出。 - PPT:按 SlideID 绑定逐页存储,删除的幻灯片作为 Retained 保留;取不到 SlideID 时 按页序绑定并提示。放映结束在 UInk 模式下归档为 slides.uink,缺失时回退 .icstk。 - PPT Agent 合同新增可选的 SlideId/SlideIds,新旧插件与 ICC 双向兼容 (VSTO 插件端仅静态核对,待 x64 机器构建实测)。 默认格式与入口 - 一次性迁移默认格式为 UInk(保留用户主动选择的 XML/整页图片);手动/定时保存、 截图伴随墨迹统一按格式设置;上传与自动清理包含 .extra。 - 打开对话框、命令行与 IPC 均支持 .uink。 测试 - InkCanvas.Calibration.Tests 新增 --uink-fixtures/-roundtrip/-robust/-reader/-bench/-all, 含 17 个官方样例、往返、变异鲁棒性、事务与加载基准;PDF 渲染测试在子进程中运行。 --- Ink Canvas/App.xaml.cs | 3 +- Ink Canvas/Helpers/DelAutoSavedFiles.cs | 97 +- Ink Canvas/Helpers/FileAssociationManager.cs | 15 +- Ink Canvas/Helpers/PPTAgentLinkManager.cs | 12 +- Ink Canvas/Helpers/PPTInkManager.cs | 51 +- Ink Canvas/Helpers/PdfWinRtHelper.cs | 182 +- Ink Canvas/Helpers/TimeMachine.cs | 28 +- Ink Canvas/Helpers/UploadHelper.cs | 108 + .../Helpers/WinRtHandwritingRecognizer.cs | 14 +- Ink Canvas/MainWindow.xaml.cs | 9 +- .../MainWindow_cs/MW_AutomationSaveStrokes.cs | 29 +- Ink Canvas/MainWindow_cs/MW_BoardControls.cs | 120 +- .../MainWindow_cs/MW_ElementsControls.cs | 87 +- .../MainWindow_cs/MW_FloatingBarIcons.cs | 8 +- Ink Canvas/MainWindow_cs/MW_InkFreeze.cs | 2 +- Ink Canvas/MainWindow_cs/MW_PPT.cs | 745 ++- .../MainWindow_cs/MW_Save&OpenStrokes.cs | 292 +- Ink Canvas/MainWindow_cs/MW_Screenshot.cs | 69 +- Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs | 5 + Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs | 972 +-- .../MW_SimulatePressure&InkToShape.cs | 55 +- Ink Canvas/MainWindow_cs/MW_TimeMachine.cs | 380 +- Ink Canvas/MainWindow_cs/MW_Timer.cs | 18 +- Ink Canvas/MainWindow_cs/MW_UInk.cs | 1550 ++++- .../Properties/CanvasStrings.en-US.resx | 21 + Ink Canvas/Properties/CanvasStrings.resx | 21 + .../Properties/CanvasStrings.zh-ME.resx | 21 + Ink Canvas/Resources/Settings.cs | 8 +- Ink Canvas/UInk/IccConicBranch.cs | 104 + Ink Canvas/UInk/IccGlyphMapping.cs | 106 + Ink Canvas/UInk/IccPublicShape.cs | 331 ++ Ink Canvas/UInk/IccShapeCapture.cs | 248 + Ink Canvas/UInk/IccShapeDescriptor.cs | 299 + Ink Canvas/UInk/IccShapeMapping.cs | 405 ++ Ink Canvas/UInk/IccShapeTools.cs | 275 + Ink Canvas/UInk/PptSlideStorage.cs | 124 + Ink Canvas/UInk/UInkAppend.cs | 2 + Ink Canvas/UInk/UInkBlockScanner.cs | 76 + Ink Canvas/UInk/UInkCaptureContext.cs | 242 + Ink Canvas/UInk/UInkContentDecoder.cs | 208 + Ink Canvas/UInk/UInkConversion.cs | 392 +- Ink Canvas/UInk/UInkCoordinateMap.cs | 64 + Ink Canvas/UInk/UInkExtraArchive.cs | 323 +- Ink Canvas/UInk/UInkFields.cs | 166 + Ink Canvas/UInk/UInkFormatters.cs | 922 +-- Ink Canvas/UInk/UInkHistoryReplay.cs | 126 + Ink Canvas/UInk/UInkHistorySnapshot.cs | 111 + Ink Canvas/UInk/UInkIccMapper.cs | 246 +- Ink Canvas/UInk/UInkMediaMapper.cs | 241 + Ink Canvas/UInk/UInkMediaRestoreCache.cs | 199 + Ink Canvas/UInk/UInkMediaWorkSet.cs | 184 + Ink Canvas/UInk/UInkMetadataDecoder.cs | 202 + Ink Canvas/UInk/UInkModel.cs | 106 +- Ink Canvas/UInk/UInkNumeric.cs | 85 + Ink Canvas/UInk/UInkPageProjection.cs | 181 + Ink Canvas/UInk/UInkPlayback.cs | 87 + Ink Canvas/UInk/UInkReadResult.cs | 64 + Ink Canvas/UInk/UInkReader.cs | 371 +- Ink Canvas/UInk/UInkSaveQueue.cs | 80 + Ink Canvas/UInk/UInkSaveService.cs | 422 +- Ink Canvas/UInk/UInkShapeDecoder.cs | 154 + Ink Canvas/UInk/UInkShowArchive.cs | 61 + Ink Canvas/UInk/UInkTestVisibility.cs | 3 + Ink Canvas/UInk/UInkUndoAdapter.cs | 198 +- Ink Canvas/UInk/UInkWriter.cs | 119 +- Ink Canvas/Windows/PPTQuickPanel.xaml.cs | 1 + .../SettingsViews/Helpers/SettingsManager.cs | 13 + .../InkCanvas.Calibration.Tests.csproj | 3 + InkCanvas.Calibration.Tests/Program.cs | 1 + .../TestData/UInk/v11/SHA256SUMS.txt | 17 + .../TestData/UInk/v11/basic-appearance.uink | Bin 0 -> 2630 bytes .../TestData/UInk/v11/compat-v10.uink | Bin 0 -> 1083 bytes .../TestData/UInk/v11/core-page-append.uink | Bin 0 -> 2718 bytes .../TestData/UInk/v11/core-pages.uink | Bin 0 -> 2333 bytes .../TestData/UInk/v11/core-shape-curves.uink | Bin 0 -> 3518 bytes .../TestData/UInk/v11/corrupt-middle.uink | Bin 0 -> 1011 bytes .../TestData/UInk/v11/fallback-unknown.uink | Bin 0 -> 1971 bytes .../TestData/UInk/v11/fixtures.json | 5237 +++++++++++++++++ .../TestData/UInk/v11/full-hdr-advanced.uink | Bin 0 -> 1765 bytes .../UInk/v11/full-layers-devices.uink | Bin 0 -> 2511 bytes .../TestData/UInk/v11/full-shape-preset.uink | Bin 0 -> 4662 bytes .../TestData/UInk/v11/future-minor.uink | Bin 0 -> 904 bytes .../TestData/UInk/v11/inkeys-erase-clear.uink | Bin 0 -> 1458 bytes .../TestData/UInk/v11/standard-media.uink | Bin 0 -> 1821 bytes .../UInk/v11/standard-media.uink.extra | Bin 0 -> 5061 bytes .../TestData/UInk/v11/standard-ppt.uink | Bin 0 -> 2787 bytes .../UInk/v11/standard-shape-object.uink | Bin 0 -> 4040 bytes .../TestData/UInk/v11/truncated-tail.uink | Bin 0 -> 741 bytes .../UInk/ShapeToolHeadReference.cs | 940 +++ InkCanvas.Calibration.Tests/UInk/UInkBench.cs | 176 + .../UInk/UInkCaptureTests.cs | 184 + .../UInk/UInkCodecCases.cs | 444 ++ .../UInk/UInkDefaultSaveTests.cs | 274 + .../UInk/UInkFixtureTests.cs | 528 ++ .../UInk/UInkLegacyReplayTests.cs | 622 ++ .../UInk/UInkMappingTests.cs | 292 + .../UInk/UInkMediaTests.cs | 1234 ++++ .../UInk/UInkPptTests.cs | 726 +++ .../UInk/UInkReaderTests.cs | 195 + .../UInk/UInkReplayAndSaveTests.cs | 344 ++ .../UInk/UInkReviewFixTests.cs | 321 + .../UInk/UInkRobustTests.cs | 267 + .../UInk/UInkRoundtripTests.cs | 187 + .../UInk/UInkShapeToolTests.cs | 883 +++ .../UInk/UInkSuites.cs | 251 + .../UInk/UInkTestApi.cs | 363 ++ .../UInk/UInkTestEncoder.cs | 214 + .../UInk/UInkTransactionTests.cs | 728 +++ .../UInk/UInkWireInspection.cs | 208 + InkCanvas.PPTAgent.Contracts/PptState.cs | 3 + .../Core/PPTController.cs | 13 +- 111 files changed, 23423 insertions(+), 3695 deletions(-) create mode 100644 Ink Canvas/UInk/IccConicBranch.cs create mode 100644 Ink Canvas/UInk/IccGlyphMapping.cs create mode 100644 Ink Canvas/UInk/IccPublicShape.cs create mode 100644 Ink Canvas/UInk/IccShapeCapture.cs create mode 100644 Ink Canvas/UInk/IccShapeDescriptor.cs create mode 100644 Ink Canvas/UInk/IccShapeMapping.cs create mode 100644 Ink Canvas/UInk/IccShapeTools.cs create mode 100644 Ink Canvas/UInk/PptSlideStorage.cs create mode 100644 Ink Canvas/UInk/UInkBlockScanner.cs create mode 100644 Ink Canvas/UInk/UInkCaptureContext.cs create mode 100644 Ink Canvas/UInk/UInkContentDecoder.cs create mode 100644 Ink Canvas/UInk/UInkCoordinateMap.cs create mode 100644 Ink Canvas/UInk/UInkFields.cs create mode 100644 Ink Canvas/UInk/UInkHistoryReplay.cs create mode 100644 Ink Canvas/UInk/UInkHistorySnapshot.cs create mode 100644 Ink Canvas/UInk/UInkMediaMapper.cs create mode 100644 Ink Canvas/UInk/UInkMediaRestoreCache.cs create mode 100644 Ink Canvas/UInk/UInkMediaWorkSet.cs create mode 100644 Ink Canvas/UInk/UInkMetadataDecoder.cs create mode 100644 Ink Canvas/UInk/UInkNumeric.cs create mode 100644 Ink Canvas/UInk/UInkPageProjection.cs create mode 100644 Ink Canvas/UInk/UInkPlayback.cs create mode 100644 Ink Canvas/UInk/UInkReadResult.cs create mode 100644 Ink Canvas/UInk/UInkSaveQueue.cs create mode 100644 Ink Canvas/UInk/UInkShapeDecoder.cs create mode 100644 Ink Canvas/UInk/UInkShowArchive.cs create mode 100644 Ink Canvas/UInk/UInkTestVisibility.cs create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/SHA256SUMS.txt create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/basic-appearance.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/compat-v10.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/core-page-append.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/core-pages.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/core-shape-curves.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/corrupt-middle.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/fallback-unknown.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/fixtures.json create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/full-hdr-advanced.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/full-layers-devices.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/full-shape-preset.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/future-minor.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/inkeys-erase-clear.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/standard-media.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/standard-media.uink.extra create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/standard-ppt.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/standard-shape-object.uink create mode 100644 InkCanvas.Calibration.Tests/TestData/UInk/v11/truncated-tail.uink create mode 100644 InkCanvas.Calibration.Tests/UInk/ShapeToolHeadReference.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkBench.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkCaptureTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkCodecCases.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkDefaultSaveTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkFixtureTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkLegacyReplayTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkMappingTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkMediaTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkPptTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkReaderTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkReplayAndSaveTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkReviewFixTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkRobustTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkRoundtripTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkShapeToolTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkSuites.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkTestApi.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkTestEncoder.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkTransactionTests.cs create mode 100644 InkCanvas.Calibration.Tests/UInk/UInkWireInspection.cs diff --git a/Ink Canvas/App.xaml.cs b/Ink Canvas/App.xaml.cs index 4aff66612..0eb20f5c9 100644 --- a/Ink Canvas/App.xaml.cs +++ b/Ink Canvas/App.xaml.cs @@ -1192,7 +1192,8 @@ private static bool IsLaunchByFileOrUri(string[] args) if (string.IsNullOrWhiteSpace(a)) continue; string t = a.Trim(); if (t.StartsWith("icc:", StringComparison.OrdinalIgnoreCase)) return true; - if (Path.GetExtension(t).Equals(".icstk", StringComparison.OrdinalIgnoreCase)) return true; + if (Path.GetExtension(t).Equals(".icstk", StringComparison.OrdinalIgnoreCase) || + FileAssociationManager.IsUInkStrokeFile(t)) return true; } return false; } diff --git a/Ink Canvas/Helpers/DelAutoSavedFiles.cs b/Ink Canvas/Helpers/DelAutoSavedFiles.cs index 23b73de81..45b28cc12 100644 --- a/Ink Canvas/Helpers/DelAutoSavedFiles.cs +++ b/Ink Canvas/Helpers/DelAutoSavedFiles.cs @@ -1,5 +1,7 @@ using System; using System.IO; +using System.Threading; +using Ink_Canvas.UInk; namespace Ink_Canvas.Helpers { @@ -10,10 +12,18 @@ public static void DeleteFilesOlder(string directoryPath, int daysThreshold) string[] extensionsToDel = { ".icstk", ".png", ".jpg" }; if (Directory.Exists(directoryPath)) { + directoryPath = Path.GetFullPath(directoryPath); + string cacheDirectory = Path.Combine(directoryPath, UInkMediaRestoreCache.CacheDirectoryName); + DateTime creationCutoff = DateTime.Now.AddDays(-daysThreshold); + if (Directory.Exists(cacheDirectory)) + WithUInkMediaCacheGate(() => DeleteExpiredUInkMedia(cacheDirectory, DateTime.UtcNow.AddDays(-daysThreshold))); // 获取目录中的所有子目录 string[] subDirectories = Directory.GetDirectories(directoryPath, "*", SearchOption.AllDirectories); foreach (string subDirectory in subDirectories) { + if (string.Equals(subDirectory, cacheDirectory, StringComparison.OrdinalIgnoreCase) || + subDirectory.StartsWith(cacheDirectory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + continue; try { // 获取子目录下的所有文件 @@ -25,9 +35,13 @@ public static void DeleteFilesOlder(string directoryPath, int daysThreshold) // 获取文件的扩展名 string fileExtension = Path.GetExtension(filePath); // 如果文件的创建日期早于指定天数且是要删除的扩展名,则删除文件 - if (creationDate < DateTime.Now.AddDays(-daysThreshold)) + if (creationDate < creationCutoff) { - if (Array.Exists(extensionsToDel, ext => ext.Equals(fileExtension, StringComparison.OrdinalIgnoreCase)) + if (fileExtension.Equals(".uink", StringComparison.OrdinalIgnoreCase)) + { + UInkSaveService.WithTargetLock(filePath, () => DeleteUInkPair(filePath, creationCutoff)); + } + else if (Array.Exists(extensionsToDel, ext => ext.Equals(fileExtension, StringComparison.OrdinalIgnoreCase)) || Path.GetFileName(filePath).Equals("Position", StringComparison.OrdinalIgnoreCase)) { File.Delete(filePath); @@ -43,7 +57,7 @@ public static void DeleteFilesOlder(string directoryPath, int daysThreshold) try { // 递归删除空文件夹 - DeleteEmptyFolders(directoryPath); + DeleteEmptyFolders(directoryPath, cacheDirectory); } catch (Exception ex) { @@ -52,11 +66,84 @@ public static void DeleteFilesOlder(string directoryPath, int daysThreshold) } } - private static void DeleteEmptyFolders(string directoryPath) + private static bool DeleteUInkPair(string path, DateTime cutoff) + { + try + { + // EXTRA-1/16:先取得两个文件的句柄,再先删主文件,避免留下缺资源包的主文件。 + using var main = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Delete); + if (File.GetCreationTime(path) >= cutoff) return false; + using var extra = OpenExtraForDeletion(path + ".extra"); + File.Delete(path); + if (extra != null) File.Delete(path + ".extra"); + return true; + } + catch (IOException) { } // 任一文件正在使用,留待下次清理。 + catch (UnauthorizedAccessException ex) + { + LogHelper.WriteLogToFile("DelAutoSavedFiles | 清理 UInk 快照失败: " + ex, LogHelper.LogType.Warning); + } + return false; + } + + private static FileStream OpenExtraForDeletion(string path) + { + try { return File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Delete); } + catch (FileNotFoundException) { return null; } + } + + internal static FileStream OpenUInkMediaCacheLease(string cacheDirectory, bool exclusive) => + File.Open(Path.Combine(cacheDirectory, ".retention.lock"), FileMode.OpenOrCreate, + FileAccess.ReadWrite, exclusive ? FileShare.None : FileShare.ReadWrite); + + internal static void WithUInkMediaCacheGate(Action action) + { + // 跨进程串行化启动清理与首次打开,避免把清理期间的共享冲突当成缺资源。 + using var gate = new Mutex(false, "ICC-UInk-MediaRetention"); + try { gate.WaitOne(); } + catch (AbandonedMutexException) { } + try { action(); } + finally { gate.ReleaseMutex(); } + } + + private static void DeleteExpiredUInkMedia(string cacheDirectory, DateTime cutoff) + { + if (!Directory.Exists(cacheDirectory)) return; + try + { + if ((File.GetAttributes(cacheDirectory) & FileAttributes.ReparsePoint) != 0) return; + // 控件和离页历史可能只保留路径。任一 ICC 实例持有缓存租约时跳过整个缓存。 + using var lease = OpenUInkMediaCacheLease(cacheDirectory, exclusive: true); + foreach (string path in Directory.EnumerateFiles(cacheDirectory)) + { + if (string.Equals(path, lease.Name, StringComparison.OrdinalIgnoreCase)) continue; + try + { + if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0 || + File.GetLastAccessTimeUtc(path) >= cutoff) continue; + using var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Delete); + File.Delete(path); + } + catch (IOException) { } // 文件被占用或已由其他程序移除。 + catch (UnauthorizedAccessException ex) + { + LogHelper.WriteLogToFile("DelAutoSavedFiles | 清理 UInk 缓存文件失败: " + ex, LogHelper.LogType.Warning); + } + } + } + catch (IOException) { } // 缓存正在使用。 + catch (UnauthorizedAccessException ex) + { + LogHelper.WriteLogToFile("DelAutoSavedFiles | 清理 UInk 缓存目录失败: " + ex, LogHelper.LogType.Warning); + } + } + + private static void DeleteEmptyFolders(string directoryPath, string cacheDirectory) { foreach (string dir in Directory.GetDirectories(directoryPath)) { - DeleteEmptyFolders(dir); + if (string.Equals(dir, cacheDirectory, StringComparison.OrdinalIgnoreCase)) continue; + DeleteEmptyFolders(dir, cacheDirectory); if (Directory.GetFiles(dir).Length == 0 && Directory.GetDirectories(dir).Length == 0) { Directory.Delete(dir, false); diff --git a/Ink Canvas/Helpers/FileAssociationManager.cs b/Ink Canvas/Helpers/FileAssociationManager.cs index f3866fe39..ec2030a51 100644 --- a/Ink Canvas/Helpers/FileAssociationManager.cs +++ b/Ink Canvas/Helpers/FileAssociationManager.cs @@ -379,11 +379,14 @@ private static void RefreshSystemFileAssociations() } } + internal static bool IsUInkStrokeFile(string path) => + string.Equals(Path.GetExtension(path), ".uink", StringComparison.OrdinalIgnoreCase); + /// /// 处理命令行参数中的文件路径 /// /// 命令行参数 - /// 找到的.icstk文件路径,如果没有找到则返回null + /// 找到的 .icstk 或 .uink 文件路径,如果没有找到则返回 null public static string GetIcstkFileFromArgs(string[] args) { if (args == null || args.Length == 0) return null; @@ -392,18 +395,17 @@ public static string GetIcstkFileFromArgs(string[] args) { if (string.IsNullOrEmpty(arg)) continue; - // 检查是否为.icstk文件 - if (Path.GetExtension(arg).Equals(FileExtension, StringComparison.OrdinalIgnoreCase)) + if (Path.GetExtension(arg).Equals(FileExtension, StringComparison.OrdinalIgnoreCase) || IsUInkStrokeFile(arg)) { // 检查文件是否存在 if (File.Exists(arg)) { - LogHelper.WriteLogToFile($"从命令行参数中找到.icstk文件: {arg}", LogHelper.LogType.Event); + LogHelper.WriteLogToFile($"从命令行参数中找到墨迹文件: {arg}", LogHelper.LogType.Event); return arg; } else { - LogHelper.WriteLogToFile($"命令行参数中的.icstk文件不存在: {arg}", LogHelper.LogType.Warning); + LogHelper.WriteLogToFile($"命令行参数中的墨迹文件不存在: {arg}", LogHelper.LogType.Warning); } } } @@ -873,7 +875,8 @@ private static void ProcessIpcFiles() if (Application.Current.MainWindow is MainWindow mainWindow) { mainWindow.OpenSingleStrokeFile(filePath); - mainWindow.ShowNotification(string.Format(AutomationStrings.FileAssoc_LoadedStrokesFile, Path.GetFileName(filePath))); + if (!IsUInkStrokeFile(filePath)) + mainWindow.ShowNotification(string.Format(AutomationStrings.FileAssoc_LoadedStrokesFile, Path.GetFileName(filePath))); } } catch (Exception ex) diff --git a/Ink Canvas/Helpers/PPTAgentLinkManager.cs b/Ink Canvas/Helpers/PPTAgentLinkManager.cs index b0e310b26..2159abaa5 100644 --- a/Ink Canvas/Helpers/PPTAgentLinkManager.cs +++ b/Ink Canvas/Helpers/PPTAgentLinkManager.cs @@ -82,7 +82,6 @@ public bool TryNavigateToSlide(int slideNumber) public string GetPresentationName() => GetStateSnapshot().PresentationName ?? string.Empty; - // Agent 模式只同步演示名称,不跟踪完整文件路径,返回 null public string GetPresentationPath() => null; public bool TryShowSlideNavigation() => Send(PPTCommands.ShowSlideNavigation); @@ -178,8 +177,11 @@ private void HandleState(PPTState state, string eventName) { var oldRunning = _lastIsRunning; var oldSlide = _lastSlideIndex; + var oldId = _lastState.SlideId; var oldPresentation = _lastPresentationName; + bool changedPresentation = MainWindow.DifferentShow(_lastState.PresentationFullName, oldPresentation, + state.PresentationFullName, state.PresentationName); _lastState = state; _lastIsRunning = state.IsRunning; _lastSlideIndex = state.SlideIndex; @@ -206,10 +208,14 @@ private void HandleState(PPTState state, string eventName) raisePresentationOpen = hasPresentation && (!hadPresentation || !string.Equals(oldPresentation, state.PresentationName, StringComparison.OrdinalIgnoreCase)); raisePresentationClose = !hasPresentation && hadPresentation; raiseSlideShowBegin = !oldRunning && state.IsRunning; - raiseSlideShowNext = oldRunning && state.IsRunning && oldSlide > 0 && state.SlideIndex > 0 && oldSlide != state.SlideIndex; + raiseSlideShowNext = oldRunning && state.IsRunning && oldSlide > 0 && state.SlideIndex > 0 && + (oldSlide != state.SlideIndex || oldId != state.SlideId); raiseSlideShowEnd = oldRunning && !state.IsRunning; } + if (changedPresentation && oldRunning && state.IsRunning && !raiseSlideShowBegin && + !raiseSlideShowEnd && !raisePresentationClose) raiseSlideShowNext = true; + if (oldRunning != state.IsRunning || raiseSlideShowBegin || raiseSlideShowEnd) { raiseShowStateChanged = true; @@ -241,6 +247,8 @@ private PPTState GetStateSnapshot() return new PPTState { SlideIndex = _lastState.SlideIndex, + SlideId = _lastState.SlideId, + SlideIds = _lastState.SlideIds, TotalSlides = _lastState.TotalSlides, IsRunning = _lastState.IsRunning, PresentationName = _lastState.PresentationName, diff --git a/Ink Canvas/Helpers/PPTInkManager.cs b/Ink Canvas/Helpers/PPTInkManager.cs index 5f5006e34..ed71581cb 100644 --- a/Ink Canvas/Helpers/PPTInkManager.cs +++ b/Ink Canvas/Helpers/PPTInkManager.cs @@ -1,6 +1,7 @@ using Microsoft.Office.Interop.PowerPoint; using System; using System.IO; +using Ink_Canvas.UInk; using System.Runtime.InteropServices; using System.Windows.Ink; @@ -18,6 +19,15 @@ public class PPTInkManager : IDisposable #endregion #region Private Fields + private readonly IPptSlideStorage _showInk; + private readonly Func _showKey; + + internal PPTInkManager(IPptSlideStorage showInk, Func showKey) : this() + { + _showInk = showInk; + _showKey = showKey; + } + private MemoryStream[] _memoryStreams; private const int DefaultMaxSlides = 100; private int _maxSlides = DefaultMaxSlides; @@ -80,7 +90,9 @@ private void InitializeMemoryStreams(int capacity) /// 如果已启用自动保存且设置了 ,则会尝试加载磁盘上的已保存墨迹文件。 /// /// 要初始化的 PowerPoint Presentation 实例;为 null 时方法不执行任何操作并直接返回。 - public void InitializePresentation(Presentation presentation) + public void InitializePresentation(Presentation presentation) => InitializePresentation(presentation, true); + + internal void InitializePresentation(Presentation presentation, bool loadSavedInk) { ThrowIfDisposed(); if (presentation == null) return; @@ -113,7 +125,7 @@ public void InitializePresentation(Presentation presentation) _maxSlides = Math.Max(_maxSlides, slideCount); _memoryStreams = new MemoryStream[capacity]; - if (IsAutoSaveEnabled && !string.IsNullOrEmpty(AutoSaveLocation)) + if (loadSavedInk && IsAutoSaveEnabled && !string.IsNullOrEmpty(AutoSaveLocation)) LoadSavedStrokes(); } catch (Exception ex) @@ -141,6 +153,11 @@ public void SaveCurrentSlideStrokes(int slideIndex, StrokeCollection strokes) try { if (!CanWriteInk(slideIndex)) return; + if (_showInk != null) + { + _showInk.Write(_showKey(slideIndex), PptSlideStorage.Encode(strokes)); + return; + } if (slideIndex >= _memoryStreams.Length) return; ReplaceSlideStream(slideIndex, strokes); @@ -170,6 +187,11 @@ public void ForceSaveSlideStrokes(int slideIndex, StrokeCollection strokes) { try { + if (_showInk != null) + { + _showInk.Write(_showKey(slideIndex), PptSlideStorage.Encode(strokes)); + return; + } if (slideIndex >= _memoryStreams.Length) return; ReplaceSlideStream(slideIndex, strokes); LogHelper.WriteLogToFile($"已强制保存第{slideIndex}页墨迹", LogHelper.LogType.Trace); @@ -198,6 +220,7 @@ public StrokeCollection LoadSlideStrokes(int slideIndex) { try { + if (_showInk != null) return PptSlideStorage.Decode(_showInk.Read(_showKey(slideIndex))); if (slideIndex < _memoryStreams.Length && _memoryStreams[slideIndex] != null && _memoryStreams[slideIndex].Length > 0) { _memoryStreams[slideIndex].Position = 0; @@ -287,21 +310,16 @@ public void SaveAllStrokesToFile(Presentation presentation, int currentSlideInde throw; } - for (int i = 1; i <= slideCount && i < _memoryStreams.Length; i++) + for (int i = 1; i <= slideCount && (_showInk != null || i < _memoryStreams.Length); i++) { - if (_memoryStreams[i] == null) continue; try { - if (_memoryStreams[i].Length > 8) + var bytes = _showInk == null ? _memoryStreams[i]?.ToArray() : _showInk.Read(_showKey(i)); + if (bytes == null) continue; + if (bytes.Length > 8) { - _memoryStreams[i].Position = 0; - byte[] buf = new byte[_memoryStreams[i].Length]; - int read = _memoryStreams[i].Read(buf, 0, buf.Length); - if (read > 0) - { - string basePath = Path.Combine(folderPath, i.ToString("0000")); - File.WriteAllBytes(basePath + StrokeFileExtension, buf); - } + string basePath = Path.Combine(folderPath, i.ToString("0000")); + File.WriteAllBytes(basePath + StrokeFileExtension, bytes); } else { @@ -348,15 +366,15 @@ public void LoadSavedStrokes() { string nameWithoutExt = Path.GetFileNameWithoutExtension(file.Name); if (!int.TryParse(nameWithoutExt, out int slideIndex) || slideIndex <= 0) continue; - if (slideIndex >= _memoryStreams.Length) continue; + if (_showInk == null && slideIndex >= _memoryStreams.Length) continue; try { byte[] bytes = File.ReadAllBytes(file.FullName); if (bytes.Length > 8) { - _memoryStreams[slideIndex] = new MemoryStream(bytes); - _memoryStreams[slideIndex].Position = 0; + if (_showInk != null) _showInk.Write(_showKey(slideIndex), bytes); + else _memoryStreams[slideIndex] = new MemoryStream(bytes); loadedCount++; } } @@ -388,6 +406,7 @@ public void ClearAllStrokes() ThrowIfDisposed(); lock (_lockObject) { + _showInk?.Clear(); ClearAllStrokesInternal(); } } diff --git a/Ink Canvas/Helpers/PdfWinRtHelper.cs b/Ink Canvas/Helpers/PdfWinRtHelper.cs index ca3f0c455..b910fb830 100644 --- a/Ink Canvas/Helpers/PdfWinRtHelper.cs +++ b/Ink Canvas/Helpers/PdfWinRtHelper.cs @@ -1,11 +1,13 @@ using System; using System.IO; +using System.Runtime.InteropServices; +using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Imaging; -using Windows.Data.Pdf; -using Windows.Storage; -using Windows.Storage.Streams; +using global::Windows.Data.Pdf; +using global::Windows.Storage; +using global::Windows.Storage.Streams; namespace Ink_Canvas.Helpers { @@ -14,6 +16,19 @@ namespace Ink_Canvas.Helpers /// internal static class PdfWinRtHelper { + internal const int UInkMaxSide = 4096; + internal const long UInkMaxPixels = 16_000_000; + internal const int UInkMaxOutputBytes = 64 * 1024 * 1024; + private static readonly AsyncLocal UInkRenderBudget = new(); + // PdfEmbeddedView 的翻页和初始化共用旧渲染入口;预算仅随 UInk 调用链生效。 + internal static async Task WithUInkRenderBudgetAsync(Func render) + { + bool previous = UInkRenderBudget.Value; + UInkRenderBudget.Value = true; + try { await render(); } + finally { UInkRenderBudget.Value = previous; } + } + public static async Task GetPageCountAsync(string pdfPath) { if (string.IsNullOrWhiteSpace(pdfPath) || !File.Exists(pdfPath)) @@ -28,6 +43,9 @@ public static async Task GetPageCountAsync(string pdfPath) public static async Task RenderPageToBitmapSourceAsync(string pdfPath, uint pageIndex) { + if (UInkRenderBudget.Value) + return await Task.Run(() => RenderUInkPageAsync(pdfPath, pageIndex)); + if (string.IsNullOrWhiteSpace(pdfPath) || !File.Exists(pdfPath)) return null; @@ -75,5 +93,163 @@ public static async Task RenderPageToBitmapSourceAsync(string pdfP (page as IDisposable)?.Dispose(); } } + + [DllImport("user32.dll", ExactSpelling = true)] + private static extern uint GetDpiForSystem(); + + [DllImport("user32.dll", ExactSpelling = true)] + private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); + + private static double SystemDpiScale() + { + // 无 DPI 清单的测试进程也要读取实际系统 DPI;只在查询期间切换线程上下文。 + var previous = SetThreadDpiAwarenessContext(new IntPtr(-2)); // DPI_AWARENESS_CONTEXT_SYSTEM_AWARE + try { return Math.Max(1, GetDpiForSystem() / 96d); } + finally { if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous); } + } + + internal static Size UInkRenderSize(double width, double height, double outputScale = 1) + { + if (!double.IsFinite(width) || !double.IsFinite(height) || width <= 0 || height <= 0) + throw new InvalidDataException("Invalid UInk PDF page size."); + + // EXTRA-7/8:限制 WinRT 光栅化的输出像素,先把上限换算为请求 DIP。 + double side = Math.Floor(UInkMaxSide / outputScale); + double pixels = UInkMaxPixels / outputScale / outputScale; + double scale = Math.Min(1, side / Math.Max(width, height)); + scale = Math.Min(scale, Math.Sqrt(pixels / width / height)); + double requestWidth = Math.Max(1, Math.Floor(width * scale)); + double requestHeight = Math.Max(1, Math.Floor(height * scale)); + double outputPixels = Math.Ceiling(requestWidth * outputScale) * Math.Ceiling(requestHeight * outputScale); + if (outputPixels > UInkMaxPixels) + { + // 按向上取整的实际像素估计留余量,避免两个方向的取整合计越过面积预算。 + double correction = Math.Sqrt(UInkMaxPixels / outputPixels); + requestWidth = Math.Max(1, Math.Floor(requestWidth * correction)); + requestHeight = Math.Max(1, Math.Floor(requestHeight * correction)); + } + return new Size(requestWidth, requestHeight); + } + + internal static async Task GetUInkPageCountAsync(string path) + { + var doc = await OpenUInkPdfAsync(path).ConfigureAwait(false); + return doc.IsPasswordProtected ? 0 : doc.PageCount; + } + + private static async Task OpenUInkPdfAsync(string path) + { + var getFile = StorageFile.GetFileFromPathAsync(path); + StorageFile file; + try { file = await getFile.AsTask().ConfigureAwait(false); } + finally { getFile.Close(); } + + var load = PdfDocument.LoadFromFileAsync(file); + try { return await load.AsTask().ConfigureAwait(false); } + finally { load.Close(); } + } + + private static async Task RenderUInkPageAsync(string path, uint index) + { + var doc = await OpenUInkPdfAsync(path).ConfigureAwait(false); + if (doc.IsPasswordProtected || index >= doc.PageCount) + throw new InvalidDataException("UInk PDF page is unavailable."); + + var page = doc.GetPage(index); + using var pageLifetime = page as IDisposable; + var pageSize = page.Size; + var size = UInkRenderSize(pageSize.Width, pageSize.Height, SystemDpiScale()); + for (int attempt = 0; attempt < 2; attempt++) + { + var options = new PdfPageRenderOptions + { + DestinationWidth = (uint)size.Width, + DestinationHeight = (uint)size.Height, + BitmapEncoderId = global::Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId + }; + using var output = new UInkPdfOutputStream(UInkMaxOutputBytes); + using (var randomAccess = output.AsRandomAccessStream()) + { + var render = page.RenderToStreamAsync(randomAccess, options); + try { await render.AsTask().ConfigureAwait(false); } + finally { render.Close(); } + + output.Position = 0; + var metadata = BitmapFrame.Create(output, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); + int width = metadata.PixelWidth, height = metadata.PixelHeight; + if (width <= 0 || height <= 0) break; + if (width <= UInkMaxSide && height <= UInkMaxSide && (long)width * height <= UInkMaxPixels) + { + var bitmap = new CachedBitmap(metadata, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); + bitmap.Freeze(); + return bitmap; + } + + // 某些环境的 WinRT 输出倍率高于系统 DPI 推算值,按实测倍率重试一次。 + if (attempt == 0) + { + double observed = Math.Max(width / size.Width, height / size.Height); + size = UInkRenderSize(pageSize.Width, pageSize.Height, observed); + } + } + } + throw new InvalidDataException("UInk PDF raster pixel budget exceeded."); + } + + internal sealed class UInkPdfOutputStream : MemoryStream + { + private readonly int _limit; + + internal UInkPdfOutputStream(int limit) => _limit = limit; + + private void Check(long bytes) + { + if (bytes > _limit) throw new InvalidDataException("UInk PDF raster byte budget exceeded."); + } + + public override int Capacity + { + get => base.Capacity; + set { Check(value); base.Capacity = value; } + } + + public override void SetLength(long value) + { + Check(value); + Reserve(value); + base.SetLength(value); + } + + // MemoryStream 默认可能把容量翻倍到预算以外,先按预算约束容量增长。 + private void Reserve(long length) + { + if (length > Capacity) Capacity = (int)Math.Min(_limit, Math.Max(length, Math.Max(256L, Capacity * 2L))); + } + + private void PrepareWrite(int count) + { + long end = Position + count; + Check(end); + Reserve(end); + } + + public override void Write(byte[] buffer, int offset, int count) + { + PrepareWrite(count); + base.Write(buffer, offset, count); + } + + public override void Write(ReadOnlySpan buffer) + { + PrepareWrite(buffer.Length); + base.Write(buffer); + } + + public override void WriteByte(byte value) + { + PrepareWrite(1); + base.WriteByte(value); + } + } } } diff --git a/Ink Canvas/Helpers/TimeMachine.cs b/Ink Canvas/Helpers/TimeMachine.cs index 08e546c7d..fafed99e4 100644 --- a/Ink Canvas/Helpers/TimeMachine.cs +++ b/Ink Canvas/Helpers/TimeMachine.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Windows; +using System.Windows.Controls; using System.Windows.Ink; +using Ink_Canvas.UInk; using System.Windows.Input; using System.Windows.Media; @@ -42,7 +44,7 @@ public bool TryReplaceLastUserInputHistory(StrokeCollection stroke) } var item = _currentStrokeHistory[_currentIndex]; - if (item.CommitType != TimeMachineHistoryType.UserInput || item.StrokeHasBeenCleared) + if (item is UInkGroupHistory || item.CommitType != TimeMachineHistoryType.UserInput || item.StrokeHasBeenCleared) { return false; } @@ -150,6 +152,14 @@ public TimeMachineHistory Redo() return item; } + // 保存只读游标前的条目;保留 redo 分支,引用仅由 UI 线程短暂读取。 + public TimeMachineHistory[] GetAppliedHistorySnapshot() + { + var applied = new TimeMachineHistory[_currentIndex + 1]; + _currentStrokeHistory.CopyTo(0, applied, 0, applied.Length); + return applied; + } + public TimeMachineHistory[] ExportTimeMachineHistory() { if (_currentIndex + 1 < _currentStrokeHistory.Count) @@ -289,6 +299,22 @@ public TimeMachineHistory( } } + // 保留 UserInput 分类,既有翻页快照会据此识别已经入栈的笔迹。 + public sealed class UInkGroupHistory : TimeMachineHistory + { + // 与本组 Media 的流序一一对应;资源缺失或尚未安装时槽位为空。 + public readonly UIElement[] Elements; + + public UInkGroupHistory(StrokeCollection strokes, int mediaCount) + : base(strokes, TimeMachineHistoryType.UserInput, false) + { + Elements = mediaCount == 0 ? Array.Empty() : new UIElement[mediaCount]; + } + + internal void ApplyTo(InkCanvas canvas, bool includeElements) => + new UInkCanvasReplay(canvas, includeElements).Apply(this); + } + public enum TimeMachineHistoryType { ElementEdit, diff --git a/Ink Canvas/Helpers/UploadHelper.cs b/Ink Canvas/Helpers/UploadHelper.cs index 40376a54b..597a63d7c 100644 --- a/Ink Canvas/Helpers/UploadHelper.cs +++ b/Ink Canvas/Helpers/UploadHelper.cs @@ -36,7 +36,18 @@ public interface IUploadProvider /// public class DlassUploadProvider : IUploadProvider { + private sealed class SnapshotQueue : DlassUploadQueue + { + // 普通保存仍走持久队列。快照需等到真实传输结束,才能释放临时文件。 + protected override HashSet AllowedExtensions => new(base.AllowedExtensions) { ".uink", ".extra" }; + + internal Task SendAsync(string path) => IsRetryableError(path) + ? UploadFileInternalAsync(path, CancellationToken.None) : Task.FromResult(false); + } + + private static readonly SnapshotQueue snapshotQueue = new(); public static readonly DlassUploadQueue Queue = new DlassUploadQueue(); + internal Task SendSnapshotAsync(string path) => snapshotQueue.SendAsync(path); /// /// 提供者名称 @@ -65,7 +76,18 @@ public async Task UploadAsync(string filePath, CancellationToken cancellat /// public class WebDavUploadProvider : IUploadProvider { + private sealed class SnapshotQueue : WebDavUploadQueue + { + // 普通保存仍走持久队列。快照需等到真实传输结束,才能释放临时文件。 + protected override HashSet AllowedExtensions => new(base.AllowedExtensions) { ".uink", ".extra" }; + + internal Task SendAsync(string path) => IsRetryableError(path) + ? UploadFileInternalAsync(path, CancellationToken.None) : Task.FromResult(false); + } + + private static readonly SnapshotQueue snapshotQueue = new(); public static readonly WebDavUploadQueue Queue = new WebDavUploadQueue(); + internal Task SendSnapshotAsync(string path) => snapshotQueue.SendAsync(path); /// /// 提供者名称 @@ -232,6 +254,92 @@ public static async Task UploadFileAsync(string filePath, CancellationToke return anySuccess; } + private static readonly Dictionary snapshotUploads = new(StringComparer.OrdinalIgnoreCase); + + // 回调运行在已提交目标的事务锁内;返回前必须已经完成两份复制。 + internal static void QueueUInkSnapshot(string path) + { + try + { + var providers = GetEnabledProviders(); + providers.RemoveAll(p => (p is DlassUploadProvider && MainWindow.Settings?.Dlass?.IsAutoUploadNotes != true) || + (p is WebDavUploadProvider && !WebDavUploader.IsWebDavEnabled())); + if (providers.Count != 0) + _ = UploadUInkSnapshotAsync(path, providers, MainWindow.Settings?.Upload?.UploadDelayMinutes ?? 0); + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"UInk 上传准备失败 | {path} | {ex}", LogHelper.LogType.Warning); + } + } + + internal static async Task UploadUInkSnapshotAsync(string path, IReadOnlyList providers, int delayMinutes) + { + string folder = Path.Combine(Path.GetTempPath(), "UInkUpload_" + Guid.NewGuid().ToString("N")); + Task sending = null; + string target = null; + try + { + target = UInk.UInkSaveService.NormalizeTarget(path); + Directory.CreateDirectory(folder); + string main = Path.Combine(folder, Path.GetFileName(path)); + File.Copy(path, main); + bool hasExtra = File.Exists(path + ".extra"); + if (hasExtra) File.Copy(path + ".extra", main + ".extra"); + + var delay = delayMinutes > 0 ? Task.Delay(TimeSpan.FromMinutes(delayMinutes)) : Task.CompletedTask; + lock (snapshotUploads) + { + var previous = snapshotUploads.GetValueOrDefault(target) ?? Task.CompletedTask; + // 同名远端目标按提交顺序发布;不同目标可并行,各自的延迟从提交时起算。 + sending = Task.Run(async () => + { + await Task.WhenAll(previous, delay).ConfigureAwait(false); + foreach (var provider in providers) + { + if (!provider.IsEnabled) continue; + if (hasExtra && !await SendSnapshotFileAsync(provider, main + ".extra").ConfigureAwait(false)) continue; + await SendSnapshotFileAsync(provider, main).ConfigureAwait(false); + } + }); + snapshotUploads[target] = sending; + } + await sending.ConfigureAwait(false); + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"UInk 上传快照失败 | {path} | {ex}", LogHelper.LogType.Warning); + } + finally + { + lock (snapshotUploads) + if (sending != null && ReferenceEquals(snapshotUploads.GetValueOrDefault(target), sending)) + snapshotUploads.Remove(target); + try { if (Directory.Exists(folder)) Directory.Delete(folder, true); } + catch (Exception ex) { LogHelper.WriteLogToFile($"UInk 上传快照清理失败 | {folder} | {ex}", LogHelper.LogType.Warning); } + } + } + + private static async Task SendSnapshotFileAsync(IUploadProvider provider, string path) + { + try + { + var sending = provider switch + { + DlassUploadProvider dlass => dlass.SendSnapshotAsync(path), + WebDavUploadProvider webDav => webDav.SendSnapshotAsync(path), + _ => provider.UploadAsync(path) + }; + if (await sending.ConfigureAwait(false)) return true; + LogHelper.WriteLogToFile($"UInk 上传失败 | {provider.Name} | {Path.GetFileName(path)}", LogHelper.LogType.Warning); + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"UInk 上传失败 | {provider.Name} | {Path.GetFileName(path)} | {ex}", LogHelper.LogType.Warning); + } + return false; + } + /// /// 获取所有上传提供者 /// diff --git a/Ink Canvas/Helpers/WinRtHandwritingRecognizer.cs b/Ink Canvas/Helpers/WinRtHandwritingRecognizer.cs index d88a67a75..b8af76267 100644 --- a/Ink Canvas/Helpers/WinRtHandwritingRecognizer.cs +++ b/Ink Canvas/Helpers/WinRtHandwritingRecognizer.cs @@ -791,6 +791,7 @@ private static List CreateHandwritingGlyphStrokes( internal sealed class FilledGlyphStroke : Stroke { private readonly Geometry _geometry; + internal Geometry GlyphGeometry => _geometry; private FilledGlyphStroke(StylusPointCollection pts, Geometry geometry, DrawingAttributes da) : base(pts) @@ -818,7 +819,18 @@ public static FilledGlyphStroke TryCreate(Geometry geometry, DrawingAttributes t new StylusPoint(b.Left, b.Bottom, 0.5f), }; - return new FilledGlyphStroke(pts, geometry, templateDa); + var stroke = new FilledGlyphStroke(pts, geometry, templateDa); + UInk.IccShapeDescriptor.TagGlyph(stroke); + return stroke; + } + + // UInk 读回时配方已核对,避免重新展开轮廓。 + internal static FilledGlyphStroke FromPolygon(Geometry geometry, DrawingAttributes da) + { + var b = geometry.Bounds; + if (b.IsEmpty || b.Width <= 0 || b.Height <= 0) return null; + var points = new StylusPointCollection(new[] { b.TopLeft, b.TopRight, b.BottomRight, b.BottomLeft }); + return new FilledGlyphStroke(points, geometry, da); } protected override void DrawCore(DrawingContext drawingContext, DrawingAttributes drawingAttributes) diff --git a/Ink Canvas/MainWindow.xaml.cs b/Ink Canvas/MainWindow.xaml.cs index 522d61ae0..37d21a3f2 100644 --- a/Ink Canvas/MainWindow.xaml.cs +++ b/Ink Canvas/MainWindow.xaml.cs @@ -2062,6 +2062,11 @@ private void Window_Closed(object sender, EventArgs e) { LogHelper.WriteLogToFile("[Exit] 主窗口 Closed,开始释放资源", LogHelper.LogType.Info); + // 重启可直接调用 Application.Shutdown,无法依赖取消 Closing。写入线程不等待 UI 续体。 + // 先等待保存,再启动退出保险丝,避免保险丝提前中断写入。 + if (!_uinkSaves.DrainAsync().Wait(TimeSpan.FromSeconds(30))) + LogHelper.WriteLogToFile("UInk 退出时等待保存超过 30 秒", LogHelper.LogType.Warning); + // 进入不可逆的退出清理阶段:启动退出保险丝。 // 后续清理链(相机/PPT COM/插件卸载等)任一步卡死时,由保险丝超时强制结束进程, // 否则会出现"窗口已关、任务管理器里进程仍挂着"的残留。 @@ -3590,7 +3595,9 @@ private void HandleCommandLineFileOpen() { // 打开文件 OpenSingleStrokeFile(icstkFile); - ShowNotification(string.Format(Properties.MainWindowStrings.Main_StrokesFileLoaded, Path.GetFileName(icstkFile))); + // UInk 异步解码完成后会报告实际打开结果。 + if (!FileAssociationManager.IsUInkStrokeFile(icstkFile)) + ShowNotification(string.Format(Properties.MainWindowStrings.Main_StrokesFileLoaded, Path.GetFileName(icstkFile))); } catch (Exception ex) { diff --git a/Ink Canvas/MainWindow_cs/MW_AutomationSaveStrokes.cs b/Ink Canvas/MainWindow_cs/MW_AutomationSaveStrokes.cs index ee0b285ad..440763cc5 100644 --- a/Ink Canvas/MainWindow_cs/MW_AutomationSaveStrokes.cs +++ b/Ink Canvas/MainWindow_cs/MW_AutomationSaveStrokes.cs @@ -48,36 +48,13 @@ public void SaveStrokesForAutomation(string savePath, bool saveAsXml) if (isPptMode) { hasMultiplePages = true; - var totalSlides = _pptManager.SlidesCount; - var currentSlide = _pptManager.GetCurrentSlideNumber(); - - for (int i = 1; i <= totalSlides; i++) - { - var slideStrokes = _singlePPTInkManager?.LoadSlideStrokes(i); - if (slideStrokes != null && slideStrokes.Count > 0) - { - allPageStrokes.Add(slideStrokes); - } - else if (i == currentSlide && inkCanvas.Strokes.Count > 0) - { - allPageStrokes.Add(inkCanvas.Strokes.Clone()); - } - else - { - allPageStrokes.Add(new StrokeCollection()); - } - } + allPageStrokes = CollectLegacyPptStrokes(); } else if (currentMode != 0 && WhiteboardTotalCount > 1) { hasMultiplePages = true; - for (int i = 1; i <= WhiteboardTotalCount; i++) - { - var strokes = TimeMachineHistories[i] != null - ? ApplyHistoriesToNewStrokeCollection(TimeMachineHistories[i]) - : new StrokeCollection(); - allPageStrokes.Add(strokes); - } + // 复用常规保存的逐页取笔迹逻辑,未翻到的 UInk 页也参与导出。 + allPageStrokes = CollectLegacyWhiteboardStrokes(); } if (hasMultiplePages && allPageStrokes.Count > 0) diff --git a/Ink Canvas/MainWindow_cs/MW_BoardControls.cs b/Ink Canvas/MainWindow_cs/MW_BoardControls.cs index 4c679f813..4fce0af2a 100644 --- a/Ink Canvas/MainWindow_cs/MW_BoardControls.cs +++ b/Ink Canvas/MainWindow_cs/MW_BoardControls.cs @@ -92,24 +92,14 @@ private void SaveStrokes(bool isBackupMain = false) if (_canvasGestureOwnsTouchInput) ResetCanvasGestureInput(); EndBoardRoaming(); ApplyFreezeStateToCurrentStrokes(); + var uinkSlot = isBackupMain ? null : GetUInkSlot(CurrentWhiteboardIndex); + if (uinkSlot != null && _boardResources != null) + uinkSlot.Background = CurrentUInkBackground(uinkSlot); // 确保画布上的所有UI元素都被保存到时间机器历史记录中 var currentHistory = timeMachine.ExportTimeMachineHistory(); - var elementsInHistory = new HashSet(); - - // 收集已经在历史记录中的元素 - if (currentHistory != null) - { - foreach (var h in currentHistory) - { - if (h.CommitType == TimeMachineHistoryType.ElementInsert && - h.InsertedElement != null && - !h.StrokeHasBeenCleared) - { - elementsInHistory.Add(h.InsertedElement); - } - } - } + // 已移除后重新出现的成员也需要补记,不能只检查是否曾经加入。 + var recorded = new UInk.UInkHistorySnapshot(currentHistory); // 检查画布上的所有UI元素,确保它们都在历史记录中 var missingElements = 0; @@ -121,7 +111,7 @@ private void SaveStrokes(bool isBackupMain = false) { continue; } - if (!elementsInHistory.Contains(child)) + if (recorded.Owner(child) < 0) { timeMachine.CommitElementInsertHistory(child); missingElements++; @@ -134,28 +124,11 @@ private void SaveStrokes(bool isBackupMain = false) if (inkCanvas.Strokes.Count > 0) { // 检查是否有墨迹没有在时间机器历史记录中 - var strokesInHistory = new HashSet(); - if (currentHistory != null) - { - foreach (var h in currentHistory) - { - if (h.CommitType == TimeMachineHistoryType.UserInput && - h.CurrentStroke != null && - !h.StrokeHasBeenCleared) - { - foreach (Stroke stroke in h.CurrentStroke) - { - strokesInHistory.Add(stroke); - } - } - } - } - // 收集没有在历史记录中的墨迹 var missingStrokes = new StrokeCollection(); foreach (Stroke stroke in inkCanvas.Strokes) { - if (!strokesInHistory.Contains(stroke)) + if (recorded.Owner(stroke) < 0) { missingStrokes.Add(stroke); } @@ -181,6 +154,7 @@ private void SaveStrokes(bool isBackupMain = false) { var timeMachineHistory = timeMachine.ExportTimeMachineHistory(); TimeMachineHistories[CurrentWhiteboardIndex] = timeMachineHistory; + if (uinkSlot != null) uinkSlot.SavedHistory = timeMachineHistory; // 保存多指书写模式状态 savedMultiTouchModeStates[CurrentWhiteboardIndex] = isInMultiTouchMode; timeMachine.ClearStrokeHistory(); @@ -226,18 +200,6 @@ internal void ClearCanvasContentFromAutomation() ClearStrokes(true); } - private static HashSet CollectRemovedElementsFromHistory(TimeMachineHistory[] history) - { - var set = new HashSet(); - if (history == null) return set; - foreach (var h in history) - { - if (h.CommitType == TimeMachineHistoryType.ElementInsert && h.StrokeHasBeenCleared && h.InsertedElement != null) - set.Add(h.InsertedElement); - } - return set; - } - /// /// 恢复指定白板页面的墨迹和元素信息 /// @@ -249,7 +211,7 @@ private static HashSet CollectRemovedElementsFromHistory(TimeMachineH /// - 恢复多指书写模式状态 /// - 包含异常处理 /// - private void RestoreStrokes(bool isBackupMain = false) + private void RestoreStrokes(bool isBackupMain = false, bool throwOnError = false) { try { @@ -269,6 +231,8 @@ private void RestoreStrokes(bool isBackupMain = false) // 这里必须清除图片,因为页面切换时需要完全重置画布状态 inkCanvas.Children.Clear(); + if (!isBackupMain && InstallPendingUInkPage(targetIndex)) return; + // 如果历史记录为空,直接返回(新页面或空页面) if (TimeMachineHistories[targetIndex] == null) { @@ -279,48 +243,17 @@ private void RestoreStrokes(bool isBackupMain = false) return; } - if (isBackupMain) - { - timeMachine.ImportTimeMachineHistory(TimeMachineHistories[0]); - var removed0 = CollectRemovedElementsFromHistory(TimeMachineHistories[0]); - var elementsToProcess = new List(); - foreach (var item in TimeMachineHistories[0]) - { - if (item.CommitType == TimeMachineHistoryType.ElementInsert && - !item.StrokeHasBeenCleared && - item.InsertedElement != null && - !removed0.Contains(item.InsertedElement)) - { - elementsToProcess.Add(item.InsertedElement); - } - ApplyHistoryToCanvas(item, null, removed0); - } - RestoreMultiTouchModeState(0); - ProcessElementsAfterRestore(elementsToProcess); - } - else - { - timeMachine.ImportTimeMachineHistory(TimeMachineHistories[CurrentWhiteboardIndex]); - var removed = CollectRemovedElementsFromHistory(TimeMachineHistories[CurrentWhiteboardIndex]); - var elementsToProcess = new List(); - foreach (var item in TimeMachineHistories[CurrentWhiteboardIndex]) - { - if (item.CommitType == TimeMachineHistoryType.ElementInsert && - !item.StrokeHasBeenCleared && - item.InsertedElement != null && - !removed.Contains(item.InsertedElement)) - { - elementsToProcess.Add(item.InsertedElement); - } - ApplyHistoryToCanvas(item, null, removed); - } - RestoreMultiTouchModeState(CurrentWhiteboardIndex); - ProcessElementsAfterRestore(elementsToProcess); - } - - + var history = TimeMachineHistories[targetIndex]; + timeMachine.ImportTimeMachineHistory(history); + var previous = _currentCommitType; + _currentCommitType = CommitReason.CodeInput; + List elements; + try { elements = RestorePageHistory(history); } + finally { _currentCommitType = previous; } + RestoreMultiTouchModeState(targetIndex); + ProcessElementsAfterRestore(elements); } - catch + catch when (!throwOnError) { // ignored } @@ -724,6 +657,7 @@ private void BtnWhiteBoardAdd_Click(object sender, RoutedEventArgs e) { for (var i = WhiteboardTotalCount; i > CurrentWhiteboardIndex; i--) { + _uinkBoard[i] = _uinkBoard[i - 1]; TimeMachineHistories[i] = TimeMachineHistories[i - 1]; savedMultiTouchModeStates[i] = savedMultiTouchModeStates[i - 1]; frozenPages[i] = frozenPages[i - 1]; @@ -731,6 +665,7 @@ private void BtnWhiteBoardAdd_Click(object sender, RoutedEventArgs e) } } + _uinkBoard[CurrentWhiteboardIndex] = null; // 确保新页面的历史记录为空 TimeMachineHistories[CurrentWhiteboardIndex] = null; frozenPages[CurrentWhiteboardIndex] = false; @@ -783,6 +718,9 @@ private void DeleteWhiteBoardPageByIndex(int pageIndex) if (deletingCurrentPluginPage) CaptureCurrentPluginPageStates(); var removedPluginPage = RemovePluginWhiteboardPageId(pageIndex, oldPluginPageCount); + // 页面身份、尚未访问的原始页和背景随槽位一起移动。 + Array.Copy(_uinkBoard, pageIndex + 1, _uinkBoard, pageIndex, WhiteboardTotalCount - pageIndex); + _uinkBoard[WhiteboardTotalCount] = null; if (pageIndex == CurrentWhiteboardIndex) { PauseAllCanvasMediaPlayback(); @@ -793,7 +731,7 @@ private void DeleteWhiteBoardPageByIndex(int pageIndex) { for (var i = CurrentWhiteboardIndex; i < oldTotal; i++) { - TimeMachineHistories[i] = FlattenPageHistory(TimeMachineHistories[i + 1]); + TimeMachineHistories[i] = ShiftUInkBoardHistory(i); savedMultiTouchModeStates[i] = savedMultiTouchModeStates[i + 1]; frozenPages[i] = frozenPages[i + 1]; pageLastUserInkMutationUtc[i] = pageLastUserInkMutationUtc[i + 1]; @@ -813,7 +751,7 @@ private void DeleteWhiteBoardPageByIndex(int pageIndex) { for (var i = pageIndex; i < WhiteboardTotalCount; i++) { - TimeMachineHistories[i] = FlattenPageHistory(TimeMachineHistories[i + 1]); + TimeMachineHistories[i] = ShiftUInkBoardHistory(i); savedMultiTouchModeStates[i] = savedMultiTouchModeStates[i + 1]; frozenPages[i] = frozenPages[i + 1]; pageLastUserInkMutationUtc[i] = pageLastUserInkMutationUtc[i + 1]; @@ -826,7 +764,7 @@ private void DeleteWhiteBoardPageByIndex(int pageIndex) { for (var i = pageIndex; i < WhiteboardTotalCount; i++) { - TimeMachineHistories[i] = FlattenPageHistory(TimeMachineHistories[i + 1]); + TimeMachineHistories[i] = ShiftUInkBoardHistory(i); savedMultiTouchModeStates[i] = savedMultiTouchModeStates[i + 1]; frozenPages[i] = frozenPages[i + 1]; pageLastUserInkMutationUtc[i] = pageLastUserInkMutationUtc[i + 1]; diff --git a/Ink Canvas/MainWindow_cs/MW_ElementsControls.cs b/Ink Canvas/MainWindow_cs/MW_ElementsControls.cs index 65689bfb6..396d6074e 100644 --- a/Ink Canvas/MainWindow_cs/MW_ElementsControls.cs +++ b/Ink Canvas/MainWindow_cs/MW_ElementsControls.cs @@ -156,6 +156,7 @@ private void InitializeElementTransform(FrameworkElement element) /// private void BindElementEvents(FrameworkElement element) { + if (WasUInkElementBound(element)) return; if (element is CanvasMediaControl mediaControl) { mediaControl.RegisterSelectHandler(Element_MouseLeftButtonDown); @@ -1436,6 +1437,7 @@ private async Task CreateAndCompressImageFromPdfAsync(string fi { try { + var owner = PdfPageIdentity(); string savePath = Path.Combine(Settings.Automation.AutoSavedStrokesLocation, "File Dependency"); if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath); @@ -1445,6 +1447,7 @@ private async Task CreateAndCompressImageFromPdfAsync(string fi await Task.Run(() => File.Copy(filePath, newFilePath, true)); uint pageCount = await PdfWinRtHelper.GetPageCountAsync(newFilePath); + if (owner != PdfPageIdentity()) return null; if (pageCount == 0) { ShowNotification("无法打开 PDF(可能已加密、损坏或不支持)。"); @@ -1454,7 +1457,8 @@ private async Task CreateAndCompressImageFromPdfAsync(string fi bool compress = isLoaded && Settings.Canvas.IsCompressPicturesUploaded; var view = new PdfEmbeddedView(); await view.InitializeAsync(newFilePath, pageCount, compress); - WirePdfStrokePersistence(view); + if (owner != PdfPageIdentity()) return null; + CompleteRestoredPdf(view, owner.Generation); view.Tag = filePath; return view; } @@ -1467,28 +1471,20 @@ private async Task CreateAndCompressImageFromPdfAsync(string fi } /// 从保存的 恢复 PDF(与打开墨迹时的图片恢复流程一致,不单独写入时间轴)。 - private async Task RestorePdfFromElementInfoAsync(CanvasElementInfo info) + private async Task RestorePdfFromElementInfoAsync(CanvasElementInfo info, int generation) { - if (info == null || inkCanvas == null) return; + if (info == null || inkCanvas == null || generation != _uinkOpenGeneration) return; if (!string.Equals(info.Type, "Pdf", StringComparison.OrdinalIgnoreCase)) return; if (string.IsNullOrEmpty(info.SourcePath) || !File.Exists(info.SourcePath)) return; try { - uint pageCount = await PdfWinRtHelper.GetPageCountAsync(info.SourcePath); - if (pageCount == 0) return; - - bool compress = isLoaded && Settings.Canvas.IsCompressPicturesUploaded; - uint initial = 0; - if (info.PdfCurrentPage.HasValue) - initial = (uint)Math.Max(0, Math.Min(info.PdfCurrentPage.Value, (int)pageCount - 1)); - + var owner = PdfPageIdentity(); var view = new PdfEmbeddedView { Name = "pdf_" + DateTime.Now.ToString("yyyyMMdd_HH_mm_ss_fff") }; - await view.InitializeAsync(info.SourcePath, pageCount, compress, initial); - WirePdfStrokePersistence(view); + if (!await RestorePdfFromElementInfoAsync(info, view, () => owner == PdfPageIdentity())) return; if (info.Width > 0) view.Width = info.Width; if (info.Height > 0) view.Height = info.Height; @@ -1500,7 +1496,7 @@ private async Task RestorePdfFromElementInfoAsync(CanvasElementInfo info) BindElementEvents(view); inkCanvas.Children.Add(view); _pdfSidebarNextPositionUseHostTransform = true; - SyncPdfPageSidebarWithCanvas(); + CompleteRestoredPdf(view, generation); } catch (Exception ex) { @@ -1508,6 +1504,57 @@ private async Task RestorePdfFromElementInfoAsync(CanvasElementInfo info) } } + // MEDIA-9:普通 sidecar 与 UInk 共用实际页数及页号钳制。UInk 控件已在所属撤销组中。 + private async Task RestorePdfFromElementInfoAsync(CanvasElementInfo info, PdfEmbeddedView view, + Func ownsPage, Action onPageCount = null, uint? requestedPage = null) + { + bool imported = view.Tag is UInkPdfState; + uint count = imported + ? await Task.Run(() => PdfWinRtHelper.GetUInkPageCountAsync(info.SourcePath)) + : await PdfWinRtHelper.GetPageCountAsync(info.SourcePath); + if (count == 0 || !ownsPage()) return false; + onPageCount?.Invoke(count); + uint initial = Math.Min(requestedPage ?? (uint)Math.Max(0, info.PdfCurrentPage ?? 0), count - 1); + if (imported) + await PdfWinRtHelper.WithUInkRenderBudgetAsync(() => view.InitializeAsync(info.SourcePath, count, false, initial)); + else + await view.InitializeAsync(info.SourcePath, count, isLoaded && Settings.Canvas.IsCompressPicturesUploaded, initial); + return ownsPage(); + } + + private (int Generation, int Mode, int Page, UInkBoardSlot Slot) PdfPageIdentity() + { + if (currentMode != 0) + { + // 页号可在等待期间被删除、复用;随页移动的槽引用也必须一致。 + var slot = GetUInkSlot(CurrentWhiteboardIndex) ?? (_uinkBoard[CurrentWhiteboardIndex] = + new UInkBoardSlot { SavedHistory = TimeMachineHistories[CurrentWhiteboardIndex] }); + return (_uinkOpenGeneration, currentMode, CurrentWhiteboardIndex, slot); + } + int slide = IsInPPTPresentationMode ? _pptManager?.GetCurrentSlideNumber() ?? 0 : 0; + return (_uinkOpenGeneration, currentMode, slide, null); + } + + internal void CompleteRestoredPdf(PdfEmbeddedView view, int generation) + { + if (generation != _uinkOpenGeneration) return; + if (!inkCanvas.Children.Contains(view)) + { + // 正常翻页可暂时卸下控件;等原控件重新上屏再注入主画布回调。 + void OnLoaded(object sender, RoutedEventArgs e) + { + view.Loaded -= OnLoaded; + if (generation == _uinkOpenGeneration && inkCanvas.Children.Contains(view)) + CompleteRestoredPdf(view, generation); + } + view.Loaded += OnLoaded; + return; + } + // MEDIA-4:导入的墨迹属于白板页。PDF 翻页只导航和更新侧栏。 + if (view.Tag is not UInkPdfState) WirePdfStrokePersistence(view); + SyncPdfPageSidebarWithCanvas(); + } + /// 为 PdfEmbeddedView 注入墨迹持久化回调,使墨迹跟随 PDF 翻页。 private void WirePdfStrokePersistence(PdfEmbeddedView view) { @@ -1516,7 +1563,7 @@ private void WirePdfStrokePersistence(PdfEmbeddedView view) view.EnableStrokesPersistence = true; view.CaptureStrokes = () => { - if (inkCanvas?.Strokes == null || inkCanvas.Strokes.Count == 0) + if (inkCanvas?.Strokes == null || !inkCanvas.Children.Contains(view) || inkCanvas.Strokes.Count == 0) return null; var ms = new MemoryStream(); inkCanvas.Strokes.Save(ms); @@ -1527,7 +1574,7 @@ private void WirePdfStrokePersistence(PdfEmbeddedView view) }; view.ApplyStrokes = (data) => { - if (data == null || data.Length <= 8) return; + if (data == null || data.Length <= 8 || !inkCanvas.Children.Contains(view)) return; try { var sc = new StrokeCollection(new MemoryStream(data)); @@ -1541,6 +1588,7 @@ private void WirePdfStrokePersistence(PdfEmbeddedView view) }; view.ClearAllStrokes = () => { + if (!inkCanvas.Children.Contains(view)) return; ClearStrokes(true); timeMachine.ClearStrokeHistory(); }; @@ -2066,7 +2114,8 @@ private void UpdateImageSelectionToolbarPosition(FrameworkElement element) private PdfEmbeddedView GetPdfSidebarTargetElement() { if (inkCanvas == null) return null; - var pdfs = inkCanvas.Children.OfType().ToList(); + var pdfs = inkCanvas.Children.OfType() + .Where(pdf => pdf.Content is not UInk.UInkMissingMedia && pdf.Tag is not UInkWaitingMedia).ToList(); if (pdfs.Count == 0) return null; if (currentSelectedElement is PdfEmbeddedView sel && pdfs.Contains(sel)) return sel; @@ -2685,7 +2734,7 @@ private async void BorderPdfSidebarPagePrev_MouseUp(object sender, MouseButtonEv { var pdf = GetPdfSidebarTargetElement(); if (pdf != null && pdf.CanGoPrevious) - await pdf.GoToPreviousPageAsync(); + await NavigateRestoredPdfAsync(pdf, previous: true); SyncPdfPageSidebarWithCanvas(); } catch (Exception ex) @@ -2701,7 +2750,7 @@ private async void BorderPdfSidebarPageNext_MouseUp(object sender, MouseButtonEv { var pdf = GetPdfSidebarTargetElement(); if (pdf != null && pdf.CanGoNext) - await pdf.GoToNextPageAsync(); + await NavigateRestoredPdfAsync(pdf, previous: false); SyncPdfPageSidebarWithCanvas(); } catch (Exception ex) diff --git a/Ink Canvas/MainWindow_cs/MW_FloatingBarIcons.cs b/Ink Canvas/MainWindow_cs/MW_FloatingBarIcons.cs index 18e33278e..34bb3cb88 100644 --- a/Ink Canvas/MainWindow_cs/MW_FloatingBarIcons.cs +++ b/Ink Canvas/MainWindow_cs/MW_FloatingBarIcons.cs @@ -4590,6 +4590,9 @@ private void SwitchBackground(object sender, RoutedEventArgs e) SaveStrokes(true); ClearStrokes(true); + // 先初始化全局背景,RestoreStrokes 再恢复本页的颜色和图案。 + if (Settings.Canvas.UsingWhiteboard && CustomBackgroundColor.HasValue) + GridBackgroundCover.Background = new SolidColorBrush(CustomBackgroundColor.Value); RestoreStrokes(); // 进入白板模式时全屏(仅在非PPT模式下) @@ -4612,11 +4615,6 @@ private void SwitchBackground(object sender, RoutedEventArgs e) if (Settings.Canvas.UsingWhiteboard) { - // 如果有自定义背景色并且是白板模式,应用自定义背景色 - if (CustomBackgroundColor.HasValue) - { - GridBackgroundCover.Background = new SolidColorBrush(CustomBackgroundColor.Value); - } // 白板模式下设置墨迹颜色为黑色 CheckLastColor(0); forceEraser = false; diff --git a/Ink Canvas/MainWindow_cs/MW_InkFreeze.cs b/Ink Canvas/MainWindow_cs/MW_InkFreeze.cs index 907e91d0a..d4edc535f 100644 --- a/Ink Canvas/MainWindow_cs/MW_InkFreeze.cs +++ b/Ink Canvas/MainWindow_cs/MW_InkFreeze.cs @@ -353,7 +353,7 @@ private string LocalizeFrozenPageAction(string action) "插入控件" => "Main_Freeze_Action_InsertElement", "删除控件" => "Main_Freeze_Action_DeleteElement", "书写" => "Main_Freeze_Action_Write", - "打开墨迹文件" => "Main_Freeze_Action_OpenInkFile", + "打开墨迹文件" or "打开 UInk 文件" => "Main_Freeze_Action_OpenInkFile", "恢复墨迹文件" => "Main_Freeze_Action_RestoreInkFile", "克隆墨迹" => "Main_Freeze_Action_CloneInk", "克隆墨迹到新页面" => "Main_Freeze_Action_CloneInkToNewPage", diff --git a/Ink Canvas/MainWindow_cs/MW_PPT.cs b/Ink Canvas/MainWindow_cs/MW_PPT.cs index f966f2ee0..2cecbd71c 100644 --- a/Ink Canvas/MainWindow_cs/MW_PPT.cs +++ b/Ink Canvas/MainWindow_cs/MW_PPT.cs @@ -1,5 +1,6 @@ using Ink_Canvas.Helpers; using Ink_Canvas.WorkflowAutomation; +using Ink_Canvas.UInk; using InkCanvasPPTAgent.Contracts; using iNKORE.UI.WPF.Modern; using Microsoft.Office.Core; @@ -187,7 +188,267 @@ public partial class MainWindow : Ink_Canvas.Helpers.PerformanceTransparentWin /// internal int CurrentPPTSlideIndex => _currentSlideShowPosition > 0 ? _currentSlideShowPosition - 1 : 0; - private Dictionary _memoryStreams = new Dictionary(); + private readonly PptSlideStorage _memoryStreams = new(); + private volatile PptSlideMap _showSlides = new(null); + private PptPageKey _canvasSlide; + private int _showGeneration; + private PPTState _lastFlipWithSlideIds; + private Task _pendingSlideDecode; + + private PptSlideMap ReadShowSlides(SlideShowWindow window = null, PPTState state = null, Presentation presentation = null) + { + FinishSlideDecode(); + // Agent 已携带的页表只保留引用,到需要解析页序时才建立索引。 + if (_lastFlipWithSlideIds != null) + { + RememberShowMap(PptSlideMap.FromAgent(_lastFlipWithSlideIds)); + _lastFlipWithSlideIds = null; + } + if (state == null && _pptManager is PPTAgentLinkManager agent) state = agent.CurrentState; + if (state != null) return RememberShowMap(PptSlideMap.FromAgent(state)); + try + { + if (presentation == null) presentation = (window ?? GetSingleShowWindow())?.Presentation; + var slides = presentation?.Slides; + if (slides == null) return RememberShowMap(new PptSlideMap(null)); + var ids = new int[slides.Count]; + for (int i = 0; i < ids.Length; i++) + { + try { ids[i] = slides[i + 1].SlideID; } + catch (COMException) { } // 单页取不到 ID 时仅该页按位置写出。 + } + return RememberShowMap(new PptSlideMap(ids)); + } + catch (COMException) { return RememberShowMap(new PptSlideMap(null)); } + } + + // 最近一次完整表之后才观察到的新 ID,在下一次完整查询前不能判为已删。 + private readonly HashSet _idsSinceConfirmedMap = new(); + private PptSlideMap _confirmedSlides = new(null); + // 没有完整文稿页表时,保留实测的放映位置;它不参与按 SlideID 反查文稿索引。 + private readonly Dictionary _observedShowKeys = new(); + private readonly Dictionary _observedPositions = new(); + private readonly Dictionary _archivePages = new(); + private readonly HashSet _unclaimedArchivePages = new(); + + private PptSlideMap RememberShowMap(PptSlideMap map) + { + if (map.Complete) + { + _confirmedSlides = map; + _idsSinceConfirmedMap.Clear(); + return _showSlides = map; + } + if (map.Count == 0) return _showSlides; + if (!map.Complete && _confirmedSlides.Complete && map.AgreesWith(_confirmedSlides)) + return _showSlides = _confirmedSlides; + return _showSlides = map; + } + + private void ResetShowMaps() + { + _showArchive = null; + _pendingSlideDecode = null; + _lastFlipWithSlideIds = null; + _canvasSlide = default; + _showSlides = _confirmedSlides = new PptSlideMap(null); + _observedShowKeys.Clear(); + _observedPositions.Clear(); + _idsSinceConfirmedMap.Clear(); + _archivePages.Clear(); + _unclaimedArchivePages.Clear(); + } + + private void ObserveShowPage(int position, PptPageKey key) + { + if (_observedShowKeys.TryGetValue(position, out var oldKey)) _observedPositions.Remove(oldKey); + if (_observedPositions.TryGetValue(key, out int oldPosition)) _observedShowKeys.Remove(oldPosition); + _observedShowKeys[position] = key; + _observedPositions[key] = position; + if (key.SlideId is int id && _confirmedSlides.Resolve(id) == null) + _idsSinceConfirmedMap.Add(id); + } + + private PptPageKey ExportSlideKey(PptSlideMap map, int index) + { + var key = map.Key(index); + // 缺 ID 的当前页沿用 HEAD 放映位置;有 ID 时优先按文稿顺序定位。 + if (key == _canvasSlide || _canvasSlide.Position == index || + (index == _currentSlideShowPosition && _canvasSlide.SlideId is int id && map.Resolve(id) == null && + (!_confirmedSlides.Complete || _idsSinceConfirmedMap.Contains(id)))) + return _canvasSlide; + if (_unclaimedArchivePages.Contains(index) && _memoryStreams.Read(key) == null) + return PptPageKey.At(index, null); + if (_observedShowKeys.TryGetValue(index, out var seen)) + { + if (seen.Position == index) return seen; + if (!key.SlideId.HasValue && seen.SlideId is int seenId && map.Resolve(seenId) == null) return seen; + } + return key; + } + + private byte[] ReadExportInk(PptPageKey key) => + key.Position > 0 && _unclaimedArchivePages.Contains(key.Position) ? _archivePages[key.Position] : _memoryStreams.Read(key); + + private PptPageKey LegacySlideKey(int position) + { + // 旧格式入口只传页码;即使重排尚未触发切页,也使用现在的顺序读取同一存储。 + if (_pptManager is PPTAgentLinkManager agent) + { + var ids = agent.CurrentState.SlideIds; + if (position > 0 && position <= (ids?.Length ?? 0)) return PptPageKey.At(position, ids[position - 1]); + } + else + { + try + { + var slides = GetSingleShowWindow()?.Presentation.Slides; + if (slides != null && position > 0 && position <= slides.Count) + return PptPageKey.At(position, slides[position].SlideID); + } + catch (COMException) { } + } + return _showSlides.Key(position); + } + + private const string PptUInkArchiveName = "slides.uink"; + private Task _pptUInkArchiveWrite; + + internal Task SavePptShowArchiveAsync(string folder, int count, Presentation presentation = null, PPTState state = null) + { + if (ResolveStrokeSaveFormat(Settings.Automation) != StrokeSaveFormat.UInk) + return SaveLegacyArchiveAsync(folder, count); + + // 放映窗口或 Agent 连接可能已结束,仍可用事件文稿或最后一次页表采集。 + ReadShowSlides(state: state, presentation: presentation); + return _pptUInkArchiveWrite = SaveCurrentStateToUInk(Path.Combine(folder, PptUInkArchiveName), + newNotice: false, upload: false, pptArchiveSlideCount: count); + } + + internal async Task LoadPptShowArchiveAsync(string strokePath, int openingShow) + { + if (ResolveStrokeSaveFormat(Settings.Automation) == StrokeSaveFormat.UInk) + { + // 快速重开时先等上次归档提交,再决定是否读旧逐页文件。 + if (_pptUInkArchiveWrite != null) await _pptUInkArchiveWrite; + if (openingShow != _showGeneration) return null; + string archive = Path.Combine(strokePath, PptUInkArchiveName); + if (File.Exists(archive)) return archive; + } + + if (Directory.Exists(strokePath)) + { + var loaded = new Dictionary(); + await Task.Run(() => + { + try + { + var files = new DirectoryInfo(strokePath).GetFiles("*.icstk"); + foreach (var file in files) + { + int pageNum = 0; + try + { + string name = Path.GetFileNameWithoutExtension(file.Name); + if (int.TryParse(name, out pageNum) && pageNum > 0) + { + byte[] bytes = File.ReadAllBytes(file.FullName); + if (bytes.Length > 8) + { + loaded[pageNum] = bytes; + } + } + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"加载第 {pageNum} 页墨迹文件失败: {ex}", LogHelper.LogType.Warning); + } + } + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"加载PPT墨迹文件失败: {ex}", LogHelper.LogType.Error); + } + }); + if (openingShow != _showGeneration) return null; + foreach (var pair in loaded) + { + if (_archivePages.TryAdd(pair.Key, pair.Value)) _unclaimedArchivePages.Add(pair.Key); + } + ClaimArchivePage(_currentSlideShowPosition); + } + return null; + } + + internal Task SaveLegacyArchiveAsync(string folder, int count) + { + // 快照在调用线程完成,后台写盘只读取本场的放映位置和不可变字节数组。 + var snapshot = new Dictionary(_archivePages); + return Task.Run(() => WriteLegacyArchive(folder, count, snapshot)); + } + + private static void WriteLegacyArchive(string folderPathForSave, int totalSlidesForSave, + Dictionary snapshot) + { + try + { + if (!Directory.Exists(folderPathForSave)) + Directory.CreateDirectory(folderPathForSave); + + foreach (var (page, bytes) in snapshot) + { + if (page <= 0 || page > totalSlidesForSave) continue; + try + { + string filePath = Path.Combine(folderPathForSave, page.ToString("0000") + ".icstk"); + if (bytes.Length > 8) + File.WriteAllBytes(filePath, bytes); + else if (File.Exists(filePath)) + File.Delete(filePath); + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"为第 {page} 页保存墨迹文件失败: {ex}", LogHelper.LogType.Warning); + } + } + } + catch (Exception ex) + { + LogHelper.WriteLogToFile($"保存PPT墨迹文件失败: {ex}", LogHelper.LogType.Error); + } + } + + private void SaveShowCanvas(int position) + { + FinishSlideDecode(); + var bytes = PptSlideStorage.Encode(inkCanvas.Strokes); + _memoryStreams.Write(_canvasSlide, bytes); + if (position > 0) _archivePages[position] = bytes; + } + + private void ClaimArchivePage(int position) + { + if (_unclaimedArchivePages.Remove(position) && _memoryStreams.Read(_canvasSlide) == null) + _memoryStreams.Write(_canvasSlide, _archivePages[position]); + } + + private SlideShowWindow GetSingleShowWindow() + { + if (_pptManager?.PPTApplication is not Microsoft.Office.Interop.PowerPoint.Application app) return null; + var windows = app.SlideShowWindows; + return windows.Count == 1 ? windows[1] : null; + } + + private static PptPageKey CurrentShowKey(int position, SlideShowWindow window, PPTState state) + { + try + { + int? id = state?.SlideId ?? window?.View.Slide.SlideID; + if (id > 0) return PptPageKey.At(position, id); + } + catch (COMException) { } + return PptPageKey.At(position, null); + } private readonly object _pptEnhancedPreviewCacheLock = new object(); private List _pptEnhancedPreviewCache; private Task> _pptEnhancedPreviewBuildTask; @@ -196,7 +457,6 @@ public partial class MainWindow : Ink_Canvas.Helpers.PerformanceTransparentWin private readonly object _pptEndSlideShowTaskLock = new object(); private Task _pptEndSlideShowTask; private const int PPTEnhancedPreviewPreloadDelayMs = 100; - private int _previousSlideID = 0; /// /// 用于在PowerPoint连接断开后延迟退出PPT模式的定时器。 @@ -329,7 +589,7 @@ public void InitializePPTManagers() _pptManager.PresentationClose += payload => DispatchPPTEvent(() => OnPPTPresentationClose(payload)); _pptManager.SlideShowStateChanged += isInSlideShow => DispatchPPTEvent(() => OnPPTSlideShowStateChanged(isInSlideShow)); - _singlePPTInkManager = new PPTInkManager(); + _singlePPTInkManager = new PPTInkManager(_memoryStreams, LegacySlideKey); _singlePPTInkManager.IsAutoSaveEnabled = Settings.PowerPointSettings.IsAutoSaveStrokesInPowerPoint; _singlePPTInkManager.AutoSaveLocation = Settings.Automation.AutoSavedStrokesLocation; @@ -1028,8 +1288,10 @@ private void OnPPTPresentationOpen(object payload) var agentState = payload as PPTState; try { + int openedIn = _showGeneration; Application.Current.Dispatcher.InvokeAsync(() => { + if (openedIn != _showGeneration) return; // 在初始化墨迹管理器之前,先清理画布上的所有墨迹 ResetPPTEnhancedPreviewCache(); @@ -1104,24 +1366,52 @@ private string GetPresentationStrokeFolderPath(Presentation presentation, string return Path.Combine(basePath, $"{name ?? ""}_{slidesTotal}"); } - private void OnPPTPresentationClose(object payload) + internal static bool DifferentShow(string trackedPath, string trackedName, string path, string name) + { + if (!string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(trackedPath)) + return !string.Equals(path, trackedPath, StringComparison.OrdinalIgnoreCase); + return !string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(trackedName) && + !string.Equals(name, trackedName, StringComparison.OrdinalIgnoreCase); + } + + private bool DifferentShow(object payload) { try { - Application.Current.Dispatcher.InvokeAsync(() => + var state = payload as PPTState; + var presentation = payload as Presentation ?? (payload as SlideShowWindow)?.Presentation; + string path = state?.PresentationFullName; + if (presentation != null) { - CollapseAllPPTNavBarPreviews(); - ResetPPTEnhancedPreviewCache(); - - lock (_memoryStreams) - { - foreach (var stream in _memoryStreams.Values) - stream?.Dispose(); - _memoryStreams.Clear(); - } + try { path = presentation.FullName; } + catch (COMException) { } // 未保存的文稿仍可按名称识别。 + } + return DifferentShow(_presentationFullNameSnapshot, _presentationNameSnapshot, + path, state?.PresentationName ?? presentation?.Name); + } + catch (COMException) { return false; } + } + private void OnPPTPresentationClose(object payload) + { + try + { + // 事件入口已经切回 UI 线程,关闭无需排队清理下一场放映。 + if (DifferentShow(payload)) return; + if (_canvasSlide != default) + { + // Agent 可能先发布 Close 再发布 End;同一场只由结束入口取一次快照。 + OnPPTSlideShowEnd(payload); _pptUIManager?.UpdateConnectionStatus(false); - }); + return; + } + CollapseAllPPTNavBarPreviews(); + ResetPPTEnhancedPreviewCache(); + _showGeneration++; + ResetPptUInkPages(); + ResetShowMaps(); + _memoryStreams.Clear(); + _pptUIManager?.UpdateConnectionStatus(false); } catch (COMException comEx) { @@ -1210,19 +1500,6 @@ private async void OnPPTSlideShowBegin(object payload) _floatingBarFoldedBeforePPT = isFloatingBarFolded; _hasFloatingBarStateBeforePPT = true; - if (Settings.Automation.IsAutoFoldInPPTSlideShow) - { - if (!isFloatingBarFolded) - await FoldFloatingBarByCode(hold: true); - } - else - { - if (isFloatingBarFolded) - { - await UnFoldFloatingBarByCode(); - } - } - isStopInkReplay = true; int currentSlide = 0; @@ -1285,70 +1562,58 @@ private async void OnPPTSlideShowBegin(object payload) } } + if (_canvasSlide != default && DifferentShow(_presentationFullNameSnapshot, _presentationNameSnapshot, + presentationFullName, presentationName)) + { + ClearStrokes(true); + timeMachine.ClearStrokeHistory(); + } _presentationNameSnapshot = presentationName; _presentationFullNameSnapshot = presentationFullName; _presentationSlideCountSnapshot = totalSlides; _currentSlideShowPosition = currentSlide; - _previousSlideID = currentSlide; + _showGeneration++; + ResetShowMaps(); + ReadShowSlides(wn, agentState); + _canvasSlide = CurrentShowKey(currentSlide, wn, agentState); + ResetPptUInkPages(); NotifyPluginSlideShowStateChanged(true); - lock (_memoryStreams) + _memoryStreams.Clear(); + ObserveShowPage(currentSlide, _canvasSlide); + int openingShow = _showGeneration; + isEnteredSlideShowEndEvent = false; + if (Settings.Automation.IsAutoFoldInPPTSlideShow) + { + if (!isFloatingBarFolded) + await FoldFloatingBarByCode(hold: true); + } + else { - foreach (var stream in _memoryStreams.Values) - stream?.Dispose(); - _memoryStreams.Clear(); + if (isFloatingBarFolded) + { + await UnFoldFloatingBarByCode(); + } } + if (openingShow != _showGeneration) return; + + string uinkArchivePath = null; if (Settings.PowerPointSettings.IsAutoSaveStrokesInPowerPoint && !string.IsNullOrEmpty(presentationName)) { string strokePath = GetPresentationStrokeFolderPath(activePresentation, presentationName, totalSlides, presentationFullName); - if (Directory.Exists(strokePath)) - { - await Task.Run(() => - { - try - { - var files = new DirectoryInfo(strokePath).GetFiles("*.icstk"); - foreach (var file in files) - { - int pageNum = 0; - try - { - string name = Path.GetFileNameWithoutExtension(file.Name); - if (int.TryParse(name, out pageNum) && pageNum > 0) - { - byte[] bytes = File.ReadAllBytes(file.FullName); - if (bytes.Length > 8) - { - lock (_memoryStreams) - { - _memoryStreams[pageNum] = new MemoryStream(bytes); - _memoryStreams[pageNum].Position = 0; - } - } - } - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"加载第 {pageNum} 页墨迹文件失败: {ex}", LogHelper.LogType.Warning); - } - } - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"加载PPT墨迹文件失败: {ex}", LogHelper.LogType.Error); - } - }); - } + uinkArchivePath = await LoadPptShowArchiveAsync(strokePath, openingShow); + if (openingShow != _showGeneration) return; } await Application.Current.Dispatcher.InvokeAsync(async () => { + if (openingShow != _showGeneration) return; if (activePresentation != null && _singlePPTInkManager != null) { try { - _singlePPTInkManager.InitializePresentation(activePresentation); + _singlePPTInkManager.InitializePresentation(activePresentation, false); } catch (Exception ex) { @@ -1397,6 +1662,16 @@ await Application.Current.Dispatcher.InvokeAsync(async () => BtnHideInkCanvas_Click(null, null); } + // 白板退出后才恢复归档当前页,避免把 PPT 批注装入白板。 + if (uinkArchivePath != null && openingShow == _showGeneration && !isEnteredSlideShowEndEvent) + { + if (_currentSlideShowPosition == currentSlide) LoadCurrentSlideInk(currentSlide); + WatchUInkResourcesOnClose(); + string notice = await RestorePptShowUInkAsync(uinkArchivePath, totalSlides); + if (openingShow != _showGeneration || isEnteredSlideShowEndEvent) return; + if (notice != null) ShowNotification(notice); + } + SetFloatingBarContentVisibility(true); // 在PPT模式下根据设置决定是否隐藏手势面板和手势按钮 @@ -1410,6 +1685,7 @@ await Application.Current.Dispatcher.InvokeAsync(async () => !Settings.Automation.IsAutoFoldInPPTSlideShow) { await Task.Delay(300); + if (openingShow != _showGeneration) return; // 先进入批注模式,这会显示调色盘 PenIcon_Click(null, null); // 然后设置颜色 @@ -1428,10 +1704,9 @@ await Application.Current.Dispatcher.InvokeAsync(async () => } } - isEnteredSlideShowEndEvent = false; - // 加载当前页墨迹 - LoadCurrentSlideInk(currentSlide); + if (openingShow != _showGeneration) return; + if (uinkArchivePath == null && _currentSlideShowPosition == currentSlide) LoadCurrentSlideInk(currentSlide); // 仅PPT模式:放映开始立即同步主窗口可见性(勿仅依赖 SlideShowStateChanged 定时器) CheckMainWindowVisibility(); @@ -1480,8 +1755,9 @@ await Dispatcher.InvokeAsync(() => /// - 如果收到与当前记录相同的页码或已有切换正在处理,则忽略该事件。 /// - 在切换过程中会保存前一页的墨迹(如存在)、清空画布与历史、加载新页的墨迹、锁定新页墨迹并刷新当前页显示序号,同时更新内部的当前播放位置状态。 /// - private void OnPPTSlideShowNextSlide(object payload) + private Task OnPPTSlideShowNextSlide(object payload) { + Task loaded = Task.CompletedTask; var wn = payload as SlideShowWindow; var agentState = payload as PPTState; try @@ -1520,79 +1796,46 @@ private void OnPPTSlideShowNextSlide(object payload) currentSlide = agentState?.SlideIndex ?? _pptManager?.GetCurrentSlideNumber() ?? 0; } + if (DifferentShow(payload)) + { + OnPPTSlideShowBegin(payload); + return Task.CompletedTask; + } totalSlides = agentState?.TotalSlides ?? _pptManager?.SlidesCount ?? 0; if (totalSlides > 0) { _presentationSlideCountSnapshot = totalSlides; } - if (currentSlide == _previousSlideID) return; + if (currentSlide <= 0) return Task.CompletedTask; + RememberQuickPanelOwners(); + if (agentState?.SlideIds?.Length > 0) _lastFlipWithSlideIds = agentState; + var next = CurrentShowKey(currentSlide, wn, agentState); - int prev = _previousSlideID; - - Application.Current.Dispatcher.InvokeAsync(() => + int previousPosition = _currentSlideShowPosition; + _currentSlideShowPosition = currentSlide; + ObserveShowPage(currentSlide, next); + _pptUIManager?.UpdateCurrentSlideNumber(currentSlide, totalSlides); + if (next == _canvasSlide) { - MemoryStream ms; - if (inkCanvas.Strokes.Count > 0) - { - ms = new MemoryStream(); - inkCanvas.Strokes.Save(ms); - ms.Position = 0; - } - else - { - ms = new MemoryStream(); - } - - lock (_memoryStreams) - { - if (_memoryStreams.ContainsKey(prev)) - _memoryStreams[prev]?.Dispose(); - _memoryStreams[prev] = ms; - } - - ClearStrokes(true); - timeMachine.ClearStrokeHistory(); - - _currentSlideShowPosition = currentSlide; - _singlePPTInkManager?.LockInkForSlide(currentSlide); - _pptUIManager?.UpdateCurrentSlideNumber(currentSlide, totalSlides); + if (previousPosition != currentSlide) SaveShowCanvas(previousPosition); + return Task.CompletedTask; + } - byte[] bytesToLoad = null; - lock (_memoryStreams) - { - if (_memoryStreams.ContainsKey(currentSlide) && _memoryStreams[currentSlide] != null) - bytesToLoad = _memoryStreams[currentSlide].ToArray(); - } - if (bytesToLoad != null) - { - if (bytesToLoad.Length > 8) - { - int loadingPage = currentSlide; - Task.Run(() => - { - try - { - return new StrokeCollection(new MemoryStream(bytesToLoad)); - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"从内存流加载第 {loadingPage} 页墨迹失败: {ex}", LogHelper.LogType.Warning); - return null; - } - }).ContinueWith(t => - { - if (t.IsFaulted || t.Result == null) return; - Application.Current.Dispatcher.InvokeAsync(() => - { - if (_currentSlideShowPosition != loadingPage) return; - inkCanvas.Strokes.Add(t.Result); - }); - }); - } - } - }); - _previousSlideID = currentSlide; + // 事件入口已封送到 UI 线程。先按画布原有身份保存,再加载新页。 + if (_pendingSlideDecode != null && inkCanvas.Strokes.Count == 0) + { + // 快速离开尚未解码的页,保存原有 ISF,不把临时空画布写回。 + _pendingSlideDecode = null; + _archivePages[previousPosition] = _memoryStreams.Read(_canvasSlide); + } + else SaveShowCanvas(previousPosition); + LeavePptUInkMedia(_canvasSlide); + _canvasSlide = next; + ClaimArchivePage(currentSlide); + _singlePPTInkManager?.LockInkForSlide(currentSlide); + loaded = LoadFlipInk(next); + EnterPptUInkMedia(next); NotifyPluginSlideChanged(currentSlide); // 刷新智慧模式区域(翻页时视频控件可能变化) @@ -1606,6 +1849,7 @@ private void OnPPTSlideShowNextSlide(object payload) { LogHelper.WriteLogToFile($"处理幻灯片切换事件失败: {ex}", LogHelper.LogType.Error); } + return loaded; } #region 智慧模式:视频控件区域刷新与坐标转换 @@ -1875,25 +2119,9 @@ private async void OnPPTSlideShowEnd(object payload) var agentState = payload as PPTState; try { - ResetPPTEnhancedPreviewCache(); - await Application.Current.Dispatcher.InvokeAsync(() => CollapseAllPPTNavBarPreviews()); - - // 形态收敛(折叠/展开)统一交给状态机 helper;这里只描述目标形态,位置由清理段尾部统一落地。 - await SettleFloatingBarAfterPPTSlideShowAsync(applyFinalPosition: false); - - if (isEnteredSlideShowEndEvent) return; + if (DifferentShow(payload) || isEnteredSlideShowEndEvent) return; + int endingShow = _showGeneration; isEnteredSlideShowEndEvent = true; - NotifyPluginSlideShowStateChanged(false); - - // 清除智慧模式区域 - _smartModeRegions = null; - _smartModeSlideIndex = -1; - - // 清除WPF坐标映射和定时器 - _mediaPassthroughRects?.Clear(); - StopMediaPassthroughTimer(); - _isMediaRegionMouseMode = false; - // 获取当前播放页码,优先使用跟踪的页码,否则尝试从PPT管理器获取 int currentPage = _currentSlideShowPosition; if (currentPage <= 0) @@ -1916,30 +2144,9 @@ private async void OnPPTSlideShowEnd(object payload) } } - await Application.Current.Dispatcher.InvokeAsync(() => - { - if (currentPage > 0 && inkCanvas?.Strokes != null) - { - MemoryStream ms; - if (inkCanvas.Strokes.Count > 0) - { - ms = new MemoryStream(); - inkCanvas.Strokes.Save(ms); - ms.Position = 0; - } - else - { - ms = new MemoryStream(); - } - - lock (_memoryStreams) - { - if (_memoryStreams.ContainsKey(currentPage)) - _memoryStreams[currentPage]?.Dispose(); - _memoryStreams[currentPage] = ms; - } - } - }); + if (currentPage > 0 && inkCanvas?.Strokes != null && + (currentMode == 0 || ResolveStrokeSaveFormat(Settings.Automation) != StrokeSaveFormat.UInk)) + SaveShowCanvas(currentPage); string presentationNameForSave = !string.IsNullOrEmpty(agentState?.PresentationName) ? agentState.PresentationName @@ -2000,75 +2207,46 @@ await Application.Current.Dispatcher.InvokeAsync(() => } } + Task archiveWrite = Task.CompletedTask; if (Settings.PowerPointSettings.IsAutoSaveStrokesInPowerPoint && !string.IsNullOrEmpty(presentationNameForSave) && totalSlidesForSave > 0) { string folderPathForSave = GetPresentationStrokeFolderPath(pres, presentationNameForSave, totalSlidesForSave, presentationFullNameForSave); - await Task.Run(() => - { - try - { - if (!Directory.Exists(folderPathForSave)) - Directory.CreateDirectory(folderPathForSave); - - // 先在锁内快照出 (页码, 字节) 列表,再在锁外做磁盘 IO。 - // 之前在 lock 内直接 File.WriteAllBytes 把磁盘 IO 与字典保护混在一起, - // 磁盘繁忙/AV 扫描锁定文件时 _memoryStreams 被独占数十秒, - // 期间 OnPPTSlideShowNextSlide/ExitPPTPresentation 任何持锁访问全卡死。 - var snapshot = new List<(int page, byte[] bytes)>(); - lock (_memoryStreams) - { - for (int i = 1; i <= totalSlidesForSave; i++) - { - if (_memoryStreams.TryGetValue(i, out MemoryStream value) && value != null) - snapshot.Add((i, value.ToArray())); - } - } - - foreach (var (page, bytes) in snapshot) - { - try - { - string filePath = Path.Combine(folderPathForSave, page.ToString("0000") + ".icstk"); - if (bytes.Length > 8) - File.WriteAllBytes(filePath, bytes); - else if (File.Exists(filePath)) - File.Delete(filePath); - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"为第 {page} 页保存墨迹文件失败: {ex}", LogHelper.LogType.Warning); - } - } - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"保存PPT墨迹文件失败: {ex}", LogHelper.LogType.Error); - } - finally - { - lock (_memoryStreams) - { - foreach (var stream in _memoryStreams.Values) - stream?.Dispose(); - _memoryStreams.Clear(); - } - } - }); + archiveWrite = SavePptShowArchiveAsync(folderPathForSave, totalSlidesForSave, pres, agentState); } - else + + ResetPPTEnhancedPreviewCache(); + await Application.Current.Dispatcher.InvokeAsync(() => { - lock (_memoryStreams) - { - foreach (var stream in _memoryStreams.Values) - stream?.Dispose(); - _memoryStreams.Clear(); - } - } + if (endingShow == _showGeneration) CollapseAllPPTNavBarPreviews(); + }); + + if (endingShow != _showGeneration) return; + + // 形态收敛(折叠/展开)统一交给状态机 helper;这里只描述目标形态,位置由清理段尾部统一落地。 + await SettleFloatingBarAfterPPTSlideShowAsync(applyFinalPosition: false); + + if (endingShow != _showGeneration) return; + NotifyPluginSlideShowStateChanged(false); + // 清除智慧模式区域 + _smartModeRegions = null; + _smartModeSlideIndex = -1; + + // 清除WPF坐标映射和定时器 + _mediaPassthroughRects?.Clear(); + StopMediaPassthroughTimer(); + _isMediaRegionMouseMode = false; + + await archiveWrite; await Application.Current.Dispatcher.InvokeAsync(() => { try { + if (endingShow != _showGeneration) return; + _showGeneration++; + ResetShowMaps(); + _memoryStreams.Clear(); + ResetPptUInkPages(); // 更新UI状态 _pptUIManager?.UpdateSlideShowStatus(false); _pptUIManager?.UpdateSidebarExitButtons(false); @@ -2122,7 +2300,10 @@ await Application.Current.Dispatcher.InvokeAsync(() => // 可见性由 UpdateSlideShowStatus 排在 Normal。这里只等一个 ApplicationIdle 空操作: // 同优先级 FIFO 保证窗口几何与布局都已定型,随后按折叠标志落位才是真正的最终位置。 // 不要用固定延时去猜“多久算稳定”——猜短了会拿旧窗口尺寸居中,猜长了就是白等。 - await Dispatcher.InvokeAsync(ApplyFloatingBarFinalPosition, + await Dispatcher.InvokeAsync(() => + { + if (_showGeneration == endingShow + 1 && _canvasSlide == default) ApplyFloatingBarFinalPosition(); + }, System.Windows.Threading.DispatcherPriority.ApplicationIdle); } catch (Exception ex) @@ -2388,6 +2569,33 @@ private async void CheckAndNotifyAutoPlaySettings(Presentation pres, PPTState ag } } + private async Task LoadFlipInk(PptPageKey key) + { + ClearStrokes(true); + timeMachine.ClearStrokeHistory(); + byte[] bytes = _memoryStreams.Read(key); + if (bytes == null || bytes.Length == 0) return; + int generation = _showGeneration; + var dispatcher = inkCanvas.Dispatcher; + var decode = _pendingSlideDecode = Task.Run(() => PptSlideStorage.Decode(bytes)); + try { await decode.ConfigureAwait(false); } + catch (Exception) { /* 在 UI 提交处处理解码错误。 */ } + await dispatcher.InvokeAsync(() => + { + if (_pendingSlideDecode == decode && generation == _showGeneration && _canvasSlide == key) + FinishSlideDecode(); + }); + } + + private void FinishSlideDecode() + { + var decode = _pendingSlideDecode; + if (decode == null) return; + _pendingSlideDecode = null; + try { inkCanvas.Strokes.Add(decode.GetAwaiter().GetResult()); } + catch (Exception ex) { LogHelper.WriteLogToFile($"加载翻页墨迹失败: {ex}", LogHelper.LogType.Warning); } + } + /// /// 加载当前幻灯片的墨迹:清空画布和历史记录,然后加载指定幻灯片的墨迹。 /// @@ -2404,29 +2612,11 @@ private void LoadCurrentSlideInk(int slideIndex) { try { + _pendingSlideDecode = null; ClearStrokes(true); timeMachine.ClearStrokeHistory(); - byte[] bytes = null; - lock (_memoryStreams) - { - if (_memoryStreams.TryGetValue(slideIndex, out var ms) && ms != null && ms.Length > 0) - { - ms.Position = 0; - bytes = ms.ToArray(); - } - } - if (bytes != null) - { - try - { - inkCanvas.Strokes.Add(new StrokeCollection(new MemoryStream(bytes))); - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"从内存流加载第 {slideIndex} 页墨迹失败: {ex}", LogHelper.LogType.Warning); - } - } + inkCanvas.Strokes.Add(PptSlideStorage.Decode(_memoryStreams.Read(_canvasSlide))); } catch (Exception ex) { @@ -2479,13 +2669,10 @@ public void ResetPPTStateVariables() // 重置当前播放页码跟踪 _currentSlideShowPosition = 0; - _previousSlideID = 0; - lock (_memoryStreams) - { - foreach (var stream in _memoryStreams.Values) - stream?.Dispose(); - _memoryStreams.Clear(); - } + _showGeneration++; + ResetShowMaps(); + ResetPptUInkPages(); + _memoryStreams.Clear(); LogHelper.WriteLogToFile("PPT状态变量已重置", LogHelper.LogType.Trace); } @@ -3551,15 +3738,7 @@ public async Task ExitPPTPresentation() { if (inkCanvas?.Strokes != null && inkCanvas.Strokes.Count > 0) { - var ms = new MemoryStream(); - inkCanvas.Strokes.Save(ms); - ms.Position = 0; - lock (_memoryStreams) - { - if (_memoryStreams.ContainsKey(currentSlide)) - _memoryStreams[currentSlide]?.Dispose(); - _memoryStreams[currentSlide] = ms; - } + _memoryStreams.Write(_canvasSlide, PptSlideStorage.Encode(inkCanvas.Strokes)); } timeMachine.ClearStrokeHistory(); } @@ -3569,15 +3748,7 @@ await Dispatcher.InvokeAsync(() => { if (inkCanvas?.Strokes != null && inkCanvas.Strokes.Count > 0) { - var ms = new MemoryStream(); - inkCanvas.Strokes.Save(ms); - ms.Position = 0; - lock (_memoryStreams) - { - if (_memoryStreams.ContainsKey(currentSlide)) - _memoryStreams[currentSlide]?.Dispose(); - _memoryStreams[currentSlide] = ms; - } + _memoryStreams.Write(_canvasSlide, PptSlideStorage.Encode(inkCanvas.Strokes)); } timeMachine.ClearStrokeHistory(); }); diff --git a/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs b/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs index 0ae0c410b..ebfea447c 100644 --- a/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs +++ b/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs @@ -64,14 +64,24 @@ private void CollectCanvasElementsMetadata(List elementInfos) foreach (var child in inkCanvas.Children) { - if (child is Image img && img.Source is BitmapImage bmp) + if (child is Image img && (img is UInkBitmapImage { SourcePath: not null } || img.Source is BitmapImage)) { + var position = new System.Windows.Point(InkCanvas.GetLeft(img), InkCanvas.GetTop(img)); + string sourcePath; + if (img is UInkBitmapImage { SourcePath: not null } mapped) + { + // UInk 把导入位置合入矩阵;旧 sidecar 只有 Left/Top 字段。 + var matrix = img.RenderTransform.Value; + position.Offset(matrix.OffsetX, matrix.OffsetY); + sourcePath = mapped.SourcePath; + } + else sourcePath = ((BitmapImage)img.Source).UriSource?.LocalPath ?? ""; elementInfos.Add(new CanvasElementInfo { Type = "Image", - SourcePath = bmp.UriSource?.LocalPath ?? "", - Left = InkCanvas.GetLeft(img), - Top = InkCanvas.GetTop(img), + SourcePath = sourcePath, + Left = position.X, + Top = position.Y, Width = img.Width, Height = img.Height, Stretch = img.Stretch.ToString() @@ -485,14 +495,43 @@ private void SymbolIconSaveStrokes_MouseUp(object sender, MouseButtonEventArgs e /// 5. 异步上传保存的文件到Dlass /// 6. 保存元素信息 /// - public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) + public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) => + SaveInkCanvasStrokes(newNotice, saveByUser, timed: false); + + private List CollectLegacyPptStrokes() + { + var map = ReadShowSlides(); + int count = map.Count > 0 ? map.Count : _pptManager.SlidesCount; + var pages = new List(count); + for (int i = 1; i <= count; i++) + { + var key = ExportSlideKey(map, i); + // 空画布也是当前页的新状态,不能重新取回离页时的旧墨迹。 + pages.Add(key == _canvasSlide ? inkCanvas.Strokes.Clone() : + PptSlideStorage.Decode(ReadExportInk(key))); + } + return pages; + } + + internal enum StrokeSaveFormat { UInk, Xml, FullPage, Icstk } + + internal static StrokeSaveFormat ResolveStrokeSaveFormat(Automation automation) + { + if (automation.IsSaveStrokesAsUInK) return StrokeSaveFormat.UInk; + if (automation.IsSaveStrokesAsXML) return StrokeSaveFormat.Xml; + if (automation.IsSaveFullPageStrokes) return StrokeSaveFormat.FullPage; + return StrokeSaveFormat.Icstk; + } + + private void SaveInkCanvasStrokes(bool newNotice, bool saveByUser, bool timed) { try { + var format = ResolveStrokeSaveFormat(Settings.Automation); var savePath = Settings.Automation.AutoSavedStrokesLocation + (saveByUser ? @"\User Saved - " : @"\Auto Saved - ") + (currentMode == 0 ? "Annotation Strokes" : "BlackBoard Strokes"); - if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath); + if (format != StrokeSaveFormat.UInk && !Directory.Exists(savePath)) Directory.CreateDirectory(savePath); string savePathWithName; if (Settings.Automation.IsUseCustomSaveFileName) { @@ -513,14 +552,13 @@ public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) //savePathWithName = savePath + @"\" + DateTime.Now.ToString("u").Replace(':', '-') + ".icstk"; savePathWithName = savePath + @"\" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss-fff") + ".icstk"; - if (Settings.Automation.IsSaveStrokesAsUInK) + if (format == StrokeSaveFormat.UInk) { - // UInk 1.0 格式保存(跨软件互操作),走两阶段提交 - SaveCurrentStateToUInk(Path.ChangeExtension(savePathWithName, ".uink"), newNotice); + _ = SaveCurrentStateToUInk(Path.ChangeExtension(savePathWithName, ".uink"), newNotice, timed); return; } - if (Settings.Automation.IsSaveStrokesAsXML) + if (format == StrokeSaveFormat.Xml) { // XML保存模式 - 检查是否存在多页面墨迹 bool hasMultiplePages = false; @@ -530,42 +568,13 @@ public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) if (IsInPPTPresentationMode && _pptManager?.IsConnected == true) { hasMultiplePages = true; - var totalSlides = _pptManager.SlidesCount; - var currentSlide = _pptManager.GetCurrentSlideNumber(); - - for (int i = 1; i <= totalSlides; i++) - { - var slideStrokes = _singlePPTInkManager?.LoadSlideStrokes(i); - if (slideStrokes != null && slideStrokes.Count > 0) - { - allPageStrokes.Add(slideStrokes); - } - else if (i == currentSlide && inkCanvas.Strokes.Count > 0) - { - allPageStrokes.Add(inkCanvas.Strokes.Clone()); - } - else - { - allPageStrokes.Add(new StrokeCollection()); - } - } + allPageStrokes = CollectLegacyPptStrokes(); } // 检查白板模式下的多页面墨迹 else if (currentMode != 0 && WhiteboardTotalCount > 1) { hasMultiplePages = true; - for (int i = 1; i <= WhiteboardTotalCount; i++) - { - if (TimeMachineHistories[i] != null) - { - var strokes = ApplyHistoriesToNewStrokeCollection(TimeMachineHistories[i]); - allPageStrokes.Add(strokes); - } - else - { - allPageStrokes.Add(new StrokeCollection()); - } - } + allPageStrokes = CollectLegacyWhiteboardStrokes(); } if (hasMultiplePages && allPageStrokes.Count > 0) @@ -640,7 +649,7 @@ public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) } } } - else if (Settings.Automation.IsSaveFullPageStrokes) + else if (format == StrokeSaveFormat.FullPage) { // 全页面保存模式 - 检查是否存在多页面墨迹 bool hasMultiplePages = false; @@ -651,45 +660,14 @@ public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) { hasMultiplePages = true; // 收集PPT放映模式下的所有页面墨迹 - var totalSlides = _pptManager.SlidesCount; - var currentSlide = _pptManager.GetCurrentSlideNumber(); - - for (int i = 1; i <= totalSlides; i++) - { - var slideStrokes = _singlePPTInkManager?.LoadSlideStrokes(i); - if (slideStrokes != null && slideStrokes.Count > 0) - { - allPageStrokes.Add(slideStrokes); - } - else if (i == currentSlide && inkCanvas.Strokes.Count > 0) - { - // 当前页面的墨迹 - allPageStrokes.Add(inkCanvas.Strokes.Clone()); - } - else - { - allPageStrokes.Add(new StrokeCollection()); // 空页面 - } - } + allPageStrokes = CollectLegacyPptStrokes(); } // 检查白板模式下的多页面墨迹 else if (currentMode != 0 && WhiteboardTotalCount > 1) { hasMultiplePages = true; // 收集白板模式下的所有页面墨迹 - for (int i = 1; i <= WhiteboardTotalCount; i++) - { - if (TimeMachineHistories[i] != null) - { - // 从历史记录中恢复墨迹 - var strokes = ApplyHistoriesToNewStrokeCollection(TimeMachineHistories[i]); - allPageStrokes.Add(strokes); - } - else - { - allPageStrokes.Add(new StrokeCollection()); // 空页面 - } - } + allPageStrokes = CollectLegacyWhiteboardStrokes(); } if (hasMultiplePages && allPageStrokes.Count > 0) @@ -714,42 +692,13 @@ public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) if (IsInPPTPresentationMode && _pptManager?.IsConnected == true) { hasMultiplePages = true; - var totalSlides = _pptManager.SlidesCount; - var currentSlide = _pptManager.GetCurrentSlideNumber(); - - for (int i = 1; i <= totalSlides; i++) - { - var slideStrokes = _singlePPTInkManager?.LoadSlideStrokes(i); - if (slideStrokes != null && slideStrokes.Count > 0) - { - allPageStrokes.Add(slideStrokes); - } - else if (i == currentSlide && inkCanvas.Strokes.Count > 0) - { - allPageStrokes.Add(inkCanvas.Strokes.Clone()); - } - else - { - allPageStrokes.Add(new StrokeCollection()); - } - } + allPageStrokes = CollectLegacyPptStrokes(); } // 检查白板模式下的多页面墨迹 else if (currentMode != 0 && WhiteboardTotalCount > 1) { hasMultiplePages = true; - for (int i = 1; i <= WhiteboardTotalCount; i++) - { - if (TimeMachineHistories[i] != null) - { - var strokes = ApplyHistoriesToNewStrokeCollection(TimeMachineHistories[i]); - allPageStrokes.Add(strokes); - } - else - { - allPageStrokes.Add(new StrokeCollection()); - } - } + allPageStrokes = CollectLegacyWhiteboardStrokes(); } if (hasMultiplePages && allPageStrokes.Count > 0) @@ -799,60 +748,40 @@ public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) else { // 单页面保存 - if (Settings.Automation.IsSaveStrokesAsXML) + // 保存为二进制格式:先写临时文件后 Replace 原子替换, + // 避免 FileMode.Create 直接截断 → 写入中途失败 → 文件停在 0 字节。 + // 同目录下移动替换是原子操作,Windows 同卷 NTFS 保证。 + var tmpPath = savePathWithName + ".tmp"; + try { - // 保存为XML格式 - string xmlPath = Path.ChangeExtension(savePathWithName, ".xml"); - SaveStrokesAsXML(inkCanvas.Strokes, xmlPath); - SavePluginPageDocumentSidecar(xmlPath, CurrentWhiteboardIndex); - if (newNotice) + using (var fs = new FileStream(tmpPath, FileMode.Create)) { - Task.Delay(100).ContinueWith(t => - { - Dispatcher.Invoke(() => - { - ShowNotification(string.Format(MainWindowStrings.Main_Strokes_SaveXmlSuccess, xmlPath)); - }); - }); + inkCanvas.Strokes.Save(fs); } + if (File.Exists(savePathWithName)) + File.Replace(tmpPath, savePathWithName, null); + else + File.Move(tmpPath, savePathWithName); } - else + catch { - // 保存为二进制格式:先写临时文件后 Replace 原子替换, - // 避免 FileMode.Create 直接截断 → 写入中途失败 → 文件停在 0 字节。 - // 同目录下移动替换是原子操作,Windows 同卷 NTFS 保证。 - var tmpPath = savePathWithName + ".tmp"; - try + try { if (File.Exists(tmpPath)) File.Delete(tmpPath); } + catch (Exception ex) { - using (var fs = new FileStream(tmpPath, FileMode.Create)) - { - inkCanvas.Strokes.Save(fs); - } - if (File.Exists(savePathWithName)) - File.Replace(tmpPath, savePathWithName, null); - else - File.Move(tmpPath, savePathWithName); + LogHelper.WriteLogToFile($"[Settings] 原子写入墨迹文件失败后删除临时文件 {Path.GetFileName(tmpPath)} 失败: {ex.Message}", LogHelper.LogType.Info); } - catch - { - try { if (File.Exists(tmpPath)) File.Delete(tmpPath); } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"[Settings] 原子写入墨迹文件失败后删除临时文件 {Path.GetFileName(tmpPath)} 失败: {ex.Message}", LogHelper.LogType.Info); - } - throw; - } - SavePluginPageDocumentSidecar(savePathWithName, CurrentWhiteboardIndex); - if (newNotice) + throw; + } + SavePluginPageDocumentSidecar(savePathWithName, CurrentWhiteboardIndex); + if (newNotice) + { + Task.Delay(100).ContinueWith(t => { - Task.Delay(100).ContinueWith(t => + Dispatcher.Invoke(() => { - Dispatcher.Invoke(() => - { - ShowNotification(string.Format(MainWindowStrings.Main_Strokes_SaveSuccess, savePathWithName)); - }); + ShowNotification(string.Format(MainWindowStrings.Main_Strokes_SaveSuccess, savePathWithName)); }); - } + }); } // 异步上传文件 @@ -860,8 +789,7 @@ public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) { try { - string uploadPath = Settings.Automation.IsSaveStrokesAsXML ? Path.ChangeExtension(savePathWithName, ".xml") : savePathWithName; - await Helpers.UploadHelper.UploadFileAsync(uploadPath); + await Helpers.UploadHelper.UploadFileAsync(savePathWithName); } catch (Exception ex) { @@ -872,7 +800,7 @@ public void SaveInkCanvasStrokes(bool newNotice = true, bool saveByUser = false) // 保存元素信息 var elementInfos = new List(); CollectCanvasElementsMetadata(elementInfos); - string elementsPath = Settings.Automation.IsSaveStrokesAsXML ? Path.ChangeExtension(savePathWithName, ".elements.json") : Path.ChangeExtension(savePathWithName, ".elements.json"); + string elementsPath = Path.ChangeExtension(savePathWithName, ".elements.json"); File.WriteAllText(elementsPath, JsonConvert.SerializeObject(elementInfos, Newtonsoft.Json.Formatting.Indented)); } } @@ -1359,7 +1287,7 @@ internal bool ExportStrokesAsPngForPlugin(StrokeCollection strokes, string fileP /// - 其他:处理单个墨迹文件(二进制格式) /// 5. 如果墨迹画布不可见,切换到鼠标模式 /// - private void SymbolIconOpenStrokes_MouseUp(object sender, MouseButtonEventArgs e) + private async void SymbolIconOpenStrokes_MouseUp(object sender, MouseButtonEventArgs e) { if (TryBlockFrozenPageMutation("打开墨迹文件")) return; if (lastBorderMouseDownObject != sender) return; @@ -1392,10 +1320,9 @@ private void SymbolIconOpenStrokes_MouseUp(object sender, MouseButtonEventArgs e } } - if (fileExtension == ".uink") + if (FileAssociationManager.IsUInkStrokeFile(openFileDialog.FileName)) { - // UInk 1.0 墨迹文件(MessagePack 对象流 + .uink.extra 资源包) - OpenUInkFile(openFileDialog.FileName); + if (!await OpenUInkFromEntryAsync(openFileDialog.FileName)) return; } else if (fileExtension == ".zip") { @@ -1449,6 +1376,7 @@ private static string BuildOpenStrokesFilter() /// private void OpenICCZipFile(string zipFilePath) { + BeginCanvasOpen(); try { // 创建临时目录来解压文件 @@ -1621,26 +1549,29 @@ private void RestorePPTStrokesFromZip(string tempDir, Dictionary parsedStrokesByPage[pageNumber] = strokes; } - // 清空当前墨迹 + // 先固定与逐页导出相同的身份,再整体替换,避免清理时改变待认领归档的映射。 + var map = ReadShowSlides(); + var writes = parsedStrokesByPage.ToDictionary(pair => ExportSlideKey(map, pair.Key), + pair => PptSlideStorage.Encode(pair.Value)); + _uinkOpenGeneration++; ClearStrokes(true); timeMachine.ClearStrokeHistory(); + ReleaseLegacyReplacedDocument(UInkWorkspaceType.Presentation); // 重置PPT墨迹存储 - _singlePPTInkManager?.ClearAllStrokes(); - - foreach (var pair in parsedStrokesByPage) - _singlePPTInkManager?.ForceSaveSlideStrokes(pair.Key, pair.Value); - - // 恢复当前页面的墨迹 - if (_pptManager?.IsInSlideShow == true) + if (_singlePPTInkManager != null) _singlePPTInkManager.ClearAllStrokes(); + else _memoryStreams.Clear(); + foreach (int position in _archivePages.Keys.ToArray()) { - int currentSlide = _pptManager.GetCurrentSlideNumber(); - var currentStrokes = _singlePPTInkManager?.LoadSlideStrokes(currentSlide); - if (currentStrokes != null && currentStrokes.Count > 0) - { - inkCanvas.Strokes.Add(currentStrokes); - } + var key = _observedShowKeys.GetValueOrDefault(position, PptPageKey.At(position, null)); + _archivePages[position] = writes.GetValueOrDefault(key) ?? Array.Empty(); } + _unclaimedArchivePages.RemoveWhere(position => _archivePages[position].Length == 0); + foreach (var pair in writes) + if (!_unclaimedArchivePages.Contains(pair.Key.Position)) _memoryStreams.Write(pair.Key, pair.Value); + + if (_pptManager?.IsInSlideShow == true) + inkCanvas.Strokes.Add(PptSlideStorage.Decode(_memoryStreams.Read(_canvasSlide))); LogHelper.WriteLogToFile($"成功恢复PPT墨迹,共{allFiles.Count}页"); } @@ -1692,6 +1623,7 @@ private void RestoreWhiteboardStrokesFromZip(string tempDir, Dictionary public void OpenXMLStrokeFile(string filePath) { + BeginCanvasOpen(); if (TryBlockFrozenPageMutation("打开墨迹文件")) return; try { @@ -1776,6 +1710,8 @@ public void OpenXMLStrokeFile(string filePath) } } + int generation = ++_uinkOpenGeneration; + if (ActiveUInkWorkspace == UInkWorkspaceType.ScreenAnnotation) ReleaseLegacyReplacedDocument(ActiveUInkWorkspace); ClearStrokes(true); timeMachine.ClearStrokeHistory(); inkCanvas.Strokes.Add(strokes); @@ -1810,7 +1746,7 @@ public void OpenXMLStrokeFile(string filePath) } else if (string.Equals(info.Type, "Pdf", StringComparison.OrdinalIgnoreCase) && File.Exists(info.SourcePath)) { - Dispatcher.BeginInvoke(new Action(() => { _ = RestorePdfFromElementInfoAsync(info); }), DispatcherPriority.Loaded); + _ = RestorePdfFromElementInfoAsync(info, generation); } else if (string.Equals(info.Type, "Media", StringComparison.OrdinalIgnoreCase) && File.Exists(info.SourcePath)) { @@ -1937,11 +1873,21 @@ private DrawingAttributes ParseDrawingAttributes(string attributesStr) /// public void OpenSingleStrokeFile(string filePath) { + if (FileAssociationManager.IsUInkStrokeFile(filePath)) + { + _ = OpenUInkFromEntryAsync(filePath); + return; + } + + BeginCanvasOpen(); if (TryBlockFrozenPageMutation("打开墨迹文件")) return; + int generation; var fileStreamHasNoStroke = false; using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { var strokes = new StrokeCollection(fs); + generation = ++_uinkOpenGeneration; + if (ActiveUInkWorkspace == UInkWorkspaceType.ScreenAnnotation) ReleaseLegacyReplacedDocument(ActiveUInkWorkspace); fileStreamHasNoStroke = strokes.Count == 0; if (!fileStreamHasNoStroke) { @@ -1982,7 +1928,7 @@ public void OpenSingleStrokeFile(string filePath) } else if (string.Equals(info.Type, "Pdf", StringComparison.OrdinalIgnoreCase) && File.Exists(info.SourcePath)) { - Dispatcher.BeginInvoke(new Action(() => { _ = RestorePdfFromElementInfoAsync(info); }), DispatcherPriority.Loaded); + _ = RestorePdfFromElementInfoAsync(info, generation); } else if (string.Equals(info.Type, "Media", StringComparison.OrdinalIgnoreCase) && File.Exists(info.SourcePath)) { diff --git a/Ink Canvas/MainWindow_cs/MW_Screenshot.cs b/Ink Canvas/MainWindow_cs/MW_Screenshot.cs index 75efac166..bc0648b00 100644 --- a/Ink Canvas/MainWindow_cs/MW_Screenshot.cs +++ b/Ink Canvas/MainWindow_cs/MW_Screenshot.cs @@ -29,7 +29,6 @@ private void CaptureAndEnqueueScreenshotSave(bool isHideNotification, string fil System.Drawing.Bitmap bitmap = null; StrokeCollection strokesToSave = null; - int pageIndexForStrokes = 0; string strokeSavePath = null; try @@ -37,31 +36,7 @@ private void CaptureAndEnqueueScreenshotSave(bool isHideNotification, string fil bitmap = CaptureScreenshotToBitmap(); if (bitmap == null) return; - if (Settings.Automation.IsAutoSaveStrokesAtScreenshot && inkCanvas.Strokes.Count > 0) - { - strokesToSave = inkCanvas.Strokes.Clone(); - pageIndexForStrokes = CurrentWhiteboardIndex; - var basePath = Settings.Automation.AutoSavedStrokesLocation - + @"\Auto Saved - BlackBoard Strokes"; - if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath); - string stem; - if (Settings.Automation.IsUseCustomSaveFileName) - { - stem = SaveFileNameHelper.Render(Settings.Automation.CustomSaveFileNameTemplate, - new SaveFileNameContext - { - Mode = "BlackBoard", - Type = "Auto", - Page = pageIndexForStrokes, - Count = strokesToSave.Count - }); - } - else - { - stem = $"{DateTime.Now:yyyy-MM-dd HH-mm-ss-fff} Page-{pageIndexForStrokes} StrokesCount-{strokesToSave.Count}"; - } - strokeSavePath = Path.Combine(basePath, stem + ".icstk"); - } + CaptureScreenshotCompanion(out strokesToSave, out strokeSavePath); } catch (Exception ex) { @@ -129,6 +104,48 @@ private void CaptureAndEnqueueScreenshotSave(bool isHideNotification, string fil }); } + // 在截图入队前保留当前文档;ISF 副本交给截图队列,UInk 交给统一的保存队列。 + internal void CaptureScreenshotCompanion(out StrokeCollection strokesToSave, out string strokeSavePath) + { + strokesToSave = null; + strokeSavePath = null; + bool saveUInk = ResolveStrokeSaveFormat(Settings.Automation) == StrokeSaveFormat.UInk; + if (Settings.Automation.IsAutoSaveStrokesAtScreenshot && + (saveUInk ? HasSavableDocumentContent() : inkCanvas.Strokes.Count > 0)) + { + int pageIndexForStrokes = CurrentWhiteboardIndex; + int strokeCount = inkCanvas.Strokes.Count; + var basePath = Settings.Automation.AutoSavedStrokesLocation + + @"\Auto Saved - BlackBoard Strokes"; + if (!saveUInk && !Directory.Exists(basePath)) Directory.CreateDirectory(basePath); + string stem; + if (Settings.Automation.IsUseCustomSaveFileName) + { + stem = SaveFileNameHelper.Render(Settings.Automation.CustomSaveFileNameTemplate, + new SaveFileNameContext + { + Mode = "BlackBoard", + Type = "Auto", + Page = pageIndexForStrokes, + Count = strokeCount + }); + } + else + { + stem = $"{DateTime.Now:yyyy-MM-dd HH-mm-ss-fff} Page-{pageIndexForStrokes} StrokesCount-{strokeCount}"; + } + // 切页/清屏前抓取实时快照,编码与提交复用 UInk 保存队列。 + if (saveUInk) + _ = SaveCurrentStateToUInk(Path.Combine(basePath, stem + ".uink"), false, upload: false); + else + { + // 此队列此前始终写单页 ISF,保留 XML/整页配置下的伴随文件行为。 + strokesToSave = inkCanvas.Strokes.Clone(); + strokeSavePath = Path.Combine(basePath, stem + ".icstk"); + } + } + } + /// /// 将当前屏幕内容捕获为位图(仅内存,不写文件)。调用方或后台任务负责 Dispose。 /// diff --git a/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs b/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs index 01223d29d..1a42b77f1 100644 --- a/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs +++ b/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs @@ -177,6 +177,11 @@ private void LoadSettings(bool isStartup = false, bool skipAutoUpdateCheck = fal LogHelper.WriteLogToFile("[Fold] 迁移退出白板/PPT 后的浮动栏形态设置失败", LogHelper.LogType.Warning); } + if (SettingsManager.MigrateUInkDefaultSaveFormat() && !SettingsManager.TrySaveSettingsToFile()) + { + LogHelper.WriteLogToFile("[UInk] 迁移默认墨迹保存格式后保存失败", LogHelper.LogType.Warning); + } + SettingsManager.MigrateAutoStartSetting(); if (isStartup && !AutoStartHelper.TryReconcile(Settings.Startup.RunAtStartup)) diff --git a/Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs b/Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs index 1d1b77b32..1b690bf38 100644 --- a/Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs +++ b/Ink Canvas/MainWindow_cs/MW_ShapeDrawing.cs @@ -1269,24 +1269,13 @@ private void MouseTouchMove(Point endP) // 在绘制过程中禁用浮动栏交互,避免干扰绘制 ViewboxFloatingBar.IsHitTestVisible = false; BlackboardUIGridForInkReplay.IsHitTestVisible = false; - List pointList; - StylusPointCollection point; Stroke stroke; var strokes = new StrokeCollection(); - var newIniP = iniP; switch (drawingShapeMode) { case 1: _currentCommitType = CommitReason.ShapeDrawing; - pointList = new List { - new Point(iniP.X, iniP.Y), - new Point(endP.X, endP.Y) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; + stroke = GenerateLineStroke(iniP, endP); try { inkCanvas.Strokes.Remove(lastTempStroke); @@ -1328,23 +1317,8 @@ private void MouseTouchMove(Point endP) break; case 2: _currentCommitType = CommitReason.ShapeDrawing; - double w = 15, h = 10; - var theta = Math.Atan2(iniP.Y - endP.Y, iniP.X - endP.X); - var sint = Math.Sin(theta); - var cost = Math.Cos(theta); - - pointList = new List { - new Point(iniP.X, iniP.Y), - new Point(endP.X, endP.Y), - new Point(endP.X + (w * cost - h * sint), endP.Y + (w * sint + h * cost)), - new Point(endP.X, endP.Y), - new Point(endP.X + (w * cost + h * sint), endP.Y - (h * cost - w * sint)) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; + stroke = UInk.IccShapeDescriptor.Between(UInk.IccShapeDescriptor.Tool.Arrow, iniP, endP) + .Preview(inkCanvas.DefaultDrawingAttributes)[0]; try { inkCanvas.Strokes.Remove(lastTempStroke); @@ -1356,58 +1330,8 @@ private void MouseTouchMove(Point endP) break; case 15: _currentCommitType = CommitReason.ShapeDrawing; - var d = GetDistance(iniP, endP); - if (d == 0) return; - var sinTheta = (iniP.Y - endP.Y) / d; - var cosTheta = (endP.X - iniP.X) / d; - var tanTheta = Math.Abs(sinTheta / cosTheta); - double x = 25; - if (Math.Abs(tanTheta) < 1.0 / 12) - { - sinTheta = 0; - cosTheta = 1; - endP.Y = iniP.Y; - } - - if (tanTheta < 0.63 && tanTheta > 0.52) //30 - { - sinTheta = sinTheta / Math.Abs(sinTheta) * 0.5; - cosTheta = cosTheta / Math.Abs(cosTheta) * 0.866; - endP.Y = iniP.Y - d * sinTheta; - endP.X = iniP.X + d * cosTheta; - } - - if (tanTheta < 1.08 && tanTheta > 0.92) //45 - { - sinTheta = sinTheta / Math.Abs(sinTheta) * 0.707; - cosTheta = cosTheta / Math.Abs(cosTheta) * 0.707; - endP.Y = iniP.Y - d * sinTheta; - endP.X = iniP.X + d * cosTheta; - } - - if (tanTheta < 1.95 && tanTheta > 1.63) //60 - { - sinTheta = sinTheta / Math.Abs(sinTheta) * 0.866; - cosTheta = cosTheta / Math.Abs(cosTheta) * 0.5; - endP.Y = iniP.Y - d * sinTheta; - endP.X = iniP.X + d * cosTheta; - } - - if (Math.Abs(cosTheta / sinTheta) < 1.0 / 12) - { - endP.X = iniP.X; - sinTheta = 1; - cosTheta = 0; - } - - strokes.Add(GenerateLineStroke(new Point(iniP.X - 3 * x * sinTheta, iniP.Y - 3 * x * cosTheta), - new Point(endP.X - 3 * x * sinTheta, endP.Y - 3 * x * cosTheta))); - strokes.Add(GenerateLineStroke(new Point(iniP.X - x * sinTheta, iniP.Y - x * cosTheta), - new Point(endP.X - x * sinTheta, endP.Y - x * cosTheta))); - strokes.Add(GenerateLineStroke(new Point(iniP.X + x * sinTheta, iniP.Y + x * cosTheta), - new Point(endP.X + x * sinTheta, endP.Y + x * cosTheta))); - strokes.Add(GenerateLineStroke(new Point(iniP.X + 3 * x * sinTheta, iniP.Y + 3 * x * cosTheta), - new Point(endP.X + 3 * x * sinTheta, endP.Y + 3 * x * cosTheta))); + strokes = UInk.IccShapeTools.Parallel(iniP, endP, inkCanvas.DefaultDrawingAttributes); + if (strokes.Count == 0) return; try { inkCanvas.Strokes.Remove(lastTempStrokeCollection); @@ -1421,104 +1345,14 @@ private void MouseTouchMove(Point endP) inkCanvas.Strokes.Add(strokes); break; case 11: - _currentCommitType = CommitReason.ShapeDrawing; - var xAxisStart = new Point(2 * iniP.X - (endP.X - 20), iniP.Y); - var xAxisEnd = new Point(endP.X, iniP.Y); - var yAxisStart = new Point(iniP.X, 2 * iniP.Y - (endP.Y + 20)); - var yAxisEnd = new Point(iniP.X, endP.Y); - strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); - strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); - AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd); - try - { - inkCanvas.Strokes.Remove(lastTempStrokeCollection); - } - catch - { - Trace.WriteLine("lastTempStrokeCollection failed."); - } - - lastTempStrokeCollection = strokes; - inkCanvas.Strokes.Add(strokes); - break; case 12: - _currentCommitType = CommitReason.ShapeDrawing; - if (Math.Abs(iniP.X - endP.X) < 0.01) return; - xAxisStart = new Point(iniP.X + (iniP.X - endP.X) / Math.Abs(iniP.X - endP.X) * 25, iniP.Y); - xAxisEnd = new Point(endP.X, iniP.Y); - yAxisStart = new Point(iniP.X, 2 * iniP.Y - (endP.Y + 20)); - yAxisEnd = new Point(iniP.X, endP.Y); - strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); - strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); - AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd); - try - { - inkCanvas.Strokes.Remove(lastTempStrokeCollection); - } - catch - { - Trace.WriteLine("lastTempStrokeCollection failed."); - } - - lastTempStrokeCollection = strokes; - inkCanvas.Strokes.Add(strokes); - break; case 13: - _currentCommitType = CommitReason.ShapeDrawing; - if (Math.Abs(iniP.Y - endP.Y) < 0.01) return; - xAxisStart = new Point(2 * iniP.X - (endP.X - 20), iniP.Y); - xAxisEnd = new Point(endP.X, iniP.Y); - yAxisStart = new Point(iniP.X, iniP.Y + (iniP.Y - endP.Y) / Math.Abs(iniP.Y - endP.Y) * 25); - yAxisEnd = new Point(iniP.X, endP.Y); - strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); - strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); - AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd); - try - { - inkCanvas.Strokes.Remove(lastTempStrokeCollection); - } - catch - { - Trace.WriteLine("lastTempStrokeCollection failed."); - } - - lastTempStrokeCollection = strokes; - inkCanvas.Strokes.Add(strokes); - break; case 14: - _currentCommitType = CommitReason.ShapeDrawing; - if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return; - xAxisStart = new Point(iniP.X + (iniP.X - endP.X) / Math.Abs(iniP.X - endP.X) * 25, iniP.Y); - xAxisEnd = new Point(endP.X, iniP.Y); - yAxisStart = new Point(iniP.X, iniP.Y + (iniP.Y - endP.Y) / Math.Abs(iniP.Y - endP.Y) * 25); - yAxisEnd = new Point(iniP.X, endP.Y); - strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); - strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); - AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd); - try - { - inkCanvas.Strokes.Remove(lastTempStrokeCollection); - } - catch - { - Trace.WriteLine("lastTempStrokeCollection failed."); - } - - lastTempStrokeCollection = strokes; - inkCanvas.Strokes.Add(strokes); - break; case 17: _currentCommitType = CommitReason.ShapeDrawing; - xAxisStart = new Point(iniP.X, iniP.Y); - xAxisEnd = new Point(iniP.X + Math.Abs(endP.X - iniP.X), iniP.Y); - yAxisStart = new Point(iniP.X, iniP.Y); - yAxisEnd = new Point(iniP.X, iniP.Y - Math.Abs(endP.Y - iniP.Y)); - strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); - strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); - d = (Math.Abs(iniP.X - endP.X) + Math.Abs(iniP.Y - endP.Y)) / 2; - var zAxisEnd = new Point(iniP.X - d / 1.76, iniP.Y + d / 1.76); - strokes.Add(GenerateArrowLineStroke(new Point(iniP.X, iniP.Y), zAxisEnd)); - AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd, zAxisEnd); + strokes = UInk.IccShapeTools.Axes(drawingShapeMode, iniP, endP, Settings.Canvas.ShowCoordinateUnitMarks, + inkCanvas.DefaultDrawingAttributes); + if (strokes.Count == 0) return; try { inkCanvas.Strokes.Remove(lastTempStrokeCollection); @@ -1532,44 +1366,9 @@ private void MouseTouchMove(Point endP) inkCanvas.Strokes.Add(strokes); break; case 3: - _currentCommitType = CommitReason.ShapeDrawing; - pointList = new List { - new Point(iniP.X, iniP.Y), - new Point(iniP.X, endP.Y), - new Point(endP.X, endP.Y), - new Point(endP.X, iniP.Y), - new Point(iniP.X, iniP.Y) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - try - { - inkCanvas.Strokes.Remove(lastTempStroke); - } - catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } - - lastTempStroke = stroke; - inkCanvas.Strokes.Add(stroke); - break; case 19: _currentCommitType = CommitReason.ShapeDrawing; - var a = iniP.X - endP.X; - var b = iniP.Y - endP.Y; - pointList = new List { - new Point(iniP.X - a, iniP.Y - b), - new Point(iniP.X - a, iniP.Y + b), - new Point(iniP.X + a, iniP.Y + b), - new Point(iniP.X + a, iniP.Y - b), - new Point(iniP.X - a, iniP.Y - b) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; + stroke = UInk.IccShapeTools.Rectangle(iniP, endP, drawingShapeMode == 19, inkCanvas.DefaultDrawingAttributes); try { inkCanvas.Strokes.Remove(lastTempStroke); @@ -1581,12 +1380,7 @@ private void MouseTouchMove(Point endP) break; case 4: _currentCommitType = CommitReason.ShapeDrawing; - pointList = GenerateEllipseGeometry(iniP, endP); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; + stroke = GenerateEllipseStroke(iniP, endP); try { inkCanvas.Strokes.Remove(lastTempStroke); @@ -1599,13 +1393,8 @@ private void MouseTouchMove(Point endP) case 5: _currentCommitType = CommitReason.ShapeDrawing; var R = GetDistance(iniP, endP); - pointList = GenerateEllipseGeometry(new Point(iniP.X - R, iniP.Y - R), + stroke = GenerateEllipseStroke(new Point(iniP.X - R, iniP.Y - R), new Point(iniP.X + R, iniP.Y + R)); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; try { inkCanvas.Strokes.Remove(lastTempStroke); @@ -1625,13 +1414,8 @@ private void MouseTouchMove(Point endP) _currentCommitType = CommitReason.ShapeDrawing; var halfA = endP.X - iniP.X; var halfB = endP.Y - iniP.Y; - pointList = GenerateEllipseGeometry(new Point(iniP.X - halfA, iniP.Y - halfB), + stroke = GenerateEllipseStroke(new Point(iniP.X - halfA, iniP.Y - halfB), new Point(iniP.X + halfA, iniP.Y + halfB)); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; try { inkCanvas.Strokes.Remove(lastTempStroke); @@ -1643,57 +1427,7 @@ private void MouseTouchMove(Point endP) break; case 23: _currentCommitType = CommitReason.ShapeDrawing; - a = Math.Abs(endP.X - iniP.X); - b = Math.Abs(endP.Y - iniP.Y); - pointList = GenerateEllipseGeometry(new Point(iniP.X - a, iniP.Y - b), - new Point(iniP.X + a, iniP.Y + b)); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke); - var c = Math.Sqrt(Math.Abs(a * a - b * b)); - StylusPoint stylusPoint; - if (a > b) - { - stylusPoint = new StylusPoint(iniP.X + c, iniP.Y, (float)1.0); - point = new StylusPointCollection(); - point.Add(stylusPoint); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - stylusPoint = new StylusPoint(iniP.X - c, iniP.Y, (float)1.0); - point = new StylusPointCollection(); - point.Add(stylusPoint); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - } - else if (a < b) - { - stylusPoint = new StylusPoint(iniP.X, iniP.Y - c, (float)1.0); - point = new StylusPointCollection(); - point.Add(stylusPoint); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - stylusPoint = new StylusPoint(iniP.X, iniP.Y + c, (float)1.0); - point = new StylusPointCollection(); - point.Add(stylusPoint); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - } - + strokes = UInk.IccShapeTools.EllipseWithFoci(iniP, endP, inkCanvas.DefaultDrawingAttributes); try { inkCanvas.Strokes.Remove(lastTempStrokeCollection); @@ -1725,107 +1459,21 @@ private void MouseTouchMove(Point endP) _currentCommitType = CommitReason.ShapeDrawing; //双曲线 x^2/a^2 - y^2/b^2 = 1 if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return; - var pointList2 = new List(); - var pointList3 = new List(); - var pointList4 = new List(); if (drawMultiStepShapeCurrentStep == 0) { //第一笔:画渐近线 var k = Math.Abs((endP.Y - iniP.Y) / (endP.X - iniP.X)); - strokes.Add( - GenerateDashedLineStrokeCollection(new Point(2 * iniP.X - endP.X, 2 * iniP.Y - endP.Y), - endP)); - strokes.Add(GenerateDashedLineStrokeCollection(new Point(2 * iniP.X - endP.X, endP.Y), - new Point(endP.X, 2 * iniP.Y - endP.Y))); + strokes = UInk.IccShapeTools.HyperbolaAsymptotes(iniP, endP, inkCanvas.DefaultDrawingAttributes); drawMultiStepShapeSpecialParameter3 = k; drawMultiStepShapeSpecialStrokeCollection = strokes; } else { - //第二笔:画双曲线 - // 保留第一笔渐近线的引用,保证收尾时移除的是画布上的实际笔画。 - if (drawMultiStepShapeSpecialStrokeCollection != null && drawMultiStepShapeSpecialStrokeCollection.Count > 0) - { - foreach (var asymptoteStroke in drawMultiStepShapeSpecialStrokeCollection) - { - strokes.Add(asymptoteStroke); - } - } - - var k = drawMultiStepShapeSpecialParameter3; - var isHyperbolaFocalPointOnXAxis = Math.Abs((endP.Y - iniP.Y) / (endP.X - iniP.X)) < k; - if (isHyperbolaFocalPointOnXAxis) - { - // 焦点在 x 轴上 - a = Math.Sqrt(Math.Abs((endP.X - iniP.X) * (endP.X - iniP.X) - - (endP.Y - iniP.Y) * (endP.Y - iniP.Y) / (k * k))); - b = a * k; - pointList = new List(); - for (var i = a; i <= Math.Abs(endP.X - iniP.X); i += 0.5) - { - var rY = Math.Sqrt(Math.Abs(k * k * i * i - b * b)); - pointList.Add(new Point(iniP.X + i, iniP.Y - rY)); - pointList2.Add(new Point(iniP.X + i, iniP.Y + rY)); - pointList3.Add(new Point(iniP.X - i, iniP.Y - rY)); - pointList4.Add(new Point(iniP.X - i, iniP.Y + rY)); - } - } - else - { - // 焦点在 y 轴上 - a = Math.Sqrt(Math.Abs((endP.Y - iniP.Y) * (endP.Y - iniP.Y) - - (endP.X - iniP.X) * (endP.X - iniP.X) * (k * k))); - b = a / k; - pointList = new List(); - for (var i = a; i <= Math.Abs(endP.Y - iniP.Y); i += 0.5) - { - var rX = Math.Sqrt(Math.Abs(i * i / k / k - b * b)); - pointList.Add(new Point(iniP.X - rX, iniP.Y + i)); - pointList2.Add(new Point(iniP.X + rX, iniP.Y + i)); - pointList3.Add(new Point(iniP.X - rX, iniP.Y - i)); - pointList4.Add(new Point(iniP.X + rX, iniP.Y - i)); - } - } - try { - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - point = new StylusPointCollection(pointList2); - stroke = new Stroke(point) - { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - point = new StylusPointCollection(pointList3); - stroke = new Stroke(point) - { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - point = new StylusPointCollection(pointList4); - stroke = new Stroke(point) - { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - if (drawingShapeMode == 25) - { - //画焦点 - c = Math.Sqrt(a * a + b * b); - stylusPoint = isHyperbolaFocalPointOnXAxis - ? new StylusPoint(iniP.X + c, iniP.Y, (float)1.0) - : new StylusPoint(iniP.X, iniP.Y + c, (float)1.0); - point = new StylusPointCollection(); - point.Add(stylusPoint); - stroke = new Stroke(point) - { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - stylusPoint = isHyperbolaFocalPointOnXAxis - ? new StylusPoint(iniP.X - c, iniP.Y, (float)1.0) - : new StylusPoint(iniP.X, iniP.Y - c, (float)1.0); - point = new StylusPointCollection(); - point.Add(stylusPoint); - stroke = new Stroke(point) - { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - } + strokes = UInk.IccShapeTools.HyperbolaPreview(drawingShapeMode, iniP, endP, + drawMultiStepShapeSpecialParameter3, drawMultiStepShapeSpecialStrokeCollection, + inkCanvas.DefaultDrawingAttributes); } catch { @@ -1854,113 +1502,11 @@ private void MouseTouchMove(Point endP) inkCanvas.Strokes.Add(strokes); break; case 20: - _currentCommitType = CommitReason.ShapeDrawing; - //抛物线 y=ax^2 - if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return; - a = (iniP.Y - endP.Y) / ((iniP.X - endP.X) * (iniP.X - endP.X)); - pointList = new List(); - pointList2 = new List(); - for (var i = 0.0; i <= Math.Abs(endP.X - iniP.X); i += 0.5) - { - pointList.Add(new Point(iniP.X + i, iniP.Y - a * i * i)); - pointList2.Add(new Point(iniP.X - i, iniP.Y - a * i * i)); - } - - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - point = new StylusPointCollection(pointList2); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - try - { - inkCanvas.Strokes.Remove(lastTempStrokeCollection); - } - catch - { - Trace.WriteLine("lastTempStrokeCollection failed."); - } - - lastTempStrokeCollection = strokes; - inkCanvas.Strokes.Add(strokes); - break; case 21: - _currentCommitType = CommitReason.ShapeDrawing; - //抛物线 y^2=ax - if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return; - a = (iniP.X - endP.X) / ((iniP.Y - endP.Y) * (iniP.Y - endP.Y)); - pointList = new List(); - pointList2 = new List(); - for (var i = 0.0; i <= Math.Abs(endP.Y - iniP.Y); i += 0.5) - { - pointList.Add(new Point(iniP.X - a * i * i, iniP.Y + i)); - pointList2.Add(new Point(iniP.X - a * i * i, iniP.Y - i)); - } - - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - point = new StylusPointCollection(pointList2); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - try - { - inkCanvas.Strokes.Remove(lastTempStrokeCollection); - } - catch - { - Trace.WriteLine("lastTempStrokeCollection failed."); - } - - lastTempStrokeCollection = strokes; - inkCanvas.Strokes.Add(strokes); - break; case 22: _currentCommitType = CommitReason.ShapeDrawing; - //抛物线 y^2=ax, 含焦点 - if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return; - var p = (iniP.Y - endP.Y) * (iniP.Y - endP.Y) / (2 * (iniP.X - endP.X)); - a = 0.5 / p; - pointList = new List(); - pointList2 = new List(); - for (var i = 0.0; i <= Math.Abs(endP.Y - iniP.Y); i += 0.5) - { - pointList.Add(new Point(iniP.X - a * i * i, iniP.Y + i)); - pointList2.Add(new Point(iniP.X - a * i * i, iniP.Y - i)); - } - - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - point = new StylusPointCollection(pointList2); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - stylusPoint = new StylusPoint(iniP.X - p / 2, iniP.Y, (float)1.0); - point = new StylusPointCollection(); - point.Add(stylusPoint); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); + strokes = UInk.IccShapeTools.ParabolaPreview(drawingShapeMode, iniP, endP, inkCanvas.DefaultDrawingAttributes); + if (strokes.Count == 0) return; try { inkCanvas.Strokes.Remove(lastTempStrokeCollection); @@ -1974,113 +1520,9 @@ private void MouseTouchMove(Point endP) inkCanvas.Strokes.Add(strokes); break; case 6: - _currentCommitType = CommitReason.ShapeDrawing; - newIniP = iniP; - if (iniP.Y > endP.Y) - { - newIniP = new Point(iniP.X, endP.Y); - endP = new Point(endP.X, iniP.Y); - } - - var topA = Math.Abs(newIniP.X - endP.X); - var topB = topA / 2.646; - //顶部椭圆 - pointList = GenerateEllipseGeometry(new Point(newIniP.X, newIniP.Y - topB / 2), - new Point(endP.X, newIniP.Y + topB / 2)); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - //底部椭圆 - pointList = GenerateEllipseGeometry(new Point(newIniP.X, endP.Y - topB / 2), - new Point(endP.X, endP.Y + topB / 2), false); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - strokes.Add(GenerateDashedLineEllipseStrokeCollection(new Point(newIniP.X, endP.Y - topB / 2), - new Point(endP.X, endP.Y + topB / 2), true, false)); - //左侧 - pointList = new List { - new Point(newIniP.X, newIniP.Y), - new Point(newIniP.X, endP.Y) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - //右侧 - pointList = new List { - new Point(endP.X, newIniP.Y), - new Point(endP.X, endP.Y) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - try - { - inkCanvas.Strokes.Remove(lastTempStrokeCollection); - } - catch - { - Trace.WriteLine("lastTempStrokeCollection failed."); - } - - lastTempStrokeCollection = strokes; - inkCanvas.Strokes.Add(strokes); - break; case 7: _currentCommitType = CommitReason.ShapeDrawing; - if (iniP.Y > endP.Y) - { - newIniP = new Point(iniP.X, endP.Y); - endP = new Point(endP.X, iniP.Y); - } - - var bottomA = Math.Abs(newIniP.X - endP.X); - var bottomB = bottomA / 2.646; - //底部椭圆 - pointList = GenerateEllipseGeometry(new Point(newIniP.X, endP.Y - bottomB / 2), - new Point(endP.X, endP.Y + bottomB / 2), false); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - strokes.Add(GenerateDashedLineEllipseStrokeCollection(new Point(newIniP.X, endP.Y - bottomB / 2), - new Point(endP.X, endP.Y + bottomB / 2), true, false)); - //左侧 - pointList = new List { - new Point((newIniP.X + endP.X) / 2, newIniP.Y), - new Point(newIniP.X, endP.Y) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - //右侧 - pointList = new List { - new Point((newIniP.X + endP.X) / 2, newIniP.Y), - new Point(endP.X, endP.Y) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); + strokes = UInk.IccShapeTools.Solid(drawingShapeMode == 6, iniP, endP, inkCanvas.DefaultDrawingAttributes); try { inkCanvas.Strokes.Remove(lastTempStrokeCollection); @@ -2098,11 +1540,7 @@ private void MouseTouchMove(Point endP) _currentCommitType = CommitReason.ShapeDrawing; if (isFirstTouchCuboid) { - //分开画线条方便后期单独擦除某一条棱 - strokes.Add(GenerateLineStroke(new Point(iniP.X, iniP.Y), new Point(iniP.X, endP.Y))); - strokes.Add(GenerateLineStroke(new Point(iniP.X, endP.Y), new Point(endP.X, endP.Y))); - strokes.Add(GenerateLineStroke(new Point(endP.X, endP.Y), new Point(endP.X, iniP.Y))); - strokes.Add(GenerateLineStroke(new Point(iniP.X, iniP.Y), new Point(endP.X, iniP.Y))); + strokes = UInk.IccShapeTools.CuboidFront(iniP, endP, inkCanvas.DefaultDrawingAttributes); try { inkCanvas.Strokes.Remove(lastTempStrokeCollection); @@ -2119,59 +1557,8 @@ private void MouseTouchMove(Point endP) } else { - d = CuboidFrontRectIniP.Y - endP.Y; - if (d < 0) d = -d; //就是懒不想做反向的,不要让我去做,想做自己做好之后 Pull Request - a = CuboidFrontRectEndP.X - CuboidFrontRectIniP.X; //正面矩形长 - b = CuboidFrontRectEndP.Y - CuboidFrontRectIniP.Y; //正面矩形宽 - - //横上 - var newLineIniP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectIniP.Y - d); - var newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectIniP.Y - d); - pointList = new List { newLineIniP, newLineEndP }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - //横下 (虚线) - newLineIniP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectEndP.Y - d); - newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectEndP.Y - d); - strokes.Add(GenerateDashedLineStrokeCollection(newLineIniP, newLineEndP)); - //斜左上 - newLineIniP = new Point(CuboidFrontRectIniP.X, CuboidFrontRectIniP.Y); - newLineEndP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectIniP.Y - d); - pointList = new List { newLineIniP, newLineEndP }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - //斜右上 - newLineIniP = new Point(CuboidFrontRectEndP.X, CuboidFrontRectIniP.Y); - newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectIniP.Y - d); - pointList = new List { newLineIniP, newLineEndP }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - //斜左下 (虚线) - newLineIniP = new Point(CuboidFrontRectIniP.X, CuboidFrontRectEndP.Y); - newLineEndP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectEndP.Y - d); - strokes.Add(GenerateDashedLineStrokeCollection(newLineIniP, newLineEndP)); - //斜右下 - newLineIniP = new Point(CuboidFrontRectEndP.X, CuboidFrontRectEndP.Y); - newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectEndP.Y - d); - pointList = new List { newLineIniP, newLineEndP }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - //竖左 (虚线) - newLineIniP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectIniP.Y - d); - newLineEndP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectEndP.Y - d); - strokes.Add(GenerateDashedLineStrokeCollection(newLineIniP, newLineEndP)); - //竖右 - newLineIniP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectIniP.Y - d); - newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectEndP.Y - d); - pointList = new List { newLineIniP, newLineEndP }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) { DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; - strokes.Add(stroke.Clone()); - + strokes = UInk.IccShapeTools.CuboidBack(CuboidFrontRectIniP, CuboidFrontRectEndP, + Math.Abs(CuboidFrontRectIniP.Y - endP.Y), inkCanvas.DefaultDrawingAttributes); try { inkCanvas.Strokes.Remove(lastTempStrokeCollection); @@ -2370,36 +1757,11 @@ private void UpdateTempStrokeCollectionSafely(StrokeCollection newStrokeCollecti /// 2. 根据参数决定是否绘制上半部分和下半部分 /// 3. 使用参数方程生成椭圆上的点 /// - private List GenerateEllipseGeometry(Point st, Point ed, bool isDrawTop = true, - bool isDrawBottom = true) + private Stroke GenerateEllipseStroke(Point st, Point ed, bool isDrawTop = true, bool isDrawBottom = true) { - // 防御:画布被极端缩放/平移时识别出的椭圆中心/半轴可能非有限,直接返回空避免生成 NaN 点。 - if (!double.IsFinite(st.X) || !double.IsFinite(st.Y) || - !double.IsFinite(ed.X) || !double.IsFinite(ed.Y)) - return new List(); - - var a = 0.5 * (ed.X - st.X); - var b = 0.5 * (ed.Y - st.Y); - var pointList = new List(); - if (isDrawTop && isDrawBottom) - { - for (double r = 0; r <= 2 * Math.PI; r = r + 0.01) - pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), - 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); - } - else - { - if (isDrawBottom) - for (double r = 0; r <= Math.PI; r = r + 0.01) - pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), - 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); - if (isDrawTop) - for (var r = Math.PI; r <= 2 * Math.PI; r = r + 0.01) - pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), - 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); - } - - return pointList; + var kind = isDrawTop && isDrawBottom ? UInk.IccShapeDescriptor.Tool.Ellipse : UInk.IccShapeDescriptor.Tool.Arc; + return UInk.IccShapeDescriptor.Between(kind, st, ed, (isDrawBottom ? 1 : 0) | (isDrawTop ? 2 : 0)) + .Preview(inkCanvas.DefaultDrawingAttributes)[0]; } /// @@ -2420,95 +1782,7 @@ private List GenerateEllipseGeometry(Point st, Point ed, bool isDrawTop = private StrokeCollection GenerateDashedLineEllipseStrokeCollection(Point st, Point ed, bool isDrawTop = true, bool isDrawBottom = true) { - var strokes = new StrokeCollection(); - // 防御:非有限坐标直接返回空集,避免生成 NaN 笔画。 - if (!double.IsFinite(st.X) || !double.IsFinite(st.Y) || - !double.IsFinite(ed.X) || !double.IsFinite(ed.Y)) - return strokes; - - var a = 0.5 * (ed.X - st.X); - var b = 0.5 * (ed.Y - st.Y); - var step = 0.05; - var pointList = new List(); - StylusPointCollection point; - Stroke stroke; - if (isDrawBottom) - for (var i = 0.0; i < 1.0; i += step * 1.66) - { - pointList = new List(); - for (var r = Math.PI * i; r <= Math.PI * (i + step); r = r + 0.01) - pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), - 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - } - - if (isDrawTop) - for (var i = 1.0; i < 2.0; i += step * 1.66) - { - pointList = new List(); - for (var r = Math.PI * i; r <= Math.PI * (i + step); r = r + 0.01) - pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), - 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - } - - return strokes; - } - - private const double CoordinateCentimeterUnitLength = 37.7952755906; - - private void AddCoordinateUnitMarks(StrokeCollection strokes, Point origin, Point xAxisStart, Point xAxisEnd, - Point yAxisStart, Point yAxisEnd, Point? zAxisEnd = null) - { - if (!Settings.Canvas.ShowCoordinateUnitMarks) return; - - AddCoordinateAxisUnitMarks(strokes, origin, xAxisStart, xAxisEnd, CoordinateCentimeterUnitLength, new Vector(0, 1)); - AddCoordinateAxisUnitMarks(strokes, origin, yAxisStart, yAxisEnd, CoordinateCentimeterUnitLength, new Vector(1, 0)); - if (zAxisEnd is Point zEnd) - AddCoordinateAxisUnitMarks(strokes, origin, origin, zEnd, CoordinateCentimeterUnitLength, new Vector(1, 1)); - } - - private void AddCoordinateAxisUnitMarks(StrokeCollection strokes, Point origin, Point axisStart, Point axisEnd, - double unitLength, Vector tickDirection) - { - var axisVector = axisEnd - origin; - var axisLength = axisVector.Length; - if (axisLength < 0.01) return; - - axisVector.Normalize(); - if (tickDirection.Length < 0.01) - tickDirection = new Vector(-axisVector.Y, axisVector.X); - tickDirection.Normalize(); - - for (var distance = unitLength; distance <= axisLength; distance += unitLength) - { - var positiveUnitPoint = origin + axisVector * distance; - if (IsPointOnSegment(positiveUnitPoint, axisStart, axisEnd)) - strokes.Add(GenerateLineStroke(positiveUnitPoint - tickDirection * 5, positiveUnitPoint + tickDirection * 5)); - - var negativeUnitPoint = origin - axisVector * distance; - if (IsPointOnSegment(negativeUnitPoint, axisStart, axisEnd)) - strokes.Add(GenerateLineStroke(negativeUnitPoint - tickDirection * 5, negativeUnitPoint + tickDirection * 5)); - } - } - - private bool IsPointOnSegment(Point point, Point segmentStart, Point segmentEnd) - { - const double tolerance = 0.5; - return point.X >= Math.Min(segmentStart.X, segmentEnd.X) - tolerance && - point.X <= Math.Max(segmentStart.X, segmentEnd.X) + tolerance && - point.Y >= Math.Min(segmentStart.Y, segmentEnd.Y) - tolerance && - point.Y <= Math.Max(segmentStart.Y, segmentEnd.Y) + tolerance; + return UInk.IccShapeDescriptor.Between(UInk.IccShapeDescriptor.Tool.DashedArc, st, ed, (isDrawBottom ? 1 : 0) | (isDrawTop ? 2 : 0)).Preview(inkCanvas.DefaultDrawingAttributes); } /// @@ -2525,61 +1799,9 @@ private bool IsPointOnSegment(Point point, Point segmentStart, Point segmentEnd) /// private Stroke GenerateLineStroke(Point st, Point ed) { - var pointList = new List(); - StylusPointCollection point; - Stroke stroke; - pointList = new List { - new Point(st.X, st.Y), - new Point(ed.X, ed.Y) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - return stroke; - } - - /// - /// 生成带箭头的直线笔画 - /// - /// 起始点坐标 - /// 结束点坐标 - /// 返回带箭头的直线笔画 - /// - /// 根据给定的起始点和结束点,生成带箭头的直线笔画: - /// 1. 计算箭头的角度和方向 - /// 2. 创建包含起始点、结束点和箭头尖端的点列表 - /// 3. 将点列表转换为StylusPointCollection - /// 4. 创建并返回带有默认绘图属性的笔画 - /// - private Stroke GenerateArrowLineStroke(Point st, Point ed) - { - var pointList = new List(); - StylusPointCollection point; - Stroke stroke; - - double w = 20, h = 7; - var theta = Math.Atan2(st.Y - ed.Y, st.X - ed.X); - var sint = Math.Sin(theta); - var cost = Math.Cos(theta); - - pointList = new List { - new Point(st.X, st.Y), - new Point(ed.X, ed.Y), - new Point(ed.X + (w * cost - h * sint), ed.Y + (w * sint + h * cost)), - new Point(ed.X, ed.Y), - new Point(ed.X + (w * cost + h * sint), ed.Y - (h * cost - w * sint)) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - return stroke; + return UInk.IccShapeDescriptor.Between(UInk.IccShapeDescriptor.Tool.Line, st, ed).Preview(inkCanvas.DefaultDrawingAttributes)[0]; } - /// /// 生成虚线笔画集合 /// @@ -2595,29 +1817,7 @@ private Stroke GenerateArrowLineStroke(Point st, Point ed) /// private StrokeCollection GenerateDashedLineStrokeCollection(Point st, Point ed) { - double step = 5; - var pointList = new List(); - StylusPointCollection point; - Stroke stroke; - var strokes = new StrokeCollection(); - var d = GetDistance(st, ed); - var sinTheta = (ed.Y - st.Y) / d; - var cosTheta = (ed.X - st.X) / d; - for (var i = 0.0; i < d; i += step * 2.76) - { - pointList = new List { - new Point(st.X + i * cosTheta, st.Y + i * sinTheta), - new Point(st.X + Math.Min(i + step, d) * cosTheta, st.Y + Math.Min(i + step, d) * sinTheta) - }; - point = new StylusPointCollection(pointList); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - } - - return strokes; + return UInk.IccShapeDescriptor.Between(UInk.IccShapeDescriptor.Tool.Dash, st, ed).Preview(inkCanvas.DefaultDrawingAttributes); } /// @@ -2635,27 +1835,7 @@ private StrokeCollection GenerateDashedLineStrokeCollection(Point st, Point ed) /// private StrokeCollection GenerateDotLineStrokeCollection(Point st, Point ed) { - double step = 3; - var pointList = new List(); - StylusPointCollection point; - Stroke stroke; - var strokes = new StrokeCollection(); - var d = GetDistance(st, ed); - var sinTheta = (ed.Y - st.Y) / d; - var cosTheta = (ed.X - st.X) / d; - for (var i = 0.0; i < d; i += step * 2.76) - { - var stylusPoint = new StylusPoint(st.X + i * cosTheta, st.Y + i * sinTheta, (float)0.8); - point = new StylusPointCollection(); - point.Add(stylusPoint); - stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - strokes.Add(stroke.Clone()); - } - - return strokes; + return UInk.IccShapeDescriptor.Between(UInk.IccShapeDescriptor.Tool.Dot, st, ed).Preview(inkCanvas.DefaultDrawingAttributes); } /// @@ -2885,6 +2065,7 @@ private void inkCanvas_MouseUp(object sender, MouseButtonEventArgs e) ViewboxFloatingBar.IsHitTestVisible = true; BlackboardUIGridForInkReplay.IsHitTestVisible = true; + int completedMode = drawingShapeMode; if (drawingShapeMode == 5) { if (lastTempStroke != null) @@ -2963,7 +2144,7 @@ private void inkCanvas_MouseUp(object sender, MouseButtonEventArgs e) } _currentCommitType = CommitReason.UserInput; - timeMachine.CommitStrokeUserInputHistory(CuboidStrokeCollection); + CommitDrawnShape(timeMachine, CuboidStrokeCollection, completedMode); CuboidStrokeCollection = null; } } @@ -2985,9 +2166,9 @@ private void inkCanvas_MouseUp(object sender, MouseButtonEventArgs e) switch (Settings.Canvas.HyperbolaAsymptoteOption) { case OptionalOperation.Yes: - break; case OptionalOperation.No: - RemoveHyperbolaAsymptotes(asymptoteStrokes, lastTempStrokeCollection); + ApplyAsymptoteOption(Settings.Canvas.HyperbolaAsymptoteOption, false, + inkCanvas.Strokes, asymptoteStrokes, lastTempStrokeCollection); break; case OptionalOperation.Ask: StrokeCollection pendingCollection = null; @@ -3003,15 +2184,14 @@ private void inkCanvas_MouseUp(object sender, MouseButtonEventArgs e) // 推迟到当前触摸/手写笔输入事件处理完结后再弹出模态框,避免触摸屏上弹窗按钮无响应。 Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { - if (MessageBoxHelper.Show(this, Properties.CanvasStrings.Shape_RemoveAsymptote, "Ink Canvas", MessageBoxButton.YesNo) == - MessageBoxResult.Yes) - { - RemoveHyperbolaAsymptotes(asymptoteStrokes, pendingCollection); - } + bool remove = MessageBoxHelper.Show(this, Properties.CanvasStrings.Shape_RemoveAsymptote, + "Ink Canvas", MessageBoxButton.YesNo) == MessageBoxResult.Yes; + ApplyAsymptoteOption(OptionalOperation.Ask, remove, inkCanvas.Strokes, + asymptoteStrokes, pendingCollection); if (pendingCollection != null && pendingCollection.Count > 0) { - timeMachine.CommitStrokeUserInputHistory(pendingCollection); + CommitDrawnShape(timeMachine, pendingCollection, completedMode); } })); break; @@ -3043,7 +2223,7 @@ private void inkCanvas_MouseUp(object sender, MouseButtonEventArgs e) if (lastTempStrokeCollection != null && lastTempStrokeCollection.Count > 0) collection = lastTempStrokeCollection; else if (lastTempStroke != null) collection = new StrokeCollection { lastTempStroke }; - if (collection != null) timeMachine.CommitStrokeUserInputHistory(collection); + if (collection != null) CommitDrawnShape(timeMachine, collection, completedMode); } if (completedShapeMode == 1 && lastTempStroke != null && @@ -3078,11 +2258,25 @@ private void inkCanvas_MouseUp(object sender, MouseButtonEventArgs e) if (Settings.Canvas.FitToCurve == true) drawingAttributes.FitToCurve = true; } - private void RemoveHyperbolaAsymptotes(StrokeCollection asymptoteStrokes, StrokeCollection commitCollection) + internal static void CommitDrawnShape(TimeMachine machine, StrokeCollection strokes, int mode = 0) + { + // 延迟确认等路径可能已经切回普通笔,以生成时保存在笔迹上的样式为准。 + foreach (var stroke in strokes) + { + var style = stroke.DrawingAttributes; + UInk.UInkConversion.SetLogicalPenKind(stroke, style.IsHighlighter || style.StylusTip == StylusTip.Rectangle); + } + if (mode != 0) UInk.IccShapeDescriptor.Commit(strokes, mode); + machine.CommitStrokeUserInputHistory(strokes); + } + + internal static void ApplyAsymptoteOption(OptionalOperation option, bool removeOnAsk, StrokeCollection canvas, + StrokeCollection asymptoteStrokes, StrokeCollection commitCollection) { + if (option != OptionalOperation.No && (option != OptionalOperation.Ask || !removeOnAsk)) return; foreach (var asymptoteStroke in new StrokeCollection(asymptoteStrokes)) { - if (inkCanvas.Strokes.Contains(asymptoteStroke)) inkCanvas.Strokes.Remove(asymptoteStroke); + if (canvas.Contains(asymptoteStroke)) canvas.Remove(asymptoteStroke); // 已移除的渐近线不应进入最终图形的撤销/重做记录。 commitCollection?.Remove(asymptoteStroke); } @@ -3110,36 +2304,40 @@ private bool NeedUpdateIniP() /// 绘制圆心标记 /// /// 圆心位置 - private void DrawCircleCenter(Point centerPoint) + internal static Stroke CircleCenter(Point centerPoint, DrawingAttributes da) { - try + // 创建一个点作为圆心标记 + var centerSize = 0.5; // 圆心标记的大小 + + // 创建一个小圆作为圆心标记 + var circlePoints = new List(); + for (double angle = 0; angle <= 2 * Math.PI; angle += 0.1) { - // 创建一个点作为圆心标记 - var centerSize = 0.5; // 圆心标记的大小 + circlePoints.Add(new Point( + centerPoint.X + centerSize * Math.Cos(angle), + centerPoint.Y + centerSize * Math.Sin(angle) + )); + } - // 创建一个小圆作为圆心标记 - var circlePoints = new List(); - for (double angle = 0; angle <= 2 * Math.PI; angle += 0.1) - { - circlePoints.Add(new Point( - centerPoint.X + centerSize * Math.Cos(angle), - centerPoint.Y + centerSize * Math.Sin(angle) - )); - } + // 绘制圆心点 + var point = new StylusPointCollection(circlePoints); + var stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; - // 绘制圆心点 - var point = new StylusPointCollection(circlePoints); - var stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; + // 设置圆心点的样式 + stroke.DrawingAttributes.Width = 2.0; + stroke.DrawingAttributes.Height = 2.0; - // 设置圆心点的样式 - stroke.DrawingAttributes.Width = 2.0; - stroke.DrawingAttributes.Height = 2.0; + return stroke; + } - // 添加到画布 - inkCanvas.Strokes.Add(stroke); + private void DrawCircleCenter(Point centerPoint) + { + try + { + inkCanvas.Strokes.Add(CircleCenter(centerPoint, inkCanvas.DefaultDrawingAttributes)); } catch (Exception ex) { diff --git a/Ink Canvas/MainWindow_cs/MW_SimulatePressure&InkToShape.cs b/Ink Canvas/MainWindow_cs/MW_SimulatePressure&InkToShape.cs index 3b100c6fa..5cd5e73ff 100644 --- a/Ink Canvas/MainWindow_cs/MW_SimulatePressure&InkToShape.cs +++ b/Ink Canvas/MainWindow_cs/MW_SimulatePressure&InkToShape.cs @@ -361,8 +361,11 @@ private Stroke RunStrokeCollectedPostShapeRecognitionTail(InkCanvasStrokeCollect /// private void inkCanvas_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e) { - if (e?.Stroke != null) - ProcessCommittedStroke(e.Stroke); + if (e?.Stroke == null) return; + // 传统荧光笔允许叠色时 IsHighlighter 为 false,收笔的 DA 仍保留其矩形笔尖。 + var attributes = e.Stroke.DrawingAttributes; + UInk.UInkConversion.SetLogicalPenKind(e.Stroke, attributes.IsHighlighter || attributes.StylusTip == StylusTip.Rectangle); + ProcessCommittedStroke(e.Stroke); } /// @@ -641,6 +644,7 @@ private void ProcessCommittedStroke(Stroke stroke) straightStroke.AddPropertyData(WinRTStrokeConverter.PauseStraightenedGuid, true); } straightStroke.AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + UInk.IccShapeDescriptor.Recognize(straightStroke, UInk.IccShapeDescriptor.Tool.Line); // Replace the original stroke with the straightened one ReplaceStrokesSafely(null, straightStroke, e.Stroke); @@ -771,13 +775,9 @@ async Task InkToShapeProcessCoreAsync() result.Centroid.Y - result.ShapeHeight / 2); var endP = new Point(result.Centroid.X + result.ShapeWidth / 2, result.Centroid.Y + result.ShapeHeight / 2); - var pointList = GenerateEllipseGeometry(iniP, endP); - var point = new StylusPointCollection(pointList); - var stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; + var stroke = GenerateEllipseStroke(iniP, endP); stroke.AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + UInk.IccShapeDescriptor.Commit(new StrokeCollection { stroke }, 4); circles.Add(new Circle(result.Centroid, result.ShapeWidth / 2.0, stroke)); ReplaceStrokesSafely(result.StrokesToRemove, stroke, e.Stroke); newStrokes = new StrokeCollection(); @@ -868,19 +868,8 @@ async Task InkToShapeProcessCoreAsync() newStrokes = new StrokeCollection(); - var _pointList = GenerateEllipseGeometry(iniP, endP, false); - var _point = new StylusPointCollection(_pointList); - var _stroke = new Stroke(_point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; - _stroke.AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); - var _dashedLineStroke = - GenerateDashedLineEllipseStrokeCollection(iniP, endP, true, false); - var strokes = new StrokeCollection { - _stroke, - _dashedLineStroke - }; + var strokes = UInk.IccShapeTools.TangentEllipse(iniP, endP, + inkCanvas.DefaultDrawingAttributes); ReplaceStrokesSafely(result.StrokesToRemove, strokes, e.Stroke); return; } @@ -914,13 +903,9 @@ async Task InkToShapeProcessCoreAsync() p = new PointCollection { ellipseMajor0, ellipseMinor0, ellipseMajor1, ellipseMinor1 }; } - var pointList = GenerateEllipseGeometry(iniP, endP); - var point = new StylusPointCollection(pointList); - var stroke = new Stroke(point) - { - DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() - }; + var stroke = GenerateEllipseStroke(iniP, endP); stroke.AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + UInk.IccShapeDescriptor.Commit(new StrokeCollection { stroke }, 4); if (needRotation) { @@ -965,6 +950,7 @@ async Task InkToShapeProcessCoreAsync() DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; stroke.AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + UInk.IccShapeDescriptor.Recognize(stroke, UInk.IccShapeDescriptor.Tool.Polygon); ReplaceStrokesSafely(result.StrokesToRemove, stroke, e.Stroke); GridInkCanvasSelectionCover.Visibility = Visibility.Collapsed; newStrokes = new StrokeCollection(); @@ -1007,6 +993,7 @@ async Task InkToShapeProcessCoreAsync() DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; stroke.AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + UInk.IccShapeDescriptor.Recognize(stroke, UInk.IccShapeDescriptor.Tool.Polygon); ReplaceStrokesSafely(result.StrokesToRemove, stroke, e.Stroke); GridInkCanvasSelectionCover.Visibility = Visibility.Collapsed; newStrokes = new StrokeCollection(); @@ -2293,6 +2280,12 @@ private static bool IsStrokePressureApproximatelyConstant(StylusPointCollection return true; } + internal static void InheritRecognitionPenKind(Stroke source, Stroke replacement) + { + if (source != null) + UInk.UInkConversion.SetLogicalPenKind(replacement, UInk.UInkConversion.IsLogicalHighlighter(source)); + } + private void ReplaceStrokesSafely(StrokeCollection strokesToRemove, Stroke replacementStroke, Stroke fallbackOriginalStroke = null) { if (replacementStroke == null) return; @@ -2306,6 +2299,7 @@ private void ReplaceStrokesSafely(StrokeCollection strokesToRemove, Stroke repla if (fallbackOriginalStroke != null && inkCanvas.Strokes.Contains(fallbackOriginalStroke)) inkCanvas.Strokes.Remove(fallbackOriginalStroke); + InheritRecognitionPenKind(fallbackOriginalStroke ?? strokesToRemove?.FirstOrDefault(), replacementStroke); if (!inkCanvas.Strokes.Contains(replacementStroke)) inkCanvas.Strokes.Add(replacementStroke); } @@ -2328,6 +2322,8 @@ private void ReplaceStrokesSafely(StrokeCollection strokesToRemove, StrokeCollec if (fallbackOriginalStroke != null && inkCanvas.Strokes.Contains(fallbackOriginalStroke)) inkCanvas.Strokes.Remove(fallbackOriginalStroke); + var source = fallbackOriginalStroke ?? strokesToRemove?.FirstOrDefault(); + foreach (var replacement in replacementStrokes) InheritRecognitionPenKind(source, replacement); inkCanvas.Strokes.Add(replacementStrokes); } finally @@ -3227,6 +3223,7 @@ private void CreateRectangleFromLines(List lines) DrawingAttributes = inkCanvas.DefaultDrawingAttributes.Clone() }; rectangleStroke.AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + UInk.IccShapeDescriptor.Recognize(rectangleStroke, UInk.IccShapeDescriptor.Tool.Polygon); // 移除原有的四条直线 SetNewBackupOfStroke(); @@ -3241,6 +3238,7 @@ private void CreateRectangleFromLines(List lines) } // 添加新的矩形 + InheritRecognitionPenKind(lines[lines.Count - 1].OriginalStroke, rectangleStroke); inkCanvas.Strokes.Add(rectangleStroke); _currentCommitType = CommitReason.UserInput; @@ -3525,7 +3523,10 @@ private async Task HandwritingGlyphReplaceFromBatchCoreAsync(ulong revisionWhenI } foreach (Stroke s in result) + { + InheritRecognitionPenKind(canvasStrokes[canvasStrokes.Count - 1], s); inkCanvas.Strokes.Add(s); + } _currentCommitType = CommitReason.UserInput; foreach (Stroke s in canvasStrokes) diff --git a/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs b/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs index c89829c03..2816e4d6a 100644 --- a/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs +++ b/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs @@ -1,5 +1,6 @@ using Ink_Canvas.Controls; using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; using System; using System.Collections.Generic; using System.Diagnostics; @@ -98,277 +99,46 @@ private enum CommitReason /// 将历史记录应用到画布 /// /// 时间机器历史记录项 - /// 要应用的画布,默认为null(使用主画布) - /// - /// 根据历史记录类型执行不同的操作: - /// 1. UserInput: 处理用户输入的笔画 - /// 2. ShapeRecognition: 处理形状识别的笔画 - /// 3. Manipulation: 处理笔画操作 - /// 4. DrawingAttributes: 处理绘制属性变化 - /// 5. Clear: 处理清除画布操作 - /// 6. ElementInsert: 处理元素插入操作 - /// - /// - private void ApplyHistoryToCanvas(TimeMachineHistory item, InkCanvas applyCanvas = null, HashSet elementsRemovedInThisPage = null) + internal void ApplyHistoryToCanvas(TimeMachineHistory item, InkCanvas applyCanvas = null, bool? includeElements = null) { _currentCommitType = CommitReason.CodeInput; - var canvas = inkCanvas; - if (applyCanvas != null && applyCanvas is InkCanvas) - { - canvas = applyCanvas; - } - - if (item.CommitType == TimeMachineHistoryType.UserInput) - { - if (!item.StrokeHasBeenCleared) - { - foreach (var strokes in item.CurrentStroke) - if (!canvas.Strokes.Contains(strokes)) - canvas.Strokes.Add(strokes); - } - else - { - foreach (var strokes in item.CurrentStroke) - if (canvas.Strokes.Contains(strokes)) - canvas.Strokes.Remove(strokes); - } - } - else if (item.CommitType == TimeMachineHistoryType.ShapeRecognition) - { - if (item.StrokeHasBeenCleared) - { - if (item.CurrentStroke != null) - { - foreach (var strokes in item.CurrentStroke) - if (canvas.Strokes.Contains(strokes)) - canvas.Strokes.Remove(strokes); - } - - if (item.ReplacedStroke != null) - { - foreach (var strokes in item.ReplacedStroke) - if (!canvas.Strokes.Contains(strokes)) - canvas.Strokes.Add(strokes); - } - } - else - { - if (item.CurrentStroke != null) - { - foreach (var strokes in item.CurrentStroke) - if (!canvas.Strokes.Contains(strokes)) - canvas.Strokes.Add(strokes); - } - - if (item.ReplacedStroke != null) - { - foreach (var strokes in item.ReplacedStroke) - if (canvas.Strokes.Contains(strokes)) - canvas.Strokes.Remove(strokes); - } - } - } - else if (item.CommitType == TimeMachineHistoryType.Manipulation) + try { - if (!item.StrokeHasBeenCleared) - { - foreach (var currentStroke in item.StylusPointDictionary) - { - if (canvas.Strokes.Contains(currentStroke.Key)) - { - currentStroke.Key.StylusPoints = currentStroke.Value.Item2; - } - } - } - else + var target = applyCanvas ?? inkCanvas; + bool replayElements = includeElements ?? (target == inkCanvas); + Action restoreLayout = null; + if (replayElements && target != inkCanvas && item.CommitType == TimeMachineHistoryType.ElementInsert) + restoreLayout = RestoreReplayedElementLayout; + if (item.CommitType == TimeMachineHistoryType.ElementEdit) { - foreach (var currentStroke in item.StylusPointDictionary) + if (replayElements) { - if (canvas.Strokes.Contains(currentStroke.Key)) - { - currentStroke.Key.StylusPoints = currentStroke.Value.Item1; - } + var state = item.StrokeHasBeenCleared ? item.PreviousElementState : item.CurrentElementState; + var replacement = RestoreEditedElement(item.EditedElement, state, target); + if (replacement != null) item.EditedElement = replacement; } + return; } - if (item.DrawingAttributes != null) - foreach (var attributes in item.DrawingAttributes) - if (canvas.Strokes.Contains(attributes.Key)) - attributes.Key.DrawingAttributes = (item.StrokeHasBeenCleared - ? attributes.Value.Item1 : attributes.Value.Item2).Clone(); - if (item.ElementTransforms != null) - foreach (var transform in item.ElementTransforms) - if (canvas.Children.Contains(transform.Key)) - transform.Key.SetCurrentValue(UIElement.RenderTransformProperty, - (item.StrokeHasBeenCleared ? transform.Value.Item1 : transform.Value.Item2).CloneCurrentValue()); - } - else if (item.CommitType == TimeMachineHistoryType.DrawingAttributes) - { - if (!item.StrokeHasBeenCleared) - { - foreach (var currentStroke in item.DrawingAttributes) - { - if (canvas.Strokes.Contains(currentStroke.Key)) - { - currentStroke.Key.DrawingAttributes = currentStroke.Value.Item2; - } - } - } - else - { - foreach (var currentStroke in item.DrawingAttributes) - { - if (canvas.Strokes.Contains(currentStroke.Key)) - { - currentStroke.Key.DrawingAttributes = currentStroke.Value.Item1; - } - } - } - } - else if (item.CommitType == TimeMachineHistoryType.Clear) - { - if (!item.StrokeHasBeenCleared) - { - if (item.CurrentStroke != null) - foreach (var currentStroke in item.CurrentStroke) - if (!canvas.Strokes.Contains(currentStroke)) - canvas.Strokes.Add(currentStroke); - - if (item.ReplacedStroke != null) - foreach (var replacedStroke in item.ReplacedStroke) - if (canvas.Strokes.Contains(replacedStroke)) - canvas.Strokes.Remove(replacedStroke); - } - else - { - if (item.ReplacedStroke != null) - foreach (var replacedStroke in item.ReplacedStroke) - if (!canvas.Strokes.Contains(replacedStroke)) - canvas.Strokes.Add(replacedStroke); - - if (item.CurrentStroke != null) - foreach (var currentStroke in item.CurrentStroke) - if (canvas.Strokes.Contains(currentStroke)) - canvas.Strokes.Remove(currentStroke); - } - } - else if (item.CommitType == TimeMachineHistoryType.ElementEdit) - { - var state = item.StrokeHasBeenCleared ? item.PreviousElementState : item.CurrentElementState; - var replacement = RestoreEditedElement(item.EditedElement, state, canvas); - if (replacement != null) - item.EditedElement = replacement; + new UInkCanvasReplay(target, replayElements, restoreLayout).Apply(item); + if (applyCanvas == null) ApplyPluginUndoState(item.PluginId, PluginStateAtHistoryEntry(item)); } - else if (item.CommitType == TimeMachineHistoryType.ElementInsert) - { - var targetCanvas = canvas ?? inkCanvas; + // 撤销重做后回到用户输入,避免保留 ShapeDrawing 等状态而跳过后续笔画入栈。 + finally { _currentCommitType = CommitReason.UserInput; } + } - if (item.StrokeHasBeenCleared) - { - if (elementsRemovedInThisPage != null) - return; - if (item.InsertedElement != null && targetCanvas.Children.Contains(item.InsertedElement)) - targetCanvas.Children.Remove(item.InsertedElement); - } - else - { - if (elementsRemovedInThisPage != null && item.InsertedElement != null && elementsRemovedInThisPage.Contains(item.InsertedElement)) - return; - if (item.InsertedElement != null && !targetCanvas.Children.Contains(item.InsertedElement)) - { - targetCanvas.Children.Add(item.InsertedElement); - - if (targetCanvas != inkCanvas) - { - if (item.InsertedElement is Image img) - { - double left = InkCanvas.GetLeft(img); - double top = InkCanvas.GetTop(img); - if (double.IsNaN(left) || double.IsNaN(top)) - { - CenterAndScaleElement(img); - } - } - else if (item.InsertedElement is MediaElement media) - { - double left = InkCanvas.GetLeft(media); - double top = InkCanvas.GetTop(media); - if (double.IsNaN(left) || double.IsNaN(top)) - { - CenterAndScaleElement(media); - } - } - else if (item.InsertedElement is CanvasMediaControl mediaControl) - { - double left = InkCanvas.GetLeft(mediaControl); - double top = InkCanvas.GetTop(mediaControl); - if (double.IsNaN(left) || double.IsNaN(top)) - { - CenterAndScaleElement(mediaControl); - } - } - else if (item.InsertedElement is FrameworkElement genericElement - && !(genericElement is Image) - && !(genericElement is MediaElement)) - { - // 插件插入的自定义控件(见 ICanvasElementService): - // 撤销重做重插后若位置缺失则居中,并补齐 TransformGroup。 - double left = InkCanvas.GetLeft(genericElement); - double top = InkCanvas.GetTop(genericElement); - if (double.IsNaN(left) || double.IsNaN(top)) - { - CenterAndScaleElement(genericElement); - } - if (genericElement.RenderTransform == null - || genericElement.RenderTransform == Transform.Identity) - { - InitializeElementTransform(genericElement); - } - } - } - } - } - } - else if (item.CommitType == TimeMachineHistoryType.PluginStateChange && applyCanvas == null) + // 旧版只在临时画布重插后补齐位置,并给普通控件初始化变换。 + private void RestoreReplayedElementLayout(UIElement child) + { + if (child is FrameworkElement element) { - ApplyPluginUndoState( - item.PluginId, - item.StrokeHasBeenCleared ? item.PluginStateBefore : item.PluginStateAfter); + if (double.IsNaN(InkCanvas.GetLeft(element)) || double.IsNaN(InkCanvas.GetTop(element))) + CenterAndScaleElement(element); + if (element is not Image && element is not MediaElement && element is not CanvasMediaControl && + (element.RenderTransform == null || element.RenderTransform == Transform.Identity)) + InitializeElementTransform(element); } - else if (item.CommitType == TimeMachineHistoryType.PluginInkConversion) - { - if (item.StrokeHasBeenCleared) - { - if (item.CurrentStroke != null) - foreach (var stroke in item.CurrentStroke) - if (canvas.Strokes.Contains(stroke)) - canvas.Strokes.Remove(stroke); - } - else - { - if (item.CurrentStroke != null) - foreach (var stroke in item.CurrentStroke) - if (!canvas.Strokes.Contains(stroke)) - canvas.Strokes.Add(stroke); - } - - if (applyCanvas == null) - ApplyPluginUndoState( - item.PluginId, - item.StrokeHasBeenCleared ? item.PluginStateAfter : item.PluginStateBefore); - } - - _currentCommitType = CommitReason.UserInput; } - /// - /// 将历史记录应用到新的笔画集合 - /// - /// 时间机器历史记录数组 - /// 返回应用历史记录后的笔画集合 - /// - /// 创建一个临时画布,应用历史记录,然后返回画布中的笔画集合 - /// 只处理笔画历史,不处理图片元素历史 - /// private FrameworkElement RestoreEditedElement(UIElement current, string serializedState, InkCanvas canvas) { if (current is not FrameworkElement currentElement || string.IsNullOrWhiteSpace(serializedState) || canvas == null) @@ -523,28 +293,61 @@ private void InitializeElementTransformIfMissing(FrameworkElement element) private StrokeCollection ApplyHistoriesToNewStrokeCollection(TimeMachineHistory[] items) { - InkCanvas fakeInkCanv = new InkCanvas + var strokes = new StrokeCollection(); + var previousCommitType = _currentCommitType; + _currentCommitType = CommitReason.CodeInput; + try { InstallReplayedStrokes(items, strokes); } + finally { _currentCommitType = previousCommitType; } + return strokes; + } + + internal static void InstallReplayedStrokes(TimeMachineHistory[] items, StrokeCollection destination) => + new UInkHistorySnapshot(items).InstallStrokes(destination); + + // 翻页先按时间顺序归约,再一次安装最终成员,避免临时挂接已删除的媒体。 + internal static List InstallPageHistory(TimeMachineHistory[] items, InkCanvas canvas) + { + var history = new UInkHistorySnapshot(items); + history.InstallStrokes(canvas.Strokes); + var elements = new List(); + foreach (var pair in history.ElementTransforms) + pair.Key.SetCurrentValue(UIElement.RenderTransformProperty, pair.Value.CloneCurrentValue()); + foreach (var element in history.Visible()) { - Width = inkCanvas.ActualWidth, - Height = inkCanvas.ActualHeight, - EditingMode = InkCanvasEditingMode.None, - }; + canvas.Children.Add(element); + elements.Add(element); + } + return elements; + } - if (items != null && items.Length > 0) + private static string PluginStateAtHistoryEntry(TimeMachineHistory item) => item.CommitType switch + { + TimeMachineHistoryType.PluginStateChange => item.StrokeHasBeenCleared ? item.PluginStateBefore : item.PluginStateAfter, + TimeMachineHistoryType.PluginInkConversion => item.StrokeHasBeenCleared ? item.PluginStateAfter : item.PluginStateBefore, + _ => null + }; + + private List RestorePageHistory(TimeMachineHistory[] history) + { + // SecAgent 的序列化编辑会重建控件,沿用按时间顺序回放;其它页面批量安装最终成员。 + if (Array.Exists(history, item => item.CommitType == TimeMachineHistoryType.ElementEdit)) { - foreach (var timeMachineHistory in items) + var snapshot = new UInkHistorySnapshot(history); + foreach (var item in history) { - // 只处理笔画历史,不处理图片元素历史 - // 因为页面预览只需要显示笔画,图片元素会影响主画布 - if (timeMachineHistory.CommitType != TimeMachineHistoryType.ElementInsert && - timeMachineHistory.CommitType != TimeMachineHistoryType.PluginStateChange) - { - ApplyHistoryToCanvas(timeMachineHistory, fakeInkCanv); - } + if (item.CommitType == TimeMachineHistoryType.ElementInsert && !item.StrokeHasBeenCleared && + item.InsertedElement != null && snapshot.Owner(item.InsertedElement) < 0) continue; + ApplyHistoryToCanvas(item); } + + var attached = new List(inkCanvas.Children.Count); + foreach (UIElement element in inkCanvas.Children) attached.Add(element); + return attached; } - return fakeInkCanv.Strokes; + var elements = InstallPageHistory(history, inkCanvas); + foreach (var item in history) ApplyPluginUndoState(item.PluginId, PluginStateAtHistoryEntry(item)); + return elements; } /// @@ -557,7 +360,6 @@ private TimeMachineHistory[] FlattenPageHistory(TimeMachineHistory[] history) { if (history == null || history.Length == 0) return null; - var removed = CollectRemovedElementsFromHistory(history); var fakeInkCanv = new InkCanvas { Width = inkCanvas.ActualWidth > 0 ? inkCanvas.ActualWidth : 1920, @@ -565,18 +367,19 @@ private TimeMachineHistory[] FlattenPageHistory(TimeMachineHistory[] history) EditingMode = InkCanvasEditingMode.None, }; - var latestPluginStates = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var item in history) + var previous = _currentCommitType; + _currentCommitType = CommitReason.CodeInput; + try { - if (item.CommitType == TimeMachineHistoryType.PluginStateChange || - item.CommitType == TimeMachineHistoryType.PluginInkConversion) - { - if (!string.IsNullOrWhiteSpace(item.PluginId)) latestPluginStates[item.PluginId] = item; - if (item.CommitType == TimeMachineHistoryType.PluginStateChange) continue; - } - - ApplyHistoryToCanvas(item, fakeInkCanv, removed); + foreach (var child in InstallPageHistory(history, fakeInkCanv)) + RestoreReplayedElementLayout(child); } + finally { _currentCommitType = previous; } + + var latestPluginStates = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var item in history) + if (!string.IsNullOrWhiteSpace(item.PluginId) && PluginStateAtHistoryEntry(item) is string state) + latestPluginStates[item.PluginId] = state; var list = new List(); if (fakeInkCanv.Strokes.Count > 0) @@ -592,13 +395,8 @@ private TimeMachineHistory[] FlattenPageHistory(TimeMachineHistory[] history) fakeInkCanv.Children.Remove(child); } } - foreach (var item in latestPluginStates.Values) - { - var finalState = item.StrokeHasBeenCleared - ? item.PluginStateBefore - : item.PluginStateAfter; - list.Add(new TimeMachineHistory(item.PluginId, string.Empty, finalState)); - } + foreach (var state in latestPluginStates) + list.Add(new TimeMachineHistory(state.Key, string.Empty, state.Value)); return list.Count == 0 ? null : list.ToArray(); } diff --git a/Ink Canvas/MainWindow_cs/MW_Timer.cs b/Ink Canvas/MainWindow_cs/MW_Timer.cs index 6261d4152..5e5198903 100644 --- a/Ink Canvas/MainWindow_cs/MW_Timer.cs +++ b/Ink Canvas/MainWindow_cs/MW_Timer.cs @@ -339,18 +339,28 @@ public void UpdateAutoSaveStrokesTimer() /// 事件发送者 /// 事件参数 /// - /// 当定时器触发时,检查画布是否可见且有墨迹 + /// UInk 检查整本文档,其余格式检查画布是否可见且有墨迹 /// 如果满足条件,则调用SaveInkCanvasStrokes方法进行静默保存 /// private void AutoSaveStrokesTimer_Tick(object sender, EventArgs e) { try { - // 只有在画布可见且有墨迹时才保存 - if (inkCanvas.Visibility == Visibility.Visible && inkCanvas.Strokes.Count > 0) + // 定时抓取会结算手势,输入尚未结束时留待下一次 tick。 + if (Settings.Automation.IsSaveStrokesAsUInK && (_canvasGestureOwnsTouchInput || + _isBoardTouchpadGesture || _isBoardRoamingPointerDown || _boardRoamingContactIds?.Count > 0 || + dec?.Count > 0 || isMouseDown || + inkCanvas.AreAnyTouchesCapturedWithin || inkCanvas.AreAnyTouchesOver || inkCanvas.IsStylusCaptureWithin || + System.Windows.Input.Stylus.CurrentStylusDevice?.InAir == false || + System.Windows.Input.Mouse.LeftButton == System.Windows.Input.MouseButtonState.Pressed)) return; + // F25:UInk 按整本文档判空,包含离页墨迹和持久媒体。 + if (Settings.Automation.IsSaveStrokesAsUInK ? HasSavableDocumentContent() : + inkCanvas.Visibility == Visibility.Visible && inkCanvas.Strokes.Count > 0) { // 静默保存 - SaveInkCanvasStrokes(false, false); + var capture = Settings.Automation.IsSaveStrokesAsUInK ? Stopwatch.StartNew() : null; + SaveInkCanvasStrokes(false, false, timed: true); + if (capture != null) Debug.WriteLine($"UInk 定时 UI 采集 {capture.ElapsedMilliseconds} ms"); } } catch (Exception ex) diff --git a/Ink Canvas/MainWindow_cs/MW_UInk.cs b/Ink Canvas/MainWindow_cs/MW_UInk.cs index 4f0424e90..7104a3437 100644 --- a/Ink Canvas/MainWindow_cs/MW_UInk.cs +++ b/Ink Canvas/MainWindow_cs/MW_UInk.cs @@ -1,3 +1,4 @@ +using Ink_Canvas.Controls; using Ink_Canvas.Helpers; using Ink_Canvas.Properties; using Ink_Canvas.UInk; @@ -8,426 +9,1385 @@ using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; +using System.Windows.Controls.Primitives; using System.Windows.Ink; +using System.Windows.Media; using System.Windows.Media.Imaging; -using System.Windows.Threading; -using File = System.IO.File; namespace Ink_Canvas { /// - /// UInk 1.0 规范集成(保存/打开)。保存走两阶段提交(先 .uink.extra 后主文件); + /// UInk 规范集成(保存/打开)。保存走两阶段提交(先 .uink.extra 后主文件); /// 打开按 Workspace 类型恢复到对应模式(PPT/白板/屏幕批注),媒体资源经预算检查解压并拷贝到持久缓存目录。 /// public partial class MainWindow { // ==================== 保存 ==================== - /// 把当前 ICC 状态保存为 .uink(多页白板/PPT 幻灯片逐页、单页批注单页)。 - internal void SaveCurrentStateToUInk(string path, bool newNotice) + private sealed class UInkBoardSlot + { + internal string Guid = System.Guid.NewGuid().ToString(); + internal bool Imported; + internal UInkBackground Background; + internal UInkPageData Pending; + internal UInkCoordinateMap MediaCoordinates; + internal TimeMachineHistory[] SavedHistory; + } + + private readonly UInkBoardSlot[] _uinkBoard = new UInkBoardSlot[101]; + private readonly string[] _uinkWorkspaceIds = new string[3]; + internal sealed class UInkSession + { + private readonly string sourcePath; + internal readonly UInkPageProjection Projection; + + internal UInkSession(string path = null, UInkPageProjection projection = null) + { + sourcePath = path == null ? null : UInkSaveService.NormalizeTarget(path); + Projection = projection; + } + + internal string Save(UInkCaptureContext context, string target, bool timed, UInkShowArchive archive = null, Action committed = null) => + context.Save(target, timed, sourcePath, archive, committed); + } + + private readonly UInkSession[] _uinkSessions = new UInkSession[3]; + private UInkShowArchive _showArchive; + private string _uinkPptPath, _uinkPptName; + private readonly UInkSaveQueue _uinkSaves = new(); + private UInkMediaRestoreCache _boardResources, _preservedPptResources; + private readonly Dictionary _pptPageResources = new(); + private readonly Dictionary _pptPageGuids = new(); + private readonly Dictionary _pendingPptMedia = new(); + private readonly Dictionary _preservedPptGuids = new(); + private readonly List _preservedPptPages = new(); + private readonly Dictionary _quickPanelOwners = new(); + private readonly Dictionary> _pptElements = new(); + + private void RememberQuickPanelOwners() + { + if (PPTQuickPanel == null) return; + foreach (var element in _quickPanelOwners.Keys.Where(e => !PPTQuickPanel.SlideImageOwners.ContainsKey(e)).ToArray()) + _quickPanelOwners.Remove(element); + foreach (var pair in PPTQuickPanel.SlideImageOwners) + _quickPanelOwners.TryAdd(pair.Key, pair.Value == _currentSlideShowPosition ? _canvasSlide : + _observedShowKeys.GetValueOrDefault(pair.Value, PptPageKey.At(pair.Value, null))); + } + + // Quick Panel 的离页元素仍在画布上;导入后离页的元素则由放映存储单独持有。 + internal static Dictionary> CollectPptElements(IEnumerable children, + IReadOnlyDictionary owners, + Dictionary> detached, PptPageKey current) + { + var result = new Dictionary>(); + List For(PptPageKey key) + { + if (!result.TryGetValue(key, out var items)) result[key] = items = new(); + return items; + } + foreach (var child in children) + For(child is FrameworkElement fe && owners.TryGetValue(fe, out var key) ? key : current).Add(child); + foreach (var pair in detached) + if (pair.Key != current) For(pair.Key).AddRange(pair.Value); + return result; + } + + private void LeavePptUInkMedia(PptPageKey key) + { + if (!_pptElements.TryGetValue(key, out var elements)) return; + var attached = inkCanvas.Children.Cast().ToHashSet(); + elements.RemoveAll(e => !attached.Contains(e)); + foreach (var element in elements) inkCanvas.Children.Remove(element); + } + + private void EnterPptUInkMedia(PptPageKey key) + { + if (_pendingPptMedia.Remove(key, out var page)) + { + _ = RestoreUInkMediaForPage(page, _pptPageResources.GetValueOrDefault(key), null); + TrackPptElements(key, page); + } + else if (_pptElements.TryGetValue(key, out var elements)) + foreach (var element in elements) inkCanvas.Children.Add(element); + } + + private void TrackPptElements(PptPageKey key, UInkPageData page) + { + _pptElements[key] = page.History.OfType().SelectMany(g => g.Elements) + .OfType().ToList(); + } + + private void ResetPptUInkPages() + { + foreach (var elements in _pptElements.Values) + foreach (var element in elements) + { + if (element is CanvasMediaControl control) control.Shutdown(); + inkCanvas.Children.Remove(element); + } + _pptElements.Clear(); + _pendingPptMedia.Clear(); + _preservedPptPages.Clear(); + _preservedPptGuids.Clear(); + _pptPageGuids.Clear(); + _uinkWorkspaceIds[(int)UInkWorkspaceType.Presentation] = null; + _quickPanelOwners.Clear(); + foreach (var lease in _pptPageResources.Values) lease.Dispose(); + _pptPageResources.Clear(); + _preservedPptResources?.Dispose(); + _preservedPptResources = null; + } + + private UInkWorkspaceType ActiveUInkWorkspace => currentMode != 0 ? UInkWorkspaceType.Whiteboard : + IsInPPTPresentationMode && _pptManager?.IsConnected == true ? UInkWorkspaceType.Presentation : UInkWorkspaceType.ScreenAnnotation; + + private UInkSession CurrentUInkSession(UInkSession opened = null, UInkWorkspaceType? workspace = null) + { + var type = workspace ?? ActiveUInkWorkspace; + if (type == UInkWorkspaceType.Presentation) + { + string path = workspace.HasValue ? _presentationFullNameSnapshot : + _pptManager is PPTAgentLinkManager agent ? agent.CurrentState.PresentationFullName : _pptManager.GetPresentationPath(); + string name = workspace.HasValue ? _presentationNameSnapshot : _pptManager.GetPresentationName(); + // 有些宿主只在开始放映时给出完整路径;同场且名称仍吻合时可沿用。 + if (!workspace.HasValue && string.IsNullOrWhiteSpace(path) && _canvasSlide != default && + !string.IsNullOrWhiteSpace(name) && string.Equals(name, _presentationNameSnapshot, StringComparison.OrdinalIgnoreCase)) + path = _presentationFullNameSnapshot; + if (!string.Equals(path, _uinkPptPath, StringComparison.OrdinalIgnoreCase) || name != _uinkPptName) + { + _uinkPptPath = path; + _uinkPptName = name; + _uinkSessions[(int)type] = null; + } + } + if (opened != null) _uinkSessions[(int)type] = opened; + return _uinkSessions[(int)type] ??= new UInkSession(); + } + + internal async Task SaveCurrentStateToUInk(string path, bool newNotice, bool timed = false, bool upload = true, + int? pptArchiveSlideCount = null) { try { - var devices = UInkIccMapper.BuildDisplayDevices(); - var workspaces = new List(); - var pages = new List(); - - bool isPPT = IsInPPTPresentationMode && _pptManager?.IsConnected == true; - string wsGuid = Guid.NewGuid().ToString(); - UInkWorkspace ws = currentMode != 0 - ? new UInkWorkspace { Guid = wsGuid, WorkspaceType = (int)UInkWorkspaceType.Whiteboard, Name = "白板" } - : isPPT - ? new UInkWorkspace { Guid = wsGuid, WorkspaceType = (int)UInkWorkspaceType.Presentation, Name = "演示" } - : new UInkWorkspace { Guid = wsGuid, WorkspaceType = (int)UInkWorkspaceType.ScreenAnnotation, Name = "屏幕批注" }; - UInkIccMapper.EnsureWorkspace(workspaces, ws); - string deviceGuid = devices.Count > 0 ? devices[0].Guid : ""; - - // 当前页媒体(图片/PDF/音视频) - var currentMedia = new List<(UInkMedia media, string sourceFile)>(); - CollectMediaToUInk(currentMedia); - - if (isPPT) - { - int totalSlides = _pptManager.SlidesCount; - int currentSlide = _pptManager.GetCurrentSlideNumber(); - for (int i = 1; i <= totalSlides; i++) + bool archiving = pptArchiveSlideCount.HasValue; + var session = CurrentUInkSession(workspace: archiving ? UInkWorkspaceType.Presentation : null); + // 放映结束可能早于恢复续体,入队时固定状态,不借用下一场的权限。 + var archive = archiving ? (_showArchive == null || _showArchive.State == UInkShowArchive.RestoreState.Pending || + !ReferenceEquals(_showArchive.Projection, session.Projection) + ? new UInkShowArchive() : _showArchive) : null; + path = Path.GetFullPath(path); + var context = pptArchiveSlideCount.HasValue ? CaptureUInkWorkspace(pptArchiveSlideCount) : CaptureUInk(); + string actual = null; + // Agent 宿主可能只报告同名演示,无法确认文档身份时保留每次定时请求。 + bool show = !archiving && ActiveUInkWorkspace == UInkWorkspaceType.Presentation; + bool coalesce = timed && (!show || (!string.IsNullOrWhiteSpace(_uinkPptPath) && Path.IsPathFullyQualified(_uinkPptPath))); + object document = show ? (session, _showGeneration) : session; + await _uinkSaves.Enqueue(document, path, coalesce, () => + { + try { actual = session.Save(context, path, timed, archive, upload ? UploadHelper.QueueUInkSnapshot : null); } + catch (Exception ex) { - var strokes = _singlePPTInkManager?.LoadSlideStrokes(i); - if ((strokes == null || strokes.Count == 0) && i == currentSlide) - strokes = inkCanvas.Strokes.Clone(); - pages.Add(new UInkPageInput - { - Canvas = UInkIccMapper.BuildCanvas(wsGuid, deviceGuid, - Guid.NewGuid().ToString(), (uint)(i - 1), (uint)i, TryGetSlideId(i), null), - Strokes = strokes ?? new StrokeCollection(), - Media = i == currentSlide ? currentMedia.Select(x => x.media).ToList() : new List(), - }); + // Dispatcher 可能正在退出,失败结果在后台落日志。 + LogHelper.WriteLogToFile($"UInk 保存失败 | {ex}", LogHelper.LogType.Error); + throw; } + }, context.ReleaseResources); + if (actual != null) + LogHelper.WriteLogToFile($"[UInk] 保存完成: {actual}, {context.Pages.Count} 页", LogHelper.LogType.Info); + int byPosition = context.Workspace.WorkspaceType == (int)UInkWorkspaceType.Presentation + ? context.Pages.Count(page => page.Canvas.Binding == 1 && page.Canvas.PageKind != 1 && page.Canvas.PageState != 1) : 0; + if (actual != null && (byPosition > 0 || newNotice || (!timed && context.DroppedMediaCount != 0) || + !string.Equals(actual, path, StringComparison.OrdinalIgnoreCase))) + { + string message = string.Format(archiving && !string.Equals(actual, path, StringComparison.OrdinalIgnoreCase) + ? UInkText("PptArchiveCopy") : MainWindowStrings.Main_Strokes_SaveUInkSuccess, actual); + if (context.DroppedMediaCount != 0) + message += Environment.NewLine + string.Format(UInkText("MediaDropped"), context.DroppedMediaCount); + if (byPosition > 0) message += Environment.NewLine + string.Format(UInkText("PptByPosition"), byPosition); + ShowNotification(message); } - else if (currentMode != 0 && WhiteboardTotalCount > 1) + } + catch (Exception ex) { ReportUInkSaveFailure(ex); } + } + + private void ReportUInkSaveFailure(Exception ex) + { + ShowNotification(MainWindowStrings.Main_Strokes_SaveUInkFailed); + LogHelper.WriteLogToFile($"UInk 保存失败 | {ex}", LogHelper.LogType.Error); + } + + internal bool HasSavableDocumentContent() + { + bool HasInk(IEnumerable strokes) => strokes != null && + strokes.Any(s => !s.ContainsPropertyData(InkFadeManager.LaserRenderModeGuid)); + if (HasInk(inkCanvas.Strokes) || inkCanvas.Children.Cast().Any(IsSavableUInkElement)) return true; + if (currentMode != 0) + { + for (int i = 1; i <= WhiteboardTotalCount; i++) { - for (int i = 1; i <= WhiteboardTotalCount; i++) + if (i == CurrentWhiteboardIndex) continue; + var pending = GetUInkSlot(i)?.Pending; + // 索引页只作候选;后台解码后再次判空,不能为了定时器提前展开整本白板。 + if (pending != null) { - var strokes = TimeMachineHistories[i] != null - ? ApplyHistoriesToNewStrokeCollection(TimeMachineHistories[i]) - : new StrokeCollection(); - if (strokes.Count == 0 && i == CurrentWhiteboardIndex) - strokes = inkCanvas.Strokes.Clone(); - pages.Add(new UInkPageInput - { - Canvas = UInkIccMapper.BuildCanvas(wsGuid, deviceGuid, - Guid.NewGuid().ToString(), (uint)(i - 1), (uint)i, null, null), - Strokes = strokes, - Media = i == CurrentWhiteboardIndex ? currentMedia.Select(x => x.media).ToList() : new List(), - }); + if (pending.HasIndexedContent) return true; + continue; } + var history = new UInkHistorySnapshot(TimeMachineHistories[i]); + if (HasInk(history.Visible()) || history.Visible().Any(IsSavableUInkElement)) return true; } - else + } + else if (IsInPPTPresentationMode && _pptManager?.IsConnected == true) + { + if (_unclaimedArchivePages.Count > 0 || _preservedPptPages.Any(page => page.HasIndexedContent) || _pendingPptMedia.Count != 0 || + _pptElements.Any(pair => pair.Key != _canvasSlide && pair.Value.Count != 0)) return true; + foreach (var key in _memoryStreams.InkedKeys()) + if (key != _canvasSlide && HasInk(PptSlideStorage.Decode(_memoryStreams.Read(key)))) return true; + } + return false; + } + + private UInkCaptureContext CaptureUInk() => CaptureUInkWorkspace(null); + + private UInkCaptureContext CaptureUInkWorkspace(int? pptArchiveSlideCount) + { + EndBoardTouchpadGesture(); + if (_canvasGestureOwnsTouchInput) ResetCanvasGestureInput(); + EndBoardRoaming(); + bool board = currentMode != 0 && !pptArchiveSlideCount.HasValue; + bool ppt = pptArchiveSlideCount.HasValue || (!board && IsInPPTPresentationMode && _pptManager?.IsConnected == true); + // 结束放映时白板可能仍开启,放映画布已备份在历史槽 0。 + bool archiveFromBoard = pptArchiveSlideCount.HasValue && currentMode != 0; + var liveHistory = archiveFromBoard ? TimeMachineHistories[0] : timeMachine.GetAppliedHistorySnapshot(); + var type = board ? UInkWorkspaceType.Whiteboard : ppt ? UInkWorkspaceType.Presentation : UInkWorkspaceType.ScreenAnnotation; + int total = pptArchiveSlideCount ?? (board ? WhiteboardTotalCount : ppt ? Math.Max(1, _pptManager.SlidesCount) : 1); + int current = board ? CurrentWhiteboardIndex : 1; + Dictionary> pptElements = null; + if (ppt) + { + RememberQuickPanelOwners(); + if (!pptArchiveSlideCount.HasValue) ReadShowSlides(); + if (_showSlides.Count > 0) total = _showSlides.Count; + current = _canvasSlide.SlideId is int id ? _showSlides.Resolve(id) ?? 0 : _canvasSlide.Position; + var children = archiveFromBoard ? new UInkHistorySnapshot(liveHistory).Visible() : + inkCanvas.Children.Cast(); + pptElements = CollectPptElements(children, _quickPanelOwners, _pptElements, _canvasSlide); + } + var dpi = VisualTreeHelper.GetDpi(inkCanvas); + string workspaceId = _uinkWorkspaceIds[(int)type] ??= Guid.NewGuid().ToString(); + var context = new UInkCaptureContext + { + Devices = UInkIccMapper.BuildDisplayDevices(), DpiX = dpi.DpiScaleX, DpiY = dpi.DpiScaleY, + Workspace = new UInkWorkspace { Guid = workspaceId, WorkspaceType = (int)type, + HostId = ppt ? PptHostHint() : null, + Name = board ? "白板" : ppt ? "演示" : "屏幕批注", CurrentPageIndex = (uint)Math.Max(0, current - 1) } + }; + string device = context.Devices.FirstOrDefault()?.Guid ?? ""; + var occupied = ppt ? _memoryStreams.InkedKeys().Concat(pptElements.Where(pair => pair.Value.Any(IsPersistentUInkElement)) + .Select(pair => pair.Key)).Concat(_pendingPptMedia.Keys) : null; + if (ppt) + { + occupied = occupied.Concat(_unclaimedArchivePages.Select(i => PptPageKey.At(i, null))); + if (archiveFromBoard || inkCanvas.Strokes.Count > 0) occupied = occupied.Append(_canvasSlide); + } + var pptKeys = ppt ? _showSlides.CaptureOrder(total, occupied, i => ExportSlideKey(_showSlides, i)) : null; + for (int i = 1; i <= (ppt ? pptKeys.Count : total); i++) + { + var key = ppt ? pptKeys[i - 1] : default; + bool livePage = ppt ? key == _canvasSlide : i == current; + var slot = board ? GetUInkSlot(i) ?? (_uinkBoard[i] = new UInkBoardSlot { SavedHistory = TimeMachineHistories[i] }) : null; + string guid; + if (!ppt) guid = slot?.Guid ?? Guid.NewGuid().ToString(); + else if (!_pptPageGuids.TryGetValue(key, out guid)) + _pptPageGuids[key] = guid = Guid.NewGuid().ToString(); + var page = new UInkPageInput + { + Canvas = ppt ? PptSlideMap.CaptureCanvas(workspaceId, device, guid, key, i, total) + : UInkIccMapper.BuildCanvas(workspaceId, device, guid, (uint)(i - 1), (uint)i, null, null) + }; + if (ppt) { - pages.Add(new UInkPageInput + if (livePage) context.CurrentPptCanvas = page.Canvas; + // 不完整的 ID 表不能证明页已删除;被位置页挤出的有效 ID 也仍属正常页。 + if (i > total && key.SlideId is int knownId && (!_confirmedSlides.Complete || + _idsSinceConfirmedMap.Contains(knownId) || _confirmedSlides.Resolve(knownId) != null || + _showSlides.Resolve(knownId) != null)) + page.Canvas.PageState = null; + } + context.Pages.Add(page); + if (ppt && !livePage && _pendingPptMedia.TryGetValue(key, out var pendingMedia)) + { + context.CapturePendingPage(page, pendingMedia, + UInkMediaMapper.PageCoordinates(pendingMedia.Canvas, dpi.DpiScaleX, dpi.DpiScaleY)); + // 导入后从未显示的媒体和新插入的 Quick Panel 图片可以共存。 + page.PendingMediaOnly = true; + CaptureUInkPage(page, null, PptSlideStorage.Decode(ReadExportInk(key)), pptElements.GetValueOrDefault(key)); + continue; + } + if (board) + { + var background = i == current ? CurrentUInkBackground(slot) : slot.Background ?? DefaultUInkBackground(); + page.Canvas.Background = new UInkBackground { Pattern = background.Pattern, Color = new UInkColor { - Canvas = UInkIccMapper.BuildCanvas(wsGuid, deviceGuid, - Guid.NewGuid().ToString(), 0, 1, null, UInkIccMapper.IdentityViewport()), - Strokes = inkCanvas.Strokes.Clone(), - Media = currentMedia.Select(x => x.media).ToList(), - }); + Fallback = background.Color.Fallback, Space = background.Color.Space, + Components = (float[])background.Color.Components?.Clone() + } }; + } + if (i != current && slot?.Pending != null) + { + context.CapturePendingPage(page, slot.Pending, slot.MediaCoordinates ?? + UInkMediaMapper.PageCoordinates(slot.Pending.Canvas, dpi.DpiScaleX, dpi.DpiScaleY)); + continue; } - var doc = UInkIccMapper.BuildDocument( - UInkIccMapper.NewFileGuid(), devices, workspaces, pages, - (ulong)DateTimeOffset.UtcNow.ToUnixTimeSeconds()); + var live = livePage && !archiveFromBoard ? inkCanvas.Strokes : + livePage && liveHistory != null ? null : ppt ? PptSlideStorage.Decode(ReadExportInk(key)) : null; + CaptureUInkPage(page, livePage ? liveHistory : board ? TimeMachineHistories[i] : null, + live, ppt ? (IEnumerable)pptElements.GetValueOrDefault(key) ?? Array.Empty() : + livePage ? inkCanvas.Children.Cast() : null); + } + if (ppt) + { + var identities = context.Pages.Select(page => page.Canvas).ToList(); + foreach (var saved in _preservedPptPages) + { + context.CapturePreservedPptPage(saved, device); + var canvas = context.Pages[^1].Canvas; + if (_preservedPptGuids.TryGetValue(saved, out var guid)) canvas.PageGuid = guid; + identities.Add(canvas); + } + for (int i = 0; i < pptKeys.Count; i++) + context.UsePageResources(context.Pages[i], _pptPageResources.GetValueOrDefault(pptKeys[i])); + context.Resources = _preservedPptResources?.Retain(); + context.FinalizePptLayout(); + // CANVAS-1:发生冲突后分配的新身份在后续完整保存中继续使用。 + for (int i = 0; i < pptKeys.Count; i++) _pptPageGuids[pptKeys[i]] = identities[i].PageGuid; + for (int i = 0; i < _preservedPptPages.Count; i++) + _preservedPptGuids[_preservedPptPages[i]] = identities[pptKeys.Count + i].PageGuid; + } + if (board) context.Resources = _boardResources?.Retain(); + return context; + } - // 资源集(entryPath, sourceFile) - var resources = new List<(string, string)>(); - foreach (var (m, src) in currentMedia) - resources.Add((m.Path, src)); + internal static void CaptureUInkPage(UInkPageInput page, TimeMachineHistory[] entries, StrokeCollection live, + IEnumerable liveElements) + { + var history = new UInkHistorySnapshot(entries); + history.CaptureStrokes(page, live); + foreach (var child in liveElements ?? history.Visible()) + if (IsPersistentUInkElement(child)) + page.Elements.Add(CaptureUInkElement((FrameworkElement)child, history.Owner(child), + liveElements != null ? null : history.ElementTransforms.GetValueOrDefault(child))); + } - UInkSaveService.SaveFull(doc, path, resources); - LogHelper.WriteLogToFile( - $"[UInk] 保存完成: {path}, {pages.Count} 页, 资源 {resources.Count} 个, 媒体 {currentMedia.Count} 个", - LogHelper.LogType.Info); + internal static StrokeCollection SnapshotWhiteboardPageStrokes(int pageIndex, int currentPageIndex, + StrokeCollection live, TimeMachineHistory[] history) + { + var page = new UInkPageInput(); + CaptureUInkPage(page, history, pageIndex == currentPageIndex ? live : null, Array.Empty()); + return page.Strokes; + } - if (newNotice) + internal List CollectLegacyWhiteboardStrokes() + { + var pages = new List(WhiteboardTotalCount); + for (int i = 1; i <= WhiteboardTotalCount; i++) + { + if (i == CurrentWhiteboardIndex) pages.Add(inkCanvas.Strokes.Clone()); + else if (GetUInkSlot(i)?.Pending is UInkPageData page) { - Task.Delay(100).ContinueWith(t => + // 独立解码,不占用首次翻页的安装槽。 + if (page.IsMaterialized) pages.Add(page.FinalStrokes.Clone()); + else { - Dispatcher.Invoke(() => - { - ShowNotification(string.Format(MainWindowStrings.Main_Strokes_SaveUInkSuccess, path)); - }); - }); + var decoded = new UInkPageData(); + page.Materialize(decoded); + pages.Add(decoded.FinalStrokes); + } } + else pages.Add(new UInkHistorySnapshot(TimeMachineHistories[i]).CloneLegacyStrokes()); } - catch (Exception ex) - { - ShowNotification(MainWindowStrings.Main_Strokes_SaveUInkFailed); - LogHelper.WriteLogToFile($"UInk 保存失败 | {ex}", LogHelper.LogType.Error); - } + return pages; } - /// 遍历 inkCanvas 子元素,收集文件型媒体为 UInkMedia + 源文件(剪贴板/内存位图无源文件则跳过)。 - private void CollectMediaToUInk(List<(UInkMedia media, string sourceFile)> result) + private static bool IsPersistentUInkElement(UIElement child) => + child is PdfEmbeddedView or CanvasMediaControl or MediaElement or UInkMissingMedia || + child is Image img && !Equals(img.Tag, VideoPresenterLiveFrameTag); + + private static bool IsSavableUInkElement(UIElement child) => IsPersistentUInkElement(child) && + child is not UInkMissingMedia and not UInkBitmapImage { Source: null } and + not ContentControl { Content: UInkMissingMedia }; + + private static UInkCapturedElement CaptureUInkElement(FrameworkElement child, int owner, Transform editedTransform) { - if (inkCanvas == null) return; - var elements = new List(); - CollectCanvasElementsMetadata(elements); + var info = new CanvasElementInfo + { + Width = double.IsNaN(child.Width) ? child.ActualWidth : child.Width, + Height = double.IsNaN(child.Height) ? child.ActualHeight : child.Height, + Left = InkCanvas.GetLeft(child), Top = InkCanvas.GetTop(child) + }; + if (double.IsNaN(info.Left)) info.Left = 0; + if (double.IsNaN(info.Top)) info.Top = 0; + var captured = new UInkCapturedElement { Info = info, Owner = owner, Opacity = child.Opacity, + Origin = child.RenderTransformOrigin, Transform = (editedTransform ?? child.RenderTransform)?.Value ?? Matrix.Identity }; + bool hasLayoutTransform = child.LayoutTransform != null && !child.LayoutTransform.Value.IsIdentity; + bool bitmapLayout = child is Image { Source: BitmapSource } image && + (image.Stretch != Stretch.Fill || image.Clip != null); + if (hasLayoutTransform || bitmapLayout) + { + // 布局变换和对齐都会改变视觉原点,已排列的元素直接记录到画布的仿射映射。 + if (editedTransform == null || editedTransform.Value == child.RenderTransform.Value) + captured.LayoutMatrix = CaptureUInkLayoutMatrix(child, bitmapLayout && !hasLayoutTransform); + captured.LayoutDegraded = hasLayoutTransform && !captured.LayoutMatrix.HasValue; + } - var used = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var e in elements) + if (child.Tag is UInkWaitingMedia waiting) { - if (string.IsNullOrEmpty(e.SourcePath) || !File.Exists(e.SourcePath)) continue; - var entryPath = MakeUniqueEntryPath(e.SourcePath, used); + captured.PendingMedia = waiting.Media; + captured.LocalUnits = waiting.Coordinates; + if (child is CanvasMediaControl && waiting.Media.Width is float width && waiting.Media.Height is float height) + { + var preview = waiting.Coordinates.MediaBoxToDip(width, height); + if (UInkMediaMapper.TryGetNativeVideoLayout(waiting.Media, preview, out _, out var inset)) + captured.VideoPreview = new Rect(inset, preview); + } + return captured; + } + if (child is UInkMissingMedia or ContentControl { Content: UInkMissingMedia }) + return captured; - var media = new UInkMedia + if (child is Image img) + { + info.Type = "Image"; + captured.Stretch = img.Stretch; + if (img is UInkBitmapImage mapped) { - Path = entryPath, - MimeType = UInkExtraArchive.MimeForPath(e.SourcePath), - Width = e.Width > 0 ? (float)e.Width : 800f, - Height = e.Height > 0 ? (float)e.Height : 520f, - Transform = new[] { 1f, 0f, 0f, 1f, (float)e.Left, (float)e.Top }, - Opacity = 1f, - }; - if (string.Equals(e.Type, "Pdf", StringComparison.OrdinalIgnoreCase)) + info.SourcePath = mapped.SourcePath; + captured.BitmapStamp = mapped.SourceStamp; + } + else if (img.Source is BitmapImage { UriSource: { IsAbsoluteUri: true, IsFile: true } uri, + Rotation: Rotation.Rotate0 } file && file.SourceRect.IsEmpty && + file.DecodePixelWidth == 0 && file.DecodePixelHeight == 0) + info.SourcePath = uri.LocalPath; + if (img.Source is BitmapSource bitmap) + { + captured.Bitmap = bitmap.IsFrozen ? bitmap : bitmap.CloneCurrentValue(); + if (!captured.Bitmap.IsFrozen) + { + if (captured.Bitmap.CanFreeze) captured.Bitmap.Freeze(); + else + { + captured.Bitmap = null; + info.SourcePath = null; + } + } + if (bitmapLayout) CaptureNativeBitmapLayout(img, bitmap, captured); + } + } + else if (child is PdfEmbeddedView pdf) + { + info.Type = "Pdf"; + info.SourcePath = pdf.PdfPath; + info.PdfCurrentPage = (int)pdf.CurrentPageIndex; + info.PdfPageCount = (int)pdf.PageCount; + captured.Stretch = Stretch.Uniform; + if (pdf.Tag is UInkPdfState pending) + { + captured.Stretch = UInkMediaMapper.StretchFromFit(pending.Media.Fit); + // PDF 初始化期间仍可从已验证的缓存路径保存原字节。 + info.SourcePath ??= pending.Info.SourcePath; + if (pdf.PdfPath == null) + { + info.PdfCurrentPage = pending.Info.PdfCurrentPage; + info.PdfPageCount = pending.Info.PdfPageCount; + } + } + } + else + { + info.Type = "Media"; + TryGetMediaSourcePath(child, out string file); + info.SourcePath = file; + if (child is CanvasMediaControl control) { - media.PageCount = e.PdfPageCount.HasValue ? (uint?)e.PdfPageCount.Value : null; - media.PageIndex = e.PdfCurrentPage.HasValue ? (uint?)e.PdfCurrentPage.Value : null; + captured.IgnoreFit = true; + if (file != null && UInkMediaMapper.IsVideo(UInkExtraArchive.MimeForPath(file))) + CaptureNativeVideoPreview(control, captured); + info.MediaPositionSeconds = control.GetPlaybackPositionOrNull()?.TotalSeconds; + info.MediaSpeedRatio = control.PlaybackRate; + info.MediaVolume = control.VolumeLevel; + if (control.Tag is UInkPlaybackState state) + { + var imported = state.Media; + captured.Autoplay = imported.Autoplay; + captured.Loop = imported.Loop; + if (!state.SettingsApplied) + { + info.MediaPositionSeconds = imported.StartTime; + info.MediaSpeedRatio = imported.PlaybackRate; + info.MediaVolume = imported.Volume; + } + else if (control.MediaPlayer.Source == null) info.MediaPositionSeconds = imported.StartTime; + else info.MediaSpeedRatio = control.MediaPlayer.SpeedRatio; + } } - else if (string.Equals(e.Type, "Media", StringComparison.OrdinalIgnoreCase)) + else if (child is MediaElement media) { - media.Volume = e.MediaVolume.HasValue ? (float)e.MediaVolume.Value : 1f; - media.StartTime = e.MediaPositionSeconds ?? 0.0; - media.PlaybackRate = e.MediaSpeedRatio.HasValue ? (float)e.MediaSpeedRatio.Value : 1f; + captured.Stretch = media.Stretch; + info.MediaPositionSeconds = media.Position.TotalSeconds; + info.MediaSpeedRatio = media.SpeedRatio; + info.MediaVolume = media.Volume; + captured.Autoplay = media.LoadedBehavior == MediaState.Play; } - result.Add((media, e.SourcePath)); } + return captured; } - private static string MakeUniqueEntryPath(string sourceFile, HashSet used) + private static void CaptureNativeVideoPreview(CanvasMediaControl control, UInkCapturedElement captured) { - string name = Path.GetFileName(sourceFile); - if (string.IsNullOrWhiteSpace(name)) name = "resource"; - foreach (var c in Path.GetInvalidFileNameChars()) name = name.Replace(c, '_'); - string candidate = "media/" + name; - int n = 1; - while (!used.Add(candidate)) - candidate = "media/" + (n++) + "_" + name; - return candidate; + var info = captured.Info; + if (!(info.Width > 0 && info.Height > 0) || control.FindName("PreviewHost") is not FrameworkElement preview) + return; + + // 离页控件没有布局父级时,使用原生控件自身的 Measure/Arrange 得到控制栏占用后的预览框。 + if (!control.IsArrangeValid) + { + if (VisualTreeHelper.GetParent(control) == null) + { + var size = new Size(info.Width, info.Height); + control.Measure(size); + control.Arrange(new Rect(size)); + } + else control.UpdateLayout(); + } + if (preview.RenderSize.Width > 0 && preview.RenderSize.Height > 0) + captured.VideoPreview = new Rect(preview.TranslatePoint(new Point(), control), preview.RenderSize); } - /// best-effort 取 PowerPoint COM SlideID(失败返回 null,省略 slideId)。 - private int? TryGetSlideId(int slideIndex) + private static Matrix? CaptureUInkLayoutMatrix(FrameworkElement element, bool useDetachedBitmapLayout) { - try + if (!element.IsArrangeValid || element.RenderSize.Width <= 0 || element.RenderSize.Height <= 0) return null; + var visualParent = VisualTreeHelper.GetParent(element); + for (var parent = visualParent; parent != null; parent = VisualTreeHelper.GetParent(parent)) { - if (pptApplication == null) return null; - var presentation = pptApplication.SlideShowWindows?[1]?.Presentation; - if (presentation == null || slideIndex < 1 || slideIndex > presentation.Slides.Count) return null; - return presentation.Slides[slideIndex].SlideID; + if (parent is not InkCanvas canvas) continue; + var transform = element.TransformToAncestor(canvas); + if (transform.TryTransform(new Point(), out var o) && + transform.TryTransform(new Point(1, 0), out var x) && + transform.TryTransform(new Point(0, 1), out var y)) + return new Matrix(x.X - o.X, x.Y - o.Y, y.X - o.X, y.Y - o.Y, o.X, o.Y); + break; } - catch (Exception) + if (useDetachedBitmapLayout && visualParent == null) { - return null; + // 白板离页保留上次排列的视觉偏移;普通位图无需 LayoutTransform 的布局补偿。 + var offset = VisualTreeHelper.GetOffset(element); + double x = element.RenderTransformOrigin.X * element.RenderSize.Width; + double y = element.RenderTransformOrigin.Y * element.RenderSize.Height; + var matrix = Matrix.Identity; + matrix.Translate(-x, -y); + matrix.Append(element.RenderTransform.Value); + matrix.Translate(x + offset.X, y + offset.Y); + return matrix; } + return null; + } + + private static void CaptureNativeBitmapLayout(Image image, BitmapSource bitmap, UInkCapturedElement captured) + { + var info = captured.Info; + if (!(bitmap.Width > 0 && bitmap.Height > 0 && info.Width > 0 && info.Height > 0)) return; + var frame = new Rect(0, 0, info.Width, info.Height); + // MEDIA-1/3:写实际可见的 DIP 框。原生布局有裁切时,后台将可见区域编码为独立 PNG。 + bool arranged = captured.LayoutMatrix.HasValue; + var placed = arranged ? new Rect(image.RenderSize) : + UInkMediaMapper.FitBox(frame.Size, new Size(bitmap.Width, bitmap.Height), image.Stretch); + var drawing = new Rect(placed.Size); + var visible = drawing; + if (arranged) + { + if (LayoutInformation.GetLayoutClip(image) is Geometry layoutClip) visible.Intersect(layoutClip.Bounds); + } + else visible.Intersect(new Rect(-placed.X, -placed.Y, frame.Width, frame.Height)); + if (image.Clip is RectangleGeometry clip && clip.RadiusX == 0 && clip.RadiusY == 0 && + clip.Transform.Value.IsIdentity) visible.Intersect(clip.Rect); + if (visible.IsEmpty || visible.Width == 0 || visible.Height == 0) return; + if (visible != drawing) + { + double sx = bitmap.PixelWidth / drawing.Width, sy = bitmap.PixelHeight / drawing.Height; + captured.BitmapRegion = new Rect((visible.X - drawing.X) * sx, (visible.Y - drawing.Y) * sy, + visible.Width * sx, visible.Height * sy); + info.SourcePath = null; + } + else if (placed == frame && image.Stretch != Stretch.None && bitmap.DpiX == bitmap.DpiY) + return; + + var matrix = Matrix.Identity; + matrix.Translate(visible.X, visible.Y); + matrix.Append(captured.LayoutMatrix ?? UInkMediaMapper.ElementMatrix(captured, drawing.Size)); + // 无排列结果时,对齐偏移属于布局位置,在 RenderTransform 之后应用。 + if (!arranged) matrix.Translate(placed.X, placed.Y); + captured.LayoutMatrix = matrix; + captured.Stretch = Stretch.Fill; + info.Width = visible.Width; + info.Height = visible.Height; + } + + private string PptHostHint() + { + if (string.IsNullOrEmpty(_presentationFullNameSnapshot) && string.IsNullOrEmpty(_presentationNameSnapshot)) + return null; + int count = _showSlides.Count > 0 ? _showSlides.Count : _presentationSlideCountSnapshot; + return $"ICC-PPT:{_presentationFullNameSnapshot}|{_presentationNameSnapshot}|{count}"; + } + + // 页数变化可能仅因删页。弱提示相等也必须继续向当前放映查询 SlideID。 + internal static bool DifferentPptSource(string source, string current) + { + if (source?.StartsWith("ICC-PPT:", StringComparison.Ordinal) != true || current == null) return false; + int end = source.LastIndexOf('|'), currentEnd = current.LastIndexOf('|'); + return end > 0 && currentEnd > 0 && !string.Equals(source.Substring(0, end), + current.Substring(0, currentEnd), StringComparison.OrdinalIgnoreCase); } // ==================== 打开 ==================== - /// 打开 .uink 主文件(含 .uink.extra 资源包)。 - private void OpenUInkFile(string path) + // 请求编号决定谁可以安装;媒体回调只观察已经安装的文档代次。 + private int _uinkOpenGeneration; + private int _uinkOpenRequest; + private int BeginCanvasOpen() => ++_uinkOpenRequest; + + private void ReleaseLegacyReplacedDocument(UInkWorkspaceType type) { - if (TryBlockFrozenPageMutation("打开 UInk 文件")) return; - try + _uinkSessions[(int)type] = null; + _uinkWorkspaceIds[(int)type] = null; + if (type == UInkWorkspaceType.Presentation) ResetPptUInkPages(); + if (type != UInkWorkspaceType.Whiteboard) return; + Array.Clear(_uinkBoard, 0, _uinkBoard.Length); + _boardResources?.Dispose(); + _boardResources = null; + } + + private const int UInkWhiteboardLimit = 99; + private static readonly Dictionary UInkMediaCacheLeases = new(StringComparer.OrdinalIgnoreCase); + + private static void RetainUInkMediaCache(string cacheDirectory) + { + cacheDirectory = Path.GetFullPath(cacheDirectory); + lock (UInkMediaCacheLeases) { - var doc = UInkReader.Load(path); - if (doc == null) - { - LogHelper.WriteLogToFile($"[UInk] 打开失败:文件头校验不通过 {path}", LogHelper.LogType.Warning); - ShowNotification(MainWindowStrings.Main_Strokes_UInkInvalid); - return; - } - LogHelper.WriteLogToFile( - $"[UInk] 开始打开: {path}, 画布 {doc.Canvases?.Count ?? 0} 个, 资源扩展={(doc.HeaderExtension != null)}", - LogHelper.LogType.Info); + if (UInkMediaCacheLeases.ContainsKey(cacheDirectory)) return; + Directory.CreateDirectory(cacheDirectory); + // 控件、历史和后台保存可共用缓存路径,租约随进程退出由系统关闭。 + DelAutoSavedFiles.WithUInkMediaCacheGate(() => + UInkMediaCacheLeases.Add(cacheDirectory, DelAutoSavedFiles.OpenUInkMediaCacheLease(cacheDirectory, exclusive: false))); + } + } - // 资源包:预算检查 + 安全解压到临时目录(媒体随后拷贝到持久缓存) - Dictionary extraMap = null; - string extractDir = null; - string extraPath = path + ".extra"; - if (File.Exists(extraPath)) - { - extractDir = Path.Combine(Path.GetTempPath(), "UInkOpen_" + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(extractDir); - extraMap = UInkExtraArchive.ExtractWithBudget(extraPath, extractDir); - if (extraMap == null) - LogHelper.WriteLogToFile($"UInk 资源包预算/安全校验失败,仅加载墨迹: {extraPath}", LogHelper.LogType.Warning); - } + private async Task OpenUInkFromEntryAsync(string path) + { + if (TryBlockFrozenPageMutation("打开 UInk 文件")) return false; + WatchUInkResourcesOnClose(); + var opening = OpenUInkFileAsync(path); + int generation = _uinkOpenRequest; + string notice = await opening; + if (generation != _uinkOpenRequest) return false; + if (notice != null) ShowNotification(notice); + return true; + } - try + private void WatchUInkResourcesOnClose() + { + Closed -= CloseUInkBoardResources; + Closed += CloseUInkBoardResources; + } + + internal Task RestorePptShowUInkAsync(string path, int count) => + OpenUInkFileAsync(path, count); + + internal async Task OpenUInkFileAsync(string path, int? pptArchiveSlideCount = null) + { + int generation = BeginCanvasOpen(); + var dpi = VisualTreeHelper.GetDpi(inkCanvas); + string cacheDir = Path.Combine(Settings.Automation.AutoSavedStrokesLocation, UInkMediaRestoreCache.CacheDirectoryName); + bool pptArchive = pptArchiveSlideCount.HasValue; + int pptCount = pptArchiveSlideCount ?? + (IsInPPTPresentationMode && _pptManager?.IsConnected == true ? _pptManager.SlidesCount : 0); + int showGeneration = _showGeneration; + var slideMap = pptCount > 0 ? ReadShowSlides() : new PptSlideMap(null); + var archive = pptArchive ? new UInkShowArchive() : null; + if (pptArchive) _showArchive = archive; + UInkMediaRestoreCache resources = null; + try + { + var projection = await Task.Run(() => { - var pages = UInkIccMapper.ToPages(doc, UInkConversion.BlockToStroke); - if (pages.Count == 0) + var pair = UInkSaveService.OpenReadPair(path); + UInkReadResult read; + using (pair.Main) { - ShowNotification(MainWindowStrings.Main_Strokes_UInkInvalid); - return; + var extraError = pair.ExtraError; + try + { + resources = UInkMediaRestoreCache.FromStream(pair.Extra, cacheDir); + if (pair.Extra != null) RetainUInkMediaCache(cacheDir); + } + catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is UnauthorizedAccessException) + { + resources?.Dispose(); + resources = new UInkMediaRestoreCache(null, null, cacheDir); + extraError = ex; + } + read = UInkReader.Read(pair.Main, new UInkReadOptions { MaterializeContent = false }); + if (extraError != null) + { + read.Note("EXTRA-11"); + LogHelper.WriteLogToFile($"UInk 资源包不可用: {extraError.Message}", LogHelper.LogType.Warning); + } } - - // UInk 可注册父子 Workspace(如主白板 + 板中板)。ICC 当前一次只能承载一个 Workspace, - // 因此优先加载根 Workspace(无 parentWorkspaceGuid);否则同 pageIndex 的空子 Workspace - // 会覆盖主 Workspace 的墨迹(explicit-multilayer fixture 即为此情形)。 - var rootWorkspace = doc.HeaderExtension?.Workspaces? - .FirstOrDefault(x => string.IsNullOrEmpty(x.ParentWorkspaceGuid)) - ?? doc.HeaderExtension?.Workspaces?.FirstOrDefault(); - if (rootWorkspace != null) + if (read.Status == UInkReadStatus.Rejected) { - var rootPages = pages - .Where(p => string.Equals(p.Canvas?.WorkspaceGuid, rootWorkspace.Guid, StringComparison.Ordinal)) - .ToList(); - if (rootPages.Count > 0) pages = rootPages; + LogHelper.WriteLogToFile($"[UInk] 打开失败: {path}, {string.Join(", ", read.Diagnostics)}", LogHelper.LogType.Warning); + return null; } + if (pptArchive) archive.MainDigest = System.Security.Cryptography.SHA256.HashData(read.Bytes.Span); + var index = UInkPageProjection.Build(read, dpi.DpiScaleX, dpi.DpiScaleY, slideMap.Resolve, + UInkConversion.BlockToStroke, whiteboardLimit: UInkWhiteboardLimit, preserveUnbound: pptArchive); + if (index.Workspace?.WorkspaceType == (int)UInkWorkspaceType.Presentation && pptCount > 0) + { + var bound = SelectPptRestorePages(index.Pages, pptCount, out _); + var preparing = pptArchive ? index.Pages.Concat(index.RetainedPages) : bound; + foreach (var page in preparing) + { + page.EnsureMaterialized(); + if (page.Media.Count > 0) PrepareUInkMediaFiles(page, resources); + } + } + else if (index.Pages.Count > 0) + PrepareUInkMediaFiles(index.Pages[index.CurrentPageDisplayIndex], resources); + return index; + }); + if (generation != _uinkOpenRequest || + (pptArchive && (showGeneration != _showGeneration || isEnteredSlideShowEndEvent || currentMode != 0))) return null; + if (TryBlockFrozenPageMutation("打开 UInk 文件")) return null; + if (projection?.Workspace == null || projection.Pages.Count + projection.RetainedPages.Count == 0 || + (pptArchive && projection.Workspace.WorkspaceType != (int)UInkWorkspaceType.Presentation)) + return MainWindowStrings.Main_Strokes_UInkInvalid; - var wsType = rootWorkspace?.WorkspaceType ?? (int)UInkWorkspaceType.ScreenAnnotation; - bool isPPT = IsInPPTPresentationMode && _pptManager?.IsConnected == true; - bool isWhiteboard = currentMode != 0; - - if (wsType == (int)UInkWorkspaceType.Presentation && isPPT) - RestoreUInkToPPT(pages, extraMap, extractDir); - else if (wsType == (int)UInkWorkspaceType.Whiteboard && isWhiteboard) - RestoreUInkToWhiteboard(pages, extraMap, extractDir); - else - RestoreUInkToAnnotation(pages, extraMap, extractDir); - - ShowNotification(string.Format(MainWindowStrings.Main_Strokes_OpenUInkSuccess, pages.Count)); - LogHelper.WriteLogToFile( - $"[UInk] 打开完成: {path}, 载入 {pages.Count} 页, workspaceType={wsType}, ppt={isPPT}, whiteboard={isWhiteboard}", - LogHelper.LogType.Info); + var pages = projection.Pages; + int current = projection.CurrentPageDisplayIndex; + int installed = pages.Count; + string notification = null; + if (projection.Workspace.WorkspaceType == (int)UInkWorkspaceType.Whiteboard && pages.Count > 0) + { + for (int i = 1; i <= WhiteboardTotalCount; i++) + if (IsPageFrozen(i)) + return MainWindowStrings.Main_Freeze_PageFrozen; + if (currentMode == 0) ImageBlackboard_MouseUp(null, null); + if (currentMode == 0) return MainWindowStrings.Main_Strokes_OpenFailed; + installed = Math.Min(UInkWhiteboardLimit, pages.Count); + RestoreUInkToWhiteboard(projection, installed, resources, dpi); + if (installed < pages.Count) + { + projection.ReadResult.Note("whiteboardCapacity"); + notification = string.Format(UInkText("Capacity"), installed, pages.Count - installed); + } } - finally + else if (projection.Workspace.WorkspaceType == (int)UInkWorkspaceType.Presentation && + (pptArchive || (IsInPPTPresentationMode && _pptManager?.IsConnected == true))) { - if (extractDir != null) + // CANVAS-13/14:放映归档与手动打开使用同一套 PPT 绑页及未绑定页保留逻辑。 + if (pptCount == 0 || showGeneration != _showGeneration) + return MainWindowStrings.Main_Strokes_OpenFailed; + var (unbound, restored, byPosition) = RestoreUInkToPPT(projection, resources, dpi); + notification = string.Format(UInkText("PptRestored"), unbound, restored); + if (byPosition > 0) notification += Environment.NewLine + string.Format(UInkText("PptByPosition"), byPosition); + string hint = PptHostHint(); + if (hint != null && projection.Workspace.HostId is string source && + !string.Equals(source, hint, StringComparison.OrdinalIgnoreCase)) + notification += Environment.NewLine + source + " → " + hint; + } + else if (pages.Count > 0) + { + RestoreUInkToAnnotation(pages[current], resources, dpi); + if (projection.Workspace.WorkspaceType == (int)UInkWorkspaceType.Presentation) + notification = string.Format(UInkText("PptRestored"), pages.Count + projection.RetainedPages.Count, 0); + } + + // 来源与投影(含后续解码的降级状态)属于本次打开,文件内的 Workspace GUID 可重复。 + var opened = CurrentUInkSession(new UInkSession(path, projection), + pptArchive ? UInkWorkspaceType.Presentation : null); + if (pptArchive) + { + archive.Projection = projection; + archive.State = projection.RequiresSaveAs ? UInkShowArchive.RestoreState.Lossy : UInkShowArchive.RestoreState.Complete; + if (projection.RequiresSaveAs) { - try { if (Directory.Exists(extractDir)) Directory.Delete(extractDir, true); } catch (Exception ex) + // 部分恢复的旧内容本身不触发另存;记录安装后的可保存内容供结束时比较。 + var baseline = CaptureUInkWorkspace(pptArchiveSlideCount); + archive.RestoredContent = Task.Run(() => { - LogHelper.WriteLogToFile($"[UInk] 清理临时解压目录失败: {ex.Message}", LogHelper.LogType.Info); - } + try { return baseline.ArchiveContentDigest(); } + finally { baseline.ReleaseResources(); } + }); } } + notification ??= string.Format(MainWindowStrings.Main_Strokes_OpenUInkSuccess, installed); + if (pages.Any(p => p.HasLayerOrderFallback)) + notification += Environment.NewLine + UInkText("LayerOrder"); + string mediaNotice = TakeUInkMediaNotice(projection.ReadResult, resources); + if (mediaNotice != null) notification += Environment.NewLine + mediaNotice; + if (mediaNotice == null && opened.Projection.RequiresSaveAs) notification += Environment.NewLine + UInkText("SaveAs"); + KeyValuePair[] diagnostics; + lock (projection.ReadResult) diagnostics = projection.ReadResult.DiagnosticCounts.ToArray(); + foreach (var diagnostic in diagnostics) + LogHelper.WriteLogToFile($"UInk {diagnostic.Key}: {diagnostic.Value}", LogHelper.LogType.Warning); + LogHelper.WriteLogToFile( + $"[UInk] 打开完成: {path}, 文档 {pages.Count} 页, workspaceType={projection.Workspace.WorkspaceType}", + LogHelper.LogType.Info); + return notification; } catch (Exception ex) { - ShowNotification(MainWindowStrings.Main_Strokes_OpenFailed); LogHelper.WriteLogToFile($"UInk 打开失败: {ex}", LogHelper.LogType.Error); + return generation == _uinkOpenRequest && (!pptArchive || showGeneration == _showGeneration) + ? MainWindowStrings.Main_Strokes_OpenFailed : null; + } + finally + { + if (pptArchive && archive.State == UInkShowArchive.RestoreState.Pending) archive.State = UInkShowArchive.RestoreState.Failed; + resources?.Dispose(); } } - /// 屏幕批注/单页恢复:当前画布载入首个可见页墨迹 + 撤回链 + 媒体。 - private void RestoreUInkToAnnotation(List pages, Dictionary extraMap, string extractDir) + private static string UInkText(string key) => CanvasStrings.GetString("Canvas_UInk" + key); + + private void RestoreUInkToAnnotation(UInkPageData page, UInkMediaRestoreCache resources, DpiScale dpi) { - var page = pages.FirstOrDefault(p => p.Canvas?.LayerIndex == 0) ?? pages[0]; + _uinkOpenGeneration++; ClearStrokes(true); - timeMachine.ClearStrokeHistory(); - if (page.History != null && page.History.Length > 0) + ShutdownAllCanvasMediaElements(); + for (int i = inkCanvas.Children.Count - 1; i >= 0; i--) + if (inkCanvas.Children[i] is UInkMissingMedia or ContentControl { Content: UInkMissingMedia } || + IsPersistentUInkElement(inkCanvas.Children[i])) inkCanvas.Children.RemoveAt(i); + _ = InstallUInkPage(page, resources, UInkMediaMapper.PageCoordinates(page.Canvas, dpi.DpiScaleX, dpi.DpiScaleY)); + } + + internal Task InstallUInkPage(UInkPageData page, UInkMediaRestoreCache resources, UInkCoordinateMap coordinates = null) + { + page.EnsureMaterialized(); + var previous = _currentCommitType; + _currentCommitType = CommitReason.CodeInput; + try + { + if (page.FinalStrokes.Count != 0) inkCanvas.Strokes.Add(page.FinalStrokes); + var preparing = RestoreUInkMediaForPage(page, resources, coordinates); timeMachine.ImportTimeMachineHistory(page.History); - inkCanvas.Strokes.Add(page.FinalStrokes); - RestoreUInkMediaForPage(page.Media, extraMap, extractDir); - var bounds = page.FinalStrokes.Count > 0 ? page.FinalStrokes.GetBounds() : Rect.Empty; - LogHelper.WriteLogToFile($"UInk 屏幕批注恢复: {page.FinalStrokes.Count} 条墨迹, bounds={bounds}", LogHelper.LogType.Event); + return preparing; + } + finally { _currentCommitType = previous; } } - /// 白板恢复:按 pageIndex 填充 TimeMachineHistories,切到第 1 页。 - private void RestoreUInkToWhiteboard(List pages, Dictionary extraMap, string extractDir) + private void RestoreUInkToWhiteboard(UInkPageProjection projection, int count, UInkMediaRestoreCache resources, DpiScale dpi) { + _uinkOpenGeneration++; ClearStrokes(true); - timeMachine.ClearStrokeHistory(); - - WhiteboardTotalCount = Math.Max(pages.Count, 1); - CurrentWhiteboardIndex = 1; - ResetInkFreezePageStates(); - for (int i = 0; i < TimeMachineHistories.Length; i++) TimeMachineHistories[i] = null; + _boardResources?.Dispose(); + _boardResources = resources?.Retain(); + IndexUInkWhiteboard(projection, count, dpi); + WhiteboardTotalCount = count; + CurrentWhiteboardIndex = projection.CurrentPageDisplayIndex + 1; + RestoreStrokes(throwOnError: true); + UpdateIndexInfoDisplay(); + } - foreach (var page in pages) + internal void IndexUInkWhiteboard(UInkPageProjection projection, int count, DpiScale? dpi = null) + { + // 槽 0 是进入白板前的批注,不能随白板文档清掉。 + Array.Clear(TimeMachineHistories, 1, TimeMachineHistories.Length - 1); + Array.Clear(_uinkBoard, 0, _uinkBoard.Length); + for (int i = 1; i <= count; i++) { - int idx = (int)(page.Canvas?.PageIndex ?? 0) + 1; - if (idx < 1 || idx >= TimeMachineHistories.Length) continue; - TimeMachineHistories[idx] = page.History != null && page.History.Length > 0 - ? page.History - : new[] { new TimeMachineHistory(page.FinalStrokes, TimeMachineHistoryType.UserInput, false) }; + var page = projection.Pages[i - 1]; + var slot = new UInkBoardSlot + { + Pending = page, Imported = true, Background = page.Canvas.LayerIndex == 0 ? page.Canvas.Background : null, + // 离页墨迹沿用打开时的 DPI,媒体须共享同一映射,即使首访前换了屏幕。 + MediaCoordinates = dpi.HasValue + ? UInkMediaMapper.PageCoordinates(page.Canvas, dpi.Value.DpiScaleX, dpi.Value.DpiScaleY) : null + }; + if (Guid.TryParse(page.Canvas.PageGuid, out var guid)) slot.Guid = guid.ToString(); + _uinkBoard[i] = slot; + TimeMachineHistories[i] = slot.SavedHistory = new TimeMachineHistory[0]; } + _uinkWorkspaceIds[(int)UInkWorkspaceType.Whiteboard] = Guid.TryParse(projection.Workspace.Guid, out var ws) + ? ws.ToString() : Guid.NewGuid().ToString(); + } - if (TimeMachineHistories[1] != null) RestoreStrokes(); - if (pages.Count > 0) RestoreUInkMediaForPage(pages[0].Media, extraMap, extractDir); - UpdateIndexInfoDisplay(); - LogHelper.WriteLogToFile($"UInk 白板恢复: {pages.Count} 页", LogHelper.LogType.Event); + private void CloseUInkBoardResources(object sender, EventArgs e) + { + BeginCanvasOpen(); + _uinkOpenGeneration++; + ResetPptUInkPages(); + _boardResources?.Dispose(); + _boardResources = null; } - /// PPT 放映恢复:按 pageIndex 写入 _singlePPTInkManager,恢复当前幻灯片墨迹。 - private void RestoreUInkToPPT(List pages, Dictionary extraMap, string extractDir) + private bool InstallPendingUInkPage(int index) { - if (!IsInPPTPresentationMode || _pptManager == null) return; - ClearStrokes(true); - timeMachine.ClearStrokeHistory(); - _singlePPTInkManager?.ClearAllStrokes(); + var slot = GetUInkSlot(index); + ApplyUInkBackground(slot); + var page = slot?.Pending; + if (page == null) return false; + bool firstVisit = !page.IsMaterialized; + _ = InstallUInkPage(page, _boardResources, slot.MediaCoordinates); + TimeMachineHistories[index] = slot.SavedHistory = page.History; + slot.Pending = null; + RestoreMultiTouchModeState(index); + SyncPdfPageSidebarWithCanvas(); + if (firstVisit && page.HasLayerOrderFallback) + ShowNotification(UInkText("LayerOrder") + Environment.NewLine + UInkText("SaveAs")); + return true; + } - foreach (var page in pages) + private UInkBoardSlot GetUInkSlot(int index) + { + var slot = _uinkBoard[index]; + // 其它格式也可直接替换白板历史;标记不再匹配时不得安装旧文档的离页。 + if (slot != null && TimeMachineHistories[index] != slot.SavedHistory) + _uinkBoard[index] = slot = null; + return slot; + } + + private TimeMachineHistory[] ShiftUInkBoardHistory(int index) + { + var source = TimeMachineHistories[index + 1]; + var slot = _uinkBoard[index]; // 槽位元数据已随 Array.Copy 前移。 + if (slot != null && slot.SavedHistory != source) _uinkBoard[index] = slot = null; + // 导入页持有复合媒体组或离页标记,移位时保留原有引用。 + var history = slot?.Imported == true ? source : FlattenPageHistory(source); + if (slot != null) slot.SavedHistory = history; + return history; + } + + private static UInkBackground BackgroundFromColor(Color color) => new UInkBackground + { + Color = new UInkColor { Fallback = (uint)(color.R << 16 | color.G << 8 | color.B) } + }; + + private UInkBackground DefaultUInkBackground() => BackgroundFromColor( + _boardResources == null && GridBackgroundCover.Background is SolidColorBrush native ? native.Color : + CustomBackgroundColor ?? (Settings.Canvas.UsingWhiteboard ? Color.FromRgb(234, 235, 237) : Color.FromRgb(22, 41, 36))); + + private UInkBackground CurrentUInkBackground(UInkBoardSlot slot) => + GridBackgroundCover.Background is SolidColorBrush solid ? BackgroundFromColor(solid.Color) : + slot.Background ?? DefaultUInkBackground(); + + private void ApplyUInkBackground(UInkBoardSlot slot) + { + if (_boardResources == null && slot?.Background == null && GridBackgroundCover.Background is not DrawingBrush) return; + var background = slot?.Background ?? DefaultUInkBackground(); + uint rgb = background.Color.Fallback; + var fill = new SolidColorBrush(Color.FromRgb((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb)); + if (background.Pattern != 1 && background.Pattern != 2) { GridBackgroundCover.Background = fill; return; } + + // CANVAS-9:使用同一逻辑尺寸的平铺图案,色差随背景亮度调整。 + var tile = new Rect(0, 0, 20, 20); + var detail = new SolidColorBrush(fill.Color.R + fill.Color.G + fill.Color.B > 384 + ? Color.FromArgb(60, 0, 0, 0) : Color.FromArgb(60, 255, 255, 255)); + var drawing = new DrawingGroup(); + using (var dc = drawing.Open()) { - int slide = (int)(page.Canvas?.PageIndex ?? 0) + 1; - if (slide < 1) continue; - _singlePPTInkManager?.ForceSaveSlideStrokes(slide, page.FinalStrokes); + dc.DrawRectangle(fill, null, tile); + if (background.Pattern == 1) dc.DrawEllipse(detail, null, new Point(10, 10), 1, 1); + else + { + dc.DrawRectangle(detail, null, new Rect(0, 0, 20, 1)); + dc.DrawRectangle(detail, null, new Rect(0, 1, 1, 19)); + } } + var brush = new DrawingBrush(drawing) { TileMode = TileMode.Tile, ViewportUnits = BrushMappingMode.Absolute, Viewport = tile }; + brush.Freeze(); + GridBackgroundCover.Background = brush; + } - int currentSlide = _pptManager.GetCurrentSlideNumber(); - var current = _singlePPTInkManager?.LoadSlideStrokes(currentSlide); - if (current != null && current.Count > 0) inkCanvas.Strokes.Add(current); + private (int Unbound, int Restored, int ByPosition) RestoreUInkToPPT(UInkPageProjection projection, UInkMediaRestoreCache resources, DpiScale dpi) + { + var map = ReadShowSlides(); + int count = map.Count > 0 ? map.Count : _pptManager.SlidesCount; + string hint = PptHostHint(); + string source = projection.Workspace.HostId; + bool mismatch = DifferentPptSource(source, hint); + int? Resolve(int id) + { + if (mismatch) return null; + if (_pptManager is PPTAgentLinkManager) return map.Resolve(id); + try { return GetSingleShowWindow()?.Presentation.Slides.FindBySlideID(id)?.SlideIndex; } + catch (System.Runtime.InteropServices.COMException) { return null; } + } - var curPage = pages.FirstOrDefault(p => (int)(p.Canvas?.PageIndex ?? 0) + 1 == currentSlide); - if (curPage != null) RestoreUInkMediaForPage(curPage.Media, extraMap, extractDir); - LogHelper.WriteLogToFile($"UInk PPT 恢复: {pages.Count} 张幻灯片", LogHelper.LogType.Event); + var candidates = BindPptPages(projection.Pages, count, Resolve); + var retained = projection.Pages.Except(candidates).Concat(projection.RetainedPages).ToList(); + // 所有 ISF 编码成功后再发布,避免异常留下半个文档。 + var writes = candidates.Select(page => + { + page.EnsureMaterialized(); + // CANVAS-13:显式页码查询文稿表;只有放映位置的观测值不能证明文稿索引。 + var key = page.Binding == 1 ? map.Key(page.SlideIndex.Value) : PptPageKey.At(0, page.SlideId); + return (Page: page, Key: key, Ink: PptSlideStorage.Encode(page.FinalStrokes)); + }).ToArray(); + _uinkOpenGeneration++; + RememberQuickPanelOwners(); + var replaced = writes.Select(item => item.Key).ToHashSet(); + foreach (var child in inkCanvas.Children.OfType().Where(IsPersistentUInkElement).ToArray()) + { + var owner = _quickPanelOwners.GetValueOrDefault(child, _canvasSlide); + if (!replaced.Contains(owner)) continue; + if (child is CanvasMediaControl control) control.Shutdown(); + inkCanvas.Children.Remove(child); + } + // 只替换实际命中的页。导入完全未绑定的文档时,现有放映画布和离页资源仍然有效。 + foreach (var key in replaced) + { + if (_pptElements.Remove(key, out var oldElements) && key != _canvasSlide) + foreach (var control in oldElements.OfType()) control.Shutdown(); + _pendingPptMedia.Remove(key); + if (_pptPageResources.Remove(key, out var old)) old.Dispose(); + } + _preservedPptPages.Clear(); + _preservedPptGuids.Clear(); + _preservedPptResources?.Dispose(); + _preservedPptResources = retained.Count > 0 ? resources?.Retain() : null; + _preservedPptPages.AddRange(retained); + _uinkWorkspaceIds[(int)UInkWorkspaceType.Presentation] = projection.Workspace.Guid; + foreach (var item in writes) + { + _memoryStreams.Write(item.Key, item.Ink); + if (item.Key.Position > 0) _unclaimedArchivePages.Remove(item.Key.Position); + if (item.Page.Media.Count > 0 && resources != null) _pptPageResources[item.Key] = resources.Retain(); + _pptPageGuids[item.Key] = item.Page.Canvas.PageGuid; + if (item.Key == _canvasSlide) + { + ClearStrokes(true); + timeMachine.ClearStrokeHistory(); + _ = InstallUInkPage(item.Page, resources, UInkMediaMapper.PageCoordinates(item.Page.Canvas, dpi.DpiScaleX, dpi.DpiScaleY)); + TrackPptElements(item.Key, item.Page); + } + else if (item.Page.Media.Count > 0) _pendingPptMedia[item.Key] = item.Page; + } + return (retained.Count(p => p.PageKind == 0), writes.Length, candidates.Count(p => p.Binding == 1)); } - /// 把 UInkMedia 还原为画布元素:资源拷贝到持久缓存目录后,复用既有 Image/PDF/媒体恢复管线。 - private void RestoreUInkMediaForPage(IEnumerable mediaList, Dictionary extraMap, string extractDir) + internal static List BindPptPages(List pages, int count, Func resolve) { - if (mediaList == null) return; - var cacheDir = Path.Combine(Settings.Automation.AutoSavedStrokesLocation, "UInk Media"); - try { Directory.CreateDirectory(cacheDir); } catch (Exception ex) + foreach (var page in pages) { - LogHelper.WriteLogToFile($"[UInk] 创建媒体缓存目录失败: {ex.Message}", LogHelper.LogType.Info); + if (page.PageKind != 0) continue; + int? target = page.Binding == 1 + ? page.Canvas.PageIndex < int.MaxValue ? (int)page.Canvas.PageIndex + 1 : null + : page.SlideId is int id ? resolve(id) : null; + page.SlideIndex = target > 0 && target <= count ? target : null; + page.IsUnbound = !page.SlideIndex.HasValue; } + // 一个目标不能覆盖两份批注;冲突页作为未绑定页完整保留。 + var bound = SelectPptRestorePages(pages, count, out _); + foreach (var group in bound.GroupBy(page => page.SlideIndex).Where(group => group.Count() > 1)) + foreach (var page in group) + { + page.IsUnbound = true; + page.SlideIndex = null; + } + bound.RemoveAll(page => page.IsUnbound); + return bound; + } - foreach (var m in mediaList) + internal static List SelectPptRestorePages(List pages, int slideCount, out int unbound) + { + // CANVAS-14:空 resolver 保留按 SlideID 绑定的页;只写入放映中有效的绑定位置。 + var bound = pages.Where(p => p.PageKind == 0 && p.Canvas.PageState != 1 && !p.IsUnbound && + p.SlideIndex > 0 && p.SlideIndex <= slideCount).ToList(); + unbound = pages.Count(p => p.PageKind == 0) - bound.Count; + return bound; + } + + internal static void PrepareUInkMediaFiles(UInkPageData page, UInkMediaRestoreCache resources) + { + if (page.MediaFiles != null) return; + var files = new string[page.Media.Count]; + for (int i = 0; i < files.Length; i++) { + var media = page.Media[i]; + // MEDIA-1/3、COMPAT-3/4:保留文件字段供诊断,ICC 只显示原生布局。 + lock (page.ReadResult) + { + if (media.Crop != null) page.ReadResult.Note("mediaCropIgnored"); + // 旧文件无全局 ICC 作者标记。自产视频由与公共框匹配的私有布局识别。 + if (UInkMediaMapper.IsVideo(media.MimeType)) + { + var box = new Size(media.Width ?? 0, media.Height ?? 0); + if (!UInkMediaMapper.TryGetNativeVideoLayout(media, box, out _, out _)) + page.ReadResult.Note("mediaVideoFitIgnored"); + } + else if (media.Fit is 2 or 3 && (media.MimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || + media.MimeType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase))) + page.ReadResult.Note("mediaVisualFitApproximation"); + if (UInkMediaMapper.IsSvg(media.MimeType)) page.ReadResult.Note("MEDIA-7"); + } try { - string localFile = null; - if (!string.IsNullOrEmpty(m.Path) && extraMap != null && extraMap.TryGetValue(m.Path, out var extracted)) - localFile = extracted; - if (string.IsNullOrEmpty(localFile) || !File.Exists(localFile)) + string file = resources?.GetVerifiedPath(media.Path, media.MimeType); + if (file != null && media.MimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) && + resources.GetBitmap(file) == null) + file = null; + + files[i] = file; + // Windows 可延迟更新访问时间,恢复成功时显式续期。 + if (file != null) { - LogHelper.WriteLogToFile($"UInk 媒体资源缺失(保留布局): {m.Path}", LogHelper.LogType.Warning); - continue; + try { File.SetLastAccessTimeUtc(file, DateTime.UtcNow); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } } + } + catch (Exception ex) when (UInkMediaMapper.IsResourceFailure(ex)) + { + LogHelper.WriteLogToFile($"UInk 媒体读取失败: {ex.Message}", LogHelper.LogType.Warning); + } + if (files[i] == null) lock (page.ReadResult) page.ReadResult.Note("EXTRA-11"); + } + page.MediaFiles = files; + } + + private static string TakeUInkMediaNotice(UInkReadResult result, UInkMediaRestoreCache resources) + { + if (resources == null) return null; + lock (result) + { + bool missing = (result.DiagnosticCounts.ContainsKey("EXTRA-11") || result.DiagnosticCounts.ContainsKey("MEDIA-6")) && + resources.TryTakeMissingNotice(); + bool layout = (result.DiagnosticCounts.ContainsKey("mediaCropIgnored") || + result.DiagnosticCounts.ContainsKey("mediaVideoFitIgnored") || + result.DiagnosticCounts.ContainsKey("mediaVisualFitApproximation")) && resources.TryTakeLayoutNotice(); + if (missing) return UInkMissingMediaNotice() + Environment.NewLine + UInkText("SaveAs"); + return layout ? UInkText("SaveAs") : null; + } + } - string cached = Path.Combine(cacheDir, Path.GetFileName(localFile)); - if (!File.Exists(cached)) File.Copy(localFile, cached, overwrite: true); + private static string UInkMissingMediaNotice() => + string.Format(MainWindowStrings.Main_MediaInsert_InsertFailed, new FileNotFoundException().Message); - float left = m.Transform != null && m.Transform.Length == 6 ? m.Transform[4] : 0f; - float top = m.Transform != null && m.Transform.Length == 6 ? m.Transform[5] : 0f; - double width = m.Width.HasValue && m.Width.Value > 0 ? m.Width.Value : 800.0; - double height = m.Height.HasValue && m.Height.Value > 0 ? m.Height.Value : 520.0; - bool isPdf = string.Equals(m.MimeType, "application/pdf", StringComparison.OrdinalIgnoreCase); - bool isAudio = m.MimeType != null && m.MimeType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase); - bool isVideo = m.MimeType != null && m.MimeType.StartsWith("video/", StringComparison.OrdinalIgnoreCase); + private sealed record UInkWaitingMedia(UInkMedia Media, UInkCoordinateMap Coordinates); + private sealed record UInkPdfState(CanvasElementInfo Info, UInkMedia Media, Action Failed); + private sealed record UInkPlaybackState(UInkMedia Media) + { + internal bool SettingsApplied; + } - var info = new CanvasElementInfo + private System.Runtime.CompilerServices.ConditionalWeakTable _uinkBoundElements; + + private bool WasUInkElementBound(FrameworkElement element) + { + if (!(element is UInkBitmapImage or UInkMissingMedia || element.Tag is UInkPdfState or UInkPlaybackState or UInkWaitingMedia)) + return false; + // 翻页会再次走公共绑定入口,导入元素复用同一实例及事件。 + var bound = _uinkBoundElements ??= new(); + if (bound.TryGetValue(element, out _)) return true; + bound.Add(element, this); + return false; + } + + // MEDIA-4/6:先占组内位置,后台完成后只更换内容,撤销和离页历史仍持有原引用。 + private Task RestoreUInkMediaForPage(UInkPageData page, UInkMediaRestoreCache resources, UInkCoordinateMap coordinates) + { + if (page.Media.Count == 0) return Task.CompletedTask; + var dpi = VisualTreeHelper.GetDpi(inkCanvas); + coordinates ??= UInkMediaMapper.PageCoordinates(page.Canvas, dpi.DpiScaleX, dpi.DpiScaleY); + var owner = PdfPageIdentity(); + bool preparing = page.MediaFiles == null; + var pptKey = _canvasSlide; + bool pptLease = resources != null && ReferenceEquals(resources, _pptPageResources.GetValueOrDefault(pptKey)); + bool OwnsPage() + { + // PPT 离页仍持有原元素;仅在该页资源被替换后取消后台完成回调。 + if (pptLease) return ReferenceEquals(resources, _pptPageResources.GetValueOrDefault(pptKey)); + if (owner.Generation != _uinkOpenGeneration) return false; + if (owner.Slot == null) return owner == PdfPageIdentity(); + int slotIndex = Array.IndexOf(_uinkBoard, owner.Slot); + return slotIndex > 0 && GetUInkSlot(slotIndex) == owner.Slot && + string.Equals(owner.Slot.Guid, page.Canvas.PageGuid, StringComparison.OrdinalIgnoreCase); + } + + var complete = new List>(page.Media.Count); + int previousGroup = -1, elementIndex = 0; + foreach (var item in page.Items) + { + if (item.Block is not UInkMedia media) continue; + if (previousGroup != item.Group) { previousGroup = item.Group; elementIndex = 0; } + var group = (UInkGroupHistory)page.History[item.Group]; + int index = elementIndex++; + string cached = preparing ? null : page.MediaFiles[complete.Count]; + FrameworkElement element; + Action finish = null; + + bool Owns(FrameworkElement candidate) => group.Elements[index] == candidate && OwnsPage(); + + void Failed(ContentControl control, Exception ex) + { + if (!Owns(control)) return; + control.Content = new UInkMissingMedia(media.Path); + lock (page.ReadResult) page.ReadResult.Note("MEDIA-6"); + ReportUInkMediaNotice(page, resources); + if (ex != null) LogHelper.WriteLogToFile($"UInk 媒体恢复失败: {ex.Message}", LogHelper.LogType.Warning); + if (control is PdfEmbeddedView) SyncPdfPageSidebarWithCanvas(); + } + + if (UInkMediaMapper.IsSvg(media.MimeType) || (!preparing && cached == null)) + { + element = new UInkMissingMedia(media.Path); + } + else if (media.MimeType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase)) + { + var pdf = new PdfEmbeddedView { EnableStrokesPersistence = false, MinWidth = 0, MinHeight = 0 }; + var placeholder = new UInkMissingMedia(media.Path); + var grid = (Grid)pdf.Content; + ((Image)grid.Children[0]).Stretch = UInkMediaMapper.StretchFromFit(media.Fit); + grid.Children.Add(placeholder); + element = pdf; + finish = file => { - Type = isPdf ? "Pdf" : (isAudio || isVideo ? "Media" : "Image"), - SourcePath = cached, - Left = left, - Top = top, - Width = width, - Height = height, - Stretch = "Uniform", - MediaKind = isAudio ? "Audio" : (isVideo ? "Video" : null), - MediaDisplayName = Path.GetFileName(cached), - MediaPositionSeconds = m.StartTime > 0 ? m.StartTime : (double?)null, - MediaSpeedRatio = Math.Abs(m.PlaybackRate - 1f) > 0.0001f ? (double?)m.PlaybackRate : null, - MediaVolume = Math.Abs(m.Volume - 1f) > 0.0001f ? (double?)m.Volume : null, - PdfCurrentPage = m.PageIndex.HasValue ? (int?)m.PageIndex.Value : null, - PdfPageCount = m.PageCount.HasValue ? (int?)m.PageCount.Value : null, + if (file == null) { Failed(pdf, null); return; } + var info = new CanvasElementInfo { Type = "Pdf", SourcePath = file, + PdfCurrentPage = (int?)Math.Min(media.PageIndex ?? 0, int.MaxValue), + PdfPageCount = media.PageCount.HasValue ? (int?)Math.Min(media.PageCount.Value, int.MaxValue) : null }; + var state = new UInkPdfState(info, media, ex => Failed(pdf, ex)); + pdf.Tag = state; + _ = InitializeUInkPdfAsync(pdf, state, placeholder, page.ReadResult, owner.Generation, () => Owns(pdf)); }; - - if (isPdf) + } + else if (media.MimeType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) || + media.MimeType.StartsWith("video/", StringComparison.OrdinalIgnoreCase)) + { + var control = new CanvasMediaControl(); + var layout = control.Content; + if (preparing) control.Content = new UInkMissingMedia(media.Path); + element = control; + finish = file => { - Dispatcher.BeginInvoke(new Action(() => { _ = RestorePdfFromElementInfoAsync(info); }), DispatcherPriority.Loaded); - } - else if (isAudio || isVideo) + if (file == null) { Failed(control, null); return; } + var state = new UInkPlaybackState(media); + control.Tag = state; + control.Content = layout; + UInkPlayback.Configure(control, file, media, () => state.SettingsApplied = true, ex => + { + if (!Owns(control)) return; + control.Shutdown(); + Failed(control, ex); + }); + double width = control.Width, height = control.Height; + control.Initialize(file, Path.GetFileName(media.Path)); + // 原生初始化会设置音频默认高度,导入仍使用文件中的元素框。 + control.Width = width; + control.Height = height; + }; + } + else if (media.MimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) + { + var image = new UInkBitmapImage(media); + element = image; + finish = file => { - RestoreMediaFromElementInfo(info); - } - else + if (file != null && resources.GetPreparedBitmap(file, out var stamp) is BitmapSource bitmap) + image.SetBitmap(bitmap, file, stamp); + }; + } + else element = new UInkMissingMedia(media.Path); + + UInkMediaMapper.ApplyLayout(element, media, coordinates); + // 保留初始化器创建的操作槽,在最前面承载导入矩阵供鼠标/触摸继续组合。 + var imported = element.RenderTransform; + InitializeElementTransform(element); + ((TransformGroup)element.RenderTransform).Children.Insert(0, imported); + if (finish != null) element.Tag = new UInkWaitingMedia(media, coordinates); + BindElementEvents(element); + group.Elements[index] = element; + inkCanvas.Children.Add(element); + complete.Add(finish == null ? null : file => + { + if (!Owns(element)) return; + try { finish(file); } + catch (Exception ex) when (UInkMediaMapper.IsResourceFailure(ex)) { - var bitmapImage = new BitmapImage(); - bitmapImage.BeginInit(); - bitmapImage.UriSource = new Uri(info.SourcePath); - bitmapImage.CacheOption = BitmapCacheOption.OnLoad; - bitmapImage.EndInit(); - bitmapImage.Freeze(); - var img = new Image + if (element is ContentControl control) Failed(control, ex); + else { - Source = bitmapImage, - Width = width, - Height = height, - Stretch = System.Windows.Media.Stretch.Uniform, - }; - InkCanvas.SetLeft(img, left); - InkCanvas.SetTop(img, top); - inkCanvas.Children.Add(img); + lock (page.ReadResult) page.ReadResult.Note("MEDIA-6"); + LogHelper.WriteLogToFile($"UInk 媒体恢复失败: {ex.Message}", LogHelper.LogType.Warning); + } } - } - catch (Exception ex) + finally { if (element.Tag is UInkWaitingMedia) element.Tag = null; } + }); + } + + if (preparing) return CompleteUInkMediaAsync(page, resources, complete, OwnsPage); + for (int i = 0; i < complete.Count; i++) complete[i]?.Invoke(page.MediaFiles[i]); + return Task.CompletedTask; + } + + private async Task CompleteUInkMediaAsync(UInkPageData page, UInkMediaRestoreCache resources, + List> complete, Func ownsPage) + { + using var lease = resources?.Retain(); + await Task.Run(() => PrepareUInkMediaFiles(page, lease)).ConfigureAwait(false); + await inkCanvas.Dispatcher.InvokeAsync(() => + { + if (!ownsPage()) return; + for (int i = 0; i < complete.Count; i++) complete[i]?.Invoke(page.MediaFiles[i]); + ReportUInkMediaNotice(page, resources); + }); + } + + private void ReportUInkMediaNotice(UInkPageData page, UInkMediaRestoreCache resources) + { + string notice = TakeUInkMediaNotice(page.ReadResult, resources); + if (notice != null) ShowNotification(notice); + } + + internal static async Task NavigateRestoredPdfAsync(PdfEmbeddedView view, bool previous) + { + Func navigate = previous ? view.GoToPreviousPageAsync : view.GoToNextPageAsync; + if (view.Tag is not UInkPdfState state) + { + await navigate(); + return; + } + try { await PdfWinRtHelper.WithUInkRenderBudgetAsync(navigate); } + catch (Exception ex) { state.Failed(ex); } + } + + private async Task InitializeUInkPdfAsync(PdfEmbeddedView view, UInkPdfState state, + UInkMissingMedia placeholder, UInkReadResult read, int generation, Func ownsPage) + { + var (info, media, failed) = state; + try + { + bool restored = await RestorePdfFromElementInfoAsync(info, view, ownsPage, count => { - LogHelper.WriteLogToFile($"UInk 媒体恢复失败: {ex.Message}", LogHelper.LogType.Error); + if (media.PageCount.HasValue && media.PageCount.Value != count) + { + lock (read) read.Note("MEDIA-9"); + LogHelper.WriteLogToFile($"UInk MEDIA-9: PDF 页数 {media.PageCount.Value} → {count}", LogHelper.LogType.Warning); + } + }, media.PageIndex ?? 0); + if (!ownsPage()) return; + if (!restored || view.Content is not Grid grid || grid.Children[0] is not Image { Source: BitmapSource }) + { + failed(null); + return; } + grid.Children.Remove(placeholder); + CompleteRestoredPdf(view, generation); } + catch (Exception ex) { failed(ex); } } } } diff --git a/Ink Canvas/Properties/CanvasStrings.en-US.resx b/Ink Canvas/Properties/CanvasStrings.en-US.resx index 419a9c3f9..c25b2ff31 100644 --- a/Ink Canvas/Properties/CanvasStrings.en-US.resx +++ b/Ink Canvas/Properties/CanvasStrings.en-US.resx @@ -438,4 +438,25 @@ Remove asymptote lines? + + Opened {0} whiteboard pages. {1} additional pages exceeded the page limit. + + + Save a new copy to keep the original document. Some content may display differently or be omitted. + + + {0} page(s) matched by slide number because slide IDs were unavailable. + + + Retained {0} unbound slides and restored {1} slides. + + + Ink appears above media in ICC. The stacking order on this page may differ from the file. + + + Skipped {0} media items with missing or unsafe resources. + + + The original slide archive was preserved. This show was saved to {0}. + diff --git a/Ink Canvas/Properties/CanvasStrings.resx b/Ink Canvas/Properties/CanvasStrings.resx index dc285946a..8da0079dd 100644 --- a/Ink Canvas/Properties/CanvasStrings.resx +++ b/Ink Canvas/Properties/CanvasStrings.resx @@ -438,4 +438,25 @@ 是否移除渐近线? + + 已装入 {0} 页白板,另有 {1} 页超出页数上限。 + + + 部分内容可能以兼容方式显示或未装入。请另存为新文件以保留原件。 + + + {0} 页按页码对应幻灯片(未取得幻灯片标识) + + + 保留 {0} 个未绑定页,已恢复 {1} 页 + + + ICC 将墨迹显示在媒体上方,此页的遮挡顺序可能与原文件不同。 + + + 已跳过 {0} 个缺失或不安全的媒体对象。 + + + 已保留原放映归档,本场批注已另存至 {0}。 + diff --git a/Ink Canvas/Properties/CanvasStrings.zh-ME.resx b/Ink Canvas/Properties/CanvasStrings.zh-ME.resx index 1d2343468..13450f06b 100644 --- a/Ink Canvas/Properties/CanvasStrings.zh-ME.resx +++ b/Ink Canvas/Properties/CanvasStrings.zh-ME.resx @@ -438,4 +438,25 @@ 物理超度渐近线? + + 已装入 {0} 页白板,另有 {1} 页超出页数上限。 + + + 部分内容可能以兼容方式显示或未装入。请另存为新文件以保留原件。 + + + {0} 页按页码对应幻灯片(未取得幻灯片标识) + + + 已保留 {0} 页未绑定幻灯片,恢复了 {1} 页。 + + + ICC 将墨迹显示在媒体上方,此页的遮挡顺序可能与原文件不同。 + + + 已略过 {0} 个缺失或不安全的媒体对象。 + + + 已保留原放映归档,本场批注已另存至 {0}。 + diff --git a/Ink Canvas/Resources/Settings.cs b/Ink Canvas/Resources/Settings.cs index d58658f42..92c361267 100644 --- a/Ink Canvas/Resources/Settings.cs +++ b/Ink Canvas/Resources/Settings.cs @@ -14,6 +14,9 @@ public class Settings [JsonProperty("updatePackageDefaultsMigrated")] public bool UpdatePackageDefaultsMigrated { get; set; } + [JsonProperty("uinkDefaultMigrated", DefaultValueHandling = DefaultValueHandling.Populate)] + public bool UInkDefaultMigrated { get; set; } = true; + [JsonProperty("advanced")] public Advanced Advanced { get; set; } = new Advanced(); @@ -1715,8 +1718,9 @@ public class Automation [JsonProperty("isSaveStrokesAsXML")] public bool IsSaveStrokesAsXML { get; set; } = false; - [JsonProperty("isSaveStrokesAsUInK")] - public bool IsSaveStrokesAsUInK { get; set; } = false; + // 旧 JSON 缺键时先采用旧默认,由一次性迁移结合 XML/整页设置判定。 + [JsonProperty("isSaveStrokesAsUInK", DefaultValueHandling = DefaultValueHandling.Populate)] + public bool IsSaveStrokesAsUInK { get; set; } = true; [JsonProperty("isAutoEnterAnnotationAfterKillHite")] public bool IsAutoEnterAnnotationAfterKillHite { get; set; } diff --git a/Ink Canvas/UInk/IccConicBranch.cs b/Ink Canvas/UInk/IccConicBranch.cs new file mode 100644 index 000000000..04ce070be --- /dev/null +++ b/Ink Canvas/UInk/IccConicBranch.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Windows; + +namespace Ink_Canvas.UInk +{ + internal sealed partial class IccShapeDescriptor + { + // 一条连续曲线对应两条原生半支。记录解析参数,避免把工具的 0.5 DIP 步长当成设备像素误差保证。 + internal static IccShapeDescriptor Parabola(Point center, double coefficient, double extent, bool vertical) => new() + { + Kind = Tool.Parabola, + Data = new[] + { + center.X, + center.Y, + coefficient, + extent, + vertical ? 1d : 0d, + 0d + } + }; + internal static IccShapeDescriptor Hyperbola(Point center, double a, double b, double slope, double extent, bool horizontal, double side) => new() + { + Kind = Tool.Hyperbola, + Data = new[] + { + center.X, + center.Y, + a, + b, + slope, + extent, + horizontal ? 1d : 0d, + side + } + }; + private void NativeBranch(Action> append) + { + for (int half = 0; half < 2; half++) + { + var points = new List(); + if (Kind == Tool.Parabola) + { + for (double i = 0; i <= Data[3]; i += 0.5) + { + double s = half == 0 ? i : -i, bend = -Data[2] * i * i; + points.Add(Data[4] == 1 ? new Point(Data[0] + s, Data[1] + bend) : new Point(Data[0] + bend, Data[1] + s)); + } + } + else + { + double a = Data[2], b = Data[3], k = Data[4]; + for (double i = a; i <= Data[5]; i += 0.5) + { + double off = Math.Sqrt(Math.Abs(Data[6] == 1 ? k * k * i * i - b * b : i * i / k / k - b * b)); + double v = half == 0 ? -off : off; + points.Add(Data[6] == 1 ? new Point(Data[0] + Data[7] * i, Data[1] + v) : new Point(Data[0] + v, Data[1] + Data[7] * i)); + } + } + + if (points.Count != 0) + append(points); + } + } + + private bool SampleBranch(Action add) + { + var matrix = Transform; + bool parabola = Kind == Tool.Parabola; + bool primaryX = parabola ? Data[4] == 1 : Data[6] == 1; + var center = matrix.Transform(new Point(Data[0], Data[1])); + var x = matrix.Transform(primaryX ? new Vector(1, 0) : new Vector(0, 1)); + var y = matrix.Transform(primaryX ? new Vector(0, 1) : new Vector(1, 0)); + double t, bound; + if (parabola) + { + t = Math.Floor(Data[3] * 2) / 2; + bound = 2 * Math.Abs(Data[2]) * y.Length; + } + else + { + double a = Data[2], b = Data[3]; + if (a <= 0 || b <= 0) + return false; + double end = a + Math.Floor((Data[5] - a) * 2) / 2; + t = Math.Acosh(Math.Max(1, end / a)); + bound = a * Math.Cosh(t) * x.Length + b * Math.Sinh(t) * y.Length; + } + + // SHAPE-24:对二阶导数取上界,最大弦误差 ≤ M·h²/8。 + double segments = Math.Max(1, Math.Ceiling(2 * t * Math.Sqrt(bound / 2))); + if (!double.IsFinite(segments) || segments > UInkBlockScanner.MaxContainer - 1) + return false; + for (int j = 0; j <= (int)segments; j++) + { + double s = t * (2.0 * j / segments - 1); + add(parabola ? center + x * s - y * (Data[2] * s * s) : center + x * (Data[7] * Data[2] * Math.Cosh(s)) + y * (Data[3] * Math.Sinh(s))); + } + + return true; + } + } +} diff --git a/Ink Canvas/UInk/IccGlyphMapping.cs b/Ink Canvas/UInk/IccGlyphMapping.cs new file mode 100644 index 000000000..3e73aa09a --- /dev/null +++ b/Ink Canvas/UInk/IccGlyphMapping.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using Ink_Canvas.Helpers; + +namespace Ink_Canvas.UInk +{ + internal sealed partial class IccShapeDescriptor + { + internal static bool IsPublicGlyph(UInkShape shape) => shape.Geometry is UInkLineGeometry && shape.ShapeType == (int)UInkShapeType.Polygon && shape.Fill != null && shape.Stroke == null && shape.Extra != null && shape.Extra.TryGetValue("icc:glyph/v1", out string marker) && marker == "1"; + private static IEnumerable> Contours(PathGeometry flat) + { + var matrix = flat.Transform?.Value ?? Matrix.Identity; + foreach (var figure in flat.Figures) + { + if (!figure.IsFilled) + continue; + var points = new List + { + matrix.Transform(figure.StartPoint) + }; + foreach (var seg in figure.Segments) + { + if (seg is PolyLineSegment poly) + foreach (var point in poly.Points) + points.Add(matrix.Transform(point)); + else if (seg is LineSegment line) + points.Add(matrix.Transform(line.Point)); + } + + if (points.Count > 1 && points[^1] == points[0]) + points.RemoveAt(points.Count - 1); + if (points.Count >= 3) + yield return points; + } + } + + private static bool HasLinearGlyphOutline(Geometry geometry) + { + // 三次曲线的实心边界不能用有限个直线段无损表示,按 D5 写实际轮廓 Ink。 + foreach (var figure in PathGeometry.CreateFromGeometry(geometry).Figures) + foreach (var segment in figure.Segments) + if (segment is not LineSegment && segment is not PolyLineSegment) + return false; + return true; + } + + internal static void TagGlyph(FilledGlyphStroke stroke) => + BuildGlyphDescriptor(stroke.GlyphGeometry, stroke)?.Attach(new StrokeCollection { stroke }, 0); + + // 由实际绘制的填充轮廓生成字形 Polygon;创建与导出共用,选区变换后也以实际轮廓为准。 + internal static IccShapeDescriptor BuildGlyphDescriptor(Geometry geometry, Stroke style) + { + if (!HasLinearGlyphOutline(geometry)) return null; + var flat = geometry.GetOutlinedPathGeometry(0.0001, ToleranceType.Absolute).GetFlattenedPathGeometry(0.0001, ToleranceType.Absolute); + var vertices = new List(); + void Add(Point p) + { + vertices.Add(p.X); + vertices.Add(p.Y); + } + + foreach (var contour in Contours(flat)) + { + // SHAPE-2:沿原方向走完每个环。连接桥往返重合,对非零环绕数的贡献为零。 + foreach (var point in contour) + Add(point); + Add(contour[0]); + if (contour[0].X != vertices[0] || contour[0].Y != vertices[1]) + Add(new Point(vertices[0], vertices[1])); + } + + if (vertices.Count < 6) + return null; + var d = new IccShapeDescriptor + { + Kind = Tool.Glyph, + Data = vertices.ToArray(), + Count = 1, + ObjectId = Guid.NewGuid().ToString() + }; + if (!d.CaptureStyle(style)) + return null; + var polygon = d.GlyphGeometry(); + // EvenOdd 字体的洞也必须通过非零填充的对称差检查。 + var difference = Geometry.Combine(flat, polygon, GeometryCombineMode.Xor, null, 0.0001, ToleranceType.Absolute); + if (difference.GetArea(0.0001, ToleranceType.Absolute) > 0.0001 || d.Payload().Length > 1000000) + return null; + return d; + } + + internal static IEnumerable OutlineGlyph(Geometry geometry, DrawingAttributes da) + { + var flat = geometry.GetFlattenedPathGeometry(0.001, ToleranceType.Absolute); + foreach (var points in Contours(flat)) + { + points.Add(points[0]); + var s = new Stroke(new StylusPointCollection(points), da.Clone()); + yield return s; + } + } + } +} diff --git a/Ink Canvas/UInk/IccPublicShape.cs b/Ink Canvas/UInk/IccPublicShape.cs new file mode 100644 index 000000000..76fe0cc3b --- /dev/null +++ b/Ink Canvas/UInk/IccPublicShape.cs @@ -0,0 +1,331 @@ +using System; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; + +namespace Ink_Canvas.UInk +{ + internal sealed partial class IccShapeDescriptor + { + internal static StrokeCollection ImportPublic(UInkShape shape, Stroke outline, UInkCoordinateMap map, Action note) + { + if (IsPublicGlyph(shape)) + { + var dGlyph = Path(outline, Tool.Glyph); + if (dGlyph.CaptureStyle(outline)) + { + var native = dGlyph.Native(outline.DrawingAttributes); + if (native.Count > 0) + { + dGlyph.ObjectId = shape.Object?.Id ?? shape.Object?.Ref ?? Guid.NewGuid().ToString(); + dGlyph.Part = (int)(shape.Object?.PartIndex ?? 0); + dGlyph.Count = (int)(shape.Object?.PartCount ?? 1); + dGlyph.Attach(native, 0); + return native; + } + } + + note?.Invoke("glyphOutline"); + } + + var d = new IccShapeDescriptor + { + Kind = Tool.Public, + Data = new double[4], + PublicBlock = PublicBytes(shape), + ObjectId = shape.Object?.Id ?? shape.Object?.Ref, + Count = (int)(shape.Object?.PartCount ?? 0), + Part = (int)(shape.Object?.PartIndex ?? 0), + Revision = shape.Object?.Revision ?? 1 + }; + d.Map(map, false); + d.CaptureStyle(outline); + d.Recognized = shape.Extra != null && shape.Extra.TryGetValue("icc:recognized/v1", out string flag) && flag == "1"; + var strokes = d.NativePublic(outline.DrawingAttributes, note); + if (strokes.Count > 0) + { + d.Members = strokes.Count; + d.Attach(strokes, 0); + } + + return strokes; + } + + private UInkShape DecodePublic() + { + if (PublicBlock == null || UInkBlockScanner.Scan(PublicBlock, out int n) != UInkFrame.Complete || n != PublicBlock.Length) + return null; + try + { + return (UInkShape)new UInkDecoder(new UInkReadResult()).Content((int)UInkBlockType.Shape, new UInkValue(PublicBlock)); + } + catch (Exception ex) when (ex is UInkFieldException || ex is UInkBudgetException || ex is MessagePack.MessagePackSerializationException || ex is InvalidOperationException) + { + return null; + } + } + + private StrokeCollection NativePublic(DrawingAttributes da, Action note = null) + { + var shape = DecodePublic(); + if (shape == null) + return new StrokeCollection(); + var outline = UInkConversion.ShapeOutline(shape); + if (outline == null) + return new StrokeCollection(); + var strokes = DisplayPublic(shape, outline, UInkCoordinateMap.Identity, note); + foreach (var stroke in strokes) + { + stroke.DrawingAttributes = da.Clone(); + stroke.Transform(Transform, false); + if (Recognized) stroke.AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + } + + return strokes; + } + + private UInkShape ProjectPublic() + { + var shape = DecodePublic(); + var m = Transform; + if (shape == null || m.IsIdentity) + return shape; + double dashScale = 1; + if (shape.Stroke?.DashArray is { Count: > 0 }) + { + // SHAPE-7/26:跨顶点的相位连续,所有非零边都必须具有同一长度比。 + var outline = UInkConversion.ComputeShapeOutlinePoints(shape.ShapeType, shape.Geometry); + double? ratio = null; + for (int i = 1; i < outline.Count; i++) + { + var edge = new Vector(outline[i].x - outline[i-1].x, outline[i].y - outline[i-1].y); + if (edge.LengthSquared == 0) continue; + double scale = m.Transform(edge).Length / edge.Length; + if (!double.IsFinite(scale) || scale <= 0 || + (ratio.HasValue && Math.Abs(scale - ratio.Value) > 1e-10 * scale)) + return null; + ratio = scale; + } + if (!ratio.HasValue) return null; + dashScale = ratio.Value; + // 参数图形重建时可能改变起点或绕行方向,此时保留原生实段。 + if (shape.Geometry is not UInkLineGeometry && + (m.Determinant < 0 || (shape.Geometry is UInkCircleGeometry && (m.M12 != 0 || m.M11 < 0)))) + return null; + } + if (shape.Geometry is UInkLineGeometry line) + { + for (int i = 0; i < line.Points.Count; i++) + { + var p = m.Transform(new Point(line.Points[i].X, line.Points[i].Y)); + line.Points[i] = new UInkShapePoint + { + X = (float)p.X, + Y = (float)p.Y + }; + } + } + else + { + double x, y, rx, ry, angle; + bool ellipse = shape.ShapeType == (int)UInkShapeType.Circle || shape.ShapeType == (int)UInkShapeType.Ellipse; + if (shape.Geometry is UInkRectGeometry rect) + { + x = rect.CenterX; + y = rect.CenterY; + rx = rect.Width / 2.0; + ry = rect.Height / 2.0; + angle = rect.Rotation ?? 0; + } + else if (shape.Geometry is UInkSquareGeometry square) + { + x = square.CenterX; + y = square.CenterY; + rx = ry = square.Size / 2.0; + angle = square.Rotation ?? 0; + } + else if (shape.Geometry is UInkCircleGeometry circle) + { + x = circle.CenterX; + y = circle.CenterY; + rx = ry = circle.Radius; + angle = 0; + } + else + return null; + var center = m.Transform(new Point(x, y)); + var a = m.Transform(new Vector(rx * Math.Cos(angle), rx * Math.Sin(angle))); + var b = m.Transform(new Vector(-ry * Math.Sin(angle), ry * Math.Cos(angle))); + if (Math.Abs(Vector.Multiply(a, b)) > 1e-10 * a.Length * b.Length) + { + var polygon = new UInkLineGeometry(); + if (ellipse) + { + double steps=Math.Ceiling(2*Math.PI*Math.Sqrt((a.Length+b.Length)/2)); + if (!double.IsFinite(steps) || steps>UInkBlockScanner.MaxContainer) return null; + int count=Math.Max(4,(int)steps); + for (int i=0;i 0 }) return null; + var points = polygon.Points; + if (points.Count > 1 && points[0].X == points[^1].X && points[0].Y == points[^1].Y) + points.RemoveAt(points.Count - 1); // SHAPE-2:Polygon 隐式闭合。 + shape.ShapeType = (int)UInkShapeType.Polygon; + shape.Geometry = polygon; + } + else if (shape.Geometry is UInkCircleGeometry c && Math.Abs(a.Length - b.Length) <= 1e-10 * a.Length) + { + c.CenterX = (float)center.X; + c.CenterY = (float)center.Y; + c.Radius = (float)a.Length; + } + else + { + var old = shape.Geometry as UInkRectGeometry; + shape.ShapeType = (int)(ellipse ? UInkShapeType.Ellipse : UInkShapeType.Rectangle); + shape.Geometry = new UInkRectGeometry + { + CenterX = (float)center.X, + CenterY = (float)center.Y, + Width = (float)(2 * a.Length), + Height = (float)(2 * b.Length), + Rotation = (float)Math.Atan2(a.Y, a.X), + CornerRadiusX = old?.CornerRadiusX * (float)(a.Length / rx), + CornerRadiusY = old?.CornerRadiusY * (float)(b.Length / ry) + }; + } + } + + if (shape.Stroke != null) + { + float scale = (float)dashScale; + shape.Stroke.Width = (float)Width; + shape.Stroke.DashOffset *= scale; + if (shape.Stroke.DashOffset is float offset && !float.IsFinite(offset)) return null; + var dash = shape.Stroke.DashArray; + if (dash != null) + for (int i = 0; i < dash.Count; i++) + dash[i] *= scale; + } + + return shape; + } + + internal static StrokeCollection DisplayPublic(UInkShape shape, Stroke outline, UInkCoordinateMap map, Action note) + { + var parts = new UInkStrokeCollection(); + var points = outline.StylusPoints; + var da = outline.DrawingAttributes; + var dash = shape.Stroke?.DashArray; + var first = points[0].ToPoint(); + var last = points[^1].ToPoint(); + if (dash == null || dash.Count == 0) + { + // 单端 OpenArrow 和 ICC 的箭头使用同一条折返折线。 + if (shape.ShapeType == (int)UInkShapeType.Line && shape.Stroke?.StartMarker != 1 && shape.Stroke?.EndMarker == 1) + parts.AppendNew(Between(Tool.Arrow, first, last).Native(da)[0]); + else + parts.AppendNew(outline); + } + else + { + // SHAPE-7/26:相位在跨越折线顶点时连续,零长实段保留一个点。 + var lengths = new double[dash.Count]; + double period = 0; + for (int i = 0; i < lengths.Length; i++) + period += lengths[i] = dash[i]; + double offset = (shape.Stroke.DashOffset ?? 0) % period; + if (offset < 0) + offset += period; + int index = 0; + while (offset > 0 && offset >= lengths[index]) + { + offset -= lengths[index]; + index = (index + 1) % lengths.Length; + } + + double remaining = lengths[index] - offset; + StylusPointCollection run = null; + void Add(Point p) + { + run ??= new StylusPointCollection(); + if (run.Count == 0 || run[^1].X != p.X || run[^1].Y != p.Y) + run.Add(new StylusPoint(p.X, p.Y)); + } + + void Finish() + { + if (run != null) + parts.AppendNew(new Stroke(run, da.Clone())); + run = null; + } + + int iterations = 0; + for (int edge = 1; edge < points.Count; edge++) + { + Point start = points[edge - 1].ToPoint(), end = points[edge].ToPoint(); + var delta = end - start; + Point deviceStart = map.FromDip(start.X, start.Y), deviceEnd = map.FromDip(end.X, end.Y); + double length = (deviceEnd - deviceStart).Length; + for (double s = 0; s < length;) + { + // 极细图案不能将一个外部块膨胀为无界数量的 WPF 对象。 + if (++iterations > 65536 + points.Count) + { + note?.Invoke("shapeDashBudget"); + return new StrokeCollection + { + outline + }; + } + + double step = Math.Min(remaining, length - s); + if ((index & 1) == 0) + { + Add(start + delta * (s / length)); + if (step > 0) + Add(start + delta * ((s + step) / length)); + } + + s += step; + remaining -= step; + if (remaining <= 0) + { + Finish(); + index = (index + 1) % lengths.Length; + remaining = lengths[index]; + } + } + } + + Finish(); + } + + void Marker(Point tail, Point tip) + { + var arrow = Between(Tool.Arrow, tail, tip).Native(da)[0]; + arrow.StylusPoints.RemoveAt(0); + parts.AppendNew(arrow); + } + + if (shape.Stroke?.StartMarker == 1) + Marker(points[1].ToPoint(), first); + if (shape.Stroke?.EndMarker == 1 && (shape.ShapeType != 0 || shape.Stroke.StartMarker == 1 || dash?.Count > 0)) + Marker(points[^2].ToPoint(), last); + return parts; + } + } +} diff --git a/Ink Canvas/UInk/IccShapeCapture.cs b/Ink Canvas/UInk/IccShapeCapture.cs new file mode 100644 index 000000000..603863055 --- /dev/null +++ b/Ink Canvas/UInk/IccShapeCapture.cs @@ -0,0 +1,248 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; + +namespace Ink_Canvas.UInk +{ + internal sealed partial class IccShapeDescriptor + { + // 预览频繁被替换,只暂存参数。完成整个工具提交时再确定部件顺序并写 ISF 属性。 + private static readonly ConditionalWeakTable Drafts = new(); + internal StrokeCollection Preview(DrawingAttributes attributes) + { + if (Kind == Tool.Dot) + Pressure = 0.8f; + var strokes = Native(attributes); + if (strokes.Count > 0) + { + Members = strokes.Count; + Drafts.Add(strokes[0], this); + } + + return strokes; + } + + internal static void Commit(StrokeCollection strokes, int mode) + { + var parts = new List<(int Index, IccShapeDescriptor Descriptor)>(); + for (int i = 0; i < strokes.Count;) + { + var s = strokes[i]; + if (!Drafts.TryGetValue(s, out var d)) + { + if (s.StylusPoints.Count < 2) + { + if (mode is 22 or 23 or 25) s.AddPropertyData(FocusProperty, true); + i++; + continue; + } + + var kind = s.StylusPoints.Count == 2 ? Tool.Line : Tool.Path; + if (mode == 3 || mode == 19) + kind = Tool.Rectangle; + d = Path(s, kind); + } + + if (d.Members > strokes.Count - i) + break; + if (d.CaptureStyle(s)) + parts.Add((i, d)); + i += d.Members; + } + + // SHAPE-11:焦点、圆心仍是 Ink,只有连续 Shape 部件能组成一个对象。 + for (int start = 0; start < parts.Count;) + { + int end = start + 1; + while (end < parts.Count && parts[end - 1].Index + parts[end - 1].Descriptor.Members == parts[end].Index) + end++; + string id = end - start > 1 ? Guid.NewGuid().ToString() : null; + for (int i = start; i < end; i++) + { + var d = parts[i].Descriptor; + d.ObjectId = id; + d.Part = i - start; + d.Count = end - start; + d.Attach(strokes, parts[i].Index); + } + + start = end; + } + } + + internal static void Recognize(Stroke stroke, Tool kind) + { + var d = Path(stroke, kind); + if (!d.CaptureStyle(stroke)) + return; + for (int i = 1; i < stroke.StylusPoints.Count; i++) + { + if (stroke.StylusPoints[i].PressureFactor == d.Pressure) + continue; + if (!d.IgnorePressure) + return; // SHAPE-5:保留有可见笔锋的识别结果。 + d.Pressures = new float[stroke.StylusPoints.Count]; + for (int j = 0; j < d.Pressures.Length; j++) + d.Pressures[j] = stroke.StylusPoints[j].PressureFactor; + break; + } + + d.Attach(new StrokeCollection { stroke }, 0); + } + + // ISF 以 HIMETRIC 整数存坐标,量化误差最多半个单位(约 0.019 DIP);真实编辑的位移远大于此。 + private const double MatchTolerance = 0.05; + // ISF 同样量化笔宽(4 DIP 读回约 3.99999)。 + private const double WidthTolerance = 1e-3; + + internal static bool TryExport(StrokeCollection strokes, int index, UInkCoordinateMap map, out IccShapeDescriptor d, out UInkShape shape, Geometry glyphOutline = null) + { + d = null; + shape = null; + var head = strokes[index]; + if (!head.ContainsPropertyData(Property) || head.GetPropertyData(Property) is not string payload) + return false; + if (head.ContainsPropertyData(Helpers.InkFadeManager.LaserRenderModeGuid)) return false; + // ISF 剪贴板可带第三方属性。单个坏配方回退为当前 Ink。 + try { return Validate(Read(payload),strokes,index,map,out d,out shape, glyphOutline ?? (head as Helpers.FilledGlyphStroke)?.GlyphGeometry); } + catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException || + ex is System.IO.InvalidDataException || ex is ArithmeticException) + { + return false; + } + } + + private static bool Validate(IccShapeDescriptor descriptor,StrokeCollection strokes,int index,UInkCoordinateMap map, + out IccShapeDescriptor d,out UInkShape shape, Geometry glyphOutline) + { + d=descriptor; + shape=null; + var head=strokes[index]; + if (d == null || !d.SafeNativeSize() || d.Members > strokes.Count - index || d.Width < DrawingAttributes.MinWidth || + d.Width > DrawingAttributes.MaxWidth) + return false; + // 字形的实际填充由 DrawCore 持有,选区变换后的命中框不能参与几何拟合。 + if (glyphOutline != null || d.Kind == Tool.Glyph) + { + if (glyphOutline == null || d.Kind != Tool.Glyph || d.Members != 1) + return false; + // 描述符只标记 ICC 字形;几何按实际轮廓重建并做面积等价检查(Geometry.IsEmpty 不看面积)。 + var rebuilt = BuildGlyphDescriptor(glyphOutline, head); + if (rebuilt == null) return false; + rebuilt.ObjectId = d.ObjectId ?? rebuilt.ObjectId; + rebuilt.Recognized = d.Recognized; + d = rebuilt; + shape = d.Export(map); + return shape != null; + } + if (d.Kind == Tool.Dash || d.Kind == Tool.Dot) + { + // 从单条虚线的首笔截取出来的残段不应触发整组的重建。 + if (head.StylusPoints.Count != (d.Kind == Tool.Dot ? 1 : 2)) + return false; + } + + var original = d.Native(d.Attributes()); + if (original.Count != d.Members) + return false; + bool exact = true; + Point origin = default, target = default; + double sx = 0, sy = 0, su = 0, sv = 0; + long count = 0; + for (int j = 0; j < original.Count; j++) + { + Stroke before = original[j], after = strokes[index + j]; + var da = after.DrawingAttributes; + if (before.StylusPoints.Count != after.StylusPoints.Count || da.Color != before.DrawingAttributes.Color || + Math.Abs(da.Width - d.Width) > WidthTolerance || Math.Abs(da.Height - d.Width) > WidthTolerance || da.IgnorePressure != d.IgnorePressure || da.IsHighlighter || + da.FitToCurve != d.Fit || da.StylusTip != StylusTip.Ellipse || !da.StylusTipTransform.IsIdentity || + UInkConversion.IsLogicalHighlighter(after)) + return false; + if (j > 0 && (!after.ContainsPropertyData(Property) || !Equals(after.GetPropertyData(Property), j))) + return false; + for (int k = 0; k < before.StylusPoints.Count; k++) + { + var sp = before.StylusPoints[k]; + var actual = after.StylusPoints[k]; + if (Math.Abs(sp.PressureFactor - actual.PressureFactor) > 1e-6) + { + // ISF 用整数压力包存放 0.8 等值,只额外接受 WPF 自己解包后的压力。 + var pressure = StylusPointProperties.NormalPressure; + sp.SetPropertyValue(pressure, sp.GetPropertyValue(pressure)); + if (Math.Abs(sp.PressureFactor - actual.PressureFactor) > 1e-6) + return false; + } + Point p = sp.ToPoint(), q = actual.ToPoint(); + if (j == 0 && k == 0) + { + origin = p; + target = q; + } + + if ((p - q).Length > MatchTolerance) + exact = false; + sx += p.X - origin.X; + sy += p.Y - origin.Y; + su += q.X - target.X; + sv += q.Y - target.Y; + count++; + } + } + + if (!exact) + { + // 中心化最小二乘,避免把三个 ISF 量化点的误差放大到整条曲线。 + var center = origin + new Vector(sx / count, sy / count); + var moved = target + new Vector(su / count, sv / count); + double xx = 0, xy = 0, yy = 0, xu = 0, xv = 0, yu = 0, yv = 0; + foreach (var pair in Samples()) + { + var p = pair.P - center; + var q = pair.Q - moved; + xx += p.X * p.X; + xy += p.X * p.Y; + yy += p.Y * p.Y; + xu += p.X * q.X; + xv += p.X * q.Y; + yu += p.Y * q.X; + yv += p.Y * q.Y; + } + + double trace = xx + yy, det = xx * yy - xy * xy; + var basis = Matrix.Identity; + if (det > trace * trace * 1e-12) + basis = new Matrix((yy*xu-xy*yu)/det, (yy*xv-xy*yv)/det, + (xx*yu-xy*xu)/det, (xx*yv-xy*xv)/det, 0, 0); + else if (trace > 0) + { + // 共线点只能确定沿线的变化,选择保持夹角的旋转缩放候选。 + double real = (xu + yv) / trace, imag = (xv - yu) / trace; + basis = new Matrix(real, imag, -imag, real, 0, 0); + } + // 单点保持单位线性部分;所有候选都必须逐点核验。 + var offset = moved - basis.Transform(center); + basis.Translate(offset.X, offset.Y); + if (!basis.HasInverse) + return false; + foreach (var pair in Samples()) + if ((basis.Transform(pair.P) - pair.Q).Length > MatchTolerance) + return false; + d.Apply(basis); + d.Edited = true; + } + + shape = d.Export(map); + return shape != null; + IEnumerable<(Point P, Point Q)> Samples() + { + for (int j = 0; j < original.Count; j++) + for (int k = 0; k < original[j].StylusPoints.Count; k++) + yield return (original[j].StylusPoints[k].ToPoint(), strokes[index + j].StylusPoints[k].ToPoint()); + } + } + } +} diff --git a/Ink Canvas/UInk/IccShapeDescriptor.cs b/Ink Canvas/UInk/IccShapeDescriptor.cs new file mode 100644 index 000000000..d92b8db30 --- /dev/null +++ b/Ink Canvas/UInk/IccShapeDescriptor.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using Ink_Canvas.Helpers; + +namespace Ink_Canvas.UInk +{ + // Data 使用工具创建时的 DIP;Frame 将这些点映射至当前 DIP(写文件时为 Device px)。 + internal sealed partial class IccShapeDescriptor + { + internal static readonly Guid FocusProperty = new("828f897d-2a4d-4801-a54a-7b133abdc750"); + internal const string Key = "icc:shape/v1"; + internal static readonly Guid Property = new("94b50dc7-4e62-4c68-a62b-a7e07e615a87"); + internal enum Tool + { + Path, + Line, + Polygon, + Rectangle, + Ellipse, + Arrow, + AxisArrow, + Dash, + Dot, + Arc, + DashedArc, + Parabola, + Hyperbola, + Glyph, + Public + } + + public Tool Kind { get; set; } + public double[] Data { get; set; } + public double[] Frame { get; set; } = new double[] + { + 1, + 0, + 0, + 1, + 0, + 0 + }; + public byte[] PublicBlock { get; set; } + public int ArcMask { get; set; } = 3; + public double Width { get; set; } + public uint Argb { get; set; } + public bool IgnorePressure { get; set; } + public bool Fit { get; set; } + public float Pressure { get; set; } = 0.5f; + public float[] Pressures { get; set; } + public bool Recognized { get; set; } + public string ObjectId { get; set; } + public ulong Revision { get; set; } = 1; + internal bool Edited { get; set; } + public int Part { get; set; } + public int Count { get; set; } + public int Members { get; set; } = 1; + + internal static IccShapeDescriptor Between(Tool kind, Point a, Point b, int mask = 3) => new() + { + Kind = kind, + Data = new[] + { + a.X, + a.Y, + b.X, + b.Y + }, + ArcMask = mask + }; + internal static IccShapeDescriptor Path(Stroke s, Tool kind) + { + var points = s.StylusPoints; + var data = new double[points.Count * 2]; + for (int i = 0; i < points.Count; i++) + { + data[2 * i] = points[i].X; + data[2 * i + 1] = points[i].Y; + } + + return new IccShapeDescriptor + { + Kind = kind, + Data = data + }; + } + + internal Matrix Transform => new(Frame[0], Frame[1], Frame[2], Frame[3], Frame[4], Frame[5]); + + internal void Apply(Matrix m) + { + var result = Transform; + result.Append(m); + Frame = new[] + { + result.M11, + result.M12, + result.M21, + result.M22, + result.OffsetX, + result.OffsetY + }; + } + + internal bool CaptureStyle(Stroke s) + { + var da = s.DrawingAttributes; + if (da.Width != da.Height || da.StylusTip != StylusTip.Ellipse || da.IsHighlighter || + !da.StylusTipTransform.IsIdentity || UInkConversion.IsLogicalHighlighter(s)) + return false; + Width = da.Width; + IgnorePressure = da.IgnorePressure; + Fit = da.FitToCurve; + var c = da.Color; + Argb = ((uint)c.A << 24) | ((uint)c.R << 16) | ((uint)c.G << 8) | c.B; + Pressure = s.StylusPoints[0].PressureFactor; + Recognized = s.ContainsPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid); + return true; + } + + internal DrawingAttributes Attributes() => new() + { + Width = Width, + Height = Width, + IgnorePressure = IgnorePressure, + FitToCurve = Fit, + Color = Color.FromArgb((byte)(Argb >> 24), (byte)(Argb >> 16), (byte)(Argb >> 8), (byte)Argb) + }; + internal static IccShapeDescriptor Read(string json) + { + if (json == null || json.Length > UInkBlockScanner.MaxObject || !json.StartsWith(Key + " ", StringComparison.Ordinal)) + return null; + try + { + var d = JsonSerializer.Deserialize(json.Substring(Key.Length + 1)); + if (d?.Data == null || d.Data.Length < 4 || (d.Data.Length & 1) != 0 || d.Frame?.Length != 6 || d.Members < 1 || + d.ArcMask < 1 || d.ArcMask > 3 || !Enum.IsDefined(typeof(Tool), d.Kind) || d.Width <= 0 || d.Pressure < 0 || + d.Pressure > 1 || (d.Kind == Tool.Parabola && d.Data.Length != 6) || + (d.Kind == Tool.Hyperbola && d.Data.Length != 8)) + return null; + if (d.Pressures != null && (!d.IgnorePressure || d.Pressures.Length != d.Data.Length / 2 || + (d.Kind != Tool.Line && d.Kind != Tool.Polygon && d.Kind != Tool.Rectangle) || + Array.Exists(d.Pressures, v => !(v >= 0 && v <= 1)))) + return null; + if (Array.Exists(d.Data, v => !double.IsFinite(v)) || Array.Exists(d.Frame, v => !double.IsFinite(v)) || + !double.IsFinite(d.Width)) + return null; + if (d.ObjectId != null && (!Guid.TryParseExact(d.ObjectId, "D", out Guid id) || id == Guid.Empty || d.Count < 0 || + d.Part < 0 || d.Revision == 0 && d.Part == 0)) + return null; + return d; + } + catch (JsonException) + { + return null; + } + } + + internal string Payload() => Key + " " + JsonSerializer.Serialize(this); + internal static void CopyProperties(Stroke source, Stroke copy) + { + if (source.ContainsPropertyData(FocusProperty)) copy.AddPropertyData(FocusProperty, true); + if (source.ContainsPropertyData(Property)) + copy.AddPropertyData(Property, source.GetPropertyData(Property)); + if (source.ContainsPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid)) + copy.AddPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + } + + internal void Attach(StrokeCollection strokes, int index) + { + strokes[index].AddPropertyData(Property, Payload()); + // 从属笔画仅存部件内序号;首笔被擦除后不能单独恢复旧图形。 + for (int i = 1; i < Members; i++) + strokes[index + i].AddPropertyData(Property, i); + } + + internal static List EllipsePoints(Point st, Point ed, bool top, bool bottom) + { + var points = new List(); + if ((!top && !bottom) || !double.IsFinite(st.X) || !double.IsFinite(st.Y) || !double.IsFinite(ed.X) || !double.IsFinite(ed.Y)) + return points; + AddArc(points, st, ed, bottom ? 0 : Math.PI, top ? 2 * Math.PI : Math.PI); + return points; + } + + private static void AddArc(List points, Point st, Point ed, double from, double to) + { + for (double angle = from; angle <= to; angle += 0.01) + points.Add(new Point((st.X + ed.X) / 2 + (ed.X - st.X) / 2 * Math.Cos(angle), (st.Y + ed.Y) / 2 + (ed.Y - st.Y) / 2 * Math.Sin(angle))); + } + + internal StrokeCollection Native(DrawingAttributes da) + { + if (Kind == Tool.Public) + return NativePublic(da); + var result = new UInkStrokeCollection(); + var m = Transform; + var a = new Point(Data[0], Data[1]); + var b = new Point(Data[2], Data[3]); + void Add(List points) + { + var stylus = new StylusPointCollection(points.Count); + for (int i = 0; i < points.Count; i++) + { + Point p = m.Transform(points[i]); + stylus.Add(new StylusPoint(p.X, p.Y, Pressures == null ? Pressure : Pressures[i])); + } + + result.AppendNew(new Stroke(stylus, da.Clone())); + } + + if (Kind == Tool.Dash || Kind == Tool.Dot) + { + var delta = b - a; + double length = delta.Length; + if (length == 0) + return result; + delta /= length; + double step = Kind == Tool.Dot ? 3 : 5; + for (double s = 0; s < length; s += step * 2.76) + { + var points = new List + { + a + delta * s + }; + if (Kind == Tool.Dash) + points.Add(a + delta * Math.Min(s + step, length)); + Add(points); + } + } + else if (Kind == Tool.DashedArc) + { + if (!double.IsFinite(a.X) || !double.IsFinite(a.Y) || !double.IsFinite(b.X) || !double.IsFinite(b.Y)) + return result; + for (int half = 0; half < 2; half++) + { + if ((ArcMask & (1 << half)) == 0) + continue; + for (double i = half; i < half + 1; i += 0.05 * 1.66) + { + var points = new List(); + AddArc(points, a, b, Math.PI * i, Math.PI * (i + 0.05)); + Add(points); + } + } + } + else if (Kind == Tool.Ellipse || Kind == Tool.Arc) + Add(EllipsePoints(a, b, (ArcMask & 2) != 0, (ArcMask & 1) != 0)); + else if (Kind == Tool.Arrow || Kind == Tool.AxisArrow) + { + double w = Kind == Tool.Arrow ? 15 : 20, h = Kind == Tool.Arrow ? 10 : 7; + double theta = Math.Atan2(a.Y - b.Y, a.X - b.X); + var along = new Vector(Math.Cos(theta), Math.Sin(theta)); + var normal = new Vector(-along.Y, along.X); + Add(new List { a, b, b + along * w + normal * h, b, b + along * w - normal * h }); + } + else if (Kind == Tool.Parabola || Kind == Tool.Hyperbola) + NativeBranch(Add); + else if (Kind == Tool.Glyph) + { + var geometry = GlyphGeometry(); + var glyph = FilledGlyphStroke.FromPolygon(geometry, da); + if (glyph != null) + result.AppendNew(glyph); + } + else + { + var points = new List(Data.Length / 2); + for (int i = 0; i < Data.Length; i += 2) + points.Add(new Point(Data[i], Data[i + 1])); + Add(points); + } + + if (Recognized) + foreach (var s in result) + s.AddPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + return result; + } + + private StreamGeometry GlyphGeometry() + { + var g = new StreamGeometry + { + FillRule = FillRule.Nonzero + }; + using var ctx = g.Open(); + var matrix = Transform; + ctx.BeginFigure(matrix.Transform(new Point(Data[0], Data[1])), true, true); + for (int i = 2; i < Data.Length; i += 2) + ctx.LineTo(matrix.Transform(new Point(Data[i], Data[i + 1])), true, false); + return g; + } + } +} diff --git a/Ink Canvas/UInk/IccShapeMapping.cs b/Ink Canvas/UInk/IccShapeMapping.cs new file mode 100644 index 000000000..406332972 --- /dev/null +++ b/Ink Canvas/UInk/IccShapeMapping.cs @@ -0,0 +1,405 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Media; +using MessagePack; + +namespace Ink_Canvas.UInk +{ + internal sealed partial class IccShapeDescriptor + { + // 只序列化公开几何和样式用于核对;私有信息不能覆盖文件里的公共字段。 + private static byte[] PublicBytes(UInkShape shape) + { + var buffer = new ArrayBufferWriter(); + var w = new MessagePackWriter(buffer); + UInkSerializer.WriteBlock(ref w, new UInkShape { ShapeType = shape.ShapeType, Geometry = shape.Geometry, Stroke = shape.Stroke, Fill = shape.Fill }); + w.Flush(); + return buffer.WrittenSpan.ToArray(); + } + + private UInkShape PublicShape() + { + if (Kind == Tool.Public) + return ProjectPublic(); + var matrix = Transform; + Point P(int i) => matrix.Transform(new Point(Data[i], Data[i + 1])); + var first = P(0); + var last = P(Data.Length - 2); + var color = new UInkColor + { + Fallback = Argb & 0xffffff + }; + var style = new UInkStroke + { + Color = color, + Opacity = (Argb >> 24) / 255f, + Width = (float)(Width * (IgnorePressure ? 1 : 0.25 + 1.5 * Pressure)) + }; + var shape = new UInkShape + { + Stroke = style + }; + var path = new UInkLineGeometry(); + shape.Geometry = path; + void Add(Point p) => path.Points.Add(new UInkShapePoint { X = (float)p.X, Y = (float)p.Y }); + bool closed = Kind == Tool.Polygon || Kind == Tool.Glyph || Kind == Tool.Rectangle; + if (Kind == Tool.Glyph) + { + shape.Stroke = null; + shape.Fill = new UInkFill + { + Color = color, + Opacity = style.Opacity + }; + } + + shape.ShapeType = (int)(closed ? UInkShapeType.Polygon : UInkShapeType.Polyline); + var corners = Kind == Tool.Polygon && Recognized ? RectangleCorners() : null; + if (Kind == Tool.Rectangle || Kind == Tool.Ellipse || corners != null) + { + Point center; + Vector x, y; + if (Kind == Tool.Rectangle || corners != null) + { + if (corners == null && Data.Length != 10) + return null; + x = (P(corners == null ? 6 : corners[3]) - first) / 2; + y = (P(corners == null ? 2 : corners[1]) - first) / 2; + center = first + x + y; + if ((last-first).Length>0.001 || (P(corners == null ? 4 : corners[2])-(center+x+y)).Length>0.001) + return null; + } + else + { + center = first + (P(2) - first) / 2; + x = matrix.Transform(new Vector((Data[2] - Data[0]) / 2, 0)); + y = matrix.Transform(new Vector(0, (Data[3] - Data[1]) / 2)); + } + + double rx = x.Length, ry = y.Length; + if (rx <= 0 || ry <= 0) + return null; + if (Math.Abs(Vector.Multiply(x, y)) <= 1e-10 * rx * ry) + { + if (Kind == Tool.Ellipse && Math.Abs(rx - ry) <= 1e-10 * rx) + { + shape.ShapeType = (int)UInkShapeType.Circle; + shape.Geometry = new UInkCircleGeometry + { + CenterX = (float)center.X, + CenterY = (float)center.Y, + Radius = (float)rx + }; + } + else + { + shape.ShapeType = (int)(Kind == Tool.Ellipse ? UInkShapeType.Ellipse : UInkShapeType.Rectangle); + shape.Geometry = new UInkRectGeometry + { + CenterX = (float)center.X, + CenterY = (float)center.Y, + Width = (float)(2 * rx), + Height = (float)(2 * ry), + Rotation = (float)Math.Atan2(x.Y, x.X) + }; + } + + return shape; + } + + if (Kind == Tool.Ellipse) + shape.ShapeType = (int)UInkShapeType.Polygon; + } + + if (Kind == Tool.Ellipse || Kind == Tool.Arc || Kind == Tool.DashedArc) + { + var center = first + (P(2) - first) / 2; + var x = matrix.Transform(new Vector((Data[2] - Data[0]) / 2, 0)); + var y = matrix.Transform(new Vector(0, (Data[3] - Data[1]) / 2)); + // SHAPE-24:弦插值误差不超过 max|p''| * dt² / 8。 + double step = Math.Min(0.01, Math.Sqrt(2 / (x.Length + y.Length))); + if (!(step > 0) || Math.PI * 2 / step > UInkBlockScanner.MaxContainer) + return null; + Point At(double angle) => center + x * Math.Cos(angle) + y * Math.Sin(angle); + if (Kind != Tool.DashedArc) + { + double start = (ArcMask & 1) != 0 ? 0 : Math.PI; + double end = (ArcMask & 2) != 0 ? 2 * Math.PI : Math.PI; + if (Kind == Tool.Arc) + end = start + Math.Floor((end - start) / 0.01) * 0.01; + for (double angle = start; angle < end; angle += step) + Add(At(angle)); + if (Kind != Tool.Ellipse) + Add(At(end)); + } + else + { + // ICC 在半周边界重新起相位,末段还可能越过半周。用一条带精确段长的路径保留重叠。 + var dash = new List(); + Point previous = default; + for (int half = 0; half < 2; half++) + { + if ((ArcMask & (1 << half)) == 0) + continue; + for (double i = half; i < half + 1; i += 0.05 * 1.66) + { + var point = At(Math.PI * i); + if (dash.Count > 0) + dash.Add((float)(point - previous).Length); + Add(point); + previous = point; + double length = 0; + // 原生循环最后一个样点距起点 0.15 弧度。 + int samples = (int)Math.Ceiling(0.15 / step); + for (int j = 1; j <= samples; j++) + { + point = At(Math.PI * i + 0.15 * j / samples); + Add(point); + length += (point - previous).Length; + previous = point; + } + + dash.Add((float)length); + } + } + + dash.Add(0); + style.DashArray = dash; + } + } + else if (Kind == Tool.Line || Kind == Tool.Arrow || Kind == Tool.AxisArrow || Kind == Tool.Dash || Kind == Tool.Dot) + { + if (Kind == Tool.Line && Data.Length > 4) + { + // 识别出的直线可以有均匀插值点,但私有点列不能偏离公开线段或折返。 + var axis=last-first; + double length=axis.Length; + if (length==0) return null; + axis/=length; + double previous=0; + for (int i=2;i0.001 || alonglength+0.001) + return null; + previous=along; + } + } + if (Kind == Tool.Arrow || Kind == Tool.AxisArrow) + { + // 非相似变换会改变两翼的夹角与比例,保留 ICC 已变形的折线。 + var x = matrix.Transform(new Vector(1, 0)); + var y = matrix.Transform(new Vector(0, 1)); + if (Math.Abs(x.Length - y.Length) > 1e-10 * x.Length || Math.Abs(Vector.Multiply(x, y)) > 1e-10 * x.Length * y.Length) + { + double angle = Math.Atan2(Data[1] - Data[3], Data[0] - Data[2]); + double w = Kind == Tool.Arrow ? 15 : 20, h = Kind == Tool.Arrow ? 10 : 7; + var along = new Vector(Math.Cos(angle), Math.Sin(angle)); + var normal = new Vector(-along.Y, along.X); + Add(first); + Add(last); + Add(last + matrix.Transform(along * w + normal * h)); + Add(last); + Add(last + matrix.Transform(along * w - normal * h)); + return shape; + } + } + + Add(first); + Add(last); + shape.ShapeType = (int)UInkShapeType.Line; + if (Kind == Tool.Arrow || Kind == Tool.AxisArrow) + style.EndMarker = 1; + if (Kind == Tool.Dash || Kind == Tool.Dot) + { + double length = new Vector(Data[2] - Data[0], Data[3] - Data[1]).Length; + if (length == 0) + return null; + double scale = (last - first).Length / length; + style.DashArray = Kind == Tool.Dot ? new List + { + 0, + (float)(8.28 * scale) + } + + : new List + { + (float)(5 * scale), + (float)(8.8 * scale) + }; + if (Kind == Tool.Dot) + style.LineCap = 0; + } + } + else if (Kind == Tool.Parabola || Kind == Tool.Hyperbola) + { + if (!SampleBranch(Add)) + return null; + } + else + { + for (int i = 0; i < Data.Length; i += 2) + Add(P(i)); + } + + if (closed && path.Points.Count > 1 && path.Points[0].X == path.Points[^1].X && path.Points[0].Y == path.Points[^1].Y) + path.Points.RemoveAt(path.Points.Count - 1); + if (path.Points.Count < (closed ? 3 : 2)) + return null; + return shape; + } + + private List RectangleCorners() + { + if (Data.Length < 10 || Data[0] != Data[^2] || Data[1] != Data[^1]) + return null; + var corners = new List + { + 0 + }; + Vector previous = default; + for (int i = 2; i < Data.Length; i += 2) + { + var direction = new Vector(Data[i] - Data[i - 2], Data[i + 1] - Data[i - 1]); + if (direction.LengthSquared == 0) + continue; + direction.Normalize(); + if (previous.LengthSquared > 0 && (direction - previous).Length > 1e-6) + { + if (Math.Abs(Vector.Multiply(previous, direction)) > 1e-6 || corners.Count == 4) + return null; + corners.Add(i - 2); + } + + previous = direction; + } + + return corners.Count == 4 ? corners : null; + } + + private void Map(UInkCoordinateMap map, bool export) + { + Apply(map.ShapeMatrix(export)); + Width = export ? map.LengthFromDip(Width) : map.LengthToDip(Width); + } + + internal UInkShape Export(UInkCoordinateMap map) + { + Map(map, true); + var shape = PublicShape(); + if (shape == null) + return null; + // SHAPE-7:在设备坐标转成 float 后检查,退化虚线由调用方逐笔保存。 + if (shape.Stroke?.DashArray is { Count: > 0 } dash && + ((dash.Count & 1) != 0 || dash.Exists(value => !float.IsFinite(value) || value < 0) || + !dash.Exists(value => value > 0))) + return null; + if (Kind == Tool.Public) + { + if (Recognized) shape.Extra = new Dictionary { ["icc:recognized/v1"] = "1" }; + return shape; + } + // 对象层只来自公开 head/ref,避免复制对象后把旧 ID 带进私有配方。 + string id = ObjectId; + int index = Part, count = Count; + ulong revision = Revision; + ObjectId = null; + Part = Count = 0; + Revision = 1; + string payload = Payload(); + ObjectId = id; + Part = index; + Count = count; + Revision = revision; + if (payload.Length > 1000000) + return null; + shape.Extra = new Dictionary(); + for (int i = 0; i < payload.Length; i += 64000) + { + string key = i == 0 ? Key : Key + "/" + (i / 64000).ToString(System.Globalization.CultureInfo.InvariantCulture); + shape.Extra[key] = payload.Substring(i, Math.Min(64000, payload.Length - i)); + } + + if (Kind == Tool.Glyph) + shape.Extra["icc:glyph/v1"] = "1"; + if (Recognized) + shape.Extra["icc:recognized/v1"] = "1"; + return shape; + } + + internal static StrokeCollection Restore(UInkShape shape, UInkCoordinateMap map) + { + if (shape.Extra == null || !shape.Extra.TryGetValue(Key, out string payload)) + return null; + if (shape.Extra.ContainsKey(Key + "/1")) + { + var joined = new System.Text.StringBuilder(payload); + for (int i = 1; shape.Extra.TryGetValue(Key + "/" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), out string chunk); i++) + { + if (joined.Length + chunk.Length > 1000000) + return null; + joined.Append(chunk); + } + + payload = joined.ToString(); + } + + var d = Read(payload); + if (d == null || d.Kind == Tool.Public || (d.Kind == Tool.Glyph && !shape.Extra.ContainsKey("icc:glyph/v1"))) + return null; + // 私有配方只有在能再生相同公共块时才生效。窗口外的异常坐标和无限细分均走公共回退。 + if (!d.SafeNativeSize()) + return null; + var check = d.PublicShape(); + if (check == null || !PublicBytes(check).AsSpan().SequenceEqual(PublicBytes(shape))) + return null; + d.Map(map, false); + if (d.Width < DrawingAttributes.MinWidth || d.Width > DrawingAttributes.MaxWidth) + return null; + if (!d.SafeNativeSize()) + return null; + var strokes = d.Native(d.Attributes()); + if (strokes.Count == 0 || strokes.Count != d.Members) + return null; + d.ObjectId = shape.Object?.Id ?? shape.Object?.Ref; + d.Part = (int)(shape.Object?.PartIndex ?? 0); + d.Count = (int)(shape.Object?.PartCount ?? 0); + d.Revision = shape.Object?.Revision ?? 1; + d.Attach(strokes, 0); + return strokes; + } + + private bool SafeNativeSize() + { + if (Array.Exists(Frame, v => !double.IsFinite(v) || Math.Abs(v) > 1e15) || + Array.Exists(Data, v => !double.IsFinite(v) || Math.Abs(v) > 1e15)) + return false; + if (Kind == Tool.Dot || Kind == Tool.Dash) + { + double length = new Vector(Data[2] - Data[0], Data[3] - Data[1]).Length; + if (Math.Ceiling(length / (Kind == Tool.Dot ? 8.28 : 13.8)) > 65536) + return false; + } + + if (Kind == Tool.Parabola && (Data[3] < 0 || Data[3] > 500000)) + return false; + if (Kind == Tool.Hyperbola && (Data[2] <= 0 || Data[2] > 1e12 || Data[3] <= 0 || Data[4] <= 0 || Data[5] < Data[2] || + Data[5] - Data[2] > 500000)) + return false; + if (Kind == Tool.Hyperbola) + { + double expectedB = Data[6] == 1 ? Data[2] * Data[4] : Data[2] / Data[4]; + if (Math.Abs(Data[3]-expectedB) > Data[3]*1e-12 || Math.Abs(Data[7]) != 1) + return false; + } + if ((Kind == Tool.Ellipse || Kind == Tool.Arc || Kind == Tool.DashedArc || + Kind == Tool.Arrow || Kind == Tool.AxisArrow || Kind == Tool.Dash || Kind == Tool.Dot) && Data.Length != 4) + return false; + return Members <= 65536; + } + } +} diff --git a/Ink Canvas/UInk/IccShapeTools.cs b/Ink Canvas/UInk/IccShapeTools.cs new file mode 100644 index 000000000..edf685fe2 --- /dev/null +++ b/Ink Canvas/UInk/IccShapeTools.cs @@ -0,0 +1,275 @@ +using System; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Input; +using static Ink_Canvas.UInk.IccShapeDescriptor; + +namespace Ink_Canvas.UInk +{ + internal static class IccShapeTools + { + private static Stroke Line(DrawingAttributes da, Point a, Point b) => Between(Tool.Line, a, b).Preview(da)[0]; + internal static Stroke Rectangle(Point a, Point b, bool centered, DrawingAttributes da) + { + if (centered) + { + var start = b; + b = a + (a - b); + a = start; + } + + var part = new IccShapeDescriptor + { + Kind = Tool.Rectangle, + Data = new[] + { + a.X, + a.Y, + a.X, + b.Y, + b.X, + b.Y, + b.X, + a.Y, + a.X, + a.Y + } + }; + return part.Preview(da)[0]; + } + + internal static StrokeCollection Parallel(Point iniP, Point endP, DrawingAttributes da) + { + var strokes = new StrokeCollection(); + var d = (endP - iniP).Length; + if (d == 0) + return strokes; + var sinTheta = (iniP.Y - endP.Y) / d; + var cosTheta = (endP.X - iniP.X) / d; + var tanTheta = Math.Abs(sinTheta / cosTheta); + double x = 25; + if (Math.Abs(tanTheta) < 1.0 / 12) + { + sinTheta = 0; + cosTheta = 1; + endP.Y = iniP.Y; + } + + if (tanTheta < 0.63 && tanTheta > 0.52) //30 + { + sinTheta = sinTheta / Math.Abs(sinTheta) * 0.5; + cosTheta = cosTheta / Math.Abs(cosTheta) * 0.866; + endP.Y = iniP.Y - d * sinTheta; + endP.X = iniP.X + d * cosTheta; + } + + if (tanTheta < 1.08 && tanTheta > 0.92) //45 + { + sinTheta = sinTheta / Math.Abs(sinTheta) * 0.707; + cosTheta = cosTheta / Math.Abs(cosTheta) * 0.707; + endP.Y = iniP.Y - d * sinTheta; + endP.X = iniP.X + d * cosTheta; + } + + if (tanTheta < 1.95 && tanTheta > 1.63) //60 + { + sinTheta = sinTheta / Math.Abs(sinTheta) * 0.866; + cosTheta = cosTheta / Math.Abs(cosTheta) * 0.5; + endP.Y = iniP.Y - d * sinTheta; + endP.X = iniP.X + d * cosTheta; + } + + if (Math.Abs(cosTheta / sinTheta) < 1.0 / 12) + { + endP.X = iniP.X; + sinTheta = 1; + cosTheta = 0; + } + + strokes.Add(Line(da, new Point(iniP.X - 3 * x * sinTheta, iniP.Y - 3 * x * cosTheta), new Point(endP.X - 3 * x * sinTheta, endP.Y - 3 * x * cosTheta))); + strokes.Add(Line(da, new Point(iniP.X - x * sinTheta, iniP.Y - x * cosTheta), new Point(endP.X - x * sinTheta, endP.Y - x * cosTheta))); + strokes.Add(Line(da, new Point(iniP.X + x * sinTheta, iniP.Y + x * cosTheta), new Point(endP.X + x * sinTheta, endP.Y + x * cosTheta))); + strokes.Add(Line(da, new Point(iniP.X + 3 * x * sinTheta, iniP.Y + 3 * x * cosTheta), new Point(endP.X + 3 * x * sinTheta, endP.Y + 3 * x * cosTheta))); + return strokes; + } + + internal static StrokeCollection Axes(int mode, Point origin, Point end, bool ticks, DrawingAttributes da) + { + var strokes = new UInkStrokeCollection(); + double dx = end.X - origin.X, dy = end.Y - origin.Y; + bool shortX = mode == 12 || mode == 14, shortY = mode == 13 || mode == 14; + if ((shortX && Math.Abs(dx) < 0.01) || (shortY && Math.Abs(dy) < 0.01)) + return strokes; + var xStart = new Point(shortX ? origin.X - Math.Sign(dx) * 25 : 2 * origin.X - end.X + 20, origin.Y); + var yStart = new Point(origin.X, shortY ? origin.Y - Math.Sign(dy) * 25 : 2 * origin.Y - end.Y - 20); + var xEnd = new Point(end.X, origin.Y); + var yEnd = new Point(origin.X, end.Y); + Point? z = null; + if (mode == 17) + { + xStart = yStart = origin; + xEnd.X = origin.X + Math.Abs(dx); + yEnd.Y = origin.Y - Math.Abs(dy); + double distance = (Math.Abs(dx) + Math.Abs(dy)) / 2; + z = new Point(origin.X - distance / 1.76, origin.Y + distance / 1.76); + } + + strokes.Add(Between(Tool.AxisArrow, xStart, xEnd).Preview(da)); + strokes.Add(Between(Tool.AxisArrow, yStart, yEnd).Preview(da)); + if (z.HasValue) + strokes.Add(Between(Tool.AxisArrow, origin, z.Value).Preview(da)); + if (ticks) + AddCoordinateUnitMarks(strokes, origin, xStart, xEnd, yStart, yEnd, da, z); + return strokes; + } + + private const double CoordinateCentimeterUnitLength = 37.7952755906; + private static void AddCoordinateUnitMarks(UInkStrokeCollection strokes, Point origin, Point xAxisStart, Point xAxisEnd, Point yAxisStart, Point yAxisEnd, DrawingAttributes da, Point? zAxisEnd = null) + { + AddCoordinateAxisUnitMarks(da, strokes, origin, xAxisStart, xAxisEnd, CoordinateCentimeterUnitLength, new Vector(0, 1)); + AddCoordinateAxisUnitMarks(da, strokes, origin, yAxisStart, yAxisEnd, CoordinateCentimeterUnitLength, new Vector(1, 0)); + if (zAxisEnd is Point zEnd) + AddCoordinateAxisUnitMarks(da, strokes, origin, origin, zEnd, CoordinateCentimeterUnitLength, new Vector(1, 1)); + } + + private static void AddCoordinateAxisUnitMarks(DrawingAttributes da, UInkStrokeCollection strokes, Point origin, Point axisStart, Point axisEnd, double unitLength, Vector tickDirection) + { + var axisVector = axisEnd - origin; + var axisLength = axisVector.Length; + if (axisLength < 0.01) + return; + axisVector.Normalize(); + if (tickDirection.Length < 0.01) + tickDirection = new Vector(-axisVector.Y, axisVector.X); + tickDirection.Normalize(); + for (var distance = unitLength; distance <= axisLength; distance += unitLength) + { + var positiveUnitPoint = origin + axisVector * distance; + if (IsPointOnSegment(positiveUnitPoint, axisStart, axisEnd)) + strokes.AppendNew(Line(da, positiveUnitPoint - tickDirection * 5, positiveUnitPoint + tickDirection * 5)); + var negativeUnitPoint = origin - axisVector * distance; + if (IsPointOnSegment(negativeUnitPoint, axisStart, axisEnd)) + strokes.AppendNew(Line(da, negativeUnitPoint - tickDirection * 5, negativeUnitPoint + tickDirection * 5)); + } + } + + private static bool IsPointOnSegment(Point point, Point segmentStart, Point segmentEnd) + { + const double tolerance = 0.5; + return point.X >= Math.Min(segmentStart.X, segmentEnd.X) - tolerance && point.X <= Math.Max(segmentStart.X, segmentEnd.X) + tolerance && point.Y >= Math.Min(segmentStart.Y, segmentEnd.Y) - tolerance && point.Y <= Math.Max(segmentStart.Y, segmentEnd.Y) + tolerance; + } + + private static Stroke Focus(Point p, DrawingAttributes da) => + new Stroke(new StylusPointCollection { new StylusPoint(p.X, p.Y, 1) }, da.Clone()); + + internal static StrokeCollection EllipseWithFoci(Point start, Point end, DrawingAttributes da) + { + double a = Math.Abs(end.X - start.X), b = Math.Abs(end.Y - start.Y); + var axes = new Vector(a, b); + var strokes = Between(Tool.Ellipse, start - axes, start + axes).Preview(da); + if (a == b) return strokes; + double c = Math.Sqrt(Math.Abs(a * a - b * b)); + // HEAD 横轴焦点先右后左,纵轴焦点先上后下。 + var delta = a > b ? new Vector(c, 0) : new Vector(0, -c); + strokes.Add(Focus(start + delta, da)); + strokes.Add(Focus(start - delta, da)); + return strokes; + } + + internal static StrokeCollection ParabolaPreview(int mode, Point start, Point end, DrawingAttributes da) + { + double dx = end.X - start.X, dy = end.Y - start.Y; + if (Math.Abs(dx) < 0.01 || Math.Abs(dy) < 0.01) return new StrokeCollection(); + bool vertical = mode == 20; + double p = dy * dy / (-2 * dx); + double coefficient = mode == 22 ? 0.5 / p : vertical ? -dy / (dx * dx) : -dx / (dy * dy); + var strokes = Parabola(start, coefficient, Math.Abs(vertical ? dx : dy), vertical).Preview(da); + if (mode == 22) strokes.Add(Focus(new Point(start.X - p / 2, start.Y), da)); + return strokes; + } + + internal static StrokeCollection HyperbolaAsymptotes(Point start, Point end, DrawingAttributes da) + { + var opposite = new Point(2 * start.X - end.X, 2 * start.Y - end.Y); + return new StrokeCollection + { + Between(Tool.Dash, opposite, end).Preview(da), + Between(Tool.Dash, new Point(opposite.X, end.Y), new Point(end.X, opposite.Y)).Preview(da) + }; + } + + internal static StrokeCollection HyperbolaPreview(int mode, Point start, Point end, double slope, + StrokeCollection asymptotes, DrawingAttributes da) + { + double dx = end.X - start.X, dy = end.Y - start.Y; + bool horizontal = Math.Abs(dy / dx) < slope; + double a = Math.Sqrt(Math.Abs(horizontal ? dx * dx - dy * dy / (slope * slope) + : dy * dy - dx * dx * (slope * slope))); + double b = horizontal ? a * slope : a / slope; + // 保留第一步的原 Stroke 引用,收尾时从预览与撤回组中同步移除。 + var strokes = new StrokeCollection(); + if (asymptotes != null) strokes.Add(asymptotes); + foreach (double side in new[] { 1d, -1d }) + strokes.Add(Hyperbola(start, a, b, slope, Math.Abs(horizontal ? dx : dy), horizontal, side).Preview(da)); + if (mode == 25) + { + double c = Math.Sqrt(a * a + b * b); + var delta = horizontal ? new Vector(c, 0) : new Vector(0, c); + strokes.Add(Focus(start + delta, da)); + strokes.Add(Focus(start - delta, da)); + } + return strokes; + } + + internal static StrokeCollection TangentEllipse(Point start, Point end, DrawingAttributes da) + { + var strokes = Between(Tool.Arc, start, end, 1).Preview(da); + // HEAD 只保护实半弧;虚半弧仍允许参与 WinRT 识别。 + strokes[0].AddPropertyData(Helpers.ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + strokes.Add(Between(Tool.DashedArc, start, end, 2).Preview(da)); + Commit(strokes, 4); + return strokes; + } + + internal static StrokeCollection Solid(bool cylinder, Point start, Point end, DrawingAttributes da) + { + var strokes = new StrokeCollection(); + double top = Math.Min(start.Y, end.Y), bottom = Math.Max(start.Y, end.Y); + double ry = Math.Abs(end.X - start.X) / 2.646 / 2; + if (cylinder) + strokes.Add(Between(Tool.Ellipse, new Point(start.X, top - ry), new Point(end.X, top + ry)).Preview(da)); + var a = new Point(start.X, bottom - ry); + var b = new Point(end.X, bottom + ry); + strokes.Add(Between(Tool.Arc, a, b, 1).Preview(da)); + strokes.Add(Between(Tool.DashedArc, a, b, 2).Preview(da)); + double mid = (start.X + end.X) / 2; + strokes.Add(Line(da, new Point(cylinder ? start.X : mid, top), new Point(start.X, bottom))); + strokes.Add(Line(da, new Point(cylinder ? end.X : mid, top), new Point(end.X, bottom))); + return strokes; + } + + internal static StrokeCollection CuboidFront(Point a, Point b, DrawingAttributes da) => new() + { + Line(da, a, new Point(a.X, b.Y)), + Line(da, new Point(a.X, b.Y), b), + Line(da, b, new Point(b.X, a.Y)), + Line(da, a, new Point(b.X, a.Y)) + }; + internal static StrokeCollection CuboidBack(Point a, Point b, double depth, DrawingAttributes da) + { + var d = new Vector(depth, -depth); + var tr = new Point(b.X, a.Y); + var bl = new Point(a.X, b.Y); + var strokes = new StrokeCollection(); + strokes.Add(Line(da, a + d, tr + d)); + strokes.Add(Between(Tool.Dash, bl + d, b + d).Preview(da)); + strokes.Add(Line(da, a, a + d)); + strokes.Add(Line(da, tr, tr + d)); + strokes.Add(Between(Tool.Dash, bl, bl + d).Preview(da)); + strokes.Add(Line(da, b, b + d)); + strokes.Add(Between(Tool.Dash, a + d, bl + d).Preview(da)); + strokes.Add(Line(da, tr + d, b + d)); + return strokes; + } + } +} diff --git a/Ink Canvas/UInk/PptSlideStorage.cs b/Ink Canvas/UInk/PptSlideStorage.cs new file mode 100644 index 000000000..a85dacc0d --- /dev/null +++ b/Ink Canvas/UInk/PptSlideStorage.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Collections.ObjectModel; +using System.Linq; +using System.Windows.Ink; +using InkCanvasPPTAgent.Contracts; + +namespace Ink_Canvas.UInk +{ + // 有 ID 时位置不参与身份比较,旧 Agent / WPS 只使用位置。 + internal readonly record struct PptPageKey(int Position, int? SlideId) + { + internal static PptPageKey At(int position, int? id) => + id > 0 ? new PptPageKey(0, id) : new PptPageKey(position, null); + } + + internal sealed class PptSlideMap + { + private readonly Dictionary _indices = new(); + private readonly int[] _ids; + internal PptSlideMap(int[] ids) + { + _ids = ids == null ? Array.Empty() : (int[])ids.Clone(); + for (int i = 0; i < _ids.Length; i++) + if (_ids[i] > 0) _indices[_ids[i]] = i + 1; + } + + internal static PptSlideMap FromAgent(PPTState state) => new PptSlideMap(state.SlideIds); + + internal bool Complete => Count > 0 && _indices.Count == Count; + + internal bool AgreesWith(PptSlideMap confirmed) + { + if (Count != confirmed.Count) return false; + foreach (var pair in _indices) + if (confirmed.Resolve(pair.Key) != pair.Value) return false; + return true; + } + + internal PptPageKey Key(int position) => PptPageKey.At(position, + position > 0 && position <= _ids.Length ? _ids[position - 1] : null); + internal int? Resolve(int id) => _indices.TryGetValue(id, out int position) ? position : null; + internal int Count => _ids.Length; + + internal static UInkCanvas CaptureCanvas(string workspace, string device, string guid, + PptPageKey key, int position, int slideCount) + { + var canvas = UInkIccMapper.BuildPptCanvas(workspace, device, guid, (uint)(position - 1), key.SlideId); + if (position > slideCount) canvas.PageState = 1; + return canvas; + } + + // CANVAS-11:正常页按放映当前顺序输出,已消失但仍有内容的 ID 单独保留。 + internal List CaptureOrder(int count, IEnumerable occupied, + Func pageKey = null) + { + var pages = new List(count); + for (int i = 1; i <= count; i++) pages.Add(pageKey == null ? Key(i) : pageKey(i)); + var seen = pages.ToHashSet(); + foreach (var key in occupied) + if (seen.Add(key)) pages.Add(key); + return pages; + } + } + + internal interface IPptSlideStorage + { + byte[] Read(PptPageKey key); + void Write(PptPageKey key, byte[] ink); + void Clear(); + } + + internal sealed class PptSlideStorage : ReadOnlyDictionary, IPptSlideStorage + { + private readonly Dictionary _streams; + internal PptSlideStorage() : this(new Dictionary()) { } + private PptSlideStorage(Dictionary streams) : base(streams) => _streams = streams; + + public byte[] Read(PptPageKey key) + { + lock (_streams) return _streams.GetValueOrDefault(key)?.GetBuffer(); + } + + public void Write(PptPageKey key, byte[] ink) + { + lock (_streams) + { + if (_streams.TryGetValue(key, out var old)) old.Dispose(); + // 只发布完整 ISF 数组,读取方可在锁外解码,内存统计仍可枚举原始流。 + _streams[key] = new MemoryStream(ink, 0, ink.Length, false, true); + } + } + + public void Clear() + { + lock (_streams) + { + foreach (var stream in _streams.Values) stream.Dispose(); + _streams.Clear(); + } + } + + internal PptPageKey[] InkedKeys() + { + lock (_streams) return _streams.Where(pair => pair.Value.Length > 0).Select(pair => pair.Key).ToArray(); + } + + internal static byte[] Encode(StrokeCollection strokes) + { + if (strokes.Count == 0) return Array.Empty(); + using var stream = new MemoryStream(); + strokes.Save(stream); + return stream.ToArray(); + } + + internal static StrokeCollection Decode(byte[] ink) + { + if (ink == null || ink.Length == 0) return new StrokeCollection(); + using var stream = new MemoryStream(ink, false); + return new StrokeCollection(stream); + } + } +} diff --git a/Ink Canvas/UInk/UInkAppend.cs b/Ink Canvas/UInk/UInkAppend.cs index 06be23ee4..e37081ff8 100644 --- a/Ink Canvas/UInk/UInkAppend.cs +++ b/Ink Canvas/UInk/UInkAppend.cs @@ -9,6 +9,8 @@ namespace Ink_Canvas.UInk /// UInk 增量追加(可选崩溃保护路径)。只向既有对象流末尾最后一个 Canvas 追加已完整结束的 /// Ink/Shape/Media,不更新 Header(读取端按对象流重算状态)。不满足追加条件时调用方应回退完整保存。 /// + // SAVE-22/23:旧追加入口没有验证并截断坏尾,重做之前禁止接入。 + [Obsolete("追加前尚未按 SAVE-22/23 校验并截断,请使用完整保存。")] public static class UInkAppend { /// diff --git a/Ink Canvas/UInk/UInkBlockScanner.cs b/Ink Canvas/UInk/UInkBlockScanner.cs new file mode 100644 index 000000000..793c6cbb2 --- /dev/null +++ b/Ink Canvas/UInk/UInkBlockScanner.cs @@ -0,0 +1,76 @@ +using System; +using System.Buffers.Binary; + +namespace Ink_Canvas.UInk +{ + internal enum UInkFrame { Complete, Truncated, Malformed, LimitExceeded } + + internal static class UInkBlockScanner + { + internal const int MaxFile = 128 << 20, MaxObject = 32 << 20, MaxString = 8 << 20; + internal const int MaxContainer = 1_000_000, MaxDepth = 32, MaxPoints = 4_000_000; + + // FILE-16/17:只从已知边界进入,不在失败位置后搜索可疑的块头。 + internal static UInkFrame Scan(ReadOnlySpan bytes, out int length) + { + Span remaining = stackalloc int[MaxDepth + 1]; + int depth = 0; + remaining[0] = 1; + length = 0; + while (depth >= 0) + { + if (remaining[depth]-- == 0) { depth--; continue; } + if (length >= MaxObject) return UInkFrame.LimitExceeded; + if (length == bytes.Length) return UInkFrame.Truncated; + byte code = bytes[length++]; + if (code < 0x80 || code >= 0xe0) continue; + + int children = 0, prefix = 0; + uint payload = 0; + if (code < 0x90) children = 2 * (code & 15); + else if (code < 0xa0) children = code & 15; + else if (code < 0xc0) payload = (uint)(code & 31); + else switch (code) + { + case 0xc0: case 0xc2: case 0xc3: continue; + case 0xc1: return UInkFrame.Malformed; + case 0xcc: case 0xd0: payload = 1; break; + case 0xcd: case 0xd1: payload = 2; break; + case 0xce: case 0xd2: case 0xca: payload = 4; break; + case 0xcf: case 0xd3: case 0xcb: payload = 8; break; + case 0xd4: case 0xd5: case 0xd6: case 0xd7: case 0xd8: + payload = 1u + (1u << (code - 0xd4)); break; + case 0xc4: case 0xc7: case 0xd9: prefix = 1; break; + case 0xc5: case 0xc8: case 0xda: case 0xdc: case 0xde: prefix = 2; break; + default: prefix = 4; break; + } + if (prefix != 0) + { + if (length + prefix > MaxObject) return UInkFrame.LimitExceeded; + if (bytes.Length - length < prefix) return UInkFrame.Truncated; + var header = bytes.Slice(length, prefix); + uint count = prefix == 1 ? header[0] : prefix == 2 ? + BinaryPrimitives.ReadUInt16BigEndian(header) : BinaryPrimitives.ReadUInt32BigEndian(header); + length += prefix; + if (code >= 0xdc) + { + if (count > MaxContainer) return UInkFrame.LimitExceeded; + children = (int)count * (code >= 0xde ? 2 : 1); + } + else + { + if (count > MaxObject || (code >= 0xd9 && count > MaxString)) return UInkFrame.LimitExceeded; + payload = count + (code >= 0xc7 && code <= 0xc9 ? 1u : 0u); + } + } + if (length + (long)payload > MaxObject) return UInkFrame.LimitExceeded; + if (payload > bytes.Length - length) return UInkFrame.Truncated; + length += (int)payload; + // 空容器也有一层深度,不能用最后一个空 Map 绕过深度上限。 + if (depth == MaxDepth && (code < 0xa0 || code >= 0xdc)) return UInkFrame.LimitExceeded; + if (children > 0) remaining[++depth] = children; + } + return UInkFrame.Complete; + } + } +} diff --git a/Ink Canvas/UInk/UInkCaptureContext.cs b/Ink Canvas/UInk/UInkCaptureContext.cs new file mode 100644 index 000000000..c0909a470 --- /dev/null +++ b/Ink Canvas/UInk/UInkCaptureContext.cs @@ -0,0 +1,242 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace Ink_Canvas.UInk +{ + // UI 线程固定布局、资源来源和冻结位图,供后台生成媒体块。 + internal sealed class UInkCapturedElement + { + internal CanvasElementInfo Info; + internal int Owner; + internal BitmapSource Bitmap; + internal UInkBitmapFileStamp? BitmapStamp; + internal Matrix Transform; + internal Point Origin; + internal double Opacity; + internal Stretch Stretch; + internal Rect? BitmapRegion; + internal Rect? VideoPreview; + internal Matrix? LayoutMatrix; + internal UInkMedia PendingMedia; + internal bool LayoutDegraded; + internal UInkCoordinateMap LocalUnits; + internal bool Autoplay, Loop, IgnoreFit; + } + + internal sealed class UInkCaptureContext + { + internal List Devices; + internal UInkWorkspace Workspace; + internal readonly List Pages = new(); + internal UInkCanvas CurrentPptCanvas; + internal double DpiX, DpiY; + internal UInkMediaRestoreCache Resources; + private readonly Dictionary _pageResources = new(); + private readonly HashSet _leases = new(); + + internal void UsePageResources(UInkPageInput page, UInkMediaRestoreCache cache) + { + if (cache == null) return; + _pageResources[page] = cache; + if (_leases.Add(cache)) cache.Retain(); + } + + internal void ReleaseResources() + { + Resources?.Dispose(); + foreach (var lease in _leases) lease.Dispose(); + } + internal int DroppedMediaCount { get; private set; } + private readonly Dictionary _pendingMediaCoordinates = new(); + + internal void CapturePendingPage(UInkPageInput captured, UInkPageData pending, UInkCoordinateMap coordinates) + { + captured.DecodePending = pending.Materialize ?? pending.ReplayPptPage; + _pendingMediaCoordinates.Add(captured, coordinates); + } + + internal void CapturePreservedPptPage(UInkPageData saved, string device) + { + var canvas = UInkIccMapper.BuildCanvas(Workspace.Guid, device, saved.Canvas.PageGuid, + saved.Canvas.PageIndex, saved.Canvas.PageNumber, saved.SlideId, null); + canvas.Binding = saved.Binding; + canvas.PageKind = saved.PageKind; + canvas.PageState = saved.PageKind == 1 ? saved.Canvas.PageState : 1; + var page = new UInkPageInput { Canvas = canvas }; + Pages.Add(page); + CapturePendingPage(page, saved, UInkMediaMapper.PageCoordinates(saved.Canvas, DpiX, DpiY)); + } + + private bool _pptLayoutFinalized; + + internal void FinalizePptLayout() + { + // CANVAS-3、SAVE-14:完整保存先固定正常页序,保留页与结束页随后独立编号。 + var ordered = Pages.OrderBy(p => p.Canvas.PageKind == 1 ? 2 : p.Canvas.PageState == 1 ? 1 : 0).ToList(); + var guids = new HashSet(StringComparer.OrdinalIgnoreCase); + if (CurrentPptCanvas != null) guids.Add(CurrentPptCanvas.PageGuid); + Workspace.CurrentPageIndex = 0; + for (int i = 0; i < ordered.Count; i++) + { + var canvas = ordered[i].Canvas; + canvas.PageIndex = (uint)i; + if (canvas == CurrentPptCanvas) + { + if (canvas.PageState != 1) Workspace.CurrentPageIndex = (uint)i; + } + else if (!guids.Add(canvas.PageGuid)) + { + // FILE-8:两份独立内容不得写成同一 Canvas 的两次更新。 + do { canvas.PageGuid = Guid.NewGuid().ToString(); } while (!guids.Add(canvas.PageGuid)); + } + } + Pages.Clear(); + Pages.AddRange(ordered); + _pptLayoutFinalized = true; + } + + internal string Save(string path, bool timed, string sourcePath = null, UInkShowArchive archive = null, + Action committed = null) + { + using var resources = new UInkMediaWorkSet(); + var doc = BuildSnapshot(resources); + if (timed && !doc.Canvases.Exists(c => c.Blocks.Count > 0)) return null; + if (archive != null) return archive.Save(doc, path, resources.Resources, sourcePath, DroppedMediaCount); + return UInkSaveService.SaveSnapshot(doc, path, resources.Resources, sourcePath, committed); + } + + internal byte[] ArchiveContentDigest() + { + using var resources = new UInkMediaWorkSet(); + return UInkShowArchive.ContentDigest(BuildSnapshot(resources)); + } + + private UInkDocument BuildSnapshot(UInkMediaWorkSet resources) + { + if (!_pptLayoutFinalized && Workspace?.WorkspaceType == (int)UInkWorkspaceType.Presentation) + FinalizePptLayout(); + var coordinates = new UInkCoordinateMap(DpiX, DpiY); + var notes = new Dictionary(); + void Note(string key) => notes[key] = notes.GetValueOrDefault(key) + 1; + + DroppedMediaCount = 0; + void Drop(string rule) + { + DroppedMediaCount++; + Note(rule); + } + + string ArchiveImported(UInkMedia media, UInkMediaRestoreCache cache) + { + try + { + string file = cache?.GetVerifiedPath(media.Path, media.MimeType); + if (file == null) return null; + if (!media.MimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) + return resources.Add(file, null, media.MimeType); + var bitmap = cache.GetBitmap(file); + if (bitmap == null) return null; + cache.GetPreparedBitmap(file, out var stamp); + string entry = resources.Add(file, bitmap, media.MimeType, stamp); + if (entry != null) return entry; + media.MimeType = "image/png"; + return resources.Add(null, bitmap, media.MimeType); + } + catch (Exception ex) when (UInkMediaMapper.IsResourceFailure(ex)) + { + return null; + } + } + + var output = new List(Pages.Count); + foreach (var captured in Pages) + { + var cache = _pageResources.GetValueOrDefault(captured) ?? Resources; + var page = new UInkPageInput { Canvas = captured.Canvas, Strokes = captured.Strokes, + GlyphFallbacks = captured.GlyphFallbacks }; + page.StrokeOwners.AddRange(captured.StrokeOwners); + output.Add(page); + if (captured.DecodePending != null) + { + // 未翻到的页只读原始索引,在工作线程生成独占笔迹,绝不借用即将显示的对象。 + var decoded = new UInkPageData(); + captured.DecodePending(decoded); + if (!captured.PendingMediaOnly) page.Strokes = decoded.FinalStrokes; + var imported = _pendingMediaCoordinates.GetValueOrDefault(captured) ?? coordinates; + // 一个公共 Shape 可能展开成多条原生笔画,按实际撤回组填写每条笔画的创建序号。 + if (!captured.PendingMediaOnly) + for (int group = 0; group < decoded.History.Length; group++) + for (int i = 0; i < (decoded.History[group].CurrentStroke?.Count ?? 0); i++) + page.StrokeOwners.Add(group); + foreach (var item in decoded.Items) + { + if (item.Block is UInkMedia original) + { + var media = original.CopyForSave(); + media.Path = ArchiveImported(media, cache); + if (media.Path == null) { Drop("EXTRA-11"); continue; } + // 离页也要把原视口烘焙入矩阵,局部框和资源 crop 保持原单位。 + media.Transform = coordinates.MediaMatrixFromDip(imported.MapMediaMatrix(original.Transform), imported); + page.Media.Add(media); + page.MediaOwners.Add(item.Group); + } + } + } + + foreach (var element in captured.Elements) + { + if (element.LayoutDegraded) Note("mediaLayoutTransform"); + var pending = element.PendingMedia; + if (pending == null && element.Info.SourcePath == null && element.Bitmap == null) + { + Drop("EXTRA-11"); + continue; + } + string mime = pending?.MimeType ?? (element.Info.SourcePath == null ? "image/png" : + UInkExtraArchive.MimeForPath(element.Info.SourcePath)); + var media = UInkMediaMapper.Capture(element, coordinates, mime); + if (media == null) { Note("MEDIA-13"); continue; } + + if (pending != null) + { + var layout = media; + media = pending.CopyForSave(); + media.Width = pending.Width.HasValue ? layout.Width : null; + media.Height = pending.Height.HasValue ? layout.Height : null; + media.Transform = layout.Transform; + media.Opacity = layout.Opacity; + if (element.VideoPreview.HasValue) media.Extra = layout.Extra; + media.Path = ArchiveImported(media, cache); + } + else + { + media.Path = element.Info.SourcePath == null ? null : + resources.Add(element.Info.SourcePath, element.Bitmap, mime, element.BitmapStamp); + if (media.Path == null && element.Bitmap != null) + { + // EXTRA-10:用已冻结的画布位图;原生布局的可见区域在写端打包。 + media.MimeType = "image/png"; + var bitmap = element.BitmapRegion is Rect region + ? UInkMediaMapper.BakeBitmapRegion(element.Bitmap, region) : element.Bitmap; + media.Path = resources.Add(null, bitmap, media.MimeType); + } + } + if (media.Path == null) { Drop("EXTRA-11"); continue; } + page.Media.Add(media); + page.MediaOwners.Add(element.Owner); + } + } + + var doc = UInkIccMapper.BuildDocument(UInkIccMapper.NewFileGuid(), Devices, new[] { Workspace }, + output, (ulong)DateTimeOffset.UtcNow.ToUnixTimeSeconds(), DpiX, DpiY, Note); + foreach (var entry in notes) + Helpers.LogHelper.WriteLogToFile($"UInk {entry.Key}: {entry.Value}", Helpers.LogHelper.LogType.Warning); + return doc; + } + } +} diff --git a/Ink Canvas/UInk/UInkContentDecoder.cs b/Ink Canvas/UInk/UInkContentDecoder.cs new file mode 100644 index 000000000..a0c76bf03 --- /dev/null +++ b/Ink Canvas/UInk/UInkContentDecoder.cs @@ -0,0 +1,208 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using MessagePack; + +namespace Ink_Canvas.UInk +{ + internal sealed partial class UInkDecoder + { + private static readonly UInkSchema InkKeys = new(8, "type contentId undoId inkType color opacity texture points nib cap renderOnlyWhenLatest extra"); + private static readonly UInkSchema PointKeys = new(3, "x y width color opacity"); + private static readonly UInkSchema XYKeys = new(2, "x y"); + private static readonly UInkSchema ColorKeys = new(1, "fallback space components"); + private static readonly UInkSchema NibKeys = new(0, "shape aspect orientation"); + private static readonly UInkSchema ClearKeys = new(3, "type contentId undoId extra"); + private static readonly UInkSchema MediaKeys = new(5, "type contentId undoId path mimeType width height transform opacity fit crop pageCount pageIndex autoplay loop volume startTime playbackRate extra"); + private static readonly UInkSchema CropKeys = new(4, "x y width height"); + + private static readonly UInkSchema UndoIdKey = new(1, "undoId"); + + internal static uint? ReadUndoId(UInkValue raw) + { + var r = raw.Reader(); + int count = r.ReadMapHeader(); + uint? undo = null; + for (int i = 0; i < count; i++) + { + if (UndoIdKey.Key(ref r) == 0) + { + // TYPE-7:重复 undoId 无法确定物理组,按不可读处理。 + if (undo.HasValue) return null; + try { undo = (uint)UInkNumeric.Unsigned(ref r, uint.MaxValue); } + catch (UInkFieldException) { return null; } + } + else r.Skip(); + } + return undo; + } + + internal UInkContentBlock Content(int type, UInkValue raw) + { + switch ((UInkBlockType)type) + { + case UInkBlockType.Ink: return Ink(raw); + case UInkBlockType.Shape: return Shape(raw); + case UInkBlockType.Media: return Media(raw); + case UInkBlockType.Clear: + var f = Fields(raw, ClearKeys); + return new UInkClear { ContentId = f["contentId"].UInt(), UndoId = f["undoId"].UInt(), Extra = Extra(f) }; + default: throw new UInkFieldException(); + } + } + + private UInkColor Color(UInkValue raw) + { + var f = Fields(raw, ColorKeys); + uint rgb = f["fallback"].UInt(); + if (rgb > 0xffffff) result.Note("COLOR-3"); + var color = new UInkColor { Fallback = rgb & 0xffffff }; + if (f["space"].Present || f["components"].Present) + { + try + { + string space = f["space"].Text(); + var components = f["components"].Vector(3); + if (space != "scrgb" && (space != "srgb" || Array.Exists(components, c => c < 0 || c > 1))) + throw new UInkFieldException(); + color.Space = space; color.Components = components; + } + catch (UInkFieldException) { result.Note("COLOR-2"); } + } + return color; + } + + private UInkNib Nib(UInkValue raw) + { + var f = Fields(raw, NibKeys); + var nib = new UInkNib { Shape = f["shape"].Enum(result, 1, "NIB-7") ?? 0, + Orientation = f["orientation"].Enum(result, 1, "NIB-7") ?? 0 }; + if (nib.Shape == 1) nib.Aspect = f["aspect"].Positive(); + return nib; + } + + private UInkInk Ink(UInkValue raw) + { + var f = Fields(raw, InkKeys); + var ink = new UInkInk { ContentId = f["contentId"].UInt(), UndoId = f["undoId"].UInt(), + InkType = f["inkType"].Int(), Texture = f["texture"].Int(), Color = Color(f["color"]), + Opacity = f["opacity"].Unit(result, "INK-18"), Extra = Extra(f), + Nib = Recover(f["nib"], Nib, "NIB-6"), + RenderOnlyWhenLatest = f["renderOnlyWhenLatest"].Present && f["renderOnlyWhenLatest"].Bool() }; + // NIB-3:矩形笔尖的端帽字段不适用,连字段类型也无需解释。 + if (ink.Nib?.Shape != 1) ink.Cap = f["cap"].Enum(result, 2, "NIB-7"); + if (ink.InkType < 0 || ink.InkType > 3) result.Note("INK-13"); + if (ink.Texture != 0) result.Note("INK-14"); // 留存原值供映射层识别。 + var r = f["points"].Reader(); + if (r.NextMessagePackType != MessagePackType.Array) throw new UInkFieldException(); + int n = r.ReadArrayHeader(); + if (n == 0) throw new UInkFieldException(); + result.ReservePoints(n); + ink.Points = new UInkPoint[n]; + if (!ReadSimplePoints(f["points"].Span.Slice((int)r.Consumed), ink.Points)) + for (int i = 0; i < n; i++) ink.Points[i] = Point(ref r, ink, i); + return ink; + } + + // 常见 wire 是 fixmap(3) + x/y/width 三个 float32(每点 26 字节)。 + // 只有键、编码和边界全部匹配才走直读;乱序、锚点及其他合法数值编码走通用路径。 + private static bool ReadSimplePoints(ReadOnlySpan data, UInkPoint[] points) + { + if (data.Length != points.Length * 26) return false; + for (int i = 0; i < points.Length; i++, data = data.Slice(26)) + { + if (data[0] != 0x83 || data[1] != 0xa1 || data[2] != 'x' || data[3] != 0xca || + data[8] != 0xa1 || data[9] != 'y' || data[10] != 0xca || data[15] != 0xa5 || + !data.Slice(16, 5).SequenceEqual(PointKeys.Keys[2]) || data[21] != 0xca) + return false; + float x = BinaryPrimitives.ReadSingleBigEndian(data.Slice(4)); + float y = BinaryPrimitives.ReadSingleBigEndian(data.Slice(11)); + float width = BinaryPrimitives.ReadSingleBigEndian(data.Slice(22)); + if (!float.IsFinite(x) || !float.IsFinite(y) || !float.IsFinite(width) || width <= 0) + throw new UInkFieldException(); + points[i] = new UInkPoint(x, y, width); + } + return true; + } + + // 点的基本字段在栈上直接解码,只有 INK-12 成对锚点才创建样式对象。 + private UInkPoint Point(ref MessagePackReader r, UInkInk ink, int index) + { + if (r.NextMessagePackType != MessagePackType.Map) throw new UInkFieldException(); + int n = r.ReadMapHeader(), seenMask = 0; + float x = 0, y = 0, width = 0, opacity = 0; + UInkColor color = null; + var keys = ink == null ? XYKeys : PointKeys; + for (int j = 0; j < n; j++) + { + int key = keys.Key(ref r); + if (key < 0) { r.Skip(); result.Note("TYPE-8"); continue; } + int bit = 1 << key; + if ((seenMask & bit) != 0) throw new UInkDuplicateKey(); + seenMask |= bit; + switch (key) + { + case 0: x = UInkNumeric.Single(ref r); break; + case 1: y = UInkNumeric.Single(ref r); break; + case 2: width = UInkNumeric.Single(ref r); break; + case 3: color = Color(UInkValue.Take(ref r)); break; + case 4: opacity = UInkValue.Take(ref r).Unit(result, "INK-18"); break; + } + } + if ((seenMask & keys.RequiredMask) != keys.RequiredMask || (ink != null && width <= 0)) throw new UInkFieldException(); + if ((seenMask & 24) != 0) + { + if ((seenMask & 24) != 24) throw new UInkFieldException(); + (ink.StyleAnchors ??= new()).Add((index, color, opacity)); + } + return new UInkPoint(x, y, width); + } + + private UInkCrop Crop(UInkValue raw) + { + var f = Fields(raw, CropKeys); + return new UInkCrop { X = f["x"].Float(), Y = f["y"].Float(), Width = f["width"].Positive(), Height = f["height"].Positive() }; + } + + private UInkMedia Media(UInkValue raw) + { + var f = Fields(raw, MediaKeys); + var m = new UInkMedia { ContentId = f["contentId"].UInt(), UndoId = f["undoId"].UInt(), + Path = f["path"].Text(), MimeType = f["mimeType"].Text(), Extra = Extra(f), + Fit = f["fit"].Enum(result, 3, "MEDIA-3"), Crop = Recover(f["crop"], Crop, "MEDIA-3"), + PageCount = f.UInt("pageCount"), PageIndex = f.UInt("pageIndex") }; + if (m.Path.Length == 0 || m.MimeType.Length == 0) throw new UInkFieldException(); + bool visual = UInkMedia.IsVisualMime(m.MimeType); + if (visual || f["width"].Present) m.Width = f["width"].Positive(); + if (visual || f["height"].Present) m.Height = f["height"].Positive(); + if (f["transform"].Present) + { + try { m.Transform = f["transform"].Vector(6); } + catch (UInkFieldException) { m.Transform = UInkMedia.IdentityMatrix(); result.Note("MEDIA-2"); } + } + else if (visual) + { + // MEDIA-2:合法省略使用单位矩阵并提示,不触发另存。 + m.Transform = UInkMedia.IdentityMatrix(); + result.Note("MEDIA-2", false); + } + // PDF 字段表要求页数为正;MEDIA-9 仍允许从实际文档获取页数。 + if (m.PageCount == 0) { m.PageCount = null; result.Note("MEDIA-9"); } + if (f["opacity"].Present) m.Opacity = f["opacity"].Unit(result, "MEDIA-12"); + if (f["volume"].Present) m.Volume = f["volume"].Unit(result, "MEDIA-12"); + if (f["loop"].Present) m.Loop = f["loop"].Bool(); + if (f["autoplay"].Present) m.Autoplay = f["autoplay"].Bool(); + if (f["startTime"].Present) + { + m.StartTime = f["startTime"].Double(); + if (m.StartTime < 0) { m.StartTime = 0; result.Note("MEDIA-10"); } + } + if (f["playbackRate"].Present) + { + try { m.PlaybackRate = f["playbackRate"].Positive(); } + catch (UInkFieldException) { result.Note("MEDIA-10"); } + } + return m; + } + } +} diff --git a/Ink Canvas/UInk/UInkConversion.cs b/Ink Canvas/UInk/UInkConversion.cs index a592eca47..005cd3197 100644 --- a/Ink Canvas/UInk/UInkConversion.cs +++ b/Ink Canvas/UInk/UInkConversion.cs @@ -1,132 +1,240 @@ using System; using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; +using Ink_Canvas.Helpers; +using System.Windows; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; namespace Ink_Canvas.UInk { - /// - /// ICC WPF 墨迹模型 ⇄ UInk Ink 块 的双向转换。 - /// 语义(对应方案决策): - /// - inkType 统一 = Pen(1); - /// - 块级 opacity 承载 ICC 的 alpha(AARRGGBB 的 A):写 opacity = A / 255f,读回 A = (byte)(opacity * 255f); - /// - 剩余 DrawingAttributes(Width/Height/FitToCurve/IsHighlighter/IgnorePressure/StylusTip)经 extra["icc:da"] - /// 私有键无损往返;读取端有 icc:da 用 icc:da,否则从块级字段推导(外部文件回退,透明度仍尊重块级 opacity)。 - /// + /// ICC WPF 墨迹与 UInk 公共几何、样式的转换。 public static class UInkConversion { - /// 私有扩展键:序列化的 ICC DrawingAttributes 字符串。 - public const string IccDaKey = "icc:da"; + // P3 在收笔时写入 int 型 UInkInkType;Native 荧光笔可能没有设置 DA.IsHighlighter。 + public static readonly Guid LogicalPenKindGuid = new("fe1d49b1-071b-47bc-8ff8-280e1af1d25f"); + public static readonly Guid ImportedOpacityGuid = new("5ecccf6a-c176-4567-9ab9-7bceeed2c8c3"); + internal static void SetLogicalPenKind(Stroke stroke, bool highlighter) => + stroke.AddPropertyData(LogicalPenKindGuid, (int)(highlighter ? UInkInkType.Highlighter : UInkInkType.Pen)); - // ---------- Stroke → UInkInk ---------- + public static bool IsLogicalHighlighter(Stroke stroke) => stroke.DrawingAttributes.IsHighlighter || + (stroke.ContainsPropertyData(LogicalPenKindGuid) && stroke.GetPropertyData(LogicalPenKindGuid) is int kind && + kind == (int)UInkInkType.Highlighter); - public static UInkInk StrokeToInk(Stroke stroke, uint contentId = 0, uint undoId = 0) + public static UInkInk StrokeToInk(Stroke stroke, uint contentId = 0, uint undoId = 0, + UInkCoordinateMap map = null, Action note = null) { + if (stroke.ContainsPropertyData(InkFadeManager.LaserRenderModeGuid)) return null; + map ??= UInkCoordinateMap.Identity; var da = stroke.DrawingAttributes; + bool rectangle = da.StylusTip == StylusTip.Rectangle; + var transform = da.StylusTipTransform; + double w = da.Width, h = da.Height; + double wx = w * transform.M11, hx = h * transform.M21; + double wy = w * transform.M12, hy = h * transform.M22; + double diameter; + if (rectangle) + { + // NIB-2/3:斜交矩形用轴对齐外接框近似,纯轴缩放或交换两轴保持精确。 + bool aligned = (transform.M12 == 0 && transform.M21 == 0) || + (transform.M11 == 0 && transform.M22 == 0); + if (!aligned) note?.Invoke("tipTransformApprox"); + w = Math.Abs(wx) + Math.Abs(hx); + h = Math.Abs(wy) + Math.Abs(hy); + diameter = h; + } + else + { + // INK-5:圆形回退保持椭圆面积,纯旋转不会改变等效直径。 + if (wx * wx + hx * hx != wy * wy + hy * hy || wx * wy + hx * hy != 0) + note?.Invoke("ellipseWidthApprox"); + diameter = Math.Sqrt(w * h * Math.Abs(transform.Determinant)); + } + // INK-9/10:优先保留导入的公共值。原生 WPF 荧光使用固定 0.5 的容器透明度。 + float opacity = stroke.ContainsPropertyData(ImportedOpacityGuid) && + stroke.GetPropertyData(ImportedOpacityGuid) is float imported + ? imported : da.IsHighlighter ? 0.5f : da.Color.A / 255f; + var points = da.FitToCurve ? stroke.GetBezierStylusPoints() : stroke.StylusPoints; var ink = new UInkInk { - ContentId = contentId, - UndoId = undoId, - InkType = (int)UInkInkType.Pen, // 统一普通笔 - Color = new UInkColor { Fallback = RgbOf(da.Color) }, - Opacity = da.Color.A / 255f, // 块级 opacity 承载 alpha - Texture = 0, - Extra = new Dictionary { [IccDaKey] = SerializeDrawingAttributes(da) }, + ContentId = contentId, UndoId = undoId, + InkType = IsLogicalHighlighter(stroke) ? (int)UInkInkType.Highlighter : (int)UInkInkType.Pen, + Color = new UInkColor { Fallback = RgbOf(da.Color) }, Opacity = opacity, + Nib = rectangle ? new UInkNib { Shape = 1, Aspect = (float)(w / h), Orientation = 0 } : null, + Points = new UInkPoint[points.Count] }; - - var sps = stroke.StylusPoints; + if (rectangle && (!float.IsFinite(ink.Nib.Aspect.Value) || ink.Nib.Aspect.Value <= 0)) + throw new InvalidOperationException("Nib aspect exceeds the UInk float32 range."); bool ignorePressure = da.IgnorePressure; - float baseWidth = (float)da.Width; - for (int i = 0; i < sps.Count; i++) + var previous = new Point(); + for (int i = 0; i < points.Count; i++) { - var p = sps[i]; - // UInk width = 该点完整直径;WPF 渲染宽度 = DA.Width * PressureFactor - float width = ignorePressure - ? Math.Max(0.01f, baseWidth) - : Math.Max(0.01f, baseWidth * p.PressureFactor); - ink.Points.Add(new UInkInkPoint - { - X = i == 0 ? (float)p.X : (float)(p.X - sps[i - 1].X), // 首点绝对,后续相对 - Y = i == 0 ? (float)p.Y : (float)(p.Y - sps[i - 1].Y), - Width = width, - }); + var p = points[i]; + var absolute = map.FromDip(p.X, p.Y); + float q = ignorePressure ? 1f : 0.25f + 1.5f * p.PressureFactor; + var point = new UInkPoint((float)(absolute.X - previous.X), (float)(absolute.Y - previous.Y), + (float)map.LengthFromDip(q * diameter)); + if (!float.IsFinite(point.X) || !float.IsFinite(point.Y) || !float.IsFinite(point.Width) || point.Width <= 0) + throw new InvalidOperationException("Ink geometry exceeds the UInk float32 range."); + ink.Points[i] = point; + previous = absolute; } + if (stroke.ContainsPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid)) + ink.Extra = new Dictionary { ["icc:recognized/v1"] = "1" }; + if (ink.Points.Length == 1 && stroke.ContainsPropertyData(IccShapeDescriptor.FocusProperty)) + WriteFocusStyle(stroke, ink, map); return ink; } public static List StrokesToInks(StrokeCollection strokes, uint startContentId = 0, uint undoId = 0) { var inks = new List(strokes.Count); - uint cid = startContentId; - foreach (Stroke s in strokes) - inks.Add(StrokeToInk(s, cid++, undoId)); + foreach (var stroke in strokes) + { + var ink = StrokeToInk(stroke, startContentId, undoId); + if (ink == null) continue; + inks.Add(ink); + startContentId++; + undoId++; + } return inks; } - // ---------- UInkInk → Stroke ---------- - public static StrokeCollection InksToStrokes(IEnumerable inks) { - var strokes = new StrokeCollection(); + var strokes = new UInkStrokeCollection(); foreach (var ink in inks) { var stroke = InkToStroke(ink); - if (stroke != null) strokes.Add(stroke); + if (stroke != null) strokes.AppendNew(stroke); } return strokes; } - public static Stroke InkToStroke(UInkInk ink) + public static Stroke InkToStroke(UInkInk ink, UInkCoordinateMap map = null, Action note = null) { - if (ink.Points == null || ink.Points.Count == 0) return null; - - // 块级透明度:alpha = opacity * 255(尊重外部文件,保证透明度统一) - byte alpha = (byte)Math.Max(0, Math.Min(255, Math.Round(ink.Opacity * 255f))); - - DrawingAttributes da; - if (ink.Extra != null && ink.Extra.TryGetValue(IccDaKey, out var daStr) && !string.IsNullOrEmpty(daStr)) - { - da = ParseDrawingAttributes(daStr); - var c = da.Color; c.A = alpha; da.Color = c; // 块级 opacity 覆盖 alpha - } - else + if (ink.InkType == (int)UInkInkType.Erase) { note?.Invoke("INK-11"); return null; } + if (ink.Points == null || ink.Points.Length == 0) return null; + map ??= UInkCoordinateMap.Identity; + float min = float.MaxValue, max = 0; + foreach (var p in ink.Points) { - da = new DrawingAttributes(); - uint fb = ink.Color?.Fallback ?? 0; - da.Color = Color.FromArgb(alpha, (byte)(fb >> 16), (byte)(fb >> 8), (byte)fb); + min = Math.Min(min, p.Width); + max = Math.Max(max, p.Width); } + bool constant = min == max; + bool rectangle = ink.Nib?.Shape == 1; + if (rectangle && ink.Nib.Orientation == 1) note?.Invoke("nibDirectionApprox"); + if (!rectangle && ink.Cap.GetValueOrDefault() != 0) note?.Invoke("capApprox"); + bool advanced = ink.InkType == (int)UInkInkType.AdvancedHighlighter; + if (advanced) note?.Invoke("INK-12"); + if (ink.Color?.Components != null) note?.Invoke("COLOR-2"); - float maxWidth = ink.Points.Max(p => p.Width); - if (maxWidth <= 0f) maxWidth = 1f; - da.Width = maxWidth; - da.Height = maxWidth; + double aspect = rectangle ? ink.Nib.Aspect ?? 1 : 1; + double maxDip = map.LengthToDip(max); + if (!double.IsFinite(maxDip) || !double.IsFinite(aspect) || maxDip <= 0 || aspect <= 0 || min <= 0) + return null; + // INK-5 / D4:共同基准须同时满足压力范围、DA 高度与 B·aspect 的宽度限制。 + // float32 写回可使合法的 7:1 略微超界,比较时留相对舍入容差。 + double pressureMin = constant ? maxDip : maxDip / 1.75; + double pressureMax = constant ? maxDip : map.LengthToDip(min) * 4 * (1 + 1e-6); + if (pressureMin > pressureMax) note?.Invoke("widthRangeApprox"); + double tipMin = Math.Max(DrawingAttributes.MinHeight, DrawingAttributes.MinWidth / aspect); + double tipMax = Math.Min(DrawingAttributes.MaxHeight, DrawingAttributes.MaxWidth / aspect); + double basis = pressureMin; + if (tipMin <= tipMax) basis = Math.Clamp(basis, tipMin, tipMax); + if (tipMin > tipMax || tipMax < pressureMin || tipMin > Math.Max(pressureMax, pressureMin)) + note?.Invoke("tipSizeApprox"); + var da = new DrawingAttributes + { + IgnorePressure = constant, FitToCurve = false, + IsHighlighter = advanced || ink.InkType == (int)UInkInkType.Highlighter, + StylusTip = rectangle ? StylusTip.Rectangle : StylusTip.Ellipse, + Width = Math.Clamp(basis * aspect, DrawingAttributes.MinWidth, DrawingAttributes.MaxWidth), + Height = Math.Clamp(basis, DrawingAttributes.MinHeight, DrawingAttributes.MaxHeight), + Color = BlockColor(ink.Color, ink.Opacity) + }; - var sps = new StylusPointCollection(); - float cx = 0f, cy = 0f; + basis = da.Height; + double x = 0, y = 0; + var points = new StylusPointCollection(ink.Points.Length); foreach (var p in ink.Points) { - cx += p.X; // 累加 delta 还原绝对坐标 - cy += p.Y; - float pressure = da.IgnorePressure - ? 0.5f - : Math.Max(0f, Math.Min(1f, p.Width / maxWidth)); - sps.Add(new StylusPoint(cx, cy, pressure)); + // INK-4:位移先按 double 累加,再以绝对坐标映射视口。 + x += p.X; + y += p.Y; + var dip = map.ToDip(x, y); + if (!CanCreateStylusPoint(dip)) + { + note?.Invoke("coordinateRange"); + return null; + } + float pressure = constant ? 0.5f : (float)Math.Clamp((map.LengthToDip(p.Width) / basis - 0.25) / 1.5, 0, 1); + points.Add(new StylusPoint(dip.X, dip.Y, pressure)); } - return new Stroke(sps) { DrawingAttributes = da }; + var stroke = new Stroke(points, da); + stroke.AddPropertyData(ImportedOpacityGuid, ink.Opacity); + if (ink.Extra != null && ink.Extra.TryGetValue("icc:recognized/v1", out string flag) && flag == "1") + stroke.AddPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + if (ink.Points.Length == 1 && ink.Extra != null && ink.Extra.TryGetValue("icc:focus/v1", out string focus)) + RestoreFocusStyle(stroke, ink, map, focus); + return stroke; + } + + // ICC 焦点保持 Ink。公共可见宽度相同的单点可以有不同的 DA 基准宽与压力。 + private static void WriteFocusStyle(Stroke stroke, UInkInk ink, UInkCoordinateMap map) + { + var da = stroke.DrawingAttributes; + if (da.Width != da.Height || ink.Nib != null || !da.StylusTipTransform.IsIdentity) return; + float pressure = stroke.StylusPoints[0].PressureFactor; + int flags = (da.IgnorePressure ? 1 : 0) | (da.FitToCurve ? 2 : 0); + (ink.Extra ??= new Dictionary())["icc:focus/v1"] = + FormattableString.Invariant($"{flags},{pressure:R},{map.LengthFromDip(da.Width):R}"); + } + + private static void RestoreFocusStyle(Stroke stroke, UInkInk ink, UInkCoordinateMap map, string payload) + { + var parts = payload.Split(','); + var culture = System.Globalization.CultureInfo.InvariantCulture; + var number = System.Globalization.NumberStyles.Float; + if (ink.Nib != null || parts.Length != 3 || !int.TryParse(parts[0], out int flags) || flags < 0 || flags > 3 || + !float.TryParse(parts[1], number, culture, out float pressure) || !(pressure >= 0 && pressure <= 1) || + !double.TryParse(parts[2], number, culture, out double basis)) return; + float factor = (flags & 1) != 0 ? 1f : 0.25f + 1.5f * pressure; + double width = map.LengthToDip(basis); + if (!(width >= DrawingAttributes.MinWidth && width <= DrawingAttributes.MaxWidth) || + Math.Abs(basis * factor - ink.Points[0].Width) > 1e-6 * ink.Points[0].Width) return; + var da = stroke.DrawingAttributes; + da.Width = da.Height = width; + da.IgnorePressure = (flags & 1) != 0; + da.FitToCurve = (flags & 2) != 0; + var point = stroke.StylusPoints[0]; + point.PressureFactor = pressure; + stroke.StylusPoints[0] = point; + stroke.AddPropertyData(IccShapeDescriptor.FocusProperty, true); + } + + // INK-4/6:WPF 会静默钳制越界坐标,导入时按原块跳过并报告损失。 + private static bool CanCreateStylusPoint(Point p) => + p.X >= StylusPoint.MinXY && p.X <= StylusPoint.MaxXY && + p.Y >= StylusPoint.MinXY && p.Y <= StylusPoint.MaxXY; + + private static Color BlockColor(UInkColor color, float opacity) + { + uint rgb = color?.Fallback ?? 0; + return Color.FromArgb((byte)Math.Round(Math.Clamp(opacity, 0, 1) * 255f), + (byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); } // ---------- UInkShape → Stroke(读侧渲染) ---------- /// - /// 把 UInkShape 渲染为一条 Stroke:按几何生成轮廓点列(闭合图形回绕首点), - /// 用 stroke 样式(color/opacity/width)着色;仅 fill 时用 fill 颜色描轮廓近似。 - /// dashArray/markers 目前按实线近似(规范允许渲染差异)。 + /// 返回 Shape 的首条原生笔画,整组转换由带 parts 参数的 BlockToStroke 提供。 /// - public static Stroke ShapeToStroke(UInkShape shape) + public static Stroke ShapeToStroke(UInkShape shape, UInkCoordinateMap map = null, Action note = null) => + shape == null ? null : BlockToStroke(shape,map ?? UInkCoordinateMap.Identity,note,out _); + + internal static Stroke ShapeOutline(UInkShape shape, UInkCoordinateMap map = null, Action note = null) { if (shape?.Geometry == null) return null; var points = ComputeShapeOutlinePoints(shape.ShapeType, shape.Geometry); @@ -138,31 +246,73 @@ public static Stroke ShapeToStroke(UInkShape shape) ? shape.Stroke.Width : (shape.Fill != null ? 8f : 4f); // 仅填充时用较粗描边近似 - uint fb = color.Fallback & 0xFFFFFF; + map ??= UInkCoordinateMap.Identity; + double mappedWidth = map.LengthToDip(width); + if (!double.IsFinite(mappedWidth)) return null; + double tip = Math.Clamp(mappedWidth, DrawingAttributes.MinWidth, DrawingAttributes.MaxWidth); + if (mappedWidth != tip) note?.Invoke("tipSizeApprox"); + if (color.Components != null) note?.Invoke("COLOR-2"); + if (shape.Stroke?.UnknownMarker == true) note?.Invoke("shapeMarkerApprox"); + if (shape.Fill != null && !IccShapeDescriptor.IsPublicGlyph(shape)) note?.Invoke("shapeFillOutline"); + if (shape.Geometry is UInkRectGeometry rect && rect.CornerRadiusX > 0) note?.Invoke("shapeCornerApprox"); + if (shape.Stroke?.LineCap > 0) note?.Invoke("shapeCapApprox"); + if (shape.Stroke?.LineJoin > 0) note?.Invoke("shapeJoinApprox"); var da = new DrawingAttributes { - Color = Color.FromArgb( - (byte)Math.Max(0, Math.Min(255, Math.Round(opacity * 255f))), - (byte)(fb >> 16), (byte)(fb >> 8), (byte)fb), - Width = width, - Height = width, + Color = BlockColor(color, opacity), + Width = tip, Height = tip, IgnorePressure = true, FitToCurve = false, }; - var sps = new StylusPointCollection(); + var sps = new StylusPointCollection(points.Count); foreach (var (x, y) in points) - sps.Add(new StylusPoint(x, y, 0.5f)); - return new Stroke(sps) { DrawingAttributes = da }; + { + var p = map.ToDip(x, y); + if (!CanCreateStylusPoint(p)) + { + note?.Invoke("coordinateRange"); + return null; + } + sps.Add(new StylusPoint(p.X, p.Y, 0.5f)); + } + return new Stroke(sps, da); } /// 内容块 → Stroke 分发(Ink→InkToStroke,Shape→ShapeToStroke,Media→null)。供撤回适配/映射器使用。 - public static Stroke BlockToStroke(IUInkContentBlock block) => block switch + public static Stroke BlockToStroke(IUInkContentBlock block, UInkCoordinateMap map = null, Action note = null) => block switch { - UInkInk ink => InkToStroke(ink), - UInkShape shape => ShapeToStroke(shape), + UInkInk ink => InkToStroke(ink, map, note), + UInkShape shape => ShapeToStroke(shape, map, note), _ => null, }; - private static List<(double x, double y)> ComputeShapeOutlinePoints(int shapeType, UInkShapeGeometry geometry) + internal static Stroke BlockToStroke(IUInkContentBlock block, UInkCoordinateMap map, Action note, + out StrokeCollection parts) + { + parts = null; + if (block is not UInkShape shape) return BlockToStroke(block, map, note); + map ??= UInkCoordinateMap.Identity; + try { parts = IccShapeDescriptor.Restore(shape, map); } + catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException || + ex is System.IO.InvalidDataException || ex is ArithmeticException) + { + note?.Invoke("shapeDescriptorInvalid"); + } + if (parts == null) + { + var outline = ShapeOutline(shape, map, note); + if (outline == null) return null; + try { parts = IccShapeDescriptor.ImportPublic(shape, outline, map, note); } + catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException || + ex is System.IO.InvalidDataException || ex is ArithmeticException) + { + note?.Invoke("shapeOutline"); + return outline; + } + } + return parts.Count == 0 ? null : parts[0]; + } + + internal static List<(double x, double y)> ComputeShapeOutlinePoints(int shapeType, UInkShapeGeometry geometry) { var list = new List<(double, double)>(); switch (shapeType) @@ -236,67 +386,9 @@ private static void AddCorner(List<(double, double)> list, float cx, float cy, private static void AddEllipsePoints(List<(double, double)> list, float cx, float cy, float rx, float ry, float rot) { - const int n = 64; double cos = Math.Cos(rot), sin = Math.Sin(rot); - for (int i = 0; i < n; i++) - { - double t = 2.0 * Math.PI * i / n; - double ex = rx * Math.Cos(t), ey = ry * Math.Sin(t); - list.Add((cx + ex * cos - ey * sin, cy + ex * sin + ey * cos)); - } - if (list.Count > 0) list.Add(list[0]); // 闭合 - } - - // ---------- DrawingAttributes 私有序列化(extra["icc:da"]) ---------- - - private static string SerializeDrawingAttributes(DrawingAttributes da) - { - var sb = new StringBuilder(); - sb.Append("Color=").Append(da.Color.ToString()).Append(';'); - sb.Append("Width=").Append(da.Width.ToString(CultureInfo.InvariantCulture)).Append(';'); - sb.Append("Height=").Append(da.Height.ToString(CultureInfo.InvariantCulture)).Append(';'); - sb.Append("FitToCurve=").Append(da.FitToCurve).Append(';'); - sb.Append("IsHighlighter=").Append(da.IsHighlighter).Append(';'); - sb.Append("IgnorePressure=").Append(da.IgnorePressure).Append(';'); - sb.Append("StylusTip=").Append(da.StylusTip).Append(';'); - return sb.ToString(); - } - - private static DrawingAttributes ParseDrawingAttributes(string s) - { - var da = new DrawingAttributes(); - foreach (var part in s.Split(';')) - { - var kv = part.Split('='); - if (kv.Length != 2) continue; - var key = kv[0].Trim(); - var value = kv[1].Trim(); - switch (key) - { - case "Color": - if (ColorConverter.ConvertFromString(value) is Color c) da.Color = c; - break; - case "Width": - if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var w)) da.Width = w; - break; - case "Height": - if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var h)) da.Height = h; - break; - case "FitToCurve": - if (bool.TryParse(value, out var f)) da.FitToCurve = f; - break; - case "IsHighlighter": - if (bool.TryParse(value, out var hg)) da.IsHighlighter = hg; - break; - case "IgnorePressure": - if (bool.TryParse(value, out var ip)) da.IgnorePressure = ip; - break; - case "StylusTip": - da.StylusTip = Enum.TryParse(value, out var tip) ? tip : StylusTip.Ellipse; - break; - } - } - return da; + foreach (var p in IccShapeDescriptor.EllipsePoints(new Point(-rx, -ry), new Point(rx, ry), true, true)) + list.Add((cx + p.X * cos - p.Y * sin, cy + p.X * sin + p.Y * cos)); } private static uint RgbOf(Color c) => (uint)((c.R << 16) | (c.G << 8) | c.B); diff --git a/Ink Canvas/UInk/UInkCoordinateMap.cs b/Ink Canvas/UInk/UInkCoordinateMap.cs new file mode 100644 index 000000000..67203043f --- /dev/null +++ b/Ink Canvas/UInk/UInkCoordinateMap.cs @@ -0,0 +1,64 @@ +using System; +using System.Windows; +using System.Windows.Media; + +namespace Ink_Canvas.UInk +{ + public sealed class UInkCoordinateMap + { + public static readonly UInkCoordinateMap Identity = new(1, 1); + private readonly double dpiX, dpiY, lengthScale, x, y, scale; + + public UInkCoordinateMap(double dpiScaleX, double dpiScaleY, UInkViewport viewport = null) + { + if (!double.IsFinite(dpiScaleX) || dpiScaleX <= 0) throw new ArgumentOutOfRangeException(nameof(dpiScaleX)); + if (!double.IsFinite(dpiScaleY) || dpiScaleY <= 0) throw new ArgumentOutOfRangeException(nameof(dpiScaleY)); + dpiX = dpiScaleX; + dpiY = dpiScaleY; + scale = 1; + // CANVAS-22:视口三个分量一起回退,不能只采用部分有效字段。 + if (viewport != null && float.IsFinite(viewport.X) && float.IsFinite(viewport.Y) && + float.IsFinite(viewport.Scale) && viewport.Scale > 0) + { + x = viewport.X; + y = viewport.Y; + scale = viewport.Scale; + } + lengthScale = scale / (Math.Sqrt(dpiX) * Math.Sqrt(dpiY)); + } + + public Point ToDip(double px, double py) => new((px - x) * scale / dpiX, (py - y) * scale / dpiY); + public Point FromDip(double dx, double dy) => new(dx * dpiX / scale + x, dy * dpiY / scale + y); + public double LengthToDip(double length) => length * lengthScale; + public double LengthFromDip(double length) => length / lengthScale; + + internal Matrix ShapeMatrix(bool export) + { + // 直接取比例,避免从两个带大视口偏移的绝对坐标相减丢失精度。 + return export ? new Matrix(dpiX / scale, 0, 0, dpiY / scale, x, y) : + new Matrix(scale / dpiX, 0, 0, scale / dpiY, -x * scale / dpiX, -y * scale / dpiY); + } + + // 框在局部坐标中,viewport 的缩放由矩阵承担。 + internal Size MediaBoxToDip(double width, double height) => new(width / dpiX, height / dpiY); + internal Size MediaBoxFromDip(double width, double height) => new(width * dpiX, height * dpiY); + + internal float[] MediaMatrixFromDip(Matrix matrix, UInkCoordinateMap localUnits = null) + { + // MEDIA-2 / DEV-1:WPF 行向量,局部像素 → DIP → WPF 矩阵 → 设备像素。 + localUnits ??= this; + return new[] { (float)(matrix.M11 * dpiX / localUnits.dpiX), (float)(matrix.M12 * dpiY / localUnits.dpiX), + (float)(matrix.M21 * dpiX / localUnits.dpiY), (float)(matrix.M22 * dpiY / localUnits.dpiY), + (float)(matrix.OffsetX * dpiX), (float)(matrix.OffsetY * dpiY) }; + } + + public Matrix MapMediaMatrix(float[] matrix) + { + // WPF 行向量:局部 DIP → 像素 → Media → viewport → 目标 DIP。 + var m = matrix ?? UInkMedia.IdentityMatrix(); + var origin = ToDip(m[4], m[5]); + return new Matrix(m[0] * scale, m[1] * scale * dpiX / dpiY, + m[2] * scale * dpiY / dpiX, m[3] * scale, origin.X, origin.Y); + } + } +} diff --git a/Ink Canvas/UInk/UInkExtraArchive.cs b/Ink Canvas/UInk/UInkExtraArchive.cs index 137647cb9..d8ef8844f 100644 --- a/Ink Canvas/UInk/UInkExtraArchive.cs +++ b/Ink Canvas/UInk/UInkExtraArchive.cs @@ -1,26 +1,23 @@ using Ink_Canvas.Helpers; using System; +using System.Buffers.Binary; using System.Collections.Generic; using System.IO; using System.IO.Compression; +using System.Security.Cryptography; using System.Text; namespace Ink_Canvas.UInk { - /// - /// `.uink.extra` 资源包(ZIP)读写。规范约束(uink_media / uink_conf): - /// - Media.path 写入前必须 Unicode NFC、`/` 分隔,不得以 `/` 开头、含 `\`、NUL、控制字符、空路径段、`.` 或 `..`; - /// - ZIP 条目路径用相同 NFC 规范化形式,且不得重复; - /// - 读取不受信任 ZIP 前必须做资源预算检查(条目数、单条目大小、总解压大小、压缩比),禁止直接解压到工作目录。 - /// 路径穿越校验思路与 SafeZipExtractor 一致(拒绝绝对路径/`..`,Combine 后二次确认在目标目录内)。 - /// - public static class UInkExtraArchive + public sealed class UInkExtraArchive : IDisposable { // 资源预算上限(防 zip 炸弹) public const int MaxEntries = 10_000; + internal const int MaxCentralDirectoryBytes = 16 * 1024 * 1024; public const long MaxSingleEntryBytes = 512L * 1024 * 1024; // 512 MiB public const long MaxTotalBytes = 1L * 1024 * 1024 * 1024; // 1 GiB public const double MaxCompressionRatio = 1000.0; + private static readonly uint[] _crc32Table = CreateCrc32Table(); /// 规范化 ZIP 条目/Media 相对路径。返回 null 表示非法。 public static string NormalizeEntryPath(string rawPath) @@ -32,6 +29,8 @@ public static string NormalizeEntryPath(string rawPath) if (nfc.IndexOf('\\') >= 0) return null; // 禁止 \(规范要求 / 分隔) if (nfc.IndexOf('\0') >= 0) return null; // NUL + int colon = nfc.IndexOf(':'); + if (colon > 0 && Uri.CheckSchemeName(nfc.Substring(0, colon))) return null; if (Path.IsPathRooted(nfc)) return null; // 绝对路径/盘符 foreach (char c in nfc) if (char.IsControl(c)) return null; // 控制字符 @@ -45,60 +44,288 @@ public static string NormalizeEntryPath(string rawPath) return nfc; } - /// 创建 `.uink.extra` ZIP。重复条目、非法条目跳过;入口路径已 NFC 规范化。 + private readonly ZipArchive archive; + private readonly Dictionary index = new(StringComparer.Ordinal); + private long extracted; + public int EntryCount => archive.Entries.Count; + + public UInkExtraArchive(string path) + : this(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) { } + + // 接管打开时固定的句柄,后续同名替换不影响本次解码。 + internal UInkExtraArchive(FileStream stream) + { + try + { + CheckCentralDirectory(stream); + archive = new ZipArchive(stream, ZipArchiveMode.Read); + long declared = 0; + foreach (var e in archive.Entries) + { + string key = NormalizeEntryPath(e.FullName); + if (key == null) continue; + // EXTRA-5:即使第一次出现的条目超限,后续同名资源也不可用。 + if (!index.TryAdd(key, null)) { index[key] = null; continue; } + if (e.Length < 0 || e.CompressedLength < 0 || e.Length > MaxSingleEntryBytes || e.Length > MaxTotalBytes - declared || + e.Length > MaxCompressionRatio * e.CompressedLength) continue; + declared += e.Length; + index[key] = e; + } + } + catch { archive?.Dispose(); stream.Dispose(); throw; } + } + + private static void CheckCentralDirectory(FileStream stream) + { + const int endSize = 22, locatorSize = 20, zip64Size = 56, entryHeaderSize = 46; + const uint endSignature = 0x06054b50, locatorSignature = 0x07064b50; + long tailStart = Math.Max(0, stream.Length - endSize - ushort.MaxValue); + var tail = new byte[(int)(stream.Length - tailStart)]; + ReadAt(stream, tailStart, tail); + int i = tail.Length - endSize; + // 取最后一个候选签名,与 .NET 6 的反向搜索一致,避免两次解析认到不同目录。 + while (i >= 0 && U32(tail, i) != endSignature) i--; + if (i < 0 || U16(tail, i + 20) != tail.Length - i - endSize || + U16(tail, i + 4) != U16(tail, i + 6) || U16(tail, i + 8) != U16(tail, i + 10)) + throw BadDirectory(); + + long directoryEnd = tailStart + i; + ushort disk = U16(tail, i + 4), count16 = U16(tail, i + 10); + uint size32 = U32(tail, i + 12), offset32 = U32(tail, i + 16); + ulong count = count16, size = size32, offset = offset32; + long locatorOffset = directoryEnd - locatorSize; + Span locator = stackalloc byte[locatorSize]; + if (locatorOffset >= 0) ReadAt(stream, locatorOffset, locator); + if (locatorOffset >= 0 && U32(locator, 0) == locatorSignature) + { + ulong recordOffset = U64(locator, 8); + if (U32(locator, 4) != 0 || U32(locator, 16) != 1 || locatorOffset < zip64Size || + recordOffset > (ulong)(locatorOffset - zip64Size)) throw BadDirectory(); + Span record = stackalloc byte[zip64Size]; + ReadAt(stream, (long)recordOffset, record); + if (U32(record, 0) != 0x06064b50 || U64(record, 4) != (ulong)locatorOffset - recordOffset - 12 || + U32(record, 16) != 0 || U32(record, 20) != 0 || U64(record, 24) != U64(record, 32)) + throw BadDirectory(); + count = U64(record, 32); size = U64(record, 40); offset = U64(record, 48); + if ((disk != 0 && disk != ushort.MaxValue) || + (count16 != ushort.MaxValue && count16 != count) || (size32 != uint.MaxValue && size32 != size) || + (offset32 != uint.MaxValue && offset32 != offset)) throw BadDirectory(); + directoryEnd = (long)recordOffset; + } + else if (disk != 0 || count16 == ushort.MaxValue || size32 == uint.MaxValue || offset32 == uint.MaxValue) + throw BadDirectory(); + + if (count > MaxEntries || size > MaxCentralDirectoryBytes) + throw new InvalidDataException("EXTRA-7:中央目录条目数或大小超限"); + if (offset > (ulong)directoryEnd || size != (ulong)directoryEnd - offset) throw BadDirectory(); + + // 声明值可能造假。逐条读固定头,确认实际条数和边界后才让 ZipArchive 分配条目。 + Span header = stackalloc byte[entryHeaderSize]; + long position = (long)offset; + for (ulong entry = 0; entry < count; entry++) + { + if (directoryEnd - position < entryHeaderSize) throw BadDirectory(); + ReadAt(stream, position, header); + if (U32(header, 0) != 0x02014b50) throw BadDirectory(); + position += entryHeaderSize + U16(header, 28) + U16(header, 30) + U16(header, 32); + if (position > directoryEnd) throw BadDirectory(); + } + if (position < directoryEnd) + { + // PKWARE 4.3.13:中央目录末尾可有数字签名记录。 + if (directoryEnd - position < 6) throw BadDirectory(); + ReadAt(stream, position, header.Slice(0, 6)); + if (U32(header, 0) != 0x05054b50 || directoryEnd - position != 6 + U16(header, 4)) + throw BadDirectory(); + } + } + + private static ushort U16(ReadOnlySpan bytes, int offset) => BinaryPrimitives.ReadUInt16LittleEndian(bytes.Slice(offset)); + private static uint U32(ReadOnlySpan bytes, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(bytes.Slice(offset)); + private static ulong U64(ReadOnlySpan bytes, int offset) => BinaryPrimitives.ReadUInt64LittleEndian(bytes.Slice(offset)); + + private static InvalidDataException BadDirectory() => new("EXTRA-7:ZIP 中央目录无效"); + + private static void ReadAt(FileStream stream, long position, Span buffer) + { + stream.Position = position; + while (!buffer.IsEmpty) + { + int n = stream.Read(buffer); + if (n == 0) throw BadDirectory(); + buffer = buffer.Slice(n); + } + } + + public bool Contains(string path) => NormalizeEntryPath(path) is string key && + index.TryGetValue(key, out var entry) && entry != null; + + public bool TryExtractEntry(string entryPath, string destinationFile) + { + // ZipArchive 的条目共享输入流;同一实例的实际解压预算也随读取串行更新。 + lock (index) return Extract(entryPath, destinationFile); + } + + // SAVE-1 / EXTRA-8/17:回读临时包,复用解压预算及 CRC 检查,不落第二份资源文件。 + internal bool VerifyEntry(string entryPath) + { + lock (index) return Extract(entryPath, null); + } + + private static uint[] CreateCrc32Table() + { + // ZIP 使用反射形式的 IEEE CRC-32。 + var table = new uint[256]; + for (uint i = 0; i < table.Length; i++) + { + uint crc = i; + for (int bit = 0; bit < 8; bit++) + crc = (crc >> 1) ^ ((crc & 1) != 0 ? 0xEDB88320u : 0u); + table[i] = crc; + } + return table; + } + + private bool Extract(string entryPath, string destinationFile) + { + string key = NormalizeEntryPath(entryPath); + if (key == null || !index.TryGetValue(key, out var e) || e == null || e.Length > MaxTotalBytes - extracted) + return false; + string temp = destinationFile == null ? null : destinationFile + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + string expected = destinationFile == null ? EntryHash(key) : null; + using var hash = expected == null ? null : IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using (var input = e.Open()) + using (var output = temp == null ? Stream.Null : new FileStream(temp, FileMode.CreateNew, FileAccess.Write)) + { + byte[] buffer = new byte[81920]; + long size = 0; + uint crc = uint.MaxValue; + int n; + while ((n = input.Read(buffer, 0, buffer.Length)) > 0) + { + // EXTRA-8:失败的流也已消耗解压预算,不能通过重试重置。 + extracted += n; + size += n; + if (extracted > MaxTotalBytes || size > e.Length || size > MaxSingleEntryBytes || + size > e.CompressedLength * MaxCompressionRatio) return false; + hash?.AppendData(buffer, 0, n); + output.Write(buffer, 0, n); + for (int i = 0; i < n; i++) + crc = _crc32Table[(crc ^ buffer[i]) & 0xff] ^ (crc >> 8); + } + // EXTRA-8:Deflate 流可能在声明长度处停止,用中央目录 CRC 校验实际写入的字节。 + if (size != e.Length || ~crc != e.Crc32) return false; + } + if (hash != null && !string.Equals(expected, Convert.ToHexString(hash.GetHashAndReset()), StringComparison.OrdinalIgnoreCase)) return false; + if (temp != null) File.Move(temp, destinationFile, true); + return true; + } + catch (InvalidDataException) { return false; } + catch (IOException) { return false; } + finally { if (File.Exists(temp)) File.Delete(temp); } + } + + public void Dispose() { lock (index) archive.Dispose(); } + + public static string ContentHashPath(string sourceFile, string ext) + { + using var input = File.OpenRead(sourceFile); + using var sha = SHA256.Create(); + return HashPath(sha.ComputeHash(input), ext); + } + + public static string ContentHashPath(byte[] bytes, string ext) => HashPath(SHA256.HashData(bytes), ext); + + private static string HashPath(byte[] hash, string ext) + { + string suffix = (ext ?? "").TrimStart('.').ToLowerInvariant(); + if (suffix.Length == 0) suffix = "bin"; + if (suffix.IndexOfAny(new[] { '/', '\\', ':' }) >= 0) + throw new ArgumentException("资源扩展名无效", nameof(ext)); + string path = "media/" + Convert.ToHexString(hash).ToLowerInvariant() + "." + suffix; + return NormalizeEntryPath(path) ?? throw new ArgumentException("资源路径无效", nameof(ext)); + } + public static void WriteArchive(string zipPath, IReadOnlyList<(string entryPath, string sourceFile)> resources) { - if (resources == null) return; - if (File.Exists(zipPath)) File.Delete(zipPath); + if (resources.Count > MaxEntries) throw new InvalidDataException("资源条目数超限"); using var archive = ZipFile.Open(zipPath, ZipArchiveMode.Create); var seen = new HashSet(StringComparer.Ordinal); - int written = 0; + long total = 0; + var buffer = new byte[81920]; foreach (var (entryPath, sourceFile) in resources) { - if (string.IsNullOrEmpty(sourceFile) || !File.Exists(sourceFile)) continue; - var safe = NormalizeEntryPath(entryPath); - if (safe == null || !seen.Add(safe)) continue; - archive.CreateEntryFromFile(sourceFile, safe, CompressionLevel.Optimal); - written++; + string key = NormalizeEntryPath(entryPath); + if (key == null || !seen.Add(key)) throw new InvalidDataException("资源路径无效或重复"); + using var input = File.OpenRead(sourceFile); + if (input.Length > MaxSingleEntryBytes || input.Length > MaxTotalBytes - total) + throw new InvalidDataException("资源大小超限"); + using var output = archive.CreateEntry(key, CompressionLevel.NoCompression).Open(); + string expected = EntryHash(key); + using var hash = expected == null ? null : IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + long size = 0; + int n; + while ((n = input.Read(buffer, 0, buffer.Length)) > 0) + { + size += n; + total += n; + if (size > MaxSingleEntryBytes || total > MaxTotalBytes) throw new InvalidDataException("资源大小超限"); + output.Write(buffer, 0, n); + hash?.AppendData(buffer, 0, n); + } + // EXTRA-17:比较实际入包字节,避免源文件在生成路径后变化。 + if (hash != null && !string.Equals(expected, Convert.ToHexString(hash.GetHashAndReset()), StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("资源内容与路径中的 SHA-256 摘要不符:" + key); } LogHelper.WriteLogToFile( - $"[UInk] 资源包已写入: {Path.GetFileName(zipPath)}, 条目 {written}/{resources.Count}", + $"[UInk] 资源包条目已写入: {Path.GetFileName(zipPath)}, 条目 {seen.Count}", LogHelper.LogType.Info); } - /// - /// 预算检查 + 路径安全解压 `.uink.extra`,返回「入口路径(NFC) → 本地文件」映射。 - /// 任何预算/路径违规立即返回 null(不部分解压)。目录条目跳过。 - /// - public static Dictionary ExtractWithBudget(string zipPath, string extractDir) + private static string EntryHash(string key) { - var result = new Dictionary(StringComparer.Ordinal); - long totalBytes = 0; - int entryCount = 0; - var rootFull = Path.GetFullPath(extractDir).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + const int start = 6, length = 64, dot = start + length; + if (!key.StartsWith("media/", StringComparison.Ordinal) || key.Length <= dot + 1 || + key[dot] != '.' || key.IndexOf('/', dot + 1) >= 0) return null; + for (int i = start; i < dot; i++) + if (!Uri.IsHexDigit(key[i])) return null; + return key.Substring(start, length); + } - using var archive = ZipFile.OpenRead(zipPath); - foreach (var entry in archive.Entries) + private static bool Tag(ReadOnlySpan bytes, int offset, string ascii) + { + if (bytes.Length < offset + ascii.Length) return false; + for (int i = 0; i < ascii.Length; i++) if (bytes[offset + i] != ascii[i]) return false; + return true; + } + + public static bool IsMimeConsistent(string mime, ReadOnlySpan bytes) + { + // EXTRA-10:只识别文件签名,最终解码结果仍由对应解码器决定。 + switch (mime?.ToLowerInvariant()) { - if (string.IsNullOrEmpty(entry.Name) || entry.FullName.EndsWith("/")) continue; // 目录条目 - entryCount++; - if (entryCount > MaxEntries) return null; - if (entry.Length > MaxSingleEntryBytes) return null; - totalBytes += entry.Length; - if (totalBytes > MaxTotalBytes) return null; - if (entry.CompressedLength > 0 && entry.Length / (double)entry.CompressedLength > MaxCompressionRatio) return null; - - var safe = NormalizeEntryPath(entry.FullName); - if (safe == null) return null; - - var full = Path.GetFullPath(Path.Combine(extractDir, safe)); - if (!full.StartsWith(rootFull, StringComparison.Ordinal)) return null; - - Directory.CreateDirectory(Path.GetDirectoryName(full)); - entry.ExtractToFile(full, overwrite: true); - result[safe] = full; + case "image/png": return Tag(bytes, 0, "\u0089PNG\r\n\u001a\n"); + case "image/jpeg": return Tag(bytes, 0, "\u00ff\u00d8\u00ff"); + case "image/gif": return Tag(bytes, 0, "GIF87a") || Tag(bytes, 0, "GIF89a"); + case "image/bmp": return Tag(bytes, 0, "BM"); + case "image/tiff": return Tag(bytes, 0, "II*\0") || Tag(bytes, 0, "MM\0*"); + case "image/webp": return Tag(bytes, 0, "RIFF") && Tag(bytes, 8, "WEBP"); + case "application/pdf": return Tag(bytes, 0, "%PDF-"); + case "audio/wav": return Tag(bytes, 0, "RIFF") && Tag(bytes, 8, "WAVE"); + case "audio/flac": return Tag(bytes, 0, "fLaC"); + case "audio/mpeg": return Tag(bytes, 0, "ID3") || + (bytes.Length >= 2 && bytes[0] == 255 && (bytes[1] & 0xe0) == 0xe0 && (bytes[1] & 6) != 0); + case "audio/aac": return bytes.Length >= 2 && bytes[0] == 255 && (bytes[1] & 0xf6) == 0xf0; + case "video/x-msvideo": return Tag(bytes, 0, "RIFF") && Tag(bytes, 8, "AVI "); + // WMV 使用 ASF 的 Header Object GUID;实际视频解码仍由系统处理。 + case "video/x-ms-wmv": return Tag(bytes, 0, "\u0030\u0026\u00b2\u0075\u008e\u0066\u00cf\u0011\u00a6\u00d9\0\u00aa\0\u0062\u00ce\u006c"); + case "video/x-flv": return Tag(bytes, 0, "FLV\u0001"); + case "audio/mp4": case "video/mp4": case "video/quicktime": return Tag(bytes, 4, "ftyp"); + case "video/webm": case "video/x-matroska": return Tag(bytes, 0, "\u001aE\u00df\u00a3"); + default: return false; } - return result; } /// 按文件扩展名推断 MIME(UInk Media.mimeType)。未知回退 application/octet-stream。 @@ -123,6 +350,8 @@ public static string MimeForPath(string path) case ".webm": return "video/webm"; case ".avi": return "video/x-msvideo"; case ".mkv": return "video/x-matroska"; + case ".wmv": return "video/x-ms-wmv"; + case ".flv": return "video/x-flv"; case ".pdf": return "application/pdf"; default: return "application/octet-stream"; } diff --git a/Ink Canvas/UInk/UInkFields.cs b/Ink Canvas/UInk/UInkFields.cs new file mode 100644 index 000000000..2c2d2c6e1 --- /dev/null +++ b/Ink Canvas/UInk/UInkFields.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Text; +using MessagePack; + +namespace Ink_Canvas.UInk +{ + // 必填键在前,requiredMask 与字段次序一起声明。键字节仅在静态 schema 初始化时分配。 + internal sealed class UInkSchema + { + internal readonly string[] Names; + internal readonly byte[][] Keys; + internal readonly int RequiredMask; + + internal UInkSchema(int required, string names) + { + Names = names.Split(' '); + Keys = Array.ConvertAll(Names, Encoding.UTF8.GetBytes); + RequiredMask = (1 << required) - 1; + } + + internal int Key(ref MessagePackReader reader) + { + if (reader.NextMessagePackType != MessagePackType.String) + { + reader.Skip(); + return -1; + } + if (!reader.TryReadStringSpan(out var key)) return Array.IndexOf(Names, reader.ReadString()); + for (int i = 0; i < Keys.Length; i++) + if (key.SequenceEqual(Keys[i])) return i; + return -1; + } + } + + internal readonly struct UInkValue + { + private readonly ReadOnlyMemory bytes; + internal UInkValue(ReadOnlyMemory value) => bytes = value; + internal UInkValue Suffix(int offset) => new(bytes.Slice(offset)); + internal ReadOnlySpan Span => bytes.Span; + internal bool Present => !bytes.IsEmpty; + internal MessagePackReader Reader() => Present ? new MessagePackReader(bytes) : throw new UInkFieldException(); + internal static UInkValue Take(ref MessagePackReader r) => new(r.ReadRaw().First); + + internal string Text() + { + var r = Reader(); + if (r.NextMessagePackType != MessagePackType.String) throw new UInkFieldException(); + return r.ReadString(); + } + + internal string GuidText() + { + string s = Text(); + return s.Length == 36 && Guid.TryParseExact(s, "D", out _) ? s.ToLowerInvariant() : throw new UInkFieldException(); + } + + internal int Int() { var r = Reader(); return UInkNumeric.Int32(ref r); } + internal uint UInt() { var r = Reader(); return (uint)UInkNumeric.Unsigned(ref r, uint.MaxValue); } + internal ulong ULong() { var r = Reader(); return UInkNumeric.Unsigned(ref r); } + internal float Float() { var r = Reader(); return UInkNumeric.Single(ref r); } + internal double Double() { var r = Reader(); return UInkNumeric.Double(ref r); } + internal float Positive() { float f = Float(); return f > 0 ? f : throw new UInkFieldException(); } + internal bool Bool() + { + var r = Reader(); + return r.NextMessagePackType == MessagePackType.Boolean ? r.ReadBoolean() : throw new UInkFieldException(); + } + + internal float Unit(UInkReadResult result, string rule) + { + float f = Float(); + if (f >= 0 && f <= 1) return f; + result.Note(rule); + return Math.Clamp(f, 0, 1); + } + + internal int? Enum(UInkReadResult result, int max, string rule) + { + if (!Present) return null; + int i = Int(); + if (i >= 0 && i <= max) return i; + result.Note(rule); + return 0; + } + + internal float[] Vector(int size) + { + var r = Reader(); + if (r.NextMessagePackType != MessagePackType.Array || r.ReadArrayHeader() != size) + throw new UInkFieldException(); + var values = new float[size]; + for (int i = 0; i < size; i++) values[i] = UInkNumeric.Single(ref r); + return values; + } + } + + internal sealed class UInkFields + { + private readonly UInkSchema schema; + private readonly UInkValue[] values; + internal UInkValue this[string name] => values[Array.IndexOf(schema.Names, name)]; + + internal UInkFields(UInkValue raw, UInkSchema schema, UInkReadResult result) + { + this.schema = schema; + var r = raw.Reader(); + if (r.NextMessagePackType != MessagePackType.Map) throw new UInkFieldException(); + int n = r.ReadMapHeader(), seenMask = 0; + values = new UInkValue[schema.Keys.Length]; + for (int i = 0; i < n; i++) + { + int key = schema.Key(ref r); + // TYPE-8:整个切片已通过有界 scanner;Skip 不可能越过已验证的帧。 + if (key < 0) { r.Skip(); result.Note("TYPE-8"); continue; } + int bit = 1 << key; + if ((seenMask & bit) != 0) throw new UInkDuplicateKey(); + seenMask |= bit; + // 最后一项的结束位置就是已验证的 Map 末尾。常见的 points 数组无需再扫描一次。 + values[key] = i == n - 1 ? raw.Suffix((int)r.Consumed) : UInkValue.Take(ref r); + } + if ((seenMask & schema.RequiredMask) != schema.RequiredMask) throw new UInkFieldException(); + } + + internal string Text(string name) => this[name].Present ? this[name].Text() : null; + internal uint? UInt(string name) => this[name].Present ? this[name].UInt() : null; + internal int? Int(string name) => this[name].Present ? this[name].Int() : null; + internal float? Float(string name) => this[name].Present ? this[name].Float() : null; + + internal static Dictionary Strings(UInkValue raw, bool privateOnly, UInkReadResult result) + { + if (!raw.Present) return null; + var r = raw.Reader(); + if (r.NextMessagePackType != MessagePackType.Map) { result.Note("TYPE-4"); return null; } + int n = r.ReadMapHeader(), total = 0; + Dictionary map = null; + for (int i = 0; i < n; i++) + { + if (r.NextMessagePackType != MessagePackType.String) { r.Skip(); r.Skip(); result.Note("TYPE-8"); continue; } + var key = r.ReadStringSequence().Value; + // TYPE-4:ICC 拥有 icc: 命名空间,保留其中任意键的字符串值。 + if ((privateOnly && !key.FirstSpan.StartsWith(PrivatePrefix)) || + r.NextMessagePackType != MessagePackType.String) + { + r.Skip(); + result.Note("TYPE-8"); + continue; + } + var value = r.ReadStringSequence().Value; + if (privateOnly && (key.Length > 65536 || value.Length > 65536 || total + key.Length + value.Length > (1 << 20))) + { + result.LimitExceeded = true; + result.FailureOffset ??= result.Offset; + result.Note("extra-limit"); + continue; + } + total += (int)(key.Length + value.Length); + (map ??= new(StringComparer.Ordinal))[Encoding.UTF8.GetString(key.FirstSpan)] = + Encoding.UTF8.GetString(value.FirstSpan); + } + return map; + } + private static readonly byte[] PrivatePrefix = Encoding.UTF8.GetBytes("icc:"); + } +} diff --git a/Ink Canvas/UInk/UInkFormatters.cs b/Ink Canvas/UInk/UInkFormatters.cs index 08fa9d911..9f06021b6 100644 --- a/Ink Canvas/UInk/UInkFormatters.cs +++ b/Ink Canvas/UInk/UInkFormatters.cs @@ -2,98 +2,14 @@ using System.Collections.Generic; using System.IO; using MessagePack; -using MessagePack.Formatters; -using MessagePack.Resolvers; namespace Ink_Canvas.UInk { - // ============================================================ - // 写入端强制字段表精确位宽;读取端容错接受可无损转换的其他数值编码。 - // 整数一律 WriteUInt16/WriteUInt32/WriteInt32/WriteUInt64,浮点 Write(Single)。 - // ============================================================ - internal static class UInkFmt + // TYPE-1:数值字段使用固定编码宽度。 + internal static class UInkSerializer { - // ---------- MessagePack 类型探测(3.x 无 NextMessageType,用 NextCode 解码) ---------- - public static bool IsNil(ref MessagePackReader r) => r.NextCode == MessagePackCode.Nil; - - public static bool IsInteger(ref MessagePackReader r) => IsIntegerCode(r.NextCode); - - private static bool IsIntegerCode(byte code) => - code <= 0x7F || code >= 0xE0 || (code >= 0xCC && code <= 0xCF) || (code >= 0xD0 && code <= 0xD3); - - private static bool IsStringCode(byte code) => - (code >= 0xA0 && code <= 0xBF) || code == MessagePackCode.Str8 || code == MessagePackCode.Str16 || code == MessagePackCode.Str32; - - // ---------- 容错读取(数值字段) ---------- - public static ushort ReadUInt16Tolerant(ref MessagePackReader r) - { - var code = r.NextCode; - if (code == MessagePackCode.Float32) return (ushort)r.ReadSingle(); - if (code == MessagePackCode.Float64) return (ushort)r.ReadDouble(); - return r.ReadUInt16(); - } - - public static uint ReadUInt32Tolerant(ref MessagePackReader r) - { - var code = r.NextCode; - if (code == MessagePackCode.Float32) return (uint)r.ReadSingle(); - if (code == MessagePackCode.Float64) return (uint)r.ReadDouble(); - return r.ReadUInt32(); - } - - public static ulong ReadUInt64Tolerant(ref MessagePackReader r) - { - var code = r.NextCode; - if (code == MessagePackCode.Float32) return (ulong)r.ReadSingle(); - if (code == MessagePackCode.Float64) return (ulong)r.ReadDouble(); - return r.ReadUInt64(); - } - - public static int ReadInt32Tolerant(ref MessagePackReader r) - { - var code = r.NextCode; - if (code == MessagePackCode.Float32) return (int)r.ReadSingle(); - if (code == MessagePackCode.Float64) return (int)r.ReadDouble(); - return r.ReadInt32(); - } - - public static bool ReadBoolTolerant(ref MessagePackReader r) - { - var code = r.NextCode; - if (code == MessagePackCode.False) { r.ReadBoolean(); return false; } - if (code == MessagePackCode.True) { r.ReadBoolean(); return true; } - if (IsIntegerCode(code)) return r.ReadInt32() != 0; - throw new MessagePackSerializationException("不是布尔/整数"); - } - - public static float ReadSingleTolerant(ref MessagePackReader r) - { - var code = r.NextCode; - if (code == MessagePackCode.Float32) return r.ReadSingle(); - if (code == MessagePackCode.Float64) return (float)r.ReadDouble(); - if (IsIntegerCode(code)) return r.ReadInt64(); - throw new MessagePackSerializationException("不是数值"); - } - - public static double ReadDoubleTolerant(ref MessagePackReader r) + private static void WriteStringMap(ref MessagePackWriter w, Dictionary map) { - var code = r.NextCode; - if (code == MessagePackCode.Float32) return r.ReadSingle(); - if (code == MessagePackCode.Float64) return r.ReadDouble(); - if (IsIntegerCode(code)) return r.ReadInt64(); - throw new MessagePackSerializationException("不是数值"); - } - - public static string ReadOptionalString(ref MessagePackReader r) - { - if (IsNil(ref r)) { r.ReadNil(); return null; } - return r.ReadString(); - } - - // ---------- string→string Map(extra 用) ---------- - public static void WriteStringMap(ref MessagePackWriter w, Dictionary map) - { - if (map == null || map.Count == 0) { w.WriteNil(); return; } w.WriteMapHeader(map.Count); foreach (var kv in map) { @@ -102,29 +18,13 @@ public static void WriteStringMap(ref MessagePackWriter w, Dictionary ReadStringMap(ref MessagePackReader r) - { - if (IsNil(ref r)) { r.ReadNil(); return null; } - int count = r.ReadMapHeader(); - var map = new Dictionary(count); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - if (IsStringCode(r.NextCode)) - map[key] = r.ReadString(); - else - r.Skip(); // 非字符串值按未知键忽略 - } - return map; - } - - // ---------- Color Map ---------- - public static void WriteColor(ref MessagePackWriter w, UInkColor c) + private static void WriteColor(ref MessagePackWriter w, UInkColor c) { - bool hasHdr = !string.IsNullOrEmpty(c?.Space) && c.Components != null && c.Components.Length == 3; + if (c == null || c.Fallback > 0xffffff) throw new InvalidDataException("COLOR-1:无效的 SDR 颜色"); + bool hasHdr = !string.IsNullOrEmpty(c.Space) && c.Components != null && c.Components.Length == 3; w.WriteMapHeader(hasHdr ? 3 : 1); w.Write("fallback"); - w.WriteUInt32(c?.Fallback ?? 0u); + w.WriteUInt32(c.Fallback); if (hasHdr) { w.Write("space"); @@ -135,44 +35,7 @@ public static void WriteColor(ref MessagePackWriter w, UInkColor c) } } - public static UInkColor ReadColor(ref MessagePackReader r) - { - if (IsNil(ref r)) { r.ReadNil(); return null; } - var c = new UInkColor(); - int count = r.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "fallback": - c.Fallback = ReadUInt32Tolerant(ref r); - break; - case "space": - c.Space = r.ReadString(); - break; - case "components": - int len = r.ReadArrayHeader(); - if (len == 3) - { - c.Components = new float[3]; - for (int j = 0; j < 3; j++) c.Components[j] = ReadSingleTolerant(ref r); - } - else - { - for (int j = 0; j < len; j++) r.Skip(); - } - break; - default: - r.Skip(); - break; - } - } - return c; - } - - // ---------- Viewport Map ---------- - public static void WriteViewport(ref MessagePackWriter w, UInkViewport v) + private static void WriteViewport(ref MessagePackWriter w, UInkViewport v) { w.WriteMapHeader(3); w.Write("x"); w.Write(v.X); @@ -180,71 +43,29 @@ public static void WriteViewport(ref MessagePackWriter w, UInkViewport v) w.Write("scale"); w.Write(v.Scale); } - public static UInkViewport ReadViewport(ref MessagePackReader r) - { - var v = new UInkViewport(); - int count = r.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "x": v.X = ReadSingleTolerant(ref r); break; - case "y": v.Y = ReadSingleTolerant(ref r); break; - case "scale": v.Scale = ReadSingleTolerant(ref r); break; - default: r.Skip(); break; - } - } - return v; - } - - // ---------- Hardware Map(Device 内) ---------- - public static void WriteHardware(ref MessagePackWriter w, UInkHardware h) + private static void WriteHardware(ref MessagePackWriter w, UInkHardware h) { - w.WriteMapHeader(6); - w.Write("name"); w.Write(h.Name ?? ""); - w.Write("id"); w.Write(h.Id ?? ""); - w.Write("identifiers"); - WriteStringMap(ref w, h.Identifiers); - w.Write("physicalWidth"); - if (h.PhysicalWidth.HasValue) w.WriteUInt32(h.PhysicalWidth.Value); else w.WriteNil(); - w.Write("physicalHeight"); - if (h.PhysicalHeight.HasValue) w.WriteUInt32(h.PhysicalHeight.Value); else w.WriteNil(); - w.Write("scaleFactor"); - if (h.ScaleFactor.HasValue) w.Write(h.ScaleFactor.Value); else w.WriteNil(); - } - - public static UInkHardware ReadHardware(ref MessagePackReader r) - { - var h = new UInkHardware(); - int count = r.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "name": h.Name = r.ReadString(); break; - case "id": h.Id = r.ReadString(); break; - case "identifiers": h.Identifiers = ReadStringMap(ref r); break; - case "physicalWidth": - if (!IsNil(ref r)) h.PhysicalWidth = ReadUInt32Tolerant(ref r); else r.ReadNil(); - break; - case "physicalHeight": - if (!IsNil(ref r)) h.PhysicalHeight = ReadUInt32Tolerant(ref r); else r.ReadNil(); - break; - case "scaleFactor": - if (!IsNil(ref r)) h.ScaleFactor = ReadSingleTolerant(ref r); else r.ReadNil(); - break; - default: r.Skip(); break; - } - } - return h; + int n = 0; + if (h.Name != null) n++; + if (h.Id != null) n++; + if (h.Identifiers?.Count > 0) n++; + if (h.PhysicalWidth.HasValue) n++; + if (h.PhysicalHeight.HasValue) n++; + if (h.ScaleFactor.HasValue) n++; + w.WriteMapHeader(n); + if (h.Name != null) { w.Write("name"); w.Write(h.Name); } + if (h.Id != null) { w.Write("id"); w.Write(h.Id); } + if (h.Identifiers?.Count > 0) { w.Write("identifiers"); WriteStringMap(ref w, h.Identifiers); } + if (h.PhysicalWidth.HasValue) { w.Write("physicalWidth"); w.WriteUInt32(h.PhysicalWidth.Value); } + if (h.PhysicalHeight.HasValue) { w.Write("physicalHeight"); w.WriteUInt32(h.PhysicalHeight.Value); } + if (h.ScaleFactor.HasValue) { w.Write("scaleFactor"); w.Write(h.ScaleFactor.Value); } } - // ---------- Device Map(Header Extension devices 数组项) ---------- - public static void WriteDevice(ref MessagePackWriter w, UInkDevice d) + private static void WriteDevice(ref MessagePackWriter w, UInkDevice d) { - int n = 4; // guid, deviceType, name, extra + int n = 2; + if (d.Name != null) n++; + if (d.Extra?.Count > 0) n++; bool isDisplay = d.DeviceType == (int)UInkDeviceType.Display; if (d.Hardware != null) n++; if (isDisplay) n += 4; @@ -252,7 +73,7 @@ public static void WriteDevice(ref MessagePackWriter w, UInkDevice d) w.WriteMapHeader(n); w.Write("guid"); w.Write(d.Guid ?? ""); w.Write("deviceType"); w.WriteInt32(d.DeviceType); - w.Write("name"); w.Write(d.Name ?? ""); + if (d.Name != null) { w.Write("name"); w.Write(d.Name); } if (d.Hardware != null) { w.Write("hardware"); WriteHardware(ref w, d.Hardware); } if (isDisplay) { @@ -270,66 +91,10 @@ public static void WriteDevice(ref MessagePackWriter w, UInkDevice d) w.Write("height"); w.Write(d.WindowHeight ?? 0f); w.Write("zIndex"); w.WriteUInt32(d.ZIndex ?? 0); } - w.Write("extra"); - WriteStringMap(ref w, d.Extra); + if (d.Extra?.Count > 0) { w.Write("extra"); WriteStringMap(ref w, d.Extra); } } - public static UInkDevice ReadDevice(ref MessagePackReader r) - { - var d = new UInkDevice(); - int count = r.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "guid": d.Guid = r.ReadString(); break; - case "deviceType": d.DeviceType = ReadInt32Tolerant(ref r); break; - case "name": d.Name = r.ReadString(); break; - case "hardware": d.Hardware = ReadHardware(ref r); break; - case "parentDeviceGuid": d.ParentDeviceGuid = r.ReadString(); break; - case "x": - if (d.DeviceType == (int)UInkDeviceType.Window) - { - if (IsIntegerCode(r.NextCode)) d.WindowX = r.ReadInt32(); - else d.WindowX = ReadSingleTolerant(ref r); - } - else d.DisplayX = ReadInt32Tolerant(ref r); - break; - case "y": - if (d.DeviceType == (int)UInkDeviceType.Window) - { - if (IsIntegerCode(r.NextCode)) d.WindowY = r.ReadInt32(); - else d.WindowY = ReadSingleTolerant(ref r); - } - else d.DisplayY = ReadInt32Tolerant(ref r); - break; - case "width": - if (d.DeviceType == (int)UInkDeviceType.Window) - { - if (IsIntegerCode(r.NextCode)) d.WindowWidth = r.ReadInt32(); - else d.WindowWidth = ReadSingleTolerant(ref r); - } - else d.DisplayWidth = ReadUInt32Tolerant(ref r); - break; - case "height": - if (d.DeviceType == (int)UInkDeviceType.Window) - { - if (IsIntegerCode(r.NextCode)) d.WindowHeight = r.ReadInt32(); - else d.WindowHeight = ReadSingleTolerant(ref r); - } - else d.DisplayHeight = ReadUInt32Tolerant(ref r); - break; - case "zIndex": d.ZIndex = ReadUInt32Tolerant(ref r); break; - case "extra": d.Extra = ReadStringMap(ref r); break; - default: r.Skip(); break; - } - } - return d; - } - - // ---------- Workspace Map(Header Extension workspaces 数组项) ---------- - public static void WriteWorkspace(ref MessagePackWriter w, UInkWorkspace ws) + private static void WriteWorkspace(ref MessagePackWriter w, UInkWorkspace ws) { int n = 2; // guid, workspaceType if (!string.IsNullOrEmpty(ws.Name)) n++; @@ -347,54 +112,14 @@ public static void WriteWorkspace(ref MessagePackWriter w, UInkWorkspace ws) if (ws.Extra != null && ws.Extra.Count > 0) { w.Write("extra"); WriteStringMap(ref w, ws.Extra); } } - public static UInkWorkspace ReadWorkspace(ref MessagePackReader r) - { - var ws = new UInkWorkspace(); - int count = r.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "guid": ws.Guid = r.ReadString(); break; - case "workspaceType": ws.WorkspaceType = ReadInt32Tolerant(ref r); break; - case "name": ws.Name = r.ReadString(); break; - case "parentWorkspaceGuid": ws.ParentWorkspaceGuid = r.ReadString(); break; - case "hostId": ws.HostId = r.ReadString(); break; - case "currentPageIndex": ws.CurrentPageIndex = ReadUInt32Tolerant(ref r); break; - case "extra": ws.Extra = ReadStringMap(ref r); break; - default: r.Skip(); break; - } - } - return ws; - } - - // ---------- Shape Geometry / Stroke / Fill ---------- - public static void WriteShapePoint(ref MessagePackWriter w, UInkShapePoint p) + private static void WriteShapePoint(ref MessagePackWriter w, UInkShapePoint p) { w.WriteMapHeader(2); w.Write("x"); w.Write(p.X); w.Write("y"); w.Write(p.Y); } - public static UInkShapePoint ReadShapePoint(ref MessagePackReader r) - { - var p = new UInkShapePoint(); - int count = r.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "x": p.X = ReadSingleTolerant(ref r); break; - case "y": p.Y = ReadSingleTolerant(ref r); break; - default: r.Skip(); break; - } - } - return p; - } - - public static void WriteGeometry(ref MessagePackWriter w, int shapeType, UInkShapeGeometry g) + private static void WriteGeometry(ref MessagePackWriter w, int shapeType, UInkShapeGeometry g) { switch (shapeType) { @@ -405,8 +130,14 @@ public static void WriteGeometry(ref MessagePackWriter w, int shapeType, UInkSha var line = (UInkLineGeometry)g; w.WriteMapHeader(1); w.Write("points"); - w.WriteArrayHeader(line.Points.Count); - foreach (var p in line.Points) WriteShapePoint(ref w, p); + int count = line.Points.Count; + // SHAPE-2:Polygon 隐式闭合,不重复写首点。 + if (shapeType == (int)UInkShapeType.Polygon && count > 1 && + line.Points[0].X == line.Points[^1].X && line.Points[0].Y == line.Points[^1].Y) count--; + if (count < 2 || (shapeType == (int)UInkShapeType.Line && count != 2) || + (shapeType == (int)UInkShapeType.Polygon && count < 3)) throw new InvalidDataException("SHAPE-1:几何点数无效"); + w.WriteArrayHeader(count); + for (int i = 0; i < count; i++) WriteShapePoint(ref w, line.Points[i]); break; } case (int)UInkShapeType.Rectangle: @@ -414,11 +145,15 @@ public static void WriteGeometry(ref MessagePackWriter w, int shapeType, UInkSha { var rect = (UInkRectGeometry)g; int n = rect.Rotation.HasValue ? 5 : 4; + if (rect.CornerRadiusX.HasValue) n++; + if (rect.CornerRadiusY.HasValue) n++; w.WriteMapHeader(n); w.Write("centerX"); w.Write(rect.CenterX); w.Write("centerY"); w.Write(rect.CenterY); w.Write("width"); w.Write(rect.Width); w.Write("height"); w.Write(rect.Height); + if (rect.CornerRadiusX.HasValue) { w.Write("cornerRadiusX"); w.Write(rect.CornerRadiusX.Value); } + if (rect.CornerRadiusY.HasValue) { w.Write("cornerRadiusY"); w.Write(rect.CornerRadiusY.Value); } if (rect.Rotation.HasValue) { w.Write("rotation"); w.Write(rect.Rotation.Value); } break; } @@ -448,94 +183,18 @@ public static void WriteGeometry(ref MessagePackWriter w, int shapeType, UInkSha } } - public static UInkShapeGeometry ReadGeometry(ref MessagePackReader r, int shapeType) - { - int count = r.ReadMapHeader(); - switch (shapeType) - { - case (int)UInkShapeType.Line: - case (int)UInkShapeType.Polyline: - case (int)UInkShapeType.Polygon: - { - var line = new UInkLineGeometry(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - if (key == "points") - { - int len = r.ReadArrayHeader(); - for (int j = 0; j < len; j++) line.Points.Add(ReadShapePoint(ref r)); - } - else r.Skip(); - } - return line; - } - case (int)UInkShapeType.Rectangle: - case (int)UInkShapeType.Ellipse: - { - var rect = new UInkRectGeometry(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "centerX": rect.CenterX = ReadSingleTolerant(ref r); break; - case "centerY": rect.CenterY = ReadSingleTolerant(ref r); break; - case "width": rect.Width = ReadSingleTolerant(ref r); break; - case "height": rect.Height = ReadSingleTolerant(ref r); break; - case "rotation": rect.Rotation = ReadSingleTolerant(ref r); break; - default: r.Skip(); break; - } - } - return rect; - } - case (int)UInkShapeType.Square: - { - var sq = new UInkSquareGeometry(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "centerX": sq.CenterX = ReadSingleTolerant(ref r); break; - case "centerY": sq.CenterY = ReadSingleTolerant(ref r); break; - case "size": sq.Size = ReadSingleTolerant(ref r); break; - case "rotation": sq.Rotation = ReadSingleTolerant(ref r); break; - default: r.Skip(); break; - } - } - return sq; - } - case (int)UInkShapeType.Circle: - { - var ci = new UInkCircleGeometry(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "centerX": ci.CenterX = ReadSingleTolerant(ref r); break; - case "centerY": ci.CenterY = ReadSingleTolerant(ref r); break; - case "radius": ci.Radius = ReadSingleTolerant(ref r); break; - default: r.Skip(); break; - } - } - return ci; - } - default: - for (int i = 0; i < count; i++) { r.ReadString(); r.Skip(); } - return null; - } - } - - public static void WriteStroke(ref MessagePackWriter w, UInkStroke s) + private static void WriteStroke(ref MessagePackWriter w, UInkStroke s) { int n = 3; // color, opacity, width if (s.DashArray != null && s.DashArray.Count > 0) n++; if (s.DashOffset.HasValue) n++; if (s.StartMarker.HasValue) n++; if (s.EndMarker.HasValue) n++; + if (s.LineCap.HasValue) n++; + if (s.LineJoin.HasValue) n++; w.WriteMapHeader(n); + if (s.LineCap.HasValue) { w.Write("lineCap"); w.WriteInt32(s.LineCap.Value); } + if (s.LineJoin.HasValue) { w.Write("lineJoin"); w.WriteInt32(s.LineJoin.Value); } w.Write("color"); WriteColor(ref w, s.Color); w.Write("opacity"); w.Write(s.Opacity); w.Write("width"); w.Write(s.Width); @@ -550,35 +209,7 @@ public static void WriteStroke(ref MessagePackWriter w, UInkStroke s) if (s.EndMarker.HasValue) { w.Write("endMarker"); w.WriteInt32(s.EndMarker.Value); } } - public static UInkStroke ReadStroke(ref MessagePackReader r) - { - var s = new UInkStroke(); - int count = r.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "color": s.Color = ReadColor(ref r); break; - case "opacity": s.Opacity = ReadSingleTolerant(ref r); break; - case "width": s.Width = ReadSingleTolerant(ref r); break; - case "dashArray": - { - int len = r.ReadArrayHeader(); - s.DashArray = new List(len); - for (int j = 0; j < len; j++) s.DashArray.Add(ReadSingleTolerant(ref r)); - break; - } - case "dashOffset": s.DashOffset = ReadSingleTolerant(ref r); break; - case "startMarker": s.StartMarker = ReadInt32Tolerant(ref r); break; - case "endMarker": s.EndMarker = ReadInt32Tolerant(ref r); break; - default: r.Skip(); break; - } - } - return s; - } - - public static void WriteFill(ref MessagePackWriter w, UInkFill f) + private static void WriteFill(ref MessagePackWriter w, UInkFill f) { w.WriteMapHeader(3); w.Write("fillType"); w.WriteInt32(f.FillType); @@ -586,37 +217,11 @@ public static void WriteFill(ref MessagePackWriter w, UInkFill f) w.Write("opacity"); w.Write(f.Opacity); } - public static UInkFill ReadFill(ref MessagePackReader r) - { - var f = new UInkFill(); - int count = r.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = r.ReadString(); - switch (key) - { - case "fillType": f.FillType = ReadInt32Tolerant(ref r); break; - case "color": f.Color = ReadColor(ref r); break; - case "opacity": f.Opacity = ReadSingleTolerant(ref r); break; - default: r.Skip(); break; - } - } - return f; - } - } - - // ============================================================ - // Header:强制 array(7),字段顺序/位宽/guid 编码不得更改 - // ============================================================ - public sealed class UInkHeaderFormatter : IMessagePackFormatter - { - public static readonly UInkHeaderFormatter Instance = new UInkHeaderFormatter(); - - public void Serialize(ref MessagePackWriter writer, UInkHeader value, MessagePackSerializerOptions options) + private static void Write(ref MessagePackWriter writer, UInkHeader value) { writer.WriteArrayHeader(7); - writer.WriteUInt16(value.Type); // 0 - writer.WriteUInt16(value.Version); // 10 + writer.WriteUInt16(0); + writer.WriteUInt16(11); writer.Write(value.Guid ?? ""); writer.WriteUInt32(value.DeviceNum); writer.WriteUInt32(value.WorkspaceNum); @@ -624,31 +229,7 @@ public void Serialize(ref MessagePackWriter writer, UInkHeader value, MessagePac writer.WriteUInt64(value.Time); } - public UInkHeader Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - int len = reader.ReadArrayHeader(); - if (len != 7) - throw new MessagePackSerializationException($"UInk Header 必须为 array(7),实际长度 {len}"); - var h = new UInkHeader(); - h.Type = UInkFmt.ReadUInt16Tolerant(ref reader); - h.Version = UInkFmt.ReadUInt16Tolerant(ref reader); - h.Guid = reader.ReadString(); - h.DeviceNum = UInkFmt.ReadUInt32Tolerant(ref reader); - h.WorkspaceNum = UInkFmt.ReadUInt32Tolerant(ref reader); - h.PageNum = UInkFmt.ReadUInt32Tolerant(ref reader); - h.Time = UInkFmt.ReadUInt64Tolerant(ref reader); - return h; - } - } - - // ============================================================ - // Header Extension(Type ID = 1) - // ============================================================ - public sealed class UInkHeaderExtensionFormatter : IMessagePackFormatter - { - public static readonly UInkHeaderExtensionFormatter Instance = new UInkHeaderExtensionFormatter(); - - public void Serialize(ref MessagePackWriter writer, UInkHeaderExtension value, MessagePackSerializerOptions options) + private static void Write(ref MessagePackWriter writer, UInkHeaderExtension value) { int n = 1; // type if (!string.IsNullOrEmpty(value.Name)) n++; @@ -665,58 +246,18 @@ public void Serialize(ref MessagePackWriter writer, UInkHeaderExtension value, M { writer.Write("devices"); writer.WriteArrayHeader(value.Devices.Count); - foreach (var d in value.Devices) UInkFmt.WriteDevice(ref writer, d); + foreach (var d in value.Devices) WriteDevice(ref writer, d); } if (value.Workspaces != null && value.Workspaces.Count > 0) { writer.Write("workspaces"); writer.WriteArrayHeader(value.Workspaces.Count); - foreach (var ws in value.Workspaces) UInkFmt.WriteWorkspace(ref writer, ws); + foreach (var ws in value.Workspaces) WriteWorkspace(ref writer, ws); } - if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); UInkFmt.WriteStringMap(ref writer, value.Extra); } + if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); WriteStringMap(ref writer, value.Extra); } } - public UInkHeaderExtension Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var ext = new UInkHeaderExtension(); - int count = reader.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = reader.ReadString(); - switch (key) - { - case "name": ext.Name = reader.ReadString(); break; - case "explanation": ext.Explanation = reader.ReadString(); break; - case "devices": - { - int len = reader.ReadArrayHeader(); - ext.Devices = new List(len); - for (int j = 0; j < len; j++) ext.Devices.Add(UInkFmt.ReadDevice(ref reader)); - break; - } - case "workspaces": - { - int len = reader.ReadArrayHeader(); - ext.Workspaces = new List(len); - for (int j = 0; j < len; j++) ext.Workspaces.Add(UInkFmt.ReadWorkspace(ref reader)); - break; - } - case "extra": ext.Extra = UInkFmt.ReadStringMap(ref reader); break; - default: reader.Skip(); break; - } - } - return ext; - } - } - - // ============================================================ - // Canvas(Type ID = 2) - // ============================================================ - public sealed class UInkCanvasFormatter : IMessagePackFormatter - { - public static readonly UInkCanvasFormatter Instance = new UInkCanvasFormatter(); - - public void Serialize(ref MessagePackWriter writer, UInkCanvas value, MessagePackSerializerOptions options) + private static void Write(ref MessagePackWriter writer, UInkCanvas value) { int n = 6; // type, pageGuid, pageIndex, pageNumber, layerIndex, layerNumber if (!string.IsNullOrEmpty(value.WorkspaceGuid)) n++; @@ -724,75 +265,53 @@ public void Serialize(ref MessagePackWriter writer, UInkCanvas value, MessagePac if (value.SlideId.HasValue) n++; if (value.Viewport != null) n++; if (value.Extra != null && value.Extra.Count > 0) n++; + if (value.PageKind.HasValue) n++; + if (value.PageState.HasValue) n++; + if (value.Binding.HasValue) n++; + if (value.Background != null) n++; writer.WriteMapHeader(n); writer.Write("type"); writer.WriteUInt16((ushort)UInkBlockType.Canvas); if (!string.IsNullOrEmpty(value.WorkspaceGuid)) { writer.Write("workspaceGuid"); writer.Write(value.WorkspaceGuid); } if (!string.IsNullOrEmpty(value.DeviceGuid)) { writer.Write("deviceGuid"); writer.Write(value.DeviceGuid); } writer.Write("pageGuid"); writer.Write(value.PageGuid ?? ""); + if (value.PageKind.HasValue) { writer.Write("pageKind"); writer.WriteInt32(value.PageKind.Value); } + if (value.PageState.HasValue) { writer.Write("pageState"); writer.WriteInt32(value.PageState.Value); } + if (value.Binding.HasValue) { writer.Write("binding"); writer.WriteInt32(value.Binding.Value); } + if (value.Background != null) { writer.Write("background"); WriteBackground(ref writer, value.Background); } writer.Write("pageIndex"); writer.WriteUInt32(value.PageIndex); writer.Write("pageNumber"); writer.WriteUInt32(value.PageNumber); writer.Write("layerIndex"); writer.WriteUInt32(value.LayerIndex); writer.Write("layerNumber"); writer.WriteUInt32(value.LayerNumber); if (value.SlideId.HasValue) { writer.Write("slideId"); writer.WriteInt32(value.SlideId.Value); } - if (value.Viewport != null) { writer.Write("viewport"); UInkFmt.WriteViewport(ref writer, value.Viewport); } - if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); UInkFmt.WriteStringMap(ref writer, value.Extra); } + if (value.Viewport != null) { writer.Write("viewport"); WriteViewport(ref writer, value.Viewport); } + if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); WriteStringMap(ref writer, value.Extra); } } - public UInkCanvas Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var c = new UInkCanvas(); - int count = reader.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = reader.ReadString(); - switch (key) - { - case "workspaceGuid": c.WorkspaceGuid = reader.ReadString(); break; - case "deviceGuid": c.DeviceGuid = reader.ReadString(); break; - case "pageGuid": c.PageGuid = reader.ReadString(); break; - case "pageIndex": c.PageIndex = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "pageNumber": c.PageNumber = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "layerIndex": c.LayerIndex = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "layerNumber": c.LayerNumber = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "slideId": - if (UInkFmt.IsNil(ref reader)) reader.ReadNil(); - else c.SlideId = UInkFmt.ReadInt32Tolerant(ref reader); - break; - case "viewport": c.Viewport = UInkFmt.ReadViewport(ref reader); break; - case "extra": c.Extra = UInkFmt.ReadStringMap(ref reader); break; - default: reader.Skip(); break; - } - } - return c; - } - } - - // ============================================================ - // Ink(Type ID = 3) - // ============================================================ - public sealed class UInkInkFormatter : IMessagePackFormatter - { - public static readonly UInkInkFormatter Instance = new UInkInkFormatter(); - - public void Serialize(ref MessagePackWriter writer, UInkInk value, MessagePackSerializerOptions options) + private static void Write(ref MessagePackWriter writer, UInkInk value) { int n = 8; // type, contentId, undoId, inkType, color, opacity, texture, points if (value.RenderOnlyWhenLatest) n++; if (value.Extra != null && value.Extra.Count > 0) n++; + if (value.Nib != null) n++; + if (value.Cap.HasValue) n++; writer.WriteMapHeader(n); writer.Write("type"); writer.WriteUInt16((ushort)UInkBlockType.Ink); writer.Write("contentId"); writer.WriteUInt32(value.ContentId); writer.Write("undoId"); writer.WriteUInt32(value.UndoId); writer.Write("inkType"); writer.WriteInt32(value.InkType); - writer.Write("color"); UInkFmt.WriteColor(ref writer, value.Color); + writer.Write("color"); WriteColor(ref writer, value.Color); writer.Write("opacity"); writer.Write(value.Opacity); writer.Write("texture"); writer.WriteInt32(value.Texture); + if (value.Nib != null) { writer.Write("nib"); WriteNib(ref writer, value.Nib); } + if (value.Cap.HasValue) { writer.Write("cap"); writer.WriteInt32(value.Cap.Value); } writer.Write("points"); - writer.WriteArrayHeader(value.Points.Count); - foreach (var p in value.Points) + writer.WriteArrayHeader(value.Points.Length); + int anchor = 0; + for (int i = 0; i < value.Points.Length; i++) { - bool hasPointColor = p.Color != null && !string.IsNullOrEmpty(p.Color.Space) && p.Color.Components != null; + var p = value.Points[i]; + bool hasPointColor = anchor < (value.StyleAnchors?.Count ?? 0) && value.StyleAnchors[anchor].Index == i; int pn = hasPointColor ? 5 : 3; writer.WriteMapHeader(pn); writer.Write("x"); writer.Write(p.X); @@ -800,259 +319,154 @@ public void Serialize(ref MessagePackWriter writer, UInkInk value, MessagePackSe writer.Write("width"); writer.Write(p.Width); if (hasPointColor) { - writer.Write("color"); UInkFmt.WriteColor(ref writer, p.Color); - writer.Write("opacity"); writer.Write(p.Opacity ?? 1f); + var style = value.StyleAnchors[anchor++]; + writer.Write("color"); WriteColor(ref writer, style.Color); + writer.Write("opacity"); writer.Write(style.Opacity); } } + if (anchor != (value.StyleAnchors?.Count ?? 0)) throw new InvalidDataException("无效的点样式锚点顺序"); if (value.RenderOnlyWhenLatest) { writer.Write("renderOnlyWhenLatest"); writer.Write(true); } - if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); UInkFmt.WriteStringMap(ref writer, value.Extra); } - } - - public UInkInk Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var ink = new UInkInk(); - int count = reader.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = reader.ReadString(); - switch (key) - { - case "contentId": ink.ContentId = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "undoId": ink.UndoId = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "inkType": ink.InkType = UInkFmt.ReadInt32Tolerant(ref reader); break; - case "color": ink.Color = UInkFmt.ReadColor(ref reader) ?? new UInkColor(); break; - case "opacity": ink.Opacity = UInkFmt.ReadSingleTolerant(ref reader); break; - case "texture": ink.Texture = UInkFmt.ReadInt32Tolerant(ref reader); break; - case "points": - { - int len = reader.ReadArrayHeader(); - ink.Points = new List(len); - for (int j = 0; j < len; j++) ink.Points.Add(ReadInkPoint(ref reader)); - break; - } - case "renderOnlyWhenLatest": ink.RenderOnlyWhenLatest = UInkFmt.ReadBoolTolerant(ref reader); break; - case "extra": ink.Extra = UInkFmt.ReadStringMap(ref reader); break; - default: reader.Skip(); break; - } - } - return ink; + if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); WriteStringMap(ref writer, value.Extra); } } - private static UInkInkPoint ReadInkPoint(ref MessagePackReader reader) - { - var p = new UInkInkPoint { Width = 1f }; - int count = reader.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = reader.ReadString(); - switch (key) - { - case "x": p.X = UInkFmt.ReadSingleTolerant(ref reader); break; - case "y": p.Y = UInkFmt.ReadSingleTolerant(ref reader); break; - case "width": p.Width = UInkFmt.ReadSingleTolerant(ref reader); break; - case "color": p.Color = UInkFmt.ReadColor(ref reader); break; - case "opacity": - if (UInkFmt.IsNil(ref reader)) reader.ReadNil(); - else p.Opacity = UInkFmt.ReadSingleTolerant(ref reader); - break; - default: reader.Skip(); break; - } - } - return p; - } - } - - // ============================================================ - // Shape(Type ID = 5) - // ============================================================ - public sealed class UInkShapeFormatter : IMessagePackFormatter - { - public static readonly UInkShapeFormatter Instance = new UInkShapeFormatter(); - - public void Serialize(ref MessagePackWriter writer, UInkShape value, MessagePackSerializerOptions options) + private static void Write(ref MessagePackWriter writer, UInkShape value) { int n = 5; // type, contentId, undoId, shapeType, geometry if (value.Stroke != null) n++; if (value.Fill != null) n++; if (value.RenderOnlyWhenLatest) n++; if (value.Extra != null && value.Extra.Count > 0) n++; + if (value.Object != null) n++; writer.WriteMapHeader(n); writer.Write("type"); writer.WriteUInt16((ushort)UInkBlockType.Shape); writer.Write("contentId"); writer.WriteUInt32(value.ContentId); writer.Write("undoId"); writer.WriteUInt32(value.UndoId); writer.Write("shapeType"); writer.WriteInt32(value.ShapeType); - writer.Write("geometry"); UInkFmt.WriteGeometry(ref writer, value.ShapeType, value.Geometry); - if (value.Stroke != null) { writer.Write("stroke"); UInkFmt.WriteStroke(ref writer, value.Stroke); } - if (value.Fill != null) { writer.Write("fill"); UInkFmt.WriteFill(ref writer, value.Fill); } + if (value.Object != null) { writer.Write("object"); WriteObject(ref writer, value.Object); } + writer.Write("geometry"); WriteGeometry(ref writer, value.ShapeType, value.Geometry); + if (value.Stroke != null) { writer.Write("stroke"); WriteStroke(ref writer, value.Stroke); } + if (value.Fill != null) { writer.Write("fill"); WriteFill(ref writer, value.Fill); } if (value.RenderOnlyWhenLatest) { writer.Write("renderOnlyWhenLatest"); writer.Write(true); } - if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); UInkFmt.WriteStringMap(ref writer, value.Extra); } - } - - public UInkShape Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) - { - var shape = new UInkShape(); - int count = reader.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = reader.ReadString(); - switch (key) - { - case "contentId": shape.ContentId = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "undoId": shape.UndoId = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "shapeType": shape.ShapeType = UInkFmt.ReadInt32Tolerant(ref reader); break; - case "geometry": shape.Geometry = UInkFmt.ReadGeometry(ref reader, shape.ShapeType); break; - case "stroke": shape.Stroke = UInkFmt.ReadStroke(ref reader); break; - case "fill": shape.Fill = UInkFmt.ReadFill(ref reader); break; - case "renderOnlyWhenLatest": shape.RenderOnlyWhenLatest = UInkFmt.ReadBoolTolerant(ref reader); break; - case "extra": shape.Extra = UInkFmt.ReadStringMap(ref reader); break; - default: reader.Skip(); break; - } - } - return shape; + if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); WriteStringMap(ref writer, value.Extra); } } - } - - // ============================================================ - // Media(Type ID = 4) - // ============================================================ - public sealed class UInkMediaFormatter : IMessagePackFormatter - { - public static readonly UInkMediaFormatter Instance = new UInkMediaFormatter(); - public void Serialize(ref MessagePackWriter writer, UInkMedia value, MessagePackSerializerOptions options) + private static void Write(ref MessagePackWriter writer, UInkMedia value) { + // MEDIA-2:自产视觉媒体显式写矩阵,使自检无需警告。 + var transform = value.Transform ?? (UInkMedia.IsVisualMime(value.MimeType) ? UInkMedia.IdentityMatrix() : null); int n = 5; // type, contentId, undoId, path, mimeType if (value.Width.HasValue) n++; if (value.Height.HasValue) n++; - if (value.Transform != null) n++; + if (transform != null) n++; if (value.Opacity.HasValue) n++; - if (value.PageCount.HasValue) n++; + // PDF 页数未知或为零时省略,字段表只允许写正数。 + bool hasPageCount = value.PageCount > 0; + if (hasPageCount) n++; if (value.PageIndex.HasValue) n++; if (value.Autoplay) n++; if (value.Loop) n++; - if (Math.Abs(value.Volume - 1f) > 0.0001f) n++; - if (Math.Abs(value.StartTime) > 0.0000001) n++; - if (Math.Abs(value.PlaybackRate - 1f) > 0.0001f) n++; + if (value.Volume != 1f) n++; + if (value.StartTime != 0) n++; + if (value.PlaybackRate != 1f) n++; if (value.Extra != null && value.Extra.Count > 0) n++; + if (value.Fit.HasValue) n++; + if (value.Crop != null) n++; writer.WriteMapHeader(n); writer.Write("type"); writer.WriteUInt16((ushort)UInkBlockType.Media); writer.Write("contentId"); writer.WriteUInt32(value.ContentId); writer.Write("undoId"); writer.WriteUInt32(value.UndoId); - writer.Write("path"); writer.Write(value.Path ?? ""); + if (value.Fit.HasValue) { writer.Write("fit"); writer.WriteInt32(value.Fit.Value); } + if (value.Crop != null) { writer.Write("crop"); WriteCrop(ref writer, value.Crop); } + writer.Write("path"); writer.Write(UInkExtraArchive.NormalizeEntryPath(value.Path) ?? throw new InvalidDataException("EXTRA-4:非法资源路径")); writer.Write("mimeType"); writer.Write(value.MimeType ?? ""); if (value.Width.HasValue) { writer.Write("width"); writer.Write(value.Width.Value); } if (value.Height.HasValue) { writer.Write("height"); writer.Write(value.Height.Value); } - if (value.Transform != null) + if (transform != null) { writer.Write("transform"); - writer.WriteArrayHeader(6); - for (int i = 0; i < 6; i++) - writer.Write(i < value.Transform.Length ? value.Transform[i] : (i == 0 || i == 3 ? 1f : 0f)); + WriteMatrix(ref writer, transform); } if (value.Opacity.HasValue) { writer.Write("opacity"); writer.Write(value.Opacity.Value); } - if (value.PageCount.HasValue) { writer.Write("pageCount"); writer.WriteUInt32(value.PageCount.Value); } + if (hasPageCount) { writer.Write("pageCount"); writer.WriteUInt32(value.PageCount.Value); } if (value.PageIndex.HasValue) { writer.Write("pageIndex"); writer.WriteUInt32(value.PageIndex.Value); } if (value.Autoplay) { writer.Write("autoplay"); writer.Write(true); } if (value.Loop) { writer.Write("loop"); writer.Write(true); } - if (Math.Abs(value.Volume - 1f) > 0.0001f) { writer.Write("volume"); writer.Write(value.Volume); } - if (Math.Abs(value.StartTime) > 0.0000001) { writer.Write("startTime"); writer.Write(value.StartTime); } - if (Math.Abs(value.PlaybackRate - 1f) > 0.0001f) { writer.Write("playbackRate"); writer.Write(value.PlaybackRate); } - if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); UInkFmt.WriteStringMap(ref writer, value.Extra); } + if (value.Volume != 1f) { writer.Write("volume"); writer.Write(value.Volume); } + if (value.StartTime != 0) { writer.Write("startTime"); writer.Write(value.StartTime); } + if (value.PlaybackRate != 1f) { writer.Write("playbackRate"); writer.Write(value.PlaybackRate); } + if (value.Extra != null && value.Extra.Count > 0) { writer.Write("extra"); WriteStringMap(ref writer, value.Extra); } } - public UInkMedia Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + private static void WriteBackground(ref MessagePackWriter w, UInkBackground b) { - var media = new UInkMedia(); - int count = reader.ReadMapHeader(); - for (int i = 0; i < count; i++) - { - var key = reader.ReadString(); - switch (key) - { - case "contentId": media.ContentId = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "undoId": media.UndoId = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "path": media.Path = reader.ReadString(); break; - case "mimeType": media.MimeType = reader.ReadString(); break; - case "width": media.Width = UInkFmt.ReadSingleTolerant(ref reader); break; - case "height": media.Height = UInkFmt.ReadSingleTolerant(ref reader); break; - case "transform": - { - int len = reader.ReadArrayHeader(); - media.Transform = new float[6]; - for (int j = 0; j < 6; j++) - media.Transform[j] = j < len ? UInkFmt.ReadSingleTolerant(ref reader) : (j == 0 || j == 3 ? 1f : 0f); - for (int j = 6; j < len; j++) reader.Skip(); - break; - } - case "opacity": media.Opacity = UInkFmt.ReadSingleTolerant(ref reader); break; - case "pageCount": media.PageCount = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "pageIndex": media.PageIndex = UInkFmt.ReadUInt32Tolerant(ref reader); break; - case "autoplay": media.Autoplay = UInkFmt.ReadBoolTolerant(ref reader); break; - case "loop": media.Loop = UInkFmt.ReadBoolTolerant(ref reader); break; - case "volume": media.Volume = UInkFmt.ReadSingleTolerant(ref reader); break; - case "startTime": media.StartTime = UInkFmt.ReadDoubleTolerant(ref reader); break; - case "playbackRate": media.PlaybackRate = UInkFmt.ReadSingleTolerant(ref reader); break; - case "extra": media.Extra = UInkFmt.ReadStringMap(ref reader); break; - default: reader.Skip(); break; - } - } - return media; + w.WriteMapHeader(b.Pattern.HasValue ? 2 : 1); + w.Write("color"); WriteColor(ref w, b.Color); + if (b.Pattern.HasValue) { w.Write("pattern"); w.WriteInt32(b.Pattern.Value); } } - } - // ============================================================ - // 共享 SerializerOptions:注册全部顶层块 formatters - // ============================================================ - public static class UInkSerializer - { - public static readonly MessagePackSerializerOptions Options; - - static UInkSerializer() + private static void WriteNib(ref MessagePackWriter w, UInkNib nib) { - var resolver = CompositeResolver.Create( - new IMessagePackFormatter[] - { - UInkHeaderFormatter.Instance, - UInkHeaderExtensionFormatter.Instance, - UInkCanvasFormatter.Instance, - UInkInkFormatter.Instance, - UInkShapeFormatter.Instance, - UInkMediaFormatter.Instance, - }, - new IFormatterResolver[] { StandardResolver.Instance }); + w.WriteMapHeader(nib.Aspect.HasValue ? 3 : 2); + w.Write("shape"); w.WriteInt32(nib.Shape); + w.Write("orientation"); w.WriteInt32(nib.Orientation); + if (nib.Aspect.HasValue) { w.Write("aspect"); w.Write(nib.Aspect.Value); } + } - Options = MessagePackSerializerOptions.Standard - .WithResolver(resolver) - .WithSecurity(MessagePackSecurity.UntrustedData); + private static void WriteMatrix(ref MessagePackWriter w, float[] matrix) + { + if (matrix.Length != 6) throw new InvalidDataException("仿射矩阵应包含六个元素"); + w.WriteArrayHeader(6); + foreach (float v in matrix) w.Write(v); } - /// 把一个顶层块序列化为一个完整 MessagePack 对象,追加到流末尾。 - public static void WriteBlock(Stream stream, object block) + private static void WriteObject(ref MessagePackWriter w, UInkShapeObject obj) { - switch (block) + if (obj.Ref != null) { - case UInkHeader h: MessagePackSerializer.Serialize(stream, h, Options); break; - case UInkHeaderExtension e: MessagePackSerializer.Serialize(stream, e, Options); break; - case UInkCanvas c: MessagePackSerializer.Serialize(stream, c, Options); break; - case UInkInk i: MessagePackSerializer.Serialize(stream, i, Options); break; - case UInkShape s: MessagePackSerializer.Serialize(stream, s, Options); break; - case UInkMedia m: MessagePackSerializer.Serialize(stream, m, Options); break; - default: throw new NotSupportedException($"未知 UInk 块类型: {block?.GetType().Name}"); + w.WriteMapHeader(2); + w.Write("ref"); w.Write(obj.Ref); + w.Write("partIndex"); w.WriteUInt32(obj.PartIndex); + return; } + w.WriteMapHeader(3 + (obj.Preset == null ? 0 : 1) + (obj.Transform == null ? 0 : 1)); + w.Write("id"); w.Write(obj.Id); + w.Write("revision"); w.WriteUInt64(obj.Revision); + w.Write("partCount"); w.WriteUInt32(obj.PartCount); + if (obj.Preset != null) { w.Write("preset"); w.Write(obj.Preset); } + if (obj.Transform != null) { w.Write("transform"); WriteMatrix(ref w, obj.Transform); } + } + + private static void WriteCrop(ref MessagePackWriter w, UInkCrop crop) + { + w.WriteMapHeader(4); + w.Write("x"); w.Write(crop.X); + w.Write("y"); w.Write(crop.Y); + w.Write("width"); w.Write(crop.Width); + w.Write("height"); w.Write(crop.Height); + } + + private static void Write(ref MessagePackWriter w, UInkClear clear) + { + bool extra = clear.Extra?.Count > 0; + w.WriteMapHeader(extra ? 4 : 3); + w.Write("type"); w.WriteUInt16(6); + w.Write("contentId"); w.WriteUInt32(clear.ContentId); + w.Write("undoId"); w.WriteUInt32(clear.UndoId); + if (extra) { w.Write("extra"); WriteStringMap(ref w, clear.Extra); } } - /// 把一个顶层块写入 MessagePackWriter(供增量追加在已有写入器上继续)。 - public static void WriteBlock(ref MessagePackWriter writer, object block) + internal static void WriteBlock(ref MessagePackWriter w, object block) { switch (block) { - case UInkHeader h: UInkHeaderFormatter.Instance.Serialize(ref writer, h, Options); break; - case UInkHeaderExtension e: UInkHeaderExtensionFormatter.Instance.Serialize(ref writer, e, Options); break; - case UInkCanvas c: UInkCanvasFormatter.Instance.Serialize(ref writer, c, Options); break; - case UInkInk i: UInkInkFormatter.Instance.Serialize(ref writer, i, Options); break; - case UInkShape s: UInkShapeFormatter.Instance.Serialize(ref writer, s, Options); break; - case UInkMedia m: UInkMediaFormatter.Instance.Serialize(ref writer, m, Options); break; - default: throw new NotSupportedException($"未知 UInk 块类型: {block?.GetType().Name}"); + case UInkHeader header: Write(ref w, header); break; + case UInkHeaderExtension headerextension: Write(ref w, headerextension); break; + case UInkCanvas canvas: Write(ref w, canvas); break; + case UInkInk ink: Write(ref w, ink); break; + case UInkShape shape: Write(ref w, shape); break; + case UInkMedia media: Write(ref w, media); break; + case UInkClear clear: Write(ref w, clear); break; + default: throw new InvalidDataException("未知的 UInk 块类型"); } } } diff --git a/Ink Canvas/UInk/UInkHistoryReplay.cs b/Ink Canvas/UInk/UInkHistoryReplay.cs new file mode 100644 index 000000000..7c044307b --- /dev/null +++ b/Ink Canvas/UInk/UInkHistoryReplay.cs @@ -0,0 +1,126 @@ +using Ink_Canvas.Helpers; +using System; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; + +namespace Ink_Canvas.UInk +{ + // SAVE-2:画布和只读快照共享每条记录的执行顺序,只替换读写成员的方式。 + internal abstract class UInkHistoryReplay + { + protected abstract void Strokes(StrokeCollection batch, bool insert); + protected abstract void Element(UIElement element, bool insert); + protected abstract bool Contains(object item); + protected abstract void SetPoints(Stroke stroke, StylusPointCollection points); + protected abstract void SetAttributes(Stroke stroke, DrawingAttributes attributes, bool clone); + protected abstract void SetTransform(UIElement element, Transform transform); + + internal void Apply(TimeMachineHistory entry) + { + bool cleared = entry.StrokeHasBeenCleared; + switch (entry.CommitType) + { + case TimeMachineHistoryType.UserInput: + Strokes(entry.CurrentStroke, !cleared); + if (entry is UInkGroupHistory group) + foreach (var element in group.Elements) + if (element != null) Element(element, !cleared); + break; + case TimeMachineHistoryType.ShapeRecognition when cleared: + Strokes(entry.CurrentStroke, false); + Strokes(entry.ReplacedStroke, true); + break; + case TimeMachineHistoryType.ShapeRecognition: + case TimeMachineHistoryType.Clear: + // 同一次点擦的中间残段可同时在两组中,先加入再移除。 + Strokes(cleared ? entry.ReplacedStroke : entry.CurrentStroke, true); + Strokes(cleared ? entry.CurrentStroke : entry.ReplacedStroke, false); + break; + case TimeMachineHistoryType.PluginInkConversion: + // 转换状态已应用时,源墨迹已从画布消耗;撤销时才恢复。 + Strokes(entry.CurrentStroke, !cleared); + break; + case TimeMachineHistoryType.ElementInsert: + if (entry.InsertedElement != null) Element(entry.InsertedElement, !cleared); + break; + case TimeMachineHistoryType.Manipulation: + case TimeMachineHistoryType.DrawingAttributes: + bool manipulation = entry.CommitType == TimeMachineHistoryType.Manipulation; + if (manipulation && entry.StylusPointDictionary != null) + foreach (var pair in entry.StylusPointDictionary) + if (Contains(pair.Key)) SetPoints(pair.Key, cleared ? pair.Value.Item1 : pair.Value.Item2); + if (entry.DrawingAttributes != null) + foreach (var pair in entry.DrawingAttributes) + if (Contains(pair.Key)) SetAttributes(pair.Key, cleared ? pair.Value.Item1 : pair.Value.Item2, + manipulation); + if (manipulation && entry.ElementTransforms != null) + foreach (var pair in entry.ElementTransforms) + if (Contains(pair.Key)) SetTransform(pair.Key, cleared ? pair.Value.Item1 : pair.Value.Item2); + break; + } + } + } + + internal sealed class UInkCanvasReplay : UInkHistoryReplay + { + private readonly InkCanvas canvas; + private readonly bool includeElements; + private readonly Action restoreElementLayout; + private HashSet presentStrokes; + private HashSet presentElements; + internal UInkCanvasReplay(InkCanvas canvas, bool includeElements = true, Action restoreElementLayout = null) + { + this.canvas = canvas; + this.includeElements = includeElements; + this.restoreElementLayout = restoreElementLayout; + } + + protected override void Strokes(StrokeCollection batch, bool insert) + { + if (batch == null || batch.Count == 0) return; + // 复合组可能已有成员或成员已被擦除,只批量提交实际变化。 + var present = PresentStrokes; + var changed = new UInkStrokeCollection(); + foreach (var stroke in batch) + if (insert ? present.Add(stroke) : present.Remove(stroke)) changed.AppendNew(stroke); + if (changed.Count == 0) return; + if (insert) canvas.Strokes.Add(changed); + else canvas.Strokes.Remove(changed); + } + + protected override void Element(UIElement element, bool insert) + { + if (!includeElements || !(insert ? PresentElements.Add(element) : PresentElements.Remove(element))) return; + if (insert) + { + canvas.Children.Add(element); + restoreElementLayout?.Invoke(element); + } + else canvas.Children.Remove(element); + } + + private HashSet PresentStrokes => presentStrokes ??= new HashSet(canvas.Strokes, ReferenceEqualityComparer.Instance); + private HashSet PresentElements + { + get + { + if (presentElements != null) return presentElements; + presentElements = new HashSet(ReferenceEqualityComparer.Instance); + foreach (UIElement element in canvas.Children) presentElements.Add(element); + return presentElements; + } + } + + protected override bool Contains(object item) => item is Stroke stroke ? PresentStrokes.Contains(stroke) : + includeElements && PresentElements.Contains((UIElement)item); + protected override void SetPoints(Stroke stroke, StylusPointCollection points) => stroke.StylusPoints = points; + protected override void SetAttributes(Stroke stroke, DrawingAttributes attributes, bool clone) => + stroke.DrawingAttributes = clone ? attributes.Clone() : attributes; + protected override void SetTransform(UIElement element, Transform transform) => + element.SetCurrentValue(UIElement.RenderTransformProperty, transform.CloneCurrentValue()); + } +} diff --git a/Ink Canvas/UInk/UInkHistorySnapshot.cs b/Ink Canvas/UInk/UInkHistorySnapshot.cs new file mode 100644 index 000000000..0d66c8264 --- /dev/null +++ b/Ink Canvas/UInk/UInkHistorySnapshot.cs @@ -0,0 +1,111 @@ +using Ink_Canvas.Helpers; +using System; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; + +namespace Ink_Canvas.UInk +{ + // 仅在 UI 线程使用。按引用匹配历史,避免回放时改写原 Stroke 或重挂元素。 + internal sealed class UInkHistorySnapshot : UInkHistoryReplay + { + private readonly Dictionary owners = new(ReferenceEqualityComparer.Instance); + private readonly List<(object Item, int Group)> order = new(); + private readonly Dictionary points = new(); + private readonly Dictionary attributes = new(); + internal readonly Dictionary ElementTransforms = new(); + + private int group; + + internal UInkHistorySnapshot(TimeMachineHistory[] history) + { + if (history == null) return; + for (group = 0; group < history.Length; group++) Apply(history[group]); + } + + protected override void Strokes(StrokeCollection strokes, bool insert) + { + if (strokes != null) + foreach (var stroke in strokes) ChangeMembership(stroke, insert); + } + + protected override void Element(UIElement element, bool insert) => ChangeMembership(element, insert); + private void ChangeMembership(object item, bool insert) + { + if (!insert) owners.Remove(item); + else if (owners.TryAdd(item, group)) order.Add((item, group)); + } + + protected override bool Contains(object item) => owners.ContainsKey(item); + protected override void SetPoints(Stroke stroke, StylusPointCollection value) => points[stroke] = value; + protected override void SetAttributes(Stroke stroke, DrawingAttributes value, bool clone) => attributes[stroke] = (value, clone); + protected override void SetTransform(UIElement element, Transform value) => ElementTransforms[element] = value; + + internal void InstallStrokes(StrokeCollection destination) + { + // 曾在场时生效的编辑也属于历史对象,后续撤销删除时仍需保留。 + foreach (var pair in points) pair.Key.StylusPoints = pair.Value; + foreach (var pair in attributes) + pair.Key.DrawingAttributes = pair.Value.NeedsClone ? pair.Value.Value.Clone() : pair.Value.Value; + var final = new UInkStrokeCollection(); + foreach (var stroke in Visible()) final.AppendNew(stroke); + if (final.Count != 0) destination.Add(final); + } + + internal int Owner(object item) => owners.GetValueOrDefault(item, -1); + + internal IEnumerable Visible() where T : class + { + // 删除后重新插入的对象只在最后一次加入的位置输出。 + foreach (var (item, group) in order) + if (item is T value && Owner(item) == group) yield return value; + } + + internal StrokeCollection CloneLegacyStrokes() + { + // 旧格式保留 Stroke 子类及所有扩展属性,编辑只写入副本。 + var copies = new UInkStrokeCollection(); + foreach (var stroke in Visible()) + { + var copy = stroke.Clone(); + if (points.TryGetValue(stroke, out var p)) copy.StylusPoints = p.Clone(); + if (attributes.TryGetValue(stroke, out var da)) copy.DrawingAttributes = da.Value.Clone(); + copies.AppendNew(copy); + } + return copies; + } + + internal void CaptureStrokes(UInkPageInput page, StrokeCollection live) + { + var copies = new UInkStrokeCollection(); + IEnumerable source = live ?? Visible(); + foreach (var stroke in source) + { + if (stroke.ContainsPropertyData(InkFadeManager.LaserRenderModeGuid)) continue; + // 只交付普通 Stroke。识别字形等子类可能持有 UI Geometry,点与 DA 必须独占。 + var p = live == null ? points.GetValueOrDefault(stroke) ?? stroke.StylusPoints : stroke.StylusPoints; + var da = live == null ? attributes.GetValueOrDefault(stroke).Value ?? stroke.DrawingAttributes : stroke.DrawingAttributes; + var copy = new Stroke(p.Clone(), da.Clone()); + if (stroke.ContainsPropertyData(UInkConversion.LogicalPenKindGuid) && + stroke.GetPropertyData(UInkConversion.LogicalPenKindGuid) is int kind) + copy.AddPropertyData(UInkConversion.LogicalPenKindGuid, kind); + if (stroke.ContainsPropertyData(UInkConversion.ImportedOpacityGuid) && + stroke.GetPropertyData(UInkConversion.ImportedOpacityGuid) is float opacity) + copy.AddPropertyData(UInkConversion.ImportedOpacityGuid, opacity); + if (stroke is FilledGlyphStroke glyph) + { + // 保存工作线程只访问冻结的独立几何。验证失败时从真实字形提取轮廓,不能把命中框当轮廓。 + var outline = glyph.GlyphGeometry.CloneCurrentValue(); + outline.Freeze(); + (page.GlyphFallbacks ??= new Dictionary()).Add(copy, outline); + } + IccShapeDescriptor.CopyProperties(stroke, copy); + copies.AppendNew(copy); + page.StrokeOwners.Add(Owner(stroke)); + } + page.Strokes = copies; + } + } +} diff --git a/Ink Canvas/UInk/UInkIccMapper.cs b/Ink Canvas/UInk/UInkIccMapper.cs index 97496921b..ffb16f557 100644 --- a/Ink Canvas/UInk/UInkIccMapper.cs +++ b/Ink Canvas/UInk/UInkIccMapper.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Windows.Forms; using System.Windows.Ink; -using System.Windows.Media; using Ink_Canvas.Helpers; namespace Ink_Canvas.UInk @@ -12,7 +11,31 @@ namespace Ink_Canvas.UInk public sealed class UInkPageData { public UInkCanvas Canvas; - public StrokeCollection FinalStrokes = new StrokeCollection(); + public int Binding => Canvas.LayerIndex == 0 ? Canvas.Binding ?? 0 : 0; + public int? SlideId => Canvas.LayerIndex == 0 ? Canvas.SlideId : null; + public int PageKind => Canvas.LayerIndex == 0 ? Canvas.PageKind ?? 0 : 0; + public int DisplayIndex { get; internal set; } + public int? SlideIndex { get; internal set; } + public bool IsUnbound { get; internal set; } + internal UInkReadResult ReadResult; + internal int LastPosition; + internal bool HasIndexedContent, HasLayerOrderFallback; + internal string[] MediaFiles; + internal Action Materialize; + internal Action ReplayPptPage; + internal List<(IUInkContentBlock Block, Stroke Stroke, int Group)> Items = new(); + public bool IsMaterialized => Materialize == null; + + public void EnsureMaterialized() + { + lock (this) + { + Materialize?.Invoke(this); + Materialize = null; + } + } + + public StrokeCollection FinalStrokes; public TimeMachineHistory[] History; public List Media = new List(); public List Shapes = new List(); @@ -24,12 +47,18 @@ public sealed class UInkPageInput public UInkCanvas Canvas; public StrokeCollection Strokes; public List Media = new List(); + internal readonly List Elements = new(); + internal Action DecodePending; + internal bool PendingMediaOnly; + internal Dictionary GlyphFallbacks; + internal readonly List StrokeOwners = new(); + internal readonly List MediaOwners = new(); } /// /// ICC 运行态 ⇄ UInkDocument 的结构映射(屏幕→Display Device、模式→Workspace、页/PPT 幻灯片→Canvas、viewport)。 /// 设备/工作区/页 GUID 规则见规范:pageGuid 全程唯一;(workspaceKey, deviceKey, pageGuid, layerIndex) 是 Canvas 唯一键。 - /// 写侧把当前可见状态归一化(undoId=0、全 renderOnlyWhenLatest=false)。 + /// 写侧按可见对象的创建操作分组,区间交错时维持画布顺序。 /// public static class UInkIccMapper { @@ -83,13 +112,24 @@ public static UInkCanvas BuildCanvas(string workspaceGuid, string deviceGuid, }; } + internal static UInkCanvas BuildPptCanvas(string workspaceGuid, string deviceGuid, string pageGuid, + uint pageIndex, int? slideId) + { + var canvas = BuildCanvas(workspaceGuid, deviceGuid, pageGuid, pageIndex, pageIndex + 1, + slideId > 0 ? slideId : null, null); + // CANVAS-13:没有可靠 SlideID 的自产普通页明确按页码绑定。 + canvas.Binding = canvas.SlideId.HasValue ? 0 : 1; + return canvas; + } + /// 默认 viewport:ICC 无持久画布变换时用恒等 {0,0,1}。 public static UInkViewport IdentityViewport() => new UInkViewport { X = 0f, Y = 0f, Scale = 1f }; /// 汇总为 UInkDocument:写 Header/HeaderExtension、逐页写 Canvas+内容块、重算 Header 统计。 public static UInkDocument BuildDocument(string headerGuid, IReadOnlyList devices, IReadOnlyList workspaces, - IReadOnlyList pages, ulong nowUnixSeconds) + IReadOnlyList pages, ulong nowUnixSeconds, + double dpiScaleX = 1, double dpiScaleY = 1, Action note = null) { var doc = new UInkDocument { Header = new UInkHeader { Guid = headerGuid, Time = nowUnixSeconds } }; if ((devices != null && devices.Count > 0) || (workspaces != null && workspaces.Count > 0)) @@ -101,26 +141,97 @@ public static UInkDocument BuildDocument(string headerGuid, }; } - uint contentId = 0; + var map = new UInkCoordinateMap(dpiScaleX, dpiScaleY); + if (dpiScaleX != dpiScaleY) note?.Invoke("nonUniformDpi"); foreach (var page in pages) { var record = new UInkCanvasRecord { Canvas = page.Canvas }; - if (page.Strokes != null) + var owners = new List(); + void Append(IUInkContentBlock block, List groups, int index) { - foreach (var ink in UInkConversion.StrokesToInks(page.Strokes, contentId, 0)) - { - record.Blocks.Add(ink); - contentId++; - } + block.ContentId = (uint)record.Blocks.Count; + int owner = index < groups.Count ? groups[index] : -1; + // 无历史对象各占一组;负数与历史序号不相交。 + owners.Add(owner >= 0 ? owner : -1 - owners.Count); + record.Blocks.Add(block); } + + // FILE-14 / Q3:ICC 的媒体位于墨迹下方。 if (page.Media != null) - { - foreach (var media in page.Media) + for (int i = 0; i < page.Media.Count; i++) + Append(page.Media[i], page.MediaOwners, i); + int objectStart = -1, expected = 0; + string objectId = null; + ulong revision = 1; + bool edited = false; + HashSet usedIds = null; + if (page.Strokes != null) + for (int i = 0; i < page.Strokes.Count; i++) { - media.ContentId = contentId++; - media.UndoId = 0; - record.Blocks.Add(media); + var geometry = (page.Strokes[i] as FilledGlyphStroke)?.GlyphGeometry; + if (geometry == null && page.GlyphFallbacks != null) + page.GlyphFallbacks.TryGetValue(page.Strokes[i], out geometry); + if (IccShapeDescriptor.TryExport(page.Strokes, i, map, out var descriptor, out var shape, geometry)) + { + Append(shape, page.StrokeOwners, i); + // SHAPE-11/14:直到末件通过校验才发布对象层。缺件时有效部件各自独立。 + if (descriptor.Part == 0 && descriptor.Count > 0 && descriptor.ObjectId != null) + { + objectStart = record.Blocks.Count - 1; + expected = descriptor.Count; + objectId = descriptor.ObjectId; + revision = descriptor.Revision; + edited = false; + } + if (objectStart >= 0 && descriptor.Part == record.Blocks.Count - 1 - objectStart && + (descriptor.Count == expected || descriptor.Count == 0) && descriptor.ObjectId == objectId) + { + edited |= descriptor.Edited; + if (descriptor.Part + 1 == expected) + { + usedIds ??= new HashSet(); + if (!usedIds.Add(objectId)) + { + objectId = Guid.NewGuid().ToString(); + usedIds.Add(objectId); + } + if (edited && revision < ulong.MaxValue) revision++; + for (int j = 0; j < expected; j++) + { + var part = (UInkShape)record.Blocks[objectStart + j]; + part.Object = j == 0 ? new UInkShapeObject { Id = objectId, Revision = revision, PartCount = (uint)expected } : + new UInkShapeObject { Ref = objectId, PartIndex = (uint)j }; + owners[objectStart + j] = owners[objectStart]; + } + objectStart = -1; + } + } + else objectStart = -1; + i += descriptor.Members - 1; + continue; + } + objectStart = -1; + if (geometry != null) + { + note?.Invoke("glyphOutline"); + foreach (var outline in IccShapeDescriptor.OutlineGlyph(geometry, page.Strokes[i].DrawingAttributes)) + Append(UInkConversion.StrokeToInk(outline, map: map, note: note), page.StrokeOwners, i); + continue; + } + var ink = UInkConversion.StrokeToInk(page.Strokes[i], map: map, note: note); + if (ink != null) Append(ink, page.StrokeOwners, i); } + + // INK-3:交错的插入组必须合并。区间内遇到另一组则延长到其末端。 + var last = new Dictionary(); + for (int i = 0; i < owners.Count; i++) last[owners[i]] = i; + int end = -1; + uint undo = 0; + for (int i = 0; i < owners.Count; i++) + { + if (i > end && i > 0) undo++; + end = Math.Max(end, last[owners[i]]); + record.Blocks[i].UndoId = undo; } doc.Canvases.Add(record); } @@ -134,108 +245,13 @@ public static UInkDocument BuildDocument(string headerGuid, // ==================== 加载方向 ==================== - /// - /// 把文档映射为逻辑页面列表:按 (workspaceGuid, deviceGuid, pageGuid) 合并同页所有 layer, - /// layerIndex 越大越靠前;layer 1+ 继承 layer 0 的 viewport。各 layer 的撤回 delta 链按层顺序拼接。 - /// - public static List ToPages(UInkDocument doc, Func toStroke) + public static UInkPageProjection BuildPageIndex(UInkReadResult read, double dpiScaleX, double dpiScaleY, + Func resolveSlide = null) { - var pages = new List(); - if (doc?.Canvases == null) return pages; - - var groups = doc.Canvases - .Where(x => x?.Canvas != null) - .GroupBy(x => new - { - Workspace = x.Canvas.WorkspaceGuid ?? "", - Device = x.Canvas.DeviceGuid ?? "", - Page = x.Canvas.PageGuid ?? "", - }); - - foreach (var group in groups) - { - var layers = group.OrderBy(x => x.Canvas.LayerIndex).ToList(); - var baseLayer = layers.FirstOrDefault(x => x.Canvas.LayerIndex == 0) ?? layers[0]; - var viewport = baseLayer.Canvas.Viewport; - var page = new UInkPageData { Canvas = baseLayer.Canvas }; - var history = new List(); - - foreach (var record in layers) - { - foreach (var b in record.Blocks) - { - switch (b) - { - case UInkMedia m: page.Media.Add(m); break; - case UInkShape s: page.Shapes.Add(s); break; - } - } - - var adapt = UInkUndoAdapter.Adapt(record, toStroke); - ApplyViewportToAdaptation(adapt, viewport); - foreach (Stroke stroke in adapt.FinalStrokes) - if (!page.FinalStrokes.Contains(stroke)) - page.FinalStrokes.Add(stroke); - if (adapt.History != null) - history.AddRange(adapt.History); - } - - page.History = history.Count == 0 ? null : history.ToArray(); - pages.Add(page); - } - return pages; - } - - /// - /// viewport 必须应用到撤回适配中的所有 Stroke,而不只是最终可见集合;否则 Undo 后重新显露的 - /// renderOnlyWhenLatest 原稿仍停留在 Canvas 世界坐标。用引用去重确保每条 Stroke 只变换一次。 - /// - private static void ApplyViewportToAdaptation(UInkUndoAdaptation adaptation, UInkViewport viewport) - { - if (adaptation == null || viewport == null) return; - if (viewport.Scale <= 0 || !float.IsFinite(viewport.Scale)) return; - if (Math.Abs(viewport.Scale - 1f) < 1e-6 && Math.Abs(viewport.X) < 1e-6 && Math.Abs(viewport.Y) < 1e-6) return; - - var matrix = new Matrix(viewport.Scale, 0, 0, viewport.Scale, - -viewport.X * viewport.Scale, -viewport.Y * viewport.Scale); - var transformed = new HashSet(); - - if (adaptation.FinalStrokes != null) - foreach (Stroke stroke in adaptation.FinalStrokes) - if (transformed.Add(stroke)) stroke.Transform(matrix, false); - - if (adaptation.History == null) return; - foreach (var item in adaptation.History) - { - TransformHistoryCollection(item?.CurrentStroke, matrix, transformed); - TransformHistoryCollection(item?.ReplacedStroke, matrix, transformed); - } - } - - private static void TransformHistoryCollection(StrokeCollection strokes, Matrix matrix, HashSet transformed) - { - if (strokes == null) return; - foreach (Stroke stroke in strokes) - if (transformed.Add(stroke)) - stroke.Transform(matrix, false); - } - - /// - /// 把 Canvas 世界坐标按 viewport 逆变换转回 Device 坐标:device = (canvas − vp.xy) * vp.scale。 - /// History 与 FinalStrokes 共享 Stroke 引用,转换后同步生效。scale=1 且无平移时不动。 - /// - public static void ApplyViewportToStrokes(StrokeCollection strokes, UInkViewport vp) - { - if (strokes == null || strokes.Count == 0 || vp == null) return; - if (vp.Scale <= 0 || !float.IsFinite(vp.Scale)) return; - if (Math.Abs(vp.Scale - 1f) < 1e-6 && Math.Abs(vp.X) < 1e-6 && Math.Abs(vp.Y) < 1e-6) return; - - var matrix = new Matrix(vp.Scale, 0, 0, vp.Scale, -vp.X * vp.Scale, -vp.Y * vp.Scale); - foreach (Stroke stroke in strokes) - stroke.Transform(matrix, false); + return UInkPageProjection.Build(read, dpiScaleX, dpiScaleY, resolveSlide, UInkConversion.BlockToStroke); } - /// 生成文件级 UUID(Header.guid;"另存为"才换)。 + /// 每次完整保存生成新的快照 UUID(Header.guid)。 public static string NewFileGuid() => Guid.NewGuid().ToString(); } } diff --git a/Ink Canvas/UInk/UInkMediaMapper.cs b/Ink Canvas/UInk/UInkMediaMapper.cs new file mode 100644 index 000000000..f96d28784 --- /dev/null +++ b/Ink Canvas/UInk/UInkMediaMapper.cs @@ -0,0 +1,241 @@ +using System; +using System.Globalization; +using System.IO; +using Ink_Canvas.Controls; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace Ink_Canvas.UInk +{ + internal static class UInkMediaMapper + { + internal const long MaxBitmapPixels = 64L * 1024 * 1024; + internal const string NativeVideoLayoutKey = "icc:mediaControl/v1"; + + internal static bool IsVideo(string mime) => mime?.StartsWith("video/", StringComparison.OrdinalIgnoreCase) == true; + + internal static bool IsSvg(string mime) => string.Equals(mime, "image/svg+xml", StringComparison.OrdinalIgnoreCase); + + internal static int FitFromStretch(Stretch stretch) => stretch switch + { + Stretch.Uniform => 1, + Stretch.UniformToFill => 2, + Stretch.None => 3, + _ => 0 + }; + + internal static Stretch StretchFromFit(int? fit) => fit switch + { + 1 => Stretch.Uniform, + 2 => Stretch.UniformToFill, + 3 => Stretch.None, + _ => Stretch.Fill + }; + + internal static UInkMedia Capture(UInkCapturedElement element, UInkCoordinateMap coordinates, string mime) + { + var e = element.Info; + var matrix = element.LayoutMatrix ?? ElementMatrix(element); + var units = element.LocalUnits ?? coordinates; + var preview = element.VideoPreview; + if (preview.HasValue) matrix.TranslatePrepend(preview.Value.X, preview.Value.Y); + var box = units.MediaBoxFromDip(preview?.Width ?? e.Width, preview?.Height ?? e.Height); + var wire = coordinates.MediaMatrixFromDip(matrix, units); + if (!(box.Width > 0 && box.Height > 0) || !float.IsFinite((float)box.Width) || + !float.IsFinite((float)box.Height) || !Array.TrueForAll(wire, float.IsFinite)) + return null; + + float rate = (float)(e.MediaSpeedRatio ?? 1); + return new UInkMedia + { + MimeType = mime, Width = (float)box.Width, Height = (float)box.Height, + Transform = wire, Opacity = (float)Math.Clamp(element.Opacity, 0, 1), + Fit = preview.HasValue ? 1 : element.IgnoreFit ? null : FitFromStretch(element.Stretch), + // TYPE-4:公共框描述视频预览;私有数据只补还原原生控制栏所需的外框。 + Extra = preview is Rect view ? new() + { + [NativeVideoLayoutKey] = FormattableString.Invariant( + $"{e.Width:R};{e.Height:R};{view.X:R};{view.Y:R};{view.Width:R};{view.Height:R};{(float)box.Width:R};{(float)box.Height:R}") + } : null, + PageCount = e.PdfPageCount > 0 ? (uint?)e.PdfPageCount.Value : null, + PageIndex = e.PdfCurrentPage >= 0 ? (uint?)e.PdfCurrentPage.Value : null, + Volume = (float)Math.Clamp(e.MediaVolume ?? 1, 0, 1), + StartTime = Math.Max(0, e.MediaPositionSeconds ?? 0), + PlaybackRate = float.IsFinite(rate) && rate > 0 ? rate : 1, + Autoplay = element.Autoplay, Loop = element.Loop + }; + } + + internal static Matrix ElementMatrix(UInkCapturedElement element, Size? renderSize = null) + { + var e = element.Info; + double x = element.Origin.X * (renderSize?.Width ?? e.Width); + double y = element.Origin.Y * (renderSize?.Height ?? e.Height); + var matrix = Matrix.Identity; + matrix.Translate(-x, -y); + matrix.Append(element.Transform); + matrix.Translate(x + e.Left, y + e.Top); + return matrix; + } + + internal static bool IsResourceFailure(Exception ex) => + ex is IOException or InvalidDataException or UnauthorizedAccessException or FormatException or NotSupportedException or + ArgumentException or InvalidOperationException or System.Runtime.InteropServices.COMException; + + internal static UInkCoordinateMap PageCoordinates(UInkCanvas canvas, double dpiX, double dpiY) => + new(dpiX, dpiY, canvas?.LayerIndex == 0 ? canvas.Viewport : null); + + internal static bool TryGetNativeVideoLayout(UInkMedia media, Size mappedPreview, out Size outer, out Point inset) + { + outer = default; + inset = default; + if (!IsVideo(media.MimeType) || media.Fit != 1 || media.Crop != null || media.Extra == null || + !media.Extra.TryGetValue(NativeVideoLayoutKey, out string raw) || raw == null || raw.Length > 240) + return false; + + var fields = raw.Split(';'); + if (fields.Length != 8) return false; + Span values = stackalloc double[8]; + for (int i = 0; i < values.Length; i++) + if (!double.TryParse(fields[i], NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]) || + !double.IsFinite(values[i])) + return false; + // 公共框或 fit 被其他软件改过时,遵循公共字段。公共仿射变换始终应用到原预览原点。 + if (media.Width != (float)values[6] || media.Height != (float)values[7] || + values[2] < 0 || values[3] < 0 || values[4] <= 0 || values[5] <= 0 || + values[0] + 1e-6 < values[2] + values[4] || values[1] + 1e-6 < values[3] + values[5]) + return false; + + double sx = mappedPreview.Width / values[4], sy = mappedPreview.Height / values[5]; + double width = values[0] * sx, height = values[1] * sy; + if (!double.IsFinite(width) || !double.IsFinite(height) || width <= 0 || height <= 0) return false; + outer = new Size(width, height); + inset = new Point(values[2] * sx, values[3] * sy); + return true; + } + + internal static void ApplyLayout(FrameworkElement element, UInkMedia media, UInkCoordinateMap coordinates) + { + var box = coordinates.MediaBoxToDip(media.Width ?? 800, media.Height ?? + (media.MimeType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) ? 168 : 520)); + var matrix = coordinates.MapMediaMatrix(media.Transform); + if (element is CanvasMediaControl && TryGetNativeVideoLayout(media, box, out var outer, out var inset)) + { + box = outer; + matrix.TranslatePrepend(-inset.X, -inset.Y); + } + element.Width = box.Width; + element.Height = box.Height; + element.Opacity = Math.Clamp(media.Opacity ?? 1, 0, 1); + element.RenderTransformOrigin = new Point(0, 0); + element.RenderTransform = new MatrixTransform(matrix); + InkCanvas.SetLeft(element, 0); + InkCanvas.SetTop(element, 0); + } + + internal static Rect FitBox(Size box, Size source, Stretch stretch) + { + if (stretch == Stretch.Fill) return new Rect(box); + double x = box.Width / source.Width, y = box.Height / source.Height; + double scale = stretch == Stretch.None ? 1 : stretch == Stretch.UniformToFill ? Math.Max(x, y) : Math.Min(x, y); + double width = source.Width * scale, height = source.Height * scale; + // WPF 默认 Stretch 对齐遇到溢出时靠左或靠上,其余方向居中。 + return new Rect(Math.Max(0, (box.Width - width) / 2), Math.Max(0, (box.Height - height) / 2), width, height); + } + + internal static BitmapSource BakeBitmapRegion(BitmapSource bitmap, Rect region) + { + int x = (int)Math.Round(region.X), y = (int)Math.Round(region.Y); + int width = (int)Math.Round(region.Width), height = (int)Math.Round(region.Height); + if (width > 0 && height > 0 && x >= 0 && y >= 0 && x + width <= bitmap.PixelWidth && y + height <= bitmap.PixelHeight && + Math.Abs(region.X - x) < 1e-6 && Math.Abs(region.Y - y) < 1e-6 && + Math.Abs(region.Width - width) < 1e-6 && Math.Abs(region.Height - height) < 1e-6) + return new CroppedBitmap(bitmap, new Int32Rect(x, y, width, height)); + + // 小数像素边界不能四舍五入成整数裁剪;按可见区域重采样,输出不超过源位图尺寸。 + width = Math.Min(bitmap.PixelWidth, (int)Math.Ceiling(region.Width)); + height = Math.Min(bitmap.PixelHeight, (int)Math.Ceiling(region.Height)); + if ((long)width * height > MaxBitmapPixels) return null; + double sx = width / region.Width, sy = height / region.Height; + var visual = new DrawingVisual(); + using (var dc = visual.RenderOpen()) + dc.DrawImage(bitmap, new Rect(-region.X * sx, -region.Y * sy, bitmap.PixelWidth * sx, bitmap.PixelHeight * sy)); + var target = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); + target.Render(visual); + target.Freeze(); + return target; + } + + internal static void EncodePng(BitmapSource bitmap, Stream output) + { + var encoder = new PngBitmapEncoder(); + encoder.Frames.Add(BitmapFrame.Create(bitmap)); + encoder.Save(output); + } + + internal static BitmapSource DecodeBitmap(string path, long remainingPixels = long.MaxValue) + { + using var stream = File.OpenRead(path); + return DecodeBitmap(stream, remainingPixels); + } + + internal static BitmapSource DecodeBitmap(Stream stream, long remainingPixels) + { + var metadata = BitmapFrame.Create(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); + if ((long)metadata.PixelWidth * metadata.PixelHeight > Math.Min(MaxBitmapPixels, remainingPixels)) + throw new InvalidDataException("UInk bitmap pixel budget exceeded."); + var bitmap = new CachedBitmap(metadata, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); + bitmap.Freeze(); + return bitmap; + } + } + + internal sealed class UInkMissingMedia : Border + { + internal UInkMissingMedia(string path) + { + BorderBrush = Brushes.Gray; + BorderThickness = new Thickness(1); + Background = Brushes.Transparent; + ClipToBounds = true; + // 路径取名字作为标签;对不安全路径只显示警示符号。 + string safe = UInkExtraArchive.NormalizeEntryPath(path); + string name = safe == null ? "" : Path.GetFileName(safe); + if (name.Length > 40) name = name.Substring(0, 37) + "…"; + Child = new TextBlock { Text = "⚠ " + name, Margin = new Thickness(4), + TextTrimming = TextTrimming.CharacterEllipsis }; + } + } + + internal sealed class UInkBitmapImage : Image + { + private BitmapSource _bitmap; + internal string SourcePath => ReferenceEquals(Source, _bitmap) ? _sourcePath : null; + internal UInkBitmapFileStamp? SourceStamp { get; private set; } + private string _sourcePath; + + internal UInkBitmapImage(UInkMedia media) => Stretch = UInkMediaMapper.StretchFromFit(media.Fit); + + internal void SetBitmap(BitmapSource bitmap, string path, UInkBitmapFileStamp stamp) + { + _sourcePath = path; + SourceStamp = stamp; + Source = _bitmap = bitmap; + } + + protected override void OnRender(DrawingContext context) + { + if (Source == null) + { + // 离页准备期间和解码失败后继续占用原图的布局与撤销槽。 + var pen = new Pen(Brushes.Gray, 1); + context.DrawRectangle(Brushes.Transparent, pen, new Rect(RenderSize)); + context.DrawLine(pen, new Point(), new Point(RenderSize.Width, RenderSize.Height)); + return; + } + base.OnRender(context); + } + } +} diff --git a/Ink Canvas/UInk/UInkMediaRestoreCache.cs b/Ink Canvas/UInk/UInkMediaRestoreCache.cs new file mode 100644 index 000000000..bf1be01df --- /dev/null +++ b/Ink Canvas/UInk/UInkMediaRestoreCache.cs @@ -0,0 +1,199 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using System.Windows.Media.Imaging; + +namespace Ink_Canvas.UInk +{ + internal sealed class UInkMediaRestoreCache : IDisposable + { + // P6 的持久缓存回收入口使用同一个目录名;本阶段只清理会话的提取目录。 + internal const string CacheDirectoryName = "UInk Media"; + private readonly ConcurrentDictionary bitmaps = new(StringComparer.Ordinal); + private bool missingNoticeTaken, layoutNoticeTaken; + private long remainingBitmapPixels = 128L * 1024 * 1024; + + private readonly UInkExtraArchive archive; + private readonly string extractDir, cacheDir; + private readonly Dictionary extracted = new(StringComparer.Ordinal); + private readonly HashSet verified = new(StringComparer.Ordinal); + + internal UInkMediaRestoreCache(UInkExtraArchive archive, string extractDir, string cacheDir) + { + this.archive = archive; + this.extractDir = extractDir; + this.cacheDir = cacheDir; + } + + private int references = 1; + private bool ownsArchive; + + internal static UInkMediaRestoreCache Open(string mainPath, string cacheDir) + { + string path = mainPath + ".extra"; + if (!File.Exists(path)) return new UInkMediaRestoreCache(null, null, cacheDir); + return FromStream(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete), cacheDir); + } + + internal static UInkMediaRestoreCache FromStream(FileStream stream, string cacheDir) + { + if (stream == null) return new UInkMediaRestoreCache(null, null, cacheDir); + UInkExtraArchive archive = null; + try + { + archive = new UInkExtraArchive(stream); + string temp = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), + "UInkOpen_" + Guid.NewGuid().ToString("N"))).FullName; + return new UInkMediaRestoreCache(archive, temp, cacheDir) { ownsArchive = true }; + } + catch + { + archive?.Dispose(); + throw; + } + } + + // 离页快照可能仍在后台读取同一资源包,最后一个持有者负责关闭与清理。 + internal UInkMediaRestoreCache Retain() + { + System.Threading.Interlocked.Increment(ref references); + return this; + } + + public void Dispose() + { + if (System.Threading.Interlocked.Decrement(ref references) != 0 || !ownsArchive) return; + archive?.Dispose(); + try { if (extractDir != null) Directory.Delete(extractDir, true); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + + internal string GetVerifiedPath(string entryPath, string mime) + { + // ICC 无 SVG 解码器。EXTRA-9/11:标为不可用,无需提取或预检内容。 + if (UInkMediaMapper.IsSvg(mime)) return null; + lock (extracted) return ExtractVerified(entryPath, mime); + } + + internal BitmapSource GetBitmap(string verifiedPath) + { + lock (extracted) + { + if (!bitmaps.TryGetValue(verifiedPath, out var prepared)) + { + // EXTRA-7:同一会话的独立位图共同消耗解码预算,异常也记一次。 + bitmaps[verifiedPath] = default; + using var input = File.OpenRead(verifiedPath); + var stamp = UInkBitmapFileStamp.Read(input); + var bitmap = UInkMediaMapper.DecodeBitmap(input, remainingBitmapPixels); + bitmaps[verifiedPath] = prepared = (bitmap, stamp); + remainingBitmapPixels -= (long)bitmap.PixelWidth * bitmap.PixelHeight; + } + return prepared.Bitmap; + } + } + + // 供 UI 取已冻结结果,避免等待另存或下一页持有的提取锁。 + internal BitmapSource GetPreparedBitmap(string verifiedPath, out UInkBitmapFileStamp stamp) + { + bitmaps.TryGetValue(verifiedPath, out var prepared); + stamp = prepared.Stamp; + return prepared.Bitmap; + } + + internal bool TryTakeMissingNotice() + { + if (missingNoticeTaken) return false; + missingNoticeTaken = true; + return true; + } + + internal bool TryTakeLayoutNotice() + { + if (layoutNoticeTaken) return false; + layoutNoticeTaken = true; + return true; + } + + private string ExtractVerified(string entryPath, string mime) + { + string key = UInkExtraArchive.NormalizeEntryPath(entryPath); + string extension = CanonicalExtension(mime); + if (key == null || extension == null || archive == null || extractDir == null) return null; + if (!extracted.TryGetValue(key, out var entry)) + { + // EXTRA-7/8:同一打开会话中,规范化条目只提取一次,失败的条目也记住。 + extracted.Add(key, default); + string temp = Path.Combine(extractDir, Guid.NewGuid().ToString("N")); + if (!archive.TryExtractEntry(key, temp)) return null; + using var input = new BinaryReader(File.OpenRead(temp)); + byte[] header = input.ReadBytes(4096); + input.BaseStream.Position = 0; + entry = (temp, header, Hash(input.BaseStream), input.BaseStream.Length); + extracted[key] = entry; + } + + if (entry.File == null || !UInkExtraArchive.IsMimeConsistent(mime, entry.Header)) return null; + string cached = Path.Combine(cacheDir, entry.Hash + extension); + if (verified.Contains(cached)) return cached; + + Directory.CreateDirectory(cacheDir); + // EXTRA-10/17:缓存命中也核对字节,确保控件收到的文件与此次嗅探的内容一致。 + if (!HasHash(cached, entry.Hash, entry.Length)) + { + string staging = cached + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + File.Copy(entry.File, staging); + File.Move(staging, cached, true); + } + finally { if (File.Exists(staging)) File.Delete(staging); } + } + verified.Add(cached); + return cached; + } + + private static bool HasHash(string path, string expected, long length) + { + try + { + using var input = File.OpenRead(path); + return input.Length == length && Hash(input) == expected; + } + catch (FileNotFoundException) { return false; } + } + + private static string Hash(Stream input) + { + using var sha = SHA256.Create(); + return Convert.ToHexString(sha.ComputeHash(input)).ToLowerInvariant(); + } + + internal static string CanonicalExtension(string mime) => mime?.ToLowerInvariant() switch + { + "image/png" => ".png", + "image/jpeg" => ".jpg", + "image/gif" => ".gif", + "image/bmp" => ".bmp", + "image/webp" => ".webp", + "image/tiff" => ".tif", + "application/pdf" => ".pdf", + "audio/mpeg" => ".mp3", + "audio/wav" => ".wav", + "audio/mp4" => ".m4a", + "audio/aac" => ".aac", + "audio/flac" => ".flac", + "video/mp4" => ".mp4", + "video/quicktime" => ".mov", + "video/webm" => ".webm", + "video/x-msvideo" => ".avi", + "video/x-matroska" => ".mkv", + "video/x-ms-wmv" => ".wmv", + "video/x-flv" => ".flv", + _ => null + }; + } +} diff --git a/Ink Canvas/UInk/UInkMediaWorkSet.cs b/Ink Canvas/UInk/UInkMediaWorkSet.cs new file mode 100644 index 000000000..951c1ea5c --- /dev/null +++ b/Ink Canvas/UInk/UInkMediaWorkSet.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Media.Imaging; + +namespace Ink_Canvas.UInk +{ + internal readonly record struct UInkBitmapFileStamp(long Length, DateTime LastWriteUtc) + { + internal static UInkBitmapFileStamp Read(FileStream file) => new(file.Length, File.GetLastWriteTimeUtc(file.Name)); + } + + internal sealed class UInkMediaWorkSet : IDisposable + { + private sealed record StagedFile(string File, byte[] Header, string HashPath); + + private readonly Dictionary _files = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _stagedByHash = new(StringComparer.Ordinal); + private readonly Dictionary<(string File, string Mime), string> _fileEntries = new(); + private readonly Dictionary _bitmaps = new(ReferenceEqualityComparer.Instance); + private readonly HashSet _entries = new(StringComparer.Ordinal); + private string _directory; + private int _serial; + private byte[] _copyBuffer; + private long _bytes; + private long _stagedBytes; + + internal readonly List<(string EntryPath, string SourceFile)> Resources = new(); + + internal string Add(string source, BitmapSource bitmap, string mime, UInkBitmapFileStamp? expectedStamp = null) + { + if (UInkMediaMapper.IsSvg(mime)) return null; + string ext = UInkMediaRestoreCache.CanonicalExtension(mime); + if (ext == null || (source == null && (bitmap == null || ext != ".png"))) return null; + if (source == null && _bitmaps.TryGetValue(bitmap, out var cached)) return cached; + _directory ??= Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "UInkSave_" + Guid.NewGuid().ToString("N"))).FullName; + + string staged, entry; + var sourceKey = (source?.ToUpperInvariant(), mime.ToLowerInvariant()); + if (source != null) + { + if (!_files.TryGetValue(source, out var stagedSource)) + { + var stagedFile = StageSource(source, out var stamp); + stagedSource = (stagedFile, stamp); + _files.Add(source, stagedSource); + } + var copy = stagedSource.Copy; + // EXTRA-10:先嗅探同一份暂存副本,再核对加载时的指纹或冻结像素。 + if (copy == null || !UInkExtraArchive.IsMimeConsistent(mime, copy.Header)) return null; + if (bitmap != null && (expectedStamp.HasValue + ? expectedStamp.Value != stagedSource.Stamp : !MatchesBitmapCached(source, stagedSource.Stamp, copy.File, bitmap))) + return null; + if (_fileEntries.TryGetValue(sourceKey, out var entryPath)) return entryPath; + staged = copy.File; + entry = Path.ChangeExtension(copy.HashPath, ext); + } + else + { + if ((long)bitmap.PixelWidth * bitmap.PixelHeight > UInkMediaMapper.MaxBitmapPixels) return null; + staged = NewStagePath(); + using (var output = File.Create(staged)) UInkMediaMapper.EncodePng(bitmap, output); + entry = UInkExtraArchive.ContentHashPath(staged, ext); + } + + long length = new FileInfo(staged).Length; + if (!_entries.Contains(entry)) + { + if (length > UInkExtraArchive.MaxSingleEntryBytes || + length > UInkExtraArchive.MaxTotalBytes - _bytes || _entries.Count >= UInkExtraArchive.MaxEntries) + { + if (source == null) File.Delete(staged); + return null; + } + _entries.Add(entry); + _bytes += length; + Resources.Add((entry, staged)); + } + else if (source == null) File.Delete(staged); + + if (source == null) _bitmaps.Add(bitmap, entry); + else _fileEntries[sourceKey] = entry; + return entry; + } + + // 已核验通过的显示位图记住源路径与文件指纹;指纹不变时后续保存不再整图解码。 + private static readonly ConditionalWeakTable> VerifiedBitmaps = new(); + + private static bool MatchesBitmapCached(string source, UInkBitmapFileStamp stamp, string staged, BitmapSource displayed) + { + if (VerifiedBitmaps.TryGetValue(displayed, out var verified) && + string.Equals(verified.Item1, source, StringComparison.OrdinalIgnoreCase) && verified.Item2 == stamp) + return true; + if (!MatchesBitmap(staged, displayed)) return false; + VerifiedBitmaps.AddOrUpdate(displayed, Tuple.Create(source, stamp)); + return true; + } + + private static bool MatchesBitmap(string staged, BitmapSource displayed) + { + // 普通图片入口未记录加载指纹。只在后台比较暂存副本与冻结位图,无法确认时交给 PNG 路径。 + try + { + var decoded = UInkMediaMapper.DecodeBitmap(staged); + if (decoded.PixelWidth != displayed.PixelWidth || decoded.PixelHeight != displayed.PixelHeight || + decoded.DpiX != displayed.DpiX || decoded.DpiY != displayed.DpiY || + decoded.Format != displayed.Format || decoded.Palette != null || displayed.Palette != null) + return false; + + int stride = (decoded.PixelWidth * decoded.Format.BitsPerPixel + 7) / 8; + var expected = new byte[stride]; + var actual = new byte[stride]; + for (int row = 0; row < decoded.PixelHeight; row++) + { + var area = new Int32Rect(0, row, decoded.PixelWidth, 1); + displayed.CopyPixels(area, expected, stride, 0); + decoded.CopyPixels(area, actual, stride, 0); + if (!expected.AsSpan().SequenceEqual(actual)) return false; + } + return true; + } + catch (Exception ex) when (UInkMediaMapper.IsResourceFailure(ex)) + { + return false; + } + } + + private string NewStagePath() => Path.Combine(_directory, (++_serial).ToString()); + + private StagedFile StageSource(string source, out UInkBitmapFileStamp stamp) + { + stamp = default; + string staged = NewStagePath(); + bool keep = false; + try + { + // EXTRA-17:只打开原文件一次,嗅探、哈希与 ZIP 都读取同一份工作副本。 + using var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read); + const long limit = UInkExtraArchive.MaxSingleEntryBytes; + stamp = UInkBitmapFileStamp.Read(input); + if (stamp.Length > limit) return default; + using (var output = File.Create(staged)) + { + _copyBuffer ??= new byte[64 * 1024]; + int count; + while ((count = input.Read(_copyBuffer, 0, _copyBuffer.Length)) != 0) + { + if (count > limit - output.Length) return default; + output.Write(_copyBuffer, 0, count); + } + } + + string hashPath = UInkExtraArchive.ContentHashPath(staged, ".bin"); + if (_stagedByHash.TryGetValue(hashPath, out var existing)) return existing; + using var reader = new BinaryReader(File.OpenRead(staged)); + long length = reader.BaseStream.Length; + if (length > UInkExtraArchive.MaxTotalBytes - _stagedBytes) return null; + var copy = new StagedFile(staged, reader.ReadBytes(4096), hashPath); + _stagedByHash.Add(hashPath, copy); + _stagedBytes += length; + keep = true; + return copy; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return default; + } + finally + { + if (!keep && File.Exists(staged)) File.Delete(staged); + } + } + + public void Dispose() + { + if (_directory == null) return; + try { Directory.Delete(_directory, true); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } +} diff --git a/Ink Canvas/UInk/UInkMetadataDecoder.cs b/Ink Canvas/UInk/UInkMetadataDecoder.cs new file mode 100644 index 000000000..b10a8b1e2 --- /dev/null +++ b/Ink Canvas/UInk/UInkMetadataDecoder.cs @@ -0,0 +1,202 @@ +using System; +using System.Collections.Generic; +using MessagePack; + +namespace Ink_Canvas.UInk +{ + internal sealed partial class UInkDecoder + { + private readonly UInkReadResult result; + internal UInkDecoder(UInkReadResult result) => this.result = result; + private static readonly UInkSchema TypeKey = new(1, "type"); + private static readonly UInkSchema ExtensionKeys = new(1, "type name explanation devices workspaces extra"); + private static readonly UInkSchema DeviceKeys = new(2, "guid deviceType name hardware x y width height parentDeviceGuid zIndex extra"); + private static readonly UInkSchema HardwareKeys = new(0, "name id identifiers physicalWidth physicalHeight scaleFactor"); + private static readonly UInkSchema WorkspaceKeys = new(2, "guid workspaceType name parentWorkspaceGuid hostId currentPageIndex extra"); + private static readonly UInkSchema CanvasKeys = new(6, "type pageGuid pageIndex pageNumber layerIndex layerNumber workspaceGuid deviceGuid slideId viewport background pageState pageKind binding extra"); + private static readonly UInkSchema BackgroundKeys = new(1, "color pattern"); + private static readonly UInkSchema ViewportKeys = new(3, "x y scale"); + private UInkFields Fields(UInkValue raw, UInkSchema keys) => new(raw, keys, result); + private Dictionary Extra(UInkFields f) => UInkFields.Strings(f["extra"], true, result); + + internal static int Type(UInkValue raw) + { + var r = raw.Reader(); + if (r.NextMessagePackType == MessagePackType.Array) return 0; + if (r.NextMessagePackType != MessagePackType.Map) return -1; + int n = r.ReadMapHeader(); + for (int i = 0; i < n; i++) + { + if (TypeKey.Key(ref r) == 0) return (int)UInkNumeric.Unsigned(ref r, ushort.MaxValue); + r.Skip(); + } + return -1; + } + + internal UInkHeader Header(UInkValue raw) + { + var r = raw.Reader(); + if (r.NextMessagePackType != MessagePackType.Array || r.ReadArrayHeader() != 7 || + UInkNumeric.Unsigned(ref r, ushort.MaxValue) != 0) throw new UInkFieldException(); + ushort version = (ushort)UInkNumeric.Unsigned(ref r, ushort.MaxValue); + result.Version = version; + if (version < 10 || version > 19) throw new UInkFieldException(); // HDR-2、VER-3 + return new UInkHeader + { + Version = version, Guid = UInkValue.Take(ref r).GuidText(), + DeviceNum = (uint)UInkNumeric.Unsigned(ref r, uint.MaxValue), + WorkspaceNum = (uint)UInkNumeric.Unsigned(ref r, uint.MaxValue), + PageNum = (uint)UInkNumeric.Unsigned(ref r, uint.MaxValue), Time = UInkNumeric.Unsigned(ref r) + }; + } + + internal UInkHeaderExtension Extension(UInkValue raw) + { + var f = Fields(raw, ExtensionKeys); + return new UInkHeaderExtension + { + Name = f.Text("name"), Explanation = f.Text("explanation"), Extra = Extra(f), + Devices = Registry(f["devices"], Device, d => d.Guid, d => d.ParentDeviceGuid, d => d.ParentDeviceGuid = null, out bool devicesDeclared), + Workspaces = Registry(f["workspaces"], Workspace, w => w.Guid, w => w.ParentWorkspaceGuid, w => w.ParentWorkspaceGuid = null, out bool workspacesDeclared), + DevicesDeclared = devicesDeclared, WorkspacesDeclared = workspacesDeclared + }; + } + + private List Registry(UInkValue raw, Func decode, Func id, + Func parent, Action detach, out bool declared) where T : class + { + declared = false; + if (!raw.Present) return null; + var r = raw.Reader(); + if (r.NextMessagePackType != MessagePackType.Array) throw new UInkFieldException(); + int count = r.ReadArrayHeader(); + // HEXT-3/5:空数组是隐式单例,非空数组即使修复后全空也保留显式身份。 + declared = count > 0; + if (count > 1024) throw new UInkBudgetException(); + var list = new List(count); + var byId = new Dictionary(count); + for (int i = 0; i < count; i++) + { + var value = UInkValue.Take(ref r); + try + { + T item = decode(value); + if (byId.TryAdd(id(item), item)) list.Add(item); + else result.Note("HEXT-2"); + } + catch (UInkFieldException ex) when (ex is not UInkDuplicateKey) { result.Note("HEXT-13"); } + } + // DEV-7、HEXT-13:每条父引用最多遍历一次,保留注册顺序。 + var visited = new HashSet(); + var chain = new HashSet(); + foreach (T start in list) + { + chain.Clear(); + T item = start; + while (visited.Add(item)) + { + chain.Add(item); + string p = parent(item); + if (p == null) break; + if (!byId.TryGetValue(p, out var next) || chain.Contains(next)) + { + detach(item); + result.Note("FILE-22"); + break; + } + item = next; + } + } + return list; + } + + private UInkDevice Device(UInkValue raw) + { + var f = Fields(raw, DeviceKeys); + var d = new UInkDevice { Guid = f["guid"].GuidText(), DeviceType = f["deviceType"].Int(), Name = f.Text("name"), Extra = Extra(f) }; + if (f["hardware"].Present) d.Hardware = Recover(f["hardware"], Hardware, "DEV-4"); + // 先收齐字段再解释坐标;Window 与 Display 的同名键有不同数值类型。 + if (d.DeviceType == 0) + { + d.DisplayX = f["x"].Int(); d.DisplayY = f["y"].Int(); + d.DisplayWidth = f["width"].UInt(); d.DisplayHeight = f["height"].UInt(); + if (d.DisplayWidth == 0 || d.DisplayHeight == 0) throw new UInkFieldException(); + } + else if (d.DeviceType == 1) + { + d.WindowX = f["x"].Float(); d.WindowY = f["y"].Float(); + d.WindowWidth = f["width"].Positive(); d.WindowHeight = f["height"].Positive(); + d.ZIndex = f["zIndex"].UInt(); + if (f["parentDeviceGuid"].Present) d.ParentDeviceGuid = f["parentDeviceGuid"].GuidText(); + else result.Note("DEV-7"); + } + else { d.DeviceType = 0; result.Note("FILE-21"); } + return d; + } + + private UInkHardware Hardware(UInkValue raw) + { + var f = Fields(raw, HardwareKeys); + var h = new UInkHardware { Name = f.Text("name"), Id = f.Text("id"), + Identifiers = UInkFields.Strings(f["identifiers"], false, result), + PhysicalWidth = f.UInt("physicalWidth"), PhysicalHeight = f.UInt("physicalHeight"), + ScaleFactor = f.Float("scaleFactor") }; + if (h.PhysicalWidth == 0 || h.PhysicalHeight == 0 || h.ScaleFactor <= 0) throw new UInkFieldException(); + return h; + } + + private UInkWorkspace Workspace(UInkValue raw) + { + var f = Fields(raw, WorkspaceKeys); + var w = new UInkWorkspace { Guid = f["guid"].GuidText(), WorkspaceType = f["workspaceType"].Int(), + Name = f.Text("name"), HostId = f.Text("hostId"), CurrentPageIndex = f.UInt("currentPageIndex"), Extra = Extra(f) }; + if (f["parentWorkspaceGuid"].Present) w.ParentWorkspaceGuid = f["parentWorkspaceGuid"].GuidText(); + if (w.WorkspaceType < 0 || w.WorkspaceType > 2) + { + w.WorkspaceType = 1; w.HostId = null; result.Note("HEXT-14"); + } + return w; + } + + private T Recover(UInkValue value, Func decode, string rule) where T : class + { + if (!value.Present) return null; + try { return decode(value); } + catch (UInkFieldException ex) when (ex is not UInkDuplicateKey) { result.Note(rule); return null; } + } + + internal UInkCanvas Canvas(UInkValue raw) + { + var f = Fields(raw, CanvasKeys); + var c = new UInkCanvas { PageGuid = f["pageGuid"].GuidText(), PageIndex = f["pageIndex"].UInt(), + PageNumber = f["pageNumber"].UInt(), LayerIndex = f["layerIndex"].UInt(), LayerNumber = f["layerNumber"].UInt(), + SlideId = f.Int("slideId"), Extra = Extra(f) }; + if (f["workspaceGuid"].Present) c.WorkspaceGuid = f["workspaceGuid"].GuidText(); + if (f["deviceGuid"].Present) c.DeviceGuid = f["deviceGuid"].GuidText(); + if (c.LayerIndex != 0) + { + if (f["viewport"].Present || f["background"].Present || f["pageState"].Present || f["pageKind"].Present || f["binding"].Present) + result.Note("CANVAS-8"); + return c; + } + c.PageState = f["pageState"].Enum(result, 1, "CANVAS-12"); + c.PageKind = f["pageKind"].Enum(result, 1, "CANVAS-12"); + c.Binding = f["binding"].Enum(result, 1, "CANVAS-12"); + c.Viewport = Recover(f["viewport"], Viewport, "CANVAS-22"); + c.Background = Recover(f["background"], Background, "CANVAS-10"); + return c; + } + + private UInkViewport Viewport(UInkValue raw) + { + var f = Fields(raw, ViewportKeys); + return new UInkViewport { X = f["x"].Float(), Y = f["y"].Float(), Scale = f["scale"].Positive() }; + } + + private UInkBackground Background(UInkValue raw) + { + var f = Fields(raw, BackgroundKeys); + return new UInkBackground { Color = Color(f["color"]), Pattern = f["pattern"].Enum(result, 2, "CANVAS-9") }; + } + } +} diff --git a/Ink Canvas/UInk/UInkModel.cs b/Ink Canvas/UInk/UInkModel.cs index 30ee4f0fd..5baedf0ed 100644 --- a/Ink Canvas/UInk/UInkModel.cs +++ b/Ink Canvas/UInk/UInkModel.cs @@ -4,7 +4,7 @@ namespace Ink_Canvas.UInk { // ============================================================ - // UInk 1.0 Beta(规范 version 10)模型契约 + // UInk 1.1(规范 version 11)模型契约 // 顶层块类型 ID // ============================================================ public enum UInkBlockType : ushort @@ -15,6 +15,7 @@ public enum UInkBlockType : ushort Ink = 3, Media = 4, Shape = 5, + Clear = 6, } /// Ink 渲染类型(inkType)。ICC 统一使用 Pen=1,透明度经块级 opacity 承载。 @@ -60,7 +61,23 @@ public enum UInkFillType : int } /// Ink/Shape/Media 内容块统一标记接口(字段以具体类型访问)。 - public interface IUInkContentBlock { } + public interface IUInkContentBlock + { + uint ContentId { get; set; } + uint UndoId { get; set; } + } + + public abstract class UInkContentBlock : IUInkContentBlock + { + public uint ContentId; + public uint UndoId; + // 读取来源信息仅供投影使用,不写回 wire。 + internal int? PhysicalFrameOrdinal { get; set; } + public int? PhysicalUndoGroupOrdinal { get; internal set; } + internal int? StreamOffset { get; set; } + uint IUInkContentBlock.ContentId { get => ContentId; set => ContentId = value; } + uint IUInkContentBlock.UndoId { get => UndoId; set => UndoId = value; } + } // ============================================================ // Header(Type ID = 0,强制 array(7)) @@ -68,7 +85,7 @@ public interface IUInkContentBlock { } public sealed class UInkHeader { public ushort Type = (ushort)UInkBlockType.Header; // 固定 0 - public ushort Version = 10; // 固定 10 + public ushort Version = 11; public string Guid = ""; // 36 字符 UUID,标识同一逻辑文件 public uint DeviceNum; public uint WorkspaceNum; @@ -81,6 +98,7 @@ public sealed class UInkHeader // ============================================================ public sealed class UInkHeaderExtension { + internal bool DevicesDeclared, WorkspacesDeclared; public string Name; // 可选 public string Explanation; // 可选 public List Devices; // Device 注册表 @@ -148,6 +166,12 @@ public sealed class UInkViewport public float Scale = 1f; } + public sealed class UInkBackground + { + public UInkColor Color; + public int? Pattern; + } + public sealed class UInkCanvas { public string WorkspaceGuid = ""; // 用显式 Workspace 注册表时必填,否则省略 @@ -157,6 +181,8 @@ public sealed class UInkCanvas public uint PageNumber; public uint LayerIndex; public uint LayerNumber; + public UInkBackground Background; + public int? PageState, PageKind, Binding; public int? SlideId; // PPT Workspace 必填的 PowerPoint COM SlideID public UInkViewport Viewport; // 仅 layerIndex=0 可保存 public Dictionary Extra; @@ -175,24 +201,29 @@ public sealed class UInkColor // ============================================================ // Ink(Type ID = 3) // ============================================================ - public sealed class UInkInkPoint + // INK-4:保留线上的相对位移,显示层负责累加。 + public readonly struct UInkPoint { - public float X; // 首点绝对 X,后续点为相对前一点位移 - public float Y; // 同上 - public float Width; // 该点完整直径,> 0 - public UInkColor Color; // 高级荧光笔点级颜色(可选) - public float? Opacity; // 高级荧光笔点级透明度(与 Color 成对) + public readonly float X, Y, Width; + public UInkPoint(float x, float y, float width) => (X, Y, Width) = (x, y, width); } - public sealed class UInkInk : IUInkContentBlock + public sealed class UInkNib + { + public int Shape, Orientation; + public float? Aspect; + } + + public sealed class UInkInk : UInkContentBlock { - public uint ContentId; - public uint UndoId; public int InkType = (int)UInkInkType.Pen; public UInkColor Color = new UInkColor(); public float Opacity = 1f; public int Texture; - public List Points = new List(); + public UInkPoint[] Points = Array.Empty(); + public List<(int Index, UInkColor Color, float Opacity)> StyleAnchors; + public UInkNib Nib; + public int? Cap; public bool RenderOnlyWhenLatest; public Dictionary Extra; } @@ -200,7 +231,7 @@ public sealed class UInkInk : IUInkContentBlock // ============================================================ // Shape(Type ID = 5,参数化图形) // ============================================================ - public sealed class UInkShapePoint + public struct UInkShapePoint { public float X; // Canvas 绝对坐标 public float Y; @@ -219,6 +250,7 @@ public sealed class UInkRectGeometry : UInkShapeGeometry public float CenterY; public float Width; public float Height; + public float? CornerRadiusX, CornerRadiusY; public float? Rotation; // 弧度,正值顺时针 } @@ -244,6 +276,8 @@ public sealed class UInkStroke public float Width; public List DashArray; // 可选,偶数个非负有限值 public float? DashOffset; + public int? LineCap, LineJoin; + internal bool UnknownMarker; public int? StartMarker; public int? EndMarker; } @@ -255,12 +289,19 @@ public sealed class UInkFill public float Opacity = 1f; } - public sealed class UInkShape : IUInkContentBlock + public sealed class UInkShapeObject + { + public string Id, Preset, Ref; + public ulong Revision; + public uint PartCount, PartIndex; + public float[] Transform; + } + + public sealed class UInkShape : UInkContentBlock { - public uint ContentId; - public uint UndoId; public int ShapeType; public UInkShapeGeometry Geometry; + public UInkShapeObject Object; public UInkStroke Stroke; public UInkFill Fill; public bool RenderOnlyWhenLatest; @@ -270,15 +311,25 @@ public sealed class UInkShape : IUInkContentBlock // ============================================================ // Media(Type ID = 4) // ============================================================ - public sealed class UInkMedia : IUInkContentBlock + public sealed class UInkClear : UInkContentBlock + { + public Dictionary Extra; + } + + public sealed class UInkCrop + { + public float X, Y, Width, Height; + } + + public sealed class UInkMedia : UInkContentBlock { - public uint ContentId; - public uint UndoId; public string Path = ""; // .uink.extra 内安全相对路径(NFC / 分隔) public string MimeType = ""; public Dictionary Extra; // 视觉媒体(图片/SVG/视频/PDF 单页视口) + public int? Fit; + public UInkCrop Crop; public float? Width; public float? Height; public float[] Transform; // 仿射矩阵 [a,b,c,d,e,f],可选 @@ -294,6 +345,16 @@ public sealed class UInkMedia : IUInkContentBlock public float Volume = 1f; public double StartTime; public float PlaybackRate = 1f; + + // 未访问页导出时只更换块编号与资源路径,不修改打开会话的原始块。 + internal UInkMedia CopyForSave() => (UInkMedia)MemberwiseClone(); + + internal static bool IsVisualMime(string mime) => mime != null && + (mime.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || + mime.StartsWith("video/", StringComparison.OrdinalIgnoreCase) || + mime.Equals("application/pdf", StringComparison.OrdinalIgnoreCase)); + + internal static float[] IdentityMatrix() => new float[] { 1, 0, 0, 1, 0, 0 }; } // ============================================================ @@ -301,6 +362,11 @@ public sealed class UInkMedia : IUInkContentBlock // ============================================================ public sealed class UInkCanvasRecord { + public int StreamOrdinal { get; internal set; } + public int ContentStart { get; internal set; } + public int ContentEnd { get; internal set; } + internal UInkReadResult Source; + internal List<(int Offset, int Length, int Type, int Ordinal)> Frames; public UInkCanvas Canvas; public List Blocks = new List(); } diff --git a/Ink Canvas/UInk/UInkNumeric.cs b/Ink Canvas/UInk/UInkNumeric.cs new file mode 100644 index 000000000..01828053e --- /dev/null +++ b/Ink Canvas/UInk/UInkNumeric.cs @@ -0,0 +1,85 @@ +using System; +using MessagePack; + +namespace Ink_Canvas.UInk +{ + internal class UInkFieldException : Exception { } + internal sealed class UInkDuplicateKey : UInkFieldException { } + internal sealed class UInkBudgetException : Exception { } + + internal static class UInkNumeric + { + // TYPE-5/6:保留整数原型直到比较完成,不能先转 double(2^53+1 会丢位)。 + private static bool Signed(byte code) => code >= 0xe0 || (code >= 0xd0 && code <= 0xd3); + private const double U64End = 18446744073709551616d; + private const double I64End = 9223372036854775808d; + + internal static ulong Unsigned(ref MessagePackReader r, ulong max = ulong.MaxValue) + { + ulong value; + if (r.NextMessagePackType == MessagePackType.Integer) + { + if (Signed(r.NextCode)) + { + long i = r.ReadInt64(); + if (i < 0) throw new UInkFieldException(); + value = (ulong)i; + } + else value = r.ReadUInt64(); + } + else + { + double d = Floating(ref r); + if (d < 0 || d >= U64End || Math.Truncate(d) != d) throw new UInkFieldException(); + value = (ulong)d; + } + return value <= max ? value : throw new UInkFieldException(); + } + + internal static int Int32(ref MessagePackReader r) + { + if (r.NextMessagePackType == MessagePackType.Integer && !Signed(r.NextCode)) + return (int)Unsigned(ref r, int.MaxValue); + if (r.NextMessagePackType == MessagePackType.Integer) + { + long i = r.ReadInt64(); + return i >= int.MinValue && i <= int.MaxValue ? (int)i : throw new UInkFieldException(); + } + double d = Floating(ref r); + return d >= int.MinValue && d <= int.MaxValue && Math.Truncate(d) == d ? + (int)d : throw new UInkFieldException(); + } + + private static double Floating(ref MessagePackReader r) + { + if (r.NextMessagePackType != MessagePackType.Float) throw new UInkFieldException(); + double d = r.ReadDouble(); + return double.IsFinite(d) ? d : throw new UInkFieldException(); + } + + internal static double Double(ref MessagePackReader r) + { + if (r.NextMessagePackType != MessagePackType.Integer) return Floating(ref r); + if (Signed(r.NextCode)) + { + long i = r.ReadInt64(); + double d = i; + return d < I64End && (long)d == i ? d : throw new UInkFieldException(); + } + ulong u = r.ReadUInt64(); + double v = u; + return v < U64End && (ulong)v == u ? v : throw new UInkFieldException(); + } + + internal static float Single(ref MessagePackReader r) + { + if (r.NextCode == 0xca) + { + float f = r.ReadSingle(); + return float.IsFinite(f) ? f : throw new UInkFieldException(); + } + double d = Double(ref r); + return (double)(float)d == d ? (float)d : throw new UInkFieldException(); + } + } +} diff --git a/Ink Canvas/UInk/UInkPageProjection.cs b/Ink Canvas/UInk/UInkPageProjection.cs new file mode 100644 index 000000000..6236cda87 --- /dev/null +++ b/Ink Canvas/UInk/UInkPageProjection.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Ink; +using Ink_Canvas.Helpers; + +namespace Ink_Canvas.UInk +{ + internal delegate Stroke UInkBlockConverter(IUInkContentBlock block, UInkCoordinateMap map, + Action note, out StrokeCollection parts); + internal delegate Stroke UInkPageConverter(IUInkContentBlock block, out StrokeCollection parts); + + public sealed class UInkPageProjection + { + public UInkWorkspace Workspace { get; private set; } + public readonly List Pages = new(); + public readonly List RetainedPages = new(); + public readonly List<(string Guid, int WorkspaceType, int PageCount)> UndisplayedWorkspaces = new(); + public int CurrentPageDisplayIndex { get; private set; } + public UInkReadResult ReadResult { get; private set; } + public bool RequiresSaveAs => ReadResult.RequiresSaveAs; + + private sealed class WorkspacePages + { + internal readonly UInkWorkspace Workspace; + internal readonly Dictionary> Pages = new(); + internal readonly int FirstReference; + internal WorkspacePages(UInkWorkspace workspace, int firstReference) + { + Workspace = workspace; + FirstReference = firstReference; + } + } + + internal static UInkPageProjection Build(UInkReadResult read, double dpiX, double dpiY, + Func resolveSlide, UInkBlockConverter convert, + Action decode = null, int whiteboardLimit = int.MaxValue, bool preserveUnbound = false) + { + decode ??= UInkReader.MaterializeContent; + var projection = new UInkPageProjection { ReadResult = read }; + var ext = read.Document.HeaderExtension; + var workspaces = new List(); + var byId = new Dictionary(); + void Register(string key, UInkWorkspace workspace, int firstReference = -1) + { + var entry = new WorkspacePages(workspace, firstReference); + byId.Add(key, entry); + workspaces.Add(entry); + } + if (ext?.Workspaces != null) + foreach (var ws in ext.Workspaces) Register(ws.Guid, ws); + if (ext?.WorkspacesDeclared != true) Register("", new UInkWorkspace()); + + var devices = new Dictionary(); + if (ext?.Devices != null) + foreach (var device in ext.Devices) devices.Add(device.Guid, devices.Count); + if (ext?.DevicesDeclared != true) devices.Add("", 0); + int registeredDeviceCount = devices.Count; + + foreach (var rec in read.Document.Canvases) + { + var c = rec.Canvas; + // FILE-23/24:临时项用替代前的首次引用排序;缺失引用沿用该 Canvas 的身份。 + string Key(string id, bool declared) => !declared ? "" : id.Length > 0 ? id : "#" + rec.StreamOrdinal; + var wsKey = Key(c.WorkspaceGuid, ext?.WorkspacesDeclared == true); + if (!byId.TryGetValue(wsKey, out var entry)) + { + Register(wsKey, new UInkWorkspace { Guid = c.WorkspaceGuid, WorkspaceType = (int)UInkWorkspaceType.Whiteboard }, + read.FirstWorkspaceReference.GetValueOrDefault(wsKey, rec.StreamOrdinal)); + entry = byId[wsKey]; + read.Note("FILE-23"); + } + var deviceKey = Key(c.DeviceGuid, ext?.DevicesDeclared == true); + if (!devices.TryGetValue(deviceKey, out int rank)) + { + rank = registeredDeviceCount + read.FirstDeviceReference.GetValueOrDefault(deviceKey, rec.StreamOrdinal); + devices.Add(deviceKey, rank); + read.Note("FILE-23"); + } + if (!entry.Pages.TryGetValue(c.PageGuid, out var layers)) + entry.Pages.Add(c.PageGuid, layers = new()); + layers.Add((rank, rec)); + } + + // 注册项同为 -1,稳定排序保留其注册顺序。 + workspaces = workspaces.OrderBy(w => w.FirstReference).ToList(); + // ICC 选择注册顺序中首个有页面的根 Workspace;其余仅保留索引,不解码内容。 + var selected = workspaces.Find(w => w.Pages.Count != 0 && string.IsNullOrEmpty(w.Workspace.ParentWorkspaceGuid)); + foreach (var entry in workspaces) + if (entry != selected) + { + projection.UndisplayedWorkspaces.Add((entry.Workspace.Guid, entry.Workspace.WorkspaceType, entry.Pages.Count)); + read.Note("undisplayedWorkspace"); + } + if (selected == null) return projection; + projection.Workspace = selected.Workspace; + if (dpiX != dpiY) read.Note("nonUniformDpi"); + foreach (var candidates in selected.Pages.Values) + { + // FILE-9 / CANVAS-8:先按页选设备,再叠加该设备的图层。布局只从第 0 层取得。 + int device = candidates.Min(x => x.Device); + var layers = candidates.Where(x => x.Device == device).Select(x => x.Record) + .OrderBy(r => r.Canvas.LayerIndex).ToArray(); + if (layers.Length < candidates.Count) read.Note("undisplayedDevice"); + var c = layers[0].Canvas; + var page = new UInkPageData { Canvas = c, ReadResult = read, LastPosition = layers.Max(r => r.StreamOrdinal) }; + page.HasIndexedContent = layers.Any(r => r.Blocks.Count > 0 || r.ContentEnd > r.ContentStart); + var map = new UInkCoordinateMap(dpiX, dpiY, c.LayerIndex == 0 ? c.Viewport : null); + bool ppt = projection.Workspace.WorkspaceType == (int)UInkWorkspaceType.Presentation; + if (ppt && page.PageKind == 0) + { + if (page.Binding == 1) + { + if (c.PageIndex < int.MaxValue) page.SlideIndex = (int)c.PageIndex + 1; + } + else if (page.SlideId.HasValue) + page.SlideIndex = resolveSlide?.Invoke(page.SlideId.Value); + page.IsUnbound = !(page.SlideIndex > 0); + if (page.IsUnbound) read.Note("CANVAS-14", !preserveUnbound); + } + page.Materialize = target => + { + // 每文档共享 P1 的预算和诊断。只在成功后发布整页,调用者可安全重试。 + lock (read) + { + var data = new UInkPageData(); + var final = new UInkStrokeCollection(); + var history = new List(); + Action note = rule => read.Note(rule); + Stroke ToStroke(IUInkContentBlock block, out StrokeCollection parts) + { + if (block is UInkContentBlock { StreamOffset: int offset }) read.Offset = offset; + return convert(block, map, note, out parts); + } + foreach (var record in layers) + { + decode(record); + UInkUndoAdapter.AppendCanvas(record, data, final, history, ToStroke, note); + } + bool sawInk = false; + foreach (var item in data.Items) + { + if (item.Stroke != null) sawInk = true; + else if (sawInk && item.Block is UInkMedia) + { + target.HasLayerOrderFallback = true; + note("FILE-14"); + break; + } + } + target.FinalStrokes = final; + target.History = history.ToArray(); + target.Items = data.Items; + target.Shapes = data.Shapes; + target.Media = data.Media; + } + }; + if (ppt) page.ReplayPptPage = page.Materialize; + (c.PageState == 1 ? projection.RetainedPages : projection.Pages).Add(page); + } + + foreach (var list in new[] { projection.Pages, projection.RetainedPages }) + { + list.Sort((a, b) => + { + int order = a.Canvas.PageIndex.CompareTo(b.Canvas.PageIndex); + return order != 0 ? order : a.LastPosition.CompareTo(b.LastPosition); + }); + for (int i = 0; i < list.Count; i++) list[i].DisplayIndex = i; + } + uint? current = projection.Workspace.CurrentPageIndex; + if (current.HasValue && current.Value < projection.Pages.Count) + projection.CurrentPageDisplayIndex = (int)current.Value; + else read.Note("HEXT-10", false); + if (projection.Workspace.WorkspaceType == (int)UInkWorkspaceType.Whiteboard && + projection.CurrentPageDisplayIndex >= whiteboardLimit) projection.CurrentPageDisplayIndex = 0; + if (projection.Pages.Count > 0) projection.Pages[projection.CurrentPageDisplayIndex].EnsureMaterialized(); + return projection; + } + } +} diff --git a/Ink Canvas/UInk/UInkPlayback.cs b/Ink Canvas/UInk/UInkPlayback.cs new file mode 100644 index 000000000..7b79f843d --- /dev/null +++ b/Ink Canvas/UInk/UInkPlayback.cs @@ -0,0 +1,87 @@ +using System; +using System.Windows; +using System.Windows.Controls; +using Ink_Canvas.Controls; + +namespace Ink_Canvas.UInk +{ + internal static class UInkPlayback + { + internal static void Configure(CanvasMediaControl control, string path, UInkMedia media, + Action ready, Action failed) + { + var player = control.MediaPlayer; + var source = new Uri(path, UriKind.Absolute); + bool unavailable = false; + // MEDIA-10/11:等媒体打开后才读时长、定位及应用自动播放。 + player.MediaOpened += (_, _) => + { + if (!control.IsLoaded || unavailable || player.Source == null) return; + try + { + double speed = media.PlaybackRate > 0 && float.IsFinite(media.PlaybackRate) ? media.PlaybackRate : 1; + // 控件的下拉列表只收录常用倍率,清除预设选择后可使用其自定义倍率值。 + if (control.FindName("SpeedComboBox") is ComboBox speeds) speeds.SelectedIndex = -1; + control.SetPlaybackRate(speed); + try { player.SpeedRatio = speed; } + catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or NotSupportedException) { } + control.SetVolumeLevel(Math.Clamp(media.Volume, 0, 1)); + var position = StartPosition(media.StartTime, player.NaturalDuration); + control.SetPlaybackPosition(position); + ready(); + if (media.Autoplay && (!player.NaturalDuration.HasTimeSpan || position < player.NaturalDuration.TimeSpan)) + Play(control); + } + catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or NotSupportedException) + { + // 平台可能拒绝起播,文档和控件仍可用。 + } + }; + if (media.Loop) + { + player.MediaEnded += (_, _) => + { + if (control.IsLoaded && !unavailable && player.Source != null) + { + control.SetPlaybackPosition(TimeSpan.Zero); + Play(control); + } + }; + } + player.MediaFailed += (_, args) => + { + if (unavailable || player.Source == null) return; + unavailable = true; + failed(args.ErrorException); + }; + + control.Loaded += (_, _) => + { + if (unavailable) return; + // 白板翻页会关闭播放器。重新挂回同一历史元素时打开同一份缓存资源。 + if (player.Source == null) player.Source = source; + control.PausePlayback(); + }; + control.Unloaded += (_, _) => + { + control.PausePlayback(); + player.Source = null; + }; + } + + internal static TimeSpan StartPosition(double seconds, Duration duration) + { + if (!double.IsFinite(seconds) || seconds <= 0) return TimeSpan.Zero; + if (duration.HasTimeSpan && seconds >= duration.TimeSpan.TotalSeconds) return duration.TimeSpan; + if (seconds >= TimeSpan.MaxValue.TotalSeconds) return TimeSpan.MaxValue; + return TimeSpan.FromSeconds(seconds); + } + + private static void Play(CanvasMediaControl control) + { + // 经控件自己的播放入口同步按钮和进度状态。 + if (control.FindName("PlayPauseButton") is Button button) + button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); + } + } +} diff --git a/Ink Canvas/UInk/UInkReadResult.cs b/Ink Canvas/UInk/UInkReadResult.cs new file mode 100644 index 000000000..3b151caa2 --- /dev/null +++ b/Ink Canvas/UInk/UInkReadResult.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; + +namespace Ink_Canvas.UInk +{ + public enum UInkReadStatus { Ok, Rejected, Recovered } + public sealed class UInkReadOptions + { + public bool MaterializeContent { get; set; } = true; + } + + public sealed class UInkReadResult + { + public UInkReadStatus Status { get; internal set; } + public UInkDocument Document { get; internal set; } + public ushort? Version { get; internal set; } + public bool TruncatedTail { get; internal set; } + public bool StoppedOnCorruption { get; internal set; } + public bool LimitExceeded { get; internal set; } + public long? FailureOffset { get; internal set; } + public int SkippedBlocks { get; internal set; } + public int UnknownBlocks { get; internal set; } + private bool lossy; + public bool RequiresSaveAs => lossy || Pending > 0; + public Dictionary DiagnosticCounts { get; } = new(); + public List Diagnostics { get; } = new(); + + internal readonly Dictionary FirstWorkspaceReference = new(); + internal readonly Dictionary FirstDeviceReference = new(); + internal ReadOnlyMemory Bytes; + internal int Offset, Points, Pending; + + // 键仅取自解码器固定的规则编号;样本文本有界,不保存输入文件的任意字符串。 + internal void Note(string rule, bool loss = true) + { + DiagnosticCounts.TryGetValue(rule, out int count); + DiagnosticCounts[rule] = count + 1; + if (Diagnostics.Count < 64) Diagnostics.Add($"{rule} @ {Offset}"); + if (loss) lossy = true; + } + + internal void Skip(string rule) + { + SkippedBlocks++; + FailureOffset ??= Offset; + Note(rule); + } + + internal void StopAtLimit(string rule) + { + FailureOffset = Offset; + LimitExceeded = true; + Status = UInkReadStatus.Recovered; + Note(rule); + } + + internal void ReservePoints(int count) + { + if (count > UInkBlockScanner.MaxContainer || count > UInkBlockScanner.MaxPoints - Points) + throw new UInkBudgetException(); + Points += count; + } + } +} diff --git a/Ink Canvas/UInk/UInkReader.cs b/Ink Canvas/UInk/UInkReader.cs index ada97c448..a6edb86b8 100644 --- a/Ink Canvas/UInk/UInkReader.cs +++ b/Ink Canvas/UInk/UInkReader.cs @@ -1,217 +1,254 @@ -using Ink_Canvas.Helpers; using System; -using System.Buffers; +using System.Collections.Generic; using System.IO; -using System.Threading; +using System.Linq; using MessagePack; namespace Ink_Canvas.UInk { - /// - /// UInk 主文件读取器。读取连续 MessagePack 对象流,重建 。 - /// 容错规则(对应规范 uink_conf / uink_inc): - /// - 首块必须是 array(7) Header(type=0, version=10),否则视为非 UInk 文件(返回 null); - /// - 未知 Type ID 跳过(作为完整对象已消费); - /// - EOF 处不完整尾块丢弃(保留此前完整对象); - /// - 解码失败停止读取,不重新同步。 - /// public static class UInkReader { - public static UInkDocument Load(string path) + public const int MaxFileBytes = UInkBlockScanner.MaxFile; + internal const int MaxTopLevelObjects = 250_000, MaxCanvasRecords = 16_384, MaxContentFrames = 200_000; + + public static UInkDocument Load(string path) => Read(path).Document; + + public static UInkReadResult Read(string path, UInkReadOptions options = null) { - using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); - return Load(fs); + try + { + using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + return Read(file, options); + } + catch (IOException) { return Reject("IO"); } + catch (UnauthorizedAccessException) { return Reject("IO"); } } - public static UInkDocument Load(Stream stream) + internal static UInkReadResult Read(Stream file, UInkReadOptions options) { - var doc = new UInkDocument(); - bool headerSeen = false; - UInkCanvasRecord current = null; - - using (var sr = new MessagePackStreamReader(stream)) + if (file.Length > UInkBlockScanner.MaxFile) return Reject("file-limit", true); + var bytes = new byte[(int)file.Length]; + int offset = 0; + while (offset < bytes.Length) { - while (true) - { - ReadOnlySequence blockBytes; - try - { - var read = sr.ReadAsync(CancellationToken.None).GetAwaiter().GetResult(); - if (read == null) - { - // EOF。RemainingBytes 非空 = 截断尾块,丢弃。 - break; - } - blockBytes = read.Value; - } - catch (Exception) - { - // 流读取异常视为损坏:停止读取,保留此前完整对象。 - break; - } + int n = file.Read(bytes, offset, bytes.Length - offset); + if (n == 0) return Reject("IO"); + offset += n; + } + return Read(bytes, options); + } - if (!headerSeen) - { - // 首块校验:array(7) Header - UInkHeader header; - try - { - var first = new MessagePackReader(blockBytes); - if (!IsArrayHeader(ref first, out int len) || len != 7) - return null; - // 第一元素必须为整数 0(type) - if (!UInkFmt.IsInteger(ref first)) return null; - if (first.ReadInt32() != (int)UInkBlockType.Header) return null; - var hr = new MessagePackReader(blockBytes); - header = UInkHeaderFormatter.Instance.Deserialize(ref hr, UInkSerializer.Options); - if (header.Version != 10 || header.Type != 0) return null; - } - catch (Exception) - { - return null; - } - doc.Header = header; - headerSeen = true; - continue; - } + private static UInkReadResult Reject(string rule, bool limit = false) + { + var r = new UInkReadResult { Status = UInkReadStatus.Rejected, LimitExceeded = limit, FailureOffset = 0 }; + r.Note(rule); + return r; + } - // 后续块:按 Type ID 分发 - UInkBlockType type; - try - { - type = PeekType(blockBytes); - } - catch (Exception) + public static UInkReadResult Read(ReadOnlyMemory bytes, UInkReadOptions options = null) + { + if (bytes.Length > UInkBlockScanner.MaxFile) return Reject("file-limit", true); + var result = new UInkReadResult { Bytes = bytes }; + var codec = new UInkDecoder(result); + var reader = new MessagePackReader(bytes); + var winners = new Dictionary<(string, string, string, uint), UInkCanvasRecord>(); + UInkCanvasRecord current = null; + int ordinal = 0, canvasCount = 0, contentFrames = 0; + while (!reader.End) + { + int offset = (int)reader.Consumed; + result.Offset = offset; + // D1.9:即使对象很小或没有有效内容,也限制全文件的工作量。 + if (ordinal == MaxTopLevelObjects) + { + result.StopAtLimit("object-count-limit"); + break; + } + var frame = UInkBlockScanner.Scan(bytes.Span.Slice(offset), out int length); + if (frame != UInkFrame.Complete) + { + result.TruncatedTail = frame == UInkFrame.Truncated; + result.StoppedOnCorruption = frame == UInkFrame.Malformed; + result.LimitExceeded = frame == UInkFrame.LimitExceeded; + result.FailureOffset = offset; + result.Status = UInkReadStatus.Recovered; + result.Note(result.TruncatedTail ? "FILE-16" : result.LimitExceeded ? "frame-limit" : "FILE-17"); + break; + } + var raw = new UInkValue(reader.ReadRaw(length).First); + try + { + if (ordinal == 0) { - break; // 无法判定类型 → 停止读取 + var header = codec.Header(raw); + result.Document = new UInkDocument { Header = header }; + if (header.Version != 11) result.Note(header.Version == 10 ? "VER-5" : "VER-4", header.Version > 11); } - - try + else { + int type; + try { type = UInkDecoder.Type(raw); } + catch (UInkFieldException) when (current != null) { type = -1; } switch (type) { - case UInkBlockType.Header: - // 重复 Header → 结构非法,停止读取 - return null; - case UInkBlockType.HeaderExtension: - if (doc.HeaderExtension != null) return null; // 最多 1 个 - { - var er = new MessagePackReader(blockBytes); - doc.HeaderExtension = UInkHeaderExtensionFormatter.Instance.Deserialize(ref er, UInkSerializer.Options); - } - current = null; - break; - case UInkBlockType.Canvas: - { - var cr = new MessagePackReader(blockBytes); - var canvas = UInkCanvasFormatter.Instance.Deserialize(ref cr, UInkSerializer.Options); - current = new UInkCanvasRecord { Canvas = canvas }; - doc.Canvases.Add(current); - } - break; - case UInkBlockType.Ink: - { - if (current == null) return null; // 首个 Canvas 前不得出现内容块 - var ir = new MessagePackReader(blockBytes); - current.Blocks.Add(UInkInkFormatter.Instance.Deserialize(ref ir, UInkSerializer.Options)); - } + + case 0: result.Skip("FILE-1"); break; + case 1: + if (ordinal == 1) result.Document.HeaderExtension = codec.Extension(raw); + else result.Skip("HEXT-1"); break; - case UInkBlockType.Shape: + case 2: + if (canvasCount == MaxCanvasRecords) { - if (current == null) return null; - var sr2 = new MessagePackReader(blockBytes); - current.Blocks.Add(UInkShapeFormatter.Instance.Deserialize(ref sr2, UInkSerializer.Options)); + result.StopAtLimit("canvas-count-limit"); + break; } + canvasCount++; + // FILE-3:即使新 Canvas 无效,也要先关闭前一个作用域。 + if (current != null) current.ContentEnd = offset; + current = null; + var canvas = codec.Canvas(raw); + current = new UInkCanvasRecord { Canvas = canvas, StreamOrdinal = ordinal, + ContentStart = offset + length, Source = result }; + // FILE-8/23:即使 Canvas 随后被替代,也保留原流中的首次 GUID 引用。 + if (canvas.WorkspaceGuid.Length > 0) + result.FirstWorkspaceReference.TryAdd(canvas.WorkspaceGuid, ordinal); + if (canvas.DeviceGuid.Length > 0) + result.FirstDeviceReference.TryAdd(canvas.DeviceGuid, ordinal); + var ext = result.Document.HeaderExtension; + var key = (RegistryKey(canvas.WorkspaceGuid, ext?.WorkspacesDeclared == true, ordinal, result), + RegistryKey(canvas.DeviceGuid, ext?.DevicesDeclared == true, ordinal, result), canvas.PageGuid, canvas.LayerIndex); + if (winners.ContainsKey(key)) result.Note("FILE-8", false); + winners[key] = current; break; - case UInkBlockType.Media: + case -1: + result.Skip("FILE-19"); + // 已分帧但类型损坏的 Map 也保留原位置,避免合并两侧的撤回组。 + if (current == null || raw.Reader().NextMessagePackType != MessagePackType.Map) break; + goto case 3; + case 3: case 4: case 5: case 6: + if (current == null) result.Skip("FILE-4"); + else if (contentFrames == MaxContentFrames) result.StopAtLimit("content-index-limit"); + else { - if (current == null) return null; - var mr = new MessagePackReader(blockBytes); - current.Blocks.Add(UInkMediaFormatter.Instance.Deserialize(ref mr, UInkSerializer.Options)); + contentFrames++; + (current.Frames ??= new()).Add((offset, length, type, ordinal)); } break; - default: - // 未知 Type ID:作为完整对象已消费,跳过继续。 - break; + default: result.UnknownBlocks++; result.Skip("TYPE-9"); break; } } - catch (Exception) - { - // 块解码失败 → 停止读取,保留此前完整对象。 - break; - } } + catch (UInkBudgetException) + { + result.StopAtLimit("registry-limit"); + break; + } + catch (UInkFieldException ex) + { + if (ordinal == 0) break; + result.Skip(ex is UInkDuplicateKey ? "TYPE-7" : "FILE-19"); + } + if (result.Status == UInkReadStatus.Recovered) break; + if (current != null) current.ContentEnd = offset + length; + ordinal++; } - if (!headerSeen) + if (result.Document == null) { - LogHelper.WriteLogToFile("[UInk] 读取中止:未找到合法 Header 块,按非 UInk 文件处理", LogHelper.LogType.Warning); - return null; + result.Status = UInkReadStatus.Rejected; + result.FailureOffset = 0; + result.Note("HDR-2"); + result.Bytes = default; + return result; } - - int blockCount = 0; - foreach (var rec in doc.Canvases) - blockCount += rec.Blocks.Count; - LogHelper.WriteLogToFile( - $"[UInk] 读取完成: 画布 {doc.Canvases.Count} 个, 内容块 {blockCount} 个, 资源扩展={(doc.HeaderExtension != null)}", - LogHelper.LogType.Info); - return doc; + result.Document.Canvases = winners.Values.OrderBy(c => c.StreamOrdinal).ToList(); + result.Pending = winners.Count; + if (options?.MaterializeContent != false) + foreach (var rec in result.Document.Canvases) MaterializeContent(rec); + if (result.Pending == 0) result.Bytes = default; + return result; } - /// 读取块类型:Header 是 array,其余是带 "type" 键的 Map。 - private static UInkBlockType PeekType(ReadOnlySequence bytes) + private static string RegistryKey(string id, bool explicitRegistry, int ordinal, UInkReadResult result) { - var r = new MessagePackReader(bytes); - if (IsArrayHeader(ref r, out _)) - return UInkBlockType.Header; - - if (!IsMapHeader(ref r, out int count)) - throw new MessagePackSerializationException("UInk 块既不是 array 也不是 map"); - - for (int i = 0; i < count; i++) + if (!explicitRegistry) { - var key = r.ReadString(); - if (key == "type") - { - return (UInkBlockType)UInkFmt.ReadInt32Tolerant(ref r); - } - r.Skip(); + if (id.Length > 0) result.Note("HEXT-4"); + return ""; } - throw new MessagePackSerializationException("UInk Map 块缺少 type 键"); + if (id.Length > 0) return id; + // CANVAS-24:缺失引用没有可复用的身份;索引专用临时键避免误替代,DTO 保留原始缺失状态。 + result.Note("CANVAS-24"); + return "#" + ordinal; } - private static bool IsArrayHeader(ref MessagePackReader r, out int count) + public static void MaterializeContent(UInkCanvasRecord record) { - var code = r.NextCode; - if (code == MessagePackCode.Array16 || code == MessagePackCode.Array32) + var result = record.Source; + if (result == null) return; + // 同一文档的预算与诊断共享,允许多次请求同一页而不重复追加。 + lock (result) { - count = r.ReadArrayHeader(); - return true; - } - if (code >= 0x90 && code <= 0x9F) - { - count = r.ReadArrayHeader(); - return true; + if (record.Source == null) return; + var codec = new UInkDecoder(result); + // INK-3:按物理帧递增组序号。坏块的可读 undoId 仍参与分组;读不到时断开连续组。 + var frames = record.Frames; + uint? previousUndo = null; + int groupOrdinal = -1; + for (int index = 0; index < (frames?.Count ?? 0); index++) + { + var (offsetInFile, length, type, ordinal) = frames[index]; + result.Offset = offsetInFile; + var raw = new UInkValue(result.Bytes.Slice(offsetInFile, length)); + UInkContentBlock block = null; + try + { + if (type != -1) block = codec.Content(type, raw); + } + catch (UInkFieldException ex) + { + result.Skip(ex is UInkDuplicateKey ? "TYPE-7" : type == 6 ? "CLEAR-12" : "FILE-19"); + } + catch (UInkBudgetException) + { + result.LimitExceeded = true; + result.Status = UInkReadStatus.Recovered; + result.Skip("point-limit"); + break; + } + + uint? before = previousUndo; + uint? undo = block?.UndoId ?? UInkDecoder.ReadUndoId(raw); + if (!undo.HasValue || undo != before) groupOrdinal++; + previousUndo = undo; + if (block == null) continue; + if (block is UInkClear) + { + // CLEAR-4/12:即使相邻块体无效,仍使用其可读的物理撤回编号。 + uint? after = AdjacentUndoId(result.Bytes, frames, index + 1); + if ((index == 0 && block.UndoId != 0) || before >= block.UndoId || after <= block.UndoId) + { + result.Skip("CLEAR-12"); + continue; + } + } + block.PhysicalFrameOrdinal = ordinal; + block.PhysicalUndoGroupOrdinal = groupOrdinal; + block.StreamOffset = offsetInFile; + record.Blocks.Add(block); + } + record.Frames = null; + record.Source = null; + if (--result.Pending == 0) result.Bytes = default; } - count = 0; - return false; } - private static bool IsMapHeader(ref MessagePackReader r, out int count) + private static uint? AdjacentUndoId(ReadOnlyMemory bytes, List<(int Offset, int Length, int Type, int Ordinal)> frames, int index) { - var code = r.NextCode; - if (code == MessagePackCode.Map16 || code == MessagePackCode.Map32) - { - count = r.ReadMapHeader(); - return true; - } - if (code >= 0x80 && code <= 0x8F) - { - count = r.ReadMapHeader(); - return true; - } - count = 0; - return false; + if (index < 0 || index >= frames.Count) return null; + var (offset, length, _, _) = frames[index]; + return UInkDecoder.ReadUndoId(new UInkValue(bytes.Slice(offset, length))); } } } diff --git a/Ink Canvas/UInk/UInkSaveQueue.cs b/Ink Canvas/UInk/UInkSaveQueue.cs new file mode 100644 index 000000000..a0ce77bc4 --- /dev/null +++ b/Ink Canvas/UInk/UInkSaveQueue.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; + +namespace Ink_Canvas.UInk +{ + internal sealed class UInkSaveQueue + { + private sealed class Job + { + internal object Key; + internal bool Timed; + internal Action Write; + internal Action Release; + internal readonly TaskCompletionSource Completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + private readonly LinkedList jobs = new(); + private readonly Dictionary> pending = new(); + private Task worker; + + internal Task Enqueue(object document, string target, bool timed, Action write, Action release) + { + var job = new Job { Key = document, Timed = timed, + Write = write, Release = release }; + lock (jobs) + { + // 只合并同一文档尚未开始的定时任务;新快照按实际接收顺序入队。 + if (timed && pending.Remove(job.Key, out var superseded)) + { + jobs.Remove(superseded); + superseded.Value.Release?.Invoke(); + superseded.Value.Completion.SetResult(false); + } + var node = jobs.AddLast(job); + Debug.WriteLine($"UInk 保存队列长度 {jobs.Count}"); + if (timed) pending.Add(job.Key, node); + worker ??= Task.Run(Run); + } + return job.Completion.Task; + } + + internal Task DrainAsync() + { + lock (jobs) return worker ?? Task.CompletedTask; + } + + private void Run() + { + while (true) + { + Job job; + lock (jobs) + { + if (jobs.First == null) + { + worker = null; + return; + } + job = jobs.First.Value; + jobs.RemoveFirst(); + if (job.Timed) pending.Remove(job.Key); + } + try + { + var elapsed = Stopwatch.StartNew(); + try { job.Write(); } + finally + { + Debug.WriteLine($"UInk 后台保存 {elapsed.ElapsedMilliseconds} ms"); + job.Release?.Invoke(); + } + job.Completion.SetResult(true); + } + catch (Exception ex) { job.Completion.SetException(ex); } + } + } + } +} diff --git a/Ink Canvas/UInk/UInkSaveService.cs b/Ink Canvas/UInk/UInkSaveService.cs index 4857026a0..0c4c34a35 100644 --- a/Ink Canvas/UInk/UInkSaveService.cs +++ b/Ink Canvas/UInk/UInkSaveService.cs @@ -2,156 +2,370 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using Microsoft.Win32.SafeHandles; namespace Ink_Canvas.UInk { - /// - /// UInk 完整保存编排(两阶段原子提交)。提交顺序对应规范 uink_inc / uink_conf: - /// 1. 确定完整对象流 + 新主文件引用的资源集合; - /// 2. 生成并校验临时 `.uink.extra`(**必须包含旧主文件仍引用的资源与新主文件将引用资源的并集**); - /// 3. 生成并校验临时 `.uink` 主文件(暂不替换); - /// 4. 先用临时资源包替换目标资源包,然后原子替换 `.uink` 主文件(主文件最后提交); - /// 5. 主文件提交成功后才清理多余 ZIP 条目或整个无用资源包。 - /// 任一步失败:删除临时文件,旧文件保持原样。 - /// public static class UInkSaveService { - /// - /// 完整保存:把 doc 写入 mainPath,资源打包进 mainPath + ".extra"。 - /// resources 为「新主文件引用的资源」(入口路径 NFC 规范化在 WriteArchive 内完成)。 - /// + internal static void SaveFull(UInkDocument doc, string mainPath, + IReadOnlyList<(string entryPath, string sourceFile)> resources, Action fault) + { + TrySaveFull(doc, Path.GetFullPath(mainPath), resources, false, fault); + } + public static void SaveFull(UInkDocument doc, string mainPath, IReadOnlyList<(string entryPath, string sourceFile)> resources) { - string extraPath = mainPath + ".extra"; - string tmpMain = mainPath + ".tmp"; - string tmpExtra = mainPath + ".extra.tmp"; - string workDir = null; + TrySaveFull(doc, Path.GetFullPath(mainPath), resources, false); + } - try + internal static string NormalizeTarget(string path) + { + path = Path.GetFullPath(path); + return Path.Combine(ResolveDirectory(Path.GetDirectoryName(path)), Path.GetFileName(path)); + } + + internal static string SaveSnapshot(UInkDocument doc, string path, + IReadOnlyList<(string entryPath, string sourceFile)> resources, string sourcePath, Action committed = null) + { + path = Path.GetFullPath(path); + if (!string.Equals(sourcePath, NormalizeTarget(path), StringComparison.OrdinalIgnoreCase)) { - // 1. 资源并集(旧主文件仍引用的 + 新的),崩溃恢复安全。 - // 旧资源解压到 workDir,该目录必须活到 WriteArchive 之后。 - workDir = Path.Combine(Path.GetTempPath(), "UInkUnion_" + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(workDir); - var union = BuildUnionResources(mainPath, extraPath, resources, workDir); - - // 2. 临时 .uink.extra - if (File.Exists(tmpExtra)) File.Delete(tmpExtra); - if (union.Count > 0) - UInkExtraArchive.WriteArchive(tmpExtra, union); + TrySaveFull(doc, path, resources, false, committed: committed); + return path; + } - // 3. 临时 .uink - if (File.Exists(tmpMain)) File.Delete(tmpMain); - UInkWriter.WriteDocument(doc, tmpMain); + // TYPE-12 / COMPAT-3:外部打开的源文件一律保留,包括延迟解码后才发现降级的页。 + string stem = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path)); + for (int i = 1; ; i++) + { + string candidate = stem + " (" + i + ")" + Path.GetExtension(path); + if (TrySaveFull(doc, candidate, resources, true, committed: committed)) return candidate; + } + } + + private static bool TrySaveFull(UInkDocument doc, string mainPath, + IReadOnlyList<(string entryPath, string sourceFile)> resources, bool newFileOnly, Action fault = null, + Action committed = null) + { + Directory.CreateDirectory(Path.GetDirectoryName(mainPath)); + return WithTargetLock(mainPath, () => + { + if (newFileOnly && (File.Exists(mainPath) || Directory.Exists(mainPath) || + File.Exists(mainPath + ".extra") || Directory.Exists(mainPath + ".extra"))) return false; + Commit(doc, mainPath, resources, fault); + committed?.Invoke(mainPath); + return true; + }); + } + + // EXTRA-16:同一路径及目录别名共享跨进程事务边界。 + internal static T WithTargetLock(string mainPath, Func action) + { + string target = NormalizeTarget(mainPath); + string key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(target.ToUpperInvariant()))); + using var gate = new Mutex(false, "ICC-UInk-" + key); + try { gate.WaitOne(); } + catch (AbandonedMutexException) { /* 前一进程退出,重新读取磁盘上的主文件。 */ } + try { return action(); } + finally { gate.ReleaseMutex(); } + } - // 4. 先替换资源包,再原子替换主文件(主文件最后提交) - if (File.Exists(tmpExtra)) - AtomicReplace(tmpExtra, extraPath); - AtomicReplace(tmpMain, mainPath); + internal static (FileStream Main, FileStream Extra, Exception ExtraError) OpenReadPair(string path) + { + // EXTRA-1/16:两次打开同属一个事务,解码在释放锁后通过原句柄进行。 + return WithTargetLock<(FileStream, FileStream, Exception)>(path, () => + { + const FileShare sharing = FileShare.Read | FileShare.Delete; + var main = new FileStream(path, FileMode.Open, FileAccess.Read, sharing); + try { return (main, new FileStream(path + ".extra", FileMode.Open, FileAccess.Read, sharing), null); } + catch (FileNotFoundException) { return (main, null, null); } + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) + { + return (main, null, ex); + } + catch { main.Dispose(); throw; } + }); + } + + private static string ResolveDirectory(string directory) + { + const uint openExisting = 3, backupSemantics = 0x02000000; + using var handle = CreateFileW(directory, 0, FileShare.ReadWrite | FileShare.Delete, + IntPtr.Zero, openExisting, backupSemantics, IntPtr.Zero); + if (handle.IsInvalid) return directory; + var buffer = new StringBuilder(260); + uint length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Capacity, 0); + if (length >= buffer.Capacity) + { + buffer.EnsureCapacity((int)length); + length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Capacity, 0); + } + return length > 0 && length < buffer.Capacity ? buffer.ToString() : directory; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern SafeFileHandle CreateFileW(string path, uint access, FileShare share, + IntPtr security, uint creation, uint flags, IntPtr template); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] + private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder path, + uint capacity, uint flags); + + private static void Commit(UInkDocument doc, string mainPath, + IReadOnlyList<(string entryPath, string sourceFile)> resources, Action fault) + { + string prefix = mainPath + "." + Guid.NewGuid().ToString("N"); + string work = prefix + ".work", tempMain = prefix + ".tmp", tempExtra = prefix + ".extra.tmp"; + string extra = mainPath + ".extra", extraBackup = prefix + ".extra.bak", mainBackup = prefix + ".main.bak"; + bool keepRecoveryFiles = false, hadExtra = File.Exists(extra), hadMain = File.Exists(mainPath); + Directory.CreateDirectory(work); + try + { + var union = new Dictionary(StringComparer.Ordinal); + foreach (var rec in doc.Canvases) UInkReader.MaterializeContent(rec); + var needed = Paths(doc); + var oldPaths = new HashSet(StringComparer.Ordinal); + if (hadMain) + { + var old = UInkReader.Read(mainPath); + if (old.Status == UInkReadStatus.Ok && old.SkippedBlocks == 0 && old.Version <= 11) + oldPaths = Paths(old.Document); + else if (hadExtra) + throw new InvalidDataException("旧主文件的资源引用无法完整确认"); + } + if (resources != null) + { + foreach (var (name, source) in resources) + { + string path = Safe(name); + if (!needed.Contains(path) && !oldPaths.Contains(path)) continue; + if (union.TryGetValue(path, out var existing)) + { + if (!EqualBytes(existing, source)) throw Collision(); + } + else union.Add(path, source); + } + } + if (hadExtra) + { + using var previous = new UInkExtraArchive(extra); + // EXTRA-13/17:可复用包内现有资源;旧主引用的同名条目必须逐字节相同。 + var extract = new HashSet(oldPaths, StringComparer.Ordinal); + foreach (string path in needed) + if (!union.ContainsKey(path)) extract.Add(path); + int serial = 0; + foreach (string path in extract) + { + string file = Path.Combine(work, (++serial).ToString()); + if (!previous.TryExtractEntry(path, file)) throw new InvalidDataException("无法读取旧资源 " + path); + if (union.TryGetValue(path, out var source) && !EqualBytes(file, source)) throw Collision(); + union[path] = file; + } + } + if (!needed.IsSubsetOf(union.Keys) || !oldPaths.IsSubsetOf(union.Keys)) throw new InvalidDataException("缺少新主文件引用的资源"); + if (union.Count > 0) + { + UInkExtraArchive.WriteArchive(tempExtra, union.Select(p => (p.Key, p.Value)).ToList()); + fault?.Invoke("before-extra-verify"); + using var check = new UInkExtraArchive(tempExtra); + if (check.EntryCount != union.Count) throw new InvalidDataException("资源包条目数量不符"); + foreach (string name in union.Keys) + if (!check.VerifyEntry(name)) throw new InvalidDataException("临时资源包条目校验失败 " + name); + } - LogHelper.WriteLogToFile( - $"[UInk] 两阶段提交完成: {mainPath}, 资源 {union.Count} 个, 主文件 {new FileInfo(mainPath).Length} 字节", - LogHelper.LogType.Info); + UInkWriter.WriteDocument(doc, tempMain); + Verify(doc, tempMain); + try + { + if (union.Count > 0) + { + fault?.Invoke("before-extra-replace"); + if (hadExtra) File.Replace(tempExtra, extra, extraBackup); + else File.Move(tempExtra, extra); + fault?.Invoke("after-extra-replace"); + } + fault?.Invoke("before-main-replace"); + if (hadMain) File.Replace(tempMain, mainPath, mainBackup); + else File.Move(tempMain, mainPath); + fault?.Invoke("after-main-replace"); + } + catch (Exception original) + { + try + { + Recover(mainPath, mainBackup, tempMain, hadMain, extra, extraBackup, tempExtra, + hadExtra, union.Count > 0, work, fault); + } + catch (Exception restore) + { + keepRecoveryFiles = true; + throw new IOException($"UInk 保存及恢复均失败,恢复文件前缀:{prefix}", + new AggregateException(original, restore)); + } + throw; + } + LogHelper.WriteLogToFile($"[UInk] 两阶段提交完成: {mainPath}, 资源 {union.Count} 个", LogHelper.LogType.Info); } catch (Exception ex) { - LogHelper.WriteLogToFile($"[UInk] 两阶段提交失败,已回滚临时文件: {mainPath}, 原因: {ex.Message}", LogHelper.LogType.Error); - TryDelete(tmpMain); - TryDelete(tmpExtra); + LogHelper.WriteLogToFile($"[UInk] 两阶段提交失败: {mainPath}, 原因: {ex.Message}", LogHelper.LogType.Error); throw; } finally { - if (workDir != null) + if (!keepRecoveryFiles) { - try { if (Directory.Exists(workDir)) Directory.Delete(workDir, true); } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"[UInk] 两阶段提交后删除资源并集临时目录失败: {workDir}, 原因: {ex.Message}", LogHelper.LogType.Info); - } + TryDelete(tempMain); + TryDelete(tempExtra); + TryDelete(mainBackup); + TryDelete(extraBackup); + } + try { Directory.Delete(work, true); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + LogHelper.WriteLogToFile($"[UInk] 清理资源并集临时目录失败: {work}, 原因: {ex.Message}", LogHelper.LogType.Info); } } } - /// 临时文件可被崩溃恢复发现(记录残留路径日志由调用方处理)。 - public static string TempMainPath(string mainPath) => mainPath + ".tmp"; - public static string TempExtraPath(string mainPath) => mainPath + ".extra.tmp"; - - private static List<(string entryPath, string sourceFile)> BuildUnionResources( - string mainPath, string extraPath, - IReadOnlyList<(string entryPath, string sourceFile)> newResources, - string workDir) + private static void Recover(string main, string mainBackup, string tempMain, bool hadMain, + string extra, string extraBackup, string tempExtra, bool hadExtra, bool writesExtra, string work, Action fault) { - var result = new List<(string, string)>(); - var seen = new HashSet(StringComparer.Ordinal); - if (newResources != null) + // EXTRA-15/16:Windows 替换报错时旧目标可能已移到备份。先修复主文件,再决定能否撤回资源并集。 + bool mainExists = ExistsForRecovery(main), mainTempExists = ExistsForRecovery(tempMain); + if (mainExists && !mainTempExists) return; // 新主已就位,资源并集必须保留。 + if (!mainExists && !hadMain) { - foreach (var r in newResources) + // 首次保存没有旧主可还原,按原顺序补齐已验证的资源包与主文件。 + if (!mainTempExists) throw new IOException("找不到可恢复的临时主文件"); + if (writesExtra) { - var safe = UInkExtraArchive.NormalizeEntryPath(r.entryPath); - if (safe != null && seen.Add(safe)) - result.Add((safe, r.sourceFile)); + if (ExistsForRecovery(tempExtra)) File.Move(tempExtra, extra, true); + if (!ExistsForRecovery(extra)) throw new IOException("找不到可恢复的资源包"); + } + File.Move(tempMain, main); + return; + } + if (!mainExists) + { + try + { + if (!ExistsForRecovery(mainBackup)) throw new IOException("找不到旧主文件备份"); + RestoreBackup(mainBackup, main, Path.Combine(work, "restore-main")); + } + catch (Exception restoreMain) + { + // 旧主文件恢复失败时,已验证的临时主文件仍可与已经到位的资源并集配对。 + try + { + if (mainTempExists && !ExistsForRecovery(main) && + (!writesExtra || (ExistsForRecovery(extra) && !ExistsForRecovery(tempExtra)))) + File.Move(tempMain, main); + } + catch (Exception installMain) { throw new AggregateException(restoreMain, installMain); } + throw; } } - // 旧主文件仍引用的资源:从旧 extra 提取到 workDir 并加入并集, - // 防止主文件替换前资源包已被换掉导致旧主引用断裂。workDir 由调用方在 WriteArchive 后清理。 - if (File.Exists(mainPath) && File.Exists(extraPath)) + if (!writesExtra) return; + if (ExistsForRecovery(extraBackup)) { - UInkDocument oldDoc = null; - try { oldDoc = UInkReader.Load(mainPath); } - catch (Exception ex) + try { - LogHelper.WriteLogToFile($"[UInk] 读取旧主文件以并集旧资源引用失败: {mainPath}, 原因: {ex.Message}", LogHelper.LogType.Info); - oldDoc = null; + fault?.Invoke("before-extra-restore"); + RestoreBackup(extraBackup, extra, Path.Combine(work, "restore-extra")); } - if (oldDoc != null) + catch (Exception restoreExtra) { - var oldPaths = new HashSet(StringComparer.Ordinal); - foreach (var rec in oldDoc.Canvases) - foreach (var b in rec.Blocks) - if (b is UInkMedia m && !string.IsNullOrEmpty(m.Path)) - oldPaths.Add(m.Path); - if (oldPaths.Count > 0) + // 旧包仍在备份路径且无法复制时,可用已验证的临时并集补全目标。 + try { - try - { - var map = UInkExtraArchive.ExtractWithBudget(extraPath, workDir); - if (map != null) - { - foreach (var p in oldPaths) - { - if (!seen.Contains(p) && map.TryGetValue(p, out var file) && File.Exists(file)) - { - result.Add((p, file)); - seen.Add(p); - } - } - } - } - catch (Exception ex) - { - LogHelper.WriteLogToFile($"[UInk] 提取旧资源包以保留旧主文件引用失败: {extraPath}, 原因: {ex.Message}", LogHelper.LogType.Info); - } + if (!ExistsForRecovery(extra) && ExistsForRecovery(tempExtra)) File.Move(tempExtra, extra); } + catch (Exception installExtra) { throw new AggregateException(restoreExtra, installExtra); } + throw; } } - return result; + else if (hadExtra && !ExistsForRecovery(extra)) + { + if (!ExistsForRecovery(tempExtra)) throw new IOException("找不到可恢复的资源包"); + File.Move(tempExtra, extra); + } + // 原来没有资源包时,保留已提交的并集,以便旧主文件也能继续使用其中的资源。 + } + + private static bool ExistsForRecovery(string path) + { + try { return (File.GetAttributes(path) & FileAttributes.Directory) == 0; } + catch (FileNotFoundException) { return false; } + catch (DirectoryNotFoundException) { return false; } + } + + private static void RestoreBackup(string backup, string target, string staging) + { + // 恢复时先复制,直到两份文件均恢复后才清理备份。 + File.Copy(backup, staging); + File.Move(staging, target, true); + } + + private static HashSet Paths(UInkDocument doc) + { + var paths = new HashSet(StringComparer.Ordinal); + foreach (var rec in doc.Canvases) + foreach (var block in rec.Blocks) + if (block is UInkMedia m) paths.Add(Safe(m.Path)); + return paths; + } + + private static string Safe(string path) => + UInkExtraArchive.NormalizeEntryPath(path) ?? throw new InvalidDataException("非法资源路径"); + + private static InvalidDataException Collision() => new("同一路径对应不同资源,应使用内容摘要路径"); + + private static bool EqualBytes(string first, string second) + { + using var a = new BinaryReader(File.OpenRead(first)); + using var b = new BinaryReader(File.OpenRead(second)); + if (a.BaseStream.Length != b.BaseStream.Length) return false; + while (a.BaseStream.Position < a.BaseStream.Length) + if (!a.ReadBytes(81920).AsSpan().SequenceEqual(b.ReadBytes(81920))) return false; + return true; } - private static void AtomicReplace(string tmp, string target) + private static void Verify(UInkDocument doc, string path) { - if (File.Exists(target)) - File.Replace(tmp, target, null); // 同卷 NTFS 原子替换 - else - File.Move(tmp, target); + var check = UInkReader.Read(path); + if (check.Status != UInkReadStatus.Ok || check.Diagnostics.Count != 0 || + check.Document.Canvases.Count != doc.Canvases.Count || check.Version != 11) + throw new InvalidDataException("临时主文件解码校验失败:" + string.Join(", ", check.Diagnostics)); + var h = check.Document.Header; + if ((h.DeviceNum, h.WorkspaceNum, h.PageNum) != UInkWriter.ComputeStats(doc)) + throw new InvalidDataException("Header 统计不符"); + int index = 0; + foreach (var original in UInkWriter.Ordered(doc)) + { + var actual = check.Document.Canvases[index++]; + if (actual.Blocks.Count != original.Blocks.Count || + !string.Equals(original.Canvas.PageGuid, actual.Canvas.PageGuid, StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("Canvas 内容校验失败"); + for (int i = 0; i < actual.Blocks.Count; i++) + if (actual.Blocks[i].ContentId != (uint)i || actual.Blocks[i].GetType() != original.Blocks[i].GetType() || + actual.Blocks[i].UndoId != original.Blocks[i].UndoId) + throw new InvalidDataException("内容块类型或编号不符"); + } } private static void TryDelete(string path) { - try { if (File.Exists(path)) File.Delete(path); } - catch (Exception ex) + try { File.Delete(path); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { LogHelper.WriteLogToFile($"[UInk] 删除临时文件失败: {path}, 原因: {ex.Message}", LogHelper.LogType.Info); } diff --git a/Ink Canvas/UInk/UInkShapeDecoder.cs b/Ink Canvas/UInk/UInkShapeDecoder.cs new file mode 100644 index 000000000..e7d53094f --- /dev/null +++ b/Ink Canvas/UInk/UInkShapeDecoder.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Generic; +using MessagePack; + +namespace Ink_Canvas.UInk +{ + internal sealed partial class UInkDecoder + { + private static readonly UInkSchema ShapeKeys = new(5, "type contentId undoId shapeType geometry stroke fill object renderOnlyWhenLatest extra"); + private static readonly UInkSchema LineKeys = new(1, "points"); + private static readonly UInkSchema RectKeys = new(4, "centerX centerY width height rotation cornerRadiusX cornerRadiusY"); + private static readonly UInkSchema SquareKeys = new(3, "centerX centerY size rotation"); + private static readonly UInkSchema CircleKeys = new(3, "centerX centerY radius"); + private static readonly UInkSchema StrokeKeys = new(3, "color width opacity dashArray dashOffset startMarker endMarker lineCap lineJoin"); + private static readonly UInkSchema FillKeys = new(3, "color opacity fillType"); + private static readonly UInkSchema ObjectKeys = new(0, "id revision preset partCount transform ref partIndex construction style aux"); + + private UInkShape Shape(UInkValue raw) + { + var f = Fields(raw, ShapeKeys); + int type = f["shapeType"].Int(); + var s = new UInkShape + { + ContentId = f["contentId"].UInt(), UndoId = f["undoId"].UInt(), ShapeType = type, + Geometry = Geometry(f["geometry"], type), Stroke = Recover(f["stroke"], v => Stroke(v, type <= 1), "SHAPE-22"), + Fill = Recover(f["fill"], Fill, "SHAPE-22"), Extra = Extra(f), + RenderOnlyWhenLatest = f["renderOnlyWhenLatest"].Present && f["renderOnlyWhenLatest"].Bool() + }; + if (type <= 1 && s.Fill != null) { s.Fill = null; result.Note("SHAPE-4"); } + if (s.Stroke == null && s.Fill == null) throw new UInkFieldException(); + if (f["object"].Present) + { + // TYPE-7:重复已知键交给块级处理,其余对象层错误才按 SHAPE-14 降级。 + try { s.Object = Object(f["object"]); } + catch (UInkFieldException ex) when (ex is not UInkDuplicateKey) { result.Note("SHAPE-14"); } + } + return s; + } + + private UInkShapeGeometry Geometry(UInkValue raw, int type) + { + switch ((UInkShapeType)type) + { + case UInkShapeType.Line: + case UInkShapeType.Polyline: + case UInkShapeType.Polygon: + var line = Fields(raw, LineKeys); + var r = line["points"].Reader(); + if (r.NextMessagePackType != MessagePackType.Array) throw new UInkFieldException(); + int n = r.ReadArrayHeader(); + if (n < 2 || (type == 0 && n != 2) || (type == 6 && n < 3)) throw new UInkFieldException(); + result.ReservePoints(n); + var points = new List(n); + for (int i = 0; i < n; i++) + { + var p = Point(ref r, null, i); + points.Add(new UInkShapePoint { X = p.X, Y = p.Y }); + } + return new UInkLineGeometry { Points = points }; + case UInkShapeType.Square: + var sq = Fields(raw, SquareKeys); + return new UInkSquareGeometry { CenterX = sq["centerX"].Float(), CenterY = sq["centerY"].Float(), + Size = sq["size"].Positive(), Rotation = sq.Float("rotation") }; + case UInkShapeType.Circle: + var c = Fields(raw, CircleKeys); + return new UInkCircleGeometry { CenterX = c["centerX"].Float(), CenterY = c["centerY"].Float(), Radius = c["radius"].Positive() }; + case UInkShapeType.Rectangle: + case UInkShapeType.Ellipse: + var f = Fields(raw, RectKeys); + var rect = new UInkRectGeometry { CenterX = f["centerX"].Float(), CenterY = f["centerY"].Float(), + Width = f["width"].Positive(), Height = f["height"].Positive(), Rotation = f.Float("rotation") }; + if (type == (int)UInkShapeType.Rectangle && (f["cornerRadiusX"].Present || f["cornerRadiusY"].Present)) + { + try + { + float x = f["cornerRadiusX"].Float(), y = f["cornerRadiusY"].Float(); + // SHAPE-3:保留次正规宽高除以二的精确值,避免 float32 上舍入。 + if (!((x == 0 && y == 0) || (x > 0 && y > 0 && x <= rect.Width / 2.0 && y <= rect.Height / 2.0))) + throw new UInkFieldException(); + rect.CornerRadiusX = x; rect.CornerRadiusY = y; + } + catch (UInkFieldException) { result.Note("SHAPE-3"); } + } + return rect; + default: throw new UInkFieldException(); // SHAPE-20 + } + } + + private UInkStroke Stroke(UInkValue raw, bool markersApply) + { + var f = Fields(raw, StrokeKeys); + var s = new UInkStroke { Color = Color(f["color"]), Width = f["width"].Positive(), + Opacity = f["opacity"].Unit(result, "SHAPE-23"), LineCap = f["lineCap"].Enum(result, 2, "NIB-7"), + LineJoin = f["lineJoin"].Enum(result, 2, "NIB-7") }; + if (markersApply) + { + s.StartMarker = f["startMarker"].Enum(result, 1, "SHAPE-21"); + s.EndMarker = f["endMarker"].Enum(result, 1, "SHAPE-21"); + s.UnknownMarker = (f["startMarker"].Present && f["startMarker"].Int() != s.StartMarker) || + (f["endMarker"].Present && f["endMarker"].Int() != s.EndMarker); + } + // SHAPE-9:闭合图形上的 Marker 整个字段被忽略,不影响描边。 + else if (f["startMarker"].Present || f["endMarker"].Present) result.Note("SHAPE-9"); + try + { + s.DashOffset = f.Float("dashOffset"); + if (f["dashArray"].Present) + { + var r = f["dashArray"].Reader(); + if (r.NextMessagePackType != MessagePackType.Array) throw new UInkFieldException(); + int n = r.ReadArrayHeader(); + if ((n & 1) != 0) throw new UInkFieldException(); + var dash = new List(n); + bool positive = false; + for (int i = 0; i < n; i++) + { + float d = UInkNumeric.Single(ref r); + if (d < 0) throw new UInkFieldException(); + positive |= d > 0; + dash.Add(d); + } + if (n > 0 && !positive) throw new UInkFieldException(); + s.DashArray = dash; + } + } + catch (UInkFieldException) { s.DashArray = null; s.DashOffset = null; result.Note("SHAPE-7"); } + return s; + } + + private UInkFill Fill(UInkValue raw) + { + var f = Fields(raw, FillKeys); + return new UInkFill { Color = Color(f["color"]), Opacity = f["opacity"].Unit(result, "SHAPE-23"), + FillType = f["fillType"].Enum(result, 0, "SHAPE-21").Value }; + } + + private UInkShapeObject Object(UInkValue raw) + { + var f = Fields(raw, ObjectKeys); + if (f["ref"].Present) + { + var part = new UInkShapeObject { Ref = f["ref"].GuidText(), PartIndex = f["partIndex"].UInt() }; + if (part.PartIndex == 0 || f["id"].Present) throw new UInkFieldException(); + return part; + } + var head = new UInkShapeObject { Id = f["id"].GuidText(), Revision = f["revision"].ULong(), + Preset = f.Text("preset"), PartCount = f["partCount"].UInt() }; + if (head.Id == Guid.Empty.ToString() || head.Revision == 0 || head.PartCount == 0) throw new UInkFieldException(); + if (f["transform"].Present) head.Transform = f["transform"].Vector(6); + if (f["construction"].Present || f["style"].Present || f["aux"].Present) result.Note("SHAPE-15"); + return head; + } + } +} diff --git a/Ink Canvas/UInk/UInkShowArchive.cs b/Ink Canvas/UInk/UInkShowArchive.cs new file mode 100644 index 000000000..652e2c89e --- /dev/null +++ b/Ink Canvas/UInk/UInkShowArchive.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Threading.Tasks; + +namespace Ink_Canvas.UInk +{ + // 每次放映持有独立对象,结束时排队的快照只使用当时的恢复结果。 + internal sealed class UInkShowArchive + { + internal enum RestoreState { Pending, Complete, Failed, Lossy } + internal RestoreState State; + internal byte[] MainDigest; + internal UInkPageProjection Projection; + internal Task RestoredContent; + + internal static byte[] ContentDigest(UInkDocument doc) + { + using var hash = SHA256.Create(); + using var stream = new CryptoStream(Stream.Null, hash, CryptoStreamMode.Write); + // 只比较有内容的页,当前页位置、保存时间和文件 GUID 不代表新增批注。 + foreach (var page in doc.Canvases.Where(c => c.Blocks.Count > 0).OrderBy(c => c.Canvas.PageGuid, StringComparer.Ordinal)) + { + stream.Write(Guid.Parse(page.Canvas.PageGuid).ToByteArray()); + UInkWriter.WriteBlocks(stream, page.Blocks); + } + stream.FlushFinalBlock(); + return hash.Hash; + } + + internal string Save(UInkDocument doc, string path, IReadOnlyList<(string entryPath, string sourceFile)> resources, + string sourcePath, int droppedMedia) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)); + bool written = UInkSaveService.WithTargetLock(path, () => + { + bool exists = File.Exists(path); + if (exists) + { + if (State != RestoreState.Complete || droppedMedia != 0 || Projection.RequiresSaveAs || + !string.Equals(sourcePath, UInkSaveService.NormalizeTarget(path), StringComparison.OrdinalIgnoreCase)) return false; + // SAVE-1:另一个放映可能已经提交到同名目标,只允许替换实际读到的那一代。 + using var hash = SHA256.Create(); + using var input = File.OpenRead(path); + if (!hash.ComputeHash(input).AsSpan().SequenceEqual(MainDigest)) return false; + } + else if (File.Exists(path + ".extra") || string.Equals(sourcePath, UInkSaveService.NormalizeTarget(path), + StringComparison.OrdinalIgnoreCase)) return false; + UInkSaveService.SaveFull(doc, path, resources); + return true; + }); + if (written) return path; + if (!doc.Canvases.Exists(c => c.Blocks.Count > 0)) return null; + if (RestoredContent != null && ContentDigest(doc).AsSpan().SequenceEqual(RestoredContent.GetAwaiter().GetResult())) return null; + // TYPE-12 / COMPAT-3:复用普通另存的源保护与同目录独占选名。 + return UInkSaveService.SaveSnapshot(doc, path, resources, UInkSaveService.NormalizeTarget(path)); + } + } +} diff --git a/Ink Canvas/UInk/UInkTestVisibility.cs b/Ink Canvas/UInk/UInkTestVisibility.cs new file mode 100644 index 000000000..b1eb56953 --- /dev/null +++ b/Ink Canvas/UInk/UInkTestVisibility.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("InkCanvas.Calibration.Tests")] diff --git a/Ink Canvas/UInk/UInkUndoAdapter.cs b/Ink Canvas/UInk/UInkUndoAdapter.cs index 9ce5187d0..5ec2bdbbd 100644 --- a/Ink Canvas/UInk/UInkUndoAdapter.cs +++ b/Ink Canvas/UInk/UInkUndoAdapter.cs @@ -1,149 +1,99 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Windows.Ink; using Ink_Canvas.Helpers; namespace Ink_Canvas.UInk { - /// 一个 Canvas 的撤回适配结果:最终可见墨迹 + 可导入 ICC TimeMachine 的 delta 链。 - public sealed class UInkUndoAdaptation + // 只用于构建尚未发布的集合。每个块产生全新的 Stroke;WPF 的 IEnumerable 构造器逐笔线性查重。 + internal sealed class UInkStrokeCollection : StrokeCollection { - /// 最终可见墨迹(与 History 共享 Stroke 引用)。 - public StrokeCollection FinalStrokes = new StrokeCollection(); - - /// delta 链:每 undoId 边界的 added→UserInput(false) / removed→UserInput(true)。 - public TimeMachineHistory[] History; + internal void AppendNew(Stroke stroke) => Items.Add(stroke); } - /// - /// 加载方向撤回语义适配(UInk → ICC TimeMachine)。 - /// UInk 用 undoId 分组 + renderOnlyWhenLatest 末尾最新组表达撤回;ICC TimeMachine 是增量栈 - /// (ApplyHistoryToCanvas 对 UserInput:cleared=false 添加 CurrentStroke,true 移除)。 - /// 适配算法: - /// 1. 按 undoId 分组(连续同值 = 一次撤回操作); - /// 2. 对每个前缀应用末尾最新组规则得到可见集 visibleSet(i); - /// 3. 相邻边界差集得 added/removed,生成 UserInput 历史项; - /// 4. 最终可见集 = 载入画布的墨迹。此后 ICC 的 Undo 沿链逐步把「隐藏但未撤回的原稿」展现出来。 - /// Media 块不参与墨迹撤回链(其 undoId 分组语义由元素恢复管线处理,见 UInkIccMapper)。 - /// public static class UInkUndoAdapter { - public static UInkUndoAdaptation Adapt(UInkCanvasRecord record, Func toStroke) - { - var result = new UInkUndoAdaptation(); - if (record?.Blocks == null) return result; - - // 只取 Ink/Shape(Media 不参与墨迹撤回链),并把每个块惰性转换为 Stroke(共享引用) - var content = new List(); - var strokeOf = new Dictionary(); - foreach (var b in record.Blocks) - { - if (!(b is UInkInk || b is UInkShape)) continue; - var s = toStroke?.Invoke(b); - if (s == null) continue; - content.Add(b); - strokeOf[b] = s; - } - if (content.Count == 0) return result; - - // 1. 按 undoId 分组 - var groups = GroupByUndoId(content); - - // 2. 每个前缀的可见集 - var visibleSets = new List> - { - new HashSet(), // S_0 = 空 - }; - var prefix = new List(); - for (int g = 0; g < groups.Count; g++) - { - prefix.AddRange(groups[g]); - visibleSets.Add(ComputeVisibleSet(prefix)); - } + // 内存直接构造的块没有物理序号,继续按相邻 undoId 分组。 + private static long GroupKey(IUInkContentBlock block) => + block is UInkContentBlock { PhysicalUndoGroupOrdinal: int ordinal } ? ordinal : -1L - block.UndoId; - // 3. 相邻边界差集 → delta 链 - var history = new List(); - for (int i = 1; i < visibleSets.Count; i++) - { - var prev = visibleSets[i - 1]; - var cur = visibleSets[i]; - var added = cur.Where(x => !prev.Contains(x)).Select(x => strokeOf[x]).ToList(); - var removed = prev.Where(x => !cur.Contains(x)).Select(x => strokeOf[x]).ToList(); - if (added.Count > 0) - history.Add(new TimeMachineHistory(ToCollection(added), TimeMachineHistoryType.UserInput, false)); - if (removed.Count > 0) - history.Add(new TimeMachineHistory(ToCollection(removed), TimeMachineHistoryType.UserInput, true)); - } - if (history.Count == 0) - history.Add(new TimeMachineHistory( - ToCollection(content.Select(x => strokeOf[x])), TimeMachineHistoryType.UserInput, false)); - - result.FinalStrokes = ToCollection(visibleSets[visibleSets.Count - 1].Select(x => strokeOf[x])); - result.History = history.ToArray(); - return result; - } - - private static List> GroupByUndoId(List content) + // SHAPE-11/14:对象 ID 重复时两处都应解除关联,因此先统计首件,再检查连续区间。 + private static void ValidateObjects(List blocks, Action note) { - var groups = new List>(); - List cur = null; - uint? lastUndo = null; - foreach (var b in content) - { - uint undo = GetUndoId(b); - if (cur == null || undo != lastUndo.Value) + Dictionary counts = null; + foreach (var block in blocks) + if (block is UInkShape { Object: { } obj } && (obj.Id ?? obj.Ref) is string id) { - cur = new List(); - groups.Add(cur); - lastUndo = undo; + counts ??= new Dictionary(); + counts.TryGetValue(id, out var count); + counts[id] = (count.Heads + (obj.Id == null ? 0 : 1), count.Parts + 1); } - cur.Add(b); + if (counts == null) return; + for (int i = 0; i < blocks.Count; i++) + { + if (blocks[i] is not UInkShape { Object: { } obj } shape) continue; + bool valid = obj.Id != null && counts.TryGetValue(obj.Id, out var count) && + count.Heads == 1 && count.Parts == obj.PartCount && + obj.PartCount > 0 && obj.PartCount <= blocks.Count-i; + for (int j=1;valid && j b switch - { - UInkInk i => i.UndoId, - UInkShape s => s.UndoId, - _ => 0, - }; - - private static bool GetMarked(IUInkContentBlock b) => b switch - { - UInkInk i => i.RenderOnlyWhenLatest, - UInkShape s => s.RenderOnlyWhenLatest, - _ => false, - }; - - /// - /// 对前缀应用末尾最新组规则:跳过 Media(此处已过滤),从尾部收集连续 - /// renderOnlyWhenLatest=true 的 Ink/Shape,遇到第一个未标记即停止。 - /// 可见 = 所有未标记块 + 末尾最新组;其他标记块隐藏。 - /// - private static HashSet ComputeVisibleSet(IReadOnlyList prefix) + internal static void AppendCanvas(UInkCanvasRecord record, UInkPageData page, + UInkStrokeCollection final, List history, UInkPageConverter convert, Action note) { - int runStart = prefix.Count; - for (int i = prefix.Count - 1; i >= 0; i--) + var blocks = record.Blocks; + ValidateObjects(blocks,note); + int start = blocks.Count; + // CLEAR-4/7/12:P1 已按原始帧验证 Clear 的独占组;每层分别取最后一个有效切点。 + while (start > 0 && blocks[start - 1] is not UInkClear) start--; + if (start > 0) note("CLEAR-7"); + for (int i = start; i < blocks.Count;) { - if (GetMarked(prefix[i])) runStart = i; - else break; - } - var visible = new HashSet(); - for (int i = 0; i < prefix.Count; i++) - { - if (!GetMarked(prefix[i]) || i >= runStart) - visible.Add(prefix[i]); + long group = GroupKey(blocks[i]); + int ordinal = history.Count; + var strokes = new UInkStrokeCollection(); + int mediaCount = 0; + // INK-3:先确定连续组边界,空组不会把两侧同编号的组连接起来。 + do + { + var block = blocks[i++]; + Stroke stroke = null; + if (block is UInkMedia media) + { + page.Media.Add(media); + mediaCount++; + } + else + { + if (block is UInkInk { RenderOnlyWhenLatest: true } || block is UInkShape { RenderOnlyWhenLatest: true }) + note("INK-15"); + stroke = convert(block, out var parts); + if (stroke == null) + { + if (block is not UInkInk ink || ink.InkType != (int)UInkInkType.Erase) note("unconvertible"); + continue; + } + if (block is UInkShape shape) page.Shapes.Add(shape); + strokes.AppendNew(stroke); + final.AppendNew(stroke); + if (parts != null) + for (int j = 1; j < parts.Count; j++) + { + strokes.AppendNew(parts[j]); + final.AppendNew(parts[j]); + } + } + page.Items.Add((block, stroke, ordinal)); + } while (i < blocks.Count && GroupKey(blocks[i]) == group); + if (strokes.Count > 0 || mediaCount > 0) + history.Add(new UInkGroupHistory(strokes, mediaCount)); } - return visible; - } - - private static StrokeCollection ToCollection(IEnumerable strokes) - { - var c = new StrokeCollection(); - foreach (var s in strokes) c.Add(s); - return c; } } } diff --git a/Ink Canvas/UInk/UInkWriter.cs b/Ink Canvas/UInk/UInkWriter.cs index 664387437..aa46c671e 100644 --- a/Ink Canvas/UInk/UInkWriter.cs +++ b/Ink Canvas/UInk/UInkWriter.cs @@ -1,73 +1,106 @@ -using Ink_Canvas.Helpers; using System; +using System.Buffers; using System.Collections.Generic; using System.IO; +using System.Linq; +using MessagePack; namespace Ink_Canvas.UInk { - /// - /// UInk 主文件写入器。按对象流顺序写出 Header → HeaderExtension → (Canvas → 内容块)*。 - /// 完整保存走 ;增量追加走 。 - /// 两阶段提交(先 .uink.extra 后主文件)由 UInkSaveService 编排。 - /// public static class UInkWriter { - public static void Save(UInkDocument doc, string path) + public static void Save(UInkDocument doc, string path) => UInkSaveService.SaveFull(doc, path, null); + + internal static IEnumerable Ordered(UInkDocument doc) + { + var ws = new Dictionary(StringComparer.OrdinalIgnoreCase); + var devices = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (doc.HeaderExtension?.Workspaces != null) + foreach (var w in doc.HeaderExtension.Workspaces) ws.Add(w.Guid, ws.Count); + if (doc.HeaderExtension?.Devices != null) + foreach (var d in doc.HeaderExtension.Devices) devices.Add(d.Guid, devices.Count); + // SAVE-3:OrderBy/ThenBy 对所有排序键相同的记录保持输入顺序。 + return doc.Canvases.OrderBy(c => ws.GetValueOrDefault(c.Canvas.WorkspaceGuid ?? "", int.MaxValue)) + .ThenBy(c => c.Canvas.PageIndex) + .ThenBy(c => devices.GetValueOrDefault(c.Canvas.DeviceGuid ?? "", int.MaxValue)) + .ThenBy(c => c.Canvas.LayerIndex); + } + + public static void Save(UInkDocument doc, Stream stream) { - var tmp = path + ".tmp"; - try + // 延迟加载的文档也必须写入所有胜出内容。 + foreach (var rec in doc.Canvases) { - using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write)) - { - Save(doc, fs); - } - // 同目录移动替换是原子操作(Windows 同卷 NTFS) - if (File.Exists(path)) - File.Replace(tmp, path, null); - else - File.Move(tmp, path); + UInkReader.MaterializeContent(rec); + ValidateUndo(rec); } - catch (Exception ex) + doc.Header.Type = 0; + doc.Header.Version = 11; + (doc.Header.DeviceNum, doc.Header.WorkspaceNum, doc.Header.PageNum) = ComputeStats(doc); + if (doc.Header.Guid?.Length != 36 || !Guid.TryParseExact(doc.Header.Guid, "D", out _)) + throw new InvalidDataException("无效的 Header UUID"); + WriteBlocks(stream, FullBlocks(doc)); + } + + private static IEnumerable FullBlocks(UInkDocument doc) + { + yield return doc.Header; + if (doc.HeaderExtension != null) yield return doc.HeaderExtension; + foreach (var rec in Ordered(doc)) { - LogHelper.WriteLogToFile($"[UInk] 写入主文件失败(临时文件 {tmp} 未提交): {path}, 原因: {ex.Message}", LogHelper.LogType.Info); - try { if (File.Exists(tmp)) File.Delete(tmp); } - catch (Exception cleanupEx) + yield return rec.Canvas; + uint id = 0; + foreach (var block in rec.Blocks) { - LogHelper.WriteLogToFile($"[UInk] 写入主文件失败后删除临时文件失败: {tmp}, 原因: {cleanupEx.Message}", LogHelper.LogType.Info); + block.ContentId = id++; + yield return block; } - throw; } } - public static void Save(UInkDocument doc, Stream stream) + private static void ValidateUndo(UInkCanvasRecord record) { - UInkSerializer.WriteBlock(stream, doc.Header); - if (doc.HeaderExtension != null) - UInkSerializer.WriteBlock(stream, doc.HeaderExtension); - foreach (var rec in doc.Canvases) + IUInkContentBlock previous = null; + foreach (var block in record.Blocks) + { + uint last = previous?.UndoId ?? 0; + if ((previous == null && block.UndoId != 0) || block.UndoId < last) + throw new InvalidDataException("FILE-15:Canvas 撤回编号应从零开始且只增不减"); + // CLEAR-4:Clear 左右均不能与其相邻内容共用撤回组。 + if (previous != null && block.UndoId == last && (previous is UInkClear || block is UInkClear)) + throw new InvalidDataException("CLEAR-4:Clear 必须独占撤回组"); + previous = block; + } + } + + internal static void WriteBlocks(Stream stream, IEnumerable blocks) + { + var buffer = new ArrayBufferWriter(64 * 1024); + var writer = new MessagePackWriter(buffer); + foreach (var block in blocks) { - UInkSerializer.WriteBlock(stream, rec.Canvas); - foreach (var b in rec.Blocks) - UInkSerializer.WriteBlock(stream, b); + UInkSerializer.WriteBlock(ref writer, block); + writer.Flush(); + if (buffer.WrittenCount >= 64 * 1024) + { + stream.Write(buffer.WrittenSpan); + buffer.Clear(); + writer = new MessagePackWriter(buffer); + } } + stream.Write(buffer.WrittenSpan); } - /// 纯写入(无原子替换),供两阶段提交写临时文件使用。 - public static void WriteDocument(UInkDocument doc, string path) + internal static void WriteDocument(UInkDocument doc, string path) { - using var fs = new FileStream(path, FileMode.Create, FileAccess.Write); + using var fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write); Save(doc, fs); } - /// - /// 增量追加:把已完成的 Ink/Shape/Media 块追加到文件末尾最后一个 Canvas 之后。 - /// 不更新 Header(增量语义:Header 统计可暂时落后,读取端按对象流重算)。 - /// - public static void AppendBlocks(string path, IEnumerable blocks) + internal static void AppendBlocks(string path, IEnumerable blocks) { using var fs = new FileStream(path, FileMode.Append, FileAccess.Write); - foreach (var b in blocks) - UInkSerializer.WriteBlock(fs, b); + WriteBlocks(fs, blocks); } /// 按对象流统计 deviceNum / workspaceNum / pageNum(供完整保存重算 Header)。 @@ -83,7 +116,7 @@ public static (uint deviceNum, uint workspaceNum, uint pageNum) ComputeStats(UIn if (workspaceNum == 0) workspaceNum = 1; // 隐式单例 Workspace // pageNum:各 Workspace 逻辑页数之和,跨设备/跨图层共享 pageGuid 的同页只计一次 - var pageGuids = new HashSet(StringComparer.Ordinal); + var pageGuids = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var rec in doc.Canvases) { if (!string.IsNullOrEmpty(rec.Canvas?.PageGuid)) diff --git a/Ink Canvas/Windows/PPTQuickPanel.xaml.cs b/Ink Canvas/Windows/PPTQuickPanel.xaml.cs index 5dbfacd4f..125d291e4 100644 --- a/Ink Canvas/Windows/PPTQuickPanel.xaml.cs +++ b/Ink Canvas/Windows/PPTQuickPanel.xaml.cs @@ -102,6 +102,7 @@ public static IMMDeviceEnumerator CreateInstance() private double _collapsedOffset = 200; // 折叠时的偏移量(隐藏内容区域) private MainWindow _mainWindow; + internal IReadOnlyDictionary SlideImageOwners => _pptImages; private Dictionary _pptImages = new Dictionary(); private Dictionary> _pptImagePaths = new Dictionary>(); diff --git a/Ink Canvas/Windows/SettingsViews/Helpers/SettingsManager.cs b/Ink Canvas/Windows/SettingsViews/Helpers/SettingsManager.cs index b04d6e8af..aa95324f7 100644 --- a/Ink Canvas/Windows/SettingsViews/Helpers/SettingsManager.cs +++ b/Ink Canvas/Windows/SettingsViews/Helpers/SettingsManager.cs @@ -281,6 +281,19 @@ public static bool MigrateUpdatePackageDefaults() return true; } + public static bool MigrateUInkDefaultSaveFormat() + { + if (Settings == null || Settings.UInkDefaultMigrated) return false; + + var automation = Settings.Automation ??= new Automation(); + // 旧配置的 false 也是默认值;显式 XML/整页用户继续使用原来的优先级。 + if (!automation.IsSaveStrokesAsXML && !automation.IsSaveFullPageStrokes) + automation.IsSaveStrokesAsUInK = true; + + Settings.UInkDefaultMigrated = true; + return true; + } + public static bool MigrateChickenSoupSettings() { if (Settings?.Appearance == null) return false; diff --git a/InkCanvas.Calibration.Tests/InkCanvas.Calibration.Tests.csproj b/InkCanvas.Calibration.Tests/InkCanvas.Calibration.Tests.csproj index 3031a66a1..df208f1ca 100644 --- a/InkCanvas.Calibration.Tests/InkCanvas.Calibration.Tests.csproj +++ b/InkCanvas.Calibration.Tests/InkCanvas.Calibration.Tests.csproj @@ -10,4 +10,7 @@ + + + diff --git a/InkCanvas.Calibration.Tests/Program.cs b/InkCanvas.Calibration.Tests/Program.cs index e387eb245..e82bb9854 100644 --- a/InkCanvas.Calibration.Tests/Program.cs +++ b/InkCanvas.Calibration.Tests/Program.cs @@ -35,6 +35,7 @@ private static int Main(string[] args) string testRoot = Path.Combine(AppContext.BaseDirectory, "test-data", Guid.NewGuid().ToString("N")); App.RootPath = testRoot; SettingsManager.Settings = new Settings(); + if (UInk.UInkReaderTests.IsRequested(args)) return UInk.UInkReaderTests.Dispatch(args); int failed = 0; var tests = new Action[] { TouchCalibrationTests.RunAll, PageConstruction, PointRouteSaves, AreaRouteSaves, FailedSaveRetainsDraft, SpringSolverTests.RunAll, PopupCurveTests.RunAll, PopupTimingTests.RunAll, diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/SHA256SUMS.txt b/InkCanvas.Calibration.Tests/TestData/UInk/v11/SHA256SUMS.txt new file mode 100644 index 000000000..b39c5931e --- /dev/null +++ b/InkCanvas.Calibration.Tests/TestData/UInk/v11/SHA256SUMS.txt @@ -0,0 +1,17 @@ +a796d19f6c4d736721b32e883dab87017f26fa7da9a5a96f0becabea7a9419a4 basic-appearance.uink +a54d13386b7010c401cbb184546d5ae20dbe6c9235b3c8f3a9861b5538cf1c8d compat-v10.uink +6e63809f5dff0908fef66ebcaa396123cedb2e970dc95d3e1ebf7ceeba4673f3 core-page-append.uink +b8ddf6881ffe9e2dd7049650e2990cf36f8af4955a009b464099c81421efc618 core-pages.uink +cecfef2f1740c111aef6c8a0e034eb88657535afcd0a688182a61e6ee4b3958f core-shape-curves.uink +b19b6842606cc49c3a6268c0559a1c1fdd4cd67d96f0fbe586a6506217227295 corrupt-middle.uink +640aa5a533f2114f69f2ecc8f4ff03c53998d38f444567d38aa7e6f6cbe9e889 fallback-unknown.uink +ee50bf99e7f42b0a9fe5e0dee1648d2c24d80c4fead310a1f097c419943820b4 full-hdr-advanced.uink +23c91d8e78763a311d50fac29498ab21e9e54ec8db9bee6e20bd91f1ae98bbb3 full-layers-devices.uink +264f466f6f6b3dfe68dc291b3a1de65e4fc3713aee2d09bd950d942885dfe373 full-shape-preset.uink +da8d84e72783f482b3b74eec1235d7bd230910c664faf21a5639e6838b85eaf1 future-minor.uink +6a8bc79b72b3416ba17b652dfcdb126a391ff896ce674872b683e1671ff8a525 inkeys-erase-clear.uink +8959d697123f835fddd226d14fefde2464fd8eef262ea3c53f98a66283492d10 standard-media.uink +9499aa634378877795e7b02fc0415594fc7fde0348e5225f8249083a1cdf9d4f standard-media.uink.extra +17e63ddcb25a72b8ee76af27d1585b153c7e6b24c27fd93708441bb348530660 standard-ppt.uink +8ecec66188ee304e96240fd3bd0485f3639ecda4d4142a310a6e099f0bc2614f standard-shape-object.uink +ba009c2a6e66598c5a37f60645e2c3d4f7f978a313909fb4f1cb8165f49c479b truncated-tail.uink diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/basic-appearance.uink b/InkCanvas.Calibration.Tests/TestData/UInk/v11/basic-appearance.uink new file mode 100644 index 0000000000000000000000000000000000000000..23d4846be85946e13292af6d9e0478625df80c6f GIT binary patch literal 2630 zcmb7`&rcIU6vt;v`4#UbUX&Ov9*7u8(RNjL2*l#)nKBnf>E57uT(oU$^IZB`VUK{3wS zY}cFT?x$=Sa2l2VtbRWJ@O4R$gzDct;2;-STYxwdE<#?(zyxwWSH(Ch_A2{)%+OGd zIjtKg>eL+A zu?WOu9O4whyw$77&?K`3S-V8mekrnd0LWz26l5=hWR2D3lI{7)03CMZ4Xr+ztVQG< zQsf=}$dy1&R^*(}(}$bmPKv$=Gv%1Bcizbu^$MJ&)9kq)Ayi>J59!f( ziOh6Le4Ur!i}m>USnYFMhtKmme9YTAZx`fKe0-tB=1tTk0d@I-LSDia$|^lm5uUJP zAE}6rF=c?of&>oj8Lp9VWR0Kl$lVgunPP}8&4gdN#ycs0ozMlcqGIc!y%1pv0< zdOBUKu&dYZ!3E^D9a>#oYf-P=5`MQIKkVVpH^+}%t>d#sbMbr5N}lhuytca5qUo4m UHv6fmu`}jzJZ>RkkIZm91L6UT@YO zNLyP{Mn3sE1^^>BmG9C8xB6r2&4GvloIoWGNE@GYsXbk^vUNqidx<)}=G)j)N#Rhr zPrIEaa(&66M$^r>-)7l23)D}*<`~{#8`MNiYoRlJsLPUOZ3AIt6Hj31hdFr#DkW)W8I-2~A zdQf09Kj&-;Mn}HQI(lA@iu|M4_se1%e~4ZAA7a1G#J+xo*h%P+059Z*xQ(oXf=An# zl7pRsk{PggbpGUr8V{>mxLcM{z}+IB>0E&#-w2_h)-_5X6v TqMo-KE1NfFzQEgiZmGcEWlM^* literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/core-page-append.uink b/InkCanvas.Calibration.Tests/TestData/UInk/v11/core-page-append.uink new file mode 100644 index 0000000000000000000000000000000000000000..66c1d44ff0b31b190372280a6e600f4ccc83cbf1 GIT binary patch literal 2718 zcmbP!mVx0c1NTjpG$_zDFfcIEH35>k79awM;ouwt0|O(RU_KAzGGwz{ZfIFjQdy9C zmVt3eUSe+Qre{5!FBfiov48K=t_9DR?0T}VdwEJ~S!Qx-@x-7|(|H&s%g0FP~k zt00;}fJR>e*|e|%LREsPrRA9^B^f}+us1BrNX<;oC;_rrELN507iAY0B!Vn!fm)Ub z1^6sm3)cs;58|0+&u8v^Hh2Gqf{x(CrTP9x*mT zy$8`iOn9s)09p=Fo(u(ee3ZBnq#WVaRUockX>L+#5jX}{i_b5U|eLD zRGzYLU|?8Yl3GzxS_FyCWd-?}c_qb@n-^A`a-If^-pW(XCm0wY@p{VP00RR^#_0oC z=8ys|87EYk!5k$?s8Pa*79~vdh?1usz67IW5^|IPV+JisppnG@1V}Q2IpC8~1D**j z;F;+W@Jb7^2?jh$UigI)yhwS$sQ{PEAyk>c93>+nFQ65jj7UW%BY~om! ze2SJR1|*-79Pp$Tkb^N%v_Ts(tf+N86H literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/core-pages.uink b/InkCanvas.Calibration.Tests/TestData/UInk/v11/core-pages.uink new file mode 100644 index 0000000000000000000000000000000000000000..ccb03854d1c2dcc4d75956bad856300bab5291cf GIT binary patch literal 2333 zcmbW3zi-n(6vtnj9|ItT*E+9opp%P3j`61B^FdznCbCXMACAA~xq9#mf0|l`l zS_BqmT-4=&OWD3N-X8GY(UMisg!>{0W6d1V>tY?Hl$Tt&L=|G;c}0=%^L^>Vxvi-A zhlK7Y*}%7((h8cs*2&0)!m^yoAHtOq?XHATgx?fOo| zh!+8Nsz&@B!0xJ&#yR5-nNB@1({s?UJw4Gg!#z-JUUj3HtgScdqDgRnK)$Y z37!Lorv_ee^Eu+?n-I4@OZO(m?F~IoV#yu1s5gP+Adn^yT)lQ{BEc3Turk-MqeC89 ztY;WojNIIDBQr?0zy7d2G zBHmo5BDRu2Zp{2^=4KtBRl>TKNA=MPamRTWshS-R7nh(Tk;^y2^_GGpE^!cMUN_Bo z6Em?OdLMA_RMao5uHm8cGXGous=^$s0*en;~(`29+#2M^Ks9VO-$kLl;fe8!KNxJ-JYd1mvN z&64sI8F5lF_Q@8L7k^E4G7rXpgE1g71~{XgibTf6Xh}3qb$x0ozI^=r{cKTveJs8o zJcxr1;-E+z4Xhkyfn^|n+^~ua5?)AnT(=pB#^uhlAsZ##W{}(sKzAL%pLd)~o$hj&MLa~VQv zYcn=-S+un@4(}l8r-gt90)a=zk8mjNmSd5z#cZw(tj*QE&+|TCxFN35KYcfD_u+Zp z=jZ2np6{IqDoRj^A5AyQCrhu--juabuh(bgijVN0_Vg=?qMP{`2t%bbX1L-=o!e8U z29+pZnQ@Q0t=w8Xnr@QMJ@jS!#qk~XVs*bzsx%1rT>0K2)d@x#Y(|gjoRK#Io;jc# zm3Hs*n;dqxYIpA_21WJd_F{+p?sr*?W$KGz|9%Xc(E0YLj=iee={Zzi=CIn`u8^{_ z^5p&iYx>=A(i7l2-zo%nbxpN^`HwdPyqypfFlX7MfIRBhJ^`~1CIMXhRFZ(}%2NR@ zeJoSJwDAJ~msx8COl=DSOpY}R_{dGr%v0`f7BIz@3DSq(0aeNCzzx0v4Lz8GaMki0 zaX3-0z~R&kP?eyf-PB89Xvvv-sF~gQ7!RXeHa%bf zDSE|jeTEQyX1}d%0x3qs#@C=`jF*Lum_dr!V3#+?0mNLfzT{4Tm`T}|W&9X+U{HNx6m)q$mRja%vht1(Uwj!gcv|mZh+J~siUc-Skl7Rf^H1JUpkiYRK)RqY7aRNPwfUb^7QEDQfefWxiM8J~wfF?vhGpZs2 znr>|uhlzm3eV~d6_zD^#0=_&6eLw^>jDlB0K*J_5LQHsfbuR85H)KAM7tUR z(JPIB=(9#Zj7TFO#;Xw!v!M|XbEOdwGf4!Lc_sqNDi8r>js7bED?f3n=6}aP;F~r9 zb@T8oYJR>ca|T`wG@2ZDFWkT;Me;F=*(^Kj&AFZRcJ=#r?W}Mk_=}A$OM%mA^wb0j z@)ade5dNoZw*^NVHBYqB3yoHU2SZ1;S~&RsPqfkVL>n_JT3zHai=9*3kg^*BY^@NZ zpG{QYG;j5bo@V1a>p?byy zjf?QY>!|_`#^K%Xwsr~_l&~H46AL_zY42DCcY7}5Uc8toh6n5J#_iR)4czEjkE*(y zV?x@Qh%2Yt4~H)v#I5=L4KZmL!QMy3K4zWEbHK?6U&nl@ZAM##8;GHHn5<4^=>Q* zR-dP@#KfKls_?b%!fNMjz$?Dqi#{U>dDatHeWWPgkcI&wfw{h25_lK96_K=M3LxEW z;RnKb)-<2Xh7Cq`zir7AQu6BT7)Z(IubKrJw1}Fn!Cs|!Ked3AveCFjkU`5;Lk7IM zQ6~Lq@N!0Z_T|D|s>10~kW!86FTkp#3f6A~UQvC$gHvHcjH>TFE&^o44R0iKq?C9i z?-J{zX5u8;WyDzYiV>gDXGUzth_qh7c(qQ!Y-oLixnk61XFh^vryj(_Y90FdLlN!# z#jc2U{_+@173zJg5u?fQ^#~lMxq$^`G*!NVR}yXJVD+_$)LaQuh2|AfMVn^ldYVL@ zY1SdHv`N_FgSkO-5=qEtinanp#f+W*-Sn63&)#)|hBs!N*=n;@`NSvvR#E1z;J-(% HMkx3P&2?Pn literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/corrupt-middle.uink b/InkCanvas.Calibration.Tests/TestData/UInk/v11/corrupt-middle.uink new file mode 100644 index 0000000000000000000000000000000000000000..f0841e75162f1be26292ce9a8081c14ea57d9765 GIT binary patch literal 1011 zcmbP!mVx0c1NTjpG$_zDFfd5fH35>k79awM;ouwt0|O(RU^)-vGGwz{ZfILlQdy9C zmVs$SL1KEUdue9MO_gLQz+;}_N|18Typ+@mkf98#KwQ7l+@#bZuqCT<5-U@S5b~?R ze1rmq4ye7%E0go{N>cMmJX631Ei27S$%nF+XXa&x09|(pXaVEW($vC3Q9K`NwMkH4=5^(iX4`0$;eFB%;h;}uOux3JX zH4_0>D=o+-&DFmsb~TwP(+D+XGNPqSCVHgI8mqSiLu(Q^{Q;9Cj+6QU3c-F z;`~$zQjjAf#q!?XkAVmZ3TQ0SptT(&sM4j0LrIiBDeHUs}stmPmWNbXOqj+BEhYz zp;M>!qjR=dr~LKZVe-)z@Qc6IA9otbtEpezb!y8hIGt%lRYIMrgmdY_aGeV`@Ue2% zG0w1Ar#bs^{9WqL3K_1E-;clV{<}Fm-X6l?>Gf;J+dn+L+j+A6+ws=@Un+H37v#&- z<0quqqYmSO*gqwz&xu0=DVn!7LYFc-3J43h2nCkFO5>)Xr#Nx`k!I&CfDJpz2WO$P z?_-A~=9XEf5i(HbE6gShG*rh=>$No^4husMH;K>+m2tGE)4KoWZ+^dK*{4-1FIu;O9o zL7IxGfyJ35Os?2EmbG8uf^ z*=fY(ONx)UdC6(_x9ML6(@CF4b~+~a~m#8^_UNuJrYu&+^@Dqdl(Ci}rv!}4^Vr9y_K z!azGod9wNr;WYv+(CJy=gov-=<#`|{5x&+eL;~Bi9>h!c5Q+kyyChKLzZ601fY3h4 z^_y?Mm*YC+v4zkJFdh~&0E>BmXbkX*$o*G+Jxd_k2m!IeVj|LV`Q1}z`V zC++`^&zydZ)`)U7(5iX3GF4E%mx<{-5Gn;`L4}Lj9o?9*!kcWWPvd21MBS9T6)JU3 zt{GVWn+DSvSku{Q@aM@$pIlnaMVg%kD4hl{A+>kta#dkz74IXYG-gg@`dZD2j3zr7 GK=T~zI_bIq literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/fixtures.json b/InkCanvas.Calibration.Tests/TestData/UInk/v11/fixtures.json new file mode 100644 index 000000000..1e0124d62 --- /dev/null +++ b/InkCanvas.Calibration.Tests/TestData/UInk/v11/fixtures.json @@ -0,0 +1,5237 @@ +{ + "format": "UInk 1.1 Beta conformance fixtures", + "version": 11, + "generator": "scripts/uink-fixtures/build.mjs(pnpm fixtures:uink),输入为 scripts/uink-fixtures/cases/*.json;重复运行输出逐字节一致", + "levels": { + "core": "核心级", + "basic": "基础级", + "standard": "标准级", + "full": "完整级", + "inkeys": "完整级 + Inkeys 附加级" + }, + "notes": [ + "expected 按等级描述读取器应有的显示结果。core、basic、standard、full 是未实现 Inkeys 附加级的读取器;inkeys 是完整级 + Inkeys 附加级的读取器。", + "objects 是逐个对象解码后的可读内容:Ink 轨迹点保持文件中的写法(首点绝对坐标,其余为位移);float32 写成能还原同一数值的最短十进制。", + "deviations 列出样例故意偏离写入规则的地方(非规范但无损的数值编码、保留的枚举值、不完整的图形对象层),用来验证读取器的容错与回退;写入器不得模仿。", + "validPrefixBytes 是截断或损坏样例中可读部分的结束偏移(不完整或无法解码的对象的起点),也就是 SAVE-22 的安全追加位置;bytesAfterCorruption 是损坏位置之后被放弃的字节数。" + ], + "fixtures": [ + { + "file": "core-pages.uink", + "title": "多页、笔迹与七种基础图形", + "primaryLevel": "core", + "rules": [ + "VER-2", + "HDR-1", + "TYPE-1", + "HEXT-3", + "HEXT-4", + "HEXT-6", + "FILE-1", + "FILE-3", + "FILE-5", + "FILE-7", + "FILE-9", + "FILE-15", + "CANVAS-1", + "CANVAS-10", + "CANVAS-16", + "INK-2", + "INK-3", + "INK-4", + "INK-5", + "INK-7", + "NIB-1", + "COLOR-2", + "SHAPE-1", + "SHAPE-2", + "SHAPE-3", + "SHAPE-4" + ], + "description": "没有 Header Extension,Device 与 Workspace 都是隐式单例(隐式 Workspace 为屏幕批注)。共 3 页:第 1 页 3 条 Pen 笔迹(一条宽度从 4 渐变到 10 再回到 4,一条单点笔迹,一条对勾);第 2 页依次是 Line、Polyline、Rectangle(旋转 15°,描边 + 填充)、Square(旋转 45°)、Ellipse(旋转 −20°,只填充)、Circle、Polygon 三角形(描边 + 填充);第 3 页是没有内容的空白页。所有透明度都是 1。", + "expected": { + "core": "列出 3 页。第 1 页:蓝色波浪笔迹的宽度按每个点的 width 由细到粗再变细;(800, 300) 处一个直径 16 的红色圆点;一个黑色对勾。第 2 页:7 个图形全部画出,旋转角度正确,矩形与三角形同时有描边和填充,椭圆只有浅蓝填充。第 3 页为空白页,不得被省略。", + "basic": "与核心级相同;页码标签为 1、2、3。没有 background,背景透明(隐式 Workspace 是屏幕批注)。", + "standard": "与基础级相同;隐式 Workspace 按屏幕批注处理,没有 viewport,按 { x: 0, y: 0, scale: 1 } 显示;每个内容块是一个撤回组。", + "full": "与标准级相同。", + "inkeys": "与标准级相同。" + }, + "expectedObjects": 14, + "size": 2333, + "sha256": "b8ddf6881ffe9e2dd7049650e2990cf36f8af4955a009b464099c81421efc618", + "objects": [ + [ + 0, + 11, + "ffffffff-0001-4000-8000-000000000000", + 1, + 1, + 3, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-0001-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 240, + "y": 300, + "width": 4 + }, + { + "x": 60, + "y": -20, + "width": 6 + }, + { + "x": 60, + "y": -10, + "width": 8 + }, + { + "x": 60, + "y": 10, + "width": 10 + }, + { + "x": 60, + "y": 20, + "width": 10 + }, + { + "x": 60, + "y": 20, + "width": 8 + }, + { + "x": 60, + "y": 10, + "width": 6 + }, + { + "x": 60, + "y": -10, + "width": 4 + } + ] + }, + { + "type": 3, + "contentId": 1, + "undoId": 1, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 800, + "y": 300, + "width": 16 + } + ] + }, + { + "type": 3, + "contentId": 2, + "undoId": 2, + "inkType": 1, + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 960, + "y": 320, + "width": 5 + }, + { + "x": 40, + "y": 40, + "width": 6 + }, + { + "x": 80, + "y": -100, + "width": 5 + } + ] + }, + { + "type": 2, + "pageGuid": "cccccccc-0001-4000-8000-000000000002", + "pageIndex": 1, + "pageNumber": 2, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 5, + "contentId": 0, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 200, + "y": 200 + }, + { + "x": 500, + "y": 260 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + } + }, + { + "type": 5, + "contentId": 1, + "undoId": 1, + "shapeType": 1, + "geometry": { + "points": [ + { + "x": 600, + "y": 260 + }, + { + "x": 680, + "y": 180 + }, + { + "x": 760, + "y": 260 + }, + { + "x": 840, + "y": 180 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + } + }, + { + "type": 5, + "contentId": 2, + "undoId": 2, + "shapeType": 2, + "geometry": { + "centerX": 300, + "centerY": 520, + "width": 240, + "height": 140, + "rotation": 0.2617994 + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 16769162 + }, + "opacity": 1 + } + }, + { + "type": 5, + "contentId": 3, + "undoId": 3, + "shapeType": 3, + "geometry": { + "centerX": 620, + "centerY": 520, + "size": 160, + "rotation": 0.7853982 + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + } + }, + { + "type": 5, + "contentId": 4, + "undoId": 4, + "shapeType": 4, + "geometry": { + "centerX": 920, + "centerY": 520, + "width": 260, + "height": 140, + "rotation": -0.3490659 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 9425919 + }, + "opacity": 1 + } + }, + { + "type": 5, + "contentId": 5, + "undoId": 5, + "shapeType": 5, + "geometry": { + "centerX": 1220, + "centerY": 520, + "radius": 80 + }, + "stroke": { + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "width": 6 + } + }, + { + "type": 5, + "contentId": 6, + "undoId": 6, + "shapeType": 6, + "geometry": { + "points": [ + { + "x": 1460, + "y": 600 + }, + { + "x": 1560, + "y": 420 + }, + { + "x": 1660, + "y": 600 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 16757683 + }, + "opacity": 1 + } + }, + { + "type": 2, + "pageGuid": "cccccccc-0001-4000-8000-000000000003", + "pageIndex": 2, + "pageNumber": 3, + "layerIndex": 0, + "layerNumber": 0 + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030312d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000003cf000000006b04d38086a474797065cd0002a87061676547756964d92463636363636363632d303030312d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739883a178ca43700000a179ca43960000a57769647468ca4080000083a178ca42700000a179cac1a00000a57769647468ca40c0000083a178ca42700000a179cac1200000a57769647468ca4100000083a178ca42700000a179ca41200000a57769647468ca4120000083a178ca42700000a179ca41a00000a57769647468ca4120000083a178ca42700000a179ca41a00000a57769647468ca4100000083a178ca42700000a179ca41200000a57769647468ca40c0000083a178ca42700000a179cac1200000a57769647468ca4080000088a474797065cd0003a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739183a178ca44480000a179ca43960000a57769647468ca4180000088a474797065cd0003a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca44700000a179ca43a00000a57769647468ca40a0000083a178ca42200000a179ca42200000a57769647468ca40c0000083a178ca42a00000a179cac2c80000a57769647468ca40a0000086a474797065cd0002a87061676547756964d92463636363636363632d303030312d343030302d383030302d303030303030303030303032a970616765496e646578ce00000001aa706167654e756d626572ce00000002aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000086a474797065cd0005a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca43480000a179ca4348000082a178ca43fa0000a179ca43820000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca4080000086a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a9736861706554797065d200000001a867656f6d6574727981a6706f696e74739482a178ca44160000a179ca4382000082a178ca442a0000a179ca4334000082a178ca443e0000a179ca4382000082a178ca44520000a179ca43340000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca4080000087a474797065cd0005a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a9736861706554797065d200000002a867656f6d6574727985a763656e74657258ca43960000a763656e74657259ca44020000a57769647468ca43700000a6686569676874ca430c0000a8726f746174696f6eca3e860a92a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce00ffe08aa76f706163697479ca3f80000086a474797065cd0005a9636f6e74656e744964ce00000003a6756e646f4964ce00000003a9736861706554797065d200000003a867656f6d6574727984a763656e74657258ca441b0000a763656e74657259ca44020000a473697a65ca43200000a8726f746174696f6eca3f490fdba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca4080000086a474797065cd0005a9636f6e74656e744964ce00000004a6756e646f4964ce00000004a9736861706554797065d200000004a867656f6d6574727985a763656e74657258ca44660000a763656e74657259ca44020000a57769647468ca43820000a6686569676874ca430c0000a8726f746174696f6ecabeb2b8c4a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce008fd3ffa76f706163697479ca3f80000086a474797065cd0005a9636f6e74656e744964ce00000005a6756e646f4964ce00000005a9736861706554797065d200000005a867656f6d6574727983a763656e74657258ca44988000a763656e74657259ca44020000a6726164697573ca42a00000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a57769647468ca40c0000087a474797065cd0005a9636f6e74656e744964ce00000006a6756e646f4964ce00000006a9736861706554797065d200000006a867656f6d6574727981a6706f696e74739382a178ca44b68000a179ca4416000082a178ca44c30000a179ca43d2000082a178ca44cf8000a179ca44160000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce00ffb3b3a76f706163697479ca3f80000086a474797065cd0002a87061676547756964d92463636363636363632d303030312d343030302d383030302d303030303030303030303033a970616765496e646578ce00000002aa706167654e756d626572ce00000003aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000" + }, + { + "file": "core-page-append.uink", + "title": "按页追加:同一页以最后出现的版本为准", + "primaryLevel": "core", + "rules": [ + "FILE-7", + "FILE-8", + "FILE-9", + "CANVAS-3", + "CANVAS-5", + "CANVAS-6", + "SAVE-10", + "SAVE-12", + "SAVE-14", + "SAVE-15", + "SAVE-20", + "SAVE-21", + "HDR-4", + "HDR-5", + "HEXT-5", + "HEXT-10" + ], + "description": "一个白板 Workspace,一个 1920×1080 Device。完整保存时有 A、B、C 三页(pageIndex 0、1、2),Header 的 pageNum 快照为 3。之后第 2 页 B 被按页追加了两次:第一次追加的 B′ 多了一笔;第二次追加的 B″ 又多了一个圆,并把 pageIndex 改成 2(用户把 B 拖到最后,C 的新版本还没来得及追加),于是 pageIndex 1 暂时空缺、pageIndex 2 暂时重复。每个新版本的 contentId 与 undoId 都从 0 开始。", + "expected": { + "core": "列出 3 页,顺序为 A、C、B(pageIndex 2 重复,C 的 Canvas 在对象流中先出现,B″ 后出现;读取器为本次显示重新编号为 0、1、2)。A 有 1 条蓝色笔迹;C 有 1 条绿色笔迹;B 只显示最后一个版本 B″:2 条红色笔迹和 1 个圆。B 的旧版本与 B′ 不显示。Header 的 pageNum 与实际页数一致,但读取器不得依赖它。", + "basic": "与核心级相同;页码标签按 pageNumber 显示为 1、3、3(pageNumber 只用于显示,可以重复)。", + "standard": "与基础级相同;按白板打开;currentPageIndex 为 0,按读取器排好的页序解释(HEXT-10),初始显示 A。B″ 的撤回组为 3 个(两笔与圆各一组)。", + "full": "与标准级相同。", + "inkeys": "与标准级相同。" + }, + "expectedObjects": 15, + "size": 2718, + "sha256": "6e63809f5dff0908fef66ebcaa396123cedb2e970dc95d3e1ebf7ceeba4673f3", + "objects": [ + [ + 0, + 11, + "ffffffff-0002-4000-8000-000000000000", + 1, + 1, + 3, + 1795478400 + ], + { + "type": 1, + "name": "按页追加示例", + "devices": [ + { + "guid": "dddddddd-0002-4000-8000-000000000001", + "deviceType": 0, + "x": 0, + "y": 0, + "width": 1920, + "height": 1080 + } + ], + "workspaces": [ + { + "guid": "aaaaaaaa-0002-4000-8000-000000000001", + "workspaceType": 1, + "name": "白板", + "currentPageIndex": 0 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0002-4000-8000-000000000001", + "deviceGuid": "dddddddd-0002-4000-8000-000000000001", + "pageGuid": "cccccccc-0002-4000-8000-00000000000a", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 300, + "y": 400, + "width": 6 + }, + { + "x": 120, + "y": -40, + "width": 6 + }, + { + "x": 120, + "y": 40, + "width": 6 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0002-4000-8000-000000000001", + "deviceGuid": "dddddddd-0002-4000-8000-000000000001", + "pageGuid": "cccccccc-0002-4000-8000-00000000000b", + "pageIndex": 1, + "pageNumber": 2, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 300, + "y": 300, + "width": 6 + }, + { + "x": 300, + "y": 0, + "width": 6 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0002-4000-8000-000000000001", + "deviceGuid": "dddddddd-0002-4000-8000-000000000001", + "pageGuid": "cccccccc-0002-4000-8000-00000000000c", + "pageIndex": 2, + "pageNumber": 3, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 2269291 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 300, + "y": 500, + "width": 6 + }, + { + "x": 120, + "y": 60, + "width": 6 + }, + { + "x": 120, + "y": -60, + "width": 6 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0002-4000-8000-000000000001", + "deviceGuid": "dddddddd-0002-4000-8000-000000000001", + "pageGuid": "cccccccc-0002-4000-8000-00000000000b", + "pageIndex": 1, + "pageNumber": 2, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 300, + "y": 300, + "width": 6 + }, + { + "x": 300, + "y": 0, + "width": 6 + } + ] + }, + { + "type": 3, + "contentId": 1, + "undoId": 1, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 300, + "y": 380, + "width": 6 + }, + { + "x": 300, + "y": 0, + "width": 6 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0002-4000-8000-000000000001", + "deviceGuid": "dddddddd-0002-4000-8000-000000000001", + "pageGuid": "cccccccc-0002-4000-8000-00000000000b", + "pageIndex": 2, + "pageNumber": 3, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 300, + "y": 300, + "width": 6 + }, + { + "x": 300, + "y": 0, + "width": 6 + } + ] + }, + { + "type": 3, + "contentId": 1, + "undoId": 1, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 300, + "y": 380, + "width": 6 + }, + { + "x": 300, + "y": 0, + "width": 6 + } + ] + }, + { + "type": 5, + "contentId": 2, + "undoId": 2, + "shapeType": 5, + "geometry": { + "centerX": 760, + "centerY": 340, + "radius": 60 + }, + "stroke": { + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "width": 4 + } + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030322d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000003cf000000006b04d38084a474797065cd0001a46e616d65b2e68c89e9a1b5e8bfbde58aa0e7a4bae4be8ba7646576696365739186a467756964d92464646464646464642d303030322d343030302d383030302d303030303030303030303031aa64657669636554797065d200000000a178d200000000a179d200000000a57769647468ce00000780a6686569676874ce00000438aa776f726b7370616365739184a467756964d92461616161616161612d303030322d343030302d383030302d303030303030303030303031ad776f726b737061636554797065d200000001a46e616d65a6e799bde69dbfb063757272656e7450616765496e646578ce0000000088a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030322d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030322d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030322d343030302d383030302d303030303030303030303061a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43960000a179ca43c80000a57769647468ca40c0000083a178ca42f00000a179cac2200000a57769647468ca40c0000083a178ca42f00000a179ca42200000a57769647468ca40c0000088a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030322d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030322d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030322d343030302d383030302d303030303030303030303062a970616765496e646578ce00000001aa706167654e756d626572ce00000002aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43960000a179ca43960000a57769647468ca40c0000083a178ca43960000a179ca00000000a57769647468ca40c0000088a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030322d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030322d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030322d343030302d383030302d303030303030303030303063a970616765496e646578ce00000002aa706167654e756d626572ce00000003aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43960000a179ca43fa0000a57769647468ca40c0000083a178ca42f00000a179ca42700000a57769647468ca40c0000083a178ca42f00000a179cac2700000a57769647468ca40c0000088a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030322d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030322d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030322d343030302d383030302d303030303030303030303062a970616765496e646578ce00000001aa706167654e756d626572ce00000002aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43960000a179ca43960000a57769647468ca40c0000083a178ca43960000a179ca00000000a57769647468ca40c0000088a474797065cd0003a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43960000a179ca43be0000a57769647468ca40c0000083a178ca43960000a179ca00000000a57769647468ca40c0000088a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030322d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030322d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030322d343030302d383030302d303030303030303030303062a970616765496e646578ce00000002aa706167654e756d626572ce00000003aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43960000a179ca43960000a57769647468ca40c0000083a178ca43960000a179ca00000000a57769647468ca40c0000088a474797065cd0003a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43960000a179ca43be0000a57769647468ca40c0000083a178ca43960000a179ca00000000a57769647468ca40c0000086a474797065cd0005a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a9736861706554797065d200000005a867656f6d6574727983a763656e74657258ca443e0000a763656e74657259ca43aa0000a6726164697573ca42700000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a57769647468ca40800000" + }, + { + "file": "basic-appearance.uink", + "title": "外观:透明度、荧光笔、笔尖、端帽、虚线、箭头、圆角、背景", + "primaryLevel": "basic", + "rules": [ + "INK-9", + "INK-10", + "NIB-1", + "NIB-3", + "NIB-4", + "NIB-5", + "SHAPE-3", + "SHAPE-6", + "SHAPE-7", + "SHAPE-9", + "CANVAS-8", + "CANVAS-9", + "COMPAT-1" + ], + "description": "一个白板 Workspace,一页,页面背景为米白色点阵(pattern 1)。Ink:半透明蓝色 Pen(opacity 0.5);Inkeys 荧光笔(矩形笔尖 1:8、Fixed、width 表示高度,opacity 0.4;文件里写了 cap = Butt,矩形笔尖忽略端帽,两端就是笔尖的边(NIB-3)),这一笔从左到右再折返,前后两段有一半重叠;Square 端帽与 Butt 端帽的粗笔迹各一条。Shape:虚线 {16, 8} 双向箭头;点线 {0, 18}(Round 端帽,画成一串圆点);Butt 端帽 + Miter 拐角 + 终点箭头的折线;Square 端帽 + Bevel 拐角的折线;圆角矩形(rx 24、ry 16,填充透明度 0.3);半透明虚线椭圆(opacity 0.6,dashOffset 6)。", + "expected": { + "core": "背景按透明或软件默认背景显示。全部按不透明绘制:蓝色 Pen 不透明;荧光笔按 Pen 绘制为不透明黄色、圆形笔尖、直径 24;两条粗笔迹两端都画成圆头。4 条线都是实线、没有箭头,两条折线的拐角与端头都是圆的;矩形是直角,填充为不透明蓝色;椭圆是不透明的实线红色描边。", + "basic": "米白色点阵背景。蓝色 Pen 半透明;荧光笔为竖直的 3 × 24 矩形笔尖扫出的黄色带,两端平头,整条合成一次,折返重叠处颜色不加深;第 3 条笔迹两端为方头(多出半个宽度),第 4 条为平头。第 1 条线是虚线且两端有开放箭头;第 2 条线是一串直径 6 的圆点;第 3 条折线平头、尖角、终点有箭头;第 4 条折线方头、斜切角。矩形四角为椭圆圆角(24 × 16),填充 30% 透明;椭圆描边 60% 透明且为虚线。", + "standard": "与基础级相同。", + "full": "与基础级相同。", + "inkeys": "与基础级相同。" + }, + "expectedObjects": 13, + "size": 2630, + "sha256": "a796d19f6c4d736721b32e883dab87017f26fa7da9a5a96f0becabea7a9419a4", + "objects": [ + [ + 0, + 11, + "ffffffff-0003-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 1, + "devices": [ + { + "guid": "dddddddd-0003-4000-8000-000000000001", + "deviceType": 0, + "x": 0, + "y": 0, + "width": 1920, + "height": 1080 + } + ], + "workspaces": [ + { + "guid": "aaaaaaaa-0003-4000-8000-000000000001", + "workspaceType": 1, + "name": "白板" + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0003-4000-8000-000000000001", + "deviceGuid": "dddddddd-0003-4000-8000-000000000001", + "pageGuid": "cccccccc-0003-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0, + "background": { + "color": { + "fallback": 16447472 + }, + "pattern": 1 + } + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 0.5, + "texture": 0, + "points": [ + { + "x": 200, + "y": 200, + "width": 8 + }, + { + "x": 120, + "y": -20, + "width": 8 + }, + { + "x": 120, + "y": 20, + "width": 8 + }, + { + "x": 120, + "y": -20, + "width": 8 + } + ] + }, + { + "type": 3, + "contentId": 1, + "undoId": 1, + "inkType": 2, + "color": { + "fallback": 16770560 + }, + "opacity": 0.4, + "texture": 0, + "nib": { + "shape": 1, + "aspect": 0.125, + "orientation": 0 + }, + "cap": 2, + "points": [ + { + "x": 200, + "y": 320, + "width": 24 + }, + { + "x": 360, + "y": 0, + "width": 24 + }, + { + "x": -320, + "y": 12, + "width": 24 + }, + { + "x": 360, + "y": 0, + "width": 24 + } + ] + }, + { + "type": 3, + "contentId": 2, + "undoId": 2, + "inkType": 1, + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "texture": 0, + "cap": 1, + "points": [ + { + "x": 200, + "y": 460, + "width": 16 + }, + { + "x": 360, + "y": 0, + "width": 16 + } + ] + }, + { + "type": 3, + "contentId": 3, + "undoId": 3, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "cap": 2, + "points": [ + { + "x": 200, + "y": 540, + "width": 16 + }, + { + "x": 360, + "y": 0, + "width": 16 + } + ] + }, + { + "type": 5, + "contentId": 4, + "undoId": 4, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 700, + "y": 200 + }, + { + "x": 1100, + "y": 200 + } + ] + }, + "stroke": { + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "width": 4, + "dashArray": [ + 16, + 8 + ], + "lineCap": 0, + "startMarker": 1, + "endMarker": 1 + } + }, + { + "type": 5, + "contentId": 5, + "undoId": 5, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 700, + "y": 300 + }, + { + "x": 1100, + "y": 300 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 6, + "dashArray": [ + 0, + 18 + ], + "lineCap": 0 + } + }, + { + "type": 5, + "contentId": 6, + "undoId": 6, + "shapeType": 1, + "geometry": { + "points": [ + { + "x": 700, + "y": 480 + }, + { + "x": 820, + "y": 380 + }, + { + "x": 940, + "y": 480 + }, + { + "x": 1060, + "y": 380 + } + ] + }, + "stroke": { + "color": { + "fallback": 2269291 + }, + "opacity": 1, + "width": 14, + "lineCap": 2, + "lineJoin": 1, + "endMarker": 1 + } + }, + { + "type": 5, + "contentId": 7, + "undoId": 7, + "shapeType": 1, + "geometry": { + "points": [ + { + "x": 700, + "y": 640 + }, + { + "x": 820, + "y": 540 + }, + { + "x": 940, + "y": 640 + }, + { + "x": 1060, + "y": 540 + } + ] + }, + "stroke": { + "color": { + "fallback": 2269291 + }, + "opacity": 1, + "width": 14, + "lineCap": 1, + "lineJoin": 2 + } + }, + { + "type": 5, + "contentId": 8, + "undoId": 8, + "shapeType": 2, + "geometry": { + "centerX": 1400, + "centerY": 300, + "width": 320, + "height": 180, + "cornerRadiusX": 24, + "cornerRadiusY": 16 + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 1989375 + }, + "opacity": 0.3 + } + }, + { + "type": 5, + "contentId": 9, + "undoId": 9, + "shapeType": 4, + "geometry": { + "centerX": 1400, + "centerY": 600, + "width": 300, + "height": 160 + }, + "stroke": { + "color": { + "fallback": 15026253 + }, + "opacity": 0.6, + "width": 6, + "dashArray": [ + 24, + 12 + ], + "dashOffset": 6 + } + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030332d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38083a474797065cd0001a7646576696365739186a467756964d92464646464646464642d303030332d343030302d383030302d303030303030303030303031aa64657669636554797065d200000000a178d200000000a179d200000000a57769647468ce00000780a6686569676874ce00000438aa776f726b7370616365739183a467756964d92461616161616161612d303030332d343030302d383030302d303030303030303030303031ad776f726b737061636554797065d200000001a46e616d65a6e799bde69dbf89a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030332d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030332d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030332d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000aa6261636b67726f756e6482a5636f6c6f7281a866616c6c6261636bce00faf7f0a77061747465726ed20000000188a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f000000a774657874757265d200000000a6706f696e74739483a178ca43480000a179ca43480000a57769647468ca4100000083a178ca42f00000a179cac1a00000a57769647468ca4100000083a178ca42f00000a179ca41a00000a57769647468ca4100000083a178ca42f00000a179cac1a00000a57769647468ca410000008aa474797065cd0003a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a7696e6b54797065d200000002a5636f6c6f7281a866616c6c6261636bce00ffe600a76f706163697479ca3ecccccda774657874757265d200000000a36e696283a57368617065d200000001a6617370656374ca3e000000ab6f7269656e746174696f6ed200000000a3636170d200000002a6706f696e74739483a178ca43480000a179ca43a00000a57769647468ca41c0000083a178ca43b40000a179ca00000000a57769647468ca41c0000083a178cac3a00000a179ca41400000a57769647468ca41c0000083a178ca43b40000a179ca00000000a57769647468ca41c0000089a474797065cd0003a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a774657874757265d200000000a3636170d200000001a6706f696e74739283a178ca43480000a179ca43e60000a57769647468ca4180000083a178ca43b40000a179ca00000000a57769647468ca4180000089a474797065cd0003a9636f6e74656e744964ce00000003a6756e646f4964ce00000003a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a3636170d200000002a6706f696e74739283a178ca43480000a179ca44070000a57769647468ca4180000083a178ca43b40000a179ca00000000a57769647468ca4180000086a474797065cd0005a9636f6e74656e744964ce00000004a6756e646f4964ce00000004a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca442f0000a179ca4348000082a178ca44898000a179ca43480000a67374726f6b6587a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a57769647468ca40800000a964617368417272617992ca41800000ca41000000a76c696e65436170d200000000ab73746172744d61726b6572d200000001a9656e644d61726b6572d20000000186a474797065cd0005a9636f6e74656e744964ce00000005a6756e646f4964ce00000005a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca442f0000a179ca4396000082a178ca44898000a179ca43960000a67374726f6b6585a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40c00000a964617368417272617992ca00000000ca41900000a76c696e65436170d20000000086a474797065cd0005a9636f6e74656e744964ce00000006a6756e646f4964ce00000006a9736861706554797065d200000001a867656f6d6574727981a6706f696e74739482a178ca442f0000a179ca43f0000082a178ca444d0000a179ca43be000082a178ca446b0000a179ca43f0000082a178ca44848000a179ca43be0000a67374726f6b6586a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a57769647468ca41600000a76c696e65436170d200000002a86c696e654a6f696ed200000001a9656e644d61726b6572d20000000186a474797065cd0005a9636f6e74656e744964ce00000007a6756e646f4964ce00000007a9736861706554797065d200000001a867656f6d6574727981a6706f696e74739482a178ca442f0000a179ca4420000082a178ca444d0000a179ca4407000082a178ca446b0000a179ca4420000082a178ca44848000a179ca44070000a67374726f6b6585a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a57769647468ca41600000a76c696e65436170d200000001a86c696e654a6f696ed20000000287a474797065cd0005a9636f6e74656e744964ce00000008a6756e646f4964ce00000008a9736861706554797065d200000002a867656f6d6574727986a763656e74657258ca44af0000a763656e74657259ca43960000a57769647468ca43a00000a6686569676874ca43340000ad636f726e657252616469757358ca41c00000ad636f726e657252616469757359ca41800000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3e99999a86a474797065cd0005a9636f6e74656e744964ce00000009a6756e646f4964ce00000009a9736861706554797065d200000004a867656f6d6574727984a763656e74657258ca44af0000a763656e74657259ca44160000a57769647468ca43960000a6686569676874ca43200000a67374726f6b6585a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f19999aa57769647468ca40c00000a964617368417272617992ca41c00000ca41400000aa646173684f6666736574ca40c00000" + }, + { + "file": "standard-ppt.uink", + "title": "PPT 批注:slideId 绑定、页码绑定、保留页、结束页", + "primaryLevel": "standard", + "rules": [ + "HEXT-7", + "HEXT-8", + "HEXT-10", + "HEXT-14", + "FILE-9", + "CANVAS-8", + "CANVAS-11", + "CANVAS-12", + "CANVAS-13", + "CANVAS-14", + "COMPAT-1", + "COMPAT-4" + ], + "description": "一个 PPT Workspace(workspaceType 2,hostId 为 INKEYS-PPT-7B58E2A1,currentPageIndex 1),一个 1920×1080 Device,共 5 页:第 0 页按 slideId 256 绑定;第 1 页按 slideId 257 绑定,有一条笔迹和一个带箭头的直线;第 2 页 binding = 1,按页码绑定第 3 张幻灯片,不写 slideId;第 3 页 pageState = 1(保留页),原本绑定的 slideId 258 已在演示文稿中删除;第 4 页 pageKind = 1(放映结束后的黑屏页),不写 slideId。没有 background,PPT 页面背景透明。", + "expected": { + "core": "Workspace 类型与绑定字段全部忽略,按普通页面序列显示 5 页(按 pageIndex 0–4),保留页与结束页也作为普通页面显示:第 1 页红色下划线;第 2 页蓝色圈注与一条直线;第 3 页绿色对勾;第 4 页灰色删除线;第 5 页黄色“谢谢”涂写。", + "basic": "与核心级相同;页码标签为 1–5;直线终点有开放箭头。", + "standard": "识别为 hostId 为 INKEYS-PPT-7B58E2A1 的演示文稿批注。第 0 页附着到 SlideID 256 的幻灯片,第 1 页附着到 SlideID 257,第 2 页按页码附着到第 3 张幻灯片;第 4 页是放映结束后的黑屏页;第 3 页是保留页,不放进正常页序,可以单独列出供用户查看或重新绑定。打开后定位到第 1 页(SlideID 257)。在当前演示文稿中找不到 SlideID 256 或 257 时,对应页面必须保留为未绑定页并提示用户,不得按页码、当前页或其他幻灯片自动附着。", + "full": "与标准级相同。", + "inkeys": "与标准级相同。" + }, + "expectedObjects": 13, + "size": 2787, + "sha256": "17e63ddcb25a72b8ee76af27d1585b153c7e6b24c27fd93708441bb348530660", + "objects": [ + [ + 0, + 11, + "ffffffff-0004-4000-8000-000000000000", + 1, + 1, + 5, + 1795478400 + ], + { + "type": 1, + "name": "物理课", + "devices": [ + { + "guid": "dddddddd-0004-4000-8000-000000000001", + "deviceType": 0, + "x": 0, + "y": 0, + "width": 1920, + "height": 1080 + } + ], + "workspaces": [ + { + "guid": "aaaaaaaa-0004-4000-8000-000000000001", + "workspaceType": 2, + "name": "第三章 力", + "hostId": "INKEYS-PPT-7B58E2A1", + "currentPageIndex": 1 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0004-4000-8000-000000000001", + "deviceGuid": "dddddddd-0004-4000-8000-000000000001", + "pageGuid": "cccccccc-0004-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0, + "slideId": 256 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 400, + "y": 620, + "width": 6 + }, + { + "x": 300, + "y": 4, + "width": 6 + }, + { + "x": 300, + "y": -6, + "width": 6 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0004-4000-8000-000000000001", + "deviceGuid": "dddddddd-0004-4000-8000-000000000001", + "pageGuid": "cccccccc-0004-4000-8000-000000000002", + "pageIndex": 1, + "pageNumber": 2, + "layerIndex": 0, + "layerNumber": 0, + "slideId": 257 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 900, + "y": 300, + "width": 5 + }, + { + "x": 100, + "y": -40, + "width": 5 + }, + { + "x": 100, + "y": 40, + "width": 5 + }, + { + "x": 0, + "y": 80, + "width": 5 + }, + { + "x": -100, + "y": 40, + "width": 5 + }, + { + "x": -100, + "y": -40, + "width": 5 + }, + { + "x": 0, + "y": -70, + "width": 5 + } + ] + }, + { + "type": 5, + "contentId": 1, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 600, + "y": 600 + }, + { + "x": 880, + "y": 400 + } + ] + }, + "stroke": { + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "width": 4, + "endMarker": 1 + } + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0004-4000-8000-000000000001", + "deviceGuid": "dddddddd-0004-4000-8000-000000000001", + "pageGuid": "cccccccc-0004-4000-8000-000000000003", + "pageIndex": 2, + "pageNumber": 3, + "layerIndex": 0, + "layerNumber": 0, + "binding": 1 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 2269291 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 1400, + "y": 500, + "width": 8 + }, + { + "x": 40, + "y": 40, + "width": 8 + }, + { + "x": 80, + "y": -100, + "width": 8 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0004-4000-8000-000000000001", + "deviceGuid": "dddddddd-0004-4000-8000-000000000001", + "pageGuid": "cccccccc-0004-4000-8000-000000000004", + "pageIndex": 3, + "pageNumber": 4, + "layerIndex": 0, + "layerNumber": 0, + "pageState": 1, + "slideId": 258 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 7041664 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 500, + "y": 540, + "width": 6 + }, + { + "x": 900, + "y": 0, + "width": 6 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0004-4000-8000-000000000001", + "deviceGuid": "dddddddd-0004-4000-8000-000000000001", + "pageGuid": "cccccccc-0004-4000-8000-000000000005", + "pageIndex": 4, + "pageNumber": 5, + "layerIndex": 0, + "layerNumber": 0, + "pageKind": 1 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 16765952 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 800, + "y": 520, + "width": 8 + }, + { + "x": 60, + "y": -40, + "width": 8 + }, + { + "x": 40, + "y": 80, + "width": 8 + }, + { + "x": 60, + "y": -90, + "width": 8 + }, + { + "x": 40, + "y": 90, + "width": 8 + }, + { + "x": 60, + "y": -80, + "width": 8 + }, + { + "x": 60, + "y": 60, + "width": 8 + } + ] + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030342d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000005cf000000006b04d38084a474797065cd0001a46e616d65a9e789a9e79086e8afbea7646576696365739186a467756964d92464646464646464642d303030342d343030302d383030302d303030303030303030303031aa64657669636554797065d200000000a178d200000000a179d200000000a57769647468ce00000780a6686569676874ce00000438aa776f726b7370616365739185a467756964d92461616161616161612d303030342d343030302d383030302d303030303030303030303031ad776f726b737061636554797065d200000002a46e616d65ade7acace4b889e7aba020e58a9ba6686f73744964b3494e4b4559532d5050542d3742353845324131b063757272656e7450616765496e646578ce0000000189a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030342d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030342d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030342d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a7736c6964654964d20000010088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43c80000a179ca441b0000a57769647468ca40c0000083a178ca43960000a179ca40800000a57769647468ca40c0000083a178ca43960000a179cac0c00000a57769647468ca40c0000089a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030342d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030342d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030342d343030302d383030302d303030303030303030303032a970616765496e646578ce00000001aa706167654e756d626572ce00000002aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a7736c6964654964d20000010188a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739783a178ca44610000a179ca43960000a57769647468ca40a0000083a178ca42c80000a179cac2200000a57769647468ca40a0000083a178ca42c80000a179ca42200000a57769647468ca40a0000083a178ca00000000a179ca42a00000a57769647468ca40a0000083a178cac2c80000a179ca42200000a57769647468ca40a0000083a178cac2c80000a179cac2200000a57769647468ca40a0000083a178ca00000000a179cac28c0000a57769647468ca40a0000086a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44160000a179ca4416000082a178ca445c0000a179ca43c80000a67374726f6b6584a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a57769647468ca40800000a9656e644d61726b6572d20000000189a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030342d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030342d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030342d343030302d383030302d303030303030303030303033a970616765496e646578ce00000002aa706167654e756d626572ce00000003aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a762696e64696e67d20000000188a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca44af0000a179ca43fa0000a57769647468ca4100000083a178ca42200000a179ca42200000a57769647468ca4100000083a178ca42a00000a179cac2c80000a57769647468ca410000008aa474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030342d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030342d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030342d343030302d383030302d303030303030303030303034a970616765496e646578ce00000003aa706167654e756d626572ce00000004aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a9706167655374617465d200000001a7736c6964654964d20000010288a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce006b7280a76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43fa0000a179ca44070000a57769647468ca40c0000083a178ca44610000a179ca00000000a57769647468ca40c0000089a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030342d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030342d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030342d343030302d383030302d303030303030303030303035a970616765496e646578ce00000004aa706167654e756d626572ce00000005aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a8706167654b696e64d20000000188a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00ffd400a76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739783a178ca44480000a179ca44020000a57769647468ca4100000083a178ca42700000a179cac2200000a57769647468ca4100000083a178ca42200000a179ca42a00000a57769647468ca4100000083a178ca42700000a179cac2b40000a57769647468ca4100000083a178ca42200000a179ca42b40000a57769647468ca4100000083a178ca42700000a179cac2a00000a57769647468ca4100000083a178ca42700000a179ca42700000a57769647468ca41000000" + }, + { + "file": "standard-media.uink", + "title": "图片 Media:fit、crop、transform、viewport 映射与资源缺失", + "primaryLevel": "standard", + "rules": [ + "MEDIA-1", + "MEDIA-2", + "MEDIA-3", + "MEDIA-4", + "MEDIA-6", + "MEDIA-7", + "MEDIA-8", + "MEDIA-9", + "MEDIA-11", + "CANVAS-16", + "CANVAS-17", + "CANVAS-18", + "CANVAS-21", + "EXTRA-1", + "EXTRA-2", + "EXTRA-3", + "EXTRA-4", + "EXTRA-9", + "EXTRA-11", + "FILE-14", + "COMPAT-1", + "TYPE-10" + ], + "description": "一个白板页面,viewport = { x: 100, y: 50, scale: 1.5 }:Device 像素 = (Canvas 坐标 − (100, 50)) × 1.5,可见范围为 Canvas (100, 50)–(1380, 770)。资源包 standard-media.uink.extra 中有 32×16 的四色 PNG(左上蓝、右上橙、左下绿、右下洋红)、96×96 的静态 SVG、两页 PDF 和一段 WAV。内容依次为:① PNG 放进 320×320 的框,fit = 1 Contain,平移到 (140, 100);② PNG 放进 160×160 的框,fit = 2 Cover,平移到 (520, 100);③ PNG 的 crop 为左半部分 (0, 0, 16, 16),fit = 0 Fill 放进 160×160 的框,transform 为顺时针旋转 90° 后平移到 (880, 100);④ SVG 放进 64×64 的框,fit = 3 None,opacity 0.6,平移到 (960, 100);⑤ 一条红色 Pen 笔迹画在图片 ① 上;⑥ 引用资源包中不存在的 images/missing.png,框 240×135,平移到 (140, 460);⑦ PDF 的第 2 页(pageCount 2、pageIndex 1),框 320×180,平移到 (440, 460);⑧ 一段音频(不自动播放、音量 0.8)。", + "expected": { + "core": "跳过全部 Media 与资源包,也忽略 viewport:只显示红色笔迹,位于 Canvas 坐标 (150, 260)–(450, 260),宽 6,按 Device 像素原样绘制。", + "basic": "与核心级相同。", + "standard": "应用 viewport:每个内容都按 (x − 100) × 1.5、(y − 50) × 1.5 映射,宽度乘 1.5。① 四色图保持比例放进框内:图像占框中间的 320×160(Canvas y 180–340),上下各留 80 透明;② 四色图保持比例铺满 160×160 的框,只显示中间一半,左边蓝 / 绿、右边橙 / 洋红各占一半;③ 只取左半部分(上蓝下绿)拉伸到 160×160 后顺时针旋转 90°,占据 Canvas (720, 100)–(880, 260),蓝色在右、绿色在左;④ SVG 不缩放,只显示左上 64×64(蓝色圆角方块与白色圆的一部分),60% 透明;⑤ 红色笔迹画在图片 ① 之上(Device 坐标 (75, 315)–(525, 315),宽 9);⑥ 资源缺失:在 (140, 460) 保留 240×135 的位置并提示缺失,其他内容不受影响;⑦ PDF 不支持:在 (440, 460) 保留 320×180 的占位并提示不支持;⑧ 音频不支持:提示不支持。", + "full": "与标准级相同,但 ⑦ 显示 PDF 的第 2 页(橙色矩形中间一个白色方块),⑧ 可以播放音频,音量 0.8,不自动播放、不循环。", + "inkeys": "与完整级相同。" + }, + "expectedObjects": 11, + "size": 1821, + "sha256": "8959d697123f835fddd226d14fefde2464fd8eef262ea3c53f98a66283492d10", + "objects": [ + [ + 0, + 11, + "ffffffff-0005-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 1, + "devices": [ + { + "guid": "dddddddd-0005-4000-8000-000000000001", + "deviceType": 0, + "x": 0, + "y": 0, + "width": 1920, + "height": 1080 + } + ], + "workspaces": [ + { + "guid": "aaaaaaaa-0005-4000-8000-000000000001", + "workspaceType": 1, + "name": "白板" + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0005-4000-8000-000000000001", + "deviceGuid": "dddddddd-0005-4000-8000-000000000001", + "pageGuid": "cccccccc-0005-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0, + "viewport": { + "x": 100, + "y": 50, + "scale": 1.5 + } + }, + { + "type": 4, + "contentId": 0, + "undoId": 0, + "path": "images/quadrants.png", + "mimeType": "image/png", + "width": 320, + "height": 320, + "transform": [ + 1, + 0, + 0, + 1, + 140, + 100 + ], + "fit": 1 + }, + { + "type": 4, + "contentId": 1, + "undoId": 1, + "path": "images/quadrants.png", + "mimeType": "image/png", + "width": 160, + "height": 160, + "transform": [ + 1, + 0, + 0, + 1, + 520, + 100 + ], + "fit": 2 + }, + { + "type": 4, + "contentId": 2, + "undoId": 2, + "path": "images/quadrants.png", + "mimeType": "image/png", + "width": 160, + "height": 160, + "transform": [ + 0, + 1, + -1, + 0, + 880, + 100 + ], + "fit": 0, + "crop": { + "x": 0, + "y": 0, + "width": 16, + "height": 16 + } + }, + { + "type": 4, + "contentId": 3, + "undoId": 3, + "path": "images/badge.svg", + "mimeType": "image/svg+xml", + "width": 64, + "height": 64, + "transform": [ + 1, + 0, + 0, + 1, + 960, + 100 + ], + "opacity": 0.6, + "fit": 3 + }, + { + "type": 3, + "contentId": 4, + "undoId": 4, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 150, + "y": 260, + "width": 6 + }, + { + "x": 300, + "y": 0, + "width": 6 + } + ] + }, + { + "type": 4, + "contentId": 5, + "undoId": 5, + "path": "images/missing.png", + "mimeType": "image/png", + "width": 240, + "height": 135, + "transform": [ + 1, + 0, + 0, + 1, + 140, + 460 + ] + }, + { + "type": 4, + "contentId": 6, + "undoId": 6, + "path": "documents/handout.pdf", + "mimeType": "application/pdf", + "width": 320, + "height": 180, + "transform": [ + 1, + 0, + 0, + 1, + 440, + 460 + ], + "pageCount": 2, + "pageIndex": 1 + }, + { + "type": 4, + "contentId": 7, + "undoId": 7, + "path": "audio/chime.wav", + "mimeType": "audio/wav", + "autoplay": false, + "loop": false, + "volume": 0.8, + "startTime": 0, + "playbackRate": 1 + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030352d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38083a474797065cd0001a7646576696365739186a467756964d92464646464646464642d303030352d343030302d383030302d303030303030303030303031aa64657669636554797065d200000000a178d200000000a179d200000000a57769647468ce00000780a6686569676874ce00000438aa776f726b7370616365739183a467756964d92461616161616161612d303030352d343030302d383030302d303030303030303030303031ad776f726b737061636554797065d200000001a46e616d65a6e799bde69dbf89a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030352d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030352d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030352d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a876696577706f727483a178ca42c80000a179ca42480000a57363616c65ca3fc0000089a474797065cd0004a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a470617468b4696d616765732f7175616472616e74732e706e67a86d696d6554797065a9696d6167652f706e67a57769647468ca43a00000a6686569676874ca43a00000a97472616e73666f726d96ca3f800000ca00000000ca00000000ca3f800000ca430c0000ca42c80000a3666974d20000000189a474797065cd0004a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a470617468b4696d616765732f7175616472616e74732e706e67a86d696d6554797065a9696d6167652f706e67a57769647468ca43200000a6686569676874ca43200000a97472616e73666f726d96ca3f800000ca00000000ca00000000ca3f800000ca44020000ca42c80000a3666974d2000000028aa474797065cd0004a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a470617468b4696d616765732f7175616472616e74732e706e67a86d696d6554797065a9696d6167652f706e67a57769647468ca43200000a6686569676874ca43200000a97472616e73666f726d96ca00000000ca3f800000cabf800000ca00000000ca445c0000ca42c80000a3666974d200000000a463726f7084a178ca00000000a179ca00000000a57769647468ca41800000a6686569676874ca418000008aa474797065cd0004a9636f6e74656e744964ce00000003a6756e646f4964ce00000003a470617468b0696d616765732f62616467652e737667a86d696d6554797065ad696d6167652f7376672b786d6ca57769647468ca42800000a6686569676874ca42800000a97472616e73666f726d96ca3f800000ca00000000ca00000000ca3f800000ca44700000ca42c80000a76f706163697479ca3f19999aa3666974d20000000388a474797065cd0003a9636f6e74656e744964ce00000004a6756e646f4964ce00000004a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43160000a179ca43820000a57769647468ca40c0000083a178ca43960000a179ca00000000a57769647468ca40c0000088a474797065cd0004a9636f6e74656e744964ce00000005a6756e646f4964ce00000005a470617468b2696d616765732f6d697373696e672e706e67a86d696d6554797065a9696d6167652f706e67a57769647468ca43700000a6686569676874ca43070000a97472616e73666f726d96ca3f800000ca00000000ca00000000ca3f800000ca430c0000ca43e600008aa474797065cd0004a9636f6e74656e744964ce00000006a6756e646f4964ce00000006a470617468b5646f63756d656e74732f68616e646f75742e706466a86d696d6554797065af6170706c69636174696f6e2f706466a57769647468ca43a00000a6686569676874ca43340000a97472616e73666f726d96ca3f800000ca00000000ca00000000ca3f800000ca43dc0000ca43e60000a970616765436f756e74ce00000002a970616765496e646578ce000000018aa474797065cd0004a9636f6e74656e744964ce00000007a6756e646f4964ce00000007a470617468af617564696f2f6368696d652e776176a86d696d6554797065a9617564696f2f776176a86175746f706c6179c2a46c6f6f70c2a6766f6c756d65ca3f4ccccda9737461727454696d65cb0000000000000000ac706c61796261636b52617465ca3f800000" + }, + { + "file": "standard-media.uink.extra", + "title": "standard-media.uink 的资源包", + "description": "不压缩的 ZIP,条目按路径排序。PNG 与 PDF 由生成脚本逐字节构造;SVG 只含静态图形,没有脚本、事件与外部引用;images/missing.png 故意不放入。", + "entries": [ + { + "path": "audio/chime.wav", + "mimeType": "audio/wav", + "size": 2044, + "sha256": "8d03cbd54543024d71e6379ab52b0c660f4c555894d1f6723bce4d422bc23651" + }, + { + "path": "documents/handout.pdf", + "mimeType": "application/pdf", + "size": 725, + "sha256": "1ec137046904372d7e18122d2c7f74d92c62eea3b27356b079b33f5e49c62016" + }, + { + "path": "images/badge.svg", + "mimeType": "image/svg+xml", + "size": 202, + "sha256": "fa017ded589b5884575d7c60dca619b7bbe63f3392af57b59b0697b7bce49fe6" + }, + { + "path": "images/quadrants.png", + "mimeType": "image/png", + "size": 1620, + "sha256": "ff3cb2447dc12d17def16f55f7728a7fef4ebb5b40bf4bc117ffff662ec67242" + } + ], + "size": 5061, + "sha256": "9499aa634378877795e7b02fc0415594fc7fde0348e5225f8249083a1cdf9d4f", + "hex": "504b03040a00000000000000785d6dac0fe7fc070000fc0700000f000000617564696f2f6368696d652e77617652494646f407000057415645666d74201000000001000100401f0000401f00000100080064617461d00700009898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868989898989898989868686868686868689898989898989898686868686868686898989898989898986868686868686868504b03040a00000000000000785df719861ad5020000d502000015000000646f63756d656e74732f68616e646f75742e706466255044462d312e340a312030206f626a0a3c3c202f54797065202f436174616c6f67202f5061676573203220302052203e3e0a656e646f626a0a322030206f626a0a3c3c202f54797065202f5061676573202f4b696473205b33203020522035203020525d202f436f756e742032203e3e0a656e646f626a0a332030206f626a0a3c3c202f54797065202f50616765202f506172656e74203220302052202f4d65646961426f78205b30203020333230203138305d202f5265736f7572636573203c3c203e3e202f436f6e74656e7473203420302052203e3e0a656e646f626a0a342030206f626a0a3c3c202f4c656e677468203336203e3e0a73747265616d0a302e31313820302e33353320312072670a3230203230203238302031343020726520660a656e6473747265616d0a656e646f626a0a352030206f626a0a3c3c202f54797065202f50616765202f506172656e74203220302052202f4d65646961426f78205b30203020333230203138305d202f5265736f7572636573203c3c203e3e202f436f6e74656e7473203620302052203e3e0a656e646f626a0a362030206f626a0a3c3c202f4c656e677468203539203e3e0a73747265616d0a3120302e35343120302072670a3230203230203238302031343020726520660a31203120312072670a31323020363020383020363020726520660a656e6473747265616d0a656e646f626a0a787265660a3020370a303030303030303030302036353533352066200a30303030303030303039203030303030206e200a30303030303030303538203030303030206e200a30303030303030313231203030303030206e200a30303030303030323235203030303030206e200a30303030303030333130203030303030206e200a30303030303030343134203030303030206e200a747261696c65720a3c3c202f53697a652037202f526f6f74203120302052203e3e0a7374617274787265660a3532320a2525454f460a504b03040a00000000000000785d4a9aeb3fca000000ca00000010000000696d616765732f62616467652e7376673c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667222077696474683d22393622206865696768743d223936222076696577426f783d22302030203936203936223e3c7265637420783d22342220793d2234222077696474683d22383822206865696768743d223838222072783d223136222066696c6c3d2223314535414646222f3e3c636972636c652063783d223438222063793d2234382220723d223234222066696c6c3d2223464646464646222f3e3c2f7376673e0a504b03040a00000000000000785d2bd8f7fc540600005406000014000000696d616765732f7175616472616e74732e706e6789504e470d0a1a0a0000000d4948445200000020000000100802000000f862ea0e0000061b494441547801011006eff9001e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5affff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00001e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5affff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00001e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5affff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00001e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5affff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00001e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5affff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00001e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5affff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00001e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5affff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00001e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5aff1e5affff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a00ff8a000022a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06bd63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d633840022a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06bd63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d633840022a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06bd63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d633840022a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06bd63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d633840022a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06bd63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d633840022a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06bd63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d633840022a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06bd63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d633840022a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06b22a06bd63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d63384d633843a92dd1ffcc639300000000049454e44ae426082504b010214000a00000000000000785d6dac0fe7fc070000fc0700000f0000000000000000000000000000000000617564696f2f6368696d652e776176504b010214000a00000000000000785df719861ad5020000d5020000150000000000000000000000000029080000646f63756d656e74732f68616e646f75742e706466504b010214000a00000000000000785d4a9aeb3fca000000ca0000001000000000000000000000000000310b0000696d616765732f62616467652e737667504b010214000a00000000000000785d2bd8f7fc54060000540600001400000000000000000000000000290c0000696d616765732f7175616472616e74732e706e67504b0506000000000400040000010000af1200000000" + }, + { + "file": "standard-shape-object.uink", + "title": "图形对象层:箭头、长方体与不完整的对象", + "primaryLevel": "standard", + "rules": [ + "SHAPE-7", + "SHAPE-8", + "SHAPE-9", + "SHAPE-11", + "SHAPE-12", + "SHAPE-13", + "SHAPE-14", + "PRESET-7", + "PRESET-9", + "PRESET-14", + "PRESET-15", + "PRESET-17", + "PRESET-18", + "PRESET-19", + "INK-3", + "COMPAT-1" + ], + "description": "隐式单例,一页。对象 1 是箭头(preset arrow):杆是 Line,箭头是三点实线 Polyline,两个部件共享 undoId 0。对象 2 是长方体(preset cuboid,底面中心 (960, 640),baseSize 320 × 240,height −240,描边宽 3):12 条 Line 按“底边 i、顶边 i、侧棱 i”顺序输出,看不见的 3 条边写成虚线 [12, 18],共享 undoId 1,首个部件带单位矩阵 transform。两个对象都没有 construction(部件即权威几何),部件几何由生成脚本按图形预设注册表计算。对象 3 故意不完整:partCount 为 3 但只写了 2 个部件(undoId 2),用于验证 SHAPE-14 的回退。最后是一条独立的 Pen 笔迹(undoId 3)。", + "expected": { + "core": "忽略对象层,16 个 Shape 各自作为独立图形画出:箭头的杆与箭头(实线)、长方体的 12 条边(全部画成实线)、两条平行横线;另有 1 条蓝色笔迹。", + "basic": "与核心级相同,但长方体看不见的 3 条边(底面后边、底面左边、左后竖棱)画成 [12, 18] 的虚线。", + "standard": "外观与基础级相同。箭头的 2 个部件、长方体的 12 个部件分别作为一个整体选择、移动、删除;对象 3 部件数与 partCount 不符,两条横线作为独立 Shape 处理并报告警告,不拒绝整页。撤回组共 4 个:撤回一次去掉笔迹,再撤回去掉两条横线,再撤回去掉整个长方体,最后去掉箭头。", + "full": "与标准级相同;对象没有 construction,不能修改参数,按对象层整体编辑。", + "inkeys": "与完整级相同。" + }, + "expectedObjects": 19, + "deviations": [ + "#18 Shape.object: 对象 eeeeeeee-0006-4000-8000-000000000003 只有 2/3 个连续部件(被其他内容打断,SHAPE-11)" + ], + "size": 4040, + "sha256": "8ecec66188ee304e96240fd3bd0485f3639ecda4d4142a310a6e099f0bc2614f", + "objects": [ + [ + 0, + 11, + "ffffffff-0006-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-0006-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 5, + "contentId": 0, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 200, + "y": 500 + }, + { + "x": 520, + "y": 340 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "object": { + "id": "eeeeeeee-0006-4000-8000-000000000001", + "revision": 1, + "preset": "arrow", + "partCount": 2 + } + }, + { + "type": 5, + "contentId": 1, + "undoId": 0, + "shapeType": 1, + "geometry": { + "points": [ + { + "x": 511.95016, + "y": 350.73312 + }, + { + "x": 520, + "y": 340 + }, + { + "x": 506.5836, + "y": 340 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000001", + "partIndex": 1 + } + }, + { + "type": 5, + "contentId": 2, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 757.5736, + "y": 682.4264 + }, + { + "x": 1077.5736, + "y": 682.4264 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "id": "eeeeeeee-0006-4000-8000-000000000002", + "revision": 1, + "preset": "cuboid", + "partCount": 12, + "transform": [ + 1, + 0, + 0, + 1, + 0, + 0 + ] + } + }, + { + "type": 5, + "contentId": 3, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 757.5736, + "y": 442.42642 + }, + { + "x": 1077.5736, + "y": 442.42642 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 1 + } + }, + { + "type": 5, + "contentId": 4, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 757.5736, + "y": 682.4264 + }, + { + "x": 757.5736, + "y": 442.42642 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 2 + } + }, + { + "type": 5, + "contentId": 5, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1077.5736, + "y": 682.4264 + }, + { + "x": 1162.4264, + "y": 597.5736 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 3 + } + }, + { + "type": 5, + "contentId": 6, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1077.5736, + "y": 442.42642 + }, + { + "x": 1162.4264, + "y": 357.57358 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 4 + } + }, + { + "type": 5, + "contentId": 7, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1077.5736, + "y": 682.4264 + }, + { + "x": 1077.5736, + "y": 442.42642 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 5 + } + }, + { + "type": 5, + "contentId": 8, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1162.4264, + "y": 597.5736 + }, + { + "x": 842.4264, + "y": 597.5736 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3, + "dashArray": [ + 12, + 18 + ] + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 6 + } + }, + { + "type": 5, + "contentId": 9, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1162.4264, + "y": 357.57358 + }, + { + "x": 842.4264, + "y": 357.57358 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 7 + } + }, + { + "type": 5, + "contentId": 10, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1162.4264, + "y": 597.5736 + }, + { + "x": 1162.4264, + "y": 357.57358 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 8 + } + }, + { + "type": 5, + "contentId": 11, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 842.4264, + "y": 597.5736 + }, + { + "x": 757.5736, + "y": 682.4264 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3, + "dashArray": [ + 12, + 18 + ] + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 9 + } + }, + { + "type": 5, + "contentId": 12, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 842.4264, + "y": 357.57358 + }, + { + "x": 757.5736, + "y": 442.42642 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 10 + } + }, + { + "type": 5, + "contentId": 13, + "undoId": 1, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 842.4264, + "y": 597.5736 + }, + { + "x": 842.4264, + "y": 357.57358 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3, + "dashArray": [ + 12, + 18 + ] + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000002", + "partIndex": 11 + } + }, + { + "type": 5, + "contentId": 14, + "undoId": 2, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1300, + "y": 300 + }, + { + "x": 1500, + "y": 300 + } + ] + }, + "stroke": { + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "width": 4 + }, + "object": { + "id": "eeeeeeee-0006-4000-8000-000000000003", + "revision": 1, + "partCount": 3 + } + }, + { + "type": 5, + "contentId": 15, + "undoId": 2, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1300, + "y": 360 + }, + { + "x": 1500, + "y": 360 + } + ] + }, + "stroke": { + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "width": 4 + }, + "object": { + "ref": "eeeeeeee-0006-4000-8000-000000000003", + "partIndex": 1 + } + }, + { + "type": 3, + "contentId": 16, + "undoId": 3, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 1300, + "y": 500, + "width": 5 + }, + { + "x": 100, + "y": -20, + "width": 5 + }, + { + "x": 100, + "y": 20, + "width": 5 + } + ] + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030362d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38086a474797065cd0002a87061676547756964d92463636363636363632d303030362d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000087a474797065cd0005a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca43480000a179ca43fa000082a178ca44020000a179ca43aa0000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a66f626a65637484a26964d92465656565656565652d303030362d343030302d383030302d303030303030303030303031a87265766973696f6ecf0000000000000001a6707265736574a56172726f77a970617274436f756e74ce0000000287a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000000a9736861706554797065d200000001a867656f6d6574727981a6706f696e74739382a178ca43fff99fa179ca43af5dd782a178ca44020000a179ca43aa000082a178ca43fd4ab3a179ca43aa0000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000187a474797065cd0005a9636f6e74656e744964ce00000002a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca443d64b6a179ca442a9b4a82a178ca4486b25ba179ca442a9b4aa67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637485a26964d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a87265766973696f6ecf0000000000000001a6707265736574a66375626f6964a970617274436f756e74ce0000000ca97472616e73666f726d96ca3f800000ca00000000ca00000000ca3f800000ca00000000ca0000000087a474797065cd0005a9636f6e74656e744964ce00000003a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca443d64b6a179ca43dd369582a178ca4486b25ba179ca43dd3695a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000187a474797065cd0005a9636f6e74656e744964ce00000004a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca443d64b6a179ca442a9b4a82a178ca443d64b6a179ca43dd3695a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000287a474797065cd0005a9636f6e74656e744964ce00000005a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca4486b25ba179ca442a9b4a82a178ca44914da5a179ca441564b6a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000387a474797065cd0005a9636f6e74656e744964ce00000006a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca4486b25ba179ca43dd369582a178ca44914da5a179ca43b2c96ba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000487a474797065cd0005a9636f6e74656e744964ce00000007a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca4486b25ba179ca442a9b4a82a178ca4486b25ba179ca43dd3695a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000587a474797065cd0005a9636f6e74656e744964ce00000008a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44914da5a179ca441564b682a178ca44529b4aa179ca441564b6a67374726f6b6584a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a964617368417272617992ca41400000ca41900000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000687a474797065cd0005a9636f6e74656e744964ce00000009a6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44914da5a179ca43b2c96b82a178ca44529b4aa179ca43b2c96ba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000787a474797065cd0005a9636f6e74656e744964ce0000000aa6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44914da5a179ca441564b682a178ca44914da5a179ca43b2c96ba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000887a474797065cd0005a9636f6e74656e744964ce0000000ba6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44529b4aa179ca441564b682a178ca443d64b6a179ca442a9b4aa67374726f6b6584a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a964617368417272617992ca41400000ca41900000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000987a474797065cd0005a9636f6e74656e744964ce0000000ca6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44529b4aa179ca43b2c96b82a178ca443d64b6a179ca43dd3695a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000a87a474797065cd0005a9636f6e74656e744964ce0000000da6756e646f4964ce00000001a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44529b4aa179ca441564b682a178ca44529b4aa179ca43b2c96ba67374726f6b6584a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a964617368417272617992ca41400000ca41900000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000b87a474797065cd0005a9636f6e74656e744964ce0000000ea6756e646f4964ce00000002a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44a28000a179ca4396000082a178ca44bb8000a179ca43960000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a57769647468ca40800000a66f626a65637483a26964d92465656565656565652d303030362d343030302d383030302d303030303030303030303033a87265766973696f6ecf0000000000000001a970617274436f756e74ce0000000387a474797065cd0005a9636f6e74656e744964ce0000000fa6756e646f4964ce00000002a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44a28000a179ca43b4000082a178ca44bb8000a179ca43b40000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a57769647468ca40800000a66f626a65637482a3726566d92465656565656565652d303030362d343030302d383030302d303030303030303030303033a970617274496e646578ce0000000188a474797065cd0003a9636f6e74656e744964ce00000010a6756e646f4964ce00000003a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca44a28000a179ca43fa0000a57769647468ca40a0000083a178ca42c80000a179cac1a00000a57769647468ca40a0000083a178ca42c80000a179ca41a00000a57769647468ca40a00000" + }, + { + "file": "full-layers-devices.uink", + "title": "多图层、多 Device 与嵌套 Workspace", + "primaryLevel": "full", + "rules": [ + "FILE-9", + "FILE-11", + "FILE-12", + "FILE-13", + "CANVAS-2", + "CANVAS-4", + "CANVAS-8", + "CANVAS-15", + "DEV-1", + "DEV-4", + "DEV-5", + "DEV-6", + "HEXT-2", + "HEXT-5", + "HEXT-11", + "HEXT-12", + "COMPAT-1" + ], + "description": "Device:D1 主显示器 (0, 0) 1920×1080(带 hardware,scaleFactor 1.25 仅供参考);D2 副显示器 (1920, 0) 1920×1080;D3 是 D1 上的板中板 Window,位于 (960, 120),800×600,zIndex 1。Workspace:W1 白板;W2 是 W1 的子白板(parentWorkspaceGuid = W1)。W1 的第 1 页在 D1 上有两个图层:第 0 层是网格背景和一条蓝色笔迹,第 1 层是一个不透明的黄色矩形,盖住蓝色笔迹的中段;同一页在 D2 上另有一个 Canvas,只有一条红色笔迹。W2 的第 1 页只在 D3 上,有一条绿色笔迹。页面元数据只写在第 0 层。", + "expected": { + "core": "按 Workspace 注册顺序列出 2 页。W1 的页面取第一个注册 Device(D1)上的 Canvas:第 0 层与第 1 层按 layerIndex 叠加成一层显示,黄色矩形盖住蓝色笔迹中段;D2 上的红色笔迹不显示(或由软件让用户选择 Device)。W2 是独立的页面序列:它的页面在第一个注册 Device(D1)上没有 Canvas,按注册顺序取第一个有这一页 Canvas 的 Device(D3),作为独立页面显示绿色笔迹,不叠加到 D1 上。背景透明或为软件默认背景。", + "basic": "与核心级相同;W1 第 1 页显示白色网格背景。", + "standard": "与基础级相同;两个 Workspace 都识别为白板。", + "full": "D1 显示 W1 第 1 页:网格背景、蓝色笔迹,第 1 层的黄色矩形在其上方。D2 同时显示同一页的另一个 Canvas,只有红色笔迹,与 D1 的内容互相独立。D3 是 D1 上 (960, 120) 处 800×600 的窗口,W2 的页面合成在 W1 之上,绿色笔迹画在窗口内(窗口自身的 Canvas 坐标)。", + "inkeys": "与完整级相同。" + }, + "expectedObjects": 10, + "size": 2511, + "sha256": "23c91d8e78763a311d50fac29498ab21e9e54ec8db9bee6e20bd91f1ae98bbb3", + "objects": [ + [ + 0, + 11, + "ffffffff-0007-4000-8000-000000000000", + 3, + 2, + 2, + 1795478400 + ], + { + "type": 1, + "name": "双屏与板中板", + "devices": [ + { + "guid": "dddddddd-0007-4000-8000-000000000001", + "deviceType": 0, + "name": "主显示器", + "x": 0, + "y": 0, + "width": 1920, + "height": 1080, + "hardware": { + "name": "Generic Monitor", + "id": "DISPLAY\\GEN0001", + "physicalWidth": 1920, + "physicalHeight": 1080, + "scaleFactor": 1.25 + } + }, + { + "guid": "dddddddd-0007-4000-8000-000000000002", + "deviceType": 0, + "name": "副显示器", + "x": 1920, + "y": 0, + "width": 1920, + "height": 1080 + }, + { + "guid": "dddddddd-0007-4000-8000-000000000003", + "deviceType": 1, + "name": "板中板", + "parentDeviceGuid": "dddddddd-0007-4000-8000-000000000001", + "x": 960, + "y": 120, + "width": 800, + "height": 600, + "zIndex": 1 + } + ], + "workspaces": [ + { + "guid": "aaaaaaaa-0007-4000-8000-000000000001", + "workspaceType": 1, + "name": "白板", + "currentPageIndex": 0 + }, + { + "guid": "aaaaaaaa-0007-4000-8000-000000000002", + "workspaceType": 1, + "name": "板中板白板", + "parentWorkspaceGuid": "aaaaaaaa-0007-4000-8000-000000000001" + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0007-4000-8000-000000000001", + "deviceGuid": "dddddddd-0007-4000-8000-000000000001", + "pageGuid": "cccccccc-0007-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0, + "background": { + "color": { + "fallback": 16777215 + }, + "pattern": 2 + } + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 400, + "width": 10 + }, + { + "x": 600, + "y": 0, + "width": 10 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0007-4000-8000-000000000001", + "deviceGuid": "dddddddd-0007-4000-8000-000000000001", + "pageGuid": "cccccccc-0007-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 1, + "layerNumber": 1 + }, + { + "type": 5, + "contentId": 0, + "undoId": 0, + "shapeType": 2, + "geometry": { + "centerX": 500, + "centerY": 400, + "width": 200, + "height": 120 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 16769162 + }, + "opacity": 1 + } + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0007-4000-8000-000000000001", + "deviceGuid": "dddddddd-0007-4000-8000-000000000002", + "pageGuid": "cccccccc-0007-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0, + "background": { + "color": { + "fallback": 16777215 + }, + "pattern": 2 + } + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 300, + "y": 600, + "width": 8 + }, + { + "x": 600, + "y": -100, + "width": 8 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-0007-4000-8000-000000000002", + "deviceGuid": "dddddddd-0007-4000-8000-000000000003", + "pageGuid": "cccccccc-0007-4000-8000-000000000002", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 2269291 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 100, + "y": 300, + "width": 6 + }, + { + "x": 300, + "y": -100, + "width": 6 + }, + { + "x": 300, + "y": 100, + "width": 6 + } + ] + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030372d343030302d383030302d303030303030303030303030ce00000003ce00000002ce00000002cf000000006b04d38084a474797065cd0001a46e616d65b2e58f8ce5b18fe4b88ee69dbfe4b8ade69dbfa7646576696365739388a467756964d92464646464646464642d303030372d343030302d383030302d303030303030303030303031aa64657669636554797065d200000000a46e616d65ace4b8bbe698bee7a4bae599a8a178d200000000a179d200000000a57769647468ce00000780a6686569676874ce00000438a8686172647761726585a46e616d65af47656e65726963204d6f6e69746f72a26964af444953504c41595c47454e30303031ad706879736963616c5769647468ce00000780ae706879736963616c486569676874ce00000438ab7363616c65466163746f72ca3fa0000087a467756964d92464646464646464642d303030372d343030302d383030302d303030303030303030303032aa64657669636554797065d200000000a46e616d65ace589afe698bee7a4bae599a8a178d200000780a179d200000000a57769647468ce00000780a6686569676874ce0000043889a467756964d92464646464646464642d303030372d343030302d383030302d303030303030303030303033aa64657669636554797065d200000001a46e616d65a9e69dbfe4b8ade69dbfb0706172656e7444657669636547756964d92464646464646464642d303030372d343030302d383030302d303030303030303030303031a178ca44700000a179ca42f00000a57769647468ca44480000a6686569676874ca44160000a67a496e646578ce00000001aa776f726b7370616365739284a467756964d92461616161616161612d303030372d343030302d383030302d303030303030303030303031ad776f726b737061636554797065d200000001a46e616d65a6e799bde69dbfb063757272656e7450616765496e646578ce0000000084a467756964d92461616161616161612d303030372d343030302d383030302d303030303030303030303032ad776f726b737061636554797065d200000001a46e616d65afe69dbfe4b8ade69dbfe799bde69dbfb3706172656e74576f726b737061636547756964d92461616161616161612d303030372d343030302d383030302d30303030303030303030303189a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030372d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030372d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030372d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000aa6261636b67726f756e6482a5636f6c6f7281a866616c6c6261636bce00ffffffa77061747465726ed20000000288a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43480000a179ca43c80000a57769647468ca4120000083a178ca44160000a179ca00000000a57769647468ca4120000088a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030372d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030372d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030372d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000001ab6c617965724e756d626572ce0000000186a474797065cd0005a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a9736861706554797065d200000002a867656f6d6574727984a763656e74657258ca43fa0000a763656e74657259ca43c80000a57769647468ca43480000a6686569676874ca42f00000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce00ffe08aa76f706163697479ca3f80000089a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030372d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030372d343030302d383030302d303030303030303030303032a87061676547756964d92463636363636363632d303030372d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000aa6261636b67726f756e6482a5636f6c6f7281a866616c6c6261636bce00ffffffa77061747465726ed20000000288a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43960000a179ca44160000a57769647468ca4100000083a178ca44160000a179cac2c80000a57769647468ca4100000088a474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030372d343030302d383030302d303030303030303030303032aa64657669636547756964d92464646464646464642d303030372d343030302d383030302d303030303030303030303033a87061676547756964d92463636363636363632d303030372d343030302d383030302d303030303030303030303032a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca42c80000a179ca43960000a57769647468ca40c0000083a178ca43960000a179cac2c80000a57769647468ca40c0000083a178ca43960000a179ca42c80000a57769647468ca40c00000" + }, + { + "file": "full-hdr-advanced.uink", + "title": "HDR 颜色、Advanced Highlighter、纹理与 renderOnlyWhenLatest", + "primaryLevel": "full", + "rules": [ + "COLOR-1", + "COLOR-2", + "INK-9", + "INK-10", + "INK-12", + "INK-13", + "INK-14", + "INK-15", + "SAVE-4", + "COMPAT-1" + ], + "description": "隐式单例,一页,6 个内容块,各自一个撤回组:① Pen,颜色为 scRGB HDR 黄色 [1.8, 0.65, 0.1],fallback 0xFFCC00;② Advanced Highlighter(inkType 3),块级颜色为浅蓝、opacity 0.5,第 2 个点带橙色 0.6 锚点、第 4 个点带洋红 0.3 锚点;③ Pen,texture = 130(私有纹理,只有事先约定的软件认识);④ Rectangle,描边颜色为 srgb [0.2, 0.4, 1.0],fallback 0x3366FF;⑤ 手画的不规则圆(Pen,renderOnlyWhenLatest = true,形状修正前的原稿);⑥ 修正结果:一个标准 Circle(未标记)。", + "expected": { + "core": "全部 6 个内容都显示。① 用 fallback 0xFFCC00 绘制;② 按 Pen 绘制:圆形笔尖、直径 24、块级浅蓝色、不透明,没有点级颜色;③ 按默认纹理绘制;④ 描边使用 fallback 0x3366FF;⑤ 手画原稿与 ⑥ 修正后的圆同时显示(重叠在一起)。", + "basic": "与核心级相同,但 ② 按 Highlighter 绘制:矩形笔尖、块级浅蓝、整条 50% 透明合成一次,不使用点级锚点。", + "standard": "与基础级相同。", + "full": "① 在 HDR 屏幕上使用 scRGB [1.8, 0.65, 0.1](超出 SDR 的高亮黄色),在 SDR 屏幕上使用 fallback;② 第 2 个点之前为橙色 0.6,第 2 到第 4 个点之间由橙色 0.6 平滑过渡到洋红 0.3,之后保持洋红 0.3,整条合成一次;③ 私有纹理 130 不认识,按 0 绘制;④ 使用 srgb 扩展颜色(与 fallback 视觉相同);⑤ 被隐藏,只显示 ⑥ 修正后的圆。撤回 ⑥ 后,⑤ 成为末尾最新组,重新显示。", + "inkeys": "与完整级相同。" + }, + "expectedObjects": 8, + "size": 1765, + "sha256": "ee50bf99e7f42b0a9fe5e0dee1648d2c24d80c4fead310a1f097c419943820b4", + "objects": [ + [ + 0, + 11, + "ffffffff-0008-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-0008-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 16763904, + "space": "scrgb", + "components": [ + 1.8, + 0.65, + 0.1 + ] + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 200, + "width": 10 + }, + { + "x": 200, + "y": -20, + "width": 10 + }, + { + "x": 200, + "y": 40, + "width": 10 + } + ] + }, + { + "type": 3, + "contentId": 1, + "undoId": 1, + "inkType": 3, + "color": { + "fallback": 8180991 + }, + "opacity": 0.5, + "texture": 0, + "nib": { + "shape": 1, + "aspect": 0.125, + "orientation": 0 + }, + "cap": 2, + "points": [ + { + "x": 200, + "y": 360, + "width": 24 + }, + { + "x": 120, + "y": 0, + "width": 24, + "color": { + "fallback": 16747008 + }, + "opacity": 0.6 + }, + { + "x": 120, + "y": 0, + "width": 24 + }, + { + "x": 120, + "y": 0, + "width": 24, + "color": { + "fallback": 14037892 + }, + "opacity": 0.3 + }, + { + "x": 120, + "y": 0, + "width": 24 + } + ] + }, + { + "type": 3, + "contentId": 2, + "undoId": 2, + "inkType": 1, + "color": { + "fallback": 2269291 + }, + "opacity": 1, + "texture": 130, + "points": [ + { + "x": 200, + "y": 480, + "width": 8 + }, + { + "x": 200, + "y": 20, + "width": 8 + }, + { + "x": 200, + "y": -20, + "width": 8 + } + ] + }, + { + "type": 5, + "contentId": 3, + "undoId": 3, + "shapeType": 2, + "geometry": { + "centerX": 400, + "centerY": 680, + "width": 300, + "height": 160 + }, + "stroke": { + "color": { + "fallback": 3368703, + "space": "srgb", + "components": [ + 0.2, + 0.4, + 1 + ] + }, + "opacity": 1, + "width": 6 + } + }, + { + "type": 3, + "contentId": 4, + "undoId": 4, + "inkType": 1, + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 1320, + "y": 400, + "width": 5 + }, + { + "x": -11, + "y": 63, + "width": 5 + }, + { + "x": -52, + "y": 36, + "width": 5 + }, + { + "x": -57, + "y": 23, + "width": 5 + }, + { + "x": -58, + "y": -22, + "width": 5 + }, + { + "x": -49, + "y": -38, + "width": 5 + }, + { + "x": -11, + "y": -62, + "width": 5 + }, + { + "x": 9, + "y": -63, + "width": 5 + }, + { + "x": 52, + "y": -36, + "width": 5 + }, + { + "x": 57, + "y": -23, + "width": 5 + }, + { + "x": 59, + "y": 21, + "width": 5 + }, + { + "x": 49, + "y": 39, + "width": 5 + }, + { + "x": 8, + "y": 58, + "width": 5 + } + ], + "renderOnlyWhenLatest": true + }, + { + "type": 5, + "contentId": 5, + "undoId": 5, + "shapeType": 5, + "geometry": { + "centerX": 1200, + "centerY": 400, + "radius": 120 + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 5 + } + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030382d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38086a474797065cd0002a87061676547756964d92463636363636363632d303030382d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7283a866616c6c6261636bce00ffcc00a57370616365a57363726762aa636f6d706f6e656e747393ca3fe66666ca3f266666ca3dcccccda76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43480000a179ca43480000a57769647468ca4120000083a178ca43480000a179cac1a00000a57769647468ca4120000083a178ca43480000a179ca42200000a57769647468ca412000008aa474797065cd0003a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a7696e6b54797065d200000003a5636f6c6f7281a866616c6c6261636bce007cd4ffa76f706163697479ca3f000000a774657874757265d200000000a36e696283a57368617065d200000001a6617370656374ca3e000000ab6f7269656e746174696f6ed200000000a3636170d200000002a6706f696e74739583a178ca43480000a179ca43b40000a57769647468ca41c0000085a178ca42f00000a179ca00000000a57769647468ca41c00000a5636f6c6f7281a866616c6c6261636bce00ff8a00a76f706163697479ca3f19999a83a178ca42f00000a179ca00000000a57769647468ca41c0000085a178ca42f00000a179ca00000000a57769647468ca41c00000a5636f6c6f7281a866616c6c6261636bce00d63384a76f706163697479ca3e99999a83a178ca42f00000a179ca00000000a57769647468ca41c0000088a474797065cd0003a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a774657874757265d200000082a6706f696e74739383a178ca43480000a179ca43f00000a57769647468ca4100000083a178ca43480000a179ca41a00000a57769647468ca4100000083a178ca43480000a179cac1a00000a57769647468ca4100000086a474797065cd0005a9636f6e74656e744964ce00000003a6756e646f4964ce00000003a9736861706554797065d200000002a867656f6d6574727984a763656e74657258ca43c80000a763656e74657259ca442a0000a57769647468ca43960000a6686569676874ca43200000a67374726f6b6583a5636f6c6f7283a866616c6c6261636bce003366ffa57370616365a473726762aa636f6d706f6e656e747393ca3e4ccccdca3ecccccdca3f800000a76f706163697479ca3f800000a57769647468ca40c0000089a474797065cd0003a9636f6e74656e744964ce00000004a6756e646f4964ce00000004a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739d83a178ca44a50000a179ca43c80000a57769647468ca40a0000083a178cac1300000a179ca427c0000a57769647468ca40a0000083a178cac2500000a179ca42100000a57769647468ca40a0000083a178cac2640000a179ca41b80000a57769647468ca40a0000083a178cac2680000a179cac1b00000a57769647468ca40a0000083a178cac2440000a179cac2180000a57769647468ca40a0000083a178cac1300000a179cac2780000a57769647468ca40a0000083a178ca41100000a179cac27c0000a57769647468ca40a0000083a178ca42500000a179cac2100000a57769647468ca40a0000083a178ca42640000a179cac1b80000a57769647468ca40a0000083a178ca426c0000a179ca41a80000a57769647468ca40a0000083a178ca42440000a179ca421c0000a57769647468ca40a0000083a178ca41000000a179ca42680000a57769647468ca40a00000b472656e6465724f6e6c795768656e4c6174657374c386a474797065cd0005a9636f6e74656e744964ce00000005a6756e646f4964ce00000005a9736861706554797065d200000005a867656f6d6574727983a763656e74657258ca44960000a763656e74657259ca43c80000a6726164697573ca42f00000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40a00000" + }, + { + "file": "full-shape-preset.uink", + "title": "图形预设:construction 重建与不认识的预设", + "primaryLevel": "full", + "rules": [ + "SHAPE-11", + "SHAPE-12", + "SHAPE-13", + "SHAPE-15", + "PRESET-1", + "PRESET-2", + "PRESET-3", + "PRESET-4", + "PRESET-5", + "PRESET-7", + "PRESET-8", + "PRESET-10", + "PRESET-14", + "PRESET-15", + "PRESET-17", + "PRESET-18", + "PRESET-19", + "PRESET-20", + "COMPAT-1" + ], + "description": "隐式单例,一页,3 个对象,每个对象一个撤回组。对象 1 是长方体(preset cuboid,revision 3):construction 为 start (0, 0)、height −160、baseSize 200 × 160、baseRotation 0.5 弧度;对象 transform 为等比缩放 1.5 并平移到 (700, 620);style.width 为 2(局部单位),部件描边宽度 = 2 × 1.5 = 3,隐藏边为 [12, 18] 虚线;aux = 0。对象 2 是圆(preset circle,mode 1 圆心 + 半径):圆心 (1400, 400)、半径 120,描边 + 浅蓝填充,aux = 1 在圆心生成一个半径 4 的点(只有填充的 Circle,颜色与透明度取描边的 1E5AFF 与 strokeOpacity),共 2 个部件。两个对象的部件都由生成脚本从 construction 计算,与 construction 一致。对象 3 的 preset 为 x-example-unknown(私有预设,读取器不认识),带一个五角星 Polygon 与一条 Line,construction 中还有不认识的键 spikes。", + "expected": { + "core": "忽略对象层,16 个 Shape 各自画出:长方体 12 条边(按 PRESET-19 的顶点顺序输出,全部实线,宽 3)、圆(描边 + 填充)与圆心实心点、五角星与下方横线。", + "basic": "与核心级相同,但长方体看不见的边画成 [12, 18] 虚线。", + "standard": "外观与基础级相同;3 个对象各自作为整体选择、移动、删除,不能修改参数。", + "full": "外观与标准级相同,显示以文件中的部件为准。长方体与圆认识预设且 construction 有效,可以重建后继续编辑参数(例如拖动高度、修改 baseRotation 或半径),编辑后替换全部部件;x-example-unknown 不认识,退回对象层,只能整体编辑,不拒绝整页。", + "inkeys": "与完整级相同。" + }, + "expectedObjects": 18, + "size": 4662, + "sha256": "264f466f6f6b3dfe68dc291b3a1de65e4fc3713aee2d09bd950d942885dfe373", + "objects": [ + [ + 0, + 11, + "ffffffff-0009-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-0009-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 5, + "contentId": 0, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 563.23566, + "y": 682.6581 + }, + { + "x": 877.36115, + "y": 631.8073 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "id": "eeeeeeee-0009-4000-8000-000000000001", + "revision": 3, + "preset": "cuboid", + "partCount": 12, + "transform": [ + 1.5, + 0, + 0, + 1.5, + 700, + 620 + ], + "construction": { + "start": { + "x": 0, + "y": 0 + }, + "height": -160, + "baseSize": { + "x": 200, + "y": 160 + }, + "baseRotation": 0.5 + }, + "style": { + "stroke": true, + "fill": false, + "strokeColor": { + "fallback": 2042167 + }, + "strokeOpacity": 1, + "width": 2, + "linePattern": 0 + }, + "aux": 0 + } + }, + { + "type": 5, + "contentId": 1, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 563.23566, + "y": 442.65805 + }, + { + "x": 877.36115, + "y": 391.80728 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 1 + } + }, + { + "type": 5, + "contentId": 2, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 563.23566, + "y": 682.6581 + }, + { + "x": 563.23566, + "y": 442.65805 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 2 + } + }, + { + "type": 5, + "contentId": 3, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 877.36115, + "y": 631.8073 + }, + { + "x": 836.76434, + "y": 557.3419 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3, + "dashArray": [ + 12, + 18 + ] + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 3 + } + }, + { + "type": 5, + "contentId": 4, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 877.36115, + "y": 391.80728 + }, + { + "x": 836.76434, + "y": 317.34195 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 4 + } + }, + { + "type": 5, + "contentId": 5, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 877.36115, + "y": 631.8073 + }, + { + "x": 877.36115, + "y": 391.80728 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 5 + } + }, + { + "type": 5, + "contentId": 6, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 836.76434, + "y": 557.3419 + }, + { + "x": 522.63885, + "y": 608.1927 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3, + "dashArray": [ + 12, + 18 + ] + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 6 + } + }, + { + "type": 5, + "contentId": 7, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 836.76434, + "y": 317.34195 + }, + { + "x": 522.63885, + "y": 368.19272 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 7 + } + }, + { + "type": 5, + "contentId": 8, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 836.76434, + "y": 557.3419 + }, + { + "x": 836.76434, + "y": 317.34195 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3, + "dashArray": [ + 12, + 18 + ] + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 8 + } + }, + { + "type": 5, + "contentId": 9, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 522.63885, + "y": 608.1927 + }, + { + "x": 563.23566, + "y": 682.6581 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 9 + } + }, + { + "type": 5, + "contentId": 10, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 522.63885, + "y": 368.19272 + }, + { + "x": 563.23566, + "y": 442.65805 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 10 + } + }, + { + "type": 5, + "contentId": 11, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 522.63885, + "y": 608.1927 + }, + { + "x": 522.63885, + "y": 368.19272 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000001", + "partIndex": 11 + } + }, + { + "type": 5, + "contentId": 12, + "undoId": 1, + "shapeType": 5, + "geometry": { + "centerX": 1400, + "centerY": 400, + "radius": 120 + }, + "stroke": { + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "width": 4 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 14477567 + }, + "opacity": 1 + }, + "object": { + "id": "eeeeeeee-0009-4000-8000-000000000002", + "revision": 1, + "preset": "circle", + "partCount": 2, + "construction": { + "start": { + "x": 1400, + "y": 400 + }, + "end": { + "x": 1520, + "y": 400 + }, + "mode": 1 + }, + "style": { + "stroke": true, + "fill": true, + "strokeColor": { + "fallback": 1989375 + }, + "fillColor": { + "fallback": 14477567 + }, + "strokeOpacity": 1, + "fillOpacity": 1, + "width": 4, + "linePattern": 0 + }, + "aux": 1 + } + }, + { + "type": 5, + "contentId": 13, + "undoId": 1, + "shapeType": 5, + "geometry": { + "centerX": 1400, + "centerY": 400, + "radius": 4 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 1989375 + }, + "opacity": 1 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000002", + "partIndex": 1 + } + }, + { + "type": 5, + "contentId": 14, + "undoId": 2, + "shapeType": 6, + "geometry": { + "points": [ + { + "x": 1450, + "y": 700 + }, + { + "x": 1464, + "y": 740.5 + }, + { + "x": 1507, + "y": 741.5 + }, + { + "x": 1473, + "y": 767.5 + }, + { + "x": 1485, + "y": 808.5 + }, + { + "x": 1450, + "y": 784 + }, + { + "x": 1415, + "y": 808.5 + }, + { + "x": 1427, + "y": 767.5 + }, + { + "x": 1393, + "y": 741.5 + }, + { + "x": 1436, + "y": 740.5 + } + ] + }, + "stroke": { + "color": { + "fallback": 14037892 + }, + "opacity": 1, + "width": 3 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 16769162 + }, + "opacity": 1 + }, + "object": { + "id": "eeeeeeee-0009-4000-8000-000000000003", + "revision": 1, + "preset": "x-example-unknown", + "partCount": 2, + "construction": { + "start": { + "x": 1390, + "y": 700 + }, + "end": { + "x": 1510, + "y": 810 + }, + "sides": 5, + "spikes": 0.4 + }, + "style": { + "stroke": true, + "fill": true, + "strokeColor": { + "fallback": 14037892 + }, + "fillColor": { + "fallback": 16769162 + }, + "width": 3 + } + } + }, + { + "type": 5, + "contentId": 15, + "undoId": 2, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 1380, + "y": 840 + }, + { + "x": 1520, + "y": 840 + } + ] + }, + "stroke": { + "color": { + "fallback": 14037892 + }, + "opacity": 1, + "width": 3 + }, + "object": { + "ref": "eeeeeeee-0009-4000-8000-000000000003", + "partIndex": 1 + } + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030392d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38086a474797065cd0002a87061676547756964d92463636363636363632d303030392d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000087a474797065cd0005a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca440ccf15a179ca442aaa1e82a178ca445b571da179ca441df3aba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637488a26964d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a87265766973696f6ecf0000000000000003a6707265736574a66375626f6964a970617274436f756e74ce0000000ca97472616e73666f726d96ca3fc00000ca00000000ca00000000ca3fc00000ca442f0000ca441b0000ac636f6e737472756374696f6e84a5737461727482a178ca00000000a179ca00000000a6686569676874cac3200000a86261736553697a6582a178ca43480000a179ca43200000ac62617365526f746174696f6eca3f000000a57374796c6586a67374726f6b65c3a466696c6cc2ab7374726f6b65436f6c6f7281a866616c6c6261636bce001f2937ad7374726f6b654f706163697479ca3f800000a57769647468ca40000000ab6c696e655061747465726ed200000000a3617578ce0000000087a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca440ccf15a179ca43dd543b82a178ca445b571da179ca43c3e755a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000187a474797065cd0005a9636f6e74656e744964ce00000002a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca440ccf15a179ca442aaa1e82a178ca440ccf15a179ca43dd543ba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000287a474797065cd0005a9636f6e74656e744964ce00000003a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca445b571da179ca441df3ab82a178ca445130eba179ca440b55e2a67374726f6b6584a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a964617368417272617992ca41400000ca41900000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000387a474797065cd0005a9636f6e74656e744964ce00000004a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca445b571da179ca43c3e75582a178ca445130eba179ca439eabc5a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000487a474797065cd0005a9636f6e74656e744964ce00000005a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca445b571da179ca441df3ab82a178ca445b571da179ca43c3e755a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000587a474797065cd0005a9636f6e74656e744964ce00000006a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca445130eba179ca440b55e282a178ca4402a8e3a179ca44180c55a67374726f6b6584a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a964617368417272617992ca41400000ca41900000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000687a474797065cd0005a9636f6e74656e744964ce00000007a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca445130eba179ca439eabc582a178ca4402a8e3a179ca43b818aba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000787a474797065cd0005a9636f6e74656e744964ce00000008a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca445130eba179ca440b55e282a178ca445130eba179ca439eabc5a67374726f6b6584a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a964617368417272617992ca41400000ca41900000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000887a474797065cd0005a9636f6e74656e744964ce00000009a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca4402a8e3a179ca44180c5582a178ca440ccf15a179ca442aaa1ea67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000987a474797065cd0005a9636f6e74656e744964ce0000000aa6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca4402a8e3a179ca43b818ab82a178ca440ccf15a179ca43dd543ba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000a87a474797065cd0005a9636f6e74656e744964ce0000000ba6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca4402a8e3a179ca44180c5582a178ca4402a8e3a179ca43b818aba67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000b88a474797065cd0005a9636f6e74656e744964ce0000000ca6756e646f4964ce00000001a9736861706554797065d200000005a867656f6d6574727983a763656e74657258ca44af0000a763656e74657259ca43c80000a6726164697573ca42f00000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a57769647468ca40800000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce00dce8ffa76f706163697479ca3f800000a66f626a65637487a26964d92465656565656565652d303030392d343030302d383030302d303030303030303030303032a87265766973696f6ecf0000000000000001a6707265736574a6636972636c65a970617274436f756e74ce00000002ac636f6e737472756374696f6e83a5737461727482a178ca44af0000a179ca43c80000a3656e6482a178ca44be0000a179ca43c80000a46d6f6465d200000001a57374796c6588a67374726f6b65c3a466696c6cc3ab7374726f6b65436f6c6f7281a866616c6c6261636bce001e5affa966696c6c436f6c6f7281a866616c6c6261636bce00dce8ffad7374726f6b654f706163697479ca3f800000ab66696c6c4f706163697479ca3f800000a57769647468ca40800000ab6c696e655061747465726ed200000000a3617578ce0000000187a474797065cd0005a9636f6e74656e744964ce0000000da6756e646f4964ce00000001a9736861706554797065d200000005a867656f6d6574727983a763656e74657258ca44af0000a763656e74657259ca43c80000a6726164697573ca40800000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303032a970617274496e646578ce0000000188a474797065cd0005a9636f6e74656e744964ce0000000ea6756e646f4964ce00000002a9736861706554797065d200000006a867656f6d6574727981a6706f696e74739a82a178ca44b54000a179ca442f000082a178ca44b70000a179ca4439200082a178ca44bc6000a179ca4439600082a178ca44b82000a179ca443fe00082a178ca44b9a000a179ca444a200082a178ca44b54000a179ca4444000082a178ca44b0e000a179ca444a200082a178ca44b26000a179ca443fe00082a178ca44ae2000a179ca4439600082a178ca44b38000a179ca44392000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce00d63384a76f706163697479ca3f800000a57769647468ca40400000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce00ffe08aa76f706163697479ca3f800000a66f626a65637486a26964d92465656565656565652d303030392d343030302d383030302d303030303030303030303033a87265766973696f6ecf0000000000000001a6707265736574b1782d6578616d706c652d756e6b6e6f776ea970617274436f756e74ce00000002ac636f6e737472756374696f6e84a5737461727482a178ca44adc000a179ca442f0000a3656e6482a178ca44bcc000a179ca444a8000a57369646573ce00000005a67370696b6573ca3ecccccda57374796c6585a67374726f6b65c3a466696c6cc3ab7374726f6b65436f6c6f7281a866616c6c6261636bce00d63384a966696c6c436f6c6f7281a866616c6c6261636bce00ffe08aa57769647468ca4040000087a474797065cd0005a9636f6e74656e744964ce0000000fa6756e646f4964ce00000002a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca44ac8000a179ca4452000082a178ca44be0000a179ca44520000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce00d63384a76f706163697479ca3f800000a57769647468ca40400000a66f626a65637482a3726566d92465656565656565652d303030392d343030302d383030302d303030303030303030303033a970617274496e646578ce00000001" + }, + { + "file": "inkeys-erase-clear.uink", + "title": "Inkeys 附加级:Erase Ink、橡皮笔尖与 Clear 区间", + "primaryLevel": "inkeys", + "rules": [ + "INK-11", + "INK-17", + "NIB-2", + "NIB-3", + "SHAPE-18", + "CLEAR-1", + "CLEAR-3", + "CLEAR-4", + "CLEAR-5", + "CLEAR-7", + "CLEAR-9", + "FILE-14", + "COMPAT-4" + ], + "description": "隐式单例,一页,按对象流顺序:A 蓝色横线(undoId 0);矩形(undoId 1);矩形橡皮擦过的轨迹(Erase Ink,nib 为 Rectangle 2:3、Fixed,width 40 即笔尖高度,笔尖 26.67 × 40;cap 写 Butt,矩形笔尖两端就是笔尖的边),竖直穿过 A 与矩形的上下两条边(undoId 2);Clear(undoId 3,独占一组);B 红色横线(undoId 4);C 绿色横线(undoId 5);方形橡皮(nib 为 Rectangle 1:1,笔尖 40 × 40)竖直穿过 B(undoId 6);D 紫色斜线(undoId 7),在橡皮之后画过被擦掉的位置。", + "expected": { + "core": "两条 Erase Ink 都必须跳过,不得画成可见笔迹。按 CLEAR-7 只显示最后一个 Clear 之后的内容:B、C、D 三条笔迹,B 完整无缺口(橡皮失效);Clear 之前的 A 与矩形不显示。做不到时必须提示“此页的显示可能包含已被清空的内容”。", + "basic": "与核心级相同。", + "standard": "与核心级相同;撤回只按 undoId 分组,不理解 Clear 的区间语义。", + "full": "与核心级相同。", + "inkeys": "当前画面为 B、C、D:B 在 x = 450 附近被方形橡皮擦出一段约 40 宽的缺口(方形边长 = width = 40),D 在橡皮之后画出,完整显示。逐组撤回:撤回 D;撤回方形橡皮后 B 恢复完整;撤回 C、B 后画布为空;撤回 Clear 后显示 A 与矩形,它们在 x = 450 附近被矩形橡皮擦出约 26.7 宽的竖直缺口(橡皮高 40、宽 26.7)。" + }, + "expectedObjects": 10, + "size": 1458, + "sha256": "6a8bc79b72b3416ba17b652dfcdb126a391ff896ce674872b683e1671ff8a525", + "objects": [ + [ + 0, + 11, + "ffffffff-000a-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-000a-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 300, + "width": 8 + }, + { + "x": 500, + "y": 0, + "width": 8 + } + ] + }, + { + "type": 5, + "contentId": 1, + "undoId": 1, + "shapeType": 2, + "geometry": { + "centerX": 450, + "centerY": 500, + "width": 400, + "height": 160 + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + } + }, + { + "type": 3, + "contentId": 2, + "undoId": 2, + "inkType": 0, + "color": { + "fallback": 0 + }, + "opacity": 1, + "texture": 0, + "nib": { + "shape": 1, + "aspect": 0.6666667, + "orientation": 0 + }, + "cap": 2, + "points": [ + { + "x": 450, + "y": 240, + "width": 40 + }, + { + "x": 0, + "y": 160, + "width": 40 + }, + { + "x": 0, + "y": 200, + "width": 40 + } + ] + }, + { + "type": 6, + "contentId": 3, + "undoId": 3 + }, + { + "type": 3, + "contentId": 4, + "undoId": 4, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 760, + "width": 8 + }, + { + "x": 500, + "y": 0, + "width": 8 + } + ] + }, + { + "type": 3, + "contentId": 5, + "undoId": 5, + "inkType": 1, + "color": { + "fallback": 2269291 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 900, + "y": 300, + "width": 8 + }, + { + "x": 400, + "y": 0, + "width": 8 + } + ] + }, + { + "type": 3, + "contentId": 6, + "undoId": 6, + "inkType": 0, + "color": { + "fallback": 0 + }, + "opacity": 1, + "texture": 0, + "nib": { + "shape": 1, + "aspect": 1, + "orientation": 0 + }, + "cap": 2, + "points": [ + { + "x": 450, + "y": 700, + "width": 40 + }, + { + "x": 0, + "y": 120, + "width": 40 + } + ] + }, + { + "type": 3, + "contentId": 7, + "undoId": 7, + "inkType": 1, + "color": { + "fallback": 8141549 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 410, + "y": 720, + "width": 6 + }, + { + "x": 80, + "y": 80, + "width": 6 + } + ] + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030612d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38086a474797065cd0002a87061676547756964d92463636363636363632d303030612d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43480000a179ca43960000a57769647468ca4100000083a178ca43fa0000a179ca00000000a57769647468ca4100000086a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a9736861706554797065d200000002a867656f6d6574727984a763656e74657258ca43e10000a763656e74657259ca43fa0000a57769647468ca43c80000a6686569676874ca43200000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca408000008aa474797065cd0003a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a7696e6b54797065d200000000a5636f6c6f7281a866616c6c6261636bce00000000a76f706163697479ca3f800000a774657874757265d200000000a36e696283a57368617065d200000001a6617370656374ca3f2aaaabab6f7269656e746174696f6ed200000000a3636170d200000002a6706f696e74739383a178ca43e10000a179ca43700000a57769647468ca4220000083a178ca00000000a179ca43200000a57769647468ca4220000083a178ca00000000a179ca43480000a57769647468ca4220000083a474797065cd0006a9636f6e74656e744964ce00000003a6756e646f4964ce0000000388a474797065cd0003a9636f6e74656e744964ce00000004a6756e646f4964ce00000004a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43480000a179ca443e0000a57769647468ca4100000083a178ca43fa0000a179ca00000000a57769647468ca4100000088a474797065cd0003a9636f6e74656e744964ce00000005a6756e646f4964ce00000005a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca44610000a179ca43960000a57769647468ca4100000083a178ca43c80000a179ca00000000a57769647468ca410000008aa474797065cd0003a9636f6e74656e744964ce00000006a6756e646f4964ce00000006a7696e6b54797065d200000000a5636f6c6f7281a866616c6c6261636bce00000000a76f706163697479ca3f800000a774657874757265d200000000a36e696283a57368617065d200000001a6617370656374ca3f800000ab6f7269656e746174696f6ed200000000a3636170d200000002a6706f696e74739283a178ca43e10000a179ca442f0000a57769647468ca4220000083a178ca00000000a179ca42f00000a57769647468ca4220000088a474797065cd0003a9636f6e74656e744964ce00000007a6756e646f4964ce00000007a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce007c3aeda76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43cd0000a179ca44340000a57769647468ca40c0000083a178ca42a00000a179ca42a00000a57769647468ca40c00000" + }, + { + "file": "compat-v10.uink", + "title": "1.1 读取器读取 version 10 文件", + "primaryLevel": "core", + "rules": [ + "VER-1", + "VER-3", + "VER-5", + "HDR-2", + "INK-4", + "INK-9", + "INK-10", + "NIB-1", + "SHAPE-7", + "SHAPE-9", + "CANVAS-16" + ], + "description": "Header.version = 10,只使用 1.0 已有的字段,按 1.0 的写法每个 Canvas 都写了 viewport(单位视口)。隐式单例,共 2 页:第 1 页一条 Pen 与一条 Highlighter(1.0 没有 nib 与 cap,按圆形笔尖、圆头绘制,opacity 0.4);第 2 页一条虚线 [12, 6] 带终点箭头的 Line 与一个只填充的 Ellipse。坐标按 Device 像素理解,不做换算。这是 1.0 写入器产生的文件,version 10 不是 1.1 写入器应写的值(见 deviations)。", + "expected": { + "core": "尽力读取,不拒绝(这个样例只用到 1.1 仍然保留的写法,应完整显示)。共 2 页:第 1 页蓝色 Pen 与黄色笔迹(荧光笔按 Pen 绘制,可以不透明);第 2 页一条实线、无箭头的直线与一个绿色填充椭圆。所有坐标按 Device 像素原样使用。", + "basic": "与核心级相同,但荧光笔为圆形笔尖、40% 透明、整条合成一次;直线为 [12, 6] 虚线,终点有开放箭头。", + "standard": "与基础级相同;viewport 为单位视口,显示位置不变。", + "full": "与基础级相同。", + "inkeys": "与基础级相同。" + }, + "expectedObjects": 7, + "deviations": [ + "#0 Header.version: 写入 10,1.1 写入器必须写 11(VER-2)" + ], + "size": 1083, + "sha256": "a54d13386b7010c401cbb184546d5ae20dbe6c9235b3c8f3a9861b5538cf1c8d", + "objects": [ + [ + 0, + 10, + "ffffffff-000b-4000-8000-000000000000", + 1, + 1, + 2, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-000b-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0, + "viewport": { + "x": 0, + "y": 0, + "scale": 1 + } + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 240, + "width": 6 + }, + { + "x": 200, + "y": -20, + "width": 6.5 + }, + { + "x": 200, + "y": 20, + "width": 6 + } + ] + }, + { + "type": 3, + "contentId": 1, + "undoId": 1, + "inkType": 2, + "color": { + "fallback": 16770560 + }, + "opacity": 0.4, + "texture": 0, + "points": [ + { + "x": 200, + "y": 360, + "width": 20 + }, + { + "x": 400, + "y": 0, + "width": 20 + } + ] + }, + { + "type": 2, + "pageGuid": "cccccccc-000b-4000-8000-000000000002", + "pageIndex": 1, + "pageNumber": 2, + "layerIndex": 0, + "layerNumber": 0, + "viewport": { + "x": 0, + "y": 0, + "scale": 1 + } + }, + { + "type": 5, + "contentId": 0, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 200, + "y": 300 + }, + { + "x": 700, + "y": 300 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4, + "dashArray": [ + 12, + 6 + ], + "endMarker": 1 + } + }, + { + "type": 5, + "contentId": 1, + "undoId": 1, + "shapeType": 4, + "geometry": { + "centerX": 1000, + "centerY": 500, + "width": 280, + "height": 160, + "rotation": 0 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 2269291 + }, + "opacity": 1 + } + } + ], + "hex": "97cd0000cd000ad92466666666666666662d303030622d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000002cf000000006b04d38087a474797065cd0002a87061676547756964d92463636363636363632d303030622d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a876696577706f727483a178ca00000000a179ca00000000a57363616c65ca3f80000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43480000a179ca43700000a57769647468ca40c0000083a178ca43480000a179cac1a00000a57769647468ca40d0000083a178ca43480000a179ca41a00000a57769647468ca40c0000088a474797065cd0003a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a7696e6b54797065d200000002a5636f6c6f7281a866616c6c6261636bce00ffe600a76f706163697479ca3ecccccda774657874757265d200000000a6706f696e74739283a178ca43480000a179ca43b40000a57769647468ca41a0000083a178ca43c80000a179ca00000000a57769647468ca41a0000087a474797065cd0002a87061676547756964d92463636363636363632d303030622d343030302d383030302d303030303030303030303032a970616765496e646578ce00000001aa706167654e756d626572ce00000002aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a876696577706f727483a178ca00000000a179ca00000000a57363616c65ca3f80000086a474797065cd0005a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca43480000a179ca4396000082a178ca442f0000a179ca43960000a67374726f6b6585a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a964617368417272617992ca41400000ca40c00000a9656e644d61726b6572d20000000186a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a9736861706554797065d200000004a867656f6d6574727985a763656e74657258ca447a0000a763656e74657259ca43fa0000a57769647468ca438c0000a6686569676874ca43200000a8726f746174696f6eca00000000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000" + }, + { + "file": "fallback-unknown.uink", + "title": "不认识的块、键与枚举值,以及非规范的数值编码", + "primaryLevel": "core", + "rules": [ + "VER-4", + "TYPE-5", + "TYPE-8", + "TYPE-9", + "TYPE-12", + "FILE-18", + "FILE-20", + "HEXT-14", + "CANVAS-9", + "INK-8", + "INK-13", + "INK-14", + "NIB-7", + "SHAPE-20", + "SHAPE-21", + "MEDIA-3", + "MEDIA-6", + "COMPAT-1", + "COMPAT-2", + "COMPAT-3" + ], + "description": "模拟“来自更新版本或其他软件”的文件,故意包含读取器不认识的内容(见 deviations)。Header Extension 有不认识的键 futureRegistry,唯一的 Workspace 的 workspaceType 为保留值 99。Canvas 的 pageIndex 写成 fixint、pageNumber 写成 uint8、viewport 的三个分量写成 float64(都是能无损转换的非规范编码),background.pattern 为 99,另有不认识的键 futurePageField。随后依次为:Type ID 7 的完整块(7 及以上保留给后续版本,1.1 写入器不得写出);inkType 77 的 Ink(点上带不认识的键 pressure,nib.shape 99、orientation 7,cap 99,texture 99(保留值),块上有不认识的键 futureInkField);shapeType 99 的 Shape;contentId 写成 uint8、endMarker 99、lineCap 99、lineJoin 99 的 Line;fillType 99、描边宽度写成 float64 的 Rectangle;fit 99 的图片 Media(资源包不存在);inkType 200(私有值)的 Ink。", + "expected": { + "core": "不拒绝文件,显示 1 页。跳过 Type ID 7 的块(读取器不认识的 Type ID);忽略全部不认识的键(包括点上的 pressure)。inkType 77 的 Ink 按 Pen 画出蓝色曲线(圆形笔尖、width 为直径);shapeType 99 的 Shape 整个跳过,不猜测成其他几何;Line 画出;Rectangle 按 Solid 填充浅黄色(fillType 99),描边宽 4;Media 跳过;inkType 200 的 Ink 按 Pen 画出红色笔迹。非规范编码的数值都能无损转换,照常使用。默认不覆盖原文件,保存时另存为。", + "basic": "与核心级相同;背景为白色、图案按 Blank(pattern 99);inkType 77 的笔迹 nib 与 cap 取值不认识,按圆形笔尖、圆头绘制;Line 终点不画箭头(endMarker 99 按 None),端帽与拐角按 Round。", + "standard": "与基础级相同;Workspace 类型 99 按普通白板加载,不执行宿主绑定;viewport 为单位视口;图片 Media 的资源包不存在,在 (1200, 200) 保留 320×180 的位置并提示资源缺失(fit 99 按 Fill 处理)。", + "full": "与标准级相同;纹理 99 是保留值,不认识,按 0 绘制。", + "inkeys": "与完整级相同。" + }, + "expectedObjects": 10, + "deviations": [ + "#1 HeaderExtension.workspaces[0].workspaceType: 99 是未注册的保留值", + "#1 HeaderExtension.workspaces[0].futureWorkspaceKey: 未注册的键(TYPE-4)", + "#1 HeaderExtension.futureRegistry: 未注册的键(TYPE-4)", + "#2 Canvas.pageIndex: 应为 u32,实际为 fixint", + "#2 Canvas.pageNumber: 应为 u32,实际为 u8", + "#2 Canvas.viewport.x: 应为 f32,实际为 f64", + "#2 Canvas.viewport.y: 应为 f32,实际为 f64", + "#2 Canvas.viewport.scale: 应为 f32,实际为 f64", + "#2 Canvas.background.pattern: 99 是未注册的保留值", + "#2 Canvas.futurePageField: 未注册的键(TYPE-4)", + "#3: Type ID 7 未注册", + "#4 Ink.inkType: 77 是未注册的保留值", + "#4 Ink.texture: 99 是未注册的保留值", + "#4 Ink.points[0].pressure: 未注册的键(TYPE-4)", + "#4 Ink.points[1].pressure: 未注册的键(TYPE-4)", + "#4 Ink.points[2].pressure: 未注册的键(TYPE-4)", + "#4 Ink.nib.shape: 99 是未注册的保留值", + "#4 Ink.nib.orientation: 7 是未注册的保留值", + "#4 Ink.cap: 99 是未注册的保留值", + "#4 Ink.futureInkField: 未注册的键(TYPE-4)", + "#5 Shape.shapeType: 99 是未注册的保留值", + "#5 Shape.geometry.spokes: 未注册的键(TYPE-4)", + "#6 Shape.contentId: 应为 u32,实际为 u8", + "#6 Shape.stroke.lineCap: 99 是未注册的保留值", + "#6 Shape.stroke.lineJoin: 99 是未注册的保留值", + "#6 Shape.stroke.endMarker: 99 是未注册的保留值", + "#7 Shape.stroke.width: 应为 f32,实际为 f64", + "#7 Shape.fill.fillType: 99 是未注册的保留值", + "#8 Media.fit: 99 是未注册的保留值" + ], + "size": 1971, + "sha256": "640aa5a533f2114f69f2ecc8f4ff03c53998d38f444567d38aa7e6f6cbe9e889", + "objects": [ + [ + 0, + 11, + "ffffffff-000c-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 1, + "devices": [ + { + "guid": "dddddddd-000c-4000-8000-000000000001", + "deviceType": 0, + "x": 0, + "y": 0, + "width": 1920, + "height": 1080 + } + ], + "workspaces": [ + { + "guid": "aaaaaaaa-000c-4000-8000-000000000001", + "workspaceType": 99, + "name": "来自未来版本的场景", + "futureWorkspaceKey": "ignored" + } + ], + "futureRegistry": [ + { + "kind": "sensor", + "rate": 120 + } + ] + }, + { + "type": 2, + "workspaceGuid": "aaaaaaaa-000c-4000-8000-000000000001", + "deviceGuid": "dddddddd-000c-4000-8000-000000000001", + "pageGuid": "cccccccc-000c-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0, + "viewport": { + "x": 0, + "y": 0, + "scale": 1 + }, + "background": { + "color": { + "fallback": 16777215 + }, + "pattern": 99 + }, + "futurePageField": "ignored" + }, + { + "type": 7, + "payload": "complete unknown block", + "nested": { + "list": [ + 1, + 2 + ], + "flag": true + } + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 77, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 99, + "points": [ + { + "x": 200, + "y": 300, + "width": 6, + "pressure": 0.3 + }, + { + "x": 120, + "y": -40, + "width": 7, + "pressure": 0.6 + }, + { + "x": 120, + "y": 40, + "width": 8, + "pressure": 0.9 + } + ], + "nib": { + "shape": 99, + "aspect": 0.5, + "orientation": 7 + }, + "cap": 99, + "futureInkField": true + }, + { + "type": 5, + "contentId": 1, + "undoId": 1, + "shapeType": 99, + "geometry": { + "centerX": 700, + "centerY": 300, + "radius": 80, + "spokes": 6 + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + } + }, + { + "type": 5, + "contentId": 2, + "undoId": 2, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 200, + "y": 500 + }, + { + "x": 600, + "y": 500 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 6, + "lineCap": 99, + "lineJoin": 99, + "startMarker": 0, + "endMarker": 99 + } + }, + { + "type": 5, + "contentId": 3, + "undoId": 3, + "shapeType": 2, + "geometry": { + "centerX": 900, + "centerY": 650, + "width": 240, + "height": 140 + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "fill": { + "fillType": 99, + "color": { + "fallback": 16769162 + }, + "opacity": 1 + } + }, + { + "type": 4, + "contentId": 4, + "undoId": 4, + "path": "images/future.png", + "mimeType": "image/png", + "width": 320, + "height": 180, + "transform": [ + 1, + 0, + 0, + 1, + 1200, + 200 + ], + "fit": 99 + }, + { + "type": 3, + "contentId": 5, + "undoId": 5, + "inkType": 200, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 1200, + "y": 600, + "width": 6 + }, + { + "x": 200, + "y": 40, + "width": 6 + }, + { + "x": 200, + "y": -40, + "width": 6 + } + ] + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030632d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38084a474797065cd0001a7646576696365739186a467756964d92464646464646464642d303030632d343030302d383030302d303030303030303030303031aa64657669636554797065d200000000a178d200000000a179d200000000a57769647468ce00000780a6686569676874ce00000438aa776f726b7370616365739184a467756964d92461616161616161612d303030632d343030302d383030302d303030303030303030303031ad776f726b737061636554797065d200000063a46e616d65bbe69da5e887aae69caae69da5e78988e69cace79a84e59cbae699afb2667574757265576f726b73706163654b6579a769676e6f726564ae66757475726552656769737472799182a46b696e64a673656e736f72a472617465cd00788ba474797065cd0002ad776f726b737061636547756964d92461616161616161612d303030632d343030302d383030302d303030303030303030303031aa64657669636547756964d92464646464646464642d303030632d343030302d383030302d303030303030303030303031a87061676547756964d92463636363636363632d303030632d343030302d383030302d303030303030303030303031a970616765496e64657800aa706167654e756d626572cc01aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000a876696577706f727483a178cb0000000000000000a179cb0000000000000000a57363616c65cb3ff0000000000000aa6261636b67726f756e6482a5636f6c6f7281a866616c6c6261636bce00ffffffa77061747465726ed200000063af667574757265506167654669656c64a769676e6f72656483a474797065cd0007a77061796c6f6164b6636f6d706c65746520756e6b6e6f776e20626c6f636ba66e657374656482a46c69737492cc01cc02a4666c6167c38ba474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d20000004da5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000063a6706f696e74739384a178ca43480000a179ca43960000a57769647468ca40c00000a87072657373757265ca3e99999a84a178ca42f00000a179cac2200000a57769647468ca40e00000a87072657373757265ca3f19999a84a178ca42f00000a179ca42200000a57769647468ca41000000a87072657373757265ca3f666666a36e696283a57368617065d200000063a6617370656374ca3f000000ab6f7269656e746174696f6ed200000007a3636170d200000063ae667574757265496e6b4669656c64c386a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a9736861706554797065d200000063a867656f6d6574727984a763656e74657258ca442f0000a763656e74657259ca43960000a6726164697573ca42a00000a673706f6b6573ce00000006a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca4080000086a474797065cd0005a9636f6e74656e744964cc02a6756e646f4964ce00000002a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca43480000a179ca43fa000082a178ca44160000a179ca43fa0000a67374726f6b6587a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40c00000a76c696e65436170d200000063a86c696e654a6f696ed200000063ab73746172744d61726b6572d200000000a9656e644d61726b6572d20000006387a474797065cd0005a9636f6e74656e744964ce00000003a6756e646f4964ce00000003a9736861706554797065d200000002a867656f6d6574727984a763656e74657258ca44610000a763656e74657259ca44228000a57769647468ca43700000a6686569676874ca430c0000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468cb4010000000000000a466696c6c83a866696c6c54797065d200000063a5636f6c6f7281a866616c6c6261636bce00ffe08aa76f706163697479ca3f80000089a474797065cd0004a9636f6e74656e744964ce00000004a6756e646f4964ce00000004a470617468b1696d616765732f6675747572652e706e67a86d696d6554797065a9696d6167652f706e67a57769647468ca43a00000a6686569676874ca43340000a97472616e73666f726d96ca3f800000ca00000000ca00000000ca3f800000ca44960000ca43480000a3666974d20000006388a474797065cd0003a9636f6e74656e744964ce00000005a6756e646f4964ce00000005a7696e6b54797065d2000000c8a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca44960000a179ca44160000a57769647468ca40c0000083a178ca43480000a179ca42200000a57769647468ca40c0000083a178ca43480000a179cac2200000a57769647468ca40c00000" + }, + { + "file": "truncated-tail.uink", + "title": "最后一个对象不完整时的恢复", + "primaryLevel": "core", + "rules": [ + "FILE-16", + "SAVE-6", + "SAVE-22", + "SAVE-23", + "COMPAT-2" + ], + "description": "隐式单例,一页,前两条 Pen 笔迹完整;第三条 Ink 在写入过程中崩溃,文件在它的 points 数组中间结束(被截掉最后 20 字节)。validPrefixBytes 是第二条笔迹的结束位置,也是再次追加前应截断到的安全位置。", + "expected": { + "core": "保留前 4 个完整对象,丢弃不完整的第三条 Ink:页面显示蓝色与绿色两条笔迹。不报告文件损坏而拒绝打开,也不自动修改源文件。准备再次追加时,先把文件截断到 validPrefixBytes,新内容的 contentId 从 2、undoId 从 2 开始。", + "basic": "与核心级相同。", + "standard": "与核心级相同。", + "full": "与核心级相同。", + "inkeys": "与核心级相同。" + }, + "expectedObjects": 4, + "validPrefixBytes": 553, + "size": 741, + "sha256": "ba009c2a6e66598c5a37f60645e2c3d4f7f978a313909fb4f1cb8165f49c479b", + "objects": [ + [ + 0, + 11, + "ffffffff-000d-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-000d-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 300, + "width": 6 + }, + { + "x": 200, + "y": -20, + "width": 6 + }, + { + "x": 200, + "y": 20, + "width": 6 + } + ] + }, + { + "type": 3, + "contentId": 1, + "undoId": 1, + "inkType": 1, + "color": { + "fallback": 2269291 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 400, + "width": 6 + }, + { + "x": 200, + "y": -20, + "width": 6 + }, + { + "x": 200, + "y": 20, + "width": 6 + } + ] + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030642d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38086a474797065cd0002a87061676547756964d92463636363636363632d303030642d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43480000a179ca43960000a57769647468ca40c0000083a178ca43480000a179cac1a00000a57769647468ca40c0000083a178ca43480000a179ca41a00000a57769647468ca40c0000088a474797065cd0003a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43480000a179ca43c80000a57769647468ca40c0000083a178ca43480000a179cac1a00000a57769647468ca40c0000083a178ca43480000a179ca41a00000a57769647468ca40c0000088a474797065cd0003a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739483a178ca43480000a179ca43fa0000a57769647468ca40c0000083a178ca43480000a179cac1a00000a57769647468ca40c0000083a178ca43480000a179ca41a00000a57769647468ca40c0000083a178ca4348" + }, + { + "file": "corrupt-middle.uink", + "title": "中间对象损坏:保留之前的内容并停止读取", + "primaryLevel": "core", + "rules": [ + "FILE-17", + "FILE-24", + "SAVE-21", + "SAVE-22", + "SAVE-24", + "HDR-5", + "COMPAT-2" + ], + "description": "隐式单例,原本是 2 页的有效文件(Header 的 pageNum 为 2):第 1 页有蓝、红、绿三条笔迹,第 2 页有一条紫色笔迹。第 1 页的第二条笔迹(红色)的首字节被改成 0xC1(MessagePack 中永不使用的字节),其余字节原样保留,所以紧随其后仍有看起来完整的 Map 与对象。validPrefixBytes 是损坏对象的起点;bytesAfterCorruption 是之后被放弃的字节数。", + "expected": { + "core": "只保留损坏位置之前的 3 个完整对象:显示 1 页,只有蓝色笔迹。红色笔迹、绿色笔迹与第 2 页都不显示;读取器不得逐字节向后搜索下一个对象,也不得因为 Header 的 pageNum 为 2 而补出空白页。应提示文件已损坏、部分内容无法读取;恢复结果只用于显示,不自动写回源文件。再次保存时必须完整保存(或另存为),不得截断到 validPrefixBytes 后直接追加。", + "basic": "与核心级相同。", + "standard": "与核心级相同。", + "full": "与核心级相同。", + "inkeys": "与核心级相同。" + }, + "expectedObjects": 3, + "validPrefixBytes": 371, + "bytesAfterCorruption": 640, + "size": 1011, + "sha256": "b19b6842606cc49c3a6268c0559a1c1fdd4cd67d96f0fbe586a6506217227295", + "objects": [ + [ + 0, + 11, + "ffffffff-000e-4000-8000-000000000000", + 1, + 1, + 2, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-000e-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 300, + "width": 6 + }, + { + "x": 200, + "y": -20, + "width": 6 + }, + { + "x": 200, + "y": 20, + "width": 6 + } + ] + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303030652d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000002cf000000006b04d38086a474797065cd0002a87061676547756964d92463636363636363632d303030652d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43480000a179ca43960000a57769647468ca40c0000083a178ca43480000a179cac1a00000a57769647468ca40c0000083a178ca43480000a179ca41a00000a57769647468ca40c00000c1a474797065cd0003a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43480000a179ca43c80000a57769647468ca40c0000083a178ca43480000a179cac1a00000a57769647468ca40c0000083a178ca43480000a179ca41a00000a57769647468ca40c0000088a474797065cd0003a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce0022a06ba76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43480000a179ca43fa0000a57769647468ca40c0000083a178ca43480000a179cac1a00000a57769647468ca40c0000083a178ca43480000a179ca41a00000a57769647468ca40c0000086a474797065cd0002a87061676547756964d92463636363636363632d303030652d343030302d383030302d303030303030303030303032a970616765496e646578ce00000001aa706167654e756d626572ce00000002aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000088a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce007c3aeda76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739283a178ca43960000a179ca43960000a57769647468ca40c0000083a178ca43c80000a179ca43480000a57769647468ca40c00000" + }, + { + "file": "future-minor.uink", + "title": "来自更高次版本的文件(version 12)", + "primaryLevel": "core", + "rules": [ + "VER-1", + "VER-3", + "VER-4", + "HDR-2", + "TYPE-8", + "TYPE-9", + "TYPE-11", + "TYPE-12", + "FILE-18", + "COMPAT-1", + "COMPAT-3" + ], + "description": "模拟 UInk 1.2 写入器产生的文件:Header.version = 12(同一主版本、更高次版本),隐式单例,一页。Canvas、第一条 Ink 与 Rectangle 上各有一个 1.1 未注册的键(futureLayout、futureStyle、futureEffect);两条 Ink 之间有一个 Type ID 9 的完整块(1.1 未注册)。其余内容都是 1.1 已有的写法。对 1.1 生成脚本而言,version 12、未注册的键与 Type ID 都是故意的偏离(见 deviations)。未按勘误更新的 1.0 读取器只接受 version 10,会拒绝这个文件;已按勘误更新的 1.0 读取器与 1.1 读取器一样尽力读取。", + "expected": { + "core": "接受 version 12(在 10–19 之间),尽力读取,不拒绝文件;可以提示“文件来自更新的版本,部分内容可能无法显示”。显示 1 页:蓝色笔迹、矩形(描边 + 浅黄填充)与红色笔迹。跳过 Type ID 9 的块,忽略三个不认识的键,它们不改变已知字段的含义。文件含有读取器不认识的内容,保存时默认另存为,用户确认后才可以覆盖。", + "basic": "与核心级相同。", + "standard": "与核心级相同。", + "full": "与核心级相同。", + "inkeys": "与核心级相同。" + }, + "expectedObjects": 6, + "deviations": [ + "#0 Header.version: 写入 12,1.1 写入器必须写 11(VER-2)", + "#1 Canvas.futureLayout: 未注册的键(TYPE-4)", + "#2 Ink.futureStyle: 未注册的键(TYPE-4)", + "#3: Type ID 9 未注册", + "#4 Shape.futureEffect: 未注册的键(TYPE-4)" + ], + "size": 904, + "sha256": "da8d84e72783f482b3b74eec1235d7bd230910c664faf21a5639e6838b85eaf1", + "objects": [ + [ + 0, + 12, + "ffffffff-000f-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-000f-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0, + "futureLayout": { + "mode": "infinite", + "gridSize": 40 + } + }, + { + "type": 3, + "contentId": 0, + "undoId": 0, + "inkType": 1, + "color": { + "fallback": 1989375 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 200, + "y": 300, + "width": 6 + }, + { + "x": 200, + "y": -40, + "width": 7 + }, + { + "x": 200, + "y": 40, + "width": 6 + } + ], + "futureStyle": { + "glow": 0.5 + } + }, + { + "type": 9, + "text": "来自 1.2 的新块", + "x": 800, + "y": 300 + }, + { + "type": 5, + "contentId": 1, + "undoId": 1, + "shapeType": 2, + "geometry": { + "centerX": 400, + "centerY": 520, + "width": 300, + "height": 160 + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 16769162 + }, + "opacity": 1 + }, + "futureEffect": "shadow" + }, + { + "type": 3, + "contentId": 2, + "undoId": 2, + "inkType": 1, + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "texture": 0, + "points": [ + { + "x": 800, + "y": 520, + "width": 6 + }, + { + "x": 200, + "y": -20, + "width": 6 + }, + { + "x": 200, + "y": 40, + "width": 6 + } + ] + } + ], + "hex": "97cd0000cd000cd92466666666666666662d303030662d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38087a474797065cd0002a87061676547756964d92463636363636363632d303030662d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce00000000ac6675747572654c61796f757482a46d6f6465a8696e66696e697465a86772696453697a65ca4220000089a474797065cd0003a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce001e5affa76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca43480000a179ca43960000a57769647468ca40c0000083a178ca43480000a179cac2200000a57769647468ca40e0000083a178ca43480000a179ca42200000a57769647468ca40c00000ab6675747572655374796c6581a4676c6f77ca3f00000084a474797065cd0009a474657874b4e69da5e887aa20312e3220e79a84e696b0e59d97a178ca44480000a179ca4396000088a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000001a9736861706554797065d200000002a867656f6d6574727984a763656e74657258ca43c80000a763656e74657259ca44020000a57769647468ca43960000a6686569676874ca43200000a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce00ffe08aa76f706163697479ca3f800000ac667574757265456666656374a6736861646f7788a474797065cd0003a9636f6e74656e744964ce00000002a6756e646f4964ce00000002a7696e6b54797065d200000001a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a774657874757265d200000000a6706f696e74739383a178ca44480000a179ca44020000a57769647468ca40c0000083a178ca43480000a179cac1a00000a57769647468ca40c0000083a178ca43480000a179ca42200000a57769647468ca40c00000" + }, + { + "file": "core-shape-curves.uink", + "title": "曲线与自由图形:双曲线与心形", + "primaryLevel": "core", + "rules": [ + "SHAPE-1", + "SHAPE-2", + "SHAPE-4", + "SHAPE-7", + "SHAPE-11", + "SHAPE-13", + "SHAPE-14", + "SHAPE-24", + "SHAPE-25" + ], + "description": "隐式单例,一页。UInk 不保存曲线方程,曲线都写成按顺序采样的点,折线与原曲线的最大距离不超过 0.25(SHAPE-24)。对象 1 是双曲线 x²/120² − y²/90² = 1(中心 (760, 540),参数 t ∈ [−1.9, 1.9]):两支不相连,各写成一个 Polyline(左支 29 个点、右支 29 个点,自适应采样,顶点附近更密);两条渐近线 y − 540 = ±0.75 (x − 760) 写成 [12, 8] 灰色虚线 Line;4 个部件用图形对象层组合,不写 preset(SHAPE-25),共享 undoId 0。随后是一个闭合的心形,写成 94 个点的 Polygon,红色描边、浅红填充(undoId 1)。", + "expected": { + "core": "1 页。左右两支黑色双曲线,顶点在 (640, 540) 与 (880, 540),向上下张开,看不出折线的棱角;两条渐近线画成灰色实线(核心级可以不画虚线),从左上到右下、从左下到右上交叉于 (760, 540);右侧一个红色描边、浅红填充的心形。", + "basic": "与核心级相同,但两条渐近线是 [12, 8] 的虚线。", + "standard": "与基础级相同;双曲线的两支与两条渐近线作为一个对象整体选择、移动、删除;心形是独立的 Shape。", + "full": "与标准级相同;对象没有 preset,按对象层整体编辑,不能修改曲线参数。", + "inkeys": "与完整级相同。" + }, + "expectedObjects": 7, + "size": 3518, + "sha256": "cecfef2f1740c111aef6c8a0e034eb88657535afcd0a688182a61e6ee4b3958f", + "objects": [ + [ + 0, + 11, + "ffffffff-0016-4000-8000-000000000000", + 1, + 1, + 1, + 1795478400 + ], + { + "type": 2, + "pageGuid": "cccccccc-0016-4000-8000-000000000001", + "pageIndex": 0, + "pageNumber": 1, + "layerIndex": 0, + "layerNumber": 0 + }, + { + "type": 5, + "contentId": 0, + "undoId": 0, + "shapeType": 1, + "geometry": { + "points": [ + { + "x": 349.87, + "y": 834.13 + }, + { + "x": 432.27, + "y": 768.73 + }, + { + "x": 496.1, + "y": 716.28 + }, + { + "x": 522.21, + "y": 693.97 + }, + { + "x": 544.97, + "y": 673.83 + }, + { + "x": 564.69, + "y": 655.57 + }, + { + "x": 581.65, + "y": 638.95 + }, + { + "x": 596.1, + "y": 623.73 + }, + { + "x": 608.23, + "y": 609.69 + }, + { + "x": 618.22, + "y": 596.63 + }, + { + "x": 626.21, + "y": 584.38 + }, + { + "x": 632.3, + "y": 572.75 + }, + { + "x": 636.6, + "y": 561.58 + }, + { + "x": 639.15, + "y": 550.71 + }, + { + "x": 640, + "y": 540 + }, + { + "x": 639.15, + "y": 529.29 + }, + { + "x": 636.6, + "y": 518.42 + }, + { + "x": 632.3, + "y": 507.25 + }, + { + "x": 626.21, + "y": 495.62 + }, + { + "x": 618.22, + "y": 483.37 + }, + { + "x": 608.23, + "y": 470.31 + }, + { + "x": 596.1, + "y": 456.27 + }, + { + "x": 581.65, + "y": 441.05 + }, + { + "x": 564.69, + "y": 424.43 + }, + { + "x": 544.97, + "y": 406.17 + }, + { + "x": 522.21, + "y": 386.03 + }, + { + "x": 496.1, + "y": 363.72 + }, + { + "x": 432.27, + "y": 311.27 + }, + { + "x": 349.87, + "y": 245.87 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "object": { + "id": "eeeeeeee-0016-4000-8000-000000000001", + "revision": 1, + "partCount": 4 + } + }, + { + "type": 5, + "contentId": 1, + "undoId": 0, + "shapeType": 1, + "geometry": { + "points": [ + { + "x": 1170.13, + "y": 834.13 + }, + { + "x": 1087.73, + "y": 768.73 + }, + { + "x": 1023.9, + "y": 716.28 + }, + { + "x": 997.79, + "y": 693.97 + }, + { + "x": 975.03, + "y": 673.83 + }, + { + "x": 955.31, + "y": 655.57 + }, + { + "x": 938.35, + "y": 638.95 + }, + { + "x": 923.9, + "y": 623.73 + }, + { + "x": 911.77, + "y": 609.69 + }, + { + "x": 901.78, + "y": 596.63 + }, + { + "x": 893.79, + "y": 584.38 + }, + { + "x": 887.7, + "y": 572.75 + }, + { + "x": 883.4, + "y": 561.58 + }, + { + "x": 880.85, + "y": 550.71 + }, + { + "x": 880, + "y": 540 + }, + { + "x": 880.85, + "y": 529.29 + }, + { + "x": 883.4, + "y": 518.42 + }, + { + "x": 887.7, + "y": 507.25 + }, + { + "x": 893.79, + "y": 495.62 + }, + { + "x": 901.78, + "y": 483.37 + }, + { + "x": 911.77, + "y": 470.31 + }, + { + "x": 923.9, + "y": 456.27 + }, + { + "x": 938.35, + "y": 441.05 + }, + { + "x": 955.31, + "y": 424.43 + }, + { + "x": 975.03, + "y": 406.17 + }, + { + "x": 997.79, + "y": 386.03 + }, + { + "x": 1023.9, + "y": 363.72 + }, + { + "x": 1087.73, + "y": 311.27 + }, + { + "x": 1170.13, + "y": 245.87 + } + ] + }, + "stroke": { + "color": { + "fallback": 2042167 + }, + "opacity": 1, + "width": 4 + }, + "object": { + "ref": "eeeeeeee-0016-4000-8000-000000000001", + "partIndex": 1 + } + }, + { + "type": 5, + "contentId": 2, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 349.87, + "y": 847.6 + }, + { + "x": 1170.13, + "y": 232.4 + } + ] + }, + "stroke": { + "color": { + "fallback": 9080728 + }, + "opacity": 1, + "width": 2, + "dashArray": [ + 12, + 8 + ] + }, + "object": { + "ref": "eeeeeeee-0016-4000-8000-000000000001", + "partIndex": 2 + } + }, + { + "type": 5, + "contentId": 3, + "undoId": 0, + "shapeType": 0, + "geometry": { + "points": [ + { + "x": 349.87, + "y": 232.4 + }, + { + "x": 1170.13, + "y": 847.6 + } + ] + }, + "stroke": { + "color": { + "fallback": 9080728 + }, + "opacity": 1, + "width": 2, + "dashArray": [ + 12, + 8 + ] + }, + "object": { + "ref": "eeeeeeee-0016-4000-8000-000000000001", + "partIndex": 3 + } + }, + { + "type": 5, + "contentId": 4, + "undoId": 1, + "shapeType": 6, + "geometry": { + "points": [ + { + "x": 1500, + "y": 465 + }, + { + "x": 1501.31, + "y": 456.63 + }, + { + "x": 1504.31, + "y": 447.05 + }, + { + "x": 1506.73, + "y": 441.33 + }, + { + "x": 1509.86, + "y": 435.2 + }, + { + "x": 1513.76, + "y": 428.82 + }, + { + "x": 1518.44, + "y": 422.39 + }, + { + "x": 1523.91, + "y": 416.08 + }, + { + "x": 1530.18, + "y": 410.08 + }, + { + "x": 1537.2, + "y": 404.55 + }, + { + "x": 1544.94, + "y": 399.66 + }, + { + "x": 1553.3, + "y": 395.54 + }, + { + "x": 1562.23, + "y": 392.33 + }, + { + "x": 1571.59, + "y": 390.12 + }, + { + "x": 1581.3, + "y": 388.99 + }, + { + "x": 1591.2, + "y": 388.99 + }, + { + "x": 1601.17, + "y": 390.15 + }, + { + "x": 1611.06, + "y": 392.47 + }, + { + "x": 1620.73, + "y": 395.93 + }, + { + "x": 1630.02, + "y": 400.48 + }, + { + "x": 1638.79, + "y": 406.06 + }, + { + "x": 1646.9, + "y": 412.59 + }, + { + "x": 1654.23, + "y": 419.96 + }, + { + "x": 1660.65, + "y": 428.09 + }, + { + "x": 1666.05, + "y": 436.84 + }, + { + "x": 1670.35, + "y": 446.13 + }, + { + "x": 1673.47, + "y": 455.82 + }, + { + "x": 1675.36, + "y": 465.81 + }, + { + "x": 1676, + "y": 476 + }, + { + "x": 1675.36, + "y": 486.3 + }, + { + "x": 1673.47, + "y": 496.62 + }, + { + "x": 1670.35, + "y": 506.9 + }, + { + "x": 1666.05, + "y": 517.09 + }, + { + "x": 1660.65, + "y": 527.13 + }, + { + "x": 1654.23, + "y": 537 + }, + { + "x": 1646.9, + "y": 546.68 + }, + { + "x": 1638.79, + "y": 556.16 + }, + { + "x": 1630.02, + "y": 565.44 + }, + { + "x": 1620.73, + "y": 574.54 + }, + { + "x": 1601.17, + "y": 592.2 + }, + { + "x": 1562.23, + "y": 625.67 + }, + { + "x": 1544.94, + "y": 641.48 + }, + { + "x": 1530.18, + "y": 656.46 + }, + { + "x": 1518.44, + "y": 670.31 + }, + { + "x": 1509.86, + "y": 682.59 + }, + { + "x": 1504.31, + "y": 692.83 + }, + { + "x": 1501.31, + "y": 700.55 + }, + { + "x": 1500, + "y": 707 + }, + { + "x": 1498.69, + "y": 700.55 + }, + { + "x": 1495.69, + "y": 692.83 + }, + { + "x": 1490.14, + "y": 682.59 + }, + { + "x": 1481.56, + "y": 670.31 + }, + { + "x": 1469.82, + "y": 656.46 + }, + { + "x": 1455.06, + "y": 641.48 + }, + { + "x": 1437.77, + "y": 625.67 + }, + { + "x": 1398.83, + "y": 592.2 + }, + { + "x": 1379.27, + "y": 574.54 + }, + { + "x": 1369.98, + "y": 565.44 + }, + { + "x": 1361.21, + "y": 556.16 + }, + { + "x": 1353.1, + "y": 546.68 + }, + { + "x": 1345.77, + "y": 537 + }, + { + "x": 1339.35, + "y": 527.13 + }, + { + "x": 1333.95, + "y": 517.09 + }, + { + "x": 1329.65, + "y": 506.9 + }, + { + "x": 1326.53, + "y": 496.62 + }, + { + "x": 1324.64, + "y": 486.3 + }, + { + "x": 1324, + "y": 476 + }, + { + "x": 1324.64, + "y": 465.81 + }, + { + "x": 1326.53, + "y": 455.82 + }, + { + "x": 1329.65, + "y": 446.13 + }, + { + "x": 1333.95, + "y": 436.84 + }, + { + "x": 1339.35, + "y": 428.09 + }, + { + "x": 1345.77, + "y": 419.96 + }, + { + "x": 1353.1, + "y": 412.59 + }, + { + "x": 1361.21, + "y": 406.06 + }, + { + "x": 1369.98, + "y": 400.48 + }, + { + "x": 1379.27, + "y": 395.93 + }, + { + "x": 1388.94, + "y": 392.47 + }, + { + "x": 1398.83, + "y": 390.15 + }, + { + "x": 1408.8, + "y": 388.99 + }, + { + "x": 1418.7, + "y": 388.99 + }, + { + "x": 1428.41, + "y": 390.12 + }, + { + "x": 1437.77, + "y": 392.33 + }, + { + "x": 1446.7, + "y": 395.54 + }, + { + "x": 1455.06, + "y": 399.66 + }, + { + "x": 1462.8, + "y": 404.55 + }, + { + "x": 1469.82, + "y": 410.08 + }, + { + "x": 1476.09, + "y": 416.08 + }, + { + "x": 1481.56, + "y": 422.39 + }, + { + "x": 1486.24, + "y": 428.82 + }, + { + "x": 1490.14, + "y": 435.2 + }, + { + "x": 1493.27, + "y": 441.33 + }, + { + "x": 1495.69, + "y": 447.05 + }, + { + "x": 1498.69, + "y": 456.63 + } + ] + }, + "stroke": { + "color": { + "fallback": 15026253 + }, + "opacity": 1, + "width": 3 + }, + "fill": { + "fillType": 0, + "color": { + "fallback": 16766680 + }, + "opacity": 1 + } + } + ], + "hex": "97cd0000cd000bd92466666666666666662d303031362d343030302d383030302d303030303030303030303030ce00000001ce00000001ce00000001cf000000006b04d38086a474797065cd0002a87061676547756964d92463636363636363632d303031362d343030302d383030302d303030303030303030303031a970616765496e646578ce00000000aa706167654e756d626572ce00000001aa6c61796572496e646578ce00000000ab6c617965724e756d626572ce0000000087a474797065cd0005a9636f6e74656e744964ce00000000a6756e646f4964ce00000000a9736861706554797065d200000001a867656f6d6574727981a6706f696e7473dc001d82a178ca43aeef5ca179ca4450885282a178ca43d8228fa179ca44402eb882a178ca43f80ccda179ca443311ec82a178ca44028d71a179ca442d7e1482a178ca44083e14a179ca4428751f82a178ca440d2c29a179ca4423e47b82a178ca4411699aa179ca441fbccd82a178ca44150666a179ca441beeb882a178ca44180eb8a179ca44186c2982a178ca441a8e14a179ca4415285282a178ca441c8d71a179ca4412185282a178ca441e1333a179ca440f300082a178ca441f2666a179ca440c651f82a178ca441fc99aa179ca4409ad7182a178ca44200000a179ca4407000082a178ca441fc99aa179ca4404528f82a178ca441f2666a179ca44019ae182a178ca441e1333a179ca43fda00082a178ca441c8d71a179ca43f7cf5c82a178ca441a8e14a179ca43f1af5c82a178ca44180eb8a179ca43eb27ae82a178ca44150666a179ca43e4228f82a178ca4411699aa179ca43dc866682a178ca440d2c29a179ca43d4370a82a178ca44083e14a179ca43cb15c382a178ca44028d71a179ca43c103d782a178ca43f80ccda179ca43b5dc2982a178ca43d8228fa179ca439ba28f82a178ca43aeef5ca179ca4375deb8a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a66f626a65637483a26964d92465656565656565652d303031362d343030302d383030302d303030303030303030303031a87265766973696f6ecf0000000000000001a970617274436f756e74ce0000000487a474797065cd0005a9636f6e74656e744964ce00000001a6756e646f4964ce00000000a9736861706554797065d200000001a867656f6d6574727981a6706f696e7473dc001d82a178ca44924429a179ca4450885282a178ca4487f75ca179ca44402eb882a178ca447ff99aa179ca443311ec82a178ca4479728fa179ca442d7e1482a178ca4473c1eca179ca4428751f82a178ca446ed3d7a179ca4423e47b82a178ca446a9666a179ca441fbccd82a178ca4466f99aa179ca441beeb882a178ca4463f148a179ca44186c2982a178ca446171eca179ca4415285282a178ca445f728fa179ca4412185282a178ca445deccda179ca440f300082a178ca445cd99aa179ca440c651f82a178ca445c3666a179ca4409ad7182a178ca445c0000a179ca4407000082a178ca445c3666a179ca4404528f82a178ca445cd99aa179ca44019ae182a178ca445deccda179ca43fda00082a178ca445f728fa179ca43f7cf5c82a178ca446171eca179ca43f1af5c82a178ca4463f148a179ca43eb27ae82a178ca4466f99aa179ca43e4228f82a178ca446a9666a179ca43dc866682a178ca446ed3d7a179ca43d4370a82a178ca4473c1eca179ca43cb15c382a178ca4479728fa179ca43c103d782a178ca447ff99aa179ca43b5dc2982a178ca4487f75ca179ca439ba28f82a178ca44924429a179ca4375deb8a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce001f2937a76f706163697479ca3f800000a57769647468ca40800000a66f626a65637482a3726566d92465656565656565652d303031362d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000187a474797065cd0005a9636f6e74656e744964ce00000002a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca43aeef5ca179ca4453e66682a178ca44924429a179ca43686666a67374726f6b6584a5636f6c6f7281a866616c6c6261636bce008a8f98a76f706163697479ca3f800000a57769647468ca40000000a964617368417272617992ca41400000ca41000000a66f626a65637482a3726566d92465656565656565652d303031362d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000287a474797065cd0005a9636f6e74656e744964ce00000003a6756e646f4964ce00000000a9736861706554797065d200000000a867656f6d6574727981a6706f696e74739282a178ca43aeef5ca179ca4368666682a178ca44924429a179ca4453e666a67374726f6b6584a5636f6c6f7281a866616c6c6261636bce008a8f98a76f706163697479ca3f800000a57769647468ca40000000a964617368417272617992ca41400000ca41000000a66f626a65637482a3726566d92465656565656565652d303031362d343030302d383030302d303030303030303030303031a970617274496e646578ce0000000387a474797065cd0005a9636f6e74656e744964ce00000004a6756e646f4964ce00000001a9736861706554797065d200000006a867656f6d6574727981a6706f696e7473dc005e82a178ca44bb8000a179ca43e8800082a178ca44bba9eca179ca43e450a482a178ca44bc09eca179ca43df866682a178ca44bc575ca179ca43dcaa3d82a178ca44bcbb85a179ca43d9999a82a178ca44bd3852a179ca43d668f682a178ca44bdce14a179ca43d331ec82a178ca44be7d1fa179ca43d00a3d82a178ca44bf45c3a179ca43cd0a3d82a178ca44c02666a179ca43ca466682a178ca44c11e14a179ca43c7d47b82a178ca44c2299aa179ca43c5c51f82a178ca44c3475ca179ca43c42a3d82a178ca44c472e1a179ca43c30f5c82a178ca44c5a99aa179ca43c27eb882a178ca44c6e666a179ca43c27eb882a178ca44c82571a179ca43c3133382a178ca44c961eca179ca43c43c2982a178ca44ca975ca179ca43c5f70a82a178ca44cbc0a4a179ca43c83d7182a178ca44ccd948a179ca43cb07ae82a178ca44cddccda179ca43ce4b8582a178ca44cec75ca179ca43d1fae182a178ca44cf94cda179ca43d60b8582a178ca44d0419aa179ca43da6b8582a178ca44d0cb33a179ca43df10a482a178ca44d12f0aa179ca43e3e8f682a178ca44d16b85a179ca43e8e7ae82a178ca44d18000a179ca43ee000082a178ca44d16b85a179ca43f3266682a178ca44d12f0aa179ca43f84f5c82a178ca44d0cb33a179ca43fd733382a178ca44d0419aa179ca440145c382a178ca44cf94cda179ca4403c85282a178ca44cec75ca179ca4406400082a178ca44cddccda179ca4408ab8582a178ca44ccd948a179ca440b0a3d82a178ca44cbc0a4a179ca440d5c2982a178ca44ca975ca179ca440fa28f82a178ca44c82571a179ca44140ccd82a178ca44c3475ca179ca441c6ae182a178ca44c11e14a179ca44205eb882a178ca44bf45c3a179ca44241d7182a178ca44bdce14a179ca442793d782a178ca44bcbb85a179ca442aa5c382a178ca44bc09eca179ca442d351f82a178ca44bba9eca179ca442f233382a178ca44bb8000a179ca4430c00082a178ca44bb5614a179ca442f233382a178ca44baf614a179ca442d351f82a178ca44ba447ba179ca442aa5c382a178ca44b931eca179ca442793d782a178ca44b7ba3da179ca44241d7182a178ca44b5e1eca179ca44205eb882a178ca44b3b8a4a179ca441c6ae182a178ca44aeda8fa179ca44140ccd82a178ca44ac68a4a179ca440fa28f82a178ca44ab3f5ca179ca440d5c2982a178ca44aa26b8a179ca440b0a3d82a178ca44a92333a179ca4408ab8582a178ca44a838a4a179ca4406400082a178ca44a76b33a179ca4403c85282a178ca44a6be66a179ca440145c382a178ca44a634cda179ca43fd733382a178ca44a5d0f6a179ca43f84f5c82a178ca44a5947ba179ca43f3266682a178ca44a58000a179ca43ee000082a178ca44a5947ba179ca43e8e7ae82a178ca44a5d0f6a179ca43e3e8f682a178ca44a634cda179ca43df10a482a178ca44a6be66a179ca43da6b8582a178ca44a76b33a179ca43d60b8582a178ca44a838a4a179ca43d1fae182a178ca44a92333a179ca43ce4b8582a178ca44aa26b8a179ca43cb07ae82a178ca44ab3f5ca179ca43c83d7182a178ca44ac68a4a179ca43c5f70a82a178ca44ad9e14a179ca43c43c2982a178ca44aeda8fa179ca43c3133382a178ca44b0199aa179ca43c27eb882a178ca44b15666a179ca43c27eb882a178ca44b28d1fa179ca43c30f5c82a178ca44b3b8a4a179ca43c42a3d82a178ca44b4d666a179ca43c5c51f82a178ca44b5e1eca179ca43c7d47b82a178ca44b6d99aa179ca43ca466682a178ca44b7ba3da179ca43cd0a3d82a178ca44b882e1a179ca43d00a3d82a178ca44b931eca179ca43d331ec82a178ca44b9c7aea179ca43d668f682a178ca44ba447ba179ca43d9999a82a178ca44baa8a4a179ca43dcaa3d82a178ca44baf614a179ca43df866682a178ca44bb5614a179ca43e450a4a67374726f6b6583a5636f6c6f7281a866616c6c6261636bce00e5484da76f706163697479ca3f800000a57769647468ca40400000a466696c6c83a866696c6c54797065d200000000a5636f6c6f7281a866616c6c6261636bce00ffd6d8a76f706163697479ca3f800000" + } + ] +} diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/full-hdr-advanced.uink b/InkCanvas.Calibration.Tests/TestData/UInk/v11/full-hdr-advanced.uink new file mode 100644 index 0000000000000000000000000000000000000000..be7ae5a8cfb60b4f414fde695f6232d35c59830d GIT binary patch literal 1765 zcmb7E&ubGw6n^=2^5RiJut*UU0+9;#Vq!J{Efn=2sK?FjBw3Q|F1r(&Ko8Ya(OyNR zf{@bYXD=Rl@YuwQEJ+0wq5ptq|AYAUM>dm8QgI-Y8NQkKzW43-=KT<026v98YULMe@PKFR{>tc@FEi3ZrvgD03;@#-j$JbPu zRP3P8wYT@nr3^8gB;BG|CB_6lboP@2@XE^@>PVVOiAvXGCs4Dj%9^)sDQe*nvipt+ z0u4zkYDTS{6^q4;C>2g%G=PSwixO#=l99`FC9R}uDuy!OSc%`+td+Qm)9t}v*wXNr zLaSC{3!p_wg_aE`Dl~OXu`ks2Dpu+qz+Tn)YiuYo&0EPO00!yR0p=qD9%PW6`Naj8 z;sR`OA-A|^OmUk(M-$dC!+Kv;GPQ=87d>s7qNx*!T5&vhs2K`sAW}tBZQ)>F5_NkK z^lE*}RFpcJ@ID53fhq`p92M-F}!O)6h*SOunwvJc)onwI4^DQ1`3JL#1{>#^HEtG%Um>+GC(+#&VvFb4c)Z0dS zF$WPgIi&y4Mb7hx>>$a{Jd$^i-X|VOJ4pWmhjkR%!o83PDvQjpkmtoqCY$MJ(fnoa>H)^Sb literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/full-layers-devices.uink b/InkCanvas.Calibration.Tests/TestData/UInk/v11/full-layers-devices.uink new file mode 100644 index 0000000000000000000000000000000000000000..75a267225f5d5ba7ceff29e867a5063f6e663e1b GIT binary patch literal 2511 zcmds2O-vI(6rL6g2k#yYF~u1QL~l z2{omEh()~+jX&{ZHUSeoaq~do>e)+uvpc&jAax0e2PWz4%)EK;&HKLhUY~9tw1G}< zwTz3=+Sb-~q4hk>t(|;=pEouULJfQh+S4~!p;+UO)O3cK2H8M?jD{!3oATVF^6Rng_%qwp~zb;vKV!|wHFLk;u(D99`#oZuf*XBxr`;SVs$Mc^uT{`p}z-Lo-OSS zt|?VNxLN-$JNCJB$SQaotr>uk#=IqH0yDaIdPVeN$v8wXpO;o8=at3CMP>mOBa7IAUP>^(u z0dE5`cZ0H^u8Va}(PAFg2Th*6QOW6$M+!5ot`tH!Mv^Q+oo10WbVXzF`6~i=%;ggIZ6|=HzHuGeN3lU%=!5wP(I*I_=5$U1 zrU<=m_5KFDoy}-1upDZ)@OeMTj4P@-mFKf-4jp8&^7G*yCjV=lgid;$l=}zwpnG_o zJh7{R7lr8K-B1`cb@HXAfJ4S;#w-oy)@CzK?9>A41 YD8OF;fAO;eJU;?S4e+$ZCcf|Yp`Uc|r$T|KQJ&~7xJOltls;5UJ1ex}K3zIWA zpMy&vTFNQI@N-Ak9`9DYqd~q;%5?Z4Q-h;4DVU?-5ht63h&^P^Q1TE}?^jq{9RSXG z&yAH;%f!&chcuR`=$M-2eJONqya#|wE_x>x${&+Z-U+}wsS5$%sF>uQn6)uULjlt91R#AYrlCHZ z#_nP-DNa(c;n(^PkdBeQU}Ge5eV$%FW?_Y=2;c6c#OQ$QrcL?H%v5LWUOJCIPU`VS&+kC0KYHfX2-Nv|Cz7TkTSY zw(5J}M05A(WUZO_SH~VW1!jl*E2|TBM zu34wPca2kz_)c9%ssZbrdbG}fk5>&i#ZOiXihLTH8e{gZe`zLbX>7X^;XZrHs|fem ziz1&*s#B);*BEeuI>3Ne=-41fPO2$%i z(fZEr@H=~DH~A}L@{a^1m+rz?_$MP)9_Z!a!fAGQ;4}|!_p)$snTK~Svhc7s*h?h? ze)sxv-QAl!)yj9T@l-3BZx#51dK)O}zy66pMG=SGoTA<=|5TU2qhYdHMfD36bz?LR zN0n^OfN{snnAV8dNL)3$Tlwle2AtI27uN#6bhtpauDS+ox{r<(?VO&0wtL{ggC(xC xADdGesamkoNHuEy2M{a*ABa0j^#8;>r}CKB27IcJNhqEx8!+3lRQgv*DXa<%JsX~QBH&8!ou@c{mh-H{okA0dwkr}y zm5_?$I8I>b&<_Beswag??Zn0c?YE%s1t+$HXrJWMJKepz|L@NG1AqZMIG;7*Qz#aT zMqysq!c%F)H$GAv!+Tj&m(^exp#H;Eq&{Uia74Uc&)zEFMYv3Eh0>KGB*AU0tbnJ&@S$y?;l@&F%V zg;PC^+6-;BrVm?&o~_gP-X(TrLvZ{QQgR)QTGZW+4Aru>RIPFbGn?04>ZlrFK3{AC zbQv~ecbN{MLy665yRE|pFRcO``nHbfk7;*6-hhN0JjTVUwq6Ih<||RhJhLj1%XcMBiM;mD=ApzKdZi6eVJ)<=c?lw Sr-m`H>eJ8TF-=4!R{a;zs#T2u literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/inkeys-erase-clear.uink b/InkCanvas.Calibration.Tests/TestData/UInk/v11/inkeys-erase-clear.uink new file mode 100644 index 0000000000000000000000000000000000000000..dd09d16b68d9641e9b25d2b064d5b37bf930e0f6 GIT binary patch literal 1458 zcmb_czi-n(82#e>=)nH~73u;~M35?h7-)$j(GD;%0NcgBCYDp58a_rMJORWp~-5rbT+n!C^qA5&7 z`LwlLrGXqWX^;*L7Wh=wiwm%?=4Qth^EmbRwk;bCTAt0+dFXiVGi3J-2W0vdYp`H% zv_l$=DzV%Xxc>6*kom-NcqiQG0t`8A^Hw0Q!@y^b$D8kZNA1wu0yye~<_CcOE63*b z@DX;D$RCMdr6Y4s@=0zPjaz2itP`Kk*%_l6WxJFIoi{@Z#n9k+X#PM-QSl-)agdsA zegPQNsZ*=-&|JlHlLySDz4HQZ+`5+#s2Xf`0S=biXJ`}+-99+q9W^JqC+s`+oNBKx zHA?pfr0G+Oha0yi(2UbX}OQycMida#YZ`6?AU@Ek|8|OLG*xyitxScVgaW(o+7NKvLXZ(G;!dik2kd g^@CqmbKAs!VDz-I9y8ed9A&(GC=u~Be`^u>2V^l7eEqD{dT)PwZsWx6{_hV1UFyR-SYMJuA-^iZiF zSWNS!r6PKimY!ra74%f_YW+8SGdtOAgK3KRU}xU!yqWiVzxUoe?<3SlXAh?fN@iwf zXRpl6!8kK72KXX5KnQ8W;TtSbIrXEl*5q}E^pVy!NQLUed-||h^r>+;Z74b6*2}%{ z&0Mw73RyfL24ogs3(@Ud~21s zGABI~*NHpaejLGX4zw}Iv=}n&pO9UQAp?C9vc<#*vcwZrGb5ZOV#pHz z8yPTyLgIEC1L79%j37fz-DS=LNVYJCWQ$29p>oXODnQBwJ95wfr z&P?Xs>lCnQu427>fPO9A9NrCx+MLw5?}l$r%V89X`I+dD{CP=Q{(eN-)jfpd&iW{w zVrPJDqz^*m}9Cv*-F5_L{`GJ&#l@<(GcdL{Zi+Vm literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/standard-media.uink.extra b/InkCanvas.Calibration.Tests/TestData/UInk/v11/standard-media.uink.extra new file mode 100644 index 0000000000000000000000000000000000000000..290e27f91221ecf55faf9bee98c0594f566f58dd GIT binary patch literal 5061 zcmeHLON-M`6u$K_4)HaJE>zG%WELXk+0<6r>gY^$93N#I6coWsbDKunW=wCV)uo7_ zOIPB`A0YZKT)1+hxN$A$!i}K9fS!|PCQej_;>Ja8?oD$~zVp22KAP&x`VA5rl>W8W zv+W<2HZewRI}+`#;kCHZvlnNlE0r(!>hi>;sd`Jm7(z059pBHwmSLmJv4#B_ zF^{9th)UWYL?DgFAOdMVr1?M*NasU3A1DIpdhma*2h~*vg|EBs?|HM1F>1T;6yW%^ zZi}}?M{U?`$L|Vd!Ksf|Co6|_B`fKmfj@skDi%SVyS>0cJ&C7;rtgAUwO!r;0|B#8 zE=wGl5lH>j3=S+;u4;%k z4Gr|XhVo{4$L|I;Gz;x5mq|fekZ+I;^~QRrzpUphZ@Z!aW{&LWh=AKINmFz^51L|H zCg>2j66&CuM^#x30uFWZI6_ChlUvI|2f-rW|K0dp!g%U0>xqoF3cnbSgQi$n8oECl zuA@t#Q#!ho(*T{q`=5R42fQw6a75Bp3gj%yw4e?#tpMR$XvZ`Q!$;*8nr@&?37TPG z)DkpP$6-y-vN{ggGED@w*W^K%l^4A`9FE}F`@TT0qHOF4I}oAmmSITa<5L$Z(&~9| z=E?Yh=rr7+Uxa{o~ihOs~TvEiU=8c zo+BD1xsa2g!9BMj2G5Hg?_q|PWXjM&4y#-)2D~N!X;~R=hxdp%pO2a8IY5k#0_$G0 zS&|RvQ`SVKBCF+M%?oNx4mFa2xEe_zd`UJ?W(2QW_zPsG2HRGhAti{(}(7Pj3!Y-Q-+Ml21{njt#+=>7hs zmjw-X3pPDvyX&nRPqa-#=IpHZF7lhy z54}Xt{8F*d9(pR`sRXpp_Ts&g{tdm@H$QgGCegK!Lk6<5lQ(bP%=>)j?bZoGC+ODM zz@liO!NI|i&m#UC`lc8+&>*6l8<3Q55p`U|BLR+A|L?}2b_ z*)TOLBhz3nMKD>k>w+CPes(+`JHtU^fB*NF^~PQ?c)szWlrk(5RX#=MW~Ls`hhnjX z(1XZmcxrfj=wl*lnph_>Ifmnh(%k>|z1l(j#A_3gtCK;<_AUL0%5be4% zSLt+Tuc$_cbJ?XhHrd{5X*rM0OZy%hUrs<}E3GOxssIlOy%Hz&R}+R#AQ4f8u7XNg zT`|OaS=BW=z0z*NNE_x#Wl>J2<8nefMd#DAWdqQuBwv46K&VV`j$}&mQbYS^SjPwHj4-gnE@*CJQHw_M|@uBdvFowN&by;syc<;u#*P3wdJTMShxN@HxqL?nZ{+ fjbOV4{&JV{R-eyT`gE{}IK_4!ZiztGbUXh6G@r{> literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/TestData/UInk/v11/standard-shape-object.uink b/InkCanvas.Calibration.Tests/TestData/UInk/v11/standard-shape-object.uink new file mode 100644 index 0000000000000000000000000000000000000000..6e4e5162e70d3943fc6020f1e1d141fda9acab17 GIT binary patch literal 4040 zcmd6q%}*0S7{+JY@{J!CuX^F42?>HhFGgxfgeG_}o-`h|yHi+OcAD9#&|CQsJt{;z za8S^e77r$9xOnoWn}CTP3&BfNjvV z+mp3hZ(m>EVDBZ`_g-Ng{W)z103f;D7aD?G;#+y)H7OO~Hi*><@;JOv)YRP`#coH; zcd^c1AJtVj%_apKEWBBq%s|W+*~rT!h~4owJa%6IkL-0@>I%{c)XAvIC#n{871_^q zV?r*#+w}XsvNdYs5KTgYOEc91(sW`h&aO_IsSyBHOJ?df04yAiS>Xl%RfAxZgL4%H z-&~8U1qK4rE z&Crm}Q%XNmsunObAgRb0qbZsvOj4+*6NVQPU`t|b=@9l3$KLz(f?>bC_x%7iAN`Yl z$3~mX!t5&yv%%89IUT(v0cXs^DFu>u_^P@^Nro@1q&erp=3P5%T;3r^-iJZu?H9^h zRf-v;seXOC>jcZXkwtiNnLEp*q64dAMsq_!g5qHll=?CF%#$D%Hj|*>%J&CTJ`ono zQQk5_WMHDdZcF1}u7|l|Psb|E(r47INEC|;tk@bB%(0>cmfHNBiv%no0BZ{i=2+1Z zFfuE)2*BDK2Xnp0t$1rC?YH85@WYetu60#5CXyJ-rA0GIV>9{0*>XegD6In8jkJFVwh+&b5*b*#0IaKVFxQYA%)JcQJIXQeXNQ2cJ1ni^&xlXFP6617 zuwafqEmb}KJO(m$320AxXk)>ytZQXnku2L4$p(f#{N^0%mux&4jjI+`Y)-X z1OHTL()WH+8a6{3{G=E-aQA#{7nN~;QF+<}7GKx&+~1N?I()jFy|d>NVx7QgQp8pT kYS*1hbF9#`Ri<@k#V#LT0>DPDf8r(RM;iWnBk79awM;ouwt0|O(1I1l79WV2juXj@WJS&({` zfoVlSVtT53X=chzm1HQuW1itkkaEwwl++54p$w})T))!Xq|_p?C9850D^rUQ@~gpo zgaU>RsJ+Z9lk@XRQu9hYQ@{o-E6q#Ehq9Mv=4FQfU3Up+0prr-{G9xv#uaIaIXOv* z$=T-^6s~HKnT4_NxX|6tj%WagpnhD9(Oaxs0 U)WesctEV7^sPiw1T@5h}0EkWzC;$Ke literal 0 HcmV?d00001 diff --git a/InkCanvas.Calibration.Tests/UInk/ShapeToolHeadReference.cs b/InkCanvas.Calibration.Tests/UInk/ShapeToolHeadReference.cs new file mode 100644 index 000000000..45552ff6d --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/ShapeToolHeadReference.cs @@ -0,0 +1,940 @@ +using System; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Input; + +namespace InkCanvas.Calibration.Tests.UInk +{ + // HEAD a357364d,MW_ShapeDrawing.cs:1242–2159、2343–2629、3057–3087。 + // 逐字保留点列、采样、压力及 DA 公式。预览集合替代画布,第二步状态由调用方传入。 + internal sealed class ShapeToolHeadReference + { + private readonly DrawingAttributes da; + private readonly bool marks; + internal ShapeToolHeadReference(DrawingAttributes da, bool marks) + { + this.da = da; + this.marks = marks; + } + + internal static Stroke CircleCenter(Point centerPoint, DrawingAttributes da) + { + // 创建一个点作为圆心标记 + var centerSize = 0.5; // 圆心标记的大小 + + // 创建一个小圆作为圆心标记 + var circlePoints = new List(); + for (double angle = 0; angle <= 2 * Math.PI; angle += 0.1) + { + circlePoints.Add(new Point( + centerPoint.X + centerSize * Math.Cos(angle), + centerPoint.Y + centerSize * Math.Sin(angle) + )); + } + + // 绘制圆心点 + var point = new StylusPointCollection(circlePoints); + var stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + + // 设置圆心点的样式 + stroke.DrawingAttributes.Width = 2.0; + stroke.DrawingAttributes.Height = 2.0; + + return stroke; + } + + private static double GetDistance(Point p, Point q) => + Math.Sqrt((p.X-q.X)*(p.X-q.X) + (p.Y-q.Y)*(p.Y-q.Y)); + + internal StrokeCollection Generate(int drawingShapeMode, Point iniP, Point endP, + bool isFirstTouchCuboid, Point CuboidFrontRectIniP, Point CuboidFrontRectEndP, + int drawMultiStepShapeCurrentStep, double drawMultiStepShapeSpecialParameter3, + StrokeCollection drawMultiStepShapeSpecialStrokeCollection) + { + List pointList; + StylusPointCollection point; + Stroke stroke; + var strokes = new StrokeCollection(); + var newIniP = iniP; + switch (drawingShapeMode) + { + case 1: + pointList = new List { + new Point(iniP.X, iniP.Y), + new Point(endP.X, endP.Y) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + + strokes.Add(stroke); + break; + case 8: + strokes.Add(GenerateDashedLineStrokeCollection(iniP, endP)); + + break; + case 18: + strokes.Add(GenerateDotLineStrokeCollection(iniP, endP)); + + break; + case 2: + double w = 15, h = 10; + var theta = Math.Atan2(iniP.Y - endP.Y, iniP.X - endP.X); + var sint = Math.Sin(theta); + var cost = Math.Cos(theta); + + pointList = new List { + new Point(iniP.X, iniP.Y), + new Point(endP.X, endP.Y), + new Point(endP.X + (w * cost - h * sint), endP.Y + (w * sint + h * cost)), + new Point(endP.X, endP.Y), + new Point(endP.X + (w * cost + h * sint), endP.Y - (h * cost - w * sint)) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + + strokes.Add(stroke); + break; + case 15: + var d = GetDistance(iniP, endP); + if (d == 0) return new StrokeCollection(); + var sinTheta = (iniP.Y - endP.Y) / d; + var cosTheta = (endP.X - iniP.X) / d; + var tanTheta = Math.Abs(sinTheta / cosTheta); + double x = 25; + if (Math.Abs(tanTheta) < 1.0 / 12) + { + sinTheta = 0; + cosTheta = 1; + endP.Y = iniP.Y; + } + + if (tanTheta < 0.63 && tanTheta > 0.52) //30 + { + sinTheta = sinTheta / Math.Abs(sinTheta) * 0.5; + cosTheta = cosTheta / Math.Abs(cosTheta) * 0.866; + endP.Y = iniP.Y - d * sinTheta; + endP.X = iniP.X + d * cosTheta; + } + + if (tanTheta < 1.08 && tanTheta > 0.92) //45 + { + sinTheta = sinTheta / Math.Abs(sinTheta) * 0.707; + cosTheta = cosTheta / Math.Abs(cosTheta) * 0.707; + endP.Y = iniP.Y - d * sinTheta; + endP.X = iniP.X + d * cosTheta; + } + + if (tanTheta < 1.95 && tanTheta > 1.63) //60 + { + sinTheta = sinTheta / Math.Abs(sinTheta) * 0.866; + cosTheta = cosTheta / Math.Abs(cosTheta) * 0.5; + endP.Y = iniP.Y - d * sinTheta; + endP.X = iniP.X + d * cosTheta; + } + + if (Math.Abs(cosTheta / sinTheta) < 1.0 / 12) + { + endP.X = iniP.X; + sinTheta = 1; + cosTheta = 0; + } + + strokes.Add(GenerateLineStroke(new Point(iniP.X - 3 * x * sinTheta, iniP.Y - 3 * x * cosTheta), + new Point(endP.X - 3 * x * sinTheta, endP.Y - 3 * x * cosTheta))); + strokes.Add(GenerateLineStroke(new Point(iniP.X - x * sinTheta, iniP.Y - x * cosTheta), + new Point(endP.X - x * sinTheta, endP.Y - x * cosTheta))); + strokes.Add(GenerateLineStroke(new Point(iniP.X + x * sinTheta, iniP.Y + x * cosTheta), + new Point(endP.X + x * sinTheta, endP.Y + x * cosTheta))); + strokes.Add(GenerateLineStroke(new Point(iniP.X + 3 * x * sinTheta, iniP.Y + 3 * x * cosTheta), + new Point(endP.X + 3 * x * sinTheta, endP.Y + 3 * x * cosTheta))); + + break; + case 11: + var xAxisStart = new Point(2 * iniP.X - (endP.X - 20), iniP.Y); + var xAxisEnd = new Point(endP.X, iniP.Y); + var yAxisStart = new Point(iniP.X, 2 * iniP.Y - (endP.Y + 20)); + var yAxisEnd = new Point(iniP.X, endP.Y); + strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); + strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); + AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd); + + break; + case 12: + if (Math.Abs(iniP.X - endP.X) < 0.01) return new StrokeCollection(); + xAxisStart = new Point(iniP.X + (iniP.X - endP.X) / Math.Abs(iniP.X - endP.X) * 25, iniP.Y); + xAxisEnd = new Point(endP.X, iniP.Y); + yAxisStart = new Point(iniP.X, 2 * iniP.Y - (endP.Y + 20)); + yAxisEnd = new Point(iniP.X, endP.Y); + strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); + strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); + AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd); + + break; + case 13: + if (Math.Abs(iniP.Y - endP.Y) < 0.01) return new StrokeCollection(); + xAxisStart = new Point(2 * iniP.X - (endP.X - 20), iniP.Y); + xAxisEnd = new Point(endP.X, iniP.Y); + yAxisStart = new Point(iniP.X, iniP.Y + (iniP.Y - endP.Y) / Math.Abs(iniP.Y - endP.Y) * 25); + yAxisEnd = new Point(iniP.X, endP.Y); + strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); + strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); + AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd); + + break; + case 14: + if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return new StrokeCollection(); + xAxisStart = new Point(iniP.X + (iniP.X - endP.X) / Math.Abs(iniP.X - endP.X) * 25, iniP.Y); + xAxisEnd = new Point(endP.X, iniP.Y); + yAxisStart = new Point(iniP.X, iniP.Y + (iniP.Y - endP.Y) / Math.Abs(iniP.Y - endP.Y) * 25); + yAxisEnd = new Point(iniP.X, endP.Y); + strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); + strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); + AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd); + + break; + case 17: + xAxisStart = new Point(iniP.X, iniP.Y); + xAxisEnd = new Point(iniP.X + Math.Abs(endP.X - iniP.X), iniP.Y); + yAxisStart = new Point(iniP.X, iniP.Y); + yAxisEnd = new Point(iniP.X, iniP.Y - Math.Abs(endP.Y - iniP.Y)); + strokes.Add(GenerateArrowLineStroke(xAxisStart, xAxisEnd)); + strokes.Add(GenerateArrowLineStroke(yAxisStart, yAxisEnd)); + d = (Math.Abs(iniP.X - endP.X) + Math.Abs(iniP.Y - endP.Y)) / 2; + var zAxisEnd = new Point(iniP.X - d / 1.76, iniP.Y + d / 1.76); + strokes.Add(GenerateArrowLineStroke(new Point(iniP.X, iniP.Y), zAxisEnd)); + AddCoordinateUnitMarks(strokes, iniP, xAxisStart, xAxisEnd, yAxisStart, yAxisEnd, zAxisEnd); + + break; + case 3: + pointList = new List { + new Point(iniP.X, iniP.Y), + new Point(iniP.X, endP.Y), + new Point(endP.X, endP.Y), + new Point(endP.X, iniP.Y), + new Point(iniP.X, iniP.Y) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + + strokes.Add(stroke); + break; + case 19: + var a = iniP.X - endP.X; + var b = iniP.Y - endP.Y; + pointList = new List { + new Point(iniP.X - a, iniP.Y - b), + new Point(iniP.X - a, iniP.Y + b), + new Point(iniP.X + a, iniP.Y + b), + new Point(iniP.X + a, iniP.Y - b), + new Point(iniP.X - a, iniP.Y - b) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + + strokes.Add(stroke); + break; + case 4: + pointList = GenerateEllipseGeometry(iniP, endP); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + + strokes.Add(stroke); + break; + case 5: + var R = GetDistance(iniP, endP); + pointList = GenerateEllipseGeometry(new Point(iniP.X - R, iniP.Y - R), + new Point(iniP.X + R, iniP.Y + R)); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + + strokes.Add(stroke); + + break; + case 16: + var halfA = endP.X - iniP.X; + var halfB = endP.Y - iniP.Y; + pointList = GenerateEllipseGeometry(new Point(iniP.X - halfA, iniP.Y - halfB), + new Point(iniP.X + halfA, iniP.Y + halfB)); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + + strokes.Add(stroke); + break; + case 23: + a = Math.Abs(endP.X - iniP.X); + b = Math.Abs(endP.Y - iniP.Y); + pointList = GenerateEllipseGeometry(new Point(iniP.X - a, iniP.Y - b), + new Point(iniP.X + a, iniP.Y + b)); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke); + var c = Math.Sqrt(Math.Abs(a * a - b * b)); + StylusPoint stylusPoint; + if (a > b) + { + stylusPoint = new StylusPoint(iniP.X + c, iniP.Y, (float)1.0); + point = new StylusPointCollection(); + point.Add(stylusPoint); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + stylusPoint = new StylusPoint(iniP.X - c, iniP.Y, (float)1.0); + point = new StylusPointCollection(); + point.Add(stylusPoint); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + } + else if (a < b) + { + stylusPoint = new StylusPoint(iniP.X, iniP.Y - c, (float)1.0); + point = new StylusPointCollection(); + point.Add(stylusPoint); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + stylusPoint = new StylusPoint(iniP.X, iniP.Y + c, (float)1.0); + point = new StylusPointCollection(); + point.Add(stylusPoint); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + } + + + break; + case 10: + R = GetDistance(iniP, endP); + strokes = GenerateDashedLineEllipseStrokeCollection(new Point(iniP.X - R, iniP.Y - R), + new Point(iniP.X + R, iniP.Y + R)); + + break; + case 24: + case 25: + //双曲线 x^2/a^2 - y^2/b^2 = 1 + if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return new StrokeCollection(); + var pointList2 = new List(); + var pointList3 = new List(); + var pointList4 = new List(); + if (drawMultiStepShapeCurrentStep == 0) + { + //第一笔:画渐近线 + var k = Math.Abs((endP.Y - iniP.Y) / (endP.X - iniP.X)); + strokes.Add( + GenerateDashedLineStrokeCollection(new Point(2 * iniP.X - endP.X, 2 * iniP.Y - endP.Y), + endP)); + strokes.Add(GenerateDashedLineStrokeCollection(new Point(2 * iniP.X - endP.X, endP.Y), + new Point(endP.X, 2 * iniP.Y - endP.Y))); + } + else + { + //第二笔:画双曲线 + // 保留第一笔渐近线的引用,保证收尾时移除的是画布上的实际笔画。 + if (drawMultiStepShapeSpecialStrokeCollection != null && drawMultiStepShapeSpecialStrokeCollection.Count > 0) + { + foreach (var asymptoteStroke in drawMultiStepShapeSpecialStrokeCollection) + { + strokes.Add(asymptoteStroke); + } + } + + var k = drawMultiStepShapeSpecialParameter3; + var isHyperbolaFocalPointOnXAxis = Math.Abs((endP.Y - iniP.Y) / (endP.X - iniP.X)) < k; + if (isHyperbolaFocalPointOnXAxis) + { + // 焦点在 x 轴上 + a = Math.Sqrt(Math.Abs((endP.X - iniP.X) * (endP.X - iniP.X) - + (endP.Y - iniP.Y) * (endP.Y - iniP.Y) / (k * k))); + b = a * k; + pointList = new List(); + for (var i = a; i <= Math.Abs(endP.X - iniP.X); i += 0.5) + { + var rY = Math.Sqrt(Math.Abs(k * k * i * i - b * b)); + pointList.Add(new Point(iniP.X + i, iniP.Y - rY)); + pointList2.Add(new Point(iniP.X + i, iniP.Y + rY)); + pointList3.Add(new Point(iniP.X - i, iniP.Y - rY)); + pointList4.Add(new Point(iniP.X - i, iniP.Y + rY)); + } + } + else + { + // 焦点在 y 轴上 + a = Math.Sqrt(Math.Abs((endP.Y - iniP.Y) * (endP.Y - iniP.Y) - + (endP.X - iniP.X) * (endP.X - iniP.X) * (k * k))); + b = a / k; + pointList = new List(); + for (var i = a; i <= Math.Abs(endP.Y - iniP.Y); i += 0.5) + { + var rX = Math.Sqrt(Math.Abs(i * i / k / k - b * b)); + pointList.Add(new Point(iniP.X - rX, iniP.Y + i)); + pointList2.Add(new Point(iniP.X + rX, iniP.Y + i)); + pointList3.Add(new Point(iniP.X - rX, iniP.Y - i)); + pointList4.Add(new Point(iniP.X + rX, iniP.Y - i)); + } + } + + try + { + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + point = new StylusPointCollection(pointList2); + stroke = new Stroke(point) + { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + point = new StylusPointCollection(pointList3); + stroke = new Stroke(point) + { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + point = new StylusPointCollection(pointList4); + stroke = new Stroke(point) + { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + if (drawingShapeMode == 25) + { + //画焦点 + c = Math.Sqrt(a * a + b * b); + stylusPoint = isHyperbolaFocalPointOnXAxis + ? new StylusPoint(iniP.X + c, iniP.Y, (float)1.0) + : new StylusPoint(iniP.X, iniP.Y + c, (float)1.0); + point = new StylusPointCollection(); + point.Add(stylusPoint); + stroke = new Stroke(point) + { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + stylusPoint = isHyperbolaFocalPointOnXAxis + ? new StylusPoint(iniP.X - c, iniP.Y, (float)1.0) + : new StylusPoint(iniP.X, iniP.Y - c, (float)1.0); + point = new StylusPointCollection(); + point.Add(stylusPoint); + stroke = new Stroke(point) + { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + } + } + catch + { + return new StrokeCollection(); + } + } + + break; + case 20: + //抛物线 y=ax^2 + if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return new StrokeCollection(); + a = (iniP.Y - endP.Y) / ((iniP.X - endP.X) * (iniP.X - endP.X)); + pointList = new List(); + pointList2 = new List(); + for (var i = 0.0; i <= Math.Abs(endP.X - iniP.X); i += 0.5) + { + pointList.Add(new Point(iniP.X + i, iniP.Y - a * i * i)); + pointList2.Add(new Point(iniP.X - i, iniP.Y - a * i * i)); + } + + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + point = new StylusPointCollection(pointList2); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + + break; + case 21: + //抛物线 y^2=ax + if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return new StrokeCollection(); + a = (iniP.X - endP.X) / ((iniP.Y - endP.Y) * (iniP.Y - endP.Y)); + pointList = new List(); + pointList2 = new List(); + for (var i = 0.0; i <= Math.Abs(endP.Y - iniP.Y); i += 0.5) + { + pointList.Add(new Point(iniP.X - a * i * i, iniP.Y + i)); + pointList2.Add(new Point(iniP.X - a * i * i, iniP.Y - i)); + } + + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + point = new StylusPointCollection(pointList2); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + + break; + case 22: + //抛物线 y^2=ax, 含焦点 + if (Math.Abs(iniP.X - endP.X) < 0.01 || Math.Abs(iniP.Y - endP.Y) < 0.01) return new StrokeCollection(); + var p = (iniP.Y - endP.Y) * (iniP.Y - endP.Y) / (2 * (iniP.X - endP.X)); + a = 0.5 / p; + pointList = new List(); + pointList2 = new List(); + for (var i = 0.0; i <= Math.Abs(endP.Y - iniP.Y); i += 0.5) + { + pointList.Add(new Point(iniP.X - a * i * i, iniP.Y + i)); + pointList2.Add(new Point(iniP.X - a * i * i, iniP.Y - i)); + } + + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + point = new StylusPointCollection(pointList2); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + stylusPoint = new StylusPoint(iniP.X - p / 2, iniP.Y, (float)1.0); + point = new StylusPointCollection(); + point.Add(stylusPoint); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + + break; + case 6: + newIniP = iniP; + if (iniP.Y > endP.Y) + { + newIniP = new Point(iniP.X, endP.Y); + endP = new Point(endP.X, iniP.Y); + } + + var topA = Math.Abs(newIniP.X - endP.X); + var topB = topA / 2.646; + //顶部椭圆 + pointList = GenerateEllipseGeometry(new Point(newIniP.X, newIniP.Y - topB / 2), + new Point(endP.X, newIniP.Y + topB / 2)); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + //底部椭圆 + pointList = GenerateEllipseGeometry(new Point(newIniP.X, endP.Y - topB / 2), + new Point(endP.X, endP.Y + topB / 2), false); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + strokes.Add(GenerateDashedLineEllipseStrokeCollection(new Point(newIniP.X, endP.Y - topB / 2), + new Point(endP.X, endP.Y + topB / 2), true, false)); + //左侧 + pointList = new List { + new Point(newIniP.X, newIniP.Y), + new Point(newIniP.X, endP.Y) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + //右侧 + pointList = new List { + new Point(endP.X, newIniP.Y), + new Point(endP.X, endP.Y) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + + break; + case 7: + if (iniP.Y > endP.Y) + { + newIniP = new Point(iniP.X, endP.Y); + endP = new Point(endP.X, iniP.Y); + } + + var bottomA = Math.Abs(newIniP.X - endP.X); + var bottomB = bottomA / 2.646; + //底部椭圆 + pointList = GenerateEllipseGeometry(new Point(newIniP.X, endP.Y - bottomB / 2), + new Point(endP.X, endP.Y + bottomB / 2), false); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + strokes.Add(GenerateDashedLineEllipseStrokeCollection(new Point(newIniP.X, endP.Y - bottomB / 2), + new Point(endP.X, endP.Y + bottomB / 2), true, false)); + //左侧 + pointList = new List { + new Point((newIniP.X + endP.X) / 2, newIniP.Y), + new Point(newIniP.X, endP.Y) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + //右侧 + pointList = new List { + new Point((newIniP.X + endP.X) / 2, newIniP.Y), + new Point(endP.X, endP.Y) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + + break; + case 9: + // 画长方体 + if (isFirstTouchCuboid) + { + //分开画线条方便后期单独擦除某一条棱 + strokes.Add(GenerateLineStroke(new Point(iniP.X, iniP.Y), new Point(iniP.X, endP.Y))); + strokes.Add(GenerateLineStroke(new Point(iniP.X, endP.Y), new Point(endP.X, endP.Y))); + strokes.Add(GenerateLineStroke(new Point(endP.X, endP.Y), new Point(endP.X, iniP.Y))); + strokes.Add(GenerateLineStroke(new Point(iniP.X, iniP.Y), new Point(endP.X, iniP.Y))); + + } + else + { + d = CuboidFrontRectIniP.Y - endP.Y; + if (d < 0) d = -d; //就是懒不想做反向的,不要让我去做,想做自己做好之后 Pull Request + a = CuboidFrontRectEndP.X - CuboidFrontRectIniP.X; //正面矩形长 + b = CuboidFrontRectEndP.Y - CuboidFrontRectIniP.Y; //正面矩形宽 + + //横上 + var newLineIniP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectIniP.Y - d); + var newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectIniP.Y - d); + pointList = new List { newLineIniP, newLineEndP }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + //横下 (虚线) + newLineIniP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectEndP.Y - d); + newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectEndP.Y - d); + strokes.Add(GenerateDashedLineStrokeCollection(newLineIniP, newLineEndP)); + //斜左上 + newLineIniP = new Point(CuboidFrontRectIniP.X, CuboidFrontRectIniP.Y); + newLineEndP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectIniP.Y - d); + pointList = new List { newLineIniP, newLineEndP }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + //斜右上 + newLineIniP = new Point(CuboidFrontRectEndP.X, CuboidFrontRectIniP.Y); + newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectIniP.Y - d); + pointList = new List { newLineIniP, newLineEndP }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + //斜左下 (虚线) + newLineIniP = new Point(CuboidFrontRectIniP.X, CuboidFrontRectEndP.Y); + newLineEndP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectEndP.Y - d); + strokes.Add(GenerateDashedLineStrokeCollection(newLineIniP, newLineEndP)); + //斜右下 + newLineIniP = new Point(CuboidFrontRectEndP.X, CuboidFrontRectEndP.Y); + newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectEndP.Y - d); + pointList = new List { newLineIniP, newLineEndP }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + //竖左 (虚线) + newLineIniP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectIniP.Y - d); + newLineEndP = new Point(CuboidFrontRectIniP.X + d, CuboidFrontRectEndP.Y - d); + strokes.Add(GenerateDashedLineStrokeCollection(newLineIniP, newLineEndP)); + //竖右 + newLineIniP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectIniP.Y - d); + newLineEndP = new Point(CuboidFrontRectEndP.X + d, CuboidFrontRectEndP.Y - d); + pointList = new List { newLineIniP, newLineEndP }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) { DrawingAttributes = da.Clone() }; + strokes.Add(stroke.Clone()); + + + } + + break; + } + return strokes; + } + + private List GenerateEllipseGeometry(Point st, Point ed, bool isDrawTop = true, + bool isDrawBottom = true) + { + // 防御:画布被极端缩放/平移时识别出的椭圆中心/半轴可能非有限,直接返回空避免生成 NaN 点。 + if (!double.IsFinite(st.X) || !double.IsFinite(st.Y) || + !double.IsFinite(ed.X) || !double.IsFinite(ed.Y)) + return new List(); + + var a = 0.5 * (ed.X - st.X); + var b = 0.5 * (ed.Y - st.Y); + var pointList = new List(); + if (isDrawTop && isDrawBottom) + { + for (double r = 0; r <= 2 * Math.PI; r = r + 0.01) + pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), + 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); + } + else + { + if (isDrawBottom) + for (double r = 0; r <= Math.PI; r = r + 0.01) + pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), + 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); + if (isDrawTop) + for (var r = Math.PI; r <= 2 * Math.PI; r = r + 0.01) + pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), + 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); + } + + return pointList; + } + + private StrokeCollection GenerateDashedLineEllipseStrokeCollection(Point st, Point ed, bool isDrawTop = true, + bool isDrawBottom = true) + { + var strokes = new StrokeCollection(); + // 防御:非有限坐标直接返回空集,避免生成 NaN 笔画。 + if (!double.IsFinite(st.X) || !double.IsFinite(st.Y) || + !double.IsFinite(ed.X) || !double.IsFinite(ed.Y)) + return strokes; + + var a = 0.5 * (ed.X - st.X); + var b = 0.5 * (ed.Y - st.Y); + var step = 0.05; + var pointList = new List(); + StylusPointCollection point; + Stroke stroke; + if (isDrawBottom) + for (var i = 0.0; i < 1.0; i += step * 1.66) + { + pointList = new List(); + for (var r = Math.PI * i; r <= Math.PI * (i + step); r = r + 0.01) + pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), + 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + } + + if (isDrawTop) + for (var i = 1.0; i < 2.0; i += step * 1.66) + { + pointList = new List(); + for (var r = Math.PI * i; r <= Math.PI * (i + step); r = r + 0.01) + pointList.Add(new Point(0.5 * (st.X + ed.X) + a * Math.Cos(r), + 0.5 * (st.Y + ed.Y) + b * Math.Sin(r))); + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + } + + return strokes; + } + + private const double CoordinateCentimeterUnitLength = 37.7952755906; + + private void AddCoordinateUnitMarks(StrokeCollection strokes, Point origin, Point xAxisStart, Point xAxisEnd, + Point yAxisStart, Point yAxisEnd, Point? zAxisEnd = null) + { + if (!marks) return; + + AddCoordinateAxisUnitMarks(strokes, origin, xAxisStart, xAxisEnd, CoordinateCentimeterUnitLength, new Vector(0, 1)); + AddCoordinateAxisUnitMarks(strokes, origin, yAxisStart, yAxisEnd, CoordinateCentimeterUnitLength, new Vector(1, 0)); + if (zAxisEnd is Point zEnd) + AddCoordinateAxisUnitMarks(strokes, origin, origin, zEnd, CoordinateCentimeterUnitLength, new Vector(1, 1)); + } + + private void AddCoordinateAxisUnitMarks(StrokeCollection strokes, Point origin, Point axisStart, Point axisEnd, + double unitLength, Vector tickDirection) + { + var axisVector = axisEnd - origin; + var axisLength = axisVector.Length; + if (axisLength < 0.01) return; + + axisVector.Normalize(); + if (tickDirection.Length < 0.01) + tickDirection = new Vector(-axisVector.Y, axisVector.X); + tickDirection.Normalize(); + + for (var distance = unitLength; distance <= axisLength; distance += unitLength) + { + var positiveUnitPoint = origin + axisVector * distance; + if (IsPointOnSegment(positiveUnitPoint, axisStart, axisEnd)) + strokes.Add(GenerateLineStroke(positiveUnitPoint - tickDirection * 5, positiveUnitPoint + tickDirection * 5)); + + var negativeUnitPoint = origin - axisVector * distance; + if (IsPointOnSegment(negativeUnitPoint, axisStart, axisEnd)) + strokes.Add(GenerateLineStroke(negativeUnitPoint - tickDirection * 5, negativeUnitPoint + tickDirection * 5)); + } + } + + private bool IsPointOnSegment(Point point, Point segmentStart, Point segmentEnd) + { + const double tolerance = 0.5; + return point.X >= Math.Min(segmentStart.X, segmentEnd.X) - tolerance && + point.X <= Math.Max(segmentStart.X, segmentEnd.X) + tolerance && + point.Y >= Math.Min(segmentStart.Y, segmentEnd.Y) - tolerance && + point.Y <= Math.Max(segmentStart.Y, segmentEnd.Y) + tolerance; + } + + private Stroke GenerateLineStroke(Point st, Point ed) + { + var pointList = new List(); + StylusPointCollection point; + Stroke stroke; + pointList = new List { + new Point(st.X, st.Y), + new Point(ed.X, ed.Y) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + return stroke; + } + + private Stroke GenerateArrowLineStroke(Point st, Point ed) + { + var pointList = new List(); + StylusPointCollection point; + Stroke stroke; + + double w = 20, h = 7; + var theta = Math.Atan2(st.Y - ed.Y, st.X - ed.X); + var sint = Math.Sin(theta); + var cost = Math.Cos(theta); + + pointList = new List { + new Point(st.X, st.Y), + new Point(ed.X, ed.Y), + new Point(ed.X + (w * cost - h * sint), ed.Y + (w * sint + h * cost)), + new Point(ed.X, ed.Y), + new Point(ed.X + (w * cost + h * sint), ed.Y - (h * cost - w * sint)) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + return stroke; + } + + + private StrokeCollection GenerateDashedLineStrokeCollection(Point st, Point ed) + { + double step = 5; + var pointList = new List(); + StylusPointCollection point; + Stroke stroke; + var strokes = new StrokeCollection(); + var d = GetDistance(st, ed); + var sinTheta = (ed.Y - st.Y) / d; + var cosTheta = (ed.X - st.X) / d; + for (var i = 0.0; i < d; i += step * 2.76) + { + pointList = new List { + new Point(st.X + i * cosTheta, st.Y + i * sinTheta), + new Point(st.X + Math.Min(i + step, d) * cosTheta, st.Y + Math.Min(i + step, d) * sinTheta) + }; + point = new StylusPointCollection(pointList); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + } + + return strokes; + } + + private StrokeCollection GenerateDotLineStrokeCollection(Point st, Point ed) + { + double step = 3; + var pointList = new List(); + StylusPointCollection point; + Stroke stroke; + var strokes = new StrokeCollection(); + var d = GetDistance(st, ed); + var sinTheta = (ed.Y - st.Y) / d; + var cosTheta = (ed.X - st.X) / d; + for (var i = 0.0; i < d; i += step * 2.76) + { + var stylusPoint = new StylusPoint(st.X + i * cosTheta, st.Y + i * sinTheta, (float)0.8); + point = new StylusPointCollection(); + point.Add(stylusPoint); + stroke = new Stroke(point) + { + DrawingAttributes = da.Clone() + }; + strokes.Add(stroke.Clone()); + } + + return strokes; + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkBench.cs b/InkCanvas.Calibration.Tests/UInk/UInkBench.cs new file mode 100644 index 000000000..a00fbbb81 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkBench.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Security.Cryptography; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkBench + { + private const int PointsPerInk = 200; + private const int PngSize = 512; + private static readonly DateTimeOffset ArchiveTime = new(2026, 11, 24, 0, 0, 0, TimeSpan.Zero); + + private readonly record struct Workload(string Name, uint Pages, uint InksPerPage, bool Media); + private readonly record struct Sample(double TotalMs, UInkTestTimings Stages, long AllocatedBytes); + + public static int Run(string outDir, int rounds, ushort version) + { + var suite = new UInkSuite("bench"); + if (!suite.Test("OutputDirectory", _ => Directory.CreateDirectory(outDir))) return suite.Finish(); + + var workloads = new[] + { + new Workload("A-single-page", 1, 5000, false), + new Workload("B-whiteboard", 50, 100, false), + new Workload("C-whiteboard-media", 50, 100, true), + }; + var rows = new List(); + foreach (var workload in workloads) + suite.Test(workload.Name, c => Measure(c, outDir, workload, rounds, version, rows)); + + Console.WriteLine(FormattableString.Invariant($"UInk {version}, {rounds} measured rounds after 1 warm-up (median / max)")); + Console.WriteLine("| Workload | Total ms | Read bytes ms | Decode ms | Map to pages ms | Build strokes ms | Current-thread bytes |"); + Console.WriteLine("| --- | ---: | ---: | ---: | ---: | ---: | ---: |"); + foreach (string row in rows) Console.WriteLine(row); + return suite.Finish(); + } + + private static void Measure(UInkChecks c, string outDir, Workload workload, int rounds, + ushort version, List rows) + { + string path = Path.Combine(outDir, FormattableString.Invariant($"uink-bench-v{version}-{workload.Name}.uink")); + Generate(path, workload, version); + CheckLoad(c, UInkTestApi.LoadTimed(path).Result, workload, version); + + var samples = new Sample[rounds]; + for (int i = 0; i < samples.Length; i++) + { + var clock = new Stopwatch(); + long before = GC.GetAllocatedBytesForCurrentThread(); + clock.Start(); + var (result, stages) = UInkTestApi.LoadTimed(path); + clock.Stop(); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + samples[i] = new Sample(clock.Elapsed.TotalMilliseconds, stages, allocated); + c.That(result.Status != UInkTestStatus.Rejected, $"round {i + 1} rejected: {result.Error}"); + } + + rows.Add($"| {workload.Name} | {Summary(samples, s => s.TotalMs)} | " + + $"{Summary(samples, s => s.Stages.ReadBytesMs)} | {Summary(samples, s => s.Stages.DecodeMs)} | " + + $"{Summary(samples, s => s.Stages.MapToPagesMs)} | {Summary(samples, s => s.Stages.BuildStrokesMs)} | " + + $"{Summary(samples, s => s.AllocatedBytes, "F1")} |"); + } + + private static void CheckLoad(UInkChecks c, UInkTestLoadResult result, Workload workload, ushort version) + { + c.That(result.Status != UInkTestStatus.Rejected, "warm-up rejected: " + result.Error); + c.Equal(version, result.HeaderVersion, "benchmark version"); + c.Equal((int)workload.Pages, result.Pages.Count, "benchmark page count"); + int inks = 0, points = 0, media = 0; + foreach (var page in result.Pages) + foreach (var item in page.Items) + { + if (item.Kind == UInkTestItemKind.Ink) + { + inks++; + points += item.PointCount; + } + else if (item.Kind == UInkTestItemKind.Media && item.MediaResourceAvailable) media++; + } + c.Equal((int)(workload.Pages * workload.InksPerPage), inks, "benchmark inks"); + c.Equal(1_000_000, points, "benchmark points"); + c.Equal(workload.Media ? (int)workload.Pages : 0, media, "benchmark media resources"); + } + + private static string Summary(Sample[] samples, Func value, string format = "F3") + { + double[] sorted = samples.Select(value).ToArray(); + Array.Sort(sorted); + int mid = sorted.Length / 2; + double median = (sorted.Length % 2 != 0) ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; + return median.ToString(format, System.Globalization.CultureInfo.InvariantCulture) + " / " + + sorted[^1].ToString(format, System.Globalization.CultureInfo.InvariantCulture); + } + + private static void Generate(string path, Workload workload, ushort version) + { + var resources = workload.Media ? WriteResources(path + ".extra", (int)workload.Pages) : null; + using var stream = File.Create(path); + var encoder = new UInkTestEncoder(stream); + bool whiteboard = workload.Pages > 1; + encoder.Header(version, workload.Pages); + if (whiteboard) encoder.HeaderExtension(); + + // 重用点缓冲区。每页编号从 0 开始,媒体与每条 Ink 各自一个撤回组。 + var points = new UInkTestPoint[PointsPerInk]; + for (uint page = 0; page < workload.Pages; page++) + { + encoder.Canvas(page, whiteboard); + uint firstInkId = 0; + if (resources != null) + { + encoder.Media(0, 0, resources[(int)page]); + firstInkId = 1; + } + + for (uint ink = 0; ink < workload.InksPerPage; ink++) + { + float x0 = (ink % 16) * 50; + float y0 = (ink % 64) * 12; + for (int point = 0; point < points.Length; point++) + points[point] = new UInkTestPoint(x0 + point * 1.5f, y0 + point % 12, 4 + point % 5); + uint id = firstInkId + ink; + encoder.Ink(id, id, 0x3666D9, points); + } + } + } + + public static void WriteResources(string path, string[] names) => WriteResources(path, names.Length, names); + + private static string[] WriteResources(string path, int count, string[] names = null) + { + var paths = new string[count]; + var pixels = new byte[PngSize * PngSize * 4]; + using var stream = File.Create(path); + using var archive = new ZipArchive(stream, ZipArchiveMode.Create); + for (int image = 0; image < count; image++) + { + byte[] png = EncodePng(pixels, image); + string name = names == null ? "media/" + Convert.ToHexString(SHA256.HashData(png)).ToLowerInvariant() + ".png" : names[image]; + paths[image] = name; + // PNG 已压缩,固定归档时间以便重复生成同一组素材。 + var entry = archive.CreateEntry(name, CompressionLevel.NoCompression); + entry.LastWriteTime = ArchiveTime; + using var entryStream = entry.Open(); + entryStream.Write(png, 0, png.Length); + } + return paths; + } + + private static byte[] EncodePng(byte[] pixels, int image) + { + for (int y = 0; y < PngSize; y++) + for (int x = 0; x < PngSize; x++) + { + int at = (y * PngSize + x) * 4; + pixels[at] = (byte)(x ^ y); + pixels[at + 1] = (byte)(y + image); + pixels[at + 2] = (byte)(x * 3 + image * 17); + pixels[at + 3] = 255; + } + + var bitmap = BitmapSource.Create(PngSize, PngSize, 96, 96, PixelFormats.Bgra32, null, pixels, PngSize * 4); + var encoder = new PngBitmapEncoder(); + encoder.Frames.Add(BitmapFrame.Create(bitmap)); + using var stream = new MemoryStream(); + encoder.Save(stream); + return stream.ToArray(); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkCaptureTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkCaptureTests.cs new file mode 100644 index 000000000..868cccebd --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkCaptureTests.cs @@ -0,0 +1,184 @@ +using Ink_Canvas; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkCaptureTests + { + internal static void Register(UInkSuite suite) + { + UInkReplayAndSaveTests.Register(suite); + suite.Test(nameof(HistoryEditsAreReadOnly), HistoryEditsAreReadOnly); + suite.Test(nameof(CaptureSaveOpen), CaptureSaveOpen); + suite.Test(nameof(WhiteboardCapacityFirstPage), WhiteboardCapacityFirstPage); + suite.Test(nameof(InterleavedInsertionIntervals), InterleavedInsertionIntervals); + } + + private static Stroke Dot(int x) => new(new StylusPointCollection { new StylusPoint(x, 10) }); + private static StrokeCollection Batch(params Stroke[] strokes) => new(strokes); + private static UInkPageInput Page(uint index) => new() + { + Canvas = UInkIccMapper.BuildCanvas(UInkTestEncoder.WorkspaceGuid, "", UInkTestEncoder.PageGuid(index), + index, index + 1, null, null) + }; + + private static void HistoryEditsAreReadOnly(UInkChecks c) + { + var machine = new TimeMachine(); + var original = Dot(1); + var shape = Dot(2); + var remnant = Dot(3); + var extra = Dot(4); + var changed = Dot(42).StylusPoints; + var da = new DrawingAttributes { Width = 8 }; + machine.CommitStrokeUserInputHistory(Batch(original)); + machine.CommitStrokeShapeHistory(Batch(original), Batch(shape, extra)); + machine.CommitStrokeEraseHistory(Batch(shape), Batch(remnant)); + machine.CommitStrokeManipulationHistory(new Dictionary> + { [extra] = Tuple.Create(extra.StylusPoints, changed) }); + machine.CommitStrokeDrawingAttributesHistory(new Dictionary> + { [extra] = Tuple.Create(extra.DrawingAttributes, da) }); + machine.CommitStrokeEraseHistory(Batch(extra, remnant)); + machine.Undo(); + var entries = machine.GetAppliedHistorySnapshot(); + var page = Page(0); + MainWindow.CaptureUInkPage(page, entries, null, null); + c.That(machine.CanRedo && entries.Length == 5, "capture preserves the redo branch"); + c.Equal(2, page.Strokes.Count, "only surviving shape output and eraser remnant"); + c.Near(42, page.Strokes[0].StylusPoints[0].X, "fold final geometry"); + c.Near(8, page.Strokes[0].DrawingAttributes.Width, "fold final attributes"); + c.Near(4, extra.StylusPoints[0].X, "history source never mutated"); + c.That(!ReferenceEquals(changed, page.Strokes[0].StylusPoints) && + !ReferenceEquals(da, page.Strokes[0].DrawingAttributes), "background owns the copies"); + c.That(page.StrokeOwners.SequenceEqual(new[] { 1, 2 }), "shape and eraser own their outputs"); + machine.Redo(); + page = Page(0); + MainWindow.CaptureUInkPage(page, machine.GetAppliedHistorySnapshot(), null, null); + c.Equal(0, page.Strokes.Count, "fully erased inactive page stays empty"); + } + + private static void CaptureSaveOpen(UInkChecks c) + { + string dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).FullName; + try + { + var hidden = new Image(); + var photo = new Image { Width = 12, Height = 14 }; + string file = Path.Combine(dir, "pixel.png"); + var encoder = new PngBitmapEncoder(); + var bitmap = BitmapSource.Create(1, 1, 96, 96, PixelFormats.Bgra32, null, new byte[4], 4); + encoder.Frames.Add(BitmapFrame.Create(bitmap)); + using (var stream = File.Create(file)) encoder.Save(stream); + var loaded = new BitmapImage(); + loaded.BeginInit(); + loaded.UriSource = new Uri(file); + loaded.CacheOption = BitmapCacheOption.OnLoad; + loaded.EndInit(); + photo.Source = loaded; + + var pen = Dot(11); + var machine = new TimeMachine(); + machine.CommitStrokeUserInputHistory(Batch(pen)); + machine.CommitElementInsertHistory(photo); + machine.CommitElementRemoveHistory(photo); + machine.CommitElementInsertHistory(hidden); + machine.CommitElementRemoveHistory(hidden); + machine.CommitElementInsertHistory(photo); + var applied = machine.GetAppliedHistorySnapshot(); + var other = Page(0); + MainWindow.CaptureUInkPage(other, applied, null, null); + c.Equal(1, other.Elements.Count, "last insertion wins, last removal stays absent"); + c.That(other.Elements[0].Bitmap.IsFrozen && other.Elements[0].Owner == 5, "frozen image and reinsertion owner"); + var live = Page(1); + MainWindow.CaptureUInkPage(live, applied, new StrokeCollection(), Array.Empty()); + c.Equal(0, live.Elements.Count, "stale slot cannot restore removed current-page children"); + + var context = new UInkCaptureContext + { + DpiX = 1, DpiY = 1, Workspace = new UInkWorkspace { Guid = UInkTestEncoder.WorkspaceGuid, + WorkspaceType = (int)UInkWorkspaceType.Whiteboard, CurrentPageIndex = 1 } + }; + context.Pages.Add(other); + context.Pages.Add(live); + string target = Path.Combine(dir, "snapshot.uink"); + context.Save(target, true); + var read = UInkReader.Read(target, new UInkReadOptions { MaterializeContent = false }); + var reopened = UInkIccMapper.BuildPageIndex(read, 1, 1); + c.Equal(1, reopened.CurrentPageDisplayIndex, "restored active page"); + c.Equal(0, reopened.Pages[1].FinalStrokes.Count, "empty live page wins over stale history"); + c.That(!reopened.Pages[0].IsMaterialized, "sibling is lazy"); + // 未访问的页也必须能立即另存,且后台导出不能消费 UI 的首次安装。 + string copy = Path.Combine(dir, "copy.uink"); + using (var cache = UInkMediaRestoreCache.Open(target, Path.Combine(dir, "cache"))) + { + var deferred = new UInkCaptureContext { Workspace = context.Workspace, DpiX = 1, DpiY = 1, Resources = cache }; + var pending = Page(0); + pending.DecodePending = reopened.Pages[0].Materialize; + deferred.Pages.Add(pending); + deferred.Pages.Add(live); + deferred.Save(copy, true); + } + c.That(!reopened.Pages[0].IsMaterialized, "export did not consume deferred install"); + var copied = UInkReader.Read(copy); + c.Equal(2, copied.Document.Canvases[0].Blocks.Count, "unvisited page copied to another file"); + c.That(copied.Document.Canvases[0].Blocks[0] is UInkMedia, "deferred resource remains first"); + reopened.Pages[0].EnsureMaterialized(); + var items = reopened.Pages[0].Items; + c.Equal(2, items.Count, "surviving media and ink"); + c.That(items[0].Block is UInkMedia && items[1].Block is UInkInk, "native layer order on wire"); + c.That(items[0].Group != items[1].Group, "independent insertions undo independently"); + using (var archive = new UInkExtraArchive(target + ".extra")) + c.Equal(1, archive.EntryCount, "inactive page resource committed"); + string guid = read.Document.Header.Guid; + context.Save(target, false); + c.That(UInkReader.Read(target).Document.Header.Guid != guid, "new snapshot identity for each save"); + c.Equal(UInkTestEncoder.PageGuid(0), reopened.Pages[0].Canvas.PageGuid, "retained page identity"); + } + finally { Directory.Delete(dir, true); } + } + + private static void WhiteboardCapacityFirstPage(UInkChecks c) + { + var workspace = new UInkWorkspace { Guid = UInkTestEncoder.WorkspaceGuid, + WorkspaceType = (int)UInkWorkspaceType.Whiteboard, CurrentPageIndex = 99 }; + var pages = new List(); + for (uint i = 0; i < 100; i++) pages.Add(Page(i)); + var document = UInkIccMapper.BuildDocument(UInkTestEncoder.HeaderGuid, null, new[] { workspace }, pages, 0); + using var stream = new MemoryStream(); + UInkWriter.Save(document, stream); + var read = UInkReader.Read(stream.ToArray(), new UInkReadOptions { MaterializeContent = false }); + var projection = UInkPageProjection.Build(read, 1, 1, null, UInkConversion.BlockToStroke, whiteboardLimit: 99); + c.Equal(100, projection.Pages.Count, "overflow page retained in index"); + c.Equal(0, projection.CurrentPageDisplayIndex, "overflow selection falls back to first visible page"); + c.That(projection.Pages[0].IsMaterialized && projection.Pages.Skip(1).All(p => !p.IsMaterialized), + "only installed first page materialized"); + } + + private static void InterleavedInsertionIntervals(UInkChecks c) + { + var a = Dot(1); var b = Dot(2); var c1 = Dot(3); var d = Dot(4); + var laser = Dot(5); + laser.AddPropertyData(InkFadeManager.LaserRenderModeGuid, true); + var history = new[] { new UInkGroupHistory(Batch(a, c1), 0) }; + var page = Page(0); + MainWindow.CaptureUInkPage(page, history, Batch(a, b, laser, c1, d), Array.Empty()); + var doc = UInkIccMapper.BuildDocument(UInkTestEncoder.HeaderGuid, null, null, new[] { page }, 0); + var blocks = doc.Canvases[0].Blocks; + c.That(blocks.Select(x => x.UndoId).SequenceEqual(new uint[] { 0, 0, 0, 1 }), "A,B,A joins exactly the overlap"); + c.That(blocks.Select(x => x.ContentId).SequenceEqual(new uint[] { 0, 1, 2, 3 }), "laser consumes no ID"); + c.That(blocks.Cast().Select(x => x.Points[0].X).SequenceEqual(new float[] { 1, 2, 3, 4 }), + "merge only changes undo grouping, never drawing order"); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkCodecCases.cs b/InkCanvas.Calibration.Tests/UInk/UInkCodecCases.cs new file mode 100644 index 000000000..02df66cee --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkCodecCases.cs @@ -0,0 +1,444 @@ +using System; +using System.Buffers; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.ExceptionServices; +using Ink_Canvas.UInk; +using MessagePack; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkCodecCases + { + private static readonly UInkTestPoint[] Points = { new(1, 2, 3) }; + private static readonly string GuidText = UInkTestEncoder.HeaderGuid; + private static (string, object)[] Map(params (string, object)[] fields) => fields; + private static object Color => Map(("fallback", 0xab4567u)); + + // 独立写测试 wire,保留 Map 键顺序及重复项。 + private static void Pack(ref MessagePackWriter w, object value) + { + switch (value) + { + case ValueTuple[] map: + w.WriteMapHeader(map.Length); + foreach (var (key, v) in map) { w.Write(key); Pack(ref w, v); } + break; + case object[] array: + w.WriteArrayHeader(array.Length); + foreach (var v in array) Pack(ref w, v); + break; + case float f: w.Write(f); break; + case double d: w.Write(d); break; + case ulong u: w.WriteUInt64(u); break; + case uint u32: w.WriteUInt32(u32); break; + case int i: w.WriteInt32(i); break; + case string s: w.Write(s); break; + case bool b: w.Write(b); break; + default: throw new ArgumentException("unsupported test value"); + } + } + + private static void Frame(Stream stream, object fields) + { + var buf = new ArrayBufferWriter(); + var w = new MessagePackWriter(buf); + Pack(ref w, fields); + w.Flush(); + stream.Write(buf.WrittenSpan); + } + + private static byte[] FileBytes(Action body, bool canvas = true) + { + using var ms = new MemoryStream(); + var e = new UInkTestEncoder(ms); + e.Header(11, 1); + if (canvas) e.Canvas(0); + body(ms, e); + return ms.ToArray(); + } + + private static object Ink(object width, object extra, object opacity = null) => Map( + ("points", new object[] { Map(("width", width), ("y", 2), ("x", 3)) }), + ("contentId", 0.0), ("undoId", 0f), ("opacity", opacity ?? 1f), ("texture", 0), + ("color", Color), ("inkType", 1), ("extra", extra), ("type", 3)); + + private static object Shape(object obj, object stroke = null, object geometry = null) => Map( + ("geometry", geometry ?? Map(("centerY", 0), ("centerX", 1), ("width", 5), ("height", 8))), + ("stroke", stroke ?? Map(("color", Color), ("width", 2), ("opacity", 1))), + ("shapeType", 2), ("object", obj), ("contentId", 0), ("undoId", 0), ("type", 5)); + + internal static int Run() + { + var suite = new UInkSuite("codec robustness"); + suite.Test("ExactNumericAndExtra", ExactNumericAndExtra); + suite.Test("ShapeOrderAndObject", ShapeOrderAndObject); + suite.Test("RegistryOrderAndIdentifiers", RegistryOrderAndIdentifiers); + suite.Test("File8IdentityAfterRegistryRepair", File8IdentityAfterRegistryRepair); + suite.Test("ScopeAndLazyReplacement", ScopeAndLazyReplacement); + suite.Test("ClearNeighbours", ClearNeighbours); + suite.Test("ClearNeighboursWithCorruptBodies", ClearNeighboursWithCorruptBodies); + suite.Test("DepthAndLengthLimits", DepthAndLengthLimits); + suite.Test("DenseFramedScalarsStopAtObjectLimit", DenseFramedScalarsStopAtObjectLimit); + suite.Test("CumulativeCanvasAndContentIndexLimits", CumulativeCanvasAndContentIndexLimits); + suite.Test("FieldFallbacks", FieldFallbacks); + suite.Test("VisualMediaTransformAndPageCount", VisualMediaTransformAndPageCount); + suite.Test("InapplicableFieldsAndExactCornerBound", InapplicableFieldsAndExactCornerBound); + suite.Test("CanvasAndNibFallbacks", CanvasAndNibFallbacks); + suite.Test("BoundedPrivateStrings", BoundedPrivateStrings); + return suite.Finish(); + } + + private static void ExactNumericAndExtra(UInkChecks c) + { + object extra = Map(("icc:keep", "yes"), ("not:icc", "no"), ("icc:object", new object[] { 7, Map(("x", 5)) })); + foreach (var width in new object[] { 16777217, 9007199254740993UL, ulong.MaxValue, 0.1d, float.NaN, + double.PositiveInfinity, float.NegativeInfinity, false, -1, 0f }) + { + var bad = UInkReader.Read(FileBytes((s, e) => { Frame(s, Ink(width, extra)); e.Ink(1, 1, 1, Points); })); + c.Equal(1, bad.SkippedBlocks, $"width {width}"); + c.That(bad.RequiresSaveAs && bad.Document.Canvases.Single().Blocks.Single().ContentId == 1, "recovery continues"); + } + var good = UInkReader.Read(FileBytes((s, e) => + { + Frame(s, Ink(16777216, extra, 1.5)); + Frame(s, Ink(0.5d, false)); + Frame(s, Map(("type", 6), ("contentId", 0.25), ("undoId", 2))); + Frame(s, Map(("type", 6), ("contentId", -1), ("undoId", 2))); + Frame(s, Map(("type", 6), ("contentId", 4294967296d), ("undoId", 2))); + })); + var inks = good.Document.Canvases.Single().Blocks.Cast().ToArray(); + c.Equal(3, good.SkippedBlocks, "nonintegral/out-of-range ID"); + c.Equal(2, inks.Length, "valid widths"); + c.Equal(1, inks[0].Extra.Count, "private projection"); + c.Equal("yes", inks[0].Extra["icc:keep"], "private string"); + c.Equal(16777216f, inks[0].Points[0].Width, "exact integer to float"); + c.Equal(1f, inks[0].Opacity, "INK-18"); + c.That(inks[1].Extra == null, "wrong extra type ignored"); + foreach (object time in new object[] { (1UL << 53) + 1, ulong.MaxValue, 9223372036854775808d, 18446744073709551616d }) + { + using var stream = new MemoryStream(); + Frame(stream, new object[] { 0, 11d, GuidText, 1, 1, 0, time }); + var read = UInkReader.Read(stream.ToArray()); + if (time is double d && d >= 18446744073709551616d) c.Equal(UInkReadStatus.Rejected, read.Status, "2^64"); + else c.Equal(time is ulong n ? n : 1UL << 63, read.Document.Header.Time, "exact uint64 time"); + } + var media = UInkReader.Read(FileBytes((s, _) => Frame(s, Map(("path", "a"), ("mimeType", "audio/wav"), + ("type", 4), ("undoId", 0), ("contentId", 0), ("startTime", 9007199254740993UL))))); + c.Equal(1, media.SkippedBlocks, "2^53+1 not exact as float64"); + } + + private static void ShapeOrderAndObject(UInkChecks c) + { + var result = UInkReader.Read(FileBytes((s, e) => + { + Frame(s, Shape(Map(("id", GuidText), ("partCount", 1), ("revision", ulong.MaxValue)))); + Frame(s, Shape(Map(("id", GuidText), ("partCount", 1), ("revision", 1), ("revision", 2)))); + Frame(s, Shape(Map(("id", GuidText), ("partCount", 1), ("revision", 1)), + Map(("color", Map(("fallback", 1), ("fallback", 2))), ("opacity", 1), ("width", 2)))); + })); + var shapes = result.Document.Canvases.Single().Blocks.Cast().ToArray(); + c.Equal(2, result.SkippedBlocks, "TYPE-7 nested object or color invalidates whole Shape"); + c.Equal(2, result.DiagnosticCounts["TYPE-7"], "both nested duplicates diagnosed"); + c.Equal(1, shapes.Length, "only valid Shape survives"); + c.Equal(ulong.MaxValue, shapes[0].Object.Revision, "revision"); + c.That(shapes[0].Geometry is UInkRectGeometry { Width: 5 }, "order and duplicate object"); + } + + private static void RegistryOrderAndIdentifiers(UInkChecks c) + { + string other = UInkTestEncoder.WorkspaceGuid; + var result = UInkReader.Read(FileBytes((s, e) => Frame(s, Map(("devices", new object[] { + Map(("x", -5), ("y", 0), ("width", 64), ("height", 64), ("guid", GuidText), ("deviceType", 0), + ("hardware", Map(("identifiers", Map(("serial", "abc"), ("number", 3)))))), + Map(("width", 1.5), ("height", 4), ("x", -2.5d), ("y", 0), ("zIndex", 0), + ("guid", other), ("parentDeviceGuid", GuidText), ("deviceType", 1)) }), + ("workspaces", new object[] { Map(("workspaceType", 99), ("guid", GuidText)), Map(("guid", GuidText), ("workspaceType", 1)) }), + ("type", 1))), false)); + var ext = result.Document.HeaderExtension; + c.Equal(2, ext.Devices.Count, "devices"); + c.Equal(1.5f, ext.Devices[1].WindowWidth, "discriminator last"); + c.Equal(1, ext.Devices[0].Hardware.Identifiers.Count, "identifiers"); + c.Equal("abc", ext.Devices[0].Hardware.Identifiers["serial"], "nonprivate key"); + c.Equal(1, ext.Workspaces.Single().WorkspaceType, "HEXT-14 fallback and HEXT-2 duplicate"); + c.That(result.RequiresSaveAs, "registry recovery"); + } + + private static void File8IdentityAfterRegistryRepair(UInkChecks c) + { + string other = UInkTestEncoder.WorkspaceGuid; + foreach (bool varyingWorkspace in new[] { true, false }) + { + var result = UInkReader.Read(FileBytes((s, e) => + { + Frame(s, Map(("type", 1), ("workspaces", new object[] { Map(("guid", "invalid"), ("workspaceType", 0)) }), + ("devices", new object[] { Map(("guid", "invalid"), ("deviceType", 0)) }))); + void Canvas(string id, uint revision) + { + Frame(s, Map(("type", 2), ("pageGuid", UInkTestEncoder.PageGuid(0)), ("pageIndex", 0), + ("pageNumber", revision), ("layerIndex", 0), ("layerNumber", 0), + ("workspaceGuid", varyingWorkspace ? id : GuidText), ("deviceGuid", varyingWorkspace ? GuidText : id))); + } + Canvas(GuidText, 1); Canvas(other, 2); Canvas(GuidText.ToUpperInvariant(), 3); + }, false)); + var ext = result.Document.HeaderExtension; + c.That(ext.Workspaces.Count == 0 && ext.Devices.Count == 0, "both registries fully repaired"); + var pages = result.Document.Canvases; + c.That(pages.Select(p => p.Canvas.PageNumber).SequenceEqual(new[] { 2u, 3u }), + "different GUIDs survive and a case variant supersedes its first version"); + c.Equal(1, result.DiagnosticCounts["FILE-8"], "one replacement"); + c.Equal(GuidText, varyingWorkspace ? pages[1].Canvas.WorkspaceGuid : pages[1].Canvas.DeviceGuid, "normalized GUID"); + } + + var implicitResult = UInkReader.Read(FileBytes((s, _) => + { + Frame(s, Map(("type", 1), ("workspaces", Array.Empty()), ("devices", Array.Empty()))); + foreach (string id in new[] { GuidText, other }) + Frame(s, Map(("type", 2), ("pageGuid", UInkTestEncoder.PageGuid(0)), ("pageIndex", 0), + ("pageNumber", 1), ("layerIndex", 0), ("layerNumber", 0), ("workspaceGuid", id), ("deviceGuid", id))); + }, false)); + c.Equal(1, implicitResult.Document.Canvases.Count, "empty registries still imply an empty key"); + c.Equal(1, implicitResult.DiagnosticCounts["FILE-8"], "different GUIDs share the implicit key"); + } + + private static void ScopeAndLazyReplacement(UInkChecks c) + { + var bytes = FileBytes((s, e) => + { + e.Clear(0, 0); e.HeaderExtension(); e.Canvas(0); + e.Ink(0, 0, 1, Points, UInkTestInkFault.InvalidWidth); + e.Canvas(0); e.Ink(0, 0, 3, Points); + Frame(s, Map(("pageGuid", "bad"), ("type", 2))); + e.Ink(0, 0, 4, Points); e.Canvas(1); e.Clear(0, 0); + }, false); + var result = UInkReader.Read(bytes, new UInkReadOptions { MaterializeContent = false }); + c.Equal(4, result.SkippedBlocks, "early content, late extension, bad Canvas and orphan"); + c.Equal(1, result.DiagnosticCounts["FILE-8"], "superseded"); + var pages = result.Document.Canvases; + c.Equal(2, pages.Count, "winners"); + c.Equal(0, pages[0].Blocks.Count, "lazy index"); + UInkReader.MaterializeContent(pages[1]); UInkReader.MaterializeContent(pages[0]); UInkReader.MaterializeContent(pages[0]); + c.Equal(3u, ((UInkInk)pages[0].Blocks.Single()).Color.Fallback, "winner contents"); + c.That(pages[1].Blocks.Single() is UInkClear, "CLEAR-11 empty Canvas Clear"); + c.Equal(4, result.SkippedBlocks, "superseded malformed points never decoded"); + } + + private static void ClearNeighbours(UInkChecks c) + { + var result = UInkReader.Read(FileBytes((s, e) => + { + e.Ink(0, 0, 1, Points); e.Clear(1, 0); e.Clear(2, 1); e.Ink(3, 1, 2, Points); e.Clear(4, 2); + })); + var blocks = result.Document.Canvases[0].Blocks; + c.Equal(2, result.SkippedBlocks, "both neighboring directions invalidate Clear"); + c.That(result.RequiresSaveAs && blocks.OfType().Single().ContentId == 4, "CLEAR-12/13"); + } + + private static void ClearNeighboursWithCorruptBodies(UInkChecks c) + { + var result = UInkReader.Read(FileBytes((s, e) => + { + e.Clear(0, 0); + e.Ink(1, 0, 2, Points, UInkTestInkFault.InvalidWidth); + e.Ink(2, 1, 3, Points, UInkTestInkFault.InvalidWidth); + e.Clear(3, 1); + e.Ink(4, 2, 4, Points); + })); + c.Equal(2, result.DiagnosticCounts["CLEAR-12"], "invalid body on either side still supplies its undo ID"); + c.Equal(2, result.DiagnosticCounts["FILE-19"], "invalid points were skipped"); + c.Equal(4u, result.Document.Canvases.Single().Blocks.Single().ContentId, "only unrelated valid Ink remains"); + + var noCrossing = UInkReader.Read(FileBytes((s, e) => + { + e.Ink(0, 0, 1, Points); + Frame(s, Map(("type", 3), ("contentId", 1), ("undoId", false))); + e.Clear(2, 0); + e.Ink(3, 1, 2, Points); + })); + c.That(noCrossing.Document.Canvases.Single().Blocks.OfType().Any(), + "Clear must not compare against an earlier non-neighbor when the physical neighbor has no readable ID"); + } + + private static void DenseFramedScalarsStopAtObjectLimit(UInkChecks c) + { + byte[] prefix = FileBytes((s, e) => e.Ink(0, 0, 1, Points)); + byte[] bytes = new byte[prefix.Length + 1_000_000]; // 每个 0x00 都是完整的 MessagePack 正整数。 + prefix.CopyTo(bytes, 0); + int exceptions = 0, thread = Environment.CurrentManagedThreadId; + void Observe(object sender, FirstChanceExceptionEventArgs args) + { + if (Environment.CurrentManagedThreadId == thread) exceptions++; + } + _ = UInkReader.Read(prefix); // 只计密集输入本身的耗时。 + UInkReadResult result; + var timer = new Stopwatch(); + AppDomain.CurrentDomain.FirstChanceException += Observe; + try + { + timer.Start(); + result = UInkReader.Read(bytes); + timer.Stop(); + } + finally { AppDomain.CurrentDomain.FirstChanceException -= Observe; } + const int expectedScalars = 250_000 - 3; // Header、Canvas 和有效 Ink 占三个顶层对象。 + c.That(result.LimitExceeded && result.RequiresSaveAs && result.Status == UInkReadStatus.Recovered, "object budget"); + c.Equal(expectedScalars, result.SkippedBlocks, "bounded scalar count"); + c.Equal(prefix.Length + expectedScalars, result.FailureOffset, "first unprocessed object"); + c.Equal(1, result.Document.Canvases.Single().Blocks.Count, "prefix retained"); + c.Equal(0, exceptions, "no exceptions during scalar classification"); + c.That(timer.Elapsed < TimeSpan.FromSeconds(2), $"scalar scan duration: {timer.Elapsed.TotalMilliseconds:F0} ms"); + } + + private static void CumulativeCanvasAndContentIndexLimits(UInkChecks c) + { + var canvases = FileBytes((s, e) => + { + for (int i = 0; i < 16_384; i++) e.Canvas(0); + e.Canvas(1); + }, false); + var result = UInkReader.Read(canvases); + c.That(result.LimitExceeded && result.Status == UInkReadStatus.Recovered && + result.DiagnosticCounts.ContainsKey("canvas-count-limit"), "cumulative canvas cap counts superseded records"); + c.Equal(16_384, result.Document.Canvases.Single().StreamOrdinal, "last in-budget Canvas wins"); + + long stop = 0; + byte[] frame = { 0x81, 0xa4, (byte)'t', (byte)'y', (byte)'p', (byte)'e', 3 }; + var content = FileBytes((s, e) => + { + for (int i = 0; i < 200_000; i++) + { + if (i == 100_000) e.Canvas(1); + s.Write(frame); + } + stop = s.Position; + s.Write(frame); + e.Canvas(2); + }); + result = UInkReader.Read(content, new UInkReadOptions { MaterializeContent = false }); + c.That(result.LimitExceeded && result.Status == UInkReadStatus.Recovered && + result.DiagnosticCounts.ContainsKey("content-index-limit"), "frame limit is shared across canvases"); + c.Equal(stop, result.FailureOffset, "first over-budget content frame"); + c.That(result.Document.Canvases.Select(p => p.Frames.Count).SequenceEqual(new[] { 100_000, 100_000 }), "bounded prefix index"); + } + + private static void DepthAndLengthLimits(UInkChecks c) + { + foreach (var tail in new[] { Enumerable.Repeat((byte)0x91, 34).Concat(new byte[] { 0 }).ToArray(), + new byte[] { 0xdb, 0, 0x80, 0, 1 }, new byte[] { 0xdd, 0, 0x10, 0, 0 } }) + { + var result = UInkReader.Read(FileBytes((s, e) => s.Write(tail))); + c.That(result.LimitExceeded && result.RequiresSaveAs && !result.TruncatedTail, "budget precedes allocation"); + c.Equal(1, result.Document.Canvases.Count, "valid prefix"); + } + } + + private static void CanvasAndNibFallbacks(UInkChecks c) + { + object Canvas(int layer, object viewport) => Map(("type", 2), ("pageGuid", GuidText), ("pageIndex", 0), + ("pageNumber", 1), ("layerIndex", layer), ("layerNumber", layer), ("viewport", viewport), + ("background", Map(("color", Map(("fallback", false))))), ("pageKind", 99), ("binding", -1), ("pageState", 50)); + var fields = ((ValueTuple[])Ink(2, Map())).Append(("nib", (object)Map(("shape", 1), ("aspect", double.NaN)))).ToArray(); + var result = UInkReader.Read(FileBytes((s, e) => + { + Frame(s, Canvas(0, Map(("scale", 1), ("x", 5)))); + Frame(s, fields); + Frame(s, Canvas(1, Map(("scale", 1), ("x", 3), ("y", 4)))); + }, false)); + var pages = result.Document.Canvases; + c.Equal(2, pages.Count, "two layers"); + var root = pages[0].Canvas; + c.That(root.Viewport == null && root.Background == null, "CANVAS-22 and invalid background"); + c.That(root.PageKind == 0 && root.Binding == 0 && root.PageState == 0, "CANVAS-12"); + c.That(pages[1].Canvas.PageKind == null && pages[1].Canvas.Viewport == null, "CANVAS-8"); + c.That(((UInkInk)pages[0].Blocks.Single()).Nib == null && result.RequiresSaveAs, "NIB-6"); + } + + private static void BoundedPrivateStrings(UInkChecks c) + { + var extra = Map(("icc:large", new string('a', 65537)), ("icc:small", "value")); + var read = UInkReader.Read(FileBytes((s, e) => Frame(s, Ink(1, extra)))); + c.That(read.LimitExceeded && read.RequiresSaveAs && read.SkippedBlocks == 0, "private field budget"); + var ink = (UInkInk)read.Document.Canvases.Single().Blocks.Single(); + c.Equal(1, ink.Extra.Count, "oversized value omitted"); + c.Equal("value", ink.Extra["icc:small"], "later private value"); + } + + private static void VisualMediaTransformAndPageCount(UInkChecks c) + { + var identity = new[] { 1f, 0f, 0f, 1f, 0f, 0f }; + var baseFields = Map(("type", 4), ("contentId", 0), ("undoId", 0), ("path", "a.pdf"), + ("mimeType", "application/pdf"), ("width", 5), ("height", 6)); + UInkReadResult ReadMedia(params (string, object)[] extra) => + UInkReader.Read(FileBytes((s, _) => Frame(s, baseFields.Concat(extra).ToArray()))); + UInkMedia Media(UInkReadResult result) => (UInkMedia)result.Document.Canvases.Single().Blocks.Single(); + + var absent = ReadMedia(); + c.Floats(identity, Media(absent).Transform, "missing transform defaults to identity"); + c.Equal(1, absent.DiagnosticCounts["MEDIA-2"], "missing transform note"); + c.That(!absent.RequiresSaveAs, "legal omission does not require Save As"); + + var malformed = ReadMedia(("transform", false)); + c.Floats(identity, Media(malformed).Transform, "malformed transform defaults to identity"); + c.That(malformed.RequiresSaveAs && malformed.DiagnosticCounts["MEDIA-2"] == 1, "malformed transform is lossy"); + + var zero = ReadMedia(("transform", new object[] { 1, 0, 0, 1, 0, 0 }), ("pageCount", 0)); + c.That(Media(zero).PageCount == null && zero.DiagnosticCounts["MEDIA-9"] == 1, "zero page count ignored and diagnosed"); + + var doc = absent.Document; + Media(absent).Transform = null; + Media(absent).PageCount = 0; + using var stream = new MemoryStream(); + UInkWriter.Save(doc, stream); + var self = UInkReader.Read(stream.ToArray()); + c.Equal(0, self.Diagnostics.Count, "writer explicitly emits the default visual transform"); + c.Floats(identity, Media(self).Transform, "self-produced identity"); + c.Equal(null, Media(self).PageCount, "writer omits an unknown PDF page count"); + } + + private static void InapplicableFieldsAndExactCornerBound(UInkChecks c) + { + var ink = ((ValueTuple[])Ink(1, Map())).Concat(Map( + ("nib", Map(("shape", 1), ("aspect", 1))), ("cap", false))).ToArray(); + var stroke = Map(("color", Color), ("width", 2), ("opacity", 1), ("startMarker", false), + ("endMarker", Map(("unexpected", 0)))); + float epsilon = float.Epsilon; + var geometry = Map(("width", 3 * epsilon), ("height", 3 * epsilon), ("centerX", 0), ("centerY", 0), + ("cornerRadiusX", 2 * epsilon), ("cornerRadiusY", 2 * epsilon)); + var result = UInkReader.Read(FileBytes((s, _) => + { + Frame(s, ink); + Frame(s, Shape(Map(("id", GuidText), ("partCount", 1), ("revision", 1)), stroke, geometry)); + })); + var blocks = result.Document.Canvases.Single().Blocks; + c.Equal(0, result.SkippedBlocks, "irrelevant values cannot invalidate a block"); + c.That(blocks[0] is UInkInk { Cap: null, Nib.Shape: 1 }, "NIB-3 ignores even a malformed cap"); + var shape = (UInkShape)blocks[1]; + c.That(shape.Stroke is { StartMarker: null, EndMarker: null } && + result.DiagnosticCounts["SHAPE-9"] == 1, "SHAPE-9 keeps the stroke and skips malformed markers"); + c.That(shape.Geometry is UInkRectGeometry { CornerRadiusX: null, CornerRadiusY: null } && + result.DiagnosticCounts["SHAPE-3"] == 1, "exact half-width is smaller than the float-rounded half-width"); + } + + private static void FieldFallbacks(UInkChecks c) + { + var stroke = Map(("color", Map(("fallback", 0xffabcdefu), ("components", new object[] { 1, 2 }))), + ("opacity", -2), ("width", 3), ("lineCap", 88), ("dashArray", new object[] { 1, -1 })); + var geom = Map(("width", 4), ("height", 2), ("centerX", 0), ("centerY", 0), ("cornerRadiusX", 5)); + var result = UInkReader.Read(FileBytes((s, e) => + { + Frame(s, Shape(Map(("id", GuidText), ("partCount", 1), ("revision", 1)), stroke, geom)); + Frame(s, Map(("type", 4), ("contentId", 1), ("undoId", 1), ("path", "x"), ("mimeType", "image/png"), + ("width", 4), ("height", 6), ("transform", new object[] { 1, 2 }), ("fit", 20), ("opacity", 2))); + })); + var blocks = result.Document.Canvases.Single().Blocks; + var shape = (UInkShape)blocks[0]; + c.That(((UInkRectGeometry)shape.Geometry).CornerRadiusX == null && shape.Stroke.DashArray == null, "SHAPE-3/7"); + c.Equal(0xabcdefu, shape.Stroke.Color.Fallback, "COLOR-3"); + c.That(shape.Stroke.Color.Components == null && shape.Stroke.Opacity == 0 && shape.Stroke.LineCap == 0, "COLOR-2 NIB-7 SHAPE-23"); + var media = (UInkMedia)blocks[1]; + c.Floats(new float[] { 1, 0, 0, 1, 0, 0 }, media.Transform, "MEDIA-2"); + c.That(media.Fit == 0 && media.Opacity == 1 && result.RequiresSaveAs, "MEDIA-3/12"); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkDefaultSaveTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkDefaultSaveTests.cs new file mode 100644 index 000000000..5fb96400e --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkDefaultSaveTests.cs @@ -0,0 +1,274 @@ +using Ink_Canvas; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; +using Ink_Canvas.Windows.SettingsViews.Helpers; +using Newtonsoft.Json; +using System; +using System.IO; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using System.Runtime.Serialization; +using WpfInkCanvas = System.Windows.Controls.InkCanvas; +using System.Windows.Ink; +using System.Windows.Input; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkDefaultSaveTests + { + internal static void Register(UInkSuite suite) + { + suite.Test(nameof(MigrateUInkDefaultOnce), MigrateUInkDefaultOnce); + suite.Test(nameof(StrokeSaveFormatPriority), StrokeSaveFormatPriority); + suite.Test(nameof(ManualTimedAndScreenshotSaveFormats), ManualTimedAndScreenshotSaveFormats); + suite.Test(nameof(DeleteExpiredUInkPairs), DeleteExpiredUInkPairs); + suite.Test(nameof(RetainRecentAndActiveUInkMedia), RetainRecentAndActiveUInkMedia); + suite.Test(nameof(RecognizeUInkCommandLinePath), RecognizeUInkCommandLinePath); + } + + private static void MigrateUInkDefaultOnce(UInkChecks c) + { + var original = SettingsManager.Settings; + try + { + SettingsManager.Settings = new Settings(); + c.That(SettingsManager.Settings.Automation.IsSaveStrokesAsUInK, "fresh settings use UInk"); + c.That(SettingsManager.Settings.UInkDefaultMigrated, "fresh settings already have the marker"); + c.That(!SettingsManager.MigrateUInkDefaultSaveFormat(), "fresh settings need no migration"); + + foreach (var (automation, expected) in new[] + { + ("{}", true), + ("{\"isSaveStrokesAsUInK\":false}", true), + ("{\"isSaveStrokesAsUInK\":true}", true), + ("{\"isSaveStrokesAsXML\":true}", false), + ("{\"isSaveStrokesAsXML\":true,\"isSaveStrokesAsUInK\":false}", false), + ("{\"isSaveFullPageStrokes\":true}", false), + ("{\"isSaveFullPageStrokes\":true,\"isSaveStrokesAsUInK\":false}", false), + ("{\"isSaveStrokesAsXML\":true,\"isSaveStrokesAsUInK\":true}", true) + }) + { + var settings = JsonConvert.DeserializeObject("{\"automation\":" + automation + "}"); + SettingsManager.Settings = settings; + bool xml = settings.Automation.IsSaveStrokesAsXML; + bool fullPage = settings.Automation.IsSaveFullPageStrokes; + c.That(SettingsManager.MigrateUInkDefaultSaveFormat(), automation + " migrates"); + c.Equal(expected, settings.Automation.IsSaveStrokesAsUInK, automation); + c.Equal(xml, settings.Automation.IsSaveStrokesAsXML, "preserve XML preference"); + c.Equal(fullPage, settings.Automation.IsSaveFullPageStrokes, "preserve full-page preference"); + // 迁移后关闭 UInk 并序列化,再加载应继续保留关闭选择。 + settings.Automation.IsSaveStrokesAsUInK = false; + SettingsManager.Settings = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(settings)); + c.That(SettingsManager.Settings.UInkDefaultMigrated, "persisted migration marker"); + c.That(!SettingsManager.MigrateUInkDefaultSaveFormat(), "marker prevents a second migration"); + c.That(!SettingsManager.Settings.Automation.IsSaveStrokesAsUInK, "preserve opt-out after migration"); + } + } + finally { SettingsManager.Settings = original; } + } + + private static void StrokeSaveFormatPriority(UInkChecks c) + { + foreach (var (uink, xml, image, expected) in new[] + { + (true, true, true, MainWindow.StrokeSaveFormat.UInk), + (false, true, true, MainWindow.StrokeSaveFormat.Xml), + (false, false, true, MainWindow.StrokeSaveFormat.FullPage), + (false, false, false, MainWindow.StrokeSaveFormat.Icstk) + }) + { + var settings = new Automation + { + IsSaveStrokesAsUInK = uink, IsSaveStrokesAsXML = xml, IsSaveFullPageStrokes = image + }; + c.Equal(expected, MainWindow.ResolveStrokeSaveFormat(settings), "save format priority"); + } + } + + private static void ManualTimedAndScreenshotSaveFormats(UInkChecks c) + { + var original = MainWindow.Settings; + var directory = NewTestDirectory(); + try + { + MainWindow.Settings = new Settings(); + var automation = MainWindow.Settings.Automation; + automation.AutoSavedStrokesLocation = directory; + automation.IsUseCustomSaveFileName = true; + automation.IsAutoSaveStrokesAtScreenshot = true; + var window = (MainWindow)FormatterServices.GetUninitializedObject(typeof(MainWindow)); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + var canvas = new WpfInkCanvas(); + var queue = new UInkSaveQueue(); + var type = typeof(MainWindow); + type.GetField("inkCanvas", fields).SetValue(window, canvas); + type.GetField("timeMachine", fields).SetValue(window, new TimeMachine()); + type.GetField("_uinkSaves", fields).SetValue(window, queue); + type.GetField("_uinkSessions", fields).SetValue(window, new MainWindow.UInkSession[3]); + type.GetField("_uinkWorkspaceIds", fields).SetValue(window, new string[3]); + canvas.Strokes.Add(new Stroke(new StylusPointCollection { new StylusPoint(10, 20) })); + + automation.CustomSaveFileNameTemplate = "manual"; + window.SaveInkCanvasStrokes(false, true); + automation.CustomSaveFileNameTemplate = "gesture"; + type.GetField("_canvasGestureOwnsTouchInput", fields).SetValue(window, true); + type.GetMethod("AutoSaveStrokesTimer_Tick", fields).Invoke(window, new object[] { null, EventArgs.Empty }); + c.That((bool)type.GetField("_canvasGestureOwnsTouchInput", fields).GetValue(window), + "timer leaves active gesture intact"); + type.GetField("_canvasGestureOwnsTouchInput", fields).SetValue(window, false); + automation.CustomSaveFileNameTemplate = "timer"; + type.GetMethod("AutoSaveStrokesTimer_Tick", fields).Invoke(window, new object[] { null, EventArgs.Empty }); + automation.CustomSaveFileNameTemplate = "companion"; + window.CaptureScreenshotCompanion(out var strokes, out var path); + c.That(strokes == null && path == null, "UInk companion bypasses legacy ISF queue"); + var captured = canvas.Strokes.Clone(); + canvas.Strokes.Clear(); // 模拟截图入队后立即清屏/切页。 + if (!queue.DrainAsync().Wait(TimeSpan.FromSeconds(20))) + { + c.That(false, "save queue did not drain"); + return; + } + + c.That(Directory.GetFiles(directory, "gesture.uink", SearchOption.AllDirectories).Length == 0, + "no timed capture while input is active"); + CheckSnapshot("User Saved - Annotation Strokes", "manual.uink"); + CheckSnapshot("Auto Saved - Annotation Strokes", "timer.uink"); + CheckSnapshot("Auto Saved - BlackBoard Strokes", "companion.uink"); + + canvas.Strokes.Add(captured); + automation.IsSaveStrokesAsUInK = false; + foreach (var (xml, wholePage) in new[] { (false, false), (true, false), (false, true) }) + { + automation.IsSaveStrokesAsXML = xml; + automation.IsSaveFullPageStrokes = wholePage; + window.CaptureScreenshotCompanion(out strokes, out path); + c.Equal(".icstk", Path.GetExtension(path), "legacy screenshot companion format"); + c.Equal(1, strokes?.Count ?? 0, "legacy screenshot companion has live ink"); + } + + void CheckSnapshot(string folder, string name) + { + string file = Path.Combine(directory, folder, name); + c.That(File.Exists(file), name + " exists"); + if (!File.Exists(file)) return; + var document = UInkReader.Read(file).Document; + c.Equal(1, document?.Canvases[0].Blocks.Count ?? 0, name + " preserves pre-clear ink"); + } + } + finally + { + MainWindow.Settings = original; + Directory.Delete(directory, recursive: true); + } + } + + private static void DeleteExpiredUInkPairs(UInkChecks c) + { + string root = NewTestDirectory(); + try + { + string folder = Directory.CreateDirectory(Path.Combine(root, "Auto Saved - BlackBoard Strokes")).FullName; + string expired = CreateFile(folder, "old.UINK", oldCreation: true); + string expiredExtra = CreateFile(folder, "old.UINK.extra"); + string standalone = CreateFile(folder, "ink-only.uink", oldCreation: true); + string recent = CreateFile(folder, "recent.uink"); + string recentExtra = CreateFile(folder, "recent.uink.extra", oldCreation: true); + string held = CreateFile(folder, "held.uink", oldCreation: true); + string heldExtra = CreateFile(folder, "held.uink.extra", oldCreation: true); + + using (File.OpenRead(heldExtra)) + { + string renewing = CreateFile(folder, "renewing.uink", oldCreation: true); + string renewingExtra = CreateFile(folder, "renewing.uink.extra"); + using var started = new ManualResetEventSlim(); + Task cleanup = null; + UInkSaveService.WithTargetLock(renewing, () => + { + cleanup = Task.Run(() => + { + started.Set(); + DelAutoSavedFiles.DeleteFilesOlder(root, 7); + }); + c.That(started.Wait(TimeSpan.FromSeconds(5)), "cleanup started"); + c.That(!cleanup.Wait(500) && File.Exists(renewing), "cleanup waits for target lock"); + File.SetCreationTime(renewing, DateTime.Now); + return true; + }); + c.That(cleanup.Wait(TimeSpan.FromSeconds(5)), "cleanup resumed"); + c.That(File.Exists(renewing) && File.Exists(renewingExtra), "renewed pair survives"); + c.That(File.Exists(held) && File.Exists(heldExtra), "an open sidecar protects the pair"); + } + c.That(!File.Exists(expired) && !File.Exists(expiredExtra), "expired main removes its newer sidecar"); + c.That(!File.Exists(standalone), "expired main can have no sidecar"); + c.That(File.Exists(recent) && File.Exists(recentExtra), "recent main protects its older sidecar"); + + DelAutoSavedFiles.DeleteFilesOlder(root, 7); + c.That(!File.Exists(held) && !File.Exists(heldExtra), "expired pair removed after closing"); + } + finally { Directory.Delete(root, recursive: true); } + } + + private static void RetainRecentAndActiveUInkMedia(UInkChecks c) + { + string root = NewTestDirectory(); + try + { + string cache = Directory.CreateDirectory(Path.Combine(root, UInkMediaRestoreCache.CacheDirectoryName)).FullName; + string recent = CreateFile(cache, "recent.png", oldCreation: true); + string expired = CreateFile(cache, "expired.mp4"); + string held = CreateFile(cache, "held.pdf", oldCreation: true); + File.SetLastAccessTimeUtc(recent, DateTime.UtcNow); + File.SetLastAccessTimeUtc(expired, DateTime.UtcNow.AddDays(-30)); + File.SetLastAccessTimeUtc(held, DateTime.UtcNow.AddDays(-30)); + + using (DelAutoSavedFiles.OpenUInkMediaCacheLease(cache, exclusive: false)) + { + DelAutoSavedFiles.DeleteFilesOlder(root, 7); + c.That(File.Exists(expired), "a live cache lease protects path-only users"); + c.That(File.Exists(recent), "legacy creation-time sweep skips the cache"); + } + using (File.OpenRead(held)) + { + DelAutoSavedFiles.DeleteFilesOlder(root, 7); + c.That(File.Exists(held), "retention skips an open cache file"); + } + c.That(File.Exists(recent), "old creation time does not remove recently accessed media"); + c.That(!File.Exists(expired), "expired video removed by access time"); + + // 打开文件可能刷新访问时间,关闭后重新构造过期条件。 + File.SetLastAccessTimeUtc(held, DateTime.UtcNow.AddDays(-30)); + DelAutoSavedFiles.DeleteFilesOlder(root, 7); + c.That(!File.Exists(held), "unused expired PDF removed"); + } + finally { Directory.Delete(root, recursive: true); } + } + + private static void RecognizeUInkCommandLinePath(UInkChecks c) + { + string root = NewTestDirectory(); + try + { + string uink = CreateFile(root, "saved.UINK"); + string sidecar = CreateFile(root, "saved.UINK.extra"); + string legacy = CreateFile(root, "saved.icstk"); + c.Equal(uink, FileAssociationManager.GetIcstkFileFromArgs(new[] { sidecar, uink, legacy }), "select UInk main file"); + c.Equal(legacy, FileAssociationManager.GetIcstkFileFromArgs(new[] { Path.Combine(root, "missing.uink"), legacy }), + "skip missing UInk and accept legacy ink"); + c.That(FileAssociationManager.GetIcstkFileFromArgs(new[] { sidecar }) == null, "resource bundle is not an open target"); + } + finally { Directory.Delete(root, recursive: true); } + } + + private static string NewTestDirectory() => + Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"))).FullName; + + private static string CreateFile(string folder, string name, bool oldCreation = false) + { + string path = Path.Combine(folder, name); + File.WriteAllText(path, name); + if (oldCreation) File.SetCreationTimeUtc(path, DateTime.UtcNow.AddDays(-30)); + return path; + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkFixtureTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkFixtureTests.cs new file mode 100644 index 000000000..ac5d8d858 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkFixtureTests.cs @@ -0,0 +1,528 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using static InkCanvas.Calibration.Tests.UInk.UInkTestItemKind; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkFixtureTests + { + private const uint Blue = 1989375, Red = 15026253, Green = 2269291, Black = 2042167; + private const string Annotation = "ScreenAnnotation", Board = "Whiteboard", Ppt = "Presentation"; + + private static readonly (string Name, Action Check)[] Fixtures = + { + ("core-pages", CorePages), + ("core-page-append", CorePageAppend), + ("basic-appearance", BasicAppearance), + ("standard-ppt", StandardPpt), + ("standard-media", StandardMedia), + ("standard-shape-object", StandardShapeObject), + ("full-layers-devices", FullLayersDevices), + ("full-hdr-advanced", FullHdrAdvanced), + ("full-shape-preset", FullShapePreset), + ("inkeys-erase-clear", InkeysEraseClear), + ("compat-v10", CompatV10), + ("fallback-unknown", FallbackUnknown), + ("truncated-tail", TruncatedTail), + ("corrupt-middle", CorruptMiddle), + ("future-minor", FutureMinor), + ("core-shape-curves", CoreShapeCurves), + }; + + public static int Run(string directory) + { + var suite = new UInkSuite("fixtures"); + if (suite.Test("SHA256SUMS", c => VerifyHashes(c, directory))) + foreach (var (name, check) in Fixtures) + suite.Test(name, c => check(c, Path.Combine(directory, name + ".uink"))); + return suite.Finish(); + } + + private static void VerifyHashes(UInkChecks c, string directory) + { + var expected = new HashSet(StringComparer.Ordinal) { "standard-media.uink.extra" }; + foreach (var (name, _) in Fixtures) expected.Add(name + ".uink"); + var seen = new HashSet(StringComparer.Ordinal); + foreach (string line in File.ReadLines(Path.Combine(directory, "SHA256SUMS.txt"))) + { + if (string.IsNullOrWhiteSpace(line)) continue; + var fields = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + if (fields.Length != 2 || fields[0].Length != 64) + { + c.That(false, "invalid SHA256SUMS row: " + line); + continue; + } + string name = fields[1].TrimStart('*'); + if (Path.GetFileName(name) != name || name.Contains(':')) + { + c.That(false, "invalid SHA256SUMS file name: " + name); + continue; + } + c.That(seen.Add(name), "duplicate SHA256SUMS entry: " + name); + string path = Path.Combine(directory, name); + if (!File.Exists(path)) + { + c.That(false, "missing fixture: " + name); + continue; + } + using var stream = File.OpenRead(path); + using var sha = SHA256.Create(); + string actual = Convert.ToHexString(sha.ComputeHash(stream)); + c.That(string.Equals(fields[0], actual, StringComparison.OrdinalIgnoreCase), + $"SHA-256 mismatch for {name}: expected {fields[0]}, got {actual}"); + } + foreach (string name in expected) c.That(seen.Contains(name), "checksum missing for " + name); + string[] paths = Directory.GetFiles(directory, "*.uink*"); + Array.Sort(paths, StringComparer.Ordinal); + foreach (string path in paths) + { + string name = Path.GetFileName(path); + c.That(seen.Contains(name), "unlisted fixture: " + name); + c.That(expected.Contains(name), "fixture has no structural test: " + name); + } + } + + private static void CorePages(UInkChecks c, string path) + { + var result = Read(c, path, "0001", Annotation, 3); + var p = Page(c, result, "0001", 0, 1, 0, 1, 3, 3); + InkItem(c, p, 0, Blue, 8, (240, 300, 4), (660, 320, 4)); + c.Floats(new[] { 4f, 6, 8, 10, 10, 8, 6, 4 }, At(p, 0)?.Width, "wave widths"); + InkItem(c, p, 1, Red, 1, (800, 300, 16), (800, 300, 16)); + InkItem(c, p, 2, Black, 3, (960, 320, 5), (1080, 260, 5)); + c.Equal(null, p?.BackgroundRgb, "annotation background"); + Viewport(c, p, 0, 0, 1, implicitIdentity: true); + + p = Page(c, result, "0001", 1, 2, 1, 2, 7, 7); + ShapeItem(c, p, 0, 0, Black, 4); + ShapeItem(c, p, 1, 1, Black, 4); + ShapeItem(c, p, 2, 2, Black, 4, fill: 16769162); + ShapeItem(c, p, 3, 3, Black, 4); + ShapeItem(c, p, 4, 4, 9425919, null, fill: 9425919); + ShapeItem(c, p, 5, 5, Blue, 6); + ShapeItem(c, p, 6, 6, Black, 4, fill: 16757683); + Page(c, result, "0001", 2, 3, 2, 3, 0, 0); + } + + private static void CorePageAppend(UInkChecks c, string path) + { + var result = Read(c, path, "0002", Board, 3); + // FILE-8、SAVE-14:旧 B 整体替换,同 pageIndex 按最后 Canvas 的位置排序。 + var p = Page(c, result, "0002", 0, 0xa, 0, 1, 1, 1); + InkItem(c, p, 0, Blue, 3, (300, 400, 6), (540, 400, 6)); + p = Page(c, result, "0002", 1, 0xc, 2, 3, 1, 1); + InkItem(c, p, 0, Green, 3, (300, 500, 6), (540, 500, 6)); + p = Page(c, result, "0002", 2, 0xb, 2, 3, 3, 3); + InkItem(c, p, 0, Red, 2, (300, 300, 6), (600, 300, 6)); + InkItem(c, p, 1, Red, 2, (300, 380, 6), (600, 380, 6)); + ShapeItem(c, p, 2, 5, Red, 4); + } + + private static void BasicAppearance(UInkChecks c, string path) + { + var result = Read(c, path, "0003", Board, 1); + var p = Page(c, result, "0003", 0, 1, 0, 1, 10, 10); + c.Equal(16447472, p?.BackgroundRgb, "background RGB"); + c.Equal(1, p?.BackgroundPattern, "dotted background"); + InkItem(c, p, 0, Blue, 4, (200, 200, 8), (560, 180, 8), opacity: 0.5f); + // NIB-3:矩形笔尖忽略显式 cap;圆笔尖保留方头和平头。 + InkItem(c, p, 1, 16770560, 4, (200, 320, 24), (600, 332, 24), inkType: 2, opacity: 0.4f, aspect: 0.125f); + InkItem(c, p, 2, Black, 2, (200, 460, 16), (560, 460, 16), cap: 1); + InkItem(c, p, 3, Red, 2, (200, 540, 16), (560, 540, 16), cap: 2); + ShapeItem(c, p, 4, 0, Blue, 4, dash: new[] { 16f, 8 }, start: 1, end: 1); + ShapeItem(c, p, 5, 0, Black, 6, dash: new[] { 0f, 18 }); + ShapeItem(c, p, 6, 1, Green, 14, end: 1, lineCap: 2, lineJoin: 1); + ShapeItem(c, p, 7, 1, Green, 14, lineCap: 1, lineJoin: 2); + ShapeItem(c, p, 8, 2, Black, 4, fill: Blue, fillOpacity: 0.3f); + c.Near(24, At(p, 8)?.CornerRadiusX, "rectangle corner X"); + c.Near(16, At(p, 8)?.CornerRadiusY, "rectangle corner Y"); + ShapeItem(c, p, 9, 4, Red, 6, opacity: 0.6f, dash: new[] { 24f, 12 }); + c.Near(6, At(p, 9)?.DashOffset, "ellipse dash offset"); + void Fallback(int index, string reason) => + c.That(Array.IndexOf(At(p, index)?.DisplayDiagnostics ?? Array.Empty(), reason) >= 0, reason); + Fallback(2, "capApprox"); + Fallback(6, "shapeCapApprox"); + Fallback(7, "shapeJoinApprox"); + Fallback(8, "shapeCornerApprox"); + Fallback(8, "shapeFillOutline"); + } + + private static void StandardPpt(UInkChecks c, string path) + { + var result = Read(c, path, "0004", Ppt, 4, current: 1, retained: 1, + resolveSlide: new Ink_Canvas.UInk.PptSlideMap(new[] { 257, 999, 256 }).Resolve); + c.Equal("INKEYS-PPT-7B58E2A1", result.HostId, "PPT host ID"); + var p = Page(c, result, "0004", 0, 1, 0, 1, 1, 1); + Binding(c, p, 0, 256); + c.Equal(3, p?.SlideIndex, "resolved 1-based slide index"); + InkItem(c, p, 0, Red, 3, (400, 620, 6), (1000, 618, 6)); + + p = Page(c, result, "0004", 1, 2, 1, 2, 2, 2); + Binding(c, p, 0, 257); + c.Equal(1, p?.SlideIndex, "reordered slide index"); + InkItem(c, p, 0, Blue, 7, (900, 300, 5), (900, 310, 5)); + ShapeItem(c, p, 1, 0, Blue, 4, end: 1); + + p = Page(c, result, "0004", 2, 3, 2, 3, 1, 1); + Binding(c, p, 1, null); + c.Equal(3, p?.SlideIndex, "index-bound slide"); + InkItem(c, p, 0, Green, 3, (1400, 500, 8), (1520, 440, 8)); + + p = Page(c, result, "0004", 3, 5, 4, 5, 1, 1); + c.Equal(1, p?.PageKind, "EndScreen page kind"); + c.Equal(null, p?.SlideId, "EndScreen SlideID"); + InkItem(c, p, 0, 16765952, 7, (800, 520, 8), (1120, 540, 8)); + + p = Page(c, result, "0004", 0, 4, 3, 4, 1, 1, retained: true); + c.Equal(1, p?.PageState, "Retained page state"); + c.Equal(258, p?.SlideId, "Retained SlideID"); + InkItem(c, p, 0, 7041664, 2, (500, 540, 6), (1400, 540, 6)); + + // CANVAS-14:查询失败时,保持 PageGuid 与 SlideID,严禁退回按页码绑定。 + var missing = Read(c, path, "0004", Ppt, 4, current: 1, retained: 1, resolveSlide: _ => null); + Binding(c, Page(c, missing, "0004", 0, 1, 0, 1, 1, 1), 0, 256, unbound: true); + Binding(c, Page(c, missing, "0004", 1, 2, 1, 2, 2, 2), 0, 257, unbound: true); + Binding(c, Page(c, missing, "0004", 2, 3, 2, 3, 1, 1), 1, null); + UInkPptTests.PreservedPagesRoundtrip(c, path); + } + + private static void StandardMedia(UInkChecks c, string path) + { + var result = Read(c, path, "0005", Board, 1, saveAs: true); + var p = Page(c, result, "0005", 0, 1, 0, 1, 8, groups: null); + Viewport(c, p, 100, 50, 1.5f); + MediaItem(c, p, 0, "images/quadrants.png", "image/png", 1, true, 320, 320, new[] { 1.5f, 0, 0, 1.5f, 60, 75 }); + MediaItem(c, p, 1, "images/quadrants.png", "image/png", 2, true, 160, 160, new[] { 1.5f, 0, 0, 1.5f, 630, 75 }); + MediaItem(c, p, 2, "images/quadrants.png", "image/png", 0, true, 160, 160, new[] { 0f, 1.5f, -1.5f, 0, 1170, 75 }); + c.Floats(new[] { 0f, 0, 16, 16 }, At(p, 2)?.MediaCrop, "media crop in resource pixels"); + MediaItem(c, p, 3, "images/badge.svg", "image/svg+xml", 3, false, 64, 64, + new[] { 1.5f, 0, 0, 1.5f, 1290, 75 }, 0.6f); + c.That(At(p, 3)?.MediaPlaceholder == true, "unsupported SVG keeps a placeholder slot"); + InkItem(c, p, 4, Red, 2, (75, 315, 9), (525, 315, 9), ordinal: 4); + MediaItem(c, p, 5, "images/missing.png", "image/png", 0, false, 240, 135, + new[] { 1.5f, 0, 0, 1.5f, 60, 615 }); + c.That(At(p, 5)?.MediaPlaceholder == true, "missing image keeps a placeholder slot"); + // R5:ICC 保留 PDF/音频能力。资源可用性与是否能播放或显现分开验证。 + MediaItem(c, p, 6, "documents/handout.pdf", "application/pdf", 0, true, 320, 180, + new[] { 1.5f, 0, 0, 1.5f, 510, 615 }); + MediaItem(c, p, 7, "audio/chime.wav", "audio/wav", 0, true, null, null, null); + UInkMediaTests.AssertStandardMediaCropIgnored(c, path); + } + + private static void StandardShapeObject(UInkChecks c, string path) + { + var result = Read(c, path, "0006", Annotation, 1, saveAs: true); + var p = Page(c, result, "0006", 0, 1, 0, 1, 17, 4); + ShapeItem(c, p, 0, 0, Black, 4, ordinal: 0); + ShapeItem(c, p, 1, 1, Black, 4, ordinal: 0); + Group(c, p, "0006", 1, 0, 2); + for (int i = 0; i < 12; i++) + ShapeItem(c, p, i + 2, 0, Black, 3, dash: i is 6 or 9 or 11 ? new[] { 12f, 18 } : null, ordinal: 1); + Group(c, p, "0006", 2, 2, 12); + ShapeItem(c, p, 14, 0, Red, 4, ordinal: 2); + ShapeItem(c, p, 15, 0, Red, 4, ordinal: 2); + Independent(c, p, 14); + Independent(c, p, 15); + InkItem(c, p, 16, Blue, 3, (1300, 500, 5), (1500, 500, 5), ordinal: 3); + } + + private static void FullLayersDevices(UInkChecks c, string path) + { + // CP0 裁定②:Pages 只含 W1,W2 的页面数来自独立索引。 + var result = Read(c, path, "0007", Board, 1, saveAs: true); + c.Equal(1, result.UndisplayedWorkspaces.Count, "undisplayed Workspace count"); + if (result.UndisplayedWorkspaces.Count == 1) + c.Equal(("aaaaaaaa-0007-4000-8000-000000000002", 1, 1), result.UndisplayedWorkspaces[0], "undisplayed W2"); + var p = Page(c, result, "0007", 0, 1, 0, 1, 2, 2); + c.Equal(0xFFFFFF, p?.BackgroundRgb, "layer-0 background"); + c.Equal(2, p?.BackgroundPattern, "grid background"); + InkItem(c, p, 0, Blue, 2, (200, 400, 10), (800, 400, 10)); + ShapeItem(c, p, 1, 2, 16769162, null, fill: 16769162); + foreach (var page in result.Pages) + foreach (var item in page.Items) + c.That(item.Kind != Ink || item.ColorRgb != Red, "second-device red ink leaked into the display"); + } + + private static void FullHdrAdvanced(UInkChecks c, string path) + { + var result = Read(c, path, "0008", Annotation, 1, saveAs: true); + var p = Page(c, result, "0008", 0, 1, 0, 1, 6, 6); + InkItem(c, p, 0, 0xFFCC00, 3, (200, 200, 10), (600, 220, 10)); + InkItem(c, p, 1, 8180991, 5, (200, 360, 24), (680, 360, 24), inkType: 2, opacity: 0.5f, aspect: 0.125f); + InkItem(c, p, 2, Green, 3, (200, 480, 8), (600, 480, 8)); + ShapeItem(c, p, 3, 2, 0x3366FF, 6); + InkItem(c, p, 4, Black, 13, (1320, 400, 5), (1316, 396, 5)); + ShapeItem(c, p, 5, 5, Black, 5); + } + + private static void FullShapePreset(UInkChecks c, string path) + { + var result = Read(c, path, "0009", Annotation, 1, saveAs: true); + var p = Page(c, result, "0009", 0, 1, 0, 1, 16, 3); + for (int i = 0; i < 12; i++) + ShapeItem(c, p, i, 0, Black, 3, dash: i is 3 or 6 or 8 ? new[] { 12f, 18 } : null, ordinal: 0); + // SHAPE-12/15:几何已经是最终部件坐标,不再应用 object.transform。 + Endpoints(c, At(p, 0), (563.23566f, 682.6581f), (877.36115f, 631.8073f), "cuboid first edge"); + ShapeItem(c, p, 12, 5, Blue, 4, fill: 14477567, ordinal: 1); + ShapeItem(c, p, 13, 5, Blue, null, fill: Blue, ordinal: 1); + ShapeItem(c, p, 14, 6, 14037892, 3, fill: 16769162, ordinal: 2); + ShapeItem(c, p, 15, 0, 14037892, 3, ordinal: 2); + Group(c, p, "0009", 1, 0, 12); + Group(c, p, "0009", 2, 12, 2); + Group(c, p, "0009", 3, 14, 2); + } + + private static void InkeysEraseClear(UInkChecks c, string path) + { + var result = Read(c, path, "000a", Annotation, 1, saveAs: true); + var p = Page(c, result, "000a", 0, 1, 0, 1, 3, 3); + // INK-11、CLEAR-7:B 仍是连续两点,A、矩形与两条橡皮均不可见。 + InkItem(c, p, 0, Red, 2, (200, 760, 8), (700, 760, 8)); + InkItem(c, p, 1, Green, 2, (900, 300, 8), (1300, 300, 8)); + InkItem(c, p, 2, 8141549, 2, (410, 720, 6), (490, 800, 6)); + } + + private static void CompatV10(UInkChecks c, string path) + { + var result = Read(c, path, "000b", Annotation, 2, version: 10); + var p = Page(c, result, "000b", 0, 1, 0, 1, 2, 2); + Viewport(c, p, 0, 0, 1, implicitIdentity: true); + InkItem(c, p, 0, Blue, 3, (200, 240, 6), (600, 240, 6)); + c.Floats(new[] { 6f, 6.5f, 6 }, At(p, 0)?.Width, "v10 pen visible widths"); + InkItem(c, p, 1, 16770560, 2, (200, 360, 20), (600, 360, 20), inkType: 2, opacity: 0.4f); + p = Page(c, result, "000b", 1, 2, 1, 2, 2, 2); + Viewport(c, p, 0, 0, 1, implicitIdentity: true); + ShapeItem(c, p, 0, 0, Black, 4, dash: new[] { 12f, 6 }, end: 1); + ShapeItem(c, p, 1, 4, Green, null, fill: Green); + } + + private static void FallbackUnknown(UInkChecks c, string path) + { + var result = Read(c, path, "000c", Board, 1, saveAs: true, minimumSkipped: 2); + var p = Page(c, result, "000c", 0, 1, 0, 1, 5, groups: null); + Viewport(c, p, 0, 0, 1, implicitIdentity: true); + c.Equal(0xFFFFFF, p?.BackgroundRgb, "fallback background"); + c.Equal(0, p?.BackgroundPattern, "fallback Blank pattern"); + InkItem(c, p, 0, Blue, 3, (200, 300, 6), (440, 300, 8)); + c.Floats(new[] { 6f, 7, 8 }, At(p, 0)?.Width, "losslessly decoded widths"); + ShapeItem(c, p, 1, 0, Black, 6, ordinal: null); + ShapeItem(c, p, 2, 2, Black, 4, fill: 16769162, ordinal: null); + MediaItem(c, p, 3, "images/future.png", "image/png", 0, false, 320, 180, + new[] { 1f, 0, 0, 1, 1200, 200 }); + InkItem(c, p, 4, Red, 3, (1200, 600, 6), (1600, 600, 6), ordinal: null); + } + + private static void TruncatedTail(UInkChecks c, string path) + { + var result = Read(c, path, "000d", Annotation, 1, saveAs: true, truncated: true); + var p = Page(c, result, "000d", 0, 1, 0, 1, 2, 2); + InkItem(c, p, 0, Blue, 3, (200, 300, 6), (600, 300, 6)); + InkItem(c, p, 1, Green, 3, (200, 400, 6), (600, 400, 6)); + } + + private static void CorruptMiddle(UInkChecks c, string path) + { + var result = Read(c, path, "000e", Annotation, 1, saveAs: true, corrupt: true); + var p = Page(c, result, "000e", 0, 1, 0, 1, 1, 1); + InkItem(c, p, 0, Blue, 3, (200, 300, 6), (600, 300, 6)); + } + + private static void FutureMinor(UInkChecks c, string path) + { + var result = Read(c, path, "000f", Annotation, 1, version: 12, saveAs: true, minimumSkipped: 1); + var p = Page(c, result, "000f", 0, 1, 0, 1, 3, 3); + InkItem(c, p, 0, Blue, 3, (200, 300, 6), (600, 300, 6)); + ShapeItem(c, p, 1, 2, Black, 4, fill: 16769162); + InkItem(c, p, 2, Red, 3, (800, 520, 6), (1200, 540, 6)); + } + + private static void CoreShapeCurves(UInkChecks c, string path) + { + var result = Read(c, path, "0016", Annotation, 1); + var p = Page(c, result, "0016", 0, 1, 0, 1, 5, 2); + ShapeItem(c, p, 0, 1, Black, 4, ordinal: 0); + ShapeItem(c, p, 1, 1, Black, 4, ordinal: 0); + for (int i = 2; i <= 3; i++) + ShapeItem(c, p, i, 0, 9080728, 2, dash: new[] { 12f, 8 }, ordinal: 0); + Endpoints(c, At(p, 0), (349.87f, 834.13f), (349.87f, 245.87f), "left branch"); + Endpoints(c, At(p, 1), (1170.13f, 834.13f), (1170.13f, 245.87f), "right branch"); + Endpoints(c, At(p, 2), (349.87f, 847.6f), (1170.13f, 232.4f), "rising asymptote"); + Endpoints(c, At(p, 3), (349.87f, 232.4f), (1170.13f, 847.6f), "falling asymptote"); + ShapeItem(c, p, 4, 6, Red, 3, fill: 16766680, ordinal: 1); + Group(c, p, "0016", 1, 0, 4); + Independent(c, p, 4); + } + + private static UInkTestLoadResult Read(UInkChecks c, string path, string id, string workspace, int? pages, + int current = 0, int retained = 0, int version = 11, bool saveAs = false, bool truncated = false, + bool corrupt = false, int minimumSkipped = 0, Func resolveSlide = null) + { + var result = UInkTestApi.Load(path, resolveSlide); + c.That(result.Status is UInkTestStatus.Ok or UInkTestStatus.Recovered, "load result: " + result.Status + " " + result.Error); + if (truncated || corrupt) c.Equal(UInkTestStatus.Recovered, result.Status, "recovery status"); + c.Equal(version, result.HeaderVersion, "Header version"); + c.Equal($"ffffffff-{id}-4000-8000-000000000000", result.HeaderGuid, "Header GUID"); + c.Equal(workspace, result.SelectedWorkspaceType, "selected Workspace type"); + c.Equal(current, result.CurrentPageDisplayIndex, "current display index"); + if (pages.HasValue) c.Equal(pages.Value, result.Pages.Count, "display page count"); + c.Equal(retained, result.RetainedPages.Count, "retained page count"); + c.Equal(truncated, result.Truncated, "truncated"); + c.Equal(corrupt, result.StoppedOnCorruption, "stopped on corruption"); + c.That(result.SkippedBlocks >= minimumSkipped, $"skipped {result.SkippedBlocks} blocks, expected at least {minimumSkipped}"); + if (saveAs) c.That(result.RequiresSaveAs, "requires Save As"); + return result; + } + + private static UInkTestPage Page(UInkChecks c, UInkTestLoadResult result, string id, int position, + int guidSuffix, uint originalIndex, uint pageNumber, int items, int? groups, bool retained = false) + { + var pages = retained ? result.RetainedPages : result.Pages; + string label = (retained ? "retained page " : "page ") + position; + if (position >= pages.Count) + { + c.That(false, label + " is missing"); + return null; + } + var page = pages[position]; + c.Equal($"cccccccc-{id}-4000-8000-{guidSuffix:x12}", page.PageGuid, label + " GUID"); + c.Equal(originalIndex, page.OriginalPageIndex, label + " original index"); + if (!retained) c.Equal(position, page.DisplayIndex, label + " display index"); + c.Equal(pageNumber, page.PageNumber, label + " page number"); + c.Equal(items, page.Items.Count, label + " item count"); + if (groups.HasValue) c.Equal(groups.Value, page.UndoGroupCount, label + " undo group count"); + return page; + } + + private static void Viewport(UInkChecks c, UInkTestPage page, float x, float y, float scale, bool implicitIdentity = false) + { + if (page == null) return; + var actual = page.Viewport; + if (!actual.HasValue && implicitIdentity) return; + c.Near(x, actual?.x, "viewport x"); + c.Near(y, actual?.y, "viewport y"); + c.Near(scale, actual?.scale, "viewport scale"); + } + + private static void Binding(UInkChecks c, UInkTestPage page, int binding, int? slideId, bool unbound = false) + { + if (page == null) return; + c.Equal(binding, page.Binding, "binding for " + page.PageGuid); + c.Equal(slideId, page.SlideId, "SlideID for " + page.PageGuid); + c.Equal(unbound, page.Unbound, "unbound flag for " + page.PageGuid); + c.Equal(0, page.PageKind, "PPT slide page kind"); + c.Equal(0, page.PageState, "PPT normal page state"); + } + + private static UInkTestItem At(UInkTestPage p, int i) => + p != null && i < p.Items.Count ? p.Items[i] : null; + + private static UInkTestItem Item(UInkChecks c, UInkTestPage p, int i, UInkTestItemKind kind, uint? ordinal) + { + var item = At(p, i); + if (p == null) return null; + string label = $"page {p.PageGuid}, item {i}"; + if (item == null) c.That(false, label + " is missing"); + else + { + c.Equal(kind, item.Kind, label + " kind"); + if (ordinal.HasValue) c.Equal(ordinal.Value, item.UndoGroupOrdinal, label + " undo ordinal"); + } + return item; + } + + private static void InkItem(UInkChecks c, UInkTestPage p, int i, uint rgb, int points, + (float x, float y, float width) first, (float x, float y, float width) last, + int inkType = 1, float opacity = 1, float? aspect = null, int cap = 0, int? ordinal = -1) + { + var item = Item(c, p, i, Ink, GroupOrdinal(i, ordinal)); + if (item == null) return; + string label = $"{p.PageGuid} ink {i}"; + c.Equal(rgb, item.ColorRgb, label + " RGB"); + c.Equal(inkType, item.InkType, label + " inkType"); + c.Near(opacity, item.Opacity, label + " opacity", 0.5 / 255 + 1e-6); + c.Equal(points, item.PointCount, label + " point count"); + Endpoints(c, item, (first.x, first.y), (last.x, last.y), label); + c.Equal(points, item.Width?.Length ?? 0, label + " width count"); + c.Near(first.width, First(item.Width), label + " first width"); + c.Near(last.width, Last(item.Width), label + " last width"); + c.Equal(aspect.HasValue ? 1 : 0, item.NibShape, label + " nib shape"); + if (aspect.HasValue) c.Near(aspect.Value, item.NibAspect, label + " nib aspect"); + else c.Equal(cap, item.Cap, label + " cap"); + } + + private static void ShapeItem(UInkChecks c, UInkTestPage p, int i, int type, uint rgb, float? width, + uint? fill = null, float opacity = 1, float fillOpacity = 1, float[] dash = null, int start = 0, + int end = 0, int lineCap = 0, int lineJoin = 0, int? ordinal = -1) + { + var item = Item(c, p, i, Shape, GroupOrdinal(i, ordinal)); + if (item == null) return; + string label = $"{p.PageGuid} shape {i}"; + c.Equal(type, item.ShapeType, label + " type"); + c.Equal(rgb, item.ColorRgb, label + " RGB"); + c.Near(opacity, item.Opacity, label + " opacity", 0.5 / 255 + 1e-6); + c.Equal(width.HasValue, item.HasStroke, label + " has stroke"); + c.Equal(fill.HasValue, item.HasFill, label + " has fill"); + if (width.HasValue) c.Near(width.Value, item.StrokeWidth, label + " stroke width"); + if (fill.HasValue) + { + c.Equal(fill, item.FillColorRgb, label + " fill RGB"); + c.Near(fillOpacity, item.FillOpacity, label + " fill opacity"); + } + c.Floats(dash, item.Dash, label + " dash"); + c.Equal(start, item.StartMarker, label + " start marker"); + c.Equal(end, item.EndMarker, label + " end marker"); + c.Equal(lineCap, item.LineCap, label + " line cap"); + c.Equal(lineJoin, item.LineJoin, label + " line join"); + } + + private static void MediaItem(UInkChecks c, UInkTestPage p, int i, string path, string mime, int fit, + bool available, float? width, float? height, float[] matrix, float opacity = 1) + { + var item = Item(c, p, i, Media, null); + if (item == null) return; + string label = $"{p.PageGuid} media {i}"; + c.Equal(path, item.MediaPath, label + " path"); + c.Equal(mime, item.MediaMime, label + " MIME"); + c.Equal(fit, item.MediaFit, label + " fit"); + c.Equal(available, item.MediaResourceAvailable, label + " resource available"); + c.Equal(width, item.MediaWidth, label + " local frame width"); + c.Equal(height, item.MediaHeight, label + " local frame height"); + c.Near(opacity, item.MediaOpacity, label + " opacity"); + c.Floats(matrix, item.MediaTransform, label + " device matrix"); + } + + private static void Group(UInkChecks c, UInkTestPage p, string id, int suffix, int start, int count) + { + for (int j = 0; j < count; j++) + { + var item = At(p, start + j); + if (item == null) continue; + c.Equal($"eeeeeeee-{id}-4000-8000-{suffix:x12}", item.ObjectId, $"item {start + j} object ID"); + c.Equal(j, item.ObjectPartIndex, $"item {start + j} part index"); + } + } + + private static void Independent(UInkChecks c, UInkTestPage p, int i) + { + var item = At(p, i); + if (item != null) c.That(string.IsNullOrEmpty(item.ObjectId), $"item {i} must be an independent shape"); + } + + private static void Endpoints(UInkChecks c, UInkTestItem item, + (float x, float y) first, (float x, float y) last, string label) + { + if (item == null) return; + c.Near(first.x, First(item.AbsX), label + " first X"); + c.Near(first.y, First(item.AbsY), label + " first Y"); + c.Near(last.x, Last(item.AbsX), label + " last X"); + c.Near(last.y, Last(item.AbsY), label + " last Y"); + } + + private static float? First(float[] values) => values?.Length > 0 ? values[0] : null; + private static float? Last(float[] values) => values?.Length > 0 ? values[^1] : null; + private static uint? GroupOrdinal(int position, int? ordinal) => + ordinal.HasValue ? (uint)(ordinal.Value < 0 ? position : ordinal.Value) : null; + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkLegacyReplayTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkLegacyReplayTests.cs new file mode 100644 index 000000000..0bf55bfe0 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkLegacyReplayTests.cs @@ -0,0 +1,622 @@ +using Ink_Canvas; +using Ink_Canvas.Controls; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; + +namespace InkCanvas.Calibration.Tests.UInk +{ + using InkCanvas = System.Windows.Controls.InkCanvas; + + internal static class UInkLegacyReplayTests + { + private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + internal static void Register(UInkSuite suite) + { + suite.Test(nameof(RandomStrokeHistoriesMatchOriginal), RandomStrokeHistoriesMatchOriginal); + suite.Test(nameof(ElementSequencesMatchOriginal), ElementSequencesMatchOriginal); + suite.Test(nameof(NonMainElementLayoutIsRestored), NonMainElementLayoutIsRestored); + suite.Test(nameof(UndoAndRedoResetCommitReason), UndoAndRedoResetCommitReason); + suite.Test(nameof(PluginConversionReplaysStrokesAndState), PluginConversionReplaysStrokesAndState); + suite.Test(nameof(EditableSceneReplayKeepsErasedGroupRemoved), EditableSceneReplayKeepsErasedGroupRemoved); + suite.Test(nameof(AutomationExportsLiveVisitedAndUnvisitedPages), AutomationExportsLiveVisitedAndUnvisitedPages); + } + + private static MainWindow HeadlessWindow(InkCanvas canvas) + { + var window = (MainWindow)FormatterServices.GetUninitializedObject(typeof(MainWindow)); + typeof(MainWindow).GetField("inkCanvas", Fields).SetValue(window, canvas); + return window; + } + + private static StrokeCollection Batch(params Stroke[] strokes) => new(strokes); + + private static void RandomStrokeHistoriesMatchOriginal(UInkChecks checks) + { + const int seed = 112711; + var seeds = new Random(seed); + var actual = new InkCanvas(); + var expected = new InkCanvas(); + var window = HeadlessWindow(actual); + for (int sample = 0; sample < 1024; sample++) + { + expected.Strokes.Clear(); + actual.Strokes.Clear(); + int historySeed = seeds.Next(); + // 每侧单独重建笔画和历史,避免共享可变的点集或 DA 掩盖回放偏差。 + var (expectedPool, expectedHistory) = MakeStrokeHistory(historySeed); + var (actualPool, actualHistory) = MakeStrokeHistory(historySeed); + var identities = new Dictionary(ReferenceEqualityComparer.Instance); + for (int i = 0; i < expectedPool.Length; i++) identities.Add(expectedPool[i], actualPool[i]); + var expectedMachine = new TimeMachine(); + var actualMachine = new TimeMachine(); + expectedMachine.ImportTimeMachineHistory(expectedHistory); + actualMachine.ImportTimeMachineHistory(actualHistory); + string context = $"seed {seed}, sample {sample}, history seed {historySeed}"; + for (int i = 0; i < expectedHistory.Length; i++) + { + if (!ReplayAndCompare(expectedHistory[i], actualHistory[i], $"forward {i}")) return; + } + + // 强制撤销尾部的识别,再随机沿真实游标前后移动。 + if (!ReplayAndCompare(expectedMachine.Undo(), actualMachine.Undo(), "first undo")) return; + if (!ReplayAndCompare(expectedMachine.Redo(), actualMachine.Redo(), "first redo")) return; + var toggles = new Random(historySeed); + for (int i = 0; i < 30; i++) + { + bool undo = !expectedMachine.CanRedo || (expectedMachine.CanUndo && toggles.Next(2) == 0); + if (undo) + { + if (!ReplayAndCompare(expectedMachine.Undo(), actualMachine.Undo(), $"undo {i}")) return; + } + else if (!ReplayAndCompare(expectedMachine.Redo(), actualMachine.Redo(), $"redo {i}")) return; + } + + bool ReplayAndCompare(TimeMachineHistory oldEntry, TimeMachineHistory newEntry, string step) + { + LegacyApplyHistoryToCanvas(oldEntry, expected); + window.ApplyHistoryToCanvas(newEntry); + string label = $"{context}, {step}, {oldEntry.CommitType}, cleared={oldEntry.StrokeHasBeenCleared}"; + checks.Equal(expected.Strokes.Count, actual.Strokes.Count, label + " count"); + if (checks.Failures.Count != 0) return false; + for (int i = 0; i < expected.Strokes.Count; i++) + { + var oldStroke = expected.Strokes[i]; + var newStroke = actual.Strokes[i]; + checks.That(ReferenceEquals(identities[oldStroke], newStroke), $"{label}, stroke {i} identity/order"); + checks.That(oldStroke.StylusPoints.SequenceEqual(newStroke.StylusPoints), $"{label}, stroke {i} points"); + checks.That(oldStroke.DrawingAttributes.Equals(newStroke.DrawingAttributes), $"{label}, stroke {i} DA"); + if (checks.Failures.Count != 0) return false; + } + return true; + } + } + } + + private static (Stroke[] Strokes, TimeMachineHistory[] History) MakeStrokeHistory(int seed) + { + var random = new Random(seed); + var strokes = new Stroke[8]; + for (int i = 0; i < strokes.Length; i++) + strokes[i] = new Stroke(Points(random), Attributes(random)); + + // 中间残段同时在擦除的两边。带重叠的尾部识别会显式走一遍 Undo 和 Redo。 + var history = new TimeMachineHistory[18]; + history[0] = new TimeMachineHistory(Batch(strokes[0], strokes[1], strokes[2]), + TimeMachineHistoryType.UserInput, false); + history[1] = StrokeEdit(random, strokes[0], strokes[1], manipulation: true); + history[2] = StrokeEdit(random, strokes[2], strokes[0], manipulation: false); + history[3] = new TimeMachineHistory(Batch(strokes[3], strokes[4]), TimeMachineHistoryType.Clear, + false, Batch(strokes[2], strokes[3])); + history[4] = new TimeMachineHistory(Batch(strokes[4], strokes[5]), TimeMachineHistoryType.Clear, + true, Batch(strokes[5], strokes[6])); + for (int i = 5; i < history.Length - 1; i++) + { + int index = random.Next(strokes.Length); + var first = strokes[index]; + var second = strokes[(index + random.Next(1, strokes.Length)) % strokes.Length]; + var third = strokes[(index + 1) % strokes.Length]; + bool cleared = random.Next(2) == 0; + history[i] = random.Next(5) switch + { + 0 => new TimeMachineHistory(Batch(first, second), TimeMachineHistoryType.UserInput, cleared), + 1 => new TimeMachineHistory(Batch(first), TimeMachineHistoryType.ShapeRecognition, cleared, Batch(second)), + 2 => new TimeMachineHistory(Batch(first, third), TimeMachineHistoryType.Clear, cleared, Batch(second)), + 3 => StrokeEdit(random, first, second, manipulation: true), + _ => StrokeEdit(random, first, second, manipulation: false) + }; + history[i].StrokeHasBeenCleared = cleared; + } + history[^1] = new TimeMachineHistory(Batch(strokes[6], strokes[5]), TimeMachineHistoryType.ShapeRecognition, + false, Batch(strokes[5], strokes[7])); + return (strokes, history); + } + + private static TimeMachineHistory StrokeEdit(Random random, Stroke first, Stroke second, bool manipulation) + { + var attributes = new Dictionary> + { + [first] = Tuple.Create(Attributes(random), Attributes(random)), + [second] = Tuple.Create(Attributes(random), Attributes(random)) + }; + if (!manipulation) return new TimeMachineHistory(attributes, TimeMachineHistoryType.DrawingAttributes); + return new TimeMachineHistory(new Dictionary> + { + [first] = Tuple.Create(Points(random), Points(random)), + [second] = Tuple.Create(Points(random), Points(random)) + }, TimeMachineHistoryType.Manipulation) { DrawingAttributes = attributes }; + } + + private static StylusPointCollection Points(Random random) + { + int count = random.Next(1, 5); + var points = new StylusPointCollection(count); + for (int i = 0; i < count; i++) + points.Add(new StylusPoint(random.Next(100), random.Next(100), random.Next(1, 100) / 100f)); + return points; + } + + private static DrawingAttributes Attributes(Random random) => new() + { + Color = Color.FromRgb((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256)), + Width = random.Next(2, 16), + Height = random.Next(2, 16), + FitToCurve = random.Next(2) == 0, + IgnorePressure = random.Next(2) == 0, + IsHighlighter = random.Next(2) == 0, + StylusTip = random.Next(2) == 0 ? StylusTip.Ellipse : StylusTip.Rectangle, + StylusTipTransform = random.Next(2) == 0 ? Matrix.Identity : new Matrix(1.2, 0, 0, 1.4, 0, 0) + }; + + private static void ElementSequencesMatchOriginal(UInkChecks checks) + { + var expected = new InkCanvas(); + var actual = new InkCanvas(); + var window = HeadlessWindow(actual); + // 只覆盖旧元素语义与现实现重叠的部分,R3 的时间顺序另有重插测试。 + for (int removed = 0; removed < 2; removed++) + { + expected.Children.Clear(); + actual.Children.Clear(); + var oldElements = new[] { new Image(), new Image(), new Image() }; + var newElements = new[] { new Image(), new Image(), new Image() }; + var oldHistory = ElementHistory(oldElements, removed); + var newHistory = ElementHistory(newElements, removed); + for (int i = 0; i < oldHistory.Length; i++) + { + LegacyApplyHistoryToCanvas(oldHistory[i], expected); + window.ApplyHistoryToCanvas(newHistory[i]); + string label = $"removed {removed}, element step {i}"; + checks.Equal(expected.Children.Count, actual.Children.Count, label + " count"); + if (checks.Failures.Count != 0) return; + for (int j = 0; j < expected.Children.Count; j++) + { + int identity = Array.IndexOf(oldElements, (Image)expected.Children[j]); + checks.That(ReferenceEquals(newElements[identity], actual.Children[j]), label + " identity/order"); + } + for (int j = 0; j < oldElements.Length; j++) + checks.Equal(oldElements[j].RenderTransform.Value, newElements[j].RenderTransform.Value, label + " transform"); + } + } + } + + private static TimeMachineHistory[] ElementHistory(Image[] elements, int removed) => new[] + { + new TimeMachineHistory(elements[0], TimeMachineHistoryType.ElementInsert), + new TimeMachineHistory(elements[1], TimeMachineHistoryType.ElementInsert), + new TimeMachineHistory(elements[removed], TimeMachineHistoryType.ElementInsert) { StrokeHasBeenCleared = true }, + new TimeMachineHistory(new Dictionary>(), + TimeMachineHistoryType.Manipulation) + { + ElementTransforms = new() + { + [elements[removed]] = Tuple.Create(Transform.Identity, new TranslateTransform(7, 11)), + [elements[1 - removed]] = Tuple.Create(Transform.Identity, new TranslateTransform(3, 5)) + } + }, + new TimeMachineHistory(elements[2], TimeMachineHistoryType.ElementInsert) + }; + + private static void NonMainElementLayoutIsRestored(UInkChecks checks) + { + var main = new InkCanvas { Width = 200, Height = 100 }; + main.Measure(new Size(200, 100)); + main.Arrange(new Rect(0, 0, 200, 100)); + var target = new InkCanvas(); + var window = HeadlessWindow(main); + // 无窗口构造跳过了 DispatcherObject 的初始化,补上 STA 调度器以运行 Loaded 回调。 + typeof(DispatcherObject).GetField("_dispatcher", Fields).SetValue(window, target.Dispatcher); + var image = new Image { Width = 280, Height = 50 }; + var machine = new TimeMachine(); + machine.CommitElementRemoveHistory(image); + window.ApplyHistoryToCanvas(machine.Undo(), target, includeElements: true); + checks.That(target.Children.Contains(image), "unmeasured image is inserted"); + checks.That(double.IsNaN(InkCanvas.GetLeft(image)) && double.IsNaN(InkCanvas.GetTop(image)), + "unmeasured image keeps its position until Loaded"); + + // 用有实际尺寸的元素触发原 CenterAndScaleElement 分支,按主画布的 70% 上限计算居中。 + target.Measure(new Size(360, 240)); + target.Arrange(new Rect(0, 0, 360, 240)); + // 无 Source 的 Image 测量为 0,会走等待 Loaded 的分支;给出 280×50 的位图才能得到有效尺寸。 + var measured = new Image { Width = 280, Height = 50, Source = System.Windows.Media.Imaging.BitmapSource.Create( + 280, 50, 96, 96, PixelFormats.Bgra32, null, new byte[280 * 50 * 4], 280 * 4) }; + measured.Measure(new Size(280, 50)); + measured.Arrange(new Rect(0, 0, 280, 50)); + window.ApplyHistoryToCanvas(new TimeMachineHistory(measured, TimeMachineHistoryType.ElementInsert), + target, includeElements: true); + checks.Near(140, measured.Width, "legacy centering caps width at 70% of the main canvas"); + checks.Near(25, measured.Height, "legacy centering preserves aspect"); + checks.Near(30, InkCanvas.GetLeft(measured), "legacy computed left"); + checks.Near(37.5, InkCanvas.GetTop(measured), "legacy computed top"); + + var control = new Border(); + InkCanvas.SetLeft(control, 15); + InkCanvas.SetTop(control, 25); + var controlInsertion = new TimeMachineHistory(control, TimeMachineHistoryType.ElementInsert); + window.ApplyHistoryToCanvas(controlInsertion, target, includeElements: true); + checks.That(control.RenderTransform is TransformGroup, "positioned generic element gets a transform group"); + checks.Near(15, InkCanvas.GetLeft(control), "existing left is preserved"); + checks.Near(25, InkCanvas.GetTop(control), "existing top is preserved"); + } + + private static void UndoAndRedoResetCommitReason(UInkChecks checks) + { + var canvas = new InkCanvas(); + var window = HeadlessWindow(canvas); + var reason = typeof(MainWindow).GetField("_currentCommitType", Fields); + var shapeDrawing = Enum.Parse(reason.FieldType, "ShapeDrawing"); + var userInput = Enum.Parse(reason.FieldType, "UserInput"); + var machine = new TimeMachine(); + canvas.Strokes.Add(new Stroke(new StylusPointCollection { new StylusPoint(1, 2) })); + machine.CommitStrokeUserInputHistory(Batch(canvas.Strokes[0])); + reason.SetValue(window, shapeDrawing); + window.ApplyHistoryToCanvas(machine.Undo()); + checks.Equal(userInput, reason.GetValue(window), "undo resets commit reason"); + reason.SetValue(window, shapeDrawing); + window.ApplyHistoryToCanvas(machine.Redo()); + checks.Equal(userInput, reason.GetValue(window), "redo resets commit reason"); + } + + private static void PluginConversionReplaysStrokesAndState(UInkChecks checks) + { + const string pluginId = "conversion-test"; + var canvas = new InkCanvas(); + var window = HeadlessWindow(canvas); + var states = new List(); + typeof(MainWindow).GetField("_pluginUndoStateHandlers", Fields).SetValue(window, + new Dictionary> { [pluginId] = states.Add }); + var consumed = new Stroke(new StylusPointCollection { new StylusPoint(1, 2) }); + var retained = new Stroke(new StylusPointCollection { new StylusPoint(3, 4) }); + var machine = new TimeMachine(); + machine.CommitStrokeUserInputHistory(Batch(consumed, retained)); + machine.CommitPluginStateHistory(pluginId, "empty", "before"); + machine.CommitPluginInkConversionHistory(pluginId, "before", "converted", Batch(consumed)); + var history = machine.ExportTimeMachineHistory(); + + var visible = new UInkHistorySnapshot(history).Visible().ToArray(); + checks.That(visible.SequenceEqual(new[] { retained }), "saved ink excludes consumed strokes"); + var flattened = (TimeMachineHistory[])typeof(MainWindow).GetMethod("FlattenPageHistory", Fields) + .Invoke(window, new object[] { history }); + checks.Equal("converted", flattened.Last().PluginStateAfter, "flattening keeps the active plugin state"); + checks.Equal(0, states.Count, "flattening does not call the live plugin"); + + typeof(MainWindow).GetMethod("RestorePageHistory", Fields).Invoke(window, new object[] { history }); + checks.That(canvas.Strokes.SequenceEqual(new[] { retained }), "page restore excludes consumed strokes"); + checks.That(states.SequenceEqual(new[] { "before", "converted" }), "page restore replays plugin state"); + window.ApplyHistoryToCanvas(machine.Undo()); + checks.That(canvas.Strokes.Contains(consumed), "undo restores the original stroke"); + checks.Equal("before", states.Last(), "undo restores pre-conversion plugin state"); + window.ApplyHistoryToCanvas(machine.Redo()); + checks.That(canvas.Strokes.SequenceEqual(new[] { retained }), "redo consumes the source stroke again"); + checks.Equal("converted", states.Last(), "redo restores converted plugin state"); + } + + private static void EditableSceneReplayKeepsErasedGroupRemoved(UInkChecks checks) + { + var canvas = new InkCanvas(); + var window = HeadlessWindow(canvas); + var group = new Border(); + var history = new[] + { + new TimeMachineHistory(group, TimeMachineHistoryType.ElementInsert), + new TimeMachineHistory(group, "{\"elements\":[{}]}", "{\"elements\":[]}") + }; + + var elements = (List)typeof(MainWindow).GetMethod("RestorePageHistory", Fields) + .Invoke(window, new object[] { history }); + checks.Equal(0, canvas.Children.Count, "an empty edited scene stays removed after restoring the page"); + checks.Equal(0, elements.Count, "removed groups are not passed to layout restoration"); + } + + private static void AutomationExportsLiveVisitedAndUnvisitedPages(UInkChecks checks) + { + using var bytes = new MemoryStream(); + var encoder = new UInkTestEncoder(bytes); + encoder.Header(11, 3); + encoder.HeaderExtension(); + for (uint i = 0; i < 3; i++) + { + encoder.Canvas(i, whiteboard: true); + encoder.Ink(0, 0, 0x112233, new[] { new UInkTestPoint(10 + i, 20, 4) }); + } + var projection = UInkIccMapper.BuildPageIndex(UInkReader.Read(bytes.ToArray(), + new UInkReadOptions { MaterializeContent = false }), 1, 1); + var pending = projection.Pages[2]; + var canvas = new InkCanvas(); + var window = HeadlessWindow(canvas); + var histories = new TimeMachineHistory[101][]; + var type = typeof(MainWindow); + type.GetField("TimeMachineHistories", Fields).SetValue(window, histories); + var board = type.GetField("_uinkBoard", Fields); + board.SetValue(window, Array.CreateInstance(board.FieldType.GetElementType(), histories.Length)); + type.GetField("_uinkWorkspaceIds", Fields).SetValue(window, new string[3]); + type.GetField("_currentMode", Fields).SetValue(window, 1); + type.GetField("_currentWhiteboardIndex", Fields).SetValue(window, 1); + type.GetField("_whiteboardTotalCount", Fields).SetValue(window, 3); + window.IndexUInkWhiteboard(projection, 3); + histories[1] = PageHistory(10); + histories[2] = PageHistory(24); + canvas.Strokes.Add(new Stroke(new StylusPointCollection { new StylusPoint(42, 20) })); + var pendingHistory = histories[3]; + checks.That(!pending.IsMaterialized && pendingHistory.Length == 0, "page 3 starts unvisited"); + + // 使用实际 ICSTK 导出入口并读回文件,旧循环会漏掉第 3 页。 + var directory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"))).FullName; + try + { + window.SaveStrokesForAutomation(directory, saveAsXml: false); + var expectedX = new[] { 42d, 24d, 12d }; + for (int i = 0; i < expectedX.Length; i++) + { + var paths = Directory.GetFiles(directory, $"*_Page-{i + 1}.icstk"); + checks.Equal(1, paths.Length, $"automation ICSTK page {i + 1}"); + if (paths.Length != 1) continue; + using var stream = File.OpenRead(paths[0]); + var saved = new StrokeCollection(stream); + checks.Equal(1, saved.Count, $"automation page {i + 1} stroke count"); + // WPF ISF 使用 HIMETRIC 量化,坐标误差最多约半个单位(0.019 DIP)。 + if (saved.Count == 1) + checks.Near(expectedX[i], saved[0].StylusPoints[0].X, $"automation page {i + 1} X", 0.02); + } + checks.That(!pending.IsMaterialized && ReferenceEquals(histories[3], pendingHistory), + "export preserves the pending page installation state"); + } + finally { Directory.Delete(directory, recursive: true); } + + static TimeMachineHistory[] PageHistory(int x) => new[] + { + new TimeMachineHistory(Batch(new Stroke(new StylusPointCollection { new StylusPoint(x, 20) })), + TimeMachineHistoryType.UserInput, false) + }; + } + + // 来自 mwtm-orig.cs。主画布与可选布局回调作参数,除此之外仅移除提交状态写入。 + private static void LegacyApplyHistoryToCanvas(TimeMachineHistory item, InkCanvas inkCanvas, + InkCanvas applyCanvas = null, HashSet elementsRemovedInThisPage = null, + Action CenterAndScaleElement = null, Action InitializeElementTransform = null) + { + var canvas = inkCanvas; + if (applyCanvas != null && applyCanvas is InkCanvas) + { + canvas = applyCanvas; + } + + if (item.CommitType == TimeMachineHistoryType.UserInput) + { + if (!item.StrokeHasBeenCleared) + { + foreach (var strokes in item.CurrentStroke) + if (!canvas.Strokes.Contains(strokes)) + canvas.Strokes.Add(strokes); + } + else + { + foreach (var strokes in item.CurrentStroke) + if (canvas.Strokes.Contains(strokes)) + canvas.Strokes.Remove(strokes); + } + } + else if (item.CommitType == TimeMachineHistoryType.ShapeRecognition) + { + if (item.StrokeHasBeenCleared) + { + if (item.CurrentStroke != null) + { + foreach (var strokes in item.CurrentStroke) + if (canvas.Strokes.Contains(strokes)) + canvas.Strokes.Remove(strokes); + } + + if (item.ReplacedStroke != null) + { + foreach (var strokes in item.ReplacedStroke) + if (!canvas.Strokes.Contains(strokes)) + canvas.Strokes.Add(strokes); + } + } + else + { + if (item.CurrentStroke != null) + { + foreach (var strokes in item.CurrentStroke) + if (!canvas.Strokes.Contains(strokes)) + canvas.Strokes.Add(strokes); + } + + if (item.ReplacedStroke != null) + { + foreach (var strokes in item.ReplacedStroke) + if (canvas.Strokes.Contains(strokes)) + canvas.Strokes.Remove(strokes); + } + } + } + else if (item.CommitType == TimeMachineHistoryType.Manipulation) + { + if (!item.StrokeHasBeenCleared) + { + foreach (var currentStroke in item.StylusPointDictionary) + { + if (canvas.Strokes.Contains(currentStroke.Key)) + { + currentStroke.Key.StylusPoints = currentStroke.Value.Item2; + } + } + } + else + { + foreach (var currentStroke in item.StylusPointDictionary) + { + if (canvas.Strokes.Contains(currentStroke.Key)) + { + currentStroke.Key.StylusPoints = currentStroke.Value.Item1; + } + } + } + if (item.DrawingAttributes != null) + foreach (var attributes in item.DrawingAttributes) + if (canvas.Strokes.Contains(attributes.Key)) + attributes.Key.DrawingAttributes = (item.StrokeHasBeenCleared + ? attributes.Value.Item1 : attributes.Value.Item2).Clone(); + if (item.ElementTransforms != null) + foreach (var transform in item.ElementTransforms) + if (canvas.Children.Contains(transform.Key)) + transform.Key.SetCurrentValue(UIElement.RenderTransformProperty, + (item.StrokeHasBeenCleared ? transform.Value.Item1 : transform.Value.Item2).CloneCurrentValue()); + } + else if (item.CommitType == TimeMachineHistoryType.DrawingAttributes) + { + if (!item.StrokeHasBeenCleared) + { + foreach (var currentStroke in item.DrawingAttributes) + { + if (canvas.Strokes.Contains(currentStroke.Key)) + { + currentStroke.Key.DrawingAttributes = currentStroke.Value.Item2; + } + } + } + else + { + foreach (var currentStroke in item.DrawingAttributes) + { + if (canvas.Strokes.Contains(currentStroke.Key)) + { + currentStroke.Key.DrawingAttributes = currentStroke.Value.Item1; + } + } + } + } + else if (item.CommitType == TimeMachineHistoryType.Clear) + { + if (!item.StrokeHasBeenCleared) + { + if (item.CurrentStroke != null) + foreach (var currentStroke in item.CurrentStroke) + if (!canvas.Strokes.Contains(currentStroke)) + canvas.Strokes.Add(currentStroke); + + if (item.ReplacedStroke != null) + foreach (var replacedStroke in item.ReplacedStroke) + if (canvas.Strokes.Contains(replacedStroke)) + canvas.Strokes.Remove(replacedStroke); + } + else + { + if (item.ReplacedStroke != null) + foreach (var replacedStroke in item.ReplacedStroke) + if (!canvas.Strokes.Contains(replacedStroke)) + canvas.Strokes.Add(replacedStroke); + + if (item.CurrentStroke != null) + foreach (var currentStroke in item.CurrentStroke) + if (canvas.Strokes.Contains(currentStroke)) + canvas.Strokes.Remove(currentStroke); + } + } + else if (item.CommitType == TimeMachineHistoryType.ElementInsert) + { + var targetCanvas = canvas ?? inkCanvas; + + if (item.StrokeHasBeenCleared) + { + if (elementsRemovedInThisPage != null) + return; + if (item.InsertedElement != null && targetCanvas.Children.Contains(item.InsertedElement)) + targetCanvas.Children.Remove(item.InsertedElement); + } + else + { + if (elementsRemovedInThisPage != null && item.InsertedElement != null && elementsRemovedInThisPage.Contains(item.InsertedElement)) + return; + if (item.InsertedElement != null && !targetCanvas.Children.Contains(item.InsertedElement)) + { + targetCanvas.Children.Add(item.InsertedElement); + + if (targetCanvas != inkCanvas) + { + if (item.InsertedElement is Image img) + { + double left = InkCanvas.GetLeft(img); + double top = InkCanvas.GetTop(img); + if (double.IsNaN(left) || double.IsNaN(top)) + { + CenterAndScaleElement(img); + } + } + else if (item.InsertedElement is MediaElement media) + { + double left = InkCanvas.GetLeft(media); + double top = InkCanvas.GetTop(media); + if (double.IsNaN(left) || double.IsNaN(top)) + { + CenterAndScaleElement(media); + } + } + else if (item.InsertedElement is CanvasMediaControl mediaControl) + { + double left = InkCanvas.GetLeft(mediaControl); + double top = InkCanvas.GetTop(mediaControl); + if (double.IsNaN(left) || double.IsNaN(top)) + { + CenterAndScaleElement(mediaControl); + } + } + else if (item.InsertedElement is FrameworkElement genericElement + && !(genericElement is Image) + && !(genericElement is MediaElement)) + { + // 插件插入的自定义控件(见 ICanvasElementService): + // 撤销重做重插后若位置缺失则居中,并补齐 TransformGroup。 + double left = InkCanvas.GetLeft(genericElement); + double top = InkCanvas.GetTop(genericElement); + if (double.IsNaN(left) || double.IsNaN(top)) + { + CenterAndScaleElement(genericElement); + } + if (genericElement.RenderTransform == null + || genericElement.RenderTransform == Transform.Identity) + { + InitializeElementTransform(genericElement); + } + } + } + } + } + } + + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkMappingTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkMappingTests.cs new file mode 100644 index 000000000..c6feb261b --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkMappingTests.cs @@ -0,0 +1,292 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; +using WpfInkCanvas = System.Windows.Controls.InkCanvas; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkMappingTests + { + internal static void Register(UInkSuite suite) + { + suite.Test(nameof(CoordinatesAndMediaMatrix), CoordinatesAndMediaMatrix); + suite.Test(nameof(PublicWidthsAndDeltas), PublicWidthsAndDeltas); + suite.Test(nameof(ExportTipAndLogicalKind), ExportTipAndLogicalKind); + suite.Test(nameof(CurrentPageFirst), CurrentPageFirst); + suite.Test(nameof(RegistryFallbackAndLayerCuts), RegistryFallbackAndLayerCuts); + suite.Test(nameof(CompositeUndo), CompositeUndo); + UInkReviewFixTests.Register(suite); + suite.Test(nameof(WorkerStrokeOnSta), WorkerStrokeOnSta); + } + + private static void CoordinatesAndMediaMatrix(UInkChecks c) + { + var vp = new UInkViewport { X = 10, Y = 20, Scale = 3 }; + var map = new UInkCoordinateMap(2, 4, vp); + var dip = map.ToDip(14, 32); + c.Equal(new Point(6, 9), dip, "axis-specific DIP"); + c.Equal(new Point(14, 32), map.FromDip(dip.X, dip.Y), "inverse point"); + c.Near(3 / Math.Sqrt(8), map.LengthToDip(1), "width DPI"); + var local = new Point(4, 2); + // (4,2) DIP → (8,8) px → (6,48) canvas → (-6,21) DIP。 + var matrix = map.MapMediaMatrix(new float[] { 0, 2, -1, 0, 14, 32 }); + c.Equal(new Point(-6, 21), matrix.Transform(local), "D M V D^-1"); + c.Equal(map.ToDip(8, 8), map.MapMediaMatrix(null).Transform(local), "identity media"); + vp.Scale = float.NaN; + c.Equal(new Point(7, 8), new UInkCoordinateMap(2, 4, vp).ToDip(14, 32), "invalid viewport"); + + var shape = new UInkShape + { + ShapeType = 0, Stroke = new UInkStroke { Width = 8 }, + Geometry = new UInkLineGeometry { Points = new List + { new() { X = 14, Y = 32 }, new() { X = 24, Y = 40 } } } + }; + var outline = UInkConversion.ShapeToStroke(shape, map); + c.Equal(dip, outline.StylusPoints[0].ToPoint(), "mapped shape"); + c.Near(24 / Math.Sqrt(8), outline.DrawingAttributes.Width, "mapped outline width"); + } + + private static void PublicWidthsAndDeltas(UInkChecks c) + { + var ink = new UInkInk + { + Points = new[] { new UInkPoint(16777216, 0, 1), new UInkPoint(1, 0, 70), new UInkPoint(-16777216, 2, 7) }, + Color = new UInkColor { Fallback = 0x123456 }, Opacity = 0.25f, + InkType = 3, Nib = new UInkNib { Shape = 1, Aspect = 0.5f, Orientation = 1 }, + Extra = new() { ["icc:da"] = "Width=42;Color=#FFFFFFFF;IgnorePressure=True;FitToCurve=True" } + }; + var notes = new List(); + var stroke = UInkConversion.InkToStroke(ink, new UInkCoordinateMap(2, 2), notes.Add); + c.Equal(new Point(0.5, 1), stroke.StylusPoints[2].ToPoint(), "double delta accumulation"); + var da = stroke.DrawingAttributes; + c.Equal(Color.FromArgb(64, 0x12, 0x34, 0x56), da.Color, "public color and alpha"); + c.That(!da.IgnorePressure && !da.FitToCurve && da.IsHighlighter, "public ink attributes"); + c.Near(20, da.Height, "B after DPI"); + c.Near(10, da.Width, "aspect times B"); + c.Near(0, stroke.StylusPoints[0].PressureFactor, "unrepresentable width clamp"); + c.Near(1, stroke.StylusPoints[1].PressureFactor, "maximum pressure"); + c.Equal(1, notes.FindAll(s => s == "widthRangeApprox").Count, "one range diagnostic"); + c.That(notes.Contains("nibDirectionApprox"), "FollowDirection diagnostic"); + ink.InkType = 200; + ink.Points = new[] { new UInkPoint(5, 4, 8) }; + stroke = UInkConversion.InkToStroke(ink); + c.That(!stroke.DrawingAttributes.IsHighlighter && stroke.DrawingAttributes.IgnorePressure, "constant fallback pen"); + ink.InkType = 0; + c.That(UInkConversion.InkToStroke(ink) == null, "Erase skipped"); + } + + private static void ExportTipAndLogicalKind(UInkChecks c) + { + var pts = new StylusPointCollection + { + new StylusPoint(0, 0, 0.1f), new StylusPoint(12, 18, 0.6f), + new StylusPoint(25, 3, 0.3f), new StylusPoint(38, 24, 0.9f) + }; + var da = new DrawingAttributes { Width = 8, Height = 2, IgnorePressure = true, FitToCurve = false }; + var stroke = new Stroke(pts, da); + stroke.AddPropertyData(UInkConversion.LogicalPenKindGuid, 2); + var notes = new List(); + var ink = UInkConversion.StrokeToInk(stroke, note: notes.Add); + c.Near(4, ink.Points[0].Width, "equal area diameter"); + c.That(notes.Contains("ellipseWidthApprox"), "ellipse diagnostic"); + c.Equal(2, ink.InkType, "logical highlighter"); + c.That(ink.Extra == null || !ink.Extra.ContainsKey("icc:da"), "no private DA"); + double cos = Math.Sqrt(0.5); + da.StylusTipTransform = new Matrix(cos, cos, -cos, cos, 0, 0); + c.Near(4, UInkConversion.StrokeToInk(stroke).Points[0].Width, "rotated ellipse diameter"); + da.StylusTipTransform = new Matrix(2 * cos, 2 * cos, -3 * cos, 3 * cos, 0, 0); + c.Near(Math.Sqrt(96), UInkConversion.StrokeToInk(stroke).Points[0].Width, "affine ellipse diameter"); + da.StylusTip = StylusTip.Rectangle; + da.StylusTipTransform = new Matrix(2, 0, 0, 3, 0, 0); + ink = UInkConversion.StrokeToInk(stroke); + c.Near(6, ink.Points[0].Width, "scaled rectangle height"); + c.Near(16.0 / 6, ink.Nib.Aspect, "scaled rectangle aspect"); + c.Equal(null, ink.Cap, "rectangle cap omitted"); + da.StylusTipTransform = new Matrix(1, 0.5, -1, 1, 0, 0); + da.FitToCurve = true; + ink = UInkConversion.StrokeToInk(stroke, note: notes.Add); + c.Near(6, ink.Points[0].Width, "transformed bounding height"); + c.Near(10.0 / 6, ink.Nib.Aspect, "transformed bounding aspect"); + c.That(notes.Contains("tipTransformApprox"), "non-axis-aligned diagnostic"); + var fitted = stroke.GetBezierStylusPoints(); + c.That(fitted.Count != pts.Count, "fixture distinguishes fitted and raw points"); + c.Equal(fitted.Count, ink.Points.Length, "per-stroke Bezier samples"); + da.IgnorePressure = false; + ink = UInkConversion.StrokeToInk(stroke); + double x = 0, y = 0; + for (int i = 0; i < fitted.Count; i++) + { + x += ink.Points[i].X; + y += ink.Points[i].Y; + c.Near(fitted[i].X, x, $"Bezier {i} X"); + c.Near(fitted[i].Y, y, $"Bezier {i} Y"); + c.Near(6 * (0.25 + 1.5 * fitted[i].PressureFactor), ink.Points[i].Width, $"Bezier {i} pressure width"); + } + stroke.AddPropertyData(InkFadeManager.LaserRenderModeGuid, true); + var (pages, bytes) = UInkTestApi.SavePagesAndReload(new[] { new StrokeCollection { stroke } }, 1); + c.Equal(0, pages[0].Count, "laser excluded from saved page"); + c.That(!UInkWireInspection.Read(bytes, c).Exists(b => b.Type == 3), "no laser on wire"); + } + + private static void CurrentPageFirst(UInkChecks c) + { + static UInkReadResult ReadFixture(string name) => UInkReader.Read( + Path.Combine(AppContext.BaseDirectory, "TestData", "UInk", "v11", name + ".uink"), + new UInkReadOptions { MaterializeContent = false }); + var read = ReadFixture("standard-ppt"); + var projection = UInkIccMapper.BuildPageIndex(read, 1, 1); + c.Equal(1, projection.CurrentPageDisplayIndex, "selected page"); + c.That(projection.Pages[1].IsMaterialized && !projection.Pages[0].IsMaterialized, "only current page ready"); + c.That(projection.Pages[1].IsUnbound && !projection.Pages[2].IsUnbound, "disconnected SlideID and PageIndex"); + c.That(!projection.RetainedPages[0].IsMaterialized, "retained page remains lazy"); + projection.Pages[0].EnsureMaterialized(); + var strokes = projection.Pages[0].FinalStrokes; + projection.Pages[0].EnsureMaterialized(); + c.That(ReferenceEquals(strokes, projection.Pages[0].FinalStrokes), "materialization idempotent"); + read = ReadFixture("full-layers-devices"); + projection = UInkIccMapper.BuildPageIndex(read, 1, 1); + c.Equal(2, read.Pending, "other Device and Workspace content not decoded"); + c.That(projection.RequiresSaveAs, "undisplayed content requires Save As"); + } + + private static void RegistryFallbackAndLayerCuts(UInkChecks c) + { + string Id(uint n) => UInkTestEncoder.PageGuid(n); + var empty = new UInkWorkspace { Guid = Id(80), WorkspaceType = 1 }; + var board = new UInkWorkspace { Guid = Id(81), WorkspaceType = 1, CurrentPageIndex = 99 }; + var ext = new UInkHeaderExtension + { + WorkspacesDeclared = true, DevicesDeclared = true, Workspaces = new() { empty, board }, + Devices = new() { new() { Guid = Id(90) }, new() { Guid = Id(91) } } + }; + var doc = new UInkDocument { HeaderExtension = ext }; + UInkCanvasRecord Record(string ws, string device, uint page, uint layer) + { + var record = new UInkCanvasRecord { Canvas = new UInkCanvas + { + WorkspaceGuid = ws, DeviceGuid = device, PageGuid = Id(page), + PageIndex = 7, PageNumber = page, LayerIndex = layer + }, StreamOrdinal = doc.Canvases.Count }; + doc.Canvases.Add(record); + return record; + } + Record(Id(83), Id(90), 1, 0); + var top = Record(board.Guid, Id(91), 4, 1); + top.Blocks.Add(new UInkMedia { Path = "cleared.png" }); + top.Blocks.Add(new UInkClear { UndoId = 1 }); + top.Blocks.Add(new UInkInk { UndoId = 2, Points = new[] { new UInkPoint(16, 10, 4) } }); + Record(board.Guid, Id(99), 4, 0).Blocks.Add(new UInkMedia { Path = "wrong-device.png" }); + Record(board.Guid, Id(91), 3, 0); + var bottom = Record(board.Guid, Id(91), 4, 0); + bottom.Canvas.Viewport = new UInkViewport { X = 10, Y = 2, Scale = 3 }; + bottom.Blocks.Add(new UInkMedia { Path = "kept.png" }); + Record("", Id(90), 5, 0); + var read = new UInkReadResult { Document = doc }; + var projection = UInkIccMapper.BuildPageIndex(read, 1.5, 1.5); + c.Equal(board.Guid, projection.Workspace.Guid, "first registered root with pages"); + c.Equal(3, projection.UndisplayedWorkspaces.Count, "empty root and two temporary workspaces"); + c.Equal((empty.Guid, 1, 0), projection.UndisplayedWorkspaces[0], "registration before temporary items"); + c.Equal((Id(83), 1, 1), projection.UndisplayedWorkspaces[1], "first referenced temporary root"); + c.Equal(("", 1, 1), projection.UndisplayedWorkspaces[2], "missing reference kept separate"); + c.That(read.DiagnosticCounts.ContainsKey("FILE-23") && read.DiagnosticCounts.ContainsKey("HEXT-10"), + "temporary registry and stale current page diagnostics"); + c.Equal(0, projection.CurrentPageDisplayIndex, "out-of-range current page"); + c.Equal(2, projection.Pages.Count, "one logical page per GUID"); + c.Equal(Id(3), projection.Pages[0].Canvas.PageGuid, "equal pageIndex ordered by last layer"); + c.Equal(0, projection.Pages[0].FinalStrokes.Count, "empty page preserved"); + var page = projection.Pages[1]; + page.EnsureMaterialized(); + c.Equal(2, page.History.Length, "Clear cuts its own layer only"); + c.Equal(1, page.Media.Count, "only selected device and surviving media"); + c.Equal("kept.png", page.Media[0].Path, "bottom layer unaffected"); + c.Equal(new Point(12, 16), page.FinalStrokes[0].StylusPoints[0].ToPoint(), "upper layer inherits viewport"); + c.Near(8, page.FinalStrokes[0].DrawingAttributes.Width, "upper layer inherits width scale"); + } + + private static void CompositeUndo(UInkChecks c) + { + var rec = new UInkCanvasRecord { Canvas = new UInkCanvas() }; + UInkInk Ink(uint group, int kind = 1) => new() { UndoId = group, InkType = kind, + Points = new[] { new UInkPoint(0, 0, 5) } }; + var first = Ink(7); + first.RenderOnlyWhenLatest = true; + rec.Blocks.Add(first); + rec.Blocks.Add(Ink(8, 0)); + rec.Blocks.Add(Ink(7)); + rec.Blocks.Add(new UInkMedia { UndoId = 7, Path = "missing.png" }); + var read = new UInkReadResult { Document = new UInkDocument { Canvases = new() { rec } } }; + var page = UInkIccMapper.BuildPageIndex(read, 1, 1).Pages[0]; + c.Equal(2, page.History.Length, "Erase-only group splits equal undo IDs"); + c.Equal(2, page.FinalStrokes.Count, "visible strokes"); + var machine = new TimeMachine(); + machine.ImportTimeMachineHistory(page.History); + var group = (UInkGroupHistory)page.History[1]; + c.Equal(1, group.Elements.Length, "missing media owns a placeholder"); + c.That(ReferenceEquals(page.FinalStrokes[1], group.CurrentStroke[0]), "same visible stroke reference"); + group.Elements[0] = new Border(); + var canvas = new WpfInkCanvas(); + ((UInkGroupHistory)page.History[0]).ApplyTo(canvas, true); + group.ApplyTo(canvas, true); + ((UInkGroupHistory)machine.Undo()).ApplyTo(canvas, true); + c.Equal(0, canvas.Children.Count, "one undo removes group's element"); + c.Equal(1, canvas.Strokes.Count, "one undo removes group's stroke"); + c.That(ReferenceEquals(page.FinalStrokes[0], canvas.Strokes[0]), "earlier group remains"); + ((UInkGroupHistory)machine.Redo()).ApplyTo(canvas, true); + c.That(canvas.Children.Contains(group.Elements[0]) && ReferenceEquals(page.FinalStrokes[1], canvas.Strokes[1]), + "one redo restores both references"); + + canvas.Strokes.Remove(group.CurrentStroke[0]); + ((UInkGroupHistory)machine.Undo()).ApplyTo(canvas, true); + c.Equal(1, canvas.Strokes.Count, "undo of an already missing group member keeps other strokes"); + c.Equal(0, canvas.Children.Count, "missing stroke still allows undo of the group's elements"); + } + + private static void WorkerStrokeOnSta(UInkChecks c) + { + c.Equal(ApartmentState.STA, Thread.CurrentThread.GetApartmentState(), "consumer STA"); + Stroke stroke = null; + Exception error = null; + var worker = new Thread(() => + { + try + { + var points = new StylusPointCollection(2) { new StylusPoint(8, 12), new StylusPoint(40, 12) }; + stroke = new Stroke(points, new DrawingAttributes { Color = Colors.Red, Width = 6, Height = 6, IgnorePressure = true }); + } + catch (Exception ex) { error = ex; } + }) { IsBackground = true }; + worker.SetApartmentState(ApartmentState.MTA); + UInkSuites.ObserveWorker(worker); + worker.Start(); + if (!worker.Join(TimeSpan.FromSeconds(10))) throw new TimeoutException("Stroke worker"); + if (error != null) throw new InvalidOperationException("Worker stroke construction", error); + + var canvas = new WpfInkCanvas { Width = 64, Height = 64, Background = Brushes.Transparent }; + canvas.Strokes.Add(stroke); + c.Equal(1, canvas.Strokes.HitTest(new Point(24, 12)).Count, "hit worker stroke on STA"); + var clone = stroke.Clone(); + stroke.Transform(new Matrix(1, 0, 0, 1, 0, 16), true); + c.That(clone.HitTest(new Point(24, 12)) && stroke.HitTest(new Point(24, 28)), "independent clone and transform"); + + // 离屏布局并验证变换后的红色像素,全程不创建 Window。 + canvas.Measure(new Size(64, 64)); + canvas.Arrange(new Rect(0, 0, 64, 64)); + canvas.UpdateLayout(); + var bitmap = new RenderTargetBitmap(64, 64, 96, 96, PixelFormats.Pbgra32); + bitmap.Render(canvas); + var pixels = new byte[64 * 64 * 4]; + bitmap.CopyPixels(pixels, 64 * 4, 0); + int pixel = (28 * 64 + 24) * 4; + c.That(pixels[pixel + 2] > 200 && pixels[pixel + 1] < 30 && pixels[pixel + 3] > 200, "rendered stroke pixel"); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkMediaTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkMediaTests.cs new file mode 100644 index 000000000..45a3a63a0 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkMediaTests.cs @@ -0,0 +1,1234 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Reflection; +using System.Diagnostics; +using System.Text; +using System.Threading; +using System.Runtime.Serialization; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; +using System.Windows.Controls; +using System.Windows.Ink; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; +using Ink_Canvas; +using Ink_Canvas.Controls; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; + +namespace InkCanvas.Calibration.Tests.UInk +{ + using InkCanvas = System.Windows.Controls.InkCanvas; + + internal static class UInkMediaTests + { + private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + internal static void Register(UInkSuite suite) + { + suite.Test(nameof(AffineLayoutAt150Percent), AffineLayoutAt150Percent); + suite.Test(nameof(FitMapsToNativeStretch), FitMapsToNativeStretch); + suite.Test(nameof(DeferredBitmapPngRoundTrip), DeferredBitmapPngRoundTrip); + suite.Test(nameof(MediaResourcesAcrossPages), MediaResourcesAcrossPages); + suite.Test(nameof(WorkSetKeepsSnapshotBytes), WorkSetKeepsSnapshotBytes); + suite.Test(nameof(UnvisitedMediaBakesViewport), UnvisitedMediaBakesViewport); + suite.Test(nameof(MissingMediaSharesUndoGroup), MissingMediaSharesUndoGroup); + suite.Test(nameof(PlaybackStartIsClamped), PlaybackStartIsClamped); + UInkSuites.RunIsolated(suite, nameof(ImportedPdfFlipKeepsWhiteboardHistory), ImportedPdfFlipKeepsWhiteboardHistory); + suite.Test(nameof(PdfRasterLimits), PdfRasterLimits); + suite.Test(nameof(NativeBitmapDpiRoundTripPixels), NativeBitmapDpiRoundTripPixels); + suite.Test(nameof(ImportedVideoKeepsNativeLayout), ImportedVideoKeepsNativeLayout); + suite.Test(nameof(NativeVideoUsesPublicPreviewBox), NativeVideoUsesPublicPreviewBox); + suite.Test(nameof(ForeignMediaFitRequiresSaveAs), ForeignMediaFitRequiresSaveAs); + suite.Test(nameof(RestoredBitmapIsCollectedForLegacySidecar), RestoredBitmapIsCollectedForLegacySidecar); + suite.Test(nameof(ReplacedValidPngKeepsDisplayedPixels), ReplacedValidPngKeepsDisplayedPixels); + suite.Test(nameof(SaveAsReportsDroppedMediaAndReencodesBitmap), SaveAsReportsDroppedMediaAndReencodesBitmap); + suite.Test(nameof(VideoMimeSignaturesAndSuffixes), VideoMimeSignaturesAndSuffixes); + suite.Test(nameof(OverlappingOpensKeepOrReplaceRestoringDocument), OverlappingOpensKeepOrReplaceRestoringDocument); + suite.Test(nameof(DeferredMediaUsesOriginalSlotAndRejectsStaleResults), DeferredMediaUsesOriginalSlotAndRejectsStaleResults); + suite.Test(nameof(LayoutTransformCaptureUsesActualAffineMap), LayoutTransformCaptureUsesActualAffineMap); + } + + private static void AffineLayoutAt150Percent(UInkChecks c) + { + var image = new Image + { + Width = 40, Height = 20, RenderTransformOrigin = new Point(0.25, 0.75), Opacity = 0.6, + Source = BitmapSource.Create(2, 1, 96, 96, PixelFormats.Bgra32, null, new byte[8], 8), + Stretch = Stretch.UniformToFill + }; + var transform = Matrix.Identity; + transform.Scale(2, 3); + transform.Rotate(90); + transform.Skew(0, 45); + transform.Translate(4, 6); + image.RenderTransform = new MatrixTransform(transform); + InkCanvas.SetLeft(image, 80); + InkCanvas.SetTop(image, 25); + var page = Page(0); + MainWindow.CaptureUInkPage(page, null, new StrokeCollection(), new[] { image }); + var coordinates = new UInkCoordinateMap(1.5, 1.5); + var media = UInkMediaMapper.Capture(page.Elements.Single(), coordinates, "image/png"); + c.Near(60, media.Width, "pre-transform width in device pixels"); + c.Near(30, media.Height, "pre-transform height in device pixels"); + c.Near(0.6, media.Opacity, "opacity"); + c.Equal(2, media.Fit, "cover fit"); + + // 局部中心 (10,15):平移后 (94,46)。局部基向量再验证旋转、缩放与错切的次序。 + var wire = new Matrix(media.Transform[0], media.Transform[1], media.Transform[2], media.Transform[3], + media.Transform[4], media.Transform[5]); + PointNear(c, new Point(141, 69), wire.Transform(new Point(15, 22.5)), "Device pivot"); + PointNear(c, new Point(141, 72), wire.Transform(new Point(16.5, 22.5)), "Device X basis"); + PointNear(c, new Point(136.5, 64.5), wire.Transform(new Point(15, 24)), "Device Y basis"); + + var restored = new Image(); + UInkMediaMapper.ApplyLayout(restored, media, coordinates); + c.Near(40, restored.Width, "roundtrip local width"); + c.Near(20, restored.Height, "roundtrip local height"); + c.That(restored.RenderTransform is MatrixTransform, "restored affine transform"); + c.Near(0, InkCanvas.GetLeft(restored), "embedded translation leaves Left=0"); + c.Near(0, InkCanvas.GetTop(restored), "embedded translation leaves Top=0"); + PointNear(c, new Point(94, 46), restored.RenderTransform.Value.Transform(new Point(10, 15)), "DIP pivot"); + + // 不等 DPI 的剪切系数会改变,等比 DPI 的回环不足以发现 S 与 S⁻¹ 写反。 + var anisotropic = new UInkCoordinateMap(1.5, 2); + var nonuniform = UInkMediaMapper.Capture(page.Elements[0], anisotropic, "image/png"); + c.Near(8.0 / 3, nonuniform.Transform[1], "Device x-to-y linear coefficient"); + c.Near(-2.25, nonuniform.Transform[2], "Device y-to-x linear coefficient"); + UInkMediaMapper.ApplyLayout(restored, nonuniform, anisotropic); + PointNear(c, new Point(91, 43), restored.RenderTransform.Value.Transform(new Point(10, 16)), "nonuniform DPI roundtrip"); + + var auto = new Image { Source = Bitmap(), Stretch = Stretch.Fill }; + auto.Measure(new Size(27, 19)); + auto.Arrange(new Rect(0, 0, 27, 19)); + var autoPage = Page(0); + MainWindow.CaptureUInkPage(autoPage, null, new StrokeCollection(), new[] { auto }); + var autoMedia = UInkMediaMapper.Capture(autoPage.Elements.Single(), coordinates, "image/png"); + c.Near(40.5, autoMedia.Width, "Auto width falls back to ActualWidth"); + c.Near(28.5, autoMedia.Height, "Auto height falls back to ActualHeight"); + } + + private static void FitMapsToNativeStretch(UInkChecks c) + { + var modes = new[] { Stretch.Fill, Stretch.Uniform, Stretch.UniformToFill, Stretch.None }; + for (int i = 0; i < modes.Length; i++) + { + c.Equal(i, UInkMediaMapper.FitFromStretch(modes[i]), "Stretch to fit"); + c.Equal(modes[i], UInkMediaMapper.StretchFromFit(i), "fit to Stretch"); + } + c.Equal(Stretch.Fill, UInkMediaMapper.StretchFromFit(128), "unknown fit"); + c.Equal(Stretch.Fill, UInkMediaMapper.StretchFromFit(null), "missing fit"); + + } + + internal static void AssertStandardMediaCropIgnored(UInkChecks c, string path) + { + using var tmp = new TempDirectory(); + var read = UInkReader.Read(path); + // 直接用夹具中的裁剪块,单独安装,避开同页无关的 PDF 和音频。 + var blocks = read.Document.Canvases.Single().Blocks; + blocks.RemoveAll(block => block is not UInkMedia { Crop: not null }); + var page = UInkIccMapper.BuildPageIndex(read, 1, 1).Pages.Single(); + using var cache = UInkMediaRestoreCache.Open(path, Path.Combine(tmp.Root, "cache")); + var canvas = new InkCanvas { Background = Brushes.Transparent }; + WaitForUi(HeadlessWindow(canvas, new TimeMachine()).InstallUInkPage(page, cache, UInkMediaMapper.PageCoordinates(page.Canvas, 1, 1))); + c.Equal(1, read.DiagnosticCounts.GetValueOrDefault("mediaCropIgnored"), "foreign bitmap crop is diagnosed once"); + c.That(read.RequiresSaveAs, "bitmap crop fallback requires Save As"); + var image = (Image)canvas.Children[0]; + c.Equal(Stretch.Fill, image.Stretch, "fixture file fit maps to native Stretch"); + + var media = page.Media.Single(); + var full = UInkMediaMapper.DecodeBitmap(cache.GetVerifiedPath(media.Path, media.MimeType)); + var reference = new InkCanvas { Background = Brushes.Transparent }; + reference.Children.Add(new Image { Width = 160, Height = 160, Source = full, Stretch = Stretch.Fill, + RenderTransform = new MatrixTransform(0, 1.5, -1.5, 0, 1170, 75) }); + byte[] expected = Render(reference); + c.That(expected[(255 * 1200 + 960) * 4 + 3] == 255, "full fixture image is visible in its last quadrant"); + c.That(expected.SequenceEqual(Render(canvas)), "crop is ignored on display and all four fixture quadrants are rendered"); + + static byte[] Render(InkCanvas surface) + { + var size = new Size(1200, 340); + surface.Measure(size); + surface.Arrange(new Rect(size)); + var target = new RenderTargetBitmap(1200, 340, 96, 96, PixelFormats.Pbgra32); + target.Render(surface); + return Pixels(target); + } + } + + private static void DeferredBitmapPngRoundTrip(UInkChecks c) + { + using var tmp = new TempDirectory(); + var source = new TransformedBitmap(Bitmap(), new RotateTransform(90)); + var image = new Image { Width = 15, Height = 25, Source = source }; + var page = Page(0); + MainWindow.CaptureUInkPage(page, null, new StrokeCollection(), new[] { image }); + var capture = page.Elements.Single(); + c.That(capture.Bitmap.IsFrozen && !source.IsFrozen, "freeze a snapshot without freezing the live bitmap"); + byte[] expected = Pixels(source); + + string file = Path.Combine(tmp.Root, "bitmap.png"); + Task.Run(() => + { + using var stream = File.Create(file); + UInkMediaMapper.EncodePng(capture.Bitmap, stream); + }).GetAwaiter().GetResult(); + var restored = UInkMediaMapper.DecodeBitmap(file); + c.Equal(source.PixelWidth, restored.PixelWidth, "PNG reloaded width"); + c.Equal(source.PixelHeight, restored.PixelHeight, "PNG reloaded height"); + c.That(expected.SequenceEqual(Pixels(restored)), "PNG pixels round trip exactly"); + } + + private static void MediaResourcesAcrossPages(UInkChecks c) + { + using var tmp = new TempDirectory(); + string file = Path.Combine(tmp.Root, "source.png"), secondFile = Path.Combine(tmp.Root, "same.png"); + using (var stream = File.Create(file)) UInkMediaMapper.EncodePng(Bitmap(), stream); + File.Copy(file, secondFile); + string expectedEntry = UInkExtraArchive.ContentHashPath(File.ReadAllBytes(file), ".png"); + + var live = new InkCanvas(); + var first = new Image { Width = 20, Height = 30, Source = FileBitmap(file), Stretch = Stretch.Uniform }; + InkCanvas.SetLeft(first, 12); + live.Children.Add(first); + var second = new Image { Width = 20, Height = 10, Source = FileBitmap(secondFile), Stretch = Stretch.None, Opacity = 0.4 }; + InkCanvas.SetTop(second, 20); + var extra = new Image { Width = 10, Height = 10, Source = new TransformedBitmap(Bitmap(), new RotateTransform(90)) }; + var history = new TimeMachine(); + history.CommitElementInsertHistory(second); + history.CommitElementInsertHistory(extra); + var p0 = Page(0); + var p1 = Page(1); + MainWindow.CaptureUInkPage(p0, null, live.Strokes, live.Children.Cast()); + MainWindow.CaptureUInkPage(p1, history.GetAppliedHistorySnapshot(), null, null); + + var context = new UInkCaptureContext { Workspace = new UInkWorkspace { Guid = UInkTestEncoder.WorkspaceGuid, + WorkspaceType = (int)UInkWorkspaceType.Whiteboard, CurrentPageIndex = 0 }, DpiX = 1.5, DpiY = 1.5 }; + context.Pages.Add(p0); + context.Pages.Add(p1); + string target = Path.Combine(tmp.Root, "all-pages.uink"); + Task.Run(() => context.Save(target, false)).GetAwaiter().GetResult(); + using (var pack = ZipFile.OpenRead(target + ".extra")) + { + var original = pack.GetEntry(expectedEntry); + c.That(original != null, "original PNG entry uses its exact byte digest"); + if (original != null) + { + using var copied = original.Open(); + using var bytes = new MemoryStream(); + copied.CopyTo(bytes); + c.That(File.ReadAllBytes(file).SequenceEqual(bytes.ToArray()), "original file bytes survive"); + } + c.Equal(2, pack.Entries.Count, "two original file paths share one entry and memory PNG has its own"); + } + + var read = UInkReader.Read(target, new UInkReadOptions { MaterializeContent = false }); + var canvas = new InkCanvas(); + var dpi = VisualTreeHelper.GetDpi(canvas); + var board = UInkIccMapper.BuildPageIndex(read, dpi.DpiScaleX, dpi.DpiScaleY); + c.Equal(2, board.Pages.Count, "two saved pages"); + c.That(!board.Pages[1].IsMaterialized, "second page deferred until installation"); + using var cache = UInkMediaRestoreCache.Open(target, Path.Combine(tmp.Root, "cache")); + var machine = new TimeMachine(); + var window = HeadlessWindow(canvas, machine); + WaitForUi(window.InstallUInkPage(board.Pages[0], cache)); + c.Equal(1, canvas.Children.Count, "first page media only"); + c.Equal(expectedEntry, board.Pages[0].Media.Single().Path, "first file resource"); + var firstBitmap = ((Image)canvas.Children[0]).Source; + c.Near(18 / dpi.DpiScaleX, ((FrameworkElement)canvas.Children[0]).RenderTransform.Value.OffsetX, "first page Device translation"); + + canvas.Children.Clear(); + WaitForUi(window.InstallUInkPage(board.Pages[1], cache)); + c.That(board.Pages[1].IsMaterialized, "second page materialized by install"); + c.Equal(2, canvas.Children.Count, "second page restores file and PNG"); + c.Equal(expectedEntry, board.Pages[1].Media[0].Path, "identical original resources share a path"); + var restored = (Image)canvas.Children[0]; + c.That(ReferenceEquals(firstBitmap, restored.Source), "content cache shares the frozen bitmap"); + c.Equal(Stretch.Fill, restored.Stretch, "second page stores the native None picture as its visible frame"); + c.Near(0.4, restored.Opacity, "second page retains opacity"); + c.Near((20 + (10 - second.Source.Height) / 2) * 1.5 / dpi.DpiScaleY, + restored.RenderTransform.Value.OffsetY, "second page includes native None alignment"); + c.That(board.Pages[1].Media[1].Path.StartsWith("media/", StringComparison.Ordinal) && + board.Pages[1].Media[1].MimeType == "image/png", "memory bitmap has a hashed PNG resource"); + window.ApplyHistoryToCanvas(machine.Undo()); + c.Equal(1, canvas.Children.Count, "undo last insertion on second page"); + window.ApplyHistoryToCanvas(machine.Redo()); + c.Equal(2, canvas.Children.Count, "redo last insertion on second page"); + } + + private static void WorkSetKeepsSnapshotBytes(UInkChecks c) + { + using var tmp = new TempDirectory(); + using var work = new UInkMediaWorkSet(); + string source = Path.Combine(tmp.Root, "mutable.png"); + using (var stream = File.Create(source)) UInkMediaMapper.EncodePng(Bitmap(), stream); + byte[] original = File.ReadAllBytes(source); + string entryPath = work.Add(source, null, "image/png"); + File.WriteAllBytes(source, new byte[] { 4, 5, 6 }); + c.Equal(entryPath, work.Add(source, null, "image/png"), "each source is captured once per save"); + c.Equal(UInkExtraArchive.ContentHashPath(original, ".png"), entryPath, "hash uses captured bytes"); + string path = Path.Combine(tmp.Root, "snapshot.extra"); + UInkExtraArchive.WriteArchive(path, work.Resources); + using var archive = ZipFile.OpenRead(path); + using var entry = archive.Entries.Single().Open(); + using var bytes = new MemoryStream(); + entry.CopyTo(bytes); + c.That(original.SequenceEqual(bytes.ToArray()), "archive bytes are independent of subsequent source edits"); + } + + private static void UnvisitedMediaBakesViewport(UInkChecks c) + { + using var tmp = new TempDirectory(); + string file = Path.Combine(tmp.Root, "source.png"); + using (var stream = File.Create(file)) UInkMediaMapper.EncodePng(Bitmap(), stream); + string entry = UInkExtraArchive.ContentHashPath(file, ".png"); + var workspace = new UInkWorkspace { Guid = UInkTestEncoder.WorkspaceGuid, + WorkspaceType = (int)UInkWorkspaceType.Whiteboard, CurrentPageIndex = 0 }; + var first = Page(0); + var imported = Page(1); + imported.Canvas.Viewport = new UInkViewport { X = 100, Y = 50, Scale = 1.5f }; + imported.Media.Add(new UInkMedia { Path = entry, MimeType = "image/png", Width = 250, Height = 180, Fit = 3, + Crop = new UInkCrop { X = 0, Y = 1, Width = 1, Height = 2 }, + Transform = new[] { 0f, 2f, -3f, 0f, 140f, 80f } }); + var doc = UInkIccMapper.BuildDocument(UInkIccMapper.NewFileGuid(), null, new[] { workspace }, new[] { first, imported }, 0); + string original = Path.Combine(tmp.Root, "imported.uink"); + UInkSaveService.SaveFull(doc, original, new[] { (entry, file) }); + var read = UInkReader.Read(original, new UInkReadOptions { MaterializeContent = false }); + var pending = UInkIccMapper.BuildPageIndex(read, 1.5, 1.5).Pages[1]; + c.That(!pending.IsMaterialized, "source page starts deferred"); + + using var cache = UInkMediaRestoreCache.Open(original, Path.Combine(tmp.Root, "cache")); + var snapshot = new UInkCaptureContext { Workspace = workspace, DpiX = 1, DpiY = 1, Resources = cache }; + snapshot.Pages.Add(Page(0)); + var captured = Page(1); + snapshot.CapturePendingPage(captured, pending, UInkMediaMapper.PageCoordinates(pending.Canvas, 1.5, 1.5)); + snapshot.Pages.Add(captured); + string target = Path.Combine(tmp.Root, "copy.uink"); + snapshot.Save(target, false); + c.That(!pending.IsMaterialized, "save does not install the deferred source page"); + var saved = UInkReader.Read(target).Document.Canvases[1]; + c.That(saved.Canvas.Viewport == null, "new snapshot uses the identity viewport"); + var media = (UInkMedia)saved.Blocks.Single(); + c.Floats(new[] { 0f, 2f, -3f, 0f, 40f, 30f }, media.Transform, "viewport and target DPI baked into unvisited media"); + c.Near(250, media.Width, "local width unchanged by viewport"); + c.Near(180, media.Height, "local height unchanged by viewport"); + c.Equal(3, media.Fit, "deferred fit"); + c.Near(1, media.Crop?.Y, "deferred resource crop"); + } + + private static void MissingMediaSharesUndoGroup(UInkChecks c) + { + using var bytes = new MemoryStream(); + var encoder = new UInkTestEncoder(bytes); + encoder.Header(11, 1); + encoder.HeaderExtension(); + encoder.Canvas(0, whiteboard: true); + encoder.Media(0, 0, "images/missing.png"); + encoder.Media(1, 0, "../outside.png"); + encoder.Ink(2, 0, 0x112233, new[] { new UInkTestPoint(5, 6, 4) }); + var read = UInkReader.Read(bytes.ToArray(), new UInkReadOptions { MaterializeContent = false }); + var page = UInkIccMapper.BuildPageIndex(read, 1, 1).Pages.Single(); + var canvas = new InkCanvas(); + var history = new TimeMachine(); + var window = HeadlessWindow(canvas, history); + using var cache = new UInkMediaRestoreCache(null, null, null); + Task.Run(() => MainWindow.PrepareUInkMediaFiles(page, cache)).GetAwaiter().GetResult(); + WaitForUi(window.InstallUInkPage(page, cache)); + c.That(read.RequiresSaveAs, "missing resources require Save As"); + c.Equal(2, canvas.Children.Count, "both resource failures keep their layout"); + c.Equal(1, canvas.Strokes.Count, "other contents remain"); + c.Equal(1, page.History.Length, "missing media and stroke retain a single undo group"); + var first = (UInkMissingMedia)canvas.Children[0]; + var second = (UInkMissingMedia)canvas.Children[1]; + var dpi = VisualTreeHelper.GetDpi(canvas); + c.Near(512 / dpi.DpiScaleX, first.Width, "placeholder uses original frame"); + c.Near(0, InkCanvas.GetLeft(first), "placeholder uses matrix positioning"); + c.Near(100 / dpi.DpiScaleX, first.RenderTransform.Value.OffsetX, "placeholder preserves horizontal translation"); + c.Near(50 / dpi.DpiScaleY, first.RenderTransform.Value.OffsetY, "placeholder preserves vertical translation"); + c.That(ReferenceEquals(((UInkGroupHistory)page.History[0]).Elements[1], second), "second slot preserves order"); + window.ApplyHistoryToCanvas(history.Undo()); + c.Equal(0, canvas.Children.Count, "single undo removes both placeholders"); + c.Equal(0, canvas.Strokes.Count, "same undo removes the stroke"); + window.ApplyHistoryToCanvas(history.Redo()); + c.That(ReferenceEquals(first, canvas.Children[0]) && ReferenceEquals(second, canvas.Children[1]), "redo restores original order"); + c.Equal(1, canvas.Strokes.Count, "same redo restores the stroke"); + } + + private static void PlaybackStartIsClamped(UInkChecks c) + { + var duration = new Duration(TimeSpan.FromSeconds(3)); + c.Equal(TimeSpan.Zero, UInkPlayback.StartPosition(-2, duration), "negative start clamps to zero"); + c.Equal(TimeSpan.FromSeconds(1.25), UInkPlayback.StartPosition(1.25, duration), "in-range start"); + c.Equal(TimeSpan.FromSeconds(3), UInkPlayback.StartPosition(double.MaxValue, duration), "seek is bounded before conversion"); + } + + private static void ImportedPdfFlipKeepsWhiteboardHistory(UInkChecks c) + { + using var tmp = new TempDirectory(); + string pdfFile = Path.Combine(tmp.Root, "two-pages.pdf"); + WriteTwoPagePdf(pdfFile); + string entry = UInkExtraArchive.ContentHashPath(pdfFile, ".pdf"); + var first = Page(0); + var second = Page(1); + first.Canvas.Background = second.Canvas.Background = new UInkBackground { Color = new UInkColor { Fallback = 0xffffff } }; + first.Media.Add(new UInkMedia { Path = entry, MimeType = "application/pdf", Width = 90, Height = 55, + Fit = 0, Crop = new UInkCrop { X = 75, Width = 75, Height = 75 }, PageCount = 3 }); + first.MediaOwners.Add(0); + first.Strokes = new StrokeCollection { new Stroke(new StylusPointCollection { new StylusPoint(10, 20) }) }; + first.StrokeOwners.Add(0); + string path = Path.Combine(tmp.Root, "pdf-board.uink"); + UInkSaveService.SaveFull(UInkIccMapper.BuildDocument(UInkIccMapper.NewFileGuid(), null, + new[] { Whiteboard() }, new[] { first, second }, 0), path, new[] { (entry, pdfFile) }); + + var projection = Project(path); + using var cache = UInkMediaRestoreCache.Open(path, Path.Combine(tmp.Root, "cache")); + var machine = new TimeMachine(); + var canvas = new InkCanvas(); + var window = HeadlessWindow(canvas, machine); + var histories = ConfigureBoard(window, projection, cache); + var originalContext = SynchronizationContext.Current; + SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(canvas.Dispatcher)); + try + { + RestoreBoardPage(window); + var pdf = (PdfEmbeddedView)canvas.Children[0]; + PumpUiUntil(() => pdf.Content is UInkMissingMedia || + pdf.Content is Grid grid && grid.Children.Count == 1 && grid.Children[0] is Image { Source: BitmapSource }); + c.Equal((uint)2, pdf.PageCount, "actual WinRT page count takes precedence"); + c.That(pdf.Content is Grid && !pdf.EnableStrokesPersistence && pdf.ClearAllStrokes == null, + "imported PDF initializes without canvas ink persistence"); + var firstPageImage = (Image)((Grid)pdf.Content).Children[0]; + var firstRaster = (BitmapSource)firstPageImage.Source; + c.Equal(Stretch.Fill, firstPageImage.Stretch, "PDF fit maps onto the existing native image"); + c.Near(90, pdf.Width, "first page keeps the mapped DIP width"); + c.Near(55, pdf.Height, "first page keeps the mapped DIP height"); + AssertRaster(firstRaster, Colors.Red, Colors.Blue, "first page"); + c.Equal(1, projection.ReadResult.DiagnosticCounts.GetValueOrDefault("mediaCropIgnored"), "PDF crop fallback is diagnosed"); + c.That(projection.ReadResult.DiagnosticCounts.ContainsKey("MEDIA-9"), "wrong declared PDF page count is reported"); + c.Equal(1, machine.GetAppliedHistorySnapshot().Length, "PDF and stroke form one group"); + + WaitForUi(MainWindow.NavigateRestoredPdfAsync(pdf, previous: false)); + c.Equal((uint)1, pdf.CurrentPageIndex, "PDF actually flips to the second page"); + c.That(pdf.Content is Grid && pdf.CanGoPrevious, "bounded rendering updates the PDF navigation state"); + var secondPageImage = (Image)((Grid)pdf.Content).Children[0]; + c.That(ReferenceEquals(firstPageImage, secondPageImage) && !ReferenceEquals(firstRaster, secondPageImage.Source), + "page navigation updates the existing native image"); + c.Near(90, pdf.Width, "second page keeps the mapped DIP width"); + c.Near(55, pdf.Height, "second page keeps the mapped DIP height"); + AssertRaster((BitmapSource)secondPageImage.Source, Colors.Green, Colors.Yellow, "second page"); + c.Equal(1, canvas.Strokes.Count, "flipping the PDF preserves canvas ink"); + c.That(machine.CanUndo, "flipping the PDF preserves the undo cursor"); + window.ApplyHistoryToCanvas(machine.Undo()); + c.Equal(0, canvas.Strokes.Count, "one undo removes the ink"); + c.Equal(0, canvas.Children.Count, "same undo removes the PDF"); + window.ApplyHistoryToCanvas(machine.Redo()); + c.Equal(1, canvas.Strokes.Count, "redo restores the ink"); + c.That(canvas.Children.Count == 1 && ReferenceEquals(pdf, canvas.Children[0]), "redo restores the same PDF"); + + MoveBoardPage(window, 2); + c.Equal(0, canvas.Children.Count, "the next whiteboard page has no PDF"); + MoveBoardPage(window, 1); + c.That(canvas.Children.Count == 1 && ReferenceEquals(pdf, canvas.Children[0]), "board round-trip retains the PDF"); + c.Equal((uint)1, pdf.CurrentPageIndex, "board round-trip retains the PDF page"); + c.Equal(1, canvas.Strokes.Count, "board round-trip retains ink"); + c.That(machine.CanUndo && histories[1].Length == 1, "board round-trip retains the composite history"); + } + finally { SynchronizationContext.SetSynchronizationContext(originalContext); } + + void AssertRaster(BitmapSource source, Color left, Color right, string label) + { + int width = source.PixelWidth, height = source.PixelHeight; + c.That(width > 0 && height > 0 && width <= PdfWinRtHelper.UInkMaxSide && height <= PdfWinRtHelper.UInkMaxSide && + (long)width * height <= PdfWinRtHelper.UInkMaxPixels, label + " output pixel budget"); + c.Near(width / 2d, height, label + " raster aspect ratio", 1); + + // 取两侧色块内部的小样本。裁掉任一半,或翻页后仍显示上一页,都无法满足这两个断言。 + var pixels = source.Format == PixelFormats.Bgra32 ? source : + new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0); + CheckBand(width / 4, left, "left"); + CheckBand(width * 3 / 4, right, "right"); + + void CheckBand(int x, Color expected, string side) + { + var pixel = new byte[4]; + pixels.CopyPixels(new Int32Rect(x, height / 2, 1, 1), pixel, 4, 0); + c.Near(expected.R, pixel[2], label + " " + side + " red", 8); + c.Near(expected.G, pixel[1], label + " " + side + " green", 8); + c.Near(expected.B, pixel[0], label + " " + side + " blue", 8); + } + } + } + + private static void PdfRasterLimits(UInkChecks c) + { + c.Equal(new Size(612, 792), PdfWinRtHelper.UInkRenderSize(612, 792), "ordinary page raster dimensions"); + foreach (double scale in new[] { 1d, 1.5, 1.8, 2.0 }) + { + var wide = PdfWinRtHelper.UInkRenderSize(9000, 100, scale); + var square = PdfWinRtHelper.UInkRenderSize(4096, 4096, scale); + c.Near(Math.Floor(PdfWinRtHelper.UInkMaxSide / scale), wide.Width, $"DIP side at scale {scale}"); + c.Near(Math.Floor(Math.Sqrt(PdfWinRtHelper.UInkMaxPixels) / scale), square.Width, $"DIP area at scale {scale}"); + c.Equal(square.Width, square.Height, "square page retains its aspect"); + foreach (var size in new[] { wide, square }) + c.That(size.Width * scale <= PdfWinRtHelper.UInkMaxSide && + size.Height * scale <= PdfWinRtHelper.UInkMaxSide && + Math.Ceiling(size.Width * scale) * Math.Ceiling(size.Height * scale) <= PdfWinRtHelper.UInkMaxPixels, + $"expected output obeys side and pixel limits at {scale}"); + } + + var rounded = PdfWinRtHelper.UInkRenderSize(2718, 2830, 1.5); + c.That(Math.Ceiling(rounded.Width * 1.5) * Math.Ceiling(rounded.Height * 1.5) <= PdfWinRtHelper.UInkMaxPixels, + "per-axis output rounding cannot exceed the pixel area limit"); + + using var stream = new PdfWinRtHelper.UInkPdfOutputStream(8); + stream.Write(new byte[8], 0, 8); + Reject(() => stream.WriteByte(0)); + Reject(() => stream.SetLength(9)); + Reject(() => stream.Write(new byte[1].AsSpan())); + Reject(() => stream.WriteAsync(new byte[1], 0, 1).GetAwaiter().GetResult()); + c.Equal(8L, stream.Length, "writes beyond the PDF byte limit leave stream length unchanged"); + + void Reject(Action write) + { + try { write(); c.That(false, "oversized PDF output must fail"); } + catch (InvalidDataException) { } + } + } + + private static void NativeBitmapDpiRoundTripPixels(UInkChecks c) + { + using var tmp = new TempDirectory(); + var coordinates = new UInkCoordinateMap(1.5, 1.5); + var sz = new Size(220, 120); + foreach (var stretch in new[] { Stretch.Fill, Stretch.Uniform, Stretch.UniformToFill, Stretch.None }) + foreach (var (dpiX, dpiY) in new[] { (96d, 96d), (120d, 120d), (96d, 192d) }) + Verify(stretch, dpiX, dpiY, 100, 50, 80, stretch == Stretch.UniformToFill ? 50 : 40); + Verify(Stretch.None, 96, 96, 100, 40, 140, 64); + + void Verify(Stretch stretch, double dpiX, double dpiY, int pixelsX, int pixelsY, double width, double height) + { + var pixels = new byte[pixelsX * pixelsY * 4]; + for (int y = 0; y < pixelsY; y++) + for (int x = 0; x < pixelsX; x++) + { + int offset = (y * pixelsX + x) * 4; + pixels[offset + (y < pixelsY / 2 ? 2 : 0)] = 255; + pixels[offset + 1] = (byte)(x >= pixelsX / 4 && x < pixelsX * 3 / 4 ? 255 : 0); + pixels[offset + 3] = 255; + } + var image = new Image { Width = width, Height = height, Stretch = stretch, + Source = BitmapSource.Create(pixelsX, pixelsY, dpiX, dpiY, PixelFormats.Bgra32, null, pixels, pixelsX * 4) }; + InkCanvas.SetLeft(image, 20); + InkCanvas.SetTop(image, 16); + var live = new InkCanvas { Background = Brushes.Transparent }; + VisualTreeHelper.SetRootDpi(live, new DpiScale(1.5, 1.5)); + live.Children.Add(image); + byte[] before = Render(live); + int ColoredOnRow(byte[] bytes, int y) => Enumerable.Range(0, 330).Count(x => + { + int i = (y * 330 + x) * 4; + return bytes[i + 3] == 255 && (bytes[i] != 0 || bytes[i + 2] != 0); + }); + int footprint = Enumerable.Range(0, 180).Max(y => ColoredOnRow(before, y)); + c.That(footprint > 0 && footprint < 330, "transparent canvas measures only the colored bitmap"); + if (stretch == Stretch.None && width == 140) + c.Equal(150, footprint, "100 px at 96 DPI renders 150 screen pixels"); + + var input = Page(0); + MainWindow.CaptureUInkPage(input, null, live.Strokes, live.Children.Cast()); + var context = new UInkCaptureContext { Workspace = Whiteboard(), DpiX = 1.5, DpiY = 1.5 }; + context.Pages.Add(input); + string path = Path.Combine(tmp.Root, FormattableString.Invariant($"{stretch}-{dpiX}-{dpiY}-{width}.uink")); + Task.Run(() => context.Save(path, false)).GetAwaiter().GetResult(); + var restored = new InkCanvas { Background = Brushes.Transparent }; + VisualTreeHelper.SetRootDpi(restored, new DpiScale(1.5, 1.5)); + using var cache = UInkMediaRestoreCache.Open(path, Path.Combine(tmp.Root, "cache")); + var page = Project(path).Pages.Single(); + page.EnsureMaterialized(); + Task.Run(() => MainWindow.PrepareUInkMediaFiles(page, cache)).GetAwaiter().GetResult(); + WaitForUi(HeadlessWindow(restored, new TimeMachine()).InstallUInkPage(page, cache, coordinates)); + var media = page.Media.Single(); + var picture = (Image)restored.Children[0]; + c.That(media.Crop == null, "native image clipping is already reflected in the saved resource"); + c.Equal(UInkMediaMapper.StretchFromFit(media.Fit), picture.Stretch, "import uses the recorded native Stretch"); + c.That(!page.ReadResult.RequiresSaveAs, "ICC bitmap can be reopened without a compatibility fallback"); + c.That(picture.Source is BitmapSource, "saved bitmap installs without fallback"); + // ICC 不创建 None/Cover;这两种布局验证公共可见框及可打开,Fill/Uniform 仍要求逐像素相同。 + if (stretch is Stretch.None or Stretch.UniformToFill) + { + double naturalWidth = pixelsX * 96 / dpiX, naturalHeight = pixelsY * 96 / dpiY; + double visibleWidth = stretch == Stretch.None ? Math.Min(width, naturalWidth) : width; + double visibleHeight = stretch == Stretch.None ? Math.Min(height, naturalHeight) : height; + double left = (20 + (width - visibleWidth) / 2) * 1.5; + double top = (16 + (height - visibleHeight) / 2) * 1.5; + c.Equal(0, media.Fit, "public fit describes the visible bitmap"); + c.Near(left, media.Transform[4], "public left in Device pixels", 0.5); + c.Near(top, media.Transform[5], "public top in Device pixels", 0.5); + c.Near(left + visibleWidth * 1.5, media.Transform[4] + media.Width, "public right in Device pixels", 0.5); + c.Near(top + visibleHeight * 1.5, media.Transform[5] + media.Height, "public bottom in Device pixels", 0.5); + return; + } + if (stretch == Stretch.Uniform && dpiX != dpiY) + { + c.Equal(0, media.Fit, "non-square bitmap DPI stores the actual native DIP aspect"); + c.Near(120, media.Width, "non-square Uniform width on disk"); + c.Near(30, media.Height, "non-square Uniform height on disk"); + } + c.That(before.SequenceEqual(Render(restored)), + FormattableString.Invariant($"{stretch} at {dpiX}×{dpiY} bitmap DPI preserves the raster at 150% display DPI")); + + } + + byte[] Render(InkCanvas canvas) + { + canvas.Measure(sz); + canvas.Arrange(new Rect(sz)); + var target = new RenderTargetBitmap(330, 180, 144, 144, PixelFormats.Pbgra32); + target.Render(canvas); + return Pixels(target); + } + } + + private static void ImportedVideoKeepsNativeLayout(UInkChecks c) + { + using var tmp = new TempDirectory(); + string video = Path.Combine(tmp.Root, "clip.wmv"); + // 仅验证资源准备和原生控件布局;没有挂载媒体,也无需系统解码器。 + File.WriteAllBytes(video, Convert.FromHexString("3026B2758E66CF11A6D900AA0062CE6C")); + string entry = UInkExtraArchive.ContentHashPath(video, ".wmv"); + var input = Page(0); + input.Media.Add(new UInkMedia { MimeType = "video/x-ms-wmv", Path = entry, Width = 220, Height = 160, + Fit = 2, Crop = new UInkCrop { X = 1, Y = 1, Width = 20, Height = 20 } }); + string file = Path.Combine(tmp.Root, "video.uink"); + UInkSaveService.SaveFull(UInkIccMapper.BuildDocument(UInkIccMapper.NewFileGuid(), null, + new[] { Whiteboard() }, new[] { input }, 0), file, new[] { (entry, video) }); + var page = Project(file).Pages.Single(); + using var cache = UInkMediaRestoreCache.Open(file, Path.Combine(tmp.Root, "cache")); + var canvas = new InkCanvas(); + var window = HeadlessWindow(canvas, new TimeMachine()); + WaitForUi(window.InstallUInkPage(page, cache, UInkCoordinateMap.Identity)); + var control = (CanvasMediaControl)canvas.Children[0]; + try + { + var box = new Size(220, 160); + control.Measure(box); + control.Arrange(new Rect(box)); + c.That(((Grid)control.FindName("PreviewHost")).ActualHeight < box.Height, "native control retains its own control row"); + c.Equal(Stretch.Uniform, control.MediaPlayer.Stretch, "video uses the native preview stretch"); + c.That(control.MediaPlayer.Clip == null, "video crop leaves the complete native preview"); + c.Equal(1, page.ReadResult.DiagnosticCounts.GetValueOrDefault("mediaVideoFitIgnored"), "foreign video fit is diagnosed"); + c.Equal(1, page.ReadResult.DiagnosticCounts.GetValueOrDefault("mediaCropIgnored"), "foreign video crop is diagnosed"); + c.That(page.ReadResult.RequiresSaveAs, "video layout fallback requires Save As"); + } + finally + { + control.Shutdown(); + canvas.Children.Clear(); + } + } + + private static void NativeVideoUsesPublicPreviewBox(UInkChecks c) + { + using var tmp = new TempDirectory(); + string video = Path.Combine(tmp.Root, "native.wmv"); + File.WriteAllBytes(video, Convert.FromHexString("3026B2758E66CF11A6D900AA0062CE6C")); + var control = new CanvasMediaControl { Width = 300, Height = 220, RenderTransformOrigin = new Point(0.5, 0.5), + RenderTransform = new MatrixTransform(1.1, 0.2, -0.15, 0.9, 8, 9) }; + control.Initialize(video); + InkCanvas.SetLeft(control, 23); + InkCanvas.SetTop(control, 31); + var canvas = new InkCanvas { Width = 500, Height = 400 }; + canvas.Children.Add(control); + try + { + canvas.Measure(new Size(500, 400)); + canvas.Arrange(new Rect(0, 0, 500, 400)); + var preview = (Grid)control.FindName("PreviewHost"); + c.That(preview.ActualHeight > 0 && preview.ActualHeight < control.Height, "native video has a separate preview"); + var previewMap = preview.TransformToAncestor(canvas); + var outerMap = control.TransformToAncestor(canvas); + var coordinates = new UInkCoordinateMap(1.5, 2); + string path = SaveCanvas(tmp.Root, "native-video", canvas, 1.5, 2); + var media = UInkReader.Read(path).Document.Canvases.Single().Blocks.OfType().Single(); + c.Equal(1, media.Fit, "video public fit is Contain"); + c.Near(preview.ActualWidth * 1.5, media.Width, "public preview width in Device pixels"); + c.Near(preview.ActualHeight * 2, media.Height, "public preview height in Device pixels"); + var matrix = coordinates.MapMediaMatrix(media.Transform); + var points = new[] { new Point(), new Point(100, 0), new Point(0, 100) }; + foreach (var point in points) + PointNear(c, previewMap.Transform(point), matrix.Transform(point), "public preview placement"); + c.That(media.Extra?.ContainsKey("icc:mediaControl/v1") == true, "outer control box is in the versioned extra"); + + using var cache = UInkMediaRestoreCache.Open(path, Path.Combine(tmp.Root, "cache")); + var restored = new InkCanvas(); + var page = Project(path).Pages.Single(); + WaitForUi(HeadlessWindow(restored, new TimeMachine()).InstallUInkPage(page, cache, coordinates)); + var reopened = (CanvasMediaControl)restored.Children[0]; + try + { + c.Near(300, reopened.Width, "outer width on reopen"); + c.Near(220, reopened.Height, "outer height on reopen"); + foreach (var point in points) + PointNear(c, outerMap.Transform(point), reopened.RenderTransform.Value.Transform(point), "reopened outer placement"); + c.That(!page.ReadResult.RequiresSaveAs, "ICC native video has no layout fallback"); + } + finally { reopened.Shutdown(); restored.Children.Clear(); } + } + finally { control.Shutdown(); canvas.Children.Clear(); } + } + + private static void ForeignMediaFitRequiresSaveAs(UInkChecks c) + { + using var tmp = new TempDirectory(); + string png = Path.Combine(tmp.Root, "foreign.png"); + using (var stream = File.Create(png)) UInkMediaMapper.EncodePng(Bitmap(), stream); + string pdf = Path.Combine(tmp.Root, "foreign.pdf"); + WriteTwoPagePdf(pdf); + string video = Path.Combine(tmp.Root, "foreign.wmv"); + File.WriteAllBytes(video, Convert.FromHexString("3026B2758E66CF11A6D900AA0062CE6C")); + + Verify(png, "image/png", 0, null); + Verify(png, "image/png", 1, null); + Verify(png, "image/png", 2, "mediaVisualFitApproximation"); + Verify(png, "image/png", 3, "mediaVisualFitApproximation"); + Verify(pdf, "application/pdf", 2, "mediaVisualFitApproximation"); + Verify(pdf, "application/pdf", 3, "mediaVisualFitApproximation"); + Verify(video, "video/x-ms-wmv", null, "mediaVideoFitIgnored"); + Verify(video, "video/x-ms-wmv", 1, "mediaVideoFitIgnored"); + + void Verify(string source, string mime, int? fit, string expected) + { + string entry = UInkExtraArchive.ContentHashPath(source, Path.GetExtension(source)); + var input = Page(0); + input.Media.Add(new UInkMedia { MimeType = mime, Path = entry, Width = 220, Height = 160, Fit = fit }); + string file = Path.Combine(tmp.Root, Path.GetFileName(source) + "-" + fit + ".uink"); + UInkSaveService.SaveFull(UInkIccMapper.BuildDocument(UInkIccMapper.NewFileGuid(), null, + new[] { Whiteboard() }, new[] { input }, 0), file, new[] { (entry, source) }); + var page = Project(file).Pages.Single(); + page.EnsureMaterialized(); + using var cache = UInkMediaRestoreCache.Open(file, Path.Combine(tmp.Root, "cache")); + MainWindow.PrepareUInkMediaFiles(page, cache); + string label = mime + " fit=" + fit; + c.That(File.Exists(page.MediaFiles.Single()), label + " resource remains usable"); + c.Equal(expected != null, page.ReadResult.RequiresSaveAs, label + " Save As"); + if (expected != null) + c.Equal(1, page.ReadResult.DiagnosticCounts.GetValueOrDefault(expected), label + " layout diagnostic"); + var notice = typeof(MainWindow).GetMethod("TakeUInkMediaNotice", BindingFlags.Static | BindingFlags.NonPublic); + c.Equal(expected != null, notice.Invoke(null, new object[] { page.ReadResult, cache }) is string, label + " aggregate notice"); + } + } + + private static void RestoredBitmapIsCollectedForLegacySidecar(UInkChecks c) + { + using var tmp = new TempDirectory(); + var image = new Image { Width = 35, Height = 22, Stretch = Stretch.Fill, Source = Bitmap() }; + InkCanvas.SetLeft(image, 27); + InkCanvas.SetTop(image, 44); + var canvas = new InkCanvas(); + canvas.Children.Add(image); + string path = SaveCanvas(tmp.Root, "legacy-source", canvas); + + using var cache = UInkMediaRestoreCache.Open(path, Path.Combine(tmp.Root, "cache")); + var restored = new InkCanvas(); + var window = HeadlessWindow(restored, new TimeMachine()); + WaitForUi(window.InstallUInkPage(Project(path).Pages.Single(), cache, UInkCoordinateMap.Identity)); + var entries = new List(); + typeof(MainWindow).GetMethod("CollectCanvasElementsMetadata", Fields).Invoke(window, new object[] { entries }); + c.Equal(1, entries.Count, "legacy collector includes one restored image"); + var entry = entries.Single(); + c.Equal("Image", entry.Type, "legacy element type"); + c.That(File.Exists(entry.SourcePath), "legacy source path points at the persistent restore cache"); + c.That(Pixels(Bitmap()).SequenceEqual(Pixels(UInkMediaMapper.DecodeBitmap(entry.SourcePath))), "legacy source contains the restored image"); + c.Near(27, entry.Left, "legacy left"); + c.Near(44, entry.Top, "legacy top"); + c.Near(35, entry.Width, "legacy width"); + c.Near(22, entry.Height, "legacy height"); + c.Equal("Fill", entry.Stretch, "legacy stretch"); + } + + private static void ReplacedValidPngKeepsDisplayedPixels(UInkChecks c) + { + using var tmp = new TempDirectory(); + string source = Path.Combine(tmp.Root, "mutable.png"); + using (var stream = File.Create(source)) UInkMediaMapper.EncodePng(Bitmap(), stream); + var canvas = new InkCanvas(); + var image = new Image { Width = 25, Height = 30, Stretch = Stretch.Fill, Source = FileBitmap(source) }; + canvas.Children.Add(image); + byte[] expected = Pixels((BitmapSource)image.Source); + string original = SaveCanvas(tmp.Root, "before-replacement", canvas); + + ReplacePng(source); + VerifySavedPixels(SaveCanvas(tmp.Root, "replaced-original", canvas), "ordinary file bitmap"); + + using var cache = UInkMediaRestoreCache.Open(original, Path.Combine(tmp.Root, "restored-cache")); + var restored = new InkCanvas(); + var page = Project(original).Pages.Single(); + WaitForUi(HeadlessWindow(restored, new TimeMachine()).InstallUInkPage(page, cache, UInkCoordinateMap.Identity)); + var mapped = (UInkBitmapImage)restored.Children[0]; + ReplacePng(mapped.SourcePath); + VerifySavedPixels(SaveCanvas(tmp.Root, "replaced-cache", restored), "UInk restored bitmap"); + + void ReplacePng(string path) + { + var changed = BitmapSource.Create(2, 3, 96, 96, PixelFormats.Bgra32, null, new byte[24], 8); + var lastWrite = File.GetLastWriteTimeUtc(path); + using (var stream = File.Create(path)) UInkMediaMapper.EncodePng(changed, stream); + File.SetLastWriteTimeUtc(path, lastWrite.AddSeconds(5)); + c.That(!expected.SequenceEqual(Pixels(UInkMediaMapper.DecodeBitmap(path))), "replacement is a valid different PNG"); + } + + void VerifySavedPixels(string path, string label) + { + var media = UInkReader.Read(path).Document.Canvases.Single().Blocks.OfType().Single(); + using var savedCache = UInkMediaRestoreCache.Open(path, Path.Combine(tmp.Root, "verify-cache")); + var bitmap = savedCache.GetBitmap(savedCache.GetVerifiedPath(media.Path, media.MimeType)); + c.That(expected.SequenceEqual(Pixels(bitmap)), label + " saves the originally displayed pixels"); + } + } + + private static string SaveCanvas(string directory, string name, InkCanvas canvas, double dpiX = 1, double dpiY = 1) + { + var input = Page(0); + MainWindow.CaptureUInkPage(input, null, canvas.Strokes, canvas.Children.Cast()); + var context = new UInkCaptureContext { Workspace = Whiteboard(), DpiX = dpiX, DpiY = dpiY }; + context.Pages.Add(input); + return Task.Run(() => context.Save(Path.Combine(directory, name + ".uink"), false)).GetAwaiter().GetResult(); + } + + private static void SaveAsReportsDroppedMediaAndReencodesBitmap(UInkChecks c) + { + using var tmp = new TempDirectory(); + string original = Path.Combine(tmp.Root, "source.uink"); + using (var bytes = new MemoryStream()) + { + var encoder = new UInkTestEncoder(bytes); + encoder.Header(11, 2); + encoder.HeaderExtension(); + encoder.Canvas(0, whiteboard: true); + encoder.Media(0, 0, "visited/missing.png"); + encoder.Media(1, 0, "icons/unsupported.svg", "image/svg+xml"); + encoder.Canvas(1, whiteboard: true); + encoder.Media(0, 0, "unvisited/missing.png"); + encoder.Media(1, 0, "icons/unsupported.svg", "image/svg+xml"); + File.WriteAllBytes(original, bytes.ToArray()); + } + string svg = Path.Combine(tmp.Root, "safe.svg"); + File.WriteAllText(svg, ""); + UInkExtraArchive.WriteArchive(original + ".extra", new[] { ("icons/unsupported.svg", svg) }); + string imagePath = Path.Combine(tmp.Root, "was.png"); + using (var stream = File.Create(imagePath)) UInkMediaMapper.EncodePng(Bitmap(), stream); + var fileBitmap = new BitmapImage(); + fileBitmap.BeginInit(); + fileBitmap.UriSource = new Uri(imagePath); + fileBitmap.CacheOption = BitmapCacheOption.OnLoad; + fileBitmap.SourceRect = new Int32Rect(0, 1, 2, 2); + fileBitmap.EndInit(); + byte[] expected = Pixels(fileBitmap); + var sourceBitmap = FileBitmap(imagePath); + byte[] expectedFull = Pixels(sourceBitmap); + File.WriteAllText(imagePath, "These bytes are no longer PNG."); + + var board = Project(original); + var canvas = new InkCanvas(); + var snapshot = new UInkCaptureContext { Workspace = Whiteboard(), DpiX = 1, DpiY = 1 }; + using var resources = UInkMediaRestoreCache.Open(original, Path.Combine(tmp.Root, "cache")); + snapshot.Resources = resources; + Task.Run(() => MainWindow.PrepareUInkMediaFiles(board.Pages[0], resources)).GetAwaiter().GetResult(); + WaitForUi(HeadlessWindow(canvas, new TimeMachine()).InstallUInkPage(board.Pages[0], resources)); + c.That(canvas.Children[1] is UInkMissingMedia, "a safe SVG still uses the missing-resource placeholder"); + canvas.Children.Add(new Image { Source = fileBitmap, Width = 20, Height = 20, Stretch = Stretch.Fill }); + canvas.Children.Add(new Image { Source = sourceBitmap, Width = 20, Height = 20, Stretch = Stretch.Fill }); + string wrongVideo = Path.Combine(tmp.Root, "wrong.flv"); + File.WriteAllText(wrongVideo, "Not Flash video."); + canvas.Children.Add(new MediaElement { Source = new Uri(wrongVideo), Width = 40, Height = 30 }); + var visited = Page(0); + MainWindow.CaptureUInkPage(visited, null, canvas.Strokes, canvas.Children.Cast()); + var unvisited = Page(1); + snapshot.CapturePendingPage(unvisited, board.Pages[1], new UInkCoordinateMap(1, 1)); + snapshot.Pages.Add(visited); + snapshot.Pages.Add(unvisited); + + string copy = Task.Run(() => snapshot.Save(original, false, UInkSaveService.NormalizeTarget(original))).GetAwaiter().GetResult(); + c.That(copy != original, "imported source is preserved by Save As"); + c.Equal(5, snapshot.DroppedMediaCount, "missing files, unsupported SVGs and invalid video are counted"); + var saved = UInkReader.Read(copy).Document.Canvases.SelectMany(page => page.Blocks).OfType().ToArray(); + c.Equal(2, saved.Length, "only the recovered bitmaps are referenced"); + using var restored = UInkMediaRestoreCache.Open(copy, Path.Combine(tmp.Root, "copy-cache")); + for (int i = 0; i < saved.Length; i++) + { + var image = saved[i]; + c.That(image.MimeType == "image/png" && image.Crop == null, "PNG contains the actual bitmap without a separate crop"); + var bitmap = restored.GetBitmap(restored.GetVerifiedPath(image.Path, image.MimeType)); + c.That((i == 0 ? expected : expectedFull).SequenceEqual(Pixels(bitmap)), "PNG archives the frozen display pixels"); + } + using var savedPack = ZipFile.OpenRead(copy + ".extra"); + c.That(savedPack.Entries.All(entry => entry.FullName.EndsWith(".png", StringComparison.Ordinal)), "Save As archives no SVG"); + } + + private static void VideoMimeSignaturesAndSuffixes(UInkChecks c) + { + Verify(".wmv", "video/x-ms-wmv", Convert.FromHexString("3026B2758E66CF11A6D900AA0062CE6C")); + Verify(".flv", "video/x-flv", new byte[] { 0x46, 0x4c, 0x56, 1, 5, 0, 0, 0, 9 }); + c.Equal("application/octet-stream", UInkExtraArchive.MimeForPath("movie.mkw"), "mkw is not registered"); + + void Verify(string ext, string mime, byte[] header) + { + c.Equal(mime, UInkExtraArchive.MimeForPath("movie" + ext), "writer MIME"); + c.Equal(ext, UInkMediaRestoreCache.CanonicalExtension(mime), "cache extension"); + c.That(UInkExtraArchive.IsMimeConsistent(mime, header), "valid container signature"); + header[0] = 0; + c.That(!UInkExtraArchive.IsMimeConsistent(mime, header), "wrong container signature rejected"); + } + } + + private static void DeferredMediaUsesOriginalSlotAndRejectsStaleResults(UInkChecks c) + { + using var tmp = new TempDirectory(); + string path = SaveDeferredBoard(tmp.Root); + + foreach (int invalidate in new[] { 0, 1, 2, 3 }) + { + using var cache = UInkMediaRestoreCache.Open(path, Path.Combine(tmp.Root, "cache-" + invalidate)); + var projection = Project(path); + var page = projection.Pages[1]; + var canvas = new InkCanvas(); + var machine = new TimeMachine(); + var window = HeadlessWindow(canvas, machine); + var histories = ConfigureBoard(window, projection, cache); + window.CurrentWhiteboardIndex = 2; + // 占用提取锁,确保返回的占位和历史在任何后台资源完成前即可检查。 + object gate = typeof(UInkMediaRestoreCache).GetField("extracted", Fields).GetValue(cache); + using var locked = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var holding = Task.Run(() => + { + lock (gate) + { + locked.Set(); + release.Wait(TimeSpan.FromSeconds(10)); + } + }); + if (!locked.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException("Test resource lock did not become available."); + Image image; + Task preparing; + try + { + preparing = window.InstallUInkPage(page, cache, new UInkCoordinateMap(1, 1)); + image = (Image)canvas.Children[0]; + c.That(!preparing.IsCompleted && image.Source == null, "first visit installs a placeholder without waiting for extraction"); + c.Near(40, image.Width, "first-visit placeholder width"); + c.Near(10, image.RenderTransform.Value.OffsetX, "first-visit placeholder transform"); + c.That(ReferenceEquals(image, ((UInkGroupHistory)page.History[0]).Elements[0]), "placeholder occupies the history slot"); + if (invalidate == 3) + { + string invalid = Path.Combine(tmp.Root, "invalid.uink"); + File.WriteAllBytes(invalid, new byte[] { 0xff }); + var opening = window.OpenUInkFileAsync(invalid); + WaitForUi(opening); + c.Equal(Ink_Canvas.Properties.MainWindowStrings.Main_Strokes_UInkInvalid, opening.Result, + "invalid UInk open finishes before releasing the original media"); + } + if (invalidate == 1) SetWindowField(window, "_uinkOpenGeneration", 1); + if (invalidate == 2) histories[2] = Array.Empty(); + window.ApplyHistoryToCanvas(machine.Undo()); + c.Equal(0, canvas.Children.Count, "pending placeholder can be undone"); + } + finally { release.Set(); holding.GetAwaiter().GetResult(); } + WaitForUi(preparing); + c.Equal(0, canvas.Children.Count, "completion does not reinsert an undone element"); + c.That(invalidate is 0 or 3 ? image.Source is BitmapSource { IsFrozen: true } : image.Source == null, + "only the surviving open generation and slot receive the frozen bitmap"); + window.ApplyHistoryToCanvas(machine.Redo()); + c.That(ReferenceEquals(image, canvas.Children[0]), "redo uses the original element"); + } + } + + private static string SaveDeferredBoard(string directory) + { + string source = Path.Combine(directory, "picture.png"); + using (var stream = File.Create(source)) UInkMediaMapper.EncodePng(Bitmap(), stream); + string key = UInkExtraArchive.ContentHashPath(source, ".png"); + var p0 = Page(0); + var p1 = Page(1); + p1.Media.Add(new UInkMedia { MimeType = "image/png", Path = key, Width = 40, Height = 30, + Transform = new[] { 1f, 0f, 0f, 1f, 10f, 20f } }); + string path = Path.Combine(directory, "deferred.uink"); + UInkSaveService.SaveFull(UInkIccMapper.BuildDocument(UInkIccMapper.NewFileGuid(), null, + new[] { Whiteboard() }, new[] { p0, p1 }, 0), path, new[] { (key, source) }); + return path; + } + + private static void OverlappingOpensKeepOrReplaceRestoringDocument(UInkChecks c) + { + using var tmp = new TempDirectory(); + string original = SaveDeferredBoard(tmp.Root); + string invalid = Path.Combine(tmp.Root, "invalid.uink"); + File.WriteAllBytes(invalid, new byte[] { 0xff }); + string valid = Path.Combine(tmp.Root, "replacement.uink"); + UInkSaveService.SaveFull(UInkIccMapper.BuildDocument(UInkIccMapper.NewFileGuid(), null, + new[] { Whiteboard() }, new[] { Page(0) }, 0), valid, null); + + var canvas = new InkCanvas(); + var window = HeadlessWindow(canvas, new TimeMachine()); + ConfigureBoard(window, null, null); + var sessions = new MainWindow.UInkSession[3]; + SetWindowField(window, "_uinkSessions", sessions); + SetWindowField(window, "_boardToolbarViews", new Dictionary()); + SetWindowField(window, "TextBlockWhiteBoardIndexInfo", new TextBlock()); + foreach (string name in new[] { "BtnWhiteBoardSwitchNext", "BtnWhiteBoardSwitchPrevious", "BtnWhiteBoardDelete" }) + SetWindowField(window, name, new Button()); + + var appResources = Application.Current.Resources; + var oldBrush = appResources["IconForeground"]; + var oldSettings = MainWindow.Settings; + var oldContext = SynchronizationContext.Current; + var cacheField = typeof(MainWindow).GetField("_boardResources", Fields); + try + { + appResources["IconForeground"] = Brushes.Black; + MainWindow.Settings = new Settings(); + MainWindow.Settings.Automation.AutoSavedStrokesLocation = tmp.Root; + SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(canvas.Dispatcher)); + foreach (bool replace in new[] { false, true }) + { + var first = window.OpenUInkFileAsync(original); + WaitForUi(first); + var session = sessions[(int)UInkWorkspaceType.Whiteboard]; + c.That(session?.Projection.Pages.Count == 2, "opened the original two-page document"); + var cache = (UInkMediaRestoreCache)cacheField.GetValue(window); + var generationField = typeof(MainWindow).GetField("_uinkOpenGeneration", Fields); + int installedGeneration = (int)generationField.GetValue(window); + var page = session.Projection.Pages[1]; + window.CurrentWhiteboardIndex = 2; + Image image; + Task restoring; + Task superseded = null; + // 固定离页资源准备与较早的打开请求,分别控制媒体回调和两个请求的完成顺序。 + lock (typeof(UInkMediaRestoreCache).GetField("extracted", Fields).GetValue(cache)) + { + restoring = window.InstallUInkPage(page, cache); + image = (Image)canvas.Children[0]; + c.That(!restoring.IsCompleted && image.Source == null, "original image is loading"); + UInkSaveService.WithTargetLock(original, () => + { + superseded = window.OpenUInkFileAsync(original); + var latest = window.OpenUInkFileAsync(replace ? valid : invalid); + WaitForUi(latest); + c.That(!superseded.IsCompleted, "older open still waits for its pair"); + if (replace) + c.That(sessions[(int)UInkWorkspaceType.Whiteboard] != session && window.WhiteboardTotalCount == 1, + "valid winner installed the replacement"); + else + c.Equal(Ink_Canvas.Properties.MainWindowStrings.Main_Strokes_UInkInvalid, latest.Result, + "invalid winner reported rejection"); + return true; + }); + } + WaitForUi(Task.WhenAll(restoring, superseded)); + c.Equal(null, superseded.Result, "late valid request cannot install"); + c.Equal(replace, installedGeneration != (int)generationField.GetValue(window), + "only an installed replacement invalidates original callbacks"); + if (replace) + c.That(image.Source == null && canvas.Children.Count == 0 && window.WhiteboardTotalCount == 1, + "late callbacks and older opens leave the replacement untouched"); + else + c.That(sessions[(int)UInkWorkspaceType.Whiteboard] == session && canvas.Children.Contains(image) && + image.Source is BitmapSource bitmap && Pixels(bitmap).SequenceEqual(Pixels(Bitmap())), + "failed open keeps the original document and installs its decoded pixels"); + } + } + finally + { + SynchronizationContext.SetSynchronizationContext(oldContext); + MainWindow.Settings = oldSettings; + if (oldBrush == null) appResources.Remove("IconForeground"); + else appResources["IconForeground"] = oldBrush; + ((UInkMediaRestoreCache)cacheField.GetValue(window))?.Dispose(); + // 生产租约随进程退出;这里释放仅属于本用例临时目录的那一个。 + var leases = (Dictionary)typeof(MainWindow) + .GetField("UInkMediaCacheLeases", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); + lock (leases) + if (leases.Remove(Path.Combine(tmp.Root, UInkMediaRestoreCache.CacheDirectoryName), out var lease)) + lease.Dispose(); + } + } + + private static void LayoutTransformCaptureUsesActualAffineMap(UInkChecks c) + { + var canvas = new InkCanvas(); + var image = new Image { Width = 42, Height = 30, Stretch = Stretch.Fill, Source = Bitmap(), + LayoutTransform = new RotateTransform(90), RenderTransform = new TranslateTransform(4, 9) }; + InkCanvas.SetLeft(image, 11); + InkCanvas.SetTop(image, 17); + canvas.Children.Add(image); + canvas.Measure(new Size(200, 180)); + canvas.Arrange(new Rect(0, 0, 200, 180)); + var page = Page(0); + MainWindow.CaptureUInkPage(page, null, canvas.Strokes, canvas.Children.Cast()); + var coordinates = new UInkCoordinateMap(1.5, 1.5); + var captured = page.Elements.Single(); + var mapped = coordinates.MapMediaMatrix(UInkMediaMapper.Capture(captured, coordinates, "image/png").Transform); + var expected = image.TransformToAncestor(canvas); + foreach (var point in new[] { new Point(), new Point(42, 0), new Point(0, 30) }) + PointNear(c, expected.Transform(point), mapped.Transform(point), "layout-aware affine map"); + c.That(!captured.LayoutDegraded, "arranged canvas element has a measured mapping"); + canvas.Children.Clear(); + var offscreen = Page(1); + MainWindow.CaptureUInkPage(offscreen, null, canvas.Strokes, new[] { image }); + c.That(offscreen.Elements.Single().LayoutDegraded, "detached element signals layout degradation"); + } + + private static UInkWorkspace Whiteboard() => new() + { + Guid = UInkTestEncoder.WorkspaceGuid, WorkspaceType = (int)UInkWorkspaceType.Whiteboard, CurrentPageIndex = 0 + }; + + private static UInkPageProjection Project(string path) => + UInkIccMapper.BuildPageIndex(UInkReader.Read(path, new UInkReadOptions { MaterializeContent = false }), 1, 1); + + private static TimeMachineHistory[][] ConfigureBoard(MainWindow window, UInkPageProjection projection, UInkMediaRestoreCache cache) + { + var histories = new TimeMachineHistory[101][]; + SetWindowField(window, "TimeMachineHistories", histories); + var board = typeof(MainWindow).GetField("_uinkBoard", Fields); + board.SetValue(window, Array.CreateInstance(board.FieldType.GetElementType(), histories.Length)); + SetWindowField(window, "_uinkWorkspaceIds", new string[3]); + SetWindowField(window, "_currentMode", 1); + SetWindowField(window, "_currentWhiteboardIndex", 1); + SetWindowField(window, "_whiteboardTotalCount", projection?.Pages.Count ?? 1); + SetWindowField(window, "savedMultiTouchModeStates", new bool[101]); + SetWindowField(window, "frozenPages", new bool[101]); + SetWindowField(window, "GridBackgroundCover", new Grid()); + SetWindowField(window, "_boardResources", cache); + if (projection != null) window.IndexUInkWhiteboard(projection, projection.Pages.Count, new DpiScale(1, 1)); + return histories; + } + + private static void SetWindowField(MainWindow window, string name, object value) => + typeof(MainWindow).GetField(name, Fields).SetValue(window, value); + + private static void RestoreBoardPage(MainWindow window) => + typeof(MainWindow).GetMethod("RestoreStrokes", Fields).Invoke(window, new object[] { false, true }); + + private static void MoveBoardPage(MainWindow window, int index) + { + typeof(MainWindow).GetMethod("SaveStrokes", Fields).Invoke(window, new object[] { false }); + window.CurrentWhiteboardIndex = index; + RestoreBoardPage(window); + } + + private static void WaitForUi(Task task) + { + PumpUiUntil(() => task.IsCompleted); + task.GetAwaiter().GetResult(); + } + + private static void PumpUiUntil(Func complete) + { + if (complete()) return; + var watch = Stopwatch.StartNew(); + var frame = new DispatcherFrame(); + var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(10) }; + timer.Tick += (_, _) => + { + if (complete() || watch.Elapsed > TimeSpan.FromSeconds(30)) frame.Continue = false; + }; + timer.Start(); + try { Dispatcher.PushFrame(frame); } + finally { timer.Stop(); } + if (!complete()) throw new TimeoutException("Timed out waiting for UInk media on the test dispatcher."); + } + + private static void WriteTwoPagePdf(string path) + { + const string first = "1 0 0 rg\n0 0 75 75 re f\n0 0 1 rg\n75 0 75 75 re f\n"; + const string second = "0 .5 0 rg\n0 0 1800 1800 re f\n1 1 0 rg\n1800 0 1800 1800 re f\n"; + string[] objects = + { + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 150 75] /Resources << >> /Contents 5 0 R >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 3600 1800] /Resources << >> /Contents 6 0 R >>", + $"<< /Length {first.Length} >>\nstream\n{first}endstream", + $"<< /Length {second.Length} >>\nstream\n{second}endstream" + }; + var source = new StringBuilder("%PDF-1.4\n"); + var offsets = new int[objects.Length]; + for (int i = 0; i < objects.Length; i++) + { + offsets[i] = source.Length; + source.Append($"{i + 1} 0 obj\n{objects[i]}\nendobj\n"); + } + int crossReference = source.Length; + source.Append($"xref\n0 {objects.Length + 1}\n0000000000 65535 f \n"); + foreach (int offset in offsets) source.Append($"{offset:D10} 00000 n \n"); + source.Append($"trailer\n<< /Size {objects.Length + 1} /Root 1 0 R >>\nstartxref\n{crossReference}\n%%EOF\n"); + File.WriteAllText(path, source.ToString(), Encoding.ASCII); + } + + private static UInkPageInput Page(uint index) => new() + { + Canvas = UInkIccMapper.BuildCanvas(UInkTestEncoder.WorkspaceGuid, "", UInkTestEncoder.PageGuid(index), index, + index + 1, null, null) + }; + + private static MainWindow HeadlessWindow(InkCanvas canvas, TimeMachine history) + { + var window = (MainWindow)FormatterServices.GetUninitializedObject(typeof(MainWindow)); + typeof(MainWindow).GetField("inkCanvas", Fields).SetValue(window, canvas); + typeof(MainWindow).GetField("timeMachine", Fields).SetValue(window, history); + typeof(DispatcherObject).GetField("_dispatcher", Fields).SetValue(window, canvas.Dispatcher); + // 未初始化对象不会运行字段初始化器;补上生产代码中由初始化器保证非空的 PPT 逐页集合。 + foreach (var name in new[] { "_pptPageResources", "_quickPanelOwners", "_memoryStreams" }) + { + var field = typeof(MainWindow).GetField(name, Fields); + if (field != null && field.GetValue(window) == null) + field.SetValue(window, Activator.CreateInstance(field.FieldType, true)); + } + return window; + } + + private static BitmapSource Bitmap() => BitmapSource.Create(2, 3, 96, 96, PixelFormats.Bgra32, null, + new byte[] { 0, 0, 255, 255, 0, 255, 0, 255, 255, 0, 0, 255, 100, 100, 100, 255, + 1, 2, 3, 128, 7, 8, 9, 255 }, 8); + + private static BitmapImage FileBitmap(string path) + { + var bitmap = new BitmapImage(); + bitmap.BeginInit(); + bitmap.UriSource = new Uri(path); + bitmap.CacheOption = BitmapCacheOption.OnLoad; + bitmap.EndInit(); + return bitmap; + } + + private static byte[] Pixels(BitmapSource source) + { + if (source.Format != PixelFormats.Bgra32) source = new FormatConvertedBitmap(source, PixelFormats.Bgra32, null, 0); + int stride = source.PixelWidth * 4; + var bytes = new byte[source.PixelHeight * stride]; + source.CopyPixels(bytes, stride, 0); + return bytes; + } + + private static void PointNear(UInkChecks c, Point expected, Point actual, string label) + { + c.Near(expected.X, actual.X, label + " X"); + c.Near(expected.Y, actual.Y, label + " Y"); + } + + private sealed class TempDirectory : IDisposable + { + internal readonly string Root = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), + "UInkMediaTest_" + Guid.NewGuid().ToString("N"))).FullName; + + public void Dispose() => Directory.Delete(Root, true); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkPptTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkPptTests.cs new file mode 100644 index 000000000..4096a0a39 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkPptTests.cs @@ -0,0 +1,726 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.Serialization; +using System.Xml.Linq; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; +using Ink_Canvas; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; +using InkCanvasPPTAgent.Contracts; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace InkCanvas.Calibration.Tests.UInk +{ + public class ExportShowProxy : DispatchProxy + { + protected override object Invoke(MethodInfo method, object[] args) => method.Name switch + { + "get_IsConnected" or "get_IsInSlideShow" => true, + "get_SlidesCount" => 2, + "GetCurrentSlideNumber" => 1, + "get_PPTApplication" => null, + _ => throw new NotSupportedException(method.Name) + }; + } + + internal static class UInkPptTests + { + internal static void Register(UInkSuite suite) + { + suite.Test(nameof(SlideReorderAndDeletion), SlideReorderAndDeletion); + suite.Test(nameof(ForeignSlideAndIndexFallback), ForeignSlideAndIndexFallback); + suite.Test(nameof(LegacyStorageSharesSlideInk), LegacyStorageSharesSlideInk); + suite.Test(nameof(FlipIgnoresFullMapAndStaleDecode), FlipIgnoresFullMapAndStaleDecode); + suite.Test(nameof(PartialSlideIdCapture), PartialSlideIdCapture); + suite.Test(nameof(LegacyExportsAfterSlideRevisit), LegacyExportsAfterSlideRevisit); + suite.Test(nameof(EndingBeforeRestorePreservesArchive), EndingBeforeRestorePreservesArchive); + suite.Test(nameof(FailedRestoreSavesNewInkBesideArchive), FailedRestoreSavesNewInkBesideArchive); + suite.Test(nameof(LossyRestoreOnlyCopiesChangedContent), LossyRestoreOnlyCopiesChangedContent); + suite.Test(nameof(ClearedRestoredArchiveCanReplaceOriginal), ClearedRestoredArchiveCanReplaceOriginal); + suite.Test(nameof(UInkShowArchiveRestoresAfterReorder), UInkShowArchiveRestoresAfterReorder); + suite.Test(nameof(UInkShowArchiveKeepsUnboundAndPositionPages), UInkShowArchiveKeepsUnboundAndPositionPages); + suite.Test(nameof(LegacyOnlyShowArchiveRestores), LegacyOnlyShowArchiveRestores); + suite.Test(nameof(UInkShowArchiveWinsOverLegacy), UInkShowArchiveWinsOverLegacy); + suite.Test(nameof(XmlShowArchiveKeepsLegacyBehavior), XmlShowArchiveKeepsLegacyBehavior); + suite.Test(nameof(PerSlideMediaOwnership), PerSlideMediaOwnership); + suite.Test(nameof(AgentContractBothDirections), AgentContractBothDirections); + } + + private static void SlideReorderAndDeletion(UInkChecks c) + { + var original = new PptSlideMap(new[] { 301, 302, 303 }); + var ink = new PptSlideStorage(); + ink.Write(original.Key(1), new byte[] { 12 }); + ink.Write(original.Key(2), new byte[] { 34 }); + var changed = new PptSlideMap(new[] { 303, 301 }); + var pages = changed.CaptureOrder(2, ink.InkedKeys()); + c.Equal(3, pages.Count, "two active pages and deleted page with ink"); + c.That(ink.Read(pages[0]) == null, "no ink inherited at the old position"); + c.Equal((byte)12, ink.Read(pages[1])[0], "ink follows SlideID after reorder"); + var canvases = pages.Select((key, i) => PptSlideMap.CaptureCanvas(UInkTestEncoder.WorkspaceGuid, + "", UInkTestEncoder.PageGuid((uint)i), key, i + 1, 2)).ToArray(); + c.Equal(301, canvases[1].SlideId, "moved page keeps SlideID"); + c.Equal(0, canvases[1].Binding, "explicit SlideID binding"); + c.Equal(0, canvases[1].PageState ?? 0, "moved slide remains active"); + c.Equal(1, canvases[2].PageState, "deleted slide is Retained"); + c.Equal(302, canvases[2].SlideId, "retained slide keeps SlideID"); + c.Equal((byte)34, ink.Read(pages[2])[0], "retained ink survives deletion"); + } + + private static void ForeignSlideAndIndexFallback(UInkChecks c) + { + c.That(MainWindow.DifferentPptSource("ICC-PPT:A|A|3", "ICC-PPT:B|B|3"), "different ICC presentation hint"); + c.That(!MainWindow.DifferentPptSource("ICC-PPT:A|A|3", "ICC-PPT:A|A|2"), "deletion alone keeps source"); + var slides = new PptSlideMap(new[] { 42, 41, 0 }); + var indexed = PptSlideMap.CaptureCanvas("", "", UInkTestEncoder.PageGuid(2), slides.Key(3), 3, 3); + c.Equal(1, indexed.Binding, "missing ID uses position"); + c.Equal(null, indexed.SlideId, "no synthesized SlideID"); + var byIndex = new UInkPageData { Canvas = indexed, SlideIndex = 3 }; + var moved = new UInkPageData { Canvas = new UInkCanvas { SlideId = 41 } }; + var foreign = new UInkPageData { Canvas = new UInkCanvas { SlideId = 404, PageIndex = 0 } }; + var pages = new List { foreign, moved, byIndex }; + var targets = MainWindow.BindPptPages(pages, 3, slides.Resolve); + c.That(targets.SequenceEqual(new[] { moved, byIndex }), "only successful bindings enter storage"); + c.Equal(2, moved.SlideIndex, "resolver determines the new position"); + c.That(foreign.IsUnbound && foreign.SlideIndex == null && pages.Contains(foreign), + "foreign page retained without falling back to pageIndex"); + c.Equal(404, foreign.SlideId, "original unbound ID is preserved"); + byIndex.Canvas.PageIndex = 1; + targets = MainWindow.BindPptPages(pages, 3, slides.Resolve); + c.Equal(0, targets.Count, "colliding ID and position are both excluded"); + c.That(moved.IsUnbound && byIndex.IsUnbound && moved.SlideIndex == null && byIndex.SlideIndex == null, + "conflict pages have no target index"); + } + + internal static void PreservedPagesRoundtrip(UInkChecks c, string fixture) + { + ReopenedDeletedSlideKeepsBothContents(c, fixture); + var source = UInkIccMapper.BuildPageIndex(UInkReader.Read(fixture), 1, 1, _ => null); + var context = new UInkCaptureContext { Workspace = source.Workspace, DpiX = 1, DpiY = 1 }; + foreach (var page in source.Pages.Where(p => p.IsUnbound || p.PageKind == 1).Concat(source.RetainedPages)) + { + // 包括已经物化的未绑定页;另存不能只保留页头。 + page.EnsureMaterialized(); + context.CapturePreservedPptPage(page, ""); + } + var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).FullName; + try + { + var path = Path.Combine(dir, "preserved.uink"); + context.Save(path, false); + var result = UInkIccMapper.BuildPageIndex(UInkReader.Read(path), 1, 1); + c.Equal(3, result.RetainedPages.Count, "two unresolved pages and the original retained page"); + c.Equal(1, result.Pages.Count, "only EndScreen remains in the display sequence"); + c.Equal(1, result.Pages[0].PageKind, "EndScreen survives save"); + c.Equal(null, result.Pages[0].SlideId, "EndScreen has no SlideID"); + foreach (var page in result.RetainedPages) + { + var original = source.Pages.Concat(source.RetainedPages).Single(p => p.Canvas.PageGuid == page.Canvas.PageGuid); + page.EnsureMaterialized(); + c.Equal(original.SlideId, page.SlideId, "retained ID survives save"); + c.Equal(original.FinalStrokes.Count, page.FinalStrokes.Count, "retained ink survives save"); + } + } + finally { Directory.Delete(dir, true); } + } + + private static void ReopenedDeletedSlideKeepsBothContents(UInkChecks c, string fixture) + { + int[] ids = { 256, 500 }; + var window = TestShow(new PptSlideMap(ids), out var canvas); + var manager = typeof(MainWindow).GetField("_pptManager", fields); + var connected = manager.GetValue(window); + var agent = new PPTAgentLinkManager(); + PPTState State(int index, int id) => new PPTState { SlideIds = ids, SlideId = id, SlideIndex = index, TotalSlides = ids.Length }; + void Open() + { + manager.SetValue(window, agent); + typeof(PPTAgentLinkManager).GetField("_lastState", fields).SetValue(agent, State(1, 500)); + var projection = UInkIccMapper.BuildPageIndex(UInkReader.Read(fixture), 1, 1); + typeof(MainWindow).GetMethod("RestoreUInkToPPT", fields).Invoke(window, + new object[] { projection, null, new DpiScale(1, 1) }); + manager.SetValue(window, connected); + } + void Flip(int pos, int id) => WaitForFlip(window, State(pos, id)); + + Open(); + Flip(2, 256); + c.Equal(1, canvas.Strokes.Count, "imported slide 256 has one stroke"); + canvas.Strokes.Add(new Stroke(new StylusPointCollection { new StylusPoint(61, 14) })); + ids = new[] { 501, 500 }; + Flip(1, 500); + Open(); + var context = (UInkCaptureContext)typeof(MainWindow).GetMethod("CaptureUInk", fields).Invoke(window, null); + var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"))).FullName; + try + { + string path = Path.Combine(dir, "reopened.uink"); + context.Save(path, false); + var read = UInkReader.Read(path); + var all = read.Document.Canvases.Select(record => record.Canvas).ToList(); + c.That(all.Select(page => (int)page.PageIndex).SequenceEqual(Enumerable.Range(0, all.Count)), + "full save uses contiguous indices across all page kinds"); + c.Equal(all.Count, all.Select(page => page.PageGuid).Distinct().Count(), "unique Canvas keys"); + var output = UInkIccMapper.BuildPageIndex(read, 1, 1); + c.Equal(1, output.Workspace.CurrentPageIndex, "current slide 500 is second in final order"); + c.That(output.Pages.Any(page => page.PageKind == 1), "EndScreen survives"); + var copies = output.RetainedPages.Where(page => page.SlideId == 256).ToList(); + foreach (var copy in copies) copy.EnsureMaterialized(); + c.That(copies.Select(page => page.FinalStrokes.Count).OrderBy(n => n).SequenceEqual(new[] { 1, 2 }), + "edited deleted slide and reopened original both survive"); + } + finally + { + context.ReleaseResources(); + Directory.Delete(dir, true); + } + } + + private sealed class FakeStorage : IPptSlideStorage + { + private readonly Dictionary _ink = new(); + public byte[] Read(PptPageKey key) => _ink.GetValueOrDefault(key); + public void Write(PptPageKey key, byte[] ink) => _ink[key] = ink; + public void Clear() => _ink.Clear(); + } + + private static void LegacyStorageSharesSlideInk(UInkChecks c) + { + var store = new FakeStorage(); + var slides = new PptSlideMap(new[] { 41, 42 }); + using var legacy = new PPTInkManager(store, i => slides.Key(i)); + var strokes = new StrokeCollection { new Stroke(new StylusPointCollection { new StylusPoint(2, 3) }) }; + store.Write(slides.Key(1), PptSlideStorage.Encode(strokes)); + slides = new PptSlideMap(new[] { 42, 41 }); + c.Equal(0, legacy.LoadSlideStrokes(1).Count, "legacy save sees the empty new first slide"); + c.Equal(1, legacy.LoadSlideStrokes(2).Count, "legacy save sees off-slide live storage"); + legacy.ForceSaveSlideStrokes(1, strokes); + c.Equal(1, PptSlideStorage.Decode(store.Read(slides.Key(1))).Count, "legacy open feeds page flips"); + legacy.ClearAllStrokes(); + c.That(store.Read(slides.Key(2)) == null, "legacy replacement clears shared storage"); + } + + private const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + + private static MainWindow TestShow(PptSlideMap map, out System.Windows.Controls.InkCanvas canvas) + { + var window = (MainWindow)FormatterServices.GetUninitializedObject(typeof(MainWindow)); + void Set(string field, object value) => typeof(MainWindow).GetField(field, fields).SetValue(window, value); + void Init(string field) + { + var info = typeof(MainWindow).GetField(field, fields); + info.SetValue(window, Activator.CreateInstance(info.FieldType)); + } + + canvas = new System.Windows.Controls.InkCanvas { Width = 80, Height = 80 }; + canvas.Measure(new Size(80, 80)); + canvas.Arrange(new Rect(0, 0, 80, 80)); + Set("inkCanvas", canvas); + Set("_pptManager", DispatchProxy.Create()); + Set("timeMachine", new TimeMachine()); + Set("_memoryStreams", new PptSlideStorage()); + Init("_archivePages"); + foreach (string name in new[] { "_observedShowKeys", "_observedPositions", "_unclaimedArchivePages", "_pptElements", "_pendingPptMedia", + "_idsSinceConfirmedMap", "_pptPageGuids", "_preservedPptPages", "_preservedPptGuids", "_pptPageResources", "_quickPanelOwners" }) + Init(name); + Set("_uinkWorkspaceIds", new string[3]); + Set("_confirmedSlides", map); + Set("_showSlides", map); + Set("_canvasSlide", map.Key(2)); + Set("_currentSlideShowPosition", 1); + window.IsInPPTPresentationMode = true; + return window; + } + + private static void FlipIgnoresFullMapAndStaleDecode(UInkChecks c) => WithShowArchive(async folder => + { + int[] ids = { 41, 42, 43 }; + var show = ArchiveShow(ids, out var canvas, out var agent); + var mapField = typeof(MainWindow).GetField("_showSlides", fields); + object originalMap = mapField.GetValue(show); + var store = (PptSlideStorage)typeof(MainWindow).GetField("_memoryStreams", fields).GetValue(show); + AddArchiveStroke(canvas, 22); + var key = PptPageKey.At(2, 42); + store.Write(key, PptSlideStorage.Encode(canvas.Strokes)); + canvas.Strokes.Clear(); + var decoding = FlipAsync(show, SetArchiveAgentState(agent, ids, 2, null)); + // 不让 UI 泵送解码提交;下一页到达后才释放调度器。 + await FlipAsync(show, SetArchiveAgentState(agent, ids, 3, null)); + await decoding; + c.That(ReferenceEquals(originalMap, mapField.GetValue(show)), "flips never rebuild the slide table"); + c.Equal(0, canvas.Strokes.Count, "late slide 42 decode cannot draw on slide 43"); + c.Near(22, ArchiveStrokeX(PptSlideStorage.Decode(store.Read(key))), "rapid flip preserves pending ink", 0.02); + }); + + private static void PartialSlideIdCapture(UInkChecks c) + { + var window = TestShow(new PptSlideMap(null), out var canvas); + void Flip(int position, int id, int[] ids) => WaitForFlip(window, new PPTState { SlideIndex = position, SlideId = id, SlideIds = ids, TotalSlides = 2 }); + UInkCaptureContext Capture() => (UInkCaptureContext)typeof(MainWindow).GetMethod("CaptureUInk", fields).Invoke(window, null); + Flip(1, 301, null); + canvas.Strokes.Add(new Stroke(new StylusPointCollection { new StylusPoint(8, 4) })); + Flip(2, 302, null); + var first = Capture(); + c.That(first.Pages.Select(page => page.Canvas.SlideId).SequenceEqual(new int?[] { 301, 302 }), + "current-only Agent preserves both observed IDs"); + c.That(first.Pages.All(page => page.Canvas.PageState != 1), "missing table cannot prove deletion"); + first.ReleaseResources(); + Flip(1, 301, new[] { 302, 301 }); + Flip(1, 301, null); + var last = Capture(); + c.That(last.Pages.Select(page => page.Canvas.SlideId).SequenceEqual(new int?[] { 302, 301 }), + "transient table failure keeps last confirmed presentation order"); + c.Equal(1, last.Workspace.CurrentPageIndex, "currentPageIndex uses the confirmed order"); + last.ReleaseResources(); + c.That(MainWindow.DifferentShow("A/deck.pptx", "deck", "B/deck.pptx", "deck"), + "equal names and SlideIDs do not imply equal presentations"); + } + + private static void LegacyExportsAfterSlideRevisit(UInkChecks c) + { + var window = TestShow(new PptSlideMap(new[] { 42, 41 }), out var canvas); + var original = MainWindow.Settings; + var root = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"))).FullName; + try + { + MainWindow.Settings = new Settings(); + MainWindow.Settings.Automation.IsSaveStrokesAsUInK = false; + MainWindow.Settings.PowerPointSettings.EnableSmartMode = false; + void Add(int x) => canvas.Strokes.Add(new Stroke(new StylusPointCollection { new StylusPoint(x, 4) })); + void Flip(int position, int? id) => WaitForFlip(window, new PPTState { SlideIndex = position, SlideId = id, TotalSlides = 2, + SlideIds = new[] { 42, 41 } }); + + Add(10); + Flip(2, 42); + c.Equal(0, canvas.Strokes.Count, "B starts blank"); + Add(20); + Flip(1, 41); + c.Equal(1, canvas.Strokes.Count, "A restored"); + Add(30); + // 放映顺序 A、B,文稿顺序 B、A。旧归档按放映位置;逐页导出按文稿索引。 + var folder = Path.Combine(root, "archive"); + window.SaveLegacyArchiveAsync(folder, 2).GetAwaiter().GetResult(); + c.That(Directory.GetFiles(folder).Select(Path.GetFileName).OrderBy(x => x) + .SequenceEqual(new[] { "0001.icstk", "0002.icstk" }), "HEAD archive file names"); + using (var page = File.OpenRead(Path.Combine(folder, "0001.icstk"))) + c.Near(10, new StrokeCollection(page)[0].StylusPoints[0].X, "HEAD file 0001 holds A", 0.02); + + foreach (bool clear in new[] { false, true }) + { + if (clear) canvas.Strokes.Clear(); + foreach (var format in new[] { "automation", "xml", "icstk", "zip" }) + { + string dir = Path.Combine(root, clear.ToString(), format); + MainWindow.Settings.Automation.AutoSavedStrokesLocation = dir; + MainWindow.Settings.Automation.IsSaveStrokesAsXML = format == "xml"; + MainWindow.Settings.Automation.IsSaveFullPageStrokes = format == "zip"; + if (format == "automation") window.SaveStrokesForAutomation(dir, false); + else window.SaveInkCanvasStrokes(false, true); + var files = Directory.GetFiles(dir, "*", SearchOption.AllDirectories); + if (format == "zip") + { + using var zip = ZipFile.OpenRead(files.Single(f => f.EndsWith(".zip"))); + c.That(zip.GetEntry("page_0001.icstk") != null, "ZIP contains B"); + c.Equal(!clear, zip.GetEntry("page_0002.png") != null, "full-page PNG follows live A"); + var entry = zip.GetEntry("page_0002.icstk"); + c.Equal(!clear, entry != null, "ZIP follows live A"); + if (entry != null) + { + using var stream = entry.Open(); + using var bytes = new MemoryStream(); + stream.CopyTo(bytes); + c.Equal(2, PptSlideStorage.Decode(bytes.ToArray()).Count, "ZIP includes added stroke"); + } + } + else + { + string ext = format == "xml" ? ".xml" : ".icstk"; + c.That(files.Any(f => f.EndsWith("_Page-1" + ext)), format + " preserves B"); + var path = files.SingleOrDefault(f => f.EndsWith("_Page-2" + ext)); + c.Equal(!clear, path != null, format + " exports live A"); + if (path != null) + { + int count = format == "xml" ? XDocument.Load(path).Root.Elements("Stroke").Count() + : PptSlideStorage.Decode(File.ReadAllBytes(path)).Count; + c.Equal(2, count, format + " includes added stroke"); + } + } + } + } + typeof(MainWindow).GetMethod("SaveShowCanvas", fields).Invoke(window, new object[] { 1 }); + window.SaveLegacyArchiveAsync(folder, 2).GetAwaiter().GetResult(); + c.That(!File.Exists(Path.Combine(folder, "0001.icstk")) && File.Exists(Path.Combine(folder, "0002.icstk")), + "HEAD removes cleared show position and keeps B"); + Flip(1, null); + c.Equal(PptPageKey.At(1, null), (PptPageKey)typeof(MainWindow).GetField("_canvasSlide", fields).GetValue(window), + "missing current SlideID uses show position even with a complete table"); + } + finally + { + MainWindow.Settings = original; + Directory.Delete(root, true); + } + } + + private static void EndingBeforeRestorePreservesArchive(UInkChecks c) => WithShowArchive(async folder => + { + int[] ids = { 41 }; + var first = ArchiveShow(ids, out var canvas, out _); + AddArchiveStroke(canvas, 10); + await first.SavePptShowArchiveAsync(folder, 1); + var next = ArchiveShow(ids, out _, out _); + string path = await next.LoadPptShowArchiveAsync(folder, 0); + byte[] before = File.ReadAllBytes(path); + var opening = next.RestorePptShowUInkAsync(path, 1); + typeof(MainWindow).GetField("isEnteredSlideShowEndEvent", fields).SetValue(next, true); + await next.SavePptShowArchiveAsync(folder, 1); + await opening; + c.That(File.ReadAllBytes(path).SequenceEqual(before), "immediate end preserves the previous archive bytes"); + c.Equal(1, Directory.GetFiles(folder, "*.uink").Length, "empty pending restore creates no sibling"); + }); + + private static void FailedRestoreSavesNewInkBesideArchive(UInkChecks c) => WithShowArchive(async folder => + { + string path = Path.Combine(folder, "slides.uink"); + byte[] invalid = { 0xff }; + File.WriteAllBytes(path, invalid); + var show = ArchiveShow(new[] { 41 }, out var canvas, out _); + await show.RestorePptShowUInkAsync(await show.LoadPptShowArchiveAsync(folder, 0), 1); + AddArchiveStroke(canvas, 37); + await show.SavePptShowArchiveAsync(folder, 1); + c.That(File.ReadAllBytes(path).SequenceEqual(invalid), "failed restore preserves original bytes"); + string sibling = Directory.GetFiles(folder, "*.uink").Single(file => file != path); + var dpi = VisualTreeHelper.GetDpi(canvas); + var saved = UInkIccMapper.BuildPageIndex(UInkReader.Read(sibling), dpi.DpiScaleX, dpi.DpiScaleY); + c.Near(37, ArchiveStrokeX(saved.Pages.Single().FinalStrokes), "sibling contains the new stroke", 0.02); + }); + + private static void LossyRestoreOnlyCopiesChangedContent(UInkChecks c) => WithShowArchive(async folder => + { + int[] ids = { 41 }; + var first = ArchiveShow(ids, out var canvas, out _); + AddArchiveStroke(canvas, 10); + await first.SavePptShowArchiveAsync(folder, 1); + string path = Path.Combine(folder, "slides.uink"); + // FILE-16:有效页后追加截断的 Map,可恢复旧笔迹,但不能覆盖原件。 + using (var append = File.Open(path, FileMode.Append)) append.WriteByte(0x81); + byte[] before = File.ReadAllBytes(path); + var next = ArchiveShow(ids, out var restored, out _); + await next.RestorePptShowUInkAsync(await next.LoadPptShowArchiveAsync(folder, 0), 1); + c.Equal(1, restored.Strokes.Count, "lossy archive still restores its valid ink"); + await next.SavePptShowArchiveAsync(folder, 1); + c.Equal(1, Directory.GetFiles(folder, "*.uink").Length, "restored ink alone creates no copy"); + AddArchiveStroke(restored, 40); + await next.SavePptShowArchiveAsync(folder, 1); + c.Equal(2, Directory.GetFiles(folder, "*.uink").Length, "new ink creates a sibling"); + c.That(File.ReadAllBytes(path).SequenceEqual(before), "lossy archive stays byte-identical"); + }); + + private static void ClearedRestoredArchiveCanReplaceOriginal(UInkChecks c) => WithShowArchive(async folder => + { + int[] ids = { 41 }; + var first = ArchiveShow(ids, out var canvas, out _); + AddArchiveStroke(canvas, 10); + await first.SavePptShowArchiveAsync(folder, 1); + var next = ArchiveShow(ids, out var restored, out _); + string path = await next.LoadPptShowArchiveAsync(folder, 0); + await next.RestorePptShowUInkAsync(path, 1); + c.Equal(1, restored.Strokes.Count, "restore completed before clear"); + restored.Strokes.Clear(); + await next.SavePptShowArchiveAsync(folder, 1); + c.Equal(0, UInkReader.Read(path).Document.Canvases.Sum(page => page.Blocks.Count), "explicit clear replaces old ink"); + c.Equal(1, Directory.GetFiles(folder, "*.uink").Length, "complete restore needs no sibling"); + }); + + private static void UInkShowArchiveRestoresAfterReorder(UInkChecks c) => WithShowArchive(async folder => + { + var show = ArchiveShow(new[] { 41, 42 }, out var canvas, out var agent); + AddArchiveStroke(canvas, 10); + FlipArchiveShow(show, agent, new[] { 41, 42 }, 2); + AddArchiveStroke(canvas, 20); + show.IsInPPTPresentationMode = false; + await show.SavePptShowArchiveAsync(folder, 2); + + string main = Path.Combine(folder, "slides.uink"); + c.That(Directory.GetFiles(folder).Select(Path.GetFileName).SequenceEqual(new[] { "slides.uink" }), + "one UInk file and no per-slide ICSTK"); + var projection = UInkIccMapper.BuildPageIndex(UInkReader.Read(main), 1, 1); + c.Equal(2, projection.Workspace.WorkspaceType, "archive is a PPT workspace"); + c.That(projection.Pages.Select(page => page.SlideId).SequenceEqual(new int?[] { 41, 42 }) && + projection.Pages.All(page => page.Binding == 0), "both slides use SlideID binding"); + + var reopened = ArchiveShow(new[] { 42, 41 }, out var restored, out var reopenedAgent); + var archive = await reopened.LoadPptShowArchiveAsync(folder, 0); + c.Equal(main, archive, "next show selects the archive"); + reopened.IsInPPTPresentationMode = false; + c.That(await reopened.RestorePptShowUInkAsync(archive, 2) == PptRestoreNotice(0, 2), + "both archive slides restored"); + c.Near(20, ArchiveStrokeX(restored.Strokes), "new first slide restores ID 42", 0.02); + FlipArchiveShow(reopened, reopenedAgent, new[] { 42, 41 }, 2); + c.Near(10, ArchiveStrokeX(restored.Strokes), "new second slide restores ID 41", 0.02); + + restored.Strokes.Clear(); + AddArchiveStroke(restored, 30); + await reopened.SavePptShowArchiveAsync(folder, 2); + var again = ArchiveShow(new[] { 41, 42 }, out var updated, out _); + await again.RestorePptShowUInkAsync(await again.LoadPptShowArchiveAsync(folder, 0), 2); + c.Near(30, ArchiveStrokeX(updated.Strokes), "next save replaces the same archive", 0.02); + c.Equal(1, Directory.GetFiles(folder).Length, "no numbered UInk copies or legacy files"); + }); + + private static void UInkShowArchiveKeepsUnboundAndPositionPages(UInkChecks c) => WithShowArchive(async folder => + { + // INK-6 / DEV-1:固定 200% DPI,归档使用设备像素,断言比较还原后的 DIP。 + var dpi = new DpiScale(2, 2); + int[] originalIds = { 41, 42, 0 }; + var show = ArchiveShow(originalIds, out var canvas, out var agent); + VisualTreeHelper.SetRootDpi(canvas, dpi); + AddArchiveStroke(canvas, 10); + FlipArchiveShow(show, agent, originalIds, 2); + AddArchiveStroke(canvas, 20); + FlipArchiveShow(show, agent, originalIds, 3); + AddArchiveStroke(canvas, 30); + await show.SavePptShowArchiveAsync(folder, 3); + + int[] nextIds = { 91, 42, 93 }; + var reopened = ArchiveShow(nextIds, out var restored, out var reopenedAgent); + VisualTreeHelper.SetRootDpi(restored, dpi); + string main = await reopened.LoadPptShowArchiveAsync(folder, 0); + string notice = await reopened.RestorePptShowUInkAsync(main, 3); + c.That(notice?.StartsWith(PptRestoreNotice(1, 2), StringComparison.Ordinal) == true, + "notice reports one unbound and two restored pages"); + c.Equal(0, restored.Strokes.Count, "unmatched SlideID is not rebound to its former position"); + FlipArchiveShow(reopened, reopenedAgent, nextIds, 2); + c.Near(20, ArchiveStrokeX(restored.Strokes), "SlideID page restores to its slide", 0.02); + FlipArchiveShow(reopened, reopenedAgent, nextIds, 3); + c.Near(30, ArchiveStrokeX(restored.Strokes), "binding=1 restores to the matching position", 0.02); + + await reopened.SavePptShowArchiveAsync(folder, 3); + var projection = UInkIccMapper.BuildPageIndex(UInkReader.Read(main), dpi.DpiScaleX, dpi.DpiScaleY); + var retained = projection.RetainedPages.Single(); + c.Equal(41, retained.SlideId, "Retained page keeps its original SlideID"); + retained.EnsureMaterialized(); + c.Near(10, ArchiveStrokeX(retained.FinalStrokes), "next archive preserves unbound ink as Retained", 0.02); + var bound = projection.Pages.Single(page => page.SlideId == 42); + bound.EnsureMaterialized(); + c.Near(20, ArchiveStrokeX(bound.FinalStrokes), "next archive keeps slide 42 ink on its own page", 0.02); + }); + + private static void LegacyOnlyShowArchiveRestores(UInkChecks c) => WithShowArchive(async folder => + { + WriteArchiveStroke(Path.Combine(folder, "0001.icstk"), 70); + WriteArchiveStroke(Path.Combine(folder, "0002.icstk"), 80); + int[] ids = { 42, 41 }; + var show = ArchiveShow(ids, out var canvas, out var agent); + c.Equal(null, await show.LoadPptShowArchiveAsync(folder, 0), "legacy fallback selected"); + typeof(MainWindow).GetMethod("LoadCurrentSlideInk", fields).Invoke(show, new object[] { 1 }); + c.Near(70, ArchiveStrokeX(canvas.Strokes), "legacy file 0001 maps to show position 1", 0.02); + FlipArchiveShow(show, agent, ids, 2); + c.Near(80, ArchiveStrokeX(canvas.Strokes), "legacy file 0002 maps to show position 2", 0.02); + }); + + private static void UInkShowArchiveWinsOverLegacy(UInkChecks c) => WithShowArchive(async folder => + { + int[] ids = { 41, 42 }; + var show = ArchiveShow(ids, out var canvas, out _); + AddArchiveStroke(canvas, 10); + string legacy = Path.Combine(folder, "0001.icstk"); + WriteArchiveStroke(legacy, 75); + var original = File.ReadAllBytes(legacy); + await show.SavePptShowArchiveAsync(folder, 2); + + var reopened = ArchiveShow(ids, out var restored, out _); + var archive = await reopened.LoadPptShowArchiveAsync(folder, 0); + c.Equal(Path.Combine(folder, "slides.uink"), archive, "UInk wins when both formats exist"); + await reopened.RestorePptShowUInkAsync(archive, 2); + c.Near(10, ArchiveStrokeX(restored.Strokes), "restored UInk instead of stale legacy ink", 0.02); + c.That(original.SequenceEqual(File.ReadAllBytes(legacy)), "legacy file survives write and restore byte-for-byte"); + }); + + private static void XmlShowArchiveKeepsLegacyBehavior(UInkChecks c) => WithShowArchive(async folder => + { + int[] ids = { 42, 41 }; + var show = ArchiveShow(ids, out var canvas, out var agent, positionId: 41); + AddArchiveStroke(canvas, 10); + await show.SavePptShowArchiveAsync(folder, 2); + string uink = Path.Combine(folder, "slides.uink"); + byte[] originalUInk = File.ReadAllBytes(uink); + + MainWindow.Settings.Automation.IsSaveStrokesAsUInK = false; + MainWindow.Settings.Automation.IsSaveStrokesAsXML = true; + canvas.Strokes.Clear(); + AddArchiveStroke(canvas, 30); + FlipArchiveShow(show, agent, ids, 2, positionId: 42); + AddArchiveStroke(canvas, 40); + // 实际结束事件在归档入口前保存末页。 + typeof(MainWindow).GetMethod("SaveShowCanvas", fields).Invoke(show, new object[] { 2 }); + var legacyBytes = (Dictionary)typeof(MainWindow).GetField("_archivePages", fields).GetValue(show); + await show.SavePptShowArchiveAsync(folder, 2); + + c.That(Directory.GetFiles(folder).Select(Path.GetFileName).OrderBy(x => x) + .SequenceEqual(new[] { "0001.icstk", "0002.icstk", "slides.uink" }), "XML setting keeps HEAD archive names"); + c.That(originalUInk.SequenceEqual(File.ReadAllBytes(uink)), "legacy save leaves existing UInk untouched"); + c.That(legacyBytes[1].SequenceEqual(File.ReadAllBytes(Path.Combine(folder, "0001.icstk"))) && + legacyBytes[2].SequenceEqual(File.ReadAllBytes(Path.Combine(folder, "0002.icstk"))), + "legacy writer preserves each position's original ISF bytes"); + var reopened = ArchiveShow(ids, out var restored, out _, positionId: 41); + c.Equal(null, await reopened.LoadPptShowArchiveAsync(folder, 0), "XML restore selects legacy despite UInk file"); + typeof(MainWindow).GetMethod("LoadCurrentSlideInk", fields).Invoke(reopened, new object[] { 1 }); + c.Near(30, ArchiveStrokeX(restored.Strokes), "XML restore follows HEAD show position", 0.02); + }); + + private static MainWindow ArchiveShow(int[] ids, out System.Windows.Controls.InkCanvas canvas, + out PPTAgentLinkManager agent, int? positionId = null) + { + var map = new PptSlideMap(ids); + var show = TestShow(map, out canvas); + agent = new PPTAgentLinkManager(); + typeof(MainWindow).GetField("_pptManager", fields).SetValue(show, agent); + typeof(MainWindow).GetField("_canvasSlide", fields).SetValue(show, PptPageKey.At(1, positionId ?? ids[0])); + typeof(MainWindow).GetField("_uinkSessions", fields).SetValue(show, new MainWindow.UInkSession[3]); + typeof(MainWindow).GetField("_uinkSaves", fields).SetValue(show, new UInkSaveQueue()); + typeof(MainWindow).GetField("frozenPages", fields).SetValue(show, new bool[101]); + SetArchiveAgentState(agent, ids, 1, positionId); + return show; + } + + private static PPTState SetArchiveAgentState(PPTAgentLinkManager agent, int[] ids, int position, int? positionId) + { + var state = new PPTState { SlideIds = ids, SlideId = positionId ?? ids[position - 1], + SlideIndex = position, TotalSlides = ids.Length }; + typeof(PPTAgentLinkManager).GetField("_lastState", fields).SetValue(agent, state); + return state; + } + + private static void FlipArchiveShow(MainWindow show, PPTAgentLinkManager agent, int[] ids, int position, int? positionId = null) => + WaitForFlip(show, SetArchiveAgentState(agent, ids, position, positionId)); + + private static Task FlipAsync(MainWindow window, PPTState state) => + (Task)typeof(MainWindow).GetMethod("OnPPTSlideShowNextSlide", fields).Invoke(window, new object[] { state }); + + private static void WaitForFlip(MainWindow window, PPTState state) + { + var task = FlipAsync(window, state); + if (!task.IsCompleted) + { + var frame = new DispatcherFrame(); + var dispatcher = Dispatcher.CurrentDispatcher; + var timeout = new DispatcherTimer { Interval = TimeSpan.FromSeconds(10) }; + timeout.Tick += (_, _) => frame.Continue = false; + timeout.Start(); + _ = task.ContinueWith(_ => dispatcher.InvokeAsync(() => frame.Continue = false)); + Dispatcher.PushFrame(frame); + timeout.Stop(); + if (!task.IsCompleted) throw new TimeoutException("flip decode"); + } + task.GetAwaiter().GetResult(); + } + + private static string PptRestoreNotice(int unbound, int restored) => + string.Format(Ink_Canvas.Properties.CanvasStrings.GetString("Canvas_UInkPptRestored"), unbound, restored); + + private static void AddArchiveStroke(System.Windows.Controls.InkCanvas canvas, int x) => + canvas.Strokes.Add(new Stroke(new StylusPointCollection { new StylusPoint(x, 4) })); + + private static void WriteArchiveStroke(string path, int x) + { + using var stream = File.Create(path); + new StrokeCollection { new Stroke(new StylusPointCollection { new StylusPoint(x, 4) }) }.Save(stream); + } + + private static double? ArchiveStrokeX(StrokeCollection strokes) => + strokes.Count == 1 ? strokes[0].StylusPoints[0].X : (double?)null; + + private static void WithShowArchive(Func test) + { + string folder = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"))).FullName; + var originalSettings = MainWindow.Settings; + var originalContext = SynchronizationContext.Current; + var dispatcher = Dispatcher.CurrentDispatcher; + try + { + MainWindow.Settings = new Settings(); + MainWindow.Settings.Automation.AutoSavedStrokesLocation = folder; + MainWindow.Settings.PowerPointSettings.EnableSmartMode = false; + // 调度器仅用于 STA 续体,测试不创建窗口或连接 PowerPoint。 + SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(dispatcher)); + var task = test(folder); + if (!task.IsCompleted) + { + var frame = new DispatcherFrame(); + var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(30) }; + timer.Tick += (_, _) => frame.Continue = false; + task.GetAwaiter().OnCompleted(() => frame.Continue = false); + timer.Start(); + try { Dispatcher.PushFrame(frame); } + finally { timer.Stop(); } + if (!task.IsCompleted) throw new TimeoutException("PPT archive test did not complete."); + } + task.GetAwaiter().GetResult(); + } + finally + { + SynchronizationContext.SetSynchronizationContext(originalContext); + MainWindow.Settings = originalSettings; + Directory.Delete(folder, true); + } + } + + private static void PerSlideMediaOwnership(UInkChecks c) + { + var slides = new PptSlideMap(new[] { 302, 301 }); + var live = new Image(); + var hidden = new Image { Visibility = Visibility.Collapsed }; + var restored = new Image(); + var owners = new Dictionary { [hidden] = slides.Key(2) }; + var detached = new Dictionary> + { + [slides.Key(1)] = new() { live }, [slides.Key(2)] = new() { restored } + }; + var groups = MainWindow.CollectPptElements(new UIElement[] { live, hidden }, owners, detached, slides.Key(1)); + c.That(groups[slides.Key(1)].SequenceEqual(new[] { live }), "live page contains its element exactly once"); + c.That(groups[slides.Key(2)].SequenceEqual(new[] { hidden, restored }), "hidden and detached images retain ownership"); + } + + private sealed class OldState + { + public int SlideIndex { get; set; } + public int TotalSlides { get; set; } + public bool IsRunning { get; set; } + } + + private static void AgentContractBothDirections(UInkChecks c) + { + var oldWire = JsonConvert.SerializeObject(new PPTPipeMessage { Data = new OldState + { SlideIndex = 2, TotalSlides = 3, IsRunning = true } }); + var current = JObject.Parse(oldWire)["Data"].ToObject(); + c.That(current.IsRunning && current.SlideIndex == 2 && current.TotalSlides == 3, "old state fields"); + c.That(current.SlideId == null && current.SlideIds == null, "old Agent omits both optional fields"); + c.Equal(PptPageKey.At(2, null), PptSlideMap.FromAgent(current).Key(2), "old Agent storage uses position"); + current.SlideId = 301; + c.Equal(PptPageKey.At(2, null), PptSlideMap.FromAgent(current).Key(2), "show position does not locate a presentation ID"); + c.Equal(null, PptSlideMap.FromAgent(current).Resolve(301), "current-only Agent has no presentation index"); + current.SlideIds = new[] { 303, 301, 302 }; + var wire = JsonConvert.SerializeObject(new PPTPipeMessage { Data = current }); + var data = JObject.Parse(wire)["Data"]; + var old = data.ToObject(); + c.That(old.IsRunning && old.SlideIndex == 2 && old.TotalSlides == 3, "old ICC ignores new JSON fields"); + var roundtrip = data.ToObject(); + c.Equal(301, roundtrip.SlideId, "current SlideID on wire"); + c.That(roundtrip.SlideIds.SequenceEqual(current.SlideIds), "ordered presentation mapping on wire"); + c.Equal(2, PptSlideMap.FromAgent(roundtrip).Resolve(301), "agent map resolves moved slide"); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkReaderTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkReaderTests.cs new file mode 100644 index 000000000..cb797ec80 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkReaderTests.cs @@ -0,0 +1,195 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Ink_Canvas.UInk; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal sealed class UInkStructure + { + internal readonly UInkReadResult Read; + internal readonly List Canvases; + internal UInkReadStatus Status => Read.Status; + internal ushort? Version => Read.Version; + internal long? FailureOffset => Read.FailureOffset; + internal bool TruncatedTail => Read.TruncatedTail; + internal bool StoppedOnCorruption => Read.StoppedOnCorruption; + internal bool RequiresSaveAs => Read.RequiresSaveAs; + internal int SkippedBlocks => Read.SkippedBlocks; + internal int UnknownBlocks => Read.UnknownBlocks; + internal int Superseded => Read.DiagnosticCounts.GetValueOrDefault("FILE-8"); + internal UInkStructure(UInkReadResult read) + { + Read = read; + Canvases = read.Document?.Canvases.ConvertAll(r => new CanvasView(r)) ?? new(); + } + + internal sealed class CanvasView + { + internal readonly UInkCanvas Metadata; + internal readonly string Types; + internal readonly Dictionary Counts = new(); + internal int ClearCount => Counts.GetValueOrDefault(UInkBlockType.Clear); + internal (string, string, string, uint) Key => + (Metadata.WorkspaceGuid, Metadata.DeviceGuid, Metadata.PageGuid, Metadata.LayerIndex); + internal CanvasView(UInkCanvasRecord rec) + { + Metadata = rec.Canvas; + var types = new char[rec.Blocks.Count]; + for (int i = 0; i < types.Length; i++) + { + var type = rec.Blocks[i] switch + { + UInkInk => UInkBlockType.Ink, UInkShape => UInkBlockType.Shape, + UInkMedia => UInkBlockType.Media, UInkClear => UInkBlockType.Clear, + _ => throw new InvalidDataException() + }; + types[i] = type.ToString()[0]; + Counts[type] = Counts.GetValueOrDefault(type) + 1; + } + Types = new string(types); + } + } + } + + internal static class UInkReaderTests + { + internal static bool IsRequested(string[] args) => UInkSuites.IsRequested(args) || args.Contains("--uink-reader"); + + internal static int Dispatch(string[] args) + { + string dir = Path.Combine(AppContext.BaseDirectory, "TestData", "UInk", "v11"); + var prior = new List(); + bool reader = false; + for (int i = 0; i < args.Length; i++) + { + if (args[i] == "--uink-reader") + { + reader = true; + if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal)) dir = args[++i]; + continue; + } + if (args[i] == "--uink-fixtures" && i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal)) + dir = args[i + 1]; + prior.Add(args[i]); + } + return UInkSuites.Run(prior.ToArray(), () => + { + int code = 0; + bool all = prior.Contains("--uink-all"); + if (reader || all) code |= Fixtures(dir); + if (all || prior.Contains("--uink-robust")) code |= UInkCodecCases.Run(); + if (all || prior.Contains("--uink-roundtrip")) code |= UInkTransactionTests.Run(); + return code; + }); + } + + private readonly record struct Canvas(int Page, uint Index, string Blocks, uint Layer = 0, int Ws = 0, int Device = 0); + private static int Fixtures(string dir) + { + var suite = new UInkSuite("reader"); + void Check(string name, int fileId, Canvas[] expected, int skipped = 0, int unknown = 0, + int superseded = 0, ushort version = 11, long? tail = null, long? corrupt = null, Action more = null) + { + suite.Test(name, c => + { + var s = UInkTestApi.ReadStructure(Path.Combine(dir, name + ".uink")); + var r = s; + c.Equal(tail.HasValue || corrupt.HasValue ? UInkReadStatus.Recovered : UInkReadStatus.Ok, r.Status, "status"); + c.Equal(version, r.Version, "version"); + c.Equal(tail.HasValue, r.TruncatedTail, "truncated"); + c.Equal(corrupt.HasValue, r.StoppedOnCorruption, "corrupt"); + if (tail.HasValue || corrupt.HasValue) c.Equal(tail ?? corrupt, r.FailureOffset, "first incomplete frame"); + c.Equal(skipped, r.SkippedBlocks, "skipped"); + c.Equal(unknown, r.UnknownBlocks, "unknown"); + c.Equal(superseded, s.Superseded, "superseded"); + if (skipped != 0 || tail.HasValue || corrupt.HasValue) c.That(r.RequiresSaveAs, "requires Save As"); + c.Equal(expected.Length, s.Canvases.Count, "winning Canvas count"); + for (int i = 0; i < Math.Min(expected.Length, s.Canvases.Count); i++) + { + var e = expected[i]; + var a = s.Canvases[i]; + string Id(string prefix, int n) => n == 0 ? "" : $"{prefix}-{fileId:x4}-4000-8000-{n:x12}"; + c.Equal((Id("aaaaaaaa", e.Ws), Id("dddddddd", e.Device), Id("cccccccc", e.Page), e.Layer), a.Key, $"Canvas {i} key"); + c.Equal(e.Index, a.Metadata.PageIndex, $"Canvas {i} pageIndex"); + c.Equal(e.Blocks, a.Types, $"Canvas {i} content stream"); + c.Equal(e.Blocks.Count(b => b == 'C'), a.ClearCount, $"Canvas {i} Clear count"); + } + more?.Invoke(c, s); + }); + } + + // 来自 fixtures.json.objects 的固定期望;不使用被测解码器生成标准答案。 + Check("core-pages", 1, new Canvas[] { new(1, 0, "III"), new(2, 1, "SSSSSSS"), new(3, 2, "") }); + Check("core-page-append", 2, new Canvas[] { new(10, 0, "I", 0, 1, 1), new(12, 2, "I", 0, 1, 1), + new(11, 2, "IIS", 0, 1, 1) }, superseded: 2, more: (c, s) => c.Equal(3u, s.Canvases[2].Metadata.PageNumber, "B″")); + Check("basic-appearance", 3, new Canvas[] { new(1, 0, "IIIISSSSSS", 0, 1, 1) }, + more: (c, s) => + { + c.Equal(1, s.Canvases[0].Metadata.Background?.Pattern, "dots"); + var blocks = s.Read.Document.Canvases[0].Blocks; + var highlighter = (UInkInk)blocks[1]; + c.Equal(1, highlighter.Nib.Shape, "rectangular nib"); + c.Equal(0.125f, highlighter.Nib.Aspect, "nib aspect"); + c.Equal(null, highlighter.Cap, "rectangle ignores cap"); + c.Equal(2, ((UInkInk)blocks[3]).Cap, "butt cap"); + c.Equal(24, ((UInkRectGeometry)((UInkShape)blocks[8]).Geometry).CornerRadiusX, "corner X"); + }); + Check("standard-ppt", 4, new Canvas[] { new(1, 0, "I", 0, 1, 1), new(2, 1, "IS", 0, 1, 1), + new(3, 2, "I", 0, 1, 1), new(4, 3, "I", 0, 1, 1), new(5, 4, "I", 0, 1, 1) }, more: (c, s) => + { + c.Equal(257, s.Canvases[1].Metadata.SlideId, "SlideID"); + c.Equal(1, s.Canvases[2].Metadata.Binding, "index binding"); + c.Equal(1, s.Canvases[3].Metadata.PageState, "retained"); + c.Equal(1, s.Canvases[4].Metadata.PageKind, "end screen"); + }); + Check("standard-media", 5, new Canvas[] { new(1, 0, "MMMMIMMM", 0, 1, 1) }, + more: (c, s) => + { + c.Near(1.5, s.Canvases[0].Metadata.Viewport?.Scale, "zoom"); + var m = (UInkMedia)s.Read.Document.Canvases[0].Blocks[2]; + c.Equal(16f, m.Crop.Width, "crop width"); + c.Equal(0, m.Fit, "fit"); + c.Floats(new float[] { 0, 1, -1, 0, 880, 100 }, m.Transform, "media transform"); + }); + suite.Test("standard-media.uink.extra", c => + { + using var zip = new UInkExtraArchive(Path.Combine(dir, "standard-media.uink.extra")); + c.Equal(4, zip.EntryCount, "ZIP entries"); + foreach (string path in new[] { "audio/chime.wav", "documents/handout.pdf", "images/badge.svg", "images/quadrants.png" }) + c.That(zip.Contains(path), path); + c.That(!zip.Contains("images/missing.png"), "missing reference"); + }); + Check("standard-shape-object", 6, new Canvas[] { new(1, 0, new string('S', 16) + "I") }); + Check("full-layers-devices", 7, new Canvas[] { new(1, 0, "I", 0, 1, 1), new(1, 0, "S", 1, 1, 1), + new(1, 0, "I", 0, 1, 2), new(2, 0, "I", 0, 2, 3) }); + Check("full-hdr-advanced", 8, new Canvas[] { new(1, 0, "IIISIS") }, more: (c, s) => + { + var blocks = s.Read.Document.Canvases[0].Blocks; + var anchors = ((UInkInk)blocks[1]).StyleAnchors; + c.Equal(2, anchors.Count, "sparse style anchors"); + c.Equal(14037892u, anchors[1].Color.Fallback, "last anchor color"); + c.Near(0.3, anchors[1].Opacity, "last anchor opacity"); + c.Equal(130, ((UInkInk)blocks[2]).Texture, "unknown texture retained"); + }); + Check("full-shape-preset", 9, new Canvas[] { new(1, 0, new string('S', 16)) }); + Check("inkeys-erase-clear", 10, new Canvas[] { new(1, 0, "ISICIIII") }); + Check("compat-v10", 11, new Canvas[] { new(1, 0, "II"), new(2, 1, "SS") }, version: 10); + Check("fallback-unknown", 12, new Canvas[] { new(1, 0, "ISSMI", 0, 1, 1) }, skipped: 2, unknown: 1, + more: (c, s) => + { + c.Equal(0, s.Canvases[0].Metadata.Background?.Pattern, "unknown pattern"); + var blocks = s.Read.Document.Canvases[0].Blocks; + c.Equal(0, ((UInkShape)blocks[1]).Stroke.EndMarker, "unknown marker"); + c.Equal(0, ((UInkShape)blocks[2]).Fill.FillType, "unknown fill"); + c.Equal(0, ((UInkMedia)blocks[3]).Fit, "unknown fit"); + }); + Check("truncated-tail", 13, new Canvas[] { new(1, 0, "II") }, tail: 553); + Check("corrupt-middle", 14, new Canvas[] { new(1, 0, "I") }, corrupt: 371); + Check("future-minor", 15, new Canvas[] { new(1, 0, "ISI") }, skipped: 1, unknown: 1, version: 12); + Check("core-shape-curves", 0x16, new Canvas[] { new(1, 0, "SSSSS") }); + return suite.Finish(); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkReplayAndSaveTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkReplayAndSaveTests.cs new file mode 100644 index 000000000..1070816ac --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkReplayAndSaveTests.cs @@ -0,0 +1,344 @@ +using Ink_Canvas; +using Ink_Canvas.Helpers; +using Ink_Canvas.Controls; +using Ink_Canvas.UInk; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using WpfInkCanvas = System.Windows.Controls.InkCanvas; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkReplayAndSaveTests + { + internal static void Register(UInkSuite suite) + { + UInkLegacyReplayTests.Register(suite); + suite.Test(nameof(OverlappingReplacements), OverlappingReplacements); + suite.Test(nameof(ReinsertAndIgnoreAbsentEdits), ReinsertAndIgnoreAbsentEdits); + suite.Test(nameof(RandomHistoriesMatchCanvas), RandomHistoriesMatchCanvas); + suite.Test(nameof(LegacyExportWithoutVisiting), LegacyExportWithoutVisiting); + suite.Test(nameof(DrainAndCoalesce), DrainAndCoalesce); + suite.Test(nameof(OpenedSourceIsPreserved), OpenedSourceIsPreserved); + suite.Test(nameof(PdfCompletionChecksOwnership), PdfCompletionChecksOwnership); + suite.Test(nameof(RecognitionInheritsPenKind), RecognitionInheritsPenKind); + } + + // 与现有手势测试相同,绕过 MainWindow 构造,仅给实际回放方法传入未显示的画布。 + private static MainWindow HeadlessWindow() => (MainWindow)FormatterServices.GetUninitializedObject(typeof(MainWindow)); + + private static Stroke Dot(int x) => new(new StylusPointCollection { new StylusPoint(x, 10) }); + private static StrokeCollection Batch(params Stroke[] strokes) => new(strokes); + + private static void OverlappingReplacements(UInkChecks c) + { + var s = Dot(1); + var r = Dot(2); + var t = Dot(3); + var machine = new TimeMachine(); + machine.CommitStrokeUserInputHistory(Batch(s)); + machine.CommitStrokeEraseHistory(Batch(s, r), Batch(r, t)); + var history = machine.GetAppliedHistorySnapshot(); + var page = new UInkPageInput(); + var canvas = new WpfInkCanvas(); + MainWindow.CaptureUInkPage(page, history, null, null); + var window = HeadlessWindow(); + foreach (var entry in history) window.ApplyHistoryToCanvas(entry, canvas, true); + c.That(canvas.Strokes.SequenceEqual(new[] { t }), "S → R → T leaves only T on canvas"); + c.That(page.Strokes.Select(x => x.StylusPoints[0].X).SequenceEqual(new[] { 3d }) && + page.StrokeOwners.SequenceEqual(new[] { 1 }), "only T belongs to the eraser group"); + + // 撤销识别恰好相反,先删生成内容再恢复源;两个集合中相同的引用必须存活。 + var undoShape = new TimeMachineHistory(Batch(t, r), TimeMachineHistoryType.ShapeRecognition, true, Batch(r, s)); + var undone = history.Concat(new[] { undoShape }).ToArray(); + c.That(new UInkHistorySnapshot(undone).Visible().SequenceEqual(new[] { r, s }), + "undone recognition restores shared member at its new position"); + window.ApplyHistoryToCanvas(undoShape, canvas, true); + c.That(canvas.Strokes.SequenceEqual(new[] { r, s }), "undone recognition canvas order"); + } + + private static void ReinsertAndIgnoreAbsentEdits(UInkChecks c) + { + var e = new Image(); + var other = new Image(); + var stroke = Dot(4); + var machine = new TimeMachine(); + machine.CommitElementInsertHistory(e); + machine.CommitElementRemoveHistory(e); + machine.CommitElementInsertHistory(other); + machine.CommitStrokeManipulationHistory(null, null, new() { [other] = + Tuple.Create(Transform.Identity, new TranslateTransform(7, 8)) }); + machine.CommitStrokeManipulationHistory(new() { [stroke] = Tuple.Create(stroke.StylusPoints, Dot(99).StylusPoints) }, + new() { [stroke] = Tuple.Create(stroke.DrawingAttributes, new DrawingAttributes { Width = 12 }) }, + new() { [e] = Tuple.Create(Transform.Identity, new TranslateTransform(30, 40)) }); + machine.CommitElementInsertHistory(e); + machine.CommitStrokeUserInputHistory(Batch(stroke)); + var history = machine.GetAppliedHistorySnapshot(); + var page = new UInkPageInput(); + MainWindow.CaptureUInkPage(page, history, null, null); + c.That(page.Elements.Select(x => x.Owner).SequenceEqual(new[] { 2, 5 }), "last insert moves E to end"); + c.Near(7, page.Elements[0].Transform.OffsetX, "present element uses its recorded transform"); + c.Equal(Matrix.Identity, page.Elements[1].Transform, "absent element ignores transform"); + c.Near(4, page.Strokes[0].StylusPoints[0].X, "absent stroke ignores points"); + c.Near(stroke.DrawingAttributes.Width, page.Strokes[0].DrawingAttributes.Width, "absent stroke ignores DA"); + var canvas = new WpfInkCanvas(); + MainWindow.InstallPageHistory(history, canvas); + c.That(canvas.Children.Cast().SequenceEqual(new UIElement[] { other, e }), + "page switch restores same reinserted element at the end"); + c.Equal(Matrix.Identity, e.RenderTransform.Value, "page switch ignores absent transform"); + c.Near(8, other.RenderTransform.Value.OffsetY, "page switch applies present transform"); + + var removed = new UInkGroupHistory(Batch(stroke, Dot(99)), 2) { StrokeHasBeenCleared = true }; + removed.Elements[0] = other; + removed.Elements[1] = new Image(); + var reinsert = new TimeMachineHistory(other, TimeMachineHistoryType.ElementInsert); + var after = new UInkHistorySnapshot(history.Concat(new TimeMachineHistory[] { removed, reinsert }).ToArray()); + c.That(!after.Visible().Any() && after.Visible().SequenceEqual(new UIElement[] { e, other }), + "cleared imported group removes present members only, later insert wins"); + c.Equal(history.Length + 1, after.Owner(other), "reinserted media belongs to last insertion"); + } + + private static void RandomHistoriesMatchCanvas(UInkChecks c) + { + var random = new Random(110327); + var window = HeadlessWindow(); + for (int sample = 0; sample < 600; sample++) + { + var pool = Enumerable.Range(1, 8).Select(Dot).ToArray(); + var elements = Enumerable.Range(0, 4).Select(_ => new Image()).ToArray(); + var entries = new List(); + Stroke Pick() => pool[random.Next(pool.Length)]; + for (int step = 0; step < 30; step++) + { + var a = Pick(); + var b = Pick(); + var e = elements[random.Next(elements.Length)]; + var kind = step < 7 ? step : random.Next(7); + var da = Tuple.Create(new DrawingAttributes { Width = 1 + step }, + new DrawingAttributes { Height = 2 + step, Color = Colors.Red }); + TimeMachineHistory entry; + switch (kind) + { + case 0: + entry = new TimeMachineHistory(Batch(a), TimeMachineHistoryType.UserInput, false); + break; + case 1: + case 2: + entry = new TimeMachineHistory(Batch(a), kind == 1 ? TimeMachineHistoryType.ShapeRecognition : + TimeMachineHistoryType.Clear, false, Batch(b)); + break; + case 3: + var changed = new StylusPointCollection { new StylusPoint(step, sample, 0.3f), new StylusPoint(step + 1, 5) }; + entry = new TimeMachineHistory(new Dictionary> + { [a] = Tuple.Create(a.StylusPoints, changed) }, TimeMachineHistoryType.Manipulation) + { + DrawingAttributes = new() { [b] = da }, + ElementTransforms = new() { [e] = Tuple.Create( + new TranslateTransform(step, 1), new TranslateTransform(1, sample)) } + }; + break; + case 4: + entry = new TimeMachineHistory(new Dictionary> + { [a] = da }, TimeMachineHistoryType.DrawingAttributes); + break; + case 5: + entry = new TimeMachineHistory(e, TimeMachineHistoryType.ElementInsert); + break; + default: + var group = new UInkGroupHistory(a == b ? Batch(a) : Batch(a, b), 2); + group.Elements[0] = e; // 第二槽模拟缺失资源 + entry = group; + break; + } + entry.StrokeHasBeenCleared = random.Next(2) == 0; + entries.Add(entry); + } + + var machine = new TimeMachine(); + var all = entries.ToArray(); + machine.ImportTimeMachineHistory(all); + int tail = 1 + random.Next(6); + for (int i = 0; i < tail; i++) machine.Undo(); + // 交替覆盖游标前的保存视图,以及包含已翻转尾项的整页回放。 + var history = sample % 2 == 0 ? all : machine.GetAppliedHistorySnapshot(); + var snapshot = new UInkHistorySnapshot(history); + var copies = new UInkPageInput(); + snapshot.CaptureStrokes(copies, null); + var children = snapshot.Visible().ToArray(); + var transforms = children.Select(e => + (snapshot.ElementTransforms.GetValueOrDefault(e) ?? e.RenderTransform).Value).ToArray(); + var canvas = new WpfInkCanvas(); + foreach (var entry in history) window.ApplyHistoryToCanvas(entry, canvas, true); + string label = $"seed 110327, sample {sample}"; + c.That(canvas.Strokes.SequenceEqual(snapshot.Visible()), label + " stroke identity/order"); + c.Equal(canvas.Strokes.Count, copies.Strokes.Count, label + " copied count"); + for (int i = 0; i < canvas.Strokes.Count; i++) + { + c.That(canvas.Strokes[i].StylusPoints.SequenceEqual(copies.Strokes[i].StylusPoints), label + " all points"); + c.That(canvas.Strokes[i].DrawingAttributes.Equals(copies.Strokes[i].DrawingAttributes), label + " final DA"); + } + c.That(canvas.Children.Cast().SequenceEqual(children), label + " element identity/order"); + c.That(canvas.Children.Cast().Select(e => e.RenderTransform.Value).SequenceEqual(transforms), + label + " final transforms"); + if (c.Failures.Count != 0) return; + } + } + + private static byte[] TwoPageBoard() + { + using var stream = new MemoryStream(); + var encoder = new UInkTestEncoder(stream); + encoder.Header(11, 2); + encoder.HeaderExtension(); + for (uint i = 0; i < 2; i++) + { + encoder.Canvas(i, whiteboard: true); + encoder.Ink(0, 0, 0x112233, new[] { new UInkTestPoint(10 + i, 20, 4) }); + } + return stream.ToArray(); + } + + private static void LegacyExportWithoutVisiting(UInkChecks c) + { + var index = UInkIccMapper.BuildPageIndex(UInkReader.Read(TwoPageBoard(), + new UInkReadOptions { MaterializeContent = false }), 1, 1); + var second = index.Pages[1]; + var window = HeadlessWindow(); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + var type = typeof(MainWindow); + var canvas = new WpfInkCanvas(); + var slots = new TimeMachineHistory[101][]; + type.GetField("inkCanvas", fields).SetValue(window, canvas); + type.GetField("TimeMachineHistories", fields).SetValue(window, slots); + var board = type.GetField("_uinkBoard", fields); + board.SetValue(window, Array.CreateInstance(board.FieldType.GetElementType(), slots.Length)); + type.GetField("_uinkWorkspaceIds", fields).SetValue(window, new string[3]); + type.GetField("_currentMode", fields).SetValue(window, 1); + type.GetField("_currentWhiteboardIndex", fields).SetValue(window, 1); + type.GetField("_whiteboardTotalCount", fields).SetValue(window, 2); + window.IndexUInkWhiteboard(index, 2); + c.That(!second.IsMaterialized && slots[2].Length == 0, "second page starts with a pending slot"); + c.That(window.HasSavableDocumentContent(), "timed trigger sees unvisited ink with empty live page"); + canvas.Strokes.Add(Dot(42)); + var exported = window.CollectLegacyWhiteboardStrokes(); + c.Near(42, exported[0][0].StylusPoints[0].X, "current page uses live strokes"); + c.Equal(1, exported[1].Count, "legacy exporter keeps unvisited page"); + c.Near(11, exported[1][0].StylusPoints[0].X, "unvisited geometry"); + c.That(!second.IsMaterialized && slots[2].Length == 0, "export leaves installation pending"); + canvas.Strokes.Clear(); + slots[2] = new[] { new TimeMachineHistory(new Image(), TimeMachineHistoryType.ElementInsert) }; + c.That(window.HasSavableDocumentContent(), "timed trigger sees media-only history"); + slots[2] = Array.Empty(); + c.That(!window.HasSavableDocumentContent(), "empty document after clearing media"); + } + + private static void DrainAndCoalesce(UInkChecks c) + { + var queue = new UInkSaveQueue(); + using var release = new ManualResetEventSlim(); + using var started = new ManualResetEventSlim(); + var written = new List(); + var a = new object(); + var b = new object(); + var first = queue.Enqueue(a, "a.uink", false, () => + { + started.Set(); + if (!release.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException(); + written.Add(0); + }, null); + c.That(started.Wait(TimeSpan.FromSeconds(5)), "worker started without a dispatcher pump"); + int released = 0; + Task Add(object doc, string path, bool timed, int id) => queue.Enqueue(doc, path, timed, + () => written.Add(id), () => Interlocked.Increment(ref released)); + var accepted = new[] { first, Add(a, "a.uink", true, 1), Add(b, "a.uink", true, 2), + Add(a, "b.uink", true, 3), Add(a, "a.uink", false, 4), Add(a, "A.uink", true, 5), + Add(a, "a.uink", false, 6) }; + var drain = queue.DrainAsync(); + c.That(!drain.IsCompleted && released == 2, "accepted writes pending, only superseded snapshot released"); + release.Set(); + c.That(drain.Wait(TimeSpan.FromSeconds(5)), "drains while caller thread is blocked"); + c.That(accepted.All(t => t.IsCompletedSuccessfully), "all accepted requests resolved"); + c.That(written.SequenceEqual(new[] { 0, 2, 4, 5, 6 }), "FIFO across documents, targets and manual saves"); + c.Equal(6, released, "every queued snapshot released exactly once"); + } + + private static void OpenedSourceIsPreserved(UInkChecks c) + { + var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).FullName; + try + { + string original = Path.Combine(dir, "fixed.uink"); + var bytes = TwoPageBoard(); + File.WriteAllBytes(original, bytes); + var projection = UInkIccMapper.BuildPageIndex(UInkReader.Read(original), 1, 1); + var session = new MainWindow.UInkSession(original, projection); + var ctx = new UInkCaptureContext { Workspace = projection.Workspace, DpiX = 1, DpiY = 1 }; + ctx.Pages.Add(new UInkPageInput { Canvas = projection.Pages[0].Canvas, Strokes = Batch(Dot(88)) }); + var occupied = Path.Combine(dir, "fixed (1).uink.extra"); + File.WriteAllBytes(occupied, bytes); + string alias = Path.Combine(dir, ".", "FIXED.uink"); + string copy = session.Save(ctx, alias, false); + c.That(string.Equals(Path.Combine(dir, "fixed (2).uink"), copy, StringComparison.OrdinalIgnoreCase), + "external source and occupied companion require a new target"); + projection.ReadResult.Note("whiteboardCapacity"); + c.That(session.Projection.RequiresSaveAs, "session retains late degradation"); + string next = session.Save(ctx, alias, false); + c.That(string.Equals(Path.Combine(dir, "fixed (3).uink"), next, StringComparison.OrdinalIgnoreCase), + "degraded save skips the earlier copy"); + c.That(File.ReadAllBytes(original).SequenceEqual(bytes) && File.ReadAllBytes(occupied).SequenceEqual(bytes), + "source bytes and pre-existing companion untouched"); + c.Equal(1, UInkReader.Read(next).Document.Canvases.Count, "new path contains saved snapshot"); + } + finally { Directory.Delete(dir, true); } + } + + private static void PdfCompletionChecksOwnership(UInkChecks c) + { + var window = HeadlessWindow(); + var canvas = new WpfInkCanvas(); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + typeof(MainWindow).GetField("inkCanvas", fields).SetValue(window, canvas); + typeof(MainWindow).GetField("frozenPages", fields).SetValue(window, new bool[101]); + // 与文件关联共用真正的单文件入口;新请求读取失败,原文档的 PDF 回调仍能完成。 + try { window.OpenSingleStrokeFile(Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".icstk")); } + catch (FileNotFoundException) { } + var stale = new PdfEmbeddedView(); + canvas.Children.Add(stale); + window.CompleteRestoredPdf(stale, -1); + c.That(stale.CaptureStrokes == null, "stale generation cannot wire callbacks even on canvas"); + var returning = new PdfEmbeddedView(); + window.CompleteRestoredPdf(returning, 0); + c.That(returning.CaptureStrokes == null, "detached page cannot bind main canvas"); + canvas.Children.Add(returning); + returning.RaiseEvent(new RoutedEventArgs(FrameworkElement.LoadedEvent)); + c.That(returning.CaptureStrokes != null, "same-generation page can finish on return"); + } + + private static void RecognitionInheritsPenKind(UInkChecks c) + { + var source = Dot(1); + source.DrawingAttributes.StylusTip = StylusTip.Rectangle; + var machine = new TimeMachine(); + var pen = Dot(3); + MainWindow.CommitDrawnShape(machine, Batch(source, pen)); + c.Equal(1, machine.GetAppliedHistorySnapshot().Length, "one final shape batch"); + c.Equal((int)UInkInkType.Pen, (int)pen.GetPropertyData(UInkConversion.LogicalPenKindGuid), "normal part"); + c.Equal((int)UInkInkType.Highlighter, (int)source.GetPropertyData(UInkConversion.LogicalPenKindGuid), + "rectangular overdraw highlighter retains creating style"); + var replacement = Dot(2); + MainWindow.InheritRecognitionPenKind(source, replacement); + c.Equal((int)UInkInkType.Highlighter, UInkConversion.StrokeToInk(replacement).InkType, + "non-WPF-highlighter source keeps its logical kind after replacement"); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkReviewFixTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkReviewFixTests.cs new file mode 100644 index 000000000..6de705f73 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkReviewFixTests.cs @@ -0,0 +1,321 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using Ink_Canvas; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkReviewFixTests + { + internal static void Register(UInkSuite suite) + { + suite.Test(nameof(UndoThenSaveWhiteboard), UndoThenSaveWhiteboard); + suite.Test(nameof(Replay5000Groups), Replay5000Groups); + suite.Test(nameof(ReplayKeepsOrderAndEdits), ReplayKeepsOrderAndEdits); + suite.Test(nameof(PptBindingWithNoResolver), PptBindingWithNoResolver); + suite.Test(nameof(HighlighterOpacityOnWire), HighlighterOpacityOnWire); + suite.Test(nameof(PressureBasisAtWpfLimit), PressureBasisAtWpfLimit); + suite.Test(nameof(CoordinateRangeDiagnostics), CoordinateRangeDiagnostics); + suite.Test(nameof(FirstReferencesBeforeReplacement), FirstReferencesBeforeReplacement); + suite.Test(nameof(PhysicalGroupsSurviveBadFrames), PhysicalGroupsSurviveBadFrames); + } + + private static void UndoThenSaveWhiteboard(UInkChecks c) + { + using var input = new MemoryStream(); + var encoder = new UInkTestEncoder(input); + encoder.Header(11, 2); + encoder.HeaderExtension(); + encoder.Canvas(0, whiteboard: true); + encoder.Ink(0, 0, 0x112233, new[] { new UInkTestPoint(10, 20, 4) }); + encoder.Canvas(1, whiteboard: true); + encoder.Ink(0, 0, 0x223344, new[] { new UInkTestPoint(30, 40, 5) }); + + var projection = UInkIccMapper.BuildPageIndex(UInkReader.Read(input.ToArray()), 1, 1); + c.Equal((int)UInkWorkspaceType.Whiteboard, projection.Workspace.WorkspaceType, "imported whiteboard"); + c.Equal(2, projection.Pages.Count, "two pages imported"); + int current = projection.CurrentPageDisplayIndex; + var currentPage = projection.Pages[current]; + var pageSlot = currentPage.History; + var machine = new TimeMachine(); + machine.ImportTimeMachineHistory(pageSlot); + c.That(ReferenceEquals(pageSlot[0], machine.Undo()), "undo marks the shared page-slot group"); + c.That(pageSlot[0].StrokeHasBeenCleared && machine.CanRedo, "original undo granularity"); + + var live = new StrokeCollection(); + MainWindow.InstallReplayedStrokes(pageSlot, live); + c.Equal(0, live.Count, "rebuilding an undone insert from empty succeeds"); + var pages = new List(); + foreach (var page in projection.Pages) + { + page.EnsureMaterialized(); + pages.Add(new UInkPageInput + { + Canvas = page.Canvas, + Strokes = MainWindow.SnapshotWhiteboardPageStrokes(page.DisplayIndex + 1, current + 1, live, page.History), + }); + } + var saved = UInkIccMapper.BuildDocument(UInkTestEncoder.HeaderGuid, null, new[] { projection.Workspace }, pages, 0); + var reopened = UInkIccMapper.BuildPageIndex(UInkReader.Read(Write(saved)), 1, 1); + c.Equal(2, reopened.Pages.Count, "saved whiteboard still has both pages"); + c.Equal(0, reopened.Pages[0].FinalStrokes.Count, "immediate save preserves the undone blank page"); + reopened.Pages[1].EnsureMaterialized(); + c.Equal(1, reopened.Pages[1].FinalStrokes.Count, "other page was replayed for save"); + c.Near(30, reopened.Pages[1].FinalStrokes[0].StylusPoints[0].X, "other page's original stroke"); + + machine.Redo(); + c.Equal(0, MainWindow.SnapshotWhiteboardPageStrokes(1, 1, live, pageSlot).Count, + "nonempty stale slot cannot revive a blank live page"); + var newLive = new StrokeCollection { PointStroke(99) }; + c.Near(99, MainWindow.SnapshotWhiteboardPageStrokes(1, 1, newLive, pageSlot)[0].StylusPoints[0].X, + "live edits win over a stale slot"); + } + + private static void Replay5000Groups(UInkChecks c) + { + const int count = 5000; + var history = new TimeMachineHistory[count]; + for (int i = 0; i < history.Length; i++) + history[i] = new UInkGroupHistory(new StrokeCollection { PointStroke(i) }, 0); + var target = new StrokeCollection(); + int events = 0, added = 0; + target.StrokesChanged += (_, args) => + { + events++; + added += args.Added.Count; + }; + + var watch = Stopwatch.StartNew(); + MainWindow.InstallReplayedStrokes(history, target); + watch.Stop(); + + c.That(watch.ElapsedMilliseconds < 1000, $"5,000 groups replayed in {watch.Elapsed.TotalMilliseconds:F1} ms"); + c.Equal(1, events, "single WPF Add event"); + c.Equal(count, added, "entire batch installed"); + c.Equal(count, target.Count, "visible stroke count"); + for (int i = 0; i < target.Count; i++) + c.That(ReferenceEquals(history[i].CurrentStroke[0], target[i]), $"reference/order at {i}"); + } + + private static void ReplayKeepsOrderAndEdits(UInkChecks c) + { + var first = PointStroke(10); + var second = PointStroke(20); + var firstSet = new StrokeCollection { first }; + var secondSet = new StrokeCollection { second }; + var survivor = PointStroke(25); + var changed = new StylusPointCollection { new StylusPoint(30, 40, 0.6f) }; + var attributes = new DrawingAttributes { Width = 8, Height = 8 }; + var history = new TimeMachineHistory[] + { + new UInkGroupHistory(firstSet, 0), + new UInkGroupHistory(secondSet, 0), + new UInkGroupHistory(new StrokeCollection { survivor }, 0), + new UInkGroupHistory(secondSet, 0) { StrokeHasBeenCleared = true }, + new TimeMachineHistory(null, TimeMachineHistoryType.Clear, false, firstSet), + new TimeMachineHistory(firstSet, TimeMachineHistoryType.UserInput, false), + new TimeMachineHistory(new Dictionary> + { [first] = Tuple.Create(first.StylusPoints, changed) }, TimeMachineHistoryType.Manipulation), + new TimeMachineHistory(new Dictionary> + { [first] = Tuple.Create(first.DrawingAttributes, attributes) }, TimeMachineHistoryType.DrawingAttributes), + }; + + var rebuilt = new StrokeCollection(); + MainWindow.InstallReplayedStrokes(history, rebuilt); + c.That(!rebuilt.Contains(second), "cleared group removes its still-present stroke"); + c.Equal(2, rebuilt.Count, "untouched and reinserted strokes survive"); + c.That(ReferenceEquals(survivor, rebuilt[0]) && ReferenceEquals(first, rebuilt[1]), "reinsertion moves to end"); + c.Near(30, rebuilt[1].StylusPoints[0].X, "manipulation replay"); + c.Near(8, rebuilt[1].DrawingAttributes.Width, "drawing attributes replay"); + } + + private static void PptBindingWithNoResolver(UInkChecks c) + { + var workspace = new UInkWorkspace { Guid = UInkTestEncoder.WorkspaceGuid, WorkspaceType = (int)UInkWorkspaceType.Presentation }; + var unbound = UInkIccMapper.BuildPptCanvas(workspace.Guid, "", UInkTestEncoder.PageGuid(0), 0, 256); + var byIndex = UInkIccMapper.BuildPptCanvas(workspace.Guid, "", UInkTestEncoder.PageGuid(1), 1, null); + var invalidId = UInkIccMapper.BuildPptCanvas(workspace.Guid, "", UInkTestEncoder.PageGuid(2), 2, 0); + var doc = UInkIccMapper.BuildDocument(UInkTestEncoder.HeaderGuid, null, new[] { workspace }, new[] + { + new UInkPageInput { Canvas = unbound, Strokes = new StrokeCollection { PointStroke(10) } }, + new UInkPageInput { Canvas = byIndex, Strokes = new StrokeCollection { PointStroke(20) } }, + new UInkPageInput { Canvas = invalidId, Strokes = new StrokeCollection { PointStroke(30) } }, + }, 0); + var read = UInkReader.Read(Write(doc)); + c.Equal(1, read.Document.Canvases[1].Canvas.Binding, "CANVAS-13 explicit page-index binding on wire"); + c.Equal(1, read.Document.Canvases[2].Canvas.Binding, "invalid SlideID falls back to page index"); + c.Equal(null, read.Document.Canvases[2].Canvas.SlideId, "invalid SlideID omitted"); + var pages = UInkIccMapper.BuildPageIndex(read, 1, 1).Pages; + c.That(pages[0].IsUnbound && pages[0].SlideIndex == null, "SlideID page has no fallback attachment"); + c.Equal(256, pages[0].SlideId, "original SlideID preserved"); + c.Equal(2, pages[1].SlideIndex, "explicit page-index binding restored"); + c.Equal(3, pages[2].SlideIndex, "other explicit page-index binding restored"); + var targets = MainWindow.SelectPptRestorePages(pages, 3, out int keptUnbound); + c.Equal(1, keptUnbound, "PPT notification unbound count"); + c.Equal(2, targets.Count, "PPT notification restore target count"); + c.That(ReferenceEquals(pages[1], targets[0]) && ReferenceEquals(pages[2], targets[1]), + "production restore targets exclude the unresolved SlideID"); + targets = MainWindow.SelectPptRestorePages(pages, 2, out keptUnbound); + c.Equal(2, keptUnbound, "out-of-range index also has no restore target"); + c.Equal(1, targets.Count, "only existing slides can be restored"); + } + + private static void HighlighterOpacityOnWire(UInkChecks c) + { + var legacy = PointStroke(10); + legacy.DrawingAttributes.Color = Colors.Gold; + legacy.DrawingAttributes.IsHighlighter = true; + var (_, bytes) = UInkTestApi.SaveStrokesAndReload(new StrokeCollection { legacy }, 1); + c.Near(0.5, UInkWireInspection.Read(bytes, c).Find(b => b.Type == 3).Opacity, "opaque legacy DA exports 0.5", 1e-7); + + var canvas = UInkIccMapper.BuildCanvas("", "", UInkTestEncoder.PageGuid(0), 0, 1, null, null); + var record = new UInkCanvasRecord { Canvas = canvas }; + record.Blocks.Add(new UInkInk + { + InkType = (int)UInkInkType.Highlighter, Opacity = 0.25f, + Color = new UInkColor { Fallback = 0xffdd00 }, Points = new[] { new UInkPoint(5, 6, 8) } + }); + var foreign = new UInkDocument + { Header = new UInkHeader { Guid = UInkTestEncoder.HeaderGuid }, Canvases = new() { record } }; + var strokes = UInkIccMapper.BuildPageIndex(UInkReader.Read(Write(foreign)), 1, 1).Pages[0].FinalStrokes; + c.That(strokes[0].DrawingAttributes.IsHighlighter, "import uses existing WPF highlighter rendering"); + c.Equal((byte)64, strokes[0].DrawingAttributes.Color.A, "DA alpha remains quantized"); + var (_, resaved) = UInkTestApi.SaveStrokesAndReload(strokes.Clone(), 1); + c.Near(0.25, UInkWireInspection.Read(resaved, c).Find(b => b.Type == 3).Opacity, + "imported opacity survives cloning and re-save", 1e-7); + } + + private static void PressureBasisAtWpfLimit(UInkChecks c) + { + const float aspect = 4e-6f; + var narrow = new UInkInk + { + InkType = (int)UInkInkType.Pen, Points = new[] { new UInkPoint(10, 10, 2.5f), new UInkPoint(5, 0, 10) }, + Nib = new UInkNib { Shape = 1, Aspect = aspect } + }; + var notes = new List(); + var stroke = UInkConversion.InkToStroke(narrow, note: notes.Add); + c.That(notes.Count == 0, "legal common DA basis needs no approximation"); + var da = stroke.DrawingAttributes; + c.Near(aspect, da.Width / da.Height, "aspect retained at DA minimum width", 1e-11); + for (int i = 0; i < stroke.StylusPoints.Count; i++) + c.Near(narrow.Points[i].Width, da.Height * (0.25 + 1.5 * stroke.StylusPoints[i].PressureFactor), + $"pressure-expressed height {i}", 1e-5); + + var extreme = new Stroke(new StylusPointCollection { new StylusPoint(10, 20, 0), new StylusPoint(25, 35, 1) }, + new DrawingAttributes { Width = 7.3, Height = 7.3 }); + var (_, bytes) = UInkTestApi.SaveStrokesAndReload(new StrokeCollection { extreme }, 1.5); + var read = UInkReader.Read(bytes); + var widths = ((UInkInk)read.Document.Canvases[0].Blocks[0]).Points; + c.That((double)widths[1].Width / widths[0].Width > 7, "fixture exercises float32 rounding at 7:1"); + var projected = UInkIccMapper.BuildPageIndex(read, 1.5, 1.5).Pages[0].FinalStrokes[0]; + c.Near(0, projected.StylusPoints[0].PressureFactor, "minimum pressure retained"); + c.Near(1, projected.StylusPoints[1].PressureFactor, "maximum pressure retained"); + c.That(!read.DiagnosticCounts.ContainsKey("widthRangeApprox") && !read.RequiresSaveAs, + "float32 round-trip is lossless for Save As policy"); + } + + private static void CoordinateRangeDiagnostics(UInkChecks c) + { + using var stream = new MemoryStream(); + var encoder = new UInkTestEncoder(stream); + encoder.Header(11, 1); + encoder.Canvas(0); + long inkOffset = stream.Position; + encoder.Ink(0, 0, 0x123456, new[] { new UInkTestPoint(80000000, 0, 4), new UInkTestPoint(100000000, 0, 4) }); + long shapeOffset = stream.Position; + encoder.Shape(1, 1, 0x234567, endX: -100000000); + encoder.Ink(2, 2, 0x345678, new[] { new UInkTestPoint(15, 25, 4) }); + + var read = UInkReader.Read(stream.ToArray(), new UInkReadOptions { MaterializeContent = false }); + var page = UInkIccMapper.BuildPageIndex(read, 1, 1).Pages[0]; + c.Equal(1, page.FinalStrokes.Count, "out-of-range Ink and Shape skipped; subsequent Ink survives"); + c.Near(15, page.FinalStrokes[0].StylusPoints[0].X, "surviving coordinate"); + c.That(read.Diagnostics.Contains($"coordinateRange @ {inkOffset}"), "located Ink rejection"); + c.That(read.Diagnostics.Contains($"coordinateRange @ {shapeOffset}"), "located Shape rejection"); + c.That(read.RequiresSaveAs, "coordinate loss requires Save As"); + } + + private static void FirstReferencesBeforeReplacement(UInkChecks c) + { + var a = UInkTestEncoder.PageGuid(80); + var b = UInkTestEncoder.PageGuid(81); + var knownDevice = UInkTestEncoder.PageGuid(90); + var point = new[] { new UInkTestPoint(10, 20, 5) }; + using var workspaceStream = new MemoryStream(); + var encoder = new UInkTestEncoder(workspaceStream); + encoder.Header(11, 2); + encoder.HeaderExtension(knownDevice); + encoder.Canvas(0, workspaceGuid: a, deviceGuid: knownDevice); + encoder.Ink(0, 0, 0, point); + encoder.Canvas(1, workspaceGuid: b, deviceGuid: knownDevice); + encoder.Canvas(0, workspaceGuid: a, deviceGuid: knownDevice); + var read = UInkReader.Read(workspaceStream.ToArray()); + c.Equal(2, read.FirstWorkspaceReference[a], "temporary A first appears at physical object 2"); + var projection = UInkIccMapper.BuildPageIndex(read, 1, 1); + c.Equal(a, projection.Workspace.Guid, "temporary A precedes B despite later replacement"); + c.Equal(b, projection.UndisplayedWorkspaces[1].Guid, "undisplayed B follows the registered workspace"); + c.Equal(0, projection.Pages[0].FinalStrokes.Count, "previous A version was replaced"); + + using var deviceStream = new MemoryStream(); + encoder = new UInkTestEncoder(deviceStream); + encoder.Header(11, 1); + encoder.HeaderExtension(knownDevice); + encoder.Canvas(0, whiteboard: true, deviceGuid: a); + encoder.Ink(0, 0, 0, point); + encoder.Canvas(0, whiteboard: true, deviceGuid: b); + encoder.Ink(0, 0, 0, point); + encoder.Canvas(0, whiteboard: true, deviceGuid: a); + read = UInkReader.Read(deviceStream.ToArray()); + c.Equal(2, read.FirstDeviceReference[a], "temporary device A first reference retained"); + projection = UInkIccMapper.BuildPageIndex(read, 1, 1); + c.Equal(a, projection.Pages[0].Canvas.DeviceGuid, "FILE-9 chooses first originally referenced device"); + c.Equal(0, projection.Pages[0].FinalStrokes.Count, "only replacement version of first device shown"); + } + + private static void PhysicalGroupsSurviveBadFrames(UInkChecks c) + { + var point = new[] { new UInkTestPoint(10, 20, 4) }; + void Check(Action badFrame, int lastOrdinal, int groups, string label) + { + using var stream = new MemoryStream(); + var encoder = new UInkTestEncoder(stream); + encoder.Header(11, 1); + encoder.Canvas(0); + encoder.Ink(0, 7, 0, point); + badFrame(encoder); + encoder.Ink(2, 7, 0, point); + var read = UInkReader.Read(stream.ToArray()); + var record = read.Document.Canvases[0]; + c.Equal(2, record.Blocks.Count, label + " valid blocks"); + c.Equal(0, ((UInkContentBlock)record.Blocks[0]).PhysicalUndoGroupOrdinal, label + " first ordinal"); + c.Equal(lastOrdinal, ((UInkContentBlock)record.Blocks[1]).PhysicalUndoGroupOrdinal, label + " last ordinal"); + var page = UInkIccMapper.BuildPageIndex(read, 1, 1).Pages[0]; + c.Equal(2, page.FinalStrokes.Count, label + " visible strokes"); + c.Equal(groups, page.History.Length, label + " undo groups"); + } + + Check(e => e.Ink(1, 8, 0, point, UInkTestInkFault.InvalidWidth), 2, 2, "readable different undoId"); + Check(e => e.InkWithUnreadableField(1, unreadableType: false), 2, 2, "unreadable undoId"); + Check(e => e.InkWithUnreadableField(1, unreadableType: true), 2, 2, "type rejected during framing"); + Check(e => e.Clear(1, 8), 2, 2, "invalid Clear stays a boundary"); + Check(e => e.Ink(1, 7, 0, point, UInkTestInkFault.InvalidWidth), 0, 1, "readable same undoId"); + } + + private static Stroke PointStroke(int x) => + new(new StylusPointCollection { new StylusPoint(x, 20, 0.5f) }); + + private static byte[] Write(UInkDocument document) + { + using var stream = new MemoryStream(); + UInkWriter.Save(document, stream); + return stream.ToArray(); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkRobustTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkRobustTests.cs new file mode 100644 index 000000000..ef93e509f --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkRobustTests.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using static InkCanvas.Calibration.Tests.UInk.UInkTestItemKind; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkRobustTests + { + private const int VariantCount = 64; + private static readonly UInkTestPoint[] Points = { new(20, 40, 4), new(90, 40, 5) }; + private const uint FirstColor = 0x2456CD, MiddleColor = 0x24623E, LastColor = 0xB52943; + + public static int Run(string directory) + { + var suite = new UInkSuite("robust"); + var inputs = Array.Empty(); + if (suite.Test("MutationInputs", c => + { + inputs = Directory.GetFiles(directory, "*.uink"); + Array.Sort(inputs, StringComparer.Ordinal); + c.That(inputs.Length > 0, "no .uink fixtures found"); + })) + foreach (string input in inputs) + suite.Test("Mutations " + Path.GetFileName(input), c => Mutations(c, input)); + + suite.Test("UnknownType7", c => BetweenInks(c, e => e.Unknown(), middleVisible: false, skipped: true, lastContentId: 1)); + suite.Test("InvalidInkField", c => BetweenInks(c, + e => e.Ink(1, 1, MiddleColor, Points, UInkTestInkFault.InvalidWidth), middleVisible: false, skipped: true)); + suite.Test("DuplicateKnownKey", c => BetweenInks(c, + e => e.Ink(1, 1, MiddleColor, Points, UInkTestInkFault.DuplicateInkType), middleVisible: false, skipped: true)); + suite.Test("HeterogeneousExtra", c => BetweenInks(c, + e => e.Ink(1, 1, MiddleColor, Points, UInkTestInkFault.HeterogeneousExtra), middleVisible: true, skipped: false)); + suite.Test("Version9Rejected", c => HeaderCase(c, 9, UInkTestEncoder.HeaderGuid, accepted: false)); + suite.Test("Version19Accepted", c => HeaderCase(c, 19, UInkTestEncoder.HeaderGuid, accepted: true)); + suite.Test("Version20Rejected", c => HeaderCase(c, 20, UInkTestEncoder.HeaderGuid, accepted: false)); + suite.Test("MalformedUuidRejected", c => HeaderCase(c, 10, "zfffffff-0000-4000-8000-000000000000", accepted: false)); + suite.Test("LastValidClear", LastValidClear); + suite.Test("MixedUndoGroup", MixedUndoGroup); + return suite.Finish(); + } + + private static void Mutations(UInkChecks c, string input) + { + byte[] bytes = File.ReadAllBytes(input); + c.That(bytes.Length > 0, "fixture is empty"); + if (bytes.Length == 0) return; + WithScratch(path => + { + if (File.Exists(input + ".extra")) File.Copy(input + ".extra", path + ".extra"); + using var loader = new DeadlineLoader(); + for (int i = 0; i < VariantCount; i++) + { + // 包含空文件,最大长度为原文件减 1,避免把未截断文件计入变体。 + int length = (int)((long)(bytes.Length - 1) * i / (VariantCount - 1)); + using (var stream = File.Create(path)) stream.Write(bytes, 0, length); + if (!loader.TryLoad(c, path, $"truncate at {length}", out _)) return; + } + + var random = new Random(0x51C6); + var visited = new HashSet(); + for (int i = 0; i < VariantCount; i++) + { + int position; + do { position = random.Next(bytes.Length); } + while (visited.Count < bytes.Length && !visited.Add(position)); + + byte mask = (byte)(1 << random.Next(8)); + bytes[position] ^= mask; + File.WriteAllBytes(path, bytes); + bytes[position] ^= mask; + if (!loader.TryLoad(c, path, $"flip at {position}, mask 0x{mask:x2}", out _)) return; + } + }); + } + + private static void BetweenInks(UInkChecks c, Action middle, bool middleVisible, bool skipped, uint lastContentId = 2) + { + Synthetic(c, 11, UInkTestEncoder.HeaderGuid, encoder => + { + encoder.Ink(0, 0, FirstColor, Points); + middle(encoder); + encoder.Ink(lastContentId, lastContentId, LastColor, Points); + }, result => + { + CheckInks(c, result, middleVisible ? new[] { FirstColor, MiddleColor, LastColor } : new[] { FirstColor, LastColor }); + c.Equal(1, result.Pages.Count, "Canvas scope survived the middle block"); + c.Equal(skipped ? 1 : 0, result.SkippedBlocks, "skipped block count"); + if (skipped) c.That(result.RequiresSaveAs, "skipped content requires Save As"); + c.That(!result.Truncated && !result.StoppedOnCorruption, "complete block must not cause stream recovery"); + }); + } + + private static void HeaderCase(UInkChecks c, ushort version, string guid, bool accepted) + { + Synthetic(c, version, guid, encoder => encoder.Ink(0, 0, FirstColor, Points), result => + { + if (accepted) + { + c.Equal(version, result.HeaderVersion, "accepted Header version"); + c.Equal(guid, result.HeaderGuid, "accepted Header GUID"); + CheckInks(c, result, new[] { FirstColor }); + } + else + { + c.Equal(UInkTestStatus.Rejected, result.Status, "invalid Header status"); + c.Equal(0, result.Pages.Count, "invalid Header does not expose pages"); + } + }); + } + + private static void LastValidClear(UInkChecks c) + { + Synthetic(c, 11, UInkTestEncoder.HeaderGuid, e => + { + e.Ink(0, 0, FirstColor, Points); + e.Clear(1, 1); + e.Shape(2, 2, MiddleColor); + e.Clear(3, 3); + e.Ink(4, 4, MiddleColor, Points); + e.Clear(5, 4); // CLEAR-4/12:与上一条笔迹共组,无效。 + e.Ink(6, 5, LastColor, Points); + }, result => + { + CheckInks(c, result, new[] { MiddleColor, LastColor }); + c.That(result.RequiresSaveAs, "Clear fallback requires Save As"); + }); + } + + private static void MixedUndoGroup(UInkChecks c) + { + Synthetic(c, 11, UInkTestEncoder.HeaderGuid, e => + { + e.Media(0, 0, "image.png"); + e.Ink(1, 1, FirstColor, Points); + e.Shape(2, 1, MiddleColor); + e.Media(3, 1, "image.png"); + e.Ink(4, 2, LastColor, Points); + }, result => + { + c.That(result.Status != UInkTestStatus.Rejected, "mixed group load: " + result.Error); + c.Equal(1, result.Pages.Count, "mixed group page count"); + if (result.Pages.Count == 0) return; + var page = result.Pages[0]; + c.Equal(3, page.UndoGroupCount, "mixed group undo count"); + var kinds = new[] { Media, Ink, Shape, Media, Ink }; + var ordinals = new[] { 0u, 1u, 1u, 1u, 2u }; + c.Equal(kinds.Length, page.Items.Count, "mixed group item count"); + for (int i = 0; i < Math.Min(kinds.Length, page.Items.Count); i++) + { + c.Equal(kinds[i], page.Items[i].Kind, $"mixed item {i} kind"); + c.Equal(ordinals[i], page.Items[i].UndoGroupOrdinal, $"mixed item {i} undo group"); + } + }, addResource: true); + } + + private static void Synthetic(UInkChecks c, ushort version, string guid, Action content, + Action check, bool addResource = false) + { + WithScratch(path => + { + using (var stream = File.Create(path)) + { + var encoder = new UInkTestEncoder(stream); + encoder.Header(version, 1, guid); + encoder.Canvas(0); + content(encoder); + } + if (addResource) UInkBench.WriteResources(path + ".extra", new[] { "image.png" }); + using var loader = new DeadlineLoader(); + if (loader.TryLoad(c, path, "synthetic load", out var result) && result != null) check(result); + }); + } + + private static void CheckInks(UInkChecks c, UInkTestLoadResult result, uint[] colors) + { + c.That(result.Status is UInkTestStatus.Ok or UInkTestStatus.Recovered, "load result: " + result.Status + " " + result.Error); + c.Equal(1, result.Pages.Count, "page count"); + if (result.Pages.Count == 0) return; + var items = result.Pages[0].Items; + c.Equal(colors.Length, items.Count, "visible item count"); + for (int i = 0; i < Math.Min(colors.Length, items.Count); i++) + { + c.Equal(Ink, items[i].Kind, $"item {i} kind"); + c.Equal(colors[i], items[i].ColorRgb, $"item {i} RGB"); + c.Equal(Points.Length, items[i].PointCount, $"item {i} point count"); + } + } + + private static void WithScratch(Action action) + { + string directory = Path.Combine(Path.GetTempPath(), "ICC-UInk-robust-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + string path = Path.Combine(directory, "sample.uink"); + try { action(path); } + finally + { + File.Delete(path); + File.Delete(path + ".extra"); + Directory.Delete(directory); + } + } + + private sealed class DeadlineLoader : IDisposable + { + private static readonly TimeSpan Limit = TimeSpan.FromSeconds(2); + private readonly BlockingCollection _queue = new(1); + private readonly Thread _worker; + + public DeadlineLoader() + { + // WPF 物化保持在 STA。独立 watchdog 能在 Load 卡住时让套件继续。 + _worker = new Thread(Work) { IsBackground = true }; + _worker.SetApartmentState(ApartmentState.STA); + UInkSuites.ObserveWorker(_worker); + _worker.Start(); + } + + private void Work() + { + try + { + foreach (var request in _queue.GetConsumingEnumerable()) request(); + } + finally + { + // WPF 解码可能在这个 STA 创建 Dispatcher,随 worker 一起释放。 + System.Windows.Threading.Dispatcher.FromThread(Thread.CurrentThread)?.InvokeShutdown(); + } + } + + public bool TryLoad(UInkChecks c, string path, string label, out UInkTestLoadResult result) + { + result = null; + var completion = new TaskCompletionSource<(UInkTestLoadResult Result, Exception Error, TimeSpan Elapsed)>(); + _queue.Add(() => + { + var clock = Stopwatch.StartNew(); + try { completion.SetResult((UInkTestApi.Load(path), null, clock.Elapsed)); } + catch (Exception ex) { completion.SetResult((null, ex, clock.Elapsed)); } + }); + if (!completion.Task.Wait(Limit)) + { + c.That(false, label + " exceeded 2 s; remaining mutations of this fixture were stopped"); + return false; + } + + var timed = completion.Task.Result; + c.That(timed.Elapsed <= Limit, label + " exceeded 2 s inside Load"); + c.That(timed.Error == null, label + " threw: " + timed.Error); + if (timed.Error == null) c.That(timed.Result != null, label + " returned null"); + result = timed.Result; + return true; + } + + public void Dispose() + { + _queue.CompleteAdding(); + if (_worker.Join(50)) _queue.Dispose(); + } + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkRoundtripTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkRoundtripTests.cs new file mode 100644 index 000000000..928eef5ae --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkRoundtripTests.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkRoundtripTests + { + private static readonly Color PenColor = Color.FromArgb(255, 17, 113, 221); + + public static int Run() + { + var suite = new UInkSuite("roundtrip"); + suite.Test("ConstantPressurePen", ConstantPressurePen); + suite.Test("VaryingPressurePen", VaryingPressurePen); + suite.Test("IgnorePressurePen", IgnorePressurePen); + suite.Test("RectangleHighlighter", RectangleHighlighter); + suite.Test("SemitransparentPen", SemitransparentPen); + suite.Test("DevicePixelsAt150Percent", DevicePixelsAt150Percent); + suite.Test("ExactHeaderAndCanvasNumbering", ExactHeaderAndCanvasNumbering); + UInkShapeToolTests.Register(suite); + UInkMappingTests.Register(suite); + UInkPptTests.Register(suite); + UInkCaptureTests.Register(suite); + UInkMediaTests.Register(suite); + UInkDefaultSaveTests.Register(suite); + return suite.Finish(); + } + + private static void ConstantPressurePen(UInkChecks c) => + CheckStroke(c, MakeStroke(PenColor, new[] { 0.6f, 0.6f, 0.6f }), 1); + + private static void VaryingPressurePen(UInkChecks c) => + CheckStroke(c, MakeStroke(PenColor, new[] { 0f, 0.15f, 0.5f, 0.85f, 1f }), 1); + + private static void IgnorePressurePen(UInkChecks c) => + CheckStroke(c, MakeStroke(PenColor, new[] { 0f, 0.5f, 1f }, ignorePressure: true), 1); + + private static void RectangleHighlighter(UInkChecks c) => + CheckStroke(c, MakeStroke(Color.FromArgb(128, 254, 228, 17), new[] { 0.3f, 0.5f, 0.8f }, highlighter: true), 1); + + private static void SemitransparentPen(UInkChecks c) => + CheckStroke(c, MakeStroke(Color.FromArgb(73, 79, 25, 202), new[] { 0.5f, 0.5f, 0.5f }), 1); + + private static void DevicePixelsAt150Percent(UInkChecks c) => + CheckStroke(c, MakeStroke(PenColor, new[] { 0f, 0.5f, 1f }), 1.5); + + private static void ExactHeaderAndCanvasNumbering(UInkChecks c) + { + var pen = MakeStroke(PenColor, new[] { 0.5f, 0.5f }); + var first = new StrokeCollection { pen, pen.Clone() }; + var second = new StrokeCollection { pen.Clone(), pen.Clone(), pen.Clone() }; + var (pages, bytes) = UInkTestApi.SavePagesAndReload(new[] { first, second }, 1); + c.Equal(2, pages.Count, "reloaded page count"); + if (pages.Count > 0) c.Equal(2, pages[0].Count, "first reloaded page stroke count"); + if (pages.Count > 1) c.Equal(3, pages[1].Count, "second reloaded page stroke count"); + + var blocks = UInkWireInspection.Read(bytes, c); + var contentCounts = new List(); + uint? lastUndo = null; + foreach (var block in blocks) + { + if (block.Type == 2) + { + contentCounts.Add(0); + lastUndo = null; + } + else if (block.Type == 3) + { + bool hasCanvas = contentCounts.Count > 0; + c.That(hasCanvas, "Ink appears before any Canvas"); + if (!hasCanvas) continue; + uint expectedContent = contentCounts[^1]; + c.Equal(expectedContent, block.ContentId, "Canvas contentId"); + contentCounts[^1] = expectedContent + 1; + if (!lastUndo.HasValue) c.Equal(0, block.UndoId, "first Canvas undoId"); + else + { + c.That(block.UndoId >= lastUndo, "undoId decreased or is missing"); + // D7:没有历史的独立笔画各成一组。 + c.That(block.UndoId > lastUndo, "independent input strokes share an undo group"); + } + lastUndo = block.UndoId; + } + else c.Equal(1, block.Type, "unexpected output block type"); + } + + c.Equal(2, contentCounts.Count, "wire Canvas count"); + if (contentCounts.Count > 0) c.Equal(2u, contentCounts[0], "first wire Canvas content count"); + if (contentCounts.Count > 1) c.Equal(3u, contentCounts[1], "second wire Canvas content count"); + } + + private static Stroke MakeStroke(Color color, float[] pressure, bool ignorePressure = false, bool highlighter = false) + { + var points = new StylusPointCollection(pressure.Length); + for (int i = 0; i < pressure.Length; i++) + points.Add(new StylusPoint(-12.25 + 13.75 * i, 23.5 - 4.25 * i, pressure[i])); + + return new Stroke(points, new DrawingAttributes + { + Width = highlighter ? 3 : 12, + Height = highlighter ? 24 : 12, + StylusTip = highlighter ? StylusTip.Rectangle : StylusTip.Ellipse, + IsHighlighter = highlighter, + IgnorePressure = ignorePressure, + FitToCurve = false, + Color = color, + }); + } + + private static void CheckStroke(UInkChecks c, Stroke source, double dpiScale) + { + var (reloaded, bytes) = UInkTestApi.SaveStrokesAndReload(new StrokeCollection { source }, dpiScale); + c.Equal(1, reloaded.Count, "reloaded stroke count"); + if (reloaded.Count > 0) CheckWpf(c, source, reloaded[0]); + + var blocks = UInkWireInspection.Read(bytes, c); + var inks = blocks.FindAll(block => block.Type == 3); + c.Equal(1, inks.Count, "wire Ink block count"); + if (inks.Count > 0) CheckWire(c, source, dpiScale, inks[0]); + } + + private static void CheckWpf(UInkChecks c, Stroke source, Stroke reloaded) + { + var expectedColor = source.DrawingAttributes.Color; + var actualColor = reloaded.DrawingAttributes.Color; + c.Equal(expectedColor.R, actualColor.R, "reloaded R"); + c.Equal(expectedColor.G, actualColor.G, "reloaded G"); + c.Equal(expectedColor.B, actualColor.B, "reloaded B"); + c.Equal(expectedColor.A, actualColor.A, "reloaded alpha"); + c.Equal(source.DrawingAttributes.StylusTip, reloaded.DrawingAttributes.StylusTip, "reloaded nib shape"); + if (source.DrawingAttributes.StylusTip == StylusTip.Rectangle) + c.Near(Aspect(source), Aspect(reloaded), "reloaded nib aspect", 1e-4); + + c.Equal(source.StylusPoints.Count, reloaded.StylusPoints.Count, "reloaded point count"); + for (int i = 0; i < Math.Min(source.StylusPoints.Count, reloaded.StylusPoints.Count); i++) + { + c.Near(source.StylusPoints[i].X, reloaded.StylusPoints[i].X, $"reloaded point {i} X"); + c.Near(source.StylusPoints[i].Y, reloaded.StylusPoints[i].Y, $"reloaded point {i} Y"); + double expected = VisibleWidth(source, i); + c.Near(expected, VisibleWidth(reloaded, i), $"reloaded point {i} visible width", expected * 1e-3); + } + } + + private static void CheckWire(UInkChecks c, Stroke source, double dpiScale, UInkWireBlock ink) + { + var da = source.DrawingAttributes; + uint rgb = (uint)((da.Color.R << 16) | (da.Color.G << 8) | da.Color.B); + c.Equal(rgb, ink.Color, "wire RGB"); + c.Equal(da.IsHighlighter ? 2 : 1, ink.InkType, "wire inkType"); + // 传统 WPF 荧光的有效透明度是 0.5;公开 alpha 可有一个字节的舍入误差。 + c.Near(da.IsHighlighter ? 0.5 : da.Color.A / 255.0, ink.Opacity, "wire opacity", 0.5 / 255 + 1e-6); + if (da.StylusTip == StylusTip.Rectangle) + { + c.Equal(1, ink.NibShape, "wire nib shape"); + c.Near(Aspect(source), ink.NibAspect, "wire nib aspect"); + } + + c.Equal(source.StylusPoints.Count, ink.Points?.Length ?? 0, "wire point count"); + if (ink.Points == null) return; + double? x = 0, y = 0; + for (int i = 0; i < Math.Min(source.StylusPoints.Count, ink.Points.Length); i++) + { + x += ink.Points[i].X; + y += ink.Points[i].Y; + c.Near(source.StylusPoints[i].X * dpiScale, x, $"wire point {i} X in Device px"); + c.Near(source.StylusPoints[i].Y * dpiScale, y, $"wire point {i} Y in Device px"); + double expected = VisibleWidth(source, i) * dpiScale; + c.Near(expected, ink.Points[i].Width, $"wire point {i} width in Device px", expected * 1e-3); + } + } + + private static double VisibleWidth(Stroke stroke, int i) + { + // D4:圆笔尖取直径,矩形取高度;WPF 的压力比例不等于 PressureFactor 本身。 + var da = stroke.DrawingAttributes; + double q = da.IgnorePressure ? 1 : 0.25 + 1.5 * stroke.StylusPoints[i].PressureFactor; + double tip = da.StylusTip == StylusTip.Rectangle ? da.Height : da.Width; + return q * tip; + } + + private static double Aspect(Stroke stroke) => + stroke.DrawingAttributes.Width / stroke.DrawingAttributes.Height; + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkShapeToolTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkShapeToolTests.cs new file mode 100644 index 000000000..dc927c862 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkShapeToolTests.cs @@ -0,0 +1,883 @@ +using System; +using System.IO; +using System.Linq; +using System.Windows; +using System.Windows.Ink; +using System.Windows.Input; +using System.Windows.Media; +using Ink_Canvas; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; +using static Ink_Canvas.UInk.IccShapeDescriptor; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkShapeToolTests + { + internal static void Register(UInkSuite suite) + { + for (int mode = 1; mode <= 25; mode++) + { + int tool = mode; + suite.Test("HeadEquivalence" + tool.ToString("D2"), _ => HeadEquivalence(tool)); + suite.Test("ShapeTool" + tool.ToString("D2"), c => ToolRoundtrip(c, tool)); + } + + suite.Test(nameof(SnapshotPenStyle), SnapshotPenStyle); + suite.Test(nameof(DegenerateDash), DegenerateDash); + suite.Test(nameof(GlyphDrawnGeometry), GlyphDrawnGeometry); + suite.Test(nameof(IsfCurveAndDots), IsfCurveAndDots); + suite.Test(nameof(ForeignShapeEdit), ForeignShapeEdit); + suite.Test(nameof(InterruptedObjectFrames), InterruptedObjectFrames); + suite.Test(nameof(TangentEllipseRecognition), TangentEllipseRecognition); + suite.Test(nameof(DescriptorLifetime), DescriptorLifetime); + suite.Test(nameof(CurveDeviation), CurveDeviation); + suite.Test(nameof(GlyphWithHole), GlyphWithHole); + suite.Test(nameof(CurvedGlyphOutline), CurvedGlyphOutline); + suite.Test(nameof(RecognizedPressure), RecognizedPressure); + suite.Test(nameof(PublicDashPhase), PublicDashPhase); + suite.Test(nameof(PrimitiveGeometry), PrimitiveGeometry); + suite.Test(nameof(DamagedObject), DamagedObject); + suite.Test(nameof(RecognizedShapes), RecognizedShapes); + suite.Test(nameof(HyperbolaDeviation), HyperbolaDeviation); + suite.Test(nameof(PendingShapeUndo), PendingShapeUndo); + } + + private static byte[] SnapshotBytes(StrokeCollection strokes) + { + var machine = new TimeMachine(); + machine.CommitStrokeUserInputHistory(strokes); + var input = new UInkPageInput { Canvas = UInkIccMapper.BuildCanvas("", "", + UInkTestEncoder.PageGuid(0), 0, 1, null, null) }; + new UInkHistorySnapshot(machine.GetAppliedHistorySnapshot()).CaptureStrokes(input, null); + var doc = UInkIccMapper.BuildDocument(UInkTestEncoder.HeaderGuid, null, null, new[] { input }, 0); + using var stream = new MemoryStream(); + UInkWriter.Save(doc, stream); + return stream.ToArray(); + } + + private static void SnapshotPenStyle(UInkChecks c) + { + var marker = Build(1, out _)[0]; + marker.DrawingAttributes.StylusTip = StylusTip.Rectangle; + UInkConversion.SetLogicalPenKind(marker, true); + var strokes = new StrokeCollection { marker }; + foreach (bool highlighter in new[] { true, false }) + { + var ink = UInkConversion.StrokeToInk(marker); + ink.InkType = (int)(highlighter ? UInkInkType.Highlighter : UInkInkType.Pen); + ink.Opacity = 0.3f; + strokes.Add(UInkConversion.InkToStroke(ink)); + } + var blocks = UInkReader.Read(SnapshotBytes(strokes)).Document.Canvases.Single().Blocks; + c.Equal((int)UInkInkType.Highlighter, ((UInkInk)blocks[0]).InkType, "overlap highlighter"); + c.Equal(0.3f, ((UInkInk)blocks[1]).Opacity, "imported highlighter opacity"); + c.Equal(0.3f, ((UInkInk)blocks[2]).Opacity, "unquantized pen opacity"); + } + + private static void DegenerateDash(UInkChecks c) + { + foreach (int mode in new[] { 6, 7, 10 }) + { + Point a = new(10, 20), b = new(10, 60); + var strokes = mode == 10 ? Between(Tool.DashedArc, a, a).Preview(Pen()) : + IccShapeTools.Solid(mode == 6, a, b, Pen()); + Commit(strokes, mode); + var read = UInkReader.Read(SnapshotBytes(strokes)); + var blocks = read.Document.Canvases.Single().Blocks; + int start = mode == 6 ? 2 : mode == 7 ? 1 : 0; + int segments = mode == 10 ? 26 : 13; + c.Equal(strokes.Count, blocks.Count, "single native strokes stay in order"); + for (int i = start; i < start + segments; i++) + { + var ink = blocks[i] as UInkInk; + c.That(ink != null, "zero-length dashed arc must be Ink"); + if (ink == null) continue; + var points = strokes[i].StylusPoints; + c.Equal(points.Count, ink.Points.Length, "native segment point count"); + for (int j = 0; j < points.Count; j++) + { + c.Near(points[j].X - (j == 0 ? 0 : points[j-1].X), ink.Points[j].X, "x"); + c.Near(points[j].Y - (j == 0 ? 0 : points[j-1].Y), ink.Points[j].Y, "y"); + } + } + c.That(blocks.All(block => block.UndoId == blocks[0].UndoId), "single undo group"); + c.That(!read.DiagnosticCounts.ContainsKey("SHAPE-7"), "valid wire dash arrays"); + } + } + + private static void GlyphDrawnGeometry(UInkChecks c) + { + var bounds = new Rect(4, 6, 40, 50); + var solid = FilledGlyphStroke.TryCreate(new RectangleGeometry(bounds), Pen()); + var ring = new GeometryGroup { FillRule = FillRule.EvenOdd }; + ring.Children.Add(new RectangleGeometry(bounds)); + ring.Children.Add(new RectangleGeometry(new Rect(12, 18, 16, 12))); + var glyph = FilledGlyphStroke.TryCreate(ring, Pen()); + var move = Matrix.Identity; + move.Translate(80, 25); + glyph.Transform(move, false); + var canvas = UInkReader.Read(SnapshotBytes(new StrokeCollection { glyph })); + var page = UInkIccMapper.BuildPageIndex(canvas, 1, 1).Pages.Single(); + page.EnsureMaterialized(); + var restored = (FilledGlyphStroke)page.FinalStrokes.Single(); + // HEAD 的 FilledGlyphStroke.Transform 只移动命中框,DrawCore 仍画原轮廓;文件按实际绘制位置保存(float32 精度)。 + var want = glyph.GlyphGeometry.Bounds; + var got = restored.GlyphGeometry.Bounds; + c.Near(want.X, got.X, "drawn position X"); + c.Near(want.Y, got.Y, "drawn position Y"); + c.Near(want.Width, got.Width, "drawn width"); + c.Near(want.Height, got.Height, "drawn height"); + c.That(!restored.GlyphGeometry.FillContains(new Point(16, 20)), "drawn hole"); + + glyph = FilledGlyphStroke.TryCreate(ring, Pen()); + glyph.AddPropertyData(Property, solid.GetPropertyData(Property)); + var blocks = UInkReader.Read(SnapshotBytes(new StrokeCollection { glyph })).Document.Canvases.Single().Blocks; + // 过期描述符(实心)不能决定几何:按实际轮廓(带洞)写出一个 Polygon。 + c.Equal(1, blocks.Count, "stale descriptor yields one glyph block"); + c.That(blocks.Single() is UInkShape { ShapeType: 6 }, "glyph written as Polygon"); + var reread = UInkIccMapper.BuildPageIndex(UInkReader.Read(SnapshotBytes(new StrokeCollection { glyph })), 1, 1).Pages.Single(); + reread.EnsureMaterialized(); + c.That(reread.FinalStrokes.Single() is FilledGlyphStroke g && !g.GlyphGeometry.FillContains(new Point(16, 20)), + "actual hole is kept, not the stale solid recipe"); + } + + private static void IsfCurveAndDots(UInkChecks c) + { + foreach (var kind in new[] { Tool.Ellipse, Tool.Dot }) + { + var strokes = Between(kind, new Point(3.47, -7.22), new Point(92.73, 103.88)).Preview(Pen()); + if (kind == Tool.Ellipse) c.Equal(629, strokes[0].StylusPoints.Count, "full ellipse"); + Commit(strokes, kind == Tool.Dot ? 18 : 4); + using var stream = new MemoryStream(); + strokes.Save(stream); + stream.Position = 0; + var pasted = new StrokeCollection(stream); + c.That(TryExport(pasted, 0, UInkCoordinateMap.Identity, out _, out var shape) && + shape.ShapeType == (int)(kind == Tool.Ellipse ? UInkShapeType.Ellipse : UInkShapeType.Line), + "ISF-quantized geometry and pressure"); + var move = Matrix.Identity; + move.Rotate(23); + move.Translate(80, 12); + pasted.Transform(move, false); + c.That(TryExport(pasted, 0, UInkCoordinateMap.Identity, out _, out _), + "affine fit after ISF quantization"); + if (kind == Tool.Ellipse) + { + var point = pasted[0].StylusPoints[81]; + point.X += 0.2; + pasted[0].StylusPoints[81] = point; + c.That(!TryExport(pasted, 0, UInkCoordinateMap.Identity, out _, out _), + "one independently edited sample fails full verification"); + } + } + var dots = Between(Tool.Dot, new Point(2, 4), new Point(5, 8)).Preview(Pen()); + Commit(dots, 18); + var translation = Matrix.Identity; + translation.Translate(12, 9); + dots.Transform(translation, false); + c.That(TryExport(dots, 0, UInkCoordinateMap.Identity, out _, out var moved), "single dot translation"); + var line = ((UInkLineGeometry)moved.Geometry).Points; + c.Near(14, line[0].X, "translated start x"); + c.Near(17, line[1].Y, "translated end y"); + } + + private static void ForeignShapeEdit(UInkChecks c) + { + var line = new UInkShape { ShapeType = (int)UInkShapeType.Polyline, + Geometry = new UInkLineGeometry { Points = { new UInkShapePoint(), + new UInkShapePoint { X = 30 }, new UInkShapePoint { X = 30, Y = 30 } } }, + Stroke = new UInkStroke { Color = new UInkColor(), Width = 2, DashArray = new() { 5, 5 }, DashOffset = 2 } }; + UInkConversion.BlockToStroke(line, UInkCoordinateMap.Identity, null, out var parts); + parts.Transform(new Matrix(2, 0, 0, 1, 0, 0), false); + var blocks = UInkReader.Read(SnapshotBytes(parts)).Document.Canvases.Single().Blocks; + c.Equal(parts.Count, blocks.Count, "mixed scales preserve native runs"); + c.That(blocks.All(part => part is UInkInk), "ambiguous dash scale falls back"); + + // 非等比矩阵作用于两条不同方向的边,但两条边恰好有相同长度比。 + var path = ((UInkLineGeometry)line.Geometry).Points; + path[1] = new UInkShapePoint { X = 30, Y = 30 }; + path[2] = new UInkShapePoint { X = 60, Y = 0 }; + UInkConversion.BlockToStroke(line, UInkCoordinateMap.Identity, null, out parts); + parts.Transform(new Matrix(2, 0, 0, 1, 0, 0), false); + var scaled = (UInkShape)UInkReader.Read(SnapshotBytes(parts)).Document.Canvases.Single().Blocks.Single(); + double ratio = Math.Sqrt(2.5); + c.Near(5 * ratio, scaled.Stroke.DashArray[0], "shared direction-dependent scale"); + c.Near(2 * ratio, scaled.Stroke.DashOffset, "phase uses the same scale"); + + var rect = new UInkShape { ShapeType = (int)UInkShapeType.Rectangle, + Geometry = new UInkRectGeometry { Width = 40, Height = 30 }, + Stroke = new UInkStroke { Color = new UInkColor(), Width = 2 } }; + var first = UInkConversion.BlockToStroke(rect, UInkCoordinateMap.Identity, null, out parts); + parts ??= new StrokeCollection { first }; + parts.Transform(new Matrix(1, 0, 0.5, 1, 0, 0), false); + c.That(TryExport(parts, 0, UInkCoordinateMap.Identity, out _, out var projected) && + projected.Geometry is UInkLineGeometry projectedPath && projectedPath.Points.Count == 4, + "projection itself omits the closing point before the wire formatter"); + var polygon = (UInkShape)UInkReader.Read(SnapshotBytes(parts)).Document.Canvases.Single().Blocks.Single(); + c.Equal((int)UInkShapeType.Polygon, polygon.ShapeType, "sheared public rectangle"); + var corners = ((UInkLineGeometry)polygon.Geometry).Points; + c.Equal(4, corners.Count, "implicit closing edge"); + c.That(corners[0].X != corners[^1].X || corners[0].Y != corners[^1].Y, "distinct final corner"); + } + + private static void InterruptedObjectFrames(UInkChecks c) + { + var strokes = Build(11, out _); + Commit(strokes, 11); + var source = SnapshotBytes(strokes); + var blocks = UInkReader.Read(source).Document.Canvases.Single().Blocks; + var second = (UInkShape)blocks[1]; + int split = second.StreamOffset.Value; + foreach (bool unknown in new[] { false, true }) + { + using var stream = new MemoryStream(); + stream.Write(source, 0, split); + if (unknown) + { + // 同组的未知块,map {type:uint16(7), undoId:uint32(0)}。 + stream.Write(new byte[] { 0x82, 0xa4, 116, 121, 112, 101, 0xcd, 0, 7, + 0xa6, 117, 110, 100, 111, 73, 100, 0xce, 0, 0, 0, 0 }); + } + else new UInkTestEncoder(stream).Ink(99, second.UndoId, 0, + new[] { new UInkTestPoint(0, 0, 1) }, UInkTestInkFault.InvalidWidth); + stream.Write(source, split, source.Length - split); + var read = UInkReader.Read(stream.ToArray()); + var page = UInkIccMapper.BuildPageIndex(read, 1, 1).Pages.Single(); + page.EnsureMaterialized(); + c.Equal(blocks.Count, page.Shapes.Count, "all independent parts survive"); + c.That(page.Shapes.All(shape => shape.Object == null), "physical break dissolves object"); + c.That(read.DiagnosticCounts.ContainsKey("SHAPE-14"), "object diagnostic"); + c.Equal(1, page.History.Length, "INK-3 group survives"); + } + } + + private static StrokeCollection PreviewFromHelpers(int mode, Point start, Point end, DrawingAttributes da, + bool marks, Point frontStart, Point frontEnd, double slope, StrokeCollection firstStep = null) + { + StrokeCollection Part(Tool kind, Point a, Point b) => Between(kind, a, b).Preview(da); + double dx = end.X - start.X, dy = end.Y - start.Y; + switch (mode) + { + case 1: return Part(Tool.Line, start, end); + case 2: return Part(Tool.Arrow, start, end); + case 3: case 19: return new StrokeCollection { IccShapeTools.Rectangle(start, end, mode == 19, da) }; + case 4: return Part(Tool.Ellipse, start, end); + case 5: case 10: + double r = (end - start).Length; + var radius = new Vector(r, r); + return Part(mode == 5 ? Tool.Ellipse : Tool.DashedArc, start-radius, start+radius); + case 6: case 7: return IccShapeTools.Solid(mode == 6, start, end, da); + case 8: return Part(Tool.Dash, start, end); + case 9: return firstStep == null ? IccShapeTools.CuboidFront(start, end, da) : + IccShapeTools.CuboidBack(frontStart, frontEnd, Math.Abs(frontStart.Y-end.Y), da); + case 11: case 12: case 13: case 14: case 17: return IccShapeTools.Axes(mode, start, end, marks, da); + case 15: return IccShapeTools.Parallel(start, end, da); + case 16: return Part(Tool.Ellipse, start-new Vector(dx, dy), end); + case 18: return Part(Tool.Dot, start, end); + case 20: case 21: case 22: return IccShapeTools.ParabolaPreview(mode, start, end, da); + case 23: return IccShapeTools.EllipseWithFoci(start, end, da); + case 24: case 25: + if (Math.Abs(dx) < 0.01 || Math.Abs(dy) < 0.01) return new StrokeCollection(); + return firstStep == null ? IccShapeTools.HyperbolaAsymptotes(start, end, da) : + IccShapeTools.HyperbolaPreview(mode, start, end, slope, firstStep, da); + default: throw new ArgumentOutOfRangeException(nameof(mode)); + } + } + + private static void ComparePreview(StrokeCollection expected, StrokeCollection actual, int mode, int sample) + { + string label = $"mode {mode}, sample {sample}"; + if (expected.Count != actual.Count) throw new InvalidOperationException(label + " stroke count"); + for (int i = 0; i < expected.Count; i++) + { + var a = expected[i]; + var b = actual[i]; + if (!a.DrawingAttributes.Equals(b.DrawingAttributes) || a.StylusPoints.Count != b.StylusPoints.Count) + throw new InvalidOperationException($"{label}, stroke {i} DA or point count"); + for (int j = 0; j < a.StylusPoints.Count; j++) + { + var p = a.StylusPoints[j]; + var q = b.StylusPoints[j]; + if (!((p.ToPoint()-q.ToPoint()).Length <= 1e-9) || p.PressureFactor != q.PressureFactor) + throw new InvalidOperationException($"{label}, stroke {i}, point {j}: {p} vs {q}"); + } + } + } + + private static void HeadEquivalence(int mode) + { + var random = new Random(357364 + mode); + double Coordinate() => random.NextDouble()*180-90; + for (int i = 0; i < 200; i++) + { + var start = new Point(Coordinate(), Coordinate()); + double dx = Coordinate(), dy = Coordinate(); + if (i % 10 == 0) dx = 0.00999; + if (i % 10 == 1) dy = -0.01001; + var end = start + new Vector(dx, dy); + var da = Pen(); + da.Width = da.Height = 2 + random.NextDouble()*8; + da.IgnorePressure = i % 3 == 0; + bool marks = i % 2 == 0; + var head = new ShapeToolHeadReference(da, marks); + var expected = head.Generate(mode, start, end, true, default, default, 0, 0, null); + var actual = PreviewFromHelpers(mode, start, end, da, marks, default, default, 0); + if (mode == 5 && marks) + { + expected.Add(ShapeToolHeadReference.CircleCenter(start, da)); + actual.Add(MainWindow.CircleCenter(start, da)); + } + ComparePreview(expected, actual, mode, i); + if (mode != 9 && mode != 24 && mode != 25) continue; + if (mode != 9 && expected.Count == 0) continue; + var min = new Point(Math.Min(start.X,end.X), Math.Min(start.Y,end.Y)); + var max = new Point(Math.Max(start.X,end.X), Math.Max(start.Y,end.Y)); + var finish = new Point(Coordinate(), Coordinate()); + double slope = Math.Abs((end.Y-start.Y)/(end.X-start.X)); + var next = head.Generate(mode, start, finish, false, min, max, 1, slope, expected); + var current = PreviewFromHelpers(mode, start, finish, da, marks, min, max, slope, actual); + ComparePreview(next, current, mode, i); + if (mode == 9) + { + expected.Add(next); + actual.Add(current); + ComparePreview(expected, actual, mode, i); + continue; + } + if (next.Count == 0) continue; + // 收尾的四个结果依次覆盖 Yes、No、Ask 后移除、Ask 后保留。 + var option = (i % 4) switch { 0 => OptionalOperation.Yes, 1 => OptionalOperation.No, _ => OptionalOperation.Ask }; + if (i % 4 == 1 || i % 4 == 2) next.Remove(expected); + MainWindow.ApplyAsymptoteOption(option, i % 4 == 2, new StrokeCollection(current), actual, current); + ComparePreview(next, current, mode, i); + } + } + + private static void TangentEllipseRecognition(UInkChecks c) + { + foreach (double value in new[] { double.NaN, double.PositiveInfinity, double.NegativeInfinity }) + c.Equal(0, Between(Tool.DashedArc, new Point(0, 1), new Point(2, value)).Preview(Pen()).Count, + "non-finite dashed ellipse"); + var strokes = IccShapeTools.TangentEllipse(new Point(3, 4), new Point(40, 28), Pen()); + c.Equal(14, strokes.Count, "solid lower arc and thirteen upper dashes"); + for (int i = 0; i < strokes.Count; i++) + c.Equal(i == 0, strokes[i].ContainsPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid), + "HEAD recognition set " + i); + } + + private static DrawingAttributes Pen() => new() + { + Color = Color.FromArgb(160, 20, 40, 80), + Width = 4, + Height = 4, + FitToCurve = false + }; + private static StrokeCollection Build(int mode, out int[] types) + { + Point a = new(10, 20), b = new(90, 70); + var da = Pen(); + StrokeCollection Part(Tool kind, Point start, Point end) => Between(kind, start, end).Preview(da); + var strokes = new StrokeCollection(); + void Dot(Point p) => strokes.Add(new Stroke(new StylusPointCollection { new StylusPoint(p.X, p.Y, 1) }, da.Clone())); + switch (mode) + { + case 1: + types = new[] + { + 0 + }; + return Part(Tool.Line, a, b); + case 2: + types = new[] + { + 0 + }; + return Part(Tool.Arrow, a, b); + case 3: + case 19: + types = new[] + { + 2 + }; + strokes.Add(IccShapeTools.Rectangle(a, b, mode == 19, da)); + break; + case 4: + case 16: + case 23: + types = mode == 23 ? new[] + { + 4, + -1, + -1 + } + + : new[] + { + 4 + }; + strokes.Add(Part(Tool.Ellipse, mode == 4 ? a : a + (a - b), b)); + if (mode == 23) + { + Dot(new Point(-52.45, 20)); + Dot(new Point(72.45, 20)); + } + + break; + case 5: + types = new[] + { + 5 + }; + return Part(Tool.Ellipse, a, new Point(90, 100)); + case 6: + types = new[] + { + 4, + 1, + 1, + 0, + 0 + }; + return IccShapeTools.Solid(true, a, b, da); + case 7: + types = new[] + { + 1, + 1, + 0, + 0 + }; + return IccShapeTools.Solid(false, a, b, da); + case 8: + types = new[] + { + 0 + }; + return Part(Tool.Dash, a, b); + case 9: + types = new int[12]; + strokes = IccShapeTools.CuboidFront(a, b, da); + strokes.Add(IccShapeTools.CuboidBack(a, b, 32, da)); + break; + case 10: + types = new[] + { + 1 + }; + return Part(Tool.DashedArc, a, new Point(90, 100)); + case 11: + case 12: + case 13: + case 14: + case 17: + types = new int[mode == 17 ? 3 : 2]; + return IccShapeTools.Axes(mode, a, b, false, da); + case 15: + types = new int[4]; + return IccShapeTools.Parallel(a, b, da); + case 18: + types = new[] + { + 0 + }; + return Part(Tool.Dot, a, b); + case 20: + case 21: + case 22: + strokes = Parabola(a, 0.03, 60, mode == 20).Preview(da); + types = mode == 22 ? new[] + { + 1, + -1 + } + + : new[] + { + 1 + }; + if (mode == 22) + Dot(new Point(1, 20)); + break; + case 24: + case 25: + strokes.Add(Part(Tool.Dash, a, b)); + strokes.Add(Part(Tool.Dash, new Point(a.X, b.Y), new Point(b.X, a.Y))); + foreach (int side in new[] + { + 1, + -1 + } + + ) + strokes.Add(Hyperbola(a, 10, 5, 0.5, 30, true, side).Preview(da)); + types = mode == 25 ? new[] + { + 0, + 0, + 1, + 1, + -1, + -1 + } + + : new[] + { + 0, + 0, + 1, + 1 + }; + if (mode == 25) + { + Dot(new Point(-1, 20)); + Dot(new Point(21, 20)); + } + + break; + default: + throw new ArgumentOutOfRangeException(nameof(mode)); + } + + return strokes; + } + + private static void ToolRoundtrip(UInkChecks c, int mode) + { + var strokes = Build(mode, out var expected); + var machine = new TimeMachine(); + MainWindow.CommitDrawnShape(machine, strokes, mode); + var snapshot = new UInkHistorySnapshot(machine.GetAppliedHistorySnapshot()); + var input = new UInkPageInput + { + Canvas = UInkIccMapper.BuildCanvas("", "", "aaaaaaaa-0000-4000-8000-000000000001", 0, 1, null, null) + }; + snapshot.CaptureStrokes(input, strokes); + var doc = UInkIccMapper.BuildDocument("aaaaaaaa-0000-4000-8000-000000000002", null, null, new[] { input }, 0, 1.5, 1.5); + using var stream = new MemoryStream(); + UInkWriter.Save(doc, stream); + var read = UInkReader.Read(stream.ToArray()); + var blocks = read.Document.Canvases[0].Blocks; + c.Equal(expected.Length, blocks.Count, "content count"); + int parts = expected.Count(type => type >= 0); + for (int j = 0; j < blocks.Count && j < expected.Length; j++) + { + c.Equal(0u, blocks[j].UndoId, "one creation undo group"); + if (expected[j] < 0) + { + c.That(blocks[j] is UInkInk, "focus remains Ink"); + continue; + } + + var shape = blocks[j] as UInkShape; + c.That(shape != null, "expected Shape " + j); + if (shape == null) + continue; + c.Equal(expected[j], shape.ShapeType, "shapeType " + j); + c.Near(160 / 255.0, shape.Stroke.Opacity, "alpha"); + c.Equal(0x142850u, shape.Stroke.Color.Fallback, "color"); + c.Near(mode == 18 ? 8.7 : 6, shape.Stroke.Width, "device width"); + if (parts > 1) + { + var id = ((UInkShape)blocks[0]).Object?.Id; + c.That(Guid.TryParse(id, out _), "object head id"); + if (j == 0) + c.Equal((uint)parts, shape.Object?.PartCount ?? 0, "part count"); + else + { + c.Equal(id, shape.Object?.Ref, "part ref"); + c.Equal((uint)j, shape.Object?.PartIndex ?? 0, "part order"); + } + } + + if (mode == 2 || mode is 11 or 12 or 13 or 14 or 17) + c.Equal(1, shape.Stroke.EndMarker ?? 0, "OpenArrow"); + if (mode == 8 || (mode == 9 && j is 5 or 8 or 10) || ((mode == 24 || mode == 25) && j < 2)) + c.Floats(new[] { 7.5f, 13.2f }, shape.Stroke.DashArray?.ToArray(), "ICC dash"); + if (mode == 18) + c.Floats(new[] { 0f, 12.42f }, shape.Stroke.DashArray?.ToArray(), "ICC dot"); + } + + var index = UInkIccMapper.BuildPageIndex(read, 1.5, 1.5); + var page = index.Pages.Single(); + page.EnsureMaterialized(); + c.Equal(1, page.History.Length, "one native undo operation"); + SameStrokes(c, strokes, page.FinalStrokes); + input.Strokes = page.FinalStrokes; + var again = UInkIccMapper.BuildDocument(doc.Header.Guid, null, null, new[] { input }, 0, 1.5, 1.5); + using var second = new MemoryStream(); + UInkWriter.Save(again, second); + c.That(stream.ToArray().SequenceEqual(second.ToArray()), "stable wire fields after reload"); + } + + private static void SameStrokes(UInkChecks c, StrokeCollection a, StrokeCollection b) + { + c.Equal(a.Count, b.Count, "native stroke count"); + for (int i = 0; i < Math.Min(a.Count, b.Count); i++) + { + var before = a[i]; + var after = b[i]; + c.That(before.DrawingAttributes.Equals(after.DrawingAttributes), "DA " + i); + c.Equal(before.StylusPoints.Count, after.StylusPoints.Count, "native point count"); + for (int k = 0; k < Math.Min(before.StylusPoints.Count, after.StylusPoints.Count); k++) + { + var p = before.StylusPoints[k]; + var q = after.StylusPoints[k]; + if ((p.ToPoint() - q.ToPoint()).Length > 0.001 || Math.Abs(p.PressureFactor - q.PressureFactor) > 1e-6) + { + c.That(false, "native point " + i + "/" + k); + break; + } + } + } + } + + private static void DescriptorLifetime(UInkChecks c) + { + var strokes = Build(3, out _); + var machine = new TimeMachine(); + MainWindow.CommitDrawnShape(machine, strokes, 3); + machine.Undo(); + machine.Redo(); + var clone = machine.GetAppliedHistorySnapshot().Single().CurrentStroke.Clone(); + c.That(clone[0].ContainsPropertyData(Property), "undo/redo/clone keeps property"); + using var isf = new MemoryStream(); + clone.Save(isf); + isf.Position = 0; + var paste = new StrokeCollection(isf); + c.Equal((string)clone[0].GetPropertyData(Property), (string)paste[0].GetPropertyData(Property), "ISF descriptor"); + c.That(TryExport(paste, 0, UInkCoordinateMap.Identity, out _, out var pasted) && pasted.ShapeType == 2, + "ISF-quantized unedited rectangle still exports as Shape"); + var matrix = Matrix.Identity; + matrix.Rotate(35); + matrix.Scale(2, 1); + matrix.Translate(40, 10); + clone.Transform(matrix, false); + c.That(TryExport(clone, 0, UInkCoordinateMap.Identity, out _, out var shape) && shape.ShapeType == 6, "sheared rectangle is Polygon"); + var clipped = strokes[0].GetEraseResult(new[] { new Point(10, 40) }, new EllipseStylusShape(8, 8)); + c.That(clipped.Count > 0, "point erase yielded fragments"); + for (int i = 0; i < clipped.Count; i++) + c.That(!TryExport(clipped, i, UInkCoordinateMap.Identity, out _, out _), "erased fragment is Ink"); + clone[0].DrawingAttributes.Width += 1; + c.That(!TryExport(clone, 0, UInkCoordinateMap.Identity, out _, out _), "DA edit invalidates descriptor"); + } + + private static void CurveDeviation(UInkChecks c) + { + var center = new Point(0, 0); + var strokes = Parabola(center, 0.2, 10, true).Preview(Pen()); + Commit(strokes, 20); + var map = new UInkCoordinateMap(4, 4); + c.That(TryExport(strokes, 0, map, out _, out var shape), "curve exported"); + var poly = (UInkLineGeometry)shape.Geometry; + for (int i = 1; i < poly.Points.Count; i++) + { + var a = poly.Points[i - 1]; + var b = poly.Points[i]; + double x = (a.X + b.X) / 2; + c.That(Math.Abs((a.Y + b.Y) / 2 + 0.05 * x * x) <= 0.25001, "device-space chord deviation"); + } + } + + private static void GlyphWithHole(UInkChecks c) + { + var ring = new GeometryGroup + { + FillRule = FillRule.EvenOdd + }; + ring.Children.Add(new RectangleGeometry(new Rect(0, 0, 48, 60))); + ring.Children.Add(new RectangleGeometry(new Rect(12, 12, 24, 36))); + var glyph = FilledGlyphStroke.TryCreate(ring, Pen()); + var saved = UInkTestApi.SaveStrokesAndReload(new StrokeCollection { glyph }, 1); + var shape = UInkReader.Read(saved.Bytes).Document.Canvases[0].Blocks.Single() as UInkShape; + c.That(shape?.ShapeType == 6 && shape.Fill != null && shape.Stroke == null && shape.Object?.PartCount == 1 && shape.Extra.ContainsKey("icc:glyph/v1"), "filled Polygon under object"); + c.That(saved.Strokes[0] is FilledGlyphStroke, "restored glyph class"); + if (saved.Strokes[0] is FilledGlyphStroke restored) + { + c.That(restored.GlyphGeometry.FillContains(new Point(2, 3)), "filled exterior"); + c.That(!restored.GlyphGeometry.FillContains(new Point(20, 20)), "hole remains transparent"); + } + } + + private static void CurvedGlyphOutline(UInkChecks c) + { + var glyph = FilledGlyphStroke.TryCreate(new EllipseGeometry(new Point(50, 50), 30, 40), Pen()); + var page = new UInkPageInput + { + Canvas = UInkIccMapper.BuildCanvas("", "", "aaaaaaaa-0000-4000-8000-000000000001", 0, 1, null, null) + }; + var machine = new TimeMachine(); + machine.CommitStrokeUserInputHistory(new StrokeCollection { glyph }); + new UInkHistorySnapshot(machine.GetAppliedHistorySnapshot()).CaptureStrokes(page, null); + var reasons = new System.Collections.Generic.List(); + var doc = UInkIccMapper.BuildDocument("aaaaaaaa-0000-4000-8000-000000000002", null, null, new[] { page }, 0, note: reasons.Add); + var ink = doc.Canvases.Single().Blocks.Single() as UInkInk; + c.That(ink != null && ink.Points.Length > 4, "fallback uses the curved outline"); + c.That(reasons.Contains("glyphOutline"), "glyph fallback diagnostic"); + } + + private static void RecognizedPressure(UInkChecks c) + { + var points = new StylusPointCollection + { + new StylusPoint(0, 0, 0.3f), + new StylusPoint(10, 0, 0.8f) + }; + var s = new Stroke(points, Pen()); + s.AddPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + Recognize(s, Tool.Line); + var saved = UInkTestApi.SaveStrokesAndReload(new StrokeCollection { s }, 1); + var ink = UInkReader.Read(saved.Bytes).Document.Canvases[0].Blocks.Single() as UInkInk; + c.That(ink?.Extra?["icc:recognized/v1"] == "1", "variable pressure stays private-marked Ink"); + c.That(saved.Strokes[0].ContainsPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid), "recognizer guard restored"); + } + + private static void PrimitiveGeometry(UInkChecks c) + { + var da = Pen(); + Point a = new(0, 0), b = new(30, 0); + var arrow = Between(Tool.Arrow, a, b).Preview(da)[0].StylusPoints; + c.Near(15, arrow[2].X, "arrow depth"); + c.Near(-10, arrow[2].Y, "arrow first wing"); + c.Near(10, arrow[4].Y, "arrow second wing"); + var dashed = Between(Tool.Dash, a, b).Preview(da); + c.Equal(3, dashed.Count, "dash count"); + c.Near(5, dashed[0].StylusPoints[1].X, "first dash end"); + c.Near(13.8, dashed[1].StylusPoints[0].X, "second dash start"); + c.Near(30, dashed[2].StylusPoints[1].X, "last dash clipped"); + var dots = Between(Tool.Dot, a, b).Preview(da); + c.Equal(4, dots.Count, "dot count"); + c.Equal(1, dots[2].StylusPoints.Count, "dot native point count"); + c.Near(16.56, dots[2].StylusPoints[0].X, "third dot"); + c.Near(0.8, dots[2].StylusPoints[0].PressureFactor, "dot pressure"); + var axes = IccShapeTools.Axes(17, a, new Point(100, -90), true, da); + c.That(axes.Count > 3, "coordinate tick marks"); + c.Near(-95 / 1.76, axes[2].StylusPoints[1].X, "Z axis endpoint"); + var circle = Between(Tool.Ellipse, a, new Point(80, 80)).Preview(da)[0]; + c.Equal(629, circle.StylusPoints.Count, "ICC angle step"); + c.Near(40 + 40 * Math.Sin(1.57), circle.StylusPoints[157].Y, "ICC sample 157"); + } + + private static void DamagedObject(UInkChecks c) + { + var strokes = Build(9, out _); + Commit(strokes, 9); + strokes[0].DrawingAttributes.Color = Colors.Red; + var saved = UInkTestApi.SaveStrokesAndReload(strokes, 1); + var blocks = UInkReader.Read(saved.Bytes).Document.Canvases[0].Blocks; + c.That(blocks[0] is UInkInk, "modified part stays Ink"); + c.Equal(11, blocks.OfType().Count(), "intact edges survive"); + c.That(blocks.OfType().All(shape => shape.Object == null), "no dangling object layer"); + } + + private static void RecognizedShapes(UInkChecks c) + { + void Check(Point[] points, Tool kind, int type) + { + var stroke = new Stroke(new StylusPointCollection(points), Pen()); + stroke.AddPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid, true); + Recognize(stroke, kind); + var saved = UInkTestApi.SaveStrokesAndReload(new StrokeCollection { stroke }, 1); + var shape = UInkReader.Read(saved.Bytes).Document.Canvases[0].Blocks.Single() as UInkShape; + c.Equal(type, shape?.ShapeType ?? -1, "recognized geometry"); + c.That(saved.Strokes[0].ContainsPropertyData(ModernInkAnalyzer.ShapeStrokePropertyGuid), "recognized Shape restored"); + SameStrokes(c, new StrokeCollection { stroke }, saved.Strokes); + } + + Check(new[] { new Point(0, 0), new Point(3, 0), new Point(6, 0) }, Tool.Line, 0); + Check(new[] { new Point(0, 0), new Point(4, 0), new Point(2, 3), new Point(0, 0) }, Tool.Polygon, 6); + Check(new[] { new Point(0, 0), new Point(4, 0), new Point(4, 3), new Point(0, 3), new Point(0, 0) }, Tool.Polygon, 2); + } + + private static void HyperbolaDeviation(UInkChecks c) + { + var strokes = Hyperbola(new Point(0, 0), 2, 12, 6, 80, true, 1).Preview(Pen()); + Commit(strokes, 24); + c.That(TryExport(strokes, 0, new UInkCoordinateMap(3, 3), out _, out var shape), "hyperbola exported"); + var path = ((UInkLineGeometry)shape.Geometry).Points; + for (int i = 1; i < path.Count; i++) + { + var p = path[i - 1]; + var q = path[i]; + double t = (Math.Asinh(p.Y / 36.0) + Math.Asinh(q.Y / 36.0)) / 2; + var mid = new Point(6 * Math.Cosh(t), 36 * Math.Sinh(t)); + var chord = new Point((p.X + q.X) / 2, (p.Y + q.Y) / 2); + c.That((mid - chord).Length <= 0.25001, "hyperbola device-space deviation"); + } + } + + private static void PendingShapeUndo(UInkChecks c) + { + string dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "UInkPendingShape_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + var workspace = new UInkWorkspace { Guid = UInkTestEncoder.WorkspaceGuid, + WorkspaceType = (int)UInkWorkspaceType.Whiteboard, CurrentPageIndex = 1 }; + UInkPageInput Page(uint n) => new() { Canvas = UInkIccMapper.BuildCanvas(workspace.Guid, "", + UInkTestEncoder.PageGuid(n), n, n + 1, null, null) }; + var context = new UInkCaptureContext { Workspace = workspace, DpiX = 1, DpiY = 1 }; + var first = Page(0); + var dashed = Build(8, out _); + var machine = new TimeMachine(); + MainWindow.CommitDrawnShape(machine, dashed, 8); + machine.CommitStrokeUserInputHistory(new StrokeCollection + { + new Stroke(new StylusPointCollection { new StylusPoint(5, 4) }), + new Stroke(new StylusPointCollection { new StylusPoint(6, 4) }) + }); + new UInkHistorySnapshot(machine.GetAppliedHistorySnapshot()).CaptureStrokes(first, null); + context.Pages.Add(first); + context.Pages.Add(Page(1)); + string file = System.IO.Path.Combine(dir, "source.uink"); + context.Save(file, false); + var index = UInkIccMapper.BuildPageIndex(UInkReader.Read(file, new UInkReadOptions { MaterializeContent = false }), 1, 1); + c.That(!index.Pages[0].IsMaterialized, "dashed sibling page initially lazy"); + var deferred = new UInkCaptureContext { Workspace = workspace, DpiX = 1, DpiY = 1 }; + var page = Page(0); + deferred.CapturePendingPage(page, index.Pages[0], UInkCoordinateMap.Identity); + deferred.Pages.Add(page); + string copy = System.IO.Path.Combine(dir, "copy.uink"); + deferred.Save(copy, false); + var blocks = UInkReader.Read(copy).Document.Canvases[0].Blocks; + c.Equal(3, blocks.Count, "one dash followed by a pair of Ink strokes"); + c.That(blocks[0] is UInkShape && blocks[1] is UInkInk && blocks[0].UndoId != blocks[1].UndoId && + blocks[1].UndoId == blocks[2].UndoId, + "native expansion preserves following stroke owner"); + } + finally { Directory.Delete(dir, true); } + } + + private static void PublicDashPhase(UInkChecks c) + { + var line = new UInkShape + { + Geometry = new UInkLineGeometry + { + Points = + { + new UInkShapePoint(), + new UInkShapePoint + { + X = 30 + } + } + }, + Stroke = new UInkStroke + { + Width = 2, + DashArray = new() + { + 5, + 5 + }, + DashOffset = 3 + } + }; + UInkConversion.BlockToStroke(line, UInkCoordinateMap.Identity, null, out var parts); + c.Equal(4, parts.Count, "positive phase run count"); + c.Near(2, parts[0].StylusPoints[^1].X, "first shortened dash"); + c.Near(7, parts[1].StylusPoints[0].X, "second dash start"); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkSuites.cs b/InkCanvas.Calibration.Tests/UInk/UInkSuites.cs new file mode 100644 index 000000000..f22a03e88 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkSuites.cs @@ -0,0 +1,251 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Threading; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal sealed class UInkChecks + { + public readonly List Failures = new(); + internal string SkipReason { get; set; } + + public void That(bool condition, string reason) + { + if (!condition) Failures.Add(reason); + } + + public void Equal(T expected, T actual, string label) + { + if (!EqualityComparer.Default.Equals(expected, actual)) + Failures.Add(FormattableString.Invariant($"{label}: expected {expected}, got {actual}")); + } + + public void Near(double expected, double? actual, string label, double tolerance = 1e-4) + { + if (!actual.HasValue || !double.IsFinite(actual.Value) || Math.Abs(expected - actual.Value) > tolerance) + Failures.Add(FormattableString.Invariant($"{label}: expected {expected:G9} ± {tolerance:G3}, got {actual:G9}")); + } + + public void Floats(float[] expected, float[] actual, string label, double tolerance = 1e-4) + { + Equal(expected?.Length ?? 0, actual?.Length ?? 0, label + " length"); + if (expected == null || actual == null) return; + for (int i = 0; i < Math.Min(expected.Length, actual.Length); i++) + Near(expected[i], actual[i], $"{label}[{i}]", tolerance); + } + } + + internal sealed class UInkSuite + { + private readonly string _name; + private int _passed, _failed, _skipped; + + public UInkSuite(string name) => _name = name; + + // 诊断用:UINK_ONLY=名称1,名称2 时只运行名称包含任一子串的用例。 + private static readonly string[] OnlyFilter = + Environment.GetEnvironmentVariable("UINK_ONLY")?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + public bool Test(string name, Action test) + { + if (UInkSuites.IsChild + ? !string.Equals(name, Environment.GetEnvironmentVariable("UINK_ONLY"), StringComparison.Ordinal) + : OnlyFilter is { Length: > 0 } && !Array.Exists(OnlyFilter, f => name.Contains(f, StringComparison.OrdinalIgnoreCase))) + return true; + var checks = new UInkChecks(); + try { test(checks); } + catch (Exception ex) { checks.Failures.Add(ex.GetBaseException().ToString()); } + + if (checks.Failures.Count == 0) + { + if (checks.SkipReason != null) + { + _skipped++; + Console.WriteLine("SKIP " + name + ": " + checks.SkipReason); + return true; + } + _passed++; + Console.WriteLine("PASS " + name); + return true; + } + _failed++; + Console.WriteLine("FAIL " + name + ": " + string.Join(" | ", checks.Failures)); + return false; + } + + public int Finish() + { + Console.WriteLine(FormattableString.Invariant($"UInk {_name}: {_passed} passed, {_failed} failed, {_skipped} skipped")); + return _failed == 0 ? 0 : 1; + } + } + + internal static class UInkSuites + { + private static readonly string[] Switches = + { "--uink-fixtures", "--uink-roundtrip", "--uink-robust", "--uink-bench", "--uink-all" }; + + private static readonly List WorkerThreads = new(); + + internal static void ObserveWorker(Thread worker) => WorkerThreads.Add(worker); + + internal static bool IsChild => Environment.GetEnvironmentVariable("UINK_CHILD") == "1"; + + internal static void RunIsolated(UInkSuite suite, string name, Action test) + { + // PDF 与后续 WPF 渲染分属不同进程,避免驱动在套件退出时挂起。 + suite.Test(name, IsChild ? test : checks => + { + var start = new ProcessStartInfo(Environment.ProcessPath) + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, + CreateNoWindow = true + }; + if (string.Equals(Path.GetFileNameWithoutExtension(start.FileName), "dotnet", StringComparison.OrdinalIgnoreCase)) + start.ArgumentList.Add(typeof(UInkSuites).Assembly.Location); + start.ArgumentList.Add("--uink-roundtrip"); + start.Environment["UINK_CHILD"] = "1"; + start.Environment["UINK_ONLY"] = name; + using var child = Process.Start(start); + var output = child.StandardOutput.ReadToEndAsync(); + var errors = child.StandardError.ReadToEndAsync(); + if (!Task.WhenAll(child.WaitForExitAsync(), output, errors).Wait(TimeSpan.FromSeconds(120))) + { + checks.That(false, "isolated test timeout (120 s)"); + try { child.Kill(); } + catch (InvalidOperationException) when (child.HasExited) { } + return; + } + + string[] lines = output.Result.Split('\n'); + if (child.ExitCode == 0 && Array.Exists(lines, line => line.TrimEnd('\r') == "PASS " + name)) + return; + string failure = Array.Find(lines, line => line.StartsWith("FAIL " + name + ":", StringComparison.Ordinal)); + string tail = (output.Result + Environment.NewLine + errors.Result).Trim(); + if (tail.Length > 2000) tail = tail.Substring(tail.Length - 2000); + checks.That(false, $"isolated exit {child.ExitCode}: {failure?.TrimEnd() ?? tail}"); + }); + } + + public static bool IsRequested(string[] args) => Array.Exists(args, arg => Array.IndexOf(Switches, arg) >= 0); + + public static int Run(string[] args, Func runRemaining) + { + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + + string fixtureDir = Path.Combine(AppContext.BaseDirectory, "TestData", "UInk", "v11"); + string outDir = Path.Combine(Path.GetTempPath(), "ICC-UInk-bench"); + bool fixtures = false, roundtrip = false, robust = false, bench = false; + int rounds = 5; + ushort version = 11; + for (int i = 0; i < args.Length; i++) + { + switch (args[i]) + { + case "--uink-fixtures": + fixtures = true; + fixtureDir = OptionalPath(args, ref i, fixtureDir); + break; + case "--uink-roundtrip": roundtrip = true; break; + case "--uink-robust": robust = true; break; + case "--uink-bench": + bench = true; + outDir = OptionalPath(args, ref i, outDir); + break; + case "--uink-all": fixtures = roundtrip = robust = true; break; + case "--rounds": + if (++i == args.Length || !int.TryParse(args[i], NumberStyles.None, CultureInfo.InvariantCulture, out rounds) || rounds < 1) + return UsageError("--rounds requires a positive integer."); + break; + case "--version": + if (++i == args.Length || !ushort.TryParse(args[i], NumberStyles.None, CultureInfo.InvariantCulture, out version) + || (version != 10 && version != 11)) + return UsageError("--version requires 10 or 11."); + break; + default: return UsageError("Unknown UInk argument " + args[i]); + } + } + + var threadsAtStart = SnapshotNativeThreads(); + int exitCode = 0; + try + { + if (fixtures) exitCode |= UInkFixtureTests.Run(fixtureDir); + if (roundtrip) exitCode |= UInkRoundtripTests.Run(); + if (robust) exitCode |= UInkRobustTests.Run(fixtureDir); + if (bench) exitCode |= UInkBench.Run(outDir, rounds, version); + if (!IsChild) exitCode |= runRemaining(); + return exitCode; + } + finally + { + try + { + // 测试入口没有调用 Application.Run。先服务应用退出,再主动释放 STA 调度器。 + var dispatcher = Dispatcher.FromThread(Thread.CurrentThread); + if (dispatcher != null && !dispatcher.HasShutdownStarted) + { + Application.Current?.Shutdown(exitCode); + dispatcher.Invoke(() => { }, DispatcherPriority.Background); + dispatcher.InvokeShutdown(); + } + } + finally { LogRemainingThreads(threadsAtStart); } + } + } + + private static Dictionary SnapshotNativeThreads() + { + var result = new Dictionary(); + try + { + using var process = Process.GetCurrentProcess(); + foreach (ProcessThread thread in process.Threads) + { + using (thread) + { + try { result.Add(thread.Id, thread.ThreadState); } + catch (InvalidOperationException) { } // 线程可能在枚举后结束。 + } + } + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) + { + Console.Error.WriteLine("UInk thread diagnostics: " + ex.Message); + } + return result; + } + + private static void LogRemainingThreads(Dictionary threadsAtStart) + { + foreach (var worker in WorkerThreads) + if (worker.IsAlive && !worker.IsBackground) + Console.Error.WriteLine($"UInk foreground thread still alive: {worker.ManagedThreadId} ({worker.Name ?? "unnamed"})"); + WorkerThreads.Clear(); + + // .NET 6 不能枚举任意托管 Thread;列出新增 OS 线程以协助定位 WinRT/WPF,状态不代表前后台。 + var additional = new List(); + foreach (var thread in SnapshotNativeThreads()) + if (!threadsAtStart.ContainsKey(thread.Key)) additional.Add($"{thread.Key} ({thread.Value})"); + if (additional.Count != 0) + Console.Error.WriteLine("UInk native thread candidates at exit: " + string.Join(", ", additional)); + } + + private static string OptionalPath(string[] args, ref int index, string fallback) => + index + 1 < args.Length && !args[index + 1].StartsWith("--", StringComparison.Ordinal) + ? args[++index] : fallback; + + private static int UsageError(string reason) + { + Console.WriteLine("FAIL UInk arguments: " + reason); + return 2; + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkTestApi.cs b/InkCanvas.Calibration.Tests/UInk/UInkTestApi.cs new file mode 100644 index 000000000..1f3278bb8 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkTestApi.cs @@ -0,0 +1,363 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using Ink_Canvas; +using System.Windows.Ink; +using System.Windows.Media; +using Ink_Canvas.UInk; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal enum UInkTestStatus { Ok, Rejected, Recovered } + internal enum UInkTestItemKind { Ink, Shape, Media } + + internal sealed class UInkTestLoadResult + { + public UInkTestStatus Status { get; set; } + public int? HeaderVersion { get; set; } + public string HeaderGuid { get; set; } + public string Error { get; set; } + public bool Truncated { get; set; } + public bool StoppedOnCorruption { get; set; } + public int SkippedBlocks { get; set; } + public bool RequiresSaveAs { get; set; } + public string SelectedWorkspaceType { get; set; } + public string HostId { get; set; } + public int CurrentPageDisplayIndex { get; set; } + public List Pages = new(); + public List RetainedPages = new(); + public List<(string Guid, int WorkspaceType, int PageCount)> UndisplayedWorkspaces = new(); + } + + internal sealed class UInkTestPage + { + public string PageGuid { get; set; } + public uint OriginalPageIndex { get; set; } + public int DisplayIndex { get; set; } + public uint PageNumber { get; set; } + public int? SlideId { get; set; } + public int? Binding { get; set; } + public int? PageState { get; set; } + public int? PageKind { get; set; } + public bool Unbound { get; set; } + public int? SlideIndex { get; set; } + public uint? BackgroundRgb { get; set; } + public int? BackgroundPattern { get; set; } + public (float x, float y, float scale)? Viewport { get; set; } + public List Items = new(); + public int UndoGroupCount { get; set; } + } + + internal sealed class UInkTestItem + { + public UInkTestItemKind Kind { get; set; } + public int FileInkType { get; set; } + public float FileOpacity { get; set; } + public int InkType { get; set; } + public uint ColorRgb { get; set; } + public float Opacity { get; set; } + public int PointCount { get; set; } + public float[] AbsX { get; set; } + public float[] AbsY { get; set; } + public float[] Width { get; set; } + public int? NibShape { get; set; } + public float? NibAspect { get; set; } + public string[] DisplayDiagnostics { get; set; } = Array.Empty(); + public int Cap { get; set; } + public int ShapeType { get; set; } + public bool HasFill { get; set; } + public bool HasStroke { get; set; } + public uint? FillColorRgb { get; set; } + public float? FillOpacity { get; set; } + public float? StrokeWidth { get; set; } + public float? DashOffset { get; set; } + public float? CornerRadiusX { get; set; } + public float? CornerRadiusY { get; set; } + public int LineCap { get; set; } + public int LineJoin { get; set; } + public float[] Dash { get; set; } + public int StartMarker { get; set; } + public int EndMarker { get; set; } + public string ObjectId { get; set; } + public int ObjectPartIndex { get; set; } + public string MediaPath { get; set; } + public string MediaMime { get; set; } + // 局部框是应用 viewport 前的尺寸,矩阵保存合成 viewport 后的 Device 变换。 + public float[] MediaTransform { get; set; } + public float? MediaWidth { get; set; } + public float? MediaHeight { get; set; } + public float[] MediaCrop { get; set; } + public float MediaOpacity { get; set; } + public int MediaFit { get; set; } + public bool MediaResourceAvailable { get; set; } + public bool MediaPlaceholder { get; set; } + public uint UndoGroupOrdinal { get; set; } + } + + internal readonly record struct UInkTestTimings( + double ReadBytesMs, double DecodeMs, double MapToPagesMs, double BuildStrokesMs); + + internal static class UInkTestApi + { + public static UInkStructure ReadStructure(string path) => new(UInkReader.Read(path)); + + public static UInkTestLoadResult Load(string path) => LoadTimed(path).Result; + + public static UInkTestLoadResult Load(string path, Func resolveSlide) => LoadTimed(path, resolveSlide).Result; + + public static (UInkTestLoadResult Result, UInkTestTimings Timings) LoadTimed(string path, Func resolveSlide = null) + { + var result = new UInkTestLoadResult { Status = UInkTestStatus.Rejected }; + double readMs = 0, decodeMs = 0, mapMs = 0; + var clock = Stopwatch.StartNew(); + var build = new Stopwatch(); + var decodeContent = new Stopwatch(); + try + { + if (new FileInfo(path).Length > UInkReader.MaxFileBytes) + { + result.RequiresSaveAs = true; + result.Error = "UInk file exceeds the read budget."; + return (result, new UInkTestTimings(clock.Elapsed.TotalMilliseconds, 0, 0, 0)); + } + byte[] bytes = File.ReadAllBytes(path); + readMs = clock.Elapsed.TotalMilliseconds; + clock.Restart(); + var decoded = UInkReader.Read(bytes, new UInkReadOptions { MaterializeContent = false }); + var document = decoded.Document; + result.Truncated = decoded.TruncatedTail; + result.StoppedOnCorruption = decoded.StoppedOnCorruption; + result.SkippedBlocks = decoded.SkippedBlocks; + result.RequiresSaveAs = decoded.RequiresSaveAs; + decodeMs = clock.Elapsed.TotalMilliseconds; + if (document?.Header == null) + { + result.Error = "UInkReader rejected the header or document."; + return (result, new UInkTestTimings(readMs, decodeMs, 0, 0)); + } + + result.HeaderVersion = document.Header.Version; + result.HeaderGuid = document.Header.Guid; + clock.Restart(); + MapPages(path, decoded, result, build, decodeContent, resolveSlide); + result.SkippedBlocks = decoded.SkippedBlocks; + result.RequiresSaveAs = decoded.RequiresSaveAs; + // 延迟解码仍计入 Decode,使 Bench A 的 Map 阶段与基线可比。 + decodeMs += decodeContent.Elapsed.TotalMilliseconds; + mapMs = clock.Elapsed.TotalMilliseconds - build.Elapsed.TotalMilliseconds - decodeContent.Elapsed.TotalMilliseconds; + result.Status = decoded.Status == UInkReadStatus.Recovered ? UInkTestStatus.Recovered : UInkTestStatus.Ok; + } + catch (Exception ex) + { + result.Pages.Clear(); + result.RetainedPages.Clear(); + result.Error = ex.ToString(); + } + return (result, new UInkTestTimings(readMs, decodeMs, mapMs, build.Elapsed.TotalMilliseconds)); + } + + private static void MapPages(string path, UInkReadResult read, UInkTestLoadResult result, Stopwatch build, + Stopwatch decodeContent, Func resolveSlide) + { + void Decode(UInkCanvasRecord record) + { + decodeContent.Start(); + try { UInkReader.MaterializeContent(record); } + finally { decodeContent.Stop(); } + } + var diagnostics = new Dictionary>(); + IUInkContentBlock displayBlock = null; + Action addNote = null; + void DisplayNote(string reason) + { + if (!diagnostics.TryGetValue(displayBlock, out var notes)) + diagnostics.Add(displayBlock, notes = new List()); + notes.Add(reason); + addNote(reason); + } + Action recordDisplayNote = DisplayNote; + Stroke Convert(IUInkContentBlock block, UInkCoordinateMap map, Action note, out StrokeCollection parts) + { + build.Start(); + displayBlock = block; + addNote = note; + try { return UInkConversion.BlockToStroke(block, map, recordDisplayNote, out parts); } + finally { build.Stop(); } + } + var projection = UInkPageProjection.Build(read, 1, 1, resolveSlide, Convert, Decode); + result.SelectedWorkspaceType = ((UInkWorkspaceType)(projection.Workspace?.WorkspaceType ?? 0)).ToString(); + result.HostId = projection.Workspace?.HostId; + result.CurrentPageDisplayIndex = projection.CurrentPageDisplayIndex; + result.UndisplayedWorkspaces.AddRange(projection.UndisplayedWorkspaces); + string cachePath = Path.Combine(Path.GetTempPath(), "UInkFixture_" + Guid.NewGuid().ToString("N")); + try + { + using var resources = UInkMediaRestoreCache.Open(path, cachePath); + foreach (var page in projection.Pages) result.Pages.Add(Inspect(page, resources)); + foreach (var page in projection.RetainedPages) result.RetainedPages.Add(Inspect(page, resources)); + } + finally + { + if (Directory.Exists(cachePath)) Directory.Delete(cachePath, true); + } + + UInkTestPage Inspect(UInkPageData data, UInkMediaRestoreCache resources) + { + data.EnsureMaterialized(); + var canvas = data.Canvas; + var page = new UInkTestPage + { + PageGuid = canvas.PageGuid, OriginalPageIndex = canvas.PageIndex, + DisplayIndex = data.DisplayIndex, PageNumber = canvas.PageNumber, + PageState = canvas.PageState ?? 0, PageKind = data.PageKind, Binding = data.Binding, + SlideId = data.SlideId, SlideIndex = data.SlideIndex, Unbound = data.IsUnbound, + BackgroundRgb = canvas.Background?.Color?.Fallback, BackgroundPattern = canvas.Background?.Pattern ?? 0, + Viewport = canvas.Viewport == null ? null : (canvas.Viewport.X, canvas.Viewport.Y, canvas.Viewport.Scale), + UndoGroupCount = data.History.Length + }; + MainWindow.PrepareUInkMediaFiles(data, resources); + var coordinates = UInkMediaMapper.PageCoordinates(canvas, 1, 1); + int mediaIndex = 0; + foreach (var (block, stroke, ordinal) in data.Items) + { + var item = block is UInkMedia media + ? MediaItem(media, coordinates, data.MediaFiles[mediaIndex++] != null) + : StrokeItem(block, stroke, (uint)ordinal); + if (block is UInkShape { Geometry: UInkLineGeometry line }) + { + item.PointCount = line.Points.Count; + item.AbsX = new float[line.Points.Count]; + item.AbsY = new float[line.Points.Count]; + for (int j = 0; j < line.Points.Count; j++) + { + var point = coordinates.ToDip(line.Points[j].X, line.Points[j].Y); + item.AbsX[j] = (float)point.X; + item.AbsY[j] = (float)point.Y; + } + } + item.UndoGroupOrdinal = (uint)ordinal; + if (diagnostics.TryGetValue(block, out var notes)) item.DisplayDiagnostics = notes.ToArray(); + page.Items.Add(item); + } + return page; + } + } + + private static UInkTestItem MediaItem(UInkMedia media, UInkCoordinateMap coordinates, bool available) + { + var crop = media.Crop; + return new UInkTestItem + { + Kind = UInkTestItemKind.Media, + MediaPath = media.Path, + MediaMime = media.MimeType, + MediaTransform = media.Transform == null ? null : UInkCoordinateMap.Identity.MediaMatrixFromDip( + coordinates.MapMediaMatrix(media.Transform)), + MediaWidth = media.Width, + MediaHeight = media.Height, + MediaFit = media.Fit ?? 0, + MediaCrop = crop == null ? null : new[] { crop.X, crop.Y, crop.Width, crop.Height }, + MediaOpacity = media.Opacity ?? 1f, + MediaResourceAvailable = available, + MediaPlaceholder = !available + }; + } + + private static UInkTestItem StrokeItem(IUInkContentBlock block, Stroke stroke, uint ordinal) + { + var da = stroke.DrawingAttributes; + var item = new UInkTestItem + { + ColorRgb = Rgb(da.Color), + Opacity = da.Color.A / 255f, + UndoGroupOrdinal = ordinal, + }; + if (block is UInkInk ink) + { + item.FileInkType = ink.InkType; + item.FileOpacity = ink.Opacity; + item.Cap = ink.Cap ?? 0; + item.Kind = UInkTestItemKind.Ink; + item.InkType = da.IsHighlighter ? 2 : 1; + item.NibShape = da.StylusTip == StylusTip.Rectangle ? 1 : 0; + if (item.NibShape == 1) item.NibAspect = (float)(da.Width / da.Height); + item.Width = new float[stroke.StylusPoints.Count]; + } + else if (block is UInkShape shape) + { + // SHAPE-3/4/7/9/11:从已解码的公共字段检查文件,显示回退另行记录。 + item.Kind = UInkTestItemKind.Shape; + item.ShapeType = shape.ShapeType; + item.HasStroke = shape.Stroke != null; + item.HasFill = shape.Fill != null; + item.ColorRgb = (shape.Stroke?.Color ?? shape.Fill?.Color)?.Fallback ?? 0; + item.Opacity = shape.Stroke?.Opacity ?? shape.Fill?.Opacity ?? 1; + item.StrokeWidth = shape.Stroke?.Width; + item.FillColorRgb = shape.Fill?.Color?.Fallback; + item.FillOpacity = shape.Fill?.Opacity; + item.Dash = shape.Stroke?.DashArray?.ToArray(); + item.DashOffset = shape.Stroke?.DashOffset; + item.StartMarker = shape.Stroke?.StartMarker ?? 0; + item.EndMarker = shape.Stroke?.EndMarker ?? 0; + item.LineCap = shape.Stroke?.LineCap ?? 0; + item.LineJoin = shape.Stroke?.LineJoin ?? 0; + item.CornerRadiusX = (shape.Geometry as UInkRectGeometry)?.CornerRadiusX; + item.CornerRadiusY = (shape.Geometry as UInkRectGeometry)?.CornerRadiusY; + item.ObjectId = shape.Object?.Id ?? shape.Object?.Ref; + item.ObjectPartIndex = (int)(shape.Object?.PartIndex ?? 0); + } + + var points = stroke.StylusPoints; + item.PointCount = points.Count; + item.AbsX = new float[points.Count]; + item.AbsY = new float[points.Count]; + for (int i = 0; i < points.Count; i++) + { + var point = points[i]; + item.AbsX[i] = (float)point.X; + item.AbsY[i] = (float)point.Y; + if (item.Width != null) + { + double q = da.IgnorePressure ? 1 : 0.25 + 1.5 * point.PressureFactor; + item.Width[i] = (float)(q * da.Height); + } + } + return item; + } + + private static uint Rgb(Color color) => (uint)((color.R << 16) | (color.G << 8) | color.B); + + public static (StrokeCollection Strokes, byte[] Bytes) SaveStrokesAndReload(StrokeCollection strokes, double dpiScale) + { + var (pages, bytes) = SavePagesAndReload(new[] { strokes }, dpiScale); + return (pages.Count == 0 ? new StrokeCollection() : pages[0], bytes); + } + + public static (List Pages, byte[] Bytes) SavePagesAndReload( + IReadOnlyList pages, double dpiScale) + { + var inputs = new List(pages.Count); + for (int i = 0; i < pages.Count; i++) + { + string pageGuid = FormattableString.Invariant($"cccccccc-0000-4000-8000-{i + 1:x12}"); + inputs.Add(new UInkPageInput + { + Canvas = UInkIccMapper.BuildCanvas("", "", pageGuid, (uint)i, (uint)i + 1, null, null), + Strokes = pages[i], + }); + } + + var document = UInkIccMapper.BuildDocument("ffffffff-0000-4000-8000-000000000000", null, null, inputs, 0, dpiScale, dpiScale); + using var stream = new MemoryStream(); + UInkWriter.Save(document, stream); + byte[] bytes = stream.ToArray(); + var loaded = UInkReader.Read(bytes, new UInkReadOptions { MaterializeContent = false }); + // 读回失败时保留原始字节,使测试仍能定位写入标记或字段的错误。 + if (loaded.Document == null) return (new List(), bytes); + var mapped = UInkIccMapper.BuildPageIndex(loaded, dpiScale, dpiScale); + foreach (var page in mapped.Pages) page.EnsureMaterialized(); + return (mapped.Pages.ConvertAll(page => page.FinalStrokes), bytes); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkTestEncoder.cs b/InkCanvas.Calibration.Tests/UInk/UInkTestEncoder.cs new file mode 100644 index 000000000..0290a234f --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkTestEncoder.cs @@ -0,0 +1,214 @@ +using System; +using System.Buffers; +using System.IO; +using MessagePack; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal readonly record struct UInkTestPoint(float X, float Y, float Width); + + internal enum UInkTestInkFault { None, InvalidWidth, DuplicateInkType, HeterogeneousExtra } + + internal sealed class UInkTestEncoder + { + public const string HeaderGuid = "ffffffff-0000-4000-8000-000000000000"; + public const string WorkspaceGuid = "aaaaaaaa-0000-4000-8000-000000000001"; + private readonly Stream _stream; + private readonly ArrayBufferWriter _buffer = new(); + + public UInkTestEncoder(Stream stream) => _stream = stream; + + public static string PageGuid(uint pageIndex) => + FormattableString.Invariant($"cccccccc-0000-4000-8000-{pageIndex + 1:x12}"); + + public void Header(ushort version, uint pages, string guid = HeaderGuid) + { + var writer = new MessagePackWriter(_buffer); + // HDR-1、TYPE-1:即使值很小,整数也用字段规定的原始标记与位宽。 + writer.WriteArrayHeader(7); + writer.WriteUInt16(0); + writer.WriteUInt16(version); + writer.Write(guid); + writer.WriteUInt32(1); + writer.WriteUInt32(1); + writer.WriteUInt32(pages); + writer.WriteUInt64(1795478400UL); + Flush(ref writer); + } + + public void HeaderExtension(string deviceGuid = null) + { + var writer = new MessagePackWriter(_buffer); + Begin(ref writer, deviceGuid == null ? 2 : 3, 1); + writer.Write("workspaces"); + writer.WriteArrayHeader(1); + writer.WriteMapHeader(3); + writer.Write("guid"); writer.Write(WorkspaceGuid); + writer.Write("workspaceType"); writer.WriteInt32(1); + writer.Write("currentPageIndex"); writer.WriteUInt32(0); + if (deviceGuid != null) + { + writer.Write("devices"); writer.WriteArrayHeader(1); + writer.WriteMapHeader(6); + writer.Write("guid"); writer.Write(deviceGuid); + writer.Write("deviceType"); writer.WriteInt32(0); + writer.Write("x"); writer.WriteInt32(0); + writer.Write("y"); writer.WriteInt32(0); + writer.Write("width"); writer.WriteUInt32(1920); + writer.Write("height"); writer.WriteUInt32(1080); + } + Flush(ref writer); + } + + public void Canvas(uint pageIndex, bool whiteboard = false, string workspaceGuid = null, string deviceGuid = null) + { + var writer = new MessagePackWriter(_buffer); + if (whiteboard) workspaceGuid ??= WorkspaceGuid; + Begin(ref writer, 6 + (workspaceGuid != null ? 1 : 0) + (deviceGuid != null ? 1 : 0), 2); + writer.Write("pageGuid"); writer.Write(PageGuid(pageIndex)); + writer.Write("pageIndex"); writer.WriteUInt32(pageIndex); + writer.Write("pageNumber"); writer.WriteUInt32(pageIndex + 1); + writer.Write("layerIndex"); writer.WriteUInt32(0); + writer.Write("layerNumber"); writer.WriteUInt32(0); + if (workspaceGuid != null) { writer.Write("workspaceGuid"); writer.Write(workspaceGuid); } + if (deviceGuid != null) { writer.Write("deviceGuid"); writer.Write(deviceGuid); } + Flush(ref writer); + } + + public void Ink(uint contentId, uint undoId, uint rgb, ReadOnlySpan points, + UInkTestInkFault fault = UInkTestInkFault.None) + { + var writer = new MessagePackWriter(_buffer); + int fields = 8; + if (fault is UInkTestInkFault.DuplicateInkType or UInkTestInkFault.HeterogeneousExtra) fields++; + BeginContent(ref writer, fields, 3, contentId, undoId); + writer.Write("inkType"); writer.WriteInt32(1); + if (fault == UInkTestInkFault.DuplicateInkType) + { + writer.Write("inkType"); writer.WriteInt32(2); + } + writer.Write("color"); Color(ref writer, rgb); + writer.Write("opacity"); writer.Write(1f); + writer.Write("texture"); writer.WriteInt32(0); + writer.Write("points"); writer.WriteArrayHeader(points.Length); + + // INK-4:调用方提供绝对坐标,首点之后改写为相对上一点的位移。 + float x = 0, y = 0; + for (int i = 0; i < points.Length; i++) + { + var point = points[i]; + writer.WriteMapHeader(3); + writer.Write("x"); writer.Write(point.X - x); + writer.Write("y"); writer.Write(point.Y - y); + writer.Write("width"); + if (i == 0 && fault == UInkTestInkFault.InvalidWidth) writer.Write(false); + else writer.Write(point.Width); + x = point.X; + y = point.Y; + } + + if (fault == UInkTestInkFault.HeterogeneousExtra) + { + writer.Write("extra"); + writer.WriteMapHeader(2); + writer.Write("test:nested"); + writer.WriteMapHeader(1); + writer.Write("value"); writer.WriteInt32(5); + writer.Write("test:integer"); writer.WriteInt32(42); + } + Flush(ref writer); + } + + public void Shape(uint contentId, uint undoId, uint rgb, float endX = 90f) + { + var writer = new MessagePackWriter(_buffer); + BeginContent(ref writer, 6, 5, contentId, undoId); + writer.Write("shapeType"); writer.WriteInt32(0); + writer.Write("geometry"); writer.WriteMapHeader(1); + writer.Write("points"); writer.WriteArrayHeader(2); + ShapePoint(ref writer, 20f, 40f); + ShapePoint(ref writer, endX, 40f); + writer.Write("stroke"); writer.WriteMapHeader(3); + writer.Write("color"); Color(ref writer, rgb); + writer.Write("width"); writer.Write(4f); + writer.Write("opacity"); writer.Write(1f); + Flush(ref writer); + } + + public void Media(uint contentId, uint undoId, string path, string mime = "image/png") + { + var writer = new MessagePackWriter(_buffer); + BeginContent(ref writer, 8, 4, contentId, undoId); + writer.Write("path"); writer.Write(path); + writer.Write("mimeType"); writer.Write(mime); + writer.Write("width"); writer.Write(512f); + writer.Write("height"); writer.Write(512f); + writer.Write("transform"); writer.WriteArrayHeader(6); + writer.Write(1f); writer.Write(0f); writer.Write(0f); + writer.Write(1f); writer.Write(100f); writer.Write(50f); + Flush(ref writer); + } + + public void Clear(uint contentId, uint undoId) + { + var writer = new MessagePackWriter(_buffer); + BeginContent(ref writer, 3, 6, contentId, undoId); + Flush(ref writer); + } + + public void InkWithUnreadableField(uint contentId, bool unreadableType) + { + var writer = new MessagePackWriter(_buffer); + writer.WriteMapHeader(3); + writer.Write("type"); + if (unreadableType) writer.Write(false); + else writer.WriteUInt16(3); + writer.Write("contentId"); writer.WriteUInt32(contentId); + writer.Write("undoId"); writer.Write(false); + Flush(ref writer); + } + + public void Unknown() + { + var writer = new MessagePackWriter(_buffer); + Begin(ref writer, 2, 7); + writer.Write("payload"); writer.WriteArrayHeader(2); + writer.Write("unknown"); + writer.Write(true); + Flush(ref writer); + } + + private static void ShapePoint(ref MessagePackWriter writer, float x, float y) + { + writer.WriteMapHeader(2); + writer.Write("x"); writer.Write(x); + writer.Write("y"); writer.Write(y); + } + + private static void Color(ref MessagePackWriter writer, uint rgb) + { + writer.WriteMapHeader(1); + writer.Write("fallback"); writer.WriteUInt32(rgb); + } + + private static void BeginContent(ref MessagePackWriter writer, int count, ushort type, uint contentId, uint undoId) + { + Begin(ref writer, count, type); + writer.Write("contentId"); writer.WriteUInt32(contentId); + writer.Write("undoId"); writer.WriteUInt32(undoId); + } + + private static void Begin(ref MessagePackWriter writer, int count, ushort type) + { + writer.WriteMapHeader(count); + writer.Write("type"); writer.WriteUInt16(type); + } + + private void Flush(ref MessagePackWriter writer) + { + writer.Flush(); + _stream.Write(_buffer.WrittenSpan); + _buffer.Clear(); + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkTransactionTests.cs b/InkCanvas.Calibration.Tests/UInk/UInkTransactionTests.cs new file mode 100644 index 000000000..c9a4b29b5 --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkTransactionTests.cs @@ -0,0 +1,728 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Ink_Canvas.Helpers; +using Ink_Canvas.UInk; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal static class UInkTransactionTests + { + internal static int Run() + { + var suite = new UInkSuite("file transaction"); + suite.Test(nameof(ReadPinsCommittedPair), c => InDirectory(d => ReadPinsCommittedPair(c, d))); + suite.Test(nameof(UploadReadsCommittedPair), c => InDirectory(d => UploadReadsCommittedPair(c, d))); + suite.Test("OldAndNewResourceUnion", c => InDirectory(d => OldAndNewResourceUnion(c, d))); + suite.Test("CollisionAndUnreadableOriginal", c => InDirectory(d => CollisionAndUnreadableOriginal(c, d))); + suite.Test("MainReplaceRollback", c => InDirectory(d => MainReplaceRollback(c, d))); + suite.Test("ExtraReplacedBeforeMainFailure", c => InDirectory(d => ExtraReplacedBeforeMainFailure(c, d))); + suite.Test("ExtraMovedToBackupBeforeFailure", c => InDirectory(d => ExtraMovedToBackupBeforeFailure(c, d))); + suite.Test("MainMovedToBackupBeforeFailure", c => InDirectory(d => MainMovedToBackupBeforeFailure(c, d))); + suite.Test("RestoreFailureKeepsBackups", c => InDirectory(d => RestoreFailureKeepsBackups(c, d))); + suite.Test("CompletedMainKeepsUnion", c => InDirectory(d => CompletedMainKeepsUnion(c, d))); + suite.Test("FirstSaveFailurePublishesVerifiedPair", c => InDirectory(d => FirstSaveFailurePublishesVerifiedPair(c, d))); + suite.Test("AliasedDirectorySerializesSaves", c => InDirectory(d => AliasedDirectorySerializesSaves(c, d))); + suite.Test("CorruptTempEntryRefusesCommit", c => InDirectory(d => CorruptTempEntryRefusesCommit(c, d))); + suite.Test("ContentHashRejectsChangedSource", c => InDirectory(d => ContentHashRejectsChangedSource(c, d))); + suite.Test("DuplicateAndUnsafeArchiveEntries", c => InDirectory(d => DuplicateAndUnsafeArchiveEntries(c, d))); + suite.Test("DeclaredAndActualEntrySize", c => InDirectory(d => DeclaredAndActualEntrySize(c, d))); + suite.Test("CentralDirectoryPreflight", c => InDirectory(d => CentralDirectoryPreflight(c, d))); + suite.Test("VerifiedMediaRestoreCache", c => InDirectory(d => VerifiedMediaRestoreCache(c, d))); + suite.Test("CanonicalOrderAndUndo", CanonicalOrderAndUndo); + suite.Test("StableFourLevelCanvasOrder", StableFourLevelCanvasOrder); + suite.Test("StreamRejectsSharedClearGroup", StreamRejectsSharedClearGroup); + suite.Test("PublicFieldEncoding", PublicFieldEncoding); + return suite.Finish(); + } + + private static void InDirectory(Action test) + { + string dir = Path.Combine(Path.GetTempPath(), "ICC-UInk-files-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try { test(dir); } + finally { Directory.Delete(dir, true); } + } + + private static UInkDocument Document(string path) + { + var doc = new UInkDocument { Header = new UInkHeader { Guid = UInkTestEncoder.HeaderGuid } }; + var rec = new UInkCanvasRecord { Canvas = new UInkCanvas { PageGuid = UInkTestEncoder.PageGuid(0), PageNumber = 1 } }; + if (path != null) rec.Blocks.Add(new UInkMedia { ContentId = 99, Path = path, MimeType = "audio/wav" }); + doc.Canvases.Add(rec); + return doc; + } + + private static (string path, string source) Resource(string dir, string name) + { + string source = Path.Combine(dir, name); + File.WriteAllText(source, "RIFF0000WAVE" + name); + return (UInkExtraArchive.ContentHashPath(source, ".WAV"), source); + } + + private static void ReadPinsCommittedPair(UInkChecks c, string dir) + { + var old = Resource(dir, "old"); + var next = Resource(dir, "new"); + string path = Path.Combine(dir, "paired.uink"); + UInkSaveService.SaveFull(Document(old.path), path, new[] { old }); + using var started = new ManualResetEventSlim(); + var reading = UInkSaveService.WithTargetLock(path, () => + { + var pending = Task.Run(() => + { + started.Set(); + return UInkSaveService.OpenReadPair(path); + }); + if (!started.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException("paired read did not start"); + c.That(!pending.Wait(TimeSpan.FromMilliseconds(500)), "paired read waits for the target lock"); + UInkSaveService.SaveFull(Document(next.path), path, new[] { next }); + return pending; + }); + if (!reading.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException("paired read stayed blocked"); + var pair = reading.Result; + using var main = pair.Main; + using var extra = pair.Extra; + c.That(extra != null && pair.ExtraError == null, "committed extra was opened"); + + // 再次替换两个路径后才解码,验证锁外消费的确是刚才固定的两个句柄。 + UInkSaveService.SaveFull(Document(null), path, Array.Empty<(string, string)>()); + var media = (UInkMedia)UInkReader.Read(main, null).Document.Canvases.Single().Blocks.Single(); + c.Equal(next.path, media.Path, "main handle pins the newly committed generation"); + using var archive = new UInkExtraArchive(extra); + c.That(archive.Contains(old.path), "archive handle pins the preceding union before the next replacement"); + string extracted = Path.Combine(dir, "extracted"); + c.That(archive.TryExtractEntry(media.Path, extracted), "paired archive serves the pinned main"); + c.That(File.ReadAllBytes(extracted).SequenceEqual(File.ReadAllBytes(next.source)), "resource bytes match"); + } + + private sealed class SnapshotProvider : IUploadProvider + { + internal readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly List<(string Path, byte[] Bytes)> Received = new(); + public string Name => "snapshot test"; + public bool IsEnabled => true; + + public async Task UploadAsync(string filePath, CancellationToken token = default) + { + await Release.Task.ConfigureAwait(false); + Received.Add((filePath, File.ReadAllBytes(filePath))); + return true; + } + } + + private static void UploadReadsCommittedPair(UInkChecks c, string dir) + { + string main = Path.Combine(dir, "file.uink"); + var a = Resource(dir, "first"); + var b = Resource(dir, "second"); + var provider = new SnapshotProvider(); + var uploads = new List(); + var expected = new List(); + void Queue(string path) + { + expected.Add(File.ReadAllBytes(path + ".extra")); + expected.Add(File.ReadAllBytes(path)); + uploads.Add(UploadHelper.UploadUInkSnapshotAsync(path, new[] { provider }, 0)); + } + + try + { + UInkSaveService.SaveSnapshot(Document(a.path), main, new[] { a }, null, Queue); + UInkSaveService.SaveSnapshot(Document(b.path), main, new[] { b }, null, Queue); + } + finally { provider.Release.TrySetResult(true); } + c.That(Task.WhenAll(uploads).Wait(TimeSpan.FromSeconds(10)), "snapshot transfers complete"); + c.Equal(4, provider.Received.Count, "both pairs uploaded"); + for (int i = 0; i < 4; i++) + { + var received = provider.Received[i]; + c.Equal(i % 2 == 0 ? "file.uink.extra" : "file.uink", Path.GetFileName(received.Path), "publish extra first"); + c.That(expected[i].SequenceEqual(received.Bytes), "uploaded bytes belong to the committed generation"); + c.That(!Directory.Exists(Path.GetDirectoryName(received.Path)), "completed snapshot directory removed"); + } + } + + private static void OldAndNewResourceUnion(UInkChecks c, string dir) + { + var a = Resource(dir, "first"); + var b = Resource(dir, "second"); + c.That(a.path != b.path && a.path.EndsWith(".wav", StringComparison.Ordinal), "hash paths"); + c.Equal(a.path, UInkExtraArchive.ContentHashPath(File.ReadAllBytes(a.source), "wav"), "file and bytes"); + string main = Path.Combine(dir, "file.uink"); + UInkSaveService.SaveFull(Document(a.path), main, new[] { a }); + UInkSaveService.SaveFull(Document(b.path), main, new[] { b }); + using var zip = new UInkExtraArchive(main + ".extra"); + c.Equal(2, zip.EntryCount, "union count"); + foreach (var item in new[] { a, b }) + { + string copy = Path.Combine(dir, "copy"); + c.That(zip.TryExtractEntry(item.path, copy), "referenced entry"); + c.That(File.ReadAllBytes(copy).SequenceEqual(File.ReadAllBytes(item.source)), "resource bytes"); + } + var result = UInkReader.Read(main); + c.Equal(0, result.Diagnostics.Count, "main verifies"); + var media = (UInkMedia)result.Document.Canvases.Single().Blocks.Single(); + c.Equal(b.path, media.Path, "new main"); + c.Equal(0u, media.ContentId, "renumbering"); + } + + private static void CollisionAndUnreadableOriginal(UInkChecks c, string dir) + { + var a = Resource(dir, "first"); + var b = Resource(dir, "second"); + string main = Path.Combine(dir, "file.uink"); + UInkSaveService.SaveFull(Document(a.path), main, new[] { a }); + byte[] original = File.ReadAllBytes(main), extra = File.ReadAllBytes(main + ".extra"); + try { UInkSaveService.SaveFull(Document(a.path), main, new[] { (a.path, b.source) }); c.That(false, "collision accepted"); } + catch (InvalidDataException) { } + c.That(File.ReadAllBytes(main).SequenceEqual(original) && File.ReadAllBytes(main + ".extra").SequenceEqual(extra), "originals after collision"); + File.WriteAllBytes(main, new byte[] { 0xc1 }); + try { UInkSaveService.SaveFull(Document(b.path), main, new[] { b }); c.That(false, "unreadable old main accepted"); } + catch (InvalidDataException) { } + c.That(File.ReadAllBytes(main).SequenceEqual(new byte[] { 0xc1 }) && File.ReadAllBytes(main + ".extra").SequenceEqual(extra), + "originals after unreadable main"); + // Windows 通配符 "file.uink.*" 也会匹配 "file.uink" 本身,需同时排除主文件。 + var residue = Directory.EnumerateFileSystemEntries(dir, "file.uink.*").Except(new[] { main, main + ".extra" }).Select(Path.GetFileName).ToArray(); + c.That(residue.Length == 0, "no temp residue: " + string.Join(", ", residue)); + } + + private static void MainReplaceRollback(UInkChecks c, string dir) + { + var a = Resource(dir, "old"); + var b = Resource(dir, "new"); + string main = Path.Combine(dir, "file.uink"); + UInkSaveService.SaveFull(Document(a.path), main, new[] { a }); + byte[] old = File.ReadAllBytes(main), extra = File.ReadAllBytes(main + ".extra"); + // Windows 允许读取旧主文件,但该句柄不共享删除,最后一步原子替换应失败。 + using (File.Open(main, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + try { UInkSaveService.SaveFull(Document(b.path), main, new[] { b }); c.That(false, "locked replace succeeded"); } + catch (IOException) { } + } + c.That(File.ReadAllBytes(main).SequenceEqual(old) && File.ReadAllBytes(main + ".extra").SequenceEqual(extra), + "rolled back both files"); + } + + private static void ExtraReplacedBeforeMainFailure(UInkChecks c, string dir) => + CheckReplaceFault(c, dir, "after-extra-replace"); + + private static void ExtraMovedToBackupBeforeFailure(UInkChecks c, string dir) => + CheckReplaceFault(c, dir, "before-extra-replace", moveToBackup: ".extra"); + + private static void MainMovedToBackupBeforeFailure(UInkChecks c, string dir) => + CheckReplaceFault(c, dir, "before-main-replace", moveToBackup: ".main"); + + private static void RestoreFailureKeepsBackups(UInkChecks c, string dir) => + CheckReplaceFault(c, dir, "before-main-replace", moveToBackup: ".main", failRestore: true); + + private static void CompletedMainKeepsUnion(UInkChecks c, string dir) => + CheckReplaceFault(c, dir, "after-main-replace", mainCommitted: true); + + private static void CheckReplaceFault(UInkChecks c, string dir, string failStep, string moveToBackup = null, + bool failRestore = false, bool mainCommitted = false) + { + var oldResource = Resource(dir, "old"); + var newResource = Resource(dir, "new"); + string main = Path.Combine(dir, "file.uink"); + string extra = main + ".extra"; + UInkSaveService.SaveFull(Document(oldResource.path), main, new[] { oldResource }); + byte[] oldMain = File.ReadAllBytes(main), oldExtra = File.ReadAllBytes(extra); + var original = new IOException("simulated replace error"); + var restore = new IOException("simulated restore error"); + Action fault = step => + { + if (failRestore && step == "before-extra-restore") throw restore; + if (step != failStep) return; + if (mainCommitted) c.Equal(2, Directory.GetFiles(dir, "*.bak").Length, "both real replacements made backups"); + if (moveToBackup != null) + { + // 模拟 ReplaceFileW 1177:旧文件已移动,新文件仍以临时名称存在。 + string suffix = moveToBackup == ".main" ? ".tmp" : ".extra.tmp"; + string temp = Directory.EnumerateFiles(dir, "file.uink.*.tmp") + .Single(p => p.EndsWith(suffix, StringComparison.Ordinal) && + (moveToBackup != ".main" || !p.EndsWith(".extra.tmp", StringComparison.Ordinal))); + string backup = temp.Substring(0, temp.Length - suffix.Length) + moveToBackup + ".bak"; + File.Move(moveToBackup == ".main" ? main : extra, backup); + } + throw original; + }; + try + { + UInkSaveService.SaveFull(Document(newResource.path), main, new[] { newResource }, fault); + c.That(false, "fault was not surfaced"); + } + catch (IOException ex) + { + if (failRestore) + c.That(ex.InnerException is AggregateException errors && + errors.InnerExceptions.SequenceEqual(new[] { original, restore }), "both exceptions are retained"); + else c.That(ReferenceEquals(original, ex), "original error is propagated"); + } + + c.That(File.Exists(main), "main target exists"); + if (!mainCommitted) c.That(File.ReadAllBytes(main).SequenceEqual(oldMain), "old main restored"); + if (!failRestore && !mainCommitted) c.That(File.ReadAllBytes(extra).SequenceEqual(oldExtra), "old extra restored"); + var media = (UInkMedia)UInkReader.Read(main).Document.Canvases.Single().Blocks.Single(); + c.Equal(mainCommitted ? newResource.path : oldResource.path, media.Path, "installed main resource reference"); + using var archive = new UInkExtraArchive(extra); + c.That(archive.Contains(oldResource.path), "archive can serve old main"); + if (failRestore || mainCommitted) c.That(archive.Contains(newResource.path), "compatible union preserved"); + var backups = Directory.GetFiles(dir, "*.bak"); + c.Equal(failRestore ? 2 : 0, backups.Length, "backup cleanup or retention"); + if (failRestore) + { + c.That(File.ReadAllBytes(backups.Single(p => p.EndsWith(".main.bak", StringComparison.Ordinal))).SequenceEqual(oldMain), + "main backup retains original bytes"); + c.That(File.ReadAllBytes(backups.Single(p => p.EndsWith(".extra.bak", StringComparison.Ordinal))).SequenceEqual(oldExtra), + "extra backup retains original bytes"); + } + } + + private static void AliasedDirectorySerializesSaves(UInkChecks c, string dir) + { + string target = Directory.CreateDirectory(Path.Combine(dir, "target")).FullName; + string alias = Path.Combine(dir, "alias"); + try { Directory.CreateSymbolicLink(alias, target); } + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is PlatformNotSupportedException) + { + try { CreateDirectoryJunction(dir); } + catch (Exception junctionError) when (junctionError is Win32Exception || junctionError is IOException || + junctionError is InvalidOperationException || junctionError is NotSupportedException || + junctionError is UnauthorizedAccessException || junctionError is TimeoutException) + { + c.SkipReason = "Directory symlink unavailable: " + ex.Message + + " | Directory junction unavailable: " + junctionError.Message; + return; + } + } + + try + { + var a = Resource(dir, "first"); + var b = Resource(dir, "second"); + string main = Path.Combine(target, "file.uink"); + string aliasMain = Path.Combine(alias, "file.uink"); + using var firstAtCommit = new ManualResetEventSlim(); + using var secondStarted = new ManualResetEventSlim(); + using var secondAtCommit = new ManualResetEventSlim(); + using var releaseFirst = new ManualResetEventSlim(); + int commitCount = 0; + Action fault = step => + { + if (step != "after-extra-replace") return; + if (Interlocked.Increment(ref commitCount) == 1) + { + firstAtCommit.Set(); + if (!releaseFirst.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException("release first save"); + } + else secondAtCommit.Set(); + }; + Task first = null, second = null; + try + { + first = Task.Run(() => UInkSaveService.SaveFull(Document(a.path), main, new[] { a }, fault)); + if (!firstAtCommit.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException("first save did not reach main commit"); + second = Task.Run(() => + { + secondStarted.Set(); + UInkSaveService.SaveFull(Document(b.path), aliasMain, new[] { b }, fault); + }); + if (!secondStarted.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException("second save did not start"); + c.That(!secondAtCommit.Wait(TimeSpan.FromSeconds(1)), "alias save must wait for direct path save"); + } + finally + { + releaseFirst.Set(); + if (!Task.WaitAll(new[] { first, second }.Where(task => task != null).ToArray(), TimeSpan.FromSeconds(15))) + throw new TimeoutException("concurrent saves did not complete"); + } + c.That(secondAtCommit.IsSet, "alias save reached commit"); + using var archive = new UInkExtraArchive(main + ".extra"); + c.That(archive.Contains(a.path) && archive.Contains(b.path), "second save merges with first committed main"); + var media = (UInkMedia)UInkReader.Read(main).Document.Canvases.Single().Blocks.Single(); + c.Equal(b.path, media.Path, "second save wins"); + } + finally { Directory.Delete(alias); } + } + + private static void CreateDirectoryJunction(string dir) + { + // 普通用户可创建 junction;在测试目录内使用固定名称,避免 cmd 解析绝对路径中的特殊字符。 + using var process = Process.Start(new ProcessStartInfo( + Path.Combine(Environment.SystemDirectory, "cmd.exe"), "/d /c mklink /J \"alias\" \"target\"") + { + WorkingDirectory = dir, + UseShellExecute = false, + CreateNoWindow = true + }); + if (process == null) throw new IOException("Could not start mklink"); + if (!process.WaitForExit(10_000)) + { + process.Kill(); + throw new TimeoutException("mklink exceeded 10 seconds"); + } + if (process.ExitCode != 0 || !Directory.Exists(Path.Combine(dir, "alias"))) + throw new IOException("mklink did not create the junction, exit code " + process.ExitCode); + } + + private static void CorruptTempEntryRefusesCommit(UInkChecks c, string dir) + { + var old = Resource(dir, "original"); + var next = Resource(dir, "replacement"); + string main = Path.Combine(dir, "file.uink"); + UInkSaveService.SaveFull(Document(old.path), main, new[] { old }); + byte[] originalMain = File.ReadAllBytes(main), originalExtra = File.ReadAllBytes(main + ".extra"); + foreach (bool validCrc in new[] { false, true }) + { + var entry = (path: validCrc ? next.path : "media/legacy.wav", source: next.source); + void Corrupt(string step) + { + if (step != "before-extra-verify") return; + string temp = Directory.EnumerateFiles(dir, "*.extra.tmp").Single(); + if (validCrc) + { + // 合法 ZIP 中同名异内容仅能由 SHA-256 检出。 + using var zip = ZipFile.Open(temp, ZipArchiveMode.Update); + zip.GetEntry(entry.path).Delete(); + using var output = zip.CreateEntry(entry.path).Open(); + output.WriteByte(0); + } + else + { + byte[] bytes = File.ReadAllBytes(temp); + int offset = bytes.AsSpan().IndexOf(File.ReadAllBytes(next.source).AsSpan()); + if (offset < 0) throw new InvalidOperationException("missing stored payload"); + bytes[offset] ^= 1; + File.WriteAllBytes(temp, bytes); + } + } + try + { + UInkSaveService.SaveFull(Document(entry.path), main, new[] { entry }, Corrupt); + c.That(false, "corrupted temp archive committed"); + } + catch (InvalidDataException) { } + c.That(originalMain.SequenceEqual(File.ReadAllBytes(main)) && + originalExtra.SequenceEqual(File.ReadAllBytes(main + ".extra")), "original generation preserved"); + } + } + + private static void ContentHashRejectsChangedSource(UInkChecks c, string dir) + { + var oldResource = Resource(dir, "old"); + var newResource = Resource(dir, "new"); + string main = Path.Combine(dir, "file.uink"); + UInkSaveService.SaveFull(Document(oldResource.path), main, new[] { oldResource }); + byte[] oldMain = File.ReadAllBytes(main), oldExtra = File.ReadAllBytes(main + ".extra"); + File.WriteAllText(newResource.source, "RIFF0000WAVEchanged after hashing"); + try + { + UInkSaveService.SaveFull(Document(newResource.path), main, new[] { newResource }); + c.That(false, "wrong digest accepted"); + } + catch (InvalidDataException ex) { c.That(ex.Message.Contains("SHA-256"), "digest-specific validation error"); } + c.That(File.ReadAllBytes(main).SequenceEqual(oldMain) && File.ReadAllBytes(main + ".extra").SequenceEqual(oldExtra), + "hash mismatch detected before either commit"); + } + + private static void DuplicateAndUnsafeArchiveEntries(UInkChecks c, string dir) + { + foreach (string path in new[] { "/abs", "d:rel", "https://host/r", "urn:item", "a\\b", "a//b", "a/.", "../a", "a\nb" }) + c.That(UInkExtraArchive.NormalizeEntryPath(path) == null, "reject " + path); + string file = Path.Combine(dir, "entries.zip"); + using (var zip = ZipFile.Open(file, ZipArchiveMode.Create)) + foreach (string name in new[] { "é.wav", "e\u0301.wav", "../outside", "valid" }) + { + using var s = zip.CreateEntry(name).Open(); + s.WriteByte(1); + } + using var archive = new UInkExtraArchive(file); + string destination = Path.Combine(dir, "extracted"); + c.That(!archive.TryExtractEntry("é.wav", destination) && !File.Exists(destination), "NFC collisions unavailable"); + c.That(archive.TryExtractEntry("valid", destination), "bad entry isolated"); + byte[] png = { 137, 80, 78, 71, 13, 10, 26, 10 }; + c.That(UInkExtraArchive.IsMimeConsistent("image/png", png) && !UInkExtraArchive.IsMimeConsistent("image/jpeg", png), "signature mismatch"); + } + + private static void DeclaredAndActualEntrySize(UInkChecks c, string dir) + { + string file = Path.Combine(dir, "sizes.zip"); + using (var zip = ZipFile.Open(file, ZipArchiveMode.Create)) + foreach (string name in new[] { "bad", "good" }) + { + using var stream = zip.CreateEntry(name, CompressionLevel.Optimal).Open(); + stream.Write(new byte[] { 1, 2, 3 }); + } + // 保留三字节的真实内容,仅改第一个中央目录项的声明长度。 + byte[] bytes = File.ReadAllBytes(file); + int header = bytes.AsSpan().IndexOf(new byte[] { 0x50, 0x4b, 1, 2 }); + foreach (uint declared in new[] { 2u, 4u, (uint)UInkExtraArchive.MaxSingleEntryBytes + 1 }) + { + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(header + 24), declared); + File.WriteAllBytes(file, bytes); + using var zip = new UInkExtraArchive(file); + c.Equal(declared <= UInkExtraArchive.MaxSingleEntryBytes, zip.Contains("bad"), "declared entry budget"); + string dest = Path.Combine(dir, "result"); + File.WriteAllText(dest, "previous"); + c.That(!zip.TryExtractEntry("bad", dest), "invalid size rejected"); + c.Equal("previous", File.ReadAllText(dest), "failed copy preserves destination"); + c.That(zip.TryExtractEntry("good", dest), "other entry survives"); + } + + // 实际内容和声明长度都跨过提取缓冲区,低报的长度仍在预算内。 + const uint declaredLargeSize = 81921; + var large = new byte[163843]; + for (int i = 0; i < large.Length; i++) large[i] = (byte)(i & 0xff); + string largeFile = Path.Combine(dir, "large-size.zip"); + using (var zip = ZipFile.Open(largeFile, ZipArchiveMode.Create)) + using (var stream = zip.CreateEntry("large", CompressionLevel.Optimal).Open()) + stream.Write(large); + + string largeDest = Path.Combine(dir, "large-result"); + using (var zip = new UInkExtraArchive(largeFile)) + { + c.That(zip.TryExtractEntry("large", largeDest), "valid multi-buffer entry extracted"); + c.That(File.Exists(largeDest) && File.ReadAllBytes(largeDest).SequenceEqual(large), "valid multi-buffer content preserved"); + } + + byte[] largeZip = File.ReadAllBytes(largeFile); + // 此测试生成普通单条目 ZIP,EOCD 无注释,中央目录偏移在末尾倒数 6 字节处。 + int largeDirectory = BinaryPrimitives.ReadInt32LittleEndian(largeZip.AsSpan(largeZip.Length - 6)); + BinaryPrimitives.WriteUInt32LittleEndian(largeZip.AsSpan(largeDirectory + 24), declaredLargeSize); + File.WriteAllBytes(largeFile, largeZip); + File.WriteAllText(largeDest, "previous"); + using var truncated = new UInkExtraArchive(largeFile); + c.That(truncated.Contains("large"), "underdeclared entry is within metadata budget"); + c.That(!truncated.TryExtractEntry("large", largeDest), "large size mismatch rejected"); + c.Equal("previous", File.ReadAllText(largeDest), "large failed copy preserves destination"); + } + + private static void CentralDirectoryPreflight(UInkChecks c, string dir) + { + string file = Path.Combine(dir, "directory.zip"); + void Reject(byte[] bytes, string message) + { + File.WriteAllBytes(file, bytes); + try { using var ignored = new UInkExtraArchive(file); c.That(false, "invalid central directory accepted"); } + catch (InvalidDataException ex) { c.Equal(message, ex.Message, "preflight rejection"); } + } + + const string limit = "EXTRA-7:中央目录条目数或大小超限"; + var end = new byte[22]; + BinaryPrimitives.WriteUInt32LittleEndian(end, 0x06054b50); + BinaryPrimitives.WriteUInt16LittleEndian(end.AsSpan(8), (ushort)(UInkExtraArchive.MaxEntries + 1)); + BinaryPrimitives.WriteUInt16LittleEndian(end.AsSpan(10), (ushort)(UInkExtraArchive.MaxEntries + 1)); + Reject(end, limit); + end.AsSpan(8, 4).Clear(); + BinaryPrimitives.WriteUInt32LittleEndian(end.AsSpan(12), UInkExtraArchive.MaxCentralDirectoryBytes + 1); + Reject(end, limit); + + // 用空 ZIP64 验证合法目录,同时覆盖 ZIP64 的条目数与目录大小字段。 + var zip64 = new byte[56 + 20 + 22]; + BinaryPrimitives.WriteUInt32LittleEndian(zip64, 0x06064b50); + BinaryPrimitives.WriteUInt64LittleEndian(zip64.AsSpan(4), 44); + BinaryPrimitives.WriteUInt16LittleEndian(zip64.AsSpan(12), 45); + BinaryPrimitives.WriteUInt16LittleEndian(zip64.AsSpan(14), 45); + BinaryPrimitives.WriteUInt32LittleEndian(zip64.AsSpan(56), 0x07064b50); + BinaryPrimitives.WriteUInt32LittleEndian(zip64.AsSpan(72), 1); + BinaryPrimitives.WriteUInt32LittleEndian(zip64.AsSpan(76), 0x06054b50); + zip64.AsSpan(84, 12).Fill(0xff); + File.WriteAllBytes(file, zip64); + using (var archive = new UInkExtraArchive(file)) c.Equal(0, archive.EntryCount, "valid empty ZIP64"); + BinaryPrimitives.WriteUInt64LittleEndian(zip64.AsSpan(24), UInkExtraArchive.MaxEntries + 1); + BinaryPrimitives.WriteUInt64LittleEndian(zip64.AsSpan(32), UInkExtraArchive.MaxEntries + 1); + Reject(zip64, limit); + zip64.AsSpan(24, 16).Clear(); + BinaryPrimitives.WriteUInt64LittleEndian(zip64.AsSpan(40), UInkExtraArchive.MaxCentralDirectoryBytes + 1); + Reject(zip64, limit); + + File.Delete(file); + using (var zip = ZipFile.Open(file, ZipArchiveMode.Create)) + foreach (string name in new[] { "a", "b" }) + { + using var stream = zip.CreateEntry(name).Open(); + stream.WriteByte(1); + } + byte[] undercount = File.ReadAllBytes(file); + BinaryPrimitives.WriteUInt16LittleEndian(undercount.AsSpan(undercount.Length - 14), 1); + BinaryPrimitives.WriteUInt16LittleEndian(undercount.AsSpan(undercount.Length - 12), 1); + Reject(undercount, "EXTRA-7:ZIP 中央目录无效"); + } + + private static void VerifiedMediaRestoreCache(UInkChecks c, string dir) + { + byte[] png = { 137, 80, 78, 71, 13, 10, 26, 10, 1 }; + byte[] secondPng = { 137, 80, 78, 71, 13, 10, 26, 10, 2 }; + string source = Path.Combine(dir, "first"), second = Path.Combine(dir, "second"); + File.WriteAllBytes(source, png); + File.WriteAllBytes(second, secondPng); + string file = Path.Combine(dir, "media.zip"); + UInkExtraArchive.WriteArchive(file, new[] { ("é/logo.png", source), ("other/logo.png", second) }); + string extract = Directory.CreateDirectory(Path.Combine(dir, "extract")).FullName; + string cache = Directory.CreateDirectory(Path.Combine(dir, "cache")).FullName; + string expected = Path.Combine(cache, Path.GetFileName(UInkExtraArchive.ContentHashPath(png, "png"))); + File.WriteAllText(expected, "stale bytes even under the expected cache name"); + using var archive = new UInkExtraArchive(file); + var restore = new UInkMediaRestoreCache(archive, extract, cache); + c.That(restore.GetVerifiedPath("é/logo.png", "image/jpeg") == null, "MIME mismatch"); + string cached = restore.GetVerifiedPath("é/logo.png", "image/png"); + c.Equal(expected, cached, "SHA-256 and canonical extension"); + c.Equal(cached, restore.GetVerifiedPath("é/logo.png", "IMAGE/PNG"), "normalized repeat reference"); + c.Equal(1, Directory.GetFiles(extract).Length, "entry extracted once, including the failed sniff"); + c.That(File.ReadAllBytes(cached).SequenceEqual(png), "decoder path holds the bytes that were sniffed"); + string distinct = restore.GetVerifiedPath("other/logo.png", "image/png"); + c.That(cached != distinct && File.ReadAllBytes(distinct).SequenceEqual(secondPng), "same basename, distinct bytes"); + } + + private static void StableFourLevelCanvasOrder(UInkChecks c) + { + var doc = Document(null); + string[] ws = { UInkTestEncoder.HeaderGuid, UInkTestEncoder.WorkspaceGuid }; + string[] dev = { UInkTestEncoder.PageGuid(11), UInkTestEncoder.PageGuid(10) }; + doc.HeaderExtension = new UInkHeaderExtension + { + Workspaces = ws.Select(g => new UInkWorkspace { Guid = g }).ToList(), + Devices = dev.Select(g => new UInkDevice { Guid = g, DisplayX = 0, DisplayY = 0, DisplayWidth = 100, DisplayHeight = 100 }).ToList() + }; + UInkCanvasRecord Record(uint id, int workspace, uint page, int device, uint layer) => new() + { + Canvas = new UInkCanvas { PageGuid = UInkTestEncoder.PageGuid(id), WorkspaceGuid = ws[workspace], + PageIndex = page, PageNumber = page + 1, DeviceGuid = dev[device], LayerIndex = layer, LayerNumber = layer } + }; + // 每对倒序的相邻排序键分别改变一层;ID 9 先于 ID 1 验证同键稳定性。 + doc.Canvases = new() { Record(4, 1, 0, 0, 0), Record(3, 0, 1, 0, 0), Record(2, 0, 0, 1, 0), + Record(5, 0, 0, 0, 1), Record(9, 0, 0, 0, 0), Record(1, 0, 0, 0, 0) }; + using var stream = new MemoryStream(); + UInkWriter.Save(doc, stream); + var read = UInkReader.Read(stream.ToArray()); + c.Equal(0, read.Diagnostics.Count, "valid sorted stream"); + var ids = read.Document.Canvases.Select(rec => rec.Canvas.PageGuid); + c.That(ids.SequenceEqual(new uint[] { 9, 1, 5, 2, 3, 4 }.Select(UInkTestEncoder.PageGuid)), "four-level SAVE-3 stable order"); + } + + private static void StreamRejectsSharedClearGroup(UInkChecks c) + { + foreach (bool clearFirst in new[] { true, false }) + { + var doc = Document(null); + var clear = new UInkClear(); + var ink = new UInkInk { Points = new[] { new UInkPoint(1, 1, 1) } }; + var blocks = doc.Canvases.Single().Blocks; + blocks.Add(clearFirst ? clear : ink); + blocks.Add(clearFirst ? ink : clear); + using var stream = new MemoryStream(); + try { UInkWriter.Save(doc, stream); c.That(false, "direct stream wrote shared Clear group"); } + catch (InvalidDataException ex) { c.That(ex.Message.Contains("CLEAR-4"), "Clear group validation"); } + c.Equal(0L, stream.Length, "invalid groups rejected before writing"); + } + } + + private static void PublicFieldEncoding(UInkChecks c) + { + var doc = Document(null); + var rec = doc.Canvases.Single(); + var color = new UInkColor { Fallback = 0x123456 }; + rec.Canvas.Background = new UInkBackground { Color = color, Pattern = 2 }; + rec.Canvas.PageState = 1; rec.Canvas.PageKind = 1; rec.Canvas.Binding = 1; + var ink = new UInkInk + { + Color = color, InkType = 3, Nib = new UInkNib { Shape = 1, Aspect = 0.5f, Orientation = 1 }, + Points = new[] { new UInkPoint(2, 3, 5), new UInkPoint(-1, 4, 2) }, + StyleAnchors = new List<(int, UInkColor, float)> { (1, color, 0.25f) } + }; + rec.Blocks.Add(ink); + rec.Blocks.Add(new UInkInk { Points = ink.Points, Cap = 2 }); + rec.Blocks.Add(new UInkShape + { + UndoId = 1, ShapeType = 2, + Geometry = new UInkRectGeometry { Width = 8, Height = 6, CornerRadiusX = 3, CornerRadiusY = 2 }, + Stroke = new UInkStroke { Width = 2, Color = color, LineCap = 1, LineJoin = 2 }, + Object = new UInkShapeObject { Id = UInkTestEncoder.HeaderGuid, Revision = ulong.MaxValue, + PartCount = 2, Preset = "fixture", Transform = new float[] { 1, 0, 0, 1, 5, 6 } } + }); + rec.Blocks.Add(new UInkShape { UndoId = 1, ShapeType = 5, Geometry = new UInkCircleGeometry { Radius = 4 }, + Fill = new UInkFill { Color = color }, Object = new UInkShapeObject { Ref = UInkTestEncoder.HeaderGuid, PartIndex = 1 } }); + rec.Blocks.Add(new UInkMedia { UndoId = 2, Path = "media/a", MimeType = "image/png", Width = 20, Height = 30, + Transform = new float[] { 0, 1, -1, 0, 4, 3 }, Crop = new UInkCrop { X = 1, Y = 2, Width = 3, Height = 4 }, Fit = 2 }); + rec.Blocks.Add(new UInkClear { UndoId = 3, Extra = new() { ["icc:test"] = "ok" } }); + using var ms = new MemoryStream(); + UInkWriter.Save(doc, ms); + var bytes = ms.ToArray(); + UInkWireInspection.Read(bytes, c); + var read = UInkReader.Read(bytes); + c.Equal(0, read.Diagnostics.Count, "public fields encoded without fallback"); + var record = read.Document.Canvases.Single(); + var canvas = record.Canvas; + c.That(canvas.PageState == 1 && canvas.Binding == 1 && canvas.PageKind == 1 && + canvas.Background.Pattern == 2 && canvas.Background.Color.Fallback == color.Fallback, "Canvas metadata"); + var blocks = record.Blocks; + var a = (UInkInk)blocks[0]; + c.That(a.Nib.Shape == 1 && a.Nib.Aspect == 0.5f && a.Nib.Orientation == 1, "nib"); + c.That(a.StyleAnchors.Single().Index == 1 && a.StyleAnchors[0].Opacity == 0.25f, "style anchor"); + c.Equal(2, ((UInkInk)blocks[1]).Cap, "cap"); + var sh = (UInkShape)blocks[2]; + c.That(sh.Object.PartCount == 2 && sh.Object.Revision == ulong.MaxValue && sh.Object.Preset == "fixture", "object head"); + c.Floats(new float[] { 1, 0, 0, 1, 5, 6 }, sh.Object.Transform, "object transform"); + var part = ((UInkShape)blocks[3]).Object; + c.That(part.Ref == sh.Object.Id && part.PartIndex == 1, "object part"); + c.That(sh.Stroke.LineCap == 1 && sh.Stroke.LineJoin == 2 && + sh.Geometry is UInkRectGeometry { CornerRadiusX: 3, CornerRadiusY: 2 }, "rectangle and stroke"); + var media = (UInkMedia)blocks[4]; + c.That(media.Fit == 2 && media.Crop.X == 1 && media.Crop.Y == 2 && media.Crop.Width == 3 && media.Crop.Height == 4, "crop"); + c.Equal("ok", ((UInkClear)blocks[5]).Extra["icc:test"], "Clear extra"); + } + + private static void FirstSaveFailurePublishesVerifiedPair(UInkChecks c, string dir) + { + var resource = Resource(dir, "resource"); + string main = Path.Combine(dir, "first.uink"); + var original = new IOException("simulated first main install failure"); + Action fault = step => + { + if (step == "after-extra-replace") throw original; + }; + try + { + UInkSaveService.SaveFull(Document(resource.path), main, new[] { resource }, fault); + c.That(false, "fault was not surfaced"); + } + catch (IOException ex) { c.That(ReferenceEquals(original, ex), "first-save fault is propagated"); } + + var media = (UInkMedia)UInkReader.Read(main).Document.Canvases.Single().Blocks.Single(); + using var archive = new UInkExtraArchive(main + ".extra"); + c.That(media.Path == resource.path && archive.Contains(media.Path), "first save recovers a verified pair"); + } + + private static void CanonicalOrderAndUndo(UInkChecks c) + { + var doc = Document(null); + var later = doc.Canvases[0]; + later.Canvas.PageIndex = 1; + later.Blocks.Add(new UInkClear { ContentId = 8 }); + var earlier = Document(null).Canvases[0]; + earlier.Canvas.PageGuid = UInkTestEncoder.PageGuid(1); + doc.Canvases.Add(earlier); + using var ms = new MemoryStream(); + UInkWriter.Save(doc, ms); + var result = UInkReader.Read(ms.ToArray()); + c.Equal(0, result.Diagnostics.Count, "canonical stream"); + c.Equal(2u, result.Document.Header.PageNum, "distinct pages"); + c.Equal(1u, result.Document.Header.DeviceNum, "implicit device"); + c.Equal(1u, result.Document.Header.WorkspaceNum, "implicit workspace"); + c.Equal(earlier.Canvas.PageGuid, result.Document.Canvases[0].Canvas.PageGuid, "SAVE-3 order"); + c.Equal(0u, result.Document.Canvases[1].Blocks.Single().ContentId, "renumber Clear"); + later.Blocks.Add(new UInkClear { UndoId = 3 }); + later.Blocks.Add(new UInkClear { UndoId = 2 }); + try { UInkWriter.Save(doc, ms); c.That(false, "decreasing undo accepted"); } + catch (InvalidDataException) { } + } + } +} diff --git a/InkCanvas.Calibration.Tests/UInk/UInkWireInspection.cs b/InkCanvas.Calibration.Tests/UInk/UInkWireInspection.cs new file mode 100644 index 000000000..274d20e2c --- /dev/null +++ b/InkCanvas.Calibration.Tests/UInk/UInkWireInspection.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using System.IO; +using MessagePack; + +namespace InkCanvas.Calibration.Tests.UInk +{ + internal sealed class UInkWireBlock + { + public ushort? Type; + public uint? ContentId, UndoId, Color; + public int? InkType, NibShape; + public float? Opacity, NibAspect; + public (float? X, float? Y, float? Width)[] Points; + } + + internal static class UInkWireInspection + { + // HDR-1、TYPE-1:先看原始标记,再独立解码值,避免容错读取掩盖写入位宽错误。 + public static List Read(byte[] data, UInkChecks c) + { + var reader = new MessagePackReader(new ReadOnlyMemory(data)); + Marker(c, ref reader, 0x97, "Header array(7)"); + if (reader.ReadArrayHeader() != 7) throw new InvalidDataException("Header does not have 7 fields."); + Marker(c, ref reader, 0xcd, "Header type uint16"); + c.Equal(0, reader.ReadUInt16(), "Header type"); + Marker(c, ref reader, 0xcd, "Header version uint16"); + c.Equal(11, reader.ReadUInt16(), "Header version"); + + int offset = (int)reader.Consumed; + Marker(c, ref reader, 0xd9, "Header GUID str8"); + c.That(offset + 38 <= data.Length && data[offset + 1] == 36, "Header GUID str8 length byte must be 0x24"); + string guid = reader.ReadString(); + c.That(guid?.Length == 36 && Guid.TryParseExact(guid, "D", out _), "Header GUID must be a 36-character UUID"); + for (int i = offset + 2; i < offset + 38 && i < data.Length; i++) + c.That(data[i] < 0x80, "Header GUID contains a non-ASCII byte"); + + foreach (string key in new[] { "deviceNum", "workspaceNum", "pageNum" }) + { + Marker(c, ref reader, 0xce, "Header " + key + " uint32"); + reader.ReadUInt32(); + } + Marker(c, ref reader, 0xcf, "Header time uint64"); + reader.ReadUInt64(); + + var blocks = new List(); + while (!reader.End) + { + var block = new UInkWireBlock(); + int count = reader.ReadMapHeader(); + for (int i = 0; i < count; i++) + { + string readerKey = reader.ReadString(); + switch (readerKey) + { + case "type": + Marker(c, ref reader, 0xcd, "block type uint16"); + block.Type = reader.ReadUInt16(); + break; + case "contentId": + Marker(c, ref reader, 0xce, "contentId uint32"); + block.ContentId = reader.ReadUInt32(); + break; + case "undoId": + Marker(c, ref reader, 0xce, "undoId uint32"); + block.UndoId = reader.ReadUInt32(); + break; + case "inkType": + Marker(c, ref reader, 0xd2, "inkType int32"); + block.InkType = reader.ReadInt32(); + break; + case "color": + block.Color = ReadColor(ref reader, c); + break; + case "nib": + (block.NibShape, block.NibAspect) = ReadNib(ref reader, c); + break; + case "background": case "object": case "geometry": case "stroke": case "crop": + ReadNested(ref reader, c, readerKey); + break; + case "fit": case "pageState": case "pageKind": case "binding": case "cap": + Marker(c, ref reader, 0xd2, readerKey + " int32"); + reader.ReadInt32(); + break; + case "opacity": + block.Opacity = Single(ref reader, c, "opacity"); + break; + case "points": + block.Points = ReadPoints(ref reader, c); + break; + default: reader.Skip(); break; + } + } + blocks.Add(block); + } + return blocks; + } + + private static uint? ReadColor(ref MessagePackReader reader, UInkChecks c) + { + uint? rgb = null; + int count = reader.ReadMapHeader(); + for (int i = 0; i < count; i++) + { + if (reader.ReadString() == "fallback") + { + Marker(c, ref reader, 0xce, "fallback RGB uint32"); + rgb = reader.ReadUInt32(); + } + else reader.Skip(); + } + return rgb; + } + + private static (int?, float?) ReadNib(ref MessagePackReader reader, UInkChecks c) + { + int? shape = null; + float? aspect = null; + int count = reader.ReadMapHeader(); + for (int i = 0; i < count; i++) + { + switch (reader.ReadString()) + { + case "shape": + Marker(c, ref reader, 0xd2, "nib shape int32"); + shape = reader.ReadInt32(); + break; + case "aspect": aspect = Single(ref reader, c, "nib aspect"); break; + case "orientation": + Marker(c, ref reader, 0xd2, "nib orientation int32"); + reader.ReadInt32(); + break; + default: reader.Skip(); break; + } + } + return (shape, aspect); + } + + private static void ReadNested(ref MessagePackReader reader, UInkChecks c, string map) + { + int count = reader.ReadMapHeader(); + for (int i = 0; i < count; i++) + { + string key = reader.ReadString(); + string label = map + "." + key; + switch (map, key) + { + case ("background", "color"): + _ = ReadColor(ref reader, c); + continue; + case ("background", "pattern"): + case ("stroke", "lineCap" or "lineJoin"): + Marker(c, ref reader, 0xd2, label + " int32"); + break; + case ("object", "partCount" or "partIndex"): + Marker(c, ref reader, 0xce, label + " uint32"); + break; + case ("object", "revision"): + Marker(c, ref reader, 0xcf, label + " uint64"); + break; + case ("object", "transform"): + int length = reader.ReadArrayHeader(); + c.Equal(6, length, label + " length"); + for (int j = 0; j < length; j++) _ = Single(ref reader, c, label); + continue; + case ("geometry", "cornerRadiusX" or "cornerRadiusY"): + case ("crop", "x" or "y" or "width" or "height"): + Marker(c, ref reader, 0xca, label + " float32"); + break; + } + reader.Skip(); + } + } + + private static (float? X, float? Y, float? Width)[] ReadPoints(ref MessagePackReader reader, UInkChecks c) + { + var points = new (float? X, float? Y, float? Width)[reader.ReadArrayHeader()]; + for (int i = 0; i < points.Length; i++) + { + int fields = reader.ReadMapHeader(); + for (int j = 0; j < fields; j++) + { + switch (reader.ReadString()) + { + case "x": points[i].X = Single(ref reader, c, "point x"); break; + case "y": points[i].Y = Single(ref reader, c, "point y"); break; + case "width": points[i].Width = Single(ref reader, c, "point width"); break; + default: reader.Skip(); break; + } + } + } + return points; + } + + private static float Single(ref MessagePackReader reader, UInkChecks c, string key) + { + Marker(c, ref reader, 0xca, key + " float32"); + return reader.ReadSingle(); + } + + private static void Marker(UInkChecks c, ref MessagePackReader reader, byte expected, string label) + { + byte actual = reader.NextCode; + if (expected != actual) + c.That(false, $"{label} at byte {reader.Consumed}: expected 0x{expected:x2}, got 0x{actual:x2}"); + } + } +} diff --git a/InkCanvas.PPTAgent.Contracts/PptState.cs b/InkCanvas.PPTAgent.Contracts/PptState.cs index 9bc36a39f..ba3fabb58 100644 --- a/InkCanvas.PPTAgent.Contracts/PptState.cs +++ b/InkCanvas.PPTAgent.Contracts/PptState.cs @@ -3,6 +3,9 @@ namespace InkCanvasPPTAgent.Contracts public sealed class PPTState { public int SlideIndex { get; set; } + // 可选 JSON 字段;旧加载项缺省时由 ICC 按位置绑定。 + public int? SlideId { get; set; } + public int[] SlideIds { get; set; } public int TotalSlides { get; set; } public bool IsRunning { get; set; } public string PresentationName { get; set; } diff --git a/InkCanvas.PowerPointAddIn/Core/PPTController.cs b/InkCanvas.PowerPointAddIn/Core/PPTController.cs index 45e254854..e7526415a 100644 --- a/InkCanvas.PowerPointAddIn/Core/PPTController.cs +++ b/InkCanvas.PowerPointAddIn/Core/PPTController.cs @@ -56,7 +56,18 @@ public PPTState GetState() if (_application.SlideShowWindows.Count > 0) { state.IsRunning = true; - state.SlideIndex = _application.SlideShowWindows[1].View.CurrentShowPosition; + var window = _application.SlideShowWindows[1]; + try { state.SlideIndex = window.View.CurrentShowPosition; } catch { } + // 当前页与整份文稿的 ID 表可能独立读取失败。 + try { state.SlideId = window.View.Slide.SlideID; } catch { } + try + { + var slides = window.Presentation.Slides; + var ids = new int[slides.Count]; + for (int i = 0; i < ids.Length; i++) ids[i] = slides[i + 1].SlideID; + state.SlideIds = ids; + } + catch { } } } catch { } From a8259b143c21d133020207c45ce356cbe1e7bde0 Mon Sep 17 00:00:00 2001 From: Huoxing-Rusty <220455872+Huoxing-Rusty@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:57:19 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8F=AF=E6=8B=96?= =?UTF-8?q?=E5=8A=A8=E6=82=AC=E6=B5=AE=E7=90=83=E6=94=B6=E7=BA=B3=E6=96=B9?= =?UTF-8?q?=E5=BC=8F=E5=B9=B6=E4=BF=9D=E7=95=99=E4=BE=A7=E8=BE=B9=E6=A0=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Ink Canvas/Controls/FloatingFoldBall.xaml | 16 ++ Ink Canvas/Controls/FloatingFoldBall.xaml.cs | 148 ++++++++++++++++++ Ink Canvas/MainWindow.xaml | 4 +- Ink Canvas/MainWindow_cs/MW_AutoFold.cs | 28 +++- .../MainWindow_cs/MW_FloatingFoldBall.cs | 80 ++++++++++ Ink Canvas/MainWindow_cs/MW_Settings.cs | 1 + Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs | 4 + .../MainWindow_cs/MW_WindowChromeHitTest.cs | 1 + .../Properties/ThemeStrings.Designer.cs | 7 +- Ink Canvas/Properties/ThemeStrings.en-US.resx | 12 ++ Ink Canvas/Properties/ThemeStrings.resx | 14 +- Ink Canvas/Properties/ThemeStrings.zh-ME.resx | 14 +- Ink Canvas/Resources/Settings.cs | 9 ++ .../SettingsViews/Pages/SidebarPage.xaml | 8 + .../SettingsViews/Pages/SidebarPage.xaml.cs | 9 ++ 15 files changed, 349 insertions(+), 6 deletions(-) create mode 100644 Ink Canvas/Controls/FloatingFoldBall.xaml create mode 100644 Ink Canvas/Controls/FloatingFoldBall.xaml.cs create mode 100644 Ink Canvas/MainWindow_cs/MW_FloatingFoldBall.cs diff --git a/Ink Canvas/Controls/FloatingFoldBall.xaml b/Ink Canvas/Controls/FloatingFoldBall.xaml new file mode 100644 index 000000000..c370816ea --- /dev/null +++ b/Ink Canvas/Controls/FloatingFoldBall.xaml @@ -0,0 +1,16 @@ + + + + + + + + diff --git a/Ink Canvas/Controls/FloatingFoldBall.xaml.cs b/Ink Canvas/Controls/FloatingFoldBall.xaml.cs new file mode 100644 index 000000000..c18400bb9 --- /dev/null +++ b/Ink Canvas/Controls/FloatingFoldBall.xaml.cs @@ -0,0 +1,148 @@ +using System; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace Ink_Canvas.Controls +{ + public partial class FloatingFoldBall : UserControl + { + public event RoutedEventHandler Click; + public event EventHandler PositionChanged; + + private Point _pointerStart; + private Point _positionStart; + private bool _pressed; + private bool _dragged; + private TouchDevice _touch; + + public FloatingFoldBall() + { + InitializeComponent(); + IsVisibleChanged += (_, _) => + { + if (!IsVisible) + { + EndDrag(true); + ReleaseMouseCapture(); + _touch?.Capture(null); + _touch = null; + } + }; + } + + internal static Point ClampPosition(Point point, Size bounds, Size size) => new Point( + Math.Clamp(double.IsFinite(point.X) ? point.X : 0, 0, Math.Max(0, bounds.Width - size.Width)), + Math.Clamp(double.IsFinite(point.Y) ? point.Y : 0, 0, Math.Max(0, bounds.Height - size.Height))); + + public void SetPosition(Point point) + { + // 首次布局前也保留配置位置,待宿主取得尺寸后再约束到可见区域。 + if (Parent is FrameworkElement parent && parent.ActualWidth > 0 && parent.ActualHeight > 0) + point = ClampPosition(point, parent.RenderSize, new Size(Width, Height)); + else + point = new Point(double.IsFinite(point.X) ? Math.Max(0, point.X) : 0, + double.IsFinite(point.Y) ? Math.Max(0, point.Y) : 0); + Margin = new Thickness(point.X, point.Y, 0, 0); + } + + private void BeginDrag(Point pointer) + { + _pointerStart = pointer; + _positionStart = new Point(Margin.Left, Margin.Top); + _pressed = true; + _dragged = false; + } + + private void MoveDrag(Point pointer) + { + if (!_pressed) return; + var delta = pointer - _pointerStart; + if (!_dragged && Math.Abs(delta.X) < SystemParameters.MinimumHorizontalDragDistance && + Math.Abs(delta.Y) < SystemParameters.MinimumVerticalDragDistance) return; + _dragged = true; + SetPosition(_positionStart + delta); + } + + private void EndDrag(bool cancelled) + { + if (!_pressed) return; + _pressed = false; + if (_dragged) PositionChanged?.Invoke(this, EventArgs.Empty); + else if (!cancelled) Click?.Invoke(this, new RoutedEventArgs()); + _dragged = false; + } + + protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonDown(e); + if (_touch != null) return; + if (CaptureMouse()) BeginDrag(e.GetPosition(Parent as IInputElement)); + e.Handled = true; + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + if (_touch == null && _pressed) + { + MoveDrag(e.GetPosition(Parent as IInputElement)); + e.Handled = true; + } + } + + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonUp(e); + if (_touch != null) return; + MoveDrag(e.GetPosition(Parent as IInputElement)); + EndDrag(false); + ReleaseMouseCapture(); + e.Handled = true; + } + + protected override void OnLostMouseCapture(MouseEventArgs e) + { + base.OnLostMouseCapture(e); + if (_touch == null) EndDrag(true); + } + + protected override void OnTouchDown(TouchEventArgs e) + { + base.OnTouchDown(e); + e.Handled = true; + if (_pressed || _touch != null) return; + if (e.TouchDevice.Capture(this)) + { + _touch = e.TouchDevice; + BeginDrag(e.GetTouchPoint(Parent as IInputElement).Position); + } + } + + protected override void OnTouchMove(TouchEventArgs e) + { + base.OnTouchMove(e); + e.Handled = true; + if (e.TouchDevice == _touch) MoveDrag(e.GetTouchPoint(Parent as IInputElement).Position); + } + + protected override void OnTouchUp(TouchEventArgs e) + { + base.OnTouchUp(e); + e.Handled = true; + if (e.TouchDevice != _touch) return; + MoveDrag(e.GetTouchPoint(Parent as IInputElement).Position); + EndDrag(false); + _touch = null; + e.TouchDevice.Capture(null); + } + + protected override void OnLostTouchCapture(TouchEventArgs e) + { + base.OnLostTouchCapture(e); + if (e.TouchDevice != _touch) return; + EndDrag(true); + _touch = null; + } + } +} diff --git a/Ink Canvas/MainWindow.xaml b/Ink Canvas/MainWindow.xaml index 1af7841b4..4f6c18306 100644 --- a/Ink Canvas/MainWindow.xaml +++ b/Ink Canvas/MainWindow.xaml @@ -142,7 +142,7 @@ - + @@ -1428,6 +1428,8 @@ + diff --git a/Ink Canvas/MainWindow_cs/MW_AutoFold.cs b/Ink Canvas/MainWindow_cs/MW_AutoFold.cs index a14f6b103..a395f4da7 100644 --- a/Ink Canvas/MainWindow_cs/MW_AutoFold.cs +++ b/Ink Canvas/MainWindow_cs/MW_AutoFold.cs @@ -278,6 +278,13 @@ private int ComputeFoldEdge() private async Task AnimateSidePanelsAsync(int edge, bool skipAnimation) { int thisVersion = ++_sidePanelAnimVersion; + if (Settings.Appearance.UseFloatingFoldBall) + { + LeftSidePanel.Visibility = Visibility.Collapsed; + FoldedBall.Visibility = isFloatingBarFolded ? Visibility.Visible : Visibility.Collapsed; + UpdateFloatingFoldBallLayout(); + return; + } Task leftMotion = Task.CompletedTask; await Dispatcher.InvokeAsync(() => @@ -299,6 +306,7 @@ await Dispatcher.InvokeAsync(() => await Dispatcher.InvokeAsync(() => { + if (_sidePanelAnimVersion != thisVersion) return; if (edge == SidePanelEdgeHidden) LeftSidePanel.Visibility = Visibility.Collapsed; }); } @@ -316,12 +324,14 @@ await Dispatcher.InvokeAsync(() => /// private async void LeftUnFoldButtonDisplayQuickPanel_MouseUp(object sender, RoutedEventArgs e) { + int modeVersion = _foldedModeVersion; if (Settings.Appearance.IsShowQuickPanel) { SidePannelMarginAnimation(-50); HideRightQuickPanel(); LeftUnFoldButtonQuickPanel.Visibility = Visibility.Visible; await MoveQuickPanelTo(LeftUnFoldButtonQuickPanel, QuickPanelUnfoldedMargin, false); + if (modeVersion != _foldedModeVersion) return; StartAutoCollapseQuickPanelTimer(); } @@ -344,12 +354,14 @@ private async void LeftUnFoldButtonDisplayQuickPanel_MouseUp(object sender, Rout /// private async void RightUnFoldButtonDisplayQuickPanel_MouseUp(object sender, RoutedEventArgs e) { + int modeVersion = _foldedModeVersion; if (Settings.Appearance.IsShowQuickPanel) { SidePannelMarginAnimation(-50); HideLeftQuickPanel(); RightUnFoldButtonQuickPanel.Visibility = Visibility.Visible; await MoveQuickPanelTo(RightUnFoldButtonQuickPanel, QuickPanelUnfoldedMargin, true); + if (modeVersion != _foldedModeVersion) return; StartAutoCollapseQuickPanelTimer(); } @@ -370,9 +382,17 @@ private async void RightUnFoldButtonDisplayQuickPanel_MouseUp(object sender, Rou /// private async void HideLeftQuickPanel() { + int modeVersion = _foldedModeVersion; + if (Settings.Appearance.UseFloatingFoldBall) + { + LeftUnFoldButtonQuickPanel.BeginAnimation(MarginProperty, null); + LeftUnFoldButtonQuickPanel.Visibility = Visibility.Collapsed; + return; + } if (LeftUnFoldButtonQuickPanel.Visibility == Visibility.Visible) { await MoveQuickPanelTo(LeftUnFoldButtonQuickPanel, QuickPanelFoldedMargin, false); + if (modeVersion != _foldedModeVersion) return; LeftUnFoldButtonQuickPanel.Visibility = Visibility.Collapsed; } } @@ -388,9 +408,11 @@ private async void HideLeftQuickPanel() /// private async void HideRightQuickPanel() { + int modeVersion = _foldedModeVersion; if (RightUnFoldButtonQuickPanel.Visibility == Visibility.Visible) { await MoveQuickPanelTo(RightUnFoldButtonQuickPanel, QuickPanelFoldedMargin, true); + if (modeVersion != _foldedModeVersion) return; RightUnFoldButtonQuickPanel.Visibility = Visibility.Collapsed; } } @@ -634,7 +656,8 @@ internal void HandleAutoCollapseOnMouseDown(MouseButtonEventArgs e) if (IsDescendantOf(hitTarget, LeftUnFoldButtonQuickPanel) || IsDescendantOf(hitTarget, RightUnFoldButtonQuickPanel) || IsDescendantOf(hitTarget, LeftSidePanel) || - IsDescendantOf(hitTarget, RightSidePanel)) + IsDescendantOf(hitTarget, RightSidePanel) || + IsDescendantOf(hitTarget, FoldedBall)) { // 重置计时器 StartAutoCollapseQuickPanelTimer(); @@ -740,7 +763,8 @@ private bool IsExpandedEdgeDuringFold(int marginFromEdge) /// private bool IsFoldedAppearanceIntact() { - if (LeftSidePanel.Visibility != Visibility.Visible) return false; + var entry = Settings.Appearance.UseFloatingFoldBall ? (FrameworkElement)FoldedBall : LeftSidePanel; + if (entry.Visibility != Visibility.Visible) return false; return IsFloatingBarUiAbsentFromScreens(); } diff --git a/Ink Canvas/MainWindow_cs/MW_FloatingFoldBall.cs b/Ink Canvas/MainWindow_cs/MW_FloatingFoldBall.cs new file mode 100644 index 000000000..9c00e8484 --- /dev/null +++ b/Ink Canvas/MainWindow_cs/MW_FloatingFoldBall.cs @@ -0,0 +1,80 @@ +using Ink_Canvas.Controls; +using System; +using System.Windows; + +namespace Ink_Canvas +{ + public partial class MainWindow + { + private int _foldedModeVersion; + + internal void ApplyFoldedMode() + { + // 使旧布局失效,但保留折叠/展开互斥状态,直到进行中的操作结束。 + ++_foldedModeVersion; + ++_sidePanelAnimVersion; + StopAutoCollapseQuickPanelTimer(); + LeftSidePanel.BeginAnimation(MarginProperty, null); + RightSidePanel.BeginAnimation(MarginProperty, null); + LeftUnFoldButtonQuickPanel.BeginAnimation(MarginProperty, null); + RightUnFoldButtonQuickPanel.BeginAnimation(MarginProperty, null); + LeftUnFoldButtonQuickPanel.Visibility = Visibility.Collapsed; + RightUnFoldButtonQuickPanel.Visibility = Visibility.Collapsed; + bool useBall = Settings.Appearance.UseFloatingFoldBall; + LeftUnFoldButtonQuickPanel.VerticalAlignment = useBall ? VerticalAlignment.Top : VerticalAlignment.Center; + LeftUnFoldButtonQuickPanel.Margin = new Thickness(QuickPanelFoldedMargin, 0, 0, + Settings.Appearance.QuickPanelBottomOffset); + LeftSidePanel.Visibility = isFloatingBarFolded && !useBall ? Visibility.Visible : Visibility.Collapsed; + LeftSidePanel.Margin = new Thickness(-10, 0, 0, Settings.Appearance.QuickPanelBottomOffset); + RightSidePanel.Margin = new Thickness(0, 0, -10, Settings.Appearance.QuickPanelBottomOffset); + FoldedBall.Visibility = isFloatingBarFolded && useBall ? Visibility.Visible : Visibility.Collapsed; + FoldedBall.SetPosition(new Point(Settings.Appearance.FloatingFoldBallX, Settings.Appearance.FloatingFoldBallY)); + } + + private void FoldedBall_Click(object sender, RoutedEventArgs e) + { + if (!isFloatingBarFolded || isFloatingBarChangingHideMode) return; + if (!Settings.Appearance.IsShowQuickPanel) + { + UnFoldFloatingBar_MouseUp(sender, null); + return; + } + if (LeftUnFoldButtonQuickPanel.Visibility == Visibility.Visible) + { + HideQuickPanelAndResetMargin(); + return; + } + LeftUnFoldButtonQuickPanel.BeginAnimation(MarginProperty, null); + LeftUnFoldButtonQuickPanel.VerticalAlignment = VerticalAlignment.Top; + LeftUnFoldButtonQuickPanel.Visibility = Visibility.Visible; + UpdateFloatingFoldBallLayout(); + StartAutoCollapseQuickPanelTimer(); + } + + private void FoldedBall_PositionChanged(object sender, EventArgs e) + { + Settings.Appearance.FloatingFoldBallX = FoldedBall.Margin.Left; + Settings.Appearance.FloatingFoldBallY = FoldedBall.Margin.Top; + SaveSettingsToFile(); + UpdateFloatingFoldBallLayout(); + } + + private void FoldedBallHost_SizeChanged(object sender, SizeChangedEventArgs e) => UpdateFloatingFoldBallLayout(); + + private void UpdateFloatingFoldBallLayout() + { + if (FoldedBall == null || !Settings.Appearance.UseFloatingFoldBall || + Main_Grid.ActualWidth <= 0 || Main_Grid.ActualHeight <= 0) return; + FoldedBall.SetPosition(new Point(FoldedBall.Margin.Left, FoldedBall.Margin.Top)); + if (LeftUnFoldButtonQuickPanel.Visibility != Visibility.Visible) return; + // 复用原快捷面板;优先放在球右侧,空间不足时放在左侧。 + LeftUnFoldButtonQuickPanel.Margin = new Thickness(0); + LeftUnFoldButtonQuickPanel.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + var size = LeftUnFoldButtonQuickPanel.DesiredSize; + double x = FoldedBall.Margin.Left + FoldedBall.Width + 8; + if (x + size.Width > Main_Grid.ActualWidth) x = FoldedBall.Margin.Left - size.Width - 8; + var point = FloatingFoldBall.ClampPosition(new Point(x, FoldedBall.Margin.Top), Main_Grid.RenderSize, size); + LeftUnFoldButtonQuickPanel.Margin = new Thickness(point.X, point.Y, 0, 0); + } + } +} diff --git a/Ink Canvas/MainWindow_cs/MW_Settings.cs b/Ink Canvas/MainWindow_cs/MW_Settings.cs index 36c1dd391..4666a2a46 100644 --- a/Ink Canvas/MainWindow_cs/MW_Settings.cs +++ b/Ink Canvas/MainWindow_cs/MW_Settings.cs @@ -1495,6 +1495,7 @@ public void ApplySidePanelSettings() LeftSidePanel?.ApplySettings(); RightSidePanel?.ApplySettings(); ApplyQuickPanelLayoutSettings(); + ApplyFoldedMode(); } public void ApplyQuickPanelLayoutSettings() diff --git a/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs b/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs index 1a42b77f1..751aaebd6 100644 --- a/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs +++ b/Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs @@ -953,12 +953,16 @@ internal void ApplyQuickPanelBottomOffset(double offset) var leftQuickPanelMargin = LeftUnFoldButtonQuickPanel.Margin; LeftUnFoldButtonQuickPanel.Margin = new Thickness(leftQuickPanelMargin.Left, leftQuickPanelMargin.Top, leftQuickPanelMargin.Right, offset); + UpdateFloatingFoldBallLayout(); + var rightQuickPanelMargin = RightUnFoldButtonQuickPanel.Margin; RightUnFoldButtonQuickPanel.Margin = new Thickness(rightQuickPanelMargin.Left, rightQuickPanelMargin.Top, rightQuickPanelMargin.Right, offset); } internal void ApplyQuickPanelOpacity(double opacity) { + if (FoldedBall != null) + FoldedBall.Opacity = opacity; if (LeftUnFoldButtonQuickPanel != null) LeftUnFoldButtonQuickPanel.Opacity = opacity; if (RightUnFoldButtonQuickPanel != null) diff --git a/Ink Canvas/MainWindow_cs/MW_WindowChromeHitTest.cs b/Ink Canvas/MainWindow_cs/MW_WindowChromeHitTest.cs index 1c1e4c53f..1fee6560a 100644 --- a/Ink Canvas/MainWindow_cs/MW_WindowChromeHitTest.cs +++ b/Ink Canvas/MainWindow_cs/MW_WindowChromeHitTest.cs @@ -288,6 +288,7 @@ protected override bool ShouldHandleWindowChromeHitTest(Point windowPoint) return ContainsPoint(ViewboxFloatingBar, windowPoint) || ContainsPoint(LeftSidePanel, windowPoint) || ContainsPoint(RightSidePanel, windowPoint) + || ContainsPoint(FoldedBall, windowPoint) || ContainsPoint(LeftUnFoldButtonQuickPanel, windowPoint) || ContainsPoint(RightUnFoldButtonQuickPanel, windowPoint) || ContainsPoint(LeftBottomPanelForPPTNavigation, windowPoint) diff --git a/Ink Canvas/Properties/ThemeStrings.Designer.cs b/Ink Canvas/Properties/ThemeStrings.Designer.cs index ef5254bc2..2e776e73e 100644 --- a/Ink Canvas/Properties/ThemeStrings.Designer.cs +++ b/Ink Canvas/Properties/ThemeStrings.Designer.cs @@ -194,6 +194,11 @@ public static string GetString(string key) public static string Theme_UnfoldButtonIcon => ResourceManager.GetString(nameof(Theme_UnfoldButtonIcon), _resourceCulture); + public static string Theme_FoldedMode => ResourceManager.GetString(nameof(Theme_FoldedMode), _resourceCulture); + public static string Theme_FoldedMode_Sidebar => ResourceManager.GetString(nameof(Theme_FoldedMode_Sidebar), _resourceCulture); + public static string Theme_FoldedMode_Ball => ResourceManager.GetString(nameof(Theme_FoldedMode_Ball), _resourceCulture); + public static string Theme_FloatingFoldBall_Hint => ResourceManager.GetString(nameof(Theme_FloatingFoldBall_Hint), _resourceCulture); + public static string Theme_UnfoldIcon_Arrow => ResourceManager.GetString(nameof(Theme_UnfoldIcon_Arrow), _resourceCulture); public static string Theme_UnfoldIcon_ClassicArrow => ResourceManager.GetString(nameof(Theme_UnfoldIcon_ClassicArrow), _resourceCulture); @@ -437,4 +442,4 @@ public static string GetString(string key) public static string Theme_Tips_Title => ResourceManager.GetString(nameof(Theme_Tips_Title), _resourceCulture); } -} \ No newline at end of file +} diff --git a/Ink Canvas/Properties/ThemeStrings.en-US.resx b/Ink Canvas/Properties/ThemeStrings.en-US.resx index 12548f4bd..df8200415 100644 --- a/Ink Canvas/Properties/ThemeStrings.en-US.resx +++ b/Ink Canvas/Properties/ThemeStrings.en-US.resx @@ -647,4 +647,16 @@ You need to restart the app for theme changes to fully take effect. Restart now? + + Folded toolbar style + + + Sidebar + + + Floating ball + + + Click to expand; drag to move + diff --git a/Ink Canvas/Properties/ThemeStrings.resx b/Ink Canvas/Properties/ThemeStrings.resx index 2518c2b8b..b61d522b6 100644 --- a/Ink Canvas/Properties/ThemeStrings.resx +++ b/Ink Canvas/Properties/ThemeStrings.resx @@ -653,4 +653,16 @@ 更改主题后需要重启应用程序才能完全生效。是否立即重启? - \ No newline at end of file + + 收纳方式 + + + 原有侧边栏 + + + 悬浮球 + + + 点击展开,拖动调整位置 + + diff --git a/Ink Canvas/Properties/ThemeStrings.zh-ME.resx b/Ink Canvas/Properties/ThemeStrings.zh-ME.resx index 6ad12776a..0d7ce8305 100644 --- a/Ink Canvas/Properties/ThemeStrings.zh-ME.resx +++ b/Ink Canvas/Properties/ThemeStrings.zh-ME.resx @@ -647,4 +647,16 @@ 主题切了,但全套皮肤得重开应用才完全到账。现在立刻重启? - \ No newline at end of file + + 收纳方式 + + + 原有侧边栏 + + + 悬浮球 + + + 点击展开,拖动调整位置 + + diff --git a/Ink Canvas/Resources/Settings.cs b/Ink Canvas/Resources/Settings.cs index 92c361267..61c1ed18f 100644 --- a/Ink Canvas/Resources/Settings.cs +++ b/Ink Canvas/Resources/Settings.cs @@ -1035,6 +1035,15 @@ public class Appearance [JsonProperty("quickPanelBottomOffset")] public double QuickPanelBottomOffset { get; set; } = -150; + [JsonProperty("useFloatingFoldBall")] + public bool UseFloatingFoldBall { get; set; } = false; + + [JsonProperty("floatingFoldBallX")] + public double FloatingFoldBallX { get; set; } = 80; + + [JsonProperty("floatingFoldBallY")] + public double FloatingFoldBallY { get; set; } = 200; + [JsonProperty("useMinimalistGrabHandle")] public bool UseMinimalistGrabHandle { get; set; } = true; diff --git a/Ink Canvas/Windows/SettingsViews/Pages/SidebarPage.xaml b/Ink Canvas/Windows/SettingsViews/Pages/SidebarPage.xaml index c5361225a..dc61ab949 100644 --- a/Ink Canvas/Windows/SettingsViews/Pages/SidebarPage.xaml +++ b/Ink Canvas/Windows/SettingsViews/Pages/SidebarPage.xaml @@ -17,6 +17,14 @@ + + + + + + + diff --git a/Ink Canvas/Windows/SettingsViews/Pages/SidebarPage.xaml.cs b/Ink Canvas/Windows/SettingsViews/Pages/SidebarPage.xaml.cs index d0c48898d..2c268df37 100644 --- a/Ink Canvas/Windows/SettingsViews/Pages/SidebarPage.xaml.cs +++ b/Ink Canvas/Windows/SettingsViews/Pages/SidebarPage.xaml.cs @@ -68,6 +68,7 @@ private void LoadSettings() if (settings?.Appearance == null) return; ToggleSwitchEnableQuickPanel.IsOn = settings.Appearance.IsShowQuickPanel; + ComboBoxFoldedMode.SelectedIndex = settings.Appearance.UseFloatingFoldBall ? 1 : 0; QuickPanelBottomOffsetSlider.Value = settings.Appearance.QuickPanelBottomOffset; ComboBoxUnFoldBtnImg.SelectedIndex = settings.Appearance.UnFoldButtonImageType; ToggleSwitchAllowDragSidePanel.IsOn = settings.Appearance.AllowDragSidePanel; @@ -76,6 +77,14 @@ private void LoadSettings() AutoCollapseDelaySlider.Value = settings.Appearance.AutoCollapseQuickPanelDelay; } + private void ComboBoxFoldedMode_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (!_isLoaded) return; + SettingsManager.Settings.Appearance.UseFloatingFoldBall = ComboBoxFoldedMode.SelectedIndex == 1; + SettingsManager.SaveSettingsToFile(); + (Application.Current.MainWindow as MainWindow)?.ApplyFoldedMode(); + } + private void ToggleSwitchEnableQuickPanel_Toggled(object sender, RoutedEventArgs e) { if (!_isLoaded) return; From 9782e5e9cf8fb25386f2c583dcdb729cef7b7f0a Mon Sep 17 00:00:00 2001 From: Huoxing-Rusty <220455872+Huoxing-Rusty@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:57:22 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E4=B8=BA=E6=82=AC=E6=B5=AE=E7=90=83?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=8E=AF=E5=BD=A2=E5=BF=AB=E6=8D=B7=E8=8F=9C?= =?UTF-8?q?=E5=8D=95=E5=92=8C=E6=97=8B=E8=BD=AC=E6=94=B6=E6=94=BE=E4=BA=A4?= =?UTF-8?q?=E4=BA=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Ink Canvas/Controls/FloatingFoldBall.xaml | 33 +++-- Ink Canvas/Controls/FloatingFoldBall.xaml.cs | 21 ++- Ink Canvas/Controls/FloatingFoldMenu.xaml | 84 ++++++++++++ Ink Canvas/Controls/FloatingFoldMenu.xaml.cs | 127 ++++++++++++++++++ Ink Canvas/Helpers/PPTUIManager.cs | 2 + Ink Canvas/MainWindow.xaml | 7 +- Ink Canvas/MainWindow_cs/MW_AutoFold.cs | 15 +-- .../MainWindow_cs/MW_FloatingFoldBall.cs | 95 ++++++++++--- Ink Canvas/MainWindow_cs/MW_SettingsToLoad.cs | 4 - .../MainWindow_cs/MW_WindowChromeHitTest.cs | 1 + .../Properties/ThemeStrings.Designer.cs | 1 + Ink Canvas/Properties/ThemeStrings.en-US.resx | 3 + Ink Canvas/Properties/ThemeStrings.resx | 3 + Ink Canvas/Properties/ThemeStrings.zh-ME.resx | 3 + Ink Canvas/Resources/Settings.cs | 9 ++ .../SettingsViews/Pages/SidebarPage.xaml | 11 ++ .../SettingsViews/Pages/SidebarPage.xaml.cs | 19 ++- 17 files changed, 394 insertions(+), 44 deletions(-) create mode 100644 Ink Canvas/Controls/FloatingFoldMenu.xaml create mode 100644 Ink Canvas/Controls/FloatingFoldMenu.xaml.cs diff --git a/Ink Canvas/Controls/FloatingFoldBall.xaml b/Ink Canvas/Controls/FloatingFoldBall.xaml index c370816ea..927d7d8d1 100644 --- a/Ink Canvas/Controls/FloatingFoldBall.xaml +++ b/Ink Canvas/Controls/FloatingFoldBall.xaml @@ -2,15 +2,28 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:props="clr-namespace:Ink_Canvas.Properties" - Width="48" Height="48" HorizontalAlignment="Left" VerticalAlignment="Top" - Cursor="Hand" ToolTip="{x:Static props:ThemeStrings.Theme_FloatingFoldBall_Hint}" + Width="50.342825" Height="{Binding Width, RelativeSource={RelativeSource Self}}" + HorizontalAlignment="Left" VerticalAlignment="Top" + Cursor="Hand" ToolTip="{x:Static props:ThemeStrings.Theme_FloatingFoldBall_Hint}" Focusable="True" + AutomationProperties.Name="{x:Static props:ThemeStrings.Theme_FloatingFoldBall_Hint}" Stylus.IsPressAndHoldEnabled="False" Stylus.IsFlicksEnabled="False"> - - - - - - + + + + + + + + + + + + + + diff --git a/Ink Canvas/Controls/FloatingFoldBall.xaml.cs b/Ink Canvas/Controls/FloatingFoldBall.xaml.cs index c18400bb9..162afc3b8 100644 --- a/Ink Canvas/Controls/FloatingFoldBall.xaml.cs +++ b/Ink Canvas/Controls/FloatingFoldBall.xaml.cs @@ -9,6 +9,8 @@ public partial class FloatingFoldBall : UserControl { public event RoutedEventHandler Click; public event EventHandler PositionChanged; + public event EventHandler DragMoved; + internal bool IsPointerPressed => _pressed; private Point _pointerStart; private Point _positionStart; @@ -46,10 +48,18 @@ public void SetPosition(Point point) Margin = new Thickness(point.X, point.Y, 0, 0); } + internal void ShowMenuState(bool isOpen, Vector offset) + { + MenuOffset.X = offset.X; + MenuOffset.Y = offset.Y; + PenIcon.Visibility = isOpen ? Visibility.Collapsed : Visibility.Visible; + CloseIcon.Visibility = isOpen ? Visibility.Visible : Visibility.Collapsed; + } + private void BeginDrag(Point pointer) { _pointerStart = pointer; - _positionStart = new Point(Margin.Left, Margin.Top); + _positionStart = new Point(Margin.Left + MenuOffset.X, Margin.Top + MenuOffset.Y); _pressed = true; _dragged = false; } @@ -62,6 +72,7 @@ private void MoveDrag(Point pointer) Math.Abs(delta.Y) < SystemParameters.MinimumVerticalDragDistance) return; _dragged = true; SetPosition(_positionStart + delta); + DragMoved?.Invoke(this, EventArgs.Empty); } private void EndDrag(bool cancelled) @@ -107,6 +118,14 @@ protected override void OnLostMouseCapture(MouseEventArgs e) if (_touch == null) EndDrag(true); } + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (e.Key != Key.Enter && e.Key != Key.Space) return; + if (!e.IsRepeat) Click?.Invoke(this, new RoutedEventArgs()); + e.Handled = true; + } + protected override void OnTouchDown(TouchEventArgs e) { base.OnTouchDown(e); diff --git a/Ink Canvas/Controls/FloatingFoldMenu.xaml b/Ink Canvas/Controls/FloatingFoldMenu.xaml new file mode 100644 index 000000000..c222ee828 --- /dev/null +++ b/Ink Canvas/Controls/FloatingFoldMenu.xaml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + +