JFLib

22. Diagrams: nodes, ports and edges#

ui.diagram is a canvas for node / edge editors (network topologies, flow charts). The app owns the model and paints it; the widget keeps the view, the selection and the gestures in a DiagramState and returns what the user did as DEv events (lib/ui/diagram.rs, the test app apps/diagramtest).

// in frame (self.st: DiagramState, self.scene: Rc<RefCell<Scene>>, self.painter: Rc<dyn DgPaint>)
ui.next_size(-1, -1);
let sc = self.scene.clone();
let sc = sc.borrow();
let m = DModel { nodes: &sc.nodes, ports: &sc.ports, edges: &sc.edges, wps: &sc.wps, ver: sc.ver };
let evs = ui.diagram(ID_DIAGRAM, &mut self.st, &m, DG_SELECT, Some(self.painter.clone()), 0);
ui.diagram_minimap(ID_MINI, &mut self.st, &m);
ui.diagram_sems(ID_DIAGRAM, &mut self.st, &m, &|k| sc.label(k));
drop(sc);
for ev in evs {
    match ev {
        DEv::Move { keys, d, .. } => self.move_nodes(&keys, d), // and bump the model's ver
        DEv::Connect { from, to, .. } => self.connect(from, to),
        DEv::Delete => self.delete_selection(),
        _ => {}
    }
}
  • The model is borrowed per call: DNode { key, rect, ports, flags } (world x, y, w, h and a range of ports), DPort { key, at, flags } (relative to its node), DEdge { key, a, b, route, wps } (a / b are port or node keys; DR_STRAIGHT, DR_BEZIER, DR_ORTHO; a range of wps). Keys are non-zero and unique over all three; bump ver with every geometry change (the routes and the spatial index are rebuilt then). A world unit is a DIP at 100 %.
  • Tools: DG_SELECT (click, Shift adds, Ctrl toggles, marquee; a drag moves the selection snapped to st.grid, Alt moves freely; a drag out of a port connects; the handles of a selected edge move and insert waypoints, a double click removes one), DG_PAN, DG_CONNECT (drag, or two clicks, from node / port to node / port), DG_PLACE (DEv::Click at a snapped point). Middle drag, Space + drag and the wheel pan, Ctrl + wheel zooms at the pointer; arrows nudge, Del, Ctrl+A, Esc, Tab, Enter, Ctrl + plus / minus / 0 work while the canvas has the focus.
  • A double click on a node, port or edge is DEv::Activate, one on the background with DG_SELECT (no Shift, no Ctrl) DEv::DoubleClick { at } with the world point of the second press, not snapped: no marquee and no second Click follow it, and a press that became a drag (a marquee) or a key between the clicks makes none. The time is the theme's double_click_ms. DN_HITMIN gives a small node, a line of text say, a hit box of at least 16 x 16 DIP around it, so it stays selectable at low zoom. To type right on the canvas, place a ui.textbox_presented over it with ui.next_rect_px (in a mirrored window its logical x is ui.rtl_map(x + w - 1, r[0], r[2]), the canvas is not mirrored) and give the keyboard back with ui.focus_quiet(id) after a pointer gesture: it is ui.focus without the focus ring. JFNetworker's labels do this (canvas/labels.rs).
  • Painting: the DgPaint runs at render time with a DgFrame (vp: world <-> px, clip: the world part to paint, geo.routes: the polyline of every edge, the theme's colours and fonts, moving). Cull with f.visible(rect) / f.route_visible(route, width), stroke with dg_stroke_edge (gfx::dash caps for arrows, dash patterns), place moving things with dg_point_at(&route.pts, f). Selection, hover, ports, handles, marquee and rubber band are drawn by the widget as ordinary commands on top. Pass a ver that changes with anything else the paint shows (states, labels).
  • Screen readers and keyboard: ui.diagram_edge_sems(id, &mut st, &m, &label) adds one listitem per visible edge (a small box around the middle of its route; a screen reader's click selects it), st.tab_edges = true lets Tab walk the edges after the nodes (a focused edge gets the focus ring along its route, Enter activates it, the menu key opens its context menu), st.name names the canvas.
  • Scripts: every visible node is a listitem with the label the app gives (click listitem:"R1", expect listitem:"R1" selected). down / up take a point (down 470,164): a listitem: selector there reads as the button letter. A second press on the same thing within the double-click time activates it, so wait 600 between a click and a drag of the same node. Ctrl + wheel: wheel S DY ctrl. Scripts cannot hold Space: the app sets DiagramState::test_keys (1 Space, 2 Ctrl) from a command (cmd 900 1 in diagramtest).
  • Large diagrams: the widget paints the whole canvas into a backing store (an XRGB surface of the DiagramState, from the window's corner to the canvas' far corner) whenever the paint's version changes (the model, ver, the view, the theme, DgFrame::moving); dirty rectangles then only copy their part, so hover, selection and what is drawn on top (moving packets) never repaint the scene. In the paint, iterate f.find(margin_px, edges) (the spatial buckets near the clip, ascending indices) instead of every node and edge, and cull with visible / route_visible before computing anything per item. While a gesture moves the view or nodes (a pan, wheel turns until 160 ms after the last one, a drag of nodes or a waypoint) f.moving is set: with many things in view, leave out small labels and LEDs and stroke edges with dg_hairline (1 px anti-aliased lines, a fraction of dg_stroke_edge's cost); the canvas is painted in full detail once the gesture ends. JFNetworker's tests/perf.uis holds 500 devices and 800 cables this way.
  • Frames, groups and a backdrop (node flags, additive): a DN_FRAME node is a labelled frame around other nodes. The app computes its box from its members' (with room for their labels and a title bar) and puts it before them in nodes, so they lie on top. It is hit on its title bar (the top st.frame_bar world units, 24 by default) and on its 4 DIP border only: its inside stays the background (a marquee starts there, members are clicked through it), the overview draws it as an outline and diagram_sems gives it a record over its title bar. DN_TOGGLE adds a collapse button, the box dg_toggle_rect(node, st.frame_bar) (the right end of a frame's title bar, else the node's top right corner): a click there reports DEv::Toggle(key) and leaves the selection alone, a right click there is one on the node. For a collapsed group the app hides the members (their nodes and the edges between them), shows one node in their place and draws the edges to the outside to it. DN_STEP nodes move by whole grid steps instead of snapping their corner, so the members such a frame or cluster stands for (each snapped on its own) stay on the grid. A selected DN_RESIZE node shows a handle at its bottom right corner; dragging it reports DEv::Resize { key, rect, done } with the new box (the top left corner stays, at least 8 units; Esc sends the old box with done). DN_OUTLINE draws a node as an outline in the overview (an area, a backdrop). DgPaint::paint_under(g, f) (nothing by default) paints what lies under the grid into the backing store, a backdrop image say; draw it cached per zoom, since it runs with every repaint of the store. apps/diagramtest --frames shows all of it (a frame around four nodes that collapses into one, an area that resizes; tests/frames.uis), JFNetworker's groups and background picture use it (src/workspace/canvas/groups.rs, backdrop.rs).

Editing shapes: ui.shape_edit and ui.ruler#

For drawings made of shapes instead of nodes and ports, DG_EDIT makes ui.diagram the view only (the paint, zoom and pan), and ui.shape_edit, called right after it with the same id, takes the left button, the keys and the overlays: selection, the eight handles and the rotation handle, connection points with glue, guides, and the tools SE_POINTER, SE_CONNECT, SE_LINE, SE_RECT, SE_ELLIPSE, SE_TEXT, SE_PLACE, SE_FREEFORM, SE_ARC and SE_CPOINT. The app owns the model and applies what the user did:

ui.next_size(-1, -1);
ui.diagram(ID_CANVAS, &mut self.dg, &m, DG_EDIT, Some(self.painter.clone()), self.ver);
for ev in ui.shape_edit(ID_CANVAS, &mut self.se, &mut self.dg, &shapes, self.tool) {
    match ev {
        SeEv::Move { keys, total, done } => self.preview_move(&keys, total, done),
        SeEv::Resize { keys, from, to, done } => self.preview_resize(&keys, from, to, done),
        SeEv::Connect { a, ga, b, gb, .. } => self.add_connector(a, ga, b, gb),
        SeEv::Draw { tool, a, b } => self.add_shape(tool, a, b),
        SeEv::Cancel => self.drop_preview(),
        _ => {}
    }
}

A live gesture reports the whole change from the start of the drag with every step (done = false) and once more when it ends (done = true), so the app replaces its preview each time and keeps the last one as the undo step. ui.shape_edit_sems names the shapes and handles for screen readers and scripts. ui.ruler(id, &vp, &spec) is a ruler along the canvas in the document's units; dragging out of it makes a guide (RulerEv::Guide). The headers of lib/ui/shape_edit.rs and lib/ui/ruler.rs describe every gesture, JFDiagrammer uses both.

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