mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
Merge #17449 into the merge queue batch
Contextual task bar for a shape layer: Fill, Stroke, width, type, Corner radius, Duplicate layer, More properties (#16755)
This commit is contained in:
commit
61bf37bd00
10 files changed
+686
-1
No files matched your search
@@ -579,6 +579,7 @@ fn canvas_controls(
|
||||
crate::crop_task_bar::show(app, ui, bar_area);
|
||||
if primary {
|
||||
crate::transform_task_bar::show(app, ui, bar_area);
|
||||
crate::shape_task_bar::show(app, ui, bar_area);
|
||||
}
|
||||
crate::frame_tool::task_bar::show(ui, app, bar_area);
|
||||
}
|
||||
|
||||
@@ -100,7 +100,12 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
|
||||
}
|
||||
// Last frame's task bar rect, unless the bar can't show now (hidden by `ui.set` before the
|
||||
// next draw).
|
||||
let task_bar_rect = app.ui.task_bar_shown.filter(|_| crate::crop_task_bar::eligible(app)).or_else(|| crate::transform_task_bar::shown_rect(app, app.ctx()));
|
||||
let task_bar_rect = app
|
||||
.ui
|
||||
.task_bar_shown
|
||||
.filter(|_| crate::crop_task_bar::eligible(app))
|
||||
.or_else(|| crate::transform_task_bar::shown_rect(app, app.ctx()))
|
||||
.or_else(|| crate::shape_task_bar::shown_rect(app, app.ctx()));
|
||||
// The one open canvas context menu, told apart by its kind.
|
||||
let menu = app.ui.canvas_tool_menu.as_ref();
|
||||
let kind = menu.map(|menu| &menu.kind);
|
||||
|
||||
@@ -39,6 +39,8 @@ fn pen_app(points: &[[f64; 2]]) -> Box<PhotocraftApp> {
|
||||
fn pen_command_z_and_backspace_retract_points_before_document_undo() {
|
||||
let mut app = pen_app(&[]);
|
||||
app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap();
|
||||
// The rectangle's contextual task bar (#16755) would sit over the clicks below.
|
||||
app.ui.panels.context_task_bar = false;
|
||||
let history = app.session.active().unwrap().history.past_len();
|
||||
// Away from the rectangle's anchors, which the Pen would edit.
|
||||
for at in [[100.0, 100.0], [150.0, 100.0], [150.0, 150.0]] {
|
||||
|
||||
@@ -287,6 +287,7 @@ use tools::shape_gradient_ui;
|
||||
use tools::shape_options;
|
||||
use tools::shape_paint_ui;
|
||||
pub use tools::shape_stroke_ui;
|
||||
pub use tools::shape_task_bar;
|
||||
pub use tools::slice_ui;
|
||||
pub use tools::stroke_constraint;
|
||||
pub use tools::stroke_trace;
|
||||
|
||||
@@ -65,6 +65,8 @@ pub enum TaskBarContext {
|
||||
Crop { doc: u64, frame: u64 },
|
||||
/// The Frame tool's bar for one frame layer.
|
||||
Frame { doc: u64, layer: u64 },
|
||||
/// A shape layer's bar for that layer.
|
||||
Shape { doc: u64, layer: u64 },
|
||||
}
|
||||
|
||||
/// The contextual task bar's context bookkeeping (#16758), kept out of saved state.
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
//! The shape layer's contextual task bar (#16755) through the real canvas, its widgets and the existing commands.
|
||||
|
||||
use egui::{Key, Modifiers};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use photocraft_doc::vector::LiveShape;
|
||||
use photocraft_doc::{LayerContent, LayerId};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::app::framework::BuildApp as _;
|
||||
use crate::state::Tool;
|
||||
|
||||
type AppHarness = Harness<'static, Box<PhotocraftApp>>;
|
||||
|
||||
/// A 400 x 300 document with a red 120 x 80 rectangle shape layer "Shape" at 100,100, selected, with `tool`.
|
||||
fn harness(tool: Tool) -> (AppHarness, LayerId) {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = app.run("shape.create", json!({"kind": "rect", "rect": [100, 100, 120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
|
||||
app.run("layer.renameLayer", json!({"layer": id, "name": "Shape"})).unwrap();
|
||||
app.sync_views();
|
||||
app.ui.extras.rulers = false;
|
||||
app.ui.tool = tool;
|
||||
let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1000.0, 700.0)).build_app(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui));
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let v = &mut h.state_mut().ui.views[0];
|
||||
v.zoom = 1.0;
|
||||
v.center = [200.0, 150.0];
|
||||
v.clear_pending();
|
||||
h.run_steps(4);
|
||||
(h, LayerId(id))
|
||||
}
|
||||
|
||||
fn bar(h: &AppHarness) -> Option<[f32; 4]> {
|
||||
super::shown_rect(h.state(), &h.ctx)
|
||||
}
|
||||
|
||||
/// `ui.inspect`'s `taskBar`, through the control channel.
|
||||
fn inspect_task_bar(h: &mut AppHarness) -> serde_json::Value {
|
||||
let ctx = h.ctx.clone();
|
||||
let (request, _reply) = crate::control::ControlRequest::new("ui.inspect", json!({}));
|
||||
let crate::control::Reply::Done(reply) = crate::control::handle(h.state_mut(), &ctx, &request) else { panic!("ui.inspect replies at once") };
|
||||
reply["result"]["taskBar"].clone()
|
||||
}
|
||||
|
||||
fn history(h: &AppHarness) -> usize {
|
||||
h.state().session.active().unwrap().history.past_len()
|
||||
}
|
||||
|
||||
fn radii(h: &AppHarness, id: LayerId) -> [f64; 4] {
|
||||
match &h.state().session.active().unwrap().doc.layer(id).unwrap().content {
|
||||
LayerContent::Shape(sh) => match sh.live {
|
||||
Some(LiveShape::Rect { radii, .. }) => radii,
|
||||
ref other => panic!("not a live rectangle: {other:?}"),
|
||||
},
|
||||
_ => panic!("not a shape layer"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The left edge of the widget named `label` on screen.
|
||||
fn left(h: &AppHarness, label: &str) -> f32 {
|
||||
h.query_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")).rect().min.x
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bar_shows_under_the_shape_left_aligned_with_its_bounds() {
|
||||
let (mut h, _) = harness(Tool::Move);
|
||||
let rect = bar(&h).expect("a selected rectangle shape layer shows the bar");
|
||||
let inspected = inspect_task_bar(&mut h);
|
||||
assert_eq!((inspected["visible"].as_bool(), inspected["rect"].clone()), (Some(true), json!(rect)), "ui.inspect reports the bar");
|
||||
let view = crate::canvas::testing::view(h.state()).unwrap();
|
||||
let (top_left, bottom_left) =
|
||||
(view.to_screen(craft::behavior::kurbo::Point::new(100.0, 100.0)), view.to_screen(craft::behavior::kurbo::Point::new(100.0, 180.0)));
|
||||
assert!(rect[1] > bottom_left.y, "below the shape: bar top {} vs shape bottom {}", rect[1], bottom_left.y);
|
||||
assert!(rect[1] - bottom_left.y < 40.0, "close under the shape: {}", rect[1] - bottom_left.y);
|
||||
assert!((rect[0] - top_left.x).abs() < 1.0, "left-aligned with the shape: bar left {} vs shape left {}", rect[0], top_left.x);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bar_controls_come_in_the_reference_order_with_their_names() {
|
||||
let (h, _) = harness(Tool::Move);
|
||||
let order = ["Fill", "Stroke", "Stroke width", "Stroke style", "Corner radius", "Duplicate layer", "More properties", "More options"];
|
||||
let xs: Vec<f32> = order.iter().map(|label| left(&h, label)).collect();
|
||||
assert!(xs.windows(2).all(|w| w[0] < w[1]), "left to right {order:?}: {xs:?}");
|
||||
// The visible labels in front of the chips.
|
||||
assert!(h.query_by_label("Fill").is_some() && h.query_by_label("Stroke").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_bar_for_crop_transform_several_layers_other_layers_or_unmeasured_shapes() {
|
||||
let (mut h, _) = harness(Tool::Crop);
|
||||
h.run_steps(2);
|
||||
assert!(bar(&h).is_none() && !super::eligible(h.state()), "the Crop tool has its own bar");
|
||||
|
||||
let (mut h, id) = harness(Tool::Move);
|
||||
let other = h.state_mut().run("shape.create", json!({"kind": "rect", "rect": [10, 10, 20, 20], "fill": "#00ff00"})).unwrap()["layer"].as_u64().unwrap();
|
||||
h.state_mut().run("layer.select", json!({"layer": id.0})).unwrap();
|
||||
h.state_mut().run("layer.select", json!({"layer": other, "mode": "add"})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(!super::eligible(h.state()), "two layers selected: no bar");
|
||||
|
||||
let (mut h, _) = harness(Tool::Move);
|
||||
h.state_mut().run("shape.create", json!({"kind": "ellipse", "rect": [10, 10, 60, 40], "fill": "#00ff00"})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(!super::eligible(h.state()), "an ellipse was not measured: no bar");
|
||||
|
||||
let (mut h, _) = harness(Tool::Move);
|
||||
h.state_mut().run("layer.new.layer", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(!super::eligible(h.state()), "a pixel layer is not this bar's");
|
||||
|
||||
let (mut h, _) = harness(Tool::Move);
|
||||
let ctx = h.ctx.clone();
|
||||
crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(!super::eligible(h.state()), "Free Transform shows its own bar");
|
||||
|
||||
let (mut h, _) = harness(Tool::Move);
|
||||
h.state_mut().ui.panels.context_task_bar = false;
|
||||
h.run_steps(3);
|
||||
assert!(bar(&h).is_none(), "Window > Contextual Task Bar off: no bar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_bar_for_a_shape_in_a_hidden_group() {
|
||||
let (mut h, id) = harness(Tool::Move);
|
||||
let group = LayerId(h.state_mut().run("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
|
||||
h.state_mut().run("layer.select", json!({"layer": id.0})).unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(super::eligible(h.state()), "a shape inside a shown group keeps its bar");
|
||||
h.state_mut()
|
||||
.session
|
||||
.edit("hide group", |doc, _| {
|
||||
doc.layer_mut(group).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().session.active().unwrap().doc.layer(id).unwrap().visible, "the shape's own flag stays on");
|
||||
assert!(bar(&h).is_none() && !super::eligible(h.state()), "a shape in a hidden group is not shown: no bar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_layer_adds_one_step_and_selects_the_copy_above() {
|
||||
let (mut h, id) = harness(Tool::Move);
|
||||
let before = history(&h);
|
||||
h.get_by_label("Duplicate layer").click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(history(&h), before + 1, "one history step");
|
||||
assert!(!h.state().dialog_open(), "no Duplicate Layer dialog");
|
||||
let st = h.state().session.active().unwrap();
|
||||
assert_eq!(st.history.undo_label(), Some("Duplicate Layer"));
|
||||
let copy = st.active_layer.unwrap();
|
||||
assert_ne!(copy, id);
|
||||
assert_eq!(st.selected_layers(), &[copy], "the copy is selected");
|
||||
assert_eq!(st.doc.layer(copy).unwrap().name, "Shape copy");
|
||||
let order: Vec<LayerId> = st.doc.layers.iter().map(|l| l.id).collect();
|
||||
let (at, copy_at) = (order.iter().position(|l| *l == id).unwrap(), order.iter().position(|l| *l == copy).unwrap());
|
||||
assert_eq!(copy_at, at + 1, "the copy sits right above the original");
|
||||
let bounds = |l: LayerId| match &st.doc.layer(l).unwrap().content {
|
||||
LayerContent::Shape(sh) => sh.path.control_bounds(),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(bounds(copy), bounds(id), "same bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_properties_shows_the_properties_panel() {
|
||||
let (mut h, _) = harness(Tool::Move);
|
||||
let ctx = h.ctx.clone();
|
||||
crate::menus::invoke(h.state_mut(), &ctx, "window.panel.properties", json!({"show": false})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert!(!crate::panels::panel_docking::is_shown(h.state(), "properties"));
|
||||
let before = history(&h);
|
||||
h.get_by_label("More properties").click();
|
||||
h.run_steps(4);
|
||||
assert!(crate::panels::panel_docking::is_shown(h.state(), "properties"), "the Properties panel shows");
|
||||
// A second click keeps it shown: More properties never hides the panel.
|
||||
h.get_by_label("More properties").click();
|
||||
h.run_steps(4);
|
||||
assert!(crate::panels::panel_docking::is_shown(h.state(), "properties"));
|
||||
assert_eq!(history(&h), before, "no document edit");
|
||||
}
|
||||
|
||||
/// Types `text` into the Corner radius popover's field named `name` and commits it with Enter.
|
||||
fn type_radius(h: &mut AppHarness, name: &str, text: &str) {
|
||||
let field = h.get_all_by_label(name).find(|n| n.accesskit_node().role() != egui::accesskit::Role::Button).expect("a field");
|
||||
field.click();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::A);
|
||||
let field = h.get_all_by_label(name).find(|n| n.accesskit_node().role() != egui::accesskit::Role::Button).expect("a field");
|
||||
field.type_text(text);
|
||||
h.key_press(Key::Enter);
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_radius_popover_sets_all_corners_then_one_corner_one_step_each() {
|
||||
let (mut h, id) = harness(Tool::Move);
|
||||
h.get_by_label("Corner radius").click();
|
||||
h.run_steps(4);
|
||||
for name in ["Top Left", "Top Right", "Bottom Left", "Bottom Right"] {
|
||||
assert!(h.query_by_label(name).is_some(), "the popover has {name}");
|
||||
}
|
||||
let before = history(&h);
|
||||
type_radius(&mut h, "Corner radius", "12");
|
||||
assert_eq!(radii(&h, id), [12.0; 4], "all corners");
|
||||
assert_eq!(history(&h), before + 1, "one step for all corners");
|
||||
type_radius(&mut h, "Bottom Left", "4");
|
||||
assert_eq!(radii(&h, id), [12.0, 12.0, 12.0, 4.0], "Bottom Left is the radii's fourth corner");
|
||||
assert_eq!(history(&h), before + 2, "one step for one corner");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_and_stroke_edit_the_layer_as_the_options_bar_does() {
|
||||
let (mut h, id) = harness(Tool::Move);
|
||||
let layer = |h: &AppHarness| match &h.state().session.active().unwrap().doc.layer(id).unwrap().content {
|
||||
LayerContent::Shape(sh) => sh.clone(),
|
||||
_ => panic!("not a shape layer"),
|
||||
};
|
||||
let t = super::target(h.state()).unwrap();
|
||||
let gradients = [
|
||||
photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 0.0, 1.0)),
|
||||
photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 0.0, 1.0)),
|
||||
];
|
||||
let blue = craft::color_ui::ui::Paint::Solid(craft::theme::Srgba::new(0.0, 0.0, 1.0, 1.0));
|
||||
let set = |paint: craft::color_ui::ui::Paint| {
|
||||
craft::behavior::EditEvent::set(craft::behavior::Mixed::Same(craft::color_ui::ui::Paint::None), paint, std::sync::Arc::from("Fill"), None)
|
||||
};
|
||||
let before = history(&h);
|
||||
let ctx = h.ctx.clone();
|
||||
super::apply(h.state_mut(), &ctx, &t, [0.0; 4], &gradients, vec![super::Change::Fill(set(blue.clone())), super::Change::Stroke(set(blue))]);
|
||||
let sh = layer(&h);
|
||||
assert_eq!(crate::shape_paint_ui::color_of(sh.fill.as_ref().unwrap()), Some([0.0, 0.0, 1.0, 1.0]), "the fill is blue");
|
||||
let stroke = sh.stroke.expect("a stroke was added");
|
||||
assert_eq!(crate::shape_paint_ui::color_of(&stroke.paint), Some([0.0, 0.0, 1.0, 1.0]));
|
||||
assert!(stroke.width > 0.0, "the stroke shows: {}", stroke.width);
|
||||
assert_eq!(history(&h), before + 2, "one step per change");
|
||||
let t = super::target(h.state()).unwrap();
|
||||
super::apply(h.state_mut(), &ctx, &t, [0.0; 4], &gradients, vec![super::Change::Stroke(set(craft::color_ui::ui::Paint::None))]);
|
||||
assert!(layer(&h).stroke.is_none(), "No Color removes the stroke");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_width_cell_edits_the_layer() {
|
||||
use craft::draw::ui::shape::ShapeChange;
|
||||
let (mut h, id) = harness(Tool::Move);
|
||||
let ctx = h.ctx.clone();
|
||||
let black = photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 0.0, 1.0));
|
||||
let gradients = [black.clone(), black];
|
||||
let stroke = |h: &AppHarness| match &h.state().session.active().unwrap().doc.layer(id).unwrap().content {
|
||||
LayerContent::Shape(sh) => sh.stroke.clone(),
|
||||
_ => None,
|
||||
};
|
||||
let set = |before, after| craft::behavior::EditEvent::set(craft::behavior::Mixed::Same(before), after, std::sync::Arc::from("Stroke"), None);
|
||||
let before = history(&h);
|
||||
let t = super::target(h.state()).unwrap();
|
||||
let width = set(ShapeChange::StrokeWidth(0.0), ShapeChange::StrokeWidth(5.0));
|
||||
super::apply(h.state_mut(), &ctx, &t, [0.0; 4], &gradients, vec![super::Change::Cells(width)]);
|
||||
assert_eq!(stroke(&h).map(|s| s.width), Some(5.0), "the width cell gives the shape a 5 px stroke");
|
||||
assert_eq!(history(&h), before + 1, "one step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_bar_from_the_more_menu_turns_the_bar_off() {
|
||||
let (mut h, _) = harness(Tool::Move);
|
||||
h.get_by_label("More options").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Hide bar").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.panels.context_task_bar, "Hide bar unticks Window > Contextual Task Bar");
|
||||
assert!(bar(&h).is_none());
|
||||
}
|
||||
@@ -37,6 +37,7 @@ pub(super) mod shape_gradient_ui;
|
||||
pub(super) mod shape_options;
|
||||
pub(super) mod shape_paint_ui;
|
||||
pub mod shape_stroke_ui;
|
||||
pub mod shape_task_bar;
|
||||
pub mod slice_ui;
|
||||
pub mod stroke_constraint;
|
||||
pub mod stroke_trace;
|
||||
|
||||
@@ -77,6 +77,8 @@ fn the_rectangle_tools_radius_field_leaves_the_active_shape_alone() {
|
||||
#[test]
|
||||
fn the_next_rectangle_takes_the_typed_radius() {
|
||||
let mut h = bar_with(Tool::Rectangle);
|
||||
// Rectangle 1's contextual task bar (#16755) would sit over the drag below.
|
||||
h.state_mut().ui.panels.context_task_bar = false;
|
||||
type_radius(&mut h, "5000");
|
||||
drag(h.state_mut(), [100.0, 100.0], [180.0, 170.0]);
|
||||
let all = radii(&h);
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//! The shape layer's contextual task bar (#16755), in the framework's shared `TaskBar`, left-aligned under the
|
||||
//! shape's bounds as in the reference application. Left to right:
|
||||
//!
|
||||
//! 1. the grip (the bar's);
|
||||
//! 2. `Fill` and `Stroke` with their paint chips: the shape options bar's chips (`shape_paint_ui`), editing the layer
|
||||
//! with `shape.edit`;
|
||||
//! 3. the stroke width and the stroke type button (the framework's `StrokeCells`, which the options bar shows too);
|
||||
//! 4. Corner radius: a popover with the radius of all corners, then Top Left, Top Right, Bottom Left and Bottom Right;
|
||||
//! 5. Duplicate layer (`layer.duplicate`) and More properties (`window.panel.properties`, shown);
|
||||
//! 6. the ⋯ menu (the bar's: Hide bar, Pin bar position, Reset bar position).
|
||||
//!
|
||||
//! Shown while exactly one layer is selected and it is a shape layer holding one live rectangle, Window › Contextual
|
||||
//! Task Bar is ticked, and no Crop tool, transform, canvas gesture or dialog is running. Other shapes (an ellipse, a
|
||||
//! path, several shapes in one layer) were not measured in the reference, so they keep no bar.
|
||||
|
||||
use craft::behavior::kurbo::Point;
|
||||
use craft::behavior::overlay::{Align, Side};
|
||||
use craft::behavior::{EditEvent, IconId};
|
||||
use craft::color_ui::ui::{Paint, PaintChip, PaintChipOutput};
|
||||
use craft::draw::ui::shape::{ShapeChange, ShapePaint, ShapeWords, StrokeCells};
|
||||
use craft::ui::buttons::IconButton;
|
||||
use craft::ui::canvas_controls::{TaskBar, TaskBarHang};
|
||||
use craft::ui::contract::{Bind, LabelScheme, PopupKind, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::popover::Popover;
|
||||
use craft::ui::runtime::env::{Env, Label, UnitKind};
|
||||
use craft::ui::text::{NumberField, RangeAlert};
|
||||
use photocraft_doc::vector::LiveShape;
|
||||
use photocraft_doc::{LayerContent, LayerId, ShapeLayer};
|
||||
use photocraft_engine::presets::PresetsExt as _;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::shape_paint_ui::{ChipLibrary, decorate_chip, fill_param, solid_rgb, srgba};
|
||||
use crate::shape_stroke_ui::StrokeOptions;
|
||||
use crate::state::{TaskBarContext, Tool};
|
||||
|
||||
/// The id the screen eyedropper's sample is kept under for this bar's chips.
|
||||
const PICKER: &str = "shape-task-bar";
|
||||
|
||||
/// Whether the Corner radius popover is open, kept by the framework per viewer.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct CornersOpen(bool);
|
||||
|
||||
/// Whether the stroke type popover is open, kept by the framework per viewer.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct StrokeOpen(bool);
|
||||
|
||||
/// Where the bar showed, for the layer it showed for.
|
||||
#[derive(Clone, Copy)]
|
||||
struct ShownRect {
|
||||
layer: u64,
|
||||
rect: [f32; 4],
|
||||
}
|
||||
|
||||
fn shown_id() -> egui::Id {
|
||||
egui::Id::unique("shape-layer-task-bar-rect")
|
||||
}
|
||||
|
||||
/// The shape layer the bar is for and its bounds `[x0, y0, x1, y1]` in document pixels.
|
||||
struct Target {
|
||||
doc: u64,
|
||||
layer: LayerId,
|
||||
shape: ShapeLayer,
|
||||
bounds: [f64; 4],
|
||||
locked: bool,
|
||||
}
|
||||
|
||||
fn target(app: &PhotocraftApp) -> Option<Target> {
|
||||
if !app.ui.panels.context_task_bar
|
||||
|| app.ui.tool == Tool::Crop
|
||||
|| app.ui.transform.is_some()
|
||||
|| app.transform_preview.is_some()
|
||||
|| app.dialog_open()
|
||||
|| crate::canvas::tools::in_gesture(app)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let st = app.session.active()?;
|
||||
let [id] = st.selected_layers() else { return None };
|
||||
let layer = st.doc.layer(*id)?;
|
||||
// Hidden by itself or by a group around it: the shape is not on the canvas.
|
||||
if !st.doc.shown_at(&st.doc.path_of(*id)?) {
|
||||
return None;
|
||||
}
|
||||
let LayerContent::Shape(shape) = &layer.content else { return None };
|
||||
// Only a live rectangle was measured in the reference; other shapes keep no bar.
|
||||
if !matches!(shape.live, Some(LiveShape::Rect { .. })) {
|
||||
return None;
|
||||
}
|
||||
let (x0, y0, x1, y1) = shape.path.control_bounds()?;
|
||||
let bounds = [x0, y0, x1, y1];
|
||||
if !bounds.iter().all(|v| v.is_finite()) || x1 < x0 || y1 < y0 {
|
||||
return None;
|
||||
}
|
||||
let locks = st.doc.effective_locks(*id);
|
||||
Some(Target { doc: st.doc.id.0, layer: *id, shape: shape.clone(), bounds, locked: locks.all || locks.pixels })
|
||||
}
|
||||
|
||||
/// Whether the bar can show now.
|
||||
pub fn eligible(app: &PhotocraftApp) -> bool {
|
||||
target(app).is_some()
|
||||
}
|
||||
|
||||
/// The bar's rect on screen as last shown, while it can still show for the same layer.
|
||||
pub(crate) fn shown_rect(app: &PhotocraftApp, ctx: &egui::Context) -> Option<[f32; 4]> {
|
||||
let layer = target(app)?.layer.0;
|
||||
let shown = ctx.data(|data| data.get_temp::<ShownRect>(shown_id()))?;
|
||||
(shown.layer == layer).then_some(shown.rect)
|
||||
}
|
||||
|
||||
/// One change the bar's members asked for in a run of its body.
|
||||
enum Change {
|
||||
Fill(EditEvent<Paint>),
|
||||
Stroke(EditEvent<Paint>),
|
||||
Cells(EditEvent<ShapeChange>),
|
||||
/// The radius of every corner (`None`) or of one corner, in the radii order top left, top right, bottom right,
|
||||
/// bottom left.
|
||||
Radius(Option<usize>, EditEvent<Option<f64>>),
|
||||
Duplicate,
|
||||
Properties,
|
||||
}
|
||||
|
||||
/// What one run of the body reports.
|
||||
#[derive(Default)]
|
||||
struct Run {
|
||||
changes: Vec<Change>,
|
||||
screen_pick: Option<(ShapePaint, craft::color_ui::ui::ScreenPickGesture)>,
|
||||
pick_color: Option<ShapePaint>,
|
||||
out_of_range: Option<RangeAlert>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn chip(&mut self, which: ShapePaint, out: PaintChipOutput) {
|
||||
if let Some(gesture) = out.screen_pick {
|
||||
self.screen_pick = Some((which, gesture));
|
||||
}
|
||||
if out.pick_color.is_some() {
|
||||
self.pick_color = Some(which);
|
||||
}
|
||||
for event in out.edit.events {
|
||||
self.changes.push(match which {
|
||||
ShapePaint::Stroke => Change::Stroke(event),
|
||||
_ => Change::Fill(event),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the bar under the selected shape layer, inside `area` (the canvas body's rect).
|
||||
pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, area: egui::Rect) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let Some(t) = target(app) else {
|
||||
ctx.data_mut(|data| data.remove::<ShownRect>(shown_id()));
|
||||
return;
|
||||
};
|
||||
app.ui.enter_task_bar_context(TaskBarContext::Shape { doc: t.doc, layer: t.layer.0 });
|
||||
let [x0, y0, x1, y1] = t.bounds;
|
||||
let anchor = [Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)];
|
||||
let appearance = crate::shape_paint_ui::appearance_of(&t.shape, t.locked);
|
||||
let radii = match t.shape.live {
|
||||
Some(LiveShape::Rect { radii, .. }) => radii,
|
||||
_ => [0.0; 4],
|
||||
};
|
||||
let ppi = app.session.active().map_or(72.0, |st| f64::from(st.doc.resolution_dpi));
|
||||
let (fg, bg) = (app.session.tools.foreground, app.session.tools.background);
|
||||
let sampled = [ShapePaint::Fill, ShapePaint::Stroke].into_iter().find_map(|p| crate::screen_picker::take(app, (PICKER, p)).map(|c| (p, c)));
|
||||
let recent_colors: Vec<craft::theme::Srgba> =
|
||||
crate::paint_picker::recent_colors(&app.session).into_iter().map(|c| srgba([c[0], c[1], c[2], 1.0])).collect();
|
||||
let groups = crate::shape_gradient_ui::ShapeGradients::groups_of(&app.session.presets().gradients, fg, bg);
|
||||
let gradients = crate::shape_gradient_ui::ShapeGradients { groups, current: &app.session.presets().gradient, recent: &mut app.ui.recent_gradients, fg, bg };
|
||||
let current = [t.shape.fill.clone(), t.shape.stroke.as_ref().map(|s| s.paint.clone())];
|
||||
let mut library =
|
||||
ChipLibrary::new(&recent_colors, &app.session.presets().swatches, &mut app.ui.paint_folders, gradients, &mut app.ui.shape_gradient_state, current);
|
||||
let mut place = app.ui.panels.task_bar;
|
||||
let shown = TaskBar::new(tl!("Contextual Task Bar"), &anchor, Bind::bound(&mut place))
|
||||
.side(Side::Below, Align::Start)
|
||||
.hang_gap(TaskBarHang::ClearOfHandles)
|
||||
.show(ui, area, |ui, cx| {
|
||||
let mut run = Run::default();
|
||||
let words = Env::of(ui).words::<ShapeWords>();
|
||||
Row::new().enabled(!appearance.locked).show(ui, |ui, row| {
|
||||
for (which, name, paint, fallback) in
|
||||
[(ShapePaint::Fill, &words.fill, &appearance.fill, fg), (ShapePaint::Stroke, &words.stroke, &appearance.stroke, bg)]
|
||||
{
|
||||
let (chip_name, tip) = match which {
|
||||
ShapePaint::Stroke => (&words.stroke_color, &words.set_stroke_type),
|
||||
_ => (&words.fill_color, &words.set_fill_type),
|
||||
};
|
||||
let out = Field::new(name.clone()).id_salt(("shape-task-bar-paint", name.as_str())).show(ui, |ui, _| {
|
||||
let mut chip = PaintChip::new(chip_name.clone(), Bind::given(paint.clone()), srgba(fallback)).tooltip(tip.clone());
|
||||
if let Some((_, color)) = sampled.filter(|(on, _)| *on == which) {
|
||||
chip = chip.sampled(color);
|
||||
}
|
||||
decorate_chip(chip, which, &mut library, ui)
|
||||
});
|
||||
if let Some(out) = out.inner {
|
||||
run.chip(which, out);
|
||||
}
|
||||
}
|
||||
let stroke_open = &mut row.memory.shown::<StrokeOpen>(row.id).0;
|
||||
let cells = StrokeCells::new(&appearance, ppi).stroke_open(Bind::bound(stroke_open)).show(ui);
|
||||
run.changes.extend(cells.events.into_iter().map(Change::Cells));
|
||||
run.out_of_range = cells.out_of_range.or(run.out_of_range.take());
|
||||
let corners_open = &mut row.memory.shown::<CornersOpen>(row.id).0;
|
||||
corner_radius(ui, &words, radii, corners_open, &mut run);
|
||||
});
|
||||
if IconButton::new(IconId::new("copy")).label(Label::from(tl!("Duplicate layer").to_owned())).show(ui).clicked() {
|
||||
run.changes.push(Change::Duplicate);
|
||||
}
|
||||
if IconButton::new(IconId::new("adjustments")).label(Label::from(tl!("More properties").to_owned())).show(ui).clicked() {
|
||||
run.changes.push(Change::Properties);
|
||||
}
|
||||
cx.more_menu(ui);
|
||||
run
|
||||
});
|
||||
let gradients = [library.gradient(ShapePaint::Fill), library.gradient(ShapePaint::Stroke)];
|
||||
app.ui.panels.task_bar = place;
|
||||
if shown.output.hide {
|
||||
app.ui.panels.context_task_bar = false;
|
||||
}
|
||||
let r = shown.output.rect;
|
||||
ctx.data_mut(|data| data.insert_temp(shown_id(), ShownRect { layer: t.layer.0, rect: [r.min.x, r.min.y, r.max.x, r.max.y] }));
|
||||
let Some(run) = shown.inner else { return };
|
||||
apply(app, &ctx, &t, radii, &gradients, run.changes);
|
||||
if let Some(which) = run.pick_color {
|
||||
// The Color Picker starts from the layer's own paint.
|
||||
let which = match which {
|
||||
ShapePaint::Stroke => crate::shape_fill_ui::Paint::Stroke,
|
||||
_ => crate::shape_fill_ui::Paint::Fill,
|
||||
};
|
||||
let _ = crate::shape_fill_ui::open_paint(app, which, Some(t.layer), false, fg);
|
||||
}
|
||||
if let Some((which, gesture)) = run.screen_pick {
|
||||
crate::screen_picker::hold(app, &ctx, (PICKER, which), gesture);
|
||||
}
|
||||
if let Some(alert) = run.out_of_range {
|
||||
crate::option_cells::range_alert(app, ui, &alert);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Corner radius button and its popover: the radius of all corners, then one field per corner.
|
||||
fn corner_radius(ui: &mut egui::Ui, words: &ShapeWords, radii: [f64; 4], open: &mut bool, run: &mut Run) {
|
||||
let button =
|
||||
IconButton::new(IconId::new("stroke_join_round")).label(words.corner_radius.clone()).popup(PopupKind::Dialog).expanded(*open).show(ui).response;
|
||||
if clicked(&button) {
|
||||
*open = !*open;
|
||||
}
|
||||
let all = radii.iter().all(|r| (r - radii[0]).abs() < f64::EPSILON).then_some(radii[0]);
|
||||
// The reference's order: Top Left, Top Right, Bottom Left, Bottom Right; the radii order is TL, TR, BR, BL.
|
||||
let corners = [(&words.top_left, 0), (&words.top_right, 1), (&words.bottom_left, 3), (&words.bottom_right, 2)];
|
||||
let _ = Popover::new(words.corner_radius.clone(), Bind::bound(open)).opened_by(&button).show(ui, |ui, _| {
|
||||
FieldGroup::new(words.corner_radius.clone()).labels(LabelScheme::Inspector).show(ui, |ui, _| {
|
||||
let mut field = |ui: &mut egui::Ui, caption: &Label, value: Option<f64>, corner: Option<usize>| {
|
||||
let events = Field::new(caption.clone())
|
||||
.id_salt(("shape-task-bar-radius", corner))
|
||||
.show(ui, |ui, _| NumberField::new(caption.clone(), Bind::given(value)).unit_kind(UnitKind::Pixels).show(ui).edit.events)
|
||||
.inner
|
||||
.unwrap_or_default();
|
||||
run.changes.extend(events.into_iter().map(|event| Change::Radius(corner, event)));
|
||||
};
|
||||
field(ui, &words.corner_radius, all, None);
|
||||
for (caption, index) in corners {
|
||||
field(ui, caption, radii.get(index).copied(), Some(index));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Runs each change the bar asked for on the target layer, one history step per change.
|
||||
fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, t: &Target, radii: [f64; 4], gradients: &[photocraft_doc::Fill; 2], changes: Vec<Change>) {
|
||||
let mut recent = None;
|
||||
let mut remembered = Vec::new();
|
||||
for change in changes {
|
||||
let (mut patch, key) = match &change {
|
||||
Change::Duplicate => {
|
||||
// The engine command, not the menu item: Layer › Duplicate Layer… asks for a name first, the bar does not.
|
||||
let result = app.run("layer.duplicate", json!({})).map(|_| ());
|
||||
report(app, result);
|
||||
continue;
|
||||
}
|
||||
Change::Properties => {
|
||||
let result = crate::menus::invoke(app, ctx, "window.panel.properties", json!({"show": true})).map(|_| ());
|
||||
report(app, result);
|
||||
continue;
|
||||
}
|
||||
Change::Fill(event) => {
|
||||
let Some(paint) = event.value() else { continue };
|
||||
if committed(event) {
|
||||
recent = solid_rgb(paint).or(recent);
|
||||
remembered.extend(picked_gradient(paint, &gradients[0]));
|
||||
}
|
||||
(json!({"fill": fill_param(paint, &gradients[0])}), coalesce(t, "fill", event))
|
||||
}
|
||||
Change::Stroke(event) => {
|
||||
let Some(paint) = event.value() else { continue };
|
||||
if committed(event) {
|
||||
recent = solid_rgb(paint).or(recent);
|
||||
remembered.extend(picked_gradient(paint, &gradients[1]));
|
||||
}
|
||||
let color = fill_param(paint, &gradients[1]);
|
||||
let width = t.shape.stroke.as_ref().map_or(0.0, |s| s.width);
|
||||
let stroke = if color.is_null() { Value::Null } else { json!({"color": color, "width": crate::vector_ui::enabled_stroke_width(width)}) };
|
||||
(json!({"stroke": stroke}), coalesce(t, "stroke", event))
|
||||
}
|
||||
Change::Cells(event) => {
|
||||
let Some(patch) = event.value().and_then(|c| cell_patch(c, &t.shape)) else { continue };
|
||||
(patch, coalesce(t, "stroke-cells", event))
|
||||
}
|
||||
Change::Radius(corner, event) => {
|
||||
let Some(r) = event.value().copied().flatten().filter(|r| r.is_finite()).map(|r| r.max(0.0)) else { continue };
|
||||
let next = match corner {
|
||||
None => [r; 4],
|
||||
Some(i) => {
|
||||
let mut next = radii;
|
||||
let Some(slot) = next.get_mut(*i) else { continue };
|
||||
*slot = r;
|
||||
next
|
||||
}
|
||||
};
|
||||
let field = match corner {
|
||||
None => "radius-all".to_owned(),
|
||||
Some(i) => format!("radius-{i}"),
|
||||
};
|
||||
(json!({"radii": next}), coalesce(t, &field, event))
|
||||
}
|
||||
};
|
||||
patch["layer"] = json!(t.layer.0);
|
||||
if let Some(key) = key {
|
||||
patch["coalesce"] = json!(key);
|
||||
}
|
||||
if let Err(e) = app.run("shape.edit", patch) {
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
}
|
||||
if let Some(rgb) = recent {
|
||||
crate::paint_picker::remember(app, rgb);
|
||||
}
|
||||
for g in &remembered {
|
||||
crate::shape_gradient_ui::remember_recent(&mut app.ui.recent_gradients, g);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `event` ends an edit (not a step of a running gesture or its cancel).
|
||||
fn committed<T>(event: &EditEvent<T>) -> bool {
|
||||
!matches!(event, EditEvent::Update { .. } | EditEvent::Cancel { .. })
|
||||
}
|
||||
|
||||
/// The history key that folds a gesture's steps on `field` of the target layer into one step.
|
||||
fn coalesce<T>(t: &Target, field: &str, event: &EditEvent<T>) -> Option<String> {
|
||||
crate::history_keys::coalesce(&format!("shape-task-bar-{}-{}-{field}", t.doc, t.layer.0), event)
|
||||
}
|
||||
|
||||
/// The gradient a chip's `paint` stands for over `base`; `None` for a paint that is no gradient.
|
||||
fn picked_gradient(paint: &Paint, base: &photocraft_doc::Fill) -> Option<photocraft_doc::Fill> {
|
||||
match paint {
|
||||
Paint::Gradient(preview) => Some(crate::shape_paint_ui::gradient_fill(preview, base)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `shape.edit` patch of a stroke width or stroke type change on `shape`; `None` for no edit.
|
||||
fn cell_patch(change: &ShapeChange, shape: &ShapeLayer) -> Option<Value> {
|
||||
match change {
|
||||
// A step that clamps at 0 on a shape with no stroke is no change.
|
||||
ShapeChange::StrokeWidth(w) if shape.stroke.is_none() && *w <= 0.0 => None,
|
||||
ShapeChange::StrokeWidth(w) => Some(json!({"stroke": {"width": w}})),
|
||||
ShapeChange::StrokeStyle { style, width, .. } => {
|
||||
let mut stroke = StrokeOptions::from_style(style).params();
|
||||
if let Some(w) = width {
|
||||
stroke["width"] = json!(w);
|
||||
}
|
||||
Some(json!({"stroke": stroke}))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn report(app: &mut PhotocraftApp, result: Result<(), String>) {
|
||||
if let Err(e) = result {
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../task_bar_shape_layer_tests.rs"]
|
||||
mod task_bar_shape_layer_tests;
|
||||
@@ -20,6 +20,8 @@ fn move_controls_fixture(first: [i32; 4]) -> (Harness<'static, Box<PhotocraftApp
|
||||
app.ui.tool_options.move_auto_select = true;
|
||||
app.ui.tool_options.move_target = "layer".into();
|
||||
app.ui.extras.snap = false;
|
||||
// The shape layer's contextual task bar (#16755) would sit over the points these tests press.
|
||||
app.ui.panels.context_task_bar = false;
|
||||
let ctx = app.ctx().clone();
|
||||
let mut h = Harness::builder().with_context(ctx).with_size(vec2(1000.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut Box<PhotocraftApp>| {
|
||||
|
||||
Reference in new issue
Block a user