1use std::path::{Path, PathBuf};
4
5use toml_edit::{InlineTable, Item, TableLike, Value};
6
7use crate::{operation::OperationOptions, Result, Text, Theme};
8
9use super::{
10 codec::{field, invalid, Codec},
11 Recipe,
12};
13
14pub enum StyleSource<'a> {
16 Recipe(&'a Recipe),
18 Path(PathBuf),
20}
21
22impl<'a> From<&'a Recipe> for StyleSource<'a> {
23 fn from(recipe: &'a Recipe) -> Self {
24 Self::Recipe(recipe)
25 }
26}
27
28macro_rules! style_paths {
29 ($($ty:ty),+ $(,)?) => {$(
30 impl From<$ty> for StyleSource<'_> {
31 fn from(path: $ty) -> Self {
32 Self::Path(PathBuf::from(path))
33 }
34 }
35 )+};
36}
37style_paths!(&str, String, &String, &Path, PathBuf, &PathBuf);
38
39impl StyleSource<'_> {
40 pub(crate) fn with_recipe<T>(self, apply: impl FnOnce(&Recipe) -> Result<T>) -> Result<T> {
41 match self {
42 Self::Recipe(recipe) => apply(recipe),
43 Self::Path(path) => apply(&Recipe::read_document(&path)?),
44 }
45 }
46}
47
48pub(crate) fn is_style(item: &Item) -> bool {
49 item.get("scope").and_then(Item::as_str) == Some("style")
50}
51
52pub(crate) fn style_theme(
53 fields: &dyn TableLike,
54 root: bool,
55) -> Result<Option<std::sync::Arc<Theme>>> {
56 let theme = fields
57 .get("theme")
58 .map(|item| Theme::decode(item, None))
59 .transpose()?;
60 if root && theme.is_none() {
61 return Err(invalid(
62 "a style root requires its effective complete theme",
63 ));
64 }
65 Ok(theme.map(std::sync::Arc::new))
66}
67
68pub(crate) fn capture_text(text: &Text) -> Value {
69 text.appearance_only().encode()
70}
71
72const STYLE_TEXT_FIELDS: &[super::schema::Field] = &[
73 super::schema::optional::<crate::theme::TextTheme>("style"),
74 super::schema::optional::<crate::text::TextLayout>("layout"),
75];
76pub(crate) fn text_schema(ctx: &mut super::schema::Schema) -> serde_json::Value {
77 ctx.named("TextStyle", |ctx| {
78 super::schema::record(ctx, STYLE_TEXT_FIELDS)
79 })
80}
81
82pub(crate) fn read_text(item: &Item) -> Result<Text> {
83 super::schema::record_fields(item, STYLE_TEXT_FIELDS)?;
84 Text::decode(item, None)
85}
86
87pub(crate) fn text_field(fields: &dyn TableLike, name: &str) -> Result<Text> {
88 fields
89 .get(name)
90 .map(read_text)
91 .transpose()
92 .map(|value| value.unwrap_or(Text::UNSET))
93 .map_err(|error| error.with_prefix(name))
94}
95
96pub(crate) fn copy_fields(
97 source: &dyn TableLike,
98 target: &mut InlineTable,
99 names: &[&str],
100) -> Result<()> {
101 for &name in names {
102 if let Some(item) = source.get(name) {
103 target.insert(
104 name,
105 item.clone()
106 .into_value()
107 .map_err(|_| invalid("empty declaration field"))?,
108 );
109 }
110 }
111 Ok(())
112}
113
114pub(crate) fn project_text(
115 source: &dyn TableLike,
116 target: &mut InlineTable,
117 names: &[&str],
118) -> Result<()> {
119 for &name in names {
120 if let Some(text) = source.get(name) {
121 target.insert(name, capture_text(&Text::decode(text, None)?));
122 }
123 }
124 Ok(())
125}
126
127pub(crate) fn effective_theme(fields: &dyn TableLike, parent: Option<&Theme>) -> Result<Theme> {
128 if let Some(theme) = field::<Option<Theme>>(fields, "theme", Some(None))? {
129 return Ok(theme);
130 }
131 if let Some(theme) = parent {
132 return Ok(theme.clone());
133 }
134 Ok(field::<Option<Theme>>(fields, "default_theme", Some(None))?
135 .unwrap_or_else(Theme::publication))
136}
137
138pub(crate) fn project_existing_style(
139 item: &Item,
140 parent: Option<&Theme>,
141 root: bool,
142) -> Result<InlineTable> {
143 let fields = item
144 .as_table_like()
145 .ok_or_else(|| invalid("expected a style owner"))?;
146 let Value::InlineTable(mut value) = item
147 .clone()
148 .into_value()
149 .map_err(|_| invalid("invalid style owner"))?
150 else {
151 return Err(invalid("expected a style table"));
152 };
153 if root {
154 value.insert("theme", effective_theme(fields, parent)?.encode());
155 }
156 Ok(value)
157}
158
159impl Recipe {
160 pub fn style(&self) -> Result<Self> {
162 self.style_with_operation(&OperationOptions::default())
163 }
164
165 pub fn style_with_operation(&self, options: &OperationOptions) -> Result<Self> {
167 crate::operation::run(options, || self.project_style_root())
168 }
169
170 fn project_style_root(&self) -> Result<Self> {
171 let registry = super::resolve::Registry::read(self.document.get("bindings"))?;
172 let document = self.expanded_document(®istry)?;
173 let (root, value) = if let Some(plot) = document.get("plot") {
174 (
175 "plot",
176 crate::builder::recipe::style::project(plot, None, true)?,
177 )
178 } else if let Some(canvas) = document.get("canvas") {
179 ("canvas", crate::canvas::style::project(canvas, None, true)?)
180 } else {
181 return Err(invalid("recipe has no native Plot or Canvas style root"));
182 };
183 Self::from_capture(root, value, super::capture::Capture::new())
184 }
185
186 pub fn style_in(&self, owner: impl Into<crate::layout::PanelPath>) -> Result<Self> {
189 self.style_in_with_operation(owner, &OperationOptions::default())
190 }
191
192 pub fn style_in_with_operation(
194 &self,
195 owner: impl Into<crate::layout::PanelPath>,
196 options: &OperationOptions,
197 ) -> Result<Self> {
198 crate::operation::run(options, || {
199 let owner = owner.into();
200 if owner.is_root() {
201 return self.project_style_root();
202 }
203 let registry = super::resolve::Registry::read(self.document.get("bindings"))?;
204 let document = self.expanded_document(®istry)?;
205 let canvas = document
206 .get("canvas")
207 .and_then(Item::as_table_like)
208 .ok_or_else(|| invalid("a selected grid style requires a Canvas declaration"))?;
209 let panel = style_panel(canvas, &owner)?;
210 let plot = panel.get("plot").ok_or_else(|| {
211 invalid("selected panel has no independently declared Plot style")
212 })?;
213 let parent = effective_theme(canvas, None)?;
214 let value = crate::builder::recipe::style::project(plot, Some(&parent), true)?;
215 Self::from_capture("plot", value, super::capture::Capture::new())
216 })
217 }
218
219 pub(crate) fn style_root(&self, root: &str) -> Result<&Item> {
220 self.document
221 .get(root)
222 .filter(|item| is_style(item))
223 .ok_or_else(|| {
224 invalid(format!(
225 "apply_style requires a {root} recipe with scope=\"style\""
226 ))
227 })
228 }
229
230 pub(crate) fn has_style_root(&self) -> bool {
231 ["plot", "canvas"]
232 .iter()
233 .filter_map(|root| self.document.get(root))
234 .any(is_style)
235 }
236}
237
238fn style_panel(canvas: &dyn TableLike, owner: &crate::layout::PanelPath) -> Result<Item> {
239 use crate::layout::PanelStep;
240 let [step] = owner.steps() else {
241 return Err(invalid("style selection requires a direct Canvas panel"));
242 };
243 let Some(panels) = canvas.get("panels") else {
244 return Err(invalid("Canvas has no declared panel styles"));
245 };
246 let mut matched = None;
247 for item in super::codec::array_items(panels)? {
248 crate::operation::check()?;
249 let equal = match step {
250 PanelStep::Named(name) => {
251 item.get("name").and_then(Item::as_str) == Some(name.as_str())
252 }
253 PanelStep::Cell(row, column) => {
254 let coordinate = |key: &str| {
255 item.get(key)
256 .and_then(Item::as_integer)
257 .and_then(|value| usize::try_from(value).ok())
258 };
259 coordinate("row") == Some(*row) && coordinate("column") == Some(*column)
260 }
261 _ => return Err(invalid("style selection requires a direct Canvas panel")),
262 };
263 if equal && matched.replace(item.clone()).is_some() {
264 return Err(invalid("ambiguous style panel address"));
265 }
266 }
267 matched.ok_or_else(|| invalid(format!("no declared style owner at {owner:?}")))
268}
269
270impl<K: crate::kind::Marker> crate::Plot<K> {
271 pub fn apply_style<'a>(self, source: impl Into<StyleSource<'a>>) -> Result<Self> {
274 self.apply_style_with_operation(source, &OperationOptions::default())
275 }
276
277 pub fn apply_style_with_operation<'a>(
279 mut self,
280 source: impl Into<StyleSource<'a>>,
281 options: &OperationOptions,
282 ) -> Result<Self> {
283 crate::operation::run(options, || {
284 source.into().with_recipe(|recipe| {
285 crate::builder::recipe::style::apply_plot_recipe(&mut self, recipe)
286 })?;
287 crate::operation::checkpoint()?;
288 Ok(self)
289 })
290 }
291}