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 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/OpenSlideSharp.Viewer/MainWindow.axaml.cs b/samples/OpenSlideSharp.Viewer/MainWindow.axaml.cs
new file mode 100644
index 0000000..02c66bf
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/MainWindow.axaml.cs
@@ -0,0 +1,601 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Input.Platform;
+using Avalonia.Interactivity;
+using Avalonia.Media.Imaging;
+using Avalonia.Platform.Storage;
+using Avalonia.VisualTree;
+using OpenSlideSharp.Viewer.Controls;
+using OpenSlideSharp.Viewer.Core;
+
+namespace OpenSlideSharp.Viewer;
+
+///
+/// The viewer's window: the slide in a , with a navigator, the slide's properties,
+/// associated images and selections on the left, and the pointer position, zoom and sizes in the status bar.
+///
+///
+/// A slide is opened from the command line (see ), File → Open, or by dropping a file on the
+/// window. A file that cannot be opened is reported in the status bar and the slide shown stays. Opening another
+/// slide, File → Close and closing the window close the slide shown, once the view has let go of it (a read still in
+/// flight keeps the native slide open until it returns). An event handler never lets an exception escape: what goes
+/// wrong is shown in the status bar.
+///
+internal sealed partial class MainWindow : Window
+{
+ private const string AppTitle = "OpenSlide Viewer";
+ private const string ThumbnailImageName = "thumbnail";
+ private const int ThumbnailSize = 256;
+
+ // GetThumbnail reads a whole level into memory; above this many pixels (64 MiB, as on a slide with a single
+ // large level) the navigator uses the slide's thumbnail image instead.
+ private const double MaxThumbnailSourcePixels = 16 * 1024 * 1024;
+
+ // The formats OpenSlide reads (https://openslide.org/formats/).
+ private static readonly FilePickerFileType SlideFiles = new("Slides")
+ {
+ Patterns =
+ [
+ "*.svs", "*.tif", "*.tiff", "*.ndpi", "*.vms", "*.vmu", "*.scn", "*.mrxs", "*.svslide", "*.bif", "*.dcm",
+ "*.czi",
+ ],
+ };
+
+ private readonly List _imageWindows = new();
+ private PropertyRow[] _propertyRows = [];
+ private AssociatedImageRow[] _imageRows = [];
+ private SelectionRow[] _selectionRows = [];
+ private OpenSlide? _slide;
+ private SlideSize _slideSize;
+ private Bitmap? _thumbnail;
+ private double? _mppX;
+ private double? _mppY;
+ private double? _objectivePower;
+ private int _openRequest; // counts opens (and closes): an open that finishes after a newer one is dropped
+ private bool _closed;
+
+ public MainWindow()
+ {
+ InitializeComponent();
+ // O and W with the platform's command key: Ctrl on Windows and Linux, Cmd on macOS.
+ KeyModifiers command = (this.GetPlatformSettings() ?? Avalonia.Application.Current?.PlatformSettings)
+ ?.HotkeyConfiguration.CommandModifiers ?? KeyModifiers.Control;
+ OpenMenuItem.InputGesture = OpenMenuItem.HotKey = new KeyGesture(Key.O, command);
+ CloseMenuItem.InputGesture = CloseMenuItem.HotKey = new KeyGesture(Key.W, command);
+ SetClipboardText = text => Clipboard is { } clipboard ? clipboard.SetTextAsync(text) : Task.CompletedTask;
+ Viewer.ViewChanged += UpdateStatus;
+ Viewer.LoadFailed += OnLoadFailed;
+ Viewer.Selections.Changed += OnSelectionsChanged;
+ AddHandler(DragDrop.DragEnterEvent, OnDragOver);
+ AddHandler(DragDrop.DragOverEvent, OnDragOver);
+ AddHandler(DragDrop.DropEvent, OnDrop);
+ UpdateStatus();
+ }
+
+ internal IReadOnlyList PropertyRows => _propertyRows;
+
+ internal IReadOnlyList AssociatedImageRows => _imageRows;
+
+ internal IReadOnlyList SelectionRows => _selectionRows;
+
+ internal IReadOnlyList ImageWindows => _imageWindows;
+
+ /// Gets or sets what opens a slide file, on a background thread; a test hook.
+ internal Func OpenSlideFile { get; set; } = OpenSlide.Open;
+
+ /// Gets or sets what reads an associated image, on a background thread; a test hook.
+ internal Func ReadAssociatedImage { get; set; } = image => image.Read();
+
+ /// Gets or sets what puts text on the clipboard; a test hook.
+ internal Func SetClipboardText { get; set; }
+
+ ///
+ /// Opens the slide at (on a background thread) and shows it instead of the current
+ /// one; meanwhile the status bar says it is opening the file. If it cannot be opened, whatever the reason, the
+ /// status bar says why and the current slide stays. An open overtaken by a newer one, or by File → Close, is
+ /// dropped when it finishes.
+ ///
+ public async Task OpenAsync(string path)
+ {
+ ArgumentNullException.ThrowIfNull(path);
+ int request = ++_openRequest;
+ string name = Path.GetFileName(path);
+ ClearError();
+ ShowActivity($"Opening {name}…");
+ try
+ {
+ Func open = OpenSlideFile;
+ LoadedSlide loaded = await Task.Run(() => LoadedSlide.Load(path, open));
+ if (request != _openRequest || _closed)
+ {
+ loaded.Dispose();
+ return;
+ }
+
+ Show(loaded);
+ }
+ catch (Exception e)
+ {
+ // Not only a file OpenSlide rejects (OpenSlideException) or cannot read: a native library that is missing
+ // or broken (DllNotFoundException, EntryPointNotFoundException, BadImageFormatException), no memory. Each
+ // is reported, and the viewer goes on with the slide it shows.
+ if (request == _openRequest && !_closed)
+ {
+ ShowError($"Cannot open {name}: {e.Message}");
+ }
+ }
+ finally
+ {
+ if (request == _openRequest && !_closed)
+ {
+ HideActivity();
+ }
+ }
+ }
+
+ /// Closes the slide shown (File → Close).
+ internal void CloseSlide()
+ {
+ _openRequest++; // an open still running is dropped
+ HideActivity();
+ Viewer.Slide = null; // the view stops reading the slide before it is closed
+ _slide?.Dispose();
+ _slide = null;
+ _slideSize = default;
+ CloseImageWindows();
+ Navigator.Show(default, null, null);
+ _thumbnail?.Dispose();
+ _thumbnail = null;
+ _propertyRows = [];
+ PropertyList.ItemsSource = _propertyRows;
+ _imageRows = [];
+ ImageList.ItemsSource = _imageRows;
+ (_mppX, _mppY, _objectivePower) = (null, null, null);
+ Title = AppTitle;
+ CloseMenuItem.IsEnabled = false;
+ ViewMenu.IsEnabled = false;
+ DropHint.IsVisible = true;
+ ClearError();
+ UpdateStatus();
+ }
+
+ ///
+ /// Shows the associated image of the slide in a window of its own, reading it on a
+ /// background thread; a window that already shows it is brought to the front instead. Returns the window, or
+ /// null if there is no such image, it cannot be read (the status bar then says why), or the slide was closed
+ /// meanwhile.
+ ///
+ internal async Task ShowAssociatedImageAsync(string name)
+ {
+ if (_slide is not { } slide || !slide.AssociatedImages.TryGetValue(name, out AssociatedImage? image))
+ {
+ return null;
+ }
+
+ if (ActivateImageWindow(name) is { } shown)
+ {
+ return shown;
+ }
+
+ PixelImage pixels;
+ try
+ {
+ Func read = ReadAssociatedImage;
+ pixels = await Task.Run(() => read(image));
+ }
+ catch (Exception e)
+ {
+ if (ReferenceEquals(slide, _slide))
+ {
+ ShowError($"Cannot read the {name} image: {e.Message}");
+ }
+
+ return null;
+ }
+
+ if (!ReferenceEquals(slide, _slide) || _closed)
+ {
+ return null; // another slide, or none, by now
+ }
+
+ if (ActivateImageWindow(name) is { } opened)
+ {
+ return opened; // asked twice (a double click, then Enter): the first read opened it
+ }
+
+ var window = new AssociatedImageWindow(name, pixels);
+ window.Closed += (_, _) => _imageWindows.Remove(window);
+ _imageWindows.Add(window);
+ window.Show(this);
+ return window;
+ }
+
+ /// Copies the selected properties, in list order, one per line: key<TAB>value, or just the values.
+ internal async Task CopyPropertiesAsync(bool valuesOnly)
+ {
+ var selected = new HashSet(PropertyList.SelectedItems?.OfType() ?? []);
+ string text = string.Join(
+ Environment.NewLine,
+ _propertyRows.Where(selected.Contains).Select(row => valuesOnly ? row.Value : row.Key + "\t" + row.Value));
+ if (text.Length > 0)
+ {
+ await SetClipboardText(text);
+ }
+ }
+
+ /// Returns the rows of the Properties list: one per property, sorted by key (ordinal, as OpenSlide does).
+ internal static PropertyRow[] PropertyRowsOf(IEnumerable> properties) =>
+ properties
+ .OrderBy(property => property.Key, StringComparer.Ordinal)
+ .Select(property => new PropertyRow(property.Key, property.Value))
+ .ToArray();
+
+ protected override void OnClosed(EventArgs e)
+ {
+ _closed = true;
+ CloseSlide();
+ base.OnClosed(e);
+ }
+
+ // The navigator's picture, read on the thread that opens the slide: GetThumbnail if the level it reads is not
+ // too large, else (or if that fails) the slide's thumbnail image.
+ private static PixelImage? ReadThumbnail(OpenSlide slide)
+ {
+ SlideSize size = slide.Dimensions;
+ double downsample = Math.Max((double)size.Width / ThumbnailSize, (double)size.Height / ThumbnailSize);
+ SlideSize level = slide.LevelDimensions[slide.GetBestLevelForDownsample(downsample)];
+ if ((double)level.Width * level.Height <= MaxThumbnailSourcePixels)
+ {
+ try
+ {
+ return slide.GetThumbnail(ThumbnailSize, ThumbnailSize);
+ }
+ catch (OpenSlideException e)
+ {
+ Trace.TraceWarning($"Cannot make a thumbnail of {slide.FileName}: {e.Message}");
+ }
+ }
+
+ if (slide.AssociatedImages.TryGetValue(ThumbnailImageName, out AssociatedImage? image)
+ && (double)image.Dimensions.Width * image.Dimensions.Height <= MaxThumbnailSourcePixels)
+ {
+ try
+ {
+ return image.Read();
+ }
+ catch (OpenSlideException e)
+ {
+ Trace.TraceWarning($"Cannot read the thumbnail image of {slide.FileName}: {e.Message}");
+ }
+ }
+
+ return null; // the navigator still works, without a picture
+ }
+
+ // Shows a slide just opened. If the view cannot take it, the slide is closed, the exception propagates (OpenAsync
+ // reports it) and the slide shown stays; past that point the window owns the slide.
+ private void Show(LoadedSlide loaded)
+ {
+ try
+ {
+ // First, so that the view stops reading the old slide before it is closed.
+ Viewer.Slide = loaded.Slide;
+ }
+ catch
+ {
+ loaded.Dispose();
+ throw;
+ }
+
+ _slide?.Dispose();
+ _slide = loaded.Slide;
+ _slideSize = loaded.Size;
+ CloseImageWindows();
+ Bitmap? oldThumbnail = _thumbnail;
+ _thumbnail = loaded.Thumbnail?.ToBitmap();
+ Navigator.Show(loaded.Size, _thumbnail, Viewer.Viewport);
+ Viewer.Thumbnail = _thumbnail; // drawn under the tiles of a slide too large to draw from tiles when zoomed out
+ oldThumbnail?.Dispose(); // a frame drawn with it keeps its own reference
+ _propertyRows = loaded.Properties;
+ PropertyList.ItemsSource = _propertyRows;
+ _imageRows = loaded.Images;
+ ImageList.ItemsSource = _imageRows;
+ (_mppX, _mppY, _objectivePower) = (loaded.MppX, loaded.MppY, loaded.ObjectivePower);
+ Title = $"{AppTitle} — {Path.GetFileName(loaded.Path)}";
+ CloseMenuItem.IsEnabled = true;
+ ViewMenu.IsEnabled = true;
+ DropHint.IsVisible = false;
+ ClearError();
+ OnSelectionsChanged(); // the view cleared them; the rows show the new slide's sizes
+ Viewer.Focus();
+ }
+
+ // Brings the window showing the associated image name to the front; null if there is none.
+ private AssociatedImageWindow? ActivateImageWindow(string name)
+ {
+ AssociatedImageWindow? window = _imageWindows.Find(window => window.ImageName == name);
+ window?.Activate();
+ return window;
+ }
+
+ private void CloseImageWindows()
+ {
+ foreach (AssociatedImageWindow window in _imageWindows.ToArray())
+ {
+ window.Close();
+ }
+
+ _imageWindows.Clear();
+ }
+
+ private void ShowError(string message)
+ {
+ ErrorText.Text = message;
+ ToolTip.SetTip(ErrorText, message);
+ ErrorText.IsVisible = true;
+ }
+
+ private void ClearError()
+ {
+ ErrorText.Text = null;
+ ToolTip.SetTip(ErrorText, null);
+ ErrorText.IsVisible = false;
+ }
+
+ private void ShowActivity(string message)
+ {
+ ActivityText.Text = message;
+ ActivityText.IsVisible = true;
+ }
+
+ private void HideActivity()
+ {
+ ActivityText.Text = null;
+ ActivityText.IsVisible = false;
+ }
+
+ // Runs the work of an event handler. An exception thrown out of an async void handler would end the process,
+ // so whatever it throws (a busy clipboard, a file picker that fails, no memory) is shown in the status bar.
+ private async void RunHandler(Func work, string failure)
+ {
+ try
+ {
+ await work();
+ }
+ catch (Exception e)
+ {
+ ShowError($"{failure}: {e.Message}");
+ }
+ }
+
+ private void OnLoadFailed(Exception error) =>
+ ShowError($"Cannot read {Path.GetFileName(_slide?.FileName)}: {error.Message}");
+
+ private void UpdateStatus()
+ {
+ Viewport? viewport = Viewer.Viewport;
+ CoordinatesText.Text = Viewer.PointerSlidePosition is { } pointer
+ && pointer.X >= 0 && pointer.Y >= 0 && pointer.X < _slideSize.Width && pointer.Y < _slideSize.Height
+ ? StatusFormatter.Coordinates(pointer.X, pointer.Y)
+ : ""; // off the view or off the slide
+ ZoomText.Text = viewport is null ? "" : StatusFormatter.Zoom(viewport.Downsample, _objectivePower);
+ string view = viewport is null
+ ? ""
+ : StatusFormatter.PhysicalSize(
+ viewport.ViewWidth * viewport.Downsample, viewport.ViewHeight * viewport.Downsample, _mppX, _mppY);
+ SetSegment(ViewSizeText, view.Length > 0 ? "View: " + view : "");
+
+ // The selection picked in the list, else the latest one.
+ Selection? selection = SelectionsList.SelectedItem is SelectionRow row
+ ? row.Selection
+ : Viewer.Selections.Items.LastOrDefault();
+ string selected = selection is null
+ ? ""
+ : StatusFormatter.PhysicalSize(selection.Width0, selection.Height0, _mppX, _mppY);
+ SetSegment(SelectionSizeText, selected.Length > 0 ? "Selection: " + selected : "");
+
+ static void SetSegment(TextBlock block, string text)
+ {
+ block.Text = text;
+ block.IsVisible = text.Length > 0;
+ }
+ }
+
+ private void OnSelectionsChanged()
+ {
+ IReadOnlyList selections = Viewer.Selections.Items;
+ _selectionRows = selections.Select((selection, index) => new SelectionRow(index, selection, Describe(index, selection))).ToArray();
+ SelectionsList.ItemsSource = _selectionRows;
+ UpdateStatus();
+ }
+
+ private string Describe(int index, Selection selection)
+ {
+ string text = string.Create(
+ CultureInfo.InvariantCulture,
+ $"{index + 1}. {selection.Width0:0} × {selection.Height0:0} px at {selection.X0:0}, {selection.Y0:0}");
+ string size = StatusFormatter.PhysicalSize(selection.Width0, selection.Height0, _mppX, _mppY);
+ return size.Length > 0 ? $"{text} ({size})" : text;
+ }
+
+ private void OnOpenClick(object? sender, RoutedEventArgs e) => RunHandler(PickAndOpenAsync, "Cannot open a slide");
+
+ private async Task PickAndOpenAsync()
+ {
+ IReadOnlyList files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
+ {
+ Title = "Open slide",
+ AllowMultiple = false,
+ FileTypeFilter = [SlideFiles, FilePickerFileTypes.All],
+ });
+ if (files is [IStorageFile file, ..])
+ {
+ await OpenStorageItemAsync(file);
+ }
+ }
+
+ private void OnCloseClick(object? sender, RoutedEventArgs e) => CloseSlide();
+
+ private void OnExitClick(object? sender, RoutedEventArgs e) => Close();
+
+ private void OnFitClick(object? sender, RoutedEventArgs e) => Viewer.Viewport?.Fit();
+
+ private void OnOneToOneClick(object? sender, RoutedEventArgs e) => Viewer.Viewport?.OneToOne();
+
+ private void OnCenterClick(object? sender, RoutedEventArgs e) => Viewer.Viewport?.Center();
+
+ private void OnDragOver(object? sender, DragEventArgs e)
+ {
+ e.DragEffects = e.DataTransfer.Contains(DataFormat.File) ? DragDropEffects.Copy : DragDropEffects.None;
+ e.Handled = true;
+ }
+
+ // Opens the first of the files dropped.
+ private void OnDrop(object? sender, DragEventArgs e)
+ {
+ try
+ {
+ if (e.DataTransfer.TryGetFiles() is [IStorageItem first, ..])
+ {
+ e.Handled = true;
+ RunHandler(() => OpenStorageItemAsync(first), "Cannot open " + first.Name);
+ }
+ }
+ catch (Exception error)
+ {
+ ShowError($"Cannot open the dropped file: {error.Message}");
+ }
+ }
+
+ private Task OpenStorageItemAsync(IStorageItem item)
+ {
+ if (item.TryGetLocalPath() is { } path)
+ {
+ return OpenAsync(path);
+ }
+
+ ShowError($"Cannot open {item.Name}: it is not a local file.");
+ return Task.CompletedTask;
+ }
+
+ private void OnPropertyListKeyDown(object? sender, KeyEventArgs e)
+ {
+ if (this.GetPlatformSettings()?.HotkeyConfiguration.Copy.Any(gesture => gesture.Matches(e)) == true)
+ {
+ e.Handled = true;
+ CopyProperties(valuesOnly: false);
+ }
+ }
+
+ private void OnCopyClick(object? sender, RoutedEventArgs e) => CopyProperties(valuesOnly: false);
+
+ private void OnCopyValueClick(object? sender, RoutedEventArgs e) => CopyProperties(valuesOnly: true);
+
+ private void CopyProperties(bool valuesOnly) =>
+ RunHandler(() => CopyPropertiesAsync(valuesOnly), "Cannot copy the properties");
+
+ private void OnImageListDoubleTapped(object? sender, TappedEventArgs e)
+ {
+ if ((e.Source as Control)?.DataContext is AssociatedImageRow row)
+ {
+ e.Handled = true;
+ ShowAssociatedImage(row.Name);
+ }
+ }
+
+ private void OnImageListKeyDown(object? sender, KeyEventArgs e)
+ {
+ if (e.Key == Key.Enter && ImageList.SelectedItem is AssociatedImageRow row)
+ {
+ e.Handled = true;
+ ShowAssociatedImage(row.Name);
+ }
+ }
+
+ private void ShowAssociatedImage(string name) =>
+ RunHandler(() => ShowAssociatedImageAsync(name), $"Cannot show the {name} image");
+
+ private void OnSelectionsListChanged(object? sender, SelectionChangedEventArgs e) => UpdateStatus();
+
+ private void OnZoomToSelectionClick(object? sender, RoutedEventArgs e)
+ {
+ if ((sender as Control)?.DataContext is SelectionRow { Selection: var selection } && Viewer.Viewport is { } viewport)
+ {
+ e.Handled = true;
+ viewport.ZoomTo(selection.X0, selection.Y0, selection.Width0, selection.Height0);
+ }
+ }
+
+ private void OnDeleteSelectionClick(object? sender, RoutedEventArgs e)
+ {
+ if ((sender as Control)?.DataContext is SelectionRow row && row.Index < Viewer.Selections.Items.Count)
+ {
+ e.Handled = true;
+ Viewer.Selections.RemoveAt(row.Index);
+ }
+ }
+
+ /// A slide opened on a background thread, with what the window shows about it.
+ private sealed class LoadedSlide(
+ string path, OpenSlide slide, PropertyRow[] properties, AssociatedImageRow[] images, PixelImage? thumbnail)
+ : IDisposable
+ {
+ public string Path { get; } = path;
+
+ public OpenSlide Slide { get; } = slide;
+
+ public SlideSize Size { get; } = slide.Dimensions;
+
+ /// Gets the properties, sorted by key.
+ public PropertyRow[] Properties { get; } = properties;
+
+ public AssociatedImageRow[] Images { get; } = images;
+
+ public PixelImage? Thumbnail { get; } = thumbnail;
+
+ public double? MppX { get; } = StatusFormatter.Number(slide.Properties, OpenSlideProperties.MppX);
+
+ public double? MppY { get; } = StatusFormatter.Number(slide.Properties, OpenSlideProperties.MppY);
+
+ public double? ObjectivePower { get; } = StatusFormatter.Number(slide.Properties, OpenSlideProperties.ObjectivePower);
+
+ public static LoadedSlide Load(string path, Func open)
+ {
+ OpenSlide slide = open(path);
+ try
+ {
+ PropertyRow[] properties = PropertyRowsOf(slide.Properties);
+ AssociatedImageRow[] images = slide.AssociatedImages.Values
+ .OrderBy(image => image.Name, StringComparer.Ordinal)
+ .Select(image => new AssociatedImageRow(
+ image.Name,
+ string.Create(CultureInfo.InvariantCulture, $"{image.Dimensions.Width} × {image.Dimensions.Height}")))
+ .ToArray();
+ return new LoadedSlide(path, slide, properties, images, ReadThumbnail(slide));
+ }
+ catch
+ {
+ slide.Dispose();
+ throw;
+ }
+ }
+
+ public void Dispose() => Slide.Dispose();
+ }
+}
+
+/// A row of the Properties list.
+internal sealed record PropertyRow(string Key, string Value);
+
+/// A row of the Associated images list: the image's name and its size in pixels.
+internal sealed record AssociatedImageRow(string Name, string Size);
+
+/// A row of the Selections list: the selection at in the view's list.
+internal sealed record SelectionRow(int Index, Selection Selection, string Text);
diff --git a/samples/OpenSlideSharp.Viewer/OpenSlideSharp.Viewer.csproj b/samples/OpenSlideSharp.Viewer/OpenSlideSharp.Viewer.csproj
new file mode 100644
index 0000000..e356642
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/OpenSlideSharp.Viewer.csproj
@@ -0,0 +1,94 @@
+
+
+
+ net10.0
+ WinExe
+ false
+ OpenSlideSharp.Viewer
+ app.manifest
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ $(Version)
+
+
+
+
+
+
+
+
+ true
+ true
+
+
+
+
+
+
+
+
+
+
+ <_OpenSlideBinDir Condition="'$(UseOpenSlideRuntimePackage)' == 'true'">$(PkgOpenSlideSharp_runtime)
+ <_OpenSlideBinDir Condition="'$(UseOpenSlideRuntimePackage)' != 'true'">$(MSBuildThisFileDirectory)..\..\artifacts\native
+
+
+
+
+ <_ViewerPackageFile Include="@(ResolvedFileToPublish)" Condition="'%(ResolvedFileToPublish.NuGetPackageId)' != ''"
+ PackageDir="$([System.Text.RegularExpressions.Regex]::Match('%(ResolvedFileToPublish.FullPath)', '(?i)^.*[\\/]%(ResolvedFileToPublish.NuGetPackageId)[\\/]%(ResolvedFileToPublish.NuGetPackageVersion)[\\/]').Value)" />
+ <_ViewerPackage Include="@(_ViewerPackageFile->'%(PackageDir)'->Distinct())" Condition="'%(_ViewerPackageFile.PackageDir)' != ''" />
+ <_ViewerPackageLicense Include="%(_ViewerPackage.Identity)LICENSE*;%(_ViewerPackage.Identity)THIRD-PARTY-NOTICES*"
+ PackageId="%(_ViewerPackage.NuGetPackageId)" />
+
+ <_OpenSlideBinLicense Include="$(_OpenSlideBinDir)/licenses/**" />
+
+ <_ViewerLicense Include="@(_OpenSlideBinLicense)"
+ RelativePath="licenses/openslide-bin/%(_OpenSlideBinLicense.RecursiveDir)%(_OpenSlideBinLicense.Filename)%(_OpenSlideBinLicense.Extension)" />
+ <_ViewerLicense Include="$(_OpenSlideBinDir)/VERSIONS.md" RelativePath="licenses/openslide-bin/VERSIONS.md" />
+ <_ViewerLicense Include="@(_ViewerPackageLicense)"
+ RelativePath="licenses/%(_ViewerPackageLicense.PackageId)/%(_ViewerPackageLicense.Filename)%(_ViewerPackageLicense.Extension)" />
+ <_ViewerLicense Include="$(MSBuildThisFileDirectory)..\..\LICENSE" RelativePath="licenses/OpenSlideSharp/LICENSE" />
+ <_ViewerLicense Include="$(MSBuildThisFileDirectory)THIRD-PARTY-NOTICES.txt" RelativePath="licenses/THIRD-PARTY-NOTICES.txt" />
+ <_ViewerLicense Include="$(MSBuildThisFileDirectory)SOURCE.md" RelativePath="licenses/SOURCE.md" />
+
+
+
+
+
+
diff --git a/samples/OpenSlideSharp.Viewer/ParentConsole.cs b/samples/OpenSlideSharp.Viewer/ParentConsole.cs
new file mode 100644
index 0000000..79173a5
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/ParentConsole.cs
@@ -0,0 +1,60 @@
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace OpenSlideSharp.Viewer;
+
+///
+/// Lets --check print to the console it was started from. On Windows the viewer is a GUI (WinExe) program, so
+/// it starts without a console: unless the caller redirects its output to a pipe or a file, standard output goes
+/// nowhere. Attaching to the parent process's console makes the lines appear there.
+///
+internal static class ParentConsole
+{
+ private const int StdOutputHandle = -11;
+ private const uint AttachParentProcess = unchecked((uint)-1);
+
+ ///
+ /// Whether to attach to the parent's console: on Windows, when the process has no standard output handle. A
+ /// redirected output (a pipe or a file) is a valid handle and is used as it is.
+ /// cannot decide this: it reports a missing handle as redirected.
+ ///
+ internal static bool ShouldAttach(bool isWindows, IntPtr standardOutput) =>
+ isWindows && (standardOutput == IntPtr.Zero || standardOutput == new IntPtr(-1));
+
+ ///
+ /// Attaches to the parent's console when says so, and re-opens
+ /// on it. Does nothing if the parent has no console.
+ ///
+ internal static void AttachIfNoOutput()
+ {
+ if (!OperatingSystem.IsWindows() || !ShouldAttach(isWindows: true, GetStdHandle(StdOutputHandle)))
+ {
+ return;
+ }
+
+ if (!AttachConsole(AttachParentProcess))
+ {
+ return;
+ }
+
+ // AttachConsole fills in the standard handles. Console.Out may already be bound to the missing one, so open
+ // the console's handle again, writing in the console's code page. A UTF-8 console must not get a byte order
+ // mark, which Console.OutputEncoding would write.
+ Encoding encoding = Console.OutputEncoding;
+ if (encoding.CodePage == Encoding.UTF8.CodePage)
+ {
+ encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
+ }
+
+ Console.SetOut(new StreamWriter(Console.OpenStandardOutput(), encoding) { AutoFlush = true });
+ }
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool AttachConsole(uint processId);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern IntPtr GetStdHandle(int standardHandle);
+}
diff --git a/samples/OpenSlideSharp.Viewer/Program.cs b/samples/OpenSlideSharp.Viewer/Program.cs
new file mode 100644
index 0000000..0fa9355
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/Program.cs
@@ -0,0 +1,75 @@
+using System;
+using System.IO;
+using System.Runtime.CompilerServices;
+using Avalonia;
+
+namespace OpenSlideSharp.Viewer;
+
+internal static class Program
+{
+ // The size of the region --check reads.
+ private const int CheckRegionSize = 256;
+
+ // Don't use Avalonia, third-party APIs or SynchronizationContext-reliant code before AppMain is called.
+ [STAThread]
+ public static int Main(string[] args)
+ {
+ if (args.Length > 0 && args[0] == "--check")
+ {
+ ParentConsole.AttachIfNoOutput();
+ return RunCheck(args, Console.Out);
+ }
+
+ return RunApp(args);
+ }
+
+ // Avalonia configuration; also used by the visual designer.
+ public static AppBuilder BuildAvaloniaApp()
+ => AppBuilder.Configure()
+ .UsePlatformDetect()
+ .WithInterFont()
+ .LogToTrace();
+
+ ///
+ /// --check <slide>: checks without a window (or a display) that the viewer can load OpenSlide and
+ /// read the slide. Prints openslide=<version> and slide=<width>x<height> after
+ /// reading the top-left 256 x 256 region of the lowest-resolution level.
+ ///
+ ///
+ /// 0 on success, 1 if the slide cannot be opened or read, 2 for invalid arguments, 3 if the native OpenSlide
+ /// library cannot be loaded.
+ ///
+ internal static int RunCheck(string[] args, TextWriter output)
+ {
+ if (args.Length != 2 || args[0] != "--check")
+ {
+ output.WriteLine("Usage: OpenSlideSharp.Viewer [slide] | --check ");
+ return 2;
+ }
+
+ string path = args[1];
+ try
+ {
+ output.WriteLine("openslide=" + OpenSlideLibrary.Version);
+ using OpenSlide slide = OpenSlide.Open(path);
+ var pixels = new byte[CheckRegionSize * CheckRegionSize * 4];
+ slide.ReadRegion(0, 0, slide.LevelCount - 1, CheckRegionSize, CheckRegionSize, pixels);
+ output.WriteLine(FormattableString.Invariant($"slide={slide.Dimensions.Width}x{slide.Dimensions.Height}"));
+ return 0;
+ }
+ catch (DllNotFoundException e)
+ {
+ output.WriteLine(e.Message);
+ return 3;
+ }
+ catch (Exception e) when (e is OpenSlideException or IOException or UnauthorizedAccessException or ArgumentException)
+ {
+ output.WriteLine($"Cannot open {path}: {e.Message}");
+ return 1;
+ }
+ }
+
+ // Kept out of Main so that --check does not even load Avalonia.
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static int RunApp(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
+}
diff --git a/samples/OpenSlideSharp.Viewer/README.md b/samples/OpenSlideSharp.Viewer/README.md
new file mode 100644
index 0000000..95d011d
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/README.md
@@ -0,0 +1,61 @@
+# OpenSlideSharp.Viewer
+
+A desktop viewer for whole-slide images on Windows, Linux and macOS, built on Avalonia and `OpenSlideSharp` after 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
+```
+
+Open a slide from the command line, with File → Open, or by dropping it on the window. A file that cannot be opened is reported in the status bar, and the slide shown stays.
+
+## Features
+
+- Pan and zoom; tiles are read in the background, and coarser levels show until the finer ones arrive.
+- A navigator, the slide's properties (Ctrl+C, Cmd+C on macOS, or the context menu copies them) and its associated images (double-click to open).
+- Rectangle selections, listed in the Selections tab with "Zoom to" and "Delete".
+- A status bar with the level-0 pixel under the pointer, the zoom and magnification, and physical sizes when the slide has mpp.
+
+Pixels are shown as OpenSlide returns them, without ICC color conversion, as in openslide-java's viewer.
+
+## Shortcuts
+
+| Input | Action |
+|---|---|
+| Drag | Pan |
+| Wheel | Zoom at the pointer |
+| Shift + drag | Select a rectangle |
+| Arrow keys, `W` `A` `S` `D` | Pan by 100 pixels |
+| `+` or `=`, `-` | Zoom in, out |
+| `Z` | Fit the slide to the window |
+| `1` | Zoom to 1:1 (one level-0 pixel per screen pixel) |
+| Space | Center the slide |
+| Ctrl+O (Cmd+O on macOS) | Open a slide |
+| Ctrl+W (Cmd+W on macOS) | Close the slide |
+
+The view keys work while the view has the keyboard focus: click it first.
+
+## `--check`
+
+`OpenSlideSharp.Viewer --check slide.svs` opens the slide without a window, reads a tile of its lowest-resolution level and prints `openslide=` and `slide=x`. It exits with 0 on success, 1 if the slide cannot be opened or read, 2 for invalid arguments and 3 if the native OpenSlide library cannot be loaded.
+
+On Windows the viewer is a GUI program, so a console does not wait for it. To get the output and the exit code, use `start /wait OpenSlideSharp.Viewer.exe --check slide.svs` in cmd, or pipe it in PowerShell: `.\OpenSlideSharp.Viewer.exe --check slide.svs | Out-Host`, then `$LASTEXITCODE`.
+
+## Self-contained publish
+
+```sh
+dotnet publish samples/OpenSlideSharp.Viewer -c Release -r win-x64 --self-contained -p:PublishSingleFile=true \
+ -p:UseOpenSlideRuntimePackage=true -p:OpenSlideSharpVersion=
+```
+
+`artifacts/publish/OpenSlideSharp.Viewer/release_win-x64/` then holds `OpenSlideSharp.Viewer.exe`, which runs without .NET installed, and `licenses/`. The other runtime identifiers are `linux-x64`, `linux-arm64`, `osx-arm64` and `osx-x64`. OpenSlide comes from the `OpenSlideSharp.runtime` package of that version, restored from nuget.org or from a folder given with `-p:RestoreAdditionalProjectSources=`, as `eng/Test-Packages.ps1` does.
+
+The native libraries are inside the executable. It extracts them on first start to `%TEMP%\.net` on Windows and `~/.net` on Linux and macOS (or to `DOTNET_BUNDLE_EXTRACT_BASE_DIR`), and reuses them after that. The folders that older versions of the viewer extracted there can be deleted.
+
+## Licenses
+
+`licenses/` holds the license and notice files of what the executable contains: OpenSlide and the libraries linked into it (LGPL-2.1 and others, with their versions in `VERSIONS.md`), SkiaSharp, HarfBuzzSharp, ANGLE, Avalonia, the .NET runtime and the Inter font. `THIRD-PARTY-NOTICES.txt` lists them, and `SOURCE.md` says where OpenSlide's source code is and how to run the viewer with another OpenSlide build (`OPENSLIDE_LIBRARY_PATH`). Keep the folder with the executable. The planned GitHub release builds will ship this publish folder, executable and `licenses/`, as one archive per platform.
+
+## Known issue on Windows
+
+Corrupt JPEG or PNG data in a slide terminates the viewer with `0xC0000409`, without an error message; see [the details](../../docs/known-issues/windows-cfg-longjmp-crash.md). Linux and macOS report such tiles in the status bar.
diff --git a/samples/OpenSlideSharp.Viewer/SOURCE.md b/samples/OpenSlideSharp.Viewer/SOURCE.md
new file mode 100644
index 0000000..a09795a
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/SOURCE.md
@@ -0,0 +1,35 @@
+# OpenSlide: source code and replacing the library
+
+The viewer contains a build of [OpenSlide](https://openslide.org/) from
+[openslide-bin](https://github.com/openslide/openslide-bin): `libopenslide-1.dll` on Windows, `libopenslide-1.so` on
+Linux and `libopenslide-1.dylib` on macOS, which the executable extracts when it first starts. OpenSlide is licensed
+under the GNU Lesser General Public License 2.1, and the libraries linked into it under their own licenses: see
+`openslide-bin/`, and `openslide-bin/VERSIONS.md` for their versions.
+
+## Source code
+
+The corresponding source code is the openslide-bin source archive of the same build, `openslide-bin-.tar.gz`,
+published with its binaries:
+
+- a release: `https://github.com/openslide/openslide-bin/releases/download/v/openslide-bin-.tar.gz`
+- a nightly build: the release `v` on (nightly builds are kept
+ for a limited time)
+
+The viewer has the version of the OpenSlideSharp packages it was built with, and the table under "Versioning" in
+ gives the openslide-bin build of each version.
+
+## Using another OpenSlide build
+
+Set the `OPENSLIDE_LIBRARY_PATH` environment variable to the full path of another build of the OpenSlide 4.x library,
+for example one built from the source above, changed or not. The viewer then loads that library instead of the one it
+contains:
+
+```sh
+OPENSLIDE_LIBRARY_PATH=/path/to/libopenslide.so.1 ./OpenSlideSharp.Viewer slide.svs
+```
+
+```powershell
+$env:OPENSLIDE_LIBRARY_PATH = 'C:\path\to\libopenslide-1.dll'; .\OpenSlideSharp.Viewer.exe slide.svs
+```
+
+`OpenSlideSharp.Viewer --check slide.svs` prints the version of the library it loaded (`openslide=...`).
diff --git a/samples/OpenSlideSharp.Viewer/StatusFormatter.cs b/samples/OpenSlideSharp.Viewer/StatusFormatter.cs
new file mode 100644
index 0000000..4f4980e
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/StatusFormatter.cs
@@ -0,0 +1,72 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+
+namespace OpenSlideSharp.Viewer;
+
+///
+/// The texts of the status bar, as pure functions. Numbers are formatted the same in every culture, with a decimal
+/// point.
+///
+internal static class StatusFormatter
+{
+ // Sizes from 1000 µm up are shown in millimetres.
+ private const double MicrometresPerMillimetre = 1000;
+
+ ///
+ /// Returns the level-0 pixel under the pointer, "x: 1234 y: 567" (rounded down); empty when either
+ /// coordinate is missing.
+ ///
+ public static string Coordinates(double? x, double? y) =>
+ x is { } px && y is { } py && double.IsFinite(px) && double.IsFinite(py)
+ ? string.Create(CultureInfo.InvariantCulture, $"x: {(long)Math.Floor(px)} y: {(long)Math.Floor(py)}")
+ : "";
+
+ ///
+ /// Returns the zoom as "1:4.02", level-0 pixels per screen pixel, followed by the magnification it gives
+ /// with the slide's objective, "1:4.02 (9.96×)", when is a positive
+ /// number.
+ ///
+ public static string Zoom(double downsample, double? objectivePower)
+ {
+ string zoom = string.Create(CultureInfo.InvariantCulture, $"1:{downsample:0.00}");
+ return objectivePower is { } power && IsPositive(power) && IsPositive(downsample)
+ ? string.Create(CultureInfo.InvariantCulture, $"{zoom} ({power / downsample:0.00}×)")
+ : zoom;
+ }
+
+ ///
+ /// Returns the physical size of a level-0 rectangle: "812.5 × 600.0 µm", or "1.25 × 0.80 mm" once
+ /// a side reaches 1000 µm. Empty unless both microns-per-pixel values are positive numbers.
+ ///
+ public static string PhysicalSize(double width0, double height0, double? mppX, double? mppY)
+ {
+ if (mppX is not { } micronsX || mppY is not { } micronsY || !IsPositive(micronsX) || !IsPositive(micronsY)
+ || !(double.IsFinite(width0) && width0 >= 0) || !(double.IsFinite(height0) && height0 >= 0))
+ {
+ return "";
+ }
+
+ double width = width0 * micronsX;
+ double height = height0 * micronsY;
+ // Compared as shown, so that 999.96 µm is not printed as "1000.0 µm".
+ return Math.Round(Math.Max(width, height), 1) >= MicrometresPerMillimetre
+ ? string.Create(
+ CultureInfo.InvariantCulture,
+ $"{width / MicrometresPerMillimetre:0.00} × {height / MicrometresPerMillimetre:0.00} mm")
+ : string.Create(CultureInfo.InvariantCulture, $"{width:0.0} × {height:0.0} µm");
+ }
+
+ ///
+ /// Returns the slide property as a number (such as openslide.mpp-x), or null if
+ /// it is missing or is not a positive number.
+ ///
+ public static double? Number(IReadOnlyDictionary properties, string key) =>
+ properties.TryGetValue(key, out string? text)
+ && double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out double value)
+ && IsPositive(value)
+ ? value
+ : null;
+
+ private static bool IsPositive(double value) => double.IsFinite(value) && value > 0;
+}
diff --git a/samples/OpenSlideSharp.Viewer/THIRD-PARTY-NOTICES.txt b/samples/OpenSlideSharp.Viewer/THIRD-PARTY-NOTICES.txt
new file mode 100644
index 0000000..fd5d3ce
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/THIRD-PARTY-NOTICES.txt
@@ -0,0 +1,186 @@
+OpenSlide Viewer (OpenSlideSharp.Viewer): third-party notices
+=============================================================
+
+The viewer is part of OpenSlideSharp (https://github.com/IOL0ol1/OpenSlideSharp), which is MIT licensed; its
+license is in OpenSlideSharp/LICENSE next to this file. The viewer's executable also contains the components
+below, each under its own license.
+
+Where a component's NuGet package ships license or notice files, the publish copies them into a folder named
+after the package, next to this file. The licenses of the other components are reproduced at the end of this
+file.
+
+
+1. OpenSlide and the libraries linked into it (openslide-bin)
+ License: OpenSlide: LGPL-2.1-only. The libraries statically linked into it (cairo, glib, libdicom, libffi,
+ libjpeg-turbo, libpng, libtiff, libxml2, OpenJPEG, pixman, proxy-libintl, SQLite, uthash, zlib-ng,
+ Zstandard, as listed in VERSIONS.md) are each under their own license.
+ Upstream: https://openslide.org/
+ https://github.com/openslide/openslide-bin
+ Files: openslide-bin/VERSIONS.md (the components and their versions)
+ openslide-bin// (their license texts)
+ Source code, and how to use another OpenSlide build instead: SOURCE.md.
+
+2. SkiaSharp and Skia
+ License: SkiaSharp: MIT. Skia: BSD-3-Clause, and the licenses of the code it includes.
+ Upstream: https://github.com/mono/SkiaSharp
+ https://skia.org/
+ Files: SkiaSharp/LICENSE.txt
+ SkiaSharp.NativeAssets./LICENSE.txt and THIRD-PARTY-NOTICES.txt
+
+3. HarfBuzzSharp and HarfBuzz
+ License: HarfBuzzSharp: MIT. HarfBuzz: Old MIT.
+ Upstream: https://github.com/mono/SkiaSharp
+ https://github.com/harfbuzz/harfbuzz
+ Files: HarfBuzzSharp/LICENSE.txt
+ HarfBuzzSharp.NativeAssets./LICENSE.txt and THIRD-PARTY-NOTICES.txt
+
+4. ANGLE (Windows only)
+ License: BSD-3-Clause.
+ Upstream: https://chromium.googlesource.com/angle/angle
+ Files: Avalonia.Angle.Windows.Natives/LICENSE
+
+5. Avalonia (including Avalonia.Native on macOS)
+ License: MIT; the text is below.
+ Upstream: https://github.com/AvaloniaUI/Avalonia
+
+6. MicroCom.Runtime
+ License: MIT. Copyright 2021 Nikita Tsukanov.
+ Upstream: https://github.com/kekekeks/MicroCom
+
+7. Tmds.DBus.Protocol (Linux)
+ License: MIT. Copyright Tom Deseyn.
+ Upstream: https://github.com/tmds/Tmds.DBus
+
+8. .NET runtime
+ License: MIT, with the notices of the third-party code it includes.
+ Upstream: https://github.com/dotnet/runtime
+ Files: Microsoft.NETCore.App.Runtime./LICENSE.TXT and THIRD-PARTY-NOTICES.TXT
+
+9. Inter font (in Avalonia.Fonts.Inter)
+ License: SIL Open Font License 1.1; the text is below.
+ Upstream: https://github.com/rsms/inter
+
+
+-------------------------------------------------------------------------------
+Avalonia license (https://github.com/AvaloniaUI/Avalonia/blob/master/licence.md)
+-------------------------------------------------------------------------------
+
+The MIT License (MIT)
+
+Copyright (c) AvaloniaUI OÜ
+All Rights Reserved
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+-------------------------------------------------------------------------------
+Inter license (https://github.com/rsms/inter/blob/master/LICENSE.txt)
+-------------------------------------------------------------------------------
+
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/samples/OpenSlideSharp.Viewer/app.manifest b/samples/OpenSlideSharp.Viewer/app.manifest
new file mode 100644
index 0000000..5a3e54f
--- /dev/null
+++ b/samples/OpenSlideSharp.Viewer/app.manifest
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/OpenSlideSharp.Tool.Tests/DeepZoomCommandTests.cs b/test/OpenSlideSharp.Tool.Tests/DeepZoomCommandTests.cs
index 2c0a1fa..a14e68b 100644
--- a/test/OpenSlideSharp.Tool.Tests/DeepZoomCommandTests.cs
+++ b/test/OpenSlideSharp.Tool.Tests/DeepZoomCommandTests.cs
@@ -241,7 +241,21 @@ void Cancel(string path)
cts.Token);
Assert.Equal(130, code);
- Assert.InRange(writes, 1, 3);
+
+ // How many files a complete export writes, for the same arguments as above.
+ using var slide = OpenSlide.Open(TestFiles.Get("boxes.tiff"));
+ long total = command == "deepzoom"
+ ? new DeepZoomGenerator(slide, 254, 1, limitBounds: true).TileCount
+ : new OmeZarrGenerator(slide, new OmeZarrOptions
+ {
+ Version = command == "omezarr-0.4" ? NgffVersion.V0_4 : NgffVersion.V0_5,
+ ChunkSize = 16,
+ }).EnumerateKeys().LongCount();
+
+ // Each of the two workers may finish the item it had already started, so the exact count depends on scheduling.
+ // What matters is that something was written and the export stopped before writing everything.
+ Assert.True(writes >= 1, $"writes: {writes}");
+ Assert.True(writes < total, $"writes: {writes}, a full export writes {total}");
string[] files = Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories);
Assert.NotEmpty(files);
Assert.DoesNotContain(files, f => f.EndsWith(".tmp", StringComparison.Ordinal));
diff --git a/test/OpenSlideSharp.Viewer.Tests/CheckModeTests.cs b/test/OpenSlideSharp.Viewer.Tests/CheckModeTests.cs
new file mode 100644
index 0000000..9325dc6
--- /dev/null
+++ b/test/OpenSlideSharp.Viewer.Tests/CheckModeTests.cs
@@ -0,0 +1,88 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Reflection.PortableExecutable;
+using Xunit;
+
+namespace OpenSlideSharp.Viewer.Tests;
+
+public class CheckModeTests
+{
+ [Theory]
+ [InlineData("small.svs", "slide=16x16")]
+ [InlineData("boxes.tiff", "slide=300x250")]
+ public void Check_OpensSlide_PrintsVersionAndSize(string fixture, string size)
+ {
+ var output = new StringWriter();
+
+ int code = Program.RunCheck(["--check", TestFiles.Get(fixture)], output);
+
+ Assert.True(code == 0, output.ToString());
+ Assert.Contains("openslide=4.", output.ToString());
+ Assert.Contains(size, output.ToString());
+ }
+
+ [Theory]
+ [InlineData("unopenable.tiff")]
+ [InlineData("missing.svs")]
+ public void Check_Unopenable_Returns1(string fixture)
+ {
+ var output = new StringWriter();
+
+ int code = Program.RunCheck(["--check", TestFiles.Get(fixture)], output);
+
+ Assert.Equal(1, code);
+ Assert.Contains(fixture, output.ToString());
+ Assert.DoesNotContain(
+ output.ToString().Split(Environment.NewLine),
+ line => line.StartsWith("slide=", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData]
+ [InlineData("--check")]
+ [InlineData("--check", "a.svs", "b.svs")]
+ public void Check_BadArguments_Returns2(params string[] args)
+ {
+ var output = new StringWriter();
+
+ int code = Program.RunCheck(args, output);
+
+ Assert.Equal(2, code);
+ Assert.Contains("--check ", output.ToString());
+ }
+
+ [Theory]
+ [InlineData(true, 0L, true)] // No handle: Windows started the GUI program from a console without redirecting.
+ [InlineData(true, -1L, true)] // INVALID_HANDLE_VALUE.
+ [InlineData(true, 0x1234L, false)] // A pipe or a file the caller redirected the output to.
+ [InlineData(false, 0L, false)] // Not Windows: standard output is always usable.
+ public void ParentConsole_AttachesOnlyWithoutAnOutputHandleOnWindows(bool isWindows, long handle, bool expected)
+ {
+ Assert.Equal(expected, ParentConsole.ShouldAttach(isWindows, new IntPtr(handle)));
+ }
+
+ [Fact]
+ public void Check_WindowsExecutable_PrintsToRedirectedOutput()
+ {
+ Assert.SkipUnless(
+ OperatingSystem.IsWindows(),
+ "Only Windows starts the viewer as a GUI program without a console; eng/Test-Packages.ps1 runs the published viewer on every platform");
+ string exe = Path.Combine(AppContext.BaseDirectory, "OpenSlideSharp.Viewer.exe");
+ using (var pe = new PEReader(File.OpenRead(exe)))
+ {
+ Assert.Equal(Subsystem.WindowsGui, pe.PEHeaders.PEHeader!.Subsystem);
+ }
+
+ var info = new ProcessStartInfo(exe) { UseShellExecute = false, RedirectStandardOutput = true };
+ info.ArgumentList.Add("--check");
+ info.ArgumentList.Add(TestFiles.Get("small.svs"));
+ using Process process = Process.Start(info)!;
+ string output = process.StandardOutput.ReadToEnd();
+
+ Assert.True(process.WaitForExit(30_000), "the viewer did not exit");
+ Assert.True(process.ExitCode == 0, output);
+ Assert.Contains("openslide=4.", output);
+ Assert.Contains("slide=16x16", output);
+ }
+}
diff --git a/test/OpenSlideSharp.Viewer.Tests/HeadlessSession.cs b/test/OpenSlideSharp.Viewer.Tests/HeadlessSession.cs
new file mode 100644
index 0000000..d777cd5
--- /dev/null
+++ b/test/OpenSlideSharp.Viewer.Tests/HeadlessSession.cs
@@ -0,0 +1,83 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia;
+using Avalonia.Headless;
+using Avalonia.Threading;
+using Xunit;
+
+namespace OpenSlideSharp.Viewer.Tests;
+
+///
+/// The Avalonia headless session the UI tests share: one viewer for the whole test assembly,
+/// drawn by Skia so that rendered frames can be captured. Anything that touches Avalonia runs on the session's
+/// dispatcher thread through ; tests close the windows they open.
+///
+internal static class HeadlessSession
+{
+ private static readonly TimeSpan RunTimeout = TimeSpan.FromSeconds(60);
+
+ // HeadlessUnitTestSession.StartNew(typeof(App)) would draw with the headless stub, which cannot capture
+ // frames, so the session starts from HeadlessApp.BuildAvaloniaApp instead.
+ private static readonly Lazy Session = new(
+ () => HeadlessUnitTestSession.StartNew(typeof(HeadlessApp), AvaloniaTestIsolationLevel.PerAssembly));
+
+ /// Runs on the UI thread of the session and returns its result.
+ public static T Run(Func action)
+ {
+ ArgumentNullException.ThrowIfNull(action);
+ Task task = Session.Value.Dispatch(action, TestContext.Current.CancellationToken);
+ return task.WaitAsync(RunTimeout).GetAwaiter().GetResult();
+ }
+
+ /// Runs on the UI thread of the session.
+ public static void Run(Action action)
+ {
+ ArgumentNullException.ThrowIfNull(action);
+ Run(() =>
+ {
+ action();
+ return 0;
+ });
+ }
+
+ ///
+ /// On the UI thread: runs the dispatcher's jobs and render ticks until holds,
+ /// failing the test after .
+ ///
+ public static void PumpUntil(Func condition, string what, double seconds = 5)
+ {
+ DateTime deadline = DateTime.UtcNow.AddSeconds(seconds);
+ while (true)
+ {
+ Pump();
+ if (condition())
+ {
+ return;
+ }
+
+ if (DateTime.UtcNow > deadline)
+ {
+ throw new TimeoutException("Timed out waiting until " + what + ".");
+ }
+
+ Thread.Sleep(2);
+ }
+ }
+
+ /// On the UI thread: runs the dispatcher's jobs and one render tick.
+ public static void Pump()
+ {
+ Dispatcher.UIThread.RunJobs();
+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();
+ Dispatcher.UIThread.RunJobs();
+ }
+}
+
+/// The viewer's on the headless platform, drawn by Skia.
+internal static class HeadlessApp
+{
+ public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure()
+ .UseSkia()
+ .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false });
+}
diff --git a/test/OpenSlideSharp.Viewer.Tests/MainWindowTests.cs b/test/OpenSlideSharp.Viewer.Tests/MainWindowTests.cs
new file mode 100644
index 0000000..ee9c579
--- /dev/null
+++ b/test/OpenSlideSharp.Viewer.Tests/MainWindowTests.cs
@@ -0,0 +1,712 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Input;
+using Avalonia.Input.Platform;
+using Avalonia.Input.Raw;
+using Avalonia.Media;
+using Avalonia.Platform.Storage;
+using Avalonia.VisualTree;
+using OpenSlideSharp.Viewer.Controls;
+using OpenSlideSharp.Viewer.Core;
+using Xunit;
+
+namespace OpenSlideSharp.Viewer.Tests;
+
+public class MainWindowTests
+{
+ private const string AppTitle = "OpenSlide Viewer";
+
+ [Fact]
+ public void Open_ShowsPropertiesSorted()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("small.svs");
+
+ string[] keys = host.Window.PropertyRows.Select(row => row.Key).ToArray();
+ Assert.Contains(OpenSlideProperties.Vendor, keys);
+ Assert.Equal(keys.Order(StringComparer.Ordinal), keys);
+ OpenSlide slide = host.Window.Viewer.Slide!;
+ Assert.Equal(slide.Properties.Count, keys.Length);
+ Assert.All(host.Window.PropertyRows, row => Assert.Equal(slide.Properties[row.Key], row.Value));
+ Assert.Same(host.Window.PropertyRows, host.Window.PropertyList.ItemsSource);
+ });
+ }
+
+ [Fact]
+ public void PropertyRows_AreSortedByKey()
+ {
+ var properties = new Dictionary
+ {
+ ["openslide.vendor"] = "aperio",
+ ["b"] = "2",
+ ["aperio.MPP"] = "0.499",
+ ["a"] = "1",
+ ["A"] = "0",
+ };
+
+ PropertyRow[] rows = MainWindow.PropertyRowsOf(properties);
+
+ Assert.Equal(["A", "a", "aperio.MPP", "b", "openslide.vendor"], rows.Select(row => row.Key));
+ Assert.Equal(["0", "1", "0.499", "2", "aperio"], rows.Select(row => row.Value));
+ }
+
+ [Fact]
+ public void Properties_CopiesTheSelectedRows()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("small.svs");
+ ListBox list = host.Window.PropertyList;
+ PropertyRow first = host.Window.PropertyRows[0];
+ PropertyRow vendor = host.Window.PropertyRows.Single(row => row.Key == OpenSlideProperties.Vendor);
+ list.SelectedItems!.Add(vendor);
+ list.SelectedItems.Add(first);
+
+ Task copy = host.Window.CopyPropertiesAsync(valuesOnly: false);
+ HeadlessSession.PumpUntil(() => copy.IsCompleted, "the rows are copied");
+ copy.GetAwaiter().GetResult();
+
+ // In list order, one "keyvalue" line each.
+ string expected = $"{first.Key}\t{first.Value}{Environment.NewLine}{vendor.Key}\t{vendor.Value}";
+ Assert.Equal(expected, ClipboardText(host.Window));
+
+ copy = host.Window.CopyPropertiesAsync(valuesOnly: true);
+ HeadlessSession.PumpUntil(() => copy.IsCompleted, "the values are copied");
+ Assert.Equal($"{first.Value}{Environment.NewLine}{vendor.Value}", ClipboardText(host.Window));
+
+ // The platform's copy key does the first, from a row with the focus.
+ HeadlessSession.Pump();
+ Assert.True(((Control)list.ContainerFromItem(first)!).Focus());
+ Assert.True(list.IsKeyboardFocusWithin);
+ host.Window.KeyPressQwerty(PhysicalKey.C, RawInputModifiers.Control);
+ host.Window.KeyReleaseQwerty(PhysicalKey.C, RawInputModifiers.Control);
+ HeadlessSession.PumpUntil(() => ClipboardText(host.Window) == expected, "Ctrl+C copies the rows");
+ });
+
+ static string? ClipboardText(TopLevel topLevel)
+ {
+ Task text = topLevel.Clipboard!.TryGetTextAsync();
+ HeadlessSession.PumpUntil(() => text.IsCompleted, "the clipboard is read");
+ return text.GetAwaiter().GetResult();
+ }
+ }
+
+ [Fact]
+ public void Open_ListsAssociatedImages()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("small.svs");
+ AssociatedImageRow row = Assert.Single(host.Window.AssociatedImageRows, r => r.Name == "thumbnail");
+ Assert.Equal("16 × 16", row.Size);
+
+ // A double click on the list item opens its window.
+ host.Window.Tabs.SelectedItem = host.Window.ImagesTab;
+ HeadlessSession.Pump();
+ var item = (Control)host.Window.ImageList.ContainerFromItem(row)!;
+ Point at = item.TranslatePoint(new Point(item.Bounds.Width / 2, item.Bounds.Height / 2), host.Window)!.Value;
+ host.Window.MouseDown(at, MouseButton.Left);
+ host.Window.MouseUp(at, MouseButton.Left);
+ host.Window.MouseDown(at, MouseButton.Left);
+ host.Window.MouseUp(at, MouseButton.Left);
+ HeadlessSession.PumpUntil(() => host.Window.ImageWindows.Count > 0, "the image window opens");
+
+ AssociatedImageWindow window = Assert.Single(host.Window.ImageWindows);
+ Assert.Equal("thumbnail", window.Title);
+ Assert.Equal(new PixelSize(16, 16), window.Image!.PixelSize);
+ RenderedFrame frame = RenderedFrame.Capture(window);
+ Assert.True(frame.Count(c => !RenderedFrame.IsWhite(c)) > 100, "the image is not drawn");
+
+ // The window goes when the slide does.
+ host.Open("boxes.tiff");
+ Assert.Empty(host.Window.ImageWindows);
+ Assert.False(window.IsVisible);
+ });
+ }
+
+ [Fact]
+ public void AssociatedImage_IsReadOffTheUiThread_AndOpenedOnce()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("small.svs");
+ var readThreads = new ConcurrentQueue();
+ host.Window.ReadAssociatedImage = image =>
+ {
+ readThreads.Enqueue(Environment.CurrentManagedThreadId);
+ return image.Read();
+ };
+
+ // Asked twice before the first read is done (a double click, then Enter), then once more.
+ Task first = host.Window.ShowAssociatedImageAsync("thumbnail");
+ Task second = host.Window.ShowAssociatedImageAsync("thumbnail");
+ HeadlessSession.PumpUntil(() => first.IsCompleted && second.IsCompleted, "the image is shown");
+ Task third = host.Window.ShowAssociatedImageAsync("thumbnail");
+ HeadlessSession.PumpUntil(() => third.IsCompleted, "the image is shown again");
+
+ AssociatedImageWindow window = Assert.Single(host.Window.ImageWindows);
+ Assert.Same(window, first.Result);
+ Assert.Same(window, second.Result);
+ Assert.Same(window, third.Result);
+ Assert.True(window.IsVisible);
+ Assert.NotEmpty(readThreads);
+ Assert.DoesNotContain(Environment.CurrentManagedThreadId, readThreads);
+ Assert.True(readThreads.Count <= 2, $"read {readThreads.Count} times"); // not again once it is shown
+ });
+ }
+
+ [Fact]
+ public void Navigator_ClickCentersView()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("boxes.tiff");
+ Navigator navigator = host.Window.Navigator;
+ Rect image = navigator.ImageRect; // where the slide is drawn, in the navigator
+ Assert.True(image.Contains(new Point(10, 10)) && image.Contains(new Point(60, 50)));
+ double ratioX = 300 / image.Width; // level-0 pixels per navigator pixel
+ double ratioY = 250 / image.Height;
+ Viewport viewport = host.Window.Viewer.Viewport!;
+
+ host.Click(navigator, new Point(10, 10));
+
+ Assert.InRange(viewport.CenterX, ((10 - image.X) * ratioX) - ratioX, ((10 - image.X) * ratioX) + ratioX);
+ Assert.InRange(viewport.CenterY, ((10 - image.Y) * ratioY) - ratioY, ((10 - image.Y) * ratioY) + ratioY);
+
+ // Dragging follows the pointer.
+ Point from = navigator.TranslatePoint(new Point(20, 20), host.Window)!.Value;
+ Point to = navigator.TranslatePoint(new Point(60, 50), host.Window)!.Value;
+ host.Window.MouseDown(from, MouseButton.Left);
+ host.Window.MouseMove(to, RawInputModifiers.LeftMouseButton);
+ Assert.InRange(viewport.CenterX, ((60 - image.X) * ratioX) - ratioX, ((60 - image.X) * ratioX) + ratioX);
+ Assert.InRange(viewport.CenterY, ((50 - image.Y) * ratioY) - ratioY, ((50 - image.Y) * ratioY) + ratioY);
+ host.Window.MouseUp(to, MouseButton.Left);
+ });
+ }
+
+ [Fact]
+ public void Navigator_DrawsTheThumbnailAndTheView()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("boxes.tiff");
+ Navigator navigator = host.Window.Navigator;
+ Assert.NotNull(navigator.Thumbnail);
+ Assert.Same(navigator.Thumbnail, host.Window.Viewer.Thumbnail); // the view's picture for huge levels
+ Rect image = navigator.ImageRect;
+ Assert.Equal(300.0 / 250, image.Width / image.Height, 2);
+ Viewport viewport = host.Window.Viewer.Viewport!;
+ viewport.ZoomTo(100, 80, 100, 80);
+
+ RenderedFrame frame = host.Capture();
+
+ // The thumbnail: boxes.tiff's red box is in it.
+ Point topLeft = navigator.TranslatePoint(image.TopLeft, host.Window)!.Value;
+ int red = 0;
+ for (int y = (int)topLeft.Y; y < (int)(topLeft.Y + image.Height); y++)
+ {
+ for (int x = (int)topLeft.X; x < (int)(topLeft.X + image.Width); x++)
+ {
+ red += RenderedFrame.IsRed(frame[x, y]) ? 1 : 0;
+ }
+ }
+
+ Assert.True(red > 100, $"{red} red pixels in the thumbnail");
+
+ // The view: a rectangle round its level-0 bounds, scaled like the thumbnail.
+ (double left0, double top0) = viewport.ScreenToSlide(0, 0);
+ (double right0, double bottom0) = viewport.ScreenToSlide(viewport.ViewWidth, viewport.ViewHeight);
+ double scale = image.Width / 300;
+ double left = image.X + (left0 * scale), right = image.X + (right0 * scale);
+ double top = image.Y + (top0 * scale), bottom = image.Y + (bottom0 * scale);
+ Assert.True(right - left < image.Width * 0.75, "the view is not zoomed in");
+ foreach (Point edge in new[] { new Point(left, (top + bottom) / 2), new Point(right, (top + bottom) / 2), new Point((left + right) / 2, top), new Point((left + right) / 2, bottom) })
+ {
+ Point at = navigator.TranslatePoint(edge, host.Window)!.Value;
+ Assert.True(Near(frame, at, Navigator.ViewColor), $"no view rectangle at {edge} in the navigator");
+ }
+ });
+
+ static bool Near(RenderedFrame frame, Point at, Color color)
+ {
+ for (int y = (int)at.Y - 2; y <= (int)at.Y + 2; y++)
+ {
+ for (int x = (int)at.X - 2; x <= (int)at.X + 2; x++)
+ {
+ (byte r, byte g, byte b) = frame[x, y];
+ if (Math.Abs(r - color.R) <= 40 && Math.Abs(g - color.G) <= 40 && Math.Abs(b - color.B) <= 40)
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+ }
+
+ [Fact]
+ public void Selections_ZoomTo()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("boxes.tiff");
+ var selection = new Selection(20, 30, 240, 150);
+ host.Window.Viewer.Selections.Add(selection);
+ host.Window.Tabs.SelectedItem = host.Window.SelectionsTab;
+ HeadlessSession.Pump();
+ Assert.Single(host.Window.SelectionRows);
+
+ host.ClickCenter(FindButton(host.Window.SelectionsList, "Zoom to"));
+
+ Viewport viewport = host.Window.Viewer.Viewport!;
+ (double left, double top) = viewport.SlideToScreen(selection.X0, selection.Y0);
+ (double right, double bottom) = viewport.SlideToScreen(selection.X0 + selection.Width0, selection.Y0 + selection.Height0);
+ Assert.True(left >= -1 && top >= -1, $"({left}, {top}) is outside the view");
+ Assert.True(right <= viewport.ViewWidth + 1 && bottom <= viewport.ViewHeight + 1, $"({right}, {bottom}) is outside the view");
+ Assert.True(
+ Math.Abs(right - left - viewport.ViewWidth) <= 1 || Math.Abs(bottom - top - viewport.ViewHeight) <= 1,
+ $"{right - left} x {bottom - top} in a {viewport.ViewWidth} x {viewport.ViewHeight} view touches no side");
+
+ host.ClickCenter(FindButton(host.Window.SelectionsList, "Delete"));
+ Assert.Empty(host.Window.Viewer.Selections.Items);
+ Assert.Empty(host.Window.SelectionRows);
+ });
+ }
+
+ [Fact]
+ public void Open_UnopenableFile_ShowsErrorAndKeepsRunning()
+ {
+ string text = Path.Combine(Path.GetTempPath(), $"not-a-slide-{Guid.NewGuid():N}.txt");
+ File.WriteAllText(text, "This is not a slide.");
+ try
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("boxes.tiff");
+ host.WaitForTiles();
+ OpenSlide boxes = host.Window.Viewer.Slide!;
+ PropertyRow[] properties = host.Window.PropertyRows.ToArray();
+ Assert.False(host.Window.ErrorText.IsVisible);
+
+ host.Open("unopenable.tiff");
+
+ Assert.True(host.Window.ErrorText.IsVisible);
+ Assert.Contains("unopenable.tiff", host.Window.ErrorText.Text);
+ Assert.Same(boxes, host.Window.Viewer.Slide);
+ Assert.Equal(new SlideSize(300, 250), boxes.Dimensions); // not disposed
+ Assert.Equal(properties, host.Window.PropertyRows);
+ Assert.Equal($"{AppTitle} — boxes.tiff", host.Window.Title);
+ Assert.True(host.Capture().Count(RenderedFrame.IsRed) > 100, "the boxes are no longer drawn");
+
+ // A text file, and a file that does not exist.
+ host.OpenPath(text);
+ Assert.Contains(Path.GetFileName(text), host.Window.ErrorText.Text);
+ host.OpenPath(Path.Combine(Path.GetTempPath(), "missing.svs"));
+ Assert.Contains("missing.svs", host.Window.ErrorText.Text);
+ Assert.Same(boxes, host.Window.Viewer.Slide);
+
+ // A slide that opens clears the error.
+ host.Open("small.svs");
+ Assert.False(host.Window.ErrorText.IsVisible);
+ });
+ }
+ finally
+ {
+ File.Delete(text);
+ }
+ }
+
+ [Fact]
+ public void Open_UnexpectedFailure_ShowsErrorAndKeepsRunning()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("boxes.tiff");
+ OpenSlide boxes = host.Window.Viewer.Slide!;
+ // Not one of the failures OpenSlide reports for a bad file: a broken native library, say.
+ host.Window.OpenSlideFile = _ => throw new EntryPointNotFoundException("openslide_open is missing.");
+
+ host.Open("small.svs");
+
+ Assert.True(host.Window.ErrorText.IsVisible);
+ Assert.Equal("Cannot open small.svs: openslide_open is missing.", host.Window.ErrorText.Text);
+ Assert.Same(boxes, host.Window.Viewer.Slide);
+ Assert.Equal($"{AppTitle} — boxes.tiff", host.Window.Title);
+
+ // The same from a drop, whose handler nothing awaits.
+ host.Window.ErrorText.Text = null;
+ using var data = new DataTransfer();
+ data.Add(DataTransferItem.CreateFile(host.File("small.svs")));
+ foreach (RawDragEventType type in new[] { RawDragEventType.DragEnter, RawDragEventType.DragOver, RawDragEventType.Drop })
+ {
+ host.Window.DragDrop(new Point(600, 300), type, data, DragDropEffects.Copy);
+ }
+
+ HeadlessSession.PumpUntil(() => host.Window.ErrorText.Text is not null, "the failure is shown");
+ Assert.Equal("Cannot open small.svs: openslide_open is missing.", host.Window.ErrorText.Text);
+
+ host.Window.OpenSlideFile = OpenSlide.Open;
+ host.Open("small.svs");
+ Assert.False(host.Window.ErrorText.IsVisible);
+ Assert.Equal($"{AppTitle} — small.svs", host.Window.Title);
+ });
+ }
+
+ [Fact]
+ public void Properties_ClipboardFailure_ShowsErrorAndKeepsRunning()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("small.svs");
+ host.Window.SetClipboardText = _ => throw new InvalidOperationException("The clipboard is busy.");
+ ListBox list = host.Window.PropertyList;
+ PropertyRow first = host.Window.PropertyRows[0];
+ list.SelectedItems!.Add(first);
+ HeadlessSession.Pump();
+ Assert.True(((Control)list.ContainerFromItem(first)!).Focus());
+
+ // Ctrl+C runs an event handler that nothing awaits.
+ host.Window.KeyPressQwerty(PhysicalKey.C, RawInputModifiers.Control);
+ host.Window.KeyReleaseQwerty(PhysicalKey.C, RawInputModifiers.Control);
+ HeadlessSession.PumpUntil(() => host.Window.ErrorText.IsVisible, "the failure is shown");
+
+ Assert.Equal("Cannot copy the properties: The clipboard is busy.", host.Window.ErrorText.Text);
+ host.Open("boxes.tiff"); // still running
+ Assert.Equal($"{AppTitle} — boxes.tiff", host.Window.Title);
+ });
+ }
+
+ [Fact]
+ public void Open_ShowsOpeningInTheStatusBarUntilDone()
+ {
+ using var gate = new ManualResetEventSlim();
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Window.OpenSlideFile = path =>
+ {
+ gate.Wait(TimeSpan.FromSeconds(30));
+ return OpenSlide.Open(path);
+ };
+ try
+ {
+ Task open = host.Window.OpenAsync(TestFiles.Get("boxes.tiff"));
+ HeadlessSession.Pump();
+
+ Assert.True(host.Window.ActivityText.IsVisible);
+ Assert.Equal("Opening boxes.tiff…", host.Window.ActivityText.Text);
+
+ gate.Set();
+ HeadlessSession.PumpUntil(() => open.IsCompleted, "boxes.tiff is opened");
+ Assert.False(host.Window.ActivityText.IsVisible);
+ Assert.Equal($"{AppTitle} — boxes.tiff", host.Window.Title);
+
+ // Until the error, for a file that cannot be opened.
+ gate.Reset();
+ open = host.Window.OpenAsync(TestFiles.Get("unopenable.tiff"));
+ HeadlessSession.Pump();
+ Assert.Equal("Opening unopenable.tiff…", host.Window.ActivityText.Text);
+ gate.Set();
+ HeadlessSession.PumpUntil(() => open.IsCompleted, "unopenable.tiff is tried");
+ Assert.False(host.Window.ActivityText.IsVisible);
+ Assert.Contains("unopenable.tiff", host.Window.ErrorText.Text);
+
+ // File > Close while opening: the open is dropped, and so is its message.
+ gate.Reset();
+ open = host.Window.OpenAsync(TestFiles.Get("small.svs"));
+ HeadlessSession.Pump();
+ host.Window.CloseSlide();
+ Assert.False(host.Window.ActivityText.IsVisible);
+ gate.Set();
+ HeadlessSession.PumpUntil(() => open.IsCompleted, "small.svs is opened and dropped");
+ Assert.False(host.Window.ActivityText.IsVisible);
+ Assert.Null(host.Window.Viewer.Slide);
+ }
+ finally
+ {
+ gate.Set();
+ }
+ });
+ }
+
+ [Fact]
+ public void SwitchSlide_DoesNotShowOldTiles()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("boxes.tiff");
+ host.WaitForTiles();
+ OpenSlide boxes = host.Window.Viewer.Slide!;
+ Assert.True(host.Capture().Count(RenderedFrame.IsRed) > 100, "the boxes are not drawn");
+
+ host.Open("small.svs");
+ host.WaitForTiles();
+
+ int red = host.Capture().Count(RenderedFrame.IsRed);
+ Assert.True(red < 10, $"{red} red pixels after switching to small.svs");
+ Assert.Throws(() => boxes.Dimensions); // the old slide is closed
+ });
+ }
+
+ [Fact]
+ public void Title_ShowsFileName()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ Assert.Equal(AppTitle, host.Window.Title);
+
+ host.Open("boxes.tiff");
+ Assert.Equal($"{AppTitle} — boxes.tiff", host.Window.Title);
+
+ host.Open("small.svs");
+ Assert.Equal($"{AppTitle} — small.svs", host.Window.Title);
+
+ host.Window.CloseSlide();
+ Assert.Equal(AppTitle, host.Window.Title);
+ });
+ }
+
+ [Fact]
+ public void Shortcuts_UseThePlatformCommandKey()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ KeyModifiers command = host.Window.GetPlatformSettings()!.HotkeyConfiguration.CommandModifiers;
+ Assert.Equal(new KeyGesture(Key.O, command), host.Window.OpenMenuItem.HotKey);
+ Assert.Equal(new KeyGesture(Key.O, command), host.Window.OpenMenuItem.InputGesture);
+ Assert.Equal(new KeyGesture(Key.W, command), host.Window.CloseMenuItem.HotKey);
+ Assert.Equal(new KeyGesture(Key.W, command), host.Window.CloseMenuItem.InputGesture);
+
+ host.Open("small.svs");
+ RawInputModifiers modifiers = command switch
+ {
+ KeyModifiers.Meta => RawInputModifiers.Meta,
+ _ => RawInputModifiers.Control,
+ };
+ host.Window.KeyPressQwerty(PhysicalKey.W, modifiers);
+ host.Window.KeyReleaseQwerty(PhysicalKey.W, modifiers);
+ HeadlessSession.Pump();
+
+ Assert.Null(host.Window.Viewer.Slide);
+ Assert.Equal(AppTitle, host.Window.Title);
+ });
+ }
+
+ [Fact]
+ public void CloseSlide_ClearsTheWindow()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("small.svs");
+ host.WaitForTiles();
+ OpenSlide slide = host.Window.Viewer.Slide!;
+ host.Window.Viewer.Selections.Add(new Selection(1, 1, 4, 4));
+
+ host.Window.CloseSlide();
+
+ Assert.Null(host.Window.Viewer.Slide);
+ Assert.Throws(() => slide.Dimensions);
+ Assert.Empty(host.Window.PropertyRows);
+ Assert.Empty(host.Window.AssociatedImageRows);
+ Assert.Empty(host.Window.SelectionRows);
+ Assert.Null(host.Window.Navigator.Thumbnail);
+ Assert.Null(host.Window.Viewer.Thumbnail);
+ Assert.Equal("", host.Window.ZoomText.Text ?? "");
+ host.Capture(); // draws the empty window
+ });
+ }
+
+ [Fact]
+ public void Close_DisposesTheSlide()
+ {
+ OpenSlide slide = HeadlessSession.Run(() =>
+ {
+ var host = new WindowHost();
+ host.Open("boxes.tiff");
+ host.WaitForTiles();
+ OpenSlide opened = host.Window.Viewer.Slide!;
+ host.Dispose();
+ Assert.Null(host.Window.Viewer.Loader);
+ return opened;
+ });
+
+ Assert.Throws(() => slide.Dimensions);
+ }
+
+ [Fact]
+ public void Open_TwiceQuickly_ShowsTheLastSlide()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ Task first = host.Window.OpenAsync(TestFiles.Get("boxes.tiff"));
+ Task second = host.Window.OpenAsync(TestFiles.Get("small.svs"));
+ HeadlessSession.PumpUntil(() => first.IsCompleted && second.IsCompleted, "both slides open");
+
+ Assert.Equal($"{AppTitle} — small.svs", host.Window.Title);
+ Assert.Equal(new SlideSize(16, 16), host.Window.Viewer.Slide!.Dimensions);
+ Assert.False(host.Window.ErrorText.IsVisible);
+ });
+ }
+
+ [Fact]
+ public void Drop_OpensTheFirstFile()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ using var data = new DataTransfer();
+ data.Add(DataTransferItem.CreateFile(host.File("small.svs")));
+ data.Add(DataTransferItem.CreateFile(host.File("boxes.tiff")));
+ var at = new Point(600, 300);
+
+ host.Window.DragDrop(at, RawDragEventType.DragEnter, data, DragDropEffects.Copy);
+ host.Window.DragDrop(at, RawDragEventType.DragOver, data, DragDropEffects.Copy);
+ host.Window.DragDrop(at, RawDragEventType.Drop, data, DragDropEffects.Copy);
+ HeadlessSession.PumpUntil(() => host.Window.Viewer.Slide is not null, "the dropped slide opens");
+
+ Assert.Equal($"{AppTitle} — small.svs", host.Window.Title);
+ });
+ }
+
+ [Fact]
+ public void StatusBar_ShowsPointerZoomAndSizes()
+ {
+ HeadlessSession.Run(() =>
+ {
+ using var host = new WindowHost();
+ host.Open("boxes.tiff"); // 72 dpi (352.8 µm a pixel), no objective power
+ SlideView view = host.Window.Viewer;
+ Viewport viewport = view.Viewport!;
+ OpenSlide boxes = view.Slide!;
+ double? mppX = StatusFormatter.Number(boxes.Properties, OpenSlideProperties.MppX);
+ double? mppY = StatusFormatter.Number(boxes.Properties, OpenSlideProperties.MppY);
+
+ Point center = view.TranslatePoint(new Point(view.Bounds.Width / 2, view.Bounds.Height / 2), host.Window)!.Value;
+ host.Window.MouseMove(center);
+ (double X, double Y) position = view.PointerSlidePosition!.Value;
+ Assert.Equal(StatusFormatter.Coordinates(position.X, position.Y), host.Window.CoordinatesText.Text);
+ Assert.Equal(StatusFormatter.Zoom(viewport.Downsample, null), host.Window.ZoomText.Text);
+ Assert.DoesNotContain("×", host.Window.ZoomText.Text); // no magnification without an objective power
+ string viewSize = StatusFormatter.PhysicalSize(
+ viewport.ViewWidth * viewport.Downsample, viewport.ViewHeight * viewport.Downsample, mppX, mppY);
+ Assert.EndsWith(" mm", viewSize);
+ Assert.Equal("View: " + viewSize, host.Window.ViewSizeText.Text);
+ Assert.False(host.Window.SelectionSizeText.IsVisible); // no selection yet
+
+ // Off the slide (above it, in the fitted view), no coordinates.
+ (double _, double top) = viewport.SlideToScreen(0, 0);
+ Assert.True(top > 2, "the slide fills the view's height");
+ host.Window.MouseMove(view.TranslatePoint(new Point(view.Bounds.Width / 2, top / 2), host.Window)!.Value);
+ Assert.Equal("", host.Window.CoordinatesText.Text ?? "");
+
+ // A slide with an objective power shows the magnification; selections show their size.
+ host.Open("small.svs");
+ OpenSlide small = view.Slide!;
+ mppX = StatusFormatter.Number(small.Properties, OpenSlideProperties.MppX);
+ mppY = StatusFormatter.Number(small.Properties, OpenSlideProperties.MppY);
+ double? objective = StatusFormatter.Number(small.Properties, OpenSlideProperties.ObjectivePower);
+ Assert.Equal(20, objective);
+ viewport = view.Viewport!;
+ Assert.Equal(StatusFormatter.Zoom(viewport.Downsample, objective), host.Window.ZoomText.Text);
+ Assert.Contains("×)", host.Window.ZoomText.Text);
+ viewSize = StatusFormatter.PhysicalSize(
+ viewport.ViewWidth * viewport.Downsample, viewport.ViewHeight * viewport.Downsample, mppX, mppY);
+ Assert.Equal("View: " + viewSize, host.Window.ViewSizeText.Text);
+
+ view.Selections.Add(new Selection(2, 2, 8, 4));
+ Assert.Equal("Selection: " + StatusFormatter.PhysicalSize(8, 4, mppX, mppY), host.Window.SelectionSizeText.Text);
+ Assert.True(host.Window.SelectionSizeText.IsVisible);
+
+ // Zooming updates the zoom and the size of the view.
+ viewport.ZoomAt(viewport.ViewWidth / 2, viewport.ViewHeight / 2, 2);
+ Assert.Equal(StatusFormatter.Zoom(viewport.Downsample, objective), host.Window.ZoomText.Text);
+ Assert.Equal(
+ "View: " + StatusFormatter.PhysicalSize(viewport.ViewWidth * viewport.Downsample, viewport.ViewHeight * viewport.Downsample, mppX, mppY),
+ host.Window.ViewSizeText.Text);
+ });
+ }
+
+ private static Button FindButton(Control within, string content) =>
+ within.GetVisualDescendants().OfType