JFLib

ui/diagram.rs#

Source: lib/ui/diagram.rs

diagram -- a node / edge canvas: zoom and pan, grid and snapping, a spatial index, hit
testing, selection (click, marquee, keyboard), moving, connecting, waypoints, a minimap and
one semantic record per visible node.  The app owns the model and paints it; the widget
keeps the view, the selection and the gestures in DiagramState and reports what the user
did as DEv events.

  ui.diagram(id, &mut st, &m, tool, paint, ver) -> Vec<DEv>
                                  the canvas in the next layout slot (size it with
                                  next_size); tool DG_SELECT / DG_PAN / DG_CONNECT /
                                  DG_PLACE; paint draws the content at render time
                                  (DgPaint); ver stands for everything it shows besides the
                                  geometry (labels, states, colours)
  ui.diagram_minimap(id, &mut st, &m) -> bool    an overview in the bottom right corner of
                                  the canvas; pressing / dragging there moves the view
  ui.diagram_sems(id, &mut st, &m, &label)   one K_LISTITEM record per visible node
                                  (scripts: click listitem:"R1"; screen readers), no hit box
  ui.diagram_edge_sems(id, &mut st, &m, &label)   the same for the visible edges (a box
                                  around the middle of the route); st.tab_edges lets Tab
                                  walk them after the nodes, st.name names the canvas
  Viewport::{scale, to_screen, to_world, world_rect, rect_to_screen, zoom_at, step, fit}
  dg_paint_grid(g, vp, step, minor, major)   grid lines inside the clip (render time)
  dg_edge_points(m, i, &mut out)  the route of edge i (world polyline) without a state
  dg_stroke_edge(g, vp, pts, width, argb, cap0, cap1, dash)   stroke a route (gfx::dash
                                  caps LCAP_* and patterns DASH_*), culled by the clip
  dg_point_at(pts, f) -> point    the point at fraction f of a route's length (packets)
  dg_hairline(g, vp, pts, argb)   a route as 1 px anti-aliased lines: far cheaper than
                                  dg_stroke_edge for many thin edges (DgFrame::moving)
  DgFrame::find(margin, edges)    the nodes or edges near the clip (the spatial buckets)
  dg_toggle_rect(node, bar)       the world box of a DN_TOGGLE node's collapse button
  DgPaint::paint_under(g, f)      (optional) what lies under the grid: a backdrop image

Frames and groups (additive flags, G1 of JFNetworker): a DN_FRAME node is a labelled frame
around other nodes (the app computes its box from theirs and puts it before them, so they lie
on top).  It is hit on its title bar -- the top DiagramState::frame_bar world units -- and on
its border (4 DIP) only: its inside stays the background (marquees start there, members are
clicked through it); its overview box is an outline, its record (diagram_sems) covers the
title bar.  DN_TOGGLE gives a node a collapse button at the right end of its title bar (a
frame) or in its top right corner: a click there reports DEv::Toggle (no selection change).
DN_STEP nodes move by whole grid steps instead of snapping their corner, so the members a
frame or a cluster stands for stay on the grid.  A selected DN_RESIZE node shows a handle at
its bottom right corner; dragging it reports DEv::Resize with the new box (Esc: back).
DN_OUTLINE draws a node as an outline in the overview (a backdrop, an area).  A DN_HITMIN node
(a line of text) is hit in a box of at least 16 x 16 DIP around it, so it stays selectable at
low zoom.

Model (DModel, borrowed every frame): nodes with a world rectangle and a range of ports,
ports at a position relative to their node's top left corner, edges from key a to key b
(a port, or a node: then the route starts on its border) with a route DR_STRAIGHT /
DR_BEZIER / DR_ORTHO through a range of waypoints.  Keys are non-zero and unique over
nodes, ports and edges; later nodes lie on top.  ver changes whenever the geometry
changes: the key maps, the routes and the spatial buckets (256 world units) are rebuilt
then.  World units are DIP at zoom 1.

Input: the hit test prefers the resize handles of selected DN_RESIZE nodes, the handles of
selected edges (waypoints, then the middles of their stretches), then the ports of the node
under the pointer, the topmost node (a DN_TOGGLE node's button first), the nearest edge
(max(5 DIP, half the edge width + 3 DIP)), the background.  A press + drag
(4 DIP) on a selected node moves the selection (snapped to the grid, Alt: free), from a
port connects, on a handle moves or inserts a waypoint, on the background draws a marquee
(Shift adds, Ctrl toggles); middle drag, Space + drag and DG_PAN pan; the wheel scrolls
(Shift: sideways), Ctrl + wheel zooms at the pointer.  A double click on the background with
DG_SELECT (no Shift, no Ctrl) reports DEv::DoubleClick at the second press; a press that became
a drag (a marquee) or a key between the clicks makes none.  Keys while the canvas has the focus:
arrows nudge the selection (grid steps, Shift x10, Alt 1) or pan, Del, Ctrl+A, Esc cancels
a gesture (else clears the selection), Tab / Shift+Tab walk the nodes (with tab_edges then
the edges, a focused edge drawn with the focus ring along its route; the focus leaves after
the last), Enter activates, Ctrl + plus / minus zoom, Ctrl+0 fits, Shift+F10 / the menu key
ask for the context menu.  DiagramState::test_keys stands in for held keys in scripts.
Drawing: the paint runs as one custom command whose version covers ver, the model version,
the view, the theme and the gesture flag; selection, hover, ports, handles, marquee and rubber
band are recorded commands on top, so hovering redraws only their cells.  The paint draws the
whole canvas into a backing store (an XRGB surface of the DiagramState) once per version;
every dirty rectangle copies its part out of it.  Skip what lies outside DgFrame::clip
(DgFrame::find asks the spatial buckets).  While a gesture moves the view or nodes (a pan,
wheel turns until MOVING_MS after the last one, a drag of nodes or a waypoint)
DgFrame::moving asks for less detail; a full paint follows the gesture.  Content that moves
every frame (packets) is best drawn after diagram() with ui.draw_* inside
ui.clip_push(st.vp.rect).  With a GPU a pan or a wheel zoom comes from tiles of the full paint
(canvas.rs, DiagramState::gpu, "diagram"; the first ones are copied from the backing store), no
less detail then; the CPU paints what lies under overlays and, a moment after it ends, the view.
/// tools of ui.diagram
DG_SELECT: u32 = 0  // select, move, connect from ports, waypoints
DG_PAN: u32 = 1  // a left drag pans
DG_CONNECT: u32 = 2  // a drag (or two clicks) from a node / port to another connects
DG_PLACE: u32 = 3  // a click reports DEv::Click (snapped) to place something
/// the view only (zoom, pan with the middle button, Space + drag and the wheel, the keys that zoom):
/// the left button, the other keys, the cursor and the overlays belong to ui.shape_edit, called
/// right after ui.diagram with the same DiagramState (shape_edit.rs)
DG_EDIT: u32 = 4
/// edge routes (DEdge::route)
DR_STRAIGHT: u8 = 0
DR_BEZIER: u8 = 1
DR_ORTHO: u8 = 2  // horizontal and vertical stretches (L / Z shapes)
/// node flags (DNode::flags)
DN_LOCKED: u32 = 1  // never moved by the widget
DN_NOSELECT: u32 = 2  // decoration: never hit nor selected
DN_FRAME: u32 = 4  // a frame around other nodes: hit on its title bar and border only
DN_TOGGLE: u32 = 8  // a collapse button (DEv::Toggle), see dg_toggle_rect
DN_STEP: u32 = 16  // moves by whole grid steps (its corner keeps its offset to the grid)
DN_RESIZE: u32 = 32  // selected: a handle at the bottom right corner resizes it
DN_OUTLINE: u32 = 64  // an outline in the overview (DN_FRAME nodes are always)
DN_HITMIN: u32 = 128  // hit in a box of at least 16 x 16 DIP around it (a small text)
/// port flags (DPort::flags)
DPT_HIDDEN: u32 = 1  // neither shown nor hit
DPT_USED: u32 = 2  // shown filled (connected)
  • struct Viewport what part of the world the canvas shows: zoom (DIP per world unit, 1 = 100 %), the world point at the centre of rect; rect (absolute px) and dpi are kept by ui.diagram
    • zoom: f32
    • cx: f64
    • cy: f64
    • rect: [i32; 4]
    • dpi: i32

impl Viewport

  • const ZOOM_MIN: f32 = 0.1

  • const ZOOM_MAX: f32 = 8.0

  • fn scale(&self) -> f64 px per world unit

  • fn to_screen(&self, p: [f32; 2]) -> [f32; 2] a world point in absolute px

  • fn to_world(&self, x: f32, y: f32) -> [f32; 2] an absolute px position in world units

  • fn world_rect(&self) -> [f32; 4] the world rectangle x0, y0, x1, y1 the canvas shows

  • fn rect_to_screen(&self, r: [f32; 4]) -> [f32; 4] a world rectangle x, y, w, h in px (x, y, w, h, fractional)

  • fn zoom_at(&mut self, zoom: f32, sx: f32, sy: f32) zoom (clamped) keeping the world point under the absolute px (sx, sy) in place

  • fn step(&mut self, dir: i32, sx: f32, sy: f32) the next zoom step above (dir > 0) or below around the absolute px (sx, sy)

  • fn fit(&mut self, b: [f32; 4], margin: i32) show the world rectangle b (x0, y0, x1, y1) with margin DIP around it, at most 100 %

  • fn zoom_to(&mut self, b: [f32; 4]) show the world rectangle b as large as the canvas holds it, up to ZOOM_MAX (a zoom rectangle drawn at 400 %: further in, not out to 100 % as fit would)

  • struct DNode a node: world rectangle x, y, w, h, its ports (a range of DModel::ports), DN_* flags

    • key: u64
    • rect: [f32; 4]
    • ports: Range<u32>
    • flags: u32
  • struct DPort a port: its position relative to the node's top left corner, DPT_* flags

    • key: u64
    • at: [f32; 2]
    • flags: u32
  • struct DEdge an edge from key a to key b (ports or nodes) along route DR_* through a range of DModel::wps

    • key: u64
    • a: u64
    • b: u64
    • route: u8
    • wps: Range<u32>
  • struct DModel<'a> the app's diagram, borrowed for one call; ver changes with every geometry change

    • nodes: &'a [DNode]
    • ports: &'a [DPort]
    • edges: &'a [DEdge]
    • wps: &'a [[f32; 2]]
    • ver: u32
  • enum DHit what a point of the canvas shows

    • None
    • Node(u64)
    • Port(u64)
    • Edge { key: u64, seg: u32, t: f32 } -- an edge: seg = the stretch between its defining points seg and seg + 1 (0 = the start, then the waypoints), t = 0..1 along it
    • Waypoint(u64, u32) -- the handle of waypoint idx of a selected edge
    • Mid(u64, u32) -- the handle in the middle of stretch idx of a selected edge (a drag inserts waypoint idx)
    • Toggle(u64) -- the collapse button of a DN_TOGGLE node
    • Resize(u64) -- the resize handle of a selected DN_RESIZE node

impl DHit

  • fn key(&self) -> u64 the node, port or edge key (0 = the background)

  • enum DEv what the user did (ui.diagram's result, in order)

    • Select -- st.sel changed
    • Move { keys: Vec<u64>, d: [f32; 2], total: [f32; 2], done: bool } -- move nodes keys by d (world units); the d of one gesture add up to total; done = the gesture ended (released, a key nudge; Esc sends d = minus everything so far)
    • Connect { from: u64, to: u64, quick: bool } -- connect from -> to (port or node keys); quick = dragged out of a port with DG_SELECT
    • ConnectDrag { from: u64, at: [f32; 2], over: u64 } -- a connection is being drawn: the pointer at at, over port / node over (0 = none)
    • ConnectCancel -- the connection ended without a target (released elsewhere, Esc)
    • Waypoint { edge: u64, idx: u32, at: [f32; 2], insert: bool, done: bool } -- waypoint idx of edge goes to at; insert = add it at idx first (the first event of a drag from a middle handle); done = released
    • WaypointDelete { edge: u64, idx: u32 } -- remove waypoint idx of edge (double click on its handle, Esc after an insert)
    • Activate(DHit) -- double click on a node / port / edge, Enter on the focused node
    • Context(DHit, [i32; 2]) -- right click, Shift+F10 or the menu key: at = window px (logical, for popups)
    • Delete -- Del with a selection: delete st.sel
    • Click { at: [f32; 2] } -- a click on the background, or anywhere with DG_PLACE (snapped then); world units
    • DoubleClick { at: [f32; 2] } -- a double click on the background with DG_SELECT (no Shift, no Ctrl): the world point of the second press, not snapped; neither a Click nor a marquee follows it
    • ViewChanged -- zoom or centre changed
    • Toggle(u64) -- a click on the collapse button of a DN_TOGGLE node
    • Resize { key: u64, rect: [f32; 4], done: bool } -- the resize handle of a DN_RESIZE node was dragged: its new box x, y, w, h (world, the top left corner stays; at least 8 units); done = released (Esc: the box it had)
  • struct DgRoute an edge's route in world units: the polyline, the indices of its defining points (a, the waypoints, b) in it, its bounding box x0, y0, x1, y1 (empty pts: an end is unknown)

    • key: u64
    • pts: Vec<[f32; 2]>
    • marks: Vec<u32>
    • bb: [f32; 4]
  • struct DgGeo the routes of every edge in model order and the spatial buckets of nodes and edges, built once per model version (DgFrame::find asks the buckets)

    • routes: Vec<DgRoute>
  • struct DgFrame<'a> what a DgPaint gets at render time

    • vp: Viewport
    • clip: [f32; 4] -- the world rectangle x0, y0, x1, y1 that needs pixels now: skip what lies outside
    • geo: &'a DgGeo
    • theme: &'a [u32] -- the theme's colours (color(T_*)), the canvas background (opaque)
    • bg: u32
    • fonts: [(u32, i32); 7] -- font and size (24.8 px at zoom 1) of every TS_* text style
    • dark: bool
    • moving: bool -- a gesture moves the view or nodes (a pan, wheel turns, a drag of nodes or a waypoint): leave out what costs and nobody reads in passing (small labels; plain shapes, dg_hairline); the canvas is painted in full after it

impl DgFrame<'_>

  • fn color(&self, tok: u32) -> u32 0xAARRGGBB of a theme token

  • fn visible(&self, r: [f32; 4]) -> bool the world rectangle x, y, w, h (with 2 px for anti-aliasing) touches the clip

  • fn route_visible(&self, rt: &DgRoute, width: f32) -> bool a route stroked width world units wide (dg_stroke_edge, arrow heads included) touches the clip

  • fn find(&self, margin: f32, edges: bool) -> Vec<u32> the nodes (edges = false: DModel::nodes) or the edges whose spatial buckets touch the clip grown by margin px: ascending indices, a superset of what can need paint (cheaper than looking at all of them)

  • fn font(&self, ts: u32) -> (u32, i32) font and size (24.8 px) of text style ts at the current zoom

  • trait DgPaint the app's painting of a diagram (render time): nodes, edges (DgFrame::geo), labels; it runs once per dirty rectangle, so skip what DgFrame::visible / route_visible reject

    • fn paint(&self, g: &mut Gfx, f: &DgFrame)
    • fn paint_under(&self, _g: &mut Gfx, _f: &DgFrame) what lies under the grid (a backdrop image), painted before it; nothing by default
    • fn damage(&self, _from: u32, _to: u32) -> Option<[f32; 4]> the world rectangle x0, y0, x1, y1 whose look changed from the content version from to to (ui.diagram's ver) while everything else stayed: only that part of the backing store is painted again (an edit of a few shapes in a large drawing); None (the default): unknown, all of it
  • struct DiagramState the widget's state, kept by the app: the view, the selection (node and edge keys), the focused node, grid and snapping, the hover, the gesture in progress and the index

    • vp: Viewport
    • sel: BTreeSet<u64>
    • focus: u64 -- the node with the keyboard focus (0 = none): Tab walks, Enter activates it
    • grid: f32 -- grid step in world units (0 = no grid)
    • snap: bool -- moves, waypoints and DG_PLACE clicks snap to the grid (Alt held: free)
    • grid_lines: bool -- the grid's lines are drawn (false: the grid only snaps, Visio's hidden grid)
    • hover: DHit -- what the pointer is over (after the last diagram call)
    • edge_width: f32 -- the stroke width of the edges in world units (hit testing, the highlight)
    • test_keys: u32 -- scripts cannot hold keys: 1 = as if Space were held, 2 = Ctrl
    • tab_edges: bool -- Tab / Shift+Tab also walk the edges (after the nodes, in model order): the focused edge is selected, Enter activates it, the menu key asks for its context menu
    • name: String -- the canvas' name for screen readers (its K_CANVAS record; empty: none)
    • frame_bar: f32 -- the height of a DN_FRAME node's title bar in world units (its hit area, its record, the side of its DN_TOGGLE button)
    • gpu: CanvasGpu -- how the view's pan and zoom use the GPU (canvas.rs)

impl DiagramState

  • fn new() -> DiagramState grid 16, snapping on, edges 2 units wide; the first diagram call fits the content
  • fn request_fit(&mut self) fit the whole content into the view with the next diagram call
  • fn busy(&self) -> bool a gesture (drag, marquee, connection, pan) is in progress
  • fn route(&self, key: u64) -> Option<&DgRoute> the route of edge key (as of the last diagram call)
  • fn geo(&self) -> &Rc<DgGeo> every route (model order), shared with the paint
  • fn bounds(&self) -> Option<[f32; 4]> the bounding box x0, y0, x1, y1 of nodes and routes (None: empty)
  • fn visible(&self) -> &[u32] the indices of the nodes the canvas showed in the last diagram call

impl DgGeo

  • fn find(&self, r: [f32; 4], edges: bool, out: &mut Vec<u32>) the indices of the nodes (edges = false) or edges whose buckets touch r (world x0, y0, x1, y1), ascending: a superset of what overlaps it (all when r spans too many buckets)

  • fn dg_length(pts: &[[f32; 2]]) -> f32 the length of a polyline

  • fn dg_point_at(pts: &[[f32; 2]], f: f32) -> [f32; 2] the point at fraction f (0..1) of a polyline's length (a packet travelling along an edge)

  • fn dg_toggle_rect(n: &DNode, bar: f32) -> [f32; 4] the world box x, y, w, h of a DN_TOGGLE node's collapse button: the square of the title bar's height bar at its right end (a DN_FRAME node), else a square of that side (at most the node's) in the top right corner; apps paint the button there

  • fn dg_edge_points(m: &DModel, i: usize, out: &mut Vec<[f32; 2]>) the route of edge i of m (world polyline) into out, without a DiagramState (ports and nodes are looked up linearly; DiagramState::route has them indexed)

  • fn dg_paint_grid(g: &mut Gfx, vp: &Viewport, step: f32, minor: u32, major: u32) grid lines every step world units (every fifth in major) inside the clip and the canvas; steps closer than 8 px are widened five times

  • fn dg_stroke_edge(g: &mut Gfx, vp: &Viewport, pts: &[[f32; 2]], width: f32, argb: u32, cap0: u32, cap1: u32, dash: u32) stroke a route (world points) width world units wide (at least 1 px) in argb, with gfx::dash caps (LCAP_*: arrows at an end) and pattern DASH_*; nothing when it misses the clip

  • fn dg_hairline(g: &mut Gfx, vp: &Viewport, pts: &[[f32; 2]], argb: u32) a route (world points) as 1 px anti-aliased lines in argb (Xiaolin Wu): a fraction of dg_stroke_edge's cost for many thin edges (the level of detail of DgFrame::moving); nothing outside the clip

impl Ui

  • fn diagram(&mut self, id: u32, st: &mut DiagramState, m: &DModel, tool: u32, paint: Option<Rc<dyn DgPaint>>, ver: u32) -> Vec<DEv> ui_diagram(id, st, m, tool, paint, ver) -> what the user did: the node / edge canvas in the next layout slot (see the file header)
  • fn diagram_minimap(&mut self, id: u32, st: &mut DiagramState, m: &DModel) -> bool ui_diagram_minimap(id, st, m) -> the view moved: an overview of the nodes and the shown part in the bottom right corner of the last diagram (nothing when the canvas is small); pressing or dragging there centres the view on that point
  • fn diagram_sems(&mut self, id: u32, st: &mut DiagramState, m: &DModel, label: &dyn Fn(u64) -> String) ui_diagram_sems(id, st, m, label): one K_LISTITEM record per node the last diagram call showed (label(key), value = the node's index, selected / focused / hover states), cut to the canvas; a screen reader's click on one selects it
  • fn diagram_edge_sems(&mut self, id: u32, st: &mut DiagramState, m: &DModel, label: &dyn Fn(u64) -> String) ui_diagram_edge_sems(id, st, m, label): one K_LISTITEM record per edge the last diagram call showed (label(key); value = the edge's index; selected / focused / hover states), a small box around the middle of its route cut to the canvas, after the nodes' records; a screen reader's click on one selects the edge (and focuses it with tab_edges)

Source: docs/API.md in the JFLib repository.