diff options
| author | 魏曹先生 <1992414357@qq.com> | 2026-08-15 19:51:27 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2026-08-15 19:51:27 +0800 |
| commit | 046ac064b6f4790f9053ad1e6109843bb38f89dd (patch) | |
| tree | 80c16af0d217f69001b3fad7a02dea49c2a3aebc /mingling/src/res | |
| parent | aa2b0daa88089df32b3ea67d7c1831b5d8fd64f8 (diff) | |
feat: move OSC94 under its own module and add confirmer predicates
Extract OSC94 state and guard types from `res` into a dedicated
`osc94` module, and add `ConfirmerCount` and `ConfirmerPredicate`
types with `YesConfirm` and `TrueConfirm` implementations.
Diffstat (limited to 'mingling/src/res')
| -rw-r--r-- | mingling/src/res/confirmer.rs | 108 | ||||
| -rw-r--r-- | mingling/src/res/osc94.rs | 205 | ||||
| -rw-r--r-- | mingling/src/res/osc94/state.rs | 74 |
3 files changed, 17 insertions, 370 deletions
diff --git a/mingling/src/res/confirmer.rs b/mingling/src/res/confirmer.rs index d92e2a0..146a2e8 100644 --- a/mingling/src/res/confirmer.rs +++ b/mingling/src/res/confirmer.rs @@ -1,5 +1,7 @@ use std::io::{BufRead, Write}; +use crate::confirm::{ConfirmerCount, ConfirmerPredicate}; + /// A confirmer for interactive confirmation. /// /// This structure caches the confirmed state to avoid repeated prompts. @@ -23,7 +25,8 @@ use std::io::{BufRead, Write}; /// # Examples /// /// ``` -/// use mingling::res::{Confirmer, YesConfirm}; +/// use mingling::res::Confirmer; +/// use mingling::confirm::YesConfirm; /// /// // In actual use, obtain the registered confirmer through the resource injection system /// let confirmer = Confirmer::new_confirmed(); @@ -57,7 +60,8 @@ impl Confirmer { /// # Examples /// /// ``` - /// use mingling::res::{Confirmer, YesConfirm}; + /// use mingling::res::Confirmer; + /// use mingling::confirm::YesConfirm; /// /// let confirmer = Confirmer::new_confirmed(); /// assert!(confirmer.ask::<YesConfirm>("Continue? [y/n] ")); @@ -76,7 +80,8 @@ impl Confirmer { /// # Examples /// /// ``` - /// use mingling::res::{Confirmer, YesConfirm}; + /// use mingling::res::Confirmer; + /// use mingling::confirm::YesConfirm; /// /// let mut confirmer = Confirmer::new(); /// confirmer.set_confirmed(); @@ -103,7 +108,8 @@ impl Confirmer { /// # Examples /// /// ``` - /// use mingling::res::{Confirmer, YesConfirm}; + /// use mingling::res::Confirmer; + /// use mingling::confirm::YesConfirm; /// /// let confirmer = Confirmer::new_confirmed(); /// let confirmed = confirmer.ask::<YesConfirm>("Delete this file? [y/n] "); @@ -135,7 +141,8 @@ impl Confirmer { /// # Examples /// /// ``` - /// use mingling::res::{Confirmer, YesConfirm}; + /// use mingling::res::Confirmer; + /// use mingling::confirm::YesConfirm; /// /// let confirmer = Confirmer::new_confirmed(); /// let confirmed = confirmer.try_ask::<YesConfirm>("Confirm execution? [y/n] ", 3); @@ -175,94 +182,3 @@ impl Confirmer { } } } - -/// Specifies the maximum number of attempts for a confirmation prompt. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ConfirmerCount { - /// Loop indefinitely until the user gives a parseable answer. - Loop, - /// Ask at most the specified number of times. - Max(usize), -} - -macro_rules! impl_from_for_confirmer_count { - ($($t:ty),*) => { - $( - impl From<$t> for ConfirmerCount { - fn from(n: $t) -> Self { - if n == 0 { - ConfirmerCount::Loop - } else { - match usize::try_from(n) { - Ok(max) => ConfirmerCount::Max(max), - Err(_) => ConfirmerCount::Max(usize::MAX), - } - } - } - } - )* - }; -} - -impl_from_for_confirmer_count!( - i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize -); - -/// Defines how to parse user confirmation input. -/// -/// A type implementing this trait determines which user input strings are treated as "yes" or "no". -pub trait ConfirmerPredicate { - /// Parses the user's input string, returning whether it is "yes". - /// - /// Returns `Some(true)` for yes, `Some(false)` for no, - /// and `None` if the input cannot be parsed (requiring re-entry). - fn is_yes(str: &str) -> Option<bool>; -} - -/// A `ConfirmerPredicate` implementation that accepts "y"/"yes" as yes and "n"/"no" as no. -/// -/// Input comparison is case-insensitive and automatically trims leading/trailing whitespace. -/// -/// # Examples -/// -/// ``` -/// use mingling::res::{Confirmer, YesConfirm}; -/// -/// let confirmer = Confirmer::default(); -/// let confirmed = confirmer.ask::<YesConfirm>("Continue? [y/n] "); -/// ``` -pub struct YesConfirm; - -/// A `ConfirmerPredicate` implementation that accepts "true"/"t" as yes and "false"/"f" as no. -/// -/// Input comparison is case-insensitive and automatically trims leading/trailing whitespace. -/// -/// # Examples -/// -/// ``` -/// use mingling::res::{Confirmer, TrueConfirm}; -/// -/// let confirmer = Confirmer::default(); -/// let confirmed = confirmer.ask::<TrueConfirm>("Enable this feature? [true/false] "); -/// ``` -pub struct TrueConfirm; - -impl ConfirmerPredicate for YesConfirm { - fn is_yes(str: &str) -> Option<bool> { - match str.trim().to_lowercase().as_str() { - "y" | "yes" => Some(true), - "n" | "no" => Some(false), - _ => None, - } - } -} - -impl ConfirmerPredicate for TrueConfirm { - fn is_yes(str: &str) -> Option<bool> { - match str.trim().to_lowercase().as_str() { - "true" | "t" => Some(true), - "false" | "f" => Some(false), - _ => None, - } - } -} diff --git a/mingling/src/res/osc94.rs b/mingling/src/res/osc94.rs index 3c80290..8e03b21 100644 --- a/mingling/src/res/osc94.rs +++ b/mingling/src/res/osc94.rs @@ -1,5 +1,4 @@ -mod state; -pub use state::*; +use crate::osc94::{OSC94Guard, OSC94State}; /// Process `OSC 9;4` status. /// @@ -25,7 +24,8 @@ pub use state::*; /// # Example /// /// ``` -/// use mingling::res::{OSC94, OSC94State}; +/// use mingling::res::OSC94; +/// use mingling::osc94::OSC94State; /// /// let osc94 = OSC94::default(); /// let mut guard = osc94.get_mut(); @@ -52,7 +52,8 @@ impl OSC94 { /// # Example /// /// ``` - /// use mingling::res::{OSC94, OSC94State}; + /// use mingling::res::OSC94; + /// use mingling::osc94::OSC94State; /// /// let osc94 = OSC94::default(); /// let guard = osc94.get_mut(); @@ -66,199 +67,3 @@ impl OSC94 { } } } - -/// A guard for modifying process state. -/// -/// Obtained via [`OSC94::get_mut`]. When the guard is dropped, the process state is -/// automatically restored to `OS94State::Clean`, so no manual cleanup is needed. -/// -/// # Example -/// -/// Create a guard via [`OSC94`], and the state is automatically restored to Clean -/// when the guard is dropped: -/// -/// ``` -/// use mingling::res::OSC94; -/// -/// let osc94 = OSC94::default(); -/// { -/// let mut guard = osc94.get_mut(); -/// guard.set_progress(0.5); -/// // When leaving this scope, the guard is dropped and the process state is automatically restored to Clean -/// } -/// ``` -pub struct OSC94Guard { - pub(crate) is_support: bool, - msg: OSC94State, -} - -impl OSC94Guard { - /// Set the process state to Clean. - /// - /// Indicates that the process has finished or is in a normal, problem-free state. - /// - /// # Example - /// - /// ``` - /// use mingling::res::{OSC94, OSC94State}; - /// - /// let osc94 = OSC94::default(); - /// let mut guard = osc94.get_mut(); - /// guard.set_progress(0.5); - /// guard.set_clean_state(); - /// assert_eq!(guard.state(), OSC94State::Clean); - /// ``` - pub fn set_clean_state(&mut self) { - self.msg = OSC94State::Clean; - if self.is_support { - self.msg.send(); - } - } - - /// Set the process state to Error. - /// - /// Indicates that an error occurred during process execution. - /// - /// # Example - /// - /// ``` - /// use mingling::res::{OSC94, OSC94State}; - /// - /// let osc94 = OSC94::default(); - /// let mut guard = osc94.get_mut(); - /// guard.set_error_state(); - /// assert_eq!(guard.state(), OSC94State::Error); - /// ``` - pub fn set_error_state(&mut self) { - self.msg = OSC94State::Error; - if self.is_support { - self.msg.send(); - } - } - - /// Set the process state to Warn. - /// - /// Indicates that a warning occurred during process execution, but it has not - /// reached the level of an error. - /// - /// # Example - /// - /// ``` - /// use mingling::res::{OSC94, OSC94State}; - /// - /// let osc94 = OSC94::default(); - /// let mut guard = osc94.get_mut(); - /// guard.set_warn_state(); - /// assert_eq!(guard.state(), OSC94State::Warn); - /// ``` - pub fn set_warn_state(&mut self) { - self.msg = OSC94State::Warn; - if self.is_support { - self.msg.send(); - } - } - - /// Set the process state to Unknown. - /// - /// Indicates that the process state cannot be determined or has not been defined. - /// - /// # Example - /// - /// ``` - /// use mingling::res::{OSC94, OSC94State}; - /// - /// let osc94 = OSC94::default(); - /// let mut guard = osc94.get_mut(); - /// guard.set_unknown_state(); - /// assert_eq!(guard.state(), OSC94State::Unknown); - /// ``` - pub fn set_unknown_state(&mut self) { - self.msg = OSC94State::Unknown; - if self.is_support { - self.msg.send(); - } - } - - /// Set the progress of the process. - /// - /// The `progress` parameter should be between `0.0` and `1.0`. `0.0` indicates - /// the start of the task, and `1.0` indicates the completion of the task. - /// Values outside this range are not clamped, but it is recommended to keep them - /// within this range. - /// - /// # Parameters - /// - /// * `progress` - The progress value, ranging from `0.0` to `1.0`. - /// - /// # Example - /// - /// ``` - /// use mingling::res::OSC94; - /// - /// let osc94 = OSC94::default(); - /// let mut guard = osc94.get_mut(); - /// guard.set_progress(0.5); - /// assert_eq!(guard.progress(), 0.5); - /// ``` - pub fn set_progress(&mut self, progress: f32) { - self.msg = OSC94State::Normal(progress); - if self.is_support { - self.msg.send(); - } - } - - /// Get the current process state. - /// - /// # Returns - /// - /// Returns the current [`OSC94State`] value, representing the state of the process. - /// - /// # Example - /// - /// ``` - /// use mingling::res::{OSC94, OSC94State}; - /// - /// let osc94 = OSC94::default(); - /// let guard = osc94.get_mut(); - /// assert_eq!(guard.state(), OSC94State::Clean); - /// ``` - #[must_use] - pub const fn state(&self) -> OSC94State { - self.msg - } - - /// Get the current progress value. - /// - /// Returns the actual progress value only when the state is [`OSC94State::Normal`]; - /// otherwise returns `0.0`. - /// - /// # Returns - /// - /// Returns an `f32` progress value, ranging from `0.0` to `1.0`. - /// - /// # Example - /// - /// ``` - /// use mingling::res::OSC94; - /// - /// let osc94 = OSC94::default(); - /// let mut guard = osc94.get_mut(); - /// guard.set_progress(0.25); - /// assert_eq!(guard.progress(), 0.25); - /// ``` - #[must_use] - pub const fn progress(&self) -> f32 { - match self.msg { - OSC94State::Normal(progress) => progress, - _ => 0.0, - } - } -} - -impl Drop for OSC94Guard { - fn drop(&mut self) { - if self.is_support { - OSC94State::Clean.send(); - } - } -} diff --git a/mingling/src/res/osc94/state.rs b/mingling/src/res/osc94/state.rs deleted file mode 100644 index c3d2bdf..0000000 --- a/mingling/src/res/osc94/state.rs +++ /dev/null @@ -1,74 +0,0 @@ -/// `OSC 9;4` 协议消息 -/// -/// 用于通过 ANSI 转义序列向终端发送任务进度通知消息 -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum OSC94State { - /// 清除/隐藏进度(任务完成时使用),对应状态码 `0` - Clean, - /// 正常状态,对应状态码 `1`,需要配合进度值(0-100) - Normal(f32), - /// 错误状态,对应状态码 `2`(通常显示为红色) - Error, - /// 不确定状态,对应状态码 `3`(显示为无限循环的动画,用于进度未知的任务) - Unknown, - /// 警告状态,对应状态码 `4`(通常显示为黄色) - Warn, -} - -impl OSC94State { - /// Returns the state code for the `OSC 9;4` protocol. - #[must_use] - pub const fn state_code(&self) -> u8 { - match self { - Self::Clean => 0, - Self::Normal(_) => 1, - Self::Error => 2, - Self::Unknown => 3, - Self::Warn => 4, - } - } - - /// Returns the progress value (0-100) for the `Normal` state, clamped to the valid range. - #[must_use] - pub const fn progress(&self) -> f32 { - match self { - Self::Normal(progress) => (progress.clamp(0.0, 1.0) * 100.0).round(), - _ => 0.0, - } - } - - /// Converts the message into the corresponding `OSC 9;4` escape sequence string. - #[must_use] - pub fn to_escape_sequence(&self) -> String { - format!("\x1b]9;4;{};{}\x07", self.state_code(), self.progress()) - } - - /// Sends the OSC 9;4 message to the terminal via stdout. - /// - /// # Panics - /// - /// Panics if the stdout stream cannot be flushed. - pub fn send(&self) { - use std::io::Write; - print!("{}", self.to_escape_sequence()); - std::io::stdout().flush().unwrap(); - } -} - -impl std::fmt::Display for OSC94State { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.to_escape_sequence()) - } -} - -impl From<OSC94State> for String { - fn from(msg: OSC94State) -> Self { - msg.to_escape_sequence() - } -} - -impl From<&OSC94State> for String { - fn from(msg: &OSC94State) -> Self { - msg.to_escape_sequence() - } -} |
