Skip to main content

devela/sys/os/term/
pen.rs

1// devela/src/sys/os/term/pen.rs
2//
3//! Defines [`TermPen`].
4//
5
6use crate::{TermColor, TermColors, TermStyle, Termel};
7
8#[doc = crate::_tags!(term text color)]
9/// Reusable terminal style and colors for constructing elements.
10#[doc = crate::_doc_meta!{
11    location("sys/os/term/grid"),
12    test_size_of(__: TermPen<devela::TermStyle, devela::TermColors> = 16|128)
13}]
14#[must_use]
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
16pub struct TermPen<S = TermStyle, C = TermColors> {
17    style: S,
18    colors: C,
19}
20
21impl TermPen {
22    /// A pen with no styles and terminal-default colors.
23    pub const PLAIN: Self = Self::new(TermStyle::new(), TermColors::DEFAULT);
24}
25#[rustfmt::skip]
26impl<S, C> TermPen<S, C> {
27    /// Creates a terminal pen from its style and colors.
28    pub const fn new(style: S, colors: C) -> Self {
29        Self { style, colors }
30    }
31    /// Returns the style.
32    #[must_use]
33    pub const fn style(&self) -> &S { &self.style }
34    /// Returns the colors.
35    #[must_use]
36    pub const fn colors(&self) -> &C { &self.colors }
37
38    /// Returns this pen with its style replaced.
39    pub const fn with_style<U>(self, style: U) -> TermPen<U, C> where Self: Copy {
40        TermPen::new(style, self.colors)
41    }
42    /// Returns this pen with its colors replaced.
43    pub const fn with_colors<U>(self, colors: U) -> TermPen<S, U> where Self: Copy {
44        TermPen::new(self.style, colors)
45    }
46
47    /// Replaces the style.
48    pub const fn set_style(&mut self, style: S) where S: Copy { self.style = style; }
49    /// Replaces the colors.
50    pub const fn set_colors(&mut self, colors: C) where C: Copy { self.colors = colors; }
51
52    /// Creates a terminal element using this pen.
53    pub const fn termel<T>(self, value: T) -> Termel<T, S, C> where Self: Copy {
54        Termel::from_value(value, self.style, self.colors)
55    }
56}
57
58/// # Methods from TermColors
59#[rustfmt::skip]
60impl<S> TermPen<S, TermColors> {
61    /// Returns the foreground color.
62    pub const fn fg(self) -> TermColor where Self: Copy { self.colors.fg() }
63    /// Returns the the background color.
64    pub const fn bg(self) -> TermColor where Self: Copy { self.colors.bg() }
65
66    /// Replaces the foreground color.
67    pub const fn with_fg(self, fg: TermColor) -> TermPen<S, TermColors> where Self: Copy {
68        TermPen::new(self.style, self.colors.with_fg(fg))
69    }
70    /// Replaces the background color.
71    pub const fn with_bg(self, bg: TermColor) -> TermPen<S, TermColors> where Self: Copy {
72        TermPen::new(self.style, self.colors.with_bg(bg))
73    }
74}