Skip to main content

bench_api/
lib.rs

1//! What a WebAssembly workbench and printCAD say to each other.
2//!
3//! The component interface (`wit/workbench.wit`) carries these types as
4//! JSON text; this crate is their one definition, used by the host
5//! (`wb_wasm`) and by the guest SDK. Ids (features, bodies) travel as
6//! UUID strings, lengths in millimetres, angles in degrees unless a field
7//! says otherwise, and every position is in world space.
8//!
9//! # Versions
10//!
11//! The crate's major and minor version are the contract's: 0.1.x speaks
12//! `printcad:workbench@0.1`. A patch release only adds, so a package
13//! written against an earlier 0.1.x keeps building and running:
14//!
15//! - Enums the host sends and a package matches on ([`Event`],
16//!   [`PanelEvent`], [`MenuScope`], [`PanelSlot`], [`Button`]) are
17//!   `#[non_exhaustive]`, as are `kernel_api`'s `FaceSurface` and
18//!   `ProfileSegment`: a match on them needs a wildcard arm, so a new
19//!   variant does not break it, and binds a variant's fields with `..`,
20//!   so a new field does not either. (The `exhaustive` feature lifts this for
21//!   printCAD itself, which makes every variant it sends; a package leaves
22//!   it off.)
23//! - Structs a package fills in derive `Default`; fill them with
24//!   `..Default::default()` and a new field does not break the literal.
25//! - Struct-like variants a package builds ([`Widget`], [`Request`],
26//!   [`Cell`], [`DiagramShape`], [`MarkKind`], [`Plan`], and `kernel_api`'s
27//!   `SolidOp` and the enums inside it) never gain a field within a minor
28//!   version: a new option comes as a new variant, or as a new struct that
29//!   derives `Default`.
30//! - A field added to a struct carries `#[serde(default)]`, so what an
31//!   earlier package sends still reads.
32//!
33//! A new minor version (0.2) is a new contract, which a host of 0.1 does
34//! not load.
35
36use serde::{Deserialize, Serialize};
37use serde_json::Value;
38
39pub use kernel_api::{self, SolidOp, TriMesh};
40
41/// The version of this contract, as a package's manifest names it in
42/// `api`. A host loads packages of its own major version.
43pub const API_VERSION: &str = "0.1";
44
45/// The full version of the contract this build speaks, patch included:
46/// what a manifest's `min_contract` is held against.
47pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
48
49/// Whether this build's contract is at least `min`, a version such as
50/// `0.1.4` (a `printcad:workbench@` prefix is read past). Only the
51/// numbers it names count, so `0.1` asks for any 0.1.x.
52pub fn contract_satisfies(min: &str) -> bool {
53    let numbers = |v: &str| -> Option<Vec<u64>> {
54        v.trim()
55            .trim_start_matches("printcad:workbench@")
56            .split('.')
57            .map(|part| part.trim().parse().ok())
58            .collect()
59    };
60    match (numbers(min), numbers(CONTRACT_VERSION)) {
61        (Some(min), Some(ours)) => {
62            let ours = ours.iter().copied().chain(std::iter::repeat(0));
63            for (want, have) in min.iter().zip(ours) {
64                if have != *want {
65                    return have > *want;
66                }
67            }
68            true
69        }
70        _ => false,
71    }
72}
73
74/// The component interface: the WIT world `workbench` of package
75/// `printcad:workbench`, whose values cross as JSON of this crate's types.
76pub const WIT: &str = include_str!("../wit/workbench.wit");
77
78/// Whether a package built against `api` runs on this host.
79pub fn api_compatible(api: &str) -> bool {
80    let major = |v: &str| {
81        let mut parts = v.split('.');
82        let first = parts.next().unwrap_or("");
83        // Before 1.0 a minor version breaks as a major one would.
84        if first == "0" {
85            format!("0.{}", parts.next().unwrap_or(""))
86        } else {
87            first.to_string()
88        }
89    };
90    let api = api.trim().trim_start_matches("printcad:workbench@");
91    major(api) == major(API_VERSION)
92}
93
94// ---------------------------------------------------------------- package
95
96/// `bench.toml`: what a package is and what it may reach.
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98pub struct Manifest {
99    /// Reverse-domain and unique, such as `acme.cam`. Its commands and
100    /// icons are named under it.
101    pub id: String,
102    pub name: String,
103    /// The package's own version.
104    pub version: String,
105    /// The contract it was built against: `printcad:workbench@0.1`.
106    pub api: String,
107    /// The earliest release of the contract it needs, patch included
108    /// (`0.1.4`), when it uses something a patch release added: a host
109    /// of an earlier one refuses it rather than draw part of it. Left
110    /// out, any host of `api` loads it.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub min_contract: Option<String>,
113    #[serde(default)]
114    pub description: String,
115    /// The feature kinds it owns; each starts with `id`.
116    #[serde(default)]
117    pub feature_kinds: Vec<String>,
118    #[serde(default)]
119    pub capabilities: Capabilities,
120    /// Memory an instance may grow to, in MiB (at most 4096).
121    #[serde(default = "default_memory_mb")]
122    pub memory_mb: u32,
123}
124
125fn default_memory_mb() -> u32 {
126    1024
127}
128
129impl Default for Manifest {
130    fn default() -> Self {
131        Self {
132            id: String::new(),
133            name: String::new(),
134            version: String::new(),
135            api: format!("printcad:workbench@{API_VERSION}"),
136            min_contract: None,
137            description: String::new(),
138            feature_kinds: Vec::new(),
139            capabilities: Capabilities::default(),
140            memory_mb: default_memory_mb(),
141        }
142    }
143}
144
145/// What a package asks to reach beyond itself. The user grants each.
146#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
147pub struct Capabilities {
148    /// Ask the user where to save a file it made, or a folder for several.
149    #[serde(default)]
150    pub save_dialog: bool,
151    /// Ask the user for a file to read: the package is handed its bytes.
152    #[serde(default)]
153    pub open_dialog: bool,
154    /// Run the native helpers it ships, from a job.
155    #[serde(default)]
156    pub helper: bool,
157    /// Open network connections.
158    #[serde(default)]
159    pub network: bool,
160}
161
162impl Capabilities {
163    /// The capabilities both `self` and `other` hold.
164    pub fn and(&self, other: &Capabilities) -> Capabilities {
165        Capabilities {
166            save_dialog: self.save_dialog && other.save_dialog,
167            open_dialog: self.open_dialog && other.open_dialog,
168            helper: self.helper && other.helper,
169            network: self.network && other.network,
170        }
171    }
172
173    /// Named, for the Preferences page and the log.
174    pub fn names(&self) -> Vec<&'static str> {
175        let mut out = Vec::new();
176        if self.save_dialog {
177            out.push("save_dialog");
178        }
179        if self.open_dialog {
180            out.push("open_dialog");
181        }
182        if self.helper {
183            out.push("helper");
184        }
185        if self.network {
186            out.push("network");
187        }
188        out
189    }
190}
191
192// ----------------------------------------------------------- registration
193
194/// What a bench declares once, when it is loaded (`describe`).
195#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
196pub struct Registration {
197    pub label: String,
198    #[serde(default)]
199    pub description: String,
200    /// An icon of the package (`icons/<name>.svg`) or of the design set.
201    #[serde(default)]
202    pub icon: String,
203    /// An edit-session bench: entering it remembers the bench to return to.
204    #[serde(default)]
205    pub modal: bool,
206    #[serde(default)]
207    pub tools: Vec<Tool>,
208    /// Keyboard actions beside the tools; a key sends `Event::Action`.
209    #[serde(default)]
210    pub actions: Vec<Action>,
211    /// Commands scripts and agents may call; each id starts with the
212    /// package id.
213    #[serde(default)]
214    pub commands: Vec<Command>,
215    /// Numeric fields of feature data the property panel shows in the
216    /// document's length unit.
217    #[serde(default)]
218    pub length_keys: Vec<String>,
219    /// Feature kinds of the package's own whose bodies are bought rather
220    /// than made (catalog hardware): the parts list marks them bought
221    /// until the user says otherwise, and exports and the slicer leave
222    /// them out.
223    #[serde(default)]
224    pub bought_kinds: Vec<String>,
225    /// The tools and commands, by id, the radial menu offers while the
226    /// bench is active, clockwise from the top, up to eight. The user can
227    /// choose others in Preferences; empty leaves the bench's most used
228    /// tools.
229    #[serde(default)]
230    pub radial: Vec<String>,
231}
232
233#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
234#[serde(rename_all = "snake_case")]
235pub enum ToolBehavior {
236    /// One of a group is active at a time; the default.
237    #[default]
238    Radio,
239    /// On or off on its own.
240    Check,
241    /// Fires once.
242    Action,
243}
244
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246pub struct Tool {
247    pub id: String,
248    pub label: String,
249    #[serde(default)]
250    pub icon: String,
251    #[serde(default)]
252    pub behavior: ToolBehavior,
253    #[serde(default)]
254    pub group: Option<String>,
255    /// Toolbar row: 1 or 2 are the bench's own.
256    #[serde(default = "one")]
257    pub row: u8,
258    #[serde(default)]
259    pub category: Option<String>,
260    /// Default keys, such as `"G"` or `"Shift+G"`.
261    #[serde(default)]
262    pub shortcuts: Vec<String>,
263}
264
265fn one() -> u8 {
266    1
267}
268
269impl Default for Tool {
270    fn default() -> Self {
271        Self {
272            id: String::new(),
273            label: String::new(),
274            icon: String::new(),
275            behavior: ToolBehavior::default(),
276            group: None,
277            row: one(),
278            category: None,
279            shortcuts: Vec::new(),
280        }
281    }
282}
283
284#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
285pub struct Action {
286    pub id: String,
287    pub label: String,
288    #[serde(default)]
289    pub shortcuts: Vec<String>,
290}
291
292#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
293#[serde(rename_all = "snake_case")]
294pub enum ParamKind {
295    Number,
296    Integer,
297    Bool,
298    String,
299    Id,
300    List,
301    #[default]
302    Any,
303}
304
305#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
306pub struct Param {
307    pub name: String,
308    #[serde(default)]
309    pub kind: ParamKind,
310    #[serde(default)]
311    pub required: bool,
312    #[serde(default)]
313    pub doc: String,
314}
315
316#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
317pub struct Command {
318    pub id: String,
319    pub summary: String,
320    #[serde(default)]
321    pub params: Vec<Param>,
322    #[serde(default)]
323    pub returns: String,
324    /// It changes nothing, so an agent may run it without asking.
325    #[serde(default)]
326    pub read_only: bool,
327    /// What a caller must know beyond the arguments: what it refuses, does
328    /// silently, or is easily mistaken for.
329    #[serde(default)]
330    pub notes: Vec<String>,
331    /// Working uses, each a Lua script run from an empty document.
332    #[serde(default)]
333    pub examples: Vec<Example>,
334    /// Other commands that do the related thing, by id.
335    #[serde(default)]
336    pub see_also: Vec<String>,
337}
338
339/// A working use of a command.
340#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
341pub struct Example {
342    /// What it shows, one line.
343    pub title: String,
344    /// A Lua script, run from an empty document, ending in `assert`s on
345    /// what it made.
346    pub script: String,
347}
348
349// --------------------------------------------------------------- document
350
351/// A feature of the document as a bench sees it.
352#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
353pub struct Node {
354    pub id: String,
355    pub kind: String,
356    pub name: String,
357    #[serde(default)]
358    pub body: Option<String>,
359    /// The data the feature builds from: what the user set with every
360    /// formula's value in.
361    pub data: Value,
362    #[serde(default)]
363    pub visible: bool,
364    /// The package and version that made it, `acme.cam 0.3.0`.
365    #[serde(default)]
366    pub made_by: Option<String>,
367    /// The features it reads.
368    #[serde(default)]
369    pub deps: Vec<String>,
370    /// Its place in its body's history.
371    #[serde(default)]
372    pub seq: u64,
373}
374
375#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
376pub struct Body {
377    pub id: String,
378    pub name: String,
379    pub hidden: bool,
380    /// Where the body sits: a row-major rigid 4x4 matrix.
381    pub placement: [f64; 16],
382    /// Its solid's bounds, when it has one.
383    #[serde(default)]
384    pub bounds: Option<([f32; 3], [f32; 3])>,
385}
386
387/// A number of a feature that a formula may set.
388#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
389pub struct Parameter {
390    /// What its formula is kept under.
391    pub key: String,
392    /// What formulas call it; `None` when they cannot refer to it.
393    #[serde(default)]
394    pub name: Option<String>,
395    pub label: String,
396    #[serde(default)]
397    pub dim: Dim,
398    /// A JSON pointer into the feature's data.
399    pub pointer: String,
400    /// What the data holds for one millimetre or degree.
401    #[serde(default = "unit_scale")]
402    pub scale: f64,
403    #[serde(default)]
404    pub integer: bool,
405}
406
407fn unit_scale() -> f64 {
408    1.0
409}
410
411impl Default for Parameter {
412    fn default() -> Self {
413        Self {
414            key: String::new(),
415            name: None,
416            label: String::new(),
417            dim: Dim::default(),
418            pointer: String::new(),
419            scale: unit_scale(),
420            integer: false,
421        }
422    }
423}
424
425#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
426#[serde(rename_all = "snake_case")]
427pub enum Dim {
428    #[default]
429    Length,
430    Angle,
431    Number,
432}
433
434/// How a feature shows in the tree, the property panel and the hover card.
435#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
436pub struct FeatureInfo {
437    pub icon: String,
438    pub kind_label: String,
439    #[serde(default)]
440    pub family_label: String,
441    /// It adds to its body's solid.
442    #[serde(default)]
443    pub builds_solid: bool,
444    /// How its work stands, shown as a badge beside its name in the tree.
445    /// It is asked for again when the feature changes or the bench calls
446    /// `host::redraw`.
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub status: Option<FeatureStatus>,
449}
450
451/// How a feature's work stands: a setup run, an operation checked.
452#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
453pub struct FeatureStatus {
454    pub state: FeatureState,
455    /// While `Running`, the job doing the work: the host shows how far
456    /// it is, rather than `fraction`.
457    #[serde(default)]
458    pub job: Option<u64>,
459    /// While `Running`, how far, 0 to 1.
460    #[serde(default)]
461    pub fraction: Option<f32>,
462    /// More words, shown when the pointer rests on the badge.
463    #[serde(default)]
464    pub note: Option<String>,
465}
466
467#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
468#[serde(rename_all = "snake_case")]
469pub enum FeatureState {
470    #[default]
471    NotRun,
472    Running,
473    Done,
474    Warnings,
475    Failed,
476    OutOfDate,
477}
478
479// ---------------------------------------------------------------- rebuild
480
481/// The bodies to rebuild, each with its features of this bench in history
482/// order.
483#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
484pub struct RebuildRequest {
485    pub bodies: Vec<BodyHistory>,
486}
487
488#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
489pub struct BodyHistory {
490    pub body: String,
491    pub features: Vec<Node>,
492}
493
494/// One body's plan.
495#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
496pub struct Rebuild {
497    pub body: String,
498    pub plan: Plan,
499    /// Threads drawn on round faces of the solid the plan builds.
500    #[serde(default, skip_serializing_if = "Vec::is_empty")]
501    pub threads: Vec<CosmeticThread>,
502}
503
504/// A thread drawn on a round face, never modelled: the face keeps its
505/// size (a bore its tap drill, a shank its major diameter) and a helix of
506/// the thread's pitch is drawn just off it, inside a bore and outside a
507/// shank, in every bench and never exported. A thread with a
508/// `designation` is also named where the app lists threads: a callout at
509/// the face's end, the parts list, and a STEP export's callouts.
510#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
511pub struct CosmeticThread {
512    /// The feature it belongs to: drawn while that feature shows.
513    pub feature: String,
514    /// A point on the round face, in the body's own frame, as the plan's
515    /// ops are.
516    pub point: [f64; 3],
517    /// The face's name ([`FaceRef::name`], `geom.face_loops`), found
518    /// before `point` while the solid still has a face of that name.
519    #[serde(default)]
520    pub name: Option<u64>,
521    /// mm a turn.
522    pub pitch: f64,
523    /// How far it runs from the face's end nearest `point`; 0 runs the
524    /// whole face.
525    #[serde(default)]
526    pub length: f64,
527    #[serde(default)]
528    pub left_handed: bool,
529    /// What the thread is called ("M6", "1/4-20 UNC"); `None` names it
530    /// nowhere.
531    #[serde(default, skip_serializing_if = "Option::is_none")]
532    pub designation: Option<String>,
533}
534
535/// What a [`Rebuild`] asks of the kernel.
536///
537/// A package builds these, so a variant keeps its fields for as long as
538/// the contract's minor version holds: a new option comes as a new
539/// variant, or as a new struct that derives `Default`.
540#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
541#[serde(tag = "type", rename_all = "snake_case")]
542pub enum Plan {
543    /// Build these ops; `op_features[i]` is the feature op `i` is for.
544    Ops {
545        ops: Vec<SolidOp>,
546        op_features: Vec<String>,
547    },
548    /// Nothing to build: the body's solid goes.
549    #[default]
550    Empty,
551    /// The plan could not be made; the message goes on `feature`.
552    Error {
553        #[serde(default)]
554        feature: Option<String>,
555        message: String,
556    },
557}
558
559// ------------------------------------------------------------------ input
560
561/// Something the user did while the bench is active, with what was under
562/// the cursor.
563#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
564pub struct Input {
565    pub event: Event,
566    /// The active tool, with a `:variant` suffix when one was picked.
567    #[serde(default)]
568    pub tool: Option<String>,
569    #[serde(default)]
570    pub pointer: Pointer,
571}
572
573/// Where the cursor is and what it is over.
574#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
575pub struct Pointer {
576    /// Viewport pixels.
577    #[serde(default)]
578    pub position: Option<[f32; 2]>,
579    /// The ray under the cursor: origin and unit direction.
580    #[serde(default)]
581    pub ray: Option<([f32; 3], [f32; 3])>,
582    /// The point of a body under the cursor.
583    #[serde(default)]
584    pub world: Option<[f32; 3]>,
585    #[serde(default)]
586    pub body: Option<String>,
587    /// The selected body and the face and edges picked on it.
588    #[serde(default)]
589    pub selected_body: Option<String>,
590    #[serde(default)]
591    pub face: Option<FaceRef>,
592    /// Every face picked, in the order picked; `face` is the last.
593    #[serde(default)]
594    pub faces: Vec<FaceRef>,
595    #[serde(default)]
596    pub edges: Vec<EdgeRef>,
597    /// The feature selected in the tree.
598    #[serde(default)]
599    pub active_feature: Option<String>,
600    #[serde(default)]
601    pub ctrl: bool,
602    /// The face under the cursor, whatever is selected: what a click
603    /// would pick there.
604    #[serde(default, skip_serializing_if = "Option::is_none")]
605    pub hover_face: Option<FaceRef>,
606    /// The edge under the cursor, when one is within reach.
607    #[serde(default, skip_serializing_if = "Option::is_none")]
608    pub hover_edge: Option<EdgeRef>,
609    /// The vertex under the cursor, when one is within a few pixels: an
610    /// end of the edge under it.
611    #[serde(default, skip_serializing_if = "Option::is_none")]
612    pub vertex: Option<VertexRef>,
613}
614
615/// A vertex of a body's solid, where it sits.
616#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
617pub struct VertexRef {
618    pub body: String,
619    pub point: [f32; 3],
620}
621
622#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
623pub struct FaceRef {
624    pub point: [f32; 3],
625    pub normal: [f32; 3],
626    /// The face's exact surface, when known.
627    #[serde(default)]
628    pub surface: Option<kernel_api::FaceSurface>,
629    /// The kernel's name for the face, which a rebuild keeps: what
630    /// `geom.face_loops` and a [`CosmeticThread`] find it by.
631    #[serde(default, skip_serializing_if = "Option::is_none")]
632    pub name: Option<u64>,
633}
634
635#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
636pub struct EdgeRef {
637    pub body: String,
638    pub point: [f32; 3],
639    pub direction: [f32; 3],
640    pub length: f32,
641    /// A circle's or an arc's centre, axis and radius, when the edge is
642    /// one.
643    #[serde(default)]
644    pub circle: Option<EdgeCircle>,
645    /// The names of the two faces it runs between, which name the edge
646    /// across rebuilds.
647    #[serde(default, skip_serializing_if = "Option::is_none")]
648    pub faces: Option<[u64; 2]>,
649}
650
651/// A circular edge's centre and axis (world space) and radius, mm.
652#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
653pub struct EdgeCircle {
654    pub center: [f32; 3],
655    pub normal: [f32; 3],
656    pub radius: f32,
657}
658
659#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
660#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
661#[serde(rename_all = "snake_case")]
662pub enum Button {
663    Left,
664    Middle,
665    Right,
666    Other,
667}
668
669#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
670#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
671#[serde(tag = "type", rename_all = "snake_case")]
672pub enum Event {
673    Press {
674        button: Button,
675    },
676    Release {
677        button: Button,
678    },
679    Move,
680    /// A key by name: `Escape`, `Enter`, `A`, `Digit1`.
681    Key {
682        key: String,
683        down: bool,
684    },
685    /// The active tool changed to `Input::tool`.
686    ToolActivated,
687    /// A registered action's key.
688    Action {
689        id: String,
690    },
691    Activated,
692    Deactivated,
693    /// Formulas moved the values of these features.
694    ValuesMoved {
695        features: Vec<String>,
696    },
697    /// A job this bench started finished.
698    JobFinished {
699        job: u64,
700        result: Result<String, String>,
701    },
702    /// The user asked to edit a feature of the bench's: a double click on
703    /// its tree row. Selecting a feature alone never opens it; its menu
704    /// may offer to (`menu_items`).
705    EditFeature {
706        feature: String,
707    },
708    /// A feature of the bench's dragged in the tree and dropped just
709    /// before (`before`) or after `target`. Used, the bench decides: it
710    /// moves it itself (`calls::MOVE_FEATURE`, or its own data) or leaves
711    /// it where it was; passed over, the host moves it in its body's
712    /// history. Either way it is one undo step.
713    FeatureMoved {
714        feature: String,
715        target: String,
716        before: bool,
717    },
718    /// The files the user picked for `Request::OpenFile` of this `id`;
719    /// none when the dialog was cancelled.
720    FileOpened {
721        id: String,
722        files: Vec<OpenedFile>,
723    },
724}
725
726/// A file the user picked to open: its name, without the folder, and its
727/// bytes.
728#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
729pub struct OpenedFile {
730    pub name: String,
731    pub contents: Vec<u8>,
732}
733
734/// A kind of file a dialog offers: its label and extensions, without the
735/// dot.
736#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
737pub struct FileKind {
738    pub label: String,
739    pub extensions: Vec<String>,
740}
741
742/// A file to write into the folder `Request::SaveFiles` asks for: a plain
743/// file name, no folder in it.
744#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
745pub struct FileToWrite {
746    pub name: String,
747    pub contents: Vec<u8>,
748}
749
750// ------------------------------------------------------------------ frame
751
752/// Everything a bench shows. The host keeps it and asks again only after
753/// an event reached the bench, the document changed, the selection
754/// changed, or the bench asked (`redraw`); world-space drawing is projected
755/// by the host every frame, so the view moves freely without asking.
756#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
757pub struct Frame {
758    #[serde(default)]
759    pub hud: Hud,
760    #[serde(default)]
761    pub status: Status,
762    /// An open task: the right panel shows `panel` under it.
763    #[serde(default)]
764    pub task: Option<Task>,
765    #[serde(default)]
766    pub panel: Vec<Widget>,
767    /// The feature whose edit session is open.
768    #[serde(default)]
769    pub editing: Option<String>,
770    /// While `editing`, the view stays square to its plane.
771    #[serde(default)]
772    pub locks_view: bool,
773    /// Bare digits go to the bench (a length being typed).
774    #[serde(default)]
775    pub numeric_input: bool,
776    /// Check and action tools that draw pressed.
777    #[serde(default)]
778    pub toggled: Vec<String>,
779    /// Tools that draw disabled.
780    #[serde(default)]
781    pub disabled: Vec<String>,
782    #[serde(default)]
783    pub lines: Vec<Polyline>,
784    #[serde(default)]
785    pub marks: Vec<Mark>,
786    #[serde(default)]
787    pub labels: Vec<Label>,
788    #[serde(default)]
789    pub meshes: Vec<Mesh>,
790    /// Meshes the package keeps (`host::mesh_create`), drawn by handle:
791    /// a large mesh crosses once and is then updated in part.
792    #[serde(default, skip_serializing_if = "Vec::is_empty")]
793    pub kept: Vec<KeptMesh>,
794    /// Flat regions the host fills, and hatches where asked.
795    #[serde(default, skip_serializing_if = "Vec::is_empty")]
796    pub regions: Vec<Region>,
797    /// A strip under the view, its widgets in a row, while the bench is
798    /// active: a transport bar's timeline, buttons and clock. Its events
799    /// come with `PanelSlot::Transport`.
800    #[serde(default, skip_serializing_if = "Vec::is_empty")]
801    pub transport: Vec<Widget>,
802    /// A card over the view beside what it edits, while the bench is
803    /// active: a quick edit of a value or two. Its events come with
804    /// `PanelSlot::Card`.
805    #[serde(default, skip_serializing_if = "Option::is_none")]
806    pub card: Option<FloatingCard>,
807    /// Something in it moves: while set and the bench is active, the
808    /// host asks for the frame again every frame, at the display's rate,
809    /// rather than waiting for an event.
810    #[serde(default)]
811    pub animating: bool,
812}
813
814/// A card over the view, next to what it edits: a quick edit of a value
815/// or two (a dimension, a corner's size). Anything with more to it is a
816/// task in the right panel. The host draws `widgets` as it draws a task
817/// panel's, with OK and Cancel under them; Enter is OK and Escape Cancel.
818/// OK and Cancel reach the bench as [`PanelEvent::CardClose`]. Edits wait
819/// in the bench until OK: the host makes what OK writes one undo step,
820/// and takes back anything written while the card was open on Cancel.
821/// A click in the view elsewhere is OK, while OK is allowed.
822///
823/// With a `hint` the card is a readout instead: the values a tool is
824/// drawing with, typed through the bench's own keys. The host draws the
825/// hint in place of OK and Cancel, leaves the keys and the pointer with
826/// the bench, holds no undo step and sends no `CardClose`. One card shows
827/// at a time.
828#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
829#[serde(default)]
830pub struct FloatingCard {
831    /// Names the card: one with a new id opens afresh, the field named by
832    /// `focus` taking the keys again.
833    pub id: String,
834    pub title: String,
835    pub icon: Option<String>,
836    /// The point it is beside, in world space.
837    pub at: Option<[f32; 3]>,
838    /// The point it is beside in viewport pixels, when it has no `at`;
839    /// left out of both, the view's middle.
840    pub screen: Option<[f32; 2]>,
841    pub widgets: Vec<Widget>,
842    /// The id of the text or number field that has the keys as the card
843    /// opens, its text selected so the first key typed replaces it.
844    pub focus: Option<String>,
845    /// OK's words; `OK` when empty.
846    pub ok: String,
847    /// Why OK is held back: written under the widgets, OK disabled and
848    /// Enter and a click elsewhere doing nothing.
849    pub refusal: Option<String>,
850    /// The line under the widgets of a readout card, in place of OK and
851    /// Cancel: what the keys do (`Tab next · Enter places it`).
852    pub hint: Option<String>,
853    /// OK alone, no Cancel: Escape is OK too, and only a refused card is
854    /// dropped. For what a step already made leaves to set.
855    pub ok_only: bool,
856}
857
858#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
859pub struct Hud {
860    /// The tool hint at the top left.
861    #[serde(default)]
862    pub tool: Option<ToolHint>,
863    /// The top-right badge.
864    #[serde(default)]
865    pub badge: Option<(Rgb, String)>,
866    #[serde(default)]
867    pub legend: Vec<(Rgb, String)>,
868    /// Mono readouts at the bottom right.
869    #[serde(default)]
870    pub footer: Vec<String>,
871}
872
873#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
874pub struct ToolHint {
875    pub icon: String,
876    pub name: String,
877    pub prompt: String,
878    /// `(key, meaning)` chips.
879    #[serde(default)]
880    pub keys: Vec<(String, String)>,
881}
882
883#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
884pub struct Status {
885    #[serde(default)]
886    pub state: Option<(Rgb, String)>,
887    #[serde(default)]
888    pub selection: Option<String>,
889    #[serde(default)]
890    pub mode: Option<String>,
891}
892
893#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
894pub struct Task {
895    pub title: String,
896    #[serde(default)]
897    pub icon: String,
898    /// OK and Cancel; otherwise a single Close.
899    #[serde(default)]
900    pub confirmable: bool,
901}
902
903/// Linear RGB in 0..=1.
904pub type Rgb = [f32; 3];
905
906/// A line through world points, drawn a constant `width` pixels wide over
907/// the scene.
908#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
909pub struct Polyline {
910    pub points: Vec<[f32; 3]>,
911    pub color: Rgb,
912    #[serde(default = "one_px")]
913    pub width: f32,
914    #[serde(default)]
915    pub dashed: bool,
916    #[serde(default)]
917    pub closed: bool,
918}
919
920fn one_px() -> f32 {
921    1.5
922}
923
924impl Default for Polyline {
925    fn default() -> Self {
926        Self {
927            points: Vec::new(),
928            color: [1.0; 3],
929            width: one_px(),
930            dashed: false,
931            closed: false,
932        }
933    }
934}
935
936#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
937pub struct Mark {
938    pub at: [f32; 3],
939    pub color: Rgb,
940    pub kind: MarkKind,
941}
942
943/// What a [`Mark`] draws.
944///
945/// A package builds these, so a variant keeps its fields for as long as
946/// the contract's minor version holds: a new option comes as a new
947/// variant, or as a new struct that derives `Default`.
948#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
949#[serde(tag = "type", rename_all = "snake_case")]
950pub enum MarkKind {
951    Dot { radius: f32 },
952    Cross { size: f32 },
953    Icon { name: String, size: f32 },
954}
955
956impl Default for MarkKind {
957    fn default() -> Self {
958        MarkKind::Dot { radius: 4.0 }
959    }
960}
961
962#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
963pub struct Label {
964    pub at: [f32; 3],
965    pub text: String,
966    pub color: Rgb,
967    #[serde(default = "label_size")]
968    pub size: f32,
969    /// A rounded pill behind it.
970    #[serde(default)]
971    pub pill: bool,
972    #[serde(default)]
973    pub mono: bool,
974}
975
976fn label_size() -> f32 {
977    12.0
978}
979
980impl Default for Label {
981    fn default() -> Self {
982        Self {
983            at: [0.0; 3],
984            text: String::new(),
985            color: [1.0; 3],
986            size: label_size(),
987            pill: false,
988            mono: false,
989        }
990    }
991}
992
993/// A mesh drawn in the scene, never picked.
994#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
995pub struct Mesh {
996    pub positions: Vec<[f32; 3]>,
997    pub indices: Vec<u32>,
998    pub color: Rgb,
999    #[serde(default)]
1000    pub wireframe: bool,
1001    #[serde(default = "opaque")]
1002    pub opacity: f32,
1003    /// Over everything, whatever is in front of it.
1004    #[serde(default)]
1005    pub on_top: bool,
1006    /// A colour per position, multiplying `color` (leave that white to
1007    /// show them as they are). Ignored unless it holds one per position.
1008    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1009    pub colors: Vec<Rgb>,
1010}
1011
1012fn opaque() -> f32 {
1013    1.0
1014}
1015
1016impl Default for Mesh {
1017    fn default() -> Self {
1018        Self {
1019            positions: Vec::new(),
1020            indices: Vec::new(),
1021            color: [1.0; 3],
1022            wireframe: false,
1023            opacity: opaque(),
1024            on_top: false,
1025            colors: Vec::new(),
1026        }
1027    }
1028}
1029
1030/// A kept mesh as a frame draws it: its handle and how.
1031#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1032pub struct KeptMesh {
1033    pub handle: u64,
1034    /// Multiplies the mesh's own colours, where it has them.
1035    pub color: Rgb,
1036    #[serde(default)]
1037    pub wireframe: bool,
1038    #[serde(default = "opaque")]
1039    pub opacity: f32,
1040    #[serde(default)]
1041    pub on_top: bool,
1042}
1043
1044impl Default for KeptMesh {
1045    fn default() -> Self {
1046        Self {
1047            handle: 0,
1048            color: [1.0; 3],
1049            wireframe: false,
1050            opacity: opaque(),
1051            on_top: false,
1052        }
1053    }
1054}
1055
1056/// A flat region in world space: an outline and the holes in it, all on
1057/// one plane, filled and, with `hatch`, hatched in lines that far apart.
1058#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1059pub struct Region {
1060    pub outline: Vec<[f32; 3]>,
1061    #[serde(default)]
1062    pub holes: Vec<Vec<[f32; 3]>>,
1063    pub color: Rgb,
1064    /// The fill's; 0 leaves only the hatch.
1065    #[serde(default = "region_opacity")]
1066    pub opacity: f32,
1067    /// mm between hatch lines; none for no hatch.
1068    #[serde(default)]
1069    pub hatch: Option<f32>,
1070    /// The hatch lines' angle in the region's plane, degrees.
1071    #[serde(default = "hatch_angle")]
1072    pub hatch_angle: f32,
1073    /// Over everything, whatever is in front of it.
1074    #[serde(default)]
1075    pub on_top: bool,
1076}
1077
1078fn region_opacity() -> f32 {
1079    0.35
1080}
1081
1082fn hatch_angle() -> f32 {
1083    45.0
1084}
1085
1086impl Default for Region {
1087    fn default() -> Self {
1088        Self {
1089            outline: Vec::new(),
1090            holes: Vec::new(),
1091            color: [1.0; 3],
1092            opacity: region_opacity(),
1093            hatch: None,
1094            hatch_angle: hatch_angle(),
1095            on_top: false,
1096        }
1097    }
1098}
1099
1100// ------------------------------------------------------------------ panel
1101
1102/// One element of a declared panel. The host draws it with the app's
1103/// widgets and sends back a [`PanelEvent`] when the user changes it.
1104///
1105/// A package builds these, so a variant keeps its fields for as long as
1106/// the contract's minor version holds: a new option comes as a new
1107/// variant, or as a new struct that derives `Default`.
1108#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1109#[serde(tag = "type", rename_all = "snake_case")]
1110pub enum Widget {
1111    Heading {
1112        text: String,
1113    },
1114    Text {
1115        text: String,
1116        #[serde(default)]
1117        mono: bool,
1118    },
1119    Note {
1120        #[serde(default)]
1121        kind: NoteKind,
1122        #[serde(default)]
1123        title: Option<String>,
1124        text: String,
1125    },
1126    /// A number. Bound to a parameter of a feature (`bind`), it takes
1127    /// formulas: the host keeps the formula, and the bench is told the
1128    /// value.
1129    Number {
1130        id: String,
1131        label: String,
1132        value: f64,
1133        #[serde(default)]
1134        dim: Dim,
1135        #[serde(default)]
1136        bind: Option<Bind>,
1137        #[serde(default)]
1138        min: Option<f64>,
1139        #[serde(default)]
1140        max: Option<f64>,
1141        #[serde(default = "two")]
1142        decimals: usize,
1143        #[serde(default)]
1144        error: Option<String>,
1145    },
1146    Choice {
1147        id: String,
1148        label: String,
1149        options: Vec<String>,
1150        selected: usize,
1151    },
1152    Toggle {
1153        id: String,
1154        label: String,
1155        on: bool,
1156    },
1157    TextField {
1158        id: String,
1159        label: String,
1160        value: String,
1161    },
1162    Button {
1163        id: String,
1164        label: String,
1165        #[serde(default)]
1166        style: ButtonStyle,
1167        #[serde(default = "yes")]
1168        enabled: bool,
1169    },
1170    /// A row asking for something to be clicked in the viewport. A click
1171    /// on it arms it (`PanelEvent::Pick`); the bench then reads the picks
1172    /// from the events that follow.
1173    Pick {
1174        id: String,
1175        label: String,
1176        /// What has been picked, in words.
1177        #[serde(default)]
1178        value: Option<String>,
1179        #[serde(default)]
1180        armed: bool,
1181    },
1182    /// Selectable rows.
1183    List {
1184        id: String,
1185        items: Vec<ListItem>,
1186        #[serde(default)]
1187        selected: Option<usize>,
1188    },
1189    /// Columns of text, one row selectable. A column marked in
1190    /// `editable` takes typing in its cells (`PanelEvent::Cell`): a tool
1191    /// table, a list of settings by row.
1192    Table {
1193        id: String,
1194        columns: Vec<String>,
1195        rows: Vec<Vec<String>>,
1196        #[serde(default)]
1197        selected: Option<usize>,
1198        /// One per column; a column left out is read-only.
1199        #[serde(default)]
1200        editable: Vec<bool>,
1201    },
1202    Group {
1203        title: String,
1204        #[serde(default = "yes")]
1205        open: bool,
1206        children: Vec<Widget>,
1207    },
1208    Progress {
1209        label: String,
1210        /// `None` while the amount is unknown.
1211        #[serde(default)]
1212        fraction: Option<f32>,
1213        /// A job of the bench's: the host shows how far it is.
1214        #[serde(default)]
1215        job: Option<u64>,
1216    },
1217    Separator,
1218    /// A drawing: a schematic of what the panel edits, with its measures
1219    /// marked beside the parts they size. It is drawn in a space of its
1220    /// own, `[0, width] × [0, height]` with y up, which the host fits to
1221    /// the panel's width; strokes and text keep their pixel size. A press
1222    /// on it, and every move of a drag begun on it, comes back as
1223    /// `PanelEvent::DiagramPress` in those coordinates: a timeline seeks
1224    /// where it is pressed.
1225    Diagram {
1226        id: String,
1227        width: f32,
1228        height: f32,
1229        #[serde(default)]
1230        shapes: Vec<DiagramShape>,
1231        #[serde(default)]
1232        dimensions: Vec<Dimension>,
1233        #[serde(default)]
1234        callouts: Vec<Callout>,
1235    },
1236    /// A task panel's title with an icon, on a raised band.
1237    Header {
1238        icon: String,
1239        title: String,
1240    },
1241    /// A label and a value beside it, read only.
1242    Value {
1243        label: String,
1244        value: String,
1245        #[serde(default)]
1246        mono: bool,
1247    },
1248    /// Widgets side by side, going on to the next line when the panel is
1249    /// narrow. A field with an empty label takes no label column here.
1250    Row {
1251        children: Vec<Widget>,
1252    },
1253    /// A widget with words shown while the pointer rests on it.
1254    Hinted {
1255        hint: String,
1256        widget: Box<Widget>,
1257    },
1258    /// A widget with words and a figure under them (a [`Widget::Diagram`])
1259    /// shown while the pointer rests on it.
1260    HintedFigure {
1261        hint: String,
1262        figure: Box<Widget>,
1263        widget: Box<Widget>,
1264    },
1265    /// A number dragged along a range, for a spread or a place in time
1266    /// rather than a measure; it comes back as `PanelEvent::Number`.
1267    Slider {
1268        id: String,
1269        label: String,
1270        value: f64,
1271        min: f64,
1272        max: f64,
1273        /// The values it stops at, every `step` from `min`.
1274        #[serde(default)]
1275        step: Option<f64>,
1276        #[serde(default = "two")]
1277        decimals: usize,
1278        /// The value written beside it.
1279        #[serde(default = "yes")]
1280        show_value: bool,
1281    },
1282    /// Rows of cells under column titles, some cells editable; it scrolls
1283    /// sideways when wider than the panel.
1284    Sheet {
1285        id: String,
1286        columns: Vec<String>,
1287        rows: Vec<Vec<Cell>>,
1288    },
1289    /// A folding section with a count and a summary while closed.
1290    Section(PanelSection),
1291    /// One item: an icon, a name, a value at the end, tags and badges.
1292    Item(Item),
1293    /// Items, selectable, narrowed by a [`Widget::Filter`].
1294    Items(ItemList),
1295    /// A filter field for item lists, with a kind selector.
1296    Filter(FilterField),
1297    /// A state in a few words, as a toned pill.
1298    Status(StatusLine),
1299    /// Widgets one under another.
1300    Stack(Stack),
1301    /// Widgets side by side.
1302    Flow(Flow),
1303    /// A widget taking the rest of a [`Widget::Flow`]'s width.
1304    Fill(Fill),
1305    /// Fields sharing one label column of their own.
1306    Fields(Fields),
1307    /// A field with its label beside it at its own width, no column.
1308    Inline(Inline),
1309    /// What is picked in the view, as a chip that clears.
1310    PickChip(PickChip),
1311    /// A line of text the user types, with a placeholder while empty.
1312    Entry(Entry),
1313    /// What the task panel's header shows under and beside the title.
1314    TaskHeader(TaskHeader),
1315    /// A number field with its drag speed, width and state, and as a
1316    /// stepper.
1317    Quantity(Quantity),
1318    /// A labelled check box.
1319    Check(Check),
1320    /// A choice of a few, with its width and state.
1321    Select(Select),
1322    /// Fields in a two-column grid, labels as wide as the longest.
1323    Grid(FieldGrid),
1324    /// A note the user can click.
1325    Alert(Alert),
1326    /// A raised card holding widgets, under an icon and a title.
1327    Card(Card),
1328    /// A line of words in a size and a tone.
1329    Caption(Caption),
1330    /// Room between widgets.
1331    Gap(Gap),
1332    /// Lines plotted along a strip.
1333    Plot(Plot),
1334    /// Colours to click, the chosen ones ringed.
1335    Swatches(Swatches),
1336    /// A colour, edited in the system's picker.
1337    Color(ColorField),
1338    /// A number dragged along a range, written with a suffix of its own.
1339    Range(Range),
1340    /// A frameless button as wide as the panel: one of a list of places.
1341    RowButton(RowButton),
1342    /// Words that light up while chosen, as one of a few side by side.
1343    Selectable(Selectable),
1344    /// Pictures to choose among, each over its name.
1345    Gallery(Gallery),
1346    /// A titled, bordered group of rows, as the Preferences pages draw
1347    /// theirs.
1348    Settings(SettingsGroup),
1349    /// Widgets in rows of a few columns, each column as wide as its
1350    /// widest: a table of readings.
1351    Cells(Cells),
1352    /// A small icon button on its own, its words on hover.
1353    Action(PanelAction),
1354    /// A row of icon buttons under one label, each lit while on: an
1355    /// editor's alignment buttons.
1356    Toggles(Toggles),
1357}
1358
1359/// The widgets a widget holds, in the order they are drawn: one match for
1360/// [`Widget::children`] and [`Widget::children_mut`].
1361macro_rules! widget_children {
1362    ($widget:expr, $deref:ident, $iter:ident $(, $mut:ident)?) => {{
1363        let mut out = Vec::new();
1364        match $widget {
1365            Widget::Group { children, .. }
1366            | Widget::Row { children }
1367            | Widget::Section(PanelSection { children, .. })
1368            | Widget::Stack(Stack { children, .. })
1369            | Widget::Flow(Flow { children, .. })
1370            | Widget::Fields(Fields { children, .. })
1371            | Widget::Grid(FieldGrid { children, .. })
1372            | Widget::Card(Card { children, .. })
1373            | Widget::Cells(Cells { children, .. })
1374            | Widget::Settings(SettingsGroup { children, .. }) => out.extend(children),
1375            Widget::Hinted { widget, .. } => out.push(&$($mut)? **widget),
1376            Widget::HintedFigure { figure, widget, .. } => {
1377                out.push(&$($mut)? **figure);
1378                out.push(&$($mut)? **widget);
1379            }
1380            Widget::Fill(Fill { child }) | Widget::Inline(Inline { child }) => {
1381                out.push(&$($mut)? **child)
1382            }
1383            Widget::Item(item) => out.extend(item.field.$deref()),
1384            Widget::Items(list) => {
1385                for item in list.items.$iter() {
1386                    out.extend(item.field.$deref());
1387                }
1388            }
1389            Widget::Heading { .. }
1390            | Widget::Text { .. }
1391            | Widget::Note { .. }
1392            | Widget::Number { .. }
1393            | Widget::Choice { .. }
1394            | Widget::Toggle { .. }
1395            | Widget::TextField { .. }
1396            | Widget::Button { .. }
1397            | Widget::Pick { .. }
1398            | Widget::List { .. }
1399            | Widget::Table { .. }
1400            | Widget::Progress { .. }
1401            | Widget::Separator
1402            | Widget::Diagram { .. }
1403            | Widget::Header { .. }
1404            | Widget::Value { .. }
1405            | Widget::Slider { .. }
1406            | Widget::Sheet { .. }
1407            | Widget::Filter(_)
1408            | Widget::Status(_)
1409            | Widget::PickChip(_)
1410            | Widget::Entry(_)
1411            | Widget::TaskHeader(_)
1412            | Widget::Quantity(_)
1413            | Widget::Check(_)
1414            | Widget::Select(_)
1415            | Widget::Alert(_)
1416            | Widget::Caption(_)
1417            | Widget::Gap(_)
1418            | Widget::Plot(_)
1419            | Widget::Swatches(_)
1420            | Widget::Color(_)
1421            | Widget::Range(_)
1422            | Widget::RowButton(_)
1423            | Widget::Selectable(_)
1424            | Widget::Gallery(_)
1425            | Widget::Action(_)
1426            | Widget::Toggles(_) => {}
1427        }
1428        out
1429    }};
1430}
1431
1432impl Widget {
1433    /// The widgets this one holds, in the order they are drawn: a
1434    /// container's children, a hinted widget (and its figure), an item's
1435    /// field. Empty for a widget that holds none.
1436    pub fn children(&self) -> Vec<&Widget> {
1437        widget_children!(self, as_deref, iter)
1438    }
1439
1440    /// [`Widget::children`], to change in place.
1441    pub fn children_mut(&mut self) -> Vec<&mut Widget> {
1442        widget_children!(self, as_deref_mut, iter_mut, mut)
1443    }
1444
1445    /// This widget and every widget it holds, at any depth, each before
1446    /// its children.
1447    pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Widget)) {
1448        visit(self);
1449        for child in self.children() {
1450            child.walk(visit);
1451        }
1452    }
1453
1454    /// [`Widget::walk`], to change in place.
1455    pub fn walk_mut(&mut self, visit: &mut impl FnMut(&mut Widget)) {
1456        visit(self);
1457        for child in self.children_mut() {
1458            child.walk_mut(visit);
1459        }
1460    }
1461
1462    /// The id its events carry, for a widget that has one.
1463    pub fn id(&self) -> Option<&str> {
1464        let id = match self {
1465            Widget::Number { id, .. }
1466            | Widget::Choice { id, .. }
1467            | Widget::Toggle { id, .. }
1468            | Widget::TextField { id, .. }
1469            | Widget::Button { id, .. }
1470            | Widget::Pick { id, .. }
1471            | Widget::List { id, .. }
1472            | Widget::Table { id, .. }
1473            | Widget::Diagram { id, .. }
1474            | Widget::Slider { id, .. }
1475            | Widget::Sheet { id, .. }
1476            | Widget::Section(PanelSection { id, .. })
1477            | Widget::Item(Item { id, .. })
1478            | Widget::Items(ItemList { id, .. })
1479            | Widget::Filter(FilterField { id, .. })
1480            | Widget::PickChip(PickChip { id, .. })
1481            | Widget::Entry(Entry { id, .. })
1482            | Widget::Quantity(Quantity { id, .. })
1483            | Widget::Check(Check { id, .. })
1484            | Widget::Select(Select { id, .. })
1485            | Widget::Swatches(Swatches { id, .. })
1486            | Widget::Color(ColorField { id, .. })
1487            | Widget::Range(Range { id, .. })
1488            | Widget::RowButton(RowButton { id, .. })
1489            | Widget::Selectable(Selectable { id, .. })
1490            | Widget::Gallery(Gallery { id, .. })
1491            | Widget::Action(PanelAction { id, .. })
1492            | Widget::Toggles(Toggles { id, .. }) => id,
1493            Widget::Alert(Alert { id, .. }) => id.as_ref()?,
1494            _ => return None,
1495        };
1496        (!id.is_empty()).then_some(id.as_str())
1497    }
1498
1499    /// The label a field writes in its label column, for a field that has
1500    /// one: a check box's or a button's own words are not one.
1501    pub fn field_label(&self) -> Option<&str> {
1502        let label = match self {
1503            Widget::Number { label, .. }
1504            | Widget::Choice { label, .. }
1505            | Widget::TextField { label, .. }
1506            | Widget::Pick { label, .. }
1507            | Widget::Value { label, .. }
1508            | Widget::Slider { label, .. }
1509            | Widget::PickChip(PickChip { label, .. })
1510            | Widget::Entry(Entry { label, .. })
1511            | Widget::Quantity(Quantity { label, .. })
1512            | Widget::Check(Check { label, .. })
1513            | Widget::Select(Select { label, .. })
1514            | Widget::Range(Range { label, .. })
1515            | Widget::Color(ColorField { label, .. })
1516            | Widget::Toggles(Toggles { label, .. })
1517            | Widget::Flow(Flow { label, .. }) => label,
1518            _ => return None,
1519        };
1520        (!label.is_empty()).then_some(label.as_str())
1521    }
1522}
1523
1524/// `widgets` keeping only those `keep` holds to, at any depth: a widget
1525/// left out goes with what it holds. A widget held alone (a hint's, a
1526/// fill's) stays whatever `keep` says of it.
1527pub fn retain_widgets(widgets: &mut Vec<Widget>, keep: &mut impl FnMut(&Widget) -> bool) {
1528    widgets.retain(|w| keep(w));
1529    for widget in widgets {
1530        retain_within(widget, keep);
1531    }
1532}
1533
1534fn retain_within(widget: &mut Widget, keep: &mut impl FnMut(&Widget) -> bool) {
1535    match widget {
1536        Widget::Group { children, .. }
1537        | Widget::Row { children }
1538        | Widget::Section(PanelSection { children, .. })
1539        | Widget::Stack(Stack { children, .. })
1540        | Widget::Flow(Flow { children, .. })
1541        | Widget::Fields(Fields { children, .. })
1542        | Widget::Grid(FieldGrid { children, .. })
1543        | Widget::Card(Card { children, .. })
1544        | Widget::Cells(Cells { children, .. })
1545        | Widget::Settings(SettingsGroup { children, .. }) => retain_widgets(children, keep),
1546        other => {
1547            for child in other.children_mut() {
1548                retain_within(child, keep);
1549            }
1550        }
1551    }
1552}
1553
1554/// Every widget of `widgets`, at any depth, each before its children.
1555pub fn walk_widgets(widgets: &[Widget]) -> Vec<&Widget> {
1556    let mut all = Vec::new();
1557    for widget in widgets {
1558        widget.walk(&mut |w| all.push(w));
1559    }
1560    all
1561}
1562
1563// ----------------------------------------------------------- panel blocks
1564//
1565// The blocks say what a part of a panel is; the host draws each with the
1566// controls its own panels use. They came in contract 0.1.4: a package
1567// using them names `min_contract = "0.1.4"` in its manifest.
1568
1569/// How a mark, a tag or a status reads: what it means, not its colour.
1570#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1571#[serde(rename_all = "snake_case")]
1572pub enum Tone {
1573    #[default]
1574    Neutral,
1575    Good,
1576    Warning,
1577    Bad,
1578    Info,
1579    /// The accent: what is in hand.
1580    Accent,
1581    /// Dim: what is out of play or says little.
1582    Muted,
1583}
1584
1585/// A small icon button: in a section's title, on its own
1586/// ([`Widget::Action`]: a cross at a row's end that takes it out), or an
1587/// entry of an item's menu (`label` then names it). A click comes back as
1588/// `PanelEvent::Button` (a section's or one on its own) or
1589/// `PanelEvent::ContextMenu` (a menu's) with `id`.
1590#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1591pub struct PanelAction {
1592    pub id: String,
1593    #[serde(default)]
1594    pub icon: Option<String>,
1595    /// The words on hover, or the menu entry.
1596    #[serde(default)]
1597    pub label: String,
1598    /// A menu entry's words on hover.
1599    #[serde(default)]
1600    pub hint: String,
1601    /// A menu entry with a line above it, setting it apart.
1602    #[serde(default)]
1603    pub separated: bool,
1604}
1605
1606/// A [`Widget::Toggles`]: icon buttons in a row under one label, each lit
1607/// while `on` and its words shown on hover, the way an editor shows its
1608/// alignment and wrapping. A click comes back as `PanelEvent::Button` with
1609/// the button's `id`; whether lighting one puts the others out is the
1610/// bench's to decide.
1611#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1612#[serde(default)]
1613pub struct Toggles {
1614    pub id: String,
1615    pub label: String,
1616    pub buttons: Vec<ToggleButton>,
1617}
1618
1619/// One button of [`Toggles`].
1620#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1621#[serde(default)]
1622pub struct ToggleButton {
1623    pub id: String,
1624    /// An icon of the package (`icons/<name>.svg`) or of the design set.
1625    pub icon: String,
1626    /// The words on hover: what the button does.
1627    pub hint: String,
1628    pub on: bool,
1629    /// Shown but not to be clicked.
1630    pub disabled: bool,
1631}
1632
1633/// A [`Widget::Section`]: a fold the user opens and closes, its title in
1634/// small capitals, the count of what it holds, a one-line summary while
1635/// closed, icon actions at its right end, and its children, whose fields
1636/// share one label column.
1637#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1638#[serde(default)]
1639pub struct PanelSection {
1640    /// Keeps the fold's state; the title when empty.
1641    pub id: String,
1642    pub title: String,
1643    pub count: Option<usize>,
1644    pub summary: Option<String>,
1645    /// Open the first time it is shown.
1646    pub open: bool,
1647    pub actions: Vec<PanelAction>,
1648    pub children: Vec<Widget>,
1649}
1650
1651impl Default for PanelSection {
1652    fn default() -> Self {
1653        Self {
1654            id: String::new(),
1655            title: String::new(),
1656            count: None,
1657            summary: None,
1658            open: true,
1659            actions: Vec::new(),
1660            children: Vec::new(),
1661        }
1662    }
1663}
1664
1665/// A small rounded name in an item's row: an element a constraint ties.
1666/// A click comes back as `PanelEvent::Tag`.
1667#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1668#[serde(default)]
1669pub struct Tag {
1670    pub text: String,
1671    /// `Neutral` draws it plain.
1672    pub tone: Tone,
1673    /// What it names is selected.
1674    pub selected: bool,
1675    /// What it names is in hand or tied to it: outlined.
1676    pub lit: bool,
1677}
1678
1679/// A glyph badge at an item's end: a constraint on an element. A click
1680/// comes back as `PanelEvent::Badge`.
1681#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1682#[serde(default)]
1683pub struct Badge {
1684    pub icon: String,
1685    pub tone: Tone,
1686    /// Words on hover.
1687    pub hint: String,
1688    /// What it stands for is in hand: drawn on a lit ground.
1689    pub lit: bool,
1690    /// Its colour as sRGB, in place of the tone's.
1691    pub color: Option<[u8; 3]>,
1692}
1693
1694/// One row of a list: what an [`ItemList`] holds, or alone as a
1695/// [`Widget::Item`].
1696#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1697#[serde(default)]
1698pub struct Item {
1699    /// Names the row in events when it stands alone; in a list the row's
1700    /// place names it.
1701    pub id: String,
1702    pub icon: Option<String>,
1703    /// The icon's tone; `Neutral` is the row's plain one.
1704    pub tone: Tone,
1705    /// Out of play: its name dim.
1706    pub muted: bool,
1707    /// A problem: its name in the danger colour.
1708    pub problem: bool,
1709    pub label: String,
1710    /// Dim words after the name.
1711    pub secondary: Option<String>,
1712    /// At the row's end.
1713    pub value: Option<String>,
1714    /// The value in the plain face rather than the mono one.
1715    pub value_plain: bool,
1716    pub tags: Vec<Tag>,
1717    pub badges: Vec<Badge>,
1718    pub selected: bool,
1719    /// What a [`FilterField`]'s kind selector matches.
1720    pub kind: Option<String>,
1721    /// Words on hover.
1722    pub hint: Option<String>,
1723    /// The entries of its right-click menu.
1724    pub menu: Vec<PanelAction>,
1725    /// Tied to what is in hand (hovered or selected elsewhere): a faint
1726    /// tint and a thin bar at its left edge.
1727    pub related: bool,
1728    /// What is in hand itself, hovered through something else (a tag,
1729    /// the view): lit as under the pointer.
1730    pub lit: bool,
1731    /// The icon's colour as sRGB, in place of the tone's: the colour the
1732    /// view draws it in.
1733    pub color: Option<[u8; 3]>,
1734    /// The value's tone; `Neutral` is the row's plain one.
1735    pub value_tone: Tone,
1736    /// Words on hover over the value.
1737    pub value_hint: Option<String>,
1738    /// A word after the value in its tone, its `detail` on hover.
1739    pub flag: Option<StatusLine>,
1740    /// Scrolled into view.
1741    pub reveal: bool,
1742    /// Its name as a text field, focused: told as `PanelEvent::ItemText`
1743    /// at each change and once more as it is left.
1744    pub editing: bool,
1745    /// A control at the row's end in place of the value (a
1746    /// [`Widget::Quantity`] the row's value is typed into); its events are
1747    /// its own.
1748    pub field: Option<Box<Widget>>,
1749}
1750
1751/// A [`Widget::Items`]: rows a click selects (`PanelEvent::Select`), or
1752/// with `multi` a click with Ctrl adds to (`PanelEvent::Selection`), a
1753/// double click opens (`PanelEvent::Activate`); the pointer over one is
1754/// told as `PanelEvent::Hover`, so the bench lights it in the view.
1755#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1756#[serde(default)]
1757pub struct ItemList {
1758    pub id: String,
1759    pub items: Vec<Item>,
1760    pub multi: bool,
1761    /// The [`FilterField`] that narrows it, by its id.
1762    pub filter: Option<String>,
1763    /// Shown when nothing is listed, or nothing passes the filter.
1764    pub empty: Option<String>,
1765}
1766
1767/// A [`Widget::Filter`]: a search field narrowing the item lists that
1768/// name it, by their label, secondary words and tags, and a kind selector
1769/// when `kinds` names any (the first, "All" say, passes every item; the
1770/// others pass items of that `kind`). The host filters as the user types;
1771/// with `by_bench` it leaves the lists whole and tells the bench
1772/// (`PanelEvent::Filter`) instead.
1773#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1774#[serde(default)]
1775pub struct FilterField {
1776    pub id: String,
1777    /// In the field while it is empty.
1778    pub hint: String,
1779    pub kinds: Vec<String>,
1780    /// The kind chosen when first shown.
1781    pub kind: usize,
1782    pub by_bench: bool,
1783}
1784
1785/// A [`Widget::Status`], and a task header's state ([`TaskHeader`]).
1786#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1787#[serde(default)]
1788pub struct StatusLine {
1789    pub text: String,
1790    pub tone: Tone,
1791    /// The longer reason, on hover.
1792    pub detail: String,
1793}
1794
1795/// A [`Widget::TaskHeader`]: in a task's panel, the header above it
1796/// shows `subtitle` under the title and `status` as a pill beside it,
1797/// as the app's own tasks do; anywhere else they draw in the panel.
1798#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1799#[serde(default)]
1800pub struct TaskHeader {
1801    /// What the task edits or where it sits.
1802    pub subtitle: String,
1803    pub status: Option<StatusLine>,
1804}
1805
1806/// A [`Widget::Stack`]: its children the panel's spacing apart, or
1807/// close together when `tight`, as a task's lines of text and fields
1808/// sit.
1809#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1810#[serde(default)]
1811pub struct Stack {
1812    pub children: Vec<Widget>,
1813    pub tight: bool,
1814    /// The room between its children in points, in place of the panel's.
1815    pub spacing: Option<f32>,
1816}
1817
1818/// A [`Widget::Flow`]: side by side, going on to the next line when the
1819/// panel is narrow unless `no_wrap`. A [`Widget::Fill`] among them takes
1820/// what the others leave.
1821#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1822#[serde(default)]
1823pub struct Flow {
1824    pub children: Vec<Widget>,
1825    pub no_wrap: bool,
1826    /// Written in its section's label column before the children, as a
1827    /// field's label is.
1828    pub label: String,
1829}
1830
1831/// A [`Widget::Fill`].
1832#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1833pub struct Fill {
1834    pub child: Box<Widget>,
1835}
1836
1837impl Default for Fill {
1838    fn default() -> Self {
1839        Self {
1840            child: Box::new(Widget::Separator),
1841        }
1842    }
1843}
1844
1845/// A [`Widget::Fields`]: its fields' labels in one column as wide as the
1846/// longest, within the theme's limits, apart from the section's; or
1847/// `label_width` wide.
1848#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1849#[serde(default)]
1850pub struct Fields {
1851    pub children: Vec<Widget>,
1852    /// The column's width in points, whatever the labels.
1853    pub label_width: Option<f32>,
1854}
1855
1856/// A [`Widget::Inline`].
1857#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1858pub struct Inline {
1859    pub child: Box<Widget>,
1860}
1861
1862impl Default for Inline {
1863    fn default() -> Self {
1864        Self {
1865            child: Box::new(Widget::Separator),
1866        }
1867    }
1868}
1869
1870/// A [`Widget::PickChip`]: a click arms it (`PanelEvent::Pick`), its
1871/// cross clears it (`PanelEvent::Clear`).
1872#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1873#[serde(default)]
1874pub struct PickChip {
1875    pub id: String,
1876    pub label: String,
1877    /// What has been picked, in words.
1878    pub value: Option<String>,
1879    pub armed: bool,
1880    /// In the chip while nothing is picked.
1881    pub placeholder: String,
1882}
1883
1884/// A [`Widget::Entry`]: told once typing ends (`PanelEvent::Text`).
1885#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1886#[serde(default)]
1887pub struct Entry {
1888    pub id: String,
1889    pub label: String,
1890    pub value: String,
1891    pub placeholder: String,
1892    /// Lines may break: Enter starts a new one.
1893    pub multiline: bool,
1894    /// Its width in points; the panel's field width when left out.
1895    pub width: Option<f32>,
1896    /// In the mono face.
1897    pub mono: bool,
1898    /// Told at each change rather than once typing ends.
1899    pub live: bool,
1900    /// Offers the document's names (variables, features and their
1901    /// properties) as a formula is typed, as the formula fields do.
1902    pub formulas: bool,
1903    /// In the panel's larger text size: the one text a task edits.
1904    pub large: bool,
1905}
1906
1907/// A [`Widget::Quantity`]: a number as a [`Widget::Number`] says it, with
1908/// how it drags and how wide it is. Bound to a parameter (`bind`), it
1909/// takes formulas as a bound `Number` does. Changes come back as
1910/// `PanelEvent::Number`; a stepper's buttons as the value one up or down.
1911#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1912#[serde(default)]
1913pub struct Quantity {
1914    pub id: String,
1915    pub label: String,
1916    pub value: f64,
1917    pub dim: Dim,
1918    pub bind: Option<Bind>,
1919    pub min: Option<f64>,
1920    pub max: Option<f64>,
1921    pub decimals: usize,
1922    pub error: Option<String>,
1923    /// How much the value moves per point dragged; left out, as a bound
1924    /// `Number` drags.
1925    pub speed: Option<f64>,
1926    /// Its width in points.
1927    pub width: Option<f32>,
1928    pub enabled: bool,
1929    /// Takes the keyboard focus this frame, as a field just made does.
1930    pub focus: bool,
1931    /// Written after the value in place of the `dim`'s unit: `N·m`.
1932    pub unit: Option<String>,
1933    /// The value between a down and an up button, in place of a field.
1934    pub stepper: Option<Stepper>,
1935    /// The system's bare number drag in place of the panel's field: its
1936    /// `unit` written after the value as given, its decimals as the value
1937    /// needs (none when `decimals` is 0).
1938    pub bare: bool,
1939    /// The least and largest values a drag (or the wheel, or a stepper's
1940    /// buttons) sets, inside `min` and `max`: a drag stops there, where a
1941    /// typed value may go past. For a size that builds only up to a
1942    /// limit, so that only typing can ask for one that fails.
1943    pub drag_min: Option<f64>,
1944    pub drag_max: Option<f64>,
1945    /// The field's text as the package has it, written in place of the
1946    /// value and not edited there: a value typed through the bench's own
1947    /// keys, a formula with what it comes to. `focus` then rings the
1948    /// field as the one those keys type into.
1949    pub shown: Option<String>,
1950    /// A lock after the field, shut while the value is held (typed, it
1951    /// no longer follows the cursor). A click on it comes back as
1952    /// `PanelEvent::Toggle` with the field's id.
1953    pub held: Option<bool>,
1954}
1955
1956impl Default for Quantity {
1957    fn default() -> Self {
1958        Self {
1959            id: String::new(),
1960            label: String::new(),
1961            value: 0.0,
1962            dim: Dim::default(),
1963            bind: None,
1964            min: None,
1965            max: None,
1966            decimals: 2,
1967            error: None,
1968            speed: None,
1969            width: None,
1970            enabled: true,
1971            focus: false,
1972            unit: None,
1973            stepper: None,
1974            bare: false,
1975            drag_min: None,
1976            drag_max: None,
1977            shown: None,
1978            held: None,
1979        }
1980    }
1981}
1982
1983/// A [`Quantity`] drawn as a stepper: `text` (the value when empty)
1984/// between a down and an up button, each with its state and its words on
1985/// hover.
1986#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1987#[serde(default)]
1988pub struct Stepper {
1989    pub text: String,
1990    pub down: bool,
1991    pub up: bool,
1992    pub down_hint: String,
1993    pub up_hint: String,
1994}
1995
1996/// A [`Widget::Check`]: `text` beside its box, in its section's label
1997/// column under `label` when that is not empty. Told as
1998/// `PanelEvent::Toggle`.
1999#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2000#[serde(default)]
2001pub struct Check {
2002    pub id: String,
2003    pub label: String,
2004    pub text: String,
2005    pub on: bool,
2006    pub enabled: bool,
2007    /// Words on hover.
2008    pub hint: String,
2009}
2010
2011impl Default for Check {
2012    fn default() -> Self {
2013        Self {
2014            id: String::new(),
2015            label: String::new(),
2016            text: String::new(),
2017            on: false,
2018            enabled: true,
2019            hint: String::new(),
2020        }
2021    }
2022}
2023
2024/// A [`Widget::Select`]: one of `options`, told as `PanelEvent::Choice`.
2025#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2026#[serde(default)]
2027pub struct Select {
2028    pub id: String,
2029    pub label: String,
2030    pub options: Vec<String>,
2031    pub selected: usize,
2032    /// Its width in points; the panel's field width when left out.
2033    pub width: Option<f32>,
2034    pub enabled: bool,
2035    /// Shown in the closed field in place of the option chosen: a count,
2036    /// or a prompt for a list that only adds (`selected` past the end
2037    /// then marks none).
2038    pub text: Option<String>,
2039    /// The options offered but not to be chosen now, by their place.
2040    pub disabled: Vec<usize>,
2041    /// Words on hover over each option, by its place; empty for none.
2042    pub hints: Vec<String>,
2043    /// The options with a line above them, setting them apart.
2044    pub separated: Vec<usize>,
2045    /// The options side by side in the row, the chosen one lit, in place
2046    /// of a dropdown.
2047    pub segmented: bool,
2048    /// A search field atop the open dropdown, narrowing a long list to
2049    /// the options that match what is typed.
2050    pub search: bool,
2051}
2052
2053impl Default for Select {
2054    fn default() -> Self {
2055        Self {
2056            id: String::new(),
2057            label: String::new(),
2058            options: Vec::new(),
2059            selected: 0,
2060            width: None,
2061            enabled: true,
2062            text: None,
2063            disabled: Vec::new(),
2064            hints: Vec::new(),
2065            separated: Vec::new(),
2066            segmented: false,
2067            search: false,
2068        }
2069    }
2070}
2071
2072/// A [`Widget::Grid`]: two columns, a field's label in the first and its
2073/// control in the second, the column as wide as the grid's longest label.
2074/// A widget with no label takes one cell, so two of them make a row.
2075/// Rows sit close, or a little apart when `roomy`.
2076#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2077#[serde(default)]
2078pub struct FieldGrid {
2079    /// Keeps it apart from another grid of the panel.
2080    pub id: String,
2081    pub children: Vec<Widget>,
2082    pub roomy: bool,
2083    /// The control column a little further from the labels.
2084    pub apart: bool,
2085}
2086
2087/// A [`Widget::Alert`]: a note as [`Widget::Note`] draws it; with an
2088/// `id`, a click on it comes back as `PanelEvent::Button`.
2089#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2090#[serde(default)]
2091pub struct Alert {
2092    pub id: Option<String>,
2093    pub kind: NoteKind,
2094    pub title: Option<String>,
2095    pub text: String,
2096}
2097
2098/// A [`Widget::Card`]: a raised card, its icon and title on the first
2099/// line, then its children.
2100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2101#[serde(default)]
2102pub struct Card {
2103    pub icon: Option<String>,
2104    pub title: String,
2105    /// The icon's size in points.
2106    pub icon_size: f32,
2107    pub children: Vec<Widget>,
2108    /// The room inside its edge in points, in place of the card's own.
2109    pub padding: Option<f32>,
2110}
2111
2112impl Default for Card {
2113    fn default() -> Self {
2114        Self {
2115            icon: None,
2116            title: String::new(),
2117            icon_size: 18.0,
2118            children: Vec::new(),
2119            padding: None,
2120        }
2121    }
2122}
2123
2124/// A [`Widget::Caption`]: words in the panel's text size, or the small
2125/// one, in a tone (`Neutral` is the panel's secondary text, `Muted`
2126/// dimmer still), or in the primary text colour.
2127#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2128#[serde(default)]
2129pub struct Caption {
2130    pub text: String,
2131    pub tone: Tone,
2132    pub small: bool,
2133    pub mono: bool,
2134    /// A small heading over what follows, in small capitals.
2135    pub overline: bool,
2136    /// In the semibold face and the panel's primary text colour, over
2137    /// the tone: the name of what the widgets after it edit.
2138    pub strong: bool,
2139    /// In the medium face: a heading over the rows under it.
2140    pub medium: bool,
2141    /// In the primary text colour, in place of the tone's: a value read.
2142    pub primary: bool,
2143}
2144
2145/// A [`Widget::Plot`]: lines along a strip `height` points tall, each
2146/// series scaled to its own largest value, all on one x range from zero.
2147#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2148#[serde(default)]
2149pub struct Plot {
2150    pub height: f32,
2151    pub series: Vec<PlotSeries>,
2152}
2153
2154/// A line of a [`Plot`]: its points as `[x, y]`, in its tone.
2155#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2156#[serde(default)]
2157pub struct PlotSeries {
2158    pub points: Vec<[f64; 2]>,
2159    pub tone: Tone,
2160}
2161
2162/// A [`Widget::Cells`]: `children` in rows of `columns` cells, left to
2163/// right, each column as wide as its widest cell; rows sit close and
2164/// columns a little apart. Column titles as strong captions, then a
2165/// caption per reading, make a table that reads as the panel's text.
2166#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2167#[serde(default)]
2168pub struct Cells {
2169    /// Keeps it apart from another of the panel.
2170    pub id: String,
2171    /// Cells a row; one when left at zero.
2172    pub columns: usize,
2173    pub children: Vec<Widget>,
2174}
2175
2176/// How much room a [`Widget::Gap`] leaves.
2177#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2178#[serde(rename_all = "snake_case")]
2179pub enum GapSize {
2180    #[default]
2181    Small,
2182    Medium,
2183    Large,
2184    /// The room before a part of a panel under its own heading, between
2185    /// `medium` and `large`.
2186    Section,
2187}
2188
2189/// A [`Widget::Gap`].
2190#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2191#[serde(default)]
2192pub struct Gap {
2193    pub size: GapSize,
2194}
2195
2196/// A colour of a [`Swatches`] block, as sRGB.
2197#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2198#[serde(default)]
2199pub struct Swatch {
2200    pub color: [u8; 3],
2201    /// It is the colour in use: ringed in the accent.
2202    pub chosen: bool,
2203}
2204
2205/// A [`Widget::Swatches`]: small squares of colour, side by side and
2206/// going on to the next line; a click is `PanelEvent::Choice` with the
2207/// swatch's place.
2208#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2209#[serde(default)]
2210pub struct Swatches {
2211    pub id: String,
2212    pub swatches: Vec<Swatch>,
2213    /// Keys to the colours the view paints rather than colours to pick:
2214    /// smaller, unringed, and no click; one beside each caption in a flow
2215    /// makes a legend.
2216    pub keys: bool,
2217}
2218
2219/// A [`Widget::Color`]: a button showing `color` that opens the system's
2220/// colour picker; each change is `PanelEvent::Color`.
2221#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2222#[serde(default)]
2223pub struct ColorField {
2224    pub id: String,
2225    pub label: String,
2226    /// Red, green and blue, each from 0 to 1 (sRGB).
2227    pub color: [f32; 3],
2228}
2229
2230/// A [`Widget::Range`]: a slider over `min` to `max`, its value written
2231/// beside it with `decimals` and `suffix` (` %`); told as
2232/// `PanelEvent::Number`.
2233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2234#[serde(default)]
2235pub struct Range {
2236    pub id: String,
2237    pub label: String,
2238    pub value: f64,
2239    pub min: f64,
2240    pub max: f64,
2241    /// The values it stops at, every `step` from `min`.
2242    pub step: Option<f64>,
2243    pub decimals: usize,
2244    pub suffix: String,
2245    pub enabled: bool,
2246}
2247
2248impl Default for Range {
2249    fn default() -> Self {
2250        Self {
2251            id: String::new(),
2252            label: String::new(),
2253            value: 0.0,
2254            min: 0.0,
2255            max: 1.0,
2256            step: None,
2257            decimals: 2,
2258            suffix: String::new(),
2259            enabled: true,
2260        }
2261    }
2262}
2263
2264/// A [`Widget::RowButton`]: `text` at the left of a frameless button the
2265/// panel's width, told as `PanelEvent::Button`. The `current` one (where
2266/// what the panel moves stands) is in the accent, strong, and takes no
2267/// click.
2268#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2269#[serde(default)]
2270pub struct RowButton {
2271    pub id: String,
2272    pub text: String,
2273    pub current: bool,
2274}
2275
2276/// A [`Widget::Selectable`]: words that light up while `selected`, told
2277/// as `PanelEvent::Button` when clicked; a few in a [`Widget::Flow`] pick
2278/// one of them.
2279#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2280#[serde(default)]
2281pub struct Selectable {
2282    pub id: String,
2283    pub text: String,
2284    pub selected: bool,
2285}
2286
2287/// A picture a panel shows, as rows of sRGB pixels with their alpha.
2288/// The host keeps it by `key`, so a picture shown again under the same
2289/// key is not sent to the screen again: a key names one picture.
2290#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2291#[serde(default)]
2292pub struct Picture {
2293    pub key: String,
2294    pub width: u32,
2295    pub height: u32,
2296    /// `width × height` pixels of four bytes each, red, green, blue and
2297    /// alpha, row by row from the top.
2298    pub rgba: Vec<u8>,
2299}
2300
2301/// A choice of a [`Gallery`]: its picture over its name.
2302#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2303#[serde(default)]
2304pub struct Tile {
2305    pub label: String,
2306    pub picture: Picture,
2307}
2308
2309/// A [`Widget::Gallery`]: small square pictures side by side, going on
2310/// to the next line, each over its name; the `selected` one ringed in
2311/// the accent. A click is `PanelEvent::Choice` with the tile's place.
2312#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2313#[serde(default)]
2314pub struct Gallery {
2315    pub id: String,
2316    pub tiles: Vec<Tile>,
2317    pub selected: Option<usize>,
2318}
2319
2320/// A [`Widget::Settings`]: under its overline `title` (none when empty),
2321/// a bordered group with one row per child, the child's label at the
2322/// left and its control at the right, a line between rows. A
2323/// [`Widget::Hinted`] child's hint shows under its label; a
2324/// [`Widget::Check`] with no label is a switch, its `text` the label.
2325/// The Preferences search narrows the rows by label and hint.
2326#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2327#[serde(default)]
2328pub struct SettingsGroup {
2329    pub title: String,
2330    pub children: Vec<Widget>,
2331}
2332
2333macro_rules! block_into_widget {
2334    ($($block:ident => $variant:ident),* $(,)?) => {
2335        $(impl From<$block> for Widget {
2336            fn from(block: $block) -> Self {
2337                Widget::$variant(block)
2338            }
2339        })*
2340    };
2341}
2342
2343block_into_widget! {
2344    PanelSection => Section,
2345    Item => Item,
2346    ItemList => Items,
2347    FilterField => Filter,
2348    StatusLine => Status,
2349    Stack => Stack,
2350    Flow => Flow,
2351    Fill => Fill,
2352    Fields => Fields,
2353    Inline => Inline,
2354    PickChip => PickChip,
2355    Entry => Entry,
2356    TaskHeader => TaskHeader,
2357    Quantity => Quantity,
2358    Check => Check,
2359    Select => Select,
2360    FieldGrid => Grid,
2361    Alert => Alert,
2362    Card => Card,
2363    Caption => Caption,
2364    Gap => Gap,
2365    Plot => Plot,
2366    Swatches => Swatches,
2367    ColorField => Color,
2368    Range => Range,
2369    Toggles => Toggles,
2370    RowButton => RowButton,
2371    Selectable => Selectable,
2372    Gallery => Gallery,
2373    SettingsGroup => Settings,
2374    Cells => Cells,
2375    PanelAction => Action,
2376}
2377
2378/// A cell of a [`Widget::Sheet`].
2379///
2380/// A package builds these, so a variant keeps its fields for as long as
2381/// the contract's minor version holds: a new option comes as a new
2382/// variant, or as a new struct that derives `Default`.
2383#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2384#[serde(tag = "type", rename_all = "snake_case")]
2385pub enum Cell {
2386    /// Text; `strong` for a row heading the rows under it.
2387    Text {
2388        text: String,
2389        #[serde(default)]
2390        mono: bool,
2391        #[serde(default)]
2392        strong: bool,
2393    },
2394    /// Text a click on selects its row (`PanelEvent::Select`).
2395    Link { text: String },
2396    /// Text the user edits, told once typing ends (`PanelEvent::CellText`).
2397    Edit { text: String },
2398    /// A box ticked or not (`PanelEvent::CellCheck`).
2399    Check {
2400        on: bool,
2401        #[serde(default)]
2402        hint: Option<String>,
2403    },
2404}
2405
2406/// A line of a [`Widget::Diagram`]: what it stands for, not its colour,
2407/// so the host draws it in the design's own.
2408#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2409#[serde(rename_all = "snake_case")]
2410pub enum DiagramStroke {
2411    /// The outline of the part.
2412    #[default]
2413    Outline,
2414    /// An edge behind the surface, dashed.
2415    Hidden,
2416    /// An axis or a centre line, long-dashed and faint.
2417    Axis,
2418    /// A faint line: a hatch, a reference.
2419    Thin,
2420    /// Drawn in the accent colour.
2421    Accent,
2422}
2423
2424/// A shape of a [`Widget::Diagram`], in its coordinates.
2425///
2426/// A package builds these, so a variant keeps its fields for as long as
2427/// the contract's minor version holds: a new option comes as a new
2428/// variant, or as a new struct that derives `Default`.
2429#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2430#[serde(tag = "type", rename_all = "snake_case")]
2431pub enum DiagramShape {
2432    /// A run of straight lines; `fill` shades it, and reads only a convex
2433    /// outline right.
2434    Path {
2435        points: Vec<[f32; 2]>,
2436        #[serde(default)]
2437        closed: bool,
2438        #[serde(default)]
2439        stroke: DiagramStroke,
2440        #[serde(default)]
2441        fill: bool,
2442    },
2443    Circle {
2444        center: [f32; 2],
2445        radius: f32,
2446        #[serde(default)]
2447        stroke: DiagramStroke,
2448        #[serde(default)]
2449        fill: bool,
2450    },
2451    /// Text at a point, centred on it.
2452    Text {
2453        at: [f32; 2],
2454        text: String,
2455        #[serde(default)]
2456        mono: bool,
2457    },
2458}
2459
2460/// A measure of a [`Widget::Diagram`]: the distance from `from` to `to`,
2461/// drawn as a dimension line `offset` away from them (to the left of the
2462/// way from `from` to `to`; negative for the right), its ends led out to
2463/// the points, with `text` on it.
2464#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2465pub struct Dimension {
2466    pub from: [f32; 2],
2467    pub to: [f32; 2],
2468    #[serde(default)]
2469    pub offset: f32,
2470    pub text: String,
2471    /// Drawn in the accent colour: the one being edited.
2472    #[serde(default)]
2473    pub emphasis: bool,
2474}
2475
2476/// A note of a [`Widget::Diagram`] pointing at a feature of it: a dot at
2477/// `anchor`, a leader to `at`, and `text` there.
2478#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2479pub struct Callout {
2480    pub anchor: [f32; 2],
2481    pub at: [f32; 2],
2482    pub text: String,
2483    #[serde(default)]
2484    pub emphasis: bool,
2485}
2486
2487fn two() -> usize {
2488    2
2489}
2490
2491fn yes() -> bool {
2492    true
2493}
2494
2495#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2496#[serde(rename_all = "snake_case")]
2497pub enum NoteKind {
2498    #[default]
2499    Info,
2500    Success,
2501    Warning,
2502    Error,
2503}
2504
2505#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
2506#[serde(rename_all = "snake_case")]
2507pub enum ButtonStyle {
2508    Primary,
2509    #[default]
2510    Secondary,
2511    Destructive,
2512    /// A small secondary button, for an action on the row it sits in.
2513    Small,
2514    /// The plain button of the system's controls, unframed in style.
2515    Plain,
2516    /// A plain button in the small text size.
2517    PlainSmall,
2518    /// Outlined in the accent colour: takes what is picked in the view.
2519    Outline,
2520}
2521
2522/// A number field's parameter: feature `feature`'s parameter `key`.
2523#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2524pub struct Bind {
2525    pub feature: String,
2526    pub key: String,
2527}
2528
2529#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2530pub struct ListItem {
2531    pub label: String,
2532    #[serde(default)]
2533    pub detail: Option<String>,
2534    #[serde(default)]
2535    pub icon: Option<String>,
2536}
2537
2538/// Which declared panel an event came from.
2539#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
2540#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2541#[serde(rename_all = "snake_case")]
2542pub enum PanelSlot {
2543    Task,
2544    Settings,
2545    /// The strip under the view (`Frame::transport`).
2546    Transport,
2547    /// The card over the view (`Frame::card`).
2548    Card,
2549}
2550
2551/// What the user did to a panel widget, by the widget's id.
2552#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
2553#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2554#[serde(tag = "type", rename_all = "snake_case")]
2555pub enum PanelEvent {
2556    Number {
2557        id: String,
2558        value: f64,
2559    },
2560    Choice {
2561        id: String,
2562        index: usize,
2563    },
2564    Toggle {
2565        id: String,
2566        on: bool,
2567    },
2568    Text {
2569        id: String,
2570        value: String,
2571    },
2572    Button {
2573        id: String,
2574    },
2575    Pick {
2576        id: String,
2577    },
2578    Select {
2579        id: String,
2580        index: usize,
2581    },
2582    /// A cell of a table's editable column, typed in: its text as left.
2583    Cell {
2584        id: String,
2585        row: usize,
2586        column: usize,
2587        value: String,
2588    },
2589    /// A sheet's editable cell, once typing ended.
2590    CellText {
2591        id: String,
2592        row: usize,
2593        column: usize,
2594        value: String,
2595    },
2596    /// A sheet's box ticked or cleared.
2597    CellCheck {
2598        id: String,
2599        row: usize,
2600        column: usize,
2601        on: bool,
2602    },
2603    /// A diagram pressed at `x`, `y` in its own coordinates; `dragging`
2604    /// for each move of the pointer held down after the press, and
2605    /// `released` once, where the drag ended.
2606    DiagramPress {
2607        id: String,
2608        x: f32,
2609        y: f32,
2610        #[serde(default)]
2611        dragging: bool,
2612        #[serde(default)]
2613        released: bool,
2614    },
2615    /// The pointer came onto an item (`index` in its list, 0 for an
2616    /// item alone), or left the list (`None`).
2617    Hover {
2618        id: String,
2619        index: Option<usize>,
2620    },
2621    /// An item double clicked.
2622    Activate {
2623        id: String,
2624        index: usize,
2625    },
2626    /// An entry of an item's menu chosen: the entry's id in `action`.
2627    ContextMenu {
2628        id: String,
2629        index: usize,
2630        action: String,
2631    },
2632    /// A tag of an item clicked: `tag` is its place among the item's.
2633    Tag {
2634        id: String,
2635        index: usize,
2636        tag: usize,
2637    },
2638    /// A multiple list's selection, whole, as the user left it.
2639    Selection {
2640        id: String,
2641        indices: Vec<usize>,
2642    },
2643    /// A filter the bench applies, typed in or its kind chosen.
2644    Filter {
2645        id: String,
2646        text: String,
2647        kind: usize,
2648    },
2649    /// A picked chip cleared.
2650    Clear {
2651        id: String,
2652    },
2653    /// A badge of an item clicked: `badge` is its place among the item's.
2654    Badge {
2655        id: String,
2656        index: usize,
2657        badge: usize,
2658    },
2659    /// What the pointer is on in a list changed: the item (`None` off
2660    /// the list), and the tag or badge of it under the pointer.
2661    HoverPart {
2662        id: String,
2663        index: Option<usize>,
2664        tag: Option<usize>,
2665        badge: Option<usize>,
2666    },
2667    /// An item's name typed in while it is `editing`: at each change,
2668    /// and with `done` as the field is left.
2669    ItemText {
2670        id: String,
2671        index: usize,
2672        value: String,
2673        done: bool,
2674    },
2675    /// A colour field's colour changed: red, green and blue from 0 to 1.
2676    Color {
2677        id: String,
2678        color: [f32; 3],
2679    },
2680    /// A `live` [`Entry`]'s field left, its text as it stands: by Escape
2681    /// when `escaped`, which drops what was typed.
2682    TextLeft {
2683        id: String,
2684        value: String,
2685        escaped: bool,
2686    },
2687    /// The floating card `id` closed: by OK (or Enter, or a click
2688    /// elsewhere in the view) when `accept`, else by Cancel or Escape.
2689    CardClose {
2690        id: String,
2691        accept: bool,
2692    },
2693}
2694
2695impl PanelEvent {
2696    pub fn id(&self) -> &str {
2697        match self {
2698            PanelEvent::Number { id, .. }
2699            | PanelEvent::Choice { id, .. }
2700            | PanelEvent::Toggle { id, .. }
2701            | PanelEvent::Text { id, .. }
2702            | PanelEvent::Button { id }
2703            | PanelEvent::Pick { id }
2704            | PanelEvent::Select { id, .. }
2705            | PanelEvent::Cell { id, .. }
2706            | PanelEvent::CellText { id, .. }
2707            | PanelEvent::CellCheck { id, .. }
2708            | PanelEvent::DiagramPress { id, .. }
2709            | PanelEvent::Hover { id, .. }
2710            | PanelEvent::Activate { id, .. }
2711            | PanelEvent::ContextMenu { id, .. }
2712            | PanelEvent::Tag { id, .. }
2713            | PanelEvent::Selection { id, .. }
2714            | PanelEvent::Filter { id, .. }
2715            | PanelEvent::Clear { id }
2716            | PanelEvent::Badge { id, .. }
2717            | PanelEvent::HoverPart { id, .. }
2718            | PanelEvent::ItemText { id, .. }
2719            | PanelEvent::Color { id, .. }
2720            | PanelEvent::TextLeft { id, .. }
2721            | PanelEvent::CardClose { id, .. } => id,
2722        }
2723    }
2724}
2725
2726// ------------------------------------------------------------------- menus
2727
2728#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
2729#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2730#[serde(tag = "type", content = "id", rename_all = "snake_case")]
2731pub enum MenuScope {
2732    ViewportBody(String),
2733    TreeFeature(String),
2734    TreeBody(String),
2735    StartPage,
2736    EditMenu,
2737    /// A menu the package opened itself with [`Request::OpenMenu`] (from
2738    /// 0.1.8), by the tag it gave it.
2739    Popup(String),
2740}
2741
2742#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2743pub struct MenuItem {
2744    pub id: String,
2745    pub label: String,
2746    #[serde(default)]
2747    pub icon: Option<String>,
2748    #[serde(default)]
2749    pub hint: Option<String>,
2750    #[serde(default = "yes")]
2751    pub enabled: bool,
2752    #[serde(default)]
2753    pub separator_before: bool,
2754    /// Drawn ticked, the choice that stands among the entries (from
2755    /// 0.1.8).
2756    #[serde(default)]
2757    pub checked: bool,
2758}
2759
2760impl Default for MenuItem {
2761    fn default() -> Self {
2762        Self {
2763            id: String::new(),
2764            label: String::new(),
2765            icon: None,
2766            hint: None,
2767            enabled: yes(),
2768            separator_before: false,
2769            checked: false,
2770        }
2771    }
2772}
2773
2774// --------------------------------------------------------------- requests
2775
2776/// Something a bench asks the host to do once its call returns.
2777///
2778/// A package builds these, so a variant keeps its fields for as long as
2779/// the contract's minor version holds: a new option comes as a new
2780/// variant, or as a new struct that derives `Default`.
2781#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2782#[serde(tag = "type", rename_all = "snake_case")]
2783pub enum Request {
2784    ActivateTool {
2785        tool: String,
2786    },
2787    SelectBody {
2788        body: String,
2789    },
2790    /// Name the undo step this gesture closes.
2791    JournalLabel {
2792        label: String,
2793    },
2794    SwitchWorkbench {
2795        workbench: String,
2796    },
2797    OrientCamera {
2798        origin: [f32; 3],
2799        normal: [f32; 3],
2800        up: [f32; 3],
2801    },
2802    FinishEditing,
2803    /// Ask the user where to save `contents` (the `save_dialog`
2804    /// capability).
2805    SaveFile {
2806        name: String,
2807        kind: String,
2808        extension: String,
2809        contents: Vec<u8>,
2810    },
2811    /// Ask the user for a folder and write every file into it (the
2812    /// `save_dialog` capability): one program per operation.
2813    SaveFiles {
2814        files: Vec<FileToWrite>,
2815    },
2816    /// Ask the user for a file to read, or several with `multiple` (the
2817    /// `open_dialog` capability), of the `kinds` offered; the answer comes
2818    /// as `Event::FileOpened` with this `id`.
2819    OpenFile {
2820        id: String,
2821        kinds: Vec<FileKind>,
2822        #[serde(default)]
2823        multiple: bool,
2824    },
2825    /// Put `text` on the system clipboard (contract 0.1.4): a table the
2826    /// bench made, to paste into a spreadsheet.
2827    CopyText {
2828        text: String,
2829    },
2830    /// Open a menu of `items` at the pointer (from 0.1.8), for something
2831    /// the package draws itself: a right click on a handle of its own. The
2832    /// pick comes back as `menu_command` with [`MenuScope::Popup`] and
2833    /// `tag`; Escape or a click elsewhere puts the menu away and says
2834    /// nothing.
2835    OpenMenu {
2836        tag: String,
2837        items: Vec<MenuItem>,
2838    },
2839}
2840
2841// ------------------------------------------------------------------ calls
2842
2843/// The document commands a bench calls through `host.call`. Each is an
2844/// ordinary recorded edit: one undo step per gesture, sent to peers.
2845pub mod panel;
2846
2847pub mod calls {
2848    /// `{kind, name, body?, data, deps?}` → the new feature's id. `kind`
2849    /// must be one the package owns.
2850    pub const ADD_FEATURE: &str = "doc.add_feature";
2851    /// `{id, data}`: replace an owned feature's data.
2852    pub const SET_FEATURE_DATA: &str = "doc.set_feature_data";
2853    /// `{id}`: remove an owned feature.
2854    pub const REMOVE_FEATURE: &str = "doc.remove_feature";
2855    /// `{id, after?}`: move an owned feature in its body's history to just
2856    /// after `after`, a feature of the same body, or first without it. A
2857    /// feature passes no feature it uses, nor one using it.
2858    pub const MOVE_FEATURE: &str = "doc.move_feature";
2859    /// `{id, name}`
2860    pub const RENAME_FEATURE: &str = "doc.rename_feature";
2861    /// `{id, visible}`
2862    pub const SET_FEATURE_VISIBLE: &str = "doc.set_feature_visible";
2863    /// `{name?}` → the new body's id.
2864    pub const CREATE_BODY: &str = "doc.create_body";
2865    /// `{id}`: remove a body with the package's own features on it, never
2866    /// one holding another package's feature or taking its shape from an
2867    /// import, a link or a copy. An empty body's removal undoes, so the
2868    /// body a cancelled part made can go without clearing the history.
2869    pub const REMOVE_BODY: &str = "doc.remove_body";
2870    /// `{body, matrix}`: a row-major rigid 4x4.
2871    pub const SET_PLACEMENT: &str = "doc.set_placement";
2872    /// `{entry, input}` → the job's number. The result arrives as
2873    /// `Event::JobFinished`.
2874    pub const JOB_START: &str = "job.start";
2875    /// `{job}`
2876    pub const JOB_CANCEL: &str = "job.cancel";
2877    /// `{body}` → the round holes in the body's solid, where it sits:
2878    /// `[{entry, direction, diameter, depth, through, drill_point_deg}]`.
2879    /// Read only; answered where the call may change the document (an
2880    /// event, a panel change, a command), refused elsewhere.
2881    pub const GEOM_HOLES: &str = "geom.holes";
2882    /// `{body, point}` → the edges round the face of the body's solid at
2883    /// `point` (world), each `{point, direction}` halfway along it, where
2884    /// the body sits. Read only, answered as `geom.holes` is.
2885    pub const GEOM_FACE_EDGES: &str = "geom.face_edges";
2886    /// `{body, plane: {origin, normal, x_axis?}, face?}` →
2887    /// [`Section`](crate::Section): where the plane (world) crosses the body's
2888    /// solid, or with `face` (a point, world) only the face there. Read
2889    /// only, answered as `geom.holes` is.
2890    pub const GEOM_SECTION: &str = "geom.section";
2891    /// `{body, point?, name?}` → [`FaceLoops`](crate::FaceLoops): the
2892    /// boundary loops of the face named `name` (the one of several
2893    /// nearest `point`), or of the face at `point` (world). Read only,
2894    /// answered as `geom.holes` is.
2895    pub const GEOM_FACE_LOOPS: &str = "geom.face_loops";
2896}
2897
2898/// What `geom.section` answers.
2899#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2900pub struct Section {
2901    /// The plane as cut, world space: the curves' 2D coordinates run
2902    /// along its `x_axis` and `y_axis`.
2903    pub plane: kernel_api::ProfilePlane,
2904    pub loops: Vec<SectionLoop>,
2905}
2906
2907/// Curves of a section end to end: closed round a solid's cut, open where
2908/// a sheet's edge stops it.
2909#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2910pub struct SectionLoop {
2911    pub closed: bool,
2912    pub curves: Vec<SectionCurve>,
2913}
2914
2915#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2916pub struct SectionCurve {
2917    /// The exact curve, in the plane's 2D coordinates.
2918    pub curve: kernel_api::ProjectedEdge,
2919    /// The loop runs against the way `curve` does.
2920    #[serde(default)]
2921    pub reversed: bool,
2922    /// Points along it in the loop's order, world space.
2923    pub points: Vec<[f64; 3]>,
2924    /// The name of the face it crosses, when the solid names its faces.
2925    #[serde(default)]
2926    pub face: Option<u64>,
2927}
2928
2929/// What `geom.face_loops` answers.
2930#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2931pub struct FaceLoops {
2932    /// The face's name, when the solid names its faces.
2933    #[serde(default)]
2934    pub name: Option<u64>,
2935    /// The outer loop first, then the holes, each edge in turn.
2936    pub loops: Vec<Vec<LoopEdge>>,
2937}
2938
2939#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2940pub struct LoopEdge {
2941    /// Points along it in the loop's order, world space.
2942    pub points: Vec<[f64; 3]>,
2943    pub length: f64,
2944    #[serde(default)]
2945    pub circle: Option<EdgeCircle>,
2946    /// The edge a round face meets itself along, in its loop twice.
2947    #[serde(default)]
2948    pub seam: bool,
2949    /// The names of the two faces it runs between (as
2950    /// [`EdgeRef::faces`]).
2951    #[serde(default)]
2952    pub faces: Option<[u64; 2]>,
2953}
2954
2955#[cfg(test)]
2956mod tests {
2957    use super::*;
2958
2959    #[test]
2960    fn a_host_loads_packages_of_its_own_contract_version() {
2961        assert!(api_compatible("printcad:workbench@0.1"));
2962        assert!(api_compatible("0.1.4"));
2963        assert!(!api_compatible("printcad:workbench@0.2"));
2964        assert!(!api_compatible("1.0"));
2965        // A manifest's `min_contract`, held against this build's patch.
2966        assert!(contract_satisfies(CONTRACT_VERSION));
2967        assert!(contract_satisfies("0.1"));
2968        assert!(contract_satisfies("printcad:workbench@0.1.0"));
2969        assert!(!contract_satisfies("0.1.999"));
2970        assert!(!contract_satisfies("0.2.0"));
2971        assert!(!contract_satisfies("next"));
2972    }
2973
2974    #[test]
2975    fn a_block_reads_with_its_fields_left_out_and_writes_back_the_same() {
2976        let section: Widget =
2977            serde_json::from_str(r#"{"type":"section","title":"Elements","count":9}"#).unwrap();
2978        let Widget::Section(PanelSection {
2979            open,
2980            count,
2981            children,
2982            ..
2983        }) = &section
2984        else {
2985            panic!("{section:?}");
2986        };
2987        assert!(*open && *count == Some(9) && children.is_empty());
2988        let item: Widget = Item {
2989            label: "Line 1".into(),
2990            value: Some("89.92 mm".into()),
2991            ..Default::default()
2992        }
2993        .into();
2994        for widget in [section, item] {
2995            let json = serde_json::to_string(&widget).unwrap();
2996            assert_eq!(serde_json::from_str::<Widget>(&json).unwrap(), widget);
2997        }
2998    }
2999
3000    /// `major.minor` of a version such as `0.1.4`.
3001    fn contract(version: &str) -> String {
3002        version.split('.').take(2).collect::<Vec<_>>().join(".")
3003    }
3004
3005    #[test]
3006    fn the_crate_the_wit_package_and_the_contract_share_a_version() {
3007        let declared = WIT
3008            .lines()
3009            .find_map(|line| line.trim().strip_prefix("package printcad:workbench@"))
3010            .and_then(|rest| rest.strip_suffix(';'))
3011            .expect("the WIT file names its package");
3012        assert_eq!(contract(declared), API_VERSION);
3013        assert_eq!(contract(env!("CARGO_PKG_VERSION")), API_VERSION);
3014    }
3015
3016    #[test]
3017    fn tagged_values_read_as_a_guest_writes_them() {
3018        let widget: Widget = serde_json::from_str(
3019            r#"{"type":"number","id":"teeth","label":"Teeth","value":20,"bind":{"feature":"f","key":"/teeth"}}"#,
3020        )
3021        .unwrap();
3022        match widget {
3023            Widget::Number {
3024                decimals,
3025                dim,
3026                bind,
3027                ..
3028            } => {
3029                assert_eq!(decimals, 2);
3030                assert_eq!(dim, Dim::Length);
3031                assert_eq!(bind.unwrap().key, "/teeth");
3032            }
3033            other => panic!("{other:?}"),
3034        }
3035        let plan: Plan = serde_json::from_str(r#"{"type":"error","message":"no"}"#).unwrap();
3036        assert_eq!(
3037            plan,
3038            Plan::Error {
3039                feature: None,
3040                message: "no".into()
3041            }
3042        );
3043        let scope = serde_json::to_string(&MenuScope::TreeBody("b".into())).unwrap();
3044        assert_eq!(scope, r#"{"type":"tree_body","id":"b"}"#);
3045        assert_eq!(
3046            serde_json::from_str::<MenuScope>(&scope).unwrap(),
3047            MenuScope::TreeBody("b".into())
3048        );
3049        let event = serde_json::to_string(&Event::JobFinished {
3050            job: 3,
3051            result: Ok("x".into()),
3052        })
3053        .unwrap();
3054        assert_eq!(
3055            event,
3056            r#"{"type":"job_finished","job":3,"result":{"Ok":"x"}}"#
3057        );
3058    }
3059
3060    #[test]
3061    fn layout_widgets_read_as_a_guest_writes_them() {
3062        let widget: Widget = serde_json::from_str(
3063            r#"{"type":"row","children":[
3064                {"type":"value","label":"Moves","value":"Part"},
3065                {"type":"hinted","hint":"Why","widget":
3066                    {"type":"button","id":"x","label":"X","style":"small"}}
3067            ]}"#,
3068        )
3069        .unwrap();
3070        assert_eq!(
3071            widget,
3072            Widget::Row {
3073                children: vec![
3074                    Widget::Value {
3075                        label: "Moves".into(),
3076                        value: "Part".into(),
3077                        mono: false,
3078                    },
3079                    Widget::Hinted {
3080                        hint: "Why".into(),
3081                        widget: Box::new(Widget::Button {
3082                            id: "x".into(),
3083                            label: "X".into(),
3084                            style: ButtonStyle::Small,
3085                            enabled: true,
3086                        }),
3087                    },
3088                ],
3089            }
3090        );
3091    }
3092
3093    #[test]
3094    fn a_sheet_and_its_cell_events_read_as_written() {
3095        let widget: Widget = serde_json::from_str(
3096            r#"{"type":"sheet","id":"parts","columns":["Part","Bought"],"rows":[[
3097                {"type":"link","text":"Bolt"},{"type":"check","on":true}
3098            ]]}"#,
3099        )
3100        .unwrap();
3101        let Widget::Sheet { rows, .. } = widget else {
3102            panic!("{widget:?}");
3103        };
3104        assert_eq!(
3105            rows[0][1],
3106            Cell::Check {
3107                on: true,
3108                hint: None
3109            }
3110        );
3111        let event = PanelEvent::CellText {
3112            id: "parts".into(),
3113            row: 2,
3114            column: 5,
3115            value: "ACME".into(),
3116        };
3117        let json = serde_json::to_string(&event).unwrap();
3118        assert_eq!(
3119            json,
3120            r#"{"type":"cell_text","id":"parts","row":2,"column":5,"value":"ACME"}"#
3121        );
3122        assert_eq!(event.id(), "parts");
3123    }
3124
3125    #[test]
3126    fn a_struct_left_to_its_defaults_reads_as_its_fields_left_out() {
3127        fn read<T: serde::de::DeserializeOwned>(json: &str) -> T {
3128            serde_json::from_str(json).unwrap()
3129        }
3130        assert_eq!(read::<Tool>(r#"{"id":"","label":""}"#), Tool::default());
3131        assert_eq!(
3132            read::<Parameter>(r#"{"key":"","label":"","pointer":""}"#),
3133            Parameter::default()
3134        );
3135        assert_eq!(
3136            read::<MenuItem>(r#"{"id":"","label":""}"#),
3137            MenuItem::default()
3138        );
3139        assert_eq!(
3140            read::<Label>(r#"{"at":[0,0,0],"text":"","color":[1,1,1]}"#),
3141            Label::default()
3142        );
3143        assert_eq!(
3144            read::<Mesh>(r#"{"positions":[],"indices":[],"color":[1,1,1]}"#),
3145            Mesh::default()
3146        );
3147        assert_eq!(
3148            read::<Polyline>(r#"{"points":[],"color":[1,1,1]}"#),
3149            Polyline::default()
3150        );
3151        assert_eq!(
3152            read::<Region>(r#"{"outline":[],"color":[1,1,1]}"#),
3153            Region::default()
3154        );
3155        assert_eq!(
3156            read::<KeptMesh>(r#"{"handle":0,"color":[1,1,1]}"#),
3157            KeptMesh::default()
3158        );
3159        assert_eq!(
3160            read::<Manifest>(r#"{"id":"","name":"","version":"","api":"printcad:workbench@0.1"}"#),
3161            Manifest::default()
3162        );
3163    }
3164
3165    /// The SDK passes over what it reads this way: a kind of event a newer
3166    /// app sends within the same contract.
3167    #[test]
3168    fn an_event_of_a_kind_not_known_yet_reads_as_an_unknown_variant() {
3169        let input = r#"{"event":{"type":"gesture","scale":2},"pointer":{}}"#;
3170        let error = serde_json::from_str::<Input>(input).unwrap_err();
3171        assert!(error.to_string().starts_with("unknown variant"), "{error}");
3172        let error = serde_json::from_str::<PanelEvent>(r#"{"type":"drag","id":"x"}"#).unwrap_err();
3173        assert!(error.to_string().starts_with("unknown variant"), "{error}");
3174    }
3175
3176    #[test]
3177    fn a_frame_left_empty_reads_from_nothing() {
3178        let frame: Frame = serde_json::from_str("{}").unwrap();
3179        assert_eq!(frame, Frame::default());
3180    }
3181}