nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Backend-agnostic Visual Layout & Recomposition Inspector data model.
//!
//! Zero backend or UI-framework dependencies. All hot records are fixed-size `Copy`
//! POD types stored in flat, capacity-retaining buffers so:
//! - When disabled, backends hold only `Option<Box<InspectorState>>` (8 B) and layout engines hold
//!   an empty `Vec<ResolvedBoxEdges>` (`capacity() == 0`, 0 B).
//! - When enabled, per-frame tracking and flash decay perform **0 steady-state heap allocations**.

use core::fmt;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, Not};

use nativeview_abi::ReprEnum;
use nativeview_engine::{LayoutRect, Viewport};
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::tables::{
    Display, Isolation, Layout as NvLayout, Position, TextContent, Visual, is_translucent_opacity,
};

use crate::scene::{StackingStyleSource, ZOrder};
use crate::MAX_TREE_DEPTH;

/// Default frame lifetime for paint/dirty flash borders (~300 ms at 60 Hz).
pub const DEFAULT_FLASH_TTL: u8 = 18;

/// Hard per-frame cap on active flash rectangles so full-tree rebuilds never blow frame budgets.
pub const MAX_FLASH_RECTS: usize = 256;

/// Bitflags selecting which live Visual Layout Inspector overlays are active.
///
/// `InspectorFlags::NONE` (`0`) is the default disabled state.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct InspectorFlags(u8);

impl InspectorFlags {
    pub const NONE: Self = Self(0);
    pub const BOX_MODEL: Self = Self(1 << 0);
    pub const PAINT_FLASHES: Self = Self(1 << 1);
    pub const STACKING_BADGES: Self = Self(1 << 2);
    pub const LAYOUT_WARNINGS: Self = Self(1 << 3);
    pub const PICKER_MODE: Self = Self(1 << 4);
    pub const ALL: Self = Self(
        Self::BOX_MODEL.0
            | Self::PAINT_FLASHES.0
            | Self::STACKING_BADGES.0
            | Self::LAYOUT_WARNINGS.0
            | Self::PICKER_MODE.0,
    );

    /// The inspector toggle shortcut every host binds (devtools convention): `F12`, or
    /// `Cmd/Ctrl+Shift+I` (by key or physical `KeyI`), without `Alt`.
    #[inline]
    pub fn is_toggle_shortcut(key: &str, code: &str, modifiers: nativeview_abi::EventFlags) -> bool {
        let command = modifiers.meta() || modifiers.ctrl();
        !modifiers.alt()
            && ((key == "F12" && !command)
                || (command && modifiers.shift() && (key.eq_ignore_ascii_case("i") || code == "KeyI")))
    }

    #[inline]
    pub const fn from_bits_truncate(bits: u8) -> Self {
        Self(bits & Self::ALL.0)
    }

    #[inline]
    pub const fn bits(self) -> u8 {
        self.0
    }

    #[inline]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    #[inline]
    pub const fn is_enabled(self) -> bool {
        self.0 != 0
    }

    #[inline]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    #[inline]
    pub const fn intersects(self, other: Self) -> bool {
        (self.0 & other.0) != 0
    }

    #[inline]
    pub const fn with(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    #[inline]
    pub const fn without(self, other: Self) -> Self {
        Self(self.0 & !other.0)
    }

    #[inline]
    pub const fn toggle(self, other: Self) -> Self {
        Self(self.0 ^ other.0)
    }
}

impl BitOr for InspectorFlags {
    type Output = Self;
    #[inline]
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl BitOrAssign for InspectorFlags {
    #[inline]
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

impl BitAnd for InspectorFlags {
    type Output = Self;
    #[inline]
    fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
    }
}

impl BitAndAssign for InspectorFlags {
    #[inline]
    fn bitand_assign(&mut self, rhs: Self) {
        self.0 &= rhs.0;
    }
}

impl BitXor for InspectorFlags {
    type Output = Self;
    #[inline]
    fn bitxor(self, rhs: Self) -> Self {
        Self(self.0 ^ rhs.0)
    }
}

impl Not for InspectorFlags {
    type Output = Self;
    #[inline]
    fn not(self) -> Self {
        Self((!self.0) & Self::ALL.0)
    }
}

/// Exact resolved CSS box-model edges captured opt-in from Taffy (56 B `Copy` POD).
///
/// Edge order is `[top, right, bottom, left]` in logical points, honoring `margin: auto`,
/// percentage edges, and RTL logical edge resolution.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct ResolvedBoxEdges {
    pub margin: [f32; 4],
    pub border: [f32; 4],
    pub padding: [f32; 4],
    pub content_w: f32,
    pub content_h: f32,
}

const _: () = assert!(core::mem::size_of::<ResolvedBoxEdges>() == 56);

impl ResolvedBoxEdges {
    /// Derives the outer margin box from a node's border box without storing extra coordinates.
    #[inline]
    pub fn margin_box(self, border_box: LayoutRect) -> LayoutRect {
        let [mt, mr, mb, ml] = self.margin;
        let x = border_box.x - ml;
        let y = border_box.y - mt;
        let width = (border_box.width + ml + mr).max(0.0);
        let height = (border_box.height + mt + mb).max(0.0);
        LayoutRect {
            x,
            y,
            width,
            height,
        }
    }

    /// Derives the padding box by insetting `border_box` by `self.border`.
    #[inline]
    pub fn padding_box(self, border_box: LayoutRect) -> LayoutRect {
        let [bt, br, bb, bl] = self.border;
        let bl = bl.max(0.0).min(border_box.width);
        let bt = bt.max(0.0).min(border_box.height);
        let width = (border_box.width - bl - br.max(0.0)).max(0.0);
        let height = (border_box.height - bt - bb.max(0.0)).max(0.0);
        LayoutRect {
            x: border_box.x + bl,
            y: border_box.y + bt,
            width,
            height,
        }
    }

    /// Derives the inner content box by insetting `padding_box` by `self.padding`.
    #[inline]
    pub fn content_box(self, border_box: LayoutRect) -> LayoutRect {
        let pb = self.padding_box(border_box);
        let [pt, pr, pb_e, pl] = self.padding;
        let pl = pl.max(0.0).min(pb.width);
        let pt = pt.max(0.0).min(pb.height);
        let width = (pb.width - pl - pr.max(0.0)).max(0.0);
        let height = (pb.height - pt - pb_e.max(0.0)).max(0.0);
        LayoutRect {
            x: pb.x + pl,
            y: pb.y + pt,
            width,
            height,
        }
    }

    /// Scales resolved edges by `(sx, sy)` (e.g. under a CSS `Transform2D` scale).
    #[inline]
    pub fn scaled(self, sx: f32, sy: f32) -> Self {
        let sx = if sx.is_finite() && sx > 0.0 { sx } else { 1.0 };
        let sy = if sy.is_finite() && sy > 0.0 { sy } else { 1.0 };
        Self {
            margin: [
                self.margin[0] * sy,
                self.margin[1] * sx,
                self.margin[2] * sy,
                self.margin[3] * sx,
            ],
            border: [
                self.border[0] * sy,
                self.border[1] * sx,
                self.border[2] * sy,
                self.border[3] * sx,
            ],
            padding: [
                self.padding[0] * sy,
                self.padding[1] * sx,
                self.padding[2] * sy,
                self.padding[3] * sx,
            ],
            content_w: self.content_w * sx,
            content_h: self.content_h * sy,
        }
    }
}

/// Computes the 4 non-overlapping rectangular ring bands (`[top, right, bottom, left]`)
/// between `outer` and `inner`. Empty sides have `width == 0.0` or `height == 0.0`.
#[inline]
pub fn ring_bands(outer: LayoutRect, inner: LayoutRect) -> [LayoutRect; 4] {
    let top_h = (inner.y - outer.y).max(0.0);
    let bot_y = (inner.y + inner.height).max(outer.y);
    let bot_h = (outer.y + outer.height - bot_y).max(0.0);
    let left_w = (inner.x - outer.x).max(0.0);
    let right_x = (inner.x + inner.width).max(outer.x);
    let right_w = (outer.x + outer.width - right_x).max(0.0);
    let mid_y = inner.y.max(outer.y);
    let mid_h = ((outer.y + outer.height).min(inner.y + inner.height) - mid_y).max(0.0);
    [
        LayoutRect { x: outer.x, y: outer.y, width: outer.width, height: top_h },
        LayoutRect { x: right_x, y: mid_y, width: right_w, height: mid_h },
        LayoutRect { x: outer.x, y: bot_y, width: outer.width, height: bot_h },
        LayoutRect { x: outer.x, y: mid_y, width: left_w, height: mid_h },
    ]
}

/// Computes the 4 non-overlapping margin bands (`[top, right, bottom, left]`) independently from
/// `[top, right, bottom, left]` margin widths so negative margins on one axis never clip or shrink
/// positive margin bands on the perpendicular axis.
#[inline]
pub fn margin_edge_bands(border_box: LayoutRect, margin: [f32; 4]) -> [LayoutRect; 4] {
    let mt = if margin[0].is_finite() { margin[0].max(0.0) } else { 0.0 };
    let mr = if margin[1].is_finite() { margin[1].max(0.0) } else { 0.0 };
    let mb = if margin[2].is_finite() { margin[2].max(0.0) } else { 0.0 };
    let ml = if margin[3].is_finite() { margin[3].max(0.0) } else { 0.0 };
    let full_x = border_box.x - ml;
    let full_w = (border_box.width + ml + mr).max(0.0);
    [
        LayoutRect { x: full_x, y: border_box.y - mt, width: full_w, height: mt },
        LayoutRect { x: border_box.x + border_box.width, y: border_box.y, width: mr, height: border_box.height.max(0.0) },
        LayoutRect { x: full_x, y: border_box.y + border_box.height, width: full_w, height: mb },
        LayoutRect { x: full_x, y: border_box.y, width: ml, height: border_box.height.max(0.0) },
    ]
}

/// Compact CSS-style formatter for `[top, right, bottom, left]` edge quads (`N`, `V/H`, `T/R/B/L`).
#[derive(Debug, Clone, Copy)]
pub struct CompactEdges(pub [f32; 4]);

impl fmt::Display for CompactEdges {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let [t, r, b, l] = [
            self.0[0].round() as i32,
            self.0[1].round() as i32,
            self.0[2].round() as i32,
            self.0[3].round() as i32,
        ];
        if t == r && r == b && b == l {
            write!(f, "{t}")
        } else if t == b && l == r {
            write!(f, "{t}/{r}")
        } else {
            write!(f, "{t}/{r}/{b}/{l}")
        }
    }
}

/// Fallback on-demand box-edge resolver for layout engines that do not capture resolved Taffy
/// edges (e.g. `YogaLayoutEngine`). Resolves explicit pixel margins/paddings and `Visual::border_width`.
pub fn resolve_fallback_box_edges(
    store: &NodeStore,
    id: NodeId,
    border_box: LayoutRect,
) -> ResolvedBoxEdges {
    let mut edges = ResolvedBoxEdges::default();
    if let Some(l) = store.try_row::<NvLayout>(id) {
        let px = |len: nativeview_store::Length| {
            if len.is_points() {
                let v = len.value();
                if v.is_finite() { v } else { 0.0 }
            } else {
                0.0
            }
        };
        edges.margin = [
            px(l.margin_top()),
            px(l.margin_right()),
            px(l.margin_bottom()),
            px(l.margin_left()),
        ];
        edges.padding = [
            px(l.padding_top()).max(0.0),
            px(l.padding_right()).max(0.0),
            px(l.padding_bottom()).max(0.0),
            px(l.padding_left()).max(0.0),
        ];
    }
    if let Some(v) = store.try_row::<Visual>(id) {
        let bw = v.border_width();
        if bw.is_finite() && bw > 0.0 {
            edges.border = [bw, bw, bw, bw];
        }
    }
    let cb = edges.content_box(border_box);
    edges.content_w = cb.width;
    edges.content_h = cb.height;
    edges
}

/// Reasons a node establishes a real CSS stacking context.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct StackingReasonFlags(u8);

impl StackingReasonFlags {
    pub const NONE: Self = Self(0);
    pub const ROOT: Self = Self(1 << 0);
    pub const Z_INDEX: Self = Self(1 << 1);
    pub const OPACITY: Self = Self(1 << 2);
    pub const TRANSFORM: Self = Self(1 << 3);
    pub const ISOLATION: Self = Self(1 << 4);
    pub const TOP_LAYER: Self = Self(1 << 5);
    pub const FIXED: Self = Self(1 << 6);
    pub const STICKY: Self = Self(1 << 7);

    #[inline]
    pub const fn bits(self) -> u8 {
        self.0
    }

    #[inline]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    #[inline]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    #[inline]
    pub const fn with(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

/// Computes `(is_real_sc, effective_z_index, reasons)` for `id`, matching
/// [`crate::classify_node_sc_with_parent_display`].
pub fn compute_stacking_reasons<S: StackingStyleSource>(
    store: &NodeStore,
    style: &S,
    id: NodeId,
    is_top_layer_root: bool,
) -> (bool, Option<ZOrder>, StackingReasonFlags) {
    let box_parent_display = if id == NodeId::ROOT || is_top_layer_root {
        Display::Block
    } else {
        let mut cur = store.parent(id);
        let mut parent_display = Display::Block;
        for _ in 0..MAX_TREE_DEPTH {
            let Some(p) = cur else {
                break;
            };
            if !style.is_display_contents(store, p) {
                parent_display = style.display_of(store, p);
                break;
            }
            cur = store.parent(p).filter(|&gp| gp != p);
        }
        parent_display
    };

    let pos = style.position_of(store, id);
    let parent_is_flex_or_grid = matches!(
        box_parent_display,
        Display::Flex | Display::InlineFlex | Display::Grid
    );
    let eff_z = if pos != Position::Static || parent_is_flex_or_grid {
        style.z_index_of(store, id)
    } else {
        None
    };

    let mut reasons = StackingReasonFlags::NONE;
    if id == NodeId::ROOT {
        reasons = reasons.with(StackingReasonFlags::ROOT);
    }
    if is_top_layer_root {
        reasons = reasons.with(StackingReasonFlags::TOP_LAYER);
    }
    if eff_z.is_some() {
        reasons = reasons.with(StackingReasonFlags::Z_INDEX);
    }
    if pos == Position::Fixed {
        reasons = reasons.with(StackingReasonFlags::FIXED);
    } else if pos == Position::Sticky {
        reasons = reasons.with(StackingReasonFlags::STICKY);
    }
    if is_translucent_opacity(style.opacity_of(store, id)) {
        reasons = reasons.with(StackingReasonFlags::OPACITY);
    }
    if style.has_transform(store, id) {
        reasons = reasons.with(StackingReasonFlags::TRANSFORM);
    }
    if style.isolation_of(store, id) == Isolation::Isolate {
        reasons = reasons.with(StackingReasonFlags::ISOLATION);
    }
    let extra_table_sc = store
        .node_tables(id)
        .intersects(store.stacking_context_tables());
    let is_real_sc = !reasons.is_empty() || extra_table_sc;
    (is_real_sc, eff_z.map(ZOrder), reasons)
}

/// Diagnostic layout anomaly flags computed for an inspected node.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct LayoutWarningFlags(u8);

impl LayoutWarningFlags {
    pub const NONE: Self = Self(0);
    pub const ZERO_SIZE_COLLAPSE: Self = Self(1 << 0);
    pub const OVERFLOW_CLIP: Self = Self(1 << 1);
    pub const OFFSCREEN: Self = Self(1 << 2);

    #[inline]
    pub const fn bits(self) -> u8 {
        self.0
    }

    #[inline]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    #[inline]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    #[inline]
    pub const fn with(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

/// Evaluates diagnostic [`LayoutWarningFlags`] for a laid-out node.
///
/// `ZERO_SIZE_COLLAPSE` and `OVERFLOW_CLIP` compare against untransformed `layout_box` (skipping
/// `OVERFLOW_CLIP` for scroll containers where overflow is expected), while `OFFSCREEN` compares
/// the transformed/scroll-shifted `visual_box` against `viewport`.
#[inline]
#[allow(clippy::too_many_arguments)]
pub fn compute_layout_warnings(
    store: &NodeStore,
    id: NodeId,
    layout_box: LayoutRect,
    visual_box: LayoutRect,
    edges: ResolvedBoxEdges,
    viewport: Viewport,
    clips_overflow: bool,
    is_scrollable: bool,
) -> LayoutWarningFlags {
    let mut flags = LayoutWarningFlags::NONE;
    let has_content = !store.children(id).is_empty()
        || store
            .try_row::<TextContent>(id)
            .is_some_and(|t| !t.text().is_empty());
    if has_content && (layout_box.width <= 0.0 || layout_box.height <= 0.0) {
        flags = flags.with(LayoutWarningFlags::ZERO_SIZE_COLLAPSE);
    }
    let client = edges.padding_box(layout_box);
    if clips_overflow
        && !is_scrollable
        && (edges.content_w > client.width + 0.5 || edges.content_h > client.height + 0.5)
    {
        flags = flags.with(LayoutWarningFlags::OVERFLOW_CLIP);
    }
    if viewport.width > 0.0
        && viewport.height > 0.0
        && visual_box.width > 0.0
        && visual_box.height > 0.0
        && (visual_box.x + visual_box.width <= 0.0
            || visual_box.y + visual_box.height <= 0.0
            || visual_box.x >= viewport.width
            || visual_box.y >= viewport.height)
    {
        flags = flags.with(LayoutWarningFlags::OFFSCREEN);
    }
    flags
}

/// Classification of the minimal work required to synchronize a scene or inspector frame.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ReprEnum)]
#[repr_enum(fallback = None)]
pub enum SceneDirtyKind {
    /// No visible scene changes occurred.
    #[default]
    None = 0,
    /// Only property-tree inputs (`opacity`, `transform`, `scroll`, or `z_index`) changed.
    CompositeOnly = 1,
    /// One or more nodes need local paint-chunk re-emission (no layout/tree changes).
    PaintOnly = 2,
    /// Tree topology, layout, viewport, or `display: none` changed.
    LayoutOrTree = 3,
}

impl SceneDirtyKind {
    #[inline]
    pub const fn label(self) -> &'static str {
        match self {
            Self::None => "Clean",
            Self::CompositeOnly => "CompositeOnly",
            Self::PaintOnly => "PaintOnly",
            Self::LayoutOrTree => "LayoutOrTree",
        }
    }
}

/// Stack-allocated per-node inspection snapshot (0 heap allocations).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct InspectorNodeSnapshot {
    pub node_id: NodeId,
    pub border_box: LayoutRect,
    pub edges: ResolvedBoxEdges,
    pub is_real_sc: bool,
    pub z_index: Option<ZOrder>,
    pub sc_reason: StackingReasonFlags,
    pub warnings: LayoutWarningFlags,
    pub paint_count: u32,
    pub layout_count: u32,
    pub recompose_count: u32,
    pub last_dirty_kind: u8,
}

impl InspectorNodeSnapshot {
    #[inline]
    pub fn margin_box(&self) -> LayoutRect {
        self.edges.margin_box(self.border_box)
    }

    #[inline]
    pub fn padding_box(&self) -> LayoutRect {
        self.edges.padding_box(self.border_box)
    }

    #[inline]
    pub fn content_box(&self) -> LayoutRect {
        self.edges.content_box(self.border_box)
    }

    #[inline]
    pub fn dirty_kind(&self) -> SceneDirtyKind {
        SceneDirtyKind::from_u8(self.last_dirty_kind)
    }
}

mod heat;
pub use heat::{InspectorHeatTracker, NODE_HEAT_FLASHING, NODE_HEAT_OCCUPIED, NodeHeat};

#[cfg(test)]
mod tests;