1use std::fmt;
28
29use crate::artprov::IconRole;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
38pub struct ToolId(pub u64);
39
40impl ToolId {
41 pub const fn get(self) -> u64 {
43 self.0
44 }
45}
46
47impl fmt::Display for ToolId {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(f, "tool {}", self.0)
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
55pub enum ToolDisplay {
56 #[default]
59 IconAndText,
60 IconOnly,
62 TextOnly,
64}
65
66impl ToolDisplay {
67 pub const fn as_str(self) -> &'static str {
69 match self {
70 Self::IconAndText => "icon-and-text",
71 Self::IconOnly => "icon-only",
72 Self::TextOnly => "text-only",
73 }
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
79pub enum ToolbarOrientation {
80 #[default]
82 Horizontal,
83 Vertical,
85}
86
87impl ToolbarOrientation {
88 pub const fn as_str(self) -> &'static str {
90 match self {
91 Self::Horizontal => "horizontal",
92 Self::Vertical => "vertical",
93 }
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct ToolSpec {
100 pub id: ToolId,
102 pub label: String,
105 pub accessible_label: Option<String>,
112 pub tooltip: Option<String>,
114 pub icon: Option<IconRole>,
116 pub display: ToolDisplay,
118 pub enabled: bool,
121 pub visible: bool,
123 pub checkable: bool,
125 pub checked: bool,
127 pub radio_group: Option<ToolId>,
130 pub dropdown: bool,
133}
134
135impl ToolSpec {
136 pub fn new(id: ToolId, label: impl Into<String>) -> Self {
138 Self {
139 id,
140 label: label.into(),
141 accessible_label: None,
142 tooltip: None,
143 icon: None,
144 display: ToolDisplay::default(),
145 enabled: true,
146 visible: true,
147 checkable: false,
148 checked: false,
149 radio_group: None,
150 dropdown: false,
151 }
152 }
153
154 pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
156 self.tooltip = Some(tooltip.into());
157 self
158 }
159
160 pub fn with_accessible_label(mut self, label: impl Into<String>) -> Self {
163 self.accessible_label = Some(label.into());
164 self
165 }
166
167 pub fn accessible_name(&self) -> String {
180 if let Some(label) = self.accessible_label.as_deref().map(str::trim) {
181 if !label.is_empty() {
182 return label.to_owned();
183 }
184 }
185 let text = self.label.trim();
186 if !text.is_empty() {
187 return text.to_owned();
188 }
189 format!("tool {}", self.id.get())
190 }
191
192 pub fn with_icon(mut self, icon: IconRole) -> Self {
194 self.icon = Some(icon);
195 self
196 }
197
198 pub fn with_display(mut self, display: ToolDisplay) -> Self {
200 self.display = display;
201 self
202 }
203
204 pub fn with_enabled(mut self, enabled: bool) -> Self {
206 self.enabled = enabled;
207 self
208 }
209
210 pub fn with_visible(mut self, visible: bool) -> Self {
212 self.visible = visible;
213 self
214 }
215
216 pub fn with_checkable(mut self) -> Self {
218 self.checkable = true;
219 self
220 }
221
222 pub fn with_checked(mut self, checked: bool) -> Self {
224 self.checked = checked;
225 self
226 }
227
228 pub fn with_radio_group(mut self, owner: ToolId) -> Self {
230 self.radio_group = Some(owner);
231 self.checkable = true;
232 self
233 }
234
235 pub fn with_dropdown(mut self) -> Self {
237 self.dropdown = true;
238 self
239 }
240}
241
242#[derive(Debug, Clone, PartialEq, Eq)]
244pub enum ToolbarItem {
245 Tool(ToolSpec),
247 Separator,
249}
250
251impl ToolbarItem {
252 pub fn tool(id: ToolId, label: impl Into<String>) -> Self {
254 Self::Tool(ToolSpec::new(id, label))
255 }
256
257 pub const fn separator() -> Self {
259 Self::Separator
260 }
261
262 pub fn tool_spec(&self) -> Option<&ToolSpec> {
264 match self {
265 Self::Tool(tool) => Some(tool),
266 Self::Separator => None,
267 }
268 }
269
270 pub fn tool_spec_mut(&mut self) -> Option<&mut ToolSpec> {
272 match self {
273 Self::Tool(tool) => Some(tool),
274 Self::Separator => None,
275 }
276 }
277
278 pub const fn is_separator(&self) -> bool {
280 matches!(self, Self::Separator)
281 }
282}
283
284#[derive(Debug, Clone, Default, PartialEq, Eq)]
290pub struct ToolUpdate {
291 pub label: Option<String>,
293 pub accessible_label: Option<String>,
295 pub tooltip: Option<String>,
297 pub icon: Option<IconRole>,
299 pub display: Option<ToolDisplay>,
301 pub enabled: Option<bool>,
303 pub visible: Option<bool>,
305 pub dropdown: Option<bool>,
307}
308
309impl ToolUpdate {
310 pub fn new() -> Self {
312 Self::default()
313 }
314
315 pub fn with_label(mut self, label: impl Into<String>) -> Self {
317 self.label = Some(label.into());
318 self
319 }
320
321 pub fn with_accessible_label(mut self, label: impl Into<String>) -> Self {
323 self.accessible_label = Some(label.into());
324 self
325 }
326
327 pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
329 self.tooltip = Some(tooltip.into());
330 self
331 }
332
333 pub fn with_icon(mut self, icon: IconRole) -> Self {
335 self.icon = Some(icon);
336 self
337 }
338
339 pub fn with_display(mut self, display: ToolDisplay) -> Self {
341 self.display = Some(display);
342 self
343 }
344
345 pub fn with_enabled(mut self, enabled: bool) -> Self {
347 self.enabled = Some(enabled);
348 self
349 }
350
351 pub fn with_visible(mut self, visible: bool) -> Self {
353 self.visible = Some(visible);
354 self
355 }
356
357 pub fn with_dropdown(mut self, dropdown: bool) -> Self {
359 self.dropdown = Some(dropdown);
360 self
361 }
362}
363
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367pub enum ToolbarError {
368 DuplicateToolId(ToolId),
370 UnknownRadioGroup(ToolId),
372 RadioGroupNotCheckable(ToolId),
375 UnknownTool(ToolId),
377 NotCheckable(ToolId),
379}
380
381impl fmt::Display for ToolbarError {
382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 match self {
384 Self::DuplicateToolId(id) => write!(f, "duplicate toolbar tool id {id}"),
385 Self::UnknownRadioGroup(id) => write!(
386 f,
387 "radio group {id} is not an existing checkable tool (removing a group owner \
388 requires reassigning or clearing the group in the replacement list)"
389 ),
390 Self::RadioGroupNotCheckable(id) => {
391 write!(f, "radio group owner {id} is not checkable")
392 }
393 Self::UnknownTool(id) => write!(f, "unknown toolbar {id}"),
394 Self::NotCheckable(id) => write!(f, "{id} is not checkable"),
395 }
396 }
397}
398
399impl std::error::Error for ToolbarError {}
400
401#[derive(Debug, Clone, PartialEq, Eq)]
404pub enum ToolInteraction {
405 Activated(ToolId),
407 Dropdown(ToolId),
410 Toggled(Vec<(ToolId, bool)>),
414 Ignored(ToolId),
416}
417
418pub fn find_tool(items: &[ToolbarItem], id: ToolId) -> Option<&ToolSpec> {
420 items.iter().find_map(|item| match item {
421 ToolbarItem::Tool(tool) if tool.id == id => Some(tool),
422 _ => None,
423 })
424}
425
426pub fn find_tool_mut(items: &mut [ToolbarItem], id: ToolId) -> Option<&mut ToolSpec> {
428 items.iter_mut().find_map(|item| match item {
429 ToolbarItem::Tool(tool) if tool.id == id => Some(tool),
430 _ => None,
431 })
432}
433
434pub fn validate_toolbar_items(items: &[ToolbarItem]) -> Result<(), ToolbarError> {
440 let mut seen: Vec<ToolId> = Vec::with_capacity(items.len());
441 for item in items {
442 let Some(tool) = item.tool_spec() else {
443 continue;
444 };
445 if seen.contains(&tool.id) {
446 return Err(ToolbarError::DuplicateToolId(tool.id));
447 }
448 seen.push(tool.id);
449 }
450 for item in items {
451 let Some(tool) = item.tool_spec() else {
452 continue;
453 };
454 if let Some(group) = tool.radio_group {
455 match find_tool(items, group) {
456 None => return Err(ToolbarError::UnknownRadioGroup(group)),
457 Some(owner) if !owner.checkable => {
458 return Err(ToolbarError::RadioGroupNotCheckable(group));
459 }
460 Some(_) => {}
461 }
462 }
463 }
464 Ok(())
465}
466
467pub fn set_tool_state(
475 items: &mut [ToolbarItem],
476 id: ToolId,
477 checked: bool,
478) -> Result<Vec<(ToolId, bool)>, ToolbarError> {
479 let target = find_tool(items, id).ok_or(ToolbarError::UnknownTool(id))?;
480 if !target.checkable {
481 return Err(ToolbarError::NotCheckable(id));
482 }
483 let group = target.radio_group;
484
485 let before: Vec<(ToolId, bool)> = items
486 .iter()
487 .filter_map(|item| item.tool_spec().map(|tool| (tool.id, tool.checked)))
488 .collect();
489
490 for item in items.iter_mut() {
491 let Some(tool) = item.tool_spec_mut() else {
492 continue;
493 };
494 if tool.id == id {
495 tool.checked = checked;
496 } else if checked && group.is_some() && tool.radio_group == group {
497 tool.checked = false;
498 }
499 }
500
501 Ok(state_changes(items, &before))
502}
503
504pub fn click_tool(items: &mut [ToolbarItem], id: ToolId) -> Result<ToolInteraction, ToolbarError> {
512 let tool = find_tool(items, id).ok_or(ToolbarError::UnknownTool(id))?;
513 if !tool.enabled || !tool.visible {
514 return Ok(ToolInteraction::Ignored(id));
515 }
516 if tool.dropdown {
517 return Ok(ToolInteraction::Dropdown(id));
518 }
519 if tool.checkable {
520 let next = !tool.checked;
521 let changes = set_tool_state(items, id, next)?;
522 return Ok(ToolInteraction::Toggled(changes));
523 }
524 Ok(ToolInteraction::Activated(id))
525}
526
527pub fn apply_tool_update(
533 items: &mut [ToolbarItem],
534 id: ToolId,
535 update: &ToolUpdate,
536) -> Result<(), ToolbarError> {
537 let tool = find_tool_mut(items, id).ok_or(ToolbarError::UnknownTool(id))?;
538 if let Some(label) = &update.label {
539 tool.label = label.clone();
540 }
541 if let Some(accessible_label) = &update.accessible_label {
542 tool.accessible_label = Some(accessible_label.clone());
543 }
544 if let Some(tooltip) = &update.tooltip {
545 tool.tooltip = Some(tooltip.clone());
546 }
547 if let Some(icon) = update.icon {
548 tool.icon = Some(icon);
549 }
550 if let Some(display) = update.display {
551 tool.display = display;
552 }
553 if let Some(enabled) = update.enabled {
554 tool.enabled = enabled;
555 }
556 if let Some(visible) = update.visible {
557 tool.visible = visible;
558 }
559 if let Some(dropdown) = update.dropdown {
560 tool.dropdown = dropdown;
561 }
562 Ok(())
563}
564
565fn state_changes(items: &[ToolbarItem], before: &[(ToolId, bool)]) -> Vec<(ToolId, bool)> {
567 let mut changes = Vec::new();
568 for item in items {
569 let Some(tool) = item.tool_spec() else {
570 continue;
571 };
572 let previous = before
573 .iter()
574 .find_map(|(id, checked)| (*id == tool.id).then_some(*checked));
575 if previous != Some(tool.checked) {
576 changes.push((tool.id, tool.checked));
577 }
578 }
579 changes
580}
581
582#[cfg(test)]
583mod tests {
584 use super::*;
585
586 fn sample() -> Vec<ToolbarItem> {
587 vec![
588 ToolbarItem::Tool(ToolSpec::new(ToolId(1), "New").with_icon(IconRole::New)),
589 ToolbarItem::tool(ToolId(2), "Open"),
590 ToolbarItem::Separator,
591 ToolbarItem::Tool(ToolSpec::new(ToolId(10), "Left").with_radio_group(ToolId(10))),
592 ToolbarItem::Tool(ToolSpec::new(ToolId(11), "Center").with_radio_group(ToolId(10))),
593 ToolbarItem::Tool(ToolSpec::new(ToolId(12), "Right").with_radio_group(ToolId(10))),
594 ToolbarItem::Tool(ToolSpec::new(ToolId(20), "Bold").with_checkable()),
595 ToolbarItem::Tool(ToolSpec::new(ToolId(30), "Layout").with_dropdown()),
596 ]
597 }
598
599 #[test]
600 fn defaults_are_enabled_visible_and_icon_and_text() {
601 let tool = ToolSpec::new(ToolId(7), "Save");
602 assert!(tool.enabled);
603 assert!(tool.visible);
604 assert!(!tool.checkable);
605 assert!(!tool.checked);
606 assert!(!tool.dropdown);
607 assert_eq!(tool.radio_group, None);
608 assert_eq!(tool.display, ToolDisplay::IconAndText);
609 assert_eq!(tool.accessible_label, None);
610 assert_eq!(tool.accessible_name(), "Save");
611 assert_eq!(
612 ToolbarOrientation::default(),
613 ToolbarOrientation::Horizontal
614 );
615 }
616
617 #[test]
618 fn validation_rejects_duplicate_ids_and_dangling_radio_groups() {
619 let duplicate = vec![
620 ToolbarItem::tool(ToolId(1), "A"),
621 ToolbarItem::tool(ToolId(1), "A again"),
622 ];
623 assert_eq!(
624 validate_toolbar_items(&duplicate),
625 Err(ToolbarError::DuplicateToolId(ToolId(1)))
626 );
627
628 let dangling = vec![ToolbarItem::Tool(
629 ToolSpec::new(ToolId(2), "B").with_radio_group(ToolId(1)),
630 )];
631 assert_eq!(
632 validate_toolbar_items(&dangling),
633 Err(ToolbarError::UnknownRadioGroup(ToolId(1)))
634 );
635
636 let not_checkable = vec![
637 ToolbarItem::tool(ToolId(1), "Owner"),
638 ToolbarItem::Tool(ToolSpec::new(ToolId(2), "Member").with_radio_group(ToolId(1))),
639 ];
640 assert_eq!(
643 validate_toolbar_items(¬_checkable),
644 Err(ToolbarError::RadioGroupNotCheckable(ToolId(1)))
645 );
646
647 assert_eq!(validate_toolbar_items(&sample()), Ok(()));
648 }
649
650 #[test]
651 fn programmatic_state_is_exclusive_and_silent() {
652 let mut items = sample();
653 let changes = set_tool_state(&mut items, ToolId(11), true).unwrap();
654 assert_eq!(changes, vec![(ToolId(11), true)]);
655
656 let changes = set_tool_state(&mut items, ToolId(12), true).unwrap();
658 assert_eq!(changes, vec![(ToolId(11), false), (ToolId(12), true)]);
659 assert!(!find_tool(&items, ToolId(10)).unwrap().checked);
660
661 assert_eq!(set_tool_state(&mut items, ToolId(12), true), Ok(vec![]));
663
664 let changes = set_tool_state(&mut items, ToolId(20), true).unwrap();
666 assert_eq!(changes, vec![(ToolId(20), true)]);
667 assert_eq!(
668 set_tool_state(&mut items, ToolId(1), true),
669 Err(ToolbarError::NotCheckable(ToolId(1)))
670 );
671 assert_eq!(
672 set_tool_state(&mut items, ToolId(99), true),
673 Err(ToolbarError::UnknownTool(ToolId(99)))
674 );
675 }
676
677 #[test]
678 fn user_clicks_follow_the_documented_precedence() {
679 let mut items = sample();
680 assert_eq!(
681 click_tool(&mut items, ToolId(1)),
682 Ok(ToolInteraction::Activated(ToolId(1)))
683 );
684 assert_eq!(
685 click_tool(&mut items, ToolId(30)),
686 Ok(ToolInteraction::Dropdown(ToolId(30)))
687 );
688
689 assert_eq!(
692 click_tool(&mut items, ToolId(10)),
693 Ok(ToolInteraction::Toggled(vec![(ToolId(10), true)]))
694 );
695 assert_eq!(
696 click_tool(&mut items, ToolId(11)),
697 Ok(ToolInteraction::Toggled(vec![
698 (ToolId(10), false),
699 (ToolId(11), true)
700 ]))
701 );
702 assert_eq!(
704 click_tool(&mut items, ToolId(11)),
705 Ok(ToolInteraction::Toggled(vec![(ToolId(11), false)]))
706 );
707
708 find_tool_mut(&mut items, ToolId(1)).unwrap().enabled = false;
710 find_tool_mut(&mut items, ToolId(2)).unwrap().visible = false;
711 assert_eq!(
712 click_tool(&mut items, ToolId(1)),
713 Ok(ToolInteraction::Ignored(ToolId(1)))
714 );
715 assert_eq!(
716 click_tool(&mut items, ToolId(2)),
717 Ok(ToolInteraction::Ignored(ToolId(2)))
718 );
719
720 let mut both = vec![ToolbarItem::Tool(
722 ToolSpec::new(ToolId(3), "Both")
723 .with_checkable()
724 .with_dropdown(),
725 )];
726 assert_eq!(
727 click_tool(&mut both, ToolId(3)),
728 Ok(ToolInteraction::Dropdown(ToolId(3)))
729 );
730 }
731
732 #[test]
733 fn updates_patch_only_the_named_fields() {
734 let mut items = sample();
735 let update = ToolUpdate::new()
736 .with_label("New file")
737 .with_enabled(false)
738 .with_display(ToolDisplay::TextOnly);
739 apply_tool_update(&mut items, ToolId(1), &update).unwrap();
740
741 let tool = find_tool(&items, ToolId(1)).unwrap();
742 assert_eq!(tool.label, "New file");
743 assert!(!tool.enabled);
744 assert_eq!(tool.display, ToolDisplay::TextOnly);
745 assert_eq!(tool.icon, Some(IconRole::New));
746 assert_eq!(tool.tooltip, None);
747 assert_eq!(
748 apply_tool_update(&mut items, ToolId(99), &update),
749 Err(ToolbarError::UnknownTool(ToolId(99)))
750 );
751 }
752
753 #[test]
754 fn separators_are_not_tools() {
755 let items = sample();
756 let separators = items.iter().filter(|item| item.is_separator()).count();
757 assert_eq!(separators, 1);
758 assert_eq!(ToolbarItem::separator().tool_spec(), None);
759 }
760
761 #[test]
762 fn accessible_names_fall_back_from_explicit_label_to_text_to_a_stable_default() {
763 let icon_only = ToolSpec::new(ToolId(7), "").with_accessible_label("Bold");
765 assert_eq!(icon_only.accessible_name(), "Bold");
766
767 let plain = ToolSpec::new(ToolId(8), "Open");
769 assert_eq!(plain.label, "Open");
770 assert_eq!(plain.accessible_label, None);
771 assert_eq!(plain.accessible_name(), "Open");
772
773 let unlabelled = ToolSpec::new(ToolId(9), "");
776 assert_eq!(unlabelled.accessible_name(), "tool 9");
777
778 let blank = ToolSpec::new(ToolId(10), " ").with_accessible_label(" ");
780 assert_eq!(blank.accessible_name(), "tool 10");
781
782 let padded = ToolSpec::new(ToolId(11), " Save ");
784 assert_eq!(padded.accessible_name(), "Save");
785 }
786
787 #[test]
788 fn accessible_label_round_trips_through_the_update_path() {
789 let mut items = sample();
790 assert_eq!(
791 find_tool(&items, ToolId(1)).unwrap().accessible_name(),
792 "New"
793 );
794
795 let update = ToolUpdate::new().with_accessible_label("New document");
796 apply_tool_update(&mut items, ToolId(1), &update).unwrap();
797
798 let tool = find_tool(&items, ToolId(1)).unwrap();
799 assert_eq!(tool.accessible_label.as_deref(), Some("New document"));
800 assert_eq!(tool.accessible_name(), "New document");
801 assert_eq!(tool.label, "New", "the override is announce-only");
802
803 apply_tool_update(
805 &mut items,
806 ToolId(1),
807 &ToolUpdate::new().with_label("New file"),
808 )
809 .unwrap();
810 let tool = find_tool(&items, ToolId(1)).unwrap();
811 assert_eq!(tool.label, "New file");
812 assert_eq!(tool.accessible_name(), "New document");
813
814 apply_tool_update(
816 &mut items,
817 ToolId(1),
818 &ToolUpdate::new().with_enabled(false),
819 )
820 .unwrap();
821 let tool = find_tool(&items, ToolId(1)).unwrap();
822 assert_eq!(tool.accessible_label.as_deref(), Some("New document"));
823 assert_eq!(tool.accessible_name(), "New document");
824 assert!(!tool.enabled);
825 }
826}