gpui-rhai 0.2.1

A Rhai-authored declarative UI runtime for GPUI
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! Composition audit: checks a mounted view's committed geometry and resolved
//! styles against the rules an application profile enables.
//!
//! The audit is design-language neutral: it compares relationships (heights
//! in a row, nested gaps, painted contrast) rather than fixed values. With no
//! rules enabled it reports nothing.

use std::collections::{BTreeMap, BTreeSet};

use crate::{
    Align, ColorResolver, Environment, FlexDirection, GeometryBounds, GeometryRegistry,
    InteractionState, Justify, Length, NodeId, PositionMode, RetainedUiTree, Rgba8,
    StyleProperties, Symbol, UiNode, UiNodeKind, UiValue,
};

/// One composition rule.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum AuditRule {
    /// Sibling controls in one row with different heights.
    RowHeightMismatch,
    /// Stacked text starts that nearly, but not exactly, align.
    TextEdgeMisaligned,
    /// An inner gap greater than or equal to its enclosing gap.
    SpacingNotNested,
    /// More than one solid action in one action group.
    MultipleSolidActions,
    /// More than one font size among the text of one row.
    MixedTypeInRow,
    /// Text below its contrast minimum against the painted background.
    LowContrastText,
    /// A font family that does not resolve on this platform.
    UnresolvedFont,
}

impl AuditRule {
    pub const ALL: [Self; 7] = [
        Self::RowHeightMismatch,
        Self::TextEdgeMisaligned,
        Self::SpacingNotNested,
        Self::MultipleSolidActions,
        Self::MixedTypeInRow,
        Self::LowContrastText,
        Self::UnresolvedFont,
    ];

    /// The profile identifier, such as `row-height-mismatch`.
    #[must_use]
    pub const fn id(self) -> &'static str {
        match self {
            Self::RowHeightMismatch => "row-height-mismatch",
            Self::TextEdgeMisaligned => "text-edge-misaligned",
            Self::SpacingNotNested => "spacing-not-nested",
            Self::MultipleSolidActions => "multiple-solid-actions",
            Self::MixedTypeInRow => "mixed-type-in-row",
            Self::LowContrastText => "low-contrast-text",
            Self::UnresolvedFont => "unresolved-font",
        }
    }

    #[must_use]
    pub fn parse(id: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|rule| rule.id() == id)
    }
}

/// The rules a profile enables. The default enables none.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AuditRules {
    enabled: BTreeSet<AuditRule>,
}

impl AuditRules {
    /// Every rule.
    #[must_use]
    pub fn all() -> Self {
        Self {
            enabled: AuditRule::ALL.into_iter().collect(),
        }
    }

    /// Enable rules by profile identifier.
    ///
    /// # Errors
    ///
    /// Returns the first unknown identifier.
    pub fn from_ids<'a>(ids: impl IntoIterator<Item = &'a str>) -> Result<Self, String> {
        let enabled = ids
            .into_iter()
            .map(|id| AuditRule::parse(id).ok_or_else(|| id.to_owned()))
            .collect::<Result<_, _>>()?;
        Ok(Self { enabled })
    }

    #[must_use]
    pub fn contains(&self, rule: AuditRule) -> bool {
        self.enabled.contains(&rule)
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.enabled.is_empty()
    }
}

/// One audit finding.
#[derive(Clone, Debug, PartialEq)]
pub struct AuditFinding {
    pub rule: AuditRule,
    /// The retained node the finding is anchored to.
    pub node: Option<NodeId>,
    /// A readable path of keys and indices from the root.
    pub path: String,
    pub message: String,
}

impl std::fmt::Display for AuditFinding {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "{} at {}: {}",
            self.rule.id(),
            self.path,
            self.message
        )
    }
}

const CONTROL_ROLES: &[&str] = &[
    "button",
    "tab",
    "text_field",
    "textbox",
    "searchbox",
    "combobox",
    "spinbutton",
    "checkbox",
    "radio",
    "switch",
    "slider",
];
const MARKER_ROLES: &[&str] = &["status"];
const NEAR_MISS_MAX: f64 = 8.0;
const EPSILON: f64 = 0.5;

/// Inputs shared by every node of one audit.
pub(crate) struct AuditInputs<'a, C: ColorResolver> {
    pub tree: &'a RetainedUiTree,
    pub geometry: &'a GeometryRegistry,
    pub theme: &'a C,
    pub rules: &'a AuditRules,
    /// Font families known to the text system, when the caller can provide
    /// them; `None` skips [`AuditRule::UnresolvedFont`].
    pub available_fonts: Option<&'a BTreeSet<String>>,
    /// Text starts are right edges in right-to-left views.
    pub direction: crate::TextDirection,
}

#[derive(Clone, Copy)]
struct Scope {
    environment: Environment,
    disabled: bool,
    text_color: Option<Rgba8>,
    background: Rgba8,
    font_size: Option<f64>,
    font_weight: u16,
    /// Text set in the label voice (`typography("label")`): metadata such as key
    /// legends and facets, designed to sit beside body text.
    label_voice: bool,
    /// Gaps of the nearest enclosing rows and columns with at least two
    /// children. Proximity only competes along one axis.
    enclosing_row_gap: Option<f64>,
    enclosing_column_gap: Option<f64>,
    /// Inside a control: its internal layout is the component's own
    /// responsibility, so composition rules other than contrast stop here.
    inside_control: bool,
}

/// What the audit learned about one rendered node, for its parent's checks.
#[derive(Clone, Debug, Default)]
struct NodeSummary {
    role: Option<String>,
    bounds: Option<GeometryBounds>,
    /// Height of the control this subtree stands for: a control, or a wrapper
    /// that holds just one.
    control_height: Option<f64>,
    /// Whether the subtree holds a control anywhere; such a child carries the
    /// control type scale and stays out of a row's type mix.
    contains_control: bool,
    /// Font size of the first text in this subtree, unless inside a marker.
    text_size: Option<f64>,
    /// Start x of the first text in this subtree.
    text_start: Option<f64>,
    /// Whether the first control in this subtree is a solid action.
    solid_action: bool,
}

/// Audit a committed tree.
pub(crate) fn audit<C: ColorResolver>(inputs: &AuditInputs<'_, C>) -> Vec<AuditFinding> {
    let mut findings = Vec::new();
    if inputs.rules.is_empty() {
        return findings;
    }
    let (Some(root), Some(root_id)) = (inputs.tree.root(), root_node_id(inputs.tree)) else {
        return findings;
    };
    let background = inputs
        .theme
        .resolve_token("surface")
        .unwrap_or(Rgba8::from_rgba_hex(0xffff_ffff));
    let scope = Scope {
        environment: Environment::EMPTY,
        disabled: false,
        text_color: inputs.theme.resolve_token("text_primary"),
        background,
        font_size: None,
        font_weight: 400,
        label_voice: false,
        enclosing_row_gap: None,
        enclosing_column_gap: None,
        inside_control: false,
    };
    let solid = solid_colors(inputs.theme);
    let mut reported_fonts = BTreeSet::new();
    let mut walker = Walker {
        inputs,
        solid,
        allowed: BTreeSet::new(),
        findings: &mut findings,
        reported_fonts: &mut reported_fonts,
    };
    walker.visit(root, Some(root_id), scope, "root");
    findings
}

fn root_node_id(tree: &RetainedUiTree) -> Option<NodeId> {
    tree.nodes()
        .find(|node| node.parent().is_none())
        .map(crate::RetainedNode::id)
}

fn solid_colors(theme: &impl ColorResolver) -> BTreeSet<u32> {
    ["accent", "danger", "warning", "success"]
        .into_iter()
        .filter_map(|token| theme.resolve_token(token))
        .map(Rgba8::as_rgba_hex)
        .collect()
}

struct Walker<'a, 'b, C: ColorResolver> {
    inputs: &'a AuditInputs<'b, C>,
    solid: BTreeSet<u32>,
    /// Rules a node deliberately opts out of (`audit_allow`), by node path.
    allowed: BTreeSet<(String, AuditRule)>,
    findings: &'a mut Vec<AuditFinding>,
    reported_fonts: &'a mut BTreeSet<String>,
}

impl<C: ColorResolver> Walker<'_, '_, C> {
    fn report(&mut self, rule: AuditRule, node: Option<NodeId>, path: &str, message: String) {
        if self.inputs.rules.contains(rule) && !self.allowed.contains(&(path.to_owned(), rule)) {
            self.findings.push(AuditFinding {
                rule,
                node,
                path: path.to_owned(),
                message,
            });
        }
    }

    /// The edge text starts from: left in left-to-right views, right otherwise.
    fn start_edge(&self, bounds: GeometryBounds) -> f64 {
        match self.inputs.direction {
            crate::TextDirection::LeftToRight => bounds.x,
            crate::TextDirection::RightToLeft => bounds.x + bounds.width,
        }
    }

    fn pixels(&self, length: Option<Length>, environment: &Environment) -> Option<f64> {
        match self.inputs.theme.resolve_length_in(length?, environment)? {
            Length::Pixels(value) => Some(value),
            Length::Rems(value) => Some(value * 16.0),
            Length::Relative(_) | Length::Token(_) => None,
        }
    }

    #[allow(clippy::too_many_lines)] // One ordered pass per node keeps scope inheritance readable.
    fn visit(
        &mut self,
        node: &UiNode,
        id: Option<NodeId>,
        parent: Scope,
        path: &str,
    ) -> NodeSummary {
        let retained = id.and_then(|id| self.inputs.tree.node(id));
        let style = node.style().resolve(&InteractionState::default());
        let mut scope = parent;
        if let Some(UiValue::Map(values)) = node.attributes().get("environment") {
            for (name, value) in values {
                if let UiValue::String(value) = value {
                    scope.environment = scope
                        .environment
                        .with(Symbol::intern(name), Symbol::intern(value))
                        .unwrap_or(scope.environment);
                }
            }
        }
        scope.disabled |= node.attributes().get("disabled") == Some(&UiValue::Bool(true));
        if let Some(UiValue::Array(rules)) = node.attributes().get("audit_allow") {
            for rule in rules {
                if let UiValue::String(id) = rule
                    && let Some(rule) = AuditRule::parse(id)
                {
                    self.allowed.insert((path.to_owned(), rule));
                }
            }
        }
        self.apply_paint(&style, &mut scope);
        self.apply_text(&style, &mut scope, id, path);

        let role = retained
            .and_then(|node| node.attributes().get("role"))
            .and_then(|role| match role {
                UiValue::String(role) => Some(role.clone()),
                _ => None,
            });
        let bounds = id
            .and_then(|id| self.inputs.geometry.get(id))
            .map(|geometry| geometry.visual);
        let mut summary = NodeSummary {
            role: role.clone(),
            bounds,
            ..NodeSummary::default()
        };
        let is_control = role
            .as_deref()
            .is_some_and(|role| CONTROL_ROLES.contains(&role));
        // A marker (Badge, Tag) lays out its own lamp and text, like a control.
        let is_marker = role
            .as_deref()
            .is_some_and(|role| MARKER_ROLES.contains(&role));
        if let Some(role) = &role
            && CONTROL_ROLES.contains(&role.as_str())
        {
            summary.contains_control = true;
            summary.control_height = bounds.map(|bounds| bounds.height);
            summary.solid_action = role == "button"
                && style
                    .background
                    .as_ref()
                    .and_then(|color| self.inputs.theme.resolve(color))
                    .is_some_and(|color| {
                        color.as_rgba_hex() & 0xff == 0xff
                            && self.solid.contains(&color.as_rgba_hex())
                    });
        }

        match node.kind() {
            UiNodeKind::Text { .. } | UiNodeKind::RichText { .. } => {
                if !scope.label_voice {
                    summary.text_size = scope.font_size;
                }
                summary.text_start = bounds.map(|bounds| self.start_edge(bounds));
                self.check_contrast(&scope, id, path);
            }
            // A native control renders its own text at the inherited size.
            UiNodeKind::Custom { .. } if style.typography.is_some() => {
                summary.text_size = scope.font_size;
            }
            UiNodeKind::Box { children } | UiNodeKind::Fragment { children } => {
                let direction = style.direction.unwrap_or(FlexDirection::Column);
                let gap = self.pixels(style.gap, &scope.environment);
                // Distributed rows treat the gap as a floor, not a relationship.
                let distributed = matches!(style.justify, Some(Justify::Between | Justify::Around));
                // A control's or marker's internal layout is the component's business.
                let counted = !scope.inside_control
                    && !is_control
                    && !is_marker
                    && !distributed
                    && children.len() >= 2
                    && gap.is_some_and(|gap| gap > 0.0);
                let enclosing = match direction {
                    FlexDirection::Row => parent.enclosing_row_gap,
                    FlexDirection::Column => parent.enclosing_column_gap,
                };
                if counted
                    && let (Some(inner), Some(outer)) = (gap, enclosing)
                    && inner + EPSILON >= outer
                {
                    self.report(
                        AuditRule::SpacingNotNested,
                        id,
                        path,
                        format!(
                            "inner gap {inner}px is not smaller than the enclosing gap {outer}px"
                        ),
                    );
                }
                // A heading leads its content: the heading gap is a typographic
                // relationship, so the content keeps the outer gap as its limit.
                // A container that opts out of the nesting rule (a grid, such as a
                // label column) neither answers to it nor imposes its gap below.
                let opted_out = self
                    .allowed
                    .contains(&(path.to_owned(), AuditRule::SpacingNotNested));
                let sets_limit = counted
                    && !opted_out
                    && !leads_with_heading(children)
                    && !introduced_elsewhere(node);
                let mut child_scope = Scope {
                    inside_control: scope.inside_control || is_control || is_marker,
                    ..scope
                };
                if sets_limit {
                    match direction {
                        FlexDirection::Row => child_scope.enclosing_row_gap = gap,
                        FlexDirection::Column => child_scope.enclosing_column_gap = gap,
                    }
                }
                let summaries = children
                    .iter()
                    .enumerate()
                    .map(|(index, child)| {
                        let child_id = child_link(self.inputs.tree, id, "children", index);
                        let child_path = child.key().map_or_else(
                            || format!("{path}/{index}"),
                            |key| format!("{path}/{}", key.as_str()),
                        );
                        self.visit(child, child_id, child_scope, &child_path)
                    })
                    .collect::<Vec<_>>();
                if !scope.inside_control && !is_control && !is_marker {
                    let heading_led = leads_with_heading(children) || introduced_elsewhere(node);
                    self.check_container(direction, &summaries, heading_led, id, path);
                }
                inherit_first(&mut summary, &summaries, role.as_deref());
                // Only a wrapper that hugs one control stands in for it; a container
                // of several (a pane with a toolbar and a body) is not a control in
                // its parent's row.
                if children.len() > 1 && !is_control {
                    summary.control_height = None;
                    summary.solid_action = false;
                }
            }
            UiNodeKind::Overlay {
                trigger, content, ..
            } => {
                let trigger_id = child_link(self.inputs.tree, id, "trigger", 0);
                let trigger = self.visit(trigger, trigger_id, scope, &format!("{path}/trigger"));
                // Overlay content floats in its own layer: no spacing relationship
                // with the place its trigger sits in.
                let content_id = child_link(self.inputs.tree, id, "content", 0);
                let layer = Scope {
                    enclosing_row_gap: None,
                    enclosing_column_gap: None,
                    ..scope
                };
                self.visit(content, content_id, layer, &format!("{path}/content"));
                inherit_first(&mut summary, &[trigger], role.as_deref());
            }
            UiNodeKind::Layer { content, .. } => {
                // A layer floats like overlay content.
                let content_id = child_link(self.inputs.tree, id, "content", 0);
                let layer = Scope {
                    enclosing_row_gap: None,
                    enclosing_column_gap: None,
                    ..scope
                };
                self.visit(content, content_id, layer, &format!("{path}/content"));
            }
            UiNodeKind::ErrorBoundary { child, fallback } => {
                // Audit what renders: the child, or the fallback once the child
                // failed (only the rendered one has geometry).
                let child_id = child_link(self.inputs.tree, id, "child", 0);
                let fallback_id = child_link(self.inputs.tree, id, "fallback", 0);
                let fallback_rendered = child_id
                    .is_none_or(|id| self.inputs.geometry.get(id).is_none())
                    && fallback_id.is_some_and(|id| self.inputs.geometry.get(id).is_some());
                let rendered = if fallback_rendered {
                    self.visit(fallback, fallback_id, scope, &format!("{path}/fallback"))
                } else {
                    self.visit(child, child_id, scope, &format!("{path}/child"))
                };
                inherit_first(&mut summary, &[rendered], role.as_deref());
            }
            UiNodeKind::VirtualCollection { spec } => {
                // The realized items: what a virtual list shows is audited like any
                // other content; unrealized items have no geometry yet.
                for (index, item) in spec.realized.values().enumerate() {
                    let item_id = child_link(self.inputs.tree, id, "items", index);
                    let item_path = item.key().map_or_else(
                        || format!("{path}/item/{index}"),
                        |key| format!("{path}/item/{}", key.as_str()),
                    );
                    self.visit(item, item_id, scope, &item_path);
                }
            }
            _ => {}
        }
        // Controls, markers and any filled or framed box align by their own edge;
        // their inner padding is the component's business.
        let painted = style
            .background
            .as_ref()
            .and_then(|color| self.inputs.theme.resolve(color))
            .is_some_and(|color| alpha_of(color) > 0.0);
        let framed = [
            style.border_widths.top,
            style.border_widths.right,
            style.border_widths.bottom,
            style.border_widths.left,
        ]
        .into_iter()
        .any(|width| {
            self.pixels(width, &scope.environment)
                .is_some_and(|width| width > 0.0)
        });
        // A cell that centers its content (weekday labels, day numbers) has no
        // text start of its own: the cell edge is what lines up.
        let centered = match style.direction {
            Some(FlexDirection::Row) => style.justify == Some(Justify::Center),
            Some(FlexDirection::Column) => style.align == Some(Align::Center),
            None => false,
        };
        if painted
            || framed
            || centered
            || role
                .as_deref()
                .is_some_and(|role| CONTROL_ROLES.contains(&role) || MARKER_ROLES.contains(&role))
        {
            summary.text_start = bounds
                .map(|bounds| self.start_edge(bounds))
                .or(summary.text_start);
        }
        // An absolutely positioned node (a focus frame drawn over a panel's edge, an
        // indicator) is out of flow: it does not stack with its siblings' text.
        if style.position == Some(PositionMode::Absolute) {
            summary.text_start = None;
        }
        summary
    }

    fn apply_paint(&self, style: &StyleProperties, scope: &mut Scope) {
        if let Some(color) = style
            .background
            .as_ref()
            .and_then(|color| self.inputs.theme.resolve(color))
        {
            let alpha = alpha_of(color);
            if alpha > 0.0 {
                scope.background = scope.background.mix(opaque(color), alpha);
            }
        }
        if let Some(color) = style
            .text_color
            .as_ref()
            .and_then(|color| self.inputs.theme.resolve(color))
        {
            scope.text_color = Some(color);
        }
    }

    fn apply_text(
        &mut self,
        style: &StyleProperties,
        scope: &mut Scope,
        id: Option<NodeId>,
        path: &str,
    ) {
        if let Some(name) = style.typography.as_deref() {
            scope.label_voice = name == "label";
        }
        let role = style.typography.as_deref().and_then(|role| {
            self.inputs
                .theme
                .resolve_typography_in(role, &scope.environment)
        });
        if let Some(role) = &role {
            scope.font_weight = role.weight;
            if let Some(size) = self.pixels(Some(role.size), &scope.environment) {
                scope.font_size = Some(size);
            }
            if let Some(family) = &role.family {
                self.check_font(family, &role.fallbacks, id, path);
            }
        }
        if let Some(size) = self.pixels(style.font_size, &scope.environment) {
            scope.font_size = Some(size);
        }
        if let Some(weight) = style.font_weight {
            scope.font_weight = weight;
        }
        if let Some(family) = &style.font_family {
            let fallbacks = style.font_fallbacks.clone().unwrap_or_default();
            self.check_font(family, &fallbacks, id, path);
        }
    }

    fn check_font(&mut self, family: &str, fallbacks: &[String], id: Option<NodeId>, path: &str) {
        let Some(available) = self.inputs.available_fonts else {
            return;
        };
        // Declared fallbacks are a deliberate chain; only a chain that resolves
        // nowhere falls back silently.
        let resolves = available.contains(family)
            || fallbacks
                .iter()
                .any(|fallback| available.contains(fallback));
        if !resolves && self.reported_fonts.insert(family.to_owned()) {
            self.report(
                AuditRule::UnresolvedFont,
                id,
                path,
                format!("font family `{family}` is not available; text falls back silently"),
            );
        }
    }

    fn check_contrast(&mut self, scope: &Scope, id: Option<NodeId>, path: &str) {
        if scope.disabled {
            return;
        }
        let Some(text) = scope.text_color else {
            return;
        };
        let size = scope.font_size.unwrap_or(16.0);
        let large = size >= 24.0 || (size >= 18.66 && scope.font_weight >= 700);
        let minimum = if large { 3.0 } else { 4.5 };
        let painted = scope.background.mix(opaque(text), alpha_of(text));
        let ratio = painted.contrast_ratio(scope.background);
        if ratio + 0.005 < minimum {
            self.report(
                AuditRule::LowContrastText,
                id,
                path,
                format!("text contrast {ratio:.2}:1 is below {minimum}:1"),
            );
        }
    }

    fn check_container(
        &mut self,
        direction: FlexDirection,
        children: &[NodeSummary],
        heading_led: bool,
        id: Option<NodeId>,
        path: &str,
    ) {
        match direction {
            FlexDirection::Row => {
                let heights = children
                    .iter()
                    .filter_map(|child| child.control_height)
                    .collect::<Vec<_>>();
                if let (Some(min), Some(max)) = (
                    heights.iter().copied().reduce(f64::min),
                    heights.iter().copied().reduce(f64::max),
                ) && max - min > EPSILON
                {
                    self.report(
                        AuditRule::RowHeightMismatch,
                        id,
                        path,
                        format!("controls in one row range from {min}px to {max}px high"),
                    );
                }
                // Markers and controls carry their own type scale (controls are
                // held to one height by row-height-mismatch instead).
                let sizes = children
                    .iter()
                    .filter(|child| {
                        !child.contains_control
                            && !child
                                .role
                                .as_deref()
                                .is_some_and(|role| MARKER_ROLES.contains(&role))
                    })
                    .filter_map(|child| child.text_size)
                    .map(centi_pixels)
                    .collect::<BTreeSet<_>>();
                // A row led by a heading is a header: the title and its actions
                // differ in size by design.
                if sizes.len() > 1 && !heading_led {
                    let sizes = sizes
                        .iter()
                        .map(|size| format!("{}px", f64::from(*size) / 100.0))
                        .collect::<Vec<_>>()
                        .join(", ");
                    self.report(
                        AuditRule::MixedTypeInRow,
                        id,
                        path,
                        format!("one row mixes font sizes {sizes}"),
                    );
                }
            }
            FlexDirection::Column => {
                let starts = children
                    .iter()
                    .filter_map(|child| child.text_start)
                    .collect::<Vec<_>>();
                for (index, left) in starts.iter().enumerate() {
                    for right in &starts[index + 1..] {
                        let delta = (left - right).abs();
                        if delta > EPSILON && delta < NEAR_MISS_MAX {
                            self.report(
                                AuditRule::TextEdgeMisaligned,
                                id,
                                path,
                                format!("stacked text starts differ by {delta:.1}px"),
                            );
                            return;
                        }
                    }
                }
            }
        }
        let solid = children.iter().filter(|child| child.solid_action).count();
        if solid > 1 {
            self.report(
                AuditRule::MultipleSolidActions,
                id,
                path,
                format!("{solid} solid actions share one group"),
            );
        }
    }
}

/// Font sizes in hundredths of a pixel, so sizes compare exactly.
#[allow(clippy::cast_possible_truncation)]
fn centi_pixels(size: f64) -> i32 {
    (size * 100.0)
        .round()
        .clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32
}

fn alpha_of(color: Rgba8) -> f64 {
    f64::from(u8::try_from(color.as_rgba_hex() & 0xff).unwrap_or(0)) / 255.0
}

fn opaque(color: Rgba8) -> Rgba8 {
    Rgba8::from_rgba_hex(color.as_rgba_hex() | 0xff)
}

/// Whether the first child subtree starts with a heading.
/// The content starts with a heading, or with a view switcher (a tab list
/// without a panel) that plays the heading's part.
fn leads_with_heading(children: &[UiNode]) -> bool {
    let mut cursor = children.first();
    while let Some(node) = cursor {
        if matches!(
            node.attributes().get("role"),
            Some(UiValue::String(role)) if role == "heading" || role == "tablist"
        ) {
            return true;
        }
        cursor = match node.kind() {
            UiNodeKind::Box { children } | UiNodeKind::Fragment { children } => children.first(),
            _ => None,
        };
    }
    false
}

/// A container whose heading the application draws elsewhere (a Region with
/// `external_title`, set through `.heading_elsewhere()`).
fn introduced_elsewhere(node: &UiNode) -> bool {
    node.attributes().get("heading_elsewhere") == Some(&UiValue::Bool(true))
}

/// Carry the first control and text of a subtree up to the parent.
fn inherit_first(summary: &mut NodeSummary, children: &[NodeSummary], role: Option<&str>) {
    let inside_marker = role.is_some_and(|role| MARKER_ROLES.contains(&role));
    for child in children {
        summary.contains_control |= child.contains_control;
        if summary.control_height.is_none() && child.control_height.is_some() {
            summary.control_height = child.control_height;
            summary.solid_action = child.solid_action;
        }
        if summary.text_size.is_none() && !inside_marker {
            summary.text_size = child.text_size;
        }
        if summary.text_start.is_none() {
            summary.text_start = child.text_start;
        }
    }
    if summary.bounds.is_none() {
        summary.bounds = children.iter().find_map(|child| child.bounds);
    }
}

fn child_link(
    tree: &RetainedUiTree,
    parent: Option<NodeId>,
    group: &str,
    index: usize,
) -> Option<NodeId> {
    tree.node(parent?)?
        .children()
        .filter(|child| child.group() == group)
        .nth(index)
        .map(crate::RetainedChildLink::node)
}

/// An application profile: the composition rules it enables at runtime and
/// the static rules `gpui-rhai check` applies to application source.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Profile {
    pub name: String,
    pub audit: AuditRules,
    pub static_rules: BTreeSet<String>,
}

/// Static rule identifiers understood by `gpui-rhai check`.
pub const STATIC_RULES: &[&str] = &["literal-geometry"];

/// Load `profile() -> #{ name, audit: [...], check: [...] }`.
///
/// # Errors
///
/// Returns a message for script errors, unknown fields or rule identifiers.
pub fn load_profile_source(
    engine: &rhai::Engine,
    source_name: &str,
    source: &str,
) -> Result<Profile, String> {
    let ast = engine
        .compile(source)
        .map_err(|error| format!("{source_name}: {error}"))?;
    let value: rhai::Dynamic = engine
        .call_fn(&mut rhai::Scope::new(), &ast, "profile", ())
        .map_err(|error| format!("{source_name}: {error}"))?;
    let mut map = value
        .try_cast::<rhai::Map>()
        .ok_or_else(|| format!("{source_name}: profile() must return a map"))?;
    let strings = |value: Option<rhai::Dynamic>, field: &str| -> Result<Vec<String>, String> {
        value
            .map(|value| {
                value
                    .into_typed_array::<rhai::ImmutableString>()
                    .map(|items| items.into_iter().map(|item| item.to_string()).collect())
                    .map_err(|_| format!("{source_name}: `{field}` must be an array of strings"))
            })
            .transpose()
            .map(Option::unwrap_or_default)
    };
    let name = map
        .remove("name")
        .map(|name| name.into_string().unwrap_or_default())
        .unwrap_or_default();
    let audit = strings(map.remove("audit"), "audit")?;
    let audit = AuditRules::from_ids(audit.iter().map(String::as_str))
        .map_err(|id| format!("{source_name}: unknown audit rule `{id}`"))?;
    let static_rules = strings(map.remove("check"), "check")?
        .into_iter()
        .map(|rule| {
            if STATIC_RULES.contains(&rule.as_str()) {
                Ok(rule)
            } else {
                Err(format!("{source_name}: unknown check rule `{rule}`"))
            }
        })
        .collect::<Result<_, _>>()?;
    if let Some(field) = map.keys().next() {
        return Err(format!("{source_name}: unknown profile field `{field}`"));
    }
    Ok(Profile {
        name,
        audit,
        static_rules,
    })
}

/// Group findings by rule for reports.
#[must_use]
pub fn summarize(findings: &[AuditFinding]) -> BTreeMap<&'static str, usize> {
    let mut summary = BTreeMap::new();
    for finding in findings {
        *summary.entry(finding.rule.id()).or_default() += 1;
    }
    summary
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn profiles_load_rule_sets_and_reject_unknown_rules() {
        let engine = rhai::Engine::new();
        let profile = load_profile_source(
            &engine,
            "profile.rhai",
            r#"fn profile() { #{ name: "productivity",
                audit: ["row-height-mismatch", "low-contrast-text"],
                check: ["literal-geometry"] } }"#,
        )
        .unwrap();
        assert_eq!(profile.name, "productivity");
        assert!(profile.audit.contains(AuditRule::LowContrastText));
        assert!(!profile.audit.contains(AuditRule::MixedTypeInRow));
        assert!(profile.static_rules.contains("literal-geometry"));
        assert!(
            load_profile_source(&engine, "p.rhai", r#"fn profile() { #{ audit: ["x"] } }"#)
                .is_err()
        );
        assert!(load_profile_source(&engine, "p.rhai", "fn profile() { #{ extra: 1 } }").is_err());
    }

    #[test]
    fn rule_ids_round_trip_and_unknown_ids_are_rejected() {
        for rule in AuditRule::ALL {
            assert_eq!(AuditRule::parse(rule.id()), Some(rule));
        }
        assert_eq!(
            AuditRules::from_ids(["row-height-mismatch", "nope"]),
            Err("nope".to_owned())
        );
        assert!(AuditRules::default().is_empty());
        assert!(AuditRules::all().contains(AuditRule::LowContrastText));
    }
}