mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 05:37:04 +00:00
ribbon-w6: net change of 3 commits
- ribbon-w6: finished by an agent - ribbon-w6: review fixes (review-1) - ribbon-w6: review fixes (review-1b)
This commit is contained in:
@@ -375,7 +375,7 @@ impl<'a> Draw<'a> {
|
||||
self.initial(rect, letter, StyleColor(color));
|
||||
return;
|
||||
}
|
||||
_ => super::icon::paint(self.painter, self.env.tokens, self.env.direction, rect, icon),
|
||||
_ => super::icon::paint(self.painter, self.env.tokens, self.env.direction, rect, icon, self.data != DataMode::Full),
|
||||
}
|
||||
match icon.badge {
|
||||
Some(super::IconMark::Dot(badge)) => {
|
||||
|
||||
@@ -217,9 +217,9 @@ impl<'a> IconSpec<'a> {
|
||||
}
|
||||
|
||||
/// Puts `mark` on the icon in place of any mark it has.
|
||||
pub fn with_mark(self, mark: IconMark) -> Self {
|
||||
let _ = mark;
|
||||
todo!("rb.R18")
|
||||
pub fn with_mark(mut self, mark: IconMark) -> Self {
|
||||
self.badge = Some(mark);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,8 +247,9 @@ pub fn icon_names() -> &'static [&'static str] {
|
||||
svg_set::names()
|
||||
}
|
||||
|
||||
/// Paints `spec`'s glyph centred in the square of `rect`'s shorter side; `Draw::icon` adds the badge.
|
||||
pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>) {
|
||||
/// Paints `spec`'s glyph centred in the square of `rect`'s shorter side; `Draw::icon` adds the badge. `single_ink` paints
|
||||
/// every layer of an app icon in the one colour: the icon of a component in its disabled state.
|
||||
pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, rect: Rect, spec: &IconSpec<'_>, single_ink: bool) {
|
||||
let color = spec.color_in(tokens);
|
||||
let rtl = direction == Direction::Rtl;
|
||||
let side = rect.width().min(rect.height());
|
||||
@@ -262,7 +263,7 @@ pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction,
|
||||
IconSource::Glyph(glyph) => glyph.paint(painter, tokens, square, color, rtl && glyph.directional() && spec.mirror == Mirror::Auto),
|
||||
IconSource::Svg(id) => {
|
||||
if let Some(icon) = SvgIcon::of(tokens, direction, side, id, spec.set, spec.mirror) {
|
||||
icon.paint(painter, square, color);
|
||||
icon.paint_layers(painter, square, LayerInks::of(tokens, color, single_ink));
|
||||
}
|
||||
}
|
||||
IconSource::Mark(badge) => super::pointer_art::paint_badge(painter, tokens, direction, square, *badge, color),
|
||||
@@ -308,23 +309,77 @@ impl SvgIcon {
|
||||
(px, stroke_px)
|
||||
}
|
||||
|
||||
/// The icon in white for a square of `side` points at `ppp`, its alpha from the drawing.
|
||||
/// The icon's ink layer in white for a square of `side` points at `ppp`, its alpha from the drawing.
|
||||
pub(crate) fn mask(&self, side: f32, ppp: f32) -> egui::ColorImage {
|
||||
let (px, stroke_px) = self.pixels(side, ppp);
|
||||
svg_set::rasterise_entry(self.entry, self.set, px, stroke_px as f32 / 64.0, self.mirrored)
|
||||
self.layer(side, ppp, svg_set::Layer::Ink)
|
||||
}
|
||||
|
||||
/// Paints the icon in `color` centred in `square`, on whole pixels.
|
||||
/// The icon's `layer` for a square of `side` points at `ppp`.
|
||||
pub(crate) fn layer(&self, side: f32, ppp: f32, layer: svg_set::Layer) -> egui::ColorImage {
|
||||
let (px, stroke_px) = self.pixels(side, ppp);
|
||||
svg_set::rasterise_entry(self.entry, self.set, px, stroke_px as f32 / 64.0, self.mirrored, layer)
|
||||
}
|
||||
|
||||
/// Paints every layer of the icon in `color` centred in `square`, on whole pixels: a one-ink silhouette (a
|
||||
/// cursor's icon).
|
||||
pub(crate) fn paint(&self, painter: &Painter, square: Rect, color: Color32) {
|
||||
self.paint_layers(painter, square, LayerInks::single(color));
|
||||
}
|
||||
|
||||
/// Paints the icon centred in `square`, on whole pixels, each layer in its ink of `inks`. A catalog icon has only
|
||||
/// the ink layer; an app icon also paints its accent and fixed parts over it. A layer with no part is not painted.
|
||||
pub(crate) fn paint_layers(&self, painter: &Painter, square: Rect, inks: LayerInks) {
|
||||
let ctx = painter.ctx();
|
||||
let ppp = ctx.pixels_per_point();
|
||||
let (px, stroke_px) = self.pixels(square.width(), ppp);
|
||||
let key = (self.entry, self.set, px, stroke_px, self.mirrored);
|
||||
let texture = TextureCache::texture(ctx, key, || self.mask(square.width(), ppp));
|
||||
let side = px as f32 / ppp;
|
||||
let min = (square.center() - vec2(side, side) / 2.0).round_to_pixels(ppp);
|
||||
let rect = Rect::from_min_size(min, vec2(side, side));
|
||||
let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
|
||||
crate::runtime::egui::textures::paint(painter, texture, Rect::from_min_size(min, vec2(side, side)), uv, color, egui::CornerRadius::ZERO);
|
||||
let fixed = match inks.fixed {
|
||||
Some(color) => (svg_set::Layer::FixedMask, color),
|
||||
None => (svg_set::Layer::Fixed, Color32::WHITE),
|
||||
};
|
||||
let layers = [(svg_set::Layer::Ink, inks.ink), (svg_set::Layer::Accent, inks.accent), fixed];
|
||||
let count = if matches!(self.entry, svg_set::Entry::Catalog(_)) { 1 } else { layers.len() };
|
||||
for (layer, color) in layers.into_iter().take(count) {
|
||||
// Each layer is its own texture, so a disabled icon's one-ink fixed layer and the enabled one as drawn
|
||||
// are both kept.
|
||||
let key = (self.entry, self.set, px, stroke_px, self.mirrored, layer);
|
||||
let drawn = || {
|
||||
let image = self.layer(square.width(), ppp, layer);
|
||||
(!image.pixels.iter().all(|pixel| pixel.a() == 0)).then_some(image)
|
||||
};
|
||||
let Some(texture) = TextureCache::texture_if(ctx, key, drawn) else {
|
||||
continue;
|
||||
};
|
||||
crate::runtime::egui::textures::paint(painter, texture, rect, uv, color, egui::CornerRadius::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The inks an icon's layers paint in: the ink layer, the accent layer, and the fixed layer (`None` paints it as
|
||||
/// drawn).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct LayerInks {
|
||||
ink: Color32,
|
||||
accent: Color32,
|
||||
fixed: Option<Color32>,
|
||||
}
|
||||
|
||||
impl LayerInks {
|
||||
/// Every layer in `color`.
|
||||
pub(crate) fn single(color: Color32) -> Self {
|
||||
LayerInks { ink: color, accent: color, fixed: Some(color) }
|
||||
}
|
||||
|
||||
/// The inks of an icon painted in `color`: the accent parts in `colors.accent.solid` and the fixed parts as drawn,
|
||||
/// except that with `single_ink` (a disabled component) every layer paints in `color`.
|
||||
pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool) -> Self {
|
||||
if single_ink {
|
||||
return LayerInks::single(color);
|
||||
}
|
||||
LayerInks { ink: color, accent: crate::style::rgba_color(tokens.color.accent.solid), fixed: None }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,8 @@ pub use surface::Surface;
|
||||
pub(crate) use surface::SurfaceSlot;
|
||||
pub use surround::paint_surround;
|
||||
pub use svg_set::{AppIcons, register_app_icons};
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) use svg_set::Layer;
|
||||
pub use text::{ChordText, HAlign, LayoutRun, ReadingMeasure, Span, TextLayout, TextRun, Wrap};
|
||||
pub use text_input::{
|
||||
Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp, TabKey, TextKey, TextOptions,
|
||||
|
||||
@@ -117,22 +117,57 @@ pub(crate) fn entry_stroke_width(entry: Entry, set: IconSet) -> Option<f32> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `entry` in white at `px` x `px` physical pixels; a catalog entry as [`rasterise`], an app entry through the same
|
||||
/// drawing with its set's stroke width.
|
||||
pub(crate) fn rasterise_entry(entry: Entry, set: IconSet, px: u32, stroke_px: f32, mirrored: bool) -> ColorImage {
|
||||
match entry {
|
||||
Entry::Catalog(index) => rasterise(index, set, px, stroke_px, mirrored),
|
||||
Entry::App { set: s, icon } => {
|
||||
let (name, svg, own) = app_icon(s, icon);
|
||||
image(draw(svg, own, px, stroke_px, mirrored), px, || format!("app icon {name}"))
|
||||
/// One class set of an icon's drawing. An app icon's parts marked `class="accent"` read in the accent ink and those
|
||||
/// marked `class="fixed"` keep their own colours; every other part reads in the icon's ink.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum Layer {
|
||||
/// The parts outside both classes, in white.
|
||||
Ink,
|
||||
/// The `accent` parts, in white.
|
||||
Accent,
|
||||
/// The `fixed` parts in their own colours.
|
||||
Fixed,
|
||||
/// The `fixed` parts in white, for an icon that paints every layer in one ink (disabled).
|
||||
FixedMask,
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
/// The style sheet that hides every part outside the layer; the SVG engine applies it, so the class is matched
|
||||
/// by its own selectors.
|
||||
fn style_sheet(self) -> &'static str {
|
||||
match self {
|
||||
Layer::Ink => ".accent, .accent *, .fixed, .fixed * { visibility: hidden }",
|
||||
Layer::Accent => "* { visibility: hidden } .accent, .accent * { visibility: visible }",
|
||||
Layer::Fixed | Layer::FixedMask => "* { visibility: hidden } .fixed, .fixed * { visibility: visible }",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The white image of a drawn pixmap; a failed drawing gives a transparent image and a log line.
|
||||
fn image(drawn: Result<tiny_skia::Pixmap, String>, px: u32, label: impl FnOnce() -> String) -> ColorImage {
|
||||
/// The `layer` of `entry` at `px` x `px` physical pixels, in white or, for [`Layer::Fixed`], as drawn. A catalog entry
|
||||
/// has only an ink layer, drawn as [`rasterise`]; its other layers are transparent. An app entry is drawn with its
|
||||
/// set's stroke width, the layer's parts only.
|
||||
pub(crate) fn rasterise_entry(entry: Entry, set: IconSet, px: u32, stroke_px: f32, mirrored: bool, layer: Layer) -> ColorImage {
|
||||
match (entry, layer) {
|
||||
(Entry::Catalog(index), Layer::Ink) => rasterise(index, set, px, stroke_px, mirrored),
|
||||
(Entry::Catalog(_), _) => ColorImage::filled([px as usize; 2], Color32::TRANSPARENT),
|
||||
(Entry::App { set: s, icon }, layer) => {
|
||||
let (name, svg, own) = app_icon(s, icon);
|
||||
let drawn = draw(svg, Some(layer.style_sheet()), own, px, stroke_px, mirrored);
|
||||
image(drawn, px, layer == Layer::Fixed, || format!("app icon {name}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The image of a drawn pixmap, in white with the drawing's alpha or, when `as_drawn`, in its own colours; a failed
|
||||
/// drawing gives a transparent image and a log line.
|
||||
fn image(drawn: Result<tiny_skia::Pixmap, String>, px: u32, as_drawn: bool, label: impl FnOnce() -> String) -> ColorImage {
|
||||
let size = [px as usize; 2];
|
||||
match drawn {
|
||||
// Both tiny-skia's pixels and egui's colours are premultiplied.
|
||||
Ok(pixmap) if as_drawn => ColorImage::new(
|
||||
size,
|
||||
pixmap.pixels().iter().map(|p| Color32::from_rgba_premultiplied(p.red(), p.green(), p.blue(), p.alpha())).collect(),
|
||||
),
|
||||
Ok(pixmap) => ColorImage::new(size, pixmap.pixels().iter().map(|p| Color32::from_white_alpha(p.alpha())).collect()),
|
||||
Err(error) => {
|
||||
log::error!("{}: {error}", label());
|
||||
@@ -146,18 +181,20 @@ fn image(drawn: Result<tiny_skia::Pixmap, String>, px: u32, label: impl FnOnce()
|
||||
/// A document drawn with strokes is drawn `stroke_px` physical pixels wide, one drawn with fills as drawn. `mirrored`
|
||||
/// flips the drawing horizontally. A document that fails to parse gives a transparent image and a log line.
|
||||
pub(crate) fn rasterise(index: usize, set: IconSet, px: u32, stroke_px: f32, mirrored: bool) -> ColorImage {
|
||||
image(draw(svg(index, set), stroke_width(index, set), px, stroke_px, mirrored), px, || format!("icon {} in {}", NAMES[index], set.id()))
|
||||
let drawn = draw(svg(index, set), None, stroke_width(index, set), px, stroke_px, mirrored);
|
||||
image(drawn, px, false, || format!("icon {} in {}", NAMES[index], set.id()))
|
||||
}
|
||||
|
||||
/// `own` is the document's own stroke width in view-box units; a document without one is drawn as it is.
|
||||
fn draw(svg: &[u8], own: Option<f32>, px: u32, stroke_px: f32, mirrored: bool) -> Result<tiny_skia::Pixmap, String> {
|
||||
let mut tree = svg_tree::parse(svg)?;
|
||||
/// `svg` under `style_sheet` (one class set, see [`Layer`]); `own` is the document's own stroke width in view-box
|
||||
/// units; a document without one is drawn as it is.
|
||||
fn draw(svg: &[u8], style_sheet: Option<&str>, own: Option<f32>, px: u32, stroke_px: f32, mirrored: bool) -> Result<tiny_skia::Pixmap, String> {
|
||||
let mut tree = svg_tree::parse_styled(svg, style_sheet)?;
|
||||
let view = tree.size();
|
||||
if let Some(own) = own {
|
||||
// Every `stroke-width` scales by the same factor, so a set's thinner details stay thinner.
|
||||
let units = stroke_px * view.width() / px as f32;
|
||||
let text = std::str::from_utf8(svg).map_err(|e| e.to_string())?;
|
||||
tree = svg_tree::parse(scale_stroke_widths(text, units / own).as_bytes())?;
|
||||
tree = svg_tree::parse_styled(scale_stroke_widths(text, units / own).as_bytes(), style_sheet)?;
|
||||
}
|
||||
let (sx, sy) = (px as f32 / view.width(), px as f32 / view.height());
|
||||
let transform =
|
||||
|
||||
@@ -36,12 +36,12 @@ pub fn parse(svg: &[u8]) -> Result<usvg::Tree, String> {
|
||||
/// parser, so a layer by class is read by the SVG engine's own selectors.
|
||||
#[doc(hidden)]
|
||||
pub fn parse_styled(svg: &[u8], style_sheet: Option<&str>) -> Result<usvg::Tree, String> {
|
||||
let _ = style_sheet; // P3(ribbon-w6): rb.R19
|
||||
if svg.starts_with(&GZIP_MAGIC) {
|
||||
return Err("compressed SVG".to_owned());
|
||||
}
|
||||
let options = usvg::Options {
|
||||
image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) },
|
||||
style_sheet: style_sheet.map(str::to_owned),
|
||||
..usvg::Options::default()
|
||||
};
|
||||
tree::parse(svg, &icon_limits(), &options).map_err(|e| e.to_string())
|
||||
|
||||
@@ -30,7 +30,8 @@ use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
/// One cached texture and the frame that last asked for it.
|
||||
struct Entry {
|
||||
handle: TextureHandle,
|
||||
/// `None` for a key whose image had nothing to draw.
|
||||
handle: Option<TextureHandle>,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
@@ -75,6 +76,17 @@ impl TextureCache {
|
||||
/// The texture for `key` sampled with `options` (a repeating pattern, nearest filtering); see [`Self::texture`].
|
||||
/// The options are part of the key.
|
||||
pub fn texture_with<K: Hash + 'static>(ctx: &Context, key: K, options: TextureOptions, image: impl FnOnce() -> ColorImage) -> TextureId {
|
||||
// The image is always made, so the lookup always answers.
|
||||
Self::lookup(ctx, key, options, || Some(image())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The texture for `key`, or `None` when `image` has nothing to draw; the answer is kept like a texture, so
|
||||
/// `image` runs once per key. An icon layer with no part is not painted.
|
||||
pub fn texture_if<K: Hash + 'static>(ctx: &Context, key: K, image: impl FnOnce() -> Option<ColorImage>) -> Option<TextureId> {
|
||||
Self::lookup(ctx, key, TextureOptions::LINEAR, image)
|
||||
}
|
||||
|
||||
fn lookup<K: Hash + 'static>(ctx: &Context, key: K, options: TextureOptions, image: impl FnOnce() -> Option<ColorImage>) -> Option<TextureId> {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
TypeId::of::<K>().hash(&mut hasher);
|
||||
key.hash(&mut hasher);
|
||||
@@ -84,16 +96,16 @@ impl TextureCache {
|
||||
let known = memory::with(ctx, |loaded: &mut Loaded| {
|
||||
loaded.handles.get_mut(&hash).map(|entry| {
|
||||
entry.used = frame;
|
||||
entry.handle.id()
|
||||
entry.handle.as_ref().map(TextureHandle::id)
|
||||
})
|
||||
});
|
||||
if let Some(id) = known {
|
||||
return id;
|
||||
}
|
||||
// The image is built and uploaded outside the service lock: neither calls back into the cache.
|
||||
let handle = textures::load(ctx, format!("craft_ui/{hash:016x}"), image(), options);
|
||||
let handle = image().map(|image| textures::load(ctx, format!("craft_ui/{hash:016x}"), image, options));
|
||||
memory::with(ctx, |loaded: &mut Loaded| {
|
||||
let id = loaded.handles.entry(hash).or_insert(Entry { handle, used: frame }).handle.id();
|
||||
let id = loaded.handles.entry(hash).or_insert(Entry { handle, used: frame }).handle.as_ref().map(TextureHandle::id);
|
||||
loaded.evict(frame);
|
||||
id
|
||||
})
|
||||
|
||||
@@ -114,14 +114,26 @@ impl TextureStoreOptions {
|
||||
Self { budget: TextureBudget::new(max_bytes, max_entries), filter: TextureOptions::LINEAR, packed: None }
|
||||
}
|
||||
|
||||
/// Puts pictures up to `max_side` on shared pages written in place; when full, the store recycles the least
|
||||
/// recently drawn page, never one drawn this pass. A const fn, so it carries the setting without `todo!`.
|
||||
/// Puts pictures up to `max_side` texels per side on a few shared page textures written in place, so browsing
|
||||
/// many small pictures creates and frees no textures. When every page is full the store starts over the page
|
||||
/// drawn from longest ago, never one drawn from in this frame (its pictures are on screen); the pictures on it
|
||||
/// become `Missing` and are put again. When every page was drawn from in this frame, or a picture is larger than
|
||||
/// `max_side` or a page, the picture takes a texture of its own. A packed texture is drawn by
|
||||
/// [`CachedTexture::uv`].
|
||||
#[must_use]
|
||||
pub const fn packed(mut self, max_side: u32) -> Self {
|
||||
self.packed = Some(max_side);
|
||||
self
|
||||
}
|
||||
|
||||
/// [`packed`](Self::packed) for the small pictures of an interface (a style tile, a font sample row): those up to a
|
||||
/// quarter of a page side share pages, so a few large ones never fill a page alone; a larger picture takes a
|
||||
/// texture of its own.
|
||||
#[must_use]
|
||||
pub const fn packed_small(self) -> Self {
|
||||
self.packed(PAGE_SIDE / 4)
|
||||
}
|
||||
|
||||
/// The sampling of every texture.
|
||||
#[must_use]
|
||||
pub const fn filter(mut self, filter: TextureOptions) -> Self {
|
||||
@@ -159,17 +171,26 @@ pub struct CachedTexture {
|
||||
}
|
||||
|
||||
impl CachedTexture {
|
||||
/// The picture's part of its page texture, in uv coordinates, to paint with `id`.
|
||||
/// The picture's part of its page texture, in uv coordinates, to paint with `id`: the full rect for an unpacked
|
||||
/// texture.
|
||||
pub fn uv(&self) -> Rect {
|
||||
todo!("rb.R20")
|
||||
let (width, height) = (self.page.width.max(1) as f32, self.page.height.max(1) as f32);
|
||||
let [x, y] = self.origin;
|
||||
let (x, y) = (x as f32, y as f32);
|
||||
Rect::from_min_max(
|
||||
egui::pos2(x / width, y / height),
|
||||
egui::pos2((x + self.size.width as f32) / width, (y + self.size.height as f32) / height),
|
||||
)
|
||||
}
|
||||
|
||||
/// `size` as a vector, for fitting: only the aspect matters to a cell.
|
||||
/// `size` as a vector, for fitting: only the aspect matters to a cell. It is the picture's own size, also for a
|
||||
/// packed texture.
|
||||
pub fn size_vec2(&self) -> Vec2 {
|
||||
Vec2::new(self.size.width as f32, self.size.height as f32)
|
||||
}
|
||||
|
||||
/// The texture with its size, the form `PreviewPane` and egui's image widgets take.
|
||||
/// The texture with its size, the form `PreviewPane` and egui's image widgets take. Those draw the whole
|
||||
/// texture, so a texture of a packed store is drawn by [`uv`](Self::uv) instead.
|
||||
pub fn sized(&self) -> SizedTexture {
|
||||
SizedTexture::new(self.id, self.size_vec2())
|
||||
}
|
||||
@@ -234,10 +255,82 @@ enum Picture {
|
||||
/// The whole factor `fit_image` reduced it by: 1 when it fitted.
|
||||
factor: u32,
|
||||
},
|
||||
/// A picture on the shared page `page` of a packed store, its top-left texel at `origin`.
|
||||
Packed { page: usize, origin: [u32; 2], size: PixelSize },
|
||||
Empty,
|
||||
Failed(LoadFailure),
|
||||
}
|
||||
|
||||
/// The side of a packed store's square pages in texels, at most the device limit.
|
||||
const PAGE_SIDE: u32 = 2048;
|
||||
/// At most this many pages: enough for a frame's pictures at a high display scale, still a handful of textures.
|
||||
const PAGE_COUNT: usize = 4;
|
||||
/// Transparent texels between pictures, so linear filtering never bleeds one into the next.
|
||||
const PAGE_GAP: u32 = 2;
|
||||
|
||||
/// A shared texture of a packed store, filled row by row.
|
||||
struct Page {
|
||||
handle: TextureHandle,
|
||||
side: u32,
|
||||
/// Where the next picture goes: the current row's left edge and top, and the row's height.
|
||||
x: u32,
|
||||
y: u32,
|
||||
row_height: u32,
|
||||
/// The last frame a picture on the page was seen.
|
||||
seen: u64,
|
||||
/// The page started over and still holds the old pictures' texels; it is cleared before its next picture.
|
||||
stale: bool,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
/// A free spot for a picture of `size`, taken; `None` when the page has no room for it.
|
||||
fn place(&mut self, size: PixelSize) -> Option<[u32; 2]> {
|
||||
let (w, h) = (size.width, size.height);
|
||||
if w == 0 || h == 0 || w > self.side || h > self.side {
|
||||
return None;
|
||||
}
|
||||
let (mut x, mut y, mut row_height) = (self.x, self.y, self.row_height);
|
||||
if x.saturating_add(w) > self.side {
|
||||
x = 0;
|
||||
y = y.saturating_add(row_height).saturating_add(PAGE_GAP);
|
||||
row_height = 0;
|
||||
}
|
||||
if y.saturating_add(h) > self.side {
|
||||
return None;
|
||||
}
|
||||
self.x = x.saturating_add(w).saturating_add(PAGE_GAP);
|
||||
self.y = y;
|
||||
self.row_height = row_height.max(h);
|
||||
Some([x, y])
|
||||
}
|
||||
|
||||
fn cached(&self, origin: [u32; 2], size: PixelSize) -> CachedTexture {
|
||||
CachedTexture { id: self.handle.id(), size, origin, page: PixelSize::new(self.side, self.side) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a packed picture goes, decided under the lock; the texture work runs after it.
|
||||
enum Spot {
|
||||
/// At `origin` on the page `page`; `clear` when the page started over and its texture holds old pictures.
|
||||
On { page: usize, origin: [u32; 2], handle: TextureHandle, side: u32, clear: bool },
|
||||
/// On a new page, whose texture is named `name`.
|
||||
New { name: String },
|
||||
}
|
||||
|
||||
/// A transparent page of `side` texels.
|
||||
fn blank_page(side: u32) -> ColorImage {
|
||||
ColorImage::filled([side as usize; 2], egui::Color32::TRANSPARENT)
|
||||
}
|
||||
|
||||
/// The picture `picture` shows, on its page when packed; `None` for an empty or failed entry.
|
||||
fn shown(pages: &[Page], picture: &Picture) -> Option<CachedTexture> {
|
||||
match picture {
|
||||
Picture::Texture { handle, source, factor } => Some(cached(handle, *source, *factor)),
|
||||
Picture::Packed { page, origin, size } => pages.get(*page).map(|page| page.cached(*origin, *size)),
|
||||
Picture::Empty | Picture::Failed(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
revision: Revision,
|
||||
picture: Picture,
|
||||
@@ -248,6 +341,8 @@ struct Entry {
|
||||
struct Inner<K> {
|
||||
options: TextureStoreOptions,
|
||||
entries: HashMap<K, Entry>,
|
||||
/// The shared pages of a packed store; none for an unpacked one.
|
||||
pages: Vec<Page>,
|
||||
bytes: usize,
|
||||
/// The frame the upload counters are for, and the counters.
|
||||
upload_frame: u64,
|
||||
@@ -284,7 +379,8 @@ impl<K> Default for Stores<K> {
|
||||
/// - **Eviction**, after every put: least recently seen first, until both the bytes and the entry count are within
|
||||
/// the budget, but never an entry seen in this frame or the previous one; what is in view stays even past the
|
||||
/// budget.
|
||||
/// - **One texture per entry**, no atlas.
|
||||
/// - **One texture per entry**, unless the store is built with [`TextureStoreOptions::packed`]: then small pictures
|
||||
/// share a few pages, each page's bytes counted once, and a page, not an entry, is what starts over.
|
||||
///
|
||||
/// The icon path is `TextureCache`; the store keeps pictures that change and that the app names.
|
||||
pub struct TextureStore<K: TextureKey> {
|
||||
@@ -340,13 +436,18 @@ impl<K: TextureKey> TextureStore<K> {
|
||||
/// Stores `image` as `key`'s picture at `revision` and returns it: in place when the key has a texture (same
|
||||
/// id), else a new texture with the store's filter. Reduced first when past `texture_side`. Counts as an upload
|
||||
/// this frame, marks the entry seen, then evicts. The image is sRGBA as egui's `ColorImage` holds it (built
|
||||
/// from unmultiplied values with `ColorImage::from_rgba_unmultiplied`).
|
||||
/// from unmultiplied values with `ColorImage::from_rgba_unmultiplied`). A packed store writes a small picture
|
||||
/// onto a shared page instead (see [`TextureStoreOptions::packed`]).
|
||||
pub fn put(&self, ctx: &Context, key: K, revision: Revision, image: ColorImage) -> CachedTexture {
|
||||
let frame = pass::root_frame_nr(ctx);
|
||||
let side = texture_side(ctx);
|
||||
let source = texels(image.size);
|
||||
let factor = texture_factor(source, side);
|
||||
let image = fit_image(image, side);
|
||||
let image = match self.put_packed(ctx, &key, revision, image, frame, side) {
|
||||
Ok(texture) => return texture,
|
||||
Err(image) => image,
|
||||
};
|
||||
let size = texels(image.size);
|
||||
let (existing, filter, name) = self.with(ctx, |inner| {
|
||||
let existing = inner.handle_of(&key);
|
||||
@@ -373,6 +474,54 @@ impl<K: TextureKey> TextureStore<K> {
|
||||
texture
|
||||
}
|
||||
|
||||
/// Writes `image` onto a page of a packed store as `key`'s picture at `revision`; gives the image back when the
|
||||
/// store is unpacked, the picture is larger than `max_side` or a page, or no page has room and every page was
|
||||
/// drawn from in `frame` (the picture then takes a texture of its own, `put`'s ordinary path). Two passes of
|
||||
/// one frame share its number, so a page drawn from in the first pass is kept in the second.
|
||||
fn put_packed(&self, ctx: &Context, key: &K, revision: Revision, image: ColorImage, frame: u64, side: u32) -> Result<CachedTexture, ColorImage> {
|
||||
let size = texels(image.size);
|
||||
let page_side = PAGE_SIDE.min(side);
|
||||
let Some(max_side) = self.options.packed else {
|
||||
return Err(image);
|
||||
};
|
||||
if size.width == 0 || size.height == 0 || size.width.max(size.height) > max_side.min(page_side) {
|
||||
return Err(image);
|
||||
}
|
||||
let Some(spot) = self.with(ctx, |inner| inner.spot(size, frame, page_side)) else {
|
||||
return Err(image);
|
||||
};
|
||||
// Texture work runs outside the service lock, as `put`'s upload does.
|
||||
let (page, origin, mut handle, page_side) = match spot {
|
||||
Spot::On { page, origin, mut handle, side, clear } => {
|
||||
if clear {
|
||||
textures::replace(&mut handle, blank_page(side), self.options.filter);
|
||||
}
|
||||
(page, origin, handle, side)
|
||||
}
|
||||
Spot::New { name } => {
|
||||
let handle = textures::load(ctx, name, blank_page(page_side), self.options.filter);
|
||||
let Some((page, origin)) = self.with(ctx, |inner| inner.add_page(handle.clone(), page_side, size)) else {
|
||||
return Err(image);
|
||||
};
|
||||
(page, origin, handle, page_side)
|
||||
}
|
||||
};
|
||||
textures::replace_region(&mut handle, origin, image, self.options.filter);
|
||||
let bytes = byte_size(size);
|
||||
let texture = CachedTexture { id: handle.id(), size, origin, page: PixelSize::new(page_side, page_side) };
|
||||
self.with(ctx, |inner| {
|
||||
inner.roll_uploads(frame);
|
||||
inner.uploads += 1;
|
||||
inner.upload_bytes += bytes;
|
||||
if let Some(shared) = inner.pages.get_mut(page) {
|
||||
shared.seen = frame;
|
||||
}
|
||||
inner.store(key.clone(), Entry { revision, picture: Picture::Packed { page, origin, size }, seen: frame });
|
||||
inner.evict(frame);
|
||||
});
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
/// Updates part of `key`'s picture in place and moves the entry to `revision`: `image` goes at `origin`, both
|
||||
/// in the pixels of the image last put (the navigator's damage updates). The id stays. Returns `None` and
|
||||
/// changes nothing when the key has no picture, or when the region does not fit the stored image.
|
||||
@@ -380,7 +529,8 @@ impl<K: TextureKey> TextureStore<K> {
|
||||
/// An image that was reduced by the whole factor `f` on put is updated reduced the same way: the region's
|
||||
/// origin must be a multiple of `f`, and its far edges multiples of `f` or the image's own edges; it is
|
||||
/// box-averaged by `f` and written at `origin / f`. A region off that grid returns `None`, and the app puts the
|
||||
/// whole image.
|
||||
/// whole image. A picture on a packed store's page also returns `None`, as for a key with no texture, so the
|
||||
/// caller puts the whole picture: packed pictures are small.
|
||||
pub fn put_region(&self, ctx: &Context, key: &K, revision: Revision, origin: [u32; 2], image: ColorImage) -> Option<CachedTexture> {
|
||||
let frame = pass::root_frame_nr(ctx);
|
||||
let extent = texels(image.size);
|
||||
@@ -414,11 +564,14 @@ impl<K: TextureKey> TextureStore<K> {
|
||||
if entry.revision != revision {
|
||||
return None;
|
||||
}
|
||||
let Picture::Texture { handle, source, factor } = &entry.picture else {
|
||||
return None;
|
||||
};
|
||||
let texture = shown(&inner.pages, &entry.picture)?;
|
||||
entry.seen = frame;
|
||||
Some(cached(handle, *source, *factor))
|
||||
if let Picture::Packed { page, .. } = entry.picture
|
||||
&& let Some(shared) = inner.pages.get_mut(page)
|
||||
{
|
||||
shared.seen = frame;
|
||||
}
|
||||
Some(texture)
|
||||
});
|
||||
match found {
|
||||
Some(texture) => texture,
|
||||
@@ -462,13 +615,16 @@ impl<K: TextureKey> TextureStore<K> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Drops every entry (another library opened).
|
||||
/// Drops every entry (another library opened); a packed store's pages start over and keep their textures.
|
||||
pub fn clear(&self, ctx: &Context) {
|
||||
self.with(ctx, |inner| {
|
||||
let all: Vec<K> = inner.entries.keys().cloned().collect();
|
||||
for key in &all {
|
||||
inner.remove(key);
|
||||
}
|
||||
for page in 0..inner.pages.len() {
|
||||
inner.restart(page);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -522,10 +678,11 @@ fn cached(handle: &TextureHandle, source: PixelSize, factor: u32) -> CachedTextu
|
||||
CachedTexture { id: handle.id(), size, origin: [0, 0], page: size }
|
||||
}
|
||||
|
||||
/// The texture bytes `picture` holds on its own: none for a packed picture, whose page is counted once.
|
||||
fn picture_bytes(picture: &Picture) -> usize {
|
||||
match picture {
|
||||
Picture::Texture { source, factor, .. } => byte_size(texture_size(*source, *factor)),
|
||||
Picture::Empty | Picture::Failed(_) => 0,
|
||||
Picture::Packed { .. } | Picture::Empty | Picture::Failed(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -534,6 +691,7 @@ impl<K: TextureKey> Inner<K> {
|
||||
Self {
|
||||
options,
|
||||
entries: HashMap::new(),
|
||||
pages: Vec::new(),
|
||||
bytes: 0,
|
||||
upload_frame: 0,
|
||||
uploads: 0,
|
||||
@@ -550,21 +708,72 @@ impl<K: TextureKey> Inner<K> {
|
||||
return TextureState::Missing;
|
||||
};
|
||||
entry.seen = frame;
|
||||
if let Picture::Packed { page, .. } = entry.picture
|
||||
&& let Some(shared) = self.pages.get_mut(page)
|
||||
{
|
||||
shared.seen = frame;
|
||||
}
|
||||
let same = entry.revision == revision;
|
||||
match &entry.picture {
|
||||
Picture::Texture { handle, source, factor } if same => TextureState::Ready(cached(handle, *source, *factor)),
|
||||
Picture::Texture { handle, source, factor } => TextureState::Loading { stand_in: Some(cached(handle, *source, *factor)) },
|
||||
Picture::Empty if same => TextureState::Empty,
|
||||
Picture::Failed(failure) if same => TextureState::Failed { failure: failure.clone() },
|
||||
Picture::Empty | Picture::Failed(_) => TextureState::Missing,
|
||||
match (&entry.picture, shown(&self.pages, &entry.picture)) {
|
||||
(_, Some(texture)) if same => TextureState::Ready(texture),
|
||||
(_, Some(texture)) => TextureState::Loading { stand_in: Some(texture) },
|
||||
(Picture::Empty, _) if same => TextureState::Empty,
|
||||
(Picture::Failed(failure), _) if same => TextureState::Failed { failure: failure.clone() },
|
||||
_ => TextureState::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture handle of `key`, if it has a picture.
|
||||
/// How many pages a packed store keeps: `PAGE_COUNT`, fewer when the byte budget holds fewer pages of `side`,
|
||||
/// and at least one.
|
||||
fn page_limit(&self, side: u32) -> usize {
|
||||
let page = byte_size(PixelSize::new(side, side)).max(1);
|
||||
(self.options.budget.max_bytes / page).clamp(1, PAGE_COUNT)
|
||||
}
|
||||
|
||||
/// Where a packed picture of `size` goes: the first page with room, else a new page while there are fewer than
|
||||
/// the limit, else the page seen longest ago started over. `None` when every page was seen in `frame`: none
|
||||
/// starts over while its pictures are on screen.
|
||||
fn spot(&mut self, size: PixelSize, frame: u64, side: u32) -> Option<Spot> {
|
||||
let on = |index: usize, page: &mut Page| {
|
||||
page.place(size).map(|origin| Spot::On { page: index, origin, handle: page.handle.clone(), side: page.side, clear: std::mem::take(&mut page.stale) })
|
||||
};
|
||||
if let Some(spot) = self.pages.iter_mut().enumerate().find_map(|(index, page)| on(index, page)) {
|
||||
return Some(spot);
|
||||
}
|
||||
if self.pages.len() < self.page_limit(side) {
|
||||
return Some(Spot::New { name: self.next_texture_name() });
|
||||
}
|
||||
let index = self.pages.iter().enumerate().filter(|(_, page)| page.seen < frame).min_by_key(|(_, page)| page.seen).map(|(index, _)| index)?;
|
||||
self.restart(index);
|
||||
on(index, self.pages.get_mut(index)?)
|
||||
}
|
||||
|
||||
/// Adds a page with `handle`, `side` texels square, and takes a spot for a picture of `size` on it.
|
||||
fn add_page(&mut self, handle: TextureHandle, side: u32, size: PixelSize) -> Option<(usize, [u32; 2])> {
|
||||
let mut page = Page { handle, side, x: 0, y: 0, row_height: 0, seen: 0, stale: false };
|
||||
let origin = page.place(size)?;
|
||||
self.bytes += byte_size(PixelSize::new(side, side));
|
||||
self.pages.push(page);
|
||||
Some((self.pages.len() - 1, origin))
|
||||
}
|
||||
|
||||
/// Starts the page `index` over: its layout is forgotten, its pictures become `Missing`, and its texture is
|
||||
/// cleared before the next picture goes on it.
|
||||
fn restart(&mut self, index: usize) {
|
||||
let Some(page) = self.pages.get_mut(index) else {
|
||||
return;
|
||||
};
|
||||
(page.x, page.y, page.row_height, page.stale) = (0, 0, 0, true);
|
||||
let before = self.entries.len();
|
||||
self.entries.retain(|_, entry| !matches!(entry.picture, Picture::Packed { page: on, .. } if on == index));
|
||||
self.evicted += before - self.entries.len();
|
||||
}
|
||||
|
||||
/// The texture handle of `key`, if it has a texture of its own; a packed picture's page is shared, so it has none.
|
||||
fn handle_of(&self, key: &K) -> Option<TextureHandle> {
|
||||
match &self.entries.get(key)?.picture {
|
||||
Picture::Texture { handle, .. } => Some(handle.clone()),
|
||||
Picture::Empty | Picture::Failed(_) => None,
|
||||
Picture::Packed { .. } | Picture::Empty | Picture::Failed(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -624,22 +833,66 @@ impl<K: TextureKey> Inner<K> {
|
||||
self.bytes <= self.options.budget.max_bytes && self.entries.len() <= self.options.budget.max_entries
|
||||
}
|
||||
|
||||
/// Drops the least recently seen entries until the budget holds, never one seen in `frame` or the frame before.
|
||||
/// Drops the least recently seen units until the budget holds, never one seen in `frame` or the frame before. A
|
||||
/// unit is an entry with a texture of its own, an empty or failed entry, or a whole page of a packed store with
|
||||
/// its pictures: a packed picture holds no bytes, so it goes alone only for the entry count, while the bytes are
|
||||
/// within budget.
|
||||
fn evict(&mut self, frame: u64) {
|
||||
if self.within_budget() {
|
||||
return;
|
||||
}
|
||||
let protected = frame.saturating_sub(1);
|
||||
let mut candidates: Vec<(u64, K)> =
|
||||
self.entries.iter().filter(|(_, entry)| entry.seen < protected).map(|(key, entry)| (entry.seen, key.clone())).collect();
|
||||
candidates.sort_by_key(|(seen, _)| *seen);
|
||||
for (_, key) in candidates {
|
||||
let mut units: Vec<(u64, Unit<K>)> =
|
||||
self.entries.iter().filter(|(_, entry)| entry.seen < protected).map(|(key, entry)| (entry.seen, Unit::Entry(key.clone()))).collect();
|
||||
units.extend(self.pages.iter().filter(|page| page.seen < protected).map(|page| (page.seen, Unit::Page(page.handle.id()))));
|
||||
units.sort_by_key(|(seen, _)| *seen);
|
||||
for (_, unit) in units {
|
||||
if self.within_budget() {
|
||||
break;
|
||||
}
|
||||
if self.remove(&key) {
|
||||
self.evicted += 1;
|
||||
match unit {
|
||||
Unit::Entry(key) => {
|
||||
let packed = matches!(self.entries.get(&key).map(|entry| &entry.picture), Some(Picture::Packed { .. }));
|
||||
if packed && self.bytes > self.options.budget.max_bytes {
|
||||
continue;
|
||||
}
|
||||
if self.remove(&key) {
|
||||
self.evicted += 1;
|
||||
}
|
||||
}
|
||||
Unit::Page(id) => {
|
||||
if let Some(index) = self.pages.iter().position(|page| page.handle.id() == id) {
|
||||
self.drop_page(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the page `index` with its pictures and frees its texture. The last page takes its place in the list,
|
||||
/// so the pictures on it follow.
|
||||
fn drop_page(&mut self, index: usize) {
|
||||
self.restart(index);
|
||||
let page = self.pages.swap_remove(index);
|
||||
let side = PixelSize::new(page.side, page.side);
|
||||
self.bytes -= byte_size(side);
|
||||
let moved = self.pages.len();
|
||||
if index != moved {
|
||||
for entry in self.entries.values_mut() {
|
||||
if let Picture::Packed { page: on, .. } = &mut entry.picture
|
||||
&& *on == moved
|
||||
{
|
||||
*on = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The page is a texture like any other; its handle is dropped after the lock is released.
|
||||
self.doomed.push(Picture::Texture { handle: page.handle, source: side, factor: 1 });
|
||||
}
|
||||
}
|
||||
|
||||
/// What the budget loop drops: an entry, or a page of a packed store by its texture.
|
||||
enum Unit<K> {
|
||||
Entry(K),
|
||||
Page(TextureId),
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use super::limits::MAX_TEXTURE;
|
||||
use super::loader::{LoadFailure, LoadedPicture, LoaderOptions, Priority, TextureLoader};
|
||||
use super::store::{Revision, TextureKey, TextureState, TextureStoreOptions};
|
||||
use super::store::{CachedTexture, Revision, TextureKey, TextureState, TextureStoreOptions};
|
||||
use crate::primitives::{ContentPainterCx, IconSpec, Surface};
|
||||
use crate::runtime::egui::{memory, pass, repaint, textures};
|
||||
use crate::style::{Corners, DataColor, SurfaceKind, surface_style};
|
||||
@@ -361,7 +361,7 @@ impl<K: TextureKey> Thumbnails<K> {
|
||||
match state {
|
||||
TextureState::Empty => false,
|
||||
TextureState::Ready(texture) | TextureState::Loading { stand_in: Some(texture) } => {
|
||||
paint_picture(cx, rect, texture.id, texture.size_vec2(), paint);
|
||||
paint_picture(cx, rect, texture, paint);
|
||||
true
|
||||
}
|
||||
TextureState::Missing | TextureState::Loading { stand_in: None } => {
|
||||
@@ -439,10 +439,12 @@ fn thumb_size(frame: PixelSize, longest_side: u32) -> PixelSize {
|
||||
PixelSize::new((frame_width * scale).round().max(1.0) as u32, (frame_height * scale).round().max(1.0) as u32)
|
||||
}
|
||||
|
||||
/// Draws the transparency grid and the picture for `paint.fit`.
|
||||
fn paint_picture(cx: &ContentPainterCx<'_>, cell: Rect, texture: egui::TextureId, size: Vec2, paint: &ThumbPaint) {
|
||||
/// Draws the transparency grid and the picture for `paint.fit`. The fit's uv is in the picture's own 0..1 square
|
||||
/// and is mapped into the picture's part of its texture, so a picture on a shared page shows only itself.
|
||||
fn paint_picture(cx: &ContentPainterCx<'_>, cell: Rect, texture: &CachedTexture, paint: &ThumbPaint) {
|
||||
let size = texture.size_vec2();
|
||||
let full = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
|
||||
let (target, uv) = match paint.fit {
|
||||
let (target, fit) = match paint.fit {
|
||||
ThumbFit::Contain => (fit_rect(cell, size).round_to_pixels(cx.pixels_per_point()), full),
|
||||
ThumbFit::Cover => (cell, cover_uv(cell, size)),
|
||||
};
|
||||
@@ -451,7 +453,13 @@ fn paint_picture(cx: &ContentPainterCx<'_>, cell: Rect, texture: egui::TextureId
|
||||
} else if paint.checker {
|
||||
cx.checker(target);
|
||||
}
|
||||
textures::paint(&cx.painter, texture, target, uv, paint.tint.0, egui::CornerRadius::ZERO);
|
||||
textures::paint(&cx.painter, texture.id, target, within(texture.uv(), fit), paint.tint.0, egui::CornerRadius::ZERO);
|
||||
}
|
||||
|
||||
/// The part `fit` (fractions of `outer`, 0 to 1) of the uv rect `outer`.
|
||||
fn within(outer: Rect, fit: Rect) -> Rect {
|
||||
let at = |t: egui::Pos2| outer.min + vec2(t.x * outer.width(), t.y * outer.height());
|
||||
Rect::from_min_max(at(fit.min), at(fit.max))
|
||||
}
|
||||
|
||||
/// The part of a picture a `Cover` fit shows in `cell`: centred, cut at the long sides.
|
||||
@@ -478,7 +486,7 @@ fn paint_placeholder(cx: &ContentPainterCx<'_>, rect: Rect, paper: Option<DataCo
|
||||
fn paint_failure(cx: &ContentPainterCx<'_>, rect: Rect) {
|
||||
let side = cx.tokens.size.icon.sm.min(rect.width().min(rect.height()));
|
||||
let icon = Rect::from_center_size(rect.center(), vec2(side, side));
|
||||
crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")));
|
||||
crate::primitives::icon::paint(&cx.painter, cx.tokens, cx.direction, icon, &IconSpec::svg(IconId::new("warning")), false);
|
||||
}
|
||||
|
||||
/// A [`ThumbSource`] for stories and tests in every crate: pictures made from the key and a revision the test sets,
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
//! Trials of the app icon registry: the catalog wins a clashing name, the first set keeps a name two sets share.
|
||||
//! Trials of the app icon registry: the catalog wins a clashing name, the first set keeps a name two sets share; and
|
||||
//! of an app icon's layers by class.
|
||||
|
||||
use crate::primitives::{AppIcons, IconSet, Mirror, SvgIcon, icon_names, register_app_icons};
|
||||
use crate::testing::{style, trial};
|
||||
use crate::primitives::{AppIcons, DataMode, Draw, DrawEnv, IconSet, IconSpec, Layer, Mirror, PaintRecord, SvgIcon, icon_names, register_app_icons};
|
||||
use crate::style::{Ink, StyleColor, ink_color, rgba_color};
|
||||
use crate::testing::{Frames, style, trial};
|
||||
use craft_behavior::IconId;
|
||||
use craft_i18n::Direction;
|
||||
use craft_theme::{Contrast, Mode};
|
||||
use egui::ColorImage;
|
||||
use egui::{Color32, ColorImage, Rect, Shape, TextureId, pos2};
|
||||
use std::cell::RefCell;
|
||||
|
||||
// Built from parts so the workspace scan of icon-id literals does not read them.
|
||||
const FIRST_NAME: &str = concat!("zz_t10_", "first");
|
||||
@@ -57,3 +60,86 @@ fn an_app_icon_set_resolves_after_the_catalog_and_the_first_set_keeps_a_shared_n
|
||||
assert_eq!((mask(FIRST_NAME), mask(SECOND_NAME), mask(CATALOG_NAME)), (first, second, close));
|
||||
assert_eq!(icon_names().len(), catalog);
|
||||
}
|
||||
|
||||
const LAYERED_NAME: &str = concat!("zz_t19_", "pen");
|
||||
/// A plain body, an accent nib (a group, so the class reaches its children) and a fixed red cap.
|
||||
const LAYERED: &[u8] = b"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\
|
||||
<rect x=\"4\" y=\"8\" width=\"10\" height=\"8\" fill=\"black\"/>\
|
||||
<g class=\"accent\"><path d=\"M14 8 L22 12 L14 16 Z\" fill=\"black\"/></g>\
|
||||
<rect class=\"fixed\" x=\"2\" y=\"8\" width=\"2\" height=\"8\" fill=\"#d02020\"/></svg>";
|
||||
static LAYERED_SET: AppIcons = AppIcons { name: "t19-layers", stroke_width: None, icons: &[(LAYERED_NAME, LAYERED)] };
|
||||
/// A plain icon with no classed part.
|
||||
const PLAIN_NAME: &str = concat!("zz_t19_", "plain");
|
||||
static PLAIN_SET: AppIcons = AppIcons { name: "t19-plain", stroke_width: None, icons: &[(PLAIN_NAME, DISC)] };
|
||||
|
||||
/// The texture and tint of every textured shape `shapes` holds, in paint order.
|
||||
fn textured(shapes: &[Shape]) -> Vec<(TextureId, Color32)> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter_map(|shape| match shape {
|
||||
Shape::Rect(rect) if shape.texture_id() != TextureId::default() => Some((shape.texture_id(), rect.fill)),
|
||||
Shape::Mesh(mesh) if mesh.texture_id != TextureId::default() => mesh.vertices.first().map(|vertex| (mesh.texture_id, vertex.color)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The texel at (`x`, `y`) of a 24-texel layer image.
|
||||
fn texel(image: &ColorImage, x: usize, y: usize) -> Color32 {
|
||||
image.pixels[y * 24 + x]
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_accent_part_paints_in_the_accent_ink_a_fixed_part_as_drawn_and_both_take_the_disabled_ink_when_disabled() {
|
||||
register_app_icons(&LAYERED_SET);
|
||||
register_app_icons(&PLAIN_SET);
|
||||
let tokens = style::tokens(Mode::Light, Contrast::Standard);
|
||||
let rect = Rect::from_min_max(pos2(10.0, 10.0), pos2(34.0, 34.0));
|
||||
let mut frames = Frames::new();
|
||||
// The icon painted by a `Draw` in `mode`: `Dimmed` is what a component in its Disabled state paints with.
|
||||
let mut paint = |name: &'static str, mode: DataMode, color: Color32| {
|
||||
let spec = IconSpec::svg(IconId::from(std::borrow::Cow::Borrowed(name))).color(StyleColor(color));
|
||||
let record = RefCell::new(PaintRecord::default());
|
||||
let shapes = frames.frame_shapes(|ui| {
|
||||
let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: Ink::OnPanel };
|
||||
Draw::new(ui.painter(), &record, env).data(mode).icon(rect, &spec);
|
||||
});
|
||||
textured(&shapes)
|
||||
};
|
||||
let (ink, off) = (ink_color(&tokens, Ink::OnPanel), rgba_color(tokens.color.text.disabled));
|
||||
let enabled = paint(LAYERED_NAME, DataMode::Full, ink);
|
||||
let disabled = paint(LAYERED_NAME, DataMode::Dimmed, ink);
|
||||
let enabled_in_the_disabled_colour = paint(LAYERED_NAME, DataMode::Full, off);
|
||||
|
||||
let [(ink_layer, ink_tint), (accent_layer, accent_tint), (fixed_layer, fixed_tint)] = enabled[..] else {
|
||||
panic!("an app icon paints its ink, accent and fixed layers, got {enabled:?}")
|
||||
};
|
||||
assert_eq!(ink_tint, ink, "the plain parts read in the icon's colour");
|
||||
assert_eq!(accent_tint, rgba_color(tokens.color.accent.solid), "the accent parts read in the accent ink");
|
||||
assert_ne!(accent_tint, ink_tint);
|
||||
assert_eq!(fixed_tint, Color32::WHITE, "the fixed parts keep the colours they are drawn in");
|
||||
assert!(ink_layer != accent_layer && accent_layer != fixed_layer && ink_layer != fixed_layer, "each layer is its own texture");
|
||||
|
||||
let [(off_ink, a), (off_accent, b), (off_fixed, c)] = disabled[..] else {
|
||||
panic!("a disabled app icon paints the same three layers, got {disabled:?}")
|
||||
};
|
||||
assert_eq!([a, b, c], [ink; 3], "every layer takes the one ink when the component is disabled");
|
||||
assert_eq!((off_ink, off_accent), (ink_layer, accent_layer), "the ink and accent layers are the same drawings, tinted");
|
||||
assert_ne!(off_fixed, fixed_layer, "a disabled fixed part is drawn as a silhouette, not in its own colours");
|
||||
|
||||
let tints: Vec<Color32> = enabled_in_the_disabled_colour.iter().map(|(_, tint)| *tint).collect();
|
||||
assert_eq!(tints, [off, rgba_color(tokens.color.accent.solid), Color32::WHITE], "an enabled icon in the disabled colour keeps its layers");
|
||||
|
||||
// What each layer holds: the class split is the SVG engine's, so a sheet it ignored would give every layer the whole drawing.
|
||||
let Some(layered) = icon(LAYERED_NAME) else { panic!("the layered icon resolves") };
|
||||
let (body, nib, cap) = ((9, 12), (16, 12), (3, 12));
|
||||
let [plain, accent, fixed] = [Layer::Ink, Layer::Accent, Layer::Fixed].map(|layer| layered.layer(24.0, 1.0, layer));
|
||||
assert!(texel(&plain, body.0, body.1).a() > 0 && texel(&plain, nib.0, nib.1).a() == 0, "the ink layer holds the plain body only");
|
||||
assert!(texel(&accent, nib.0, nib.1).a() > 0 && texel(&accent, body.0, body.1).a() == 0, "the accent layer holds the nib only");
|
||||
let red = texel(&fixed, cap.0, cap.1);
|
||||
assert!(red.a() > 0 && red.r() > red.g() && red.r() > red.b(), "the fixed layer holds the cap in its own colour: {red:?}");
|
||||
assert!(texel(&fixed, body.0, body.1).a() == 0 && texel(&plain, cap.0, cap.1).a() == 0, "the cap is in no other layer");
|
||||
|
||||
// An icon with no classed part paints its ink layer alone.
|
||||
assert_eq!(paint(PLAIN_NAME, DataMode::Full, ink).len(), 1, "a layer with no part paints no quad");
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use craft_ui::primitives::{
|
||||
LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, TextureBudget, TextureLoader, TextureState, TextureStore, TextureStoreOptions,
|
||||
};
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
use egui::{Color32, ColorImage, Context};
|
||||
use egui::{Color32, ColorImage, Context, Rect, TextureId, pos2};
|
||||
use std::cell::Cell;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
@@ -64,6 +64,62 @@ fn over_budget_the_oldest_unseen_entry_goes_first_and_a_fresh_entry_stays() {
|
||||
assert_eq!(crowded.statistics(&ctx).entries, 4, "entries of the previous frame stay too");
|
||||
}
|
||||
|
||||
/// A side four of which fill a page: two to a row, two rows.
|
||||
const TILE: usize = 1000;
|
||||
|
||||
/// The distinct textures of `textures`, in first-seen order.
|
||||
fn distinct(textures: impl IntoIterator<Item = TextureId>) -> Vec<TextureId> {
|
||||
let mut ids = Vec::new();
|
||||
for id in textures {
|
||||
if !ids.contains(&id) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// Pictures share pages; when every page is full and was drawn from in this frame no page starts over (the picture
|
||||
/// takes a texture of its own); a later frame starts over only the page not drawn from, in place.
|
||||
#[trial]
|
||||
fn a_packed_store_shares_pages_and_a_full_store_never_restarts_a_page_drawn_this_pass() {
|
||||
let mut frames = Frames::new();
|
||||
let ctx = frames.ctx.clone();
|
||||
let unit = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
|
||||
let plain = store_with(&ctx, "plain", TextureBudget::new(usize::MAX, usize::MAX));
|
||||
assert_eq!(plain.put(&ctx, 0, Revision::new(1), square(SMALL, shade(40))).uv(), unit, "an unpacked texture is drawn whole");
|
||||
|
||||
let budget = TextureBudget::new(usize::MAX, usize::MAX);
|
||||
let packed = TextureStore::<u32>::in_context(&ctx, "packed", TextureStoreOptions::thumbnails().packed(TILE as u32).budget(budget));
|
||||
let first: Vec<_> = (0..16).map(|key| packed.put(&ctx, key, Revision::new(1), square(TILE, shade(40 + key as u8)))).collect();
|
||||
let pages = distinct(first.iter().map(|texture| texture.id));
|
||||
assert!(pages.len() < first.len(), "pictures share pages: {} pages for {} pictures", pages.len(), first.len());
|
||||
let (a, b) = (first[0], first[1]);
|
||||
assert_eq!(a.id, b.id, "the first two pictures share a page");
|
||||
assert_ne!(a.uv(), b.uv());
|
||||
assert!(unit.contains_rect(a.uv()) && unit.contains_rect(b.uv()), "both lie in the page");
|
||||
assert!(!a.uv().intersects(b.uv()), "the two pictures do not overlap");
|
||||
assert_eq!(a.size_vec2(), egui::vec2(TILE as f32, TILE as f32), "a packed texture's size is the picture's own");
|
||||
|
||||
// Every page is full and drawn from in this frame: the next picture takes a texture of its own.
|
||||
let own = packed.put(&ctx, 16, Revision::new(1), square(TILE, shade(200)));
|
||||
assert!(!pages.contains(&own.id), "no page started over while its pictures are on screen");
|
||||
assert_eq!(own.uv(), unit);
|
||||
assert!((0..16).all(|key| ready(&packed.state(&ctx, &key, Revision::new(1)))), "every picture drawn this pass stays");
|
||||
|
||||
// A later frame draws from every page but the first one's: only that page starts over, in place.
|
||||
frames.idle(QUIET_FRAMES, |_| {});
|
||||
let page_of = |key: u32| first[key as usize].id;
|
||||
let kept: Vec<u32> = (0..16).filter(|key| page_of(*key) != a.id).collect();
|
||||
for key in &kept {
|
||||
assert!(ready(&packed.state(&ctx, key, Revision::new(1))));
|
||||
}
|
||||
let restarted = packed.put(&ctx, 17, Revision::new(1), square(TILE, shade(220)));
|
||||
assert_eq!(restarted.id, a.id, "the page drawn from longest ago starts over and keeps its texture");
|
||||
assert!((0..16).filter(|key| page_of(*key) == a.id).all(|key| packed.state(&ctx, &key, Revision::new(1)) == TextureState::Missing));
|
||||
assert!(kept.iter().all(|key| ready(&packed.state(&ctx, key, Revision::new(1)))), "pages drawn from this pass stay");
|
||||
assert_eq!(distinct(kept.iter().map(|key| page_of(*key)).chain([restarted.id])).len(), pages.len(), "no page was added");
|
||||
}
|
||||
|
||||
fn loader_with(ctx: &Context, lanes: usize, uploads: usize) -> (TextureLoader<u32>, Arc<ManualJobs>) {
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let budget = TextureBudget::new(usize::MAX, usize::MAX).uploads(uploads, usize::MAX);
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
use super::display_sense;
|
||||
use crate::contract::{Access, Common, Component, Cx, DisabledLook, MeasureCx, PaintUi, Props as _, Role};
|
||||
use crate::list::{ThumbAspect, ThumbSize};
|
||||
use crate::primitives::{ContentPainterCx, Revision, TextureStore, TextureStoreOptions, ThumbSource, Thumbnails, fit_rect};
|
||||
use crate::primitives::{
|
||||
ContentPainterCx, Priority, Revision, TextureStore, TextureStoreOptions, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails, fit_rect,
|
||||
};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::style::{ComponentStyle, StyleCx};
|
||||
use craft_behavior::{Metrics, Sense};
|
||||
use egui::{ColorImage, Id, Pos2, Rect, Response, Vec2};
|
||||
use egui::{ColorImage, Id, Rect, Response, Vec2};
|
||||
|
||||
#[cfg(feature = "testing")]
|
||||
mod stories;
|
||||
@@ -24,8 +26,8 @@ pub enum PictureSize {
|
||||
/// The sample of a thumbnail step in a panel's options dialog (`size.thumb.sample.*`); `ThumbSize::None` shows no
|
||||
/// picture.
|
||||
Sample(ThumbSize),
|
||||
/// The texture at its own size in device pixels: one image pixel to one screen pixel at every scale (owed by
|
||||
/// ribbon-w6, S-L172). A picture without pixels of its own takes the icon side.
|
||||
/// The image at its own size in device pixels, one texel to a pixel (a bitmap drawn for the screen's density).
|
||||
/// A painter or a picture made off the frame has no own size and takes the icon side.
|
||||
DevicePixels,
|
||||
}
|
||||
|
||||
@@ -49,7 +51,6 @@ enum Source<'a> {
|
||||
/// A content painter that paints into the picture's rect.
|
||||
Painter(Paint<'a>),
|
||||
/// A picture rendered off the frame by a thumbnail source, shown pending until it arrives.
|
||||
#[allow(dead_code)] // P3(ribbon-w6): rb.R23
|
||||
Rendered { key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64> },
|
||||
}
|
||||
|
||||
@@ -91,9 +92,11 @@ impl<'a> Picture<'a> {
|
||||
|
||||
/// A picture made off the frame by `source` for `key`: pending, with the framework's placeholder, until the
|
||||
/// source's picture arrives, then fitted as `new`'s texture is. `label` names it for a screen reader.
|
||||
/// The source's picture is asked through [`Thumbnails::state`] at the picture's rect and the screen's density,
|
||||
/// so a `ThumbRender::Later` render runs on the loader's lanes and no pass waits for it; its revision is the
|
||||
/// source's, not the `revision` prop.
|
||||
pub fn rendered(label: impl Into<Label>, key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
|
||||
let _ = (label.into(), key, thumbnails, source);
|
||||
todo!("rb.R23")
|
||||
Picture::from_source(label, Source::Rendered { key, thumbnails, source })
|
||||
}
|
||||
|
||||
fn from_source(label: impl Into<Label>, source: Source<'a>) -> Self {
|
||||
@@ -124,9 +127,10 @@ impl Component for Picture<'_> {
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
if let (PictureSize::DevicePixels, Source::Image { key, image }) = (self.extent, &self.source) {
|
||||
// The texture is the measured content: its size is known only once the image is made, so it is made here
|
||||
// and `paint` finds it at this revision and makes nothing.
|
||||
let ctx = cx.ui.ctx();
|
||||
let store = TextureStore::<(Id, u64)>::in_context(ctx, "picture", TextureStoreOptions::thumbnails());
|
||||
let texture = store.get_or_put(ctx, (cx.resolved.id, *key), self.revision, *image);
|
||||
let texture = store(ctx).get_or_put(ctx, (cx.resolved.id, *key), self.revision, *image);
|
||||
return texture.size_vec2() / ctx.pixels_per_point();
|
||||
}
|
||||
let height = cx.style.height;
|
||||
@@ -149,14 +153,18 @@ impl Component for Picture<'_> {
|
||||
}
|
||||
match &self.source {
|
||||
Source::Image { key, image } => {
|
||||
let store = TextureStore::<(Id, u64)>::in_context(&cx.ctx, "picture", TextureStoreOptions::thumbnails());
|
||||
let texture = store.get_or_put(&cx.ctx, (cx.resolved.id, *key), self.revision, *image);
|
||||
let texture = store(&cx.ctx).get_or_put(&cx.ctx, (cx.resolved.id, *key), self.revision, *image);
|
||||
let target = fit_rect(cx.content_rect, texture.size_vec2());
|
||||
let whole = Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0));
|
||||
ui.content_painter(cx).picture(texture.id, target, whole, 0.0);
|
||||
// The store packs, so the texture is the picture's part of a shared page.
|
||||
ui.content_painter(cx).picture(texture.id, target, texture.uv(), 0.0);
|
||||
}
|
||||
Source::Painter(paint) => paint(&ui.content_painter(cx), cx.content_rect),
|
||||
Source::Rendered { .. } => todo!("rb.R23"),
|
||||
Source::Rendered { key, thumbnails, source } => {
|
||||
let rect = cx.content_rect;
|
||||
let request = ThumbRequest::for_cell(rect.width().max(rect.height()), cx.ctx.pixels_per_point());
|
||||
let state = thumbnails.state(&cx.ctx, *source, key, &request, Priority::VISIBLE);
|
||||
thumbnails.paint(&ui.content_painter(cx), rect, &state, &ThumbPaint::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,3 +172,9 @@ impl Component for Picture<'_> {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The pictures' store of `ctx`: packed, so many small pictures (style tiles, font samples) share a few page
|
||||
/// textures; a larger picture takes a texture of its own.
|
||||
fn store(ctx: &egui::Context) -> TextureStore<(Id, u64)> {
|
||||
TextureStore::in_context(ctx, "picture", TextureStoreOptions::thumbnails().packed_small())
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::{Picture, PictureSize};
|
||||
use crate::contract::Show as _;
|
||||
use crate::list::{ThumbAspect, ThumbSize};
|
||||
use crate::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::{Color32, ColorImage, Ui};
|
||||
|
||||
@@ -30,6 +31,27 @@ fn picture_thumbnail(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
.into()
|
||||
}
|
||||
|
||||
/// A picture made off the frame: its source renders as a `Later` job, so the picture shows the placeholder until the
|
||||
/// job lands on the loader's lanes, then the picture.
|
||||
#[story(Picture<'static>, covers = [], drive = Drive::Never)]
|
||||
fn picture_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "craft_ui::stories::picture_rendered", ThumbnailOptions::new());
|
||||
let source = FakeThumbSource::<u64>::new().later(true).opaque(true);
|
||||
Picture::rendered("Rendered", 1, &thumbnails, &source).extent(PictureSize::Thumb(ThumbSize::Large)).show(ui).into()
|
||||
}
|
||||
|
||||
/// The gradient at its own size in device pixels, beside it at the icon side: the first keeps one texel to a pixel
|
||||
/// at every display scale.
|
||||
#[story(Picture<'static>, covers = [], drive = Drive::Never)]
|
||||
fn picture_device_pixels(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
ui.horizontal(|ui| {
|
||||
Picture::new("Gradient", 6, &gradient).extent(PictureSize::Icon).show(ui);
|
||||
Picture::new("Gradient", 7, &gradient).extent(PictureSize::DevicePixels).show(ui)
|
||||
})
|
||||
.inner
|
||||
.into()
|
||||
}
|
||||
|
||||
#[story(Picture<'static>, covers = [], drive = Drive::Never)]
|
||||
fn picture_painter(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Picture::painter("Swatch", ThumbAspect::new(4, 1), |cx, rect| cx.checker(rect)).extent(PictureSize::Thumb(ThumbSize::Large)).show(ui).into()
|
||||
|
||||
Reference in New Issue
Block a user