Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Add centered and transformable painting symmetry axes (#1821)

Shayan Horbanka342ab88209b
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index b1c973160..32c27346b 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -20,13 +20,15 @@ next to them.
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
-| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg` and `direct-select.svg` (109 files) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
+| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `painting-symmetry.svg` and `symmetry-*.svg` (109 files) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{check,chevron-down,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/layer-mask.svg`, `assets/icons/adjustment-layer.svg` | Layers panel footer glyphs: Add a mask (a frame around a solid disc) and New Fill or Adjustment Layer (a circle, one half solid), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/eraser-background.svg`, `assets/icons/eraser-magic.svg` | Background Eraser and Magic Eraser tool glyphs: Lucide `eraser` plus added marks | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/eraser.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
+| `assets/icons/painting-symmetry.svg` | Painting symmetry glyph: Lucide `heart` with a central axis | Lucide Icons and Contributors; adapted by @shorbank | Derived from <https://github.com/lucide-icons/lucide> `icons/heart.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
+| `assets/icons/symmetry-{vertical,horizontal,dual,diagonal}.svg` | Painting symmetry axis glyphs | @shorbank | Original work; supplied SVG line geometry centred on a common square canvas, stroke adjusted to match the painting-symmetry glyph | MIT OR Apache-2.0, [`assets/icons/LICENSE-symmetry-axes.txt`](assets/icons/LICENSE-symmetry-axes.txt) |
| `assets/icons/lasso-magnetic.svg` | Magnetic Lasso tool glyph, adapted from "Magnetic Lasso Tool" (redrawn on the 24 px toolbar grid) | Lil' Seal (Noun Project); adapted by PhotoCraft contributors | <https://thenounproject.com/icon/magnetic-lasso-tool-177513/> | CC BY 3.0, [`assets/icons/LICENSE-noun-magnetic-lasso.txt`](assets/icons/LICENSE-noun-magnetic-lasso.txt) |
| `assets/dict/en_US-scowl-50.txt.gz` | English word list for Check Spelling (SCOWL 2020.12.07, size 50, en_US; 72,403 words) | Kevin Atkinson and the SCOWL contributors | <http://wordlist.aspell.net/> | SCOWL license (permissive, keep the notice), [`assets/dict/LICENSE-SCOWL.txt`](assets/dict/LICENSE-SCOWL.txt), which also has the build recipe |
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft Coated CMYK (synthetic) ICC profile | PhotoCraft contributors (generated by `photocraft-cms`, `src/synth.rs`) | Original work, see [`crates/cms/README.md`](crates/cms/README.md) | CC0-1.0 |
diff --git a/assets/icons/LICENSE-symmetry-axes.txt b/assets/icons/LICENSE-symmetry-axes.txt
new file mode 100644
index 000000000..2232ec82f
--- /dev/null
+++ b/assets/icons/LICENSE-symmetry-axes.txt
@@ -0,0 +1,207 @@
+Original painting symmetry axis icons by @shorbank (2026).
+Files: symmetry-vertical.svg, symmetry-horizontal.svg, symmetry-dual.svg, symmetry-diagonal.svg.
+SPDX-License-Identifier: MIT OR Apache-2.0
+
+These original icons are available under either licence below, at your option.
+
+MIT License
+
+Copyright (c) 2026 shorbank
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+---
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/assets/icons/painting-symmetry.svg b/assets/icons/painting-symmetry.svg
new file mode 100644
index 000000000..0ffdfca46
--- /dev/null
+++ b/assets/icons/painting-symmetry.svg
@@ -0,0 +1,13 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 29.33 30.81"
+ fill="none"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path stroke-width="2.48" d="M1.33,11.42c0-4.05,3.28-7.33,7.33-7.33,2.08,0,4.06.88,5.45,2.43.28.3.75.32,1.06.04.01-.01.02-.02.04-.04,2.69-3.02,7.31-3.29,10.33-.6,1.57,1.4,2.46,3.4,2.45,5.5,0,3.05-2,5.33-4,7.33l-7.32,7.08c-.97,1.11-2.65,1.23-3.76.26-.08-.07-.16-.15-.24-.23l-7.34-7.11c-2-2-4-4.27-4-7.33" />
+ <line stroke-width="2.41" x1="14.57" y1="1.3" x2="14.76" y2="29.51" />
+</svg>
diff --git a/assets/icons/symmetry-diagonal.svg b/assets/icons/symmetry-diagonal.svg
new file mode 100644
index 000000000..829274df9
--- /dev/null
+++ b/assets/icons/symmetry-diagonal.svg
@@ -0,0 +1,13 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 30.81 30.81"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2.41"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <line x1="25.445" y1="25.32" x2="5.365" y2="5.5" />
+</svg>
diff --git a/assets/icons/symmetry-dual.svg b/assets/icons/symmetry-dual.svg
new file mode 100644
index 000000000..cc6f4a365
--- /dev/null
+++ b/assets/icons/symmetry-dual.svg
@@ -0,0 +1,14 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 30.81 30.81"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2.41"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <line x1="29.51" y1="15.31" x2="1.3" y2="15.5" />
+ <line x1="15.5" y1="29.51" x2="15.31" y2="1.3" />
+</svg>
diff --git a/assets/icons/symmetry-horizontal.svg b/assets/icons/symmetry-horizontal.svg
new file mode 100644
index 000000000..fa64b3e48
--- /dev/null
+++ b/assets/icons/symmetry-horizontal.svg
@@ -0,0 +1,13 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 30.81 30.81"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2.41"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <line x1="29.51" y1="15.315" x2="1.3" y2="15.505" />
+</svg>
diff --git a/assets/icons/symmetry-vertical.svg b/assets/icons/symmetry-vertical.svg
new file mode 100644
index 000000000..6206a57ba
--- /dev/null
+++ b/assets/icons/symmetry-vertical.svg
@@ -0,0 +1,13 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 30.81 30.81"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2.41"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <line x1="15.315" y1="1.3" x2="15.505" y2="29.51" />
+</svg>
diff --git a/crates/engine/examples/bench_symmetry.rs b/crates/engine/examples/bench_symmetry.rs
new file mode 100644
index 000000000..be3f4cc06
--- /dev/null
+++ b/crates/engine/examples/bench_symmetry.rs
@@ -0,0 +1,33 @@
+//! Compare plain, single-axis and dual-axis live painting on a 24 MP document.
+//! Run with `cargo run --release -p photocraft-engine --example bench_symmetry`.
+use photocraft_engine::{Session, brush_cmds::LiveStroke};
+use photocraft_paint::StrokePoint;
+use serde_json::json;
+use std::time::Instant;
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ for mode in ["off", "vertical", "dual"] {
+ let mut samples = Vec::new();
+ for _ in 0..5 {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width":6000,"height":4000,"depth":8,"mode":"rgb"}))?;
+ if mode != "off" {
+ s.execute("paint.setSymmetry", json!({"mode":mode}))?;
+ }
+ let params = json!({"points":[[1800,1200]],"size":60,"hardness":0.8,"opacity":0.5,"smoothing":0.0,"seed":7});
+ let start = Instant::now();
+ let mut live = LiveStroke::begin(&s, &params)?;
+ for i in 1..=120 {
+ let t = f64::from(i);
+ live.push(&[StrokePoint::new(1800.0 + t * 2.0, 1200.0 + 20.0 * (t / 15.0).sin(), 1.0)])?;
+ }
+ std::hint::black_box(live.doc);
+ samples.push(start.elapsed().as_secs_f64() * 1000.0);
+ }
+ samples.sort_by(f64::total_cmp);
+ if let Some(median) = samples.get(2) {
+ println!("{mode}: median {median:.2} ms / 121 live samples (24 MP, 60 px brush, 5 runs)");
+ }
+ }
+ Ok(())
+}
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs
index 32581b69f..4c9dd4271 100644
--- a/crates/engine/src/brush_cmds.rs
+++ b/crates/engine/src/brush_cmds.rs
@@ -247,7 +247,7 @@ fn erase_locked(brush: &mut BrushSettings, lock: bool, bg: [f32; 4]) {
fn stroke_with(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pts: Vec<StrokePoint>, auto_erase: bool) -> Result<Value> {
let bg = s.tools.background;
let fg = brush.color;
- let symmetry = s.active().and_then(|st| st.symmetry_path.clone());
+ let symmetry = s.active().and_then(|st| st.symmetry.clone());
let (id, brush, zoom) = stroke_target(s, p, brush)?;
let dmg = s.edit(label, |doc, _| {
let sel = doc.selection.clone();
@@ -258,18 +258,25 @@ fn stroke_with(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pt
apply_auto_erase(&mut brush, surf, pts.first(), fg, bg);
}
let damage = if let Some(axis) = &symmetry {
- let reflected = axis.reflect_points(&pts);
- if crate::symmetry_cmds::SymmetryAxis::has_distinct_mirror(&pts, &reflected) {
+ let reflected = axis.reflected_passes(&pts);
+ let copies: Vec<_> = reflected
+ .iter()
+ .filter(|p| crate::symmetry_cmds::SymmetryAxis::has_distinct_mirror(&pts, p))
+ .map(|p| {
+ let mut renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom);
+ renderer.push(p);
+ renderer.finish();
+ renderer
+ })
+ .collect();
+ if copies.is_empty() {
+ render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom)
+ } else {
let pre = surf.clone();
let mut original = StrokeRenderer::new(&brush, Some(surf.format()), zoom);
original.push(&pts);
original.finish();
- let mut mirror = StrokeRenderer::new(&brush, Some(surf.format()), zoom);
- mirror.push(&reflected);
- mirror.finish();
- original.composite_union(&mirror, &pre, surf, sel.as_ref(), lock)
- } else {
- render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom)
+ original.composite_union_many(&copies, &pre, surf, sel.as_ref(), lock)
}
} else {
render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom)
@@ -332,8 +339,11 @@ pub struct LiveStroke {
pub seed: u64,
cmd: String,
renderer: StrokeRenderer,
- mirror: Option<(crate::symmetry_cmds::SymmetryAxis, StrokeRenderer)>,
- mirror_distinct: bool,
+ symmetry: Option<crate::symmetry_cmds::PaintingSymmetry>,
+ mirrors: Vec<StrokeRenderer>,
+ mirror_distinct: Vec<bool>,
+ /// Restore passes separately; their union may span an otherwise untouched document.
+ symmetry_regions: Vec<Rect>,
pre: Surface,
sel: Option<Surface>,
lock: bool,
@@ -370,15 +380,19 @@ impl LiveStroke {
apply_auto_erase(&mut brush, surf, pts.first(), fg, s.tools.background);
}
let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom);
- let mirror = s.active().and_then(|st| st.symmetry_path.clone()).map(|axis| (axis, StrokeRenderer::new(&brush, Some(surf.format()), zoom)));
+ let symmetry = s.active().and_then(|st| st.symmetry.clone());
+ let mirrors: Vec<_> = (0..symmetry.as_ref().map_or(0, |s| s.mirror_count())).map(|_| StrokeRenderer::new(&brush, Some(surf.format()), zoom)).collect();
+ let mirror_distinct = vec![false; mirrors.len()];
let pre = surf.clone();
let mut live = Self {
doc: std::sync::Arc::new(doc),
seed,
cmd: cmd.into(),
renderer,
- mirror,
- mirror_distinct: false,
+ symmetry,
+ mirrors,
+ mirror_distinct,
+ symmetry_regions: Vec::new(),
pre,
sel,
lock,
@@ -393,7 +407,7 @@ impl LiveStroke {
/// Everything the stroke has touched so far.
pub fn bounds(&self) -> Rect {
let bounds = self.renderer.bounds().union(&self.tail);
- if self.mirror_distinct { self.mirror.as_ref().map_or(bounds, |(_, renderer)| bounds.union(&renderer.bounds())) } else { bounds }
+ self.mirrors.iter().zip(&self.mirror_distinct).filter(|(_, distinct)| **distinct).fold(bounds, |b, (r, _)| b.union(&r.bounds()))
}
/// Render more points; returns the rectangle that changed. The doc shows the stroke as
@@ -404,25 +418,39 @@ impl LiveStroke {
pub fn push(&mut self, pts: &[StrokePoint]) -> Result<Rect> {
check_coords(pts, &self.cmd)?;
self.renderer.push(pts);
- if let Some((axis, mirror)) = &mut self.mirror {
- let reflected = axis.reflect_points(pts);
- self.mirror_distinct |= crate::symmetry_cmds::SymmetryAxis::has_distinct_mirror(pts, &reflected);
- mirror.push(&reflected);
+ if let Some(symmetry) = &self.symmetry {
+ for ((mirror, distinct), reflected) in self.mirrors.iter_mut().zip(&mut self.mirror_distinct).zip(symmetry.reflected_passes(pts)) {
+ *distinct |= crate::symmetry_cmds::SymmetryAxis::has_distinct_mirror(pts, &reflected);
+ mirror.push(&reflected);
+ }
}
let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.layer, &self.params)?;
- if let (true, Some((_, mirror))) = (self.mirror_distinct, &mut self.mirror) {
- // Preview the finished strokes through one coverage buffer. Shared axis pixels
- // therefore receive the brush opacity once, exactly like the final commit.
+ if self.mirror_distinct.iter().any(|d| *d) {
+ // Merge every finished pass once, both here and on commit, including shared axes.
let old = self.tail;
let mut original_preview = self.renderer.clone();
original_preview.finish();
- let mut mirror_preview = mirror.clone();
- mirror_preview.finish();
- let bounds = original_preview.bounds().union(&mirror_preview.bounds()).union(&old);
- if !bounds.is_empty() {
- surf.write_region(bounds, &self.pre.read_region(bounds));
+ let copies: Vec<_> = self
+ .mirrors
+ .iter()
+ .zip(&self.mirror_distinct)
+ .filter(|(_, d)| **d)
+ .map(|(r, _)| {
+ let mut r = r.clone();
+ r.finish();
+ r
+ })
+ .collect();
+ let bounds = copies.iter().fold(original_preview.bounds().union(&old), |b, r| b.union(&r.bounds()));
+ if self.symmetry_regions.is_empty() && !old.is_empty() {
+ surf.write_region(old, &self.pre.read_region(old));
+ }
+ for region in &self.symmetry_regions {
+ surf.write_region(*region, &self.pre.read_region(*region));
}
- let damage = original_preview.composite_union(&mirror_preview, &self.pre, surf, self.sel.as_ref(), self.lock);
+ self.symmetry_regions =
+ std::iter::once(original_preview.bounds()).chain(copies.iter().map(StrokeRenderer::bounds)).filter(|r| !r.is_empty()).collect();
+ let damage = original_preview.composite_union_many(&copies, &self.pre, surf, self.sel.as_ref(), self.lock);
self.tail = bounds;
return Ok(damage.union(&bounds));
}
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs
index 713f5b4c7..1d1c7e0c7 100644
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@ -44,6 +44,7 @@ pub fn document(d: &DocState) -> Value {
"revision": d.revision,
"channels": crate::channel_cmds::channels_json(d),
"quickMask": doc.quick_mask.is_some(),
+ "symmetry": d.symmetry.as_ref().map(|s| s.inspect()),
"layerMaskView": crate::mask_view_cmds::view_json(d),
"layerComps": doc.layer_comps.iter().map(|c| json!({"id": c.id, "name": c.name})).collect::<Vec<_>>(),
"lastAppliedComp": doc.last_applied_comp,
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index b871f5e95..9d3d748df 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -177,8 +177,8 @@ pub struct DocState {
pub channel_view: channel_cmds::ChannelView,
/// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state).
pub isolated_layers: Vec<LayerId>,
- /// Painting symmetry axis made from the selected path (tool state, not document pixels).
- pub symmetry_path: Option<symmetry_cmds::SymmetryAxis>,
+ /// Painting symmetry preset or sampled path (tool state, not document pixels).
+ pub symmetry: Option<symmetry_cmds::PaintingSymmetry>,
/// Layers panel: layers whose effects list is collapsed under their row (the fx triangle;
/// view state, not history). Effects lists start open.
pub fx_collapsed: Vec<LayerId>,
@@ -209,7 +209,7 @@ impl DocState {
coalesce: None,
channel_view: Default::default(),
isolated_layers: Vec::new(),
- symmetry_path: None,
+ symmetry: None,
fx_collapsed: Vec::new(),
show_only: None,
floating: None,
diff --git a/crates/engine/src/symmetry_cmds.rs b/crates/engine/src/symmetry_cmds.rs
index 2cd2601d3..2339568a0 100644
--- a/crates/engine/src/symmetry_cmds.rs
+++ b/crates/engine/src/symmetry_cmds.rs
@@ -1,8 +1,11 @@
-//! Painting symmetry along a path. A sampled Bézier polyline is kept as per-document tool state;
-//! each brush sample reflects across its nearest segment, including curved paths.
+//! Per-document painting symmetry: straight presets or a sampled Bézier path.
+//! Path samples reflect across their nearest segment, including curved paths.
use photocraft_doc::{LayerContent, vector::Path};
-use photocraft_paint::StrokePoint;
+use photocraft_paint::{
+ StrokePoint,
+ symmetry::{PresetSymmetry, SymmetryMode},
+};
use serde_json::{Value, json};
use crate::{EngineError, Result, Session, commands::CommandSpec};
@@ -11,12 +14,74 @@ use crate::{EngineError, Result, Session, commands::CommandSpec};
const MAX_SEGMENTS: usize = 1024;
const SAMPLES_PER_CURVE: usize = 12;
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, PartialEq)]
pub struct SymmetryAxis {
pub source: String,
pub segments: Vec<[[f64; 2]; 2]>,
}
+/// Per-document painting tool state, never stored in the document's paths or pixels.
+#[derive(Clone, Debug, PartialEq)]
+pub enum PaintingSymmetry {
+ Path(SymmetryAxis),
+ Preset(PresetSymmetry),
+}
+
+impl PaintingSymmetry {
+ pub fn preset(&self) -> Option<PresetSymmetry> {
+ match self {
+ Self::Preset(p) => Some(*p),
+ Self::Path(_) => None,
+ }
+ }
+ pub fn path_source(&self) -> Option<&str> {
+ match self {
+ Self::Path(p) => Some(&p.source),
+ Self::Preset(_) => None,
+ }
+ }
+ pub fn mirror_count(&self) -> usize {
+ match self {
+ Self::Path(_) => 1,
+ Self::Preset(p) => p.mirror_count(),
+ }
+ }
+ pub fn reflected_passes(&self, points: &[StrokePoint]) -> Vec<Vec<StrokePoint>> {
+ match self {
+ Self::Path(axis) => vec![axis.reflect_points(points)],
+ Self::Preset(p) => p.reflected_passes(points),
+ }
+ }
+ pub fn inspect(&self) -> Value {
+ match self {
+ Self::Path(axis) => json!({"mode":"path", "source":axis.source, "segments":axis.segments.len()}),
+ Self::Preset(p) => json!({"mode":p.mode.id(), "center":p.center, "rotation":p.rotation}),
+ }
+ }
+}
+
+fn set_preset(s: &mut Session, p: &Value) -> Result<Value> {
+ let fail = || EngineError::Other("symmetry requires a valid mode, a finite [x,y] centre and a finite rotation".into());
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let mode = p.get("mode").and_then(Value::as_str).and_then(SymmetryMode::from_id).ok_or_else(fail)?;
+ let center = match p.get("center") {
+ None => [f64::from(st.doc.size.width) / 2.0, f64::from(st.doc.size.height) / 2.0],
+ Some(v) => {
+ let values = v.as_array().filter(|v| v.len() == 2).ok_or_else(fail)?;
+ [values.first().and_then(Value::as_f64).ok_or_else(fail)?, values.get(1).and_then(Value::as_f64).ok_or_else(fail)?]
+ }
+ };
+ let rotation = match p.get("rotation") {
+ None => 0.0,
+ Some(v) => v.as_f64().ok_or_else(fail)?,
+ };
+ let preset = PresetSymmetry::new(mode, center, rotation).ok_or_else(fail)?;
+ let symmetry = PaintingSymmetry::Preset(preset);
+ let result = symmetry.inspect();
+ s.active_mut().ok_or(EngineError::NoDocument)?.symmetry = Some(symmetry);
+ Ok(result)
+}
+
impl SymmetryAxis {
pub fn from_path(source: String, path: &Path) -> Result<Self> {
let mut segments = Vec::new();
@@ -109,18 +174,28 @@ fn enable(s: &mut Session, p: &Value) -> Result<Value> {
let axis = SymmetryAxis::from_path(name.to_owned(), &active_path(s, name)?)?;
let count = axis.segments.len();
let st = s.active_mut().ok_or(EngineError::NoDocument)?;
- st.symmetry_path = Some(axis);
+ st.symmetry = Some(PaintingSymmetry::Path(axis));
Ok(json!({"enabled": true, "source": name, "segments": count}))
}
fn disable(s: &mut Session) -> Result<Value> {
let st = s.active_mut().ok_or(EngineError::NoDocument)?;
- st.symmetry_path = None;
+ st.symmetry = None;
Ok(json!({"enabled": false}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
+ CommandSpec {
+ id: "paint.setSymmetry",
+ label: "Set Painting Symmetry",
+ menu: &[],
+ shortcut: None,
+ params: r#"{"mode":"vertical|horizontal|dual|diagonal","center":[x,y]?,"rotation":degrees=0}"#,
+ enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
+ run: set_preset,
+ journal: true,
+ },
CommandSpec {
id: "paint.symmetryFromPath",
label: "Make Symmetry Path",
@@ -133,11 +208,11 @@ pub fn specs() -> Vec<CommandSpec> {
},
CommandSpec {
id: "paint.symmetryDisable",
- label: "Disable Symmetry Path",
+ label: "Disable Painting Symmetry",
menu: &[],
shortcut: None,
params: "{}",
- enabled: |s| s.active().filter(|st| st.symmetry_path.is_some()).map(|_| ()).ok_or_else(|| "no active symmetry path".into()),
+ enabled: |s| s.active().filter(|st| st.symmetry.is_some()).map(|_| ()).ok_or_else(|| "no active painting symmetry".into()),
run: |s, _| disable(s),
journal: true,
},
@@ -262,3 +337,6 @@ mod tests {
}
}
}
+
+#[cfg(test)]
+mod preset_tests;
diff --git a/crates/engine/src/symmetry_cmds/preset_tests.rs b/crates/engine/src/symmetry_cmds/preset_tests.rs
new file mode 100644
index 000000000..cdce34233
--- /dev/null
+++ b/crates/engine/src/symmetry_cmds/preset_tests.rs
@@ -0,0 +1,188 @@
+use super::*;
+use crate::brush_cmds::LiveStroke;
+use photocraft_doc::{Layer, LayerMask};
+
+fn session(depth: u8, mode: &str) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width":81,"height":61,"depth":depth,"mode":mode,"background":"white"})).unwrap();
+ s
+}
+#[test]
+fn presets_validate_atomically_and_leave_document_paths_and_history_untouched() {
+ let mut s = session(8, "rgb");
+ s.execute("path.set", json!({"name":"work","path":{"subpaths":[{"knots":[[2,3],[9,15]]}]}})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let history = s.active().unwrap().history.past_len();
+ let revision = s.active().unwrap().revision;
+ for mode in SymmetryMode::ALL {
+ s.execute("paint.setSymmetry", json!({"mode":mode.id()})).unwrap();
+ let p = s.active().unwrap().symmetry.as_ref().unwrap().preset().unwrap();
+ assert_eq!(p.center, [40.5, 30.5]);
+ assert_eq!(p.rotation, 0.0);
+ assert_eq!(crate::inspect::document(s.active().unwrap())["symmetry"]["mode"], mode.id());
+ assert_eq!(s.active().unwrap().doc, before);
+ assert_eq!((s.active().unwrap().history.past_len(), s.active().unwrap().revision), (history, revision));
+ }
+ s.execute("paint.setSymmetry", json!({"mode":"dual","center":[17,29],"rotation":45})).unwrap();
+ let original = s.active().unwrap().symmetry.clone();
+ for bad in [
+ Value::Null,
+ json!([]),
+ json!({}),
+ json!({"mode":"radial"}),
+ json!({"mode":7}),
+ json!({"mode":"dual","center":[1]}),
+ json!({"mode":"dual","center":[1,2,3]}),
+ json!({"mode":"dual","center":null}),
+ json!({"mode":"dual","center":["x",2]}),
+ json!({"mode":"dual","center":[1e8,0]}),
+ json!({"mode":"dual","rotation":"x"}),
+ json!({"mode":"dual","rotation":null}),
+ ] {
+ assert!(s.execute("paint.setSymmetry", bad).is_err());
+ assert_eq!(s.active().unwrap().symmetry, original);
+ assert_eq!(s.active().unwrap().doc, before);
+ }
+ s.execute("paint.setSymmetry", json!({"mode":"dual"})).unwrap();
+ assert_eq!(s.active().unwrap().symmetry.as_ref().unwrap().preset().unwrap().center, [40.5, 30.5]);
+ s.execute("paint.symmetryFromPath", json!({"name":"work"})).unwrap();
+ assert_eq!(s.active().unwrap().symmetry.as_ref().unwrap().path_source(), Some("work"));
+ s.execute("paint.symmetryDisable", json!({})).unwrap();
+ assert!(crate::inspect::document(s.active().unwrap())["symmetry"].is_null());
+ s.execute("paint.setSymmetry", json!({"mode":"vertical"})).unwrap();
+ s.execute("file.new", json!({"width":10,"height":20})).unwrap();
+ assert!(s.active().unwrap().symmetry.is_none());
+ assert!(s.set_active(0));
+ assert!(s.active().unwrap().symmetry.is_some());
+ let mut empty = Session::new();
+ assert!(!empty.is_enabled("paint.setSymmetry"));
+ assert!(empty.execute("paint.setSymmetry", json!({"mode":"vertical"})).is_err());
+}
+fn pixel(s: &Session, x: i32, y: i32) -> [f32; 4] {
+ let st = s.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)
+}
+#[test]
+fn every_preset_live_preview_matches_committed_pixels_and_undo_at_every_depth() {
+ for depth in [8, 16, 32] {
+ for mode in ["rgb", "gray"] {
+ for preset in SymmetryMode::ALL {
+ for command in ["paint.stroke", "paint.pencil"] {
+ let mut s = session(depth, mode);
+ s.execute("paint.setSymmetry", json!({"mode":preset.id(),"center":[40,30]})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let params = json!({"points":[[20,10],[24,14]],"size":5,"hardness":1.0,"color":"#000000","opacity":0.5,"smoothing":0.0,"seed":7});
+ let live = LiveStroke::begin_with(&s, command, &params).unwrap();
+ let past = s.active().unwrap().history.past_len();
+ s.execute(command, params).unwrap();
+ let st = s.active().unwrap();
+ assert_eq!(st.history.past_len(), past + 1);
+ let id = st.active_layer.unwrap();
+ let actual = st.doc.layer(id).unwrap().surface().unwrap();
+ let preview = live.doc.layer(id).unwrap().surface().unwrap();
+ let original = StrokePoint::new(20.0, 10.0, 1.0);
+ let p = st.symmetry.as_ref().unwrap().preset().unwrap();
+ let positions = std::iter::once(original).chain(p.reflected_passes(&[original]).into_iter().map(|p| p[0]));
+ for p in positions {
+ assert!(actual.rgba(p.x.round() as i32, p.y.round() as i32)[0] < 0.9, "{depth} {mode} {preset:?}");
+ }
+ for y in 0..61 {
+ for x in 0..81 {
+ let a = actual.rgba(x, y);
+ let b = preview.rgba(x, y);
+ assert!((0..4).all(|i| (a[i] - b[i]).abs() < 0.02));
+ }
+ }
+ let after = st.doc.clone();
+ assert!(s.undo());
+ assert_eq!(s.active().unwrap().doc, before);
+ assert!(s.redo());
+ assert_eq!(s.active().unwrap().doc, after);
+ }
+ }
+ }
+ }
+}
+#[test]
+fn dual_centre_overlap_has_one_opacity_ceiling_and_eraser_uses_the_same_copies() {
+ for depth in [8, 16, 32] {
+ let mut plain = session(depth, "rgb");
+ let mut symmetric = session(depth, "rgb");
+ symmetric.execute("paint.setSymmetry", json!({"mode":"dual","center":[40,30]})).unwrap();
+ let params = json!({"points":[[40,30]],"size":9,"hardness":1.0,"opacity":0.5,"color":"#000000","smoothing":0.0});
+ plain.execute("paint.stroke", params.clone()).unwrap();
+ symmetric.execute("paint.stroke", params).unwrap();
+ let a = pixel(&plain, 40, 30);
+ let b = pixel(&symmetric, 40, 30);
+ assert!((0..4).all(|i| (a[i] - b[i]).abs() < 0.02));
+ symmetric.execute("layer.new.layer", json!({})).unwrap();
+ symmetric.execute("edit.fill", json!({"color":"#000000"})).unwrap();
+ let params = json!({"points":[[20,10],[25,15]],"size":7,"hardness":1.0,"erase":true,"smoothing":0.0});
+ let mut live = LiveStroke::begin(&symmetric, &json!({"points":[[20,10]],"size":7,"hardness":1.0,"erase":true,"smoothing":0.0})).unwrap();
+ live.push(&[StrokePoint::new(25.0, 15.0, 1.0)]).unwrap();
+ symmetric.execute("paint.stroke", params).unwrap();
+ let st = symmetric.active().unwrap();
+ let id = st.active_layer.unwrap();
+ for (x, y) in [(20, 10), (60, 10), (20, 50), (60, 50)] {
+ let a = pixel(&symmetric, x, y);
+ let b = live.doc.layer(id).unwrap().surface().unwrap().rgba(x, y);
+ assert!(a[3] < 0.2);
+ assert!((0..4).all(|i| (a[i] - b[i]).abs() < 0.02));
+ }
+ }
+}
+#[test]
+fn selection_transparency_lock_and_mask_targets_apply_to_all_passes() {
+ let mut s = session(8, "rgb");
+ s.execute("paint.setSymmetry", json!({"mode":"dual","center":[40,30]})).unwrap();
+ s.execute("select.rect", json!({"x":0,"y":0,"width":40,"height":30})).unwrap();
+ s.execute("paint.stroke", json!({"points":[[20,10]],"size":5,"hardness":1.0,"color":"#000000"})).unwrap();
+ assert!(pixel(&s, 20, 10)[0] < 0.2);
+ assert!(pixel(&s, 60, 10)[0] > 0.9);
+ s.execute("select.deselect", json!({})).unwrap();
+ s.edit("Mask fixture", |doc, active| {
+ let mut layer = Layer::raster("Mask", doc.pixel_format());
+ layer.mask = Some(LayerMask::reveal_all());
+ layer.locks.transparency = true;
+ *active = Some(layer.id);
+ doc.layers.push(layer);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("paint.stroke", json!({"points":[[20,10]],"size":5,"color":"#000000","target":"mask"})).unwrap();
+ let st = s.active().unwrap();
+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap();
+ for (x, y) in [(20, 10), (60, 10), (20, 50), (60, 50)] {
+ assert!(l.mask.as_ref().unwrap().surface.rgba(x, y)[0] < 0.8);
+ }
+ assert!(l.surface().unwrap().content_bounds().is_empty());
+ s.execute("paint.stroke", json!({"points":[[20,10]],"size":5,"color":"#ff0000"})).unwrap();
+ assert!(s.active().unwrap().doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().content_bounds().is_empty());
+}
+
+#[test]
+fn streaming_across_dual_axes_keeps_one_opacity_and_matches_commit() {
+ let points = [[40.0, 30.0], [40.0, 20.0], [35.0, 20.0], [45.0, 40.0]];
+ for depth in [8, 16, 32] {
+ let mut s = session(depth, "rgb");
+ s.execute("paint.setSymmetry", json!({"mode":"dual","center":[40,30]})).unwrap();
+ let params = json!({"points":[points[0]],"size":9,"hardness":1.0,"opacity":0.5,"color":"#000000","smoothing":0.0});
+ let mut live = LiveStroke::begin(&s, &params).unwrap();
+ for [x, y] in points.into_iter().skip(1) {
+ live.push(&[StrokePoint::new(x, y, 1.0)]).unwrap();
+ }
+ let mut params = params;
+ params["points"] = json!(points);
+ s.execute("paint.stroke", params).unwrap();
+ let st = s.active().unwrap();
+ let id = st.active_layer.unwrap();
+ for y in 0..61 {
+ for x in 0..81 {
+ let a = pixel(&s, x, y);
+ let b = live.doc.layer(id).unwrap().surface().unwrap().rgba(x, y);
+ assert!(a[0] >= 0.49, "opacity applied more than once at {x},{y}");
+ assert!((0..4).all(|i| (a[i] - b[i]).abs() < 0.02), "preview differs at {x},{y}");
+ }
+ }
+ }
+}
diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs
index 6601a9f74..ec58d456e 100644
--- a/crates/paint/src/lib.rs
+++ b/crates/paint/src/lib.rs
@@ -28,6 +28,7 @@ pub mod render;
pub mod replace;
pub mod retouch;
pub mod rng;
+pub mod symmetry;
pub mod tile;
pub use brush::{
diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs
index d0d0ff68d..641500e1c 100644
--- a/crates/paint/src/render.rs
+++ b/crates/paint/src/render.rs
@@ -423,10 +423,24 @@ impl StrokeRenderer {
/// Composite the union of this stroke and a mirrored pass as one stroke. This keeps
/// overlapping dabs on a symmetry axis under one opacity ceiling at every bit depth.
pub fn composite_union(&self, other: &Self, pre: &Surface, target: &mut Surface, selection: Option<&Surface>, lock_transparency: bool) -> Rect {
+ self.composite_union_many(std::iter::once(other), pre, target, selection, lock_transparency)
+ }
+
+ /// Combine all symmetry passes before applying brush opacity and selection once.
+ pub fn composite_union_many<'a>(
+ &self,
+ others: impl IntoIterator<Item = &'a Self>,
+ pre: &Surface,
+ target: &mut Surface,
+ selection: Option<&Surface>,
+ lock_transparency: bool,
+ ) -> Rect {
let mut merged = self.clone();
- merged.cov.union_max(&other.cov);
- if let (Some(to), Some(from)) = (&mut merged.dual, &other.dual) {
- to.union_max(from);
+ for other in others {
+ merged.cov.union_max(&other.cov);
+ if let (Some(to), Some(from)) = (&mut merged.dual, &other.dual) {
+ to.union_max(from);
+ }
}
merged.composite(pre, target, selection, lock_transparency, true)
}
diff --git a/crates/paint/src/symmetry.rs b/crates/paint/src/symmetry.rs
new file mode 100644
index 000000000..6adf8a382
--- /dev/null
+++ b/crates/paint/src/symmetry.rs
@@ -0,0 +1,143 @@
+//! Straight painting symmetry axes. Geometry is independent of pixels and the UI.
+
+use crate::StrokePoint;
+use serde::{Deserialize, Serialize};
+
+pub const MAX_COORDINATE: f64 = 1_000_000.0;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SymmetryMode {
+ Vertical,
+ Horizontal,
+ Dual,
+ Diagonal,
+}
+
+impl SymmetryMode {
+ pub const ALL: [Self; 4] = [Self::Vertical, Self::Horizontal, Self::Dual, Self::Diagonal];
+ pub fn id(self) -> &'static str {
+ match self {
+ Self::Vertical => "vertical",
+ Self::Horizontal => "horizontal",
+ Self::Dual => "dual",
+ Self::Diagonal => "diagonal",
+ }
+ }
+ pub fn from_id(id: &str) -> Option<Self> {
+ Self::ALL.into_iter().find(|m| m.id() == id)
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
+pub struct PresetSymmetry {
+ pub mode: SymmetryMode,
+ pub center: [f64; 2],
+ /// Clockwise degrees relative to the mode's initial direction (document Y points down).
+ pub rotation: f64,
+}
+
+impl PresetSymmetry {
+ pub fn new(mode: SymmetryMode, center: [f64; 2], rotation: f64) -> Option<Self> {
+ if !rotation.is_finite() || !center.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORDINATE) {
+ return None;
+ }
+ Some(Self { mode, center, rotation: rotation.rem_euclid(360.0) })
+ }
+ pub fn directions(self) -> Vec<[f64; 2]> {
+ let initial: f64 = match self.mode {
+ SymmetryMode::Horizontal => 0.0,
+ SymmetryMode::Diagonal => 45.0,
+ _ => 90.0,
+ };
+ let a = (initial + self.rotation).to_radians();
+ let first = [a.cos(), a.sin()];
+ if self.mode == SymmetryMode::Dual { vec![first, [-first[1], first[0]]] } else { vec![first] }
+ }
+ pub fn mirror_count(self) -> usize {
+ if self.mode == SymmetryMode::Dual { 3 } else { 1 }
+ }
+ pub fn reflected_passes(self, points: &[StrokePoint]) -> Vec<Vec<StrokePoint>> {
+ let reflect = |p: &StrokePoint, direction: [f64; 2]| {
+ let [dx, dy] = [p.x - self.center[0], p.y - self.center[1]];
+ let along = dx * direction[0] + dy * direction[1];
+ StrokePoint { x: self.center[0] + 2.0 * along * direction[0] - dx, y: self.center[1] + 2.0 * along * direction[1] - dy, ..*p }
+ };
+ let mut copies: Vec<_> = self.directions().into_iter().map(|d| points.iter().map(|p| reflect(p, d)).collect()).collect();
+ if self.mode == SymmetryMode::Dual {
+ copies.push(points.iter().map(|p| StrokePoint { x: 2.0 * self.center[0] - p.x, y: 2.0 * self.center[1] - p.y, ..*p }).collect());
+ }
+ copies
+ }
+ /// Clip infinite axes to document bounds without assuming that their centre is inside.
+ pub fn segments(self, size: [f64; 2]) -> Vec<[[f64; 2]; 2]> {
+ self.directions()
+ .into_iter()
+ .filter_map(|d| {
+ let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
+ for ((origin, direction), extent) in self.center.into_iter().zip(d).zip(size) {
+ if direction.abs() < 1e-12 {
+ if origin < 0.0 || origin > extent {
+ return None;
+ }
+ } else {
+ let (a, b) = (-origin / direction, (extent - origin) / direction);
+ lo = lo.max(a.min(b));
+ hi = hi.min(a.max(b));
+ }
+ }
+ if !lo.is_finite() || !hi.is_finite() || hi < lo {
+ return None;
+ }
+ Some([[self.center[0] + lo * d[0], self.center[1] + lo * d[1]], [self.center[0] + hi * d[0], self.center[1] + hi * d[1]]])
+ })
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn modes_reflect_about_their_centre_and_keep_stylus_data() {
+ let p = StrokePoint { x: 12.0, y: 25.0, pressure: 0.4, tilt_x: 18.0, ..Default::default() };
+ for (mode, expected) in [(SymmetryMode::Vertical, [28.0, 25.0]), (SymmetryMode::Horizontal, [12.0, 35.0]), (SymmetryMode::Diagonal, [15.0, 22.0])] {
+ let s = PresetSymmetry::new(mode, [20.0, 30.0], 0.0).unwrap();
+ let r = s.reflected_passes(&[p])[0][0];
+ assert!((r.x - expected[0]).abs() < 1e-9 && (r.y - expected[1]).abs() < 1e-9);
+ assert_eq!((r.pressure, r.tilt_x), (p.pressure, p.tilt_x));
+ }
+ let s = PresetSymmetry::new(SymmetryMode::Dual, [20.0, 30.0], 0.0).unwrap();
+ let copies = s.reflected_passes(&[p]);
+ assert_eq!(copies.len(), 3);
+ for (p, e) in copies.iter().zip([[28.0, 25.0], [12.0, 35.0], [28.0, 35.0]]) {
+ assert!((p[0].x - e[0]).abs() < 1e-9 && (p[0].y - e[1]).abs() < 1e-9);
+ }
+ }
+ #[test]
+ fn rotated_axes_clip_on_rectangles_and_accept_half_pixel_centres() {
+ for size in [[100.0, 100.0], [101.0, 53.0]] {
+ for mode in SymmetryMode::ALL {
+ let s = PresetSymmetry::new(mode, [size[0] / 2.0, size[1] / 2.0], 0.0).unwrap();
+ let segments = s.segments(size);
+ assert_eq!(segments.len(), if mode == SymmetryMode::Dual { 2 } else { 1 });
+ for [a, b] in segments {
+ for p in [a, b] {
+ assert!(p[0] >= -1e-9 && p[0] <= size[0] + 1e-9 && p[1] >= -1e-9 && p[1] <= size[1] + 1e-9);
+ }
+ }
+ if mode == SymmetryMode::Diagonal {
+ let d = s.directions()[0];
+ assert!((d[0] - d[1]).abs() < 1e-9);
+ }
+ }
+ }
+ let s = PresetSymmetry::new(SymmetryMode::Vertical, [20.0, 30.0], 90.0).unwrap();
+ let p = s.reflected_passes(&[StrokePoint::new(12.0, 25.0, 1.0)])[0][0];
+ assert!((p.x - 12.0).abs() < 1e-9 && (p.y - 35.0).abs() < 1e-9);
+ assert!(PresetSymmetry::new(SymmetryMode::Dual, [f64::NAN, 0.0], 0.0).is_none());
+ assert!(PresetSymmetry::new(SymmetryMode::Dual, [0.0, 0.0], f64::INFINITY).is_none());
+ assert!(PresetSymmetry::new(SymmetryMode::Dual, [MAX_COORDINATE + 1.0, 0.0], 0.0).is_none());
+ assert!(PresetSymmetry::new(SymmetryMode::Horizontal, [20.0, -5.0], 0.0).unwrap().segments([100.0, 60.0]).is_empty());
+ }
+}
diff --git a/crates/ui-egui/src/brush_panel_tests.rs b/crates/ui-egui/src/brush_panel_tests.rs
index 1e8f2a43c..0bebf859a 100644
--- a/crates/ui-egui/src/brush_panel_tests.rs
+++ b/crates/ui-egui/src/brush_panel_tests.rs
@@ -325,7 +325,7 @@ fn airbrush_smoothing_options_and_symmetry_buttons_work() {
h.run_steps(3);
h.get_by_label("Work Path").click();
h.run_steps(3);
- let source = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().symmetry_path.as_ref().map(|a| a.source.clone());
+ let source = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().symmetry.as_ref().and_then(|a| a.path_source().map(str::to_owned));
assert_eq!(source(&h).as_deref(), Some("work"));
assert_eq!(last_journal(h.state()).unwrap(), ("paint.symmetryFromPath".to_string(), json!({"name": "work"})));
h.get_by_label("Set painting symmetry options").click();
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index ed99557e7..4158d9322 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1381,6 +1381,7 @@ fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
app.tab_strip = None;
retain_gpu_documents(app);
crate::transform_tool::track_steps(app, ui.ctx());
+ crate::symmetry_ui::track(app, ui.ctx());
let n = app.session.documents().len();
// Files opening in the background (#210) have tabs before they have documents.
let opening = !app.jobs.opens.is_empty();
@@ -2711,6 +2712,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
crate::distort_ui::draw_overlay(app, &painter, &xf);
crate::retouch_ui::draw_source_marker(app, &painter, &xf);
crate::vector_ui::draw_overlay(app, &painter, &xf, &doc);
+ crate::symmetry_ui::draw(app, &painter, &xf);
crate::analysis_ui::draw_overlay(app, &painter, &xf);
crate::gradient_ui::draw_overlay(app, &painter, &xf);
crate::slice_ui::draw_overlay(app, &painter, &xf);
@@ -3438,6 +3440,9 @@ fn tool_move(app: &mut PhotocraftApp, x: f64, y: f64, pressure: f32, mods: egui:
/// Tool state machine. Shared by mouse input and automation.
pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) {
+ if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) {
+ return;
+ }
// An Alt+right-drag armed for this press (`paint_mouse`): taken before anything else can
// consume the event, so it never outlives the press it was armed for (#297).
let armed = std::mem::take(&mut app.brush_resize_armed);
diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs
index 2f7816400..02c5bb85f 100644
--- a/crates/ui-egui/src/canvas_tool_menu.rs
+++ b/crates/ui-egui/src/canvas_tool_menu.rs
@@ -190,7 +190,7 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str)
"path.style.pasteFill" => !pending && shape && app.session.path_fill_clipboard.is_some(),
"path.style.pasteStroke" => !pending && shape && app.session.path_stroke_clipboard.is_some(),
"select.isolateLayers" => layer.is_some(),
- "paint.symmetryDisable" => st.symmetry_path.is_some(),
+ "paint.symmetryDisable" => st.symmetry.is_some(),
_ => false,
}
}
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index ea332083e..9766b259b 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2253,6 +2253,11 @@ fontWeight Italic Kurzíva
Reset View Obnovit zobrazení
Drag around the centre to rotate the view · Shift constrains to 15° Tažením kolem středu otočíte zobrazení · Shift omezí na 15°
+# Painting symmetry presets.
+ Dual Axis Dvojitá osa
+ Diagonal Diagonální
+ Transform Symmetry Transformovat symetrii
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Bodový vzorek
3 by 3 Average Průměr 3 × 3
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 4519a1826..e64c8c626 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2291,6 +2291,11 @@ fontWeight Italic Kursiv
Reset View Ansicht zurücksetzen
Drag around the centre to rotate the view · Shift constrains to 15° Ansicht drehen: im Bogen ziehen · Umschalt: 15°-Schritte
+# Painting symmetry presets.
+ Dual Axis Duale Achse
+ Diagonal Diagonal
+ Transform Symmetry Symmetrie transformieren
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample 1 Pixel
3 by 3 Average 3 x 3 Pixel Durchschnitt
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index ed7284773..290c42c4c 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3364,6 +3364,11 @@ fontWeight Thin Πολύ λεπτά
Preset Name Όνομα προεπιλογής
No saved presets yet. Δεν υπάρχουν ακόμη αποθηκευμένες προεπιλογές.
+# Painting symmetry presets.
+ Dual Axis Διπλός άξονας
+ Diagonal Διαγώνια
+ Transform Symmetry Μετασχηματισμός συμμετρίας
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Σημειακό δείγμα
3 by 3 Average Μέσος όρος 3 × 3
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index e72a69080..d865e249c 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2321,6 +2321,11 @@ fontWeight Italic Cursiva
Reset View Restablecer vista
Drag around the centre to rotate the view · Shift constrains to 15° Arrastre alrededor del centro para rotar la vista · Mayús fija a 15°
+# Painting symmetry presets.
+ Dual Axis Doble eje
+ Diagonal Diagonal
+ Transform Symmetry Transformar simetría
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Muestra puntual
3 by 3 Average Promedio de 3 × 3
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 25e7e1ecd..b23cffd70 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2674,6 +2674,11 @@ fontWeight Italic Italique
Reset View Réinitialiser la vue
Drag around the centre to rotate the view · Shift constrains to 15° Faites glisser autour du centre pour tourner la vue · Maj contraint à 15°
+# Painting symmetry presets.
+ Dual Axis Deux axes
+ Diagonal Diagonale
+ Transform Symmetry Transformer la symétrie
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Échantillon ponctuel
3 by 3 Average Moyenne 3 × 3
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index e1215b511..804ff5451 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2661,6 +2661,11 @@ fontWeight Italic Miring
Reset View Atur Ulang Tampilan
Drag around the centre to rotate the view · Shift constrains to 15° Seret di sekitar pusat untuk memutar tampilan · Shift membatasi ke 15°
+# Painting symmetry presets.
+ Dual Axis Sumbu Ganda
+ Diagonal Diagonal
+ Transform Symmetry Transformasi Simetri
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Sampel Titik
3 by 3 Average Rata-rata 3 × 3
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 8e0072b6c..c855f4616 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2322,6 +2322,11 @@ fontWeight Italic Corsivo
Reset View Reimposta vista
Drag around the centre to rotate the view · Shift constrains to 15° Trascina intorno al centro per ruotare la vista · Maiusc vincola a 15°
+# Painting symmetry presets.
+ Dual Axis Doppio asse
+ Diagonal Diagonale
+ Transform Symmetry Trasforma simmetria
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Campione puntiforme
3 by 3 Average Media 3 × 3
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index d2df4fba5..9d5e28b0f 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -2234,6 +2234,11 @@ fontWeight Italic 斜体
Reset View 表示をリセット
Drag around the centre to rotate the view · Shift constrains to 15° 中心の周りをドラッグして表示を回転 · Shift で 15° 単位
+# Painting symmetry presets.
+ Dual Axis 二軸
+ Diagonal 斜め
+ Transform Symmetry 対称軸を変形
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample ポイントサンプル
3 by 3 Average 3 × 3 平均
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 89a06b610..bb4a0409d 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2832,6 +2832,11 @@ fontWeight Italic 기울임
Reset View 보기 재설정
Drag around the centre to rotate the view · Shift constrains to 15° 중심 주위를 드래그해 보기를 회전합니다 · Shift는 15°로 제한
+# Painting symmetry presets.
+ Dual Axis 이중 축
+ Diagonal 대각선
+ Transform Symmetry 대칭 변형
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample 포인트 샘플
3 by 3 Average 3 × 3 평균
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 2db906632..943f50b85 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -3458,3 +3458,8 @@ cameraRaw Whites Witten
Point Sample Puntmonster
Sample Size: Monstergrootte:
Show Sampling Ring Monsterring tonen
+
+# Painting symmetry presets.
+ Dual Axis Dubbele as
+ Diagonal Diagonaal
+ Transform Symmetry Symmetrie transformeren
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index e6337b779..5349fe91d 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -1350,6 +1350,7 @@
Set background color Ustaw kolor tła
Set foreground color Ustaw kolor pierwszego planu
Set painting symmetry options Ustaw opcje symetrii malowania
+ Symmetry Off Symetria wyłączona
Set shape fill type Ustaw typ wypełnienia kształtu
Set shape stroke type Ustaw typ obrysu kształtu
Set the text color Ustaw kolor tekstu
@@ -3275,6 +3276,11 @@ cameraRaw Roughness Chropowatość
Reset View Resetuj widok
Drag around the centre to rotate the view · Shift constrains to 15° Przeciągnij wokół środka, aby obrócić widok · Shift ogranicza do 15°
+# Painting symmetry presets.
+ Dual Axis Podwójna oś
+ Diagonal Ukośna
+ Transform Symmetry Przekształć symetrię
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Próbka punktowa
3 by 3 Average Uśrednianie 3 × 3
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 53583057c..8765a4cc3 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2681,6 +2681,11 @@ fontWeight Italic Itálico
Reset View Redefinir visualização
Drag around the centre to rotate the view · Shift constrains to 15° Arraste ao redor do centro para girar a visualização · Shift restringe a 15°
+# Painting symmetry presets.
+ Dual Axis Eixo duplo
+ Diagonal Diagonal
+ Transform Symmetry Transformar simetria
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Amostra pontual
3 by 3 Average Média de 3 × 3
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 5e5c64140..ab173750e 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2524,6 +2524,12 @@ fontWeight Italic Курсив
Reset View Сбросить вид
Drag around the centre to rotate the view · Shift constrains to 15° Перетащите вокруг центра, чтобы повернуть вид · Shift фиксирует шаг 15°
+# Painting symmetry presets.
+ Dual Axis Две оси
+ Diagonal Диагональная
+ Transform Symmetry Трансформировать симметрию
+ Set painting symmetry options Настроить параметры симметричного рисования
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample Точечная выборка
3 by 3 Average Среднее 3 × 3
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index 8ba626bf0..216f39b12 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -3380,3 +3380,8 @@ cameraRaw Masking Маскування
Point Sample Точкова вибірка
Sample Size: Розмір зразка:
Show Sampling Ring Показувати кільце вибірки
+
+# Painting symmetry presets.
+ Dual Axis Подвійна вісь
+ Diagonal Діагональна
+ Transform Symmetry Трансформувати симетрію
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 369b89f92..c78379484 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2261,6 +2261,11 @@ fontWeight Italic 斜体
Reset View 重置视图
Drag around the centre to rotate the view · Shift constrains to 15° 绕中心拖动以旋转视图 · Shift 限制为 15°
+# Painting symmetry presets.
+ Dual Axis 双轴
+ Diagonal 对角线
+ Transform Symmetry 变换对称轴
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample 采样点
3 by 3 Average 3 × 3 平均
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index d3e009eb4..b6045adde 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2230,6 +2230,11 @@ fontWeight Italic 斜體
Reset View 重設檢視
Drag around the centre to rotate the view · Shift constrains to 15° 繞中心拖曳以旋轉檢視 · Shift 限制為 15°
+# Painting symmetry presets.
+ Dual Axis 雙軸
+ Diagonal 對角線
+ Transform Symmetry 變形對稱軸
+
# Eyedropper Sample Size and Sample (#1649).
Point Sample 取樣點
3 by 3 Average 3 × 3 平均
diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs
index ae14ec284..ceab5e72b 100644
--- a/crates/ui-egui/src/icon_data.rs
+++ b/crates/ui-egui/src/icon_data.rs
@@ -1,4 +1,4 @@
-//! Lucide icons (ISC licence), embedded and tinted at runtime.
+//! Icons embedded and tinted at runtime; sources and licences are listed in `ATTRIBUTION.md`.
pub static ICONS: &[(&str, &[u8])] = &[
("adjustment-layer", include_bytes!("../../../assets/icons/adjustment-layer.svg")),
@@ -71,6 +71,7 @@ pub static ICONS: &[(&str, &[u8])] = &[
("move", include_bytes!("../../../assets/icons/move.svg")),
("navigation", include_bytes!("../../../assets/icons/navigation.svg")),
("paint-bucket", include_bytes!("../../../assets/icons/paint-bucket.svg")),
+ ("painting-symmetry", include_bytes!("../../../assets/icons/painting-symmetry.svg")),
("palette", include_bytes!("../../../assets/icons/palette.svg")),
("panel-right", include_bytes!("../../../assets/icons/panel-right.svg")),
("panels-top-left", include_bytes!("../../../assets/icons/panels-top-left.svg")),
@@ -105,6 +106,10 @@ pub static ICONS: &[(&str, &[u8])] = &[
("squares-subtract", include_bytes!("../../../assets/icons/squares-subtract.svg")),
("stamp", include_bytes!("../../../assets/icons/stamp.svg")),
("sun", include_bytes!("../../../assets/icons/sun.svg")),
+ ("symmetry-diagonal", include_bytes!("../../../assets/icons/symmetry-diagonal.svg")),
+ ("symmetry-dual", include_bytes!("../../../assets/icons/symmetry-dual.svg")),
+ ("symmetry-horizontal", include_bytes!("../../../assets/icons/symmetry-horizontal.svg")),
+ ("symmetry-vertical", include_bytes!("../../../assets/icons/symmetry-vertical.svg")),
("swatch-book", include_bytes!("../../../assets/icons/swatch-book.svg")),
("text-cursor", include_bytes!("../../../assets/icons/text-cursor.svg")),
("toggle-left", include_bytes!("../../../assets/icons/toggle-left.svg")),
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index 10faa4058..a5135c04b 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -132,9 +132,14 @@ pub fn button_chrome(ui: &egui::Ui, rect: Rect, selected: bool, hovered: bool) -
/// Square icon button: transparent until hovered; `selected` gets the accent treatment.
pub fn button(ui: &mut egui::Ui, name: &str, box_size: f32, selected: bool, tooltip: &str) -> Response {
+ button_with_icon_size(ui, name, box_size, (box_size * 0.52).round(), selected, tooltip)
+}
+
+/// Square icon button with an explicit glyph size, independent of its hit area.
+pub fn button_with_icon_size(ui: &mut egui::Ui, name: &str, box_size: f32, icon_size: f32, selected: bool, tooltip: &str) -> Response {
let (rect, resp) = ui.allocate_exact_size(Vec2::splat(box_size), Sense::click());
let tint = button_chrome(ui, rect, selected, resp.hovered());
- paint(ui, rect, name, (box_size * 0.52).round(), tint);
+ paint(ui, rect, name, icon_size, tint);
if tooltip.is_empty() { resp } else { resp.on_hover_text(tl!(tooltip)) }
}
@@ -173,4 +178,38 @@ mod tests {
assert!(!s.contains("currentColor"), "{name}");
}
}
+
+ #[test]
+ fn symmetry_axes_rasterize_centred_with_matching_line_weight_at_both_dpis() {
+ for size in [14_u32, 28] {
+ let mut coverage = Vec::new();
+ for name in ["symmetry-vertical", "symmetry-horizontal", "symmetry-diagonal", "symmetry-dual"] {
+ let bytes = white_icons().get(name).unwrap();
+ let image = egui_extras::image::load_svg_bytes_with_size(
+ bytes,
+ egui::load::SizeHint::Size { width: size, height: size, maintain_aspect_ratio: true },
+ &Default::default(),
+ )
+ .unwrap();
+ assert_eq!(image.size, [size as usize; 2]);
+ let ink: Vec<_> = image.pixels.iter().enumerate().filter(|(_, p)| p.a() > 16).collect();
+ assert!(!ink.is_empty(), "{name}");
+ let xs: Vec<_> = ink.iter().map(|(i, _)| i % size as usize).collect();
+ let ys: Vec<_> = ink.iter().map(|(i, _)| i / size as usize).collect();
+ for coords in [&xs, &ys] {
+ let centre = (*coords.iter().min().unwrap() + *coords.iter().max().unwrap()) as f32 / 2.0;
+ assert!((centre - (size as f32 - 1.0) / 2.0).abs() <= 0.5, "{name}: off-centre");
+ }
+ assert!(ink.iter().all(|(_, p)| p.r() > 0 && p.r() == p.g() && p.g() == p.b()), "{name}: tinting mask must be white");
+ coverage.push(image.pixels.iter().map(|p| f32::from(p.a()) / 255.0).sum::<f32>());
+ }
+ let vertical = coverage[0];
+ // At 14px a diagonal's antialiasing can differ by nearly two covered pixels.
+ let tolerance = if size == 14 { 0.15 } else { 0.1 };
+ for single in &coverage[1..3] {
+ assert!((single - vertical).abs() / vertical < tolerance, "inconsistent axis stroke weight at {size}px: {coverage:?}");
+ }
+ assert!(coverage[3] > vertical * 1.7 && coverage[3] < vertical * 2.1);
+ }
+ }
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 1baf355bc..a3e6630c7 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -133,6 +133,7 @@ pub mod stroke_trail;
pub mod stroke_ui;
pub mod stylus;
pub mod swatches_ui;
+pub mod symmetry_ui;
mod tab_strip;
pub mod theme;
pub mod tiff_options_ui;
@@ -682,6 +683,9 @@ impl PhotocraftApp {
}
fn run_command(&mut self, id: &str, params: Value) -> Result<Value, String> {
+ if matches!(id, "paint.setSymmetry" | "paint.symmetryFromPath" | "paint.symmetryDisable") {
+ self.ui.symmetry_transform = None;
+ }
let clip_read = std::mem::take(&mut self.clip_read_for_paste);
if self.automation_input
&& let Some(authorize) = self.services.automation_command.as_ref()
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index d7ce96f0a..0ce963b36 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -20,6 +20,7 @@ pub const TOP_MENUS: [&str; 10] = ["File", "Edit", "Image", "Layer", "Type", "Se
/// UI-level commands (handled by the shell rather than the engine): id, label, menu, shortcut.
pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
+ ("ui.symmetryTransform", "Transform Symmetry", &[], None),
("file.open", "Open…", &["File"], Some("Cmd+O")),
("file.save", "Save", &["File"], Some("Cmd+S")),
("file.saveAs", "Save As…", &["File"], Some("Cmd+Shift+S")),
@@ -134,6 +135,9 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
/// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it.
pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
+ if id == "ui.symmetryTransform" {
+ return crate::symmetry_ui::begin(app).map(|_| Value::Null);
+ }
// A pending Pen anchor is gesture state; Edit › Undo must match the keyboard.
if id == "edit.undo" && crate::vector_ui::pen_undo_last_point(app) {
return Ok(Value::Null);
@@ -501,6 +505,9 @@ fn open_path(app: &mut PhotocraftApp, path: &str) -> Result<Value, String> {
}
pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
+ if id == "ui.symmetryTransform" {
+ return crate::symmetry_ui::can_transform(app);
+ }
// Draft Pen points can be undone even when the document has no History entries.
if id == "edit.undo" && app.ui.pen.as_ref().is_some_and(|pen| !pen.knots.is_empty()) {
return true;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index b0db717e1..568574348 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -753,7 +753,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if icons::button(ui, "circle-dot", 24.0, b.pressure_size, tl!("Always use pressure for size")).clicked() {
b.pressure_size = !b.pressure_size;
}
- symmetry_menu(app, ui);
+ crate::symmetry_ui::menu(app, ui);
}
// Pencil: Photoshop's options (no hardness or flow: the pencil is always hard).
Tool::Pencil => {
@@ -2834,54 +2834,6 @@ fn smoothing_options(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings
});
}
-/// The symmetry menu's rows: `paint.symmetryFromPath` name and label for each path the Paths
-/// panel lists (saved paths, the Work Path, the selected layer's shape path or vector mask).
-fn symmetry_choices(app: &PhotocraftApp) -> Vec<(String, String)> {
- use crate::vector_ui::PathRow;
- let Some(st) = app.session.active() else { return Vec::new() };
- crate::vector_ui::path_rows(&st.doc, st.active_layer)
- .into_iter()
- .map(|row| match row.kind {
- PathRow::Saved => (row.name.clone(), row.name),
- PathRow::Work => ("work".to_string(), tl!("Work Path").to_string()),
- PathRow::Layer => ("layer".to_string(), row.name),
- })
- .collect()
-}
-
-/// Options-bar painting symmetry: Symmetry Off, or mirror Brush and Eraser strokes across one of
-/// the document's paths (`paint.symmetryFromPath`). The button is lit while symmetry is on.
-fn symmetry_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
- let t = Tokens::get(ui.ctx());
- let current = app.session.active().and_then(|st| st.symmetry_path.as_ref()).map(|axis| axis.source.clone());
- let choices = symmetry_choices(app);
- let resp = icons::button(ui, "arrow-left-right", 24.0, current.is_some(), tl!("Set painting symmetry options"));
- let resp = crate::brush_picker::named(resp, tl!("Set painting symmetry options"));
- egui::Popup::menu(&resp).show(|ui| {
- ui.set_min_width(200.0);
- let mut run = None;
- if ui.add(egui::Button::selectable(current.is_none(), tl!("Symmetry Off"))).clicked() {
- run = current.is_some().then(|| ("paint.symmetryDisable", json!({})));
- ui.close();
- }
- ui.separator();
- if choices.is_empty() {
- ui.label(RichText::new(tl!("Draw with the Pen tool (P) or make a work path from a selection.")).color(t.text_faint));
- }
- for (name, label) in &choices {
- if ui.add(egui::Button::selectable(current.as_ref() == Some(name), label)).clicked() {
- run = Some(("paint.symmetryFromPath", json!({ "name": name })));
- ui.close();
- }
- }
- if let Some((id, params)) = run
- && let Err(e) = app.run(id, params)
- {
- app.ui.status = e;
- }
- });
-}
-
/// Options-bar brush chip: a click shows or hides Photoshop's Brush Preset picker below it (size,
/// hardness, the preset library), the one a right-click on the canvas opens.
fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushSettings, state: &mut crate::state::UiState) {
diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs
index 0c77677b0..b7dbd1878 100644
--- a/crates/ui-egui/src/shortcuts.rs
+++ b/crates/ui-egui/src/shortcuts.rs
@@ -252,6 +252,11 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
if crate::menu_nav::is_open(ctx) {
return;
}
+ let symmetry_editing = app.ui.symmetry_transform.is_some();
+ crate::symmetry_ui::track(app, ctx);
+ if symmetry_editing && (app.ui.symmetry_transform.is_none() || egui::Popup::is_any_open(ctx)) {
+ return;
+ }
// Liquify is a full-window custom dialog with focusable sliders. egui can therefore claim
// keyboard input before the distortion-mode handler below runs. Give Liquify's local
// shortcuts first refusal (Undo, brush size, tool keys), but never steal keys from text edits.
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 6814cac83..d350a3054 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -812,6 +812,9 @@ pub struct UiState {
/// Free Transform session, if any.
#[serde(default)]
pub transform: Option<TransformSession>,
+ /// Temporary symmetry-axis editing, exposed to automation but never restored from settings.
+ #[serde(default, skip_deserializing)]
+ pub symmetry_transform: Option<crate::symmetry_ui::Transform>,
/// Clone Stamp / Healing source point (⌥-click) and the aligned offset once a stroke started.
#[serde(default)]
pub clone_source: Option<[f64; 2]>,
@@ -966,6 +969,7 @@ impl Default for UiState {
type_transform: None,
type_transform_pivot: None,
transform: None,
+ symmetry_transform: None,
mask_target: false,
vector_mask_target: false,
brush_picker: None,
diff --git a/crates/ui-egui/src/symmetry_ui.rs b/crates/ui-egui/src/symmetry_ui.rs
new file mode 100644
index 000000000..deb9ad6c7
--- /dev/null
+++ b/crates/ui-egui/src/symmetry_ui.rs
@@ -0,0 +1,269 @@
+//! Painting symmetry menu, guides and an isolated, cancellable transform preview.
+use crate::{
+ PhotocraftApp,
+ canvas::{ToolEvent, ViewXform},
+ icons,
+ state::Tool,
+ theme::Tokens,
+ widgets,
+};
+use egui::{Atom, Key, Stroke, vec2};
+use photocraft_doc::Document;
+use photocraft_engine::symmetry_cmds::PaintingSymmetry;
+use photocraft_paint::symmetry::{PresetSymmetry, SymmetryMode};
+use serde::Serialize;
+use serde_json::json;
+use std::sync::Arc;
+
+#[derive(Clone, Debug, Serialize)]
+pub struct Transform {
+ pub original: PresetSymmetry,
+ pub preview: PresetSymmetry,
+ document: usize,
+ tool: Tool,
+ #[serde(skip)]
+ source: Arc<Document>,
+ #[serde(skip)]
+ gesture: Option<Gesture>,
+}
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Gesture {
+ Move { start: [f64; 2], center: [f64; 2] },
+ Rotate { angle: f64, rotation: f64 },
+}
+
+impl PartialEq for Transform {
+ fn eq(&self, other: &Self) -> bool {
+ self.original == other.original
+ && self.preview == other.preview
+ && self.document == other.document
+ && self.tool == other.tool
+ && self.gesture == other.gesture
+ && Arc::ptr_eq(&self.source, &other.source)
+ }
+}
+
+fn label(mode: SymmetryMode) -> &'static str {
+ match mode {
+ SymmetryMode::Vertical => tl!("Vertical"),
+ SymmetryMode::Horizontal => tl!("Horizontal"),
+ SymmetryMode::Dual => tl!("Dual Axis"),
+ SymmetryMode::Diagonal => tl!("Diagonal"),
+ }
+}
+fn preset(app: &PhotocraftApp) -> Option<PresetSymmetry> {
+ app.session.active()?.symmetry.as_ref()?.preset()
+}
+
+pub fn can_transform(app: &PhotocraftApp) -> bool {
+ matches!(app.ui.tool, Tool::Brush | Tool::Pencil | Tool::Eraser)
+ && app.drag.is_none()
+ && preset(app).is_some()
+ && app.ui.transform.is_none()
+ && app.ui.text_edit.is_none()
+ && app.ui.dialogs.is_empty()
+ && app.camera_raw.is_none()
+ && app.distort.liquify.is_none()
+ && app.distort.puppet.is_none()
+ && app.distort.perspective.is_none()
+ && crate::jobs_ui::job_in_view(app).is_none()
+}
+pub fn begin(app: &mut PhotocraftApp) -> Result<(), String> {
+ if !can_transform(app) {
+ return Err("no preset symmetry available to transform".into());
+ }
+ let original = preset(app).ok_or("no preset symmetry")?;
+ let document = app.session.active_index().ok_or("no document")?;
+ let source = app.session.active().ok_or("no document")?.doc.clone();
+ app.ui.symmetry_transform = Some(Transform { original, preview: original, document, source, tool: app.ui.tool, gesture: None });
+ Ok(())
+}
+pub fn commit(app: &mut PhotocraftApp) {
+ if let Some(t) = app.ui.symmetry_transform.take() {
+ let _ = app.run("paint.setSymmetry", json!({"mode":t.preview.mode.id(), "center":t.preview.center,"rotation":t.preview.rotation}));
+ }
+}
+fn valid(app: &PhotocraftApp, t: &Transform) -> bool {
+ app.session.active_index() == Some(t.document)
+ && app.ui.tool == t.tool
+ && can_transform(app)
+ && preset(app) == Some(t.original)
+ && app.session.active().is_some_and(|s| Arc::ptr_eq(&s.doc, &t.source))
+}
+pub fn track(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let Some(t) = &app.ui.symmetry_transform else {
+ return;
+ };
+ if !valid(app, t) || !ctx.input(|i| i.focused) {
+ app.ui.symmetry_transform = None;
+ return;
+ }
+ // A popup owns Enter/Escape; dismissing it must not commit or cancel the transform.
+ if crate::menu_nav::is_open(ctx) || egui::Popup::is_any_open(ctx) {
+ return;
+ }
+ if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
+ app.ui.symmetry_transform = None;
+ } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter)) {
+ commit(app);
+ }
+}
+
+/// Highlight the active mode without reserving a separate checkmark column.
+fn mode_button(ui: &mut egui::Ui, mode: SymmetryMode, checked: bool) -> egui::Response {
+ let icon = ui.id().with((mode.id(), "icon"));
+ let name = label(mode);
+ let b = egui::Button::new((Atom::custom(icon, vec2(16.0, 16.0)), name, Atom::grow())).selected(checked).atom_ui(ui);
+ let tint = Tokens::get(ui.ctx()).icon;
+ if let Some(r) = b.rect(icon) {
+ let glyph = match mode {
+ SymmetryMode::Vertical => "symmetry-vertical",
+ SymmetryMode::Horizontal => "symmetry-horizontal",
+ SymmetryMode::Dual => "symmetry-dual",
+ SymmetryMode::Diagonal => "symmetry-diagonal",
+ };
+ icons::paint(ui, r, glyph, 14.0, tint);
+ }
+ b.response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), checked, name));
+ b.response
+}
+pub fn menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let current = app.session.active().and_then(|s| s.symmetry.clone());
+ let resp = icons::button_with_icon_size(ui, "painting-symmetry", 24.0, 14.0, current.is_some(), tl!("Set painting symmetry options"));
+ let resp = crate::brush_picker::named(resp, tl!("Set painting symmetry options"));
+ egui::Popup::menu(&resp).show(|ui| {
+ ui.set_min_width(220.0);
+ widgets::menu_scroll(ui, |ui| {
+ let mut run = None;
+ if ui
+ .add_enabled(
+ current.is_some() && crate::menus::is_enabled(app, "paint.symmetryDisable"),
+ egui::Button::selectable(current.is_none(), tl!("Symmetry Off")),
+ )
+ .clicked()
+ {
+ run = Some(("paint.symmetryDisable", json!({})));
+ ui.close();
+ }
+ ui.separator();
+ for mode in SymmetryMode::ALL {
+ let checked = current.as_ref().and_then(PaintingSymmetry::preset).is_some_and(|p| p.mode == mode);
+ if ui.add_enabled_ui(crate::menus::is_enabled(app, "paint.setSymmetry"), |ui| mode_button(ui, mode, checked)).inner.clicked() {
+ run = Some(("paint.setSymmetry", json!({"mode":mode.id()})));
+ ui.close();
+ }
+ }
+ if let Some(st) = app.session.active() {
+ use crate::vector_ui::{PathRow, path_rows};
+ let rows = path_rows(&st.doc, st.active_layer);
+ if !rows.is_empty() {
+ ui.separator();
+ }
+ for row in rows {
+ let (name, text) = match row.kind {
+ PathRow::Saved => (row.name.clone(), row.name),
+ PathRow::Work => ("work".into(), tl!("Work Path").into()),
+ PathRow::Layer => ("layer".into(), row.name),
+ };
+ let checked = current.as_ref().and_then(PaintingSymmetry::path_source) == Some(name.as_str());
+ if ui.add_enabled(crate::menus::is_enabled(app, "paint.symmetryFromPath"), egui::Button::selectable(checked, text)).clicked() {
+ run = Some(("paint.symmetryFromPath", json!({"name":name})));
+ ui.close();
+ }
+ }
+ }
+ ui.separator();
+ if ui.add_enabled(can_transform(app), egui::Button::new(tl!("Transform Symmetry"))).clicked() {
+ if let Err(e) = crate::menus::invoke(app, ui.ctx(), "ui.symmetryTransform", json!({})) {
+ app.ui.status = e;
+ }
+ ui.close();
+ }
+ if let Some((id, params)) = run {
+ let _ = app.run(id, params);
+ }
+ });
+ });
+}
+
+fn rotation_handle(p: PresetSymmetry, size: [f64; 2]) -> [f64; 2] {
+ let d = p.directions().into_iter().next().unwrap_or([1.0, 0.0]);
+ let r = (size[0].min(size[1]) * 0.35).max(1.0);
+ [p.center[0] + r * d[0], p.center[1] + r * d[1]]
+}
+/// True throughout transform editing, including clicks outside a handle: never paint by accident.
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {
+ if app.ui.symmetry_transform.as_ref().is_some_and(|t| !valid(app, t)) {
+ app.ui.symmetry_transform = None;
+ }
+ if app.ui.symmetry_transform.is_none() {
+ return false;
+ }
+ let Some(xf) = ViewXform::active(app) else {
+ return true;
+ };
+ let size = app.session.active().map(|s| [f64::from(s.doc.size.width), f64::from(s.doc.size.height)]).unwrap_or([1.0, 1.0]);
+ let Some(t) = &mut app.ui.symmetry_transform else {
+ return false;
+ };
+ let tol = 8.0 / f64::from(xf.zoom.max(0.001));
+ let distance = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).hypot(a[1] - b[1]);
+ match ev {
+ ToolEvent::Down { x, y, .. } => {
+ let p = [x, y];
+ t.gesture = if distance(p, t.preview.center) <= tol {
+ Some(Gesture::Move { start: p, center: t.preview.center })
+ } else if distance(p, rotation_handle(t.preview, size)) <= tol {
+ Some(Gesture::Rotate { angle: (y - t.preview.center[1]).atan2(x - t.preview.center[0]), rotation: t.preview.rotation })
+ } else {
+ None
+ };
+ }
+ ToolEvent::Move { x, y, .. } => {
+ let (center, rotation) = match t.gesture {
+ Some(Gesture::Move { start, center }) => ([center[0] + x - start[0], center[1] + y - start[1]], t.preview.rotation),
+ Some(Gesture::Rotate { angle, rotation }) => {
+ let mut r = rotation + ((y - t.preview.center[1]).atan2(x - t.preview.center[0]) - angle).to_degrees();
+ if mods.shift {
+ r = (r / 15.0).round() * 15.0;
+ }
+ (t.preview.center, r)
+ }
+ None => return true,
+ };
+ if let Some(p) = PresetSymmetry::new(t.preview.mode, center, rotation) {
+ t.preview = p;
+ }
+ }
+ ToolEvent::Up { .. } => t.gesture = None,
+ }
+ true
+}
+pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
+ if !matches!(app.ui.tool, Tool::Brush | Tool::Pencil | Tool::Eraser) && app.ui.symmetry_transform.is_none() {
+ return;
+ }
+ let Some(st) = app.session.active() else {
+ return;
+ };
+ let edit = app.ui.symmetry_transform.as_ref().filter(|t| app.session.active_index() == Some(t.document));
+ let preview = edit.map(|t| t.preview).or_else(|| preset(app));
+ let Some(p) = preview else {
+ return;
+ };
+ let size = [f64::from(st.doc.size.width), f64::from(st.doc.size.height)];
+ let painter = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect));
+ let screen = |p: [f64; 2]| xf.to_screen(p[0] as f32, p[1] as f32);
+ let t = Tokens::get(painter.ctx());
+ for [a, b] in p.segments(size) {
+ painter.line_segment([screen(a), screen(b)], Stroke::new(1.0, t.accent));
+ }
+ if edit.is_some() {
+ let center = screen(p.center);
+ crate::vector_ui::draw_anchor(&painter, center, true, t.accent);
+ crate::vector_ui::draw_handle(&painter, center, screen(rotation_handle(p, size)), t.accent);
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/ui-egui/src/symmetry_ui/tests.rs b/crates/ui-egui/src/symmetry_ui/tests.rs
new file mode 100644
index 000000000..066ca3f88
--- /dev/null
+++ b/crates/ui-egui/src/symmetry_ui/tests.rs
@@ -0,0 +1,189 @@
+use super::*;
+use egui::{Context, Modifiers, Pos2, RawInput, Rect};
+use egui_kittest::{
+ Harness,
+ kittest::{NodeT, Queryable},
+};
+use photocraft_engine::Session;
+
+fn app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width":100,"height":80})).unwrap();
+ app.sync_views();
+ app.ui.tool = Tool::Brush;
+
+ app.ui.views[0].zoom = 1.0;
+ app.last_canvas_rect = Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0));
+ app
+}
+fn down(app: &mut PhotocraftApp, p: [f64; 2]) {
+ crate::canvas::tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, Modifiers::NONE);
+}
+fn move_to(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) {
+ crate::canvas::tool_event(app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, mods);
+}
+fn up(app: &mut PhotocraftApp, p: [f64; 2]) {
+ crate::canvas::tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, Modifiers::NONE);
+}
+fn key(app: &mut PhotocraftApp, key: Key) {
+ let ctx = Context::default();
+ let input = RawInput {
+ focused: true,
+ events: vec![egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }],
+ ..Default::default()
+ };
+ ctx.run_ui(input, |ui| track(app, ui.ctx())).textures_delta.clear();
+}
+#[test]
+fn transform_moves_rotates_snaps_and_commits_without_painting_or_history() {
+ let mut app = app();
+ app.run("paint.setSymmetry", json!({"mode":"dual"})).unwrap();
+ let before = app.session.active().unwrap().doc.clone();
+ let history = app.session.active().unwrap().history.past_len();
+ crate::menus::invoke(&mut app, &Context::default(), "ui.symmetryTransform", json!({})).unwrap();
+ down(&mut app, [50.0, 40.0]);
+ move_to(&mut app, [60.0, 45.0], Modifiers::NONE);
+ up(&mut app, [60.0, 45.0]);
+ let p = app.ui.symmetry_transform.as_ref().unwrap().preview;
+ assert_eq!(p.center, [60.0, 45.0]);
+ assert_eq!(preset(&app).unwrap().center, [50.0, 40.0]);
+ let handle = rotation_handle(p, [100.0, 80.0]);
+ down(&mut app, handle);
+ let angle = 112_f64.to_radians();
+ move_to(&mut app, [60.0 + 28.0 * angle.cos(), 45.0 + 28.0 * angle.sin()], Modifiers { shift: true, ..Modifiers::NONE });
+ up(&mut app, [0.0, 0.0]);
+ assert!((app.ui.symmetry_transform.as_ref().unwrap().preview.rotation - 15.0).abs() < 1e-8);
+ key(&mut app, Key::Enter);
+ assert!(app.ui.symmetry_transform.is_none());
+ assert_eq!(preset(&app).unwrap().center, [60.0, 45.0]);
+ assert_eq!(app.session.active().unwrap().doc, before);
+ assert_eq!(app.session.active().unwrap().history.past_len(), history);
+ assert_eq!(app.session.journal.last().unwrap().0, "paint.setSymmetry");
+}
+#[test]
+fn cancel_competing_edits_tool_document_and_focus_changes_drop_only_the_preview() {
+ let mut app = app();
+ app.run("paint.setSymmetry", json!({"mode":"vertical"})).unwrap();
+ begin(&mut app).unwrap();
+ down(&mut app, [50.0, 40.0]);
+ move_to(&mut app, [10.0, 20.0], Modifiers::NONE);
+ key(&mut app, Key::Escape);
+ assert_eq!(preset(&app).unwrap().center, [50.0, 40.0]);
+ assert!(app.ui.symmetry_transform.is_none());
+ begin(&mut app).unwrap();
+ app.run("document.inspect", json!({})).unwrap();
+ assert!(app.ui.symmetry_transform.is_some());
+ app.run("paint.setSymmetry", json!({"mode":"horizontal"})).unwrap();
+ assert!(app.ui.symmetry_transform.is_none());
+ for change in 0..4 {
+ begin(&mut app).unwrap();
+ match change {
+ 0 => app.ui.tool = Tool::Pencil,
+ 1 => {
+ app.session.execute("file.new", json!({"width":10,"height":10})).unwrap();
+ }
+ 2 => {
+ app.session.execute("layer.new.layer", json!({})).unwrap();
+ }
+ _ => {}
+ }
+ let ctx = Context::default();
+ ctx.run_ui(RawInput { focused: change != 3, ..Default::default() }, |ui| track(&mut app, ui.ctx())).textures_delta.clear();
+ assert!(app.ui.symmetry_transform.is_none());
+ if change == 1 {
+ assert!(app.session.set_active(0));
+ }
+ }
+ begin(&mut app).unwrap();
+ let ctx = Context::default();
+ let input = RawInput {
+ focused: true,
+ events: vec![egui::Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: true, repeat: false, modifiers: Modifiers::NONE }],
+ ..Default::default()
+ };
+ ctx.run_ui(input, |ui| {
+ crate::shortcuts::handle(&mut app, ui.ctx());
+ track(&mut app, ui.ctx());
+ })
+ .textures_delta
+ .clear();
+ assert_eq!(app.ui.tool, Tool::Move);
+ assert!(app.ui.symmetry_transform.is_none());
+}
+#[test]
+fn guides_never_consume_normal_paint_and_transform_background_clicks_never_paint() {
+ let mut app = app();
+ app.run("paint.setSymmetry", json!({"mode":"vertical"})).unwrap();
+ let before = app.session.active().unwrap().history.past_len();
+ down(&mut app, [20.0, 20.0]);
+ up(&mut app, [20.0, 20.0]);
+ assert_eq!(app.session.active().unwrap().history.past_len(), before + 1);
+ begin(&mut app).unwrap();
+ down(&mut app, [10.0, 10.0]);
+ move_to(&mut app, [30.0, 30.0], Modifiers::NONE);
+ up(&mut app, [30.0, 30.0]);
+ assert_eq!(app.session.active().unwrap().history.past_len(), before + 1);
+}
+#[test]
+fn menu_selects_all_modes_resets_positions_and_preserves_work_path_choice() {
+ let mut app = app();
+ app.session.edit_prefs(|p| p.interface.language = "en".into());
+ app.run("path.set", json!({"name":"work","path":{"subpaths":[{"knots":[[20,0],[20,80]]}]}})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(500.0, 450.0)).build_ui_state(
+ |ctx, app| {
+ crate::i18n::with_language(crate::i18n::Lang::EN, || menu(app, ctx));
+ },
+ app,
+ );
+ for mode in SymmetryMode::ALL {
+ h.get_by_label("Set painting symmetry options").click();
+ h.run_steps(3);
+ h.get_by_label(label(mode)).click();
+ h.run_steps(3);
+ assert_eq!(preset(h.state()).unwrap().mode, mode);
+ assert_eq!(preset(h.state()).unwrap().center, [50.0, 40.0]);
+ h.get_by_label("Set painting symmetry options").click();
+ h.run_steps(3);
+ assert_eq!(h.get_by_label(label(mode)).accesskit_node().toggled(), Some(egui::accesskit::Toggled::True));
+ h.get_by_label("Transform Symmetry").click();
+ h.run_steps(3);
+ assert!(h.state().ui.symmetry_transform.is_some());
+ h.state_mut().ui.symmetry_transform = None;
+ }
+ h.get_by_label("Set painting symmetry options").click();
+ h.run_steps(3);
+ h.get_by_label("Work Path").click();
+ h.run_steps(3);
+ assert_eq!(h.state().session.active().unwrap().symmetry.as_ref().unwrap().path_source(), Some("work"));
+ assert!(!can_transform(h.state()));
+ h.get_by_label("Set painting symmetry options").click();
+ h.run_steps(3);
+ h.get_by_label("Symmetry Off").click();
+ h.run_steps(3);
+ assert!(preset(h.state()).is_none());
+}
+#[test]
+fn overlays_follow_document_view_transforms_in_every_theme() {
+ for theme in crate::theme::ThemeKind::ALL {
+ let mut app = app();
+ app.run("paint.setSymmetry", json!({"mode":"dual"})).unwrap();
+ let ctx = Context::default();
+ crate::theme::apply(&ctx, theme);
+ let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(500.0, 400.0)), zoom: 1.7, center: [50.0, 40.0], rotation: 37.0, flip: true };
+ let mut out = ctx.run_ui(RawInput { screen_rect: Some(xf.rect), ..Default::default() }, |ui| {
+ let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("symmetry")));
+ draw(&app, &painter, &xf);
+ });
+ let lines: Vec<_> =
+ out.shapes.iter().filter_map(|s| if let egui::Shape::LineSegment { points, .. } = &s.shape { Some(*points) } else { None }).collect();
+ assert_eq!(lines.len(), 2);
+ let c = xf.to_screen(50.0, 40.0);
+ for [a, b] in lines {
+ assert!((egui::pos2((a.x + b.x) / 2.0, (a.y + b.y) / 2.0) - c).length() < 0.01);
+ }
+ out.textures_delta.clear();
+ }
+ let de = crate::i18n::Lang::from_code("de").unwrap();
+ assert_eq!(crate::i18n::tr(de, "Dual Axis"), "Duale Achse");
+ assert_eq!(crate::i18n::tr(de, "Transform Symmetry"), "Symmetrie transformieren");
+}