Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.
TypeScript ai-photo-editorcomfyui-alternativegenerative-fillimage-editingimage-generationinpaintinglinuxlocal-aimacosmcpmcp-servernano-banana-alternativeofflinephoto-editorprivacyqwen-imageqwen-image-2-1stable-diffusion-cppvulkanwindows
feat: apply .cube colour LUTs to results, previewed live and saved as a new version
Gabriele Lozupone632158fc3eb7
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rsindex 7b0c2e7..d222f7b 100644--- a/crates/qls-core/src/engine.rs+++ b/crates/qls-core/src/engine.rs@@ -93,6 +93,7 @@ pub struct Engine {pub private_store: Arc<Store>,/// Measured speed of this machine, for time estimates.speed: crate::speed::SpeedBook,+ data_dir: PathBuf,private_dir: PathBuf,jobs: Mutex<HashMap<String, Job>>,order: Mutex<VecDeque<String>>,@@ -167,6 +168,7 @@ impl Engine {store,private_store,speed: if cfg!(test) { crate::speed::SpeedBook::in_memory() } else { crate::speed::SpeedBook::open(data_dir) },+ data_dir: data_dir.to_path_buf(),private_dir,jobs: Mutex::new(HashMap::new()),order: Mutex::new(VecDeque::new()),@@ -577,7 +579,16 @@ impl Engine {/// Loads one image source: "input:<id>", "gen:<id>" or an absolute path. A private job/// keeps its copy of the input in the private store.pub fn resolve_source(&self, src: &str, workspace: Option<&Path>, private: bool) -> AppResult<(LoadedImage, InputRecord)> {- let (bytes, original_path, name) = if let Some(id) = src.strip_prefix("input:") {+ let (bytes, original_path, name) = self.read_source(src, workspace)?;+ let store = if private { &self.private_store } else { &self.store };+ let rec = store.put_input(&bytes, name.as_deref(), original_path.as_deref())?;+ let img = imaging::decode_image(&bytes)?;+ Ok((img, rec))+ }++ /// The bytes of an image source, with its original path and file name.+ fn read_source(&self, src: &str, workspace: Option<&Path>) -> AppResult<(Vec<u8>, Option<String>, Option<String>)> {+ Ok(if let Some(id) = src.strip_prefix("input:") {let rec = self.input_store(id).get_input(id)?;let b = std::fs::read(&rec.path).map_err(|e| AppError::io("read the stored image", Path::new(&rec.path), e))?;(b, rec.original_path.clone(), rec.original_name.clone())@@ -590,11 +601,117 @@ impl Engine {let p = paths::validate_input_image(src, workspace, &[])?;let b = std::fs::read(&p).map_err(|e| AppError::io("read the image", &p, e))?;(b, Some(p.to_string_lossy().into_owned()), p.file_name().map(|n| n.to_string_lossy().into_owned()))+ })+ }++ /// The colour LUTs the user has opened (`<data>/luts`).+ pub fn luts(&self) -> crate::lut::LutLibrary {+ crate::lut::LutLibrary::new(self.data_dir.join("luts"))+ }++ /// A library LUT on a "gen:"/"input:" source at full strength, reduced to `max_side`, for+ /// the live preview (the UI shows the intensity as its opacity over the image). JPEG, or+ /// PNG when the image has transparency or a colour profile to keep. Returns the content type.+ pub fn lut_preview(&self, src: &str, name: &str, max_side: u32) -> AppResult<(Vec<u8>, &'static str)> {+ if !src.starts_with("gen:") && !src.starts_with("input:") {+ return Err(AppError::new(ErrorCode::InvalidInput, "LUTs apply to results and imported images."));+ }+ let lut = self.luts().load(name)?;+ let img = imaging::decode_image(&self.read_source(src, None)?.0)?;+ let small = lut.apply(&imaging::thumbnail(&img.pixels, max_side.clamp(256, 4096)), 1.0);+ if img.has_transparency || img.icc_profile.is_some() {+ Ok((imaging::encode_png(&small, &[], img.icc_profile.as_deref(), true)?, "image/png"))+ } else {+ Ok((imaging::encode_jpeg(&small, 92)?, "image/jpeg"))+ }+ }++ /// Applies a library LUT to a "gen:"/"input:" source at `intensity` (0-1) and saves the+ /// result as a new version made from it (mode "lut"; the source stays as it is). Private+ /// when asked or when the source itself is private. Same file format as a source result.+ pub fn apply_lut(&self, src: &str, name: &str, intensity: f32, private: bool) -> AppResult<GenerationRecord> {+ let started = Instant::now();+ let library = self.luts();+ let lut = library.load(name)?;+ let parent = match src.strip_prefix("gen:") {+ Some(id) => Some(self.gen_store(id).get_generation(id)?),+ None if src.starts_with("input:") => None,+ None => return Err(AppError::new(ErrorCode::InvalidInput, "LUTs apply to results and imported images.")),+ };+ let source_private = match (&parent, src.strip_prefix("input:")) {+ (Some(p), _) => Arc::ptr_eq(self.gen_store(&p.id), &self.private_store),+ (None, Some(id)) => Arc::ptr_eq(self.input_store(id), &self.private_store),+ _ => false,};+ let private = private || source_private;+ let (img, input) = self.resolve_source(src, None, private)?;+ let intensity = if intensity.is_finite() { intensity.clamp(0.0, 1.0) } else { 1.0 };+ let out = lut.apply(&img.pixels, intensity);+ library.touch(name);++ let cfg = self.config();+ let id = new_id();+ let now = chrono::Local::now();let store = if private { &self.private_store } else { &self.store };- let rec = store.put_input(&bytes, name.as_deref(), original_path.as_deref())?;- let img = imaging::decode_image(&bytes)?;- Ok((img, rec))+ let dir = if private { self.private_dir.join("out") } else { cfg.output_dir.join(now.format("%Y-%m-%d").to_string()) };+ std::fs::create_dir_all(&dir).map_err(|e| AppError::io("create the output folder", &dir, e))?;+ let format = match parent.as_ref().and_then(|p| Path::new(&p.file_path).extension()).map(|e| e.to_string_lossy().to_ascii_lowercase()).as_deref() {+ Some("jpg" | "jpeg") => OutputFormat::Jpeg,+ Some("webp") => OutputFormat::Webp,+ _ => OutputFormat::Png,+ };+ let file = paths::unique_path(dir.join(format!("{}-lut-{}.{}", now.format("%H%M%S"), paths::sanitize_file_stem(name), format.ext())), &[]);+ let pct = (intensity * 100.0).round();+ let mut rec = GenerationRecord {+ id: id.clone(),+ created_at: now_rfc3339(),+ mode: "lut".into(),+ prompt: String::new(),+ negative_prompt: String::new(),+ seed: parent.as_ref().map(|p| p.seed).unwrap_or(0),+ width: out.width(),+ height: out.height(),+ working_width: out.width(),+ working_height: out.height(),+ model: String::new(),+ sampler: String::new(),+ scheduler: None,+ steps: 0,+ cfg: 0.0,+ strength: None,+ quality: String::new(),+ resolution: String::new(),+ references: vec![ReferenceRecord { index: 0, input_id: input.id.clone(), original_path: input.original_path.clone(), width: input.width, height: input.height }],+ mask_input_id: None,+ outpaint: None,+ file_path: file.to_string_lossy().into_owned(),+ extra_paths: vec![],+ favorite: false,+ parent_id: parent.as_ref().map(|p| p.id.clone()),+ duration_ms: 0,+ notes: vec![format!("Colour LUT \"{name}\" at {pct} %.")],+ app_version: APP_VERSION.into(),+ backend_version: None,+ client: None,+ request: serde_json::json!({+ "mode": "lut",+ "images": [src],+ "parent_id": parent.as_ref().map(|p| p.id.clone()),+ "lut": { "name": name, "title": lut.title, "intensity": intensity },+ "private": private,+ }),+ pipeline: None,+ };+ rec.duration_ms = started.elapsed().as_millis() as u64;+ write_atomic(&file, &encode_output(&out, format, &rec, img.icc_profile.as_deref())?)?;+ if let Ok(j) = imaging::encode_jpeg(&imaging::thumbnail(&out, 512), 85) {+ let _ = std::fs::write(store.thumb_path(&id), j);+ }+ store.insert_generation(&rec)?;+ if !private {+ let _ = self.events.send(Event::Gallery { id: id.clone(), change: "added" });+ }+ Ok(rec)}/// How this machine's measured speed compares with the time model (None: not measured).@@ -1366,6 +1483,52 @@ mod tests {assert!(!req.private, "off unless asked");}+ #[test]+ fn lut_results_are_new_versions_of_their_source() {+ let dir = tempfile::tempdir().unwrap();+ let cfg = AppConfig { output_dir: dir.path().join("out"), ..Default::default() };+ let e = Engine::new(cfg, dir.path()).unwrap();+ let cube = dir.path().join("Invert.cube");+ let mut text = String::from("LUT_3D_SIZE 2+");+ for b in 0..2 {+ for g in 0..2 {+ for r in 0..2 {+ text.push_str(&format!("{} {} {}+", 1 - r, 1 - g, 1 - b));+ }+ }+ }+ std::fs::write(&cube, text).unwrap();+ let lut = e.luts().import(&cube).unwrap();+ let png = imaging::encode_png(&image::RgbaImage::from_pixel(16, 8, image::Rgba([200, 10, 40, 255])), &[], None, false).unwrap();+ let input = e.store.put_input(&png, Some("photo.png"), None).unwrap();+ let src = format!("input:{}", input.id);+ let preview = e.lut_preview(&src, &lut.name, 1024).unwrap();+ assert_eq!(preview.1, "image/jpeg");++ let rec = e.apply_lut(&src, &lut.name, 0.5, false).unwrap();+ assert_eq!((rec.mode.as_str(), rec.width, rec.height), ("lut", 16, 8));+ assert_eq!(rec.request["images"][0], src.as_str(), "made from the source (timeline link)");+ assert_eq!(rec.request["lut"]["intensity"], 0.5);+ assert!(Path::new(&rec.file_path).starts_with(dir.path().join("out")) && rec.file_path.ends_with(".png"));+ let px = *imaging::load_image(Path::new(&rec.file_path)).unwrap().pixels.get_pixel(0, 0);+ assert!(px[0].abs_diff(128) <= 1 && px[1].abs_diff(128) <= 1, "half way to the inverse: {px:?}");+ assert!(imaging::read_png_text(&std::fs::read(&rec.file_path).unwrap()).iter().any(|(k, v)| k == "parameters" && v.starts_with("Colour LUT: Invert")));+ assert!(e.store.get_generation(&rec.id).is_ok());++ // A result of a result keeps its format and parent; private sources stay private.+ let again = e.apply_lut(&format!("gen:{}", rec.id), &lut.name, 1.0, false).unwrap();+ assert_eq!(again.parent_id.as_deref(), Some(rec.id.as_str()));+ let other = imaging::encode_png(&image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])), &[], None, false).unwrap();+ let secret = e.private_store.put_input(&other, Some("secret.png"), None).unwrap();+ let p = e.apply_lut(&format!("input:{}", secret.id), &lut.name, 1.0, false).unwrap();+ assert!(e.store.get_generation(&p.id).is_err() && e.private_store.get_generation(&p.id).is_ok());+ assert!(Path::new(&p.file_path).starts_with(dir.path().join("private")));+ assert!(e.apply_lut("C:/x.png", &lut.name, 1.0, false).is_err());+ assert!(e.apply_lut(&src, "missing", 1.0, false).is_err());+ }+#[test]fn plan_inputs_follow_config() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rsindex 0474d69..cdd3098 100644--- a/crates/qls-core/src/lib.rs+++ b/crates/qls-core/src/lib.rs@@ -10,6 +10,7 @@ pub mod hdr;pub mod heif;pub mod imaging;pub mod installer;+pub mod lut;pub mod modelfile;pub mod paths;pub mod pipeline;diff --git a/crates/qls-core/src/lut.rs b/crates/qls-core/src/lut.rsnew file mode 100644index 0000000..784079b--- /dev/null+++ b/crates/qls-core/src/lut.rs@@ -0,0 +1,416 @@+//! Colour LUTs in the `.cube` format (Adobe / DaVinci Resolve): parsing, applying one to an+//! image at an intensity, and the folder of LUTs the user has opened (most recent first).+//!+//! 3D tables use tetrahedral interpolation (what Resolve and most graders use), 1D tables+//! linear interpolation per channel. Values are display-referred: the image's 8-bit sRGB+//! values go in as 0-1 (through `DOMAIN_MIN`/`DOMAIN_MAX`), like every grading tool does.++use std::path::{Path, PathBuf};++use image::RgbaImage;+use serde::Serialize;++use crate::error::{AppError, AppResult, ErrorCode};++/// Largest 3D table accepted (129³ is the biggest size tools write; 65³ is common).+const MAX_3D: usize = 129;+const MAX_1D: usize = 65_536;+/// Largest .cube file read (a 129³ table as text is ~50 MB).+const MAX_FILE: u64 = 96 * 1024 * 1024;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum LutKind {+ #[serde(rename = "1d")]+ OneD,+ #[serde(rename = "3d")]+ ThreeD,+}++#[derive(Debug, Clone)]+pub struct Lut {+ pub title: Option<String>,+ pub kind: LutKind,+ /// Entries per axis.+ pub size: usize,+ domain_min: [f32; 3],+ domain_max: [f32; 3],+ /// Output RGB; for 3D, red changes fastest (`r + g*n + b*n*n`).+ table: Vec<[f32; 3]>,+}++fn floats<const N: usize>(rest: &str, line: usize) -> Result<[f32; N], String> {+ let v: Vec<f32> = rest.split_whitespace().map(str::parse).collect::<Result<_, _>>().map_err(|_| format!("line {line}: expected {N} numbers"))?;+ v.try_into().map_err(|_| format!("line {line}: expected {N} numbers"))+}++impl Lut {+ /// Parses a `.cube` file. Errors are short, user-facing reasons.+ pub fn parse(text: &str) -> Result<Lut, String> {+ let mut title = None;+ let (mut size1, mut size3) = (None, None);+ let (mut dmin, mut dmax) = ([0.0f32; 3], [1.0f32; 3]);+ let mut table = Vec::new();+ for (i, raw) in text.lines().enumerate() {+ let line = i + 1;+ let l = raw.trim();+ if l.is_empty() || l.starts_with('#') {+ continue;+ }+ let (key, rest) = l.split_once(char::is_whitespace).map(|(k, r)| (k, r.trim())).unwrap_or((l, ""));+ let size = |r: &str| r.parse::<usize>().map_err(|_| format!("line {line}: bad size"));+ match key {+ "TITLE" => title = Some(rest.trim_matches('"').to_string()).filter(|t| !t.is_empty()),+ "LUT_1D_SIZE" => size1 = Some(size(rest)?),+ "LUT_3D_SIZE" => size3 = Some(size(rest)?),+ "DOMAIN_MIN" => dmin = floats::<3>(rest, line)?,+ "DOMAIN_MAX" => dmax = floats::<3>(rest, line)?,+ // Resolve's older form: one range for all channels.+ "LUT_1D_INPUT_RANGE" | "LUT_3D_INPUT_RANGE" => {+ let [a, b] = floats::<2>(rest, line)?;+ (dmin, dmax) = ([a; 3], [b; 3]);+ }+ _ if key.starts_with(|c: char| c.is_ascii_alphabetic()) => {} // other keywords+ _ => table.push(floats::<3>(l, line)?),+ }+ }+ let (kind, size) = match (size1, size3) {+ (Some(_), Some(_)) => return Err("LUTs with both a 1D and a 3D table are not supported".into()),+ (None, None) => return Err("not a .cube LUT (no LUT_3D_SIZE or LUT_1D_SIZE)".into()),+ (Some(n), None) => (LutKind::OneD, n),+ (None, Some(n)) => (LutKind::ThreeD, n),+ };+ let (max, want) = match kind {+ LutKind::OneD => (MAX_1D, size),+ LutKind::ThreeD => (MAX_3D, size.saturating_pow(3)),+ };+ if !(2..=max).contains(&size) {+ return Err(format!("unsupported table size {size}"));+ }+ if table.len() != want {+ return Err(format!("the table has {} entries instead of {want}", table.len()));+ }+ if (0..3).any(|c| dmax[c] <= dmin[c]) {+ return Err("DOMAIN_MAX must be above DOMAIN_MIN".into());+ }+ Ok(Lut { title, kind, size, domain_min: dmin, domain_max: dmax, table })+ }++ /// The LUT's output for one colour (components 0-1), clamped to 0-1.+ pub fn map(&self, rgb: [f32; 3]) -> [f32; 3] {+ let n = self.size;+ let top = (n - 1) as f32;+ let mut x = [0.0f32; 3];+ for c in 0..3 {+ x[c] = ((rgb[c] - self.domain_min[c]) / (self.domain_max[c] - self.domain_min[c])).clamp(0.0, 1.0) * top;+ }+ let out = match self.kind {+ LutKind::OneD => {+ let mut o = [0.0f32; 3];+ for c in 0..3 {+ let i = (x[c] as usize).min(n - 2);+ let f = x[c] - i as f32;+ o[c] = self.table[i][c] + f * (self.table[i + 1][c] - self.table[i][c]);+ }+ o+ }+ LutKind::ThreeD => {+ let (r, g, b) = ((x[0] as usize).min(n - 2), (x[1] as usize).min(n - 2), (x[2] as usize).min(n - 2));+ let (fr, fg, fb) = (x[0] - r as f32, x[1] - g as f32, x[2] - b as f32);+ let at = |dr: usize, dg: usize, db: usize| self.table[(r + dr) + (g + dg) * n + (b + db) * n * n];+ let c000 = at(0, 0, 0);+ let c111 = at(1, 1, 1);+ // Tetrahedral: the cube splits into six tetrahedra along its diagonal; the+ // ordering of the fractions picks the one the colour falls in.+ let (a, fa, b2, fb2, fc) = if fr > fg {+ if fg > fb {+ (at(1, 0, 0), fr, at(1, 1, 0), fg, fb)+ } else if fr > fb {+ (at(1, 0, 0), fr, at(1, 0, 1), fb, fg)+ } else {+ (at(0, 0, 1), fb, at(1, 0, 1), fr, fg)+ }+ } else if fb > fg {+ (at(0, 0, 1), fb, at(0, 1, 1), fg, fr)+ } else if fb > fr {+ (at(0, 1, 0), fg, at(0, 1, 1), fb, fr)+ } else {+ (at(0, 1, 0), fg, at(1, 1, 0), fr, fb)+ };+ let mut o = [0.0f32; 3];+ for c in 0..3 {+ o[c] = c000[c] + fa * (a[c] - c000[c]) + fb2 * (b2[c] - a[c]) + fc * (c111[c] - b2[c]);+ }+ o+ }+ };+ out.map(|v| v.clamp(0.0, 1.0))+ }++ /// Applies the LUT to every pixel, blended with the original by `intensity` (0-1). Alpha+ /// is kept. Split across the CPU cores (a 4K image takes a fraction of a second).+ pub fn apply(&self, img: &RgbaImage, intensity: f32) -> RgbaImage {+ let t = intensity.clamp(0.0, 1.0);+ let mut out = img.clone();+ if t == 0.0 {+ return out;+ }+ let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).min(16);+ let row = img.width() as usize * 4;+ let rows_per = (img.height() as usize).div_ceil(threads).max(1);+ std::thread::scope(|s| {+ for chunk in out.chunks_mut(rows_per * row.max(1)) {+ s.spawn(move || {+ for p in chunk.as_chunks_mut::<4>().0 {+ let src = [p[0] as f32 / 255.0, p[1] as f32 / 255.0, p[2] as f32 / 255.0];+ let m = self.map(src);+ for c in 0..3 {+ p[c] = ((src[c] + t * (m[c] - src[c])) * 255.0).round() as u8;+ }+ }+ });+ }+ });+ out+ }+}++/// A LUT in the library, for the picker.+#[derive(Debug, Clone, Serialize)]+pub struct LutEntry {+ /// File name without `.cube`; the LUT's id in the API.+ pub name: String,+ pub title: Option<String>,+ pub kind: LutKind,+ pub size: usize,+}++/// The LUTs the user has opened, copied into the app's data folder so they stay available+/// (`<data>/luts/<name>.cube`). Most recently used first; using one moves it to the top.+pub struct LutLibrary {+ dir: PathBuf,+}++/// How many LUTs the library keeps (the oldest beyond this are removed).+const KEEP: usize = 30;++/// A file name kept as the user wrote it (it is shown in the list), minus characters no file+/// system allows.+fn display_name(stem: &str) -> String {+ let s: String = stem.chars().map(|c| if c.is_control() || r#"/\:*?"<>|"#.contains(c) { '-' } else { c }).take(100).collect();+ let s = s.trim().trim_matches('.').trim().to_string();+ if s.is_empty() { "LUT".into() } else { s }+}++fn invalid(msg: impl Into<String>) -> AppError {+ AppError::new(ErrorCode::InvalidInput, msg)+}++impl LutLibrary {+ pub fn new(dir: PathBuf) -> Self {+ Self { dir }+ }++ fn path(&self, name: &str) -> AppResult<PathBuf> {+ if name.is_empty() || name.len() > 120 || name.contains(['/', '\\', ':']) || name.starts_with('.') {+ return Err(invalid(format!("Not a LUT name: {name}")));+ }+ Ok(self.dir.join(format!("{name}.cube")))+ }++ fn files(&self) -> Vec<(PathBuf, std::time::SystemTime)> {+ let mut v: Vec<_> = std::fs::read_dir(&self.dir)+ .into_iter()+ .flatten()+ .flatten()+ .map(|e| e.path())+ .filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("cube")))+ .map(|p| {+ let t = std::fs::metadata(&p).and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);+ (p, t)+ })+ .collect();+ v.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));+ v+ }++ /// The library, most recently used first (files that no longer parse are skipped).+ pub fn list(&self) -> Vec<LutEntry> {+ self.files()+ .into_iter()+ .filter_map(|(p, _)| {+ let name = p.file_stem()?.to_string_lossy().into_owned();+ let lut = Lut::parse(&std::fs::read_to_string(&p).ok()?).ok()?;+ Some(LutEntry { name, title: lut.title, kind: lut.kind, size: lut.size })+ })+ .collect()+ }++ /// Copies a `.cube` file into the library (the same file opened again is not duplicated).+ pub fn import(&self, src: &Path) -> AppResult<LutEntry> {+ let meta = std::fs::metadata(src).map_err(|e| AppError::io("read the LUT", src, e))?;+ if !meta.is_file() || meta.len() > MAX_FILE {+ return Err(invalid("That file is not a .cube LUT Kokon can read."));+ }+ let bytes = std::fs::read(src).map_err(|e| AppError::io("read the LUT", src, e))?;+ let text = String::from_utf8_lossy(&bytes);+ let lut = Lut::parse(&text).map_err(|why| invalid(format!("This LUT can't be used: {why}.")))?;+ std::fs::create_dir_all(&self.dir).map_err(|e| AppError::io("create the LUT folder", &self.dir, e))?;+ let stem = src.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();+ let base = display_name(&stem);+ let mut name = base.clone();+ for i in 2.. {+ let p = self.path(&name)?;+ match std::fs::read(&p) {+ Ok(existing) if existing == bytes => break,+ Ok(_) => name = format!("{base}-{i}"),+ Err(_) => {+ crate::engine::write_atomic(&p, &bytes)?;+ break;+ }+ }+ }+ self.touch(&name);+ self.prune();+ Ok(LutEntry { name, title: lut.title, kind: lut.kind, size: lut.size })+ }++ pub fn load(&self, name: &str) -> AppResult<Lut> {+ let p = self.path(name)?;+ let text = std::fs::read_to_string(&p).map_err(|_| AppError::new(ErrorCode::NotFound, format!("The LUT \"{name}\" is no longer in Kokon's LUT list.")))?;+ Lut::parse(&text).map_err(|why| invalid(format!("This LUT can't be used: {why}.")))+ }++ /// Moves a LUT to the top of the list.+ pub fn touch(&self, name: &str) {+ if let Ok(p) = self.path(name)+ && let Ok(f) = std::fs::File::options().append(true).open(&p)+ {+ let _ = f.set_modified(std::time::SystemTime::now());+ }+ }++ pub fn remove(&self, name: &str) -> AppResult<()> {+ let p = self.path(name)?;+ match std::fs::remove_file(&p) {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(AppError::io("remove the LUT", &p, e)),+ }+ }++ fn prune(&self) {+ for (p, _) in self.files().into_iter().skip(KEEP) {+ let _ = std::fs::remove_file(p);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A 3D identity of size `n`, with each output passed through `f`.+ fn cube3(n: usize, f: impl Fn([f32; 3]) -> [f32; 3]) -> String {+ let mut s = format!("TITLE \"test\"\n# comment\nLUT_3D_SIZE {n}\n\n");+ let top = (n - 1) as f32;+ for b in 0..n {+ for g in 0..n {+ for r in 0..n {+ let o = f([r as f32 / top, g as f32 / top, b as f32 / top]);+ s.push_str(&format!("{:.6} {:.6} {:.6}\n", o[0], o[1], o[2]));+ }+ }+ }+ s+ }++ fn close(a: [f32; 3], b: [f32; 3]) -> bool {+ (0..3).all(|c| (a[c] - b[c]).abs() < 1e-4)+ }++ #[test]+ fn identity_and_linear_luts_are_exact() {+ let id = Lut::parse(&cube3(17, |c| c)).unwrap();+ assert_eq!((id.kind, id.size, id.title.as_deref()), (LutKind::ThreeD, 17, Some("test")));+ let lin = Lut::parse(&cube3(5, |[r, g, b]| [0.5 * r + 0.25 * g, g, 1.0 - b])).unwrap();+ for c in [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.3, 0.7, 0.1], [0.91, 0.12, 0.55], [0.5, 0.5, 0.5]] {+ assert!(close(id.map(c), c), "{c:?}");+ // Tetrahedral interpolation reproduces any linear map exactly, between grid points too.+ let [r, g, b] = c;+ assert!(close(lin.map(c), [0.5 * r + 0.25 * g, g, 1.0 - b]), "{c:?} -> {:?}", lin.map(c));+ }+ }++ #[test]+ fn tetrahedral_interpolation_follows_the_diagonal() {+ // 2³ table, black everywhere except white at (1,1,1): along the grey axis the output+ // rises linearly (trilinear would give t³).+ let lut = Lut::parse(&cube3(2, |[r, g, b]| if r + g + b > 2.5 { [1.0; 3] } else { [0.0; 3] })).unwrap();+ assert!(close(lut.map([0.5, 0.5, 0.5]), [0.5; 3]));+ assert!(close(lut.map([0.8, 0.2, 0.2]), [0.2; 3]), "the smallest fraction sets the white share");+ }++ #[test]+ fn one_d_luts_and_domains() {+ let lut = Lut::parse("LUT_1D_SIZE 3\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n0 0 0\n0.5 0.5 1\n1 1 1\n").unwrap();+ assert_eq!(lut.kind, LutKind::OneD);+ // Input 1.0 is the middle of a 0-2 domain.+ assert!(close(lut.map([1.0, 0.5, 1.0]), [0.5, 0.25, 1.0]));+ let old = Lut::parse("LUT_3D_INPUT_RANGE 0 2\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").unwrap();+ assert!(close(old.map([1.0, 1.0, 1.0]), [0.5; 3]));+ }++ #[test]+ fn bad_files_say_why() {+ assert!(Lut::parse("hello").unwrap_err().contains("not a .cube"));+ assert!(Lut::parse("LUT_3D_SIZE 2\n0 0 0\n").unwrap_err().contains("1 entries instead of 8"));+ assert!(Lut::parse("LUT_3D_SIZE 2\n0 0\n").unwrap_err().contains("line 2"));+ assert!(Lut::parse("LUT_3D_SIZE 1000\n").unwrap_err().contains("size"));+ assert!(Lut::parse("LUT_1D_SIZE 2\nLUT_3D_SIZE 2\n").is_err());+ assert!(Lut::parse("LUT_1D_SIZE 2\nDOMAIN_MIN 1 1 1\nDOMAIN_MAX 0 0 0\n0 0 0\n1 1 1\n").is_err());+ }++ #[test]+ fn apply_blends_by_intensity_and_keeps_alpha() {+ let invert = Lut::parse(&cube3(9, |[r, g, b]| [1.0 - r, 1.0 - g, 1.0 - b])).unwrap();+ let img = RgbaImage::from_fn(37, 23, |x, y| image::Rgba([(x * 7) as u8, (y * 11) as u8, 200, (x + y) as u8]));+ let full = invert.apply(&img, 1.0);+ let half = invert.apply(&img, 0.5);+ assert_eq!(invert.apply(&img, 0.0), img);+ for (x, y, p) in img.enumerate_pixels() {+ let f = full.get_pixel(x, y);+ assert_eq!([f[0], f[1], f[2], f[3]], [255 - p[0], 255 - p[1], 55, p[3]]);+ assert!(half.get_pixel(x, y).0[..3].iter().all(|&v| (127..=128).contains(&v)));+ }+ }++ #[test]+ fn library_imports_lists_recent_first_and_removes() {+ let dir = tempfile::tempdir().unwrap();+ let lib = LutLibrary::new(dir.path().join("luts"));+ let src = dir.path().join("Warm Film.cube");+ std::fs::write(&src, cube3(2, |c| c)).unwrap();+ let a = lib.import(&src).unwrap();+ assert_eq!(a.name, "Warm Film");+ assert_eq!(lib.import(&src).unwrap().name, "Warm Film", "the same file is not copied twice");+ // Another file with the same name gets its own entry.+ let other = dir.path().join("sub");+ std::fs::create_dir_all(&other).unwrap();+ std::fs::write(other.join("Warm Film.cube"), cube3(3, |c| c)).unwrap();+ let b = lib.import(&other.join("Warm Film.cube")).unwrap();+ assert_eq!(b.name, "Warm Film-2");+ std::thread::sleep(std::time::Duration::from_millis(20));+ lib.touch("Warm Film");+ let names: Vec<_> = lib.list().into_iter().map(|e| e.name).collect();+ assert_eq!(names, ["Warm Film", "Warm Film-2"]);+ assert_eq!(lib.load("Warm Film-2").unwrap().size, 3);+ lib.remove("Warm Film").unwrap();+ assert_eq!(lib.list().len(), 1);+ assert!(lib.load("../secret").is_err());+ assert_eq!(display_name(" a:b?.cube. "), "a-b-.cube");+ let bad = dir.path().join("bad.cube");+ std::fs::write(&bad, "LUT_3D_SIZE 2\n0 0 0\n").unwrap();+ assert!(lib.import(&bad).unwrap_err().message.contains("can't be used"));+ }+}diff --git a/crates/qls-core/src/store.rs b/crates/qls-core/src/store.rsindex c4b6e9d..a5659d3 100644--- a/crates/qls-core/src/store.rs+++ b/crates/qls-core/src/store.rs@@ -89,6 +89,11 @@ pub struct GenerationRecord {impl GenerationRecord {/// AUTOMATIC1111-style "parameters" text understood by many image tools.pub fn parameters_text(&self) -> String {+ if self.mode == "lut" {+ let lut = &self.request["lut"];+ let pct = (lut["intensity"].as_f64().unwrap_or(1.0) * 100.0).round();+ return format!("Colour LUT: {}, Intensity: {pct}%, Size: {}x{}, Version: Kokon {}", lut["name"].as_str().unwrap_or("?"), self.width, self.height, self.app_version);+ }let mut s = self.prompt.clone();if !self.negative_prompt.is_empty() {s.push_str(&format!("\nNegative prompt: {}", self.negative_prompt));diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rsindex 65e1fcb..4ca33ab 100644--- a/crates/qls-service/src/api.rs+++ b/crates/qls-service/src/api.rs@@ -13,7 +13,7 @@ use axum::{http::{HeaderMap, HeaderValue, Method, StatusCode, header},middleware::{self, Next},response::{IntoResponse, Response, Sse, sse::Event as SseEvent},- routing::{get, post},+ routing::{delete, get, post},};use futures_util::stream::Stream;use qls_core::{@@ -102,6 +102,11 @@ pub fn router(state: Arc<AppState>) -> Router {.route("/gallery/{id}/original", get(gallery_original)).route("/gallery/{id}/export", post(gallery_export)).route("/image-info", post(image_info))+ .route("/luts", get(luts_list))+ .route("/luts/import", post(luts_import))+ .route("/luts/{name}", delete(luts_remove))+ .route("/luts/{name}/preview", get(luts_preview))+ .route("/luts/{name}/apply", post(luts_apply)).route("/examples", post(install_examples)).route("/session/heartbeat", post(heartbeat)).route("/session/release", post(release))@@ -867,6 +872,65 @@ async fn serve_file(path: &Path, content_type: Option<&str>) -> ApiResult<Respon.unwrap())}+async fn luts_list(State(s): St) -> Json<Value> {+ let lib = s.engine.luts();+ Json(json!({ "items": tokio::task::spawn_blocking(move || lib.list()).await.unwrap_or_default() }))+}++/// Adds a .cube file the user picked to the LUT list (copied into the data folder).+async fn luts_import(State(s): St, Json(b): Json<PathBody>) -> ApiResult<Json<Value>> {+ let p = PathBuf::from(&b.path);+ if !p.is_absolute() || !p.extension().is_some_and(|e| e.eq_ignore_ascii_case("cube")) {+ return Err(AppError::new(ErrorCode::InvalidInput, "Choose a .cube LUT file.").into());+ }+ let lib = s.engine.luts();+ let entry = tokio::task::spawn_blocking(move || lib.import(&p)).await.map_err(AppError::internal)??;+ Ok(Json(serde_json::to_value(entry).unwrap()))+}++async fn luts_remove(State(s): St, AxPath(name): AxPath<String>) -> ApiResult<Json<Value>> {+ s.engine.luts().remove(&name)?;+ Ok(Json(json!({ "removed": name })))+}++#[derive(Deserialize)]+struct LutPreviewQ {+ source: String,+ #[serde(default = "default_preview_side")]+ max: u32,+}++fn default_preview_side() -> u32 {+ 2048+}++/// The LUT on an image, reduced, for the live preview.+async fn luts_preview(State(s): St, AxPath(name): AxPath<String>, Query(q): Query<LutPreviewQ>) -> ApiResult<Response> {+ let engine = s.engine.clone();+ let (bytes, ct) = tokio::task::spawn_blocking(move || engine.lut_preview(&q.source, &name, q.max)).await.map_err(AppError::internal)??;+ Ok(Response::builder().header(header::CONTENT_TYPE, ct).header(header::CACHE_CONTROL, "no-store").body(Body::from(bytes)).unwrap())+}++#[derive(Deserialize)]+struct LutApplyBody {+ source: String,+ #[serde(default = "default_intensity")]+ intensity: f32,+ #[serde(default)]+ private: bool,+}++fn default_intensity() -> f32 {+ 1.0+}++/// Saves the image with the LUT applied as a new version (the source is kept).+async fn luts_apply(State(s): St, AxPath(name): AxPath<String>, Json(b): Json<LutApplyBody>) -> ApiResult<Json<Value>> {+ let engine = s.engine.clone();+ let rec = tokio::task::spawn_blocking(move || engine.apply_lut(&b.source, &name, b.intensity, b.private)).await.map_err(AppError::internal)??;+ Ok(Json(serde_json::to_value(rec).unwrap()))+}+async fn input_image(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Response> {let store = s.engine.input_store(&id);let r = store.get_input(&id)?;diff --git a/src/components/Lut.tsx b/src/components/Lut.tsxnew file mode 100644index 0000000..4130d65--- /dev/null+++ b/src/components/Lut.tsx@@ -0,0 +1,161 @@+import { Eye, FolderOpen, Loader2, Palette, X } from "lucide-react";+import { useEffect, useState } from "react";+import { api } from "../lib/api";+import { native } from "../lib/native";+import { toastError } from "../lib/store";+import type { LutEntry } from "../lib/types";+import { Popover } from "./ui";++/** Asks for a .cube file and adds it to Kokon's LUT list. */+async function openCubeFile(): Promise<LutEntry | null> {+ const path = await native.pickFile(["cube", "CUBE"], undefined, "LUT");+ if (!path) return null;+ try {+ return await api.importLut(path);+ } catch (e) {+ toastError(e);+ return null;+ }+}++function LutList({ current, onPick, close }: { current?: string; onPick: (name: string) => void; close: () => void }) {+ const [items, setItems] = useState<LutEntry[] | null>(null);+ useEffect(() => {+ api.luts().then((r) => setItems(r.items), toastError);+ }, []);+ const pick = (name: string) => {+ close();+ onPick(name);+ };+ return (+ <div className="lut-list">+ <span className="muted lut-list-title">Colour LUTs (.cube)</span>+ {items === null && <Loader2 className="spin" size={16} style={{ margin: 10 }} />}+ {items?.map((e) => (+ <div key={e.name} className="lut-row">+ <button className="opt" onClick={() => pick(e.name)} title={e.title && e.title !== e.name ? e.title : undefined}>+ <span className="check">{e.name === current ? <Palette size={15} /> : null}</span>+ <span className="lut-name">{e.name}</span>+ <span className="sub">{e.kind === "3d" ? `${e.size}³` : "1D"}</span>+ </button>+ <button+ className="icon-btn sm"+ title="Remove from the list"+ aria-label={`Remove ${e.name} from the list`}+ onClick={() => api.removeLut(e.name).then(() => setItems((l) => l?.filter((x) => x.name !== e.name) ?? null), toastError)}+ >+ <X size={14} />+ </button>+ </div>+ ))}+ <button+ className="opt"+ onClick={async () => {+ close();+ const e = await openCubeFile();+ if (e) onPick(e.name);+ }}+ >+ <span className="check">+ <FolderOpen size={15} />+ </span>+ <span>Open a .cube file…</span>+ </button>+ </div>+ );+}++/** "LUT" under the image: the LUTs opened before, or a .cube file (straight to the file+ * picker while the list is empty). `current` shows the LUT being previewed as its label. */+export function LutButton({ current, onPick }: { current?: string; onPick: (name: string) => void }) {+ return (+ <Popover+ placement="top-end"+ trigger={(open, toggle) => (+ <button+ className={`act ${open ? "active" : ""}`}+ title={current ? "Choose another LUT" : "LUT: apply a colour look from a .cube file (preview first, the original is kept)"}+ aria-label="LUT"+ onClick={async () => {+ if (open || current) return toggle();+ const { items } = await api.luts().catch(() => ({ items: [] as LutEntry[] }));+ if (items.length) return toggle();+ const e = await openCubeFile();+ if (e) onPick(e.name);+ }}+ >+ <Palette size={16} />+ <span className={current ? "lut-current" : "act-label"}>{current ?? "LUT"}</span>+ </button>+ )}+ >+ {(close) => <LutList current={current} onPick={onPick} close={close} />}+ </Popover>+ );+}++/** The LUT preview over the image: the LUT at full strength, its opacity = the intensity. */+export function LutOverlay({ src, opacity }: { src: string; opacity: number }) {+ const [loaded, setLoaded] = useState<string | null>(null);+ return (+ <>+ <img+ key={src}+ className="stage-img fill lut-overlay"+ src={src}+ alt=""+ draggable={false}+ style={{ opacity: loaded === src ? opacity : 0 }}+ onLoad={() => setLoaded(src)}+ onError={() => toastError(new Error("The LUT preview could not be made."))}+ />+ {loaded !== src && (+ <span className="lut-loading">+ <Loader2 className="spin" size={18} />+ </span>+ )}+ </>+ );+}++/** Replaces the actions while a LUT is previewed: which LUT, how strong, before/after, save. */+export function LutBar(props: {+ name: string;+ intensity: number;+ saving: boolean;+ onPick: (name: string) => void;+ onIntensity: (v: number) => void;+ onBefore: (on: boolean) => void;+ onCancel: () => void;+ onSave: () => void;+}) {+ const pct = Math.round(props.intensity * 100);+ return (+ <div className="actions lut-bar">+ <LutButton current={props.name} onPick={props.onPick} />+ <label className="lut-intensity" title="Intensity">+ <input type="range" min={0} max={100} value={pct} aria-label="Intensity" onChange={(e) => props.onIntensity(Number(e.target.value) / 100)} />+ <span>{pct} %</span>+ </label>+ <button+ className="act"+ title="Hold to see the image without the LUT (or hold B)"+ onPointerDown={() => props.onBefore(true)}+ onPointerUp={() => props.onBefore(false)}+ onPointerLeave={() => props.onBefore(false)}+ >+ <Eye size={16} />+ <span className="act-label">Before</span>+ </button>+ <span className="sep" />+ <button className="act" title="Cancel (Esc)" onClick={props.onCancel}>+ <X size={16} />+ <span className="act-label">Cancel</span>+ </button>+ <button className="btn primary" onClick={props.onSave} disabled={props.saving || pct === 0} title="Save as a new version (the original stays as it is)">+ {props.saving ? <Loader2 className="spin" size={14} /> : null}+ Save+ </button>+ </div>+ );+}diff --git a/src/components/Stage.tsx b/src/components/Stage.tsxindex 453153c..5c3cb57 100644--- a/src/components/Stage.tsx+++ b/src/components/Stage.tsx@@ -1,23 +1,24 @@import {- Brush, ClipboardPaste, Combine, Copy, Download, Ellipsis, Expand, FolderOpen, Heart, ImageUpscale, Info, Loader2, MousePointerClick, Pencil, RefreshCw, RotateCcw, SlidersHorizontal, Square, TextCursorInput, Trash2, Wand2, X,+ Brush, ClipboardPaste, Combine, Copy, Download, Ellipsis, Expand, FolderOpen, Heart, ImageUpscale, Info, Loader2, MousePointerClick, Palette, Pencil, RefreshCw, RotateCcw, SlidersHorizontal, Square, TextCursorInput, Trash2, Wand2, X,} from "lucide-react";import { Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { api, urls } from "../lib/api";import {- compareBase, composerFromRecord, formatDuration, jobFraction, jobLabel, MAX_UPSCALE_AREA, MAX_UPSCALE_SIDE, MODE_LABEL, pipelineSummary, remainingSeconds, sizeForWidth, upscaleRequest, arcLayout,+ compareBase, composerFromRecord, formatDuration, jobFraction, jobLabel, lutInfo, MAX_UPSCALE_AREA, MAX_UPSCALE_SIDE, MODE_LABEL, pipelineSummary, remainingSeconds, sizeForWidth, upscaleRequest, arcLayout,upscalerLabel, upscaleTargets, variationRequest, imageName, type LinkKind, type TimelineLink,} from "../lib/logic";import { native } from "../lib/native";import {- addAsReference, cancelJob, focusPrompt, getState, itemSource, removeSessionItem, reusePrompt, selectedItem, selectItem, sessionLabels, sessionLinks, setState, submitRequest, toastError, toastInfo, useStore, type SessionItem,+ addAsReference, addResult, cancelJob, focusPrompt, getState, itemSource, removeSessionItem, reusePrompt, selectedItem, selectItem, sessionLabels, sessionLinks, setState, submitRequest, toastError, toastInfo, useStore, type SessionItem,} from "../lib/store";import type { GenerationRecord, JobView, Mode, Size } from "../lib/types";import { CompareFrame, CompareFullscreen } from "./Compare";+import { LutBar, LutButton, LutOverlay } from "./Lut";import { IconButton, Popover, useFit } from "./ui";import { Fullscreen, FullscreenButton, isTyping, ZoomImage, type ViewerNav } from "./Viewer";import { fileManager, shortcut } from "../lib/platform";-export const MODE_ICON: Record<Mode, React.ReactNode> = {+export const MODE_ICON: Record<Mode | "lut", React.ReactNode> = {auto: <Wand2 size={11} />,generate: <Wand2 size={11} />,edit: <Pencil size={11} />,@@ -25,6 +26,7 @@ export const MODE_ICON: Record<Mode, React.ReactNode> = {inpaint: <Brush size={11} />,outpaint: <Expand size={11} />,upscale: <ImageUpscale size={11} />,+ lut: <Palette size={11} />,};const MODE_DOING: Record<Mode, string> = {@@ -132,7 +134,14 @@ function Failed({ job, item }: { job: JobView; item: SessionItem }) {function InfoPanel({ g }: { g: GenerationRecord }) {const pipeline = pipelineSummary(g);- const rows: [string, string][] = [+ const lut = lutInfo(g);+ const rows: [string, string][] = lut ? [+ ["Mode", MODE_LABEL[g.mode]],+ ["Size", `${g.width}×${g.height}`],+ ["LUT", lut.title && lut.title !== lut.name ? `${lut.name} (${lut.title})` : lut.name],+ ["Intensity", `${Math.round(lut.intensity * 100)} %`],+ ["Created", new Date(g.created_at).toLocaleString()],+ ] : [["Mode", MODE_LABEL[g.mode]],["Size", `${g.width}×${g.height}${g.working_width !== g.width || g.working_height !== g.height ? ` (worked at ${g.working_width}×${g.working_height})` : ""}`],...(pipeline ? ([["Pipeline", pipeline]] as [string, string][]) : []),@@ -242,7 +251,7 @@ function MoreMenu({ item, path }: { item: SessionItem; path: string | null }) {>{(close) => (<>- {g && (+ {g && g.mode !== "lut" && (<buttonclassName="opt"onClick={() => {@@ -278,10 +287,10 @@ function MoreMenu({ item, path }: { item: SessionItem; path: string | null }) {);}-function GenActions({ item, g, showOriginal }: { item: SessionItem; g: GenerationRecord; showOriginal: boolean }) {+function GenActions({ item, g, showOriginal, onLut }: { item: SessionItem; g: GenerationRecord; showOriginal: boolean; onLut: (name: string) => void }) {// Save, copy and "show in folder" act on the image on screen: the result or its pre-upscale original.const shownPath = (showOriginal && g.pipeline?.original_path) || g.file_path;- const original = g.references[0] && g.mode !== "generate" && g.mode !== "upscale" ? { width: g.references[0].width, height: g.references[0].height } : null;+ const original = g.references[0] && g.mode !== "generate" && g.mode !== "upscale" && g.mode !== "lut" ? { width: g.references[0].width, height: g.references[0].height } : null;const [fav, setFav] = useState(g.favorite);return (<div className="actions">@@ -293,7 +302,7 @@ function GenActions({ item, g, showOriginal }: { item: SessionItem; g: GeneratioonClick={() => reusePrompt(g)}/>)}- {g.request && g.mode !== "upscale" && (+ {g.request && g.mode !== "upscale" && g.mode !== "lut" && (<ActionButtontitle="Regenerate: same prompt and settings, new seed"icon={<RefreshCw size={16} />}@@ -305,6 +314,7 @@ function GenActions({ item, g, showOriginal }: { item: SessionItem; g: Generatio/>)}<UpscaleButton source={`gen:${g.id}`} size={{ width: g.width, height: g.height }} original={original} parentId={g.id} />+ <LutButton onPick={onLut} /><span className="sep" /><IconButtontitle={fav ? "Remove from favorites" : "Favorite"}@@ -364,11 +374,12 @@ function GenActions({ item, g, showOriginal }: { item: SessionItem; g: Generatio);}-function InputActions({ item }: { item: SessionItem }) {+function InputActions({ item, onLut }: { item: SessionItem; onLut: (name: string) => void }) {const input = item.input!;return (<div className="actions"><UpscaleButton source={`input:${input.id}`} size={{ width: input.width, height: input.height }} />+ <LutButton onPick={onLut} /><span className="sep" /><MoreMenu item={item} path={input.original_path ?? input.path} /></div>@@ -377,7 +388,7 @@ function InputActions({ item }: { item: SessionItem }) {/** A result or input fitted to the stage (never enlarged past its own size), with the* full-screen button in its top-right corner. */-function PlainFrame({ src, alt, w, h, maskSrc, onFullscreen }: { src: string; alt: string; w: number; h: number; maskSrc?: string; onFullscreen: () => void }) {+function PlainFrame({ src, alt, w, h, maskSrc, overlay, onFullscreen }: { src: string; alt: string; w: number; h: number; maskSrc?: string; overlay?: React.ReactNode; onFullscreen: () => void }) {const { ref, box } = useFit(w / h);const bw = Math.min(box.w, w);return (@@ -385,6 +396,7 @@ function PlainFrame({ src, alt, w, h, maskSrc, onFullscreen }: { src: string; al<div className="image-box" style={{ width: bw, height: bw * (h / w) }}><img className="stage-img fill" src={src} alt={alt} draggable={false} />{maskSrc && <img className="stage-mask" src={maskSrc} alt="" draggable={false} />}+ {overlay}<FullscreenButton onOpen={onFullscreen} /></div></div>@@ -392,8 +404,10 @@ function PlainFrame({ src, alt, w, h, maskSrc, onFullscreen }: { src: string; al}/** Under the image: which image this is and what made it, then what you can do with it. */-function StageBar({ item, label, showOriginal, setShowOriginal }: { item: SessionItem; label: string; showOriginal: boolean; setShowOriginal: (on: boolean) => void }) {+function StageBar(props: { item: SessionItem; label: string; showOriginal: boolean; setShowOriginal: (on: boolean) => void; lutBar: React.ReactNode; onLut: (name: string) => void }) {+ const { item, label, showOriginal, setShowOriginal } = props;const g = item.gen;+ const lut = g && lutInfo(g);const w = g?.width ?? item.input!.width;const h = g?.height ?? item.input!.height;const from = g?.pipeline?.original_path ? g.pipeline.enlarged_from : null;@@ -404,9 +418,9 @@ function StageBar({ item, label, showOriginal, setShowOriginal }: { item: Sessio<span className="ver">{imageName(label)}</span>{g && <span className="mode">{MODE_LABEL[g.mode]}</span>}<span className="stage-prompt" title={g?.prompt ?? name}>- {g ? g.prompt || (g.mode === "upscale" ? `${g.references[0]?.width ?? "?"}×${g.references[0]?.height ?? "?"} → ${w}×${h}` : "") : name}+ {g ? g.prompt || (g.mode === "upscale" ? `${g.references[0]?.width ?? "?"}×${g.references[0]?.height ?? "?"} → ${w}×${h}` : lut ? `${lut.name} · ${Math.round(lut.intensity * 100)} %` : "") : name}</span>- {from ? (+ {from && !props.lutBar ? (<span className="seg dims-seg" role="radiogroup" aria-label="Which image to show"><button className={showOriginal ? "" : "on"} role="radio" aria-checked={!showOriginal} onClick={() => setShowOriginal(false)} title={`The result, enlarged by ${upscalerLabel(g!.pipeline!.enlarged_with)}`}>Upscaled {w}×{h}@@ -421,7 +435,7 @@ function StageBar({ item, label, showOriginal, setShowOriginal }: { item: Sessio</span>)}</div>- {g ? <GenActions key={`actions-${g.id}`} item={item} g={g} showOriginal={showOriginal} /> : <InputActions item={item} />}+ {props.lutBar ?? (g ? <GenActions key={`actions-${g.id}`} item={item} g={g} showOriginal={showOriginal} onLut={props.onLut} /> : <InputActions item={item} onLut={props.onLut} />)}</div>);}@@ -555,7 +569,7 @@ function Timeline({ labels }: { labels: Record<string, string> }) {const pending = it.kind === "job";const failed = pending && job && ["failed", "cancelled"].includes(job.status);const frac = pending && job ? jobFraction(job) : null;- const mode: Mode | undefined = it.gen?.mode ?? job?.plan?.mode;+ const mode: Mode | "lut" | undefined = it.gen?.mode ?? job?.plan?.mode;const link = links[it.key];const pendingSrc = pending && it.request?.mode !== "generate" ? it.request?.images?.[0] : undefined;const prompt = it.gen?.prompt || it.request?.prompt || "";@@ -685,6 +699,9 @@ function StageFullscreen({ item, session, showOriginal, onClose }: { item: Sessi);}+/** The LUT intensity last saved, the starting point of the next preview. */+let lastIntensity = 1;+export function Stage() {const item = useStore(selectedItem);const session = useStore((s) => s.session);@@ -694,6 +711,11 @@ export function Stage() {const [originalOf, setOriginalOf] = useState<string | null>(null);const [full, setFull] = useState(false);const canFull = !!item && viewable(item);+ // A LUT being previewed on the selected version (intensity 0-1), before saving it as a new one.+ const [lut, setLut] = useState<{ itemKey: string; source: string; name: string; intensity: number } | null>(null);+ const [before, setBefore] = useState(false);+ const [saving, setSaving] = useState(false);+ const lutActive = lut && item && lut.itemKey === item.key ? lut : null;// The area painted for the next edit, shown on the image it belongs to (the prompt's first image).const mask = useStore((s) => s.composer.mask);const ref0 = useStore((s) => s.composer.refs[0]);@@ -711,6 +733,28 @@ export function Stage() {return () => window.removeEventListener("keydown", down);}, [full, canFull]);+ // Another version selected: the preview ends.+ useEffect(() => {+ if (lut && lut.itemKey !== item?.key) setLut(null);+ }, [item?.key, lut]);++ // While previewing a LUT: Esc cancels, holding B shows the image without it.+ useEffect(() => {+ if (!lutActive || full) return;+ const down = (e: KeyboardEvent) => {+ if (isTyping(e.target) || getState().overlay) return;+ if (e.key === "Escape") setLut(null);+ else if (e.key.toLowerCase() === "b" && !e.ctrlKey && !e.metaKey) setBefore(true);+ };+ const up = (e: KeyboardEvent) => e.key.toLowerCase() === "b" && setBefore(false);+ window.addEventListener("keydown", down);+ window.addEventListener("keyup", up);+ return () => {+ window.removeEventListener("keydown", down);+ window.removeEventListener("keyup", up);+ };+ }, [!!lutActive, full]);+// Nothing to show any more (the version was removed, or a new one is being made): leave full screen.useEffect(() => {if (full && !canFull) setFull(false);@@ -748,17 +792,57 @@ export function Stage() {const base = item.gen ? compareBase(item.gen) : null;const g = item.gen;const from = g?.pipeline?.original_path ? g.pipeline.enlarged_from : null;- const showOriginal = !!(g && from && originalOf === g.id);+ const showOriginal = !!(g && from && originalOf === g.id) && !lutActive;+ const source = g ? `gen:${g.id}` : `input:${item.input!.id}`;+ const startLut = (name: string) => setLut((l) => ({ itemKey: item.key, source, name, intensity: l?.intensity ?? lastIntensity }));+ const saveLut = async () => {+ if (!lutActive) return;+ setSaving(true);+ try {+ lastIntensity = lutActive.intensity;+ const rec = await api.applyLut(lutActive.name, lutActive.source, lutActive.intensity, getState().privateMode);+ setLut(null);+ addResult(rec);+ } catch (e) {+ toastError(e);+ } finally {+ setSaving(false);+ }+ };+ // The preview is made for the screen: the image's own size at most.+ const previewMax = Math.min(Math.max(w, h), Math.round(1600 * Math.min(2, window.devicePixelRatio || 1)), 4096);+ const lutBar = lutActive && (+ <LutBar+ name={lutActive.name}+ intensity={lutActive.intensity}+ saving={saving}+ onPick={startLut}+ onIntensity={(v) => setLut({ ...lutActive, intensity: v })}+ onBefore={setBefore}+ onCancel={() => setLut(null)}+ onSave={saveLut}+ />+ );view = (<>- {g && from && showOriginal ? (+ {lutActive ? (+ <PlainFrame+ key={src}+ src={src}+ alt={g?.prompt ?? item.input?.original_name ?? ""}+ w={w}+ h={h}+ overlay={<LutOverlay src={urls.lutPreview(lutActive.name, lutActive.source, previewMax)} opacity={before ? 0 : lutActive.intensity} />}+ onFullscreen={openFull}+ />+ ) : g && from && showOriginal ? (<PlainFrame key={`original-${g.id}`} src={urls.genOriginal(g.id)} alt={`${g.prompt} (before upscaling)`} w={from.width} h={from.height} onFullscreen={openFull} />) : item.gen && base ? (<CompareFrame key={`compare-${item.gen.id}`} g={item.gen} base={base} maskSrc={maskSrc} onFullscreen={openFull} />) : (<PlainFrame key={src} src={src} alt={item.gen?.prompt ?? item.input?.original_name ?? ""} w={w} h={h} maskSrc={maskSrc} onFullscreen={openFull} />)}- <StageBar item={item} label={labels[item.key]} showOriginal={showOriginal} setShowOriginal={(on) => setOriginalOf(on && g ? g.id : null)} />+ <StageBar item={item} label={labels[item.key]} showOriginal={showOriginal} setShowOriginal={(on) => setOriginalOf(on && g ? g.id : null)} lutBar={lutBar} onLut={startLut} /></>);}diff --git a/src/lib/api.ts b/src/lib/api.tsindex dcb3455..c60efb5 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -3,7 +3,7 @@import type {GpuBackend,- AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, HardwareReport, InputRecord, InstallStatus, JobView, ModelFileInfo, ModelScan, ModelSlot, ModelsStatus, Plan,+ AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, HardwareReport, InputRecord, InstallStatus, JobView, LutEntry, ModelFileInfo, ModelScan, ModelSlot, ModelsStatus, Plan,ServiceEvent, SetupReport, StatusResponse, UpscalerItem,} from "./types";@@ -118,6 +118,13 @@ export const api = {deleteGeneration: (id: string) => call<{ deleted: string }>(`/gallery/${id}`, { method: "DELETE" }),/** Adds the bundled example projects to the gallery (idempotent) and lists them. */installExamples: () => call<{ projects: { title: string; generations: string[] }[] }>("/examples", { method: "POST" }),+ luts: () => call<{ items: LutEntry[] }>("/luts"),+ /** Adds a .cube file to the list (copied into Kokon's data folder). */+ importLut: (path: string) => call<LutEntry>("/luts/import", { method: "POST", body: json({ path }) }),+ removeLut: (name: string) => call<{ removed: string }>(`/luts/${encodeURIComponent(name)}`, { method: "DELETE" }),+ /** Saves `source` with the LUT applied as a new version; `intensity` 0-1. */+ applyLut: (name: string, source: string, intensity: number, isPrivate: boolean) =>+ call<GenerationRecord>(`/luts/${encodeURIComponent(name)}/apply`, { method: "POST", body: json({ source, intensity, private: isPrivate }) }),exportGeneration: (id: string, path: string, original = false) => call<{ path: string }>(`/gallery/${id}/export`, { method: "POST", body: json({ path, overwrite: true, original }) }),};@@ -130,6 +137,8 @@ export const urls = {genOriginal: (id: string) => `${base}/gallery/${id}/original?token=${token}`,/** Full image for a "gen:<id>" / "input:<id>" source. */source: (s: string) => (s.startsWith("gen:") ? urls.gen(s.slice(4)) : urls.input(s.slice(6))),+ /** A LUT on a "gen:"/"input:" source at full strength, at most `max` px on its long side. */+ lutPreview: (name: string, source: string, max: number) => `${base}/luts/${encodeURIComponent(name)}/preview?source=${encodeURIComponent(source)}&max=${max}&token=${token}`,sourceThumb: (s: string) => (s.startsWith("gen:") ? urls.genThumb(s.slice(4)) : urls.inputThumb(s.slice(6))),};diff --git a/src/lib/logic.test.ts b/src/lib/logic.test.tsindex 249f710..a61b93d 100644--- a/src/lib/logic.test.ts+++ b/src/lib/logic.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import {- activeOverrides, buildRequest, compareBase, diffPixels, emptyComposer, expansionPixels, expansionPreset, jobFraction, jobLabel, moveRef, needsPrompt, normalizeQuality, persistentAdvanced, pipelineSummary,+ activeOverrides, buildRequest, compareBase, diffPixels, emptyComposer, expansionPixels, expansionPreset, jobFraction, jobLabel, lutInfo, moveRef, needsPrompt, normalizeQuality, persistentAdvanced, pipelineSummary,planPipeline, remainingSeconds, sizeForWidth, timeAgo, upscaleRequest, upscaleTargets, versionLabels, type Ref,neighbourAfterRemoval, previewIndex, starPromptDue, STAR_PROMPT_AFTER, formatBytes, formatDuration, installItemShort, installItemText, installProgress, installStep, installTimeLeft, timelineLinks, undoTarget, aspectLabel, parseRatio, sizeForRatio, expandToRatio, expandToSize, arcLayout,} from "./logic";@@ -182,8 +182,8 @@ describe("before / after comparison", () => {const rec = (mode: string, extra: Partial<GenerationRecord> = {}) =>({ mode, references: [{ index: 0, input_id: "in1", width: 1000, height: 500 }], outpaint: null, ...extra }) as unknown as GenerationRecord;- it("edits, inpaints and upscales compare against the whole source", () => {- for (const m of ["edit", "inpaint", "upscale"]) expect(compareBase(rec(m))).toEqual({ inputId: "in1", rect: { x: 0, y: 0, w: 1, h: 1 } });+ it("edits, inpaints, upscales and LUT results compare against the whole source", () => {+ for (const m of ["edit", "inpaint", "upscale", "lut"]) expect(compareBase(rec(m))).toEqual({ inputId: "in1", rect: { x: 0, y: 0, w: 1, h: 1 } });});it("an expanded image places the source inside the larger result", () => {@@ -191,6 +191,12 @@ describe("before / after comparison", () => {expect(b.rect).toEqual({ x: 0.25, y: 0, w: 0.5, h: 0.5 });});+ it("a LUT result says which LUT and how strong", () => {+ const lut = { name: "Warm Film", title: null, intensity: 0.8 };+ expect(lutInfo(rec("lut", { request: { mode: "lut", images: ["gen:a"], lut } as unknown as GenerationRecord["request"] }))).toEqual(lut);+ expect(lutInfo(rec("edit", { request: null }))).toBeNull();+ });+it("new images and multi-reference results have no before", () => {expect(compareBase(rec("generate"))).toBeNull();expect(compareBase(rec("multi_reference"))).toBeNull();diff --git a/src/lib/logic.ts b/src/lib/logic.tsindex fa56825..467c1cf 100644--- a/src/lib/logic.ts+++ b/src/lib/logic.ts@@ -1,6 +1,6 @@// Pure UI logic (unit-tested in logic.test.ts).-import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";+import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, LutInfo, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";export interface Ref {key: string;@@ -163,7 +163,7 @@ export function composerFromRecord(g: GenerationRecord, base: Composer): ComposeinpaintAction: req?.inpaint_action ?? "edit",outpaint: g.outpaint ? { ...g.outpaint, units: "pixels" } : null,// Upscales are started from the image toolbar, not the composer.- mode: req?.mode && req.mode !== "upscale" ? req.mode : "auto",+ mode: req?.mode && req.mode !== "upscale" && g.mode !== "lut" ? req.mode : "auto",quality: normalizeQuality(g.quality, base.quality),resolution: req?.resolution ?? base.resolution,aspect: req?.aspect_ratio ?? "auto",@@ -183,7 +183,7 @@ export function variationRequest(g: GenerationRecord): GenerationRequest | nullreturn { ...g.request, seed: null, client: "ui", parent_id: g.id };}-export const MODE_LABEL: Record<Mode, string> = {+export const MODE_LABEL: Record<Mode | "lut", string> = {auto: "Auto",generate: "Create",edit: "Edit",@@ -191,8 +191,14 @@ export const MODE_LABEL: Record<Mode, string> = {outpaint: "Expand",multi_reference: "Combine",upscale: "Upscale",+ lut: "LUT",};+/** The LUT a "lut" result was made with. */+export function lutInfo(g: GenerationRecord): LutInfo | null {+ return g.mode === "lut" ? ((g.request as unknown as { lut?: LutInfo } | null)?.lut ?? null) : null;+}+/** Short names within a project. Every image that starts something new (a new image, a new* seed of one, an import) gets the next number: "1", "2"… Everything made from it (edits,* edits of edits, combinations led by it, upscales) is numbered within it: "1.1", "1.2"…@@ -637,7 +643,7 @@ export interface CompareBase {export function compareBase(g: GenerationRecord): CompareBase | null {const r = g.references[0];// A new image or a combination of several has no single "before".- if (!r || !["edit", "inpaint", "outpaint", "upscale"].includes(g.mode)) return null;+ if (!r || !["edit", "inpaint", "outpaint", "upscale", "lut"].includes(g.mode)) return null;const o = g.outpaint;if (g.mode === "outpaint" && o) {// Expansion is in source pixels; the result is the source plus the expansion.diff --git a/src/lib/native.ts b/src/lib/native.tsindex d0c7dca..400932d 100644--- a/src/lib/native.ts+++ b/src/lib/native.ts@@ -24,8 +24,8 @@ export const native = {if (!r) return [];return Array.isArray(r) ? r : [r];},- pickFile: async (extensions: string[], defaultPath?: string): Promise<string | null> => {- const r = await open({ multiple: false, directory: false, defaultPath, filters: [{ name: "Model", extensions }] });+ pickFile: async (extensions: string[], defaultPath?: string, kind = "Model"): Promise<string | null> => {+ const r = await open({ multiple: false, directory: false, defaultPath, filters: [{ name: kind, extensions }] });return typeof r === "string" ? r : null;},pickFolder: async (defaultPath?: string): Promise<string | null> => {diff --git a/src/lib/store.ts b/src/lib/store.tsindex 080b46c..4e59b5f 100644--- a/src/lib/store.ts+++ b/src/lib/store.ts@@ -822,6 +822,17 @@ export async function submitRequest(req: GenerationRequest) {}}+/** A version the service made right away (a LUT applied): added after the others and+ * selected; editing carries on from it when the prompt was editing its source. */+export function addResult(g: GenerationRecord) {+ setState((s) => {+ const item: SessionItem = { key: newKey(), kind: "gen", gen: g };+ const src = g.request?.images?.[0];+ const composer = src && s.composer.refs[0]?.source === src ? { ...s.composer, refs: [refFromGen(g), ...s.composer.refs.slice(1)], mask: null, outpaint: null } : s.composer;+ return { session: [...s.session, item], selected: item.key, composer, redo: [] };+ });+}+export async function submitComposer() {const s = getState();const target = s.composer.refs[0]?.source;diff --git a/src/lib/types.ts b/src/lib/types.tsindex 8fe3171..15a0ae7 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -2,6 +2,8 @@export type Mode = "auto" | "generate" | "edit" | "inpaint" | "outpaint" | "multi_reference" | "upscale";export type ResolvedMode = Exclude<Mode, "auto">;+/** What made a saved result: a generation mode, or a colour LUT applied to an image. */+export type RecordMode = ResolvedMode | "lut";/** What an inpaint does in the painted area. */export type InpaintAction = "edit" | "remove" | "replace" | "add";/** Presets of the Turbo model (8 steps, no CFG): ~1 MP, ~1.5K, native 2K. */@@ -111,7 +113,7 @@ export interface PipelineRecord {export interface GenerationRecord {id: string;created_at: string;- mode: ResolvedMode;+ mode: RecordMode;prompt: string;negative_prompt: string;seed: number;@@ -141,6 +143,11 @@ export interface GenerationRecord {pipeline?: PipelineRecord | null;}+/** A .cube LUT in Kokon's list (most recently used first). */+export interface LutEntry { name: string; title: string | null; kind: "1d" | "3d"; size: number }+/** How a "lut" result was made (in its `request`). */+export interface LutInfo { name: string; title?: string | null; intensity: number }+export type JobStatus = "queued" | "starting_backend" | "preparing" | "running" | "saving" | "done" | "failed" | "cancelled";export type BackendStage = "preparing" | "encoding_images" | "encoding_prompt" | "generating" | "upscaling" | "refining" | "decoding" | "finishing";diff --git a/src/styles.css b/src/styles.cssindex 048aa77..d050a6b 100644--- a/src/styles.css+++ b/src/styles.css@@ -416,6 +416,20 @@ pre.diag { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font/* image box + full-screen button */.image-box { position: relative; }+/* LUT preview: the LUT image over the result, its opacity = the intensity. */+.lut-overlay { position: absolute; inset: 0; pointer-events: none; background: none; }+.lut-loading { position: absolute; top: 10px; left: 10px; display: grid; place-items: center; width: 30px; height: 30px; border-radius: 8px; background: var(--bg); color: var(--text-2); }+.lut-bar { align-items: center; flex-wrap: wrap; justify-content: center; }+.lut-bar .btn.primary { margin-left: 4px; }+.lut-current { max-width: 160px; overflow: hidden; text-overflow: ellipsis; }+.lut-intensity { display: inline-flex; align-items: center; gap: 8px; padding: 0 8px; font-size: 12px; color: var(--text-2); font-variant-numeric: tabular-nums; }+.lut-intensity input { width: 140px; }+.lut-intensity span { width: 38px; text-align: right; }+.lut-list { width: 300px; padding: 4px; display: flex; flex-direction: column; max-height: 360px; overflow: auto; }+.lut-list-title { padding: 6px 10px 4px; }+.lut-row { display: flex; align-items: center; gap: 2px; }+.lut-row .opt { flex: 1; min-width: 0; }+.lut-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.stage-img.fill { width: 100%; height: 100%; max-width: none; max-height: none; display: block; }.fullscreen-btn { position: absolute; top: 8px; right: 8px; z-index: 2; width: 30px; height: 30px; border-radius: 8px; display: grid; place-items: center; color: #fff; background: rgba(0, 0, 0, 0.5); opacity: 0.75; transition: opacity 0.15s; }.fullscreen-btn:hover, .fullscreen-btn:focus-visible { opacity: 1; background: rgba(0, 0, 0, 0.7); }