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;
pub const DEFAULT_FLASH_TTL: u8 = 18;
pub const MAX_FLASH_RECTS: usize = 256;
#[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,
);
#[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)
}
}
#[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 {
#[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,
}
}
#[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,
}
}
#[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,
}
}
#[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,
}
}
}
#[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 },
]
}
#[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) },
]
}
#[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}")
}
}
}
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
}
#[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)
}
}
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)
}
#[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)
}
}
#[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
}
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ReprEnum)]
#[repr_enum(fallback = None)]
pub enum SceneDirtyKind {
#[default]
None = 0,
CompositeOnly = 1,
PaintOnly = 2,
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",
}
}
}
#[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;