use super::action_id;
use super::Chord;
use crate::{context::invalid_value, Id, ImageSource};
use std::{fmt::Debug, hash::Hash};
#[derive(Clone, Debug)]
pub struct Action {
pub(crate) id: Id,
pub(crate) name: String,
pub(crate) title: String,
pub(crate) description: String,
pub(crate) group: String,
pub(crate) icon: Option<ImageSource>,
pub(crate) shortcuts: Vec<(Option<String>, Chord)>,
pub(crate) modal: bool,
}
impl Action {
pub fn new(id: impl Hash + Debug, title: impl Into<String>) -> Self {
let name = saved_name(&format!("{id:?}"));
Self {
id: action_id(&id),
name,
title: title.into(),
description: String::new(),
group: String::new(),
icon: None,
shortcuts: Vec::new(),
modal: false,
}
}
pub fn name(mut self, name: impl AsRef<str>) -> Self {
self.name = saved_name(name.as_ref());
self
}
#[track_caller]
pub fn shortcut(self, chord: impl Into<Chord>) -> Self {
self.bind(None, chord.into())
}
#[track_caller]
pub fn shortcut_in(self, context: impl Into<String>, chord: impl Into<Chord>) -> Self {
self.bind(Some(context.into()), chord.into())
}
#[track_caller]
fn bind(mut self, context: Option<String>, chord: Chord) -> Self {
if chord.is_empty() {
invalid_value(
"Action::shortcut",
format!("expected at least one key for \"{}\"; ignored", self.title),
);
} else {
self.shortcuts.push((context, chord));
}
self
}
pub fn group(mut self, group: impl Into<String>) -> Self {
self.group = group.into();
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = description.into();
self
}
pub fn icon(mut self, icon: impl Into<ImageSource>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn allowed_in_modal(mut self, allowed: bool) -> Self {
self.modal = allowed;
self
}
pub fn id(&self) -> Id {
self.id
}
pub fn title(&self) -> &str {
&self.title
}
pub fn saved_name(&self) -> &str {
&self.name
}
pub fn description_text(&self) -> &str {
&self.description
}
pub fn group_name(&self) -> &str {
&self.group
}
pub fn icon_source(&self) -> Option<&ImageSource> {
self.icon.as_ref()
}
pub fn is_allowed_in_modal(&self) -> bool {
self.modal
}
}
fn saved_name(text: &str) -> String {
text.trim_matches('"')
.chars()
.map(|c| {
if c.is_whitespace() || matches!(c, '=' | '@' | '#' | '"') {
'_'
} else {
c
}
})
.collect()
}