use std::num::NonZeroU32;
use crate::{Border, ColorKind, PreserveAspect, validators::layers::BORDER_WIDTH};
use pyo3::{exceptions::PyValueError, prelude::*};
use serde_saphyr::options::DuplicateKeyPolicy;
mod background;
mod colors;
mod ellipse;
mod icon;
mod polygon;
mod rectangle;
mod size_offset;
mod typography;
#[pymethods]
impl Border {
#[new]
#[pyo3(
text_signature = "(color: ColorKind, width: int = 1) -> None",
signature = (color, width = 1)
)]
pub fn new(color: ColorKind, width: Option<u32>) -> PyResult<Self> {
let width = match width {
Some(w) => NonZeroU32::new(w).ok_or(PyValueError::new_err(
"Border.width must be greater than 0".to_string(),
))?,
None => BORDER_WIDTH,
};
Ok(Self { color, width })
}
#[getter]
pub fn width(&self) -> u32 {
self.width.get()
}
#[setter]
pub fn set_width(&mut self, width: u32) -> PyResult<()> {
self.width = NonZeroU32::new(width).ok_or(PyValueError::new_err(format!(
"Border.width must be greater than 0; got {width}"
)))?;
Ok(())
}
#[staticmethod]
pub fn from_yaml_str(yaml_str: String) -> PyResult<Self> {
serde_saphyr::from_str_with_options(
&yaml_str,
serde_saphyr::options! {
duplicate_keys: DuplicateKeyPolicy::LastWins,
},
)
.map_err(|e| PyValueError::new_err(e.to_string()))
}
#[staticmethod]
pub fn from_json_str(json_str: String) -> PyResult<Self> {
serde_json::from_str(&json_str).map_err(|e| PyValueError::new_err(e.to_string()))
}
pub fn as_json_str(&self) -> PyResult<String> {
serde_json::to_string(self).map_err(|e| PyValueError::new_err(e.to_string()))
}
pub fn as_yaml_str(&self) -> PyResult<String> {
serde_saphyr::to_string(self).map_err(|e| PyValueError::new_err(e.to_string()))
}
}
#[pymethods]
impl PreserveAspect {
#[staticmethod]
#[pyo3(
name = "from_string",
text_signature = "(Literal['false', 'width', 'height', 'true']) -> PreserveAspect"
)]
pub fn from_string_py(value: String) -> PreserveAspect {
Self::from_string(&value)
}
#[staticmethod]
pub fn from_yaml_str(yaml_str: String) -> PyResult<Self> {
serde_saphyr::from_str_with_options(
&yaml_str,
serde_saphyr::options! {
duplicate_keys: DuplicateKeyPolicy::LastWins,
},
)
.map_err(|e| PyValueError::new_err(e.to_string()))
}
#[staticmethod]
pub fn from_json_str(json_str: String) -> PyResult<Self> {
serde_json::from_str(&json_str).map_err(|e| PyValueError::new_err(e.to_string()))
}
pub fn as_json_str(&self) -> PyResult<String> {
serde_json::to_string(self).map_err(|e| PyValueError::new_err(e.to_string()))
}
pub fn as_yaml_str(&self) -> PyResult<String> {
serde_saphyr::to_string(self).map_err(|e| PyValueError::new_err(e.to_string()))
}
}