The image viewport
egui-pop-viewport (the facade’s viewport feature, re-exported as
egui_pop::viewport) shows an image the application computes, in tiles:
pan and zoom in physical pixels (100 % is one image pixel per screen
pixel, in every window), a proxy first and exact tiles after, a display
transform where colour management plugs in, overlays with handles,
before and after, a pixel readout. The crate also has thumbnails in a
virtualised grid and the image tools: a histogram, a curve editor,
colour wheels, a zoom control and a navigator (see
Image tools), and the tools’ cursors and a loupe (see
Cursors and the loupe). What the wheel, a pinch and each
button do on it follows the pointer profile, and a double click may ask
the application to leave the view (Signal::Leave): see
Pointer gestures and profiles. The
on_double_click hook replaces that double click: a hook that handles
it returns its own view without calling the default action it is
given; one that passes it on calls the default, which fits, zooms or
sends Signal::Leave as the profile says, exactly as without a hook.
cargo add egui-pop --features viewport
The application implements the tile source; the viewport asks, never waits, and says what changed with signals.
use egui_pop::egui;
use egui_pop::viewport::source::{Pixels, Tile, TileRequest, TileSink, TileSource};
use egui_pop::viewport::{Signal, View, Viewport, ViewportState};
/// A flat mid-grey image, answered at once (a real source works on a
/// thread and delivers through the sink when done).
struct Grey {
sink: TileSink,
}
impl TileSource for Grey {
fn size(&self) -> Option<[u32; 2]> {
Some([6000, 4000])
}
fn request(&self, requests: Vec<TileRequest>) {
for r in requests {
let n = r.size[0] as usize * r.size[1] as usize;
// Scene-referred floats: the display transform runs on them.
self.sink.deliver(Tile::answer(&r, Pixels::Scene(vec![0.18; n * 4])));
}
}
}
fn draw(ui: &mut egui::Ui, state: &mut ViewportState, view: &mut View, source: &Grey) {
let out = Viewport::new("main").source(source).readout(true).show(ui, state, view);
for signal in out.signals {
if let Signal::View { view, .. } = signal {
// Keep the view in the document, one undo step per gesture...
let _ = view;
}
}
}
let state = ViewportState::new();
let source = Grey { sink: state.sink() };
let _ = (draw, source);
A source may also answer the pixel readout (TileSource::readout, then
TileSink::readout). Requests the viewport stops wanting get their
cancel token set.
The viewer example (cargo run -p egui-pop-viewport --example viewer,
a Mandelbrot set computed on a thread) and the gallery’s viewport page
show it in an application:
Overlays
The application owns its overlays (overlay::Overlay: a shape in image
pixels, its handles, a label) and gives them to the viewport each frame
(Viewport::overlays). Dragging a handle is one gesture
(Signal::Handle, begin, update, end, or cancel on Escape), which the
application applies to its own data (Overlay::apply does it for the
standard shapes); a double click resets (Signal::HandleReset), the
wheel adjusts (Signal::HandleWheel). The before_handle hook may veto
or snap a move; it gets where the handle was when the gesture began
(HandleMove::start), where it is, where the pointer would put it and
the keys held (modifiers). A click on a handle is
Signal::HandleClick (select its shape), a click on an outline away
from the handles Signal::EdgeClick with the segment and the nearest
point (add a point there; overlay::hit_edge numbers the segments).
Lines and handle outlines are drawn in whole physical pixels at the
window’s scale (scale::stroke), so they stay sharp at 125 % and 150 %.
Shapes are points, lines, boxes, circles, ellipses (Shape::Ellipse,
sized along its axes and turned by its handles) and paths. Each overlay
has a style: selected() (a heavier line in the handle colour),
faint() (half-transparent, handles included) and dashed(). An
overlay may carry handles of its own (Overlay::handles), among them
HandleKind::Control, a Bézier control drawn as a small diamond, whose
moves the application applies. Two paint hooks extend the drawing:
under_overlays between the image and the overlays (a mask’s tint),
after_paint above the handles.
An overlay’s label (Overlay::label) is drawn as a label over an
image: the kit’s viewport-label component, a translucent pill the
image shows through, whose text reads over the image’s brightest and
darkest pixels alike. overlay::paint_label draws one anywhere, for a
HUD’s readout or a name on an image:
use egui_pop::viewport::overlay::paint_label;
// Above and right of the point, as an overlay's label sits.
paint_label(&painter, point + egui::vec2(8.0, -8.0), egui::Align2::LEFT_BOTTOM, "Crop");
The X, Y and Z axes take the theme’s palette.axis.x, .y and .z
(Tokens::of(ctx).palette.axis), red, green and blue, each seen at 3:1
on viewport.background.
use egui_pop::viewport::overlay::{Overlay, Shape};
let overlays = vec![
Overlay::new("crop", Shape::Rect([100.0, 100.0, 900.0, 700.0])).selected(),
Overlay::new(
"vignette",
Shape::Ellipse { center: [500.0, 400.0], radii: [400.0, 250.0], rotation: 0.0 },
)
.dashed()
.faint(),
];
let _ = overlays;
Device tiles
A source that renders on the GPU hands the viewport tiles that already
live on the render device (feature wgpu, module device): nothing
crosses the CPU, nothing is uploaded, and the GPU path’s shader reads
them in place. The device is the one the GPU path was installed with
(gpu::install, eframe’s render state): the source’s engine runs on
that device (eframe’s RenderState hands out its device and queue)
and answers a request with a DeviceTile through
TileSink::deliver_device, after submitting the work that writes it.
use egui_pop::viewport::device::{BufferLayout, DeviceTile};
use egui_pop::viewport::gpu::egui_wgpu::wgpu;
use egui_pop::viewport::source::{Pixels, TileRequest, TileSink};
/// An engine's result for one request: `rgba` holds the scaled image
/// as packed `f32` RGBA rows of `width` pixels, on the render device;
/// `image` owns it on the engine's side.
fn hand_over(
sink: &TileSink,
device: &wgpu::Device,
request: &TileRequest,
rgba: wgpu::Buffer,
width: u32,
image: std::sync::Arc<dyn std::any::Any + Send + Sync>,
) {
let [x, y] = request.origin;
let tile = DeviceTile::buffer(device, rgba, BufferLayout::packed(width, 4))
// The request's pixels start there in the image.
.origin([x as u32, y as u32])
// Asked only if the viewport refuses the tile, on this thread.
.fallback(|| Option::<Pixels>::None)
// Held while the viewport holds the tile: the engine's image,
// and the charge it carries in its memory accounting.
.keep(image);
sink.deliver_device(request, tile);
}
let _ = hand_over;
- The resource: a 2D texture of any float-sampled format
(
Rgba16Float,Rgba32Float,Rgba8Unorm,Rgba8UnormSrgb…) withTEXTURE_BINDINGusage (DeviceTile::texture), or a storage buffer off32values withSTORAGEusage (DeviceTile::buffer): one to four channels a pixel, rowsrow_floatsapart, from a byteoffset(BufferLayout). The viewport binds only the rows a tile covers, so a tile may be cut from a whole image’s buffer (DeviceTile::origin). - Buffers need fragment storage: the tile shader reads a buffer in
its fragment stage, which WebGL 2 (and some downlevel adapters) cannot
do: no
DownlevelFlags::FRAGMENT_STORAGE, andmax_storage_buffers_per_shader_stageis 0.gpu::installchecks both (gpu::reads_fragment_storage) and, without them, builds no buffer binding or pipeline (creating one would fail wgpu’s validation); a buffer device tile is then refused withDeviceTileError::BuffersUnsupportedand served from its fallback. Texture device tiles and uploaded tiles work on every adapter. A producer readsgpu::render_device(ctx).buffers(or theviewportcollector’stiles.device.buffers) and delivers textures or host tiles where it is false. - The colour:
Encoding::Scene(the default) isPixels::Sceneon the device, linear values in the working space: the display stage of the viewport’s display transform (its matrix, clamp and transfer, for the window’s target) runs on them in the shader, as on uploaded tiles, and a new target or transform needs no new tile.Encoding::DisplayisPixels::Display: sRGB-encoded values shown as they are (an…Srgbtexture is read back to its encoded values). A transform that overridesDisplayTransform::apply(a LUT the stage cannot express) is not run on device tiles: deliver display values then. Alpha is not drawn, as on the GPU path. - The check: a tile is checked on the delivering thread against the
render device installed now (
TileSink::render_device, read from the viewport’s context when called), and again when the interface takes it in. One made on another device, without a GPU path, or whose resource does not fit (usage, format, size, binding limits) is refused:ViewportState::last_errorsays why (DeviceTileError), therefusedcounter counts it, and the tile’s fallback pixels, when it offers some (DeviceTile::fallback, called only then), take the usual CPU or upload path; without, the request fails.TileSink::render_devicetells a source’s thread which device to use before it renders. - Where the fallback runs: on the thread that calls
deliver_device, never on the interface thread (unless the source delivers from it). A tile refused when the interface takes it in (the render device changed after the source’s check) is dropped, its fallback not called, and its request made again through the source’srequest, as for any tile the viewport no longer holds: the source then checks against the new device and falls back on its own thread. - The order of install and first frame: install the GPU path
(
gpu::install) before the firstViewport::show, as eframe’s creation context allows (cc.wgpu_render_state); the first frame’s requests then take the device path. Installed later, the requests made before it are refused (no GPU path) and served from their fallback pixels, or fail without them; when the render device appears (or changes), the viewport asks for those tiles again, and they come back as device tiles, the fallback shown until then. A failed request is asked for again on the next frame anyway. - What a tile keeps alive:
DeviceTile::keepattaches a value (the producer’s image, with the charge it carries in a GPU memory ledger) that the viewport holds exactly as long as it holds the tile, waiting or shown, and drops when the tile is replaced, invalidated, evicted or refused, or the viewport’s state is dropped. On the GPU path a tile released is dropped at the next paint, once its binding is gone (a tile replaced before its first paint is never bound). The viewport’swgpu::Bufferorwgpu::Textureclone keeps the memory alive anyway; the kept value makes the producer’s accounting see it. - The counters:
ViewportState::transferscounts the tile pixels copied to the GPU where the copy happens (an egui texture loaded, a GPU path texture written at the paint), and the device tiles bound in place (bound, no byte);frame_transfersis the last whole frame, its paint included. Theviewportcollector shows both (tiles.uploads), withtiles.last_error, what the render device takes (tiles.device:nullwithout a GPU path,buffers), and thedeviceandrefusedcounters intiles.stats. A view drawn from device tiles alone copies zero bytes a frame. - What draws them: everything that draws the tiles: the window, the
before and after sides, the image surface on Wayland, the loupe
(which draws the tiles again, magnified), and what the
under_overlayshook paints over them (a mask’s tint).
The tests in crates/egui-pop-viewport/tests/device_tiles.rs make
textures and buffers on the test harness’s device and check the picture
against the CPU path and the counters at zero; the gpu_tiles example’s
gpu-render intake measures the hand-over on a real GPU.
Wide gamut and HDR
A window’s surface has an encoding (display::DisplayTarget: primaries,
transfer, headroom, format); the viewport’s display stage converts the
scene into it, on the GPU (its shader) and on the CPU
(Stage::encode): Display P3 and BT.2020 primaries (matrices computed
from the chromaticities), the sRGB curve, extended linear (scRGB) and
extended sRGB, SMPTE ST 2084 (PQ) and BT.2100 HLG.
An application says what it wants for a window; the viewport draws for what the surface carries, and says why when that is less:
use egui_pop::egui;
use egui_pop::viewport::display::{self, ColorSpace, DisplayTarget, SurfaceFormat, TargetSource};
let ctx = egui::Context::default();
display::want(&ctx, egui::ViewportId::ROOT, DisplayTarget::display_p3());
// Under eframe the surface is 8-bit sRGB: sRGB is drawn, with the reason.
let r = display::resolve(&DisplayTarget::display_p3(), &DisplayTarget::srgb(), true);
assert!(!r.faithful());
assert_eq!(r.drawn.color_space(), Some(ColorSpace::Srgb));
println!("{}", r.reason().unwrap());
// A host that configured an extended sRGB surface on half floats says so,
// and P3 (or HDR) is drawn faithfully.
let surface = DisplayTarget::for_color_space(
ColorSpace::ExtendedSrgb,
SurfaceFormat::Rgba16Float,
4.0,
TargetSource::Tagged,
);
display::set_target(&ctx, egui::ViewportId::ROOT, surface);
assert!(display::resolve(&DisplayTarget::display_p3(), &surface, true).faithful());
What works where:
| Surface | Who configures it | Wide gamut / HDR |
|---|---|---|
| 8-bit sRGB | eframe 0.36, every platform | no: sRGB drawn, the reason given |
| extended sRGB, half floats | a host with its own surface (gpu::choose_surface), where wgpu offers it (Metal on macOS; Vulkan drivers exposing EXTENDED_SRGB_NONLINEAR) | yes, and egui’s interface stays right |
| scRGB, HDR10 (PQ), HLG | a host with its own surface (SurfacePolicy::Any): DX12 and Vulkan on Windows, Metal | the image yes; egui’s interface is written sRGB-encoded, so the host composes it itself |
| any, CPU path | (no GPU path installed) | no: tiles are 8-bit sRGB textures |
gpu::installrecords what eframe configured (its format, wgpu’s default colour space);gpu::install_for_surfaceis for a host that configured its surface with another colour space, andgpu::choose_surfacepicks the format and colour space to configure for a wanted target among the surface’s capabilities.ViewportState::display_resolutiongives what the last frame was drawn for; the debug bridge’sviewportcollector shows it, and thebefore_displayhook may veto (draw sRGB) or redirect (a soft proof) it.- Why eframe cannot do more today, and what is missing on Wayland, is in Upstream workarounds.
The gallery’s display page shows the resolution for each wish and
surface, and the transfers’ curves.
Wide gamut on Wayland
On Wayland, the image can get a surface of its own while the interface
stays the 8-bit sRGB eframe configures (image_surface, feature
wayland, on by default; the research behind it is in
wayland-colour.md). The viewport draws its image
into a subsurface below the main window, presented just before the
window in the same compositor frame, and punches a transparent hole in
the interface where the image is: overlays, menus and tooltips are drawn
over it as before. The subsurface is tagged through
wp_color_management_v1 with the wanted encoding (BT.2020 with a 2.2
power, the encoding a compositor maps to its screen), or presented in a
colour space the driver declares when the driver holds the surface’s
colour itself.
use egui_pop::egui;
use egui_pop::viewport::display::{self, DisplayTarget, Primaries, Transfer};
use egui_pop::viewport::gpu::{self, egui_wgpu};
use egui_pop::viewport::image_surface::{self, Offer, Route, raw_window_handle as rwh};
/// At start-up: `window` is eframe's creation context, its main window
/// built with `ViewportBuilder::with_transparent(true)`.
fn wide_gamut(
ctx: &egui::Context,
rs: &egui_wgpu::RenderState,
window: &(impl rwh::HasWindowHandle + rwh::HasDisplayHandle),
) {
gpu::install(ctx, rs);
let offer = image_surface::install(
ctx,
rs,
window,
image_surface::Options { transparent_window: true },
);
if let Some(why) = offer.unavailable {
eprintln!("no image surface: {why}");
}
let rec2020 = DisplayTarget {
primaries: Primaries::Bt2020,
transfer: Transfer::Gamma22,
..DisplayTarget::srgb()
};
display::want(ctx, egui::ViewportId::ROOT, rec2020);
}
// Where the image goes is plain code, tested with fake compositors.
let rec2020 = DisplayTarget {
primaries: Primaries::Bt2020,
transfer: Transfer::Gamma22,
..DisplayTarget::srgb()
};
let x11 = Offer::unavailable("not a Wayland window (X11 or another system)");
assert_eq!(image_surface::negotiate(&rec2020, &x11).route, Route::Window);
| Compositor (Mesa Vulkan driver) | The image | Why |
|---|---|---|
| KWin 6.3+, sway (wlroots 0.19+), Weston 15+ with colour management | tagged by egui-pop: BT.2020, gamma 2.2 (10 bits when offered) | the compositor does not announce the srgb transfer, so the driver leaves the subsurface’s colour alone |
| GNOME 48+, Hyprland 0.48+ | Display P3, declared by the driver | the compositor announces srgb + srgb to the driver, which then holds every surface’s colour-management object; a second one is a fatal protocol error, so egui-pop does not tag |
without wp_color_manager_v1, X11, Windows, macOS | sRGB, on the window | said by display::Resolution::reason |
| an opaque window, a secondary window | sRGB, on the window | said |
image_surface::negotiatedecides from anOffer(the colour manager’s announcements, the subsurface’s formats and colour spaces);display::targetthen answers the image surface’s target, andFallback::Unavailablecarries why the image stayed sRGB.- The
viewportcollector’simage_surfacefield shows the route, the compositor’s announcements, each image surface (its place, tag and configuration) and the compositor’s preferred image description for the window (its primaries, transfer, luminances and target volume), re-read when the window moves to another screen. EGUI_POP_IMAGE_SURFACE=offturns it off;=no-tagkeeps the driver’s colour spaces only (for a driver that would hold the colour of surfaces beyond Mesa’s rule).- Per window: each window drawing the image has its own image surface,
negotiated for what that window wants (
display::want), set up from its handles (image_surface::install_window, or the first frame it draws onceset_window_sourcesays where handles are read) and freed when it closes (close_window, or once egui no longer knows the window).windows.listshows each window’s (surface: route, format, colour space, why). egui’s interface keeps egui-wgpu’s one format. - Detached panels’ windows: with
AppBuilder::transparent_panel_windows, built transparent on Wayland (opaque elsewhere, each saying why inwindows.list’stransparency); their handles are paired by the runner, or by a host running its own loop throughrunner::host(windows.list’shandles). - Limits: a window whose handles are known; a transparent window; the subsurface is placed on whole logical pixels (at a fractional scale its pixels may sit up to one pixel off the interface’s); the perceptual intent (the one every compositor takes).
Checking it on a screen (automation has no colour-managed Wayland session):
- In a Wayland session with colour management (KWin 6.3 or later is
the reference: the tagged route), on a wide-gamut screen with its
profile set in the display settings, run
cargo run -p egui-pop-gallery -- --wide-gamut --page viewport. A missing image surface is printed on stderr at start-up. - Open the
displaypage: “Image surface” shows the route (taggedon KWin,wsion GNOME), the image’s encoding, why when less, what the compositor announces and its preferred description. Back on theviewportpage, the image must look exactly as it does without--wide-gamut(the demo’s colours are within sRGB: the compositor maps the BT.2020 encoding back to them), with no seam or offset at its edges, and overlays, the before/after split and menus drawn over it. Pan, zoom and resize the window: the image follows in the same frame as the interface. WAYLAND_DEBUG=1 cargo run -p egui-pop-gallery -- --wide-gamut --page viewport 2>&1 | grep -E 'wp_color|wl_subsurface|set_image_description'shows one subsurface per viewport,set_primaries_named(6)(BT.2020) andset_tf_named(2)(gamma 2.2), andset_image_descriptionon the subsurface (not on the window’s surface).- In Helios,
helios doctor displayprints what the compositor announces; it should agree with the display page. With the Wide-gamut preview setting on, a test chart with colours outside sRGB (a saturated P3 or BT.2020 green) shows them distinct where the sRGB preview clips them.
The contract
The family “Image viewport” (ADR 0027).
Owns: the view model and mapping, tile sources and the cache, the GPU path, the display transform, the Wayland image surface, gestures, hooks, cursors, the loupe, overlays in image coordinates, navigation, the debug collector, a demo source.
Refuses: decoding image formats; colour management beyond the display transform; raw development. The source computes pixels, the viewport asks and draws.
The modules the sections above do not name:
| Module | What it is |
|---|---|
egui_pop_viewport::tiles | The tile cache’s limits and counters: TILE_SIZE, DEFAULT_BUDGET, DEFAULT_SETTLE, UploadBudget, UploadReport, Transfers, Device, and the scales (proxy_scale, exact_scale) |
egui_pop_viewport::thumbnail | A re-export of egui_pop_core::thumbnail (Thumbnails) |
egui_pop_viewport::tokens | ViewportTokens: the viewport.* colours of the installed theme (background, frame, grid, guides, handles, cursors) |
egui_pop_viewport::debug | The viewport collector for the debug bridge |
The tile cache. Each frame, for each side shown, the cache takes in
what the source delivered (dropping answers no longer wanted, marking a
changed region’s tiles stale) and uploads it within the upload budget,
the visible area’s tiles first; it wants the proxy (the whole image at a
power of two at or below the fit scale) and, once the view has been
still for DEFAULT_SETTLE seconds, the exact tiles of what is visible;
asks for what it lacks and cancels what is no longer wanted; draws the
proxy, then the exact tiles over it, stale tiles staying until their
replacements come; and evicts the least recently drawn tiles past the
texture budget, never one drawn this frame. A tile is never larger than
the device’s largest texture side. The limits are the state’s:
use egui_pop::viewport::ViewportState;
use egui_pop::viewport::tiles::UploadBudget;
let mut state = ViewportState::new();
state.set_texture_budget(128 << 20);
state.set_upload_budget(UploadBudget::tiles(8));
state.set_tile_size(512);
The debug collector. Register egui_pop_viewport::debug::collector
on the bridge; its viewport snapshot lists every viewport drawn (view,
mapping, hooks set and what they decided, the last signals, the tiles,
the bytes their uploads copied, the device tiles), and its set_view
action moves a viewport as a command would, through its before_view
hook, on the next frame.
use egui_pop::core::debug::DebugBridge;
let mut bridge = DebugBridge::with_core_collectors();
bridge.register(egui_pop::viewport::debug::collector()).unwrap();
States and failure: a source that never answers leaves its requests outstanding (the collector’s tiles say how many) and nothing drawn where its tiles would be; a failed device request falls back to uploaded tiles (see Device tiles); a view larger than the texture budget still shows whole, the budget only evicting what is not drawn.
Accessibility: the viewport is an image node (Role::Image, said
as an image or a graphic), named by Viewport::label (“Image
viewport” by default), and says its zoom as its value (“100 %”); its
keys follow the pointer profile and the canvas commands
(Pointer gestures).
Tier: Experimental (“The image viewport (egui-pop-viewport):
its view model, mapping, signals and hooks may still move while the
first application adopts it”, API stability).
Tests: crates/egui-pop-viewport/tests/: tiles.rs (proxy then
exact tiles, cancelling on pan, changed regions, bounded backlog,
eviction, conversion on the delivering thread, the largest texture
side, one image pixel per physical pixel at 100 % on both paths),
device_tiles.rs, view.rs (the collector and set_view),
overlays.rs, navigation.rs, canvas_navigation.rs, pointer.rs,
cursor.rs, loupe.rs, images.rs, gestures.rs (the tables read
from each built-in profile, the plain double click from the profile’s
option, the default keys, a context’s gestures following its profile
until set), hooks.rs (the hooks named, the trace kept to its bound,
before_compare asked once per press and release, its veto and
redirect traced). The tokens and the thumbnail re-export have no test
of their own; the on_readout hook’s text is painted only, with no
test.