use std::fmt;
use crate::artprov::IconRole;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ToolId(pub u64);
impl ToolId {
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)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ToolDisplay {
#[default]
IconAndText,
IconOnly,
TextOnly,
}
impl ToolDisplay {
pub const fn as_str(self) -> &'static str {
match self {
Self::IconAndText => "icon-and-text",
Self::IconOnly => "icon-only",
Self::TextOnly => "text-only",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ToolbarOrientation {
#[default]
Horizontal,
Vertical,
}
impl ToolbarOrientation {
pub const fn as_str(self) -> &'static str {
match self {
Self::Horizontal => "horizontal",
Self::Vertical => "vertical",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolSpec {
pub id: ToolId,
pub label: String,
pub accessible_label: Option<String>,
pub tooltip: Option<String>,
pub icon: Option<IconRole>,
pub display: ToolDisplay,
pub enabled: bool,
pub visible: bool,
pub checkable: bool,
pub checked: bool,
pub radio_group: Option<ToolId>,
pub dropdown: bool,
}
impl ToolSpec {
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,
}
}
pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
self.tooltip = Some(tooltip.into());
self
}
pub fn with_accessible_label(mut self, label: impl Into<String>) -> Self {
self.accessible_label = Some(label.into());
self
}
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())
}
pub fn with_icon(mut self, icon: IconRole) -> Self {
self.icon = Some(icon);
self
}
pub fn with_display(mut self, display: ToolDisplay) -> Self {
self.display = display;
self
}
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn with_visible(mut self, visible: bool) -> Self {
self.visible = visible;
self
}
pub fn with_checkable(mut self) -> Self {
self.checkable = true;
self
}
pub fn with_checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
pub fn with_radio_group(mut self, owner: ToolId) -> Self {
self.radio_group = Some(owner);
self.checkable = true;
self
}
pub fn with_dropdown(mut self) -> Self {
self.dropdown = true;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolbarItem {
Tool(ToolSpec),
Separator,
}
impl ToolbarItem {
pub fn tool(id: ToolId, label: impl Into<String>) -> Self {
Self::Tool(ToolSpec::new(id, label))
}
pub const fn separator() -> Self {
Self::Separator
}
pub fn tool_spec(&self) -> Option<&ToolSpec> {
match self {
Self::Tool(tool) => Some(tool),
Self::Separator => None,
}
}
pub fn tool_spec_mut(&mut self) -> Option<&mut ToolSpec> {
match self {
Self::Tool(tool) => Some(tool),
Self::Separator => None,
}
}
pub const fn is_separator(&self) -> bool {
matches!(self, Self::Separator)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolUpdate {
pub label: Option<String>,
pub accessible_label: Option<String>,
pub tooltip: Option<String>,
pub icon: Option<IconRole>,
pub display: Option<ToolDisplay>,
pub enabled: Option<bool>,
pub visible: Option<bool>,
pub dropdown: Option<bool>,
}
impl ToolUpdate {
pub fn new() -> Self {
Self::default()
}
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
pub fn with_accessible_label(mut self, label: impl Into<String>) -> Self {
self.accessible_label = Some(label.into());
self
}
pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
self.tooltip = Some(tooltip.into());
self
}
pub fn with_icon(mut self, icon: IconRole) -> Self {
self.icon = Some(icon);
self
}
pub fn with_display(mut self, display: ToolDisplay) -> Self {
self.display = Some(display);
self
}
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
self
}
pub fn with_visible(mut self, visible: bool) -> Self {
self.visible = Some(visible);
self
}
pub fn with_dropdown(mut self, dropdown: bool) -> Self {
self.dropdown = Some(dropdown);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolbarError {
DuplicateToolId(ToolId),
UnknownRadioGroup(ToolId),
RadioGroupNotCheckable(ToolId),
UnknownTool(ToolId),
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 {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolInteraction {
Activated(ToolId),
Dropdown(ToolId),
Toggled(Vec<(ToolId, bool)>),
Ignored(ToolId),
}
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,
})
}
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,
})
}
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(())
}
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))
}
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))
}
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(())
}
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))),
];
assert_eq!(
validate_toolbar_items(¬_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)]);
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);
assert_eq!(set_tool_state(&mut items, ToolId(12), true), Ok(vec![]));
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)))
);
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)
]))
);
assert_eq!(
click_tool(&mut items, ToolId(11)),
Ok(ToolInteraction::Toggled(vec![(ToolId(11), false)]))
);
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)))
);
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() {
let icon_only = ToolSpec::new(ToolId(7), "").with_accessible_label("Bold");
assert_eq!(icon_only.accessible_name(), "Bold");
let plain = ToolSpec::new(ToolId(8), "Open");
assert_eq!(plain.label, "Open");
assert_eq!(plain.accessible_label, None);
assert_eq!(plain.accessible_name(), "Open");
let unlabelled = ToolSpec::new(ToolId(9), "");
assert_eq!(unlabelled.accessible_name(), "tool 9");
let blank = ToolSpec::new(ToolId(10), " ").with_accessible_label(" ");
assert_eq!(blank.accessible_name(), "tool 10");
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");
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");
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);
}
}