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..35dff4915 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);
}
}
}
@@ -872,8 +874,7 @@ private static void ProcessIpcFiles()
// 获取主窗口并打开文件
if (Application.Current.MainWindow is MainWindow mainWindow)
{
- mainWindow.OpenSingleStrokeFile(filePath);
- mainWindow.ShowNotification(string.Format(AutomationStrings.FileAssoc_LoadedStrokesFile, Path.GetFileName(filePath)));
+ mainWindow.OpenStrokeFileFromShell(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..d3a196f7c 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;
}
@@ -130,11 +132,17 @@ public TimeMachineHistory Undo()
}
var item = _currentStrokeHistory[_currentIndex];
- item.StrokeHasBeenCleared = !item.StrokeHasBeenCleared;
- _currentIndex--;
+ var items = new List();
+ do
+ {
+ var entry = _currentStrokeHistory[_currentIndex--];
+ entry.StrokeHasBeenCleared = !entry.StrokeHasBeenCleared;
+ items.Add(entry);
+ } while (item.UndoGroupId != Guid.Empty && _currentIndex >= 0 &&
+ _currentStrokeHistory[_currentIndex].UndoGroupId == item.UndoGroupId);
OnUndoStateChanged?.Invoke(CanUndo);
OnRedoStateChanged?.Invoke(CanRedo);
- return item;
+ return GroupUndoResult(items);
}
public TimeMachineHistory Redo()
@@ -144,10 +152,43 @@ public TimeMachineHistory Redo()
return null;
}
- var item = _currentStrokeHistory[++_currentIndex];
- item.StrokeHasBeenCleared = !item.StrokeHasBeenCleared;
+ var item = _currentStrokeHistory[_currentIndex + 1];
+ var items = new List();
+ do
+ {
+ var entry = _currentStrokeHistory[++_currentIndex];
+ entry.StrokeHasBeenCleared = !entry.StrokeHasBeenCleared;
+ items.Add(entry);
+ } while (item.UndoGroupId != Guid.Empty && _currentIndex + 1 < _currentStrokeHistory.Count &&
+ _currentStrokeHistory[_currentIndex + 1].UndoGroupId == item.UndoGroupId);
+ NotifyUndoRedoState();
+ return GroupUndoResult(items);
+ }
+
+ private static TimeMachineHistory GroupUndoResult(List items) => items.Count == 1
+ ? items[0]
+ : new TimeMachineHistory(new StrokeCollection(), TimeMachineHistoryType.UserInput, false)
+ { GroupedHistories = items.ToArray() };
+
+ // 存储仍是原有的扁平历史,切页、保存和预览无需理解新的历史类型。
+ internal void CommitHistoryGroup(List items)
+ {
+ if (items.Count == 0) return;
+ if (_currentIndex + 1 < _currentStrokeHistory.Count)
+ _currentStrokeHistory.RemoveRange(_currentIndex + 1, _currentStrokeHistory.Count - _currentIndex - 1);
+ var groupId = items.Count > 1 ? Guid.NewGuid() : Guid.Empty;
+ foreach (var item in items) item.UndoGroupId = groupId;
+ _currentStrokeHistory.AddRange(items);
+ _currentIndex = _currentStrokeHistory.Count - 1;
NotifyUndoRedoState();
- 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()
@@ -214,6 +255,8 @@ private static void TransformStrokeCollectionIfNotOnCanvas(StrokeCollection stro
public class TimeMachineHistory
{
+ internal Guid UndoGroupId;
+ internal TimeMachineHistory[] GroupedHistories;
public TimeMachineHistoryType CommitType;
public bool StrokeHasBeenCleared;
public StrokeCollection CurrentStroke;
@@ -289,6 +332,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..a1840d92a 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/插件卸载等)任一步卡死时,由保险丝超时强制结束进程,
// 否则会出现"窗口已关、任务管理器里进程仍挂着"的残留。
@@ -3576,12 +3581,12 @@ private void HandleCommandLineFileOpen()
{
try
{
- // 检查启动参数中是否有.icstk文件
- string icstkFile = FileAssociationManager.GetIcstkFileFromArgs(App.StartArgs);
+ // 检查启动参数中是否有墨迹文件
+ string strokeFile = FileAssociationManager.GetIcstkFileFromArgs(App.StartArgs);
- if (!string.IsNullOrEmpty(icstkFile))
+ if (!string.IsNullOrEmpty(strokeFile))
{
- LogHelper.WriteLogToFile($"检测到命令行参数中的.icstk文件: {icstkFile}", LogHelper.LogType.Event);
+ LogHelper.WriteLogToFile($"检测到命令行参数中的墨迹文件: {strokeFile}", LogHelper.LogType.Event);
// 延迟执行,确保UI已完全加载
Dispatcher.BeginInvoke(new Action(() =>
@@ -3589,8 +3594,7 @@ private void HandleCommandLineFileOpen()
try
{
// 打开文件
- OpenSingleStrokeFile(icstkFile);
- ShowNotification(string.Format(Properties.MainWindowStrings.Main_StrokesFileLoaded, Path.GetFileName(icstkFile)));
+ OpenStrokeFileFromShell(strokeFile);
}
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..dfae89cb0 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,45 +1471,96 @@ 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 (!string.Equals(info.Type, "Pdf", StringComparison.OrdinalIgnoreCase)) return;
- if (string.IsNullOrEmpty(info.SourcePath) || !File.Exists(info.SourcePath)) return;
+ if (info == null || inkCanvas == null || generation != _uinkOpenGeneration) return;
try
{
- uint pageCount = await PdfWinRtHelper.GetPageCountAsync(info.SourcePath);
- if (pageCount == 0) return;
+ var owner = PdfPageIdentity();
+ var view = await CreatePdfFromElementInfoAsync(info, () => owner == PdfPageIdentity());
+ if (view == null) return;
+ inkCanvas.Children.Add(view);
+ _pdfSidebarNextPositionUseHostTransform = true;
+ CompleteRestoredPdf(view, generation);
+ }
+ catch (Exception ex)
+ {
+ LogHelper.WriteLogToFile($"从 .elements.json 恢复 PDF 失败: {ex.Message}", LogHelper.LogType.Error);
+ }
+ }
- 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));
+ private async Task CreatePdfFromElementInfoAsync(CanvasElementInfo info, Func ownsPage)
+ {
+ if (!string.Equals(info.Type, "Pdf", StringComparison.OrdinalIgnoreCase)) return null;
+ if (string.IsNullOrEmpty(info.SourcePath) || !File.Exists(info.SourcePath)) return null;
- var view = new PdfEmbeddedView
- {
- Name = "pdf_" + DateTime.Now.ToString("yyyyMMdd_HH_mm_ss_fff")
- };
- await view.InitializeAsync(info.SourcePath, pageCount, compress, initial);
- WirePdfStrokePersistence(view);
+ var view = new PdfEmbeddedView
+ {
+ Name = "pdf_" + DateTime.Now.ToString("yyyyMMdd_HH_mm_ss_fff")
+ };
+ if (!await RestorePdfFromElementInfoAsync(info, view, ownsPage)) return null;
- if (info.Width > 0) view.Width = info.Width;
- if (info.Height > 0) view.Height = info.Height;
+ if (info.Width > 0) view.Width = info.Width;
+ if (info.Height > 0) view.Height = info.Height;
- InkCanvas.SetLeft(view, info.Left);
- InkCanvas.SetTop(view, info.Top);
+ InkCanvas.SetLeft(view, info.Left);
+ InkCanvas.SetTop(view, info.Top);
- InitializeElementTransform(view);
- BindElementEvents(view);
- inkCanvas.Children.Add(view);
- _pdfSidebarNextPositionUseHostTransform = true;
- SyncPdfPageSidebarWithCanvas();
+ InitializeElementTransform(view);
+ BindElementEvents(view);
+ return view;
+ }
+
+ // 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);
}
- catch (Exception ex)
+ 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))
{
- LogHelper.WriteLogToFile($"从 .elements.json 恢复 PDF 失败: {ex.Message}", LogHelper.LogType.Error);
+ // 正常翻页可暂时卸下控件;等原控件重新上屏再注入主画布回调。
+ 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 翻页。
@@ -1516,7 +1571,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 +1582,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 +1596,7 @@ private void WirePdfStrokePersistence(PdfEmbeddedView view)
};
view.ClearAllStrokes = () =>
{
+ if (!inkCanvas.Children.Contains(view)) return;
ClearStrokes(true);
timeMachine.ClearStrokeHistory();
};
@@ -2066,7 +2122,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 +2742,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 +2758,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_PluginUndo.cs b/Ink Canvas/MainWindow_cs/MW_PluginUndo.cs
index f7db4ce5e..ad609cbab 100644
--- a/Ink Canvas/MainWindow_cs/MW_PluginUndo.cs
+++ b/Ink Canvas/MainWindow_cs/MW_PluginUndo.cs
@@ -53,11 +53,11 @@ internal bool CommitPluginUndoState(string pluginId, string beforeState, string
private void ApplyPluginUndoState(string pluginId, string state)
{
if (string.IsNullOrWhiteSpace(pluginId) || state == null) return;
- if (!_pluginUndoStateHandlers.TryGetValue(pluginId, out var handler)) return;
-
try
{
- handler(state);
+ bool hasHandler = _pluginUndoStateHandlers.TryGetValue(pluginId, out var handler);
+ _pluginWhiteboardStateStore.SetPageState(GetPluginWhiteboardPageIndex(), pluginId, state, !hasHandler);
+ handler?.Invoke(state);
}
catch (Exception ex)
{
diff --git a/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs b/Ink Canvas/MainWindow_cs/MW_Save&OpenStrokes.cs
index 0ae0c410b..cd51f63e3 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()
@@ -176,7 +186,15 @@ private void CollectCanvasElementsMetadata(List elementInfos)
private void RestoreSecAgentSceneElement(CanvasElementInfo info)
{
- if (info == null || inkCanvas == null || string.IsNullOrWhiteSpace(info.SceneElementJson)) return;
+ var element = CreateSecAgentSceneElement(info);
+ if (element == null) return;
+ inkCanvas.Children.Add(element);
+ RefreshRestoredSecAgentElementLayout(element);
+ }
+
+ private FrameworkElement CreateSecAgentSceneElement(CanvasElementInfo info)
+ {
+ if (info == null || inkCanvas == null || string.IsNullOrWhiteSpace(info.SceneElementJson)) return null;
try
{
var typeName = string.Equals(info.Type, "SvgSceneGroup", StringComparison.OrdinalIgnoreCase)
@@ -188,20 +206,20 @@ private void RestoreSecAgentSceneElement(CanvasElementInfo info)
var factoryName = string.Equals(info.Type, "SvgSceneGroup", StringComparison.OrdinalIgnoreCase)
? "FromSerializedScene"
: "FromSerializedElement";
- if (!TryInvokeSerializedElementFactory(type, factoryName, info.SceneElementJson, out var element)) return;
+ if (!TryInvokeSerializedElementFactory(type, factoryName, info.SceneElementJson, out var element)) return null;
element.Name = "svgscene_restore_" + DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
InkCanvas.SetLeft(element, double.IsNaN(info.Left) ? 0 : info.Left);
InkCanvas.SetTop(element, double.IsNaN(info.Top) ? 0 : info.Top);
InitializeElementTransform(element);
RestoreElementTransform(element, info.TransformMatrix);
- inkCanvas.Children.Add(element);
BindElementEvents(element);
- RefreshRestoredSecAgentElementLayout(element);
+ return element;
}
catch (Exception ex)
{
LogHelper.WriteLogToFile($"恢复可编辑 SVG 场景元素失败: {ex}", LogHelper.LogType.Error);
}
+ return null;
}
///
@@ -404,9 +422,15 @@ private static void RestoreElementTransform(FrameworkElement element, string ser
private void RestoreMediaFromElementInfo(CanvasElementInfo info)
{
- if (info == null || inkCanvas == null) return;
- if (!string.Equals(info.Type, "Media", StringComparison.OrdinalIgnoreCase)) return;
- if (string.IsNullOrEmpty(info.SourcePath) || !File.Exists(info.SourcePath)) return;
+ var element = CreateMediaFromElementInfo(info);
+ if (element != null) inkCanvas.Children.Add(element);
+ }
+
+ private CanvasMediaControl CreateMediaFromElementInfo(CanvasElementInfo info)
+ {
+ if (info == null || inkCanvas == null) return null;
+ if (!string.Equals(info.Type, "Media", StringComparison.OrdinalIgnoreCase)) return null;
+ if (string.IsNullOrEmpty(info.SourcePath) || !File.Exists(info.SourcePath)) return null;
try
{
@@ -436,12 +460,13 @@ private void RestoreMediaFromElementInfo(CanvasElementInfo info)
InkCanvas.SetTop(mediaControl, info.Top);
InitializeElementTransform(mediaControl);
BindElementEvents(mediaControl);
- inkCanvas.Children.Add(mediaControl);
+ return mediaControl;
}
catch (Exception ex)
{
LogHelper.WriteLogToFile($"从 .elements.json 恢复媒体失败: {ex.Message}", LogHelper.LogType.Error);
}
+ return null;
}
///
@@ -485,14 +510,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 +567,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 +583,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 +664,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 +675,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 +707,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 +763,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
- {
- 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);
- }
- catch
+ try { if (File.Exists(tmpPath)) File.Delete(tmpPath); }
+ catch (Exception ex)
{
- try { if (File.Exists(tmpPath)) File.Delete(tmpPath); }
- catch (Exception ex)
- {
- LogHelper.WriteLogToFile($"[Settings] 原子写入墨迹文件失败后删除临时文件 {Path.GetFileName(tmpPath)} 失败: {ex.Message}", LogHelper.LogType.Info);
- }
- throw;
+ LogHelper.WriteLogToFile($"[Settings] 原子写入墨迹文件失败后删除临时文件 {Path.GetFileName(tmpPath)} 失败: {ex.Message}", LogHelper.LogType.Info);
}
- 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 +804,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 +815,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 +1302,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 +1335,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 +1391,7 @@ private static string BuildOpenStrokesFilter()
///
private void OpenICCZipFile(string zipFilePath)
{
+ BeginCanvasOpen();
try
{
// 创建临时目录来解压文件
@@ -1621,26 +1564,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 +1638,7 @@ private void RestoreWhiteboardStrokesFromZip(string tempDir, Dictionary
public void OpenXMLStrokeFile(string filePath)
{
+ BeginCanvasOpen();
if (TryBlockFrozenPageMutation("打开墨迹文件")) return;
try
{
@@ -1776,6 +1725,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 +1761,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 +1888,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 +1943,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_StrokeFileOpen.cs b/Ink Canvas/MainWindow_cs/MW_StrokeFileOpen.cs
new file mode 100644
index 000000000..12edbccf5
--- /dev/null
+++ b/Ink Canvas/MainWindow_cs/MW_StrokeFileOpen.cs
@@ -0,0 +1,208 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Ink;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using Ink_Canvas.Helpers;
+using Ink_Canvas.Properties;
+using Ink_Canvas.Windows;
+using Newtonsoft.Json;
+
+namespace Ink_Canvas
+{
+ public partial class MainWindow
+ {
+ private readonly Queue pendingStrokeFiles = new Queue();
+ private bool isOpeningStrokeFile;
+
+ // 冷启动与 IPC 共用此入口;模态窗口的消息循环仍会收到 IPC,按顺序处理,避免叠放弹窗。
+ public async void OpenStrokeFileFromShell(string filePath)
+ {
+ pendingStrokeFiles.Enqueue(filePath);
+ if (isOpeningStrokeFile) return;
+ isOpeningStrokeFile = true;
+ try
+ {
+ while (pendingStrokeFiles.Count > 0)
+ {
+ var path = pendingStrokeFiles.Dequeue();
+ try
+ {
+ if (FileAssociationManager.IsUInkStrokeFile(path))
+ {
+ await OpenUInkFromEntryAsync(path);
+ continue;
+ }
+
+ var dialog = new StrokeFileOpenWindow(path) { Owner = MessageBoxHelper.GetDefaultOwner(this) };
+ if (dialog.Owner == null) dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
+ if (dialog.ShowDialog() == true && await ImportStrokeFile(path, dialog.SelectedTarget))
+ ShowNotification(string.Format(MainWindowStrings.Main_StrokesFileLoaded, Path.GetFileName(path)));
+ }
+ catch (Exception ex)
+ {
+ LogHelper.WriteLogToFile($"打开外部墨迹文件失败: {ex}", LogHelper.LogType.Error);
+ ShowNotification(ex is InvalidDataException || ex is InvalidOperationException
+ ? ex.Message : MainWindowStrings.Main_StrokesFileOpenFailed);
+ }
+ }
+ }
+ finally
+ {
+ isOpeningStrokeFile = false;
+ }
+ }
+
+ internal async Task ImportStrokeFile(string filePath, StrokeFileOpenTarget? target)
+ {
+ if (!target.HasValue) return false;
+ int targetMode = target == StrokeFileOpenTarget.Screen ? 0 : 1;
+ int targetPageIndex = targetMode == 0 ? 0 : CurrentWhiteboardIndex;
+ string targetPageId = _pluginWhiteboardStateStore.GetPageId(targetPageIndex);
+ bool wasInBooth = _isVideoPresenterSpecialMode;
+ int boothPhotoIndex = _boothCurrentPhotoIndex;
+ int generation = _uinkOpenGeneration;
+
+ bool TargetPageUnchanged() => generation == _uinkOpenGeneration &&
+ (targetMode == 0 || CurrentWhiteboardIndex == targetPageIndex) &&
+ _pluginWhiteboardStateStore.GetPageId(targetPageIndex) == targetPageId &&
+ (target != StrokeFileOpenTarget.Booth || (wasInBooth == _isVideoPresenterSpecialMode &&
+ (!wasInBooth || boothPhotoIndex == _boothCurrentPhotoIndex)));
+
+ // 在切换模式之前读完并校验,损坏、空文件不会改变当前画布。
+ StrokeCollection strokes;
+ using (var stream = File.OpenRead(filePath)) strokes = new StrokeCollection(stream);
+ var elements = new List();
+ var sceneElements = new List();
+ var elementsPath = Path.ChangeExtension(filePath, ".elements.json");
+ if (File.Exists(elementsPath))
+ {
+ var infos = JsonConvert.DeserializeObject>(File.ReadAllText(elementsPath))
+ ?? throw new InvalidDataException(MainWindowStrings.Main_StrokesFileOpenFailed);
+ foreach (var info in infos)
+ {
+ if (info == null) throw new InvalidDataException(MainWindowStrings.Main_StrokesFileOpenFailed);
+ FrameworkElement element;
+ switch (info.Type?.ToLowerInvariant())
+ {
+ case "image":
+ if (!File.Exists(info.SourcePath))
+ throw new FileNotFoundException(MainWindowStrings.Main_OpenInk_ElementFailed, info.SourcePath);
+ var bitmap = new BitmapImage();
+ bitmap.BeginInit();
+ bitmap.UriSource = new Uri(info.SourcePath, UriKind.Absolute);
+ bitmap.CacheOption = BitmapCacheOption.OnLoad;
+ bitmap.EndInit();
+ bitmap.Freeze();
+ element = new Image { Source = bitmap, Width = info.Width, Height = info.Height,
+ Stretch = Enum.TryParse(info.Stretch, out var stretch) ? stretch : Stretch.Fill };
+ InkCanvas.SetLeft(element, info.Left);
+ InkCanvas.SetTop(element, info.Top);
+ break;
+ case "pdf":
+ element = await CreatePdfFromElementInfoAsync(info, TargetPageUnchanged);
+ if (!TargetPageUnchanged())
+ throw new InvalidOperationException(MainWindowStrings.Main_OpenInk_PageChanged);
+ break;
+ case "media":
+ element = CreateMediaFromElementInfo(info);
+ break;
+ case "svgscene":
+ case "svgscenegroup":
+ element = CreateSecAgentSceneElement(info);
+ if (element != null) sceneElements.Add(element);
+ break;
+ default:
+ throw new InvalidDataException(MainWindowStrings.Main_OpenInk_ElementFailed);
+ }
+ if (element == null) throw new InvalidDataException(MainWindowStrings.Main_OpenInk_ElementFailed);
+ elements.Add(element);
+ }
+ }
+ var pluginStates = _pluginWhiteboardStateStore.ReadPageSidecars(filePath);
+ if (strokes.Count == 0 && elements.Count == 0 && pluginStates.Count == 0)
+ throw new InvalidDataException(MainWindowStrings.Main_OpenInk_Empty);
+ // PDF 准备期间会让出 UI 线程,用户可能切页、删除页或切换展台照片。
+ if (!TargetPageUnchanged())
+ throw new InvalidOperationException(MainWindowStrings.Main_OpenInk_PageChanged);
+ if (IsPageFrozen(targetPageIndex))
+ throw new InvalidOperationException(MainWindowStrings.Main_Freeze_FrozenNoEdit);
+ if (isDisplayingOrHidingBlackboard)
+ throw new InvalidOperationException(MainWindowStrings.Main_OpenInk_ModeBusy);
+ if (pluginStates.Count > 0) CaptureCurrentPluginPageStates();
+ var pluginChanges = _pluginWhiteboardStateStore.PreparePageAppend(pluginStates, targetPageIndex);
+
+ if (target == StrokeFileOpenTarget.Booth)
+ {
+ // 已在照片页时不重新进入展台,保留当前照片及其变换。
+ if (!_isVideoPresenterSpecialMode) ToggleVideoBooth();
+ }
+ else
+ {
+ if (_isVideoPresenterSpecialMode)
+ {
+ // 先保存展台状态并恢复白板,再向目标页面追加文件。
+ ExitVideoPresenterSpecialMode();
+ CloseVideoPresenterSidebarAndReleaseResources();
+ GridBackgroundCover.Visibility = Visibility.Visible;
+ }
+ if (currentMode != targetMode) ImageBlackboard_MouseUp(null, null);
+ if (target == StrokeFileOpenTarget.Screen && GridTransparencyFakeBackground.Background == Brushes.Transparent)
+ BtnHideInkCanvas_Click(null, null);
+ }
+
+ if (currentMode != targetMode || (target == StrokeFileOpenTarget.Booth && !_isVideoPresenterSpecialMode))
+ throw new InvalidOperationException(MainWindowStrings.Main_OpenInk_ModeBusy);
+
+ // 数据和元素已就绪;同步追加并将整份文件的历史组成一组,避免 PDF 异步加载到其他页面。
+ var history = new List();
+ var previousCommitType = _currentCommitType;
+ _currentCommitType = CommitReason.CodeInput;
+ try
+ {
+ if (strokes.Count > 0)
+ {
+ history.Add(new TimeMachineHistory(strokes, TimeMachineHistoryType.UserInput, false));
+ inkCanvas.Strokes.Add(strokes);
+ }
+ foreach (var element in elements)
+ {
+ history.Add(new TimeMachineHistory(element, TimeMachineHistoryType.ElementInsert));
+ inkCanvas.Children.Add(element);
+ }
+ foreach (var state in pluginChanges)
+ {
+ history.Add(new TimeMachineHistory(state.PluginId, state.EmptyState, state.LoadedState));
+ _pluginWhiteboardStateStore.SetPageState(GetPluginWhiteboardPageIndex(), state.PluginId, state.LoadedState, true);
+ }
+ }
+ catch
+ {
+ for (int i = history.Count - 1; i >= 0; i--)
+ {
+ history[i].StrokeHasBeenCleared = true;
+ ApplyHistoryToCanvas(history[i]);
+ }
+ throw;
+ }
+ finally
+ {
+ _currentCommitType = previousCommitType;
+ }
+ timeMachine.CommitHistoryGroup(history);
+ foreach (var element in sceneElements) RefreshRestoredSecAgentElementLayout(element);
+ foreach (var element in elements)
+ {
+ if (element is not Controls.PdfEmbeddedView pdf) continue;
+ _pdfSidebarNextPositionUseHostTransform = true;
+ CompleteRestoredPdf(pdf, _uinkOpenGeneration);
+ }
+ MarkCurrentPageInkChanged();
+ return true;
+ }
+ }
+}
diff --git a/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs b/Ink Canvas/MainWindow_cs/MW_TimeMachine.cs
index c89829c03..d48fe2c73 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,52 @@ 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.GroupedHistories != null)
{
- 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);
- }
- }
+ foreach (var entry in item.GroupedHistories)
+ ApplyHistoryToCanvas(entry, applyCanvas, includeElements);
+ return;
}
- else if (item.CommitType == TimeMachineHistoryType.Manipulation)
+ _currentCommitType = CommitReason.CodeInput;
+ 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 +299,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 +366,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 +373,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 +401,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/MainWindow_cs/MW_VideoPresenter.cs b/Ink Canvas/MainWindow_cs/MW_VideoPresenter.cs
index c9f1e8694..0280da37a 100644
--- a/Ink Canvas/MainWindow_cs/MW_VideoPresenter.cs
+++ b/Ink Canvas/MainWindow_cs/MW_VideoPresenter.cs
@@ -741,6 +741,8 @@ private void EnterVideoPresenterSpecialMode()
private void ExitVideoPresenterSpecialMode()
{
if (!_isVideoPresenterSpecialMode) return;
+ // 保存方法依赖展台模式标志,必须在退出模式前调用。
+ SaveCurrentBoothState();
_isVideoPresenterSpecialMode = false;
// 退出展台后恢复双指旋转开关
SetBoothGestureRotationUiEnabled(true);
@@ -748,8 +750,6 @@ private void ExitVideoPresenterSpecialMode()
_boothPreviewRestartRetryCount = 0;
LogHelper.WriteLogToFile("[Booth] 退出视频展台拍摄模式,保留拍摄态墨迹、缩放位置与旋转状态", LogHelper.LogType.Info);
- // 退出前完整保存当前展台页面状态(墨迹、缩放、位移、旋转、最后查看页码)
- SaveCurrentBoothState();
// 停止 A4 纸实时识别定时器并隐藏覆盖层
StopPaperDetectTimer();
diff --git a/Ink Canvas/Plugins/PluginWhiteboardStateStore.cs b/Ink Canvas/Plugins/PluginWhiteboardStateStore.cs
index e739e3370..6318119a2 100644
--- a/Ink Canvas/Plugins/PluginWhiteboardStateStore.cs
+++ b/Ink Canvas/Plugins/PluginWhiteboardStateStore.cs
@@ -243,6 +243,44 @@ internal void ResetPage(int pageIndex)
_pageIds[pageIndex] = null;
}
+ internal Dictionary ReadPageSidecars(string contentPath)
+ {
+ var imported = new PluginWhiteboardStateStore();
+ foreach (var pair in _legacyImporters) imported.RegisterLegacyImporter(pair.Key, pair.Value);
+ var path = Path.ChangeExtension(contentPath, ".plugins.json");
+ if (File.Exists(path)) imported.ImportSinglePageJson(File.ReadAllText(path), 0);
+ imported.ImportLegacyPageSidecars(contentPath, 0, (_, error) => throw error);
+ var pageId = imported.GetPageId(0);
+ return imported._states.ToDictionary(pair => pair.Key, pair => pair.Value[pageId], StringComparer.OrdinalIgnoreCase);
+ }
+
+ internal List PreparePageAppend(Dictionary incoming, int pageIndex)
+ {
+ var pageId = GetPageId(pageIndex);
+ var result = new List();
+ foreach (var pair in incoming)
+ {
+ string empty = _providers.TryGetValue(pair.Key, out var provider) && provider is IWhiteboardInitialHistoryProvider baseline
+ ? baseline.CaptureEmptyState() ?? string.Empty : string.Empty;
+ var before = _states.TryGetValue(pair.Key, out var states) && states.TryGetValue(pageId, out var current) ? current : empty;
+ if (string.Equals(before, pair.Value, StringComparison.Ordinal)) continue;
+ // 插件状态是不透明数据,宿主不能猜测其合并规则,也不能覆盖已有内容。
+ if (!string.IsNullOrEmpty(before) && !string.Equals(before, empty, StringComparison.Ordinal))
+ throw new InvalidOperationException(string.Format(Properties.MainWindowStrings.Main_OpenInk_PluginConflict, pair.Key));
+ result.Add(new PluginWhiteboardInitialHistory { PluginId = pair.Key, EmptyState = before, LoadedState = pair.Value });
+ }
+ return result;
+ }
+
+ internal void SetPageState(int pageIndex, string pluginId, string state, bool restore)
+ {
+ var pageId = GetPageId(pageIndex);
+ if (!_states.TryGetValue(pluginId, out var states))
+ _states.Add(pluginId, states = new Dictionary(StringComparer.Ordinal));
+ states[pageId] = state;
+ if (restore && _providers.TryGetValue(pluginId, out var provider)) provider.RestoreState(state);
+ }
+
internal void ResetDocument(int firstPageIndex, int pageCount)
{
ValidateDocumentRange(firstPageIndex, pageCount);
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/Properties/MainWindowStrings.Designer.cs b/Ink Canvas/Properties/MainWindowStrings.Designer.cs
index 4fa517b27..33ee28b14 100644
--- a/Ink Canvas/Properties/MainWindowStrings.Designer.cs
+++ b/Ink Canvas/Properties/MainWindowStrings.Designer.cs
@@ -413,5 +413,34 @@ public static string GetString(string key)
public static string Main_ExitVerifyWithTotp => ResourceManager.GetString(nameof(Main_ExitVerifyWithTotp), _resourceCulture);
public static string Main_ExitVerifyPasswordOnly => ResourceManager.GetString(nameof(Main_ExitVerifyPasswordOnly), _resourceCulture);
+ public static string Main_OpenInk_Title => ResourceManager.GetString(nameof(Main_OpenInk_Title), _resourceCulture);
+
+ public static string Main_OpenInk_ChooseDestination => ResourceManager.GetString(nameof(Main_OpenInk_ChooseDestination), _resourceCulture);
+
+ public static string Main_OpenInk_Screen => ResourceManager.GetString(nameof(Main_OpenInk_Screen), _resourceCulture);
+
+ public static string Main_OpenInk_ScreenDescription => ResourceManager.GetString(nameof(Main_OpenInk_ScreenDescription), _resourceCulture);
+
+ public static string Main_OpenInk_Whiteboard => ResourceManager.GetString(nameof(Main_OpenInk_Whiteboard), _resourceCulture);
+
+ public static string Main_OpenInk_WhiteboardDescription => ResourceManager.GetString(nameof(Main_OpenInk_WhiteboardDescription), _resourceCulture);
+
+ public static string Main_OpenInk_Booth => ResourceManager.GetString(nameof(Main_OpenInk_Booth), _resourceCulture);
+
+ public static string Main_OpenInk_BoothDescription => ResourceManager.GetString(nameof(Main_OpenInk_BoothDescription), _resourceCulture);
+
+ public static string Main_OpenInk_AppendHint => ResourceManager.GetString(nameof(Main_OpenInk_AppendHint), _resourceCulture);
+
+ public static string Main_OpenInk_Cancel => ResourceManager.GetString(nameof(Main_OpenInk_Cancel), _resourceCulture);
+
+ public static string Main_OpenInk_Empty => ResourceManager.GetString(nameof(Main_OpenInk_Empty), _resourceCulture);
+
+ public static string Main_OpenInk_ModeBusy => ResourceManager.GetString(nameof(Main_OpenInk_ModeBusy), _resourceCulture);
+
+ public static string Main_OpenInk_PluginConflict => ResourceManager.GetString(nameof(Main_OpenInk_PluginConflict), _resourceCulture);
+
+ public static string Main_OpenInk_ElementFailed => ResourceManager.GetString(nameof(Main_OpenInk_ElementFailed), _resourceCulture);
+
+ public static string Main_OpenInk_PageChanged => ResourceManager.GetString(nameof(Main_OpenInk_PageChanged), _resourceCulture);
}
}
diff --git a/Ink Canvas/Properties/MainWindowStrings.en-US.resx b/Ink Canvas/Properties/MainWindowStrings.en-US.resx
index 0865e664a..886a7bdae 100644
--- a/Ink Canvas/Properties/MainWindowStrings.en-US.resx
+++ b/Ink Canvas/Properties/MainWindowStrings.en-US.resx
@@ -748,4 +748,49 @@ Please check if the update was successful.
Sorry, an unexpected error occurred that may cause InkCanvasForClass to run unstably.
It is recommended to save your ink and restart the application.
+
+ Open ink file
+
+
+ Choose where to open
+
+
+ Screen annotation
+
+
+ Continue annotating on your screen
+
+
+ Whiteboard
+
+
+ Add ink to the current whiteboard page
+
+
+ Document camera
+
+
+ Overlay ink on the current photo or live view
+
+
+ File contents will be added to the current page. You can undo the entire import.
+
+
+ Cancel
+
+
+ This file contains no content to import.
+
+
+ A mode change is in progress. Please open the file again shortly.
+
+
+ The current page already contains data from plugin "{0}" and it cannot be safely merged. Open this file on an empty page.
+
+
+ An element could not be loaded. Check that companion files and required plugins are available.
+
+
+ The destination page has changed. Please open the file again.
+
\ No newline at end of file
diff --git a/Ink Canvas/Properties/MainWindowStrings.resx b/Ink Canvas/Properties/MainWindowStrings.resx
index 4e561f8be..9eb9ced98 100644
--- a/Ink Canvas/Properties/MainWindowStrings.resx
+++ b/Ink Canvas/Properties/MainWindowStrings.resx
@@ -748,4 +748,49 @@
请输入安全密码以退出软件。
+
+ 打开墨迹文件
+
+
+ 选择打开位置
+
+
+ 屏幕批注
+
+
+ 在屏幕上继续批注
+
+
+ 白板
+
+
+ 添加到当前白板页面
+
+
+ 展台
+
+
+ 叠加到当前照片或实时画面
+
+
+ 文件内容将添加到当前页面,可整体撤销。
+
+
+ 取消
+
+
+ 此文件不包含可导入的内容。
+
+
+ 正在切换模式,请稍后重新打开文件。
+
+
+ 当前页面已有插件“{0}”的内容,无法安全合并。请在空白页面打开此文件。
+
+
+ 无法读取文件中的某个元素。请检查配套文件及所需插件是否齐全。
+
+
+ 目标页面已变化,请重新打开文件。
+
\ No newline at end of file
diff --git a/Ink Canvas/Properties/MainWindowStrings.zh-ME.resx b/Ink Canvas/Properties/MainWindowStrings.zh-ME.resx
index 00c97f7b1..4c3262692 100644
--- a/Ink Canvas/Properties/MainWindowStrings.zh-ME.resx
+++ b/Ink Canvas/Properties/MainWindowStrings.zh-ME.resx
@@ -745,4 +745,49 @@
哎呀出意外了,InkCanvasForClass 可能要寄了。
建议赶紧存墨迹然后复活保平安。
+
+ 打开墨迹文件
+
+
+ 选择打开位置
+
+
+ 屏幕批注
+
+
+ 屏幕上面继续写
+
+
+ 白板
+
+
+ 白板里面继续写
+
+
+ 展台
+
+
+ 展台打开继续写
+
+
+ 点错了可以撤销,没事寄不了
+
+
+ 溜了溜了
+
+
+ 这文件是个啥,空的?
+
+
+ 换模式ing,客官稍后重新打开一
+
+
+ 当前页面已有插件“{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