Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.6

0.11.6 / src / network_view.luc

from luce_ui.ui import Widget, Layout, Constraints, Size, Event, Painter, Point, Font
from luce_gpu.gpu import RenderTarget, Rect, Color
from luce_window.input import EventKind, Key, ScrollUnit
from node import Node, waiting
from workspace import Workspace
from actions import Actions
from luce_std import math
from marquee import draw_box, dragged, operation_of
import theme
import time
from tool_icons import draw_icon
from edit_kinds import is_edit
import node_commands
import shader_nodes
from luce_ui import ui
from material_preview import MaterialPreview
import node_catalog
import levels
import network_wires
import cad_chain

pub let node_width: float = 96.0
pub let node_height: float = 40.0
## Inside a Material, shader nodes: a header, then a row a socket (outputs on
## the right, then inputs on the left), wired left to right.
let shader_width: float = 176.0
let shader_header: float = 24.0
let shader_row: float = 19.0

pub class NetworkView: Widget:
    let box: Layout
    let workspace: Workspace
    let actions: Actions
    let base_font: Font
    var font: Font
    pub var zoom: float = 1.0
    pub var pan_x: float = 0.0
    pub var pan_y: float = 0.0
    pub var pointer_x: float = 100.0
    pub var pointer_y: float = 70.0
    pub var on_search: func() -> unit!? = none
    ## A right click: the node under the pointer (picked first, unless it is
    ## among the picked nodes), or -1 on empty canvas; the panels open the
    ## node menu at the pointer.
    pub var on_menu: func(int) -> unit!? = none
    ## Whether the pointer is over the view (Paste puts nodes there).
    pub var pointer_inside: bool = false
    pub var on_inspect: func(int) -> unit!? = none
    var mode: str = ""
    var moving: int = -1
    var wire_node: int = -1
    var wire_port: int = -1
    var from_output: bool = true
    var start_x: float = 0.0
    var start_y: float = 0.0
    var last_x: float = 0.0
    var last_y: float = 0.0
    var node_x: float = 0.0
    var node_y: float = 0.0
    var space: bool = false
    ## Y is held: a drag cuts the wires it crosses (Houdini's Y-drag).
    var cutting: bool = false
    ## What the box does (0 replace, 1 add, 2 remove).
    var box_operation: int = 0
    var hovered: int = -1
    var last_click: int = 0
    var last_node: int = -1
    ## Frame the nodes at the next draw (a new scope shows them whole).
    var frame_pending: bool = false
    ## A move drags every picked node: their ids and where each started.
    var moving_ids: list[int]
    var moving_from: list[Point]
    ## The Material's look, while its shader nodes are shown (made at first use).
    var preview: MaterialPreview? = none

    pub func reset_scope(self) -> unit!:
        self.mode = ""
        self.hovered = -1
        self.pan_x = 20.0
        self.pan_y = 20.0
        self.zoom = 1.0
        self.last_node = -1
        self.frame_pending = true
        self.box.invalidate()

    pub func init(self, workspace: Workspace, actions: Actions, font: Font) -> unit!:
        self.workspace = workspace
        self.actions = actions
        self.base_font = font
        self.font = font
        self.moving_ids = []
        self.moving_from = []
        self.box = Layout()
        self.box.set_flex()
        self.box.set_interactive(true)
        self.box.set_focusable(true)
        self.box.set_accepts_tab(true)

    pub func layout(self) -> Layout:
        return self.box
    pub func measure(self, available: Constraints) -> Size!:
        return Size(460.0, 220.0)
    pub func to_graph(self, x: float, y: float) -> Point:
        return Point((x - self.pan_x) / self.zoom, (y - self.pan_y) / self.zoom)
    pub func to_screen(self, x: float, y: float) -> Point:
        return Point(x * self.zoom + self.pan_x, y * self.zoom + self.pan_y)
    ## Whether the network shown is a Material's shader nodes.
    func shading(self) -> bool:
        return self.workspace.network.in_material()

    ## Whether the network shown has wires: an object level has none (its
    ## nodes have no inputs, and their outputs feed nothing).
    func wired(self) -> bool:
        let graph = self.workspace.network
        return graph.level_of(graph.scope) != levels.object_level

    ## A node's box in graph units.
    func size_of(self, node: Node) -> Size:
        if not self.shading():
            return Size(node_width, node_height)
        let rows = shader_nodes.outputs(node.kind).length + shader_nodes.inputs(node.kind).length
        return Size(shader_width, shader_header + shader_row * float(rows) + 6.0)

    pub func port_point(self, node: Node, output: bool, port: int = 0) -> Point:
        if self.shading():
            let outputs = shader_nodes.outputs(node.kind).length
            let row = float(port) if output else float(outputs + port)
            return self.to_screen(node.x + (shader_width if output else 0.0), node.y + shader_header + shader_row * (row + 0.5))
        return self.to_screen(node.x + (node_width * 0.5 if output else node_width * float(port + 1) / float(node.inputs.length + 1)), node.y + (node_height if output else 0.0))

    func inside_node(self, node: Node, at: Point) -> bool:
        let size = self.size_of(node)
        return at.x >= node.x and at.x <= node.x + size.width and at.y >= node.y and at.y <= node.y + size.height

    pub func zoom_about(self, factor: float, x: float, y: float):
        let before = self.to_graph(x, y)
        self.zoom = math.max(0.3, math.min(2.5, self.zoom * factor))
        self.pan_x = x - before.x * self.zoom
        self.pan_y = y - before.y * self.zoom
        self.box.invalidate()

    pub func frame_all(self) -> unit!:
        let nodes = self.workspace.network.local_nodes()
        if nodes.length == 0:
            return
        # Geometry nodes' captions run to their right.
        let caption = 0.0 if self.shading() else 170.0
        var left = nodes[0].x
        var top = nodes[0].y
        var right = left + self.size_of(nodes[0]).width + caption
        var bottom = top + self.size_of(nodes[0]).height
        for node in nodes:
            let box = self.size_of(node)
            left = math.min(left, node.x)
            top = math.min(top, node.y)
            right = math.max(right, node.x + box.width + caption)
            bottom = math.max(bottom, node.y + box.height)
        let bounds = self.box.bounds()
        self.zoom = math.max(0.3, math.min(1.4, math.min((bounds.width - 80.0) / (right - left), (bounds.height - 70.0) / (bottom - top))))
        self.pan_x = (bounds.width - (right - left) * self.zoom) * 0.5 - left * self.zoom
        self.pan_y = (bounds.height - (bottom - top) * self.zoom) * 0.5 - top * self.zoom
        self.box.invalidate()

    pub func draw(self, target: RenderTarget) -> unit!:
        if self.frame_pending and self.box.bounds().width > 0.0:
            self.frame_pending = false
            self.frame_all()
        let size = target.size()
        let p = Painter(target)
        p.rectangle(Rect(0.0, 0.0, size.width, size.height), theme.backdrop())
        let step = 32.0 * self.zoom
        var x = self.pan_x - math.floor(self.pan_x / step) * step
        while x < size.width:
            var y = self.pan_y - math.floor(self.pan_y / step) * step
            while y < size.height:
                p.rectangle(Rect(x, y, 1.0, 1.0), theme.border())
                y += step
            x += step
        let wanted = float(int(math.max(8.0, self.base_font.size() * self.zoom)))
        if wanted != self.font.size():
            self.font = self.base_font if wanted == self.base_font.size() else Font(wanted)
        let graph = self.workspace.network
        let picked_wires = graph.selected_wires()
        for node in graph.local_nodes():
            for port in 0..<node.inputs.length:
                if let source = graph.find(node.inputs[port]):
                    self.wire(p, self.port_point(source, true, node.sources[port]), self.port_point(node, false, port), (node.id, port) in picked_wires)
        let shading = self.shading()
        let wired = self.wired()
        let picked = graph.selection()
        for node in graph.local_nodes():
            if shading:
                self.draw_shader_node(p, node, node.id in picked, size.width, size.height)
                continue
            let at = self.to_screen(node.x, node.y)
            let w = node_width * self.zoom
            let h = node_height * self.zoom
            if at.x + w + 170.0 * self.zoom < 0.0 or at.x > size.width or at.y + h < 0.0 or at.y > size.height:
                continue
            let selected = node.id in picked
            let radius = 10.0 * self.zoom if node_catalog.is_primitive(node.kind) else 3.0 * self.zoom
            let outline = 3.5 if node_catalog.holds_nodes(node.kind) else 1.5
            p.rounded_rectangle(Rect(at.x - outline, at.y - outline, w + outline * 2.0, h + outline * 2.0), theme.accent() if selected else (theme.text_muted() if self.hovered == node.id else theme.grey(78.0)), radius + outline)
            p.rounded_rectangle(Rect(at.x, at.y, w, h), theme.grey(64.0) if node.enabled else theme.tab_strip(), radius)
            if node.computing:
                p.rectangle(Rect(at.x, at.y + h - 3.0, w * math.max(0.02, math.min(1.0, node.progress)), 3.0), theme.accent())
            draw_icon(p, node.kind, at.x + 36.0 * self.zoom, at.y + 8.0 * self.zoom, 24.0 * self.zoom, theme.text() if node.enabled else theme.text_muted())
            let caption = node.name[0..<24] + "…" if node.name.length > 24 else node.name
            p.text(caption, at.x + 109.0 * self.zoom, at.y + (1.0 if self.zoom >= 0.65 else 10.0) * self.zoom, theme.text() if node.enabled else theme.text_muted(), self.font)
            let detail = (f"{node.phase} {int(node.progress * 100.0)}%" if node.progress > 0.0 else node.phase) if node.computing else ("ERROR" if node.failure != "" else (("waiting" if waiting(node.warning) else "WARNING") if node.warning != "" else ("bypassed" if not node.enabled else ("frozen" if node.frozen != "" else (f"{node.edits.length} edits" if is_edit(node.kind) else "geometry")))))
            if self.zoom >= 0.65:
                let shown = node.computing or node.failure != "" or node.warning != "" or not node.enabled or node.frozen != "" or is_edit(node.kind)
                let ink = theme.accent() if node.failure != "" or node.computing else (theme.warning() if node.warning != "" and not waiting(node.warning) else theme.text_muted())
                p.text(detail if shown else node.kind, at.x + 109.0 * self.zoom, at.y + 22.0 * self.zoom, ink, self.font)
            # Bypass and Freeze on the left; the display flag on the right.
            p.rectangle(Rect(at.x + 84.0 * self.zoom, at.y + 5.0 * self.zoom, 9.0 * self.zoom, 30.0 * self.zoom), theme.accent() if node.visible else theme.border())
            p.rectangle(Rect(at.x + 3.0 * self.zoom, at.y + 5.0 * self.zoom, 9.0 * self.zoom, 30.0 * self.zoom), theme.accent() if not node.enabled else theme.border())
            p.rectangle(Rect(at.x + 15.0 * self.zoom, at.y + 5.0 * self.zoom, 9.0 * self.zoom, 30.0 * self.zoom), theme.frozen() if node.frozen != "" else theme.border())
            if not node.enabled:
                p.line(Point(at.x + 28.0 * self.zoom, at.y + 31.0 * self.zoom), Point(at.x + 78.0 * self.zoom, at.y + 9.0 * self.zoom), 1.0, theme.text_muted())
            # Fusion's timeline badges: red, it failed; yellow, it cooked
            # but something it refers to is lost (a warning). A node
            # waiting for a pick has none: it is not at fault.
            if not node.computing and (node.failure != "" or (node.warning != "" and not waiting(node.warning))):
                draw_badge(p, at.x + w - 7.0 * self.zoom, at.y - 7.0 * self.zoom, 8.0 * self.zoom, theme.failure() if node.failure != "" else theme.warning())
            for port in 0..<node.inputs.length:
                self.draw_port(p, self.port_point(node, false, port), node.inputs[port] >= 0)
            if wired:
                self.draw_port(p, self.port_point(node, true), true)
        if self.mode == "box" and dragged([self.start_x, self.start_y, self.last_x, self.last_y]):
            draw_box(p, [self.start_x, self.start_y, self.last_x, self.last_y])
        if self.mode == "cut":
            p.line(Point(self.start_x, self.start_y), Point(self.last_x, self.last_y), 1.5, theme.warning())
        elif self.cutting:
            p.text("Drag across wires to cut them", 12.0, size.height - 24.0, theme.text_muted())
        if self.mode == "wire":
            if let node = graph.find(self.wire_node):
                let port = self.port_point(node, self.from_output, self.wire_port)
                let pointer = Point(self.pointer_x, self.pointer_y)
                self.wire(p, port if self.from_output else pointer, pointer if self.from_output else port, false)
        if self.hovered >= 0 and self.mode == "" and not shading and not self.cutting:
            if let node = graph.find(self.hovered):
                let at = self.to_graph(self.pointer_x, self.pointer_y)
                let (info_x, info_y) = self.info_at(node)
                let over_info = self.pointer_x >= info_x and self.pointer_x <= info_x + 20.0 and self.pointer_y >= info_y and self.pointer_y <= info_y + 20.0
                let hint = "Node information" if over_info else ("Bypass (B)" if at.x < node.x + 13.5 else ("Freeze / unfreeze (Shift+B)" if at.x < node.x + 27.0 else ("Display flag (D)" if at.x > node.x + 81.0 else node.kind + " / geometry")))
                p.text(hint, 12.0, size.height - 24.0, theme.text_muted())
                p.rounded_rectangle(Rect(info_x, info_y, 20.0, 20.0), theme.surface(), 4.0)
                p.text("i", info_x + 5.0, info_y + 2.0, theme.text())
        if shading:
            let side = math.min(230.0, math.min(size.width, size.height) * 0.4)
            p.rectangle(Rect(size.width - side - 13.0, size.height - side - 13.0, side + 2.0, side + 2.0), theme.border())
        p.close()
        if shading:
            # A preview that cannot render says why in its place, not stopping the app.
            self.draw_preview(target, size.width, size.height) catch failure:
                let side = math.min(230.0, math.min(size.width, size.height) * 0.4)
                let note = Painter(target)
                note.text(failure.message, size.width - side - 12.0, size.height - side - 32.0, theme.warning())
                note.close()

    ## The Material's render in the bottom-right corner, restarted when its
    ## nodes change (at twice the size, for sharp high-density screens);
    ## redrawn while passes come.
    func draw_preview(self, target: RenderTarget, width: float, height: float) -> unit!:
        let side = math.min(230.0, math.min(width, height) * 0.4)
        if self.preview == none:
            self.preview = MaterialPreview()
        let preview = self.preview else return
        let graph = self.workspace.network
        preview.update(graph, graph.require(graph.scope), int(side * 2.0))
        if preview.draw(target, width - side - 12.0, height - side - 12.0, side):
            self.box.invalidate()
        let problem = preview.problem()
        if problem != "":
            error(ui.invalid, problem)

    ## A shader node: its name over its outputs (right) and inputs (left),
    ## each a labeled socket.
    func draw_shader_node(self, p: Painter, node: Node, selected: bool, view_width: float, view_height: float) -> unit!:
        let at = self.to_screen(node.x, node.y)
        let box = self.size_of(node)
        let w = box.width * self.zoom
        let h = box.height * self.zoom
        if at.x + w < 0.0 or at.x > view_width or at.y + h < 0.0 or at.y > view_height:
            return
        let radius = 4.0 * self.zoom
        p.rounded_rectangle(Rect(at.x - 1.5, at.y - 1.5, w + 3.0, h + 3.0), theme.accent() if selected else (theme.text_muted() if self.hovered == node.id else theme.grey(78.0)), radius + 1.0)
        p.rounded_rectangle(Rect(at.x, at.y, w, h), theme.grey(64.0) if node.enabled else theme.tab_strip(), radius)
        p.rectangle(Rect(at.x, at.y + shader_header * self.zoom - 1.0, w, 1.0), theme.grey(78.0))
        let ink = theme.text() if node.enabled else theme.text_muted()
        p.text(node.name, at.x + 8.0 * self.zoom, at.y + 4.0 * self.zoom, ink, self.font)
        let outputs = shader_nodes.outputs(node.kind)
        for port in 0..<outputs.length:
            let point = self.port_point(node, true, port)
            let label = outputs[port].label
            p.text(label, point.x - (10.0 + 7.0 * float(label.length)) * self.zoom, point.y - 8.0 * self.zoom, theme.text_muted(), self.font)
            self.draw_socket(p, point, outputs[port].width, true)
        let inputs = shader_nodes.inputs(node.kind)
        for port in 0..<inputs.length:
            let point = self.port_point(node, false, port)
            p.text(inputs[port].label, point.x + 10.0 * self.zoom, point.y - 8.0 * self.zoom, ink if node.inputs[port] >= 0 else theme.text_muted(), self.font)
            self.draw_socket(p, point, inputs[port].width, node.inputs[port] >= 0)

    ## The information button above a hovered node, at a fixed screen size.
    func info_at(self, node: Node) -> (float, float):
        let screen = self.to_screen(node.x, node.y)
        let middle = screen.x + node_width * self.zoom * 0.5 - 10.0
        return (middle, screen.y - 27.0)

    ## A socket: grey for a value, accent for a color or vector.
    func draw_socket(self, p: Painter, at: Point, width: int, filled: bool) -> unit!:
        let r = math.max(3.0, 4.5 * self.zoom)
        p.rounded_rectangle(Rect(at.x - r, at.y - r, 2.0 * r, 2.0 * r), theme.accent() if width == 3 else theme.grey(170.0), r)
        if not filled:
            p.rounded_rectangle(Rect(at.x - r * 0.45, at.y - r * 0.45, r * 0.9, r * 0.9), theme.grey(64.0), r * 0.45)

    func draw_port(self, p: Painter, at: Point, connected: bool) -> unit!:
        let width = math.max(8.0, 14.0 * self.zoom)
        let height = math.max(3.0, 4.0 * self.zoom)
        p.rounded_rectangle(Rect(at.x - width * 0.5, at.y - height * 0.5, width, height), theme.text() if connected else theme.grey(90.0), 1.5)

    ## A wire from output `a` to input `b`, picked ones in the accent.
    func wire(self, p: Painter, a: Point, b: Point, picked: bool) -> unit!:
        let points = network_wires.curve(a, b, self.shading())
        let width = math.max(1.0, 1.5 * self.zoom) * (1.8 if picked else 1.0)
        for at in 1..<points.length:
            p.line(points[at - 1], points[at], width, theme.accent() if picked else theme.grey(150.0))

    ## The wires shown, each (node, input port), and their curves on screen.
    func wires_shown(self) -> (list[(int, int)], list[list[Point]]):
        let graph = self.workspace.network
        let wires: list[(int, int)] = []
        let curves: list[list[Point]] = []
        for node in graph.local_nodes():
            for port in 0..<node.inputs.length:
                if let source = graph.find(node.inputs[port]):
                    wires.append((node.id, port))
                    curves.append(network_wires.curve(self.port_point(source, true, node.sources[port]), self.port_point(node, false, port), self.shading()))
        return (wires, curves)

    ## The wire under (x, y), within 5 points, as [node, input port]; [] none.
    pub func hit_wire(self, x: float, y: float) -> list[int]:
        let (wires, curves) = self.wires_shown()
        for at in 0..<wires.length:
            if network_wires.near(curves[at], x, y, 5.0):
                let (node, port) = wires[at]
                return [node, port]
        return []

    ## [node ID, port index, output flag]. Port hit radius stays usable zoomed out.
    pub func hit_port(self, x: float, y: float) -> list[int]:
        let at = self.to_graph(x, y)
        for node in self.workspace.network.local_nodes().reversed():
            # On the body, the flag strips win over a nearby port's enlarged
            # hit radius, including when the network is zoomed right out.
            if not self.shading() and self.inside_node(node, at) and (at.x < node.x + 27.0 or at.x >= node.x + 81.0):
                return []
            let outputs = shader_nodes.outputs(node.kind).length if self.shading() else (1 if self.wired() else 0)
            for port in 0..<outputs:
                let output = self.port_point(node, true, port)
                if math.abs(output.x - x) <= 10.0 and math.abs(output.y - y) <= 10.0:
                    return [node.id, port, 1]
            for port in 0..<node.inputs.length:
                let input = self.port_point(node, false, port)
                if math.abs(input.x - x) <= 10.0 and math.abs(input.y - y) <= 10.0:
                    return [node.id, port, 0]
        return []

    pub func event(self, event: Event) -> unit!:
        self.pointer_x = event.x if event.kind == EventKind.pointer_moved or event.kind == EventKind.pointer_down else self.pointer_x
        self.pointer_y = event.y if event.kind == EventKind.pointer_moved or event.kind == EventKind.pointer_down else self.pointer_y
        if event.cancelled or event.kind == EventKind.focus_lost or event.kind == EventKind.overflow:
            if self.mode == "move":
                self.workspace.cancel()
            self.mode = ""
            self.space = false
            self.cutting = false
        elif event.kind == EventKind.key_down:
            if event.key == Key.space:
                self.space = true
            elif event.key == Key.y and not event.repeated:
                self.cutting = true
            elif event.key == Key.tab:
                if let search = self.on_search:
                    search()
            elif event.key == Key.delete or event.key == Key.backspace:
                self.actions.delete.trigger()
            # D: the selected node's display flag (the viewport's D is its
            # Select marking menu).
            elif event.key == Key.d and not (event.meta or event.control or event.alt or event.repeated):
                if self.actions.display.is_enabled():
                    self.actions.display.trigger()
            elif event.key == Key.home:
                self.frame_all()
            elif event.key == Key.enter:
                if self.workspace.selected() != none:
                    node_commands.enter_group(self.workspace, self.workspace.network.selected)
            elif event.key == Key.escape:
                if self.mode == "move":
                    self.workspace.cancel()
                self.mode = ""
        elif event.kind == EventKind.key_up and event.key == Key.space:
            self.space = false
        elif event.kind == EventKind.key_up and event.key == Key.y:
            self.cutting = false
        elif event.kind == EventKind.magnify:
            self.zoom_about(math.max(0.1, 1.0 + event.scroll_y), event.x, event.y)
        elif event.kind == EventKind.scroll:
            if event.scroll_unit == ScrollUnit.points and not event.control and not event.meta:
                self.pan_x += event.scroll_x
                self.pan_y += event.scroll_y
            else:
                self.zoom_about(math.exp(event.scroll_y * (0.01 if event.scroll_unit == ScrollUnit.points else 0.12)), event.x, event.y)
        elif event.kind == EventKind.pointer_down and event.inside:
            if event.button == 1:
                if self.mode == "move":
                    self.workspace.cancel()
                self.mode = ""
                self.open_menu(event)
                return
            if event.button == 0 and self.mode == "" and self.hovered >= 0 and not self.shading():
                if let node = self.workspace.network.find(self.hovered):
                    let (x, y) = self.info_at(node)
                    if event.x >= x and event.x <= x + 20.0 and event.y >= y and event.y <= y + 20.0:
                        node_commands.select_node(self.workspace, node.id)
                        if let inspect = self.on_inspect:
                            inspect(node.id)
                        self.box.invalidate()
                        return
            self.last_x = event.x
            self.last_y = event.y
            self.start_x = event.x
            self.start_y = event.y
            if event.button == 2 or self.space:
                self.mode = "pan"
            elif self.cutting:
                self.mode = "cut"
            elif self.mode == "wire":
                let port = self.hit_port(event.x, event.y)
                self.finish_wire(port)
                self.mode = ""
            else:
                let port = self.hit_port(event.x, event.y)
                if port.length > 0:
                    if event.alt and port[2] == 0:
                        node_commands.disconnect(self.workspace, port[0], port[1])
                    else:
                        self.mode = "wire"
                        self.wire_node = port[0]
                        self.wire_port = port[1]
                        self.from_output = port[2] == 1
                else:
                    let at = self.to_graph(event.x, event.y)
                    # Empty canvas: a box picks the nodes and wires it
                    # touches; a click on nothing picks nothing.
                    self.mode = "box"
                    self.box_operation = operation_of(event)
                    for node in self.workspace.network.local_nodes().reversed():
                        if self.inside_node(node, at):
                            # Shift adds or removes a node, Ctrl or Cmd
                            # takes it out; a picked node keeps the others
                            # picked, to move them together.
                            if self.box_operation == 2:
                                node_commands.pick_nodes(self.workspace, [node.id], 2)
                                self.mode = ""
                                break
                            if event.shift:
                                node_commands.pick_node(self.workspace, node.id, true)
                                self.mode = ""
                                break
                            let together = self.workspace.network.selection()
                            if node.id in together:
                                self.workspace.network.selected = node.id
                                self.workspace.revision += 1
                            else:
                                node_commands.select_node(self.workspace, node.id)
                            if self.shading():
                                self.start_move(node)
                            elif at.x < node.x + 13.5:
                                self.actions.enabled.trigger()
                                self.mode = ""
                            elif at.x < node.x + 27.0:
                                self.actions.freeze.trigger()
                                self.mode = ""
                            elif at.x >= node.x + 81.0:
                                self.actions.display.trigger()
                                self.mode = ""
                            else:
                                let now = time.now()
                                if self.last_node == node.id and now - self.last_click < 400000000:
                                    # A double-click enters a network, or
                                    # edits a CAD feature in the viewport
                                    # (Fusion's Edit Feature).
                                    if node_catalog.holds_nodes(node.kind) or self.workspace.network.context() == "cad":
                                        self.mode = ""
                                        self.last_node = -1
                                        cad_chain.edit_feature(self.workspace, node.id)
                                        return
                                self.last_node = node.id
                                self.last_click = now
                                self.start_move(node)
                            break
                    # A wire: picked alone, or with Shift added (taken out
                    # when picked), or with Ctrl or Cmd taken out.
                    let wire = self.hit_wire(event.x, event.y) if self.mode == "box" else []
                    if wire.length > 0:
                        let key = (wire[0], wire[1])
                        let operation = 2 if self.box_operation == 1 and key in self.workspace.network.selected_wires() else self.box_operation
                        node_commands.pick_wires(self.workspace, [key], operation)
                        self.mode = ""
        elif event.kind == EventKind.pointer_moved:
            self.pointer_inside = event.inside
            var retained = -1
            if let node = self.workspace.network.find(self.hovered):
                let screen = self.to_screen(node.x, node.y)
                if event.inside and event.x >= screen.x and event.x <= screen.x + node_width * self.zoom and event.y >= screen.y - 30.0 and event.y <= screen.y + node_height * self.zoom:
                    retained = node.id
            self.hovered = retained
            if event.inside:
                let at = self.to_graph(event.x, event.y)
                for node in self.workspace.network.local_nodes().reversed():
                    if self.inside_node(node, at):
                        self.hovered = node.id
                        break
            if self.mode == "pan":
                self.pan_x += event.x - self.last_x
                self.pan_y += event.y - self.last_y
            elif self.mode == "move" and (event.x != self.start_x or event.y != self.start_y):
                for k in 0..<self.moving_ids.length:
                    let origin = self.moving_from[k]
                    node_commands.move_node(self.workspace, self.moving_ids[k], origin.x + (event.x - self.start_x) / self.zoom, origin.y + (event.y - self.start_y) / self.zoom)
            self.last_x = event.x
            self.last_y = event.y
        elif event.kind == EventKind.pointer_up:
            if self.mode == "move":
                self.workspace.commit()
            elif self.mode == "box":
                self.finish_box()
            elif self.mode == "cut":
                self.finish_cut()
            elif self.mode == "wire":
                let port = self.hit_port(event.x, event.y)
                # A click starts a persistent wire; a drag connects on release.
                if port.length > 0 and port[0] == self.wire_node and (port[2] == 1) == self.from_output:
                    self.box.invalidate()
                    return
                self.finish_wire(port)
            self.mode = ""
        elif event.kind == EventKind.pointer_left:
            self.hovered = -1
            self.pointer_inside = false
        self.box.invalidate()

    ## A right click at `event`: the node there is picked (the picked nodes
    ## stay picked when it is among them, as Houdini does), and the node
    ## menu opens for it, or for the canvas.
    func open_menu(self, event: Event) -> unit!:
        let at = self.to_graph(event.x, event.y)
        var hit = -1
        for node in self.workspace.network.local_nodes().reversed():
            if self.inside_node(node, at):
                hit = node.id
                break
        if hit >= 0:
            if hit in self.workspace.network.selection():
                self.workspace.network.selected = hit
                self.workspace.revision += 1
            else:
                node_commands.select_node(self.workspace, hit)
        self.box.invalidate()
        if let menu = self.on_menu:
            menu(hit)

    ## Begin dragging `node` and the nodes picked with it.
    func start_move(self, node: Node) -> unit!:
        self.mode = "move"
        self.moving = node.id
        self.moving_ids = self.workspace.network.selection()
        if not (node.id in self.moving_ids):
            self.moving_ids = [node.id]
        self.moving_from = []
        for id in self.moving_ids:
            let picked = self.workspace.network.require(id)
            self.moving_from.append(Point(picked.x, picked.y))
        self.workspace.begin("Move node")

    ## Pick the nodes and wires the box touches (box_operation: alone,
    ## added, taken out); a click or a plain box on empty canvas picks
    ## nothing.
    func finish_box(self) -> unit!:
        let w = self.workspace
        let operation = self.box_operation
        if not dragged([self.start_x, self.start_y, self.last_x, self.last_y]):
            if operation == 0:
                node_commands.select_nothing(w)
            return
        let a = self.to_graph(math.min(self.start_x, self.last_x), math.min(self.start_y, self.last_y))
        let b = self.to_graph(math.max(self.start_x, self.last_x), math.max(self.start_y, self.last_y))
        let inside: list[int] = []
        for node in w.network.local_nodes():
            let size = self.size_of(node)
            if node.x <= b.x and node.x + size.width >= a.x and node.y <= b.y and node.y + size.height >= a.y:
                inside.append(node.id)
        let touched: list[(int, int)] = []
        let (wires, curves) = self.wires_shown()
        for at in 0..<wires.length:
            if network_wires.touches(curves[at], math.min(self.start_x, self.last_x), math.min(self.start_y, self.last_y), math.max(self.start_x, self.last_x), math.max(self.start_y, self.last_y)):
                touched.append(wires[at])
        # A plain box over nothing selects nothing; Shift or Ctrl changes
        # nothing.
        if operation == 0 and inside.length == 0:
            node_commands.select_nothing(w)
        if inside.length > 0:
            node_commands.pick_nodes(w, inside, operation)
        if touched.length > 0:
            node_commands.pick_wires(w, touched, 1 if operation == 0 else operation)

    ## Y-drag released: disconnect every wire the line crosses.
    func finish_cut(self) -> unit!:
        let cut: list[(int, int)] = []
        let (wires, curves) = self.wires_shown()
        for at in 0..<wires.length:
            if network_wires.crosses(curves[at], Point(self.start_x, self.start_y), Point(self.last_x, self.last_y)):
                cut.append(wires[at])
        node_commands.cut_wires(self.workspace, cut)

    func finish_wire(self, port: list[int]) -> unit!:
        if port.length > 0 and (port[2] == 1) != self.from_output:
            if self.from_output:
                node_commands.connect(self.workspace, self.wire_node, port[0], port[1], self.wire_port)
            else:
                node_commands.connect(self.workspace, port[0], self.wire_node, self.wire_port, port[1])

## A round badge of radius `r` about (`x`, `y`) with an exclamation mark.
func draw_badge(p: Painter, x: float, y: float, r: float, color: Color) -> unit!:
    p.rounded_rectangle(Rect(x - r, y - r, r * 2.0, r * 2.0), color, r)
    p.rectangle(Rect(x - r * 0.14, y - r * 0.6, r * 0.28, r * 0.75), theme.backdrop())
    p.rectangle(Rect(x - r * 0.14, y + r * 0.3, r * 0.28, r * 0.28), theme.backdrop())