Skip to content

OpenSlideSharp 4.x: Avalonia desktop viewer - #5

Merged
IOL0ol1 merged 21 commits into
masterfrom
feature/plan4-viewer
Nov 18, 2026
Merged

IOL0ol1 merged 21 commits into
masterfrom
feature/plan4-viewer

Conversation

@IOL0ol1

@IOL0ol1 IOL0ol1 commented Nov 18, 2026 •

Copy link
Copy Markdown
Owner

Plan 4 of the OpenSlideSharp 4.x rewrite (see docs/superpowers/plans/2026-11-18-plan4-viewer.md): samples/OpenSlideSharp.Viewer, an Avalonia desktop viewer comparable to openslide-java's Demo (pan/zoom with tiled background loading, navigator, properties, associated images, rectangle selections, status bar), plus a --check mode used to smoke-test self-contained single-file builds on every platform.

Work in progress; commits land task by task with CI on every push.

An exception from the loaded callback was treated as a read failure and
stopped the loader for good, and one from a Failed handler escaped the
worker thread and ended the process. Both are now traced and swallowed,
and every Failed handler runs even if an earlier one throws.
TileLoader.IsDisposed is now public.

The dispose test waited 200 ms before releasing the blocked reads; it now
waits until Dispose has dropped the queued tile, and the loaders in the
loader tests are disposed with using.
…ooled

A TileImage now owns its buffer, which may come from a pool and be longer
than the tile, until ConsumePixels hands it to the UI layer to copy into a
bitmap or Dispose drops the tile. Either way the buffer goes back through
the release callback exactly once. The hand-over is atomic, so a tile
evicted on a loader thread while the UI thread copies it is still
released once, after the copy. A drawn tile then lives on as its bitmap,
which takes the place of its pixels in the cache budget.
…elections

SlideView draws the tiles of the level that suits the zoom per device
pixel, aligned to device pixels, and stands in for tiles not loaded yet
with cached tiles of coarser levels. Missing tiles are requested centre
first from the TileLoader; a frame never reads the slide, and loaded
tiles schedule one redraw at a time. Left drag pans, Shift drag draws a
selection, the wheel zooms at the pointer by 2^(1/4) a notch, and the
keys follow the plan (arrows/WASD, +/-, Z, 1, Space).

TileBitmapCache builds a tile's bitmap on its first draw from the pixels
the tile hands over, and disposes the bitmaps of evicted tiles before
each frame, so bitmap memory follows the cache budget. Tiles are read
into pooled buffers. TileGrid picks levels without a native call, by the
rule of openslide_get_best_level_for_downsample.

The rendering tests run on the Avalonia.Headless session API with Skia,
not Avalonia.Headless.XUnit, which needs xunit.v3 3.x.
…eView

- When a visible tile is missing and no cached coarser tile stands in for
  it, the view requests the tiles two levels up (capped at the coarsest
  level) before the target tiles, so a slide just opened, or a part of it
  not seen yet, shows a low-resolution image quickly and is then replaced.
- A read failure now belongs to the slide rather than to the loader: a
  loader rebuilt after the view leaves the visual tree and comes back
  neither reads the slide again nor raises LoadFailed again. Setting the
  slide again tries it again.
- A drag follows the pointer that started it. Presses, moves and releases
  of other pointers (a second finger, say) no longer move the pan anchor
  or the selection start.
- LoaderThreads: an internal hook for the number of loader threads, used
  by the tests.
…ages and selections

- MainWindow: File (Open..., Close, Exit) and View (Fit, 1:1, Center)
  menus; a resizable left pane with the navigator and Properties /
  Associated images / Selections tabs; the SlideView; a status bar; the
  title "OpenSlide Viewer - <file name>" (with an em dash).
- OpenAsync opens the slide, its sorted properties and the navigator's
  picture on a background thread. A file that cannot be opened is reported
  in red in the status bar and the current slide stays. On success the view
  takes the new slide before the old one is disposed, and the selections,
  properties, associated images and their windows are replaced. An open
  overtaken by a newer one (or by Close) is dropped and disposed.
- Slides open from the first command-line argument, File > Open (the
  storage provider's file picker) or by dropping files (the first one).
- Navigator: the thumbnail (GetThumbnail(256, 256), or the thumbnail
  associated image when the level it would read is over 16 Mi pixels or
  reading fails) with the view outlined; a click or drag centres the view.
- Properties: a two-column list sorted by key; the copy key and a context
  menu copy the selected rows (key<TAB>value) or their values.
- Associated images: a double click (or Enter) opens a window titled with
  the image name, showing the premultiplied BGRA pixels scaled uniformly.
- Selections: one row each, with Zoom to and Delete buttons.
- Status bar (StatusFormatter): level-0 coordinates under the pointer (on
  the slide only), the zoom with the magnification when the slide has an
  objective power, and the physical size of the view and of the current
  selection when it has mpp.
…Windows

The viewer is a GUI (WinExe) program on Windows, so a console that starts
it does not give it a standard output handle and --check printed nothing
unless the output was redirected.

- ParentConsole: when --check runs on Windows without a standard output
  handle, attach to the parent process's console (AttachConsole with
  ATTACH_PARENT_PROCESS) and re-open Console.Out on it, in the console's
  code page (UTF-8 without a byte order mark). A redirected output (pipe or
  file) is a valid handle and is left alone. Console.IsOutputRedirected
  cannot make this decision: it reports a missing handle as redirected.
- Only the --check path calls it; the window path is unchanged.
- Tests: the decision (no handle or INVALID_HANDLE_VALUE on Windows only),
  and, on Windows, the built GUI-subsystem executable printing --check to a
  redirected output with exit code 0.
- A single-file publish of the viewer is one file: the native libraries
  (OpenSlide, SkiaSharp, HarfBuzzSharp, ANGLE on Windows, Avalonia.Native
  on macOS) are bundled with IncludeNativeLibrariesForSelfExtract and
  extracted on first start, a self-contained bundle is compressed (51 MB
  instead of 107 MB for win-x64), and symbols and XML documentation stay
  out of the publish folder.
- eng/Test-Packages.ps1 (packing and -SkipPack runs, so the package and
  package-unix jobs): publish the viewer self-contained as one file for the
  host's RID (win-x64, linux-x64, linux-arm64, osx-arm64 or osx-x64, picked
  like eng/Get-OpenSlide.ps1 does) with OpenSlideSharp.runtime from the
  local feed, assert that the publish folder holds only the executable, run
  --check on small.svs (exit code 0, slide=16x16) with a fresh bundle
  extraction directory, and assert that OpenSlide, SkiaSharp and HarfBuzzSharp
  were extracted from the bundle.
…ained publish

- README: a short "Desktop viewer" section with how to run it and the
  shortcuts.
- samples/OpenSlideSharp.Viewer/README.md: features, shortcuts, no ICC
  conversion, the Windows crash on corrupt tiles, --check (output, exit
  codes, and how to wait for the exit code in cmd and PowerShell), and the
  self-contained single-file publish that the GitHub Releases attach for
  win-x64, linux-x64 and osx-arm64.
Setting another slide (or File > Close, or closing the window) disposed the
loading pipeline and waited up to 5 seconds for the old slide's reads in
flight, freezing the UI thread on a slow disk or network share.

- SlideView's loaders now have a DisposeTimeout of 0. A read that outlives the
  pipeline is harmless: its native call holds a lease on the slide's handle,
  so closing the slide meanwhile defers openslide_close until it returns, and a
  read that starts after it fails quietly in the disposed loader; its tile is
  dropped by the disposed loader or cache; the callbacks only post a redraw or
  check that their slide is still the current one. The reasoning is written
  next to the setting.
- The read count lives with the slide's state, so a late read of the old slide
  no longer counts for the new one.
- Test: switching while reads of the old slide hang returns in under 200 ms;
  once the old slide is closed and the reads resume, nothing is reported or
  cached and the new slide loads.
…ways ends

When the tiles in view did not fit in the tile cache, each frame asked for
every missing tile, each tile read evicted another one in view, and that one
was asked for again by the next frame: the view flickered and read without
end, and the UI thread sorted up to about 10^5 keys a frame. This happened
with 4:1 pyramids (SVS, NDPI, SCN) on high-DPI screens, where nearly 4 level
pixels fall on each device pixel, and with slides of one or few large levels
zoomed out.

- A frame draws from, and asks for, at most TileLimit tiles of its level: half
  the cache budget in 256 x 256 tiles (512 with the default 256 MiB).
- The level is the one that suits the zoom, unless its tiles in view and
  their coarse stand-ins would be more than that; then a coarser level is
  drawn, scaled up.
- When even the coarsest level has more tiles than that, the frame takes the
  tiles nearest the centre of the view. NearestTiles finds them by merging
  the rows, each walked outwards from the column nearest the centre, so the
  work grows with the limit and the number of rows, not with the tiles in
  view, and nothing but at most TileLimit tiles is ever sorted.
- For such slides the navigator's thumbnail (SlideView.Thumbnail, set by
  MainWindow) is drawn stretched under the tiles, so the whole slide shows.
- A tile whose bitmap cannot be built (no memory, say) is dropped from the
  cache (TileCache.Remove) and read again, instead of staying blank, and the
  exception no longer escapes Render.
- TileGrid: VisibleRange, VisibleCount, TileCount, LevelSize.
- Test hooks: LevelLayout (levels instead of the slide's), BitmapFactory,
  MostRequestedTiles.
- Tests: with a cache smaller than the tiles in view, a 4:1 pyramid at
  3.9 level pixels per device pixel on a 200% screen, and a single
  100,000 x 80,000 level, frames settle (no more reads) after a bounded number
  of reads, no frame asks for more than TileLimit tiles, and the view is
  covered (by the thumbnail where the tiles are not drawn); NearestTiles
  matches the full centre-first order; a failed bitmap is read again.
… in progress

An exception thrown out of an async void event handler ends the process. The
open handlers only caught the failures OpenSlide reports for a bad file, and
the copy handlers caught nothing, so a broken native library
(EntryPointNotFoundException, BadImageFormatException), a busy clipboard, a
file picker that failed or running out of memory closed the viewer.

- OpenAsync reports any exception in the status bar ("Cannot open <file>:
  <reason>") and keeps the slide shown; Show closes a slide the view could not
  take and lets OpenAsync report it.
- The handlers of File > Open, drop, the copy key and menu items and the
  associated images list run their work through RunHandler, which shows
  whatever it throws in the status bar.
- While a slide opens, the status bar says "Opening <file name>…" until the
  slide is shown or the error is; a newer open or File > Close takes it over.
- Test hooks: OpenSlideFile (opens the slide file) and SetClipboardText.
- Tests: an open that fails with an unexpected exception, directly and from
  a drop, and a copy to a clipboard that throws, show the error and the viewer
  goes on; the "Opening" message shows until the slide, the error, or Close.
…ndow

- ShowAssociatedImageAsync reads the image on a background thread, so a large
  macro image no longer freezes the window, and reports any failure in the
  status bar (unless the slide changed meanwhile, when the result is dropped).
- A window that already shows the image is brought to the front instead of
  opening another one, also when the image was asked for twice before the
  first read finished (a double click, then Enter).
- AssociatedImageWindow.ImageName; test hook ReadAssociatedImage.
- Tests: three requests for the same image read it off the UI thread and give
  one window; the double-click test waits for the window to open.
File > Open and Close had Ctrl+O and Ctrl+W on every platform. Their shortcuts
now take the platform's command modifiers (HotkeyConfiguration.CommandModifiers):
Ctrl on Windows and Linux, Cmd on macOS. The view's own keys are unchanged.

Test: the menu items' gestures use the platform's command key, and pressing
it with W closes the slide.
The plan 3 and plan 4 steps that keep a Python venv and a screenshot outside the
repository now say they go in a temporary directory.
A single-file publish of the viewer was one executable with OpenSlide (LGPL),
the libraries linked into it, Skia, HarfBuzz, ANGLE, Avalonia, the .NET runtime
and the Inter font inside it, and none of their license notices.

- Every publish of the viewer now puts licenses/ next to the executable (kept
  out of a single-file bundle):
  - openslide-bin/: the licenses/ and VERSIONS.md of OpenSlideSharp.runtime
    (referenced with GeneratePathProperty), or of artifacts/native without it;
  - <package id>/: the LICENSE* and THIRD-PARTY-NOTICES* files of each NuGet
    package with a file in the publish, the .NET runtime pack of a
    self-contained publish among them;
  - OpenSlideSharp/LICENSE, THIRD-PARTY-NOTICES.txt (the bundled components,
    their licenses and upstream URLs, with the Avalonia and Inter licenses,
    which their packages do not ship) and SOURCE.md (OpenSlide's source is
    the openslide-bin source archive of the same build; OPENSLIDE_LIBRARY_PATH
    makes the viewer load another OpenSlide build).
- PublishOnlyTheExecutable is now PublishWithoutSymbols: it still leaves the
  .pdb and .xml files out.
- eng/Test-Packages.ps1 asserts that the publish folder holds exactly the
  executable and licenses/, with THIRD-PARTY-NOTICES.txt, SOURCE.md,
  openslide-bin/VERSIONS.md and OpenSlide's license, and still runs --check.
It was a second DrawTiles overload, next to the one Render calls.
- README: the "Desktop viewer" section keeps how to run the viewer and points
  to its README for the shortcuts, --check and the publish, instead of
  repeating the shortcut table.
- samples/OpenSlideSharp.Viewer/README.md: a short feature list, the shortcut
  table once (Cmd on macOS for Open and Close), --check in two paragraphs with
  the Windows console note, the publish (the executable and licenses/; old
  extraction folders under %TEMP%\.net or ~/.net can be deleted), a Licenses
  paragraph (what licenses/ holds, SOURCE.md and OPENSLIDE_LIBRARY_PATH; the
  planned release builds will ship the folder as one archive per platform)
  and the known issue on Windows.
@IOL0ol1
IOL0ol1 marked this pull request as ready for review November 18, 2026 10:52
@IOL0ol1
IOL0ol1 merged commit df839f7 into master Nov 18, 2026
10 checks passed
@IOL0ol1
IOL0ol1 deleted the feature/plan4-viewer branch November 18, 2026 10:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant