use std::fmt;
use super::{KeySequence, When, WhenContext};
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CommandId(String);
impl CommandId {
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_valid(&self) -> bool {
!self.0.is_empty() && !self.0.chars().any(char::is_whitespace)
}
pub fn is_namespaced(&self) -> bool {
self.0.contains('.') && self.is_valid()
}
}
impl fmt::Display for CommandId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl From<&str> for CommandId {
fn from(id: &str) -> Self {
Self(id.to_owned())
}
}
impl From<String> for CommandId {
fn from(id: String) -> Self {
Self(id)
}
}
impl AsRef<str> for CommandId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for CommandId {
fn borrow(&self) -> &str {
&self.0
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for CommandId {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for CommandId {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
<String as serde::Deserialize>::deserialize(deserializer).map(Self)
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArgKind {
Text,
Number,
Choice(Vec<String>),
Path,
}
impl ArgKind {
pub fn label(&self) -> &'static str {
match self {
Self::Text => "text",
Self::Number => "number",
Self::Choice(_) => "choice",
Self::Path => "path",
}
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ArgSchema {
pub name: String,
pub prompt: String,
pub kind: ArgKind,
pub required: bool,
}
impl ArgSchema {
pub fn text(name: impl Into<String>, prompt: impl Into<String>) -> Self {
Self {
name: name.into(),
prompt: prompt.into(),
kind: ArgKind::Text,
required: true,
}
}
pub fn optional(mut self) -> Self {
self.required = false;
self
}
pub fn kind(mut self, kind: ArgKind) -> Self {
self.kind = kind;
self
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CommandState {
pub enabled: bool,
pub checked: bool,
}
impl Default for CommandState {
fn default() -> Self {
Self {
enabled: true,
checked: false,
}
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Command {
pub id: CommandId,
pub title: String,
pub category: String,
pub icon: Option<String>,
pub description: Option<String>,
pub keywords: Vec<String>,
pub default_shortcut: Option<KeySequence>,
pub when: When,
pub state: CommandState,
pub args: Option<ArgSchema>,
}
impl Command {
pub fn new(id: impl Into<CommandId>, title: impl Into<String>) -> Self {
Self {
id: id.into(),
title: title.into(),
category: "General".to_owned(),
icon: None,
description: None,
keywords: Vec::new(),
default_shortcut: None,
when: When::always(),
state: CommandState::default(),
args: None,
}
}
pub fn category(mut self, category: impl Into<String>) -> Self {
self.category = category.into();
self
}
pub fn icon(mut self, icon: impl Into<String>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn keywords(mut self, keywords: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.keywords.extend(keywords.into_iter().map(Into::into));
self
}
pub fn shortcut(mut self, shortcut: impl AsRef<str>) -> Self {
if let Some(sequence) = KeySequence::parse(shortcut.as_ref()) {
self.default_shortcut = Some(sequence);
}
self
}
pub fn try_shortcut(mut self, shortcut: impl AsRef<str>) -> Result<Self, BindingError> {
let text = shortcut.as_ref();
let sequence = KeySequence::parse(text).ok_or_else(|| BindingError::InvalidSequence(text.to_owned()))?;
self.default_shortcut = Some(sequence);
Ok(self)
}
pub fn when(mut self, when: impl AsRef<str>) -> Self {
if let Ok(when) = When::parse(when.as_ref()) {
self.when = when;
}
self
}
pub fn try_when(mut self, when: impl AsRef<str>) -> Result<Self, BindingError> {
self.when = When::parse(when.as_ref()).map_err(|error| BindingError::InvalidWhen(error.to_string()))?;
Ok(self)
}
pub fn args(mut self, schema: ArgSchema) -> Self {
self.args = Some(schema);
self
}
pub fn is_enabled(&self) -> bool {
self.state.enabled
}
pub fn is_checked(&self) -> bool {
self.state.checked
}
pub fn applies(&self, context: &WhenContext) -> bool {
self.when.evaluate(context)
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum BindingError {
#[error("unknown command `{0}`")]
UnknownCommand(CommandId),
#[error("`{0}` is not a valid key sequence")]
InvalidSequence(String),
#[error("invalid when expression: {0}")]
InvalidWhen(String),
#[error("{sequence} is already bound to `{existing}`")]
Conflict {
sequence: KeySequence,
existing: CommandId,
},
}