uzor-framework 1.5.39

uzor app engine: one kernel of single-writer engines driven by a typed input bus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Layout blob codec (design ยง3.2.5): a postcard envelope with a `u16`
//! version, the dock structure and the floating windows.
//!
//! The structure is the library `LayoutSnapshot` (structure only; panel
//! values come back through the app's decoder), mirrored field by field in
//! [`WireDock`]: postcard is not self-describing, so the snapshot's
//! `skip_serializing_if` / `default` attributes (meant for its JSON form)
//! cannot be honoured on the wire, and the version prefix replaces them.
//! The same [`WireDock`] is the engine's "did the blob go stale" key: the
//! dock revision bumps exactly when it changes.

#[cfg(feature = "layout-blob")]
use std::collections::{HashMap, HashSet};

#[cfg(feature = "layout-blob")]
use serde::{Deserialize, Serialize};
use uzor::layout::docking::{DockPanel, LayoutSnapshot, SerializedNode, SerializedNodeType};
#[cfg(feature = "layout-blob")]
use uzor::layout::docking::{DockingTree, FloatingWindow, FloatingWindowId, LeafId, SerializedGrid};

#[cfg(feature = "layout-blob")]
use crate::types::layout_blob::{LayoutBlob, LayoutCodecError, WindowGeometrySnapshot};
#[cfg(feature = "layout-blob")]
use crate::types::spec::PanelHome;

use super::DockState;
#[cfg(feature = "layout-blob")]
use super::{dock, Ctx, PanelDecoder, WindowLayout};

/// Envelope version this build writes and reads.
#[cfg(feature = "layout-blob")]
pub const BLOB_VERSION: u16 = 1;

#[cfg(feature = "layout-blob")]
/// Largest node count a blob may hold.
const MAX_NODES: usize = 4096;
#[cfg(feature = "layout-blob")]
/// Deepest branch nesting a blob may hold.
const MAX_DEPTH: usize = 64;
#[cfg(feature = "layout-blob")]
/// Most floating windows a blob may hold.
const MAX_FLOATING: usize = 256;

/// The blob-relevant state of one dock.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "layout-blob", derive(Serialize, Deserialize))]
pub(super) struct WireDock {
    root_id: u64,
    active_leaf: Option<u64>,
    nodes: Vec<WireNode>,
    floating: Vec<WireFloating>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "layout-blob", derive(Serialize, Deserialize))]
struct WireNode {
    id: u64,
    kind: WireKind,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "layout-blob", derive(Serialize, Deserialize))]
enum WireKind {
    Leaf {
        panel_type_ids: Vec<String>,
        active_tab: u64,
        hidden: bool,
        color_tag: Option<u8>,
    },
    Branch {
        children: Vec<u64>,
        layout: String,
        proportions: Vec<f64>,
        cross_ratio: Option<(f64, f64)>,
        magnetic: bool,
        grid: Option<WireGrid>,
    },
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "layout-blob", derive(Serialize, Deserialize))]
struct WireGrid {
    rows: u64,
    cols: u64,
    row_ratios: Vec<f64>,
    col_ratios: Vec<f64>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "layout-blob", derive(Serialize, Deserialize))]
struct WireFloating {
    id: u64,
    panel_type_ids: Vec<String>,
    active_tab: u64,
    rect: (f32, f32, f32, f32),
}

/// Everything after the version prefix.
#[cfg(feature = "layout-blob")]
#[derive(Serialize, Deserialize)]
struct Envelope {
    dock: WireDock,
    geometry: Option<WindowGeometrySnapshot>,
}

impl WireDock {
    /// The blob-relevant state of `dock`.
    pub(super) fn capture<P: DockPanel>(dock: &DockState<P>) -> Self {
        let snap = LayoutSnapshot::from_tree(dock.tree(), "");
        Self {
            root_id: snap.root_id,
            active_leaf: snap.active_leaf_id,
            nodes: snap.nodes.into_iter().map(WireNode::from).collect(),
            floating: dock
                .floating_windows()
                .iter()
                .map(|f| WireFloating {
                    id: f.id.0,
                    panel_type_ids: f.panels.iter().map(|p| p.type_id().to_string()).collect(),
                    active_tab: f.active_tab as u64,
                    rect: (f.x, f.y, f.width, f.height),
                })
                .collect(),
        }
    }

    /// Test helper: the same structure with the root listing itself as a
    /// child (a cycle the validator must refuse).
    #[cfg(test)]
    pub(super) fn with_root_cycle(&self) -> Self {
        let mut out = self.clone();
        let root = out.root_id;
        for n in &mut out.nodes {
            if let (true, WireKind::Branch { children, .. }) = (n.id == root, &mut n.kind) {
                children.push(root);
            }
        }
        out
    }

    #[cfg(feature = "layout-blob")]
    fn to_snapshot(&self) -> LayoutSnapshot {
        LayoutSnapshot {
            version: "1.0".to_string(),
            name: String::new(),
            nodes: self.nodes.iter().map(SerializedNode::from).collect(),
            root_id: self.root_id,
            active_leaf_id: self.active_leaf,
        }
    }
}

impl From<SerializedNode> for WireNode {
    fn from(n: SerializedNode) -> Self {
        let kind = match n.node_type {
            SerializedNodeType::Leaf {
                panel_type_ids,
                active_tab,
                hidden,
                color_tag,
            } => WireKind::Leaf {
                panel_type_ids,
                active_tab: active_tab as u64,
                hidden,
                color_tag,
            },
            SerializedNodeType::Branch {
                children,
                layout,
                proportions,
                cross_ratio,
                magnetic,
                grid,
            } => WireKind::Branch {
                children,
                layout,
                proportions,
                cross_ratio,
                magnetic,
                grid: grid.map(|g| WireGrid {
                    rows: g.rows as u64,
                    cols: g.cols as u64,
                    row_ratios: g.row_ratios,
                    col_ratios: g.col_ratios,
                }),
            },
        };
        Self { id: n.id, kind }
    }
}

#[cfg(feature = "layout-blob")]
impl From<&WireNode> for SerializedNode {
    fn from(n: &WireNode) -> Self {
        let node_type = match &n.kind {
            WireKind::Leaf {
                panel_type_ids,
                active_tab,
                hidden,
                color_tag,
            } => SerializedNodeType::Leaf {
                panel_type_ids: panel_type_ids.clone(),
                active_tab: to_usize(*active_tab),
                hidden: *hidden,
                color_tag: *color_tag,
            },
            WireKind::Branch {
                children,
                layout,
                proportions,
                cross_ratio,
                magnetic,
                grid,
            } => SerializedNodeType::Branch {
                children: children.clone(),
                layout: layout.clone(),
                proportions: proportions.clone(),
                cross_ratio: *cross_ratio,
                magnetic: *magnetic,
                grid: grid.as_ref().map(|g| SerializedGrid {
                    rows: to_usize(g.rows),
                    cols: to_usize(g.cols),
                    row_ratios: g.row_ratios.clone(),
                    col_ratios: g.col_ratios.clone(),
                }),
            },
        };
        Self {
            id: n.id,
            node_type,
        }
    }
}

#[cfg(feature = "layout-blob")]
fn to_usize(v: u64) -> usize {
    usize::try_from(v).unwrap_or(usize::MAX)
}

#[cfg(feature = "layout-blob")]
fn malformed(why: impl Into<String>) -> LayoutCodecError {
    LayoutCodecError::Malformed(why.into())
}

#[cfg(feature = "layout-blob")]
/// Encode one dock (and optional window geometry) into a blob.
pub(super) fn encode(
    dock: &WireDock,
    geometry: Option<WindowGeometrySnapshot>,
) -> Result<LayoutBlob, LayoutCodecError> {
    let env = Envelope {
        dock: dock.clone(),
        geometry,
    };
    postcard::to_allocvec(&(BLOB_VERSION, &env))
        .map(LayoutBlob::from_bytes)
        .map_err(|e| LayoutCodecError::Encode(e.to_string()))
}

#[cfg(feature = "layout-blob")]
/// Decode a blob's envelope: version first, then the body; trailing bytes
/// are malformed.
fn decode(blob: &LayoutBlob) -> Result<Envelope, LayoutCodecError> {
    let (found, rest) = postcard::take_from_bytes::<u16>(blob.as_bytes())
        .map_err(|e| malformed(format!("version: {e}")))?;
    if found != BLOB_VERSION {
        return Err(LayoutCodecError::Version {
            found,
            supported: BLOB_VERSION,
        });
    }
    let (env, tail) =
        postcard::take_from_bytes::<Envelope>(rest).map_err(|e| malformed(e.to_string()))?;
    if !tail.is_empty() {
        return Err(malformed(format!("{} trailing bytes", tail.len())));
    }
    Ok(env)
}

#[cfg(feature = "layout-blob")]
/// The structure must be a tree the library can rebuild without
/// recursing forever: unique ids, a branch root, every child present and
/// referenced once, bounded size and depth.
fn validate(w: &WireDock) -> Result<(), LayoutCodecError> {
    if w.nodes.len() > MAX_NODES {
        return Err(malformed(format!(
            "{} nodes (max {MAX_NODES})",
            w.nodes.len()
        )));
    }
    if w.floating.len() > MAX_FLOATING {
        return Err(malformed(format!(
            "{} floating windows (max {MAX_FLOATING})",
            w.floating.len()
        )));
    }
    let mut by_id: HashMap<u64, &WireNode> = HashMap::new();
    for n in &w.nodes {
        if n.id == u64::MAX {
            return Err(malformed("node id out of range"));
        }
        if by_id.insert(n.id, n).is_some() {
            return Err(malformed(format!("duplicate node id {}", n.id)));
        }
    }
    let Some(root) = by_id.get(&w.root_id) else {
        return Err(malformed(format!("root node {} missing", w.root_id)));
    };
    if !matches!(root.kind, WireKind::Branch { .. }) {
        return Err(malformed("root is not a branch"));
    }
    let mut seen: HashSet<u64> = HashSet::from([w.root_id]);
    let mut stack: Vec<(u64, usize)> = vec![(w.root_id, 0)];
    while let Some((id, depth)) = stack.pop() {
        if depth > MAX_DEPTH {
            return Err(malformed(format!("nesting deeper than {MAX_DEPTH}")));
        }
        let Some(node) = by_id.get(&id) else {
            return Err(malformed(format!("node {id} missing")));
        };
        if let WireKind::Branch { children, .. } = &node.kind {
            for c in children {
                if !seen.insert(*c) {
                    return Err(malformed(format!("node {c} referenced twice")));
                }
                stack.push((*c, depth + 1));
            }
        }
    }
    let mut fids = HashSet::new();
    for f in &w.floating {
        if f.id == u64::MAX || !fids.insert(f.id) {
            return Err(malformed(format!("bad floating window id {}", f.id)));
        }
        if f.panel_type_ids.is_empty() {
            return Err(malformed(format!("floating window {} has no panels", f.id)));
        }
    }
    Ok(())
}

#[cfg(feature = "layout-blob")]
/// Rebuild a dock from the wire form; every panel through `decode`.
fn rebuild<P: DockPanel>(
    w: &WireDock,
    decode: PanelDecoder<P>,
) -> Result<DockState<P>, LayoutCodecError> {
    validate(w)?;
    let mut failed: Option<(u64, String)> = None;
    let tree: Result<DockingTree<P>, String> =
        w.to_snapshot().restore_tree_with_id(|leaf, type_id| {
            let panel = decode(PanelHome::Leaf(LeafId(leaf)), type_id);
            if panel.is_none() && failed.is_none() {
                failed = Some((leaf, type_id.to_string()));
            }
            panel
        });
    let tree = match (tree, failed) {
        (Ok(t), _) => t,
        (Err(_), Some((leaf, type_id))) => {
            return Err(LayoutCodecError::Panel {
                home: PanelHome::Leaf(LeafId(leaf)),
                type_id,
            })
        }
        (Err(e), None) => return Err(malformed(e)),
    };
    let mut dock = DockState::from_tree(tree);
    for f in &w.floating {
        let id = FloatingWindowId(f.id);
        let mut panels = Vec::with_capacity(f.panel_type_ids.len());
        for t in &f.panel_type_ids {
            match decode(PanelHome::Floating(id), t) {
                Some(p) => panels.push(p),
                None => {
                    return Err(LayoutCodecError::Panel {
                        home: PanelHome::Floating(id),
                        type_id: t.clone(),
                    })
                }
            }
        }
        let (x, y, width, height) = f.rect;
        if ![x, y, width, height].iter().all(|v| v.is_finite()) {
            return Err(malformed(format!("floating window {} rect", f.id)));
        }
        let fw = FloatingWindow::new(id, panels, to_usize(f.active_tab), x, y, width, height);
        if dock.insert_floating(fw).is_none() {
            return Err(malformed(format!("floating window {} refused", f.id)));
        }
    }
    Ok(dock)
}

#[cfg(feature = "layout-blob")]
/// `LayoutCmd::Restore` for one window: decode, rebuild, and swap the dock
/// in only when everything succeeded (any error leaves the window as it
/// was). The live pointer session is dropped with the old dock. Returns the
/// window geometry stored in the blob, if any.
pub(super) fn restore<P: DockPanel>(
    w: &mut WindowLayout<P>,
    blob: &LayoutBlob,
    ctx: &Ctx<P>,
) -> Result<Option<WindowGeometrySnapshot>, LayoutCodecError> {
    let env = decode(blob)?;
    let mut dock = rebuild(&env.dock, ctx.decode)?;
    dock::configure(&mut dock, &ctx.policy);
    w.dock = dock;
    w.session = None;
    Ok(env.geometry)
}