mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 22:14:30 +00:00
Clippy and test-target lints: redundant must_use, type aliases for complex types, boxed large variants, argument structs, struct-update initialisers, deprecated egui calls, unused imports and dead code; the swatch library's reorder test runs as a trial
This commit is contained in:
@@ -20,7 +20,7 @@ use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::screenshot::{Captures, DocumentId, Finished, screenshot_reply};
|
||||
use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotRequest, screenshot_reply};
|
||||
use crate::synthetic::TARGET_CHANGED;
|
||||
|
||||
/// A reply: the JSON object the transport writes as one line.
|
||||
@@ -198,7 +198,7 @@ impl ControlChannel {
|
||||
Reply::AfterInput => self.input_waiters.push(reply),
|
||||
Reply::AfterJob(job) => self.job_waiters.push((job, reply)),
|
||||
Reply::Screenshot { token, path, viewport } => {
|
||||
if let Err((reply, e)) = self.captures.admit(token, path, viewport, reply, document, settle_ms, motion::now()) {
|
||||
if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) {
|
||||
let _ = reply.send(json!({"ok": false, "error": e}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,6 +191,22 @@ impl Finished {
|
||||
}
|
||||
}
|
||||
|
||||
/// A screenshot request as the control surface received it.
|
||||
pub struct ScreenshotRequest {
|
||||
/// The caller's token: one per pending request.
|
||||
pub token: u64,
|
||||
/// Where to write the PNG, when the reply is a file.
|
||||
pub path: Option<String>,
|
||||
/// The viewport to capture.
|
||||
pub viewport: ViewportId,
|
||||
/// Where the reply goes.
|
||||
pub reply: Sender<ControlResponse>,
|
||||
/// The document the capture belongs to.
|
||||
pub document: Option<DocumentId>,
|
||||
/// The settle delay in milliseconds of animation time.
|
||||
pub settle_ms: f64,
|
||||
}
|
||||
|
||||
/// A request not yet queued: it waits while its viewport's geometry is not recorded.
|
||||
struct WaitingAdmit {
|
||||
token: u64,
|
||||
@@ -290,16 +306,8 @@ impl Captures {
|
||||
/// expected bytes / 1 MiB, integer division), or
|
||||
/// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`.
|
||||
/// While the viewport's geometry is not recorded the request waits.
|
||||
pub fn admit(
|
||||
&mut self,
|
||||
token: u64,
|
||||
path: Option<String>,
|
||||
viewport: ViewportId,
|
||||
reply: Sender<ControlResponse>,
|
||||
document: Option<DocumentId>,
|
||||
settle_ms: f64,
|
||||
now: Instant,
|
||||
) -> Result<(), (Sender<ControlResponse>, String)> {
|
||||
pub fn admit(&mut self, request: ScreenshotRequest, now: Instant) -> Result<(), (Sender<ControlResponse>, String)> {
|
||||
let ScreenshotRequest { token, path, viewport, reply, document, settle_ms } = request;
|
||||
if self.records.iter().any(|r| r.token == token) || self.waiting.iter().any(|w| w.token == token) {
|
||||
return Err((reply, format!("screenshot token {token} is already pending")));
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::time::{Duration, Instant};
|
||||
use craft_automation::control::ControlResponse;
|
||||
use craft_automation::screenshot::{
|
||||
CaptureGeometry, Captures, DEADLINE, DocumentId, Finished, MAX_IMAGE_BYTES, MAX_PENDING, MAX_RETRIES, MAX_TOTAL_BYTES, SETTLE_PASSES,
|
||||
WINDOW_CLOSED,
|
||||
ScreenshotRequest, WINDOW_CLOSED,
|
||||
};
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
@@ -39,7 +39,7 @@ fn admit_for(
|
||||
now: Instant,
|
||||
) -> Result<Receiver<ControlResponse>, String> {
|
||||
let (tx, rx) = channel();
|
||||
captures.admit(token, None, viewport, tx, document, 0.0, now).map(|()| rx).map_err(|(_, e)| e)
|
||||
captures.admit(ScreenshotRequest { token, path: None, viewport, reply: tx, document, settle_ms: 0.0 }, now).map(|()| rx).map_err(|(_, e)| e)
|
||||
}
|
||||
|
||||
fn admit(captures: &mut Captures, token: u64, now: Instant) -> Result<Receiver<ControlResponse>, String> {
|
||||
|
||||
@@ -285,7 +285,7 @@ impl OutlineDraft {
|
||||
}
|
||||
|
||||
/// The pointer moved to `at` with the button up: only the rubber band follows, to where a click would place the
|
||||
/// point ([`shift_step`](Self::shift_step)); hover moves never become vertices. [`DraftEvent::Changed`] while an outline is open.
|
||||
/// point (`shift_step`); hover moves never become vertices. [`DraftEvent::Changed`] while an outline is open.
|
||||
pub fn hover(&mut self, at: DraftPoint) -> Option<DraftEvent> {
|
||||
if !self.is_open() || !at.at.x.is_finite() || !at.at.y.is_finite() {
|
||||
return None;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::{EyedropperBar, EyedropperOptions, SampleSize, SampleSizeSelect};
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, ShowContainer as _};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
|
||||
@@ -65,8 +65,8 @@ impl<P> Outcome for GradientEditorOutput<P> {
|
||||
|
||||
/// Edits a gradient's stops: `GradientEditor::new("Gradient", Bind::bound(&mut stops)).show(ui)`.
|
||||
///
|
||||
/// The bar fills the width offered. [`StopRows::Split`] rows, top to bottom: opacity markers (their midpoints just
|
||||
/// above the ramp), the ramp, the colour midpoints, colour markers; [`StopRows::Combined`]: the midpoints, the ramp,
|
||||
/// The bar fills the width offered. [`StopRows::Split`](crate::gradient::StopRows::Split) rows, top to bottom: opacity markers (their midpoints just
|
||||
/// above the ramp), the ramp, the colour midpoints, colour markers; [`StopRows::Combined`](crate::gradient::StopRows::Combined): the midpoints, the ramp,
|
||||
/// colour markers. The bar keeps its geometry right to left: the ramp is the gradient, not reading order.
|
||||
///
|
||||
/// Pointer: a press on a marker or diamond selects and grabs it without a jump; a drag moves it (stops pass their
|
||||
|
||||
@@ -5,7 +5,7 @@ use craft_ui::runtime::requests::ColorRequest;
|
||||
use crate::gradient::StopRow;
|
||||
|
||||
/// A marker of the stop bar: a colour stop, an opacity stop, or the midpoint after stop `i` of a
|
||||
/// row. Indices are into the stops as the bar shows them ([`GradientStops::opacity_stops`] for
|
||||
/// row. Indices are into the stops as the bar shows them ([`GradientStops::opacity_stops`](crate::gradient::GradientStops::opacity_stops) for
|
||||
/// the opacity row).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -105,14 +105,12 @@ impl<'a> ColorHud<'a> {
|
||||
|
||||
/// The colour under `at` when the host's press began; the popover is placed so this colour's point sits at `at`.
|
||||
/// Without it the area's middle sits at `at`.
|
||||
#[must_use]
|
||||
pub fn start(mut self, color: Srgba) -> Self {
|
||||
self.start = Some(color);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the host's press is still held.
|
||||
#[must_use]
|
||||
pub fn held(mut self, held: bool) -> Self {
|
||||
self.held = held;
|
||||
self
|
||||
|
||||
@@ -504,7 +504,7 @@ impl Component for PaintChip<'_> {
|
||||
shown.picked = recent.edit.as_ref().and_then(|edit| edit.value()).copied();
|
||||
}
|
||||
if let Some((groups, state)) = swatches.as_mut() {
|
||||
let groups: &[SwatchGroup] = *groups;
|
||||
let groups: &[SwatchGroup] = groups;
|
||||
let rows = swatch_rows(groups, &swatch_words);
|
||||
let colors: HashMap<&str, &SwatchColor> =
|
||||
groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect();
|
||||
|
||||
@@ -480,7 +480,7 @@ impl SwatchLibrary {
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
self.add(color.clone(), Some(name), group).is_some()
|
||||
self.add(*color, Some(name), group).is_some()
|
||||
}
|
||||
SwatchEdit::NewGroup { name } => self.new_group(name).is_some(),
|
||||
SwatchEdit::Rename { swatch, name } => self.find(swatch).is_some_and(|at| self.rename(at, name)),
|
||||
@@ -545,13 +545,14 @@ pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetR
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
fn group(name: &str, entries: &[&str]) -> SwatchGroup {
|
||||
SwatchGroup { name: name.to_owned(), entries: entries.iter().map(|n| SwatchEntry::new((*n).to_owned(), SwatchColor::Gray(0.5))).collect() }
|
||||
}
|
||||
|
||||
/// Edits that move several items down or up give the order the browser's own reorder gives.
|
||||
#[test]
|
||||
#[trial]
|
||||
fn multi_item_moves_apply_as_the_reorder_does() {
|
||||
let library = SwatchLibrary::new(vec![group("G", &["A", "B", "C", "D"]), group("H", &["E"])]);
|
||||
let swatch = |n: &str| SwatchKey::Swatch(n.to_owned());
|
||||
|
||||
@@ -266,7 +266,7 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
|
||||
let blue = SwatchColor::Rgb([0.0, 0.0, 1.0]);
|
||||
let entry = |name: &str, color: SwatchColor| craft_color::palette::SwatchEntry::new(name.to_owned(), color);
|
||||
let groups = vec![
|
||||
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red", red.clone()), entry("Color Swatch 1", blue.clone())] },
|
||||
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red", red), entry("Color Swatch 1", blue)] },
|
||||
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Blue", blue)] },
|
||||
];
|
||||
let (mut fixture, edits) = swatches_rig(groups.clone());
|
||||
|
||||
@@ -330,7 +330,7 @@ impl StrokeStyle {
|
||||
let scale = self.dash_scale() * length_scale;
|
||||
let pattern: Vec<f64> = self.dashes.iter().map(|&d| f64::from(d) * scale).collect();
|
||||
// `!(x > y)` also refuses a NaN total.
|
||||
if !(pattern.iter().sum::<f64>() > MIN_RUN) {
|
||||
if pattern.iter().sum::<f64>().partial_cmp(&MIN_RUN) != Some(std::cmp::Ordering::Greater) {
|
||||
return path.clone();
|
||||
}
|
||||
let cut = match self.dash_align {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::{ArtboardBackground, ArtboardWords};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::Swatch;
|
||||
use craft_ui::contract::{Bind, Entry, Outcome, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::hash::Hash;
|
||||
|
||||
use craft_behavior::{EditEvents, IconId};
|
||||
use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetState};
|
||||
use craft_ui::runtime::drag::DropZone;
|
||||
|
||||
@@ -272,9 +272,12 @@ pub struct BrushPresetPicker<'a, K: Value + Eq + Hash> {
|
||||
opened_at: Option<(Pos2, Bind<'a, bool>)>,
|
||||
compact: bool,
|
||||
enabled: bool,
|
||||
app_rows: Option<Box<dyn FnOnce(&mut Ui) + 'a>>,
|
||||
app_rows: Option<AppRows<'a>>,
|
||||
}
|
||||
|
||||
/// The app's own rows of the picker's gear menu.
|
||||
type AppRows<'a> = Box<dyn FnOnce(&mut Ui) + 'a>;
|
||||
|
||||
impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
|
||||
/// A picker named `label` over the presets in `rows` (build each with [`brush_row`](super::brush_row)), holding the
|
||||
/// preset the brush was picked from in `current`, its view in `state` and the brush's `values`.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use super::bar_words::CropBarWords;
|
||||
use super::options::{CROP_RATIOS, CROP_SIZES, CropPresetChoice, CropRatio, CropSizeFields};
|
||||
use super::{CropDocument, CropRatioChange, CropSettings, CropUserPreset};
|
||||
use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _};
|
||||
use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Show as _};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Units};
|
||||
use egui::{Response, Ui};
|
||||
|
||||
@@ -487,7 +487,7 @@ impl CropSession {
|
||||
self.dismissed = None;
|
||||
}
|
||||
|
||||
/// The frame the last [`reset`](Self::reset) made, while no other step replaced it.
|
||||
/// The frame the last `reset` made, while no other step replaced it.
|
||||
pub fn reset_to(&self) -> Option<CropBox> {
|
||||
self.reset_to
|
||||
}
|
||||
|
||||
@@ -32,11 +32,11 @@ impl GradientStyle {
|
||||
/// The style's name.
|
||||
pub fn label(self, words: &GradientFillWords) -> Label {
|
||||
match self {
|
||||
GradientStyle::Linear => words.linear.clone().into(),
|
||||
GradientStyle::Radial => words.radial.clone().into(),
|
||||
GradientStyle::Angle => words.angle_style.clone().into(),
|
||||
GradientStyle::Reflected => words.reflected.clone().into(),
|
||||
GradientStyle::Diamond => words.diamond.clone().into(),
|
||||
GradientStyle::Linear => words.linear.clone(),
|
||||
GradientStyle::Radial => words.radial.clone(),
|
||||
GradientStyle::Angle => words.angle_style.clone(),
|
||||
GradientStyle::Reflected => words.reflected.clone(),
|
||||
GradientStyle::Diamond => words.diamond.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::{EraserMode, PaintBar, PaintTool, PaintValues};
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::contract::{Entry, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Entry, ShowContainer as _};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
|
||||
@@ -31,7 +31,9 @@ pub enum ShapePaint {
|
||||
|
||||
/// The app's decoration of a paint chip (the Gradient, Pattern and Picture editors), which also shows it, so the
|
||||
/// decoration's borrows of app state last only for the call.
|
||||
pub struct ChipSetup<'a>(Box<dyn for<'b> FnMut(ShapePaint, PaintChip<'b>, &mut Ui) -> PaintChipOutput + 'a>);
|
||||
pub struct ChipSetup<'a>(SetupFn<'a>);
|
||||
|
||||
type SetupFn<'a> = Box<dyn for<'b> FnMut(ShapePaint, PaintChip<'b>, &mut Ui) -> PaintChipOutput + 'a>;
|
||||
|
||||
impl<'a> ChipSetup<'a> {
|
||||
pub(super) fn new(setup: impl for<'b> FnMut(ShapePaint, PaintChip<'b>, &mut Ui) -> PaintChipOutput + 'a) -> Self {
|
||||
|
||||
@@ -55,7 +55,10 @@ impl CanvasTool for Driven {
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(placing: Option<Size>) -> (ToolFixture<Driven>, Rc<Cell<Option<Size>>>, Rc<RefCell<Vec<ArtboardEvent>>>) {
|
||||
/// The fixture, the size being placed and the events the tool raised.
|
||||
type Shown = (ToolFixture<Driven>, Rc<Cell<Option<Size>>>, Rc<RefCell<Vec<ArtboardEvent>>>);
|
||||
|
||||
fn shown(placing: Option<Size>) -> Shown {
|
||||
let placing = Rc::new(Cell::new(placing));
|
||||
let log = Rc::new(RefCell::new(Vec::new()));
|
||||
let driven = Driven { tool: ArtboardTool::new(), placing: Rc::clone(&placing), log: Rc::clone(&log) };
|
||||
|
||||
@@ -248,7 +248,7 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
|
||||
};
|
||||
st.view = Some(view);
|
||||
let selection = st.selection.clone();
|
||||
let canvas_id = ui.id().with("document canvas");
|
||||
let canvas_id = ui.scope_id().with("document canvas");
|
||||
let canvas = Canvas::new("Document").id(canvas_id).view(view);
|
||||
let canvas = if st.pans { canvas.document(Size::new(4000.0, 4000.0)) } else { canvas };
|
||||
let canvas = canvas.show(ui, |ui, body| {
|
||||
|
||||
@@ -27,12 +27,13 @@ fn document(width: f64, height: f64, resolution: f64) -> CropDocument {
|
||||
}
|
||||
|
||||
fn fields(width: Option<(f64, UnitKind)>, height: Option<(f64, UnitKind)>, resolution: &str, unit: ResolutionUnit) -> CropSizeFields {
|
||||
let mut fields = CropSizeFields::default();
|
||||
fields.width = width.map(|(value, unit)| CropLength::new(value, unit));
|
||||
fields.height = height.map(|(value, unit)| CropLength::new(value, unit));
|
||||
fields.resolution = resolution.to_owned();
|
||||
fields.resolution_unit = unit;
|
||||
fields
|
||||
CropSizeFields {
|
||||
width: width.map(|(value, unit)| CropLength::new(value, unit)),
|
||||
height: height.map(|(value, unit)| CropLength::new(value, unit)),
|
||||
resolution: resolution.to_owned(),
|
||||
resolution_unit: unit,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn near(value: Option<f64>, expected: f64) -> bool {
|
||||
@@ -71,8 +72,7 @@ fn size_targets_convert_units_and_perspective_limits_round_inward() {
|
||||
assert!(zero.width.is_none() && zero.height.is_none(), "{zero:?}");
|
||||
|
||||
// The settings' target needs the W × H × Resolution mode and both sides.
|
||||
let mut settings = CropSettings::default();
|
||||
settings.size = fields(inch(4.0), inch(5.0), "300", ResolutionUnit::PixelsPerInch);
|
||||
let mut settings = CropSettings { size: fields(inch(4.0), inch(5.0), "300", ResolutionUnit::PixelsPerInch), ..Default::default() };
|
||||
assert!(settings.target(&doc, &postscript).is_none(), "a ratio that is not W x H x Resolution has no target");
|
||||
settings.ratio = CropRatio::Size;
|
||||
let target = settings.target(&doc, &postscript).expect("both sides");
|
||||
@@ -87,8 +87,7 @@ fn size_targets_convert_units_and_perspective_limits_round_inward() {
|
||||
assert_eq!(per_inch.resolution, "29999.999");
|
||||
assert_eq!(per_inch.width, Some(CropLength::new(800.0, UnitKind::Pixels)));
|
||||
assert_eq!(per_inch.height, Some(CropLength::new(600.0, UnitKind::Pixels)));
|
||||
let mut per_cm = CropSizeFields::default();
|
||||
per_cm.resolution_unit = ResolutionUnit::PixelsPerCentimetre;
|
||||
let mut per_cm = CropSizeFields { resolution_unit: ResolutionUnit::PixelsPerCentimetre, ..Default::default() };
|
||||
per_cm.front_image(&high, Some((0.394, 11_811.023)));
|
||||
assert_eq!(per_cm.resolution, "11811.023", "30000 / 2.54 rounds to 11811.024, past the limit");
|
||||
assert!(per_cm.resolution_ppi().is_some_and(|ppi| ppi <= 29_999.999), "the stored value converts back inside the limit");
|
||||
|
||||
@@ -189,7 +189,7 @@ impl Rig {
|
||||
|
||||
/// The turn of the view the canvas shows, in degrees; `None` before the tool set one.
|
||||
fn view_turn(&self) -> Option<f64> {
|
||||
self.host.borrow().view.map(|view| f64::from(view.rotation))
|
||||
self.host.borrow().view.map(|view| view.rotation)
|
||||
}
|
||||
|
||||
fn drag(&mut self, from: (f64, f64), to: (f64, f64)) {
|
||||
@@ -277,7 +277,7 @@ fn leaving_during_a_drag_ends_it_at_its_last_frame_and_applies() {
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_default_frame_fits_the_ratio_follows_the_selection_and_hides_after_discard() {
|
||||
fn the_default_frame_fits_the_ratio_and_follows_the_selection() {
|
||||
// A new default frame fits the saved ratio about its centre.
|
||||
let mut square = classic();
|
||||
square.ratio = CropRatio::sides(1.0, 1.0);
|
||||
@@ -304,7 +304,11 @@ fn the_default_frame_fits_the_ratio_follows_the_selection_and_hides_after_discar
|
||||
assert_eq!(tool.frame(), Some(upright(50.0, 0.0, 350.0, 300.0)), "the ratio fits the canvas, not the selection");
|
||||
assert!(!tool.session().from_selection() && !tool.shows_selection_entry(&ratio) && !tool.session().applies());
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_default_frame_takes_no_box_step_and_hides_after_discard() {
|
||||
let selection = Rect::new(100.0, 50.0, 300.0, 250.0);
|
||||
// X on a square default frame makes no box step.
|
||||
let mut rig = Rig::new(classic());
|
||||
rig.host.borrow_mut().document = CropDocument::new(CropDocKey::new(3), Size::new(300.0, 300.0), 72.0);
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::rc::Rc;
|
||||
use craft_behavior::EditEvent;
|
||||
use craft_draw::ui::{EraserMode, MIXER_COMBINATIONS, PaintBar, PaintTool, PaintValues};
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::contract::{Entry, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Entry, ShowContainer as _};
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::{Fixture, Room, trial};
|
||||
|
||||
@@ -36,8 +36,7 @@ impl Rig {
|
||||
let mut tool = shown.borrow_mut();
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let view = CanvasView::new(room, Point::new(200.0, 150.0), 1.0);
|
||||
let mut input = PerspectiveInput::default();
|
||||
input.document = active.get();
|
||||
let input = PerspectiveInput { document: active.get(), ..Default::default() };
|
||||
let mut pass = tool.pass(input);
|
||||
let canvas = Canvas::new("Document").document(SIZE).view(view).show(ui, |ui, body| {
|
||||
let _ = pass.show_quad(ui, body.rect);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use craft_behavior::EditEvent;
|
||||
use craft_color::ui::Paint;
|
||||
use craft_draw::ui::{Arrowheads, ArrowheadsPopover, LiveShape, ShapeAppearance, ShapeChange, ShapePanel};
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::vec2;
|
||||
use std::cell::RefCell;
|
||||
|
||||
@@ -35,10 +35,13 @@ fn drawn(events: &[SliceEvent]) -> Option<Rect> {
|
||||
/// A new slice is rounded by its style: Fixed Ratio keeps the ratio on whole pixels and a click makes none; Fixed Size
|
||||
/// is exactly its pixels on the press's pixel, drawn up and left too, and a click makes it; a Normal drag no wider
|
||||
/// and no taller than two pixels is a click that selects.
|
||||
/// A style case: its name, constraint, drag start, drag delta and the slice it draws.
|
||||
type StyleCase = (&'static str, Constraint, (f64, f64), (f32, f32), Option<Rect>);
|
||||
|
||||
#[trial]
|
||||
fn a_slice_is_drawn_by_its_style() {
|
||||
// Starts have a fractional part so that float noise in the pointer's position cannot move a pixel edge.
|
||||
let cases: [(&str, Constraint, (f64, f64), (f32, f32), Option<Rect>); 6] = [
|
||||
let cases: [StyleCase; 6] = [
|
||||
("Fixed Ratio 2:1 from a 20.8 px drag", Constraint::Ratio(2.0, 1.0), (50.5, 50.5), (20.8, 0.0), Some(Rect::new(50.0, 50.0, 71.0, 61.0))),
|
||||
("Fixed Ratio click", Constraint::Ratio(2.0, 1.0), (50.5, 50.5), (0.0, 0.0), None),
|
||||
("Fixed Size drawn up and left", Constraint::Size(20.0, 10.0), (60.4, 60.6), (-5.0, -5.0), Some(Rect::new(41.0, 51.0, 61.0, 61.0))),
|
||||
@@ -109,9 +112,12 @@ enum Outcome {
|
||||
|
||||
/// A drag of a user slice moves it by whole pixels (a `Move` from `Begin` to `Commit`); a corner and an edge handle
|
||||
/// move only their edges and never empty the slice; a press on an auto or layer slice only selects.
|
||||
/// A move case: its name, the user slice grabbed, drag start, drag delta and the outcome.
|
||||
type MoveCase = (&'static str, Option<usize>, (f64, f64), (f32, f32), Outcome);
|
||||
|
||||
#[trial]
|
||||
fn user_slices_move_and_resize_and_other_slices_only_select() {
|
||||
let cases: [(&str, Option<usize>, (f64, f64), (f32, f32), Outcome); 6] = [
|
||||
let cases: [MoveCase; 6] = [
|
||||
("move by whole pixels", Some(1), (90.0, 80.0), (13.3, 7.6), Outcome::Moved(Rect::new(53.0, 48.0, 153.0, 128.0))),
|
||||
("corner handle", Some(1), (140.0, 120.0), (10.0, 6.0), Outcome::Resized(Rect::new(40.0, 40.0, 150.0, 126.0))),
|
||||
("edge handle", Some(1), (140.0, 80.0), (-30.0, 25.0), Outcome::Resized(Rect::new(40.0, 40.0, 110.0, 120.0))),
|
||||
|
||||
@@ -132,7 +132,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
|
||||
host.view = view;
|
||||
host.state
|
||||
};
|
||||
let canvas_id = ui.id().with("document canvas");
|
||||
let canvas_id = ui.scope_id().with("document canvas");
|
||||
let mut canvas = Canvas::new("Document").id(canvas_id).view(view);
|
||||
if config.snap {
|
||||
canvas = canvas.snap(snap.clone());
|
||||
|
||||
@@ -17,6 +17,9 @@ use serde::de::DeserializeOwned;
|
||||
|
||||
use super::{AdjustContext, LevelsClip, TonePicker};
|
||||
|
||||
/// The target a reset aims for, from the current and the opening value.
|
||||
type ResetWith<V> = Box<dyn Fn(&V, &V) -> V + Send>;
|
||||
|
||||
/// The phase of the editor's edit this pass, mirroring [`craft_behavior::EditEvent`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
@@ -105,7 +108,7 @@ pub struct HostedAdjustDialog<V, E = ()> {
|
||||
resizable: bool,
|
||||
remember: Option<SaveKey>,
|
||||
canvas: Option<egui::Id>,
|
||||
reset_with: Option<Box<dyn Fn(&V, &V) -> V + Send>>,
|
||||
reset_with: Option<ResetWith<V>>,
|
||||
picker: Option<TonePicker>,
|
||||
channel: usize,
|
||||
clipping: Option<LevelsClip>,
|
||||
|
||||
@@ -57,7 +57,6 @@ impl<'a> AdjustmentsPanel<'a> {
|
||||
}
|
||||
|
||||
/// Offers only `kinds`, in that order.
|
||||
#[must_use]
|
||||
pub fn kinds(mut self, kinds: &'a [AdjustmentKind]) -> Self {
|
||||
self.kinds = kinds;
|
||||
self
|
||||
|
||||
@@ -41,7 +41,6 @@ impl<'a> BlurPinsPanel<'a> {
|
||||
/// Inside a modal body, declares the canvas gesture each pass, so the pins on the canvas keep their presses while
|
||||
/// the Blur Gallery dialog is modal. The pins take presses and drags at any time, so the pass-through is
|
||||
/// [`CanvasGesture::PRIMARY`] whenever the panel is shown.
|
||||
#[must_use]
|
||||
pub fn canvas(mut self, canvas: egui::Id) -> Self {
|
||||
self.canvas = Some(canvas);
|
||||
self
|
||||
|
||||
@@ -14,7 +14,7 @@ use craft_ui::contract::{
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::list::{List, RowEvent, ThumbSize};
|
||||
use craft_ui::primitives::textures::{ThumbSource, Thumbnails};
|
||||
use craft_ui::runtime::commands::{CommandState, Commands as _};
|
||||
use craft_ui::runtime::commands::Commands as _;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::memory::Remember as _;
|
||||
use egui::Ui;
|
||||
|
||||
@@ -129,18 +129,9 @@ impl Pass {
|
||||
}
|
||||
|
||||
/// A whole-number slider row over `range`, enabled or not.
|
||||
fn slider(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
label: &Label,
|
||||
value: f64,
|
||||
range: RangeInclusive<f64>,
|
||||
percent: bool,
|
||||
enabled: bool,
|
||||
set: fn(&mut ColorRangeValue, f64),
|
||||
) {
|
||||
let mut field = SliderField::new(label.clone(), Bind::given(value), range).step(1.0).enabled(enabled);
|
||||
if percent {
|
||||
fn slider(&mut self, ui: &mut Ui, label: &Label, value: f64, scale: Scale, enabled: bool, set: fn(&mut ColorRangeValue, f64)) {
|
||||
let mut field = SliderField::new(label.clone(), Bind::given(value), scale.range).step(1.0).enabled(enabled);
|
||||
if scale.percent {
|
||||
field = field.unit_kind(UnitKind::Percent);
|
||||
}
|
||||
let events = field.show(ui).events;
|
||||
@@ -148,6 +139,22 @@ impl Pass {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a slider row reads: its range and whether the value shows as a percentage.
|
||||
struct Scale {
|
||||
range: RangeInclusive<f64>,
|
||||
percent: bool,
|
||||
}
|
||||
|
||||
impl Scale {
|
||||
fn percent(range: RangeInclusive<f64>) -> Self {
|
||||
Scale { range, percent: true }
|
||||
}
|
||||
|
||||
fn plain(range: RangeInclusive<f64>) -> Self {
|
||||
Scale { range, percent: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pass of the body gathered for the output.
|
||||
struct Collected {
|
||||
events: EditEvents<ColorRangeValue>,
|
||||
@@ -249,24 +256,24 @@ impl<'a> ColorRangeDialog<'a> {
|
||||
let events = Checkbox::new(Bind::given(now.localized)).label(words.localized.clone()).enabled(c.sampling).show(ui).events;
|
||||
pass.lift(events, |value, on| value.localized = on);
|
||||
if c.tonal {
|
||||
pass.slider(ui, &words.fuzziness, now.tone_fuzziness, 0.0..=100.0, true, c.fuzziness, |v, x| v.tone_fuzziness = x);
|
||||
pass.slider(ui, &words.fuzziness, now.tone_fuzziness, Scale::percent(0.0..=100.0), c.fuzziness, |v, x| v.tone_fuzziness = x);
|
||||
} else {
|
||||
pass.slider(ui, &words.fuzziness, now.fuzziness, 0.0..=200.0, false, c.fuzziness, |v, x| v.fuzziness = x);
|
||||
pass.slider(ui, &words.fuzziness, now.fuzziness, Scale::plain(0.0..=200.0), c.fuzziness, |v, x| v.fuzziness = x);
|
||||
}
|
||||
if c.range {
|
||||
pass.slider(ui, &words.range, now.range, 0.0..=100.0, true, true, |v, x| v.range = x);
|
||||
pass.slider(ui, &words.range, now.range, Scale::percent(0.0..=100.0), true, |v, x| v.range = x);
|
||||
}
|
||||
if c.tonal {
|
||||
match now.select {
|
||||
ColorRangeSelect::Shadows => {
|
||||
pass.slider(ui, &words.shadows_up_to, now.shadows_level, 0.0..=255.0, false, true, |v, x| v.shadows_level = x);
|
||||
pass.slider(ui, &words.shadows_up_to, now.shadows_level, Scale::plain(0.0..=255.0), true, |v, x| v.shadows_level = x);
|
||||
}
|
||||
ColorRangeSelect::Highlights => {
|
||||
pass.slider(ui, &words.highlights_from, now.highlights_level, 0.0..=255.0, false, true, |v, x| v.highlights_level = x);
|
||||
pass.slider(ui, &words.highlights_from, now.highlights_level, Scale::plain(0.0..=255.0), true, |v, x| v.highlights_level = x);
|
||||
}
|
||||
_ => {
|
||||
pass.slider(ui, &words.midtones_from, now.midtones_low, 0.0..=255.0, false, true, |v, x| v.midtones_low = x);
|
||||
pass.slider(ui, &words.midtones_to, now.midtones_high, 0.0..=255.0, false, true, |v, x| v.midtones_high = x);
|
||||
pass.slider(ui, &words.midtones_from, now.midtones_low, Scale::plain(0.0..=255.0), true, |v, x| v.midtones_low = x);
|
||||
pass.slider(ui, &words.midtones_to, now.midtones_high, Scale::plain(0.0..=255.0), true, |v, x| v.midtones_high = x);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The Styles page: the host's style presets in a [`PresetBrowser`] grid.
|
||||
|
||||
use craft_theme::TypeRole;
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _};
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetRow, PresetState, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
|
||||
@@ -98,7 +98,7 @@ impl LivePreview {
|
||||
|
||||
/// [`key`](Self::key), recording `area` (document pixels) as what the preview of this key changes, so
|
||||
/// [`switch`](Self::switch) recomposites only that: a tool's preview that changes a small part of the region
|
||||
/// (Patch heals around one offset). The last [`AREA_KEYS`] keys keep their area; an older key falls back to the
|
||||
/// (Patch heals around one offset). The last `AREA_KEYS` keys keep their area; an older key falls back to the
|
||||
/// region, which damages more, never less.
|
||||
pub fn key_in(&mut self, settings: u64, now: f64, area: PixelRect) -> PreviewKey {
|
||||
let key = self.key(settings, now);
|
||||
|
||||
@@ -11,6 +11,13 @@ use super::controls::{GRADING_TAIL, Rows, section};
|
||||
use super::words::RawDevelopWords;
|
||||
use crate::raw::{GradeWheel, RawDevelopSettings};
|
||||
|
||||
/// Reads a band's value of a tab from the settings.
|
||||
type BandGet = fn(&RawDevelopSettings, usize) -> f32;
|
||||
/// Writes a band's value of a tab into the settings.
|
||||
type BandSet = fn(&mut RawDevelopSettings, usize, f32);
|
||||
/// A band's word.
|
||||
type BandWord = fn(&RawDevelopWords) -> &Label;
|
||||
|
||||
/// The Color Mixer's tabs: the band property a row edits.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
enum MixerTab {
|
||||
@@ -21,7 +28,7 @@ enum MixerTab {
|
||||
|
||||
impl MixerTab {
|
||||
/// Reads and writes the tab's value of band `k`.
|
||||
fn accessors(self) -> (fn(&RawDevelopSettings, usize) -> f32, fn(&mut RawDevelopSettings, usize, f32)) {
|
||||
fn accessors(self) -> (BandGet, BandSet) {
|
||||
match self {
|
||||
MixerTab::Hue => (|s, k| s.hsl_hue[k], |s, k, v| s.hsl_hue[k] = v),
|
||||
MixerTab::Saturation => (|s, k| s.hsl_sat[k], |s, k, v| s.hsl_sat[k] = v),
|
||||
@@ -31,7 +38,7 @@ impl MixerTab {
|
||||
}
|
||||
|
||||
/// The eight bands: their word and the hue (degrees) their track is drawn around.
|
||||
const BANDS: [(fn(&RawDevelopWords) -> &Label, f32); 8] = [
|
||||
const BANDS: [(BandWord, f32); 8] = [
|
||||
(|w| &w.band_reds, 0.0),
|
||||
(|w| &w.band_oranges, 30.0),
|
||||
(|w| &w.band_yellows, 60.0),
|
||||
|
||||
@@ -173,7 +173,7 @@ impl RawDevelopOpen {
|
||||
#[non_exhaustive]
|
||||
pub enum RawDevelopEvent {
|
||||
/// The settings changed.
|
||||
Settings(EditEvent<RawDevelopSettings>),
|
||||
Settings(Box<EditEvent<RawDevelopSettings>>),
|
||||
/// A filmstrip pick: the app keeps the current raw's settings and calls `show_item`.
|
||||
Show(usize),
|
||||
/// Load Settings asks the app for a file.
|
||||
@@ -227,7 +227,7 @@ enum Footer {
|
||||
/// A change the passes ask of the workspace, applied after the dialog has been shown.
|
||||
enum Action {
|
||||
/// An edit of the settings from the panel or the scope's tone zones.
|
||||
Edit(EditEvent<RawDevelopSettings>),
|
||||
Edit(Box<EditEvent<RawDevelopSettings>>),
|
||||
/// The Auto button.
|
||||
Auto,
|
||||
/// A filmstrip pick.
|
||||
@@ -358,7 +358,7 @@ impl RawDevelopWorkspace {
|
||||
let event = EditEvent::set(Mixed::Same(self.settings.clone()), next.clone(), name, None);
|
||||
self.history.record(&event);
|
||||
self.settings = next;
|
||||
self.queued.push(RawDevelopEvent::Settings(event));
|
||||
self.queued.push(RawDevelopEvent::Settings(Box::new(event)));
|
||||
true
|
||||
}
|
||||
|
||||
@@ -382,7 +382,7 @@ impl RawDevelopWorkspace {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
RawDevelopEvent::Settings(event)
|
||||
RawDevelopEvent::Settings(Box::new(event))
|
||||
}
|
||||
|
||||
/// Steps the history and reports the step as a change of the settings named `name`.
|
||||
@@ -393,7 +393,7 @@ impl RawDevelopWorkspace {
|
||||
}
|
||||
self.diagnostic = None;
|
||||
let event = EditEvent::set(Mixed::Same(before), self.settings.clone(), name, None);
|
||||
Some(RawDevelopEvent::Settings(event))
|
||||
Some(RawDevelopEvent::Settings(Box::new(event)))
|
||||
}
|
||||
|
||||
/// The result the button `finish` answers.
|
||||
@@ -553,26 +553,26 @@ impl FullWindowWorkspace for RawDevelopWorkspace {
|
||||
let (at, has_selection) = (w.hover, source.has_selection());
|
||||
FullWindowSide::new(words.settings.clone()).show(ui, |ui, _| {
|
||||
let mut floating = floating_now;
|
||||
if let Some(state) = w.scope.as_mut() {
|
||||
if !floating_now {
|
||||
let region = state.settings.selected_region;
|
||||
let mut out = None;
|
||||
source.scope(before, region, at, &mut |frame| {
|
||||
let strip = RawScopeStrip::new(&mut *state, frame.as_ref(), Bind::given(settings.clone()))
|
||||
.floating(Bind::bound(&mut floating))
|
||||
.has_selection(has_selection)
|
||||
.show(ui);
|
||||
out = Some(strip);
|
||||
});
|
||||
// A source that shows no frame still gets its strip.
|
||||
let strip = out.unwrap_or_else(|| {
|
||||
RawScopeStrip::new(&mut *state, None, Bind::given(settings.clone()))
|
||||
.floating(Bind::bound(&mut floating))
|
||||
.has_selection(has_selection)
|
||||
.show(ui)
|
||||
});
|
||||
actions.borrow_mut().extend(strip.edit.events.into_iter().map(Action::Edit));
|
||||
}
|
||||
if let Some(state) = w.scope.as_mut()
|
||||
&& !floating_now
|
||||
{
|
||||
let region = state.settings.selected_region;
|
||||
let mut out = None;
|
||||
source.scope(before, region, at, &mut |frame| {
|
||||
let strip = RawScopeStrip::new(&mut *state, frame.as_ref(), Bind::given(settings.clone()))
|
||||
.floating(Bind::bound(&mut floating))
|
||||
.has_selection(has_selection)
|
||||
.show(ui);
|
||||
out = Some(strip);
|
||||
});
|
||||
// A source that shows no frame still gets its strip.
|
||||
let strip = out.unwrap_or_else(|| {
|
||||
RawScopeStrip::new(&mut *state, None, Bind::given(settings.clone()))
|
||||
.floating(Bind::bound(&mut floating))
|
||||
.has_selection(has_selection)
|
||||
.show(ui)
|
||||
});
|
||||
actions.borrow_mut().extend(strip.edit.events.into_iter().map(|event| Action::Edit(Box::new(event))));
|
||||
}
|
||||
let mut panel = RawDevelopPanel::new(Bind::given(settings.clone()).reset(original.clone()));
|
||||
if let Some(demosaic) = demosaic {
|
||||
@@ -580,7 +580,7 @@ impl FullWindowWorkspace for RawDevelopWorkspace {
|
||||
}
|
||||
let out = panel.show(ui);
|
||||
let mut queued = actions.borrow_mut();
|
||||
queued.extend(out.edit.events.into_iter().map(Action::Edit));
|
||||
queued.extend(out.edit.events.into_iter().map(|event| Action::Edit(Box::new(event))));
|
||||
if out.auto {
|
||||
queued.push(Action::Auto);
|
||||
}
|
||||
@@ -766,7 +766,7 @@ impl FullWindowWorkspace for RawDevelopWorkspace {
|
||||
);
|
||||
});
|
||||
if let Some(float) = out {
|
||||
actions.borrow_mut().extend(float.edit.events.into_iter().map(Action::Edit));
|
||||
actions.borrow_mut().extend(float.edit.events.into_iter().map(|event| Action::Edit(Box::new(event))));
|
||||
}
|
||||
}
|
||||
w.floating = floating;
|
||||
@@ -774,14 +774,13 @@ impl FullWindowWorkspace for RawDevelopWorkspace {
|
||||
});
|
||||
|
||||
let output = shown.output;
|
||||
drop(ws);
|
||||
let mut events = std::mem::take(&mut self.queued);
|
||||
for step in actions.borrow().iter().filter_map(|action| if let Action::Step(step) = action { Some(*step) } else { None }) {
|
||||
events.extend(self.step(step, Arc::from(words.name.as_str())));
|
||||
}
|
||||
for action in actions.into_inner() {
|
||||
match action {
|
||||
Action::Edit(event) => events.push(self.take_edit(event, alt)),
|
||||
Action::Edit(event) => events.push(self.take_edit(*event, alt)),
|
||||
Action::Auto => self.run_auto(source, Arc::from(words.auto.as_str())),
|
||||
Action::Show(index) => events.push(RawDevelopEvent::Show(index)),
|
||||
Action::Step(_) => {}
|
||||
|
||||
@@ -673,7 +673,6 @@ fn close_radius(cx: &ToolContext<'_>, place: &Place) -> f64 {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::MagneticSettings;
|
||||
|
||||
#[test]
|
||||
fn width_steps_by_one_and_shift_jumps_to_the_limits() {
|
||||
|
||||
@@ -264,7 +264,7 @@ impl Work<'_> {
|
||||
VanishingTool::Stamp => match self.stamp_press(p, mods, words) {
|
||||
Ok(pressed) => Some(pressed),
|
||||
Err(message) => {
|
||||
self.editor.status = Some(message);
|
||||
self.editor.status = Some(*message);
|
||||
Some(Pressed::Done)
|
||||
}
|
||||
},
|
||||
@@ -288,8 +288,8 @@ impl Work<'_> {
|
||||
}
|
||||
|
||||
/// Stamp's press: Alt sets the source, otherwise a stroke starts. `Err` is the message of a refused press.
|
||||
fn stamp_press(&mut self, p: [f64; 2], mods: Mods, words: &VanishingPointWords) -> Result<Pressed, StatusMessage> {
|
||||
let refused = |text: &Label| StatusMessage::new(text.clone()).tone(Tone::Warn);
|
||||
fn stamp_press(&mut self, p: [f64; 2], mods: Mods, words: &VanishingPointWords) -> Result<Pressed, Box<StatusMessage>> {
|
||||
let refused = |text: &Label| Box::new(StatusMessage::new(text.clone()).tone(Tone::Warn));
|
||||
if mods.alt {
|
||||
if !self.on_plane(p) {
|
||||
return Err(refused(&words.stamp_no_source));
|
||||
|
||||
@@ -201,13 +201,6 @@ pub enum CylinderHandle {
|
||||
Surface,
|
||||
}
|
||||
|
||||
impl CylinderHandle {
|
||||
/// The place of a handle with a part among [`HANDLES`]; `None` for the surface.
|
||||
fn index(self) -> Option<usize> {
|
||||
HANDLES.iter().position(|&handle| handle == self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The look of the cylinder editor: its lines in `overlay.line` over `overlay.halo`, the corners as handle squares and
|
||||
/// the other handles as small handle circles.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
@@ -302,10 +295,8 @@ impl<'a> CylinderWarp<'a> {
|
||||
cx.commit();
|
||||
}
|
||||
}
|
||||
PressPhase::Cancel { .. } => {
|
||||
if cx.press_slot::<Press>().take().is_some_and(|held| held.began) {
|
||||
cx.cancel(CancelReason::Escape);
|
||||
}
|
||||
PressPhase::Cancel { .. } if cx.press_slot::<Press>().take().is_some_and(|held| held.began) => {
|
||||
cx.cancel(CancelReason::Escape);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ fn a_seed_moves_the_reset_baseline() {
|
||||
|
||||
let slider = fixture.by_role(craft_ui::contract::Role::SLIDER).first().cloned().expect("the Brightness slider");
|
||||
fixture.drag(&slider, Vec2::new(slider.rect.width() / 4.0, 0.0)).settle();
|
||||
let value = |host: &Rc<RefCell<DialogHost>>| host.borrow().get::<Adjust>().map(|dialog| dialog.value().clone());
|
||||
let value = |host: &Rc<RefCell<DialogHost>>| host.borrow().get::<Adjust>().map(|dialog| *dialog.value());
|
||||
assert_ne!(value(&host), Some(seeded), "the drag edits the value");
|
||||
fixture.hold(Modifiers::ALT).idle(2);
|
||||
let reset = fixture.by_label("Reset").expect("Alt turns Cancel into Reset");
|
||||
|
||||
@@ -184,8 +184,7 @@ fn raw_develop_switches_raws_and_finishes_with_each_footer_button() {
|
||||
let events = host.borrow_mut().get_mut::<Hosted>().map(Hosted::take_events).unwrap_or_default();
|
||||
assert!(events.contains(&RawDevelopEvent::Show(1)), "a filmstrip pick reports Show(1): {events:?}");
|
||||
|
||||
let mut next = RawDevelopSettings::default();
|
||||
next.exposure = 0.5;
|
||||
let next = RawDevelopSettings { exposure: 0.5, ..Default::default() };
|
||||
host.borrow_mut().get_mut::<Hosted>().expect("open").workspace_mut().show_item(1, next.clone(), next, Some(Demosaic::Bilinear));
|
||||
fixture.idle(4);
|
||||
fixture.key(Key::Z, Modifiers::COMMAND).idle(4);
|
||||
@@ -308,8 +307,7 @@ fn a_tone_zone_drag_moves_exposure_from_where_it_started() {
|
||||
let mut fixture = fixture(&host, &rerun);
|
||||
host.borrow_mut().open(HostedWorkspace::new(RawDevelopWorkspace::new(open(RawTarget::Filter)), Source::with_histogram()));
|
||||
fixture.idle(10);
|
||||
let mut start = RawDevelopSettings::default();
|
||||
start.exposure = -2.0;
|
||||
let start = RawDevelopSettings { exposure: -2.0, ..Default::default() };
|
||||
host.borrow_mut().get_mut::<Hosted>().expect("open").workspace_mut().show_item(0, start.clone(), start, None);
|
||||
fixture.idle(4);
|
||||
|
||||
|
||||
@@ -318,6 +318,9 @@ fn near(got: [f64; 7], want: [f64; 7], what: &str) {
|
||||
assert!(got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-3), "{what}: {got:?} against {want:?}");
|
||||
}
|
||||
|
||||
/// A handle case: the handle's place, the drag in document units, the values after and the name.
|
||||
type HandleCase = ((f64, f64), (f32, f32), [f64; 7], &'static str);
|
||||
|
||||
#[trial]
|
||||
fn cylinder_handles_drag_their_values_and_keep_them_sound() {
|
||||
// RECT is 180 wide: the half axis is 90, the centre 190. Depths 0.5, wrap 0.85 (its handle 0.15 of the half axis out).
|
||||
@@ -325,7 +328,7 @@ fn cylinder_handles_drag_their_values_and_keep_them_sound() {
|
||||
let (top_right, bottom_left, bend, bottom, wrap, surface) =
|
||||
((280.0, 80.0), (100.0, 200.0), (190.0, 125.0), (190.0, 245.0), (203.5, 185.0), (130.0, 160.0));
|
||||
// (handle's place, the drag in document units, the values after)
|
||||
let cases: [((f64, f64), (f32, f32), [f64; 7], &str); 10] = [
|
||||
let cases: [HandleCase; 10] = [
|
||||
(top_right, (-30.0, 15.0), [100.0, 200.0, 250.0, 95.0, 0.5, 0.5, 0.85], "the top right corner takes its silhouette and its edge"),
|
||||
(bottom_left, (10.0, -20.0), [110.0, 180.0, 280.0, 80.0, 0.5, 0.5, 0.85], "the bottom left corner takes its silhouette and its edge"),
|
||||
(bend, (0.0, 9.0), [100.0, 200.0, 280.0, 80.0, 0.6, 0.6, 0.85], "Bend moves both depths by the drag over the half axis"),
|
||||
|
||||
@@ -302,7 +302,7 @@ fn an_option_click_runs_the_rows_alternate() {
|
||||
|
||||
let click = |mods: Mods| dispatch.chosen(&merge, Some(&shortcut), false, false, mods, Some(&alternate));
|
||||
assert_eq!(click(held([false, false, true, false])), Event::Click(stamp.clone()));
|
||||
assert_eq!(*seen.lock().unwrap(), [stamp.clone()], "the hook sees the alternate");
|
||||
assert_eq!(*seen.lock().unwrap(), std::slice::from_ref(&stamp), "the hook sees the alternate");
|
||||
assert_eq!(click(Mods::default()), Event::Click(merge.clone()), "no ⌥: the row's own command");
|
||||
assert_eq!(click(held([false, false, false, true])), Event::Click(merge.clone()), "another modifier is not the alternate's");
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ impl Lengths<'_> {
|
||||
}
|
||||
|
||||
/// The kerning field: a number or the name of a presets row (Metrics, Optical).
|
||||
pub(crate) fn kerning(
|
||||
pub(super) fn kerning(
|
||||
&self,
|
||||
ui: &mut Ui,
|
||||
label: Label,
|
||||
|
||||
@@ -13,7 +13,7 @@ use craft_ui::form::Field;
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::patterns::form_dialogs::HostRequests;
|
||||
use craft_ui::runtime::env::{Env, Label, WordTemplate};
|
||||
use craft_ui::text::{NumberPick, TextField};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use super::paragraph::{INDENT_RANGE, SPACE_RANGE};
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use super::{StyleAttribute, StyleOptionValues, TextStyleOptions};
|
||||
use crate::ui::character::{CharacterValues, Kerning, Leading, ParagraphValues, TextAlign};
|
||||
use craft_theme::Rgba;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
|
||||
@@ -440,6 +440,17 @@ fn char_at(lines: &[HostLine], pos: TextPos) -> usize {
|
||||
line.chars.start + line.text[..byte].chars().count()
|
||||
}
|
||||
|
||||
/// The clipboard's text when the pass's input asks to paste and the clipboard has it ready.
|
||||
fn pasted_text(cx: &mut Cx<'_, TextEditor<'_>>, inputs: &[EditorInput]) -> Option<std::sync::Arc<str>> {
|
||||
if !inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))) {
|
||||
return None;
|
||||
}
|
||||
match cx.clipboard().paste() {
|
||||
Pending::Ready(content) => content.text.clone(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for TextEditor<'_> {
|
||||
const ROLE: Role = Role::MULTILINE_TEXT_INPUT;
|
||||
const INPUT: craft_ui::contract::Input = craft_ui::contract::Input::Editor;
|
||||
@@ -485,14 +496,7 @@ impl Component for TextEditor<'_> {
|
||||
}
|
||||
let press = *cx.press();
|
||||
let now = cx.now();
|
||||
let pasted = if inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))) {
|
||||
match cx.clipboard().paste() {
|
||||
Pending::Ready(content) => content.text.clone(),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let pasted = pasted_text(cx, &inputs);
|
||||
let mut copied: Option<String> = None;
|
||||
let mut session = std::mem::take(cx.memory::<Session>());
|
||||
let mut edits = Edits {
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::ui::character::{CharacterValues, ParagraphValues, TextAlign};
|
||||
use crate::ui::type_options::{TextAntiAlias, TextOrientation};
|
||||
use craft_theme::Rgba;
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@ fn changes(edits: &RefCell<Vec<EditEvent<StyleOptionsChange>>>) -> Vec<StyleOpti
|
||||
|
||||
#[trial]
|
||||
fn a_row_left_out_of_the_style_takes_no_input_and_its_check_includes_it() {
|
||||
let mut character = CharacterValues::default();
|
||||
character.size = Some(12.0);
|
||||
let character = CharacterValues { size: Some(12.0), ..Default::default() };
|
||||
let values = StyleOptionValues::new("Emphasis", character);
|
||||
let edits = Rc::new(RefCell::new(Vec::new()));
|
||||
let sink = edits.clone();
|
||||
|
||||
@@ -10,6 +10,9 @@ use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
/// The selection the panel shows, the actions it reported and the warnings it raised.
|
||||
type PanelState = Rc<RefCell<(Selection<u64>, Vec<TextStyleAction>, usize)>>;
|
||||
|
||||
#[trial]
|
||||
fn a_click_applies_alt_clears_overrides_and_a_double_click_opens_options_except_on_none() {
|
||||
let state = Rc::new(RefCell::new((Selection::<u64>::default(), Vec::<TextStyleAction>::new())));
|
||||
@@ -58,7 +61,7 @@ fn every_attempt_to_apply_a_character_style_at_a_bare_caret_warns_and_applies_no
|
||||
*warnings += usize::from(out.status.is_some());
|
||||
});
|
||||
fixture.idle(10);
|
||||
let warnings = |state: &Rc<RefCell<(Selection<u64>, Vec<TextStyleAction>, usize)>>| std::mem::take(&mut state.borrow_mut().2);
|
||||
let warnings = |state: &PanelState| std::mem::take(&mut state.borrow_mut().2);
|
||||
|
||||
let emphasis = fixture.by_label("Emphasis").expect("the Emphasis row is shown");
|
||||
fixture.click(&emphasis).idle(4);
|
||||
|
||||
@@ -51,11 +51,11 @@ fn paint_frame(draw: &Draw<'_>, cx: &Cx<'_, CropOverlay<'_>>, scene: &Scene<'_,
|
||||
return;
|
||||
}
|
||||
let editing = scene.drag.is_some();
|
||||
if scene.started {
|
||||
if let Some(fill) = overlay.shield.fill_on(scene.space, style.canvas.egui(), editing) {
|
||||
let corners = [area.left_top(), area.right_top(), area.right_bottom(), area.left_bottom()];
|
||||
super::paint_outside(draw, corners, &q, DataColor::new(fill));
|
||||
}
|
||||
if scene.started
|
||||
&& let Some(fill) = overlay.shield.fill_on(scene.space, style.canvas.egui(), editing)
|
||||
{
|
||||
let corners = [area.left_top(), area.right_top(), area.right_bottom(), area.left_bottom()];
|
||||
super::paint_outside(draw, corners, &q, DataColor::new(fill));
|
||||
}
|
||||
let line = if scene.refused { style.invalid } else { style.line };
|
||||
if scene.started {
|
||||
|
||||
@@ -66,7 +66,7 @@ impl Snap {
|
||||
}
|
||||
|
||||
/// The snapping distance in document units for this pass, or `None` when snapping is off, the canvas has not given
|
||||
/// this snap its pass ([`at`](Self::at)) or the Control key suspends it (unless `reads_control`): the one gate of
|
||||
/// this snap its pass (`at`) or the Control key suspends it (unless `reads_control`): the one gate of
|
||||
/// `apply`, `point` and `rect`, and the reach a gesture's snapped lines were found with.
|
||||
pub fn reach(&self, mods: Mods, reads_control: bool) -> Option<f64> {
|
||||
self.tolerance.filter(|_| self.options.on && !snap_suspended(mods, self.os, reads_control))
|
||||
|
||||
@@ -22,7 +22,7 @@ const ESCAPE_DRAG_START: Vec2 = Vec2::new(0.25, 0.25);
|
||||
/// The id a [`ToolFixture`] gives its canvas labelled `label`: what a body hands to a control keyed by its canvas
|
||||
/// ([`Guides::new`](crate::canvas_controls::Guides::new)), as an app names its own canvas.
|
||||
pub fn canvas_id(label: &'static str) -> Id {
|
||||
Id::new(("tool fixture canvas", label))
|
||||
Id::unique(("tool fixture canvas", label))
|
||||
}
|
||||
|
||||
/// A tool shown on a canvas that fills the fixture's room, with the gesture phases the host reported.
|
||||
|
||||
@@ -14,7 +14,7 @@ use craft_behavior::geometry::{SnapKinds, SnapLine};
|
||||
use craft_behavior::kurbo::{self, Point};
|
||||
use craft_behavior::{Axis, CancelReason, CanvasView, Cursor, CursorIcon, GestureId, PointerButton, PointerSample};
|
||||
use craft_i18n::{Digits, Format, Region};
|
||||
use craft_keymap::{Chord, Key, Mods, Platform};
|
||||
use craft_keymap::{Chord, Key, Mods};
|
||||
use egui::{Pos2, Rect, Vec2};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -441,7 +441,7 @@ impl<'a> ToolContext<'a> {
|
||||
self.requests.snapped.extend(lines);
|
||||
}
|
||||
|
||||
/// Sets the view for a pan (as [`set_view`](Self::set_view)); the host reports it as [`ViewPan`].
|
||||
/// Sets the view for a pan (as [`set_view`](Self::set_view)); the host reports it as [`ViewPan`](super::ViewPan).
|
||||
pub fn pan_view(&mut self, view: CanvasView, scroll_all: bool) {
|
||||
self.set_view(view);
|
||||
self.requests.pan = Some(scroll_all);
|
||||
@@ -453,11 +453,6 @@ impl<'a> ToolContext<'a> {
|
||||
self.requests.autoscroll_at = Some(pointer);
|
||||
}
|
||||
|
||||
/// The OS the pass runs on: the env's; the build's for a context built without an env.
|
||||
fn os(&self) -> Platform {
|
||||
self.env.map_or_else(Platform::current, |env| env.os)
|
||||
}
|
||||
|
||||
/// The scope's number format and unit words, to write the values of a readout in the document's units and the
|
||||
/// app's language. English with the system region's number format for a context built without an env.
|
||||
pub fn units(&self) -> Units {
|
||||
|
||||
@@ -579,7 +579,7 @@ impl<'m> ToolHost<'m> {
|
||||
let current = state.gesture.map(|active| active.last).or_else(|| over.then(|| hover_pointer(&input, canvas.press)).flatten());
|
||||
// The tool of hover, cursor, paint and claims: the one the running gesture latched, else the stand-in lent for
|
||||
// the held key, else the momentary tool in effect, else the selected tool.
|
||||
let pass: &dyn CanvasTool = run_as(momentary.as_deref_mut(), momentary_tool, &mut *tool);
|
||||
let pass: &dyn CanvasTool = run_as(momentary, momentary_tool, &mut *tool);
|
||||
let effective: &dyn CanvasTool = match state.gesture.map_or(lent, |active| active.stand_in) {
|
||||
Some(StandInKey::Command) => command_stand_in.as_deref().unwrap_or(pass),
|
||||
Some(StandInKey::Alt) => alt_stand_in.as_deref().unwrap_or(pass),
|
||||
|
||||
@@ -67,9 +67,9 @@ fn stamped(y: f64) -> CoverageMask {
|
||||
|
||||
/// The footprint of one tone. The mask is kept across passes (stamped once), so the trail uploads only what changed.
|
||||
fn footprint_of(ui: &mut Ui, name: &'static str, label: &'static str, tone: TrailTone, y: f64) -> StoryOutput {
|
||||
let kept = ui.data_mut(|data| data.get_temp_mut_or_insert_with(Id::new(("footprint", name)), || Arc::new(Mutex::new(stamped(y)))).clone());
|
||||
let kept = ui.data_mut(|data| data.get_temp_mut_or_insert_with(Id::unique(("footprint", name)), || Arc::new(Mutex::new(stamped(y)))).clone());
|
||||
let mut mask = kept.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
on_canvas_view(ui, brush_view, Some(&StoryDocument::STANDARD), |ui, rect, _| StrokeTrail::new(label, &mut *mask).tone(tone).show_at(ui, rect))
|
||||
on_canvas_view(ui, brush_view, Some(&StoryDocument::STANDARD), |ui, rect, _| StrokeTrail::new(label, &mut mask).tone(tone).show_at(ui, rect))
|
||||
}
|
||||
|
||||
#[story(StrokeTrail<'static>, covers = [Default])]
|
||||
|
||||
@@ -54,7 +54,7 @@ fn texel_span(lo: f64, hi: f64, origin: f64, scale: f64, extent: u32) -> Option<
|
||||
|
||||
/// A coverage in 0..=1 as a byte; a NaN is none.
|
||||
fn byte(coverage: f32) -> u8 {
|
||||
(coverage.max(0.0).min(1.0) * 255.0).round() as u8
|
||||
(coverage.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
impl CoverageMask {
|
||||
|
||||
@@ -6,7 +6,7 @@ pub mod reading;
|
||||
#[cfg(feature = "testing")]
|
||||
mod stories;
|
||||
|
||||
pub use reading::{GuideReading, running};
|
||||
pub use reading::GuideReading;
|
||||
|
||||
use super::words::CanvasControlWords;
|
||||
use crate::canvas::{
|
||||
@@ -174,7 +174,7 @@ pub(crate) fn guides_id(canvas: egui::Id) -> egui::Id {
|
||||
|
||||
impl<'a> Guides<'a> {
|
||||
/// The guides named `label` over `guides`, in document units, on the canvas `canvas` (the id of the `Canvas` whose
|
||||
/// body shows them, [`CanvasSpace::canvas`](crate::canvas::CanvasSpace::canvas)): they take their id from it, so
|
||||
/// body shows them): they take their id from it, so
|
||||
/// [`running`] finds their drag by the canvas.
|
||||
pub fn new(label: impl Into<Label>, canvas: egui::Id, guides: Bind<'a, Vec<Guide>>) -> Self {
|
||||
Guides {
|
||||
|
||||
@@ -18,7 +18,7 @@ const MOST_GUIDES: usize = 2;
|
||||
/// [`StoryDocument::STANDARD`] at 100 % centred on its middle, as `on_canvas` does; the control gets the canvas's rect
|
||||
/// and its id, which the guides are keyed by.
|
||||
fn on_guides_canvas(ui: &mut Ui, mut control: impl FnMut(&mut Ui, Rect, Id) -> GuidesOutput) -> StoryOutput {
|
||||
let canvas = ui.id().with("guides story canvas");
|
||||
let canvas = ui.scope_id().with("guides story canvas");
|
||||
let document: &dyn RasterSource = &StoryDocument::STANDARD;
|
||||
let room = stage(ui);
|
||||
let size = document.size();
|
||||
|
||||
@@ -92,7 +92,7 @@ fn cmd_or_ctrl_with_page_down_on_a_focused_canvas_control_scrolls_the_canvas_sid
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut given = shown.get();
|
||||
given.rect = ui.available_rect_before_wrap();
|
||||
let canvas = ui.id().with("document canvas");
|
||||
let canvas = ui.scope_id().with("document canvas");
|
||||
let canvas = Canvas::new("Document")
|
||||
.id(canvas)
|
||||
.document(Size::new(4000.0, 4000.0))
|
||||
@@ -170,6 +170,9 @@ fn at_a_whole_device_zoom_with_no_rotation_the_shown_view_puts_document_pixels_o
|
||||
assert!((p.x - p.x.round()).abs() < 1e-3 && (p.y - p.y.round()).abs() < 1e-3, "a view set at a whole zoom is shown aligned: {p:?}");
|
||||
}
|
||||
|
||||
/// A case of the wheel table: its name, navigation, the events it sends, whether it reads as a pan, and the zoom it ends at.
|
||||
type NavCase<'a> = (&'a str, NavigationOptions, &'a dyn Fn(Pos2) -> Vec<Vec<egui::Event>>, bool, f64);
|
||||
|
||||
type WheelRig = (Fixture, Rc<Cell<CanvasView>>, Rc<Cell<Option<f64>>>, Rc<Cell<egui::Rect>>);
|
||||
|
||||
/// A canvas over a large document at zoom 1 below a framework number field and an app's own text field, on `os`: the
|
||||
@@ -414,7 +417,7 @@ fn pinch_and_rotation_follow_the_gesture_options_and_the_flip() {
|
||||
vec![fingers(TouchPhase::Start, at, Vec2::new(50.0, 0.0)), fingers(TouchPhase::Move, at, turned), fingers(TouchPhase::End, at, turned)]
|
||||
};
|
||||
// (case, options (pinch, gestures, rotate), input, zooms, degrees turned)
|
||||
let cases: [(&str, NavigationOptions, &dyn Fn(Pos2) -> Vec<Vec<egui::Event>>, bool, f64); 12] = [
|
||||
let cases: [NavCase<'_>; 12] = [
|
||||
("the trackpad's pinch", navigation(true, true, false), pinch, true, 0.0),
|
||||
("the fingers' pinch", navigation(true, true, false), spread, true, 0.0),
|
||||
("the trackpad's pinch without Zoom with Trackpad Pinch", navigation(false, true, false), pinch, false, 0.0),
|
||||
|
||||
@@ -322,7 +322,7 @@ enum Crowd {
|
||||
|
||||
/// A `Band` canvas inset in the room with one `Crowd` around it. Returns the fixture, the app's view and the canvas's
|
||||
/// rect.
|
||||
fn crowded_canvas(crowd: Crowd) -> (Fixture, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Rect>>) {
|
||||
fn crowded_canvas(crowd: Crowd) -> CanvasRig<Rect> {
|
||||
let view = Rc::new(Cell::new(None::<CanvasView>));
|
||||
let canvas = Rc::new(Cell::new(Rect::NOTHING));
|
||||
let (shown_view, shown_canvas) = (Rc::clone(&view), Rc::clone(&canvas));
|
||||
@@ -406,6 +406,12 @@ fn an_open_polygon_keeps_its_vertices_while_the_view_scrolls_under_a_resting_poi
|
||||
assert_eq!(tool.borrow().vertices, inside, "the vertices stay where they were clicked");
|
||||
}
|
||||
|
||||
/// A fixture with the view the canvas reported and the last value the body saw.
|
||||
type CanvasRig<Seen> = (Fixture, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Seen>>);
|
||||
|
||||
/// `CanvasRig` with the context requests the canvas raised.
|
||||
type MenuRig = (Fixture, Rc<RefCell<Vec<ContextRequest>>>, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Rect>>);
|
||||
|
||||
type Log = Rc<RefCell<Vec<String>>>;
|
||||
|
||||
/// A tool that logs its calls under its name. It refuses a press while its `refuses` key is held, answers it `Ignored`
|
||||
@@ -801,15 +807,12 @@ fn an_injected_pen_reading_reaches_the_tool() {
|
||||
/// press after its release runs the selected tool.
|
||||
/// A canvas with the momentary set and `main` as the selected tool, zoomed in, so the document is larger than the
|
||||
/// canvas and the Hand has room to pan: returns the fixture, the app's view and the canvas's id.
|
||||
fn momentary_canvas(main: Probe) -> (Fixture, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Id>>) {
|
||||
fn momentary_canvas(main: Probe) -> CanvasRig<Id> {
|
||||
momentary_canvas_with(main, |_, _| {})
|
||||
}
|
||||
|
||||
/// `momentary_canvas` with `body` as the canvas's body.
|
||||
fn momentary_canvas_with(
|
||||
main: Probe,
|
||||
mut body: impl FnMut(&mut egui::Ui, &mut craft_ui::contract::BodyCx<'_>) + 'static,
|
||||
) -> (Fixture, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Id>>) {
|
||||
fn momentary_canvas_with(main: Probe, mut body: impl FnMut(&mut egui::Ui, &mut craft_ui::contract::BodyCx<'_>) + 'static) -> CanvasRig<Id> {
|
||||
let main = RefCell::new(main);
|
||||
let (view, canvas) = (Rc::new(Cell::new(None::<CanvasView>)), Rc::new(Cell::new(Id::NULL)));
|
||||
let (shown_view, shown_canvas) = (Rc::clone(&view), Rc::clone(&canvas));
|
||||
@@ -857,7 +860,7 @@ fn a_queued_space_held_over_a_press_pans_with_the_hand_and_the_press_after_its_r
|
||||
fn a_held_space_pans_over_a_canvas_control_and_leaves_it_unchanged() {
|
||||
// Around the document's centre, which the zoomed-in view shows.
|
||||
let start = craft_behavior::geometry::CropBox::upright(craft_behavior::kurbo::Rect::new(580.0, 430.0, 620.0, 470.0));
|
||||
let crop = Rc::new(RefCell::new(start.clone()));
|
||||
let crop = Rc::new(RefCell::new(start));
|
||||
let shown = Rc::clone(&crop);
|
||||
let log = Log::default();
|
||||
let (mut fixture, view, canvas) = momentary_canvas_with(Probe::new("main", &log), move |ui, body| {
|
||||
@@ -917,7 +920,7 @@ fn a_queued_space_whose_hand_the_gate_refuses_leaves_the_press_to_the_selected_t
|
||||
}
|
||||
|
||||
/// A canvas under a dialog that keeps the canvas: returns the fixture, the app's view and the canvas's rect.
|
||||
fn kept_canvas<T: CanvasTool + 'static>(tool: Rc<RefCell<T>>) -> (Fixture, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Rect>>) {
|
||||
fn kept_canvas<T: CanvasTool + 'static>(tool: Rc<RefCell<T>>) -> CanvasRig<Rect> {
|
||||
let view = Rc::new(Cell::new(None::<CanvasView>));
|
||||
let rect = Rc::new(Cell::new(Rect::NOTHING));
|
||||
let (shown_view, shown_rect) = (Rc::clone(&view), Rc::clone(&rect));
|
||||
@@ -1115,7 +1118,7 @@ fn a_secondary_click_with_the_momentary_hand_asks_for_its_menu() {
|
||||
|
||||
/// A canvas with the Hand selected, with the momentary set when `momentary` and scroll bars in its body when `bars`.
|
||||
/// Returns the fixture, the menu requests, the app's view and the canvas's rect.
|
||||
fn menu_canvas(momentary: bool, bars: bool) -> (Fixture, Rc<RefCell<Vec<ContextRequest>>>, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Rect>>) {
|
||||
fn menu_canvas(momentary: bool, bars: bool) -> MenuRig {
|
||||
let (contexts, view, rect) = (Rc::new(RefCell::new(Vec::new())), Rc::new(Cell::new(None::<CanvasView>)), Rc::new(Cell::new(Rect::NOTHING)));
|
||||
let (shown_contexts, shown_view, shown_rect) = (Rc::clone(&contexts), Rc::clone(&view), Rc::clone(&rect));
|
||||
let mut hand = HandTool::new(NavigationOptions::default());
|
||||
|
||||
@@ -18,21 +18,20 @@ const DOCUMENT: Size = Size::new(1200.0, 900.0);
|
||||
const FRAME: f64 = 1.0 / 60.0;
|
||||
|
||||
/// A tool on a canvas whose view the rig keeps across frames as the host reports it, with the pans the host reported.
|
||||
struct Rig<T: CanvasTool + 'static> {
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
tool: Rc<RefCell<T>>,
|
||||
view: Rc<Cell<Option<CanvasView>>>,
|
||||
pans: Rc<RefCell<Vec<(DocVec, bool)>>>,
|
||||
}
|
||||
|
||||
impl<T: CanvasTool + 'static> Rig<T> {
|
||||
fn new(tool: T, start: impl Fn(egui::Rect) -> CanvasView + 'static) -> Self {
|
||||
impl Rig {
|
||||
fn new<T: CanvasTool + 'static>(tool: T, start: impl Fn(egui::Rect) -> CanvasView + 'static) -> Self {
|
||||
Self::scaled(tool, 1.0, NavigationOptions::default(), start)
|
||||
}
|
||||
|
||||
/// A rig whose canvas shows at `ppp` pixels per point from its first frame, with the canvas's navigation options
|
||||
/// `navigation`.
|
||||
fn scaled(tool: T, ppp: f32, navigation: NavigationOptions, start: impl Fn(egui::Rect) -> CanvasView + 'static) -> Self {
|
||||
fn scaled<T: CanvasTool + 'static>(tool: T, ppp: f32, navigation: NavigationOptions, start: impl Fn(egui::Rect) -> CanvasView + 'static) -> Self {
|
||||
let tool = Rc::new(RefCell::new(tool));
|
||||
let view = Rc::new(Cell::new(None::<CanvasView>));
|
||||
let pans = Rc::new(RefCell::new(Vec::<(DocVec, bool)>::new()));
|
||||
@@ -49,7 +48,7 @@ impl<T: CanvasTool + 'static> Rig<T> {
|
||||
});
|
||||
fixture.ctx().set_pixels_per_point(ppp);
|
||||
fixture.settle();
|
||||
Rig { fixture, tool, view, pans }
|
||||
Rig { fixture, view, pans }
|
||||
}
|
||||
|
||||
fn view(&self) -> CanvasView {
|
||||
|
||||
@@ -114,7 +114,7 @@ const MAX_FONT_BYTES: u64 = 128 << 20;
|
||||
/// reinstalled.
|
||||
///
|
||||
/// The loader retains no font bytes: a file is read once, checked, and handed to egui as owned data, one
|
||||
/// face per file. Memory is bounded by [`MAX_FONT_BYTES`] per file and [`MAX_SCRIPT_READS`] files per script,
|
||||
/// face per file. Memory is bounded by `MAX_FONT_BYTES` per file and [`MAX_SCRIPT_READS`] files per script,
|
||||
/// so there is no blob budget to enforce. In a collection the face is chosen by character-map coverage, then by
|
||||
/// the Han region's family, and a face whose tables are malformed is skipped.
|
||||
pub struct OnDemandFonts {
|
||||
|
||||
@@ -207,7 +207,7 @@ pub fn has_icon(id: &IconId) -> bool {
|
||||
svg_set::lookup(id.name()).is_some()
|
||||
}
|
||||
|
||||
/// The names of the built-in catalog's icons, sorted; app icon sets registered with [`register_app_icons`] are not
|
||||
/// The names of the built-in catalog's icons, sorted; app icon sets registered with [`register_app_icons`](super::register_app_icons) are not
|
||||
/// listed.
|
||||
pub fn icon_names() -> &'static [&'static str] {
|
||||
svg_set::names()
|
||||
|
||||
@@ -175,7 +175,7 @@ fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) {
|
||||
let pixels = document.pixel_size();
|
||||
let (view, show_rulers) = (document.view, document.rulers);
|
||||
let editing = matches!(tool, Tool::Move | Tool::Marquee);
|
||||
let canvas_id = ui.id().with("mock document canvas");
|
||||
let canvas_id = ui.scope_id().with("mock document canvas");
|
||||
let shown = {
|
||||
let Document { layers, guides, guide, marquee, zero, units: unit, .. } = &mut *document;
|
||||
Canvas::new("Document").id(canvas_id).view(view).document(page.size()).show_rulers(show_rulers).rulers(units, units, *zero).show(
|
||||
|
||||
@@ -54,7 +54,7 @@ pub trait DockPanels<P> {
|
||||
type Running<P> = Vec<Vec<Action<P>>>;
|
||||
|
||||
fn running_id() -> Id {
|
||||
Id::new("dock area requests")
|
||||
Id::unique("dock area requests")
|
||||
}
|
||||
|
||||
/// Hands `actions` to the dock area over panels `P` whose pass is running on `ctx`: a panel body, or code a body
|
||||
|
||||
@@ -1025,7 +1025,7 @@ pub fn set_param_field(params: &[Param], fields: &mut DialogFields, field: &str,
|
||||
return Err(FieldRefusal::Inactive.message(field));
|
||||
}
|
||||
let writes = if companion(param) {
|
||||
Some(vec![(field.to_owned(), Some(FieldValue::Json(value.clone())).filter(|_| !value.is_null()))])
|
||||
Some(vec![(field.to_owned(), (!value.is_null()).then_some(FieldValue::Json(value.clone())))])
|
||||
} else if param.key != field {
|
||||
value.as_str().map(|unit| vec![(field.to_owned(), Some(FieldValue::Text(unit.to_owned())))])
|
||||
} else if matches!(param.kind, ParamKind::Files { .. }) {
|
||||
|
||||
@@ -401,7 +401,6 @@ impl<'a> FormatOptionsDialog<'a> {
|
||||
/// Offers the TIFF rows of a document: Discard Layers when it has `layered`, Save Transparency when it is
|
||||
/// `transparent`, and the layered-file note with Don't show again when `layer_note` is set (while the layers are
|
||||
/// kept). Without this call the dialog offers every row.
|
||||
#[must_use]
|
||||
pub fn tiff_document(mut self, layered: bool, transparent: bool, layer_note: bool) -> Self {
|
||||
self.tiff = TiffDocument { layered, transparent, layer_note };
|
||||
self
|
||||
|
||||
@@ -643,7 +643,7 @@ impl HostedGuideLayoutDialog {
|
||||
impl StackDialog for HostedGuideLayoutDialog {
|
||||
type Result = GuideLayoutResult;
|
||||
|
||||
/// Answers what OK answers: the guide list of [`layout_guides`]; `None` while the layout is invalid.
|
||||
/// Answers what OK answers: the guide list of `layout_guides`; `None` while the layout is invalid.
|
||||
fn confirm(&mut self, _ctx: &egui::Context) -> Option<Self::Result> {
|
||||
let GuideLayoutDialog { units, document, artboards, existing, first_key, .. } = (self.build)(Bind::bound(&mut self.values));
|
||||
let values = self.values;
|
||||
|
||||
@@ -93,7 +93,6 @@ impl<'a> ReportDialog<'a> {
|
||||
|
||||
/// Plain `lines` shown as the notes, in place of ones built with [`ReportNote`]: each line is selectable text,
|
||||
/// and Copy hands them back as they are.
|
||||
#[must_use]
|
||||
pub fn lines(mut self, lines: Vec<Label>) -> Self {
|
||||
self.lines = lines;
|
||||
self
|
||||
|
||||
@@ -137,6 +137,9 @@ impl Outcome for HistoryPanelOutput {
|
||||
}
|
||||
|
||||
/// The row a context menu was asked for; it lives in the panel's stack memory while the menu is open.
|
||||
/// Whether a row may be deleted.
|
||||
type DeletePredicate<'a> = Box<dyn Fn(&HistoryKey) -> bool + 'a>;
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct MenuTarget(Option<HistoryKey>);
|
||||
|
||||
@@ -157,7 +160,7 @@ pub struct HistoryPanel<'a> {
|
||||
source: Option<HistoryKey>,
|
||||
has_source: bool,
|
||||
thumbs: Option<(&'a Thumbnails<u64>, &'a dyn ThumbSource<u64>)>,
|
||||
can_delete: Option<Box<dyn Fn(&HistoryKey) -> bool + 'a>>,
|
||||
can_delete: Option<DeletePredicate<'a>>,
|
||||
footer: HistoryFooter,
|
||||
reveal: Option<HistoryKey>,
|
||||
rename: Option<u64>,
|
||||
@@ -182,7 +185,6 @@ impl<'a> HistoryPanel<'a> {
|
||||
}
|
||||
|
||||
/// Shows the source column and marks the row that is the source of the history brush.
|
||||
#[must_use]
|
||||
pub fn source(mut self, source: Option<HistoryKey>) -> Self {
|
||||
self.source = source;
|
||||
self.has_source = true;
|
||||
@@ -190,42 +192,36 @@ impl<'a> HistoryPanel<'a> {
|
||||
}
|
||||
|
||||
/// Shows the pictures of the snapshot rows from `source`.
|
||||
#[must_use]
|
||||
pub fn thumbnails(mut self, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
|
||||
self.thumbs = Some((thumbnails, source));
|
||||
self
|
||||
}
|
||||
|
||||
/// Which rows the Delete button and key take; the others refuse. Without it every row is taken.
|
||||
#[must_use]
|
||||
pub fn can_delete(mut self, can: impl Fn(&HistoryKey) -> bool + 'a) -> Self {
|
||||
self.can_delete = Some(Box::new(can));
|
||||
self
|
||||
}
|
||||
|
||||
/// Which footer buttons show.
|
||||
#[must_use]
|
||||
pub fn footer(mut self, footer: HistoryFooter) -> Self {
|
||||
self.footer = footer;
|
||||
self
|
||||
}
|
||||
|
||||
/// Scrolls to `key` and shows it.
|
||||
#[must_use]
|
||||
pub fn reveal(mut self, key: HistoryKey) -> Self {
|
||||
self.reveal = Some(key);
|
||||
self
|
||||
}
|
||||
|
||||
/// Opens the rename field of the snapshot `snapshot`.
|
||||
#[must_use]
|
||||
pub fn start_rename(mut self, snapshot: u64) -> Self {
|
||||
self.rename = Some(snapshot);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the panel takes input.
|
||||
#[must_use]
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, Workspace};
|
||||
use craft_behavior::placement::Placement;
|
||||
use craft_host::target::{Backend, Caps, Os, ShellInfo};
|
||||
use craft_ui::contract::{Bind, BodyCx, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, BodyCx, ShowContainer as _};
|
||||
use craft_ui::docking::{DockConfig, DockPanels, PanelSpec};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::popover::DropVeil;
|
||||
|
||||
@@ -91,6 +91,14 @@ fn columns_on_the_width_convert_through_the_column_size() {
|
||||
}
|
||||
}
|
||||
|
||||
relative_columns();
|
||||
degenerate_column_sizes();
|
||||
shared_unit();
|
||||
resample_off();
|
||||
}
|
||||
|
||||
/// A relative change keeps 0 at 0 and its sign.
|
||||
fn relative_columns() {
|
||||
let mut relative = document().column_size(COLUMNS);
|
||||
relative.relative(true);
|
||||
relative.lock(false);
|
||||
@@ -104,7 +112,10 @@ fn columns_on_the_width_convert_through_the_column_size() {
|
||||
relative.set_width(-372.0);
|
||||
assert!(relative.set_width_unit(UnitKind::Columns));
|
||||
assert!(close(relative.width(), -2.0), "a shrink of two columns reads -2, not {}", relative.width());
|
||||
}
|
||||
|
||||
/// A degenerate or negative column size falls back to 180 pt / 12 pt, a negative gutter counts as none.
|
||||
fn degenerate_column_sizes() {
|
||||
let degenerate = [
|
||||
ColumnSize { width: 0.0, gutter: f64::NAN },
|
||||
ColumnSize { width: f64::NAN, gutter: f64::INFINITY },
|
||||
@@ -121,7 +132,10 @@ fn columns_on_the_width_convert_through_the_column_size() {
|
||||
assert!(no_gutter.set_width_unit(UnitKind::Columns));
|
||||
no_gutter.set_width(2.0);
|
||||
assert_eq!(pixels(&no_gutter).0, 200, "a negative gutter counts as none");
|
||||
}
|
||||
|
||||
/// The height keeps the shared unit; another unit turns Columns off.
|
||||
fn shared_unit() {
|
||||
let mut shared = document();
|
||||
assert!(!shared.set_width_unit(UnitKind::Columns), "without a column size the width offers no Columns");
|
||||
assert_eq!(shared.width_unit(), UnitKind::Pixels);
|
||||
@@ -132,7 +146,10 @@ fn columns_on_the_width_convert_through_the_column_size() {
|
||||
assert!(close(shared.height(), 800.0 / 72.0), "the height still reads in inches");
|
||||
assert!(shared.set_width_unit(UnitKind::Pixels));
|
||||
assert_eq!((shared.width_unit(), shared.unit()), (UnitKind::Pixels, UnitKind::Pixels), "another unit turns Columns off and sets both");
|
||||
}
|
||||
|
||||
/// With Resample off a Columns width changes the resolution.
|
||||
fn resample_off() {
|
||||
let mut fixed = document().column_size(COLUMNS);
|
||||
fixed.resampling(false);
|
||||
assert!(fixed.set_width_unit(UnitKind::Columns));
|
||||
|
||||
@@ -54,21 +54,18 @@ impl OpeningCard {
|
||||
}
|
||||
|
||||
/// The muted message under the title.
|
||||
#[must_use]
|
||||
pub fn message(mut self, message: impl Into<Label>) -> Self {
|
||||
self.message = Some(message.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// How far the job is, 0 to 1; `None` shows an indeterminate bar.
|
||||
#[must_use]
|
||||
pub fn fraction(mut self, fraction: Option<f32>) -> Self {
|
||||
self.fraction = fraction;
|
||||
self
|
||||
}
|
||||
|
||||
/// The Cancel button's text; without it the card has no Cancel.
|
||||
#[must_use]
|
||||
pub fn cancel(mut self, cancel: impl Into<Label>) -> Self {
|
||||
self.cancel = Some(cancel.into());
|
||||
self
|
||||
|
||||
@@ -226,7 +226,6 @@ impl<'a> StartScreen<'a> {
|
||||
}
|
||||
|
||||
/// Cards, rows and templates ask `thumbnails.state(..)` for what they show; `source` gives each key's revision.
|
||||
#[must_use]
|
||||
pub fn thumbnails(mut self, thumbnails: &'a Thumbnails<ThumbKey>, source: &'a dyn ThumbSource<ThumbKey>) -> Self {
|
||||
self.thumbnails = Some((thumbnails, source));
|
||||
self
|
||||
|
||||
@@ -287,7 +287,7 @@ impl Container for TitleBar<'_> {
|
||||
/// `CaptionIcons::for_desktop` once per desktop value and kept for the app's bars while the desktop stays the same.
|
||||
fn desktop_icons(ctx: &egui::Context) -> Option<CaptionIcons> {
|
||||
let desktop = WindowHost::of(ctx).desktop()?;
|
||||
let key = egui::Id::new("craft_ui.title_bar.desktop_icons");
|
||||
let key = egui::Id::unique("craft_ui.title_bar.desktop_icons");
|
||||
let kept = ctx.data(|data| data.get_temp::<(Desktop, Option<CaptionIcons>)>(key));
|
||||
if let Some((seen, icons)) = &kept
|
||||
&& *seen == desktop
|
||||
|
||||
Reference in New Issue
Block a user