From fb6c0c71e86c6caa0a47abf72ba64866a7b51240 Mon Sep 17 00:00:00 2001 From: IOL0ol1 <1353839731@qq.com> Date: Wed, 18 Nov 2026 12:49:15 +0800 Subject: [PATCH 01/21] docs: add plan 4 (Avalonia desktop viewer) --- docs/plans/2026-11-18-plan4-viewer.md | 370 ++++++++++++++++++++++++++ 1 file changed, 370 insertions(+) create mode 100644 docs/plans/2026-11-18-plan4-viewer.md diff --git a/docs/plans/2026-11-18-plan4-viewer.md b/docs/plans/2026-11-18-plan4-viewer.md new file mode 100644 index 0000000..e45b818 --- /dev/null +++ b/docs/plans/2026-11-18-plan4-viewer.md @@ -0,0 +1,370 @@ +# Plan 4:Avalonia 桌面查看器 Implementation Plan + +**Goal:** 交付 `samples/OpenSlideSharp.Viewer`,一个跨平台的 Avalonia 桌面查看器,功能对标 openslide-java 的 `Demo` / `OpenSlideView`: +- 打开切片; +- 拖动平移,滚轮以光标为中心缩放; +- 按缩放选层级,后台读取瓦片,LRU 缓存,先显示低分辨率再替换; +- 缩略图导航; +- 属性表; +- 关联图像窗口; +- 矩形选区及“缩放到选区”; +- 状态栏显示坐标、缩放倍率和物理尺寸。 + +**Architecture:** +- 查看器分成两层: + - 与 UI 无关的 `Core/`:视口数学、瓦片网格、按字节计的 LRU 缓存、带代次取消的后台加载器、选区模型。可以用纯 xUnit 测试。 + - Avalonia 层:自绘控件 `SlideView`、`MainWindow`、导航器、关联图像窗口。用 `Avalonia.Headless` 做渲染冒烟测试。 +- 瓦片像素直接来自 `OpenSlide.ReadRegion` 的预乘 BGRA,与 Avalonia 的 `Bgra8888 / Premul` 一致,不需要转换。 +- 另提供一个不开窗口的 `--check ` 模式,供 CI 和计划 5 验证自包含发布包里的原生库。 + +**Tech Stack:** +- .NET 10 +- Avalonia 12.1.6:`Avalonia`、`Avalonia.Desktop`、`Avalonia.Themes.Fluent`、`Avalonia.Fonts.Inter`、`Avalonia.Headless`。Avalonia 依赖 SkiaSharp 3.119.4,与仓库固定的版本一致。 +- xUnit v3 + +**Spec:** `docs/design/2026-11-17-openslidesharp-v4-refactor-design.md`(§6.7);参考 openslide-java 的 `org/openslide/gui/Demo.java`、`OpenSlideView.java`(main 分支)。遗留事项见 `docs/notes/2026-11-18-plan3-carryover.md`。 + +## Global Constraints + +- **项目与依赖:** + - `samples/OpenSlideSharp.Viewer`:`net10.0`,`OutputType=WinExe`,`IsPackable=false`。 + - 只依赖核心包 `OpenSlideSharp`(ProjectReference)和 Avalonia,**不**依赖 AspNetCore 和 `OpenSlideSharp.SkiaSharp`。 + - 原生库:`UseOpenSlideRuntimePackage == 'true'` 时用 `PackageReference OpenSlideSharp.runtime`(版本为 `$(Version)`),否则导入 `eng/OpenSlideNative.targets`。做法与工具相同。 + - Avalonia 各包版本统一为 12.1.6,写入 `Directory.Packages.props`。**不**使用 `Avalonia.Headless.XUnit`:它依赖 xunit.v3 3.x,与仓库的 4.0.3 不一致。测试直接用 `Avalonia.Headless` 的会话 API。 +- **交互**(与 Java Demo 一致,缩放步长改为连续的 2^(1/4)): + - 左键拖动平移; + - 滚轮以光标为中心缩放,每格缩放 2^(1/4); + - Shift + 左键拖动画矩形选区; + - 方向键或 W/A/S/D 平移 100 像素; + - `+`/`=` 放大、`-` 缩小,均以视图中心为准; + - `Z` 适配窗口,`1` 缩放到 1:1(downsample 为 1),空格居中。 +- **缩放范围:** downsample 取值在 `[1/4, max(levelDownsamples[^1], 适配窗口的 downsample) × 2]`。即最多放大到 4 倍像素,最小缩到整图适配窗口再缩一半。 +- **渲染:** + - 层级:`slide.GetBestLevelForDownsample(downsample)`。 + - 瓦片在该层级坐标下为 256×256(边缘瓦片按实际尺寸)。 + - 目标层级的瓦片尚未加载时,退回到已缓存的更粗层级瓦片,把覆盖区域缩放绘制,实现“先低分辨率再高分辨率”。 + - 背景色取 `openslide.background-color`(缺省为白色)。 + - 颜色:不做 ICC 转换,与 Java Demo 一致。README 中说明这一点。 +- **加载:** + - 后台工作线程数为 `min(4, ProcessorCount)`。 + - 视口变化时代次(generation)加 1,旧代次中尚未开始的请求直接丢弃,已经开始的照常完成并写入缓存。 + - 同一瓦片不重复加载。 + - 读取失败(如 `OpenSlideException`)时,在状态栏显示一次错误,之后不再为该切片发起请求。 +- **缓存:** LRU,上限默认 256 MiB(按 `width × height × 4` 计),线程安全。切换切片或关闭窗口时清空。 +- **状态栏:** + - 光标处 level-0 坐标:`x, y`,光标不在图上时为空; + - 缩放:`downsample` 保留两位小数;有 `openslide.objective-power` 时同时显示有效倍率 `objective / downsample`,例如 `10.0×`; + - 有 mpp 时,显示视口宽高和当前选区的物理尺寸(µm 或 mm,自动选单位)。 +- **打开方式:** + - 命令行第一个参数; + - File → Open(`StorageProvider.OpenFilePickerAsync`); + - 拖放文件到窗口。 +- **错误处理:** 打不开时显示对话框,或在状态栏提示(含文件名与原因),程序不退出。 +- **已知问题:** Windows 上损坏的瓦片会直接终止进程(CFG/longjmp,见 known-issues),README 中写明。 +- **`--check ` 模式:** + - 不创建窗口; + - 打开切片,读取最低分辨率层级左上角 256×256 区域; + - 输出 `openslide=` 和 `slide=x`,成功时退出码 0; + - 打不开时退出码为 1;缺少原生库时退出码为 3,并输出 `DllNotFoundException` 的消息。 +- **提交规范:** + - 提交身份 `IOL0ol1 <1353839731@qq.com>`(local config 已设置)。 + - 引用 Skia 类型时用文件顶部的 `using SkiaSharp;`,不写 `SkiaSharp.X` 这样的限定名(R11)。 + +## Review Focus + +1. **快速连续缩放或平移(每秒几十次视口变化)。** 旧视口的请求不得堆积;内存受缓存上限约束;UI 线程不阻塞在 `ReadRegion` 上。→ Task 1 `Loader_NewGeneration_DropsQueuedRequests`、`Cache_StaysWithinBudget`;Task 2 `SlideView_RenderDoesNotReadOnUiThread`。 +2. **在加载过程中关闭窗口或切换切片。** 后台线程不得访问已释放的 `OpenSlide`(不得出现未处理的 `ObjectDisposedException`),切换后不得显示旧切片的瓦片。→ Task 1 `Loader_DisposeWhileLoading_CompletesQuietly`;Task 3 `SwitchSlide_DoesNotShowOldTiles`。 +3. **极端尺寸的切片。** 包括 16×16 的小图、只有 1 层的大图,以及缺少 mpp 或 objective-power 属性的切片。适配窗口、1:1 和导航器都不出现除零、NaN 或负尺寸。→ Task 1 `Viewport_TinySlide_FitAndClamp`、`Viewport_NoLevels_Defaults`;Task 3 `StatusBar_NoMpp_OmitsPhysicalSize`。 +4. **打不开或损坏的文件**(`unopenable.tiff`、文本文件)**不能让程序崩溃**。→ Task 3 `Open_UnopenableFile_ShowsErrorAndKeepsRunning`。 +5. **高 DPI**(缩放 150%/200%)。瓦片按物理像素清晰绘制,坐标换算使用逻辑像素,选区和导航矩形位置正确。→ Task 2 `SlideView_RenderScaling_UsesPhysicalPixels`(headless 模式下设 RenderScaling 为 2)。 + +--- + +### Task 1: 项目骨架与 UI 无关的核心(视口、网格、缓存、加载器、选区) + +**Files:** +- Create: + - `samples/OpenSlideSharp.Viewer/OpenSlideSharp.Viewer.csproj`、`Program.cs`(含 `--check`)、`App.axaml(.cs)`(最小 Fluent 主题与空 MainWindow 占位) + - `samples/OpenSlideSharp.Viewer/Core/Viewport.cs`、`TileGrid.cs`、`TileKey.cs`、`TileCache.cs`、`TileLoader.cs`、`Selection.cs`、`SelectionList.cs` + - `test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj`:xUnit v3 MTP,ProjectReference 指向查看器,fixtures 从 `../OpenSlideSharp.Tests/Fixtures/**` 链接,导入 `eng/OpenSlideNative.targets` + - `test/OpenSlideSharp.Viewer.Tests/ViewportTests.cs`、`TileGridTests.cs`、`TileCacheTests.cs`、`TileLoaderTests.cs`、`CheckModeTests.cs` +- Modify: `OpenSlideSharp.slnx`、`Directory.Packages.props`(Avalonia 12.1.6 各包) + +**Interfaces(`internal`,命名空间 `OpenSlideSharp.Viewer.Core`;查看器项目对测试项目开放 InternalsVisibleTo):** + +```csharp +readonly record struct TileKey(int Level, long Column, long Row); + +sealed class Viewport +{ + Viewport(SlideSize slideSize, IReadOnlyList levelDownsamples); + double Downsample { get; } // 屏幕上一个逻辑像素对应的 level-0 像素数 + double CenterX { get; } double CenterY { get; } // level-0 坐标 + double ViewWidth { get; } double ViewHeight { get; } // 逻辑像素 + void Resize(double width, double height); + void ZoomAt(double screenX, double screenY, double factor); // factor > 1 放大;光标下的 level-0 点保持不动 + void PanBy(double dxScreen, double dyScreen); + void Fit(); void OneToOne(); void Center(); + void CenterOn(double x0, double y0); + void ZoomTo(double x0, double y0, double width0, double height0); // 适配一个 level-0 矩形(选区) + (double X, double Y) ScreenToSlide(double sx, double sy); + (double X, double Y) SlideToScreen(double x0, double y0); + (double MinDownsample, double MaxDownsample) Limits { get; } + event Action? Changed; +} + +sealed class TileGrid +{ + const int TileSize = 256; + TileGrid(IReadOnlyList levelDimensions, IReadOnlyList levelDownsamples); + IEnumerable VisibleTiles(int level, double left0, double top0, double right0, double bottom0); // level-0 视窗矩形 + (long X0, long Y0, int Width, int Height) Region(TileKey key); // ReadRegion 参数:level-0 左上角 + 该层宽高 + (double Left0, double Top0, double Right0, double Bottom0) Bounds(TileKey key); +} + +sealed class TileCache : IDisposable +{ + TileCache(long budgetBytes); + bool TryGet(TileKey key, out TileImage? tile); + void Add(TileKey key, TileImage tile); // 超出预算时淘汰最久未用者(Dispose 被淘汰的 TileImage) + long SizeBytes { get; } int Count { get; } + void Clear(); +} + +sealed class TileImage : IDisposable // 平台无关的像素容器:预乘 BGRA +{ + int Width { get; } int Height { get; } byte[] Pixels { get; } // UI 层在首次绘制时转换为 Avalonia Bitmap 并缓存 +} + +sealed class TileLoader : IDisposable +{ + TileLoader(Func read, TileCache cache, int workers, Action loaded); + long Generation { get; } + void Request(IEnumerable keys); // 新代次:替换队列,按给定顺序(中心优先)处理;已缓存或已在途的跳过 + event Action? Failed; // 首次失败后停止接受新请求 +} + +sealed record Selection(double X0, double Y0, double Width0, double Height0); // level-0 矩形 +sealed class SelectionList { IReadOnlyList Items { get; } void Add(Selection s); void RemoveAt(int i); event Action? Changed; } +``` + +- **视口:** 初始状态为适配窗口并居中。`ZoomAt` 与 `Fit` 都会把 downsample 限制在 `Limits` 之内。视口尺寸为 0 时,`Fit` 保持原状态。 +- **加载器:** + - `Request` 先清空尚未开始的旧请求,再按调用方给出的顺序入队; + - 工作线程从队列取出瓦片,调用 `read` 读取,写入缓存,再触发 `loaded`(在工作线程上触发,UI 层自己切回 UI 线程); + - `Dispose` 先停止接收请求,再等待正在执行的读取结束,最多等 5 秒;之后不再触发任何回调。 +- **`--check` 模式:** 写在 `Program.Main` 中,不启动 Avalonia。 + +- [ ] **Step 1: 写失败的测试** + +`ViewportTests`: +- `Viewport_Fit_CentersWholeSlide`:slide 为 300×250,视口为 150×125。`Downsample == 2`,中心为 (150, 125)。 +- `Viewport_ZoomAt_KeepsPointUnderCursor`:在屏幕坐标 (30, 40) 处缩放 1.5 倍前后,`ScreenToSlide(30, 40)` 的结果误差不超过 1e-9。 +- `Viewport_ZoomClampsToLimits`:缩放 1e6 倍后 downsample 等于 MinDownsample(0.25)。 +- `Viewport_OneToOne_SetsDownsample1`。 +- `Viewport_TinySlide_FitAndClamp`:slide 为 16×16,视口为 800×600。Fit 后 downsample 等于 0.25(下限)。所有输出都不含 NaN。 +- `Viewport_NoLevels_Defaults`:level downsample 列表只有 `[1]`,视口为 0×0。各方法都不抛异常、不产生 NaN。 +- `Viewport_ZoomTo_FitsRectangle`。 + +`TileGridTests`: +- `TileGrid_VisibleTiles_CoversViewExactly`:boxes.tiff level 0(300×250),视窗 (0, 0, 300, 250),得到 2×1 共 2 个瓦片:(0,0) 为 256×250,(1,0) 为 44×250。 +- `TileGrid_Region_UsesLevelDownsample`:level 2(75×62,downsample 4.016129032258064)的 (0,0) 瓦片,Region 返回 (0, 0, 75, 62)。 +- `TileGrid_OutsideSlide_NoTiles`:视窗完全在切片之外时为空。 + +`TileCacheTests`: +- `Cache_StaysWithinBudget`:预算为 1 MiB,依次加入 10 个 256×256 瓦片(每个 256 KiB)。之后 `SizeBytes ≤ 1 MiB`,`Count == 4`,被淘汰的瓦片已 Dispose。 +- `Cache_LruOrder`:访问过的瓦片后淘汰。 +- `Cache_ConcurrentAccess`:8 个线程交替执行 Add 和 TryGet,不抛异常,且最终仍在预算内。 + +`TileLoaderTests`(`read` 用可控的假读取器:用信号控制阻塞,并计数): +- `Loader_LoadsAndNotifies`。 +- `Loader_NewGeneration_DropsQueuedRequests`:单个 worker,第一个请求阻塞时再提交 100 个请求,随后换新的一代提交 2 个;最终只读取了 1 + 2 个。 +- `Loader_DoesNotDuplicateInFlight`。 +- `Loader_DisposeWhileLoading_CompletesQuietly`:read 阻塞时调用 Dispose;释放阻塞后 Dispose 返回,不再触发 loaded,也没有异常逃逸。 +- `Loader_FailureStopsFurtherRequests`。 + +`CheckModeTests`: +- 调用 `Program.RunCheck(["--check", small.svs], stdout)`:返回 0,输出含 `openslide=4.` 和 `slide=16x16`; +- 传入 `unopenable.tiff` 时返回 1; +- `RunCheck` 是 internal 方法,返回退出码。 + +- [ ] **Step 2: 运行,确认失败**(编译错误) +- [ ] **Step 3: 实现** + +csproj 中 Avalonia 设置 `AvaloniaUseCompiledBindingsByDefault=true`。`App` 只放 FluentTheme 和 Inter 字体。 + +- [ ] **Step 4: 运行全部测试,确认通过** + +Run: `dotnet test OpenSlideSharp.slnx -c Release` + +- [ ] **Step 5: Commit** + +```bash +git add -A && git commit -m "feat: add the viewer's core (viewport, tile grid, cache, loader) and --check mode" +``` + +--- + +### Task 2: `SlideView` 控件(渲染、平移缩放、键盘、选区绘制) + +**Files:** +- Create: + - `samples/OpenSlideSharp.Viewer/Controls/SlideView.cs` + - `samples/OpenSlideSharp.Viewer/Controls/TileBitmapCache.cs`(把 `TileImage` 转为 `WriteableBitmap`,与 `TileCache` 同生命周期) + - `test/OpenSlideSharp.Viewer.Tests/HeadlessSession.cs`(`HeadlessUnitTestSession.StartNew(typeof(App))` 单例,加上一个在会话中执行的 `Run(Func)` 辅助方法) + - `test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs` + +**Interfaces:** +- Consumes: Task 1 的 Core 类型。 +- Produces: + +```csharp +sealed class SlideView : Control +{ + OpenSlide? Slide { get; set; } // 设置时重建 Viewport/TileGrid/TileCache/TileLoader,并对旧对象 Dispose + Viewport? Viewport { get; } + SelectionList Selections { get; } + (double X, double Y)? PointerSlidePosition { get; } // 光标处 level-0 坐标;光标不在控件上时为 null + event Action? ViewChanged; // 视口或光标变化时触发(状态栏、导航器订阅) + event Action? LoadFailed; + long TileReads { get; } // 诊断/测试用:累计 ReadRegion 次数 +} +``` + +- **Render(DrawingContext):** + 1. 填充背景色; + 2. 计算目标层级和可见瓦片: + - 已缓存的瓦片直接绘制; + - 未缓存的瓦片按坐标从近到远(中心优先)放进请求列表,并按 level+1、level+2… 依次寻找已缓存的更粗层级瓦片,裁出覆盖区域绘制; + 3. 提交请求; + 4. 绘制选区(1 个设备像素的轮廓,颜色 `#FFD000`;正在拖动的选区画虚线)。 +- **线程:** Render 中**不得**调用 `ReadRegion`。瓦片加载完成后,通过 `Dispatcher.UIThread.Post(InvalidateVisual)` 合并刷新:同一帧只调度一次。 +- **高 DPI:** 以 `VisualRoot.RenderScaling` 计算设备像素。瓦片按目标层级像素与设备像素对齐绘制,使用 `RenderOptions.BitmapInterpolationMode=HighQuality`。 +- **输入:** + - 左键拖动平移;Shift + 左键拖动画选区,松开时宽高都大于 0 才加入; + - 滚轮按 `delta.Y` 换算为 2^(delta/4); + - 键盘按 Global Constraints 的映射处理,控件可获得焦点(`Focusable=true`),按下鼠标时获得焦点。 + +- [ ] **Step 1: 写失败的测试**(headless 会话,窗口 400×300,内容为 SlideView) +- `SlideView_RendersSlidePixels`: + - `Slide = boxes.tiff`,等加载完成(轮询 `TileReads > 0` 且没有待处理请求,最多 5 秒,期间不断 `Dispatcher.UIThread.RunJobs()`); + - 用 `CaptureRenderedFrame()` 截取画面,至少有 1000 个像素不是背景白色。boxes.tiff 含红、蓝、绿色块。 +- `SlideView_RenderDoesNotReadOnUiThread`:用测试替身记录 read 调用所在的线程 ID,所有调用都不在 UI 线程上。实现时可通过 internal 的读取器注入点完成。 +- `SlideView_WheelZoomsAtPointer`:在 (100, 80) 滚动 +1 格后,`PointerSlidePosition` 在缩放前后的差值不超过 1 个 level-0 像素。 +- `SlideView_DragPans`:拖动 (50, 0) 后,`Viewport.CenterX` 减少 `50 × downsample`。 +- `SlideView_ShiftDragAddsSelection`:选区数量变为 1,矩形与拖动范围换算一致。 +- `SlideView_Keyboard_ZoomFitAndOneToOne`:按 `1` 后 downsample 为 1;按 `Z` 后与 `Fit()` 的结果相同。 +- `SlideView_RenderScaling_UsesPhysicalPixels`:`RenderScaling = 2` 时,截图像素尺寸为 800×600,色块边缘位置换算正确(±2 设备像素)。如果 headless 后端不支持设置 RenderScaling,则在测试中 `Assert.Skip` 并写明原因。 +- `SlideView_SwitchSlide_DisposesOldLoader`:从 boxes.tiff 切换到 small.svs 后,旧加载器已 Dispose,缓存已清空。 + +- [ ] **Step 2: 运行,确认失败** +- [ ] **Step 3: 实现** +- [ ] **Step 4: 运行全部测试,确认通过** +- [ ] **Step 5: Commit** + +```bash +git add -A && git commit -m "feat: add the SlideView control with tiled rendering, pan, zoom and selections" +``` + +--- + +### Task 3: 主窗口(打开、导航器、属性、关联图像、选区列表、状态栏) + +**Files:** +- Create: + - `samples/OpenSlideSharp.Viewer/MainWindow.axaml(.cs)` + - `samples/OpenSlideSharp.Viewer/Controls/Navigator.cs` + - `samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml(.cs)` + - `samples/OpenSlideSharp.Viewer/StatusFormatter.cs`(纯函数,便于测试) + - `test/OpenSlideSharp.Viewer.Tests/MainWindowTests.cs`、`StatusFormatterTests.cs` +- Modify: `samples/OpenSlideSharp.Viewer/App.axaml.cs`(按命令行参数打开切片) + +**Interfaces:** +- **布局:** + - 顶部菜单:File(Open…、Close、Exit)、View(Fit、1:1、Center)。 + - 左栏(可拖动分隔条):上部导航器(缩略图 + 视口矩形,单击或拖动跳转),下部 Tab:Properties(按键名排序的两列列表,可复制)、Associated images(列表,双击打开窗口)、Selections(列表,每项带 “Zoom to” 和 “Delete” 按钮)。 + - 中间:`SlideView`。 + - 底部:状态栏。 + - 窗口标题:`OpenSlide Viewer — <文件名>`。 +- **`MainWindow.OpenAsync(string path)`:** + - 先 `OpenSlide.Open`; + - 失败时显示错误(内嵌对话框或状态栏红字),保留原切片; + - 成功后替换切片:释放旧 `OpenSlide`,同时清空选区、属性和关联图像。 +- **导航器缩略图:** `slide.GetThumbnail(256, 256)`,或缩略图关联图像,先取到哪个用哪个。 +- **关联图像窗口:** 显示 `AssociatedImage.Read()` 的结果(预乘 BGRA → WriteableBitmap),按窗口大小等比缩放;标题为图像名。 +- **StatusFormatter:** + - `Coordinates(double? x, double? y) → string`:`"x: 1234 y: 567"`,参数为空时返回 `""`; + - `Zoom(double downsample, double? objectivePower) → string`:`"1:4.02 (9.96×)"`,没有 objectivePower 时只显示 `"1:4.02"`; + - `PhysicalSize(double width0, double height0, double? mppX, double? mppY) → string`: + - 两个 mpp 都有效时返回 `"812.5 × 600.0 µm"`;任一边达到 1000 µm 时改用 mm 并保留 2 位小数,例如 `"1.25 × 0.80 mm"`; + - 否则返回 `""`。 +- **拖放:** 窗口接受拖入的文件,取第一个打开。 + +- [ ] **Step 1: 写失败的测试** + +`StatusFormatterTests`: +- 坐标:`Coordinates(null, null) == ""`,`Coordinates(1234.6, 567.2) == "x: 1234 y: 567"`(向下取整)。 +- 缩放:`Zoom(4.016129, 40) == "1:4.02 (9.96×)"`;`Zoom(1, null) == "1:1.00"`。 +- 物理尺寸: + - `PhysicalSize(1625, 1200, 0.5, 0.5) == "812.5 × 600.0 µm"`; + - `PhysicalSize(5000, 3200, 0.25, 0.25) == "1.25 × 0.80 mm"`; + - `PhysicalSize(10, 10, null, 0.5) == ""`; + - `StatusBar_NoMpp_OmitsPhysicalSize`:`PhysicalSize(800, 600, null, null) == ""`,且 `PhysicalSize(800, 600, double.NaN, 0.5) == ""`。 + +`MainWindowTests`(headless): +- `Open_ShowsPropertiesSorted`:打开 small.svs 后 Properties 列表包含 `openslide.vendor`,且按键名排序。 +- `Open_ListsAssociatedImages`:small.svs 的 Associated images 列表含 `thumbnail`;打开它的窗口后,窗口标题为 `thumbnail`,图像为 16×16。 +- `Navigator_ClickCentersView`:在导航器上点击 (10, 10) 后,主视口中心按缩略图比例换算正确(±1 level-0 像素 × 缩略图比例)。 +- `Selections_ZoomTo`:加入一个选区后点击 “Zoom to”,视口完整包含该选区,且至少一边贴合(±1 逻辑像素)。 +- `Open_UnopenableFile_ShowsErrorAndKeepsRunning`:先打开 boxes.tiff,再打开 unopenable.tiff;错误文本中含文件名,原切片仍在显示,属性列表不变。 +- `SwitchSlide_DoesNotShowOldTiles`:从 boxes.tiff 切换到 small.svs 并等待加载完成。截图中不出现 boxes 的纯红块:红色像素少于 10 个。small.svs 不含纯红。 +- `Title_ShowsFileName`。 + +- [ ] **Step 2: 运行,确认失败** +- [ ] **Step 3: 实现** +- [ ] **Step 4: 运行全部测试,确认通过**;再手动运行一次 `dotnet run --project samples/OpenSlideSharp.Viewer -- test/OpenSlideSharp.Tests/Fixtures/boxes.tiff`,用截图确认窗口正常显示,然后关闭。在报告里附上截图的保存路径(放在 scratchpad 中)。 +- [ ] **Step 5: Commit** + +```bash +git add -A && git commit -m "feat: add the viewer window with navigator, properties, associated images and selections" +``` + +--- + +### Task 4: 自包含发布冒烟、CI 与文档 + +**Files:** +- Modify: + - `eng/Test-Packages.ps1` + - `.github/workflows/ci.yml`(如需要) + - `README.md` +- Create: `samples/OpenSlideSharp.Viewer/README.md` + +**Interfaces:** +- **`Test-Packages.ps1` 新增查看器发布冒烟**,在所有平台的非 `-SkipPack` 和 `-SkipPack` 运行中都执行: + - 发布命令:`dotnet publish samples/OpenSlideSharp.Viewer -c Release -r <宿主 RID> --self-contained -p:PublishSingleFile=true -p:UseOpenSlideRuntimePackage=true -p:OpenSlideSharpVersion=`; + - 还原源加上本地 feed,`NUGET_PACKAGES` 指向隔离缓存; + - 宿主 RID 为 win-x64、linux-x64、linux-arm64、osx-arm64 之一,与 PackageSmoke 的判定方式相同。 + - 运行 `/OpenSlideSharp.Viewer[.exe] --check `,断言退出码为 0,并输出 `slide=16x16`。 + - 单文件发布时,原生库的位置要么在可执行文件旁边,要么启用 `IncludeNativeLibrariesForSelfExtract=true`。选哪种由实现者决定:应选计划 5 发布时更方便的那种,并写进 README。 +- **`ci.yml`:** 原有的 package 和 package-unix 已经运行 `Test-Packages.ps1`,所以无需新增 job。如果发布耗时导致 job 超过 30 分钟,再调大 timeout。 +- **文档:** + - 根 README 增加一节 “Desktop viewer”:运行方式和快捷键表,保持简洁; + - 查看器 README 写明: + - 功能与快捷键; + - 不做 ICC 转换; + - Windows 上的已知崩溃; + - `--check` 模式; + - 自包含发布命令(计划 5 的 Release 会附上 win-x64、linux-x64、osx-arm64 三个构建)。 + +- [ ] **Step 1: 扩展 `Test-Packages.ps1`,本机运行** + +Run: `pwsh eng/Get-OpenSlide.ps1 -Platform all; pwsh eng/Test-Packages.ps1` +Expected: `All package smoke tests passed.`,输出中包含查看器 `--check` 的成功行。 + +- [ ] **Step 2: 更新文档** +- [ ] **Step 3: 运行全部测试,提交** + +```bash +git add -A && git commit -m "ci: publish the viewer self-contained and check it on every platform; document it" +``` From 6da071474b00ec094990a47de4ee9d9d83162f90 Mon Sep 17 00:00:00 2001 From: IOL0ol1 <1353839731@qq.com> Date: Wed, 18 Nov 2026 13:09:42 +0800 Subject: [PATCH 02/21] feat: add the viewer's core (viewport, tile grid, cache, loader) and --check mode --- Directory.Packages.props | 5 + OpenSlideSharp.slnx | 2 + samples/OpenSlideSharp.Viewer/App.axaml | 10 + samples/OpenSlideSharp.Viewer/App.axaml.cs | 26 ++ .../OpenSlideSharp.Viewer/Core/Selection.cs | 4 + .../Core/SelectionList.cs | 45 ++++ .../OpenSlideSharp.Viewer/Core/TileCache.cs | 165 ++++++++++++ .../OpenSlideSharp.Viewer/Core/TileGrid.cs | 116 ++++++++ .../OpenSlideSharp.Viewer/Core/TileImage.cs | 46 ++++ samples/OpenSlideSharp.Viewer/Core/TileKey.cs | 4 + .../OpenSlideSharp.Viewer/Core/TileLoader.cs | 240 +++++++++++++++++ .../OpenSlideSharp.Viewer/Core/Viewport.cs | 178 +++++++++++++ .../OpenSlideSharp.Viewer.csproj | 37 +++ samples/OpenSlideSharp.Viewer/Program.cs | 74 ++++++ samples/OpenSlideSharp.Viewer/app.manifest | 12 + .../CheckModeTests.cs | 52 ++++ .../OpenSlideSharp.Viewer.Tests.csproj | 26 ++ .../SelectionListTests.cs | 37 +++ test/OpenSlideSharp.Viewer.Tests/TestFiles.cs | 28 ++ .../TileCacheTests.cs | 182 +++++++++++++ .../TileGridTests.cs | 77 ++++++ .../TileLoaderTests.cs | 211 +++++++++++++++ .../ViewportTests.cs | 247 ++++++++++++++++++ 23 files changed, 1824 insertions(+) create mode 100644 samples/OpenSlideSharp.Viewer/App.axaml create mode 100644 samples/OpenSlideSharp.Viewer/App.axaml.cs create mode 100644 samples/OpenSlideSharp.Viewer/Core/Selection.cs create mode 100644 samples/OpenSlideSharp.Viewer/Core/SelectionList.cs create mode 100644 samples/OpenSlideSharp.Viewer/Core/TileCache.cs create mode 100644 samples/OpenSlideSharp.Viewer/Core/TileGrid.cs create mode 100644 samples/OpenSlideSharp.Viewer/Core/TileImage.cs create mode 100644 samples/OpenSlideSharp.Viewer/Core/TileKey.cs create mode 100644 samples/OpenSlideSharp.Viewer/Core/TileLoader.cs create mode 100644 samples/OpenSlideSharp.Viewer/Core/Viewport.cs create mode 100644 samples/OpenSlideSharp.Viewer/OpenSlideSharp.Viewer.csproj create mode 100644 samples/OpenSlideSharp.Viewer/Program.cs create mode 100644 samples/OpenSlideSharp.Viewer/app.manifest create mode 100644 test/OpenSlideSharp.Viewer.Tests/CheckModeTests.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj create mode 100644 test/OpenSlideSharp.Viewer.Tests/SelectionListTests.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/TestFiles.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/TileCacheTests.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/TileGridTests.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/TileLoaderTests.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/ViewportTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 26bc3d1..0d34d7c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,6 +9,11 @@ + + + + + diff --git a/OpenSlideSharp.slnx b/OpenSlideSharp.slnx index b1ad4e5..5c3763e 100644 --- a/OpenSlideSharp.slnx +++ b/OpenSlideSharp.slnx @@ -1,5 +1,6 @@ + @@ -14,5 +15,6 @@ + diff --git a/samples/OpenSlideSharp.Viewer/App.axaml b/samples/OpenSlideSharp.Viewer/App.axaml new file mode 100644 index 0000000..fc79f69 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/App.axaml @@ -0,0 +1,10 @@ + + + + + + + diff --git a/samples/OpenSlideSharp.Viewer/App.axaml.cs b/samples/OpenSlideSharp.Viewer/App.axaml.cs new file mode 100644 index 0000000..01ed888 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/App.axaml.cs @@ -0,0 +1,26 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; + +namespace OpenSlideSharp.Viewer; + +/// The Avalonia application: the Fluent theme (App.axaml) and the main window. +public partial class App : Application +{ + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + // Placeholder until the main window exists. + desktop.MainWindow = new Window { Title = "OpenSlide Viewer", Width = 1024, Height = 768 }; + } + + base.OnFrameworkInitializationCompleted(); + } +} diff --git a/samples/OpenSlideSharp.Viewer/Core/Selection.cs b/samples/OpenSlideSharp.Viewer/Core/Selection.cs new file mode 100644 index 0000000..af78676 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/Selection.cs @@ -0,0 +1,4 @@ +namespace OpenSlideSharp.Viewer.Core; + +/// A rectangular selection in level-0 coordinates. +internal sealed record Selection(double X0, double Y0, double Width0, double Height0); diff --git a/samples/OpenSlideSharp.Viewer/Core/SelectionList.cs b/samples/OpenSlideSharp.Viewer/Core/SelectionList.cs new file mode 100644 index 0000000..2d4208b --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/SelectionList.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace OpenSlideSharp.Viewer.Core; + +/// The selections drawn on the slide, in the order they were made. Used on the UI thread only. +internal sealed class SelectionList +{ + private readonly List _items = new(); + + public SelectionList() + { + Items = new ReadOnlyCollection(_items); + } + + public IReadOnlyList Items { get; } + + /// Raised after the list changes. + public event Action? Changed; + + public void Add(Selection s) + { + ArgumentNullException.ThrowIfNull(s); + _items.Add(s); + Changed?.Invoke(); + } + + public void RemoveAt(int i) + { + _items.RemoveAt(i); + Changed?.Invoke(); + } + + public void Clear() + { + if (_items.Count == 0) + { + return; + } + + _items.Clear(); + Changed?.Invoke(); + } +} diff --git a/samples/OpenSlideSharp.Viewer/Core/TileCache.cs b/samples/OpenSlideSharp.Viewer/Core/TileCache.cs new file mode 100644 index 0000000..0312837 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileCache.cs @@ -0,0 +1,165 @@ +using System; +using System.Collections.Generic; + +namespace OpenSlideSharp.Viewer.Core; + +/// +/// A thread-safe least-recently-used cache of tiles, limited by their total size (width * height * 4 bytes +/// each). Tiles it drops, by eviction, replacement, or , are disposed. +/// +internal sealed class TileCache : IDisposable +{ + /// The default budget: 256 MiB. + public const long DefaultBudgetBytes = 256L * 1024 * 1024; + + private readonly long _budget; + private readonly object _lock = new(); + private readonly Dictionary> _entries = new(); + private readonly LinkedList _recency = new(); // most recently used first + private long _size; + private bool _disposed; + + public TileCache(long budgetBytes) + { + ArgumentOutOfRangeException.ThrowIfNegative(budgetBytes); + _budget = budgetBytes; + } + + public long SizeBytes + { + get + { + lock (_lock) + { + return _size; + } + } + } + + public int Count + { + get + { + lock (_lock) + { + return _entries.Count; + } + } + } + + /// Looks up a tile and, if it is there, marks it as the most recently used. + public bool TryGet(TileKey key, out TileImage? tile) + { + lock (_lock) + { + if (_entries.TryGetValue(key, out LinkedListNode? node)) + { + _recency.Remove(node); + _recency.AddFirst(node); + tile = node.Value.Tile; + return true; + } + } + + tile = null; + return false; + } + + /// Looks up a tile without changing its place in the eviction order. + public bool Contains(TileKey key) + { + lock (_lock) + { + return _entries.ContainsKey(key); + } + } + + /// + /// Adds a tile as the most recently used one, replacing any tile with the same key, then evicts the least + /// recently used tiles until the cache is within its budget. A tile larger than the whole budget is not kept. + /// After the tile is disposed straight away. + /// + public void Add(TileKey key, TileImage tile) + { + ArgumentNullException.ThrowIfNull(tile); + var dropped = new List(); + lock (_lock) + { + if (_disposed) + { + dropped.Add(tile); + } + else + { + if (_entries.TryGetValue(key, out LinkedListNode? existing)) + { + if (ReferenceEquals(existing.Value.Tile, tile)) + { + _recency.Remove(existing); + _recency.AddFirst(existing); + return; + } + + Remove(existing); + dropped.Add(existing.Value.Tile); + } + + _entries.Add(key, _recency.AddFirst(new Entry(key, tile))); + _size += tile.SizeBytes; + while (_size > _budget && _recency.Last is { } last) + { + Remove(last); + dropped.Add(last.Value.Tile); + } + } + } + + foreach (TileImage image in dropped) + { + image.Dispose(); + } + } + + /// Removes and disposes every tile. + public void Clear() + { + List dropped; + lock (_lock) + { + dropped = new List(_entries.Count); + foreach (Entry entry in _recency) + { + dropped.Add(entry.Tile); + } + + _entries.Clear(); + _recency.Clear(); + _size = 0; + } + + foreach (TileImage image in dropped) + { + image.Dispose(); + } + } + + /// Clears the cache; tiles added later are disposed instead of kept. + public void Dispose() + { + lock (_lock) + { + _disposed = true; + } + + Clear(); + } + + private void Remove(LinkedListNode node) + { + _recency.Remove(node); + _entries.Remove(node.Value.Key); + _size -= node.Value.Tile.SizeBytes; + } + + private readonly record struct Entry(TileKey Key, TileImage Tile); +} diff --git a/samples/OpenSlideSharp.Viewer/Core/TileGrid.cs b/samples/OpenSlideSharp.Viewer/Core/TileGrid.cs new file mode 100644 index 0000000..f558cdc --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileGrid.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; + +namespace OpenSlideSharp.Viewer.Core; + +/// +/// Splits each level of the slide into x tiles, in that level's +/// pixels; the tiles at the right and bottom edges are smaller. +/// +internal sealed class TileGrid +{ + public const int TileSize = 256; + + private readonly SlideSize[] _dimensions; + private readonly double[] _downsamples; + + public TileGrid(IReadOnlyList levelDimensions, IReadOnlyList levelDownsamples) + { + ArgumentNullException.ThrowIfNull(levelDimensions); + ArgumentNullException.ThrowIfNull(levelDownsamples); + if (levelDimensions.Count != levelDownsamples.Count) + { + throw new ArgumentException( + $"{levelDimensions.Count} level dimensions but {levelDownsamples.Count} downsamples.", nameof(levelDownsamples)); + } + + _dimensions = new SlideSize[levelDimensions.Count]; + _downsamples = new double[levelDownsamples.Count]; + for (int level = 0; level < _dimensions.Length; level++) + { + _dimensions[level] = levelDimensions[level]; + _downsamples[level] = levelDownsamples[level]; + } + } + + /// + /// Returns the tiles of that overlap the level-0 rectangle, row by row. The right and + /// bottom edges are exclusive. A level that does not exist, or a rectangle that misses the slide, has none. + /// + public IEnumerable VisibleTiles(int level, double left0, double top0, double right0, double bottom0) + { + if (level < 0 || level >= _dimensions.Length) + { + yield break; + } + + double downsample = _downsamples[level]; + SlideSize size = _dimensions[level]; + double left = Math.Max(left0 / downsample, 0); + double top = Math.Max(top0 / downsample, 0); + double right = Math.Min(right0 / downsample, size.Width); + double bottom = Math.Min(bottom0 / downsample, size.Height); + // Also false for NaN. + if (!(right > left && bottom > top)) + { + yield break; + } + + long firstColumn = (long)Math.Floor(left / TileSize); + long lastColumn = (long)Math.Ceiling(right / TileSize) - 1; + long firstRow = (long)Math.Floor(top / TileSize); + long lastRow = (long)Math.Ceiling(bottom / TileSize) - 1; + for (long row = firstRow; row <= lastRow; row++) + { + for (long column = firstColumn; column <= lastColumn; column++) + { + yield return new TileKey(level, column, row); + } + } + } + + /// + /// Returns the arguments of for the + /// tile: its top-left corner in level-0 coordinates and its size in pixels of its level. + /// + public (long X0, long Y0, int Width, int Height) Region(TileKey key) + { + (SlideSize size, double downsample) = Level(key); + long x = key.Column * TileSize; + long y = key.Row * TileSize; + return ( + (long)Math.Floor(x * downsample), + (long)Math.Floor(y * downsample), + (int)Math.Min(TileSize, size.Width - x), + (int)Math.Min(TileSize, size.Height - y)); + } + + /// + /// Returns the level-0 rectangle the tile covers, where it is drawn. Neighbouring tiles share their edges + /// exactly, so there are no seams between them. + /// + public (double Left0, double Top0, double Right0, double Bottom0) Bounds(TileKey key) + { + (long _, long _, int width, int height) = Region(key); + double downsample = _downsamples[key.Level]; + double x = key.Column * TileSize; + double y = key.Row * TileSize; + return (x * downsample, y * downsample, (x + width) * downsample, (y + height) * downsample); + } + + private (SlideSize Size, double Downsample) Level(TileKey key) + { + if (key.Level < 0 || key.Level >= _dimensions.Length) + { + throw new ArgumentOutOfRangeException(nameof(key), key, "The level does not exist."); + } + + SlideSize size = _dimensions[key.Level]; + if (key.Column < 0 || key.Row < 0 || key.Column * TileSize >= size.Width || key.Row * TileSize >= size.Height) + { + throw new ArgumentOutOfRangeException(nameof(key), key, "The tile is outside its level."); + } + + return (size, _downsamples[key.Level]); + } +} diff --git a/samples/OpenSlideSharp.Viewer/Core/TileImage.cs b/samples/OpenSlideSharp.Viewer/Core/TileImage.cs new file mode 100644 index 0000000..6604657 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileImage.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading; + +namespace OpenSlideSharp.Viewer.Core; + +/// +/// The pixels of one tile as OpenSlide returns them: premultiplied BGRA, rows top to bottom with no padding. It is +/// platform independent; the UI layer turns it into a bitmap the first time it draws it. +/// +/// +/// marks the tile as dropped from the , so whatever the UI built from it +/// can be released. stays readable afterwards: the cache may evict a tile on a loader thread +/// while the UI thread is still drawing it. +/// +internal sealed class TileImage : IDisposable +{ + private int _disposed; + + public TileImage(int width, int height, byte[] pixels) + { + ArgumentOutOfRangeException.ThrowIfNegative(width); + ArgumentOutOfRangeException.ThrowIfNegative(height); + ArgumentNullException.ThrowIfNull(pixels); + if (pixels.Length != (long)width * height * 4) + { + throw new ArgumentException($"A {width} x {height} tile needs {(long)width * height * 4} bytes, not {pixels.Length}.", nameof(pixels)); + } + + Width = width; + Height = height; + Pixels = pixels; + } + + public int Width { get; } + + public int Height { get; } + + public byte[] Pixels { get; } + + /// Gets the size the tile counts for in the cache budget: width * height * 4. + public long SizeBytes => Pixels.LongLength; + + public bool IsDisposed => Volatile.Read(ref _disposed) != 0; + + public void Dispose() => Interlocked.Exchange(ref _disposed, 1); +} diff --git a/samples/OpenSlideSharp.Viewer/Core/TileKey.cs b/samples/OpenSlideSharp.Viewer/Core/TileKey.cs new file mode 100644 index 0000000..636cb16 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileKey.cs @@ -0,0 +1,4 @@ +namespace OpenSlideSharp.Viewer.Core; + +/// A tile of the : its level, and its column and row in that level's 256-pixel grid. +internal readonly record struct TileKey(int Level, long Column, long Row); diff --git a/samples/OpenSlideSharp.Viewer/Core/TileLoader.cs b/samples/OpenSlideSharp.Viewer/Core/TileLoader.cs new file mode 100644 index 0000000..efe645f --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileLoader.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace OpenSlideSharp.Viewer.Core; + +/// +/// Reads tiles on background threads into a , newest request first. +/// +/// +/// +/// Each starts a new generation: it drops the tiles of earlier requests that have not started +/// and queues its own in the order given (the caller puts the centre of the view first). Tiles already cached, in +/// flight or queued are skipped. Reads that have started always finish and go into the cache. +/// +/// +/// A worker reads a tile, adds it to the cache, then calls loaded on its own thread; the UI layer switches +/// to the UI thread itself. The first exception from a read raises once, on a worker thread, +/// and the loader then ignores further requests. +/// +/// +/// stops taking requests, drops the queued ones and waits for the reads in flight, for at most +/// . Once it returns no callback starts, and tiles read after it are discarded. +/// +/// +internal sealed class TileLoader : IDisposable +{ + private readonly Func _read; + private readonly TileCache _cache; + private readonly Action _loaded; + private readonly Thread[] _workers; + private readonly object _lock = new(); + private readonly Queue _queue = new(); + private readonly HashSet _queued = new(); + private readonly HashSet _inFlight = new(); + private long _generation; + private bool _failed; + private bool _disposed; + + public TileLoader(Func read, TileCache cache, int workers, Action loaded) + { + ArgumentNullException.ThrowIfNull(read); + ArgumentNullException.ThrowIfNull(cache); + ArgumentNullException.ThrowIfNull(loaded); + ArgumentOutOfRangeException.ThrowIfLessThan(workers, 1); + _read = read; + _cache = cache; + _loaded = loaded; + _workers = new Thread[workers]; + for (int i = 0; i < workers; i++) + { + _workers[i] = new Thread(Work) { IsBackground = true, Name = $"Tile loader {i + 1}" }; + } + + foreach (Thread worker in _workers) + { + worker.Start(); + } + } + + /// Raised once, on a worker thread, when a read first fails. + public event Action? Failed; + + /// Gets the number of requests made so far. + public long Generation + { + get + { + lock (_lock) + { + return _generation; + } + } + } + + /// Gets the number of tiles queued or being read. + public int Pending + { + get + { + lock (_lock) + { + return _queue.Count + _inFlight.Count; + } + } + } + + /// Gets or sets how long waits for the reads in flight. + internal TimeSpan DisposeTimeout { get; set; } = TimeSpan.FromSeconds(5); + + /// Replaces the queued tiles with , to be read in that order. + public void Request(IEnumerable keys) + { + ArgumentNullException.ThrowIfNull(keys); + TileKey[] requested = keys.ToArray(); // the caller's enumeration runs outside the lock + + lock (_lock) + { + if (_disposed || _failed) + { + return; + } + + _generation++; + _queue.Clear(); + _queued.Clear(); + foreach (TileKey key in requested) + { + if (!_inFlight.Contains(key) && !_queued.Contains(key) && !_cache.Contains(key)) + { + _queue.Enqueue(key); + _queued.Add(key); + } + } + + Monitor.PulseAll(_lock); + } + } + + public void Dispose() + { + lock (_lock) + { + if (_disposed) + { + return; + } + + _disposed = true; + _queue.Clear(); + _queued.Clear(); + Monitor.PulseAll(_lock); + + // Called from a callback, the worker's own tile is in flight until Dispose returns. + int own = Array.IndexOf(_workers, Thread.CurrentThread) >= 0 ? 1 : 0; + long deadline = Environment.TickCount64 + (long)DisposeTimeout.TotalMilliseconds; + while (_inFlight.Count > own) + { + long remaining = deadline - Environment.TickCount64; + if (remaining <= 0) + { + break; + } + + Monitor.Wait(_lock, TimeSpan.FromMilliseconds(remaining)); + } + } + } + + private bool IsDisposed + { + get + { + lock (_lock) + { + return _disposed; + } + } + } + + private void Work() + { + while (true) + { + TileKey key; + lock (_lock) + { + while (_queue.Count == 0 && !_disposed) + { + Monitor.Wait(_lock); + } + + if (_disposed) + { + return; + } + + key = _queue.Dequeue(); + _queued.Remove(key); + _inFlight.Add(key); + } + + try + { + Load(key); + } + finally + { + lock (_lock) + { + _inFlight.Remove(key); + Monitor.PulseAll(_lock); // Dispose may be waiting + } + } + } + } + + private void Load(TileKey key) + { + try + { + TileImage tile = _read(key); + if (IsDisposed) + { + tile.Dispose(); + return; + } + + _cache.Add(key, tile); + if (!IsDisposed) + { + _loaded(key); + } + } + catch (Exception e) + { + Fail(e); + } + } + + private void Fail(Exception e) + { + Action? failed; + lock (_lock) + { + if (_disposed || _failed) + { + return; + } + + _failed = true; + _queue.Clear(); + _queued.Clear(); + failed = Failed; + } + + failed?.Invoke(e); + } +} diff --git a/samples/OpenSlideSharp.Viewer/Core/Viewport.cs b/samples/OpenSlideSharp.Viewer/Core/Viewport.cs new file mode 100644 index 0000000..3343bd8 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/Viewport.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; + +namespace OpenSlideSharp.Viewer.Core; + +/// +/// Which part of the slide the view shows, and how large: the level-0 point at the centre of the view and the +/// downsample (level-0 pixels per logical screen pixel). Used on the UI thread only. +/// +/// +/// +/// The downsample stays within : from 1/4 (each slide pixel 4 screen pixels wide) to twice the +/// larger of the coarsest level's downsample and the downsample that fits the slide in the view. +/// +/// +/// A new viewport fits the slide to the view and centres it, and keeps doing so as the view is resized until it is +/// zoomed, panned or centred on something else; returns to that state. Input that is not a finite +/// number is ignored, so the state never becomes NaN. +/// +/// +internal sealed class Viewport +{ + private const double MinDownsample = 0.25; + + private readonly double _slideWidth; + private readonly double _slideHeight; + private readonly double _coarsestDownsample; + private bool _fitted = true; + + public Viewport(SlideSize slideSize, IReadOnlyList levelDownsamples) + { + ArgumentNullException.ThrowIfNull(levelDownsamples); + _slideWidth = Math.Max(0, slideSize.Width); + _slideHeight = Math.Max(0, slideSize.Height); + double coarsest = levelDownsamples.Count > 0 ? levelDownsamples[^1] : 1; + _coarsestDownsample = double.IsFinite(coarsest) && coarsest > 0 ? coarsest : 1; + Downsample = Clamp(1); + CenterX = _slideWidth / 2; + CenterY = _slideHeight / 2; + } + + /// Raised after any of the properties changes. + public event Action? Changed; + + /// Gets the number of level-0 pixels per logical screen pixel. + public double Downsample { get; private set; } + + /// Gets the level-0 X coordinate at the centre of the view. + public double CenterX { get; private set; } + + /// Gets the level-0 Y coordinate at the centre of the view. + public double CenterY { get; private set; } + + /// Gets the width of the view in logical pixels. + public double ViewWidth { get; private set; } + + /// Gets the height of the view in logical pixels. + public double ViewHeight { get; private set; } + + public (double MinDownsample, double MaxDownsample) Limits => + (MinDownsample, Math.Max(MinDownsample, Math.Max(_coarsestDownsample, FitDownsample) * 2)); + + // The downsample that shows the whole slide in the view; 0 while the view or the slide is empty. + private double FitDownsample => + ViewWidth > 0 && ViewHeight > 0 ? Math.Max(_slideWidth / ViewWidth, _slideHeight / ViewHeight) : 0; + + /// Sets the size of the view in logical pixels; anything but a positive number counts as 0. + public void Resize(double width, double height) + { + width = double.IsFinite(width) && width > 0 ? width : 0; + height = double.IsFinite(height) && height > 0 ? height : 0; + bool resized = width != ViewWidth || height != ViewHeight; + ViewWidth = width; + ViewHeight = height; + if (_fitted && width > 0 && height > 0) + { + Set(Clamp(FitDownsample), _slideWidth / 2, _slideHeight / 2, fitted: true, force: resized); + } + else + { + // A larger view lowers the zoom-out limit. + Set(Clamp(Downsample), CenterX, CenterY, _fitted, force: resized); + } + } + + /// Zooms in by (out if it is below 1), keeping the slide point under the given screen point in place. + public void ZoomAt(double screenX, double screenY, double factor) + { + if (!double.IsFinite(screenX) || !double.IsFinite(screenY) || !double.IsFinite(factor) || factor <= 0) + { + return; + } + + (double x0, double y0) = ScreenToSlide(screenX, screenY); + double downsample = Clamp(Downsample / factor); + Set( + downsample, + x0 - (screenX - (ViewWidth / 2)) * downsample, + y0 - (screenY - (ViewHeight / 2)) * downsample, + fitted: false); + } + + /// Moves the slide by the given screen distance: a positive moves it to the right. + public void PanBy(double dxScreen, double dyScreen) + { + if (!double.IsFinite(dxScreen) || !double.IsFinite(dyScreen)) + { + return; + } + + Set(Downsample, CenterX - (dxScreen * Downsample), CenterY - (dyScreen * Downsample), fitted: false); + } + + /// Shows the whole slide, centred. Does nothing while the view has no size. + public void Fit() + { + if (ViewWidth > 0 && ViewHeight > 0) + { + Set(Clamp(FitDownsample), _slideWidth / 2, _slideHeight / 2, fitted: true); + } + } + + /// Zooms to one slide pixel per logical screen pixel around the centre of the view. + public void OneToOne() => Set(Clamp(1), CenterX, CenterY, fitted: false); + + /// Centres the slide without changing the zoom. + public void Center() => Set(Downsample, _slideWidth / 2, _slideHeight / 2, _fitted); + + public void CenterOn(double x0, double y0) + { + if (double.IsFinite(x0) && double.IsFinite(y0)) + { + Set(Downsample, x0, y0, fitted: false); + } + } + + /// Centres the level-0 rectangle and zooms so that it just fits, within . + public void ZoomTo(double x0, double y0, double width0, double height0) + { + if (!double.IsFinite(x0) || !double.IsFinite(y0) || !double.IsFinite(width0) || !double.IsFinite(height0)) + { + return; + } + + width0 = Math.Max(0, width0); + height0 = Math.Max(0, height0); + double downsample = ViewWidth > 0 && ViewHeight > 0 + ? Clamp(Math.Max(width0 / ViewWidth, height0 / ViewHeight)) + : Downsample; + Set(downsample, x0 + (width0 / 2), y0 + (height0 / 2), fitted: false); + } + + public (double X, double Y) ScreenToSlide(double sx, double sy) => + (CenterX + ((sx - (ViewWidth / 2)) * Downsample), CenterY + ((sy - (ViewHeight / 2)) * Downsample)); + + public (double X, double Y) SlideToScreen(double x0, double y0) => + (((x0 - CenterX) / Downsample) + (ViewWidth / 2), ((y0 - CenterY) / Downsample) + (ViewHeight / 2)); + + private double Clamp(double downsample) + { + (double min, double max) = Limits; + return Math.Clamp(downsample, min, max); + } + + private void Set(double downsample, double centerX, double centerY, bool fitted, bool force = false) + { + _fitted = fitted; + if (!force && downsample == Downsample && centerX == CenterX && centerY == CenterY) + { + return; + } + + Downsample = downsample; + CenterX = centerX; + CenterY = centerY; + Changed?.Invoke(); + } +} diff --git a/samples/OpenSlideSharp.Viewer/OpenSlideSharp.Viewer.csproj b/samples/OpenSlideSharp.Viewer/OpenSlideSharp.Viewer.csproj new file mode 100644 index 0000000..353f2c9 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/OpenSlideSharp.Viewer.csproj @@ -0,0 +1,37 @@ + + + + net10.0 + WinExe + false + OpenSlideSharp.Viewer + app.manifest + true + + + + + + + + + + + + + + + + + $(Version) + + + + + + + diff --git a/samples/OpenSlideSharp.Viewer/Program.cs b/samples/OpenSlideSharp.Viewer/Program.cs new file mode 100644 index 0000000..3cdda70 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Program.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using Avalonia; + +namespace OpenSlideSharp.Viewer; + +internal static class Program +{ + // The size of the region --check reads. + private const int CheckRegionSize = 256; + + // Don't use Avalonia, third-party APIs or SynchronizationContext-reliant code before AppMain is called. + [STAThread] + public static int Main(string[] args) + { + if (args.Length > 0 && args[0] == "--check") + { + return RunCheck(args, Console.Out); + } + + return RunApp(args); + } + + // Avalonia configuration; also used by the visual designer. + public static AppBuilder BuildAvaloniaApp() + => AppBuilder.Configure() + .UsePlatformDetect() + .WithInterFont() + .LogToTrace(); + + /// + /// --check <slide>: checks without a window (or a display) that the viewer can load OpenSlide and + /// read the slide. Prints openslide=<version> and slide=<width>x<height> after + /// reading the top-left 256 x 256 region of the lowest-resolution level. + /// + /// + /// 0 on success, 1 if the slide cannot be opened or read, 2 for invalid arguments, 3 if the native OpenSlide + /// library cannot be loaded. + /// + internal static int RunCheck(string[] args, TextWriter output) + { + if (args.Length != 2 || args[0] != "--check") + { + output.WriteLine("Usage: OpenSlideSharp.Viewer [slide] | --check "); + return 2; + } + + string path = args[1]; + try + { + output.WriteLine("openslide=" + OpenSlideLibrary.Version); + using OpenSlide slide = OpenSlide.Open(path); + var pixels = new byte[CheckRegionSize * CheckRegionSize * 4]; + slide.ReadRegion(0, 0, slide.LevelCount - 1, CheckRegionSize, CheckRegionSize, pixels); + output.WriteLine(FormattableString.Invariant($"slide={slide.Dimensions.Width}x{slide.Dimensions.Height}")); + return 0; + } + catch (DllNotFoundException e) + { + output.WriteLine(e.Message); + return 3; + } + catch (Exception e) when (e is OpenSlideException or IOException or UnauthorizedAccessException or ArgumentException) + { + output.WriteLine($"Cannot open {path}: {e.Message}"); + return 1; + } + } + + // Kept out of Main so that --check does not even load Avalonia. + [MethodImpl(MethodImplOptions.NoInlining)] + private static int RunApp(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); +} diff --git a/samples/OpenSlideSharp.Viewer/app.manifest b/samples/OpenSlideSharp.Viewer/app.manifest new file mode 100644 index 0000000..5a3e54f --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/app.manifest @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/test/OpenSlideSharp.Viewer.Tests/CheckModeTests.cs b/test/OpenSlideSharp.Viewer.Tests/CheckModeTests.cs new file mode 100644 index 0000000..44ec713 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/CheckModeTests.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class CheckModeTests +{ + [Theory] + [InlineData("small.svs", "slide=16x16")] + [InlineData("boxes.tiff", "slide=300x250")] + public void Check_OpensSlide_PrintsVersionAndSize(string fixture, string size) + { + var output = new StringWriter(); + + int code = Program.RunCheck(["--check", TestFiles.Get(fixture)], output); + + Assert.True(code == 0, output.ToString()); + Assert.Contains("openslide=4.", output.ToString()); + Assert.Contains(size, output.ToString()); + } + + [Theory] + [InlineData("unopenable.tiff")] + [InlineData("missing.svs")] + public void Check_Unopenable_Returns1(string fixture) + { + var output = new StringWriter(); + + int code = Program.RunCheck(["--check", TestFiles.Get(fixture)], output); + + Assert.Equal(1, code); + Assert.Contains(fixture, output.ToString()); + Assert.DoesNotContain( + output.ToString().Split(Environment.NewLine), + line => line.StartsWith("slide=", StringComparison.Ordinal)); + } + + [Theory] + [InlineData] + [InlineData("--check")] + [InlineData("--check", "a.svs", "b.svs")] + public void Check_BadArguments_Returns2(params string[] args) + { + var output = new StringWriter(); + + int code = Program.RunCheck(args, output); + + Assert.Equal(2, code); + Assert.Contains("--check ", output.ToString()); + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj b/test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj new file mode 100644 index 0000000..3f688d8 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + Exe + false + + + + + + + + + + + + + + + + + + + + diff --git a/test/OpenSlideSharp.Viewer.Tests/SelectionListTests.cs b/test/OpenSlideSharp.Viewer.Tests/SelectionListTests.cs new file mode 100644 index 0000000..db60418 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/SelectionListTests.cs @@ -0,0 +1,37 @@ +using System; +using OpenSlideSharp.Viewer.Core; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class SelectionListTests +{ + [Fact] + public void SelectionList_AddRemoveClear_RaiseChanged() + { + var list = new SelectionList(); + int changes = 0; + list.Changed += () => changes++; + var a = new Selection(10, 20, 30, 40); + var b = new Selection(1, 2, 3, 4); + + list.Add(a); + list.Add(b); + Assert.Equal([a, b], list.Items); + Assert.Equal(2, changes); + + list.RemoveAt(0); + Assert.Equal([b], list.Items); + Assert.Equal(3, changes); + + list.Clear(); + Assert.Empty(list.Items); + Assert.Equal(4, changes); + list.Clear(); // already empty: nothing changes + Assert.Equal(4, changes); + + Assert.Throws(() => list.RemoveAt(0)); + Assert.Throws(() => list.Add(null!)); + Assert.Equal(4, changes); + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/TestFiles.cs b/test/OpenSlideSharp.Viewer.Tests/TestFiles.cs new file mode 100644 index 0000000..d455bd1 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/TestFiles.cs @@ -0,0 +1,28 @@ +using System; +using System.IO; +using System.Threading; + +namespace OpenSlideSharp.Viewer.Tests; + +internal static class TestFiles +{ + public static string Get(string name) => Path.Combine(AppContext.BaseDirectory, "Fixtures", name); +} + +internal static class Wait +{ + /// Polls until it holds, failing the test after . + public static void Until(Func condition, string what, double seconds = 5) + { + DateTime deadline = DateTime.UtcNow.AddSeconds(seconds); + while (!condition()) + { + if (DateTime.UtcNow > deadline) + { + throw new TimeoutException("Timed out waiting until " + what + "."); + } + + Thread.Sleep(2); + } + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/TileCacheTests.cs b/test/OpenSlideSharp.Viewer.Tests/TileCacheTests.cs new file mode 100644 index 0000000..03eaa76 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/TileCacheTests.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using OpenSlideSharp.Viewer.Core; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class TileCacheTests +{ + private const long TileBytes = 256 * 256 * 4; // 256 KiB + + private static TileImage Tile(int size = 256) => new(size, size, new byte[size * size * 4]); + + private static TileKey Key(int i) => new(0, i, 0); + + [Fact] + public void Cache_StaysWithinBudget() + { + using var cache = new TileCache(1024 * 1024); + var tiles = new TileImage[10]; + + for (int i = 0; i < tiles.Length; i++) + { + tiles[i] = Tile(); + cache.Add(Key(i), tiles[i]); + Assert.True(cache.SizeBytes <= 1024 * 1024, $"{cache.SizeBytes} bytes after adding tile {i}"); + } + + Assert.Equal(4, cache.Count); + Assert.Equal(4 * TileBytes, cache.SizeBytes); + for (int i = 0; i < 6; i++) + { + Assert.True(tiles[i].IsDisposed, $"tile {i} was evicted but not disposed"); + Assert.False(cache.TryGet(Key(i), out _)); + } + + for (int i = 6; i < 10; i++) + { + Assert.False(tiles[i].IsDisposed); + Assert.True(cache.TryGet(Key(i), out TileImage? tile)); + Assert.Same(tiles[i], tile); + } + + cache.Clear(); + Assert.Equal(0, cache.Count); + Assert.Equal(0, cache.SizeBytes); + Assert.All(tiles, tile => Assert.True(tile.IsDisposed)); + } + + [Fact] + public void Cache_LruOrder() + { + using var cache = new TileCache(3 * TileBytes); + TileImage a = Tile(), b = Tile(), c = Tile(), d = Tile(); + cache.Add(Key(0), a); + cache.Add(Key(1), b); + cache.Add(Key(2), c); + + Assert.True(cache.TryGet(Key(0), out _)); // a is now the most recently used + cache.Add(Key(3), d); + + Assert.True(b.IsDisposed); + Assert.False(a.IsDisposed || c.IsDisposed || d.IsDisposed); + Assert.False(cache.TryGet(Key(1), out _)); + Assert.Equal(3, cache.Count); + + // c is now the least recently used. + TileImage e = Tile(); + cache.Add(Key(4), e); + Assert.True(c.IsDisposed); + Assert.False(a.IsDisposed || d.IsDisposed || e.IsDisposed); + } + + [Fact] + public void Cache_AddSameKey_ReplacesAndDisposesOld() + { + using var cache = new TileCache(3 * TileBytes); + TileImage first = Tile(), second = Tile(); + cache.Add(Key(0), first); + + cache.Add(Key(0), second); + cache.Add(Key(0), second); // the same tile again is a no-op + + Assert.True(first.IsDisposed); + Assert.False(second.IsDisposed); + Assert.Equal(1, cache.Count); + Assert.Equal(TileBytes, cache.SizeBytes); + Assert.True(cache.TryGet(Key(0), out TileImage? tile)); + Assert.Same(second, tile); + } + + [Fact] + public void Cache_TileLargerThanBudget_IsNotKept() + { + using var cache = new TileCache(TileBytes - 1); + TileImage tile = Tile(); + + cache.Add(Key(0), tile); + + Assert.True(tile.IsDisposed); + Assert.Equal(0, cache.Count); + Assert.Equal(0, cache.SizeBytes); + } + + [Fact] + public void Cache_Dispose_DisposesTilesAndIgnoresLateAdds() + { + var cache = new TileCache(3 * TileBytes); + TileImage kept = Tile(), late = Tile(); + cache.Add(Key(0), kept); + + cache.Dispose(); + cache.Add(Key(1), late); // a loader thread may still finish a read + + Assert.True(kept.IsDisposed); + Assert.True(late.IsDisposed); + Assert.Equal(0, cache.Count); + Assert.False(cache.TryGet(Key(1), out _)); + } + + [Fact] + public void Cache_ConcurrentAccess() + { + const int Size = 64; + const long Bytes = Size * Size * 4; + const long Budget = 10 * Bytes; + using var cache = new TileCache(Budget); + var created = new ConcurrentBag(); + var errors = new ConcurrentQueue(); + using var start = new Barrier(8); + + Thread[] threads = Enumerable.Range(0, 8).Select(t => new Thread(() => + { + try + { + var random = new Random(t); + start.SignalAndWait(); + for (int i = 0; i < 5000; i++) + { + var key = new TileKey(0, random.Next(40), 0); // shared by all threads, so keys collide + if (i % 2 == 0) + { + TileImage tile = Tile(Size); + created.Add(tile); + cache.Add(key, tile); + } + else if (cache.TryGet(key, out TileImage? tile)) + { + Assert.NotNull(tile); + } + + if (cache.SizeBytes > Budget) + { + throw new InvalidOperationException($"{cache.SizeBytes} bytes in the cache"); + } + } + } + catch (Exception e) + { + errors.Enqueue(e); + } + })).ToArray(); + + foreach (Thread thread in threads) + { + thread.Start(); + } + + foreach (Thread thread in threads) + { + thread.Join(); + } + + Assert.Empty(errors); + Assert.True(cache.SizeBytes <= Budget); + Assert.Equal(cache.Count * Bytes, cache.SizeBytes); + // Every tile that left the cache was disposed; the ones still in it were not. + Assert.Equal(cache.Count, created.Count(tile => !tile.IsDisposed)); + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/TileGridTests.cs b/test/OpenSlideSharp.Viewer.Tests/TileGridTests.cs new file mode 100644 index 0000000..bbc1d3c --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/TileGridTests.cs @@ -0,0 +1,77 @@ +using System.Linq; +using OpenSlideSharp.Viewer.Core; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class TileGridTests +{ + private static TileGrid BoxesGrid() + { + using var slide = OpenSlide.Open(TestFiles.Get("boxes.tiff")); + return new TileGrid(slide.LevelDimensions, slide.LevelDownsamples); + } + + [Fact] + public void TileGrid_VisibleTiles_CoversViewExactly() + { + TileGrid grid = BoxesGrid(); + + TileKey[] tiles = grid.VisibleTiles(0, 0, 0, 300, 250).ToArray(); + + Assert.Equal([new TileKey(0, 0, 0), new TileKey(0, 1, 0)], tiles); + Assert.Equal((0L, 0L, 256, 250), grid.Region(tiles[0])); + Assert.Equal((256L, 0L, 44, 250), grid.Region(tiles[1])); + Assert.Equal((0.0, 0.0, 256.0, 250.0), grid.Bounds(tiles[0])); + Assert.Equal((256.0, 0.0, 300.0, 250.0), grid.Bounds(tiles[1])); + + // Only the tiles the view touches: the right and bottom edges are exclusive. + Assert.Equal([new TileKey(0, 0, 0)], grid.VisibleTiles(0, 100, 10, 200, 20)); + Assert.Equal([new TileKey(0, 0, 0)], grid.VisibleTiles(0, 0, 0, 256, 250)); + Assert.Equal([new TileKey(0, 1, 0)], grid.VisibleTiles(0, 256, 0, 300, 250)); + Assert.Equal([new TileKey(0, 0, 0), new TileKey(0, 1, 0)], grid.VisibleTiles(0, 255.5, 0, 256.5, 1)); + } + + [Fact] + public void TileGrid_Region_UsesLevelDownsample() + { + TileGrid grid = BoxesGrid(); + + // Level 2 is 75 x 62 with downsample 4.016129032258064. + Assert.Equal([new TileKey(2, 0, 0)], grid.VisibleTiles(2, 0, 0, 300, 250)); + Assert.Equal((0L, 0L, 75, 62), grid.Region(new TileKey(2, 0, 0))); + (double left, double top, double right, double bottom) = grid.Bounds(new TileKey(2, 0, 0)); + Assert.Equal((0.0, 0.0), (left, top)); + Assert.Equal(75 * 4.016129032258064, right, 1e-9); + Assert.Equal(62 * 4.016129032258064, bottom, 1e-9); + + // Away from the origin the level-0 corner is the level offset times the downsample. + var synthetic = new TileGrid([new SlideSize(1000, 600), new SlideSize(400, 240)], [1.0, 2.5]); + Assert.Equal( + [new TileKey(1, 0, 0), new TileKey(1, 1, 0)], + synthetic.VisibleTiles(1, 0, 0, 1000, 600)); + Assert.Equal((640L, 0L, 144, 240), synthetic.Region(new TileKey(1, 1, 0))); + Assert.Equal((640.0, 0.0, 1000.0, 600.0), synthetic.Bounds(new TileKey(1, 1, 0))); + Assert.Equal([new TileKey(1, 1, 0)], synthetic.VisibleTiles(1, 700, 100, 900, 200)); + } + + [Fact] + public void TileGrid_OutsideSlide_NoTiles() + { + TileGrid grid = BoxesGrid(); + + Assert.Empty(grid.VisibleTiles(0, 300, 0, 400, 250)); + Assert.Empty(grid.VisibleTiles(0, 0, 250, 300, 500)); + Assert.Empty(grid.VisibleTiles(0, -100, -100, 0, 0)); + Assert.Empty(grid.VisibleTiles(3, 1000, 1000, 2000, 2000)); + Assert.Empty(grid.VisibleTiles(0, 100, 100, 100, 200)); // no width + Assert.Empty(grid.VisibleTiles(0, 200, 100, 100, 200)); // inverted + Assert.Empty(grid.VisibleTiles(0, double.NaN, 0, 10, 10)); + Assert.Empty(grid.VisibleTiles(-1, 0, 0, 300, 250)); + Assert.Empty(grid.VisibleTiles(4, 0, 0, 300, 250)); + + // A view partly outside the slide is clipped to it. + Assert.Equal([new TileKey(0, 0, 0)], grid.VisibleTiles(0, -100, -100, 50, 50)); + Assert.Equal([new TileKey(0, 1, 0)], grid.VisibleTiles(0, 290, 200, 5000, 5000)); + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/TileLoaderTests.cs b/test/OpenSlideSharp.Viewer.Tests/TileLoaderTests.cs new file mode 100644 index 0000000..1cd3c57 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/TileLoaderTests.cs @@ -0,0 +1,211 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using OpenSlideSharp.Viewer.Core; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class TileLoaderTests +{ + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(5); + + private static CancellationToken Token => TestContext.Current.CancellationToken; + + [Fact] + public void Loader_LoadsAndNotifies() + { + var reader = new FakeReader(); + using var cache = new TileCache(1 << 20); + var loaded = new ConcurrentQueue<(TileKey Key, bool Cached, int Thread)>(); + using var loader = new TileLoader(reader.Read, cache, 1, key => + loaded.Enqueue((key, cache.TryGet(key, out _), Environment.CurrentManagedThreadId))); + TileKey[] keys = [new(0, 0, 0), new(0, 1, 0), new(1, 0, 0)]; + + loader.Request(keys); + Wait.Until(() => loaded.Count == 3 && loader.Pending == 0, "the tiles are loaded"); + + Assert.Equal(1, loader.Generation); + Assert.Equal(keys, reader.Reads); // in the order given + Assert.Equal(keys, loaded.Select(l => l.Key)); + Assert.All(loaded, l => Assert.True(l.Cached, "loaded fired before the tile was cached")); + Assert.All(loaded, l => Assert.NotEqual(Environment.CurrentManagedThreadId, l.Thread)); + foreach (TileKey key in keys) + { + Assert.True(cache.TryGet(key, out TileImage? tile)); + Assert.Contains(tile, reader.Returned); + } + } + + [Fact] + public void Loader_NewGeneration_DropsQueuedRequests() + { + var reader = new FakeReader(blocked: true); + using var cache = new TileCache(1 << 20); + var loaded = new ConcurrentQueue(); + var loader = new TileLoader(reader.Read, cache, 1, loaded.Enqueue); + var first = new TileKey(0, 0, 0); + + loader.Request([first]); + Assert.True(reader.Entered.Wait(Timeout, Token), "the first read did not start"); + loader.Request(Enumerable.Range(1, 100).Select(i => new TileKey(0, i, 0))); + Assert.Equal(101, loader.Pending); + TileKey[] latest = [new(1, 0, 0), new(1, 1, 0)]; + loader.Request(latest); + Assert.Equal(3, loader.Generation); + Assert.Equal(3, loader.Pending); + + reader.Release(); + Wait.Until(() => loaded.Count == 3, "the reads finish"); + loader.Dispose(); // no read starts after this + + Assert.Equal([first, latest[0], latest[1]], reader.Reads); + // The read that had started still completes into the cache. + Assert.True(cache.TryGet(first, out _)); + } + + [Fact] + public void Loader_DoesNotDuplicateInFlight() + { + var reader = new FakeReader(blocked: true); + using var cache = new TileCache(1 << 20); + var loaded = new ConcurrentQueue(); + using var loader = new TileLoader(reader.Read, cache, 2, loaded.Enqueue); // an idle worker could take a duplicate + var key = new TileKey(0, 0, 0); + + loader.Request([key, key]); + Assert.True(reader.Entered.Wait(Timeout, Token), "the read did not start"); + loader.Request([key]); + loader.Request([key, key]); + Assert.Equal(1, loader.Pending); // only the read in flight + + reader.Release(); + Wait.Until(() => loaded.Count == 1 && loader.Pending == 0, "the read finishes"); + + // Once cached, it is not read again either. + loader.Request([key]); + Assert.Equal(0, loader.Pending); + Assert.Equal([key], reader.Reads); + Assert.Equal([key], loaded); + } + + [Fact] + public async Task Loader_DisposeWhileLoading_CompletesQuietly() + { + var reader = new FakeReader(blocked: true); + using var cache = new TileCache(1 << 20); + int loaded = 0, failed = 0; + var loader = new TileLoader(reader.Read, cache, 2, _ => Interlocked.Increment(ref loaded)); + loader.Failed += _ => Interlocked.Increment(ref failed); + TileKey[] keys = [new(0, 0, 0), new(0, 1, 0), new(0, 2, 0)]; + loader.Request(keys); + Assert.True(reader.Entered.Wait(Timeout, Token) && reader.Entered.Wait(Timeout, Token), "the reads did not start"); + + Task dispose = Task.Run(loader.Dispose, Token); + await Task.WhenAny(dispose, Task.Delay(200, Token)); + Assert.False(dispose.IsCompleted, "Dispose returned while reads were still running"); + reader.Release(); + await dispose.WaitAsync(Timeout, Token); // throws if it does not return, or if it threw + + loader.Request([new TileKey(1, 0, 0)]); // ignored + loader.Dispose(); + Assert.Equal(0, Volatile.Read(ref loaded)); + Assert.Equal(0, Volatile.Read(ref failed)); + Assert.Equal(2, reader.Reads.Count); // the queued third tile never started + Assert.Equal(0, loader.Pending); + // What the reads returned after Dispose is dropped, not cached. + Assert.Equal(0, cache.Count); + Assert.All(reader.Returned, tile => Assert.True(tile.IsDisposed)); + } + + [Fact] + public void Loader_DisposeTimesOut_NoCallbacksAfterward() + { + var reader = new FakeReader(blocked: true); + using var cache = new TileCache(1 << 20); + int loaded = 0, failed = 0; + var loader = new TileLoader(reader.Read, cache, 1, _ => Interlocked.Increment(ref loaded)) + { + DisposeTimeout = TimeSpan.FromMilliseconds(100), + }; + loader.Failed += _ => Interlocked.Increment(ref failed); + loader.Request([new TileKey(0, 0, 0)]); + Assert.True(reader.Entered.Wait(Timeout, Token), "the read did not start"); + + loader.Dispose(); // gives up waiting on the blocked read + + reader.Release(); + Wait.Until(() => loader.Pending == 0, "the abandoned read finishes"); + Assert.Equal(0, Volatile.Read(ref loaded)); + Assert.Equal(0, Volatile.Read(ref failed)); + Assert.Equal(0, cache.Count); + Assert.All(reader.Returned, tile => Assert.True(tile.IsDisposed)); + } + + [Fact] + public void Loader_FailureStopsFurtherRequests() + { + var error = new OpenSlideException("boom"); + var reader = new FakeReader(blocked: true) { Fail = _ => error }; + using var cache = new TileCache(1 << 20); + var loaded = new ConcurrentQueue(); + var failures = new ConcurrentQueue(); + using var loader = new TileLoader(reader.Read, cache, 2, loaded.Enqueue); + loader.Failed += failures.Enqueue; + TileKey a = new(0, 0, 0), b = new(0, 1, 0), queued = new(0, 2, 0); + + loader.Request([a, b, queued]); + Assert.True(reader.Entered.Wait(Timeout, Token) && reader.Entered.Wait(Timeout, Token), "the reads did not start"); + reader.Release(); // both reads fail + Wait.Until(() => !failures.IsEmpty && loader.Pending == 0, "the failures are handled"); + + Assert.Same(error, Assert.Single(failures)); // reported once + long generation = loader.Generation; + loader.Request([new TileKey(1, 0, 0)]); + Assert.Equal(0, loader.Pending); + Assert.Equal(generation, loader.Generation); + Assert.Equal(new[] { a, b }.ToHashSet(), reader.Reads.ToHashSet()); // the queued tile was dropped + Assert.Empty(loaded); + Assert.Single(failures); + } + + /// A read function whose calls can be held at a gate, counted and made to fail. + private sealed class FakeReader + { + private readonly ManualResetEventSlim _gate; + + public FakeReader(bool blocked = false) => _gate = new ManualResetEventSlim(!blocked); + + public ConcurrentQueue Reads { get; } = new(); + + public ConcurrentQueue Returned { get; } = new(); + + /// Released once each time a read starts. + public SemaphoreSlim Entered { get; } = new(0); + + public Func? Fail { get; init; } + + public void Release() => _gate.Set(); + + public TileImage Read(TileKey key) + { + Reads.Enqueue(key); + Entered.Release(); + if (!_gate.Wait(TimeSpan.FromSeconds(30))) + { + throw new TimeoutException("The test never released the read."); + } + + if (Fail?.Invoke(key) is { } error) + { + throw error; + } + + var tile = new TileImage(4, 4, new byte[4 * 4 * 4]); + Returned.Enqueue(tile); + return tile; + } + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/ViewportTests.cs b/test/OpenSlideSharp.Viewer.Tests/ViewportTests.cs new file mode 100644 index 0000000..7ccadce --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/ViewportTests.cs @@ -0,0 +1,247 @@ +using System; +using OpenSlideSharp.Viewer.Core; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class ViewportTests +{ + // boxes.tiff + private static readonly SlideSize Boxes = new(300, 250); + private static readonly double[] BoxesDownsamples = [1.0, 2.0, 4.016129032258064, 8.086312118570184]; + + private static Viewport BoxesViewport(double width = 150, double height = 125) + { + var viewport = new Viewport(Boxes, BoxesDownsamples); + viewport.Resize(width, height); + return viewport; + } + + [Fact] + public void Viewport_Fit_CentersWholeSlide() + { + // The initial state fits the slide to the view and centres it. + Viewport viewport = BoxesViewport(); + Assert.Equal(2, viewport.Downsample); + Assert.Equal((150.0, 125.0), (viewport.CenterX, viewport.CenterY)); + Assert.Equal((150.0, 125.0), (viewport.ViewWidth, viewport.ViewHeight)); + + viewport.ZoomAt(10, 20, 3); + viewport.PanBy(40, -15); + int changes = 0; + viewport.Changed += () => changes++; + viewport.Fit(); + + Assert.Equal(1, changes); + Assert.Equal(2, viewport.Downsample); + Assert.Equal((150.0, 125.0), (viewport.CenterX, viewport.CenterY)); + Assert.Equal((0.0, 0.0), viewport.ScreenToSlide(0, 0)); + Assert.Equal((300.0, 250.0), viewport.ScreenToSlide(150, 125)); + Assert.Equal((75.0, 62.5), viewport.SlideToScreen(150, 125)); + } + + [Fact] + public void Viewport_ZoomAt_KeepsPointUnderCursor() + { + Viewport viewport = BoxesViewport(400, 300); + double fit = viewport.Downsample; + (double X, double Y) before = viewport.ScreenToSlide(30, 40); + + viewport.ZoomAt(30, 40, 1.5); + + Assert.Equal(fit / 1.5, viewport.Downsample, 1e-12); + (double X, double Y) after = viewport.ScreenToSlide(30, 40); + Assert.Equal(before.X, after.X, 1e-9); + Assert.Equal(before.Y, after.Y, 1e-9); + + // Zooming out keeps it too, and SlideToScreen is the inverse. + viewport.ZoomAt(30, 40, 1 / 3.0); + after = viewport.ScreenToSlide(30, 40); + Assert.Equal(before.X, after.X, 1e-9); + Assert.Equal(before.Y, after.Y, 1e-9); + (double X, double Y) screen = viewport.SlideToScreen(before.X, before.Y); + Assert.Equal(30, screen.X, 1e-9); + Assert.Equal(40, screen.Y, 1e-9); + } + + [Fact] + public void Viewport_ZoomClampsToLimits() + { + Viewport viewport = BoxesViewport(); + (double X, double Y) anchor = viewport.ScreenToSlide(30, 40); + + viewport.ZoomAt(30, 40, 1e6); + + Assert.Equal(0.25, viewport.Limits.MinDownsample); + Assert.Equal(viewport.Limits.MinDownsample, viewport.Downsample); + (double X, double Y) after = viewport.ScreenToSlide(30, 40); + Assert.Equal(anchor.X, after.X, 1e-9); + Assert.Equal(anchor.Y, after.Y, 1e-9); + + // The far end: the larger of the last level's downsample and the fit downsample, doubled. + viewport.ZoomAt(30, 40, 1e-6); + Assert.Equal(8.086312118570184 * 2, viewport.Limits.MaxDownsample); + Assert.Equal(viewport.Limits.MaxDownsample, viewport.Downsample); + + viewport.Resize(10, 10); // fit downsample max(30, 25) = 30 + Assert.Equal(60, viewport.Limits.MaxDownsample); + viewport.ZoomAt(5, 5, 1e-6); + Assert.Equal(60, viewport.Downsample); + } + + [Fact] + public void Viewport_OneToOne_SetsDownsample1() + { + Viewport viewport = BoxesViewport(); + viewport.PanBy(20, 10); + (double X, double Y) center = (viewport.CenterX, viewport.CenterY); + + viewport.OneToOne(); + + Assert.Equal(1, viewport.Downsample); + Assert.Equal(center, (viewport.CenterX, viewport.CenterY)); // around the view centre + } + + [Fact] + public void Viewport_TinySlide_FitAndClamp() + { + var viewport = new Viewport(new SlideSize(16, 16), [1.0]); + viewport.Resize(800, 600); + AssertSane(viewport); + + viewport.ZoomAt(100, 100, 0.5); + viewport.Fit(); + + Assert.Equal(0.25, viewport.Downsample); + Assert.Equal(viewport.Limits.MinDownsample, viewport.Downsample); + Assert.Equal(2, viewport.Limits.MaxDownsample); // max(1, 16 / 600) * 2 + Assert.Equal((8.0, 8.0), (viewport.CenterX, viewport.CenterY)); + AssertSane(viewport); + + Exercise(viewport); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(300, 250)] + public void Viewport_NoLevels_Defaults(long width, long height) + { + var viewport = new Viewport(new SlideSize(width, height), [1.0]); + viewport.Resize(0, 0); + AssertSane(viewport); + + // With no view size, Fit leaves the state alone. + viewport.ZoomAt(0, 0, 2); + viewport.PanBy(7, 3); + (double, double, double) state = (viewport.Downsample, viewport.CenterX, viewport.CenterY); + viewport.Fit(); + Assert.Equal(state, (viewport.Downsample, viewport.CenterX, viewport.CenterY)); + + Exercise(viewport); + + // Nonsense input is ignored rather than turned into NaN. + viewport.Resize(-5, double.NaN); + AssertSane(viewport); + viewport.ZoomAt(0, 0, double.NaN); + viewport.ZoomAt(0, 0, 0); + viewport.ZoomAt(0, 0, -2); + viewport.PanBy(double.PositiveInfinity, 0); + viewport.CenterOn(double.NaN, 1); + viewport.ZoomTo(double.NaN, 0, 10, 10); + AssertSane(viewport); + } + + [Fact] + public void Viewport_ZoomTo_FitsRectangle() + { + Viewport viewport = BoxesViewport(); + + viewport.ZoomTo(100, 50, 60, 25); + + // The wider side (60 / 150 = 0.4 over 25 / 125 = 0.2) decides; the rectangle is centred. + Assert.Equal(0.4, viewport.Downsample, 1e-12); + Assert.Equal(130, viewport.CenterX, 1e-9); + Assert.Equal(62.5, viewport.CenterY, 1e-9); + (double X, double Y) topLeft = viewport.SlideToScreen(100, 50); + (double X, double Y) bottomRight = viewport.SlideToScreen(160, 75); + Assert.Equal(0, topLeft.X, 1e-9); + Assert.Equal(31.25, topLeft.Y, 1e-9); + Assert.Equal(150, bottomRight.X, 1e-9); + Assert.Equal(93.75, bottomRight.Y, 1e-9); + + // A rectangle smaller than the zoom limit allows is centred at the limit. + viewport.ZoomTo(10, 10, 2, 2); + Assert.Equal(0.25, viewport.Downsample); + Assert.Equal((11.0, 11.0), (viewport.CenterX, viewport.CenterY)); + } + + [Fact] + public void Viewport_PanAndCenter() + { + Viewport viewport = BoxesViewport(); + + viewport.PanBy(50, -10); + Assert.Equal((150 - 50 * 2.0, 125 + 10 * 2.0), (viewport.CenterX, viewport.CenterY)); + + viewport.CenterOn(30, 40); + Assert.Equal((30.0, 40.0), (viewport.CenterX, viewport.CenterY)); + + viewport.ZoomAt(0, 0, 2); + double downsample = viewport.Downsample; + viewport.Center(); + Assert.Equal((150.0, 125.0), (viewport.CenterX, viewport.CenterY)); + Assert.Equal(downsample, viewport.Downsample); + + // After the user zooms, resizing keeps the zoom and the centre instead of fitting again. + viewport.Resize(300, 200); + Assert.Equal(downsample, viewport.Downsample); + Assert.Equal((150.0, 125.0), (viewport.CenterX, viewport.CenterY)); + } + + private static void Exercise(Viewport viewport) + { + Action[] operations = + [ + viewport.Fit, + viewport.OneToOne, + viewport.Center, + () => viewport.CenterOn(5, 5), + () => viewport.ZoomAt(0, 0, 2), + () => viewport.ZoomAt(3, 4, 0.5), + () => viewport.ZoomAt(0, 0, 1e9), + () => viewport.ZoomAt(0, 0, 1e-9), + () => viewport.PanBy(10, -10), + () => viewport.ZoomTo(0, 0, 10, 10), + () => viewport.ZoomTo(0, 0, 0, 0), + () => viewport.ZoomTo(1, 1, -4, -4), + () => viewport.Resize(0, 0), + () => viewport.Resize(1, 1), + viewport.Fit, + ]; + foreach (Action operation in operations) + { + operation(); + AssertSane(viewport); + } + } + + private static void AssertSane(Viewport viewport) + { + (double min, double max) = viewport.Limits; + AssertFinite(min, max, viewport.Downsample, viewport.CenterX, viewport.CenterY, viewport.ViewWidth, viewport.ViewHeight); + Assert.True(min > 0 && min <= max, $"limits {min}..{max}"); + Assert.InRange(viewport.Downsample, min, max); + Assert.True(viewport.ViewWidth >= 0 && viewport.ViewHeight >= 0); + (double x, double y) = viewport.ScreenToSlide(0, 0); + (double sx, double sy) = viewport.SlideToScreen(0, 0); + AssertFinite(x, y, sx, sy); + } + + private static void AssertFinite(params double[] values) + { + foreach (double value in values) + { + Assert.True(double.IsFinite(value), $"{value} is not finite"); + } + } +} From 78e86a89749fd098175984e30084dcca04f2ac1e Mon Sep 17 00:00:00 2001 From: IOL0ol1 <1353839731@qq.com> Date: Wed, 18 Nov 2026 15:15:32 +0800 Subject: [PATCH 03/21] fix: keep the tile loader running when a callback throws An exception from the loaded callback was treated as a read failure and stopped the loader for good, and one from a Failed handler escaped the worker thread and ended the process. Both are now traced and swallowed, and every Failed handler runs even if an earlier one throws. TileLoader.IsDisposed is now public. The dispose test waited 200 ms before releasing the blocked reads; it now waits until Dispose has dropped the queued tile, and the loaders in the loader tests are disposed with using. --- .../OpenSlideSharp.Viewer/Core/TileLoader.cs | 63 ++++++++++++++----- .../TileLoaderTests.cs | 59 +++++++++++++++-- 2 files changed, 102 insertions(+), 20 deletions(-) diff --git a/samples/OpenSlideSharp.Viewer/Core/TileLoader.cs b/samples/OpenSlideSharp.Viewer/Core/TileLoader.cs index efe645f..ef0775d 100644 --- a/samples/OpenSlideSharp.Viewer/Core/TileLoader.cs +++ b/samples/OpenSlideSharp.Viewer/Core/TileLoader.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; @@ -20,6 +21,11 @@ namespace OpenSlideSharp.Viewer.Core; /// and the loader then ignores further requests. /// /// +/// An exception thrown by loaded or by a handler is a bug in the caller, not a read +/// failure: it is traced and swallowed, so it neither ends the process from a worker thread nor stops the loader, +/// and the other handlers still run. +/// +/// /// stops taking requests, drops the queued ones and waits for the reads in flight, for at most /// . Once it returns no callback starts, and tiles read after it are discarded. /// @@ -86,6 +92,18 @@ public int Pending } } + /// Gets whether has been called. + public bool IsDisposed + { + get + { + lock (_lock) + { + return _disposed; + } + } + } + /// Gets or sets how long waits for the reads in flight. internal TimeSpan DisposeTimeout { get; set; } = TimeSpan.FromSeconds(5); @@ -148,17 +166,6 @@ public void Dispose() } } - private bool IsDisposed - { - get - { - lock (_lock) - { - return _disposed; - } - } - } - private void Work() { while (true) @@ -208,14 +215,29 @@ private void Load(TileKey key) } _cache.Add(key, tile); - if (!IsDisposed) - { - _loaded(key); - } } catch (Exception e) { Fail(e); + return; + } + + if (!IsDisposed) + { + Notify(_loaded, key, "loaded"); + } + } + + // Runs a callback on a worker thread: what it throws must not end the process or pass for a read failure. + private static void Notify(Action callback, T argument, string name) + { + try + { + callback(argument); + } + catch (Exception e) + { + Trace.TraceError($"TileLoader: the {name} callback threw: {e}"); } } @@ -235,6 +257,15 @@ private void Fail(Exception e) failed = Failed; } - failed?.Invoke(e); + if (failed is null) + { + return; + } + + // Each handler on its own, so that one that throws does not keep the others from running. + foreach (Action handler in failed.GetInvocationList()) + { + Notify(handler, e, nameof(Failed)); + } } } diff --git a/test/OpenSlideSharp.Viewer.Tests/TileLoaderTests.cs b/test/OpenSlideSharp.Viewer.Tests/TileLoaderTests.cs index 1cd3c57..8db5b97 100644 --- a/test/OpenSlideSharp.Viewer.Tests/TileLoaderTests.cs +++ b/test/OpenSlideSharp.Viewer.Tests/TileLoaderTests.cs @@ -45,7 +45,7 @@ public void Loader_NewGeneration_DropsQueuedRequests() var reader = new FakeReader(blocked: true); using var cache = new TileCache(1 << 20); var loaded = new ConcurrentQueue(); - var loader = new TileLoader(reader.Read, cache, 1, loaded.Enqueue); + using var loader = new TileLoader(reader.Read, cache, 1, loaded.Enqueue); var first = new TileKey(0, 0, 0); loader.Request([first]); @@ -97,14 +97,16 @@ public async Task Loader_DisposeWhileLoading_CompletesQuietly() var reader = new FakeReader(blocked: true); using var cache = new TileCache(1 << 20); int loaded = 0, failed = 0; - var loader = new TileLoader(reader.Read, cache, 2, _ => Interlocked.Increment(ref loaded)); + using var loader = new TileLoader(reader.Read, cache, 2, _ => Interlocked.Increment(ref loaded)); loader.Failed += _ => Interlocked.Increment(ref failed); TileKey[] keys = [new(0, 0, 0), new(0, 1, 0), new(0, 2, 0)]; loader.Request(keys); Assert.True(reader.Entered.Wait(Timeout, Token) && reader.Entered.Wait(Timeout, Token), "the reads did not start"); Task dispose = Task.Run(loader.Dispose, Token); - await Task.WhenAny(dispose, Task.Delay(200, Token)); + // Dispose drops the queued third tile at once, then waits for the two reads in flight. Releasing the reads + // before that could let a worker start the third tile. + Wait.Until(() => loader.Pending == 2, "Dispose drops the queued tile"); Assert.False(dispose.IsCompleted, "Dispose returned while reads were still running"); reader.Release(); await dispose.WaitAsync(Timeout, Token); // throws if it does not return, or if it threw @@ -126,7 +128,7 @@ public void Loader_DisposeTimesOut_NoCallbacksAfterward() var reader = new FakeReader(blocked: true); using var cache = new TileCache(1 << 20); int loaded = 0, failed = 0; - var loader = new TileLoader(reader.Read, cache, 1, _ => Interlocked.Increment(ref loaded)) + using var loader = new TileLoader(reader.Read, cache, 1, _ => Interlocked.Increment(ref loaded)) { DisposeTimeout = TimeSpan.FromMilliseconds(100), }; @@ -171,6 +173,55 @@ public void Loader_FailureStopsFurtherRequests() Assert.Single(failures); } + [Fact] + public void Loader_ThrowingLoadedHandler_KeepsLoading() + { + var reader = new FakeReader(); + using var cache = new TileCache(1 << 20); + var loaded = new ConcurrentQueue(); + var failures = new ConcurrentQueue(); + using var loader = new TileLoader(reader.Read, cache, 1, key => + { + loaded.Enqueue(key); + throw new InvalidOperationException("a bug in the handler"); + }); + loader.Failed += failures.Enqueue; + + loader.Request([new TileKey(0, 0, 0), new TileKey(0, 1, 0)]); + Wait.Until(() => loaded.Count == 2 && loader.Pending == 0, "both tiles are loaded"); + + // The handler's exception is not a read failure: the worker survives and the loader still takes requests. + loader.Request([new TileKey(0, 2, 0)]); + Wait.Until(() => loaded.Count == 3 && loader.Pending == 0, "the next request is loaded"); + Assert.Empty(failures); + Assert.Equal(3, cache.Count); + Assert.Equal(2, loader.Generation); + } + + [Fact] + public void Loader_ThrowingFailedHandler_DoesNotEscapeTheWorker() + { + var error = new OpenSlideException("boom"); + var reader = new FakeReader { Fail = _ => error }; + using var cache = new TileCache(1 << 20); + var calls = new ConcurrentQueue(); + using var loader = new TileLoader(reader.Read, cache, 1, _ => { }); + loader.Failed += _ => + { + calls.Enqueue("first"); + throw new InvalidOperationException("a bug in the handler"); + }; + loader.Failed += _ => calls.Enqueue("second"); + + loader.Request([new TileKey(0, 0, 0)]); + + // An exception escaping the worker thread would end the test process; the handlers after it still run. + Wait.Until(() => calls.Count == 2 && loader.Pending == 0, "both handlers run"); + Assert.Equal(["first", "second"], calls); + loader.Dispose(); + Assert.True(loader.IsDisposed); + } + /// A read function whose calls can be held at a gate, counted and made to fail. private sealed class FakeReader { From 1904982ea67ba1de8a0e25acfd529af1085f0088 Mon Sep 17 00:00:00 2001 From: IOL0ol1 <1353839731@qq.com> Date: Wed, 18 Nov 2026 15:15:50 +0800 Subject: [PATCH 04/21] feat: let a tile hand its pixel buffer over once, so buffers can be pooled A TileImage now owns its buffer, which may come from a pool and be longer than the tile, until ConsumePixels hands it to the UI layer to copy into a bitmap or Dispose drops the tile. Either way the buffer goes back through the release callback exactly once. The hand-over is atomic, so a tile evicted on a loader thread while the UI thread copies it is still released once, after the copy. A drawn tile then lives on as its bitmap, which takes the place of its pixels in the cache budget. --- .../OpenSlideSharp.Viewer/Core/TileImage.cs | 80 ++++++++++++-- .../TileImageTests.cs | 102 ++++++++++++++++++ 2 files changed, 171 insertions(+), 11 deletions(-) create mode 100644 test/OpenSlideSharp.Viewer.Tests/TileImageTests.cs diff --git a/samples/OpenSlideSharp.Viewer/Core/TileImage.cs b/samples/OpenSlideSharp.Viewer/Core/TileImage.cs index 6604657..054788e 100644 --- a/samples/OpenSlideSharp.Viewer/Core/TileImage.cs +++ b/samples/OpenSlideSharp.Viewer/Core/TileImage.cs @@ -8,39 +8,97 @@ namespace OpenSlideSharp.Viewer.Core; /// platform independent; the UI layer turns it into a bitmap the first time it draws it. /// /// -/// marks the tile as dropped from the , so whatever the UI built from it -/// can be released. stays readable afterwards: the cache may evict a tile on a loader thread -/// while the UI thread is still drawing it. +/// +/// The tile owns its pixel buffer, which may come from a pool, until one of two things happens, whichever is first: +/// +/// +/// hands the buffer to the UI layer, which copies it into a bitmap; or +/// marks the tile as dropped from the . +/// +/// +/// Either way the buffer then goes back through the release callback, exactly once, and the tile no longer +/// has pixels: a drawn tile lives on as its bitmap, which takes the pixels' place in the cache budget. The hand-over +/// is atomic, so the cache may evict a tile on a loader thread while the UI thread is copying it: the UI thread +/// still finishes its copy, and the release comes after it. +/// /// internal sealed class TileImage : IDisposable { + private readonly Action? _release; + private byte[]? _pixels; private int _disposed; - public TileImage(int width, int height, byte[] pixels) + /// The width in pixels. + /// The height in pixels. + /// + /// The pixels in its first width * height * 4 bytes; a pooled array may be longer. The tile owns it from + /// now on. + /// + /// + /// Called once with when the tile is done with it, for example to return it to its + /// pool; null leaves it to the garbage collector. + /// + public TileImage(int width, int height, byte[] pixels, Action? release = null) { ArgumentOutOfRangeException.ThrowIfNegative(width); ArgumentOutOfRangeException.ThrowIfNegative(height); ArgumentNullException.ThrowIfNull(pixels); - if (pixels.Length != (long)width * height * 4) + long size = (long)width * height * 4; + if (pixels.Length < size) { - throw new ArgumentException($"A {width} x {height} tile needs {(long)width * height * 4} bytes, not {pixels.Length}.", nameof(pixels)); + throw new ArgumentException($"A {width} x {height} tile needs {size} bytes, not {pixels.Length}.", nameof(pixels)); } Width = width; Height = height; - Pixels = pixels; + SizeBytes = size; + _pixels = pixels; + _release = release; } public int Width { get; } public int Height { get; } - public byte[] Pixels { get; } - /// Gets the size the tile counts for in the cache budget: width * height * 4. - public long SizeBytes => Pixels.LongLength; + public long SizeBytes { get; } + + /// Gets whether the tile still holds its pixels: neither consumed nor disposed. + public bool HasPixels => Volatile.Read(ref _pixels) is not null; public bool IsDisposed => Volatile.Read(ref _disposed) != 0; - public void Dispose() => Interlocked.Exchange(ref _disposed, 1); + /// + /// Hands the pixel buffer to , then releases it. Only the first call gets the pixels, + /// and only if the tile has not been disposed; must not keep the array. + /// + /// What returned, or null if the pixels were already gone. + public T? ConsumePixels(Func consume) + where T : class + { + ArgumentNullException.ThrowIfNull(consume); + byte[]? pixels = Interlocked.Exchange(ref _pixels, null); + if (pixels is null) + { + return null; + } + + try + { + return consume(pixels); + } + finally + { + _release?.Invoke(pixels); + } + } + + /// Marks the tile as dropped from the cache and releases its pixels unless they were consumed. + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0 && Interlocked.Exchange(ref _pixels, null) is { } pixels) + { + _release?.Invoke(pixels); + } + } } diff --git a/test/OpenSlideSharp.Viewer.Tests/TileImageTests.cs b/test/OpenSlideSharp.Viewer.Tests/TileImageTests.cs new file mode 100644 index 0000000..921a593 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/TileImageTests.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using OpenSlideSharp.Viewer.Core; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class TileImageTests +{ + [Fact] + public void TileImage_ConsumePixels_HandsThemOverOnceThenReleasesThem() + { + var released = new List(); + byte[] pixels = new byte[(2 * 2 * 4) + 16]; // a pooled array can be longer than the tile needs + var tile = new TileImage(2, 2, pixels, released.Add); + Assert.Equal(16, tile.SizeBytes); + Assert.True(tile.HasPixels); + + string? built = tile.ConsumePixels(p => + { + Assert.Same(pixels, p); + Assert.Empty(released); // still the consumer's while it runs + return "bitmap"; + }); + + Assert.Equal("bitmap", built); + Assert.Same(pixels, Assert.Single(released)); + Assert.False(tile.HasPixels); + Assert.Equal(16, tile.SizeBytes); // still what it counts for in the cache + Assert.Null(tile.ConsumePixels(_ => "again")); + tile.Dispose(); + Assert.Single(released); // never released twice + Assert.True(tile.IsDisposed); + } + + [Fact] + public void TileImage_Dispose_ReleasesPixelsNotConsumed() + { + var released = new List(); + byte[] pixels = new byte[4 * 4 * 4]; + var tile = new TileImage(4, 4, pixels, released.Add); + + tile.Dispose(); + tile.Dispose(); + + Assert.Same(pixels, Assert.Single(released)); + Assert.False(tile.HasPixels); + Assert.Null(tile.ConsumePixels(_ => "too late")); + } + + [Fact] + public async Task TileImage_ConsumeRacingDispose_ReleasesEachBufferOnce() + { + // The UI thread consumes a tile while a loader thread evicts it: exactly one of them gets the buffer. + var released = new ConcurrentQueue(); + var consumed = 0; + const int Tiles = 2000; + var tiles = new TileImage[Tiles]; + for (int i = 0; i < Tiles; i++) + { + tiles[i] = new TileImage(1, 1, new byte[4], released.Enqueue); + } + + using var start = new Barrier(2); + Task consume = Task.Run(() => + { + start.SignalAndWait(TestContext.Current.CancellationToken); + foreach (TileImage tile in tiles) + { + if (tile.ConsumePixels(_ => "bitmap") is not null) + { + Interlocked.Increment(ref consumed); + } + } + }, TestContext.Current.CancellationToken); + Task dispose = Task.Run(() => + { + start.SignalAndWait(TestContext.Current.CancellationToken); + foreach (TileImage tile in tiles) + { + tile.Dispose(); + } + }, TestContext.Current.CancellationToken); + await Task.WhenAll(consume, dispose).WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken); + + Assert.Equal(Tiles, released.Count); + Assert.Equal(Tiles, new HashSet(released, ReferenceEqualityComparer.Instance).Count); + Assert.All(tiles, tile => Assert.False(tile.HasPixels)); + Assert.InRange(consumed, 0, Tiles); + } + + [Fact] + public void TileImage_RejectsAShortBuffer() + { + Assert.Throws(() => new TileImage(2, 2, new byte[15])); + Assert.Throws(() => new TileImage(2, 2, null!)); + Assert.Throws(() => new TileImage(-1, 2, new byte[16])); + } +} From 557c4a4099d210f4ebeddad6ef7d0da3a61dd94c Mon Sep 17 00:00:00 2001 From: IOL0ol1 <1353839731@qq.com> Date: Wed, 18 Nov 2026 15:15:50 +0800 Subject: [PATCH 05/21] feat: add the SlideView control with tiled rendering, pan, zoom and selections SlideView draws the tiles of the level that suits the zoom per device pixel, aligned to device pixels, and stands in for tiles not loaded yet with cached tiles of coarser levels. Missing tiles are requested centre first from the TileLoader; a frame never reads the slide, and loaded tiles schedule one redraw at a time. Left drag pans, Shift drag draws a selection, the wheel zooms at the pointer by 2^(1/4) a notch, and the keys follow the plan (arrows/WASD, +/-, Z, 1, Space). TileBitmapCache builds a tile's bitmap on its first draw from the pixels the tile hands over, and disposes the bitmaps of evicted tiles before each frame, so bitmap memory follows the cache budget. Tiles are read into pooled buffers. TileGrid picks levels without a native call, by the rule of openslide_get_best_level_for_downsample. The rendering tests run on the Avalonia.Headless session API with Skia, not Avalonia.Headless.XUnit, which needs xunit.v3 3.x. --- Directory.Packages.props | 3 + .../Controls/SlideView.cs | 642 ++++++++++++++++++ .../Controls/TileBitmapCache.cs | 123 ++++ .../OpenSlideSharp.Viewer/Core/TileGrid.cs | 28 + .../HeadlessSession.cs | 83 +++ .../OpenSlideSharp.Viewer.Tests.csproj | 2 + .../RenderedFrame.cs | 113 +++ .../SlideViewTests.cs | 624 +++++++++++++++++ .../TileBitmapCacheTests.cs | 151 ++++ .../TileGridTests.cs | 41 ++ 10 files changed, 1810 insertions(+) create mode 100644 samples/OpenSlideSharp.Viewer/Controls/SlideView.cs create mode 100644 samples/OpenSlideSharp.Viewer/Controls/TileBitmapCache.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/HeadlessSession.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/RenderedFrame.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/TileBitmapCacheTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 0d34d7c..54bc149 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -14,6 +14,9 @@ + + + diff --git a/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs b/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs new file mode 100644 index 0000000..de3e0a2 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs @@ -0,0 +1,642 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Media.Immutable; +using Avalonia.Threading; +using OpenSlideSharp.Viewer.Core; + +namespace OpenSlideSharp.Viewer.Controls; + +/// +/// Draws a slide from tiles read in the background, and lets the user pan, zoom and draw rectangular selections. +/// +/// +/// +/// Each frame draws the tiles of the level that suits the zoom ( of +/// the downsample per device pixel), aligned to device pixels. A tile not loaded yet is stood in for by the cached +/// tiles of coarser levels, scaled up; the missing tiles are requested centre first. A frame never reads the slide: +/// the reads on its own threads, and each tile it loads schedules one redraw at most. +/// +/// +/// Setting builds a new viewport and loading pipeline (tile cache, bitmap cache and loader), and +/// disposes the old ones, waiting for the old slide's reads in flight. The view does not own the slide: dispose it +/// after replacing it here. Leaving the visual tree (closing the window) disposes the pipeline too. +/// +/// +/// Input: dragging with the left button pans, and with Shift held draws a selection; the wheel zooms around the +/// pointer by 2^(1/4) a notch. Keys, while the view has the focus (it takes it when clicked): the arrows or W, A, +/// S and D pan by 100 pixels, + (or =) and - zoom around the centre, Z fits the slide, 1 zooms to one slide pixel per +/// screen pixel and Space centres the slide. +/// +/// +internal sealed class SlideView : Control +{ + private const double KeyboardPan = 100; + + private static readonly double ZoomStep = Math.Pow(2, 0.25); + private static readonly ImmutableSolidColorBrush SelectionBrush = new(Color.FromRgb(0xFF, 0xD0, 0x00)); + private static readonly ImmutableDashStyle SelectionBeingDrawnDashes = new([4, 4], 0); + + // Tile pixels live from the read until the first draw copies them into a bitmap (or the tile is dropped), so + // only a screenful or so is out at any time; pooling them spares the large-object heap while zooming. + private static readonly ArrayPool PixelPool = + ArrayPool.Create(TileGrid.TileSize * TileGrid.TileSize * 4, maxArraysPerBucket: 32); + + private static readonly Action ReturnPixels = pixels => PixelPool.Return(pixels); + + private readonly List _missing = new(); + private readonly List<(Bitmap Bitmap, Rect Source, Rect Destination)> _coarser = new(); + private OpenSlide? _slide; + private TileGrid? _grid; + private Viewport? _viewport; + private Pipeline? _pipeline; + private IBrush _background = Brushes.White; + private bool _attached; + private Point? _pointer; + private DragMode _drag; + private Point _dragFrom; + private (double X, double Y) _selectionStart; + private Selection? _selectionBeingDrawn; + private (double Scaling, ImmutablePen Solid, ImmutablePen Dashed)? _pens; + private long _tileReads; + private int _redrawPosted; + + public SlideView() + { + Focusable = true; + ClipToBounds = true; + Selections.Changed += InvalidateVisual; + } + + private enum DragMode + { + None, + Pan, + Select, + } + + /// Raised on the UI thread when the viewport or the pointer position changes. + public event Action? ViewChanged; + + /// + /// Raised on the UI thread, once per slide, when reading a tile fails; the view then reads no more tiles of it. + /// + public event Action? LoadFailed; + + /// Gets or sets the slide shown; null shows nothing. The view does not dispose it. + public OpenSlide? Slide + { + get => _slide; + set => SetSlide(value); + } + + /// Gets what part of the slide is shown, and how large; null without a slide. + public Viewport? Viewport => _viewport; + + /// Gets the selections drawn on the slide; they are cleared when the slide changes. + public SelectionList Selections { get; } = new(); + + /// Gets the level-0 point under the pointer; null when the pointer is not over the view or there is no slide. + public (double X, double Y)? PointerSlidePosition => + _pointer is { } pointer && _viewport is { } viewport && new Rect(Bounds.Size).Contains(pointer) + ? viewport.ScreenToSlide(pointer.X, pointer.Y) + : null; + + /// Gets the number of tiles read from the slide since it was set (diagnostics and tests). + public long TileReads => Interlocked.Read(ref _tileReads); + + /// + /// Gets or sets what reads a tile on the loader threads (by default ); a test hook, taken + /// when the loading pipeline is built. + /// + internal Func? TileReader { get; set; } + + /// Gets or sets the tile cache budget, taken when the loading pipeline is built. + internal long CacheBudgetBytes { get; set; } = TileCache.DefaultBudgetBytes; + + /// Gets the level the last frame drew. + internal int TargetLevel { get; private set; } + + internal TileLoader? Loader => _pipeline?.Loader; + + internal TileCache? Cache => _pipeline?.Cache; + + internal TileBitmapCache? Bitmaps => _pipeline?.Bitmaps; + + /// Gets the number of tiles queued or being read. + internal int PendingTiles => _pipeline?.Loader.Pending ?? 0; + + /// + /// Reads a tile into a pooled buffer, which goes back to the pool once a bitmap is built from it or the tile is + /// dropped (see ). + /// + internal static TileImage ReadTile(OpenSlide slide, TileGrid grid, TileKey key) + { + (long x0, long y0, int width, int height) = grid.Region(key); + int length = width * height * 4; + byte[] pixels = PixelPool.Rent(length); + try + { + slide.ReadRegion(x0, y0, key.Level, width, height, pixels.AsSpan(0, length)); + return new TileImage(width, height, pixels, ReturnPixels); + } + catch + { + PixelPool.Return(pixels); + throw; + } + } + + /// Orders tiles by the distance of their centres from the level-0 point (, ). + internal static void SortCenterFirst(List keys, TileGrid grid, double x0, double y0) + { + keys.Sort((a, b) => + { + int order = Distance(a).CompareTo(Distance(b)); + return order != 0 ? order : a.Row != b.Row ? a.Row.CompareTo(b.Row) : a.Column.CompareTo(b.Column); + }); + + double Distance(TileKey key) + { + (double left, double top, double right, double bottom) = grid.Bounds(key); + double dx = ((left + right) / 2) - x0; + double dy = ((top + bottom) / 2) - y0; + return (dx * dx) + (dy * dy); + } + } + + public override void Render(DrawingContext context) + { + context.FillRectangle(_background, new Rect(Bounds.Size)); + if (_viewport is not { ViewWidth: > 0, ViewHeight: > 0 } viewport) + { + return; + } + + double scaling = TopLevel.GetTopLevel(this)?.RenderScaling ?? 1; + if (_pipeline is { } pipeline) + { + DrawTiles(context, pipeline, viewport, scaling); + } + + DrawSelections(context, viewport, scaling); + } + + protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) + { + base.OnAttachedToVisualTree(e); + _attached = true; + OpenPipeline(); + } + + protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) + { + base.OnDetachedFromVisualTree(e); + _attached = false; + ClosePipeline(); + EndDrag(); + _pointer = null; + } + + protected override void OnSizeChanged(SizeChangedEventArgs e) + { + base.OnSizeChanged(e); + _viewport?.Resize(e.NewSize.Width, e.NewSize.Height); + } + + protected override void OnPointerPressed(PointerPressedEventArgs e) + { + base.OnPointerPressed(e); + Focus(NavigationMethod.Pointer); + PointerPoint point = e.GetCurrentPoint(this); + _pointer = point.Position; + if (_viewport is not { } viewport || !point.Properties.IsLeftButtonPressed) + { + return; + } + + _drag = (e.KeyModifiers & KeyModifiers.Shift) != 0 ? DragMode.Select : DragMode.Pan; + _dragFrom = point.Position; + _selectionStart = viewport.ScreenToSlide(point.Position.X, point.Position.Y); + e.Pointer.Capture(this); + e.Handled = true; + } + + protected override void OnPointerMoved(PointerEventArgs e) + { + base.OnPointerMoved(e); + Point position = e.GetPosition(this); + _pointer = position; + if (_viewport is { } viewport) + { + if (_drag == DragMode.Pan) + { + Vector moved = position - _dragFrom; + _dragFrom = position; + viewport.PanBy(moved.X, moved.Y); + } + else if (_drag == DragMode.Select) + { + _selectionBeingDrawn = SelectionTo(viewport, position); + InvalidateVisual(); + } + } + + ViewChanged?.Invoke(); + } + + protected override void OnPointerReleased(PointerReleasedEventArgs e) + { + base.OnPointerReleased(e); + if (e.InitialPressMouseButton != MouseButton.Left || _drag == DragMode.None) + { + return; + } + + if (_drag == DragMode.Select && _viewport is { } viewport) + { + Selection selection = SelectionTo(viewport, e.GetPosition(this)); + if (selection.Width0 > 0 && selection.Height0 > 0) + { + Selections.Add(selection); + } + } + + EndDrag(); + e.Pointer.Capture(null); + e.Handled = true; + } + + protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) + { + base.OnPointerCaptureLost(e); + EndDrag(); // another control took the pointer: a selection being drawn is dropped + } + + protected override void OnPointerExited(PointerEventArgs e) + { + base.OnPointerExited(e); + _pointer = null; + ViewChanged?.Invoke(); + } + + protected override void OnPointerWheelChanged(PointerWheelEventArgs e) + { + base.OnPointerWheelChanged(e); + if (_viewport is not { } viewport) + { + return; + } + + Point position = e.GetPosition(this); + _pointer = position; + viewport.ZoomAt(position.X, position.Y, Math.Pow(2, e.Delta.Y / 4)); + e.Handled = true; + } + + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + // Shortcuts with Ctrl, Alt or the platform key belong to the window. + if (e.Handled || _viewport is not { } viewport + || (e.KeyModifiers & (KeyModifiers.Control | KeyModifiers.Alt | KeyModifiers.Meta)) != 0) + { + return; + } + + double centerX = viewport.ViewWidth / 2; + double centerY = viewport.ViewHeight / 2; + switch (e.Key) + { + case Key.Left or Key.A: + viewport.PanBy(KeyboardPan, 0); + break; + case Key.Right or Key.D: + viewport.PanBy(-KeyboardPan, 0); + break; + case Key.Up or Key.W: + viewport.PanBy(0, KeyboardPan); + break; + case Key.Down or Key.S: + viewport.PanBy(0, -KeyboardPan); + break; + case Key.OemPlus or Key.Add: + viewport.ZoomAt(centerX, centerY, ZoomStep); + break; + case Key.OemMinus or Key.Subtract: + viewport.ZoomAt(centerX, centerY, 1 / ZoomStep); + break; + case Key.Z: + viewport.Fit(); + break; + case Key.D1 or Key.NumPad1: + viewport.OneToOne(); + break; + case Key.Space: + viewport.Center(); + break; + default: + // Keyboard layouts that put these characters on other keys. + switch (e.KeySymbol) + { + case "+" or "=": + viewport.ZoomAt(centerX, centerY, ZoomStep); + break; + case "-": + viewport.ZoomAt(centerX, centerY, 1 / ZoomStep); + break; + case "1": + viewport.OneToOne(); + break; + default: + return; + } + + break; + } + + e.Handled = true; + } + + /// + /// Returns the slide's background colour, openslide.background-color (RRGGBB in hex); white if it is + /// missing or malformed. + /// + internal static Color BackgroundColor(IReadOnlyDictionary properties) => + properties.TryGetValue(OpenSlideProperties.BackgroundColor, out string? value) + && value.Length == 6 + && uint.TryParse(value, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out uint rgb) + ? Color.FromUInt32(0xFF000000 | rgb) + : Colors.White; + + // The level-0 rectangle on the screen, its edges rounded to device pixels: tiles that share an edge in the + // slide share it on the screen, with no seam or overlap. (Layout rounding puts the view itself on whole device + // pixels, so rounding relative to it is enough.) + private static Rect OnScreen(Viewport viewport, double scaling, double left0, double top0, double right0, double bottom0) + { + (double left, double top) = viewport.SlideToScreen(left0, top0); + (double right, double bottom) = viewport.SlideToScreen(right0, bottom0); + return new Rect( + new Point(Math.Round(left * scaling) / scaling, Math.Round(top * scaling) / scaling), + new Point(Math.Round(right * scaling) / scaling, Math.Round(bottom * scaling) / scaling)); + } + + // The selection on the screen with its edges through the centres of device pixels, so that a line one device + // pixel wide covers exactly one pixel. + private static Rect Outline(Viewport viewport, double scaling, Selection selection) + { + (double left, double top) = viewport.SlideToScreen(selection.X0, selection.Y0); + (double right, double bottom) = viewport.SlideToScreen(selection.X0 + selection.Width0, selection.Y0 + selection.Height0); + return new Rect(new Point(Center(left), Center(top)), new Point(Center(right), Center(bottom))); + + double Center(double x) => (Math.Floor(x * scaling) + 0.5) / scaling; + } + + private void SetSlide(OpenSlide? slide) + { + if (ReferenceEquals(slide, _slide)) + { + return; + } + + // Read the new slide first: if that throws, the view keeps the old one. + TileGrid? grid = null; + Viewport? viewport = null; + IBrush background = Brushes.White; + if (slide is not null) + { + grid = new TileGrid(slide.LevelDimensions, slide.LevelDownsamples); + viewport = new Viewport(slide.Dimensions, slide.LevelDownsamples); + background = new ImmutableSolidColorBrush(BackgroundColor(slide.Properties)); + } + + ClosePipeline(); + if (_viewport is not null) + { + _viewport.Changed -= OnViewportChanged; + } + + _slide = slide; + _grid = grid; + _viewport = viewport; + _background = background; + Interlocked.Exchange(ref _tileReads, 0); + EndDrag(); + Selections.Clear(); + if (viewport is not null) + { + viewport.Resize(Bounds.Width, Bounds.Height); + viewport.Changed += OnViewportChanged; + } + + OpenPipeline(); + InvalidateVisual(); + ViewChanged?.Invoke(); + } + + private void OpenPipeline() + { + if (_pipeline is not null || !_attached || _slide is not { } slide || _grid is not { } grid) + { + return; + } + + Func read = TileReader ?? ReadTile; + var cache = new TileCache(CacheBudgetBytes); + var loader = new TileLoader( + key => + { + Interlocked.Increment(ref _tileReads); + return read(slide, grid, key); + }, + cache, + Math.Min(4, Environment.ProcessorCount), + _ => ScheduleRedraw()); + var pipeline = new Pipeline(grid, cache, new TileBitmapCache(), loader); + loader.Failed += error => Dispatcher.UIThread.Post(() => + { + if (ReferenceEquals(pipeline, _pipeline)) + { + LoadFailed?.Invoke(error); + } + }); + _pipeline = pipeline; + InvalidateVisual(); + } + + private void ClosePipeline() + { + Pipeline? pipeline = _pipeline; + _pipeline = null; + pipeline?.Dispose(); + } + + // Called on the loader threads: one post at a time, however many tiles arrive before it runs. + private void ScheduleRedraw() + { + if (Interlocked.Exchange(ref _redrawPosted, 1) == 0) + { + Dispatcher.UIThread.Post(() => + { + Volatile.Write(ref _redrawPosted, 0); + InvalidateVisual(); + }); + } + } + + private void OnViewportChanged() + { + InvalidateVisual(); + ViewChanged?.Invoke(); + } + + private void DrawTiles(DrawingContext context, Pipeline pipeline, Viewport viewport, double scaling) + { + pipeline.Bitmaps.Sweep(); + TileGrid grid = pipeline.Grid; + int level = grid.BestLevelForDownsample(viewport.Downsample / scaling); + TargetLevel = level; + (double left0, double top0) = viewport.ScreenToSlide(0, 0); + (double right0, double bottom0) = viewport.ScreenToSlide(viewport.ViewWidth, viewport.ViewHeight); + + _missing.Clear(); + using (context.PushRenderOptions(new RenderOptions { BitmapInterpolationMode = BitmapInterpolationMode.HighQuality })) + { + foreach (TileKey key in grid.VisibleTiles(level, left0, top0, right0, bottom0)) + { + if (BitmapOf(pipeline, key) is { } bitmap) + { + (double left, double top, double right, double bottom) = grid.Bounds(key); + context.DrawImage(bitmap, new Rect(bitmap.Size), OnScreen(viewport, scaling, left, top, right, bottom)); + } + else + { + _missing.Add(key); + DrawCoarser(context, pipeline, viewport, scaling, key); + } + } + } + + SortCenterFirst(_missing, grid, viewport.CenterX, viewport.CenterY); + pipeline.Loader.Request(_missing); // also drops what earlier frames queued and this one no longer needs + } + + /// + /// Stands in for a tile not loaded yet with the cached tiles of coarser levels: from the next level up to the + /// first one whose cached tiles cover the whole tile, drawing coarser levels first so finer ones end up on top. + /// + private void DrawCoarser(DrawingContext context, Pipeline pipeline, Viewport viewport, double scaling, TileKey key) + { + TileGrid grid = pipeline.Grid; + (double areaLeft, double areaTop, double areaRight, double areaBottom) = grid.Bounds(key); + _coarser.Clear(); + for (int level = key.Level + 1; level < grid.LevelCount; level++) + { + bool covered = true; + double downsample = grid.LevelDownsample(level); + foreach (TileKey coarse in grid.VisibleTiles(level, areaLeft, areaTop, areaRight, areaBottom)) + { + if (BitmapOf(pipeline, coarse) is not { } bitmap) + { + covered = false; + continue; + } + + (double coarseLeft, double coarseTop, double coarseRight, double coarseBottom) = grid.Bounds(coarse); + double left = Math.Max(areaLeft, coarseLeft); + double top = Math.Max(areaTop, coarseTop); + double right = Math.Min(areaRight, coarseRight); + double bottom = Math.Min(areaBottom, coarseBottom); + var source = new Rect( + (left / downsample) - (coarse.Column * TileGrid.TileSize), + (top / downsample) - (coarse.Row * TileGrid.TileSize), + (right - left) / downsample, + (bottom - top) / downsample); + _coarser.Add((bitmap, source, OnScreen(viewport, scaling, left, top, right, bottom))); + } + + if (covered) + { + break; + } + } + + for (int i = _coarser.Count - 1; i >= 0; i--) + { + context.DrawImage(_coarser[i].Bitmap, _coarser[i].Source, _coarser[i].Destination); + } + } + + private Bitmap? BitmapOf(Pipeline pipeline, TileKey key) => + pipeline.Cache.TryGet(key, out TileImage? tile) && tile is not null ? pipeline.Bitmaps.Get(key, tile) : null; + + private void DrawSelections(DrawingContext context, Viewport viewport, double scaling) + { + if (Selections.Items.Count == 0 && _selectionBeingDrawn is null) + { + return; + } + + if (_pens is not { } pens || pens.Scaling != scaling) + { + // One device pixel wide. + pens = (scaling, new ImmutablePen(SelectionBrush, 1 / scaling), new ImmutablePen(SelectionBrush, 1 / scaling, SelectionBeingDrawnDashes)); + _pens = pens; + } + + foreach (Selection selection in Selections.Items) + { + context.DrawRectangle(null, pens.Solid, Outline(viewport, scaling, selection)); + } + + if (_selectionBeingDrawn is { } drawing) + { + context.DrawRectangle(null, pens.Dashed, Outline(viewport, scaling, drawing)); + } + } + + private Selection SelectionTo(Viewport viewport, Point position) + { + (double x, double y) = viewport.ScreenToSlide(position.X, position.Y); + (double startX, double startY) = _selectionStart; + return new Selection(Math.Min(startX, x), Math.Min(startY, y), Math.Abs(x - startX), Math.Abs(y - startY)); + } + + private void EndDrag() + { + _drag = DragMode.None; + if (_selectionBeingDrawn is not null) + { + _selectionBeingDrawn = null; + InvalidateVisual(); + } + } + + /// The loading machinery of one slide: built when a slide is set, disposed together. + private sealed class Pipeline(TileGrid grid, TileCache cache, TileBitmapCache bitmaps, TileLoader loader) : IDisposable + { + public TileGrid Grid { get; } = grid; + + public TileCache Cache { get; } = cache; + + public TileBitmapCache Bitmaps { get; } = bitmaps; + + public TileLoader Loader { get; } = loader; + + public void Dispose() + { + // The loader first: once it returns no read is running (or, past its timeout, none will be cached) and + // no callback will start. Clearing the cache then releases the tiles' pixels, and the bitmaps go last. + Loader.Dispose(); + Cache.Dispose(); + Bitmaps.Dispose(); + } + } +} diff --git a/samples/OpenSlideSharp.Viewer/Controls/TileBitmapCache.cs b/samples/OpenSlideSharp.Viewer/Controls/TileBitmapCache.cs new file mode 100644 index 0000000..c75ab77 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Controls/TileBitmapCache.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Avalonia; +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using OpenSlideSharp.Viewer.Core; + +namespace OpenSlideSharp.Viewer.Controls; + +/// +/// The bitmaps built from the tiles of one , on the UI thread. Keep it exactly as long as that +/// cache, and use it on the UI thread only. +/// +/// +/// +/// builds a tile's bitmap the first time the tile is drawn, consuming its pixels (see +/// ), so from then on the bitmap is the only copy: dropping it while the tile is still cached +/// would leave the tile with nothing to draw. +/// +/// +/// When the cache drops a tile it disposes the , possibly on a loader thread. The bitmap is +/// disposed on the UI thread by the next , which SlideView runs before each frame, or when +/// the same key gets a new tile; a frame already recorded keeps its own reference to the bitmap's pixels, so this is +/// safe. Bitmap memory therefore follows the cache budget, plus the tiles evicted since the last frame. +/// +/// +internal sealed class TileBitmapCache : IDisposable +{ + private static readonly Vector Dpi = new(96, 96); + + private readonly Dictionary _entries = new(); + private readonly List _dropped = new(); + + /// Gets the number of bitmaps held. + public int Count => _entries.Count; + + /// + /// Returns the bitmap of , the tile cached under , building it from + /// the tile's pixels the first time; null if the tile was disposed before it was ever drawn. + /// + public Bitmap? Get(TileKey key, TileImage tile) + { + ArgumentNullException.ThrowIfNull(tile); + if (_entries.TryGetValue(key, out Entry entry)) + { + if (ReferenceEquals(entry.Tile, tile)) + { + return entry.Bitmap; + } + + // The cache replaced the tile under this key, which disposed the old one. + entry.Bitmap.Dispose(); + _entries.Remove(key); + } + + Bitmap? bitmap = tile.ConsumePixels(pixels => Create(tile.Width, tile.Height, pixels)); + if (bitmap is not null) + { + _entries.Add(key, new Entry(tile, bitmap)); + } + + return bitmap; + } + + /// Disposes the bitmaps of the tiles the cache has dropped since the last sweep. + /// The number of bitmaps disposed. + public int Sweep() + { + foreach (KeyValuePair pair in _entries) + { + if (pair.Value.Tile.IsDisposed) + { + _dropped.Add(pair.Key); + } + } + + foreach (TileKey key in _dropped) + { + _entries.Remove(key, out Entry entry); + entry.Bitmap.Dispose(); + } + + int count = _dropped.Count; + _dropped.Clear(); + return count; + } + + /// Disposes every bitmap. Call it together with clearing the cache. + public void Clear() + { + foreach (Entry entry in _entries.Values) + { + entry.Bitmap.Dispose(); + } + + _entries.Clear(); + } + + public void Dispose() => Clear(); + + private static Bitmap Create(int width, int height, byte[] pixels) + { + // OpenSlide's premultiplied BGRA is Avalonia's Bgra8888 with premultiplied alpha; the bitmap copies it. + GCHandle handle = GCHandle.Alloc(pixels, GCHandleType.Pinned); + try + { + return new Bitmap( + Avalonia.Platform.PixelFormat.Bgra8888, + AlphaFormat.Premul, + handle.AddrOfPinnedObject(), + new PixelSize(width, height), + Dpi, + width * 4); + } + finally + { + handle.Free(); + } + } + + private readonly record struct Entry(TileImage Tile, Bitmap Bitmap); +} diff --git a/samples/OpenSlideSharp.Viewer/Core/TileGrid.cs b/samples/OpenSlideSharp.Viewer/Core/TileGrid.cs index f558cdc..89fa485 100644 --- a/samples/OpenSlideSharp.Viewer/Core/TileGrid.cs +++ b/samples/OpenSlideSharp.Viewer/Core/TileGrid.cs @@ -33,6 +33,34 @@ public TileGrid(IReadOnlyList levelDimensions, IReadOnlyList } } + public int LevelCount => _dimensions.Length; + + /// Gets the downsample of : level-0 pixels per pixel of that level. + public double LevelDownsample(int level) => _downsamples[level]; + + /// + /// Returns the level to draw at level-0 pixels per screen pixel, by the rule of + /// openslide_get_best_level_for_downsample: the last level whose downsample is not above it, else level + /// 0. Computed from the level downsamples, so the UI thread can call it without touching the native slide. + /// + public int BestLevelForDownsample(double downsample) + { + if (_downsamples.Length == 0 || downsample < _downsamples[0]) + { + return 0; + } + + for (int level = 1; level < _downsamples.Length; level++) + { + if (downsample < _downsamples[level]) + { + return level - 1; + } + } + + return _downsamples.Length - 1; + } + /// /// Returns the tiles of that overlap the level-0 rectangle, row by row. The right and /// bottom edges are exclusive. A level that does not exist, or a rectangle that misses the slide, has none. diff --git a/test/OpenSlideSharp.Viewer.Tests/HeadlessSession.cs b/test/OpenSlideSharp.Viewer.Tests/HeadlessSession.cs new file mode 100644 index 0000000..d777cd5 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/HeadlessSession.cs @@ -0,0 +1,83 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Headless; +using Avalonia.Threading; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +/// +/// The Avalonia headless session the UI tests share: one viewer for the whole test assembly, +/// drawn by Skia so that rendered frames can be captured. Anything that touches Avalonia runs on the session's +/// dispatcher thread through ; tests close the windows they open. +/// +internal static class HeadlessSession +{ + private static readonly TimeSpan RunTimeout = TimeSpan.FromSeconds(60); + + // HeadlessUnitTestSession.StartNew(typeof(App)) would draw with the headless stub, which cannot capture + // frames, so the session starts from HeadlessApp.BuildAvaloniaApp instead. + private static readonly Lazy Session = new( + () => HeadlessUnitTestSession.StartNew(typeof(HeadlessApp), AvaloniaTestIsolationLevel.PerAssembly)); + + /// Runs on the UI thread of the session and returns its result. + public static T Run(Func action) + { + ArgumentNullException.ThrowIfNull(action); + Task task = Session.Value.Dispatch(action, TestContext.Current.CancellationToken); + return task.WaitAsync(RunTimeout).GetAwaiter().GetResult(); + } + + /// Runs on the UI thread of the session. + public static void Run(Action action) + { + ArgumentNullException.ThrowIfNull(action); + Run(() => + { + action(); + return 0; + }); + } + + /// + /// On the UI thread: runs the dispatcher's jobs and render ticks until holds, + /// failing the test after . + /// + public static void PumpUntil(Func condition, string what, double seconds = 5) + { + DateTime deadline = DateTime.UtcNow.AddSeconds(seconds); + while (true) + { + Pump(); + if (condition()) + { + return; + } + + if (DateTime.UtcNow > deadline) + { + throw new TimeoutException("Timed out waiting until " + what + "."); + } + + Thread.Sleep(2); + } + } + + /// On the UI thread: runs the dispatcher's jobs and one render tick. + public static void Pump() + { + Dispatcher.UIThread.RunJobs(); + AvaloniaHeadlessPlatform.ForceRenderTimerTick(); + Dispatcher.UIThread.RunJobs(); + } +} + +/// The viewer's on the headless platform, drawn by Skia. +internal static class HeadlessApp +{ + public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() + .UseSkia() + .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }); +} diff --git a/test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj b/test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj index 3f688d8..bdb754b 100644 --- a/test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj +++ b/test/OpenSlideSharp.Viewer.Tests/OpenSlideSharp.Viewer.Tests.csproj @@ -10,6 +10,8 @@ + + diff --git a/test/OpenSlideSharp.Viewer.Tests/RenderedFrame.cs b/test/OpenSlideSharp.Viewer.Tests/RenderedFrame.cs new file mode 100644 index 0000000..6bccb35 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/RenderedFrame.cs @@ -0,0 +1,113 @@ +using System; +using System.Runtime.InteropServices; +using Avalonia.Controls; +using Avalonia.Headless; +using Avalonia.Media.Imaging; +using Avalonia.Platform; + +namespace OpenSlideSharp.Viewer.Tests; + +/// A frame the headless renderer drew, copied out as RGB in device pixels. +internal sealed class RenderedFrame +{ + private readonly byte[] _rgba; + + private RenderedFrame(int width, int height, byte[] rgba) + { + Width = width; + Height = height; + _rgba = rgba; + } + + public int Width { get; } + + public int Height { get; } + + public (byte R, byte G, byte B) this[int x, int y] + { + get + { + int i = ((y * Width) + x) * 4; + return (_rgba[i], _rgba[i + 1], _rgba[i + 2]); + } + } + + /// On the UI thread: renders and copies the frame. + public static RenderedFrame Capture(TopLevel topLevel) + { + using WriteableBitmap bitmap = topLevel.CaptureRenderedFrame() + ?? throw new InvalidOperationException("Nothing was rendered."); + using ILockedFramebuffer buffer = bitmap.Lock(); + bool bgra = buffer.Format == Avalonia.Platform.PixelFormat.Bgra8888; + if (!bgra && buffer.Format != Avalonia.Platform.PixelFormat.Rgba8888) + { + throw new NotSupportedException($"Frames in {buffer.Format} are not supported."); + } + + int width = buffer.Size.Width; + int height = buffer.Size.Height; + var rgba = new byte[width * height * 4]; + for (int y = 0; y < height; y++) + { + Marshal.Copy(buffer.Address + (y * buffer.RowBytes), rgba, y * width * 4, width * 4); + } + + if (bgra) + { + for (int i = 0; i < rgba.Length; i += 4) + { + (rgba[i], rgba[i + 2]) = (rgba[i + 2], rgba[i]); + } + } + + return new RenderedFrame(width, height, rgba); + } + + public static bool IsWhite((byte R, byte G, byte B) c) => c.R >= 245 && c.G >= 245 && c.B >= 245; + + public static bool IsRed((byte R, byte G, byte B) c) => c.R >= 200 && c.G <= 60 && c.B <= 60; + + public static bool IsBlue((byte R, byte G, byte B) c) => c.R <= 60 && c.G <= 60 && c.B >= 200; + + /// The selection outline colour, #FFD000. + public static bool IsSelectionYellow((byte R, byte G, byte B) c) => + Math.Abs(c.R - 0xFF) <= 8 && Math.Abs(c.G - 0xD0) <= 8 && c.B <= 8; + + public int Count(Func<(byte R, byte G, byte B), bool> match) + { + int count = 0; + for (int y = 0; y < Height; y++) + { + for (int x = 0; x < Width; x++) + { + if (match(this[x, y])) + { + count++; + } + } + } + + return count; + } + + /// The smallest rectangle holding every matching pixel (right and bottom exclusive), or null. + public (int Left, int Top, int Right, int Bottom)? BoundsOf(Func<(byte R, byte G, byte B), bool> match) + { + int left = int.MaxValue, top = int.MaxValue, right = int.MinValue, bottom = int.MinValue; + for (int y = 0; y < Height; y++) + { + for (int x = 0; x < Width; x++) + { + if (match(this[x, y])) + { + left = Math.Min(left, x); + top = Math.Min(top, y); + right = Math.Max(right, x + 1); + bottom = Math.Max(bottom, y + 1); + } + } + } + + return left == int.MaxValue ? null : (left, top, right, bottom); + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs b/test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs new file mode 100644 index 0000000..b211a03 --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs @@ -0,0 +1,624 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Headless; +using Avalonia.Input; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using OpenSlideSharp.Viewer.Controls; +using OpenSlideSharp.Viewer.Core; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class SlideViewTests +{ + private const double WindowWidth = 400; + private const double WindowHeight = 300; + + private static readonly double ZoomStep = Math.Pow(2, 0.25); + + private static OpenSlide Boxes() => OpenSlide.Open(TestFiles.Get("boxes.tiff")); + + [Fact] + public void SlideView_RendersSlidePixels() + { + using OpenSlide slide = Boxes(); + + (int coloured, int red, int blue) = HeadlessSession.Run(() => + { + using var host = new ViewHost(slide); + host.WaitForTiles(); + RenderedFrame frame = host.Capture(); + return ( + frame.Count(c => !RenderedFrame.IsWhite(c)), + frame.Count(RenderedFrame.IsRed), + frame.Count(RenderedFrame.IsBlue)); + }); + + Assert.True(coloured >= 1000, $"only {coloured} pixels are not background white"); + Assert.True(red > 0 && blue > 0, $"{red} red and {blue} blue pixels"); + } + + [Fact] + public void SlideView_RenderDoesNotReadOnUiThread() + { + using OpenSlide slide = Boxes(); + var readThreads = new ConcurrentQueue(); + using var gate = new ManualResetEventSlim(); + + (int uiThread, long reads) = HeadlessSession.Run(() => + { + using var host = new ViewHost(configure: view => view.TileReader = (s, grid, key) => + { + readThreads.Enqueue(Environment.CurrentManagedThreadId); + gate.Wait(TimeSpan.FromSeconds(30)); + return SlideView.ReadTile(s, grid, key); + }); + try + { + host.View.Slide = slide; + HeadlessSession.PumpUntil(() => !readThreads.IsEmpty, "a read starts"); + + // The reads are held, yet the UI thread goes on rendering frames. + for (int i = 0; i < 3; i++) + { + host.Capture(); + } + + Assert.True(host.View.PendingTiles > 0, "the reads finished early"); + } + finally + { + gate.Set(); + } + + host.WaitForTiles(); + return (Environment.CurrentManagedThreadId, host.View.TileReads); + }); + + Assert.True(reads > 0); + Assert.Equal(reads, readThreads.Count); + Assert.DoesNotContain(uiThread, readThreads); + } + + [Fact] + public void SlideView_WheelZoomsAtPointer() + { + using OpenSlide slide = Boxes(); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide); + Viewport viewport = host.View.Viewport!; + var at = new Point(100, 80); + host.Window.MouseMove(at); + (double X, double Y) before = host.View.PointerSlidePosition!.Value; + double downsample = viewport.Downsample; + + host.Window.MouseWheel(at, new Vector(0, 1)); + + (double X, double Y) after = host.View.PointerSlidePosition!.Value; + Assert.InRange(after.X - before.X, -1, 1); + Assert.InRange(after.Y - before.Y, -1, 1); + Assert.Equal(downsample / ZoomStep, viewport.Downsample, 9); + + host.Window.MouseWheel(at, new Vector(0, -2)); // out by two notches + Assert.Equal(downsample * ZoomStep, viewport.Downsample, 9); + Assert.InRange(host.View.PointerSlidePosition!.Value.X - before.X, -1, 1); + }); + } + + [Fact] + public void SlideView_DragPans() + { + using OpenSlide slide = Boxes(); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide); + Viewport viewport = host.View.Viewport!; + (double x, double y, double downsample) = (viewport.CenterX, viewport.CenterY, viewport.Downsample); + + Drag(host.Window, new Point(100, 100), new Point(150, 100)); + + Assert.Equal(x - (50 * downsample), viewport.CenterX, 9); + Assert.Equal(y, viewport.CenterY, 9); + Assert.Empty(host.View.Selections.Items); + + // Once the button is up, moving does not pan. + host.Window.MouseMove(new Point(200, 120)); + Assert.Equal(x - (50 * downsample), viewport.CenterX, 9); + Assert.Equal(y, viewport.CenterY, 9); + }); + } + + [Fact] + public void SlideView_ShiftDragAddsSelection() + { + using OpenSlide slide = Boxes(); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide); + Viewport viewport = host.View.Viewport!; + (double x0, double y0) = viewport.ScreenToSlide(100, 80); + (double x1, double y1) = viewport.ScreenToSlide(220, 200); + (double centerX, double centerY) = (viewport.CenterX, viewport.CenterY); + + Drag(host.Window, new Point(100, 80), new Point(220, 200), RawInputModifiers.Shift); + + Selection selection = Assert.Single(host.View.Selections.Items); + AssertSelection(x0, y0, x1 - x0, y1 - y0, selection); + Assert.Equal((centerX, centerY), (viewport.CenterX, viewport.CenterY)); // drawing does not pan + + // Dragged up and to the left, the rectangle is the same. + Drag(host.Window, new Point(220, 200), new Point(100, 80), RawInputModifiers.Shift); + Assert.Equal(2, host.View.Selections.Items.Count); + AssertSelection(x0, y0, x1 - x0, y1 - y0, host.View.Selections.Items[1]); + + // Without width or height nothing is added. + Drag(host.Window, new Point(50, 50), new Point(150, 50), RawInputModifiers.Shift); + Drag(host.Window, new Point(50, 50), new Point(50, 150), RawInputModifiers.Shift); + Assert.Equal(2, host.View.Selections.Items.Count); + }); + + static void AssertSelection(double x0, double y0, double width0, double height0, Selection actual) + { + Assert.Equal(x0, actual.X0, 9); + Assert.Equal(y0, actual.Y0, 9); + Assert.Equal(width0, actual.Width0, 9); + Assert.Equal(height0, actual.Height0, 9); + } + } + + [Fact] + public void SlideView_Keyboard_ZoomFitAndOneToOne() + { + using OpenSlide slide = Boxes(); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide); + host.Window.MouseDown(new Point(10, 10), MouseButton.Left); + host.Window.MouseUp(new Point(10, 10), MouseButton.Left); + Assert.True(host.View.IsFocused, "a click did not focus the view"); + Viewport viewport = host.View.Viewport!; + viewport.ZoomAt(50, 50, 3); + viewport.PanBy(30, 20); + + Press(host.Window, PhysicalKey.Digit1); + Assert.Equal(1, viewport.Downsample); + + Press(host.Window, PhysicalKey.Z); + (double, double, double) fitted = (viewport.Downsample, viewport.CenterX, viewport.CenterY); + Assert.NotEqual(1, fitted.Item1); + viewport.Fit(); + Assert.Equal(fitted, (viewport.Downsample, viewport.CenterX, viewport.CenterY)); + }); + } + + [Fact] + public void SlideView_Keyboard_PansZoomsAndCenters() + { + using OpenSlide slide = Boxes(); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide); + host.View.Focus(); + Viewport viewport = host.View.Viewport!; + (double x, double y, double downsample) = (viewport.CenterX, viewport.CenterY, viewport.Downsample); + double step = 100 * downsample; + + // The arrows and W/A/S/D move the view 100 pixels over the slide. + Press(host.Window, PhysicalKey.ArrowRight); + Assert.Equal(x + step, viewport.CenterX, 9); + Press(host.Window, PhysicalKey.D); + Assert.Equal(x + (2 * step), viewport.CenterX, 9); + Press(host.Window, PhysicalKey.ArrowLeft); + Press(host.Window, PhysicalKey.A); + Assert.Equal(x, viewport.CenterX, 9); + Press(host.Window, PhysicalKey.ArrowDown); + Assert.Equal(y + step, viewport.CenterY, 9); + Press(host.Window, PhysicalKey.W); + Press(host.Window, PhysicalKey.ArrowUp); + Assert.Equal(y - step, viewport.CenterY, 9); + Press(host.Window, PhysicalKey.S); + Assert.Equal((x, y), (viewport.CenterX, viewport.CenterY)); + + // + (or =) and - zoom by 2^(1/4) around the centre of the view. + Press(host.Window, PhysicalKey.Equal); + Assert.Equal(downsample / ZoomStep, viewport.Downsample, 9); + Press(host.Window, PhysicalKey.Equal, RawInputModifiers.Shift); // + + Assert.Equal(downsample / ZoomStep / ZoomStep, viewport.Downsample, 9); + Press(host.Window, PhysicalKey.Minus); + Press(host.Window, PhysicalKey.NumPadSubtract); + Assert.Equal(downsample, viewport.Downsample, 9); + Press(host.Window, PhysicalKey.NumPadAdd); + Assert.Equal(downsample / ZoomStep, viewport.Downsample, 9); + Assert.Equal((x, y), (viewport.CenterX, viewport.CenterY)); + + // Space centres the slide and keeps the zoom. + viewport.PanBy(-70, 40); + double zoomed = viewport.Downsample; + Press(host.Window, PhysicalKey.Space); + Assert.Equal((150.0, 125.0, zoomed), (viewport.CenterX, viewport.CenterY, viewport.Downsample)); + + // Shortcuts with Ctrl are left to the window. + Press(host.Window, PhysicalKey.Z, RawInputModifiers.Control); + Press(host.Window, PhysicalKey.ArrowRight, RawInputModifiers.Control); + Assert.Equal((150.0, 125.0, zoomed), (viewport.CenterX, viewport.CenterY, viewport.Downsample)); + }); + } + + [Fact] + public void SlideView_RenderScaling_UsesPhysicalPixels() + { + using OpenSlide slide = Boxes(); + (int Left, int Top, int Right, int Bottom) blue0 = SlideBounds(slide, RenderedFrame.IsBlue); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide, scaling: 2); + host.WaitForTiles(); + + RenderedFrame frame = host.Capture(); + + Assert.Equal((800, 600), (frame.Width, frame.Height)); + Viewport viewport = host.View.Viewport!; + Assert.Equal((WindowWidth, WindowHeight), (viewport.ViewWidth, viewport.ViewHeight)); // logical pixels + (double left, double top) = viewport.SlideToScreen(blue0.Left, blue0.Top); + (double right, double bottom) = viewport.SlideToScreen(blue0.Right, blue0.Bottom); + (int Left, int Top, int Right, int Bottom) blue = frame.BoundsOf(RenderedFrame.IsBlue)!.Value; + Assert.InRange(blue.Left, (left * 2) - 2, (left * 2) + 2); + Assert.InRange(blue.Top, (top * 2) - 2, (top * 2) + 2); + Assert.InRange(blue.Right, (right * 2) - 2, (right * 2) + 2); + Assert.InRange(blue.Bottom, (bottom * 2) - 2, (bottom * 2) + 2); + + // The level is picked per device pixel: 3 slide pixels per logical pixel are 1.5 per device pixel, so + // level 0 (downsample 1) rather than level 1 (downsample 2). + viewport.ZoomAt(200, 150, viewport.Downsample / 3); + host.Capture(); + Assert.Equal(0, host.View.TargetLevel); + host.Window.SetRenderScaling(1); + host.Capture(); + Assert.Equal(1, host.View.TargetLevel); + }); + } + + [Theory] + [InlineData(1.0)] + [InlineData(2.0)] + public void SlideView_DrawsSelectionsOneDevicePixelWide(double scaling) + { + using OpenSlide slide = Boxes(); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide, scaling); + host.WaitForTiles(); + Viewport viewport = host.View.Viewport!; + (double x0, double y0) = viewport.ScreenToSlide(60.3, 50.6); + (double x1, double y1) = viewport.ScreenToSlide(250.2, 200.7); + RenderedFrame before = host.Capture(); + host.View.Selections.Add(new Selection(x0, y0, x1 - x0, y1 - y0)); + + RenderedFrame frame = host.Capture(); + + // Each edge covers one device pixel fully and leaves the pixels on either side as they were. + int left = (int)Math.Floor(60.3 * scaling), right = (int)Math.Floor(250.2 * scaling); + int top = (int)Math.Floor(50.6 * scaling), bottom = (int)Math.Floor(200.7 * scaling); + int middleX = (left + right) / 2, middleY = (top + bottom) / 2; + foreach ((int x, int y, int dx, int dy) in new[] { (left, middleY, 1, 0), (right, middleY, 1, 0), (middleX, top, 0, 1), (middleX, bottom, 0, 1) }) + { + Assert.True(RenderedFrame.IsSelectionYellow(frame[x, y]), $"({x}, {y}) is {frame[x, y]}"); + Assert.Equal(before[x - dx, y - dy], frame[x - dx, y - dy]); + Assert.Equal(before[x + dx, y + dy], frame[x + dx, y + dy]); + } + + // The selection being drawn is dashed; once the button is up it is solid. + host.Window.MouseDown(new Point(300, 40), MouseButton.Left, RawInputModifiers.Shift); + host.Window.MouseMove(new Point(380, 280), RawInputModifiers.Shift | RawInputModifiers.LeftMouseButton); + double dashed = YellowFraction(host.Capture(), (int)Math.Floor(380 * scaling), (int)(60 * scaling), (int)(260 * scaling)); + Assert.InRange(dashed, 0.2, 0.8); + host.Window.MouseUp(new Point(380, 280), MouseButton.Left, RawInputModifiers.Shift); + double solid = YellowFraction(host.Capture(), (int)Math.Floor(380 * scaling), (int)(60 * scaling), (int)(260 * scaling)); + Assert.Equal(1.0, solid); + Assert.Equal(2, host.View.Selections.Items.Count); + }); + + static double YellowFraction(RenderedFrame frame, int x, int top, int bottom) => + Enumerable.Range(top, bottom - top).Count(y => RenderedFrame.IsSelectionYellow(frame[x, y])) / (double)(bottom - top); + } + + [Fact] + public void SlideView_SwitchSlide_DisposesOldLoader() + { + using OpenSlide boxes = Boxes(); + using OpenSlide small = OpenSlide.Open(TestFiles.Get("small.svs")); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(boxes); + host.WaitForTiles(); + host.View.Selections.Add(new Selection(10, 10, 20, 20)); + TileLoader oldLoader = host.View.Loader!; + TileCache oldCache = host.View.Cache!; + TileBitmapCache oldBitmaps = host.View.Bitmaps!; + Assert.True(oldCache.Count > 0 && oldBitmaps.Count > 0); + var key = new TileKey(0, 0, 0); + Assert.True(oldCache.TryGet(key, out TileImage? tile)); + Bitmap bitmap = oldBitmaps.Get(key, tile!)!; + + host.View.Slide = small; + + Assert.True(oldLoader.IsDisposed); + Assert.Equal(0, oldCache.Count); + Assert.Equal(0, oldCache.SizeBytes); + Assert.Equal(0, oldBitmaps.Count); + Assert.Throws(() => bitmap.PixelSize); + Assert.NotSame(oldLoader, host.View.Loader); + Assert.NotSame(oldCache, host.View.Cache); + Assert.Empty(host.View.Selections.Items); // they belonged to the other slide + Assert.Equal(0, host.View.TileReads); + Assert.Equal((8.0, 8.0), (host.View.Viewport!.CenterX, host.View.Viewport.CenterY)); // the 16 x 16 slide, centred + + host.WaitForTiles(); + Assert.True(host.View.Cache!.Count > 0); + }); + } + + [Fact] + public void SlideView_DrawsCoarserTilesWhileLoading() + { + using OpenSlide slide = Boxes(); + (int Left, int Top, int Right, int Bottom) blue0 = SlideBounds(slide, RenderedFrame.IsBlue); + using var gate = new ManualResetEventSlim(true); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(configure: view => view.TileReader = (s, grid, key) => + { + if (key.Level == 0) + { + gate.Wait(TimeSpan.FromSeconds(30)); + } + + return SlideView.ReadTile(s, grid, key); + }); + try + { + // Zoomed all the way out first, so only the coarsest level is read. + host.View.Slide = slide; + Viewport viewport = host.View.Viewport!; + viewport.ZoomAt(200, 150, 1.0 / 16); + host.WaitForTiles(); + Assert.Equal(slide.LevelCount - 1, host.View.TargetLevel); + + // Back to fit, level 0, whose reads are held: the coarse tiles stand in for them. + gate.Reset(); + viewport.Fit(); + HeadlessSession.PumpUntil(() => host.View.PendingTiles > 0, "level 0 is requested"); + RenderedFrame frame = host.Capture(); + + Assert.Equal(0, host.View.TargetLevel); + Assert.False(host.View.Cache!.Contains(new TileKey(0, 0, 0))); + int coloured = frame.Count(c => !RenderedFrame.IsWhite(c)); + Assert.True(coloured >= 1000, $"only {coloured} pixels are not background white"); + (double left, double top) = viewport.SlideToScreen(blue0.Left, blue0.Top); + (double right, double bottom) = viewport.SlideToScreen(blue0.Right, blue0.Bottom); + (int Left, int Top, int Right, int Bottom) blue = frame.BoundsOf(RenderedFrame.IsBlue)!.Value; + double slack = 1 + (slide.LevelDownsamples[^1] / viewport.Downsample); // a coarse pixel, in screen pixels + Assert.InRange(blue.Left, left - slack, left + slack); + Assert.InRange(blue.Top, top - slack, top + slack); + Assert.InRange(blue.Right, right - slack, right + slack); + Assert.InRange(blue.Bottom, bottom - slack, bottom + slack); + } + finally + { + gate.Set(); + } + + host.WaitForTiles(); + Assert.True(host.View.Cache!.Contains(new TileKey(0, 0, 0))); + }); + } + + [Fact] + public void SlideView_RapidZoom_KeepsBitmapsWithinTheCache() + { + using OpenSlide slide = Boxes(); + const long Budget = 300 * 1024; // both level-0 tiles fit, but not with the coarser ones as well + + HeadlessSession.Run(() => + { + using var host = new ViewHost(configure: view => view.CacheBudgetBytes = Budget); + host.View.Slide = slide; + Viewport viewport = host.View.Viewport!; + + for (int i = 0; i < 40; i++) + { + viewport.ZoomAt(200, 150, i % 2 == 0 ? 1.0 / 8 : 8); // out to the coarsest level, back in to level 0 + HeadlessSession.Pump(); + } + + host.WaitForTiles(); + host.Capture(); // a frame sweeps the bitmaps of the tiles evicted before it + + TileCache cache = host.View.Cache!; + Assert.InRange(cache.SizeBytes, 1, Budget); + Assert.True(host.View.Bitmaps!.Count <= cache.Count, $"{host.View.Bitmaps.Count} bitmaps for {cache.Count} cached tiles"); + }); + } + + [Fact] + public void SlideView_ReadFailure_RaisesLoadFailedOnceOnTheUiThread() + { + using OpenSlide slide = Boxes(); + var error = new OpenSlideException("corrupt tile"); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(configure: view => view.TileReader = (_, _, _) => throw error); + var failures = new List<(Exception Error, int Thread)>(); + host.View.LoadFailed += e => failures.Add((e, Environment.CurrentManagedThreadId)); + + host.View.Slide = slide; + HeadlessSession.PumpUntil(() => failures.Count > 0, "the failure is reported"); + long reads = host.View.TileReads; + host.View.Viewport!.ZoomAt(200, 150, 2); // a new view, but no new requests for this slide + for (int i = 0; i < 5; i++) + { + HeadlessSession.Pump(); + } + + (Exception reported, int thread) = Assert.Single(failures); + Assert.Same(error, reported); + Assert.Equal(Environment.CurrentManagedThreadId, thread); + Assert.Equal(reads, host.View.TileReads); + }); + } + + [Fact] + public void SlideView_PointerSlidePosition_FollowsThePointer() + { + using OpenSlide slide = Boxes(); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide); + int changes = 0; + host.View.ViewChanged += () => changes++; + Assert.Null(host.View.PointerSlidePosition); + + host.Window.MouseMove(new Point(200, 150)); + Assert.Equal(host.View.Viewport!.ScreenToSlide(200, 150), host.View.PointerSlidePosition); + Assert.True(changes > 0, "ViewChanged was not raised"); + + host.Window.MouseMove(new Point(WindowWidth + 50, WindowHeight + 50)); // off the view + Assert.Null(host.View.PointerSlidePosition); + + host.Window.MouseMove(new Point(200, 150)); + host.View.Slide = null; + Assert.Null(host.View.PointerSlidePosition); + Assert.Null(host.View.Viewport); + Assert.Null(host.View.Loader); + host.Capture(); // draws just the background + }); + } + + [Fact] + public void SlideView_RequestsTilesCenterFirst() + { + var grid = new TileGrid([new SlideSize(1280, 1280)], [1.0]); // 5 x 5 tiles + List keys = grid.VisibleTiles(0, 0, 0, 1280, 1280).ToList(); + + SlideView.SortCenterFirst(keys, grid, 640, 640); + + Assert.Equal(new TileKey(0, 2, 2), keys[0]); + double[] distances = keys.Select(Distance).ToArray(); + Assert.Equal(distances.Order(), distances); + Assert.Equal(25, keys.Distinct().Count()); + + double Distance(TileKey key) + { + (double left, double top, double right, double bottom) = grid.Bounds(key); + return Math.Pow(((left + right) / 2) - 640, 2) + Math.Pow(((top + bottom) / 2) - 640, 2); + } + } + + [Fact] + public void SlideView_BackgroundColor_ComesFromTheSlide() + { + Assert.Equal(Color.FromRgb(0x10, 0x20, 0x30), SlideView.BackgroundColor(Properties("102030"))); + Assert.Equal(Color.FromRgb(0xAB, 0xCD, 0xEF), SlideView.BackgroundColor(Properties("abcdef"))); + Assert.Equal(Colors.White, SlideView.BackgroundColor(new Dictionary())); + foreach (string malformed in new[] { "", "12345", "1234567", "GG0000", "+12345", " 12345", "0x1234" }) + { + Assert.Equal(Colors.White, SlideView.BackgroundColor(Properties(malformed))); + } + + static Dictionary Properties(string color) => new() { [OpenSlideProperties.BackgroundColor] = color }; + } + + private static void Drag(Window window, Point from, Point to, RawInputModifiers modifiers = RawInputModifiers.None) + { + window.MouseDown(from, MouseButton.Left, modifiers); + window.MouseMove(new Point((from.X + to.X) / 2, (from.Y + to.Y) / 2), modifiers | RawInputModifiers.LeftMouseButton); + window.MouseMove(to, modifiers | RawInputModifiers.LeftMouseButton); + window.MouseUp(to, MouseButton.Left, modifiers); + } + + private static void Press(Window window, PhysicalKey key, RawInputModifiers modifiers = RawInputModifiers.None) + { + window.KeyPressQwerty(key, modifiers); + window.KeyReleaseQwerty(key, modifiers); + } + + /// The level-0 rectangle (right and bottom exclusive) holding every pixel of the slide that matches. + private static (int Left, int Top, int Right, int Bottom) SlideBounds(OpenSlide slide, Func<(byte R, byte G, byte B), bool> match) + { + int width = (int)slide.Dimensions.Width, height = (int)slide.Dimensions.Height; + var bgra = new byte[width * height * 4]; + slide.ReadRegion(0, 0, 0, width, height, bgra); + int left = int.MaxValue, top = int.MaxValue, right = int.MinValue, bottom = int.MinValue; + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + int i = ((y * width) + x) * 4; + if (match((bgra[i + 2], bgra[i + 1], bgra[i]))) + { + (left, top) = (Math.Min(left, x), Math.Min(top, y)); + (right, bottom) = (Math.Max(right, x + 1), Math.Max(bottom, y + 1)); + } + } + } + + Assert.NotEqual(int.MaxValue, left); + return (left, top, right, bottom); + } + + /// A 400 x 300 window holding a ; closing it disposes the view's loader. + private sealed class ViewHost : IDisposable + { + public ViewHost(OpenSlide? slide = null, double scaling = 1, Action? configure = null) + { + View = new SlideView(); + configure?.Invoke(View); + Window = new Window { Width = WindowWidth, Height = WindowHeight, Content = View }; + Window.Show(); + if (scaling != 1) + { + Window.SetRenderScaling(scaling); + } + + HeadlessSession.Pump(); // lays the view out + if (slide is not null) + { + View.Slide = slide; + } + } + + public SlideView View { get; } + + public Window Window { get; } + + /// Renders until the view has read its tiles and has none left to read. + public void WaitForTiles() => + HeadlessSession.PumpUntil(() => View.TileReads > 0 && View.PendingTiles == 0, "the visible tiles are loaded"); + + public RenderedFrame Capture() => RenderedFrame.Capture(Window); + + public void Dispose() + { + Window.Close(); + HeadlessSession.Pump(); + } + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/TileBitmapCacheTests.cs b/test/OpenSlideSharp.Viewer.Tests/TileBitmapCacheTests.cs new file mode 100644 index 0000000..7462e2b --- /dev/null +++ b/test/OpenSlideSharp.Viewer.Tests/TileBitmapCacheTests.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Avalonia; +using Avalonia.Media.Imaging; +using OpenSlideSharp.Viewer.Controls; +using OpenSlideSharp.Viewer.Core; +using Xunit; + +namespace OpenSlideSharp.Viewer.Tests; + +public class TileBitmapCacheTests +{ + private const int TileBytes = 2 * 2 * 4; + + private static TileKey Key(int i) => new(0, i, 0); + + private static TileImage Tile(List? released = null) => + new(2, 2, new byte[TileBytes], released is null ? null : released.Add); + + private static bool IsDisposed(Bitmap bitmap) + { + try + { + _ = bitmap.PixelSize; + return false; + } + catch (ObjectDisposedException) + { + return true; + } + } + + [Fact] + public void BitmapCache_DisposesTheBitmapsOfEvictedTiles() + { + HeadlessSession.Run(() => + { + using var cache = new TileCache(2 * TileBytes); + using var bitmaps = new TileBitmapCache(); + TileImage a = Tile(), b = Tile(), c = Tile(); + cache.Add(Key(0), a); + cache.Add(Key(1), b); + Bitmap bitmapA = bitmaps.Get(Key(0), a)!; + Bitmap bitmapB = bitmaps.Get(Key(1), b)!; + Assert.Same(bitmapA, bitmaps.Get(Key(0), a)); // built once + Assert.Equal(2, bitmaps.Count); + + cache.Add(Key(2), c); // evicts a, the least recently used + Assert.True(a.IsDisposed); + Assert.False(IsDisposed(bitmapA)); // until the next sweep: a frame being drawn may still use it + + Assert.Equal(1, bitmaps.Sweep()); + Assert.True(IsDisposed(bitmapA)); + Assert.False(IsDisposed(bitmapB)); + Assert.Equal(1, bitmaps.Count); + Assert.Equal(0, bitmaps.Sweep()); + + cache.Clear(); + Assert.Equal(1, bitmaps.Sweep()); + Assert.True(IsDisposed(bitmapB)); + Assert.Equal(0, bitmaps.Count); + }); + } + + [Fact] + public void BitmapCache_ReplacedTile_DisposesTheOldBitmap() + { + HeadlessSession.Run(() => + { + using var cache = new TileCache(1 << 20); + using var bitmaps = new TileBitmapCache(); + TileImage first = Tile(), second = Tile(); + cache.Add(Key(0), first); + Bitmap old = bitmaps.Get(Key(0), first)!; + + cache.Add(Key(0), second); // the same tile read again + Bitmap replacement = bitmaps.Get(Key(0), second)!; + + Assert.NotSame(old, replacement); + Assert.True(IsDisposed(old)); + Assert.Equal(1, bitmaps.Count); + }); + } + + [Fact] + public void BitmapCache_BuildsTheBitmapFromThePixelsThenReleasesThem() + { + HeadlessSession.Run(() => + { + using var bitmaps = new TileBitmapCache(); + var released = new List(); + // Premultiplied BGRA: opaque blue, half-transparent red, transparent, opaque white. + byte[] pixels = [255, 0, 0, 255, 0, 0, 128, 128, 0, 0, 0, 0, 255, 255, 255, 255, 99, 99]; // two spare bytes + var tile = new TileImage(2, 2, pixels, released.Add); + + Bitmap bitmap = bitmaps.Get(Key(0), tile)!; + + Assert.Equal(new PixelSize(2, 2), bitmap.PixelSize); + Assert.Equal(Avalonia.Platform.PixelFormat.Bgra8888, bitmap.Format); + Assert.Equal(Avalonia.Platform.AlphaFormat.Premul, bitmap.AlphaFormat); + var copy = new byte[TileBytes]; + GCHandle handle = GCHandle.Alloc(copy, GCHandleType.Pinned); + try + { + bitmap.CopyPixels(new PixelRect(0, 0, 2, 2), handle.AddrOfPinnedObject(), copy.Length, 2 * 4); + } + finally + { + handle.Free(); + } + + Assert.Equal(pixels.AsSpan(0, TileBytes).ToArray(), copy); + // The bitmap holds the pixels now: the buffer went back to its owner straight away. + Assert.Same(pixels, Assert.Single(released)); + Assert.False(tile.HasPixels); + Assert.Same(bitmap, bitmaps.Get(Key(0), tile)); + }); + } + + [Fact] + public void BitmapCache_DisposedTile_HasNoBitmap() + { + HeadlessSession.Run(() => + { + using var bitmaps = new TileBitmapCache(); + var released = new List(); + TileImage tile = Tile(released); + tile.Dispose(); // evicted before it was ever drawn + + Assert.Null(bitmaps.Get(Key(0), tile)); + Assert.Equal(0, bitmaps.Count); + Assert.Single(released); + }); + } + + [Fact] + public void BitmapCache_Dispose_DisposesEveryBitmap() + { + HeadlessSession.Run(() => + { + var bitmaps = new TileBitmapCache(); + Bitmap bitmap = bitmaps.Get(Key(0), Tile())!; + + bitmaps.Dispose(); + + Assert.True(IsDisposed(bitmap)); + Assert.Equal(0, bitmaps.Count); + }); + } +} diff --git a/test/OpenSlideSharp.Viewer.Tests/TileGridTests.cs b/test/OpenSlideSharp.Viewer.Tests/TileGridTests.cs index bbc1d3c..896010b 100644 --- a/test/OpenSlideSharp.Viewer.Tests/TileGridTests.cs +++ b/test/OpenSlideSharp.Viewer.Tests/TileGridTests.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using System.Linq; using OpenSlideSharp.Viewer.Core; using Xunit; @@ -74,4 +76,43 @@ public void TileGrid_OutsideSlide_NoTiles() Assert.Equal([new TileKey(0, 0, 0)], grid.VisibleTiles(0, -100, -100, 50, 50)); Assert.Equal([new TileKey(0, 1, 0)], grid.VisibleTiles(0, 290, 200, 5000, 5000)); } + + [Theory] + [InlineData("boxes.tiff")] + [InlineData("small.svs")] + public void TileGrid_BestLevel_MatchesOpenSlide(string fixture) + { + // The view picks its level on the UI thread without a native call; it must pick the one OpenSlide would. + using var slide = OpenSlide.Open(TestFiles.Get(fixture)); + var grid = new TileGrid(slide.LevelDimensions, slide.LevelDownsamples); + var downsamples = new List { -1, 0, 0.1, 0.25, double.MaxValue, double.PositiveInfinity, double.NaN }; + for (double downsample = 0.25; downsample <= 64; downsample *= 1.05) + { + downsamples.Add(downsample); + } + + foreach (double level in slide.LevelDownsamples) + { + downsamples.AddRange([Math.BitDecrement(level), level, Math.BitIncrement(level)]); + } + + Assert.Equal(slide.LevelCount, grid.LevelCount); + for (int level = 0; level < grid.LevelCount; level++) + { + Assert.Equal(slide.LevelDownsamples[level], grid.LevelDownsample(level)); + } + + foreach (double downsample in downsamples) + { + Assert.True( + slide.GetBestLevelForDownsample(downsample) == grid.BestLevelForDownsample(downsample), + $"downsample {downsample}: OpenSlide {slide.GetBestLevelForDownsample(downsample)}, grid {grid.BestLevelForDownsample(downsample)}"); + } + + // A slide without levels has nothing to draw at level 0 either. + var empty = new TileGrid([], []); + Assert.Equal(0, empty.LevelCount); + Assert.Equal(0, empty.BestLevelForDownsample(4)); + Assert.Empty(empty.VisibleTiles(0, 0, 0, 100, 100)); + } } From cdf597a6c2bf016957a82e7ce25ca3a5eed49338 Mon Sep 17 00:00:00 2001 From: IOL0ol1 <1353839731@qq.com> Date: Wed, 18 Nov 2026 15:49:24 +0800 Subject: [PATCH 06/21] feat: show coarse tiles first and keep failure and drag state in SlideView - When a visible tile is missing and no cached coarser tile stands in for it, the view requests the tiles two levels up (capped at the coarsest level) before the target tiles, so a slide just opened, or a part of it not seen yet, shows a low-resolution image quickly and is then replaced. - A read failure now belongs to the slide rather than to the loader: a loader rebuilt after the view leaves the visual tree and comes back neither reads the slide again nor raises LoadFailed again. Setting the slide again tries it again. - A drag follows the pointer that started it. Presses, moves and releases of other pointers (a second finger, say) no longer move the pan anchor or the selection start. - LoaderThreads: an internal hook for the number of loader threads, used by the tests. --- .../Controls/SlideView.cs | 128 +++++++++++++---- .../SlideViewTests.cs | 129 ++++++++++++++++++ 2 files changed, 227 insertions(+), 30 deletions(-) diff --git a/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs b/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs index de3e0a2..925fe83 100644 --- a/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs +++ b/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs @@ -21,8 +21,10 @@ namespace OpenSlideSharp.Viewer.Controls; /// /// Each frame draws the tiles of the level that suits the zoom ( of /// the downsample per device pixel), aligned to device pixels. A tile not loaded yet is stood in for by the cached -/// tiles of coarser levels, scaled up; the missing tiles are requested centre first. A frame never reads the slide: -/// the reads on its own threads, and each tile it loads schedules one redraw at most. +/// tiles of coarser levels, scaled up; the missing tiles are requested centre first. Where no cached tile stands in +/// (a slide just opened, or a part of it not seen yet), the tiles two levels up are requested before them, so a +/// low-resolution image shows quickly and is then replaced. A frame never reads the slide: the +/// reads on its own threads, and each tile it loads schedules one redraw at most. /// /// /// Setting builds a new viewport and loading pipeline (tile cache, bitmap cache and loader), and @@ -30,16 +32,20 @@ namespace OpenSlideSharp.Viewer.Controls; /// after replacing it here. Leaving the visual tree (closing the window) disposes the pipeline too. /// /// -/// Input: dragging with the left button pans, and with Shift held draws a selection; the wheel zooms around the -/// pointer by 2^(1/4) a notch. Keys, while the view has the focus (it takes it when clicked): the arrows or W, A, -/// S and D pan by 100 pixels, + (or =) and - zoom around the centre, Z fits the slide, 1 zooms to one slide pixel per -/// screen pixel and Space centres the slide. +/// Input: dragging with the left button (or a finger) pans, and with Shift held draws a selection; one drag at a +/// time, so other buttons or fingers pressed meanwhile are ignored. The wheel zooms around the pointer by 2^(1/4) a +/// notch. Keys, while the view has the focus (it takes it when clicked): the arrows or W, A, S and D pan by 100 +/// pixels, + (or =) and - zoom around the centre, Z fits the slide, 1 zooms to one slide pixel per screen pixel and +/// Space centres the slide. /// /// internal sealed class SlideView : Control { private const double KeyboardPan = 100; + // How many levels above the target level the quick stand-ins are read from (see DrawTiles). + private const int CoarseLevelStep = 2; + private static readonly double ZoomStep = Math.Pow(2, 0.25); private static readonly ImmutableSolidColorBrush SelectionBrush = new(Color.FromRgb(0xFF, 0xD0, 0x00)); private static readonly ImmutableDashStyle SelectionBeingDrawnDashes = new([4, 4], 0); @@ -52,8 +58,11 @@ internal sealed class SlideView : Control private static readonly Action ReturnPixels = pixels => PixelPool.Return(pixels); private readonly List _missing = new(); + private readonly List _coarse = new(); + private readonly HashSet _coarseSeen = new(); private readonly List<(Bitmap Bitmap, Rect Source, Rect Destination)> _coarser = new(); private OpenSlide? _slide; + private SlideState? _slideState; private TileGrid? _grid; private Viewport? _viewport; private Pipeline? _pipeline; @@ -61,6 +70,7 @@ internal sealed class SlideView : Control private bool _attached; private Point? _pointer; private DragMode _drag; + private IPointer? _dragPointer; private Point _dragFrom; private (double X, double Y) _selectionStart; private Selection? _selectionBeingDrawn; @@ -86,7 +96,8 @@ private enum DragMode public event Action? ViewChanged; /// - /// Raised on the UI thread, once per slide, when reading a tile fails; the view then reads no more tiles of it. + /// Raised on the UI thread, once per slide, when reading a tile fails; the view then reads no more tiles of it, + /// even after leaving the visual tree and coming back, until is set again. /// public event Action? LoadFailed; @@ -121,6 +132,9 @@ public OpenSlide? Slide /// Gets or sets the tile cache budget, taken when the loading pipeline is built. internal long CacheBudgetBytes { get; set; } = TileCache.DefaultBudgetBytes; + /// Gets or sets the number of loader threads, taken when the loading pipeline is built. + internal int LoaderThreads { get; set; } = Math.Min(4, Environment.ProcessorCount); + /// Gets the level the last frame drew. internal int TargetLevel { get; private set; } @@ -217,12 +231,16 @@ protected override void OnPointerPressed(PointerPressedEventArgs e) Focus(NavigationMethod.Pointer); PointerPoint point = e.GetCurrentPoint(this); _pointer = point.Position; - if (_viewport is not { } viewport || !point.Properties.IsLeftButtonPressed) + // One drag at a time: a press during one (another finger, say) neither restarts it nor moves its anchor. + if (_drag != DragMode.None + || _viewport is not { } viewport + || point.Properties.PointerUpdateKind != PointerUpdateKind.LeftButtonPressed) { return; } _drag = (e.KeyModifiers & KeyModifiers.Shift) != 0 ? DragMode.Select : DragMode.Pan; + _dragPointer = e.Pointer; _dragFrom = point.Position; _selectionStart = viewport.ScreenToSlide(point.Position.X, point.Position.Y); e.Pointer.Capture(this); @@ -234,7 +252,7 @@ protected override void OnPointerMoved(PointerEventArgs e) base.OnPointerMoved(e); Point position = e.GetPosition(this); _pointer = position; - if (_viewport is { } viewport) + if (_viewport is { } viewport && e.Pointer == _dragPointer) { if (_drag == DragMode.Pan) { @@ -255,7 +273,7 @@ protected override void OnPointerMoved(PointerEventArgs e) protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); - if (e.InitialPressMouseButton != MouseButton.Left || _drag == DragMode.None) + if (_drag == DragMode.None || e.Pointer != _dragPointer || e.InitialPressMouseButton != MouseButton.Left) { return; } @@ -277,7 +295,10 @@ protected override void OnPointerReleased(PointerReleasedEventArgs e) protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) { base.OnPointerCaptureLost(e); - EndDrag(); // another control took the pointer: a selection being drawn is dropped + if (e.Pointer == _dragPointer) + { + EndDrag(); // another control took the pointer: a selection being drawn is dropped + } } protected override void OnPointerExited(PointerEventArgs e) @@ -424,6 +445,7 @@ private void SetSlide(OpenSlide? slide) } _slide = slide; + _slideState = slide is null ? null : new SlideState(); _grid = grid; _viewport = viewport; _background = background; @@ -443,7 +465,8 @@ private void SetSlide(OpenSlide? slide) private void OpenPipeline() { - if (_pipeline is not null || !_attached || _slide is not { } slide || _grid is not { } grid) + if (_pipeline is not null || !_attached || _slide is not { } slide || _slideState is not { } state + || _grid is not { } grid) { return; } @@ -457,16 +480,23 @@ private void OpenPipeline() return read(slide, grid, key); }, cache, - Math.Min(4, Environment.ProcessorCount), + LoaderThreads, _ => ScheduleRedraw()); var pipeline = new Pipeline(grid, cache, new TileBitmapCache(), loader); - loader.Failed += error => Dispatcher.UIThread.Post(() => + loader.Failed += error => { - if (ReferenceEquals(pipeline, _pipeline)) + // The failure belongs to the slide, not to this loader: a loader built after leaving the visual tree + // and coming back must not read the slide again, nor report it again. + state.Failed = true; + Dispatcher.UIThread.Post(() => { - LoadFailed?.Invoke(error); - } - }); + if (ReferenceEquals(state, _slideState) && !state.Reported) + { + state.Reported = true; + LoadFailed?.Invoke(error); + } + }); + }; _pipeline = pipeline; InvalidateVisual(); } @@ -506,7 +536,13 @@ private void DrawTiles(DrawingContext context, Pipeline pipeline, Viewport viewp (double left0, double top0) = viewport.ScreenToSlide(0, 0); (double right0, double bottom0) = viewport.ScreenToSlide(viewport.ViewWidth, viewport.ViewHeight); + // Missing tiles that nothing cached stands in for are first covered from a coarse level, two levels up + // (4 to 16 times coarser on the usual pyramids, so a few tiles cover a screenful), read before the + // target tiles: a slide just opened, or a part of it not seen yet, shows a low-resolution image quickly. + int coarseLevel = Math.Min(level + CoarseLevelStep, grid.LevelCount - 1); _missing.Clear(); + _coarse.Clear(); + _coarseSeen.Clear(); using (context.PushRenderOptions(new RenderOptions { BitmapInterpolationMode = BitmapInterpolationMode.HighQuality })) { foreach (TileKey key in grid.VisibleTiles(level, left0, top0, right0, bottom0)) @@ -515,31 +551,49 @@ private void DrawTiles(DrawingContext context, Pipeline pipeline, Viewport viewp { (double left, double top, double right, double bottom) = grid.Bounds(key); context.DrawImage(bitmap, new Rect(bitmap.Size), OnScreen(viewport, scaling, left, top, right, bottom)); + continue; } - else + + _missing.Add(key); + if (!DrawCoarser(context, pipeline, viewport, scaling, key) && coarseLevel > level) { - _missing.Add(key); - DrawCoarser(context, pipeline, viewport, scaling, key); + (double left, double top, double right, double bottom) = grid.Bounds(key); + foreach (TileKey coarse in grid.VisibleTiles(coarseLevel, left, top, right, bottom)) + { + if (_coarseSeen.Add(coarse)) + { + _coarse.Add(coarse); + } + } } } } + if (_slideState is { Failed: true }) + { + return; // reading this slide failed: no more requests for it + } + + SortCenterFirst(_coarse, grid, viewport.CenterX, viewport.CenterY); SortCenterFirst(_missing, grid, viewport.CenterX, viewport.CenterY); - pipeline.Loader.Request(_missing); // also drops what earlier frames queued and this one no longer needs + _coarse.AddRange(_missing); + pipeline.Loader.Request(_coarse); // also drops what earlier frames queued and this one no longer needs } /// /// Stands in for a tile not loaded yet with the cached tiles of coarser levels: from the next level up to the /// first one whose cached tiles cover the whole tile, drawing coarser levels first so finer ones end up on top. + /// Returns whether one level covered the whole tile. /// - private void DrawCoarser(DrawingContext context, Pipeline pipeline, Viewport viewport, double scaling, TileKey key) + private bool DrawCoarser(DrawingContext context, Pipeline pipeline, Viewport viewport, double scaling, TileKey key) { TileGrid grid = pipeline.Grid; (double areaLeft, double areaTop, double areaRight, double areaBottom) = grid.Bounds(key); _coarser.Clear(); - for (int level = key.Level + 1; level < grid.LevelCount; level++) + bool covered = false; + for (int level = key.Level + 1; level < grid.LevelCount && !covered; level++) { - bool covered = true; + covered = true; double downsample = grid.LevelDownsample(level); foreach (TileKey coarse in grid.VisibleTiles(level, areaLeft, areaTop, areaRight, areaBottom)) { @@ -561,17 +615,14 @@ private void DrawCoarser(DrawingContext context, Pipeline pipeline, Viewport vie (bottom - top) / downsample); _coarser.Add((bitmap, source, OnScreen(viewport, scaling, left, top, right, bottom))); } - - if (covered) - { - break; - } } for (int i = _coarser.Count - 1; i >= 0; i--) { context.DrawImage(_coarser[i].Bitmap, _coarser[i].Source, _coarser[i].Destination); } + + return covered; } private Bitmap? BitmapOf(Pipeline pipeline, TileKey key) => @@ -612,6 +663,7 @@ private Selection SelectionTo(Viewport viewport, Point position) private void EndDrag() { _drag = DragMode.None; + _dragPointer = null; if (_selectionBeingDrawn is not null) { _selectionBeingDrawn = null; @@ -619,6 +671,22 @@ private void EndDrag() } } + /// What the view keeps about the slide while it is set, across loading pipelines. + private sealed class SlideState + { + // Set on a loader thread when a read fails; read by every frame. + private volatile bool _failed; + + public bool Failed + { + get => _failed; + set => _failed = value; + } + + /// Gets or sets whether was raised (UI thread only). + public bool Reported { get; set; } + } + /// The loading machinery of one slide: built when a slide is set, disposed together. private sealed class Pipeline(TileGrid grid, TileCache cache, TileBitmapCache bitmaps, TileLoader loader) : IDisposable { diff --git a/test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs b/test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs index b211a03..b03758c 100644 --- a/test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs +++ b/test/OpenSlideSharp.Viewer.Tests/SlideViewTests.cs @@ -429,6 +429,135 @@ public void SlideView_DrawsCoarserTilesWhileLoading() }); } + [Fact] + public void SlideView_NewSlide_ShowsACoarseLevelBeforeTheTargetLevel() + { + using OpenSlide slide = Boxes(); + using var gate = new ManualResetEventSlim(); + var levelsRead = new ConcurrentQueue(); + + HeadlessSession.Run(() => + { + // One loader thread, and level 0 held: if a level-0 tile were read first, nothing would ever load. + using var host = new ViewHost(configure: view => + { + view.LoaderThreads = 1; + view.TileReader = (s, grid, key) => + { + levelsRead.Enqueue(key.Level); + if (key.Level == 0) + { + gate.Wait(TimeSpan.FromSeconds(30)); + } + + return SlideView.ReadTile(s, grid, key); + }; + }); + try + { + // Fitted to the window, the slide is drawn from level 0, and nothing is cached yet. + host.View.Slide = slide; + HeadlessSession.PumpUntil(() => levelsRead.Contains(0), "the coarse tiles are read and level 0 is next"); + RenderedFrame frame = host.Capture(); + + Assert.Equal(0, host.View.TargetLevel); + Assert.NotEqual(0, levelsRead.First()); + Assert.False(host.View.Cache!.Contains(new TileKey(0, 0, 0))); + int coloured = frame.Count(c => !RenderedFrame.IsWhite(c)); + Assert.True(coloured >= 1000, $"only {coloured} pixels are not background white"); + Assert.True(frame.Count(RenderedFrame.IsRed) > 0 && frame.Count(RenderedFrame.IsBlue) > 0, "the boxes are not drawn"); + } + finally + { + gate.Set(); + } + + host.WaitForTiles(); + Assert.True(host.View.Cache!.Contains(new TileKey(0, 0, 0))); + }); + } + + [Fact] + public void SlideView_ReadFailure_StaysReportedWhenTheViewIsAttachedAgain() + { + using OpenSlide slide = Boxes(); + var error = new OpenSlideException("corrupt tile"); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(configure: view => view.TileReader = (_, _, _) => throw error); + int failures = 0; + host.View.LoadFailed += _ => failures++; + host.View.Slide = slide; + HeadlessSession.PumpUntil(() => failures > 0, "the failure is reported"); + long reads = host.View.TileReads; + + // Out of the window and back: a new loader, but the slide is still known to fail. + host.Window.Content = null; + HeadlessSession.Pump(); + Assert.Null(host.View.Loader); + host.Window.Content = host.View; + for (int i = 0; i < 20; i++) + { + HeadlessSession.Pump(); + Thread.Sleep(5); + } + + Assert.NotNull(host.View.Loader); + Assert.Equal(1, failures); + Assert.Equal(reads, host.View.TileReads); + + // Setting the slide again tries it again. + host.View.Slide = null; + host.View.Slide = slide; + HeadlessSession.PumpUntil(() => failures == 2, "the failure is reported again"); + }); + } + + [Fact] + public void SlideView_AnotherPointerPressed_KeepsTheDrag() + { + using OpenSlide slide = Boxes(); + + HeadlessSession.Run(() => + { + using var host = new ViewHost(slide); + Viewport viewport = host.View.Viewport!; + (double x, double y, double downsample) = (viewport.CenterX, viewport.CenterY, viewport.Downsample); + + // Panning with one finger: a second one touching down, moving and lifting changes nothing. + IHeadlessTouchPointer first = host.Window.TouchBegin(new Point(100, 100)); + host.Window.TouchMove(first, new Point(120, 100)); + IHeadlessTouchPointer second = host.Window.TouchBegin(new Point(300, 200)); + host.Window.TouchMove(second, new Point(320, 230)); + Assert.Equal((x - (20 * downsample), y), (viewport.CenterX, viewport.CenterY)); + host.Window.TouchMove(first, new Point(140, 100)); + host.Window.TouchEnd(second, new Point(320, 230)); + host.Window.TouchMove(first, new Point(160, 100)); + host.Window.TouchEnd(first, new Point(160, 100)); + + Assert.Equal(x - (60 * downsample), viewport.CenterX, 9); + Assert.Equal(y, viewport.CenterY, 9); + + // Drawing a selection: the second finger moves neither its start nor its end. + (double x0, double y0) = viewport.ScreenToSlide(100, 80); + (double x1, double y1) = viewport.ScreenToSlide(220, 200); + first = host.Window.TouchBegin(new Point(100, 80), RawInputModifiers.Shift); + host.Window.TouchMove(first, new Point(150, 120), RawInputModifiers.Shift); + second = host.Window.TouchBegin(new Point(300, 250), RawInputModifiers.Shift); + host.Window.TouchMove(second, new Point(310, 260), RawInputModifiers.Shift); + host.Window.TouchEnd(second, new Point(310, 260), RawInputModifiers.Shift); + host.Window.TouchMove(first, new Point(220, 200), RawInputModifiers.Shift); + host.Window.TouchEnd(first, new Point(220, 200), RawInputModifiers.Shift); + + Selection selection = Assert.Single(host.View.Selections.Items); + Assert.Equal(x0, selection.X0, 9); + Assert.Equal(y0, selection.Y0, 9); + Assert.Equal(x1 - x0, selection.Width0, 9); + Assert.Equal(y1 - y0, selection.Height0, 9); + }); + } + [Fact] public void SlideView_RapidZoom_KeepsBitmapsWithinTheCache() { From 3bf31b676684077a283325cb6e2a6cdadb745ab3 Mon Sep 17 00:00:00 2001 From: IOL0ol1 <1353839731@qq.com> Date: Wed, 18 Nov 2026 16:20:39 +0800 Subject: [PATCH 07/21] feat: add the viewer window with navigator, properties, associated images and selections - MainWindow: File (Open..., Close, Exit) and View (Fit, 1:1, Center) menus; a resizable left pane with the navigator and Properties / Associated images / Selections tabs; the SlideView; a status bar; the title "OpenSlide Viewer - " (with an em dash). - OpenAsync opens the slide, its sorted properties and the navigator's picture on a background thread. A file that cannot be opened is reported in red in the status bar and the current slide stays. On success the view takes the new slide before the old one is disposed, and the selections, properties, associated images and their windows are replaced. An open overtaken by a newer one (or by Close) is dropped and disposed. - Slides open from the first command-line argument, File > Open (the storage provider's file picker) or by dropping files (the first one). - Navigator: the thumbnail (GetThumbnail(256, 256), or the thumbnail associated image when the level it would read is over 16 Mi pixels or reading fails) with the view outlined; a click or drag centres the view. - Properties: a two-column list sorted by key; the copy key and a context menu copy the selected rows (keyvalue) or their values. - Associated images: a double click (or Enter) opens a window titled with the image name, showing the premultiplied BGRA pixels scaled uniformly. - Selections: one row each, with Zoom to and Delete buttons. - Status bar (StatusFormatter): level-0 coordinates under the pointer (on the slide only), the zoom with the magnification when the slide has an objective power, and the physical size of the view and of the current selection when it has mpp. --- samples/OpenSlideSharp.Viewer/App.axaml.cs | 15 +- .../AssociatedImageWindow.axaml | 10 + .../AssociatedImageWindow.axaml.cs | 48 ++ .../Controls/Navigator.cs | 192 +++++++ .../Controls/PixelImageExtensions.cs | 39 ++ .../OpenSlideSharp.Viewer/MainWindow.axaml | 129 +++++ .../OpenSlideSharp.Viewer/MainWindow.axaml.cs | 500 ++++++++++++++++ .../OpenSlideSharp.Viewer/StatusFormatter.cs | 72 +++ .../MainWindowTests.cs | 534 ++++++++++++++++++ .../StatusFormatterTests.cs | 88 +++ 10 files changed, 1623 insertions(+), 4 deletions(-) create mode 100644 samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml create mode 100644 samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml.cs create mode 100644 samples/OpenSlideSharp.Viewer/Controls/Navigator.cs create mode 100644 samples/OpenSlideSharp.Viewer/Controls/PixelImageExtensions.cs create mode 100644 samples/OpenSlideSharp.Viewer/MainWindow.axaml create mode 100644 samples/OpenSlideSharp.Viewer/MainWindow.axaml.cs create mode 100644 samples/OpenSlideSharp.Viewer/StatusFormatter.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/MainWindowTests.cs create mode 100644 test/OpenSlideSharp.Viewer.Tests/StatusFormatterTests.cs diff --git a/samples/OpenSlideSharp.Viewer/App.axaml.cs b/samples/OpenSlideSharp.Viewer/App.axaml.cs index 01ed888..f61f350 100644 --- a/samples/OpenSlideSharp.Viewer/App.axaml.cs +++ b/samples/OpenSlideSharp.Viewer/App.axaml.cs @@ -1,11 +1,13 @@ using Avalonia; -using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; namespace OpenSlideSharp.Viewer; -/// The Avalonia application: the Fluent theme (App.axaml) and the main window. +/// +/// The Avalonia application: the Fluent theme (App.axaml) and the main window, which opens the slide given as the +/// first command-line argument. +/// public partial class App : Application { public override void Initialize() @@ -17,8 +19,13 @@ public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { - // Placeholder until the main window exists. - desktop.MainWindow = new Window { Title = "OpenSlide Viewer", Width = 1024, Height = 768 }; + var window = new MainWindow(); + desktop.MainWindow = window; + if (desktop.Args is [string path, ..]) + { + // A slide that cannot be opened is reported in the window, not thrown. + _ = window.OpenAsync(path); + } } base.OnFrameworkInitializationCompleted(); diff --git a/samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml b/samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml new file mode 100644 index 0000000..5354f86 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml @@ -0,0 +1,10 @@ + + + + diff --git a/samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml.cs b/samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml.cs new file mode 100644 index 0000000..ab2a849 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml.cs @@ -0,0 +1,48 @@ +using System; +using Avalonia.Controls; +using Avalonia.Media.Imaging; +using OpenSlideSharp.Viewer.Controls; + +namespace OpenSlideSharp.Viewer; + +/// +/// Shows one associated image of a slide (its label, macro or thumbnail image), scaled to the window with its +/// aspect ratio kept. The window holds a copy of the pixels, so it outlives the slide. +/// +internal sealed partial class AssociatedImageWindow : Window +{ + // The window starts at the image's size, within these limits. + private const double MinStartWidth = 240; + private const double MinStartHeight = 180; + private const double MaxStartWidth = 1024; + private const double MaxStartHeight = 768; + + /// For the designer. + public AssociatedImageWindow() + { + InitializeComponent(); + } + + /// Shows , as read by , titled . + public AssociatedImageWindow(string name, PixelImage image) + : this() + { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(image); + Title = name; + Image = image.ToBitmap(); + Picture.Source = Image; + Width = Math.Clamp(image.Width, MinStartWidth, MaxStartWidth); + Height = Math.Clamp(image.Height, MinStartHeight, MaxStartHeight); + } + + /// Gets the image shown; null for an image without pixels. + internal WriteableBitmap? Image { get; } + + protected override void OnClosed(EventArgs e) + { + base.OnClosed(e); + Picture.Source = null; + Image?.Dispose(); + } +} diff --git a/samples/OpenSlideSharp.Viewer/Controls/Navigator.cs b/samples/OpenSlideSharp.Viewer/Controls/Navigator.cs new file mode 100644 index 0000000..620a001 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Controls/Navigator.cs @@ -0,0 +1,192 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Media.Immutable; +using OpenSlideSharp.Viewer.Core; + +namespace OpenSlideSharp.Viewer.Controls; + +/// +/// A small picture of the whole slide with the part the main view shows outlined; clicking or dragging on it +/// centres the view there. +/// +/// +/// The slide is drawn at its own aspect ratio, as wide as the control may be and at most +/// high (scaled up for a slide smaller than that), from the thumbnail if there is one and as a plain area if not. +/// Coordinates map linearly between that area and level 0, so a thumbnail whose rounded size differs slightly from +/// the slide's ratio is stretched to fit rather than shifting the outline. +/// +internal sealed class Navigator : Control +{ + /// The largest height (and, with no width given, width) the slide is drawn at, in logical pixels. + public const double MaxImageHeight = 256; + + /// The colour of the outline of the view. + public static readonly Color ViewColor = Color.FromRgb(0x00, 0xA0, 0xFF); + + private static readonly ImmutablePen ViewPen = new(new ImmutableSolidColorBrush(ViewColor), 2); + private static readonly ImmutableSolidColorBrush NoThumbnailBrush = new(Color.FromArgb(0x30, 0x80, 0x80, 0x80)); + + private SlideSize _slideSize; + private Viewport? _viewport; + private bool _dragging; + + public Navigator() + { + ClipToBounds = true; + Cursor = new Cursor(StandardCursorType.Hand); + } + + /// Gets the picture of the slide, or null if there is none (or no slide). + public Bitmap? Thumbnail { get; private set; } + + /// + /// Gets where the slide is drawn, in this control's coordinates: as large as fits, centred; empty without a + /// slide. (Measured to the slide's aspect ratio, the control is normally just that size.) + /// + internal Rect ImageRect + { + get + { + Size bounds = Bounds.Size; + double scale = _slideSize.Width > 0 && _slideSize.Height > 0 + ? Math.Min(bounds.Width / _slideSize.Width, bounds.Height / _slideSize.Height) + : 0; + if (!(scale > 0)) + { + return default; + } + + double width = _slideSize.Width * scale; + double height = _slideSize.Height * scale; + return new Rect((bounds.Width - width) / 2, (bounds.Height - height) / 2, width, height); + } + } + + /// + /// Shows a slide of level-0 pixels, its thumbnail (or none) and the view's + /// ; a null viewport shows nothing. The navigator does not dispose the thumbnail. + /// + public void Show(SlideSize slideSize, Bitmap? thumbnail, Viewport? viewport) + { + if (_viewport is not null) + { + _viewport.Changed -= InvalidateVisual; + } + + _viewport = viewport; + _slideSize = viewport is null ? default : slideSize; + Thumbnail = viewport is null ? null : thumbnail; + _dragging = false; + if (_viewport is not null) + { + _viewport.Changed += InvalidateVisual; + } + + InvalidateMeasure(); + InvalidateVisual(); + } + + public override void Render(DrawingContext context) + { + Rect image = ImageRect; + if (_viewport is not { } viewport || image.Width <= 0 || image.Height <= 0) + { + return; + } + + if (Thumbnail is { } thumbnail) + { + using (context.PushRenderOptions(new RenderOptions { BitmapInterpolationMode = BitmapInterpolationMode.HighQuality })) + { + context.DrawImage(thumbnail, new Rect(thumbnail.Size), image); + } + } + else + { + context.FillRectangle(NoThumbnailBrush, image); + } + + // The level-0 rectangle the view shows; the part outside the slide is clipped away. + (double left0, double top0) = viewport.ScreenToSlide(0, 0); + (double right0, double bottom0) = viewport.ScreenToSlide(viewport.ViewWidth, viewport.ViewHeight); + Point topLeft = ToNavigator(image, left0, top0); + Point bottomRight = ToNavigator(image, right0, bottom0); + context.DrawRectangle(null, ViewPen, new Rect(topLeft, bottomRight)); + } + + protected override Size MeasureOverride(Size availableSize) + { + if (_slideSize.Width <= 0 || _slideSize.Height <= 0) + { + return default; + } + + // As wide as allowed and at most MaxImageHeight high, keeping the slide's aspect ratio. + double maxWidth = double.IsFinite(availableSize.Width) ? availableSize.Width : MaxImageHeight; + double maxHeight = Math.Min(MaxImageHeight, availableSize.Height); + double scale = Math.Min(maxWidth / _slideSize.Width, maxHeight / _slideSize.Height); + return scale > 0 ? new Size(_slideSize.Width * scale, _slideSize.Height * scale) : default; + } + + protected override void OnPointerPressed(PointerPressedEventArgs e) + { + base.OnPointerPressed(e); + PointerPoint point = e.GetCurrentPoint(this); + if (point.Properties.PointerUpdateKind != PointerUpdateKind.LeftButtonPressed || _viewport is null) + { + return; + } + + _dragging = true; + e.Pointer.Capture(this); + CenterViewOn(point.Position); + e.Handled = true; + } + + protected override void OnPointerMoved(PointerEventArgs e) + { + base.OnPointerMoved(e); + if (_dragging) + { + CenterViewOn(e.GetPosition(this)); + } + } + + protected override void OnPointerReleased(PointerReleasedEventArgs e) + { + base.OnPointerReleased(e); + if (_dragging && e.InitialPressMouseButton == MouseButton.Left) + { + _dragging = false; + e.Pointer.Capture(null); + e.Handled = true; + } + } + + protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) + { + base.OnPointerCaptureLost(e); + _dragging = false; + } + + private Point ToNavigator(Rect image, double x0, double y0) => + new(image.X + (x0 * image.Width / _slideSize.Width), image.Y + (y0 * image.Height / _slideSize.Height)); + + // Centres the view on the slide point under the given point of the navigator, kept on the slide. + private void CenterViewOn(Point position) + { + Rect image = ImageRect; + if (_viewport is not { } viewport || image.Width <= 0 || image.Height <= 0) + { + return; + } + + double x0 = (position.X - image.X) * _slideSize.Width / image.Width; + double y0 = (position.Y - image.Y) * _slideSize.Height / image.Height; + viewport.CenterOn(Math.Clamp(x0, 0, _slideSize.Width), Math.Clamp(y0, 0, _slideSize.Height)); + } +} diff --git a/samples/OpenSlideSharp.Viewer/Controls/PixelImageExtensions.cs b/samples/OpenSlideSharp.Viewer/Controls/PixelImageExtensions.cs new file mode 100644 index 0000000..2e360c1 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Controls/PixelImageExtensions.cs @@ -0,0 +1,39 @@ +using System; +using System.Runtime.InteropServices; +using Avalonia; +using Avalonia.Media.Imaging; +using Avalonia.Platform; + +namespace OpenSlideSharp.Viewer.Controls; + +internal static class PixelImageExtensions +{ + /// + /// Copies the image into a new bitmap with the same pixels (both are B, G, R, A in memory), or returns null for + /// an image without pixels. Call on the UI thread. + /// + public static WriteableBitmap? ToBitmap(this PixelImage image) + { + ArgumentNullException.ThrowIfNull(image); + if (image.Width == 0 || image.Height == 0) + { + return null; + } + + AlphaFormat alpha = image.Format switch + { + OpenSlideSharp.PixelFormat.Bgra32Premultiplied => AlphaFormat.Premul, + OpenSlideSharp.PixelFormat.Bgra32 => AlphaFormat.Unpremul, + _ => AlphaFormat.Opaque, + }; + var bitmap = new WriteableBitmap( + new PixelSize(image.Width, image.Height), new Vector(96, 96), Avalonia.Platform.PixelFormat.Bgra8888, alpha); + using ILockedFramebuffer buffer = bitmap.Lock(); + for (int y = 0; y < image.Height; y++) + { + Marshal.Copy(image.Data, y * image.Stride, buffer.Address + (y * buffer.RowBytes), image.Stride); + } + + return bitmap; + } +} diff --git a/samples/OpenSlideSharp.Viewer/MainWindow.axaml b/samples/OpenSlideSharp.Viewer/MainWindow.axaml new file mode 100644 index 0000000..7591a95 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/MainWindow.axaml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +