notcurses/color/
palette.rs

1// notcurses::color::palette
2//
3//!
4//
5
6use crate::{
7    color::{Channel, Rgb},
8    error::NotcursesResult as Result,
9    sys::{NcChannel, NcPalette},
10    Notcurses,
11};
12
13/// An array of 256 [`Channel`]s.
14#[derive(Clone, PartialEq, Eq)]
15pub struct Palette {
16    nc: *mut NcPalette,
17}
18
19mod core_impls {
20    use super::{NcPalette, Palette};
21    use core::fmt;
22
23    impl Drop for Palette {
24        fn drop(&mut self) {
25            if crate::Notcurses::is_initialized() {
26                self.into_ref_mut().free()
27            }
28        }
29    }
30
31    impl fmt::Debug for Palette {
32        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33            write!(
34                f,
35                "Palette {{ {:?}, {:?}, {:?}, … }}",
36                self.get_channel(0),
37                self.get_channel(1),
38                self.get_channel(2),
39            )
40        }
41    }
42
43    impl From<&mut NcPalette> for Palette {
44        fn from(ncplane: &mut NcPalette) -> Palette {
45            Palette {
46                nc: ncplane as *mut NcPalette,
47            }
48        }
49    }
50}
51
52/// # constructors & desconstructors
53impl Palette {
54    /// Creates a new palette, that's initialized with our best
55    /// knowledge of the currently configured palette.
56    pub fn new(terminal: &Notcurses) -> Palette {
57        terminal.with_nc_mut(|nc| Self {
58            nc: NcPalette::new(nc),
59        })
60    }
61
62    //
63
64    /// Returns a shared reference to the inner [`NcPalette`].
65    pub fn into_ref(&self) -> &NcPalette {
66        unsafe { &*self.nc }
67    }
68
69    /// Returns an exclusive reference to the inner [`NcPalette`].
70    pub fn into_ref_mut(&mut self) -> &mut NcPalette {
71        unsafe { &mut *self.nc }
72    }
73}
74
75/// # methods
76impl Palette {
77    /// Attempts to use this palette in the `terminal`.
78    pub fn use_in(&self, terminal: &Notcurses) -> Result<()> {
79        terminal.with_nc_mut(|nc| Ok(self.into_ref().r#use(nc)?))
80    }
81
82    /// Returns the `Rgb` value at `index`.
83    pub fn get(&self, index: impl Into<u8>) -> Rgb {
84        self.into_ref().get(index.into()).into()
85    }
86
87    /// Sets the `Rgb` value at `index`.
88    pub fn set(&mut self, index: impl Into<u8>, rgb: impl Into<Rgb>) {
89        self.into_ref_mut().set(index.into(), rgb.into());
90    }
91
92    /// Returns the channel at `index`.
93    pub fn get_channel(&self, index: impl Into<u8>) -> Channel {
94        NcChannel::from(self.into_ref().chans[index.into() as usize]).into()
95    }
96
97    /// Sets the `channel` value at `index`.
98    pub fn set_channel(&mut self, index: impl Into<u8>, channel: impl Into<Channel>) {
99        let ncc = NcChannel::from(channel.into());
100        self.into_ref_mut().chans[index.into() as usize] = ncc.into();
101    }
102}