diff --git a/.github/workflows/kernel-paused.yml b/.github/workflows/kernel-paused.yml index cfa6d659b..be5de83cd 100644 --- a/.github/workflows/kernel-paused.yml +++ b/.github/workflows/kernel-paused.yml @@ -1,6 +1,7 @@ -# While a new geometry kernel is evaluated, new issues, pull requests and discussions about kernel -# work are labelled `kernel-paused` for a maintainer to answer (CONTRIBUTING.md, "Kernel work is -# paused"). The logic is in scripts/kernel-paused/ (tested in ci.yml). +# While a new geometry kernel is evaluated, new issues and discussions about kernel work, and new +# pull requests that change the kernel directories, are labelled `kernel-paused` for a maintainer to +# answer (CONTRIBUTING.md, "Kernel work is paused"). The logic is in scripts/kernel-paused/ (tested +# in ci.yml). name: Kernel paused on: diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 2e555f98c..06b992d85 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -647,6 +647,129 @@ Original SolidCraft drawings, Open for owner review; no runtime assignments. | assets/icons/ui/design/svg/model/print_face.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/locales/fi.json | SolidCraft contributors | Original Finnish translation of SolidCraft's English catalog, AI-assisted (Claude Code) clean-room from the English and not yet reviewed line by line by a native speaker; no commercial CAD text used | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/plane_axis_point.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-2x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-2x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-4x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-4x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-8x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-8x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-off.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-off.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/agent-pointer-speed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/agent-pointer-speed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/ao-on.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/ao-on.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/assembly-move.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/assembly-move.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-card.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-card.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-column.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-column.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-bends.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-bends.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-draft.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-draft.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-failed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-failed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-fixed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-fixed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-projected.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-projected.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/direct-interaction.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/direct-interaction.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/frame-rate.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/frame-rate.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-bottom.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-bottom.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-in-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-in-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-left.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-left.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-under-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-under-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/layout-schematic.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/layout-schematic.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/measure-axis-distances.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/measure-axis-distances.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/mouse-mapping.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/mouse-mapping.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-cube.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-cube.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-centre.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-centre.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-origin.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-origin.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-y-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-y-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-z-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-z-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/quick-measure.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/quick-measure.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-bodies.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-bodies.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-faces-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-faces-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-conflict.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-conflict.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-keep.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-keep.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-previous.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-previous.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-unless-turned.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-guides.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-guides.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-hide-glyphs.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-hide-glyphs.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-state-icons.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-state-icons.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/style-shaded-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/style-shaded-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-coarse.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-coarse.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-fine.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-fine.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-normal.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-normal.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-ultra.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-ultra.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-dark.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-dark.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-gruvbox.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-gruvbox.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-imported.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-imported.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-light.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-light.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-dark-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-dark-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-light-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-light-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-extrude.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-extrude.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-hole.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-hole.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-placement.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-placement.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/vertex-markers.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/vertex-markers.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-angles.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-angles.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-grid.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-grid.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-perspective.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-perspective.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-shadow.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-shadow.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| `assets/locales/pending/sketch-offset-instances.json` | SolidCraft contributors | Original offset instance-count label and translations | MIT OR Apache-2.0 | ## Code adapted from sibling projects diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7de036e48..ba20c817f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,12 +19,13 @@ Questions, ideas or want to say what you're working on? Join the [Discord](https ## Kernel work is paused -We're evaluating a new geometry kernel. Until that's decided, please don't open issues, pull -requests or discussions about kernel work: booleans, fillets, chamfers, shell, offsets, sweeps and -lofts, threads and holes, STEP/IGES import and export, tessellation, or anything else that changes -`crates/kernel/`. The pinned issue on the tracker explains it. New ones get the `kernel-paused` -label (`.github/workflows/kernel-paused.yml`) and a maintainer answers them. Crashes and data loss -are still taken as issues, and everything outside the kernel carries on as normal. +We're moving to a new geometry kernel. Until that's done, please don't open pull requests that +change `crates/kernel/`, `crates/geom/` or `vendor/truck*`, or issues and discussions about kernel +work: booleans, fillets, chamfers, shell, offsets, sweeps and lofts, threads and holes, STEP/IGES +import and export, or tessellation. The pinned issue on the tracker explains it. New ones get the +`kernel-paused` label (`.github/workflows/kernel-paused.yml`) and a maintainer answers them. Crashes +and data loss are still taken as issues. Pull requests outside those directories carry on as normal, +including the dialogs and tools for these features. ## Get it running (about 10 minutes on a fast machine) diff --git a/Cargo.lock b/Cargo.lock index 9a365007e..f6a66bada 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4204,6 +4204,7 @@ dependencies = [ "solidcraft-geom", "solidcraft-kernel", "solidcraft-profile", + "solidcraft-testkit", "thiserror 2.0.21", "zip", ] @@ -4230,6 +4231,7 @@ dependencies = [ name = "solidcraft-mcp" version = "0.29.0" dependencies = [ + "image", "serde_json", "solidcraft-engine", "solidcraft-gpu", @@ -4254,6 +4256,7 @@ dependencies = [ "serde_json", "sha2 0.10.9", "solidcraft-geom", + "web-time", "weezl", ] @@ -4298,6 +4301,10 @@ dependencies = [ "solidcraft-profile", ] +[[package]] +name = "solidcraft-testkit" +version = "0.29.0" + [[package]] name = "solidcraft-ui-egui" version = "0.29.0" diff --git a/Cargo.toml b/Cargo.toml index ae47952d3..8ffd7aaa5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,8 @@ solidcraft-space-mouse = { path = "crates/space-mouse" } solidcraft-mcp = { path = "crates/mcp" } solidcraft-derive = { path = "crates/derive" } solidcraft-3dx-client = { path = "crates/threedx-client" } +# test tooling: a dev-dependency only (xtask/src/layers.rs) +solidcraft-testkit = { path = "crates/testkit" } # foundation thiserror = "2" diff --git a/assets/locales/ar.json b/assets/locales/ar.json index a38f34e30..884af24ff 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -556,6 +556,7 @@ "Section": "مقطع", "Section (optional)": "المقطع (اختياري)", "Section position": "موضع المقطع", + "Sections": "المقاطع", "Sections (one sketch each)": "المقاطع (رسم واحد لكل منها)", "Select Other": "تحديد آخر", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "تحديد آخر: أبقِ الزر الأيسر ثابتًا على النموذج (أو انقر بالزر الأيمن › تحديد آخر…) لعرض كل ما تحت المؤشر؛ وانقر مرة أخرى في الموضع نفسه لتحديد العنصر التالي هناك. انقر نقرًا مزدوجًا بالزر الأوسط للانتقال إلى العرض الرئيسي (التفضيلات › التنقل).", @@ -936,6 +937,11 @@ "cmd.explode_show": "إظهار العرض المفكك", "cmd.expr_evaluate": "تقييم تعبير", "cmd.face_delete": "حذف وجه", + "cmd.file.export_3mf": "تصدير 3MF", + "cmd.file.export_obj": "تصدير OBJ", + "cmd.file.export_step": "تصدير STEP", + "cmd.file.export_stl": "تصدير STL", + "cmd.file.export_urdf": "تصدير URDF", "cmd.file_export": "تصدير", "cmd.file_insert_mesh": "إدراج شبكة", "cmd.file_insert_step": "إدراج STEP", @@ -953,6 +959,7 @@ "cmd.inspect_colored_components": "تفعيل ألوان المكوّنات", "cmd.inspect_colored_components_disable": "تعطيل ألوان المكوّنات", "cmd.inspect_compare": "مقارنة الأجسام", + "cmd.inspect_compare_picture": "مقارنة بصورة مرجعية", "cmd.inspect_continuity": "تحليل الاستمرارية", "cmd.inspect_curvature_comb": "تحليل مشط الانحناء", "cmd.inspect_curvature_map": "تحليل خريطة الانحناء", @@ -1043,6 +1050,9 @@ "cmd.pointcloud_edit": "تحرير سحابة النقاط", "cmd.pointcloud_insert": "إدراج سحابة نقاط", "cmd.pointcloud_list": "سحب النقاط", + "cmd.render.compare.divider": "تحريك فاصل مقارنة التصيير", + "cmd.render.result.discard": "تجاهل نتيجة التصيير", + "cmd.render.result.select": "تحديد نتيجة التصيير", "cmd.render_aging_describe": "تقادم السطح بالطبقات", "cmd.render_backends": "محركات التصيير", "cmd.render_batch": "تصيير كل اللقطات", @@ -1290,9 +1300,11 @@ "cmd.view_tool": "أداة التنقل", "cmd.view_top": "العرض العلوي", "cmd.view_visual_style": "نمط العرض", + "color.blue": "أزرق", "color.copy": "انقر لنسخ قيم اللون", "color.edit": "انقر لتعديل اللون", "color.gamma": "عرض قيم اللون في نطاق جاما 0-255", + "color.green": "أخضر", "color.hex": "Hex", "color.hex_help": "أدخل #rrggbb أو #rrggbbaa؛ مع الخانات الست تبقى العتامة كما هي", "color.hex_hint": "#rrggbb", @@ -1300,6 +1312,7 @@ "color.linear": "عرض قيم اللون في النطاق الخطي 0-1", "color.recent": "الألوان الأخيرة", "color.recent_help": "تظهر هنا الألوان التي تختارها في أي حقل لون", + "color.red": "أحمر", "color.saturation": "التشبع (بالمئة)", "color.saturation_value": "التشبع والقيمة", "color.selected": "اللون المحدد", @@ -1357,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "اختر أجسامًا أو ميزات: الرسم ليس أيًّا منهما. كرّر منحنياته بأداة النمط أو المرآة داخل الرسم، أو ابثقه أولًا.", "dialog.select": "↖ تحديد", "dialog.selected_count": "↖ {count} محدد", + "dialog.selection_constraint": "قيد {id}", + "dialog.selection_external_curve": "{sketch} · منحنى {id}", "dialog.selection_guidance": "حدد مُدخلًا لتغييره. انقر على العناصر المحددة لإزالتها؛ Ctrl/Cmd مع النقر يبدّل تحديدها أيضًا. راجع المعاينة ثم اضغط موافق.", + "dialog.selection_midpoint": "نقطة المنتصف · {id}", + "dialog.selection_profile": "{sketch} · المقطع {number}", "dialog.selection_step": "{step} من {total}: حدد {input}", "dialog.step": "الخطوة", "document.changed_on_disk": "تغيّر {name} على القرص", @@ -2139,6 +2156,8 @@ "prefs.button_left": "سحب بالزر الأيسر", "prefs.button_middle": "سحب بالزر الأوسط", "prefs.button_right": "سحب بالزر الأيمن", + "prefs.carousel_next": "التالي", + "prefs.carousel_previous": "السابق", "prefs.choose_font": "اختيار ملف خط…", "prefs.click": "نقر", "prefs.contact_shading": "تظليل التلامس الناعم", @@ -2151,6 +2170,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "الأسطح المنحنية", "prefs.curves": "الأسطح المنحنية", + "prefs.cut_preview_tint": "إظهار المادة المُزالة باللون الأحمر", + "prefs.cut_preview_tint_help": "تملأ المعاينة المادة التي تزيلها الميزة، والشكل الذي تستبدله، بطيف أحمر شبه شفاف. عند الإيقاف تكون هذه التعبئة شفافة تمامًا ولا يُرسم سوى محيطها.", "prefs.dark_parts_shading": "الحفاظ على شكل الأجزاء الداكنة", "prefs.dark_parts_shading_help": "تظليل العرض بإضاءة خطية مع إضاءة سماء ناعمة، لتحتفظ الأوجه الداكنة بتدرج بدل أن تصبح سوداء", "prefs.dead_zone_note": "الشريط المخطط هو المنطقة الميتة: تُتجاهل الحركة داخلها.", @@ -2270,6 +2291,8 @@ "prefs.placement": "الموضع", "prefs.prefer_free_sketch_points": "تفضيل نقاط الرسم القابلة للتحريك عند تداخل النقاط", "prefs.preview_choices": "معاينة اختياراتك", + "prefs.preview_tint_new_faces": "تلوين السطح الجديد في المعاينة", + "prefs.preview_tint_new_faces_help": "يمكن لمعاينة ميزة تغيّر جسمًا أن ترسم السطح المضاف بلون المعاينة. عند الإيقاف يُرسم الجسم بلونه الأصلي.", "prefs.print_face_highlight": "إبراز وجه الطباعة", "prefs.print_face_highlight_tip": "مدى قوة تلوين وجه الطباعة للجسم ورسم حدوده في العرض. القيمة 0 % لا تُظهر أي إبراز.", "prefs.profile_active": "ملف التعريف النشط", @@ -2567,6 +2590,10 @@ "render.base_color": "اللون الأساسي · sRGB", "render.base_metallic": "النسبة المعدنية", "render.base_opaque_only": "يحافظ هذا المحرر على دلالات الجسم المعتم. استخدم عناصر التحكم الصريحة للزجاج من أجل النفاذ البصري.", + "render.batch_all_shots": "كل اللقطات ({count})", + "render.batch_empty": "احفظ لقطة قبل تصيير كل اللقطات.", + "render.batch_limit": "تصيير كل اللقطات محدود بـ 32 لقطة.", + "render.batch_status": "{running} قيد التشغيل · {waiting} في الانتظار", "render.bloom_enable": "توهج العرض", "render.bloom_help": "توهج إبداعي للإخراج فقط من الإضاءات الخطية الموجبة، يُنشر بثلاث تمريرات صندوقية مُطبّعة. نصف القطر ببكسلات الإخراج. يُضاف في ضوء العرض الخطي قبل sRGB؛ وليس عدسة ولا تأثيرًا حجميًا ولا تحسينًا للتقارب. يبقى EXR الخام دون تغيير.", "render.bloom_opaque": "يتطلب التوهج إخراجًا معتمًا. يُرفض PNG الشفاف بدل تسطيحه بصمت.", @@ -2677,6 +2704,13 @@ "render.choose_look": "اختر مظهرًا من المظاهر أولًا", "render.chromatic_offset": "إزاحة لونية عند الحواف", "render.clear_stage": "إزالة المنصة المحفوظة", + "render.compare_divider": "فاصل المقارنة", + "render.compare_live": "حي", + "render.compare_live_preview": "معاينة حية", + "render.compare_render": "التصيير {number}", + "render.compare_side": "التصيير {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} ث · {renderer} · التُقطت عند المراجعة {revision}", + "render.compare_swap": "تبديل", "render.copy_request": "نسخ JSON", "render.cpu_aa_help": "العيّنات المكانية: المزيد منها يحسّن الحواف ويزيد زمن التصيير.", "render.cpu_area_add": "إضافة ضوء مستطيل على CPU", @@ -3426,6 +3460,10 @@ "render.result_retained": "تُعرض آخر صورة مكتملة؛ ولم يستبدلها تصيير أحدث.", "render.result_sequence": "نقطة التحقق", "render.result_title": "نتيجة التصيير", + "render.results_choose": "النتائج المحتفظ بها", + "render.results_label": "التصيير {number} · {shot} · {seconds} ث", + "render.results_stale_label": "{result} [قديم]", + "render.results_unnamed": "صورة", "render.return_design": "العودة إلى التصميم", "render.review_stale": "هذه المراجعة قديمة. حُلّها أو افحص مرة أخرى قبل التطبيق.", "render.ribbon_aging": "التقادم", @@ -4097,6 +4135,7 @@ "ui.agent_chat_ctx_features": "الميزات", "ui.agent_chat_ctx_more": "+{n} أخرى", "ui.agent_chat_ctx_other": "أخرى", + "ui.agent_chat_custom_heading": "نموذج مخصص", "ui.agent_chat_custom_hint": "أي برنامج يتحدث بروتوكول Agent Client Protocol عبر stdin وstdout. لا تشغّله أي صدفة أوامر.", "ui.agent_chat_denied": "مرفوض", "ui.agent_chat_deny": "رفض", @@ -4140,8 +4179,16 @@ "ui.agent_chat_mode_all": "الكل", "ui.agent_chat_mode_ask": "السؤال", "ui.agent_chat_mode_edits": "التعديلات", + "ui.agent_chat_model_custom": "استخدام المخصص: {model}", "ui.agent_chat_model_no_tools": "لا يستطيع {model} استخدام أدوات SolidCraft، لذا يمكنه المحادثة فقط. اختر نموذجًا يدعم الأدوات.", + "ui.agent_chat_model_rejected": "لم يقبل الوكيل {model}: {error}", + "ui.agent_chat_model_search": "البحث عن النماذج…", "ui.agent_chat_model_tip": "النموذج الذي يستخدمه الوكيل. يُحفظ اختيارك لهذا الوكيل.", + "ui.agent_chat_models_failed": "تعذّر جلب قائمة النماذج: {error}", + "ui.agent_chat_models_heading": "النماذج المتاحة", + "ui.agent_chat_models_listing": "جارٍ جلب قائمة النماذج…", + "ui.agent_chat_models_none": "لا تسرد نقطة النهاية أي نماذج", + "ui.agent_chat_models_not_a_list": "لم يكن الرد قائمة نماذج", "ui.agent_chat_new": "محادثة جديدة", "ui.agent_chat_new_confirm": "بدء محادثة جديدة؟ ستُمسح المحادثة الحالية.", "ui.agent_chat_next_picture": "الصورة التالية", @@ -4723,6 +4770,7 @@ "ui.insert_design.saved_file": "في {name} تغييرات غير محفوظة، لذا أُدرج ملفه المحفوظ. احفظه، ثم استخدم تحديث الروابط لإدخال التغييرات.", "ui.insert_design.unsaved": "تغييرات غير محفوظة", "ui.inspect": "فحص", + "ui.instances": "النسخ", "ui.intersect": "تقاطع", "ui.isolate": "عزل", "ui.join": "ضم", @@ -5214,6 +5262,7 @@ "web.open_link": "فتح التصميم المرتبط؟", "web.open_link_confirm": "توجد تغييرات غير محفوظة. هل تريد فتح التصميم المرتبط في تبويب جديد؟", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ اختيار · Enter / Tab إكمال · Esc إغلاق", + "↑ ↓ choose · Enter applies this value": "↑ ↓ اختيار · Enter يطبّق هذه القيمة", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ اختيار · Enter يطبّق ما كتبته · Esc إغلاق", "⌘Enter continues on GitHub.": "⌘Enter يتابع في GitHub." } diff --git a/assets/locales/bs.json b/assets/locales/bs.json index ba9249dd7..8bf268a8e 100644 --- a/assets/locales/bs.json +++ b/assets/locales/bs.json @@ -4706,6 +4706,7 @@ "ui.insert_design.saved_file": "{name} ima nesačuvane promjene, pa je umetnuta njegova sačuvana datoteka. Sačuvajte ga, a zatim pokrenite Ažuriraj veze da unesete promjene.", "ui.insert_design.unsaved": "Nesačuvane promjene", "ui.inspect": "Pregledaj", + "ui.instances": "Instance", "ui.intersect": "Presjek", "ui.isolate": "Izoluj", "ui.join": "Spoji", diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 694c0f116..b0834d79e 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -4706,6 +4706,7 @@ "ui.insert_design.saved_file": "{name} obsahuje neuložené změny, proto byl vložen jeho uložený soubor. Uložte jej a pak použijte Aktualizovat odkazy, aby se změny převzaly.", "ui.insert_design.unsaved": "Neuložené změny", "ui.inspect": "Analýza", + "ui.instances": "Instance", "ui.intersect": "Průnik", "ui.isolate": "Izolovat", "ui.join": "Sjednotit", diff --git a/assets/locales/da.json b/assets/locales/da.json index 825b629e9..55696428f 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -4706,6 +4706,7 @@ "ui.insert_design.saved_file": "{name} har ændringer, der ikke er gemt, så dens gemte fil blev indsat. Gem den, og kør derefter Opdatér forbindelser for at hente ændringerne.", "ui.insert_design.unsaved": "Ikke-gemte ændringer", "ui.inspect": "Inspicér", + "ui.instances": "Forekomster", "ui.intersect": "Fællesvolumen", "ui.isolate": "Isolér", "ui.join": "Foren", diff --git a/assets/locales/de.json b/assets/locales/de.json index 4d5f1ecbb..cc740be5c 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -556,6 +556,7 @@ "Section": "Schnitt", "Section (optional)": "Abschnitt (optional)", "Section position": "Lage des Querschnitts", + "Sections": "Querschnitte", "Sections (one sketch each)": "Querschnitte (je eine Skizze)", "Select Other": "Andere auswählen", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Anderes auswählen: Halten Sie die linke Taste ruhig auf dem Modell gedrückt (oder Rechtsklick › Anderes auswählen…), um alles unter dem Cursor aufzulisten; klicken Sie erneut an dieselbe Stelle, um das nächste Element dort auszuwählen. Doppelklick mit der mittleren Taste wechselt zur Startansicht (Einstellungen › Navigation).", @@ -934,6 +935,11 @@ "cmd.explode_show": "Explosionsdarstellung anzeigen", "cmd.expr_evaluate": "Ausdruck auswerten", "cmd.face_delete": "Fläche löschen", + "cmd.file.export_3mf": "Als 3MF exportieren", + "cmd.file.export_obj": "Als OBJ exportieren", + "cmd.file.export_step": "Als STEP exportieren", + "cmd.file.export_stl": "Als STL exportieren", + "cmd.file.export_urdf": "Als URDF exportieren", "cmd.file_export": "Exportieren", "cmd.file_insert_mesh": "Netz einfügen", "cmd.file_insert_step": "STEP einfügen", @@ -1041,6 +1047,9 @@ "cmd.pointcloud_edit": "Punktwolke bearbeiten", "cmd.pointcloud_insert": "Punktwolke einfügen", "cmd.pointcloud_list": "Punktwolken", + "cmd.render.compare.divider": "Render-Vergleichstrenner verschieben", + "cmd.render.result.discard": "Renderergebnis verwerfen", + "cmd.render.result.select": "Renderergebnis auswählen", "cmd.render_aging_describe": "Mehrschichtige Oberflächenalterung", "cmd.render_backends": "Render-Backends", "cmd.render_batch": "Alle Aufnahmen rendern", @@ -1288,9 +1297,11 @@ "cmd.view_tool": "Navigationswerkzeug", "cmd.view_top": "Draufsicht", "cmd.view_visual_style": "Darstellungsstil", + "color.blue": "Blau", "color.copy": "Klicken, um Farbwerte zu kopieren", "color.edit": "Klicken, um Farbe zu bearbeiten", "color.gamma": "Farbwerte im Gammaraum 0-255 anzeigen", + "color.green": "Grün", "color.hex": "Hex", "color.hex_help": "#rrggbb oder #rrggbbaa eingeben; sechs Ziffern behalten die Deckkraft bei", "color.hex_hint": "#rrggbb", @@ -1298,6 +1309,7 @@ "color.linear": "Farbwerte im linearen Raum 0-1 anzeigen", "color.recent": "Zuletzt verwendete Farben", "color.recent_help": "Farben, die Sie in einem beliebigen Farbfeld wählen, erscheinen hier", + "color.red": "Rot", "color.saturation": "Sättigung (Prozent)", "color.saturation_value": "Sättigung und Wert", "color.selected": "Ausgewählte Farbe", @@ -1355,7 +1367,11 @@ "dialog.pattern_sketch_not_object": "Körper oder Funktionen wählen: Eine Skizze ist keines von beiden. Ihre Kurven mit Muster oder Spiegeln in der Skizze wiederholen oder sie zuerst extrudieren.", "dialog.select": "↖ Auswählen", "dialog.selected_count": "↖ {count} ausgewählt", + "dialog.selection_constraint": "Bedingung {id}", + "dialog.selection_external_curve": "{sketch} · Kurve {id}", "dialog.selection_guidance": "Wählen Sie eine Eingabe aus, um sie zu ändern. Klicken Sie auf ausgewählte Objekte, um sie zu entfernen; Strg/Cmd-Klick schaltet sie ebenfalls um. Prüfen Sie die Vorschau und drücken Sie dann OK.", + "dialog.selection_midpoint": "Mittelpunkt · {id}", + "dialog.selection_profile": "{sketch} · Profil {number}", "dialog.selection_step": "{step} von {total}: {input} auswählen", "dialog.step": "Schritt", "document.changed_on_disk": "{name} wurde auf dem Datenträger geändert", @@ -2137,6 +2153,8 @@ "prefs.button_left": "Ziehen mit der linken Maustaste", "prefs.button_middle": "Ziehen mit der mittleren Maustaste", "prefs.button_right": "Ziehen mit der rechten Maustaste", + "prefs.carousel_next": "Weiter", + "prefs.carousel_previous": "Zurück", "prefs.choose_font": "Schriftdatei auswählen…", "prefs.click": "Klicken", "prefs.contact_shading": "Weiche Kontaktschattierung", @@ -2149,6 +2167,8 @@ "prefs.ctrl_cmd": "Strg / Cmd", "prefs.curved_surfaces": "Gekrümmte Flächen", "prefs.curves": "Gekrümmte Flächen", + "prefs.cut_preview_tint": "Entferntes Material rot anzeigen", + "prefs.cut_preview_tint_help": "Eine Vorschau füllt das Material, das ein Feature entfernt, sowie die ersetzte Form mit einem roten, durchscheinenden Geist. Wenn deaktiviert, sind diese Füllungen völlig transparent und es werden nur ihre Umrisse gezeichnet.", "prefs.dark_parts_shading": "Form dunkler Teile erhalten", "prefs.dark_parts_shading_help": "Die Ansicht in linearem Licht mit sanftem Himmelslicht schattieren, damit dunkle Flächen einen Verlauf behalten statt schwarz zu werden", "prefs.dead_zone_note": "Der schraffierte Bereich kennzeichnet die Totzone. Bewegungen innerhalb dieses Bereichs werden ignoriert.", @@ -2266,6 +2286,8 @@ "prefs.placement": "Platzierung", "prefs.prefer_free_sketch_points": "Bei überlappenden Punkten bewegliche Skizzenpunkte bevorzugen", "prefs.preview_choices": "Vorschau Ihrer Einstellungen", + "prefs.preview_tint_new_faces": "Neue Fläche in der Vorschau einfärben", + "prefs.preview_tint_new_faces_help": "Eine Vorschau eines Features, das einen Körper ändert, kann die hinzugefügte Fläche in der Vorschaufarbe zeichnen. Wenn deaktiviert, wird der Körper wie er ist gezeichnet.", "prefs.print_face_highlight": "Hervorhebung der Auflagefläche", "prefs.print_face_highlight_tip": "Wie stark die Auflagefläche eines Körpers in der Ansicht eingefärbt und umrandet wird. 0 % zeigt keine Hervorhebung.", "prefs.profile_active": "Aktives Profil", @@ -2563,6 +2585,10 @@ "render.base_color": "Grundfarbe · sRGB", "render.base_metallic": "Metallanteil", "render.base_opaque_only": "Dieser Editor lässt Körper undurchsichtig. Für optische Transmission verwenden Sie die gesonderten Glaseinstellungen.", + "render.batch_all_shots": "Alle Ansichten ({count})", + "render.batch_empty": "Vor dem Rendern aller Ansichten eine Ansicht speichern.", + "render.batch_limit": "Es können höchstens 32 Ansichten gerendert werden.", + "render.batch_status": "{running} läuft · {waiting} warten", "render.bloom_enable": "Darstellungs-Bloom", "render.bloom_help": "Kreativer Ausgabeglanz aus linearen Glanzlichtern mit drei normierten Durchläufen. Radius in Ausgabepixeln; Addition vor sRGB. Keine Linsen-, Volumen- oder Konvergenzsimulation. Das rohe EXR bleibt unverändert.", "render.bloom_opaque": "Bloom benötigt eine deckende Ausgabe. Transparentes PNG wird abgelehnt, nicht still abgeflacht.", @@ -2673,6 +2699,13 @@ "render.choose_look": "Zuerst einen Look in der Bibliothek wählen", "render.chromatic_offset": "Chromatischer Kantenversatz", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "Vergleichstrenner", + "render.compare_live": "Live", + "render.compare_live_preview": "Live-Vorschau", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · aufgenommen bei Revision {revision}", + "render.compare_swap": "Tauschen", "render.copy_request": "JSON kopieren", "render.cpu_aa_help": "Räumliche Samples: Mehr Samples verbessern die Kantenglättung, verlängern jedoch die Renderzeit.", "render.cpu_area_add": "Rechteckiges CPU-Flächenlicht hinzufügen", @@ -3422,6 +3455,10 @@ "render.result_retained": "Das zuletzt fertiggestellte Bild wird angezeigt; ein neueres Rendering hat es noch nicht ersetzt.", "render.result_sequence": "Prüfpunkt", "render.result_title": "Render-Ergebnis", + "render.results_choose": "Behaltene Ergebnisse", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [veraltet]", + "render.results_unnamed": "Bild", "render.return_design": "Zurück zu Design", "render.review_stale": "Diese Prüfung ist veraltet. Lösen Sie sie auf oder prüfen Sie erneut, bevor Sie sie anwenden.", "render.ribbon_aging": "Alterung", @@ -4093,6 +4130,7 @@ "ui.agent_chat_ctx_features": "Funktionen", "ui.agent_chat_ctx_more": "+{n} weitere", "ui.agent_chat_ctx_other": "Sonstiges", + "ui.agent_chat_custom_heading": "Eigenes Modell", "ui.agent_chat_custom_hint": "Jedes Programm, das das Agent Client Protocol über stdin und stdout spricht. Es läuft ohne Shell.", "ui.agent_chat_denied": "Abgelehnt", "ui.agent_chat_deny": "Ablehnen", @@ -4136,8 +4174,16 @@ "ui.agent_chat_mode_all": "Alles", "ui.agent_chat_mode_ask": "Fragen", "ui.agent_chat_mode_edits": "Ändern", + "ui.agent_chat_model_custom": "Eigenes verwenden: {model}", "ui.agent_chat_model_no_tools": "{model} kann die Werkzeuge von SolidCraft nicht verwenden und daher nur chatten. Wählen Sie ein Modell mit Werkzeugunterstützung.", + "ui.agent_chat_model_rejected": "Der Agent hat {model} nicht akzeptiert: {error}", + "ui.agent_chat_model_search": "Modelle suchen…", "ui.agent_chat_model_tip": "Das vom Agenten verwendete Modell. Ihre Auswahl wird für diesen Agenten gespeichert.", + "ui.agent_chat_models_failed": "Modelle konnten nicht abgerufen werden: {error}", + "ui.agent_chat_models_heading": "Verfügbare Modelle", + "ui.agent_chat_models_listing": "Modelle werden abgerufen…", + "ui.agent_chat_models_none": "Der Endpunkt listet keine Modelle", + "ui.agent_chat_models_not_a_list": "Die Antwort war keine Modellliste", "ui.agent_chat_new": "Neuer Chat", "ui.agent_chat_new_confirm": "Neuen Chat starten? Der aktuelle wird geleert.", "ui.agent_chat_next_picture": "Nächstes Bild", @@ -4716,6 +4762,7 @@ "ui.insert_design.saved_file": "{name} hat ungespeicherte Änderungen, daher wurde die gespeicherte Datei eingefügt. Speichern Sie sie und wählen Sie dann Verknüpfungen aktualisieren, um die Änderungen zu übernehmen.", "ui.insert_design.unsaved": "Ungespeicherte Änderungen", "ui.inspect": "Prüfen", + "ui.instances": "Instanzen", "ui.intersect": "Schnitt", "ui.isolate": "Isolieren", "ui.join": "Verbinden", @@ -5206,6 +5253,7 @@ "web.open_link": "Verknüpftes Design öffnen?", "web.open_link_confirm": "Es gibt nicht gespeicherte Änderungen. Das verknüpfte Design in einem neuen Tab öffnen?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ auswählen · Eingabe / Tab vervollständigen · Esc schließen", + "↑ ↓ choose · Enter applies this value": "↑ ↓ auswählen · Eingabe übernimmt diesen Wert", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ wählen · Enter wendet das Getippte an · Esc schließt", "⌘Enter continues on GitHub.": "⌘Enter geht weiter zu GitHub." } diff --git a/assets/locales/en-GB.json b/assets/locales/en-GB.json index 6e55dc209..934271166 100644 --- a/assets/locales/en-GB.json +++ b/assets/locales/en-GB.json @@ -249,6 +249,7 @@ "ui.details_curvature_caption": "Faces are coloured by their local radius of curvature.", "ui.details_draft_caption": "Faces are coloured by their angle to the pull direction.", "ui.export_keymap_tip": "Keys, S box favourites and the toolbar, as a file", + "ui.instances": "Instances", "ui.layout_compact": "Compact", "ui.layout_floating": "Floating", "ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.", diff --git a/assets/locales/en.json b/assets/locales/en.json index 305b18614..07ededad6 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -556,6 +556,7 @@ "Section": "Section", "Section (optional)": "Section (optional)", "Section position": "Section position", + "Sections": "Sections", "Sections (one sketch each)": "Sections (one sketch each)", "Select Other": "Select Other", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).", @@ -936,6 +937,11 @@ "cmd.explode_show": "Show Exploded View", "cmd.expr_evaluate": "Evaluate Expression", "cmd.face_delete": "Delete Face", + "cmd.file.export_3mf": "Export 3MF", + "cmd.file.export_obj": "Export OBJ", + "cmd.file.export_step": "Export STEP", + "cmd.file.export_stl": "Export STL", + "cmd.file.export_urdf": "Export URDF", "cmd.file_export": "Export", "cmd.file_insert_mesh": "Insert Mesh", "cmd.file_insert_step": "Insert STEP", @@ -953,6 +959,7 @@ "cmd.inspect_colored_components": "Enable Component Colors", "cmd.inspect_colored_components_disable": "Disable Component Colors", "cmd.inspect_compare": "Compare Bodies", + "cmd.inspect_compare_picture": "Compare Picture", "cmd.inspect_continuity": "Continuity Analysis", "cmd.inspect_curvature_comb": "Curvature Comb Analysis", "cmd.inspect_curvature_map": "Curvature Map Analysis", @@ -1043,6 +1050,9 @@ "cmd.pointcloud_edit": "Edit Point Cloud", "cmd.pointcloud_insert": "Insert Point Cloud", "cmd.pointcloud_list": "Point Clouds", + "cmd.render.compare.divider": "Move Render Comparison Divider", + "cmd.render.result.discard": "Discard Render Result", + "cmd.render.result.select": "Select Render Result", "cmd.render_aging_describe": "Layered Surface Aging", "cmd.render_backends": "Render Backends", "cmd.render_batch": "Render All Shots", @@ -1290,9 +1300,11 @@ "cmd.view_tool": "Navigation tool", "cmd.view_top": "Top View", "cmd.view_visual_style": "Visual style", + "color.blue": "Blue", "color.copy": "Click to copy color values", "color.edit": "Click to edit color", "color.gamma": "Showing color values in 0-255 gamma space", + "color.green": "Green", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", @@ -1300,6 +1312,7 @@ "color.linear": "Showing color values in 0-1 linear space", "color.recent": "Recent colors", "color.recent_help": "Colors you pick in any color field appear here", + "color.red": "Red", "color.saturation": "Saturation (percent)", "color.saturation_value": "Saturation and value", "color.selected": "Selected color", @@ -1357,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "Pick bodies or features: a sketch is neither. Repeat its curves with the sketch's own Pattern or Mirror, or extrude it first.", "dialog.select": "↖ Select", "dialog.selected_count": "↖ {count} selected", + "dialog.selection_constraint": "Constraint {id}", + "dialog.selection_external_curve": "{sketch} · curve {id}", "dialog.selection_guidance": "Select an input to change it. Click selected objects to remove them; Ctrl/Cmd-click also toggles them. Review the preview, then press OK.", + "dialog.selection_midpoint": "Midpoint · {id}", + "dialog.selection_profile": "{sketch} · profile {number}", "dialog.selection_step": "{step} of {total}: Select {input}", "dialog.step": "Step", "document.changed_on_disk": "{name} changed on disk", @@ -2139,6 +2156,8 @@ "prefs.button_left": "Left drag", "prefs.button_middle": "Middle drag", "prefs.button_right": "Right drag", + "prefs.carousel_next": "Next", + "prefs.carousel_previous": "Previous", "prefs.choose_font": "Choose font file…", "prefs.click": "Click", "prefs.contact_shading": "Soft contact shading", @@ -2151,6 +2170,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Curved surfaces", "prefs.curves": "Curved surfaces", + "prefs.cut_preview_tint": "Show removed material in red", + "prefs.cut_preview_tint_help": "A preview fills the material a feature removes, and the shape it replaces, with a red see-through ghost. When off, those fills are fully transparent and only their outlines are drawn.", "prefs.dark_parts_shading": "Keep the shape of dark parts", "prefs.dark_parts_shading_help": "Shade the view in linear light with a soft sky fill, so dark faces keep a gradient instead of turning black", "prefs.dead_zone_note": "The hatched band is the dead zone: motion inside it is ignored.", @@ -2270,6 +2291,8 @@ "prefs.placement": "Placement", "prefs.prefer_free_sketch_points": "Prefer movable sketch points when points overlap", "prefs.preview_choices": "Preview of your choices", + "prefs.preview_tint_new_faces": "Tint new surface in a preview", + "prefs.preview_tint_new_faces_help": "A preview of a feature that changes a body can draw the surface it adds in the preview colour. When off, the body is drawn as itself.", "prefs.print_face_highlight": "Print face highlight", "prefs.print_face_highlight_tip": "How strongly the print face of a body is tinted and outlined in the view. 0 % shows no highlight.", "prefs.profile_active": "Active profile", @@ -2567,6 +2590,10 @@ "render.base_color": "Base color · sRGB", "render.base_metallic": "Metallic fraction", "render.base_opaque_only": "This editor preserves opaque body semantics. Use the explicit glass controls for optical transmission.", + "render.batch_all_shots": "All shots ({count})", + "render.batch_empty": "Save a shot before rendering all shots.", + "render.batch_limit": "Render all shots is limited to 32 shots.", + "render.batch_status": "{running} running · {waiting} waiting", "render.bloom_enable": "Display bloom", "render.bloom_help": "Creative output-only glow from positive linear highlights, spread with three normalized box passes. Radius is in output pixels. Added in linear display light before sRGB; not a lens, volumetric effect or convergence improvement. The raw EXR is unchanged.", "render.bloom_opaque": "Bloom requires opaque output. Transparent PNG is refused, not silently flattened.", @@ -2677,6 +2704,13 @@ "render.choose_look": "Choose a look in Appearances first", "render.chromatic_offset": "Chromatic edge offset", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "Comparison divider", + "render.compare_live": "Live", + "render.compare_live_preview": "Live preview", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · captured at revision {revision}", + "render.compare_swap": "Swap", "render.copy_request": "Copy JSON", "render.cpu_aa_help": "Spatial samples: more samples improve edges and increase render time.", "render.cpu_area_add": "Add rectangular CPU light", @@ -3426,6 +3460,10 @@ "render.result_retained": "Showing the last completed image; a newer render has not replaced it.", "render.result_sequence": "Checkpoint", "render.result_title": "Render Result", + "render.results_choose": "Retained results", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [stale]", + "render.results_unnamed": "Image", "render.return_design": "Return to Design", "render.review_stale": "This review is stale. Resolve or check again before applying.", "render.ribbon_aging": "Aging", @@ -4097,6 +4135,7 @@ "ui.agent_chat_ctx_features": "Features", "ui.agent_chat_ctx_more": "+{n} more", "ui.agent_chat_ctx_other": "Other", + "ui.agent_chat_custom_heading": "Custom model", "ui.agent_chat_custom_hint": "Any program that speaks the Agent Client Protocol on stdin and stdout. No shell runs it.", "ui.agent_chat_denied": "Denied", "ui.agent_chat_deny": "Deny", @@ -4140,8 +4179,16 @@ "ui.agent_chat_mode_all": "All", "ui.agent_chat_mode_ask": "Ask", "ui.agent_chat_mode_edits": "Edits", + "ui.agent_chat_model_custom": "Use custom: {model}", "ui.agent_chat_model_no_tools": "{model} can't use SolidCraft's tools, so it can only chat. Pick a model with tool support.", + "ui.agent_chat_model_rejected": "The agent did not accept {model}: {error}", + "ui.agent_chat_model_search": "Search models…", "ui.agent_chat_model_tip": "The model the agent uses. Your choice is remembered for this agent.", + "ui.agent_chat_models_failed": "Couldn't list models: {error}", + "ui.agent_chat_models_heading": "Available models", + "ui.agent_chat_models_listing": "Listing models…", + "ui.agent_chat_models_none": "The endpoint lists no models", + "ui.agent_chat_models_not_a_list": "The answer was no model list", "ui.agent_chat_new": "New chat", "ui.agent_chat_new_confirm": "Start a new chat? The current one is cleared.", "ui.agent_chat_next_picture": "Next picture", @@ -4723,6 +4770,7 @@ "ui.insert_design.saved_file": "{name} has unsaved changes, so its saved file was inserted. Save it, then Update Links to bring the changes in.", "ui.insert_design.unsaved": "Unsaved changes", "ui.inspect": "Inspect", + "ui.instances": "Instances", "ui.intersect": "Intersect", "ui.isolate": "Isolate", "ui.join": "Join", @@ -5214,6 +5262,7 @@ "web.open_link": "Open linked design?", "web.open_link_confirm": "There are unsaved changes. Open the linked design in a new tab?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choose · Enter / Tab complete · Esc dismiss", + "↑ ↓ choose · Enter applies this value": "↑ ↓ choose · Enter applies this value", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ choose · Enter applies what you typed · Esc dismiss", "⌘Enter continues on GitHub.": "⌘Enter continues on GitHub." } diff --git a/assets/locales/es.json b/assets/locales/es.json index c11913b3b..5ae4ea115 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -4354,6 +4354,7 @@ "ui.insert_design.saved_file": "{name} tiene cambios sin guardar, así que se insertó su archivo guardado. Guárdalo y luego Actualizar vínculos para traer los cambios.", "ui.insert_design.unsaved": "Cambios sin guardar", "ui.inspect": "Inspeccionar", + "ui.instances": "Instancias", "ui.intersect": "Intersecar", "ui.isolate": "Aislar", "ui.join": "Unir", diff --git a/assets/locales/fi.json b/assets/locales/fi.json index 5a8f0809e..3af298273 100644 --- a/assets/locales/fi.json +++ b/assets/locales/fi.json @@ -4318,6 +4318,7 @@ "ui.insert_design.saved_file": "Mallissa {name} on tallentamattomia muutoksia, joten sen tallennettu tiedosto lisättiin. Tallenna se ja tuo muutokset valitsemalla Päivitä linkit.", "ui.insert_design.unsaved": "Tallentamattomia muutoksia", "ui.inspect": "Tarkastele", + "ui.instances": "Esiintymät", "ui.intersect": "Leikkaus", "ui.isolate": "Eristä", "ui.join": "Yhdistä", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index e70de521f..4da478259 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -4654,6 +4654,7 @@ "ui.insert_design.saved_file": "{name} contient des modifications non enregistrées ; c'est donc son fichier enregistré qui a été inséré. Enregistrez-le, puis utilisez Mettre à jour les liens pour intégrer les modifications.", "ui.insert_design.unsaved": "Modifications non enregistrées", "ui.inspect": "Inspecter", + "ui.instances": "Instances", "ui.intersect": "Intersection", "ui.isolate": "Isoler", "ui.join": "Joindre", diff --git a/assets/locales/he.json b/assets/locales/he.json index 6549a2441..93fe01ff4 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -556,6 +556,7 @@ "Section": "חתך", "Section (optional)": "חתך (אופציונלי)", "Section position": "מיקום החתך", + "Sections": "חתכים", "Sections (one sketch each)": "חתכים (סקיצה אחת לכל אחד)", "Select Other": "בחירת אחר", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "בחירת אחר: החזקת הכפתור השמאלי ללא תזוזה על המודל (או לחיצה ימנית › בחירת אחר…) מציגה את כל מה שמתחת לסמן; לחיצה נוספת באותה נקודה בוחרת את הפריט הבא שם. לחיצה כפולה על הכפתור האמצעי חוזרת לתצוגת הבית (העדפות › ניווט).", @@ -936,6 +937,11 @@ "cmd.explode_show": "הצגת תצוגה מפוצצת", "cmd.expr_evaluate": "חישוב ביטוי", "cmd.face_delete": "מחיקת פאה", + "cmd.file.export_3mf": "ייצוא 3MF", + "cmd.file.export_obj": "ייצוא OBJ", + "cmd.file.export_step": "ייצוא STEP", + "cmd.file.export_stl": "ייצוא STL", + "cmd.file.export_urdf": "ייצוא URDF", "cmd.file_export": "ייצוא", "cmd.file_insert_mesh": "הוספת רשת משולשים", "cmd.file_insert_step": "הוספת STEP", @@ -953,6 +959,7 @@ "cmd.inspect_colored_components": "הפעלת צבעי רכיבים", "cmd.inspect_colored_components_disable": "ביטול צבעי רכיבים", "cmd.inspect_compare": "השוואת גופים", + "cmd.inspect_compare_picture": "השוואה לתמונת ייחוס", "cmd.inspect_continuity": "ניתוח רציפות", "cmd.inspect_curvature_comb": "ניתוח מסרק עקמומיות", "cmd.inspect_curvature_map": "ניתוח מפת עקמומיות", @@ -1043,6 +1050,9 @@ "cmd.pointcloud_edit": "עריכת ענן נקודות", "cmd.pointcloud_insert": "הוספת ענן נקודות", "cmd.pointcloud_list": "ענני נקודות", + "cmd.render.compare.divider": "הזז את מחיצת ההשוואה של הרינדור", + "cmd.render.result.discard": "השלך תוצאת רינדור", + "cmd.render.result.select": "בחר תוצאת רינדור", "cmd.render_aging_describe": "הזדקנות משטח בשכבות", "cmd.render_backends": "מנועי הדמיה", "cmd.render_batch": "רינדור כל הצילומים", @@ -1290,9 +1300,11 @@ "cmd.view_tool": "כלי ניווט", "cmd.view_top": "תצוגה עליונה", "cmd.view_visual_style": "סגנון תצוגה", + "color.blue": "כחול", "color.copy": "לחיצה מעתיקה את ערכי הצבע", "color.edit": "לחיצה לעריכת הצבע", "color.gamma": "ערכי הצבע מוצגים במרחב גמא 0-255", + "color.green": "ירוק", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", @@ -1300,6 +1312,7 @@ "color.linear": "ערכי הצבע מוצגים במרחב לינארי 0-1", "color.recent": "צבעים אחרונים", "color.recent_help": "צבעים שבוחרים בכל שדה צבע מופיעים כאן", + "color.red": "אדום", "color.saturation": "רוויה (אחוזים)", "color.saturation_value": "רוויה ובהירות", "color.selected": "הצבע שנבחר", @@ -1357,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "בחרו גופים או פיצ'רים: סקיצה אינה אף אחד מהם. חזרו על העקומות שלה בעזרת המערך או השיקוף של הסקיצה עצמה, או בצעו לה שליפה קודם.", "dialog.select": "↖ בחירה", "dialog.selected_count": "↖ {count} נבחרו", + "dialog.selection_constraint": "אילוץ {id}", + "dialog.selection_external_curve": "{sketch} · עקומה {id}", "dialog.selection_guidance": "יש לבחור קלט כדי לשנות אותו. לחיצה על אובייקט שנבחר מסירה אותו; גם Ctrl/Cmd+לחיצה מחליפה את מצבו. לאחר בדיקת התצוגה המקדימה יש ללחוץ על אישור.", + "dialog.selection_midpoint": "נקודת אמצע · {id}", + "dialog.selection_profile": "{sketch} · פרופיל {number}", "dialog.selection_step": "{step} מתוך {total}: בחירת {input}", "dialog.step": "שלב", "document.changed_on_disk": "{name} השתנה בדיסק", @@ -2139,6 +2156,8 @@ "prefs.button_left": "גרירה שמאלית", "prefs.button_middle": "גרירה אמצעית", "prefs.button_right": "גרירה ימנית", + "prefs.carousel_next": "הבא", + "prefs.carousel_previous": "הקודם", "prefs.choose_font": "בחירת קובץ גופן…", "prefs.click": "לחיצה", "prefs.contact_shading": "הצללת מגע רכה", @@ -2151,6 +2170,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "משטחים מעוקלים", "prefs.curves": "משטחים מעוקלים", + "prefs.cut_preview_tint": "הצגת חומר שהוסר באדום", + "prefs.cut_preview_tint_help": "תצוגה מקדימה ממלאת את החומר שהפעולה מסירה, ואת הצורה שהיא מחליפה, ברוח אדומה שקופה. כשהאפשרות כבויה המילויים האלה שקופים לחלוטין ומצוירים רק קווי המתאר שלהם.", "prefs.dark_parts_shading": "שמירה על צורת חלקים כהים", "prefs.dark_parts_shading_help": "הצללת התצוגה באור ליניארי עם תאורת שמיים רכה, כך שפאות כהות שומרות על מעבר גוונים במקום להפוך לשחורות", "prefs.dead_zone_note": "הפס המקווקו הוא האזור המת: תנועה בתוכו לא נלקחת בחשבון.", @@ -2270,6 +2291,8 @@ "prefs.placement": "מיקום", "prefs.prefer_free_sketch_points": "העדפת נקודות סקיצה ניתנות להזזה כשנקודות חופפות", "prefs.preview_choices": "תצוגה מקדימה של הבחירות שלך", + "prefs.preview_tint_new_faces": "צביעת משטח חדש בתצוגה מקדימה", + "prefs.preview_tint_new_faces_help": "תצוגה מקדימה של פעולה שמשנה גוף יכולה לצבוע את המשטח שנוסף בצבע התצוגה המקדימה. כשהאפשרות כבויה הגוף מצויר בצבעו שלו.", "prefs.print_face_highlight": "הדגשת פאת ההדפסה", "prefs.print_face_highlight_tip": "עד כמה חזק צובעים ומקיפים את פאת ההדפסה של גוף בתצוגה. ‏0 % אינו מציג הדגשה.", "prefs.profile_active": "פרופיל פעיל", @@ -2567,6 +2590,10 @@ "render.base_color": "צבע בסיס · sRGB", "render.base_metallic": "שיעור מתכתיות", "render.base_opaque_only": "עורך זה שומר על משמעות של גוף אטום. להעברה אופטית יש להשתמש בפקדי הזכוכית המפורשים.", + "render.batch_all_shots": "כל הצילומים ({count})", + "render.batch_empty": "שמור צילום לפני רינדור כל הצילומים.", + "render.batch_limit": "רינדור כל הצילומים מוגבל ל-32 צילומים.", + "render.batch_status": "{running} רצים · {waiting} ממתינים", "render.bloom_enable": "זוהר בתצוגה", "render.bloom_help": "זוהר יצירתי לפלט בלבד מהבהרות ליניאריות חיוביות, המתפשט בשלושה מעברי תיבה מנורמלים. הרדיוס בפיקסלים של הפלט. נוסף באור תצוגה ליניארי לפני sRGB; אינו עדשה, אינו אפקט נפחי ואינו שיפור התכנסות. ה־EXR הגולמי אינו משתנה.", "render.bloom_opaque": "זוהר דורש פלט אטום. PNG שקוף נדחה, ואינו משוטח בשקט.", @@ -2677,6 +2704,13 @@ "render.choose_look": "בחר קודם מראה במראות", "render.chromatic_offset": "היסט כרומטי בקצוות", "render.clear_stage": "הסרת הבמה השמורה", + "render.compare_divider": "מחיצת השוואה", + "render.compare_live": "חי", + "render.compare_live_preview": "תצוגה חיה", + "render.compare_render": "רינדור {number}", + "render.compare_side": "רינדור {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} שנ׳ · {renderer} · נקלט בגרסה {revision}", + "render.compare_swap": "החלף", "render.copy_request": "העתקת JSON", "render.cpu_aa_help": "דגימות מרחביות: יותר דגימות משפרות קצוות ומאריכות את זמן ההדמיה.", "render.cpu_area_add": "הוספת אור מלבני ב־CPU", @@ -3426,6 +3460,10 @@ "render.result_retained": "מוצגת התמונה הגמורה האחרונה; הדמיה חדשה יותר לא החליפה אותה.", "render.result_sequence": "נקודת ביקורת", "render.result_title": "תוצאת הדמיה", + "render.results_choose": "תוצאות שנשמרו", + "render.results_label": "רינדור {number} · {shot} · {seconds} שנ׳", + "render.results_stale_label": "{result} [ישן]", + "render.results_unnamed": "תמונה", "render.return_design": "חזרה לתכן", "render.review_stale": "סקירה זו אינה עדכנית. יש לפתור או לבדוק שוב לפני ההחלה.", "render.ribbon_aging": "הזדקנות", @@ -4097,6 +4135,7 @@ "ui.agent_chat_ctx_features": "פיצ'רים", "ui.agent_chat_ctx_more": "+{n} נוספים", "ui.agent_chat_ctx_other": "אחר", + "ui.agent_chat_custom_heading": "מודל מותאם אישית", "ui.agent_chat_custom_hint": "כל תוכנה שמדברת Agent Client Protocol דרך stdin ו־stdout. היא לא מורצת דרך מעטפת (shell).", "ui.agent_chat_denied": "נדחה", "ui.agent_chat_deny": "דחייה", @@ -4140,8 +4179,16 @@ "ui.agent_chat_mode_all": "הכול", "ui.agent_chat_mode_ask": "שאלה", "ui.agent_chat_mode_edits": "עריכות", + "ui.agent_chat_model_custom": "שימוש במותאם אישית: {model}", "ui.agent_chat_model_no_tools": "{model} לא יכול להשתמש בכלים של SolidCraft, ולכן הוא יכול רק לשוחח. יש לבחור מודל שתומך בכלים.", + "ui.agent_chat_model_rejected": "הסוכן לא קיבל את {model}: {error}", + "ui.agent_chat_model_search": "חיפוש מודלים…", "ui.agent_chat_model_tip": "המודל שבו הסוכן משתמש. הבחירה נשמרת עבור הסוכן הזה.", + "ui.agent_chat_models_failed": "לא ניתן היה לטעון את רשימת המודלים: {error}", + "ui.agent_chat_models_heading": "מודלים זמינים", + "ui.agent_chat_models_listing": "טוען רשימת מודלים…", + "ui.agent_chat_models_none": "נקודת הקצה אינה מציגה מודלים", + "ui.agent_chat_models_not_a_list": "התשובה לא הייתה רשימת מודלים", "ui.agent_chat_new": "צ'אט חדש", "ui.agent_chat_new_confirm": "להתחיל צ'אט חדש? הצ'אט הנוכחי יימחק.", "ui.agent_chat_next_picture": "התמונה הבאה", @@ -4723,6 +4770,7 @@ "ui.insert_design.saved_file": "ב-{name} יש שינויים שלא נשמרו, ולכן נוסף הקובץ השמור שלו. שמרו אותו ואז בחרו עדכון קישורים כדי להכניס את השינויים.", "ui.insert_design.unsaved": "שינויים שלא נשמרו", "ui.inspect": "בדיקה", + "ui.instances": "מופעים", "ui.intersect": "חיתוך משותף", "ui.isolate": "בידוד", "ui.join": "איחוד", @@ -5214,6 +5262,7 @@ "web.open_link": "לפתוח את התכן המקושר?", "web.open_link_confirm": "יש שינויים שלא נשמרו. לפתוח את התכן המקושר בלשונית חדשה?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ בחירה · Enter / Tab השלמה · Esc סגירה", + "↑ ↓ choose · Enter applies this value": "↑ ↓ בחירה · Enter מחיל את הערך הזה", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ בחירה · Enter מחיל את מה שהוקלד · Esc סגירה", "⌘Enter continues on GitHub.": "⌘Enter ממשיך ב־GitHub." } diff --git a/assets/locales/hr.json b/assets/locales/hr.json index dcdfe4df3..d34506684 100644 --- a/assets/locales/hr.json +++ b/assets/locales/hr.json @@ -4706,6 +4706,7 @@ "ui.insert_design.saved_file": "{name} ima nespremljene promjene, pa je umetnuta njegova spremljena datoteka. Spremite ga, a zatim pokrenite Ažuriraj veze kako biste unijeli promjene.", "ui.insert_design.unsaved": "Nespremljene promjene", "ui.inspect": "Pregledaj", + "ui.instances": "Instance", "ui.intersect": "Presjek", "ui.isolate": "Izoliraj", "ui.join": "Spoji", diff --git a/assets/locales/it.json b/assets/locales/it.json index 993d686af..30c9e227b 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -4706,6 +4706,7 @@ "ui.insert_design.saved_file": "{name} contiene modifiche non salvate, quindi è stato inserito il file salvato. Salvalo, poi usa Aggiorna collegamenti per includere le modifiche.", "ui.insert_design.unsaved": "Modifiche non salvate", "ui.inspect": "Esamina", + "ui.instances": "Istanze", "ui.intersect": "Interseca", "ui.isolate": "Isola", "ui.join": "Unisci", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index b62c8e779..8ee6660fe 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -556,6 +556,7 @@ "Section": "断面", "Section (optional)": "断面(任意)", "Section position": "断面の位置", + "Sections": "セクション", "Sections (one sketch each)": "セクション (各1スケッチ)", "Select Other": "その他を選択", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。", @@ -936,6 +937,11 @@ "cmd.explode_show": "分解図を表示", "cmd.expr_evaluate": "式を評価", "cmd.face_delete": "面を削除", + "cmd.file.export_3mf": "3MF をエクスポート", + "cmd.file.export_obj": "OBJ をエクスポート", + "cmd.file.export_step": "STEP をエクスポート", + "cmd.file.export_stl": "STL をエクスポート", + "cmd.file.export_urdf": "URDF をエクスポート", "cmd.file_export": "エクスポート", "cmd.file_insert_mesh": "メッシュを挿入", "cmd.file_insert_step": "STEP を挿入", @@ -953,6 +959,7 @@ "cmd.inspect_colored_components": "コンポーネントの色分けを有効化", "cmd.inspect_colored_components_disable": "コンポーネントの色分けを無効化", "cmd.inspect_compare": "ボディを比較", + "cmd.inspect_compare_picture": "参考画像と比較", "cmd.inspect_continuity": "連続性解析", "cmd.inspect_curvature_comb": "曲率コーム解析", "cmd.inspect_curvature_map": "曲率マップ解析", @@ -1043,6 +1050,9 @@ "cmd.pointcloud_edit": "点群を編集", "cmd.pointcloud_insert": "点群を挿入", "cmd.pointcloud_list": "点群", + "cmd.render.compare.divider": "レンダー比較の境界を移動", + "cmd.render.result.discard": "レンダリング結果を破棄", + "cmd.render.result.select": "レンダリング結果を選択", "cmd.render_aging_describe": "レイヤー式表面エイジング", "cmd.render_backends": "レンダリング バックエンド", "cmd.render_batch": "すべてのショットをレンダリング", @@ -1290,9 +1300,11 @@ "cmd.view_tool": "ナビゲーションツール", "cmd.view_top": "上面ビュー", "cmd.view_visual_style": "表示スタイル", + "color.blue": "青", "color.copy": "クリックして色の値をコピー", "color.edit": "クリックして色を編集", "color.gamma": "0〜255のガンマ空間で色の値を表示", + "color.green": "緑", "color.hex": "Hex", "color.hex_help": "#rrggbb または #rrggbbaa を入力。6 桁の場合は不透明度を維持", "color.hex_hint": "#rrggbb", @@ -1300,6 +1312,7 @@ "color.linear": "0〜1の線形空間で色の値を表示", "color.recent": "最近使った色", "color.recent_help": "どの色フィールドで選んだ色もここに表示されます", + "color.red": "赤", "color.saturation": "彩度(パーセント)", "color.saturation_value": "彩度と明度", "color.selected": "選択した色", @@ -1357,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "ボディかフィーチャーを選んでください。スケッチはどちらでもありません。曲線はスケッチ内のパターンかミラーで繰り返すか、先に押し出してください。", "dialog.select": "↖ 選択", "dialog.selected_count": "↖ {count} 個選択中", + "dialog.selection_constraint": "拘束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲線 {id}", "dialog.selection_guidance": "入力欄を選んで変更します。選択済みのオブジェクトをクリックすると解除できます。Ctrl/Cmd を押しながらクリックしても切り替えられます。プレビューを確認してから OK を押してください。", + "dialog.selection_midpoint": "中点 · {id}", + "dialog.selection_profile": "{sketch} · プロファイル {number}", "dialog.selection_step": "{total} ステップ中 {step}: {input} を選択", "dialog.step": "ステップ", "document.changed_on_disk": "{name} がディスク上で変更されました", @@ -2139,6 +2156,8 @@ "prefs.button_left": "左ドラッグ", "prefs.button_middle": "中央ドラッグ", "prefs.button_right": "右ドラッグ", + "prefs.carousel_next": "次へ", + "prefs.carousel_previous": "前へ", "prefs.choose_font": "フォントファイルを選択…", "prefs.click": "クリック", "prefs.contact_shading": "柔らかな接触陰影", @@ -2151,6 +2170,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "曲面", "prefs.curves": "曲面", + "prefs.cut_preview_tint": "除去される材料を赤で表示", + "prefs.cut_preview_tint_help": "プレビューでは、フィーチャーが除去する材料と置き換えられる形状を、赤い透過ゴーストで塗りつぶします。オフにすると、この塗りつぶしは完全に透明になり、輪郭のみが描画されます。", "prefs.dark_parts_shading": "暗い部品の形状を保つ", "prefs.dark_parts_shading_help": "リニア光と柔らかいスカイライトでビューをシェーディングし、暗い面が黒くつぶれずにグラデーションを保つようにします", "prefs.dead_zone_note": "斜線の帯はデッドゾーンです。この範囲内の動きは無視されます。", @@ -2270,6 +2291,8 @@ "prefs.placement": "配置", "prefs.prefer_free_sketch_points": "スケッチ点が重なったときは移動可能な点を優先する", "prefs.preview_choices": "選択した設定のプレビュー", + "prefs.preview_tint_new_faces": "プレビューで新しい面に色を付ける", + "prefs.preview_tint_new_faces_help": "ボディを変更するフィーチャーのプレビューで、追加される面をプレビュー色で描画できます。オフにすると、ボディはそのままの色で描画されます。", "prefs.print_face_highlight": "造形面の強調", "prefs.print_face_highlight_tip": "ビューでボディの造形面を色付けし輪郭を描く強さ。0 % で強調しません。", "prefs.profile_active": "使用中のプロファイル", @@ -2567,6 +2590,10 @@ "render.base_color": "ベースカラー・sRGB", "render.base_metallic": "金属成分の割合", "render.base_opaque_only": "この編集では不透明ボディの意味を保持します。透過には明示的なガラス設定を使用してください。", + "render.batch_all_shots": "すべてのショット ({count})", + "render.batch_empty": "すべてのショットをレンダリングする前にショットを保存してください。", + "render.batch_limit": "一度にレンダリングできるショットは32個までです。", + "render.batch_status": "{running} 実行中 · {waiting} 待機中", "render.bloom_enable": "表示ブルーム", "render.bloom_help": "正の線形ハイライトを3回の正規化フィルターで広げる表示専用の効果です。半径は出力ピクセル単位。sRGB変換前に加算され、レンズ・体積・収束の改善ではありません。生EXRは変わりません。", "render.bloom_opaque": "ブルームには不透明な出力が必要です。透明PNGを暗黙に統合せず拒否します。", @@ -2677,6 +2704,13 @@ "render.choose_look": "まず外観ライブラリで外観を選択", "render.chromatic_offset": "色収差のずれ", "render.clear_stage": "保存済みステージを削除", + "render.compare_divider": "比較の境界", + "render.compare_live": "ライブ", + "render.compare_live_preview": "ライブプレビュー", + "render.compare_render": "レンダー {number}", + "render.compare_side": "レンダー {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · リビジョン {revision} で取得", + "render.compare_swap": "入れ替え", "render.copy_request": "JSONをコピー", "render.cpu_aa_help": "空間サンプル数を増やすと輪郭が滑らかになりますが、描画時間も増えます。", "render.cpu_area_add": "CPU矩形ライトを追加", @@ -3426,6 +3460,10 @@ "render.result_retained": "最後に完成した画像を表示しています。新しいレンダリングにはまだ置き換わっていません。", "render.result_sequence": "中間結果", "render.result_title": "レンダリング結果", + "render.results_choose": "保持した結果", + "render.results_label": "レンダー {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [更新前]", + "render.results_unnamed": "画像", "render.return_design": "設計に戻る", "render.review_stale": "この確認結果は古くなっています。適用前に再解決または再確認してください。", "render.ribbon_aging": "エイジング", @@ -4097,6 +4135,7 @@ "ui.agent_chat_ctx_features": "フィーチャ", "ui.agent_chat_ctx_more": "ほか{n}件", "ui.agent_chat_ctx_other": "その他", + "ui.agent_chat_custom_heading": "カスタムモデル", "ui.agent_chat_custom_hint": "標準入出力で Agent Client Protocol を話す任意のプログラム。シェルは使いません。", "ui.agent_chat_denied": "拒否しました", "ui.agent_chat_deny": "拒否", @@ -4140,8 +4179,16 @@ "ui.agent_chat_mode_all": "すべて", "ui.agent_chat_mode_ask": "確認", "ui.agent_chat_mode_edits": "編集", + "ui.agent_chat_model_custom": "カスタムを使用: {model}", "ui.agent_chat_model_no_tools": "{model} は SolidCraft のツールを使えず、チャットのみ可能です。ツール対応のモデルを選んでください。", + "ui.agent_chat_model_rejected": "エージェントは {model} を受け付けませんでした: {error}", + "ui.agent_chat_model_search": "モデルを検索…", "ui.agent_chat_model_tip": "エージェントが使うモデル。選択はこのエージェントに対して記憶されます。", + "ui.agent_chat_models_failed": "モデルを一覧表示できませんでした: {error}", + "ui.agent_chat_models_heading": "利用可能なモデル", + "ui.agent_chat_models_listing": "モデルを一覧表示中…", + "ui.agent_chat_models_none": "エンドポイントにモデルがありません", + "ui.agent_chat_models_not_a_list": "応答はモデル一覧ではありませんでした", "ui.agent_chat_new": "新しいチャット", "ui.agent_chat_new_confirm": "新しいチャットを始めますか? 現在のチャットは消去されます。", "ui.agent_chat_next_picture": "次の画像", @@ -4723,6 +4770,7 @@ "ui.insert_design.saved_file": "{name} に保存されていない変更があるため、保存済みのファイルを挿入しました。保存してから、リンクを更新で変更を取り込んでください。", "ui.insert_design.unsaved": "未保存の変更", "ui.inspect": "検査", + "ui.instances": "インスタンス", "ui.intersect": "交差", "ui.isolate": "分離表示", "ui.join": "結合", @@ -5214,6 +5262,7 @@ "web.open_link": "リンク先のデザインを開きますか?", "web.open_link_confirm": "保存していない変更があります。リンク先のデザインを新しいタブで開きますか?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 選択 · Enter / Tab 補完 · Esc 閉じる", + "↑ ↓ choose · Enter applies this value": "↑ ↓ 選択 · Enter この値を適用", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 選択 · Enter 入力どおりに適用 · Esc 閉じる", "⌘Enter continues on GitHub.": "⌘EnterでGitHubに進みます。" } diff --git a/assets/locales/ko.json b/assets/locales/ko.json index c10e7f4e1..3f6b3ecbc 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -476,6 +476,7 @@ "Second point": "두 번째 점", "Section": "단면", "Section position": "단면 위치", + "Sections": "단면", "Sections (one sketch each)": "단면 (각각 스케치 하나)", "Select Other": "다른 항목 선택", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "다른 항목 선택: 모델 위에서 왼쪽 버튼을 가만히 누르고 있거나(또는 오른쪽 클릭 › 다른 항목 선택…) 커서 아래의 모든 항목을 나열합니다. 같은 위치를 다시 클릭하면 다음 항목이 선택됩니다. 가운데 버튼을 더블 클릭하면 홈으로 이동합니다(환경설정 › 탐색).", @@ -905,6 +906,9 @@ "cmd.pointcloud_edit": "포인트 클라우드 편집", "cmd.pointcloud_insert": "포인트 클라우드 삽입", "cmd.pointcloud_list": "포인트 클라우드", + "cmd.render.compare.divider": "렌더 비교 구분선 이동", + "cmd.render.result.discard": "렌더 결과 버리기", + "cmd.render.result.select": "렌더 결과 선택", "cmd.render_backends": "렌더링 백엔드", "cmd.render_batch": "모든 샷 렌더링", "cmd.render_camera_fit": "렌더 대상 화면 맞춤", @@ -1110,14 +1114,17 @@ "cmd.view_render_frame": "렌더 프레임 가이드", "cmd.view_save": "새 이름 있는 보기", "cmd.view_shots_strip": "샷 스트립", + "color.blue": "파랑", "color.copy": "클릭하여 색상 값 복사", "color.edit": "클릭하여 색상 편집", "color.gamma": "색상 값을 0-255 감마 공간으로 표시 중", + "color.green": "초록", "color.hex": "Hex", "color.hex_help": "#rrggbb 또는 #rrggbbaa 입력. 6자리 값은 불투명도 유지", "color.hex_hint": "#rrggbb", "color.hue": "색조", "color.linear": "색상 값을 0-1 선형 공간으로 표시 중", + "color.red": "빨강", "color.saturation_value": "채도 및 명도", "color.selected": "선택한 색상", "config.column_filter_empty": "일치하는 열이 없습니다", @@ -1167,7 +1174,11 @@ "dialog.pattern_sketch_not_object": "바디나 피처를 선택하세요. 스케치는 둘 다 아닙니다. 곡선은 스케치 안의 패턴이나 대칭 복사로 반복하거나, 먼저 돌출하세요.", "dialog.select": "↖ 선택", "dialog.selected_count": "↖ {count}개 선택됨", + "dialog.selection_constraint": "구속 조건 {id}", + "dialog.selection_external_curve": "{sketch} · 곡선 {id}", "dialog.selection_guidance": "변경할 입력을 선택하세요. 선택한 객체를 클릭하면 선택이 해제되며, Ctrl/Cmd를 누른 채 클릭해도 전환됩니다. 미리 보기를 확인한 다음 확인을 누르세요.", + "dialog.selection_midpoint": "중점 · {id}", + "dialog.selection_profile": "{sketch} · 프로파일 {number}", "dialog.selection_step": "{step}/{total} 단계: {input} 선택", "dialog.step": "단계", "document.save_changes": "{name}의 변경 사항을 저장하시겠습니까?", @@ -1541,6 +1552,8 @@ "prefs.button_left": "왼쪽 드래그", "prefs.button_middle": "가운데 드래그", "prefs.button_right": "오른쪽 드래그", + "prefs.carousel_next": "다음", + "prefs.carousel_previous": "이전", "prefs.choose_font": "글꼴 파일 선택…", "prefs.click": "클릭", "prefs.contact_shading": "부드러운 접촉 음영", @@ -1553,6 +1566,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "곡면", "prefs.curves": "곡면", + "prefs.cut_preview_tint": "제거되는 재료를 빨간색으로 표시", + "prefs.cut_preview_tint_help": "미리 보기는 피처가 제거하는 재료와 대체되는 형상을 빨간색 반투명 고스트로 채웁니다. 끄면 이 채움이 완전히 투명해지고 윤곽선만 그려집니다.", "prefs.dark_parts_shading": "어두운 부품의 형태 유지", "prefs.dark_parts_shading_help": "선형 조명과 부드러운 하늘광으로 뷰를 음영 처리하여 어두운 면이 검게 뭉개지지 않고 그라데이션을 유지합니다", "prefs.dead_zone_note": "빗금 친 영역이 데드존입니다. 그 안의 움직임은 무시됩니다.", @@ -1639,6 +1654,8 @@ "prefs.persistent_ribbon_pressed_help": "효과가 켜져 있는 동안 리본 명령을 강조 표시합니다. 끄면 이전의 중립적인 모양과 명령 도움말을 유지합니다.", "prefs.perspective_fov": "시야각", "prefs.preview_choices": "선택 항목 미리보기", + "prefs.preview_tint_new_faces": "미리 보기에서 새 면에 색 입히기", + "prefs.preview_tint_new_faces_help": "바디를 변경하는 피처의 미리 보기에서 추가되는 면을 미리 보기 색으로 그릴 수 있습니다. 끄면 바디가 원래 색으로 그려집니다.", "prefs.print_face_highlight": "출력 바닥면 강조", "prefs.print_face_highlight_tip": "뷰에서 바디의 출력 바닥면을 색칠하고 윤곽을 그리는 강도입니다. 0 %이면 강조하지 않습니다.", "prefs.project_options_dialog": "Project 옵션 대화상자", @@ -1829,6 +1846,10 @@ "render.appearances": "외관", "render.assign_help": "클릭하여 선택 항목에 적용하거나 드래그하여 미리 보고 놓으세요. 선택이 없으면 칠하기를 시작합니다.", "render.background": "장면 배경", + "render.batch_all_shots": "모든 샷 ({count})", + "render.batch_empty": "모든 샷을 렌더링하기 전에 샷을 저장하세요.", + "render.batch_limit": "한 번에 최대 32개의 샷을 렌더링할 수 있습니다.", + "render.batch_status": "{running}개 실행 중 · {waiting}개 대기 중", "render.bloom_enable": "표시 블룸", "render.bloom_help": "양의 선형 하이라이트를 세 번의 정규화 필터로 확산하는 출력 전용 효과입니다. 반경은 출력 픽셀 단위이며 sRGB 전에 더합니다. 렌즈·볼륨·수렴 개선이 아니며 원본 EXR은 변하지 않습니다.", "render.bloom_opaque": "블룸에는 불투명 출력이 필요합니다. 투명 PNG를 몰래 합성하지 않고 거부합니다.", @@ -1920,6 +1941,13 @@ "render.children.workstation": "워크스테이션", "render.choose_look": "먼저 외관 라이브러리에서 외관을 선택하세요", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "비교 구분선", + "render.compare_live": "라이브", + "render.compare_live_preview": "라이브 미리보기", + "render.compare_render": "렌더 {number}", + "render.compare_side": "렌더 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds}초 · {renderer} · 리비전 {revision}에서 캡처", + "render.compare_swap": "맞바꾸기", "render.cpu_budget": "CPU 리소스 프로필", "render.cpu_budget_bodies": "바디 수 상한", "render.cpu_budget_compact": "컴팩트 (기존 제한)", @@ -2388,6 +2416,10 @@ "render.result_actual": "100%", "render.result_actual_size": "100%", "render.result_reduced_display": "표시 미리보기를 뷰포트 장치 또는 캐시 제한에 맞춰 축소했습니다. 보관된 PNG와 내보내기는 전체 해상도를 유지합니다. 이 축소 보기에서는 원본 100% 검사가 불가능합니다.", + "render.results_choose": "보관된 결과", + "render.results_label": "렌더 {number} · {shot} · {seconds}초", + "render.results_stale_label": "{result} [이전 버전]", + "render.results_unnamed": "이미지", "render.return_design": "설계로 돌아가기", "render.ribbon_backgrounds": "배경", "render.ribbon_check": "검사", @@ -2935,6 +2967,7 @@ "ui.agent_chat_command": "에이전트 명령", "ui.agent_chat_connect": "연결", "ui.agent_chat_copy": "복사", + "ui.agent_chat_custom_heading": "사용자 지정 모델", "ui.agent_chat_custom_hint": "표준 입출력으로 Agent Client Protocol을 사용하는 모든 프로그램. 셸 없이 실행됩니다.", "ui.agent_chat_denied": "거부함", "ui.agent_chat_deny": "거부", @@ -2976,7 +3009,15 @@ "ui.agent_chat_mode_all": "모두", "ui.agent_chat_mode_ask": "확인", "ui.agent_chat_mode_edits": "편집", + "ui.agent_chat_model_custom": "직접 입력 사용: {model}", + "ui.agent_chat_model_rejected": "에이전트가 {model}을(를) 받아들이지 않았습니다: {error}", + "ui.agent_chat_model_search": "모델 검색…", "ui.agent_chat_model_tip": "에이전트가 사용하는 모델입니다. 선택은 이 에이전트에 기억됩니다.", + "ui.agent_chat_models_failed": "모델 목록을 가져올 수 없습니다: {error}", + "ui.agent_chat_models_heading": "사용 가능한 모델", + "ui.agent_chat_models_listing": "모델 목록을 가져오는 중…", + "ui.agent_chat_models_none": "엔드포인트에 나열된 모델이 없습니다", + "ui.agent_chat_models_not_a_list": "응답이 모델 목록이 아닙니다", "ui.agent_chat_new": "새 채팅", "ui.agent_chat_new_confirm": "새 채팅을 시작할까요? 현재 채팅은 지워집니다.", "ui.agent_chat_next_picture": "다음 이미지", @@ -3497,6 +3538,7 @@ "ui.insert_design.saved_file": "{name}에 저장되지 않은 변경 사항이 있어 저장된 파일을 삽입했습니다. 저장한 다음 링크 업데이트로 변경 사항을 가져오세요.", "ui.insert_design.unsaved": "저장되지 않은 변경 사항", "ui.inspect": "검사", + "ui.instances": "인스턴스", "ui.intersect": "교차", "ui.isolate": "분리 표시", "ui.join": "접합", diff --git a/assets/locales/nl.json b/assets/locales/nl.json index 8d2508440..22f2b541d 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -4706,6 +4706,7 @@ "ui.insert_design.saved_file": "{name} heeft niet-opgeslagen wijzigingen, dus is het opgeslagen bestand ingevoegd. Sla het op en gebruik daarna Koppelingen bijwerken om de wijzigingen over te nemen.", "ui.insert_design.unsaved": "Niet-opgeslagen wijzigingen", "ui.inspect": "Inspecteren", + "ui.instances": "Instanties", "ui.intersect": "Snijden", "ui.isolate": "Isoleren", "ui.join": "Samenvoegen", diff --git a/assets/locales/pending/agent-chat-copy-message.json b/assets/locales/pending/agent-chat-copy-message.json new file mode 100644 index 000000000..cb724aa67 --- /dev/null +++ b/assets/locales/pending/agent-chat-copy-message.json @@ -0,0 +1,9 @@ +{ + "en": { "ui.agent_chat_copy_message": "Copy message" }, + "de": { "ui.agent_chat_copy_message": "Nachricht kopieren" }, + "ar": { "ui.agent_chat_copy_message": "نسخ الرسالة" }, + "he": { "ui.agent_chat_copy_message": "העתק הודעה" }, + "ja": { "ui.agent_chat_copy_message": "メッセージをコピー" }, + "vi": { "ui.agent_chat_copy_message": "Sao chép tin nhắn" }, + "zh": { "ui.agent_chat_copy_message": "复制消息" } +} diff --git a/assets/locales/pending/assistant-shortcut.json b/assets/locales/pending/assistant-shortcut.json new file mode 100644 index 000000000..888dcf986 --- /dev/null +++ b/assets/locales/pending/assistant-shortcut.json @@ -0,0 +1,26 @@ +{ + "ar": { + "cmd.ui.assistant": "إظهار المساعد أو إخفاؤه" + }, + "de": { + "cmd.ui.assistant": "Assistenten ein-/ausblenden" + }, + "en": { + "cmd.ui.assistant": "Toggle Assistant" + }, + "he": { + "cmd.ui.assistant": "הצגה או הסתרה של העוזר" + }, + "ja": { + "cmd.ui.assistant": "アシスタントの表示切り替え" + }, + "ko": { + "cmd.ui.assistant": "도우미 표시 전환" + }, + "vi": { + "cmd.ui.assistant": "Bật/tắt trợ lý" + }, + "zh": { + "cmd.ui.assistant": "切换助手显示" + } +} diff --git a/assets/locales/pending/spline-remove-point.json b/assets/locales/pending/spline-remove-point.json new file mode 100644 index 000000000..17e7511b4 --- /dev/null +++ b/assets/locales/pending/spline-remove-point.json @@ -0,0 +1,31 @@ +{ + "en": { "cmd.sketch_spline_remove_point": "Remove Spline Point" }, + "ar": { "cmd.sketch_spline_remove_point": "إزالة نقطة من المنحنى الشريحي" }, + "bs": { "cmd.sketch_spline_remove_point": "Ukloni tačku splajna" }, + "cs": { "cmd.sketch_spline_remove_point": "Odebrat bod splajnu" }, + "da": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" }, + "de": { "cmd.sketch_spline_remove_point": "Splinepunkt entfernen" }, + "es": { "cmd.sketch_spline_remove_point": "Eliminar punto de spline" }, + "fi": { "cmd.sketch_spline_remove_point": "Poista splinipiste" }, + "fr": { "cmd.sketch_spline_remove_point": "Supprimer un point de spline" }, + "gl": { "cmd.sketch_spline_remove_point": "Eliminar punto do spline" }, + "he": { "cmd.sketch_spline_remove_point": "הסרת נקודה מהספליין" }, + "hr": { "cmd.sketch_spline_remove_point": "Ukloni točku splinea" }, + "hu": { "cmd.sketch_spline_remove_point": "Splinepont eltávolítása" }, + "id": { "cmd.sketch_spline_remove_point": "Hapus Titik Spline" }, + "it": { "cmd.sketch_spline_remove_point": "Rimuovi punto dalla spline" }, + "ja": { "cmd.sketch_spline_remove_point": "スプライン点を削除" }, + "ms": { "cmd.sketch_spline_remove_point": "Buang Titik Splin" }, + "nb": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" }, + "nl": { "cmd.sketch_spline_remove_point": "Splinepunt verwijderen" }, + "pl": { "cmd.sketch_spline_remove_point": "Usuń punkt splajnu" }, + "ro": { "cmd.sketch_spline_remove_point": "Elimină punct din spline" }, + "ru": { "cmd.sketch_spline_remove_point": "Удалить точку сплайна" }, + "sr": { "cmd.sketch_spline_remove_point": "Уклони тачку сплајна" }, + "sv": { "cmd.sketch_spline_remove_point": "Ta bort splinepunkt" }, + "tr": { "cmd.sketch_spline_remove_point": "Spline Noktasını Kaldır" }, + "uk": { "cmd.sketch_spline_remove_point": "Видалити точку сплайна" }, + "vi": { "cmd.sketch_spline_remove_point": "Xóa điểm khỏi đường cong Spline" }, + "zh": { "cmd.sketch_spline_remove_point": "删除样条曲线点" }, + "zh-TW": { "cmd.sketch_spline_remove_point": "刪除雲形線點" } +} diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 8ef9b8c41..f2873bceb 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -2995,6 +2995,7 @@ "ui.insert_design.saved_file": "{name} ma niezapisane zmiany, więc wstawiono jego zapisany plik. Zapisz go, a potem użyj Aktualizuj łącza, aby wprowadzić zmiany.", "ui.insert_design.unsaved": "Niezapisane zmiany", "ui.inspect": "Sprawdź", + "ui.instances": "Wystąpienia", "ui.intersect": "Przytnij", "ui.isolate": "Izoluj", "ui.join": "Połącz", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 4c63bb71a..4dbb4a957 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -2092,6 +2092,7 @@ "ui.infinite": "Infinita", "ui.insert": "Inserir", "ui.inspect": "Inspecionar", + "ui.instances": "Instâncias", "ui.intersect": "Interseção", "ui.isolate": "Isolar", "ui.join": "Unir", diff --git a/assets/locales/sr.json b/assets/locales/sr.json index 5920b7551..089e76bcd 100644 --- a/assets/locales/sr.json +++ b/assets/locales/sr.json @@ -4706,6 +4706,7 @@ "ui.insert_design.saved_file": "Дизајн {name} има несачуване промене, па је уметнута његова сачувана датотека. Сачувајте га, а затим покрените Ажурирај везе да бисте унели промене.", "ui.insert_design.unsaved": "Несачуване промене", "ui.inspect": "Прегледај", + "ui.instances": "Инстанце", "ui.intersect": "Пресек", "ui.isolate": "Изолуј", "ui.join": "Споји", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index b443cf259..f2fe74478 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -4706,6 +4706,7 @@ "ui.insert_design.saved_file": "{name} має незбережені зміни, тому вставлено його збережений файл. Збережіть його, потім оновіть зв'язки, щоб перенести зміни.", "ui.insert_design.unsaved": "Незбережені зміни", "ui.inspect": "Перевірити", + "ui.instances": "Екземпляри", "ui.intersect": "Перетин", "ui.isolate": "Ізолювати", "ui.join": "З'єднати", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 123026c9c..c6dde61c4 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -556,6 +556,7 @@ "Section": "Mặt cắt", "Section (optional)": "Mặt cắt (tùy chọn)", "Section position": "Vị trí mặt cắt", + "Sections": "Các mặt cắt", "Sections (one sketch each)": "Các mặt cắt (mỗi mặt cắt một phác thảo)", "Select Other": "Chọn đối tượng khác", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Chọn đối tượng khác: giữ nút chuột trái đứng yên trên mô hình (hoặc nhấp chuột phải › Chọn đối tượng khác…) để liệt kê mọi đối tượng dưới con trỏ; nhấp lại vào cùng vị trí đó để chọn đối tượng kế tiếp. Nhấp đúp chuột giữa để về Góc nhìn chuẩn (Tùy chọn cài đặt › Điều hướng).", @@ -936,6 +937,11 @@ "cmd.explode_show": "Hiển thị chế độ xem phân rã", "cmd.expr_evaluate": "Tính giá trị biểu thức", "cmd.face_delete": "Xóa mặt", + "cmd.file.export_3mf": "Xuất tệp 3MF", + "cmd.file.export_obj": "Xuất tệp OBJ", + "cmd.file.export_step": "Xuất tệp STEP", + "cmd.file.export_stl": "Xuất tệp STL", + "cmd.file.export_urdf": "Xuất tệp URDF", "cmd.file_export": "Xuất tệp", "cmd.file_insert_mesh": "Chèn lưới đa giác (Mesh)", "cmd.file_insert_step": "Chèn tệp STEP", @@ -953,6 +959,7 @@ "cmd.inspect_colored_components": "Bật màu cụm chi tiết", "cmd.inspect_colored_components_disable": "Tắt màu cụm chi tiết", "cmd.inspect_compare": "So sánh các thân khối", + "cmd.inspect_compare_picture": "So sánh với ảnh tham chiếu", "cmd.inspect_continuity": "Phân tích độ liên tục mặt", "cmd.inspect_curvature_comb": "Phân tích lược độ cong (Curvature Comb)", "cmd.inspect_curvature_map": "Phân tích bản đồ độ cong (Curvature Map)", @@ -1043,6 +1050,9 @@ "cmd.pointcloud_edit": "Chỉnh sửa đám mây điểm", "cmd.pointcloud_insert": "Chèn đám mây điểm", "cmd.pointcloud_list": "Đám mây điểm", + "cmd.render.compare.divider": "Di chuyển vạch so sánh kết xuất", + "cmd.render.result.discard": "Bỏ kết quả kết xuất", + "cmd.render.result.select": "Chọn kết quả kết xuất", "cmd.render_aging_describe": "Lão hóa bề mặt phân lớp", "cmd.render_backends": "Kết xuất hình ảnh Sauends", "cmd.render_batch": "Kết xuất mọi cảnh chụp", @@ -1290,9 +1300,11 @@ "cmd.view_tool": "Công cụ điều hướng", "cmd.view_top": "Góc nhìn từ trên", "cmd.view_visual_style": "Kiểu hiển thị trực quan", + "color.blue": "Xanh dương", "color.copy": "Nhấp để sao chép giá trị màu", "color.edit": "Nhấp để sửa màu", "color.gamma": "Đang hiển thị giá trị màu trong không gian gamma 0-255", + "color.green": "Xanh lá", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", @@ -1300,6 +1312,7 @@ "color.linear": "Đang hiển thị giá trị màu trong không gian tuyến tính 0-1", "color.recent": "Màu gần đây", "color.recent_help": "Các màu bạn chọn ở bất kỳ ô màu nào sẽ hiện ở đây", + "color.red": "Đỏ", "color.saturation": "Độ bão hòa (phần trăm)", "color.saturation_value": "Độ bão hòa và giá trị", "color.selected": "Màu đã chọn", @@ -1357,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "Hãy chọn thân khối hoặc tính năng: bản phác thảo không phải là cả hai. Lặp lại các đường cong của nó bằng Mảng hoặc Lấy đối xứng trong chính bản phác thảo, hoặc đùn khối nó trước.", "dialog.select": "↖ Chọn", "dialog.selected_count": "↖ {count} đã chọn", + "dialog.selection_constraint": "Ràng buộc {id}", + "dialog.selection_external_curve": "{sketch} · đường cong {id}", "dialog.selection_guidance": "Chọn một mục đầu vào để thay đổi. Nhấp vào đối tượng đã chọn để bỏ chọn; Ctrl/Cmd-nhấp để bật/tắt chọn. Xem trước kết quả, sau đó nhấn OK.", + "dialog.selection_midpoint": "Trung điểm · {id}", + "dialog.selection_profile": "{sketch} · biên dạng {number}", "dialog.selection_step": "{step} / {total}: Chọn {input}", "dialog.step": "Bước", "document.changed_on_disk": "{name} đã thay đổi trên đĩa", @@ -2139,6 +2156,8 @@ "prefs.button_left": "Kéo chuột trái", "prefs.button_middle": "Kéo chuột giữa", "prefs.button_right": "Kéo chuột phải", + "prefs.carousel_next": "Tiếp", + "prefs.carousel_previous": "Trước", "prefs.choose_font": "Chọn tệp phông chữ…", "prefs.click": "Nhấp chuột", "prefs.contact_shading": "Đổ bóng tiếp xúc mềm", @@ -2151,6 +2170,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Các mặt cong", "prefs.curves": "Các đường cong", + "prefs.cut_preview_tint": "Hiển thị vật liệu bị loại bỏ bằng màu đỏ", + "prefs.cut_preview_tint_help": "Bản xem trước tô vật liệu mà đặc trưng loại bỏ, và hình dạng mà nó thay thế, bằng một bóng mờ màu đỏ. Khi tắt, các phần tô này hoàn toàn trong suốt và chỉ vẽ đường viền của chúng.", "prefs.dark_parts_shading": "Giữ hình dạng của chi tiết tối", "prefs.dark_parts_shading_help": "Tô bóng khung nhìn bằng ánh sáng tuyến tính với ánh sáng bầu trời dịu, để các mặt tối giữ được dải chuyển màu thay vì thành màu đen", "prefs.dead_zone_note": "Dải sọc chéo là vùng chết: các chuyển động bên trong vùng này sẽ bị bỏ qua.", @@ -2270,6 +2291,8 @@ "prefs.placement": "Vị trí đặt", "prefs.prefer_free_sketch_points": "Ưu tiên điểm phác thảo có thể di chuyển khi các điểm chồng lên nhau", "prefs.preview_choices": "Xem trước các lựa chọn của bạn", + "prefs.preview_tint_new_faces": "Tô màu bề mặt mới trong bản xem trước", + "prefs.preview_tint_new_faces_help": "Bản xem trước của một đặc trưng làm thay đổi một khối có thể vẽ bề mặt được thêm vào bằng màu xem trước. Khi tắt, khối được vẽ bằng màu của chính nó.", "prefs.print_face_highlight": "Tô sáng mặt in", "prefs.print_face_highlight_tip": "Mức tô màu và viền mặt in của thân trong khung nhìn. 0 % không tô sáng.", "prefs.profile_active": "Hồ sơ đang dùng", @@ -2567,6 +2590,10 @@ "render.base_color": "Màu cơ sở · sRGB", "render.base_metallic": "Tỷ lệ kim loại", "render.base_opaque_only": "Trình chỉnh sửa này giữ nguyên ngữ nghĩa khối đục. Dùng các điều khiển thủy tinh riêng biệt để chỉnh độ truyền quang học.", + "render.batch_all_shots": "Mọi cảnh chụp ({count})", + "render.batch_empty": "Hãy lưu một cảnh chụp trước khi kết xuất mọi cảnh chụp.", + "render.batch_limit": "Kết xuất mọi cảnh chụp giới hạn ở 32 cảnh chụp.", + "render.batch_status": "{running} đang chạy · {waiting} đang chờ", "render.bloom_enable": "Hiển thị lóe sáng (Bloom)", "render.bloom_help": "Hiệu ứng phát sáng sáng tạo cho đầu ra từ các điểm nhấn tuyến tính dương, được khuếch tán qua ba lượt lọc chuẩn hóa. Bán kính tính theo pixel đầu ra. Được cộng vào ánh sáng tuyến tính hiển thị trước sRGB; không phải ống kính thực tế, hiệu ứng thể tích hay cải thiện hội tụ. Tệp EXR thô không đổi.", "render.bloom_opaque": "Hiệu ứng lóe sáng yêu cầu đầu ra đục. PNG trong suốt sẽ bị từ chối chứ không âm thầm làm phẳng nền.", @@ -2677,6 +2704,13 @@ "render.choose_look": "Hãy chọn một diện mạo trong Diện mạo trước", "render.chromatic_offset": "Độ lệch sắc sai viền", "render.clear_stage": "Xóa sân khấu đã lưu", + "render.compare_divider": "Vạch so sánh", + "render.compare_live": "Trực tiếp", + "render.compare_live_preview": "Xem trước trực tiếp", + "render.compare_render": "Kết xuất {number}", + "render.compare_side": "Kết xuất {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} giây · {renderer} · ghi tại bản sửa {revision}", + "render.compare_swap": "Hoán đổi", "render.copy_request": "Sao chép JSON", "render.cpu_aa_help": "Số mẫu không gian: tăng số mẫu giúp cạnh mượt hơn nhưng tăng thời gian kết xuất.", "render.cpu_area_add": "Thêm nguồn sáng vùng chữ nhật CPU", @@ -3426,6 +3460,10 @@ "render.result_retained": "Đang hiển thị hình ảnh hoàn thành gần nhất; kết xuất mới hơn chưa thay thế nó.", "render.result_sequence": "Điểm kiểm tra trung gian", "render.result_title": "Kết quả kết xuất", + "render.results_choose": "Kết quả được giữ lại", + "render.results_label": "Kết xuất {number} · {shot} · {seconds} giây", + "render.results_stale_label": "{result} [cũ]", + "render.results_unnamed": "Ảnh", "render.return_design": "Quay lại thiết kế", "render.review_stale": "Kết quả xem xét này đã cũ. Hãy xử lý hoặc kiểm tra lại trước khi áp dụng.", "render.ribbon_aging": "Lão hóa", @@ -4097,6 +4135,7 @@ "ui.agent_chat_ctx_features": "Tính năng", "ui.agent_chat_ctx_more": "+{n} mục khác", "ui.agent_chat_ctx_other": "Khác", + "ui.agent_chat_custom_heading": "Mô hình tùy chỉnh", "ui.agent_chat_custom_hint": "Bất kỳ chương trình nào hỗ trợ giao thức Agent Client Protocol qua stdin và stdout. Không chạy qua shell hệ thống.", "ui.agent_chat_denied": "Đã từ chối", "ui.agent_chat_deny": "Từ chối", @@ -4140,8 +4179,16 @@ "ui.agent_chat_mode_all": "Tất cả", "ui.agent_chat_mode_ask": "Hỏi", "ui.agent_chat_mode_edits": "Chỉnh sửa", + "ui.agent_chat_model_custom": "Dùng tùy chỉnh: {model}", "ui.agent_chat_model_no_tools": "{model} không thể sử dụng các công cụ của SolidCraft nên chỉ có thể trò chuyện. Hãy chọn mô hình có hỗ trợ công cụ.", + "ui.agent_chat_model_rejected": "Tác tử không chấp nhận {model}: {error}", + "ui.agent_chat_model_search": "Tìm mô hình…", "ui.agent_chat_model_tip": "Mô hình AI đang sử dụng. Lựa chọn của bạn sẽ được ghi nhớ cho Agent này.", + "ui.agent_chat_models_failed": "Không thể lấy danh sách mô hình: {error}", + "ui.agent_chat_models_heading": "Các mô hình có sẵn", + "ui.agent_chat_models_listing": "Đang lấy danh sách mô hình…", + "ui.agent_chat_models_none": "Điểm cuối không liệt kê mô hình nào", + "ui.agent_chat_models_not_a_list": "Phản hồi không phải là danh sách mô hình", "ui.agent_chat_new": "Cuộc trò chuyện mới", "ui.agent_chat_new_confirm": "Bắt đầu cuộc trò chuyện mới? Cuộc trò chuyện hiện tại sẽ bị xóa.", "ui.agent_chat_next_picture": "Ảnh kế tiếp", @@ -4723,6 +4770,7 @@ "ui.insert_design.saved_file": "{name} có thay đổi chưa lưu, nên tệp đã lưu của nó đã được chèn. Hãy lưu nó, rồi dùng Cập nhật liên kết để đưa các thay đổi vào.", "ui.insert_design.unsaved": "Thay đổi chưa lưu", "ui.inspect": "Kiểm tra", + "ui.instances": "Số bản", "ui.intersect": "Giao nhau", "ui.isolate": "Cô lập đối tượng", "ui.join": "Nối liền", @@ -5214,6 +5262,7 @@ "web.open_link": "Mở thiết kế liên kết?", "web.open_link_confirm": "Có những thay đổi chưa lưu. Mở thiết kế liên kết trong tab mới?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ chọn · Enter / Tab hoàn tất · Esc bỏ qua", + "↑ ↓ choose · Enter applies this value": "↑ ↓ để chọn · Enter để áp dụng giá trị này", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ để chọn · Enter để áp dụng nội dung đã nhập · Esc để đóng", "⌘Enter continues on GitHub.": "Nhấn ⌘Enter để tiếp tục trên GitHub." } diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index fd463a62c..efa82f87d 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -4708,6 +4708,7 @@ "ui.insert_design.saved_file": "{name} 有未儲存的變更,因此插入的是其已儲存的檔案。請儲存後執行「更新連結」以帶入變更。", "ui.insert_design.unsaved": "未儲存的變更", "ui.inspect": "檢查", + "ui.instances": "實例數", "ui.intersect": "相交", "ui.isolate": "隔離", "ui.join": "接合", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 649f2807a..4599dd401 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -556,6 +556,7 @@ "Section": "剖面", "Section (optional)": "截面(可选)", "Section position": "截面位置", + "Sections": "截面", "Sections (one sketch each)": "截面(每个一个草图)", "Select Other": "选择其他", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。", @@ -936,6 +937,11 @@ "cmd.explode_show": "显示爆炸图", "cmd.expr_evaluate": "计算表达式", "cmd.face_delete": "删除面", + "cmd.file.export_3mf": "导出 3MF", + "cmd.file.export_obj": "导出 OBJ", + "cmd.file.export_step": "导出 STEP", + "cmd.file.export_stl": "导出 STL", + "cmd.file.export_urdf": "导出 URDF", "cmd.file_export": "导出", "cmd.file_insert_mesh": "插入网格", "cmd.file_insert_step": "插入 STEP", @@ -953,6 +959,7 @@ "cmd.inspect_colored_components": "启用组件颜色", "cmd.inspect_colored_components_disable": "禁用组件颜色", "cmd.inspect_compare": "比较实体", + "cmd.inspect_compare_picture": "比较参考图", "cmd.inspect_continuity": "连续性分析", "cmd.inspect_curvature_comb": "曲率梳分析", "cmd.inspect_curvature_map": "曲率图分析", @@ -1043,6 +1050,9 @@ "cmd.pointcloud_edit": "编辑点云", "cmd.pointcloud_insert": "插入点云", "cmd.pointcloud_list": "点云", + "cmd.render.compare.divider": "移动渲染比较分隔线", + "cmd.render.result.discard": "丢弃渲染结果", + "cmd.render.result.select": "选择渲染结果", "cmd.render_aging_describe": "分层表面老化", "cmd.render_backends": "渲染后端", "cmd.render_batch": "渲染所有镜头", @@ -1290,9 +1300,11 @@ "cmd.view_tool": "导航工具", "cmd.view_top": "俯视图", "cmd.view_visual_style": "视觉样式", + "color.blue": "蓝色", "color.copy": "单击复制颜色值", "color.edit": "单击编辑颜色", "color.gamma": "以 0–255 伽马空间显示颜色值", + "color.green": "绿色", "color.hex": "Hex", "color.hex_help": "输入 #rrggbb 或 #rrggbbaa;六位数保留不透明度", "color.hex_hint": "#rrggbb", @@ -1300,6 +1312,7 @@ "color.linear": "以 0–1 线性空间显示颜色值", "color.recent": "最近使用的颜色", "color.recent_help": "在任意颜色字段中选择的颜色会显示在这里", + "color.red": "红色", "color.saturation": "饱和度(百分比)", "color.saturation_value": "饱和度和明度", "color.selected": "所选颜色", @@ -1357,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "请选择实体或特征:草图两者都不是。请用草图自身的阵列或镜像重复其曲线,或先将其拉伸。", "dialog.select": "↖ 选择", "dialog.selected_count": "↖ 已选择 {count} 个", + "dialog.selection_constraint": "约束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲线 {id}", "dialog.selection_guidance": "选择输入项进行修改。点击已选对象可取消选择;按住 Ctrl/Cmd 点击也可切换选择。检查预览后,再按“确定”。", + "dialog.selection_midpoint": "中点 · {id}", + "dialog.selection_profile": "{sketch} · 轮廓 {number}", "dialog.selection_step": "第 {step} 步,共 {total} 步:选择{input}", "dialog.step": "步骤", "document.changed_on_disk": "{name} 已在磁盘上更改", @@ -2139,6 +2156,8 @@ "prefs.button_left": "左键拖动", "prefs.button_middle": "中键拖动", "prefs.button_right": "右键拖动", + "prefs.carousel_next": "下一个", + "prefs.carousel_previous": "上一个", "prefs.choose_font": "选择字体文件…", "prefs.click": "单击", "prefs.contact_shading": "柔和接触阴影", @@ -2151,6 +2170,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "曲面", "prefs.curves": "曲面", + "prefs.cut_preview_tint": "以红色显示被移除的材料", + "prefs.cut_preview_tint_help": "预览会用红色半透明幻影填充特征所移除的材料以及被替换的形状。关闭时,这些填充完全透明,仅绘制其轮廓。", "prefs.dark_parts_shading": "保持深色零件的形状", "prefs.dark_parts_shading_help": "以线性光照和柔和的天空补光着色视图,使深色面保留渐变而不变成一片黑色", "prefs.dead_zone_note": "斜线区域为死区:此范围内的移动将被忽略。", @@ -2270,6 +2291,8 @@ "prefs.placement": "放置", "prefs.prefer_free_sketch_points": "草图点重合时优先选择可移动的点", "prefs.preview_choices": "所选设置预览", + "prefs.preview_tint_new_faces": "在预览中为新表面着色", + "prefs.preview_tint_new_faces_help": "更改实体的特征,其预览可以用预览颜色绘制新增的表面。关闭时,实体按自身颜色绘制。", "prefs.print_face_highlight": "打印底面高亮", "prefs.print_face_highlight_tip": "视图中实体打印底面的着色和轮廓强度。0 % 不显示高亮。", "prefs.profile_active": "当前配置文件", @@ -2567,6 +2590,10 @@ "render.base_color": "基础颜色 · sRGB", "render.base_metallic": "金属比例", "render.base_opaque_only": "此编辑器保留不透明实体语义;光学透射请使用明确的玻璃控件。", + "render.batch_all_shots": "所有镜头 ({count})", + "render.batch_empty": "渲染所有镜头前请先保存镜头。", + "render.batch_limit": "一次最多渲染32个镜头。", + "render.batch_status": "{running} 个运行中 · {waiting} 个等待中", "render.bloom_enable": "显示泛光", "render.bloom_help": "仅用于输出的创意辉光,将正线性高光经过三次归一化滤波扩散。半径以输出像素计,在 sRGB 前叠加;不模拟镜头或体积,也不改善收敛。原始 EXR 不变。", "render.bloom_opaque": "泛光需要不透明输出;会拒绝透明 PNG,而非暗中合成背景。", @@ -2677,6 +2704,13 @@ "render.choose_look": "请先在外观库中选择外观", "render.chromatic_offset": "边缘色差偏移", "render.clear_stage": "移除已保存的舞台", + "render.compare_divider": "比较分隔线", + "render.compare_live": "实时", + "render.compare_live_preview": "实时预览", + "render.compare_render": "渲染 {number}", + "render.compare_side": "渲染 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · 捕获于修订版 {revision}", + "render.compare_swap": "交换", "render.copy_request": "复制 JSON", "render.cpu_aa_help": "增加空间采样可改善边缘,但会增加渲染时间。", "render.cpu_area_add": "添加 CPU 矩形光源", @@ -3426,6 +3460,10 @@ "render.result_retained": "正在显示最后完成的图像;较新的渲染尚未替换它。", "render.result_sequence": "中间结果", "render.result_title": "渲染结果", + "render.results_choose": "保留的结果", + "render.results_label": "渲染 {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [已过期]", + "render.results_unnamed": "图像", "render.return_design": "返回设计", "render.review_stale": "此审阅结果已过期;应用前请重新解析或检查。", "render.ribbon_aging": "老化", @@ -4097,6 +4135,7 @@ "ui.agent_chat_ctx_features": "特征", "ui.agent_chat_ctx_more": "另有 {n} 项", "ui.agent_chat_ctx_other": "其他", + "ui.agent_chat_custom_heading": "自定义模型", "ui.agent_chat_custom_hint": "任何通过标准输入输出使用 Agent Client Protocol 的程序。不经过 shell 运行。", "ui.agent_chat_denied": "已拒绝", "ui.agent_chat_deny": "拒绝", @@ -4140,8 +4179,16 @@ "ui.agent_chat_mode_all": "全部", "ui.agent_chat_mode_ask": "询问", "ui.agent_chat_mode_edits": "编辑", + "ui.agent_chat_model_custom": "使用自定义:{model}", "ui.agent_chat_model_no_tools": "{model} 无法使用 SolidCraft 的工具,只能聊天。请选择支持工具的模型。", + "ui.agent_chat_model_rejected": "智能体未接受 {model}:{error}", + "ui.agent_chat_model_search": "搜索模型…", "ui.agent_chat_model_tip": "智能体使用的模型。你的选择会为此智能体记住。", + "ui.agent_chat_models_failed": "无法列出模型:{error}", + "ui.agent_chat_models_heading": "可用模型", + "ui.agent_chat_models_listing": "正在列出模型…", + "ui.agent_chat_models_none": "该端点未列出任何模型", + "ui.agent_chat_models_not_a_list": "响应不是模型列表", "ui.agent_chat_new": "新对话", "ui.agent_chat_new_confirm": "开始新对话?当前对话将被清除。", "ui.agent_chat_next_picture": "下一张图片", @@ -4723,6 +4770,7 @@ "ui.insert_design.saved_file": "{name} 有未保存的更改,因此插入的是其已保存的文件。请先保存,再使用“更新链接”导入这些更改。", "ui.insert_design.unsaved": "未保存的更改", "ui.inspect": "检查", + "ui.instances": "实例数", "ui.intersect": "相交", "ui.isolate": "隔离", "ui.join": "连接", @@ -5214,6 +5262,7 @@ "web.open_link": "打开链接的设计?", "web.open_link_confirm": "有未保存的更改。要在新标签页中打开链接的设计吗?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 选择 · Enter / Tab 补全 · Esc 关闭", + "↑ ↓ choose · Enter applies this value": "↑ ↓ 选择 · Enter 应用此值", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 选择 · Enter 按原样应用 · Esc 关闭", "⌘Enter continues on GitHub.": "按⌘Enter在GitHub中继续。" } diff --git a/assets/styles/ui/palettes.rs b/assets/styles/ui/palettes.rs index afad473f8..6a1ba653d 100644 --- a/assets/styles/ui/palettes.rs +++ b/assets/styles/ui/palettes.rs @@ -231,6 +231,28 @@ impl Tokens { dialog_label: Color32::from_rgb(58, 70, 86), selected_ink: Color32::from_rgb(26, 80, 127), selected_bg: Color32::from_rgb(232, 241, 250), + figure_ground: Color32::from_rgb(247, 248, 250), + figure_line: Color32::from_rgb(111, 124, 143), + figure_face_top: Color32::from_rgb(255, 255, 255), + figure_face_left: Color32::from_rgb(228, 233, 240), + figure_face_right: Color32::from_rgb(201, 210, 222), + figure_card: Color32::from_rgb(255, 255, 255), + figure_white: Color32::WHITE, + figure_black: Color32::BLACK, + figure_accent: Color32::from_rgb(35, 110, 173), + figure_reference: Color32::from_rgb(138, 83, 0), + figure_axis_x: Color32::from_rgb(214, 69, 69), + figure_axis_y: Color32::from_rgb(46, 158, 91), + figure_axis_z: Color32::from_rgb(47, 111, 208), + figure_ok: Color32::from_rgb(47, 125, 91), + figure_warn: Color32::from_rgb(201, 138, 0), + pref_well: Color32::from_rgb(238, 241, 245), + pref_note: Color32::from_rgb(184, 74, 0), + pref_note_fill: Color32::from_rgb(251, 235, 221), + pref_on_accent: Color32::from_rgb(255, 255, 255), + pref_ok: Color32::from_rgb(39, 107, 44), + pref_ok_fill: Color32::from_rgb(229, 242, 230), + pref_disabled: Color32::from_rgb(138, 148, 163), timeline_item: Color32::WHITE, timeline_item_error: Color32::from_rgb(250, 220, 220), timeline_marker: Color32::from_rgb(70, 76, 88), @@ -352,6 +374,26 @@ impl Tokens { t.dialog_label = t.text; t.selected_ink = Color32::from_rgb(156, 199, 245); t.selected_bg = Color32::from_rgb(42, 70, 110); + t.figure_ground = Color32::from_rgb(28, 31, 38); + t.figure_line = Color32::from_rgb(163, 174, 194); + t.figure_face_top = Color32::from_rgb(107, 119, 144); + t.figure_face_left = Color32::from_rgb(81, 91, 114); + t.figure_face_right = Color32::from_rgb(57, 66, 86); + t.figure_card = Color32::from_rgb(47, 52, 62); + t.figure_accent = Color32::from_rgb(140, 190, 245); + t.figure_reference = Color32::from_rgb(232, 194, 74); + t.figure_axis_x = Color32::from_rgb(242, 122, 122); + t.figure_axis_y = Color32::from_rgb(98, 212, 142); + t.figure_axis_z = Color32::from_rgb(108, 168, 247); + t.figure_ok = Color32::from_rgb(127, 209, 174); + t.figure_warn = Color32::from_rgb(232, 194, 74); + t.pref_well = Color32::from_rgb(47, 52, 62); + t.pref_note = Color32::from_rgb(240, 162, 122); + t.pref_note_fill = Color32::from_rgb(74, 51, 38); + t.pref_on_accent = Color32::from_rgb(15, 22, 32); + t.pref_ok = Color32::from_rgb(127, 209, 174); + t.pref_ok_fill = Color32::from_rgb(31, 58, 49); + t.pref_disabled = Color32::from_rgb(138, 148, 163); t.construction_geom = icon_primary(crate::icon_svg::CONSTRUCTION_PRIMARY[1]); t.error = Color32::from_rgb(240, 100, 96); t.sketch_conflict = t.error; diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 67c038323..05c17aca3 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2550,6 +2550,169 @@ impl FeatureKind { FeatureKind::Repair { .. } => "RepairFeature", } } + + /// Design-file variant key (e.g. `"extrude"`, `"box"`, `"sheet_flange"`). + pub fn kind_key(&self) -> &'static str { + match self { + FeatureKind::BodyTransfer { .. } => "body_transfer", + FeatureKind::Sketch { .. } => "sketch", + FeatureKind::Extrude { .. } => "extrude", + FeatureKind::Revolve { .. } => "revolve", + FeatureKind::Fillet { .. } => "fillet", + FeatureKind::Chamfer { .. } => "chamfer", + FeatureKind::Box { .. } => "box", + FeatureKind::Cylinder { .. } => "cylinder", + FeatureKind::Sphere { .. } => "sphere", + FeatureKind::Torus { .. } => "torus", + FeatureKind::Cone { .. } => "cone", + FeatureKind::Combine { .. } => "combine", + FeatureKind::Pattern { .. } => "pattern", + FeatureKind::Mirror { .. } => "mirror", + FeatureKind::Hole { .. } => "hole", + FeatureKind::Thread { .. } => "thread", + FeatureKind::Loft { .. } => "loft", + FeatureKind::Sweep { .. } => "sweep", + FeatureKind::Shell { .. } => "shell", + FeatureKind::Draft { .. } => "draft", + FeatureKind::ConstructionPlane { .. } => "construction_plane", + FeatureKind::Split { .. } => "split", + FeatureKind::ConstructionAxis { .. } => "construction_axis", + FeatureKind::ConstructionPoint { .. } => "construction_point", + FeatureKind::SplitFace { .. } => "split_face", + FeatureKind::Scale { .. } => "scale", + FeatureKind::OffsetFace { .. } => "offset_face", + FeatureKind::DeleteFace { .. } => "delete_face", + FeatureKind::BoundingSolid { .. } => "bounding_solid", + FeatureKind::Pipe { .. } => "pipe", + FeatureKind::FrameMember { .. } => "frame_member", + FeatureKind::Emboss { .. } => "emboss", + FeatureKind::Rib { .. } => "rib", + FeatureKind::ReplaceFace { .. } => "replace_face", + FeatureKind::Align { .. } => "align", + FeatureKind::Coil { .. } => "coil", + FeatureKind::SheetBase { .. } => "sheet_base", + FeatureKind::SheetContour { .. } => "sheet_contour", + FeatureKind::SheetFlange { .. } => "sheet_flange", + FeatureKind::SheetHem { .. } => "sheet_hem", + FeatureKind::SheetPerforate { .. } => "sheet_perforate", + FeatureKind::SheetFold { .. } => "sheet_fold", + FeatureKind::SheetPath { .. } => "sheet_path", + FeatureKind::SheetUnfold { .. } => "sheet_unfold", + FeatureKind::SheetConvert { .. } => "sheet_convert", + FeatureKind::Boss { .. } => "boss", + FeatureKind::Lip { .. } => "lip", + FeatureKind::SnapFit { .. } => "snap_fit", + FeatureKind::Rest { .. } => "rest", + FeatureKind::BoundaryFill { .. } => "boundary_fill", + FeatureKind::Remove { .. } => "remove", + FeatureKind::Patch { .. } => "patch", + FeatureKind::Stitch { .. } => "stitch", + FeatureKind::Thicken { .. } => "thicken", + FeatureKind::SurfaceExtrude { .. } => "surface_extrude", + FeatureKind::Unstitch { .. } => "unstitch", + FeatureKind::ReverseNormal { .. } => "reverse_normal", + FeatureKind::SurfaceUntrim { .. } => "surface_untrim", + FeatureKind::SurfaceRevolve { .. } => "surface_revolve", + FeatureKind::SurfaceSweep { .. } => "surface_sweep", + FeatureKind::SurfaceLoft { .. } => "surface_loft", + FeatureKind::SurfaceOffset { .. } => "surface_offset", + FeatureKind::SurfaceRuled { .. } => "surface_ruled", + FeatureKind::SurfaceExtend { .. } => "surface_extend", + FeatureKind::SurfaceBlend { .. } => "surface_blend", + FeatureKind::SurfaceBoundary { .. } => "surface_boundary", + FeatureKind::SurfaceNetwork { .. } => "surface_network", + FeatureKind::SurfaceMatch { .. } => "surface_match", + FeatureKind::SurfaceFair { .. } => "surface_fair", + FeatureKind::SurfaceTrim { .. } => "surface_trim", + FeatureKind::Move { .. } => "move", + FeatureKind::Import { .. } => "import", + FeatureKind::MeshConvert { .. } => "mesh_convert", + FeatureKind::MeshImport { .. } => "mesh_import", + FeatureKind::Repair { .. } => "repair", + } + } + + /// Map a display or Rust type name (e.g. `"HoleFeature"`, `"EdgeFlangeFeature"`) + /// to the canonical design-file variant key (`"hole"`, `"sheet_flange"`). + pub fn type_name_to_kind_key(name: &str) -> Option<&'static str> { + Some(match name { + "BodyTransferFeature" => "body_transfer", + "Sketch" => "sketch", + "ExtrudeFeature" => "extrude", + "RevolveFeature" => "revolve", + "FilletFeature" => "fillet", + "ChamferFeature" => "chamfer", + "BoxFeature" => "box", + "CylinderFeature" => "cylinder", + "SphereFeature" => "sphere", + "TorusFeature" => "torus", + "ConeFeature" => "cone", + "CombineFeature" => "combine", + "RectangularPatternFeature" | "PathPatternFeature" | "CircularPatternFeature" => "pattern", + "MirrorFeature" => "mirror", + "ConstructionPlane" => "construction_plane", + "HoleFeature" => "hole", + "ThreadFeature" => "thread", + "LoftFeature" => "loft", + "SweepFeature" => "sweep", + "ShellFeature" => "shell", + "DraftFeature" => "draft", + "SplitBodyFeature" => "split", + "SplitFaceFeature" => "split_face", + "ConstructionAxis" => "construction_axis", + "ConstructionPoint" => "construction_point", + "MoveFeature" => "move", + "ScaleFeature" => "scale", + "OffsetFacesFeature" => "offset_face", + "DeleteFaceFeature" => "delete_face", + "OffsetSurfaceFeature" => "surface_offset", + "BoundingSolidFeature" => "bounding_solid", + "PipeFeature" => "pipe", + "FrameMemberFeature" => "frame_member", + "EmbossFeature" => "emboss", + "BossFeature" => "boss", + "LipFeature" | "GrooveFeature" => "lip", + "SnapFitFeature" => "snap_fit", + "RestFeature" => "rest", + "BoundaryFillFeature" => "boundary_fill", + "BaseFlangeFeature" => "sheet_base", + "ContourFlangeFeature" => "sheet_contour", + "EdgeFlangeFeature" => "sheet_flange", + "HemFeature" => "sheet_hem", + "PerforateFeature" => "sheet_perforate", + "FoldFeature" => "sheet_fold", + "PathFlangeFeature" => "sheet_path", + "UnfoldFeature" | "RefoldFeature" => "sheet_unfold", + "ConvertToSheetMetalFeature" => "sheet_convert", + "CoilFeature" => "coil", + "RibFeature" | "WebFeature" => "rib", + "ReplaceFaceFeature" => "replace_face", + "AlignFeature" => "align", + "RemoveFeature" => "remove", + "PatchFeature" => "patch", + "SurfaceExtrudeFeature" => "surface_extrude", + "SurfaceRevolveFeature" => "surface_revolve", + "SurfaceSweepFeature" => "surface_sweep", + "SurfaceLoftFeature" => "surface_loft", + "BlendFeature" => "surface_blend", + "BoundaryFeature" => "surface_boundary", + "MatchFeature" => "surface_match", + "FairFeature" => "surface_fair", + "StitchFeature" => "stitch", + "ThickenFeature" => "thicken", + "TrimFeature" => "surface_trim", + "ExtendFeature" => "surface_extend", + "RuledSurfaceFeature" => "surface_ruled", + "UnstitchFeature" => "unstitch", + "ReverseNormalFeature" => "reverse_normal", + "UntrimFeature" => "surface_untrim", + "BaseFeature" => "import", + "MeshFeature" => "mesh_import", + "MeshConvertFeature" => "mesh_convert", + "RepairFeature" => "repair", + _ => return None, + }) + } /// Default name prefix (`Extrude` → `Extrude1`). pub fn base_name(&self) -> &'static str { match self { @@ -3727,12 +3890,18 @@ impl Document { } else { 0 }; - let id = self.next_id.max(1); - self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let name = match name { Some(n) if !n.trim().is_empty() => n.trim().to_string(), _ => self.unique_name(kind.base_name()), }; + // Plane references share the feature namespace. A duplicate would silently select + // the first feature. Other shared names (a sketch and its extrude) remain supported. + let is_plane = matches!(kind, FeatureKind::ConstructionPlane { .. }); + if self.features.iter().any(|f| f.name == name && (is_plane || matches!(f.kind, FeatureKind::ConstructionPlane { .. }))) { + return Err(DocError::Invalid(format!("another feature is called `{name}`"))); + } + let id = self.next_id.max(1); + self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let f = Feature { id, name, diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index d094ef24d..f48c619b1 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4595,6 +4595,29 @@ pub fn revolve_extent_with_convention( symmetric: bool, to: Option, convention: crate::RevolveConvention, +) -> Result { + let extent = revolve_extent_for_handle(st, plane, regions, (origin, axis), (angle, angle2), symmetric, to, convention)?; + // A solid needs an open sweep inside one full turn. Zero and a turn past 360° keep a + // handle frame (`revolve_extent_for_handle`) and still fail here, with the same message. + if !(extent.sweep.abs() > 1e-9 && extent.sweep.abs() <= std::f64::consts::TAU + 1e-9) { + return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into())); + } + Ok(extent) +} + +/// Where the angle handle sits. A sweep of zero, or past a full turn, builds no solid and +/// [`revolve_extent_with_convention`] refuses it. The boundary is still a point on the circle, +/// and the grab point stays there so the angle can be dragged back into range. +#[allow(clippy::too_many_arguments)] +pub fn revolve_extent_for_handle( + st: &ModelState, + plane: &Plane, + regions: &[Region2], + (origin, axis): (Vec3, Vec3), + (angle, angle2): (f64, Option), + symmetric: bool, + to: Option, + convention: crate::RevolveConvention, ) -> Result { let (start, sweep) = match (to, angle2, symmetric) { (Some(point), _, _) => { @@ -4634,7 +4657,7 @@ pub fn revolve_extent_with_convention( (None, None, true) => (-angle / 2.0, angle), (None, None, false) => (0.0, angle), }; - if !(sweep.is_finite() && start.is_finite() && sweep.abs() > 1e-9 && sweep.abs() <= std::f64::consts::TAU + 1e-9) { + if !(sweep.is_finite() && start.is_finite()) { return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into())); } let points: Vec = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect(); @@ -6563,7 +6586,7 @@ fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> } let note = if !crate::naming::face_name_exact(b, hit.face) && (face.centroid - at).dot(n).abs() > tol { // Named from geometry and moved off the picked plane: geometry alone decided. - Some(format!("face `{name}` was found by geometry, not exact history; check it")) + Some(format!("face `{}` was found by geometry, not exact history; check it", crate::name_lookup::quoted(name))) } else { None }; diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rs index 40540151b..a6cd5c9a0 100644 --- a/crates/doc/src/eval_cost_tests.rs +++ b/crates/doc/src/eval_cost_tests.rs @@ -174,6 +174,25 @@ fn joint_face_measurements_never_follow_a_replaced_body_or_stale_offset() { assert_eq!(work.joint_faces, 0, "offsets are applied after the shared face measurements"); } +/// Every solve of a drag resolves its edge origins again: they share the joint faces' one +/// measurement, as a face origin does, instead of tessellating the whole body each time. +#[test] +fn an_edge_origin_measures_its_faces_once() { + use crate::joints::{JointOrigin, Snap}; + let doc = Document::new("edge origin"); + let mut state = ModelState::default(); + state.bodies.push(ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(), 0)); + let pick = Vec3::new(5.0, 0.0, 10.0); + let origin = JointOrigin { occurrence: 0, snap: Snap::Edge { pick, edge: None, face: None, corner: None, axis: None } }; + let work = counted(|| { + for _ in 0..8 { + let frame = joints::resolve_origin(&doc, &state.clone(), &origin).unwrap(); + assert!(apply_point(&frame, Vec3::ZERO).dist(pick) < 1e-9); + } + }); + assert_eq!(work.joint_faces, 1, "a solve must not measure the faces again: {work:?}"); +} + /// `parts` imported files of two boxes each, every one in its own component placed away from /// the origin (as inserted parts are). fn placed_imports(parts: usize) -> Document { diff --git a/crates/doc/src/joints_edge.rs b/crates/doc/src/joints_edge.rs index c2fd1ed7a..836e3f50c 100644 --- a/crates/doc/src/joints_edge.rs +++ b/crates/doc/src/joints_edge.rs @@ -50,7 +50,7 @@ fn edge_index(b: &ModelBody, name: Option<&str>, pick: Vec3) -> Option { fn face_of(b: &ModelBody, i: usize, name: Option<&str>, pick: Vec3) -> Result<(usize, Vec3, Vec3)> { let m = b.mesh(); let beside: Vec = m.edge_faces.get(i).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default(); - let infos = b.body.faces(tol(b))?; + let infos = b.joint_faces()?; let planar = |f: usize| infos.iter().find(|x| x.index == f).and_then(|x| x.plane_normal.map(|n| (x.index, n, x.centroid, x.area))); let chosen = match name { Some(n) => { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 9545e1406..7b1761a61 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -90,7 +90,7 @@ pub use document::*; pub use eval::{ EdgeRef, FeatureResult, KeptSeparate, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, blend_target, curve_pick_error, draft_corner_options, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, - import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, + import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_for_handle, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, suggested_thread_in, tangent_face_chain, through_all_distance, world_state, world_state_reusing, }; diff --git a/crates/doc/src/name_lookup.rs b/crates/doc/src/name_lookup.rs index ffe025f58..fcf32e7a3 100644 --- a/crates/doc/src/name_lookup.rs +++ b/crates/doc/src/name_lookup.rs @@ -184,7 +184,7 @@ enum Miss { impl FaceHit { /// What a feature says about how it found a face by its stored name `name` (`None`: exactly). pub fn note(&self, name: &str) -> Option { - if !self.verified && !self.on_point { Some(format!("face `{name}` was found by geometry, not exact history; check it")) } else { None } + if !self.verified && !self.on_point { Some(format!("face `{}` was found by geometry, not exact history; check it", quoted(name))) } else { None } } } @@ -287,10 +287,26 @@ fn inside_nearest(m: &Mesh, face: usize, p: Vec3, margin: f64) -> Option { best.map(|(_, q)| q) } +/// A stored name as a message quotes it: whole up to about 80 characters, else its start and +/// end around an ellipsis. Generated names grow with the history (a split edge's name holds both +/// its faces' names), and a chamfer's warning that quoted fourteen of them in full ran to 122,701 +/// characters (#8541). +pub(crate) fn quoted(name: &str) -> String { + const HEAD: usize = 48; + const TAIL: usize = 24; + let n = name.chars().count(); + if n <= HEAD + TAIL + 8 { + return name.to_string(); + } + let head: String = name.chars().take(HEAD).collect(); + let tail: String = name.chars().skip(n - TAIL).collect(); + format!("{head}…{tail}") +} + impl EdgeHit { /// What a feature says about how it found an edge by its stored name `name` (`None`: exactly). pub fn note(&self, name: &str) -> Option { - if !self.verified && !self.on_point { Some(format!("edge `{name}` was found by geometry, not exact history; check it")) } else { None } + if !self.verified && !self.on_point { Some(format!("edge `{}` was found by geometry, not exact history; check it", quoted(name))) } else { None } } } diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index b5a638486..5165a5758 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -1846,8 +1846,9 @@ fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) { for i in 0..out.len() { let Some(LinkGeom::Arc { c, a, b }) = out.get(i).cloned() else { continue }; let r = (c.dist(a) + c.dist(b)) / 2.0; - // (arc end, line index, line end index, tangent point, unit normal towards the centre, centre distance) - let mut hits: Vec<(usize, usize, usize, Vec2, Vec2, f64)> = Vec::new(); + // Per arc end: (gap to the line's end, line index, line end index, tangent point, unit + // normal towards the centre, centre distance) + let mut hits: [Vec<(f64, usize, usize, Vec2, Vec2, f64)>; 2] = [Vec::new(), Vec::new()]; for (end, e) in [a, b].into_iter().enumerate() { for (j, g) in out.iter().enumerate() { let LinkGeom::Line(p, q) = g else { continue }; @@ -1865,17 +1866,39 @@ fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) { if (foot - far).dot(near_pt - far) <= 0.0 || near_pt.dist(foot) > 0.25 * r { continue; } - hits.push((end, j, near, foot, n, d)); + // When this end of the arc already meets another piece of the outline and the line + // doesn't end there, the line lies further along (past that piece, as along a + // conic fitted with several arcs): moving the end onto it would leave a gap. + let gap = near_pt.dist(e); + let meets = |g: &LinkGeom| match *g { + LinkGeom::Line(s, t) | LinkGeom::Arc { a: s, b: t, .. } => s.dist(e) <= tol || t.dist(e) <= tol, + _ => false, + }; + if gap > tol && out.iter().enumerate().any(|(k, g)| k != i && k != j && meets(g)) { + continue; + } + if let Some(h) = hits.get_mut(end) { + h.push((gap, j, near, foot, n, d)); + } } } - let mut hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [None, None]; - for (end, j, near, foot, n, d) in hits { - if let Some(slot) = hits_by_end.get_mut(end) - && slot.is_none() - { - *slot = Some((j, near, foot, n, d)); - } + for h in &mut hits { + h.sort_by(|x, y| x.0.total_cmp(&y.0)); } + // Each end takes the line ending nearest it. Both ends on one line would pull the arc down + // to a point: the end nearer that line's end keeps it, the other takes its next line. + let [ha, hb] = &hits; + let (ta, tb) = match (ha.first(), hb.first()) { + (Some(x), Some(y)) if x.1 == y.1 => { + if x.0 <= y.0 { + (Some(x), hb.iter().find(|h| h.1 != x.1)) + } else { + (ha.iter().find(|h| h.1 != y.1), Some(y)) + } + } + pair => pair, + }; + let hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [ta, tb].map(|h| h.map(|&(_, j, near, foot, n, d)| (j, near, foot, n, d))); let (mut c, mut r) = (c, r); if let [Some((_, _, _, n1, d1)), Some((_, _, _, n2, d2))] = hits_by_end { // One circle tangent to both lines: equal distance to each. diff --git a/crates/doc/src/project_order.rs b/crates/doc/src/project_order.rs index 242613c10..7131428ab 100644 --- a/crates/doc/src/project_order.rs +++ b/crates/doc/src/project_order.rs @@ -255,6 +255,117 @@ mod tests { let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.get(1), out.get(2)) else { panic!("{out:?}") }; assert!(a.dist(*p) < 1e-9, "{out:?}"); } + + #[test] + fn tangent_snapping_leaves_a_line_further_along_alone() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + // The arc's end at x = 0.5 already meets the next piece; the line along y = 0 ends at + // x = 0.3, further along the outline the other way. Snapping onto it would pull the end + // off the piece it meets. + let mut out = vec![ + LinkGeom::Arc { c: v(0., 2.), a: v(0.5, y(0.5)), b: v(-1.5, y(-1.5)) }, + LinkGeom::Line(v(0.3, 0.), v(10., 0.)), + LinkGeom::Line(v(0.5, y(0.5)), v(3., 3.)), + ]; + let before = out.clone(); + super::super::snap_tangent_arcs(&mut out, 0.05); + assert_eq!(out.get(1), before.get(1), "{out:?}"); + let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.first(), out.get(2)) else { panic!("{out:?}") }; + assert!(a.dist(*p) < 1e-9, "{out:?}"); + } + + #[test] + fn tangent_snapping_gives_one_line_to_one_end_of_an_arc() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + // A short arc whose two ends both lie near the end of one line: both snapping onto it + // would shrink the arc to the tangent point. + let mut out = vec![LinkGeom::Arc { c: v(0., 2.), a: v(-0.2, y(-0.2)), b: v(0.2, y(0.2)) }, LinkGeom::Line(v(-10., 0.), v(0., 0.))]; + super::super::snap_tangent_arcs(&mut out, 0.05); + let Some(LinkGeom::Arc { a, b, .. }) = out.first() else { panic!("{out:?}") }; + assert!(a.dist(*b) > 0.1, "{out:?}"); + } + + #[test] + fn tangent_snapping_moves_the_other_end_of_an_arc_to_its_next_line() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + let (a, b) = (v(-0.2, y(-0.2)), v(0.2, y(0.2))); + // The line along y = 0 ends nearest both ends of the arc but nearer b, which keeps it; a + // takes the next line, tangent to the circle at a and ending a little past it. + let back = (v(0., 2.) - a).normalized().map(|n| v(-n.y, n.x)).unwrap_or(Vec2::X); + let mut out = + vec![LinkGeom::Arc { c: v(0., 2.), a, b }, LinkGeom::Line(v(0.1, 0.), v(10., 0.)), LinkGeom::Line(a + back * 10., a + back * 0.35)]; + super::super::snap_tangent_arcs(&mut out, 0.05); + let (Some(LinkGeom::Arc { a, b, .. }), Some(LinkGeom::Line(p, _)), Some(LinkGeom::Line(_, q))) = (out.first(), out.get(1), out.get(2)) else { + panic!("{out:?}") + }; + assert!(b.dist(*p) < 1e-9 && a.dist(*q) < 1e-9 && a.dist(*b) > 0.1, "{out:?}"); + } + + #[test] + fn tangent_snapping_closes_a_conic_corner_in_any_order() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + // A square of side 150 with a conic round of 10 mm legs at each corner, fitted with lines + // and arcs the way a silhouette is, then snapped with the pieces in each order. + for rho in [0.1, 0.15, 0.5, 0.8, 0.9] { + let w = rho / (1. - rho); + let conic = |s: Vec2, apex: Vec2, e: Vec2, t: f64| { + let (b0, b1, b2) = ((1. - t) * (1. - t), 2. * t * (1. - t) * w, t * t); + (s * b0 + apex * b1 + e * b2) * (1. / (b0 + b1 + b2)) + }; + let v = Vec2::new; + let corners = [ + (v(-75., 65.), v(-75., 75.), v(-65., 75.)), + (v(65., 75.), v(75., 75.), v(75., 65.)), + (v(75., -65.), v(75., -75.), v(65., -75.)), + (v(-65., -75.), v(-75., -75.), v(-75., -65.)), + ]; + let mut chain = Vec::new(); + for (s, apex, e) in corners { + chain.extend((0..=40).map(|k| conic(s, apex, e, f64::from(k) / 40.))); + } + if let Some(&first) = chain.first() { + chain.push(first); + } + let mut fitted = Vec::new(); + super::super::fit_chain_with_arcs(&chain, Some(212. * 1e-5), &mut fitted, true); + assert!(fitted.iter().any(|g| matches!(g, LinkGeom::Arc { .. })), "{fitted:?}"); + let ends = |g: &LinkGeom| match *g { + LinkGeom::Line(s, t) | LinkGeom::Arc { a: s, b: t, .. } => vec![s, t], + _ => Vec::new(), + }; + for k in 0..fitted.len() { + let mut out = fitted.clone(); + out.rotate_left(k); + super::super::snap_tangent_arcs(&mut out, 212. * 1e-3); + // Every end still meets another piece's end. An end left without a line moves a little + // when the arc's radius is set from the lines (well under 0.01 mm here); before, ends + // pulled onto lines further along left gaps of 0.25 to 0.55 mm. + for (i, g) in out.iter().enumerate() { + for e in ends(g) { + let gap = out + .iter() + .enumerate() + .filter(|(j, _)| *j != i) + .flat_map(|(_, h)| ends(h)) + .map(|x| x.dist(e)) + .fold(f64::INFINITY, f64::min); + assert!(gap < 212. * 1e-3 * 0.02, "rho {rho}, rotation {k}: gap {gap} at {e:?}: {out:?}"); + } + } + } + } + } + #[test] fn boundaries_touching_at_a_vertex_project() { // Two squares of one face family meet only at the corner (1, 1): four boundary edges meet diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index dca02c19c..544986ad9 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -160,6 +160,21 @@ fn results_kept_ahead_outlive_the_cache() { assert!(rel(measure(&m.state().bodies[0].body).unwrap().volume, 30000.0) < 1e-9); } +/// A warning quotes a long generated name by its start and end (#8541: fourteen split edges' +/// full names made one chamfer warning 122,701 characters long); a short name stays whole. +#[test] +fn warnings_quote_long_names_by_their_ends() { + let face = |i: usize| format!("Extrude{i}.side(Sketch{i}.l{i})·Fillet{i}.blend(Chamfer{i}.cap)"); + let long = (0..40).map(face).collect::>().join("|"); + let q = crate::name_lookup::quoted(&long); + assert!(q.chars().count() <= 80, "{q}"); + assert!(q.starts_with("Extrude0.side") && q.ends_with(&long[long.len() - 10..]) && q.contains('…'), "{q}"); + assert_eq!(crate::name_lookup::quoted("Extrude1.side|Box1.top"), "Extrude1.side|Box1.top"); + // Characters, not bytes: a name of non-ASCII characters is cut between characters. + let wide = "Ü".repeat(200); + assert_eq!(crate::name_lookup::quoted(&wide).chars().count(), 73); +} + /// A saved model whose feature warning is longer than 65,536 characters is still taken on open /// (#8541): Save writes it, so Open reads it. #[test] @@ -659,6 +674,28 @@ fn new_names_take_the_first_free_number() { assert_eq!(name(&doc, next), names[0], "the first freed number is taken again"); } +#[test] +fn construction_plane_name_collisions_leave_the_document_unchanged() { + let plane = || FeatureKind::ConstructionPlane { plane: PlaneRef::Origin { name: "XY".into() } }; + let sketch = || FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() }; + for (first, second) in [(plane(), plane()), (plane(), sketch()), (sketch(), plane())] { + let mut doc = Document::new("names"); + let id = doc.add_feature(first, Some("Mid")).unwrap(); + // A suppressed feature beyond the marker still owns its name. + doc.feature_mut(id).unwrap().suppressed = true; + doc.marker = Some(0); + let before = doc.clone(); + for name in ["Mid", " Mid "] { + let error = doc.add_feature(second.clone(), Some(name)).unwrap_err().to_string(); + assert!(error.contains("another feature is called `Mid`"), "{error}"); + assert_eq!(doc, before, "a refused name must not consume an id or change the timeline"); + } + let other = doc.add_feature(second, Some("Upper")).unwrap(); + assert_eq!(doc.feature(other).unwrap().name, "Upper"); + assert_eq!(other, before.next_id); + } +} + #[test] fn empty_boolean_targets_name_overlapping_component() { for (operation, offset) in [(Operation::Cut, 0.0), (Operation::Intersect, 0.0), (Operation::Cut, 40.0)] { @@ -974,3 +1011,19 @@ fn browser_data_survives_a_save_and_old_designs_read_unchanged() { assert_eq!(resaved["browser_groups"], groups, "{order}"); } } + +/// #10748: verify that type names map to their canonical design-file kind keys. +#[test] +fn feature_kind_key_and_type_name_mappings() { + assert_eq!(FeatureKind::type_name_to_kind_key("HoleFeature"), Some("hole")); + assert_eq!(FeatureKind::type_name_to_kind_key("BoxFeature"), Some("box")); + assert_eq!(FeatureKind::type_name_to_kind_key("EdgeFlangeFeature"), Some("sheet_flange")); + assert_eq!(FeatureKind::type_name_to_kind_key("RectangularPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("PathPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("CircularPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("ExtrudeFeature"), Some("extrude")); + assert_eq!(FeatureKind::type_name_to_kind_key("SplitBodyFeature"), Some("split")); + assert_eq!(FeatureKind::type_name_to_kind_key("BaseFeature"), Some("import")); + assert_eq!(FeatureKind::type_name_to_kind_key("MeshFeature"), Some("mesh_import")); + assert_eq!(FeatureKind::type_name_to_kind_key("NonExistent"), None); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 61c83fed4..6d813d931 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -44,6 +44,7 @@ solidcraft-doc = { workspace = true } solidcraft-io = { workspace = true } solidcraft-render = { workspace = true } solidcraft-profile = { workspace = true } +# reference pictures for inspect.compare_picture (PNG and JPEG decode, PNG encode) image = { workspace = true, features = ["jpeg"] } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/engine/src/cmd/compare_picture.rs b/crates/engine/src/cmd/compare_picture.rs new file mode 100644 index 000000000..6dce661b0 --- /dev/null +++ b/crates/engine/src/cmd/compare_picture.rs @@ -0,0 +1,692 @@ +//! Compare the model with a reference picture (#1486): agents model to a picture, and an +//! overlap score plus per-edge mm offsets tell the agent which edge to move and by how much. + +use std::collections::{HashMap, VecDeque}; +use std::io::Cursor; + +use serde_json::{Value, json}; +use solidcraft_doc::canvas::base64_encode; + +use super::CommandSpec; +use super::silhouette::{self, Silhouette}; +use crate::params::bad; +use crate::{Result, Session}; + +const CMD: &str = "inspect.compare_picture"; +/// A reference picture is read through the vfs with a byte cap, like `screenshot` output. +const MAX_REFERENCE_BYTES: usize = 32 << 20; +/// Decoded pixels are capped as well, so a small file cannot unfold into a huge raster. +const MAX_DECODED_PIXELS: u64 = 16 << 20; +/// The comparison grid each mask is fitted into at most — the picture's and the fitted +/// model's alike; keeps the slide search and the memory it needs bounded. +const MAX_GRID: usize = 1024; +/// Background grows from the border only through steps of at most this per channel, so a +/// backdrop's gradual shading belongs to it and the step at the part's outline stops it. +const BG_STEP: u16 = 12; +/// When the first pass finds no part, the flood retries at this stricter step: a white part +/// on a (245, 245, 245) studio backdrop is a step of 10, which BG_STEP lets through. +const BG_STEP_STRICT: u16 = 4; +/// A picture whose border is mostly transparent: a pixel below this alpha is see-through. +const ALPHA_BG: u8 = 128; +/// The global retry's backdrop: a pixel within this of the border's main colour is +/// background. A light JPEG (white on (245, 245, 245) at quality 75) blurs the step at the +/// part's outline below any local limit, so that pass compares to the backdrop's colour. +const BG_NEAR: u16 = 8; +/// Stations per side for the edge offsets. +const STATIONS: usize = 9; + +// For agents modelling to a picture; nothing to show a person, so no toolbar button. +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Compare Picture", run).noundo().icon("compare").params( + "reference: path to a PNG or JPEG the model should match; view?/camera?/bodies?/rows? as inspect.silhouette; \ + crop_px?: [x, y, w, h] in pixels, or crop_fraction?: [x, y, w, h] as fractions 0..1 of the picture \ + (to take one view off a board); part_fills_crop?: false — with true the crop box is the part itself \ + and no background search runs, for a crop that tightly frames the part; \ + fit?: \"width\" | \"height\" | \"both\" (default \"width\"): one uniform scale, taken from the named \ + dimension (\"both\" claims both and scales by width, reporting aspect_mismatch when the shapes differ); \ + overlay?: false leaves the overlay PNG out → overlap (0..1), edges: top|bottom|left|right in mm at nine stations \ + (positive where the model reaches past the picture, null where a station misses one of the two), the grid and its \ + mm_per_px, and overlay_png (red model, blue picture) as base64 PNG. The compare is outline only: \ + holes are not compared — both the picture's and the model's holes are filled", +)]; + +fn run(s: &mut Session, p: &Value) -> Result { + let reference = p + .get("reference") + .and_then(Value::as_str) + .filter(|v| !v.trim().is_empty()) + .ok_or_else(|| bad(CMD, "`reference` is required: a path to a PNG or JPEG"))?; + let fit = match p.get("fit") { + None => Fit::Width, + Some(Value::String(v)) => match v.as_str() { + "width" => Fit::Width, + "height" => Fit::Height, + "both" => Fit::Both, + other => return Err(bad(CMD, format!("`fit` must be \"width\", \"height\" or \"both\", not `{other}`"))), + }, + Some(_) => return Err(bad(CMD, "`fit` must be a string")), + }; + let overlay = p.get("overlay").map(|v| v.as_bool().unwrap_or(false)).unwrap_or(true); + let part_fills_crop = p.get("part_fills_crop").and_then(Value::as_bool).unwrap_or(false); + + // The model side: the same outline inspect.silhouette returns, as filled rows. + let camera = silhouette::camera(p)?; + let rows = silhouette::rows(p)?; + let wanted = silhouette::body_names(p)?; + let model = silhouette::outline(s, &camera, wanted.as_deref(), rows)?; + + // The picture side: decode, crop, and find the part. + let bytes = solidcraft_io::vfs::read(reference, MAX_REFERENCE_BYTES).map_err(|e| bad(CMD, format!("{reference}: {e}")))?; + let img = decode(&bytes)?; + let img = apply_crop(img, p.get("crop_px"), p.get("crop_fraction"))?; + let picture = if part_fills_crop { + part_from_box(&img).map_err(|reason| bad(CMD, format!("the crop cannot be the part: {reason}")))? + } else { + find_part(&img).map_err(|reason| bad(CMD, format!("no part found in the picture: {reason}")))? + }; + + // Fit the model outline to the picture's scale, then slide it to the best overlap. + let (mw, mh, mmpp_x, mmpp_y) = fit_model(&model, picture.width, picture.height, fit); + let mut model_scaled = resample(&model.mask, model.width, model.height, mw, mh); + // The same hole rule the picture side has: a through-hole in the model counts as its + // outline, not as a hole the picture has to match. + fill_holes(&mut model_scaled); + let best = best_overlap(&model_scaled, &picture); + let placed = Placed { dx: best.dx, dy: best.dy, mask: &model_scaled }; + let aspect_mismatch = (picture.width as f64 * mh as f64) / (picture.height as f64 * mw as f64); + + let mut out = json!({ + "overlap": round4(best.overlap), + "stations": STATIONS, + "edges": { + "top": edge_offsets(&placed, &picture, Edge::Top, mmpp_y), + "bottom": edge_offsets(&placed, &picture, Edge::Bottom, mmpp_y), + "left": edge_offsets(&placed, &picture, Edge::Left, mmpp_x), + "right": edge_offsets(&placed, &picture, Edge::Right, mmpp_x), + }, + "fit": match fit { Fit::Width => "width", Fit::Height => "height", Fit::Both => "both" }, + "aspect_mismatch": round4(aspect_mismatch), + "mm_per_px": {"x": round4(mmpp_x), "y": round4(mmpp_y)}, + "model": {"width": model.width, "height": model.height, "box_mm": [[round4(model.lo[0]), round4(model.lo[1])], [round4(model.hi[0]), round4(model.hi[1])]], "bodies": model.bodies}, + "picture": {"width": picture.width, "height": picture.height, "source": reference}, + }); + if overlay { + out["overlay_png"] = json!(base64_encode(&overlay_png(&picture, &placed))); + } + Ok(out) +} + +#[derive(Clone, Copy)] +enum Fit { + Width, + Height, + Both, +} + +#[derive(Clone, Copy)] +enum Edge { + Top, + Bottom, + Left, + Right, +} + +/// A picture mask, tightly framed to the found part. +struct Part { + width: usize, + height: usize, + mask: Vec>, +} + +/// A model mask placed relative to the picture: its top-left sits at (dx, dy) in the +/// picture's own pixel coordinates, which may be negative. +struct Placed<'a> { + dx: i64, + dy: i64, + mask: &'a [Vec], +} + +/// Decode PNG or JPEG to RGBA8, refusing anything else and anything that unfolds too large. +fn decode(bytes: &[u8]) -> Result { + let guess = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + if !matches!(guess.format(), Some(image::ImageFormat::Png) | Some(image::ImageFormat::Jpeg)) { + return Err(bad(CMD, "the reference must be a PNG or a JPEG")); + } + let (w, h) = guess.into_dimensions().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + if w as u64 * h as u64 > MAX_DECODED_PIXELS { + return Err(bad(CMD, format!("the picture is {w}x{h}: over the {} megapixel limit", MAX_DECODED_PIXELS >> 20))); + } + let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + let img = reader.decode().map_err(|e| bad(CMD, format!("cannot decode the picture: {e}")))?; + Ok(img.to_rgba8()) +} + +/// Apply `crop_px: [x, y, w, h]` (pixels) or `crop_fraction: [x, y, w, h]` (fractions 0..1 +/// of the picture). Explicit units: a crop of `[0, 0, 1, 1]` means one pixel, not the whole. +fn apply_crop(img: image::RgbaImage, crop_px: Option<&Value>, crop_fraction: Option<&Value>) -> Result { + match (crop_px, crop_fraction) { + (Some(_), Some(_)) => Err(bad(CMD, "give `crop_px` or `crop_fraction`, not both")), + (None, None) => Ok(img), + (Some(v), None) => { + let nums = crop_nums(v, "crop_px")?; + let (w, h) = img.dimensions(); + crop_to(img, nums[0].round() as usize, nums[1].round() as usize, nums[2].round() as usize, nums[3].round() as usize, w, h) + } + (None, Some(v)) => { + let nums = crop_nums(v, "crop_fraction")?; + if nums.iter().any(|f| *f > 1.0) { + return Err(bad(CMD, "`crop_fraction` values must be 0..1")); + } + let (w, h) = img.dimensions(); + crop_to( + img, + (nums[0] * w as f64).round() as usize, + (nums[1] * h as f64).round() as usize, + (nums[2] * w as f64).round() as usize, + (nums[3] * h as f64).round() as usize, + w, + h, + ) + } + } +} + +fn crop_nums(v: &Value, name: &str) -> Result> { + let nums: Vec = v + .as_array() + .filter(|a| a.len() == 4) + .and_then(|a| a.iter().map(|v| v.as_f64()).collect()) + .ok_or_else(|| bad(CMD, format!("`{name}` must be [x, y, w, h]")))?; + if nums.iter().any(|v| !v.is_finite() || *v < 0.0) { + return Err(bad(CMD, format!("`{name}` values must be non-negative"))); + } + Ok(nums) +} + +fn crop_to(img: image::RgbaImage, x: usize, y: usize, cw: usize, ch: usize, w: u32, h: u32) -> Result { + if x >= w as usize || y >= h as usize { + return Err(bad(CMD, "the crop starts outside the picture")); + } + let cw = cw.max(1).min(w as usize - x); + let ch = ch.max(1).min(h as usize - y); + Ok(image::imageops::crop_imm(&img, x as u32, y as u32, cw as u32, ch as u32).to_image()) +} + +/// Find the part. Alpha decides only when the backdrop really is transparent — most border +/// pixels see-through — so one stray translucent pixel cannot switch the read; then any ink +/// is part, so a part drawn at a faint alpha survives. Otherwise grow the background in from +/// the border through small colour steps only — seeded from the border pixels close to the +/// border's main colour, so a part touching the border is not eaten by its own edge — keep +/// what the background did not reach, and keep the largest 4-connected piece. On a retry the +/// step is stricter, so a white part on a (245, 245, 245) backdrop (a step of 10) still +/// separates; on a second retry the backdrop is taken globally — within BG_NEAR of the +/// border's main colour — because a light JPEG blurs the step at the part's outline below +/// any local limit. Says which happened when no part is found. +fn find_part(img: &image::RgbaImage) -> std::result::Result { + let (w, h) = (img.width() as usize, img.height() as usize); + if w < 2 || h < 2 { + return Err("the picture is smaller than 2 x 2 pixels".to_string()); + } + let px = |x: usize, y: usize| -> [u16; 3] { + let p = img.get_pixel(x as u32, y as u32).0; + [p[0] as u16, p[1] as u16, p[2] as u16] + }; + let step = |a: [u16; 3], b: [u16; 3]| (a[0].abs_diff(b[0])).max(a[1].abs_diff(b[1])).max(a[2].abs_diff(b[2])); + + // Alpha decides only when the border is mostly see-through: a single backdrop pixel at + // alpha 254 in an otherwise opaque picture must not turn the whole read into alpha. + let mut border = 0usize; + let mut see_through = 0usize; + for x in 0..w { + for y in [0, h - 1] { + border += 1; + if img.get_pixel(x as u32, y as u32)[3] < ALPHA_BG { + see_through += 1; + } + } + } + for y in 0..h { + for x in [0, w - 1] { + border += 1; + if img.get_pixel(x as u32, y as u32)[3] < ALPHA_BG { + see_through += 1; + } + } + } + let uses_alpha = see_through * 2 > border; + + let (part, too_small): (Vec, String) = if uses_alpha { + let mask: Vec = img.pixels().map(|p| p[3] > 0).collect(); + (mask, "the picture is transparent: no pixel holds any ink".to_string()) + } else { + let bg = flood_background(&px, w, h, BG_STEP, &step); + let mask: Vec = (0..w * h).map(|i| !bg[i]).collect(); + if largest_piece(&mask, w, h).len() >= 16 { + (mask, "the picture holds no piece big enough to be a part".to_string()) + } else { + let bg = flood_background(&px, w, h, BG_STEP_STRICT, &step); + let mask: Vec = (0..w * h).map(|i| !bg[i]).collect(); + if largest_piece(&mask, w, h).len() >= 16 { + (mask, "the picture holds no piece big enough to be a part".to_string()) + } else { + // The local step fails on a light JPEG: the codec blurs the 10-level step + // at the part's outline into steps of a few levels each, under any limit. + // Take the backdrop globally instead: near the border's main colour. + let main = border_main_colour(&px, w, h); + let mask: Vec = (0..w * h).map(|i| step(main, px(i % w, i / w)) > BG_NEAR).collect(); + (mask, "the background grew from the border over the whole picture, even with a stricter colour step: the part's colour is too close to the backdrop's".to_string()) + } + } + }; + + let best = largest_piece(&part, w, h); + if best.len() < 16 { + return Err(too_small); + } + // Tight frame, then downscale to the comparison grid at need. + let (x0, y0, x1, y1) = frame(&best, w); + let (pw, ph) = (x1 - x0 + 1, y1 - y0 + 1); + let mut mask = vec![vec![false; pw]; ph]; + for &i in &best { + let (x, y) = (i % w, i / w); + mask[y - y0][x - x0] = true; + } + let (dw, dh) = fit_grid(pw, ph); + let mut mask = if (dw, dh) == (pw, ph) { mask } else { resample(&mask, pw, ph, dw, dh) }; + fill_holes(&mut mask); + Ok(Part { width: dw, height: dh, mask }) +} + +/// The crop box is the part itself (`part_fills_crop`): no background search. This is how +/// one view cropped tight off a board says so — a part touching three sides leaves the +/// border's main colour the part's own, and the flood would keep the backdrop strip instead. +fn part_from_box(img: &image::RgbaImage) -> std::result::Result { + let (w, h) = (img.width() as usize, img.height() as usize); + if w < 2 || h < 2 { + return Err("the crop is smaller than 2 x 2 pixels".to_string()); + } + let (dw, dh) = fit_grid(w, h); + Ok(Part { width: dw, height: dh, mask: vec![vec![true; dw]; dh] }) +} + +/// The border's main colour: the border colour it has most of. A part crossing the border +/// is in the border too, but the backdrop is what most of the border shows. +fn border_main_colour(px: &impl Fn(usize, usize) -> [u16; 3], w: usize, h: usize) -> [u16; 3] { + let mut counts: HashMap<[u16; 3], usize> = HashMap::new(); + for x in 0..w { + for y in [0, h - 1] { + *counts.entry(px(x, y)).or_default() += 1; + } + } + for y in 0..h { + for x in [0, w - 1] { + *counts.entry(px(x, y)).or_default() += 1; + } + } + counts.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap_or([0; 3]) +} + +/// The background mask: grown from every border pixel whose colour is close to the border's +/// main colour, crossing only steps of at most `limit` per channel. +fn flood_background(px: &impl Fn(usize, usize) -> [u16; 3], w: usize, h: usize, limit: u16, step: &impl Fn([u16; 3], [u16; 3]) -> u16) -> Vec { + let main = border_main_colour(px, w, h); + + let mut bg = vec![false; w * h]; + let mut queue: VecDeque<(usize, usize)> = VecDeque::new(); + let mut seed = |x: usize, y: usize| { + if step(main, px(x, y)) <= limit && !bg[y * w + x] { + bg[y * w + x] = true; + queue.push_back((x, y)); + } + }; + for x in 0..w { + seed(x, 0); + seed(x, h - 1); + } + for y in 0..h { + seed(0, y); + seed(w - 1, y); + } + while let Some((x, y)) = queue.pop_front() { + let here = px(x, y); + for (nx, ny) in neighbours(x, y, w, h) { + if !bg[ny * w + nx] && step(here, px(nx, ny)) <= limit { + bg[ny * w + nx] = true; + queue.push_back((nx, ny)); + } + } + } + bg +} + +/// The largest 4-connected piece of a mask, as indices into `w`-wide rows. +fn largest_piece(mask: &[bool], w: usize, h: usize) -> Vec { + let mut best: Vec = Vec::new(); + let mut seen = vec![false; w * h]; + for start in 0..w * h { + if !mask[start] || seen[start] { + continue; + } + let mut piece: Vec = Vec::new(); + let mut queue: VecDeque = VecDeque::new(); + seen[start] = true; + queue.push_back(start); + while let Some(i) = queue.pop_front() { + piece.push(i); + let (x, y) = (i % w, i / w); + for (nx, ny) in neighbours(x, y, w, h) { + let j = ny * w + nx; + if mask[j] && !seen[j] { + seen[j] = true; + queue.push_back(j); + } + } + } + if piece.len() > best.len() { + best = piece; + } + } + best +} + +/// Fill the holes: pixels the outside never reaches become part — the rule the picture's +/// border flood gives the picture side for free, given to the model's mask as well. +fn fill_holes(mask: &mut [Vec]) { + let (h, w) = (mask.len(), mask.first().map_or(0, Vec::len)); + if w < 2 || h < 2 { + return; + } + let mut outside = vec![false; w * h]; + let mut queue: VecDeque = VecDeque::new(); + for x in 0..w { + for y in [0, h - 1] { + if !mask[y][x] && !outside[y * w + x] { + outside[y * w + x] = true; + queue.push_back(y * w + x); + } + } + } + for y in 0..h { + for x in [0, w - 1] { + if !mask[y][x] && !outside[y * w + x] { + outside[y * w + x] = true; + queue.push_back(y * w + x); + } + } + } + while let Some(i) = queue.pop_front() { + let (x, y) = (i % w, i / w); + for (nx, ny) in neighbours(x, y, w, h) { + let j = ny * w + nx; + if !mask[ny][nx] && !outside[j] { + outside[j] = true; + queue.push_back(j); + } + } + } + for y in 0..h { + for x in 0..w { + if !mask[y][x] && !outside[y * w + x] { + mask[y][x] = true; + } + } + } +} + +fn neighbours(x: usize, y: usize, w: usize, h: usize) -> impl Iterator { + [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)].into_iter().filter(move |(nx, ny)| *nx < w && *ny < h) +} + +fn frame(pixels: &[usize], w: usize) -> (usize, usize, usize, usize) { + let mut x0 = usize::MAX; + let mut y0 = usize::MAX; + let mut x1 = 0; + let mut y1 = 0; + for &i in pixels { + let (x, y) = (i % w, i / w); + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x); + y1 = y1.max(y); + } + (x0, y0, x1, y1) +} + +fn fit_grid(w: usize, h: usize) -> (usize, usize) { + let scale = (MAX_GRID as f64 / w.max(h) as f64).min(1.0); + (((w as f64 * scale).round() as usize).max(2), ((h as f64 * scale).round() as usize).max(2)) +} + +/// Nearest-neighbour resample of a mask to (w1, h1). +fn resample(mask: &[Vec], w0: usize, h0: usize, w1: usize, h1: usize) -> Vec> { + (0..h1) + .map(|y| { + let row = &mask[((y * h0) / h1.max(1)).min(h0 - 1)]; + (0..w1).map(|x| row[((x * w0) / w1.max(1)).min(w0 - 1)]).collect() + }) + .collect() +} + +/// The model outline's size in picture pixels and the mm per pixel that follows. One +/// uniform scale, taken from the dimension the two share — the axes are never stretched +/// apart, which would hide the very mismatch the tool is for. `both` claims both dimensions +/// and scales by width; the result's `aspect_mismatch` says how far the shapes are apart. +/// The fitted size takes the same MAX_GRID cap as the picture's: a narrow model fitted by +/// width against a wide picture would otherwise ask for hundreds of megabytes of mask. +fn fit_model(model: &Silhouette, pw: usize, ph: usize, fit: Fit) -> (usize, usize, f64, f64) { + let s = match fit { + Fit::Width | Fit::Both => pw as f64 / model.width as f64, + Fit::Height => ph as f64 / model.height as f64, + }; + let mw = ((model.width as f64 * s).round() as usize).max(2); + let mh = ((model.height as f64 * s).round() as usize).max(2); + let (mw, mh) = fit_grid(mw, mh); + (mw, mh, model.width as f64 * model.mm_per_px / mw as f64, model.height as f64 * model.mm_per_px / mh as f64) +} + +struct Best { + overlap: f64, + dx: i64, + dy: i64, +} + +/// Slide the model mask over the picture mask to the best intersection-over-union. The +/// coarse pass covers the whole range of placements where the two frames can share a +/// pixel — a tenth of the picture around the centre is not enough when the heights differ — +/// and the fine pass walks every offset around its winner. +fn best_overlap(model: &[Vec], picture: &Part) -> Best { + let pic = spans_of(&picture.mask); + let mdl = spans_of(model); + let model_area: i64 = mdl.iter().flatten().map(|[a, b]| (b - a) as i64).sum(); + let pic_area: i64 = pic.iter().flatten().map(|[a, b]| (b - a) as i64).sum(); + + let (mw, mh) = (model[0].len() as i64, model.len() as i64); + let (lo_x, hi_x) = (1 - mw, picture.width as i64); + let (lo_y, hi_y) = (1 - mh, picture.height as i64); + // About 64 coarse samples per axis, never finer than 4 px, never coarser than 32. + let step_x = ((hi_x - lo_x) / 64).clamp(4, 32); + let step_y = ((hi_y - lo_y) / 64).clamp(4, 32); + + // The frames' aligned corners: both masks are tightly framed, so the best placement of a + // matching picture is at or near here. + let (mut bx, mut by) = (0i64, 0i64); + for round in 0..2 { + // Coarse: the whole range at the step; fine: every offset within one coarse step + // of the coarse winner. + let (sx, sy, x0, x1, y0, y1) = if round == 0 { + (step_x, step_y, lo_x, hi_x, lo_y, hi_y) + } else { + (1, 1, (bx - step_x).max(lo_x), (bx + step_x).min(hi_x), (by - step_y).max(lo_y), (by + step_y).min(hi_y)) + }; + let (mut best_score, mut best_x, mut best_y) = (i64::MIN, bx, by); + let mut dy = y0; + while dy <= y1 { + let mut dx = x0; + while dx <= x1 { + let hits = intersection(&mdl, &pic, dx, dy); + let union = model_area + pic_area - hits; + let score = if union <= 0 { i64::MIN } else { hits * 1_000_000 / union }; + if score > best_score { + best_score = score; + best_x = dx; + best_y = dy; + } + dx += sx; + } + dy += sy; + } + bx = best_x; + by = best_y; + } + + let hits = intersection(&mdl, &pic, bx, by); + let union = model_area + pic_area - hits; + Best { overlap: if union <= 0 { 0.0 } else { hits as f64 / union as f64 }, dx: bx, dy: by } +} + +fn spans_of(mask: &[Vec]) -> Vec> { + mask.iter().map(|row| silhouette::spans(row)).collect() +} + +/// Pixels the model shares with the picture at model offset (dx, dy), from run-length rows. +fn intersection(mdl: &[Vec<[usize; 2]>], pic: &[Vec<[usize; 2]>], dx: i64, dy: i64) -> i64 { + let mut hits = 0i64; + for (r, spans) in mdl.iter().enumerate() { + if spans.is_empty() { + continue; + } + let Some(y) = (dy + r as i64).try_into().ok().and_then(|y: usize| pic.get(y)) else { continue }; + if y.is_empty() { + continue; + } + for &[a, b] in spans { + let (mut lo, hi) = ((a as i64 + dx).max(0), b as i64 + dx); + if hi <= lo { + continue; + } + for &[pa, pb] in y { + let (s, e) = (lo.max(pa as i64), hi.min(pb as i64)); + if e > s { + hits += e - s; + } + lo = lo.max(pb as i64); + if lo >= hi || pb as i64 >= hi { + break; + } + } + } + } + hits +} + +/// The model's edge against the picture's, in mm, at nine stations along one side; positive +/// where the model reaches past the picture, null where a station misses one of the two. +fn edge_offsets(model: &Placed, picture: &Part, side: Edge, mmpp: f64) -> Vec { + (1..=STATIONS) + .map(|i| { + let station = match side { + Edge::Top | Edge::Bottom => (picture.width as u64 * i as u64 / (STATIONS as u64 + 1)) as usize, + Edge::Left | Edge::Right => (picture.height as u64 * i as u64 / (STATIONS as u64 + 1)) as usize, + }; + let offset = match side { + Edge::Top | Edge::Bottom => { + let pic = column_edge(&picture.mask, station, matches!(side, Edge::Top)); + let mdl = (station as i64 - model.dx) + .try_into() + .ok() + .and_then(|mx: usize| column_edge(model.mask, mx, matches!(side, Edge::Top))) + .map(|e| e as i64 + model.dy); + match (mdl, pic) { + (Some(m), Some(p)) => Some(match side { + Edge::Top => (p as f64 - m as f64) * mmpp, + _ => (m as f64 - p as f64) * mmpp, + }), + _ => None, + } + } + Edge::Left | Edge::Right => { + let pic = row_edge(&picture.mask, station, matches!(side, Edge::Left)); + let mdl = (station as i64 - model.dy) + .try_into() + .ok() + .and_then(|my: usize| row_edge(model.mask, my, matches!(side, Edge::Left))) + .map(|e| e as i64 + model.dx); + match (mdl, pic) { + (Some(m), Some(p)) => Some(match side { + Edge::Left => (p as f64 - m as f64) * mmpp, + _ => (m as f64 - p as f64) * mmpp, + }), + _ => None, + } + } + }; + offset.map(|mm| json!(round3(mm))).unwrap_or(Value::Null) + }) + .collect() +} + +/// The first (or last, when `first` is false) row holding column `x`; None if none does. +fn column_edge(mask: &[Vec], x: usize, first: bool) -> Option { + let mut found = None; + for (y, row) in mask.iter().enumerate() { + if row.get(x).copied().unwrap_or(false) { + if first { + return Some(y); + } + found = Some(y); + } + } + found +} + +/// The first (or last) column set in row `y`; None if the row is empty or missing. +fn row_edge(mask: &[Vec], y: usize, first: bool) -> Option { + let row = mask.get(y)?; + if first { row.iter().position(|&on| on) } else { row.iter().rposition(|&on| on) } +} + +/// The overlay PNG: the picture in blue, the model in red, on a canvas that holds both. +fn overlay_png(picture: &Part, model: &Placed) -> Vec { + // A margin so a model that hangs off the picture still fits the canvas. + let m = 8i64; + let (x0, y0) = (0.min(model.dx) - m, 0.min(model.dy) - m); + let (x1, y1) = ( + (picture.width as i64).max(model.dx + model.mask.first().map_or(0, |r| r.len()) as i64) + m, + (picture.height as i64).max(model.dy + model.mask.len() as i64) + m, + ); + let (w, h) = ((x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32); + let mut img = image::RgbaImage::from_pixel(w, h, image::Rgba([250, 250, 250, 255])); + for (y, row) in picture.mask.iter().enumerate() { + for (x, &on) in row.iter().enumerate() { + if on { + img.put_pixel((x as i64 - x0) as u32, (y as i64 - y0) as u32, image::Rgba([70, 110, 230, 255])); + } + } + } + for (r, row) in model.mask.iter().enumerate() { + for (c, &on) in row.iter().enumerate() { + if !on { + continue; + } + let (x, y) = (model.dx + c as i64 - x0, model.dy + r as i64 - y0); + if (0..w as i64).contains(&x) && (0..h as i64).contains(&y) { + img.put_pixel(x as u32, y as u32, image::Rgba([235, 60, 60, 255])); + } + } + } + let mut out = Cursor::new(Vec::new()); + // Encoding a mask-sized PNG cannot realistically fail; if it ever does, no overlay. + let enc = image::codecs::png::PngEncoder::new(&mut out); + use image::ImageEncoder as _; + if enc.write_image(img.as_raw(), img.width(), img.height(), image::ExtendedColorType::Rgba8).is_err() { + return Vec::new(); + } + out.into_inner() +} + +fn round4(v: f64) -> f64 { + if v.abs() < 1e12 { (v * 10_000.0).round() / 10_000.0 } else { v } +} + +fn round3(v: f64) -> f64 { + if v.abs() < 1e12 { (v * 1_000.0).round() / 1_000.0 } else { v } +} diff --git a/crates/engine/src/cmd/compare_picture_tests.rs b/crates/engine/src/cmd/compare_picture_tests.rs new file mode 100644 index 000000000..fe8f44390 --- /dev/null +++ b/crates/engine/src/cmd/compare_picture_tests.rs @@ -0,0 +1,490 @@ +//! Tests for `inspect.compare_picture` (#1486): synthetic reference pictures drawn in code, +//! written to the temp dir and read back through the vfs like any other reference. + +use std::io::Cursor; + +use serde_json::{Value, json}; + +use super::super::Session; +use image::ImageEncoder as _; + +fn run(s: &mut Session, cmd: &str, params: Value) -> Value { + s.execute(cmd, ¶ms).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn box_body(s: &mut Session, name: &str, x1: f64, y1: f64, z: f64) { + let sketch = format!("{name}Sketch"); + run(s, "sketch.create", json!({"plane": "XY", "name": sketch})); + run(s, "sketch.rectangle.two_point", json!({"p0": [0.0, 0.0], "p1": [x1, y1]})); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": sketch, "distance": z, "operation": "new_body", "body_name": name})); +} + +/// A PNG whose pixels come from `paint`. +fn png(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + png_rgba(w, h, |x, y| { + let [r, g, b] = paint(x, y); + [r, g, b, 255] + }) +} + +/// A PNG with alpha, whose pixels come from `paint`. +fn png_rgba(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 4]) -> Vec { + let mut img = image::RgbaImage::new(w as u32, h as u32); + for y in 0..h { + for x in 0..w { + img.put_pixel(x as u32, y as u32, image::Rgba(paint(x, y))); + } + } + let mut out = Cursor::new(Vec::new()); + image::codecs::png::PngEncoder::new(&mut out).write_image(img.as_raw(), w as u32, h as u32, image::ExtendedColorType::Rgba8).unwrap(); + out.into_inner() +} + +fn jpeg(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + jpeg_q(w, h, 90, paint) +} + +fn jpeg_q(w: usize, h: usize, q: u8, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + let mut img = image::RgbaImage::new(w as u32, h as u32); + for y in 0..h { + for x in 0..w { + let [r, g, b] = paint(x, y); + img.put_pixel(x as u32, y as u32, image::Rgba([r, g, b, 255])); + } + } + let rgb = image::DynamicImage::ImageRgba8(img).to_rgb8(); + let mut out = Cursor::new(Vec::new()); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, q) + .write_image(rgb.as_raw(), w as u32, h as u32, image::ExtendedColorType::Rgb8) + .unwrap(); + out.into_inner() +} + +/// Write a reference into the temp dir and return its path. +fn reference(name: &str, bytes: &[u8]) -> String { + let path = std::env::temp_dir().join(format!("solidcraft-compare-picture-{}-{name}", std::process::id())); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() +} + +/// A white rectangle on a grey backdrop: `x0..x1, y0..y1` in pixels. +fn rect_picture(w: usize, h: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Vec { + png(w, h, |x, y| if (x0..x1).contains(&x) && (y0..y1).contains(&y) { [255, 255, 255] } else { [200, 200, 200] }) +} + +fn edges(v: &Value) -> Vec>> { + ["top", "bottom", "left", "right"] + .iter() + .map(|side| v["edges"][side].as_array().unwrap().iter().map(|e| e.as_f64()).collect::>>()) + .collect() +} + +fn near(v: Option, want: f64, tol: f64) -> bool { + v.is_some_and(|e| (e - want).abs() <= tol) +} + +#[test] +fn a_matching_picture_scores_high_with_flat_edges() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); // front view: 20 wide, 30 tall + let path = reference("match.png", &rect_picture(200, 280, 20, 20, 180, 260)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + for side in edges(&out) { + for e in side { + assert!(near(e, 0.0, 0.6), "edge {e:?}"); + } + } + assert!(!out["overlay_png"].as_str().unwrap().is_empty()); +} + +#[test] +fn a_step_in_the_bottom_edge_shows_up_in_mm() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // The aligned picture: a plain part 160 x 240 px — the model's own shape at 8 px per mm. + let aligned_path = reference("aligned.png", &rect_picture(200, 280, 20, 20, 180, 260)); + let aligned = run(&mut s, "inspect.compare_picture", json!({"reference": aligned_path, "view": "front"})); + // The stepped picture: over its right half the part's bottom edge sits 35 px higher. + // The width fit gives 8 px per mm, so 35 px is 4.375 mm of the model reaching past + // the picture. + let stepped_path = reference( + "stepped.png", + &png(200, 280, |x, y| { + let bottom = if x >= 100 { 225 } else { 260 }; + if (20..180).contains(&x) && (20..bottom).contains(&y) { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let stepped = run(&mut s, "inspect.compare_picture", json!({"reference": stepped_path, "view": "front"})); + let flat = edges(&aligned)[1].clone(); + let step = edges(&stepped)[1].clone(); + for e in flat.iter() { + assert!(near(*e, 0.0, 0.6), "flat bottom {e:?}"); + } + // Stations sit at local x = 16..144 px; the notch starts at local x = 80 (global 100), + // so stations 5..9 are over it. + for e in step.iter().take(4) { + assert!(near(*e, 0.0, 0.6), "step bottom left {e:?}"); + } + for e in step.iter().skip(4) { + assert!(near(*e, 4.375, 0.6), "step bottom right {e:?}"); + } + assert!(stepped["overlap"].as_f64().unwrap() < aligned["overlap"].as_f64().unwrap()); +} + +/// #1486's example, pinned: `examples/bracket.json` as it is (upright 30 mm) against the +/// same bracket at 40 mm, both from the front, scaled by the 40 mm arm they share. +/// The issue's prototype numbers: overlap 0.865, bottom −9.9 mm at the upright (6 % across), +/// 0.0 mm everywhere else. +#[test] +fn the_issue_bracket_pins_overlap_and_the_short_upright() { + let mut s = Session::default(); + // The bracket profile of examples/bracket.json: a 40 x 6 arm with a 6-wide upright to + // 30 mm, on XZ so the front view shows the upright hanging below the arm. + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Profile"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 6], [6, 6], [6, 30], [0, 30]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 20.0, "direction": "negative", "body_name": "Bracket"})); + // The same bracket with the upright at 40 mm, at 20 px per mm: an 800 x 800 part, the + // 800 x 120 arm on top and the 120-wide upright down to 800, on a grey margin. + let path = reference( + "bracket.png", + &png(840, 840, |x, y| { + let part = ((20..820).contains(&x) && (20..140).contains(&y)) || ((20..140).contains(&x) && (20..820).contains(&y)); + if part { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "rows": 480, "overlay": false})); + let overlap = out["overlap"].as_f64().unwrap(); + assert!((overlap - 0.865).abs() <= 0.01, "overlap {overlap}"); + let e = edges(&out); + // The upright is the first station (x = 80 of 800): the model is 10 mm short there. + assert!(near(e[1][0], -10.0, 0.2), "bottom at the upright {:?}", e[1][0]); + for side in 1..9 { + assert!(near(e[1][side], 0.0, 0.1), "bottom elsewhere {:?}", e[1]); + } + for i in 0..9 { + assert!(near(e[0][i], 0.0, 0.1), "top {:?}", e[0]); + // Below the model's 30 mm upright the model has no row to answer with: those + // side stations are null, as documented. + for side in [e[2].clone(), e[3].clone()] { + match side[i] { + None => {} + Some(v) => assert!(v.abs() <= 0.1, "side {side:?}"), + } + } + } +} + +#[test] +fn a_gradient_backdrop_still_separates_from_the_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // A backdrop that shifts one step per row: the border flood follows it; the step at the + // part's outline (to white) stops it. + let path = reference( + "gradient.png", + &png(200, 300, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [200 + (y / 30) as u8, 200, 200] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} + +#[test] +fn a_jpeg_reference_works_too() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = + reference("match.jpg", &jpeg(200, 300, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [40, 40, 40] })); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} + +#[test] +fn crop_takes_one_part_off_the_board() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // Two parts side by side; the crop keeps the left one, a plain rectangle that matches + // the model. The right part is bigger overall but L-shaped, so without the crop the + // largest piece wins and the score drops. + let path = reference( + "two.png", + &png(400, 300, |x, y| { + let left = (20..180).contains(&x) && (20..260).contains(&y); + let right = (210..390).contains(&x) && (5..295).contains(&y) && !((300..390).contains(&x) && (100..200).contains(&y)); + if left || right { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "crop_fraction": [0.0, 0.0, 0.5, 1.0]})); + // The picture size is the found part's tight frame: the left rectangle is 160 x 240 px. + assert_eq!(out["picture"]["width"], 160); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + let whole = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(whole["overlap"].as_f64().unwrap() < out["overlap"].as_f64().unwrap()); +} + +#[test] +fn crop_px_has_explicit_units() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = reference("px.png", &rect_picture(200, 280, 20, 20, 180, 260)); + // Pixels mean pixels: [10, 10, 180, 260] keeps the part with a margin, and a crop of + // one pixel is one pixel, not the whole picture. + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "crop_px": [10, 10, 180, 260]})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + let dot = reference("dot.png", &rect_picture(200, 280, 100, 100, 101, 101)); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": dot, "crop_px": [0, 0, 1, 1]})).unwrap_err().to_string().contains("no part found") + ); + // Giving both spellings is refused, and so is a fraction above 1. + assert!( + s.execute("inspect.compare_picture", &json!({"reference": path, "crop_px": [0, 0, 10, 10], "crop_fraction": [0.0, 0.0, 0.1, 0.1]})) + .unwrap_err() + .to_string() + .contains("not both") + ); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": path, "crop_fraction": [0.0, 0.0, 1.5, 1.0]})) + .unwrap_err() + .to_string() + .contains("0..1") + ); +} + +#[test] +fn fit_both_never_stretches_the_axes_apart() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); // front view: 20 wide, 30 tall + // A 20 x 20 mm square picture of a 20 x 30 mm model: `both` used to stretch the model + // to the square and report a perfect 1.000 with every edge at 0.0 mm. One uniform + // scale (from the width they share) leaves the 10 mm of overhang visible instead. + let path = reference("square.png", &rect_picture(220, 220, 10, 10, 210, 210)); + let both = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "fit": "both", "overlay": false})); + assert!((both["overlap"].as_f64().unwrap() - 200.0 / 300.0).abs() < 0.02, "overlap {}", both["overlap"]); + assert!((both["aspect_mismatch"].as_f64().unwrap() - 1.5).abs() < 0.01, "aspect_mismatch {}", both["aspect_mismatch"]); + // And `width` is the default: leaving `fit` out answers the same as naming it. + let plain = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert_eq!(plain["overlap"], both["overlap"]); + assert_eq!(plain["edges"], both["edges"]); +} + +#[test] +fn fit_width_keeps_the_models_aspect() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // The picture part is 160 x 160 px: fit=width scales the model uniformly to 160 x 240, + // so it hangs 80 px (10 mm) over the picture's height in total, wherever the slide puts + // it. The overlap of a contained model is 160/240 wherever it sits. + let path = reference("short.png", &rect_picture(200, 220, 20, 20, 180, 180)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "fit": "width"})); + assert!((out["overlap"].as_f64().unwrap() - 160.0 / 240.0).abs() < 0.05, "overlap {}", out["overlap"]); + let bottom: Vec> = out["edges"]["bottom"].as_array().unwrap().iter().map(|e| e.as_f64()).collect(); + let top: Vec> = out["edges"]["top"].as_array().unwrap().iter().map(|e| e.as_f64()).collect(); + for i in 0..9 { + // The overhang splits between top and bottom but always totals the extra 10 mm. + assert!(bottom[i].unwrap() >= 0.0 && top[i].unwrap() >= 0.0, "bottom {:?} top {:?}", bottom[i], top[i]); + assert!((bottom[i].unwrap() + top[i].unwrap() - 10.0).abs() < 0.6, "bottom {:?} top {:?}", bottom[i], top[i]); + } +} + +#[test] +fn a_narrow_model_fits_the_grid_not_the_memory() { + let mut s = Session::default(); + // A 2 mm x 1000 mm sliver seen from the front: fitted by width against a 1024-wide + // picture it used to become 1024 x 524 288 booleans. The fitted model now takes the + // same MAX_GRID cap as the picture, so the comparison just runs. + box_body(&mut s, "Sliver", 2.0, 1.0, 1000.0); + let path = reference("sliver.png", &rect_picture(1030, 1010, 3, 5, 1027, 1005)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The shapes are nothing alike (the sliver is 1:500, the picture 1024:1000), and the + // capped model grid keeps the overlap small — what matters is that it ran at all. + assert!(out["overlap"].as_f64().unwrap() < 0.1, "overlap {}", out["overlap"]); +} + +#[test] +fn ordinary_pictures_keep_their_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // A part touching the picture's border: only border pixels close to the border's main + // colour seed the background, so the part's own border pixels do not flood it. + let border = reference("border.png", &rect_picture(200, 280, 0, 20, 160, 260)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": border, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "border overlap {}", out["overlap"]); + // A white part on a (245, 245, 245) studio backdrop: the step of 10 is below BG_STEP, + // but the stricter retry separates it. + let studio = reference( + "studio.png", + &png(200, 280, |x, y| if (20..180).contains(&x) && (20..260).contains(&y) { [255, 255, 255] } else { [245, 245, 245] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": studio, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "studio overlap {}", out["overlap"]); + // A part on a transparent background: alpha below 128 is background. + let alpha = reference( + "alpha.png", + &png_rgba(200, 280, |x, y| if (20..180).contains(&x) && (20..260).contains(&y) { [90, 90, 90, 255] } else { [0, 0, 0, 0] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": alpha, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "alpha overlap {}", out["overlap"]); +} + +#[test] +fn a_through_hole_counts_the_same_on_both_sides() { + let mut s = Session::default(); + // A 200 x 200 mm plate with a 100 x 100 mm through-hole, against a picture of itself + // at 1 px per mm, seen from the top (the hole goes through the plate's faces). The + // picture's hole is filled by the border flood; the model's hole now gets the same + // rule, so the plate scores ~1.0 instead of 0.75. + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Plate"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0.0, 0.0], "p1": [200.0, 200.0]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Plate", "distance": 10.0, "operation": "new_body", "body_name": "Plate"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Hole"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [50.0, 50.0], "p1": [150.0, 150.0]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Hole", "distance": 20.0, "operation": "cut"})); + let path = reference( + "plate.png", + &png(220, 220, |x, y| { + let plate = (10..210).contains(&x) && (10..210).contains(&y); + let hole = (60..160).contains(&x) && (60..160).contains(&y); + if plate && !hole { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "top", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.98, "overlap {}", out["overlap"]); + for side in edges(&out) { + for e in side { + assert!(near(e, 0.0, 0.6), "edge {e:?}"); + } + } +} + +#[test] +fn hostile_and_empty_references_fail_cleanly() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + assert!(s.execute("inspect.compare_picture", &json!({})).is_err()); + // Not an image at all. + let text = reference("not.png", b"just text, not a picture"); + assert!(s.execute("inspect.compare_picture", &json!({"reference": text})).unwrap_err().to_string().contains("PNG or a JPEG")); + // A uniform picture: the background eats everything, and says so. + let flat = reference("flat.png", &png(64, 64, |_, _| [200, 200, 200])); + assert!(s.execute("inspect.compare_picture", &json!({"reference": flat})).unwrap_err().to_string().contains("no part found")); + // A fully transparent picture: alpha says there is nothing there. + let clear = reference("clear.png", &png_rgba(64, 64, |_, _| [0, 0, 0, 0])); + assert!(s.execute("inspect.compare_picture", &json!({"reference": clear})).unwrap_err().to_string().contains("transparent")); + // A missing file. + assert!(s.execute("inspect.compare_picture", &json!({"reference": "no-such-file.png"})).is_err()); + // A bad fit name. + let path = reference("match2.png", &rect_picture(200, 280, 20, 20, 180, 260)); + assert!(s.execute("inspect.compare_picture", &json!({"reference": path, "fit": "diagonal"})).is_err()); + // overlay: false leaves the PNG out. + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert!(out.get("overlay_png").is_none()); +} + +/// Reviewer re-test case: a 60 x 60 opaque PNG with a white 40 x 40 square and a single +/// backdrop pixel at alpha 254 used to be read as all part — 1.000 against the 40 x 40 +/// square at 0.067 mm/px instead of 0.1. Alpha now decides only when the border is mostly +/// see-through, and a part drawn at alpha 100 on a transparent backdrop is still the part. +#[test] +fn one_translucent_pixel_does_not_switch_to_alpha() { + let mut s = Session::default(); + box_body(&mut s, "Square", 4.0, 1.0, 4.0); // front view: 4 x 4 mm + let path = reference( + "speck.png", + &png_rgba(60, 60, |x, y| { + let alpha = if x == 5 && y == 55 { 254 } else { 255 }; + let c = if (10..50).contains(&x) && (10..50).contains(&y) { 255u8 } else { 128 }; + [c, c, c, alpha] + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The part is the 40 x 40 square: 4 mm over 40 px is 0.1 mm/px, not 4/60 = 0.067. + let mmpp = out["mm_per_px"]["x"].as_f64().unwrap(); + assert!((mmpp - 0.1).abs() < 0.01, "mm_per_px {mmpp}"); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); + // A part drawn at alpha 100 on a transparent backdrop is the part, not the background. + let faint = reference( + "faint.png", + &png_rgba(60, 60, |x, y| if (10..50).contains(&x) && (10..50).contains(&y) { [255, 255, 255, 100] } else { [0, 0, 0, 0] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": faint, "view": "front", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "faint overlap {}", out["overlap"]); + let mmpp = out["mm_per_px"]["x"].as_f64().unwrap(); + assert!((mmpp - 0.1).abs() < 0.01, "faint mm_per_px {mmpp}"); +} + +/// Reviewer re-test case: one view cropped off a board — the part touches three sides and +/// takes 270 of the 400 border samples, so the border's main colour is the part's own and +/// the flood eats it: the 15 px backdrop strip becomes "the part" and an exact model scores +/// 0.18. `part_fills_crop: true` says the crop box is the part: no flood, exact model ~1.0. +#[test] +fn a_tight_crop_can_declare_the_box_is_the_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 17.0, 10.0, 20.0); // front view: 17 wide, 20 tall + // The tight crop: the white part fills x 0..85 of a 100 x 100 box, touching three + // sides — 270 of the border samples — with a 15 px backdrop strip down the right. + let path = reference("tight.png", &png(100, 100, |x, _| if x < 85 { [255, 255, 255] } else { [200, 200, 200] })); + let flood = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "overlay": false})); + assert!(flood["overlap"].as_f64().unwrap() < 0.5, "the flood keeps the strip: overlap {}", flood["overlap"]); + let out = run( + &mut s, + "inspect.compare_picture", + json!({"reference": path, "view": "front", "crop_px": [0, 0, 85, 100], "part_fills_crop": true, "overlay": false}), + ); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + // 17 mm over the 85 px the part fills: 0.2 mm/px. + assert!((out["mm_per_px"]["x"].as_f64().unwrap() - 0.2).abs() < 0.01, "mm_per_px {}", out["mm_per_px"]); + // A crop of a 2 x 2 box is the part; a 1 px box is refused. + let dot = reference("tight-dot.png", &png(4, 4, |_, _| [255, 255, 255])); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": dot, "part_fills_crop": true, "crop_px": [0, 0, 1, 1]})) + .unwrap_err() + .to_string() + .contains("2 x 2") + ); +} + +/// Reviewer re-test case: holes are filled on both sides, so a model missing a 100 x 100 +/// through-hole scores ~1.000 against a picture that shows the hole. That is the contract — +/// outline only — and the command description must say so, so an agent does not read 1.000 +/// as "matches". +#[test] +fn the_compare_is_outline_only_holes_are_not_compared() { + assert!( + crate::cmd::compare_picture::COMMANDS[0].params.contains("holes are not compared"), + "the command description must say the compare is outline only" + ); + let mut s = Session::default(); + // A solid 200 x 200 mm plate against a picture of a plate with a 100 x 100 through-hole. + box_body(&mut s, "Plate", 200.0, 10.0, 200.0); + let path = reference( + "hole-only.png", + &png(220, 220, |x, y| { + let plate = (10..210).contains(&x) && (10..210).contains(&y); + let hole = (60..160).contains(&x) && (60..160).contains(&y); + if plate && !hole { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The outlines match: the hole is not compared, as the description says. + assert!(out["overlap"].as_f64().unwrap() > 0.98, "overlap {}", out["overlap"]); +} + +/// Reviewer re-test case: a white part on (245, 245, 245) saved as JPEG at quality 75 gave +/// "no part" even on the stricter retry — the codec blurs the 10-level step at the part's +/// outline into steps of a few levels each, under any local limit. The third pass takes the +/// backdrop globally: near the border's main colour. +#[test] +fn a_light_jpeg_keeps_its_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = reference( + "light.jpg", + &jpeg_q(200, 300, 75, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [245, 245, 245] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index b6aab16be..d33fdbcff 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -31,7 +31,8 @@ mod relink_tests; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params( "path: a .sc design → a new component linked to it, holding its solid bodies as placed in that design and a copy of its design properties; \ - name? (default: the design's name); parent?: component id or name (default: the active one); translate?: [x,y,z]; \ + name? (default: the design's name); parent?: component id or name (default: the active one); \ + translate?: [x,y,z] in mm from the destination parent's origin (default [0,0,0], also with reuse); \ reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available", ), CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params( @@ -507,8 +508,13 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { if p.get("reuse").and_then(Value::as_bool).unwrap_or(false) { let existing = s.doc.links.iter().find(|(_, link)| absolute(&resolve(s.path.as_deref(), &link.path)) == file).map(|(id, _)| *id); if let Some(component) = existing { - let parent = p.get("parent").cloned().unwrap_or_else(|| json!(s.active_component)); - return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate})); + let parent = if p.get("parent").is_some() { component_key(s, p, "parent", cmd)? } else { s.active_component }; + // Reuse the definition, not another placement's captured or pending move. + // Insert Design places from the parent origin whether the link is new or reused. + let mut transform = solidcraft_doc::IDENTITY; + transform[3] = [translate.x, translate.y, translate.z, 1.0]; + let occurrence = s.doc_mut().add_occurrence(component, parent, transform)?; + return Ok(json!({"occurrence": occurrence, "component": component})); } } let ((design_name, sf, faces, metadata, properties), read) = linked_bodies_read(&file, s.path.as_deref(), s.validation())?; diff --git a/crates/engine/src/cmd/component_relink_tests.rs b/crates/engine/src/cmd/component_relink_tests.rs index 4044b5b76..f214f20ab 100644 --- a/crates/engine/src/cmd/component_relink_tests.rs +++ b/crates/engine/src/cmd/component_relink_tests.rs @@ -161,6 +161,90 @@ fn reused_design_insertion_is_free_even_before_a_link_exists() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn reused_design_insertion_uses_the_requested_position_and_survives_undo_and_reopen() { + let dir = folder("reuse-position"); + let file = dir.join("part.sc"); + part(&file, 30); + for first_reuses in [false, true] { + let mut s = Session::default(); + let first = run(&mut s, "component.insert_design", json!({"path": file, "translate": [20, 0, 0], "reuse": first_reuses})); + let before = s.doc.to_json(); + let undo = s.undo.len(); + let second = run(&mut s, "component.insert_design", json!({"path": file, "translate": [40, 5, 7], "reuse": true})); + assert_eq!(first["component"], second["component"]); + assert_eq!(s.doc.links.len(), 1); + assert_eq!(s.doc.features.len(), 1); + assert_eq!(s.undo.len(), undo + 1); + let occurrence = second["occurrence"].as_u64().unwrap(); + assert_linked_bounds(&mut s, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + assert_linked_bounds(&mut s, first["occurrence"].as_u64().unwrap(), [20.0, 0.0, 0.0], [30.0, 20.0, 30.0]); + assert!(!s.doc.occurrences.iter().find(|o| o.id == occurrence).unwrap().grounded); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert_linked_bounds(&mut s, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + let assembly = dir.join("assembly.sc"); + run(&mut s, "file.save", json!({"path": assembly})); + let mut cold = Session::default(); + run(&mut cold, "doc.open", json!({"path": assembly})); + assert_linked_bounds(&mut cold, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + let at_origin = run(&mut cold, "component.insert_design", json!({"path": file, "reuse": true}))["occurrence"].as_u64().unwrap(); + assert_linked_bounds(&mut cold, at_origin, [0.0, 0.0, 0.0], [10.0, 20.0, 30.0]); + } + let _ = std::fs::remove_dir_all(dir); +} + +fn assert_linked_bounds(s: &mut Session, occurrence: u64, min: [f64; 3], max: [f64; 3]) { + let p = run(s, "occurrence.properties", json!({"occurrence": occurrence})); + assert_eq!(p["body_count"], 1); + assert!((p["total"]["volume_mm3"].as_f64().unwrap() - 6000.0).abs() < 1e-6, "{p}"); + for (key, expected) in [("min", min), ("max", max)] { + for (axis, expected) in expected.into_iter().enumerate() { + assert!((p["total"]["bbox"][key][axis].as_f64().unwrap() - expected).abs() < 1e-6, "{key}[{axis}] != {expected}: {p}"); + } + } +} + +#[test] +fn reused_design_insertion_ignores_existing_moves_and_uses_the_destination_parent() { + let dir = folder("reuse-parent"); + let file = dir.join("part.sc"); + part(&file, 30); + for capture in [false, true] { + let mut s = Session::default(); + let first = run(&mut s, "component.insert_design", json!({"path": file, "translate": [20, 0, 0]})); + run( + &mut s, + "occurrence.move", + json!({"occurrence": first["occurrence"], "translate": [0, 10, 0], "axis": [0, 0, 1], "angle": "90 deg", "capture": capture, "move_grounded": true}), + ); + let original = s.doc.occurrences.clone(); + let pending = s.pending_moves.clone(); + let parent = run(&mut s, "component.create", json!({"name": "Parent", "activate": false})); + run(&mut s, "occurrence.move", json!({"occurrence": parent["occurrence"], "translate": [100, 0, 0], "axis": [0, 0, 1], "angle": "90 deg"})); + for explicit_parent in [true, false] { + let mut params = json!({"path": file, "translate": [40, 5, 7], "reuse": true}); + if explicit_parent { + params["parent"] = json!("Parent"); + } else { + run(&mut s, "component.activate", json!({"component": parent["component"]})); + } + let inserted = run(&mut s, "component.insert_design", params); + assert_eq!(inserted["component"], first["component"]); + assert_linked_bounds(&mut s, inserted["occurrence"].as_u64().unwrap(), [75.0, 40.0, 7.0], [95.0, 50.0, 37.0]); + assert_eq!(s.doc.occurrences.first(), original.first()); + assert_eq!(s.pending_moves, pending); + } + let before = s.doc.to_json(); + for parent in [json!("missing"), first["component"].clone()] { + assert!(s.execute("component.insert_design", &json!({"path": file, "parent": parent, "reuse": true})).is_err()); + assert_eq!(s.doc.to_json(), before); + } + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn linked_design_properties_update_density_without_geometry_and_keep_edited_cards() { let dir = folder("properties-density"); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 96bfd003c..e30c1c298 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -10,6 +10,14 @@ use crate::params::{bad, bool_, name_or_id_values, num, str_}; use crate::{EngineError, Result, Sel, Session, Snapshot}; pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("ui.assistant", "Toggle Assistant", crate::checked!("ui.assistant", assistant)) + .icon("assistant") + .key("Ctrl+Shift+A") + .noundo() + .doc_only() + .contract(&ASSISTANT_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("Show or hide Assistant in the app. Headless calls are refused without changing the design"), CommandSpec::new("edit.undo", "Undo", undo).icon("undo").key("Ctrl+Z").noundo().doc_only(), CommandSpec::new("edit.redo", "Redo", redo).icon("redo").key("Ctrl+Y").noundo().doc_only(), CommandSpec::new("edit.repeat", "Repeat Last Command", crate::checked!("edit.repeat", repeat)) @@ -119,6 +127,12 @@ fn redo(s: &mut Session, _p: &Value) -> Result { Ok(json!({"redone": label})) } +const ASSISTANT_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +fn assistant(_s: &mut Session, _p: &Value) -> Result { + Err(EngineError::Other("ui.assistant shows or hides Assistant in the app; no assistant panel exists in a headless session".into())) +} + const REPEAT_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); /// Repeat Last Command (#7077) starts a tool, which only the app has: it starts the last one in @@ -1125,7 +1139,7 @@ fn inspect_feature(s: &mut Session, p: &Value) -> Result { let rolled_back = s.doc.features.iter().position(|x| x.id == id).is_some_and(|i| i >= marker); let r = s.model.result(id); Ok(json!({ - "id": f.id, "name": f.name, "type": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": rolled_back, + "id": f.id, "name": f.name, "type": f.kind.kind_key(), "type_name": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": rolled_back, "definition": def, "omitted": omitted, "inputs": inputs, "error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone()), })) @@ -1741,6 +1755,11 @@ fn redefine(s: &mut Session, p: &Value) -> Result { } trial.doc_mut().marker = Some(idx + 1); trial.refresh(); + // The edited feature keeps its name. Its temporary replacement needs a fresh one while + // the original remains in the trial as a placeholder (including construction planes). + if let Some(parameters) = params.as_object_mut() { + parameters.remove("name"); + } let r = spec.run_nested(&mut trial, ¶ms)?; let made = r.get("feature").and_then(Value::as_u64).ok_or_else(|| bad(cmd, format!("`{cid}` did not make a feature")))?; let mut new = trial.doc.feature(made).cloned().ok_or_else(|| bad(cmd, format!("`{cid}` did not make a feature")))?; diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index 6ba32b425..05c950810 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -1652,3 +1652,14 @@ fn edits_after_a_canvas_share_its_image_with_every_undo_state() { assert_eq!(s.doc.canvases[0].data.as_ptr(), image, "undo brings back the same image"); assert_eq!(s.doc.canvases[0].bytes().as_deref(), Some(png.as_slice())); } + +#[test] +fn assistant_toggle_is_refused_headlessly_without_changing_the_document() { + let mut s = Session::default(); + let before = (s.doc.to_json(), s.undo.len()); + let error = s.execute("ui.assistant", &json!({})).unwrap_err().to_string(); + assert!(error.contains("headless session"), "{error}"); + assert_eq!((s.doc.to_json(), s.undo.len()), before); + let spec = crate::find_command("ui.assistant").unwrap(); + assert_eq!((spec.shortcut, spec.tab, spec.undoable), (Some("Ctrl+Shift+A"), "", false)); +} diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 0070842f5..4bb751233 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -1644,8 +1644,8 @@ pub(crate) fn edge_ref_form(e: &Value) -> std::result::Result, & Ok(EdgeRefForm::Index { body, index }) } -/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); an -/// edge is rounded (a fillet). +/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); a +/// fillet's or chamfer's face changes that feature's size; an edge is rounded (a fillet). fn press_pull(s: &mut Session, p: &Value) -> Result { let cmd = "solid.press_pull"; let distance = req_expr(cmd, p, "distance")?; @@ -1657,10 +1657,9 @@ fn press_pull(s: &mut Session, p: &Value) -> Result { if d.abs() < 1e-9 { return Err(bad(cmd, "the distance must not be zero")); } - // A fillet's or chamfer's face: its size changes by the distance (the feature is edited). - if let Some(fp) = vec3(face) - && super::face::face_is_planar(s, fp) == Some(false) - { + // A fillet's or chamfer's face: its size changes by the distance (the feature is edited). A + // chamfer's face is flat, so this is asked before whether the face is planar (#4986). + if let Some(fp) = vec3(face) { let name = solidcraft_doc::naming::face_names_at(&s.model.state(), &[fp]).into_iter().next().unwrap_or_default(); let fid = solidcraft_doc::persistent_name::made_by(&name); if solidcraft_doc::persistent_name::is_blend(&name) { @@ -1678,8 +1677,10 @@ fn press_pull(s: &mut Session, p: &Value) -> Result { return Ok(json!({"feature": f.id, "edited": f.name, key: new, "recomputed": out.get("recomputed"), "restored": out.get("restored")})); } // Another curved face moves along its normal. - let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?; - return (r.run)(s, &json!({"faces": [face], "distance": distance})); + if super::face::face_is_planar(s, fp) == Some(false) { + let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?; + return (r.run)(s, &json!({"faces": [face], "distance": distance})); + } } // Pushed in: the extrude cuts the other way by as much (a bare number stays one, so it keeps // being read as a bare number typed into the extrude). diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index dc03d6ccb..1e7a1def5 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -61,6 +61,39 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("export") .noundo() .params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"), + // One command per format, so each File › Export item can have a key of its own; started + // from a key or command search, the app opens the save picker (the mesh dialog for STL and + // 3MF). Each takes `file.export`'s parameters for its format, without `format`. + CommandSpec::new("file.export_step", "Export STEP", crate::checked!("file.export_step", export_step)) + .icon("export") + .noundo() + .contract(&EXPORT_STEP_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body; a design with components then exports as a STEP assembly) → {path, bytes, format}: STEP, whatever the path's extension"), + CommandSpec::new("file.export_stl", "Export STL", crate::checked!("file.export_stl", export_stl)) + .icon("mesh_export") + .noundo() + .contract(&EXPORT_STL_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format}: binary STL, whatever the path's extension"), + CommandSpec::new("file.export_3mf", "Export 3MF", crate::checked!("file.export_3mf", export_3mf)) + .icon("mesh_export") + .noundo() + .contract(&EXPORT_3MF_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard); objects?: body|component (as file.export) → {path, bytes, format}: 3MF, whatever the path's extension"), + CommandSpec::new("file.export_obj", "Export OBJ", crate::checked!("file.export_obj", export_obj_cmd)) + .icon("export") + .noundo() + .contract(&EXPORT_OBJ_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format, files}: OBJ, with the colours of the bodies in a material library (`.mtl`) next to it"), + CommandSpec::new("file.export_urdf", "Export URDF", crate::checked!("file.export_urdf", export_urdf_cmd)) + .icon("export") + .noundo() + .contract(&EXPORT_URDF_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; mesh_prefix?; effort? (default 1000); velocity? (default 10) → {path, format, files, links, joints, warnings}: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md"), CommandSpec::new("file.save_mesh", "Save As Mesh", save_mesh) .at("INSERT", "FILES") .icon("mesh_export") @@ -89,6 +122,12 @@ fn new_doc(s: &mut Session, p: &Value) -> Result { Ok(json!({"name": name})) } +const EXPORT_STEP_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_STL_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_3MF_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_OBJ_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_URDF_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + fn path_arg<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> { str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required")) } @@ -726,6 +765,7 @@ fn component_parts(s: &Session) -> Vec<(String, Vec)> { fn export_to( s: &Session, + cmd: &str, path: &str, format: Format, bodies: &[String], @@ -740,7 +780,7 @@ fn export_to( // A design with components exports as a STEP assembly; otherwise bodies as placed. let bytes = if format == Format::Design { if !bodies.is_empty() { - return Err(bad("file.export", "design JSON exports the complete document; omit bodies")); + return Err(bad(cmd, "design JSON exports the complete document; omit bodies")); } solidcraft_io::write_design(&s.design()) } else if format == Format::Step && bodies.is_empty() && !s.doc.occurrences.is_empty() { @@ -779,11 +819,44 @@ fn export(s: &mut Session, p: &Value) -> Result { let path = path_arg(p, cmd)?; let format = Format::from_name(str_(p, "format").unwrap_or(path))?; if format == Format::Urdf { - return export_urdf(s, path, p); + if !string_list(cmd, p, "bodies")?.is_empty() { + return Err(bad(cmd, "urdf exports the whole assembly; omit bodies")); + } + return export_urdf(s, cmd, path, p); } let quality = mesh_quality(p, cmd)?; let parts = mesh_parts(s, p, cmd, format)?; - export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) + export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) +} + +fn export_step(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_step"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::Step, &string_list(cmd, p, "bodies")?, &[], solidcraft_io::MeshQuality::default()) +} + +fn export_stl(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_stl"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::StlBinary, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?) +} + +fn export_3mf(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_3mf"; + let path = path_arg(p, cmd)?; + let parts = mesh_parts(s, p, cmd, Format::ThreeMf)?; + export_to(s, cmd, path, Format::ThreeMf, &string_list(cmd, p, "bodies")?, &parts, mesh_quality(p, cmd)?) +} + +fn export_obj_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_obj"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::Obj, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?) +} + +fn export_urdf_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_urdf"; + export_urdf(s, cmd, path_arg(p, cmd)?, p) } /// The OBJ export: the mesh file and the material library beside it, with the colours of the @@ -814,11 +887,7 @@ fn export_obj(s: &Session, path: &str, bodies: &[String], quality: solidcraft_io /// The assembly as a URDF and its meshes next to it (docs/urdf.md). Every path is checked before /// anything is written; the meshes go first and the `.urdf` last. -fn export_urdf(s: &Session, path: &str, p: &Value) -> Result { - let cmd = "file.export"; - if !string_list(cmd, p, "bodies")?.is_empty() { - return Err(bad(cmd, "urdf exports the whole assembly; omit bodies")); - } +fn export_urdf(s: &Session, cmd: &str, path: &str, p: &Value) -> Result { let positive = |k: &str| match p.get(k) { None | Some(Value::Null) => Ok(None), Some(_) => num(p, k).filter(|x| *x > 0.0).map(Some).ok_or_else(|| bad(cmd, format!("`{k}` must be a positive number"))), @@ -915,7 +984,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result { }, ); } - export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) + export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) } /// The browser build can't start a program. @@ -1103,6 +1172,43 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Each format's own export command (one key each in Keyboard Shortcuts) writes that format + /// whatever the path's extension, as `file.export` does with `format`, and says so. + #[test] + fn each_format_has_an_export_command_of_its_own() { + let dir = std::env::temp_dir().join(format!("solidcraft-export-per-format-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let at = |n: &str| dir.join(n).to_string_lossy().to_string(); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})).unwrap(); + for (cmd, format, signature) in [ + ("file.export_step", "Step", &b"ISO-10303-21;"[..]), + ("file.export_3mf", "ThreeMf", &b"PK"[..]), + ("file.export_obj", "Obj", &b""[..]), + ("file.export_stl", "StlBinary", &b""[..]), + ] { + // A name with another format's extension: the command, not the name, picks the format. + let path = at(&format!("{format}.txt")); + let r = s.execute(cmd, &json!({"path": path})).unwrap(); + assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(path.as_str()), Some(format)), "{cmd}: {r}"); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64), "{cmd}"); + assert!(bytes.starts_with(signature), "{cmd}"); + } + // The triangles `file.export` writes (the 80-byte header holds the file's name): a box is + // 12 triangles, 84 + 50 bytes each. + s.execute("file.export", &json!({"path": at("box.stl")})).unwrap(); + assert_eq!(std::fs::read(at("StlBinary.txt")).unwrap()[80..], std::fs::read(at("box.stl")).unwrap()[80..]); + assert_eq!(std::fs::metadata(at("box.stl")).unwrap().len(), 84 + 50 * 12); + let obj = std::fs::read_to_string(at("Obj.txt")).unwrap(); + assert_eq!(obj.lines().filter(|l| l.starts_with("f ")).count(), 12, "{obj}"); + let r = s.execute("file.export_urdf", &json!({"path": at("robot.urdf")})).unwrap(); + assert_eq!(r["format"], "Urdf"); + assert!(std::fs::read_to_string(at("robot.urdf")).unwrap().contains(" Option 1.0 - 1e-6)); let mut json = json!({"type": "face", "area_mm2": area, "planar": planar.is_some()}); let verts: Vec = tris.iter().flat_map(|t| t.iter().copied()).collect(); - let shape = match solidcraft_kernel::face_surface(&b.body, *index) { + let surface = solidcraft_kernel::face_surface(&b.body, *index); + let shape = match surface { Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }) => { super::measure_shape::cylinder(origin, axis, radius, &verts).unwrap_or(Shape::Other) } @@ -365,6 +366,7 @@ fn describe(s: &Session, st: &solidcraft_doc::ModelState, sel: &Sel) -> Option Shape::Other, }; add_round(&mut json, &shape); + super::measure_shape::add_curved(&mut json, surface); let slot = if matches!(shape, Shape::Round { .. }) && !shape.full() { face_slot(b, &m, &shape, &verts) } else { None }; if let Some(sl) = &slot { json["slot"] = sl.json(); diff --git a/crates/engine/src/cmd/measure_shape.rs b/crates/engine/src/cmd/measure_shape.rs index 71fb6904a..cbe9b712e 100644 --- a/crates/engine/src/cmd/measure_shape.rs +++ b/crates/engine/src/cmd/measure_shape.rs @@ -68,6 +68,27 @@ pub(crate) fn add_round(v: &mut Value, shape: &Shape) { }); } +/// The radius of a toroidal or spherical face, added to its description: a fillet round a +/// circular edge is a torus whose tube radius is the fillet's (`major_radius` is the ring +/// through the middle of the rolling ball), a ball or a spherical corner patch a sphere. These +/// faces have no axis to measure from, so they stay out of [`Shape`]. +pub(crate) fn add_curved(v: &mut Value, surface: Option) { + use solidcraft_kernel::FaceSurface; + let (radius, kind) = match surface { + Some(FaceSurface::Torus { minor, major, .. }) if minor.is_finite() && minor > 0.0 => { + if major.is_finite() { + v["major_radius"] = json!(major.abs()); + } + (minor, "torus") + } + Some(FaceSurface::Sphere { radius, .. }) if radius.is_finite() && radius > 0.0 => (radius, "sphere"), + _ => return, + }; + v["diameter"] = json!(2.0 * radius); + v["radius"] = json!(radius); + v["surface"] = json!(kind); +} + /// Cylinder `axis` through `origin` of radius `radius` over the points of its face: the /// round shape, centred level with the middle of the face, with its extent and coverage. pub(crate) fn cylinder(origin: Vec3, axis: UnitVec3, radius: f64, pts: &[Vec3]) -> Option { diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index ca96a6199..c76ed7bd8 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -26,6 +26,9 @@ pub(crate) mod clearance; mod clipboard; mod clipboard_foreign; mod compare; +mod compare_picture; +#[cfg(test)] +mod compare_picture_tests; mod component; mod component_clone; mod component_clone_assembly; @@ -346,6 +349,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(metadata::COMMANDS.iter()); v.extend(inspect::COMMANDS.iter()); v.extend(compare::COMMANDS.iter()); + v.extend(compare_picture::COMMANDS.iter()); v.extend(silhouette::COMMANDS.iter()); v.extend(materials::COMMANDS.iter()); v.extend(material_properties::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index de8a6f697..64001d6c0 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -68,7 +68,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("render.optics.unbind","Remove Optical Binding",optical_bindings::unbind).icon("appearance").doc_only() .params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."), CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only() - .params("job: exact completed JobId; presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."), + .params("job?: exact completed JobId (default selected result); presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."), CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only() .params("camera: complete Render Camera snapshot (target, yaw, pitch, distance, fov; roll defaults to 0 and up to z). Validates the same finite mm/radian bounds as saved render intent, preserves explicit roll/up and changes only transient view state. No model evaluation, setup save, renderer, dirty flag or undo step. Design view.apply retains its separate up-axis policy."), CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo() @@ -102,7 +102,7 @@ CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_ CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only() .params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."), CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only() - .params("job: completed JobId, or null to release the displayed-result pin. Retains at most one completed result independently of a newer completion; preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."), + .params("job?: completed JobId (default selected result), or null to clear selection. Selects within the eight retained completed results; oldest is evicted first. Preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."), CommandSpec::new("render.library.targets", "Find Render Library Targets", library::targets).icon("list").noundo() .params("query?: exact-name substring; offset?:0; limit?:128 (1..128). Returns a bounded page of captured body ordinals/names, revision and scene bounds. Settles the model through ordinary command handling; never returns a large mesh payload."), CommandSpec::new("render.library.list", "Browse Render Library", library::list).icon("list").noundo().doc_only() @@ -128,13 +128,13 @@ CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).ic CommandSpec::new("render.start", "Render Image", jobs::start).key("R").noundo().doc_only().at("RENDER", "IMAGE").icon("render_image") .params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"), CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only() - .params("job: {session, serial, generation}. Non-blocking progress, error, optional CPU preview metadata {frame_sequence,samples_per_pixel,frame}, and completed frame metadata, optional sampling allocation/work counts and retained-master presentation provenance; no image bytes and no rendering in this call. Preview is separate from the exportable final image."), + .params("job?: {session, serial, generation}. Non-blocking progress, errors and captured frame metadata with queue:{running,waiting,job,shot,error}. Without job returns queue only. Advances an explicitly started render.batch through render.start as jobs finish; never pumps render work. Preview is separate from the exportable final image."), CommandSpec::new("render.cancel", "Cancel Render", jobs::cancel).icon("delete").noundo().doc_only() - .params("job: {session, serial, generation}. Requests cooperative cancellation; completed jobs remain completed. Late cancelled frames cannot be published."), + .params("job?: {session, serial, generation}, default the active render.batch job. Requests cooperative cancellation and drops its waiting shots; completed jobs remain completed. Late cancelled frames cannot be published."), CommandSpec::new("render.result.copy", "Copy Render Image", jobs::copy).icon("copy").noundo().doc_only() - .params("job: completed JobId. Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."), + .params("job?: completed JobId (default selected result). Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."), CommandSpec::new("render.export", "Export Render Image", jobs::export).icon("export").noundo().doc_only() - .params("job: {session, serial, generation}, path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"), + .params("job?: {session, serial, generation} (default selected result), path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"), CommandSpec::new("render.backends", "Render Backends", backends).icon("list") .noundo() .doc_only() diff --git a/crates/engine/src/cmd/render/job_tests.rs b/crates/engine/src/cmd/render/job_tests.rs index 02ee106a0..f15ddeff3 100644 --- a/crates/engine/src/cmd/render/job_tests.rs +++ b/crates/engine/src/cmd/render/job_tests.rs @@ -1052,6 +1052,14 @@ fn completed_png_content_identity_matches_status_and_exact_retained_export() { finish(&host); let newer = s.execute("render.status", &json!({"job":replacement})).unwrap(); assert_ne!(newer["frame"]["png_sha256"], metadata["png_sha256"]); + let still_retained = dir.join("still-retained.png"); + s.execute("render.export", &json!({"job":id,"path":still_retained})).unwrap(); + assert_eq!(std::fs::read(still_retained).unwrap(), bytes); + for _ in 0..7 { + let next = start(&mut s); + finish(&host); + s.execute("render.status", &json!({"job":next})).unwrap(); + } let evicted = dir.join("evicted.png"); assert!(s.execute("render.export", &json!({"job":id,"path":evicted})).is_err()); assert!(!evicted.exists()); @@ -1281,7 +1289,12 @@ fn output_viewer_copy_validates_completed_job_without_mutation_or_pixel_payloads assert_eq!(copied["frame"]["job"], json!(job)); assert_eq!(copied["frame"]["width"], 16); assert!(copied.get("png").is_none()); - for params in [json!({}), json!(null), json!({"job":job,"extra":true}), json!({"job":{"session":0,"serial":0,"generation":0}})] { + for params in [json!({}), json!(null)] { + assert_eq!(s.execute("render.result.copy", ¶ms).unwrap(), copied, "an omitted job uses the selected result"); + } + for params in + [json!({"job":1e300}), json!({"job":"selected"}), json!({"job":job,"extra":true}), json!({"job":{"session":0,"serial":0,"generation":0}})] + { assert!(s.execute("render.result.copy", ¶ms).is_err()); } assert!(Arc::ptr_eq(&document, &s.doc)); diff --git a/crates/engine/src/cmd/render/jobs.rs b/crates/engine/src/cmd/render/jobs.rs index b0b0b29de..86d4161db 100644 --- a/crates/engine/src/cmd/render/jobs.rs +++ b/crates/engine/src/cmd/render/jobs.rs @@ -675,7 +675,12 @@ pub(super) fn start(s: &mut Session, params: &Value) -> Result { p.scene, p.request, p.replace, - crate::render_jobs::Execution { executor: p.executor, options: p.options, environment: p.environment }, + crate::render_jobs::Execution { + executor: p.executor, + options: p.options, + environment: p.environment, + shot: params.get("setup").and_then(Value::as_str).map(str::to_owned), + }, ) .map_err(job_error)?; let mut status = json!(status); @@ -688,24 +693,32 @@ pub(super) fn start(s: &mut Session, params: &Value) -> Result { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Regrade { - job: JobId, + job: Option, presentation: solidcraft_render::job::presentation::Presentation, } pub(super) fn regrade(s: &mut Session, params: &Value) -> Result { let input: Regrade = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.regrade", e.to_string()))?; input.presentation.validate().map_err(job_error)?; - Ok(json!(s.render_jobs.regrade(input.job, input.presentation).map_err(job_error)?)) + let job = result_source(s, input.job, "render.result.regrade")?; + Ok(json!(s.render_jobs.regrade(job, input.presentation).map_err(job_error)?)) } -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Job { - job: JobId, +fn result_source(s: &mut Session, job: Option, command: &str) -> Result { + s.render_jobs.collect().map_err(job_error)?; + job.or_else(|| s.render_selected_result()).ok_or_else(|| bad(command, "no completed result is selected")) } pub(super) fn status(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?; - Ok(json!(s.render_jobs.status(input.job).map_err(job_error)?)) + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?; + s.advance_render_batch()?; + let Some(job) = input.job else { + return Ok(json!({"queue":s.render_queue_state()})); + }; + let mut reply = json!(s.render_jobs.status(job).map_err(job_error)?); + if let Some(object) = reply.as_object_mut() { + object.insert("queue".into(), json!(s.render_queue_state())); + } + Ok(reply) } #[derive(Deserialize)] @@ -714,18 +727,23 @@ struct Pin { job: Option, } pub(super) fn pin(s: &mut Session, params: &Value) -> Result { - if params.get("job").is_none() { - return Err(bad("render.result.pin", "job or explicit null is required")); - } let input: Pin = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.pin", e.to_string()))?; - Ok(json!({"frame":s.render_jobs.pin(input.job).map_err(job_error)?})) + let job = if params.get("job").is_some_and(Value::is_null) { None } else { Some(result_source(s, input.job, "render.result.pin")?) }; + Ok(json!({"frame":s.render_jobs.pin(job).map_err(job_error)?})) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ResultJob { + job: Option, } pub(super) fn copy(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?; + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?; + let job = result_source(s, input.job, "render.result.copy")?; let frame = s .render_jobs - .handle(input.job) + .handle(job) .map_err(job_error)? .frame() .map_err(job_error)? @@ -738,12 +756,14 @@ pub(super) fn copy(s: &mut Session, params: &Value) -> Result { } pub(super) fn cancel(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?; - let status = s.render_jobs.status(input.job).map_err(job_error)?; + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?; + let job = input.job.or(s.render_queue_state().job).ok_or_else(|| bad("render.cancel", "job is required without an active shot queue"))?; + let status = s.render_jobs.status(job).map_err(job_error)?; + s.cancel_render_batch(job); if status.progress.phase.terminal() { return Ok(json!(status)); } - Ok(json!(s.render_jobs.handle(input.job).map_err(job_error)?.cancel().map_err(job_error)?)) + Ok(json!(s.render_jobs.handle(job).map_err(job_error)?.cancel().map_err(job_error)?)) } #[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] @@ -766,7 +786,7 @@ impl ExportFormat { struct Export { #[serde(default)] format: ExportFormat, - job: JobId, + job: Option, path: String, #[serde(default)] overwrite: bool, @@ -784,7 +804,8 @@ pub(super) fn export(s: &mut Session, params: &Value) -> Result { // Atomic native writers are also used for the app's own files and do not // apply a request's path scope. Check the caller's destination explicitly. solidcraft_io::vfs::check(&input.path).map_err(|e| bad("render.export", e.to_string()))?; - let frame = s.render_jobs.frame(input.job).map_err(job_error)?; + let job = result_source(s, input.job, "render.export")?; + let frame = s.render_jobs.frame(job).map_err(job_error)?; let bytes = match input.format { ExportFormat::Png => frame.png(), ExportFormat::Exr => frame @@ -797,7 +818,7 @@ pub(super) fn export(s: &mut Session, params: &Value) -> Result { if input.overwrite { solidcraft_io::write_atomic(path, bytes, false) } else { solidcraft_io::safe_write::create_atomic(path, bytes) }; result.map_err(|e| bad("render.export", format!("could not export completed {}: {e}", input.format.extension())))?; Ok( - json!({"job":input.job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}), + json!({"job":job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}), ) } diff --git a/crates/engine/src/cmd/render_ui.rs b/crates/engine/src/cmd/render_ui.rs index d6f4f28d2..261ee48d1 100644 --- a/crates/engine/src/cmd/render_ui.rs +++ b/crates/engine/src/cmd/render_ui.rs @@ -1,7 +1,10 @@ -//! Planned Render interactions, with explicit non-mutating refusals. +//! Transient Render view requests and explicit refusals for planned interactions. use super::CommandSpec; use crate::schema::render_lights::{MuteParams, SoloParams}; -use crate::schema::{TypedContract, output_schema_for, render_ui::CheckReport}; +use crate::schema::{ + TypedContract, output_schema_for, + render_ui::{BatchParams, BatchResult, CheckReport, CompareDivider, CompareParams, CompareSide, ResultIndex}, +}; use crate::{Result, Session, params::bad}; use serde::Deserialize; use serde_json::{Value, json}; @@ -33,19 +36,10 @@ fn mute(_: &mut crate::Session, params: &serde_json::Value) -> crate::Result { - CommandSpec::new($id, $label, |_, _| Err(crate::EngineError::Other(concat!("not supported yet: ", $reason).into()))) - .enabled(|_| Err(concat!("not supported yet: ", $reason).into())) - .planned("5493") - .noundo() - .doc_only() - .at($tab, $panel) - .icon($icon) - .params("No supported parameters. Always refuses without changing the design or history.") - }; -} +const RESULT_INDEX: TypedContract = TypedContract::new(); +const COMPARE: TypedContract = TypedContract::new(); +const DIVIDER: TypedContract = TypedContract::new(); +const BATCH: TypedContract = TypedContract::new(); const CHECK_REPORT: TypedContract = TypedContract::new(); @@ -57,6 +51,16 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .doc_only() .params("text: nonempty report, at most 65536 bytes. Validated clipboard request; headless echo only, never renders or edits a design."), + CommandSpec::new("render.result.select", "Select Render Result", crate::checked!("render.result.select", select_result)) + .icon("render_image").noundo().doc_only() + .enabled(results_ready) + .contract(&RESULT_INDEX).output(output_schema_for::) + .params("index: integer 0..7, oldest first; must be retained. Selects a completed result as transient per-document view state; echoes index."), + CommandSpec::new("render.result.discard", "Discard Render Result", crate::checked!("render.result.discard", discard_result)) + .icon("delete").noundo().doc_only() + .enabled(results_ready) + .contract(&RESULT_INDEX).output(output_schema_for::) + .params("index: integer 0..7, oldest first; must be retained. Drops only that transient result, selecting the newest remaining result if necessary; echoes index."), CommandSpec::new("render.output.size", "Set Render Output Size", output_size) .icon("settings") .noundo() @@ -88,8 +92,20 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo().doc_only().icon("render_scene").at("RENDER SCENE","LIGHTS") .contract(&MUTE).output(crate::schema::output_schema_for::) .params("id: kind:slot light address; mute:bool. Validates and echoes per-document UI view state, applied to live preview and captured render copies only. Never changes saved settings or history."), - waiting!("render.compare", "Compare Images", "RENDER", "RESULT", "compare", "retained image comparison"), - waiting!("render.batch", "Render All Shots", "RENDER", "BATCH", "render_image", "the saved-shot render queue"), + CommandSpec::new("render.compare", "Compare Images", crate::checked!("render.compare", compare)) + .icon("compare").noundo().doc_only().at("RENDER", "RESULT") + .enabled(results_ready) + .contract(&COMPARE).output(output_schema_for::) + .params("left, right: live or retained result index 0..7 (oldest first), distinct and retained; OR off:true. Validated per-document comparison view request; headless echo, no rendering or design/history change."), + CommandSpec::new("render.compare.divider", "Move Render Comparison Divider", crate::checked!("render.compare.divider", divider)) + .icon("compare").noundo().doc_only() + .contract(&DIVIDER).output(output_schema_for::) + .params("position: finite number, clamped to 0.05..0.95. Transient comparison divider request; headless echo only."), + CommandSpec::new("render.batch", "Render All Shots", crate::checked!("render.batch", batch)) + .icon("render_image").noundo().doc_only().at("RENDER", "BATCH") + .enabled(|s| s.render_batch_ready()) + .contract(&BATCH).output(output_schema_for::) + .params("request?: render.start parameters, shared across all saved shots except camera. Default: first saved setup in name order. Captures up to 32 shot cameras and queues sequentially through render.start; returns {queued:n}. Refuses active renders, no shots or stale geometry. render.status (also with {}) and the UI tick advance the queue; Cancel on the active job drops waiting shots. No design/history/revision change."), ]; fn copy_check(_: &mut Session, params: &Value) -> Result { @@ -100,6 +116,110 @@ fn copy_check(_: &mut Session, params: &Value) -> Result { Ok(json!({"text":report.text})) } +fn compare(s: &mut Session, params: &Value) -> Result { + let input: CompareParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.compare", e.to_string()))?; + match input { + CompareParams::Off(off) if off.off => { + s.render_jobs.set_comparison(None); + Ok(json!({"off":true})) + } + CompareParams::Pair(pair) => { + if pair.left == pair.right { + return Err(bad("render.compare", "comparison sides must differ")); + } + let results = s.render_retained_results()?; + for side in [pair.left, pair.right] { + if let CompareSide::Result(index) = side + && (index > 7 || results.get(index as usize).is_none()) + { + return Err(bad("render.compare", "retained result index is out of bounds")); + } + } + let resolve = |side| match side { + CompareSide::Live(_) => None, + CompareSide::Result(index) => results.get(index as usize).map(|result| result.frame.job), + }; + s.render_jobs.set_comparison(Some([resolve(pair.left), resolve(pair.right)])); + Ok(json!({"left":pair.left,"right":pair.right})) + } + _ => Err(bad("render.compare", "off must be true")), + } +} + +fn divider(_: &mut Session, params: &Value) -> Result { + let input: CompareDivider = serde_json::from_value(params.clone()).map_err(|e| bad("render.compare.divider", e.to_string()))?; + if !input.position.is_finite() { + return Err(bad("render.compare.divider", "position must be finite")); + } + Ok(json!({"position":input.position.clamp(0.05,0.95)})) +} + +fn batch(s: &mut Session, params: &Value) -> Result { + let input: BatchParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.batch", e.to_string()))?; + s.render_batch_ready().map_err(|reason| bad("render.batch", reason))?; + if s.model.is_stale() { + return Err(bad("render.batch", "finish the modelling gesture before rendering shots")); + } + for name in s.doc.render.setups.keys() { + solidcraft_doc::render_settings::RenderSettings::validate_name(name).map_err(|error| bad("render.batch", error.to_string()))?; + } + let common = if let Some(request) = input.request { + Value::Object(request.into_iter().collect()) + } else { + let setup = s.doc.render.setups.values().next().ok_or_else(|| bad("render.batch", "no saved shots"))?; + json!({"settings":setup}) + }; + let mut request = common.as_object().cloned().ok_or_else(|| bad("render.batch", "request must be an object"))?; + let settings = if let Some(name) = request.get("setup") { + let name = name.as_str().ok_or_else(|| bad("render.batch", "setup must be a saved name"))?; + if request.contains_key("settings") { + return Err(bad("render.batch", "choose either setup or settings")); + } + s.doc.render.setups.get(name).cloned().ok_or_else(|| bad("render.batch", "unknown saved setup"))? + } else if let Some(settings) = request.get("settings") { + serde_json::from_value(settings.clone()).map_err(|e| bad("render.batch", e.to_string()))? + } else { + s.doc.render.setups.values().next().cloned().ok_or_else(|| bad("render.batch", "no saved shots"))? + }; + request.remove("setup"); + // A batch never replaces an active job; malformed replace values must still refuse. + if request.get("replace").is_some_and(|value| value != &json!(false)) { + return Err(bad("render.batch", "replace must be false or omitted")); + } + request.insert("settings".into(), json!(settings)); + let request = std::sync::Arc::new(Value::Object(request)); + let shots = s + .doc + .render + .setups + .iter() + .map(|(name, shot)| crate::render_jobs::BatchShot { name: name.clone(), camera: shot.camera, request: request.clone() }) + .collect(); + let queued = s.start_render_batch(shots)?; + Ok(json!({"queued":queued})) +} + +fn results_ready(s: &Session) -> std::result::Result<(), String> { + if s.render_jobs.has_results() { Ok(()) } else { Err("no completed render results are retained".into()) } +} + +fn indexed_result(s: &mut Session, params: &Value, command: &str, discard: bool) -> Result { + let input: ResultIndex = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + if input.index > 7 { + return Err(bad(command, "index must be in 0..7")); + } + s.render_jobs.result_index(input.index as usize, discard).map_err(crate::render_jobs::job_error)?; + Ok(json!({"index":input.index})) +} + +fn select_result(s: &mut Session, params: &Value) -> Result { + indexed_result(s, params, "render.result.select", false) +} + +fn discard_result(s: &mut Session, params: &Value) -> Result { + indexed_result(s, params, "render.result.discard", true) +} + #[cfg(test)] #[test] fn render_lights_remaining_planned_commands_refuse_without_mutation() { @@ -149,17 +269,21 @@ fn output_size(_: &mut Session, params: &Value) -> Result { struct ResultView { view: String, } -fn result_view(_: &mut Session, params: &Value) -> Result { +fn result_view(s: &mut Session, params: &Value) -> Result { let input: ResultView = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.view", e.to_string()))?; if !matches!(input.view.as_str(), "model" | "image" | "fit" | "actual") { return Err(bad("render.result.view", "view must be model, image, fit or actual")); } + if input.view == "model" { + s.render_jobs.set_comparison(None); + } Ok(json!({"view":input.view})) } -fn close_result(_: &mut Session, params: &Value) -> Result { +fn close_result(s: &mut Session, params: &Value) -> Result { if !params.as_object().is_some_and(|p| p.is_empty()) { return Err(bad("render.result.close", "expected no parameters")); } + s.render_jobs.set_comparison(None); Ok(json!({"view":"model"})) } @@ -210,3 +334,344 @@ fn output_sections_copy_report_validates_without_design_history_or_job_changes() assert!(std::sync::Arc::ptr_eq(&doc, &s.doc)); assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); } + +#[cfg(test)] +fn complete_result(s: &mut Session, shot: &str) -> solidcraft_render::job::JobId { + let reply = s.execute("render.start", &json!({"setup":shot})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = s.render_job_host().unwrap().clone(); + for _ in 0..1000 { + host.pump(4096).unwrap(); + if s.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "completed" { + return job; + } + } + panic!("bounded result fixture did not complete"); +} + +#[cfg(test)] +#[test] +fn retained_results_cap_order_metadata_and_selection_never_edit_a_design() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":16,"height":8}})).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":32}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.redo.len(), 1, "view commands must preserve an available redo step"); + let document = s.doc.clone(); + let before = (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()); + let jobs: Vec<_> = (0..10).map(|_| complete_result(&mut s, "Hero")).collect(); + let results = s.render_retained_results().unwrap(); + assert_eq!(results.len(), 8); + assert_eq!(results.iter().map(|result| result.frame.job).collect::>(), jobs[2..]); + for result in &results { + assert_eq!(result.shot.as_deref(), Some("Hero")); + assert_eq!((result.frame.width, result.frame.height), (16, 8)); + assert!(result.seconds.is_finite() && result.seconds >= 0.0); + assert_eq!(result.frame.scene_generation, s.revision); + assert!(!result.stale); + } + assert!(s.render_job_handle(jobs[0]).is_err()); + assert!(s.render_job_handle(jobs[1]).is_err()); + assert_eq!(s.render_selected_result(), Some(jobs[9])); + assert_eq!(s.execute("render.result.select", &json!({"index":0})).unwrap(), json!({"index":0})); + assert_eq!(s.render_selected_result(), Some(jobs[2])); + assert_eq!(s.execute("render.result.copy", &json!({})).unwrap()["frame"]["job"], json!(jobs[2])); + assert_eq!(s.execute("render.result.pin", &json!({})).unwrap()["frame"]["job"], json!(jobs[2])); + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + assert_eq!(s.render_selected_result(), Some(jobs[9])); + assert!(s.render_job_handle(jobs[2]).is_err()); + s.execute("render.result.select", &json!({"index":2})).unwrap(); + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + assert_eq!(s.render_selected_result(), Some(jobs[5]), "discarding an earlier row preserves the selected identity"); + while !s.render_retained_results().unwrap().is_empty() { + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + } + assert!(s.render_selected_result().is_none()); + assert!(s.execute("render.result.copy", &json!({})).is_err()); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn retained_result_requests_refuse_hostile_and_missing_indices_atomically() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Front","set":{"width":8,"height":8}})).unwrap(); + let job = complete_result(&mut s, "Front"); + let document = s.doc.clone(); + let before = (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()); + let retained = s.render_job_host().unwrap().admitted_bytes(); + for mode in [crate::schema::ParamCheck::Off, crate::schema::ParamCheck::Strict] { + s.param_check = mode; + for command in ["render.result.select", "render.result.discard"] { + let spec = super::find_command(command).unwrap(); + assert!(spec.contract.is_some() && spec.output.is_some()); + for request in [ + json!(null), + json!([]), + json!({}), + json!({"index":-1}), + json!({"index":0.5}), + json!({"index":1e300}), + json!({"index":u64::MAX}), + json!({"index":"0"}), + json!({"index":null}), + json!({"index":true}), + json!({"index":1}), + json!({"index":8}), + json!({"index":0,"extra":true}), + ] { + assert!(s.execute(command, &request).is_err(), "{command}: {request}"); + assert_eq!(s.render_retained_results().unwrap().len(), 1); + assert_eq!(s.render_selected_result(), Some(job)); + assert_eq!(s.render_job_host().unwrap().admitted_bytes(), retained); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty())); + } + } + } + s.execute("render.settings.set", &json!({"name":"Front","set":{"width":16}})).unwrap(); + assert!(s.render_retained_results().unwrap()[0].stale); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.render_retained_results().unwrap()[0].stale, "undo does not recapture pixels"); + assert_eq!(s.render_retained_results().unwrap()[0].frame.scene_generation, before.2); + let mut other = Session::default(); + assert!(other.render_retained_results().unwrap().is_empty()); + assert!(other.execute("render.result.select", &json!({"index":0})).is_err()); + assert!(other.render_job_handle(job).is_err()); +} + +#[cfg(test)] +#[test] +fn render_results_compare_validates_both_sides_and_clamps_only_finite_dividers_without_mutation() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":8,"height":8}})).unwrap(); + complete_result(&mut s, "Hero"); + complete_result(&mut s, "Hero"); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":16}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + let selected = s.selection.clone(); + for mode in [crate::schema::ParamCheck::Off, crate::schema::ParamCheck::Strict] { + s.param_check = mode; + for request in [json!({"left":"live","right":0}), json!({"left":1,"right":0}), json!({"left":0,"right":"live"}), json!({"off":true})] { + assert_eq!(s.execute("render.compare", &request).unwrap(), request); + } + for request in [ + json!({}), + json!([]), + json!({"off":false}), + json!({"off":true,"left":0}), + json!({"left":"live","right":"live"}), + json!({"left":0,"right":0}), + json!({"left":"unknown","right":0}), + json!({"left":"live","right":2}), + json!({"left":8,"right":0}), + json!({"left":-1,"right":0}), + json!({"left":0.5,"right":0}), + json!({"left":1e300,"right":"live"}), + json!({"left":null,"right":0}), + json!({"left":"0","right":1}), + json!({"left":true,"right":0}), + json!({"left":"live","right":0,"extra":true}), + ] { + assert!(s.execute("render.compare", &request).is_err(), "{request}"); + } + for (position, expected) in [(-1e300, 0.05), (0.0, 0.05), (0.25, 0.25), (1.0, 0.95), (1e300, 0.95)] { + assert_eq!(s.execute("render.compare.divider", &json!({"position":position})).unwrap(), json!({"position":expected})); + } + for request in [json!({}), json!({"position":null}), json!({"position":"NaN"}), json!({"position":true}), json!({"position":0.5,"extra":1})] { + assert!(s.execute("render.compare.divider", &request).is_err()); + } + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + assert_eq!(s.selection, selected); + assert_eq!(s.render_retained_results().unwrap().len(), 2); + } + let mut empty = Session::default(); + assert!(empty.execute("render.compare", &json!({"left":"live","right":0})).is_err()); + assert!(empty.execute("render.compare", &json!({"off":true})).is_err()); + for id in ["render.compare", "render.compare.divider", "render.batch"] { + let command = super::find_command(id).unwrap(); + assert!(command.contract.is_some() && command.output.is_some() && command.planned.is_none()); + assert!(!command.undoable && !command.reads_model); + } +} + +#[cfg(test)] +fn batch_fixture(count: usize) -> Session { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + for index in 0..count { + let camera = solidcraft_render::Camera { yaw: index as f64 * 0.2, roll: index as f64 * 0.01, ..Default::default() }; + s.execute("render.settings.set", &json!({"name":format!("Shot {index:02}"),"set":{"camera":camera,"width":8+index,"height":8}})).unwrap(); + } + s +} + +#[cfg(test)] +#[test] +fn render_results_batch_is_sequential_uses_snapshot_cameras_and_one_setup_without_design_or_history_changes() { + let mut s = batch_fixture(3); + s.execute("render.settings.set", &json!({"name":"Shot 00","set":{"width":64}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + let cameras: Vec<_> = s.doc.render.setups.values().map(|setup| setup.camera).collect(); + s.param_check = crate::schema::ParamCheck::Strict; + assert_eq!( + s.execute("render.batch", &json!({"request":{"settings":{"width":12,"height":10,"background":[7,8,9]}}})).unwrap(), + json!({"queued":3}) + ); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (1, 2)); + assert!(s.execute("render.batch", &json!({})).is_err()); + let host = s.render_job_host().unwrap().clone(); + let mut jobs = Vec::new(); + for (index, camera) in cameras.iter().enumerate() { + let queue = s.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 2 - index)); + let job = queue.job.unwrap(); + let status = s.render_job_handle(job).unwrap().status().unwrap(); + assert_eq!(status.request.camera, *camera); + assert_eq!((status.request.width, status.request.height, status.request.background), (12, 10, [7, 8, 9])); + assert_eq!(queue.shot, Some(format!("Shot {index:02}"))); + jobs.push(job); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + let reply = s.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(reply["progress"]["phase"], "completed"); + } + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().job.is_none()); + let results = s.render_retained_results().unwrap(); + assert_eq!(results.iter().map(|result| result.frame.job).collect::>(), jobs); + assert_eq!(results.iter().map(|result| result.shot.clone().unwrap()).collect::>(), ["Shot 00", "Shot 01", "Shot 02"]); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn render_results_batch_caps_at_32_and_cancel_discards_every_waiting_shot() { + let mut s = batch_fixture(32); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + assert_eq!(s.execute("render.batch", &json!({})).unwrap(), json!({"queued":32})); + let queue = s.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 31)); + let job = queue.job.unwrap(); + assert!(s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).is_err()); + s.execute("render.cancel", &json!({})).unwrap(); + assert_eq!(s.render_queue_state().waiting, 0); + assert!(s.render_queue_state().job.is_none()); + s.render_job_host().unwrap().pump(4096).unwrap(); + assert!(s.render_job_handle(job).unwrap().frame().unwrap().is_none()); + for _ in 0..3 { + assert_eq!(s.execute("render.status", &json!({})).unwrap()["queue"]["waiting"], 0); + } + assert!(s.render_retained_results().unwrap().is_empty()); + let next = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + assert_eq!(next["job"]["serial"], 2, "Cancel must not start any waiting shot"); + s.execute("render.cancel", &json!({"job":next["job"]})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut s.doc).render).setups.insert("Over limit".into(), Default::default()); + assert!(s.execute("render.batch", &json!({})).unwrap_err().to_string().contains("32")); + assert_eq!(s.render_queue_state().waiting, 0); +} + +#[cfg(test)] +#[test] +fn render_results_batch_refuses_missing_shots_busy_hostile_and_failed_requests_without_queuing() { + let mut empty = batch_fixture(0); + assert!(empty.execute("render.batch", &json!({})).is_err()); + let mut s = batch_fixture(2); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + for request in [ + json!([]), + json!({"request":1e300}), + json!({"request":[]}), + json!({"request":{"bogus":true}}), + json!({"request":{"replace":true}}), + json!({"request":{"settings":{"width":0}}}), + json!({"extra":true}), + ] { + assert!(s.execute("render.batch", &request).is_err(), "{request}"); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().job.is_none()); + } + let job = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap()["job"].clone(); + assert!(s.execute("render.batch", &json!({})).is_err()); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (1, 0)); + s.execute("render.cancel", &json!({"job":job})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + s.set_render_job_host(None).unwrap(); + assert!(s.execute("render.batch", &json!({})).is_err()); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().error.is_some()); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn render_results_batch_cameras_and_common_setup_are_captured_before_later_shot_edits() { + let mut s = batch_fixture(2); + let original = s.doc.render.setups.get("Shot 01").unwrap().camera; + s.execute("render.batch", &json!({"request":{"setup":"Shot 00"}})).unwrap(); + let first = s.render_queue_state().job.unwrap(); + let changed = solidcraft_render::Camera { yaw: 2.0, ..Default::default() }; + s.execute("render.settings.set", &json!({"name":"Shot 01","set":{"camera":changed}})).unwrap(); + s.execute("render.settings.set", &json!({"name":"Shot 00","set":{"width":64}})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations); + let host = s.render_job_host().unwrap().clone(); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + let reply = s.execute("render.status", &json!({})).unwrap(); + let next: solidcraft_render::job::JobId = serde_json::from_value(reply["queue"]["job"].clone()).unwrap(); + assert_ne!(next, first); + let request = s.render_job_handle(next).unwrap().status().unwrap().request; + assert_eq!(request.camera, original); + assert_eq!(request.width, 8); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations)); + s.execute("render.cancel", &json!({"job":next})).unwrap(); +} + +#[cfg(test)] +#[test] +fn render_results_compare_keeps_copy_on_the_visible_result_until_a_source_is_evicted() { + let mut s = batch_fixture(1); + let first = complete_result(&mut s, "Shot 00"); + complete_result(&mut s, "Shot 00"); + s.execute("render.compare", &json!({"left":"live","right":0})).unwrap(); + assert_eq!(s.render_comparison(), Some([None, Some(first)])); + assert_eq!(s.render_selected_result(), Some(first)); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations); + let mut newest = first; + for index in 0..7 { + newest = complete_result(&mut s, "Shot 00"); + if index < 6 { + assert_eq!(s.execute("render.result.copy", &json!({})).unwrap()["frame"]["job"], json!(first)); + assert_eq!(s.render_comparison(), Some([None, Some(first)])); + } + } + assert!(s.render_comparison().is_none()); + assert_eq!(s.render_selected_result(), Some(newest)); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations)); +} diff --git a/crates/engine/src/cmd/script.rs b/crates/engine/src/cmd/script.rs index d2bd90779..24a4a13dc 100644 --- a/crates/engine/src/cmd/script.rs +++ b/crates/engine/src/cmd/script.rs @@ -36,6 +36,19 @@ fn add(s: &mut Session, p: &Value) -> Result { .and_then(Value::as_object) .ok_or_else(|| bad(cmd, "`feature` must be a feature object, as a design file or timeline.inspect has it"))?; let mut raw = raw.clone(); + if let Some(Value::Object(def)) = raw.remove("definition") { + for (k, v) in def { + raw.entry(k).or_insert(v); + } + } + for meta in ["omitted", "inputs", "error", "warning", "boolean_diagnostics", "rolled_back", "type_name"] { + raw.remove(meta); + } + if let Some(kind_str) = raw.get("type").and_then(Value::as_str) + && let Some(canonical) = FeatureKind::type_name_to_kind_key(kind_str) + { + raw.insert("type".into(), json!(canonical)); + } resolve_legacy_names(&mut raw, &s.doc); let feature = recorded_feature(cmd, &raw)?; let params = step_params(cmd, p.get("params"))?; diff --git a/crates/engine/src/cmd/script_tests.rs b/crates/engine/src/cmd/script_tests.rs index d5966651b..2952e10cc 100644 --- a/crates/engine/src/cmd/script_tests.rs +++ b/crates/engine/src/cmd/script_tests.rs @@ -244,6 +244,34 @@ fn a_recorded_feature_that_does_not_fit_is_refused_and_changes_nothing() { assert!(s.doc.feature(r["feature"].as_u64().unwrap()).is_some_and(|f| !f.param_names.is_empty()), "its inputs get parameter names"); } +/// #10748: `timeline.inspect` reports a feature's design variant name in `type` and display name +/// in `type_name`; `timeline.add` accepts `timeline.inspect` results and inspect type names. +#[test] +fn timeline_add_accepts_inspect_result_and_type_names() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 5, "name": "Block"})); + let mut inspected = run(&mut s, "timeline.inspect", json!({"feature": "Block"})); + assert_eq!(inspected["type"], "box", "inspect type is the design file variant name"); + assert_eq!(inspected["type_name"], "BoxFeature", "inspect type_name is the display type"); + + // 1. timeline.add accepts the full inspected object directly in a new session + let mut s2 = Session::default(); + let added = run(&mut s2, "timeline.add", json!({"feature": inspected.clone()})); + assert!(added["error"].is_null(), "{added}"); + assert_eq!(s2.doc.features.len(), 1); + + // 2. timeline.add with id 0 allocates a new id in the current session + inspected["id"] = json!(0); + let added2 = run(&mut s, "timeline.add", json!({"feature": inspected})); + assert!(added2["error"].is_null(), "{added2}"); + assert_eq!(s.doc.features.len(), 2); + + // 3. timeline.add accepts the inspect type name (e.g. BoxFeature, HoleFeature) + let added_by_type_name = + run(&mut s, "timeline.add", json!({"feature": {"type": "BoxFeature", "length": "5", "width": "5", "height": "5", "corner": [50, 0, 0]}})); + assert!(added_by_type_name["error"].is_null(), "{added_by_type_name}"); +} + #[test] fn the_script_is_written_to_a_file_that_replays() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/silhouette.rs b/crates/engine/src/cmd/silhouette.rs index a989677de..45c8a3c66 100644 --- a/crates/engine/src/cmd/silhouette.rs +++ b/crates/engine/src/cmd/silhouette.rs @@ -20,19 +20,50 @@ fn run(s: &mut Session, p: &Value) -> Result { let camera = camera(p)?; let rows = rows(p)?; let wanted = body_names(p)?; + let out = outline(s, &camera, wanted.as_deref(), rows)?; + let mask: Vec> = out.mask.iter().map(|row| spans(row)).collect(); + Ok(json!({ + "width": out.width, + "height": out.height, + "mm_per_px": round4(out.mm_per_px), + "box_mm": [[round4(out.lo[0]), round4(out.lo[1])], [round4(out.hi[0]), round4(out.hi[1])]], + "right": [clean(out.right.x), clean(out.right.y), clean(out.right.z)], + "up": [clean(out.up.x), clean(out.up.y), clean(out.up.z)], + "projection": if out.perspective { "perspective" } else { "parallel" }, + "bodies": out.bodies, + "triangles": out.triangles, + "mask": mask, + })) +} + +/// A projected, tightly framed silhouette: the pixel grid, its scale and placement, and the +/// filled mask as one row of booleans per pixel row. `inspect.silhouette` renders this as +/// run-length rows; `inspect.compare_picture` uses the filled rows directly. +pub(crate) struct Silhouette { + pub width: usize, + pub height: usize, + pub mm_per_px: f64, + /// The view-plane box the mask frames, in mm (u along `right`, v along `up`). + pub lo: [f64; 2], + pub hi: [f64; 2], + pub right: Vec3, + pub up: Vec3, + pub perspective: bool, + pub bodies: usize, + pub triangles: usize, + pub mask: Vec>, +} + +pub(crate) fn outline(s: &Session, camera: &Camera, wanted: Option<&[String]>, rows: usize) -> Result { let state = s.world_state()?; - if let Some(names) = &wanted { + if let Some(names) = wanted { for name in names { if !state.bodies.iter().any(|b| b.name == *name) { return Err(bad(CMD, format!("unknown body name `{name}`"))); } } } - let bodies: Vec<_> = state - .bodies - .iter() - .filter(|b| wanted.as_ref().map_or_else(|| s.body_visible(&b.name), |names| names.iter().any(|name| name == &b.name))) - .collect(); + let bodies: Vec<_> = state.bodies.iter().filter(|b| wanted.map_or_else(|| s.body_visible(&b.name), |names| names.contains(&b.name))).collect(); if bodies.is_empty() { return Err(bad(CMD, "nothing visible to outline")); } @@ -133,22 +164,22 @@ fn run(s: &mut Session, p: &Value) -> Result { } } - let mask: Vec> = covered.chunks_exact(width).map(spans).collect(); - Ok(json!({ - "width": width, - "height": height, - "mm_per_px": round4(mm_per_px), - "box_mm": [[round4(lo[0]), round4(lo[1])], [round4(hi[0]), round4(hi[1])]], - "right": [clean(right.x), clean(right.y), clean(right.z)], - "up": [clean(up.x), clean(up.y), clean(up.z)], - "projection": if perspective { "perspective" } else { "parallel" }, - "bodies": bodies.len(), - "triangles": triangle_count, - "mask": mask, - })) + Ok(Silhouette { + width, + height, + mm_per_px, + lo, + hi, + right, + up, + perspective, + bodies: bodies.len(), + triangles: triangle_count, + mask: covered.chunks_exact(width).map(|row| row.to_vec()).collect(), + }) } -fn camera(p: &Value) -> Result { +pub(crate) fn camera(p: &Value) -> Result { if p.get("view").is_some() && p.get("camera").is_some() { return Err(bad(CMD, "give `view` or `camera`, not both")); } @@ -171,7 +202,7 @@ fn camera(p: &Value) -> Result { Ok(camera) } -fn body_names(p: &Value) -> Result>> { +pub(crate) fn body_names(p: &Value) -> Result>> { match p.get("bodies") { None => Ok(None), Some(Value::String(name)) => Ok(Some(vec![name.clone()])), @@ -184,7 +215,7 @@ fn body_names(p: &Value) -> Result>> { } } -fn rows(p: &Value) -> Result { +pub(crate) fn rows(p: &Value) -> Result { match p.get("rows") { None => Ok(240), Some(v) => { @@ -209,7 +240,7 @@ fn edge(a: [f64; 2], b: [f64; 2], p: [f64; 2]) -> f64 { (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) } -fn spans(row: &[bool]) -> Vec<[usize; 2]> { +pub(crate) fn spans(row: &[bool]) -> Vec<[usize; 2]> { let mut out = Vec::new(); let mut start = None; for (x, &on) in row.iter().enumerate() { diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 59e6c5992..df826210a 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -472,6 +472,9 @@ const CONNECT_TOL: f64 = 1e-6; /// New points (index `first` on) that land on an existing point, the origin included, get a /// coincident constraint to it, as when a click snaps there; `connect: false` leaves them free. +/// A point placed by parameter expressions is never tied: it follows its expressions, and a +/// Coincident to where the expressions happened to come to at draw time conflicts with the +/// next parameter change (#10703). fn connect_points(sk: &mut Sketch, first: usize, p: &Value) -> Result> { if !bool_(p, "connect").unwrap_or(true) { return Ok(Vec::new()); @@ -481,6 +484,9 @@ fn connect_points(sk: &mut Sketch, first: usize, p: &Value) -> Result = TypedContract::new(); +const SPLINE_REMOVE_POINT_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line) @@ -88,6 +89,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("spline") .enabled(in_sketch) .params("curve: fit point spline id, at: [x,y]: a fit point is inserted where the curve passes nearest to it, between its neighbours (the curve still runs through it and all its old points; constraints on them stay); end?: start|end: `at` becomes the spline's new first or last point instead, and the curve runs on to it (refused when that end is joined to other geometry). Control point splines take no new points yet. Returns point: the new point's id"), + CommandSpec::new("sketch.spline.remove_point", "Remove Spline Point", crate::checked!("sketch.spline.remove_point", spline_remove_point)) + .icon("spline") + .enabled(in_sketch) + .contract(&SPLINE_REMOVE_POINT_CONTRACT) + .output(output_schema_for::) + .params("curve: spline id, point: one of its points (a point id, or the curve's start or end such as s1.end): the spline runs through (or over) its other points only, and the point goes with the constraints on it unless another curve uses it. Fit point, control point and closed splines. Refused for a closed spline's closing point, for an end joined to other geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed spline), and for a projected, offset or patterned spline. Returns curve, point: the point's id, deleted: whether the point went too"), CommandSpec::new("sketch.spline.reverse", "Reverse Spline Direction", crate::checked!("sketch.spline.reverse", spline_reverse)) .icon("spline") .enabled(in_sketch) @@ -705,6 +712,22 @@ fn spline_insert_point(s: &mut Session, p: &Value) -> Result { Ok(json!({"point": point, "curve": p.get("curve"), "sketch": info})) } +/// One point taken out of a spline (#10783). +fn spline_remove_point(s: &mut Session, p: &Value) -> Result { + let cmd = "sketch.spline.remove_point"; + let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string(); + let point = str_(p, "point").ok_or_else(|| bad(cmd, "`point` must be one of the spline's points"))?.to_string(); + let ((point, deleted), info) = edit(s, p, cmd, false, |sk, _| { + let c = sk.curve_index(&id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; + let at = sk.resolve_point(&point).ok_or_else(|| bad(cmd, format!("unknown sketch point `{point}`")))?; + let name = sk.points.get(at).map_or(point.clone(), |q| q.id.clone()); + let deleted = sk.remove_spline_point(c, at).map_err(|e| bad(cmd, e.to_string()))?; + Ok((name, deleted)) + })?; + let reply = SplineRemovePointResult { curve: id, point, deleted, sketch: info, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + fn spline_reverse(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.spline.reverse"; let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string(); diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rs index 81de8afdb..4f724e4cb 100644 --- a/crates/engine/src/cmd/sketch_import.rs +++ b/crates/engine/src/cmd/sketch_import.rs @@ -245,6 +245,11 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { let v = (q - pivot) * k; Vec2::new(v.x * cos - v.y * sin, v.x * sin + v.y * cos) + off }; + // A dense SVG/DXF (a floorplan) can yield far more entities than a sketch takes; refuse + // before adding so the message names the cap (#10874). Scale alone does not shrink the count. + if geom.len() > solidcraft_sketch::MAX_POINTS { + return Err(solidcraft_sketch::SketchError::TooLarge.into()); + } let ((curves, texts), info) = edit(s, p, cmd, false, |sk, _| { let (cs, texts) = add_geometry(sk, &geom, &f, k, tol)?; Ok((ids_of(sk, &cs), texts)) @@ -371,6 +376,22 @@ mod tests { } } + /// #10874: a drawing with more entities than a sketch can hold is refused with the point + /// cap and that scale alone does not help (a floorplan SVG often hits this). + #[test] + fn a_drawing_with_too_many_entities_names_the_sketch_cap() { + let n = solidcraft_sketch::MAX_POINTS + 1; + let mut dxf = String::from("0\nSECTION\n2\nENTITIES\n"); + for i in 0..n { + dxf.push_str(&format!("0\nLINE\n10\n{i}\n20\n0\n11\n{}\n21\n1\n", i + 1)); + } + dxf.push_str("0\nENDSEC\n0\nEOF\n"); + let mut s = Session::default(); + let e = s.execute("sketch.insert_dxf", &json!({"text": dxf})).unwrap_err().to_string(); + assert!(e.contains("20000") && e.contains("scale"), "{e}"); + assert!(s.active_sketch.is_none(), "a refused insert leaves no empty sketch behind"); + } + /// #9641: an SVG with nothing SolidCraft can draw (here only an embedded picture) is refused /// with a message naming the file and saying why, not "invalid parameters … no geometry"; a /// UTF-16 SVG file inserts. diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 83d29ff71..27c18df96 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -48,7 +48,8 @@ pub static COMMANDS: &[CommandSpec] = &[ .params(concat!( "curves: [ids], distance: number in mm or length expression (creates an editable dimension; positive = left of the chain, or toward `side`), side?: [x,y], chain?: bool (default true: the connected chain, including ends that only coincide). A corner is trimmed back to the crossing when the offset runs past it, and extended until the offset curves intersect when the corner falls short; ", "direction?: one_side|symmetric (default one_side) or symmetric?: bool (the same distance each way; no `side`, whose job it takes over), ", - "distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions", + "distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions; ", + "instances?: whole number or unitless expression, 1…100 (default 1): each instance after the first offsets the instance before it by the same distance again, so instance n stands n distances from the curves picked. Every instance of a side is driven by that side's own dimension, and each entry of `sides` names its `instance`; an instance the shape cannot take refuses the whole command", created_doc!() )), CommandSpec::new("sketch.offset.break", "Break Offset Association", break_offset).icon("sketch_break") @@ -112,6 +113,10 @@ pub static COMMANDS: &[CommandSpec] = &[ const TOL: f64 = 1e-7; const MAX_COPIES: usize = 500; +/// The most offsets `sketch.offset` stacks one behind the other in a single run. Each instance +/// is its own association, so this stays below the sketch's own caps on analytic offset groups +/// and free-form associations (both 128). +const MAX_INSTANCES: usize = 100; fn curve_arg(sk: &Sketch, p: &Value, cmd: &str) -> Result { let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a curve id"))?; @@ -2386,6 +2391,24 @@ fn offset_length(s: &Session, p: &Value, key: &str, positive: bool) -> Result<(f Ok((value, expression)) } +/// `instances`: how many offsets stand one behind the other, each at the same distance from the +/// one before it. A number or a unitless expression; one (the offset by itself) by default. +fn offset_instances(s: &Session, p: &Value, cmd: &str) -> Result { + let message = format!("`instances` must be a whole number from 1 to {MAX_INSTANCES}, or an expression for one"); + let count = match p.get("instances") { + None | Some(Value::Null) => return Ok(1), + Some(Value::Number(_)) => num(p, "instances").ok_or_else(|| bad(cmd, message.clone()))?, + Some(_) => { + let expression = expr(p, "instances").ok_or_else(|| bad(cmd, message.clone()))?.into_string(); + s.doc.eval(&expression, solidcraft_doc::expr::Kind::Unitless).map_err(|error| bad(cmd, format!("`instances`: {error}")))? + } + }; + if !count.is_finite() || count.fract() != 0.0 || !(1.0..=MAX_INSTANCES as f64).contains(&count) { + return Err(bad(cmd, message)); + } + Ok(count as usize) +} + #[derive(Clone, Copy)] struct OffsetOptions { side: Option, @@ -2520,6 +2543,125 @@ fn offset_group(sk: &mut Sketch, ids: &[String], eligible: &std::collections::Ha Ok(sides) } +/// One rung of an offset ladder: the offsets of `ids`, with the infinite flag carried over from +/// infinite sources (#1359) and a driving dimension on each side that is linked to its source. +/// `names` is the parameter each side is driven by, in side order, falling back to the first for +/// a side the rung before it had none for. The sources the rung consumed come back with it. +fn offset_rung( + sk: &mut Sketch, + cmd: &str, + ids: &[String], + eligible: &std::collections::HashSet, + options: OffsetOptions, + names: &[String], +) -> Result<(Vec, Vec)> { + let mut group = offset_group(sk, ids, eligible, options)?; + let output = group.first().and_then(|side| side.curves.first()).ok_or_else(|| bad(cmd, "offset produced no curves"))?; + let sources = sk + .offsets + .iter() + .find(|o| o.owns_output(output)) + .map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::>()) + .or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()])) + .or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone())) + .ok_or_else(|| bad(cmd, "offset association is missing"))?; + // An offset of infinite lines is infinite lines too (#1359). + let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite)); + if infinite { + for id in group.iter().flat_map(|side| side.curves.iter()) { + if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c)) + && matches!(cu.kind, CurveKind::Line { .. }) + { + cu.infinite = true; + cu.construction = true; + } + } + } + for (index, side) in group.iter_mut().enumerate() { + // A trimmed offset is not linked to its source: it has no distance to drive. + if side.unlinked_sources.is_some() { + continue; + } + let name = names.get(index).or_else(|| names.first()).ok_or_else(|| bad(cmd, "offset has no driving dimension"))?; + let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?; + side.constraints.push(sk.add_constraint( + ConstraintKind::OffsetDistance { output: output.clone(), value: side.distance.abs(), reverse: side.distance < 0.0 }, + Some(name.clone()), + )?); + side.param = Some(name.clone()); + } + Ok((group, sources)) +} + +/// Where the next instance of an offset belongs: one more step the way the rung already went. +/// The rung's own normal-distance annotation knows that, since its ends are the middle of its +/// first source curve and the point one signed distance away on the rung itself; the same step +/// again lands one distance past the rung. The side is taken from the geometry this way rather +/// than from the sign again, because an output's stored ends need not run the way the chain +/// through them is walked, and a reversed walk reads the same sign as the other side. A trimmed +/// offset has no annotation and is ordinary geometry: `None` leaves the sign to speak for it. +fn offset_beyond(sk: &Sketch, rung: &[String]) -> Option { + // A circle offsets concentrically: there is no chain to walk and so no walk direction to + // mistake, and its own side is read as "outside the current radius". A step past a ring + // smaller than the distance lands beyond the centre, which reads as outside and would turn + // an inward ladder round into a growing one instead of letting it run out of room. Its + // signed distance already says which way, so leave the side to it. + let index = sk.curve_index(rung.first()?)?; + if matches!(sk.curves.get(index)?.kind, CurveKind::Circle { .. }) { + return None; + } + let (from, to) = sk.offset_dimension_points(rung.first()?)?; + (from.dist(to) > TOL).then(|| to + (to - from)) +} + +/// What one side of a rung leaves for the next: the curves to offset again, its own signed +/// distance, and the dimension its whole ladder is driven by. +fn offset_leaves(side: &Side, fallback: &str) -> (Vec, f64, String) { + (side.curves.clone(), side.distance, side.param.clone().unwrap_or_else(|| fallback.to_string())) +} + +/// Every offset of one connected source group: the first rung at the distances asked for, then +/// one more rung per extra instance, each offsetting the rung before it the same way and the +/// same distance again, so instance n stands n distances from the curves picked. Each side comes +/// back paired with the instance it belongs to, and the first rung's sources come with them, so +/// the caller can take those out of the selection it is still working through. +fn offset_ladder( + sk: &mut Sketch, + cmd: &str, + ids: &[String], + eligible: &std::collections::HashSet, + options: OffsetOptions, + instances: usize, + names: &[String], +) -> Result<(Vec<(usize, Side)>, Vec)> { + let primary = names.first().cloned().ok_or_else(|| bad(cmd, "offset has no driving dimension"))?; + let (first, sources) = offset_rung(sk, cmd, ids, eligible, options, names)?; + let mut rung: Vec<(Vec, f64, String)> = first.iter().map(|side| offset_leaves(side, &primary)).collect(); + let mut sides: Vec<(usize, Side)> = first.into_iter().map(|side| (1, side)).collect(); + for instance in 2..=instances { + let mut next = Vec::new(); + for (curves, distance, name) in &rung { + // One side at a time from here: the side this rung follows is the whole of its + // direction, so `side`, `symmetric` and `distance2` had their say in the first rung. + let beyond = offset_beyond(sk, curves); + let step = OffsetOptions { side: beyond, chain: false, distance: *distance, symmetric: false, distance2: None }; + // Which instance ran out of room is the whole of the answer, so the refusal names it + // in front of the reason, rather than wrapping one "invalid parameters" in another. + let (made, _) = offset_rung(sk, cmd, curves, eligible, step, std::slice::from_ref(name)).map_err(|error| { + let reason = match &error { + crate::EngineError::BadParams { msg, .. } => msg.clone(), + other => other.to_string(), + }; + bad(cmd, format!("instance {instance} of {instances}: {reason}")) + })?; + next.extend(made.iter().map(|side| offset_leaves(side, name))); + sides.extend(made.into_iter().map(|side| (instance, side))); + } + rung = next; + } + Ok((sides, sources)) +} + fn offset(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.offset"; let ids = string_list(cmd, p, "curves")?; @@ -2550,6 +2692,7 @@ fn offset(s: &mut Session, p: &Value) -> Result { if symmetric && side.is_some() { return Err(bad(cmd, "`symmetric` offsets both sides, so `side` has no side left to pick: drop one of them")); } + let instances = offset_instances(s, p, cmd)?; let ((sides, param, param2), info) = edit(s, p, cmd, true, |sk, doc| { sk.refresh_offsets()?; let rep = solve_current(sk, doc)?; @@ -2564,41 +2707,8 @@ fn offset(s: &mut Session, p: &Value) -> Result { let mut pending = ids.clone(); let mut sides = Vec::new(); while !pending.is_empty() { - let mut group = offset_group(sk, &pending, &eligible, OffsetOptions { side, chain: use_chain, distance: d0, symmetric, distance2 })?; - let output = group.first().and_then(|side| side.curves.first()).ok_or_else(|| bad(cmd, "offset produced no curves"))?; - let sources = sk - .offsets - .iter() - .find(|o| o.owns_output(output)) - .map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::>()) - .or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()])) - .or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone())) - .ok_or_else(|| bad(cmd, "offset association is missing"))?; - // An offset of infinite lines is infinite lines too (#1359). - let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite)); - if infinite { - for id in group.iter().flat_map(|side| side.curves.iter()) { - if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c)) - && matches!(cu.kind, CurveKind::Line { .. }) - { - cu.infinite = true; - cu.construction = true; - } - } - } - for (index, side) in group.iter_mut().enumerate() { - // A trimmed offset is not linked to its source: it has no distance to drive. - if side.unlinked_sources.is_some() { - continue; - } - let name = if index == 1 { param2.as_ref().unwrap_or(¶m) } else { ¶m }; - let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?; - side.constraints.push(sk.add_constraint( - ConstraintKind::OffsetDistance { output: output.clone(), value: side.distance.abs(), reverse: side.distance < 0.0 }, - Some(name.clone()), - )?); - side.param = Some(name.clone()); - } + let options = OffsetOptions { side, chain: use_chain, distance: d0, symmetric, distance2 }; + let (group, sources) = offset_ladder(sk, cmd, &pending, &eligible, options, instances, &made)?; let before = pending.len(); pending.retain(|id| !sources.contains(id)); if pending.len() == before { @@ -2607,31 +2717,31 @@ fn offset(s: &mut Session, p: &Value) -> Result { sides.extend(group); } // Parameters made for distances that only trimmed (unlinked) offsets used drive nothing. - let used = |name: &String| sides.iter().any(|side: &Side| side.param.as_ref() == Some(name)); + let used = |name: &String| sides.iter().any(|(_, side): &(usize, Side)| side.param.as_ref() == Some(name)); let param = used(¶m).then_some(param); let param2 = param2.filter(|name| used(name)); doc.params.retain(|p| !made.contains(&p.name) || param.as_ref() == Some(&p.name) || param2.as_ref() == Some(&p.name)); Ok((sides, param, param2)) })?; - let curves: Vec<&String> = sides.iter().flat_map(|side| side.curves.iter()).collect(); - let constraints: Vec<&String> = sides.iter().flat_map(|side| side.constraints.iter()).collect(); + let curves: Vec<&String> = sides.iter().flat_map(|(_, side)| side.curves.iter()).collect(); + let constraints: Vec<&String> = sides.iter().flat_map(|(_, side)| side.constraints.iter()).collect(); let each: Vec = sides .iter() - .map(|side| { - let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param}); + .map(|(instance, side)| { + let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param, "instance": instance}); if let Some(association) = &side.association { entry["association"] = json!(association); } entry }) .collect(); - let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param}); + let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param,"instances":instances}); if let Some(param2) = param2 { response["param2"] = json!(param2); } - // One side keeps the single `association` it always returned. Two sides have one each, in - // `sides`, so there is no single association left to name. - if let [only] = sides.as_slice() + // One side keeps the single `association` it always returned. Two sides, or an instance + // behind another, have one each in `sides`, so there is no single association left to name. + if let [(_, only)] = sides.as_slice() && let Some(association) = &only.association { response["association"] = json!(association); diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 690abccef..55c898cf9 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1492,6 +1492,64 @@ fn a_point_added_to_a_spline_keeps_its_constraints_and_undoes() { assert_eq!(sketch(&s), unchanged, "refusals change nothing"); } +/// Remove Spline Point (#10783): one fit point goes, with the dimension on it. The spline runs +/// through its other points, which stay where they were, and the line joined to its end stays. +/// Undo puts the point back. The end the line joins, a line and an unknown point are refused; a +/// control point spline gives up a point too. +#[test] +fn a_point_removed_from_a_spline_goes_with_its_dimension_and_undoes() { + let mut s = new_sketch(); + let sid = + ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [20, 0], [30, 6]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [format!("{sid}.end"), [40, 6]], "connect": false})); + let sk = sketch(&s); + let si = sk.curve_index(&sid).unwrap(); + let names: Vec = sk.curves[si].kind.point_ids().iter().map(|i| sk.points[*i].id.clone()).collect(); + run(&mut s, "sketch.dimension", json!({"entities": [names[1], names[2]], "value": 12.8})); + let before = sketch(&s); + let at = |sk: &solidcraft_sketch::Sketch, id: &str| sk.point(sk.point_index(id).unwrap()).unwrap(); + + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": sid, "point": names[1]})); + assert_eq!((r["curve"].as_str(), r["point"].as_str(), r["deleted"].as_bool()), (Some(sid.as_str()), Some(names[1].as_str()), Some(true)), "{r}"); + let after = sketch(&s); + assert!(after.point_index(&names[1]).is_none(), "the point went"); + let left: Vec = after.curves[si].kind.point_ids().iter().map(|i| after.points[*i].id.clone()).collect(); + assert_eq!(left, [names[0].clone(), names[2].clone(), names[3].clone()]); + let segs = after.exact_segs(si).unwrap(); + for id in &left { + let q = at(&after, id); + assert!(q.dist(at(&before, id)) < 1e-9, "{id} stays where it was"); + let off = segs.iter().map(|seg| seg.point_at(seg.closest_param(q)).dist(q)).fold(f64::INFINITY, f64::min); + assert!(off < 1e-9, "the curve runs through {id}"); + } + assert!(after.constraints.iter().all(|c| c.kind.value().is_none()), "the dimension on the point went"); + let joined = after.curves.iter().any(|c| matches!(c.kind, CurveKind::Line { a, .. } if after.points[a].id == names[3])); + assert!(joined, "the line still starts at the spline's end"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s), before, "undo puts the point back"); + + let line = before.curves.iter().find(|c| matches!(c.kind, CurveKind::Line { .. })).unwrap().id.clone(); + for (p, why) in [ + (json!({"curve": sid, "point": format!("{sid}.end")}), "joined"), + (json!({"curve": line, "point": names[0]}), "spline"), + (json!({"curve": sid, "point": "nope"}), "unknown sketch point"), + (json!({"curve": sid}), "`point`"), + ] { + let e = s.execute("sketch.spline.remove_point", &p).unwrap_err().to_string(); + assert!(e.contains(why), "{p}: {e}"); + } + assert_eq!(sketch(&s), before, "refusals change nothing"); + + let cv = + ids(&run(&mut s, "sketch.spline.control_point", json!({"points": [[0, 20], [10, 30], [20, 20]], "connect": false}))["curves"])[0].clone(); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": cv, "point": format!("{cv}.start")})); + assert_eq!(r["deleted"], json!(true), "{r}"); + let sk = sketch(&s); + let ci = sk.curve_index(&cv).unwrap(); + let left: Vec = sk.curves[ci].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect(); + assert_eq!(left, [Vec2::new(10.0, 30.0), Vec2::new(20.0, 20.0)]); +} + /// Reverse Spline Direction (#8224): a fit, a control point and a closed spline each run the /// other way along the same path, their ends swapped. Their points, the constraints on them and /// a line joined to an end stay, and undo restores the spline. A line and the source and output @@ -1880,7 +1938,7 @@ fn fillet_a_line_and_an_arc() { fn fillet_a_line_and_an_arc_drawn_to_meet_at_a_point() { // #1208: the arc starts at the line's end by coordinates, so the corner is two points held // together by a Coincident constraint. By point and by naming the two curves. - for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "a1"})] { + for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "a1"}), json!({"a": "a1", "b": "l1"})] { let mut s = new_sketch(); run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l1"]})); run(&mut s, "sketch.arc.center_point", json!({"center": [50, 0], "start": [60, 0], "end": [40, 0], "id": "a1"})); @@ -1946,6 +2004,38 @@ fn fillet_a_coincident_corner_that_a_dimension_measures_to() { } } +#[test] +fn fillet_coincident_line_and_arc_selection_order() { + for held in ["l1.end", "a1.end"] { + for (a, b) in [("l1", "a1"), ("a1", "l1")] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l1"]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [50, 0], "start": [60, 0], "end": [40, 0], "id": "a1"})); + // Keep the fixed sharp corner in place, whichever endpoint is fixed or picked + // first when rounding the same corner. + run(&mut s, "sketch.constraint.fix", json!({"entity": held})); + let before = serde_json::to_value(sketch(&s)).unwrap(); + let f = run(&mut s, "sketch.fillet", json!({"a": a, "b": b, "radius": 3})); + let sk = sketch(&s); + let ai = sk.curve_index(&ids(&f["curves"])[0]).unwrap(); + let want = Vec2::new(50.0 - 160f64.sqrt(), 3.0); + assert!((sk.radius(ai).unwrap() - 3.0).abs() < 1e-7, "{held}: {a}, {b}"); + assert!(sk.center(ai).unwrap().dist(want) < 1e-6, "{held}: {a}, {b}"); + let fixed = sk + .constraints + .iter() + .find_map(|c| match c.kind { + ConstraintKind::Fix { p } => Some(p), + _ => None, + }) + .unwrap(); + assert!(sk.point(fixed).unwrap().dist(Vec2::new(40.0, 0.0)) < 1e-6); + assert_eq!(run(&mut s, "sketch.inspect", json!({}))["status"], "solved"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before); + } + } +} #[test] fn chamfer_two_lines_drawn_to_meet_at_a_point() { let mut s = new_sketch(); @@ -2429,6 +2519,143 @@ fn offset_two_sides_of_one_curve_follows_the_sign_of_the_distance() { assert!(close(one.1.x - one.0.x, 40.0) && close(two.1.x - two.0.x, 40.0), "{one:?} {two:?}"); } +/// Each instance of an outward offset of a 40 by 30 rectangle, as a box one more step out. +fn offset_rings(sk: &solidcraft_sketch::Sketch, o: &Value, out: &[f64]) { + for (index, out) in out.iter().copied().enumerate() { + let curves = side_curves(o, index); + assert_eq!(curves.len(), 4, "{o}"); + assert!(box_is(sk, &curves, [-out, -out], [40.0 + out, 30.0 + out]), "instance {}: {:?}", index + 1, bounds(sk, &curves)); + } +} + +#[test] +fn offset_instances_stack_one_behind_another_at_the_same_distance() { + let mut s = new_sketch(); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let l = ids(&r["curves"]); + // Three instances outward by 5 from a 40 by 30 rectangle: rings 5, 10 and 15 out, each the + // offset of the one before it. + let o = run(&mut s, "sketch.offset", json!({"curves": [l[0]], "distance": 5, "side": [20, -10], "instances": 3})); + assert_eq!(o["instances"], 3, "{o}"); + let sides = o["sides"].as_array().unwrap().clone(); + assert_eq!(sides.len(), 3, "{o}"); + assert_eq!(sides.iter().map(|side| side["instance"].as_u64()).collect::>(), vec![Some(1), Some(2), Some(3)], "{o}"); + assert_eq!(ids(&o["curves"]).len(), 12, "{o}"); + offset_rings(&sketch(&s), &o, &[5.0, 10.0, 15.0]); + // One dimension drives the whole ladder, so every ring moves together when it changes. + let param = o["param"].as_str().unwrap().to_string(); + assert!(sides.iter().all(|side| side["param"].as_str() == Some(param.as_str())), "{o}"); + assert_eq!(sketch(&s).constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::OffsetDistance { .. })).count(), 3); + run(&mut s, "parameters.change", json!({"name": param, "expression": "8 mm"})); + offset_rings(&sketch(&s), &o, &[8.0, 16.0, 24.0]); +} + +#[test] +fn offset_instances_go_the_way_the_first_one_went() { + let mut s = new_sketch(); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let l = ids(&r["curves"]); + // Inward by 5: rings at (5,5)-(35,25) and (10,10)-(30,20). A later instance reads its side + // from the ring it follows, so it never doubles back over the one before it. + let o = run(&mut s, "sketch.offset", json!({"curves": [l[0]], "distance": 5, "side": [20, 15], "instances": 2})); + let sk = sketch(&s); + assert!(box_is(&sk, &side_curves(&o, 0), [5.0, 5.0], [35.0, 25.0]), "{:?}", bounds(&sk, &side_curves(&o, 0))); + assert!(box_is(&sk, &side_curves(&o, 1), [10.0, 10.0], [30.0, 20.0]), "{:?}", bounds(&sk, &side_curves(&o, 1))); +} + +#[test] +fn offset_instances_stop_where_the_shape_runs_out() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let before = s.doc.to_json(); + // Inward by 5 twice reaches a 20 by 10 ring; a third would have no height left, so the + // whole command is refused and names the instance that could not be made. + let error = s.execute("sketch.offset", &json!({"curves": ["l1"], "distance": 5, "side": [20, 15], "instances": 3})).unwrap_err().to_string(); + assert!(error.contains("instance 3 of 3"), "{error}"); + assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone"); + // Two of them still work on the same shape. + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 5, "side": [20, 15], "instances": 2})); + assert_eq!(o["sides"].as_array().map(Vec::len), Some(2), "{o}"); +} + +#[test] +fn offset_instances_count_must_be_a_whole_number_within_the_cap() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + for count in [json!(0), json!(-1), json!(1.5), json!(101), json!("two"), json!(true)] { + let params = json!({"curves": ["l1"], "distance": 1, "side": [20, -10], "instances": count.clone()}); + assert!(s.execute("sketch.offset", ¶ms).is_err(), "instances {count} must be refused"); + } + // No count, and a count of one, are the offset by itself. + for count in [json!(null), json!(1), json!("1")] { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 1, "side": [20, -10], "instances": count})); + assert_eq!(o["instances"], 1, "{o}"); + assert_eq!(o["sides"].as_array().map(Vec::len), Some(1), "{o}"); + assert_eq!(ids(&o["curves"]).len(), 4, "{o}"); + } +} + +#[test] +fn offset_instances_into_a_circle_run_out_at_the_centre() { + let mut s = new_sketch(); + let c = ids(&run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}))["curves"])[0].clone(); + let radii = |s: &Session, o: &Value| -> Vec { + let sk = sketch(s); + o["sides"] + .as_array() + .unwrap() + .iter() + .map(|side| match sk.curves.get(sk.curve_index(ids(&side["curves"])[0].as_str()).unwrap()).unwrap().kind { + CurveKind::Circle { r, .. } => r, + ref other => panic!("{other:?}"), + }) + .collect() + }; + // Inward by 3 from a 10 mm circle: rings at 7, 4 and 1 mm. + let o = run(&mut s, "sketch.offset", json!({"curves": [c.clone()], "distance": 3, "side": [0, 0], "instances": 3})); + let got = radii(&s, &o); + assert!(got.iter().zip([7.0, 4.0, 1.0]).all(|(a, b)| close(*a, b)), "{got:?}"); + let before = s.doc.to_json(); + // A fourth has nothing left to take. The ladder has to run out here: a step past a ring + // smaller than the distance lands beyond the centre, and reading that as the outward side + // turned the ladder round and grew it again (1, 4, 1, 4 ...) rather than refusing. + let error = s.execute("sketch.offset", &json!({"curves": [c.clone()], "distance": 3, "side": [0, 0], "instances": 4})).unwrap_err().to_string(); + assert!(error.contains("instance 4 of 4"), "{error}"); + assert!(error.contains("no size"), "{error}"); + assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone"); + // Outward is unaffected: every ring is one distance larger than the last. + let out = run(&mut s, "sketch.offset", json!({"curves": [c], "distance": 3, "side": [40, 0], "instances": 3})); + let got = radii(&s, &out); + assert!(got.iter().zip([13.0, 16.0, 19.0]).all(|(a, b)| close(*a, b)), "{got:?}"); +} + +#[test] +fn offset_instances_follow_each_side_of_a_symmetric_offset() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + // Symmetric by 5, two instances: both ways get a second ring a further 5 out, so the four + // rings are 5 and 10 inside and 5 and 10 outside. + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 5, "symmetric": true, "instances": 2})); + let sides = o["sides"].as_array().unwrap().clone(); + assert_eq!(sides.len(), 4, "{o}"); + assert_eq!(sides.iter().filter(|side| side["instance"] == 2).count(), 2, "{o}"); + let sk = sketch(&s); + let mut boxes: Vec<[f64; 4]> = sides + .iter() + .map(|side| { + let (lo, hi) = bounds(&sk, &ids(&side["curves"])); + [lo.x, lo.y, hi.x, hi.y] + }) + .collect(); + boxes.sort_by(|a, b| a[0].total_cmp(&b[0])); + let want = [[-10.0, -10.0, 50.0, 40.0], [-5.0, -5.0, 45.0, 35.0], [5.0, 5.0, 35.0, 25.0], [10.0, 10.0, 30.0, 20.0]]; + for (got, want) in boxes.iter().zip(&want) { + assert!(got.iter().zip(want).all(|(a, b)| close(*a, *b)), "{boxes:?}"); + } +} + #[test] fn offset_both_sides_of_a_rounded_boundary_keep_separate_associations() { let mut s = new_sketch(); diff --git a/crates/engine/src/cmd/sketch_point_expr_tests.rs b/crates/engine/src/cmd/sketch_point_expr_tests.rs index 678fe5038..c8b148ec8 100644 --- a/crates/engine/src/cmd/sketch_point_expr_tests.rs +++ b/crates/engine/src/cmd/sketch_point_expr_tests.rs @@ -400,3 +400,50 @@ fn a_rejected_size_or_corner_expression_leaves_nothing_behind() { assert_eq!(count(&s), before, "{cmd} {p}"); } } + +/// A corner typed as an expression that comes to 0 when drawn lands on the origin; it must not +/// be tied to it by the automatic Coincident a snapped click gets, or the next parameter change +/// conflicts with the tie (#10703). +#[test] +fn a_rectangle_corner_whose_expression_is_zero_when_drawn_is_not_tied_to_the_origin() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "x0", "expression": "0 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": ["x0", 0], "p1": [40, 30]})); + assert_eq!(r["constraints"].as_array().map(Vec::len), Some(4), "the four side constraints, no Coincident to the origin: {r}"); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "S", "distance": 10})); + no_trouble(&s); + assert!((volume(&mut s) - 40.0 * 30.0 * 10.0).abs() < 1e-6); + run(&mut s, "parameters.change", json!({"name": "x0", "expression": "15 mm"})); + no_trouble(&s); + assert!((volume(&mut s) - 25.0 * 30.0 * 10.0).abs() < 1e-6); +} + +/// The same for a lone `sketch.point`: an expression that comes to the origin at draw time +/// leaves the point free, and it follows the parameter from there (#10703). +#[test] +fn a_point_whose_expression_is_zero_when_drawn_is_not_tied_to_the_origin() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "x0", "expression": "0 mm"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(&mut s, "sketch.point", json!({"point": ["x0", 0], "id": "p"})); + assert_eq!(r["constraints"].as_array().map(Vec::len), Some(0), "no Coincident to the origin: {r}"); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); + run(&mut s, "parameters.change", json!({"name": "x0", "expression": "15 mm"})); + no_trouble(&s); + assert_eq!(solved(&s, "p"), Vec2::new(15.0, 0.0)); +} + +/// A corner given as plain numbers on the origin still snaps to it, as a clicked point does: +/// only expression-placed points are exempt from the automatic Coincident. +#[test] +fn a_plain_corner_on_the_origin_still_snaps_to_it() { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"})); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + assert_eq!(r["constraints"].as_array().map(Vec::len), Some(5), "the four side constraints plus the Coincident to the origin: {r}"); + run(&mut s, "sketch.finish", json!({})); + no_trouble(&s); +} diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index e8933b53f..7ae27da8f 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -1414,3 +1414,46 @@ fn a_spheres_silhouette_is_one_circle() { let done = run(&mut s, "sketch.finish", json!({})); assert_eq!(done["profiles"], 1, "{done}"); } + +/// The silhouette of a square with a conic round at each corner (rho 0.19, 0.4, 0.5 and 0.7) is +/// one closed outline of the square's true area. Fitted arcs along a conic were snapped onto lines +/// that ended further along the outline, which left gaps of up to 3.6 mm: no profile. +#[test] +fn the_silhouette_of_conic_rounds_closes() { + let mut s = Session::default(); + let corners = [ + ([-75., 65.], [-75., 75.], [-65., 75.], 0.19), + ([65., 75.], [75., 75.], [75., 65.], 0.4), + ([75., -65.], [75., -75.], [65., -75.], 0.5), + ([-65., -75.], [-75., -75.], [-75., -65.], 0.7), + ]; + run(&mut s, "sketch.create", json!({"plane": "XZ"})); + for (i, (start, apex, end, rho)) in corners.iter().enumerate() { + run(&mut s, "sketch.conic", json!({"start": start, "apex": apex, "end": end, "rho": rho})); + let next = corners[(i + 1) % 4].0; + run(&mut s, "sketch.line", json!({"points": [end, next]})); + } + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 55, "body_name": "Part"})); + run(&mut s, "sketch.create", json!({"plane": "XZ", "offset": -10})); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Part"}]})); + // The true area: the outline through the four rational quadratic Béziers (apex weight + // rho / (1 - rho)), finely sampled, and the straight sides between them. + let mut outline: Vec<[f64; 2]> = Vec::new(); + for (start, apex, end, rho) in corners { + let w = rho / (1. - rho); + for k in 0..=2000 { + let t = f64::from(k) / 2000.; + let (b0, b1, b2) = ((1. - t) * (1. - t), 2. * t * (1. - t) * w, t * t); + let sum = b0 + b1 + b2; + outline.push([(b0 * start[0] + b1 * apex[0] + b2 * end[0]) / sum, (b0 * start[1] + b1 * apex[1] + b2 * end[1]) / sum]); + } + } + let n = outline.len(); + let exact = (0..n).map(|i| outline[i][0] * outline[(i + 1) % n][1] - outline[(i + 1) % n][0] * outline[i][1]).sum::().abs() / 2.; + let si = inspect(&mut s); + let profiles = si["profiles"].as_array().unwrap(); + assert_eq!(profiles.len(), 1, "{}", si["profiles"]); + let area = profiles[0]["area_mm2"].as_f64().unwrap(); + assert!((area - exact).abs() < exact * 2e-4, "area {area}, exact {exact}"); +} diff --git a/crates/engine/src/construct_tests.rs b/crates/engine/src/construct_tests.rs index 853304a98..5d32dd222 100644 --- a/crates/engine/src/construct_tests.rs +++ b/crates/engine/src/construct_tests.rs @@ -43,6 +43,55 @@ fn plane(s: &Session, name: &str) -> Plane { construction_planes(s).into_iter().find(|p| p.1 == name).map(|p| p.2).unwrap_or_else(|| panic!("no plane {name}")) } +#[test] +fn construction_plane_names_cannot_be_reused_by_new_features() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 5, "body_name": "Block"})); + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Mid"})); + let before = s.doc.clone(); + for (command, params) in [ + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Mid"})), + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": " Mid "})), + ("sketch.create", json!({"plane": "XY", "name": "Mid"})), + ("solid.box", json!({"length": 1, "width": 1, "height": 1, "name": "Mid"})), + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Box1"})), + ] { + let error = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(error.contains("another feature is called"), "{command}: {error}"); + assert_eq!(s.doc, before, "{command}: a refused creation changes nothing"); + } + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Upper"})); + run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "Upper"})); + let measured = run(&mut s, "inspect.measure", json!({})); + let mirrored = measured["bodies"].as_array().unwrap().iter().find(|b| b["name"] == "Block (2)").unwrap(); + assert_eq!(mirrored["bbox"]["min"][2], 35.0); + assert_eq!(mirrored["bbox"]["max"][2], 40.0); +} + +#[test] +fn redefining_a_construction_plane_keeps_its_existing_name() { + let mut s = Session::default(); + let id = run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Mid"}))["feature"].as_u64().unwrap(); + run(&mut s, "sketch.create", json!({"plane": "Mid", "name": "Profile"})); + run(&mut s, "sketch.finish", json!({})); + run( + &mut s, + "timeline.redefine", + json!({"feature": id, "command": "construct.plane.offset", "params": {"base": "XY", "offset": 20, "name": "Mid"}}), + ); + assert_eq!(s.doc.feature(id).unwrap().name, "Mid"); + assert_eq!(s.doc.features.len(), 2); + assert!(near(plane(&s, "Mid").origin, Vec3::new(0.0, 0.0, 20.0))); + run(&mut s, "edit.undo", json!({})); + assert!(near(plane(&s, "Mid").origin, Vec3::new(0.0, 0.0, 10.0))); + run(&mut s, "edit.redo", json!({})); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + reopened.refresh(); + assert_eq!(reopened.doc.feature(id).unwrap().name, "Mid"); + assert!(near(plane(&reopened, "Mid").origin, Vec3::new(0.0, 0.0, 20.0))); + assert!(reopened.model.results.iter().all(|r| r.error.is_none())); +} + #[test] fn renamed_construction_references_survive_edits_and_reopening() { let mut s = Session::default(); diff --git a/crates/engine/src/face_name_tests.rs b/crates/engine/src/face_name_tests.rs index 672d5cc99..d4ad4b863 100644 --- a/crates/engine/src/face_name_tests.rs +++ b/crates/engine/src/face_name_tests.rs @@ -241,3 +241,28 @@ fn replace_face_takes_the_face_by_name() { // A's top moves up to B's, 15 high: 10 x 10 x 15. assert!((volume(&mut s, "A") - 1500.0).abs() < 1e-6, "{}", volume(&mut s, "A")); } + +/// A face name on two bodies, each with one such face (two bodies one extrude made, the pieces of +/// a split body), is not a split face: a hole placed on one of them gives no warning (#10699). +#[test] +fn a_face_name_on_two_bodies_is_no_split_face() { + let said = |s: &Session, feature: &str| { + let r = s.model.result(s.doc.find_feature(feature).unwrap().id).unwrap(); + format!("{}{}", r.error.clone().unwrap_or_default(), r.warning.clone().unwrap_or_default()) + }; + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [14, 0], "p1": [24, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 10, "operation": "new"})); + run(&mut s, "solid.hole", json!({"position": [5, 5, 10], "diameter": 5, "depth": 5, "name": "Hole1"})); + assert_eq!(said(&s, "Hole1"), ""); + assert!((volume(&mut s, "Body1") - (1000.0 - PI * 2.5 * 2.5 * 5.0)).abs() < 0.1); + assert!((volume(&mut s, "Body2") - 1000.0).abs() < 1e-6); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10})); + run(&mut s, "solid.split_body", json!({"body": "Body1", "plane": {"origin": [20, 0, 0], "normal": [1, 0, 0]}})); + run(&mut s, "solid.hole", json!({"position": [30, 10, 10], "diameter": 5, "name": "Hole1", "targets": ["Body1"]})); + assert_eq!(said(&s, "Hole1"), ""); +} diff --git a/crates/engine/src/measure_centre_tests.rs b/crates/engine/src/measure_centre_tests.rs index 36e0eda92..f0bff39b1 100644 --- a/crates/engine/src/measure_centre_tests.rs +++ b/crates/engine/src/measure_centre_tests.rs @@ -336,6 +336,48 @@ fn a_cylinders_top_circle_is_as_long_as_its_circumference() { assert!(close(&r["items"][0]["length_mm"], TAU * 5.0, 1e-9), "{r}"); } +/// The first face whose analytic surface satisfies `want`, as a pick. +fn face_of(s: &Session, want: impl Fn(solidcraft_kernel::FaceSurface) -> bool) -> Value { + let st = s.model.state(); + let b = st.bodies.first().unwrap(); + let m = b.mesh(); + let n = m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap(); + let f = (0..n).find(|&f| solidcraft_kernel::face_surface(&b.body, f).is_some_and(&want)).expect("face"); + let p = m.triangles.iter().zip(&m.tri_face).find(|(_, tf)| **tf as usize == f).and_then(|(t, _)| m.tri(t)).unwrap()[0]; + json!({"type": "face", "body": b.name, "index": f, "point": p}) +} + +/// A fillet round the foot of a boss is a toroidal face: it measures its radius (the fillet's) +/// next to its area, and says it is a torus with its ring radius too. +#[test] +fn a_fillet_round_a_boss_reports_its_radius() { + use solidcraft_kernel::FaceSurface; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10})); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 12, "base": [20, 20, 10], "operation": "join"})); + run(&mut s, "solid.fillet", json!({"edges": [[25, 20, 10]], "radius": 3})); + let fillet = face_of(&s, |f| matches!(f, FaceSurface::Torus { minor, .. } if (minor - 3.0).abs() < 1e-6)); + let r = measure(&mut s, vec![fillet]); + assert!(close(&r["radius"], 3.0, 1e-6) && close(&r["diameter"], 6.0, 1e-6), "{r}"); + assert_eq!(r["items"][0]["surface"], "torus", "{r}"); + // The ring through the middle of the rolling ball: the boss's radius plus the fillet's. + assert!(close(&r["items"][0]["major_radius"], 8.0, 1e-6), "{r}"); + // The area is still there. + assert!(r["items"][0]["area_mm2"].as_f64().is_some_and(|a| a > 1.0), "{r}"); +} + +/// A ball's face reports its radius. +#[test] +fn a_sphere_face_reports_its_radius() { + use solidcraft_kernel::FaceSurface; + let mut s = Session::default(); + run(&mut s, "solid.sphere", json!({"radius": 7, "center": [0, 0, 0]})); + let ball = face_of(&s, |f| matches!(f, FaceSurface::Sphere { .. })); + let r = measure(&mut s, vec![ball]); + assert!(close(&r["radius"], 7.0, 1e-6) && close(&r["diameter"], 14.0, 1e-6), "{r}"); + assert_eq!(r["items"][0]["surface"], "sphere", "{r}"); +} + /// A plate with holes through STEP: the holes come back as cylinders, and measure the same. #[test] fn step_round_trip_of_a_plate_with_holes() { diff --git a/crates/engine/src/render_jobs.rs b/crates/engine/src/render_jobs.rs index 7ea415311..b7d0d801a 100644 --- a/crates/engine/src/render_jobs.rs +++ b/crates/engine/src/render_jobs.rs @@ -36,6 +36,41 @@ pub(crate) struct Execution { pub executor: solidcraft_render::ExecutorId, pub options: solidcraft_render::job::JobOptions, pub environment: Option, + pub shot: Option, +} + +struct LiveJob { + handle: JobHandle, + shot: Option, +} + +/// Transient completed-image metadata. Neither pixels nor selection enter a design or undo. +#[derive(Clone, Debug, serde::Serialize)] +pub struct RetainedResult { + pub frame: solidcraft_render::job::FrameInfo, + pub shot: Option, + pub seconds: f64, + pub stale: bool, +} + +struct Completed { + handle: JobHandle, + info: RetainedResult, +} + +pub(crate) struct BatchShot { + pub name: String, + pub camera: solidcraft_render::Camera, + pub request: Arc, +} + +#[derive(Clone, Debug, serde::Serialize)] +pub struct RenderQueueState { + pub running: usize, + pub waiting: usize, + pub job: Option, + pub shot: Option, + pub error: Option, } pub(crate) struct Jobs { @@ -45,12 +80,14 @@ pub(crate) struct Jobs { pub(crate) host: Option, pub(crate) descriptor: Option, pub(crate) additional: Vec<(CpuHost, ExecutorDescriptor)>, - live: Vec, + live: Vec, history: VecDeque, - last_good: Option, - /// One explicitly displayed completed result, independent of a newer completion. - /// The existing frame Arc keeps its original host reservation accounted for. - pinned: Option, + completed: VecDeque, + selected: Option, + waiting: VecDeque, + batch_job: Option, + batch_error: Option, + comparison: Option<[Option; 2]>, } impl Default for Jobs { @@ -64,8 +101,12 @@ impl Default for Jobs { additional: Vec::new(), live: Vec::new(), history: VecDeque::new(), - last_good: None, - pinned: None, + completed: VecDeque::new(), + selected: None, + waiting: VecDeque::new(), + batch_job: None, + batch_error: None, + comparison: None, } } } @@ -73,12 +114,26 @@ impl Default for Jobs { impl Drop for Jobs { fn drop(&mut self) { for job in &self.live { - let _ = job.cancel(); + let _ = job.handle.cancel(); } } } impl Jobs { + pub(crate) fn set_comparison(&mut self, sides: Option<[Option; 2]>) { + self.comparison = sides; + if let Some([left, right]) = sides { + self.selected = right.or(left); + } + } + + fn valid_comparison(&self) -> Option<[Option; 2]> { + self.comparison.filter(|sides| sides.iter().flatten().all(|job| self.completed.iter().any(|result| result.handle.id() == *job))) + } + pub(crate) fn has_results(&self) -> bool { + !self.completed.is_empty() || self.live.iter().any(|job| job.handle.frame().ok().flatten().is_some()) + } + pub(crate) fn host_for(&self, executor: &solidcraft_render::ExecutorId) -> Option<&CpuHost> { if executor.as_str() == "cpu-raytrace" { return self @@ -103,14 +158,26 @@ impl Jobs { pub(crate) fn collect(&mut self) -> Result<(), JobError> { let mut i = 0; while i < self.live.len() { - let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.status()?; + let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.handle.status()?; if !status.progress.phase.terminal() { i += 1; continue; } - let handle = self.live.remove(i); - if status.progress.phase == Phase::Completed && self.last_good.as_ref().is_none_or(|old| old.id().serial < handle.id().serial) { - self.last_good = Some(handle); + let job = self.live.remove(i); + if let Some(frame) = status.frame.as_ref().filter(|_| status.progress.phase == Phase::Completed) { + let seconds = job.handle.completed_duration()?.map_or(0.0, |duration| duration.as_secs_f64()); + let completed_id = job.handle.id(); + self.completed.push_back(Completed { + handle: job.handle, + info: RetainedResult { frame: frame.clone(), shot: job.shot, seconds, stale: false }, + }); + while self.completed.len() > 8 { + self.completed.pop_front(); + } + if self.valid_comparison().is_none() { + self.comparison = None; + self.selected = Some(completed_id); + } } self.history.push_back(status); while self.history.len() > 4 { @@ -128,12 +195,19 @@ impl Jobs { replace: bool, execution: Execution, ) -> Result { - let Execution { executor, options, environment } = execution; + let Execution { executor, options, environment, shot } = execution; + if self.batch_job.is_some() { + if !replace { + return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before starting another render")); + } + self.waiting.clear(); + self.batch_job = None; + } self.collect()?; let host = self.host_for(&executor).ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "resolved image host is not installed"))?.clone(); if replace { for job in self.live.drain(..) { - let mut status = job.cancel()?; + let mut status = job.handle.cancel()?; // Replaced handles are deliberately abandoned: keep a cancellation tombstone, // not a permanently "cancelling" snapshot. The token already prevents any // publication; the host can finish releasing its buffers asynchronously. @@ -165,7 +239,7 @@ impl Jobs { let status = handle.status()?; self.serial = serial; self.generation = generation; - self.live.push(handle); + self.live.push(LiveJob { handle, shot }); Ok(status) } @@ -174,6 +248,9 @@ impl Jobs { source_id: JobId, presentation: solidcraft_render::job::presentation::Presentation, ) -> Result { + if self.batch_job.is_some() { + return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before regrading")); + } self.collect()?; let source = self.handle(source_id)?; let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?; @@ -194,7 +271,8 @@ impl Jobs { let status = handle.status()?; self.serial = serial; self.generation = generation; - self.live.push(handle); + let shot = self.completed.iter().find(|result| result.handle.id() == source_id).and_then(|result| result.info.shot.clone()); + self.live.push(LiveJob { handle, shot }); Ok(status) } @@ -209,8 +287,8 @@ impl Jobs { self.check_owner(id)?; self.live .iter() - .chain(self.last_good.iter()) - .chain(self.pinned.iter()) + .map(|job| &job.handle) + .chain(self.completed.iter().map(|result| &result.handle)) .find(|j| j.id() == id) .cloned() .ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "render job is no longer retained")) @@ -226,17 +304,35 @@ impl Jobs { } pub(crate) fn pin(&mut self, id: Option) -> Result, JobError> { + self.collect()?; let Some(id) = id else { - self.pinned = None; + self.selected = None; + self.comparison = None; return Ok(None); }; let handle = self.handle(id)?; let frame = handle.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "only a completed result can be pinned"))?; let info = frame.info.clone(); - self.pinned = Some(handle); + self.comparison = None; + self.selected = Some(id); Ok(Some(info)) } + pub(crate) fn result_index(&mut self, index: usize, discard: bool) -> Result<(), JobError> { + self.collect()?; + let id = self.completed.get(index).ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "retained result index is out of bounds"))?.handle.id(); + if discard { + self.completed.remove(index); + if self.selected == Some(id) { + self.selected = self.completed.back().map(|result| result.handle.id()); + } + } else { + self.comparison = None; + self.selected = Some(id); + } + Ok(()) + } + pub(crate) fn frame(&mut self, id: JobId) -> Result, JobError> { self.collect()?; self.handle(id)?.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "render has no completed image")) @@ -244,6 +340,126 @@ impl Jobs { } impl crate::Session { + pub fn render_comparison(&self) -> Option<[Option; 2]> { + self.render_jobs.valid_comparison() + } + + pub fn render_queue_state(&self) -> RenderQueueState { + let active = self.render_jobs.batch_job.and_then(|id| self.render_jobs.live.iter().find(|job| job.handle.id() == id)); + RenderQueueState { + running: self.render_jobs.live.iter().filter(|job| job.handle.status().is_ok_and(|status| !status.progress.phase.terminal())).count(), + waiting: self.render_jobs.waiting.len(), + job: self.render_jobs.batch_job, + shot: active.and_then(|job| job.shot.clone()), + error: self.render_jobs.batch_error.clone(), + } + } + + pub fn render_batch_ready(&self) -> std::result::Result<(), String> { + if self.doc.render.setups.is_empty() { + return Err("no saved shots to render".into()); + } + if self.doc.render.setups.len() > 32 { + return Err("render all shots is limited to 32 shots".into()); + } + if self.render_jobs.batch_job.is_some() || self.render_queue_state().running != 0 { + return Err("a render or shot queue is already active".into()); + } + Ok(()) + } + + pub(crate) fn start_render_batch(&mut self, shots: VecDeque) -> crate::Result { + self.render_batch_ready().map_err(crate::EngineError::Other)?; + if shots.is_empty() || shots.len() > 32 { + return Err(crate::EngineError::Other("shot queue must contain 1..32 shots".into())); + } + let queued = shots.len(); + self.render_jobs.waiting = shots; + self.render_jobs.batch_error = None; + self.start_next_batch_shot()?; + Ok(queued) + } + + fn start_next_batch_shot(&mut self) -> crate::Result<()> { + let Some(shot) = self.render_jobs.waiting.pop_front() else { return Ok(()) }; + let result: crate::Result<()> = (|| { + let mut params = (*shot.request).clone(); + let settings = params + .get_mut("settings") + .and_then(serde_json::Value::as_object_mut) + .ok_or_else(|| crate::EngineError::Other("queued render settings are missing".into()))?; + settings.insert("camera".into(), serde_json::json!(shot.camera)); + let reply = self.execute("render.start", ¶ms)?; + let job: JobId = serde_json::from_value(reply.get("job").cloned().unwrap_or_default()) + .map_err(|error| crate::EngineError::Other(format!("invalid queued render identity: {error}")))?; + self.label_render_job(job, &shot.name)?; + self.render_jobs.batch_job = Some(job); + Ok(()) + })(); + if let Err(error) = &result { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_error = Some(error.to_string()); + } + result + } + + /// Non-blocking queue scheduling. The existing host still owns all render work. + pub fn advance_render_batch(&mut self) -> crate::Result<()> { + let Some(job) = self.render_jobs.batch_job else { return Ok(()) }; + let status = self.render_jobs.status(job).map_err(job_error)?; + if !status.progress.phase.terminal() { + return Ok(()); + } + self.render_jobs.batch_job = None; + if status.progress.phase != Phase::Completed { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_error = status.error.map(|error| error.to_string()); + return Ok(()); + } + self.start_next_batch_shot() + } + + pub(crate) fn cancel_render_batch(&mut self, job: JobId) { + if self.render_jobs.batch_job == Some(job) { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_job = None; + } + } + + /// Capture the UI draft's label alongside an unnamed active request, never in the design. + pub fn label_render_job(&mut self, id: JobId, shot: &str) -> crate::Result<()> { + solidcraft_doc::render_settings::RenderSettings::validate_name(shot).map_err(|error| crate::EngineError::Other(error.to_string()))?; + let job = self + .render_jobs + .live + .iter_mut() + .find(|job| job.handle.id() == id) + .ok_or_else(|| job_error(JobError::new(ErrorCode::UnknownJob, "render job is no longer active")))?; + if job.shot.is_none() { + job.shot = Some(shot.to_owned()); + } + Ok(()) + } + + /// Oldest first, capped at eight. Staleness follows the current design revision. + pub fn render_retained_results(&mut self) -> crate::Result> { + self.render_jobs.collect().map_err(job_error)?; + Ok(self + .render_jobs + .completed + .iter() + .map(|result| { + let mut info = result.info.clone(); + info.stale = info.frame.scene_generation != self.revision; + info + }) + .collect()) + } + + pub fn render_selected_result(&self) -> Option { + self.render_jobs.selected + } + /// A host is installed by the application, never by document data or a command. pub fn set_render_job_host(&mut self, host: Option) -> crate::Result<()> { if self.render_jobs.host.as_ref().zip(host.as_ref()).is_some_and(|(a, b)| a.same_host(b)) { @@ -350,7 +566,7 @@ mod displayed_result_tests { panic!("bounded result fixture did not finish") } #[test] - fn explicit_display_pin_preserves_the_old_exact_frame_without_unbounded_history() { + fn explicit_display_pin_selects_exact_bytes_within_bounded_retention() { let mut s = crate::Session::default(); let host = CpuHost::cooperative(); s.set_render_job_host(Some(host.clone())).unwrap(); @@ -368,10 +584,11 @@ mod displayed_result_tests { let foreign = JobId { session: old.session + 1, ..old }; assert!(s.execute("render.result.pin", &json!({"job":foreign})).is_err()); assert_eq!(host.admitted_bytes(), retained); - assert!(s.execute("render.result.pin", &json!({})).is_err()); + assert_eq!(s.execute("render.result.pin", &json!({})).unwrap()["frame"]["job"], json!(s.render_selected_result())); s.execute("render.result.pin", &json!({"job":null})).unwrap(); - assert!(s.render_job_handle(old).is_err()); - assert!(host.admitted_bytes() < retained); + assert!(s.render_selected_result().is_none()); + assert!(s.render_job_handle(old).is_ok(), "clearing selection does not discard retained results"); + assert_eq!(host.admitted_bytes(), retained); assert_eq!(s.doc.to_json(), before); assert_eq!(s.undo.len(), undo); let reply = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); diff --git a/crates/engine/src/schema/edit.rs b/crates/engine/src/schema/edit.rs index 901f33381..c84cf9674 100644 --- a/crates/engine/src/schema/edit.rs +++ b/crates/engine/src/schema/edit.rs @@ -3,6 +3,15 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; +/// Assistant visibility is UI-owned and takes no parameters. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AssistantParams {} + +/// Headless sessions refuse Assistant display requests and produce no result. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AssistantResult {} + /// `edit.repeat` takes no parameters: it starts the last tool with its defaults. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -39,12 +48,13 @@ pub struct TimelinePlayResult { #[cfg(test)] mod tests { - use super::RepeatParams; + use super::{AssistantParams, RepeatParams}; use crate::schema::input_schema_for; use crate::schema::tests::assert_keys; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &[]); } } diff --git a/crates/engine/src/schema/file.rs b/crates/engine/src/schema/file.rs new file mode 100644 index 000000000..58754f627 --- /dev/null +++ b/crates/engine/src/schema/file.rs @@ -0,0 +1,135 @@ +//! Contracts and result types for the commands in `cmd/file.rs`: so far the export command of +//! each format (`file.export_step`, `file.export_stl`, `file.export_3mf`, `file.export_obj`, +//! `file.export_urdf`), which take what `file.export` takes for that format, without `format`. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::types::StringList; + +/// How closely an exported mesh follows curved faces. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum MeshQualityParam { + /// A chord tolerance of 2e-4 of each body's size. + Standard, + /// 5e-5 of each body's size. + Fine, + /// 1e-5 of each body's size. + Finest, +} + +/// What each 3MF object holds. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum ObjectsParam { + /// One object per body. + Body, + /// One object for each placed component with two or more bodies, with those bodies as its + /// parts, so a slicer loads them as one object with parts; other bodies stay objects of their own. + Component, +} + +/// Export bodies as a STEP file. With no `bodies`, a design with components exports as a STEP +/// assembly, otherwise its bodies as placed. The file is STEP whatever the path's extension. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExportStepParams { + /// The file to write. + pub path: String, + /// The bodies to export, by name. Default: every body. + #[serde(default)] + pub bodies: Option, +} + +/// Export bodies as a mesh file: binary STL for `file.export_stl`, OBJ for `file.export_obj` +/// (the colours of the bodies go in a material library, `.mtl`, written next to it). The file +/// has that format whatever the path's extension. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExportMeshParams { + /// The file to write. + pub path: String, + /// The bodies to export, by name. Default: every body. + #[serde(default)] + pub bodies: Option, + /// How closely the mesh follows curved faces. Default: standard. + #[serde(default)] + pub quality: Option, +} + +/// Export bodies as a 3MF file, whatever the path's extension. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct Export3mfParams { + /// The file to write. + pub path: String, + /// The bodies to export, by name. Default: every body. + #[serde(default)] + pub bodies: Option, + /// How closely the mesh follows curved faces. Default: standard. + #[serde(default)] + pub quality: Option, + /// What each object in the file holds. Default: body. + #[serde(default)] + pub objects: Option, +} + +/// Export the whole assembly as a robot description (URDF), with an STL mesh for each link +/// written next to it (docs/urdf.md). +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExportUrdfParams { + /// The `.urdf` file to write; the meshes go in its folder. + pub path: String, + /// Put before each mesh file name in the URDF, such as `package://robot/meshes/`. Default: none. + #[serde(default)] + pub mesh_prefix: Option, + /// Each joint's effort limit, a positive number. Default: 1000. + #[serde(default)] + pub effort: Option, + /// Each joint's velocity limit, a positive number. Default: 10. + #[serde(default)] + pub velocity: Option, +} + +/// What `file.export_step`, `file.export_stl`, `file.export_3mf` and `file.export_obj` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ExportResult { + /// The file written. + pub path: String, + /// Its size in bytes. + pub bytes: usize, + /// The format written: Step, StlBinary, ThreeMf or Obj. + pub format: String, + /// OBJ only: every file written, the material library first and the mesh file last. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub files: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `file.export_urdf` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct UrdfExportResult { + /// The `.urdf` file written. + pub path: String, + /// Always Urdf. + pub format: String, + /// Every file written, the meshes first and the `.urdf` last. + pub files: Vec, + /// How many links the robot has. + pub links: usize, + /// How many joints the robot has. + pub joints: usize, + /// What the export could not carry over as it is in the design. + pub warnings: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "file_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/file_tests.rs b/crates/engine/src/schema/file_tests.rs new file mode 100644 index 000000000..f040637bf --- /dev/null +++ b/crates/engine/src/schema/file_tests.rs @@ -0,0 +1,38 @@ +use serde_json::json; + +use super::{Export3mfParams, ExportMeshParams, ExportStepParams, ExportUrdfParams}; +use crate::Session; +use crate::schema::tests::assert_keys; +use crate::schema::{ParamCheck, input_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["bodies", "path"]); + assert_keys(input_schema_for::(), &["bodies", "path", "quality"]); + assert_keys(input_schema_for::(), &["bodies", "objects", "path", "quality"]); + assert_keys(input_schema_for::(), &["effort", "mesh_prefix", "path", "velocity"]); +} + +#[test] +fn bad_calls_say_what_is_wrong_and_write_nothing() { + let dir = std::env::temp_dir().join(format!("solidcraft-export-schemas-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}")); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + for cmd in ["file.export_step", "file.export_stl", "file.export_3mf", "file.export_obj", "file.export_urdf"] { + let e = s.execute(cmd, &json!({})).unwrap_err().to_string(); + assert!(e.contains(cmd) && e.contains("path"), "{cmd}: {e}"); + } + let at = dir.join("a.stl").to_string_lossy().to_string(); + let e = s.execute("file.export_stl", &json!({"path": at, "quality": "rough"})).unwrap_err().to_string(); + assert!(e.contains("quality"), "{e}"); + s.param_check = ParamCheck::Strict; + let e = s.execute("file.export_stl", &json!({"path": at, "objects": "component"})).unwrap_err().to_string(); + assert!(e.contains("objects"), "objects is for 3MF only: {e}"); + s.param_check = ParamCheck::Off; + let e = s.execute("file.export_urdf", &json!({"path": at, "effort": -1})).unwrap_err().to_string(); + assert!(e.contains("effort"), "{e}"); + assert_eq!(std::fs::read_dir(&dir).map(|d| d.count()).unwrap_or(0), 0, "nothing written"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 69cb6f1f3..34c83f6d0 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -60,6 +60,7 @@ pub mod construct; pub mod diagnostics; pub mod edit; pub mod features; +pub mod file; pub mod inspect; pub mod joints; pub mod mass_properties; diff --git a/crates/engine/src/schema/render_ui.rs b/crates/engine/src/schema/render_ui.rs index eef51c954..be7551493 100644 --- a/crates/engine/src/schema/render_ui.rs +++ b/crates/engine/src/schema/render_ui.rs @@ -1,4 +1,4 @@ -//! Clipboard requests for the Render workspace; headless calls only echo validated text. +//! Contracts for transient Render workspace clipboard and retained-result requests. use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -9,3 +9,68 @@ pub struct CheckReport { #[schemars(length(min = 1, max = 65536))] pub text: String, } + +/// Select or discard a retained result without editing a design. +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ResultIndex { + /// Zero-based index, oldest first. The result must still be retained. + #[schemars(range(min = 0, max = 7))] + pub index: u32, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum LiveSide { + Live, +} + +/// A live product view or a retained result's zero-based index (oldest first). +#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)] +#[serde(untagged)] +pub enum CompareSide { + Live(LiveSide), + Result(#[schemars(range(min = 0, max = 7))] u32), +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ComparePair { + pub left: CompareSide, + pub right: CompareSide, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CompareOff { + /// Must be true. Leave comparison without changing retained results. + pub off: bool, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum CompareParams { + Off(CompareOff), + Pair(ComparePair), +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CompareDivider { + /// Finite fraction of the canvas width, clamped to 0.05..0.95. + pub position: f64, +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct BatchParams { + /// Optional render.start request. Its setup is shared, with each saved shot's camera. + /// Without a request, use the first saved shot's setup (name order). + pub request: Option>, +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct BatchResult { + /// Total accepted shots, including the first active job. At most 32. + pub queued: u32, +} diff --git a/crates/engine/src/schema/sketch_create.rs b/crates/engine/src/schema/sketch_create.rs index 558045450..7c6d1971e 100644 --- a/crates/engine/src/schema/sketch_create.rs +++ b/crates/engine/src/schema/sketch_create.rs @@ -80,6 +80,50 @@ pub struct SplineReverseParams { pub sketch: Option, } +/// Take one point out of a spline: it runs through (or over) its other points only, and the point +/// goes with the constraints on it unless another curve uses it. Takes fit point, control point +/// and closed splines; refused for a closed spline's closing point, for an end joined to other +/// geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed +/// spline), and for a projected, offset or patterned spline. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SplineRemovePointParams { + /// The spline's curve id. + #[serde(deserialize_with = "spline_id")] + pub curve: String, + /// One of the spline's points: a point id, or the curve's `start` or `end` (`s1.end`). + #[serde(deserialize_with = "point_ref")] + pub point: String, + /// The sketch (default: the one being edited). + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "SketchRef")] + pub sketch: Option, +} + +/// What `sketch.spline.remove_point` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SplineRemovePointResult { + /// The spline's curve id (unchanged). + pub curve: String, + /// The id the point had. + pub point: String, + /// Whether the point went too; `false` when another curve still uses it. + pub deleted: bool, + /// The sketch's solve: `{solved, dof}`. + pub sketch: Value, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// A point reference, with the handler's message for anything else. +fn point_ref<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(serde::de::Error::custom("must be one of the spline's points")), + } +} + /// A curve id, with the handler's message for anything else. fn spline_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { match Value::deserialize(d)? { diff --git a/crates/engine/src/schema/sketch_create_tests.rs b/crates/engine/src/schema/sketch_create_tests.rs index 3f841c626..bea64f761 100644 --- a/crates/engine/src/schema/sketch_create_tests.rs +++ b/crates/engine/src/schema/sketch_create_tests.rs @@ -1,6 +1,6 @@ use serde_json::json; -use super::{SplineReverseParams, SplineReverseResult}; +use super::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult}; use crate::Session; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; @@ -8,6 +8,7 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["curve", "sketch"]); + assert_keys(input_schema_for::(), &["curve", "point", "sketch"]); } #[test] @@ -17,9 +18,30 @@ fn strict_keeps_todays_errors() { ("sketch.spline.reverse", json!({"curve": null})), ("sketch.spline.reverse", json!({"curve": "nope"})), ("sketch.spline.reverse", json!({"curve": "l1"})), + ("sketch.spline.remove_point", json!({"curve": 5, "point": "p1"})), + ("sketch.spline.remove_point", json!({"curve": "nope", "point": "p1"})), + ("sketch.spline.remove_point", json!({"curve": "l1", "point": 3})), + ("sketch.spline.remove_point", json!({"curve": "l1"})), ]); } +#[test] +fn spline_remove_point_reply_matches_its_schema() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: serde_json::Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let c = run(&mut s, "sketch.spline.fit_point", json!({"points": [[5, 0], [10, 5], [20, 0], [30, 5], [40, 0]]})); + let spline = c["curves"][0].as_str().unwrap_or_else(|| panic!("{c}")).to_string(); + let schema = output_schema_for::(); + let schema = schema.as_value(); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": spline, "point": format!("{spline}.start")})); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": spline, "point": format!("{spline}.end"), "unknown": 1})); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}"); +} + #[test] fn spline_reverse_reply_matches_its_schema() { let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 779d5fadf..345c67df9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1092,8 +1092,15 @@ fn hostile_params_never_panic() { let _ = start.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [5, 5]})); for v in hostile_values() { for k in keys { - if k == "path" && (id.starts_with("parameters.") || id == "timeline.export_script") { - continue; // parameter and script files: covered by their own tests (no stray files) + if k == "path" + && (id.starts_with("parameters.") + || id == "timeline.export_script" + || matches!( + id, + "file.export_3mf" | "file.export_obj" | "file.export_step" | "file.export_stl" | "file.export_urdf" + )) + { + continue; // parameter, script and export files: covered by their own tests (no stray files) } let mut s = copy_with_history(&start); let p = json!({ k: v.clone() }); @@ -1323,7 +1330,8 @@ fn timeline_inspect_shows_what_timeline_edit_changes() { run(&mut s, "solid.extrude", json!({"distance": 10, "name": "Slab"})); run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2, "name": "Round"})); let i = run(&mut s, "timeline.inspect", json!({"feature": "Slab"})); - assert_eq!(i["type"], "ExtrudeFeature", "{i}"); + assert_eq!(i["type"], "extrude", "{i}"); + assert_eq!(i["type_name"], "ExtrudeFeature", "{i}"); assert_eq!(i["definition"]["extent"]["distance"], "10", "{i}"); assert_eq!(i["definition"]["operation"], "new_body", "{i}"); assert!(i["definition"].get("type").is_none() && i["definition"].get("param_names").is_none(), "{i}"); @@ -3077,6 +3085,60 @@ fn press_pull_on_curved_faces() { assert!((volume(&mut s) - v0 - ring).abs() < 4e-7 * v0, "{} vs {ring}", volume(&mut s) - v0); } +/// #4986: Press Pull on a chamfer's flat face changes the chamfer's distance, as on a fillet's +/// face it changes the radius, rather than extruding the face. +#[test] +fn press_pull_on_a_chamfer_face_edits_the_chamfer() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + run(&mut s, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"})); + let cut = |d: f64| d * d / 2.0 * 20.0; + assert!(rel(volume(&mut s), 24000.0 - cut(3.0)) < 1e-6); + // The chamfer's face runs from (37, 0) to (40, 3); its middle. + let out = run(&mut s, "solid.press_pull", json!({"face": [38.5, 1.5, 10], "distance": 2})); + assert_eq!(out["edited"], "Bevel", "{out}"); + assert_eq!(s.doc.features.len(), 2, "no extrude added"); + assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{}", volume(&mut s)); + // A point on the flat front face 0.02 mm from its edge with the chamfer (which now runs from + // (35, 0) to (40, 5)) is the front face's: it is extruded, the chamfer is left alone. + let mut t = Session::default(); + run(&mut t, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + run(&mut t, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"})); + let out = run(&mut t, "solid.press_pull", json!({"face": [36.98, 0, 10], "distance": 1})); + assert!(out.get("edited").is_none(), "{out}"); + assert!(matches!(t.doc.features.last().map(|f| &f.kind), Some(solidcraft_doc::FeatureKind::Extrude { .. })), "an extrude added: {out}"); + assert!( + matches!(&t.doc.features[1].kind, solidcraft_doc::FeatureKind::Chamfer { distance, .. } if distance == "3"), + "{:?}", + t.doc.features[1].kind + ); + // Too far in (past zero) or too far out: an error, the chamfer as it was. + let on = [39.0, 1.0, 10.0]; + for d in [-10.0, 1e9] { + assert!(s.execute("solid.press_pull", &json!({"face": on, "distance": d})).is_err(), "{d}"); + assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{d}: {}", volume(&mut s)); + } + // An unequal chamfer's first distance changes and its second stays; an angle chamfer keeps + // its angle. + // Each chamfer's face crosses the corner's bisector at legs a, b: (40 - u, u), u = ab / (a + b). + let tan30 = (PI / 6.0).tan(); + for (extra, u) in [(json!({"distance2": 4}), 8.0 / 6.0), (json!({"angle": "30 deg"}), 2.0 * tan30 / (1.0 + tan30))] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + let mut p = json!({"edges": [[40, 0, 10]], "distance": 2, "name": "Bevel"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + run(&mut s, "solid.chamfer", p); + let v0 = volume(&mut s); + let out = run(&mut s, "solid.press_pull", json!({"face": [40.0 - u, u, 10.0], "distance": 1})); + assert_eq!(out["edited"], "Bevel", "{extra}: {out}"); + assert_eq!(s.doc.features.len(), 2, "{extra}"); + let Some(solidcraft_doc::FeatureKind::Chamfer { distance2, angle, .. }) = s.doc.features.last().map(|f| &f.kind) else { panic!("{extra}") }; + assert_eq!(distance2.as_ref().map(|e| e.to_string()), extra.get("distance2").map(|v| v.to_string()), "{extra}"); + assert_eq!(angle.as_ref().map(|e| e.to_string()), extra.get("angle").and_then(|v| v.as_str()).map(str::to_string), "{extra}"); + assert!(volume(&mut s) < v0 - 1.0, "{extra}: a bigger chamfer cuts more"); + } +} + /// A cut in one component leaves other components' bodies alone unless they are named as /// participants; auto join/cut looks at the active component only. #[test] diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index e509668be..f61531ca1 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -107,13 +107,17 @@ impl Capturer { self.lost.load(Ordering::Acquire) } - /// [`Capturer::is_lost`], asking the driver first: an empty submission meets a loss the - /// driver reports and marks it, where the picture's first upload would panic inside wgpu. + /// [`Capturer::is_lost`], asking the driver first: a submission that opens a command list + /// meets a loss the driver reports and marks it, where the picture's first upload would + /// panic inside wgpu. As `egui_wgpu::DeviceLost::probe`: an empty submission only signals a + /// fence, which a reset D3D12 device let through (#6528). fn probe_lost(&self) -> bool { if self.is_lost() { return true; } - self.queue.submit([]); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("device lost probe") }); + encoder.insert_debug_marker("device lost probe"); + self.queue.submit([encoder.finish()]); self.is_lost() } diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 46569aa7b..afb300195 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -44,3 +44,6 @@ rustix = { version = "1", default-features = false, features = ["std", "fs"] } # The computer's name for a design's lock file (src/design_lock.rs; the browser keeps no lock files). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] gethostname = { workspace = true } + +[dev-dependencies] +solidcraft-testkit = { workspace = true } diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs index 10e27a12b..c5dcd68b1 100644 --- a/crates/io/src/mutate.rs +++ b/crates/io/src/mutate.rs @@ -1,323 +1,40 @@ -//! Deterministic mutations of valid files, and the readers run over them (#469). Every reader of -//! bytes the user didn't write gets the same treatment: truncation, flipped and overwritten -//! bytes, dropped and repeated runs, appended garbage and, for text formats, dropped and -//! repeated lines and numbers that lie (`nan`, `inf`, `1e400`, …). Each mutated file must give an -//! error or a result, never a panic, within a time budget and the reader's own caps. A panic a -//! reader catches itself (`solidcraft_kernel::guard`) counts too: the browser build aborts on any -//! panic, so a caught one on the desktop is a crash there. -//! -//! The mutations come from a fixed seed (xorshift), so a failure names a case that reproduces. -//! No fuzzing dependency, nothing nightly, nothing native: it runs in the normal test suite and -//! builds for wasm. The readers' own hand-written cases stay; they cover particular lies (a -//! length in a container header) that random changes rarely hit. STEP, IGES and FreeCAD/Rhino -//! files are read by the kernel, which is moving to solidcore (#1597), and keep their own tests. +//! Every reader of bytes the user didn't write, run over mutations of a valid file (#469): each +//! case gives an error or a result, never a panic, within the time budget and the reader's own +//! caps. The mutations and the check are `solidcraft_testkit`'s. -use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::time::{Duration, Instant}; +use solidcraft_geom::{Mesh, Vec2, Vec3}; +use solidcraft_testkit::{mutations, survives}; -/// A deterministic xorshift64 stream. -pub(crate) struct Rng(u64); - -impl Rng { - pub(crate) fn new(seed: u64) -> Rng { - Rng(seed | 1) - } - - pub(crate) fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } - - /// A value in `0..n` (0 when `n` is 0). - pub(crate) fn below(&mut self, n: usize) -> usize { - if n == 0 { 0 } else { (self.next() % n as u64) as usize } - } +fn cube() -> Mesh { + let positions = (0..8).map(|i| Vec3::new(f64::from(i & 1) * 10.0, f64::from((i >> 1) & 1) * 10.0, f64::from((i >> 2) & 1) * 10.0)).collect(); + let t = [[0, 2, 1], [1, 2, 3], [4, 5, 6], [5, 7, 6], [0, 1, 4], [1, 5, 4], [2, 6, 3], [3, 6, 7], [0, 4, 2], [2, 4, 6], [1, 3, 5], [3, 7, 5]]; + Mesh { positions, triangles: t.to_vec(), ..Default::default() } } -/// Numbers a hostile file might hold in place of a real one. -const LIARS: [&str; 10] = ["nan", "inf", "-inf", "1e400", "-1e400", "-0", "4294967296", "-1", "99999999999999999999", "0x7fffffff"]; - -/// Most truncations of one file (every length up to this, evenly spaced beyond). -const MAX_TRUNCATIONS: usize = 1024; - -/// Mutations of `good`, the same for the same `good` and `seed`. `text`: also line and number -/// mutations (the file is UTF-8 text). -pub(crate) fn mutations(good: &[u8], text: bool, seed: u64) -> Vec> { - let mut out: Vec> = Vec::new(); - let n = good.len(); - let mut rng = Rng::new(seed); - // Truncations: every length of a short file; of a long one, its first and last 64 lengths - // (headers, final records) and evenly spaced ones between. - if n <= MAX_TRUNCATIONS { - out.extend((0..n).map(|k| good[..k].to_vec())); - } else { - let mut cuts: Vec = (0..64).chain(n - 64..n).collect(); - cuts.extend((0..MAX_TRUNCATIONS - 128).map(|i| 64 + i * (n - 128) / (MAX_TRUNCATIONS - 128))); - cuts.sort_unstable(); - cuts.dedup(); - out.extend(cuts.into_iter().map(|k| good[..k].to_vec())); - } - if n == 0 { - return out; - } - // Bytes flipped, zeroed and saturated at seeded places. - for i in 0..384 { - let at = rng.below(n); - let mut b = good.to_vec(); - b[at] = match i % 3 { - 0 => b[at] ^ ((rng.next() >> 32) as u8 | 1), - 1 => 0x00, - _ => 0xff, - }; - out.push(b); - } - // Runs of bytes dropped, repeated and swapped with their neighbour. - for _ in 0..96 { - let at = rng.below(n); - let len = 1 + rng.below(64.min(n - at)); - let end = at + len; - let mut dropped = good[..at].to_vec(); - dropped.extend_from_slice(&good[end..]); - out.push(dropped); - let mut repeated = good[..end].to_vec(); - repeated.extend_from_slice(&good[at..]); - out.push(repeated); - if end + len <= n { - let mut swapped = good[..at].to_vec(); - swapped.extend_from_slice(&good[end..end + len]); - swapped.extend_from_slice(&good[at..end]); - swapped.extend_from_slice(&good[end + len..]); - out.push(swapped); - } - } - // The whole file: with garbage after it, twice over, reversed. - let mut tail = good.to_vec(); - tail.extend((0..4096).map(|_| (rng.next() >> 40) as u8)); - out.push(tail); - out.push([good, good].concat()); - out.push(good.iter().rev().copied().collect()); - if text && let Ok(s) = std::str::from_utf8(good) { - out.extend(text_mutations(s, &mut rng)); - } - out +#[test] +fn stl_survives_mutation() { + let mesh = cube(); + let binary = crate::stl_binary(std::slice::from_ref(&mesh), "fuzz"); + let ascii = crate::stl_ascii(std::slice::from_ref(&mesh), "fuzz").into_bytes(); + assert_eq!(crate::read_stl(&binary).map(|t| t.len()).ok(), Some(12)); + assert_eq!(crate::read_stl(&ascii).map(|t| t.len()).ok(), Some(12)); + let read = |b: &[u8]| crate::read_stl(b).ok().map(|t| t.len()); + survives("binary STL", &mutations(&binary, false, 0x5717), crate::MAX_STL_TRIANGLES, read); + survives("ASCII STL", &mutations(&ascii, true, 0x5718), crate::MAX_STL_TRIANGLES, read); } -/// A text file's lines dropped, repeated and swapped, and its numbers replaced by lies. -fn text_mutations(s: &str, rng: &mut Rng) -> Vec> { - let mut out = Vec::new(); - let lines: Vec<&str> = s.split_inclusive('\n').collect(); - let join = |v: &[&str]| v.concat().into_bytes(); - let picked: Vec = if lines.len() <= 200 { (0..lines.len()).collect() } else { (0..200).map(|_| rng.below(lines.len())).collect() }; - for &i in &picked { - let mut v = lines.clone(); - v.remove(i); - out.push(join(&v)); - let mut v = lines.clone(); - v.insert(i, lines[i]); - out.push(join(&v)); - if i + 1 < lines.len() { - let mut v = lines.clone(); - v.swap(i, i + 1); - out.push(join(&v)); - } - } - // A line in place of another (a block that inserts itself, a count where a coordinate was). - for _ in 0..200.min(lines.len() * lines.len()) { - let (i, j) = (rng.below(lines.len()), rng.below(lines.len())); - let mut v = lines.clone(); - v[i] = lines[j]; - out.push(join(&v)); - } - // A word in place of another of the file's own words: a renamed block, a swapped keyword, a - // block that now inserts itself. Every pair in a small file, a sample in a large one. - let words = word_spans(s); - let mut vocab: Vec<&str> = words.iter().map(|&(a, b)| &s[a..b]).collect(); - vocab.sort_unstable(); - vocab.dedup(); - let pairs = words.len().saturating_mul(vocab.len()); - let swap = |(a, b): (usize, usize), w: &str| format!("{}{w}{}", &s[..a], &s[b..]).into_bytes(); - if pairs <= 3000 { - for &span in &words { - for &w in vocab.iter().filter(|w| **w != &s[span.0..span.1]) { - out.push(swap(span, w)); - } - } - } else { - for _ in 0..400 { - out.push(swap(words[rng.below(words.len())], vocab[rng.below(vocab.len())])); - } - } - // Numbers: each of up to 200 of them, in turn, becomes one of the liars. - let numbers = number_spans(s); - let chosen: Vec<(usize, usize)> = if numbers.len() <= 200 { numbers } else { (0..200).map(|_| numbers[rng.below(numbers.len())]).collect() }; - for (k, (a, b)) in chosen.into_iter().enumerate() { - let liar = LIARS[k % LIARS.len()]; - out.push(format!("{}{liar}{}", &s[..a], &s[b..]).into_bytes()); - } - // Every number lying at once (two counts that are only harmless one at a time). - let all = number_spans(s); - for liar in LIARS { - let mut t = String::with_capacity(s.len()); - let mut at = 0; - for &(a, b) in &all { - t.push_str(&s[at..a]); - t.push_str(liar); - at = b; - } - t.push_str(&s[at..]); - out.push(t.into_bytes()); - } - out -} - -/// Byte spans of the words in `s` (runs of ASCII letters, digits and `_` that start with a -/// letter). -fn word_spans(s: &str) -> Vec<(usize, usize)> { - let b = s.as_bytes(); - let mut out = Vec::new(); - let mut i = 0; - while i < b.len() { - if !b[i].is_ascii_alphabetic() || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) { - i += 1; - continue; - } - let a = i; - while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { - i += 1; - } - out.push((a, i)); - } - out -} - -/// Byte spans of the decimal numbers in `s` (a sign, digits, a point, an exponent). -fn number_spans(s: &str) -> Vec<(usize, usize)> { - let b = s.as_bytes(); - let mut out = Vec::new(); - let mut i = 0; - while i < b.len() { - let starts = b[i].is_ascii_digit() || ((b[i] == b'-' || b[i] == b'.') && b.get(i + 1).is_some_and(u8::is_ascii_digit)); - let after_word = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); - if !starts || after_word { - i += 1; - continue; - } - let a = i; - i += 1; - while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || ((b[i] == b'e' || b[i] == b'E') && i + 1 < b.len())) { - if (b[i] == b'e' || b[i] == b'E') && (b[i + 1] == b'-' || b[i + 1] == b'+') { - i += 1; - } - i += 1; - } - out.push((a, i)); - } - out -} - -thread_local! { - /// Panics on this thread so far, caught or not ([`count_panics`]). - static PANICS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Count every panic per thread (tests run on several), then run the hook that was there. -fn count_panics() { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - let previous = std::panic::take_hook(); - std::panic::set_hook(Box::new(move |info| { - PANICS.with(|p| p.set(p.get() + 1)); - previous(info); - })); +#[test] +fn obj_survives_mutation() { + let good = crate::obj(&[("Cube".into(), cube())]).into_bytes(); + assert!(crate::read_obj(&good, "fuzz").is_ok()); + survives("OBJ", &mutations(&good, true, 0x0b1), usize::MAX, |b| { + crate::read_obj(b, "fuzz").ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) }); } -/// The time any one reader call may take on a mutated file (a debug build on a loaded machine: -/// generous, but far below what unbounded work on a lying count would take). -pub(crate) const BUDGET: Duration = Duration::from_secs(2); - -/// Run `read` over `inputs`: no panic, within [`BUDGET`], and `read`'s count (triangles, -/// entities, …) at most `cap`. `read` returns `None` for an error. Panics (the test fails) naming -/// the first case that breaks a rule. -pub(crate) fn survives(what: &str, inputs: &[Vec], cap: usize, mut read: impl FnMut(&[u8]) -> Option) { - count_panics(); - let mut slowest = (Duration::ZERO, 0); - let mut read_ok = 0; - for (i, input) in inputs.iter().enumerate() { - let before = PANICS.with(std::cell::Cell::get); - let t = Instant::now(); - let r = catch_unwind(AssertUnwindSafe(|| read(input))); - let took = t.elapsed(); - let head = String::from_utf8_lossy(&input[..input.len().min(120)]).into_owned(); - let Ok(r) = r else { panic!("{what}: case {i} ({} bytes) panicked; it starts {head:?}", input.len()) }; - let caught = PANICS.with(std::cell::Cell::get) - before; - assert!( - caught == 0, - "{what}: case {i} ({} bytes) panicked inside the reader (caught there, but the browser aborts); it starts {head:?}", - input.len() - ); - assert!(took <= BUDGET, "{what}: case {i} ({} bytes) took {took:?} (budget {BUDGET:?}); it starts {head:?}", input.len()); - if let Some(count) = r { - assert!(count <= cap, "{what}: case {i} gave {count} (cap {cap})"); - read_ok += 1; - } - slowest = slowest.max((took, i)); - } - eprintln!("{what}: {} mutations, {read_ok} read, slowest case {} in {:?}", inputs.len(), slowest.1, slowest.0); -} - -#[cfg(test)] -mod tests { - use super::*; - use solidcraft_geom::{Mesh, Vec2, Vec3}; - - fn cube() -> Mesh { - let positions = (0..8).map(|i| Vec3::new(f64::from(i & 1) * 10.0, f64::from((i >> 1) & 1) * 10.0, f64::from((i >> 2) & 1) * 10.0)).collect(); - let t = [[0, 2, 1], [1, 2, 3], [4, 5, 6], [5, 7, 6], [0, 1, 4], [1, 5, 4], [2, 6, 3], [3, 6, 7], [0, 4, 2], [2, 4, 6], [1, 3, 5], [3, 7, 5]]; - Mesh { positions, triangles: t.to_vec(), ..Default::default() } - } - - #[test] - fn mutations_are_deterministic_and_cover_the_file() { - let good = b"solid x\n facet normal 0 0 1\n vertex 1.5 -2 3e2\n endfacet\nendsolid x\n"; - let a = mutations(good, true, 7); - assert_eq!(a, mutations(good, true, 7), "the same seed gives the same cases"); - assert_ne!(a, mutations(good, true, 8)); - assert!(a.iter().any(Vec::is_empty) && a.iter().any(|m| m.len() == good.len() - 1), "truncations down to nothing"); - assert!(a.iter().any(|m| m.windows(3).any(|w| w == b"nan")), "a number replaced by a liar"); - assert_eq!(number_spans("v 1.5 -2 3e2 x1 .5e-3"), vec![(2, 5), (6, 8), (9, 12), (16, 21)]); - // A long file: bounded truncations, kept to the first and last bytes and spaced between. - let long = vec![b'a'; 100_000]; - let m = mutations(&long, false, 1); - assert!(m.len() < 3000, "{} cases", m.len()); - } - - #[test] - fn stl_survives_mutation() { - let mesh = cube(); - let binary = crate::stl_binary(std::slice::from_ref(&mesh), "fuzz"); - let ascii = crate::stl_ascii(std::slice::from_ref(&mesh), "fuzz").into_bytes(); - assert_eq!(crate::read_stl(&binary).map(|t| t.len()).ok(), Some(12)); - assert_eq!(crate::read_stl(&ascii).map(|t| t.len()).ok(), Some(12)); - let read = |b: &[u8]| crate::read_stl(b).ok().map(|t| t.len()); - survives("binary STL", &mutations(&binary, false, 0x5717), crate::MAX_STL_TRIANGLES, read); - survives("ASCII STL", &mutations(&ascii, true, 0x5718), crate::MAX_STL_TRIANGLES, read); - } - - #[test] - fn obj_survives_mutation() { - let good = crate::obj(&[("Cube".into(), cube())]).into_bytes(); - assert!(crate::read_obj(&good, "fuzz").is_ok()); - survives("OBJ", &mutations(&good, true, 0x0b1), usize::MAX, |b| { - crate::read_obj(b, "fuzz").ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - } - - #[test] - fn svg_survives_mutation() { - let good = br##" +#[test] +fn svg_survives_mutation() { + let good = br##" @@ -328,266 +45,265 @@ mod tests { "##; - assert!(crate::read_svg(std::str::from_utf8(good).unwrap()).is_ok()); - survives("SVG", &mutations(good, true, 0x5f6), usize::MAX, |b| crate::read_svg(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); - } + assert!(crate::read_svg(std::str::from_utf8(good).unwrap()).is_ok()); + survives("SVG", &mutations(good, true, 0x5f6), usize::MAX, |b| crate::read_svg(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); +} - #[test] - fn dxf_survives_mutation() { - let geom = [ - crate::Geom2::Line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), - crate::Geom2::Circle(Vec2::new(5.0, 5.0), 2.5), - crate::Geom2::Arc { c: Vec2::new(0.0, 0.0), a: Vec2::new(3.0, 0.0), b: Vec2::new(0.0, 3.0) }, - crate::Geom2::Point(Vec2::new(1.0, 1.0)), - ]; - let written = crate::write_dxf(&geom).into_bytes(); - assert!(crate::read_dxf(std::str::from_utf8(&written).unwrap()).is_ok_and(|g| g.len() >= 3)); - survives("DXF (written)", &mutations(&written, true, 0xdf), usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - // Blocks inside blocks, an array insert and a bulged polyline: what the block recursion, - // the array cells and the work budget guard. - let pairs: &[(&str, &str)] = &[ - ("0", "SECTION"), - ("2", "BLOCKS"), - ("0", "BLOCK"), - ("2", "inner"), - ("10", "0"), - ("20", "0"), - ("0", "LINE"), - ("10", "0"), - ("20", "0"), - ("11", "1"), - ("21", "1"), - ("0", "ENDBLK"), - ("0", "BLOCK"), - ("2", "outer"), - ("10", "0"), - ("20", "0"), - ("0", "INSERT"), - ("2", "inner"), - ("10", "2"), - ("20", "2"), - ("0", "CIRCLE"), - ("10", "0"), - ("20", "0"), - ("40", "1"), - ("0", "ENDBLK"), - ("0", "ENDSEC"), - ("0", "SECTION"), - ("2", "ENTITIES"), - ("0", "INSERT"), - ("2", "outer"), - ("10", "5"), - ("20", "5"), - ("41", "2"), - ("42", "2"), - ("50", "30"), - ("70", "3"), - ("71", "2"), - ("44", "10"), - ("45", "10"), - ("0", "LWPOLYLINE"), - ("90", "3"), - ("70", "1"), - ("10", "0"), - ("20", "0"), - ("42", "0.5"), - ("10", "5"), - ("20", "0"), - ("10", "5"), - ("20", "5"), - ("0", "ENDSEC"), - ("0", "EOF"), - ]; - let blocks: String = pairs - .iter() - .map(|(c, v)| { - format!( - "{c} +#[test] +fn dxf_survives_mutation() { + let geom = [ + crate::Geom2::Line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), + crate::Geom2::Circle(Vec2::new(5.0, 5.0), 2.5), + crate::Geom2::Arc { c: Vec2::new(0.0, 0.0), a: Vec2::new(3.0, 0.0), b: Vec2::new(0.0, 3.0) }, + crate::Geom2::Point(Vec2::new(1.0, 1.0)), + ]; + let written = crate::write_dxf(&geom).into_bytes(); + assert!(crate::read_dxf(std::str::from_utf8(&written).unwrap()).is_ok_and(|g| g.len() >= 3)); + survives("DXF (written)", &mutations(&written, true, 0xdf), usize::MAX, |b| crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); + // Blocks inside blocks, an array insert and a bulged polyline: what the block recursion, + // the array cells and the work budget guard. + let pairs: &[(&str, &str)] = &[ + ("0", "SECTION"), + ("2", "BLOCKS"), + ("0", "BLOCK"), + ("2", "inner"), + ("10", "0"), + ("20", "0"), + ("0", "LINE"), + ("10", "0"), + ("20", "0"), + ("11", "1"), + ("21", "1"), + ("0", "ENDBLK"), + ("0", "BLOCK"), + ("2", "outer"), + ("10", "0"), + ("20", "0"), + ("0", "INSERT"), + ("2", "inner"), + ("10", "2"), + ("20", "2"), + ("0", "CIRCLE"), + ("10", "0"), + ("20", "0"), + ("40", "1"), + ("0", "ENDBLK"), + ("0", "ENDSEC"), + ("0", "SECTION"), + ("2", "ENTITIES"), + ("0", "INSERT"), + ("2", "outer"), + ("10", "5"), + ("20", "5"), + ("41", "2"), + ("42", "2"), + ("50", "30"), + ("70", "3"), + ("71", "2"), + ("44", "10"), + ("45", "10"), + ("0", "LWPOLYLINE"), + ("90", "3"), + ("70", "1"), + ("10", "0"), + ("20", "0"), + ("42", "0.5"), + ("10", "5"), + ("20", "0"), + ("10", "5"), + ("20", "5"), + ("0", "ENDSEC"), + ("0", "EOF"), + ]; + let blocks: String = pairs + .iter() + .map(|(c, v)| { + format!( + "{c} {v} " - ) - }) - .collect(); - let n = crate::read_dxf(&blocks).map(|g| g.len()).unwrap_or(0); - assert!(n >= 12, "the array insert expands its nested blocks: {n} entities"); - survives("DXF (blocks)", &mutations(blocks.as_bytes(), true, 0xdb), usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - // The two lies that need each other, written out: a block that inserts itself (the - // depth limit), and an array of 10,000 by 10,000 copies (the cell and work budgets). - let looped = blocks.replacen( - "2 + ) + }) + .collect(); + let n = crate::read_dxf(&blocks).map(|g| g.len()).unwrap_or(0); + assert!(n >= 12, "the array insert expands its nested blocks: {n} entities"); + survives("DXF (blocks)", &mutations(blocks.as_bytes(), true, 0xdb), usize::MAX, |b| { + crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) + }); + // The two lies that need each other, written out: a block that inserts itself (the + // depth limit), and an array of 10,000 by 10,000 copies (the cell and work budgets). + let looped = blocks.replacen( + "2 inner 10 2", - "2 + "2 outer 10 2", - 1, - ); - assert_ne!(looped, blocks, "the outer block now inserts itself"); - let huge = blocks.replacen( - "70 + 1, + ); + assert_ne!(looped, blocks, "the outer block now inserts itself"); + let huge = blocks.replacen( + "70 3 71 2", - "70 + "70 10000 71 10000", - 1, - ); - assert_ne!(huge, blocks); - survives("DXF (self-insert, huge array)", &[looped.into_bytes(), huge.into_bytes()], usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - } + 1, + ); + assert_ne!(huge, blocks); + survives("DXF (self-insert, huge array)", &[looped.into_bytes(), huge.into_bytes()], usize::MAX, |b| { + crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) + }); +} - #[test] - fn threemf_survives_mutation() { - let mesh = cube(); - let object = crate::MeshObject { - name: "Cube".into(), - positions: mesh.positions, - triangles: mesh.triangles, - color: Some([0.8, 0.2, 0.1]), - ..Default::default() - }; - let good = crate::write_3mf(&[object]).unwrap(); - assert!(crate::read_3mf(&good).is_ok()); - survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| { +#[test] +fn threemf_survives_mutation() { + let mesh = cube(); + let object = crate::MeshObject { + name: "Cube".into(), + positions: mesh.positions, + triangles: mesh.triangles, + color: Some([0.8, 0.2, 0.1]), + ..Default::default() + }; + let good = crate::write_3mf(&[object]).unwrap(); + assert!(crate::read_3mf(&good).is_ok()); + survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| { + crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) + }); + // Objects in another model part (production extension), as slicers save projects. + let production = crate::threemf::tests::production_package(); + assert!(crate::read_3mf(&production).is_ok()); + survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| { + crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) + }); + // Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its + // checksums, these reach the `p:path` and `objectid` handling. + let parts = crate::threemf::tests::production_parts(); + for (k, (name, xml)) in parts.iter().enumerate() { + let rezipped: Vec> = mutations(xml.as_bytes(), true, 0x2089 + k as u64) + .iter() + .map(|m| { + let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect(); + crate::threemf::tests::package_bytes(&entries) + }) + .collect(); + survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| { crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) }); - // Objects in another model part (production extension), as slicers save projects. - let production = crate::threemf::tests::production_package(); - assert!(crate::read_3mf(&production).is_ok()); - survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| { - crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - // Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its - // checksums, these reach the `p:path` and `objectid` handling. - let parts = crate::threemf::tests::production_parts(); - for (k, (name, xml)) in parts.iter().enumerate() { - let rezipped: Vec> = mutations(xml.as_bytes(), true, 0x2089 + k as u64) - .iter() - .map(|m| { - let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect(); - crate::threemf::tests::package_bytes(&entries) - }) - .collect(); - survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| { - crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - } - } - - #[test] - fn gltf_survives_mutation() { - let mut f = crate::gltf_in::tests::Fixture::default(); - let m = f.cube_mesh("Cube", 0.01); - let child = f.node(serde_json::json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]})); - let n = f.node(serde_json::json!({"mesh": m, "children": [child], "rotation": [0.0, 0.0, std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2]})); - f.roots = vec![n]; - let mut no_files = |name: &str| -> std::result::Result, String> { Err(format!("no file `{name}`")) }; - let glb = f.glb(); - assert!(crate::read_gltf(&glb, "fuzz.glb", &mut no_files).is_ok()); - survives("glTF (.glb)", &mutations(&glb, false, 0x91b), usize::MAX, |b| crate::read_gltf(b, "fuzz.glb", &mut no_files).ok().map(|_| 1)); - // The JSON form, its buffer embedded as a data URI. - let uri = format!("data:application/octet-stream;base64,{}", base64(&f.bin)); - let gltf = f.json(Some(&uri)).to_string().into_bytes(); - assert!(crate::read_gltf(&gltf, "fuzz.gltf", &mut no_files).is_ok()); - survives("glTF (.gltf)", &mutations(&gltf, true, 0x917), usize::MAX, |b| crate::read_gltf(b, "fuzz.gltf", &mut no_files).ok().map(|_| 1)); - } - - #[test] - fn designs_survive_mutation() { - let mut doc = solidcraft_doc::Document::new("Fuzz"); - doc.set_param("width", "40", Some("mm"), None).unwrap(); - let mesh = solidcraft_doc::MeshData { - name: "Preview".into(), - positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(), - triangles: vec![0, 1, 2].into(), - color: None, - }; - let preview = crate::DesignPreview { meshes: vec![mesh] }; - let container = crate::write_design_container_with_preview(&doc, crate::DesignCompression::Fast, Some(&preview)).unwrap(); - assert!(crate::read_design(&container).is_ok() && crate::read_design_preview(&container).is_some()); - survives("design container", &mutations(&container, false, 0xde5), usize::MAX, |b| { - let _ = crate::read_design_preview(b); - let _ = crate::read_design_thumbnail(b); - crate::read_design(b).ok().map(|d| d.features.len()) - }); - let json = crate::write_design(&doc); - assert!(crate::read_design(&json).is_ok()); - survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len())); - } - - /// A drawing, as a container and as plain JSON: every mutation gives an error or a drawing, - /// never a panic, and `file_kind` always answers. - #[test] - fn drawings_survive_mutation() { - use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; - let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a); - let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); - let mut drawing = solidcraft_doc::drawing::Drawing::new("Fuzz", "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap(); - let id = drawing.allocate_id(&mut ids).unwrap(); - drawing.sources.push(solidcraft_doc::drawing::Source { id, path: "plate.sc".into() }); - let container = crate::write_drawing_container(&drawing).unwrap(); - assert!(crate::read_drawing(&container).is_ok()); - survives("drawing container", &mutations(&container, false, 0xd4b), usize::MAX, |b| { - let _ = crate::file_kind(b); - let _ = crate::read_design(b); - crate::read_drawing(b).ok().map(|d| d.sheets.len()) - }); - let json = drawing.to_json().unwrap().into_bytes(); - assert!(crate::read_drawing(&json).is_ok()); - survives("drawing JSON", &mutations(&json, true, 0xd4c), usize::MAX, |b| { - let _ = crate::file_kind(b); - crate::read_drawing(b).ok().map(|d| d.sheets.len()) - }); - } - - /// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document, - /// never a panic. - #[test] - fn paper_scenes_survive_mutation_into_svg() { - use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene}; - use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; - let p = Vec2::new; - let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); - let items = vec![ - Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7 }, - Item::Stroke { path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], closed: false, width_mm: 0.35 }, - Item::Fill { region: Region2 { outer: border, holes: vec![] } }, - ]; - let scene = Scene { size_mm: p(420.0, 297.0), groups: vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }] }; - let json = serde_json::to_vec(&scene).unwrap(); - let write = |b: &[u8]| -> Option { - let scene: Scene = serde_json::from_slice(b).ok()?; - let prepared = scene.prepare().ok()?; - crate::paper::paper_svg(&prepared).ok().map(|(bytes, _)| bytes.len()) - }; - assert!(write(&json).is_some()); - survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write); - } - - /// Standard base64 (RFC 4648) of `bytes`, for a data URI. - fn base64(bytes: &[u8]) -> String { - const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut s = String::new(); - for c in bytes.chunks(3) { - let v = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); - for k in 0..4 { - if k <= c.len() { - s.push(char::from(A[(v >> (18 - 6 * k)) as usize & 63])); - } else { - s.push('='); - } - } - } - s } } + +#[test] +fn gltf_survives_mutation() { + let mut f = crate::gltf_in::tests::Fixture::default(); + let m = f.cube_mesh("Cube", 0.01); + let child = f.node(serde_json::json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]})); + let n = f.node( + serde_json::json!({"mesh": m, "children": [child], "rotation": [0.0, 0.0, std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2]}), + ); + f.roots = vec![n]; + let mut no_files = |name: &str| -> std::result::Result, String> { Err(format!("no file `{name}`")) }; + let glb = f.glb(); + assert!(crate::read_gltf(&glb, "fuzz.glb", &mut no_files).is_ok()); + survives("glTF (.glb)", &mutations(&glb, false, 0x91b), usize::MAX, |b| crate::read_gltf(b, "fuzz.glb", &mut no_files).ok().map(|_| 1)); + // The JSON form, its buffer embedded as a data URI. + let uri = format!("data:application/octet-stream;base64,{}", base64(&f.bin)); + let gltf = f.json(Some(&uri)).to_string().into_bytes(); + assert!(crate::read_gltf(&gltf, "fuzz.gltf", &mut no_files).is_ok()); + survives("glTF (.gltf)", &mutations(&gltf, true, 0x917), usize::MAX, |b| crate::read_gltf(b, "fuzz.gltf", &mut no_files).ok().map(|_| 1)); +} + +#[test] +fn designs_survive_mutation() { + let mut doc = solidcraft_doc::Document::new("Fuzz"); + doc.set_param("width", "40", Some("mm"), None).unwrap(); + let mesh = solidcraft_doc::MeshData { + name: "Preview".into(), + positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(), + triangles: vec![0, 1, 2].into(), + color: None, + }; + let preview = crate::DesignPreview { meshes: vec![mesh] }; + let container = crate::write_design_container_with_preview(&doc, crate::DesignCompression::Fast, Some(&preview)).unwrap(); + assert!(crate::read_design(&container).is_ok() && crate::read_design_preview(&container).is_some()); + survives("design container", &mutations(&container, false, 0xde5), usize::MAX, |b| { + let _ = crate::read_design_preview(b); + let _ = crate::read_design_thumbnail(b); + crate::read_design(b).ok().map(|d| d.features.len()) + }); + let json = crate::write_design(&doc); + assert!(crate::read_design(&json).is_ok()); + survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len())); +} + +/// A drawing, as a container and as plain JSON: every mutation gives an error or a drawing, +/// never a panic, and `file_kind` always answers. +#[test] +fn drawings_survive_mutation() { + use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; + let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a); + let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); + let mut drawing = solidcraft_doc::drawing::Drawing::new("Fuzz", "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap(); + let id = drawing.allocate_id(&mut ids).unwrap(); + drawing.sources.push(solidcraft_doc::drawing::Source { id, path: "plate.sc".into() }); + let container = crate::write_drawing_container(&drawing).unwrap(); + assert!(crate::read_drawing(&container).is_ok()); + survives("drawing container", &mutations(&container, false, 0xd4b), usize::MAX, |b| { + let _ = crate::file_kind(b); + let _ = crate::read_design(b); + crate::read_drawing(b).ok().map(|d| d.sheets.len()) + }); + let json = drawing.to_json().unwrap().into_bytes(); + assert!(crate::read_drawing(&json).is_ok()); + survives("drawing JSON", &mutations(&json, true, 0xd4c), usize::MAX, |b| { + let _ = crate::file_kind(b); + crate::read_drawing(b).ok().map(|d| d.sheets.len()) + }); +} + +/// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document, +/// never a panic. +#[test] +fn paper_scenes_survive_mutation_into_svg() { + use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene}; + use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; + let p = Vec2::new; + let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); + let items = vec![ + Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7 }, + Item::Stroke { path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], closed: false, width_mm: 0.35 }, + Item::Fill { region: Region2 { outer: border, holes: vec![] } }, + ]; + let scene = Scene { size_mm: p(420.0, 297.0), groups: vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }] }; + let json = serde_json::to_vec(&scene).unwrap(); + let write = |b: &[u8]| -> Option { + let scene: Scene = serde_json::from_slice(b).ok()?; + let prepared = scene.prepare().ok()?; + crate::paper::paper_svg(&prepared).ok().map(|(bytes, _)| bytes.len()) + }; + assert!(write(&json).is_some()); + survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write); +} + +/// Standard base64 (RFC 4648) of `bytes`, for a data URI. +fn base64(bytes: &[u8]) -> String { + const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut s = String::new(); + for c in bytes.chunks(3) { + let v = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); + for k in 0..4 { + if k <= c.len() { + s.push(char::from(A[(v >> (18 - 6 * k)) as usize & 63])); + } else { + s.push('='); + } + } + } + s +} diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 057cca258..47c03f4da 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -15,3 +15,5 @@ serde_json = { workspace = true } [dev-dependencies] # The renderer `solidcraft-cli mcp` installs, so the tests' screenshots are drawn as the server's. solidcraft-gpu = { workspace = true } +# Synthetic reference pictures for the compare_picture test. +image = { workspace = true } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 23957f826..4a0e6cc0a 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -137,6 +137,7 @@ fn handshake_and_tools_list() { "set_parameter", "check_parameters", "screenshot", + "compare_picture", "export", "undo", "redo", @@ -1469,6 +1470,46 @@ fn legacy_design_files_and_resource_uris() { let _ = std::fs::remove_dir_all(&dir); } +/// `compare_picture` (#1486): the overlay comes back as an image block and the numbers as text. +#[test] +fn compare_picture_returns_the_overlay_as_an_image() { + use image::ImageEncoder as _; + use std::io::Cursor; + // A scoped server, like `solidcraft-cli mcp`: the reference must be inside the folders. + let base = solidcraft_engine::io::vfs::temp_dir().join(format!("solidcraft-mcp-compare-{}", std::process::id())); + let recovery = base.join("recovery"); + std::fs::create_dir_all(&recovery).unwrap(); + let scope = crate::agent_scope_with(Some(recovery.clone()), []); + let mut s = Server::new(Box::new(Headless::default())).with_path_scope(Some(scope)); + tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 20, "width": 10, "height": 30}})); + // A white rectangle on grey with the box's front-view proportions (20 x 30 mm). + let (w, h) = (200u32, 300u32); + let mut img = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 200, 200, 255])); + for y in 20..280 { + for x in 20..180 { + img.put_pixel(x, y, image::Rgba([255, 255, 255, 255])); + } + } + let mut png = Cursor::new(Vec::new()); + image::codecs::png::PngEncoder::new(&mut png).write_image(img.as_raw(), w, h, image::ExtendedColorType::Rgba8).unwrap(); + let path = recovery.join("target.png"); + std::fs::write(&path, png.into_inner()).unwrap(); + + let r = raw_tool(&mut s, "compare_picture", json!({"reference": path.to_string_lossy(), "view": "front"})); + assert_ne!(r["result"]["isError"], json!(true), "{r}"); + let content = r["result"]["content"].as_array().unwrap().clone(); + assert_eq!(content[0]["type"], "image", "{content:?}"); + assert_eq!(content[0]["mimeType"], "image/png"); + assert!(content[0]["data"].as_str().unwrap().starts_with("iVBORw0KGgo"), "not a PNG"); + let info: Value = serde_json::from_str(content[1]["text"].as_str().unwrap()).unwrap(); + assert!(info["overlap"].as_f64().unwrap() > 0.9, "{info}"); + assert!(info.get("overlay_png").is_none(), "the base64 blob belongs in the image block only"); + // A reference outside the server's folders is refused through the existing path rules. + let outside = raw_tool(&mut s, "compare_picture", json!({"reference": "/etc/hostname"})); + assert_eq!(outside["result"]["isError"], json!(true), "{outside}"); + let _ = std::fs::remove_dir_all(&base); +} + /// The default folders (#205): the recovery folder works out of the box, `screenshot` without a /// `path` uses the server's own scratch folder, and the open design's folder counts while the /// design is open there, without its hidden files. The working folder doesn't count at all. diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 4c8c57cba..10edfe085 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -147,7 +147,7 @@ pub fn tool_definitions() -> Vec { (as list_commands lists them). A step may also name one of these tools with that tool's arguments as params, \ and runs the engine command it stands for: set_parameter (parameters.change; `value` or `expression`), \ list_commands (engine.commands, with `filter`), describe_command (engine.describe), execute ({command, params}), \ - measure (inspect.measure), \ + measure (inspect.measure), compare_picture (inspect.compare_picture, numbers only: no overlay PNG), \ inspect_design (document.inspect), undo, redo, export, save, open, new_design, crash_reports; screenshot, \ body_topology, batch and pending can't be steps. On an error the steps already run are undone (unless \ rollback: false), so the batch is all-or-nothing; the reply names the failing step (index from 0), its error, \ @@ -307,6 +307,34 @@ pub fn tool_definitions() -> Vec { ), Effect::Files, ), + tool( + "compare_picture", + "Compare with a reference picture", + "Compare the model's outline with the part in a reference picture — a concept render, a product photo, one view off a design board. \ + The model's outline is `inspect.silhouette` from `view` (default front), `camera` and `bodies`; the picture's part is found by growing \ + the background in from the border, so a backdrop's gradual shading stays background. The compare is outline only: holes are not \ + compared — both the picture's and the model's holes are filled. `reference` is a PNG or JPEG inside the server's \ + folders. `crop_px` / `crop_fraction` take one view off a board: [x, y, w, h] in pixels or as fractions 0..1 of the picture; \ + `part_fills_crop: true` says the crop box is the part itself, for a crop that tightly frames it. `fit` names \ + the dimension the scale comes from (\"width\", \"height\", \"both\"; default \"width\") — one uniform scale, never stretched per axis; \ + \"both\" scales by width and reports `aspect_mismatch` when the shapes differ. Returns as text the overlap (0..1) and the model's top, \ + bottom, left and right edges against the picture's in mm at nine stations (positive where the model reaches past the picture), and as \ + an image the overlay PNG: model red, picture blue.", + obj( + json!({ + "reference": string("PNG or JPEG to match, inside the server's folders"), + "view": string("Standard view (front, top, right, iso, ...) the picture is seen from (default front)"), + "camera": {"type": "object", "description": "Look from this camera instead: {target: [x,y,z], yaw, pitch, distance, fov?} (radians, mm; as view.apply). A photo taken in perspective gets an fov"}, + "bodies": {"type": "array", "items": {"type": "string"}, "description": "Body names to outline (default: the visible bodies)"}, + "crop_px": {"type": "array", "items": {"type": "number"}, "description": "[x, y, w, h] in pixels"}, + "crop_fraction": {"type": "array", "items": {"type": "number"}, "description": "[x, y, w, h] as fractions 0..1 of the picture"}, + "fit": {"type": "string", "enum": ["width", "height", "both"], "description": "The dimension the one uniform scale comes from (default width); both scales by width and reports aspect_mismatch"}, + "rows": {"type": "integer", "description": "The model outline's height in pixels (default 240)"}, + }), + &["reference"], + ), + Effect::Files, + ), tool( "export", "Export", @@ -497,6 +525,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value { let a = args.as_object().unwrap_or(&empty); let r = match name { "screenshot" => return screenshot(b, a), + "compare_picture" => return compare_picture(b, a), "batch" => return batch(b, a), "check_parameters" => return check_parameters(b, a), "execute" => return execute(b, a), @@ -992,6 +1021,14 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { Some(items) => mapped("inspect.measure", json!({"items": items})), None => Ok(("inspect.measure".into(), measure_params(a), measure_summary_wanted(a).then_some(Narrow::MeasureSummary))), }, + "compare_picture" => { + // A batch step gets the numbers; the overlay PNG would be a base64 blob in text. + let mut p = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]); + if let Some(obj) = p.as_object_mut() { + obj.entry("overlay".to_string()).or_insert(json!(false)); + } + mapped("inspect.compare_picture", p) + } "inspect_design" => mapped("document.inspect", json!({"measure": a.get("measure").and_then(Value::as_bool).unwrap_or(true)})), "undo" => mapped("edit.undo", json!({})), "redo" => mapped("edit.redo", json!({})), @@ -1020,6 +1057,7 @@ const TOOL_STEPS: &[&str] = &[ "batch", "body_topology", "check_parameters", + "compare_picture", "crash_reports", "describe_command", "execute", @@ -1777,6 +1815,28 @@ fn screenshot(b: &mut dyn Backend, a: &Map) -> Value { } } +/// `compare_picture`: run the engine comparison and hand the overlay PNG back as an MCP +/// image block, the numbers as text — an agent sees the picture, not a base64 blob. +fn compare_picture(b: &mut dyn Backend, a: &Map) -> Value { + let mut params = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]); + params["overlay"] = json!(true); + match exec(b, "inspect.compare_picture", params) { + Ok(v) => { + let overlay = v.get("overlay_png").and_then(Value::as_str).unwrap_or_default().to_string(); + let mut info = v; + if let Some(obj) = info.as_object_mut() { + obj.remove("overlay_png"); + } + let mut content = vec![json!({"type": "text", "text": info.to_string()})]; + if !overlay.is_empty() { + content.insert(0, json!({"type": "image", "data": overlay, "mimeType": "image/png"})); + } + json!({"content": content}) + } + Err(e) => text_result(&Value::String(e), true), + } +} + fn capture(b: &mut dyn Backend, a: &Map) -> Result<(Vec, Value), String> { // `grid` and `axes` shape a model render; the window shows what it shows. let guides: Vec<(&str, bool)> = ["grid", "axes"].into_iter().filter_map(|k| a.get(k).and_then(Value::as_bool).map(|v| (k, v))).collect(); diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 56a544cd9..68de22ec8 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,6 +19,7 @@ image = { workspace = true, features = ["jpeg"] } moxcms = { workspace = true } png = { workspace = true } sha2 = { workspace = true } +web-time = { workspace = true } weezl = { workspace = true } [dev-dependencies] diff --git a/crates/render/src/job/host.rs b/crates/render/src/job/host.rs index 8c06a153f..c8ee940df 100644 --- a/crates/render/src/job/host.rs +++ b/crates/render/src/job/host.rs @@ -362,6 +362,7 @@ pub struct JobStatus { } struct Data { + completed_duration: Option, punctual_diagnostics: Option, sampling: Option, progress: Progress, @@ -370,6 +371,7 @@ struct Data { preview: Option>, } struct Record { + started: web_time::Instant, presentation: Option>, textures: Option, options: JobOptions, @@ -399,6 +401,10 @@ impl JobHandle { pub fn id(&self) -> JobId { self.0.id } + /// Submission-to-publication time, captured once by the host, independent of UI polling. + pub fn completed_duration(&self) -> Result> { + self.0.data.lock().map(|data| data.completed_duration).map_err(|_| JobError::new(ErrorCode::Internal, "render duration lock poisoned")) + } pub fn status(&self) -> Result { let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; Ok(JobStatus { @@ -861,6 +867,7 @@ impl Running { })); data.preview = None; data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 }; + data.completed_duration = Some(self.handle.0.started.elapsed()); self.handle.0.notify(); Ok(false) } @@ -1318,6 +1325,7 @@ impl ImageHost { (request, None) }; let handle = JobHandle(Arc::new(Record { + started: web_time::Instant::now(), presentation: None, textures, options, @@ -1329,6 +1337,7 @@ impl ImageHost { resolved, cancel: CancelToken::default(), data: Mutex::new(Data { + completed_duration: None, punctual_diagnostics: None, sampling: None, progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, @@ -1435,6 +1444,7 @@ impl ImageHost { let metadata = self.0.shared.budget.reserve(metadata_bytes)?; let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata }); let handle = JobHandle(Arc::new(Record { + started: web_time::Instant::now(), presentation: Some(origin), textures: None, options, @@ -1446,6 +1456,7 @@ impl ImageHost { resolved, cancel: CancelToken::default(), data: Mutex::new(Data { + completed_duration: None, punctual_diagnostics: None, sampling: None, progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, diff --git a/crates/render/src/job/host_tests.rs b/crates/render/src/job/host_tests.rs index 62afa6298..e18a5cd6b 100644 --- a/crates/render/src/job/host_tests.rs +++ b/crates/render/src/job/host_tests.rs @@ -348,6 +348,25 @@ fn native_job_finishes_without_any_poll_or_ui_pump() { assert_eq!(frame.info.png_bytes, frame.png().len() as u64); assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); assert_eq!(status.frame.unwrap().png_sha256, frame.info.png_sha256); + let duration = job.completed_duration().unwrap().unwrap(); + assert_eq!(job.completed_duration().unwrap(), Some(duration), "completed duration is independent of status polling"); +} + +#[test] +fn completed_duration_is_captured_at_publication_and_never_for_cancelled_work() { + let host = CpuHost::cooperative(); + let job = host.submit(id(1, 1), 12, empty(), request()).unwrap(); + assert!(job.completed_duration().unwrap().is_none()); + drain(&host); + let duration = job.completed_duration().unwrap().unwrap(); + assert!(duration.as_secs_f64().is_finite()); + job.status().unwrap(); + host.pump(1).unwrap(); + assert_eq!(job.completed_duration().unwrap(), Some(duration)); + let cancelled = host.submit(id(1, 2), 12, empty(), request()).unwrap(); + cancelled.cancel().unwrap(); + drain(&host); + assert!(cancelled.completed_duration().unwrap().is_none()); } /// Isolate the existing integrator-to-host completion boundary with a real PNG diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index b09bb9c0d..55fbfc5b2 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -8,6 +8,8 @@ pub const MAX_POINTS: usize = 20_000; pub const MAX_CONSTRAINTS: usize = 40_000; /// Curves need points, so this follows the point cap. pub const MAX_CURVES: usize = MAX_POINTS; +// [`SketchError::TooLarge`]'s message names this number; keep them matched (#10874). +const _: () = assert!(MAX_POINTS == 20_000); /// Largest coordinate or dimension value (mm) a sketch accepts. pub const MAX_COORD: f64 = 1e9; @@ -37,7 +39,12 @@ pub enum SketchError { Duplicate(String), #[error("invalid value: {0}")] Invalid(String), - #[error("sketch is too large")] + /// Cap hit on points, curves or constraints ([`MAX_POINTS`], [`MAX_CURVES`], + /// [`MAX_CONSTRAINTS`]). Insert SVG/DXF of a dense drawing (a floorplan) often hits this; + /// scale alone does not reduce how many curves the file has (#10874). + #[error( + "sketch is too large (at most 20000 points or curves); simplify the drawing or split it across sketches — changing scale does not reduce how many curves it has" + )] TooLarge, } @@ -1703,7 +1710,7 @@ impl Sketch { /// Points held together only through points about to go stay together: two rectangles' /// corners made coincident with one arc end are tied to each other when a trim takes that /// end away, instead of coming apart where they still meet. - fn keep_ties_through(&mut self, gone: &[usize]) { + pub(crate) fn keep_ties_through(&mut self, gone: &[usize]) { if gone.is_empty() { return; } @@ -1740,7 +1747,7 @@ impl Sketch { } } - fn point_used_by_curve(&self, p: usize) -> bool { + pub(crate) fn point_used_by_curve(&self, p: usize) -> bool { self.curves.iter().any(|c| c.kind.uses(p)) } diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index 2148fa534..0ff232c17 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -611,6 +611,13 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec) { LineCircleDistance { l, c, value, inside } => out.push(s.line_circle_gap(l, c, inside) - value), PointCircleDistance { p, c, value, inside } => out.push(s.point_circle_gap(p, c, inside) - value), CircleCircleDistance { a, b, value, circles } => out.push(s.circle_circle_gap(a, b, circles) - value), + // A length within convergence tolerance of zero means the line's two ends meet: + // the component rows keep both directions constrained even when they do, the way a + // coincidence does (the same treatment a distance of zero gets above). + Length { l, value } if value.abs() <= TOL => { + let (a, b) = s.line(l); + out.extend([b.x - a.x, b.y - a.y]); + } Length { l, value } => { let (a, b) = s.line(l); out.push(a.dist(b) - value); diff --git a/crates/sketch/src/spline_points.rs b/crates/sketch/src/spline_points.rs index a2ab1308e..bd8e28e67 100644 --- a/crates/sketch/src/spline_points.rs +++ b/crates/sketch/src/spline_points.rs @@ -1,6 +1,6 @@ //! New points on an existing fit spline (#6533): a fit point inserted where the curve already -//! runs, or a new first or last point the spline runs on to. Also a spline's direction reversed -//! (#8224). +//! runs, or a new first or last point the spline runs on to. One point taken out of a spline +//! (#10783). Also a spline's direction reversed (#8224). //! //! The spline keeps its curve index and every point it had (the new point is appended to //! `Sketch::points`), so constraints on its points and on the curve stay as they were. @@ -87,6 +87,77 @@ impl Sketch { Ok(p) } + /// Take point `p` out of spline `ci` (#10783), and return whether the point itself went too. + /// The spline runs through (or over) its other points, and keeps its curve index, so + /// constraints on the curve and on its other points stay. The point goes with the constraints + /// on it, unless another curve uses it (it stays, for that curve) or it is the origin. + /// + /// The spline keeps at least 2 points (a closed one 3 besides its closing point, which stays). + /// An end of an open spline joined to other geometry stays, as for [`Sketch::extend_spline`]: + /// the spline would no longer end where it is joined. + pub fn remove_spline_point(&mut self, ci: usize, p: usize) -> Result { + let curve = self.curves.get(ci).ok_or_else(|| SketchError::Unknown(format!("curve {ci}")))?; + let CurveKind::Spline { pts, periodic, .. } = &curve.kind else { + return Err(SketchError::WrongKind(curve.id.clone(), "only a spline has points to remove".into())); + }; + let (pts, periodic) = (pts.clone(), *periodic); + if curve.link.is_some() { + return Err(SketchError::Invalid("a projected spline follows its source; its points can't be removed".into())); + } + if self.freeform_offsets.iter().any(|o| o.output == curve.id) { + return Err(SketchError::Invalid("an offset spline follows its source; break the offset association first".into())); + } + if self.freeform_offsets.iter().any(|o| o.source == curve.id) { + return Err(SketchError::Invalid( + "not supported yet: removing a point from a spline that has an offset; break the offset association first".into(), + )); + } + if self.patterns.iter().any(|pattern| pattern.contains(&curve.id)) { + return Err(SketchError::Invalid("not supported yet: removing a point from a patterned spline".into())); + } + let at = match pts.iter().enumerate().filter(|(_, q)| **q == p).map(|(i, _)| i).collect::>().as_slice() { + [] => return Err(SketchError::Invalid(format!("that point isn't one of {}'s points", curve.id))), + [at] => *at, + _ => return Err(SketchError::Invalid("that point closes the spline; remove another one".into())), + }; + let last = pts.len().saturating_sub(1); + if periodic && (at == 0 || at == last) { + return Err(SketchError::Invalid("a closed spline's closing point stays; remove another one".into())); + } + if pts.len() < if periodic { 5 } else { 3 } { + return Err(SketchError::Invalid(format!("a spline keeps at least {} points", if periodic { 3 } else { 2 }))); + } + if !periodic && (at == 0 || at == last) { + let joined = self.curves.iter().enumerate().any(|(i, c)| i != ci && c.kind.uses(p)) + || self.constraints.iter().any(|k| { + let (points, curves) = k.kind.indices(); + points.contains(&p) || (curves.contains(&ci) && matches!(k.kind, ConstraintKind::Tangent { .. } | ConstraintKind::Smooth { .. })) + }); + if joined { + return Err(SketchError::Invalid( + "that end of the spline is joined to other geometry or held by a constraint; remove those first".into(), + )); + } + } + let mut left = pts; + left.remove(at); + if periodic { + let pos: Vec = + left.iter().map(|i| self.point(*i).ok_or_else(|| SketchError::Unknown(format!("point {i}")))).collect::>()?; + crate::periodic::validate_periodic_points(&pos)?; + } + if let Some(CurveKind::Spline { pts, .. }) = self.curves.get_mut(ci).map(|c| &mut c.kind) { + *pts = left; + } + // The origin (point 0) is never removed. + if p == 0 || self.point_used_by_curve(p) { + return Ok(false); + } + self.keep_ties_through(&[p]); + self.remove_points(&[p]); + Ok(true) + } + /// Reverse spline `ci`'s direction: its last point becomes its first and the curve runs the /// other way along the same path. Its points are reversed in place, so every point, and every /// constraint on them and on the curve, stays. The shape doesn't change: a fit spline's chord diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index ff7b98f06..6e2806db0 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -210,6 +210,27 @@ fn zero_distance_edits_preserve_dimension_rank() { } } +/// A length dimension of zero still constrains the sketch: the two ends of the line meet, and +/// the dimension holds them together instead of leaving a degree of freedom behind (#5505). +#[test] +fn zero_length_keeps_the_line_constrained() { + for seed in [false, true] { + seeded(seed, || { + let mut sk = Sketch::new(); + let a = sk.add_point(v(0.0, 0.0), None).unwrap(); + let b = sk.add_point(v(10.0, 0.0), None).unwrap(); + let l = sk.add_line_pts(a, b, None).unwrap(); + sk.add_constraint(ConstraintKind::Fix { p: a }, None).unwrap(); + let id = sk.add_constraint(ConstraintKind::Length { l, value: 0.0 }, None).unwrap(); + let report = solve(&mut sk); + assert!(report.ok(), "{report:?}"); + assert_eq!(report.dof, 0, "a zero length holds the line's ends together: {report:?}"); + assert!(!report.redundant.contains(&id), "a zero length is not redundant: {report:?}"); + assert!(sk.point(b).unwrap().dist(v(0.0, 0.0)) < 1e-6, "{:?}", sk.point(b)); + }); + } +} + #[test] fn under_constrained_reports_dof() { let mut sk = Sketch::new(); @@ -1199,6 +1220,88 @@ fn a_spline_extends_to_a_new_end_unless_the_end_is_joined() { assert!(sk.extend_spline(s, v(-10.0, 5.0), true).is_err(), "already a point there"); } +/// Where spline `s`'s points are, in order. +fn spline_places(sk: &Sketch, s: usize) -> Vec { + let CurveKind::Spline { pts, .. } = &sk.curves[s].kind else { panic!("{s} is no spline") }; + pts.iter().map(|i| sk.point(*i).unwrap()).collect() +} + +/// #10783: a spline gives up one of its points. The curve runs through the others, in order, and +/// the point goes with the constraints on it; a point a line also ends at stays, for the line. +#[test] +fn a_point_removed_from_a_spline_goes_and_the_curve_keeps_the_others() { + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, false); + let mut others = spline_places(&sk, s); + let gone = others.remove(2); + // A free point held on the one that goes: the constraint goes, the free point stays. + let free = sk.add_point(gone, None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: pts[2], q: free }, None).unwrap(); + let count = sk.points.len(); + assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true)); + assert_eq!(spline_places(&sk, s), others); + for q in &others { + assert!(off_curve(&sk, s, *q) < 1e-9, "the curve still runs through {q:?}"); + } + assert!(matches!(sk.curves[s].kind, CurveKind::Spline { control: false, periodic: false, .. })); + assert_eq!(sk.points.len(), count - 1, "the point went"); + assert!(sk.constraints.is_empty(), "the constraint on it went: {:?}", sk.constraints); + // A free end goes too: the spline starts at the next point. + let start = sk.curves[s].kind.ends().unwrap().0; + assert_eq!(sk.remove_spline_point(s, start), Ok(true)); + others.remove(0); + assert_eq!(spline_places(&sk, s), others); + // An inner point a line also ends at stays, for the line. + let CurveKind::Spline { pts: now, .. } = sk.curves[s].kind.clone() else { panic!() }; + let line = sk.add_line(others[1], v(40.0, 30.0), Some(now[1]), None, None).unwrap(); + assert_eq!(sk.remove_spline_point(s, now[1]), Ok(false)); + assert!(sk.curves[line].kind.uses(now[1]) && !sk.curves[s].kind.uses(now[1])); + others.remove(1); + assert_eq!(spline_places(&sk, s), others); + // Two points are as few as a spline keeps. + assert_eq!(others.len(), 2); + let before = sk.clone(); + assert!(sk.remove_spline_point(s, sk.curves[s].kind.ends().unwrap().1).is_err()); + assert_eq!(sk, before, "a refused removal changes nothing"); +} + +/// #10783: what a spline keeps: an end joined to a line or held by a constraint, a closed +/// spline's closing point and its last three points. A control point spline gives up a point as a +/// fit point spline does. +#[test] +fn a_spline_keeps_its_joined_ends_and_closing_point() { + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, false); + let line = sk.add_line(sk.point(pts[4]).unwrap(), v(60.0, 0.0), Some(pts[4]), None, None).unwrap(); + let tied = sk.add_point(sk.point(pts[0]).unwrap(), None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: pts[0], q: tied }, None).unwrap(); + let before = sk.clone(); + assert!(sk.remove_spline_point(s, pts[4]).is_err(), "a line ends there"); + assert!(sk.remove_spline_point(s, pts[0]).is_err(), "a constraint holds the start"); + assert!(sk.remove_spline_point(s, tied).is_err(), "not one of the spline's points"); + assert!(sk.remove_spline_point(line, pts[4]).is_err(), "a line has no spline points"); + assert_eq!(sk, before, "a refused removal changes nothing"); + + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, true); + assert!(sk.remove_spline_point(s, pts[0]).is_err(), "the closing point"); + assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true)); + assert_eq!(sk.remove_spline_point(s, pts[1]), Ok(true)); + let CurveKind::Spline { pts: now, periodic, .. } = sk.curves[s].kind.clone() else { panic!() }; + assert!(periodic); + assert_eq!(now.len(), 4, "three points and the closing one: {now:?}"); + assert!(sk.remove_spline_point(s, now[1]).is_err(), "a closed spline keeps three points"); + sk.validate_periodic_splines().unwrap(); + + let mut sk = Sketch::new(); + let places = [v(0.0, 0.0), v(10.0, 10.0), v(20.0, -10.0), v(30.0, 0.0)]; + let cv: Vec = places.iter().map(|q| sk.add_point(*q, None).unwrap()).collect(); + let c = sk.add_curve(CurveKind::Spline { pts: cv.clone(), control: true, degree: 3, periodic: false, nurbs: None }, None).unwrap(); + assert_eq!(sk.remove_spline_point(c, cv[1]), Ok(true)); + assert!(matches!(sk.curves[c].kind, CurveKind::Spline { control: true, .. })); + assert_eq!(spline_places(&sk, c), vec![places[0], places[2], places[3]]); +} + /// #755: a line drawn through a junction of a loop, but 2e-5 off it, still splits the loop. The /// junction lies on the loop's two curves only, so it cuts neither of them where the line /// crosses, and that crossing, next to the junction, was taken for one already cut there: the diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml new file mode 100644 index 000000000..118c436d2 --- /dev/null +++ b/crates/testkit/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "solidcraft-testkit" +description = "SolidCraft test tooling: deterministic mutations of valid files and the no-panic check run over them (a dev-dependency only)" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs new file mode 100644 index 000000000..60ba9eccc --- /dev/null +++ b/crates/testkit/src/lib.rs @@ -0,0 +1,294 @@ +//! Deterministic mutations of valid files, and the readers run over them (#469). Every reader of +//! bytes the user didn't write gets the same treatment: truncation, flipped and overwritten +//! bytes, dropped and repeated runs, appended garbage and, for text formats, dropped and +//! repeated lines and numbers that lie (`nan`, `inf`, `1e400`, …). Each mutated file must give an +//! error or a result, never a panic, within a time budget and the reader's own caps. A panic a +//! reader catches itself (`solidcraft_kernel::guard`) counts too: the browser build aborts on any +//! panic, so a caught one on the desktop is a crash there. +//! +//! The mutations come from a fixed seed (xorshift), so a failure names a case that reproduces. +//! No fuzzing dependency, nothing nightly, nothing native: it runs in the normal test suite and +//! builds for wasm. The readers' own hand-written cases stay; they cover particular lies (a +//! length in a container header) that random changes rarely hit. STEP, IGES and FreeCAD/Rhino +//! files are read by the kernel, which is moving to solidcore (#1597), and keep their own tests. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::time::{Duration, Instant}; + +/// A deterministic xorshift64 stream. +struct Rng(u64); + +impl Rng { + fn new(seed: u64) -> Rng { + Rng(seed | 1) + } + + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + /// A value in `0..n` (0 when `n` is 0). + fn below(&mut self, n: usize) -> usize { + if n == 0 { 0 } else { (self.next() % n as u64) as usize } + } +} + +/// Numbers a hostile file might hold in place of a real one. +const LIARS: [&str; 10] = ["nan", "inf", "-inf", "1e400", "-1e400", "-0", "4294967296", "-1", "99999999999999999999", "0x7fffffff"]; + +/// Most truncations of one file (every length up to this, evenly spaced beyond). +const MAX_TRUNCATIONS: usize = 1024; + +/// Mutations of `good`, the same for the same `good` and `seed`. `text`: also line and number +/// mutations (the file is UTF-8 text). +pub fn mutations(good: &[u8], text: bool, seed: u64) -> Vec> { + let mut out: Vec> = Vec::new(); + let n = good.len(); + let mut rng = Rng::new(seed); + // Truncations: every length of a short file; of a long one, its first and last 64 lengths + // (headers, final records) and evenly spaced ones between. + if n <= MAX_TRUNCATIONS { + out.extend((0..n).map(|k| good[..k].to_vec())); + } else { + let mut cuts: Vec = (0..64).chain(n - 64..n).collect(); + cuts.extend((0..MAX_TRUNCATIONS - 128).map(|i| 64 + i * (n - 128) / (MAX_TRUNCATIONS - 128))); + cuts.sort_unstable(); + cuts.dedup(); + out.extend(cuts.into_iter().map(|k| good[..k].to_vec())); + } + if n == 0 { + return out; + } + // Bytes flipped, zeroed and saturated at seeded places. + for i in 0..384 { + let at = rng.below(n); + let mut b = good.to_vec(); + b[at] = match i % 3 { + 0 => b[at] ^ ((rng.next() >> 32) as u8 | 1), + 1 => 0x00, + _ => 0xff, + }; + out.push(b); + } + // Runs of bytes dropped, repeated and swapped with their neighbour. + for _ in 0..96 { + let at = rng.below(n); + let len = 1 + rng.below(64.min(n - at)); + let end = at + len; + let mut dropped = good[..at].to_vec(); + dropped.extend_from_slice(&good[end..]); + out.push(dropped); + let mut repeated = good[..end].to_vec(); + repeated.extend_from_slice(&good[at..]); + out.push(repeated); + if end + len <= n { + let mut swapped = good[..at].to_vec(); + swapped.extend_from_slice(&good[end..end + len]); + swapped.extend_from_slice(&good[at..end]); + swapped.extend_from_slice(&good[end + len..]); + out.push(swapped); + } + } + // The whole file: with garbage after it, twice over, reversed. + let mut tail = good.to_vec(); + tail.extend((0..4096).map(|_| (rng.next() >> 40) as u8)); + out.push(tail); + out.push([good, good].concat()); + out.push(good.iter().rev().copied().collect()); + if text && let Ok(s) = std::str::from_utf8(good) { + out.extend(text_mutations(s, &mut rng)); + } + out +} + +/// A text file's lines dropped, repeated and swapped, and its numbers replaced by lies. +fn text_mutations(s: &str, rng: &mut Rng) -> Vec> { + let mut out = Vec::new(); + let lines: Vec<&str> = s.split_inclusive('\n').collect(); + let join = |v: &[&str]| v.concat().into_bytes(); + let picked: Vec = if lines.len() <= 200 { (0..lines.len()).collect() } else { (0..200).map(|_| rng.below(lines.len())).collect() }; + for &i in &picked { + let mut v = lines.clone(); + v.remove(i); + out.push(join(&v)); + let mut v = lines.clone(); + v.insert(i, lines[i]); + out.push(join(&v)); + if i + 1 < lines.len() { + let mut v = lines.clone(); + v.swap(i, i + 1); + out.push(join(&v)); + } + } + // A line in place of another (a block that inserts itself, a count where a coordinate was). + for _ in 0..200.min(lines.len() * lines.len()) { + let (i, j) = (rng.below(lines.len()), rng.below(lines.len())); + let mut v = lines.clone(); + v[i] = lines[j]; + out.push(join(&v)); + } + // A word in place of another of the file's own words: a renamed block, a swapped keyword, a + // block that now inserts itself. Every pair in a small file, a sample in a large one. + let words = word_spans(s); + let mut vocab: Vec<&str> = words.iter().map(|&(a, b)| &s[a..b]).collect(); + vocab.sort_unstable(); + vocab.dedup(); + let pairs = words.len().saturating_mul(vocab.len()); + let swap = |(a, b): (usize, usize), w: &str| format!("{}{w}{}", &s[..a], &s[b..]).into_bytes(); + if pairs <= 3000 { + for &span in &words { + for &w in vocab.iter().filter(|w| **w != &s[span.0..span.1]) { + out.push(swap(span, w)); + } + } + } else { + for _ in 0..400 { + out.push(swap(words[rng.below(words.len())], vocab[rng.below(vocab.len())])); + } + } + // Numbers: each of up to 200 of them, in turn, becomes one of the liars. + let numbers = number_spans(s); + let chosen: Vec<(usize, usize)> = if numbers.len() <= 200 { numbers } else { (0..200).map(|_| numbers[rng.below(numbers.len())]).collect() }; + for (k, (a, b)) in chosen.into_iter().enumerate() { + let liar = LIARS[k % LIARS.len()]; + out.push(format!("{}{liar}{}", &s[..a], &s[b..]).into_bytes()); + } + // Every number lying at once (two counts that are only harmless one at a time). + let all = number_spans(s); + for liar in LIARS { + let mut t = String::with_capacity(s.len()); + let mut at = 0; + for &(a, b) in &all { + t.push_str(&s[at..a]); + t.push_str(liar); + at = b; + } + t.push_str(&s[at..]); + out.push(t.into_bytes()); + } + out +} + +/// Byte spans of the words in `s` (runs of ASCII letters, digits and `_` that start with a +/// letter). +fn word_spans(s: &str) -> Vec<(usize, usize)> { + let b = s.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + if !b[i].is_ascii_alphabetic() || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) { + i += 1; + continue; + } + let a = i; + while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { + i += 1; + } + out.push((a, i)); + } + out +} + +/// Byte spans of the decimal numbers in `s` (a sign, digits, a point, an exponent). +fn number_spans(s: &str) -> Vec<(usize, usize)> { + let b = s.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let starts = b[i].is_ascii_digit() || ((b[i] == b'-' || b[i] == b'.') && b.get(i + 1).is_some_and(u8::is_ascii_digit)); + let after_word = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); + if !starts || after_word { + i += 1; + continue; + } + let a = i; + i += 1; + while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || ((b[i] == b'e' || b[i] == b'E') && i + 1 < b.len())) { + if (b[i] == b'e' || b[i] == b'E') && (b[i + 1] == b'-' || b[i + 1] == b'+') { + i += 1; + } + i += 1; + } + out.push((a, i)); + } + out +} + +thread_local! { + /// Panics on this thread so far, caught or not ([`count_panics`]). + static PANICS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Count every panic per thread (tests run on several), then run the hook that was there. +fn count_panics() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + PANICS.with(|p| p.set(p.get() + 1)); + previous(info); + })); + }); +} + +/// The time any one reader call may take on a mutated file (a debug build on a loaded machine: +/// generous, but far below what unbounded work on a lying count would take). +pub const BUDGET: Duration = Duration::from_secs(2); + +/// Run `read` over `inputs`: no panic, within [`BUDGET`], and `read`'s count (triangles, +/// entities, …) at most `cap`. `read` returns `None` for an error. Panics (the test fails) naming +/// the first case that breaks a rule. +// Failing the calling test is this function's job; it only ever runs inside tests. +#[allow(clippy::panic)] +pub fn survives(what: &str, inputs: &[Vec], cap: usize, mut read: impl FnMut(&[u8]) -> Option) { + count_panics(); + let mut slowest = (Duration::ZERO, 0); + let mut read_ok = 0; + for (i, input) in inputs.iter().enumerate() { + let before = PANICS.with(std::cell::Cell::get); + let t = Instant::now(); + let r = catch_unwind(AssertUnwindSafe(|| read(input))); + let took = t.elapsed(); + let head = String::from_utf8_lossy(&input[..input.len().min(120)]).into_owned(); + let Ok(r) = r else { panic!("{what}: case {i} ({} bytes) panicked; it starts {head:?}", input.len()) }; + let caught = PANICS.with(std::cell::Cell::get) - before; + assert!( + caught == 0, + "{what}: case {i} ({} bytes) panicked inside the reader (caught there, but the browser aborts); it starts {head:?}", + input.len() + ); + assert!(took <= BUDGET, "{what}: case {i} ({} bytes) took {took:?} (budget {BUDGET:?}); it starts {head:?}", input.len()); + if let Some(count) = r { + assert!(count <= cap, "{what}: case {i} gave {count} (cap {cap})"); + read_ok += 1; + } + slowest = slowest.max((took, i)); + } + eprintln!("{what}: {} mutations, {read_ok} read, slowest case {} in {:?}", inputs.len(), slowest.1, slowest.0); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mutations_are_deterministic_and_cover_the_file() { + let good = b"solid x\n facet normal 0 0 1\n vertex 1.5 -2 3e2\n endfacet\nendsolid x\n"; + let a = mutations(good, true, 7); + assert_eq!(a, mutations(good, true, 7), "the same seed gives the same cases"); + assert_ne!(a, mutations(good, true, 8)); + assert!(a.iter().any(Vec::is_empty) && a.iter().any(|m| m.len() == good.len() - 1), "truncations down to nothing"); + assert!(a.iter().any(|m| m.windows(3).any(|w| w == b"nan")), "a number replaced by a liar"); + assert_eq!(number_spans("v 1.5 -2 3e2 x1 .5e-3"), vec![(2, 5), (6, 8), (9, 12), (16, 21)]); + // A long file: bounded truncations, kept to the first and last bytes and spaced between. + let long = vec![b'a'; 100_000]; + let m = mutations(&long, false, 1); + assert!(m.len() < 3000, "{} cases", m.len()); + } +} diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index e9f88f4bb..6b453964c 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -166,6 +166,8 @@ impl AcpBackend { out.push(Event::TurnEnded { reason: "auth".into() }); } out.push(Event::AuthRequired { methods: self.auth.clone() }); + } else if what == Pending::SetModel { + out.push(Event::ModelRejected(message)); } else if !config_error { if what == Pending::Prompt { out.push(Event::TurnEnded { reason: "error".into() }); @@ -382,4 +384,26 @@ mod tests { assert!(matches!(events.as_slice(), [Event::ConfigOptionFinished { result: Ok(options), .. }] if options[0].current_value == "smart")); backend.shutdown(true); } + + /// A refused model is the picker's business, not an error of the chat; signing in stays as it was. + #[test] + fn a_refused_model_is_reported_as_such() { + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap(); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events); + backend.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + events.clear(); + backend.set_model("zzz"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Err((-32602, "no such model".into())) }, &mut events); + assert!(matches!(events.as_slice(), [Event::ModelRejected(message)] if message == "no such model"), "{events:?}"); + events.clear(); + backend.set_model("fast"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({})) }, &mut events); + assert!(events.is_empty(), "{events:?}"); + backend.set_model("zzz"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Err((acp::AUTH_REQUIRED, "sign in".into())) }, &mut events); + assert!(matches!(events.as_slice(), [Event::AuthRequired { .. }]), "{events:?}"); + backend.shutdown(true); + } } diff --git a/crates/ui-egui/src/agent_chat/agents.rs b/crates/ui-egui/src/agent_chat/agents.rs index b7d6b8a81..51e49b973 100644 --- a/crates/ui-egui/src/agent_chat/agents.rs +++ b/crates/ui-egui/src/agent_chat/agents.rs @@ -76,7 +76,7 @@ impl Kind { } /// The wire protocol of an endpoint the user added. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Protocol { /// `{base}/chat/completions`, as Ollama, LM Studio, OpenAI and their kin speak. #[default] @@ -303,9 +303,11 @@ pub struct ApiPreset { pub const OPENAI_PRESETS: &[ApiPreset] = &[ ApiPreset { name: "Ollama", base_url: "http://localhost:11434/v1" }, ApiPreset { name: "LM Studio", base_url: "http://localhost:1234/v1" }, + ApiPreset { name: "OpenClaw", base_url: "http://localhost:18789/v1" }, ApiPreset { name: "OpenAI", base_url: "https://api.openai.com/v1" }, ApiPreset { name: "Mammouth AI", base_url: "https://api.mammouth.ai/v1" }, ApiPreset { name: "OpenCode Go", base_url: "https://opencode.ai/zen/go/v1" }, + ApiPreset { name: "OpenRouter", base_url: "https://openrouter.ai/api/v1" }, ]; /// Anthropic-compatible endpoints people use. The base URL is the one their documentation calls @@ -400,6 +402,18 @@ mod tests { assert!(presets(Protocol::Anthropic).iter().any(|p| p.base_url == "https://api.anthropic.com/v1")); } + /// The first preset is the one an Add dialog opens with, and the one taken for Ollama. + #[test] + fn ollama_stays_the_first_preset_and_every_preset_can_take_a_key() { + assert_eq!(OPENAI_PRESETS.first().map(|p| p.name), Some("Ollama")); + assert_eq!(OPENAI_PRESETS.last().map(|p| p.name), Some("OpenRouter")); + assert!(OPENAI_PRESETS.iter().any(|p| p.name == "OpenClaw")); + for preset in OPENAI_PRESETS.iter().chain(ANTHROPIC_PRESETS) { + assert_eq!(normalize_url(preset.base_url).as_deref(), Ok(preset.base_url), "{}", preset.name); + assert!(key_safe_for(preset.base_url), "{}", preset.name); + } + } + #[test] fn request_timeouts_default_to_300_s_and_stay_between_30_s_and_an_hour() { assert_eq!(AgentConfig::default().request_timeout_s, 300); diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 88c38e39a..e3bc37ecb 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -15,6 +15,7 @@ use std::time::Duration; use serde_json::{Map, Value, json}; +use super::MODEL_LIST_CAP; use super::acp::ModelInfo; use super::agents::Protocol; use super::backend::{ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus}; @@ -22,6 +23,8 @@ use super::process::{AgentProcess, FromAgent, ProcessHandle}; /// Longest tool result handed back to the model. const MAX_TOOL_TEXT: usize = 20_000; +/// Longest name kept for a listed model. +const MODEL_NAME_CAP: usize = 256; /// Messages kept in the conversation (the system note stays). const MAX_HISTORY: usize = 240; /// Pictures of the view kept in the conversation. The whole history goes with every request @@ -795,15 +798,24 @@ impl Worker { } self.emit(Event::ToolsAvailable(!self.tools.is_empty())); self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true }); - // The endpoint's models for the picker; an endpoint that does not list them shows none. - if let Ok(list) = self.model_list() { - let mut available = list; - if !self.cfg.model.is_empty() && !available.iter().any(|m| m.id == self.cfg.model) { - available.insert(0, ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() }); + // The endpoint's models for the picker. An endpoint that does not list them still shows the + // configured model, and says why there are no others. + let configured = ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() }; + let available = match self.model_list() { + Ok(mut list) => { + self.emit(Event::ModelsNote(None)); + if !self.cfg.model.is_empty() && !list.iter().any(|m| m.id == self.cfg.model) { + list.insert(0, configured); + } + list } - if !available.is_empty() { - self.emit(Event::Models { current: self.cfg.model.clone(), available }); + Err(e) => { + self.emit(Event::ModelsNote(Some(e))); + if self.cfg.model.is_empty() { Vec::new() } else { vec![configured] } } + }; + if !available.is_empty() { + self.emit(Event::Models { current: self.cfg.model.clone(), available }); } for cmd in cmds { match cmd { @@ -1628,7 +1640,7 @@ fn anthropic_headers(base_url: &str, key: Option<&str>) -> Result) -> Result, String> { let req = HttpRequest { method: "GET", url: endpoint(base_url, "models"), headers: anthropic_headers(base_url, key)?, body: None, timeout_s: 15 }; let (status, bytes) = http(&req)?; @@ -1636,19 +1648,10 @@ pub fn anthropic_model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> if status != 200 { return Err(http_error(status, &v)); } - Ok(v.get("data") - .and_then(Value::as_array) - .map(|a| { - a.iter() - .take(500) - .filter_map(|m| { - let id = m.get("id").and_then(Value::as_str)?.to_string(); - let name = m.get("display_name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| id.clone()); - Some(ModelInfo { id, name, description: String::new() }) - }) - .collect() - }) - .unwrap_or_default()) + Ok(listed_models(&v, "display_name")? + .into_iter() + .map(|(id, name)| ModelInfo { name: name.unwrap_or_else(|| id.clone()), id, description: String::new() }) + .collect()) } /// Test an Anthropic-compatible endpoint: send the smallest message there is, so the check covers @@ -1721,18 +1724,35 @@ fn tool_title(name: &str, args: &Value) -> String { } } -/// `GET {base_url}/models`: the model ids, in the order the endpoint lists them. -fn model_ids(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result, String> { +/// The ids of a `/models` body and the names the endpoint gives them (when not just the id), in +/// its order. The body is the endpoint's to write: an id that could not be sent back is left out, +/// and a name is cut. A body without a `data` array is no model list (a web page where the +/// endpoint should be, say): an error, so the picker says so and asks again later. +fn listed_models(body: &Value, name_key: &str) -> Result)>, String> { + let Some(entries) = body.get("data").and_then(Value::as_array) else { + return Err(crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string()); + }; + Ok(entries + .iter() + .filter_map(|m| { + let id = m.get("id").and_then(Value::as_str).filter(|id| super::model_id_valid(id))?; + let name = m.get(name_key).and_then(Value::as_str).filter(|name| *name != id).map(|name| name.chars().take(MODEL_NAME_CAP).collect()); + Some((id.to_string(), name)) + }) + .take(MODEL_LIST_CAP) + .collect()) +} + +/// `GET {base_url}/models`: the models, in the order the endpoint lists them. The picker shows the +/// ids, so an endpoint's own name for a model is its description. +fn model_entries(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result, String> { let req = HttpRequest { method: "GET", url: format!("{base_url}/models"), headers, body: None, timeout_s: 15 }; let (status, bytes) = http(&req)?; let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); if status != 200 { return Err(http_error(status, &v)); } - Ok(v.get("data") - .and_then(Value::as_array) - .map(|a| a.iter().take(500).filter_map(|m| m.get("id").and_then(Value::as_str).map(String::from)).collect()) - .unwrap_or_default()) + Ok(listed_models(&v, "name")?.into_iter().map(|(id, name)| ModelInfo { name: id.clone(), id, description: name.unwrap_or_default() }).collect()) } /// The endpoint's models for the picker. @@ -1744,7 +1764,7 @@ pub fn model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result, model: &s } headers.push(("Authorization".to_string(), format!("Bearer {k}"))); } - let ids = model_ids(http, base_url, headers)?; - let ids: Vec<&str> = ids.iter().map(String::as_str).collect(); - let found = model.is_empty() || ids.contains(&model); - Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &ids.len().to_string()), ("model", model)])) + let models = model_entries(http, base_url, headers)?; + let found = model.is_empty() || models.iter().any(|m| m.id == model); + Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &models.len().to_string()), ("model", model)])) } #[cfg(test)] @@ -2059,6 +2078,7 @@ mod tests { let Some(Event::Models { current, available }) = events.iter().find(|e| matches!(e, Event::Models { .. })) else { panic!("{events:?}") }; assert_eq!(current, "local"); assert_eq!(available.iter().map(|m| m.id.as_str()).collect::>(), ["local", "big", "small"]); + assert!(events.iter().any(|e| matches!(e, Event::ModelsNote(None))), "{events:?}"); b.set_model("big"); b.prompt(&[PromptPart::Text("hi".into())]); wait_for_seen(&seen); @@ -2561,6 +2581,87 @@ mod tests { assert!(tools[0].pointer("/parameters/additionalProperties").is_none(), "{tools:?}"); } + /// An endpoint that refuses the listing still shows the configured model, and says why first. + #[test] + fn a_refused_listing_keeps_the_configured_model_and_says_why() { + let http: HttpFn = Arc::new(|r: &HttpRequest| { + assert_eq!(r.method, "GET"); + Ok((401, json!({"error": {"message": "No auth credentials"}}).to_string().into_bytes())) + }); + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "local".into(), + key: None, + http, + request_timeout_s: 300, + reasoning_effort: String::new(), + }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + let mut events = Vec::new(); + let start = std::time::Instant::now(); + while !events.iter().any(|e| matches!(e, Event::Models { .. })) && start.elapsed() < Duration::from_secs(10) { + events.extend(b.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + let listing: Vec<&Event> = events.iter().filter(|e| matches!(e, Event::Models { .. } | Event::ModelsNote(_))).collect(); + let [Event::ModelsNote(Some(note)), Event::Models { current, available }] = listing[..] else { panic!("{events:?}") }; + assert!(note.contains("No auth credentials"), "{note}"); + assert_eq!(current, "local"); + assert_eq!(available.iter().map(|m| m.id.as_str()).collect::>(), ["local"]); + b.shutdown(true); + } + + /// OpenRouter's shape: the name is the description, whatever else an entry holds is ignored, an + /// id that could not be sent back is left out, and the list stays within its caps. + #[test] + fn a_listing_keeps_the_names_and_stays_within_its_caps() { + let mut data = vec![ + json!({"id": "openai/gpt-x", "name": "OpenAI: GPT X", "description": "Long text", "supported_parameters": ["tools"]}), + json!({"id": "same", "name": "same", "display_name": "Same One"}), + json!({"id": "long", "name": "n".repeat(MODEL_NAME_CAP + 10), "display_name": "d".repeat(MODEL_NAME_CAP + 10)}), + json!({"id": "x".repeat(super::super::MODEL_ID_CAP + 1)}), + json!({"id": "bell\u{7}"}), + json!({"id": ""}), + json!({"id": 7}), + json!({"name": "no id"}), + ]; + data.extend((0..MODEL_LIST_CAP + 500).map(|i| json!({"id": format!("m{i}")}))); + let body = json!({"data": data}).to_string().into_bytes(); + let http: HttpFn = Arc::new(move |_: &HttpRequest| Ok((200, body.clone()))); + let list = model_list(&http, "https://openrouter.ai/api/v1", None).unwrap(); + assert_eq!(list.len(), MODEL_LIST_CAP); + let [first, same, long, next] = &list[..4] else { panic!("{}", list.len()) }; + assert_eq!((first.id.as_str(), first.name.as_str(), first.description.as_str()), ("openai/gpt-x", "openai/gpt-x", "OpenAI: GPT X")); + assert_eq!((same.id.as_str(), same.description.as_str()), ("same", "")); + assert_eq!(long.description.chars().count(), MODEL_NAME_CAP); + assert_eq!(next.id, "m0"); + let list = anthropic_model_list(&http, "https://openrouter.ai/api/v1", None).unwrap(); + assert_eq!(list.len(), MODEL_LIST_CAP); + let [first, same, long] = &list[..3] else { panic!("{}", list.len()) }; + assert_eq!(first.name, "openai/gpt-x"); + assert_eq!(same.name, "Same One"); + assert_eq!(long.name.chars().count(), MODEL_NAME_CAP); + assert!(test_endpoint(&http, "https://openrouter.ai/api/v1", None, "openai/gpt-x").unwrap().contains(&MODEL_LIST_CAP.to_string())); + } + + /// A 200 that is no model list (a web page where the endpoint should be) is an error, so the + /// picker says why and asks again later; a list with nothing in it is a list. + #[test] + fn an_answer_that_is_no_model_list_is_an_error() { + let expected = crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string(); + let page: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, b"Control UI".to_vec()))); + assert_eq!(model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected); + assert_eq!(anthropic_model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected); + assert_eq!(test_endpoint(&page, "http://localhost:18789/v1", None, "").unwrap_err(), expected); + let object: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"object": "list"}).to_string().into_bytes()))); + assert_eq!(model_list(&object, "http://localhost:18789/v1", None).unwrap_err(), expected); + let empty: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"data": []}).to_string().into_bytes()))); + assert!(model_list(&empty, "http://localhost:18789/v1", None).unwrap().is_empty()); + } + #[test] fn tool_arguments_are_an_object_or_an_error() { assert_eq!(tool_arguments(None), Ok(json!({}))); diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index c7976a8d5..ccd404c09 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -96,6 +96,11 @@ pub enum Event { current: String, available: Vec, }, + /// Why an endpoint's models could not be listed (`None`: they could). It comes before the + /// [`Event::Models`] of that listing, which then holds only the configured model. + ModelsNote(Option), + /// The agent refused the model it was just sent, and says why. + ModelRejected(String), ConfigOptions(Vec), ConfigOptionFinished { id: String, diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index b1554a06c..952fd63cc 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -50,7 +50,7 @@ use crate::{ControlRequest, SolveApp}; use backend::{ChatBackend, Event, PermissionOption, PromptPart, ToolStatus}; pub(crate) use panel::{left_inset, tool_space}; -pub use panel::{show, tip as panel_tip, toggle}; +pub use panel::{show, tip as panel_tip, toggle, toggle_shortcut}; /// Most entries kept in the conversation; older ones are dropped. const MAX_ITEMS: usize = 2000; @@ -316,6 +316,15 @@ impl Loading { } } +/// The model before an ACP agent was sent another, for when it refuses that one. +struct ModelRevert { + model: String, + /// The one sent was not listed, so it leaves the list again. + unlisted: bool, + /// The model remembered for this agent. + saved: Option, +} + #[derive(Default)] pub struct AgentChat { /// The panel is shown (View menu, the application bar's chat button, Ctrl+Shift+A). @@ -402,6 +411,12 @@ pub struct AgentChat { /// The provider picked in the header when the models come from several providers (`None`: the /// current model's). It only narrows the model list; the agent keeps its model until one is chosen. pub model_provider: Option, + /// Why the running endpoint's models could not be listed, for the picker. + pub models_note: Option, + /// What to put back if the running ACP agent refuses the model it was last sent. + model_revert: Option, + /// The typed model an agent's model option was sent, until it answers. + typed_model: Option, pub config_options: Option>, pub config_pending: bool, /// An API endpoint's models, kept per endpoint (its base URL) for the next connection. @@ -484,6 +499,7 @@ impl AgentChat { self.model_provider = None; } self.config_pending = false; + self.typed_model = None; } fn apply_config_snapshot(&mut self, options: Vec) { @@ -575,6 +591,11 @@ impl AgentChat { pictures.push(Picture::shared(Arc::new(png), "", true)); } } + /// Say that the agent refused a model, and in its words why. + fn model_refused(&mut self, model: &str, error: &str) { + let text = trf("ui.agent_chat_model_rejected", &[("model", model), ("error", error)]); + self.notice(text.chars().take(MODELS_NOTE_CAP).collect::(), true); + } fn notice(&mut self, text: impl Into, error: bool) { self.push(Item::Notice { text: text.into(), error }); } @@ -718,11 +739,21 @@ impl AgentChat { } } Event::Models { current, available } => { + self.model_revert = None; if self.config_options.is_none() && !available.is_empty() { - if !self.running_endpoint.is_empty() { - self.models_cache.insert(self.running_endpoint.clone(), available.clone()); + if self.models_note.is_some() { + // The listing failed: last time's list stays, with the configured model in it. + for model in available { + if !self.models.iter().any(|m| m.id == model.id) { + self.models.insert(0, model); + } + } + } else { + if !self.running_endpoint.is_empty() { + self.models_cache.insert(self.running_endpoint.clone(), available.clone()); + } + self.models = available; } - self.models = available; } if self.config_options.is_none() { if current != self.model { @@ -731,16 +762,36 @@ impl AgentChat { self.model = current; } } + // Formatted here: the listing's thread has no language of its own. + Event::ModelsNote(error) => { + self.models_note = + error.map(|error| trf("ui.agent_chat_models_failed", &[("error", &error)]).chars().take(MODELS_NOTE_CAP).collect()); + } + Event::ModelRejected(message) => { + let refused = self.model.clone(); + self.model_refused(&refused, &message); + if let Some(revert) = self.model_revert.take() { + if revert.unlisted { + let refused = std::mem::take(&mut self.model); + self.models.retain(|m| m.id != refused); + } + self.model = revert.model; + self.model_provider = None; + } + } Event::ConfigOptions(options) => { self.apply_config_snapshot(options); } Event::ConfigOptionFinished { result, .. } => { self.config_pending = false; - match result { - Ok(options) => { + let typed = self.typed_model.take(); + match (result, typed) { + (Ok(options), _) => { self.apply_config_snapshot(options); } - Err(message) => self.notice(message, true), + // An agent's own words may not say what it refused ("Internal error"). + (Err(message), Some(model)) => self.model_refused(&model, &message), + (Err(message), None) => self.notice(message, true), } } Event::AuthRequired { methods } => { @@ -856,7 +907,7 @@ pub(crate) fn assistant_mark(app: &SolveApp) -> AssistantMark { ) } -pub(crate) fn assistant_tip(mark: AssistantMark) -> String { +pub(crate) fn assistant_tip(app: &SolveApp, mark: AssistantMark) -> String { let state = match mark { AssistantMark::Quiet => tr("ui.agent_chat_state_off").to_string(), AssistantMark::Ready => tr("ui.agent_chat_state_ready").to_string(), @@ -865,7 +916,11 @@ pub(crate) fn assistant_tip(mark: AssistantMark) -> String { AssistantMark::Stopped => tr("ui.agent_chat_state_exited").to_string(), AssistantMark::Waiting(count) => trf("ui.assistant_waiting", &[("count", &count.to_string())]), }; - format!("{} (Ctrl+Shift+A) — {state}", tr("ui.assistant")) + let name = match crate::keymap::display_for(app, "ui.assistant") { + Some(key) => format!("{} ({key})", tr("ui.assistant")), + None => tr("ui.assistant").to_string(), + }; + format!("{name} — {state}") } /// Whether a permission question is about one of SolidCraft's own tools (which SolidCraft's own @@ -986,6 +1041,8 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { chat.mode.clear(); chat.models.clear(); chat.model.clear(); + chat.models_note = None; + chat.model_revert = None; chat.running_endpoint = if entry.kind.is_api() { entry.base_url.clone() } else { String::new() }; // An endpoint's models from the last time, until the new list arrives. if let Some(list) = chat.models_cache.get(&chat.running_endpoint) { @@ -1352,6 +1409,7 @@ pub fn new_chat(app: &mut SolveApp) { chat.stopped = false; chat.ended = None; chat.discard_end = running; + chat.model_revert = None; if matches!(chat.state(), State::Ready | State::Busy) { chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty()); chat.state = Some(State::Starting); @@ -1880,6 +1938,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { } _ => None, }; + let refused = if matches!(e, Event::ModelRejected(_)) { app.agent_chat.model_revert.as_ref().map(|r| r.saved.clone()) } else { None }; match app.agent_chat.on_event(e) { Some(Outcome::TurnEnd) => { end_turn(app); @@ -1895,10 +1954,19 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { } if let Some(model) = confirmed_model { app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), model.clone()); - if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind == agents::Kind::Api) { + if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind.is_api()) { a.model = model; } } + match refused { + Some(Some(saved)) => { + app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), saved); + } + Some(None) => { + app.preferences.agent_models.remove(&app.agent_chat.running_id); + } + None => {} + } if ready { apply_saved_model(app); } @@ -1919,6 +1987,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { settings::poll_capabilities(app, ctx); + settings::poll_listing(app, ctx); connect_at_start(app, ctx); } pump_tools(app); @@ -1953,15 +2022,66 @@ pub fn set_model(app: &mut SolveApp, model: &str) { set_config_option(app, &id, model); return; } - if !app.agent_chat.models.iter().any(|m| m.id == model) { - return; + if app.agent_chat.models.iter().any(|m| m.id == model) { + send_model(app, model); } - if let Some(b) = app.agent_chat.backend.as_mut() { +} + +/// Whether a model the agent did not list can be sent: an endpoint, an ACP agent with a model +/// option, or a legacy ACP agent that listed models. +pub fn custom_models_accepted(app: &SolveApp) -> bool { + let chat = &app.agent_chat; + if chat.backend.is_none() || !chat.state().running() { + return false; + } + match chat.config_options.as_ref() { + Some(options) => options.iter().any(|o| o.category == "model"), + None => !chat.running_endpoint.is_empty() || !chat.models.is_empty(), + } +} + +/// A typed model (the pickers' custom row). A listed id goes the usual way, others by the agent's +/// kind; an agent that refuses it keeps its model and the chat says so. Returns whether it was sent. +pub fn set_custom_model(app: &mut SolveApp, text: &str) -> bool { + let model = text.trim(); + if !model_id_valid(model) || !custom_models_accepted(app) { + return false; + } + let option = app.agent_chat.config_options.as_ref().and_then(|options| options.iter().find(|o| o.category == "model")); + if let Some(id) = option.map(|o| o.id.clone()) { + let sent = set_config_option_checked(app, &id, model, false); + if sent { + app.agent_chat.typed_model = Some(model.to_string()); + } + return sent; + } + send_model(app, model); + true +} + +/// Switch a legacy ACP agent or an endpoint to `model`: it shows as current at once and is +/// remembered for this agent; an endpoint also keeps it as its default model. +fn send_model(app: &mut SolveApp, model: &str) { + let agent = app.agent_chat.running_id.clone(); + let chat = &mut app.agent_chat; + let unlisted = !chat.models.iter().any(|m| m.id == model); + let entry = || acp::ModelInfo { id: model.to_string(), name: model.to_string(), description: String::new() }; + if unlisted { + chat.models.insert(0, entry()); + chat.models.truncate(MODEL_LIST_CAP); + } + if chat.running_endpoint.is_empty() { + chat.model_revert = Some(ModelRevert { model: chat.model.clone(), unlisted, saved: app.preferences.agent_models.get(&agent).cloned() }); + } else if unlisted { + let cached = chat.models_cache.entry(chat.running_endpoint.clone()).or_default(); + cached.insert(0, entry()); + cached.truncate(MODEL_LIST_CAP); + } + if let Some(b) = chat.backend.as_mut() { b.set_model(model); } - app.agent_chat.model = model.to_string(); - app.agent_chat.model_provider = None; - let agent = app.agent_chat.running_id.clone(); + chat.model = model.to_string(); + chat.model_provider = None; if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == agent && a.kind.is_api()) { a.model = model.to_string(); } @@ -1984,10 +2104,22 @@ pub fn models_shown(app: &SolveApp) -> bool { /// Longest provider name kept from an agent's model list. const PROVIDER_NAME_CAP: usize = 128; +/// Most models kept for a picker, whether listed or typed. +const MODEL_LIST_CAP: usize = 2000; +/// Longest model id kept from a listing or sent to an agent. +pub const MODEL_ID_CAP: usize = 256; +/// Longest note about a listing that failed or a model the agent refused. +const MODELS_NOTE_CAP: usize = 1024; + +/// Whether a model id can go to an agent: not empty, not too long, no control characters. +fn model_id_valid(id: &str) -> bool { + !id.is_empty() && id.chars().count() <= MODEL_ID_CAP && !id.chars().any(char::is_control) +} /// A model's provider and its name at that provider, when the agent says which provider serves it: -/// a name `Provider · model` (Hermes, OpenCode) or a description `Provider: …` (up to a ` • `). -/// `None`: the agent names no provider. +/// a name `Provider · model` (Hermes, OpenCode), a description `Provider: …` (up to a ` • `), or +/// an endpoint's listing whose id reads `vendor/model` and whose description (the endpoint's own +/// name for it) reads `Vendor: Model` (OpenRouter). `None`: the agent names no provider. pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> { let cap = |s: &str| s.trim().chars().take(PROVIDER_NAME_CAP).collect::(); if let Some((provider, name)) = m.name.split_once(" · ") @@ -1996,9 +2128,48 @@ pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> { { return Some((cap(provider), name.trim().to_string())); } - let rest = m.description.strip_prefix("Provider:")?; - let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or(""); - (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone())) + if let Some(rest) = m.description.strip_prefix("Provider:") { + let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or(""); + return (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone())); + } + let first_line = m.description.lines().next().unwrap_or(""); + if m.id.contains('/') + && let Some((vendor, name)) = first_line.split_once(": ") + && !vendor.trim().is_empty() + && vendor.chars().count() <= PROVIDER_NAME_CAP + && !name.trim().is_empty() + { + return Some((cap(vendor), name.trim().to_string())); + } + None +} + +/// How a picker shows `models`: each one's label, the group it folds under and its tooltip. With +/// models from two or more providers the label is the name at the provider, the group the +/// provider and the tooltip the id (or the description where the label already is the id); +/// otherwise the name as it is, no group, and the description. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub fn model_rows(models: &[acp::ModelInfo]) -> Vec<(String, Option, String)> { + let mut providers: Vec = Vec::new(); + for m in models { + let p = provider_of(m); + if !providers.contains(&p) { + providers.push(p); + } + } + let grouped = providers.len() >= 2; + models + .iter() + .map(|m| { + if grouped { + let (provider, name) = model_provider(m).unwrap_or_else(|| (provider_of(m), m.name.clone())); + let tip = if name == m.id { m.description.clone() } else { m.id.clone() }; + (name, Some(provider), tip) + } else { + (m.name.clone(), None, m.description.clone()) + } + }) + .collect() } /// The provider a model is listed under: its own, or "Other" when the agent names none. @@ -2051,8 +2222,17 @@ pub fn listed_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String)> { .collect() } -/// Show one provider's models in the model picker (the header's provider picker). The agent keeps -/// its model until one of them is chosen. A provider the agent does not offer is ignored. +/// Every model the header's picker lists, with its label, the group it folds under and its tooltip +/// ([`model_rows`]). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub fn grouped_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String, Option, String)> { + let rows = model_rows(&app.agent_chat.models); + app.agent_chat.models.iter().cloned().zip(rows).map(|(m, (label, group, tip))| (m, label, group, tip)).collect() +} + +/// The provider whose group the header's model picker opens first (the control channel's +/// `provider`). The agent keeps its model until one is chosen. A provider the agent does not offer +/// is ignored. pub fn set_model_provider(app: &mut SolveApp, provider: &str) { if model_providers(app).iter().any(|(n, _)| n == provider) { app.agent_chat.model_provider = Some(provider.to_string()); @@ -2079,19 +2259,25 @@ pub fn set_mode(app: &mut SolveApp, mode: &str) { /// Change a reported modern ACP configuration option; only acknowledged snapshots change state. pub fn set_config_option(app: &mut SolveApp, id: &str, value: &str) { + set_config_option_checked(app, id, value, true); +} + +/// [`set_config_option`], with a choice the agent did not list (`listed_only` false: a typed +/// model, which the agent may refuse). Returns whether it was sent. +fn set_config_option_checked(app: &mut SolveApp, id: &str, value: &str, listed_only: bool) -> bool { let Some(option) = app.agent_chat.config_options.as_ref().and_then(|xs| xs.iter().find(|x| x.id == id)) else { - return; + return false; }; if app.agent_chat.config_pending || !matches!(app.agent_chat.state(), State::Ready | State::Busy) - || !option.options.iter().any(|x| x.value == value) + || (listed_only && !option.options.iter().any(|x| x.value == value)) { - return; - } - if let Some(b) = app.agent_chat.backend.as_mut() { - b.set_config_option(id, value); - app.agent_chat.config_pending = true; + return false; } + let Some(b) = app.agent_chat.backend.as_mut() else { return false }; + b.set_config_option(id, value); + app.agent_chat.config_pending = true; + true } /// `ui.agent_chat` on the control channel (tests and screenshots): `enabled`, `command`, @@ -2186,7 +2372,11 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result Value { #[cfg(target_arch = "wasm32")] let detection: Option = None; let pid = c.backend.as_ref().and_then(|b| b.pid()); - json!({ + let mut state = json!({ "features": app.preferences.ai_features, "configOptions": c.config_options, "configPending": c.config_pending, @@ -2355,7 +2545,13 @@ pub fn status(app: &SolveApp) -> Value { "turnWarning": c.turn_warning, "detection": detection, "items": items, - }) + }); + // Added apart: `json!` has reached the compiler's recursion limit above. + if let Some(state) = state.as_object_mut() { + state.insert("modelsNote".into(), json!(c.models_note)); + state.insert("customModels".into(), json!(custom_models_accepted(app))); + } + state } #[cfg(test)] diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 389a20148..201b2f8b8 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -14,8 +14,34 @@ pub const MIN_WIDTH: f32 = 280.0; pub const MAX_WIDTH: f32 = 760.0; /// The folded panel's width. const STRIP: f32 = 30.0; -/// The keyboard shortcut that shows and hides the panel (also from its own text field). -pub const SHORTCUT: egui::KeyboardShortcut = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), egui::Key::A); +/// Consume the configured toggle before CAD shortcuts, including in the chat's own window. +/// Bare character keys remain text while a field owns the keyboard; chords still hide chat. +pub fn toggle_shortcut(app: &mut SolveApp, ctx: &egui::Context) { + if !shown(app) || crate::keymap::capturing(app) { + return; + } + let keys = crate::keymap::keys(app, "ui.assistant"); + let typing = ctx.egui_wants_keyboard_input(); + let pressed = ctx.input_mut(|input| { + let mut pressed = false; + input.events.retain(|event| { + if let egui::Event::Key { key, modifiers, pressed: true, repeat, .. } = event { + if typing && !modifiers.command && !modifiers.ctrl && !modifiers.alt { + return true; + } + if keys.contains(&crate::keymap::key_name(*key, *modifiers)) { + pressed |= !repeat; + return false; + } + } + true + }); + pressed + }); + if pressed { + toggle(app); + } +} fn panel_id(left: bool) -> Id { Id::new(if left { "sc_agent_chat_left" } else { "sc_agent_chat_right" }) @@ -50,9 +76,11 @@ pub fn toggle(app: &mut SolveApp) { } /// The tooltip of the chat's buttons: its name and shortcut. -pub fn tip() -> String { - let key = if cfg!(target_os = "macos") { "Cmd+Shift+A" } else { "Ctrl+Shift+A" }; - format!("{} ({key})", tr("ui.agent_chat")) +pub fn tip(app: &SolveApp) -> String { + match crate::keymap::display_for(app, "ui.assistant") { + Some(key) => format!("{} ({key})", tr("ui.agent_chat")), + None => tr("ui.agent_chat").to_string(), + } } /// The panel, when the chat is turned on and open. Call before the central viewport is laid out. @@ -69,9 +97,6 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if !shown(app) { return; } - if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) { - toggle(app); - } // A window that isn't drawn this frame closes; the next one opens at the saved place. if !(app.agent_chat.open && app.preferences.agent_chat_popped) { app.agent_chat.window_placed = false; @@ -531,6 +556,11 @@ fn window(app: &mut SolveApp, ctx: &egui::Context) { // The side panel isn't drawn: its place no longer counts as "in the chat". app.agent_chat.panel_rect = None; ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("sc_agent_chat_window"), builder, |ui, class| { + // Root/embedded inputs are handled by SolveApp::logic. A native chat window owns + // its input and must see the toggle before its text editor can consume the chord. + if class != egui::ViewportClass::EmbeddedWindow { + toggle_shortcut(app, ui.ctx()); + } let t = Tokens::get(); let frame = Container::new(ui.ctx(), Surface::Panel).edge_frame(t.dialog_body); let r = Container::new(ui.ctx(), Surface::Viewport).central().frame(frame).show(ui, |ui| ui_kit::scope(ui, |ui| body(app, ui, false))); @@ -555,9 +585,6 @@ fn window(app: &mut SolveApp, ctx: &egui::Context) { if ctx.input(|i| !i.raw.hovered_files.is_empty()) { drop_hint(&ctx, r.response.rect); } - if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) { - toggle(app); - } // The whole window is the chat, so New chat works anywhere in it. if ctx.input_mut(|i| i.consume_shortcut(&NEW_CHAT_SHORTCUT)) { request_new_chat(app); @@ -667,7 +694,7 @@ fn strip(app: &mut SolveApp, ui: &mut egui::Ui) { if app.preferences.agent_chat_side == "left" { [r.right_top(), r.right_bottom()] } else { [r.left_top(), r.left_bottom()] }, t.primary_border(t.border), ); - let tip = format!("{} · {}", tip(), state.label()); + let tip = format!("{} · {}", tip(app), state.label()); if resp.on_hover_text(tip).clicked() { app.preferences.agent_chat_minimized = false; } @@ -1044,11 +1071,8 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { ); let models = !modern && models_shown(app); let providers = if models { model_providers(app) } else { Vec::new() }; - let w = (ui.available_width() - - if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - - if models { 146.0 } else { 0.0 } - - if providers.is_empty() { 0.0 } else { 146.0 }) - .clamp(90.0, 260.0); + let w = (ui.available_width() - if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - if models { 146.0 } else { 0.0 }) + .clamp(90.0, 260.0); let mut picked: Option = None; let mut add = false; let combo = ui @@ -1109,61 +1133,47 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { set_mode(app, &m); } } - // Models from several providers: pick the provider first, then one of its models. - if let Some(shown) = shown_provider(app).filter(|_| !providers.is_empty()) { - let mut pick: Option = None; - let width = picker_width(ui, &shown); - let r = ui - .allocate_ui(vec2(width, t.control_height), |ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - ui_kit::dropdown_menu(ui, "sc_agent_provider", &shown, |ui| { - for (name, count) in &providers { - let row = ui_kit::list_picker(ui, &format!("provider:{name}"), name, *name == shown) - .on_hover_text(trf("ui.agent_chat_provider_models", &[("count", &count.to_string())])); - crate::scenario::publish_handle(&format!("agent_chat:provider:{name}"), row.rect.center()); - if row.clicked() { - pick = Some(name.clone()); - } - } - }) - }) - .inner; - crate::scenario::publish_rect("agent_chat:provider", r.rect); - crate::scenario::publish_handle("agent_chat:provider", r.rect.center()); - r.on_hover_text(tr("ui.agent_chat_provider_tip")); - if let Some(p) = pick { - set_model_provider(app, &p); - } - } // The agent's models (ACP `models`, or an endpoint's list): shown only when it reports some. if models { - let list = listed_models(app); - let cur = list.iter().find(|(m, _)| m.id == app.agent_chat.model).map_or_else( - || if providers.is_empty() { app.agent_chat.model.clone() } else { tr("ui.agent_chat_choose_model").to_string() }, - |(_, name)| name.clone(), - ); - let mut pick: Option = None; + // Models from several providers fold under their providers inside the picker, the + // current model's provider open. + let list = grouped_models(app); + let open = shown_provider(app).filter(|_| !providers.is_empty()); + let cur = list + .iter() + .find(|(m, _, _, _)| m.id == app.agent_chat.model) + .map_or_else(|| app.agent_chat.model.clone(), |(_, name, _, _)| name.clone()); let width = if providers.is_empty() { t.form_label_width } else { picker_width(ui, &cur) }; - let r = ui + let choices: Vec> = + list.iter().map(|(m, name, group, tip)| ui_kit::SearchChoice { value: &m.id, label: name, tip, group: group.as_deref() }).collect(); + let custom = custom_models_accepted(app); + let picker = ui .allocate_ui(vec2(width, t.control_height), |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - ui_kit::dropdown_menu(ui, "sc_agent_model", &cur, |ui| { - for (m, name) in &list { - let row = ui_kit::list_picker(ui, &m.id, name, m.id == app.agent_chat.model); - let row = if m.description.is_empty() { row } else { row.on_hover_text(&m.description) }; - crate::scenario::publish_handle(&format!("agent_chat:model:{}", m.id), row.rect.center()); - if row.clicked() { - pick = Some(m.id.clone()); - } - } - }) + ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: "sc_agent_model", + handles: "agent_chat:model", + current: &cur, + current_value: &app.agent_chat.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom, + note: app.agent_chat.models_note.as_deref(), + open_group: open.as_deref(), + enabled: true, + }, + ) }) .inner; - crate::scenario::publish_rect("agent_chat:model", r.rect); - crate::scenario::publish_handle("agent_chat:model", r.rect.center()); - r.on_hover_text(tr("ui.agent_chat_model_tip")); - if let Some(m) = pick { - set_model(app, &m); + picker.response.on_hover_text(tr("ui.agent_chat_model_tip")); + match picker.inner { + Some(ui_kit::Picked::Listed(m)) => set_model(app, &m), + Some(ui_kit::Picked::Custom(m)) => { + set_custom_model(app, &m); + } + None => {} } } }); @@ -1288,52 +1298,95 @@ fn config_select(app: &mut SolveApp, ui: &mut egui::Ui, option: &acp::ConfigOpti .collect::>() .join("\n"); let mut picked = None; - let response = ui - .add_enabled_ui(!pending && !option.options.is_empty(), |ui| { - ui.allocate_ui(vec2(width, t.control_height), |ui| { - ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| { - let mut previous_group: Option<&str> = None; - for choice in &option.options { - let group = choice.group.as_deref().filter(|g| !g.is_empty()); - if let Some(group) = group - && previous_group != Some(group) - { - ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).on_hover_text(group); - } - previous_group = group; - let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value); - let row = row.on_hover_text( - [choice.name.as_str(), choice.description.as_str()] - .into_iter() - .filter(|part| !part.is_empty()) - .collect::>() - .join("\n"), - ); - crate::scenario::publish_handle(&format!("agent_chat:config:{}:{}", option.id, choice.value), row.rect.center()); - if option.category == "model" { - crate::scenario::publish_handle(&format!("agent_chat:model:{}", choice.value), row.rect.center()); - } - if row.clicked() { - picked = Some(choice.value.clone()); - } - } - }) + let enabled = !pending && !option.options.is_empty(); + let handles = format!("agent_chat:config:{}", option.id); + let response = if option.category == "model" { + let choices: Vec> = option + .options + .iter() + .map(|choice| ui_kit::SearchChoice { + value: &choice.value, + label: &choice.name, + tip: &choice.description, + group: choice.group.as_deref(), }) - .inner - }) - .inner; - crate::scenario::publish_handle(&format!("agent_chat:config:{}", option.id), response.rect.center()); - crate::scenario::publish_rect(&format!("agent_chat:config:{}", option.id), response.rect); - if option.category == "model" { - crate::scenario::publish_handle("agent_chat:model", response.rect.center()); - } else if option.category == "mode" { - crate::scenario::publish_handle("agent_chat:mode", response.rect.center()); - } - response - .widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, !pending && !option.options.is_empty(), format!("{name}: {selected}"))); + .collect(); + let id = format!("sc_agent_config:{}", option.id); + let picker = ui + .allocate_ui(vec2(width, t.control_height), |ui| { + ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: &id, + handles: &handles, + current: &displayed, + current_value: &option.current_value, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: None, + open_group: None, + enabled, + }, + ) + }) + .inner; + picked = picker.inner; + // Under the names every kind of agent's model picker goes by. + let rows = format!("{handles}:"); + for (name, at) in crate::scenario::handles(&rows) { + if let Some(row) = name.strip_prefix(&rows) { + crate::scenario::publish_handle(&format!("agent_chat:model:{row}"), at); + } + } + crate::scenario::publish_target("agent_chat:model", picker.response.rect); + picker.response + } else { + let response = ui + .add_enabled_ui(enabled, |ui| { + ui.allocate_ui(vec2(width, t.control_height), |ui| { + ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| { + let mut previous_group: Option<&str> = None; + for choice in &option.options { + let group = choice.group.as_deref().filter(|g| !g.is_empty()); + if let Some(group) = group + && previous_group != Some(group) + { + ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).on_hover_text(group); + } + previous_group = group; + let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value); + let row = row.on_hover_text( + [choice.name.as_str(), choice.description.as_str()] + .into_iter() + .filter(|part| !part.is_empty()) + .collect::>() + .join("\n"), + ); + crate::scenario::publish_handle(&format!("{handles}:{}", choice.value), row.rect.center()); + if row.clicked() { + picked = Some(ui_kit::Picked::Listed(choice.value.clone())); + } + } + }) + }) + .inner + }) + .inner; + crate::scenario::publish_target(&handles, response.rect); + if option.category == "mode" { + crate::scenario::publish_handle("agent_chat:mode", response.rect.center()); + } + response + }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, enabled, format!("{name}: {selected}"))); response.on_hover_text(tip); - if let Some(value) = picked { - super::set_config_option(app, &option.id, &value); + match picked { + Some(ui_kit::Picked::Listed(value)) => super::set_config_option(app, &option.id, &value), + Some(ui_kit::Picked::Custom(value)) => { + super::set_custom_model(app, &value); + } + None => {} } } @@ -1560,6 +1613,49 @@ fn auth_box(app: &mut SolveApp, ui: &mut egui::Ui) { }); } +/// The visible **Copy message** button of one transcript message (#10675): copies the whole +/// message — the prompt as entered, or the assistant's original Markdown — and nothing else. +/// A streaming reply copies the stable text received so far, which is what `text` holds. +#[cfg(not(target_arch = "wasm32"))] +fn copy_message_button(ui: &mut egui::Ui, n: usize, text: &str) { + let b = ui_kit::button(ui, tr("ui.agent_chat_copy_message"), ui_kit::Button::Small); + crate::scenario::publish_handle(&format!("agent_chat:copy:{n}"), b.rect.center()); + if b.clicked() { + ui.ctx().copy_text(text.to_owned()); + } +} + +/// The right-click menu of one transcript message (#10675): the same single action as the +/// visible button, on the whole message area, beside the composer's own text menu. +/// The area stays hover-only so partial text selection keeps working, so the menu opens on a +/// right-click released over it rather than on a click the response itself would report. +#[cfg(not(target_arch = "wasm32"))] +fn copy_message_menu(ui: &egui::Ui, response: &egui::Response, n: usize, text: &str) { + crate::scenario::publish_rect(&format!("agent_chat:msg:{n}"), response.rect); + let opened = ui + .input(|i| i.pointer.button_released(egui::PointerButton::Secondary) && i.pointer.interact_pos().is_some_and(|p| response.rect.contains(p))); + let mut copy = false; + Container::new(ui.ctx(), Surface::Popup) + .menu(response) + .at_pointer_fixed() + .frame(ui_kit::Menu::frame()) + .open_memory(if opened { Some(egui::SetOpenCommand::Bool(true)) } else { None }) + .show(|ui| { + ui_kit::Menu::show(ui, crate::context_menu::LIST_W, |ui| { + let item = ui_kit::MenuItem::new("copy_message", tr("ui.agent_chat_copy_message"), "copy"); + let row = item.show(ui); + crate::scenario::publish_handle(&format!("agent_chat:copy_menu:{n}"), row.rect.center()); + if row.clicked() { + copy = true; + ui.close(); + } + }); + }); + if copy { + ui.ctx().copy_text(text.to_owned()); + } +} + #[cfg(not(target_arch = "wasm32"))] fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); @@ -1573,6 +1669,9 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { for (n, item) in app.agent_chat.items.iter().enumerate() { match item { Item::User { text, image, pictures, context, files } => { + // A picture-only prompt has no text to copy: no action rather than an empty copy (#10675). + let copyable = !text.is_empty(); + let before = ui.cursor(); ui_kit::assistant_bubble(ui, |ui| { if !text.is_empty() { ui.add(egui::Label::new(RichText::new(text).color(t.text)).selectable(true).wrap()); @@ -1587,13 +1686,28 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { } context_chips(ui, context, false); files_line(ui, files.iter().map(String::as_str)); + if copyable { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| copy_message_button(ui, n, text)); + } }); + if copyable { + let drawn = egui::Rect::from_x_y_ranges(before.x_range(), before.min.y..=ui.cursor().min.y); + let resp = ui.interact(drawn, Id::new(("agent_chat_msg", n)), Sense::hover()); + copy_message_menu(ui, &resp, n, text); + } } Item::Agent { thought, text } => { if *thought { ui.add(egui::Label::new(RichText::new(text).italics().color(t.text_dim)).selectable(true).wrap()); } else { + let before = ui.cursor(); ui_kit::assistant_prose(ui, |ui| super::markdown_view::show(ui, n, text)); + if !text.is_empty() { + copy_message_button(ui, n, text); + let drawn = egui::Rect::from_x_y_ranges(before.x_range(), before.min.y..=ui.cursor().min.y); + let resp = ui.interact(drawn, Id::new(("agent_chat_msg", n)), Sense::hover()); + copy_message_menu(ui, &resp, n, text); + } } } Item::Tool { .. } => { @@ -2347,7 +2461,7 @@ mod tests { ui_kit::scope(ui, |ui| switcher(&mut app, ui)); }); output.textures_delta.clear(); - let rects: Vec<_> = ["switcher", "mode", "provider", "model"] + let rects: Vec<_> = ["switcher", "mode", "model"] .into_iter() .map(|name| { let rect = crate::scenario::rect_of(&format!("agent_chat:{name}")).expect("picker retained"); diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs index 98527212b..07f584e70 100644 --- a/crates/ui-egui/src/agent_chat/settings.rs +++ b/crates/ui-egui/src/agent_chat/settings.rs @@ -38,6 +38,10 @@ pub struct AddState { /// Editing an endpoint whose key is in the keychain: an empty key field keeps it. pub saved_key: bool, test: Option, + /// The endpoint the model picker lists: what the fields said when they were last left. + listing: Option, + /// The fields were left, or the picker opened: take what they say now. + list_again: bool, } /// A connection test running or done. @@ -80,6 +84,147 @@ pub struct State { capabilities: std::collections::HashMap<(String, String), Option>, #[cfg(not(target_arch = "wasm32"))] checking: Option, + /// Endpoints' models as they were last listed here, or why they could not be. + endpoint_models: std::collections::HashMap, String>>, + #[cfg(not(target_arch = "wasm32"))] + listing: Option, + /// An agent card's picker asked for this listing (with the agent whose key goes along). + #[cfg(not(target_arch = "wasm32"))] + card_listing: Option<(ListingKey, String)>, +} + +/// What an endpoint's models are listed by: its protocol, its base URL, and whether a key goes along. +type ListingKey = (Protocol, String, bool); + +/// Most endpoints' listings kept. +const ENDPOINT_LISTINGS_CAP: usize = 128; + +/// The listing of `base_url`, if that is an address. A key goes along only where it may be sent. +fn listing_key(protocol: Protocol, base_url: &str, with_key: bool) -> Option { + let url = agents::normalize_url(base_url).ok().filter(|url| url.len() <= 4096)?; + let with_key = with_key && agents::key_safe_for(&url); + Some((protocol, url, with_key)) +} + +/// The models listed for `key`, and the note for under them: still listing, or why it could not. +fn listed_for<'a>( + listings: &'a std::collections::HashMap, String>>, + key: Option<&ListingKey>, +) -> (&'a [acp::ModelInfo], Option) { + match key.and_then(|key| listings.get(key)) { + Some(Ok(models)) if models.is_empty() => (&[], Some(tr("ui.agent_chat_models_none").to_string())), + Some(Ok(models)) => (models, None), + Some(Err(error)) => (&[], Some(trf("ui.agent_chat_models_failed", &[("error", error)]))), + None => (&[], key.map(|_| tr("ui.agent_chat_models_listing").to_string())), + } +} + +/// Whether a listing is worth asking for again: it failed, or it listed nothing. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn listing_wants_retry(listing: Option<&Result, String>>) -> bool { + match listing { + Some(Err(_)) => true, + Some(Ok(models)) => models.is_empty(), + None => false, + } +} + +/// `models` as a model picker's rows: the id chooses, the endpoint's name for it is searched too. +fn model_choices<'a>(models: &'a [acp::ModelInfo], rows: &'a [(String, Option, String)]) -> Vec> { + models.iter().zip(rows).map(|(m, (label, group, tip))| ui_kit::SearchChoice { value: &m.id, label, tip, group: group.as_deref() }).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +struct ModelListing { + key: ListingKey, + rx: std::sync::mpsc::Receiver, String>>, +} + +/// List an endpoint's models in the background, one listing at a time; a finished one stays until +/// it is asked for again. `secret` runs on that thread too: a keychain may take its time to answer. +#[cfg(not(target_arch = "wasm32"))] +fn start_listing(app: &mut SolveApp, ctx: &egui::Context, key: ListingKey, secret: impl FnOnce() -> Result, String> + Send + 'static) { + let state = &mut app.agent_chat.settings; + if state.listing.is_some() || state.endpoint_models.contains_key(&key) { + return; + } + if state.endpoint_models.len() >= ENDPOINT_LISTINGS_CAP { + state.endpoint_models.clear(); + } + let Some(http) = app.services.agent_http.clone() else { + state.endpoint_models.insert(key, Err(tr("ui.ai_no_http").to_string())); + return; + }; + let (tx, rx) = std::sync::mpsc::channel(); + let (protocol, url) = (key.0, key.1.clone()); + let language = crate::i18n::language(); + let wake = ctx.clone(); + let spawned = std::thread::Builder::new().name("endpoint-models".into()).spawn(move || { + let _language = crate::i18n::scope(language); + let list = secret().and_then(|secret| match protocol { + Protocol::OpenAi => super::api_client::model_list(&http, &url, secret.as_deref()), + Protocol::Anthropic => super::api_client::anthropic_model_list(&http, &url, secret.as_deref()), + }); + let _ = tx.send(list); + wake.request_repaint(); + }); + match spawned { + Ok(_) => state.listing = Some(ModelListing { key, rx }), + Err(e) => { + state.endpoint_models.insert(key, Err(e.to_string())); + } + } +} + +/// Take in a finished listing, and start the one an agent card asked for. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn poll_listing(app: &mut SolveApp, ctx: &egui::Context) { + use std::sync::mpsc::TryRecvError; + let state = &mut app.agent_chat.settings; + if let Some(listing) = &state.listing { + let result = match listing.rx.try_recv() { + Ok(result) => result, + Err(TryRecvError::Disconnected) => Err(tr("ui.ai_no_answer").to_string()), + Err(TryRecvError::Empty) => return, + }; + state.endpoint_models.insert(listing.key.clone(), result); + state.listing = None; + } + let Some((key, agent)) = state.card_listing.take() else { return }; + let secrets = app.services.secrets.clone().filter(|_| key.2); + start_listing(app, ctx, key, move || match secrets { + Some(secrets) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])), + None => Ok(None), + }); +} + +/// The Add dialog's listing, of what its fields said when last left, never of a half-typed address. +#[cfg(not(target_arch = "wasm32"))] +fn list_for_dialog(app: &mut SolveApp, ctx: &egui::Context) { + let state = &mut app.agent_chat.settings; + let Some(s) = state.add.as_mut().filter(|s| s.kind == AddKind::Api) else { return }; + let typed = Some(s.key.trim().to_string()).filter(|typed| !typed.is_empty()); + // Editing an agent whose key is kept: the listing goes with that key, read on its thread. + let stored = s.editing.clone().filter(|_| s.saved_key && typed.is_none()); + if std::mem::take(&mut s.list_again) { + s.listing = listing_key(s.protocol, &s.base_url, typed.is_some() || stored.is_some()); + // Asked again: what failed may work now, with another key or the server back up. + if let Some(key) = &s.listing + && listing_wants_retry(state.endpoint_models.get(key)) + { + state.endpoint_models.remove(key); + } + } + let Some(key) = s.listing.clone() else { return }; + if state.listing.is_some() || state.endpoint_models.contains_key(&key) { + return; + } + let typed = typed.filter(|_| key.2); + let stored = stored.filter(|_| key.2).and_then(|agent| app.services.secrets.clone().map(|secrets| (secrets, agent))); + start_listing(app, ctx, key, move || match stored { + Some((secrets, agent)) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])), + None => Ok(typed), + }); } #[cfg(not(target_arch = "wasm32"))] @@ -171,6 +316,7 @@ pub fn open_add(app: &mut SolveApp) { base_url: preset.map(|p| p.base_url.to_string()).unwrap_or_default(), name: preset.map(|p| p.name.to_string()).unwrap_or_default(), request_timeout_s: agents::DEFAULT_REQUEST_TIMEOUT_S, + list_again: true, ..Default::default() }); } @@ -185,6 +331,7 @@ pub fn open_edit(app: &mut SolveApp, id: &str) -> bool { request_timeout_s: c.request_timeout_s.clamp(agents::MIN_REQUEST_TIMEOUT_S, agents::MAX_REQUEST_TIMEOUT_S), reasoning_effort: c.reasoning_effort.clone(), editing: Some(c.id.clone()), + list_again: true, ..Default::default() }; if c.kind.is_api() { @@ -222,6 +369,7 @@ pub(super) fn choose_preset(s: &mut AddState, protocol: Protocol, index: usize) } s.error = None; s.test = None; + s.list_again = true; } /// Run a connection test in the background (it starts the agent briefly, or asks the endpoint @@ -455,6 +603,7 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { let mut edit: Option = None; let mut retimed: Option<(String, u64)> = None; let mut reeffort: Option<(String, String)> = None; + let mut picked_model: Option<(String, ui_kit::Picked)> = None; let t = crate::theme::Tokens::get(); ui_kit::settings_section(ui, "agents", tr("ui.ai_agents"), |ui| { if app.agent_chat.detecting.is_some() { @@ -545,6 +694,55 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { None => {} } }); + if let Some(protocol) = entry.kind.protocol() { + ui_kit::row(ui, tr("ui.ai_model"), |ui| { + let chat = &mut app.agent_chat; + let running = chat.running_id == entry.id && chat.backend.is_some(); + let key = listing_key(protocol, &entry.base_url, entry.key); + let (models, note) = if running { + (chat.models.as_slice(), chat.models_note.clone()) + } else if let Some(models) = chat.models_cache.get(&entry.base_url).filter(|models| !models.is_empty()) { + (models.as_slice(), None) + } else { + listed_for(&chat.settings.endpoint_models, key.as_ref()) + }; + let listed = !models.is_empty(); + let rows = super::model_rows(models); + let choices = model_choices(models, &rows); + let id = format!("sc_ai_model:{}", entry.id); + let handles = format!("prefs:ai_model:{}", entry.id); + let picker = ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: &id, + handles: &handles, + current: &entry.model, + current_value: &entry.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: note.as_deref(), + open_group: None, + enabled: true, + }, + ); + // Nobody is asked until the picker opens: not for looking at this page. + if picker.response.clicked() + && !running + && !listed + && let Some(key) = key + { + // Asked again: what failed may work now. + if listing_wants_retry(chat.settings.endpoint_models.get(&key)) { + chat.settings.endpoint_models.remove(&key); + } + chat.settings.card_listing = Some((key, entry.id.clone())); + } + if let Some(pick) = picker.inner { + picked_model = Some((entry.id.clone(), pick)); + } + }); + } }); if entry.kind == Kind::Api && let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == entry.id) @@ -594,6 +792,25 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some(id) = edit { open_edit(app, &id); } + if let Some((id, pick)) = picked_model { + if app.agent_chat.running_id == id && app.agent_chat.backend.is_some() { + match pick { + ui_kit::Picked::Listed(model) => set_model(app, &model), + ui_kit::Picked::Custom(model) => { + set_custom_model(app, &model); + } + } + } else { + let (ui_kit::Picked::Listed(model) | ui_kit::Picked::Custom(model)) = pick; + let model = model.trim(); + if model_id_valid(model) { + if let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == id) { + c.model = model.to_string(); + } + app.preferences.agent_models.insert(id, model.to_string()); + } + } + } // The running conversation uses a new timeout from its next request on. if let Some((id, secs)) = retimed && app.agent_chat.running_id == id @@ -748,10 +965,34 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { ui_kit::text_field(ui, &mut s.name, ""); }); ui_kit::row(ui, tr("ui.ai_base_url"), |ui| { - ui_kit::text_field(ui, &mut s.base_url, tr("ui.ai_url_hint")); + s.list_again |= + ui_kit::cell_editor(ui, egui::Id::new("sc_ai_add_url"), &mut s.base_url, tr("ui.ai_url_hint"), false).lost_focus(); }); ui_kit::row(ui, tr("ui.ai_model"), |ui| { - ui_kit::text_field(ui, &mut s.model, tr("ui.ai_model_hint")); + let (models, note) = listed_for(&app.agent_chat.settings.endpoint_models, s.listing.as_ref()); + let rows = super::model_rows(models); + let choices = model_choices(models, &rows); + let current = if s.model.is_empty() { tr("ui.agent_chat_choose_model") } else { s.model.as_str() }; + let picker = ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: "sc_ai_add_model", + handles: "ai_add:model", + current, + current_value: &s.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: note.as_deref(), + open_group: None, + enabled: true, + }, + ); + s.list_again |= picker.response.clicked(); + if let Some(ui_kit::Picked::Listed(model) | ui_kit::Picked::Custom(model)) = picker.inner { + s.model = model; + s.error = None; + } }); ui_kit::row(ui, tr("ui.ai_request_timeout"), |ui| { timeout_field(ui, &mut s.request_timeout_s, "ai_add:request_timeout"); @@ -764,6 +1005,7 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { let hint = tr(if s.saved_key { "ui.ai_key_keep_hint" } else { "ui.ai_key_hint" }); let r = ui_kit::password_field(ui, egui::Id::new("sc_ai_add_key"), &mut s.key, hint); crate::scenario::publish_target("ai_add:key", r.rect); + s.list_again |= r.lost_focus(); }); }); ui_kit::text(ui, tr(if has_keychain { "ui.ai_key_note" } else { "ui.ai_no_keychain" }), ui_kit::Text::Note("keychain")); @@ -782,6 +1024,8 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { } add |= action == ui_kit::Action::Ok; open &= !closed && action != ui_kit::Action::Cancel; + #[cfg(not(target_arch = "wasm32"))] + list_for_dialog(app, ctx); if test { #[cfg(not(target_arch = "wasm32"))] if let Some(s) = app.agent_chat.settings.add.as_ref() { @@ -1179,4 +1423,267 @@ mod card_tests { assert_eq!(add_agent(&mut h.app), Err(tr("ui.ai_edit_gone").to_string())); assert!(h.app.preferences.agents.is_empty()); } + + /// An `agent_http` that may not be called on the window's thread: it answers `/models` as + /// OpenRouter does, or 401 for an address with `refused` in it, and records what it was asked. + fn listing_http(h: &mut Harness) -> std::sync::Arc>> { + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = seen.clone(); + let ui_thread = std::thread::current().id(); + h.app.services.agent_http = Some(std::sync::Arc::new(move |request: &super::super::backend::HttpRequest| { + assert_ne!(std::thread::current().id(), ui_thread); + // The running agent's capability check goes through here too. + if request.url.ends_with("/models") + && let Ok(mut log) = log.lock() + { + log.push((request.url.clone(), request.headers.iter().any(|(name, _)| name == "Authorization"))); + } + if request.url.contains("refused") { + return Ok((401, br#"{"error":{"message":"no such key"}}"#.to_vec())); + } + if request.url.contains("/page/") { + return Ok((200, b"Control UI".to_vec())); + } + if request.url.contains("/empty/") { + return Ok((200, br#"{"data":[]}"#.to_vec())); + } + Ok((200, json!({"data": [{"id": "vendor/big", "name": "Vendor: Big"}, {"id": "vendor/small"}]}).to_string().into_bytes())) + })); + seen + } + + /// A web page where the models should be, or a list with nothing in it, says so under the + /// picker, and is asked for again the next time. + #[test] + fn a_listing_that_is_no_list_or_lists_nothing_says_so_and_is_asked_again() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().len(); + open_add(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests(), 1); + let note = |h: &Harness| { + let add = h.app.agent_chat.settings.add.as_ref().unwrap(); + listed_for(&h.app.agent_chat.settings.endpoint_models, add.listing.as_ref()).1.unwrap_or_default() + }; + // What the dialog's listing holds for the fields as they are (the words are the language's). + let listing = |h: &Harness| { + let add = h.app.agent_chat.settings.add.as_ref().unwrap(); + add.listing.as_ref().and_then(|key| h.app.agent_chat.settings.endpoint_models.get(key)).cloned() + }; + let ask = |h: &mut Harness, url: &str| { + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = url.into(); + add.list_again = true; + list_settled(h); + }; + ask(&mut h, "http://localhost:18789/page/v1"); + assert_eq!(requests(), 2); + assert!(matches!(listing(&h), Some(Err(_))), "a page where the list should be is an error: {:?}", listing(&h)); + assert!(!note(&h).is_empty(), "and the picker says so"); + ask(&mut h, "http://localhost:18789/page/v1"); + assert_eq!(requests(), 3, "a page where the list should be is asked for again"); + ask(&mut h, "http://localhost:18789/empty/v1"); + assert_eq!(requests(), 4); + assert!(matches!(listing(&h), Some(Ok(models)) if models.is_empty()), "{:?}", listing(&h)); + assert!(!note(&h).is_empty(), "an empty list is said so too"); + ask(&mut h, "http://localhost:18789/empty/v1"); + assert_eq!(requests(), 5, "an empty list is asked for again"); + ask(&mut h, "http://localhost:11434/v1"); + assert_eq!(requests(), 5, "a list that had models is kept"); + assert_eq!(note(&h), ""); + } + + /// Editing an endpoint whose key is kept lists its models at once, with that key from the + /// keychain (never shown). + #[test] + fn editing_an_endpoint_lists_with_its_stored_key() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let keys = std::sync::Arc::new(MemoryKeys::default()); + h.app.services.secrets = Some(keys.clone()); + keys.set("api-1", "test-key-1").unwrap(); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().clone(); + h.app.preferences.agents.push(AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: Kind::Api, + base_url: "https://openrouter.ai/api/v1".into(), + model: "vendor/big".into(), + key: true, + ..Default::default() + }); + h.call("ui.prefs", json!({"open": "AI"})); + h.frames(3); + assert!(open_edit(&mut h.app, "api-1")); + list_settled(&mut h); + assert_eq!(requests(), [("https://openrouter.ai/api/v1/models".to_string(), true)], "listed on opening, with the kept key"); + assert!(h.app.agent_chat.settings.add.as_ref().unwrap().key.is_empty(), "the kept key stays out of the field"); + } + + fn list_settled(h: &mut Harness) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + h.frames(2); + while (h.app.agent_chat.settings.listing.is_some() || h.app.agent_chat.settings.card_listing.is_some()) + && std::time::Instant::now() < deadline + { + std::thread::sleep(std::time::Duration::from_millis(1)); + h.frames(1); + } + assert!(h.app.agent_chat.settings.listing.is_none()); + h.frames(2); + } + + /// The dialog lists an endpoint's models off the window's thread, once per endpoint and key, of + /// what the fields say when they are left and not while they are typed in; a key goes only + /// where it may. A row and a typed model both fill the field, and Add takes either. + #[test] + fn the_add_dialog_lists_an_endpoints_models_once_and_takes_a_row_or_a_typed_model() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().clone(); + open_add(&mut h.app); + h.frames(3); + assert!(requests().is_empty(), "no endpoint chosen yet"); + h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests(), [("http://localhost:11434/v1/models".to_string(), false)]); + h.frames(5); + assert_eq!(requests().len(), 1, "once"); + + h.step(&json!({"click":{"handle":"ai_add:preset"}})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:preset:OpenRouter"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests().last().cloned(), Some(("https://openrouter.ai/api/v1/models".to_string(), false))); + + // Typed in: no request until the field is left, which here the flag stands for. + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "http://10.0.0.2:1234/v1".into(); + add.key = "not-a-real-key".into(); + h.frames(5); + assert_eq!(requests().len(), 2, "not while it is typed"); + h.app.agent_chat.settings.add.as_mut().unwrap().list_again = true; + list_settled(&mut h); + assert_eq!( + requests().last().cloned(), + Some(("http://10.0.0.2:1234/v1/models".to_string(), false)), + "no key over plain http to another computer" + ); + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://openrouter.ai/api/v1".into(); + add.list_again = true; + list_settled(&mut h); + assert_eq!(requests().last().cloned(), Some(("https://openrouter.ai/api/v1/models".to_string(), true)), "with a key is another listing"); + + // A row and a typed model. + assert!(scenario::handle_at("ai_add:model").is_some()); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + h.frames(3); + assert!(scenario::handle_at("ai_add:model:search").is_some()); + assert!(scenario::handle_at("ai_add:model:group:Vendor").is_some(), "an endpoint's vendors are the groups"); + h.step(&json!({"click":{"handle":"ai_add:model:vendor/big"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().model, "vendor/big"); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text":"vendor/own:free"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().model, "vendor/own:free"); + assert_eq!(requests().len(), 4, "opening the picker asks nobody again"); + + // A refusal shows in the popup, and opening it again asks again. + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://refused.example/v1".into(); + add.key.clear(); + add.list_again = true; + list_settled(&mut h); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests().len(), 6, "asked again on opening"); + let listing = h.app.agent_chat.settings.add.as_ref().unwrap().listing.clone(); + let (models, note) = listed_for(&h.app.agent_chat.settings.endpoint_models, listing.as_ref()); + assert!(models.is_empty()); + assert!(note.as_deref().is_some_and(|note| note.contains("no such key")), "{note:?}"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(3); + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://openrouter.ai/api/v1".into(); + h.step(&json!({"click":{"handle":"ai_add:add"}})).unwrap(); + assert!(h.app.agent_chat.settings.add.is_none()); + assert_eq!(h.app.preferences.agents.last().map(|a| a.model.as_str()), Some("vendor/own:free")); + } + + /// The keychain answers on the listing's thread, not on the window's. + struct KeyOffTheWindow(std::thread::ThreadId); + impl super::super::backend::Secrets for KeyOffTheWindow { + fn get(&self, _: &str) -> Result, String> { + assert_ne!(std::thread::current().id(), self.0); + Ok(Some("not-a-real-key".into())) + } + fn set(&self, _: &str, _: &str) -> Result<(), String> { + Ok(()) + } + fn delete(&self, _: &str) -> Result<(), String> { + Ok(()) + } + } + + /// An endpoint's card has a model row. The page asks nobody; opening the picker lists, with the + /// agent's key from the keychain, and a row or a typed model becomes an idle agent's model. + #[test] + fn the_card_lists_when_its_picker_opens_and_changes_an_idle_endpoints_model() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + h.app.services.secrets = Some(std::sync::Arc::new(KeyOffTheWindow(std::thread::current().id()))); + let seen = listing_http(&mut h); + h.app.preferences.agents.push(AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: Kind::Api, + base_url: "http://localhost:1/v1".into(), + model: "local".into(), + key: true, + ..Default::default() + }); + h.step(&json!({"call":"ui.prefs","params":{"open":"AI"}})).unwrap(); + h.frames(4); + assert!(scenario::handle_at("prefs:ai_model:api-1").is_some()); + assert!(seen.lock().unwrap().is_empty(), "looking at the page asks nobody"); + + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1"}})).unwrap(); + list_settled(&mut h); + assert_eq!(*seen.lock().unwrap(), [("http://localhost:1/v1/models".to_string(), true)]); + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1:vendor/big"}})).unwrap(); + h.frames(3); + let model = |h: &Harness| h.app.preferences.agents.iter().find(|a| a.id == "api-1").map(|a| a.model.clone()); + assert_eq!(model(&h).as_deref(), Some("vendor/big")); + assert_eq!(h.app.preferences.agent_models.get("api-1").map(String::as_str), Some("vendor/big")); + + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + h.step(&json!({"text":" vendor/own "})).unwrap(); + h.frames(3); + assert!(h.ctx.memory(|m| m.has_focus(egui::Id::new("sc_ai_model:api-1").with("search"))), "the box keeps the focus over Preferences"); + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1:custom"}})).unwrap(); + h.frames(3); + assert_eq!(model(&h).as_deref(), Some("vendor/own")); + assert_eq!(h.app.preferences.agent_models.get("api-1").map(String::as_str), Some("vendor/own")); + assert_eq!(seen.lock().unwrap().len(), 1, "listed once"); + } } diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 11a1be2a6..be1652902 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1400,6 +1400,83 @@ fn models_reply(current: &str) -> Event { Event::Models { current: current.into(), available: vec![m("fast"), m("smart")] } } +/// An endpoint's listing whose ids read `vendor/model` and whose names (the descriptions here) read +/// `Vendor: Model`, as OpenRouter's, names its providers; the rows then read the model's name with +/// the id as the tooltip. One vendor is one flat list. +#[test] +fn an_endpoints_vendor_named_listing_names_its_providers() { + let m = |id: &str, description: &str| acp::ModelInfo { id: id.into(), name: id.into(), description: description.into() }; + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra")), Some(("OpenAI".into(), "GPT-6.1 Terra".into()))); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra\nmore")), Some(("OpenAI".into(), "GPT-6.1 Terra".into()))); + assert_eq!(model_provider(&m("gpt-6.1-terra", "OpenAI: GPT-6.1 Terra")), None, "no vendor in the id"); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: ")), None, "no name"); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "")), None); + assert_eq!( + model_provider(&m("openai/gpt-6.1-terra", "Provider: Host • current")), + Some(("Host".into(), "openai/gpt-6.1-terra".into())), + "an agent's own word first" + ); + let rows = model_rows(&[m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra"), m("qwen/qwen3.8-flash", "Qwen: Qwen3.8 Flash"), m("free-model", "")]); + assert_eq!( + rows, + [ + ("GPT-6.1 Terra".to_string(), Some("OpenAI".to_string()), "openai/gpt-6.1-terra".to_string()), + ("Qwen3.8 Flash".to_string(), Some("Qwen".to_string()), "qwen/qwen3.8-flash".to_string()), + ("free-model".to_string(), Some(tr("ui.agent_chat_provider_other").to_string()), String::new()), + ] + ); + let rows = model_rows(&[m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra"), m("openai/gpt-5.6-luna", "OpenAI: GPT-5.6 Luna")]); + assert_eq!(rows[0], ("openai/gpt-6.1-terra".to_string(), None, "OpenAI: GPT-6.1 Terra".to_string()), "one vendor is one flat list"); +} + +/// Models from several providers fold under their providers inside the picker: the current model's +/// provider is open and the others folded; a header opens or folds its group; a typed search opens +/// every group with a match but one folded by hand; the provider asked for over the control channel +/// is open at the next opening. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_header_groups_models_by_provider_and_folds_them() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "claude".into(); + let m = |id: &str, name: &str| acp::ModelInfo { id: id.into(), name: name.into(), description: String::new() }; + script.report(Event::Models { + current: "a".into(), + available: vec![m("a", "Host · Alpha"), m("c", "Nous Portal · Gamma"), m("b", "Host · Beta"), m("d", "Nous Portal · Delta")], + }); + h.frames(4); + assert!(handle_at("agent_chat:provider").is_none(), "no provider drop-down of its own"); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:group:Host").is_some() && handle_at("agent_chat:model:group:Nous Portal").is_some()); + assert!(handle_at("agent_chat:model:a").is_some() && handle_at("agent_chat:model:b").is_some(), "the current model's provider is open"); + assert!(handle_at("agent_chat:model:c").is_none() && handle_at("agent_chat:model:d").is_none(), "the other provider is folded"); + h.step(&json!({"click": {"handle": "agent_chat:model:group:Nous Portal"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:c").is_some(), "a header opens its group"); + h.step(&json!({"click": {"handle": "agent_chat:model:group:Host"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:a").is_none(), "and folds it"); + h.step(&json!({"text": "ta"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:b").is_none(), "a fold made by hand stays while searching, Beta or not"); + assert!(handle_at("agent_chat:model:d").is_some() && handle_at("agent_chat:model:c").is_none(), "Delta matches, Gamma does not"); + h.step(&json!({"click": {"handle": "agent_chat:model:d"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: d"]); + assert_eq!(h.app.agent_chat.model, "d"); + assert!(handle_at("agent_chat:model:search").is_none(), "a choice closes it"); + + control(&mut h.app, &h.ctx, &json!({"provider": "Host"})).unwrap(); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:a").is_some(), "the provider asked for is open"); + assert!(handle_at("agent_chat:model:d").is_some(), "and the current model's"); +} + /// Choosing a model tells the agent, shows it as current and remembers it for this agent; a model /// the agent did not offer is ignored. #[test] @@ -1423,6 +1500,388 @@ fn choosing_a_model_sets_it_and_remembers_it() { assert_eq!(app.agent_chat.models.len(), 2, "the list stays"); } +/// A scripted endpoint: its agent is configured, and it is running with these models. +#[cfg(not(target_arch = "wasm32"))] +fn endpoint_with_script() -> (SolveApp, Script, egui::Context) { + let (mut app, script, ctx) = app_with_script(); + let endpoint = "http://localhost:11434/v1"; + app.agent_chat.running_id = "api-1".into(); + app.agent_chat.running_endpoint = endpoint.into(); + app.preferences.agents.push(agents::AgentConfig { + id: "api-1".into(), + kind: agents::Kind::Api, + base_url: endpoint.into(), + model: "fast".into(), + ..Default::default() + }); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + (app, script, ctx) +} + +/// A typed model goes straight to an endpoint, joins the list for the next connection and becomes +/// the agent's default. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_typed_model_goes_to_an_endpoint_and_is_remembered() { + let (mut app, script, _ctx) = endpoint_with_script(); + assert!(custom_models_accepted(&app)); + assert!(set_custom_model(&mut app, " openai/gpt-x ")); + assert_eq!(script.calls(), ["set_model: openai/gpt-x"]); + assert_eq!(app.agent_chat.models.first().map(|m| m.id.as_str()), Some("openai/gpt-x")); + assert_eq!(app.agent_chat.models_cache.get("http://localhost:11434/v1").and_then(|l| l.first()).map(|m| m.id.as_str()), Some("openai/gpt-x")); + assert_eq!(app.preferences.agents.iter().find(|a| a.id == "api-1").unwrap().model, "openai/gpt-x"); + assert_eq!(app.preferences.agent_models.get("api-1").map(String::as_str), Some("openai/gpt-x")); + assert_eq!(status(&app)["model"], "openai/gpt-x"); + assert_eq!(status(&app)["customModels"], true); + let listed = app.agent_chat.models.len(); + assert!(set_custom_model(&mut app, "smart")); + assert_eq!(app.agent_chat.models.len(), listed, "a listed id goes the usual way"); + assert_eq!(app.agent_chat.model, "smart"); +} + +/// A typed model is only sent when it could be a model at all, and the list stays within its cap. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_typed_model_that_cannot_be_one_is_not_sent() { + let (mut app, script, _ctx) = endpoint_with_script(); + for text in ["", " ", "x".repeat(MODEL_ID_CAP + 1).as_str(), "bell\u{7}", "two\nlines"] { + assert!(!set_custom_model(&mut app, text), "{text:?}"); + } + assert!(script.calls().is_empty()); + assert!(set_custom_model(&mut app, &"x".repeat(MODEL_ID_CAP))); + app.agent_chat.models = + (0..MODEL_LIST_CAP).map(|i| acp::ModelInfo { id: format!("m{i}"), name: String::new(), description: String::new() }).collect(); + assert!(set_custom_model(&mut app, "one-more")); + assert_eq!(app.agent_chat.models.len(), MODEL_LIST_CAP); + assert_eq!(app.agent_chat.models.first().map(|m| m.id.as_str()), Some("one-more")); +} + +/// An agent with a model option gets a typed model through it. Nothing changes until it answers, +/// and a refusal leaves the old model with the agent's reason in the chat. +#[test] +fn a_typed_model_is_sent_to_a_modern_agent_and_a_rejection_keeps_the_old_one() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "modern".into(); + script.report(Event::ConfigOptions(modern_options("fast"))); + poll(&mut app, &ctx); + assert!(custom_models_accepted(&app)); + assert!(set_custom_model(&mut app, "claude-x")); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=claude-x"]); + assert!(app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + assert!(!set_custom_model(&mut app, "claude-y"), "one request at a time"); + + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Err("no such model".into()) }); + poll(&mut app, &ctx); + assert!(!app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + assert!( + app.agent_chat + .items + .iter() + .any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("claude-x") && text.contains("no such model"))), + "the notice names the model and the reason" + ); + assert!(!app.preferences.agent_models.contains_key("modern")); + assert_eq!(app.agent_chat.typed_model, None); + + // An agent that takes it says so in its snapshot, and that is what is remembered. + assert!(set_custom_model(&mut app, "claude-x")); + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("claude-x")) }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "claude-x"); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("claude-x")); +} + +/// A legacy agent shows a typed model at once; a refusal puts everything back and says why. +#[test] +fn a_typed_model_is_sent_to_a_legacy_agent_and_a_rejection_reverts_it() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "claude".into(); + app.preferences.agent_models.insert("claude".into(), "fast".into()); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert!(set_custom_model(&mut app, "zzz")); + assert_eq!(script.calls(), ["set_model: zzz"]); + assert_eq!(app.agent_chat.model, "zzz"); + assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("zzz")); + + script.report(Event::ModelRejected("no such model".into())); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.agent_chat.models.iter().map(|m| m.id.as_str()).collect::>(), ["fast", "smart"]); + assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("fast")); + assert!( + app.agent_chat + .items + .iter() + .any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("zzz") && text.contains("no such model"))), + "the notice names the model and the reason" + ); + + // A listed model the agent refuses goes back too, and nothing was remembered before it here. + app.preferences.agent_models.remove("claude"); + set_model(&mut app, "smart"); + script.report(Event::ModelRejected("x".repeat(MODELS_NOTE_CAP * 2))); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.agent_chat.models.len(), 2); + assert!(!app.preferences.agent_models.contains_key("claude")); + let Some(Item::Notice { text, .. }) = app.agent_chat.items.last() else { panic!("no notice") }; + assert_eq!(text.chars().count(), MODELS_NOTE_CAP); + + // The agent confirming its model ends the wait: a later refusal has nothing to put back. + assert!(set_custom_model(&mut app, "zzz")); + script.report(Event::Models { current: "zzz".into(), available: vec![] }); + script.report(Event::ModelRejected("late".into())); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "zzz"); +} + +/// An agent that lists no models and has no model option cannot be sent one; a stopped one neither. +#[test] +fn an_agent_without_models_takes_no_typed_model() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "other".into(); + script.report(Event::Ready { agent: "fake".into(), images: false }); + poll(&mut app, &ctx); + assert!(!custom_models_accepted(&app)); + assert_eq!(status(&app)["customModels"], false); + assert!(!set_custom_model(&mut app, "zzz")); + assert!(script.calls().is_empty()); + script.report(Event::ConfigOptions(vec![])); + poll(&mut app, &ctx); + assert!(!custom_models_accepted(&app), "its options name no model"); + + let (mut app, script, ctx) = app_with_script(); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert!(custom_models_accepted(&app)); + app.agent_chat.backend = None; + assert!(!custom_models_accepted(&app)); + assert!(!set_custom_model(&mut app, "zzz")); +} + +/// The control channel's `model`: a listed one as before, an unlisted one when the agent takes +/// typed models, otherwise ignored as before. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_control_channel_sends_an_unlisted_model_where_it_can_go() { + let (mut app, script, ctx) = endpoint_with_script(); + let reply = control(&mut app, &ctx, &json!({"model": "smart"})).unwrap(); + assert_eq!(reply["model"], "smart"); + let reply = control(&mut app, &ctx, &json!({"model": "unlisted"})).unwrap(); + assert_eq!(reply["model"], "unlisted"); + assert_eq!(reply["customModels"], true); + assert_eq!(reply["modelsNote"], Value::Null); + assert_eq!(script.calls(), ["set_model: smart", "set_model: unlisted"]); + + let (mut app, script, ctx) = app_with_script(); + let reply = control(&mut app, &ctx, &json!({"model": "unlisted"})).unwrap(); + assert_eq!(reply["model"], ""); + assert_eq!(reply["customModels"], false); + assert!(script.calls().is_empty()); +} + +/// The header's picker on an agent that lists models: it searches, a row chooses, and what was typed +/// can be chosen too. The control and the popup stay in a narrow chat's window. +#[test] +fn the_header_model_picker_searches_and_takes_a_typed_model() { + use crate::scenario::{handle_at, rect_of}; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "claude".into(); + script.report(models_reply("fast")); + h.frames(4); + let panel = rect_of("agent_chat:panel").expect("the panel"); + let control = rect_of("agent_chat:model").expect("the picker"); + assert!(control.left() >= panel.left() && control.right() <= panel.right(), "{control:?} in {panel:?}"); + assert!(handle_at("agent_chat:model:search").is_none(), "closed"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + for name in ["search", "fast", "smart"] { + assert!(handle_at(&format!("agent_chat:model:{name}")).is_some(), "{name}"); + } + assert!(handle_at("agent_chat:model:custom").is_none(), "nothing typed"); + let search = rect_of("agent_chat:model:search").expect("the search box"); + assert!(search.left() >= 0.0 && search.right() <= 1600.0, "inside the harness's window: {search:?}"); + + h.step(&json!({"text": "SMA"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:fast").is_none() && handle_at("agent_chat:model:smart").is_some()); + assert!(handle_at("agent_chat:model:custom").is_some(), "the typed text is not a listed model"); + h.step(&json!({"click": {"handle": "agent_chat:model:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart"]); + assert_eq!(h.app.agent_chat.model, "smart"); + assert!(handle_at("agent_chat:model:search").is_none(), "a choice closes it"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + h.step(&json!({"click": {"handle": "agent_chat:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart", "set_model: zzz"]); + assert_eq!(h.app.agent_chat.model, "zzz"); + disconnect(&mut h.app); +} + +/// The picker on an agent with a model option goes by the same names. A row and a typed model both +/// go through the option, and other options stay plain dropdowns. +#[test] +fn the_header_model_option_searches_and_takes_a_typed_model() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + script.report(Event::ConfigOptions(modern_options("fast"))); + h.frames(4); + assert_eq!(handle_at("agent_chat:model"), handle_at("agent_chat:config:some.provider.model")); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + for name in ["search", "fast", "smart"] { + assert!(handle_at(&format!("agent_chat:model:{name}")).is_some(), "{name}"); + assert_eq!(handle_at(&format!("agent_chat:model:{name}")), handle_at(&format!("agent_chat:config:some.provider.model:{name}"))); + } + h.step(&json!({"click": {"handle": "agent_chat:model:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=smart"]); + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + h.frames(3); + assert_eq!(h.app.agent_chat.model, "smart"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:custom").is_some()); + h.step(&json!({"click": {"handle": "agent_chat:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls().last().map(String::as_str), Some("set_config_option: some.provider.model=zzz")); + assert_eq!(h.app.agent_chat.model, "smart", "not until the agent says so"); + assert!(h.app.agent_chat.config_pending); + disconnect(&mut h.app); +} + +/// Nothing typed can be chosen where it could not be sent, and the reason a listing failed shows +/// in the popup. +#[test] +fn the_header_model_picker_offers_no_typed_model_it_cannot_send_and_shows_why_listing_failed() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.models = vec![acp::ModelInfo { id: "fast".into(), name: "fast".into(), description: String::new() }]; + h.app.agent_chat.model = "fast".into(); + h.app.agent_chat.models_note = Some("Couldn't list models: offline".into()); + h.frames(4); + assert!(!custom_models_accepted(&h.app)); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(h.widget("Couldn't list models: offline").is_some()); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:search").is_some()); + assert!(handle_at("agent_chat:model:custom").is_none()); +} + +/// A running endpoint's card uses the chat's list and changes the chat's model. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_card_of_a_running_endpoint_changes_the_chats_model() { + use crate::scenario::handle_at; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "api-1".into(); + h.app.agent_chat.running_endpoint = "http://localhost:1/v1".into(); + h.app.preferences.agents.push(agents::AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: agents::Kind::Api, + base_url: "http://localhost:1/v1".into(), + model: "fast".into(), + ..Default::default() + }); + script.report(models_reply("fast")); + h.step(&json!({"call": "ui.prefs", "params": {"open": "AI"}})).unwrap(); + h.frames(4); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + assert!(handle_at("prefs:ai_model:api-1:smart").is_some()); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart"]); + assert_eq!(h.app.agent_chat.model, "smart"); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart", "set_model: zzz"]); + assert_eq!(h.app.preferences.agents.iter().find(|a| a.id == "api-1").map(|a| a.model.as_str()), Some("zzz")); + disconnect(&mut h.app); +} + +/// A listing that fails says why and leaves last time's list, with the configured model in it; the +/// next connection starts without the note. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_listing_that_fails_says_why_and_keeps_the_list_of_last_time() { + let (mut app, script, ctx) = app_with_script(); + let endpoint = "http://localhost:11434/v1"; + app.agent_chat.running_endpoint = endpoint.into(); + script.report(Event::ModelsNote(None)); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.models_note, None); + let ids = |app: &SolveApp| app.agent_chat.models.iter().map(|m| m.id.clone()).collect::>(); + assert_eq!(ids(&app), ["fast", "smart"]); + + let only = |id: &str| acp::ModelInfo { id: id.into(), name: id.into(), description: String::new() }; + script.report(Event::ModelsNote(Some("x".repeat(MODELS_NOTE_CAP + 10)))); + script.report(Event::Models { current: "local".into(), available: vec![only("local")] }); + poll(&mut app, &ctx); + let note = app.agent_chat.models_note.clone().unwrap(); + assert!(note.starts_with(&trf("ui.agent_chat_models_failed", &[("error", "x")])), "{note}"); + assert_eq!(note.chars().count(), MODELS_NOTE_CAP); + assert_eq!(ids(&app), ["local", "fast", "smart"]); + assert_eq!(app.agent_chat.model, "local"); + assert_eq!(app.agent_chat.models_cache.get(endpoint).map(Vec::len), Some(2), "the failed listing is not remembered"); + + script.report(Event::ModelsNote(Some("again".into()))); + script.report(Event::Models { current: "fast".into(), available: vec![only("fast")] }); + poll(&mut app, &ctx); + assert_eq!(ids(&app), ["local", "fast", "smart"], "a model already listed is not listed twice"); + + // A real listing on an endpoint that cannot be reached. + let mut app = app_with_endpoints(); + app.agent_chat.models_note = Some("from before".into()); + app.agent_chat.agent_id = Some("api-1".into()); + connect(&mut app, &ctx); + assert_eq!(app.agent_chat.models_note, None); + let start = std::time::Instant::now(); + while app.agent_chat.models.is_empty() && start.elapsed() < std::time::Duration::from_secs(10) { + poll(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(app.agent_chat.models_note.as_deref().is_some_and(|note| note.contains("offline")), "{:?}", app.agent_chat.models_note); + assert_eq!(ids(&app), ["m"]); + assert!(models_shown(&app)); + disconnect(&mut app); +} + /// The next session puts back the model chosen last time, when the agent offers it. #[test] fn the_remembered_model_is_set_on_the_next_session() { @@ -1944,7 +2403,8 @@ done } /// An agent that lists `models` but does not serve the unstable `session/set_model` answers -/// "method not found": the choice stays and no error shows (#9970). Other errors still show. +/// "method not found": the choice stays and no error shows (#9970). Other errors still show, as +/// the refusal of the model they were about. #[cfg(unix)] #[test] fn set_model_method_not_found_shows_no_error() { @@ -1986,12 +2446,13 @@ done set_model(&mut app, "fast"); // Replies come in order: once the second one's error shows, the first reply was handled too. let t = std::time::Instant::now(); - while !errors(&app).iter().any(|e| e == "model unavailable") { + let refused = trf("ui.agent_chat_model_rejected", &[("model", "fast"), ("error", "model unavailable")]); + while !errors(&app).contains(&refused) { poll(&mut app, &ctx); assert!(t.elapsed() < std::time::Duration::from_secs(20), "no error for the second choice: {:?}", errors(&app)); std::thread::sleep(std::time::Duration::from_millis(10)); } - assert_eq!(errors(&app), ["model unavailable"], "method not found is no error to show"); + assert_eq!(errors(&app), [refused], "method not found is no error to show"); assert!(app.agent_chat.state().running(), "the chat goes on"); assert_eq!(std::fs::read_to_string(&log).unwrap().matches("session/set_model").count(), 2); disconnect(&mut app); @@ -3703,3 +4164,101 @@ fn tool_room_beside_the_docked_assistant_survives_an_inside_out_view() { assert!(free.min.x.is_finite() && free.max.x.is_finite(), "{side}: {free:?}"); } } + +// ---- Copy message (#10675) ---- + +/// A chat with a multi-paragraph prompt and a Markdown reply, both drawn. +fn chat_with_copiable_messages() -> crate::scenario::Harness { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::User { + text: "make a plate\n\nwith two holes:\n- 6 mm\n- 8 mm".into(), + image: false, + pictures: Vec::new(), + files: Vec::new(), + context: Context::default(), + }); + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```".into() }); + h.frames(3); + h +} + +/// The text the last frame copied to the clipboard, if any. +fn copied_text(h: &crate::scenario::Harness) -> Option { + h.output.commands.iter().rev().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }) +} + +fn click_at(h: &mut crate::scenario::Harness, at: egui::Pos2, button: egui::PointerButton) { + h.frame_with(vec![egui::Event::PointerMoved(at)]); + h.frame_with(vec![egui::Event::PointerButton { pos: at, button, pressed: true, modifiers: egui::Modifiers::NONE }]); + h.frame_with(vec![egui::Event::PointerButton { pos: at, button, pressed: false, modifiers: egui::Modifiers::NONE }]); +} + +/// The visible button on a sent prompt copies the whole prompt, as entered. +#[test] +fn the_copy_message_button_copies_the_prompt_as_entered() { + let mut h = chat_with_copiable_messages(); + let at = crate::scenario::handle_at("agent_chat:copy:0").expect("the prompt's Copy message button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("make a plate\n\nwith two holes:\n- 6 mm\n- 8 mm"), "the whole prompt, paragraphs and list items"); +} + +/// The visible button on a reply copies its original Markdown: heading, paragraphs, list and +/// fenced code, not the laid-out text. +#[test] +fn the_copy_message_button_copies_the_reply_as_original_markdown() { + let mut h = chat_with_copiable_messages(); + let at = crate::scenario::handle_at("agent_chat:copy:1").expect("the reply's Copy message button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```")); +} + +/// Right-clicking a message opens its menu, and its row copies the same whole reply. +#[test] +fn right_clicking_a_message_offers_copy_message() { + let mut h = chat_with_copiable_messages(); + let msg = crate::scenario::rect_of("agent_chat:msg:1").expect("the reply's message area"); + click_at(&mut h, msg.center(), egui::PointerButton::Secondary); + h.frames(1); // let the popup settle at its final place before clicking its row + let item = crate::scenario::handle_at("agent_chat:copy_menu:1").expect("the right-click menu's Copy message row"); + click_at(&mut h, item, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```")); +} + +/// A reply that is still streaming copies the stable text received so far. +#[test] +fn a_streaming_reply_copies_the_text_received_so_far() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "half a repl".into() }); + h.frames(3); + let at = crate::scenario::handle_at("agent_chat:copy:0").expect("the streaming reply's button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("half a repl")); +} + +/// A picture-only prompt has no text to copy: no button, no menu, and a thought has none +/// either — the clipboard is never overwritten with an empty string. +#[test] +fn a_picture_only_prompt_and_a_thought_have_no_copy_message_action() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::User { + text: String::new(), + image: true, + pictures: Vec::new(), + files: Vec::new(), + context: Context::default(), + }); + h.app.agent_chat.items.push(Item::Agent { thought: true, text: "pondering".into() }); + h.frames(3); + assert!(crate::scenario::handle_at("agent_chat:copy:0").is_none(), "a picture-only prompt hides the text-copy action"); + assert!(crate::scenario::handle_at("agent_chat:copy:1").is_none(), "a thought has no copy action"); + assert!(h.widget("Copy message").is_none(), "nothing to click"); +} diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rs index 90576fd46..10b06f375 100644 --- a/crates/ui-egui/src/apply_off_thread_tests.rs +++ b/crates/ui-egui/src/apply_off_thread_tests.rs @@ -336,6 +336,42 @@ fn changed_first_cut_adopts_its_entire_suffix_without_window_evaluation() { assert!((redone - after_volume).abs() < 0.001); } +/// An edit in a dialog without a live preview (Offset Plane) is computed off the window thread +/// too: OK evaluates nothing here, the features after the plane included. +#[test] +fn an_edit_without_a_preview_adopts_its_suffix_without_window_evaluation() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.apply_off_thread = Some(Duration::ZERO); + h.app.run("construct.plane.offset", json!({"base":"XY","offset":10,"name":"Shelf"})).unwrap(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.app.run("solid.box", json!({"corner":[5,5,20],"length":10,"width":10,"height":5,"operation":"join"})).unwrap(); + let plane = h.app.session.doc.find_feature("Shelf").unwrap().id; + let undo = h.app.session.undo.len(); + h.call("ui.editFeature", json!({"feature":plane})); + h.frames(2); + assert!(h.app.dialog.as_ref().is_some_and(|d| !d.previews()), "Offset Plane has no live preview"); + if let Some(crate::dialogs::Kind::OffsetPlane { offset }) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + *offset = "15".into(); + } + let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default()); + solidcraft_engine::doc::progress::watch(window.clone(), || { + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + assert!(h.app.applying.is_some(), "computing beside the window"); + until_applied(&mut h); + }); + assert_eq!(window.features(), (0, 0), "nothing evaluated on the window thread"); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + assert_eq!(h.app.session.doc.marker, None); + assert_eq!(h.app.session.undo.len(), undo + 1); + let shelf = &h.app.session.doc.feature(plane).unwrap().kind; + assert!( + matches!(shelf, solidcraft_engine::doc::FeatureKind::ConstructionPlane { plane: solidcraft_engine::doc::PlaneRef::Offset { distance, .. } } if *distance == "15"), + "{shelf:?}" + ); + h.step(&json!({"expect":{"bodies":1,"volume":24500}})).unwrap(); +} + #[test] fn cancelling_an_edit_restores_pinned_geometry_without_evaluating_an_evicted_suffix() { let (mut h, target) = cut_chain(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 26297ad22..407e97dc4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -20,7 +20,7 @@ use crate::viewport::{Proj, projected_polygon}; /// direction a growing value points. pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { let st = crate::open_meshing::session_world(&app.session); - let first = d.inputs.first()?.items.first()?; + let first = &anchor_item(app, d)?; let (at, normal) = match first { Sel::Profile { sketch, index } => { let ss = st.sketch(*sketch)?; @@ -250,12 +250,44 @@ pub(crate) fn blend_grow_dir(m: &Mesh, index: usize, p: Vec3) -> Option { Some(if edge_concave(m, index, p).unwrap_or(false) { n } else { -n }) } +/// The pick the dialog's arrow sits on: the first, or for a fillet or chamfer reopened from a +/// click on one of its faces (Press Pull), its edge nearest the click, at the point on it nearest +/// the click (#4986). +fn anchor_item(app: &SolveApp, d: &Dialog) -> Option { + let items = &d.inputs.first()?.items; + let first = items.first()?.clone(); + let (Some(hint), Kind::Fillet { .. }) = (d.anchor_hint, &d.kind) else { return Some(first) }; + let st = crate::open_meshing::session_world(&app.session); + let nearest = items + .iter() + .filter_map(|s| { + let Sel::Edge { body, index, .. } = s else { return None }; + let at = nearest_on_polyline(st.body(body)?.mesh().edges.get(*index)?, hint)?; + Some((at.dist(hint), Sel::Edge { body: body.clone(), index: *index, point: at })) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)); + Some(nearest.map_or(first, |(_, s)| s)) +} + +/// The point of the polyline `pts` nearest `p`. +fn nearest_on_polyline(pts: &[Vec3], p: Vec3) -> Option { + let on = |a: Vec3, b: Vec3| { + let ab = b - a; + let len2 = ab.dot(ab); + a + ab * if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 } + }; + pts.windows(2) + .filter_map(|w| if let [a, b] = w { Some(on(*a, *b)) } else { None }) + .min_by(|x, y| x.dist(p).total_cmp(&y.dist(p))) + .or_else(|| pts.first().copied()) +} + /// The directions Distance 1 and Distance 2 of a chamfer of two distances run from its edge at /// `at`: along the face that faces up most, or the other one with Flip, and along the remaining /// face (the kernel's `chamfer_tool_sides` picks them the same way). None for any other dialog. pub(crate) fn chamfer_face_dirs(app: &SolveApp, d: &Dialog, at: Vec3) -> Option<(Vec3, Vec3)> { let Kind::Fillet { chamfer: true, ctype: 1, flip, .. } = &d.kind else { return None }; - let Some(Sel::Edge { body, index, .. }) = d.inputs.first()?.items.first() else { return None }; + let Some(Sel::Edge { body, index, .. }) = &anchor_item(app, d) else { return None }; let st = crate::open_meshing::session_world(&app.session); let mesh = st.body(body)?.mesh(); let sides = edge_sides(&mesh, *index, at)?; @@ -1830,7 +1862,9 @@ fn revolve_display_extent(app: &SolveApp, d: &Dialog, axis: (Vec3, Vec3)) -> Opt .ok()?; (angle, other) }; - solidcraft_engine::doc::revolve_extent_with_convention( + // The solid refuses 0° and a sweep past a full turn, and the dialog says so. The handle + // still uses that boundary, so the grab point stays and the angle can be dragged back. + solidcraft_engine::doc::revolve_extent_for_handle( &state, &plane, ®ions, @@ -1963,6 +1997,19 @@ fn arrow(painter: &egui::Painter, a: Pos2, b: Pos2, col: Color32) { mod tests { use super::*; + /// The arrow's point on a picked edge: one point, a zero-length piece, a click past the end. + #[test] + fn nearest_on_polyline_handles_short_edges_and_clicks_past_the_end() { + let p = |x: f64, y: f64| Vec3::new(x, y, 0.0); + assert_eq!(nearest_on_polyline(&[], p(1.0, 1.0)), None); + assert_eq!(nearest_on_polyline(&[p(2.0, 3.0)], p(9.0, 9.0)), Some(p(2.0, 3.0))); + assert_eq!(nearest_on_polyline(&[p(2.0, 3.0), p(2.0, 3.0)], p(9.0, 9.0)), Some(p(2.0, 3.0))); + let edge = [p(0.0, 0.0), p(0.0, 0.0), p(10.0, 0.0)]; + assert_eq!(nearest_on_polyline(&edge, p(4.0, 2.0)), Some(p(4.0, 0.0))); + assert_eq!(nearest_on_polyline(&edge, p(15.0, 1.0)), Some(p(10.0, 0.0))); + assert_eq!(nearest_on_polyline(&edge, p(-3.0, -1.0)), Some(p(0.0, 0.0))); + } + #[test] fn offset_plane_preview_stays_within_its_square() { let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); diff --git a/crates/ui-egui/src/colour_tokens_tests.rs b/crates/ui-egui/src/colour_tokens_tests.rs index f47f4c9aa..3328de3ff 100644 --- a/crates/ui-egui/src/colour_tokens_tests.rs +++ b/crates/ui-egui/src/colour_tokens_tests.rs @@ -31,6 +31,8 @@ fn moved_colours_keep_the_values_they_were_drawn_with() { assert_eq!(t.logo, [Color32::from_rgb(96, 158, 236), Color32::from_rgb(58, 136, 238), Color32::from_rgb(55, 108, 197)]); assert_eq!(t.icons.marker_halo, Color32::from_black_alpha(150)); assert_eq!(t.icons.agent, Color32::from_rgb(168, 85, 247)); + assert_eq!(t.figure_white, Color32::WHITE); + assert_eq!(t.figure_black, Color32::BLACK); } let (l, d) = (Tokens::light(), Tokens::dark()); assert_eq!((l.bend_up, l.bend_down), (Color32::from_rgb(30, 140, 50), Color32::from_rgb(200, 90, 20))); diff --git a/crates/ui-egui/src/colour_vision_tests.rs b/crates/ui-egui/src/colour_vision_tests.rs index 1c290174a..8f0b06127 100644 --- a/crates/ui-egui/src/colour_vision_tests.rs +++ b/crates/ui-egui/src/colour_vision_tests.rs @@ -401,6 +401,35 @@ fn groups(t: &Tokens) -> Vec { out.push(group(name, &[(key, fill)], &[("panel", t.panel)])); } out.push(group("dark pill text", &[("tab_on_fill_dark", t.tab_on_fill_dark)], &[("mesh_fill", t.mesh_fill)])); + // Miniature figures identify axes by labels and direction, reference points by + // position. Each ink must remain visible on its surfaces; + // the hues are not the only way to distinguish these marks from one another. + for (key, ink) in [ + ("figure_line", t.figure_line), + ("figure_accent", t.figure_accent), + ("figure_reference", t.figure_reference), + ("figure_axis_x", t.figure_axis_x), + ("figure_axis_y", t.figure_axis_y), + ("figure_axis_z", t.figure_axis_z), + ("figure_ok", t.figure_ok), + ("figure_warn", t.figure_warn), + ] { + out.push(group(key, &[(key, ink)], &[("figure_ground", t.figure_ground), ("figure_card", t.figure_card)])); + } + // The static sketch-state illustration uses success and warm alert inks on + // the top face. Keep success apart from each alert; the two warm warning + // shades are not a colour-only legend for live solver states. + out.push(group( + "preferences sketch states", + &[("figure_ok", t.figure_ok), ("figure_warn", t.figure_warn)], + &[("figure_face_top", t.figure_face_top)], + )); + out.push(group("preferences sketch note", &[("figure_ok", t.figure_ok), ("pref_note", t.pref_note)], &[("figure_face_top", t.figure_face_top)])); + // Badge words identify the status; check the ink against its own fill, as for + // tab text above, rather than treating an ink and its tint as competing states. + out.push(group("preferences note", &[("pref_note", t.pref_note)], &[("pref_note_fill", t.pref_note_fill)])); + out.push(group("preferences success", &[("pref_ok", t.pref_ok)], &[("pref_ok_fill", t.pref_ok_fill)])); + out.push(group("preferences accent ink", &[("pref_on_accent", t.pref_on_accent)], &[("form_primary", t.form_primary)])); // The removed part of a cut preview is translucent over the body. if let Some(sel) = out.iter_mut().find(|g| g.name == "selection") { sel.members.push(("preview_cut", over(t.preview_cut, t.body))); @@ -414,6 +443,12 @@ const SHADED: [&str; 2] = ["analysis.draft", "analysis.access"]; /// Tokens no colour vision mode needs to keep apart, and why. A new token fails /// `every_token_is_measured_or_carries_no_meaning` until it is in a group above or here. const NO_MEANING: &[(&str, &str)] = &[ + ("figure_face_left", "neutral cube shading; face geometry identifies the orientation"), + ("figure_face_right", "neutral cube shading; face geometry identifies the orientation"), + ("figure_white", "neutral axis label and highlight ink; letters identify the axes"), + ("figure_black", "neutral hatching and shadows; pattern and geometry carry the meaning"), + ("pref_well", "neutral well behind a labelled control or illustration"), + ("pref_disabled", "dimmed control ink; label and disabled interaction identify availability"), ("nav_hover", "neutral hover surface; placement and pointer feedback identify the control"), ("nav_press", "neutral pressed/open surface; interaction and menu presence identify the state"), ("nav_dim", "neutral secondary ink; the Later label identifies the unavailable option"), diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 0fedfa747..074693b40 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1286,6 +1286,19 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { { v.push(cmd(app, "sketch.spline.reverse", "Reverse Spline Direction").with(json!({ "curve": curve }))); } + // #10783: a point of one spline of the sketch's own, alone, comes out of that spline. + if let ([], [point]) = (curves.as_slice(), points.as_slice()) + && let Some(at) = ss.sketch.resolve_point(point) + && let [spline] = ss + .sketch + .curves + .iter() + .filter(|c| c.link.is_none() && matches!(&c.kind, CurveKind::Spline { pts, .. } if pts.contains(&at))) + .collect::>() + .as_slice() + { + v.push(cmd(app, "sketch.spline.remove_point", "Remove Spline Point").with(json!({ "curve": spline.id, "point": point }))); + } v.push(act("ui.fix", "Fix/Unfix", "c_fix").with(json!({ "entities": ents }))); // The clipboard beside Delete, as in every menu. v.push(act("ui.cut", "Cut", "cut").key("Ctrl+X")); @@ -2958,6 +2971,47 @@ mod tests { assert!(added.dist(at) < 0.5, "the new fit point is where the menu was opened: {added:?}"); } + /// #10783: a right-click on one of a spline's points offers Remove Spline Point, and the item + /// takes that point out: the spline stays, through its other points. A line's end isn't + /// offered it. + #[test] + fn spline_context_menu_removes_the_clicked_point() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let fit = h.app.run("sketch.spline.fit_point", json!({"points":[[0,0],[10,8],[20,0],[30,6]],"connect":false})).unwrap()["curves"][0] + .as_str() + .unwrap() + .to_owned(); + h.app.run("sketch.line", json!({"points":[[0,-12],[20,-12]],"connect":false})).unwrap(); + let sid = h.app.session.active_sketch.unwrap(); + let places = |h: &crate::scenario::Harness| { + let state = h.app.session.world_state().unwrap(); + let sk = &state.sketch(sid).unwrap().sketch; + sk.curves[sk.curve_index(&fit).unwrap()].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect::>() + }; + h.call("ui.view", json!({"view":"top"})); + h.app.cam.distance = 80.0; + h.settle(); + + h.step(&json!({"click":{"world":[20,-12,0]},"button":"right"})).unwrap(); + assert!(matches!(h.app.session.selection.as_slice(), [Sel::SketchPoint { .. }]), "{:?}", h.app.session.selection); + assert!(items(&h.app, &Target::Viewport).iter().all(|item| item.id != "sketch.spline.remove_point"), "a line's end"); + close(&mut h.app); + + let mut left = places(&h); + left.remove(1); + h.step(&json!({"click":{"world":[10,8,0]},"button":"right"})).unwrap(); + let [Sel::SketchPoint { id }] = h.app.session.selection.as_slice() else { panic!("{:?}", h.app.session.selection) }; + let id = id.clone(); + let menu = items(&h.app, &Target::Viewport); + let item = menu.iter().find(|item| item.id == "sketch.spline.remove_point").expect("a spline's point offers Remove Spline Point"); + assert_eq!((item.label.as_str(), item.params.clone()), ("Remove Spline Point", Some(json!({"curve": fit, "point": id})))); + assert!(item.enabled); + h.step(&json!({"click":{"handle":"menu:sketch.spline.remove_point"}})).unwrap(); + assert_eq!(places(&h), left, "the spline runs through its other points"); + } + #[test] fn solidworks_face_menu_runs_normal_to_selection_and_rejects_curved_faces() { let mut h = crate::scenario::Harness::new(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2ef4d0cb5..7aea70fe4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -187,6 +187,55 @@ fn wrap(r: Result) -> Outcome { /// The design's own Sketches folder (`Visibility::hidden_folders`), which `showSketches` sets. const SKETCHES_FOLDER: &str = "c0/sketches"; +/// The open dialog as `ui.inspect`, `ui.start` and `ui.editFeature` report it: its command, its +/// picks and what OK runs, in the commands' own terms rather than the form's internals (#9087). +fn dialog_state(app: &SolveApp) -> Value { + let Some(d) = app.dialog.as_ref() else { return Value::Null }; + let runs = crate::dialogs::apply_commands(app, d); + json!({ + "command": d.command(), + "title": crate::dialogs::report_title(d), + "editing": d.editing.map(|(feature, _)| feature), + "inputs": d.inputs.iter().enumerate().map(|(i, input)| json!({"label": input.label, "items": input.items, "active": i == d.active})).collect::>(), + "error": d.error, + "commands": runs.as_ref().ok().map(|cmds| cmds.iter().map(|(command, params)| json!({"command": command, "params": params})).collect::>()), + "waiting": runs.err(), + }) +} + +/// The windows open beside the model (#9087), each named by what opens it: the command +/// `ui.start` takes, or the `ui.help` item. +fn open_windows(app: &SolveApp) -> Vec<&'static str> { + [ + (app.params.is_some(), "parameters.change"), + (app.design_properties.is_some(), "document.metadata"), + (app.sketch_report.is_some(), "sketch.inspect"), + (app.bom.is_some(), "assembly.bom"), + (app.material_card_review.is_some(), "material.properties.validate"), + (app.help.about, "about"), + (app.updater.open, "updates"), + (app.keymap.open, "shortcuts"), + (app.crashes.open, "crashes"), + (app.issue_report.draft.is_some(), "report"), + (app.messages.open, "messages"), + ] + .into_iter() + .filter_map(|(open, command)| open.then_some(command)) + .collect() +} + +/// What a start or an edit opened: the tool, the dialog and the windows. `pending` while it +/// waits for the history to compute first; it opens on a later frame (`ui.inspect` shows it). +fn started(app: &SolveApp) -> Value { + json!({ + "tool": app.tool.as_ref().map(|t| t.cmd), + "dialog": dialog_state(app), + "windows": open_windows(app), + "pending": app.pending_feature_edit.is_some() || app.start_after_roll.is_some(), + "status": app.status.as_ref().map(|(text, _, error)| json!({"text": text, "error": error})), + }) +} + /// `UiState` as `ui.inspect` and `ui.set` report it, with the browser's view of the design /// (kept in the session) under the names the UI state used to give it. fn ui_state(app: &SolveApp) -> Value { @@ -669,9 +718,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> "viewport": app.viewport.rect.map(|r| json!([r.left(), r.top(), r.width(), r.height()])), "camera": app.cam, "tool": app.tool.as_ref().map(|t| t.cmd), - "dialog": app.dialog.as_ref().map(|d| format!("{d:?}")), + "dialog": dialog_state(app), + "windows": open_windows(app), "status": app.status.as_ref().map(|(text, _, error)| json!({"text": text, "error": error})), - "hover": app.viewport.hover.as_ref().map(|h| format!("{h:?}")), + "hover": app.viewport.hover, "renderer": if app.viewport.gpu.is_some() { "gpu" } else { "cpu" }, "frame_ms": app.frame_ms, "draw": app.viewport.draw_stats.as_ref().and_then(|s| s.lock().ok().map(|d| json!({ @@ -845,7 +895,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> return err(e); } } - ok(json!({"tool": app.tool.as_ref().map(|t| t.cmd), "dialog": app.dialog.as_ref().map(|d| format!("{d:?}"))})) + ok(started(app)) } "ui.move" | "ui.click" => { let (Some(x), Some(y)) = (f("x"), f("y")) else { return err("missing x/y") }; @@ -925,12 +975,16 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> }; let Some(id) = app.session.doc.find_feature(&key).map(|f| f.id) else { return err(format!("no feature `{key}`")) }; app.edit_feature(id); - ok(json!({"dialog": app.dialog.as_ref().map(|d| format!("{d:?}")), "marker": app.session.doc.marker})) + let mut reply = started(app); + if let Some(o) = reply.as_object_mut() { + o.insert("marker".into(), json!(app.session.doc.marker)); + } + ok(reply) } "ui.selection" => ok(json!({ "selection": app.session.selection, "dialog": app.dialog.as_ref().map(|d| d.inputs.iter().map(|i| json!({"label": i.label, "items": i.items})).collect::>()), - "hover": app.viewport.hover.as_ref().map(|h| format!("{h:?}")), + "hover": app.viewport.hover, "dimensions": crate::dim_view::drawn().into_iter().map(|(id, p)| json!({"id": id, "x": p.x, "y": p.y})).collect::>(), "shown_dimensions": crate::dim_view::model_drawn() .into_iter() @@ -2503,6 +2557,56 @@ mod tests { } } + /// #9087: the dialog is reported as data (its command, inputs and what OK runs), not as the + /// form's Debug text; `ui.start` and `ui.editFeature` reply with what they opened, and the + /// tool windows (Parameters, Bill of Materials) are reported by the command that opens them. + #[test] + fn dialogs_and_tool_windows_are_reported_as_data() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let mut h = crate::scenario::Harness::new(); + h.app = SolveApp::new(s, Services::default()); + let r = h.call("ui.start", json!({"command": "solid.fillet"})); + let d = &r["result"]["dialog"]; + assert_eq!((&d["command"], &d["title"], &d["editing"]), (&json!("solid.fillet"), &json!("FILLET"), &Value::Null), "{r}"); + assert_eq!((&d["inputs"][0]["active"], &d["inputs"][0]["items"]), (&json!(true), &json!([])), "{r}"); + assert!(d["commands"].is_null() && d["waiting"].is_string(), "no edge picked yet: {r}"); + assert_eq!((&r["result"]["pending"], &r["result"]["windows"]), (&json!(false), &json!([])), "{r}"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["dialog"], *d, "ui.inspect reports the same"); + crate::dialogs::cancel(&mut h.app); + + let feature = h.app.session.doc.features[0].id; + let r = h.call("ui.editFeature", json!({"feature": feature})); + let d = &r["result"]["dialog"]; + assert_eq!((&d["command"], &d["editing"]), (&json!("solid.box"), &json!(feature)), "{r}"); + // OK rebuilds the feature in place, from what the form holds. + let runs = &d["commands"][0]; + assert_eq!((&runs["command"], &runs["params"]["command"]), (&json!("timeline.redefine"), &json!("solid.box")), "{r}"); + assert_eq!((&runs["params"]["feature"], &runs["params"]["params"]["length"]), (&json!(feature), &json!("40")), "{r}"); + assert!(r["result"].get("marker").is_some(), "{r}"); + crate::dialogs::cancel(&mut h.app); + + for (command, windows) in + [("parameters.change", json!(["parameters.change"])), ("assembly.bom", json!(["parameters.change", "assembly.bom"]))] + { + let r = h.call("ui.start", json!({"command": command})); + assert_eq!((&r["result"]["dialog"], &r["result"]["tool"], &r["result"]["windows"]), (&Value::Null, &Value::Null, &windows), "{r}"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["windows"], windows, "{command}"); + } + h.call("ui.help", json!({"item": "about"})); + assert_eq!( + h.call("ui.inspect", json!({}))["result"]["windows"], + json!(["parameters.change", "assembly.bom", "about"]), + "the Help menu's windows too" + ); + + // What is under the pointer is a selection-like item, not the viewport's Debug text. + h.app.viewport.hover = + Some(crate::viewport::Hit::Face { body: "Body1".into(), index: 2, point: solidcraft_engine::geom::Vec3::new(1.0, 2.0, 3.0) }); + let hover = json!({"type": "face", "body": "Body1", "index": 2, "point": [1.0, 2.0, 3.0]}); + assert_eq!(h.call("ui.selection", json!({}))["result"]["hover"], hover); + } + /// #9087: a sample index that names no sample is refused, so an agent can tell a typo from /// a sample that opened. The index is checked before it reaches `open_sample`, which would /// otherwise drop it and reply `ok`. diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rs index 5b8f7bf71..03b30c327 100644 --- a/crates/ui-egui/src/control_job.rs +++ b/crates/ui-egui/src/control_job.rs @@ -67,7 +67,8 @@ const AHEAD_AREAS: &[&str] = &[ const NAMES_A_FILE: &[&str] = &["path", "paths", "file", "files", "dir", "folder", "url", "out"]; /// Commands that change nothing in the design and write a file: they run on a copy. -const ANSWERED_ON_A_COPY: &[&str] = &["file.export", "file.save_mesh"]; +const ANSWERED_ON_A_COPY: &[&str] = + &["file.export", "file.export_3mf", "file.export_obj", "file.export_step", "file.export_stl", "file.export_urdf", "file.save_mesh"]; /// Commands that only read the design, which can take long on a large one (a measure of every /// body, an inspection that measures them, #4604; a clearance or interference check of every pair diff --git a/crates/ui-egui/src/deferred.rs b/crates/ui-egui/src/deferred.rs index ab75509c7..30991ac8b 100644 --- a/crates/ui-egui/src/deferred.rs +++ b/crates/ui-egui/src/deferred.rs @@ -52,6 +52,17 @@ impl Deferred { } } +#[cfg(test)] +impl Deferred { + /// A command that never finishes computing, with the sender that keeps it so, for the tests + /// of what waits for one (the real worker would finish in a moment). + pub(crate) fn never_done(id: &str, params: Value, revision: u64) -> (Self, std::sync::mpsc::Sender>) { + let (tx, rx) = std::sync::mpsc::channel(); + let job = Deferred { done: rx, evaluated: None, started: crate::now_ms(), command: (id.to_string(), params), revision, kept: None }; + (job, tx) + } +} + /// How a command asked to run off the window thread goes. enum Start { /// It computes off the window thread. @@ -176,6 +187,25 @@ impl SolveApp { started.into_iter().flatten().reduce(f64::min) } + /// Whether the "Computing" toast can stop what it waits for (#8266): a history command or a + /// delete's check computing off the window thread. A feature edit applying has its own + /// dialog, with its own Cancel. + pub fn can_cancel_computing(&self) -> bool { + self.deferred.is_some() || self.delete_check.is_some() + } + + /// Stop waiting for the history command, and the delete check, computing off the window thread + /// (#8266), and drop the commands waiting behind them. The design is as it was before they + /// started: a command only runs for real once its evaluation is in. The worker threads run + /// to the end of what they evaluate and their results are dropped (the same as Cancel while a + /// feature is applying). + pub fn cancel_computing(&mut self) { + self.deferred = None; + self.deferred_queue.clear(); + self.delete_check = None; + self.start_after_roll = None; + } + /// Run a delete's check `commands` and carry on with `then` once their replies are in: off /// the window thread when it takes longer than the app's wait (see the module notes), /// otherwise right away. A Delete while another delete is being checked is left out. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 508798a61..0d476a3ac 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -521,6 +521,9 @@ pub struct Dialog { pub press_pull: bool, /// The operation the window chooses by itself (#6901). pub op_auto: crate::op_auto::OpAuto, + /// Where the face that reopened this fillet or chamfer was clicked (Press Pull): its arrow + /// sits on the edge nearest it. UI state only, never saved. + pub(crate) anchor_hint: Option, } #[derive(Clone, Debug)] @@ -558,8 +561,11 @@ impl DialogComputation { session, cmds, marker: d.editing.map(|(_, marker)| marker), + // The editor's pinned original is for a dialog that previews (as `open_feature_edit` + // keeps it); one that no longer does (Modeled unticked) edits the design as it is. editing: d .editing + .filter(|_| d.previews()) .and(app.editing_state.as_ref()) .map(|state| EditingState { source: state.source.scratch(), original: state.original.scratch() }), }) @@ -629,12 +635,13 @@ fn display_quality(app: &SolveApp) -> solidcraft_engine::doc::display_quality::D solidcraft_engine::doc::display_quality::DisplayQuality::parse(&app.preferences.display_quality).unwrap_or_default() } -/// Desktop feature dialogs evaluate the entire command and its dependent suffix once. -/// Results wait until a later frame before adoption, keeping the computing state visible. +/// Desktop feature dialogs evaluate the entire command and its dependent suffix once; so does +/// any feature edit, with a live preview or without. Results wait until a later frame before +/// adoption, keeping the computing state visible. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn begin_applying(app: &SolveApp, d: &Dialog) -> Option { let wait = app.apply_off_thread?; - if !d.previews() { + if !d.previews() && d.editing.is_none() { return None; } let computation = DialogComputation::new(app, d).ok()?; @@ -777,6 +784,7 @@ impl Dialog { shell_chain: Default::default(), press_pull: false, op_auto: Default::default(), + anchor_hint: None, } } @@ -2722,9 +2730,19 @@ fn occurrence_paths(s: &Session, items: &[Sel]) -> Vec> { /// the name the preferences give it. pub(crate) fn selection_label(s: &Session, names: crate::prefs::OriginPlaneNames, d: &Dialog, inp: &SelInput, item: &Sel) -> String { let axis = inp.accept == selection::AXIS_PICKS && round_axis(s, item).is_some(); + let sketch_name = + |id| s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_else(|| crate::i18n::format("browser.sketch_name", &[("number", &id.to_string())])); match item { Sel::SketchCurve { id, .. } => id.clone(), Sel::SketchPoint { id } => crate::sketch_modify_ui::point_id(s, item).unwrap_or(id).to_string(), + Sel::SketchMidpoint { id } => crate::i18n::format("dialog.selection_midpoint", &[("id", id)]), + Sel::ExternalSketchCurve { sketch, id } => { + crate::i18n::format("dialog.selection_external_curve", &[("sketch", &sketch_name(*sketch)), ("id", id)]) + } + Sel::SketchConstraint { id } => crate::i18n::format("dialog.selection_constraint", &[("id", id)]), + Sel::Profile { sketch, index } => { + crate::i18n::format("dialog.selection_profile", &[("sketch", &sketch_name(*sketch)), ("number", &index.saturating_add(1).to_string())]) + } Sel::Plane { name } => names.label(name).to_string(), Sel::Axis { name } | Sel::ConstructionPoint { name } | Sel::Body { name } => name.clone(), Sel::Face { body, index, .. } if axis => format!("{body} · face {index} axis"), @@ -2737,6 +2755,7 @@ pub(crate) fn selection_label(s: &Session, names: crate::prefs::OriginPlaneNames // A point of the model: a vertex, or the centre a round edge stands for. Sel::Vertex { body, .. } if !body.is_empty() => format!("{body} · point"), Sel::Feature { id } => s.doc.feature(*id).map(|f| f.name.clone()).unwrap_or_else(|| format!("Feature {id}")), + Sel::Occurrence { path } if path.is_empty() => s.doc.name.clone(), Sel::Occurrence { path } => s.occurrence_placement(path).map(|p| p.name).unwrap_or_else(|_| "Component".into()), Sel::Vertex { body, point } if body.is_empty() => { let state = crate::open_meshing::session_world(s); @@ -2948,11 +2967,6 @@ fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut { d.refuse(app, error); } - // For Corner dialogs (fillet/chamfer), propagate preview errors to `d.error` - // so impossible sizes still show a refusal message and tests can check it. - if matches!(d.kind, Kind::SketchModify(crate::sketch_modify_ui::Mod::Corner { .. })) && app.preview.error.is_some() && d.error.is_none() { - d.error = app.preview.error.clone(); - } let shown_id = egui::Id::new("sc_dialog_refusal_shown"); if d.error.is_none() && app.preview.error.is_none() { ui.data_mut(|m| m.remove::(shown_id)); @@ -3558,6 +3572,20 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let (ok_label, close_label) = action_labels(&d.kind); // What the footer's OK takes, for the check in the view's corner too (#6709). let ok_enabled = valid && !ok_label.is_empty() && app.applying.is_none(); + // #10620: the card widens to fit its widest label in the current language. The body + // publishes the extra it needs under this key each pass; the card applies it next pass, + // so the label column grows and the control column keeps its design width. Manager cards + // keep their approved fixed width. + let manager = matches!( + d.kind, + Kind::Material { .. } + | Kind::Appearance(_) + | Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }) + | Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. }) + | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. }) + ); + let grow_key = egui::Id::new(("sc_dialog_label_grow", raw_title)); + let label_grow = ctx.data(|data| data.get_temp::(grow_key)).unwrap_or(0.0).min((vp.width() - t.space_24 - card_width(&d)).max(0.0)); let panel = crate::ui_kit::Panel::new(&heading, egui::Id::new(("sc_dialog", title(&d.kind))), anchor, drag_bounds, side, frame) .actions(ok_label, close_label); let panel = if let Some(column) = column { @@ -3565,8 +3593,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } else if wide && side == crate::frame::Side::Left { let available = app.viewport.palette_rect.map_or(vp.width(), |r| (r.left() - vp.left() - t.space_8).max(0.0)); panel.width(card_width(&d).min(available)) - } else { + } else if manager { panel.width(card_width(&d)) + } else { + panel.width(card_width(&d) + label_grow).grow_label(grow_key) }; let reset_scroll = d.reset_scroll; let panel = @@ -3600,14 +3630,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let heading = crate::ui_kit::FeatureOptions { icon, title: label, drag_key, moved, docked, apply_label: repeatable.then_some("Apply") }; let applying = app.applying.is_some(); let mut collapsed = d.collapsed; - let manager = matches!( - d.kind, - Kind::Material { .. } - | Kind::Appearance(_) - | Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }) - | Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. }) - | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. }) - ); // A study/configuration owns Enter for its cells, including when folded. let cell_enter = matches!(&d.kind, Kind::Motion(k) if k.wide()) || matches!(&d.kind, Kind::Material { editor, .. } if editor.editing()); if cell_enter && collapsed { @@ -4857,33 +4879,31 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S } Kind::Loft { operation, rail_fit } => { need(0, "profiles of two or more sketches")?; - // One section per sketch, in the order the sketches were first picked; a sketch point - // is a section of its own, an apex the loft closes to (#4830). - let mut sections: Vec<(u64, Vec, Option<&str>)> = Vec::new(); + // Each picked profile is a section, in pick order, two of them from one sketch + // included (#8221); a sketch point is a section of its own, an apex the loft closes + // to (#4830). + let mut sections: Vec = Vec::new(); + let (mut profile_sketches, mut apexes) = (Vec::new(), 0); for x in sels(d, 0) { match x { - Sel::Profile { sketch, index } => match sections.iter_mut().find(|(sk, _, apex)| sk == sketch && apex.is_none()) { - Some((_, v, _)) => v.push(*index), - None => sections.push((*sketch, vec![*index], None)), - }, + Sel::Profile { sketch, index } => { + sections.push(json!({"sketch": sketch, "profiles": [index]})); + profile_sketches.push(*sketch); + } Sel::SketchPoint { id } => { if let Some((sk, point)) = id.split_once(':').and_then(|(sk, point)| Some((sk.parse::().ok()?, point))) { - sections.push((sk, Vec::new(), Some(point))); + sections.push(json!({"sketch": sk, "point": point})); + apexes += 1; } } _ => {} } } - if sections.len() < 2 { + profile_sketches.sort_unstable(); + profile_sketches.dedup(); + if profile_sketches.len() + apexes < 2 { return Err("pick profiles in two or more sketches, or a profile and a sketch point".into()); } - let sections: Vec = sections - .into_iter() - .map(|(sk, v, apex)| match apex { - Some(point) => json!({"sketch": sk, "point": point}), - None => json!({"sketch": sk, "profiles": v}), - }) - .collect(); let mut p = json!({"sections": sections, "operation": OPS.get(*operation).copied().unwrap_or("new")}); crate::dialogs_sweep::rail_params(app, *rail_fit, [sels(d, 1), sels(d, 2)], &mut p)?; ("solid.loft", p) @@ -6314,7 +6334,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option = at.iter().map(|e| e.as_str()).collect(); d.extra.insert("position_exprs".into(), json!({"at": exprs, "point": pt3(position.0)})); } - crate::hole_refs::restore(s, &mut d, references, &f.edge_names); + crate::hole_refs::restore(s, &mut d, references, &f.edge_names, app.preferences.length_decimals); } } if to.is_some() { @@ -6367,7 +6387,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option english_card.width(), "the German card widened: {card:?} vs {english_card:?}"); + assert!(label.width() > t.form_label_width * 1.6, "past the ordinary cap: {label:?}"); + assert!(english_label.width() <= t.form_label_width * 1.6, "English keeps the design's label column: {english_label:?}"); + // The drawn galley holds the whole translation: no ellipsis. + let drawn = h + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.job.text.contains("Anpassung") => Some(text.galley.job.text.to_string()), + _ => None, + }) + .expect("the Rail Fit row drew its German label"); + assert!(drawn.contains("Leitkurve") && !drawn.contains('…'), "the label is not ellipsized: {drawn:?}"); +} + #[test] fn remaining_dialogs_keep_kit_chrome_and_cancel_restores_preview() { for command in [ @@ -966,6 +998,51 @@ fn coil_from_a_profile_hides_the_primitive_section() { assert!(p.get("operation").is_some(), "{p}"); } +/// The Revolutions field steps by whole turns like the other counts (#7481). +#[test] +fn coil_revolutions_arrows_step_whole_turns() { + let mut h = fixture(); + h.app.run("parameters.add", json!({"name":"turns","expression":"3","unit":""})).unwrap(); + h.app.dialog = Some(Dialog::for_command(&h.app, "solid.coil").unwrap()); + h.settle(); + let sent = |h: &Harness| { + let cmds = crate::dialogs::preview_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + cmds.iter().find(|(id, _)| id == "solid.coil").map(|(_, p)| p["revolutions"].clone()).unwrap_or_else(|| panic!("{cmds:?}")) + }; + let set = |h: &mut Harness, text: &str| { + if let Some(Kind::Primitive { fields, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) + && let Some((_, value)) = fields.iter_mut().find(|(k, _)| *k == "revolutions") + { + *value = text.into(); + } + h.frames(2); + }; + let click = |h: &mut Harness, arrow: &str| h.step(&json!({"click":{"handle":format!("dialog:ui.revolutions {arrow}")}})).unwrap(); + assert_eq!(sent(&h), json!("4")); + click(&mut h, "up"); + assert_eq!(sent(&h), json!("5")); + click(&mut h, "down"); + click(&mut h, "down"); + assert_eq!(sent(&h), json!("3")); + // A fraction steps to the next whole turn either way. + set(&mut h, "2.5"); + click(&mut h, "up"); + assert_eq!(sent(&h), json!("3")); + set(&mut h, "2.5"); + click(&mut h, "down"); + assert_eq!(sent(&h), json!("2")); + // From 1 to the helix's 200 turns. + set(&mut h, "1"); + click(&mut h, "down"); + assert_eq!(sent(&h), json!("1")); + set(&mut h, "200"); + click(&mut h, "up"); + assert_eq!(sent(&h), json!("200")); + set(&mut h, "turns"); + click(&mut h, "up"); + assert_eq!(sent(&h), json!("turns + 1")); +} + fn extrude_focus_fixture() -> Harness { let mut h = Harness::new(); h.app.home.open = false; @@ -1302,3 +1379,56 @@ fn stored_bare_numbers_edit_with_their_units() { assert_eq!(h.app.session.doc.features.len(), count, "{command}: the feature is redefined in place"); } } + +#[test] +fn dialog_profile_labels_name_the_sketch_in_coil_and_mirror() { + for command in ["solid.coil", "sketch.mirror"] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane": "XY", "name": "Panel"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})).unwrap(); + let sketch = h.app.session.active_sketch.unwrap(); + if command == "solid.coil" { + h.app.run("sketch.finish", json!({})).unwrap(); + } + h.call("ui.view", json!({"view": "top"})); + h.call("ui.camera", json!({"target": [20, 15, 0], "distance": 100})); + h.step(&json!({"click": {"world": [20, 15, 0]}})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::Profile { sketch, index: 0 }]); + h.app.start(command); + h.app.dialog.as_mut().unwrap().preview_enabled = false; + h.frames(3); + let d = h.app.dialog.as_ref().unwrap(); + let input = &d.inputs[0]; + assert_eq!(input.items, vec![Sel::Profile { sketch, index: 0 }]); + assert_eq!(selection_label(&h.app.session, h.app.preferences.origin_plane_names, d, input, &input.items[0]), "Panel · profile 1"); + let mut painted = false; + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape { + painted |= text.galley.text() == "Panel · profile 1"; + } + }); + } + assert!(painted, "{command}: the painted selection label"); + } +} + +#[test] +fn dialog_sketch_selection_labels_translate_and_keep_identifiers() { + let mut h = Harness::new(); + let sketch = h.app.run("sketch.create", json!({"plane": "XY", "name": "Panel"})).unwrap()["sketch"].as_u64().unwrap(); + let d = Dialog::for_command(&h.app, "sketch.mirror").unwrap(); + for (sel, english, german) in [ + (Sel::Profile { sketch, index: 1 }, "Panel · profile 2", "Panel · Profil 2"), + (Sel::SketchMidpoint { id: "l7".into() }, "Midpoint · l7", "Mittelpunkt · l7"), + (Sel::ExternalSketchCurve { sketch, id: "l7".into() }, "Panel · curve l7", "Panel · Kurve l7"), + (Sel::SketchConstraint { id: "k3".into() }, "Constraint k3", "Bedingung k3"), + ] { + for (language, expected) in [("en", english), ("de", german)] { + let _language = crate::i18n::scope(language); + assert_eq!(selection_label(&h.app.session, h.app.preferences.origin_plane_names, &d, &d.inputs[0], &sel), expected); + } + } + let missing = Sel::Profile { sketch: 999, index: 0 }; + assert_eq!(selection_label(&h.app.session, h.app.preferences.origin_plane_names, &d, &d.inputs[0], &missing), "Sketch999 · profile 1"); +} diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 0e0c669dd..750fc7b8b 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -333,13 +333,24 @@ fn side_inputs() -> Vec { /// The pick a joint side shows in the side inputs: the face or edge of its own occurrence that /// the side's snap names (the piece nearest its pick, when the name has several), else the face -/// or edge nearest the pick. A point or frame side names no face: None. +/// or edge nearest the pick. A point or frame side names no face, so it shows its component. fn side_pick(app: &SolveApp, o: &JointOrigin) -> Option { let s = &app.session; let (pick, face, edge) = match &o.snap { Snap::FaceCenter { pick, face, .. } | Snap::CircleCenter { pick, face, .. } => (*pick, face.as_deref(), None), Snap::Edge { pick, edge, .. } => (*pick, None, edge.as_deref()), - Snap::Point { .. } | Snap::Frame { .. } => return None, + Snap::Point { .. } | Snap::Frame { .. } => { + let path = if o.occurrence == 0 { + Vec::new() + } else { + let occurrence = s.doc.occurrences.iter().find(|p| p.id == o.occurrence)?; + let mut path = s.doc.first_path(occurrence.parent); + path.push(occurrence.id); + s.doc.path_placement(&path)?; + path + }; + return Some(Sel::Occurrence { path }); + } }; // The pick is in the component's coordinates; the placed bodies are in the world. let at = diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index fcab1b112..a3970ca83 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -167,6 +167,8 @@ fn joint_and_drive_preview_on_the_placed_model() { removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true, + tint_new: true, + cut_tint: true, }; let cmds = preview_commands(&app, &d).unwrap(); let b = world_preview(&app.session, &cmds, colors).unwrap().unwrap(); @@ -323,6 +325,72 @@ fn edit_joint_shows_both_sides_and_a_repick_sends_only_that_side() { assert_ne!(after.b, before.b); } +/// Point and frame origins have no face pick, but Edit Joint must still identify their +/// components (#7749). Showing those components must not replace either stored origin. +#[test] +fn edit_joint_shows_components_for_point_and_frame_origins() { + for command in ["joint.create", "joint.as_built", "joint.rigid_group"] { + let mut app = two_boxes(); + let (a, b) = (occ(&app, "A"), occ(&app, "B")); + let params = match command { + "joint.create" => json!({"type": "rigid", "flip": true, + "a": {"occurrence": a, "point": [10, 10, 10], "z": [0, 0, 1]}, + "b": {"occurrence": b, "point": [40, 10, 10], "z": [0, 0, 1]}}), + "joint.as_built" => json!({"type": "rigid", "a": a, "b": b}), + _ => json!({"occurrences": [a, b]}), + }; + app.run(command, params).unwrap(); + let before = app.session.doc.assembly.joints[0].clone(); + let mut d = edit_joint(&app, before.id).unwrap(); + for (input, (id, name)) in d.inputs.iter().zip([(a, "A:1"), (b, "B:1")]) { + let item = input.items.first().expect("the stored component is shown"); + assert_eq!(item, &Sel::Occurrence { path: vec![id] }, "{command}"); + assert_eq!(crate::dialogs::selection_label(&app.session, app.preferences.origin_plane_names, &d, input, item), name); + } + let commands = apply_commands(&app, &d).unwrap(); + assert!(commands[0].1.get("a").is_none() && commands[0].1.get("b").is_none(), "{commands:?}"); + for (id, params) in commands { + app.run(&id, params).unwrap(); + } + let after = &app.session.doc.assembly.joints[0]; + assert_eq!((&after.a, &after.b), (&before.a, &before.b), "{command}"); + + // Replacing just B with a face still edits only B, preserving A's point/frame. + let body = app.session.world_state().unwrap().bodies.iter().find(|body| occurrence_of_body(&app.session, &body.name) == Some(b)).unwrap().name.clone(); + let picked = Sel::Face { body, index: 0, point: Vec3::new(40.0, 10.0, 10.0) }; + d.active = 1; + d.pick(&app.session, picked); + let commands = apply_commands(&app, &d).unwrap(); + assert!(commands[0].1.get("a").is_none(), "{commands:?}"); + assert_eq!(commands[0].1["b"]["occurrence"], b); + } +} + +#[test] +fn edit_joint_component_labels_keep_the_nested_instance_and_root() { + let mut app = SolveApp::new(Session::default(), Services::default()); + let parent = app.run("component.create", json!({"name": "Assembly", "activate": false})).unwrap()["occurrence"].as_u64().unwrap(); + let first = + app.run("component.create", json!({"name": "Part", "parent": "Assembly", "activate": false})).unwrap()["occurrence"].as_u64().unwrap(); + let second = app.run("occurrence.copy", json!({"occurrence": first})).unwrap()["occurrence"].as_u64().unwrap(); + let origin = |id| json!({"occurrence": id, "frame": {"origin": [0, 0, 0], "z": [0, 0, 1], "x": [1, 0, 0]}}); + app.run("joint.create", json!({"type": "rigid", "flip": true, "a": origin(0), "b": origin(second)})).unwrap(); + let before = app.session.doc.assembly.joints[0].clone(); + let mut d = edit_joint(&app, before.id).unwrap(); + for (input, (path, label)) in d.inputs.iter().zip([(vec![], app.session.doc.name.as_str()), (vec![parent, second], "Part:2")]) { + let item = input.items.first().expect("the stored component is shown"); + assert_eq!(item, &Sel::Occurrence { path }); + assert_eq!(crate::dialogs::selection_label(&app.session, app.preferences.origin_plane_names, &d, input, item), label); + } + for (id, params) in apply_commands(&app, &d).unwrap() { + app.run(&id, params).unwrap(); + } + let after = &app.session.doc.assembly.joints[0]; + assert_eq!((&after.a, &after.b), (&before.a, &before.b)); + d.inputs[1].items.clear(); + assert!(apply_commands(&app, &d).is_err(), "clearing a side still requires a replacement origin"); +} + /// A side on a hole's wall shows the wall, a cylinder, not the plate's face beside the hole: the /// face its snap names is the one the pre-fill takes, however near the other face's plane lies. #[test] @@ -871,6 +939,8 @@ fn drive_says_where_a_loop_stopped_it() { removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true, + tint_new: true, + cut_tint: true, }; let rocker = app.session.doc.assembly.joints.iter().position(|j| j.name == "Rocker").unwrap(); let mut d = drive_joint(&app, app.session.doc.assembly.joints[rocker].id).unwrap(); @@ -931,6 +1001,8 @@ fn drive_says_when_its_joint_is_joined_to_nothing_grounded() { removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true, + tint_new: true, + cut_tint: true, }; let b = world_preview(&app.session, &apply_commands(&app, &d).unwrap(), colors).unwrap().unwrap(); let why = b.stopped.as_ref().and_then(drive_stop).unwrap(); diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 1c2fbb1e2..556f02975 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -261,8 +261,18 @@ const MAX_PATTERN_INSTANCES: i64 = 1000; /// A solid pattern's quantity row, with step arrows from 1 to `MAX_PATTERN_INSTANCES`. The /// count goes to the command as typed, so it is evaluated as the document evaluates it. fn quantity_row(ui: &mut egui::Ui, doc: &solidcraft_engine::doc::Document, label: &str, value: &mut String) -> bool { + count_row_to(ui, doc, label, value, MAX_PATTERN_INSTANCES) +} + +/// The most revolutions a coil makes (the helix's own limit). +const MAX_COIL_REVOLUTIONS: i64 = 200; + +/// A count row with step arrows by whole numbers from 1 to `max`, evaluated as the document +/// evaluates it. A fraction still types in (a coil's revolutions); an arrow steps it to the next +/// whole number. +fn count_row_to(ui: &mut egui::Ui, doc: &solidcraft_engine::doc::Document, label: &str, value: &mut String, max: i64) -> bool { let eval = |text: &str| doc.eval(text.trim(), solidcraft_engine::doc::expr::Kind::Unitless).ok(); - ui_kit::count_row(ui, label, value, &ui_kit::Count { min: 1, max: MAX_PATTERN_INSTANCES, eval: &eval }) + ui_kit::count_row(ui, label, value, &ui_kit::Count { min: 1, max, eval: &eval }) } fn fillet_type(extra: &serde_json::Map) -> usize { @@ -335,7 +345,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: placement_row(d, ui, app); if crate::hole_refs::takes(d) { // Each reference edge with its distance (#37, #6380). - enter |= crate::hole_refs::input_rows(d, ui, &app.session, app.preferences.origin_plane_names); + enter |= crate::hole_refs::input_rows(d, ui, &app.session, app.preferences.origin_plane_names, app.preferences.length_decimals); } else { input_rows(d, ui, &app.session, app.preferences.origin_plane_names); } @@ -962,7 +972,12 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo if from_sketch && (*k == "diameter" || *k == "section_size") { continue; } - enter |= expr_row(ui, primitive_label(k), v); + // Revolutions steps by whole turns like the other counts (#7481). + enter |= if *k == "revolutions" { + count_row_to(ui, &app.session.doc, primitive_label(k), v, MAX_COIL_REVOLUTIONS) + } else { + expr_row(ui, primitive_label(k), v) + }; } if *cmd == "solid.coil" { enter |= coil_rows(ui, &mut d.extra); diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rs index 594964fc8..86a6b2b50 100644 --- a/crates/ui-egui/src/dialogs_sketch_tests.rs +++ b/crates/ui-egui/src/dialogs_sketch_tests.rs @@ -80,7 +80,7 @@ macro_rules! form_case { } form_case!(scale, "sketch.scale", ["Factor"]); -form_case!(offset, "sketch.offset", ["Direction", "Distance"]); +form_case!(offset, "sketch.offset", ["Direction", "Distance", "Instances"]); form_case!(mirror, "sketch.mirror", []); form_case!(move_copy, "sketch.move", ["Position", "Angle"]); form_case!(rectangular_pattern, "sketch.pattern.rectangular", ["Quantity", "Spacing", "Alignment", "Quantity 2", "Spacing 2", "Alignment 2"]); diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index 03ba444c0..09c6cd11c 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -189,7 +189,7 @@ fn inputs(k: &Surf) -> Vec { } Surf::Loft { .. } => { let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); - vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true), rail, rail2] + vec![SelInput::new("Sections", PROFILES | CURVES, true), rail, rail2] } Surf::Blend { .. } => vec![SelInput::new("From edges", EDGES, true), SelInput::new("To edges", EDGES, true)], Surf::Boundary { .. } => vec![SelInput::new("Curves", CURVES | EDGES, true), SelInput::new("Cross curves", CURVES | EDGES, true)], @@ -525,30 +525,37 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map { - need(0, "the sections, one sketch each")?; - // One section per sketch, in the order the sketches were first picked. - let sketch_of = |x: &Sel| match x { - Sel::Profile { sketch, .. } => Some(*sketch), - Sel::SketchCurve { .. } => crate::dialogs::picks_sketch(app, std::slice::from_ref(x), None), - _ => None, - }; - let mut order: Vec = Vec::new(); - for x in items(inputs, 0) { - let sk = sketch_of(x).ok_or("a picked curve is no longer in a sketch")?; - if !order.contains(&sk) { - order.push(sk); + need(0, "the sections")?; + // Each picked profile is a section, and so is each chain of picked curves (those of + // one sketch that meet end to end), in the order of their first pick: two sections + // can come from one sketch (#8221). + let picks = items(inputs, 0); + let curves: Vec = picks.iter().filter(|x| matches!(x, Sel::SketchCurve { .. })).cloned().collect(); + let mut chained: Vec> = chains(app, &curves)?.into_iter().map(Some).collect(); + let mut sections: Vec = Vec::new(); + let mut sketches: Vec = Vec::new(); + for x in picks { + match x { + Sel::Profile { sketch, index } => { + sections.push(json!({"sketch": sketch, "profiles": [index]})); + sketches.push(*sketch); + } + Sel::SketchCurve { id, .. } => { + let sk = crate::dialogs::picks_sketch(app, std::slice::from_ref(x), None).ok_or("a picked curve is no longer in a sketch")?; + let holds = |c: &Option| matches!(c, Some(Chain::Sketch { sketch, ids }) if *sketch == sk && ids.contains(id)); + if let Some(Some(Chain::Sketch { sketch, ids })) = chained.iter_mut().find(|c| holds(c)).map(Option::take) { + sections.push(json!({"sketch": sketch, "curves": ids})); + sketches.push(sketch); + } + } + _ => {} } } - if order.len() < 2 { + sketches.sort_unstable(); + sketches.dedup(); + if sketches.len() < 2 { return Err("pick sections in two or more sketches".into()); } - let sections: Vec = order - .iter() - .map(|sk| { - let picks: Vec = items(inputs, 0).iter().filter(|x| sketch_of(x) == Some(*sk)).cloned().collect(); - sheet_picks(app, &picks) - }) - .collect::>()?; let mut p = json!({ "sections": sections }); crate::dialogs_sweep::rail_params(app, *rail_fit, [items(inputs, 1), items(inputs, 2)], &mut p)?; ("surface.loft", p) diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 55ba950e7..b50df3d03 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -15,6 +15,23 @@ use crate::SolveApp; use crate::theme::Tokens; use crate::ui_kit; +/// Continue transient shot queues without adopting their document or view into the active tab. +pub(crate) fn advance_render_batches(app: &mut SolveApp, ctx: &egui::Context) { + let mut error = None; + for slot in app.docs.slots.iter_mut().flatten() { + if let Err(failure) = slot.session.advance_render_batch() { + error = Some(failure.to_string()); + } + let queue = slot.session.render_queue_state(); + if queue.running != 0 || queue.waiting != 0 { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + if let Some(error) = error { + app.set_status(error, true); + } +} + /// Most designs open at once. pub const MAX_OPEN: usize = 32; @@ -217,6 +234,8 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot { crate::agent_chat::leave_document(app); app.agent_chat.swap_document(&mut slot.agent_chat); let out_rev = app.session.revision; + // A click's point means nothing in the other design. + app.edit_anchor_hint = None; let mut out = DocSlot { session: std::mem::replace(&mut app.session, slot.session), autosave: app.autosave.as_mut().and_then(|a| std::mem::replace(&mut a.active, slot.autosave)), diff --git a/crates/ui-egui/src/expression_complete.rs b/crates/ui-egui/src/expression_complete.rs index 71c8f66ff..cafdf46ab 100644 --- a/crates/ui-egui/src/expression_complete.rs +++ b/crates/ui-egui/src/expression_complete.rs @@ -35,6 +35,11 @@ struct Popup { empty: bool, /// Down arrow in the empty box opened it: every named parameter, however many (#9246). every: bool, + /// The box was typed in since it took the focus. Until then an unarmed list only shows + /// what longer names there are, for a value the window filled in (`T` in Edit Extrude + /// lists `tan(`): Escape passes it by and closes the window as it would without the list, + /// as Enter and Tab do (#9084). + typed: bool, } fn popup_id() -> egui::Id { @@ -105,6 +110,7 @@ pub(crate) fn begin_frame(ctx: &egui::Context) { // Unarmed, the typed word is complete: Enter submits it and Tab moves on. Key::Enter | Key::Tab if !popup.armed => continue, Key::Enter | Key::Tab => popup.accept = true, + Key::Escape if !popup.armed && !popup.typed => continue, Key::Escape => { popup.dismissed = true; popup.accept = false; @@ -169,6 +175,7 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri // Dismissed suggestions stay closed until this box is typed in: another control rewriting // its text (a slider dragged while the box keeps the focus) or a moved caret is no reason. let dismissed = previous.as_ref().is_some_and(|p| p.dismissed) && !resp.changed(); + let typed = resp.changed() || previous.as_ref().is_some_and(|p| p.typed); // What the word follows, blanks aside. let before = text.chars().take(start).filter(|c| !c.is_whitespace()).last(); // A word that is already a complete name opens unarmed: Enter submits it as typed. A unit is @@ -191,7 +198,9 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri keyed: false, empty: false, every: false, + typed, }); + popup.typed = typed; popup.empty = text.is_empty(); popup.armed = popup.keyed || armed; // Never over a control being dragged: the drag dismisses them. @@ -251,10 +260,13 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri popup.armed.then_some(popup.selected), &options, // Unarmed, the typed word is complete and Enter submits it; an arrow key arms the list. + // Escape is the window's until the box is typed in. crate::i18n::tr_label(if popup.armed { "↑ ↓ choose · Enter / Tab complete · Esc dismiss" - } else { + } else if popup.typed { "↑ ↓ choose · Enter applies what you typed · Esc dismiss" + } else { + "↑ ↓ choose · Enter applies this value" }), ) && pick.is_none() && !released_after_press @@ -542,6 +554,26 @@ mod tests { } } + /// A list that opened by itself on a value the window filled in leaves Escape to the window + /// (#9084); once the box is typed in, Escape dismisses the list first. + #[test] + fn escape_passes_an_unarmed_list_until_the_box_is_typed_in() { + let mut e = Editor::new("width"); + assert_eq!(e.popup().map(|(_, armed)| armed), Some(false)); + e.key(Key::Escape); + assert!(e.leaked.contains(&Key::Escape)); + assert!(!e.ctx.memory(|m| m.has_focus(e.id))); + + let mut e = Editor::new("widt"); + e.frame(vec![egui::Event::Text("h".into())]); + assert_eq!(e.text, "width"); + assert_eq!(e.popup().map(|(_, armed)| armed), Some(false)); + e.key(Key::Escape); + assert!(e.leaked.is_empty()); + assert!(!showing(&e.ctx, e.id)); + assert!(e.ctx.memory(|m| m.has_focus(e.id))); + } + /// From the unarmed popup an arrow key picks a row (Down the first, Up the last); Enter or /// Tab then complete it as usual. #[test] diff --git a/crates/ui-egui/src/extrude_preview.rs b/crates/ui-egui/src/extrude_preview.rs index b1c6e2286..481a9f9e0 100644 --- a/crates/ui-egui/src/extrude_preview.rs +++ b/crates/ui-egui/src/extrude_preview.rs @@ -31,6 +31,9 @@ struct Surface { normal: Vec3, triangles: Vec<[Vec3; 3]>, edges: Vec<[Vec3; 2]>, + /// Per edge: whether its start is a corner of the outline, where the walls meet at an edge + /// of their own (a line is drawn up it), and the wall's normal at its start and end. + sides: Vec<(bool, [Vec3; 2])>, } impl StraightPreview { @@ -115,6 +118,10 @@ impl StraightPreview { let color = scene.color(color); let cut_edge = scene.color(cut_edge); let triangle = |scene: &mut GpuScene, points: [Vec3; 3], normal: Vec3| { + // Removed material the preference leaves fully transparent: only the cut's outline. + if operation == "cut" && !colors.cut_tint { + return; + } for point in points { if matches!(operation, "cut" | "intersect") { scene.xray_tri(point.to_f32(), normal.to_f32(), color); @@ -134,11 +141,18 @@ impl StraightPreview { } } let edge_color = if operation == "cut" { cut_edge } else { scene.color(colors.edge) }; - for &[a, b] in &surface.edges { - let normal = (b - a).cross(surface.normal).normalized()?; - triangle(&mut scene, [a + low, b + low, b + high], normal); - triangle(&mut scene, [a + low, b + high, a + high], normal); - for (a, b) in [(a + low, b + low), (a + high, b + high), (a + low, a + high)] { + for (&[a, b], &(corner, [na, nb])) in surface.edges.iter().zip(&surface.sides) { + for (points, normals) in [([a + low, b + low, b + high], [na, nb, nb]), ([a + low, b + high, a + high], [na, nb, na])] { + for (point, normal) in points.into_iter().zip(normals) { + if matches!(operation, "cut" | "intersect") { + scene.xray_tri(point.to_f32(), normal.to_f32(), color); + } else { + scene.tri(point.to_f32(), normal.to_f32(), color); + } + } + } + let up = corner.then_some((a + low, a + high)); + for (a, b) in [(a + low, b + low), (a + high, b + high)].into_iter().chain(up) { scene.line(a.to_f32(), b.to_f32(), edge_color, 1.3, operation != "join"); } } @@ -180,7 +194,7 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { if triangles.is_empty() { return None; } - let edges = std::iter::once((®ion.outer, true)) + let edges: Vec<[Vec3; 2]> = std::iter::once((®ion.outer, true)) .chain(region.holes.iter().map(|hole| (hole, false))) .flat_map(|(loop_, outer)| { let reverse = (loop_.signed_area() > 0.) != outer; @@ -190,9 +204,12 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { }) }) .collect(); - surfaces.push(Surface { normal: sketch.plane.normal(), triangles, edges }); + // Profiles of lines only: every end is a corner. + let sides = walls(&edges, sketch.plane.normal(), &|_| true)?; + surfaces.push(Surface { normal: sketch.plane.normal(), triangles, edges, sides }); } } else if inputs.iter().all(|input| matches!(input, Sel::Face { .. })) { + let mut vertices: HashMap, f64)> = HashMap::new(); // One pass over each selected body's triangles, rather than one full scan per pick. for body in &state.bodies { let mut selected = HashMap::new(); @@ -206,7 +223,7 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { } let normal = body.body.planar_face(*index)?.normal(); selected.insert(face, (surfaces.len(), *point)); - surfaces.push(Surface { normal, triangles: Vec::new(), edges: Vec::new() }); + surfaces.push(Surface { normal, triangles: Vec::new(), edges: Vec::new(), sides: Vec::new() }); } } if selected.is_empty() { @@ -224,6 +241,19 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { surface.triangles.push(points); } } + // The ends of the face's own edges: an outline turns at a corner only there, never + // between the points a curved edge is drawn with. + for (face, (index, _)) in &selected { + let ends: Vec = mesh + .edges + .iter() + .zip(&mesh.edge_faces) + .filter(|(_, faces)| faces.contains(face)) + .flat_map(|(points, _)| [points.first().copied(), points.last().copied()]) + .flatten() + .collect(); + vertices.insert(*index, (ends, (mesh.bounds().diagonal() * 1e-9).max(1e-9))); + } // The command resolves picks by their point. A stale display face index // must fall back rather than previewing a different face. let tolerance = (mesh.bounds().diagonal() * 1e-8).max(1e-8); @@ -259,6 +289,12 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { return None; } } + for (index, surface) in surfaces.iter_mut().enumerate() { + let (ends, tolerance) = vertices.remove(&index).unwrap_or_default(); + // A face whose edges the mesh doesn't list: every point may be a corner, as before. + let vertex = |p: Vec3| ends.is_empty() || ends.iter().any(|e| e.dist(p) <= tolerance); + surface.sides = walls(&surface.edges, surface.normal, &vertex)?; + } } else { return None; } @@ -266,6 +302,61 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { Some(Cached { document: app.session.doc.clone(), revision: app.session.revision, inputs: inputs.to_vec(), surfaces, bounds }) } +/// The walls an outline sweeps: per edge (in `edges`' order), whether its start is a corner +/// and the wall's normal at its start and end. A point turns the outline at a corner only +/// where `vertex` says an edge of the face ends there, and only by more than the points of the +/// curves on either side turn it (a circle drawn in two halves meets itself smoothly). Between +/// two smooth pieces the wall's normal is their mean, so a round wall shades round. `None` +/// when an edge has no length. +fn walls(edges: &[[Vec3; 2]], normal: Vec3, vertex: &dyn Fn(Vec3) -> bool) -> Option> { + let key = |point: Vec3| [point.x, point.y, point.z].map(|coordinate| if coordinate == 0. { 0 } else { coordinate.to_bits() }); + let starts: HashMap<_, usize> = edges.iter().enumerate().map(|(i, e)| (key(e[0]), i)).collect(); + let next = |i: usize| edges.get(i).and_then(|e| starts.get(&key(e[1])).copied()); + let mut prev = vec![None; edges.len()]; + for i in 0..edges.len() { + if let Some(j) = next(i) + && let Some(slot) = prev.get_mut(j) + { + *slot = Some(i); + } + } + let dirs: Vec = edges.iter().map(|e| (e[1] - e[0]).normalized()).collect::>()?; + let outward: Vec = dirs.iter().map(|d| d.cross(normal).normalized()).collect::>()?; + // The turn at the start of edge `i`. + let turn = |i: usize| -> Option { + let p = prev.get(i).copied().flatten()?; + Some(dirs.get(p)?.dot(*dirs.get(i)?).clamp(-1.0, 1.0).acos()) + }; + let corner: Vec = (0..edges.len()) + .map(|i| { + let (Some(a), Some(t)) = (edges.get(i).map(|e| e[0]), turn(i)) else { return true }; + if !vertex(a) { + return false; + } + // How far the curves on either side turn between their own points. + let before = prev.get(i).copied().flatten().filter(|p| edges.get(*p).is_some_and(|e| !vertex(e[0]))).and_then(turn).unwrap_or(0.0); + let after = next(i).filter(|n| edges.get(*n).is_some_and(|e| !vertex(e[0]))).and_then(turn).unwrap_or(0.0); + t > 1.25 * before.max(after) + 1e-2 + }) + .collect(); + let mean = |a: Vec3, b: Option<&Vec3>| b.and_then(|b| (a + *b).normalized()).unwrap_or(a); + let smooth = |i: usize| corner.get(i).is_some_and(|c| !c); + (0..edges.len()) + .map(|i| { + let own = *outward.get(i)?; + let at_start = match prev.get(i).copied().flatten() { + Some(p) if smooth(i) => mean(own, outward.get(p)), + _ => own, + }; + let at_end = match next(i) { + Some(n) if smooth(n) => mean(own, outward.get(n)), + _ => own, + }; + Some((!smooth(i), [at_start, at_end])) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -348,6 +439,65 @@ mod tests { commands[0].1 = json!({"distance":2,"taper":"3deg"}); assert!(preview.compute(&harness.app, &commands, colors).is_none()); } + /// Lines the feedback draws straight up the walls (along +z), under or over the model. + fn upright_lines(scene: &GpuScene) -> usize { + [&scene.lines, &scene.overlay] + .into_iter() + .flat_map(|lines| lines.as_chunks::<{ crate::gpu::LINE_SIZE }>().0) + .filter(|line| { + let v: Vec = line.as_chunks::<4>().0.iter().take(6).map(|bytes| f32::from_le_bytes(*bytes)).collect(); + (v[0] - v[3]).abs() < 1e-4 && (v[1] - v[4]).abs() < 1e-4 && (v[2] - v[5]).abs() > 1e-3 + }) + .count() + } + + /// A face with round edges is swept into round walls: no line up the wall at each point the + /// circle is drawn with, and normals that turn with the wall (the Bolted Flange's face looked + /// like a polygon while extruding, 2026-10-29). A box's face keeps a line up each corner. + #[test] + fn face_feedback_draws_lines_up_corners_only() { + for (shape, corners) in [("solid.cylinder", 0), ("solid.box", 4)] { + let mut harness = Harness::new(); + let params = if shape == "solid.cylinder" { + json!({"radius": 20, "height": 5, "body_name": "Stock"}) + } else { + json!({"length": 4, "width": 3, "height": 5, "body_name": "Stock"}) + }; + harness.app.run(shape, params).unwrap(); + let state = harness.app.session.world_state().unwrap(); + let face = state + .body("Stock") + .unwrap() + .body + .faces(0.001) + .unwrap() + .into_iter() + .find(|face| face.plane_normal.is_some_and(|normal| normal.z > 0.99)) + .unwrap(); + harness.app.session.selection = vec![Sel::Face { body: "Stock".into(), index: face.index, point: face.centroid }]; + harness.app.start("solid.extrude"); + if let Kind::Extrude { distance, operation, auto_op, .. } = &mut harness.app.dialog.as_mut().unwrap().kind { + *distance = "2".into(); + *operation = 0; + *auto_op = false; + } + let commands = crate::dialogs::apply_commands(&harness.app, harness.app.dialog.as_ref().unwrap()).unwrap(); + let mut preview = StraightPreview::default(); + let built = preview.compute(&harness.app, &commands, Colors::from_tokens(&crate::theme::Tokens::get())).unwrap().unwrap(); + assert_eq!(upright_lines(&built.scene), corners, "{shape}"); + if shape == "solid.cylinder" { + // Each wall vertex's normal points away from the axis. + let surface = &preview.cached.as_ref().unwrap().surfaces[0]; + for (edge, (_, normals)) in surface.edges.iter().zip(&surface.sides) { + for (point, normal) in edge.iter().zip(normals) { + let radial = Vec3::new(point.x, point.y, 0.0).normalized().unwrap(); + assert!(normal.dot(radial) > 0.999, "{point:?}: {normal:?}"); + } + } + } + } + } + #[test] fn identity_component_feedback_skips_moved_and_repeated_placements() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index b2459c0c6..edb5fe718 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -1190,7 +1190,7 @@ mod tests { let capturer = solidcraft_gpu::capture::Capturer::new(&adapter, device.clone(), queue.clone()).unwrap().watching(lost.flag()); let (scene, cam) = (solidcraft_engine::render::Scene::default(), solidcraft_engine::render::Camera::default()); assert_ne!(super::picture(&capturer, &scene, &cam, 16, 16).unwrap().renderer, "cpu"); - assert!(!lost.probe(&queue), "a working device isn't lost"); + assert!(!lost.probe(&device, &queue), "a working device isn't lost"); // egui's renderer is made with the window, before any loss (made on a lost device, its // uniform buffer's `create_buffer_init` panics). @@ -1198,7 +1198,7 @@ mod tests { device.destroy(); let _ = device.poll(wgpu::PollType::wait_indefinitely()); - assert!(lost.is_lost() && lost.probe(&queue), "the lost callback marked the device"); + assert!(lost.is_lost() && lost.probe(&device, &queue), "the lost callback marked the device"); assert!(lost.reason().is_some_and(|r| r.starts_with("Destroyed")), "{:?}", lost.reason()); // The next frame's uploads, as the painter would make them were it not skipping: wgpu @@ -1211,4 +1211,39 @@ mod tests { let picture = super::picture(&capturer, &scene, &cam, 16, 16).unwrap(); assert_eq!((picture.renderer, picture.rgba.len()), ("cpu", 16 * 16 * 4)); } + + /// The probe runs before every frame's uploads, so on a working device it must cost nothing + /// visible: no error for any scope or handler, and the uploads after it go through. On a + /// reset D3D12 device an empty submission went through and the upload after it panicked + /// inside wgpu (#6528); the probe now opens a command list, the driver call that upload's + /// queue write would make first. A driver reset can't be made here: `destroy` loses the + /// device in wgpu itself, before any driver call. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_lost_device_probe_is_clean_on_a_working_device() { + use egui_wgpu::wgpu; + let Some((adapter, device, queue)) = super::offscreen_device() else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let lost = egui_wgpu::DeviceLost::watch(&device); + let capturer = solidcraft_gpu::capture::Capturer::new(&adapter, device.clone(), queue.clone()).unwrap().watching(lost.flag()); + let mut renderer = egui_wgpu::Renderer::new(&device, wgpu::TextureFormat::Rgba8Unorm, Default::default()); + let image = egui::ImageData::Color(std::sync::Arc::new(egui::ColorImage::filled([4, 4], egui::Color32::WHITE))); + let delta = egui::epaint::ImageDelta::full(image, egui::TextureOptions::LINEAR); + let (scene, cam) = (solidcraft_engine::render::Scene::default(), solidcraft_engine::render::Camera::default()); + for frame in 0..3 { + // As the painter: the probe, then the frame's first queue write. + let (was_lost, error) = egui_wgpu::capture_errors(&device, || { + let was_lost = lost.probe(&device, &queue); + renderer.update_texture(&device, &queue, egui::TextureId::Managed(0), &delta); + was_lost + }); + assert!(!was_lost && error.is_none(), "frame {frame}: lost {was_lost}, {error:?}"); + // A save's thumbnail, which probes too, still comes from the GPU. + assert_ne!(super::picture(&capturer, &scene, &cam, 16, 16).unwrap().renderer, "cpu"); + } + let _ = device.poll(wgpu::PollType::wait_indefinitely()); + assert!(!lost.is_lost() && lost.reason().is_none(), "{:?}", lost.reason()); + } } diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rs index 36cd0263a..60e7897fe 100644 --- a/crates/ui-egui/src/history_off_thread_tests.rs +++ b/crates/ui-egui/src/history_off_thread_tests.rs @@ -209,6 +209,43 @@ fn a_marker_moved_again_replaces_the_move_still_waiting() { assert_eq!(marker(&h), None, "where the drag ended: the end of the history"); } +/// The "Computing" toast has a Cancel (#8266): it gives up on a marker move that takes too long, and +/// on the moves waiting behind it, and the design stays as it was. +#[test] +fn cancel_on_the_computing_toast_gives_up_on_the_move() { + let mut h = block_boss_hole(); + // A move that does not finish, with another waiting behind it. + let (job, _keep) = crate::deferred::Deferred::never_done("timeline.roll_to", json!({"position": 1}), h.app.session.revision); + h.app.deferred = Some(job); + h.app.deferred_queue.push(("timeline.roll_to".into(), json!({"position": 2}))); + h.frames(2); + let toast = crate::scenario::rect_of("toast:computing").expect("the computing toast"); + let cancel = crate::scenario::handle_at("toast:computing:cancel").expect("its Cancel"); + assert!(toast.contains(cancel), "{cancel:?} in {toast:?}"); + assert!(h.widget("Cancel").is_some(), "Cancel has an accessible name"); + h.step(&json!({"click": {"handle": "toast:computing:cancel"}})).unwrap(); + h.frames(2); + assert!(h.app.deferred.is_none() && h.app.deferred_queue.is_empty(), "nothing computes or waits"); + assert!(h.app.computing_since().is_none()); + assert!(crate::scenario::rect_of("toast:computing").is_none(), "the toast is gone"); + assert_eq!(marker(&h), None, "the marker stays where it was"); + // And the history moves again afterwards. + h.app.run_heavy("timeline.roll_to", json!({"position": 1})).unwrap(); + until_settled(&mut h); + assert_eq!(marker(&h), Some(1)); +} + +/// A feature edit applying has the dialog's own Cancel, so its toast has none. +#[test] +fn the_computing_toast_has_no_cancel_for_what_cannot_be_given_up() { + let mut h = block_boss_hole(); + assert!(!h.app.can_cancel_computing(), "nothing computes"); + h.app.run_heavy("timeline.roll_to", json!({"position": 1})).unwrap(); + assert!(h.app.can_cancel_computing(), "a move can be given up"); + until_settled(&mut h); + assert!(!h.app.can_cancel_computing()); +} + #[test] fn undo_computes_off_the_window_thread() { let mut h = block_boss_hole(); diff --git a/crates/ui-egui/src/hole_refs.rs b/crates/ui-egui/src/hole_refs.rs index a89f0e560..86c5aa90f 100644 --- a/crates/ui-egui/src/hole_refs.rs +++ b/crates/ui-egui/src/hole_refs.rs @@ -34,11 +34,25 @@ pub(crate) const DISTANCES: [&str; 2] = ["Distance 1", "Distance 2"]; #[derive(Clone, Debug, Default, PartialEq)] pub struct Refs { pub distance: [String; 2], + /// The model-space text each distance was measured from, while its field still shows the + /// rounded form below. + exact: [Option; 2], + /// The rounded text written into `distance` for that model value. + shown: [Option; 2], seen: Option, frame: Option, focus: Option, } +/// The text that drives the model for reference `k`: the exact measured value while the field +/// still shows its rounded form, else what the user typed. +fn model_text(refs: &Refs, k: usize) -> Option<&str> { + match (refs.exact.get(k).and_then(Option::as_deref), refs.shown.get(k).and_then(Option::as_deref)) { + (Some(exact), Some(shown)) if refs.distance.get(k).is_some_and(|d| d == shown) => Some(exact), + _ => refs.distance.get(k).map(String::as_str), + } +} + /// The place, edges and distances the dialog last had in step. #[derive(Clone, Debug, PartialEq)] struct Seen { @@ -186,7 +200,7 @@ fn frame(s: &Session, d: &mut Dialog) -> Option<(ReferenceFrame, Vec)> { /// Keep the distances and the hole's place in step: a new place or a new edge is measured, a /// typed distance moves the place there (when it stays on the face). Run before the dialog's /// commands are made. -pub(crate) fn sync(s: &Session, d: &mut Dialog) { +pub(crate) fn sync(s: &Session, d: &mut Dialog, decimals: u8) { if !takes(d) { return; } @@ -207,7 +221,7 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) { // Typed: the hole goes to the distances. Some(sn) if sn.distance != refs.distance => { let values: Option> = - picked.iter().map(|k| refs.distance.get(*k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); + picked.iter().map(|k| model_text(refs, *k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); if let Some(c) = values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&crate::open_meshing::session_world(s), f, *c)) { @@ -223,7 +237,13 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) { if let Some(slot) = refs.distance.get_mut(*k) && (moved || new_edge || slot.trim().is_empty()) { - *slot = crate::canvas::format_len(&s.doc, v.max(0.0)); + // The field shows the document's length precision; the model keeps the + // measured value until the user edits that field. + let measured = v.max(0.0); + refs.exact[*k] = Some(crate::length_input::model(&s.doc, measured)); + let shown = crate::prefs::format_length(measured, &s.doc.units, decimals); + refs.shown[*k] = Some(shown.clone()); + *slot = shown; } if new_edge && edges.get(*k).is_some_and(Option::is_some) { refs.focus = Some(*k); @@ -240,7 +260,7 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) { /// The Single hole's (or the Cylinder's) selection rows, each reference edge with its distance on /// the row below it once it is picked. Whether Enter was pressed in a distance. -pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: crate::prefs::OriginPlaneNames) -> bool { +pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: crate::prefs::OriginPlaneNames, decimals: u8) -> bool { let mut enter = false; for i in 0..d.inputs.len() { crate::dialogs::input_rows_range(d, ui, s, names, i..i + 1); @@ -252,6 +272,11 @@ pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: && let (Some(label), Some(value)) = (DISTANCES.get(k), refs.distance.get_mut(k)) { enter |= crate::ui_kit::expr_row(ui, label, value); + // The field no longer shows the measured value: the user now owns what drives it. + if refs.shown[k].as_deref().is_some_and(|shown| shown != value.as_str()) { + refs.exact[k] = None; + refs.shown[k] = None; + } // Without value boxes in the view (#9479), a newly picked edge's distance takes the // keyboard here, as its box would. if refs.focus == Some(k) && !crate::canvas::boxes_shown(ui.ctx()) { @@ -263,19 +288,26 @@ pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: d.give_keyboard(id); } } - sync(s, d); + sync(s, d, decimals); enter } /// The `references` OK sends: each picked edge (a point on it) with its distance. pub(crate) fn params(d: &Dialog) -> Vec { let Some(refs) = refs(d).filter(|_| takes(d)) else { return Vec::new() }; - edges(d).iter().zip(&refs.distance).filter_map(|(e, distance)| e.map(|p| json!({"edge": [p.x, p.y, p.z], "distance": distance.trim()}))).collect() + edges(d) + .iter() + .enumerate() + .filter_map(|(k, e)| { + let distance = model_text(refs, k)?; + e.map(|p| json!({"edge": [p.x, p.y, p.z], "distance": distance.trim()})) + }) + .collect() } /// Editing a hole (or a cylinder) with reference edges: the edges picked again where they are /// now, their distances, and the place where those distances put it now. -pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], names: &[String]) { +pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], names: &[String], decimals: u8) { if references.is_empty() { return; } @@ -300,7 +332,23 @@ pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], if let Some(refs) = refs_mut(d) && let Some(slot) = refs.distance.get_mut(k) { - *slot = r.distance.to_string(); + // A literal distance shows at the document's precision; its exact value stays for the + // model. An expression stays as written, since rounding it would break its parameters. + let exact = r.distance.to_string(); + let literal = if solidcraft_engine::doc::expr::is_literal(&exact) { s.doc.eval(&exact, ValueKind::Length).ok() } else { None }; + match literal { + Some(value) => { + let shown = crate::prefs::format_length(value, &s.doc.units, decimals); + refs.exact[k] = Some(exact); + refs.shown[k] = Some(shown.clone()); + *slot = shown; + } + None => { + *slot = exact; + refs.exact[k] = None; + refs.shown[k] = None; + } + } } } // The hole where its distances put it now (the part may have changed since it was placed). @@ -308,7 +356,7 @@ pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], if let Some(f) = &found && let Some(refs) = refs(d) { - let values: Option> = refs.distance.iter().take(f.lines.len()).map(|e| s.doc.eval(e, ValueKind::Length).ok()).collect(); + let values: Option> = (0..f.lines.len()).map(|k| model_text(refs, k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); if let Some(c) = values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&st, f, *c)) { to = c; } diff --git a/crates/ui-egui/src/hole_refs_ui_tests.rs b/crates/ui-egui/src/hole_refs_ui_tests.rs index c87d62cd1..8e14971b0 100644 --- a/crates/ui-egui/src/hole_refs_ui_tests.rs +++ b/crates/ui-egui/src/hole_refs_ui_tests.rs @@ -110,19 +110,70 @@ fn a_hole_is_placed_by_its_distances_from_two_edges() { h.frames(4); assert!(picked_edge(&h, "Reference 1").is_some_and(|p| p.x.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 1")); assert!(picked_edge(&h, "Reference 2").is_some_and(|p| p.y.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 2")); - assert_eq!(distances(&h), ["10 mm", "12 mm"]); + assert_eq!(distances(&h), ["10.00 mm", "12.00 mm"]); assert!(place(&h).dist(Vec3::new(10.0, 12.0, 10.0)) < 1e-6, "{:?}", place(&h)); // The hole moved on its face (a new pick, or its handle dragged): the distances follow. if let Some(Sel::Face { point, .. }) = h.app.dialog.as_mut().and_then(|d| d.inputs.first_mut()).and_then(|i| i.items.first_mut()) { *point = Vec3::new(20.0, 30.0, 10.0); } h.frames(2); - assert_eq!(distances(&h), ["20 mm", "30 mm"]); + assert_eq!(distances(&h), ["20.00 mm", "30.00 mm"]); h.step(&json!({"widget": "OK"})).unwrap(); assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|d| &d.error)); assert!(!solid_at(&h, Vec3::new(20.0, 30.0, 8.0)) && solid_at(&h, Vec3::new(10.0, 12.0, 8.0)), "the edit moved the hole to (20, 30)"); } +/// #10693: a measured distance reads at the document's precision, while OK still sends the +/// measured value, not the rounded one. +#[test] +fn a_measured_distance_shows_the_document_precision_but_keeps_its_model_value() { + let mut h = plate(); + h.step(&json!({"start": "solid.hole"})).unwrap(); + let at = screen(&mut h, Vec3::new(30.0, 25.0, 10.0)); + h.step(&json!({"click": at})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Reference 1"}})).unwrap(); + let left = screen(&mut h, Vec3::new(0.0, 20.0, 10.0)); + h.step(&json!({"click": left})).unwrap(); + h.frames(2); + // A face pick lands a hair off the whole millimetre, as a real pick does. + let exact = 20.000000868569572; + if let Some(Sel::Face { point, .. }) = h.app.dialog.as_mut().and_then(|d| d.inputs.first_mut()).and_then(|i| i.items.first_mut()) { + *point = Vec3::new(exact, 30.0, 10.0); + } + h.frames(2); + assert_eq!(distances(&h)[0], "20.00 mm"); + h.step(&json!({"widget": "OK"})).unwrap(); + let f = h.app.session.doc.features.last().unwrap().clone(); + let FeatureKind::Hole { references, .. } = &f.kind else { panic!("the last feature is a hole") }; + let text = references[0].distance.to_string(); + let value = h.app.session.doc.eval(&text, solidcraft_engine::doc::expr::Kind::Length).unwrap(); + assert!((value - exact).abs() < 1e-9, "OK keeps the measured distance, not the rounded text: {text}"); +} + +/// #10693: a comma decimal literal stored on a reference reads at the document's precision. +#[test] +fn a_comma_decimal_reference_distance_shows_the_document_precision() { + let mut h = plate(); + h.app + .run( + "solid.hole", + json!({ + "position": [30.0, 25.0, 10.0], + "diameter": 5, + "depth": 6, + "references": [ + {"edge": [0.0, 20.0, 10.0], "distance": "29,99999999999999 mm"}, + {"edge": [25.0, 0.0, 10.0], "distance": "25,000001373022986 mm"}, + ], + }), + ) + .unwrap(); + let id = h.app.session.doc.features.last().unwrap().id; + h.step(&json!({"call": "ui.editFeature", "params": {"feature": id}})).unwrap(); + h.frames(4); + assert_eq!(distances(&h), ["30.00 mm", "25.00 mm"]); +} + /// Reference edges place one hole: with places on two faces, OK says to pick one. #[test] fn reference_edges_place_one_hole() { diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index e7de0778c..e5d869ab7 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -28,7 +28,6 @@ pub const RESERVED: &[&str] = &[ "Ctrl+O", "Ctrl+W", "Ctrl+Comma", - "Ctrl+Shift+A", "Ctrl+C", "Ctrl+X", "Ctrl+V", @@ -872,6 +871,92 @@ pub fn capturing(app: &SolveApp) -> bool { mod tests { use super::*; + #[test] + fn assistant_shortcut_can_be_rebound_cleared_saved_and_reset() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.frames(2); + assert_eq!(effective(&h.app, "ui.assistant").as_deref(), Some("Ctrl+Shift+A")); + bind(&mut h.app, "ui.assistant", "Ctrl+Shift+J", false).unwrap(); + h.step(&json!({"key":"A", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open, "the old key no longer opens Assistant"); + let held_key = |pressed, repeat| egui::Event::Key { + key: egui::Key::J, + physical_key: None, + pressed, + repeat, + modifiers: egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), + }; + h.frame_with(vec![held_key(true, false)]); + assert!(h.app.agent_chat.open, "the custom key opens Assistant"); + h.frame_with(vec![held_key(true, true)]); + assert!(h.app.agent_chat.open, "holding the key does not repeatedly toggle"); + h.frame_with(vec![held_key(false, false)]); + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open, "the custom key also hides Assistant"); + let saved = h.app.keymap.prefs(); + let mut restored = app(); + restored.keymap.load(&saved); + assert_eq!(keys(&restored, "ui.assistant"), ["Ctrl+Shift+J"]); + assert!(bind(&mut h.app, "solid.box", "Ctrl+Shift+J", false).is_err(), "conflicts are reported"); + bind(&mut h.app, "ui.assistant", "", false).unwrap(); + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open, "clearing disables the shortcut"); + reset(&mut h.app, Some("ui.assistant")); + h.step(&json!({"key":"A", "cmd":true, "shift":true})).unwrap(); + assert!(h.app.agent_chat.open, "reset restores the original shortcut"); + } + + #[test] + fn a_released_unbound_assistant_chord_does_not_start_a_plain_letter_command() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + bind(&mut h.app, "ui.assistant", "Ctrl+Shift+J", false).unwrap(); + h.frames(2); + let modifiers = egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT); + h.frame_with(vec![ + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: false, repeat: false, modifiers }, + egui::Event::ModifiersChanged(egui::Modifiers::NONE), + ]); + assert!(!h.app.agent_chat.open, "the old chord is unbound"); + assert!(h.app.dialog.is_none() && h.app.tool.is_none(), "Ctrl+Shift+A must not become plain A (Appearance) after release"); + } + + #[test] + fn assistant_shortcut_respects_text_focus_ai_switch_and_capture() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + bind(&mut h.app, "ui.assistant", "Ctrl+Shift+J", false).unwrap(); + h.app.preferences.ai_features = false; + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open); + h.app.preferences.ai_features = true; + h.step(&json!({"key":"J", "cmd":true, "shift":true, "alt":true})).unwrap(); + assert!(!h.app.agent_chat.open, "extra modifiers do not match"); + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(h.app.agent_chat.open); + h.ctx.memory_mut(|m| m.request_focus(egui::Id::new("sc_agent_chat_input"))); + h.frames(2); + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open, "a chord can hide Assistant from its input field"); + bind(&mut h.app, "ui.assistant", "J", true).unwrap(); + h.call("ui.palette", json!({})); + h.frames(3); + h.step(&json!({"key":"J"})).unwrap(); + assert!(!h.app.agent_chat.open, "a bare letter in a text field remains text"); + h.call("ui.palette", json!({"open":false})); + h.frames(2); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_SHORTCUTS); + h.app.keymap.capturing = Some("solid.box".into()); + h.step(&json!({"key":"J"})).unwrap(); + assert!(!h.app.agent_chat.open, "recording a shortcut must not activate it"); + assert!(crate::agent_chat::assistant_tip(&h.app, crate::agent_chat::AssistantMark::Ready).contains("(J)")); + bind(&mut h.app, "ui.assistant", "", false).unwrap(); + assert!(!crate::agent_chat::assistant_tip(&h.app, crate::agent_chat::AssistantMark::Ready).contains("(J)")); + } + fn app() -> SolveApp { SolveApp::new(solidcraft_engine::Session::default(), Default::default()) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 92283774c..983648040 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -595,6 +595,8 @@ pub struct SolveApp { /// A linked component's design edited in place, with its assembly around it. pub edit_in_place: edit_in_place::EditInPlace, pub(crate) pending_feature_edit: Option, + /// The feature being reopened from a click and where, until its dialog opens (UI state only). + edit_anchor_hint: Option<(u64, solidcraft_engine::geom::Vec3)>, /// The open feature window's check of what its material does (#6901). pub op_check: op_auto::OpCheck, /// A command recomputing the history (the marker moved, undo) computing off the window @@ -831,6 +833,7 @@ impl SolveApp { editing_state: None, edit_in_place: Default::default(), pending_feature_edit: None, + edit_anchor_hint: None, op_check: op_auto::OpCheck::default(), deferred: None, deferred_queue: Vec::new(), @@ -1558,6 +1561,12 @@ impl SolveApp { } return; } + if id == "ui.assistant" { + if agent_chat::shown(self) { + agent_chat::toggle(self); + } + return; + } if id == "ui.palette" { shortcut_box::open(self, None); return; @@ -1753,7 +1762,7 @@ impl SolveApp { dim_view::cancel(); self.tool = None; self.home.open = false; - if dialogs_sheet::start_export(self, id) { + if dialogs_sheet::start_export(self, id) || toolbar::start_export(self, id) { return; } if id == "component.finish_edit" { @@ -1858,9 +1867,9 @@ impl SolveApp { self.cancel_sketch(); return; } - // Press Pull: edges get a fillet, a fillet's round face reopens its fillet (its size - // changes, as `solid.press_pull` does: #1932), other curved faces an offset, planar faces - // and profiles an extrude. + // Press Pull: edges get a fillet, a fillet's round face or a chamfer's flat one reopens + // its feature (its size changes, as `solid.press_pull` does: #1932, #4986), other curved + // faces an offset, planar faces and profiles an extrude. if id == "solid.press_pull" { if let Some(pending) = &mut self.pending_feature_edit { pending.then_start(id); @@ -1870,16 +1879,18 @@ impl SolveApp { return self.start("solid.fillet"); } let sel = &self.session.selection; - let curved = sel.iter().find_map(|s| match s { - solidcraft_engine::Sel::Face { body, index, .. } if dialogs::planar_face(&self.session, body, *index).is_none() => { - Some((body, *index)) - } + let blend = sel.iter().find_map(|s| match s { + solidcraft_engine::Sel::Face { body, index, point } => dialogs::blend_feature(&self.session, body, *index).map(|id| (id, *point)), _ => None, }); - if let Some((body, index)) = curved { - if let Some(blend) = dialogs::blend_feature(&self.session, body, index) { - return self.edit_feature(blend); - } + // Its arrow sits on the edge of the face clicked. + if let Some((blend, point)) = blend { + return self.edit_feature_at(blend, Some(point)); + } + let curved = sel.iter().any( + |s| matches!(s, solidcraft_engine::Sel::Face { body, index, .. } if dialogs::planar_face(&self.session, body, *index).is_none()), + ); + if curved { return self.start("solid.offset_face"); } let empty = sel.is_empty(); @@ -2059,7 +2070,15 @@ impl SolveApp { /// Edit a feature: sketches open in sketch mode; other features roll the /// timeline back to just before themselves and reopen their dialog, filled in. pub fn edit_feature(&mut self, id: u64) { + self.edit_feature_at(id, None); + } + + /// [`Self::edit_feature`] opened from a click at `at` on what the feature made: the dialog's + /// arrow sits by that point (a fillet's or chamfer's edge nearest it). + pub(crate) fn edit_feature_at(&mut self, id: u64, at: Option) { use solidcraft_engine::doc::FeatureKind; + // A non-finite point (over the control channel) keeps the first edge. + self.edit_anchor_hint = at.filter(|p| p.is_finite()).map(|p| (id, p)); dialogs::cancel(self); let Some(f) = self.session.doc.feature(id) else { return }; if matches!(f.kind, FeatureKind::Sketch { .. }) { @@ -2082,8 +2101,12 @@ impl SolveApp { fn open_feature_edit(&mut self, id: u64, marker: Option, original: Session) { self.editing_state = Some(dialogs::EditingState { source: self.session.scratch(), original }); + // The id check matters while another feature's reopening is still pending: a later call + // for a feature id that is gone returns before it drops that pending edit. + let hint = self.edit_anchor_hint.take().filter(|(f, _)| *f == id).map(|(_, p)| p); match dialogs::for_feature(self, id, marker) { - Some(d) => { + Some(mut d) => { + d.anchor_hint = hint; if !d.previews() { self.editing_state = None; } @@ -2291,7 +2314,9 @@ impl SolveApp { /// Is the origin widget shown? Origin planes and axes are drawn and pickable. While a dialog /// picks a plane ([`SolveApp::picking_plane`]) the Origin is always shown, drawn through the - /// model (a plane inside a body stays visible), even when the browser hides it. + /// model (a plane inside a body stays visible), even when the browser hides it — except the + /// origin planes for Project ([`SolveApp::picking_project_geometry`], #10778), which keep a + /// hidden Origin hidden. pub fn origin_visible(&self) -> bool { self.origin_shown() || self.picking_plane() } @@ -2308,6 +2333,15 @@ impl SolveApp { self.picking_sketch_plane() || self.dialog.as_ref().is_some_and(|d| d.inputs.get(d.active).is_some_and(|i| i.accept & selection::PLANES != 0)) } + /// Is the Sketch Project dialog open, picking its geometry? Its pick takes origin planes, + /// but Project must not bring hidden origin planes back (#10778): every line a plane + /// projects, an origin axis already gives, so the planes only add noise over the geometry + /// being picked. Other dialogs that pick a plane keep the reveal ([`Self::picking_plane`], + /// #2581). + pub fn picking_project_geometry(&self) -> bool { + self.dialog.as_ref().is_some_and(|d| matches!(d.kind, dialogs::Kind::SketchProject { .. })) + } + /// The field of view the view is drawn with: the `perspective_fov` preference while the view is /// in perspective ([`Self::perspective_view`]), and 0 (parallel) otherwise. The one place the /// drawn angle is decided. @@ -2813,6 +2847,7 @@ impl SolveApp { if !keymap::capturing(self) { expression_complete::begin_frame(ctx); } + agent_chat::toggle_shortcut(self, ctx); // A digit for a construction line's Length box is not a shortcut (#10258). sketch_construction::claim_typed_length(self, ctx); if !self.embedded { @@ -3028,7 +3063,10 @@ impl SolveApp { (i.pointer.middle_down() || i.pointer.secondary_down()) && i.pointer.press_origin().is_some_and(|p| full.contains(p) && !shell::covered(self, p)) }); - let blocked = !continuing_navigation && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| shell::covered(self, p)); + // A captured comparison divider also keeps its primary drag across floating cards. + let continuing_comparison = render_workspace::comparison_drag_captured(self) && ui.input(|i| i.pointer.primary_down()); + let blocked = + !continuing_navigation && !continuing_comparison && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| shell::covered(self, p)); let mut viewport_ui = ui.new_child(egui::UiBuilder::new().max_rect(full).id_salt("floating_viewport")); if blocked { // Disabled only to shield the scene from input under a card or menu; it must diff --git a/crates/ui-egui/src/loft_rails_dialog_tests.rs b/crates/ui-egui/src/loft_rails_dialog_tests.rs index 6a3a74aa6..9c56c4231 100644 --- a/crates/ui-egui/src/loft_rails_dialog_tests.rs +++ b/crates/ui-egui/src/loft_rails_dialog_tests.rs @@ -1,5 +1,6 @@ //! The Loft and Surface Loft dialogs' guide rails (#201): rails picked in the dialog reach the //! commands with their sketches and the fit, and editing the loft brings them back and keeps them. +//! Their sections follow the picks, two of them from one sketch included (#8221). use crate::dialogs::Kind; use crate::dialogs_surface::Surf; use crate::scenario::Harness; @@ -127,3 +128,92 @@ fn curves_that_share_an_id_are_picked_from_their_own_sketches() { let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); assert_eq!(commands[0].1["sections"], json!([{"sketch": low, "curves": ["l"]}, {"sketch": high, "curves": ["l"]}])); } + +/// A sketch at height `z` named `name`, made by `draw`; its id. +fn sketch_at(h: &mut Harness, name: &str, z: i32, draw: &[(&str, serde_json::Value)]) -> u64 { + h.app.run("sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})).unwrap(); + for (command, params) in draw { + h.app.run(command, params.clone()).unwrap(); + } + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.session.doc.find_feature(name).unwrap().id +} + +/// Two sections can come from one sketch (#8221): Surface Loft from one line of `A`, over `B`'s, +/// back to `A`'s other line makes three sections in pick order, and an edit keeps them. +#[test] +fn surface_loft_sections_from_one_sketch_stay_apart() { + let mut h = Harness::new(); + let a = sketch_at( + &mut h, + "A", + 0, + &[ + ("sketch.line", json!({"points": [[-10, 0], [10, 0]], "ids": ["front"]})), + ("sketch.line", json!({"points": [[-10, 40], [10, 40]], "ids": ["back"]})), + ], + ); + let b = sketch_at(&mut h, "B", 30, &[("sketch.line", json!({"points": [[-10, 20], [10, 20]], "ids": ["top"]}))]); + h.step(&json!({"call":"ui.start","params":{"command":"surface.loft"}})).unwrap(); + h.frames(3); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![ + Sel::SketchCurve { id: "front".into(), sketch: Some(a) }, + Sel::SketchCurve { id: "top".into(), sketch: Some(b) }, + Sel::SketchCurve { id: "back".into(), sketch: Some(a) }, + ]; + let expected = json!([{"sketch": a, "curves": ["front"]}, {"sketch": b, "curves": ["top"]}, {"sketch": a, "curves": ["back"]}]); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["sections"], expected); + ok(&mut h); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["params"]["sections"], expected); + ok(&mut h); +} + +/// Curves of one sketch that meet end to end are still one Surface Loft section, whatever order +/// they were picked in. +#[test] +fn surface_loft_curves_that_meet_are_one_section() { + let mut h = Harness::new(); + let a = sketch_at(&mut h, "A", 0, &[("sketch.line", json!({"points": [[-10, 0], [0, 0], [10, 5]], "ids": ["left", "right"]}))]); + let b = sketch_at(&mut h, "B", 30, &[("sketch.line", json!({"points": [[-10, 0], [10, 0]], "ids": ["top"]}))]); + h.step(&json!({"call":"ui.start","params":{"command":"surface.loft"}})).unwrap(); + h.frames(3); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![ + Sel::SketchCurve { id: "right".into(), sketch: Some(a) }, + Sel::SketchCurve { id: "top".into(), sketch: Some(b) }, + Sel::SketchCurve { id: "left".into(), sketch: Some(a) }, + ]; + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["sections"], json!([{"sketch": a, "curves": ["right", "left"]}, {"sketch": b, "curves": ["top"]}])); +} + +/// Loft from one circle of `C`, over `D`'s, back to `C`'s other circle (#8221): each picked +/// profile is a section, in pick order, and an edit keeps them. +#[test] +fn loft_profiles_from_one_sketch_stay_apart() { + let mut h = Harness::new(); + let circle = |x: i32, y: i32| ("sketch.circle.center", json!({"center": [x, y], "diameter": 12})); + let c = sketch_at(&mut h, "C", 0, &[circle(0, 0), circle(0, 40)]); + let d_sketch = sketch_at(&mut h, "D", 30, &[circle(0, 20)]); + h.step(&json!({"call":"ui.start","params":{"command":"solid.loft"}})).unwrap(); + h.frames(3); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::Profile { sketch: c, index: 0 }, Sel::Profile { sketch: d_sketch, index: 0 }, Sel::Profile { sketch: c, index: 1 }]; + let expected = json!([{"sketch": c, "profiles": [0]}, {"sketch": d_sketch, "profiles": [0]}, {"sketch": c, "profiles": [1]}]); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["sections"], expected); + ok(&mut h); + assert_eq!(h.app.session.world_state().unwrap().bodies.len(), 1, "{:?}", h.app.session.log); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["params"]["sections"], expected); + ok(&mut h); +} diff --git a/crates/ui-egui/src/move_preview.rs b/crates/ui-egui/src/move_preview.rs index e4fac8185..b6583ce6e 100644 --- a/crates/ui-egui/src/move_preview.rs +++ b/crates/ui-egui/src/move_preview.rs @@ -95,7 +95,7 @@ impl MovePreview { let mut bounds = Aabb3::EMPTY; for mesh in &cache.meshes { draw(&mut scene, mesh, &m, colors, &mut bounds); - if !copy { + if !copy && colors.cut_tint { // Where the body was, as the scratch-design preview shows a body moved away. for t in &mesh.triangles { for k in t { @@ -119,9 +119,11 @@ impl MovePreview { } } -/// `mesh` moved by `m`, in the colour of geometry the feature adds, with its shaded edges. +/// `mesh` moved by `m`, in the colour of geometry the feature adds, or the body's own where +/// the preference leaves new surface untinted (a move makes none either way), with its shaded +/// edges. fn draw(scene: &mut GpuScene, mesh: &Mesh, m: &Mat, colors: Colors, bounds: &mut Aabb3) { - let added = scene.color(colors.added); + let added = scene.color(if colors.tint_new { colors.added } else { colors.body }); for t in &mesh.triangles { for k in t { let i = *k as usize; diff --git a/crates/ui-egui/src/navigation_cube.rs b/crates/ui-egui/src/navigation_cube.rs index 7ab002301..f43c8ce22 100644 --- a/crates/ui-egui/src/navigation_cube.rs +++ b/crates/ui-egui/src/navigation_cube.rs @@ -11,10 +11,39 @@ const HALF: f64 = 40.0; // The remaining regions belong to the face, including the middle of each edge. const INSET: f64 = 0.68; +fn camera(app: &SolveApp) -> Camera { + let mut cam = app.cam; + if !crate::render_workspace::active(app) { + cam.fov = app.view_fov(); + } + cam +} + +fn inverse_focal_length(cam: &Camera) -> f64 { + // The field of view spans the whole navigator, including the margin around its cube. + let half_height = f64::from(DESIGN_SIZE) / (2.0 * HALF); + if cam.fov.is_finite() { (cam.fov.clamp(0.0, std::f64::consts::FRAC_PI_2) * 0.5).tan() / half_height } else { 0.0 } +} + fn project(cam: &Camera, v: Vec3, scale: f64) -> egui::Vec2 { - let (r, u, _) = cam.basis(); + let (r, u, b) = cam.basis(); let v = cam.from_frame(v); - vec2((v.dot(r) * scale) as f32, -(v.dot(u) * scale) as f32) + // A unit cube has its own camera, independent of model size and zoom. Place its eye + // one unit beyond the focal distance: the front face keeps its size beside the arrows. + // At the maximum 90-degree field of view the eye is still outside the cube's sphere, + // so every vertex stays in front of it. Zero fov gives the original parallel projection. + let denominator = 1.0 + inverse_focal_length(cam) * (1.0 - v.dot(b)); + vec2((v.dot(r) * scale / denominator) as f32, -(v.dot(u) * scale / denominator) as f32) +} + +/// Local projected axes at a label's centre; a direction alone has no perspective position. +fn project_direction(cam: &Camera, at: Vec3, direction: Vec3) -> egui::Vec2 { + let (r, u, b) = cam.basis(); + let inverse_focal = inverse_focal_length(cam); + let direction = cam.from_frame(direction); + let denominator = 1.0 + inverse_focal * (1.0 - cam.from_frame(at).dot(b)); + let parallel = vec2(direction.dot(r) as f32, -direction.dot(u) as f32); + (parallel + project(cam, at, 1.0) * (inverse_focal * direction.dot(b)) as f32) / denominator as f32 } fn direction_label(d: Vec3) -> String { @@ -38,16 +67,21 @@ fn facets(cam: &Camera, c: Pos2, half: f64) -> Vec { return Vec::new(); } let mut out = Vec::new(); + let inverse_focal = inverse_focal_length(cam); + let inverse_eye_distance = inverse_focal / (1.0 + inverse_focal); let mut add = |d: Vec3, normal: Vec3, mut vertices: Vec, axes: Option<(Vec3, Vec3)>| { let depth = cam.from_frame(normal).dot(cam.back()); - if depth <= 1e-5 { + // All face planes are one unit from the origin. In perspective a face must look + // toward the finite eye, not merely toward the parallel view direction. + if depth <= inverse_eye_distance + 1e-5 { return; } let centre = vertices.iter().copied().fold(Vec3::ZERO, |sum, p| sum + p) / vertices.len() as f64; - let at = c + project(cam, centre, half); + let projected_centre = project(cam, centre, half); + let at = c + projected_centre; vertices.sort_by(|a, b| { - let a = project(cam, *a - centre, half); - let b = project(cam, *b - centre, half); + let a = project(cam, *a, half) - projected_centre; + let b = project(cam, *b, half) - projected_centre; a.y.atan2(a.x).total_cmp(&b.y.atan2(b.x)) }); let vertices = Ring::new(vertices); @@ -62,7 +96,7 @@ fn facets(cam: &Camera, c: Pos2, half: f64) -> Vec { outer_edges, centre: at, label: direction_label(d), - text_axes: axes.map(|(r, u)| (project(cam, r, 1.0), -project(cam, u, 1.0))), + text_axes: axes.map(|(r, u)| (project_direction(cam, centre, r), -project_direction(cam, centre, u))), depth, }); }; @@ -115,8 +149,8 @@ fn hit(faces: &[Facet], p: Pos2) -> Option { faces.iter().enumerate().rev().find(|(_, f)| contains(&f.points, p)).map(|(i, _)| i) } -pub(super) fn drag_origin(cam: &Camera, centre: Pos2, pointer: Pos2, scale: f32) -> bool { - hit(&facets(cam, centre, HALF * f64::from(scale)), pointer).is_some() +pub(super) fn drag_origin(app: &SolveApp, centre: Pos2, pointer: Pos2, scale: f32) -> bool { + hit(&facets(&camera(app), centre, HALF * f64::from(scale)), pointer).is_some() } fn navigate(app: &mut SolveApp, action: Option<&str>, dir: Option) { @@ -188,7 +222,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { let active = orbiting || ui.rect_contains_pointer(outer); let t = Tokens::get().navigation_cube(active); crate::scenario::publish_count("navigation_cube:active", f64::from(u8::from(active))); - let faces = facets(&app.cam, c, HALF * f64::from(scale)); + let faces = facets(&camera(app), c, HALF * f64::from(scale)); let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| ui.is_enabled() && ui.rect_contains_pointer(rect) && !crate::shell::covered(app, *p)); let hovered = if orbiting { None } else { hover.and_then(|p| hit(&faces, p)) }; let painter = ui.painter_at(outer); @@ -298,6 +332,64 @@ mod tests { output } + #[test] + fn cube_projection_foreshortens_depth_only_in_perspective() { + for up in [UpAxis::Z, UpAxis::Y] { + let mut cam = Camera { up, ..Default::default() }; + cam.set_view(StandardView::Front); + let near = Vec3::new(0.5, -1.0, 0.0); + let far = Vec3::new(0.5, 1.0, 0.0); + assert_eq!(project(&cam, near, HALF), project(&cam, far, HALF)); + for fov in [0.2618, 0.6, std::f64::consts::FRAC_PI_2] { + cam.fov = fov; + let front = project(&cam, near, HALF); + let back = project(&cam, far, HALF); + assert!(back.x < front.x, "perspective must make the far edge smaller: {up:?}, {fov}"); + assert!((front.x - HALF as f32 * 0.5).abs() < 1e-4, "the front face must retain its size beside the orbit arrows"); + let focal_distance = f64::from(DESIGN_SIZE) / (2.0 * HALF * (fov * 0.5).tan()); + let ratio = focal_distance / (focal_distance + 2.0); + assert!((f64::from(back.x / front.x) - ratio).abs() < 1e-6); + } + } + } + + #[test] + fn perspective_toggle_changes_the_cube_and_its_faces_still_navigate() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"navigator_style":"cube", "look_at_anim":false})); + h.call("ui.view", json!({"view":"iso"})); + let orthographic = crate::scenario::handle_at("navigation_cube:front").unwrap(); + h.call("ui.set", json!({"perspective":true})); + let fov = camera(&h.app).fov; + assert!(fov > 0.0); + let p = crate::scenario::handle_at("navigation_cube:front").unwrap(); + assert_ne!(p, orthographic, "the drawn cube must follow the viewport's projection selection"); + h.call("ui.click", json!({"x":p.x,"y":p.y})); + assert_eq!(h.app.cam.aligned_standard_view(1e-5), Some(StandardView::Front)); + assert_eq!(camera(&h.app).fov, fov); + h.call("ui.set", json!({"autoOrthoFaces":true})); + assert_eq!(camera(&h.app).fov, 0.0, "automatic orthographic axis views also apply to the cube"); + h.call("ui.view", json!({"view":"iso"})); + assert_eq!(camera(&h.app).fov, fov); + } + + #[test] + fn perspective_cube_culls_sides_facing_away_and_ignores_model_framing() { + let cam = Camera { yaw: -0.1, pitch: 0.1, fov: 0.6, ..Default::default() }; + let faces = facets(&cam, Pos2::ZERO, HALF); + assert_eq!(faces.len(), 9, "only the front face is visible from this finite eye"); + assert!(faces.iter().all(|face| face.direction.y == -1.0)); + let points = |cam: &Camera| facets(cam, Pos2::ZERO, HALF).into_iter().flat_map(|face| face.points).collect::>(); + let expected = points(&cam); + for distance in [1e-3, 100.0, 1e12] { + assert_eq!(points(&Camera { distance, target: Vec3::new(123.0, -456.0, 789.0), ..cam }), expected); + } + let parallel = Camera { fov: 0.0, ..cam }; + for fov in [f64::NAN, f64::INFINITY, -1.0] { + assert_eq!(points(&Camera { fov, ..cam }), points(¶llel)); + } + } + #[test] fn cube_targets_are_only_six_faces_and_eight_corners_in_both_up_frames() { for up in [UpAxis::Z, UpAxis::Y] { @@ -463,12 +555,16 @@ mod tests { cam.set_view(view); for roll in [0.0, 0.7, std::f64::consts::FRAC_PI_2] { cam.roll = roll; - let faces = facets(&cam, Pos2::ZERO, HALF); - assert!(!faces.is_empty()); - for (i, face) in faces.iter().enumerate() { - assert_eq!(hit(&faces, face.centre), Some(i), "{up:?} {view:?} {roll} {}", face.label); + for fov in [0.0, 0.2618, 0.6, std::f64::consts::FRAC_PI_2] { + cam.fov = fov; + let faces = facets(&cam, Pos2::ZERO, HALF); + assert!(!faces.is_empty()); + for (i, face) in faces.iter().enumerate() { + assert_eq!(hit(&faces, face.centre), Some(i), "{up:?} {view:?} {roll} {fov} {}", face.label); + assert!(face.points.iter().all(|p| p.is_finite() && p.to_vec2().length() <= (HALF * 3.0_f64.sqrt()) as f32 + 1e-4)); + } + assert!(hit(&faces, pos2(80.0, 80.0)).is_none()); } - assert!(hit(&faces, pos2(80.0, 80.0)).is_none()); } } } diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index c45899be5..b944c09cb 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1118,6 +1118,13 @@ preference_settings! { /// A small dot at every vertex wherever edges are drawn (#7834). Off by default: the viewport /// draws edges only, as it always has. vertex_markers: bool = false => check("Vertex markers", "Show a small dot at every vertex wherever edges are drawn"); + /// A preview of a feature that changes a body draws the surface it adds in the preview + /// colour, working out face by face which surface that is. Off: the body is drawn as itself + /// and nothing is worked out (`preview::Colors::tint_new`). + preview_tint_new_faces: bool = true, PAGE_GRAPHICS => check_id("prefs.preview_tint_new_faces"); + /// A preview that removes material shows the removed shape as a red see-through ghost. Off: + /// the ghost is fully transparent and only its outline is drawn (`preview::Colors::cut_tint`). + cut_preview_tint: bool = true, PAGE_GRAPHICS => check_id("prefs.cut_preview_tint"); /// Restore the previous platform-specific fixed Render preview geometry budget. render_previous_geometry_budget: bool = false, PAGE_GRAPHICS => check_id("prefs.render_previous_geometry_budget"); /// How finely the viewport tessellates curved faces and edges: `coarse`, `normal`, `fine` or diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rs index d1ce36f4c..23c5dc61f 100644 --- a/crates/ui-egui/src/prefs/graphics.rs +++ b/crates/ui-egui/src/prefs/graphics.rs @@ -191,6 +191,10 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { setting::profile_operations(app, left).on_hover_text(app.tr("prefs.profile_operations_note")); crate::prefs::view_angles_checkbox(app, left); setting::reference_geometry_through_bodies(app, left).on_hover_text(app.tr("settings.reference_geometry_through_bodies_help")); + let tint_new = setting::preview_tint_new_faces(app, left).on_hover_text(app.tr("prefs.preview_tint_new_faces_help")); + crate::scenario::publish_target("prefs:preview_tint_new_faces", tint_new.rect); + let cut_tint = setting::cut_preview_tint(app, left).on_hover_text(app.tr("prefs.cut_preview_tint_help")); + crate::scenario::publish_target("prefs:cut_preview_tint", cut_tint.rect); setting::sketch_halo(app, left); setting::vertex_markers(app, left); } diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 266fc4042..660c834e7 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -967,6 +967,105 @@ fn fillet_face_then_press_pull_edits_its_fillet() { assert_eq!(d.editing.map(|e| e.0), Some(fillet)); } +/// Press Pull on a chamfer's flat face reopens the chamfer to change its distance, as on a +/// fillet's face, rather than extruding it (#4986): picked first, or picked with Press Pull +/// already open. +#[test] +fn chamfer_face_then_press_pull_edits_its_chamfer() { + let script = json!([ + {"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20}}, + {"command": "solid.chamfer", "params": {"edges": [[40, 0, 10]], "distance": 3}} + ]); + // The middle of the chamfer's face, from (37, 0) to (40, 3). + let p = Vec3::new(38.5, 1.5, 10.0); + let bevel = |app: &SolveApp| { + let names = solidcraft_engine::doc::naming::face_names_at(&app.session.model.state(), &[p]); + assert!(names[0].contains("blend"), "{names:?}"); + let st = app.session.model.state(); + let b = st.body("Body1").unwrap(); + let index = solidcraft_engine::doc::naming::face_names(b).iter().position(|n| *n == names[0]).unwrap(); + Sel::Face { body: "Body1".into(), index, point: p } + }; + let mut app = app_with(script.clone()); + let chamfer = app.session.doc.features.last().unwrap().id; + let sel = bevel(&app); + let d = start(&mut app, vec![sel], "solid.press_pull"); + assert!(matches!(&d.kind, Kind::Fillet { radius, chamfer: true, .. } if radius.starts_with('3')), "{:?}", d.kind); + assert_eq!(d.editing.map(|e| e.0), Some(chamfer)); + + let mut app = app_with(script); + app.start("solid.press_pull"); + let sel = bevel(&app); + let index = if let Sel::Face { index, .. } = &sel { *index } else { 0 }; + crate::viewport::dialog_pick(&mut app, &crate::viewport::Hit::Face { body: "Body1".into(), index, point: p }, sel); + let d = app.dialog.clone().unwrap(); + assert!(matches!(d.kind, Kind::Fillet { chamfer: true, .. }), "{:?}", d.kind); + assert_eq!(d.editing.map(|e| e.0), Some(chamfer)); +} + +/// Press Pull reopens a fillet or chamfer of several edges with its arrow on the edge of the face +/// clicked, not on the feature's first edge (the Sample Plate's far corner): picked first, or +/// picked with Press Pull open. Opened from the history, the arrow stays on the first edge. +#[test] +fn press_pull_on_a_blend_face_puts_the_arrow_on_the_clicked_edge() { + let r = 6.0 * std::f64::consts::FRAC_1_SQRT_2; + let chamfered = json!([ + {"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20}}, + {"command": "solid.chamfer", "params": {"edges": [[20, 0, 20], [40, 15, 20], [20, 30, 20], [0, 15, 20]], "distance": 2}} + ]); + // The script, the body, a point on the clicked blend face, its edge, the feature's first edge. + let cases = [ + (solidcraft_engine::sample::script(), "Plate", Vec3::new(74.0 + r, 44.0 + r, 4.0), Vec3::new(80.0, 50.0, 4.0), Vec3::new(0.0, 0.0, 4.0)), + (chamfered, "Body1", Vec3::new(20.0, 29.0, 19.0), Vec3::new(20.0, 30.0, 20.0), Vec3::new(20.0, 0.0, 20.0)), + ]; + for (script, body, p, clicked, first) in cases { + let setup = |h: &mut crate::scenario::Harness| -> Sel { + h.app.session.run_script(&script).unwrap(); + h.frames(2); + h.step(&json!({"call": "ui.view", "params": {"view": "fit"}})).unwrap(); + let names = solidcraft_engine::doc::naming::face_names_at(&h.app.session.model.state(), &[p]); + assert!(names[0].contains("blend"), "{names:?}"); + let st = h.app.session.model.state(); + let index = solidcraft_engine::doc::naming::face_names(st.body(body).unwrap()).iter().position(|n| *n == names[0]).unwrap(); + Sel::Face { body: body.into(), index, point: p } + }; + // The arrow is nearer `want` than `other` on screen. + let arrow_near = |h: &mut crate::scenario::Harness, want: Vec3, other: Vec3, how: &str| { + h.frames(5); + assert!( + matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::Fillet { .. })), + "{body} {how}: {:?}", + h.app.dialog.as_ref().map(|d| &d.kind) + ); + let tip = crate::scenario::handle_at("arrow").unwrap_or_else(|| panic!("{body} {how}: no arrow")); + let mut dist = |w: Vec3| { + let [x, y] = h.at(&json!({"world": [w.x, w.y, w.z]})).unwrap(); + tip.distance(egui::pos2(x as f32, y as f32)) + }; + let (a, b) = (dist(want), dist(other)); + assert!(a < b, "{body} {how}: the arrow is {a} px from the edge it should be on, {b} px from the other"); + }; + let mut h = crate::scenario::Harness::new(); + let face = setup(&mut h); + h.app.session.selection = vec![face]; + h.step(&json!({"start": "solid.press_pull"})).unwrap(); + arrow_near(&mut h, clicked, first, "picked first"); + // No click to go by: the feature's first edge, as before. + let id = h.app.dialog.as_ref().and_then(|d| d.editing).map(|e| e.0).unwrap(); + crate::dialogs::cancel(&mut h.app); + h.step(&json!({"call": "ui.editFeature", "params": {"feature": id}})).unwrap(); + arrow_near(&mut h, first, clicked, "from the history"); + + let mut h = crate::scenario::Harness::new(); + let face = setup(&mut h); + h.step(&json!({"start": "solid.press_pull"})).unwrap(); + let index = if let Sel::Face { index, .. } = &face { *index } else { 0 }; + let hit = crate::viewport::Hit::Face { body: body.into(), index, point: p }; + crate::viewport::dialog_pick(&mut h.app, &hit, face); + arrow_near(&mut h, clicked, first, "picked with Press Pull open"); + } +} + #[test] fn faces_then_shell_and_face_then_hole() { let mut app = boxed(); @@ -1582,6 +1681,39 @@ fn modeled_thread_survives_timeline_double_click_and_ok() { } } +/// A modeled thread's editor previews; unticking Modeled makes it a plain edit, so its OK +/// computes off the window thread from the design as it is: a body hidden meanwhile doesn't +/// refuse it as a changed design. +#[test] +fn a_thread_edit_switched_to_cosmetic_applies_after_a_body_is_hidden() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.apply_off_thread = Some(std::time::Duration::ZERO); + h.app.run("solid.cylinder", json!({"radius":4,"height":4})).unwrap(); + h.app.run("solid.box", json!({"corner":[20,0,0],"length":4,"width":4,"height":4})).unwrap(); + let Sel::Face { point, .. } = thread_face(&h.app, "Body1") else { panic!("face") }; + let id = h.app.run("solid.thread", json!({"face":point,"designation":"M8x1","modeled":true})).unwrap()["feature"].as_u64().unwrap(); + h.frames(4); + h.step(&json!({"click":{"handle":"timeline:Thread1"},"double":true})).unwrap(); + h.frames(4); + assert!(h.app.dialog.as_ref().unwrap().previews(), "a modeled thread previews"); + h.app.dialog.as_mut().unwrap().extra["modeled"] = json!(false); + assert!(!h.app.dialog.as_ref().unwrap().previews()); + h.app.run("browser.visibility", json!({"items":["Body2"],"visible":false})).unwrap(); + h.step(&json!({"widget":"OK"})).unwrap(); + for _ in 0..500 { + if h.app.applying.is_none() { + break; + } + h.frames(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + h.frames(4); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + assert_eq!(h.app.session.doc.marker, None); + assert!(matches!(h.app.session.doc.feature(id).unwrap().kind, solidcraft_engine::doc::FeatureKind::Thread { modeled: false, .. })); +} + #[test] fn planar_face_reopen_keeps_the_tight_pick_tolerance() { for (command, mut params, point) in [ diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index ed6b9fdbb..d1f9ea133 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -1,9 +1,10 @@ //! Live operation previews. While a feature dialog is open, its commands are evaluated on a //! scratch copy of the session ([`solidcraft_engine::Session::preview`]), off the UI thread //! where threads exist, and the result is drawn in place of the bodies it changes: new surface -//! tinted, removed material as a translucent ghost. The last good preview stays up while the -//! next one computes; once the current inputs make the feature fail, nothing is previewed and -//! the error shows in the dialog (#3254). +//! tinted (unless Graphics' Tint new surface in a preview is off, when a changed body is drawn +//! as itself), removed material as a translucent ghost. The last good preview stays up while +//! the next one computes; once the current inputs make the feature fail, nothing is previewed +//! and the error shows in the dialog (#3254). //! Nothing here touches the document or the undo history. //! //! A feature that adds or removes a tool body (join, cut, intersect) shows only its tool. That @@ -19,6 +20,7 @@ use solidcraft_engine::Session; use solidcraft_engine::doc::ModelState; use solidcraft_engine::doc::progress::Progress; use solidcraft_engine::geom::{Aabb3, Mesh, Ring, Vec3}; +use solidcraft_engine::kernel::history::Change; use crate::SolveApp; use crate::gpu::{GpuScene, SceneSlot}; @@ -28,6 +30,8 @@ use crate::theme::Tokens; #[derive(Clone, Copy, Debug)] pub struct Colors { pub body: [u8; 4], + /// The tool a join, cut or intersect adds, a datum plane a preview creates, and, where the + /// preference asks for it (`tint_new`), the surface a feature adds to a body it changes. pub added: [u8; 4], /// A body the preview creates (New Body), so it doesn't look like a join. pub new_body: [u8; 4], @@ -35,12 +39,29 @@ pub struct Colors { pub edge: [u8; 4], /// Whether a moved component's old place is drawn as a ghost (Drive Joints' Show ghost). pub ghost: bool, + /// Whether the surface a feature adds to a body it changes is drawn in the added colour + /// (Graphics' Tint new surface in a preview). Off: that body is drawn as itself, and which + /// of its faces are new is never worked out. + pub tint_new: bool, + /// Whether removed material is filled in the cut colour (Graphics' Show removed material in + /// red): the see-through cut and the ghost of the shape a feature replaces. Off: those fills + /// are left out altogether, so they are fully transparent and only outlines are drawn. + pub cut_tint: bool, } impl Colors { pub fn from_tokens(t: &Tokens) -> Colors { let c = |c: egui::Color32| c.to_srgba_unmultiplied(); - Colors { body: c(t.body), added: c(t.preview_add), new_body: c(t.preview_new), removed: c(t.preview_cut), edge: c(t.body_edge), ghost: true } + Colors { + body: c(t.body), + added: c(t.preview_add), + new_body: c(t.preview_new), + removed: c(t.preview_cut), + edge: c(t.body_edge), + ghost: true, + tint_new: true, + cut_tint: true, + } } fn for_tool(t: &Tokens, tab: &str, active: bool) -> Colors { @@ -366,6 +387,8 @@ pub fn update(app: &mut SolveApp, ctx: &egui::Context) { if app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::Assembly(crate::dialogs_assembly::Asm::Drive { .. }))) { colors.ghost = app.preferences.drive_joints_ghost; } + colors.tint_new = app.preferences.preview_tint_new_faces; + colors.cut_tint = app.preferences.cut_preview_tint; let key = job_key(&cmds, app.session.revision, colors); let stream_key = stream_key(&cmds, app.session.revision, colors); let tool = as_new_body(&cmds).is_some(); @@ -577,6 +600,7 @@ fn build_tool(before: &ModelState, after: &ModelState, c: Colors, op: &str) -> B let i = *k as usize; if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { match op { + "cut" if !c.cut_tint => {} "cut" => sc.xray_tri(p.to_f32(), n.to_f32(), removed), "intersect" => sc.xray_tri(p.to_f32(), n.to_f32(), intersect), _ => sc.tri(p.to_f32(), n.to_f32(), added), @@ -665,26 +689,43 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { if old.as_ref().is_some_and(|bm| same(bm, &am)) { continue; } - let nf = am.tri_face.iter().max().map_or(0, |m| *m as usize + 1); - let added: Vec = match &old { - Some(bm) => new_faces(&am, nf, bm), - None => vec![true; nf], - }; // Material removed from a body (a hole, a pocket): its new faces also show through the // body in the cut colour, so the cut is seen from any side. - let cut = old.as_ref().is_some_and(|bm| am.measure().volume < bm.measure().volume - 1e-6); + let cut = c.cut_tint && old.as_ref().is_some_and(|bm| am.measure().volume < bm.measure().volume - 1e-6); + // Which of the body's faces the feature made, asked only when something is drawn from + // the answer: the cut above, and the tint the preference offers. A changed body is + // otherwise drawn as itself, so a preview looks like the model and nothing has to be + // worked out face by face. + let new_face: Vec = match &old { + Some(bm) if cut || c.tint_new => { + let mut new = new_faces(&am, am.tri_face.iter().max().map_or(0, |m| *m as usize + 1), bm); + // The kernel recorded which faces the operation that made this body generated, + // i.e. has no face of an input under it. The two answers are taken together + // because each misses something on its own: geometry cannot see a round small + // beside the part, which lies within its tolerance of the faces it is tangent + // to all along both of its sides, while the record may be of a later operation + // than the one previewed (a parameter change re-evaluates the design, and a + // body keeps the history of whatever last made it), so the record only ever + // adds faces to the answer. + if let Some(history) = a.body.history() { + for (is_new, face) in new.iter_mut().zip(&history.faces) { + *is_new |= face.change == Change::Generated; + } + } + new + } + _ => Vec::new(), + }; + let kept = if old.is_some() { body_color } else { new_body }; for (t, f) in am.triangles.iter().zip(&am.tri_face) { - let new = added.get(*f as usize).copied().unwrap_or(true); - let col = match (new, old.is_some()) { - (false, _) => body_color, - (true, true) => added_color, - (true, false) => new_body, - }; + let new = new_face.get(*f as usize).copied().unwrap_or(false); + let col = if new && c.tint_new { added_color } else { kept }; + let through = cut && new; for k in t { let i = *k as usize; if let (Some(p), Some(n)) = (am.positions.get(i), am.normals.get(i)) { sc.tri(p.to_f32(), n.to_f32(), col); - if new && cut { + if through { sc.xray_tri(p.to_f32(), n.to_f32(), removed); } } @@ -708,20 +749,22 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { continue; } let m = b.mesh(); - // A changed body's surface it keeps is not removed material: drawn as ghost there it - // lies on the new body's face, and where that face is curved and meshed anew (its - // boundary moved) the two triangulations cross by up to their chord error, far past the - // ghost's depth bias, so the ghost showed through the new face in slivers. - let kept = if gone { None } else { after.body(&b.name).and_then(|a| SurfaceIndex::new(&a.mesh())) }; - for t in &m.triangles { - let Some(corners) = m.tri(t) else { continue }; - if kept.as_ref().is_some_and(|k| on_surface(k, corners)) { - continue; - } - for k in t { - let i = *k as usize; - if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { - sc.ghost_tri(p.to_f32(), n.to_f32(), removed); + if c.cut_tint { + // A changed body's surface it keeps is not removed material: drawn as ghost there it + // lies on the new body's face, and where that face is curved and meshed anew (its + // boundary moved) the two triangulations cross by up to their chord error, far past the + // ghost's depth bias, so the ghost showed through the new face in slivers. + let kept = if gone { None } else { after.body(&b.name).and_then(|a| SurfaceIndex::new(&a.mesh())) }; + for t in &m.triangles { + let Some(corners) = m.tri(t) else { continue }; + if kept.as_ref().is_some_and(|k| on_surface(k, corners)) { + continue; + } + for k in t { + let i = *k as usize; + if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { + sc.ghost_tri(p.to_f32(), n.to_f32(), removed); + } } } } @@ -770,6 +813,12 @@ fn on_surface(index: &SurfaceIndex, [a, b, c]: [Vec3; 3]) -> bool { [a, b, c, (a + b) / 2.0, (b + c) / 2.0, (c + a) / 2.0, (a + b + c) / 3.0].into_iter().all(|p| index.contains(p)) } +/// Points of one face the vote in [`new_faces`] asks about: every centroid of a face with no +/// more than this many triangles, so its answer doesn't ride on where that face's rows of +/// facets happen to fall, and a spread sample of a larger one. The lookups per face stay +/// bounded, so a modeled thread's thousands of faces still cost little. +const FACE_SAMPLES: usize = 24; + /// Which of the `nf` faces of `m` are new surface, i.e. not on the old mesh? Each is decided by /// a vote of points on it (triangle centroids spread over the face). One pass over `m`'s /// triangles gathers the centroids, and the old mesh is indexed once, so the cost stays @@ -789,10 +838,23 @@ fn new_faces(m: &Mesh, nf: usize, old: &Mesh) -> Vec { if cents.is_empty() { return true; } - let step = cents.len().div_ceil(9); - let samples: Vec<&Vec3> = cents.iter().step_by(step.max(1)).collect(); + let samples: Vec<&Vec3> = if cents.len() <= FACE_SAMPLES { + cents.iter().collect() + } else { + // Spread by the golden ratio rather than at a fixed step: a face's triangles + // come in rows across its curve, and a step that divides the row length would + // ask about the same place in every row (a blend's tangent sides, say), so two + // alike faces could be told apart by nothing but how long they are. + let len = cents.len() as f64; + (0..FACE_SAMPLES).filter_map(|i| cents.get(((i as f64 * 0.618_033_988_75).fract() * len) as usize)).collect() + }; let off = samples.iter().filter(|p| !index.contains(***p)).count(); - off * 3 > samples.len() + // More than an eighth of the face off the old surface is new surface. A blend meets + // the faces it rounds tangentially, so the rows of facets along both of its sides + // lie within the tolerance of the old surface and only the band through its middle + // is clearly off: a small round on a large part never reaches the third the vote + // asked for before, and was drawn as if it had always been there. + off * 8 > samples.len() }) .collect() } @@ -948,7 +1010,16 @@ mod tests { } fn colors() -> Colors { - Colors { body: [1, 1, 1, 255], added: [2, 2, 2, 255], new_body: [4, 4, 4, 255], removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true } + Colors { + body: [1, 1, 1, 255], + added: [2, 2, 2, 255], + new_body: [4, 4, 4, 255], + removed: [3, 3, 3, 100], + edge: [0, 0, 0, 255], + ghost: true, + tint_new: true, + cut_tint: true, + } } #[test] @@ -1220,6 +1291,32 @@ mod tests { assert_eq!(count(&b.scene, &b.scene.xray, 28, colors().removed), 0); } + /// Graphics' Show removed material in red, off: the cut and the ghost of the shape the + /// feature replaces are left out, and the body itself is still drawn. + #[test] + fn removed_material_can_be_left_fully_transparent() { + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let cmds = [("solid.hole".to_string(), json!({"position": [20, 15, 20], "diameter": 5, "depth": 10}))]; + let p = s.preview(&cmds).unwrap(); + let plain = colors(); + let b = build(&p.before, &p.after, plain); + assert!(count(&b.scene, &b.scene.ghost, 28, plain.removed) > 0, "the replaced shape is ghosted while the tint is on"); + let quiet = Colors { cut_tint: false, ..plain }; + let b = build(&p.before, &p.after, quiet); + assert_eq!(count(&b.scene, &b.scene.xray, 28, quiet.removed), 0, "no see-through cut"); + assert_eq!(count(&b.scene, &b.scene.ghost, 28, quiet.removed), 0, "no ghost of the old shape"); + assert!(count(&b.scene, &b.scene.tris, 28, quiet.body) > 0, "the body is still drawn"); + // The tool of a cut is left out too, its outline alone showing where it goes. + let cmds = [("solid.box".to_string(), json!({"length": 10, "width": 10, "height": 30, "operation": "new"}))]; + let p = s.preview(&cmds).unwrap(); + let shown = build_tool(&p.before, &p.after, plain, "cut"); + assert!(count(&shown.scene, &shown.scene.xray, 28, plain.removed) > 0, "the tool is see-through red while the tint is on"); + let b = build_tool(&p.before, &p.after, quiet, "cut"); + assert_eq!(count(&b.scene, &b.scene.xray, 28, quiet.removed), 0, "no see-through tool"); + assert!(!b.scene.overlay.is_empty(), "the tool's outline still shows where the cut goes"); + } + fn plate() -> Session { let mut s = Session::default(); for (id, p) in [ @@ -1383,6 +1480,42 @@ mod tests { assert!(!b.scene.ghost.is_empty(), "the edge the fillet removes is still shown as ghost"); } + /// Graphics' Tint new surface in a preview, off: the changed body is drawn as itself, and + /// no face of it is worked out. + #[test] + fn the_tint_on_new_surface_can_be_turned_off() { + let s = plate(); + let cmds = [("solid.fillet".to_string(), json!({"edges": [[0, 0, 10]], "radius": 3}))]; + let plain = Colors { tint_new: false, ..colors() }; + let b = compute(&s, &cmds, plain).unwrap(); + assert_eq!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, plain.added), 0, "nothing is tinted"); + assert!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, plain.body) > 0, "the body is drawn as itself"); + } + + /// With the tint on, a round far smaller than the part is new surface too. Every facet of + /// this one lies within the preview's tolerance (half a millimetre here) of the faces it is + /// tangent to, so no point on it is off the old body and only the kernel's record of what + /// the fillet generated can tell. + #[test] + fn a_small_round_on_a_large_part_is_tinted_as_new() { + let mut s = Session::default(); + for (id, p) in [ + ("sketch.create", json!({"plane": "XY"})), + ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [200, 150]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance": 10})), + ] { + s.execute(id, &p).unwrap(); + } + // The plate's diagonal is 250 mm, so a point counts as on the old surface within half a + // millimetre: a 0.5 mm round never leaves it, bulging 0.15 mm at the most. + let tinted = Colors { tint_new: true, ..colors() }; + let b = compute(&s, &[("solid.fillet".into(), json!({"edges": [[100, 0, 10]], "radius": 0.5}))], tinted).unwrap(); + let added = count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, tinted.added); + assert!(added > 0, "the round is drawn as new surface, not as part of the old body"); + assert!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, tinted.body) > 0, "the rest of the plate is kept"); + } + /// A cut shows its tool see-through and replaces nothing. #[test] fn cut_preview_scene() { diff --git a/crates/ui-egui/src/preview_drag_tests.rs b/crates/ui-egui/src/preview_drag_tests.rs index 3167b3156..22e96f819 100644 --- a/crates/ui-egui/src/preview_drag_tests.rs +++ b/crates/ui-egui/src/preview_drag_tests.rs @@ -3,7 +3,16 @@ use super::*; use serde_json::json; fn colors() -> Colors { - Colors { body: [1, 1, 1, 255], added: [2, 2, 2, 255], new_body: [2, 2, 2, 255], removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true } + Colors { + body: [1, 1, 1, 255], + added: [2, 2, 2, 255], + new_body: [2, 2, 2, 255], + removed: [3, 3, 3, 100], + edge: [0, 0, 0, 255], + ghost: true, + tint_new: true, + cut_tint: true, + } } fn fixture() -> Session { diff --git a/crates/ui-egui/src/render_ui/mod.rs b/crates/ui-egui/src/render_ui/mod.rs index 4b6b9d4c1..b3c2dd007 100644 --- a/crates/ui-egui/src/render_ui/mod.rs +++ b/crates/ui-egui/src/render_ui/mod.rs @@ -198,6 +198,15 @@ pub(crate) fn overlays(app: &mut SolveApp, ui: &mut egui::Ui) { crate::render_workspace::assign::selection_bar(app, ui, free); crate::render_workspace::assign::replacement_dialog(app, ui.ctx()); crate::navigation_bar_view::show(app, ui, viewport); + crate::shell::register_panel(app, "render:compare-controls", None, None); + if !crate::render_workspace::result_active(app) && app.session.render_selected_result().is_some() { + let free = if crate::render_workspace::job_busy(app) { Container::below_navigation_row(free) } else { free }; + let card = + Container::navigation_card(ui.ctx(), egui::Id::new("sc_render_compare_controls"), free.center_top(), egui::Align2::CENTER_TOP, |ui| { + crate::render_workspace::comparison_controls(app, ui) + }); + crate::shell::register_panel(app, "render:compare-controls", Some(card.response.rect), None); + } if !focused(app) { shots_pill(app, ui, free); } diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index a64998aa8..3aa351945 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -25,6 +25,9 @@ const MAX_GEOMETRY_BYTES: usize = #[path = "render_workspace_ribbon.rs"] mod ribbon; +#[path = "render_workspace_compare.rs"] +mod compare; + #[path = "render_workspace_cpu.rs"] mod cpu; @@ -145,6 +148,7 @@ pub struct State { preview_image: Option, clipboard_image: Option, clipboard_text: Option, + comparison_images: Vec<(solidcraft_engine::render::job::JobId, Result)>, } /// Provisional pixels are never an export source and never replace the retained final image. @@ -361,6 +365,9 @@ pub struct ViewState { clean_setup: Option, job: Option, completed: Option, + retained: Vec, + follow_job: bool, + compare: Option, transparent: bool, method: ImageMethod, raytrace: RaytraceOptions, @@ -426,6 +433,9 @@ impl Default for ViewState { clean_setup: None, job: None, completed: None, + retained: Vec::new(), + follow_job: true, + compare: None, transparent: false, method: ImageMethod::Raster, raytrace: RaytraceOptions::default(), @@ -474,6 +484,7 @@ impl Default for State { preview_image: None, clipboard_image: None, clipboard_text: None, + comparison_images: Vec::new(), } } } @@ -509,6 +520,10 @@ pub(crate) fn result_active(app: &SolveApp) -> bool { active(app) && app.render_workspace.view.result } +pub(crate) fn comparison_drag_captured(app: &SolveApp) -> bool { + active(app) && app.render_workspace.view.compare.as_ref().is_some_and(|view| view.dragging) +} + pub(crate) fn fit_result(app: &mut SolveApp) { app.render_workspace.view.result_scale = ResultScale::Fit; } @@ -526,6 +541,9 @@ pub(crate) fn inspect_state(app: &SolveApp) -> serde_json::Value { json!({ "active": active(app), "stage": view.stage.key(), "setup": view.name, "draft_dirty": view.dirty, "method": method, "job": view.job, "completed": view.completed, + "results": view.retained, + "comparison": view.compare, + "queue": app.session.render_queue_state(), "showing_result": view.result, "export_format": if view.studio.export_exr {"exr"} else {"png"}, }) } @@ -614,6 +632,15 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { Err(e) => app.set_status(e.to_string(), true), } } + crate::documents::advance_render_batches(app, ctx); + if let Err(error) = app.session.advance_render_batch() { + app.set_status(error.to_string(), true); + } + follow_batch(app); + let queue = app.session.render_queue_state(); + if queue.running != 0 || queue.waiting != 0 { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } if app.render_workspace.view.job.is_some() { cache_render_images(app, ctx); } @@ -640,6 +667,7 @@ pub(crate) fn invalidate_images(app: &mut SolveApp) { app.render_workspace.image = None; app.render_workspace.image_info = None; app.render_workspace.preview_image = None; + app.render_workspace.comparison_images.clear(); } pub fn invalidate_scene(app: &mut SolveApp) { @@ -1136,9 +1164,6 @@ fn job_controls(app: &mut SolveApp, ui: &mut egui::Ui, compact: bool) { Ok(status) => { let phase = status["progress"]["phase"].as_str().unwrap_or(crate::i18n::tr("render.property_unknown")); busy = matches!(phase, "queued" | "preparing" | "running" | "encoding" | "cancelling"); - if phase == "completed" { - app.render_workspace.view.completed = Some(job); - } state = Some(status); } Err(error) => { @@ -1278,6 +1303,11 @@ fn cache_completed_image(app: &mut SolveApp, ctx: &egui::Context) { let result = (|| -> Result { let handle = app.session.render_job_handle(job).map_err(|e| e.to_string())?; let frame = handle.frame().map_err(|e| e.to_string())?.ok_or(crate::i18n::tr("render.error_no_completed_image"))?; + if let Some((_, cached)) = app.render_workspace.comparison_images.iter().find(|(id, _)| *id == job) { + let texture = cached.clone()?; + app.render_workspace.image_info = Some(frame.info.clone()); + return Ok(texture); + } let captured = handle.status().map_err(|e| e.to_string())?; let budget = if frame.info.executor.as_str() == "gpu-path" { solidcraft_engine::render::job::GPU_PATH_LIMITS @@ -1285,7 +1315,6 @@ fn cache_completed_image(app: &mut SolveApp, ctx: &egui::Context) { captured_image_limits(&captured.request) }; let image = decode_render_image(frame.png(), frame.info.width, frame.info.height, budget, ctx.input(|i| i.max_texture_side))?; - app.session.execute("render.result.pin", &json!({"job":job})).map_err(|e| e.to_string())?; app.render_workspace.image_info = Some(frame.info.clone()); Ok(ctx.load_texture("sc_render_image", image, egui::TextureOptions::LINEAR)) })(); @@ -1341,16 +1370,17 @@ fn cache_preview_frame(app: &mut SolveApp, ctx: &egui::Context, info: &PreviewIn } fn cache_preview_image(app: &mut SolveApp, ctx: &egui::Context) { - if let Some(job) = app.render_workspace.view.job + if app.render_workspace.view.follow_job + && let Some(job) = app.render_workspace.view.job && let Ok(handle) = app.session.render_job_handle(job) { let preview = handle.preview().ok().flatten(); // Read the final after the checkpoint: completion may occur after the panel's // earlier status query. Promote the real final before dropping its preview, // rather than briefly falling back to an older job and losing result framing. - if handle.frame().ok().flatten().is_some() { - app.render_workspace.view.completed = Some(job); - } else if let Some(preview) = preview { + if handle.frame().ok().flatten().is_none() + && let Some(preview) = preview + { cache_preview_frame(app, ctx, &preview.info, preview.png()); return; } @@ -1373,11 +1403,44 @@ fn cache_render_images(app: &mut SolveApp, ctx: &egui::Context) { app.render_workspace.view.result_job == Some(preview.info.frame.job) && app.render_workspace.view.job == Some(preview.info.frame.job) }); cache_preview_image(app, ctx); + sync_results(app); cache_completed_image(app, ctx); // Checkpoint updates and preview→final/cancel transitions preserve shared pan/zoom. remember_displayed_job(app, preserve_view); } +fn sync_results(app: &mut SolveApp) { + let Ok(mut results) = app.session.render_retained_results() else { return }; + let view = &mut app.render_workspace.view; + for result in &mut results { + if result.shot.is_none() { + result.shot = view.retained.iter().find(|old| old.frame.job == result.frame.job).and_then(|old| old.shot.clone()); + if result.shot.is_none() && view.job == Some(result.frame.job) { + result.shot = view.job_shot.clone(); + } + } + } + view.retained = results; + view.completed = app.session.render_selected_result(); + if view.compare.as_ref().is_some_and(|comparison| { + [comparison.left, comparison.right].into_iter().flatten().any(|job| !view.retained.iter().any(|result| result.frame.job == job)) + }) { + view.compare = None; + app.render_workspace.comparison_images.clear(); + } +} + +fn follow_batch(app: &mut SolveApp) { + let queue = app.session.render_queue_state(); + if let Some(job) = queue.job { + if app.render_workspace.view.job != Some(job) { + app.render_workspace.view.follow_job = app.render_workspace.view.compare.is_none(); + } + app.render_workspace.view.job = Some(job); + app.render_workspace.view.job_shot = queue.shot; + } +} + fn captured_image_limits(request: &solidcraft_engine::render::job::ImageRequest) -> RenderLimits { if request.integrator == Integrator::Raytrace { request.cpu_budget().image_limits(request.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())) @@ -1489,6 +1552,35 @@ fn result_rect(camera: Camera, size: [u32; 2], canvas: egui::Rect) -> egui::Rect } fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) { + compare::controls(app, ui); + let results = app.render_workspace.view.retained.clone(); + if !results.is_empty() { + let selected = results.iter().position(|result| Some(result.frame.job) == app.render_workspace.view.completed); + let label = selected.and_then(|index| results.get(index)).map(result_label).unwrap_or_else(|| app.tr("render.results_choose").to_string()); + let mut chosen = None; + let picker = crate::ui_kit::compact_dropdown_menu(ui, "render_results", &label, |ui| { + for (index, result) in results.iter().enumerate().rev() { + let response = crate::ui_kit::list_picker(ui, &format!("result:{index}"), &result_label(result), selected == Some(index)); + crate::scenario::publish_target(&format!("render:result:select:{index}"), response.rect); + if response.clicked() { + chosen = Some(index); + ui.close(); + } + } + }); + crate::scenario::publish_target("render:results", picker.rect); + if let Some(index) = chosen { + let _ = app.run("render.result.select", json!({"index":index})); + } + let discard = + ui.add_enabled_ui(selected.is_some(), |ui| crate::ui_kit::StageBar::icon_action(ui, "delete", app.tr("cmd.render.result.discard"))).inner; + crate::scenario::publish_target("render:result-discard", discard.rect); + if discard.clicked() + && let Some(index) = selected + { + let _ = app.run("render.result.discard", json!({"index":index})); + } + } for (view, key) in [("model", "render.state_model"), ("fit", "render.output_fit"), ("actual", "render.result_actual")] { let enabled = view != "actual" || !reduced_display(app); if crate::ui_kit::button(ui, app.tr(key), crate::ui_kit::Button::Enabled(enabled)).clicked() { @@ -1517,6 +1609,15 @@ fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) { } } +fn result_label(result: &solidcraft_engine::render_jobs::RetainedResult) -> String { + let name = result.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed")); + let label = crate::i18n::format( + "render.results_label", + &[("number", &result.frame.job.serial.to_string()), ("shot", name), ("seconds", &format!("{:.0}", result.seconds))], + ); + if result.stale { crate::i18n::format("render.results_stale_label", &[("result", &label)]) } else { label } +} + fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) { cache_render_images(app, ui.ctx()); let t = Tokens::get(); @@ -1966,6 +2067,12 @@ fn preview_background(app: &SolveApp) -> Tokens { } pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { + if app.render_workspace.view.compare.is_some() { + app.render_workspace.view.environment_ring = environment::RingView::default(); + assign::stop(app); + compare::show(app, ui); + return; + } if app.render_workspace.view.result { app.render_workspace.view.environment_ring = environment::RingView::default(); assign::stop(app); @@ -2019,8 +2126,26 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } else { app.viewport.hover = None; } + crate::gpu::paint_background(ui.painter(), viewport, &preview_background(app)); + paint_product(app, ui, rect, app.cam, None); + shot::overlay(app, ui, viewport); + crate::viewport::axis_view(app, ui, viewport); + crate::navigation_bar_view::show(app, ui, viewport); +} + +fn product_projection(camera: Camera, radius: f64, canvas: egui::Rect, image: Option) -> solidcraft_engine::render::Mat4 { + let image = image.unwrap_or(canvas); + let projection = camera.view_proj(f64::from(image.width() / image.height().max(1.0)), radius); + let sx = f64::from(image.width() / canvas.width().max(1.0)); + let sy = f64::from(image.height() / canvas.height().max(1.0)); + let tx = f64::from(2.0 * (image.center().x - canvas.center().x) / canvas.width().max(1.0)); + let ty = f64::from(2.0 * (canvas.center().y - image.center().y) / canvas.height().max(1.0)); + solidcraft_engine::render::Mat4([[sx, 0.0, 0.0, 0.0], [0.0, sy, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [tx, ty, 0.0, 1.0]]).mul(&projection) +} + +fn paint_product(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera: Camera, image: Option) { let background = preview_background(app); - crate::gpu::paint_background(ui.painter(), viewport, &background); + crate::gpu::paint_background(ui.painter(), rect, &background); let result = (|| -> Result<(), String> { if app.viewport.gpu.is_none() { return Err(crate::i18n::tr("render.error_gpu_preview").into()); @@ -2081,7 +2206,6 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if scene.bounds.is_empty() { return Err(crate::i18n::tr("render.error_visible_solid").into()); } - let camera = app.cam; let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); let eye = camera.eye(); let highlight_key = crate::viewport::highlight_key(app); @@ -2106,7 +2230,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { pv_key: 0, pv_slot: slot, pv_hide: false, - view_proj: camera.view_proj(f64::from(rect.width() / rect.height().max(1.0)), radius).to_f32(), + view_proj: product_projection(camera, radius, rect, image).to_f32(), back: camera.back().to_f32(), size_px: [rect.width() * ppp, rect.height() * ppp], clip: [0.0; 4], @@ -2130,15 +2254,12 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }, hatch: Default::default(), }); - crate::blur::viewport(ui.painter(), rect, callback, viewport, [background.viewport_top, background.viewport_bottom]); + crate::blur::viewport(ui.painter(), rect, callback, rect, [background.viewport_top, background.viewport_bottom]); Ok(()) })(); if let Err(error) = result { preview_error(app, ui, rect, &error); } - shot::overlay(app, ui, viewport); - crate::viewport::axis_view(app, ui, viewport); - crate::navigation_bar_view::show(app, ui, viewport); } /// Apply validated UI requests after the same registry call used by automation. @@ -2147,6 +2268,45 @@ pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Va "render.preflight.copy" => { app.render_workspace.clipboard_text = Some(reply["text"].as_str().ok_or("invalid check report")?.to_string()); } + "render.compare" => compare::apply(app, reply)?, + "render.compare.divider" => { + let position = reply["position"].as_f64().ok_or("invalid comparison divider position")?; + if let Some(view) = &mut app.render_workspace.view.compare { + view.position = crate::ui_kit::comparison_position(position as f32); + } + } + "render.batch" => follow_batch(app), + "render.start" | "render.result.regrade" => { + let job = serde_json::from_value(reply["job"].clone()).map_err(|e| format!("invalid render job identity: {e}"))?; + let shot = if id == "render.result.regrade" { + app.render_workspace + .view + .retained + .iter() + .find(|result| Some(result.frame.job) == app.render_workspace.view.completed) + .and_then(|result| result.shot.clone()) + } else { + Some(app.render_workspace.view.name.clone()) + }; + if let Some(shot) = &shot { + let _ = app.session.label_render_job(job, shot); + } + app.render_workspace.view.job = Some(job); + app.render_workspace.view.job_shot = shot; + app.render_workspace.view.follow_job = app.render_workspace.view.compare.is_none(); + } + "render.result.select" | "render.result.discard" | "render.result.pin" => { + sync_results(app); + app.render_workspace.preview_image = None; + app.render_workspace.view.follow_job = false; + if matches!(id, "render.result.select" | "render.result.pin") { + app.render_workspace.view.compare = None; + app.render_workspace.comparison_images.clear(); + } + if id == "render.result.select" { + app.render_workspace.view.result = true; + } + } "render.output.size" => { let width = reply["width"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid output width")?; let height = reply["height"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid output height")?; @@ -2164,6 +2324,10 @@ pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Va return Err(app.tr("render.result_reduced_display").into()); } app.render_workspace.view.result = view != "model"; + if matches!(view, "model") || id == "render.result.close" { + app.render_workspace.view.compare = None; + app.render_workspace.comparison_images.clear(); + } match view { "fit" => fit_result(app), "actual" => app.render_workspace.view.result_scale = ResultScale::Actual, @@ -2229,6 +2393,9 @@ pub(crate) fn interactive_command_info(app: &SolveApp, command: &solidcraft_engi } info } +pub(crate) fn comparison_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + compare::controls(app, ui); +} pub(crate) fn start_interactive(app: &mut SolveApp, id: &str) -> bool { let handled = assign::start(app, id) || ribbon::start(app, id); // Opening Appearance Advanced must still reach its atmosphere controls after leaving Wear. diff --git a/crates/ui-egui/src/render_workspace_compare.rs b/crates/ui-egui/src/render_workspace_compare.rs new file mode 100644 index 000000000..ed28ed33b --- /dev/null +++ b/crates/ui-egui/src/render_workspace_compare.rs @@ -0,0 +1,291 @@ +//! Result comparison composition. The kit owns controls, chips and the divider. +use super::*; +use crate::ui_kit; +use solidcraft_engine::render::job::JobId; + +#[derive(Clone, Debug, serde::Serialize)] +pub(super) struct View { + pub left: Option, + pub right: Option, + pub position: f32, + pub reference: JobId, + #[serde(skip)] + pub dragging: bool, +} + +fn side_value(app: &SolveApp, side: Option) -> Option { + match side { + None => Some(json!("live")), + Some(job) => app.render_workspace.view.retained.iter().position(|result| result.frame.job == job).map(|index| json!(index)), + } +} + +pub(super) fn apply(app: &mut SolveApp, reply: &serde_json::Value) -> Result<(), String> { + if reply.get("off").and_then(serde_json::Value::as_bool) == Some(true) { + app.render_workspace.view.compare = None; + app.render_workspace.comparison_images.clear(); + return Ok(()); + } + sync_results(app); + let [left, right] = app.session.render_comparison().ok_or("comparison result is no longer retained")?; + let position = app.render_workspace.view.compare.as_ref().map_or(0.5, |view| view.position); + let reference = app + .render_workspace + .view + .compare + .as_ref() + .map(|view| view.reference) + .filter(|job| [left, right].contains(&Some(*job))) + .or(right) + .or(left) + .ok_or("comparison needs a retained result")?; + if app.render_workspace.view.compare.as_ref().is_none_or(|view| view.reference != reference) { + app.render_workspace.view.result_scale = ResultScale::Fit; + } + app.render_workspace.view.compare = Some(View { left, right, position, reference, dragging: false }); + app.render_workspace.view.result = true; + app.render_workspace.view.follow_job = false; + app.render_workspace.preview_image = None; + app.cancel_view_animation(); + app.viewport.nav = None; + app.viewport.key_hold = None; + app.viewport.orbit_free = None; + Ok(()) +} + +pub(super) fn start_default(app: &mut SolveApp) -> Result<(), String> { + sync_results(app); + if app.render_workspace.view.compare.is_some() { + app.run("render.compare", json!({"off":true}))?; + } else { + let index = app + .render_workspace + .view + .retained + .iter() + .position(|result| Some(result.frame.job) == app.render_workspace.view.completed) + .ok_or_else(|| app.tr("render.ribbon_no_result").to_string())?; + app.run("render.compare", json!({"left":"live","right":index}))?; + } + Ok(()) +} + +pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let results = &app.render_workspace.view.retained; + if results.is_empty() { + return; + } + let mut labels = vec![app.tr("render.compare_live").to_owned()]; + labels.extend(results.iter().map(|result| crate::i18n::format("render.compare_render", &[("number", &result.frame.job.serial.to_string())]))); + let mut targets = vec!["render:compare:live".to_string()]; + targets.extend(results.iter().enumerate().map(|(index, _)| format!("render:compare:result:{index}"))); + let choices: Vec<_> = std::iter::once(None).chain(results.iter().map(|result| Some(result.frame.job))).collect(); + let current = if app.render_workspace.view.result { app.render_workspace.view.completed } else { None }; + let comparison = app.render_workspace.view.compare.clone(); + let states: Vec<_> = + choices.iter().map(|side| comparison.as_ref().map_or(*side == current, |view| *side == view.left || *side == view.right)).collect(); + let mut selected = usize::MAX; + if ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { + targets: &targets.iter().map(String::as_str).collect::>(), + states: &states, + intrinsic: true, + dense: true, + compact: true, + workspace_accent: true, + ..Default::default() + }, + ) && let Some(chosen) = choices.get(selected).copied() + { + if let Some(view) = comparison { + if chosen == view.left || chosen == view.right { + let remaining = if chosen == view.left { view.right } else { view.left }; + let _ = app.run("render.compare", json!({"off":true})); + choose_single(app, remaining); + } else if let (Some(left), Some(right)) = (side_value(app, view.left), side_value(app, chosen)) { + let _ = app.run("render.compare", json!({"left":left,"right":right})); + } + } else if chosen != current { + let (left, right) = if chosen.is_none() { (chosen, current) } else { (current, chosen) }; + if let (Some(left), Some(right)) = (side_value(app, left), side_value(app, right)) { + let _ = app.run("render.compare", json!({"left":left,"right":right})); + } + } + } + if let Some(view) = app.render_workspace.view.compare.clone() { + let swap = ui_kit::compact_icon_label_button(ui, app.tr("render.compare_swap"), "compare", true); + crate::scenario::publish_target("render:compare:swap", swap.rect); + if swap.clicked() + && let (Some(left), Some(right)) = (side_value(app, view.right), side_value(app, view.left)) + { + let _ = app.run("render.compare", json!({"left":left,"right":right})); + } + } +} + +fn choose_single(app: &mut SolveApp, side: Option) { + match side { + None => { + let _ = app.run("render.result.view", json!({"view":"model"})); + } + Some(job) => { + if let Some(index) = app.render_workspace.view.retained.iter().position(|result| result.frame.job == job) { + let _ = app.run("render.result.select", json!({"index":index})); + } + } + } +} + +fn texture(app: &mut SolveApp, ctx: &egui::Context, job: JobId) -> Result { + if let Some((_, image)) = app.render_workspace.comparison_images.iter().find(|(id, _)| *id == job) { + return image.clone(); + } + if let Some((id, image)) = &app.render_workspace.image + && *id == job + { + let image = image.clone(); + app.render_workspace.comparison_images.push((job, image.clone())); + return image; + } + let image: Result = (|| { + let handle = app.session.render_job_handle(job).map_err(|error| error.to_string())?; + let frame = handle.frame().map_err(|error| error.to_string())?.ok_or("comparison image is not completed")?; + let captured = handle.status().map_err(|error| error.to_string())?; + let limits = if frame.info.executor.as_str() == "gpu-path" { + solidcraft_engine::render::job::GPU_PATH_LIMITS + } else { + captured_image_limits(&captured.request) + }; + let image = decode_render_image(frame.png(), frame.info.width, frame.info.height, limits, ctx.input(|input| input.max_texture_side))?; + Ok(ctx.load_texture("sc_render_compare", image, egui::TextureOptions::LINEAR)) + })(); + app.render_workspace.comparison_images.push((job, image.clone())); + image +} + +fn label(app: &SolveApp, side: Option) -> String { + side.and_then(|job| app.render_workspace.view.retained.iter().find(|result| result.frame.job == job)).map_or_else( + || app.tr("render.compare_live_preview").to_owned(), + |result| { + crate::i18n::format( + "render.compare_side", + &[ + ("number", &result.frame.job.serial.to_string()), + ("shot", result.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed"))), + ], + ) + }, + ) +} + +pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { + cache_render_images(app, ui.ctx()); + if app.render_workspace.view.compare.is_none() { + show_result(app, ui); + return; + } + ui.painter().rect_filled(ui.max_rect(), 0.0, Tokens::get().viewport_bottom); + let mut free = crate::render_ui::canvas(app, ui.max_rect()); + if ribbon::busy(app) { + free = ui_kit::Container::below_navigation_row(free); + } + let mut content = ui.new_child(egui::UiBuilder::new().max_rect(free).id_salt("render_compare_content")); + let ui = &mut content; + ui_kit::Container::navigation_contents(ui, |ui| { + ui.horizontal_wrapped(|ui| result_actions(app, ui)); + }); + let Some(view) = app.render_workspace.view.compare.clone() else { return }; + app.render_workspace.comparison_images.retain(|(job, _)| [view.left, view.right].contains(&Some(*job))); + let Some(reference) = app.render_workspace.view.retained.iter().find(|result| result.frame.job == view.reference).cloned() else { return }; + let stale = app.render_workspace.view.retained.iter().any(|result| [view.left, view.right].contains(&Some(result.frame.job)) && result.stale); + // Keep freshness and the capture summary below the image, as in the result board. + ui_kit::Panel::pinned_footer(ui, "render_compare_summary", 2, |ui| { + ui_kit::completion_text(ui, app.tr(if stale { "render.image_stale" } else { "render.result_current" }), !stale); + let summary = crate::i18n::format( + "render.compare_summary", + &[ + ("shot", reference.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed"))), + ("width", &reference.frame.width.to_string()), + ("height", &reference.frame.height.to_string()), + ("seconds", &format!("{:.0}", reference.seconds)), + ("renderer", reference.frame.executor.as_str()), + ("revision", &reference.frame.scene_generation.to_string()), + ], + ); + ui_kit::text(ui, &summary, ui_kit::Text::Inline); + }); + let canvas = ui.available_rect_before_wrap(); + if !canvas.is_positive() { + return; + } + let response = ui.allocate_rect(canvas, Sense::click_and_drag()); + app.viewport.rect = Some(canvas); + crate::viewport::refresh_layout(app, ui.ctx()); + let size = [reference.frame.width, reference.frame.height]; + if app.render_workspace.view.result_scale != ResultScale::Free { + app.render_workspace.view.result_camera = result_camera(size, canvas, ui.ctx().pixels_per_point(), app.render_workspace.view.result_scale); + } + // Reserve the divider before navigation; captured drags cannot reach any camera path. + let mut position = view.position; + let divider = ui_kit::comparison_divider(ui, canvas, &mut position, app.tr("render.compare_divider")); + let captured = divider.dragged() || divider.is_pointer_button_down_on() || divider.drag_stopped(); + if let Some(view) = &mut app.render_workspace.view.compare { + view.dragging = divider.is_pointer_button_down_on() || divider.dragged(); + } + if divider.changed() + && let Err(error) = app.run("render.compare.divider", json!({"position":position})) + { + app.set_status(error, true); + } + if !captured { + with_result_camera(app, |app| { + crate::navigation::handle(app, ui, canvas, &response, crate::navigation::NavCaps { orbit: false, pick: false }); + }); + } + let image = result_rect(app.render_workspace.view.result_camera, size, canvas); + let split = canvas.left() + canvas.width() * position; + let halves = [ + egui::Rect::from_min_max(canvas.min, egui::pos2(split, canvas.bottom())), + egui::Rect::from_min_max(egui::pos2(split, canvas.top()), canvas.max), + ]; + let camera = app.session.render_job_handle(reference.frame.job).ok().and_then(|handle| handle.status().ok()).map(|status| status.request.camera); + // Paint sources behind the already registered handle, then raise its shared chrome. + for ((side, half), right) in [view.left, view.right].into_iter().zip(halves).zip([false, true]) { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(canvas).id_salt(("compare_side", right))); + child.set_clip_rect(half.intersect(image).intersect(ui.clip_rect())); + if child.clip_rect().is_positive() { + match side { + None => { + if let Some(camera) = camera { + paint_product(app, &mut child, canvas, camera, Some(image)); + } + } + Some(job) => match texture(app, ui.ctx(), job) { + Ok(texture) => { + let source = app.render_workspace.view.retained.iter().find(|result| result.frame.job == job); + let aspect = source.map_or(1.0, |result| result.frame.width as f32 / result.frame.height.max(1) as f32); + let height = image.height().min(image.width() / aspect); + let destination = egui::Rect::from_center_size(image.center(), egui::vec2(height * aspect, height)); + child.painter().image( + texture.id(), + destination, + egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), + Tokens::get().file_image_tint, + ); + } + Err(error) => { + ui_kit::text(&mut child, &error, ui_kit::Text::Inline); + } + }, + } + } + ui_kit::comparison_badge(ui, half, &label(app, side), right); + } + // The line and handle must stay above both source callbacks and label chips. + ui_kit::comparison_divider_chrome(ui, canvas, position); + crate::scenario::publish_rect("render:compare:canvas", canvas); + crate::scenario::publish_rect("render:compare:image", image); +} diff --git a/crates/ui-egui/src/render_workspace_inspector.rs b/crates/ui-egui/src/render_workspace_inspector.rs index ffc21d715..307729afd 100644 --- a/crates/ui-egui/src/render_workspace_inspector.rs +++ b/crates/ui-egui/src/render_workspace_inspector.rs @@ -279,6 +279,29 @@ pub(super) fn panel(app: &mut SolveApp, ui: &mut egui::Ui) { } }, |ui| { + if output { + ui_kit::Panel::pinned_footer(ui, "render_output_footer", 1, |ui| { + ui.horizontal_wrapped(|ui| { + for (id, label, target) in [ + ("render.start", app.tr("cmd.render_start").to_owned(), "render:output:render"), + ( + "render.batch", + crate::i18n::format("render.batch_all_shots", &[("count", &app.session.doc.render.setups.len().to_string())]), + "render:output:all-shots", + ), + ] { + let ready = super::ribbon::action_ready(app, id); + let response = ui_kit::icon_label_action(ui, &label, Some("play"), ready.is_ok(), id == "render.start"); + let response = if let Err(reason) = ready { response.on_disabled_hover_text(reason) } else { response }; + crate::scenario::publish_target(target, response.rect); + if response.clicked() { + app.start(id); + } + } + }); + crate::scenario::publish_rect("render:output-footer", ui.min_rect()); + }); + } if !appearance_editor && !output && !standalone { header(app, ui); ui_kit::Panel::pinned_footer(ui, "render_job_footer", 4, |ui| { diff --git a/crates/ui-egui/src/render_workspace_ribbon.rs b/crates/ui-egui/src/render_workspace_ribbon.rs index ce8ec02f8..ff8cb4f20 100644 --- a/crates/ui-egui/src/render_workspace_ribbon.rs +++ b/crates/ui-egui/src/render_workspace_ribbon.rs @@ -7,7 +7,10 @@ use solidcraft_engine::render::job::Phase; use solidcraft_engine::{CommandInfo, CommandSpec}; fn is_job_action(id: &str) -> bool { - matches!(id, "render.preflight" | "render.start" | "render.cancel" | "render.export" | "render.result.regrade" | "render.result.copy") + matches!( + id, + "render.preflight" | "render.start" | "render.batch" | "render.cancel" | "render.export" | "render.result.regrade" | "render.result.copy" + ) } fn handled(id: &str) -> bool { is_job_action(id) @@ -47,10 +50,15 @@ fn handled(id: &str) -> bool { | "render.backends" | "render.result.view" | "render.result.close" + | "render.compare" ) } pub(super) fn busy(app: &SolveApp) -> bool { + let queue = app.session.render_queue_state(); + if queue.running != 0 || queue.waiting != 0 { + return true; + } app.render_workspace .view .job @@ -66,6 +74,19 @@ pub(super) fn action_ready(app: &SolveApp, id: &str) -> Result<(), String> { return Err(app.tr("render.ribbon_finish_dialog").into()); } match id { + "render.batch" => { + if app.session.doc.render.setups.is_empty() { + return Err(app.tr("render.batch_empty").into()); + } + if app.session.doc.render.setups.len() > 32 { + return Err(app.tr("render.batch_limit").into()); + } + if busy(app) { + return Err(app.tr("render.ribbon_job_active").into()); + } + super::image_params(app).map(|_| ()) + } + "render.compare" if app.render_workspace.view.retained.is_empty() => Err(app.tr("render.ribbon_no_result").into()), "render.preflight" | "render.start" => { if id == "render.start" && busy(app) { return Err(app.tr("render.ribbon_job_active").into()); @@ -128,6 +149,10 @@ pub(super) fn command_info(app: &SolveApp, command: &CommandSpec) -> CommandInfo pub(super) fn perform_job(app: &mut SolveApp, id: &str) -> Result<(), String> { action_ready(app, id)?; match id { + "render.batch" => { + let request = super::image_params(app)?; + app.run(id, json!({"request":request}))?; + } "render.preflight" => { let request = super::image_params(app)?; let reply = match app.run(id, request.clone()) { @@ -161,7 +186,12 @@ pub(super) fn perform_job(app: &mut SolveApp, id: &str) -> Result<(), String> { app.render_workspace.view.job = Some(job); } "render.cancel" => { - let job = app.render_workspace.view.job.ok_or_else(|| app.tr("render.ribbon_no_active_job").to_string())?; + let job = app + .session + .render_queue_state() + .job + .or(app.render_workspace.view.job) + .ok_or_else(|| app.tr("render.ribbon_no_active_job").to_string())?; app.run(id, json!({"job":job}))?; } "render.export" => { @@ -238,6 +268,7 @@ fn navigate(app: &mut SolveApp, id: &str) -> Result<(), String> { focus(app, Page::Appearance, None); inspector::reveal(app, "render:appearance:advanced"); } + "render.compare" => super::compare::start_default(app)?, "render.result.close" => { app.run(id, json!({}))?; } diff --git a/crates/ui-egui/src/render_workspace_shots.rs b/crates/ui-egui/src/render_workspace_shots.rs index ef4879d8a..48fe8b1ce 100644 --- a/crates/ui-egui/src/render_workspace_shots.rs +++ b/crates/ui-egui/src/render_workspace_shots.rs @@ -45,6 +45,8 @@ pub(crate) fn contents(app: &mut SolveApp, ui: &mut egui::Ui) { ) }) .unwrap_or_else(|| app.tr("render.shots_no_result").to_string()); + let queue = app.session.render_queue_state(); + let queue_label = crate::i18n::format("render.batch_status", &[("running", &queue.running.to_string()), ("waiting", &queue.waiting.to_string())]); let (mut hide, mut start, mut save, mut chosen, mut size) = (false, false, false, None, None); let mut visible = Vec::new(); ui_kit::Panel::strip_contents( @@ -53,6 +55,8 @@ pub(crate) fn contents(app: &mut SolveApp, ui: &mut egui::Ui) { let response = ui_kit::strip_toggle(ui, true, crate::i18n::tr_label("Hide Shots strip")); crate::scenario::publish_target("render:shots:hide", response.rect); hide = response.clicked(); + let response = ui_kit::completion_text(ui, &queue_label, false); + crate::scenario::publish_rect("render:shots:queue", response.rect); let response = ui_kit::icon_label_action(ui, app.tr("cmd.render_start"), Some("play"), ready.is_ok(), true); let response = if let Err(reason) = &ready { response.on_disabled_hover_text(reason) } else { response }; crate::scenario::publish_target("render:shots:render", response.rect); diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index 09e63988c..ec6c0ee54 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -2353,6 +2353,7 @@ fn delayed_image_export_never_substitutes_a_newer_retained_image() { use crate::picker_test_support::{Slot, save}; let (mut h, job) = async_export_fixture(); let path = h.dir.join("old-image.png"); + let bytes = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap().png().to_vec(); let ctx = crate::fonts::test_context(); let slot: Slot = Default::default(); save(&mut h.app, &slot); @@ -2362,9 +2363,18 @@ fn delayed_image_export_never_substitutes_a_newer_retained_image() { h.app.render_workspace.view.completed = Some(newer); *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); crate::file_picker::tick(&mut h.app, &ctx); - assert!(!path.exists(), "the evicted requested image must fail instead of exporting the newer image"); - assert!(matches!(&h.app.status, Some((_, _, true)))); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "an older retained image remains the exact pending export source"); assert_eq!(h.app.render_workspace.view.completed, Some(newer)); + let evicted = h.dir.join("evicted.png"); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + for _ in 0..7 { + completed_preview(&mut h, [50, 60, 70]); + } + *slot.borrow_mut() = Some(Some(evicted.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!evicted.exists(), "an evicted requested image fails without substituting a newer image"); + assert!(matches!(&h.app.status, Some((_, _, true)))); let newer_path = h.dir.join("new-image.png"); h.app.run("render.export", json!({"job":newer,"path":newer_path})).unwrap(); assert!(newer_path.is_file()); @@ -5838,6 +5848,117 @@ fn output_viewer_r_starts_active_setup_and_escape_returns_to_model_without_cance assert_ne!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); } +#[test] +fn retained_results_picker_and_discard_dispatch_the_selected_index() { + let mut h = output_viewer_fixture(); + let first = completed_preview(&mut h, [20, 40, 60]); + let second = completed_preview(&mut h, [80, 100, 120]); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + h.app.run("render.result.select", json!({"index":1})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:results"}})).unwrap(); + h.frames(2); + h.step(&json!({"click":{"handle":"render:result:select:0"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.completed, Some(first)); + h.step(&json!({"click":{"handle":"render:result-discard"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + assert_eq!(h.app.render_workspace.view.retained.len(), 1); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); +} + +#[test] +fn retained_results_select_discard_copy_export_and_repaint_keep_exact_selected_pixels() { + let mut h = output_viewer_fixture(); + let ctx = crate::fonts::test_context(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let mut jobs = Vec::new(); + for shade in 0..10 { + let job = completed_preview(&mut h, [shade * 20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.job_shot = Some(format!("Shot {shade}")); + cache_render_images(&mut h.app, &ctx); + jobs.push(job); + } + assert_eq!(h.app.render_workspace.view.retained.len(), 8); + assert_eq!(h.app.render_workspace.view.retained.iter().map(|result| result.frame.job).collect::>(), jobs[2..]); + assert_eq!(h.app.render_workspace.view.retained[0].shot.as_deref(), Some("Shot 2")); + h.app.run("render.result.select", json!({"index":0})).unwrap(); + assert!(h.app.render_workspace.view.result); + for _ in 0..3 { + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(jobs[2])); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().job, jobs[2]); + } + h.app.run("render.result.copy", json!({})).unwrap(); + assert!(h.app.render_workspace.clipboard_image.as_ref().unwrap().pixels.iter().all(|pixel| *pixel == Color32::from_rgb(40, 40, 60))); + let frame = h.app.session.render_job_handle(jobs[2]).unwrap().frame().unwrap().unwrap(); + let path = h.dir.join("selected-result.png"); + h.app.run("render.export", json!({"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(jobs[9])); + assert!(h.app.session.render_job_handle(jobs[2]).is_err()); + assert!(h.app.run("render.result.select", json!({"index":7})).is_err()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn retained_results_and_selection_stay_with_the_document_tab_and_clear_on_reset() { + let mut h = output_viewer_fixture(); + let first = completed_preview(&mut h, [20, 40, 60]); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + cache_render_images(&mut h.app, &h.ctx); + h.app.run("render.result.select", json!({"index":0})).unwrap(); + h.app.run("solid.box", json!({"length":1,"width":1,"height":1})).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.retained.iter().all(|result| result.stale)); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(h.app.render_workspace.view.retained.is_empty()); + assert!(h.app.run("render.result.select", json!({"index":0})).is_err()); + crate::documents::switch(&mut h.app, 0); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(first)); + assert_eq!(h.app.render_workspace.view.retained.len(), 2); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(displayed_image(&h.app).is_none(), "polling the discarded active job cannot resurrect its image"); + reset_document(&mut h.app); + assert!(h.app.render_workspace.view.retained.is_empty()); +} + +#[test] +fn retained_results_capture_the_draft_shot_name_before_the_user_switches_shots() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.name = "Hero".into(); + let reply = h.app.run("render.start", json!({"settings":{"width":8,"height":8}})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..100 { + if !host.pump(16384).unwrap() { + break; + } + } + let duration = h.app.session.render_job_handle(job).unwrap().completed_duration().unwrap().unwrap().as_secs_f64(); + h.app.render_workspace.view.name = "Front".into(); + h.app.run("render.start", json!({"settings":{"width":8,"height":8}})).unwrap(); + sync_results(&mut h.app); + assert_eq!(h.app.render_workspace.view.retained[0].shot.as_deref(), Some("Hero")); + assert_eq!(h.app.render_workspace.view.retained[0].seconds, duration); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + assert!(h.app.dialog.is_none()); +} + /// Actual app controls and retained pixels, rasterized from egui without a window. #[test] fn output_viewer_evidence() { @@ -5938,8 +6059,9 @@ fn output_viewer_evidence() { } #[test] -fn output_viewer_radial_defaults_enable_lights_and_keep_planned_compare_disabled() { - let h = output_viewer_fixture(); +fn output_viewer_radial_defaults_enable_lights_and_compare_requires_a_result() { + let mut h = render_lights_fixture(); + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); let expected = [ "render.start", "appearance.assign", @@ -5951,8 +6073,12 @@ fn output_viewer_radial_defaults_enable_lights_and_keep_planned_compare_disabled "undo", ]; assert_eq!(crate::mouse_gesture::Studio::Render.defaults(), expected); + assert!(solidcraft_engine::find_command("render.lights.add").unwrap().planned.is_none()); assert!(crate::mouse_gesture::item(&h.app, "render.lights.add").unwrap().enabled); assert!(!crate::mouse_gesture::item(&h.app, "render.compare").unwrap().enabled); + completed_preview(&mut h, [20, 40, 60]); + assert!(crate::mouse_gesture::item(&h.app, "render.compare").unwrap().enabled); + assert!(crate::mouse_gesture::item(&h.app, "render.lights.add").unwrap().enabled); } #[test] @@ -5980,7 +6106,7 @@ fn output_viewer_presets_are_commands_with_limits_and_custom_keeps_the_size() { } #[test] -fn output_viewer_has_sections_without_pages_or_footer_and_selected_row_routes_to_output() { +fn output_viewer_has_sections_and_shared_footer_without_pages_and_selected_row_routes_to_output() { for dark in [false, true] { let mut h = output_viewer_fixture(); h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); @@ -5991,6 +6117,10 @@ fn output_viewer_has_sections_without_pages_or_footer_and_selected_row_routes_to assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).is_some(), "{key}"); } assert!(crate::scenario::rect_of("render:job-footer").is_none()); + let footer = crate::scenario::rect_of("render:output-footer").unwrap(); + for target in ["render:output:render", "render:output:all-shots"] { + assert!(footer.contains_rect(crate::scenario::rect_of(target).unwrap())); + } for page in ["output", "effects", "all"] { assert!(crate::scenario::rect_of(&format!("render:page:{page}")).is_none()); } @@ -6464,6 +6594,145 @@ fn render_lights_each_kind_contains_design_sections_and_real_parameter_fields_in } } +fn render_results_compare_fixture() -> (Harness, solidcraft_engine::render::job::JobId, solidcraft_engine::render::job::JobId) { + let mut h = output_viewer_fixture(); + h.call("ui.resize", json!({"width":1440,"height":900})); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(first); + h.app.render_workspace.view.job_shot = Some("Front".into()); + cache_render_images(&mut h.app, &h.ctx); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + h.app.render_workspace.view.job_shot = Some("Hero".into()); + cache_render_images(&mut h.app, &h.ctx); + (h, first, second) +} + +#[test] +fn render_results_compare_live_two_renders_swap_labels_and_common_framing_use_the_shared_controls() { + let (mut h, first, second) = render_results_compare_fixture(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + h.app.run("render.compare", json!({"left":"live","right":1})).unwrap(); + h.frames(3); + let view = h.app.render_workspace.view.compare.as_ref().unwrap(); + assert_eq!((view.left, view.right, view.reference), (None, Some(second), second)); + let image = crate::scenario::rect_of("render:compare:image").unwrap(); + let canvas = crate::scenario::rect_of("render:compare:canvas").unwrap(); + for target in ["render:compare:left-label", "render:compare:right-label", "render:compare:divider"] { + assert!(canvas.contains_rect(crate::scenario::rect_of(target).unwrap()), "{target}"); + } + assert!( + h.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == h.app.tr("render.compare_live_preview"))) + ); + h.step(&json!({"click":{"handle":"render:compare:swap"}})).unwrap(); + h.frames(2); + let view = h.app.render_workspace.view.compare.as_ref().unwrap(); + assert_eq!((view.left, view.right, view.reference), (Some(second), None, second)); + assert_eq!(crate::scenario::rect_of("render:compare:image"), Some(image)); + h.app.run("render.compare", json!({"left":0,"right":1})).unwrap(); + h.frames(2); + let first_texture = h.app.render_workspace.comparison_images.iter().find(|(job, _)| *job == first).unwrap().1.as_ref().unwrap().id(); + let second_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let vertices = |texture| { + h.shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id == texture => Some(mesh.vertices.iter().map(|vertex| vertex.pos).collect::>()), + _ => None, + }) + .unwrap() + }; + assert_eq!(vertices(first_texture), vertices(second_texture), "both rendered sources use the same image framing"); + h.step(&json!({"click":{"handle":"render:compare:swap"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), first_texture); + assert!(h.app.render_workspace.comparison_images.iter().any(|(job, image)| *job == second && image.as_ref().unwrap().id() == second_texture)); + assert!(h.app.render_workspace.comparison_images.len() <= 2); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); + h.app.run("render.compare", json!({"off":true})).unwrap(); + assert!(h.app.render_workspace.view.compare.is_none()); + assert!(h.app.render_workspace.comparison_images.is_empty()); +} + +#[test] +fn render_results_compare_divider_drag_clamps_and_blocks_all_camera_input() { + use egui::{Event, Modifiers, MouseWheelUnit, PointerButton, vec2}; + let (mut h, _, _) = render_results_compare_fixture(); + h.app.run("render.compare", json!({"left":0,"right":1})).unwrap(); + let pending = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap()["job"].clone(); + assert!(!h.app.render_workspace.view.follow_job, "new job previews must not replace comparison framing"); + h.frames(3); + h.app.preferences.nav = "maya".into(); + h.app.render_workspace.view.result_scale = ResultScale::Free; + let product = h.app.cam; + let result = h.app.render_workspace.view.result_camera; + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let canvas = crate::scenario::rect_of("render:compare:canvas").unwrap(); + let start = crate::scenario::rect_of("render:compare:handle").unwrap().center(); + h.frame_with(vec![ + Event::ModifiersChanged(Modifiers::ALT), + Event::PointerMoved(start), + Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }, + ]); + let end = egui::pos2(canvas.right() + 100.0, start.y); + h.frame_with(vec![ + Event::PointerMoved(end), + Event::MouseWheel { unit: MouseWheelUnit::Point, delta: vec2(0.0, -300.0), modifiers: Modifiers::ALT, phase: egui::TouchPhase::Move }, + ]); + assert!( + (h.app.render_workspace.view.compare.as_ref().unwrap().position - 0.95).abs() < 1e-6, + "divider position {:?}, canvas {canvas:?}, press {start:?}, pointer {end:?}, captured {:?}", + h.app.render_workspace.view.compare.as_ref().unwrap().position, + h.ctx.dragged_id() + ); + assert_eq!(h.app.render_workspace.view.result_camera, result); + assert_eq!(h.app.cam, product); + let end = egui::pos2(canvas.left() - 100.0, start.y); + h.frame_with(vec![Event::PointerMoved(end)]); + assert!((h.app.render_workspace.view.compare.as_ref().unwrap().position - 0.05).abs() < 1e-6); + assert_eq!(h.app.render_workspace.view.result_camera, result); + assert_eq!(h.app.cam, product); + h.frame_with(vec![ + Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }, + Event::ModifiersChanged(Modifiers::NONE), + ]); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); + h.app.run("render.cancel", json!({"job":pending})).unwrap(); +} + +#[test] +fn render_results_compare_live_projection_matches_image_fit_zoom_and_pan_without_an_oversized_gpu_viewport() { + use solidcraft_engine::geom::Vec3; + let canvas = egui::Rect::from_min_size(egui::pos2(100.0, 200.0), egui::vec2(800.0, 600.0)); + for fov in [0.0, 0.6] { + let camera = Camera { fov, roll: 0.25, ..Default::default() }; + for image in [ + egui::Rect::from_center_size(canvas.center(), egui::vec2(400.0, 400.0)), + egui::Rect::from_center_size(canvas.center(), egui::vec2(1600.0, 1200.0)), + egui::Rect::from_min_size(egui::pos2(-200.0, 350.0), egui::vec2(1200.0, 900.0)), + ] { + let projection = product_projection(camera, 100.0, canvas, Some(image)); + for point in [camera.target, camera.target + Vec3::X * 5.0, camera.target + Vec3::Z * 10.0] { + let (x, y, _) = camera.to_screen(point, f64::from(image.width()), f64::from(image.height()), 100.0).unwrap(); + let expected = egui::pos2(image.left() + x as f32, image.top() + y as f32); + let clip = projection.apply(point); + let actual = egui::pos2( + canvas.left() + ((clip[0] / clip[3] + 1.0) * 0.5) as f32 * canvas.width(), + canvas.top() + ((1.0 - clip[1] / clip[3]) * 0.5) as f32 * canvas.height(), + ); + assert!(actual.distance(expected) < 0.001, "{actual:?} != {expected:?}"); + } + } + assert_eq!(product_projection(camera, 100.0, canvas, None), camera.view_proj(f64::from(canvas.width() / canvas.height()), 100.0)); + } +} + #[test] fn render_lighting_preset_materialises_values_and_replacement_requires_review_consent() { let mut h = render_lights_fixture(); @@ -6713,3 +6982,106 @@ fn entering_render_fits_a_saved_portrait_setup_inside_its_final_frame() { assert_eq!((h.app.cam, h.app.ui.perspective), design, "fov {fov}: leaving Render restores the Design camera"); } } + +#[test] +fn render_results_compare_segments_work_from_live_and_close_safely_when_a_source_is_discarded() { + let (mut h, first, second) = render_results_compare_fixture(); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:compare:result:0"}})).unwrap(); + h.frames(2); + let view = h.app.render_workspace.view.compare.as_ref().unwrap(); + assert_eq!((view.left, view.right), (None, Some(first))); + h.step(&json!({"click":{"handle":"render:compare:result:1"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.compare.as_ref().unwrap().right, Some(second)); + h.step(&json!({"click":{"handle":"render:compare:live"}})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.compare.is_none()); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + h.app.run("render.compare", json!({"left":0,"right":1})).unwrap(); + h.frames(2); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.compare.is_none()); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + let third = completed_preview(&mut h, [100, 120, 140]); + let fourth = completed_preview(&mut h, [140, 160, 180]); + h.app.run("render.compare", json!({"left":1,"right":2})).unwrap(); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + h.frames(2); + let view = h.app.render_workspace.view.compare.as_ref().unwrap(); + assert_eq!((view.left, view.right), (Some(third), Some(fourth)), "discarding an unrelated earlier row must not retarget comparison"); + assert_eq!(h.app.session.render_comparison(), Some([Some(third), Some(fourth)])); + assert!(h.app.run("render.compare", json!({"left":"live","right":99})).is_err()); +} + +fn render_results_batch_fixture() -> Harness { + let mut h = output_viewer_fixture(); + h.call("ui.resize", json!({"width":1440,"height":900})); + for (index, name) in ["Front", "Hero", "Top"].iter().enumerate() { + let camera = Camera { yaw: index as f64 * 0.3, ..Default::default() }; + h.app.run("render.settings.set", json!({"name":name,"set":{"camera":camera,"width":8,"height":8}})).unwrap(); + } + h.frames(3); + h +} + +#[test] +fn render_results_batch_output_footer_only_starts_on_click_and_cancel_drops_waiting_shots() { + let mut h = render_results_batch_fixture(); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + h.app.render_workspace.view.draft.width = 128; + h.app.render_workspace.view.draft.height = 128; + h.app.render_workspace.view.dirty = true; + h.frames(2); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + h.step(&json!({"click":{"handle":"render:output:all-shots"}})).unwrap(); + h.frames(1); + let queue = h.app.session.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 2)); + assert_eq!(h.app.render_workspace.view.job, queue.job); + let status = crate::i18n::format("render.batch_status", &[("running", "1"), ("waiting", "2")]); + assert!(h.shapes.iter().any(|shape| matches!(&shape.shape,egui::Shape::Text(text) if text.galley.text()==status))); + assert!(crate::scenario::rect_of("render:shots:queue").is_some()); + h.step(&json!({"click":{"handle":"render:stage:render.cancel"}})).unwrap(); + h.frames(3); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); +} + +#[test] +fn render_results_batch_continues_in_background_tabs_and_keeps_each_shot_result_with_its_document() { + let mut h = render_results_batch_fixture(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len()); + let captured_revision = h.app.session.revision; + let host = h.app.session.render_job_host().unwrap().clone(); + h.app.run("render.batch", json!({"request":{"settings":{"width":8,"height":8}}})).unwrap(); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + let other = h.app.session.doc.clone(); + for _ in 0..3 { + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + h.frames(1); + } + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + crate::documents::switch(&mut h.app, 0); + h.frames(2); + let results = h.app.session.render_retained_results().unwrap(); + assert_eq!(results.iter().map(|result| result.shot.as_deref().unwrap()).collect::>(), ["Front", "Hero", "Top"]); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len())); + assert!(results.iter().all(|result| result.frame.scene_generation == captured_revision)); +} diff --git a/crates/ui-egui/src/revolve_manipulator_tests.rs b/crates/ui-egui/src/revolve_manipulator_tests.rs index a9b8334a9..65e299e10 100644 --- a/crates/ui-egui/src/revolve_manipulator_tests.rs +++ b/crates/ui-egui/src/revolve_manipulator_tests.rs @@ -225,6 +225,44 @@ fn free_drag_and_invalid_expression_stay_editable_before_commit() { assert!((volume(&h) - expected_volume(60.0)).abs() < 0.03); } +/// Typing 0° builds no solid, and the dialog keeps the range error. The grab point stays on +/// the profile, and dragging it brings the angle back. +#[test] +fn zero_angle_keeps_the_grab_point_and_a_drag_brings_the_angle_back() { + for (params, handle, drag_to, entered_angle, committed) in + [(json!({}), "revolve", 45.0, "45 deg", 45.0), (json!({"direction": "symmetric"}), "revolve2", -45.0, "90 deg", 90.0)] + { + let mut h = fixture(Harness::new(), params.clone()); + open(&mut h); + h.step(&json!({"click":{"handle":"dialog:Angle"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"0 deg"})).unwrap(); + h.frames(4); + handle_at(&mut h, "revolve", at_angle(0.0)); + // A preview refusal stays on the preview while the angle field is still being typed in. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while h.app.preview.busy { + assert!(std::time::Instant::now() < deadline, "the preview did not finish"); + h.frames(1); + } + let error = h.app.dialog.as_ref().and_then(|dialog| dialog.error.clone()).or_else(|| h.app.preview.error.clone()).unwrap_or_default(); + assert!(error.contains("more than 0"), "{error}"); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_some(), "a zero angle still builds no solid"); + h.step(&json!({"drag":[{"handle":handle},{"world":at_angle(drag_to)}]})).unwrap(); + let crate::dialogs::Kind::Revolve { angle: entered, .. } = &h.app.dialog.as_ref().unwrap().kind else { panic!("revolve") }; + assert_eq!(entered, entered_angle); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|dialog| &dialog.error)); + assert_eq!(angle(&h), entered_angle); + let got = volume(&h); + let want = expected_volume(committed); + // A symmetric drag that starts with both handles stacked at 0° lands within a tenth of a + // cubic millimetre of the analytic quarter turn. + assert!((got - want).abs() < 0.1, "params={params} got={got} want={want}"); + } +} + #[test] fn second_side_can_be_dragged_to_zero_without_becoming_full_turn() { let mut h = fixture(Harness::new(), json!({"angle":"60 deg","angle2":"30 deg"})); diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index 757141daf..e8c9c333a 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -897,14 +897,16 @@ pub fn check(h: &mut Harness, e: &Value) -> Result<(), String> { } } "dialog" => { - let d = &ui["dialog"]; + // A word of the dialog's state as the code holds it: scenarios check fields that + // `ui.inspect` reports only as the command OK runs. + let d = h.app.dialog.as_ref().map(|d| format!("{d:?}")); let ok = match v { - Value::Null => d.is_null(), - Value::String(w) => d.as_str().is_some_and(|d| d.contains(w.as_str())), + Value::Null => d.is_none() && ui["dialog"].is_null(), + Value::String(w) => d.as_deref().is_some_and(|d| d.contains(w.as_str())), _ => false, }; if !ok { - return Err(format!("dialog: got {d}, want {v}")); + return Err(format!("dialog: got {d:?}, want {v}")); } } "tool" => { diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs index 91afb68c5..d2276f014 100644 --- a/crates/ui-egui/src/shortcut_box.rs +++ b/crates/ui-egui/src/shortcut_box.rs @@ -173,6 +173,10 @@ fn keywords(id: &str) -> &'static str { match id { "file.save_mesh" => "export stl 3mf mesh 3d print printing slicer", "file.export" => "export stl 3mf obj step urdf mesh 3d print", + "file.export_step" => "stp cad", + "file.export_stl" | "file.export_3mf" => "mesh 3d print printing", + "file.export_obj" => "mesh", + "file.export_urdf" => "robot ros simulation", _ => "", } } diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index b7b5f4577..7d54ff4aa 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -545,6 +545,27 @@ fn escape_leaves_the_sketch_and_the_history_untouched() { assert_eq!((h.app.session.doc.to_json(), h.app.session.undo.len()), before); } +/// #9316: the refusal of a size being typed (`4 m` on the way to `4 mm`) goes once the size fits. +#[test] +fn a_refused_size_gives_way_to_one_that_fits() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[20,30]})).unwrap(); + h.frames(2); + h.step(&json!({"start":"sketch.fillet"})).unwrap(); + h.frames(2); + h.step(&json!({"click":{"world":[0,0,0]}})).unwrap(); + h.frames(2); + let shown = |h: &mut crate::scenario::Harness, size: &str| { + set_size(&mut h.app, size); + h.settle(); + h.frames(2); + h.app.dialog.as_ref().and_then(|d| d.error.clone()).or_else(|| h.app.preview.error.clone()) + }; + assert!(shown(&mut h, "4 m").is_some_and(|e| e.contains("too large"))); + assert_eq!(shown(&mut h, "4 mm"), None); +} + /// A size the corner cannot take is refused with a reason, and the window stays open on it. #[test] fn an_impossible_size_keeps_the_window_open_with_its_reason() { @@ -958,3 +979,41 @@ fn corner_candidates_agree_with_engine_spatial_curve_filter() { h.app.dialog = None; } } + +#[test] +fn line_arc_fillet_preview_and_apply_work_in_both_pick_orders() { + for reverse in [false, true] { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,0],[40,0]],"ids":["l1"]})).unwrap(); + h.app.run("sketch.arc.center_point", json!({"center":[50,0],"start":[60,0],"end":[40,0],"id":"a1"})).unwrap(); + h.app.run("sketch.constraint.fix", json!({"entity":"l1.end"})).unwrap(); + h.app.run("view.fit", json!({})).unwrap(); + h.settle(); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.fillet"})).unwrap(); + h.frames(2); + let mut picks = [[32, 0, 0], [50, 10, 0]]; + if reverse { + picks.reverse(); + } + for point in picks { + h.step(&json!({"click":{"world":point}})).unwrap(); + h.frames(2); + } + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items.len(), 2); + set_size(&mut h.app, "3 mm"); + h.step(&json!({"until":{"count":{"name":"sketch_preview_curves","value":3}}})).unwrap(); + apply(&mut h); + assert!(h.app.dialog.is_none(), "reverse {reverse}: {:?}", h.app.status); + assert_eq!(h.app.session.undo.len(), undo + 1); + let st = h.app.session.world_state().unwrap(); + let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + assert!(ss.report.ok()); + assert_eq!(ss.sketch.curves.len(), 3); + let want = Vec2::new(50.0 - 160f64.sqrt(), 3.0); + assert!(ss.sketch.curves.iter().enumerate().any(|(i, _)| { + ss.sketch.radius(i).is_some_and(|r| (r - 3.0).abs() < 1e-7) && ss.sketch.center(i).is_some_and(|c| c.dist(want) < 1e-6) + })); + } +} diff --git a/crates/ui-egui/src/sketch_drag_ui_tests.rs b/crates/ui-egui/src/sketch_drag_ui_tests.rs index 83f9be4a1..6e3578c56 100644 --- a/crates/ui-egui/src/sketch_drag_ui_tests.rs +++ b/crates/ui-egui/src/sketch_drag_ui_tests.rs @@ -461,3 +461,34 @@ fn a_freed_circle_centre_on_the_origin_drags_instead_of_the_origin() { assert!(point(&h, "c1.center").dist(Vec2::new(15.0, 10.0)) < 0.05, "{:?}", point(&h, "c1.center")); assert!(point(&h, "origin").dist(Vec2::new(0.0, 0.0)) < 1e-9); } + +/// A centre rectangle's centre held on the origin stays there when dragged, and the rectangle +/// keeps its size. The press lands on the middle of the rectangle's diagonal as well as on the +/// centre; the drag took the diagonal by its middle and turned and stretched it about the held +/// centre, resizing the rectangle (#10510). +#[test] +fn a_centre_rectangles_centre_held_on_the_origin_keeps_the_rectangle_when_dragged() { + let mut h = Harness::new(); + run(&mut h, "sketch.create", json!({"plane": "XY"})); + run(&mut h, "sketch.rectangle.center", json!({"center": [3, 2], "corner": [13, 9]})); + run(&mut h, "sketch.constraint.coincident", json!({"a": "p5", "b": "origin"})); + run(&mut h, "sketch.options", json!({"snap": false, "show_dimensions": false, "show_constraints": false})); + h.call("ui.view", json!({"view": "top"})); + h.app.cam.distance = 150.0; + h.frames(3); + let corners = ["p1", "p2", "p3", "p4"].map(|p| point(&h, p)); + assert!(point(&h, "p5").len() < 1e-9, "{:?}", point(&h, "p5")); + // A press a little off the centre, as a hand presses. + let a = screen(&mut h, 0.3, 0.2); + let b = screen(&mut h, 12.0, 8.0); + let mut path = vec![a]; + path.extend(steps(a, b, 6)); + press_and_move(&mut h, &path); + assert_eq!(h.app.viewport.point_drag.as_ref().map(|(id, _, _)| id.as_str()), Some("p5"), "grabbed the centre, not the diagonal"); + h.frames(4); + release(&mut h, b); + assert!(point(&h, "p5").len() < 1e-6, "the centre left the origin: {:?}", point(&h, "p5")); + for (p, was) in ["p1", "p2", "p3", "p4"].into_iter().zip(corners) { + assert!(point(&h, p).dist(was) < 1e-6, "{p} moved from {was:?} to {:?}", point(&h, p)); + } +} diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs index 0a63a115e..d3a13a981 100644 --- a/crates/ui-egui/src/sketch_modify_ui.rs +++ b/crates/ui-egui/src/sketch_modify_ui.rs @@ -72,6 +72,9 @@ const CHAMFER_TYPE_ICONS: [&str; 3] = ["sketch_chamfer_equal", "sketch_chamfer_t /// The engine's own cap on the copies one sketch pattern may make. const MAX_COPIES: f64 = 500.0; +/// The engine's own cap on the offsets `sketch.offset` stacks one behind the other. +const MAX_OFFSET_INSTANCES: i64 = 100; + /// The offset directions, in the words and the order `solid.extrude` already uses for them. /// One Side offsets the way the distance points. Two Sides adds an independent distance the /// other way. Symmetric applies the one distance each way. @@ -102,8 +105,10 @@ pub enum Mod { /// `sketch.offset`: the curves to offset, the distance typed and whether the connected /// chain follows. A positive distance is left of the chain, as the command defines it; /// `flip` reverses whatever sign the field holds. `mode` indexes [`OFFSET_MODES`], and - /// `distance2` is the other side's distance that Two Sides asks for. - Offset { distance: String, distance2: String, mode: usize, chain: bool, flip: bool }, + /// `distance2` is the other side's distance that Two Sides asks for. `instances` is how many + /// offsets stand one behind the other, each the same distance again from the one before it: + /// one, the offset by itself, by default. + Offset { distance: String, distance2: String, instances: String, mode: usize, chain: bool, flip: bool }, /// `sketch.mirror`: the entities and the line they reflect in. The command has no number of /// its own, so the window's whole job is to show what is picked and let a pick be changed /// before anything is committed. @@ -227,6 +232,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "sketch.offset" => Mod::Offset { distance: crate::dialogs::length_default(&app.session, "2"), distance2: crate::dialogs::length_default(&app.session, "2"), + instances: "1".into(), mode: 0, chain: true, flip: false, @@ -524,12 +530,15 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Mod, doc: &Document) -> bool { let mut enter = false; match k { Mod::Scale { factor } => enter |= number(ui, "Factor", factor), - Mod::Offset { distance, distance2, mode, chain, flip } => { + Mod::Offset { distance, distance2, instances, mode, chain, flip } => { icons(ui, "Direction", &OFFSET_MODES, &OFFSET_MODE_ICONS, mode); enter |= number(ui, "Distance", distance); if *mode == TWO_SIDES { enter |= number(ui, "Distance 2", distance2); } + // Every instance after the first offsets the one before it by Distance again, so the + // arrows walk the offset outwards one ring at a time. + enter |= quantity(ui, doc, "Instances", instances, 1, MAX_OFFSET_INSTANCES); ui_kit::section(ui, "offset_options", "Options", true, |ui| { if *mode != SYMMETRIC { ui_kit::checkbox_grid(ui, &mut [("Flip", flip), ("Chain", chain)], 2); @@ -796,6 +805,15 @@ fn whole(app: &SolveApp, label: &str, text: &str) -> Result { Ok(v.round() as u64) } +/// Validate a typed offset instance count before sending it to the command. +fn offset_instances(app: &SolveApp, text: &str) -> Result { + let v = app.session.doc.eval(text.trim(), ValueKind::Unitless).map_err(|e| format!("Instances: {e}"))?; + if !v.is_finite() || !(1.0..=MAX_OFFSET_INSTANCES as f64).contains(&v) || (v - v.round()).abs() > 1e-9 { + return Err(format!("Instances must be a whole number from 1 to {MAX_OFFSET_INSTANCES}")); + } + Ok(v.round() as u64) +} + /// A typed length as the command wants it, in millimetres. A bare number means the design's /// units, as a typed sketch value does everywhere else. `value` above reads an empty row as /// zero, which a Move window wants and a pattern spacing does not. @@ -903,14 +921,18 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map { + Mod::Offset { distance, distance2, instances, mode, chain, flip } => { let curves = curve_ids(inputs, 0); if curves.is_empty() { return Err("Select the curves to offset first".into()); } // Symmetric hides Flip, so a flip left over from another mode does not travel with it. signed_length(app, "Distance", distance, *flip && *mode != SYMMETRIC)?; - let mut params = json!({"curves": curves, "distance": distance.trim(), "flip": *flip && *mode != SYMMETRIC, "chain": chain}); + // The count is not kept in the design, so the command gets the number it evaluates to + // rather than the text, the way Scale and the pattern spacings send theirs. + let count = offset_instances(app, instances)?; + let mut params = + json!({"curves": curves, "distance": distance.trim(), "flip": *flip && *mode != SYMMETRIC, "chain": chain, "instances": count}); if let Value::Object(m) = &mut params { if *mode == SYMMETRIC { m.insert("symmetric".into(), json!(true)); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e7b511092..dae836541 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -1190,6 +1190,50 @@ pub struct Tokens { pub dialog_label: Color32, pub selected_ink: Color32, pub selected_bg: Color32, + /// Ground under every Preferences figure. + pub figure_ground: Color32, + /// Outlines and reference lines of Preferences figures. + pub figure_line: Color32, + /// Top face of the Preferences figure cube. + pub figure_face_top: Color32, + /// Left face of the Preferences figure cube. + pub figure_face_left: Color32, + /// Right face of the Preferences figure cube. + pub figure_face_right: Color32, + /// Paper, panels and pads drawn inside Preferences figures. + pub figure_card: Color32, + /// Fixed white label and highlight ink inside Preferences illustrations. + pub figure_white: Color32, + /// Fixed black hatch and shadow ink inside Preferences illustrations. + pub figure_black: Color32, + /// What a Preferences figure or selected card acts on. + pub figure_accent: Color32, + /// Reference point in a Preferences figure: pivot, origin, pointer. + pub figure_reference: Color32, + /// X axis in a Preferences figure. + pub figure_axis_x: Color32, + /// Y axis in a Preferences figure. + pub figure_axis_y: Color32, + /// Z axis in a Preferences figure. + pub figure_axis_z: Color32, + /// Done or fully constrained mark in a Preferences figure. + pub figure_ok: Color32, + /// Warning mark in a Preferences figure. + pub figure_warn: Color32, + /// Segmented control well and tint behind figures in Preferences. + pub pref_well: Color32, + /// Warning badge text and stroke in Preferences. + pub pref_note: Color32, + /// Warning badge fill in Preferences. + pub pref_note_fill: Color32, + /// Ink on a Preferences accent fill. + pub pref_on_accent: Color32, + /// Success badge text in Preferences. + pub pref_ok: Color32, + /// Success badge fill in Preferences. + pub pref_ok_fill: Color32, + /// Ink of a dimmed Preferences control. + pub pref_disabled: Color32, /// Timeline items: normal and failed. pub timeline_item: Color32, pub timeline_item_error: Color32, diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs index 5c7a06f4b..efdefd004 100644 --- a/crates/ui-egui/src/theme_files.rs +++ b/crates/ui-egui/src/theme_files.rs @@ -470,6 +470,7 @@ macro_rules! theme_keys { form_card_width: _, form_icon_size: _, form_close_size: _, form_inset: _, form_icon_inset: _, form_section_icon_size: _, form_checkbox_height: _, form_button_height: _, sketch_palette_width: _, sketch_mode_size: _, sketch_mode_radius: _, sketch_mode_border: _, sketch_palette_alpha: _, sketch_mode_tint: _, sketch_footer_icon_size: _, font_section_tracking: _, + figure_ground: _, figure_line: _, figure_face_top: _, figure_face_left: _, figure_face_right: _, figure_card: _, figure_white: _, figure_black: _, figure_accent: _, figure_reference: _, figure_axis_x: _, figure_axis_y: _, figure_axis_z: _, figure_ok: _, figure_warn: _, pref_well: _, pref_note: _, pref_note_fill: _, pref_on_accent: _, pref_ok: _, pref_ok_fill: _, pref_disabled: _, } = t; let IconColors { $($ione: _,)* } = &t.icons; } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index e512e9a8e..8223f4b25 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -829,32 +829,36 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { close = true; } ui.separator(); - if item_if(ui, "Export STL…", "", "mesh_export", shown) { - FileAction::ExportMesh("stl").run(app); + // Each format's item runs its own command, so it shows that command's key. + let key = |id: &str| crate::keymap::effective(app, id).unwrap_or_default(); + let (stl_key, mf_key, step_key, obj_key, urdf_key) = + (key("file.export_stl"), key("file.export_3mf"), key("file.export_step"), key("file.export_obj"), key("file.export_urdf")); + if item_if(ui, "Export STL…", &stl_key, "mesh_export", shown) { + FileAction::Command("file.export_stl").run(app); close = true; } - if item_if(ui, "Export 3MF…", "", "mesh_export", shown) { - FileAction::ExportMesh("3mf").run(app); + if item_if(ui, "Export 3MF…", &mf_key, "mesh_export", shown) { + FileAction::Command("file.export_3mf").run(app); close = true; } if item_if(ui, "Send to Slicer", "", "mesh_export", shown && crate::dialogs_save_mesh::available(app)) { app.start("file.send_to_slicer"); close = true; } - if item_if(ui, "Export STEP…", "", "export", shown) { - FileAction::Export("step").run(app); + if item_if(ui, "Export STEP…", &step_key, "export", shown) { + FileAction::Command("file.export_step").run(app); close = true; } if item_if(ui, app.tr_label("Export Current View as DXF…"), "", "export", shown) { FileAction::Command("file.export_view_dxf").run(app); close = true; } - if item_if(ui, "Export OBJ…", "", "export", shown) { - FileAction::Export("obj").run(app); + if item_if(ui, "Export OBJ…", &obj_key, "export", shown) { + FileAction::Command("file.export_obj").run(app); close = true; } - if item_if(ui, "Export URDF…", "", "export", shown) { - FileAction::Export("urdf").run(app); + if item_if(ui, "Export URDF…", &urdf_key, "export", shown) { + FileAction::Command("file.export_urdf").run(app); close = true; } if item(ui, "Export Design as JSON…", "", "export") { @@ -964,6 +968,30 @@ pub(crate) fn export(app: &mut SolveApp, ext: &str) { export_as(app, ext, None); } +/// Each format's own export command, started from its key, command search or the File menu, +/// does what that File › Export item does: STEP, OBJ and URDF ask where to save, STL and 3MF +/// open the mesh dialog with the format chosen. `false`: `id` is no such command. +pub(crate) fn start_export(app: &mut SolveApp, id: &str) -> bool { + let (extension, mesh) = match id { + "file.export_step" => ("step", false), + "file.export_obj" => ("obj", false), + "file.export_urdf" => ("urdf", false), + "file.export_stl" => ("stl", true), + "file.export_3mf" => ("3mf", true), + _ => return false, + }; + // As the File menu's items: not while a file is being picked or loaded, or behind a bug report. + if !FileAction::Export(extension).enabled(app) { + return true; + } + if mesh { + crate::dialogs_save_mesh::start_with_format(app, extension); + } else { + export(app, extension); + } + true +} + /// Export to a file with extension `ext`, in `format` when the extension alone doesn't name it. fn export_as(app: &mut SolveApp, ext: &str, format: Option<&str>) { let name = format!("{}.{ext}", app.session.doc.name); @@ -2246,7 +2274,7 @@ fn assistant_button(app: &mut SolveApp, ui: &mut egui::Ui, at: Rect) { let resp = ui.interact(at, ui.id().with("assistant_button"), Sense::click()); crate::scenario::publish_target("titlebar:assistant", at); let mark = crate::agent_chat::assistant_mark(app); - let tip = crate::agent_chat::assistant_tip(mark); + let tip = crate::agent_chat::assistant_tip(app, mark); resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &tip)); let state = match mark { AssistantMark::Quiet => crate::ui_kit::AssistantEntryState::Quiet, @@ -3313,13 +3341,15 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { } return; } - let (keys, mods) = ctx.input(|i| { - let keys: Vec<(egui::Key, bool)> = i - .events + // A quick chord can press and release all modifiers in one frame. Dispatch each key + // with its own modifiers, not the final frame state (an unbound Ctrl+Shift+A is not A). + let keys: Vec<_> = ctx.input(|i| { + i.events .iter() - .filter_map(|e| if let egui::Event::Key { key, pressed: true, repeat, .. } = e { Some((*key, *repeat)) } else { None }) - .collect(); - (keys, i.modifiers) + .filter_map( + |e| if let egui::Event::Key { key, pressed: true, repeat, modifiers, .. } = e { Some((*key, *repeat, *modifiers)) } else { None }, + ) + .collect() }); // A theme pasted on the Interface page is a theme, not copied components (#8226). crate::prefs::take_theme_paste(app, ctx); @@ -3330,7 +3360,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { } else { crate::edit_clipboard::flush(app, ctx); } - for (k, repeat) in keys { + for (k, repeat, mods) in keys { use egui::Key; // Only Esc pressed twice in a row finishes a sketch: any other key in between resets it. if k != Key::Escape { @@ -3592,6 +3622,36 @@ mod header_report_tests { assert!(FileAction::Export("step").enabled(&h.app)); } + /// File › Export STEP…, STL…, 3MF…, OBJ… and URDF… each run a command of their own, so each + /// can be given a key in Keyboard Shortcuts: the key asks where to save the file as the menu + /// item does (STL and 3MF open Save As Mesh). + #[test] + fn each_export_format_has_a_key_that_starts_it() { + let mut h = crate::scenario::Harness::new(); + let offered = std::rc::Rc::new(std::cell::RefCell::new(Vec::<(String, Vec)>::new())); + let (seen, dir) = (offered.clone(), h.dir.clone()); + h.app.services.pick_save = Some(Box::new(move |name, extensions| { + seen.borrow_mut().push((name.to_string(), extensions.iter().map(|e| e.to_string()).collect())); + Box::pin(std::future::ready(Some(dir.join(name).to_string_lossy().into_owned()))) + })); + h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap(); + h.app.session.doc_mut().name = "Bracket".into(); + for (id, key) in [("file.export_step", "Alt+Shift+F7"), ("file.export_stl", "Alt+Shift+F8")] { + crate::keymap::bind(&mut h.app, id, key, false).unwrap(); + assert_eq!(crate::keymap::effective(&h.app, id).as_deref(), Some(key), "the File menu shows it"); + } + crate::keymap::press(&mut h.app, "Alt+Shift+F7", false); + h.frames(3); + h.settle(); + assert_eq!(offered.borrow().last().cloned(), Some(("Bracket.step".to_string(), vec!["step".to_string()]))); + let step = std::fs::read(h.dir.join("Bracket.step")).unwrap(); + assert!(step.starts_with(b"ISO-10303-21;"), "a STEP file is written"); + + crate::keymap::press(&mut h.app, "Alt+Shift+F8", false); + assert_eq!(h.app.dialog.as_ref().and_then(|d| d.command()), Some("file.save_mesh"), "STL opens Save As Mesh"); + crate::dialogs::cancel(&mut h.app); + } + /// New designs are saved as `.sc`. A design opened from a `.solidcraft` file is saved back to /// that file by Save (no rename behind the user's back); Save As offers `.sc` and leaves it. #[test] diff --git a/crates/ui-egui/src/ui_kit/color.rs b/crates/ui-egui/src/ui_kit/color.rs index dfef5e72a..3f181be17 100644 --- a/crates/ui-egui/src/ui_kit/color.rs +++ b/crates/ui-egui/src/ui_kit/color.rs @@ -205,8 +205,11 @@ fn color_popover_with_opacity(ui: &mut Ui, rgb: &mut [u8; 3], mut opacity: Optio Spin { max: 255.0, step: 1.0, speed: 0.5, decimals: 0 } }; ui.columns(3, |columns| { - for ((ui, channel), name) in columns.iter_mut().zip(channels.iter_mut()).zip(["R", "G", "B"]) { - edited |= spin_channel(ui, name, None, channel, spin); + // Named like H, S and V: "R" alone doesn't say red in every language (#10201). + for ((ui, channel), (name, tip)) in + columns.iter_mut().zip(channels.iter_mut()).zip([("R", "color.red"), ("G", "color.green"), ("B", "color.blue")]) + { + edited |= spin_channel(ui, name, Some(i18n::tr(tip)), channel, spin); } }); } @@ -436,7 +439,10 @@ fn spin_buttons(ui: &mut Ui, key: &str, height: f32) -> i32 { let mut steps = 0; for (direction, half, label, end) in [(1, top, "color.step_up", "up"), (-1, bottom, "color.step_down", "down")] { let id = ui.id().with(("color_spin", key, end)); - let response = ui.interact(half, id, Sense::click()); + // Sensing drags too keeps a long press down on the button: a press that senses clicks + // only stops counting once it outlasts egui's longest click (0.8 s), and the repeat with + // it, after 8 steps (#10201). + let response = ui.interact(half, id, Sense::click_and_drag()); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), i18n::tr(label))); publish(&format!("color:spin:{key}:{end}"), &response); let held = response.is_pointer_button_down_on(); diff --git a/crates/ui-egui/src/ui_kit/color_tests.rs b/crates/ui-egui/src/ui_kit/color_tests.rs index ffc05c0f0..8e417c114 100644 --- a/crates/ui-egui/src/ui_kit/color_tests.rs +++ b/crates/ui-egui/src/ui_kit/color_tests.rs @@ -501,3 +501,43 @@ fn recent_colours_are_saved_with_the_preferences_and_hostile_entries_dropped() { assert_eq!(restored.ui.recent_colors.get(1), Some(&[1, 2, 3])); assert_eq!(restored.ui.recent_colors.len(), MAX_RECENT_COLORS); } + +/// #10201: a step button held down keeps stepping until it is let go, past egui's longest click +/// (0.8 s): two seconds of holding H's up button step it about 32 degrees, not the 8 a press +/// counted as a click managed before it stopped. +#[test] +fn a_held_step_button_keeps_stepping_until_it_is_let_go() { + let ctx = crate::fonts::test_context(); + let mut rgb = [255, 0, 0]; + let at_time = |time: f64, events: Vec, rgb: &mut [u8; 3]| { + scenario::clear_handles(); + let _ = crate::test_support::frame( + &ctx, + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 600.0))), + events, + time: Some(time), + focused: true, + ..Default::default() + }, + |ui| { + ui.set_width(280.0); + ui.push_id("picker", |ui| crate::ui_kit::scope(ui, |ui| color_popover(ui, rgb))); + }, + ); + }; + at_time(0.0, vec![], &mut rgb); + let up = scenario::handle_at("color:spin:H:up").expect("H's up button"); + at_time(0.01, pointer(up, true), &mut rgb); + for frame in 1..=120 { + at_time(0.01 + f64::from(frame) / 60.0, vec![egui::Event::PointerMoved(up)], &mut rgb); + } + let hue = |rgb: [u8; 3]| HsvaGamma::from(Color32::from_rgb(rgb[0], rgb[1], rgb[2])).h * 360.0; + let held = hue(rgb); + assert!(held > 20.0, "two seconds held stepped the hue to {held:.1} degrees"); + at_time(2.1, pointer(up, false), &mut rgb); + for frame in 1..=30 { + at_time(2.1 + f64::from(frame) / 60.0, vec![], &mut rgb); + } + assert!((hue(rgb) - held).abs() < 1.5, "let go, it stops: {} after {held}", hue(rgb)); +} diff --git a/crates/ui-egui/src/ui_kit/compare.rs b/crates/ui-egui/src/ui_kit/compare.rs new file mode 100644 index 000000000..e28c3d98f --- /dev/null +++ b/crates/ui-egui/src/ui_kit/compare.rs @@ -0,0 +1,55 @@ +//! Shared image-comparison divider and corner chips. Geometry and ink use kit tokens. +use crate::{scenario, theme::Tokens}; +use egui::{Rect, Sense, Ui, pos2, vec2}; + +pub(crate) fn comparison_position(position: f32) -> f32 { + if position.is_finite() { position.clamp(0.05, 0.95) } else { 0.5 } +} + +/// A vertical wipe handle. The caller owns its command and suppresses canvas navigation while captured. +pub(crate) fn comparison_divider(ui: &mut Ui, canvas: Rect, position: &mut f32, label: &str) -> egui::Response { + let t = Tokens::get(); + *position = comparison_position(*position); + let x = canvas.left() + canvas.width() * *position; + let rail = Rect::from_center_size(pos2(x, canvas.center().y), vec2(t.space_16, canvas.height())); + let mut response = ui.interact(rail, ui.id().with("comparison_divider"), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + if response.dragged() + && let Some(pointer) = response.interact_pointer_pos() + { + *position = comparison_position((pointer.x - canvas.left()) / canvas.width().max(1.0)); + response.mark_changed(); + } + comparison_divider_chrome(ui, canvas, *position); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, ui.is_enabled(), label)); + scenario::publish_target("render:compare:divider", rail); + response +} + +pub(crate) fn comparison_divider_chrome(ui: &Ui, canvas: Rect, position: f32) { + let t = Tokens::get(); + let x = canvas.left() + canvas.width() * comparison_position(position); + let painter = ui.painter().with_clip_rect(canvas.intersect(ui.clip_rect())); + let accent = crate::theme::TabAccent::current(ui.ctx()); + painter.vline(x, canvas.y_range(), egui::Stroke::new(t.space_2, accent.ink)); + let handle = Rect::from_center_size(pos2(x, canvas.center().y), vec2(t.space_16, t.space_24 + t.space_8)); + painter.rect_filled(handle, t.control_radius, t.panel); + painter.rect_stroke(handle, t.control_radius, t.control_border_stroke(accent.ink), egui::StrokeKind::Inside); + for offset in [-t.space_6, 0.0, t.space_6] { + painter.circle_filled(handle.center() + vec2(0.0, offset), t.space_2, accent.ink); + } + scenario::publish_rect("render:compare:handle", handle); +} + +/// Token-painted chip anchored inside either clipped half of the image canvas. +pub(crate) fn comparison_badge(ui: &mut Ui, bounds: Rect, label: &str, right: bool) { + let t = Tokens::get(); + let galley = ui.painter().layout_no_wrap(label.to_owned(), egui::FontId::proportional(t.font_label), t.form_ink); + let size = vec2((galley.size().x + t.space_16).min((bounds.width() - t.space_16).max(0.0)), t.control_height); + let x = if right { bounds.right() - size.x - t.space_8 } else { bounds.left() + t.space_8 }; + let rect = Rect::from_min_size(pos2(x, bounds.top() + t.space_8), size); + let painter = ui.painter().with_clip_rect(bounds.intersect(ui.clip_rect())); + painter.rect_filled(rect, t.control_radius, t.panel); + painter.rect_stroke(rect, t.control_radius, t.control_border_stroke(t.control_border), egui::StrokeKind::Inside); + painter.with_clip_rect(rect).galley(pos2(rect.left() + t.space_8, rect.center().y - galley.size().y * 0.5), galley, t.form_ink); + scenario::publish_rect(if right { "render:compare:right-label" } else { "render:compare:left-label" }, rect); +} diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index ad343f691..400f270e8 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -65,7 +65,14 @@ pub(crate) fn count_field(ui: &mut Ui, value: &mut String, limits: &Count<'_>) - let next = step_count(value, delta, limits); let arrow = ui.interact(half, ui.id().with(("sc_count_step", &row, name)), egui::Sense::click()); let enabled = ui.is_enabled() && next.is_some(); - if enabled && arrow.hovered() { + // The arrows stand inside the editor, which claims the text cursor across its whole + // rect: they are not text, so each one takes the ordinary cursor back after it. The + // pointer is read from the rect rather than from the hover the editor competes for. + let over = ui.rect_contains_pointer(half); + if over { + ui.ctx().set_cursor_icon(egui::CursorIcon::Default); + } + if enabled && over { painter.rect_filled(half.shrink(1.0), t.control_radius, t.selected_bg); } let ink = if enabled { t.form_ink } else { t.form_dim }; @@ -268,6 +275,397 @@ fn searchable_dropdown_with( chosen } +/// Longest search text and custom value a `search_picker` takes. +const SEARCH_TEXT_CAP: usize = 256; +/// Characters of a label shown on a `search_picker` row, and of a tip or note shown with it. +const SEARCH_LABEL_CAP: usize = 64; +const SEARCH_NOTE_CAP: usize = 1024; +/// Characters of a `search_picker` note shown under its list; the rest shows on hover. +const SEARCH_NOTE_SHOWN: usize = 200; +/// Rows a `search_picker` makes room for when it opens with none. +const SEARCH_ROWS_AWAITED: usize = 6; + +/// One row of a `search_picker`. The value, label and tip are searched; `tip` also shows on hover, +/// and a change of `group` between rows draws a heading. +pub(crate) struct SearchChoice<'a> { + pub value: &'a str, + pub label: &'a str, + pub tip: &'a str, + pub group: Option<&'a str>, +} + +/// What a `search_picker` shows. +pub(crate) struct SearchPicker<'a> { + /// ComboBox id salt; it also keys the search text, so one per picker in the window. + pub id: &'a str, + /// Scenario names: the control `{handles}`, its box `{handles}:search`, its custom row + /// `{handles}:custom` and its rows `{handles}:{value}`. + pub handles: &'a str, + /// The text on the closed control, and the value of the row to highlight. + pub current: &'a str, + pub current_value: &'a str, + /// The search box's empty-text hint. + pub hint: &'a str, + pub choices: &'a [SearchChoice<'a>], + /// Offer what was typed as a value of its own when it is not a listed one. + pub custom: bool, + /// A dim line under the list: still listing, or why it could not. + pub note: Option<&'a str>, + /// With two or more groups, each folds under its header. Before anything is typed, only the + /// current value's group and this one are open (every group, when neither names one); a group + /// with a match opens once something is typed; a fold made by hand stays until the popup closes. + pub open_group: Option<&'a str>, + pub enabled: bool, +} + +/// A `search_picker` choice: a listed value, or one typed into the box. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Picked { + Listed(String), + Custom(String), +} + +/// Dropdown whose popup opens on a focused search box over a list of `choices`, filtered as the +/// box is typed in, with an optional row taking the typed text as a value of its own. Enter picks +/// the exact or first match, else the typed text. Only the rows in view are laid out, so a long +/// list stays cheap. Returns the pick and the control's response. +/// Tokens: dropdown tokens, field tokens, `space_24`, `font_small`, `text_dim`, `form_card_width`. +pub(crate) fn search_picker(ui: &mut Ui, p: SearchPicker<'_>) -> egui::InnerResponse> { + crate::prefs_search::note_current(ui, p.current); + // As in `dropdown_menu_with_close_behavior`: only a search probe skips the real control. + if crate::prefs_search::querying(ui) + && (!ui.is_visible() || (crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[p.current]))) + { + return egui::InnerResponse::new(None, crate::prefs_search::hidden_response(ui)); + } + let state = egui::Id::new(p.id); + let mut picked = None; + let response = ui + .add_enabled_ui(p.enabled, |ui| { + let response = egui::ComboBox::from_id_salt(p.id) + .width(dimension(ui.available_width())) + .height(Tokens::get().space_24 * 20.0) + .selected_text(p.current) + .icon(dropdown_arrow) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show_ui(ui, |ui| picked = search_picker_popup(ui, &p, state)) + .response; + // Closed: the next opening starts with an empty box that has the focus. + if !egui::ComboBox::is_open(ui.ctx(), response.id) { + ui.data_mut(|data| { + data.remove::(state.with("filter")); + data.remove::(state.with("focused")); + data.remove::(state.with("height")); + data.remove::(state.with("folds")); + }); + } + response + }) + .inner; + publish(ui, &response, egui::WidgetType::ComboBox); + scenario::publish_target(p.handles, response.rect); + egui::InnerResponse::new(picked, response) +} + +/// What a `search_picker` shows while it is open; the pick, if one was made this frame. +fn search_picker_popup(ui: &mut Ui, p: &SearchPicker<'_>, state: egui::Id) -> Option { + let t = Tokens::get(); + let (filter_id, focused_id, folds_id) = (state.with("filter"), state.with("focused"), state.with("folds")); + // Esc closes this popup only: left in the input, it would also cancel a dialog around it. + if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + ui.close(); + } + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + // The rows' text starts where the box's and the headings' do. + ui.spacing_mut().button_padding.x = t.form_inset; + ui.set_min_width(search_popup_width(ui, p)); + let mut filter: String = ui.data(|data| data.get_temp(filter_id)).unwrap_or_default(); + let search = ui.add( + text_input(egui::TextEdit::singleline(&mut filter)) + .id(state.with("search")) + .char_limit(SEARCH_TEXT_CAP) + .hint_text(p.hint) + .background_color(t.input_fill()) + .desired_width(f32::INFINITY), + ); + t.input_bevel(ui, &search); + scenario::publish_target(&format!("{}:search", p.handles), search.rect); + // Asked until it has it: over a modal window egui drops the request of the opening's first frame. + if !ui.data(|data| data.get_temp::(focused_id)).unwrap_or(false) { + if search.has_focus() { + ui.data_mut(|data| data.insert_temp(focused_id, true)); + } else { + search.request_focus(); + ui.ctx().request_repaint(); + } + } + if search.has_focus() { + crate::prefs_search::note_key_sink(ui.ctx()); + } + if search.changed() { + ui.data_mut(|data| data.insert_temp(filter_id, filter.clone())); + } + let typed = filter.trim(); + let query: String = typed.chars().flat_map(char::to_lowercase).collect(); + // One buffer for every row: this runs each frame the popup is open, over a list of thousands. + let mut searched = String::new(); + let mut hit = |choice: &SearchChoice<'_>| { + searched.clear(); + for text in [choice.value, choice.label, choice.tip] { + searched.extend(text.chars().take(SEARCH_TEXT_CAP).flat_map(char::to_lowercase)); + searched.push('\n'); + } + searched.contains(&query) + }; + let visible: Vec<&SearchChoice<'_>> = p.choices.iter().filter(|choice| query.is_empty() || hit(choice)).collect(); + // Two or more groups fold under their headers: open by default are the current value's group, + // `open_group`, and every group once something is typed; a fold made by hand stays until the + // popup closes. + let grouped = search_groups(p.choices).iter().filter(|(group, _)| group.is_some()).count() >= 2; + let folds: SearchFolds = ui.data(|data| data.get_temp(folds_id)).unwrap_or_default(); + let current_group = p.choices.iter().find(|c| c.value == p.current_value).and_then(|c| c.group).filter(|g| !g.is_empty()); + let nothing_preferred = p.open_group.is_none() && current_group.is_none(); + let is_open = |group: &str| { + folds.get(group).copied().unwrap_or(!query.is_empty() || nothing_preferred || Some(group) == p.open_group || Some(group) == current_group) + }; + let rows = search_rows(&visible, grouped, &is_open); + let shown: Vec<&SearchChoice<'_>> = rows.iter().filter_map(|row| if let SearchRow::Choice(c) = row { Some(*c) } else { None }).collect(); + let custom = (p.custom && !typed.is_empty() && !p.choices.iter().any(|c| c.value == typed)).then_some(typed); + let mut picked = None; + let mut toggled: Option<(String, bool)> = None; + if search.lost_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + let found = visible.iter().find(|c| c.value == typed).or_else(|| shown.first()); + picked = match (typed.is_empty(), found, custom) { + // Nothing asked for: the choice stands. + (true, ..) => { + ui.close(); + None + } + (_, Some(choice), _) => Some(Picked::Listed(choice.value.to_owned())), + (_, None, Some(model)) => Some(Picked::Custom(model.to_owned())), + (_, None, None) => { + search.request_focus(); + None + } + }; + } + let width = ui.available_width(); + let note = p.note.map(|note| { + let shown = compact(note, SEARCH_NOTE_SHOWN); + ui.painter().layout(shown, egui::FontId::proportional(t.font_small), t.text_dim, width) + }); + let gap = ui.spacing().item_spacing.y; + let note_height = note.as_ref().map_or(0.0, |note| note.size().y + gap); + let row_height = row_height(); + let most = ui.ctx().content_rect().height() - t.space_24 * 4.0; + // A popup's Ui stays within its size of the last frame, so it can't grow once it is open. All + // that can change below the box shares a height fixed when it opens, the list taking the rest. + let height = ui.data_mut(|data| { + *data.get_temp_mut_or_insert_with(state.with("height"), || { + let rows = p.choices.len() + search_groups(p.choices).iter().filter(|(group, _)| group.is_some()).count(); + // No rows yet: they may still be on their way, and this can't grow to take them. + let rows = if rows == 0 { SEARCH_ROWS_AWAITED } else { rows }; + let heading = t.space_16 + gap; + let custom = if p.custom { heading + row_height + gap } else { 0.0 }; + let list = (rows as f32 * (row_height + gap)).clamp(custom + row_height + gap, t.space_24 * 10.0); + (heading + list + note_height).min(most).max(heading + custom + row_height + gap) + }) + }); + ui.allocate_ui(vec2(dimension(width), height), |ui| { + ui.set_min_height(height); + if let Some(model) = custom { + search_heading(ui, crate::i18n::tr("ui.agent_chat_custom_heading"), t.space_16); + let text = crate::i18n::format("ui.agent_chat_model_custom", &[("model", &compact(model, SEARCH_LABEL_CAP))]); + let row = search_row(ui, &text, false); + scenario::publish_target(&format!("{}:custom", p.handles), row.rect); + if row.clicked() { + picked = Some(Picked::Custom(model.to_owned())); + } + } + if !visible.is_empty() { + search_heading(ui, crate::i18n::tr("ui.agent_chat_models_heading"), t.space_16); + // Rows of one height, group headings too: only those in view are laid out. + let list = (ui.available_height() - note_height).max(row_height); + egui::ScrollArea::vertical() + .id_salt(state.with("list")) + .max_height(list) + .min_scrolled_height(list) + .auto_shrink([false, false]) + .show_rows(ui, row_height, rows.len(), |ui, range| { + for row in rows.get(range).unwrap_or_default() { + match row { + SearchRow::Heading(group) => search_heading(ui, group, row_height), + SearchRow::Group { name, count, open } => { + let response = search_group_row(ui, name, *count, *open); + scenario::publish_target(&format!("{}:group:{}", p.handles, name), response.rect); + if response.clicked() { + toggled = Some(((*name).to_owned(), !*open)); + } + } + SearchRow::Choice(choice) => { + let response = search_row(ui, &compact(choice.label, SEARCH_LABEL_CAP), choice.value == p.current_value); + scenario::publish_target(&format!("{}:{}", p.handles, choice.value), response.rect); + let response = + if choice.tip.is_empty() { response } else { response.on_hover_text(compact(choice.tip, SEARCH_NOTE_CAP)) }; + if response.clicked() { + picked = Some(Picked::Listed(choice.value.to_owned())); + } + } + } + } + }); + } + if let Some((group, open)) = toggled { + let mut folds = folds; + folds.insert(group, open); + ui.data_mut(|data| data.insert_temp(folds_id, folds)); + // The click took the focus from the box; typing goes on filtering. + search.request_focus(); + } + if let Some(note) = note { + let response = ui.add(egui::Label::new(note)); + if let Some(whole) = p.note.filter(|whole| whole.chars().count() > SEARCH_NOTE_SHOWN) { + response.on_hover_text(compact(whole, SEARCH_NOTE_CAP)); + } + } + }); + if picked.is_some() { + ui.close(); + } + picked +} + +enum SearchRow<'a> { + /// A lone group's dim heading. + Heading(&'a str), + /// One of several groups: its header, with how many of its choices are listed, folded or open. + Group { + name: &'a str, + count: usize, + open: bool, + }, + Choice(&'a SearchChoice<'a>), +} + +/// The folds made by hand in one opening of a `search_picker`: group name to open. +type SearchFolds = std::collections::HashMap; + +/// The groups among `choices` in order of first appearance, each with its choices; `None` is the +/// choices with no group. +fn search_groups<'a, 'c, I>(choices: I) -> Vec<(Option<&'a str>, Vec<&'c SearchChoice<'a>>)> +where + 'a: 'c, + I: IntoIterator>, +{ + let mut groups: Vec<(Option<&'a str>, Vec<&'c SearchChoice<'a>>)> = Vec::new(); + for choice in choices { + let group = choice.group.filter(|g| !g.is_empty()); + match groups.iter_mut().find(|(name, _)| *name == group) { + Some((_, members)) => members.push(choice), + None => groups.push((group, vec![choice])), + } + } + groups +} + +/// The list's rows: each group's choices under its header, which folds them when there are several +/// groups and is a plain heading when there is one; choices with no group as they are. +fn search_rows<'a>(visible: &[&'a SearchChoice<'a>], grouped: bool, is_open: &dyn Fn(&str) -> bool) -> Vec> { + let mut rows = Vec::with_capacity(visible.len()); + for (group, members) in search_groups(visible.iter().copied()) { + match group { + Some(name) if grouped => { + let open = is_open(name); + rows.push(SearchRow::Group { name, count: members.len(), open }); + if open { + rows.extend(members.into_iter().map(SearchRow::Choice)); + } + } + Some(name) => { + rows.push(SearchRow::Heading(name)); + rows.extend(members.into_iter().map(SearchRow::Choice)); + } + None => rows.extend(members.into_iter().map(SearchRow::Choice)), + } + } + rows +} + +/// The header of one of several groups in a `search_picker`: a chevron, the name, how many of its +/// choices are listed, and a rule. A click folds or opens the group. +fn search_group_row(ui: &mut Ui, name: &str, count: usize, open: bool) -> Response { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::click()); + if !ui.is_rect_visible(rect) { + return response; + } + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect, t.radius_sm, t.hover); + } + let y = rect.center().y; + super::disclosure(painter, egui::pos2(rect.left() + t.form_inset + t.space_8 * 0.5, y), open, t.text_dim); + let small = egui::FontId::proportional(t.font_small); + let title = painter.layout_no_wrap(compact(&name.to_uppercase(), SEARCH_LABEL_CAP), small.clone(), t.text); + let title_pos = egui::pos2(rect.left() + t.form_inset + t.space_16, y - title.size().y / 2.0); + let title_width = title.size().x; + painter.galley(title_pos, title, t.text); + let number = painter.layout_no_wrap(count.to_string(), small, t.text_dim); + let pad = t.space_8 * 0.75; + let badge_height = (number.size().y + pad).min(rect.height()); + let badge = egui::Rect::from_min_size( + egui::pos2(title_pos.x + title_width + t.space_8, y - badge_height / 2.0), + vec2(number.size().x + pad * 2.0, badge_height), + ); + painter.rect_filled(badge, t.radius_sm, t.chip); + painter.galley(egui::pos2(badge.left() + pad, y - number.size().y / 2.0), number, t.text_dim); + let (rule_from, rule_to) = (badge.right() + t.space_8, rect.right() - t.form_inset); + if rule_from < rule_to { + painter.hline(rule_from..=rule_to, y, egui::Stroke::new(1.0, t.border)); + } + response.on_hover_text(crate::i18n::format("ui.agent_chat_provider_models", &[("count", &count.to_string())])) +} + +/// A `search_picker` row: as `list_picker`, but read from the left, as a list of ids is. +fn search_row(ui: &mut Ui, text: &str, selected: bool) -> Response { + ui.add_sized(vec2(dimension(ui.available_width()), row_height()), egui::Button::selectable(selected, (text, egui::Atom::grow()))) +} + +/// A dim one-line heading in a `search_picker`'s popup. +fn search_heading(ui: &mut Ui, text: &str, height: f32) { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), height), egui::Sense::hover()); + paint_text( + ui, + rect.shrink2(vec2(t.form_inset, 0.0)), + &compact(text, SEARCH_LABEL_CAP), + egui::FontId::proportional(t.font_small), + t.text_dim, + false, + ); + if text.chars().count() > SEARCH_LABEL_CAP { + response.on_hover_text(compact(text, SEARCH_NOTE_CAP)); + } +} + +/// A `search_picker` popup's width: the control's, wide enough for the longest label and to search +/// in, and never wider than the window. +fn search_popup_width(ui: &Ui, p: &SearchPicker<'_>) -> f32 { + let t = Tokens::get(); + let longest = p.choices.iter().map(|c| c.label).max_by_key(|label| label.chars().take(SEARCH_LABEL_CAP + 1).count()).unwrap_or(""); + let text = ui.painter().layout_no_wrap(compact(longest, SEARCH_LABEL_CAP), egui::TextStyle::Button.resolve(ui.style()), t.text).size().x; + let wanted = text + ui.spacing().button_padding.x * 2.0 + ui.spacing().scroll.bar_width + t.space_8; + let most = (ui.ctx().content_rect().width() - t.space_24 * 2.0).max(0.0); + dimension(wanted.max(ui.available_width()).max(t.form_card_width).min(most)) +} + +/// `text` cut to `max_chars`, with an ellipsis if anything was left out. +fn compact(text: &str, max_chars: usize) -> String { + let mut chars = text.chars(); + let short: String = chars.by_ref().take(max_chars).collect(); + if chars.next().is_some() { format!("{short}…") } else { short } +} + /// Completion/focus implementation shared by field variants. Tokens: `same as field`. fn editor(ui: &mut Ui, value: &mut String, hint: &str, completion: bool) -> (bool, bool, Response) { editor_reserving(ui, value, hint, completion, 0.0) diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs index c05710673..135c9a247 100644 --- a/crates/ui-egui/src/ui_kit/fields_tests.rs +++ b/crates/ui-egui/src/ui_kit/fields_tests.rs @@ -122,6 +122,363 @@ fn searchable_dropdown_filters_selects_and_accepts_custom_values() { } } +#[test] +fn search_picker_filters_focuses_picks_and_takes_custom_values() { + let ctx = crate::fonts::test_context(); + let picked = std::cell::RefCell::new(Vec::new()); + let custom = std::cell::Cell::new(true); + let enabled = std::cell::Cell::new(true); + let choices = [ + SearchChoice { value: "a/one", label: "One", tip: "The first model", group: None }, + SearchChoice { value: "b/two", label: "Two", tip: "The second model", group: Some("Group") }, + SearchChoice { value: "b/three", label: "Three", tip: "", group: Some("Group") }, + ]; + let draw = |ui: &mut Ui| { + row(ui, "Model", |ui| { + let shown = search_picker( + ui, + SearchPicker { + id: "search_picker_test", + handles: "test:model", + current: "One", + current_value: "a/one", + hint: "Search models…", + choices: &choices, + custom: custom.get(), + note: Some("Listing models…"), + open_group: None, + enabled: enabled.get(), + }, + ); + picked.borrow_mut().extend(shown.inner); + }); + }; + let open = || { + let at = scenario::handle_at("test:model").unwrap(); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + }; + let click = |name: &str| { + let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}")); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + }; + let typing = |text: &str| { + frame(&ctx, vec![egui::Event::Text(text.into())], draw); + frame(&ctx, vec![], draw); + }; + let is_open = || scenario::handle_at("test:model:search").is_some(); + frame(&ctx, vec![], draw); + assert!(!is_open() && scenario::handle_at("test:model:a/one").is_none(), "closed: only the control"); + + // Opening focuses the box: what is typed filters over labels, tips and values. + open(); + assert!(is_open()); + assert!(ctx.memory(|m| m.has_focus(egui::Id::new("search_picker_test").with("search"))), "the box has the focus"); + for row in ["a/one", "b/two", "b/three"] { + assert!(scenario::handle_at(&format!("test:model:{row}")).is_some(), "{row}"); + } + assert!(scenario::handle_at("test:model:custom").is_none(), "nothing typed, nothing to use"); + typing("SECOND"); + assert!(scenario::handle_at("test:model:b/two").is_some(), "a tip is searched, whatever the case"); + assert!(scenario::handle_at("test:model:a/one").is_none() && scenario::handle_at("test:model:b/three").is_none()); + assert!(scenario::handle_at("test:model:custom").is_some(), "a substring is no listed value"); + + // A click picks the row, closes the popup and forgets the text. + click("test:model:b/two"); + assert_eq!(picked.take(), [Picked::Listed("b/two".into())]); + assert!(!is_open()); + open(); + assert!(scenario::handle_at("test:model:a/one").is_some(), "the next opening starts unfiltered"); + + // A value exactly as listed needs no custom row; a text nothing matches gets one. + typing("b/three"); + assert!(scenario::handle_at("test:model:custom").is_none()); + assert!(scenario::handle_at("test:model:b/three").is_some()); + frame(&ctx, key(egui::Key::Escape), draw); + frame(&ctx, vec![], draw); + assert!(!is_open() && picked.borrow().is_empty(), "Esc closes without a pick"); + open(); + typing(" vendor/model:free "); + assert!(scenario::handle_at("test:model:a/one").is_none()); + click("test:model:custom"); + assert_eq!(picked.take(), [Picked::Custom("vendor/model:free".into())], "trimmed"); + assert!(!is_open()); + + // Enter picks the first row shown; with no match, the typed text. + open(); + typing("t"); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert_eq!(picked.take(), [Picked::Listed("a/one".into())], "the first row with a t"); + assert!(!is_open()); + open(); + typing("b/"); + typing("three"); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert_eq!(picked.take(), [Picked::Listed("b/three".into())]); + open(); + typing("nothing"); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert_eq!(picked.take(), [Picked::Custom("nothing".into())]); + + // Enter on an empty box leaves the choice as it is. + open(); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert!(picked.borrow().is_empty() && !is_open()); + + // Without custom values, a miss offers nothing and Enter keeps the box. + custom.set(false); + open(); + typing("nothing"); + assert!(scenario::handle_at("test:model:custom").is_none()); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert!(picked.borrow().is_empty() && is_open()); + typing("!"); + frame(&ctx, key(egui::Key::Escape), draw); + frame(&ctx, vec![], draw); + assert!(!is_open()); + + // A disabled control does not open. + enabled.set(false); + open(); + assert!(!is_open()); +} + +/// A long list costs only the rows in view, and a long label neither widens the popup past the +/// window nor reaches past its edge. +/// A popup can't grow once it is open, so what appears in it later must fit in the room it opened +/// with: a custom row above a short list, a list that was empty, a note, and a list again after a +/// search that matched nothing. +#[test] +fn search_picker_keeps_every_row_reachable_as_its_contents_change() { + use std::cell::{Cell, RefCell}; + let ctx = crate::fonts::test_context(); + let values = RefCell::new(vec!["a/one", "b/two"]); + let note: Cell> = Cell::new(None); + let picked = RefCell::new(Vec::new()); + let frame = |events: Vec| { + scenario::clear_handles(); + let raw = + egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }; + let _ = ctx.run_ui(raw, |ui| { + ui.allocate_ui(egui::vec2(160.0, 40.0), |ui| { + crate::ui_kit::scope(ui, |ui| { + let values = values.borrow(); + let choices: Vec> = + values.iter().map(|value| SearchChoice { value, label: value, tip: "", group: None }).collect(); + let result = search_picker( + ui, + SearchPicker { + id: "search_picker_room", + handles: "room", + current: "b/two", + current_value: "b/two", + hint: "Search", + choices: &choices, + custom: true, + note: note.get(), + open_group: None, + enabled: true, + }, + ); + if let Some(pick) = result.inner { + picked.borrow_mut().push(pick); + } + }); + }); + }); + }; + let pointer = |at: egui::Pos2, pressed: bool| { + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ] + }; + let click = |name: &str| { + let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}")); + frame(pointer(at, true)); + frame(pointer(at, false)); + frame(vec![]); + frame(vec![]); + }; + let typing = |text: &str| { + frame(vec![egui::Event::Text(text.into())]); + frame(vec![]); + frame(vec![]); + }; + let erase = |times: usize| { + for _ in 0..times { + frame(vec![egui::Event::Key { + key: egui::Key::Backspace, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }]); + frame(vec![]); + } + frame(vec![]); + }; + frame(vec![]); + frame(vec![]); + + // The custom row appears above the two rows: the row under it can still be clicked. + click("room"); + typing("two"); + assert!(scenario::handle_at("room:custom").is_some()); + click("room:b/two"); + assert_eq!(picked.take(), [Picked::Listed("b/two".into())]); + + // A search that matches nothing leaves no list; taking it back brings the rows, in reach. + click("room"); + typing("zzz"); + assert!(scenario::handle_at("room:a/one").is_none()); + frame(vec![]); + frame(vec![]); + erase(3); + click("room:b/two"); + assert_eq!(picked.take(), [Picked::Listed("b/two".into())]); + + // A list that arrives while it is open, with a long note, stays in reach; the custom row too. + values.borrow_mut().clear(); + note.set(Some("Listing models…")); + frame(vec![]); + click("room"); + frame(vec![]); + values.borrow_mut().extend(["a/one", "b/two", "c/three", "d/four"]); + note.set(Some("A long reason, repeated until it wraps over a few lines of the popup, repeated until it wraps over a few lines of the popup.")); + frame(vec![]); + frame(vec![]); + typing("four"); + click("room:d/four"); + assert_eq!(picked.take(), [Picked::Listed("d/four".into())]); + click("room"); + typing("nothing"); + click("room:custom"); + assert_eq!(picked.take(), [Picked::Custom("nothing".into())]); +} + +#[test] +fn search_picker_lays_out_the_rows_in_view_inside_a_narrow_window() { + let ctx = crate::fonts::test_context(); + let values: Vec = (0..2000).map(|n| format!("vendor/a-model-with-a-rather-long-name-{n:04}-and-then-some-more-of-it-and-more")).collect(); + let choices: Vec> = values.iter().map(|v| SearchChoice { value: v, label: v, tip: "", group: None }).collect(); + let draw = |ui: &mut Ui| { + ui.allocate_ui(egui::vec2(120.0, 28.0), |ui| { + search_picker( + ui, + SearchPicker { + id: "search_picker_long", + handles: "test:long", + current: "One", + current_value: "", + hint: "", + choices: &choices, + custom: false, + note: None, + open_group: None, + enabled: true, + }, + ); + }); + }; + frame(&ctx, vec![], draw); + let at = scenario::handle_at("test:long").unwrap(); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + frame(&ctx, vec![], draw); + let rows = scenario::handles("test:long:vendor/"); + assert!(!rows.is_empty() && rows.len() < 30, "{} rows laid out", rows.len()); + let row = scenario::rect_of("test:long:vendor/a-model-with-a-rather-long-name-0000-and-then-some-more-of-it-and-more").unwrap(); + assert!(row.left() >= 0.0 && row.right() <= 320.0, "{row:?} reaches past the window"); + let search = scenario::rect_of("test:long:search").unwrap(); + assert!(search.left() >= 0.0 && search.right() <= 320.0, "{search:?} reaches past the window"); +} + +/// Several groups fold under their headers: at first only the current value's group and the one +/// asked for are open; a header opens or folds its group; a typed search opens the groups with a +/// match but one folded by hand; Enter takes the first row shown; a fresh opening forgets the folds. +#[test] +fn search_picker_folds_groups_under_their_headers() { + let ctx = crate::fonts::test_context(); + let picked = std::cell::RefCell::new(Vec::new()); + let open_group = std::cell::Cell::new(None::<&'static str>); + let current = std::cell::Cell::new("b1"); + let choices = [ + SearchChoice { value: "a1", label: "Alpha one", tip: "", group: Some("A") }, + SearchChoice { value: "b1", label: "Beta one", tip: "", group: Some("B") }, + SearchChoice { value: "a2", label: "Alpha two", tip: "", group: Some("A") }, + SearchChoice { value: "c1", label: "Gamma one", tip: "", group: Some("C") }, + ]; + let draw = |ui: &mut Ui| { + row(ui, "Model", |ui| { + let shown = search_picker( + ui, + SearchPicker { + id: "search_picker_groups", + handles: "grp", + current: "Beta one", + current_value: current.get(), + hint: "", + choices: &choices, + custom: false, + note: None, + open_group: open_group.get(), + enabled: true, + }, + ); + picked.borrow_mut().extend(shown.inner); + }); + }; + let click = |name: &str| { + let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}")); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + }; + let typing = |text: &str| { + frame(&ctx, vec![egui::Event::Text(text.into())], draw); + frame(&ctx, vec![], draw); + }; + let has = |name: &str| scenario::handle_at(name).is_some(); + frame(&ctx, vec![], draw); + click("grp"); + assert!(has("grp:group:A") && has("grp:group:B") && has("grp:group:C"), "a header per group"); + assert!(has("grp:b1") && !has("grp:a1") && !has("grp:c1"), "only the current value's group is open"); + click("grp:group:A"); + assert!(has("grp:a1") && has("grp:a2"), "a header opens its group"); + click("grp:group:A"); + assert!(!has("grp:a1"), "and folds it again"); + typing("one"); + assert!(!has("grp:a1"), "a fold made by hand stays while searching"); + assert!(has("grp:b1") && has("grp:c1"), "groups with a match open"); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert_eq!(picked.take(), [Picked::Listed("b1".into())], "Enter takes the first row shown, not one folded away"); + assert!(!has("grp:search")); + + open_group.set(Some("C")); + click("grp"); + assert!(!has("grp:a1") && has("grp:b1") && has("grp:c1"), "C opens as asked, B as the current value's, A folds"); + frame(&ctx, key(egui::Key::Escape), draw); + frame(&ctx, vec![], draw); + + open_group.set(None); + current.set(""); + click("grp"); + assert!(has("grp:a1") && has("grp:b1") && has("grp:c1"), "nothing to prefer: every group starts open"); + frame(&ctx, key(egui::Key::Escape), draw); + frame(&ctx, vec![], draw); +} + #[test] fn preference_dropdown_keeps_disabled_choices_inert_and_closes_after_selection() { let ctx = crate::fonts::test_context(); @@ -313,6 +670,39 @@ fn count_steps_stay_within_limits_and_keep_expressions() { assert_eq!(super::step_count("5", i64::MIN, &wide).as_deref(), Some("-9223372036854775803")); } +/// A count's step arrows stand inside the editor, which asks for the text cursor across its +/// whole rect, so the arrows showed an I-beam and read as part of the text. They are not text: +/// the pointer over one is the ordinary cursor, whether it can step or not, and the number +/// beside them is still typed. +#[test] +fn count_step_arrows_do_not_take_the_text_cursor() { + for value in ["5", "1"] { + let ctx = crate::fonts::test_context(); + let eval = |text: &str| text.trim().parse::().ok(); + let mut count = value.to_string(); + let mut draw = |ui: &mut Ui| { + count_row(ui, "Instances", &mut count, &Count { min: 1, max: 10, eval: &eval }); + }; + frame(&ctx, vec![], &mut draw); + let at = |name: &str| scenario::handle_at(&format!("dialog:Instances {name}")).unwrap_or_else(|| panic!("{name} has a handle")); + let (above, below) = (at("up"), at("down")); + let field = scenario::rect_of("dialog:widget:Instances").expect("the field has a rect"); + // The first frame registers the rects; the second reads the cursor they ask for. At 1 the + // down arrow is dimmed and the up arrow can still step: neither is text either way. + for (pos, which) in [(above, "up"), (below, "down")] { + frame_cursor(&ctx, pos, &mut draw); + assert_eq!(frame_cursor(&ctx, pos, &mut draw), egui::CursorIcon::Default, "{value}: the {which} arrow"); + } + let text = egui::pos2(field.left() + 2.0, field.center().y); + frame_cursor(&ctx, text, &mut draw); + assert_eq!(frame_cursor(&ctx, text, &mut draw), egui::CursorIcon::Text, "{value}: the number is still typed"); + // The enabled arrow still steps when it is clicked. + frame(&ctx, pointer(above, true), &mut draw); + frame(&ctx, pointer(above, false), &mut draw); + assert_eq!(count, if value == "1" { "2" } else { "6" }, "the up arrow steps"); + } +} + #[test] fn selection_field_has_three_distinct_looks_in_every_theme() { type Look = (Vec<(egui::Color32, egui::Color32)>, Option); diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index 5d18577e8..2c0c1a633 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -1,4 +1,5 @@ //! Table-driven layout/paint references in both themes. No window or GPU required. +use super::preferences_figures::{ThemeSample, paint_theme_system, paint_theme_thumbnail}; use super::*; use crate::ui_kit::{Container, Surface}; use crate::{scenario, theme::Tokens}; @@ -172,6 +173,15 @@ const ELEMENTS: &[Element] = &[ let (viewport, _) = ui.allocate_exact_size(vec2(200.0, 150.0), egui::Sense::hover()); frame_guides(ui, viewport, viewport.shrink(20.0), FrameGuides { thirds: true, safe_area: true, centre_mark: true }); }), + element!("comparison_divider", |ui, _| { + let (rect, _) = ui.allocate_exact_size(vec2(220.0, 100.0), egui::Sense::hover()); + let mut position = 0.5; + comparison_divider(ui, rect, &mut position, "Comparison divider"); + }), + element!("comparison_badge", |ui, _| { + let (rect, _) = ui.allocate_exact_size(vec2(220.0, 100.0), egui::Sense::hover()); + comparison_badge(ui, rect, "Live preview", false); + }), element!("tree_row_rect", |ui, _| { for (index, row) in [ Row { label: "Objects", ..Default::default() }, @@ -522,6 +532,177 @@ const ELEMENTS: &[Element] = &[ }, ); }), + element!("picture_card", |ui, _| { + use super::preferences_figure_data as figures; + let gap = ui.spacing().item_spacing.x; + let width = card_width(ui.available_width(), 4, gap); + ui.horizontal(|ui| { + picture_card( + ui, + &Card { + label: "Coarse", + sub: Some("fastest"), + selected: false, + enabled: true, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_tess_coarse, + }, + width, + ); + picture_card( + ui, + &Card { + label: "Normal", + sub: Some("default"), + selected: true, + enabled: true, + options: None, + check: true, + aspect: 120.0 / 64.0, + figure: &figures::paint_tess_normal, + }, + width, + ); + picture_card( + ui, + &Card { + label: "Fine", + sub: Some("smoother"), + selected: false, + enabled: true, + options: Some("Has options"), + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_tess_fine, + }, + width, + ); + picture_card( + ui, + &Card { + label: "8×", + sub: Some("not on this GPU"), + selected: false, + enabled: false, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_aa_8x, + }, + width, + ); + }); + }), + element!("toggle_tile", |ui, _| { + use super::preferences_figure_data as figures; + let gap = ui.spacing().item_spacing.x; + let width = card_width(ui.available_width(), 3, gap); + ui.horizontal(|ui| { + toggle_tile( + ui, + &Card { + label: "Grid", + sub: None, + selected: true, + enabled: true, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_view_grid, + }, + width, + ); + toggle_tile( + ui, + &Card { + label: "Ground shadow", + sub: None, + selected: false, + enabled: true, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_view_shadow, + }, + width, + ); + toggle_tile( + ui, + &Card { + label: "Perspective", + sub: None, + selected: false, + enabled: false, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_view_perspective, + }, + width, + ); + }); + }), + element!("preset_card", |ui, _| { + let icon = |p: &egui::Painter, r: egui::Rect, ink: egui::Color32| crate::icons::paint_ink(p, r, "settings", ink); + let width = ui.available_width(); + for (name, word, selected, enabled) in + [("Performance", "Fastest", false, true), ("Quality", "Sharpest", true, true), ("Custom", "Your own mix", false, false)] + { + preset_card(ui, name, word, selected, enabled, &icon, width); + } + }), + element!("help_icon", |ui, _| { + ui.horizontal(|ui| { + text(ui, "Anti-aliasing", Text::Hint("gallery_help")); + help_icon(ui, "Applies when SolidCraft restarts."); + }); + }), + element!("carousel", |ui, _| { + let sample = ThemeSample::from_tokens(&Tokens::get()); + let width = Tokens::get().space_24 * 2.0 + Tokens::get().space_24; + carousel(ui, "gallery_carousel", 6, width, width * 0.8, |ui, index| { + let label = ["Light", "Dark", "System", "Gruvbox", "Studio", "Mono"][index % 6]; + picture_card( + ui, + &Card { + label, + sub: Some("Built in"), + selected: index == 1, + enabled: true, + options: None, + check: false, + aspect: 124.0 / 76.0, + figure: &|p, r| paint_theme_thumbnail(p, r, &sample), + }, + width, + ); + }); + }), + element!("preference_theme_thumbnails", |ui, _| { + let (light, dark) = (ThemeSample::from_tokens(&Tokens::light()), ThemeSample::from_tokens(&Tokens::dark())); + ui.horizontal(|ui| { + for kind in 0..3 { + let (rect, _) = ui.allocate_exact_size(vec2(88.0, 88.0 * 76.0 / 124.0), egui::Sense::hover()); + match kind { + 0 => paint_theme_thumbnail(ui.painter(), rect, &light), + 1 => paint_theme_thumbnail(ui.painter(), rect, &dark), + _ => paint_theme_system(ui.painter(), rect, &light, &dark), + } + } + }); + }), + element!("preference_figures", |ui, _| { + ui.horizontal_wrapped(|ui| { + for (name, size, paint) in super::preferences_figure_data::FIGURES { + let width = 96.0; + let (rect, response) = ui.allocate_exact_size(vec2(width, width * size[1] / size[0]), egui::Sense::hover()); + paint(ui.painter(), rect); + response.on_hover_text(*name); + } + }); + }), element!("preference_option_cards", |ui, _| { ui.horizontal_wrapped(|ui| { for figure in [ @@ -1291,6 +1472,25 @@ const ELEMENTS: &[Element] = &[ searchable_dropdown(ui, "gallery", "One", &mut String::new(), &[SearchOption { value: "one", label: "One", handle: None }], None, None); }); }), + element!("search_picker", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, _| { + row(ui, "Gallery", |ui| { + search_picker( + ui, + SearchPicker { + id: "gallery_search_picker", + handles: "gallery:search_picker", + current: "One", + current_value: "one", + hint: "Search", + choices: &[SearchChoice { value: "one", label: "One", tip: "", group: None }], + custom: true, + note: None, + open_group: None, + enabled: true, + }, + ); + }); + }), element!("text_emphasis", "dialog:row:Gallery", Some("dialog:Bold"), |ui, s| { row(ui, "Gallery", |ui| { text_emphasis(ui, &mut s.checked, &mut false, true); @@ -1961,6 +2161,7 @@ fn gallery_covers_every_inline_element() { "look_chain.rs", "menu.rs", "metrics.rs", + "preferences_cards.rs", "radial.rs", "reports.rs", "sphere.rs", @@ -2572,3 +2773,177 @@ fn tree_icon_actions_keep_repeated_light_rows_independent() { }); assert_eq!(ids.len(), 3); } + +#[test] +fn card_looks_follow_selected_hover_disabled_and_focus() { + use super::preferences_cards::{CardFill, CardInk, card_look}; + let rest = card_look(false, true, false, false); + assert_eq!((rest.border, rest.fill, rest.ink, rest.bold, rest.alpha, rest.focus_ring), (1.0, CardFill::Face, CardInk::Text, false, 1.0, false)); + let hover = card_look(false, true, true, false); + assert_eq!(hover.fill, CardFill::Hover); + let selected = card_look(true, true, true, false); + assert_eq!((selected.border, selected.fill, selected.ink, selected.bold), (2.0, CardFill::Selected, CardInk::Accent, true)); + let disabled = card_look(false, false, true, true); + assert_eq!((disabled.fill, disabled.alpha, disabled.focus_ring), (CardFill::Face, 0.5, false), "a disabled card neither hovers nor shows focus"); + assert!(card_look(false, true, false, true).focus_ring); + assert!(card_look(true, false, false, false).alpha < 1.0, "a selected card can be disabled too"); +} + +#[test] +fn cards_size_to_their_container_and_survive_hostile_sizes() { + use super::preferences_cards::{card_width, carousel_window}; + assert_eq!(card_width(320.0, 4, 10.0), 72.5); + assert_eq!(card_width(320.0, 0, 10.0), 320.0); + for bad in [0.0, -5.0, f32::NAN, f32::INFINITY, f32::MAX] { + let w = card_width(bad, 3, 10.0); + assert!(w.is_finite() && w >= 0.0, "{bad}: {w}"); + let (first, visible) = carousel_window(5, 9, bad, 88.0, 8.0, 26.0); + assert!(first + visible <= 5 && visible >= 1, "{bad}: {first} {visible}"); + } + assert_eq!(carousel_window(0, 3, 400.0, 88.0, 8.0, 26.0), (0, 0)); + // 400 wide: two arrows and their gaps leave 332, which fits three 88-wide items with gaps. + assert_eq!(carousel_window(6, 0, 400.0, 88.0, 8.0, 26.0), (0, 3)); + assert_eq!(carousel_window(6, 5, 400.0, 88.0, 8.0, 26.0), (3, 3), "the offset stops at the last full window"); +} + +fn sample_card<'a>(label: &'a str, selected: bool, enabled: bool) -> super::preferences_cards::Card<'a> { + super::preferences_cards::Card { + label, + sub: Some("sub"), + selected, + enabled, + options: None, + check: selected, + aspect: 120.0 / 64.0, + figure: &super::preferences_figure_data::paint_tess_normal, + } +} + +#[test] +fn picture_cards_and_tiles_click_only_when_enabled_and_never_panic() { + use super::preferences_cards::{picture_card, toggle_tile}; + let ctx = crate::fonts::test_context(); + for tile in [false, true] { + for enabled in [true, false] { + let mut clicked = false; + let mut at = None; + for pass in 0..3 { + let events = match (pass, at) { + (1, Some(p)) => super::test_support::pointer(p, true), + (2, Some(p)) => super::test_support::pointer(p, false), + _ => vec![], + }; + super::test_support::frame(&ctx, events, |ui| { + let card = sample_card("Normal", false, enabled); + let response = if tile { toggle_tile(ui, &card, 120.0) } else { picture_card(ui, &card, 120.0) }; + at = Some(response.rect.center()); + assert!(response.rect.width() == 120.0 && response.rect.height() > 40.0); + clicked |= response.clicked(); + }); + } + assert_eq!(clicked, enabled, "tile {tile}, enabled {enabled}"); + // Zero, negative and non-finite widths must not panic and must stay finite. + super::test_support::frame(&ctx, vec![], |ui| { + for width in [0.0, -3.0, f32::NAN, f32::INFINITY, 1.0e6] { + let response = if tile { + toggle_tile(ui, &sample_card("x", true, enabled), width) + } else { + picture_card(ui, &sample_card("x", true, enabled), width) + }; + assert!(response.rect.is_finite()); + } + }); + } + } +} + +#[test] +fn preset_card_help_icon_and_carousel_behave() { + use super::preferences_cards::{carousel, help_icon, preset_card}; + let ctx = crate::fonts::test_context(); + let icon = |p: &egui::Painter, r: egui::Rect, ink: egui::Color32| crate::icons::paint_ink(p, r, "settings", ink); + super::test_support::frame(&ctx, vec![], |ui| { + for width in [0.0, 10.0, 204.0, f32::NAN] { + let response = preset_card(ui, "Performance", "Fastest", true, true, &icon, width); + assert!(response.rect.is_finite()); + } + let help = help_icon(ui, "Help text"); + assert!(help.rect.width() > 8.0 && help.rect.width() < 20.0); + }); + // The next arrow moves the window by one and stays inert at the end. + let mut first = vec![]; + let mut at = None; + for pass in 0..6 { + let events = match (pass, at) { + (2, Some(p)) => super::test_support::pointer(p, true), + (3, Some(p)) => super::test_support::pointer(p, false), + _ => vec![], + }; + super::test_support::frame(&ctx, events, |ui| { + let (f, visible) = carousel(ui, "carousel_test", 5, 60.0, 40.0, |ui, _| { + ui.allocate_exact_size(egui::vec2(60.0, 40.0), egui::Sense::hover()); + }); + first.push((f, visible)); + if let Some(rect) = scenario::rect_of("prefs:carousel:Next") { + at = Some(rect.center()); + } + }); + } + let (f0, visible) = first[0]; + assert_eq!(f0, 0); + assert!((1..5).contains(&visible), "{visible}"); + assert!(first.last().unwrap().0 >= 1, "the next arrow advanced the window: {first:?}"); +} + +/// Light and dark boards of the shared Preferences widgets and of every figure, rendered on the CPU. +/// Set `SOLIDCRAFT_PREFERENCE_WIDGET_EVIDENCE` to a directory to keep the PNGs. +#[test] +fn preference_widgets_and_figures_board_in_both_themes() { + use super::checks::tests::{raster, textures_update}; + use std::collections::HashMap; + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for (board, names) in [ + ("widgets", &["picture_card", "toggle_tile", "preset_card", "help_icon", "carousel", "preference_theme_thumbnails"][..]), + ("figures", &["preference_figures"][..]), + ] { + for scale in [1.0_f32, 2.0] { + let ctx = crate::fonts::test_context(); + ctx.set_pixels_per_point(scale); + let bounds = egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(if board == "figures" { 700.0 } else { 360.0 }, if board == "figures" { 920.0 } else { 800.0 }), + ); + let mut textures = HashMap::new(); + let mut image = None; + for _ in 0..3 { + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), ..Default::default() }, |ui| { + ui.set_width(bounds.width() - 40.0); + ui.painter().rect_filled(bounds, 0.0, Tokens::get().dialog_body); + ui.add_space(12.0); + scope(ui, |ui| { + for name in names { + example(ui, ELEMENTS.iter().find(|e| e.name == *name).unwrap()); + ui.add_space(Tokens::get().space_12); + } + }); + }); + textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + image = Some(raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures)); + } + let image = image.unwrap(); + assert!(image.pixels().any(|p| p.0[3] != 0)); + if let Some(dir) = std::env::var_os("SOLIDCRAFT_PREFERENCE_WIDGET_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let suffix = if scale > 1.0 { "@2x" } else { "" }; + image + .save(std::path::Path::new(&dir).join(format!("preferences-{board}-{}{suffix}.png", if dark { "dark" } else { "light" }))) + .unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} diff --git a/crates/ui-egui/src/ui_kit/layout.rs b/crates/ui-egui/src/ui_kit/layout.rs index d4461c4ae..cd9acc938 100644 --- a/crates/ui-egui/src/ui_kit/layout.rs +++ b/crates/ui-egui/src/ui_kit/layout.rs @@ -8,6 +8,15 @@ pub(super) const FORM: &str = "sc_dense_form"; pub(super) const LABEL: &str = "sc_form_label"; pub(super) const FIXED_LABEL: &str = "sc_fixed_label_width"; +pub(super) const GROW_LABEL: &str = "sc_grow_label_column"; + +/// A form whose card widens so its widest label fits (#10620). Each pass the form publishes, +/// under `key`, the width its label column needs beyond the design's 1.6x cap; the card's +/// owner reads that before opening the card, so the card settles one frame later. +/// Tokens: `form_label_width, font_label, dialog_label, space_4`. +pub(super) fn scope_grow(ui: &mut Ui, key: egui::Id, add: impl FnOnce(&mut Ui) -> R) -> R { + scope_inner(ui, Some(key), add) +} /// A deliberate label grid for multi-column settings, inherited by the existing shared rows. pub(crate) fn settings_form(ui: &mut Ui, label_width: f32, add: impl FnOnce(&mut Ui) -> R) -> R { @@ -18,7 +27,15 @@ pub(crate) fn settings_form(ui: &mut Ui, label_width: f32, add: impl FnOnce(& /// Mark a form without global state: children inherit this tag through their UI stack. /// Inherited form styling and label-column identity. Tokens: `space_4/8, form_gap_y, control_height, font_label, accent, selected_bg, dialog_rule, control_fill/border/radius, text`. pub(crate) fn scope(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { - ui.scope_builder(egui::UiBuilder::new().ui_stack_info(egui::UiStackInfo::default().with_tag(FORM)), |ui| { + scope_inner(ui, None, add) +} + +fn scope_inner(ui: &mut Ui, grow: Option, add: impl FnOnce(&mut Ui) -> R) -> R { + let mut info = egui::UiStackInfo::default().with_tag(FORM); + if let Some(key) = grow { + info = info.with_tag_value(GROW_LABEL, key); + } + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { let t = Tokens::get(); ui.spacing_mut().item_spacing = vec2(t.space_4, t.form_gap_y); ui.spacing_mut().interact_size.y = row_height(); diff --git a/crates/ui-egui/src/ui_kit/metrics.rs b/crates/ui-egui/src/ui_kit/metrics.rs index 775523829..6990ea468 100644 --- a/crates/ui-egui/src/ui_kit/metrics.rs +++ b/crates/ui-egui/src/ui_kit/metrics.rs @@ -107,7 +107,21 @@ pub(super) fn label_column(ui: &Ui, text: &str, row_width: f32) -> f32 { } None => natural, }; - (widest + t.space_4).clamp(base, base * LABEL_COLUMN_MAX).min(row_width * 0.5) + let needed = widest + t.space_4; + if let Some(&key) = ui.stack().iter().find_map(|node| node.tags().get_downcast::(super::layout::GROW_LABEL)) { + // A growing card (#10620): labels up to the ordinary 1.6x cap keep the design's card + // width; a longer label grows the column past the cap, and the extra the card must + // gain is published under `key` so the card widens by the same amount and the + // control column keeps its design width. + let extra = (needed - base * LABEL_COLUMN_MAX).max(0.0); + let previous = ui.ctx().data(|d| d.get_temp::(key)).unwrap_or(0.0); + if (extra - previous).abs() > 0.5 { + ui.ctx().request_discard("dialog label column width"); + } + ui.ctx().data_mut(|d| d.insert_temp(key, extra)); + return needed.max(base).min(row_width * 0.7); + } + needed.clamp(base, base * LABEL_COLUMN_MAX).min(row_width * 0.5) } #[cfg(test)] diff --git a/crates/ui-egui/src/ui_kit/metrics_tests.rs b/crates/ui-egui/src/ui_kit/metrics_tests.rs index 963642f9e..2ee9025a2 100644 --- a/crates/ui-egui/src/ui_kit/metrics_tests.rs +++ b/crates/ui-egui/src/ui_kit/metrics_tests.rs @@ -1,3 +1,4 @@ +use crate::theme::Tokens; use crate::ui_kit::metrics::dimension; use crate::ui_kit::test_support::*; use crate::ui_kit::*; @@ -22,6 +23,36 @@ fn non_finite_and_tiny_row_widths_are_sanitized() { } } +#[test] +fn a_growing_form_widens_past_the_cap_and_publishes_the_card_extra() { + // #10620: inside `grow_form` the label column takes the width the widest label needs, + // past the 1.6x cap an ordinary form clamps to, and the card's owner is told by how much + // the card must widen so the control column keeps its room. + let ctx = egui::Context::default(); + crate::fonts::setup_fonts(&ctx); + let t = Tokens::get(); + let key = egui::Id::new("grow-test"); + let long = "Anpassung an Leitkurve"; + let mut label = None; + for _ in 0..3 { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.set_width(300.0); + scope_grow(ui, key, |ui| { + let mut value = String::new(); + row(ui, long, |ui| field(ui, &mut value)); + }); + }); + output.textures_delta.clear(); + label = scenario::rect_of(&format!("dialog:label:{long}")); + } + let label = label.unwrap(); + let measured = ctx.fonts_mut(|f| f.layout_no_wrap(long.to_owned(), egui::FontId::proportional(t.font_label), t.dialog_label)).size().x; + assert!(label.width() > t.form_label_width * 1.6, "past the ordinary cap: {label:?}"); + assert!(label.width() >= measured, "the label fits its column: {label:?} vs {measured}"); + let extra = ctx.data(|d| d.get_temp::(key)).unwrap(); + assert!((extra - (label.width() - t.form_label_width * 1.6)).abs() < 0.01, "the card grows only past the cap: {extra}"); +} + #[test] fn file_tiles_are_fixed_height_bounded_and_disabled_actions_stay_inert() { let ctx = crate::fonts::test_context(); diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs index 4e5d5eede..06ea66cde 100644 --- a/crates/ui-egui/src/ui_kit/mod.rs +++ b/crates/ui-egui/src/ui_kit/mod.rs @@ -7,6 +7,7 @@ mod assistant_entry; mod checks; mod choice; mod color; +mod compare; mod confirm; pub mod container; mod details; @@ -27,6 +28,12 @@ mod navigation_settings; pub(crate) mod panel; mod preferences; mod preferences_assistant; +#[allow(dead_code, reason = "composed by the Preferences pages of #9875 to #9883")] +mod preferences_cards; +#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] +mod preferences_figure_data; +#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] +mod preferences_figure_ops; mod preferences_figures; mod preferences_layout; mod preferences_navigation; @@ -57,6 +64,7 @@ pub(crate) use checks::tests::{raster as test_raster, textures_update as test_te pub(crate) use checks::*; pub(crate) use choice::*; pub(crate) use color::*; +pub(crate) use compare::*; pub(crate) use confirm::{Confirm, Tone}; pub use container::{Container, DockEdges, Edge, Surface}; pub(crate) use details::*; @@ -83,6 +91,8 @@ pub use panel::{DialogButtons, Window}; pub(crate) use panel::{collapsible_header, header}; pub(crate) use preferences::*; pub(crate) use preferences_assistant::*; +#[allow(unused_imports, reason = "composed by the Preferences pages of #9875 to #9883")] +pub(crate) use preferences_cards::*; pub(crate) use preferences_navigation::*; pub(crate) use preferences_small::*; pub(crate) use radial::{RADIAL_RADIUS, radial_menu}; diff --git a/crates/ui-egui/src/ui_kit/panel.rs b/crates/ui-egui/src/ui_kit/panel.rs index a686c4122..d9bd34b29 100644 --- a/crates/ui-egui/src/ui_kit/panel.rs +++ b/crates/ui-egui/src/ui_kit/panel.rs @@ -282,6 +282,7 @@ pub(crate) struct Panel<'a> { cancel: &'a str, reset_scroll: bool, joined: Option, + grow_key: Option, } pub(crate) struct WorkspaceOptions<'a> { @@ -600,6 +601,7 @@ impl<'a> Panel<'a> { cancel: "Cancel", reset_scroll: false, joined: None, + grow_key: None, } } @@ -621,6 +623,13 @@ impl<'a> Panel<'a> { self } + /// The feature card's form measures its labels and publishes the width it needs under + /// this key, so the card can widen for the current language (#10620). + pub(crate) fn grow_label(mut self, key: egui::Id) -> Self { + self.grow_key = Some(key); + self + } + /// The footer's primary and closing actions when they are not OK and Cancel. An empty `ok` /// leaves the primary action out (a card that only closes, e.g. Measure). pub(crate) fn actions(mut self, ok: &'a str, cancel: &'a str) -> Self { @@ -759,7 +768,7 @@ impl<'a> Panel<'a> { mut collapsed: Option<&mut bool>, body: impl FnOnce(&mut Ui) -> ComputeStatus, ) -> (bool, super::Action) { - super::scope(ui, |ui| { + let card = |ui: &mut Ui| { let t = Tokens::get(); let min = ui.cursor().min; let band = egui::Rect::from_min_size(min, vec2(ui.available_width(), super::header_height())); @@ -845,7 +854,11 @@ impl<'a> Panel<'a> { ); super::Container::finish_content(ui, self.positioned_frame(ui.ctx())); (close, action) - }) + }; + match self.grow_key { + Some(key) => super::scope_grow(ui, key, card), + None => super::scope(ui, card), + } } /// Palette composition retains its compact padding and whole-card scrolling on short views. diff --git a/crates/ui-egui/src/ui_kit/preferences.rs b/crates/ui-egui/src/ui_kit/preferences.rs index 0275e5ee7..470345cf0 100644 --- a/crates/ui-egui/src/ui_kit/preferences.rs +++ b/crates/ui-egui/src/ui_kit/preferences.rs @@ -729,7 +729,7 @@ pub(crate) fn option_card(ui: &mut Ui, label: &str, note: Option<&str>, selected if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } } -fn centred_text(p: &egui::Painter, rect: Rect, label: &str, font: FontId, ink: Color32) { +pub(super) fn centred_text(p: &egui::Painter, rect: Rect, label: &str, font: FontId, ink: Color32) { centred_text_rows(p, rect, label, font, ink, 1); } diff --git a/crates/ui-egui/src/ui_kit/preferences_cards.rs b/crates/ui-egui/src/ui_kit/preferences_cards.rs new file mode 100644 index 000000000..7b227d209 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/preferences_cards.rs @@ -0,0 +1,319 @@ +//! The controls the redesigned Preferences pages share: picture cards, toggle tiles, preset cards, +//! the hover-help icon and the carousel. Sizes follow `docs/design/preferences/measurements.md`; +//! every colour comes from `Tokens`. A card sizes to the width its container gives it and its +//! figure keeps the figure's aspect ratio. +use super::{metrics::dimension, preferences::centred_text}; +use crate::{scenario, theme::Tokens}; +use egui::{Color32, FontId, Painter, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; + +/// How a card or tile looks in a state. Kept separate from painting so the state rules can be tested. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct CardLook { + /// Border width in points: 2 when selected, else 1. + pub border: f32, + pub fill: CardFill, + pub ink: CardInk, + pub bold: bool, + /// Multiplier on every colour; a disabled card is dimmed. + pub alpha: f32, + /// A keyboard focus ring outside the border. + pub focus_ring: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CardFill { + Face, + Hover, + Selected, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CardInk { + Text, + Accent, +} + +pub(super) fn card_look(selected: bool, enabled: bool, hovered: bool, focused: bool) -> CardLook { + CardLook { + border: if selected { 2.0 } else { 1.0 }, + fill: if selected { + CardFill::Selected + } else if enabled && hovered { + CardFill::Hover + } else { + CardFill::Face + }, + ink: if selected { CardInk::Accent } else { CardInk::Text }, + bold: selected, + alpha: if enabled { 1.0 } else { 0.5 }, + focus_ring: enabled && focused, + } +} + +/// What a picture card or toggle tile shows. +pub(crate) struct Card<'a> { + pub label: &'a str, + /// One short line under the label ("default", "Built in"). + pub sub: Option<&'a str>, + /// Selected (radio) or on (tile). + pub selected: bool, + pub enabled: bool, + /// The small "has options" disc at the top right. + pub options: Option<&'a str>, + /// An accent check at the top right (picture cards only). + pub check: bool, + /// Width over height of the figure. + pub aspect: f32, + pub figure: &'a dyn Fn(&Painter, Rect), +} + +/// The width of one of `columns` cards in `available` points with `gap` between them. +pub(super) fn card_width(available: f32, columns: usize, gap: f32) -> f32 { + let columns = columns.max(1) as f32; + let available = dimension(available); + ((available - gap.max(0.0) * (columns - 1.0)) / columns).max(0.0) +} + +fn card_height(t: &Tokens, width: f32, card: &Card) -> f32 { + let pad = t.space_6; + let aspect = if card.aspect.is_finite() && card.aspect > 0.01 { card.aspect } else { 1.0 }; + let figure = ((width - 2.0 * pad).max(0.0) / aspect).min(dimension(f32::MAX)); + let sub = if card.sub.is_some() { t.space_14 } else { 0.0 }; + pad + figure + gap(t) + t.space_16 + sub + pad + 1.0 +} + +fn gap(t: &Tokens) -> f32 { + (t.space_4 + t.space_6) * 0.5 +} + +fn paint_card(ui: &mut Ui, card: &Card, width: f32, tile: bool) -> Response { + let t = Tokens::get(); + let width = dimension(width); + let enabled = card.enabled && ui.is_enabled(); + let (rect, response) = ui.allocate_exact_size(vec2(width, card_height(&t, width, card)), if enabled { Sense::click() } else { Sense::hover() }); + let look = card_look(card.selected, enabled, response.hovered(), response.has_focus()); + let p = ui.painter(); + let dim = |c: Color32| c.gamma_multiply(look.alpha); + let fill = match look.fill { + CardFill::Selected => t.selected_bg, + CardFill::Hover => t.hover, + CardFill::Face => t.control_fill, + }; + let border = if card.selected { t.form_primary } else { t.dialog_border }; + let radius = f32::from(t.radius_lg); + p.rect(rect, radius, dim(fill), Stroke::new(look.border, dim(border)), StrokeKind::Inside); + if look.focus_ring { + p.rect_stroke(rect.expand(t.space_2), radius + t.space_2, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside); + } + let inset = t.space_6; + let figure = Rect::from_min_size( + rect.min + vec2(inset, inset), + vec2((rect.width() - 2.0 * inset).max(0.0), ((rect.width() - 2.0 * inset).max(0.0) / card.aspect.max(0.01)).min(rect.height())), + ); + if figure.is_positive() { + let figure_painter = p.with_clip_rect(figure.intersect(p.clip_rect())); + (card.figure)(&figure_painter, figure); + if !enabled { + p.rect_filled(figure, 0.0, t.control_fill.gamma_multiply(0.5)); + } + } + let ink = match look.ink { + CardInk::Accent => t.selected_ink, + CardInk::Text => t.form_ink, + }; + let font = if look.bold { crate::fonts::semibold(t.font_label) } else { FontId::proportional(t.font_label) }; + let label_rect = + Rect::from_min_size(pos2(rect.left() + t.space_2, figure.bottom() + gap(&t)), vec2((rect.width() - 2.0 * t.space_2).max(0.0), t.space_16)); + centred_text(p, label_rect, card.label, font, dim(ink)); + if let Some(sub) = card.sub { + let sub_rect = Rect::from_min_size(pos2(label_rect.left(), label_rect.bottom()), vec2(label_rect.width(), t.space_14)); + centred_text(p, sub_rect, sub, FontId::proportional(t.font_small), dim(t.form_dim)); + } + let corner = pos2(rect.right() - t.space_6, rect.top() + t.space_6); + if tile { + // The checkbox in the corner: 15 points, radius 4, accent with a tick when on. + let size = t.space_14 + 1.0; + let box_rect = Rect::from_min_size(corner - vec2(size, 0.0), vec2(size, size)); + if card.selected { + p.rect_filled(box_rect, t.space_4, dim(t.form_primary)); + tick(p, box_rect, dim(t.on_accent)); + } else { + p.rect(box_rect, t.space_4, dim(t.control_fill), Stroke::new(1.0, dim(t.control_border)), StrokeKind::Inside); + } + } else if card.options.is_some() || card.check { + let size = t.space_16; + let centre = pos2(rect.right() - t.space_6 + 1.0 - size * 0.5, rect.top() + t.space_6 - 1.0 + size * 0.5); + p.circle_filled(centre, size * 0.5, dim(t.form_primary)); + if card.check { + tick(p, Rect::from_center_size(centre, vec2(size, size) * 0.75), dim(t.on_accent)); + } else { + let dot = Rect::from_center_size(centre, vec2(size, size) * 0.6); + crate::icons::paint_ink(p, dot, "settings", dim(t.on_accent)); + } + } + let kind = if tile { egui::WidgetType::Checkbox } else { egui::WidgetType::RadioButton }; + response.widget_info(|| egui::WidgetInfo::selected(kind, enabled, card.selected, card.label)); + scenario::publish_target(&format!("prefs:card:{}", card.label), rect); + let response = if let Some(options) = card.options { response.on_hover_text(options) } else { response }; + if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } +} + +fn tick(p: &Painter, r: Rect, ink: Color32) { + let w = (r.width() * 0.16).max(1.0); + let a = pos2(r.left() + r.width() * 0.24, r.top() + r.height() * 0.52); + let b = pos2(r.left() + r.width() * 0.42, r.top() + r.height() * 0.70); + let c = pos2(r.left() + r.width() * 0.78, r.top() + r.height() * 0.32); + p.line_segment([a, b], Stroke::new(w, ink)); + p.line_segment([b, c], Stroke::new(w, ink)); +} + +/// A radio card: a figure, a label and an optional sub-label. Click it to choose it. +pub(crate) fn picture_card(ui: &mut Ui, card: &Card, width: f32) -> Response { + paint_card(ui, card, width, false) +} + +/// A toggle tile: the same picture with a checkbox in the corner. Click it to flip `card.selected`. +pub(crate) fn toggle_tile(ui: &mut Ui, card: &Card, width: f32) -> Response { + paint_card(ui, card, width, true) +} + +/// A preset card: an icon, a name, one word and a check. `icon` paints into the 38-point box in +/// the colour it is given. +pub(crate) fn preset_card( + ui: &mut Ui, + name: &str, + word: &str, + selected: bool, + enabled: bool, + icon: &dyn Fn(&Painter, Rect, Color32), + width: f32, +) -> Response { + let t = Tokens::get(); + let enabled = enabled && ui.is_enabled(); + let width = dimension(width); + let height = t.space_24 * 3.0 - t.space_2; + let (rect, response) = ui.allocate_exact_size(vec2(width, height), if enabled { Sense::click() } else { Sense::hover() }); + let look = card_look(selected, enabled, response.hovered(), response.has_focus()); + let dim = |c: Color32| c.gamma_multiply(look.alpha); + let p = ui.painter(); + let fill = match look.fill { + CardFill::Selected => t.selected_bg, + CardFill::Hover => t.hover, + CardFill::Face => t.control_fill, + }; + let radius = f32::from(t.radius_lg) + t.space_2; + p.rect(rect, radius, dim(fill), Stroke::new(look.border, dim(if selected { t.form_primary } else { t.dialog_border })), StrokeKind::Inside); + if look.focus_ring { + p.rect_stroke(rect.expand(t.space_2), radius + t.space_2, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside); + } + let box_size = t.space_24 + t.space_14; + let box_rect = Rect::from_min_size(pos2(rect.left() + t.space_14, rect.center().y - box_size * 0.5), vec2(box_size, box_size)); + let box_fill = if selected { t.form_primary } else { t.pref_well }; + let box_ink = if selected { t.on_accent } else { t.form_dim }; + p.rect_filled(box_rect, f32::from(t.radius_lg) + t.space_2, dim(box_fill)); + icon(p, Rect::from_center_size(box_rect.center(), box_rect.size() * 0.55), dim(box_ink)); + let text_left = box_rect.right() + t.space_12; + let text_width = (rect.right() - t.space_14 - t.space_24 - text_left).max(0.0); + let name_font = crate::fonts::semibold(t.font_heading.min(t.font_subtitle)); + let name_ink = if selected { t.selected_ink } else { t.form_ink }; + let name_rect = Rect::from_min_size(pos2(text_left, rect.center().y - t.space_16), vec2(text_width, t.space_16)); + super::text::paint_text(ui, name_rect, name, name_font, dim(name_ink), false); + let word_rect = Rect::from_min_size(pos2(text_left, name_rect.bottom()), vec2(text_width, t.space_16)); + super::text::paint_text(ui, word_rect, word, FontId::proportional(t.font_small), dim(t.form_dim), false); + let p = ui.painter(); + if selected { + let centre = pos2(rect.right() - t.space_14 - t.space_8 + 1.0, rect.center().y); + p.circle_filled(centre, t.space_8 + 1.0, dim(t.form_primary)); + tick(p, Rect::from_center_size(centre, vec2(t.space_12, t.space_12)), dim(t.on_accent)); + } + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, enabled, selected, name)); + scenario::publish_target(&format!("prefs:preset:{name}"), rect); + if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } +} + +/// The (i) icon after a label: shows `text` as a tooltip and tells assistive technology the same. +pub(crate) fn help_icon(ui: &mut Ui, text: &str) -> Response { + let t = Tokens::get(); + let size = t.space_12 + 1.0; + let (rect, response) = ui.allocate_exact_size(vec2(size, size), Sense::hover()); + let ink = if response.hovered() { t.form_ink } else { t.form_dim }; + let p = ui.painter(); + p.circle_stroke(rect.center(), size * 0.5 - 0.5, Stroke::new(1.0, ink)); + p.circle_filled(pos2(rect.center().x, rect.top() + size * 0.3), 0.9, ink); + p.line_segment([pos2(rect.center().x, rect.top() + size * 0.46), pos2(rect.center().x, rect.bottom() - size * 0.24)], Stroke::new(1.2, ink)); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), text)); + scenario::publish_target("prefs:help_icon", rect); + response.on_hover_text(text) +} + +/// Which items of a carousel are shown: the first one and how many fit between the two arrows. +pub(super) fn carousel_window(count: usize, offset: usize, available: f32, item_width: f32, gap: f32, arrow: f32) -> (usize, usize) { + if count == 0 { + return (0, 0); + } + let room = dimension(available) - 2.0 * (arrow + gap); + let unit = dimension(item_width).max(1.0) + gap.max(0.0); + let visible = (((room + gap) / unit).floor() as usize).clamp(1, count); + (offset.min(count - visible), visible) +} + +/// A row of items with a previous and a next arrow; an arrow is dimmed and inert at its end. +/// `item` paints the item at an index into a column `item_width` wide and `item_height` high. +pub(crate) fn carousel( + ui: &mut Ui, + id: impl std::hash::Hash + std::fmt::Debug, + count: usize, + item_width: f32, + item_height: f32, + mut item: impl FnMut(&mut Ui, usize), +) -> (usize, usize) { + let t = Tokens::get(); + let key = ui.make_persistent_id(id); + let gap = t.space_8; + let arrow = t.space_24 + 2.0; + let offset = ui.data(|d| d.get_temp::(key)).unwrap_or(0); + let (first, visible) = carousel_window(count, offset, ui.available_width(), item_width, gap, arrow); + let height = dimension(item_height); + let mut next_offset = first; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = gap; + let can_back = first > 0; + if carousel_arrow(ui, vec2(arrow, height), -1.0, can_back, crate::i18n::tr("prefs.carousel_previous")).clicked() { + next_offset = first.saturating_sub(1); + } + for index in first..first + visible { + ui.allocate_ui_with_layout(vec2(dimension(item_width), height), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_width(dimension(item_width)); + item(ui, index); + }); + } + let can_forward = first + visible < count; + if carousel_arrow(ui, vec2(arrow, height), 1.0, can_forward, crate::i18n::tr("prefs.carousel_next")).clicked() { + next_offset = (first + 1).min(count.saturating_sub(visible)); + } + }); + ui.data_mut(|d| d.insert_temp(key, next_offset)); + (first, visible) +} + +fn carousel_arrow(ui: &mut Ui, size: egui::Vec2, direction: f32, enabled: bool, label: &str) -> Response { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(size, if enabled { Sense::click() } else { Sense::hover() }); + let alpha = if enabled { 1.0 } else { 0.35 }; + let p = ui.painter(); + let fill = if enabled && response.hovered() { t.hover } else { t.control_fill }; + p.rect(rect, f32::from(t.radius_lg), fill.gamma_multiply(alpha), Stroke::new(1.0, t.dialog_border.gamma_multiply(alpha)), StrokeKind::Inside); + let icon = Rect::from_center_size(rect.center(), vec2(t.space_16, t.space_16)); + let ink = t.form_ink.gamma_multiply(alpha); + if direction < 0.0 { + crate::icons::paint_ink_mirrored(p, icon, "chevron_right", ink); + } else { + crate::icons::paint_ink(p, icon, "chevron_right", ink); + } + if enabled && response.has_focus() { + p.rect_stroke(rect.expand(t.space_2), f32::from(t.radius_lg) + t.space_2, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside); + } + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, label)); + scenario::publish_target(&format!("prefs:carousel:{label}"), rect); + if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } +} diff --git a/crates/ui-egui/src/ui_kit/preferences_figure_data.rs b/crates/ui-egui/src/ui_kit/preferences_figure_data.rs new file mode 100644 index 000000000..313496bb7 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/preferences_figure_data.rs @@ -0,0 +1,4580 @@ +//! Generated by `tools/preferences-figures/generate.py` from `docs/design/preferences/figures/*.svg`. +//! Do not edit by hand: change the SVG and run the script again. +#![allow(clippy::approx_constant, clippy::excessive_precision)] +use super::preferences_figure_ops::{Figure, G, Ink, L, Op, P}; + +pub(super) const AA_2X: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [108.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [84.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { r: [90.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [96.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { r: [78.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [84.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [66.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { r: [48.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [54.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [36.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [42.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [24.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [6.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [12.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[6.0, 8.0], [6.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[12.0, 8.0], [12.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[18.0, 8.0], [18.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[24.0, 8.0], [24.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 8.0], [30.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 8.0], [36.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 8.0], [42.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 8.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[54.0, 8.0], [54.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 8.0], [60.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 8.0], [66.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 8.0], [72.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.0, 8.0], [78.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.0, 8.0], [84.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 8.0], [90.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[96.0, 8.0], [96.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[102.0, 8.0], [102.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[108.0, 8.0], [108.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[114.0, 8.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 8.0], [114.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 14.0], [114.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 20.0], [114.0, 20.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 26.0], [114.0, 26.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 32.0], [114.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 38.0], [114.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 44.0], [114.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 50.0], [114.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 56.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const AA_4X: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.06 }), line: None }, + Op::Rect { r: [102.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.44 }), line: None }, + Op::Rect { r: [108.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.88 }), line: None }, + Op::Rect { r: [84.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.12 }), line: None }, + Op::Rect { r: [90.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.62 }), line: None }, + Op::Rect { r: [96.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.94 }), line: None }, + Op::Rect { r: [102.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.38 }), line: None }, + Op::Rect { r: [78.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [84.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.06 }), line: None }, + Op::Rect { r: [60.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [66.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.88 }), line: None }, + Op::Rect { r: [72.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { r: [48.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.62 }), line: None }, + Op::Rect { r: [54.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.06 }), line: None }, + Op::Rect { r: [30.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.38 }), line: None }, + Op::Rect { r: [36.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.81 }), line: None }, + Op::Rect { r: [42.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.12 }), line: None }, + Op::Rect { r: [18.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.56 }), line: None }, + Op::Rect { r: [24.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.94 }), line: None }, + Op::Rect { r: [30.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [6.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.69 }), line: None }, + Op::Rect { r: [12.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[6.0, 8.0], [6.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[12.0, 8.0], [12.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[18.0, 8.0], [18.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[24.0, 8.0], [24.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 8.0], [30.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 8.0], [36.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 8.0], [42.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 8.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[54.0, 8.0], [54.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 8.0], [60.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 8.0], [66.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 8.0], [72.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.0, 8.0], [78.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.0, 8.0], [84.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 8.0], [90.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[96.0, 8.0], [96.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[102.0, 8.0], [102.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[108.0, 8.0], [108.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[114.0, 8.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 8.0], [114.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 14.0], [114.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 20.0], [114.0, 20.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 26.0], [114.0, 26.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 32.0], [114.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 38.0], [114.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 44.0], [114.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 50.0], [114.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 56.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const AA_8X: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.06 }), line: None }, + Op::Rect { r: [102.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.42 }), line: None }, + Op::Rect { r: [108.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.84 }), line: None }, + Op::Rect { r: [84.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.17 }), line: None }, + Op::Rect { r: [90.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.59 }), line: None }, + Op::Rect { r: [96.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.95 }), line: None }, + Op::Rect { r: [102.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.02 }), line: None }, + Op::Rect { r: [72.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.33 }), line: None }, + Op::Rect { r: [78.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [84.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.09 }), line: None }, + Op::Rect { r: [60.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.48 }), line: None }, + Op::Rect { r: [66.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.89 }), line: None }, + Op::Rect { r: [72.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.22 }), line: None }, + Op::Rect { r: [48.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.66 }), line: None }, + Op::Rect { r: [54.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.98 }), line: None }, + Op::Rect { r: [60.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.03 }), line: None }, + Op::Rect { r: [30.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.39 }), line: None }, + Op::Rect { r: [36.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.81 }), line: None }, + Op::Rect { r: [42.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.14 }), line: None }, + Op::Rect { r: [18.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.55 }), line: None }, + Op::Rect { r: [24.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.94 }), line: None }, + Op::Rect { r: [30.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [6.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.7 }), line: None }, + Op::Rect { r: [12.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[6.0, 8.0], [6.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[12.0, 8.0], [12.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[18.0, 8.0], [18.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[24.0, 8.0], [24.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 8.0], [30.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 8.0], [36.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 8.0], [42.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 8.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[54.0, 8.0], [54.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 8.0], [60.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 8.0], [66.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 8.0], [72.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.0, 8.0], [78.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.0, 8.0], [84.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 8.0], [90.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[96.0, 8.0], [96.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[102.0, 8.0], [102.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[108.0, 8.0], [108.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[114.0, 8.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 8.0], [114.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 14.0], [114.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 20.0], [114.0, 20.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 26.0], [114.0, 26.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 32.0], [114.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 38.0], [114.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 44.0], [114.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 50.0], [114.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 56.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 0.55 }), line: None }, + ], +}; + +pub(super) const AA_OFF: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [6.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[6.0, 8.0], [6.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[12.0, 8.0], [12.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[18.0, 8.0], [18.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[24.0, 8.0], [24.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 8.0], [30.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 8.0], [36.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 8.0], [42.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 8.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[54.0, 8.0], [54.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 8.0], [60.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 8.0], [66.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 8.0], [72.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.0, 8.0], [78.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.0, 8.0], [84.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 8.0], [90.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[96.0, 8.0], [96.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[102.0, 8.0], [102.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[108.0, 8.0], [108.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[114.0, 8.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 8.0], [114.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 14.0], [114.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 20.0], [114.0, 20.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 26.0], [114.0, 26.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 32.0], [114.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 38.0], [114.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 44.0], [114.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 50.0], [114.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 56.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const AGENT_POINTER_SPEED: Figure = Figure { + size: [230.0, 84.0], + ops: &[ + Op::Poly { + pts: &[[24.0, 48.0], [115.0, 42.0], [186.0, 36.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [3.0, 4.0], round: false }), + }, + Op::Circle { c: [24.0, 48.0, 3.0], fill: Some(P { ink: Ink::ControlBorder, a: 1.0 }), line: None }, + Op::Circle { c: [115.0, 42.0, 3.0], fill: Some(P { ink: Ink::ControlBorder, a: 1.0 }), line: None }, + Op::Circle { c: [186.0, 36.0, 3.0], fill: Some(P { ink: Ink::ControlBorder, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[115.0, 42.0], [118.0, 60.0], [123.0, 53.0], [130.0, 56.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Card, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const AO_ON: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[32.742, 27.5], [44.0, 34.0], [44.0, 47.0], [32.742, 40.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[55.258, 27.5], [44.0, 34.0], [44.0, 47.0], [55.258, 40.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 21.0], [55.258, 27.5], [44.0, 34.0], [32.742, 27.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[64.742, 27.5], [76.0, 34.0], [76.0, 47.0], [64.742, 40.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[87.258, 27.5], [76.0, 34.0], [76.0, 47.0], [87.258, 40.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[76.0, 21.0], [87.258, 27.5], [76.0, 34.0], [64.742, 27.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Glow { c: [60.0, 42.0, 22.0, 7.0], a: 0.55 }, + Op::Glow { c: [60.0, 31.0, 5.0, 10.0], a: 0.44 }, + ], +}; + +pub(super) const ASSEMBLY_MOVE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 20.0], fill: None, line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }) }, + Op::Circle { c: [60.0, 32.0, 27.0], fill: None, line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }) }, + Op::Poly { + pts: &[[77.0, 32.0], [83.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[74.7, 40.5], [79.9, 43.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[68.5, 46.7], [71.5, 51.9]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 49.0], [60.0, 55.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[51.5, 46.7], [48.5, 51.9]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[45.3, 40.5], [40.1, 43.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[43.0, 32.0], [37.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[45.3, 23.5], [40.1, 20.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[51.5, 17.3], [48.5, 12.1]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 15.0], [60.0, 9.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[68.5, 17.3], [71.5, 12.1]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[74.7, 23.5], [79.9, 20.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [54.0, 26.0, 12.0, 12.0], + radius: 2.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [80.0, 32.0, 3.6], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [80.0, 32.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + ], +}; + +pub(super) const BROWSER_CARD: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 214.0, 92.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[100.01, 66.5], [113.0, 74.0], [113.0, 89.0], [100.01, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[125.99, 66.5], [113.0, 74.0], [113.0, 89.0], [125.99, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[113.0, 59.0], [125.99, 66.5], [113.0, 74.0], [100.01, 66.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [12.0, 32.0, 48.0, 62.0], + radius: 4.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 122.0, 214.0, 20.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [42.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [72.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [102.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [132.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [162.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + ], +}; + +pub(super) const BROWSER_COLUMN: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 156.0, 92.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 66.5], [142.0, 74.0], [142.0, 89.0], [129.01, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 66.5], [142.0, 74.0], [142.0, 89.0], [154.99, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 59.0], [154.99, 66.5], [142.0, 74.0], [129.01, 66.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 122.0, 214.0, 20.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [42.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [72.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [102.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [132.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [162.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + ], +}; + +pub(super) const COLOUR_VISION_AXES: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[14.0, 34.0], [66.0, 34.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv2, a: 1.0, w: 3.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[14.0, 34.0], [14.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv0, a: 1.0, w: 3.0, dash: [0.0, 0.0], round: true }), + }, + ], +}; + +pub(super) const COLOUR_VISION_BENDS: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[10.0, 14.0], [74.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv1, a: 1.0, w: 2.4, dash: [6.0, 4.0], round: false }), + }, + Op::Poly { + pts: &[[10.0, 30.0], [74.0, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv3, a: 1.0, w: 2.4, dash: [6.0, 4.0], round: false }), + }, + ], +}; + +pub(super) const COLOUR_VISION_DRAFT: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [8.0, 8.0, 22.0, 28.0], radius: 0.0, fill: Some(P { ink: Ink::Cv3, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 8.0, 22.0, 28.0], radius: 0.0, fill: Some(P { ink: Ink::Cv1, a: 1.0 }), line: None }, + Op::Clip(&[[52.0, 8.0], [76.0, 8.0], [76.0, 36.0], [52.0, 36.0]]), + Op::Rect { r: [52.0, 8.0, 24.0, 28.0], radius: 0.0, fill: Some(P { ink: Ink::Cv4, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[38.0, 36.0], [52.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 36.0], [58.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[50.0, 36.0], [64.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[56.0, 36.0], [70.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[62.0, 36.0], [76.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[68.0, 36.0], [82.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[74.0, 36.0], [88.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + ], +}; + +pub(super) const COLOUR_VISION_FAILED: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [14.0, 12.0, 56.0, 20.0], + radius: 4.0, + fill: Some(P { ink: Ink::NoteFill, a: 1.0 }), + line: Some(L { ink: Ink::Cv2, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 17.0], [48.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv2, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[48.0, 17.0], [36.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv2, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + ], +}; + +pub(super) const COLOUR_VISION_FIXED: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[12.0, 22.0], [72.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv0, a: 1.0, w: 3.0, dash: [0.0, 0.0], round: true }), + }, + ], +}; + +pub(super) const COLOUR_VISION_PROJECTED: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[12.0, 22.0], [72.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv1, a: 1.0, w: 3.0, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [12.0, 22.0, 2.2], fill: Some(P { ink: Ink::Cv1, a: 1.0 }), line: None }, + Op::Circle { c: [72.0, 22.0, 2.2], fill: Some(P { ink: Ink::Cv1, a: 1.0 }), line: None }, + ], +}; + +pub(super) const DIRECT_INTERACTION: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[31.0, 20.0], [44.0, 27.5], [44.0, 57.5], [31.0, 50.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[57.0, 20.0], [44.0, 27.5], [44.0, 57.5], [57.0, 50.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 12.5], [57.0, 20.0], [44.0, 27.5], [31.0, 20.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 12.5], [57.0, 20.0], [44.0, 27.5], [31.0, 20.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.4 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 30.5], [57.0, 38.0], [44.0, 45.5], [31.0, 38.0]], + closed: true, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.0, dash: [2.5, 2.5], round: false }), + }, + Op::Poly { + pts: &[[44.0, 34.0], [44.0, 13.1]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[44.0, 8.5], [46.8, 13.1], [41.2, 13.1]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Poly { + pts: &[[46.0, 18.0], [46.0, 31.5], [49.6, 28.26], [52.12, 34.2], [54.46, 33.12], [51.94, 27.36], [56.62, 27.18]], + closed: true, + fill: Some(P { ink: Ink::Text, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Ground, a: 1.0, w: 0.99, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [76.0, 14.0, 30.0, 14.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [91.0, 24.0], size: 6.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "+18 mm", bold: true }, + ], +}; + +pub(super) const FRAME_RATE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [26.0, 12.0, 68.0, 40.0], + radius: 6.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [60.0, 31.0], size: 10.0, anchor: 1, ink: Ink::Text, a: 1.0, s: "60 fps", bold: true }, + Op::Poly { + pts: &[ + [34.0, 39.0], + [39.0, 42.0], + [43.0, 42.0], + [48.0, 39.0], + [52.0, 42.0], + [57.0, 42.0], + [62.0, 39.0], + [66.0, 42.0], + [71.0, 42.0], + [75.0, 39.0], + [80.0, 42.0], + [85.0, 42.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.3, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const HISTORY_BOTTOM: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 156.0, 92.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 66.5], [142.0, 74.0], [142.0, 89.0], [129.01, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 66.5], [142.0, 74.0], [142.0, 89.0], [154.99, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 59.0], [154.99, 66.5], [142.0, 74.0], [129.01, 66.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 122.0, 214.0, 20.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [42.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [72.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [102.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [132.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [162.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + ], +}; + +pub(super) const HISTORY_IN_BROWSER: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 118.0, 40.0, 16.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 156.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 78.5], [142.0, 86.0], [142.0, 101.0], [129.01, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 78.5], [142.0, 86.0], [142.0, 101.0], [154.99, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 71.0], [154.99, 78.5], [142.0, 86.0], [129.01, 78.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const HISTORY_LEFT: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 20.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [90.0, 26.0, 130.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.01, 78.5], [155.0, 86.0], [155.0, 101.0], [142.01, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[167.99, 78.5], [155.0, 86.0], [155.0, 101.0], [167.99, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[155.0, 71.0], [167.99, 78.5], [155.0, 86.0], [142.01, 78.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const HISTORY_UNDER_BROWSER: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 86.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [6.0, 116.0, 52.0, 26.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [64.0, 26.0, 156.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 78.5], [142.0, 86.0], [142.0, 101.0], [129.01, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 78.5], [142.0, 86.0], [142.0, 101.0], [154.99, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 71.0], [154.99, 78.5], [142.0, 86.0], [129.01, 78.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const LAYOUT_SCHEMATIC: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 156.0, 92.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 66.5], [142.0, 74.0], [142.0, 89.0], [129.01, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 66.5], [142.0, 74.0], [142.0, 89.0], [154.99, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 59.0], [154.99, 66.5], [142.0, 74.0], [129.01, 66.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 122.0, 214.0, 20.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [42.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [72.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [102.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [132.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [162.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + ], +}; + +pub(super) const MEASURE_AXIS_DISTANCES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [20.0, 22.0, 46.0, 28.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[20.0, 14.0], [66.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[20.0, 10.0], [20.0, 18.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 10.0], [66.0, 18.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [43.0, 9.0], size: 7.0, anchor: 1, ink: Ink::Accent, a: 1.0, s: "X 46", bold: true }, + Op::Poly { + pts: &[[76.0, 22.0], [76.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 22.0], [80.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 50.0], [80.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [98.0, 39.0], size: 7.0, anchor: 1, ink: Ink::Accent, a: 1.0, s: "Y 28", bold: true }, + ], +}; + +pub(super) const MOUSE_MAPPING: Figure = Figure { + size: [96.0, 120.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 96.0, 120.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [26.0, 14.0, 44.0, 86.0], + radius: 22.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[26.0, 56.0], [70.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 14.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [43.0, 24.0, 10.0, 20.0], radius: 5.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[ + [26.0, 56.0], + [25.538, 54.028], + [25.259, 52.023], + [25.166, 50.0], + [25.259, 47.977], + [25.538, 45.972], + [26.0, 44.0], + [26.0, 36.0], + [26.423, 31.708], + [27.675, 27.581], + [29.708, 23.777], + [32.444, 20.444], + [35.777, 17.708], + [39.581, 15.675], + [43.708, 14.423], + [48.0, 14.0], + [48.0, 56.0], + ], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.0 }), + grad: None, + line: None, + }, + Op::Text { at: [36.0, 44.0], size: 8.0, anchor: 1, ink: Ink::Dim, a: 1.0, s: "L", bold: true }, + Op::Text { at: [60.0, 44.0], size: 8.0, anchor: 1, ink: Ink::Dim, a: 1.0, s: "R", bold: true }, + Op::Text { at: [48.0, 20.0], size: 7.0, anchor: 1, ink: Ink::Accent, a: 1.0, s: "M", bold: true }, + ], +}; + +pub(super) const NAVIGATOR_AXES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Circle { + c: [60.0, 32.0, 30.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 32.0, 26.0], fill: None, line: Some(L { ink: Ink::Line, a: 0.6, w: 0.6, dash: [1.5, 3.0], round: false }) }, + Op::Poly { + pts: &[[60.0, 32.0], [76.0, 22.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisY, a: 0.55, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [44.0, 22.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisX, a: 0.55, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [60.0, 50.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisZ, a: 0.55, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [44.0, 41.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisY, a: 1.0, w: 3.4, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [76.0, 41.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisX, a: 1.0, w: 3.4, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [60.0, 13.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisZ, a: 1.0, w: 3.4, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [60.0, 32.0, 3.2], fill: Some(P { ink: Ink::Dim, a: 1.0 }), line: None }, + Op::Circle { + c: [60.0, 13.5, 8.2], + fill: Some(P { ink: Ink::AxisZ, a: 1.0 }), + line: Some(L { ink: Ink::AxisZ, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [60.0, 17.0], size: 10.0, anchor: 1, ink: Ink::White, a: 1.0, s: "Z", bold: true }, + Op::Circle { + c: [76.0, 41.2, 8.2], + fill: Some(P { ink: Ink::AxisX, a: 1.0 }), + line: Some(L { ink: Ink::AxisX, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [76.0, 44.8], size: 10.0, anchor: 1, ink: Ink::White, a: 1.0, s: "X", bold: true }, + Op::Circle { + c: [44.0, 41.2, 8.2], + fill: Some(P { ink: Ink::AxisY, a: 1.0 }), + line: Some(L { ink: Ink::AxisY, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [44.0, 44.8], size: 10.0, anchor: 1, ink: Ink::White, a: 1.0, s: "Y", bold: true }, + Op::Circle { + c: [60.0, 50.5, 5.6], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::AxisZ, a: 1.0, w: 2.2, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [44.0, 22.8, 5.6], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::AxisX, a: 1.0, w: 2.2, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [76.0, 22.8, 5.6], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::AxisY, a: 1.0, w: 2.2, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const NAVIGATOR_CUBE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Poly { + pts: &[ + [82.2, 60.0], + [81.773, 60.624], + [80.51, 61.225], + [78.459, 61.778], + [75.698, 62.263], + [72.334, 62.661], + [68.496, 62.956], + [64.331, 63.139], + [60.0, 63.2], + [55.669, 63.139], + [51.504, 62.956], + [47.666, 62.661], + [44.302, 62.263], + [41.541, 61.778], + [39.49, 61.225], + [38.227, 60.624], + [37.8, 60.0], + [38.227, 59.376], + [39.49, 58.775], + [41.541, 58.222], + [44.302, 57.737], + [47.666, 57.339], + [51.504, 57.044], + [55.669, 56.861], + [60.0, 56.8], + [64.331, 56.861], + [68.496, 57.044], + [72.334, 57.339], + [75.698, 57.737], + [78.459, 58.222], + [80.51, 58.775], + [81.773, 59.376], + ], + closed: true, + fill: Some(P { ink: Ink::Black, a: 0.12 }), + grad: None, + line: None, + }, + Op::Poly { + pts: &[[36.618, 18.5], [60.0, 32.0], [60.0, 59.0], [36.618, 45.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[83.382, 18.5], [60.0, 32.0], [60.0, 59.0], [83.382, 45.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 5.0], [83.382, 18.5], [60.0, 32.0], [36.618, 18.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 5.0], [83.382, 18.5], [60.0, 32.0], [36.618, 18.5]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 10.0], [75.4, 29.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::White, a: 0.5, w: 1.0, dash: [0.0, 0.0], round: true }), + }, + Op::Text { at: [57.402, 20.0], size: 8.375, anchor: 1, ink: Ink::Text, a: 1.0, s: "TOP", bold: true }, + Op::Text { at: [48.309, 41.15], size: 6.8, anchor: 1, ink: Ink::Text, a: 1.0, s: "FRONT", bold: true }, + Op::Text { at: [71.691, 41.15], size: 6.8, anchor: 1, ink: Ink::Text, a: 1.0, s: "RIGHT", bold: true }, + ], +}; + +pub(super) const ORBIT_CENTRE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [8.0, 5.0, 104.0, 54.0], + radius: 5.0, + fill: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 5.0], [60.0, 11.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 53.0], [60.0, 59.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[8.0, 32.0], [14.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[106.0, 32.0], [112.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [28.0, 32.0], + [28.615, 30.244], + [30.436, 28.556], + [33.393, 27.0], + [37.373, 25.636], + [42.222, 24.517], + [47.754, 23.685], + [53.757, 23.173], + [60.0, 23.0], + [66.243, 23.173], + [72.246, 23.685], + [77.778, 24.517], + [82.627, 25.636], + [86.607, 27.0], + [89.564, 28.556], + [91.385, 30.244], + [92.0, 32.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.6, w: 1.2, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[28.144, 25.0], [42.0, 33.0], [42.0, 49.0], [28.144, 41.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[55.856, 25.0], [42.0, 33.0], [42.0, 49.0], [55.856, 41.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 17.0], [55.856, 25.0], [42.0, 33.0], [28.144, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [28.0, 32.0], + [28.615, 33.756], + [30.436, 35.444], + [33.393, 37.0], + [37.373, 38.364], + [42.222, 39.483], + [47.754, 40.315], + [53.757, 40.827], + [60.0, 41.0], + [66.243, 40.827], + [72.246, 40.315], + [77.778, 39.483], + [82.627, 38.364], + [86.607, 37.0], + [89.564, 35.444], + [91.385, 33.756], + [92.0, 32.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[92.0, 26.5], [88.6, 32.8], [95.4, 32.8]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Circle { + c: [60.0, 32.0, 3.8], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 32.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + ], +}; + +pub(super) const ORBIT_CURSOR: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[ + [37.0, 29.0], + [37.615, 27.244], + [39.436, 25.556], + [42.393, 24.0], + [46.373, 22.636], + [51.222, 21.517], + [56.754, 20.685], + [62.757, 20.173], + [69.0, 20.0], + [75.243, 20.173], + [81.246, 20.685], + [86.778, 21.517], + [91.627, 22.636], + [95.607, 24.0], + [98.564, 25.556], + [100.385, 27.244], + [101.0, 29.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.6, w: 1.2, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[38.144, 24.0], [52.0, 32.0], [52.0, 48.0], [38.144, 40.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[65.856, 24.0], [52.0, 32.0], [52.0, 48.0], [65.856, 40.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[52.0, 16.0], [65.856, 24.0], [52.0, 32.0], [38.144, 24.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [37.0, 29.0], + [37.615, 30.756], + [39.436, 32.444], + [42.393, 34.0], + [46.373, 35.364], + [51.222, 36.483], + [56.754, 37.315], + [62.757, 37.827], + [69.0, 38.0], + [75.243, 37.827], + [81.246, 37.315], + [86.778, 36.483], + [91.627, 35.364], + [95.607, 34.0], + [98.564, 32.444], + [100.385, 30.756], + [101.0, 29.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[101.0, 23.5], [97.6, 29.8], [104.4, 29.8]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Circle { + c: [69.0, 29.0, 3.8], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [69.0, 29.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[70.5, 30.5], [70.5, 45.5], [74.5, 41.9], [77.3, 48.5], [79.9, 47.3], [77.1, 40.9], [82.3, 40.7]], + closed: true, + fill: Some(P { ink: Ink::Text, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const ORBIT_ORIGIN: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[60.0, 21.0], [94.0, 38.0], [60.0, 55.0], [26.0, 38.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 0.35 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[ + [28.0, 38.0], + [28.615, 36.244], + [30.436, 34.556], + [33.393, 33.0], + [37.373, 31.636], + [42.222, 30.517], + [47.754, 29.685], + [53.757, 29.173], + [60.0, 29.0], + [66.243, 29.173], + [72.246, 29.685], + [77.778, 30.517], + [82.627, 31.636], + [86.607, 33.0], + [89.564, 34.556], + [91.385, 36.244], + [92.0, 38.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.6, w: 1.2, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[46.144, 22.0], [60.0, 30.0], [60.0, 46.0], [46.144, 38.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[73.856, 22.0], [60.0, 30.0], [60.0, 46.0], [73.856, 38.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 14.0], [73.856, 22.0], [60.0, 30.0], [46.144, 22.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [28.0, 38.0], + [28.615, 39.756], + [30.436, 41.444], + [33.393, 43.0], + [37.373, 44.364], + [42.222, 45.483], + [47.754, 46.315], + [53.757, 46.827], + [60.0, 47.0], + [66.243, 46.827], + [72.246, 46.315], + [77.778, 45.483], + [82.627, 44.364], + [86.607, 43.0], + [89.564, 41.444], + [91.385, 39.756], + [92.0, 38.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[92.0, 32.5], [88.6, 38.8], [95.4, 38.8]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Circle { + c: [60.0, 38.0, 3.8], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 38.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + ], +}; + +pub(super) const QUICK_MEASURE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[34.742, 29.5], [46.0, 36.0], [46.0, 49.0], [34.742, 42.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[57.258, 29.5], [46.0, 36.0], [46.0, 49.0], [57.258, 42.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[46.0, 23.0], [57.258, 29.5], [46.0, 36.0], [34.742, 29.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 22.0], [75.0, 13.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 22.0, 1.8], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [75.0, 13.5, 1.8], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { + r: [78.0, 22.0, 34.0, 15.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [95.0, 32.5], size: 7.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "12.5 mm", bold: true }, + ], +}; + +pub(super) const SELECT_BODIES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[44.412, 25.0], [60.0, 34.0], [60.0, 52.0], [44.412, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.412, 25.0], [60.0, 34.0], [60.0, 52.0], [44.412, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[75.588, 25.0], [60.0, 34.0], [60.0, 52.0], [75.588, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[75.588, 25.0], [60.0, 34.0], [60.0, 52.0], [75.588, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [75.588, 25.0], [60.0, 34.0], [44.412, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [75.588, 25.0], [60.0, 34.0], [44.412, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const SELECT_FACES_EDGES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[44.412, 25.0], [60.0, 34.0], [60.0, 52.0], [44.412, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[75.588, 25.0], [60.0, 34.0], [60.0, 52.0], [75.588, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [75.588, 25.0], [60.0, 34.0], [44.412, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [75.588, 25.0], [60.0, 34.0], [44.412, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const SKETCH_CONFLICT: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[ + [14.0, 46.0], + [18.637, 39.672], + [23.531, 34.188], + [28.66, 29.547], + [34.0, 25.75], + [39.527, 22.797], + [45.219, 20.688], + [51.051, 19.422], + [57.0, 19.0], + [63.043, 19.422], + [69.156, 20.688], + [75.316, 22.797], + [81.5, 25.75], + [87.684, 29.547], + [93.844, 34.188], + [99.957, 39.672], + [106.0, 46.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Note, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[14.0, 16.0], [106.0, 46.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Note, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 31.0, 4.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Note, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[14.0, 54.0], [106.0, 54.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [3.0, 3.0], round: false }), + }, + ], +}; + +pub(super) const SKETCH_EXIT_KEEP: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [7.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[7.0, 12.0], [37.0, 12.0], [37.0, 42.0], [7.0, 42.0]]), + Op::Poly { + pts: &[[15.505, 24.25], [22.0, 28.0], [22.0, 35.5], [15.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[28.495, 24.25], [22.0, 28.0], [22.0, 35.5], [28.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[22.0, 20.5], [28.495, 24.25], [22.0, 28.0], [15.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Rect { + r: [45.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[45.0, 12.0], [75.0, 12.0], [75.0, 42.0], [45.0, 42.0]]), + Op::Rect { + r: [53.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[49.0, 27.0], [71.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [60.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Poly { + pts: &[[37.5, 24.0], [41.5, 27.0], [37.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[75.5, 24.0], [79.5, 27.0], [75.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { + r: [83.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[83.0, 12.0], [113.0, 12.0], [113.0, 42.0], [83.0, 42.0]]), + Op::Rect { + r: [91.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[87.0, 27.0], [109.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[98.0, 16.0], [98.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Text { at: [22.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "before", bold: false }, + Op::Text { at: [60.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "sketch", bold: false }, + Op::Text { at: [98.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "after", bold: true }, + ], +}; + +pub(super) const SKETCH_EXIT_PREVIOUS: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [7.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[7.0, 12.0], [37.0, 12.0], [37.0, 42.0], [7.0, 42.0]]), + Op::Poly { + pts: &[[15.505, 24.25], [22.0, 28.0], [22.0, 35.5], [15.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[28.495, 24.25], [22.0, 28.0], [22.0, 35.5], [28.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[22.0, 20.5], [28.495, 24.25], [22.0, 28.0], [15.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Rect { + r: [45.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[45.0, 12.0], [75.0, 12.0], [75.0, 42.0], [45.0, 42.0]]), + Op::Rect { + r: [53.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[49.0, 27.0], [71.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [60.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Poly { + pts: &[[37.5, 24.0], [41.5, 27.0], [37.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[75.5, 24.0], [79.5, 27.0], [75.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { + r: [83.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[83.0, 12.0], [113.0, 12.0], [113.0, 42.0], [83.0, 42.0]]), + Op::Poly { + pts: &[[91.505, 24.25], [98.0, 28.0], [98.0, 35.5], [91.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[104.495, 24.25], [98.0, 28.0], [98.0, 35.5], [104.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[98.0, 20.5], [104.495, 24.25], [98.0, 28.0], [91.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Text { at: [22.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "before", bold: false }, + Op::Text { at: [60.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "sketch", bold: false }, + Op::Text { at: [98.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "after", bold: true }, + ], +}; + +pub(super) const SKETCH_EXIT_UNLESS_TURNED: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [7.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[7.0, 12.0], [37.0, 12.0], [37.0, 42.0], [7.0, 42.0]]), + Op::Poly { + pts: &[[15.505, 24.25], [22.0, 28.0], [22.0, 35.5], [15.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[28.495, 24.25], [22.0, 28.0], [22.0, 35.5], [28.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[22.0, 20.5], [28.495, 24.25], [22.0, 28.0], [15.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Rect { + r: [45.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[45.0, 12.0], [75.0, 12.0], [75.0, 42.0], [45.0, 42.0]]), + Op::Rect { + r: [53.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[49.0, 27.0], [71.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [60.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Poly { + pts: &[[37.5, 24.0], [41.5, 27.0], [37.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[75.5, 24.0], [79.5, 27.0], [75.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { r: [83.0, 12.0, 30.0, 30.0], radius: 4.0, fill: Some(P { ink: Ink::Top, a: 0.45 }), line: None }, + Op::Clip(&[[83.0, 12.0], [113.0, 12.0], [113.0, 42.0], [83.0, 42.0]]), + Op::Clip(&[[83.0, 12.0], [113.0, 12.0], [83.0, 42.0]]), + Op::Poly { + pts: &[[91.505, 24.25], [98.0, 28.0], [98.0, 35.5], [91.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[104.495, 24.25], [98.0, 28.0], [98.0, 35.5], [104.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[98.0, 20.5], [104.495, 24.25], [98.0, 28.0], [91.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Clip(&[[113.0, 12.0], [113.0, 42.0], [83.0, 42.0]]), + Op::Rect { + r: [91.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[87.0, 27.0], [109.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[98.0, 16.0], [98.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Poly { + pts: &[[113.0, 12.0], [83.0, 42.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [2.0, 2.0], round: false }), + }, + Op::Unclip, + Op::Rect { + r: [83.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [22.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "before", bold: false }, + Op::Text { at: [60.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "sketch", bold: false }, + Op::Text { at: [98.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "after", bold: true }, + ], +}; + +pub(super) const SKETCH_GUIDES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [20.0, 16.0, 44.0, 30.0], + radius: 0.0, + fill: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 6.0], [42.0, 58.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 31.0], [114.0, 31.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Circle { c: [42.0, 31.0, 3.0], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { + c: [90.0, 31.0, 3.4], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 24.0], [90.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[83.0, 31.0], [97.0, 31.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const SKETCH_HIDE_GLYPHS: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[12.0, 44.0], [108.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [18.0, 20.0, 14.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [42.0, 12.0, 14.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 0.8 }), + line: Some(L { ink: Ink::Line, a: 0.8, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [66.0, 20.0, 14.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 0.6 }), + line: Some(L { ink: Ink::Line, a: 0.6, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [90.0, 12.0, 14.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 0.4 }), + line: Some(L { ink: Ink::Line, a: 0.4, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const SKETCH_STATE_ICONS: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [13.0, 21.0, 22.0, 22.0], + radius: 5.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Ok, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [18.0, 38.0], + [19.0, 35.5], + [20.0, 33.333], + [21.0, 31.5], + [22.0, 30.0], + [23.0, 28.833], + [24.0, 28.0], + [25.0, 27.5], + [26.0, 27.333], + [27.0, 27.5], + [28.0, 28.0], + [29.0, 28.833], + [30.0, 30.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Ok, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [30.0, 30.0, 1.8], fill: Some(P { ink: Ink::Ok, a: 1.0 }), line: None }, + Op::Rect { + r: [49.0, 21.0, 22.0, 22.0], + radius: 5.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Warn, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [54.0, 38.0], + [55.0, 35.5], + [56.0, 33.333], + [57.0, 31.5], + [58.0, 30.0], + [59.0, 28.833], + [60.0, 28.0], + [61.0, 27.5], + [62.0, 27.333], + [63.0, 27.5], + [64.0, 28.0], + [65.0, 28.833], + [66.0, 30.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Warn, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [66.0, 30.0, 1.8], fill: Some(P { ink: Ink::Warn, a: 1.0 }), line: None }, + Op::Rect { + r: [85.0, 21.0, 22.0, 22.0], + radius: 5.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Note, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [90.0, 38.0], + [91.0, 35.5], + [92.0, 33.333], + [93.0, 31.5], + [94.0, 30.0], + [95.0, 28.833], + [96.0, 28.0], + [97.0, 27.5], + [98.0, 27.333], + [99.0, 27.5], + [100.0, 28.0], + [101.0, 28.833], + [102.0, 30.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Note, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [102.0, 30.0, 1.8], fill: Some(P { ink: Ink::Note, a: 1.0 }), line: None }, + ], +}; + +pub(super) const TESS_COARSE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 21.0], fill: None, line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.9, dash: [2.0, 2.5], round: false }) }, + Op::Poly { + pts: &[[60.0, 11.0], [74.8, 17.2], [81.0, 32.0], [74.8, 46.8], [60.0, 53.0], [45.2, 46.8], [39.0, 32.0], [45.2, 17.2]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 11.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [74.8, 17.2, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [81.0, 32.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [74.8, 46.8, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 53.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [45.2, 46.8, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [39.0, 32.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [45.2, 17.2, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Text { at: [112.0, 60.0], size: 7.0, anchor: 2, ink: Ink::Dim, a: 1.0, s: "8", bold: false }, + ], +}; + +pub(super) const TESS_FINE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 21.0], fill: None, line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.9, dash: [2.0, 2.5], round: false }) }, + Op::Poly { + pts: &[ + [60.0, 11.0], + [64.1, 11.4], + [68.0, 12.6], + [71.7, 14.5], + [74.8, 17.2], + [77.5, 20.3], + [79.4, 24.0], + [80.6, 27.9], + [81.0, 32.0], + [80.6, 36.1], + [79.4, 40.0], + [77.5, 43.7], + [74.8, 46.8], + [71.7, 49.5], + [68.0, 51.4], + [64.1, 52.6], + [60.0, 53.0], + [55.9, 52.6], + [52.0, 51.4], + [48.3, 49.5], + [45.2, 46.8], + [42.5, 43.7], + [40.6, 40.0], + [39.4, 36.1], + [39.0, 32.0], + [39.4, 27.9], + [40.6, 24.0], + [42.5, 20.3], + [45.2, 17.2], + [48.3, 14.5], + [52.0, 12.6], + [55.9, 11.4], + ], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [112.0, 60.0], size: 7.0, anchor: 2, ink: Ink::Dim, a: 1.0, s: "32", bold: false }, + ], +}; + +pub(super) const TESS_NORMAL: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 21.0], fill: None, line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.9, dash: [2.0, 2.5], round: false }) }, + Op::Poly { + pts: &[ + [60.0, 11.0], + [68.0, 12.6], + [74.8, 17.2], + [79.4, 24.0], + [81.0, 32.0], + [79.4, 40.0], + [74.8, 46.8], + [68.0, 51.4], + [60.0, 53.0], + [52.0, 51.4], + [45.2, 46.8], + [40.6, 40.0], + [39.0, 32.0], + [40.6, 24.0], + [45.2, 17.2], + [52.0, 12.6], + ], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 11.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [68.0, 12.6, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [74.8, 17.2, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [79.4, 24.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [81.0, 32.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [79.4, 40.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [74.8, 46.8, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [68.0, 51.4, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 53.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [52.0, 51.4, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [45.2, 46.8, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [40.6, 40.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [39.0, 32.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [40.6, 24.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [45.2, 17.2, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [52.0, 12.6, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Text { at: [112.0, 60.0], size: 7.0, anchor: 2, ink: Ink::Dim, a: 1.0, s: "16", bold: false }, + ], +}; + +pub(super) const TESS_ULTRA: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 21.0], fill: None, line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.9, dash: [2.0, 2.5], round: false }) }, + Op::Poly { + pts: &[ + [60.0, 11.0], + [62.1, 11.1], + [64.1, 11.4], + [66.1, 11.9], + [68.0, 12.6], + [69.9, 13.5], + [71.7, 14.5], + [73.3, 15.8], + [74.8, 17.2], + [76.2, 18.7], + [77.5, 20.3], + [78.5, 22.1], + [79.4, 24.0], + [80.1, 25.9], + [80.6, 27.9], + [80.9, 29.9], + [81.0, 32.0], + [80.9, 34.1], + [80.6, 36.1], + [80.1, 38.1], + [79.4, 40.0], + [78.5, 41.9], + [77.5, 43.7], + [76.2, 45.3], + [74.8, 46.8], + [73.3, 48.2], + [71.7, 49.5], + [69.9, 50.5], + [68.0, 51.4], + [66.1, 52.1], + [64.1, 52.6], + [62.1, 52.9], + [60.0, 53.0], + [57.9, 52.9], + [55.9, 52.6], + [53.9, 52.1], + [52.0, 51.4], + [50.1, 50.5], + [48.3, 49.5], + [46.7, 48.2], + [45.2, 46.8], + [43.8, 45.3], + [42.5, 43.7], + [41.5, 41.9], + [40.6, 40.0], + [39.9, 38.1], + [39.4, 36.1], + [39.1, 34.1], + [39.0, 32.0], + [39.1, 29.9], + [39.4, 27.9], + [39.9, 25.9], + [40.6, 24.0], + [41.5, 22.1], + [42.5, 20.3], + [43.8, 18.7], + [45.2, 17.2], + [46.7, 15.8], + [48.3, 14.5], + [50.1, 13.5], + [52.0, 12.6], + [53.9, 11.9], + [55.9, 11.4], + [57.9, 11.1], + ], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [112.0, 60.0], size: 7.0, anchor: 2, ink: Ink::Dim, a: 1.0, s: "64", bold: false }, + ], +}; + +pub(super) const TOOL_CURSOR: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[10.0, 46.0], [13.4, 42.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.028, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[13.4, 42.8], [16.8, 39.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.083, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[16.8, 39.6], [20.2, 36.4]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.138, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[20.2, 36.4], [23.6, 33.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.193, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[23.6, 33.2], [27.0, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.248, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[27.0, 30.0], [30.4, 26.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.303, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[30.4, 26.8], [33.8, 23.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.357, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[33.8, 23.6], [37.2, 20.4]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.413, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[37.2, 20.4], [40.6, 17.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.468, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[40.6, 17.2], [44.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.522, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { + r: [55.5, 28.0, 22.0, 22.0], + radius: 6.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[61.0, 44.5], [72.0, 33.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { + c: [61.0, 44.5, 2.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [72.0, 33.5, 2.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[43.5, 13.5], [43.5, 33.0], [48.7, 28.32], [52.34, 36.9], [55.72, 35.34], [52.08, 27.02], [58.84, 26.76]], + closed: true, + fill: Some(P { ink: Ink::Text, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.43, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const TOOL_EXTRUDE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [20.0, 40.0, 40.0, 14.0], + radius: 2.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[40.0, 38.0], [40.0, 18.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[40.0, 14.0], [42.5, 18.2], [37.5, 18.2]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Poly { + pts: &[[12.0, 10.0], [108.0, 10.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Rect { + r: [76.0, 6.0, 28.0, 8.0], + radius: 0.0, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const TOOL_HOLE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [26.0, 8.0, 68.0, 48.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 32.0, 10.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 32.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [26.0, 32.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [94.0, 32.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 8.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 56.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + ], +}; + +pub(super) const TOOL_PLACEMENT: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [22.0, 10.0, 76.0, 44.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 32.0, 13.0], fill: None, line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }) }, + Op::Poly { + pts: &[ + [60.0, 19.0], + [62.536, 19.25], + [64.975, 19.99], + [67.222, 21.191], + [69.192, 22.808], + [70.809, 24.778], + [72.01, 27.025], + [72.75, 29.464], + [73.0, 32.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.4, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { r: [55.0, 27.0, 10.0, 10.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + ], +}; + +pub(super) const VERTEX_MARKERS: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[46.144, 26.0], [60.0, 34.0], [60.0, 50.0], [46.144, 42.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[73.856, 26.0], [60.0, 34.0], [60.0, 50.0], [73.856, 42.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 18.0], [73.856, 26.0], [60.0, 34.0], [46.144, 26.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 18.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [73.9, 26.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [73.9, 42.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 50.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [46.1, 42.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [46.1, 26.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 34.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const VIEW_ANGLES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[38.0, 44.0], [38.0, 28.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisZ, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[38.0, 24.0], [40.8, 28.6], [35.2, 28.6]], + closed: true, + fill: Some(P { ink: Ink::AxisZ, a: 1.0 }), + grad: None, + line: None, + }, + Op::Text { at: [38.0, 20.5], size: 7.5, anchor: 1, ink: Ink::AxisZ, a: 1.0, s: "Z", bold: true }, + Op::Poly { + pts: &[[38.0, 44.0], [52.2, 52.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisX, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[55.3, 54.0], [51.1, 54.1], [53.3, 50.3]], + closed: true, + fill: Some(P { ink: Ink::AxisX, a: 1.0 }), + grad: None, + line: None, + }, + Op::Text { at: [60.516, 59.5], size: 7.5, anchor: 1, ink: Ink::AxisX, a: 1.0, s: "X", bold: true }, + Op::Poly { + pts: &[[38.0, 44.0], [23.8, 52.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisY, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[20.7, 54.0], [22.7, 50.3], [24.9, 54.1]], + closed: true, + fill: Some(P { ink: Ink::AxisY, a: 1.0 }), + grad: None, + line: None, + }, + Op::Text { at: [15.484, 59.5], size: 7.5, anchor: 1, ink: Ink::AxisY, a: 1.0, s: "Y", bold: true }, + Op::Text { at: [94.0, 30.0], size: 7.5, anchor: 0, ink: Ink::Text, a: 1.0, s: "45°", bold: false }, + Op::Text { at: [94.0, 41.0], size: 7.5, anchor: 0, ink: Ink::Text, a: 1.0, s: "35°", bold: false }, + Op::Text { at: [94.0, 52.0], size: 7.5, anchor: 0, ink: Ink::Text, a: 1.0, s: "0°", bold: false }, + ], +}; + +pub(super) const VIEW_GRID: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[60.0, 13.4], [22.6, 35.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.7, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 13.4], [97.4, 35.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.7, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.2, 17.0], [28.8, 38.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[53.8, 17.0], [91.2, 38.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.5, 20.6], [35.1, 42.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[47.5, 20.6], [84.9, 42.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.7, 24.2], [41.3, 45.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[41.3, 24.2], [78.7, 45.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.9, 27.8], [47.5, 49.4]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[35.1, 27.8], [72.5, 49.4]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[91.2, 31.4], [53.8, 53.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[28.8, 31.4], [66.2, 53.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[97.4, 35.0], [60.0, 56.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.7, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[22.6, 35.0], [60.0, 56.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.7, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[49.608, 23.0], [60.0, 29.0], [60.0, 41.0], [49.608, 35.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[70.392, 23.0], [60.0, 29.0], [60.0, 41.0], [70.392, 35.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 17.0], [70.392, 23.0], [60.0, 29.0], [49.608, 23.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const VIEW_PERSPECTIVE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[30.0, 52.0], [42.0, 24.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 52.0], [78.0, 24.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 52.0], [90.0, 52.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 24.0], [78.0, 24.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 52.0], [60.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.8, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 52.0], [60.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.8, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Circle { + c: [60.0, 8.0, 3.2], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 8.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + ], +}; + +pub(super) const VIEW_SHADOW: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Glow { c: [62.0, 44.0, 26.0, 8.0], a: 0.5 }, + Op::Poly { + pts: &[[48.742, 23.5], [60.0, 30.0], [60.0, 43.0], [48.742, 36.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[71.258, 23.5], [60.0, 30.0], [60.0, 43.0], [71.258, 36.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 17.0], [71.258, 23.5], [60.0, 30.0], [48.742, 23.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const THEME_THUMBNAIL: Figure = Figure { + size: [124.0, 76.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 124.0, 76.0], radius: 0.0, fill: Some(P { ink: Ink::Slot(0), a: 1.0 }), line: None }, + Op::Rect { r: [0.0, 0.0, 124.0, 14.0], radius: 0.0, fill: Some(P { ink: Ink::Slot(1), a: 1.0 }), line: None }, + Op::Circle { c: [6.0, 7.0, 1.8], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [12.0, 7.0, 1.8], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 4.0, 14.0, 6.0], radius: 3.0, fill: Some(P { ink: Ink::Slot(3), a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 5.0, 12.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Slot(2), a: 0.7 }), line: None }, + Op::Rect { r: [58.0, 5.0, 12.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Slot(2), a: 0.7 }), line: None }, + Op::Rect { r: [102.0, 3.5, 16.0, 7.0], radius: 3.5, fill: Some(P { ink: Ink::Slot(3), a: 1.0 }), line: None }, + Op::Rect { r: [0.0, 14.0, 35.0, 62.0], radius: 0.0, fill: Some(P { ink: Ink::Slot(1), a: 1.0 }), line: None }, + Op::Rect { r: [3.0, 30.0, 30.0, 8.0], radius: 2.0, fill: Some(P { ink: Ink::Slot(3), a: 0.25 }), line: None }, + Op::Circle { c: [8.0, 26.0, 1.6], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 24.5, 16.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Slot(2), a: 0.8 }), line: None }, + Op::Circle { c: [8.0, 34.0, 1.6], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 32.5, 12.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Slot(2), a: 0.8 }), line: None }, + Op::Circle { c: [8.0, 42.0, 1.6], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 40.5, 17.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Slot(2), a: 0.8 }), line: None }, + Op::Circle { c: [8.0, 50.0, 1.6], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 48.5, 11.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Slot(2), a: 0.8 }), line: None }, + Op::Poly { + pts: &[ + [117.0, 17.0], + [118.035, 17.136], + [119.0, 17.536], + [119.828, 18.172], + [120.464, 19.0], + [120.864, 19.965], + [121.0, 21.0], + [121.0, 69.0], + [120.864, 70.035], + [120.464, 71.0], + [119.828, 71.828], + [119.0, 72.464], + [118.035, 72.864], + [117.0, 73.0], + [42.0, 73.0], + [40.965, 72.864], + [40.0, 72.464], + [39.172, 71.828], + [38.536, 71.0], + [38.136, 70.035], + [38.0, 69.0], + [38.0, 21.0], + [38.136, 19.965], + [38.536, 19.0], + [39.172, 18.172], + [40.0, 17.536], + [40.965, 17.136], + [42.0, 17.0], + ], + closed: true, + fill: None, + grad: Some(G { top: Ink::Slot(4), bottom: Ink::Slot(5), y: [17.0, 73.0] }), + line: None, + }, + Op::Poly { + pts: &[[44.0, 67.0], [115.0, 67.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 60.0], [115.0, 60.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 53.0], [115.0, 53.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 46.0], [115.0, 46.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 39.0], [115.0, 39.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[79.5, 28.0], [92.49, 35.5], [92.49, 50.5], [79.5, 58.0], [66.51, 50.5], [66.51, 35.5]], + closed: true, + fill: None, + grad: None, + line: None, + }, + Op::Poly { + pts: &[[79.5, 28.0], [92.49, 35.5], [79.5, 43.0], [66.51, 35.5]], + closed: true, + fill: Some(P { ink: Ink::Slot(7), a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Slot(8), a: 1.0, w: 0.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.51, 35.5], [79.5, 43.0], [79.5, 58.0], [66.51, 50.5]], + closed: true, + fill: Some(P { ink: Ink::Slot(9), a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Slot(8), a: 1.0, w: 0.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[92.49, 35.5], [79.5, 43.0], [79.5, 58.0], [92.49, 50.5]], + closed: true, + fill: Some(P { ink: Ink::Slot(10), a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Slot(8), a: 1.0, w: 0.8, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [65.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [72.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [79.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [86.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [93.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { + r: [0.5, 0.5, 123.0, 75.0], + radius: 5.5, + fill: None, + line: Some(L { ink: Ink::Slot(11), a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +// Theme thumbnail slots (light, dark, gruvbox, imported sample colours): +// 0: #F4F6F9 #2A2F3A #282828 #2B2F52 +// 1: #FFFFFF #323845 #3C3836 #3B4170 +// 2: #9AA7B6 #6C7689 #7C6F64 #9CA3DE +// 3: #236EAD #8CBEF5 #83A598 #B6A6FF +// 4: #EEF1F5 #3A4150 #32302F #6A5AC8 +// 5: #D9DFE7 #252A34 #1D2021 #2E5A9E +// 6: #7B8798 #99A5BA #EBDBB2 #FFFFFF +// 7: #FFFFFF #7E8AA0 #D5C4A1 #E7E1FF +// 8: #7B8798 #99A5BA #EBDBB2 None +// 9: #C3CBD6 #566176 #A89984 #9C8FE8 +// 10: #A8B3C1 #3F485A #7C6F64 #6E8FE0 +// 11: #C9D1DB #454D5E #504945 #6E76B8 + +use super::preferences_figure_ops::paint; +use egui::{Painter, Rect}; + +/// The `aa-2x` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_aa_2x(p: &Painter, rect: Rect) { + paint(p, rect, &AA_2X, None, None); +} + +/// The `aa-4x` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_aa_4x(p: &Painter, rect: Rect) { + paint(p, rect, &AA_4X, None, None); +} + +/// The `aa-8x` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_aa_8x(p: &Painter, rect: Rect) { + paint(p, rect, &AA_8X, None, None); +} + +/// The `aa-off` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_aa_off(p: &Painter, rect: Rect) { + paint(p, rect, &AA_OFF, None, None); +} + +/// The `agent-pointer-speed` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_agent_pointer_speed(p: &Painter, rect: Rect) { + paint(p, rect, &AGENT_POINTER_SPEED, None, None); +} + +/// The `ao-on` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_ao_on(p: &Painter, rect: Rect) { + paint(p, rect, &AO_ON, None, None); +} + +/// The `assembly-move` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_assembly_move(p: &Painter, rect: Rect) { + paint(p, rect, &ASSEMBLY_MOVE, None, None); +} + +/// The `browser-card` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_browser_card(p: &Painter, rect: Rect) { + paint(p, rect, &BROWSER_CARD, None, None); +} + +/// The `browser-column` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_browser_column(p: &Painter, rect: Rect) { + paint(p, rect, &BROWSER_COLUMN, None, None); +} + +/// The `colour-vision-axes` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_axes(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_AXES, None, None); +} + +/// The `colour-vision-bends` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_bends(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_BENDS, None, None); +} + +/// The `colour-vision-draft` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_draft(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_DRAFT, None, None); +} + +/// The `colour-vision-failed` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_failed(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_FAILED, None, None); +} + +/// The `colour-vision-fixed` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_fixed(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_FIXED, None, None); +} + +/// The `colour-vision-projected` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_projected(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_PROJECTED, None, None); +} + +/// The `direct-interaction` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_direct_interaction(p: &Painter, rect: Rect) { + paint(p, rect, &DIRECT_INTERACTION, None, None); +} + +/// The `frame-rate` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_frame_rate(p: &Painter, rect: Rect) { + paint(p, rect, &FRAME_RATE, None, None); +} + +/// The `history-bottom` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_history_bottom(p: &Painter, rect: Rect) { + paint(p, rect, &HISTORY_BOTTOM, None, None); +} + +/// The `history-in-browser` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_history_in_browser(p: &Painter, rect: Rect) { + paint(p, rect, &HISTORY_IN_BROWSER, None, None); +} + +/// The `history-left` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_history_left(p: &Painter, rect: Rect) { + paint(p, rect, &HISTORY_LEFT, None, None); +} + +/// The `history-under-browser` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_history_under_browser(p: &Painter, rect: Rect) { + paint(p, rect, &HISTORY_UNDER_BROWSER, None, None); +} + +/// The `layout-schematic` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_layout_schematic(p: &Painter, rect: Rect) { + paint(p, rect, &LAYOUT_SCHEMATIC, None, None); +} + +/// The `measure-axis-distances` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_measure_axis_distances(p: &Painter, rect: Rect) { + paint(p, rect, &MEASURE_AXIS_DISTANCES, None, None); +} + +/// The `mouse-mapping` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_mouse_mapping(p: &Painter, rect: Rect) { + paint(p, rect, &MOUSE_MAPPING, None, None); +} + +/// The `navigator-axes` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_navigator_axes(p: &Painter, rect: Rect) { + paint(p, rect, &NAVIGATOR_AXES, None, None); +} + +/// The `navigator-cube` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_navigator_cube(p: &Painter, rect: Rect) { + paint(p, rect, &NAVIGATOR_CUBE, None, None); +} + +/// The `orbit-centre` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_orbit_centre(p: &Painter, rect: Rect) { + paint(p, rect, &ORBIT_CENTRE, None, None); +} + +/// The `orbit-cursor` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_orbit_cursor(p: &Painter, rect: Rect) { + paint(p, rect, &ORBIT_CURSOR, None, None); +} + +/// The `orbit-origin` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_orbit_origin(p: &Painter, rect: Rect) { + paint(p, rect, &ORBIT_ORIGIN, None, None); +} + +/// The `quick-measure` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_quick_measure(p: &Painter, rect: Rect) { + paint(p, rect, &QUICK_MEASURE, None, None); +} + +/// The `select-bodies` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_select_bodies(p: &Painter, rect: Rect) { + paint(p, rect, &SELECT_BODIES, None, None); +} + +/// The `select-faces-edges` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_select_faces_edges(p: &Painter, rect: Rect) { + paint(p, rect, &SELECT_FACES_EDGES, None, None); +} + +/// The `sketch-conflict` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_conflict(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_CONFLICT, None, None); +} + +/// The `sketch-exit-keep` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_exit_keep(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_EXIT_KEEP, None, None); +} + +/// The `sketch-exit-previous` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_exit_previous(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_EXIT_PREVIOUS, None, None); +} + +/// The `sketch-exit-unless-turned` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_exit_unless_turned(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_EXIT_UNLESS_TURNED, None, None); +} + +/// The `sketch-guides` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_guides(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_GUIDES, None, None); +} + +/// The `sketch-hide-glyphs` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_hide_glyphs(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_HIDE_GLYPHS, None, None); +} + +/// The `sketch-state-icons` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_state_icons(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_STATE_ICONS, None, None); +} + +/// The `tess-coarse` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tess_coarse(p: &Painter, rect: Rect) { + paint(p, rect, &TESS_COARSE, None, None); +} + +/// The `tess-fine` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tess_fine(p: &Painter, rect: Rect) { + paint(p, rect, &TESS_FINE, None, None); +} + +/// The `tess-normal` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tess_normal(p: &Painter, rect: Rect) { + paint(p, rect, &TESS_NORMAL, None, None); +} + +/// The `tess-ultra` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tess_ultra(p: &Painter, rect: Rect) { + paint(p, rect, &TESS_ULTRA, None, None); +} + +/// The `tool-cursor` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tool_cursor(p: &Painter, rect: Rect) { + paint(p, rect, &TOOL_CURSOR, None, None); +} + +/// The `tool-extrude` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tool_extrude(p: &Painter, rect: Rect) { + paint(p, rect, &TOOL_EXTRUDE, None, None); +} + +/// The `tool-hole` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tool_hole(p: &Painter, rect: Rect) { + paint(p, rect, &TOOL_HOLE, None, None); +} + +/// The `tool-placement` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tool_placement(p: &Painter, rect: Rect) { + paint(p, rect, &TOOL_PLACEMENT, None, None); +} + +/// The `vertex-markers` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_vertex_markers(p: &Painter, rect: Rect) { + paint(p, rect, &VERTEX_MARKERS, None, None); +} + +/// The `view-angles` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_view_angles(p: &Painter, rect: Rect) { + paint(p, rect, &VIEW_ANGLES, None, None); +} + +/// The `view-grid` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_view_grid(p: &Painter, rect: Rect) { + paint(p, rect, &VIEW_GRID, None, None); +} + +/// The `view-perspective` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_view_perspective(p: &Painter, rect: Rect) { + paint(p, rect, &VIEW_PERSPECTIVE, None, None); +} + +/// The `view-shadow` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_view_shadow(p: &Painter, rect: Rect) { + paint(p, rect, &VIEW_SHADOW, None, None); +} + +/// Every figure painter by file name, for the gallery and the tests. +pub(crate) const FIGURES: &[(&str, [f32; 2], fn(&Painter, Rect))] = &[ + ("aa-2x", AA_2X.size, paint_aa_2x), + ("aa-4x", AA_4X.size, paint_aa_4x), + ("aa-8x", AA_8X.size, paint_aa_8x), + ("aa-off", AA_OFF.size, paint_aa_off), + ("agent-pointer-speed", AGENT_POINTER_SPEED.size, paint_agent_pointer_speed), + ("ao-on", AO_ON.size, paint_ao_on), + ("assembly-move", ASSEMBLY_MOVE.size, paint_assembly_move), + ("browser-card", BROWSER_CARD.size, paint_browser_card), + ("browser-column", BROWSER_COLUMN.size, paint_browser_column), + ("colour-vision-axes", COLOUR_VISION_AXES.size, paint_colour_vision_axes), + ("colour-vision-bends", COLOUR_VISION_BENDS.size, paint_colour_vision_bends), + ("colour-vision-draft", COLOUR_VISION_DRAFT.size, paint_colour_vision_draft), + ("colour-vision-failed", COLOUR_VISION_FAILED.size, paint_colour_vision_failed), + ("colour-vision-fixed", COLOUR_VISION_FIXED.size, paint_colour_vision_fixed), + ("colour-vision-projected", COLOUR_VISION_PROJECTED.size, paint_colour_vision_projected), + ("direct-interaction", DIRECT_INTERACTION.size, paint_direct_interaction), + ("frame-rate", FRAME_RATE.size, paint_frame_rate), + ("history-bottom", HISTORY_BOTTOM.size, paint_history_bottom), + ("history-in-browser", HISTORY_IN_BROWSER.size, paint_history_in_browser), + ("history-left", HISTORY_LEFT.size, paint_history_left), + ("history-under-browser", HISTORY_UNDER_BROWSER.size, paint_history_under_browser), + ("layout-schematic", LAYOUT_SCHEMATIC.size, paint_layout_schematic), + ("measure-axis-distances", MEASURE_AXIS_DISTANCES.size, paint_measure_axis_distances), + ("mouse-mapping", MOUSE_MAPPING.size, paint_mouse_mapping), + ("navigator-axes", NAVIGATOR_AXES.size, paint_navigator_axes), + ("navigator-cube", NAVIGATOR_CUBE.size, paint_navigator_cube), + ("orbit-centre", ORBIT_CENTRE.size, paint_orbit_centre), + ("orbit-cursor", ORBIT_CURSOR.size, paint_orbit_cursor), + ("orbit-origin", ORBIT_ORIGIN.size, paint_orbit_origin), + ("quick-measure", QUICK_MEASURE.size, paint_quick_measure), + ("select-bodies", SELECT_BODIES.size, paint_select_bodies), + ("select-faces-edges", SELECT_FACES_EDGES.size, paint_select_faces_edges), + ("sketch-conflict", SKETCH_CONFLICT.size, paint_sketch_conflict), + ("sketch-exit-keep", SKETCH_EXIT_KEEP.size, paint_sketch_exit_keep), + ("sketch-exit-previous", SKETCH_EXIT_PREVIOUS.size, paint_sketch_exit_previous), + ("sketch-exit-unless-turned", SKETCH_EXIT_UNLESS_TURNED.size, paint_sketch_exit_unless_turned), + ("sketch-guides", SKETCH_GUIDES.size, paint_sketch_guides), + ("sketch-hide-glyphs", SKETCH_HIDE_GLYPHS.size, paint_sketch_hide_glyphs), + ("sketch-state-icons", SKETCH_STATE_ICONS.size, paint_sketch_state_icons), + ("tess-coarse", TESS_COARSE.size, paint_tess_coarse), + ("tess-fine", TESS_FINE.size, paint_tess_fine), + ("tess-normal", TESS_NORMAL.size, paint_tess_normal), + ("tess-ultra", TESS_ULTRA.size, paint_tess_ultra), + ("tool-cursor", TOOL_CURSOR.size, paint_tool_cursor), + ("tool-extrude", TOOL_EXTRUDE.size, paint_tool_extrude), + ("tool-hole", TOOL_HOLE.size, paint_tool_hole), + ("tool-placement", TOOL_PLACEMENT.size, paint_tool_placement), + ("vertex-markers", VERTEX_MARKERS.size, paint_vertex_markers), + ("view-angles", VIEW_ANGLES.size, paint_view_angles), + ("view-grid", VIEW_GRID.size, paint_view_grid), + ("view-perspective", VIEW_PERSPECTIVE.size, paint_view_perspective), + ("view-shadow", VIEW_SHADOW.size, paint_view_shadow), +]; diff --git a/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs new file mode 100644 index 000000000..b3656dc3f --- /dev/null +++ b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs @@ -0,0 +1,583 @@ +//! The drawing engine behind the Preferences figures: a figure is a short list of operations in its +//! own coordinates (`preferences_figure_data.rs`, compiled from the SVGs in +//! `docs/design/preferences/figures/`), painted with egui shapes in the colours of the current +//! `Tokens`. Nothing is rasterised and no image is loaded; every figure costs a few dozen shapes. +//! Any rectangle, including an empty, infinite or enormous one, is safe to paint into. +use crate::theme::Tokens; +use egui::{Align2, Color32, CornerRadius, FontId, Mesh, Painter, Pos2, Rect, Shape, Stroke, StrokeKind, pos2, vec2}; + +/// Colour roles of the figures. Each reads one `Tokens` field (`docs/design/preferences/tokens.md`). +#[derive(Clone, Copy, Debug)] +pub(super) enum Ink { + Ground, + Line, + Top, + Left, + Right, + Card, + Accent, + Reference, + AxisX, + AxisY, + AxisZ, + Ok, + Warn, + Dim, + Text, + Border, + ControlBorder, + Control, + Note, + NoteFill, + White, + Black, + /// Colour vision sample colours: Z axis blue, projected, X axis, bend up and bend down. + Cv0, + Cv1, + Cv2, + Cv3, + Cv4, + /// A colour of a theme thumbnail, from its `ThemeSample`. + Slot(u8), +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct P { + pub ink: Ink, + pub a: f32, +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct L { + pub ink: Ink, + pub a: f32, + pub w: f32, + /// Dash and gap, `[0.0, 0.0]` for a solid line. + pub dash: [f32; 2], + pub round: bool, +} + +/// A vertical gradient over the figure's `y` range. +#[derive(Clone, Copy, Debug)] +pub(super) struct G { + pub top: Ink, + pub bottom: Ink, + pub y: [f32; 2], +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum Op { + Rect { + r: [f32; 4], + radius: f32, + fill: Option

, + line: Option, + }, + Circle { + c: [f32; 3], + fill: Option

, + line: Option, + }, + Poly { + pts: &'static [[f32; 2]], + closed: bool, + fill: Option

, + grad: Option, + line: Option, + }, + /// A soft black ellipse: opaque `a` at the centre, clear at the edge. + Glow { + c: [f32; 4], + a: f32, + }, + Text { + at: [f32; 2], + size: f32, + anchor: u8, + ink: Ink, + a: f32, + s: &'static str, + bold: bool, + }, + Clip(&'static [[f32; 2]]), + Unclip, +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct Figure { + pub size: [f32; 2], + pub ops: &'static [Op], +} + +/// The twelve colours a theme thumbnail is drawn with: ground, bar and side panel, muted marks, +/// accent, the window face's top and bottom, grid, cube top, cube outline, cube left, cube right +/// and the thumbnail's border. A colour may carry alpha (a glass theme's panels). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ThemeSample { + pub slots: [Color32; 12], +} + +impl ThemeSample { + /// A thumbnail of the theme whose tokens these are. + pub fn from_tokens(t: &Tokens) -> ThemeSample { + let mix = |a: Color32, b: Color32, f: f32| a.lerp_to_gamma(b, f); + ThemeSample { + slots: [ + t.dialog_footer, + t.control_fill, + t.form_dim.gamma_multiply(0.7), + t.form_primary, + t.viewport_top, + t.viewport_bottom, + t.form_dim.gamma_multiply(0.1), + t.body, + t.form_dim, + mix(t.body, t.body_edge, 0.25), + mix(t.body, t.body_edge, 0.5), + t.dialog_border, + ], + } + } + + /// The same colours with every alpha scaled (a glass theme's fills). + pub fn glass(mut self, alpha: f32) -> ThemeSample { + for slot in &mut self.slots[1..2] { + *slot = slot.gamma_multiply(alpha); + } + self + } +} + +/// Largest side, in points, a figure is painted at; anything larger is skipped, not drawn wrong. +const MAX_SIDE: f32 = 16_384.0; +const MAX_POINTS: usize = 512; + +struct Ctx<'a> { + t: &'a Tokens, + sample: Option<&'a ThemeSample>, + origin: Pos2, + scale: f32, +} + +impl Ctx<'_> { + fn ink(&self, ink: Ink, a: f32) -> Color32 { + let t = self.t; + let c = match ink { + Ink::Ground => t.figure_ground, + Ink::Line => t.figure_line, + Ink::Top => t.figure_face_top, + Ink::Left => t.figure_face_left, + Ink::Right => t.figure_face_right, + Ink::Card => t.figure_card, + Ink::Accent => t.figure_accent, + Ink::Reference => t.figure_reference, + Ink::AxisX => t.figure_axis_x, + Ink::AxisY => t.figure_axis_y, + Ink::AxisZ => t.figure_axis_z, + Ink::Ok => t.figure_ok, + Ink::Warn => t.figure_warn, + Ink::Dim => t.form_dim, + Ink::Text => t.form_ink, + Ink::Border => t.dialog_border, + Ink::ControlBorder => t.control_border, + Ink::Control => t.control_fill, + Ink::Note => t.pref_note, + Ink::NoteFill => t.pref_note_fill, + Ink::White => t.figure_white, + Ink::Black => t.figure_black, + Ink::Cv0 => t.axis_z, + Ink::Cv1 => t.sketch_projected, + Ink::Cv2 => t.axis_x, + Ink::Cv3 => t.bend_up, + Ink::Cv4 => t.bend_down, + Ink::Slot(n) => self.sample.and_then(|s| s.slots.get(n as usize).copied()).unwrap_or(Color32::TRANSPARENT), + }; + if a >= 1.0 { c } else { c.gamma_multiply(a.clamp(0.0, 1.0)) } + } + + fn at(&self, p: [f32; 2]) -> Pos2 { + self.origin + vec2(p[0] * self.scale, p[1] * self.scale) + } + + fn stroke(&self, line: &L) -> Stroke { + Stroke::new((line.w * self.scale).clamp(0.0, 64.0), self.ink(line.ink, line.a)) + } +} + +/// Paints `figure` into `rect`, scaled to fit and centred, with `Tokens::get()` colours. +pub(super) fn paint(p: &Painter, rect: Rect, figure: &Figure, sample: Option<&ThemeSample>, clip: Option<&[[f32; 2]]>) { + let size = rect.size(); + if !rect.min.is_finite() || !size.is_finite() || size.x < 1.0 || size.y < 1.0 || size.x > MAX_SIDE || size.y > MAX_SIDE { + return; + } + let [fw, fh] = figure.size; + if !(fw > 0.0 && fh > 0.0) { + return; + } + let scale = (size.x / fw).min(size.y / fh); + let fitted = Rect::from_center_size(rect.center(), vec2(fw * scale, fh * scale)); + let t = Tokens::get(); + let ctx = Ctx { t: &t, sample, origin: fitted.min, scale }; + let p = p.with_clip_rect(fitted.intersect(p.clip_rect())); + let outer: Option> = clip.map(|c| c.iter().map(|&q| ctx.at(q)).collect()); + // Nested clips are inside one another in every figure, so the innermost one is the clip. + let mut stack: Vec> = Vec::new(); + for op in figure.ops { + match op { + Op::Clip(points) if outer.is_none() => stack.push(points.iter().map(|&q| ctx.at(q)).collect()), + Op::Unclip if outer.is_none() => { + stack.pop(); + } + Op::Clip(_) | Op::Unclip => {} + _ => draw(&p, &ctx, op, outer.as_deref().or(stack.last().map(Vec::as_slice))), + } + } +} + +fn draw(p: &Painter, ctx: &Ctx, op: &Op, clip: Option<&[Pos2]>) { + match op { + Op::Rect { r, radius, fill, line } => { + let rect = Rect::from_min_size(ctx.at([r[0], r[1]]), vec2(r[2] * ctx.scale, r[3] * ctx.scale)); + if clip.is_some() { + let pts = rounded(rect, radius * ctx.scale); + poly(p, ctx, &pts, true, fill, None, line, clip); + return; + } + let corner = CornerRadius::same((radius * ctx.scale).clamp(0.0, 255.0).round() as u8); + if let Some(f) = fill { + p.rect_filled(rect, corner, ctx.ink(f.ink, f.a)); + } + if let Some(l) = line { + p.rect_stroke(rect, corner, ctx.stroke(l), StrokeKind::Middle); + } + } + Op::Circle { c, fill, line } => { + let centre = ctx.at([c[0], c[1]]); + let radius = c[2] * ctx.scale; + if clip.is_some() { + let pts: Vec = (0..24) + .map(|i| { + let a = i as f32 * std::f32::consts::TAU / 24.0; + centre + vec2(a.cos(), a.sin()) * radius + }) + .collect(); + poly(p, ctx, &pts, true, fill, None, line, clip); + return; + } + if let Some(f) = fill { + p.circle_filled(centre, radius, ctx.ink(f.ink, f.a)); + } + if let Some(l) = line { + p.circle_stroke(centre, radius, ctx.stroke(l)); + } + } + Op::Poly { pts, closed, fill, grad, line } => { + let points: Vec = pts.iter().map(|&q| ctx.at(q)).collect(); + poly(p, ctx, &points, *closed, fill, grad.as_ref(), line, clip); + } + Op::Glow { c, a } => { + let centre = ctx.at([c[0], c[1]]); + let radius = vec2(c[2] * ctx.scale, c[3] * ctx.scale); + glow(p, centre, radius, ctx.ink(Ink::Black, *a)); + } + Op::Text { at, size, anchor, ink, a, s, .. } => { + if clip.is_some() { + return; + } + let align = match anchor { + 1 => Align2::CENTER_CENTER, + 2 => Align2::RIGHT_CENTER, + _ => Align2::LEFT_CENTER, + }; + // The board's captions are 6.5 to 7.5 units: too small to read at card size, so they + // are drawn a third larger (never under 8 points). The SVG's `y` is the baseline, which + // sits about 0.36 em below the middle of a line of digits and capitals. + // Longer captions sit in tight pills and on cube faces, so they are drawn slightly smaller than the board (egui's monospace face is wider than the board's). + let grow = match s.chars().count() { + 0..=4 => 1.2, + 5..=6 => 0.9, + _ => 0.76, + }; + let size = (size * ctx.scale * grow).clamp(7.0, 256.0); + let at = ctx.at(*at) - vec2(0.0, size * 0.36); + p.text(at, align, s, FontId::monospace(size), ctx.ink(*ink, *a)); + } + Op::Clip(_) | Op::Unclip => {} + } +} + +#[allow(clippy::too_many_arguments)] +fn poly(p: &Painter, ctx: &Ctx, pts: &[Pos2], closed: bool, fill: &Option

, grad: Option<&G>, line: &Option, clip: Option<&[Pos2]>) { + if pts.len() < 2 || pts.len() > MAX_POINTS || pts.iter().any(|q| !q.is_finite()) { + return; + } + let clipped; + let (shape, fillable) = match clip { + Some(c) if pts.len() >= 3 && closed => { + clipped = clip_polygon(pts, c); + (&clipped[..], clipped.len() >= 3) + } + _ => (pts, pts.len() >= 3 && closed), + }; + if fillable { + if let Some(g) = grad { + let (top, bottom) = (ctx.ink(g.top, 1.0), ctx.ink(g.bottom, 1.0)); + let (y0, y1) = (ctx.at([0.0, g.y[0]]).y, ctx.at([0.0, g.y[1]]).y); + let span = (y1 - y0).max(1e-3); + fill_polygon(p, shape, |q| top.lerp_to_gamma(bottom, ((q.y - y0) / span).clamp(0.0, 1.0))); + } else if let Some(f) = fill { + let c = ctx.ink(f.ink, f.a); + fill_polygon(p, shape, |_| c); + } + } + if let Some(l) = line { + let stroke = ctx.stroke(l); + if stroke.width <= 0.0 || stroke.color == Color32::TRANSPARENT { + return; + } + let mut path = pts.to_vec(); + if closed { + path.push(pts[0]); + } + let runs = match clip { + Some(c) => clip_path(&path, c), + None => vec![path], + }; + for run in runs { + if l.dash[0] > 0.0 && l.dash[1] > 0.0 { + let dash = (l.dash[0] * ctx.scale).max(0.5); + let gap = (l.dash[1] * ctx.scale).max(0.5); + p.extend(crate::viewport::dashed_line(&run, p.clip_rect(), stroke, dash, gap)); + } else { + p.add(Shape::line(run, stroke)); + } + } + } +} + +fn rounded(rect: Rect, radius: f32) -> Vec { + let r = radius.min(rect.width() * 0.5).min(rect.height() * 0.5).max(0.0); + if r < 0.01 { + return vec![rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()]; + } + let mut out = Vec::with_capacity(28); + for (centre, start) in [ + (rect.right_top() + vec2(-r, r), -90.0_f32), + (rect.right_bottom() + vec2(-r, -r), 0.0), + (rect.left_bottom() + vec2(r, -r), 90.0), + (rect.left_top() + vec2(r, r), 180.0), + ] { + for k in 0..=6 { + let a = (start + 90.0 * k as f32 / 6.0).to_radians(); + out.push(centre + vec2(a.cos(), a.sin()) * r); + } + } + out +} + +fn cross(o: Pos2, a: Pos2, b: Pos2) -> f32 { + (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) +} + +fn is_convex(pts: &[Pos2]) -> bool { + let n = pts.len(); + let mut sign = 0.0_f32; + for i in 0..n { + let c = cross(pts[i], pts[(i + 1) % n], pts[(i + 2) % n]); + if c.abs() < 1e-4 { + continue; + } + if sign == 0.0 { + sign = c.signum(); + } else if c.signum() != sign { + return false; + } + } + true +} + +/// Fills a simple polygon with `colour_at` per vertex: as a convex polygon when it is one, else by +/// ear clipping (at most `MAX_POINTS` vertices). +fn fill_polygon(p: &Painter, pts: &[Pos2], colour_at: impl Fn(Pos2) -> Color32) { + let n = pts.len(); + if !(3..=MAX_POINTS).contains(&n) { + return; + } + let mut mesh = Mesh::default(); + for &q in pts { + mesh.colored_vertex(q, colour_at(q)); + } + if is_convex(pts) { + for i in 1..n as u32 - 1 { + mesh.add_triangle(0, i, i + 1); + } + } else { + let area: f32 = (0..n).map(|i| pts[i].x * pts[(i + 1) % n].y - pts[(i + 1) % n].x * pts[i].y).sum(); + let mut idx: Vec = if area >= 0.0 { (0..n).collect() } else { (0..n).rev().collect() }; + let mut guard = 0; + while idx.len() > 3 && guard < n * n { + guard += 1; + let m = idx.len(); + let mut cut = None; + for k in 0..m { + let (a, b, c) = (idx[(k + m - 1) % m], idx[k], idx[(k + 1) % m]); + if cross(pts[a], pts[b], pts[c]) <= 0.0 { + continue; + } + let inside = idx.iter().any(|&o| { + o != a + && o != b + && o != c + && cross(pts[a], pts[b], pts[o]) >= 0.0 + && cross(pts[b], pts[c], pts[o]) >= 0.0 + && cross(pts[c], pts[a], pts[o]) >= 0.0 + }); + if !inside { + cut = Some(k); + break; + } + } + let Some(k) = cut else { break }; + let (a, b, c) = (idx[(k + m - 1) % m], idx[k], idx[(k + 1) % m]); + mesh.add_triangle(a as u32, b as u32, c as u32); + idx.remove(k); + } + if idx.len() == 3 { + mesh.add_triangle(idx[0] as u32, idx[1] as u32, idx[2] as u32); + } + } + p.add(Shape::mesh(mesh)); +} + +fn glow(p: &Painter, centre: Pos2, radius: egui::Vec2, ink: Color32) { + const SEGMENTS: u32 = 32; + if !(radius.x > 0.0 && radius.y > 0.0) { + return; + } + let mut mesh = Mesh::default(); + mesh.colored_vertex(centre, ink); + for i in 0..=SEGMENTS { + let a = std::f32::consts::TAU * i as f32 / SEGMENTS as f32; + mesh.colored_vertex(centre + vec2(a.cos() * radius.x, a.sin() * radius.y), Color32::TRANSPARENT); + } + for i in 1..=SEGMENTS { + mesh.add_triangle(0, i, i + 1); + } + p.add(Shape::mesh(mesh)); +} + +/// Sutherland-Hodgman clip of a polygon against a convex clip polygon of either winding. +fn clip_polygon(subject: &[Pos2], clip: &[Pos2]) -> Vec { + let n = clip.len(); + if n < 3 { + return Vec::new(); + } + let area: f32 = (0..n).map(|i| clip[i].x * clip[(i + 1) % n].y - clip[(i + 1) % n].x * clip[i].y).sum(); + let side = if area >= 0.0 { 1.0 } else { -1.0 }; + let mut out = subject.to_vec(); + for i in 0..n { + let (a, b) = (clip[i], clip[(i + 1) % n]); + let inside = |q: Pos2| side * cross(a, b, q) >= 0.0; + let input = std::mem::take(&mut out); + if input.is_empty() { + break; + } + for j in 0..input.len() { + let (cur, prev) = (input[j], input[(j + input.len() - 1) % input.len()]); + if inside(cur) { + if !inside(prev) { + out.push(intersect(prev, cur, a, b)); + } + out.push(cur); + } else if inside(prev) { + out.push(intersect(prev, cur, a, b)); + } + } + } + out +} + +fn intersect(p1: Pos2, p2: Pos2, a: Pos2, b: Pos2) -> Pos2 { + let (d1, d2) = (p2 - p1, b - a); + let den = d1.x * d2.y - d1.y * d2.x; + if den.abs() < 1e-9 { + return p1; + } + let t = ((a.x - p1.x) * d2.y - (a.y - p1.y) * d2.x) / den; + pos2(p1.x + d1.x * t, p1.y + d1.y * t) +} + +/// The parts of a polyline inside a convex clip polygon (Cyrus-Beck per segment). +fn clip_path(path: &[Pos2], clip: &[Pos2]) -> Vec> { + let n = clip.len(); + if n < 3 { + return Vec::new(); + } + let area: f32 = (0..n).map(|i| clip[i].x * clip[(i + 1) % n].y - clip[(i + 1) % n].x * clip[i].y).sum(); + let side = if area >= 0.0 { 1.0 } else { -1.0 }; + let mut runs: Vec> = Vec::new(); + for w in path.windows(2) { + let (mut t0, mut t1) = (0.0_f32, 1.0_f32); + let d = w[1] - w[0]; + let mut visible = true; + for i in 0..n { + let (a, b) = (clip[i], clip[(i + 1) % n]); + let num = side * cross(a, b, w[0]); + // The signed distance of the point at t from this edge is num + t * den. + let den = side * cross(a, b, w[1]) - num; + if den.abs() < 1e-9 { + if num < 0.0 { + visible = false; + break; + } + } else { + let t = -num / den; + if den > 0.0 { + t0 = t0.max(t); + } else { + t1 = t1.min(t); + } + } + } + if visible && t0 < t1 { + let (a, b) = (w[0] + d * t0, w[0] + d * t1); + match runs.last_mut() { + Some(run) if run.last().is_some_and(|l| l.distance(a) < 1e-3) => run.push(b), + _ => runs.push(vec![a, b]), + } + } + } + runs +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square() -> Vec { + vec![pos2(0.0, 0.0), pos2(10.0, 0.0), pos2(10.0, 10.0), pos2(0.0, 10.0)] + } + + #[test] + fn clipping_a_square_to_a_triangle_keeps_the_overlap() { + let tri = [pos2(0.0, 0.0), pos2(10.0, 0.0), pos2(0.0, 10.0)]; + let out = clip_polygon(&square(), &tri); + let n = out.len(); + let area: f32 = (0..n).map(|i| out[i].x * out[(i + 1) % n].y - out[(i + 1) % n].x * out[i].y).sum::().abs() / 2.0; + assert!((area - 50.0).abs() < 1e-3, "{area}"); + } + + #[test] + fn a_path_is_cut_at_the_clip_edge() { + let tri = [pos2(0.0, 0.0), pos2(10.0, 0.0), pos2(0.0, 10.0)]; + let runs = clip_path(&[pos2(-5.0, 2.0), pos2(15.0, 2.0)], &tri); + assert_eq!(runs.len(), 1); + assert!((runs[0][0].x - 0.0).abs() < 1e-3 && (runs[0][1].x - 8.0).abs() < 1e-3, "{:?}", runs); + } + + #[test] + fn concave_polygons_are_detected() { + assert!(is_convex(&square())); + assert!(!is_convex(&[pos2(0.0, 0.0), pos2(10.0, 0.0), pos2(5.0, 2.0), pos2(10.0, 10.0), pos2(0.0, 10.0)])); + } +} diff --git a/crates/ui-egui/src/ui_kit/preferences_figures.rs b/crates/ui-egui/src/ui_kit/preferences_figures.rs index 2c7ce82b2..7bbcd2895 100644 --- a/crates/ui-egui/src/ui_kit/preferences_figures.rs +++ b/crates/ui-egui/src/ui_kit/preferences_figures.rs @@ -260,6 +260,26 @@ pub(crate) fn paint_layout(ui: &mut egui::Ui, state: super::preferences::LayoutP super::text(ui, crate::i18n::tr("prefs.preview_choices"), super::Text::Note("preview")); } +#[allow(unused_imports, reason = "painted by the Preferences pages of #9875 to #9883")] +pub(crate) use super::preferences_figure_ops::ThemeSample; +use super::preferences_figure_ops::paint; + +#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] +/// A theme card's miniature application window, drawn with the theme's own `sample` colours. +pub(crate) fn paint_theme_thumbnail(p: &Painter, rect: Rect, sample: &ThemeSample) { + paint(p, rect, &super::preferences_figure_data::THEME_THUMBNAIL, Some(sample), None); +} + +#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] +/// The "System" theme card: `light` with `dark` over a slanted band of it (the board clips the dark +/// half to the polygon 56 %,0 / 100 %,0 / 100 %,100 % / 40 %,100 %). +pub(crate) fn paint_theme_system(p: &Painter, rect: Rect, light: &ThemeSample, dark: &ThemeSample) { + const BAND: [[f32; 2]; 4] = [[69.44, 0.0], [124.0, 0.0], [124.0, 76.0], [49.6, 76.0]]; + let figure = &super::preferences_figure_data::THEME_THUMBNAIL; + paint(p, rect, figure, Some(light), None); + paint(p, rect, figure, Some(dark), Some(&BAND)); +} + #[cfg(test)] mod tests { use super::orientation_axes; @@ -281,4 +301,101 @@ mod tests { } } } + + use super::{ThemeSample, paint_theme_system, paint_theme_thumbnail}; + use crate::theme::Tokens; + use crate::ui_kit::preferences_figure_data::FIGURES; + use egui::{Pos2, Rect, vec2}; + + /// Shapes a figure paints into `rect` on a fresh frame, in the given theme. + fn shapes(rect: Rect, paint: impl Fn(&egui::Painter, Rect)) -> Vec { + let ctx = crate::fonts::test_context(); + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))), ..Default::default() }, |ui| { + paint(ui.painter(), rect); + }); + output.textures_delta.clear(); + output.shapes + } + + fn rects() -> Vec { + let nan = f32::NAN; + vec![ + Rect::from_min_size(Pos2::ZERO, vec2(0.0, 0.0)), + Rect::from_min_size(Pos2::ZERO, vec2(0.2, 0.2)), + Rect::from_min_size(Pos2::new(5.0, 5.0), vec2(1.0, 1.0)), + Rect::from_min_size(Pos2::new(5.0, 5.0), vec2(3.0, 200.0)), + Rect::from_min_size(Pos2::new(5.0, 5.0), vec2(120.0, 64.0)), + Rect::from_min_size(Pos2::new(-50.0, -50.0), vec2(300.0, 300.0)), + Rect::from_min_size(Pos2::ZERO, vec2(1.0e5, 1.0e5)), + Rect::from_min_size(Pos2::ZERO, vec2(f32::INFINITY, 10.0)), + Rect::from_min_size(Pos2::new(nan, 0.0), vec2(10.0, 10.0)), + Rect::from_min_size(Pos2::ZERO, vec2(-40.0, 30.0)), + Rect::from_min_size(Pos2::ZERO, vec2(nan, nan)), + ] + } + + /// Every figure, in both themes, paints at size zero, tiny, normal, huge and non-finite without + /// panicking, and at a normal size stays inside its rectangle with a bounded number of shapes. + #[test] + fn every_preference_figure_paints_safely_at_any_size_in_both_themes() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + assert!(!FIGURES.is_empty()); + for (name, size, paint) in FIGURES { + for rect in rects() { + let _ = shapes(rect, paint); + } + let rect = Rect::from_min_size(Pos2::new(20.0, 10.0), vec2(size[0] * 2.0, size[1] * 2.0)); + let painted = shapes(rect, paint); + assert!(!painted.is_empty() && painted.len() < 700, "{name}: {} shapes", painted.len()); + for shape in &painted { + let bounds = shape.shape.visual_bounding_rect().intersect(shape.clip_rect); + if bounds.is_positive() { + assert!(rect.expand(1.0).contains_rect(bounds), "{name}: {bounds:?} outside {rect:?}"); + } + } + } + } + crate::theme::set_dark(previous); + } + + /// The figures read the theme: the same figure paints different colours in light and dark. + #[test] + fn preference_figures_follow_the_theme() { + let previous = crate::theme::is_dark(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(120.0, 64.0)); + let colours = |dark: bool| { + crate::theme::set_dark(dark); + let mut all = Vec::new(); + for shape in shapes(rect, super::super::preferences_figure_data::paint_orbit_origin) { + if let egui::Shape::Rect(r) = shape.shape { + all.push(r.fill); + } + } + all + }; + let (light, dark) = (colours(false), colours(true)); + assert!(!light.is_empty() && light != dark); + crate::theme::set_dark(previous); + } + + #[test] + fn theme_thumbnails_paint_with_the_sample_colours_and_a_slanted_system_band() { + let (light, dark) = (ThemeSample::from_tokens(&Tokens::light()), ThemeSample::from_tokens(&Tokens::dark())); + assert_ne!(light, dark); + let rect = Rect::from_min_size(Pos2::new(4.0, 4.0), vec2(124.0, 76.0)); + for rect in rects().into_iter().chain([rect]) { + let _ = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light)); + let _ = shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)); + } + let single = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light)).len(); + let system = shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)).len(); + assert!(system > single, "the dark band adds shapes over the light card"); + for shape in shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)) { + let bounds = shape.shape.visual_bounding_rect().intersect(shape.clip_rect); + assert!(!bounds.is_positive() || rect.expand(1.0).contains_rect(bounds), "{bounds:?}"); + } + } } diff --git a/crates/ui-egui/src/ui_kit/test_support_tests.rs b/crates/ui-egui/src/ui_kit/test_support_tests.rs index 216894e92..f288a8536 100644 --- a/crates/ui-egui/src/ui_kit/test_support_tests.rs +++ b/crates/ui-egui/src/ui_kit/test_support_tests.rs @@ -4,6 +4,29 @@ use egui::{Ui, vec2}; pub(crate) use crate::test_support::{key, pointer}; +#[test] +fn render_results_shared_divider_clamps_hostile_positions_and_uses_bounded_chrome() { + for (input, expected) in [(f32::NAN, 0.5), (f32::INFINITY, 0.5), (f32::NEG_INFINITY, 0.5), (-1e30, 0.05), (0.25, 0.25), (1e30, 0.95)] { + assert_eq!(comparison_position(input), expected); + } + let ctx = crate::fonts::test_context(); + let position = std::cell::Cell::new(0.5); + let mut draw = |ui: &mut Ui| { + let (canvas, _) = ui.allocate_exact_size(vec2(240.0, 180.0), egui::Sense::hover()); + let mut value = position.get(); + comparison_divider(ui, canvas, &mut value, "Comparison divider"); + comparison_badge(ui, canvas, "Live preview", false); + position.set(value); + }; + frame(&ctx, vec![], &mut draw); + let handle = scenario::rect_of("render:compare:handle").unwrap().center(); + frame(&ctx, pointer(handle, true), &mut draw); + let end = egui::pos2(1000.0, handle.y); + frame(&ctx, vec![egui::Event::PointerMoved(end)], &mut draw); + assert_eq!(position.get(), 0.95); + frame(&ctx, pointer(end, false), &mut draw); +} + fn draw_frame(ctx: &egui::Context, events: Vec, mut add: impl FnMut(&mut Ui)) -> egui::FullOutput { scenario::clear_handles(); crate::test_support::frame( diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index ed3406689..5ed884907 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -235,8 +235,10 @@ pub struct ViewportState { pub(crate) grid_plane: std::sync::Mutex, } -/// Something under the cursor. -#[derive(Clone, Debug, PartialEq)] +/// Something under the cursor. The control channel reports it in the selection's own form +/// (`{"type": "edge", "body", "index", …}`, #9087). +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] pub enum Hit { SketchPoint { sketch: u64, @@ -2019,11 +2021,16 @@ pub fn origin_planes(app: &SolveApp) -> Vec<(&'static str, Vec3, [Vec3; 4])> { return Vec::new(); } // While the Origin is hidden, a dialog picking a plane brings the planes back: then every - // plane; otherwise only those not hidden one by one. - let creating = !app.origin_shown() && app.picking_plane(); + // plane; otherwise only those not hidden one by one. Project is the exception (#10778): + // its pick takes planes too, but each line a plane gives, an axis already gives, so a + // hidden Origin stays hidden for it. + let reveal = !app.origin_shown() && app.picking_plane() && !app.picking_project_geometry(); + if !app.origin_shown() && !reveal { + return Vec::new(); + } origin_quads(origin_size(app.cam.half_height())) .into_iter() - .filter(|(n, _, _)| creating || !app.session.visibility.hidden_origin.iter().any(|h| h == n)) + .filter(|(n, _, _)| reveal || !app.session.visibility.hidden_origin.iter().any(|h| h == n)) .collect() } @@ -2841,22 +2848,25 @@ pub fn section_plane(app: &SolveApp) -> Option<(Vec3, Vec3)> { scratch.execute("inspect.section", &p).ok()?; return scratch.section; } - // Slice (Sketch Palette): cut the model at the plane of the sketch being edited. - if app.session.section.is_none() { - let st = crate::open_meshing::shown_world(app); - if let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)).filter(|ss| ss.sketch.view.slice) { - return Some((ss.plane.origin, ss.plane.normal())); - } - } - app.session.section + slice_plane(app).or(app.session.section) +} + +/// Slice (Sketch Palette): the plane of the sketch being edited, when Slice is on in it. It +/// stands in for a Section Analysis until it is turned off or the sketch closes: with the +/// section first, turning Slice on did nothing (#10705). +fn slice_plane(app: &SolveApp) -> Option<(Vec3, Vec3)> { + let id = app.session.active_sketch?; + let st = crate::open_meshing::shown_world(app); + let ss = st.sketch(id).filter(|ss| ss.sketch.view.slice)?; + Some((ss.plane.origin, ss.plane.normal())) } /// Whether the section [`section_plane`] shows has hatched cut faces: an open Section Analysis -/// dialog's Hatch option, else the section's own. +/// dialog's Hatch option, a Slice's always, else the section's own. pub fn section_hatch(app: &SolveApp) -> bool { match app.dialog.as_ref().map(|d| &d.kind) { Some(crate::dialogs::Kind::Section { hatch, .. }) => *hatch, - _ => app.session.section_hatch, + _ => app.session.section_hatch || slice_plane(app).is_some(), } } @@ -3285,13 +3295,17 @@ pub(crate) fn dialog_pick(app: &mut SolveApp, hit: &Hit, sel: Sel) { if app.applying.is_some() { return; } - // Press Pull's first pick of a curved face or an edge reopens it as an offset or a fillet. + // Press Pull's first pick of a curved face, a chamfer's face or an edge reopens it as an + // offset, the chamfer or a fillet. if let Some(d) = &app.dialog && d.press_pull && d.inputs.first().is_some_and(|i| i.items.is_empty()) && match &sel { Sel::Edge { .. } => true, - Sel::Face { body, index, .. } => crate::dialogs::planar_face(&app.session, body, *index).is_none(), + Sel::Face { body, index, .. } => { + crate::dialogs::planar_face(&app.session, body, *index).is_none() + || crate::dialogs::blend_feature(&app.session, body, *index).is_some() + } _ => false, } { @@ -4919,6 +4933,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // the text, also from the space between its letters (#8835). let own = matches!(&hit, Some(Hit::SketchPoint { sketch, .. } | Hit::SketchMidpoint { sketch, .. } | Hit::SketchCurve { sketch, .. }) if Some(*sketch) == active); let hit = if own { hit } else { crate::sketch_text_handles::grab_inside(app, &proj, a).or(hit) }; + let hit = hit.map(|hit| point_at_midpoint(app, hit)); match hit { Some(Hit::SketchPoint { sketch, id, .. }) if Some(sketch) == active => { // A point dragged with the rest of a selection slides with it, from where it @@ -5444,7 +5459,17 @@ pub(crate) fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Re if let Some(since) = app.computing_since() { let seconds = ((crate::now_ms() - since) / 1000.0).floor().max(0.0); let text = crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))]); - if let Some(r) = paint_toast(ui, free, text, false, true) { + // A history command or a delete's check can be given up on (#8266); a feature edit + // applying has the dialog's Cancel instead. + let cancel = app.tr_label("Cancel").to_string(); + let actions: Vec<(&str, ToastKind)> = if app.can_cancel_computing() { vec![(cancel.as_str(), ToastKind::Secondary)] } else { Vec::new() }; + if let Some((r, clicked, buttons)) = paint_toast_with(ui, free, text, ToastLead::Spinner, &actions) { + if let Some(button) = buttons.first() { + crate::scenario::publish_handle("toast:computing:cancel", button.center()); + } + if clicked == Some(0) { + app.cancel_computing(); + } obstacles.push(r); crate::scenario::publish_rect("toast:computing", r); if app.status.is_none() { @@ -5918,6 +5943,27 @@ pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool, toggle: bo /// The rest of the selected sketch geometry when the point or curve `id` is part of it (#2621): /// a drag that starts on a selected entity moves the whole selection with it. +/// A drag that starts on a line's middle where a point is held (a centre rectangle's centre on +/// its diagonal) drags that point, as a drag that starts on the point does. Dragging the line by +/// its middle instead moved its ends: with the point constrained (on the origin, on a line) the +/// line turned and stretched about it, and the rectangle round it changed size (#10510). +fn point_at_midpoint(app: &SolveApp, hit: Hit) -> Hit { + let Hit::SketchMidpoint { sketch, id, .. } = &hit else { return hit }; + let st = crate::open_meshing::session_world(&app.session); + let held = st.sketch(*sketch).and_then(|ss| { + let sk = &ss.sketch; + let line = sk.curve_index(id)?; + sk.constraints.iter().filter(|c| !c.driven).find_map(|c| match c.kind { + solidcraft_engine::sketch::ConstraintKind::Midpoint { p, l } if l == line => sk.points.get(p).map(|q| (q.id.clone(), q.pos)), + _ => None, + }) + }); + match held { + Some((id, at)) => Hit::SketchPoint { sketch: *sketch, id, at }, + None => hit, + } +} + fn dragged_with(app: &SolveApp, id: &str) -> Vec { fn geometry(s: &Sel) -> Option<&str> { match s { @@ -6727,7 +6773,7 @@ fn axis_view_orbit(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) -> bool { app.viewport.axis_drag = origin.filter(|p| match app.preferences.navigator_style { crate::prefs::NavigatorStyle::Axes => axis_rect(app, rect).contains(*p), crate::prefs::NavigatorStyle::Cube => { - navigation_cube::drag_origin(&app.cam, axis_center(app, rect), *p, axis_rect(app, rect).width() / navigation_cube::DESIGN_SIZE) + navigation_cube::drag_origin(app, axis_center(app, rect), *p, axis_rect(app, rect).width() / navigation_cube::DESIGN_SIZE) } }); if app.viewport.axis_drag.is_some() { @@ -10139,6 +10185,32 @@ mod tests { assert!(!legend(&mut h)); } + #[test] + fn a_sketch_slice_cuts_at_the_sketch_while_a_section_is_on() { + // #10705: with a Section Analysis on, turning Slice on in a sketch did nothing. + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Block"})).unwrap(); + h.app.run("construct.plane.offset", json!({"base":"XY","offset":10,"name":"Mid"})).unwrap(); + h.app.run("sketch.create", json!({"plane":"Mid"})).unwrap(); + h.app.run("inspect.section", json!({"plane":"XZ","offset":15,"hatch":false})).unwrap(); + h.frames(2); + let across_y = |h: &crate::scenario::Harness| section_plane(&h.app).is_some_and(|(o, n)| n.y.abs() > 0.99 && (o.y.abs() - 15.0).abs() < 1e-9); + assert!(across_y(&h)); + assert!(!section_hatch(&h.app)); + h.app.run("sketch.options", json!({"slice":true})).unwrap(); + h.frames(2); + let (o, n) = section_plane(&h.app).expect("the slice"); + assert!(n.z.abs() > 0.99 && (o.z - 10.0).abs() < 1e-9, "{o:?} {n:?}"); + assert!(section_hatch(&h.app), "a slice is hatched as it is without a section"); + // Slice off, or the sketch closed: the section is back. + h.app.run("sketch.options", json!({"slice":false})).unwrap(); + assert!(across_y(&h)); + h.app.run("sketch.options", json!({"slice":true})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.frames(2); + assert!(across_y(&h)); + } + #[test] fn a_section_leaves_the_origin_planes_and_axes_whole() { // #1229: the origin planes and axes are reference geometry; the section plane cuts the @@ -12868,6 +12940,30 @@ mod grid_plane_tests { assert!(origin_planes(&app).is_empty()); } + /// #10778: Project's pick takes origin planes, but it must not bring hidden origin planes + /// back: every line a plane projects, an origin axis already gives. The axes and point stay + /// as today; other dialogs that pick a plane keep the reveal (#2581). + #[test] + fn project_leaves_hidden_origin_planes_hidden() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.run("solid.box", json!({"length":40,"width":40,"height":40})).unwrap(); + app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + app.set_origin_shown(false); + app.start("sketch.project"); + assert!(app.picking_project_geometry()); + assert!(app.picking_plane(), "Project's pick takes origin planes"); + assert!(origin_planes(&app).is_empty(), "Project leaves hidden origin planes hidden"); + assert!(!origin_axes(&app).is_empty(), "the origin axes stay as today"); + // Other dialogs that pick a plane keep today's reveal. + app.dialog = None; + app.start("solid.mirror"); + app.dialog.as_mut().unwrap().active = 1; + assert_eq!(origin_planes(&app).len(), 3, "Mirror still offers every origin plane"); + app.dialog = None; + app.start("sketch.create"); + assert_eq!(origin_planes(&app).len(), 3, "Create Sketch still offers every origin plane"); + } + /// Primary rolls a live preview back for reselect, but not while a manipulator is dragged /// (same gate [`show`] uses via [`preview_should_roll_back`]). #[test] diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 0dd8cbded..5a3f31b1a 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -75,10 +75,22 @@ clicks and scrolling over the panel stay in the chat. The docked layout retains the last model choice for each agent and puts it back on the next session when still available. An endpoint's agent also keeps it as its default model. An agent that reports no choices shows no drop-down. When these model lists include more than one provider (Hermes and OpenCode name - each model `Provider · model`, or say `Provider: …` in its description), a provider drop-down - comes first and the model drop-down lists only that provider's models, without the provider in - front. It opens on the provider of the model in use; picking another provider changes nothing - until one of its models is chosen. Models with no provider named are listed under *Other*. + each model `Provider · model`, or say `Provider: …` in its description), the picker groups the + models under their providers, each a header with the count of its models that a click folds or + opens: the provider of the model in use starts open and the others folded, a search opens every + provider with a match, and a provider folded by hand stays folded until the picker closes. Models + with no provider named are listed under *Other*. An endpoint whose listing names its models + `Vendor: Model` under ids `vendor/model` (OpenRouter) is grouped by vendor the same way; its rows + read the model's name, and the id stays in the tooltip and in the search. +- **Picking a model.** Every model picker opens on a search box over the list the agent or endpoint + gave at this connection: SolidCraft has no list of its own. The search covers ids, names and + descriptions, and Enter takes the exact match or the first one shown. A model that isn't listed + can be typed: **Use custom: …** takes what is in the box, for an endpoint, an ACP agent with a + model option, or an older agent that listed models. An endpoint takes it as it is and keeps it as + its default model. An agent may refuse it: its model stays as it was and the chat says why. Only + an endpoint keeps a typed model for the next session; an agent gets it back only if it then + lists it. An endpoint that can't list its models (it has no such address, or refuses the key) + still shows its configured model, and the popup says why there are no others. - **Reasoning effort is not permissions.** The agent's thinking setting does not change SolidCraft's Ask / Edits / All approval policy. Reasoning options belong to the current session; changing them here does not rewrite OpenCode's configuration or another OpenCode session. @@ -246,16 +258,27 @@ Grok Build also supports `XAI_API_KEY` for users who choose API authentication. - **Custom command:** any other program that speaks ACP on stdin and stdout, such as `my-agent --acp`. SolidCraft starts it directly, not through a shell. - **OpenAI-compatible API:** a preset (Ollama `http://localhost:11434/v1`, LM Studio - `http://localhost:1234/v1`, OpenAI, Mammouth AI `https://api.mammouth.ai/v1`, OpenCode Go `https://opencode.ai/zen/go/v1`) or a custom URL, the model name, and an optional key. + `http://localhost:1234/v1`, OpenClaw `http://localhost:18789/v1`, OpenAI, Mammouth AI + `https://api.mammouth.ai/v1`, OpenCode Go `https://opencode.ai/zen/go/v1`, OpenRouter + `https://openrouter.ai/api/v1`) or a custom URL, the model name, and an optional key. OpenCode Go models are routed to their endpoint by themselves (`/responses`, `/messages` or Gemini for those families, `/chat/completions` for the rest), each conversation request carrying the session header Go asks for, so one preset covers every model. A model the list does not know is retried on the next protocol when Go names the mismatch. + For OpenClaw, turn on its chat endpoint (`gateway.http.endpoints.chatCompletions.enabled` in its + config) and use its gateway token as the key; the models it lists are its agents, such as `openclaw/default`. - **Anthropic-compatible API:** a preset (Anthropic) or a custom URL, for an endpoint that speaks the Anthropic Messages API (`{base}/v1/messages`). This covers Anthropic itself and providers that offer an Anthropic-compatible endpoint, such as DeepSeek and Qwen. +- The **Model** picker lists the endpoint's models, without a key where the endpoint allows that + (OpenRouter does), once you leave the address and key fields; opening it asks again after a + failure. You can also type a model. +- An endpoint's card under Preferences → AI → **Agents** has the same **Model** picker. While the + agent isn't running, opening the picker lists the models (just viewing the page asks nothing), + and a pick becomes the model for its next connection. While it runs, a pick changes the chat's + model at once. - The key goes into the system keychain (Keychain on macOS, Credential Manager on Windows, the Secret Service on Linux) and is only ever sent over HTTPS or to this computer. **Test** asks an OpenAI-compatible endpoint for its models; an Anthropic-compatible one gets a short message, @@ -478,3 +501,5 @@ the agent and puts your permission setting back. - `--markdown` writes the issue's comment template filled in; add the quantization, download size, and runtime before you post it. `--json` keeps each task's failed rules, conversation, and design before and after. Both files are rewritten after every task. + +The show/hide shortcut defaults to Ctrl+Shift+A (Cmd+Shift+A on macOS). Change, clear or reset **Toggle Assistant** (`ui.assistant`) in Preferences → Shortcuts. The binding is saved with the other keyboard shortcuts; the assistant button tooltip follows it. Disabling AI features also disables the toggle. diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index 8dfabe556..afc9ce8ac 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -397,6 +397,11 @@ off. A STEP or mesh file picked there is inserted as **Insert STEP** or **Insert Mesh** would. The part's solid bodies come in as they sit in that design, and they are kept in the assembly, so it opens even without the part file. The link is stored relative to the assembly's folder once the assembly is saved. +For scripts, `translate: [x,y,z]` places the design's origin in millimetres from the destination +parent's origin (the active component unless `parent` is supplied). It defaults to `[0,0,0]`. +With `reuse: true`, insertion reuses the existing linked component but uses the same coordinates; +it does not inherit another occurrence's position or rotation. For example, inserts at +`[20,0,0]` and `[40,0,0]` place the two origins at 20 and 40 mm, even when the second reuses the link. After the part file changes, **Update Links** (`component.update_links`) reads it again. An assembly that opens, or whose tab comes back to the front, does that by itself for the parts whose files changed since it last read them, whether the part was saved in another tab, another window or by diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md index f1e1d1b9c..0f5b1bdce 100644 --- a/docs/book/src/guide/features.md +++ b/docs/book/src/guide/features.md @@ -289,7 +289,7 @@ edited with the sketch commands. Expressions are text (`"30"`, `"30 mm"`, `"widt ```json {"command": "timeline.inspect", "params": {"feature": "Slab"}} -→ {"type": "ExtrudeFeature", +→ {"type": "extrude", "type_name": "ExtrudeFeature", "definition": {"sketch": 1, "profiles": {"type": "all"}, "operation": "new_body", "extent": {"distance": "10", "direction": "positive"}}, "inputs": [{"label": "Distance", "param": "d1", "expression": "10", "unit": "mm"}], …} diff --git a/docs/book/src/reference/glossary.md b/docs/book/src/reference/glossary.md index 7cb85b277..83581c790 100644 --- a/docs/book/src/reference/glossary.md +++ b/docs/book/src/reference/glossary.md @@ -519,8 +519,8 @@ Search lists both under the same name, and the label lookup gives both the same ## A feature's type A feature type has one name: its design-file key, such as `sheet_flange`. The label (Flange) is -its display name. Replies and scripts should use the design-file key; today `timeline.inspect` -reports a different name (`EdgeFlangeFeature`), so a script can't match one against the other. +its display name. Replies and scripts use the design-file key (`timeline.inspect` reports both +`type: "sheet_flange"` and `type_name: "EdgeFlangeFeature"`). ## Open questions for the maintainer diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 43440ed5a..78d8ac7b6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -372,11 +372,11 @@ no box selection. | Method | Params | Notes | |---|---|---| -| `ui.inspect` | — | UI state, pending file picker (`file_picker_busy`; compatibility alias `file_dialog_open`, no path), what is hidden (`visibility`: bodies, origin and construction items, sketches, joints (`hidden_joints`, joint ids); set it with the `browser.visibility` command), viewport rect, camera, active tool/dialog, the status line (`status`: text and whether it is an error), hover, renderer, timings, what the GPU drew last frame (`draw`: `draw_calls`, `triangles`, `line_segments`, `supersampled`; null without a GPU) and the graphics `adapter`, live preview (`active`, `busy`, `error`, `ms`, bodies it stands in for) | +| `ui.inspect` | — | UI state, pending file picker (`file_picker_busy`; compatibility alias `file_dialog_open`, no path), what is hidden (`visibility`: bodies, origin and construction items, sketches, joints (`hidden_joints`, joint ids); set it with the `browser.visibility` command), viewport rect, camera, the active tool (its command id), the open dialog (`dialog`, below), the windows open beside the model (`windows`, each named by what opens it: the `ui.start` command `parameters.change`, `document.metadata`, `sketch.inspect`, `assembly.bom` or `material.properties.validate`, or the `ui.help` item `about`, `updates`, `shortcuts`, `crashes`, `report`, or `messages`), what is under the pointer (`hover`, in the form of a selection item: `{"type": "edge", "body", "index", "mid", "point"}`, or null), the status line (`status`: text and whether it is an error), renderer, timings, what the GPU drew last frame (`draw`: `draw_calls`, `triangles`, `line_segments`, `supersampled`; null without a GPU) and the graphics `adapter`, live preview (`active`, `busy`, `error`, `ms`, bodies it stands in for) | | `ui.set` | any `UiState` field (`tab`, `perspective`, `showGrid`, `dark`, `layout`, …), and the browser's view of the design, saved with it: `showOrigin` (the Origin folder's eye), `showSketches` (the design's Sketches folder, `c0/sketches` in `hiddenFolders`), `hiddenBodies`, `hiddenOrigin`, `hiddenSketches`, `shownSketches`, `hiddenJoints`, `hiddenFolders`, `hiddenProfiles`, `shownDims`, `lockedBodies` (whole lists; `browser.visibility` changes single items) | `dark: false` switches to the light theme; `layout: "floating"` (default) or `"compact"` (`"docked"` is also accepted) selects the transient shell layout without saving a preference. Scenarios use `{"call":"ui.set","params":{"layout":"docked"}}` | | `ui.view` | `view`: `front`, `back`, `top`, `bottom`, `left`, `right`, `iso`, `home`, `fit`; `animate` (bool, default false: snap) | | | `ui.camera` | `target?`: `[x, y, z]` (mm), `yaw?`, `pitch?`, `roll?` (radians), `distance?` (mm), `fov?`, `up?`; `fit?`: `true`, `false` or `[occurrence id or name…]` (`root`: the bodies outside every component) | the viewport's orbit camera: it looks at `target` from `distance` away; `yaw` 0 looks along +Y (from the front), `pitch` is the elevation (±π/2: straight down or up), `roll` turns the image. Fields given are set first (the others keep their values), then `fit` frames the listed occurrences (or everything), keeping the direction. The reply, passed back, sets the same view again, so a framing can be stored and replayed. `fov` is the angle the view is drawn with: 0 (parallel) with Perspective view off or while a sketch is open, else `perspective_fov`; in Render, the Render camera's own. `fov` and `up` follow the perspective setting (`ui.set`), its angle (`ui.prefs {perspective_fov}`) and the up axis preference (`ui.prefs`) and can't change here; a refused field changes nothing | -| `ui.start` | `command`, `params?` | like a toolbar click: starts the sketch tool or dialog for the command. `params` sets what the dialog opens on, and nothing runs until OK: `joint.drive` takes `joint` (id or name; without it, the joint picked in the browser, else the first joint that moves; a rigid joint opens to say why it has nothing to drive, with an Edit Joint button, handle `drive:edit_joint`) and `values` (numbers in degrees or millimetres, or expressions); `motion.study` takes `study` (id or name), which opens that study to edit and chart. A command that takes no params is refused before it starts; a param the dialog doesn't take is refused and the dialog closes | +| `ui.start` | `command`, `params?` | like a toolbar click: starts the sketch tool or dialog for the command. `params` sets what the dialog opens on, and nothing runs until OK: `joint.drive` takes `joint` (id or name; without it, the joint picked in the browser, else the first joint that moves; a rigid joint opens to say why it has nothing to drive, with an Edit Joint button, handle `drive:edit_joint`) and `values` (numbers in degrees or millimetres, or expressions); `motion.study` takes `study` (id or name), which opens that study to edit and chart. A command that takes no params is refused before it starts; a param the dialog doesn't take is refused and the dialog closes. Replies what it opened: `tool`, `dialog` and `windows` as `ui.inspect` gives them, `status` (where a command that starts nothing says why), and `pending: true` when the start waits for the history to compute and opens on a later frame | | `ui.click` | `x`, `y` (screen points), `button?`: left/right/middle, `shift?`, `ctrl?`, `double?` | real pointer input | | `ui.move` | `x`, `y`, `shift?`, `alt?`, `ctrl?`, `cmd?` | pointer movement without a button; modifiers apply until the next synthetic move/click; a move with omitted modifiers releases them. With `nav: "touchpad"`, Shift pans and Alt/Option orbits. | | `ui.drag` | `x0`, `y0`, `x1`, `y1`, `via?`, `button?`, `shift?`, `ctrl?`, `steps?`, `hold?`, `hold_end?` | press, move, release; `via` is a list of `[x, y]` points passed through on the way (`steps` moves to each); a left drag on the model is a box selection (left to right: window, right to left: crossing), or with `lassoSelect` on (`ui.set`, the SELECT panel's Lasso) a freehand lasso that takes what is wholly inside it; with OpenSCAD navigation, plain left-drag on empty space orbits, Shift+left-drag box-selects, and drags starting on sketch geometry edit it; `hold` keeps the button down that many frames first (a right press-and-hold opens the marking menu, releasing over a direction picks it), `hold_end` that many frames at the end (a sketch drag shows its snap) | @@ -393,7 +393,7 @@ no box selection. | `ui.at` | `world: [x,y,z]` \| `sketch: [x,y]` \| `plane: "XY"` \| `axis: "Z"` \| `dimension: "d1"` (its value text) \| `handle: "arrow"` (a manipulator handle, see `scenario::publish_handle`) | the screen point (a scenario step's target; see `crates/ui-egui/src/scenario.rs`) | | `ui.pick` | `pixels?: [[x,y]…]`, `rays?: [{origin, dir}…]`, `frame?: "window"\|"model"`, `width?`, `height?`, `edges?` (default true), `edge_px?` (default 6), `all?`, `include_ghosted?` | read-only geometry under each pixel or ray (#6304): one entry per input, `null` where nothing is hit — body, face index, exact world `point` and outward `normal`, `depth`, `occurrence`/`component` for placed parts, `edge`/`vertex` within `edge_px` of a pixel, `section_cap: true` on a cut face. `window` pixels are physical pixels of a window screenshot; `model` pixels are pixels of a `ui.render` of `width`×`height` (default 960×600), so it works headless. As `view.pick` through `engine.execute`/`engine.batch`. See `crates/ui-egui/src/view_pick.rs` | | `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:` (the button alone: `button:`; a drop-down row: `dropdown:`, highlighted `dropdown_hot:`, its pin `dropdown_pin:`; Customize Toolbar's check boxes `customize:`), ribbon tabs `tab:` (MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW, SHEET METAL, WELDMENTS; contextual SKETCH; workspace RENDER), the toolbar menu button `ribbon:add_tab`, the hint when every tab is hidden `ribbon:tabs_hidden`, Preferences tab check boxes `prefs:toolbar_tab:`, panel labels `panel::` (also `ribbon:section::

`), document overflow list `tab:overflow`, workspace column `ribbon:workspace`, command-search launcher `ribbon:search`, browser rows `row: