Skip to content

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

Add the Magnetic Lasso tool (#864)

Bart Louwers0f16bce0c535
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 04d8434ef..ebc77ddba 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -16,10 +16,11 @@ next to them.
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese 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`, `eraser-background.svg` and `eraser-magic.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`, `eraser-background.svg`, `eraser-magic.svg` and `lasso-magnetic.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,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/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/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 |
| `assets/app-icon/` (all files) | PhotoCraft app icon (nine-tailed kitsune) | The project owner (drawn in ArtCraft, vectorised) | Original work, see [`assets/app-icon/README.md`](assets/app-icon/README.md) | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) |
diff --git a/README.md b/README.md
index 70fcb1417..f40345f6f 100644
--- a/README.md
+++ b/README.md
@@ -178,7 +178,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
<tr>
<td width="33%" valign="top">
<h4>🧰 34 tools</h4>
- Move · Rectangular and Elliptical Marquee · Lasso · Polygonal Lasso · Magic Wand · Quick Selection · Object Selection · Crop · Eyedropper · Brush · Pencil · Mixer Brush · Color Replacement · Eraser · Clone Stamp · Healing Brush · Spot Healing · History Brush · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Path Selection · Type · five Shape tools · Hand · Zoom
+ Move · Rectangular and Elliptical Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Magic Wand · Quick Selection · Object Selection · Crop · Eyedropper · Brush · Pencil · Mixer Brush · Color Replacement · Eraser · Clone Stamp · Healing Brush · Spot Healing · History Brush · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Path Selection · Type · five Shape tools · Hand · Zoom
</td>
<td width="33%" valign="top">
<h4>🖌️ A real brush engine</h4>
diff --git a/assets/icons/LICENSE-noun-magnetic-lasso.txt b/assets/icons/LICENSE-noun-magnetic-lasso.txt
new file mode 100644
index 000000000..7fcb546dd
--- /dev/null
+++ b/assets/icons/LICENSE-noun-magnetic-lasso.txt
@@ -0,0 +1,334 @@
+assets/icons/lasso-magnetic.svg
+
+Adapted from "Magnetic Lasso Tool" by Lil' Seal (failureiscool) from Noun Project,
+https://thenounproject.com/icon/magnetic-lasso-tool-177513/
+licensed under Creative Commons Attribution 3.0 Unported (CC BY 3.0),
+https://creativecommons.org/licenses/by/3.0/
+
+Changes by PhotoCraft contributors: redrawn as a 24 x 24 SVG on PhotoCraft's toolbar grid, with
+round-capped strokes in place of the original line weights, so it can be tinted and rasterized
+like the other toolbar icons.
+
+The full text of the licence follows.
+
+--------------------------------------------------------------------------------
+
+Creative Commons Legal Code
+
+Attribution 3.0 Unported
+
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
+ LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
+ REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR
+ DAMAGES RESULTING FROM ITS USE.
+
+License
+
+THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
+COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
+COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
+AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
+
+BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
+TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
+BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
+CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
+CONDITIONS.
+
+1. Definitions
+
+ a. "Adaptation" means a work based upon the Work, or upon the Work and
+ other pre-existing works, such as a translation, adaptation,
+ derivative work, arrangement of music or other alterations of a
+ literary or artistic work, or phonogram or performance and includes
+ cinematographic adaptations or any other form in which the Work may be
+ recast, transformed, or adapted including in any form recognizably
+ derived from the original, except that a work that constitutes a
+ Collection will not be considered an Adaptation for the purpose of
+ this License. For the avoidance of doubt, where the Work is a musical
+ work, performance or phonogram, the synchronization of the Work in
+ timed-relation with a moving image ("synching") will be considered an
+ Adaptation for the purpose of this License.
+ b. "Collection" means a collection of literary or artistic works, such as
+ encyclopedias and anthologies, or performances, phonograms or
+ broadcasts, or other works or subject matter other than works listed
+ in Section 1(f) below, which, by reason of the selection and
+ arrangement of their contents, constitute intellectual creations, in
+ which the Work is included in its entirety in unmodified form along
+ with one or more other contributions, each constituting separate and
+ independent works in themselves, which together are assembled into a
+ collective whole. A work that constitutes a Collection will not be
+ considered an Adaptation (as defined above) for the purposes of this
+ License.
+ c. "Distribute" means to make available to the public the original and
+ copies of the Work or Adaptation, as appropriate, through sale or
+ other transfer of ownership.
+ d. "Licensor" means the individual, individuals, entity or entities that
+ offer(s) the Work under the terms of this License.
+ e. "Original Author" means, in the case of a literary or artistic work,
+ the individual, individuals, entity or entities who created the Work
+ or if no individual or entity can be identified, the publisher; and in
+ addition (i) in the case of a performance the actors, singers,
+ musicians, dancers, and other persons who act, sing, deliver, declaim,
+ play in, interpret or otherwise perform literary or artistic works or
+ expressions of folklore; (ii) in the case of a phonogram the producer
+ being the person or legal entity who first fixes the sounds of a
+ performance or other sounds; and, (iii) in the case of broadcasts, the
+ organization that transmits the broadcast.
+ f. "Work" means the literary and/or artistic work offered under the terms
+ of this License including without limitation any production in the
+ literary, scientific and artistic domain, whatever may be the mode or
+ form of its expression including digital form, such as a book,
+ pamphlet and other writing; a lecture, address, sermon or other work
+ of the same nature; a dramatic or dramatico-musical work; a
+ choreographic work or entertainment in dumb show; a musical
+ composition with or without words; a cinematographic work to which are
+ assimilated works expressed by a process analogous to cinematography;
+ a work of drawing, painting, architecture, sculpture, engraving or
+ lithography; a photographic work to which are assimilated works
+ expressed by a process analogous to photography; a work of applied
+ art; an illustration, map, plan, sketch or three-dimensional work
+ relative to geography, topography, architecture or science; a
+ performance; a broadcast; a phonogram; a compilation of data to the
+ extent it is protected as a copyrightable work; or a work performed by
+ a variety or circus performer to the extent it is not otherwise
+ considered a literary or artistic work.
+ g. "You" means an individual or entity exercising rights under this
+ License who has not previously violated the terms of this License with
+ respect to the Work, or who has received express permission from the
+ Licensor to exercise rights under this License despite a previous
+ violation.
+ h. "Publicly Perform" means to perform public recitations of the Work and
+ to communicate to the public those public recitations, by any means or
+ process, including by wire or wireless means or public digital
+ performances; to make available to the public Works in such a way that
+ members of the public may access these Works from a place and at a
+ place individually chosen by them; to perform the Work to the public
+ by any means or process and the communication to the public of the
+ performances of the Work, including by public digital performance; to
+ broadcast and rebroadcast the Work by any means including signs,
+ sounds or images.
+ i. "Reproduce" means to make copies of the Work by any means including
+ without limitation by sound or visual recordings and the right of
+ fixation and reproducing fixations of the Work, including storage of a
+ protected performance or phonogram in digital form or other electronic
+ medium.
+
+2. Fair Dealing Rights. Nothing in this License is intended to reduce,
+limit, or restrict any uses free from copyright or rights arising from
+limitations or exceptions that are provided for in connection with the
+copyright protection under copyright law or other applicable laws.
+
+3. License Grant. Subject to the terms and conditions of this License,
+Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
+perpetual (for the duration of the applicable copyright) license to
+exercise the rights in the Work as stated below:
+
+ a. to Reproduce the Work, to incorporate the Work into one or more
+ Collections, and to Reproduce the Work as incorporated in the
+ Collections;
+ b. to create and Reproduce Adaptations provided that any such Adaptation,
+ including any translation in any medium, takes reasonable steps to
+ clearly label, demarcate or otherwise identify that changes were made
+ to the original Work. For example, a translation could be marked "The
+ original work was translated from English to Spanish," or a
+ modification could indicate "The original work has been modified.";
+ c. to Distribute and Publicly Perform the Work including as incorporated
+ in Collections; and,
+ d. to Distribute and Publicly Perform Adaptations.
+ e. For the avoidance of doubt:
+
+ i. Non-waivable Compulsory License Schemes. In those jurisdictions in
+ which the right to collect royalties through any statutory or
+ compulsory licensing scheme cannot be waived, the Licensor
+ reserves the exclusive right to collect such royalties for any
+ exercise by You of the rights granted under this License;
+ ii. Waivable Compulsory License Schemes. In those jurisdictions in
+ which the right to collect royalties through any statutory or
+ compulsory licensing scheme can be waived, the Licensor waives the
+ exclusive right to collect such royalties for any exercise by You
+ of the rights granted under this License; and,
+ iii. Voluntary License Schemes. The Licensor waives the right to
+ collect royalties, whether individually or, in the event that the
+ Licensor is a member of a collecting society that administers
+ voluntary licensing schemes, via that society, from any exercise
+ by You of the rights granted under this License.
+
+The above rights may be exercised in all media and formats whether now
+known or hereafter devised. The above rights include the right to make
+such modifications as are technically necessary to exercise the rights in
+other media and formats. Subject to Section 8(f), all rights not expressly
+granted by Licensor are hereby reserved.
+
+4. Restrictions. The license granted in Section 3 above is expressly made
+subject to and limited by the following restrictions:
+
+ a. You may Distribute or Publicly Perform the Work only under the terms
+ of this License. You must include a copy of, or the Uniform Resource
+ Identifier (URI) for, this License with every copy of the Work You
+ Distribute or Publicly Perform. You may not offer or impose any terms
+ on the Work that restrict the terms of this License or the ability of
+ the recipient of the Work to exercise the rights granted to that
+ recipient under the terms of the License. You may not sublicense the
+ Work. You must keep intact all notices that refer to this License and
+ to the disclaimer of warranties with every copy of the Work You
+ Distribute or Publicly Perform. When You Distribute or Publicly
+ Perform the Work, You may not impose any effective technological
+ measures on the Work that restrict the ability of a recipient of the
+ Work from You to exercise the rights granted to that recipient under
+ the terms of the License. This Section 4(a) applies to the Work as
+ incorporated in a Collection, but this does not require the Collection
+ apart from the Work itself to be made subject to the terms of this
+ License. If You create a Collection, upon notice from any Licensor You
+ must, to the extent practicable, remove from the Collection any credit
+ as required by Section 4(b), as requested. If You create an
+ Adaptation, upon notice from any Licensor You must, to the extent
+ practicable, remove from the Adaptation any credit as required by
+ Section 4(b), as requested.
+ b. If You Distribute, or Publicly Perform the Work or any Adaptations or
+ Collections, You must, unless a request has been made pursuant to
+ Section 4(a), keep intact all copyright notices for the Work and
+ provide, reasonable to the medium or means You are utilizing: (i) the
+ name of the Original Author (or pseudonym, if applicable) if supplied,
+ and/or if the Original Author and/or Licensor designate another party
+ or parties (e.g., a sponsor institute, publishing entity, journal) for
+ attribution ("Attribution Parties") in Licensor's copyright notice,
+ terms of service or by other reasonable means, the name of such party
+ or parties; (ii) the title of the Work if supplied; (iii) to the
+ extent reasonably practicable, the URI, if any, that Licensor
+ specifies to be associated with the Work, unless such URI does not
+ refer to the copyright notice or licensing information for the Work;
+ and (iv) , consistent with Section 3(b), in the case of an Adaptation,
+ a credit identifying the use of the Work in the Adaptation (e.g.,
+ "French translation of the Work by Original Author," or "Screenplay
+ based on original Work by Original Author"). The credit required by
+ this Section 4 (b) may be implemented in any reasonable manner;
+ provided, however, that in the case of a Adaptation or Collection, at
+ a minimum such credit will appear, if a credit for all contributing
+ authors of the Adaptation or Collection appears, then as part of these
+ credits and in a manner at least as prominent as the credits for the
+ other contributing authors. For the avoidance of doubt, You may only
+ use the credit required by this Section for the purpose of attribution
+ in the manner set out above and, by exercising Your rights under this
+ License, You may not implicitly or explicitly assert or imply any
+ connection with, sponsorship or endorsement by the Original Author,
+ Licensor and/or Attribution Parties, as appropriate, of You or Your
+ use of the Work, without the separate, express prior written
+ permission of the Original Author, Licensor and/or Attribution
+ Parties.
+ c. Except as otherwise agreed in writing by the Licensor or as may be
+ otherwise permitted by applicable law, if You Reproduce, Distribute or
+ Publicly Perform the Work either by itself or as part of any
+ Adaptations or Collections, You must not distort, mutilate, modify or
+ take other derogatory action in relation to the Work which would be
+ prejudicial to the Original Author's honor or reputation. Licensor
+ agrees that in those jurisdictions (e.g. Japan), in which any exercise
+ of the right granted in Section 3(b) of this License (the right to
+ make Adaptations) would be deemed to be a distortion, mutilation,
+ modification or other derogatory action prejudicial to the Original
+ Author's honor and reputation, the Licensor will waive or not assert,
+ as appropriate, this Section, to the fullest extent permitted by the
+ applicable national law, to enable You to reasonably exercise Your
+ right under Section 3(b) of this License (right to make Adaptations)
+ but not otherwise.
+
+5. Representations, Warranties and Disclaimer
+
+UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
+OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
+KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
+INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
+FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
+LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
+WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION
+OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
+
+6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE
+LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR
+ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
+ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS
+BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+7. Termination
+
+ a. This License and the rights granted hereunder will terminate
+ automatically upon any breach by You of the terms of this License.
+ Individuals or entities who have received Adaptations or Collections
+ from You under this License, however, will not have their licenses
+ terminated provided such individuals or entities remain in full
+ compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
+ survive any termination of this License.
+ b. Subject to the above terms and conditions, the license granted here is
+ perpetual (for the duration of the applicable copyright in the Work).
+ Notwithstanding the above, Licensor reserves the right to release the
+ Work under different license terms or to stop distributing the Work at
+ any time; provided, however that any such election will not serve to
+ withdraw this License (or any other license that has been, or is
+ required to be, granted under the terms of this License), and this
+ License will continue in full force and effect unless terminated as
+ stated above.
+
+8. Miscellaneous
+
+ a. Each time You Distribute or Publicly Perform the Work or a Collection,
+ the Licensor offers to the recipient a license to the Work on the same
+ terms and conditions as the license granted to You under this License.
+ b. Each time You Distribute or Publicly Perform an Adaptation, Licensor
+ offers to the recipient a license to the original Work on the same
+ terms and conditions as the license granted to You under this License.
+ c. If any provision of this License is invalid or unenforceable under
+ applicable law, it shall not affect the validity or enforceability of
+ the remainder of the terms of this License, and without further action
+ by the parties to this agreement, such provision shall be reformed to
+ the minimum extent necessary to make such provision valid and
+ enforceable.
+ d. No term or provision of this License shall be deemed waived and no
+ breach consented to unless such waiver or consent shall be in writing
+ and signed by the party to be charged with such waiver or consent.
+ e. This License constitutes the entire agreement between the parties with
+ respect to the Work licensed here. There are no understandings,
+ agreements or representations with respect to the Work not specified
+ here. Licensor shall not be bound by any additional provisions that
+ may appear in any communication from You. This License may not be
+ modified without the mutual written agreement of the Licensor and You.
+ f. The rights granted under, and the subject matter referenced, in this
+ License were drafted utilizing the terminology of the Berne Convention
+ for the Protection of Literary and Artistic Works (as amended on
+ September 28, 1979), the Rome Convention of 1961, the WIPO Copyright
+ Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996
+ and the Universal Copyright Convention (as revised on July 24, 1971).
+ These rights and subject matter take effect in the relevant
+ jurisdiction in which the License terms are sought to be enforced
+ according to the corresponding provisions of the implementation of
+ those treaty provisions in the applicable national law. If the
+ standard suite of rights granted under applicable copyright law
+ includes additional rights not granted under this License, such
+ additional rights are deemed to be included in the License; this
+ License is not intended to restrict the license of any rights under
+ applicable law.
+
+
+Creative Commons Notice
+
+ Creative Commons is not a party to this License, and makes no warranty
+ whatsoever in connection with the Work. Creative Commons will not be
+ liable to You or any party on any legal theory for any damages
+ whatsoever, including without limitation any general, special,
+ incidental or consequential damages arising in connection to this
+ license. Notwithstanding the foregoing two (2) sentences, if Creative
+ Commons has expressly identified itself as the Licensor hereunder, it
+ shall have all rights and obligations of Licensor.
+
+ Except for the limited purpose of indicating to the public that the
+ Work is licensed under the CCPL, Creative Commons does not authorize
+ the use by either party of the trademark "Creative Commons" or any
+ related trademark or logo of Creative Commons without the prior
+ written consent of Creative Commons. Any permitted use will be in
+ compliance with Creative Commons' then-current trademark usage
+ guidelines, as may be published on its website or otherwise made
+ available upon request from time to time. For the avoidance of doubt,
+ this trademark restriction does not form part of this License.
+
+ Creative Commons may be contacted at https://creativecommons.org/.
diff --git a/assets/icons/lasso-magnetic.svg b/assets/icons/lasso-magnetic.svg
new file mode 100644
index 000000000..eeccdf104
--- /dev/null
+++ b/assets/icons/lasso-magnetic.svg
@@ -0,0 +1,17 @@
+<!-- Adapted from "Magnetic Lasso Tool" by Lil' Seal from Noun Project (CC BY 3.0): see LICENSE-noun-magnetic-lasso.txt -->
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.5"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M9 1.9H16.4A4.6 4.6 0 0 1 21 6.5V7.7A4.6 4.6 0 0 1 16.4 12.3H9V8.95H16.55A0.6 0.6 0 0 0 17.15 8.35V5.85A0.6 0.6 0 0 0 16.55 5.25H9ZM9.75 2.65H12.5V4.5H9.75ZM9.75 9.7H12.5V11.55H9.75Z" fill="currentColor" fill-rule="evenodd" stroke="none" />
+ <path d="M12.4 7.5 1.8 3.6l7.7 15.3-1.8 2.8" />
+ <ellipse cx="9.25" cy="16.65" rx="2.85" ry="2.2" />
+ <path d="m12.1 16.2 10.1-3-1.6-1" />
+</svg>
diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs
index 06b46faa6..64337c97a 100644
--- a/crates/algo/src/lib.rs
+++ b/crates/algo/src/lib.rs
@@ -38,6 +38,7 @@ mod image;
pub mod inpaint;
pub mod lens;
pub mod liquify;
+pub mod magnetic;
pub mod matting;
mod noise;
mod oil;
diff --git a/crates/algo/src/magnetic.rs b/crates/algo/src/magnetic.rs
new file mode 100644
index 000000000..f2dab0881
--- /dev/null
+++ b/crates/algo/src/magnetic.rs
@@ -0,0 +1,602 @@
+//! Magnetic Lasso edge tracing: a selection border that snaps to the strongest edges near the
+//! pointer.
+//!
+//! Between two fastening points the border is the cheapest 8-connected pixel path, where pixels on
+//! a strong, well-localised edge are cheap and the rest are expensive: the "live wire" of
+//! Mortensen & Barrett, *Intelligent Scissors for Image Composition* (SIGGRAPH 1995). A link costs
+//! a weighted sum of an edge-strength term, an edge-centre term (non-maximum suppression across the
+//! edge, in place of the paper's Laplacian zero crossings) and a gradient-direction term that keeps
+//! the border running along the edge. The search stays in a corridor, the pixels within the
+//! detection width of the pointer's path, and a small pull towards that path keeps the border on
+//! the pointer where there is no edge, so it never jumps to an edge the pointer did not go near.
+//! Points on an edge are placed at its sub-pixel centre, so the border lands on the edge rather than
+//! half a pixel beside it.
+//!
+//! Pixels are read lazily in blocks through a caller-supplied fetch (a layer's pixels or the
+//! composite), so tracing on a 36 MP image reads only the area around the border.
+
+use std::cmp::Reverse;
+use std::collections::{BinaryHeap, HashMap};
+use std::f32::consts::{PI, SQRT_2};
+
+use photocraft_geom::Rect;
+
+/// Side of the cached pixel blocks (px).
+const BLOCK: i32 = 128;
+/// Blocks kept before the cache starts over (128² RGBA8 is 64 KiB, so at most 64 MiB).
+const MAX_BLOCKS: usize = 1024;
+/// Longest stretch of the pointer's path searched at once (px). Longer paths are traced in pieces
+/// that meet on an edge, which bounds every search to a small area.
+const PIECE: f64 = 256.0;
+/// Longest pointer path [`Tracer::trace`] follows (px); a longer one is returned as is.
+pub const MAX_GUIDE_LENGTH: f64 = 262_144.0;
+/// Detection width limits (px), as in Photoshop's options bar.
+pub const WIDTH_RANGE: (f64, f64) = (1.0, 256.0);
+
+// Link cost weights: Mortensen & Barrett's 0.43 (edge centre) / 0.43 (strength) / 0.14
+// (direction), a cost per pixel of length so the border never wanders along an edge for free, and
+// the pull towards the pointer's path.
+const W_CENTRE: f32 = 0.43;
+const W_STRENGTH: f32 = 0.43;
+const W_DIRECTION: f32 = 0.14;
+const W_LENGTH: f32 = 0.02;
+const W_GUIDE: f32 = 0.4;
+/// The direction term where either pixel has no edge direction (the mean of the term).
+const NEUTRAL_DIRECTION: f32 = 2.0 / 3.0;
+
+/// The 8 neighbours, in the order `Search::from` records them.
+const DIRS: [(i32, i32); 8] = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)];
+
+/// Detection settings: the Magnetic Lasso options bar.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Settings {
+ /// Detection width (px): the border follows only edges this close to the pointer's path.
+ pub width: f64,
+ /// Contrast (0..1): steps weaker than this, in every channel, are not edges.
+ pub contrast: f32,
+}
+
+impl Default for Settings {
+ fn default() -> Self {
+ Settings { width: 10.0, contrast: 0.1 }
+ }
+}
+
+impl Settings {
+ /// Settings clamped to their ranges (width 1..256 px, contrast 1..100 %); NaN takes the default.
+ pub fn new(width: f64, contrast: f32) -> Self {
+ let d = Settings::default();
+ let width = if width.is_finite() { width.clamp(WIDTH_RANGE.0, WIDTH_RANGE.1) } else { d.width };
+ let contrast = if contrast.is_finite() { contrast.clamp(0.01, 1.0) } else { d.contrast };
+ Settings { width, contrast }
+ }
+
+ /// The corridor's radius: the detection width plus room for an 8-connected path.
+ fn radius(&self) -> f64 {
+ self.width + 1.5
+ }
+}
+
+/// Reads straight-alpha RGBA8 pixels of a rectangle inside the image, row-major. A result of the
+/// wrong length reads as transparent.
+pub type Fetch<'a> = dyn FnMut(Rect) -> Vec<[u8; 4]> + 'a;
+
+/// Edge tracing over one image, caching the pixels it has read.
+#[derive(Debug)]
+pub struct Tracer {
+ bounds: Rect,
+ blocks: HashMap<(i32, i32), Vec<[u8; 4]>>,
+}
+
+impl Tracer {
+ /// A tracer for an image covering `bounds` (document pixels).
+ pub fn new(bounds: Rect) -> Self {
+ Tracer { bounds, blocks: HashMap::new() }
+ }
+
+ pub fn bounds(&self) -> Rect {
+ self.bounds
+ }
+
+ /// Pixels read so far (for tests and diagnostics).
+ pub fn cached_pixels(&self) -> usize {
+ self.blocks.values().map(Vec::len).sum()
+ }
+
+ /// Where a fastening point near `p` goes: the centre of the most prominent edge within the
+ /// detection width, or `p` itself (kept inside the image) when no edge there reaches the
+ /// contrast. `None` when `p` is not a finite point or the image is empty.
+ pub fn snap(&mut self, fetch: &mut Fetch, p: [f64; 2], s: Settings) -> Option<[f64; 2]> {
+ let s = Settings::new(s.width, s.contrast);
+ let p = self.clamp_point(p)?;
+ let r = s.width;
+ let (px, py) = self.pixel(p);
+ let ri = r.ceil() as i32 + 1;
+ let area = Rect::new(px.saturating_sub(ri), py.saturating_sub(ri), px.saturating_add(ri + 1), py.saturating_add(ri + 1)).intersect(&self.bounds);
+ let f = self.field(fetch, area);
+ let mut best: Option<(f32, [f64; 2])> = None;
+ for y in area.y0..area.y1 {
+ for x in area.x0..area.x1 {
+ let Some(i) = f.index(x, y) else { continue };
+ let strength = f.strength.get(i).copied().unwrap_or(0.0);
+ if strength < s.contrast || !f.ridge.get(i).copied().unwrap_or(false) {
+ continue;
+ }
+ let d = dist([x as f64 + 0.5, y as f64 + 0.5], p);
+ if d > r {
+ continue;
+ }
+ // The strongest edge, a little in favour of the nearer one.
+ let score = strength * (1.0 - 0.25 * (d / r) as f32);
+ if best.is_none_or(|(b, _)| score > b) {
+ best = Some((score, f.point(i, x, y, s.contrast)));
+ }
+ }
+ }
+ Some(best.map_or(p, |(_, q)| q))
+ }
+
+ /// The border from `from` to `to` along the edges near `guide`, the pointer's path between
+ /// them (`from` and `to` are its ends whatever it holds). It starts at `from` and ends at `to`
+ /// exactly (both kept inside the image). Empty when either is not a finite point or the image
+ /// is empty.
+ pub fn trace(&mut self, fetch: &mut Fetch, from: [f64; 2], to: [f64; 2], guide: &[[f64; 2]], s: Settings) -> Vec<[f64; 2]> {
+ let s = Settings::new(s.width, s.contrast);
+ let (Some(from), Some(to)) = (self.clamp_point(from), self.clamp_point(to)) else { return Vec::new() };
+ let mut g = Vec::with_capacity(guide.len().saturating_add(2));
+ g.push(from);
+ g.extend(guide.iter().filter_map(|q| self.clamp_point(*q)));
+ g.push(to);
+ // A coarse guide is enough for the corridor, and much cheaper to draw.
+ let g = simplify(&g, 0.5);
+ if length(&g) > MAX_GUIDE_LENGTH {
+ return g;
+ }
+ let pieces = split(&g, PIECE);
+ let mut out = vec![from];
+ let mut cur = from;
+ let last = pieces.len().saturating_sub(1);
+ for (k, piece) in pieces.iter().enumerate() {
+ let target = if k == last { to } else { piece.last().and_then(|q| self.snap(fetch, *q, s)).unwrap_or(to) };
+ out.extend(self.trace_piece(fetch, cur, target, piece, s).into_iter().skip(1));
+ cur = target;
+ }
+ // Within half a pixel: drops the staircase of pixel steps, keeps the curve of an edge.
+ simplify(&out, 0.5)
+ }
+
+ /// One piece of [`Tracer::trace`]: the cheapest path from `a` to `b` in the corridor around
+ /// `guide`, from `a` to `b` inclusive.
+ fn trace_piece(&mut self, fetch: &mut Fetch, a: [f64; 2], b: [f64; 2], guide: &[[f64; 2]], s: Settings) -> Vec<[f64; 2]> {
+ let rad = s.radius();
+ let (ax, ay) = self.pixel(a);
+ let (bx, by) = self.pixel(b);
+ let mut bbox = Rect::new(ax.min(bx), ay.min(by), ax.max(bx) + 1, ay.max(by) + 1);
+ for q in guide {
+ let (x, y) = self.pixel(*q);
+ bbox = bbox.union(&Rect::new(x, y, x + 1, y + 1));
+ }
+ let area = bbox.inflate(rad.ceil() as i32 + 1).intersect(&self.bounds);
+ let f = self.field(fetch, area);
+ let mut near = corridor(area, guide, rad);
+ let (Some(start), Some(goal)) = (f.index(ax, ay), f.index(bx, by)) else { return vec![a, b] };
+ for i in [start, goal] {
+ if let Some(v) = near.get_mut(i) {
+ *v = 0.0;
+ }
+ }
+ let Some(cells) = search(&f, &near, (rad * rad) as f32, start, goal, s.contrast) else { return vec![a, b] };
+ let mut pts: Vec<[f64; 2]> = cells.iter().map(|&i| f.point_at(i, s.contrast)).collect();
+ match pts.len() {
+ 0 | 1 => vec![a, b],
+ n => {
+ pts[0] = a;
+ pts[n - 1] = b;
+ pts
+ }
+ }
+ }
+
+ /// `p` kept inside the image, or `None` if it is not a finite point or the image is empty.
+ fn clamp_point(&self, p: [f64; 2]) -> Option<[f64; 2]> {
+ let b = self.bounds;
+ if b.is_empty() || !p[0].is_finite() || !p[1].is_finite() {
+ return None;
+ }
+ Some([p[0].clamp(b.x0 as f64, b.x1 as f64), p[1].clamp(b.y0 as f64, b.y1 as f64)])
+ }
+
+ /// The pixel under a point (clamped to the image).
+ fn pixel(&self, p: [f64; 2]) -> (i32, i32) {
+ let b = self.bounds;
+ let c = |v: f64, lo: i32, hi: i32| if v.is_finite() { (v.floor() as i32).clamp(lo, (hi - 1).max(lo)) } else { lo };
+ (c(p[0], b.x0, b.x1), c(p[1], b.y0, b.y1))
+ }
+
+ /// Edge features over `area` (inside the image).
+ fn field(&mut self, fetch: &mut Fetch, area: Rect) -> Field {
+ // Sobel reads one ring beyond the gradient, and non-maximum suppression one beyond the area.
+ let ext = area.inflate(2).intersect(&self.bounds);
+ let px = self.pixels(fetch, ext);
+ Field::new(area, ext, &px)
+ }
+
+ /// Straight RGBA8 pixels of `r` (inside the image), through the block cache.
+ fn pixels(&mut self, fetch: &mut Fetch, r: Rect) -> Vec<[u8; 4]> {
+ let w = r.width() as usize;
+ let mut out = vec![[0u8; 4]; w * r.height() as usize];
+ if r.is_empty() {
+ return out;
+ }
+ if self.blocks.len() > MAX_BLOCKS {
+ self.blocks.clear();
+ }
+ let (bx0, by0) = (r.x0.div_euclid(BLOCK), r.y0.div_euclid(BLOCK));
+ let (bx1, by1) = ((r.x1 - 1).div_euclid(BLOCK), (r.y1 - 1).div_euclid(BLOCK));
+ for by in by0..=by1 {
+ for bx in bx0..=bx1 {
+ let br = Rect::new(
+ bx.saturating_mul(BLOCK),
+ by.saturating_mul(BLOCK),
+ bx.saturating_add(1).saturating_mul(BLOCK),
+ by.saturating_add(1).saturating_mul(BLOCK),
+ )
+ .intersect(&self.bounds);
+ if br.is_empty() {
+ continue;
+ }
+ let n = br.width() as usize * br.height() as usize;
+ let block = self.blocks.entry((bx, by)).or_insert_with(|| {
+ let v = fetch(br);
+ if v.len() == n { v } else { vec![[0; 4]; n] }
+ });
+ let ov = br.intersect(&r);
+ let len = ov.width() as usize;
+ for y in ov.y0..ov.y1 {
+ let src = (y - br.y0) as usize * br.width() as usize + (ov.x0 - br.x0) as usize;
+ let dst = (y - r.y0) as usize * w + (ov.x0 - r.x0) as usize;
+ if let (Some(s), Some(d)) = (block.get(src..src + len), out.get_mut(dst..dst + len)) {
+ d.copy_from_slice(s);
+ }
+ }
+ }
+ }
+ out
+ }
+}
+
+/// Edge features of the pixels in an area.
+struct Field {
+ area: Rect,
+ w: usize,
+ /// Edge strength: the steepest channel's Sobel gradient, scaled so a sharp step of height `h`
+ /// reads `h` (capped at 1).
+ strength: Vec<f32>,
+ /// Unit gradient of that channel (zero on flat pixels).
+ grad: Vec<[f32; 2]>,
+ /// The pixel is the strongest across its edge (non-maximum suppression).
+ ridge: Vec<bool>,
+ /// From the pixel centre to the edge's sub-pixel centre, along the gradient.
+ offset: Vec<[f32; 2]>,
+}
+
+impl Field {
+ /// Features over `area` from the straight RGBA8 pixels `px` of `ext` (the area plus up to two
+ /// pixels around it, inside the image; beyond it the edge pixels repeat).
+ fn new(area: Rect, ext: Rect, px: &[[u8; 4]]) -> Field {
+ let (ew, eh) = (ext.width() as i32, ext.height() as i32);
+ // Premultiplied channels: an opaque shape on transparency has an edge, transparent
+ // pixels of different colours do not.
+ let ch: Vec<[f32; 4]> = px
+ .iter()
+ .map(|p| {
+ let a = f32::from(p[3]) / 255.0;
+ [f32::from(p[0]) / 255.0 * a, f32::from(p[1]) / 255.0 * a, f32::from(p[2]) / 255.0 * a, a]
+ })
+ .collect();
+ let at = |x: i32, y: i32| -> [f32; 4] {
+ let (x, y) = ((x - ext.x0).clamp(0, (ew - 1).max(0)), (y - ext.y0).clamp(0, (eh - 1).max(0)));
+ ch.get(y as usize * ew.max(0) as usize + x as usize).copied().unwrap_or_default()
+ };
+ // Gradients over the area plus one ring (non-maximum suppression looks across it).
+ let g1 = area.inflate(1).intersect(&ext);
+ let gw = g1.width() as usize;
+ let mut st = vec![0.0f32; gw * g1.height() as usize];
+ let mut gd = vec![[0.0f32; 2]; st.len()];
+ for y in g1.y0..g1.y1 {
+ for x in g1.x0..g1.x1 {
+ let (nw, n, ne) = (at(x - 1, y - 1), at(x, y - 1), at(x + 1, y - 1));
+ let (w, e) = (at(x - 1, y), at(x + 1, y));
+ let (sw, s, se) = (at(x - 1, y + 1), at(x, y + 1), at(x + 1, y + 1));
+ let mut best = (0.0f32, [0.0f32; 2]);
+ for c in 0..4 {
+ let gx = (ne[c] + 2.0 * e[c] + se[c]) - (nw[c] + 2.0 * w[c] + sw[c]);
+ let gy = (sw[c] + 2.0 * s[c] + se[c]) - (nw[c] + 2.0 * n[c] + ne[c]);
+ let m2 = gx * gx + gy * gy;
+ if m2 > best.0 {
+ best = (m2, [gx, gy]);
+ }
+ }
+ let mag = best.0.sqrt();
+ let i = (y - g1.y0) as usize * gw + (x - g1.x0) as usize;
+ if let (Some(sv), Some(gv)) = (st.get_mut(i), gd.get_mut(i)) {
+ *sv = (mag / 4.0).min(1.0);
+ *gv = if mag > 1e-6 { [best.1[0] / mag, best.1[1] / mag] } else { [0.0; 2] };
+ }
+ }
+ }
+ let s_at =
+ |x: i32, y: i32| -> f32 { if g1.contains(x, y) { st.get((y - g1.y0) as usize * gw + (x - g1.x0) as usize).copied().unwrap_or(0.0) } else { 0.0 } };
+ let w = area.width() as usize;
+ let n = w * area.height() as usize;
+ let mut f = Field { area, w, strength: vec![0.0; n], grad: vec![[0.0; 2]; n], ridge: vec![false; n], offset: vec![[0.0; 2]; n] };
+ for y in area.y0..area.y1 {
+ for x in area.x0..area.x1 {
+ let s0 = s_at(x, y);
+ let g = if g1.contains(x, y) { gd.get((y - g1.y0) as usize * gw + (x - g1.x0) as usize).copied().unwrap_or_default() } else { [0.0; 2] };
+ let i = (y - area.y0) as usize * w + (x - area.x0) as usize;
+ if let Some(v) = f.strength.get_mut(i) {
+ *v = s0;
+ }
+ if let Some(v) = f.grad.get_mut(i) {
+ *v = g;
+ }
+ if g == [0.0; 2] {
+ continue;
+ }
+ // The neighbours across the edge: the gradient rounded to one of 8 directions.
+ let q = |v: f32, o: f32| if v.abs() >= 0.4142 * o.abs() { v.signum() as i32 } else { 0 };
+ let (dx, dy) = (q(g[0], g[1]), q(g[1], g[0]));
+ let (sm, sp) = (s_at(x - dx, y - dy), s_at(x + dx, y + dy));
+ if s0 > 0.0 && s0 >= sm && s0 >= sp {
+ if let Some(v) = f.ridge.get_mut(i) {
+ *v = true;
+ }
+ // The peak of the parabola through the three strengths.
+ let denom = sm - 2.0 * s0 + sp;
+ let t = if denom < -1e-6 { (0.5 * (sm - sp) / denom).clamp(-0.5, 0.5) } else { 0.0 };
+ if let Some(v) = f.offset.get_mut(i) {
+ *v = [t * dx as f32, t * dy as f32];
+ }
+ }
+ }
+ }
+ f
+ }
+
+ fn h(&self) -> usize {
+ self.strength.len() / self.w.max(1)
+ }
+
+ fn index(&self, x: i32, y: i32) -> Option<usize> {
+ self.area.contains(x, y).then(|| (y - self.area.y0) as usize * self.w + (x - self.area.x0) as usize)
+ }
+
+ /// Where the border runs through pixel `i` at (`x`, `y`): the edge's sub-pixel centre on an edge
+ /// at least `contrast` strong, else the pixel centre.
+ fn point(&self, i: usize, x: i32, y: i32, contrast: f32) -> [f64; 2] {
+ let on_edge = self.ridge.get(i).copied().unwrap_or(false) && self.strength.get(i).copied().unwrap_or(0.0) >= contrast;
+ let o = if on_edge { self.offset.get(i).copied().unwrap_or_default() } else { [0.0; 2] };
+ [x as f64 + 0.5 + f64::from(o[0]), y as f64 + 0.5 + f64::from(o[1])]
+ }
+
+ fn point_at(&self, i: usize, contrast: f32) -> [f64; 2] {
+ let (x, y) = ((i % self.w.max(1)) as i32 + self.area.x0, (i / self.w.max(1)) as i32 + self.area.y0);
+ self.point(i, x, y, contrast)
+ }
+}
+
+/// Squared distance from each pixel centre of `area` to the polyline `guide`, infinite beyond
+/// `rad`: the corridor the border may use.
+fn corridor(area: Rect, guide: &[[f64; 2]], rad: f64) -> Vec<f32> {
+ let w = area.width() as usize;
+ let mut near = vec![f32::INFINITY; w * area.height() as usize];
+ let r2 = rad * rad;
+ let single;
+ let segs: &[[f64; 2]] = match guide {
+ [p] => {
+ single = [*p, *p];
+ &single
+ }
+ _ => guide,
+ };
+ for s in segs.windows(2) {
+ let (a, b) = (s[0], s[1]);
+ let lo = |u: f64, v: f64| (u.min(v) - rad).floor() as i32;
+ let hi = |u: f64, v: f64| (u.max(v) + rad).ceil() as i32 + 1;
+ let r = Rect::new(lo(a[0], b[0]), lo(a[1], b[1]), hi(a[0], b[0]), hi(a[1], b[1])).intersect(&area);
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let d2 = dist2_segment([x as f64 + 0.5, y as f64 + 0.5], a, b);
+ if d2 <= r2
+ && let Some(v) = near.get_mut((y - area.y0) as usize * w + (x - area.x0) as usize)
+ {
+ *v = v.min(d2 as f32);
+ }
+ }
+ }
+ }
+ near
+}
+
+/// The cheapest 8-connected path from `start` to `goal` through the corridor `near` (squared
+/// distances to the guide, `rad2` at its rim), as field indices from `start` to `goal`.
+fn search(f: &Field, near: &[f32], rad2: f32, start: usize, goal: usize, contrast: f32) -> Option<Vec<usize>> {
+ let (w, h) = (f.w, f.h());
+ let n = w * h;
+ // Cost of entering each pixel, per pixel of length, and its edge tangent.
+ let mut node = vec![f32::INFINITY; n];
+ let mut tangent = vec![[0.0f32; 2]; n];
+ for i in 0..n {
+ let d2 = near.get(i).copied().unwrap_or(f32::INFINITY);
+ if !d2.is_finite() {
+ continue;
+ }
+ let s = f.strength.get(i).copied().unwrap_or(0.0);
+ let on_edge = s >= contrast && f.ridge.get(i).copied().unwrap_or(false);
+ // No pull below the contrast, full pull from twice the contrast, a little more for
+ // stronger edges still.
+ let good = ((s - contrast) / contrast.max(0.02)).clamp(0.0, 1.0) * (0.6 + 0.4 * s.min(1.0));
+ // Grows linearly away from the pointer's path, so the border hugs it where there is no edge.
+ let pull = (d2 / rad2.max(1.0)).sqrt().min(1.0);
+ let centre = if on_edge { 0.0 } else { 1.0 };
+ if let Some(v) = node.get_mut(i) {
+ *v = W_CENTRE * centre + W_STRENGTH * (1.0 - good) + W_LENGTH + W_GUIDE * pull;
+ }
+ if s >= 0.5 * contrast
+ && let (Some(t), Some(g)) = (tangent.get_mut(i), f.grad.get(i))
+ {
+ *t = [g[1], -g[0]];
+ }
+ }
+ let mut dist = vec![f32::INFINITY; n];
+ let mut from = vec![u8::MAX; n];
+ *dist.get_mut(start)? = 0.0;
+ let mut heap = BinaryHeap::new();
+ // Costs are finite and non-negative, so their bit patterns sort like the values.
+ heap.push(Reverse((0.0f32.to_bits(), start)));
+ while let Some(Reverse((bits, i))) = heap.pop() {
+ let d = f32::from_bits(bits);
+ if d > dist.get(i).copied().unwrap_or(f32::INFINITY) {
+ continue;
+ }
+ if i == goal {
+ break;
+ }
+ let (x, y) = ((i % w) as i32, (i / w) as i32);
+ let tp = tangent.get(i).copied().unwrap_or_default();
+ for (k, &(dx, dy)) in DIRS.iter().enumerate() {
+ let (nx, ny) = (x + dx, y + dy);
+ if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 {
+ continue;
+ }
+ let j = ny as usize * w + nx as usize;
+ let cost = node.get(j).copied().unwrap_or(f32::INFINITY);
+ if !cost.is_finite() {
+ continue;
+ }
+ let len = if dx != 0 && dy != 0 { SQRT_2 } else { 1.0 };
+ let tq = tangent.get(j).copied().unwrap_or_default();
+ let nd = d + cost * len + W_DIRECTION * direction_cost(tp, tq, dx, dy, len);
+ if let (Some(dj), Some(fj)) = (dist.get_mut(j), from.get_mut(j))
+ && nd < *dj
+ {
+ *dj = nd;
+ *fj = k as u8;
+ heap.push(Reverse((nd.to_bits(), j)));
+ }
+ }
+ }
+ if !dist.get(goal).is_some_and(|d| d.is_finite()) {
+ return None;
+ }
+ let mut cells = vec![goal];
+ let mut cur = goal;
+ while cur != start && cells.len() <= n {
+ let &(dx, dy) = DIRS.get(usize::from(*from.get(cur)?))?;
+ let (x, y) = ((cur % w) as i32 - dx, (cur / w) as i32 - dy);
+ if x < 0 || y < 0 {
+ return None;
+ }
+ cur = y as usize * w + x as usize;
+ cells.push(cur);
+ }
+ cells.reverse();
+ Some(cells)
+}
+
+/// The gradient-direction term of a link from a pixel with edge tangent `tp` to its neighbour at
+/// (`dx`, `dy`) with tangent `tq`: 0 running straight along an edge, up to 1 cutting across it or
+/// turning sharply (Mortensen & Barrett's f_D).
+fn direction_cost(tp: [f32; 2], tq: [f32; 2], dx: i32, dy: i32, len: f32) -> f32 {
+ if tp == [0.0; 2] || tq == [0.0; 2] {
+ return NEUTRAL_DIRECTION;
+ }
+ let mut l = [dx as f32 / len, dy as f32 / len];
+ if tp[0] * l[0] + tp[1] * l[1] < 0.0 {
+ l = [-l[0], -l[1]];
+ }
+ let dp = (tp[0] * l[0] + tp[1] * l[1]).clamp(-1.0, 1.0);
+ let dq = (l[0] * tq[0] + l[1] * tq[1]).clamp(-1.0, 1.0);
+ 2.0 / (3.0 * PI) * (dp.acos() + dq.acos())
+}
+
+/// The polyline `g` cut into pieces at most `piece` long; each piece starts where the last ended.
+fn split(g: &[[f64; 2]], piece: f64) -> Vec<Vec<[f64; 2]>> {
+ let Some(&first) = g.first() else { return Vec::new() };
+ let mut out = Vec::new();
+ let mut cur = vec![first];
+ let mut acc = 0.0;
+ for w in g.windows(2) {
+ let (mut a, b) = (w[0], w[1]);
+ let mut seg = dist(a, b);
+ while acc + seg > piece && seg > 0.0 {
+ let t = ((piece - acc) / seg).clamp(0.0, 1.0);
+ let m = [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
+ cur.push(m);
+ out.push(std::mem::replace(&mut cur, vec![m]));
+ a = m;
+ seg = dist(a, b);
+ acc = 0.0;
+ }
+ cur.push(b);
+ acc += seg;
+ }
+ out.push(cur);
+ out
+}
+
+/// Ramer–Douglas–Peucker: drops points within `tol` of the line through their neighbours that
+/// stay, keeping both ends.
+pub fn simplify(p: &[[f64; 2]], tol: f64) -> Vec<[f64; 2]> {
+ let n = p.len();
+ if n < 3 {
+ return p.to_vec();
+ }
+ let mut keep = vec![false; n];
+ keep[0] = true;
+ keep[n - 1] = true;
+ let tol2 = tol * tol;
+ let mut stack = vec![(0usize, n - 1)];
+ while let Some((a, b)) = stack.pop() {
+ if b <= a + 1 {
+ continue;
+ }
+ let (Some(&pa), Some(&pb)) = (p.get(a), p.get(b)) else { continue };
+ let mut far = (0.0, a);
+ for (k, q) in p.iter().enumerate().take(b).skip(a + 1) {
+ let d2 = dist2_segment(*q, pa, pb);
+ if d2 > far.0 {
+ far = (d2, k);
+ }
+ }
+ if far.0 > tol2 {
+ if let Some(k) = keep.get_mut(far.1) {
+ *k = true;
+ }
+ stack.push((a, far.1));
+ stack.push((far.1, b));
+ }
+ }
+ p.iter().zip(&keep).filter(|(_, k)| **k).map(|(q, _)| *q).collect()
+}
+
+/// Length of a polyline.
+pub fn length(p: &[[f64; 2]]) -> f64 {
+ p.windows(2).map(|w| dist(w[0], w[1])).sum()
+}
+
+fn dist(a: [f64; 2], b: [f64; 2]) -> f64 {
+ (a[0] - b[0]).hypot(a[1] - b[1])
+}
+
+fn dist2_segment(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
+ let (vx, vy) = (b[0] - a[0], b[1] - a[1]);
+ let l2 = vx * vx + vy * vy;
+ let t = if l2 > 0.0 { (((p[0] - a[0]) * vx + (p[1] - a[1]) * vy) / l2).clamp(0.0, 1.0) } else { 0.0 };
+ let (dx, dy) = (p[0] - (a[0] + t * vx), p[1] - (a[1] + t * vy));
+ dx * dx + dy * dy
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/algo/src/magnetic/tests.rs b/crates/algo/src/magnetic/tests.rs
new file mode 100644
index 000000000..ccfc73bc0
--- /dev/null
+++ b/crates/algo/src/magnetic/tests.rs
@@ -0,0 +1,195 @@
+use std::cell::Cell;
+
+use super::*;
+
+/// A procedural image as a fetch that counts the pixels it reads.
+fn image<'a>(f: impl Fn(i32, i32) -> [u8; 4] + 'a, read: &'a Cell<usize>) -> impl FnMut(Rect) -> Vec<[u8; 4]> + 'a {
+ move |r: Rect| {
+ read.set(read.get() + r.width() as usize * r.height() as usize);
+ (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| (x, y))).map(|(x, y)| f(x, y)).collect()
+ }
+}
+
+fn grey(v: u8) -> [u8; 4] {
+ [v, v, v, 255]
+}
+
+/// Distance from `p` to the polyline `g`.
+fn off_polyline(p: [f64; 2], g: &[[f64; 2]]) -> f64 {
+ g.windows(2).map(|w| dist2_segment(p, w[0], w[1]).sqrt()).fold(f64::INFINITY, f64::min)
+}
+
+#[test]
+fn snaps_to_the_edge_centre_within_the_width() {
+ let read = Cell::new(0);
+ // Black left of x = 20, white from it.
+ let mut f = image(|x, _| grey(if x < 20 { 0 } else { 255 }), &read);
+ let mut t = Tracer::new(Rect::new(0, 0, 64, 32));
+ let p = t.snap(&mut f, [14.3, 10.5], Settings::new(10.0, 0.1)).unwrap();
+ assert!((p[0] - 20.0).abs() < 0.01 && (p[1] - 10.5).abs() < 0.01, "on the step, not half a pixel off: {p:?}");
+ // From the other side too.
+ let p = t.snap(&mut f, [27.0, 3.2], Settings::new(10.0, 0.1)).unwrap();
+ assert!((p[0] - 20.0).abs() < 0.01, "{p:?}");
+ // Out of reach: the point stays where it is.
+ assert_eq!(t.snap(&mut f, [14.3, 10.5], Settings::new(3.0, 0.1)), Some([14.3, 10.5]));
+}
+
+#[test]
+fn contrast_sets_which_steps_are_edges() {
+ let read = Cell::new(0);
+ // A 5% step.
+ let mut f = image(|x, _| grey(if x < 20 { 100 } else { 113 }), &read);
+ let mut t = Tracer::new(Rect::new(0, 0, 64, 32));
+ assert_eq!(t.snap(&mut f, [14.3, 10.5], Settings::new(10.0, 0.10)), Some([14.3, 10.5]), "too faint at 10%");
+ let p = t.snap(&mut f, [14.3, 10.5], Settings::new(10.0, 0.03)).unwrap();
+ assert!((p[0] - 20.0).abs() < 0.01, "an edge at 3%: {p:?}");
+}
+
+#[test]
+fn snaps_to_the_most_prominent_edge() {
+ let read = Cell::new(0);
+ // A faint step at x = 12 and a strong one at x = 18.
+ let mut f = image(|x, _| grey([0, 40, 255][usize::from(x >= 12) + usize::from(x >= 18)]), &read);
+ let mut t = Tracer::new(Rect::new(0, 0, 40, 20));
+ let p = t.snap(&mut f, [13.0, 10.0], Settings::new(10.0, 0.1)).unwrap();
+ assert!((p[0] - 18.0).abs() < 0.01, "{p:?}");
+}
+
+#[test]
+fn trace_follows_a_curved_edge() {
+ let read = Cell::new(0);
+ // A white disc of radius 30 at (50, 50) on black.
+ let mut f = image(|x, y| grey(if (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0) < 30.0 { 255 } else { 0 }), &read);
+ let mut t = Tracer::new(Rect::new(0, 0, 100, 100));
+ let s = Settings::default();
+ let a = t.snap(&mut f, [50.0, 21.0], s).unwrap();
+ let b = t.snap(&mut f, [79.0, 50.0], s).unwrap();
+ // The pointer went straight from one to the other; the border bows out along the disc, ~9 px
+ // from the chord at its middle.
+ let path = t.trace(&mut f, a, b, &[], s);
+ assert!(path.len() > 4, "{path:?}");
+ assert_eq!((path[0], path[path.len() - 1]), (a, b));
+ for p in &path {
+ let r = (p[0] - 50.0).hypot(p[1] - 50.0);
+ assert!((r - 30.0).abs() < 1.0, "{p:?} is {r:.2} from the centre: {path:?}");
+ }
+}
+
+#[test]
+fn without_edges_the_border_follows_the_pointer() {
+ let read = Cell::new(0);
+ let mut f = image(|_, _| grey(128), &read);
+ let mut t = Tracer::new(Rect::new(0, 0, 120, 80));
+ let s = Settings::default();
+ // A gentle curve: the border runs along it.
+ let (a, b) = ([10.0, 40.0], [110.0, 40.0]);
+ let guide: Vec<[f64; 2]> = (1..10).map(|i| [10.0 + f64::from(i) * 10.0, 40.0 - 15.0 * (f64::from(i) * std::f64::consts::PI / 10.0).sin()]).collect();
+ let g: Vec<[f64; 2]> = std::iter::once(a).chain(guide.iter().copied()).chain([b]).collect();
+ let path = t.trace(&mut f, a, b, &guide, s);
+ for p in &path {
+ assert!(off_polyline(*p, &g) < 2.0, "{p:?} strays from the pointer: {path:?}");
+ }
+ assert!(off_polyline([60.0, 25.0], &path) < 2.0, "the border went where the pointer went: {path:?}");
+ // A sharp turn: the border may round it off, but never leaves the detection width.
+ let guide = [[30.0, 70.0]];
+ let path = t.trace(&mut f, [10.0, 10.0], [100.0, 75.0], &guide, s);
+ for p in &path {
+ assert!(off_polyline(*p, &[[10.0, 10.0], [30.0, 70.0], [100.0, 75.0]]) <= s.width, "{p:?}: {path:?}");
+ }
+ // A straight pointer path over nothing is one straight segment.
+ assert_eq!(t.trace(&mut f, [10.0, 10.0], [110.0, 73.0], &[], s), vec![[10.0, 10.0], [110.0, 73.0]]);
+}
+
+#[test]
+fn the_corridor_keeps_the_border_off_edges_the_pointer_never_went_near() {
+ let read = Cell::new(0);
+ // A modest step at y = 20, under the pointer, and a much stronger one at y = 40.
+ let mut f = image(|_, y| grey([60, 100, 255][usize::from(y >= 20) + usize::from(y >= 40)]), &read);
+ let mut t = Tracer::new(Rect::new(0, 0, 120, 60));
+ let path = t.trace(&mut f, [10.0, 22.0], [110.0, 18.0], &[[60.0, 23.0]], Settings::new(10.0, 0.1));
+ for p in &path {
+ assert!((p[1] - 20.0).abs() <= 2.0 + 1e-9, "{p:?} left the edge under the pointer: {path:?}");
+ }
+ // Away from the ends it runs on the step itself.
+ assert!(path.iter().filter(|p| p[0] > 25.0 && p[0] < 95.0).all(|p| (p[1] - 20.0).abs() < 0.01), "{path:?}");
+}
+
+#[test]
+fn long_guides_are_traced_in_pieces_along_the_edge() {
+ let read = Cell::new(0);
+ // A step at y = 30 across a wide image; the pointer wavers 4 px either side of it.
+ let mut f = image(|_, y| grey(if y < 30 { 20 } else { 200 }), &read);
+ let mut t = Tracer::new(Rect::new(0, 0, 1000, 60));
+ let guide: Vec<[f64; 2]> = (1..20).map(|i| [f64::from(i) * 50.0, if i % 2 == 0 { 26.0 } else { 34.0 }]).collect();
+ let path = t.trace(&mut f, [5.0, 30.0], [995.0, 30.0], &guide, Settings::default());
+ for p in &path {
+ assert!((p[1] - 30.0).abs() < 0.01, "{p:?}");
+ }
+ let len = length(&path);
+ assert!((len - 990.0).abs() < 1.0, "a straight border, not a zigzag: {len}");
+ // Collinear points are dropped.
+ assert!(path.len() < 20, "{}", path.len());
+}
+
+#[test]
+fn reads_only_the_pixels_around_the_border() {
+ let read = Cell::new(0);
+ let mut f = image(|x, _| grey(if x < 3000 { 0 } else { 255 }), &read);
+ // A 24 MP image.
+ let mut t = Tracer::new(Rect::new(0, 0, 6000, 4000));
+ let s = Settings::default();
+ let a = t.snap(&mut f, [2996.0, 2000.0], s).unwrap();
+ let b = t.snap(&mut f, [3004.0, 2100.0], s).unwrap();
+ let path = t.trace(&mut f, a, b, &[], s);
+ assert!(path.iter().all(|p| (p[0] - 3000.0).abs() < 0.01), "{path:?}");
+ let first = read.get();
+ assert!(first <= 6 * 128 * 128, "read {first} px");
+ assert_eq!(t.cached_pixels(), first);
+ // The same area again comes from the cache.
+ t.trace(&mut f, a, b, &[], s);
+ assert_eq!(read.get(), first);
+}
+
+#[test]
+fn hostile_input_never_panics() {
+ let read = Cell::new(0);
+ let mut f = image(|x, y| grey(((x ^ y) & 255) as u8), &read);
+ let s = Settings::default();
+ // No image at all.
+ let mut empty = Tracer::new(Rect::EMPTY);
+ assert_eq!(empty.snap(&mut f, [1.0, 1.0], s), None);
+ assert!(empty.trace(&mut f, [1.0, 1.0], [5.0, 5.0], &[], s).is_empty());
+ let mut t = Tracer::new(Rect::new(0, 0, 50, 40));
+ // Not points.
+ assert_eq!(t.snap(&mut f, [f64::NAN, 1.0], s), None);
+ assert!(t.trace(&mut f, [f64::INFINITY, 1.0], [5.0, 5.0], &[], s).is_empty());
+ // Far outside the image: kept inside it.
+ let path = t.trace(&mut f, [-1e300, -1e9], [1e9, 1e300], &[[f64::NAN, 3.0], [1e12, -5.0]], s);
+ assert!(path.iter().all(|p| (0.0..=50.0).contains(&p[0]) && (0.0..=40.0).contains(&p[1])), "{path:?}");
+ // Nonsense settings are clamped, whichever way they arrive.
+ for s in [Settings { width: f64::NAN, contrast: f32::NAN }, Settings { width: 1e300, contrast: -4.0 }, Settings { width: -3.0, contrast: 1e30 }] {
+ t.snap(&mut f, [20.0, 20.0], s).unwrap();
+ assert!(!t.trace(&mut f, [2.0, 2.0], [45.0, 30.0], &[[10.0, 35.0]], s).is_empty());
+ }
+ // A fetch that returns the wrong amount of pixels reads as transparent.
+ let mut bad = |_: Rect| vec![[255u8; 4]; 3];
+ let mut t = Tracer::new(Rect::new(0, 0, 300, 300));
+ assert_eq!(t.snap(&mut bad, [150.0, 150.0], s), Some([150.0, 150.0]));
+ let path = t.trace(&mut bad, [10.0, 10.0], [290.0, 280.0], &[], s);
+ assert_eq!((path.first(), path.last()), (Some(&[10.0, 10.0]), Some(&[290.0, 280.0])));
+ // The same point twice.
+ assert_eq!(t.trace(&mut bad, [7.0, 7.0], [7.0, 7.0], &[], s), vec![[7.0, 7.0], [7.0, 7.0]]);
+}
+
+#[test]
+fn split_and_simplify() {
+ let g = [[0.0, 0.0], [600.0, 0.0], [600.0, 100.0]];
+ let pieces = split(&g, 256.0);
+ assert_eq!(pieces.len(), 3);
+ assert_eq!(pieces[0], vec![[0.0, 0.0], [256.0, 0.0]]);
+ assert_eq!(pieces[2].last(), Some(&[600.0, 100.0]));
+ let total: f64 = pieces.iter().map(|p| length(p)).sum();
+ assert!((total - 700.0).abs() < 1e-9);
+ assert_eq!(simplify(&[[0.0, 0.0], [1.0, 0.1], [2.0, 0.0], [3.0, 5.0]], 0.3), vec![[0.0, 0.0], [2.0, 0.0], [3.0, 5.0]]);
+ assert!(split(&[], 256.0).is_empty());
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 603fbabd0..e2fc0cd57 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -991,6 +991,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::retouch_cmds::specs());
v.extend(crate::image_cmds::specs());
v.extend(crate::selection_cmds::specs());
+ v.extend(crate::magnetic_cmds::specs());
v.extend(crate::select_extra_cmds::specs());
v.extend(crate::paint_cmds::specs());
v.extend(crate::extra_cmds::specs());
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 6a6f3230f..71850cd71 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -48,6 +48,7 @@ pub mod layer_multi_cmds;
pub mod layer_nav_cmds;
pub mod layer_style;
pub mod lens_cmds;
+pub mod magnetic_cmds;
pub mod mask_view_cmds;
mod migrate_cmds;
pub mod mode_cmds;
diff --git a/crates/engine/src/magnetic_cmds.rs b/crates/engine/src/magnetic_cmds.rs
new file mode 100644
index 000000000..f13d96fa5
--- /dev/null
+++ b/crates/engine/src/magnetic_cmds.rs
@@ -0,0 +1,191 @@
+//! Magnetic Lasso: a selection border that snaps to edges between fastening points, traced by
+//! `photocraft_algo::magnetic`.
+//!
+//! The tool is interactive (ui-egui `magnetic_lasso_ui`): it traces live through an
+//! [`EdgeSource`] and commits the outline it showed with `select.magneticLasso` and
+//! `"trace": false`, so an action replays exactly that outline. Given fastening points alone,
+//! `select.magneticLasso` traces the whole border itself, for scripts and agents.
+
+use std::sync::Arc;
+
+use photocraft_algo::magnetic::{self, Settings, Tracer};
+use photocraft_algo::selection as sel;
+use photocraft_doc::{DocId, Document, LayerId};
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{DocState, EngineError, Result, Session};
+
+const CMD: &str = "select.magneticLasso";
+/// Most points one command takes.
+const MAX_POINTS: usize = 100_000;
+/// Longest border one command traces (px, measured along the fastening points).
+const MAX_LENGTH: f64 = 200_000.0;
+
+/// The pixels the Magnetic Lasso follows: the active layer's when it is a pixel layer (Photoshop's
+/// tool sees only the current layer), else the composite. A snapshot of one document revision,
+/// read lazily and cached while a border is drawn.
+pub struct EdgeSource {
+ doc: Arc<Document>,
+ layer: Option<LayerId>,
+ revision: u64,
+ tracer: Tracer,
+}
+
+/// The active layer when it has pixels of its own.
+fn pixel_layer(d: &DocState) -> Option<LayerId> {
+ d.active_layer.filter(|id| d.doc.layer(*id).is_some_and(|l| l.surface().is_some()))
+}
+
+impl EdgeSource {
+ /// For the session's active document; `None` without one.
+ pub fn new(s: &Session) -> Option<EdgeSource> {
+ let d = s.active()?;
+ Some(EdgeSource { doc: d.doc.clone(), layer: pixel_layer(d), revision: d.revision, tracer: Tracer::new(d.doc.bounds()) })
+ }
+
+ /// Whether this still shows the session's active document, layer and revision.
+ pub fn is_current(&self, s: &Session) -> bool {
+ s.active().is_some_and(|d| d.doc.id == self.doc.id && d.revision == self.revision && pixel_layer(d) == self.layer)
+ }
+
+ /// The document this reads.
+ pub fn doc_id(&self) -> DocId {
+ self.doc.id
+ }
+
+ /// Where a fastening point near `p` goes: on the most prominent edge within the detection
+ /// width, else at `p` (see [`Tracer::snap`]).
+ pub fn snap(&mut self, p: [f64; 2], s: Settings) -> Option<[f64; 2]> {
+ let (doc, layer) = (&self.doc, self.layer);
+ self.tracer.snap(&mut |r| read(doc, layer, r), p, s)
+ }
+
+ /// The border from `from` to `to` along the edges near `guide`, the pointer's path between them
+ /// (see [`Tracer::trace`]).
+ pub fn trace(&mut self, from: [f64; 2], to: [f64; 2], guide: &[[f64; 2]], s: Settings) -> Vec<[f64; 2]> {
+ let (doc, layer) = (&self.doc, self.layer);
+ self.tracer.trace(&mut |r| read(doc, layer, r), from, to, guide, s)
+ }
+}
+
+/// Straight RGBA8 pixels of `r` from the layer, or the composite without one.
+fn read(doc: &Document, layer: Option<LayerId>, r: Rect) -> Vec<[u8; 4]> {
+ match layer.and_then(|id| doc.layer(id)).and_then(|l| l.surface()) {
+ Some(surface) => sel::rgba8_image(surface, r),
+ None => {
+ let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
+ photocraft_compose::render(doc, r).px.iter().map(|p| p.map(q)).collect()
+ }
+ }
+}
+
+fn bad(msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
+}
+
+/// `points`: `[[x, y], …]` of finite numbers.
+fn points(p: &Value) -> Result<Vec<[f64; 2]>> {
+ let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad("`points` must be [[x, y], …]"))?;
+ if a.len() > MAX_POINTS {
+ return Err(bad(format!("at most {MAX_POINTS} points")));
+ }
+ a.iter()
+ .map(|q| match q.as_array().map(Vec::as_slice) {
+ Some([x, y]) => match (x.as_f64(), y.as_f64()) {
+ (Some(x), Some(y)) if x.is_finite() && y.is_finite() => Ok([x, y]),
+ _ => Err(bad(format!("bad point {q} (want [x, y])"))),
+ },
+ _ => Err(bad(format!("bad point {q} (want [x, y])"))),
+ })
+ .collect()
+}
+
+/// A number in `range`, or `default` when absent.
+fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
+ match p.get(key) {
+ None => Ok(default),
+ Some(v) => {
+ v.as_f64().filter(|x| range.contains(x)).ok_or_else(|| bad(format!("`{key}` must be a number in {}..{} (got {v})", range.start(), range.end())))
+ }
+ }
+}
+
+fn magnetic_lasso(s: &mut Session, p: &Value) -> Result<Value> {
+ let pts = points(p)?;
+ if pts.len() < 3 {
+ return Err(bad("needs at least 3 points"));
+ }
+ let trace = match p.get("trace") {
+ None => true,
+ Some(v) => v.as_bool().ok_or_else(|| bad("`trace` must be true or false"))?,
+ };
+ let outline = if trace {
+ let width = number(p, "width", 10.0, magnetic::WIDTH_RANGE.0..=magnetic::WIDTH_RANGE.1)?;
+ let contrast = number(p, "contrast", 10.0, 1.0..=100.0)?;
+ let straight = match p.get("close").map(Value::as_str) {
+ None | Some(Some("magnetic")) => false,
+ Some(Some("straight")) => true,
+ Some(_) => return Err(bad("`close` must be \"magnetic\" or \"straight\"")),
+ };
+ let settings = Settings::new(width, (contrast / 100.0) as f32);
+ let mut src = EdgeSource::new(s).ok_or(EngineError::NoDocument)?;
+ trace_border(&mut src, &pts, settings, straight)?
+ } else {
+ pts
+ };
+ let polygon: Vec<(f32, f32)> = outline.iter().map(|q| (q[0] as f32, q[1] as f32)).collect();
+ let mut r = crate::selection_cmds::polygon_selection(s, CMD, "Magnetic Lasso", &polygon, p)?;
+ r["points"] = json!(outline.len());
+ Ok(r)
+}
+
+/// The closed border through the fastening points `pts`, each snapped to the nearest prominent
+/// edge first, as the tool places them. The last point joins the first along the edges, or
+/// straight with `straight`.
+fn trace_border(src: &mut EdgeSource, pts: &[[f64; 2]], settings: Settings, straight: bool) -> Result<Vec<[f64; 2]>> {
+ let b = src.tracer.bounds();
+ let inside = |q: &[f64; 2]| [q[0].clamp(b.x0 as f64, b.x1 as f64), q[1].clamp(b.y0 as f64, b.y1 as f64)];
+ let mut ring: Vec<[f64; 2]> = pts.iter().map(inside).collect();
+ if let Some(&first) = ring.first() {
+ ring.push(first);
+ }
+ if magnetic::length(&ring) > MAX_LENGTH {
+ return Err(bad(format!("the border is longer than {MAX_LENGTH} px")));
+ }
+ ring.pop();
+ let anchors: Vec<[f64; 2]> = ring.iter().filter_map(|q| src.snap(*q, settings)).collect();
+ let Some(&first) = anchors.first() else { return Err(EngineError::Other("the document has no pixels".into())) };
+ let mut out = vec![first];
+ for w in anchors.windows(2) {
+ out.extend(src.trace(w[0], w[1], &[], settings).into_iter().skip(1));
+ }
+ if !straight && let Some(&last) = anchors.last() {
+ out.extend(src.trace(last, first, &[], settings).into_iter().skip(1));
+ // The ring ends where it started.
+ out.pop();
+ }
+ Ok(out)
+}
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document open".into())
+}
+
+/// Magnetic Lasso command specs.
+pub fn specs() -> Vec<CommandSpec> {
+ vec![CommandSpec {
+ id: CMD,
+ label: "Magnetic Lasso",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"points":[[x,y],…] (≥3 fastening points in order; with trace=false, the finished outline),"width":1..256=10 (px: follows edges this close to the points),"contrast":1..100=10 (%: weaker edges are ignored),"close":"magnetic|straight"="magnetic" (how the last point joins the first),"trace":bool=true,"mode":"replace|add|subtract|intersect"="replace","antiAlias":bool=true,"feather":0..1000=0 (px)}"##,
+ enabled: has_doc,
+ run: magnetic_lasso,
+ journal: true,
+ }]
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/engine/src/magnetic_cmds/tests.rs b/crates/engine/src/magnetic_cmds/tests.rs
new file mode 100644
index 000000000..39f7bef2b
--- /dev/null
+++ b/crates/engine/src/magnetic_cmds/tests.rs
@@ -0,0 +1,141 @@
+use photocraft_geom::Rect;
+use serde_json::json;
+
+use super::*;
+
+/// A black 40×40 square at (40, 30) on a white 120×100 background.
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 120, "height": 100})).unwrap();
+ s.edit("paint", |doc, _| {
+ let bg = doc.layers[0].surface_mut().unwrap();
+ bg.fill_rect(Rect::new(0, 0, 120, 100), &[1.0, 1.0, 1.0, 1.0]);
+ bg.fill_rect(Rect::new(40, 30, 80, 70), &[0.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+fn coverage(s: &Session, x: i32, y: i32) -> f32 {
+ s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0))
+}
+
+fn selected_area(s: &Session) -> f32 {
+ (0..100).flat_map(|y| (0..120).map(move |x| (x, y))).map(|(x, y)| coverage(s, x, y)).sum()
+}
+
+/// Rough points near the square's corners, some inside and some outside it.
+const ROUGH: [[f64; 2]; 4] = [[43.0, 33.0], [77.0, 27.0], [83.0, 72.0], [37.0, 66.0]];
+
+#[test]
+fn rough_points_select_the_shape_along_its_edges() {
+ let mut s = session();
+ let r = s.execute("select.magneticLasso", json!({"points": ROUGH})).unwrap();
+ assert_eq!(r["selected"], json!(true));
+ assert!(r["points"].as_u64().unwrap() >= 4, "{r}");
+ let area = selected_area(&s);
+ assert!((area - 1600.0).abs() < 40.0, "the square's area, not the rough quadrilateral's: {area}");
+ for (x, y) in [(60, 50), (41, 31), (78, 68), (41, 68), (78, 31)] {
+ assert!(coverage(&s, x, y) > 0.99, "({x}, {y}) inside");
+ }
+ for (x, y) in [(38, 50), (81, 50), (60, 28), (60, 71), (36, 66), (82, 71)] {
+ assert!(coverage(&s, x, y) < 0.01, "({x}, {y}) outside");
+ }
+ let st = s.active().unwrap();
+ assert_eq!(st.history.entries().last().map(String::as_str), Some("Magnetic Lasso"));
+ // One step: Undo takes it all back.
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(s.active().unwrap().doc.selection.is_none());
+}
+
+#[test]
+fn modes_and_a_given_outline() {
+ let mut s = session();
+ // `trace: false` selects the outline as given, like the tool's own commit.
+ s.execute("select.magneticLasso", json!({"points": [[0, 0], [20, 0], [0, 20]], "trace": false})).unwrap();
+ assert_eq!((coverage(&s, 2, 2), coverage(&s, 18, 18)), (1.0, 0.0));
+ s.execute("select.magneticLasso", json!({"points": ROUGH, "mode": "add"})).unwrap();
+ assert_eq!((coverage(&s, 2, 2), coverage(&s, 60, 50)), (1.0, 1.0));
+ s.execute("select.magneticLasso", json!({"points": ROUGH, "mode": "subtract", "close": "straight", "width": 20, "contrast": 50})).unwrap();
+ assert_eq!((coverage(&s, 2, 2), coverage(&s, 60, 50)), (1.0, 0.0));
+ s.execute("select.magneticLasso", json!({"points": ROUGH, "feather": 4})).unwrap();
+ let edge = coverage(&s, 40, 50);
+ assert!(edge > 0.2 && edge < 0.8, "feathered: {edge}");
+}
+
+#[test]
+fn edges_come_from_the_active_pixel_layer() {
+ let mut s = session();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ // An empty layer has no edges: the point stays where it is.
+ let settings = Settings::default();
+ let mut src = EdgeSource::new(&s).unwrap();
+ assert_eq!(src.snap([44.0, 50.0], settings), Some([44.0, 50.0]));
+ let bg = s.active().unwrap().doc.layers[0].id;
+ s.execute("layer.select", json!({"layer": bg.0})).unwrap();
+ assert!(!src.is_current(&s), "another layer");
+ let mut src = EdgeSource::new(&s).unwrap();
+ assert!(src.is_current(&s));
+ let p = src.snap([44.0, 50.0], settings).unwrap();
+ assert!((p[0] - 40.0).abs() < 0.01 && (p[1] - 50.0).abs() <= 1.0, "on the square's edge: {p:?}");
+ // A layer without pixels of its own (an Invert adjustment): the composite, its square white
+ // on black but its edge where it was.
+ s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap();
+ let st = s.active().unwrap();
+ assert!(st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.surface().is_none()));
+ let mut src = EdgeSource::new(&s).unwrap();
+ let p = src.snap([44.0, 50.0], settings).unwrap();
+ assert!((p[0] - 40.0).abs() < 0.01, "{p:?}");
+}
+
+#[test]
+fn reads_only_around_the_border_of_a_large_image() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 6000, "height": 4000, "background": "transparent"})).unwrap();
+ s.edit("paint", |doc, _| {
+ doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(2000, 1500, 2200, 1700), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let mut src = EdgeSource::new(&s).unwrap();
+ let border = trace_border(&mut src, &[[2003.0, 1497.0], [2198.0, 1504.0], [2203.0, 1702.0], [1998.0, 1695.0]], Settings::default(), false).unwrap();
+ assert!(border.iter().all(|p| (1999.0..=2201.0).contains(&p[0]) && (1499.0..=1701.0).contains(&p[1])), "{border:?}");
+ let read = src.tracer.cached_pixels();
+ assert!(read < 40 * 128 * 128, "read {read} of 24M px");
+}
+
+#[test]
+fn bad_params_are_refused() {
+ let mut s = session();
+ for p in [
+ json!({}),
+ json!({"points": "here"}),
+ json!({"points": [[0, 0], [10, 0]]}),
+ json!({"points": [[0, 0], [10, 0], ["a", 3]]}),
+ json!({"points": [[0, 0], [10, 0], [3]]}),
+ json!({"points": [[0, 0], [10, 0], [3, 4, 5]]}),
+ json!({"points": ROUGH, "width": 0}),
+ json!({"points": ROUGH, "width": 300}),
+ json!({"points": ROUGH, "width": "wide"}),
+ json!({"points": ROUGH, "contrast": 0}),
+ json!({"points": ROUGH, "contrast": 101}),
+ json!({"points": ROUGH, "close": "zigzag"}),
+ json!({"points": ROUGH, "close": 1}),
+ json!({"points": ROUGH, "trace": "yes"}),
+ json!({"points": ROUGH, "feather": -1}),
+ json!({"points": ROUGH, "feather": 5000}),
+ json!({"points": vec![[1, 1]; MAX_POINTS + 1]}),
+ ] {
+ assert!(s.execute("select.magneticLasso", p.clone()).is_err(), "{p}");
+ }
+ assert!(s.active().unwrap().doc.selection.is_none());
+ // Far outside the canvas is kept on it; a border far too long is refused.
+ s.execute("select.magneticLasso", json!({"points": [[-1e9, -1e9], [1e9, -1e9], [1e9, 1e9]]})).unwrap();
+ let mut big = Session::new();
+ big.execute("file.new", json!({"width": 30000, "height": 30000, "background": "transparent"})).unwrap();
+ let zigzag: Vec<[f64; 2]> = (0..20).map(|i| [f64::from(i % 2) * 30000.0, f64::from(i) * 1500.0]).collect();
+ assert!(big.execute("select.magneticLasso", json!({"points": zigzag})).is_err());
+ let mut none = Session::new();
+ assert!(none.execute("select.magneticLasso", json!({"points": ROUGH})).is_err());
+}
diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rs
index e21ea7da1..e445388d0 100644
--- a/crates/engine/src/selection_cmds.rs
+++ b/crates/engine/src/selection_cmds.rs
@@ -306,13 +306,23 @@ fn lasso(s: &mut Session, p: &Value) -> Result<Value> {
if pts.len() < 3 {
return Err(EngineError::BadParams { cmd: "select.lasso".into(), msg: "needs at least 3 points".into() });
}
- let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds();
- let mut mask = sel::polygon(&pts, area, b(p, "antiAlias", true));
+ polygon_selection(s, "select.lasso", "Lasso", &pts, p)
+}
+
+/// Selects the polygon `pts` with the lasso tools' `mode`, `antiAlias` and `feather` params, as
+/// one history step called `label`.
+pub(crate) fn polygon_selection(s: &mut Session, cmd: &str, label: &str, pts: &[(f32, f32)], p: &Value) -> Result<Value> {
let feather = f(p, "feather", 0.0);
+ // Select › Modify › Feather's range.
+ if !(0.0..=1000.0).contains(&feather) {
+ return Err(EngineError::BadParams { cmd: cmd.into(), msg: "feather must be a number in 0..1000".into() });
+ }
+ let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds();
+ let mut mask = sel::polygon(pts, area, b(p, "antiAlias", true));
if feather > 0.0 {
mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather);
}
- set_selection(s, "Lasso", area, mask, mode(p))
+ set_selection(s, label, area, mask, mode(p))
}
macro_rules! spec {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 9bce06ac5..a132ed71e 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -299,6 +299,7 @@ pub(crate) fn freehand_tool(tool: Tool) -> bool {
| Tool::Burn
| Tool::Sponge
| Tool::Lasso
+ | Tool::MagneticLasso
| Tool::Patch
| Tool::ContentAwareMove
| Tool::QuickSelection
@@ -1681,6 +1682,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
app.stylus.use_pressure = app.session.prefs().tools.use_tablet_pressure;
app.stylus.update(&ui.input(|i| i.events.clone()));
crate::stylus::Stylus::sync_eraser_tool(app);
+ // A Magnetic Lasso border left behind by a tool or document switch is dropped.
+ crate::magnetic_lasso_ui::frame(app);
// Held keys (hold_keys.rs): Space repositions a crop frame, marquee, lasso or shape being
// drawn; otherwise Space is the Hand and ⌘Space / ⌘⌥Space the Zoom tool while held.
let reposition = crate::hold_keys::reposition_held(app, &ctx);
@@ -1833,6 +1836,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
app.defer_live_stroke = false;
// One live-stroke update for the whole frame, not one per recovered sample.
feed_live_stroke(app);
+ crate::magnetic_lasso_ui::flush(app);
}
if buttons.stopped {
let p = response.interact_pointer_pos().map(|p| xf.to_doc(p)).or_else(|| app.drag.as_ref().and_then(|d| d.points.last().map(|q| [q[0], q[1]])));
@@ -1857,6 +1861,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// vertex (or already closed it), so the second never starts a new polygon. egui
// reports it as a triple click when a vertex went down shortly before.
Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app),
+ // The same for the Magnetic Lasso: along the edges, or straight with ⌥.
+ Tool::MagneticLasso if response.double_clicked() || response.triple_clicked() => crate::magnetic_lasso_ui::close(app, mods.alt),
_ => {
if tool == Tool::Move && app.ui.transform.is_none() {
begin_transform_controls_at(app, &ctx, &xf, p);
@@ -1866,6 +1872,17 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
}
}
+ // Magnetic Lasso: between clicks the border follows the pointer with the button up.
+ if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && response.hovered() {
+ let moves: Vec<Pos2> = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect());
+ app.defer_live_stroke = true;
+ for p in moves.into_iter().filter(|p| rect.contains(*p)) {
+ let d = xf.to_doc(p);
+ tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods);
+ }
+ app.defer_live_stroke = false;
+ crate::magnetic_lasso_ui::flush(app);
+ }
if app.ui.transform.is_some() && response.double_clicked() {
crate::transform_tool::commit(app);
}
@@ -1992,6 +2009,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
}
Tool::Type | Tool::VerticalType => egui::CursorIcon::Text,
+ Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, &painter, p, view.zoom),
_ => egui::CursorIcon::Crosshair,
};
ui.ctx().set_cursor_icon(icon);
@@ -2126,8 +2144,9 @@ fn crop_overlay(painter: &egui::Painter, r: Rect) {
}
}
-/// Overlays that persist between gestures: polygonal lasso in progress, pending crop box.
+/// Overlays that persist between gestures: polygonal or magnetic lasso in progress, pending crop box.
fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: Option<Pos2>) {
+ crate::magnetic_lasso_ui::draw(app, painter, xf, hover);
if !app.ui.polygon.is_empty() {
let mut pts: Vec<Pos2> = app.ui.polygon.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect();
if let Some(h) = hover {
@@ -2411,6 +2430,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
if crate::lasso_ui::pointer(app, ev, mods) {
return;
}
+ // Magnetic Lasso: fastening points and the border following the pointer.
+ if crate::magnetic_lasso_ui::pointer(app, ev, mods) {
+ return;
+ }
let tool = app.ui.tool;
if tool == Tool::Eyedropper {
match ev {
@@ -2678,7 +2701,10 @@ pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {
let pts: Vec<[f64; 2]> = d.points.iter().map(|p| [p[0], p[1]]).collect();
if pts.len() >= 3 {
let mode = selection_mode(app, d.modifiers);
- let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": app.ui.tool_options.anti_alias}));
+ let o = &app.ui.tool_options;
+ // The Patch and Content-Aware Move tools have no Feather in their options bar.
+ let feather = if d.tool == Tool::Lasso { o.feather } else { 0.0 };
+ let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": o.anti_alias, "feather": feather}));
} else if app.session.is_enabled("select.deselect") {
let _ = app.run("select.deselect", json!({}));
}
@@ -2733,7 +2759,7 @@ pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) {
/// Selection mode from the options bar, overridden by modifier keys (⇧ add, ⌥ subtract, ⇧⌥ intersect).
/// The cursor badge announces the same mode (`tool_feedback`).
-fn selection_mode(app: &PhotocraftApp, m: egui::Modifiers) -> &'static str {
+pub(crate) fn selection_mode(app: &PhotocraftApp, m: egui::Modifiers) -> &'static str {
crate::tool_feedback::selection_mode(Tool::Lasso, app.ui.selection_mode, m)
}
@@ -2756,9 +2782,10 @@ fn polygon_click(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers)
app.ui.polygon.push([x, y]);
}
-/// A new-selection polygonal lasso is being drawn, so the selection it will replace is hidden.
+/// A new-selection polygonal (or magnetic) lasso is being drawn, so the selection it will replace
+/// is hidden.
pub fn polygon_replaces_selection(app: &PhotocraftApp) -> bool {
- !app.ui.polygon.is_empty() && app.ui.polygon_mode == "replace"
+ (!app.ui.polygon.is_empty() && app.ui.polygon_mode == "replace") || crate::magnetic_lasso_ui::replaces_selection(app)
}
/// Close the polygonal lasso and make the selection in the mode it started in.
@@ -2767,7 +2794,8 @@ pub fn commit_polygon(app: &mut PhotocraftApp) {
let mode = std::mem::take(&mut app.ui.polygon_mode);
if pts.len() >= 3 {
let mode = if mode.is_empty() { selection_mode(app, egui::Modifiers::NONE).to_owned() } else { mode };
- let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": app.ui.tool_options.anti_alias}));
+ let o = &app.ui.tool_options;
+ let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": o.anti_alias, "feather": o.feather}));
}
}
diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs
index 14f4790eb..4c880e291 100644
--- a/crates/ui-egui/src/canvas_tool_menu.rs
+++ b/crates/ui-egui/src/canvas_tool_menu.rs
@@ -67,7 +67,10 @@ pub const PEN_MENU: &[Option<(&str, &str)>] = &[
/// Tools whose plain canvas right-click offers selection actions.
pub fn applies(tool: Tool) -> bool {
- matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand | Tool::ObjectSelection | Tool::Pen)
+ matches!(
+ tool,
+ Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso | Tool::MagicWand | Tool::ObjectSelection | Tool::Pen
+ )
}
/// Command ids are shared with the Select menu. Disabled actions remain visible.
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 778681edd..a71f5ec42 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -606,6 +606,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
"window": {"width": screen.width(), "height": screen.height(), "pixelsPerPoint": ctx.pixels_per_point()},
"tool": app.ui.tool,
"toolOptions": app.ui.tool_options,
+ "magnetic": app.ui.magnetic,
"textEdit": app.ui.text_edit,
"layerMenu": app.ui.layer_menu,
"canvasToolMenu": app.ui.canvas_tool_menu.as_ref().map(|menu| {
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 0efa32ce6..377e7638f 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2089,3 +2089,6 @@ cameraRaw Color Barvy
Save failed: {error} Uložení se nezdařilo: {error}
Save cancelled Ukládání zrušeno
Couldn't place {name}: {error} Nelze umístit {name}: {error}
+ Magnetic Lasso Tool Nástroj magnetické laso
+ Frequency Frekvence
+ Use tablet pressure to change pen width Měnit šířku pera přítlakem tabletu
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 4ae9ba059..e4f87cda3 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2131,3 +2131,6 @@
Reset to Default Auf Standard zurücksetzen
Couldn't place {name}: {error} {name} konnte nicht platziert werden: {error}
Full-resolution preview unavailable Vorschau in voller Auflösung nicht verfügbar
+ Magnetic Lasso Tool Magnetisches-Lasso-Werkzeug
+ Frequency Frequenz
+ Use tablet pressure to change pen width Tablettdruck zum Ändern der Stiftbreite verwenden
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index ce91a49e6..49320f3a0 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2162,3 +2162,6 @@ cameraRaw Amount Cantidad
Don't show again No volver a mostrar
Save failed: {error} Error al guardar: {error}
Save cancelled Guardado cancelado
+ Magnetic Lasso Tool Herramienta Lazo magnético
+ Frequency Frecuencia
+ Use tablet pressure to change pen width Usar la presión de la tableta para cambiar la anchura del lápiz
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 0e10773ec..2aef15b10 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2522,3 +2522,6 @@ cameraRaw Blending Fusion
Save failed: {error} Échec de l'enregistrement : {error}
Save cancelled Enregistrement annulé
Couldn't place {name}: {error} Impossible d'importer {name} : {error}
+ Magnetic Lasso Tool Outil Lasso magnétique
+ Frequency Fréquence
+ Use tablet pressure to change pen width Utiliser la pression de la tablette pour modifier la largeur de la plume
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 882861084..9c1fbcd8f 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2509,3 +2509,6 @@ cameraRaw Blending Pembauran
Save failed: {error} Gagal menyimpan: {error}
Save cancelled Penyimpanan dibatalkan
Couldn't place {name}: {error} Tidak dapat menempatkan {name}: {error}
+ Magnetic Lasso Tool Alat Magnetic Lasso
+ Frequency Frekuensi
+ Use tablet pressure to change pen width Gunakan tekanan tablet untuk mengubah lebar pena
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 2e5d2773c..910ab4964 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2164,3 +2164,6 @@ cameraRaw Amount Quantità
Reset to Default Ripristina predefinito
Couldn't place {name}: {error} Impossibile inserire {name}: {error}
Full-resolution preview unavailable Anteprima a piena risoluzione non disponibile
+ Magnetic Lasso Tool Strumento Lazo magnetico
+ Frequency Frequenza
+ Use tablet pressure to change pen width Usa pressione tavoletta per cambiare la larghezza della penna
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index bd1e1ee37..668e9738d 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -2073,3 +2073,6 @@ cameraRaw Color カラー
Don't show again 次回から表示しない
Save failed: {error} 保存に失敗しました: {error}
Save cancelled 保存をキャンセルしました
+ Magnetic Lasso Tool マグネット選択ツール
+ Frequency 頻度
+ Use tablet pressure to change pen width タブレットの筆圧を使用してペンの幅を変更
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index dee968020..abb323e02 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2675,3 +2675,6 @@ cameraRaw Color 색상
Save failed: {error} 저장 실패: {error}
Save cancelled 저장이 취소되었습니다
Couldn't place {name}: {error} {name}을(를) 가져올 수 없습니다: {error}
+ Magnetic Lasso Tool 자석 올가미 도구
+ Frequency 빈도
+ Use tablet pressure to change pen width 태블릿 압력을 사용하여 펜 폭 변경
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index d1ba290da..37f02cc9c 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2530,3 +2530,6 @@ cameraRaw Whites Brancos
Reset to Default Restaurar padrão
Couldn't place {name}: {error} Não foi possível inserir {name}: {error}
Full-resolution preview unavailable Pré-visualização em resolução total indisponível
+ Magnetic Lasso Tool Ferramenta Laço magnético
+ Frequency Frequência
+ Use tablet pressure to change pen width Usar a pressão da mesa digitalizadora para alterar a largura da caneta
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 026285dc7..e375296b8 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2365,3 +2365,6 @@ cameraRaw Roughness Неровность
Save failed: {error} Не удалось сохранить: {error}
Save cancelled Сохранение отменено
Couldn't place {name}: {error} Не удалось поместить {name}: {error}
+ Magnetic Lasso Tool Магнитное лассо
+ Frequency Частота
+ Use tablet pressure to change pen width Использовать нажим планшета для изменения ширины пера
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index cb0d48027..33ba9a013 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2098,3 +2098,6 @@ cameraRaw Blending 混合
Don't show again 不再显示
Save failed: {error} 存储失败:{error}
Save cancelled 已取消存储
+ Magnetic Lasso Tool 磁性套索工具
+ Frequency 频率
+ Use tablet pressure to change pen width 使用绘图板压力以更改钢笔宽度
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index ed3bc4edc..d1e00e367 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2067,3 +2067,6 @@ cameraRaw Blending 混合
Don't show again 不再顯示
Save failed: {error} 儲存失敗:{error}
Save cancelled 已取消儲存
+ Magnetic Lasso Tool 磁性套索工具
+ Frequency 頻率
+ Use tablet pressure to change pen width 使用繪圖板壓力以變更鋼筆寬度
diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs
index b2bbd0915..9d7f2d12d 100644
--- a/crates/ui-egui/src/icon_data.rs
+++ b/crates/ui-egui/src/icon_data.rs
@@ -50,6 +50,7 @@ pub static ICONS: &[(&str, &[u8])] = &[
("image", include_bytes!("../../../assets/icons/image.svg")),
("info", include_bytes!("../../../assets/icons/info.svg")),
("lasso", include_bytes!("../../../assets/icons/lasso.svg")),
+ ("lasso-magnetic", include_bytes!("../../../assets/icons/lasso-magnetic.svg")),
("lasso-select", include_bytes!("../../../assets/icons/lasso-select.svg")),
("layers", include_bytes!("../../../assets/icons/layers.svg")),
("link", include_bytes!("../../../assets/icons/link.svg")),
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index dbb58cdd1..520a855f6 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -74,6 +74,7 @@ pub fn tool_icon(t: Tool) -> &'static str {
Tool::Count => "circle-dot",
Tool::Lasso => "lasso",
Tool::PolygonLasso => "pentagon",
+ Tool::MagneticLasso => "lasso-magnetic",
Tool::MagicWand => "wand-sparkles",
Tool::Crop => "crop",
Tool::Slice => "slice-knife",
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 59a41dff4..db06f352e 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -73,6 +73,7 @@ pub mod layer_style;
pub mod layer_tree_ui;
pub mod links;
pub mod liquify_ui;
+pub mod magnetic_lasso_ui;
pub mod mask_thumbs_ui;
pub mod menu_catalog;
pub mod menu_nav;
@@ -300,6 +301,8 @@ pub struct PhotocraftApp {
pub(crate) move_preview: Option<move_ui::MovePreview>,
/// Patch Tool drag: the healed document at the pointer (`patch_preview`).
pub(crate) patch_preview: Option<patch_preview::PatchPreview>,
+ /// The pixels a Magnetic Lasso border follows (`magnetic_lasso_ui`).
+ pub(crate) magnetic: magnetic_lasso_ui::Runtime,
/// The next tool `Down` is a right-button drag that erases (see `paint_mouse`).
secondary_erase: bool,
/// While a batch of recovered pointer samples is replayed, defer the live-stroke update to one
@@ -452,6 +455,7 @@ impl PhotocraftApp {
trail: None,
move_preview: None,
patch_preview: None,
+ magnetic: Default::default(),
secondary_erase: false,
defer_live_stroke: false,
last_stroke_end: None,
diff --git a/crates/ui-egui/src/magnetic_lasso_ui.rs b/crates/ui-egui/src/magnetic_lasso_ui.rs
new file mode 100644
index 000000000..6da047808
--- /dev/null
+++ b/crates/ui-egui/src/magnetic_lasso_ui.rs
@@ -0,0 +1,450 @@
+//! Magnetic Lasso Tool (L): a selection border that snaps to edges as the pointer moves.
+//!
+//! Click to set the first fastening point, then move the pointer along an edge (with the button up
+//! or held down): the border from the last fastening point to the pointer follows the most
+//! prominent edges within the detection width, and points fasten by themselves as it goes, more
+//! often at a higher Frequency. A click fastens a point; ⌥-click draws a straight segment and
+//! ⌥-drag a freehand one. ⌫ or Delete removes the last fastening point. Clicking the first point,
+//! a double-click or ↩ closes the border along the edges (⌥ with a straight segment); Esc cancels.
+//! [ and ] narrow or widen the detection width by 1 px. As in Photoshop, the border follows the
+//! active layer's pixels (the composite for a layer without pixels of its own).
+//!
+//! The border closes through `select.magneticLasso` with `"trace": false`: the selection is exactly
+//! the outline drawn, in one history step, and an action replays that outline.
+
+use egui::{Color32, Key, Modifiers, Pos2, Rect, Stroke, vec2};
+use photocraft_algo::magnetic::{self, Settings};
+use photocraft_engine::magnetic_cmds::EdgeSource;
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, ViewXform};
+use crate::state::Tool;
+
+/// A border being drawn (document px).
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct MagneticLasso {
+ /// The fastened border so far, from the first fastening point to the last.
+ pub path: Vec<[f64; 2]>,
+ /// Indices into `path` of the fastening points (the first is 0).
+ pub anchors: Vec<usize>,
+ /// The live segment from the last fastening point to the edge near the pointer.
+ pub live: Vec<[f64; 2]>,
+ /// Where the pointer has been since the last fastening point: edges are looked for near it.
+ pub trail: Vec<[f64; 2]>,
+ /// The selection mode the first click set (`replace`, `add`, `subtract`, `intersect`).
+ pub mode: String,
+ /// The document the border is drawn on.
+ pub doc: u64,
+ /// An ⌥-drag is drawing a freehand segment.
+ pub freehand: bool,
+}
+
+impl MagneticLasso {
+ /// A border is being drawn.
+ pub fn active(&self) -> bool {
+ !self.path.is_empty()
+ }
+}
+
+/// The pixels being traced: a snapshot of the document, kept while a border is drawn.
+#[derive(Default)]
+pub struct Runtime {
+ source: Option<EdgeSource>,
+ /// Pointer moves were batched (`PhotocraftApp::defer_live_stroke`): trace once at the end.
+ pending: bool,
+}
+
+/// Detection settings from the options bar, for an event with pen `pressure`.
+fn settings(app: &PhotocraftApp, pressure: f32) -> Settings {
+ let o = &app.ui.tool_options;
+ let mut width = f64::from(o.magnetic_width);
+ // Stylus Pressure: pressing harder narrows the width (a pen only; a mouse has no pressure).
+ if o.magnetic_pressure && app.stylus.sample().is_some() && pressure.is_finite() {
+ width = 1.0 + (width - 1.0) * f64::from(1.0 - pressure.clamp(0.0, 1.0));
+ }
+ Settings::new(width, o.magnetic_contrast / 100.0)
+}
+
+/// How far the border runs before a point fastens by itself (document px): 8 screen points at
+/// Frequency 100, 98 at 0, 47 at the default 57.
+fn spacing(app: &PhotocraftApp) -> f64 {
+ let f = app.ui.tool_options.magnetic_frequency;
+ let f = if f.is_finite() { f64::from(f.clamp(0.0, 100.0)) } else { 57.0 };
+ (8.0 + (100.0 - f) * 0.9) / f64::from(app.current_zoom().max(0.01))
+}
+
+/// Within this distance of the first point (document px), a click closes the border.
+fn close_radius(app: &PhotocraftApp) -> f64 {
+ 8.0 / f64::from(app.current_zoom().max(0.01))
+}
+
+fn dist(a: [f64; 2], b: [f64; 2]) -> f64 {
+ (a[0] - b[0]).hypot(a[1] - b[1])
+}
+
+/// The edge source for the active document, refreshed when the document or layer changed.
+fn source(app: &mut PhotocraftApp) -> Option<&mut EdgeSource> {
+ if !app.magnetic.source.as_ref().is_some_and(|s| s.is_current(&app.session)) {
+ app.magnetic.source = EdgeSource::new(&app.session);
+ }
+ app.magnetic.source.as_mut()
+}
+
+fn snap(app: &mut PhotocraftApp, p: [f64; 2], s: Settings) -> [f64; 2] {
+ source(app).and_then(|src| src.snap(p, s)).unwrap_or(p)
+}
+
+fn trace(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], guide: &[[f64; 2]], s: Settings) -> Vec<[f64; 2]> {
+ let t = source(app).map(|src| src.trace(from, to, guide, s)).unwrap_or_default();
+ if t.is_empty() { vec![from, to] } else { t }
+}
+
+/// Pointer events while the Magnetic Lasso is the tool (it takes them all).
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool {
+ if app.ui.tool != Tool::MagneticLasso {
+ return false;
+ }
+ match ev {
+ ToolEvent::Down { x, y, pressure } if x.is_finite() && y.is_finite() => down(app, [x, y], pressure, mods),
+ ToolEvent::Move { x, y, pressure } if x.is_finite() && y.is_finite() => moved(app, [x, y], pressure),
+ ToolEvent::Up { .. } => end_freehand(app),
+ _ => {}
+ }
+ true
+}
+
+fn down(app: &mut PhotocraftApp, p: [f64; 2], pressure: f32, mods: Modifiers) {
+ let s = settings(app, pressure);
+ if !app.ui.magnetic.active() {
+ // The first fastening point; the modifiers held now set the selection mode.
+ let mode = crate::canvas::selection_mode(app, mods).to_owned();
+ app.magnetic = Runtime::default();
+ let start = snap(app, p, s);
+ let doc = app.session.active().map_or(0, |d| d.doc.id.0);
+ app.ui.magnetic = MagneticLasso { path: vec![start], anchors: vec![0], trail: vec![p], mode, doc, ..Default::default() };
+ return;
+ }
+ if near_start(app, p) {
+ // On the first point: the border closes there.
+ let m = &app.ui.magnetic;
+ let (Some(&first), Some(&last)) = (m.path.first(), m.path.last()) else { return };
+ let closing = if mods.alt {
+ vec![last, first]
+ } else {
+ let guide = app.ui.magnetic.trail.clone();
+ trace(app, last, first, &guide, s)
+ };
+ let m = &mut app.ui.magnetic;
+ m.path.extend(closing.into_iter().skip(1));
+ m.live.clear();
+ commit(app);
+ return;
+ }
+ if mods.alt {
+ // ⌥-click: a straight segment to here; dragging on draws freehand.
+ let m = &mut app.ui.magnetic;
+ if m.path.last().is_none_or(|q| dist(*q, p) > 1e-9) {
+ m.path.push(p);
+ m.anchors.push(m.path.len() - 1);
+ }
+ m.live.clear();
+ m.trail = vec![p];
+ m.freehand = true;
+ return;
+ }
+ // A click fastens a point at the edge near the pointer.
+ follow(app, p, s, false);
+ fasten_live(app);
+}
+
+fn moved(app: &mut PhotocraftApp, p: [f64; 2], pressure: f32) {
+ if !app.ui.magnetic.active() {
+ return;
+ }
+ if app.ui.magnetic.freehand {
+ // ⌥-drag: the pointer's path is the border.
+ let m = &mut app.ui.magnetic;
+ if m.path.last().is_none_or(|q| dist(*q, p) >= 0.5) {
+ m.path.push(p);
+ }
+ m.trail = vec![p];
+ return;
+ }
+ let s = settings(app, pressure);
+ let step = (spacing(app) / 2.0).max(1.0);
+ let last = app.ui.magnetic.trail.last().copied().unwrap_or(p);
+ // A long jump (a fast flick, automation) is walked in steps, so points keep fastening along it.
+ let n = ((dist(last, p) / step).ceil() as usize).clamp(1, 256);
+ for k in 1..=n {
+ let t = k as f64 / n as f64;
+ let q = [last[0] + (p[0] - last[0]) * t, last[1] + (p[1] - last[1]) * t];
+ if k < n || !app.defer_live_stroke {
+ follow(app, q, s, true);
+ } else {
+ // Batched moves (one frame's worth): note the pointer, trace once in `flush`.
+ extend_trail(app, q, s);
+ app.magnetic.pending = true;
+ }
+ }
+}
+
+/// Trace to the pointer once after a batch of pointer moves.
+pub fn flush(app: &mut PhotocraftApp) {
+ if std::mem::take(&mut app.magnetic.pending)
+ && let Some(&p) = app.ui.magnetic.trail.last()
+ {
+ let s = settings(app, app.stylus.pressure());
+ follow(app, p, s, true);
+ }
+}
+
+/// Add the pointer position `q` to the trail, keeping its points a few pixels apart.
+fn extend_trail(app: &mut PhotocraftApp, q: [f64; 2], s: Settings) {
+ let gap = (s.width / 4.0).clamp(1.0, 8.0);
+ let t = &mut app.ui.magnetic.trail;
+ match t.len() {
+ n if n >= 2 && dist(t[n - 2], q) < gap => t[n - 1] = q,
+ _ => t.push(q),
+ }
+}
+
+/// The pointer is at `q`: trace the live segment to the edge near it and, with `fasten`, fasten
+/// points behind the pointer while the live segment is long enough.
+fn follow(app: &mut PhotocraftApp, q: [f64; 2], s: Settings, fasten: bool) {
+ extend_trail(app, q, s);
+ let target = snap(app, q, s);
+ let every = spacing(app);
+ for _ in 0..64 {
+ let Some(&from) = app.ui.magnetic.path.last() else { return };
+ let guide = app.ui.magnetic.trail.clone();
+ let live = trace(app, from, target, &guide, s);
+ // The part of the border `spacing` behind its start no longer changes as the pointer
+ // moves: fasten it.
+ match cut(&live, every).filter(|_| fasten) {
+ Some((head, point)) => {
+ let m = &mut app.ui.magnetic;
+ m.path.extend(head.into_iter().skip(1));
+ m.anchors.push(m.path.len() - 1);
+ // Edges are looked for along the pointer's path from where it passed the new point.
+ let near = m.trail.iter().enumerate().min_by(|a, b| dist(*a.1, point).total_cmp(&dist(*b.1, point))).map_or(0, |(i, _)| i);
+ let rest: Vec<[f64; 2]> = m.trail.iter().skip(near + 1).copied().collect();
+ m.trail = std::iter::once(point).chain(rest).collect();
+ }
+ None => {
+ app.ui.magnetic.live = live;
+ return;
+ }
+ }
+ }
+}
+
+/// The polyline `p` up to `len` along it (ending at that point) and the point, when more than a
+/// pixel of it lies beyond.
+fn cut(p: &[[f64; 2]], len: f64) -> Option<(Vec<[f64; 2]>, [f64; 2])> {
+ if magnetic::length(p) < len + 1.0 {
+ return None;
+ }
+ let mut head = Vec::new();
+ let mut acc = 0.0;
+ for w in p.windows(2) {
+ let (a, b) = (w[0], w[1]);
+ head.push(a);
+ let d = dist(a, b);
+ if acc + d >= len && d > 0.0 {
+ let t = (len - acc) / d;
+ let point = [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
+ head.push(point);
+ return Some((head, point));
+ }
+ acc += d;
+ }
+ None
+}
+
+/// Fasten the live segment: its end becomes a fastening point.
+fn fasten_live(app: &mut PhotocraftApp) {
+ let m = &mut app.ui.magnetic;
+ let live = std::mem::take(&mut m.live);
+ let before = m.path.len();
+ for q in live.into_iter().skip(1) {
+ if m.path.last().is_none_or(|l| dist(*l, q) > 1e-9) {
+ m.path.push(q);
+ }
+ }
+ if m.path.len() > before {
+ m.anchors.push(m.path.len() - 1);
+ }
+ if let Some(&end) = m.path.last() {
+ m.trail = vec![end];
+ }
+}
+
+/// An ⌥-drag ends: where it stopped is a fastening point.
+fn end_freehand(app: &mut PhotocraftApp) {
+ let m = &mut app.ui.magnetic;
+ if std::mem::take(&mut m.freehand) && m.anchors.last().is_some_and(|&a| a + 1 < m.path.len()) {
+ m.anchors.push(m.path.len() - 1);
+ }
+}
+
+/// `p` is over the first point of a border long enough to close.
+fn near_start(app: &PhotocraftApp, p: [f64; 2]) -> bool {
+ let m = &app.ui.magnetic;
+ let r = close_radius(app);
+ m.path.first().is_some_and(|&first| dist(first, p) <= r) && magnetic::length(&m.path) + magnetic::length(&m.live) > 2.0 * r
+}
+
+/// Close the border and select it: the live segment fastens, then the last point joins the first
+/// along the edges, or with a straight segment with `straight`.
+pub fn close(app: &mut PhotocraftApp, straight: bool) {
+ if !app.ui.magnetic.active() {
+ return;
+ }
+ end_freehand(app);
+ fasten_live(app);
+ let m = &app.ui.magnetic;
+ let (Some(&first), Some(&last)) = (m.path.first(), m.path.last()) else { return };
+ if !straight {
+ let s = settings(app, 0.0);
+ let mut closing = trace(app, last, first, &[], s);
+ // The border ends where it starts.
+ closing.pop();
+ app.ui.magnetic.path.extend(closing.into_iter().skip(1));
+ }
+ commit(app);
+}
+
+/// Select the border as drawn (in the mode the first click set) and finish.
+fn commit(app: &mut PhotocraftApp) {
+ let m = std::mem::take(&mut app.ui.magnetic);
+ app.magnetic = Runtime::default();
+ if m.path.len() < 3 {
+ return;
+ }
+ let o = &app.ui.tool_options;
+ let mode = if m.mode.is_empty() { "replace".to_owned() } else { m.mode };
+ let p = json!({"points": m.path, "trace": false, "mode": mode, "antiAlias": o.anti_alias, "feather": o.feather});
+ let _ = app.run("select.magneticLasso", p);
+}
+
+/// Esc: drop the border.
+pub fn cancel(app: &mut PhotocraftApp) {
+ app.ui.magnetic = MagneticLasso::default();
+ app.magnetic = Runtime::default();
+}
+
+/// ⌫ / Delete: remove the last fastening point and the border back to the one before it; with only
+/// the first point left, cancel.
+pub fn remove_last_point(app: &mut PhotocraftApp) {
+ end_freehand(app);
+ let m = &mut app.ui.magnetic;
+ if m.anchors.len() <= 1 {
+ cancel(app);
+ return;
+ }
+ m.anchors.pop();
+ let keep = m.anchors.last().map_or(1, |&a| a + 1);
+ m.path.truncate(keep);
+ m.live.clear();
+ let pointer = m.trail.last().copied();
+ m.trail = m.path.last().copied().into_iter().collect();
+ // The live segment runs from the earlier point to the pointer again; it fastens only when the
+ // pointer moves on, so ⌫ can keep removing points.
+ if let Some(p) = pointer {
+ let s = settings(app, app.stylus.pressure());
+ follow(app, p, s, false);
+ }
+}
+
+/// A new-selection border is being drawn, so the selection it will replace is hidden.
+pub fn replaces_selection(app: &PhotocraftApp) -> bool {
+ app.ui.magnetic.active() && app.ui.magnetic.mode == "replace"
+}
+
+/// Once a frame: a border left behind by a tool or document switch is dropped.
+pub fn frame(app: &mut PhotocraftApp) {
+ let m = &app.ui.magnetic;
+ if m.active() && (app.ui.tool != Tool::MagneticLasso || app.session.active().map(|d| d.doc.id.0) != Some(m.doc)) {
+ cancel(app);
+ }
+}
+
+/// Keys while the Magnetic Lasso is the tool: ↩ closes the border along the edges (⌥↩ straight),
+/// Esc cancels it, ⌫ / Delete remove the last fastening point, and [ / ] change the detection width
+/// by 1 px. Returns whether a key was taken.
+pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
+ if app.ui.tool != Tool::MagneticLasso {
+ return false;
+ }
+ let pressed = |m: Modifiers, k: Key| ctx.input_mut(|i| i.consume_key(m, k));
+ if app.ui.magnetic.active() {
+ if pressed(Modifiers::ALT, Key::Enter) {
+ close(app, true);
+ return true;
+ }
+ if pressed(Modifiers::NONE, Key::Enter) {
+ close(app, false);
+ return true;
+ }
+ if pressed(Modifiers::NONE, Key::Escape) {
+ cancel(app);
+ return true;
+ }
+ if pressed(Modifiers::NONE, Key::Backspace) || pressed(Modifiers::NONE, Key::Delete) {
+ remove_last_point(app);
+ return true;
+ }
+ }
+ let step = if pressed(Modifiers::NONE, Key::OpenBracket) {
+ -1.0
+ } else if pressed(Modifiers::NONE, Key::CloseBracket) {
+ 1.0
+ } else {
+ return false;
+ };
+ let w = &mut app.ui.tool_options.magnetic_width;
+ *w = if w.is_finite() { (w.round() + step).clamp(1.0, 256.0) } else { 10.0 };
+ true
+}
+
+/// The border being drawn, its fastening points, and the closing mark when the pointer is over the
+/// first point.
+pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: Option<Pos2>) {
+ let m = &app.ui.magnetic;
+ if !m.active() {
+ return;
+ }
+ let screen = |q: &[f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32);
+ let pts: Vec<Pos2> = m.path.iter().chain(m.live.iter().skip(1)).map(screen).collect();
+ crate::tool_feedback::draw_ants(painter, &pts, false);
+ for p in m.anchors.iter().filter_map(|&i| m.path.get(i)).map(screen) {
+ let r = Rect::from_center_size(p, vec2(5.0, 5.0));
+ painter.rect_filled(r, 0.0, Color32::WHITE);
+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::BLACK), egui::StrokeKind::Outside);
+ }
+ if let Some(h) = hover
+ && near_start(app, xf.to_doc(h))
+ {
+ // Photoshop's closing cursor: a small circle beside the pointer.
+ let c = h + vec2(12.0, 12.0);
+ painter.circle_stroke(c, 4.0, Stroke::new(3.0, Color32::from_black_alpha(200)));
+ painter.circle_stroke(c, 4.0, Stroke::new(1.2, Color32::WHITE));
+ }
+}
+
+/// The cursor over the canvas: a crosshair; Preferences › Cursors › Other Cursors › Precise also
+/// shows the detection width around it.
+pub fn cursor(app: &PhotocraftApp, painter: &egui::Painter, p: Pos2, zoom: f32) -> egui::CursorIcon {
+ if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise {
+ let r = (app.ui.tool_options.magnetic_width.clamp(1.0, 256.0) * zoom).max(2.0);
+ painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140)));
+ painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220)));
+ }
+ egui::CursorIcon::Crosshair
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/ui-egui/src/magnetic_lasso_ui/tests.rs b/crates/ui-egui/src/magnetic_lasso_ui/tests.rs
new file mode 100644
index 000000000..f1393a078
--- /dev/null
+++ b/crates/ui-egui/src/magnetic_lasso_ui/tests.rs
@@ -0,0 +1,390 @@
+//! The Magnetic Lasso through `tool_event` (mouse and `ui.pointer` alike), and through the real
+//! canvas for hover, keys and double-click.
+
+use egui::{Modifiers, PointerButton, Pos2, vec2};
+use egui_kittest::Harness;
+use photocraft_geom::Rect;
+use serde_json::json;
+
+use super::*;
+use crate::canvas::{ToolEvent, ViewXform, tool_event};
+
+const SQUARE: Rect = Rect::new(50, 40, 130, 110);
+
+/// A black 80×70 square on a white 200×150 document, the Magnetic Lasso, 100 % zoom.
+fn app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 150})).unwrap();
+ app.sync_views();
+ app.session
+ .edit("paint", |doc, _| {
+ let bg = doc.layers[0].surface_mut().unwrap();
+ bg.fill_rect(Rect::new(0, 0, 200, 150), &[1.0, 1.0, 1.0, 1.0]);
+ bg.fill_rect(SQUARE, &[0.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ app.ui.tool = Tool::MagneticLasso;
+ app
+}
+
+fn click(app: &mut PhotocraftApp, x: f64, y: f64, m: Modifiers) {
+ tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, m);
+ tool_event(app, ToolEvent::Up { x, y }, m);
+}
+
+/// The pointer moves (button up) along the polyline `pts` in 2 px steps, like a hand on a mouse.
+fn hover_along(app: &mut PhotocraftApp, pts: &[[f64; 2]]) {
+ for w in pts.windows(2) {
+ let n = (dist(w[0], w[1]) / 2.0).ceil().max(1.0) as usize;
+ for k in 1..=n {
+ let t = k as f64 / n as f64;
+ let (x, y) = (w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t);
+ tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, Modifiers::NONE);
+ }
+ }
+}
+
+/// Around the square, 3 px outside its edges, back to just past the start.
+const AROUND: [[f64; 2]; 6] = [[52.0, 37.0], [133.0, 37.0], [133.0, 113.0], [47.0, 113.0], [47.0, 37.0], [52.0, 37.0]];
+
+fn coverage(app: &PhotocraftApp, x: i32, y: i32) -> f32 {
+ app.session.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0))
+}
+
+fn selected_area(app: &PhotocraftApp) -> f32 {
+ (0..150).flat_map(|y| (0..200).map(move |x| (x, y))).map(|(x, y)| coverage(app, x, y)).sum()
+}
+
+fn last_step(app: &PhotocraftApp) -> Option<String> {
+ app.session.active().unwrap().history.entries().last().cloned()
+}
+
+/// Whether `p` lies on the square's outline (within `tol`).
+fn on_square(p: [f64; 2], tol: f64) -> bool {
+ let (x0, y0, x1, y1) = (f64::from(SQUARE.x0), f64::from(SQUARE.y0), f64::from(SQUARE.x1), f64::from(SQUARE.y1));
+ let inside = (x0 - tol..=x1 + tol).contains(&p[0]) && (y0 - tol..=y1 + tol).contains(&p[1]);
+ let near = (p[0] - x0).abs() <= tol || (p[0] - x1).abs() <= tol || (p[1] - y0).abs() <= tol || (p[1] - y1).abs() <= tol;
+ inside && near
+}
+
+#[test]
+fn tracing_around_a_shape_selects_it() {
+ let mut app = app();
+ click(&mut app, AROUND[0][0], AROUND[0][1], Modifiers::NONE);
+ let m = &app.ui.magnetic;
+ assert!(m.active() && m.anchors == vec![0] && m.mode == "replace", "{m:?}");
+ assert!(on_square(m.path[0], 0.01), "the first point snaps onto the edge: {:?}", m.path[0]);
+ hover_along(&mut app, &AROUND[..5]);
+ let m = &app.ui.magnetic;
+ // Points fastened by themselves on the way (about every 47 px at Frequency 57).
+ assert!(m.anchors.len() >= 5, "{:?}", m.anchors);
+ for p in m.path.iter().chain(&m.live) {
+ assert!(on_square(*p, 1.0), "{p:?} is off the square's edge");
+ }
+ // No selection until the border closes, and nothing in the history.
+ assert_eq!(last_step(&app).as_deref(), Some("paint"));
+ // Back at the first point, a click closes the border along the edges.
+ hover_along(&mut app, &AROUND[4..]);
+ click(&mut app, AROUND[5][0], AROUND[5][1], Modifiers::NONE);
+ assert!(!app.ui.magnetic.active());
+ let area = selected_area(&app);
+ assert!((area - 5600.0).abs() < 120.0, "the square's 80 × 70: {area}");
+ assert_eq!((coverage(&app, 90, 75), coverage(&app, 47, 75), coverage(&app, 90, 113)), (1.0, 0.0, 0.0));
+ assert_eq!(last_step(&app).as_deref(), Some("Magnetic Lasso"));
+}
+
+#[test]
+fn enter_closes_along_the_edges_and_alt_closes_straight() {
+ let mut app = app();
+ // Over the top and right edges only; the rest closes along the edges from the last point.
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ hover_along(&mut app, &[[52.0, 37.0], [133.0, 37.0], [133.0, 108.0]]);
+ close(&mut app, false);
+ let magnetic = selected_area(&app);
+ assert!(magnetic > 2000.0, "{magnetic}");
+ // Straight: the closing segment is the diagonal from the last point to the first.
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ hover_along(&mut app, &[[52.0, 37.0], [133.0, 37.0], [133.0, 108.0]]);
+ close(&mut app, true);
+ let straight = selected_area(&app);
+ assert!((straight - 2700.0).abs() < 300.0, "half the square: {straight}");
+}
+
+#[test]
+fn backspace_removes_fastening_points_back_to_the_first() {
+ let mut app = app();
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ hover_along(&mut app, &[[52.0, 37.0], [133.0, 37.0], [133.0, 70.0]]);
+ let n = app.ui.magnetic.anchors.len();
+ assert!(n >= 3, "{n}");
+ remove_last_point(&mut app);
+ let m = &app.ui.magnetic;
+ assert_eq!(m.anchors.len(), n - 1);
+ assert_eq!(m.path.len(), m.anchors[n - 2] + 1, "the border ends at the point before");
+ assert!(!m.live.is_empty(), "the live segment runs on to the pointer");
+ // Without moving, ⌫ keeps removing (nothing re-fastens) down to the first point, then cancels.
+ for _ in 0..n - 2 {
+ remove_last_point(&mut app);
+ }
+ assert_eq!(app.ui.magnetic.anchors, vec![0]);
+ remove_last_point(&mut app);
+ assert!(!app.ui.magnetic.active());
+ assert!(app.session.active().unwrap().doc.selection.is_none());
+}
+
+#[test]
+fn clicks_fasten_and_alt_draws_straight_and_freehand_segments() {
+ let mut app = app();
+ click(&mut app, 20.0, 20.0, Modifiers::NONE);
+ // A click on a flat area fastens right where it is.
+ hover_along(&mut app, &[[20.0, 20.0], [30.0, 20.0]]);
+ click(&mut app, 30.0, 20.0, Modifiers::NONE);
+ assert_eq!(app.ui.magnetic.path.last(), Some(&[30.0, 20.0]));
+ let anchors = app.ui.magnetic.anchors.len();
+ // ⌥-click: straight to the point, wherever the edges are.
+ click(&mut app, 180.0, 140.0, Modifiers::ALT);
+ let m = &app.ui.magnetic;
+ assert_eq!((m.path.last(), m.anchors.len(), m.freehand), (Some(&[180.0, 140.0]), anchors + 1, false));
+ let before = m.path.len();
+ assert_eq!(m.path[before - 2], [30.0, 20.0], "one straight segment");
+ // ⌥-drag: the pointer's path is the border.
+ tool_event(&mut app, ToolEvent::Down { x: 180.0, y: 140.0, pressure: 1.0 }, Modifiers::ALT);
+ for (x, y) in [(170.0, 142.0), (160.0, 138.0), (150.0, 141.0)] {
+ tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, Modifiers::ALT);
+ }
+ tool_event(&mut app, ToolEvent::Up { x: 150.0, y: 141.0 }, Modifiers::ALT);
+ let m = &app.ui.magnetic;
+ assert_eq!(&m.path[before..], &[[170.0, 142.0], [160.0, 138.0], [150.0, 141.0]]);
+ assert_eq!(m.anchors.last(), Some(&(m.path.len() - 1)));
+ assert!(!m.freehand);
+ // ⌫ takes the freehand segment back in one step.
+ remove_last_point(&mut app);
+ assert_eq!(app.ui.magnetic.path.last(), Some(&[180.0, 140.0]));
+}
+
+#[test]
+fn the_first_click_sets_the_mode_and_hides_a_replaced_selection() {
+ let mut app = app();
+ app.run("select.rect", json!({"x": 150, "y": 10, "width": 30, "height": 30})).unwrap();
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ assert!(crate::canvas::polygon_replaces_selection(&app));
+ cancel(&mut app);
+ assert!(!crate::canvas::polygon_replaces_selection(&app));
+ // ⇧ at the first click adds; later the modifier keys draw segments, not modes.
+ click(&mut app, 52.0, 37.0, Modifiers::SHIFT);
+ assert_eq!(app.ui.magnetic.mode, "add");
+ assert!(!crate::canvas::polygon_replaces_selection(&app));
+ hover_along(&mut app, &AROUND);
+ click(&mut app, AROUND[5][0], AROUND[5][1], Modifiers::NONE);
+ assert_eq!((coverage(&app, 160, 20), coverage(&app, 90, 75)), (1.0, 1.0), "added to the selection");
+}
+
+#[test]
+fn agents_see_the_border_in_progress() {
+ let mut app = app();
+ let ctx = egui::Context::default();
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ hover_along(&mut app, &[[52.0, 37.0], [133.0, 37.0]]);
+ let v = crate::control::inspect(&app, &ctx);
+ let m = &v["magnetic"];
+ assert_eq!(m["mode"], json!("replace"));
+ assert_eq!(m["anchors"].as_array().map(Vec::len), Some(app.ui.magnetic.anchors.len()));
+ assert!(m["path"].as_array().is_some_and(|p| p.len() >= 2), "{m}");
+ assert!(m["live"].as_array().is_some_and(|p| !p.is_empty()), "{m}");
+ assert_eq!(v["tool"], json!("MagneticLasso"));
+}
+
+#[test]
+fn switching_tools_or_documents_drops_the_border() {
+ let mut app = app();
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ frame(&mut app);
+ assert!(app.ui.magnetic.active());
+ app.ui.tool = Tool::Lasso;
+ frame(&mut app);
+ assert!(!app.ui.magnetic.active());
+ app.ui.tool = Tool::MagneticLasso;
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ app.run("file.new", json!({"width": 50, "height": 50})).unwrap();
+ app.sync_views();
+ frame(&mut app);
+ assert!(!app.ui.magnetic.active());
+}
+
+#[test]
+fn a_document_edit_while_drawing_is_traced_on() {
+ let mut app = app();
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ hover_along(&mut app, &[[52.0, 37.0], [90.0, 37.0]]);
+ // The square grows 10 px taller upwards mid-border: the border follows the new edge.
+ app.session
+ .edit("grow", |doc, _| {
+ doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(50, 30, 130, 40), &[0.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ hover_along(&mut app, &[[90.0, 37.0], [100.0, 27.0], [125.0, 27.0]]);
+ let live_end = app.ui.magnetic.live.last().copied().unwrap();
+ assert!((live_end[1] - 30.0).abs() < 0.01, "on the new edge: {live_end:?}");
+}
+
+#[test]
+fn width_follows_pen_pressure_only_when_asked_and_only_with_a_pen() {
+ let mut app = app();
+ app.ui.tool_options.magnetic_width = 21.0;
+ assert_eq!(settings(&app, 1.0).width, 21.0);
+ app.ui.tool_options.magnetic_pressure = true;
+ // A mouse has no pressure: the width stays.
+ assert_eq!(settings(&app, 1.0).width, 21.0);
+ app.stylus.use_pressure = true;
+ app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: 0.5, ..Default::default() }));
+ assert_eq!(settings(&app, 0.5).width, 11.0);
+ assert_eq!(settings(&app, 1.0).width, 1.0);
+ assert_eq!(settings(&app, f32::NAN).width, 21.0);
+}
+
+#[test]
+fn hostile_input_never_panics() {
+ let mut app = app();
+ for (x, y) in [(f64::NAN, 1.0), (1.0, f64::INFINITY)] {
+ click(&mut app, x, y, Modifiers::NONE);
+ assert!(!app.ui.magnetic.active());
+ }
+ // Far off the canvas: kept on it.
+ click(&mut app, -1e12, 1e300, Modifiers::NONE);
+ tool_event(&mut app, ToolEvent::Move { x: 1e12, y: -1e12, pressure: 1.0 }, Modifiers::NONE);
+ tool_event(&mut app, ToolEvent::Move { x: 10.0, y: 1e15, pressure: f32::NAN }, Modifiers::NONE);
+ let m = &app.ui.magnetic;
+ assert!(m.path.iter().chain(&m.live).all(|p| (0.0..=200.0).contains(&p[0]) && (0.0..=150.0).contains(&p[1])), "{m:?}");
+ close(&mut app, false);
+ // Out-of-range options are clamped.
+ for (w, c, f) in [(0.0, 0.0, -5.0), (1e9, 1e9, 1e9), (f32::NAN, f32::NAN, f32::NAN)] {
+ let o = &mut app.ui.tool_options;
+ (o.magnetic_width, o.magnetic_contrast, o.magnetic_frequency) = (w, c, f);
+ click(&mut app, 52.0, 37.0, Modifiers::NONE);
+ hover_along(&mut app, &[[52.0, 37.0], [90.0, 37.0], [90.0, 60.0]]);
+ close(&mut app, false);
+ }
+ // A border too short to select, closing, removing and cancelling with nothing drawn.
+ click(&mut app, 10.0, 10.0, Modifiers::NONE);
+ close(&mut app, false);
+ close(&mut app, true);
+ remove_last_point(&mut app);
+ cancel(&mut app);
+ // No document at all.
+ let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ empty.ui.tool = Tool::MagneticLasso;
+ click(&mut empty, 5.0, 5.0, Modifiers::NONE);
+ hover_along(&mut empty, &[[5.0, 5.0], [60.0, 5.0], [60.0, 60.0]]);
+ close(&mut empty, false);
+ assert!(!empty.ui.magnetic.active());
+}
+
+// ---------------------------------------------------------------------------- real canvas
+
+fn harness() -> Harness<'static, PhotocraftApp> {
+ let mut app = app();
+ app.ui.extras.rulers = false;
+ let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_step_dt(1.0 / 60.0).build_ui_state(
+ |ui, app: &mut PhotocraftApp| {
+ let ctx = ui.ctx().clone();
+ if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
+ return;
+ }
+ crate::shortcuts::handle(app, &ctx);
+ egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
+ },
+ app,
+ );
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ h.run_steps(4);
+ let v = &mut h.state_mut().ui.views[0];
+ v.zoom = 1.0;
+ v.center = [100.0, 75.0];
+ v.fit_pending = false;
+ h.run_steps(2);
+ h
+}
+
+fn screen(h: &Harness<'static, PhotocraftApp>, x: f64, y: f64) -> Pos2 {
+ let app = h.state();
+ let v = &app.ui.views[0];
+ let xf = ViewXform { rect: crate::rulers::content_rect(app, app.last_canvas_rect), zoom: v.zoom, center: v.center, flip: app.ui.view.flip_horizontal };
+ xf.to_screen(x as f32, y as f32)
+}
+
+fn ui_click(h: &mut Harness<'static, PhotocraftApp>, x: f64, y: f64) {
+ let p = screen(h, x, y);
+ h.event(egui::Event::PointerMoved(p));
+ h.run_steps(1);
+ for down in [true, false] {
+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE });
+ h.run_steps(1);
+ }
+}
+
+fn ui_hover(h: &mut Harness<'static, PhotocraftApp>, pts: &[[f64; 2]]) {
+ for w in pts.windows(2) {
+ let n = (dist(w[0], w[1]) / 3.0).ceil().max(1.0) as usize;
+ for k in 1..=n {
+ let t = k as f64 / n as f64;
+ let p = screen(h, w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t);
+ h.event(egui::Event::PointerMoved(p));
+ h.run_steps(1);
+ }
+ }
+}
+
+#[test]
+fn on_the_canvas_the_border_follows_the_hovering_pointer_and_keys_work() {
+ let mut h = harness();
+ ui_click(&mut h, 52.0, 37.0);
+ assert!(h.state().ui.magnetic.active());
+ // No button held: the live segment follows the pointer along the edge.
+ ui_hover(&mut h, &[[52.0, 37.0], [100.0, 36.0]]);
+ let m = &h.state().ui.magnetic;
+ let end = m.live.last().or(m.path.last()).copied().unwrap();
+ assert!((end[0] - 100.0).abs() < 1.5 && (end[1] - 40.0).abs() < 0.01, "{end:?}");
+ // [ and ] change the width; ⌫ removes a point and never clears pixels (Edit › Clear).
+ h.key_press(egui::Key::CloseBracket);
+ h.run_steps(1);
+ assert_eq!(h.state().ui.tool_options.magnetic_width, 11.0);
+ h.key_press(egui::Key::OpenBracket);
+ h.key_press(egui::Key::OpenBracket);
+ h.run_steps(1);
+ assert_eq!(h.state().ui.tool_options.magnetic_width, 9.0);
+ let revision = h.state().session.active().unwrap().revision;
+ let anchors = h.state().ui.magnetic.anchors.len();
+ h.key_press(egui::Key::Backspace);
+ h.run_steps(1);
+ assert_eq!(h.state().ui.magnetic.anchors.len(), anchors - 1);
+ assert_eq!(h.state().session.active().unwrap().revision, revision);
+ // Esc cancels; ↩ closes.
+ h.key_press(egui::Key::Escape);
+ h.run_steps(1);
+ assert!(!h.state().ui.magnetic.active());
+ ui_click(&mut h, 52.0, 37.0);
+ h.run_steps(30);
+ ui_hover(&mut h, &AROUND[..4]);
+ h.key_press(egui::Key::Enter);
+ h.run_steps(2);
+ assert!(!h.state().ui.magnetic.active());
+ let area = selected_area(h.state());
+ assert!((area - 5600.0).abs() < 120.0, "{area}");
+}
+
+#[test]
+fn on_the_canvas_a_double_click_closes_the_border() {
+ let mut h = harness();
+ ui_click(&mut h, 52.0, 37.0);
+ h.run_steps(30);
+ ui_hover(&mut h, &AROUND[..4]);
+ ui_click(&mut h, 47.0, 113.0);
+ ui_click(&mut h, 47.0, 113.0);
+ h.run_steps(2);
+ assert!(!h.state().ui.magnetic.active(), "{:?}", h.state().ui.magnetic);
+ let area = selected_area(h.state());
+ assert!((area - 5600.0).abs() < 120.0, "{area}");
+ assert_eq!(last_step(h.state()).as_deref(), Some("Magnetic Lasso"));
+}
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 19c960b1e..a1ab3bb07 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -18,7 +18,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[
&[&[Tool::Move]],
&[
&[Tool::RectMarquee, Tool::EllipseMarquee],
- &[Tool::Lasso, Tool::PolygonLasso],
+ &[Tool::Lasso, Tool::PolygonLasso, Tool::MagneticLasso],
&[Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand],
&[Tool::Crop, Tool::Slice, Tool::SliceSelect],
&[Tool::Eyedropper, Tool::Ruler, Tool::Note, Tool::Count],
@@ -598,13 +598,29 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({}));
}
}
- Tool::Lasso | Tool::PolygonLasso if t.pro => {
+ Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso if t.pro => {
selection_mode_buttons(app, ui);
widgets::vline(ui, 22.0);
opt_label(ui, tl!("Feather"));
widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0);
widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias"));
widgets::vline(ui, 22.0);
+ if app.ui.tool == Tool::MagneticLasso {
+ let o = &mut app.ui.tool_options;
+ opt_label(ui, tl!("Width"));
+ widgets::value_field(ui, &mut o.magnetic_width, 1.0..=256.0, "px", 58.0)
+ .on_hover_text(tl!("Follows only edges this close to the pointer ([ and ] change it)"));
+ opt_label(ui, tl!("Contrast"));
+ widgets::value_field(ui, &mut o.magnetic_contrast, 1.0..=100.0, "%", 58.0)
+ .on_hover_text(tl!("Higher values follow only edges that contrast sharply with their surroundings"));
+ opt_label(ui, tl!("Frequency"));
+ widgets::value_field(ui, &mut o.magnetic_frequency, 0.0..=100.0, "", 50.0)
+ .on_hover_text(tl!("How often fastening points are placed by themselves"));
+ if icons::button(ui, "circle-dot", 24.0, o.magnetic_pressure, tl!("Use tablet pressure to change pen width")).clicked() {
+ o.magnetic_pressure = !o.magnetic_pressure;
+ }
+ widgets::vline(ui, 22.0);
+ }
if widgets::secondary_button(ui, tl!("Select and Mask…"), 0.0).clicked() {
let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({}));
}
@@ -619,6 +635,15 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
} else if app.ui.tool == Tool::Lasso {
hint(ui, tl!("Hold Alt while drawing for straight segments"));
}
+ if app.ui.tool == Tool::MagneticLasso && app.ui.magnetic.active() {
+ hint(
+ ui,
+ &crate::i18n::fmt(
+ tl!("Click the first point or press {key} to close · {del} removes a point · Esc cancels"),
+ &[("key", &crate::shortcuts::pretty("Enter")), ("del", &crate::shortcuts::pretty("Backspace"))],
+ ),
+ );
+ }
}
Tool::MagicWand => {
selection_mode_buttons(app, ui);
@@ -814,6 +839,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
&[("add", &crate::shortcuts::pretty("Shift")), ("sub", &crate::shortcuts::pretty("Alt"))],
),
),
+ Tool::MagneticLasso => hint(
+ ui,
+ &crate::i18n::fmt(
+ tl!("Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close"),
+ &[("alt", &crate::shortcuts::pretty("Alt"))],
+ ),
+ ),
Tool::Crop => hint(
ui,
&crate::i18n::fmt(
diff --git a/crates/ui-egui/src/polygon_lasso_tests.rs b/crates/ui-egui/src/polygon_lasso_tests.rs
index 7a44ec73d..31b779c89 100644
--- a/crates/ui-egui/src/polygon_lasso_tests.rs
+++ b/crates/ui-egui/src/polygon_lasso_tests.rs
@@ -206,3 +206,37 @@ fn a_new_polygon_without_a_selection_adds_one_step() {
triangle(&mut h, 20.0, 20.0, Modifiers::NONE);
assert_eq!(steps(&h), before + 1);
}
+
+/// The options bar's Feather softens the Lasso and Polygonal Lasso; the Patch Tool, which has no
+/// Feather, keeps a hard edge.
+#[test]
+fn lasso_tools_apply_the_options_bar_feather() {
+ use crate::canvas::{ToolEvent, tool_event};
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 150})).unwrap();
+ app.sync_views();
+ app.ui.tool_options.feather = 4.0;
+ let corners = [(40.0, 30.0), (160.0, 30.0), (160.0, 120.0), (40.0, 120.0)];
+ let coverage = |app: &PhotocraftApp, x: i32| app.session.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, 75, 0));
+ let drag = |app: &mut PhotocraftApp, tool: Tool| {
+ app.run("select.deselect", json!({})).ok();
+ app.ui.tool = tool;
+ tool_event(app, ToolEvent::Down { x: 40.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE);
+ for (x, y) in corners.iter().skip(1) {
+ tool_event(app, ToolEvent::Move { x: *x, y: *y, pressure: 1.0 }, Modifiers::NONE);
+ }
+ tool_event(app, ToolEvent::Up { x: 40.0, y: 120.0 }, Modifiers::NONE);
+ };
+ let soft = |app: &PhotocraftApp| coverage(app, 37) > 0.05 && coverage(app, 41) < 0.95;
+ drag(&mut app, Tool::Lasso);
+ assert!(soft(&app), "lasso: {} {}", coverage(&app, 37), coverage(&app, 41));
+ app.ui.tool = Tool::PolygonLasso;
+ for (x, y) in corners {
+ tool_event(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, Modifiers::NONE);
+ tool_event(&mut app, ToolEvent::Up { x, y }, Modifiers::NONE);
+ }
+ crate::canvas::commit_polygon(&mut app);
+ assert!(soft(&app), "polygonal: {} {}", coverage(&app, 37), coverage(&app, 41));
+ drag(&mut app, Tool::Patch);
+ assert_eq!((coverage(&app, 37), coverage(&app, 41)), (0.0, 1.0), "patch: a hard edge");
+}
diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs
index da3e69bf0..cbafd9df0 100644
--- a/crates/ui-egui/src/shortcuts.rs
+++ b/crates/ui-egui/src/shortcuts.rs
@@ -291,6 +291,11 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
return;
}
}
+ // Magnetic Lasso: ↩ closes, Esc cancels, ⌫ removes a fastening point (not Edit › Clear),
+ // [ ] change the detection width (not the brush size).
+ if crate::magnetic_lasso_ui::keys(app, ctx) {
+ return;
+ }
// Inline type editing eats text and navigation keys; ⌘-shortcuts still reach the menus.
let editing = crate::type_tool::handle_keys(app, ctx);
// Registry, UI and menu-catalogue shortcuts (see [`crate::shortcut_dispatch::bindings`]).
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 35b8efbb5..9d79f5c60 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -67,6 +67,7 @@ pub enum Tool {
EllipseMarquee,
Lasso,
PolygonLasso,
+ MagneticLasso,
MagicWand,
Crop,
Eyedropper,
@@ -112,12 +113,13 @@ pub enum Tool {
}
impl Tool {
- pub const ALL: [Tool; 47] = [
+ pub const ALL: [Tool; 48] = [
Tool::Move,
Tool::RectMarquee,
Tool::EllipseMarquee,
Tool::Lasso,
Tool::PolygonLasso,
+ Tool::MagneticLasso,
Tool::MagicWand,
Tool::Crop,
Tool::Eyedropper,
@@ -179,6 +181,7 @@ impl Tool {
Tool::Count => "Count Tool",
Tool::Lasso => "Lasso Tool",
Tool::PolygonLasso => "Polygonal Lasso Tool",
+ Tool::MagneticLasso => "Magnetic Lasso Tool",
Tool::MagicWand => "Magic Wand Tool",
Tool::Crop => "Crop Tool",
Tool::Slice => "Slice Tool",
@@ -246,7 +249,7 @@ impl Tool {
Tool::Brush | Tool::Pencil | Tool::MixerBrush => 'B',
Tool::Eraser | Tool::BackgroundEraser | Tool::MagicEraser => 'E',
Tool::Eyedropper | Tool::Ruler | Tool::Note | Tool::Count => 'I',
- Tool::Lasso | Tool::PolygonLasso => 'L',
+ Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => 'L',
Tool::MagicWand => 'W',
Tool::Crop | Tool::Slice | Tool::SliceSelect => 'C',
Tool::Gradient | Tool::PaintBucket => 'G',
@@ -274,7 +277,7 @@ impl Tool {
Tool::MixerBrush => "🖌",
Tool::Eraser => "⌫",
Tool::Eyedropper => "💧",
- Tool::Lasso | Tool::PolygonLasso => "L",
+ Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => "L",
Tool::MagicWand => "W",
Tool::Crop => "C",
Tool::Gradient | Tool::PaintBucket => "G",
@@ -475,6 +478,12 @@ pub struct ToolOptions {
/// Pencil › Auto Erase: a stroke that starts on the foreground colour paints the background colour.
#[serde(default)]
pub pencil_auto_erase: bool,
+ /// Magnetic Lasso: detection width (px, 1..256), edge contrast (%, 1..100), how often it
+ /// fastens points by itself (0..100), and whether pen pressure narrows the width.
+ pub magnetic_width: f32,
+ pub magnetic_contrast: f32,
+ pub magnetic_frequency: f32,
+ pub magnetic_pressure: bool,
}
fn yes() -> bool {
@@ -550,6 +559,10 @@ impl Default for ToolOptions {
bg_protect_fg: false,
zoom_scrubby: true,
pencil_auto_erase: false,
+ magnetic_width: 10.0,
+ magnetic_contrast: 10.0,
+ magnetic_frequency: 57.0,
+ magnetic_pressure: false,
}
}
}
@@ -795,6 +808,9 @@ pub struct UiState {
/// modifiers held at its first click.
#[serde(default)]
pub polygon_mode: String,
+ /// Magnetic Lasso border in progress (`magnetic_lasso_ui`).
+ #[serde(default)]
+ pub magnetic: crate::magnetic_lasso_ui::MagneticLasso,
/// Crop tool rectangle being edited [x0, y0, x1, y1] (document coordinates).
#[serde(default)]
pub crop_rect: Option<[f64; 4]>,
@@ -865,6 +881,7 @@ impl Default for UiState {
tool_options: ToolOptions::default(),
polygon: Vec::new(),
polygon_mode: String::new(),
+ magnetic: Default::default(),
crop_rect: None,
next_id: 1,
status: String::new(),
diff --git a/crates/ui-egui/src/tool_feedback.rs b/crates/ui-egui/src/tool_feedback.rs
index 58851b789..e1f3ed14f 100644
--- a/crates/ui-egui/src/tool_feedback.rs
+++ b/crates/ui-egui/src/tool_feedback.rs
@@ -33,7 +33,17 @@ impl Badge {
/// Tools whose cursor carries the selection-mode badge.
pub fn is_selection_tool(tool: Tool) -> bool {
- matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand | Tool::QuickSelection | Tool::ObjectSelection)
+ matches!(
+ tool,
+ Tool::RectMarquee
+ | Tool::EllipseMarquee
+ | Tool::Lasso
+ | Tool::PolygonLasso
+ | Tool::MagneticLasso
+ | Tool::MagicWand
+ | Tool::QuickSelection
+ | Tool::ObjectSelection
+ )
}
/// The effective selection mode of `tool` for the options-bar mode `bar` (0 New, 1 Add,
diff --git a/docs/context-menu-inventory.md b/docs/context-menu-inventory.md
index 2f5e68cc3..d91dad896 100644
--- a/docs/context-menu-inventory.md
+++ b/docs/context-menu-inventory.md
@@ -12,7 +12,7 @@ The shared rule is **Command/Ctrl + right-click** on opaque document pixels →
| Brush, Pencil, Eraser, Background Eraser | Brush Preset picker (size, hardness, presets) | Alt/Option + right-drag changes size/hardness via `tools.setBrush`; Brush/Eraser can right-drag erase via `tools.rightClickWithPaintingTools=erase` | Verify whether context should expose brush presets, settings, or tool-specific eraser controls. Keep erase preference and modifier priority deterministic. |
| Spot Healing, Healing, Clone Stamp, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge | Brush Preset picker | Alt/Option + right-drag changes size/hardness | Compare each tool's Photoshop picker and source/retouch options; use existing brush command route. |
| Quick Selection | Brush Preset picker | Alt/Option + right-drag changes size/hardness | Check selection-tool brush options and whether mode controls belong in picker. |
-| Rectangular/Elliptical Marquee, Lasso, Polygonal Lasso, Magic Wand, Object Selection | No plain secondary action at branch point; this PR adds selection context actions | Command/Ctrl opens layer list | Reuse Select command IDs with exact enablement; compare menu placement and order with a current Photoshop capture. |
+| Rectangular/Elliptical Marquee, Lasso, Polygonal Lasso, Magnetic Lasso, Magic Wand, Object Selection | No plain secondary action at branch point; this PR adds selection context actions | Command/Ctrl opens layer list | Reuse Select command IDs with exact enablement; compare menu placement and order with a current Photoshop capture. |
| Crop, Slice, Slice Select | No plain secondary action | Command/Ctrl opens layer list | Define crop/straighten commit and cancel, aspect/preset, slice selection/edit behavior separately. |
| Eyedropper, Ruler, Note, Count | No plain secondary action | Command/Ctrl opens layer list | Check tool-specific sampling, measurement, annotation, and count menus. |
| Gradient, Paint Bucket | No plain secondary action | Command/Ctrl opens layer list | Expose gradient preset and fill settings through commands if Photoshop's context UI provides them; avoid painting on right-click. |
diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md
index 91b5849d7..7ec4fa5c9 100644
--- a/docs/context-menu-parity.md
+++ b/docs/context-menu-parity.md
@@ -19,7 +19,7 @@ The “PhotoCraft at branch point” column records behavior before this PR. Pic
| Tool(s) in PhotoCraft | Photoshop / desired contextual action | PhotoCraft at branch point | Priority, evidence |
|---|---|---|---|
| Move | Choose a layer at the point; an auto-select choice also exists in the options bar | Layers | P0; [Adobe layer movement](https://helpx.adobe.com/photoshop/using/moving-stacking-locking-layers.html); exact pop-up layout requires capture |
-| Rectangular/Elliptical Marquee, Lasso, Polygonal Lasso, Magic Wand, Quick Selection, Object Selection | Active selection: Deselect, Inverse Selection, Feather, Transform Selection, Select and Mask, Fill/Stroke where applicable **(inferred context placement)** | Quick Selection: Picker; others: no tool menu. **This PR adds an initial selection menu for the other six tools; Quick Selection keeps its picker.** The Select menu exposes these same selection commands (Feather under Select > Modify, as in the reference menus). | P1; capture each selection state |
+| Rectangular/Elliptical Marquee, Lasso, Polygonal Lasso, Magnetic Lasso, Magic Wand, Quick Selection, Object Selection | Active selection: Deselect, Inverse Selection, Feather, Transform Selection, Select and Mask, Fill/Stroke where applicable **(inferred context placement)** | Quick Selection: Picker; others: no tool menu. **This PR adds an initial selection menu for the other six tools; Quick Selection keeps its picker.** The Select menu exposes these same selection commands (Feather under Select > Modify, as in the reference menus). | P1; capture each selection state |
| Crop | During crop: ratio/preset, overlay, clear/reset, commit/cancel **(inferred context placement)** | No tool menu | P1; pending crop target |
| Eyedropper | Sample-size/source choices **(inferred)** | No tool menu | P2; [Adobe illustration uses Eyedropper](https://helpx.adobe.com/photoshop/using/panels-menus.html), but does not publish item text |
| Ruler, Note, Count | Unit / measurement, note edit/delete, count-group operations **(inferred)** | No tool menu | P2 |
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 9b2289510..ed2d67782 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -45,6 +45,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing.
- `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows
- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven.
+ - Magnetic Lasso (`tool: "magneticLasso"`): a `down`/`up` pair is a click. The first sets the first fastening point (its modifiers set the selection mode); later clicks fasten a point, or close the border on the first point. `move` events trace the border with or without a button held, fastening points by themselves; with `alt: true` a click draws a straight segment and a drag a freehand one. `ui.inspect` shows the border in progress under `magnetic` (`path`, `anchors`, `live`, `mode`). `ui.key` Enter closes it along the edges, Backspace removes the last fastening point, Escape cancels. To select along edges in one call instead, use the `select.magneticLasso` command with rough points around the shape.
- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`
- `ui.type {text}`: type text (goes to the focused widget, or to the canvas while the Type tool is editing)
- `ui.resize {width, height}`: resize the main window
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 86c2d24e8..3a1c901a5 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -70,7 +70,7 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either
| Smart filters / text / effect shapes in PSDs | Measured on our Photoshop-authored set (https://github.com/storytold/photocraft-corpus, `corpus/photoshop`, 258 files): see the per-group floors in `crates/io/tests/corpus.rs` and `crates/engine/tests/photoshop_oracles.rs`. Smart objects and smart filters now survive PSD save and open (41 corpus files, 206 smart objects, round trip strict; Photoshop opens our exports with live filters); re-rendering Photoshop's smart filters with ours matches 5/30 (was 1/30) | low–medium | Remaining re-render gaps are filter maths (Gaussian/Motion Blur, Unsharp Mask, Emboss, Add Noise RNG) and bicubic placement. |
| Core editing (layers, masks, selections, adjustments, filters, transforms) | Broad engine coverage; many interaction bugs fixed after 0.2.0 (adjustment dialogs, Curves, crop, Move/Transform modifiers, gesture origin) | medium | Fixes not yet user-validated. |
| UI / UX polish | Shortcut audit 214 → 0 failures; dock, Layers rows and menus reworked; first visual-QA sweep found 14 defects (#147–#157). 2026-10-07: the keyboard-only shortcuts with no menu item (⌥[ ⌥] ⌥, ⌥. layer navigation, ⇧⌥[ ⇧⌥] to extend the selection, 1–0 for opacity and ⇧ for flow or fill, ⇧[ ⇧] hardness, ⌥⌘T to transform a copy and ⌥⇧⌘T to step and repeat), ⌥-click colour sampling with painting tools, double-click a Layers row for Layer Style, File › New from Clipboard, a centred main window and remembered Liquify settings (#352, #417, #350, #368, #419, #418) | low–medium | Needs recurring visual QA with realistic documents. |
-| Tools | ~20 Photoshop tools missing: Pencil, Mixer Brush (tool), Patch, Content-Aware Move, Red Eye, Pattern Stamp, Art History Brush, Freeform/Curvature Pen, anchor tools, Direct Selection, Magnetic Lasso, single row/column marquee, Color Sampler, Perspective Crop, Rotate View, the Vertical Type tool (vertical layout itself landed, #199: toggle via Type › Orientation) and type masks, Frame | low–medium | Magic/Background Eraser added; live gradients in progress (#180). |
+| Tools | ~20 Photoshop tools missing: Pencil, Mixer Brush (tool), Patch, Content-Aware Move, Red Eye, Pattern Stamp, Art History Brush, Freeform/Curvature Pen, anchor tools, Direct Selection, single row/column marquee, Color Sampler, Perspective Crop, Rotate View, the Vertical Type tool (vertical layout itself landed, #199: toggle via Type › Orientation) and type masks, Frame | low–medium | Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). |
| Painting | Brush model and Brush Settings panel near Photoshop; .abr/.grd import; persistent presets; pen pressure/tilt on Windows, web, macOS and X11 | medium | Wayland pen input open (#79); macOS/X11 pressure not yet verified on tablet hardware. |
| Text / typography | Engine works; caret placement and size editing fixed; OpenType features, text-on-path editing, composer parity partial | medium-low | Measure with the Photoshop-authored set. |
| Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. |