PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Shape tools: a click opens Create Rectangle / Create Ellipse (#1175) (#2031)
David Mannc161a7a5c9ba
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 5635928fb..88d72b1a4 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -3961,6 +3961,10 @@ pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {}match d.tool {Tool::ObjectSelection => crate::retouch_ui::finish_object_selection(app, d.start, [end[0], end[1]], d.modifiers),+ // Photoshop: a click without dragging opens Create Rectangle / Ellipse / … instead.+ t if crate::vector_ui::is_shape_tool(t)+ && crate::shape_dialog::is_click(d.start, &d.points, app.current_zoom())+ && crate::shape_dialog::open(app, t, d.start).is_some() => {}t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live),Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]),Tool::Type | Tool::VerticalType => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]),diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 6383115b6..be9b0c68b 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -182,6 +182,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {}DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields),DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields),+ DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields),DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields),DialogKind::Command if crate::variables_ui::owns(&fields) => crate::variables_ui::body(app, ui, &mut fields),DialogKind::Command if crate::file_ui::owns(&fields) => crate::file_ui::body(app, ui, &mut fields),@@ -390,6 +391,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {}DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields),DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields),+ DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields),DialogKind::Command if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields),DialogKind::Command if crate::variables_ui::owns(&d.fields) => crate::variables_ui::confirm(app, &d.fields),DialogKind::Command if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields),diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 70bd1888a..d00feeb07 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2301,3 +2301,10 @@ fontWeight Italic KurzívaAuto Adjust Opacity Automaticky upravit krytíCrop Shield color Barva stínění oříznutíColor Picker (Crop Shield Color) Výběr barvy (Barva stínění oříznutí)+ From Center Ze středu+ Link radii Propojit poloměry+ Star Ratio: Poměr hvězdy:+ Create Rectangle Vytvořit obdélník+ Create Ellipse Vytvořit elipsu+ Create Triangle Vytvořit trojúhelník+ Create Polygon Vytvořit mnohoúhelníkdiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 9f28f9fee..aaf247647 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2339,3 +2339,10 @@ fontWeight Italic KursivAuto Adjust Opacity Deckkraft automatisch anpassenCrop Shield color Farbe des FreistellungsschutzesColor Picker (Crop Shield Color) Farbwähler (Farbe des Freistellungsschutzes)+ From Center Vom Mittelpunkt aus+ Link radii Radien verknüpfen+ Star Ratio: Sternverhältnis:+ Create Rectangle Rechteck erstellen+ Create Ellipse Ellipse erstellen+ Create Triangle Dreieck erstellen+ Create Polygon Polygon erstellendiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 3ce3f3068..fa51168af 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3410,3 +3410,10 @@ fontWeight Thin Πολύ λεπτάAuto Adjust Opacity Αυτόματη προσαρμογή αδιαφάνειαςCrop Shield color Χρώμα ασπίδας περικοπήςColor Picker (Crop Shield Color) Επιλογέας χρώματος (Χρώμα ασπίδας περικοπής)+ From Center Από το κέντρο+ Link radii Σύνδεση ακτίνων+ Star Ratio: Αναλογία αστεριού:+ Create Rectangle Δημιουργία ορθογωνίου+ Create Ellipse Δημιουργία έλλειψης+ Create Triangle Δημιουργία τριγώνου+ Create Polygon Δημιουργία πολυγώνουdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 7c06a08e2..fe28cc538 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2369,3 +2369,10 @@ fontWeight Italic CursivaAuto Adjust Opacity Ajustar opacidad automáticamenteCrop Shield color Color del escudo de recorteColor Picker (Crop Shield Color) Selector de color (Color del escudo de recorte)+ From Center Desde el centro+ Link radii Vincular radios+ Star Ratio: Relación de la estrella:+ Create Rectangle Crear rectángulo+ Create Ellipse Crear elipse+ Create Triangle Crear triángulo+ Create Polygon Crear polígonodiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 7c7127fbd..d9668f1a0 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2722,3 +2722,10 @@ fontWeight Italic ItaliqueAuto Adjust Opacity Réglage automatique de l’opacitéCrop Shield color Couleur du masque de recadrageColor Picker (Crop Shield Color) Sélecteur de couleurs (Couleur du masque de recadrage)+ From Center À partir du centre+ Link radii Lier les rayons+ Star Ratio: Proportion de l'étoile :+ Create Rectangle Créer un rectangle+ Create Ellipse Créer une ellipse+ Create Triangle Créer un triangle+ Create Polygon Créer un polygonediff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 4ec5c0b03..d8bf08499 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2709,3 +2709,10 @@ fontWeight Italic MiringAuto Adjust Opacity Sesuaikan Opasitas OtomatisCrop Shield color Warna perisai cropColor Picker (Crop Shield Color) Pemilih Warna (Warna Perisai Crop)+ From Center Dari Tengah+ Link radii Tautkan radius+ Star Ratio: Rasio bintang:+ Create Rectangle Buat Persegi Panjang+ Create Ellipse Buat Elips+ Create Triangle Buat Segitiga+ Create Polygon Buat Poligondiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 247641894..b44690896 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2370,3 +2370,10 @@ fontWeight Italic CorsivoAuto Adjust Opacity Regola automaticamente opacitàCrop Shield color Colore dello schermo di ritaglioColor Picker (Crop Shield Color) Selettore colore (Colore dello schermo di ritaglio)+ From Center Dal centro+ Link radii Collega raggi+ Star Ratio: Rapporto stella:+ Create Rectangle Crea rettangolo+ Create Ellipse Crea ellisse+ Create Triangle Crea triangolo+ Create Polygon Crea poligonodiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 48f740f30..10f968d25 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3325,3 +3325,10 @@ fontWeight Italic 斜体Auto Adjust Opacity 不透明度を自動調整Crop Shield color 切り抜きシールドのカラーColor Picker (Crop Shield Color) カラーピッカー(切り抜きシールドのカラー)+ From Center 中心から+ Link radii 半径をリンク+ Star Ratio: 星の比率:+ Create Rectangle 長方形を作成+ Create Ellipse 楕円を作成+ Create Triangle 三角形を作成+ Create Polygon 多角形を作成diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex cf343007b..92c1a567a 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2879,3 +2879,10 @@ fontWeight Italic 기울임Auto Adjust Opacity 자동으로 불투명도 조정Crop Shield color 자르기 방패 색상Color Picker (Crop Shield Color) 색상 선택기 (자르기 방패 색상)+ From Center 중앙에서+ Link radii 반경 연결+ Star Ratio: 별 비율:+ Create Rectangle 사각형 만들기+ Create Ellipse 타원 만들기+ Create Triangle 삼각형 만들기+ Create Polygon 다각형 만들기diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex afb97c92c..c22d1b6b3 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3485,3 +3485,10 @@ cameraRaw Whites WittenAuto Adjust Opacity Dekking automatisch aanpassenCrop Shield color Kleur van uitsnijschermColor Picker (Crop Shield Color) Kleurkiezer (kleur van uitsnijscherm)+ From Center Vanuit midden+ Link radii Radii koppelen+ Star Ratio: Sterverhouding:+ Create Rectangle Rechthoek maken+ Create Ellipse Ellips maken+ Create Triangle Driehoek maken+ Create Polygon Veelhoek makendiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 667ecacac..c9d77f56a 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3323,3 +3323,10 @@ cameraRaw Roughness ChropowatośćAuto Adjust Opacity Automatycznie dopasuj krycieCrop Shield color Kolor osłony kadrowaniaColor Picker (Crop Shield Color) Próbnik kolorów (Kolor osłony kadrowania)+ From Center Od środka+ Link radii Połącz promienie+ Star Ratio: Proporcja gwiazdy:+ Create Rectangle Utwórz prostokąt+ Create Ellipse Utwórz elipsę+ Create Triangle Utwórz trójkąt+ Create Polygon Utwórz wielokątdiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex fbcb12197..28850d136 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2729,3 +2729,10 @@ fontWeight Italic ItálicoAuto Adjust Opacity Ajustar opacidade automaticamenteCrop Shield color Cor da proteção de corteColor Picker (Crop Shield Color) Seletor de cores (Cor da proteção de corte)+ From Center A partir do centro+ Link radii Vincular raios+ Star Ratio: Proporção da estrela:+ Create Rectangle Criar retângulo+ Create Ellipse Criar elipse+ Create Triangle Criar triângulo+ Create Polygon Criar polígonodiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 388bbc068..9748b46dc 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2575,3 +2575,10 @@ fontWeight Italic КурсивAuto Adjust Opacity Автоматически настраивать непрозрачностьCrop Shield color Цвет экрана кадрированияColor Picker (Crop Shield Color) Палитра цветов (Цвет экрана кадрирования)+ From Center От центра+ Link radii Связать радиусы+ Star Ratio: Коэффициент звезды:+ Create Rectangle Создать прямоугольник+ Create Ellipse Создать эллипс+ Create Triangle Создать треугольник+ Create Polygon Создать многоугольникdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex b7b199527..829930874 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3410,3 +3410,10 @@ cameraRaw Masking МаскуванняAuto Adjust Opacity Автоматично налаштовувати непрозорістьCrop Shield color Колір екрана кадруванняColor Picker (Crop Shield Color) Вибір кольору (колір екрана кадрування)+ From Center Від центру+ Link radii Зв'язати радіуси+ Star Ratio: Пропорції зірки:+ Create Rectangle Створити прямокутник+ Create Ellipse Створити еліпс+ Create Triangle Створити трикутник+ Create Polygon Створити багатокутникdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 0ed80bf5b..4469c27d7 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2309,3 +2309,10 @@ fontWeight Italic 斜体Auto Adjust Opacity 自动调整不透明度Crop Shield color 裁剪屏蔽颜色Color Picker (Crop Shield Color) 拾色器(裁剪屏蔽颜色)+ From Center 从中心+ Link radii 链接半径+ Star Ratio: 星形比例:+ Create Rectangle 创建矩形+ Create Ellipse 创建椭圆+ Create Triangle 创建三角形+ Create Polygon 创建多边形diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 5cd9837e8..bb434c076 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2278,3 +2278,10 @@ fontWeight Italic 斜體Auto Adjust Opacity 自動調整不透明度Crop Shield color 裁切遮蔽顏色Color Picker (Crop Shield Color) 檢色器(裁切遮蔽顏色)+ From Center 從中心+ Link radii 連結半徑+ Star Ratio: 星形比例:+ Create Rectangle 建立矩形+ Create Ellipse 建立橢圓+ Create Triangle 建立三角形+ Create Polygon 建立多邊形diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 38e8de212..09c5ee0be 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -125,6 +125,7 @@ pub mod rulers;pub mod screen_picker;pub mod scrollbars;pub mod served_fonts;+pub mod shape_dialog;pub mod shortcut_dispatch;pub mod shortcuts;mod sizing;diff --git a/crates/ui-egui/src/shape_dialog.rs b/crates/ui-egui/src/shape_dialog.rsnew file mode 100644index 000000000..0056f255f--- /dev/null+++ b/crates/ui-egui/src/shape_dialog.rs@@ -0,0 +1,248 @@+//! Create Rectangle / Ellipse / Triangle / Polygon: a single click (no drag) with a Shape tool+//! opens Photoshop's creation dialog instead of drawing. OK runs the same `shape.create` command as+//! a drag, with the options bar's fill and stroke, at the clicked point (or centred on it).+//! Width and height are stored in document pixels (so automation can set them with+//! `ui.dialog.set`) and shown in the ruler unit.++use egui::{Align2, Sense, pos2, vec2};+use serde_json::{Map, Value, json};++use crate::PhotocraftApp;+use crate::state::{DialogKind, Tool};+use crate::theme::Tokens;++const MARK: &str = "__createShape";+/// Largest side the dialog accepts, in pixels (Photoshop's document limit).+const MAX_PX: f64 = 300_000.0;+/// Remembered values (document pixels; sides and radii come from the options bar).+const KEYS: [&str; 4] = ["width", "height", "fromCenter", "starRatio"];++pub fn owns(fields: &Map<String, Value>) -> bool {+ fields.contains_key(MARK)+}++/// The tool's name in the dialog fields and the title, for the tools that have a dialog.+fn kind_of(tool: Tool) -> Option<(&'static str, &'static str)> {+ Some(match tool {+ Tool::Rectangle => ("rectangle", "Create Rectangle"),+ Tool::EllipseShape => ("ellipse", "Create Ellipse"),+ Tool::Triangle => ("triangle", "Create Triangle"),+ Tool::Polygon => ("polygon", "Create Polygon"),+ _ => return None,+ })+}++fn pref_key(kind: &str) -> String {+ format!("shape.create.{kind}")+}++fn valid(key: &str, v: &Value) -> bool {+ match key {+ "width" | "height" => v.as_f64().is_some_and(|x| x.is_finite() && (1.0..=MAX_PX).contains(&x)),+ "starRatio" => v.as_f64().is_some_and(|x| x.is_finite() && (1.0..=100.0).contains(&x)),+ _ => v.is_boolean(),+ }+}++/// True for a press and release that never left `start` by more than a few screen pixels.+pub fn is_click(start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool {+ let slop = 3.0 / f64::from(zoom.max(0.01));+ points.iter().all(|p| (p[0] - start[0]).hypot(p[1] - start[1]) <= slop)+}++/// Open the creation dialog of `tool` for a click at `at` (document px). `None` for a tool without+/// one (Line, Custom Shape).+pub fn open(app: &mut PhotocraftApp, tool: Tool, at: [f64; 2]) -> Option<u64> {+ let (kind, label) = kind_of(tool)?;+ if !(at[0].is_finite() && at[1].is_finite()) {+ return None;+ }+ let o = &app.ui.tool_options;+ let r = f64::from(o.corner_radius.max(0.0));+ let sides = o.polygon_sides.clamp(3, 100);+ let mut f = Map::new();+ f.insert(MARK.into(), json!(kind));+ f.insert("__command".into(), json!("shape.create"));+ f.insert("__label".into(), json!(label));+ f.insert("__at".into(), json!([at[0].round(), at[1].round()]));+ f.insert("width".into(), json!(100.0));+ f.insert("height".into(), json!(100.0));+ f.insert("fromCenter".into(), json!(false));+ match kind {+ "rectangle" => {+ f.insert("radii".into(), json!([r, r, r, r]));+ f.insert("linkRadii".into(), json!(true));+ }+ "polygon" => {+ f.insert("sides".into(), json!(sides));+ f.insert("starRatio".into(), json!(100.0));+ }+ _ => {}+ }+ if let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(&pref_key(kind)) {+ for key in KEYS {+ if f.contains_key(key)+ && let Some(v) = saved.get(key).filter(|v| valid(key, v))+ {+ f.insert(key.into(), v.clone());+ }+ }+ }+ Some(app.ui.open_dialog(DialogKind::Command, f))+}++fn num(f: &Map<String, Value>, key: &str) -> Option<f64> {+ f.get(key).and_then(Value::as_f64).filter(|v| v.is_finite())+}++/// `shape.create` geometry for the dialog's values (no fill or stroke).+pub fn geometry(f: &Map<String, Value>) -> Result<Value, String> {+ let kind = f.get(MARK).and_then(Value::as_str).ok_or("not a Create Shape dialog")?;+ let at = f.get("__at").and_then(Value::as_array).ok_or("the dialog has no position")?;+ let (Some(x), Some(y)) = (at.first().and_then(Value::as_f64), at.get(1).and_then(Value::as_f64)) else {+ return Err("the dialog has no position".into());+ };+ let side = |key: &str, label: &str| -> Result<f64, String> {+ num(f, key).filter(|v| (1.0..=MAX_PX).contains(v)).ok_or_else(|| format!("{label} must be between 1 and {MAX_PX} pixels"))+ };+ let (w, h) = (side("width", "Width")?, side("height", "Height")?);+ let center = f.get("fromCenter").and_then(Value::as_bool).unwrap_or(false);+ if !(x.abs() <= MAX_PX && y.abs() <= MAX_PX) {+ return Err("the shape's position is out of range".into());+ }+ let (x0, y0) = if center { (x - w / 2.0, y - h / 2.0) } else { (x, y) };+ let rect = json!([x0, y0, w, h]);+ Ok(match kind {+ "rectangle" => {+ let mut radii = [0.0; 4];+ if let Some(a) = f.get("radii").and_then(Value::as_array) {+ for (r, v) in radii.iter_mut().zip(a) {+ *r = v.as_f64().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, w.min(h) / 2.0);+ }+ }+ if radii.iter().any(|r| *r > 0.0) { json!({"kind": "roundedRect", "rect": rect, "radii": radii}) } else { json!({"kind": "rect", "rect": rect}) }+ }+ "ellipse" => json!({"kind": "ellipse", "rect": rect}),+ "triangle" => json!({"kind": "polygon", "rect": rect, "sides": 3}),+ "polygon" => {+ let sides = num(f, "sides").map_or(5.0, |s| s.round().clamp(3.0, 100.0));+ let ratio = num(f, "starRatio").map_or(100.0, |r| r.clamp(1.0, 100.0));+ json!({"kind": "polygon", "rect": rect, "sides": sides, "starRatio": ratio / 100.0})+ }+ other => return Err(format!("unknown shape `{other}`")),+ })+}++/// OK: create the shape and remember the values for the next click.+pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {+ let result = geometry(f).and_then(|g| crate::vector_ui::create_shape(app, g));+ match &result {+ Ok(_) => {+ if let Some(kind) = f.get(MARK).and_then(Value::as_str) {+ let saved: Map<String, Value> = KEYS.iter().filter_map(|k| f.get(*k).map(|v| (k.to_string(), v.clone()))).collect();+ app.session.prefs.edit(|p| p.dialogs.insert(pref_key(kind), Value::Object(saved)));+ }+ }+ Err(e) => {+ app.ui.status = e.clone();+ app.ui.status_error = true;+ }+ }+ result+}++fn label(ui: &mut egui::Ui, text: &str) {+ let t = Tokens::get(ui.ctx());+ let (r, _) = ui.allocate_exact_size(vec2(96.0, 22.0), Sense::hover());+ ui.painter().text(pos2(r.right() - 6.0, r.center().y), Align2::RIGHT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim);+}++pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {+ ui.spacing_mut().item_spacing.y = 6.0;+ let kind = f.get(MARK).and_then(Value::as_str).unwrap_or("").to_string();+ // Width and height in the ruler unit (percent of the document's side).+ let ur = &app.session.prefs().units_and_rulers;+ let (unit, ppi) = (ur.rulers, ur.point_size.per_inch());+ let (dpi, size) = app+ .session+ .active()+ .map_or((72.0, [1.0, 1.0]), |d| (f64::from(d.doc.resolution_dpi.max(1.0)), [f64::from(d.doc.size.width), f64::from(d.doc.size.height)]));+ for (key, text, extent) in [("width", tl!("Width:"), size[0]), ("height", tl!("Height:"), size[1])] {+ ui.horizontal(|ui| {+ label(ui, text);+ let px = num(f, key).unwrap_or(100.0);+ let to_unit = |px: f64| unit.from_px(px, dpi, extent, ppi) as f32;+ let mut v = to_unit(px);+ if crate::widgets::value_field(ui, &mut v, to_unit(1.0)..=to_unit(MAX_PX), unit.suffix(), 110.0).changed() {+ let px = unit.to_px(f64::from(v), dpi, extent, ppi).clamp(1.0, MAX_PX);+ f.insert(key.into(), json!((px * 1000.0).round() / 1000.0));+ }+ });+ }+ match kind.as_str() {+ "rectangle" => {+ let mut radii = [0.0f32; 4];+ if let Some(a) = f.get("radii").and_then(Value::as_array) {+ for (r, v) in radii.iter_mut().zip(a) {+ *r = v.as_f64().unwrap_or(0.0) as f32;+ }+ }+ let mut linked = f.get("linkRadii").and_then(Value::as_bool).unwrap_or(true);+ let mut changed = None;+ ui.horizontal(|ui| {+ label(ui, tl!("Radius:"));+ ui.vertical(|ui| {+ for row in [[0usize, 1], [3, 2]] {+ ui.horizontal(|ui| {+ for i in row {+ if crate::widgets::value_field(ui, &mut radii[i], 0.0..=10000.0, "px", 72.0).changed() {+ changed = Some(i);+ }+ }+ });+ }+ });+ });+ ui.horizontal(|ui| {+ label(ui, "");+ if crate::widgets::checkbox(ui, &mut linked, tl!("Link radii")).changed() {+ f.insert("linkRadii".into(), json!(linked));+ }+ });+ if let Some(i) = changed {+ if linked {+ radii = [radii[i]; 4];+ }+ f.insert("radii".into(), json!(radii.map(|r| f64::from(r.max(0.0)))));+ }+ }+ "polygon" => {+ ui.horizontal(|ui| {+ label(ui, tl!("Sides:"));+ let mut s = num(f, "sides").unwrap_or(5.0) as f32;+ if crate::widgets::value_field(ui, &mut s, 3.0..=100.0, "", 72.0).changed() {+ f.insert("sides".into(), json!(s.round().clamp(3.0, 100.0) as u32));+ }+ });+ ui.horizontal(|ui| {+ label(ui, tl!("Star Ratio:"));+ let mut r = num(f, "starRatio").unwrap_or(100.0) as f32;+ if crate::widgets::value_field(ui, &mut r, 1.0..=100.0, "%", 72.0).changed() {+ f.insert("starRatio".into(), json!(f64::from(r.clamp(1.0, 100.0))));+ }+ });+ }+ _ => {}+ }+ ui.horizontal(|ui| {+ label(ui, "");+ let mut center = f.get("fromCenter").and_then(Value::as_bool).unwrap_or(false);+ if crate::widgets::checkbox(ui, &mut center, tl!("From Center")).changed() {+ f.insert("fromCenter".into(), json!(center));+ }+ });+}++#[cfg(test)]+#[path = "shape_dialog_tests.rs"]+mod tests;diff --git a/crates/ui-egui/src/shape_dialog_tests.rs b/crates/ui-egui/src/shape_dialog_tests.rsnew file mode 100644index 000000000..48fba5089--- /dev/null+++ b/crates/ui-egui/src/shape_dialog_tests.rs@@ -0,0 +1,202 @@+use photocraft_doc::LayerContent;+use photocraft_doc::vector::LiveShape;+use serde_json::json;++use super::*;+use crate::canvas::{Drag, finish_gesture};++fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap();+ app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap();+ app+}++fn press(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2]) {+ app.ui.tool = tool;+ let d = Drag::new(tool, start, vec![[start[0], start[1], 1.0], [end[0], end[1], 1.0]], egui::Modifiers::NONE, false);+ finish_gesture(app, d);+}++fn layers(app: &PhotocraftApp) -> usize {+ app.session.active().unwrap().doc.layers.len()+}++fn live(app: &PhotocraftApp) -> LiveShape {+ let st = app.session.active().unwrap();+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap();+ let LayerContent::Shape(sh) = &l.content else { panic!("not a shape layer") };+ sh.live.clone().unwrap()+}++fn set(app: &mut PhotocraftApp, id: u64, fields: Value) {+ let d = app.ui.dialog_mut(id).unwrap();+ for (k, v) in fields.as_object().unwrap() {+ d.fields.insert(k.clone(), v.clone());+ }+}++fn only_dialog(app: &PhotocraftApp) -> u64 {+ assert_eq!(app.ui.dialogs.len(), 1, "a click opens one dialog");+ let d = &app.ui.dialogs[0];+ assert!(owns(&d.fields));+ d.id+}++#[test]+fn a_rectangle_click_opens_create_rectangle_and_ok_draws_it_at_the_click() {+ let mut app = app();+ let before = layers(&app);+ press(&mut app, Tool::Rectangle, [20.4, 30.2], [20.4, 30.2]);+ let id = only_dialog(&app);+ assert_eq!(crate::dialogs::title(&app.ui.dialogs[0]), "Create Rectangle");+ assert_eq!(layers(&app), before, "the click itself draws nothing");+ set(&mut app, id, json!({"width": 120, "height": 45.5, "radii": [4, 4, 4, 4]}));+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert!(app.ui.dialogs.is_empty());+ assert_eq!(layers(&app), before + 1);+ assert_eq!(live(&app), LiveShape::Rect { rect: [20.0, 30.0, 120.0, 45.5], radii: [4.0; 4] });+ // The options bar's fill (foreground colour) is used, as for a drag.+ let st = app.session.active().unwrap();+ let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() };+ assert!(sh.fill.is_some());+}++#[test]+fn from_center_and_the_other_tools() {+ let mut app = app();+ press(&mut app, Tool::EllipseShape, [200.0, 150.0], [200.0, 150.0]);+ let id = only_dialog(&app);+ assert_eq!(crate::dialogs::title(&app.ui.dialogs[0]), "Create Ellipse");+ set(&mut app, id, json!({"width": 80, "height": 40, "fromCenter": true}));+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(live(&app), LiveShape::Ellipse { rect: [160.0, 130.0, 80.0, 40.0] });++ press(&mut app, Tool::Polygon, [10.0, 10.0], [10.0, 10.0]);+ let id = only_dialog(&app);+ set(&mut app, id, json!({"width": 50, "height": 60, "sides": 7, "starRatio": 50}));+ crate::dialogs::confirm(&mut app, id).unwrap();+ assert_eq!(live(&app), LiveShape::Polygon { rect: [10.0, 10.0, 50.0, 60.0], sides: 7, star_ratio: 0.5 });++ press(&mut app, Tool::Triangle, [5.0, 6.0], [5.0, 6.0]);+ let id = only_dialog(&app);+ crate::dialogs::confirm(&mut app, id).unwrap();+ let LiveShape::Polygon { sides: 3, .. } = live(&app) else { panic!("a triangle") };+}++#[test]+fn drags_still_draw_and_tools_without_a_dialog_ignore_clicks() {+ let mut app = app();+ let before = layers(&app);+ press(&mut app, Tool::Rectangle, [10.0, 10.0], [60.0, 40.0]);+ assert!(app.ui.dialogs.is_empty(), "a drag draws without a dialog");+ assert_eq!(live(&app), LiveShape::Rect { rect: [10.0, 10.0, 50.0, 30.0], radii: [0.0; 4] });+ for tool in [Tool::Line, Tool::CustomShape] {+ press(&mut app, tool, [30.0, 30.0], [30.0, 30.0]);+ assert!(app.ui.dialogs.is_empty(), "{tool:?}");+ }+ assert_eq!(layers(&app), before + 1);+}++#[test]+fn click_slop_scales_with_zoom() {+ let pts = |d: f64| vec![[10.0, 10.0, 1.0], [10.0 + d, 10.0, 1.0]];+ assert!(is_click([10.0, 10.0], &pts(2.0), 1.0));+ assert!(!is_click([10.0, 10.0], &pts(5.0), 1.0));+ assert!(!is_click([10.0, 10.0], &pts(2.0), 4.0), "2 document px at 400% is a drag");+ assert!(is_click([10.0, 10.0], &[], 0.0));+}++#[test]+fn cancel_draws_nothing_and_ok_remembers_the_size() {+ let mut app = app();+ let before = layers(&app);+ press(&mut app, Tool::Rectangle, [10.0, 10.0], [10.0, 10.0]);+ let id = only_dialog(&app);+ app.ui.close_dialog(id);+ assert_eq!(layers(&app), before);++ press(&mut app, Tool::Rectangle, [10.0, 10.0], [10.0, 10.0]);+ let id = only_dialog(&app);+ set(&mut app, id, json!({"width": 33, "height": 44, "fromCenter": true}));+ crate::dialogs::confirm(&mut app, id).unwrap();+ press(&mut app, Tool::Rectangle, [50.0, 50.0], [50.0, 50.0]);+ let f = &app.ui.dialogs[0].fields;+ assert_eq!((f["width"].as_f64(), f["height"].as_f64(), f["fromCenter"].as_bool()), (Some(33.0), Some(44.0), Some(true)));+ // Each tool remembers its own values.+ let id = only_dialog(&app);+ app.ui.close_dialog(id);+ press(&mut app, Tool::EllipseShape, [50.0, 50.0], [50.0, 50.0]);+ assert_eq!(app.ui.dialogs[0].fields["width"].as_f64(), Some(100.0));+}++#[test]+fn bad_values_are_errors_not_panics() {+ let mut app = app();+ for bad in [+ json!({"width": 0}),+ json!({"width": -5}),+ json!({"height": 1e12}),+ json!({"width": "wide"}),+ json!({"width": null}),+ json!({"__at": "here"}),+ json!({"__at": [1]}),+ json!({"__at": [1e308, 1e308], "fromCenter": true, "width": 300000, "height": 300000}),+ json!({"radii": "round"}),+ json!({"radii": [-1, 1e300, "x", null, 5]}),+ ] {+ let before = layers(&app);+ press(&mut app, Tool::Rectangle, [10.0, 10.0], [10.0, 10.0]);+ let id = only_dialog(&app);+ set(&mut app, id, bad.clone());+ let r = crate::dialogs::confirm(&mut app, id);+ if r.is_ok() {+ // Odd radii are clamped, not rejected.+ assert!(bad.get("radii").is_some(), "{bad} should be rejected");+ app.run("edit.undo", json!({})).unwrap();+ } else {+ assert!(app.ui.status_error);+ }+ assert!(app.ui.dialogs.is_empty());+ assert_eq!(layers(&app), before, "{bad}");+ }+ // Bad remembered values fall back to the defaults.+ app.session.prefs.edit(|p| p.dialogs.insert("shape.create.rectangle".into(), json!({"width": -1, "height": "x", "fromCenter": 3})));+ press(&mut app, Tool::Rectangle, [10.0, 10.0], [10.0, 10.0]);+ let f = &app.ui.dialogs[0].fields;+ assert_eq!((f["width"].as_f64(), f["height"].as_f64(), f["fromCenter"].as_bool()), (Some(100.0), Some(100.0), Some(false)));+}++#[test]+fn agents_click_set_and_confirm_over_the_control_channel() {+ let mut app = app();+ let ctx = egui::Context::default();+ let call = |app: &mut PhotocraftApp, method: &str, params: Value| {+ let (req, _rx) = crate::control::ControlRequest::new(method, params);+ match crate::control::handle(app, &ctx, &req) {+ crate::control::Outcome::Done(v) => v,+ _ => panic!("deferred"),+ }+ };+ call(&mut app, "ui.pointer", json!({"tool": "rectangle", "events": [{"kind": "down", "x": 40, "y": 50}, {"kind": "up", "x": 40, "y": 50}]}));+ let id = only_dialog(&app);+ for (field, value) in [("width", json!(64)), ("height", json!(32))] {+ call(&mut app, "ui.dialog.set", json!({"dialog": id, "field": field, "value": value}));+ }+ let r = call(&mut app, "ui.dialog.confirm", json!({"dialog": id}));+ assert_eq!(r["ok"], json!(true), "{r}");+ assert_eq!(live(&app), LiveShape::Rect { rect: [40.0, 50.0, 64.0, 32.0], radii: [0.0; 4] });+}++#[test]+fn the_dialog_body_renders_for_every_tool_and_unit() {+ let mut app = app();+ for (tool, unit) in [(Tool::Rectangle, "pixels"), (Tool::EllipseShape, "mm"), (Tool::Polygon, "percent"), (Tool::Triangle, "inches")] {+ app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": unit})).unwrap();+ let id = open(&mut app, tool, [1.0, 2.0]).unwrap();+ let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone();+ let ctx = egui::Context::default();+ ctx.run_ui(egui::RawInput::default(), |ui| body(&app, ui, &mut fields)).textures_delta.clear();+ app.ui.close_dialog(id);+ }+}diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rsindex 6e6ac4fe2..929cf3d8f 100644--- a/crates/ui-egui/src/vector_ui.rs+++ b/crates/ui-egui/src/vector_ui.rs@@ -87,23 +87,32 @@ fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], m/// Finish a Shape-tool drag: ⇧ constrains proportions, ⌥ draws from the centre.pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) {let Some(mut p) = shape_geometry(&app.ui.tool_options, tool, start, end, mods) else { return };- let fill = if app.ui.tool_options.shape_fill { json!(hex(app.session.tools.foreground)) } else { Value::Null };- let stroke = stroke_param(app);if tool == Tool::CustomShape {// ⇧ keeps the shape's proportions (the rect is already squared).if let Ok(rect) = serde_json::from_value(p["rect"].take()) {+ let (fill, stroke) = (fill_param(app), stroke_param(app));crate::preset_panels::finish_custom_shape(app, rect, mods.shift, fill, stroke);}return;}- p["fill"] = fill;- p["stroke"] = stroke;- if let Err(e) = app.run("shape.create", p) {+ if let Err(e) = create_shape(app, p) {app.ui.status = e;app.ui.status_error = true;}}+fn fill_param(app: &PhotocraftApp) -> Value {+ if app.ui.tool_options.shape_fill { json!(hex(app.session.tools.foreground)) } else { Value::Null }+}++/// Create a shape layer from `shape.create` geometry with the options bar's fill and stroke: the+/// end of a drag, and the Create Rectangle / Ellipse / … dialogs (`shape_dialog`).+pub fn create_shape(app: &mut PhotocraftApp, mut geometry: Value) -> Result<Value, String> {+ geometry["fill"] = fill_param(app);+ geometry["stroke"] = stroke_param(app);+ app.run("shape.create", geometry)+}+/// Shape-tool drag preview: the shape `finish_shape` will create, filled and stroked, under its/// path outline. Custom shapes show their box outline only.pub fn draw_shape_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) {diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 4fb0a680f..79ddbe531 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -53,7 +53,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i- Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`).- A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing.- `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows-- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven.+- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point.- Magnetic Lasso (`tool: "magneticLasso"`): a `down`/`up` pair is a click. The first sets the first fastening point (its modifiers set the selection mode); later clicks fasten a point, or close the border on the first point. `move` events trace the border with or without a button held, fastening points by themselves; with `alt: true` a click draws a straight segment and a drag a freehand one. `ui.inspect` shows the border in progress under `magnetic` (`path`, `anchors`, `live`, `mode`). `ui.key` Enter closes it along the edges, Backspace removes the last fastening point, Escape cancels. To select along edges in one call instead, use the `select.magneticLasso` command with rough points around the shape.- `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points (`button`: `left` (default), `right` or `middle`). `count` (default 1, `2` for a double-click) is at most 256; a larger one is an error and queues nothing- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`