| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | use std::path::{Path, PathBuf}; |
| 30 | |
| 31 | use crate::color::{ColorParams, Curve, Look, Wheels}; |
| 32 | use crate::cube::LutRef; |
| 33 | |
| 34 | |
| 35 | pub const EXT: &str = "look"; |
| 36 | |
| 37 | const MAGIC: &str = "edith look 1"; |
| 38 | |
| 39 | const MAX_NAME: usize = 60; |
| 40 | |
| 41 | |
| 42 | pub 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 | |
| 80 | pub 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 | |
| 85 | pub 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 | |
| 94 | |
| 95 | pub 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 | |
| 113 | pub 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 | |
| 131 | pub 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 | |
| 141 | pub 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 | |
| 149 | fn 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 | |
| 156 | pub 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 | |
| 185 | |
| 186 | pub 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)] |
| 249 | mod 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 | } |