Merge remote-tracking branch 'origin/main' into pin/egui-window-move

# Conflicts:
#	Cargo.toml
This commit is contained in:
David Mann committed 2026-11-30 04:01:52 +01:00
commit 89ba4dbb1e
49 files changed
+3214 -248

No files matched your search

Generated
+6 -21
View File
@@ -835,12 +835,6 @@ dependencies = [
"cpufeatures 0.3.1",
]
[[package]]
name = "block"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -1685,19 +1679,6 @@ dependencies = [
"libc",
]
[[package]]
name = "core-graphics2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c"
dependencies = [
"bitflags 2.13.2",
"block",
"cfg-if",
"core-foundation 0.10.1",
"libc",
]
[[package]]
name = "core_detect"
version = "1.0.0"
@@ -2056,6 +2037,8 @@ dependencies = [
"block2 0.6.2",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-foundation 0.3.2",
]
@@ -3805,7 +3788,7 @@ dependencies = [
"async-process",
"clipboard-win",
"core-graphics",
"core-graphics2",
"craft-appkit",
"craft-atomic",
"craft-docpath",
"craft-host",
@@ -3817,6 +3800,8 @@ dependencies = [
"js-sys",
"log",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-foundation 0.3.2",
"rfd",
"serde",
@@ -14717,7 +14702,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winit"
version = "0.30.13"
source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc"
source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45"
dependencies = [
"android-activity",
"atomic-waker",
+1 -1
View File
@@ -342,7 +342,7 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
# 32-bit stream the prediction can leave the i32 range while the sum does not, so a debug build
+8 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-appkit"
description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
description = "The macOS menu-tracking observers, Save panel calls and Core Graphics display calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -9,12 +9,19 @@ repository.workspace = true
# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through
# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action.
# The active display list and an image's pixel bytes from Core Graphics.
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6.2"
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGDataProvider", "CGDirectDisplay", "CGError", "CGImage"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] }
# A test image made from known bytes.
[target.'cfg(target_os = "macos")'.dev-dependencies]
objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFData"] }
objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGColorSpace", "CGDataProvider", "CGImage"] }
# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's
# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one
# workspace lint.
+83
View File
@@ -0,0 +1,83 @@
//! The Core Graphics display calls that need `unsafe`: listing the active displays, and reading an image's pixels
//! without copying them a second time.
use objc2_core_graphics::{CGDataProvider, CGDirectDisplayID, CGError, CGGetActiveDisplayList, CGImage};
/// The largest `max` that [`active_displays`] accepts.
pub const MAX_DISPLAYS: usize = 1024;
/// The IDs of the active displays, at most `max` of them, or `None` when `max` is above [`MAX_DISPLAYS`] or Core
/// Graphics reports an error.
pub fn active_displays(max: usize) -> Option<Vec<CGDirectDisplayID>> {
if max > MAX_DISPLAYS {
return None;
}
let capacity = u32::try_from(max).ok()?;
let mut ids: Vec<CGDirectDisplayID> = vec![0; max];
let mut count = 0u32;
// SAFETY: `ids` holds `capacity` writable IDs and `count` is a writable `u32`. Core Graphics writes at most
// `capacity` IDs and the number it wrote.
let result = unsafe { CGGetActiveDisplayList(capacity, ids.as_mut_ptr(), &mut count) };
if result != CGError::Success {
return None;
}
ids.truncate(usize::try_from(count).ok()?.min(max));
Some(ids)
}
/// Calls `read` with the bytes of `image`'s pixels, or returns `None` when the image has no data provider or the
/// provider gives no data.
pub fn with_image_bytes<R>(image: &CGImage, read: impl FnOnce(&[u8]) -> R) -> Option<R> {
let data = CGDataProvider::data(CGImage::data_provider(Some(image)).as_deref())?;
// SAFETY: `CGDataProviderCopyData` returns a new immutable `CFData` that this function holds until `read`
// returns, so nothing changes its bytes while the slice is borrowed.
Some(read(unsafe { data.as_bytes_unchecked() }))
}
#[cfg(test)]
mod tests {
use objc2_core_foundation::CFData;
use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGImageAlphaInfo, CGMainDisplayID};
use super::*;
/// The list holds the main display and no more IDs than asked for; a `max` above the limit is refused.
#[test]
fn active_displays_lists_the_main_display_within_max() {
let all = active_displays(MAX_DISPLAYS).unwrap_or_default();
assert!(all.contains(&CGMainDisplayID()), "{all:?}");
// 0 is `kCGNullDirectDisplay`: an ID Core Graphics did not write.
assert!(!all.contains(&0), "{all:?}");
assert_eq!(active_displays(0), Some(Vec::new()));
assert_eq!(active_displays(1).map(|ids| ids.len()), Some(1));
assert_eq!(active_displays(MAX_DISPLAYS + 1), None);
assert_eq!(active_displays(usize::MAX), None);
}
/// The bytes passed on are the image's own pixel rows, row padding included.
#[test]
fn image_bytes_are_the_pixels_of_the_image() {
let pixels: Vec<u8> = (0u8..24).collect();
let provider = CGDataProvider::with_cf_data(Some(&CFData::from_bytes(&pixels))).unwrap_or_else(|| panic!("no provider"));
let space = CGColorSpace::new_device_rgb().unwrap_or_else(|| panic!("no color space"));
// SAFETY: two rows of two RGBA pixels with 4 bytes of padding (12 bytes a row), 24 bytes in the provider, and a
// null decode array.
let image = unsafe {
CGImage::new(
2,
2,
8,
32,
12,
Some(&space),
CGBitmapInfo(CGImageAlphaInfo::PremultipliedLast.0),
Some(&provider),
std::ptr::null(),
false,
CGColorRenderingIntent::RenderingIntentDefault,
)
}
.unwrap_or_else(|| panic!("no image"));
assert_eq!(with_image_bytes(&image, <[u8]>::to_vec), Some(pixels));
}
}
+4 -2
View File
@@ -1,5 +1,6 @@
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the
//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere.
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, the
//! Save panel calls in `save_panel`, and the Core Graphics display calls in `display`. macOS only; the crate is empty
//! elsewhere.
//!
//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every
//! block says why it is sound.
@@ -14,6 +15,7 @@ use block2::RcBlock;
use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification};
use objc2_foundation::{NSNotification, NSNotificationCenter};
pub mod display;
pub mod save_panel;
/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)`
+2 -2
View File
@@ -78,8 +78,8 @@ pub use picker::{
PickedColor, ScreenPickGesture, TrackRamp,
};
pub use picker_dialog::{
ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary,
PickerSwatches,
ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickedSwatch,
PickerLibrary, PickerSwatches,
};
pub use popover::{ColorPopover, ColorPopoverOutput};
pub use profile_prompts::{ProfileAction, ProfileAnswer, ProfileMismatchDialog, ProfileMode, ProfileQuestion, ProfileStatus, ProfileWords};
+1
View File
@@ -99,6 +99,7 @@ impl<'a> Body<'a> {
if shown.restore
&& let Mixed::Same(current) = pass.compare
{
got.restored = true;
got.clicks.push(current);
}
if let Some(warning) = shown.warning.and_then(|at| self.warnings.get(at)) {
+7 -4
View File
@@ -106,6 +106,8 @@ pub struct ColorPickerOutput {
pub events: EditEvents<PickedColor>,
/// The screen-pick button's press this pass.
pub screen_pick: Option<ScreenPickGesture>,
/// The compare block's current half was activated this pass.
pub restored: bool,
}
impl Outcome for ColorPickerOutput {
@@ -181,6 +183,7 @@ struct Collected {
edits: EditEvents<PickedColor>,
/// Colours the compare swatch and the warning chips set.
clicks: Vec<PickedColor>,
restored: bool,
screen_pick: Option<ScreenPickGesture>,
model_pick: Option<&'static str>,
/// The mode the "Field shows" group picked.
@@ -430,8 +433,8 @@ impl<'a> ColorPicker<'a> {
events: EditEvents::new(),
};
let shown = Stack::new().label(label).show(ui, |ui, body| run.show(ui, body));
let (events, screen_pick) = shown.inner.unwrap_or_default();
ColorPickerOutput { response: shown.output, events, screen_pick }
let (events, screen_pick, restored) = shown.inner.unwrap_or_default();
ColorPickerOutput { response: shown.output, events, screen_pick, restored }
}
}
@@ -461,7 +464,7 @@ struct Run<'s, 'a> {
}
impl<'a> Run<'_, 'a> {
fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents<PickedColor>, Option<ScreenPickGesture>) {
fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents<PickedColor>, Option<ScreenPickGesture>, bool) {
let memo = body.memory::<Memo>().clone();
let held_mode = self.mode.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied());
let mut mode = held_mode.unwrap_or(memo.mode);
@@ -546,7 +549,7 @@ impl<'a> Run<'_, 'a> {
None => body.memory::<Memo>().model = Some(next),
}
}
(std::mem::take(&mut self.events), got.screen_pick)
(std::mem::take(&mut self.events), got.screen_pick, got.restored)
}
/// Lands `event`, an edit of the colour: a gesture's end takes the colour it began from, the binding takes the
+167 -20
View File
@@ -128,9 +128,19 @@ impl PickerSwatches {
/// The Color Swatches view: the library `Select` over the chosen library's spaced palette, whose cell equal to the colour
/// in `held` is marked and whose pick replaces `held`; the notice for a library without swatches. `library` is the
/// remembered index, which may lie past the end; it is written only when the user chooses another. The dialog's buttons
/// stand in the cell after it, as they head the Full picker's second column.
fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: &mut Mixed<PickedColor>, library_label: &Label) {
/// stand in the cell after it, as they head the Full picker's second column. `selected`, the swatch the colour was
/// picked from, is the marked cell when its library is shown. Returns the swatch clicked this pass, also one with the
/// colour already held, whose colour `held` then takes.
fn show_swatches(
ui: &mut Ui,
view: &PickerSwatches,
library: &mut usize,
held: &mut Mixed<PickedColor>,
selected: Option<PickedSwatch>,
library_label: &Label,
) -> Option<PickedSwatch> {
let mut chosen = (*library).min(view.libraries.len().saturating_sub(1));
let mut clicked = None;
Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).cells(CellAlign::Top).gap(Gap::Section).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
if !view.libraries.is_empty() {
@@ -145,10 +155,20 @@ fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held:
Some(lib) => {
// A colour that is not set marks no cell of a library without it; black stands for "none yet".
let color = held.same().map_or(Srgba::BLACK, |picked| picked.color);
let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches).spacing(SwatchSpacing::Spaced).show(ui);
let marked = selected.filter(|s| s.library == chosen).map(|s| s.index);
let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches)
.spacing(SwatchSpacing::Spaced)
.selected_swatch(marked)
.show(ui);
if let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()).copied() {
*held = Mixed::Same(PickedColor::rgb(picked));
}
// The clicked swatch's own colour, also when the palette files no edit for it (the colour held, or
// one that rounds to it).
if let Some((index, (_, color))) = shown.picked_swatch.and_then(|index| Some((index, lib.swatches.get(index)?))) {
*held = Mixed::Same(PickedColor::rgb(*color));
clicked = Some(PickedSwatch { library: chosen, index });
}
}
None => {
Notice::new(Tone::Neutral, view.empty.clone()).layout(NoticeLayout::Centred).show(ui);
@@ -157,6 +177,24 @@ fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held:
});
let _ = FooterSlot::new().show(ui);
});
clicked
}
/// A swatch of a [`ColorPickerDialog`]'s Color Swatches view, by its place in the [`PickerSwatches`] the app gave.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct PickedSwatch {
/// The index of its library in [`PickerSwatches::libraries`].
pub library: usize,
/// The index of the swatch in that library's [`PickerLibrary::swatches`].
pub index: usize,
}
impl PickedSwatch {
/// The swatch at `index` of library `library`.
pub fn new(library: usize, index: usize) -> Self {
PickedSwatch { library, index }
}
}
/// The remembered scope of [`ColorPickerMemory`].
@@ -170,6 +208,9 @@ pub struct ColorPickerResult {
pub key: String,
/// The colour, with the model values the user typed while they still give it (CMYK inks, Lab values outside sRGB).
pub picked: PickedColor,
/// The swatch of the Color Swatches view the colour was picked from, when the last change to the colour was a click
/// on that swatch; `None` when the colour was set any other way, or changed after the click.
pub swatch: Option<PickedSwatch>,
}
/// How a [`ColorPickerDialog`] lays out its body.
@@ -238,6 +279,9 @@ pub struct ColorPickerDialog {
opening: Option<PickedColor>,
/// The colour as it stands; `None` until the first pick when the dialog opened without one.
current: Option<PickedColor>,
/// The colour was set by the caller ([`set_color`](Self::set_color), [`pick_swatch`](Self::pick_swatch)); the
/// Only Web Colors snap at the start then leaves it as it is.
color_set: bool,
compare: bool,
/// [`no_current`](Self::no_current).
no_current: bool,
@@ -247,6 +291,8 @@ pub struct ColorPickerDialog {
working_rgb: Option<Box<dyn ColorModel + Send + Sync>>,
gamut: Option<Gamut<'static>>,
swatches: Option<PickerSwatches>,
/// The swatch the current colour was picked from, while no other change has followed the click.
picked_swatch: Option<PickedSwatch>,
eyedropper: bool,
canvas_samples: bool,
canvas: Option<Id>,
@@ -420,6 +466,7 @@ impl ColorPickerDialog {
title_args: Vec::new(),
opening,
current: opening,
color_set: false,
compare: true,
no_current: false,
remember: true,
@@ -428,6 +475,7 @@ impl ColorPickerDialog {
working_rgb: None,
gamut: None,
swatches: None,
picked_swatch: None,
eyedropper: true,
canvas_samples: true,
canvas: None,
@@ -449,10 +497,12 @@ impl ColorPickerDialog {
}
/// In the Full layout, a body button after Cancel switches between Color Models and Color Swatches: a library `Select` over a spaced
/// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button.
/// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button. A swatch
/// picked from the view it replaces is no longer named.
#[must_use]
pub fn swatch_view(mut self, swatches: PickerSwatches) -> ColorPickerDialog {
self.swatches = Some(swatches);
self.picked_swatch = None;
self
}
@@ -465,9 +515,13 @@ impl ColorPickerDialog {
}
/// Sets the dialog's layout: Full (Photoshop) or Tabbed (Word's Colors dialog).
/// A layout other than Full clears the picked swatch and keeps the current color.
#[must_use]
pub fn layout(mut self, l: ColorPickerDialogLayout) -> ColorPickerDialog {
self.layout = l;
if l != ColorPickerDialogLayout::Full {
self.picked_swatch = None;
}
self
}
@@ -497,7 +551,12 @@ impl ColorPickerDialog {
/// what the sRGB colour converts to (storytold/photocraft#4196).
#[must_use]
pub fn kept(mut self, values: craft_theme::ModelValues) -> ColorPickerDialog {
for held in [&mut self.opening, &mut self.current].into_iter().flatten() {
if let Some(held) = &mut self.opening {
held.model = Some(values);
}
if self.picked_swatch.is_none()
&& let Some(held) = &mut self.current
{
held.model = Some(values);
}
self
@@ -614,6 +673,28 @@ impl ColorPickerDialog {
/// model values when it has them, and the colour is what OK answers. The compare swatch keeps the opening colour.
pub fn set_color(&mut self, picked: PickedColor) {
self.current = Some(picked);
self.color_set = true;
self.picked_swatch = None;
}
/// The swatch of the Color Swatches view the colour was picked from, while no other change has followed the click
/// (what OK answers as [`ColorPickerResult::swatch`]).
pub fn picked_swatch(&self) -> Option<PickedSwatch> {
self.picked_swatch
}
/// Picks `swatch` of the Color Swatches view as a click on it would, for automation and scripts: the colour becomes
/// the swatch's and its library the one shown. `None` when the layout is not Full or the view has no such swatch.
pub fn pick_swatch(&mut self, swatch: PickedSwatch) -> Option<()> {
if self.layout != ColorPickerDialogLayout::Full {
return None;
}
let (_, color) = self.swatches.as_ref()?.libraries.get(swatch.library)?.swatches.get(swatch.index)?;
self.current = Some(PickedColor::rgb(*color));
self.color_set = true;
self.memory.library = swatch.library;
self.picked_swatch = Some(swatch);
Some(())
}
/// The colour Add to Swatches was pressed for, once; `None` otherwise.
@@ -640,7 +721,7 @@ impl ColorPickerDialog {
{
Remembered::<ColorPickerMemory>::new(MEMORY_SCOPE).store(host, &self.memory);
}
Some(ColorPickerResult { key: self.key.clone(), picked })
Some(ColorPickerResult { key: self.key.clone(), picked, swatch: self.picked_swatch })
}
/// Runs the dialog's start for automation that reaches it before its first pass.
@@ -651,6 +732,29 @@ impl ColorPickerDialog {
}
}
/// Sets one JSON field after the dialog's start: `swatch`, `color` or a memory field.
fn set_field(&mut self, field: &str, value: serde_json::Value) -> Result<(), String> {
if field == "swatch" {
if value.is_null() {
self.picked_swatch = None;
return Ok(());
}
let index = |i: usize| value.get(i).and_then(serde_json::Value::as_u64).and_then(|n| usize::try_from(n).ok());
let swatch = match (value.as_array().map(Vec::len), index(0), index(1)) {
(Some(2), Some(library), Some(index)) => PickedSwatch { library, index },
_ => return Err(FieldRefusal::Rejects(&value).message(field)),
};
return self.pick_swatch(swatch).ok_or_else(|| FieldRefusal::Rejects(&value).message(field));
}
if field != "color" {
return set_serde_field(&mut self.memory, field, value);
}
let parsed = value.as_str().and_then(Srgba::from_hex);
let color = parsed.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.set_color(PickedColor { color, model: None });
Ok(())
}
/// The first pass: recalls the remembered field component and Only Web Colors, and with Only Web Colors on snaps
/// the opening colour, which the compare swatch's current half follows (storytold/photocraft#4995).
fn start(&mut self, host: Option<&Arc<Host>>) {
@@ -672,7 +776,12 @@ impl ColorPickerDialog {
{
let [r, g, b] = web_safe([opening.color.r, opening.color.g, opening.color.b]);
self.opening = Some(PickedColor { color: Srgba { r, g, b, a: opening.color.a }, model: None });
self.current = self.opening;
if !self.color_set {
self.current = self.opening;
}
}
if let Some(swatch) = self.picked_swatch {
self.memory.library = swatch.library;
}
}
@@ -710,24 +819,46 @@ impl StackDialog for ColorPickerDialog {
self.instance
}
/// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab`
/// and `model`.
/// `color` (`#rrggbb`, null when there is none yet), `swatch` (`[library, index]` of the swatch the colour was picked
/// from, or null), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab` and `model`.
fn json_fields(&self) -> Option<serde_json::Value> {
let mut fields = serde_fields(&self.memory)?;
let color = self.current.map_or(serde_json::Value::Null, |picked| picked.color.to_hex().into());
fields.as_object_mut()?.insert("color".to_owned(), color);
let swatch = self.picked_swatch.map_or(serde_json::Value::Null, |s| serde_json::json!([s.library, s.index]));
let object = fields.as_object_mut()?;
object.insert("color".to_owned(), color);
object.insert("swatch".to_owned(), swatch);
Some(fields)
}
fn set_json_field(&mut self, ctx: &Context, field: &str, value: serde_json::Value) -> Result<(), String> {
// The dialog's start recalls the memory and snaps the opening colour; a field set before it would be overwritten.
self.set_json_fields(ctx, &[(field.to_owned(), value)])
}
/// Sets the fields in order; when one is refused, the fields and startup state are restored to their earlier values.
fn set_json_fields(&mut self, ctx: &Context, fields: &[(String, serde_json::Value)]) -> Result<(), String> {
if fields.is_empty() {
return Ok(());
}
let before = (
self.started,
self.host.clone(),
self.opening,
self.current,
self.color_set,
self.picked_swatch,
self.memory.clone(),
self.tab,
self.on_swatches,
);
self.start_headless(ctx);
if field != "color" {
return set_serde_field(&mut self.memory, field, value);
for (field, value) in fields {
if let Err(refusal) = self.set_field(field, value.clone()) {
(self.started, self.host, self.opening, self.current, self.color_set, self.picked_swatch, self.memory, self.tab, self.on_swatches) =
before;
return Err(refusal);
}
}
let parsed = value.as_str().and_then(Srgba::from_hex);
let color = parsed.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
self.set_color(PickedColor { color, model: None });
Ok(())
}
@@ -774,7 +905,8 @@ impl StackDialog for ColorPickerDialog {
}
};
let footer = ResetFooter::new(ui, None, true);
let changed = self.current != self.opening;
// A swatch picked at the opening colour is a change Reset takes back.
let changed = self.current != self.opening || self.picked_swatch.is_some();
let mut buttons = footer.buttons(FooterButton::new(common.ok.clone(), DialogRole::Accept).enabled(self.current.is_some()), changed).to_vec();
let full = self.layout == ColorPickerDialogLayout::Full;
// The buttons after OK and Cancel are placed by position; their indices are read back from the list.
@@ -809,6 +941,7 @@ impl StackDialog for ColorPickerDialog {
layout,
standard,
swatches: view,
picked_swatch,
working_rgb,
..
} = self;
@@ -817,6 +950,9 @@ impl StackDialog for ColorPickerDialog {
let (sampled, busy, compare_with) = (sample.take(), *screen_busy, compare.then(|| opening.map_or(Mixed::Mixed, Mixed::Same)));
let color = current.map(|current| current.color);
let web_only = memory.web_colors;
let mut clicked = None;
let mut restored = false;
let mut sample_processed = false;
let shown = Dialog::new(title.clone())
.opened(Bind::bound(open))
.buttons(buttons)
@@ -846,7 +982,7 @@ impl StackDialog for ColorPickerDialog {
// PLAN: the swatch view should keep the value fields and replace only the area and strip, which the picker body
// (picker/mod.rs, not in this set) lays out; here it replaces the whole picker body.
if let Some(view) = view.as_ref().filter(|_| memory.swatches) {
show_swatches(ui, view, &mut memory.library, &mut held, &words.library);
clicked = show_swatches(ui, view, &mut memory.library, &mut held, *picked_swatch, &words.library);
return;
}
let mut models = models_with(working_rgb, |on| on.full);
@@ -874,16 +1010,26 @@ impl StackDialog for ColorPickerDialog {
.eyedropper_busy(busy);
if let Some(sampled) = sampled {
picker = picker.sampled(sampled);
sample_processed = true;
}
if let Some(compare) = compare_with {
picker = picker.compare(compare);
}
picker = picker.compare_none(*no_current);
if let Some(gesture) = picker.show(ui).screen_pick {
let output = picker.show(ui);
restored = output.restored;
if let Some(gesture) = output.screen_pick {
*pending_screen = Some(gesture);
}
});
self.current = held.same().copied();
let after = held.same().copied();
// A swatch click names the swatch; any other change to the colour leaves it picked from no swatch.
if clicked.is_some() {
self.picked_swatch = clicked;
} else if restored || sample_processed || after != self.current {
self.picked_swatch = None;
}
self.current = after;
let (picked, closed) = (shown.output.picked, shown.output.closed);
if picked.is_some() && picked == toggle_at {
@@ -893,6 +1039,7 @@ impl StackDialog for ColorPickerDialog {
let ok = (picked == Some(0) || closed == Some(CloseReason::Enter)) && self.current.is_some();
if !ok && picked == Some(1) && footer.resetting() {
self.current = self.opening;
self.picked_swatch = None;
return None;
}
if picked.is_some() && picked == add_at {
+319 -1
View File
@@ -6,7 +6,7 @@ use std::rc::Rc;
use craft_behavior::Mixed;
use craft_color_ui::ui::{
ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab,
ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches,
ColorPopover, ColorReadout, ColorWarning, PickedColor, PickedSwatch, PickerLibrary, PickerSwatches,
};
use craft_host::{AppInfo, Host};
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId};
@@ -509,6 +509,324 @@ fn the_color_picker_dialogs_swatch_view_marks_the_current_colour_and_a_pick_is_a
assert!(fixture.texts().iter().any(|run| run.text == "No swatches"), "an empty library shows the notice");
}
const SWATCH_RED: Srgba = Srgba { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
const SWATCH_BLUE: Srgba = Srgba { r: 0.0, g: 0.0, b: 1.0, a: 1.0 };
/// A picker opened on red over two libraries, showing library 1: two swatches of one blue, and red.
fn swatch_picker() -> (Rc<RefCell<DialogHost>>, Fixture) {
let (red, blue) = (SWATCH_RED, SWATCH_BLUE);
let id = dialog_id(("color-picker", "fill"));
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&dialogs);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(vec2(900.0, 700.0));
let libraries = vec![
PickerLibrary::new("Basic", vec![(Label::from("Red"), red)]),
PickerLibrary::new("Inks", vec![(Label::from("Blue A"), blue), (Label::from("Blue B"), blue), (Label::from("Ink Red"), red)]),
];
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red).swatch_view(PickerSwatches::new(libraries, "No swatches")));
fixture.idle(6);
let ctx = fixture.ctx().clone();
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatches", serde_json::json!(true)), Ok(()));
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(1)), Ok(()));
fixture.idle(4);
(dialogs, fixture)
}
/// OK on the picker: its colour and the swatch it names.
fn swatch_answer(dialogs: &Rc<RefCell<DialogHost>>, fixture: &Fixture) -> Option<(String, Option<PickedSwatch>)> {
let ctx = fixture.ctx().clone();
assert!(dialogs.borrow_mut().confirm::<ColorPickerDialog>(&ctx));
dialogs.borrow_mut().take::<ColorPickerDialog>().and_then(DialogResult::ok).map(|result| (result.picked.color.to_hex(), result.swatch))
}
/// OK names the swatch the colour was picked from, by its library and its place there, also among swatches of one
/// colour and for a click on the colour already held; a later change to the colour leaves it named by none.
#[trial]
fn the_color_picker_dialog_answers_the_swatch_its_colour_was_picked_from() {
let (red, blue) = (SWATCH_RED, SWATCH_BLUE);
let id = dialog_id(("color-picker", "fill"));
let open = swatch_picker;
let answer = swatch_answer;
let click = |fixture: &mut Fixture, name: &str| {
let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the swatch view shows {name}"));
fixture.click(&cell).idle(4);
};
let (dialogs, mut fixture) = open();
click(&mut fixture, "Blue B");
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 1)));
let selected = |fixture: &Fixture, name: &str| {
let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the swatch view shows {name}"));
fixture.tree().selected_of(cell.node).unwrap_or(false)
};
assert!(selected(&fixture, "Blue B") && !selected(&fixture, "Blue A"), "the clicked one of two blue swatches is marked");
assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), Some(PickedSwatch::new(1, 1)))), "the second of two blue swatches");
let (dialogs, mut fixture) = open();
click(&mut fixture, "Ink Red");
assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), Some(PickedSwatch::new(1, 2)))), "a click on the colour already held");
let (dialogs, mut fixture) = open();
click(&mut fixture, "Blue A");
let ctx = fixture.ctx().clone();
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "color", serde_json::json!("#00ff00")), Ok(()));
fixture.idle(2);
assert_eq!(answer(&dialogs, &fixture), Some(("#00ff00".to_owned(), None)), "a colour set after the click is no swatch's");
let (dialogs, fixture) = open();
assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), None)), "the opening colour was picked from no swatch");
}
/// Automation picks a swatch by its place, as a click does, is refused a place the view does not have, and clears the
/// pick with null; a refused batch of fields leaves the colour, the pick and the library as they were.
#[trial]
fn automation_picks_a_color_picker_swatch_and_a_refused_batch_restores_the_pick() {
let (red, blue) = (SWATCH_RED, SWATCH_BLUE);
let id = dialog_id(("color-picker", "fill"));
let open = swatch_picker;
let answer = swatch_answer;
let (dialogs, fixture) = open();
let ctx = fixture.ctx().clone();
for bad in [serde_json::json!([1, 3]), serde_json::json!([2, 0]), serde_json::json!([1]), serde_json::json!("1,1")] {
assert!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", bad.clone()).is_err(), "{bad} is refused");
}
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::json!([1, 1])), Ok(()));
let fields = dialogs.borrow().get::<ColorPickerDialog>().and_then(StackDialog::json_fields);
assert_eq!(fields.as_ref().map(|f| f["swatch"].clone()), Some(serde_json::json!([1, 1])), "the fields report the picked swatch");
assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), Some(PickedSwatch::new(1, 1)))), "a swatch picked by automation");
let (dialogs, fixture) = open();
let ctx = fixture.ctx().clone();
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::json!([1, 1])), Ok(()));
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::Value::Null), Ok(()));
assert_eq!(dialog_field(&dialogs, "swatch"), Some(serde_json::Value::Null));
assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), None)), "clearing the pick keeps its colour");
for picked in [None, Some(PickedSwatch::new(1, 1))] {
let (dialogs, fixture) = open();
let ctx = fixture.ctx().clone();
if let Some(swatch) = picked {
assert_eq!(dialogs.borrow_mut().get_mut::<ColorPickerDialog>().expect("the picker").pick_swatch(swatch), Some(()));
}
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(0)), Ok(()));
let before = dialogs.borrow().get::<ColorPickerDialog>().and_then(StackDialog::json_fields);
let current = dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.current());
for order in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] {
let edits = [
("color".to_owned(), serde_json::json!("#00ff00")),
("swatch".to_owned(), serde_json::json!([0, 0])),
("library".to_owned(), serde_json::json!(1)),
];
let mut fields: Vec<_> = order.into_iter().map(|index| edits[index].clone()).collect();
fields.push(("swatch".to_owned(), serde_json::json!([2, 0])));
assert!(dialogs.borrow_mut().set_json_fields(&ctx, id, &fields).is_err());
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(StackDialog::json_fields), before);
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.current()), current);
}
let color = if picked.is_some() { blue } else { red };
assert_eq!(answer(&dialogs, &fixture), Some((color.to_hex(), picked)), "a refused batch restores the earlier pick");
}
}
/// A tabbed picker shows no swatch view, so it refuses a swatch pick and keeps its colour.
#[trial]
fn a_tabbed_color_picker_refuses_swatch_picks() {
let red = SWATCH_RED;
let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)])];
let mut dialog = ColorPickerDialog::new("fill", "Fill", red)
.layout(ColorPickerDialogLayout::Tabbed)
.swatch_view(PickerSwatches::new(libraries, "No swatches"));
let before = dialog.json_fields();
assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), None);
assert_eq!(dialog.json_fields(), before);
assert!(dialog.set_json_field(&egui::Context::default(), "swatch", serde_json::json!([0, 0])).is_err());
assert_eq!(dialog.json_fields(), before);
assert_eq!(dialog.current(), Some(PickedColor::rgb(red)));
assert_eq!(dialog.picked_swatch(), None);
let mut dialog = dialog.layout(ColorPickerDialogLayout::Full);
assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(()));
let dialog = dialog.layout(ColorPickerDialogLayout::Tabbed);
assert_eq!(dialog.current(), Some(PickedColor::rgb(SWATCH_BLUE)));
assert_eq!(dialog.picked_swatch(), None);
}
/// A refused batch of fields set before the dialog first runs leaves it as it was, and its start runs later as usual.
#[trial]
fn a_refused_color_picker_batch_restores_state_before_startup() {
let opened = Srgba::from_hex("#123456").expect("a color outside the web colors");
let snapped = Srgba::from_hex("#003366").expect("the nearest web color");
let id = dialog_id(("color-picker", "fill"));
for render in [false, true] {
for picked in [None, Some(PickedSwatch::new(1, 0))] {
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&dialogs);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(vec2(900.0, 700.0));
fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-batch-test", name: "Picker test", version: "0" }).build()));
fixture.idle(1);
let ctx = fixture.ctx().clone();
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED));
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(()));
assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None)));
let libraries = vec![
PickerLibrary::new("Basic", vec![(Label::from("Red"), SWATCH_RED)]),
PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)]),
];
let request = craft_ui::runtime::requests::ColorRequest::new("fill", opened).on_swatches();
let mut dialog =
ColorPickerDialog::from_request(request).tab(ColorPickerTab::Custom).swatch_view(PickerSwatches::new(libraries, "No swatches"));
if let Some(swatch) = picked {
assert_eq!(dialog.pick_swatch(swatch), Some(()));
}
let before = dialog.json_fields();
let current = dialog.current();
assert!(dialog.set_json_field(&ctx, "swatch", serde_json::json!([2, 0])).is_err());
assert_eq!(dialog.json_fields(), before);
assert_eq!(dialog.opening(), Some(PickedColor::rgb(opened)));
assert_eq!(dialog.current(), current);
assert_eq!(dialog.picked_swatch(), picked);
let fields = [("swatch".to_owned(), serde_json::json!([0, 0])), ("swatch".to_owned(), serde_json::json!([2, 0]))];
assert!(dialog.set_json_fields(&ctx, &fields).is_err());
assert_eq!(dialog.json_fields(), before);
assert_eq!(dialog.opening(), Some(PickedColor::rgb(opened)));
assert_eq!(dialog.current(), current);
assert_eq!(dialog.picked_swatch(), picked);
dialogs.borrow_mut().open(dialog);
if render {
fixture.idle(6);
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.opening()), Some(PickedColor::rgb(snapped)));
}
let color = if picked.is_some() { SWATCH_BLUE } else { snapped };
assert_eq!(swatch_answer(&dialogs, &fixture), Some((color.to_hex(), picked)), "startup runs after a refused batch");
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED));
fixture.idle(6);
assert_eq!(dialog_field(&dialogs, "tab"), Some(serde_json::json!("custom")));
assert_eq!(dialog_field(&dialogs, "swatches"), Some(serde_json::json!(true)));
assert_eq!(dialog_field(&dialogs, "library"), Some(serde_json::json!(usize::from(picked.is_some()))));
}
}
}
/// Restoring the opening color clears an equal-color swatch selection.
#[trial]
fn restoring_the_current_color_clears_the_picked_swatch() {
let (dialogs, mut fixture) = swatch_picker();
let red = fixture.by_label("Ink Red").expect("the opening color's swatch");
fixture.click(&red).idle(4);
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 2)));
let models = fixture.by_label("Color Models").expect("the model view button");
fixture.click(&models).idle(4);
let restore = fixture.by_label("Restore current color").expect("the compare block's current half");
fixture.click(&restore).idle(4);
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), None);
assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None)));
}
/// Opening model values leave a picked swatch's RGB-only result unchanged.
#[trial]
fn opening_model_values_do_not_change_a_picked_swatch() {
let values = ModelValues::new("cmyk", &[0.0, 100.0, 100.0, 0.0]);
let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)])];
let mut dialog = ColorPickerDialog::new("fill", "Fill", SWATCH_RED).swatch_view(PickerSwatches::new(libraries, "No swatches"));
assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(()));
let mut dialog = dialog.kept(values);
assert_eq!(dialog.opening(), Some(PickedColor { color: SWATCH_RED, model: Some(values) }));
assert_eq!(dialog.current(), Some(PickedColor::rgb(SWATCH_BLUE)));
let result = dialog.confirm(&egui::Context::default()).expect("the selected swatch");
assert_eq!(result.picked, PickedColor::rgb(SWATCH_BLUE));
assert_eq!(result.swatch, Some(PickedSwatch::new(0, 0)));
}
/// A swatch picked before the dialog first runs keeps its colour through the Only Web Colors snap, and OK remembers its
/// library.
#[trial]
fn a_color_picker_swatch_picked_before_startup_survives_it() {
let red = SWATCH_RED;
let id = dialog_id(("color-picker", "fill"));
let answer = swatch_answer;
for render in [false, true] {
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&dialogs);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(vec2(900.0, 700.0));
fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-start-test", name: "Picker test", version: "0" }).build()));
fixture.idle(1);
let ctx = fixture.ctx().clone();
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red));
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(()));
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatches", serde_json::json!(true)), Ok(()));
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(0)), Ok(()));
assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), None)));
let ink = Srgba::from_hex("#123456").expect("a colour outside the web colours");
let libraries =
vec![PickerLibrary::new("Basic", vec![(Label::from("Red"), red)]), PickerLibrary::new("Inks", vec![(Label::from("Ink"), ink)])];
let mut dialog = ColorPickerDialog::new("fill", "Fill", red).swatch_view(PickerSwatches::new(libraries, "No swatches"));
assert_eq!(dialog.pick_swatch(PickedSwatch::new(1, 0)), Some(()));
dialogs.borrow_mut().open(dialog);
if render {
fixture.idle(6);
}
assert_eq!(answer(&dialogs, &fixture), Some((ink.to_hex(), Some(PickedSwatch::new(1, 0)))), "startup keeps the direct pick");
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red));
fixture.idle(6);
assert_eq!(dialog_field(&dialogs, "library"), Some(serde_json::json!(1)), "OK remembers the picked swatch's library");
}
}
/// Replacing the swatch view before startup keeps the selected color and clears its swatch identity.
#[trial]
fn replacing_the_swatch_view_before_startup_preserves_the_selected_color() {
for render in [false, true] {
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&dialogs);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(vec2(900.0, 700.0));
fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-replace-test", name: "Picker test", version: "0" }).build()));
fixture.idle(1);
let ctx = fixture.ctx().clone();
let id = dialog_id(("color-picker", "fill"));
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED));
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(()));
assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None)));
let ink = Srgba::from_hex("#123456").expect("a color outside the web colors");
let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Ink"), ink)])];
let mut dialog = ColorPickerDialog::new("fill", "Fill", SWATCH_RED).swatch_view(PickerSwatches::new(libraries, "No swatches"));
assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(()));
let dialog = dialog.swatch_view(PickerSwatches::new(Vec::new(), "No swatches"));
assert_eq!(dialog.picked_swatch(), None);
assert_eq!(dialog.current(), Some(PickedColor::rgb(ink)));
dialogs.borrow_mut().open(dialog);
if render {
fixture.idle(6);
}
assert_eq!(swatch_answer(&dialogs, &fixture), Some((ink.to_hex(), None)));
}
}
/// Sampling the selected swatch's color from the canvas clears its swatch identity.
#[trial]
fn an_equal_color_canvas_sample_clears_the_picked_swatch() {
let (dialogs, mut fixture) = swatch_picker();
let blue = fixture.by_label("Blue B").expect("the blue swatch");
fixture.click(&blue);
fixture.settle();
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 1)));
let models = fixture.by_label("Color Models").expect("the model view button");
fixture.click(&models);
fixture.settle();
dialogs.borrow_mut().get_mut::<ColorPickerDialog>().expect("the picker").requests().answer_eyedropper("fill", SWATCH_BLUE);
fixture.settle();
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.current()), Some(PickedColor::rgb(SWATCH_BLUE)));
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), None);
assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_BLUE.to_hex(), None)));
}
/// The Compact picker's width is set by the area and the strip, and its rows take that width; its popover is as wide
/// wherever the well stands and whatever the room.
#[trial]
+4 -7
View File
@@ -287,14 +287,11 @@ fn truncated_metadata_never_panics_and_falls_back() {
let _ = xmp_with_resolution(x, (1.0, 1.0));
}
// Property-like text repeated inside the packet must not trigger a full-suffix rescan
// per occurrence (it used to be quadratic). With the cursor advancing past each located
// value, this completes well under a second even with many decoys; a timeout here would
// indicate the quadratic scan returned. A clean packet still extracts correctly.
let start = std::time::Instant::now();
// Property-like text repeated inside the packet has no value. craft-metadata's
// `repeated_property_text_is_searched_once_for_each_property` counts the bytes this search
// reads. A clean packet still extracts correctly.
let decoys = " tiff:ResolutionUnit>".repeat(50_000);
let _ = xmp_resolution(&decoys);
assert!(start.elapsed() < std::time::Duration::from_secs(2), "xmp scan took too long: {:?}", start.elapsed());
assert_eq!(xmp_resolution(&decoys), None);
let clean = "<tiff:XResolution>300/1</tiff:XResolution><tiff:YResolution>300/1</tiff:YResolution><tiff:ResolutionUnit>2</tiff:ResolutionUnit>";
near(xmp_resolution(clean), 300.0);
}
+5 -2
View File
@@ -43,8 +43,11 @@ impl Default for LayersSettings {
#[serde(default)]
#[non_exhaustive]
pub struct LayersOptions {
/// Thumbnail Size: [`ThumbSize::None`], `Small`, `Medium` (default) or `Large`; the row
/// height follows the size's `size.thumb.*` token.
/// Thumbnail Size: [`ThumbSize::None`], `Small`, `Medium` (default) or `Large`, whose row
/// height follows the size's `size.thumb.*` token, or [`ThumbSize::Custom`], a row height
/// the app sets in whole points (see [`ThumbPoints`](craft_ui::list::ThumbPoints) for the
/// range). The dialog's radio group offers the named sizes; it keeps a custom size while none
/// of them is picked.
pub thumbnail_size: ThumbSize,
/// Thumbnail Contents: Layer Bounds or Entire Document (default). The panel menu's Clip
/// Thumbnails to Layer Bounds is the same setting; it is part of every
+1
View File
@@ -2,6 +2,7 @@
pub(crate) mod blend_rows;
pub(crate) mod comps;
pub(crate) mod options;
pub(crate) mod panel_drag_menu;
pub(crate) mod panel_eye;
pub(crate) mod panel_filter;
+62
View File
@@ -0,0 +1,62 @@
//! Layers Panel Options with a custom thumbnail size: the saved section keeps it, a saved size outside the range reads
//! back clamped, and the panel's rows take it as their height.
use craft_layers::testing;
use craft_layers::ui::mock::FakeLayers;
use craft_layers::ui::options::LayersSettings;
use craft_layers::ui::panel::LayersPanel;
use craft_layers::ui::tree::{LayerInfo, LayerKind, LayerPart};
use craft_ui::contract::Tracked;
use craft_ui::list::{ThumbPoints, ThumbSize};
use craft_ui::testing::{Fixture, trial};
use egui::{Rect, Vec2};
/// The panel's room: wide enough for a row's parts and inside the 800 by 600 screen of a fixture.
const PANEL: Vec2 = Vec2::new(420.0, 560.0);
/// The settings with a custom thumbnail size of `points`.
fn custom(points: u16) -> LayersSettings {
let mut settings = LayersSettings::default();
settings.options.thumbnail_size = ThumbSize::Custom(ThumbPoints::new(points));
settings
}
/// A saved section keeps a custom thumbnail size, and one saved outside the range reads back clamped into it.
#[trial]
fn a_custom_thumbnail_size_round_trips_through_the_saved_section() {
let settings = custom(48);
let saved = serde_json::to_string(&settings).expect("the section saves");
let read: LayersSettings = serde_json::from_str(&saved).expect("the section reads back");
assert_eq!(read, settings, "the custom size reads back as saved: {saved}");
let mut too_large = serde_json::to_value(&settings).expect("the section saves");
too_large["options"]["thumbnail_size"]["Custom"] = serde_json::Value::from(u16::MAX);
let clamped: LayersSettings = serde_json::from_value(too_large).expect("a size outside the range still reads");
assert_eq!(clamped.options.thumbnail_size, ThumbSize::Custom(ThumbPoints::new(ThumbPoints::MAX)), "the size is clamped");
}
/// The rect of the Background row and of its thumbnail in a panel whose settings are `settings`.
fn background(settings: LayersSettings) -> (Rect, Rect) {
let info = LayerInfo::new("Background", LayerKind::Pixel);
let mut tree = FakeLayers::default();
tree.add(None, info.clone(), false);
let tree = Tracked::new(tree);
let mut fixture = Fixture::new(move |ui| {
let _ = LayersPanel::new(&tree).settings(&settings).show(ui);
});
fixture.room(PANEL);
fixture.settle();
let row = fixture.by_label("Background").expect("the layer's row");
let thumb = testing::thumb_rect(fixture.ctx(), row.node.into(), &info, LayerPart::Pixels).expect("the layer's thumbnail");
(row.rect, thumb)
}
/// The panel's rows take a custom thumbnail size as their height, and their thumbnails grow with it.
#[trial]
fn the_panel_rows_take_a_custom_thumbnail_size() {
let (short, tall) = (ThumbPoints::new(30), ThumbPoints::new(72));
let (row, thumb) = background(custom(short.get()));
let (taller, larger) = background(custom(tall.get()));
assert_eq!(row.height(), f32::from(short.get()), "the row is as high as the size: {row:?}");
assert_eq!(taller.height(), f32::from(tall.get()), "the row is as high as the size: {taller:?}");
assert_eq!(larger.height() - thumb.height(), taller.height() - row.height(), "the thumbnail grows with the row: {thumb:?} {larger:?}");
}
+8 -4
View File
@@ -14,7 +14,7 @@ workspace = true
[features]
default = []
# `appearance`: also Windows' UI settings and macOS' accessibility display setting (reduced motion).
appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys", "dep:windows", "dep:objc2-app-kit"]
appearance = ["dep:craft-theme", "dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys", "dep:windows", "dep:objc2-app-kit"]
# `browser`: downloads, and the file picker and save through `rfd`.
browser = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys", "dep:rfd", "dep:wasm-bindgen-futures"]
# `SystemReader::report_contrast` and `report_reduced_motion`: preferences a test sets in place of an OS source.
@@ -24,7 +24,7 @@ pointer = ["dep:core-graphics"]
# `usage`: the process's memory use.
usage = ["dep:sysinfo"]
# Screen capture for the screen colour picker (`craft_platform::screen`).
screen = ["dep:zbus", "zbus?/blocking-api", "dep:futures-lite", "dep:async-io", "dep:x11rb", "dep:core-graphics2", "dep:xcap"]
screen = ["dep:zbus", "zbus?/blocking-api", "dep:futures-lite", "dep:async-io", "dep:x11rb", "dep:craft-appkit", "dep:objc2-core-graphics", "dep:objc2-core-foundation", "dep:xcap"]
# `clipboard`: the clipboard handle with size limits, the synthetic-input fence, the paste probe, `EventClipboard` and `MemoryClipboard`; no system crates.
clipboard = []
# `clipboard-system`: `SystemClipboard` over the OS: arboard, and the formats on offer asked of Windows, macOS, Wayland and X11.
@@ -33,7 +33,7 @@ clipboard-system = ["clipboard", "dep:arboard", "dep:clipboard-win", "dep:objc2-
apple-events = ["dep:fmv-macos-events"]
[dependencies]
craft-theme = { workspace = true }
craft-theme = { workspace = true, optional = true }
log = "0.4"
web-time = "1.1"
craft-atomic = { workspace = true }
@@ -67,7 +67,11 @@ objc2-foundation = { version = "0.3", default-features = false, features = ["std
# Apple Events behind a safe API, pinned exactly: review the diff before bumping.
fmv-macos-events = { version = "=0.1.0", optional = true }
core-graphics = { version = "0.23", optional = true }
core-graphics2 = { version = "=0.6.1", default-features = false, features = ["display", "window", "link"], optional = true }
# The screen capture: the display list and pixel bytes through craft-appkit's safe wrappers, the rest of Core
# Graphics from the objc2 family the AppKit crates use, and the display profile's bytes (`CFData::to_vec`).
craft-appkit = { workspace = true, optional = true }
objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "libc", "CGColorSpace", "CGDataProvider", "CGDirectDisplay", "CGDisplayConfiguration", "CGImage", "CGWindow"], optional = true }
objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFData"], optional = true }
# Linux reads `/proc`; elsewhere `sysinfo` gives the system's available memory (MIT).
[target.'cfg(any(target_os = "macos", windows))'.dependencies]
+1 -1
View File
@@ -8,7 +8,7 @@ pull in heavier dependencies.
| --- | --- |
| default | Typed dialog outcomes; `PlatformText`; `open` (see below); no backend or toolkit. |
| always (not wasm) | `dialogs`: reserve waiting workers before eager UI-thread native picker creation; serial requests, failure delivery and completion wakeups. The backend factory belongs to the app. |
| always | `From<appearance::Reading> for craft_theme::SystemAppearance`, so a host hands the OS answer to `Base::resolve`. |
| `appearance` | `From<appearance::Reading> for craft_theme::SystemAppearance`, so a host hands the OS answer to `Base::resolve`. |
| `pointer` | Move the system pointer (`pointer::warp`), installed by the app as craft-ui's `Scrub::install_warp` service for a scrub's screen-edge wrap; macOS only, `false` elsewhere. |
| `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, GNOME's text scale, button layout); reduced motion on Windows and macOS; browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. |
| `browser` | Wasm download link/object URL ownership, cleanup on setup failure or abandonment, and cleanup timer registration before clicking; the file picker and save. |
+78 -54
View File
@@ -1,34 +1,57 @@
//! Behaviour tests of `logs::crash`.
#![allow(clippy::expect_used, reason = "tests fail by panicking")]
use super::*;
/// The hook, its crash log directory and the last-panic slot are process-wide; trials that
/// install and panic take turns.
/// Runs `body` in a child process of this test binary that runs only the trial `trial`, and
/// fails when the child fails or did not run it.
///
/// The hook, its crash log directory and the last-panic slot are process-wide, and `cargo test`
/// runs a binary's tests on parallel threads, so a panic in any other test of the binary would
/// land in the trial's report.
#[cfg(not(target_arch = "wasm32"))]
fn serial() -> MutexGuard<'static, ()> {
static SERIAL: Mutex<()> = Mutex::new(());
lock(&SERIAL)
fn alone(trial: &str, body: fn()) {
const DONE: &str = "CRAFT_CRASH_TRIAL_DONE";
if let Some(done) = std::env::var_os(DONE) {
body();
std::fs::write(done, trial).expect("mark the trial done");
return;
}
let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path);
let name = format!("{module}::{trial}");
let done = std::env::temp_dir().join(format!("craft-crash-done-{trial}-{}", std::process::id()));
let _ = std::fs::remove_file(&done);
let out = std::process::Command::new(std::env::current_exe().expect("the test binary"))
.args(["--exact", &name, "--test-threads=1", "--nocapture"])
.env(DONE, &done)
.output()
.expect("run the trial");
let report = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
assert!(out.status.success(), "{name} failed in its own process:\n{report}");
assert_eq!(std::fs::read_to_string(&done).ok().as_deref(), Some(trial), "the child ran {name}:\n{report}");
let _ = std::fs::remove_file(&done);
}
// A panic on a named worker thread is kept for take_last with its message and thread, and appended to the crash log.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_worker_panic_is_kept_and_written_to_the_crash_log() {
let _serial = serial();
let dir = std::env::temp_dir().join(format!("craft-crash-{}", std::process::id()));
install("CrashTest", "1.2.3", Some(dir.clone()));
let _ = take_last();
let joined = std::thread::Builder::new().name("crash-test-worker".into()).spawn(|| panic!("boom in a worker")).expect("spawn").join();
assert!(joined.is_err());
let last = take_last().expect("the hook kept the panic");
assert!(last.contains("boom in a worker") && last.contains("thread crash-test-worker"), "{last}");
assert!(take_last().is_none(), "take_last empties the slot");
let path = log_path().expect("crash log path");
assert_eq!(path.parent(), Some(dir.as_path()));
let log = std::fs::read_to_string(&path).expect("crash log");
assert!(log.contains("=== CrashTest 1.2.3 (unix ") && log.contains("boom in a worker"), "{log}");
record("window could not be created");
assert!(std::fs::read_to_string(&path).expect("crash log").contains("window could not be created"));
let _ = std::fs::remove_dir_all(dir);
alone("a_worker_panic_is_kept_and_written_to_the_crash_log", || {
let dir = std::env::temp_dir().join(format!("craft-crash-{}", std::process::id()));
install("CrashTest", "1.2.3", Some(dir.clone()));
let _ = take_last();
let joined = std::thread::Builder::new().name("crash-test-worker".into()).spawn(|| panic!("boom in a worker")).expect("spawn").join();
assert!(joined.is_err());
let last = take_last().expect("the hook kept the panic");
assert!(last.contains("boom in a worker") && last.contains("thread crash-test-worker"), "{last}");
assert!(take_last().is_none(), "take_last empties the slot");
let path = log_path().expect("crash log path");
assert_eq!(path.parent(), Some(dir.as_path()));
let log = std::fs::read_to_string(&path).expect("crash log");
assert!(log.contains("=== CrashTest 1.2.3 (unix ") && log.contains("boom in a worker"), "{log}");
record("window could not be created");
assert!(std::fs::read_to_string(&path).expect("crash log").contains("window could not be created"));
let _ = std::fs::remove_dir_all(dir);
});
}
// Text a panic quotes between backticks (std quotes the string it was slicing, which can be the
@@ -38,38 +61,39 @@ fn a_worker_panic_is_kept_and_written_to_the_crash_log() {
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_panic_report_leaves_out_quoted_text() {
let _serial = serial();
let dir = std::env::temp_dir().join(format!("craft-crash-quoted-{}", std::process::id()));
install("CrashTest", "1.2.3", Some(dir.clone()));
let _ = take_last();
let secret = "Dear Ms Smith";
let joined = std::thread::Builder::new()
.name("crash-quoted-worker".into())
.spawn(move || panic!("byte index 5 is not a char boundary; it is inside 'é' (bytes 4..6) of `{secret}`"))
.expect("spawn")
.join();
assert!(joined.is_err());
let last = take_last().expect("the hook kept the panic");
assert!(last.starts_with("byte index 5 is not a char boundary") && last.contains("of `…` (at "), "{last}");
assert!(!last.contains(secret), "{last}");
let log = std::fs::read_to_string(log_path().expect("crash log path")).expect("crash log");
assert!(log.contains("of `…` (at ") && !log.contains(secret), "{log}");
alone("a_panic_report_leaves_out_quoted_text", || {
let dir = std::env::temp_dir().join(format!("craft-crash-quoted-{}", std::process::id()));
install("CrashTest", "1.2.3", Some(dir.clone()));
let _ = take_last();
let secret = "Dear Ms Smith";
let joined = std::thread::Builder::new()
.name("crash-quoted-worker".into())
.spawn(move || panic!("byte index 5 is not a char boundary; it is inside 'é' (bytes 4..6) of `{secret}`"))
.expect("spawn")
.join();
assert!(joined.is_err());
let last = take_last().expect("the hook kept the panic");
assert!(last.starts_with("byte index 5 is not a char boundary") && last.contains("of `…` (at "), "{last}");
assert!(!last.contains(secret), "{last}");
let log = std::fs::read_to_string(log_path().expect("crash log path")).expect("crash log");
assert!(log.contains("of `…` (at ") && !log.contains(secret), "{log}");
let caught = catch(|| -> u8 { panic!("of `{secret}` and `more`") });
let message = caught.expect_err("the closure panicked").message;
assert!(message.starts_with("of `…`") && message.contains(" and "), "the text outside the backticks stays: {message}");
assert!(!message.contains(secret) && !message.contains("more"), "{message}");
assert!(take_last().is_none(), "a caught quoted panic is reported once, by the caller");
let caught = catch(|| -> u8 { panic!("of `half a sentence that {secret} wrote") });
let message = caught.expect_err("the closure panicked").message;
assert!(
message.starts_with("of `") && !message.contains("half a sentence") && !message.contains(secret),
"an unpaired backtick hides the rest: {message}"
);
assert!(take_last().is_none());
let plain = "index out of bounds: the len is 3 but the index is 5";
let caught = catch(|| -> u8 { panic!("{plain}") });
assert_eq!(caught.map_err(|p| p.message), Err(plain.to_owned()), "a message without backticks is unchanged");
assert!(take_last().is_none());
let _ = std::fs::remove_dir_all(dir);
let caught = catch(|| -> u8 { panic!("of `{secret}` and `more`") });
let message = caught.expect_err("the closure panicked").message;
assert!(message.starts_with("of `…`") && message.contains(" and "), "the text outside the backticks stays: {message}");
assert!(!message.contains(secret) && !message.contains("more"), "{message}");
assert!(take_last().is_none(), "a caught quoted panic is reported once, by the caller");
let caught = catch(|| -> u8 { panic!("of `half a sentence that {secret} wrote") });
let message = caught.expect_err("the closure panicked").message;
assert!(
message.starts_with("of `") && !message.contains("half a sentence") && !message.contains(secret),
"an unpaired backtick hides the rest: {message}"
);
assert!(take_last().is_none());
let plain = "index out of bounds: the len is 3 but the index is 5";
let caught = catch(|| -> u8 { panic!("{plain}") });
assert_eq!(caught.map_err(|p| p.message), Err(plain.to_owned()), "a message without backticks is unchanged");
assert!(take_last().is_none());
let _ = std::fs::remove_dir_all(dir);
});
}
+59 -32
View File
@@ -155,6 +155,18 @@ fn picked_color(rgb: [f64; 3]) -> Result<Capture, ScreenError> {
Ok(Capture::Color(rgb.map(|v| v as f32)))
}
/// The browser EyeDropper's `sRGBHex` answer, `#rrggbb`, as sRGB, 0 to 1 each. `None` for any other text.
#[cfg(any(test, all(target_arch = "wasm32", feature = "browser")))]
fn eyedropper_color(hex: &str) -> Option<[f32; 3]> {
let digits = hex.strip_prefix('#')?;
// `from_str_radix` accepts a leading '+', so require plain hex digits first.
if digits.len() != 6 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let channel = |i: usize| digits.get(i..i + 2).and_then(|pair| u8::from_str_radix(pair, 16).ok()).map(|v| f32::from(v) / 255.0);
Some([channel(0)?, channel(2)?, channel(4)?])
}
/// The colour in the portal's `PickColor` answer, a `(ddd)` structure; `None` for a value of another shape.
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
fn portal_color(value: &zbus::zvariant::Value<'_>) -> Option<[f64; 3]> {
@@ -494,60 +506,66 @@ mod backend {
#[cfg(target_os = "macos")]
mod backend {
use super::{Arc, AtomicBool, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, checked_stride, pixel_count, unpack_rgba};
use core_graphics2::{display::get_active_display_list, image::CGImageAlphaInfo as Alpha, window};
use craft_appkit::display::{active_displays, with_image_bytes};
use objc2_core_graphics::{
CGColorSpace, CGDisplayBounds, CGDisplayCopyDisplayMode, CGDisplayIsMain, CGDisplayMode, CGImage, CGImageAlphaInfo as Alpha,
CGPreflightScreenCaptureAccess, CGRequestScreenCaptureAccess, CGWindowImageOption, CGWindowListOption, kCGNullWindowID,
};
/// Captures each display's composed image at native resolution. Without the Screen Recording
/// permission the system prompt is shown once; a refusal is `Denied`.
pub fn capture(stop: &AtomicBool) -> Result<Vec<ScreenImage>, ScreenError> {
let failed = |m: &str| ScreenError::Failed(m.into());
if !window::preflight_screen_capture_access() && !window::request_screen_capture_access() {
if !CGPreflightScreenCaptureAccess() && !CGRequestScreenCaptureAccess() {
return Err(ScreenError::Denied);
}
let mut displays = get_active_display_list(MAX_MONITORS + 1).ok_or_else(|| failed("could not enumerate the displays"))?;
let mut displays = active_displays(MAX_MONITORS + 1).ok_or_else(|| failed("could not enumerate the displays"))?;
if displays.is_empty() || displays.len() > MAX_MONITORS {
return Err(failed("no supported screen is available"));
}
displays.sort_by_key(|d| !d.is_main());
displays.sort_by_key(|&d| !CGDisplayIsMain(d));
let mut total = 0usize;
for display in &displays {
let mode = display.copy_display_mode().ok_or_else(|| failed("the display mode is unavailable"))?;
total = add_to_budget(total, mode.pixel_width(), mode.pixel_height())?;
for &display in &displays {
let mode = CGDisplayCopyDisplayMode(display).ok_or_else(|| failed("the display mode is unavailable"))?;
total = add_to_budget(total, CGDisplayMode::pixel_width(Some(&mode)), CGDisplayMode::pixel_height(Some(&mode)))?;
}
let mut images = Vec::new();
for (n, display) in displays.into_iter().enumerate() {
if stop.load(Ordering::Relaxed) {
return Err(ScreenError::Cancelled);
}
let bounds = display.bounds();
let bounds = CGDisplayBounds(display);
let (w, h) = (bounds.size.width, bounds.size.height);
let (x, y) = (bounds.origin.x, bounds.origin.y);
if ![w, h, x, y].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 {
return Err(failed("invalid display geometry"));
}
let image = window::new_image(
#[allow(deprecated, reason = "deprecated in favor of ScreenCaptureKit")]
let retained = objc2_core_graphics::CGWindowListCreateImage(
bounds,
window::CGWindowListOption::OnScreenOnly,
window::kCGNullWindowID,
window::CGWindowImageOption::BestResolution | window::CGWindowImageOption::ShouldBeOpaque,
CGWindowListOption::OptionOnScreenOnly,
kCGNullWindowID,
CGWindowImageOption::BestResolution | CGWindowImageOption::ShouldBeOpaque,
)
.ok_or(ScreenError::Denied)?;
let (width, height) = (image.width(), image.height());
let image = Some(&*retained);
let (width, height) = (CGImage::width(image), CGImage::height(image));
pixel_count(width, height)?;
let profile = image.color_space().and_then(|space| space.copy_icc_data());
let profile = CGColorSpace::icc_data(CGImage::color_space(image).as_deref());
if profile.as_ref().is_some_and(|p| p.len() > 1024 * 1024) {
return Err(failed("the display profile exceeds the memory budget"));
}
let info = image.bitmap_info().bits();
if image.bits_per_component() != 8 || image.bits_per_pixel() != 32 || info & (1 << 8) != 0 {
let info = CGImage::bitmap_info(image).0;
if CGImage::bits_per_component(image) != 8 || CGImage::bits_per_pixel(image) != 32 || info & (1 << 8) != 0 {
return Err(failed("unsupported screen capture pixel format"));
}
let (first, premultiplied, opaque) = match image.alpha_info() {
Alpha::AlphaPremultipliedFirst => (true, true, false),
Alpha::AlphaPremultipliedLast => (false, true, false),
Alpha::AlphaFirst => (true, false, false),
Alpha::AlphaLast => (false, false, false),
Alpha::AlphaNoneSkipFirst => (true, false, true),
Alpha::AlphaNoneSkipLast => (false, false, true),
let (first, premultiplied, opaque) = match CGImage::alpha_info(image) {
Alpha::PremultipliedFirst => (true, true, false),
Alpha::PremultipliedLast => (false, true, false),
Alpha::First => (true, false, false),
Alpha::Last => (false, false, false),
Alpha::NoneSkipFirst => (true, false, true),
Alpha::NoneSkipLast => (false, false, true),
_ => return Err(failed("unsupported screen capture alpha layout")),
};
let little = match info & 0x7000 {
@@ -562,18 +580,18 @@ mod backend {
(false, true) => [3, 2, 1, 0],
(false, false) => [0, 1, 2, 3],
};
let stride = image.bytes_per_row();
let stride = CGImage::bytes_per_row(image);
checked_stride(width, height, stride)?;
let bytes = image.data_provider().and_then(|p| p.copy_data()).ok_or_else(|| failed("the screen image has no pixels"))?;
let rgba = unpack_rgba(bytes.bytes(), width, height, stride, order, premultiplied, opaque)?;
let rgba = with_image_bytes(&retained, |bytes| unpack_rgba(bytes, width, height, stride, order, premultiplied, opaque))
.ok_or_else(|| failed("the screen image has no pixels"))??;
let scale = width as f32 / w as f32;
images.push(ScreenImage {
origin: [(x as f32 * scale).round() as i32, (y as f32 * scale).round() as i32],
size: [width as u32, height as u32],
scale,
rgba: Arc::new(rgba),
icc_profile: profile.map(|p| Arc::new(p.bytes().to_vec())),
name: if display.is_main() { "Main Display".into() } else { format!("Display {}", n + 1) },
icc_profile: profile.map(|p| Arc::new(p.to_vec())),
name: if CGDisplayIsMain(display) { "Main Display".into() } else { format!("Display {}", n + 1) },
});
}
Ok(images)
@@ -586,8 +604,7 @@ mod backend {
/// future executor is needed.
#[cfg(all(target_arch = "wasm32", feature = "browser"))]
mod web {
use super::{Arc, AtomicBool, Capture, CaptureHandle, Ordering, ScreenError, Wake};
use craft_theme::Srgba;
use super::{Arc, AtomicBool, Capture, CaptureHandle, Ordering, ScreenError, Wake, eyedropper_color};
use js_sys::{Array, Function, Object, Promise, Reflect};
use std::sync::mpsc::Sender;
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
@@ -681,8 +698,8 @@ mod web {
if field(entry, "status").as_string().as_deref() == Some("fulfilled") {
return field(&field(entry, "value"), "sRGBHex")
.as_string()
.and_then(|hex| Srgba::from_hex(&hex))
.map(|c| Capture::Color([c.r, c.g, c.b]))
.and_then(|hex| eyedropper_color(&hex))
.map(Capture::Color)
.ok_or_else(|| ScreenError::Failed("the browser eyedropper returned an invalid color".into()));
}
let reason = field(entry, "reason");
@@ -740,6 +757,16 @@ mod tests {
assert!(checked_stride(1, 1, usize::MAX).is_err());
}
/// The EyeDropper's `#rrggbb` reads as its three channels, either case; any other text gives no colour.
#[test]
fn eyedropper_hex_reads_as_its_channels() {
assert_eq!(eyedropper_color("#ff8000"), Some([1.0, 128.0 / 255.0, 0.0]));
assert_eq!(eyedropper_color("#00FFaa"), Some([0.0, 1.0, 170.0 / 255.0]));
for text in ["ff8000", "#f80", "#ff8000ff", "#ff80", "#ff800g", "#+f8000", "# ff8000", "", "#", "#ff8000 "] {
assert_eq!(eyedropper_color(text), None, "{text:?}");
}
}
/// A `color` of another shape than `(ddd)` (a structure with fewer, other or more fields, a string, an array)
/// gives no colour; a `(ddd)` value gives its channels.
#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))]
+6 -4
View File
@@ -86,7 +86,7 @@ Building a scene from an app's document (layers, cameras, models, text) stays in
- **Resolve and encoding.** `try_resolve(&target, k)` averages each `k × k` block of premultiplied
pixels with equal weights, and takes the mean depth of the block's covered pixels, infinity where
none is covered; a pixel whose `f32` sums overflow, and every pixel when a block holds more than
2^24 subsamples, is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer
256 subsamples (`k` over 16), is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer
function of CSS Color 4 (<https://www.w3.org/TR/css-color-4/#color-conversion-code>), a linear
segment up to a magnitude of 0.0031308 and a 1/2.4 power above it, with a negative color keeping
its sign, multiplies by alpha again and leaves alpha linear. `srgb_to_linear` decodes a negative
@@ -140,7 +140,7 @@ far plane, where depth-range crossings lie within 1/4096 of an edge from its ins
texture coordinates times the texture's width or height reach 2^23 in magnitude, where normals'
squared lengths, squared distances from fragments to point and spot lights, or casters'
light-space coordinates times a map's focal length overflow `f32`, where shadow-casting spot
lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 2^24
lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 256
subsamples, where shadows-only materials do not receive shadows, where fragments under discarded
opaque pixels leave the depth range, where blended casters have no base texture, where
opaque-mode and masked casters have an opacity below 0.5, where casters reach within 1 unit of
@@ -198,8 +198,10 @@ Changes from those files:
- A spot light whose outer cone's half angle plus 0.05 radians is over 1.45 radians gets six maps,
as a point light does. EffectCraft gave it one map 1.45 radians wide, so receivers in the rest
of the cone were not shadowed.
- A resolve block of more than 2^24 subsamples is averaged in `f64`. EffectCraft's `f32` count of
covered subsamples stopped at 2^24, which raised the mean depth.
- A resolve block of more than 256 subsamples is averaged in `f64`. EffectCraft summed every block
in `f32`, which dropped the low bits of each sample as the sum grew (a 1024 × 1024 block of 0.7
resolved to 0.6927), and its `f32` count of covered subsamples stopped at 2^24, which raised the
mean depth.
- A clipped corner whose `1/w` overflows `f32` (a clip transform scaled near `f32`'s smallest
values) is projected in `f64` instead of dropping its triangle, and a drawn pixel whose camera
depth overflows is an error.
+24 -3
View File
@@ -18,6 +18,9 @@ pub struct Image {
/// Alpha above 1 that [`try_encode`] accepts as rounding from blending.
const ALPHA_SLACK: f32 = 1e-4;
/// The largest block [`try_resolve`] sums in `f32`.
const F32_SAMPLES: u64 = 256;
/// `w × h` as a length, when it fits `usize`.
fn area(w: u32, h: u32) -> Option<usize> {
usize::try_from(u64::from(w) * u64::from(h)).ok()
@@ -26,7 +29,7 @@ fn area(w: u32, h: u32) -> Option<usize> {
/// Box-filter a supersampled target down by `k` per side: each output pixel is the mean of its
/// `k × k` premultiplied colors, and its depth is the mean of the covered subsamples' depths
/// (infinity where none is covered). A pixel whose `f32` sums overflow, and every pixel when a
/// block holds more than 2^24 subsamples, is averaged in `f64`.
/// block holds more than 256 subsamples (`k` over 16), is averaged in `f64`.
///
/// Returns [`RenderError::BadFactor`] when `k` is zero or does not divide both sides, and
/// [`RenderError::BadDataLength`] when the color or depth buffer does not hold width × height
@@ -50,8 +53,9 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec<f32>), RenderError>
return Ok((img, depth));
}
let n = (u64::from(k) * u64::from(k)) as f32;
// An f32 count stops at 2^24, so a larger block is averaged in f64.
let wide = u64::from(k) * u64::from(k) > 1 << 24;
// An f32 sum drops the low bits of each sample as it grows, so a block of more than
// `F32_SAMPLES` subsamples is averaged in f64.
let wide = u64::from(k) * u64::from(k) > F32_SAMPLES;
img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| {
for x in 0..w as usize {
if wide {
@@ -158,3 +162,20 @@ pub fn try_render_cpu(s: &Scene, limits: &Limits) -> Result<(Image, Vec<f32>), R
}
try_resolve(&try_render(s, limits)?, k)
}
#[cfg(test)]
mod tests {
use super::{Target, try_resolve};
#[test]
fn a_large_block_of_one_color_resolves_to_that_color() {
// An f32 sum of 17 × 17 samples of 0.7 drifts past the tolerance; 17 is the first factor
// averaged in f64.
let n = 17u32;
let len = (n * n) as usize;
let t = Target { width: n, height: n, color: vec![[0.7; 4]; len], depth: vec![0.5; len] };
let (img, depth) = try_resolve(&t, n).unwrap_or_else(|e| panic!("{e:?}"));
assert!(img.data[0].iter().all(|&c| (c - 0.7).abs() < 1e-6), "{:?}", img.data[0]);
assert!((depth[0] - 0.5).abs() < 1e-6, "{}", depth[0]);
}
}
+3 -2
View File
@@ -88,9 +88,10 @@ impl Default for Material {
}
impl Material {
/// Drawn in the transparent (sorted, blended) pass.
/// Drawn in the transparent (sorted, blended) pass: a blended material, a shadows-only one, or
/// one whose opacity is below 1.
pub fn transparent(&self) -> bool {
self.alpha_mode == 2 || self.opacity < 0.999 || self.shadows_only
self.alpha_mode == 2 || self.opacity < 1.0 || self.shadows_only
}
}
+186 -6
View File
@@ -24,6 +24,51 @@ fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
/// Whether the plane through the finite `f32` corners `p` passes exactly through the origin.
/// Every product of two `f32` values is exact in `f64`, and `two_product` splits each
/// three-factor term into an exact pair, so the expansion sum gives the determinant's exact sign.
fn passes_through_origin(p: [[f32; 3]; 3]) -> bool {
let [a, b, c] = p.map(|v| v.map(f64::from));
let fast = dot3(a, cross3(b, c));
let permanent = [(0, 1, 2), (1, 2, 0), (2, 0, 1)].iter().map(|&(i, j, k)| a[i].abs() * ((b[j] * c[k]).abs() + (b[k] * c[j]).abs())).sum::<f64>();
if fast.abs() > 8.0 * f64::EPSILON * permanent {
return false;
}
let two_product = |x: f64, y: f64| {
let p = x * y;
(p, x.mul_add(y, -p))
};
// Twelve exact parts; the expansion never holds more components than parts added.
let mut expansion = [0.0_f64; 12];
let mut len = 0;
for (i, j, k) in [(0, 1, 2), (1, 2, 0), (2, 0, 1)] {
for (s, bc) in [(1.0, b[j] * c[k]), (-1.0, b[k] * c[j])] {
let (hi, lo) = two_product(s * a[i], bc);
for x in [lo, hi] {
let mut q = x;
let mut kept = 0;
for n in 0..len {
let h = expansion[n];
let sum = q + h;
let bv = sum - q;
let err = (q - (sum - bv)) + (h - bv);
if err != 0.0 {
expansion[kept] = err;
kept += 1;
}
q = sum;
}
if q != 0.0 {
expansion[kept] = q;
kept += 1;
}
len = kept;
}
}
}
len == 0
}
fn len3(a: [f64; 3]) -> f64 {
dot3(a, a).sqrt()
}
@@ -93,6 +138,15 @@ fn light_poly(s: &Scene, m: &ShadowMap, ids: [usize; 3]) -> Vec<LightCorner> {
.collect();
let mut poly = q;
if !m.ortho {
// A caster edge-on to the light covers no texels. Its clipped corners can still come
// apart when a position difference overflows, so it is dropped before clipping.
let corners = [0, 1, 2].map(|i| poly[i].0);
if corners.iter().all(|c| c[2] < NEAR) {
return vec![];
}
if corners.iter().flatten().all(|c| c.is_finite()) && passes_through_origin(corners) {
return vec![];
}
let mut out = vec![];
for i in 0..poly.len() {
let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
@@ -103,17 +157,26 @@ fn light_poly(s: &Scene, m: &ShadowMap, ids: [usize; 3]) -> Vec<LightCorner> {
if (da >= 0.0) != (db >= 0.0) {
let (from_b, k) = f32_crossing(da, db);
let (p, q) = if from_b { (b, a) } else { (a, b) };
let lerp = |x: f32, y: f32| {
let d = y - x;
if d.is_finite() || !x.is_finite() || !y.is_finite() {
x + d * k
// `y - x` can overflow f32 between far-apart finite corners. An overflowing x or y
// position difference selects the f64 fraction from the original depths for both
// position and UVs. Otherwise each component whose own difference overflows is
// taken in f64 with the f32 fraction.
let overflows = |x: f32, y: f32| x.is_finite() && y.is_finite() && !(y - x).is_finite();
let (pa, pb) = ((p.0[0], q.0[0]), (p.0[1], q.0[1]));
let (ua, ub) = ((p.1[0], q.1[0]), (p.1[1], q.1[1]));
let wide_pos = overflows(pa.0, pa.1) || overflows(pb.0, pb.1);
let (dp, dq) = (f64::from(p.0[2]) - f64::from(NEAR), f64::from(q.0[2]) - f64::from(NEAR));
let k64 = if wide_pos { dp / (dp - dq) } else { f64::from(k) };
let lerp = |wide: bool, x: f32, y: f32| {
if (wide || overflows(x, y)) && x.is_finite() && y.is_finite() {
(f64::from(x) + (f64::from(y) - f64::from(x)) * k64) as f32
} else {
(f64::from(x) + (f64::from(y) - f64::from(x)) * f64::from(k)) as f32
x + (y - x) * k
}
};
// The crossing lies on the near plane; its depth is set to it, since the lerp of
// far-apart depths can round to 0 or below.
out.push(([lerp(p.0[0], q.0[0]), lerp(p.0[1], q.0[1]), NEAR], [lerp(p.1[0], q.1[0]), lerp(p.1[1], q.1[1])]));
out.push(([lerp(wide_pos, pa.0, pa.1), lerp(wide_pos, pb.0, pb.1), NEAR], [lerp(wide_pos, ua.0, ua.1), lerp(wide_pos, ub.0, ub.1)]));
}
}
poly = out;
@@ -618,6 +681,42 @@ mod tests {
}
}
#[test]
fn edge_on_perspective_casters_with_overflowing_differences_write_no_texels() {
let a = 2.0_f32.powi(127);
for indices in [vec![0, 1, 2], vec![0, 2, 1]] {
let s = Scene {
vertices: [[-a, -0.75 * a, -32768.0], [a, 0.75 * a, 32768.0], [0.0, 0.0, NEAR]]
.map(|pos| Vertex { pos, ..Vertex::default() })
.to_vec(),
indices,
materials: vec![Material::default()],
..Scene::default()
};
let depths = shadow_raster(&s, &perspective_map(), &[0]);
assert!(depths.iter().all(|&depth| depth == f32::INFINITY));
}
}
#[test]
fn the_edge_on_test_keeps_the_rounding_residual_of_each_product() {
// Each three-factor term needs more than 53 bits; the rounded terms sum to -2048.
let (a, b) = ([1_000_008.0, 2_000_007.0, 3_000_002.0], [3_000_005.0, 2_000_007.0, 1_000_004.0]);
let c = [0, 1, 2].map(|i| a[i] + b[i]);
assert!(super::passes_through_origin([a, b, c]));
assert!(!super::passes_through_origin([a, b, [c[0], c[1], c[2] + 1.0]]));
}
#[test]
fn casters_whose_rounded_determinant_is_zero_are_kept_in_every_corner_order() {
let x = 2.0_f32.powi(48);
let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() };
let s = Scene { vertices: vec![v([-x, -NEAR, -x]), v([x, -NEAR, x]), v([0.0, NEAR, NEAR])], ..Scene::default() };
for ids in [[0, 1, 2], [1, 2, 0], [2, 0, 1], [0, 2, 1]] {
assert!(!light_poly(&s, &identity_map(), ids).is_empty(), "{ids:?}");
}
}
#[test]
fn perspective_casters_with_subnormal_reciprocals_keep_finite_depth() {
for z in [1e38, f32::MAX] {
@@ -659,4 +758,85 @@ mod tests {
assert_eq!(covered(f32::MAX, [0.0, 1.0], indices), 0);
}
}
#[test]
fn a_near_plane_crossing_with_one_overflowing_uv_axis_preserves_the_other_axis() {
let clipped = |u: f32, ids| {
let s = Scene {
vertices: [
([-1.0, 0.0, 0.0], [-u, -16_777_216.0]),
([1.0, 0.0, 3.0 * NEAR], [u, 33_554_432.0]),
([0.0, 1.0, 3.0 * NEAR], [0.0, 0.0]),
]
.map(|(pos, uv)| Vertex { pos, uv, ..Vertex::default() })
.to_vec(),
..Scene::default()
};
light_poly(&s, &identity_map(), ids)
};
for ids in [[0, 1, 2], [1, 0, 2]] {
let ordinary = clipped(1.0, ids);
let overflowing = clipped(f32::MAX, ids);
assert!(overflowing.iter().any(|(p, _)| p[2] == NEAR));
assert!(overflowing.iter().all(|(_, uv)| uv.iter().all(|v| v.is_finite())));
let unaffected = |poly: Vec<super::LightCorner>| poly.into_iter().map(|(p, uv)| (p, uv[1])).collect::<Vec<_>>();
assert_eq!(unaffected(overflowing), unaffected(ordinary));
}
}
#[test]
fn a_near_plane_crossing_whose_difference_overflows_f32_takes_its_fraction_in_f64() {
// 3e38 − (−3e38) overflows f32; the edge crosses the near plane near x = 3e35. An `f32`
// fraction puts the crossing about 1.4e31 off the edge's own crossing.
let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() };
let (a, b) = ([-3e38_f32, 0.0, -1.0], [3e38_f32, 1.0, 1.0]);
let s = Scene { vertices: vec![v(a), v(b), v([0.0, 0.1, 1.0])], ..Scene::default() };
let poly = light_poly(&s, &identity_map(), [0, 1, 2]);
assert!(!poly.is_empty());
for (p, uv) in &poly {
assert!(p.iter().chain(uv.iter()).all(|c| c.is_finite()), "{poly:?}");
}
let t = (f64::from(NEAR) - f64::from(a[2])) / (f64::from(b[2]) - f64::from(a[2]));
let x = f64::from(a[0]) + (f64::from(b[0]) - f64::from(a[0])) * t;
assert!(poly.iter().any(|(p, _)| (f64::from(p[0]) - x).abs() <= x.abs() * 1e-6 && p[2] == NEAR), "{poly:?}");
}
#[test]
fn a_wide_near_plane_crossing_stays_on_its_edge() {
// The wide edge has y = x / 2; x's difference overflows f32 and y's does not.
// Both components of its near-plane crossing take the same fraction.
let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() };
let s = Scene { vertices: vec![v([3e38, 1.5e38, -1.0]), v([-3e38, -1.5e38, 1.0 + f32::EPSILON]), v([0.0, 1.0, NEAR])], ..Scene::default() };
let poly = light_poly(&s, &identity_map(), [0, 1, 2]);
assert!(poly.iter().any(|(p, _)| p[2] == NEAR && p[0] != 0.0), "{poly:?}");
for (p, _) in &poly {
let (x, y) = (f64::from(p[0]), f64::from(p[1]));
if x == 0.0 {
continue;
}
assert!(x.is_finite() && (y - x / 2.0).abs() <= x.abs() * 1e-6, "{poly:?}");
}
}
#[test]
fn a_wide_near_plane_crossing_keeps_uvs_on_its_edge() {
let v = |pos: [f32; 3], u: f32| Vertex { pos, uv: [u, 0.0], ..Vertex::default() };
let s = Scene {
vertices: vec![v([-3e38, 0.0, -32768.0], -32768000.0), v([3e38, 1.0, 32768.0], 32768000.0), v([0.0, 1.0, NEAR], 0.0)],
..Scene::default()
};
for ids in [[0, 1, 2], [1, 0, 2]] {
let poly = light_poly(&s, &identity_map(), ids);
assert!(poly.iter().any(|(p, _)| p[2] == NEAR && p[0] != 0.0), "{poly:?}");
for (p, uv) in &poly {
let implied_u = f64::from(p[0]) / f64::from(s.vertices[0].pos[0]) * f64::from(s.vertices[0].uv[0]);
assert!((f64::from(uv[0]) - implied_u).abs() <= implied_u.abs() * 1e-6, "{poly:?}");
}
}
}
fn identity_map() -> ShadowMap {
let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]];
ShadowMap { view, focal: 1.0, ortho: false, size: 8, offset: 0, bias: 0.0, radius: 0.0 }
}
}
+1
View File
@@ -5,6 +5,7 @@
mod bounds;
mod differential;
mod moved;
mod opacity;
/// A verbatim copy of the app's previous code, run by `differential`.
mod reference {
+23
View File
@@ -0,0 +1,23 @@
//! Which materials draw in the transparent pass.
use craft_raster3d::{Limits, Material, RenderError, try_render};
use crate::quad_scene;
const WHITE: [f32; 4] = [1.0; 4];
#[test]
fn a_material_with_an_opacity_below_one_is_transparent() {
let m = |opacity: f32| Material { opacity, ..Material::default() }.transparent();
assert!(!m(1.0));
assert!(m(0.9995));
assert!(m(f32::from_bits(1.0f32.to_bits() - 1)));
assert!(m(0.5));
}
#[test]
fn an_opaque_range_triangle_with_an_opacity_just_below_one_is_rejected() {
let mut s = quad_scene(4, 4, &[([0.0, 0.0, 4.0, 4.0], 50.0, WHITE)]);
s.materials[0].opacity = 0.9995;
assert!(matches!(try_render(&s, &Limits::default()), Err(RenderError::BadMaterial(0))));
}
@@ -124,6 +124,7 @@ impl BodyHooks<'_> {
scoped.after_rule = props.header.is_some_and(|header| (header.rule || (header.heads && heads)) && !header.inline)
|| (props.header.is_none() && props.surface.is_none() && props.mount == Mount::Inline && self.after_rule);
scoped.flow_body = None;
scoped.view_flow = None;
scoped.column_row =
self.in_column && matches!(props.layout, crate::layout::BodyLayout::Row { wrap: false, align: crate::layout::RowAlign::Start });
// Children side by side share the layer's width, so none of them spans it: a collection in a row or a grid takes
@@ -101,7 +101,7 @@ impl RuleBands {
let above = on(start != Some(true) && props.header.is_some_and(|header| header.rule_above));
let spaced = above > 0.0 && env.get::<SectionRhythm>() == SectionRhythm::Spaced;
let gaps = &tokens.tokens().space.gap;
let stack_gap = env.stack_gap.filter(|(body, _)| env.flow_body == Some(*body)).map_or(0.0, |(_, gap)| gap);
let stack_gap = env.flow_gap().unwrap_or(0.0);
RuleBands {
lead: if spaced && start.is_none() { (gaps.section - stack_gap).max(0.0) } else { 0.0 },
above,
+8 -2
View File
@@ -3,7 +3,7 @@
use crate::layout::{flow_region, take_cell, take_in_flow};
use crate::runtime::egui::alloc;
use crate::runtime::env::{Env, Shrink};
use crate::runtime::env::{Env, Flow, Shrink};
use crate::runtime::focus;
use crate::runtime::layout_memory;
use crate::runtime::lazy::{self, Call, Decision, Key, Place};
@@ -149,7 +149,7 @@ impl Lazy {
access: crate::runtime::egui::access::builds_nodes(&ctx),
opacity: ui.opacity(),
env: env.key,
flow: env.flow(),
flow: flow_around(&ctx, &env, memo),
};
if real && memo {
crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass");
@@ -314,6 +314,12 @@ fn open_record(ctx: &egui::Context, audited: bool) {
replay::open(ctx);
}
/// The flow facts of the body around a child shown under `env` (`Place::flow`). A memoized view's also hold where it
/// stands in that body's flow, which its content goes on with (`layout::open_view_flow`).
fn flow_around(ctx: &egui::Context, env: &Env, memo: bool) -> Flow {
if memo { env.flow().in_flow(crate::layout::flow_start(ctx, env), env.flow_gap()) } else { env.flow() }
}
/// Where content of `size` starts in `region`: at its start edge, the right one in a right-to-left layout.
fn at_start(region: Rect, rtl: bool, size: Vec2) -> Pos2 {
Pos2::new(if rtl { region.max.x - size.x } else { region.min.x }, region.min.y)
+8 -3
View File
@@ -50,7 +50,8 @@ use std::sync::Arc;
/// theme, density, direction, language, window active) and the flow of the body around it (whether that body is a
/// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that
/// fill it, a least measure, the axes a scroll leaves unbounded, a beside label's cell, whether its leaves fit the
/// room), compared for every view and for each kind of run on its own;
/// room, whether it starts that body's flow and the gap a `Stack` body leaves before it), compared for every view and
/// for each kind of run on its own;
/// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every
/// app value, and the rest of `Scoped::scope_key`), in the key;
/// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the
@@ -67,7 +68,9 @@ use std::sync::Arc;
/// no version: the containers inside measure as outside any view.
///
/// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a column's sweep, a grid's
/// cursor) does not reach in, so the room it is given reaches it only through its place. To the body
/// cursor) does not reach in, so the room it is given reaches it only through its place. Its direct children go on with
/// the flow the view stands in: the first one starts that flow when the view does, and each one keeps the gap a `Stack`
/// body leaves before the view, so a section shown in the view stands where it stands shown without it. To the body
/// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows
/// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its
/// least. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no
@@ -154,11 +157,13 @@ impl<P: MemoProps, R: Clone + PartialEq + Shift + Send + Sync + 'static> MemoVie
// that body sizes from its content, whether its leaves fit their room and which axis it shares among the
// children that fill it (`Scoped::start_view_room`), so the view takes what its content used there, as the
// same content shown without the view would.
// Its direct children go on with the flow the view stands in (`layout::open_view_flow`).
// Its key is its content's version: a body inside measures under it (`Scoped::view_version`).
let flow = crate::layout::open_view_flow(&ctx, &env, id);
let installed = Env::install_for(
ui,
env.derive_local(|scoped| {
scoped.start_view_room(id);
scoped.start_view_room(id, flow);
scoped.view_version = follows.then_some(key);
}),
);
+22 -3
View File
@@ -364,12 +364,31 @@ pub(crate) struct FlowStarts(IdMap<bool>);
/// Where the next child placed in flow under `env` starts: `Some(edge)` while the body that places it has placed
/// nothing yet in this sweep or run, with `after_rule` when a rule precedes that body's start (`Scoped::after_rule`);
/// `None` once a child took room there, and outside a body.
/// `None` once a child took room there, and outside a body. The children of a memoized view's content read the flow
/// they go on with (`Scoped::flow_of`).
pub(crate) fn flow_start(ctx: &egui::Context, env: &Env) -> Option<bool> {
let body = env.flow_body?;
let body = env.flow_of()?;
pass_state::with::<FlowStarts, _>(ctx, |starts| starts.0.get(&body).copied())
}
/// Opens the flow of the content of the memoized view `view`, which is placed in flow under `env`, and returns its id
/// (`Scoped::view_flow`); `None` when no flow places the view. The content's first child starts that flow when the
/// view starts the flow it stands in, after a rule when the view is; otherwise something precedes it there.
pub(crate) fn open_view_flow(ctx: &egui::Context, env: &Env, view: Id) -> Option<Id> {
env.flow_of()?;
let flow = sub(view, "flow");
let start = flow_start(ctx, env);
pass_state::with::<FlowStarts, _>(ctx, |starts| match start {
Some(after_rule) => {
starts.0.insert(flow, after_rule);
}
None => {
starts.0.remove(&flow);
}
});
Some(flow)
}
/// Whether the next child placed in flow under `env` starts its body's flow (`flow_start`).
pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool {
flow_start(ctx, env).is_some()
@@ -377,7 +396,7 @@ pub(crate) fn at_flow_start(ctx: &egui::Context, env: &Env) -> bool {
/// A child took room in the flow of the body that places the children under `env`: its flow start closes.
pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) {
if let Some(body) = env.flow_body {
if let Some(body) = env.flow_of() {
pass_state::with::<FlowStarts, _>(ctx, |starts| starts.0.remove(&body));
}
}
+3 -3
View File
@@ -26,7 +26,7 @@ pub(crate) use body::run_body;
pub(crate) use body::{
BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start, count_fill_view, counting_fills,
fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room,
members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_fill_least, report_held, report_least,
report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill,
view_room,
members_line, open_first_lines, open_view_fill, open_view_flow, place_in_cell, report_bracket_control, report_fill_least, report_held,
report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall,
take_view_fill, view_room,
};
+67 -10
View File
@@ -18,6 +18,9 @@ const MAX_DIGITS: usize = 8;
pub(crate) struct AltCodeEntry {
/// The digits typed while Alt is held.
code: String,
/// A digit of the code came from the top row (its physical key is `Num0`…`Num9`, a keypad digit's is
/// `Numpad0`…`Numpad9`). Windows composes keypad codes only, so it sends no character of its own for this code.
top_row: bool,
/// A digit was typed in this Alt hold, also when the code was then dropped (a focus loss): the Alt release is no
/// lone Alt, since the key stage never saw the digits.
digits_typed: bool,
@@ -25,18 +28,44 @@ pub(crate) struct AltCodeEntry {
swallow_text: bool,
/// What the last code typed, for the character a platform composes itself and sends after it.
echo: Option<Echo>,
/// The key of the press that carries the platform's composed character, whose release is left out with it.
carrier: Option<Key>,
}
/// The character an Alt code typed, kept until the next key or pointer press.
/// The character an Alt code typed, kept until the next key or pointer press or a focus loss.
struct Echo {
typed: String,
/// The code names a byte of the code pages (1–255): the platform's own character for it wins over ours, since it
/// knows the system's code pages (double-byte ones too) better than the app's locale guess.
byte_code: bool,
/// The platform composes this code itself and sends its character after it: Windows, for a code typed on the
/// keypad.
native: bool,
/// The keys egui names the platform's character by, for the press that can carry it on Windows: the key of our
/// character, and for a code above 255 the key of the character of the byte Windows reduces it to.
carriers: Vec<Key>,
}
impl Echo {
/// The echo of `typed`, the character `code` names in `pages`. `native` tells whether the platform composes the
/// code too.
fn new(typed: char, code: &str, pages: AltCodePages, native: bool) -> Self {
let value = code.trim_start_matches('0').parse::<u32>().ok();
let byte_code = value.is_some_and(|value| value <= 255);
let mut carriers: Vec<Key> = Key::from_name(&typed.to_string()).into_iter().collect();
if let Some(value) = value.filter(|value| *value > 255) {
let byte = value % 256;
let byte_digits = if code.starts_with('0') { format!("0{byte}") } else { byte.to_string() };
if let Some(key) = craft_codepage::alt_code_char(&byte_digits, pages.ansi, pages.oem).and_then(|c| Key::from_name(&c.to_string())) {
carriers.push(key);
}
}
Echo { typed: typed.to_string(), byte_code, native, carriers }
}
}
/// Folds Alt+numpad entry out of `events` and into text events, decoding with `pages`. `os` is the platform the events
/// come from: on Windows (a browser on Windows too) the platform composes the code itself and sends its character
/// come from: on Windows (a browser on Windows too) the platform composes a keypad code itself and sends its character
/// after the Alt release. Returns whether an Alt release in `events` ended a hold in which digits were typed (a code,
/// or one a focus loss dropped), so the key stage does not take it for a lone Alt. The caller does not call it on macOS, where Option+digit types its own characters.
///
@@ -49,15 +78,36 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec<Event>, pages: Alt
let mut out = Vec::with_capacity(events.len() + 1);
for event in events.drain(..) {
match &event {
Event::Key { key, pressed: true, repeat, modifiers, .. } => {
// On Windows the composed character can come on a press of its own after the Alt release, with no
// physical key and the key egui names the character by (`\` is `Key::Backslash`). It is no key the user
// pressed: the press and its release are left out, and the text that follows meets the echo. A press of
// another key with no physical key (one egui does not map, such as a JIS key) is the user's, and so is any
// such press after a top-row code, which Windows does not compose.
Event::Key { key, physical_key: None, pressed: true, repeat: false, .. }
if entry.echo.as_ref().is_some_and(|echo| echo.native && echo.carriers.contains(key)) =>
{
entry.carrier = Some(*key);
continue;
}
Event::Key { key, physical_key: None, pressed: false, .. } if entry.carrier == Some(*key) => {
entry.carrier = None;
continue;
}
Event::Key { key, physical_key, pressed: true, repeat, modifiers, .. } => {
entry.swallow_text = false;
entry.echo = None;
// A carrier whose release never came (the platform dropped it with the held physical key's) does not
// take the release of a key pressed after it.
if !*repeat {
entry.carrier = None;
}
match digit(*key).filter(|_| alt_only(modifiers) && !claimed(&event)) {
Some(d) => {
// A held digit's auto-repeat adds nothing, as on Windows.
if !*repeat && entry.code.len() < MAX_DIGITS {
entry.code.push(d);
}
entry.top_row |= physical_key.is_some_and(|physical| digit(physical).is_some());
entry.digits_typed = true;
entry.swallow_text = true;
continue;
@@ -65,6 +115,7 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec<Event>, pages: Alt
// Another key (Alt itself, a letter, a digit with Ctrl or Shift) ends the entry unfinished.
None => {
entry.code.clear();
entry.top_row = false;
// A new Alt hold starts clean: a release that went to another window ended the last one.
if matches!(key, Key::AltLeft | Key::AltRight) && !*repeat {
entry.digits_typed = false;
@@ -79,8 +130,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec<Event>, pages: Alt
// The platform composed the same character: it is typed once.
continue;
}
if composes {
// On Windows the text after a code is the platform's character for it. For a code up to 255
if echo.native {
// On Windows the text after a keypad code is the platform's character for it. For a code up to 255
// it replaces ours, which was typed just before with no key or click since; above 255 ours
// stays (Windows reduces the code to a byte, Word types the Unicode character).
if echo.byte_code && text.chars().count() == 1 {
@@ -93,7 +144,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec<Event>, pages: Alt
}
continue;
}
// Linux and the BSDs compose nothing: a different text is what was typed next.
// Linux and the BSDs compose nothing, nor Windows a top-row code: a different text is what was
// typed next.
}
}
Event::PointerButton { pressed: true, .. } => entry.echo = None,
@@ -102,23 +154,28 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec<Event>, pages: Alt
// Focus in another window ends a code unfinished: Alt's release goes there.
Event::WindowFocused(false) => {
entry.code.clear();
entry.top_row = false;
entry.swallow_text = false;
entry.echo = None;
entry.carrier = None;
}
_ => {}
}
let released = alt_released(&event);
out.push(event);
let mut top_row = false;
if released {
ended |= std::mem::take(&mut entry.digits_typed);
top_row = std::mem::take(&mut entry.top_row);
}
if released && !entry.code.is_empty() {
let code = std::mem::take(&mut entry.code);
let native = composes && !top_row;
// A digit's own text comes with its press, before Alt is let go: text after this is the platform's
// composed character or what is typed next. A digit that sent no text must not cost the next one.
entry.swallow_text = false;
if let Some(c) = craft_codepage::alt_code_char(&code, pages.ansi, pages.oem) {
let byte_code = code.trim_start_matches('0').parse::<u32>().is_ok_and(|value| value <= 255);
entry.echo = Some(Echo { typed: c.to_string(), byte_code });
entry.echo = Some(Echo::new(c, &code, pages, native));
out.push(Event::Text(c.to_string()));
}
}
@@ -127,8 +184,8 @@ pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec<Event>, pages: Alt
ended
}
/// The digit `key` adds to a code. egui reports keypad and top-row digits alike (`Key::Num0`…`Num9`) and carries no
/// key location, so the top-row digits compose codes too; with Alt alone held they type nothing else.
/// The digit `key` adds to a code. egui's logical key is the same for keypad and top-row digits (`Key::Num0`…`Num9`),
/// so the top-row digits compose codes too; with Alt alone held they type nothing else.
fn digit(key: Key) -> Option<char> {
let n = match key {
Key::Num0 => 0,
@@ -449,6 +449,12 @@ pub(crate) fn move_to_top(ctx: &Context, layer: LayerId) {
ctx.move_to_top(layer);
}
/// egui's own area order as of the running pass, bottom first: the order of the last pass, with the layers that first
/// showed in this one at the end.
pub(crate) fn area_order(ctx: &Context) -> Vec<LayerId> {
ctx.memory(|memory| memory.layer_ids().collect())
}
/// Whether egui showed `layer` in the last pass.
pub(crate) fn visible_last_frame(ctx: &Context, layer: LayerId) -> bool {
ctx.memory(|memory| memory.areas().visible_last_frame(&layer))
+266 -18
View File
@@ -1,5 +1,7 @@
//! The egui calls `craft_ui::testing` needs: frames, raw input and options that apps reach only through the runtime.
use egui::emath::TSTransform;
use egui::epaint::ClippedShape;
use egui::{Context, Event, Key, Modifiers, Pos2, Rect, Shape, Ui, Vec2, ViewportCommand};
use std::sync::Arc;
@@ -282,32 +284,63 @@ pub(crate) fn run_frame(
}
let mut flat = Vec::new();
for clipped in &output.shapes {
let mut shapes = Vec::new();
flatten_ref(&clipped.shape, &mut shapes);
flat.extend(shapes.into_iter().map(|shape| (shape, clipped.clip_rect)));
flatten_ref(&clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, false, &mut flat);
}
let (pixels_per_point, options) = (output.pixels_per_point, ctx.tessellation_options(|options| *options));
// A shape shows only inside its clip rect.
let (bounds, overshoot): (Vec<Rect>, Vec<f32>) = flat
.iter()
.filter(|(shape, _)| !is_shadow(shape) && shape.visual_bounding_rect().is_finite())
.map(|(shape, clip)| (shape.visual_bounding_rect().intersect(*clip), stroke_width(shape) / 2.0))
.filter_map(|(shape, transform, clip, in_chunk)| {
if !fixture_draws(shape, *transform, *clip, *in_chunk, pixels_per_point, options) || is_shadow(shape) {
return None;
}
let rect = match shape {
Shape::Text(text) if *transform != TSTransform::IDENTITY && options.round_text_to_pixels => {
let mut text = text.clone();
text.pos = egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point);
text.visual_bounding_rect()
}
_ => shape.visual_bounding_rect(),
};
if !rect.is_finite() {
return None;
}
let moved = *transform * rect;
// egui mirrors the vertices of a shape it draws under a negative scale, so its drawn rect is the moved one's
// corners in order. A callback keeps the moved rect as egui passes it on.
let flipped = transform.scaling < 0.0 && !matches!(shape, Shape::Callback(_));
let moved = if flipped { Rect::from_two_pos(moved.min, moved.max) } else { moved };
Some((moved.intersect(*clip), stroke_width(shape) * transform.scaling.abs() / 2.0))
})
.filter(|(rect, _)| rect.is_finite() && rect.min.x <= rect.max.x && rect.min.y <= rect.max.y)
.unzip();
let mut painted_before: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
let texts = flat
.iter()
.filter_map(|(shape, clip)| match shape {
.filter_map(|(shape, transform, clip, in_chunk)| match shape {
Shape::Text(text) => {
let nth = painted_before.entry(Arc::as_ptr(&text.galley) as usize).or_insert(0);
let full = super::painted::full_text_of_painted(ctx, &text.galley, *nth);
*nth += 1;
if !fixture_draws(shape, *transform, *clip, *in_chunk, pixels_per_point, options) {
return None;
}
let baseline = text.galley.rows.first().map_or(0.0, |placed| match placed.row.glyphs.first() {
Some(glyph) => placed.pos.y + glyph.pos.y,
None => placed.pos.y + placed.row.size.y,
});
// egui snaps a text origin before a paint transform; an untransformed text is reported at its own origin.
let pos = if options.round_text_to_pixels && *transform != TSTransform::IDENTITY {
egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point)
} else {
text.pos
};
Some(PaintedText {
rect: text.galley.rect.translate(text.pos.to_vec2()),
baseline: text.pos.y + baseline,
rect: {
let moved = *transform * text.galley.rect.translate(pos.to_vec2());
Rect::from_two_pos(moved.min, moved.max)
},
baseline: transform.scaling * (pos.y + baseline) + transform.translation.y,
elided: full.is_some(),
text: full.unwrap_or_else(|| text.galley.job.text.clone()),
clip: *clip,
@@ -454,6 +487,7 @@ pub(crate) fn reordered_fonts() -> egui::FontDefinitions {
}
/// Runs one frame like `run_frame` and returns the shapes it painted, nested shapes flattened.
/// Mirrored text returns its visible underlines as separate line segments immediately after the text, whose underline is `Stroke::NONE`.
pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl FnMut(&mut Ui)) -> Vec<Shape> {
let screen = Rect::from_min_size(Pos2::ZERO, screen);
let children = open_children(ctx, egui::ViewportId::ROOT);
@@ -466,10 +500,106 @@ pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl
let mut output = drive(|| run_ui(ctx, input, &children, ui));
output.textures_delta.clear();
let mut flat = Vec::new();
let options = ctx.tessellation_options(|options| *options);
for clipped in output.shapes {
flatten(clipped.shape, &mut flat);
flatten(clipped, output.pixels_per_point, options, &mut flat);
}
flat.into_iter().map(|(shape, _)| shape).collect()
}
/// Whether egui's tessellator draws `shape` moved by `transform` inside `clip`. Under a negative scale, egui tessellates
/// the shape against the clip mapped back through the inverse transform, which comes out inverted, so its coarse culling
/// keeps only shapes whose bounds enclose that clip. This asks the tessellator itself.
fn egui_draws(shape: &Shape, transform: TSTransform, clip: Rect, pixels_per_point: f32, options: egui::epaint::TessellationOptions) -> bool {
if matches!(shape, Shape::Callback(_)) {
return true;
}
let clipped = ClippedShape { clip_rect: clip, shape: shape.clone(), transform_after_tessellation: transform };
let options = egui::epaint::TessellationOptions { debug_paint_clip_rects: false, ..options };
let mut tessellator = egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new());
let mut primitives = Vec::new();
tessellator.tessellate_clipped_shape(clipped, &mut primitives);
primitives.into_iter().any(|primitive| {
primitive.clip_rect.is_positive()
&& match primitive.primitive {
egui::epaint::Primitive::Mesh(mesh) => !mesh.is_empty() && mesh.calc_bounds().intersects(primitive.clip_rect),
egui::epaint::Primitive::Callback(_) => true,
}
})
}
fn fixture_draws(
shape: &Shape,
transform: TSTransform,
clip: Rect,
in_chunk: bool,
pixels_per_point: f32,
options: egui::epaint::TessellationOptions,
) -> bool {
// A top-level shape that egui paints untransformed is reported as before, whatever its clip rect.
if !in_chunk && transform == TSTransform::IDENTITY {
return true;
}
// An untransformed chunk member is reported like a top-level shape, invisible paint included, unless its clip hides it.
if transform == TSTransform::IDENTITY {
let bounds = shape.visual_bounding_rect();
return clip.is_positive() && (!bounds.is_finite() || bounds.intersects(clip));
}
transform.is_valid() && clip.is_positive() && egui_draws(shape, transform, clip, pixels_per_point, options)
}
fn transform_fixture_shape(shape: &mut Shape, transform: TSTransform) {
let corner_radius = if let Shape::Rect(rect) = shape { Some(rect.corner_radius) } else { None };
shape.transform(transform);
if transform.scaling >= 0.0 {
return;
}
match shape {
Shape::Circle(circle) => {
circle.radius = -circle.radius;
circle.stroke.width = -circle.stroke.width;
}
Shape::Ellipse(ellipse) => {
ellipse.radius = -ellipse.radius;
ellipse.stroke.width = -ellipse.stroke.width;
}
Shape::LineSegment { stroke, .. } => stroke.width = -stroke.width,
Shape::Path(path) => path.stroke.width = -path.stroke.width,
Shape::QuadraticBezier(bezier) => bezier.stroke.width = -bezier.stroke.width,
Shape::CubicBezier(bezier) => bezier.stroke.width = -bezier.stroke.width,
Shape::Band(band) => {
band.points.reverse();
for point in &mut band.points {
std::mem::swap(&mut point.y.min, &mut point.y.max);
}
band.stroke.width = -band.stroke.width;
}
Shape::Rect(rect) => {
rect.rect = Rect::from_two_pos(rect.rect.min, rect.rect.max);
if let Some(brush) = &mut rect.brush {
let uv = &mut Arc::make_mut(brush).uv;
std::mem::swap(&mut uv.min, &mut uv.max);
}
if let Some(corner_radius) = corner_radius {
rect.corner_radius = egui::CornerRadius { nw: corner_radius.se, ne: corner_radius.sw, sw: corner_radius.ne, se: corner_radius.nw }
* transform.scaling.abs();
}
rect.stroke.width = -rect.stroke.width;
rect.blur_width = -rect.blur_width;
}
Shape::Text(text) => {
text.underline.width = -text.underline.width;
let galley = Arc::make_mut(&mut text.galley);
galley.rect = Rect::from_two_pos(galley.rect.min, galley.rect.max);
galley.mesh_bounds = Rect::from_two_pos(galley.mesh_bounds.min, galley.mesh_bounds.max);
for placed in &mut galley.rows {
let row = Arc::make_mut(&mut placed.row);
let bounds = &mut row.visuals.mesh_bounds;
*bounds = Rect::from_two_pos(bounds.min, bounds.max);
}
}
_ => {}
}
flat
}
/// A blurred rect: the shadow of a surface.
@@ -488,19 +618,137 @@ fn stroke_width(shape: &Shape) -> f32 {
}
}
fn flatten_ref<'a>(shape: &'a Shape, out: &mut Vec<&'a Shape>) {
/// Pushes each shape in `shape`, nested shapes flattened, with the transform and clip rect egui paints it under: a paint
/// chunk's member moves by its own transform after the chunk's and shows only inside its own clip rect within the chunk's.
fn flatten_ref<'a>(shape: &'a Shape, transform: TSTransform, clip: Rect, in_chunk: bool, out: &mut Vec<(&'a Shape, TSTransform, Rect, bool)>) {
match shape {
Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, out)),
Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten_ref(&clipped.shape, out)),
other => out.push(other),
Shape::Vec(shapes) => shapes.iter().for_each(|shape| flatten_ref(shape, transform, clip, in_chunk, out)),
Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| {
let clip = clip.intersect(transform * clipped.clip_rect);
flatten_ref(&clipped.shape, transform * clipped.transform_after_tessellation, clip, true, out);
}),
other => out.push((other, transform, clip, in_chunk)),
}
}
pub(crate) fn flatten(shape: Shape, out: &mut Vec<Shape>) {
/// Pushes each shape in `clipped`, nested shapes flattened as [`flatten_ref`] lists them, moved by its transform, with
/// the clip rect it shows inside.
/// Mirrored text with a visible underline uses `Stroke::NONE`. Its transformed underlines follow it as separate line segments under the same clip.
pub(crate) fn flatten(clipped: ClippedShape, pixels_per_point: f32, options: egui::epaint::TessellationOptions, out: &mut Vec<(Shape, Rect)>) {
flatten_owned(clipped.shape, clipped.transform_after_tessellation, clipped.clip_rect, false, pixels_per_point, options, out);
}
fn flatten_owned(
shape: Shape,
transform: TSTransform,
clip: Rect,
in_chunk: bool,
pixels_per_point: f32,
options: egui::epaint::TessellationOptions,
out: &mut Vec<(Shape, Rect)>,
) {
match shape {
Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten(shape, out)),
Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| flatten(clipped.shape.clone(), out)),
other => out.push(other),
Shape::Vec(shapes) => shapes.into_iter().for_each(|shape| flatten_owned(shape, transform, clip, in_chunk, pixels_per_point, options, out)),
Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| {
let clip = clip.intersect(transform * clipped.clip_rect);
let transform = transform * clipped.transform_after_tessellation;
flatten_owned(clipped.shape.clone(), transform, clip, true, pixels_per_point, options, out);
}),
mut other => {
if !fixture_draws(&other, transform, clip, in_chunk, pixels_per_point, options) {
return;
}
let mut underlines = Vec::new();
if transform.scaling < 0.0
&& let Shape::Text(text) = &mut other
&& !text.underline.is_empty()
&& !text.galley.is_empty()
&& text.opacity_factor > 0.0
{
let pos = if options.round_text_to_pixels { egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point) } else { text.pos };
let rotation = egui::emath::Rot2::from_angle(text.angle);
let source_clip = transform.inverse() * clip;
for row in &text.galley.rows {
if row.visuals.mesh.is_empty() {
continue;
}
let mut rect = row.visuals.mesh_bounds;
if text.angle != 0.0 {
rect = rect.rotate_bb(rotation);
}
rect = rect.translate((pos + rotation * row.pos.to_vec2()).to_vec2());
if options.coarse_tessellation_culling && !source_clip.intersects(rect) {
continue;
}
let mut tessellator = egui::epaint::Tessellator::new(pixels_per_point, options, [1, 1], Vec::new());
tessellator.set_clip_rect(source_clip);
let mut mesh = egui::epaint::Mesh::default();
tessellator.tessellate_line_segment([rect.left_bottom(), rect.right_bottom()], text.underline, &mut mesh);
if mesh.is_empty() {
continue;
}
for vertex in &mut mesh.vertices {
vertex.pos = transform * vertex.pos;
}
underlines.push(Shape::Mesh(Arc::new(mesh)));
}
text.underline = egui::Stroke::NONE;
}
if transform != TSTransform::IDENTITY {
if options.round_text_to_pixels
&& let Shape::Text(text) = &mut other
{
text.pos = egui::emath::GuiRounding::round_to_pixels(text.pos, pixels_per_point);
}
transform_fixture_shape(&mut other, transform);
if transform.scaling != 1.0
&& let Shape::Text(text) = &mut other
{
for placed in &mut Arc::make_mut(&mut text.galley).rows {
let row = Arc::make_mut(&mut placed.row);
for glyph in &mut row.glyphs {
glyph.pos *= transform.scaling;
glyph.advance_width *= transform.scaling;
glyph.line_height *= transform.scaling;
glyph.font_ascent *= transform.scaling;
glyph.font_height *= transform.scaling;
glyph.font_face_ascent *= transform.scaling;
glyph.font_face_height *= transform.scaling;
glyph.uv_rect.offset *= transform.scaling;
glyph.uv_rect.size *= transform.scaling;
if transform.scaling < 0.0 {
let rect = glyph.logical_rect();
let uv_from = glyph.pos + glyph.uv_rect.offset;
let uv = Rect::from_two_pos(uv_from, uv_from + glyph.uv_rect.size);
glyph.advance_width = glyph.advance_width.abs();
glyph.line_height = glyph.line_height.abs();
glyph.font_ascent = glyph.font_ascent.abs();
glyph.font_height = glyph.font_height.abs();
glyph.font_face_ascent = glyph.font_face_ascent.abs();
glyph.font_face_height = glyph.font_face_height.abs();
glyph.pos = Rect::from_two_pos(rect.min, rect.max).min + egui::vec2(0.0, glyph.font_ascent);
glyph.uv_rect.offset = uv.min - glyph.pos;
glyph.uv_rect.size = uv.size();
}
}
if transform.scaling < 0.0 {
let offset = row.size;
placed.pos += offset;
row.size = -offset;
for glyph in &mut row.glyphs {
glyph.pos -= offset;
}
for vertex in &mut row.visuals.mesh.vertices {
vertex.pos -= offset;
}
row.visuals.mesh_bounds = row.visuals.mesh_bounds.translate(-offset);
}
}
}
}
out.push((other, clip));
out.extend(underlines.into_iter().map(|shape| (shape, clip)));
}
}
}
+51 -7
View File
@@ -80,10 +80,11 @@ pub(crate) struct FooterSlotOf {
/// The flow facts of the body around a memoized view that its content is laid out by: whether that body is a
/// content-sized or a given column, the axes it sizes from its content, the axis it shares among the children that fill
/// it, whether the view runs in a least measure, the
/// axes a scrolling body leaves unbounded, whether it fills a beside label's cell and whether its leaves fit the view's
/// room (`Scoped::view_fits`). A measuring run of a container or a row lays the view out under other facts than its
/// real run, so they are a fact of the view's place, which each kind of run compares on its own (`lazy::Place`,
/// `lazy::Measured`), not of its key.
/// axes a scrolling body leaves unbounded, whether it fills a beside label's cell, whether its leaves fit the view's
/// room (`Scoped::view_fits`), and where the view stands in that body's flow: whether it starts the flow, after a rule
/// or not (`layout::flow_start`), and the gap a `Stack` body leaves before it (`Scoped::flow_gap`). A measuring run of a
/// container or a row lays the view out under other facts than its real run, so they are a fact of the view's place,
/// which each kind of run compares on its own (`lazy::Place`, `lazy::Measured`), not of its key.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Flow {
content_column: bool,
@@ -95,6 +96,17 @@ pub(crate) struct Flow {
cell_fills: bool,
fits: bool,
egui_cell: bool,
start: Option<bool>,
/// The bits of the gap, so the facts compare exactly.
gap: Option<u32>,
}
impl Flow {
/// These facts for a view that stands at `start` in the flow of the body around it (`layout::flow_start`), with
/// `gap` the gap a `Stack` body leaves before it (`Scoped::flow_gap`).
pub(crate) fn in_flow(self, start: Option<bool>, gap: Option<f32>) -> Flow {
Flow { start, gap: gap.map(f32::to_bits), ..self }
}
}
/// The values of an env.
@@ -173,8 +185,13 @@ pub struct Scoped {
/// and the one a child placed in flow closes.
pub(crate) flow_body: Option<Id>,
/// The `Stack` body that places the scope's direct children in flow and the gap it leaves between them; it holds
/// only while that body is `flow_body`.
/// only while that body is the scope's flow (`flow_of`).
pub(crate) stack_gap: Option<(Id, f32)>,
/// The flow of a memoized view's content, when the view stands in a body's flow: the scope's direct children go on
/// with that body's flow from where the view stands in it. The first one starts the flow when the view does
/// (`layout::open_view_flow`), and each one follows the gap a `Stack` body left before the view (`stack_gap`), as
/// the same children shown in that body without the view would.
pub(crate) view_flow: Option<Id>,
/// A rule precedes the start of the body this scope opens: its container draws one under its header, or draws
/// nothing of its own and itself follows one. The body's layout opens its flow start with it.
pub(crate) after_rule: bool,
@@ -488,6 +505,7 @@ impl Scoped {
self.row_line = None;
self.first_line = None;
self.flow_body = None;
self.view_flow = None;
self.column_row = false;
self.fill_body = None;
self.fill_share = None;
@@ -508,6 +526,7 @@ impl Scoped {
|| self.row_line.is_some()
|| self.first_line.is_some()
|| self.flow_body.is_some()
|| self.view_flow.is_some()
|| self.column_row
|| self.fill_body.is_some()
|| self.fill_share.is_some()
@@ -529,10 +548,14 @@ impl Scoped {
/// body, given its share as its room, as the child shown without the view would be. A view that is a unit of a
/// shrinking `Row` that does not share its width sizes from its content along x, as the row counted it: a child
/// that fills there takes its measured width, not the row's flow region a view the row does not narrow is shown in.
pub(crate) fn start_view_room(&mut self, view: Id) {
///
/// `flow` is the flow the content's direct children go on with (`view_flow`, from `layout::open_view_flow`): they
/// keep the gap a `Stack` body around the view leaves before it.
pub(crate) fn start_view_room(&mut self, view: Id, flow: Option<Id>) {
let fits = self.view_fits();
let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_)));
let shares = self.shares();
let gap = self.flow_gap();
let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell);
// The view stands on the line of the row around it only to fill it, as a levelled unit does: a fill-width row in
// it (a bar in a shell slot) takes the line's height and centres on it, as shown without the view; its children
@@ -541,6 +564,8 @@ impl Scoped {
self.start_room();
(self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell);
self.row_line = line;
self.view_flow = flow;
self.stack_gap = flow.zip(gap);
self.fill_view = shares.map(|axis| (view, axis));
if fits {
self.shrink = Some(Shrink::Fit);
@@ -550,6 +575,21 @@ impl Scoped {
}
}
/// The flow that places the scope's direct children: the enclosing body's (`flow_body`), else the flow a memoized
/// view's content goes on with (`view_flow`).
pub(crate) const fn flow_of(&self) -> Option<Id> {
match self.flow_body {
Some(body) => Some(body),
None => self.view_flow,
}
}
/// The gap a `Stack` body leaves before each of the scope's direct children it places in flow after its first
/// (`stack_gap`), while that body is the scope's flow (`flow_of`).
pub(crate) fn flow_gap(&self) -> Option<f32> {
self.stack_gap.filter(|(body, _)| self.flow_of() == Some(*body)).map(|(_, gap)| gap)
}
/// The axis the enclosing body shares among its direct children that fill it (`fill_body`).
pub(crate) const fn shares(&self) -> Option<craft_behavior::Axis> {
match self.fill_body {
@@ -606,7 +646,8 @@ impl Scoped {
})
}
/// The flow facts of the enclosing body a memoized view shown in this scope is laid out by (`Flow`).
/// The flow facts of the enclosing body a memoized view shown in this scope is laid out by (`Flow`), without where
/// the view stands in that body's flow (`Flow::in_flow`).
pub(crate) const fn flow(&self) -> Flow {
Flow {
content_column: self.content_column,
@@ -618,6 +659,8 @@ impl Scoped {
cell_fills: self.cell_fills,
fits: self.view_fits(),
egui_cell: self.egui_cell,
start: None,
gap: None,
}
}
@@ -758,6 +801,7 @@ impl Env {
first_line: None,
flow_body: None,
stack_gap: None,
view_flow: None,
after_rule: false,
column_row: false,
bracket: None,
+11
View File
@@ -702,6 +702,17 @@ fn opener(state: &State, id: Id, noted: Option<StopKey>, focused: Option<Id>) ->
}
}
/// The layer `id` ended its shown life in the running pass after its body ran (a dialog host removed the dialog it
/// showed): its scope plays its exit from now on, so the end hook of this pass moves the focus inside it to its opener,
/// or nowhere, as for a scope that went away. A scope this pass did not show is left as it is.
pub(crate) fn end_scope(ctx: &Context, id: Id) {
with(ctx, |state| {
if let Some(scope) = state.scopes.get_mut(&id) {
scope.closing = true;
}
});
}
/// The innermost scope open in the running pass: the scope whose body is being shown.
#[doc(hidden)]
pub fn open_scope(ctx: &Context) -> Option<Id> {
+47 -12
View File
@@ -330,7 +330,8 @@ pub(crate) struct Persist {
appeared: IdMap<(u64, u64)>,
/// The roots whose asked raise ran in a pass where a floating window (re)appeared: egui raises every layer that
/// shows again, and its area order keeps the old order among the layers raised in one pass, so the raise is asked
/// again in the next pass.
/// again in the next pass. Also the roots raised in a pass that moved only its own raises up, past a carried one
/// that stood above them, asked again in the order they were asked.
raise_again: Vec<Id>,
}
@@ -834,14 +835,20 @@ pub fn take_keys_for_new_dialog(ctx: &Context) {
/// A dialog host removed `dialog`: the layers it showed for it (`stack_place`) in the running or the last pass end
/// their shown life at once (`memory::end_shown`), as a container that shows nothing does, and forget the open state
/// they kept for the session (`memory::open_slot`), so the next open of the dialog is a first pass and starts open: the
/// close that ended the dialog wrote that state closed.
/// close that ended the dialog wrote that state closed. The layers leave this pass's stack, so its end hook records no
/// modal and no top layer for them, and their focus scopes close (`focus::end_scope`): the end hook of this pass moves
/// the focus inside them back to the opener, and the next frame's keys go there.
#[doc(hidden)]
pub fn end_stack_dialog(ctx: &Context, dialog: Id) {
let shown: Vec<Id> =
with_pass(ctx, |pass| pass.current.iter().chain(&pass.last).filter(|entry| entry.dialog == Some(dialog)).map(|entry| entry.id).collect());
let shown: Vec<Id> = with_pass(ctx, |pass| {
let shown = pass.current.iter().chain(&pass.last).filter(|entry| entry.dialog == Some(dialog)).map(|entry| entry.id).collect();
pass.current.retain(|entry| entry.dialog != Some(dialog));
shown
});
for id in shown {
crate::runtime::memory::end_shown(ctx, id);
crate::runtime::memory::forget(ctx, crate::runtime::memory::open_slot(id));
crate::runtime::focus::end_scope(ctx, id);
}
}
@@ -922,8 +929,10 @@ pub(crate) fn end_pass(ctx: &Context) {
});
let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin);
let now = pass::root_frame_nr(ctx);
let (order, to_top, floats, asked) = with_persist(ctx, viewport, |persist| {
let raise: Vec<Id> = std::mem::take(&mut persist.raise_again).into_iter().chain(raise).collect();
let (order, lifted, floats, asked) = with_persist(ctx, viewport, |persist| {
let carried = std::mem::take(&mut persist.raise_again);
let carried_count = carried.len();
let raise: Vec<Id> = carried.into_iter().chain(raise).collect();
let stamp = |id: Id, persist: &mut Persist| {
persist.counter += 1;
persist.raised.insert(id, persist.counter);
@@ -935,6 +944,8 @@ pub(crate) fn end_pass(ctx: &Context) {
.map(|entry| entry.id)
.collect();
let mut asked: Vec<Id> = Vec::new();
// The roots raised by this pass's own reasons, without the raises carried from the last pass.
let mut fresh: Vec<Id> = Vec::new();
for root in &roots {
let shown = current.iter().find(|entry| entry.id == *root);
// A root the last pass did not have appears, and so does one that faded out then and is open again
@@ -949,9 +960,10 @@ pub(crate) fn end_pass(ctx: &Context) {
// its area in the pass before, so it raises none. A root that first shows there is raised by egui itself.
if reopened && shown.is_some_and(|entry| !entry.window && (entry.rank == Rank::Window || entry.among_windows)) {
asked.push(*root);
fresh.push(*root);
}
}
for id in raise {
for (at_raise, id) in raise.into_iter().enumerate() {
let mut at = current.iter().find(|entry| entry.id == id);
while let Some(parent) = at.and_then(|entry| entry.parent).and_then(|parent| current.iter().find(|other| other.id == parent)) {
at = Some(parent);
@@ -959,8 +971,20 @@ pub(crate) fn end_pass(ctx: &Context) {
if let Some(root) = at {
stamp(root.id, persist);
asked.push(root.id);
if at_raise >= carried_count {
fresh.push(root.id);
}
}
}
// A root asked more than once keeps its last place, so a raise asked again in every pass carries one entry.
let mut once: Vec<Id> = Vec::new();
for id in asked.iter().rev() {
if !once.contains(id) {
once.push(*id);
}
}
once.reverse();
let asked = once;
persist.raised.retain(|id, _| roots.contains(id));
persist.appeared.retain(|id, _| current.iter().any(|entry| entry.id == *id));
let before = families(&current, &persist.raised);
@@ -976,7 +1000,9 @@ pub(crate) fn end_pass(ctx: &Context) {
let families = families(&current, &persist.raised);
let mut order: Vec<Layer> = Vec::new();
let mut listed: Vec<Id> = Vec::new();
let mut to_top: Vec<Layer> = Vec::new();
// The layers an asked raise moves to the top of egui's area order, in the raise order, each with whether this
// pass asked for it.
let mut lifted: Vec<(Layer, bool)> = Vec::new();
let mut floats: Vec<Layer> = Vec::new();
persist.stack.clear();
for members in &families {
@@ -996,9 +1022,9 @@ pub(crate) fn end_pass(ctx: &Context) {
listed.push(member.id);
} else if !member.window {
floats.push(member.layer);
if members.first().is_some_and(|root| asked.contains(&root.id)) {
if let Some(root) = members.first().filter(|root| asked.contains(&root.id)) {
// An asked raise of a layer left to egui's area order raises it there, as a press on it does.
to_top.push(member.layer);
lifted.push((member.layer, fresh.contains(&root.id)));
}
}
persist.stack.push(member.id);
@@ -1026,13 +1052,22 @@ pub(crate) fn end_pass(ctx: &Context) {
.map(|(_, members)| {
members.iter().flat_map(|member| std::iter::once(member.rect).chain(member.anchor).chain(member.peers.iter().copied())).collect()
});
(order, to_top, floats, asked)
(order, lifted, floats, asked)
});
// egui keeps the old order among the layers it moves to the top in one pass. When that order differs from the
// raise order, a raise carried from the last pass and a raise asked in this one cannot go up together: the carried
// one would stay above the newer one. Only this pass's raises go up then, and `held_back` asks every raise again in
// the next pass, where this pass's raises already stand above the carried ones.
let stacked = areas::area_order(ctx);
let place = |layer: &Layer| stacked.iter().position(|at| at == layer).unwrap_or(stacked.len());
let in_order = lifted.windows(2).all(|pair| place(&pair[0].0) <= place(&pair[1].0));
let held_back = !in_order && lifted.iter().any(|(_, fresh)| *fresh) && lifted.iter().any(|(_, fresh)| !fresh);
let to_top: Vec<Layer> = lifted.into_iter().filter(|(_, fresh)| *fresh || !held_back).map(|(layer, _)| layer).collect();
areas::set_layer_order(ctx, &order);
for layer in &to_top {
areas::move_to_top(ctx, *layer);
}
if !to_top.is_empty() && floats.iter().any(|layer| !areas::visible_last_frame(ctx, *layer)) {
if held_back || (!to_top.is_empty() && floats.iter().any(|layer| !areas::visible_last_frame(ctx, *layer))) {
with_persist(ctx, viewport, |persist| persist.raise_again = asked);
}
// An owner takes a close in the frame after the request at the latest; one nobody took is for a layer that is not shown.
+9 -7
View File
@@ -528,11 +528,12 @@ impl Fixture {
let Some(mut paint) = self.frames.take_paint() else { return out };
// Only the shapes are asked for: the texture changes since the first recorded frame go unrendered.
paint.textures_delta.clear();
let mut shapes = Vec::new();
let options = self.ctx().tessellation_options(|options| *options);
for clipped in paint.shapes {
let mut shapes = Vec::new();
fixture::flatten(clipped.shape, &mut shapes);
out.extend(shapes.into_iter().map(|shape| (clipped.clip_rect, shape)));
fixture::flatten(clipped, paint.pixels_per_point, options, &mut shapes);
}
out.extend(shapes.into_iter().map(|(shape, clip)| (clip, shape)));
out
}
@@ -541,14 +542,15 @@ impl Fixture {
pub fn frame_shapes_with(&mut self, events: Vec<Event>) -> Vec<egui::Shape> {
self.frames.record_paint();
self.frame(events);
let mut shapes = Vec::new();
let Some(mut paint) = self.frames.take_paint() else { return shapes };
let Some(mut paint) = self.frames.take_paint() else { return Vec::new() };
// Only the shapes are asked for: the texture changes since the first recorded frame go unrendered.
paint.textures_delta.clear();
let mut shapes = Vec::new();
let options = self.ctx().tessellation_options(|options| *options);
for clipped in paint.shapes {
fixture::flatten(clipped.shape, &mut shapes);
fixture::flatten(clipped, paint.pixels_per_point, options, &mut shapes);
}
shapes
shapes.into_iter().map(|(shape, _)| shape).collect()
}
/// `n` frames with no events.
File diff suppressed because it is too large. Load diff
+2
View File
@@ -1,5 +1,7 @@
pub(crate) mod backdrop;
pub(crate) mod chunk_members;
pub(crate) mod draw_place;
pub(crate) mod painters;
+154 -5
View File
@@ -10,7 +10,7 @@ use craft_ui::runtime::focus::{FocusTarget, KeyUse, host_canvas, request};
use craft_ui::runtime::frame::take_output;
use craft_ui::style::StyleCx;
use craft_ui::testing::focus::{named_id, widget};
use craft_ui::testing::input::{key_press, key_repeat, text};
use craft_ui::testing::input::{key_press, text};
use craft_ui::testing::pointer::click;
use craft_ui::testing::{Frames, trial};
use craft_ui_test_kit::contract::PlainStyle;
@@ -147,12 +147,20 @@ impl Session {
const ALT: Modifiers = Modifiers::ALT;
/// The keypad digit key of `digit`; egui names keypad and top-row digits alike.
/// The logical key of `digit`; egui names keypad and top-row digits alike.
fn digit_key(digit: char) -> Key {
const DIGITS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9];
DIGITS[digit.to_digit(10).expect("a decimal digit") as usize]
}
/// A keypad digit's press, auto-repeat or release with Alt held: its physical key is the keypad one.
fn keypad(digit: char, pressed: bool, repeat: bool) -> Event {
const KEYPAD: [Key; 10] =
[Key::Numpad0, Key::Numpad1, Key::Numpad2, Key::Numpad3, Key::Numpad4, Key::Numpad5, Key::Numpad6, Key::Numpad7, Key::Numpad8, Key::Numpad9];
let physical = KEYPAD[digit.to_digit(10).expect("a decimal digit") as usize];
Event::Key { key: digit_key(digit), physical_key: Some(physical), pressed, repeat, modifiers: ALT }
}
fn key_release(key: Key, modifiers: Modifiers) -> Event {
Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers }
}
@@ -162,17 +170,28 @@ fn alt(down: bool) -> Event {
Event::ModifiersChanged(if down { ALT } else { Modifiers::NONE })
}
/// The frame of one digit typed with Alt held: its press with the digit's own text (Linux sends it), then its release.
/// The frame of one keypad digit typed with Alt held: its press with the digit's own text (Linux sends it), then its
/// release.
fn digit(d: char) -> Vec<Event> {
vec![keypad(d, true, false), text(&d.to_string()), keypad(d, false, false)]
}
/// The frame of one top-row digit typed with Alt held.
fn top_row_digit(d: char) -> Vec<Event> {
let key = digit_key(d);
vec![key_press(key, ALT), text(&d.to_string()), key_release(key, ALT)]
}
/// The frames of an Alt code: Alt down, each digit in a frame of its own, then Alt up.
/// The frames of an Alt code: Alt down, each keypad digit in a frame of its own, then Alt up.
fn code(digits: &str) -> Vec<Vec<Event>> {
std::iter::once(vec![alt(true)]).chain(digits.chars().map(digit)).chain([vec![alt(false)]]).collect()
}
/// `code(digits)` typed on the top row, which Windows does not compose.
fn top_row_code(digits: &str) -> Vec<Vec<Event>> {
std::iter::once(vec![alt(true)]).chain(digits.chars().map(top_row_digit)).chain([vec![alt(false)]]).collect()
}
/// `code(digits)`, then a frame in which the platform sends `composed`, the character it made of the code itself.
fn code_then(digits: &str, composed: &str) -> Vec<Vec<Event>> {
let mut frames = code(digits);
@@ -206,7 +225,7 @@ fn an_alt_numpad_code_types_its_character_once() {
assert_eq!(session.send(code("233")), typed("Θ"), "{os:?}: no leading 0 reads the OEM page");
assert_eq!(session.send(code("8364")), typed("€"), "{os:?}: above 255 the code is the Unicode character");
// With the repeat counted the code would be 02333, U+091D.
let held = vec![key_press(Key::Num3, ALT), text("3"), key_repeat(Key::Num3, ALT), text("3"), key_release(Key::Num3, ALT)];
let held = vec![keypad('3', true, false), text("3"), keypad('3', true, true), text("3"), keypad('3', false, false)];
let held_digit = vec![vec![alt(true)], digit('0'), digit('2'), held, digit('3'), vec![alt(false)]];
assert_eq!(session.send(held_digit), typed("é"), "{os:?}: a digit's auto-repeat adds nothing and types nothing");
// Eight digits are kept: 00000233 is é, where all nine (2334) would be U+091E.
@@ -226,6 +245,10 @@ fn an_alt_numpad_code_types_its_character_once() {
assert_eq!(other_echo, typed("€¬"), "{os:?}: a different text after a code is typed as normal");
}
}
// Windows composes keypad codes only: after a top-row code, a different text is what was typed next.
let mut top_row_then = top_row_code("0233");
top_row_then.push(vec![text("й")]);
assert_eq!(session.send(top_row_then), typed("éй"), "{os:?}: the text after a top-row code is typed as normal");
// Focus going to another window ends the code: its Alt release types nothing and is no lone Alt.
let away = vec![vec![alt(true)], digit('0'), digit('2'), vec![Event::WindowFocused(false)], vec![Event::WindowFocused(true), alt(false)]];
@@ -250,6 +273,132 @@ fn an_alt_numpad_code_types_its_character_once() {
assert!(!option.lone_alt, "macOS has no lone Alt either");
}
/// The press, text and release that winit on Windows reports a composed Alt code's character with: the press has no
/// physical key, and its key is the one egui names the character by.
fn composed_on_key(key: Key, composed: &str) -> Vec<Event> {
let event = |pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE };
vec![event(true), text(composed), event(false)]
}
/// On Windows the platform's character for a code can come on a key press of its own, with no physical key, after
/// the Alt release: in the release's frame or in the next one. For a character egui has a key for (`\` is
/// `Key::Backslash`, `A` is `Key::A`), that press is the platform's carrier of the character, not a key the user
/// pressed: the character is typed once and the press does not reach egui, where a single-key shortcut could take
/// it. Above 255 the carried character is the one of the byte Windows reduces the code to, and ours stays. A key the
/// user presses after a code still types as normal, also one with no physical key in egui.
#[trial]
fn a_composed_character_on_a_key_press_of_its_own_is_typed_once() {
let typed = Rc::new(RefCell::new(String::new()));
let reached = Rc::new(RefCell::new(Vec::<(Key, bool)>::new()));
let mut show = {
let (typed, reached) = (Rc::clone(&typed), Rc::clone(&reached));
move |ui: &mut egui::Ui| {
let keys: Vec<(Key, bool)> = ui.input(|input| {
input
.events
.iter()
.filter_map(|event| match event {
Event::Key { key, pressed, .. } => Some((*key, *pressed)),
_ => None,
})
.collect()
});
reached.borrow_mut().extend(keys);
Probe::new(&typed).label("Text").id_salt("alt_code_field").show_at(ui, AT);
}
};
let mut frames = Frames::new();
craft_ui::testing::windows::set_os(&frames.ctx, Os::Windows);
frames.root(RootEnv::default().alt_code_pages(AltCodePages::new(1252, 437)));
frames.idle(3, &mut show);
// Plays `sequence`, then a frame with none; returns the field's text and the key events that reached egui, each
// with whether it is a press.
let send = |frames: &mut Frames, show: &mut dyn FnMut(&mut egui::Ui), sequence: Vec<Vec<Event>>| {
reached.borrow_mut().clear();
typed.borrow_mut().clear();
for events in sequence {
frames.frame(events, &mut *show);
}
frames.frame(Vec::new(), &mut *show);
(typed.take(), reached.take())
};
let next_frame = || {
let mut frames = code("0092");
frames.push(composed_on_key(Key::Backslash, "\\"));
frames
};
let same_frame = || {
let mut frames = code("65");
if let Some(release) = frames.last_mut() {
release.extend(composed_on_key(Key::A, "A"));
}
frames
};
let then_pressed = || {
let mut frames = code("0233");
frames.push(vec![key_press(Key::A, Modifiers::NONE), text("a"), key_release(Key::A, Modifiers::NONE)]);
frames
};
// Above 255 Windows reduces the code to a byte: 321 is 65, `A`, while ours is U+0141.
let reduced = || {
let mut frames = code("321");
frames.push(composed_on_key(Key::A, "A"));
frames
};
// A key egui has no physical key for (a JIS key typing `\`) pressed after a code whose character is `A`.
let unmapped = || {
let mut frames = code("65");
frames.push(composed_on_key(Key::Backslash, "\\"));
frames
};
// With nothing focused, egui's input holds every key event no component took. The digits' releases reach it too.
let of = |keys: Vec<(Key, bool)>, key: Key| keys.into_iter().filter(|(k, _)| *k == key).collect::<Vec<_>>();
let (_, keys) = send(&mut frames, &mut show, next_frame());
assert_eq!(of(keys, Key::Backslash), [], "a carrier press and its release in the next frame do not reach egui");
let (_, keys) = send(&mut frames, &mut show, same_frame());
assert_eq!(of(keys, Key::A), [], "a carrier press and its release in the release's frame do not reach egui");
let (_, keys) = send(&mut frames, &mut show, then_pressed());
assert_eq!(of(keys, Key::A), [(Key::A, true), (Key::A, false)], "a key the user presses after a code reaches egui");
let (_, keys) = send(&mut frames, &mut show, reduced());
assert_eq!(of(keys, Key::A), [], "the carrier of the byte a code above 255 reduces to does not reach egui");
let (_, keys) = send(&mut frames, &mut show, unmapped());
assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "another key with no physical key reaches egui");
// The carrier's release never comes (the platform drops it with a held backslash key's), then the user presses
// that key with no physical key in egui: its release reaches egui with its press.
let mut lost_release = code("0092");
lost_release.push(composed_on_key(Key::Backslash, "\\")[..2].to_vec());
lost_release.push(composed_on_key(Key::Backslash, "\\"));
let (_, keys) = send(&mut frames, &mut show, lost_release);
assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a carrier with no release keeps no later release");
// A code the platform sends nothing after, then focus leaves the window and comes back: a key with no physical key
// in egui that types the code's character is the user's.
let mut refocused = code("0092");
refocused.push(vec![Event::WindowFocused(false)]);
refocused.push(vec![Event::WindowFocused(true)]);
refocused.push(composed_on_key(Key::Backslash, "\\"));
let (_, keys) = send(&mut frames, &mut show, refocused);
assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a focus loss ends the code's echo");
// Windows composes nothing for a top-row code: a key with no physical key in egui that types the code's character
// right after it, with no focus change, is the user's.
let top_row = || {
let mut frames = top_row_code("0092");
frames.push(composed_on_key(Key::Backslash, "\\"));
frames
};
let (_, keys) = send(&mut frames, &mut show, top_row());
assert_eq!(of(keys, Key::Backslash), [(Key::Backslash, true), (Key::Backslash, false)], "a press after a top-row code reaches egui");
click(&mut frames, AT.center(), &mut show);
frames.idle(1, &mut show);
assert_eq!(send(&mut frames, &mut show, reduced()).0, "\u{141}", "above 255 ours stays and the carried byte is dropped");
assert_eq!(send(&mut frames, &mut show, unmapped()).0, "A\\", "another key with no physical key types as normal");
assert_eq!(send(&mut frames, &mut show, next_frame()).0, "\\", "a carrier press in the next frame types nothing more");
assert_eq!(send(&mut frames, &mut show, same_frame()).0, "A", "a carrier press in the release's frame types nothing more");
assert_eq!(send(&mut frames, &mut show, then_pressed()).0, "éa", "a key the user presses after a code types as normal");
assert_eq!(send(&mut frames, &mut show, top_row()).0, "\\\\", "a key pressed after a top-row code types as normal");
}
/// Alt with the digit 3, which the host canvas of the next trial claims.
const ALT_3: craft_keymap::Chord = craft_keymap::Chord::new(craft_keymap::Mods::ALT, craft_keymap::Key::Num3);
+53
View File
@@ -1358,3 +1358,56 @@ fn an_alert_moves_by_its_title_row() {
fixture.drag_at(at, vec2(40.0, 30.0)).idle(4);
assert_eq!(dialog.get().min - before.min, vec2(40.0, 30.0), "the alert moved with the drag");
}
/// A modal dialog with a name field that finishes in the pass after `finish` is set, as a held OK the app accepted does.
struct Renaming {
name: String,
finish: Arc<AtomicBool>,
}
impl StackDialog for Renaming {
type Result = ();
fn id(&self) -> DialogId {
dialog_id("renaming")
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
Dialog::new("Rename").id_salt("renaming").show(ui, |ui, _| {
TextField::new("New name", Bind::bound(&mut self.name)).show(ui);
});
self.finish.load(Ordering::Relaxed).then_some(DialogResult::Ok(()))
}
}
/// A dialog the host removes in the pass its body ran gives up the keyboard in that pass: the next frame's typing goes
/// to the field the dialog opened from, and that frame sees no modal layer.
#[trial]
fn a_dialog_that_finishes_after_its_pass_ran_hands_the_next_keys_to_its_opener() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let below = Rc::new(RefCell::new(String::new()));
let modal_seen = Rc::new(RefCell::new(Vec::new()));
let (shown, field, seen) = (Rc::clone(&host), Rc::clone(&below), Rc::clone(&modal_seen));
let mut fixture = Fixture::new(move |ui| {
seen.borrow_mut().push(any_open(ui.ctx(), OpenFilter::Modal));
TextField::new("Layer name", Bind::bound(&mut *field.borrow_mut())).show(ui);
shown.borrow_mut().run(ui);
});
fixture.settle();
let opener = fixture.by_label("Layer name").expect("the window's field shows");
fixture.click(&opener).settle();
let finish = Arc::new(AtomicBool::new(false));
host.borrow_mut().open(Renaming { name: String::new(), finish: Arc::clone(&finish) });
fixture.settle();
let in_dialog = fixture.by_label("New name").expect("the dialog's field shows");
assert_eq!(fixture.tree().focused_key(), in_dialog.node, "the dialog's field has the keyboard");
finish.store(true, Ordering::Relaxed);
fixture.frame(Vec::new());
assert!(!host.borrow().is_open::<Renaming>(), "the dialog finished");
assert_eq!(fixture.passes(), 1, "the frame the dialog finished in ran one pass");
modal_seen.borrow_mut().clear();
fixture.frame(vec![egui::Event::Text("x".to_owned())]);
assert_eq!(modal_seen.borrow().first(), Some(&false), "the frame after the close sees no modal layer");
fixture.idle(2);
assert_eq!(*below.borrow(), "x", "the typing of the frame after the close reached the opener's field");
}
@@ -46,3 +46,96 @@ fn a_spaced_section_stands_its_rule_off_the_row_above_and_its_header() {
assert!(spaced_above >= section_gap - 0.5, "the spaced rule stands a section gap ({section_gap}) off the row, not {spaced_above}");
assert!(spaced_below > tight_below, "the spaced header stands further below its rule ({spaced_below}) than the tight one ({tight_below})");
}
/// A section that returns where its body's text landed, to show directly or as a memoized view's content.
fn section_at(title: &mut &'static str, ui: &mut Ui) -> Rect {
let mut body = Rect::NOTHING;
Section::fixed(*title).show(ui, |ui, _| body = Text::new("Width").show(ui).rect);
body
}
/// Where the bodies of three sections land under `SectionRhythm::Spaced`: in a quiet-titled panel whose title heads its
/// body (`QuietHeader::Heads`) and in a plain stack after a row, each section shown directly or, with `memo`, in a
/// `MemoView` of its own.
fn section_bodies(memo: bool) -> Vec<Rect> {
use craft_ui::contract::{MemoView, QuietHeader};
use craft_ui::sections::{HeaderStrength, Panel};
const TITLES: [&str; 3] = ["Transform", "Appearance", "Stroke"];
let mut frames = Frames::new();
let mut root = RootEnv::default();
root.values.set(SectionRhythm::Spaced);
root.values.set(QuietHeader::Heads);
frames.root(root);
let sections = |ui: &mut Ui, bodies: &mut Vec<Rect>| {
for (at, title) in TITLES.into_iter().enumerate() {
let body = if memo { MemoView::new(("section", at), title, section_at).show(ui) } else { Some(section_at(&mut { title }, ui)) };
bodies.push(body.unwrap_or(Rect::NOTHING));
}
};
let mut bodies = Vec::new();
let mut show = |ui: &mut Ui| {
bodies.clear();
Panel::new("Properties").titled().strength(HeaderStrength::Quiet).show(ui, |ui, _| sections(ui, &mut bodies));
Stack::new().show(ui, |ui, _| {
let _ = Text::new("Fill").show(ui);
sections(ui, &mut bodies);
});
};
frames.idle(4, &mut show);
bodies
}
/// Regression: a section shown in a `MemoView` in a spaced stack lost the stack's gap and flow start, so under
/// `QuietHeader::Heads` the first one drew the rule above it with a section gap of room and each later one stood a
/// stack gap further down. A memoized section lands where the same section shown directly does, on its first run and
/// on its replays.
#[trial]
fn a_memoized_section_in_a_spaced_stack_lands_where_a_direct_one_does() {
let direct = section_bodies(false);
let memoized = section_bodies(true);
assert_eq!(direct.len(), 6, "every section shows its body");
assert!(direct.iter().all(|body| body.is_positive()), "every section's body is placed: {direct:?}");
assert_eq!(memoized, direct, "memoized sections land where direct ones do");
}
/// Where the bodies of two sections land in a spaced two-column grid of equal, top-aligned columns, in the last frame
/// after they swap cells, each shown directly or, with `memo`, in a `MemoView` of its own. The first cell starts the
/// grid's flow and the second does not, and both cells give a section a room of the same size.
fn bodies_after_a_swap(memo: bool) -> [Rect; 2] {
use craft_behavior::ColumnWidth;
use craft_ui::contract::MemoView;
use craft_ui::layout::CellAlign;
use craft_ui::layout_components::Grid;
static HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(0.5), ColumnWidth::fill(0.5)];
const TITLES: [&str; 2] = ["Stroke", "Fill"];
let mut frames = Frames::new();
let mut root = RootEnv::default();
root.values.set(SectionRhythm::Spaced);
frames.root(root);
let mut bodies = [Rect::NOTHING; 2];
let mut show = |ui: &mut Ui, swapped: bool| {
Grid::new(&HALVES).fill().cells(CellAlign::Top).show(ui, |ui, _| {
for cell in 0..2 {
let at = if swapped { 1 - cell } else { cell };
bodies[at] = if memo {
MemoView::new(("section", at), TITLES[at], section_at).show(ui).unwrap_or(Rect::NOTHING)
} else {
section_at(&mut { TITLES[at] }, ui)
};
}
});
};
frames.idle(3, |ui| show(ui, false));
frames.idle(3, |ui| show(ui, true));
bodies
}
/// Regression: a memoized section that ran in the cell that starts its body's flow replayed that run in a cell of the
/// same size after it, without the room a section after another stands under, and the other the other way round. A view
/// whose place in its body's flow changed runs again.
#[trial]
fn a_memoized_section_runs_again_when_its_place_in_the_flow_changes() {
let direct = bodies_after_a_swap(false);
assert!(direct.iter().all(|body| body.is_positive()), "every section's body is placed: {direct:?}");
assert_eq!(bodies_after_a_swap(true), direct, "memoized sections land where direct ones do");
}
@@ -306,3 +306,57 @@ fn a_window_raised_as_the_windows_show_again_comes_to_the_front() {
fixture.frame(Vec::new());
assert_eq!(top.get(), first.get(), "the window raised as they showed again is in front");
}
/// A document window raised in the passes after another one's raise was carried over (a window first showed in that
/// pass) comes in front of it, and the window raised first stays in front of the one that showed. egui keeps the old
/// order among the layers it moves to the top in one pass, so the carried raise and the newer one going up together
/// left the window raised first in front.
#[trial]
fn a_window_raised_after_a_carried_raise_comes_in_front_of_it() {
use craft_ui::testing::Fixture;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
// First and Second overlap at `first_second`, First and Third (which shows later) at `first_third`.
let (first_second, first_third) = (pos2(300.0, 150.0), pos2(100.0, 220.0));
let places = [("First.psd", pos2(40.0, 40.0)), ("Second.psd", pos2(200.0, 120.0)), ("Third.psd", pos2(40.0, 200.0))];
let third_shows = Rc::new(Cell::new(false));
let raised: Rc<Cell<Option<&str>>> = Rc::new(Cell::new(None));
let layers = Rc::new(RefCell::new(HashMap::new()));
let tops = Rc::new(Cell::new((None, None)));
let (shows, raise, seen, front) = (third_shows.clone(), raised.clone(), layers.clone(), tops.clone());
let mut fixture = Fixture::new(move |ui| {
front.set((ui.ctx().layer_id_at(first_second), ui.ctx().layer_id_at(first_third)));
for (name, at) in places {
if name == "Third.psd" && !shows.get() {
continue;
}
let window = DocumentWindow::new(name).id_salt(name).first_placed(Rect::from_min_size(at, vec2(300.0, 200.0)));
if raise.get() == Some(name) { window.raise() } else { window }.show(ui, |ui, _| {
seen.borrow_mut().insert(name, ui.layer_id());
});
}
});
fixture.settle();
let layer = |name: &str| layers.borrow().get(name).copied();
assert_eq!(tops.get().0, layer("Second.psd"), "the window opened last is in front");
// Third shows in the pass First is raised in, so First's raise is carried to the next pass.
third_shows.set(true);
raised.set(Some("First.psd"));
fixture.frame(Vec::new());
// Second is raised in three passes in a row, as a body that asks for it while it is current does.
// Each frame reads the order the pass before it left.
raised.set(Some("Second.psd"));
fixture.frame(Vec::new());
fixture.frame(Vec::new());
assert_eq!(tops.get().0, layer("Second.psd"), "the window raised last is in front of the one raised before it");
fixture.frame(Vec::new());
assert_eq!(tops.get().0, layer("Second.psd"), "the window raised last stays in front");
assert_eq!(tops.get().1, layer("First.psd"), "the carried raise goes up while Second is still raised in every pass");
raised.set(None);
fixture.frame(Vec::new());
fixture.frame(Vec::new());
assert_eq!(tops.get().0, layer("Second.psd"), "the window raised last stays in front once its raise ends");
assert_eq!(tops.get().1, layer("First.psd"), "the window raised first is in front of the one that showed as it was raised");
}
+2 -2
View File
@@ -22,8 +22,8 @@ pub use predicate::{DropTest, RowTest, RowText};
pub(crate) use row::RowThumb;
pub use row::{
CellStatus, CommandHighlight, HueTarget, LabelUnderline, ListRow, ListRowStyle, RowDragSpot, RowEvent, RowInk, RowLines, RowOutput, RowRun,
RowStyleCx, ThumbAspect, ThumbPaint, ThumbRows, ThumbSize, ThumbTarget, ThumbTargets, TrailingFace, TrailingPart, TreeIndent, TreeLeaves,
label_color_label, tree_steps,
RowStyleCx, ThumbAspect, ThumbPaint, ThumbPoints, ThumbRows, ThumbSize, ThumbTarget, ThumbTargets, TrailingFace, TrailingPart, TreeIndent,
TreeLeaves, label_color_label, tree_steps,
};
pub use toggle::{ToggleCell, ToggleFace, ToggleState};
pub use tree::OpenSet;
+1 -1
View File
@@ -45,7 +45,7 @@ pub use style::{CommandHighlight, ListRowStyle, RowStyleCx, ThumbRows, TreeInden
pub(crate) use thumb::RowThumb;
pub(super) use thumb::Thumb;
use thumb::ThumbPayload;
pub use thumb::{ThumbAspect, ThumbPaint, ThumbSize, ThumbTarget, ThumbTargets};
pub use thumb::{ThumbAspect, ThumbPaint, ThumbPoints, ThumbSize, ThumbTarget, ThumbTargets};
use trailing::Hosted;
pub(super) use trailing::{Trailing, TrailingItem};
pub use trailing::{TrailingFace, TrailingPart};
+11 -5
View File
@@ -92,16 +92,22 @@ impl Sizes {
(cell - 2.0 * self.cell_inset).max(0.0)
}
/// The thumbnail side of `thumb`: a token side, or for a custom size the entered height less the padding.
fn side(&self, thumb: ThumbSize) -> f32 {
thumb.pick(self.thumbs)
match thumb {
ThumbSize::Custom(points) => (points.length() - self.thumb_pad).max(0.0),
_ => thumb.pick(self.thumbs),
}
}
/// The height of a row with a thumbnail of `thumb` and, if `detail`, a detail line: the row height, the thumbnail
/// with its padding (at least `thumb_row`), or the two lines of text, whichever is tallest.
/// with its padding (at least `thumb_row`), or the two lines of text, whichever is tallest. A custom size is the
/// row's height itself, at least the label's line.
pub(super) fn height(&self, thumb: ThumbSize, detail: bool) -> f32 {
let base = match self.side(thumb) {
0.0 => self.row,
side => (side + self.thumb_pad).max(self.thumb_row),
let base = match (thumb, self.side(thumb)) {
(ThumbSize::Custom(points), _) => points.length().max(self.label_line),
(_, 0.0) => self.row,
(_, side) => (side + self.thumb_pad).max(self.thumb_row),
};
if detail { base.max(self.label_line + self.detail_line + self.gap) } else { base }
}
+56 -2
View File
@@ -47,19 +47,24 @@ pub enum ThumbSize {
Medium,
/// `size.thumb.lg`.
Large,
/// A size the user enters: a list row is that many points high and its thumbnail is the row less the thumbnail
/// padding; a picture or a tile of this size is that many points on a side.
Custom(ThumbPoints),
}
impl ThumbSize {
/// Every setting a user picks from.
/// Every named setting a user picks from; [`ThumbSize::Custom`] is entered as a number instead.
pub const ALL: [ThumbSize; 4] = [ThumbSize::None, ThumbSize::Small, ThumbSize::Medium, ThumbSize::Large];
/// The side the setting takes from the small, medium and large sides; 0 for `None`.
/// The side the setting takes from the small, medium and large sides; 0 for `None`, the entered points for
/// `Custom`.
pub(crate) const fn pick(self, sides: [f32; 3]) -> f32 {
match self {
ThumbSize::None => 0.0,
ThumbSize::Small => sides[0],
ThumbSize::Medium => sides[1],
ThumbSize::Large => sides[2],
ThumbSize::Custom(points) => points.length(),
}
}
@@ -70,10 +75,59 @@ impl ThumbSize {
ThumbSize::Small => words.thumb_small.clone(),
ThumbSize::Medium => words.thumb_medium.clone(),
ThumbSize::Large => words.thumb_large.clone(),
ThumbSize::Custom(_) => words.thumb_custom.clone(),
}
}
}
/// The size of [`ThumbSize::Custom`]: whole points from [`ThumbPoints::MIN`] to [`ThumbPoints::MAX`]. A value outside
/// that range is clamped into it, both by [`ThumbPoints::new`] and when a saved setting is read, so a row is never
/// drawn at a size outside it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[serde(from = "u16", into = "u16")]
pub struct ThumbPoints(u16);
impl ThumbPoints {
/// The smallest size, in points.
pub const MIN: u16 = 12;
/// The largest size, in points.
pub const MAX: u16 = 100;
/// `points` whole points, clamped to `MIN..=MAX`.
pub const fn new(points: u16) -> Self {
Self(if points < Self::MIN {
Self::MIN
} else if points > Self::MAX {
Self::MAX
} else {
points
})
}
/// The size in whole points.
pub const fn get(self) -> u16 {
self.0
}
/// The size as a length in points.
pub(crate) const fn length(self) -> f32 {
self.0 as f32
}
}
impl From<u16> for ThumbPoints {
/// [`ThumbPoints::new`]: clamped to `MIN..=MAX`.
fn from(points: u16) -> Self {
Self::new(points)
}
}
impl From<ThumbPoints> for u16 {
fn from(points: ThumbPoints) -> Self {
points.get()
}
}
/// One of a row's thumbnails.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
+1
View File
@@ -9,6 +9,7 @@ craft_ui::words! {
thumb_small: "thumbSize.small" = "Small";
thumb_medium: "thumbSize.medium" = "Medium";
thumb_large: "thumbSize.large" = "Large";
thumb_custom: "thumbSize.custom" = "Custom";
toggle_visibility: "toggleCell.visibility" = "Visibility {row}";
toggle_lock: "toggleCell.lock" = "Lock {row}";
label_none: "list.labelNone" = "None";
+73
View File
@@ -248,6 +248,79 @@ fn text_rows_are_shorter_than_control_rows() {
assert!(text[2].top() - text[0].top() < control[2].top() - control[0].top(), "text rows follow each other closer");
}
/// The rect of a list row with a thumbnail of `size` and the thumbnail's rect (the rect it paints into, inside its
/// frame), with the tokens' small, medium and large thumbnail sides, the thumbnail padding and a thumbnail row's least
/// height.
fn thumb_row(size: craft_ui::list::ThumbSize) -> (egui::Rect, egui::Rect, [f32; 3], f32, f32) {
use craft_ui::runtime::env::Env;
use std::cell::Cell;
let painted = Rc::new(Cell::new(egui::Rect::NOTHING));
let read = Rc::new(Cell::new(([0.0_f32; 3], 0.0_f32, 0.0_f32, 0.0_f32)));
let (held, tokens) = (painted.clone(), read.clone());
let mut fixture = Fixture::new(move |ui| {
let env = Env::of(ui);
let all = env.tokens.tokens();
let thumb = &all.size.thumb;
let least = all.size.control.md + all.space.pad.regular;
tokens.set(([thumb.sm, thumb.md, thumb.lg], all.space.gap.stack, least, all.stroke.thin));
let keys = [0_usize];
let source = keyed(&keys, |key: &usize| *key);
let _ = List::new("Layers").show_items(ui, &source, &mut |key, _| {
let held = held.clone();
ListRow::new(NAMES[*key]).thumb(size, move |_, rect| held.set(rect))
});
});
fixture.room(Vec2::new(300.0, 400.0));
fixture.settle();
let row = fixture.by_label(NAMES[0]).expect("the row's node").rect;
let (sides, pad, least, frame) = read.get();
(row, painted.get().expand(frame), sides, pad, least)
}
/// A custom thumbnail size is the row's height, and the row's square thumbnail grows with it point for point.
#[trial]
fn a_custom_thumbnail_size_sets_the_row_height_and_its_thumbnail() {
use craft_ui::list::{ThumbPoints, ThumbSize};
let (small, large) = (ThumbPoints::new(40), ThumbPoints::new(64));
let (row, thumb, ..) = thumb_row(ThumbSize::Custom(small));
let (taller, larger, ..) = thumb_row(ThumbSize::Custom(large));
assert_eq!(row.height(), f32::from(small.get()), "the row is as high as its size: {row:?}");
assert_eq!(taller.height(), f32::from(large.get()), "the row is as high as its size: {taller:?}");
assert!(row.contains_rect(thumb) && thumb.height() < row.height(), "the thumbnail lies inside its row: {row:?} {thumb:?}");
assert_eq!(thumb.width(), thumb.height(), "the thumbnail is square: {thumb:?}");
assert_eq!(larger.height() - thumb.height(), taller.height() - row.height(), "the thumbnail grows as the row does: {thumb:?} {larger:?}");
}
/// A custom thumbnail size outside its range is clamped into it, so a row is drawn at the nearest size it takes.
#[trial]
fn a_custom_thumbnail_size_is_clamped_to_its_range() {
use craft_ui::list::{ThumbPoints, ThumbSize};
assert_eq!(ThumbPoints::new(0).get(), ThumbPoints::MIN, "below the range is the least size");
assert_eq!(ThumbPoints::from(u16::MAX).get(), ThumbPoints::MAX, "above the range is the largest size");
let (least, ..) = thumb_row(ThumbSize::Custom(ThumbPoints::new(1)));
let (most, ..) = thumb_row(ThumbSize::Custom(ThumbPoints::new(u16::MAX)));
assert_eq!(most.height(), f32::from(ThumbPoints::MAX), "the tallest row is the largest size: {most:?}");
let (at_least, ..) = thumb_row(ThumbSize::Custom(ThumbPoints::new(ThumbPoints::MIN)));
assert_eq!(least.height(), at_least.height(), "a size below the range draws as the least size: {least:?}");
let (small, ..) = thumb_row(ThumbSize::Small);
assert!(least.height() < small.height(), "the least size is shorter than a small thumbnail's row: {least:?} {small:?}");
}
/// The named thumbnail sizes keep their rows: without a thumbnail a row is a plain row's height, and with one it is the
/// token side with the thumbnail padding, at least a thumbnail row's least height.
#[trial]
fn the_named_thumbnail_sizes_keep_their_row_heights() {
use craft_ui::list::ThumbSize;
let plain = row_rects(RowHeight::Control)[0];
let (none, ..) = thumb_row(ThumbSize::None);
assert_eq!(none.height(), plain.height(), "no thumbnail keeps a plain row: {none:?} {plain:?}");
for (at, size) in [ThumbSize::Small, ThumbSize::Medium, ThumbSize::Large].into_iter().enumerate() {
let (row, thumb, sides, pad, least) = thumb_row(size);
assert_eq!(row.height(), (sides[at] + pad).max(least), "{size:?} keeps its row height: {row:?}");
assert_eq!(thumb.height(), sides[at], "{size:?} keeps its token side: {thumb:?}");
}
}
/// The text the rename field of `row` opens with.
fn opened_with(draft: fn(&usize) -> Option<String>, row: usize) -> Option<String> {
let (mut fixture, seen) = rig(draft);