Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.4

0.11.4 / src / sketch_editor.luc

## Editing a Sketch node in the viewport, Fusion 360's way
## (docs/research/FUSION-SKETCH-STUDY.md): while a Sketch node is selected
## and displayed, the viewport draws its entities on its plane (fully
## constrained ones white, free ones blue, construction orange), and the
## marking menus (hold A, S or D: CREATE, MODIFY, CONSTRAINTS) pick a tool.
##
## A tool is used once, then Select again (Line chains from its last end
## until Esc). Drawing tools are click by click; the cursor snaps through
## the snapping layer (snapping.luc: points, middles, crossings, curves,
## the grid; a snapped point is the same point, or held on its curve), and
## a line drawn near level or upright becomes horizontal or vertical.
## Holding Cmd (Ctrl elsewhere) places freely. Constraint tools take their
## entities in order, the first the reference (sketch_constrain.luc);
## Sketch Dimension takes one entity or two, then a click in empty space.
## Select picks entities (Shift adds) and drags points, which snap and
## are held where they are let go. Delete removes the selection, X makes
## it construction, Q is Select.
##
## The editor works on a live CadSketch read from the node; each finished
## action writes it back as one undo step (commit), and an undo or a change
## from elsewhere reads the node again (sync).
from sketch_chains import chain_of
from snapping import SnapMark, grid_step, on_grid, stepped, sketch_kind_name
from edit_types import point_level, edge_level, face_level
from luce_cad.sketch import CadSketch, CadProjection
from luce_cad.cad_geometry import CadGeometry
from luce_ui.ui import Event
from luce_window.input import EventKind, Key
from workspace import Workspace
from sketch_node import SketchFrame, node_frame
from sketch_frames import FrameCache
import sketch_tools
import view_projection
from luce_std import math
import sketch_constrain
import sketch_kinds
from sketch_kinds import coincident, on_curve, horizontal, vertical, midpoint, point_kind, line_kind

## How near the cursor snaps, in points on screen.
let snap_reach = 9.0
## How near level or upright a drawn line is made so (radians, 3°).
let level_angle = 0.05235987755982988

pub class SketchEditor:
    let w: Workspace
    ## The node edited and the text the live sketch was read from.
    var node: int = -1
    var text: str = ""
    var values: list[float]
    pub var sketch: CadSketch? = none
    pub var frame: SketchFrame
    pub let frames: FrameCache
    ## The input body's stamp the sketch was read with.
    var body_was: str = ""
    ## Its edges cast for Project, and what they were cast from.
    var projected: CadProjection? = none
    var projected_key: str = ""
    ## The tool in use (set_tool keeps the workspace's sketch_tool the same).
    pub var tool: str = "Select"
    ## A drawing tool's placed points: plane coordinates, and the point
    ## entity each is (-1: not made yet).
    pub var clicks: list[list[float]]
    pub var click_snaps: list[int]
    ## What each click snapped to: its kind (snapping.luc's, CadSketch.snap:
    ## 1 point, 2 middle, 4 crossing, 8 curve; 0 none or the grid) and a
    ## crossing's second curve.
    var click_kinds: list[int]
    var click_others: list[int]
    ## Each click's point once made (made_point), else -1.
    var made: list[int]
    ## The cursor on the plane, snapped, and what it snapped to (-1: none).
    pub var cursor: list[float]
    pub var snap: int = -1
    var snap_kind: int = 0
    var snap_other: int = -1
    pub var free_placing: bool = false
    pub var hover: int = -1
    pub var selection: list[int]
    ## A constraint or dimension tool's picks so far.
    pub var picks: list[int]
    ## A point being dragged by Select.
    var dragging: int = -1
    var drag_moved: bool = false
    ## Counts changes to the live sketch, so drawings are made again.
    pub var revision: int = 0
    ## A new dimension's value is typed here: called with its constraint and
    ## where the click placing it was (the viewport's points).
    pub var on_value: func(int, float, float) -> unit!? = none
    ## A drawing tool's clicks are in (sketch_create.luc finishes it), set
    ## by the view.
    pub var on_finish: func() -> unit!? = none
    ## Ask for a number (a tool's value typed): its label, the value to
    ## start from, and what takes the answer.
    pub var on_ask: func(str, float, func(float) -> unit!) -> unit!? = none
    ## The distance the last Offset was.
    pub var last_offset: float = 5.0
    ## The Text tool's clicks are in: ask what it says (place_text).
    pub var on_text: func() -> unit!? = none
    ## Where that text goes: its anchor (x, y), height and the point its
    ## anchor snapped to (-1: none).
    pub var text_at: list[float]
    ## A MODIFY tool's click (sketch_modify.luc; Shift held), set by the
    ## view so this module need not know it.
    pub var on_modify: func(bool) -> unit!? = none
    ## A click in the viewport (an open value box closes).
    pub var on_click: func() -> unit!? = none
    var node_was: int = -1
    pub var pointer_x: float = 0.0
    pub var pointer_y: float = 0.0
    ## Screen size of the last event, and the reach of a snap in sketch units.
    var width: float = 1.0
    var height: float = 1.0
    pub var reach: float = 1.0

    pub func init(self, w: Workspace):
        self.text_at = []
        self.w = w
        self.values = []
        self.frame = node_frame([1.0, 0.0])
        self.frames = FrameCache()
        self.clicks = []
        self.click_snaps = []
        self.click_kinds = []
        self.click_others = []
        self.made = []
        self.cursor = [0.0, 0.0]
        self.selection = []
        self.picks = []

    ## Whether a Sketch node is being edited: selected, displayed, enabled,
    ## and no tool prompt open.
    pub func active(self) -> bool:
        return self.w.sketching()

    ## Read the node again when it is another node, or its text or plane
    ## changed (an undo, the parameter panel).
    pub func sync(self) -> unit!:
        let node = self.w.selected() else return
        # The plane follows its face as the body upstream changes.
        let frame = self.frames.frame(self.w, node)
        if not frame.equals(self.frame):
            let moved = self.sketch != none and node.id == self.node
            self.frame = frame
            self.revision += 1
            # A new plane (a face picked): look straight at it.
            if moved:
                self.look_at()
        # Projected curves follow the input body: a new body reads again.
        _ = self.frames.body(self.w, node)
        let same = node.id == self.node and node.texts[0] == self.text and node.values[0] == (self.values + [0.0])[0] and node.values[1] == (self.values + [0.0, 0.0])[1] and self.frames.body_stamp() == self.body_was
        if same and self.sketch != none:
            return
        self.body_was = self.frames.body_stamp()
        # Another sketch than the one edited: its tool and selection go.
        if node.id != self.node and self.node >= 0:
            self.reset_tool()
            self.selection = []
            self.set_tool("Select")
        # What the pointer was over, and a tool's clicks and picks, belong to
        # the sketch read before (an undo, another node).
        self.hover = -1
        self.snap = -1
        self.reset_tool()
        self.node = node.id
        self.text = node.texts[0]
        self.values = [node.values[0], node.values[1]]
        let sketch = CadSketch.parse(self.text)
        if sketch.link_count() > 0:
            if let data = self.frames.body(self.w, node):
                if CadGeometry.model_count(data.geometry) > 0:
                    _ = sketch.relink(CadGeometry.model(data.geometry, 0), self.frame.origin, self.frame.u, self.frame.v)
        _ = sketch.solve()
        sketch.analyze()
        let entering = self.sketch == none or self.node_was != node.id
        self.node_was = node.id
        self.sketch = sketch
        if entering:
            self.look_at()
        let kept: list[int] = []
        for at in self.selection:
            if at < sketch.entity_count():
                kept.append(at)
        self.selection = kept
        self.revision += 1

    ## Look straight at the sketch plane (x right, y up, as its frame
    ## says), at the middle of what is drawn, as Fusion's Look At does.
    pub func look_at(self) -> unit!:
        let sketch = self.sketch else return
        let n = self.frame.normal()
        let view = self.w.view
        if math.abs(n.y) > 0.5:
            view.yaw = 0.0
            view.pitch = 1.5 if n.y > 0.0 else -1.5
        else:
            view.yaw = math.atan2(n.x, n.z)
            view.pitch = 0.0
        var low = [1.0e30, 1.0e30]
        var high = [-1.0e30, -1.0e30]
        for at in 0..<sketch.entity_count():
            if sketch.kind(at) == point_kind:
                low = [math.min(low[0], sketch.x(at)), math.min(low[1], sketch.y(at))]
                high = [math.max(high[0], sketch.x(at)), math.max(high[1], sketch.y(at))]
        if high[0] >= low[0]:
            view.target = self.frame.at((low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5)
            view.distance = math.max(20.0, 2.2 * math.max(high[0] - low[0], high[1] - low[1]))
        else:
            view.target = self.frame.origin
        view.update_camera()
        self.w.revision += 1

    ## Say `text` in the status line.
    pub func say(self, text: str):
        self.w.notice = text
        self.w.revision += 1

    ## Write the live sketch to the node as one undo step.
    pub func commit(self, label: str) -> unit!:
        let sketch = self.sketch else return
        let node = self.w.network.find(self.node) else return
        let text = sketch.text()
        if text == node.texts[0]:
            return
        self.w.perform(label, func () -> unit!:
            node.texts[0] = text
            self.w.network.invalidate(node.id)
            self.w.rebuild())
        self.text = text
        sketch.analyze()
        self.revision += 1
        # A tool is used once: what it made is in, so back to Select (Line
        # goes on from its end until Esc).
        if not (self.tool in ["Select", "Line"]):
            self.reset_tool()
            self.set_tool("Select")
            self.w.notice = self.hint()

    ## Pick tool `name` (Select, a drawing tool, a constraint tool or Sketch
    ## Dimension). A constraint tool with enough already selected applies
    ## to the selection at once.
    pub func choose(self, name: str) -> unit!:
        self.sync()
        self.reset_tool()
        self.set_tool(name)
        if name != "Select":
            self.w.last_sketch_tool = name
        if sketch_tools.constrains(name) and self.selection.length > 0:
            self.picks = self.selection.copy()
            if self.try_constraint():
                self.set_tool("Select")
        self.w.notice = self.hint()
        self.w.revision += 1

    ## The tool in use, here and on the workspace (the viewport's tool
    ## column shows it).
    func set_tool(self, name: str):
        self.tool = name
        self.w.sketch_tool = name

    func reset_tool(self):
        self.clicks = []
        self.click_snaps = []
        self.click_kinds = []
        self.click_others = []
        self.made = []
        self.picks = []
        self.dragging = -1

    ## The status line's hint for the current tool.
    pub func hint(self) -> str:
        if self.tool == "Select":
            return "Sketch: hold A, S or D for its tools, or drag points (Delete removes, X makes construction)"
        if self.tool == "Project":
            return "Project: click an edge of the input body to bring its shadow into the sketch (it follows the body)"
        if sketch_tools.draws(self.tool):
            return f"{self.tool}: click to place (Cmd places freely), Esc ends"
        if self.tool in ["Trim", "Extend", "Break"]:
            return f"{self.tool}: click a curve where it should change"
        if self.tool in ["Fillet", "Chamfer"]:
            return f"{self.tool}: click two lines meeting at a corner, or the corner"
        if self.tool == "Offset":
            return "Offset: click a curve (its chain goes), then to its side"
        if self.tool == "Move/Copy":
            return "Move/Copy: pick what moves, then click from and to (Shift copies)"
        if self.tool == "Sketch Scale":
            return "Sketch Scale: pick what scales, then click the base point, a point, and where it goes"
        if self.tool == "Sketch Dimension":
            return "Sketch Dimension: click a line, circle or arc, or two entities, then click where the dimension goes"
        return f"{self.tool}: pick the entities to constrain, the reference first"

    ## The viewport's events while editing; whether one was used.
    pub func event(self, event: Event, width: float, height: float) -> bool!:
        if not self.active() or event.alt:
            return false
        self.sync()
        self.width = width
        self.height = height
        let sketch = self.sketch else return false
        if event.kind == EventKind.key_down:
            return self.key(event)
        if event.kind == EventKind.pointer_moved:
            self.track(event.x, event.y, event.meta or event.control)
            if self.dragging >= 0:
                if sketch.drag(self.dragging, self.cursor[0], self.cursor[1]):
                    sketch.analyze()
                self.drag_moved = true
                self.revision += 1
            return true
        if event.kind == EventKind.pointer_up and event.button == 0 and self.dragging >= 0:
            let dragged = self.dragging
            self.dragging = -1
            if self.drag_moved:
                # Let go on a point or a curve it snapped to: held there.
                if self.snap >= 0 and self.snap != dragged:
                    # Exactly where it snapped, then held there.
                    sketch.place(dragged, self.cursor[0], self.cursor[1])
                    if self.snap_kind == 1:
                        _ = sketch.constrain(coincident, dragged, self.snap)
                    elif self.snap_kind == 8 and sketch_kinds.holds_points(sketch.kind(self.snap)):
                        _ = sketch.constrain(on_curve, dragged, self.snap)
                    if not sketch.solve():
                        sketch.unconstrain(sketch.constraint_count() - 1)
                        _ = sketch.solve()
                self.commit("Drag sketch point")
            return true
        if event.kind != EventKind.pointer_down or not event.inside:
            return false
        if let clicked = self.on_click:
            clicked()
        if event.button == 1:
            # A right click ends what is being drawn.
            self.reset_tool()
            return true
        if event.button != 0:
            return false
        self.track(event.x, event.y, event.meta or event.control)
        self.pointer_x = event.x
        self.pointer_y = event.y
        if self.tool == "Select":
            self.select_at(event.shift)
        elif self.tool == "Project":
            self.project_at()
        elif sketch_tools.draws(self.tool):
            self.place()
        elif sketch_tools.modifies(self.tool) or sketch_tools.copies(self.tool):
            if let act = self.on_modify:
                act(event.shift)
        else:
            self.pick()
        return true

    ## Keys: a tool's letter, Esc, Delete, X.
    func key(self, event: Event) -> bool!:
        if event.key == Key.escape:
            if self.clicks.length > 0 or self.picks.length > 0:
                self.reset_tool()
            elif self.tool != "Select":
                self.choose("Select")
            else:
                self.selection = []
            self.revision += 1
            return true
        if event.key == Key.enter:
            self.finish_open()
            self.reset_tool()
            return true
        if event.key in [Key.delete, Key.backspace]:
            self.remove_selection()
            return true
        # A held key's repeats pick nothing.
        if event.repeated:
            return false
        let letter = key_letter(event.key)
        # Q is Select here as everywhere.
        if letter == "Q":
            self.choose("Select")
            return true
        if letter == "X" and self.selection.length > 0:
            let sketch = self.sketch else return true
            let construction = not sketch.construction(self.selection[0])
            for at in self.selection:
                if sketch.kind(at) != point_kind:
                    sketch.set_construction(at, construction)
            self.commit("Toggle construction")
            return true
        let name = sketch_tools.tool_for_key(letter)
        if name != "":
            self.choose(name)
            return true
        return false

    ## Where the pointer at (`x`, `y`) is on the plane, snapped to a point or
    ## curve within reach unless `free`.
    func track(self, x: float, y: float, free: bool) -> unit!:
        let sketch = self.sketch else return
        let normal = self.frame.normal()
        let here = view_projection.plane(self.w, x, y, self.width, self.height, self.frame.origin, normal)
        let beside = view_projection.plane(self.w, x + snap_reach, y, self.width, self.height, self.frame.origin, normal)
        self.reach = math.max(1e-6, here.subtract(beside).length())
        self.cursor = self.frame.coordinates(here)
        self.free_placing = free
        self.snap = -1
        self.snap_kind = 0
        self.snap_other = -1
        self.hover = sketch.pick(self.cursor[0], self.cursor[1], self.reach, self.pick_filter())
        # Tools that place, and a dragged point, snap; tools that pick (Trim,
        # the constraints) read the pointer as it is.
        let places = sketch_tools.places(self.tool) or self.dragging >= 0
        if free or not places:
            return
        # The snapping layer: what the sketch has near the pointer (not the
        # point just placed or dragged, nor what is drawn on it), else the
        # grid.
        let snaps = self.w.snaps
        let step = grid_step(self.w.view.distance)
        let skip = self.dragging if self.dragging >= 0 else (self.made[-1] if self.made.length > 0 else -1)
        let found = sketch.snap(self.cursor[0], self.cursor[1], self.reach, snaps.sketch_mask(), skip)
        var mark = ""
        if found != 0:
            self.snap = sketch.snap_entity()
            self.snap_kind = found
            self.snap_other = sketch.snap_other()
            self.cursor = [sketch.snap_x(), sketch.snap_y()]
            mark = sketch_kind_name(found)
        # A line's second point near level or upright lines up.
        if self.tool == "Line" and self.clicks.length > 0 and self.snap < 0:
            let start = self.clicks[-1]
            let dx = self.cursor[0] - start[0]
            let dy = self.cursor[1] - start[1]
            if math.abs(dy) <= math.abs(dx) * math.tan(level_angle):
                self.cursor = [stepped(self.cursor[0], step, snaps.grid()), start[1]]
                mark = "Level"
            elif math.abs(dx) <= math.abs(dy) * math.tan(level_angle):
                self.cursor = [start[0], stepped(self.cursor[1], step, snaps.grid())]
                mark = "Upright"
        if mark == "" and snaps.grid():
            self.cursor = [on_grid(self.cursor[0], step), on_grid(self.cursor[1], step)]
            mark = "Grid"
        if mark != "":
            self.w.snap_mark = SnapMark(self.frame.at(self.cursor[0], self.cursor[1]), mark)

    ## A point at the cursor: the snapped point itself, else a new point (on
    ## the snapped curve, constrained there).
    func cursor_point(self) -> int!:
        let sketch = self.sketch else return -1
        if self.snap >= 0 and sketch.kind(self.snap) == point_kind:
            return self.snap
        return self.snapped_point(self.cursor, self.snap, self.snap_kind, self.snap_other)

    ## A drawing tool's click.
    func place(self) -> unit!:
        let sketch = self.sketch else return
        if self.tool == "Point":
            _ = self.cursor_point()
            self.commit("Sketch point")
            return
        # Clicking the last point again ends a chain (a spline: makes it;
        # its points are made only then, so there, where it was).
        let again = self.clicks.length > 0 and ((self.snap >= 0 and self.snap == self.click_snaps[-1]) or
                    (sketch_tools.open_ended(self.tool) and math.hypot(self.cursor[0] - self.clicks[-1][0], self.cursor[1] - self.clicks[-1][1]) <= self.reach))
        if again:
            self.finish_open()
            self.reset_tool()
            return
        self.clicks.append(self.cursor.copy())
        self.click_snaps.append(self.snap)
        self.click_kinds.append(self.snap_kind)
        self.click_others.append(self.snap_other)
        self.made.append(-1)
        self.revision += 1
        if self.tool == "Line" and self.clicks.length == 2:
            let a = self.made_point(0)
            let b = self.made_point(1)
            let line = sketch.add_line(a, b)
            if sketch.y(a) == sketch.y(b):
                _ = sketch.constrain(horizontal, line)
            elif sketch.x(a) == sketch.x(b):
                _ = sketch.constrain(vertical, line)
            self.commit("Sketch line")
            # Chain from the end, that point itself.
            self.clicks = [self.clicks[1]]
            self.click_snaps = [b]
            self.click_kinds = [1]
            self.click_others = [-1]
            self.made = [b]
        elif not sketch_tools.open_ended(self.tool) and self.clicks.length == sketch_tools.clicks_for(self.tool):
            if let finish = self.on_finish:
                finish()
            self.reset_tool()

    ## An open-ended tool (a spline) with two clicks or more: make it.
    func finish_open(self) -> unit!:
        if sketch_tools.open_ended(self.tool) and self.clicks.length >= 2:
            if let finish = self.on_finish:
                finish()

    ## The input body's edges cast onto the plane, while Project is the
    ## tool (made again when the body or the plane moves); none without a
    ## body.
    pub func projection(self) -> CadProjection?!:
        let node = self.w.network.find(self.node) else return none
        let data = self.frames.body(self.w, node) else return none
        if CadGeometry.model_count(data.geometry) == 0:
            return none
        let key = f"{self.frames.body_stamp()}|{self.frame.key()}"
        if key != self.projected_key or self.projected == none:
            self.projected = CadProjection.of(CadGeometry.model(data.geometry, 0), self.frame.origin, self.frame.u, self.frame.v)
            self.projected_key = key
        return self.projected

    ## The edge whose shadow is under the cursor, or -1.
    pub func projected_edge(self) -> int!:
        let cast = self.projection() else return -1
        return cast.nearest(self.cursor[0], self.cursor[1], self.reach)

    ## Project's click: the edge under the cursor brought in, fixed and
    ## linked.
    func project_at(self) -> unit!:
        let sketch = self.sketch else return
        let found = self.projection()
        if found == none:
            self.say("Project casts the edges of the Sketch's input body: connect a body to it")
            return
        let cast = found else return
        let edge = cast.nearest(self.cursor[0], self.cursor[1], self.reach)
        if edge < 0:
            return
        var failed = ""
        _ = sketch.project(cast, edge) catch failure:
            failed = failure.message
            recover -1
        if failed != "":
            self.say(failed)
            return
        _ = sketch.solve()
        self.commit("Project")

    ## The Text tool's words: the text where its clicks put it, as one undo.
    pub func place_text(self, content: str) -> unit!:
        let sketch = self.sketch else return
        if self.text_at.length < 4 or content.trim() == "":
            return
        let snapped = int(self.text_at[3])
        let anchor = snapped if snapped >= 0 and sketch.kind(snapped) == point_kind else sketch.add_point(self.text_at[0], self.text_at[1])
        _ = sketch.add_text(anchor, self.text_at[2], content)
        self.text_at = []
        self.commit("Text")

    ## Click `at`'s point, made once: the point it snapped to, else a new
    ## one there (on the curve it snapped to).
    pub func made_point(self, at: int) -> int!:
        let sketch = self.sketch else return -1
        if self.made[at] >= 0:
            return self.made[at]
        let point = self.snapped_point(self.clicks[at], self.click_snaps[at], self.click_kinds[at], self.click_others[at])
        self.made[at] = point
        return point

    ## A point at `place` as what it snapped to holds it: that point itself;
    ## a new one at a line's middle, on two crossing curves or on a curve
    ## (held there by its constraints); else a free new one.
    func snapped_point(self, place: list[float], snapped: int, kind: int, other: int) -> int!:
        let sketch = self.sketch else return -1
        if snapped >= 0 and sketch.kind(snapped) == point_kind:
            return snapped
        let point = sketch.add_point(place[0], place[1])
        if snapped < 0:
            return point
        if kind == 2 and sketch.kind(snapped) == line_kind:
            _ = sketch.constrain(midpoint, point, snapped)
            return point
        for curve in [snapped, other if kind == 4 else -1]:
            if curve >= 0 and sketch_kinds.holds_points(sketch.kind(curve)):
                _ = sketch.constrain(on_curve, point, curve)
        return point

    ## What Select hovers at the selection level (Points: points, Lines and
    ## Shapes: curves); other tools pick either (CadSketch.pick's `only`).
    func pick_filter(self) -> int:
        # Tools that work on curves pick only curves (not a crossing's or
        # an end's point under the cursor).
        if sketch_tools.picks_curves(self.tool):
            return 2
        if self.tool != "Select":
            return 0
        if self.w.sketch_level == point_level:
            return 1
        return 2 if self.w.sketch_level in [edge_level, face_level] else 0

    ## Select's click: the entity under the cursor, at the Shapes level its
    ## whole chain (Shift adds or takes away), or nothing; a point pressed
    ## starts a drag.
    func select_at(self, extend: bool) -> unit!:
        let sketch = self.sketch else return
        let at = self.hover
        if at >= 0 and sketch.kind(at) == point_kind:
            self.dragging = at
            self.drag_moved = false
        let picked = chain_of(sketch, at) if at >= 0 and self.w.sketch_level == face_level and sketch.kind(at) != point_kind else [at]
        if at < 0:
            if not extend:
                self.selection = []
        elif extend:
            if at in self.selection:
                for each in picked:
                    self.selection = without(self.selection, each)
            else:
                for each in picked:
                    if not (each in self.selection):
                        self.selection.append(each)
        else:
            self.selection = picked
        self.revision += 1

    ## A constraint or dimension tool's click.
    func pick(self) -> unit!:
        let sketch = self.sketch else return
        let at = self.hover
        if self.tool == "Sketch Dimension":
            if at >= 0 and self.picks.length < 2 and not (at in self.picks):
                self.picks.append(at)
            elif self.picks.length > 0:
                self.dimension()
                self.picks = []
            self.revision += 1
            return
        if at < 0:
            return
        self.picks.append(at)
        if self.try_constraint():
            self.picks = []
        self.revision += 1

    ## Apply the constraint tool to its picks when they are enough; whether
    ## they were (applied, or refused as conflicting).
    func try_constraint(self) -> bool!:
        let sketch = self.sketch else return false
        let made = sketch_constrain.constrain_picks(sketch, self.tool, self.picks)
        if made == sketch_constrain.more_picks:
            return false
        if made == sketch_constrain.unfixed:
            self.commit("Unfix")
            return true
        if made == sketch_constrain.no_fit:
            # Picks that do not fit: start again from the last.
            self.picks = [self.picks[-1]]
            self.w.notice = f"{self.tool} does not join those: pick again"
            return false
        self.settle(made)
        return true

    ## Solve after constraint `constraint` was added: kept and written back
    ## when it holds, else taken away with Fusion's over-constrained notice.
    func settle(self, constraint: int) -> unit!:
        let sketch = self.sketch else return
        let solved = sketch.solve()
        sketch.analyze()
        if not solved or sketch.conflicting_count() > 0:
            sketch.unconstrain(constraint)
            _ = sketch.solve()
            sketch.analyze()
            self.w.notice = "Sketch geometry is over constrained"
            self.revision += 1
            return
        self.commit(self.tool)

    ## Sketch Dimension's placing click: its picks measured
    ## (sketch_constrain.measure); its value is then typed where it was
    ## placed, or edited in the parameter panel.
    func dimension(self) -> unit!:
        let sketch = self.sketch else return
        let made = sketch_constrain.measure(sketch, self.picks)
        if made < 0:
            self.w.notice = "Sketch Dimension measures a line, a circle, an arc, two points, a point and a line, or two lines"
            return
        # A dimension the sketch already has is kept as a driven one.
        if not sketch.solve():
            sketch.set_driven(made, true)
        sketch.analyze()
        if sketch.conflicting_count() > 0 or sketch.redundant_count() > 0:
            sketch.set_driven(made, true)
        self.commit("Sketch dimension")
        if not sketch.driven(made):
            if let open = self.on_value:
                open(made, self.pointer_x, self.pointer_y)

    ## Delete: the selected entities (and what is drawn on them).
    func remove_selection(self) -> unit!:
        let sketch = self.sketch else return
        if self.selection.length == 0:
            return
        # Highest first, as removing renumbers what follows.
        let chosen = self.selection.copy()
        chosen.sort()
        var at = chosen.length
        while at > 0:
            at -= 1
            if chosen[at] < sketch.entity_count():
                sketch.remove(chosen[at])
        self.selection = []
        self.commit("Delete sketch entities")

## The letter key `key` types, upper case, or "".
func key_letter(key: Key) -> str:
    let keys = [Key.a, Key.b, Key.c, Key.d, Key.e, Key.f, Key.g, Key.h, Key.i, Key.j, Key.k, Key.l, Key.m, Key.n, Key.o, Key.p, Key.q, Key.r, Key.s, Key.t, Key.u, Key.v, Key.w, Key.x, Key.y, Key.z]
    let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for at in 0..<keys.length:
        if keys[at] == key:
            return letters[at..<at + 1]
    return ""

## `values` without `value`.
func without(values: list[int], value: int) -> list[int]:
    let kept: list[int] = []
    for v in values:
        if v != value:
            kept.append(v)
    return kept