oxedyne/fe2o3/fe2o3_austenite/src/settings.rs
23.4 KiB, 71 runs
created by r1870400018:68734, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! The settings of `austenite watch` and `austenite build`. |
| 2 | //! |
| 3 | //! One file, `austenite.jdat`, sits beside the document root, the directory that holds `assets/`, and is |
| 4 | //! found by walking up from the source. It is a jdat map. Every key is optional, so an absent key takes its |
| 5 | //! default and a file written before a key existed still reads. The precedence is the built-in default, then |
| 6 | //! the file, then each `--set key=value` of the command line, in order, for the one run. |
| 7 | //! |
| 8 | //! A key that is not in [`KEYS`], a value of the wrong type and a value outside its range are each refused |
| 9 | //! by the key's full dotted name before anything compiles. So is a setting that nothing reads under the |
| 10 | //! chosen `colour.space`, and a profile that cannot be read or does not suit its role |
| 11 | //! ([`Settings::check_built`], [`Settings::pdf_options`]), rather than being ignored. |
| 12 | //! |
| 13 | //! Plain `austenite SOURCE.typ` reads one key of this file, `engine`, and nothing else: `"engine": "curated"` |
| 14 | //! sends that book back to the frozen curated reader (2026-10-11, FIRE-2), which `watch` and `build` refuse. |
| 15 | |
| 16 | use crate::emit::pdf::PdfOptions; |
| 17 | |
| 18 | use oxedyne_fe2o3_core::prelude::*; |
| 19 | use oxedyne_fe2o3_graphics::icc; |
| 20 | use oxedyne_fe2o3_graphics::icc::read::{ |
| 21 | Profile, |
| 22 | Space, |
| 23 | }; |
| 24 | use oxedyne_fe2o3_graphics::icc::transform::{ |
| 25 | bpc_forced, |
| 26 | Dev, |
| 27 | Intent, |
| 28 | Transform, |
| 29 | }; |
| 30 | use oxedyne_fe2o3_graphics::pdf::{ |
| 31 | Black, |
| 32 | ColourOut, |
| 33 | }; |
| 34 | use oxedyne_fe2o3_jdat::prelude::*; |
| 35 | |
| 36 | use std::collections::BTreeMap; |
| 37 | use std::path::{ |
| 38 | Path, |
| 39 | PathBuf, |
| 40 | }; |
| 41 | use std::sync::Arc; |
| 42 | |
| 43 | pub const FILE: &str = "austenite.jdat"; |
| 44 | |
| 45 | // What a key's value may be. |
| 46 | #[derive(Clone, Copy, Debug)] |
| 47 | enum Kind { |
| 48 | Bool, |
| 49 | Num(u64, u64), |
| 50 | Text, |
| 51 | List, |
| 52 | Pick(&'static [&'static str]), |
| 53 | } |
| 54 | |
| 55 | impl Kind { |
| 56 | fn say(&self) -> String { |
| 57 | match self { |
| 58 | Self::Bool => "true or false".to_string(), |
| 59 | Self::Num(lo, hi) => fmt!("a whole number from {} to {}", lo, hi), |
| 60 | Self::Text => "text".to_string(), |
| 61 | Self::List => "a list of text".to_string(), |
| 62 | Self::Pick(ws) => fmt!("one of {}", ws.iter().map(|w| fmt!("\"{}\"", w)).collect::<Vec<_>>().join(", ")), |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | const SPACES: &[&str] = &["native", "rgb", "cmyk", "grey"]; |
| 68 | const INTENTS: &[&str] = &["perceptual", "relative", "saturation", "absolute"]; |
| 69 | const BLACKS: &[&str] = &["k", "rich"]; |
| 70 | const VERSIONS: &[&str] = &["1.4", "1.5", "1.6", "1.7"]; |
| 71 | const DIAGS: &[&str] = &["errors", "summary"]; |
| 72 | const ENGINES: &[&str] = &["evaluator", "curated"]; |
| 73 | |
| 74 | // Every key, by its dotted path. |
| 75 | const KEYS: &[(&str, Kind)] = &[ |
| 76 | ("root", Kind::Text), |
| 77 | ("fonts", Kind::List), |
| 78 | ("document", Kind::Text), |
| 79 | ("output", Kind::Text), |
| 80 | ("strict", Kind::Bool), |
| 81 | ("diagnostics", Kind::Pick(DIAGS)), |
| 82 | ("engine", Kind::Pick(ENGINES)), |
| 83 | ("watch.poll_ms", Kind::Num(10, 60_000)), |
| 84 | ("watch.warm", Kind::Bool), |
| 85 | ("figs.dir", Kind::Text), |
| 86 | ("figs.render", Kind::Bool), |
| 87 | ("colour.space", Kind::Pick(SPACES)), |
| 88 | ("colour.rgb_profile", Kind::Text), |
| 89 | ("colour.grey_profile", Kind::Text), |
| 90 | ("colour.cmyk_profile", Kind::Text), |
| 91 | ("colour.intent", Kind::Pick(INTENTS)), |
| 92 | ("colour.black_point", Kind::Bool), |
| 93 | ("colour.black", Kind::Pick(BLACKS)), |
| 94 | ("metadata.document", Kind::Bool), |
| 95 | ("metadata.engine", Kind::Bool), |
| 96 | ("pdf.version", Kind::Pick(VERSIONS)), |
| 97 | ("pdf.compress", Kind::Bool), |
| 98 | ("pdf.outline", Kind::Bool), |
| 99 | ("view.open", Kind::Bool), |
| 100 | ("view.app", Kind::Text), |
| 101 | ]; |
| 102 | |
| 103 | #[derive(Clone, Debug, FromDatMap)] |
| 104 | pub struct Watch { |
| 105 | #[optional] pub poll_ms: u64, |
| 106 | #[optional] pub warm: bool, |
| 107 | } |
| 108 | |
| 109 | impl Default for Watch { |
| 110 | fn default() -> Self { Self { poll_ms: 200, warm: true } } |
| 111 | } |
| 112 | |
| 113 | #[derive(Clone, Debug, FromDatMap)] |
| 114 | pub struct Figs { |
| 115 | #[optional] pub dir: String, |
| 116 | #[optional] pub render: bool, |
| 117 | } |
| 118 | |
| 119 | impl Default for Figs { |
| 120 | fn default() -> Self { Self { dir: "figs".to_string(), render: true } } |
| 121 | } |
| 122 | |
| 123 | #[derive(Clone, Debug, FromDatMap)] |
| 124 | pub struct Colour { |
| 125 | #[optional] pub space: String, |
| 126 | #[optional] pub rgb_profile: String, |
| 127 | #[optional] pub grey_profile: String, |
| 128 | #[optional] pub cmyk_profile: String, |
| 129 | #[optional] pub intent: String, |
| 130 | #[optional] pub black_point: bool, |
| 131 | #[optional] pub black: String, |
| 132 | } |
| 133 | |
| 134 | impl Default for Colour { |
| 135 | fn default() -> Self { |
| 136 | Self { |
| 137 | space: "native".to_string(), |
| 138 | rgb_profile: "srgb".to_string(), |
| 139 | grey_profile: "sgray".to_string(), |
| 140 | cmyk_profile: "fogra39".to_string(), |
| 141 | intent: "perceptual".to_string(), |
| 142 | black_point: true, |
| 143 | black: "k".to_string(), |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | #[derive(Clone, Debug, Default, FromDatMap)] |
| 149 | pub struct Metadata { |
| 150 | #[optional] pub document: bool, |
| 151 | #[optional] pub engine: bool, |
| 152 | } |
| 153 | |
| 154 | #[derive(Clone, Debug, FromDatMap)] |
| 155 | pub struct Pdf { |
| 156 | #[optional] pub version: String, |
| 157 | #[optional] pub compress: bool, |
| 158 | #[optional] pub outline: bool, |
| 159 | } |
| 160 | |
| 161 | impl Default for Pdf { |
| 162 | fn default() -> Self { Self { version: "1.7".to_string(), compress: true, outline: true } } |
| 163 | } |
| 164 | |
| 165 | #[derive(Clone, Debug, FromDatMap)] |
| 166 | pub struct View { |
| 167 | #[optional] pub open: bool, |
| 168 | #[optional] pub app: String, |
| 169 | } |
| 170 | |
| 171 | impl Default for View { |
| 172 | fn default() -> Self { Self { open: true, app: "auto".to_string() } } |
| 173 | } |
| 174 | |
| 175 | /// Where a run's colour settings came from, so that a file setting a `--set` has made inapplicable is told |
| 176 | /// apart from one that is wrong where it stands. |
| 177 | #[derive(Clone, Debug, Default)] |
| 178 | pub struct Layers { |
| 179 | pub file: Option<(PathBuf, Colour)>, // the settings file and its colour settings before any `--set` |
| 180 | pub set: Vec<String>, // the dotted keys the `--set`s named |
| 181 | } |
| 182 | |
| 183 | /// The settings of a run. `root` and `document` are empty when unset. |
| 184 | #[derive(Clone, Debug, FromDatMap)] |
| 185 | pub struct Settings { |
| 186 | #[optional] pub root: String, |
| 187 | #[optional] pub fonts: Vec<String>, |
| 188 | #[optional] pub document: String, |
| 189 | #[optional] pub output: String, |
| 190 | #[optional] pub strict: bool, |
| 191 | #[optional] pub diagnostics: String, |
| 192 | #[optional] pub engine: String, // "curated" sends plain `austenite` back to the frozen book reader |
| 193 | #[skip] pub watch: Watch, |
| 194 | #[skip] pub figs: Figs, |
| 195 | #[skip] pub colour: Colour, |
| 196 | #[skip] pub metadata: Metadata, |
| 197 | #[skip] pub pdf: Pdf, |
| 198 | #[skip] pub view: View, |
| 199 | #[skip] pub layers: Layers, |
| 200 | } |
| 201 | |
| 202 | impl Default for Settings { |
| 203 | fn default() -> Self { |
| 204 | Self { |
| 205 | root: String::new(), |
| 206 | fonts: vec!["assets/fonts".to_string()], |
| 207 | document: String::new(), |
| 208 | output: "{stem}.pdf".to_string(), |
| 209 | strict: false, |
| 210 | diagnostics: "errors".to_string(), |
| 211 | engine: "evaluator".to_string(), |
| 212 | watch: Watch::default(), |
| 213 | figs: Figs::default(), |
| 214 | colour: Colour::default(), |
| 215 | metadata: Metadata::default(), |
| 216 | pdf: Pdf::default(), |
| 217 | view: View::default(), |
| 218 | layers: Layers::default(), |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // The entries of a map of either kind. |
| 224 | fn pairs(d: &Dat) -> Option<Vec<(&Dat, &Dat)>> { |
| 225 | match d { |
| 226 | Dat::Map(m) => Some(m.iter().collect()), |
| 227 | Dat::OrdMap(m) => Some(m.iter().map(|(k, v)| (k.dat(), v)).collect()), |
| 228 | _ => None, |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | fn key_of(path: &str) -> Option<Kind> { |
| 233 | KEYS.iter().find(|(p, _)| *p == path).map(|(_, k)| *k) |
| 234 | } |
| 235 | |
| 236 | // Does `path` name a group, a map of keys, and not a key? |
| 237 | fn is_group(path: &str) -> bool { |
| 238 | let dotted = fmt!("{}.", path); |
| 239 | KEYS.iter().any(|(p, _)| p.starts_with(&dotted)) |
| 240 | } |
| 241 | |
| 242 | // Does the value suit the kind, and lie in its range? |
| 243 | fn suits(path: &str, kind: Kind, v: &Dat) -> Outcome<()> { |
| 244 | let ok = match kind { |
| 245 | Kind::Bool => v.get_bool().is_some(), |
| 246 | Kind::Num(lo, hi) => v.get_u64().map(|n| n >= lo && n <= hi).unwrap_or(false), |
| 247 | Kind::Text => v.get_string().is_some(), |
| 248 | Kind::List => v.get_string_list().is_some(), |
| 249 | Kind::Pick(ws) => v.get_string().map(|s| ws.contains(&s.as_str())).unwrap_or(false), |
| 250 | }; |
| 251 | if ok { Ok(()) } else { |
| 252 | Err(err!("The setting '{}' must be {}, not {}.", path, kind.say(), shown(v); Input, Invalid)) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | // A value for an error message, short. |
| 257 | fn shown(v: &Dat) -> String { |
| 258 | match v { |
| 259 | Dat::Str(s) => fmt!("\"{}\"", s), |
| 260 | Dat::Bool(b) => fmt!("{}", b), |
| 261 | other => fmt!("{:?}", other), |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | // Every leaf of the map, as a dotted path, refusing a key that is unknown and a value that does not suit. |
| 266 | fn leaves<'a>(prefix: &str, d: &'a Dat, out: &mut Vec<(String, &'a Dat)>) -> Outcome<()> { |
| 267 | let entries = match pairs(d) { |
| 268 | Some(e) => e, |
| 269 | None => return Err(err!( |
| 270 | "The settings must be a map of keys, and '{}' is not one.", if prefix.is_empty() { "the file" } else { prefix }; |
| 271 | Input, Invalid)), |
| 272 | }; |
| 273 | for (k, v) in entries { |
| 274 | let name = match k { |
| 275 | Dat::Str(s) => s.clone(), |
| 276 | other => return Err(err!("A settings key must be text, not {:?}.", other; Input, Invalid)), |
| 277 | }; |
| 278 | let path = if prefix.is_empty() { name } else { fmt!("{}.{}", prefix, name) }; |
| 279 | if is_group(&path) { |
| 280 | res!(leaves(&path, v, out)); |
| 281 | continue; |
| 282 | } |
| 283 | match key_of(&path) { |
| 284 | Some(kind) => { |
| 285 | res!(suits(&path, kind, v)); |
| 286 | out.push((path, v)); |
| 287 | }, |
| 288 | None => return Err(err!( |
| 289 | "The setting '{}' is not one Austenite has. The keys are: {}.", |
| 290 | path, KEYS.iter().map(|(p, _)| *p).collect::<Vec<_>>().join(", "); Input, Invalid)), |
| 291 | } |
| 292 | } |
| 293 | Ok(()) |
| 294 | } |
| 295 | |
| 296 | // The sub-map at `name` of the top map, as a plain map. |
| 297 | fn group(top: &Dat, name: &str) -> DaticleMap { |
| 298 | let mut m = DaticleMap::new(); |
| 299 | if let Some(entries) = pairs(top) { |
| 300 | for (k, v) in entries { |
| 301 | if k == &Dat::Str(name.to_string()) { |
| 302 | if let Some(inner) = pairs(v) { |
| 303 | for (ik, iv) in inner { |
| 304 | m.insert(ik.clone(), iv.clone()); |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | m |
| 311 | } |
| 312 | |
| 313 | impl Settings { |
| 314 | /// Reads the settings from a decoded map, refusing what [`KEYS`] does not allow. |
| 315 | pub fn from_dat(top: &Dat) -> Outcome<Self> { |
| 316 | let mut seen = Vec::new(); |
| 317 | res!(leaves("", top, &mut seen)); |
| 318 | let mut flat = DaticleMap::new(); |
| 319 | if let Some(entries) = pairs(top) { |
| 320 | for (k, v) in entries { |
| 321 | flat.insert(k.clone(), v.clone()); |
| 322 | } |
| 323 | } |
| 324 | let mut s = res!(Settings::from_datmap(flat)); |
| 325 | s.watch = res!(Watch::from_datmap(group(top, "watch"))); |
| 326 | s.figs = res!(Figs::from_datmap(group(top, "figs"))); |
| 327 | s.colour = res!(Colour::from_datmap(group(top, "colour"))); |
| 328 | s.metadata = res!(Metadata::from_datmap(group(top, "metadata"))); |
| 329 | s.pdf = res!(Pdf::from_datmap(group(top, "pdf"))); |
| 330 | s.view = res!(View::from_datmap(group(top, "view"))); |
| 331 | Ok(s) |
| 332 | } |
| 333 | |
| 334 | /// The settings of one run: the defaults, then the file `file` when there is one, then each `--set`. |
| 335 | pub fn resolve(file: Option<&Path>, sets: &[String]) -> Outcome<Self> { |
| 336 | let mut top = Dat::Map(BTreeMap::new()); |
| 337 | let mut layers = Layers::default(); |
| 338 | if let Some(f) = file { |
| 339 | let text = res!(std::fs::read_to_string(f)); |
| 340 | if !text.trim().is_empty() { |
| 341 | top = match Dat::decode_string(text) { |
| 342 | Ok(d) => d, |
| 343 | Err(e) => return Err(err!(e, "The settings file {} cannot be read.", f.display(); Input, Invalid)), |
| 344 | }; |
| 345 | } |
| 346 | let mut seen = Vec::new(); |
| 347 | if let Err(e) = leaves("", &top, &mut seen) { |
| 348 | return Err(err!(e, "In the settings file {}.", f.display(); Input, Invalid)); |
| 349 | } |
| 350 | let alone = res!(Self::from_dat(&top)); |
| 351 | layers.file = Some((f.to_path_buf(), alone.colour)); |
| 352 | } |
| 353 | for set in sets { |
| 354 | let (path, val) = res!(parse_set(set)); |
| 355 | layers.set.push(path.clone()); |
| 356 | res!(top.map_put_dotted(&path, val)); |
| 357 | } |
| 358 | let mut s = res!(Self::from_dat(&top)); |
| 359 | s.layers = layers; |
| 360 | Ok(s) |
| 361 | } |
| 362 | |
| 363 | /// Refuses a setting that nothing would read, by the key's name, and a figures directory that nothing |
| 364 | /// would render. `doc_dir` is the document's own directory, where the figure sources would be. What comes |
| 365 | /// back is one line for each file setting that a `--set` made inapplicable, for the caller to print. |
| 366 | /// |
| 367 | /// The profiles, the intent and the black point apply when `colour.space` is `cmyk` or `grey`; the grey |
| 368 | /// profile only to `grey`, and the black only to `cmyk`. A value other than the default anywhere else |
| 369 | /// would be ignored, so it is refused when the settings file holds it beside a space that does not read |
| 370 | /// it, or when a `--set` gave it. A file setting that is inapplicable only because a `--set` changed |
| 371 | /// `colour.space` is not used for the run, and is told rather than refused. A black point the output |
| 372 | /// profile and intent override is refused when the profiles are read, in [`Settings::pdf_options`]. |
| 373 | pub fn check_built(&self, doc_dir: &Path) -> Outcome<Vec<String>> { |
| 374 | if let Some((path, alone)) = &self.layers.file { |
| 375 | if let Some((key, got, only)) = unread(alone).into_iter().next() { |
| 376 | return Err(err!( |
| 377 | "In the settings file {}, the setting '{}' = {} applies only when 'colour.space' is {}, and \ |
| 378 | the file makes it \"{}\".", path.display(), key, got, spaces(only), alone.space; Input, Invalid)); |
| 379 | } |
| 380 | } |
| 381 | let mut warned = Vec::new(); |
| 382 | for (key, got, only) in unread(&self.colour) { |
| 383 | if self.layers.file.is_some() && !self.layers.set.iter().any(|k| k == key) { |
| 384 | warned.push(fmt!( |
| 385 | "The setting '{}' = {} in the settings file applies only when 'colour.space' is {}, and a --set \ |
| 386 | makes it \"{}\", so it is not used for this run.", key, got, spaces(only), self.colour.space)); |
| 387 | } else { |
| 388 | return Err(err!( |
| 389 | "The setting '{}' = {} applies only when 'colour.space' is {}, and it is \"{}\".", |
| 390 | key, got, spaces(only), self.colour.space; Input, Invalid)); |
| 391 | } |
| 392 | } |
| 393 | if self.figs.render && doc_dir.join(&self.figs.dir).is_dir() { |
| 394 | return Err(err!( |
| 395 | "The setting 'figs.render' is on and the figures directory '{}' exists beside the document, but \ |
| 396 | figure rendering is not built yet. Set figs.render=false to go on.", self.figs.dir; Input, Invalid)); |
| 397 | } |
| 398 | Ok(warned) |
| 399 | } |
| 400 | |
| 401 | /// How the PDF is written under these settings. `base` is the directory the settings file is in, which a |
| 402 | /// relative profile path is taken from. |
| 403 | pub fn pdf_options(&self, base: &Path) -> Outcome<PdfOptions> { |
| 404 | let minor = match self.pdf.version.strip_prefix("1.").and_then(|m| m.parse::<u8>().ok()) { |
| 405 | Some(m) => m, |
| 406 | None => return Err(err!("The setting 'pdf.version' = \"{}\" is not 1.4 to 1.7.", self.pdf.version; Input, Invalid)), |
| 407 | }; |
| 408 | Ok(PdfOptions { |
| 409 | minor, |
| 410 | compress: self.pdf.compress, |
| 411 | outline: self.pdf.outline, |
| 412 | doc_info: self.metadata.document, |
| 413 | engine_info: self.metadata.engine, |
| 414 | colour: res!(self.colour_out(base)), |
| 415 | }) |
| 416 | } |
| 417 | |
| 418 | // The colour mode the settings ask for, with its transforms built. Each profile is read once, here. |
| 419 | fn colour_out(&self, base: &Path) -> Outcome<ColourOut> { |
| 420 | let c = &self.colour; |
| 421 | if c.space != "cmyk" && c.space != "grey" { |
| 422 | return Ok(if c.space == "rgb" { ColourOut::Rgb } else { ColourOut::Native }); |
| 423 | } |
| 424 | let intent = match c.intent.as_str() { |
| 425 | "perceptual" => Intent::Perceptual, |
| 426 | "relative" => Intent::Relative, |
| 427 | "saturation" => Intent::Saturation, |
| 428 | "absolute" => Intent::Absolute, |
| 429 | other => return Err(err!("The setting 'colour.intent' = \"{}\" is not an intent.", other; Input, Invalid)), |
| 430 | }; |
| 431 | let bpc = c.black_point; |
| 432 | let rgb = res!(device("colour.rgb_profile", &c.rgb_profile, Space::Rgb, base)); |
| 433 | // Every transform of a space ends in its own profile, so that profile and the intent alone say whether |
| 434 | // the black point setting is heard. Turned off where it is not, it is refused, as an ignored key is. |
| 435 | let unheard = |dst: &Dev, key: &str, name: &str| -> Outcome<()> { |
| 436 | match bpc_forced(dst, intent) { |
| 437 | Some(on) if bpc != Colour::default().black_point => Err(err!( |
| 438 | "The setting 'colour.black_point' = {} changes nothing at the intent \"{}\" into the profile of \ |
| 439 | '{}' (\"{}\"), which {}. Leave it at its default.", |
| 440 | bpc, c.intent, key, name, |
| 441 | if on { "always compensates (version 4, perceptual or saturation)" } else { "never compensates" }; |
| 442 | Input, Invalid)), |
| 443 | _ => Ok(()), |
| 444 | } |
| 445 | }; |
| 446 | let joined = |keys: &str, src: &Dev, dst: &Dev| -> Outcome<Arc<Transform>> { |
| 447 | match Transform::new(src, dst, intent, bpc) { |
| 448 | Ok(xf) => Ok(Arc::new(xf)), |
| 449 | Err(e) => Err(err!(e, "The profiles of {} cannot be joined at the intent \"{}\".", keys, c.intent; Input, Invalid)), |
| 450 | } |
| 451 | }; |
| 452 | if c.space == "cmyk" { |
| 453 | let cmyk = res!(device("colour.cmyk_profile", &c.cmyk_profile, Space::Cmyk, base)); |
| 454 | res!(unheard(&cmyk, "colour.cmyk_profile", &c.cmyk_profile)); |
| 455 | let xf = res!(joined("'colour.rgb_profile' and 'colour.cmyk_profile'", &rgb, &cmyk)); |
| 456 | let black = if c.black == "rich" { Black::Rich } else { Black::KOnly }; |
| 457 | ColourOut::cmyk(xf, black) |
| 458 | } else { |
| 459 | let grey = res!(device("colour.grey_profile", &c.grey_profile, Space::Gray, base)); |
| 460 | res!(unheard(&grey, "colour.grey_profile", &c.grey_profile)); |
| 461 | let cmyk = res!(device("colour.cmyk_profile", &c.cmyk_profile, Space::Cmyk, base)); |
| 462 | let xf = res!(joined("'colour.rgb_profile' and 'colour.grey_profile'", &rgb, &grey)); |
| 463 | let cx = res!(joined("'colour.cmyk_profile' and 'colour.grey_profile'", &cmyk, &grey)); |
| 464 | ColourOut::grey(xf, cx) |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | /// The finished PDF's path for `main`: `output` with `{stem}` filled in, beside the source unless absolute. |
| 469 | pub fn output_path(&self, main: &Path) -> PathBuf { |
| 470 | let stem = main.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); |
| 471 | let name = self.output.replace("{stem}", &stem); |
| 472 | let p = PathBuf::from(name); |
| 473 | if p.is_absolute() { p } else { |
| 474 | main.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")).join(p) |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | /// The command that opens a viewer, none when `view.open` is off or no viewer is installed. |
| 479 | pub fn viewer(&self) -> Option<String> { |
| 480 | if !self.view.open { |
| 481 | return None; |
| 482 | } |
| 483 | if self.view.app != "auto" { |
| 484 | return Some(self.view.app.clone()); |
| 485 | } |
| 486 | ["papers", "evince", "xdg-open"].iter().find(|c| on_path(c)).map(|c| c.to_string()) |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | // The device space a profile setting names: the built-in one by its word, else the profile file at that path, |
| 491 | // taken from `base` when relative. The error names the key. |
| 492 | fn device(key: &str, name: &str, space: Space, base: &Path) -> Outcome<Dev> { |
| 493 | let made = || -> Outcome<Dev> { |
| 494 | match (space, name) { |
| 495 | (Space::Rgb, "srgb") => return Dev::srgb(), |
| 496 | (Space::Gray, "sgray") => return Ok(Dev::sgray()), |
| 497 | (Space::Cmyk, "fogra39") => return Dev::from_profile(&res!(icc::fogra39l())), |
| 498 | _ => (), |
| 499 | } |
| 500 | let path = base.join(name); |
| 501 | let bytes = res!(std::fs::read(&path)); |
| 502 | let p = res!(Profile::read(&path.display().to_string(), &bytes)); |
| 503 | if p.head.space != space { |
| 504 | return Err(err!( |
| 505 | "The profile {} is a {:?} one, and the setting takes a {:?} one.", path.display(), p.head.space, space; |
| 506 | Input, Invalid, Mismatch)); |
| 507 | } |
| 508 | Dev::from_profile(&p) |
| 509 | }; |
| 510 | match made() { |
| 511 | Ok(dev) => Ok(dev), |
| 512 | Err(e) => Err(err!(e, "The setting '{}' = \"{}\" cannot be used as a profile.", key, name; Input, Invalid)), |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | fn on_path(cmd: &str) -> bool { |
| 517 | match std::env::var_os("PATH") { |
| 518 | Some(path) => std::env::split_paths(&path).any(|d| d.join(cmd).is_file()), |
| 519 | None => false, |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | // The colour keys of `c` that its own space does not read and that differ from their defaults: each key, its |
| 524 | // value as told, and the spaces that read it. |
| 525 | fn unread(c: &Colour) -> Vec<(&'static str, String, &'static [&'static str])> { |
| 526 | let d = Colour::default(); |
| 527 | const BOTH: &[&str] = &["cmyk", "grey"]; |
| 528 | const GREY: &[&str] = &["grey"]; |
| 529 | const CMYK: &[&str] = &["cmyk"]; |
| 530 | [ |
| 531 | ("colour.rgb_profile", shown(&Dat::Str(c.rgb_profile.clone())), c.rgb_profile != d.rgb_profile, BOTH), |
| 532 | ("colour.grey_profile", shown(&Dat::Str(c.grey_profile.clone())), c.grey_profile != d.grey_profile, GREY), |
| 533 | ("colour.cmyk_profile", shown(&Dat::Str(c.cmyk_profile.clone())), c.cmyk_profile != d.cmyk_profile, BOTH), |
| 534 | ("colour.intent", shown(&Dat::Str(c.intent.clone())), c.intent != d.intent, BOTH), |
| 535 | ("colour.black_point", shown(&Dat::Bool(c.black_point)), c.black_point != d.black_point, BOTH), |
| 536 | ("colour.black", shown(&Dat::Str(c.black.clone())), c.black != d.black, CMYK), |
| 537 | ].into_iter() |
| 538 | .filter(|(_, _, differs, only)| *differs && !only.contains(&c.space.as_str())) |
| 539 | .map(|(key, got, _, only)| (key, got, only)) |
| 540 | .collect() |
| 541 | } |
| 542 | |
| 543 | // The spaces that read a key, as an error message names them. |
| 544 | fn spaces(only: &[&str]) -> String { |
| 545 | only.iter().map(|w| fmt!("\"{}\"", w)).collect::<Vec<_>>().join(" or ") |
| 546 | } |
| 547 | |
| 548 | // One `--set key=value`: the key, and the value typed by what the key takes. A list is comma-separated. |
| 549 | fn parse_set(arg: &str) -> Outcome<(String, Dat)> { |
| 550 | let (key, text) = match arg.split_once('=') { |
| 551 | Some(kv) => kv, |
| 552 | None => return Err(err!("--set takes key=value, and '{}' has no '='.", arg; Input, Invalid)), |
| 553 | }; |
| 554 | let kind = match key_of(key) { |
| 555 | Some(k) => k, |
| 556 | None => return Err(err!( |
| 557 | "--set names the setting '{}', which is not one Austenite has. The keys are: {}.", |
| 558 | key, KEYS.iter().map(|(p, _)| *p).collect::<Vec<_>>().join(", "); Input, Invalid)), |
| 559 | }; |
| 560 | let val = match kind { |
| 561 | Kind::Bool => match text { |
| 562 | "true" => Dat::Bool(true), |
| 563 | "false" => Dat::Bool(false), |
| 564 | _ => return Err(err!("The setting '{}' must be {}, not \"{}\".", key, kind.say(), text; Input, Invalid)), |
| 565 | }, |
| 566 | Kind::Num(..) => match text.parse::<u64>() { |
| 567 | Ok(n) => Dat::U64(n), |
| 568 | Err(_) => return Err(err!("The setting '{}' must be {}, not \"{}\".", key, kind.say(), text; Input, Invalid)), |
| 569 | }, |
| 570 | Kind::List => Dat::List(text.split(',').filter(|t| !t.is_empty()).map(|t| Dat::Str(t.trim().to_string())).collect()), |
| 571 | Kind::Text | Kind::Pick(_) => Dat::Str(text.to_string()), |
| 572 | }; |
| 573 | res!(suits(key, kind, &val)); |
| 574 | Ok((key.to_string(), val)) |
| 575 | } |
| 576 | |
| 577 | /// The settings file that sends `source` back to the curated reader: the first `austenite.jdat` at or above |
| 578 | /// it, when that sets `engine` to `"curated"`. A file that cannot be read is refused, as `build` refuses it. |
| 579 | pub fn curated_by(source: &Path) -> Outcome<Option<PathBuf>> { |
| 580 | let file = match find(source) { |
| 581 | Some(f) => f, |
| 582 | None => return Ok(None), |
| 583 | }; |
| 584 | let s = res!(Settings::resolve(Some(&file), &[])); |
| 585 | Ok(if s.engine == "curated" { Some(file) } else { None }) |
| 586 | } |
| 587 | |
| 588 | /// The settings file for a source: the first `austenite.jdat` in its directory or above it. |
| 589 | pub fn find(start: &Path) -> Option<PathBuf> { |
| 590 | let dir = if start.is_dir() { start.to_path_buf() } else { |
| 591 | start.parent().filter(|d| !d.as_os_str().is_empty()).map(|d| d.to_path_buf()).unwrap_or_else(|| PathBuf::from(".")) |
| 592 | }; |
| 593 | let mut at = std::fs::canonicalize(&dir).ok(); |
| 594 | while let Some(d) = at { |
| 595 | let f = d.join(FILE); |
| 596 | if f.is_file() { |
| 597 | return Some(f); |
| 598 | } |
| 599 | at = d.parent().map(|p| p.to_path_buf()); |
| 600 | } |
| 601 | None |
| 602 | } |
| 603 | |
| 604 | // The quoted paths that follow `import` and `include` in a source, as a file name each. |
| 605 | fn referenced(text: &str) -> Vec<String> { |
| 606 | let mut out = Vec::new(); |
| 607 | for word in ["import", "include"] { |
| 608 | let mut from = 0; |
| 609 | while let Some(i) = text[from..].find(word) { |
| 610 | let after = from + i + word.len(); |
| 611 | from = after; |
| 612 | let rest = text[after..].trim_start(); |
| 613 | if let Some(q) = rest.strip_prefix('"') { |
| 614 | if let Some(end) = q.find('"') { |
| 615 | out.push(q[..end].to_string()); |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | } |
| 620 | out |
| 621 | } |
| 622 | |
| 623 | /// The `.typ` in `dir` that no sibling imports or includes. When there are several, they are listed and |
| 624 | /// refused; when there is none, that is refused too. |
| 625 | pub fn select_document(dir: &Path) -> Outcome<PathBuf> { |
| 626 | let mut typs = Vec::new(); |
| 627 | for e in res!(std::fs::read_dir(dir)) { |
| 628 | let p = res!(e).path(); |
| 629 | if p.extension().map(|x| x == "typ").unwrap_or(false) && p.is_file() { |
| 630 | typs.push(p); |
| 631 | } |
| 632 | } |
| 633 | typs.sort(); |
| 634 | let mut used = std::collections::BTreeSet::new(); |
| 635 | for p in &typs { |
| 636 | let text = std::fs::read_to_string(p).unwrap_or_default(); |
| 637 | for r in referenced(&text) { |
| 638 | if let Ok(c) = std::fs::canonicalize(dir.join(&r)) { |
| 639 | used.insert(c); |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | let roots: Vec<PathBuf> = typs.iter() |
| 644 | .filter(|p| std::fs::canonicalize(p).map(|c| !used.contains(&c)).unwrap_or(true)) |
| 645 | .cloned() |
| 646 | .collect(); |
| 647 | match roots.len() { |
| 648 | 0 => Err(err!("No document in {}: every .typ there is imported by another. Name one.", dir.display(); Input, Missing)), |
| 649 | 1 => Ok(roots[0].clone()), |
| 650 | _ => Err(err!( |
| 651 | "More than one document in {} is imported by no other: {}. Name one.", |
| 652 | dir.display(), roots.iter().filter_map(|p| p.file_name()).map(|n| n.to_string_lossy().to_string()).collect::<Vec<_>>().join(", "); |
| 653 | Input, Invalid)), |
| 654 | } |
| 655 | } |