native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
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
//! Portable toolbar model.
//!
//! Shared, backend-agnostic model for `WidgetKind::Toolbar` per
//! `docs/widget-expansion-roadmap.md` §14: stable [`ToolId`]s that survive
//! rebuilds and reorders, separators, icon/text display modes, checkable and
//! exclusive radio tools, dropdown tools, and the pure rules every lane must
//! agree on.
//!
//! The rules are functions, not a second state store: [`Ui`](crate::Ui) owns
//! the item list on the widget spec, applies these helpers, and forwards the
//! resulting list to the backend. Keeping them here means the Mock oracle and
//! the native toolbars cannot drift on the two behaviours that are easy to get
//! wrong:
//!
//! - **radio exclusivity** — checking one member of a group unchecks the other
//!   members, and a user toggle reports one `ToolToggled` per changed tool
//!   (never a single "group" event);
//! - **programmatic vs user edits** — [`set_tool_state`] is silent by design
//!   (no activation echo), while [`click_tool`] is the user path that produces
//!   the events.
//!
//! The native compositions (GTK `gtk::Box`, Win32 `TOOLBARCLASSNAME`, Cocoa
//! `NSToolbar`) land later; until then every backend refuses
//! the kind and the toolbar setters with the typed unsupported error instead
//! of faking a toolbar.

use std::fmt;

use crate::artprov::IconRole;

/// Stable, application-facing identifier of one toolbar tool.
///
/// The model never mints or reuses ids: applications own the values, and the
/// same id keeps referring to the same tool across [`ToolbarItem`] rebuilds
/// and reorders (`set_toolbar_items`), which is what lets an app map a
/// `ToolActivated` back to its own command without title matching.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ToolId(pub u64);

impl ToolId {
    /// The numeric value, for diagnostics and evidence dumps.
    pub const fn get(self) -> u64 {
        self.0
    }
}

impl fmt::Display for ToolId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "tool {}", self.0)
    }
}

/// How a tool presents its label and icon where the lane supports both.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ToolDisplay {
    /// Icon and text together (the default: neither is the only accessible
    /// name).
    #[default]
    IconAndText,
    /// Icon only; the label stays the accessible name and tooltip source.
    IconOnly,
    /// Text only, for lanes or tools without an icon.
    TextOnly,
}

impl ToolDisplay {
    /// Stable lowercase identifier used by tests and evidence dumps.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::IconAndText => "icon-and-text",
            Self::IconOnly => "icon-only",
            Self::TextOnly => "text-only",
        }
    }
}

/// Toolbar stacking orientation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ToolbarOrientation {
    /// Left-to-right (the default, and the only orientation Cocoa offers).
    #[default]
    Horizontal,
    /// Top-to-bottom; gated per lane by the `toolbar_vertical` capability.
    Vertical,
}

impl ToolbarOrientation {
    /// Stable lowercase identifier used by tests and evidence dumps.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Horizontal => "horizontal",
            Self::Vertical => "vertical",
        }
    }
}

/// One toolbar tool.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolSpec {
    /// Stable application-facing id.
    pub id: ToolId,
    /// Visible label (also the accessible name unless overridden by
    /// [`ToolSpec::accessible_label`]).
    pub label: String,
    /// Optional accessible name for assistive technology, for tools whose visible
    /// label is absent or not meaningful —
    /// most importantly icon-only tools. [`ToolSpec::accessible_name`]
    /// resolves the announcement as this value, else [`ToolSpec::label`],
    /// else a documented `tool <id>` default, so a tool never announces
    /// nothing.
    pub accessible_label: Option<String>,
    /// Optional tooltip/short help text.
    pub tooltip: Option<String>,
    /// Optional stock-art role; the artprov lane resolves it per DPI.
    pub icon: Option<IconRole>,
    /// Icon/text presentation preference.
    pub display: ToolDisplay,
    /// Whether the tool can be activated; disabled tools report as disabled
    /// rather than disappearing.
    pub enabled: bool,
    /// Whether the tool is shown. Hidden tools keep their id and state.
    pub visible: bool,
    /// Whether the tool carries a checked state (radio member or toggle).
    pub checkable: bool,
    /// Current checked state for checkable tools.
    pub checked: bool,
    /// Radio-group owner id: the id of the first tool of the group. Members
    /// share the same owner value, and checking one unchecks the rest.
    pub radio_group: Option<ToolId>,
    /// Whether activating the tool requests its dropdown menu (the app
    /// composes the menu with the existing menu API after `ToolDropdown`).
    pub dropdown: bool,
}

impl ToolSpec {
    /// Creates an enabled, visible, plain tool with the default display mode.
    pub fn new(id: ToolId, label: impl Into<String>) -> Self {
        Self {
            id,
            label: label.into(),
            accessible_label: None,
            tooltip: None,
            icon: None,
            display: ToolDisplay::default(),
            enabled: true,
            visible: true,
            checkable: false,
            checked: false,
            radio_group: None,
            dropdown: false,
        }
    }

    /// Sets the tooltip/short help text.
    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    /// Sets the assistive-technology name, overriding [`ToolSpec::label`] for
    /// icon-only or abbreviated tools.
    pub fn with_accessible_label(mut self, label: impl Into<String>) -> Self {
        self.accessible_label = Some(label.into());
        self
    }

    /// Resolves the name assistive technology should announce for this tool.
    ///
    /// The fallback order is fixed so every lane announces the same string:
    ///
    /// 1. [`ToolSpec::accessible_label`] when it is set and not blank;
    /// 2. otherwise [`ToolSpec::label`] when it is not blank — the visible
    ///    text doubles as the accessible name;
    /// 3. otherwise `tool <id>` (for example `tool 7`), so an icon-only tool
    ///    with no label still announces something stable and identifiable
    ///    instead of reaching a screen reader as an unlabelled control.
    ///
    /// The result is never empty.
    pub fn accessible_name(&self) -> String {
        if let Some(label) = self.accessible_label.as_deref().map(str::trim) {
            if !label.is_empty() {
                return label.to_owned();
            }
        }
        let text = self.label.trim();
        if !text.is_empty() {
            return text.to_owned();
        }
        format!("tool {}", self.id.get())
    }

    /// Sets the stock-art role.
    pub fn with_icon(mut self, icon: IconRole) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Sets the icon/text presentation preference.
    pub fn with_display(mut self, display: ToolDisplay) -> Self {
        self.display = display;
        self
    }

    /// Sets the enabled state.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Sets the visible state.
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// Makes the tool checkable.
    pub fn with_checkable(mut self) -> Self {
        self.checkable = true;
        self
    }

    /// Sets the initial checked state (only meaningful for checkable tools).
    pub fn with_checked(mut self, checked: bool) -> Self {
        self.checked = checked;
        self
    }

    /// Joins a radio group; `owner` is the id of the group's first member.
    pub fn with_radio_group(mut self, owner: ToolId) -> Self {
        self.radio_group = Some(owner);
        self.checkable = true;
        self
    }

    /// Marks the tool as a dropdown (menu) tool.
    pub fn with_dropdown(mut self) -> Self {
        self.dropdown = true;
        self
    }
}

/// One row of a toolbar.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolbarItem {
    /// A tool.
    Tool(ToolSpec),
    /// A separator gap between tools.
    Separator,
}

impl ToolbarItem {
    /// Convenience constructor for a plain tool.
    pub fn tool(id: ToolId, label: impl Into<String>) -> Self {
        Self::Tool(ToolSpec::new(id, label))
    }

    /// Convenience constructor for a separator.
    pub const fn separator() -> Self {
        Self::Separator
    }

    /// The tool when this row is one.
    pub fn tool_spec(&self) -> Option<&ToolSpec> {
        match self {
            Self::Tool(tool) => Some(tool),
            Self::Separator => None,
        }
    }

    /// Mutable access to the tool when this row is one.
    pub fn tool_spec_mut(&mut self) -> Option<&mut ToolSpec> {
        match self {
            Self::Tool(tool) => Some(tool),
            Self::Separator => None,
        }
    }

    /// Whether this row is a separator.
    pub const fn is_separator(&self) -> bool {
        matches!(self, Self::Separator)
    }
}

/// Partial in-place update applied by [`crate::Ui::update_tool`].
///
/// `None` leaves a field untouched; clearing a tooltip, icon, or accessible
/// label means sending a fresh [`ToolbarItem`] list instead (the model is a
/// full-list replacement).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolUpdate {
    /// New label.
    pub label: Option<String>,
    /// New assistive-technology name.
    pub accessible_label: Option<String>,
    /// New tooltip.
    pub tooltip: Option<String>,
    /// New stock-art role.
    pub icon: Option<IconRole>,
    /// New display mode.
    pub display: Option<ToolDisplay>,
    /// New enabled state.
    pub enabled: Option<bool>,
    /// New visible state.
    pub visible: Option<bool>,
    /// New dropdown flag.
    pub dropdown: Option<bool>,
}

impl ToolUpdate {
    /// An empty update (nothing changes).
    pub fn new() -> Self {
        Self::default()
    }

    /// Replaces the label.
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Replaces the assistive-technology name.
    pub fn with_accessible_label(mut self, label: impl Into<String>) -> Self {
        self.accessible_label = Some(label.into());
        self
    }

    /// Replaces the tooltip.
    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    /// Replaces the stock-art role.
    pub fn with_icon(mut self, icon: IconRole) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Replaces the display mode.
    pub fn with_display(mut self, display: ToolDisplay) -> Self {
        self.display = Some(display);
        self
    }

    /// Replaces the enabled state.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }

    /// Replaces the visible state.
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = Some(visible);
        self
    }

    /// Replaces the dropdown flag.
    pub fn with_dropdown(mut self, dropdown: bool) -> Self {
        self.dropdown = Some(dropdown);
        self
    }
}

/// A model rule violation, surfaced by the `Ui` setters as
/// [`GuiError::Backend`](crate::GuiError::Backend) with this message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolbarError {
    /// The same [`ToolId`] appears twice.
    DuplicateToolId(ToolId),
    /// A `radio_group` value does not match any tool in the list.
    UnknownRadioGroup(ToolId),
    /// The radio-group owner is not checkable, so the group cannot be
    /// exclusive.
    RadioGroupNotCheckable(ToolId),
    /// The requested tool id is not in the list.
    UnknownTool(ToolId),
    /// A checked state was set on a tool that is not checkable.
    NotCheckable(ToolId),
}

impl fmt::Display for ToolbarError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DuplicateToolId(id) => write!(f, "duplicate toolbar tool id {id}"),
            Self::UnknownRadioGroup(id) => write!(
                f,
                "radio group {id} is not an existing checkable tool (removing a group owner \
                 requires reassigning or clearing the group in the replacement list)"
            ),
            Self::RadioGroupNotCheckable(id) => {
                write!(f, "radio group owner {id} is not checkable")
            }
            Self::UnknownTool(id) => write!(f, "unknown toolbar {id}"),
            Self::NotCheckable(id) => write!(f, "{id} is not checkable"),
        }
    }
}

impl std::error::Error for ToolbarError {}

/// The events a user click on a tool produces, decided by the shared rules so
/// every lane reports the same interaction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolInteraction {
    /// A plain tool was activated: emit `ToolActivated`.
    Activated(ToolId),
    /// A dropdown tool was clicked: emit `ToolDropdown` (the menu itself is
    /// app-composed).
    Dropdown(ToolId),
    /// A checkable tool was toggled: emit one `ToolToggled` per entry, in
    /// toolbar order (radio exclusivity therefore produces at most one extra
    /// event for the member that was unchecked).
    Toggled(Vec<(ToolId, bool)>),
    /// A disabled or hidden tool consumed the click; nothing is emitted.
    Ignored(ToolId),
}

/// Finds a tool by id.
pub fn find_tool(items: &[ToolbarItem], id: ToolId) -> Option<&ToolSpec> {
    items.iter().find_map(|item| match item {
        ToolbarItem::Tool(tool) if tool.id == id => Some(tool),
        _ => None,
    })
}

/// Mutable lookup by id.
pub fn find_tool_mut(items: &mut [ToolbarItem], id: ToolId) -> Option<&mut ToolSpec> {
    items.iter_mut().find_map(|item| match item {
        ToolbarItem::Tool(tool) if tool.id == id => Some(tool),
        _ => None,
    })
}

/// Validates a toolbar item list.
///
/// Rules: tool ids are unique, and every `radio_group` refers to an existing
/// checkable tool (the group owner). Separators carry no state and are not
/// validated.
pub fn validate_toolbar_items(items: &[ToolbarItem]) -> Result<(), ToolbarError> {
    let mut seen: Vec<ToolId> = Vec::with_capacity(items.len());
    for item in items {
        let Some(tool) = item.tool_spec() else {
            continue;
        };
        if seen.contains(&tool.id) {
            return Err(ToolbarError::DuplicateToolId(tool.id));
        }
        seen.push(tool.id);
    }
    for item in items {
        let Some(tool) = item.tool_spec() else {
            continue;
        };
        if let Some(group) = tool.radio_group {
            match find_tool(items, group) {
                None => return Err(ToolbarError::UnknownRadioGroup(group)),
                Some(owner) if !owner.checkable => {
                    return Err(ToolbarError::RadioGroupNotCheckable(group));
                }
                Some(_) => {}
            }
        }
    }
    Ok(())
}

/// Applies a programmatic checked-state change.
///
/// This is the non-user path: it never emits activation events (the caller
/// decides whether anything should be reported), and checking a radio member
/// unchecks its group peers so the group stays exclusive. The return value
/// lists every tool whose state actually changed, in toolbar order (empty for
/// a no-op), which is what an application needs to update its own model.
pub fn set_tool_state(
    items: &mut [ToolbarItem],
    id: ToolId,
    checked: bool,
) -> Result<Vec<(ToolId, bool)>, ToolbarError> {
    let target = find_tool(items, id).ok_or(ToolbarError::UnknownTool(id))?;
    if !target.checkable {
        return Err(ToolbarError::NotCheckable(id));
    }
    let group = target.radio_group;

    let before: Vec<(ToolId, bool)> = items
        .iter()
        .filter_map(|item| item.tool_spec().map(|tool| (tool.id, tool.checked)))
        .collect();

    for item in items.iter_mut() {
        let Some(tool) = item.tool_spec_mut() else {
            continue;
        };
        if tool.id == id {
            tool.checked = checked;
        } else if checked && group.is_some() && tool.radio_group == group {
            tool.checked = false;
        }
    }

    Ok(state_changes(items, &before))
}

/// Applies a user click to the toolbar model.
///
/// Precedence per tool: a disabled or hidden tool consumes the click
/// ([`ToolInteraction::Ignored`]); a dropdown tool reports
/// [`ToolInteraction::Dropdown`]; a checkable tool toggles (with radio
/// exclusivity) and reports [`ToolInteraction::Toggled`]; anything else
/// reports [`ToolInteraction::Activated`].
pub fn click_tool(items: &mut [ToolbarItem], id: ToolId) -> Result<ToolInteraction, ToolbarError> {
    let tool = find_tool(items, id).ok_or(ToolbarError::UnknownTool(id))?;
    if !tool.enabled || !tool.visible {
        return Ok(ToolInteraction::Ignored(id));
    }
    if tool.dropdown {
        return Ok(ToolInteraction::Dropdown(id));
    }
    if tool.checkable {
        let next = !tool.checked;
        let changes = set_tool_state(items, id, next)?;
        return Ok(ToolInteraction::Toggled(changes));
    }
    Ok(ToolInteraction::Activated(id))
}

/// Applies a partial [`ToolUpdate`] to one tool.
///
/// `checked` is deliberately not part of the update: use
/// [`set_tool_state`] so radio exclusivity and the silent-programmatic rule
/// apply.
pub fn apply_tool_update(
    items: &mut [ToolbarItem],
    id: ToolId,
    update: &ToolUpdate,
) -> Result<(), ToolbarError> {
    let tool = find_tool_mut(items, id).ok_or(ToolbarError::UnknownTool(id))?;
    if let Some(label) = &update.label {
        tool.label = label.clone();
    }
    if let Some(accessible_label) = &update.accessible_label {
        tool.accessible_label = Some(accessible_label.clone());
    }
    if let Some(tooltip) = &update.tooltip {
        tool.tooltip = Some(tooltip.clone());
    }
    if let Some(icon) = update.icon {
        tool.icon = Some(icon);
    }
    if let Some(display) = update.display {
        tool.display = display;
    }
    if let Some(enabled) = update.enabled {
        tool.enabled = enabled;
    }
    if let Some(visible) = update.visible {
        tool.visible = visible;
    }
    if let Some(dropdown) = update.dropdown {
        tool.dropdown = dropdown;
    }
    Ok(())
}

/// Diffs the item list against its pre-edit state, in toolbar order.
fn state_changes(items: &[ToolbarItem], before: &[(ToolId, bool)]) -> Vec<(ToolId, bool)> {
    let mut changes = Vec::new();
    for item in items {
        let Some(tool) = item.tool_spec() else {
            continue;
        };
        let previous = before
            .iter()
            .find_map(|(id, checked)| (*id == tool.id).then_some(*checked));
        if previous != Some(tool.checked) {
            changes.push((tool.id, tool.checked));
        }
    }
    changes
}

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

    fn sample() -> Vec<ToolbarItem> {
        vec![
            ToolbarItem::Tool(ToolSpec::new(ToolId(1), "New").with_icon(IconRole::New)),
            ToolbarItem::tool(ToolId(2), "Open"),
            ToolbarItem::Separator,
            ToolbarItem::Tool(ToolSpec::new(ToolId(10), "Left").with_radio_group(ToolId(10))),
            ToolbarItem::Tool(ToolSpec::new(ToolId(11), "Center").with_radio_group(ToolId(10))),
            ToolbarItem::Tool(ToolSpec::new(ToolId(12), "Right").with_radio_group(ToolId(10))),
            ToolbarItem::Tool(ToolSpec::new(ToolId(20), "Bold").with_checkable()),
            ToolbarItem::Tool(ToolSpec::new(ToolId(30), "Layout").with_dropdown()),
        ]
    }

    #[test]
    fn defaults_are_enabled_visible_and_icon_and_text() {
        let tool = ToolSpec::new(ToolId(7), "Save");
        assert!(tool.enabled);
        assert!(tool.visible);
        assert!(!tool.checkable);
        assert!(!tool.checked);
        assert!(!tool.dropdown);
        assert_eq!(tool.radio_group, None);
        assert_eq!(tool.display, ToolDisplay::IconAndText);
        assert_eq!(tool.accessible_label, None);
        assert_eq!(tool.accessible_name(), "Save");
        assert_eq!(
            ToolbarOrientation::default(),
            ToolbarOrientation::Horizontal
        );
    }

    #[test]
    fn validation_rejects_duplicate_ids_and_dangling_radio_groups() {
        let duplicate = vec![
            ToolbarItem::tool(ToolId(1), "A"),
            ToolbarItem::tool(ToolId(1), "A again"),
        ];
        assert_eq!(
            validate_toolbar_items(&duplicate),
            Err(ToolbarError::DuplicateToolId(ToolId(1)))
        );

        let dangling = vec![ToolbarItem::Tool(
            ToolSpec::new(ToolId(2), "B").with_radio_group(ToolId(1)),
        )];
        assert_eq!(
            validate_toolbar_items(&dangling),
            Err(ToolbarError::UnknownRadioGroup(ToolId(1)))
        );

        let not_checkable = vec![
            ToolbarItem::tool(ToolId(1), "Owner"),
            ToolbarItem::Tool(ToolSpec::new(ToolId(2), "Member").with_radio_group(ToolId(1))),
        ];
        // `with_radio_group` marks the member checkable, but the owner is a
        // plain tool and cannot anchor an exclusive group.
        assert_eq!(
            validate_toolbar_items(&not_checkable),
            Err(ToolbarError::RadioGroupNotCheckable(ToolId(1)))
        );

        assert_eq!(validate_toolbar_items(&sample()), Ok(()));
    }

    #[test]
    fn programmatic_state_is_exclusive_and_silent() {
        let mut items = sample();
        let changes = set_tool_state(&mut items, ToolId(11), true).unwrap();
        assert_eq!(changes, vec![(ToolId(11), true)]);

        // Switching the group within the same call reports one uncheck.
        let changes = set_tool_state(&mut items, ToolId(12), true).unwrap();
        assert_eq!(changes, vec![(ToolId(11), false), (ToolId(12), true)]);
        assert!(!find_tool(&items, ToolId(10)).unwrap().checked);

        // A no-op reports nothing.
        assert_eq!(set_tool_state(&mut items, ToolId(12), true), Ok(vec![]));

        // Independent toggles are not part of any group.
        let changes = set_tool_state(&mut items, ToolId(20), true).unwrap();
        assert_eq!(changes, vec![(ToolId(20), true)]);
        assert_eq!(
            set_tool_state(&mut items, ToolId(1), true),
            Err(ToolbarError::NotCheckable(ToolId(1)))
        );
        assert_eq!(
            set_tool_state(&mut items, ToolId(99), true),
            Err(ToolbarError::UnknownTool(ToolId(99)))
        );
    }

    #[test]
    fn user_clicks_follow_the_documented_precedence() {
        let mut items = sample();
        assert_eq!(
            click_tool(&mut items, ToolId(1)),
            Ok(ToolInteraction::Activated(ToolId(1)))
        );
        assert_eq!(
            click_tool(&mut items, ToolId(30)),
            Ok(ToolInteraction::Dropdown(ToolId(30)))
        );

        // Radio: first click checks, second click checks the other member and
        // reports the uncheck as its own entry.
        assert_eq!(
            click_tool(&mut items, ToolId(10)),
            Ok(ToolInteraction::Toggled(vec![(ToolId(10), true)]))
        );
        assert_eq!(
            click_tool(&mut items, ToolId(11)),
            Ok(ToolInteraction::Toggled(vec![
                (ToolId(10), false),
                (ToolId(11), true)
            ]))
        );
        // Clicking the checked member clears the group.
        assert_eq!(
            click_tool(&mut items, ToolId(11)),
            Ok(ToolInteraction::Toggled(vec![(ToolId(11), false)]))
        );

        // Disabled and hidden tools consume the click silently.
        find_tool_mut(&mut items, ToolId(1)).unwrap().enabled = false;
        find_tool_mut(&mut items, ToolId(2)).unwrap().visible = false;
        assert_eq!(
            click_tool(&mut items, ToolId(1)),
            Ok(ToolInteraction::Ignored(ToolId(1)))
        );
        assert_eq!(
            click_tool(&mut items, ToolId(2)),
            Ok(ToolInteraction::Ignored(ToolId(2)))
        );

        // Dropdown wins over checkable.
        let mut both = vec![ToolbarItem::Tool(
            ToolSpec::new(ToolId(3), "Both")
                .with_checkable()
                .with_dropdown(),
        )];
        assert_eq!(
            click_tool(&mut both, ToolId(3)),
            Ok(ToolInteraction::Dropdown(ToolId(3)))
        );
    }

    #[test]
    fn updates_patch_only_the_named_fields() {
        let mut items = sample();
        let update = ToolUpdate::new()
            .with_label("New file")
            .with_enabled(false)
            .with_display(ToolDisplay::TextOnly);
        apply_tool_update(&mut items, ToolId(1), &update).unwrap();

        let tool = find_tool(&items, ToolId(1)).unwrap();
        assert_eq!(tool.label, "New file");
        assert!(!tool.enabled);
        assert_eq!(tool.display, ToolDisplay::TextOnly);
        assert_eq!(tool.icon, Some(IconRole::New));
        assert_eq!(tool.tooltip, None);
        assert_eq!(
            apply_tool_update(&mut items, ToolId(99), &update),
            Err(ToolbarError::UnknownTool(ToolId(99)))
        );
    }

    #[test]
    fn separators_are_not_tools() {
        let items = sample();
        let separators = items.iter().filter(|item| item.is_separator()).count();
        assert_eq!(separators, 1);
        assert_eq!(ToolbarItem::separator().tool_spec(), None);
    }

    #[test]
    fn accessible_names_fall_back_from_explicit_label_to_text_to_a_stable_default() {
        // 1. An explicit accessible label wins: the icon-only case.
        let icon_only = ToolSpec::new(ToolId(7), "").with_accessible_label("Bold");
        assert_eq!(icon_only.accessible_name(), "Bold");

        // 2. Without one, the visible text doubles as the accessible name.
        let plain = ToolSpec::new(ToolId(8), "Open");
        assert_eq!(plain.label, "Open");
        assert_eq!(plain.accessible_label, None);
        assert_eq!(plain.accessible_name(), "Open");

        // 3. An icon-only tool with neither still announces an identifiable,
        //    documented default instead of reaching AT unlabelled.
        let unlabelled = ToolSpec::new(ToolId(9), "");
        assert_eq!(unlabelled.accessible_name(), "tool 9");

        // 4. Blank strings count as absent and are never announced verbatim.
        let blank = ToolSpec::new(ToolId(10), "  ").with_accessible_label("   ");
        assert_eq!(blank.accessible_name(), "tool 10");

        // 5. Surrounding whitespace is trimmed from whatever is announced.
        let padded = ToolSpec::new(ToolId(11), "  Save  ");
        assert_eq!(padded.accessible_name(), "Save");
    }

    #[test]
    fn accessible_label_round_trips_through_the_update_path() {
        let mut items = sample();
        assert_eq!(
            find_tool(&items, ToolId(1)).unwrap().accessible_name(),
            "New"
        );

        let update = ToolUpdate::new().with_accessible_label("New document");
        apply_tool_update(&mut items, ToolId(1), &update).unwrap();

        let tool = find_tool(&items, ToolId(1)).unwrap();
        assert_eq!(tool.accessible_label.as_deref(), Some("New document"));
        assert_eq!(tool.accessible_name(), "New document");
        assert_eq!(tool.label, "New", "the override is announce-only");

        // Re-labelling leaves the explicit accessible name authoritative.
        apply_tool_update(
            &mut items,
            ToolId(1),
            &ToolUpdate::new().with_label("New file"),
        )
        .unwrap();
        let tool = find_tool(&items, ToolId(1)).unwrap();
        assert_eq!(tool.label, "New file");
        assert_eq!(tool.accessible_name(), "New document");

        // An unrelated update never clobbers the accessible name.
        apply_tool_update(
            &mut items,
            ToolId(1),
            &ToolUpdate::new().with_enabled(false),
        )
        .unwrap();
        let tool = find_tool(&items, ToolId(1)).unwrap();
        assert_eq!(tool.accessible_label.as_deref(), Some("New document"));
        assert_eq!(tool.accessible_name(), "New document");
        assert!(!tool.enabled);
    }
}