forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

looks.rs261 lines, 10.3 KiBHistoryRawDownload
1//! Looks: a whole colour grade under one name. Eight built-in looks are colour
2//! presets (sliders, wheels and curves, no LUT file), and the user's own looks
3//! are saved as `<name>.look` text files in `$XDG_DATA_HOME/edith/looks`.
4//!
5//! A look is a plain [`ColorParams`]: applying one replaces the clip's grade,
6//! and what is saved is the grade as it stands. A `.cube` file a grade names is
7//! kept as its path and mix, so the look loads the same LUT again.
8//!
9//! The file format, one `key values` line each, in this order:
10//!
11//! ```text
12//! edith look 1
13//! brightness 0.04
14//! contrast 0.85
15//! saturation 0.75
16//! tint 0.05
17//! lift 0.1 0 0 0.03 (master, red, green, blue)
18//! gamma 0 0 0 0
19//! gain 0 0 0 0
20//! curve master 0,0 0.25,0.2 0.75,0.8 1,1 ("-" for a straight curve)
21//! curve red -
22//! curve green -
23//! curve blue -
24//! lut 0.8 /home/me/luts/warm.cube (only with a LUT: mix, then the path)
25//! ```
26//!
27//! Unknown keys are skipped, so a later edith can add lines an older one ignores.
28
29use std::path::{Path, PathBuf};
30
31use crate::color::{ColorParams, Curve, Look, Wheels};
32use crate::cube::LutRef;
33
34/// The extension a saved look's file carries.
35pub const EXT: &str = "look";
36/// The first line of every look file.
37const MAGIC: &str = "edith look 1";
38/// Longest name a saved look may have, in characters.
39const MAX_NAME: usize = 60;
40
41/// The built-in looks, in the order the card lists them.
42pub fn builtins() -> Vec<(&'static str, ColorParams)> {
43 let curve = |pts: &[[f32; 2]]| Curve::new(pts).unwrap_or_default();
44 let plain = |brightness, contrast, saturation, tint, wheels: Wheels, curves: [Curve; 4]| ColorParams {
45 brightness,
46 contrast,
47 saturation,
48 tint,
49 look: Look { wheels, curves, ..Default::default() },
50 };
51 let gain = |master: f32, red: f32, green: f32, blue: f32| Wheels { gain: [master, red, green, blue], ..Default::default() };
52 let lift = |master: f32, red: f32, green: f32, blue: f32| Wheels { lift: [master, red, green, blue], ..Default::default() };
53 let none = [Curve::default(); 4];
54 vec![
55 ("Warm", plain(0.0, 1.0, 1.0, 0.3, gain(0.0, 0.06, 0.0, -0.06), none)),
56 ("Cool", plain(0.0, 1.0, 1.0, -0.3, gain(0.0, -0.04, 0.0, 0.07), none)),
57 (
58 "Teal & orange",
59 plain(0.0, 1.0, 1.15, 0.0, Wheels { lift: [0.0, -0.02, 0.05, 0.08], gain: [0.0, 0.07, 0.0, -0.05], ..Default::default() }, none),
60 ),
61 (
62 "Bleach bypass",
63 plain(
64 0.0,
65 1.2,
66 0.35,
67 0.0,
68 Wheels::default(),
69 [curve(&[[0.0, 0.0], [0.25, 0.2], [0.75, 0.8], [1.0, 1.0]]), Curve::default(), Curve::default(), Curve::default()],
70 ),
71 ),
72 ("Black & white", plain(0.0, 1.0, 0.0, 0.0, Wheels::default(), none)),
73 ("Faded film", plain(0.04, 0.85, 0.75, 0.05, lift(0.1, 0.0, 0.0, 0.03), none)),
74 ("High contrast", plain(-0.02, 1.4, 1.1, 0.0, Wheels::default(), none)),
75 ("Vintage", plain(0.0, 0.95, 0.6, 0.2, Wheels { lift: [0.06, 0.02, 0.02, 0.0], gain: [0.0, 0.05, 0.0, -0.08], ..Default::default() }, none)),
76 ]
77}
78
79/// The built-in look called `name` (any case), if there is one.
80pub fn builtin(name: &str) -> Option<ColorParams> {
81 builtins().into_iter().find(|(n, _)| n.eq_ignore_ascii_case(name.trim())).map(|(_, p)| p)
82}
83
84/// Where saved looks live: `$XDG_DATA_HOME/edith/looks`, or `~/.local/share/edith/looks`.
85pub fn saved_dir() -> Option<PathBuf> {
86 let base = std::env::var_os("XDG_DATA_HOME")
87 .map(PathBuf::from)
88 .filter(|p| p.is_absolute())
89 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))?;
90 Some(base.join("edith").join("looks"))
91}
92
93/// The name a look is saved under, trimmed and checked: non-empty, short, no path
94/// separators or control characters, not a dot-file, and not a built-in's name.
95pub fn valid_name(name: &str) -> Result<String, String> {
96 let name = name.trim();
97 if name.is_empty() {
98 return Err("a look needs a name".into());
99 }
100 if name.chars().count() > MAX_NAME {
101 return Err(format!("a look name is at most {MAX_NAME} characters"));
102 }
103 if name.starts_with('.') || name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) {
104 return Err(format!("{name:?} has a character a file name cannot"));
105 }
106 if builtin(name).is_some() {
107 return Err(format!("{name} is a built-in look; pick another name"));
108 }
109 Ok(name.to_string())
110}
111
112/// The names of the saved looks, A to Z.
113pub fn saved_names() -> Vec<String> {
114 let Some(dir) = saved_dir() else {
115 return Vec::new();
116 };
117 let Ok(entries) = std::fs::read_dir(dir) else {
118 return Vec::new();
119 };
120 let mut names: Vec<String> = entries
121 .filter_map(Result::ok)
122 .map(|e| e.path())
123 .filter(|p| p.extension().is_some_and(|x| x == EXT))
124 .filter_map(|p| p.file_stem().map(|s| s.to_string_lossy().into_owned()))
125 .collect();
126 names.sort_by_key(|n| n.to_lowercase());
127 names
128}
129
130/// The look called `name`: a built-in first, then a saved one.
131pub fn load(name: &str) -> Result<ColorParams, String> {
132 if let Some(p) = builtin(name) {
133 return Ok(p);
134 }
135 let path = saved_path(name)?;
136 let text = std::fs::read_to_string(&path).map_err(|e| format!("no look called {name}: {e}"))?;
137 from_text(&text).map_err(|e| format!("look {name}: {e}"))
138}
139
140/// Saves `params` as the look `name`, replacing a saved look of that name. Returns the file written.
141pub fn save(name: &str, params: &ColorParams) -> Result<PathBuf, String> {
142 let path = saved_path(name)?;
143 let dir = path.parent().ok_or("no folder for looks")?;
144 std::fs::create_dir_all(dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?;
145 std::fs::write(&path, to_text(params)).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
146 Ok(path)
147}
148
149fn saved_path(name: &str) -> Result<PathBuf, String> {
150 let name = valid_name(name)?;
151 let dir = saved_dir().ok_or("no home folder to keep looks in")?;
152 Ok(dir.join(format!("{name}.{EXT}")))
153}
154
155/// The look file's text for `p`.
156pub fn to_text(p: &ColorParams) -> String {
157 let w = &p.look.wheels;
158 let four = |v: &[f32; 4]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(" ");
159 let mut out = format!(
160 "{MAGIC}\nbrightness {}\ncontrast {}\nsaturation {}\ntint {}\nlift {}\ngamma {}\ngain {}\n",
161 p.brightness,
162 p.contrast,
163 p.saturation,
164 p.tint,
165 four(&w.lift),
166 four(&w.gamma),
167 four(&w.gain)
168 );
169 for (name, c) in crate::color::CHANNELS.iter().zip(&p.look.curves) {
170 let pts = c.points();
171 let body = if pts.is_empty() {
172 "-".to_string()
173 } else {
174 pts.iter().map(|q| format!("{},{}", q[0], q[1])).collect::<Vec<_>>().join(" ")
175 };
176 out.push_str(&format!("curve {name} {body}\n"));
177 }
178 if let Some(lut) = p.look.lut {
179 out.push_str(&format!("lut {} {}\n", p.look.lut_mix, lut.path().display()));
180 }
181 out
182}
183
184/// The grade a look file's text holds. A bad number, a bad curve or a LUT that
185/// no longer loads is refused by name.
186pub fn from_text(text: &str) -> Result<ColorParams, String> {
187 let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
188 if lines.next() != Some(MAGIC) {
189 return Err("not an edith look file".into());
190 }
191 let mut p = ColorParams::default();
192 for line in lines {
193 let (key, rest) = line.split_once(' ').unwrap_or((line, ""));
194 let nums = |n: usize| -> Result<Vec<f32>, String> {
195 let v: Vec<f32> = rest
196 .split_whitespace()
197 .map(|t| t.parse::<f32>().map_err(|_| format!("{key}: {t:?} is not a number")))
198 .collect::<Result<_, _>>()?;
199 if v.len() != n {
200 return Err(format!("{key} takes {n} numbers, not {}", v.len()));
201 }
202 Ok(v)
203 };
204 let four = |v: Vec<f32>| [v[0], v[1], v[2], v[3]];
205 match key {
206 "brightness" => p.brightness = nums(1)?[0],
207 "contrast" => p.contrast = nums(1)?[0],
208 "saturation" => p.saturation = nums(1)?[0],
209 "tint" => p.tint = nums(1)?[0],
210 "lift" => p.look.wheels.lift = four(nums(4)?),
211 "gamma" => p.look.wheels.gamma = four(nums(4)?),
212 "gain" => p.look.wheels.gain = four(nums(4)?),
213 "curve" => {
214 let (channel, body) = rest.split_once(' ').unwrap_or((rest, "-"));
215 let ix = crate::color::CHANNELS
216 .iter()
217 .position(|c| *c == channel)
218 .ok_or_else(|| format!("curve {channel:?} is not master, red, green or blue"))?;
219 let pts: Vec<[f32; 2]> = if body.trim() == "-" {
220 Vec::new()
221 } else {
222 body.split_whitespace()
223 .map(|pair| {
224 let (x, y) = pair.split_once(',').ok_or_else(|| format!("curve point {pair:?} is not x,y"))?;
225 let f = |s: &str| s.parse::<f32>().map_err(|_| format!("curve point {pair:?} is not x,y"));
226 Ok([f(x)?, f(y)?])
227 })
228 .collect::<Result<_, String>>()?
229 };
230 p.look.curves[ix] = Curve::new(&pts)?;
231 }
232 "lut" => {
233 let (mix, path) = rest.split_once(' ').ok_or("lut takes a mix and a path")?;
234 let mix: f32 = mix.parse().map_err(|_| format!("lut mix {mix:?} is not a number"))?;
235 let lut = LutRef::reload(Path::new(path));
236 if let Some(why) = lut.problem() {
237 return Err(format!("the LUT {path} does not load: {why}"));
238 }
239 p.look.lut = Some(lut);
240 p.look.lut_mix = mix;
241 }
242 _ => {}
243 }
244 }
245 Ok(p)
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251
252 #[test]
253 fn a_look_round_trips_through_its_text() {
254 let (_, mut p) = builtins().into_iter().find(|(n, _)| *n == "Bleach bypass").expect("a look");
255 p.look.wheels.lift = [0.1, -0.05, 0.0, 0.25];
256 p.tint = -0.123_456_79;
257 let back = from_text(&to_text(&p)).expect("parses");
258 assert_eq!(back, p);
259 }
260
261}