diff --git a/Directory.Packages.props b/Directory.Packages.props index 26bc3d1..54bc149 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,6 +9,14 @@ + + + + + + + + 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/README.md b/README.md index 64b58c4..980a583 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,17 @@ dotnet run -c Release --project samples/OpenSlideSharp.Web -- /path/to/slide.svs Then open . Give an absolute path: under `dotnet run` the working directory is the project directory. +## Desktop viewer + +[`samples/OpenSlideSharp.Viewer`](samples/OpenSlideSharp.Viewer/README.md) is an Avalonia viewer for Windows, Linux and macOS, like openslide-java's demo viewer. From a checkout: + +```sh +pwsh eng/Get-OpenSlide.ps1 +dotnet run -c Release --project samples/OpenSlideSharp.Viewer -- /path/to/slide.svs # or File → Open, or drop a file +``` + +Its README lists the shortcuts, the `--check` mode and the self-contained publish. + ## Known issues On Windows, corrupt JPEG or PNG data in a slide terminates the whole process with `0xC0000409`, and the failure cannot be caught. Services that open untrusted slides on Windows should decode them in a separate worker process. See [the details](docs/known-issues/windows-cfg-longjmp-crash.md). diff --git a/docs/notes/2026-11-18-plan4-carryover.md b/docs/notes/2026-11-18-plan4-carryover.md new file mode 100644 index 0000000..57b2178 --- /dev/null +++ b/docs/notes/2026-11-18-plan4-carryover.md @@ -0,0 +1,57 @@ +# 计划 4 遗留事项(供计划 5 及以后使用) + +来源:计划 4(Avalonia 桌面查看器)各任务审阅、整体终审及其修复轮。下列事项都已评估为**不阻塞计划 4 合并**。 + +## 计划 5(发布)之前必须处理 + +- **发布物形态。** + - 查看器的发布目录包含单文件可执行程序和 `licenses/`。`licenses/` 下有三部分: + - openslide-bin 的许可证与 `VERSIONS.md`; + - `THIRD-PARTY-NOTICES.txt`; + - `SOURCE.md`。 + - 每个 RID(win-x64、linux-x64、osx-arm64)把整个目录打成一个 zip 或 tar.gz 附到 GitHub Release,不能只附可执行文件。 +- **`THIRD-PARTY-NOTICES.txt` 中 MicroCom.Runtime 与 Tmds.DBus.Protocol 只写了 “MIT. Copyright …”。** 发布前补上 MIT 许可全文,或注明下方的 MIT 文本同样适用于这两项。 +- **`SOURCE.md` 只给出了 openslide-bin 源码包的 URL 模式。** runtime 包没有记录确切的 openslide-bin 版本。计划 5 的发布流程要把版本写进 runtime 包(或发布目录),并在 `SOURCE.md` 中给出确切链接。 +- **macOS:** 二进制没有签名和公证,Gatekeeper 会拦截。需要选择一种处理方式: + - 在 Release 说明里写明 `xattr -d com.apple.quarantine <文件>` 的绕过方法; + - 或者在 CI 中签名并公证,这需要维护者提供 Apple 开发者证书。 +- **查看器 README 里的发布构建写的是 “planned”。** 发布流程上线后要更新这一段。 + +## 查看器(低优先级,可继续延后) + +- **渲染与加载:** + - 层级选择没有滞回。可见瓦片数随平移对齐变化(c×r 与 (c+1)×(r+1)),在临界缩放区间平移时,层级会在 L 与 L+1 之间来回切换。可以改用与对齐无关的上界,或加入滞回。 + - Bitmap 构造持续失败(例如持续 OOM)时,会无限地“读取 → 失败 → 移除 → 再读取”,没有退避。 + - 单层、超过 16 Mi 像素、又没有 `thumbnail` 关联图像的切片没有底图,适配窗口时只显示中心附近的瓦片。 + - 每次平移移动会触发两次 `ViewChanged`。 +- **窗口:** + - 如果 `Show()` 在视图已经接受新切片之后才失败(极少见,例如 OOM),状态栏会报错,但视图已在显示新切片,标题和属性却还是旧的。 + - 导航器拖动没有区分指针身份。 + - 很长的错误文本会挤占状态栏其他段。 + - 文件选择器只用了 `Patterns`,macOS 上没有 UTI 过滤。 + - 选区列表每次变化都整体重建,选中状态会丢失。 + - `--check` 在 Windows 上附加父控制台后,没有重新绑定 `Console.Error`。 +- **视口:** + - `Resize(0,0)` 会重新钳制缩放,导致缩放状态丢失。 + - 文档中 “永不为 NaN” 的说法过强:有限但极大的输入会让中心变成 ∞。 +- **测试:** + - 没有测试锁定 “Bitmap 构造时会复制像素” 这一点(应在复制后改写缓冲区再断言)。 + - `ConsumePixels` 的文档措辞不准确。 + - RapidZoom 测试只比较数量。 + - 打开失败的测试没有断言关联图像、导航器和选区保持不变。 + - 窗口级的 “无 mpp” 路径只在 `StatusFormatter` 中有单元测试。 + +## 计划 4 中做出的裁定(摘要) + +- **R1**:范围按规格 §6.7,只做矩形选区和单切片;不做自由手绘、椭圆选区和双切片联动。 +- **R2**:Task 1 的三个后续问题(偶发失败的测试、回调异常保护、位图释放与缓冲池)并入 Task 2 处理。 +- **R3**:按设备像素的 downsample 选择层级,以保证高 DPI 下清晰。 +- **R4**:先请求粗层瓦片,实现“先显示低分辨率”;加载失败的标记按切片保存;拖动只跟随按下它的那个指针。 +- **R5**:Windows 下 `--check` 附加父控制台输出。 +- **R6**:目标层可见瓦片的字节数控制在缓存预算的一半以内,按离中心距离截断请求,并用导航缩略图作底图,保证加载一定能结束。 +- **R7**:发布目录附带 `licenses/`。替换原生库的方式是设置 `OPENSLIDE_LIBRARY_PATH`。 +- **R8**:切换或关闭切片时不阻塞 UI 线程,依赖核心库的 SafeHandle 租约保证安全。 + +## 已知问题(维护者决定只写文档) + +Windows 上遇到损坏的 JPEG/PNG 会触发 CFG/longjmp 崩溃,查看器进程同样会被终止,详见 `docs/known-issues/windows-cfg-longjmp-crash.md`。 diff --git a/docs/plans/2026-11-17-openslidesharp-v4-roadmap.md b/docs/plans/2026-11-17-openslidesharp-v4-roadmap.md index 8433da1..b54279c 100644 --- a/docs/plans/2026-11-17-openslidesharp-v4-roadmap.md +++ b/docs/plans/2026-11-17-openslidesharp-v4-roadmap.md @@ -9,7 +9,7 @@ | 1 | `2026-11-17-plan1-core-binding-runtime.md`(已完成) | 仓库重置、上游清单与下载脚本、ClangSharp 生成、核心 `OpenSlide` API、原生库加载、`OpenSlideSharp.runtime`(.NET + VS C++)、基础 CI(§5、§6.1 绑定部分、§6.2、§7.1、§8 前半) | — | | 2 | `2026-11-17-plan2-rendering.md`(已完成) | `PixelImage` 合成与缩放、共享渲染流程、`OpenSlide.GetThumbnail`、`DeepZoomGenerator`、`IColorTransform`、`OmeZarrGenerator`、`OpenSlideSharp.SkiaSharp`(§6.1 其余、§6.3、§8 中 DeepZoom / Skia / OME-Zarr) | 1 | | 3 | `2026-11-18-plan3-web-tool.md`(已完成) | `OpenSlideSharp.AspNetCore`、`samples/OpenSlideSharp.Web`、`OpenSlideSharp.Tool`(§6.4–§6.6) | 2 | -| 4 | plan4-viewer(待写) | `samples/OpenSlideSharp.Viewer`(Avalonia)(§6.7) | 2 | +| 4 | `2026-11-18-plan4-viewer.md`(已完成) | `samples/OpenSlideSharp.Viewer`(Avalonia)(§6.7) | 2 | | 5 | plan5-release(待写) | 上游同步、版本号计算、发布、GitHub Release、README 重写、旧包弃用清单(§7.2、§7.3、§9) | 1–4 | 计划 3 与计划 4 互不依赖,可以并行。 diff --git a/docs/plans/2026-11-18-plan3-web-tool.md b/docs/plans/2026-11-18-plan3-web-tool.md index cd09ce8..4be3ef2 100644 --- a/docs/plans/2026-11-18-plan3-web-tool.md +++ b/docs/plans/2026-11-18-plan3-web-tool.md @@ -549,7 +549,7 @@ git add -A && git commit -m "feat: add the openslide-sharp tool with deepzoom an Run: `pwsh eng/Get-OpenSlide.ps1 -Platform all; pwsh eng/Test-Packages.ps1` Expected: `All package smoke tests passed.` -- [ ] **Step 2: 扩展 `verify-omezarr.py` 与 CI job,本机按 CI 步骤跑一遍 Python 校验**(venv 放在 scratchpad) +- [ ] **Step 2: 扩展 `verify-omezarr.py` 与 CI job,本机按 CI 步骤跑一遍 Python 校验**(venv 放在临时目录) - [ ] **Step 3: 更新文档** - [ ] **Step 4: 运行全部测试,提交** 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..03a5703 --- /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`,用截图确认窗口正常显示,然后关闭。在报告里附上截图的保存路径(放在临时目录中)。 +- [ ] **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" +``` diff --git a/eng/Test-Packages.ps1 b/eng/Test-Packages.ps1 index 79eaf98..fd19200 100644 --- a/eng/Test-Packages.ps1 +++ b/eng/Test-Packages.ps1 @@ -2,8 +2,9 @@ <# Packs OpenSlideSharp, OpenSlideSharp.SkiaSharp, OpenSlideSharp.runtime, OpenSlideSharp.AspNetCore and the OpenSlideSharp.Tool .NET tool into artifacts/smoke-feed and proves the nupkgs work for real consumers (net10.0, -an ASP.NET Core app, net48 x64 and AnyCPU, no-runtime, the installed tool and a Visual Studio C++ project), plus the -32-bit build warning. +an ASP.NET Core app, net48 x64 and AnyCPU, no-runtime, the installed tool, the desktop viewer published +self-contained as one executable with its licenses for this machine's RID, and a Visual Studio C++ project), plus +the 32-bit build warning. -SkipPack reuses the nupkgs already in artifacts/smoke-feed (CI downloads them there) instead of packing; everything else, including the nupkg content @@ -301,7 +302,66 @@ finally { Remove-Item $toolTemp -Recurse -Force -ErrorAction SilentlyContinue } -# 6. Native C++ consumer (Visual Studio vcxproj via packages.config), Windows only. +# 6. The desktop viewer, published the way its releases will be: self-contained, one executable and its licenses, for +# this machine's RID, with the native OpenSlide library from the runtime package in the feed. --check reads the slide +# without a window. +Write-Host '== smoke: viewer (self-contained single file)' +$hostArch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture +# Picked the way eng/Get-OpenSlide.ps1 picks this machine's binaries. +$viewerRid = if ($IsWindows -and $hostArch -eq 'X64') { 'win-x64' } +elseif ($IsLinux -and $hostArch -eq 'X64') { 'linux-x64' } +elseif ($IsLinux -and $hostArch -eq 'Arm64') { 'linux-arm64' } +elseif ($IsMacOS -and $hostArch -eq 'Arm64') { 'osx-arm64' } +elseif ($IsMacOS -and $hostArch -eq 'X64') { 'osx-x64' } +else { throw "[viewer] OpenSlide publishes no binaries for this platform ($hostArch)" } +$viewerOut = Join-Path $artifacts 'smoke/viewer' +Invoke-Native dotnet @('publish', (Join-Path $root 'samples/OpenSlideSharp.Viewer'), '-c', 'Release', '-r', $viewerRid, '--self-contained', + '-p:PublishSingleFile=true', '-p:UseOpenSlideRuntimePackage=true', "-p:OpenSlideSharpVersion=$Version", + "-p:RestoreAdditionalProjectSources=$feed", '--artifacts-path', $viewerOut) +$viewerPublish = Join-Path $viewerOut "publish/OpenSlideSharp.Viewer/release_$viewerRid" +$viewerName = $IsWindows ? 'OpenSlideSharp.Viewer.exe' : 'OpenSlideSharp.Viewer' +# The publish folder is exactly what a release archives: the executable, with the native libraries inside it, and +# licenses/ with the notices of what it contains. +$published = @(Get-ChildItem $viewerPublish -Recurse -File | ForEach-Object { + [pscustomobject]@{ Path = [IO.Path]::GetRelativePath($viewerPublish, $_.FullName) -replace '\\', '/'; Length = $_.Length } + }) +$published | ForEach-Object { Write-Host ("published: {0} ({1:N1} KB)" -f $_.Path, ($_.Length / 1KB)) } +$paths = @($published | ForEach-Object Path) +$unexpected = @($paths | Where-Object { $_ -ne $viewerName -and -not $_.StartsWith('licenses/') }) +if ($paths -notcontains $viewerName -or $unexpected.Count -gt 0) { + throw "[viewer] expected $viewerName and licenses/ in $viewerPublish, found: $($paths -join ', ')" +} +foreach ($required in 'licenses/THIRD-PARTY-NOTICES.txt', 'licenses/SOURCE.md', 'licenses/openslide-bin/VERSIONS.md') { + if ($paths -notcontains $required) { throw "[viewer] $required is not in $viewerPublish" } +} +# The license texts of OpenSlide and of the libraries linked into it, from the runtime package. +if (-not ($paths | Where-Object { $_ -like 'licenses/openslide-bin/OpenSlide/*' })) { throw "[viewer] OpenSlide's license is not in licenses/openslide-bin/" } +$binLicenses = @($paths | Where-Object { $_ -like 'licenses/openslide-bin/*/*' }) +Write-Host "licenses/openslide-bin: $($binLicenses.Count) license files" +# The bundle extracts its native libraries when it starts; a fresh extraction directory shows they came from it. +$viewerExtract = Join-Path $viewerOut 'extract' +$env:DOTNET_BUNDLE_EXTRACT_BASE_DIR = $viewerExtract +try { + # Piped, so that PowerShell waits for the viewer, a GUI program on Windows, and captures what it prints. + $output = & (Join-Path $viewerPublish $viewerName) --check $fixture 2>&1 | Out-String + $code = $LASTEXITCODE +} +finally { + Remove-Item Env:DOTNET_BUNDLE_EXTRACT_BASE_DIR -ErrorAction SilentlyContinue +} +Write-Host $output +if ($code -ne 0) { throw "[viewer] --check exited with code $code, expected 0" } +foreach ($line in 'openslide=4.', 'slide=16x16') { + if ($output -notmatch [regex]::Escape($line)) { throw "[viewer] --check output does not contain '$line'" } +} +$extracted = @(Get-ChildItem $viewerExtract -Recurse -File | ForEach-Object { $_.Name }) +$extracted | ForEach-Object { Write-Host "extracted: $_" } +foreach ($lib in 'libopenslide-1', 'libSkiaSharp', 'libHarfBuzzSharp') { + if (-not ($extracted | Where-Object { [IO.Path]::GetFileNameWithoutExtension($_) -eq $lib })) { throw "[viewer] $lib is not in the bundle" } +} +Write-Host "PASS: viewer ($viewerRid)" + +# 7. Native C++ consumer (Visual Studio vcxproj via packages.config), Windows only. if ($IsWindows) { $cppProj = Join-Path $root 'test/NativeCppSmoke' $nuget = Join-Path $artifacts 'tools/nuget.exe' 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..f61f350 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/App.axaml.cs @@ -0,0 +1,33 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; + +namespace OpenSlideSharp.Viewer; + +/// +/// 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() + { + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + 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..3954822 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/AssociatedImageWindow.axaml.cs @@ -0,0 +1,52 @@ +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); + ImageName = name; + Title = name; + Image = image.ToBitmap(); + Picture.Source = Image; + Width = Math.Clamp(image.Width, MinStartWidth, MaxStartWidth); + Height = Math.Clamp(image.Height, MinStartHeight, MaxStartHeight); + } + + /// Gets the name of the associated image shown; empty in the designer. + internal string ImageName { get; } = ""; + + /// 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/Controls/SlideView.cs b/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs new file mode 100644 index 0000000..5d6c6d4 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Controls/SlideView.cs @@ -0,0 +1,965 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Diagnostics; +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. 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. +/// +/// +/// A frame draws from, and asks for, at most tiles of its level, half the cache, so that +/// loading always comes to an end instead of evicting tiles in view to make room for others. When the level that +/// suits the zoom has more tiles in view (with their stand-ins), a coarser one is drawn, scaled up. When even the +/// coarsest level has more (a slide with one large level, zoomed out), the frame draws the tiles nearest the centre +/// of the view, over the stretched across the slide. +/// +/// +/// Setting builds a new viewport and loading pipeline (tile cache, bitmap cache and loader), and +/// disposes the old ones without waiting for the old slide's reads in flight (see ). 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 (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; + + // The size of a whole tile in the cache budget. + private const long TileBytes = (long)TileGrid.TileSize * TileGrid.TileSize * 4; + + 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 _visible = new(); + 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; + private IBrush _background = Brushes.White; + private Bitmap? _thumbnail; + private bool _attached; + private Point? _pointer; + private DragMode _drag; + private IPointer? _dragPointer; + private Point _dragFrom; + private (double X, double Y) _selectionStart; + private Selection? _selectionBeingDrawn; + private (double Scaling, ImmutablePen Solid, ImmutablePen Dashed)? _pens; + 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, + /// even after leaving the visual tree and coming back, until is set again. + /// + 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 => _slideState?.Reads ?? 0; + + /// + /// 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 a picture of the whole slide, such as the navigator's thumbnail, drawn stretched under the tiles of + /// a slide whose coarsest level has more tiles than . The view does not dispose it, and + /// setting clears it. + /// + public Bitmap? Thumbnail + { + get => _thumbnail; + set + { + _thumbnail = value; + InvalidateVisual(); + } + } + + /// Gets or sets the tile cache budget, taken when the loading pipeline is built. + internal long CacheBudgetBytes { get; set; } = TileCache.DefaultBudgetBytes; + + /// + /// Gets the most tiles a frame draws from, and asks for, at the level it draws: half the cache budget in + /// tiles (at least 1), so that they and their coarse stand-ins always fit in the + /// cache together. + /// + internal int TileLimit => (int)Math.Clamp(CacheBudgetBytes / (2L * TileBytes), 1, int.MaxValue); + + /// + /// Gets or sets the level sizes and downsamples to use instead of the slide's, taken when is + /// set; a test hook. + /// + internal (SlideSize[] Dimensions, double[] Downsamples)? LevelLayout { get; set; } + + /// Gets or sets what builds a tile's bitmap, taken when the loading pipeline is built; a test hook. + internal Func? BitmapFactory { get; set; } + + /// + /// Gets or sets the most tiles a frame has asked the loader for since the slide was set, or since a test set it + /// to 0. + /// + internal int MostRequestedTiles { get; set; } + + /// 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; } + + 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 (, ), + /// then by row and column. + /// + internal static void SortCenterFirst(List keys, TileGrid grid, double x0, double y0) => + keys.Sort((a, b) => Order(grid, a, x0, y0).CompareTo(Order(grid, b, x0, y0))); + + /// + /// Replaces the contents of with the tiles of that overlap the + /// level-0 rectangle and whose centres are nearest the level-0 point (, ): + /// at most , in the order of . The work is in proportion to + /// and the number of rows, however many tiles overlap the rectangle. + /// + /// The number of tiles that overlap the rectangle. + internal static long NearestTiles( + TileGrid grid, + int level, + (double Left, double Top, double Right, double Bottom) area0, + double x0, + double y0, + int max, + List nearest) + { + nearest.Clear(); + if (grid.VisibleRange(level, area0.Left, area0.Top, area0.Right, area0.Bottom) is not { } range) + { + return 0; + } + + long count = (range.LastColumn - range.FirstColumn + 1) * (range.LastRow - range.FirstRow + 1); + if (count <= max) + { + for (long row = range.FirstRow; row <= range.LastRow; row++) + { + for (long column = range.FirstColumn; column <= range.LastColumn; column++) + { + nearest.Add(new TileKey(level, column, row)); + } + } + + SortCenterFirst(nearest, grid, x0, y0); + return count; + } + + // Too many to sort: merge the rows instead. Within a row the distance falls towards the column nearest x0 and + // rises past it, so each row is two runs in order, one going left from that column and one going right from + // the next; the queue holds the next tile of every run and hands out the nearest one. + long start = Math.Clamp( + (long)Math.Floor(x0 / grid.LevelDownsample(level) / TileGrid.TileSize), range.FirstColumn, range.LastColumn); + // Its neighbour may be nearer; on a tie, the left one goes first, as in SortCenterFirst. + long first = start; + for (long column = Math.Max(start - 1, range.FirstColumn); column <= Math.Min(start + 1, range.LastColumn); column++) + { + if (Order(grid, new TileKey(level, column, range.FirstRow), x0, y0).CompareTo( + Order(grid, new TileKey(level, first, range.FirstRow), x0, y0)) < 0) + { + first = column; + } + } + + var runs = new PriorityQueue<(TileKey Key, int Step), (double, long, long)>((int)Math.Min(2 * (range.LastRow - range.FirstRow + 1), 1 << 16)); + for (long row = range.FirstRow; row <= range.LastRow; row++) + { + Enqueue(new TileKey(level, first, row), -1); + if (first < range.LastColumn) + { + Enqueue(new TileKey(level, first + 1, row), 1); + } + } + + while (nearest.Count < max && runs.TryDequeue(out (TileKey Key, int Step) run, out _)) + { + nearest.Add(run.Key); + long next = run.Key.Column + run.Step; + if (next >= range.FirstColumn && next <= range.LastColumn) + { + Enqueue(run.Key with { Column = next }, run.Step); + } + } + + return count; + + void Enqueue(TileKey key, int step) => runs.Enqueue((key, step), Order(grid, key, x0, y0)); + } + + 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; + // 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); + e.Handled = true; + } + + protected override void OnPointerMoved(PointerEventArgs e) + { + base.OnPointerMoved(e); + Point position = e.GetPosition(this); + _pointer = position; + if (_viewport is { } viewport && e.Pointer == _dragPointer) + { + 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 (_drag == DragMode.None || e.Pointer != _dragPointer || e.InitialPressMouseButton != MouseButton.Left) + { + 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); + if (e.Pointer == _dragPointer) + { + 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; + + // Where a tile comes in centre-first order: the squared distance of its centre from the level-0 point, then its + // row and column. + private static (double Distance, long Row, long Column) Order(TileGrid grid, TileKey key, double x0, double y0) + { + (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), key.Row, key.Column); + } + + // The number of tiles a frame drawing level would ask for at most, with their coarse stand-ins (see DrawTiles). + private static long TilesNeeded(TileGrid grid, int level, (double Left, double Top, double Right, double Bottom) area0) + { + int coarseLevel = Math.Min(level + CoarseLevelStep, grid.LevelCount - 1); + long tiles = grid.VisibleCount(level, area0.Left, area0.Top, area0.Right, area0.Bottom); + return coarseLevel > level + ? tiles + grid.VisibleCount(coarseLevel, area0.Left, area0.Top, area0.Right, area0.Bottom) + : tiles; + } + + // 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) + { + IReadOnlyList dimensions = slide.LevelDimensions; + IReadOnlyList downsamples = slide.LevelDownsamples; + if (LevelLayout is { } layout) + { + (dimensions, downsamples) = (layout.Dimensions, layout.Downsamples); + } + + grid = new TileGrid(dimensions, downsamples); + viewport = new Viewport(dimensions.Count > 0 ? dimensions[0] : default, downsamples); + background = new ImmutableSolidColorBrush(BackgroundColor(slide.Properties)); + } + + ClosePipeline(); + if (_viewport is not null) + { + _viewport.Changed -= OnViewportChanged; + } + + _slide = slide; + _slideState = slide is null ? null : new SlideState(); + _grid = grid; + _viewport = viewport; + _background = background; + _thumbnail = null; // it pictured the old slide + MostRequestedTiles = 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 || _slideState is not { } state + || _grid is not { } grid) + { + return; + } + + Func read = TileReader ?? ReadTile; + var cache = new TileCache(CacheBudgetBytes); + var loader = new TileLoader( + key => + { + state.CountRead(); + return read(slide, grid, key); + }, + cache, + LoaderThreads, + _ => ScheduleRedraw()) + { + // Disposing the pipeline (a new slide, File > Close, closing the window) does not wait for the reads in + // flight, which can take seconds on a slow disk or network share: the UI thread must not freeze. A read + // that outlives the pipeline is harmless: + // - its native call holds a lease on the slide's handle (OpenSlideHandle), so disposing the slide meanwhile + // defers openslide_close until the call returns, and a read that starts after it throws + // ObjectDisposedException, which the disposed loader swallows (no Failed event); + // - the loader drops a tile read after it was disposed, and the cache disposes a tile added after it was + // disposed, so the pixels go back to the pool and nothing reaches the next slide's cache or bitmaps; + // - the callbacks only post a redraw, or check that their SlideState is still the current one, and count + // reads in that SlideState, not in the next slide's. + DisposeTimeout = TimeSpan.Zero, + }; + var pipeline = new Pipeline(grid, TileLimit, cache, new TileBitmapCache(BitmapFactory), loader); + loader.Failed += error => + { + // 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(() => + { + if (ReferenceEquals(state, _slideState) && !state.Reported) + { + state.Reported = true; + 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; + if (grid.LevelCount == 0) + { + return; + } + + (double left0, double top0) = viewport.ScreenToSlide(0, 0); + (double right0, double bottom0) = viewport.ScreenToSlide(viewport.ViewWidth, viewport.ViewHeight); + var view0 = (left0, top0, right0, bottom0); + + // The level that suits the zoom, unless its tiles in view and their coarse stand-ins would take more than half + // the cache (a 4:1 pyramid on a high-DPI screen, say): they would then evict each other and be read again + // without end. A coarser level is drawn instead, scaled up. + int level = grid.BestLevelForDownsample(viewport.Downsample / scaling); + while (level < grid.LevelCount - 1 && TilesNeeded(grid, level, view0) > pipeline.TileLimit) + { + level++; + } + + TargetLevel = level; + using (context.PushRenderOptions(new RenderOptions { BitmapInterpolationMode = BitmapInterpolationMode.HighQuality })) + { + if (pipeline.DrawsThumbnail) + { + DrawThumbnail(context, grid, viewport, scaling, view0); + } + + DrawLevel(context, pipeline, viewport, scaling, level, view0); + } + + if (_slideState is { Failed: true }) + { + return; // reading this slide failed: no more requests for it + } + + SortCenterFirst(_coarse, grid, viewport.CenterX, viewport.CenterY); + _coarse.AddRange(_missing); // already centre first + MostRequestedTiles = Math.Max(MostRequestedTiles, _coarse.Count); + pipeline.Loader.Request(_coarse); // also drops what earlier frames queued and this one no longer needs + } + + // Draws the tiles of level in view or, on a slide whose coarsest level has more tiles than the pipeline's limit + // (a single large level, say), as many as the limit allows, those nearest the centre; the thumbnail stands in + // for the rest. Lists the missing tiles, centre first, in _missing, and the coarse tiles to read before them in + // _coarse. + private void DrawLevel( + DrawingContext context, + Pipeline pipeline, + Viewport viewport, + double scaling, + int level, + (double Left, double Top, double Right, double Bottom) view0) + { + TileGrid grid = pipeline.Grid; + NearestTiles(grid, level, view0, viewport.CenterX, viewport.CenterY, pipeline.TileLimit, _visible); + + // 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(); + foreach (TileKey key in _visible) + { + 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)); + continue; + } + + _missing.Add(key); + if (!DrawCoarser(context, pipeline, viewport, scaling, key) && coarseLevel > level) + { + (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); + } + } + } + } + } + + // Draws the part of the thumbnail under the view, stretched over the slide. + private void DrawThumbnail( + DrawingContext context, TileGrid grid, Viewport viewport, double scaling, (double Left, double Top, double Right, double Bottom) view0) + { + SlideSize size = grid.LevelSize(0); + if (_thumbnail is not { } thumbnail || size.Width <= 0 || size.Height <= 0) + { + return; + } + + double left = Math.Max(view0.Left, 0); + double top = Math.Max(view0.Top, 0); + double right = Math.Min(view0.Right, size.Width); + double bottom = Math.Min(view0.Bottom, size.Height); + if (!(right > left && bottom > top)) + { + return; + } + + double scaleX = thumbnail.Size.Width / size.Width; + double scaleY = thumbnail.Size.Height / size.Height; + var source = new Rect(left * scaleX, top * scaleY, (right - left) * scaleX, (bottom - top) * scaleY); + context.DrawImage(thumbnail, source, OnScreen(viewport, scaling, left, top, right, bottom)); + } + + /// + /// 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 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(); + bool covered = false; + for (int level = key.Level + 1; level < grid.LevelCount && !covered; level++) + { + 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))); + } + } + + for (int i = _coarser.Count - 1; i >= 0; i--) + { + context.DrawImage(_coarser[i].Bitmap, _coarser[i].Source, _coarser[i].Destination); + } + + return covered; + } + + private static Bitmap? BitmapOf(Pipeline pipeline, TileKey key) + { + if (!pipeline.Cache.TryGet(key, out TileImage? tile) || tile is null) + { + return null; + } + + try + { + return pipeline.Bitmaps.Get(key, tile); + } + catch (Exception e) + { + // No memory for the bitmap, say. The attempt used up the tile's pixels: drop the tile, so that it is + // missing, and read again, rather than blank for as long as it stays cached. + Trace.TraceWarning($"SlideView: cannot make a bitmap of tile {key}: {e.Message}"); + pipeline.Cache.Remove(key, tile); + return 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; + _dragPointer = null; + if (_selectionBeingDrawn is not null) + { + _selectionBeingDrawn = null; + InvalidateVisual(); + } + } + + /// 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; + private long _reads; + + public bool Failed + { + get => _failed; + set => _failed = value; + } + + /// Gets the number of tiles read from the slide (on the loader threads). + public long Reads => Interlocked.Read(ref _reads); + + public void CountRead() => Interlocked.Increment(ref _reads); + + /// 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, int tileLimit, TileCache cache, TileBitmapCache bitmaps, TileLoader loader) + : IDisposable + { + public TileGrid Grid { get; } = grid; + + /// Gets the most tiles a frame draws from, and asks for, at its level (see ). + public int TileLimit { get; } = tileLimit; + + /// + /// Gets whether the slide's coarsest level has more tiles than , so that a frame may draw + /// only some of the tiles in view, and the thumbnail goes under them. + /// + public bool DrawsThumbnail { get; } = grid.LevelCount > 0 && grid.TileCount(grid.LevelCount - 1) > tileLimit; + + public TileCache Cache { get; } = cache; + + public TileBitmapCache Bitmaps { get; } = bitmaps; + + public TileLoader Loader { get; } = loader; + + public void Dispose() + { + // The loader first: it starts no more reads and does not wait for those in flight (DisposeTimeout is 0, + // see OpenPipeline). Disposing the cache then releases the tiles' pixels, and drops the tiles of reads + // still in flight when they arrive. The bitmaps, which only the UI thread touches, 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..2737b52 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Controls/TileBitmapCache.cs @@ -0,0 +1,133 @@ +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(); + private readonly Func _create; + + /// + /// Builds a bitmap from a tile's width, height and pixels; by default . A test hook. + /// + public TileBitmapCache(Func? create = null) + { + _create = create ?? CreateBitmap; + } + + /// 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(); + + /// Copies the first width * height * 4 bytes of into a new bitmap. + internal static Bitmap CreateBitmap(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/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..b6815e9 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileCache.cs @@ -0,0 +1,187 @@ +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 the tile cached under if it is ; a tile that + /// has replaced it stays. + /// + /// Whether the tile was removed. + public bool Remove(TileKey key, TileImage tile) + { + ArgumentNullException.ThrowIfNull(tile); + lock (_lock) + { + if (!_entries.TryGetValue(key, out LinkedListNode? node) || !ReferenceEquals(node.Value.Tile, tile)) + { + return false; + } + + Remove(node); + } + + tile.Dispose(); + return true; + } + + /// 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..9b45206 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileGrid.cs @@ -0,0 +1,175 @@ +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]; + } + } + + 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. + /// + public IEnumerable VisibleTiles(int level, double left0, double top0, double right0, double bottom0) + { + if (VisibleRange(level, left0, top0, right0, bottom0) is not { } range) + { + yield break; + } + + for (long row = range.FirstRow; row <= range.LastRow; row++) + { + for (long column = range.FirstColumn; column <= range.LastColumn; column++) + { + yield return new TileKey(level, column, row); + } + } + } + + /// + /// Returns the first and last column and row (inclusive) of the tiles returns, or null + /// if it returns none. + /// + public (long FirstColumn, long FirstRow, long LastColumn, long LastRow)? VisibleRange( + int level, double left0, double top0, double right0, double bottom0) + { + if (level < 0 || level >= _dimensions.Length) + { + return null; + } + + 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)) + { + return null; + } + + return ( + (long)Math.Floor(left / TileSize), + (long)Math.Floor(top / TileSize), + (long)Math.Ceiling(right / TileSize) - 1, + (long)Math.Ceiling(bottom / TileSize) - 1); + } + + /// Returns the number of tiles returns, without listing them. + public long VisibleCount(int level, double left0, double top0, double right0, double bottom0) => + VisibleRange(level, left0, top0, right0, bottom0) is { } range + ? (range.LastColumn - range.FirstColumn + 1) * (range.LastRow - range.FirstRow + 1) + : 0; + + /// Returns the number of tiles of the whole of . + public long TileCount(int level) + { + SlideSize size = _dimensions[level]; + return ((size.Width + TileSize - 1) / TileSize) * ((size.Height + TileSize - 1) / TileSize); + } + + /// Returns the size of in its own pixels. + public SlideSize LevelSize(int level) => _dimensions[level]; + + /// + /// 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..054788e --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileImage.cs @@ -0,0 +1,104 @@ +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. +/// +/// +/// +/// 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; + + /// 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); + long size = (long)width * height * 4; + if (pixels.Length < size) + { + throw new ArgumentException($"A {width} x {height} tile needs {size} bytes, not {pixels.Length}.", nameof(pixels)); + } + + Width = width; + Height = height; + SizeBytes = size; + _pixels = pixels; + _release = release; + } + + public int Width { get; } + + public int Height { get; } + + /// Gets the size the tile counts for in the cache budget: width * height * 4. + 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; + + /// + /// 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/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..472dcee --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/Core/TileLoader.cs @@ -0,0 +1,274 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +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. +/// +/// +/// 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 with no read in flight no callback starts, and tiles read after it +/// are discarded. A read still in flight past the timeout (0 waits for none) finishes on its own: its tile is +/// discarded, or added to the cache if it beat by a hair (a disposed cache disposes it), and in +/// that case loaded may still run once; a failure is not reported. +/// +/// +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 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); + + /// 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 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); + } + 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}"); + } + } + + private void Fail(Exception e) + { + Action? failed; + lock (_lock) + { + if (_disposed || _failed) + { + return; + } + + _failed = true; + _queue.Clear(); + _queued.Clear(); + failed = Failed; + } + + 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/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/MainWindow.axaml b/samples/OpenSlideSharp.Viewer/MainWindow.axaml new file mode 100644 index 0000000..0fd74b3 --- /dev/null +++ b/samples/OpenSlideSharp.Viewer/MainWindow.axaml @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +