mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Color Lookup: Load 3D LUT opens the native file picker (#1947)
The Color Lookup properties' Load 3D LUT… entry opens the platform file picker (filtered to .cube, .3dl and .look, on desktop and web) and embeds the chosen LUT into that adjustment layer, replacing the typed-path field. A cancelled or invalid pick leaves the layer unchanged (#1749). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
a4fbb1245d
commit
bdbd43e63f
5 files changed
+123
-23
No files matched your search
@@ -275,8 +275,13 @@ fn services(inbox: Inbox) -> Services {
|
||||
})),
|
||||
file_dialog: Some(Box::new(|request, _parent, reply| match request {
|
||||
// The browser's file picker hands over the file's contents, not a path.
|
||||
FileDialogRequest::Open { .. } => wasm_bindgen_futures::spawn_local(async move {
|
||||
let picked = rfd::AsyncFileDialog::new().add_filter("All Formats", OPEN_EXTS).pick_file().await;
|
||||
FileDialogRequest::Open { extensions, .. } => wasm_bindgen_futures::spawn_local(async move {
|
||||
let dialog = if let Some(exts) = extensions {
|
||||
rfd::AsyncFileDialog::new().add_filter("Supported Files", &exts)
|
||||
} else {
|
||||
rfd::AsyncFileDialog::new().add_filter("All Formats", OPEN_EXTS)
|
||||
};
|
||||
let picked = dialog.pick_file().await;
|
||||
let answer = match picked {
|
||||
Some(file) => Some(FileDialogAnswer::Contents(file.file_name(), file.read().await)),
|
||||
None => None,
|
||||
|
||||
@@ -76,11 +76,16 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>,
|
||||
dialog = dialog.set_parent(parent);
|
||||
}
|
||||
let answer: Pin<Box<dyn Future<Output = Option<FileDialogAnswer>> + Send>> = match request {
|
||||
FileDialogRequest::Open { multiple, initial_dir } => {
|
||||
FileDialogRequest::Open { multiple, initial_dir, extensions } => {
|
||||
if let Some(dir) = initial_dir {
|
||||
dialog = dialog.set_directory(dir);
|
||||
}
|
||||
let dialog = dialog.add_filter("All Formats", &open_filter_extensions(OPEN_EXTS)).add_filter("PhotoCraft", &open_filter_extensions(&["pcraft"]));
|
||||
// A command-specific filter must not inherit the image formats used by File › Open.
|
||||
let dialog = if let Some(exts) = extensions {
|
||||
dialog.add_filter("Supported Files", &open_filter_extensions(&exts.iter().map(String::as_str).collect::<Vec<_>>()))
|
||||
} else {
|
||||
dialog.add_filter("All Formats", &open_filter_extensions(OPEN_EXTS)).add_filter("PhotoCraft", &open_filter_extensions(&["pcraft"]))
|
||||
};
|
||||
if multiple {
|
||||
let picked = dialog.pick_files();
|
||||
Box::pin(async move { picked.await.map(|files| FileDialogAnswer::Paths(files.iter().map(path_of).collect())) })
|
||||
|
||||
@@ -78,6 +78,18 @@ pub fn selective_color_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: La
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the platform for one LUT. Send embedded text through the same engine command on
|
||||
/// desktop and web, so the result doesn't depend on ambient filesystem permissions.
|
||||
fn browse_color_lookup(app: &mut PhotocraftApp, layer: LayerId) -> Result<Value, String> {
|
||||
let doc = app.active_doc_id()?;
|
||||
app.pick_file_bytes_filtered(&["cube", "3dl", "look"], move |app, file_name, bytes| {
|
||||
// Reject invalid UTF-8 instead of silently changing the LUT before parsing.
|
||||
let data = String::from_utf8(bytes).map_err(|_| format!("{file_name}: LUT must contain UTF-8 text"))?;
|
||||
app.refocus(doc)?;
|
||||
app.run("layer.setAdjustment", json!({"layer": layer.0, "fileName": file_name, "data": data}))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn color_lookup_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj: &Adjustment) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Adjustment::ColorLookup { name, lut, size, tetrahedral, dither } = adj else {
|
||||
@@ -87,31 +99,31 @@ pub fn color_lookup_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: Layer
|
||||
let current =
|
||||
if lut.is_none() { "none".to_string() } else { builtins.iter().find(|b| b.1 == name).map_or_else(|| "custom".to_string(), |b| b.0.to_string()) };
|
||||
let custom_label = format!("{name} ({size}³)");
|
||||
let mut opts: Vec<(String, &str)> = vec![("none".into(), tl!("Load 3D LUT…"))];
|
||||
let mut opts: Vec<(String, &str)> = vec![("load".into(), tl!("Load 3D LUT…")), ("none".into(), tl!("None"))];
|
||||
opts.extend(builtins.iter().map(|(id, label)| (id.to_string(), *label)));
|
||||
if current == "custom" {
|
||||
opts.push(("custom".into(), custom_label.as_str()));
|
||||
}
|
||||
let mut sel = current.clone();
|
||||
let mut params: Option<Value> = None;
|
||||
let mut browse = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(tl!("3D LUT File")).color(t.text_dim));
|
||||
if widgets::dropdown(ui, &format!("clrl-{}", id.0), &mut sel, &opts, 170.0) && sel != current && sel != "custom" {
|
||||
params = Some(json!({"lut": sel}));
|
||||
}
|
||||
});
|
||||
// A path field stands in for the platform file picker (the desktop app's File menu has one).
|
||||
let path_key = egui::Id::new(("clrl-path", id.0));
|
||||
let mut path: String = ui.data(|d| d.get_temp(path_key)).unwrap_or_default();
|
||||
ui.horizontal(|ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut path).hint_text(".cube / .3dl / .look path").desired_width(170.0));
|
||||
if r.changed() {
|
||||
ui.data_mut(|d| d.insert_temp(path_key, path.clone()));
|
||||
}
|
||||
if widgets::secondary_button(ui, tl!("Load"), 60.0).clicked() && !path.trim().is_empty() {
|
||||
params = Some(json!({"file": path.trim()}));
|
||||
if widgets::dropdown(ui, &format!("clrl-{}", id.0), &mut sel, &opts, 170.0) {
|
||||
if sel == "load" {
|
||||
browse = true;
|
||||
} else if sel != current && sel != "custom" {
|
||||
params = Some(json!({"lut": sel}));
|
||||
}
|
||||
}
|
||||
});
|
||||
if browse
|
||||
&& let Err(e) = browse_color_lookup(app, id)
|
||||
&& e != crate::file_dialog::CANCELLED
|
||||
{
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let mut tet = *tetrahedral;
|
||||
ui.horizontal(|ui| {
|
||||
@@ -132,3 +144,59 @@ pub fn color_lookup_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: Layer
|
||||
let _ = app.run("layer.setAdjustment", p);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod lookup_picker_tests {
|
||||
use super::*;
|
||||
use crate::file_dialog::{self, FileDialogAnswer, FileDialogRequest};
|
||||
use serde_json::json;
|
||||
|
||||
const CUBE: &str = "LUT_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";
|
||||
|
||||
#[test]
|
||||
fn chosen_lut_is_embedded_into_the_requested_adjustment_layer() {
|
||||
let (dialog, asked) = file_dialog::fake(vec![Some(FileDialogAnswer::Contents("custom.cube".into(), CUBE.as_bytes().to_vec()))]);
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(dialog), ..Default::default() });
|
||||
app.run("file.new", json!({"width": 16, "height": 12})).unwrap();
|
||||
let layer = app.run("layer.newAdjustmentLayer.colorLookup", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
browse_color_lookup(&mut app, LayerId(layer)).unwrap();
|
||||
app.poll_file_dialog(&egui::Context::default(), None);
|
||||
assert!(
|
||||
matches!(asked.borrow().first(), Some(FileDialogRequest::Open { multiple: false, extensions: Some(exts), .. }) if exts.iter().map(String::as_str).collect::<Vec<_>>() == ["cube", "3dl", "look"])
|
||||
);
|
||||
app.poll_file_dialog(&egui::Context::default(), None);
|
||||
let adj = &app.session.active().unwrap().doc.layer(LayerId(layer)).unwrap().content;
|
||||
assert!(
|
||||
matches!(adj, photocraft_doc::LayerContent::Adjustment(Adjustment::ColorLookup { name, lut: Some(_), size: 2, .. }) if name == "custom.cube"),
|
||||
"{adj:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_lut_does_not_modify_the_existing_adjustment() {
|
||||
let (dialog, _) = file_dialog::fake(vec![Some(FileDialogAnswer::Contents("broken.cube".into(), b"invalid".to_vec()))]);
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(dialog), ..Default::default() });
|
||||
app.run("file.new", json!({"width": 16, "height": 12})).unwrap();
|
||||
let layer = app.run("layer.newAdjustmentLayer.colorLookup", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
let before = app.session.active().unwrap().doc.layer(LayerId(layer)).unwrap().content.clone();
|
||||
browse_color_lookup(&mut app, LayerId(layer)).unwrap();
|
||||
app.poll_file_dialog(&egui::Context::default(), None);
|
||||
app.poll_file_dialog(&egui::Context::default(), None);
|
||||
assert_eq!(app.session.active().unwrap().doc.layer(LayerId(layer)).unwrap().content, before);
|
||||
assert!(app.ui.status_error && app.ui.status.contains("colorLookup"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_the_lut_picker_preserves_the_adjustment() {
|
||||
let (dialog, _) = file_dialog::fake(vec![None]);
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(dialog), ..Default::default() });
|
||||
app.run("file.new", json!({"width": 16, "height": 12})).unwrap();
|
||||
let layer = app.run("layer.newAdjustmentLayer.colorLookup", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
let before = app.session.active().unwrap().doc.layer(LayerId(layer)).unwrap().content.clone();
|
||||
browse_color_lookup(&mut app, LayerId(layer)).unwrap();
|
||||
app.poll_file_dialog(&egui::Context::default(), None);
|
||||
app.poll_file_dialog(&egui::Context::default(), None);
|
||||
assert_eq!(app.session.active().unwrap().doc.layer(LayerId(layer)).unwrap().content, before);
|
||||
assert!(!app.ui.status_error);
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ use crate::file_open::display_name;
|
||||
pub enum FileDialogRequest {
|
||||
/// Files to read: several for File › Open, one for a command that reads a file (Place,
|
||||
/// scripts, notes, presets). Starts in `initial_dir` (the last-used folder, UI-217-3).
|
||||
Open { multiple: bool, initial_dir: Option<String> },
|
||||
Open { multiple: bool, initial_dir: Option<String>, extensions: Option<Vec<String>> },
|
||||
/// Where to write, starting from `suggested` (a file name, or the document's own path).
|
||||
Save { suggested: String },
|
||||
}
|
||||
@@ -138,8 +138,18 @@ impl PhotocraftApp {
|
||||
/// name (the full path on the desktop) and bytes. A file that can't be read fails with
|
||||
/// "<file name>: <why>".
|
||||
pub(crate) fn pick_file_bytes(&mut self, then: impl FnOnce(&mut Self, String, Vec<u8>) -> Result<Value, String> + 'static) -> Result<Value, String> {
|
||||
self.pick_file_bytes_filtered(&[], then)
|
||||
}
|
||||
|
||||
/// Same asynchronous picker, with a platform-native extension filter (desktop and web).
|
||||
pub(crate) fn pick_file_bytes_filtered(
|
||||
&mut self,
|
||||
extensions: &[&str],
|
||||
then: impl FnOnce(&mut Self, String, Vec<u8>) -> Result<Value, String> + 'static,
|
||||
) -> Result<Value, String> {
|
||||
let initial_dir = last_used_dir(&self.ui.recent_files);
|
||||
self.ask_file(FileDialogRequest::Open { multiple: false, initial_dir }, move |app, answer| {
|
||||
let extensions = (!extensions.is_empty()).then(|| extensions.iter().map(|s| (*s).to_string()).collect());
|
||||
self.ask_file(FileDialogRequest::Open { multiple: false, initial_dir, extensions }, move |app, answer| {
|
||||
let (name, bytes) = read_picked(answer)?;
|
||||
then(app, name, bytes)
|
||||
})
|
||||
@@ -148,7 +158,7 @@ impl PhotocraftApp {
|
||||
/// File › Open: opens every chosen file, reporting each failure (see [`Self::open_paths`]).
|
||||
pub fn open_dialog_file(&mut self) -> Result<Value, String> {
|
||||
let initial_dir = last_used_dir(&self.ui.recent_files);
|
||||
self.ask_file(FileDialogRequest::Open { multiple: true, initial_dir }, |app, answer| {
|
||||
self.ask_file(FileDialogRequest::Open { multiple: true, initial_dir, extensions: None }, |app, answer| {
|
||||
match answer {
|
||||
FileDialogAnswer::Paths(paths) => {
|
||||
app.open_paths(&paths);
|
||||
|
||||
@@ -39,12 +39,24 @@ fn open_starts_in_the_last_used_folder() {
|
||||
menus::invoke(&mut app, &ctx, "file.open", json!({})).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert!(
|
||||
matches!(open.borrow().as_slice(), [(FileDialogRequest::Open { multiple: true, initial_dir: Some(dir) }, _)] if dir == "/pics"),
|
||||
matches!(open.borrow().as_slice(), [(FileDialogRequest::Open { multiple: true, initial_dir: Some(dir), extensions: None }, _)] if dir == "/pics"),
|
||||
"{:?}",
|
||||
open.borrow().first().map(|(r, _)| r.clone())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtered_picker_requests_only_the_given_extensions() {
|
||||
let (mut app, open, _) = app();
|
||||
app.pick_file_bytes_filtered(&["cube", "3dl", "look"], |_, _, _| Ok(Value::Null)).unwrap();
|
||||
app.poll_file_dialog(&egui::Context::default(), None);
|
||||
assert!(matches!(
|
||||
open.borrow().first().map(|(r, _)| r),
|
||||
Some(FileDialogRequest::Open { multiple: false, extensions: Some(exts), .. })
|
||||
if exts.iter().map(String::as_str).collect::<Vec<_>>() == ["cube", "3dl", "look"]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_used_dir_takes_the_most_recent_parent() {
|
||||
assert_eq!(last_used_dir(&[]), None);
|
||||
|
||||
Reference in new issue
Block a user