mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-18 02:32:33 +00:00
tools-w14: net change of 4 commits
- tools-w14: written by an agent - tools-w14: finished by an agent - tools-w14: review fixes (review-1.md) - tools-w14: the perspective bar story keeps its fields and grid in one story value (combine)
This commit is contained in:
+36
-163
@@ -2,11 +2,10 @@
|
||||
|
||||
use super::bar_words::CropBarWords;
|
||||
use super::menus::{CropOptionsMenu, CropOverlayMenu};
|
||||
use super::options::{
|
||||
CROP_RATIOS, CROP_SIZES, CropFill, CropLength, CropPresetChoice, CropRatio, CropSettings, CropSizeFields, CropUserPreset, FIELD_MAX, LENGTH_MIN,
|
||||
RATIO_DECIMALS, RATIO_MAX, RATIO_STEP, ResolutionUnit,
|
||||
};
|
||||
use super::options::{CropFill, CropRatio, CropSettings, CropUserPreset, RATIO_DECIMALS, RATIO_MAX, RATIO_STEP};
|
||||
use super::preset_list::CropPresetList;
|
||||
use super::session::CropDocument;
|
||||
use super::size_cells::{self, SizeLimits};
|
||||
use craft_behavior::{EditEvent, EditEvents, IconId, NumberCodec};
|
||||
use craft_ui::buttons::{Button, IconButton, ToggleButton};
|
||||
use craft_ui::choice::Checkbox;
|
||||
@@ -17,7 +16,7 @@ use craft_ui::display::Divider;
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Label, LengthUnits, UnitKind, Units};
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind, Units};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Response, Ui};
|
||||
@@ -62,7 +61,7 @@ pub struct CropBarOutput {
|
||||
pub help: bool,
|
||||
/// Reset was pressed this pass.
|
||||
pub reset: bool,
|
||||
/// From Selection was picked in the preset list.
|
||||
/// Selection was picked in the preset list: the app calls `CropTool::take_selection_frame`.
|
||||
pub selection: bool,
|
||||
}
|
||||
|
||||
@@ -77,16 +76,19 @@ impl Outcome for CropBarOutput {
|
||||
/// The Crop tool's options, shown as children of the app's `Bar::new(label, BarKind::Options)`; ✓ and ⊘ are the bar's
|
||||
/// `commit_cancel`.
|
||||
///
|
||||
/// - Order (Photoshop's): the preset list (Ratio, W x H x Resolution, the ratio presets, the size presets, the user's
|
||||
/// presets, Front Image, a rule, New Crop Preset…, Delete Crop Preset…); the W and H ratio fields (0 to 99,999 with 3
|
||||
/// decimals) with the swap button between them, or in W × H × Resolution mode the W, H and Resolution fields with
|
||||
/// the px/in or px/cm select; Clear; the Angle field; the Straighten toggle (pressed while armed); the overlay menu
|
||||
/// ([`CropOverlayMenu`]); the gear popover ([`CropOptionsMenu`]); the Delete Cropped Pixels check box; Fill and its
|
||||
/// select.
|
||||
/// - W and H keep their lengths with the unit they were entered in ([`CropLength`]); a cleared field is unset.
|
||||
/// - Order (Photoshop's): the preset list ([`CropPresetList`]: Selection when offered, Ratio, W x H x Resolution, the
|
||||
/// ratio presets, the size presets, the user's presets, Front Image, a rule, New Crop Preset…, Delete Crop
|
||||
/// Preset…); the W and H ratio fields (0 to 99,999 with 3 decimals) with the swap button between them, or in
|
||||
/// W × H × Resolution mode the W, H and Resolution fields with the px/in or px/cm select; Clear; the Angle field;
|
||||
/// the Straighten toggle (pressed while armed); the overlay menu ([`CropOverlayMenu`]); the gear popover
|
||||
/// ([`CropOptionsMenu`]); the Delete Cropped Pixels check box; Fill and its select; the help button when a help
|
||||
/// label is given; Reset.
|
||||
/// - W and H keep their lengths with the unit they were entered in ([`CropLength`](super::CropLength)); a cleared
|
||||
/// field is unset.
|
||||
/// - A scrub or a step of a ratio field refits live; Escape puts the ratio back.
|
||||
/// - Delete Crop Preset… is disabled when no user preset is given; New Crop Preset… when [`CropSettings::preset_name`]
|
||||
/// is `None`; Original Ratio and Front Image without a document.
|
||||
/// - Fill's first entry reads Transparent while Delete Cropped Pixels is off and Background while it is on.
|
||||
/// - **Keyboard and AccessKit:** the list is a select named "Crop ratio" with the chosen entry as its value; the
|
||||
/// fields are named Width, Height, Resolution and Angle; the Straighten toggle has its pressed state; the menus
|
||||
/// open with Enter or Space.
|
||||
@@ -106,21 +108,27 @@ pub struct CropBar<'a> {
|
||||
angle: Option<f64>,
|
||||
/// The help button after Fill; `Some` shows it, named by the label.
|
||||
#[prop(into)]
|
||||
help: Option<craft_ui::runtime::env::Label>,
|
||||
help: Option<Label>,
|
||||
/// Whether Reset is enabled (`CropTool::modified`).
|
||||
#[prop]
|
||||
can_reset: bool,
|
||||
/// Offers Selection as the preset list's first entry.
|
||||
#[prop]
|
||||
selection_entry: bool,
|
||||
/// Shows Selection as the chosen preset (`CropTool::shows_selection_entry`).
|
||||
#[prop]
|
||||
selection_chosen: bool,
|
||||
}
|
||||
|
||||
impl<'a> CropBar<'a> {
|
||||
/// The bar editing `settings`, over `document` (Original Ratio's numbers and Front Image).
|
||||
pub fn new(settings: &'a mut CropSettings, document: &'a CropDocument) -> Self {
|
||||
Self { settings, document, user_presets: &[], straighten: false, angle: None, help: None, can_reset: false }
|
||||
Self { settings, document, user_presets: &[], straighten: false, angle: None, help: None, can_reset: false, selection_entry: false, selection_chosen: false }
|
||||
}
|
||||
|
||||
/// Shows the bar's children.
|
||||
pub fn show(self, ui: &mut Ui) -> CropBarOutput {
|
||||
let Self { settings, document, user_presets, straighten, angle, help, can_reset } = self;
|
||||
let Self { settings, document, user_presets, straighten, angle, help, can_reset, selection_entry, selection_chosen } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<CropBarWords>();
|
||||
let units = env.units();
|
||||
@@ -130,9 +138,15 @@ impl<'a> CropBar<'a> {
|
||||
let (mut help_pressed, mut reset_pressed) = (false, false);
|
||||
// The options are the bar's members, spaced as the bar spaces them.
|
||||
let shown = Row::new().gap(Gap::Item).show(ui, |ui, cx| {
|
||||
preset_list(ui, settings, &words, document, has_document, user_presets, &units, &mut report);
|
||||
let list = CropPresetList::new(settings, document).user_presets(user_presets).selection_entry(selection_entry).selection_chosen(selection_chosen).show(ui);
|
||||
report.ratio = list.ratio;
|
||||
report.new_preset = list.new_preset;
|
||||
report.delete_preset = list.delete_preset;
|
||||
report.selection = list.selection;
|
||||
if settings.ratio == CropRatio::Size {
|
||||
size_fields(ui, settings, &words, document, &units, &mut report);
|
||||
if size_cells::show(ui, &mut settings.size, SizeLimits::CROP, document, &units, &words).changed {
|
||||
report.ratio = Some(CropRatioChange { editing: false });
|
||||
}
|
||||
} else {
|
||||
ratio_fields(ui, cx, settings, &words, document, has_document, &units, &mut report);
|
||||
}
|
||||
@@ -152,10 +166,8 @@ impl<'a> CropBar<'a> {
|
||||
CropOverlayMenu::new(settings).show(ui);
|
||||
report.pick_color = CropOptionsMenu::new(settings).show(ui).pick_color;
|
||||
Checkbox::new(Bind::bound(&mut settings.delete_pixels)).label(words.delete_pixels.clone()).show(ui);
|
||||
let fills = [
|
||||
Entry::new(CropFill::Background, words.fill_background.clone()),
|
||||
Entry::new(CropFill::ContentAware, words.fill_content_aware.clone()),
|
||||
];
|
||||
let background = if settings.delete_pixels { words.fill_background.clone() } else { words.fill_transparent.clone() };
|
||||
let fills = [Entry::new(CropFill::Background, background), Entry::new(CropFill::ContentAware, words.fill_content_aware.clone())];
|
||||
Field::new(words.fill_name.clone()).id_salt("fill").sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
let pick = Select::new(words.fill_name.clone(), Bind::given(settings.fill), &fills).show(ui);
|
||||
if let Some(fill) = pick.value().copied() {
|
||||
@@ -179,7 +191,7 @@ impl<'a> CropBar<'a> {
|
||||
settings_changed: changed,
|
||||
help: help_pressed,
|
||||
reset: reset_pressed,
|
||||
selection: false,
|
||||
selection: report.selection,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,67 +205,13 @@ struct Report {
|
||||
new_preset: bool,
|
||||
delete_preset: bool,
|
||||
pick_color: Option<ColorRequest>,
|
||||
selection: bool,
|
||||
}
|
||||
|
||||
/// The ratio and its fields when a scrub of a ratio field began, for Escape.
|
||||
#[derive(Clone, Default)]
|
||||
struct RatioStart(Option<(CropRatio, [f64; 2])>);
|
||||
|
||||
/// The name of size preset `index` of [`CROP_SIZES`]: its values as New Crop Preset… would name them.
|
||||
fn size_name(words: &CropBarWords, index: usize, units: &Units) -> String {
|
||||
let Some(preset) = CROP_SIZES.get(index) else { return String::new() };
|
||||
let size = CropSizeFields {
|
||||
width: Some(preset.width),
|
||||
height: Some(preset.height),
|
||||
resolution: preset.resolution.to_owned(),
|
||||
..CropSizeFields::default()
|
||||
};
|
||||
let settings = CropSettings { ratio: CropRatio::Size, size, ..CropSettings::default() };
|
||||
settings.preset_name(words, units).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The preset list: Ratio, W x H x Resolution, the ratio presets, the size presets, the user's presets, Front Image,
|
||||
/// then New Crop Preset… and Delete Crop Preset….
|
||||
#[expect(clippy::too_many_arguments, reason = "the bar's inputs")]
|
||||
fn preset_list(
|
||||
ui: &mut Ui,
|
||||
settings: &mut CropSettings,
|
||||
words: &CropBarWords,
|
||||
document: &CropDocument,
|
||||
has_document: bool,
|
||||
user_presets: &[CropUserPreset],
|
||||
units: &Units,
|
||||
report: &mut Report,
|
||||
) {
|
||||
let mut entries = vec![Entry::new(CropPresetChoice::Free, words.ratio.clone()), Entry::new(CropPresetChoice::Size, words.size_mode.clone())];
|
||||
for (i, ratio) in CROP_RATIOS.iter().enumerate() {
|
||||
let entry = Entry::new(CropPresetChoice::Ratio(i), words.ratio_name(i).to_owned());
|
||||
entries.push(if *ratio == CropRatio::Original { entry.enabled(has_document) } else { entry });
|
||||
}
|
||||
for i in 0..CROP_SIZES.len() {
|
||||
entries.push(Entry::new(CropPresetChoice::SizePreset(i), size_name(words, i, units)));
|
||||
}
|
||||
for (i, preset) in user_presets.iter().enumerate() {
|
||||
entries.push(Entry::new(CropPresetChoice::User(i), preset.name.clone()));
|
||||
}
|
||||
entries.push(Entry::new(CropPresetChoice::FrontImage, words.front_image.clone()).enabled(has_document));
|
||||
entries.push(Entry::separator());
|
||||
entries.push(Entry::new(CropPresetChoice::NewPreset, words.new_preset.clone()).enabled(settings.preset_name(words, units).is_some()));
|
||||
entries.push(Entry::new(CropPresetChoice::DeletePreset, words.delete_preset.clone()).enabled(!user_presets.is_empty()));
|
||||
let current = settings.choice(user_presets);
|
||||
let pick = Select::new(words.presets.clone(), Bind::given(current), &entries).show(ui);
|
||||
let Some(choice) = pick.value().copied() else { return };
|
||||
match choice {
|
||||
CropPresetChoice::NewPreset => report.new_preset = true,
|
||||
CropPresetChoice::DeletePreset => report.delete_preset = true,
|
||||
choice => {
|
||||
if settings.choose(choice, document, user_presets) {
|
||||
report.ratio = Some(CropRatioChange { editing: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The two ratio fields with the swap button between them.
|
||||
#[expect(clippy::too_many_arguments, reason = "the bar's inputs")]
|
||||
fn ratio_fields(
|
||||
@@ -350,88 +308,3 @@ fn ratio_field(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// W, swap, H, Resolution and its unit, in W × H × Resolution mode.
|
||||
fn size_fields(ui: &mut Ui, settings: &mut CropSettings, words: &CropBarWords, document: &CropDocument, units: &Units, report: &mut Report) {
|
||||
let mut changed = false;
|
||||
let pixels_per_inch = settings.size.resolution_ppi().unwrap_or(document.resolution);
|
||||
changed |= length_field(ui, "size-width", &words.width, &mut settings.size.width, pixels_per_inch, units.points_per_inch());
|
||||
if clicked(&IconButton::new(IconId::new("swap_horizontal")).label(words.swap.clone()).show(ui)) {
|
||||
settings.swap_fields();
|
||||
changed = true;
|
||||
}
|
||||
changed |= length_field(ui, "size-height", &words.height, &mut settings.size.height, pixels_per_inch, units.points_per_inch());
|
||||
|
||||
let resolution = settings.size.resolution.trim().replace(',', ".").parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0);
|
||||
let mut typed = None;
|
||||
Field::new(words.resolution.clone()).id_salt("size-resolution").sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
let codec = NumberCodec::new(units.reader(None), 2);
|
||||
let field = NumberField::new(words.resolution.clone(), Bind::given(resolution)).codec(codec).range(0.0..=FIELD_MAX).automatic(true).show(ui);
|
||||
typed = field.value().copied();
|
||||
});
|
||||
if let Some(value) = typed {
|
||||
let text = match value.filter(|v| *v > 0.0) {
|
||||
Some(v) => CropSizeFields::normalize_resolution(&v.to_string(), &settings.size.resolution),
|
||||
None => String::new(),
|
||||
};
|
||||
if text != settings.size.resolution {
|
||||
settings.size.resolution = text;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
let unit_entries = [
|
||||
Entry::new(ResolutionUnit::PixelsPerInch, words.pixels_per_inch.clone()),
|
||||
Entry::new(ResolutionUnit::PixelsPerCentimetre, words.pixels_per_centimetre.clone()),
|
||||
];
|
||||
let pick = Select::new(words.resolution_unit.clone(), Bind::given(settings.size.resolution_unit), &unit_entries).show(ui);
|
||||
if let Some(unit) = pick.value().copied()
|
||||
&& unit != settings.size.resolution_unit
|
||||
{
|
||||
// The same resolution in the other unit, as in Photoshop.
|
||||
if let Some(v) = resolution {
|
||||
let converted = if unit == ResolutionUnit::PixelsPerCentimetre { v / 2.54 } else { v * 2.54 };
|
||||
settings.size.resolution = CropSizeFields::normalize_resolution(&converted.to_string(), &settings.size.resolution);
|
||||
}
|
||||
settings.size.resolution_unit = unit;
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
report.ratio = Some(CropRatioChange { editing: false });
|
||||
}
|
||||
}
|
||||
|
||||
/// A length field over a length kept in its own unit: a typed number is in that unit (pixels while unset), a typed
|
||||
/// unit is converted into it, and a cleared field is unset. Returns whether `value` changed.
|
||||
fn length_field(
|
||||
ui: &mut Ui,
|
||||
salt: &'static str,
|
||||
caption: &Label,
|
||||
value: &mut Option<CropLength>,
|
||||
pixels_per_inch: f64,
|
||||
points_per_inch: f64,
|
||||
) -> bool {
|
||||
let unit = value.map_or(UnitKind::Pixels, |length| length.unit);
|
||||
let mut typed = None;
|
||||
let mut typed_unit = None;
|
||||
Field::new(caption.clone()).id_salt(salt).sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
let lengths = LengthUnits::new(unit, unit, pixels_per_inch);
|
||||
let field =
|
||||
NumberField::length(caption.clone(), Bind::given(value.map(|length| length.value)), lengths).range(LENGTH_MIN..=FIELD_MAX).show(ui);
|
||||
typed = field.value().copied();
|
||||
typed_unit = field.typed_unit;
|
||||
});
|
||||
let Some(next) = typed else { return false };
|
||||
let next = next.map(|length| match typed_unit {
|
||||
// The value is in the stored unit; a typed unit becomes the stored one, as in Photoshop.
|
||||
Some(to) if to != unit => {
|
||||
let pixels = unit.to_pixels(length, 1.0, pixels_per_inch, points_per_inch);
|
||||
let converted = pixels.and_then(|pixels| to.from_pixels(pixels, 1.0, pixels_per_inch, points_per_inch));
|
||||
converted.map_or(CropLength::new(length, unit), |value| CropLength::new(value, to))
|
||||
}
|
||||
_ => CropLength::new(length, unit),
|
||||
});
|
||||
let changed = next != *value;
|
||||
*value = next;
|
||||
changed
|
||||
}
|
||||
|
||||
@@ -3,10 +3,11 @@
|
||||
use super::super::menus::{CropOptionsMenu, CropOverlayMenu};
|
||||
use super::super::options::{CropLength, CropRatio, CropSettings, CropSizeFields, CropUserPreset};
|
||||
use super::super::session::{CropDocKey, CropDocument};
|
||||
use super::super::preset_list::CropPresetList;
|
||||
use super::CropBar;
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
use kurbo::Size;
|
||||
@@ -72,3 +73,23 @@ fn crop_options_menu_classic_mode(ui: &mut Ui, data: &mut StoryData) -> StoryOut
|
||||
let settings = data.value("classic", settings);
|
||||
CropOptionsMenu::new(settings).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(CropBar<'static>, covers = [], drive = Drive::Never)]
|
||||
fn crop_bar_selection_and_reset(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let document = document();
|
||||
let settings = data.value("selection", CropSettings::default());
|
||||
let mut output = None;
|
||||
Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
|
||||
let bar = CropBar::new(settings, &document).angle(0.0).selection_entry(true).selection_chosen(true).can_reset(true).help(Label::from("About the Fill options"));
|
||||
output = Some(bar.show(ui));
|
||||
});
|
||||
output.map(StoryOutput::from).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[story(CropPresetList<'static>, covers = [], drive = Drive::Never)]
|
||||
fn crop_preset_list(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let document = document();
|
||||
let presets = [CropUserPreset::new("3 : 2", CropRatio::Sides { width: 3.0, height: 2.0 }, CropSizeFields::default())];
|
||||
let settings = data.value("list", CropSettings::default());
|
||||
CropPresetList::new(settings, &document).user_presets(&presets).selection_entry(true).selection_chosen(true).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -62,12 +62,12 @@ craft_ui::words! {
|
||||
fill_name: "cropBar.fillName" = "Fill";
|
||||
fill_background: "cropBar.fillBackground" = "Background (Default)";
|
||||
fill_content_aware: "cropBar.fillContentAware" = "Content-Aware Fill";
|
||||
/// The preset list's From Selection entry.
|
||||
selection: "cropBar.selection" = "From Selection";
|
||||
/// The preset list's Selection entry.
|
||||
selection: "cropBar.selection" = "Selection";
|
||||
/// The Fill select's first entry while Delete Cropped Pixels is off.
|
||||
fill_transparent: "cropBar.fillTransparent" = "Transparent";
|
||||
fill_transparent: "cropBar.fillTransparent" = "Transparent (default)";
|
||||
/// The Reset button's name and tooltip.
|
||||
reset_tip: "cropBar.resetTip" = "Reset crop box";
|
||||
reset_tip: "cropBar.resetTip" = "Reset the crop box, image rotation, and aspect ratio settings";
|
||||
/// The perspective bar's Show Grid check box.
|
||||
show_grid: "cropBar.showGrid" = "Show Grid";
|
||||
commit: "cropBar.commit" = "Commit current crop operation";
|
||||
|
||||
@@ -34,6 +34,19 @@ fn guide_name(words: &CropBarWords, guide: CropGuide) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The overlay's icon; an overlay this list does not know has the thirds', as [`guide_name`] has its name.
|
||||
fn guide_icon(guide: CropGuide) -> IconId {
|
||||
IconId::new(match guide {
|
||||
CropGuide::Thirds => "crop_overlay_thirds",
|
||||
CropGuide::Grid => "crop_overlay_grid",
|
||||
CropGuide::Diagonal => "crop_overlay_diagonal",
|
||||
CropGuide::Triangle => "crop_overlay_triangle",
|
||||
CropGuide::GoldenRatio => "crop_overlay_golden_ratio",
|
||||
CropGuide::GoldenSpiral => "crop_overlay_golden_spiral",
|
||||
_ => "crop_overlay_thirds",
|
||||
})
|
||||
}
|
||||
|
||||
/// The show rule's name in `words`.
|
||||
fn show_name(words: &CropBarWords, show: GuideShow) -> &str {
|
||||
match show {
|
||||
@@ -90,13 +103,13 @@ impl<'a> CropOverlayMenu<'a> {
|
||||
let before = settings.clone();
|
||||
let shown = Row::new().show(ui, |ui, cx| {
|
||||
let open = &mut cx.memory::<Open>().0;
|
||||
let opener = IconButton::new(IconId::new("grid")).label(words.overlay.clone()).popup(PopupKind::Menu).show(ui).response;
|
||||
let opener = IconButton::new(guide_icon(settings.guide)).label(words.overlay.clone()).popup(PopupKind::Menu).show(ui).response;
|
||||
if clicked(&opener) {
|
||||
*open = !*open;
|
||||
}
|
||||
Menu::new(words.overlay.clone()).open(Bind::bound(open)).opened_by(&opener, Trigger::Click).show(ui, |ui, _| {
|
||||
for guide in CropGuide::ALL {
|
||||
let row = MenuItem::new(guide_name(&words, guide).to_owned()).radio_mark(settings.guide == guide).show(ui);
|
||||
let row = MenuItem::new(guide_name(&words, guide).to_owned()).icon(guide_icon(guide)).radio_mark(settings.guide == guide).show(ui);
|
||||
if row.ran {
|
||||
settings.set_guide(guide);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! The Crop tool: the tool on the canvas tool host ([`CropTool`]) with its pending frame ([`CropSession`]) and options
|
||||
//! ([`CropSettings`]), the options bar ([`CropBar`]) with its overlay and gear menus, and the Perspective Crop tool
|
||||
//! ([`PerspectiveCropTool`]) with its quad ([`PerspectiveCropQuad`]). The frame itself is `craft_ui::canvas::CropOverlay`,
|
||||
//! shown by [`CropToolPass::show_frame`].
|
||||
//! ([`CropSettings`]), the options bar ([`CropBar`]) with its preset list ([`CropPresetList`]), overlay and gear menus,
|
||||
//! and the Perspective Crop tool ([`PerspectiveCropTool`], run each pass as [`PerspectiveCropPass`] over a
|
||||
//! [`PerspectiveInput`]) with its quad ([`PerspectiveCropQuad`]) and options bar ([`PerspectiveCropBar`]). Both bars
|
||||
//! share the W × H × Resolution cells over [`CropSizeFields`], whose target is a [`CropSizeTarget`]. The frame itself
|
||||
//! is `craft_ui::canvas::CropOverlay`, shown by [`CropToolPass::show_frame`].
|
||||
//!
|
||||
//! The tool reports events and never crops the document: the app crops on [`CropEvent::Apply`] with the
|
||||
//! [`CropCommit`] it carries.
|
||||
|
||||
@@ -85,7 +85,7 @@ impl CropLength {
|
||||
}
|
||||
|
||||
/// The length when it is positive, finite and at most [`FIELD_MAX`].
|
||||
fn usable(length: Option<CropLength>) -> Option<CropLength> {
|
||||
pub(super) fn usable(length: Option<CropLength>) -> Option<CropLength> {
|
||||
length.filter(|l| l.value.is_finite() && l.value > 0.0 && l.value <= FIELD_MAX)
|
||||
}
|
||||
|
||||
@@ -274,7 +274,7 @@ impl Default for CropSettings {
|
||||
}
|
||||
|
||||
/// `value` with up to `decimals` decimals, trailing zeros and a bare point dropped.
|
||||
fn trim_number(value: f64, decimals: usize) -> String {
|
||||
pub(super) fn trim_number(value: f64, decimals: usize) -> String {
|
||||
let text = format!("{value:.decimals$}");
|
||||
if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.').to_owned() } else { text }
|
||||
}
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
//! [`PerspectiveCropBar`]: the Perspective Crop tool's options.
|
||||
|
||||
use super::bar_words::CropBarWords;
|
||||
use super::size_cells::{self, SizeLimits};
|
||||
use super::{CropDocument, CropSizeFields};
|
||||
use craft_ui::contract::{Bind, NoValue, Outcome};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Gap, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft_ui::display::Divider;
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The Perspective Crop options: W × H × Resolution, Front Image, Clear, a divider and Show Grid.
|
||||
///
|
||||
/// - The fields hold W to 1 to 300 000 px and the resolution to 1 to 29 999.999 px/in (px/cm divides by 2.54); a
|
||||
/// typed value outside is kept at the limit and reported as [`PerspectiveCropBarOutput::out_of_range`].
|
||||
/// - Front Image fills W, H and the resolution from the document, rounded inward to the limits; Clear empties the
|
||||
/// three and puts the resolution unit back to px/in.
|
||||
#[must_use = "show the bar's children with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
|
||||
pub struct PerspectiveCropBar<'a> {
|
||||
@@ -20,9 +35,9 @@ pub struct PerspectiveCropBar<'a> {
|
||||
pub struct PerspectiveCropBarOutput {
|
||||
/// The strip's response.
|
||||
pub response: Response,
|
||||
/// A field changed.
|
||||
/// A field changed, or Front Image or Clear was pressed.
|
||||
pub changed: bool,
|
||||
/// A typed value was out of range.
|
||||
/// A typed value was out of range: the host opens the range alert.
|
||||
pub out_of_range: Option<craft_ui::text::RangeAlert>,
|
||||
}
|
||||
|
||||
@@ -42,8 +57,31 @@ impl<'a> PerspectiveCropBar<'a> {
|
||||
|
||||
/// Shows the bar's children.
|
||||
pub fn show(self, ui: &mut Ui) -> PerspectiveCropBarOutput {
|
||||
let PerspectiveCropBar { size, document, show_grid } = self;
|
||||
let _ = (ui, size, document, show_grid);
|
||||
todo!("tl.T48")
|
||||
let PerspectiveCropBar { size, document, mut show_grid } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<CropBarWords>();
|
||||
let units = env.units();
|
||||
let has_document = document.size.width > 0.0 && document.size.height > 0.0;
|
||||
let mut changed = false;
|
||||
let mut out_of_range = None;
|
||||
let shown = Row::new().gap(Gap::Item).show(ui, |ui, _| {
|
||||
let cells = size_cells::show(ui, size, SizeLimits::PERSPECTIVE, document, &units, &words);
|
||||
changed |= cells.changed;
|
||||
// The body can run more than once in a pass: a later run does not drop an alert an earlier one raised.
|
||||
if cells.out_of_range.is_some() {
|
||||
out_of_range = cells.out_of_range;
|
||||
}
|
||||
if clicked(&Button::new(words.front_image.clone()).enabled(has_document).show(ui)) {
|
||||
size.front_image(document, SizeLimits::PERSPECTIVE.front_limits(size.resolution_unit));
|
||||
changed = true;
|
||||
}
|
||||
if clicked(&Button::new(words.clear.clone()).show(ui)) {
|
||||
size.clear_size();
|
||||
changed = true;
|
||||
}
|
||||
Divider::vertical().show(ui);
|
||||
Checkbox::new(show_grid.reborrowed()).label(words.show_grid.clone()).show(ui);
|
||||
});
|
||||
PerspectiveCropBarOutput { response: shown.output, changed, out_of_range }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! Stories of the Perspective Crop options bar.
|
||||
|
||||
use super::super::options::{CropLength, CropSizeFields};
|
||||
use super::super::session::{CropDocKey, CropDocument};
|
||||
use super::PerspectiveCropBar;
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::contract::{Bind, ShowContainer as _};
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
use kurbo::Size;
|
||||
|
||||
#[story(PerspectiveCropBar<'static>, covers = [], drive = Drive::Never)]
|
||||
fn perspective_crop_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let document = CropDocument::new(CropDocKey::new(1), Size::new(2400.0, 1500.0), 72.0);
|
||||
let fields = CropSizeFields {
|
||||
width: Some(CropLength::new(1200.0, UnitKind::Pixels)),
|
||||
height: Some(CropLength::new(900.0, UnitKind::Pixels)),
|
||||
resolution: "300".into(),
|
||||
..CropSizeFields::default()
|
||||
};
|
||||
let (size, grid) = data.value("bar", (fields, true));
|
||||
let mut output = None;
|
||||
Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
|
||||
output = Some(PerspectiveCropBar::new(&mut *size, &document, Bind::bound(&mut *grid)).show(ui));
|
||||
});
|
||||
output.map(StoryOutput::from).unwrap_or_default()
|
||||
}
|
||||
@@ -4,10 +4,12 @@
|
||||
use craft_behavior::geometry::{Homography, screen_step};
|
||||
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
|
||||
use craft_behavior::{
|
||||
CanvasView, CursorIcon, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PartKey, PartRef, PointerButton, PressPhase, Roving, Sense,
|
||||
CanvasView, CursorIcon, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PaintedCursor, PartKey, PartRef, PointerButton, PressPhase,
|
||||
Roving, Sense,
|
||||
};
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::canvas::{CanvasSpace, NUDGE, NUDGE_FAR, canvas_space};
|
||||
use craft_ui::canvas::{CanvasSpace, CropShield, NUDGE, NUDGE_FAR, canvas_space, paint_outside};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Outcome, PaintUi, PartsCx, Pointer as _,
|
||||
Props as _, Remember as _, Role, Styled as _, WordSetCx as _,
|
||||
@@ -15,7 +17,7 @@ use craft_ui::contract::{
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{EnvView, Label};
|
||||
use craft_ui::runtime::focus::KeyUse;
|
||||
use craft_ui::style::{ComponentStyle, HandleLook, StyleColor, StyleCx};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, HandleLook, StyleColor, StyleCx};
|
||||
use egui::{CornerRadius, Pos2, Rect, Response, Vec2};
|
||||
|
||||
use super::words::CropWords;
|
||||
@@ -58,6 +60,19 @@ pub struct PerspectiveCropStyle {
|
||||
reach: f32,
|
||||
/// Screen points of the longest side per grid step.
|
||||
grid_step: f32,
|
||||
/// The canvas colour the shield may match.
|
||||
canvas: StyleColor,
|
||||
}
|
||||
|
||||
/// Screen points of the longest side per grid step: the one scale of the quad's grid and the tool's preview grid.
|
||||
pub(super) fn grid_step(cx: &StyleCx<'_>) -> f32 {
|
||||
cx.tokens.size.handle.md * GRID_CELL
|
||||
}
|
||||
|
||||
/// A perspective grid line: the white of the handles on the document, faded towards the canvas.
|
||||
pub(super) fn grid_color(cx: &StyleCx<'_>) -> StyleColor {
|
||||
let tokens = cx.tokens;
|
||||
craft_theme::Mix::mix(cx.color(tokens.color.overlay.handle_fill), cx.color(tokens.color.surface.canvas), GRID_FADE)
|
||||
}
|
||||
|
||||
/// What a drag does to the quad.
|
||||
@@ -90,6 +105,8 @@ struct Live {
|
||||
struct Report {
|
||||
apply: bool,
|
||||
discard: bool,
|
||||
/// A corner or the whole quad is being dragged: Auto Adjust Opacity lightens the shield.
|
||||
dragging: bool,
|
||||
}
|
||||
|
||||
/// The Perspective Crop tool's quad over the host's document, as Photoshop's Perspective Crop: the user marks four
|
||||
@@ -99,6 +116,9 @@ struct Report {
|
||||
///
|
||||
/// - The corner nearest the pointer within its reach moves alone, keeping the press offset; inside moves the quad. A
|
||||
/// press elsewhere reaches the tool.
|
||||
/// - Shift on a corner drag keeps the axis the pointer moved less along; Alt on a corner of an upright quad moves the
|
||||
/// neighbouring corners too, so it stays a rectangle.
|
||||
/// - With a `shield` the document outside a valid quad is dimmed, under the grid.
|
||||
/// - A quad that is not convex or is wound differently from its box draws in the invalid colour without the grid and
|
||||
/// cannot be committed.
|
||||
/// - The quad and its corners are one Tab stop. Page Down and Page Up pick the whole quad or a corner; the arrows move
|
||||
@@ -116,13 +136,16 @@ pub struct PerspectiveCropQuad<'a> {
|
||||
/// Whether a valid quad shows its perspective grid (Show Grid).
|
||||
#[prop]
|
||||
show_grid: bool,
|
||||
/// The shield painted over the document outside a valid quad; `None` paints none.
|
||||
#[prop]
|
||||
shield: Option<CropShield>,
|
||||
report: Report,
|
||||
}
|
||||
|
||||
impl<'a> PerspectiveCropQuad<'a> {
|
||||
/// A quad named `label` over `quad`, in document units.
|
||||
pub fn new(label: impl Into<Label>, quad: Bind<'a, PerspectiveQuad>) -> Self {
|
||||
PerspectiveCropQuad { common: Common::new(), quad, show_grid: true, report: Report::default() }.label(label)
|
||||
PerspectiveCropQuad { common: Common::new(), quad, show_grid: true, shield: None, report: Report::default() }.label(label)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,12 +190,40 @@ fn shown(value: Option<&PerspectiveQuad>) -> Option<[Point; 4]> {
|
||||
value.copied().flatten().filter(finite)
|
||||
}
|
||||
|
||||
/// The quad a drag gives with the pointer at document point `to`.
|
||||
fn dragged(drag: &Drag, to: Point) -> [Point; 4] {
|
||||
/// Whether `q` is an upright rectangle in quad order: top left, top right, bottom right, bottom left.
|
||||
fn upright(q: &[Point; 4]) -> bool {
|
||||
let same = |a: f64, b: f64| (a - b).abs() < 1e-6;
|
||||
same(q[0].y, q[1].y) && same(q[1].x, q[2].x) && same(q[2].y, q[3].y) && same(q[3].x, q[0].x)
|
||||
}
|
||||
|
||||
/// The quad a drag gives with the pointer at document point `to` and `mods` held at this step; it reads only the
|
||||
/// step's own modifiers, so a released key puts the quad back as the press had it.
|
||||
///
|
||||
/// - Shift keeps the press position's coordinate of the corner on the axis the drag moved less along.
|
||||
/// - Alt on a corner of an upright quad moves the two neighbouring corners one coordinate each, so it stays a
|
||||
/// rectangle, put in order when the corner passes the opposite one. A skewed quad's corner moves alone.
|
||||
fn dragged(drag: &Drag, to: Point, mods: Mods) -> [Point; 4] {
|
||||
match drag.grab {
|
||||
Grab::Corner { index, offset } => {
|
||||
let from = drag.at_press[index];
|
||||
let mut target = to - offset;
|
||||
if mods.shift {
|
||||
if (target.x - from.x).abs() >= (target.y - from.y).abs() {
|
||||
target.y = from.y;
|
||||
} else {
|
||||
target.x = from.x;
|
||||
}
|
||||
}
|
||||
let mut quad = drag.at_press;
|
||||
quad[index] = to - offset;
|
||||
quad[index] = target;
|
||||
if mods.alt && upright(&drag.at_press) {
|
||||
let (next, prev) = ((index + 1) % 4, (index + 3) % 4);
|
||||
// The corner shares its row with one neighbour and its column with the other.
|
||||
let (in_row, in_column) = if index % 2 == 0 { (next, prev) } else { (prev, next) };
|
||||
quad[in_row].y = target.y;
|
||||
quad[in_column].x = target.x;
|
||||
return ordered(quad);
|
||||
}
|
||||
quad
|
||||
}
|
||||
Grab::Move => {
|
||||
@@ -195,8 +246,8 @@ impl PerspectiveCropQuad<'_> {
|
||||
}
|
||||
|
||||
/// Follows the pointer at screen point `pos`.
|
||||
fn step(cx: &mut Cx<'_, Self>, view: &CanvasView, drag: &Drag, pos: Pos2) {
|
||||
let next = dragged(drag, view.to_doc(pos));
|
||||
fn step(cx: &mut Cx<'_, Self>, view: &CanvasView, drag: &Drag, pos: Pos2, mods: Mods) {
|
||||
let next = dragged(drag, view.to_doc(pos), mods);
|
||||
if finite(&next) {
|
||||
cx.propose(Some(next));
|
||||
}
|
||||
@@ -244,9 +295,10 @@ impl Component for PerspectiveCropQuad<'_> {
|
||||
line,
|
||||
halo: cx.color(tokens.color.overlay.halo),
|
||||
invalid: cx.tone(Tone::Bad),
|
||||
grid: craft_theme::Mix::mix(cx.color(tokens.color.overlay.handle_fill), canvas, GRID_FADE),
|
||||
grid: grid_color(cx),
|
||||
reach: tokens.size.hit.target,
|
||||
grid_step: tokens.size.handle.md * GRID_CELL,
|
||||
grid_step: grid_step(cx),
|
||||
canvas,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +325,7 @@ impl Component for PerspectiveCropQuad<'_> {
|
||||
cx.part(CORNER.at(at as u64), HitShape::circle(corner, cx.style.reach))
|
||||
.sense(Sense::DRAG | Sense::TAKE_FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Handle, 0))
|
||||
.cursor(CursorIcon::Move)
|
||||
.cursor(PaintedCursor::arrow(false))
|
||||
.focusable();
|
||||
}
|
||||
cx.roving(Roving::new(NavShape::Flat).page(Some(1)));
|
||||
@@ -288,15 +340,17 @@ impl Component for PerspectiveCropQuad<'_> {
|
||||
for (part, corner) in grabs {
|
||||
let Some(result) = cx.part_if_declared(part) else { continue };
|
||||
let press = result.press;
|
||||
// Only this pass's own modifiers apply: a second pass of the frame reads the same press state.
|
||||
let mods = press.mods;
|
||||
match press.phase {
|
||||
PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => {
|
||||
let drag = Self::begin(cx, &view, quad, corner, start.origin);
|
||||
Self::step(cx, &view, &drag, pos);
|
||||
Self::step(cx, &view, &drag, pos, mods);
|
||||
live.drag = Some(drag);
|
||||
}
|
||||
PressPhase::Drag { pos, .. } => {
|
||||
if let Some(drag) = live.drag {
|
||||
Self::step(cx, &view, &drag, pos);
|
||||
Self::step(cx, &view, &drag, pos, mods);
|
||||
}
|
||||
}
|
||||
PressPhase::Release { start, pos, click: false, .. } => {
|
||||
@@ -307,7 +361,7 @@ impl Component for PerspectiveCropQuad<'_> {
|
||||
None => None,
|
||||
};
|
||||
if let Some(drag) = drag {
|
||||
Self::step(cx, &view, &drag, pos);
|
||||
Self::step(cx, &view, &drag, pos, mods);
|
||||
cx.commit();
|
||||
}
|
||||
}
|
||||
@@ -315,6 +369,7 @@ impl Component for PerspectiveCropQuad<'_> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.report.dragging = live.drag.is_some();
|
||||
self.run_keys(cx, &view, quad);
|
||||
*cx.memory::<Live>() = live;
|
||||
}
|
||||
@@ -327,6 +382,14 @@ impl Component for PerspectiveCropQuad<'_> {
|
||||
let style = &cx.style;
|
||||
let draw = ui.draw();
|
||||
let screen: Vec<Pos2> = quad.iter().map(|p| view.to_screen(*p)).collect();
|
||||
// The shield dims the document outside a quad that can be committed, before the grid.
|
||||
if valid && let (Some(shield), Some(document)) = (&self.shield, space.document()) {
|
||||
let (w, h) = (document.width, document.height);
|
||||
let canvas = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| view.to_screen(p));
|
||||
if let Some(fill) = shield.fill_on(&space, style.canvas.egui(), self.report.dragging) {
|
||||
paint_outside(&draw, canvas, &screen, DataColor::new(fill));
|
||||
}
|
||||
}
|
||||
if valid && self.show_grid {
|
||||
for [a, b] in grid_lines(&view, &quad, style.grid_step) {
|
||||
draw.stroke(&PaintShape::Path(vec![a, b]), StrokeWidth::Thin, style.grid);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Stories of the perspective crop quad, and of the Perspective Crop tool run live: with no quad a drag draws a box
|
||||
//! and four clicks place the corners; then the quad takes its own gestures, and Enter or Esc ends the crop.
|
||||
|
||||
use super::super::PerspectiveCropTool;
|
||||
use super::super::{PerspectiveCropTool, PerspectiveInput};
|
||||
use super::{CORNER, PerspectiveCropQuad, PerspectiveQuad};
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::{BezPath, Point};
|
||||
use craft_ui::canvas::RasterSource as _;
|
||||
use craft_ui::canvas::{CropShield, RasterSource as _};
|
||||
use craft_ui::contract::{Bind, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::canvas_story::{OUTLINE, StoryDocument, StoryPicture, StoryShape, on_picture, paint_shapes};
|
||||
@@ -39,7 +39,9 @@ fn on_canvas<R: Into<StoryOutput>>(ui: &mut Ui, mut quad: impl FnMut(&mut Ui, eg
|
||||
#[story(PerspectiveCropQuad<'static>, covers = [Default], drive = Drive::Drag(Grip::part(CORNER.at(0))))]
|
||||
fn skewed_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let quad = data.value("quad", Some(PAGE));
|
||||
on_canvas(ui, |ui, at| PerspectiveCropQuad::new("Perspective crop", Bind::bound(&mut *quad)).show_at(ui, at).edit)
|
||||
on_canvas(ui, |ui, at| {
|
||||
PerspectiveCropQuad::new("Perspective crop", Bind::bound(&mut *quad)).shield(CropShield::PERSPECTIVE).show_at(ui, at).edit
|
||||
})
|
||||
}
|
||||
|
||||
#[story(PerspectiveCropQuad<'static>, covers = [Invalid], drive = Drive::Drag(Grip::part(CORNER.at(0))))]
|
||||
@@ -63,13 +65,13 @@ fn drawing_a_quad(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
if tool.quad() != quad {
|
||||
tool.set(*quad);
|
||||
}
|
||||
let shown = PerspectiveCropQuad::new("Perspective crop", Bind::bound(tool.quad_mut())).show_at(ui, at);
|
||||
let shown = tool.pass(PerspectiveInput::default()).show_quad(ui, at);
|
||||
if shown.apply || shown.discard {
|
||||
tool.clear();
|
||||
}
|
||||
};
|
||||
tool_story(ui, data, ToolStory::new("Document", &picture), PerspectiveCropTool::new, None, body, |run| {
|
||||
let _ = run.host.run(run.tool);
|
||||
let _ = run.host.run(&mut run.tool.pass(PerspectiveInput::default()));
|
||||
let _ = run.tool.take_events();
|
||||
*run.document = *run.tool.quad();
|
||||
StoryOutput::default()
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
//! [`PerspectiveCropTool`]: the Perspective Crop tool's background presses. A box drag draws an upright quad, and four
|
||||
//! clicks place its corners one by one. Once a quad exists, [`PerspectiveCropQuad`](super::PerspectiveCropQuad)
|
||||
//! takes the presses on its corners and inside, and a press elsewhere does nothing.
|
||||
//! takes the presses on its corners and inside, and a press elsewhere does nothing. The tool is a canvas tool for
|
||||
//! one pass through [`PerspectiveCropPass`].
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::geometry::Constraint;
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, Mixed};
|
||||
use craft_ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, IconId, Mixed, PaintedCursor};
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::canvas::{CanvasTool, CropShield, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::patterns::form_dialogs::{Param, ParamDialog, ParamKind};
|
||||
use craft_ui::primitives::{Draw, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use egui::Pos2;
|
||||
|
||||
use super::perspective_crop::{PerspectiveQuad, ordered};
|
||||
use super::perspective_crop::{PerspectiveCropOutput, PerspectiveCropQuad, PerspectiveQuad, grid_color, grid_lines, grid_step, is_valid, ordered};
|
||||
use super::words::CropWords;
|
||||
|
||||
/// The key of the Perspective Crop To... command form.
|
||||
@@ -41,12 +46,14 @@ struct Press {
|
||||
began: bool,
|
||||
}
|
||||
|
||||
/// The Perspective Crop tool, kept by the app. It owns the quad: show it in the canvas body as
|
||||
/// `PerspectiveCropQuad::new(label, Bind::bound(tool.quad_mut()))`, and read the tool's own edits with
|
||||
/// [`take_events`](Self::take_events).
|
||||
/// The Perspective Crop tool, kept by the app. It owns the quad: show it in the canvas body with
|
||||
/// [`PerspectiveCropPass::show_quad`], and read the tool's own edits with [`take_events`](Self::take_events).
|
||||
///
|
||||
/// - With no quad, a drag draws an upright box (none while it has no area), and four clicks place corners one by one;
|
||||
/// the fourth makes the quad, corners put in order. A drag clears the clicks.
|
||||
/// the fourth makes the quad, corners put in order. A drag that makes a box clears the clicks; one that makes none
|
||||
/// keeps them.
|
||||
/// - Shift makes the box square and Alt draws it from its centre.
|
||||
/// - After two or three clicks a quad to the pointer previews the corners to come.
|
||||
/// - Esc drops the pending clicks. Once a quad exists, the quad's control takes Enter, Esc and the arrows
|
||||
/// ([`PerspectiveCropOutput::apply`](super::PerspectiveCropOutput::apply) and
|
||||
/// [`discard`](super::PerspectiveCropOutput::discard)).
|
||||
@@ -104,14 +111,19 @@ fn boxed(anchor: Point, to: Point) -> PerspectiveQuad {
|
||||
(x1 > x0 && y1 > y0).then_some([Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)])
|
||||
}
|
||||
|
||||
/// Whether `q` is convex whichever way it is wound: the preview of corners clicked in any order.
|
||||
fn convex(q: &[Point; 4]) -> bool {
|
||||
is_valid(q) || is_valid(&[q[0], q[3], q[2], q[1]])
|
||||
}
|
||||
|
||||
/// What the host hands the perspective crop pass each frame.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct PerspectiveInput<'a> {
|
||||
/// Whether the quad's grid shows.
|
||||
pub show_grid: bool,
|
||||
/// Ties the input to the pass's lifetime until the shield (tl.T44, not in this checkout) joins it.
|
||||
pub marker: std::marker::PhantomData<&'a ()>,
|
||||
/// The shield over the area outside the quad; `None` shows none.
|
||||
pub shield: Option<&'a CropShield>,
|
||||
}
|
||||
|
||||
/// This pass's perspective crop tool for the host, borrowing its input; it is the canvas tool while the pass lives.
|
||||
@@ -129,125 +141,121 @@ impl PerspectiveCropTool {
|
||||
|
||||
impl PerspectiveCropPass<'_> {
|
||||
/// Shows the quad over the canvas at `canvas_rect` and reports its edits.
|
||||
pub fn show_quad(&mut self, ui: &mut egui::Ui, canvas_rect: egui::Rect) -> super::PerspectiveCropOutput {
|
||||
let _ = (&self.tool, &self.input, ui, canvas_rect);
|
||||
todo!("tl.T48")
|
||||
pub fn show_quad(&mut self, ui: &mut egui::Ui, canvas_rect: egui::Rect) -> PerspectiveCropOutput {
|
||||
let label = Env::of(ui).words::<CropWords>().perspective_group.clone();
|
||||
let mut quad = PerspectiveCropQuad::new(label, Bind::bound(&mut self.tool.quad)).show_grid(self.input.show_grid);
|
||||
if let Some(shield) = self.input.shield {
|
||||
quad = quad.shield(shield.clone());
|
||||
}
|
||||
quad.show_at(ui, canvas_rect)
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasTool for PerspectiveCropPass<'_> {
|
||||
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
|
||||
self.tool.press(pointer, cx)
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.tool.drag(pointer, cx);
|
||||
}
|
||||
|
||||
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.tool.release(pointer, cx);
|
||||
}
|
||||
|
||||
fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) {
|
||||
self.tool.cancel(reason, cx);
|
||||
}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool {
|
||||
self.tool.key(key, cx)
|
||||
}
|
||||
|
||||
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
|
||||
self.tool.paint(draw, cx);
|
||||
}
|
||||
|
||||
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
|
||||
self.tool.cursor(cx)
|
||||
}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
self.tool.command_form()
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasTool for PerspectiveCropTool {
|
||||
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
|
||||
let Some(space) = cx.space() else { return ToolAction::Ignored };
|
||||
let anchor = space.view.to_doc(pointer.pos);
|
||||
if self.quad.is_some() || !(anchor.x.is_finite() && anchor.y.is_finite()) {
|
||||
if self.tool.quad.is_some() || !(anchor.x.is_finite() && anchor.y.is_finite()) {
|
||||
return ToolAction::Ignored;
|
||||
}
|
||||
let Some(id) = cx.gesture_id() else { return ToolAction::Ignored };
|
||||
self.press = Some(Press { id, anchor, origin: pointer.pos, before: self.quad, began: false });
|
||||
self.tool.press = Some(Press { id, anchor, origin: pointer.pos, before: self.tool.quad, began: false });
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
let (Some(mut press), Some(space)) = (self.press, cx.space()) else { return };
|
||||
let (Some(mut press), Some(space)) = (self.tool.press, cx.space()) else { return };
|
||||
if !press.began && (pointer.pos - press.origin).abs().max_elem() > cx.slop {
|
||||
press.began = true;
|
||||
self.clicks.clear();
|
||||
let label: Arc<str> = Arc::from(cx.words::<CropWords>().perspective_group.as_str());
|
||||
self.events.push(PerspectiveCropEvent::Edit(EditEvent::begin(press.id, Mixed::Same(press.before), label, None)));
|
||||
self.tool.events.push(PerspectiveCropEvent::Edit(EditEvent::begin(press.id, Mixed::Same(press.before), label, None)));
|
||||
}
|
||||
if press.began {
|
||||
self.quad = boxed(press.anchor, space.view.to_doc(pointer.pos));
|
||||
self.events.push(PerspectiveCropEvent::Edit(EditEvent::update(press.id, self.quad)));
|
||||
let (a, b) = Constraint::Free.corners(press.anchor, space.view.to_doc(pointer.pos), pointer.mods.shift, pointer.mods.alt);
|
||||
self.tool.quad = boxed(a, b);
|
||||
if self.tool.quad.is_some() {
|
||||
// A drag that makes no box keeps the corners clicked so far.
|
||||
self.tool.clicks.clear();
|
||||
}
|
||||
self.tool.events.push(PerspectiveCropEvent::Edit(EditEvent::update(press.id, self.tool.quad)));
|
||||
}
|
||||
self.press = Some(press);
|
||||
self.tool.press = Some(press);
|
||||
}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
let Some(press) = self.press.take() else { return };
|
||||
let Some(press) = self.tool.press.take() else { return };
|
||||
if press.began {
|
||||
self.events.push(PerspectiveCropEvent::Edit(EditEvent::commit(press.id, Mixed::Same(press.before), self.quad)));
|
||||
self.tool.events.push(PerspectiveCropEvent::Edit(EditEvent::commit(press.id, Mixed::Same(press.before), self.tool.quad)));
|
||||
return;
|
||||
}
|
||||
self.clicks.push(press.anchor);
|
||||
if let [a, b, c, d] = self.clicks[..] {
|
||||
self.clicks.clear();
|
||||
self.tool.clicks.push(press.anchor);
|
||||
if let [a, b, c, d] = self.tool.clicks[..] {
|
||||
self.tool.clicks.clear();
|
||||
let quad = Some(ordered([a, b, c, d]));
|
||||
let label: Arc<str> = Arc::from(cx.words::<CropWords>().perspective_group.as_str());
|
||||
self.quad = quad;
|
||||
self.events.push(PerspectiveCropEvent::Edit(EditEvent::set(Mixed::Same(press.before), quad, label, None)));
|
||||
self.tool.quad = quad;
|
||||
self.tool.events.push(PerspectiveCropEvent::Edit(EditEvent::set(Mixed::Same(press.before), quad, label, None)));
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&mut self, reason: CancelReason, _: &mut ToolContext<'_>) {
|
||||
let Some(press) = self.press.take() else { return };
|
||||
let Some(press) = self.tool.press.take() else { return };
|
||||
if press.began {
|
||||
self.quad = press.before;
|
||||
self.events.push(PerspectiveCropEvent::Edit(EditEvent::cancel(press.id, reason, Some(Mixed::Same(press.before)))));
|
||||
self.tool.quad = press.before;
|
||||
self.tool.events.push(PerspectiveCropEvent::Edit(EditEvent::cancel(press.id, reason, Some(Mixed::Same(press.before)))));
|
||||
}
|
||||
}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool {
|
||||
match key {
|
||||
ToolKey::Cancel if !self.clicks.is_empty() => {
|
||||
self.clicks.clear();
|
||||
ToolKey::Cancel if !self.tool.clicks.is_empty() => {
|
||||
self.tool.clicks.clear();
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The corners clicked so far, joined by a line.
|
||||
/// The corners clicked so far, and with two or three of them the quad to the pointer: the corners to come sit
|
||||
/// at the pointer.
|
||||
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
|
||||
let (Some(space), Some(style)) = (cx.space(), cx.style()) else { return };
|
||||
let dots: Vec<Pos2> = self.clicks.iter().map(|click| space.view.to_screen(*click)).collect();
|
||||
let view = &space.view;
|
||||
let clicks = &self.tool.clicks;
|
||||
let handle = style.handle();
|
||||
let line = style.color(style.tokens.color.overlay.line);
|
||||
if dots.len() > 1 {
|
||||
draw.stroke(&PaintShape::Path(dots.clone()), StrokeWidth::Medium, line);
|
||||
let pointer = cx.pointer.as_ref().map(|p| view.to_doc(p.pos)).filter(|p| p.x.is_finite() && p.y.is_finite());
|
||||
let preview = match (clicks.as_slice(), pointer) {
|
||||
([a, b], Some(p)) => Some([*a, *b, p, p]),
|
||||
([a, b, c], Some(p)) => Some([*a, *b, *c, p]),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(quad) = preview {
|
||||
let ok = clicks.len() == 2 || convex(&quad);
|
||||
if ok && self.input.show_grid {
|
||||
let grid = grid_color(style);
|
||||
for [a, b] in grid_lines(view, &quad, grid_step(style)) {
|
||||
draw.stroke(&PaintShape::Path(vec![a, b]), StrokeWidth::Thin, grid);
|
||||
}
|
||||
}
|
||||
let outline = PaintShape::Polygon(quad.iter().map(|p| view.to_screen(*p)).collect());
|
||||
draw.stroke(&outline, StrokeWidth::Medium, if ok { line } else { style.tone(Tone::Bad) });
|
||||
} else if clicks.len() > 1 {
|
||||
draw.stroke(&PaintShape::Path(clicks.iter().map(|c| view.to_screen(*c)).collect()), StrokeWidth::Medium, line);
|
||||
}
|
||||
for dot in dots {
|
||||
let shape = PaintShape::Circle(dot, handle.side / 2.0);
|
||||
for click in clicks {
|
||||
let shape = PaintShape::Circle(view.to_screen(*click), handle.side / 2.0);
|
||||
draw.fill(&shape, handle.fill.off.rest);
|
||||
draw.stroke(&shape, StrokeWidth::Thin, line);
|
||||
}
|
||||
}
|
||||
|
||||
fn cursor(&self, _: &ToolContext<'_>) -> Cursor {
|
||||
Cursor::System(if self.quad.is_none() { CursorIcon::Crosshair } else { CursorIcon::Default })
|
||||
if self.tool.quad.is_none() {
|
||||
PaintedCursor::crosshair_tool(IconId::new("perspective_crop")).into()
|
||||
} else {
|
||||
Cursor::System(CursorIcon::Default)
|
||||
}
|
||||
}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
//! [`CropPresetList`]: the crop preset list as one cell for the crop bar and the task bar.
|
||||
|
||||
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::{NoValue, Outcome};
|
||||
use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Units};
|
||||
use egui::{Response, Ui};
|
||||
|
||||
/// The preset list: Free, Size, the ratios, the sizes, the user presets, Front Image, New, Delete,
|
||||
/// and From Selection when [`selection_entry`](Self::selection_entry) is set. Picks go through
|
||||
/// and Selection when [`selection_entry`](Self::selection_entry) is set. Picks go through
|
||||
/// `CropSettings::choose`.
|
||||
#[must_use = "show the list with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
|
||||
@@ -15,9 +19,12 @@ pub struct CropPresetList<'a> {
|
||||
/// The user's saved crop presets, oldest first.
|
||||
#[prop]
|
||||
user_presets: &'a [CropUserPreset],
|
||||
/// Offers From Selection.
|
||||
/// Offers Selection as the first entry.
|
||||
#[prop]
|
||||
selection_entry: bool,
|
||||
/// Shows Selection as the chosen entry (`CropTool::shows_selection_entry`); it takes effect with the entry offered.
|
||||
#[prop]
|
||||
selection_chosen: bool,
|
||||
}
|
||||
|
||||
/// What [`CropPresetList::show`] returns.
|
||||
@@ -33,7 +40,7 @@ pub struct CropPresetListOutput {
|
||||
pub new_preset: bool,
|
||||
/// Delete Crop Preset… was picked.
|
||||
pub delete_preset: bool,
|
||||
/// From Selection was picked.
|
||||
/// Selection was picked: the app calls `CropTool::take_selection_frame`.
|
||||
pub selection: bool,
|
||||
}
|
||||
|
||||
@@ -45,16 +52,67 @@ impl Outcome for CropPresetListOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of size preset `index` of [`CROP_SIZES`]: its values as New Crop Preset… would name them.
|
||||
fn size_name(words: &CropBarWords, index: usize, units: &Units) -> String {
|
||||
let Some(preset) = CROP_SIZES.get(index) else { return String::new() };
|
||||
let size = CropSizeFields {
|
||||
width: Some(preset.width),
|
||||
height: Some(preset.height),
|
||||
resolution: preset.resolution.to_owned(),
|
||||
..CropSizeFields::default()
|
||||
};
|
||||
let settings = CropSettings { ratio: CropRatio::Size, size, ..CropSettings::default() };
|
||||
settings.preset_name(words, units).unwrap_or_default()
|
||||
}
|
||||
|
||||
impl<'a> CropPresetList<'a> {
|
||||
/// The list editing `settings` over `document`.
|
||||
pub fn new(settings: &'a mut CropSettings, document: &'a CropDocument) -> Self {
|
||||
CropPresetList { settings, document, user_presets: &[], selection_entry: false }
|
||||
CropPresetList { settings, document, user_presets: &[], selection_entry: false, selection_chosen: false }
|
||||
}
|
||||
|
||||
/// Shows the list.
|
||||
pub fn show(self, ui: &mut Ui) -> CropPresetListOutput {
|
||||
let CropPresetList { settings, document, user_presets, selection_entry } = self;
|
||||
let _ = (ui, settings, document, user_presets, selection_entry);
|
||||
todo!("tl.T46")
|
||||
let CropPresetList { settings, document, user_presets, selection_entry, selection_chosen } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<CropBarWords>();
|
||||
let units = env.units();
|
||||
let has_document = document.size.width > 0.0 && document.size.height > 0.0;
|
||||
let mut entries = Vec::new();
|
||||
if selection_entry {
|
||||
entries.push(Entry::new(CropPresetChoice::Selection, words.selection.clone()));
|
||||
}
|
||||
entries.push(Entry::new(CropPresetChoice::Free, words.ratio.clone()));
|
||||
entries.push(Entry::new(CropPresetChoice::Size, words.size_mode.clone()));
|
||||
for (i, ratio) in CROP_RATIOS.iter().enumerate() {
|
||||
let entry = Entry::new(CropPresetChoice::Ratio(i), words.ratio_name(i).to_owned());
|
||||
entries.push(if *ratio == CropRatio::Original { entry.enabled(has_document) } else { entry });
|
||||
}
|
||||
for i in 0..CROP_SIZES.len() {
|
||||
entries.push(Entry::new(CropPresetChoice::SizePreset(i), size_name(&words, i, &units)));
|
||||
}
|
||||
for (i, preset) in user_presets.iter().enumerate() {
|
||||
entries.push(Entry::new(CropPresetChoice::User(i), preset.name.clone()));
|
||||
}
|
||||
entries.push(Entry::new(CropPresetChoice::FrontImage, words.front_image.clone()).enabled(has_document));
|
||||
entries.push(Entry::separator());
|
||||
entries.push(Entry::new(CropPresetChoice::NewPreset, words.new_preset.clone()).enabled(settings.preset_name(&words, &units).is_some()));
|
||||
entries.push(Entry::new(CropPresetChoice::DeletePreset, words.delete_preset.clone()).enabled(!user_presets.is_empty()));
|
||||
let current = if selection_chosen { CropPresetChoice::Selection } else { settings.choice(user_presets) };
|
||||
let pick = Select::new(words.presets.clone(), Bind::given(current), &entries).show(ui);
|
||||
let response = pick.response().clone();
|
||||
let mut out = CropPresetListOutput { response, ratio: None, new_preset: false, delete_preset: false, selection: false };
|
||||
let Some(choice) = pick.value().copied() else { return out };
|
||||
match choice {
|
||||
CropPresetChoice::NewPreset => out.new_preset = true,
|
||||
CropPresetChoice::DeletePreset => out.delete_preset = true,
|
||||
choice => {
|
||||
out.selection = choice == CropPresetChoice::Selection;
|
||||
if settings.choose(choice, document, user_presets) {
|
||||
out.ratio = Some(CropRatioChange { editing: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +1,82 @@
|
||||
//! The W × H × Resolution cells both crop bars share, and the rules on [`CropSizeFields`].
|
||||
|
||||
use super::options::{CropLength, FIELD_MAX, LENGTH_MIN, ResolutionUnit, trim_number};
|
||||
use super::{CropBarWords, CropDocument, CropSizeFields};
|
||||
use craft_ui::runtime::env::Units;
|
||||
use craft_behavior::{IconId, NumberCodec};
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing, clicked};
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{LengthUnits, UnitKind, Units};
|
||||
use craft_ui::text::{NumberField, RangeAlert};
|
||||
use egui::Ui;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// Pixels per inch in one pixel per centimetre: 1 px/cm is 2.54 px/in.
|
||||
const CM_PER_INCH: f64 = 2.54;
|
||||
|
||||
/// The ranges of the cells' fields.
|
||||
#[allow(dead_code)] // P3(tools-w14): tl.T47
|
||||
///
|
||||
/// A range is in the field's own unit (a W typed in inches is held to a range of inches, a resolution in px/cm to a
|
||||
/// range of px/cm) unless `in_pixels` is set. Then `length` is in pixels and `resolution` in px/in, and the cells
|
||||
/// convert both into the field's unit at the field's resolution; a resolution range converted to px/cm is rounded
|
||||
/// inward to `resolution_decimals`, so a stored value never converts past the limit.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct SizeLimits {
|
||||
/// The length range.
|
||||
pub length: (f64, f64),
|
||||
/// The resolution range.
|
||||
pub resolution: (f64, f64),
|
||||
/// Whether the ranges are in pixels and px/in rather than the field's own unit.
|
||||
pub in_pixels: bool,
|
||||
/// The decimals the resolution field keeps.
|
||||
pub resolution_decimals: usize,
|
||||
}
|
||||
|
||||
/// What the cells reported this pass.
|
||||
#[allow(dead_code)] // P3(tools-w14): tl.T47
|
||||
pub(super) struct SizeCells {
|
||||
/// A field changed.
|
||||
pub changed: bool,
|
||||
/// A typed value was out of range.
|
||||
pub out_of_range: Option<craft_ui::text::RangeAlert>,
|
||||
pub out_of_range: Option<RangeAlert>,
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // P3(tools-w14): tl.T47
|
||||
impl SizeLimits {
|
||||
/// The crop bar's ranges, in the field's own unit.
|
||||
pub(super) const CROP: Self = Self { length: (0.0, 0.0), resolution: (0.0, 0.0) };
|
||||
/// The perspective bar's ranges, in pixels.
|
||||
pub(super) const PERSPECTIVE: Self = Self { length: (0.0, 0.0), resolution: (0.0, 0.0) };
|
||||
/// The crop bar's ranges, in the field's own unit; its fields never alert.
|
||||
pub(super) const CROP: Self = Self { length: (LENGTH_MIN, FIELD_MAX), resolution: (0.0, FIELD_MAX), in_pixels: false, resolution_decimals: 2 };
|
||||
/// The perspective bar's ranges: 1 to 300 000 px and 1 to 29 999.999 px/in.
|
||||
pub(super) const PERSPECTIVE: Self =
|
||||
Self { length: (1.0, 300_000.0), resolution: (1.0, 29_999.999), in_pixels: true, resolution_decimals: 3 };
|
||||
|
||||
/// The length range in `unit`, at `pixels_per_inch` and `points_per_inch`.
|
||||
fn length_range(&self, unit: UnitKind, pixels_per_inch: f64, points_per_inch: f64) -> RangeInclusive<f64> {
|
||||
if !self.in_pixels {
|
||||
return self.length.0..=self.length.1;
|
||||
}
|
||||
let at = |pixels: f64| unit.from_pixels(pixels, 1.0, pixels_per_inch, points_per_inch);
|
||||
match (at(self.length.0), at(self.length.1)) {
|
||||
(Some(low), Some(high)) if low <= high => low..=high,
|
||||
_ => LENGTH_MIN..=FIELD_MAX,
|
||||
}
|
||||
}
|
||||
|
||||
/// The resolution range in `unit`, rounded inward to the decimals the field keeps.
|
||||
pub(super) fn resolution_bounds(&self, unit: ResolutionUnit) -> (f64, f64) {
|
||||
let per_unit = match unit {
|
||||
ResolutionUnit::PixelsPerCentimetre if self.in_pixels => CM_PER_INCH,
|
||||
_ => 1.0,
|
||||
};
|
||||
let scale = 10f64.powi(self.resolution_decimals as i32);
|
||||
((self.resolution.0 / per_unit * scale).ceil() / scale, (self.resolution.1 / per_unit * scale).floor() / scale)
|
||||
}
|
||||
|
||||
/// The resolution range Front Image rounds into: given only for ranges in pixels.
|
||||
pub(super) fn front_limits(&self, unit: ResolutionUnit) -> Option<(f64, f64)> {
|
||||
self.in_pixels.then(|| self.resolution_bounds(unit))
|
||||
}
|
||||
}
|
||||
|
||||
/// One W × H × Resolution cell group.
|
||||
#[allow(dead_code)] // P3(tools-w14): tl.T47
|
||||
/// W, swap, H, Resolution and its unit.
|
||||
pub(super) fn show(
|
||||
ui: &mut Ui,
|
||||
size: &mut CropSizeFields,
|
||||
@@ -40,8 +85,101 @@ pub(super) fn show(
|
||||
units: &Units,
|
||||
words: &CropBarWords,
|
||||
) -> SizeCells {
|
||||
let _ = (ui, size, limits, document, units, words);
|
||||
todo!("tl.T47")
|
||||
let mut changed = false;
|
||||
let mut out_of_range = None;
|
||||
let points_per_inch = units.points_per_inch();
|
||||
let pixels_per_inch = size.resolution_ppi().unwrap_or(document.resolution);
|
||||
changed |= length_field(ui, "size-width", &words.width, &mut size.width, pixels_per_inch, points_per_inch, &limits, &mut out_of_range);
|
||||
if clicked(&IconButton::new(IconId::new("swap_horizontal")).label(words.swap.clone()).show(ui)) {
|
||||
size.swap();
|
||||
changed = true;
|
||||
}
|
||||
changed |= length_field(ui, "size-height", &words.height, &mut size.height, pixels_per_inch, points_per_inch, &limits, &mut out_of_range);
|
||||
|
||||
let unit = size.resolution_unit;
|
||||
let (low, high) = limits.resolution_bounds(unit);
|
||||
let resolution = size.resolution.trim().replace(',', ".").parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0);
|
||||
let mut typed = None;
|
||||
let mut alert = None;
|
||||
Field::new(words.resolution.clone()).id_salt("size-resolution").sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
let codec = NumberCodec::new(units.reader(None), limits.resolution_decimals);
|
||||
let field = NumberField::new(words.resolution.clone(), Bind::given(resolution)).codec(codec).range(low..=high).automatic(true).show(ui);
|
||||
typed = field.value().copied();
|
||||
alert = field.out_of_range;
|
||||
});
|
||||
if alert.is_some() {
|
||||
out_of_range = alert;
|
||||
}
|
||||
if let Some(value) = typed {
|
||||
let text = value.filter(|v| *v > 0.0).map_or_else(String::new, |v| trim_number(v.clamp(low, high), limits.resolution_decimals));
|
||||
if text != size.resolution {
|
||||
size.resolution = text;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
let unit_entries = [
|
||||
Entry::new(ResolutionUnit::PixelsPerInch, words.pixels_per_inch.clone()),
|
||||
Entry::new(ResolutionUnit::PixelsPerCentimetre, words.pixels_per_centimetre.clone()),
|
||||
];
|
||||
let pick = Select::new(words.resolution_unit.clone(), Bind::given(size.resolution_unit), &unit_entries).show(ui);
|
||||
if let Some(next) = pick.value().copied()
|
||||
&& next != size.resolution_unit
|
||||
{
|
||||
// The same resolution in the other unit, as in Photoshop.
|
||||
if let Some(v) = resolution {
|
||||
let converted = if next == ResolutionUnit::PixelsPerCentimetre { v / CM_PER_INCH } else { v * CM_PER_INCH };
|
||||
let (low, high) = limits.resolution_bounds(next);
|
||||
size.resolution = trim_number(converted.clamp(low, high), limits.resolution_decimals);
|
||||
}
|
||||
size.resolution_unit = next;
|
||||
changed = true;
|
||||
}
|
||||
SizeCells { changed, out_of_range }
|
||||
}
|
||||
|
||||
/// A length field over a length kept in its own unit: a typed number is in that unit (pixels while unset), a typed
|
||||
/// unit is converted into it, and a cleared field is unset. Returns whether `value` changed; a typed value outside
|
||||
/// the range of `limits` is clamped and reported in `out_of_range`.
|
||||
#[expect(clippy::too_many_arguments, reason = "the cells' inputs")]
|
||||
fn length_field(
|
||||
ui: &mut Ui,
|
||||
salt: &'static str,
|
||||
caption: &craft_ui::runtime::env::Label,
|
||||
value: &mut Option<CropLength>,
|
||||
pixels_per_inch: f64,
|
||||
points_per_inch: f64,
|
||||
limits: &SizeLimits,
|
||||
out_of_range: &mut Option<RangeAlert>,
|
||||
) -> bool {
|
||||
let unit = value.map_or(UnitKind::Pixels, |length| length.unit);
|
||||
let mut typed = None;
|
||||
let mut typed_unit = None;
|
||||
let mut alert = None;
|
||||
Field::new(caption.clone()).id_salt(salt).sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
let lengths = LengthUnits::new(unit, unit, pixels_per_inch);
|
||||
let range = limits.length_range(unit, pixels_per_inch, points_per_inch);
|
||||
let field = NumberField::length(caption.clone(), Bind::given(value.map(|length| length.value)), lengths).range(range).show(ui);
|
||||
typed = field.value().copied();
|
||||
typed_unit = field.typed_unit;
|
||||
alert = field.out_of_range;
|
||||
});
|
||||
if alert.is_some() {
|
||||
*out_of_range = alert;
|
||||
}
|
||||
let Some(next) = typed else { return false };
|
||||
let next = next.map(|length| match typed_unit {
|
||||
// The value is in the stored unit; a typed unit becomes the stored one, as in Photoshop.
|
||||
Some(to) if to != unit => {
|
||||
let pixels = unit.to_pixels(length, 1.0, pixels_per_inch, points_per_inch);
|
||||
let converted = pixels.and_then(|pixels| to.from_pixels(pixels, 1.0, pixels_per_inch, points_per_inch));
|
||||
converted.map_or(CropLength::new(length, unit), |value| CropLength::new(value, to))
|
||||
}
|
||||
_ => CropLength::new(length, unit),
|
||||
});
|
||||
let changed = next != *value;
|
||||
*value = next;
|
||||
changed
|
||||
}
|
||||
|
||||
/// The size a crop commit resamples to.
|
||||
@@ -59,24 +197,44 @@ pub struct CropSizeTarget {
|
||||
impl CropSizeFields {
|
||||
/// Swaps W and H.
|
||||
pub fn swap(&mut self) {
|
||||
todo!("tl.T47")
|
||||
std::mem::swap(&mut self.width, &mut self.height);
|
||||
}
|
||||
|
||||
/// Fills W, H and the resolution from `document`; with `limits` the resolution is rounded
|
||||
/// inward to 3 decimals.
|
||||
/// Fills W and H with the document's size in pixels and the resolution with the document's, in the field's unit.
|
||||
/// With `limits` (the resolution range in the field's unit) the resolution keeps 3 decimals and is clamped into
|
||||
/// them, so a stored value never converts past a limit; without, it keeps 2.
|
||||
pub fn front_image(&mut self, document: &CropDocument, limits: Option<(f64, f64)>) {
|
||||
let _ = (document, limits);
|
||||
todo!("tl.T47")
|
||||
self.width = Some(CropLength::new(document.size.width, UnitKind::Pixels));
|
||||
self.height = Some(CropLength::new(document.size.height, UnitKind::Pixels));
|
||||
let resolution = match self.resolution_unit {
|
||||
ResolutionUnit::PixelsPerInch => document.resolution,
|
||||
ResolutionUnit::PixelsPerCentimetre => document.resolution / CM_PER_INCH,
|
||||
};
|
||||
self.resolution = match limits {
|
||||
Some((low, high)) => trim_number(((resolution * 1000.0).round() / 1000.0).clamp(low, high), 3),
|
||||
None => trim_number(resolution, 2),
|
||||
};
|
||||
}
|
||||
|
||||
/// Empties W, H and the resolution and resets the resolution unit to pixels per inch.
|
||||
pub fn clear_size(&mut self) {
|
||||
todo!("tl.T47")
|
||||
self.width = None;
|
||||
self.height = None;
|
||||
self.resolution.clear();
|
||||
self.resolution_unit = ResolutionUnit::PixelsPerInch;
|
||||
}
|
||||
|
||||
/// The target the fields name.
|
||||
/// The size the fields name: each length in pixels (physical lengths at the typed resolution, else the
|
||||
/// document's; points and picas at `units`' points per inch; a bare number in pixels), each side `None` while it
|
||||
/// is empty or not a positive length of at most [`FIELD_MAX`].
|
||||
pub fn target(&self, document: &CropDocument, units: &Units) -> CropSizeTarget {
|
||||
let _ = (document, units);
|
||||
todo!("tl.T47")
|
||||
let resolution = self.resolution_ppi();
|
||||
let dpi = resolution.unwrap_or(document.resolution);
|
||||
let pixels = |length: Option<CropLength>| {
|
||||
let length = CropLength::usable(length)?;
|
||||
let px = length.unit.to_pixels(length.value, 0.0, dpi, units.points_per_inch())?;
|
||||
(px.is_finite() && px > 0.0).then_some(px)
|
||||
};
|
||||
CropSizeTarget { width: pixels(self.width), height: pixels(self.height), resolution }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The W × H × Resolution rules both crop bars share: the pixel target the fields name, and Front Image with the
|
||||
//! Perspective limits.
|
||||
|
||||
use craft_behavior::kurbo::Size;
|
||||
use craft_draw::ui::crop::{CropDocKey, CropDocument, CropLength, CropRatio, CropSettings, CropSizeFields, ResolutionUnit};
|
||||
use craft_ui::runtime::env::{Env, PointSize, UnitKind, Units, with_env};
|
||||
use craft_ui::testing::{Frames, trial};
|
||||
|
||||
/// The units of a scope whose point is `point_size`.
|
||||
fn units(point_size: PointSize) -> Units {
|
||||
let mut frames = Frames::new();
|
||||
let mut units = None;
|
||||
frames.frame(vec![], |ui| {
|
||||
with_env(
|
||||
ui,
|
||||
|scope| {
|
||||
scope.values.set(point_size);
|
||||
},
|
||||
|ui| units = Some(Env::of(ui).units()),
|
||||
)
|
||||
});
|
||||
units.expect("the frame ran")
|
||||
}
|
||||
|
||||
fn document(width: f64, height: f64, resolution: f64) -> CropDocument {
|
||||
CropDocument::new(CropDocKey::new(1), Size::new(width, height), resolution)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn near(value: Option<f64>, expected: f64) -> bool {
|
||||
value.is_some_and(|v| (v - expected).abs() < 1e-6)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn size_targets_convert_units_and_perspective_limits_round_inward() {
|
||||
let postscript = units(PointSize::PostScript);
|
||||
let traditional = units(PointSize::Traditional);
|
||||
let doc = document(800.0, 600.0, 72.0);
|
||||
let inch = |value: f64| Some((value, UnitKind::Inches));
|
||||
|
||||
// Inches convert at the typed resolution, else at the document's.
|
||||
let typed = fields(inch(4.0), inch(5.0), "300", ResolutionUnit::PixelsPerInch).target(&doc, &postscript);
|
||||
assert!(near(typed.width, 1200.0) && near(typed.height, 1500.0) && near(typed.resolution, 300.0), "{typed:?}");
|
||||
let untyped = fields(inch(2.0), inch(1.0), "", ResolutionUnit::PixelsPerInch).target(&doc, &postscript);
|
||||
assert!(near(untyped.width, 144.0) && near(untyped.height, 72.0) && untyped.resolution.is_none(), "{untyped:?}");
|
||||
|
||||
// Pixels ignore the resolution; centimetres and the px/cm resolution convert through 2.54.
|
||||
let pixels = fields(Some((100.0, UnitKind::Pixels)), Some((50.0, UnitKind::Pixels)), "300", ResolutionUnit::PixelsPerInch).target(&doc, &postscript);
|
||||
assert!(near(pixels.width, 100.0) && near(pixels.height, 50.0), "{pixels:?}");
|
||||
let centimetres = fields(Some((2.54, UnitKind::Centimetres)), inch(1.0), "10", ResolutionUnit::PixelsPerCentimetre).target(&doc, &postscript);
|
||||
assert!(near(centimetres.resolution, 25.4) && near(centimetres.width, 25.4) && near(centimetres.height, 25.4), "{centimetres:?}");
|
||||
|
||||
// A point is 1/72 in for PostScript and 1/72.27 in for Traditional.
|
||||
let points = fields(Some((72.0, UnitKind::Points)), None, "100", ResolutionUnit::PixelsPerInch);
|
||||
assert!(near(points.target(&doc, &postscript).width, 100.0));
|
||||
assert!(near(points.target(&doc, &traditional).width, 100.0 * 72.0 / 72.27));
|
||||
|
||||
// A side that is empty, zero or past the largest length has no target; the other side keeps its own.
|
||||
let one_side = fields(inch(4.0), None, "", ResolutionUnit::PixelsPerInch).target(&doc, &postscript);
|
||||
assert!(near(one_side.width, 288.0) && one_side.height.is_none(), "{one_side:?}");
|
||||
let zero = fields(Some((0.0, UnitKind::Pixels)), Some((1e12, UnitKind::Pixels)), "", ResolutionUnit::PixelsPerInch).target(&doc, &postscript);
|
||||
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);
|
||||
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");
|
||||
assert!((target.width - 1200.0).abs() < 1e-6 && (target.height - 1500.0).abs() < 1e-6 && near(target.resolution, 300.0));
|
||||
settings.size.height = None;
|
||||
assert!(settings.target(&doc, &postscript).is_none(), "one side is a free crop");
|
||||
|
||||
// Front Image with the Perspective limits keeps three decimals and rounds inward.
|
||||
let high = document(800.0, 600.0, 30_000.0);
|
||||
let mut per_inch = CropSizeFields::default();
|
||||
per_inch.front_image(&high, Some((1.0, 29_999.999)));
|
||||
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;
|
||||
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");
|
||||
// Without limits the resolution keeps two decimals.
|
||||
let mut plain = CropSizeFields::default();
|
||||
plain.front_image(&document(10.0, 10.0, 300.456), None);
|
||||
assert_eq!(plain.resolution, "300.46");
|
||||
|
||||
// Clear empties the three fields and puts the unit back to px/in; swap exchanges W and H.
|
||||
let mut cleared = fields(inch(4.0), inch(5.0), "300", ResolutionUnit::PixelsPerCentimetre);
|
||||
cleared.swap();
|
||||
assert_eq!((cleared.width, cleared.height), (Some(CropLength::new(5.0, UnitKind::Inches)), Some(CropLength::new(4.0, UnitKind::Inches))));
|
||||
cleared.clear_size();
|
||||
assert_eq!(cleared, CropSizeFields::default());
|
||||
}
|
||||
@@ -22,6 +22,7 @@ mod pen;
|
||||
|
||||
// draw-crop-b
|
||||
mod crop_tool;
|
||||
mod crop_size;
|
||||
mod perspective_crop;
|
||||
|
||||
// draw-bars
|
||||
|
||||
@@ -1,11 +1,121 @@
|
||||
//! The Perspective Crop quad and tool through the public API: the pure quad rules, the quad's gestures and keys as a
|
||||
//! canvas control, and the tool's box drag and four clicks on the background.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_draw::ui::crop::{grid_lines, grid_steps};
|
||||
use craft_ui::testing::trial;
|
||||
use egui::{Pos2, Vec2};
|
||||
use craft_behavior::geometry::Constraint;
|
||||
use craft_behavior::kurbo::{Point, Size};
|
||||
use craft_draw::ui::crop::{PerspectiveCropTool, PerspectiveInput, grid_lines, grid_steps, is_valid};
|
||||
use craft_ui::canvas::{Canvas, ToolHost};
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, Vec2};
|
||||
|
||||
const SIZE: Size = Size::new(400.0, 300.0);
|
||||
const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE };
|
||||
const ALT: Modifiers = Modifiers { alt: true, ..Modifiers::NONE };
|
||||
const BOTH: Modifiers = Modifiers { shift: true, alt: true, ..Modifiers::NONE };
|
||||
|
||||
/// The tool on a canvas showing its quad, driven by pointer events.
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
tool: Rc<RefCell<PerspectiveCropTool>>,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
let tool = Rc::new(RefCell::new(PerspectiveCropTool::new()));
|
||||
let shown = Rc::clone(&tool);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
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 pass = tool.pass(PerspectiveInput::default());
|
||||
let canvas = Canvas::new("Document").document(SIZE).view(view).show(ui, |ui, body| {
|
||||
let _ = pass.show_quad(ui, body.rect);
|
||||
});
|
||||
let _ = ToolHost::new().run(ui, &canvas.output, &mut pass);
|
||||
});
|
||||
fixture.settle();
|
||||
Rig { fixture, tool }
|
||||
}
|
||||
|
||||
/// The screen point of document point `(x, y)`: the view shows (200, 150) at the canvas's centre.
|
||||
fn at(&self, x: f64, y: f64) -> Pos2 {
|
||||
let canvas = self.fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas");
|
||||
canvas.center() + Vec2::new(x as f32 - 200.0, y as f32 - 150.0)
|
||||
}
|
||||
|
||||
fn button(&mut self, at: Pos2, pressed: bool, modifiers: Modifiers) {
|
||||
self.fixture.hold(modifiers);
|
||||
self.fixture.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }]);
|
||||
}
|
||||
|
||||
/// A drag over four moves; the last move and the release hold `last`, the others `first`.
|
||||
fn drag_with(&mut self, from: (f64, f64), to: (f64, f64), first: Modifiers, last: Modifiers) {
|
||||
let (from, to) = (self.at(from.0, from.1), self.at(to.0, to.1));
|
||||
self.fixture.hold(first);
|
||||
self.fixture.frame(vec![Event::PointerMoved(from)]);
|
||||
self.button(from, true, first);
|
||||
for step in 1..=4 {
|
||||
let mods = if step == 4 { last } else { first };
|
||||
self.fixture.hold(mods);
|
||||
self.fixture.frame(vec![Event::PointerMoved(from + (to - from) * (step as f32 / 4.0))]);
|
||||
}
|
||||
self.button(to, false, last);
|
||||
self.fixture.hold(Modifiers::NONE);
|
||||
self.fixture.frame(Vec::new());
|
||||
}
|
||||
|
||||
fn drag(&mut self, from: (f64, f64), to: (f64, f64), mods: Modifiers) {
|
||||
self.drag_with(from, to, mods, mods);
|
||||
}
|
||||
|
||||
fn click(&mut self, at: (f64, f64)) {
|
||||
let at = self.at(at.0, at.1);
|
||||
self.fixture.hold(Modifiers::NONE);
|
||||
self.fixture.frame(vec![Event::PointerMoved(at)]);
|
||||
self.button(at, true, Modifiers::NONE);
|
||||
self.button(at, false, Modifiers::NONE);
|
||||
self.fixture.frame(Vec::new());
|
||||
}
|
||||
|
||||
/// Moves the pointer to document point `(x, y)` and whether a painted path has a point at it: the preview
|
||||
/// outline's last corner sits at the pointer.
|
||||
fn preview_reaches(&mut self, (x, y): (f64, f64)) -> bool {
|
||||
let pointer = self.at(x, y);
|
||||
self.fixture.frame(vec![Event::PointerMoved(pointer)]);
|
||||
let shapes = self.fixture.frame_shapes();
|
||||
shapes.iter().any(|shape| match shape {
|
||||
egui::Shape::Path(path) => path.points.iter().any(|p| (*p - pointer).length() < 0.5),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn set(&self, quad: [(f64, f64); 4]) {
|
||||
self.tool.borrow_mut().set(Some(quad.map(|(x, y)| Point::new(x, y))));
|
||||
}
|
||||
|
||||
fn quad(&self) -> Option<[Point; 4]> {
|
||||
*self.tool.borrow().quad()
|
||||
}
|
||||
|
||||
fn placing(&self) -> usize {
|
||||
self.tool.borrow().placing()
|
||||
}
|
||||
}
|
||||
|
||||
fn near(got: Option<[Point; 4]>, want: [(f64, f64); 4]) -> bool {
|
||||
got.is_some_and(|q| q.iter().zip(want).all(|(p, (x, y))| (p.x - x).abs() < 1e-3 && (p.y - y).abs() < 1e-3))
|
||||
}
|
||||
|
||||
fn rectangle((a, b): (Point, Point)) -> [(f64, f64); 4] {
|
||||
let (x0, y0, x1, y1) = (a.x.min(b.x), a.y.min(b.y), a.x.max(b.x), a.y.max(b.y));
|
||||
[(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn grid_lines_meet_at_the_quads_vanishing_points() {
|
||||
@@ -22,3 +132,60 @@ fn grid_lines_meet_at_the_quads_vanishing_points() {
|
||||
let gaps: Vec<f32> = rows.windows(2).map(|pair| pair[1] - pair[0]).collect();
|
||||
assert!(gaps.len() >= 2 && gaps.windows(2).any(|pair| (pair[0] - pair[1]).abs() > 0.5), "perspective rows are not evenly spaced: {gaps:?}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn perspective_box_and_corner_modifiers_and_clicks() {
|
||||
let mut rig = Rig::new();
|
||||
|
||||
// A box drag follows the shared marquee rule: Shift squares it, Alt draws it from the press, both do both.
|
||||
let (press, to) = ((100.0, 80.0), (200.0, 150.0));
|
||||
for (mods, square, centre) in [(Modifiers::NONE, false, false), (SHIFT, true, false), (ALT, false, true), (BOTH, true, true)] {
|
||||
rig.tool.borrow_mut().clear();
|
||||
rig.drag(press, to, mods);
|
||||
let want = rectangle(Constraint::Free.corners(Point::new(press.0, press.1), Point::new(to.0, to.1), square, centre));
|
||||
assert!(near(rig.quad(), want), "box with {mods:?}: {:?} vs {want:?}", rig.quad());
|
||||
}
|
||||
|
||||
// A drag that makes no box keeps the clicks; one that makes a box clears them.
|
||||
rig.tool.borrow_mut().clear();
|
||||
rig.click((100.0, 50.0));
|
||||
rig.click((300.0, 200.0));
|
||||
assert_eq!(rig.placing(), 2);
|
||||
assert!(rig.preview_reaches((250.0, 120.0)), "after two clicks the preview's last corner sits at the pointer");
|
||||
rig.drag((50.0, 250.0), (200.0, 250.0), Modifiers::NONE);
|
||||
assert!(rig.quad().is_none() && rig.placing() == 2, "a flat drag leaves no quad and keeps the clicks");
|
||||
rig.click((300.0, 50.0));
|
||||
assert_eq!(rig.placing(), 3);
|
||||
assert!(rig.preview_reaches((120.0, 180.0)), "after three clicks the preview's last corner sits at the pointer");
|
||||
rig.click((100.0, 200.0));
|
||||
assert!(near(rig.quad(), [(100.0, 50.0), (300.0, 50.0), (300.0, 200.0), (100.0, 200.0)]), "the fourth click puts the corners in order: {:?}", rig.quad());
|
||||
assert_eq!(rig.placing(), 0);
|
||||
rig.tool.borrow_mut().clear();
|
||||
rig.click((100.0, 50.0));
|
||||
rig.drag((20.0, 20.0), (120.0, 120.0), Modifiers::NONE);
|
||||
assert!(rig.quad().is_some() && rig.placing() == 0, "a box drag clears the clicks");
|
||||
|
||||
// Corner drags on an upright quad.
|
||||
let upright = [(100.0, 80.0), (300.0, 80.0), (300.0, 220.0), (100.0, 220.0)];
|
||||
let by = (340.0, 230.0);
|
||||
rig.set(upright);
|
||||
rig.drag((300.0, 220.0), by, SHIFT);
|
||||
assert!(near(rig.quad(), [(100.0, 80.0), (300.0, 80.0), (340.0, 220.0), (100.0, 220.0)]), "Shift locks the axis moved less along: {:?}", rig.quad());
|
||||
rig.set(upright);
|
||||
rig.drag((300.0, 220.0), by, ALT);
|
||||
assert!(near(rig.quad(), [(100.0, 80.0), (340.0, 80.0), (340.0, 230.0), (100.0, 230.0)]), "Alt keeps the rectangle: {:?}", rig.quad());
|
||||
rig.set(upright);
|
||||
rig.drag_with((300.0, 220.0), by, ALT, Modifiers::NONE);
|
||||
assert!(near(rig.quad(), [(100.0, 80.0), (300.0, 80.0), (340.0, 230.0), (100.0, 220.0)]), "releasing Alt mid-drag puts the neighbours back: {:?}", rig.quad());
|
||||
rig.set([(120.0, 80.0), (300.0, 80.0), (300.0, 220.0), (100.0, 220.0)]);
|
||||
rig.drag((300.0, 220.0), (320.0, 230.0), ALT);
|
||||
assert!(near(rig.quad(), [(120.0, 80.0), (300.0, 80.0), (320.0, 230.0), (100.0, 220.0)]), "a skewed quad's corner moves alone: {:?}", rig.quad());
|
||||
rig.set(upright);
|
||||
rig.drag((300.0, 220.0), (50.0, 40.0), ALT);
|
||||
assert!(rig.quad().is_some_and(|q| is_valid(&q)), "Alt past the opposite corner stays a valid quad: {:?}", rig.quad());
|
||||
|
||||
// A click on a corner with no drag changes nothing.
|
||||
rig.set(upright);
|
||||
rig.click((300.0, 220.0));
|
||||
assert!(near(rig.quad(), upright), "a click moves nothing: {:?}", rig.quad());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user