Skip to main content

uncurses/text/
pen.rs

1//! A pen combines visual style and an optional hyperlink for painted text.
2
3use std::sync::Arc;
4
5use crate::style::{Link, Style};
6
7/// Visual style and optional OSC 8 hyperlink for a text paint operation.
8///
9/// Use [`Pen::new`] to start empty, then add a style or a shared link with
10/// [`Pen::with_style`] and [`Pen::with_link`]. Any value that converts
11/// into [`Style`] also converts to `Pen`. [`Link`] and `Arc<Link>` values
12/// convert directly.
13///
14/// ```rust
15/// use std::sync::Arc;
16/// use uncurses::buffer::{Surface, TextBuffer};
17/// use uncurses::style::{Link, Style};
18/// use uncurses::text::{Pen, TextSurface};
19///
20/// let mut buffer = TextBuffer::new(8, 1);
21/// let link = Arc::new(Link {
22///     url: "https://example.test".into(),
23///     params: String::new(),
24/// });
25/// buffer.set_str(
26///     (0, 0),
27///     "docs",
28///     Pen::new()
29///         .with_style(Style::new().underline())
30///         .with_link(link),
31/// );
32/// assert_eq!(
33///     buffer.cell((0, 0).into()).unwrap().link().unwrap().url,
34///     "https://example.test"
35/// );
36/// ```
37#[derive(Debug, Default, Clone, PartialEq, Eq)]
38pub struct Pen {
39    /// Visual SGR state for painted cells.
40    pub style: Style,
41    /// Shared OSC 8 link for painted cells.
42    pub link: Option<Arc<Link>>,
43}
44
45impl Pen {
46    /// Create an empty pen.
47    pub fn new() -> Self {
48        Self::default()
49    }
50
51    /// Set the visual style and return this pen.
52    pub fn with_style(mut self, style: impl Into<Style>) -> Self {
53        self.style = style.into();
54        self
55    }
56
57    /// Attach a shared OSC 8 link and return this pen.
58    pub fn with_link(mut self, link: impl Into<Arc<Link>>) -> Self {
59        self.link = Some(link.into());
60        self
61    }
62}
63
64impl<T: Into<Style>> From<T> for Pen {
65    fn from(style: T) -> Self {
66        Self::new().with_style(style)
67    }
68}
69
70impl From<Link> for Pen {
71    fn from(link: Link) -> Self {
72        Self::new().with_link(link)
73    }
74}
75
76impl From<Arc<Link>> for Pen {
77    fn from(link: Arc<Link>) -> Self {
78        Self::new().with_link(link)
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    struct CustomStyle(Style);
87
88    impl From<CustomStyle> for Style {
89        fn from(style: CustomStyle) -> Self {
90            style.0
91        }
92    }
93
94    #[test]
95    fn custom_style_conversions_remain_valid_pens() {
96        let style = Style::new().bold();
97        let pen = Pen::from(CustomStyle(style));
98
99        assert_eq!(pen.style, style);
100        assert!(pen.link.is_none());
101    }
102}