cargo fmt --all

This commit is contained in:
skylartaylor committed 2026-11-26 03:35:55 +01:00
1 parent 7581754b06
commit a36a577c3b
115 files changed
+2408 -1645

No files matched your search

+12 -3
View File
@@ -223,7 +223,9 @@ impl eframe::App for App {
self.0.ui(ui);
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
if let Some(window) = &self.2 { self.0.drain_ui_completions(&window.ctx); }
if let Some(window) = &self.2 {
self.0.drain_ui_completions(&window.ctx);
}
// (a size the window was just given is remembered too)
self.0.ui.window = self.1.window_at_exit(self.0.ui.window);
if let Err(e) = self.1.save(&self.0) {
@@ -734,7 +736,11 @@ fn native_exit_drains_the_final_owned_output_before_shutdown() {
inner.install_framework(&ctx);
let mut app = App(inner, PrefsWriter::default(), Some(HostWindow { ctx: ctx.clone(), textures: None }), NightlyExit::none());
for _ in 0..3 {
ctx.run_ui(egui::RawInput::default(), |ui| { app.0.logic(ui.ctx()); app.0.ui(ui); }).drop_without_applying_deltas();
ctx.run_ui(egui::RawInput::default(), |ui| {
app.0.logic(ui.ctx());
app.0.ui(ui);
})
.drop_without_applying_deltas();
}
app.0.widgets.clear(); // make the last pending publication observable at the actual exit seam
eframe::App::on_exit(&mut app, None);
@@ -744,6 +750,9 @@ fn native_exit_drains_the_final_owned_output_before_shutdown() {
// Shutdown is process-global: isolate it just like the existing native on_exit tests.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "native_exit_drains_the_final_owned_output_before_shutdown", "--nocapture"])
.env("LIGHTCRAFT_TEST_COMPLETION_EXIT", "1").env("LIGHTCRAFT_NO_PREFS", "1").output().unwrap();
.env("LIGHTCRAFT_TEST_COMPLETION_EXIT", "1")
.env("LIGHTCRAFT_NO_PREFS", "1")
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stdout));
}
+146 -47
View File
@@ -1,7 +1,7 @@
//! Per-pass presentation facts only. Genuine input stays in the receiving app body.
use super::LightcraftApp;
use std::sync::{Weak, atomic::AtomicU8};
use crate::{control::ClipboardFacts, panels, state::GestureFrame, widgets::WidgetHit};
use std::sync::{Weak, atomic::AtomicU8};
pub(super) struct GestureFacts {
pub now_ms: f64,
@@ -15,8 +15,7 @@ pub(super) struct GestureFacts {
}
impl GestureFacts {
pub fn ready(&self, gesture: &crate::PendingGesture) -> bool {
gesture.resolved_pass.is_none() && self.now_ms <= gesture.deadline_ms
&& self.epoch > gesture.admitted_epoch && self.frame == gesture.frame
gesture.resolved_pass.is_none() && self.now_ms <= gesture.deadline_ms && self.epoch > gesture.admitted_epoch && self.frame == gesture.frame
}
}
pub(super) struct Snapshot {
@@ -40,18 +39,19 @@ pub(super) struct Completion {
ready: Vec<Snapshot>,
}
impl egui::Plugin for Completion {
fn debug_name(&self) -> &'static str { "lightcraft.host-completion" }
fn debug_name(&self) -> &'static str {
"lightcraft.host-completion"
}
fn on_begin_pass(&mut self, ui: &mut egui::Ui) {
// This instance belongs to ONE Context. Capture identity before end_pass pops a viewport.
self.stack.push(Pass {
owner: ui.ctx().viewport_id(), max_passes: ui.ctx().options(|o| o.max_passes.get()), body: None,
});
self.stack.push(Pass { owner: ui.ctx().viewport_id(), max_passes: ui.ctx().options(|o| o.max_passes.get()), body: None });
}
fn output_hook(&mut self, ctx: &egui::Context, output: &mut egui::FullOutput) {
let Some(pass) = self.stack.pop() else { return };
let Some(mut body) = pass.body else { return }; // early return / foreign body is not a layout
if output.platform_output.requested_discard()
&& output.platform_output.num_completed_passes < pass.max_passes { return; }
if output.platform_output.requested_discard() && output.platform_output.num_completed_passes < pass.max_passes {
return;
}
// Earlier nested output is already valid. Count that completion, never a newer live App frame.
if let Some(previous) = self.ready.last() {
body.gestures.passes = previous.gestures.passes.wrapping_add(1);
@@ -70,11 +70,15 @@ impl egui::Plugin for Completion {
let hidden = body.hidden;
self.ready.push(body);
// Hidden logic has no next body. Visible input/logic drains first; exit drains the last one.
if hidden { ctx.request_repaint_of(pass.owner); }
if hidden {
ctx.request_repaint_of(pass.owner);
}
}
}
pub(super) fn install(ctx: &egui::Context) {
if ctx.plugin_opt::<Completion>().is_none() { ctx.add_plugin(Completion::default()); }
if ctx.plugin_opt::<Completion>().is_none() {
ctx.add_plugin(Completion::default());
}
}
impl LightcraftApp {
pub(crate) fn capture_ui_completion(&mut self, ctx: &egui::Context) {
@@ -87,13 +91,18 @@ impl LightcraftApp {
self.synthetic_in_flight = false;
let body = self.presentation_snapshot(ctx);
if let Some(pass) = plugin.lock().stack.last_mut()
&& pass.owner == ctx.viewport_id() { pass.body = Some(body); }
&& pass.owner == ctx.viewport_id()
{
pass.body = Some(body);
}
}
/// Host seam: before any next App mutation, and immediately after the final headless output.
pub fn drain_ui_completions(&mut self, ctx: &egui::Context) {
let Some(plugin) = ctx.plugin_opt::<Completion>() else { return };
let ready = std::mem::take(&mut plugin.lock().ready);
for body in ready { self.apply_ui_completion(ctx, body); }
for body in ready {
self.apply_ui_completion(ctx, body);
}
}
}
@@ -101,7 +110,10 @@ impl LightcraftApp {
mod tests {
use super::Completion;
use crate::{LightcraftApp, Services};
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
fn app(ctx: &egui::Context) -> LightcraftApp {
let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
app.install_framework(ctx);
@@ -109,7 +121,11 @@ mod tests {
app
}
fn raw() -> egui::RawInput {
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))), time: Some(7.0), ..Default::default() }
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))),
time: Some(7.0),
..Default::default()
}
}
/// A framework text field named `name`: the paste target the host needs (an `egui` text editor holding the focus).
/// `begin` asks for the focus before the field's first input.
@@ -130,9 +146,8 @@ mod tests {
fn marker(app: &mut LightcraftApp, name: &str) {
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(20.0, 20.0));
app.next_widgets = vec![(name.into(), rect)];
app.next_widget_hits = vec![(name.into(), crate::widgets::WidgetHit {
id: egui::Id::unique(name), layer_id: egui::LayerId::background(), interact_rect: rect,
})];
app.next_widget_hits =
vec![(name.into(), crate::widgets::WidgetHit { id: egui::Id::unique(name), layer_id: egui::LayerId::background(), interact_rect: rect })];
}
#[test]
fn genuine_input_is_visible_before_late_discard_and_empty_retry_never_replays_it() {
@@ -140,10 +155,15 @@ mod tests {
let mut app = app(&ctx);
let effects = Arc::new(AtomicUsize::new(0));
let seen = effects.clone();
ctx.on_end_pass("late SDK discard", Arc::new(move |ui| {
assert_eq!(seen.load(Ordering::SeqCst), 1, "effect already committed before the late hook");
if ui.ctx().current_pass_index() == 0 { ui.ctx().request_discard("late sizing"); }
}));
ctx.on_end_pass(
"late SDK discard",
Arc::new(move |ui| {
assert_eq!(seen.load(Ordering::SeqCst), 1, "effect already committed before the late hook");
if ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("late sizing");
}
}),
);
let mut input = raw();
input.events.push(egui::Event::Text("accepted".into()));
let mut passes = 0;
@@ -200,7 +220,8 @@ mod tests {
marker(&mut app, "own");
app.pointer_cleanup = true;
app.capture_ui_completion(ui.ctx());
}).drop_without_applying_deltas();
})
.drop_without_applying_deltas();
app.set_simulated_clock(Some(100000.0));
app.ui_passes = 900;
app.layout_epoch = 900;
@@ -229,7 +250,11 @@ mod tests {
let mut app = app(&ctx);
let mut input = raw();
input.viewports.entry(egui::ViewportId::ROOT).or_default().minimized = Some(true);
ctx.run_ui(input, |ui| { marker(&mut app, "hidden"); app.capture_ui_completion(ui.ctx()); }).drop_without_applying_deltas();
ctx.run_ui(input, |ui| {
marker(&mut app, "hidden");
app.capture_ui_completion(ui.ctx());
})
.drop_without_applying_deltas();
assert_eq!(app.ui_passes, 0);
assert!(ctx.has_requested_repaint(), "output hook woke ordinary hidden logic");
app.logic(&ctx);
@@ -245,7 +270,11 @@ mod tests {
let (reply, rx) = std::sync::mpsc::channel();
app.admit_gesture(&ctx, "ui.clickWidget".into(), serde_json::json!({"id": "new-target"}), reply).unwrap();
app.ui.filmstrip = !app.ui.filmstrip;
ctx.run_ui(raw(), |ui| { marker(&mut app, "new-target"); app.capture_ui_completion(ui.ctx()); }).drop_without_applying_deltas();
ctx.run_ui(raw(), |ui| {
marker(&mut app, "new-target");
app.capture_ui_completion(ui.ctx());
})
.drop_without_applying_deltas();
app.drain_ui_completions(&ctx);
let response = rx.try_recv().unwrap();
assert_eq!(response["ok"], false);
@@ -275,7 +304,10 @@ mod tests {
assert!(rx.try_recv().is_err(), "queueing a host command is not delivery");
let mut next = ctx.run_ui(raw(), |ui| app.capture_ui_completion(ui.ctx()));
next.textures_delta.clear();
assert!(next.viewport_output.values().all(|v| v.commands.iter().all(|c| !matches!(c, egui::ViewportCommand::RequestPaste))), "drain did not reissue a command");
assert!(
next.viewport_output.values().all(|v| v.commands.iter().all(|c| !matches!(c, egui::ViewportCommand::RequestPaste))),
"drain did not reissue a command"
);
app.drain_ui_completions(&ctx);
assert_eq!(rx.try_recv().unwrap()["ok"], true, "queue acknowledgement only, not host delivery");
}
@@ -286,8 +318,10 @@ mod tests {
let mut app = app(&ctx);
let child = egui::ViewportId::from_hash_of("paste-child");
let (stale, stale_rx) = std::sync::mpsc::channel();
app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({}), stale).unwrap(); app.pending_gestures[0].deadline_ms = 0.0;
let mut text = String::new(); let mut parent_text = String::new();
app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({}), stale).unwrap();
app.pending_gestures[0].deadline_ms = 0.0;
let mut text = String::new();
let mut parent_text = String::new();
// both viewports' fields hold their own keyboard focus before the pass under test
focus_field(&ctx, egui::ViewportId::ROOT, "parent-field", &mut parent_text);
focus_field(&ctx, child, "child-field", &mut text);
@@ -296,11 +330,19 @@ mod tests {
let survivor = Arc::downgrade(&app.pending_gestures[1].completion);
let (fence, _fence_rx) = std::sync::mpsc::channel();
app.admit_gesture(&ctx, "ui.move".into(), serde_json::json!({}), fence).unwrap();
ctx.on_end_pass("nested sizing discard", Arc::new(move |ui| {
if discard && ui.ctx().current_pass_index() == 0 { ui.ctx().request_discard("late parent/child sizing"); }
}));
ctx.on_end_pass(
"nested sizing discard",
Arc::new(move |ui| {
if discard && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("late parent/child sizing");
}
}),
);
let mut outer = ctx.run_ui(raw(), |ui| {
if ui.ctx().current_pass_index() > 0 { app.capture_ui_completion(ui.ctx()); return; }
if ui.ctx().current_pass_index() > 0 {
app.capture_ui_completion(ui.ctx());
return;
}
ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste); // unrelated parent request
field(ui, "parent-field", &mut parent_text, false);
app.capture_ui_completion(ui.ctx()); // SAME pending paste in BOTH real candidates
@@ -308,20 +350,46 @@ mod tests {
input.viewport_id = child;
input.viewports.entry(child).or_default().parent = Some(egui::ViewportId::ROOT);
let mut own = ctx.run_ui(input, |child_ui| {
if cancel { app.cancel_gestures_for_barrier(false, "nested prompt"); }
if cancel {
app.cancel_gestures_for_barrier(false, "nested prompt");
}
field(child_ui, "child-field", &mut text, false);
child_ui.ctx().send_viewport_cmd(egui::ViewportCommand::Title("unrelated child".into()));
app.capture_ui_completion(child_ui.ctx());
});
own.textures_delta.clear();
assert_eq!(own.viewport_output.get(&child).unwrap().commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaste)).count(), if cancel { 0 } else { 1 });
assert!(own.viewport_output.get(&child).unwrap().commands.iter().any(|c| matches!(c, egui::ViewportCommand::Title(s) if s == "unrelated child")));
assert_eq!(
own.viewport_output.get(&child).unwrap().commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaste)).count(),
if cancel { 0 } else { 1 }
);
assert!(
own.viewport_output
.get(&child)
.unwrap()
.commands
.iter()
.any(|c| matches!(c, egui::ViewportCommand::Title(s) if s == "unrelated child"))
);
assert!(own.viewport_output.get(&egui::ViewportId::ROOT).unwrap().commands.is_empty(), "child output did not steal parent commands");
if drain { app.drain_ui_completions(&ctx); }
if drain && !cancel { app.pending_gestures[0].deadline_ms += 2000.0; }
if drain {
app.drain_ui_completions(&ctx);
}
if drain && !cancel {
app.pending_gestures[0].deadline_ms += 2000.0;
}
});
outer.textures_delta.clear();
assert_eq!(outer.viewport_output.get(&egui::ViewportId::ROOT).unwrap().commands.iter().filter(|c| matches!(c, egui::ViewportCommand::RequestPaste)).count(), 1);
assert_eq!(
outer
.viewport_output
.get(&egui::ViewportId::ROOT)
.unwrap()
.commands
.iter()
.filter(|c| matches!(c, egui::ViewportCommand::RequestPaste))
.count(),
1
);
app.drain_ui_completions(&ctx);
assert_eq!((app.ui_passes, app.layout_epoch), (2, 2));
if cancel {
@@ -332,7 +400,8 @@ mod tests {
assert_eq!(app.pending_gestures[0].resolved_pass, Some(1));
assert!(Arc::ptr_eq(&survivor.upgrade().unwrap(), &app.pending_gestures[0].completion));
assert_eq!(app.pending_gestures[0].deadline_ms, if drain { 17000.0 } else { 15000.0 });
assert_eq!(stale_rx.try_recv().unwrap()["ok"], false); assert!(rx.try_recv().is_err(), "no false failure/ack while own input remains queued");
assert_eq!(stale_rx.try_recv().unwrap()["ok"], false);
assert!(rx.try_recv().is_err(), "no false failure/ack while own input remains queued");
}
}
#[test]
@@ -343,9 +412,14 @@ mod tests {
let mut app = app(&ctx);
super::install(&other);
let child = egui::ViewportId::from_hash_of("child");
ctx.on_end_pass("discard child sizing", Arc::new(move |ui| {
if ui.ctx().viewport_id() == child && ui.ctx().current_pass_index() == 0 { ui.ctx().request_discard("child sizing"); }
}));
ctx.on_end_pass(
"discard child sizing",
Arc::new(move |ui| {
if ui.ctx().viewport_id() == child && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("child sizing");
}
}),
);
let mut output = ctx.run_ui(raw(), |ui| {
marker(&mut app, "parent");
app.capture_ui_completion(ui.ctx());
@@ -359,22 +433,47 @@ mod tests {
child_ui.ctx().send_viewport_cmd(egui::ViewportCommand::Title("child-output".into()));
});
nested.textures_delta.clear();
assert!(nested.viewport_output.get(&child).unwrap().commands.iter().any(|c| matches!(c, egui::ViewportCommand::Title(s) if s == "child-output")));
assert!(
nested
.viewport_output
.get(&child)
.unwrap()
.commands
.iter()
.any(|c| matches!(c, egui::ViewportCommand::Title(s) if s == "child-output"))
);
assert_eq!(ui.ctx().viewport_id(), egui::ViewportId::ROOT);
if drain { app.drain_ui_completions(&ctx); assert_eq!(app.ui_passes, index + 1); }
if drain {
app.drain_ui_completions(&ctx);
assert_eq!(app.ui_passes, index + 1);
}
}
other.run_ui(raw(), |_| {}).drop_without_applying_deltas();
});
output.textures_delta.clear();
assert!(output.viewport_output.get(&egui::ViewportId::ROOT).unwrap().commands.iter().all(|c| !matches!(c, egui::ViewportCommand::RequestPaste)), "child command was not reissued to popped parent");
assert!(
output
.viewport_output
.get(&egui::ViewportId::ROOT)
.unwrap()
.commands
.iter()
.all(|c| !matches!(c, egui::ViewportCommand::RequestPaste)),
"child command was not reissued to popped parent"
);
let plugin = ctx.plugin::<Completion>();
let mut completion = plugin.lock();
let ready = std::mem::take(&mut completion.ready);
assert_eq!(ready.iter().map(|s| s.widgets[0].0.as_str()).collect::<Vec<_>>(), if drain { vec!["parent"] } else { vec!["child", "parent"] });
assert_eq!(
ready.iter().map(|s| s.widgets[0].0.as_str()).collect::<Vec<_>>(),
if drain { vec!["parent"] } else { vec!["child", "parent"] }
);
assert_eq!(ready.iter().map(|s| s.gestures.passes).collect::<Vec<_>>(), if drain { vec![3] } else { vec![1, 2] });
assert!(completion.stack.is_empty());
assert!(other.plugin::<Completion>().lock().ready.is_empty());
completion.ready = ready; drop(completion); app.drain_ui_completions(&ctx);
completion.ready = ready;
drop(completion);
app.drain_ui_completions(&ctx);
let total = if drain { 3 } else { 2 };
assert_eq!((app.ui_passes, app.layout_epoch), (total, total), "all and only valid children plus parent, across drains/discards");
}
+39 -13
View File
@@ -1,6 +1,6 @@
use super::completion::GestureFacts;
use super::{ControlResponse, GESTURE_TIMEOUT_MS, GestureFrame, LightcraftApp, MAX_PENDING_GESTURES, PendingGesture, Sender, Value};
use crate::control;
use super::completion::GestureFacts;
impl LightcraftApp {
/// Take the control receiver for this frame, run every queued request whose sender still
@@ -81,16 +81,31 @@ impl LightcraftApp {
/// completed. A changed view/document/dialog/panel state cancels instead of retargeting.
pub(super) fn completion_gestures(&self, ctx: &egui::Context, epoch: u64, passes: u64) -> GestureFacts {
let mut facts = GestureFacts {
now_ms: self.tick_now_ms(), frame: self.gesture_frame(), epoch, passes,
now_ms: self.tick_now_ms(),
frame: self.gesture_frame(),
epoch,
passes,
deadlines: self.pending_gestures.iter().map(|gesture| (std::sync::Arc::downgrade(&gesture.completion), gesture.deadline_ms)).collect(),
clipboard: control::ClipboardFacts::capture(self, ctx), pastes: Some(Vec::new()),
clipboard: control::ClipboardFacts::capture(self, ctx),
pastes: Some(Vec::new()),
};
facts.pastes = Some(self.pending_gestures.iter().filter_map(|gesture| {
(gesture.resolved_pass.is_none() && gesture.method == "ui.clipboard"
&& gesture.params.get("action").and_then(Value::as_str) == Some("paste")
&& gesture.params.get("text").and_then(Value::as_str).is_none()).then(||
(std::sync::Arc::downgrade(&gesture.completion), facts.ready(gesture) && control::check_gesture_numbers(&gesture.method, &gesture.params).is_ok()))
}).collect());
facts.pastes = Some(
self.pending_gestures
.iter()
.filter_map(|gesture| {
(gesture.resolved_pass.is_none()
&& gesture.method == "ui.clipboard"
&& gesture.params.get("action").and_then(Value::as_str) == Some("paste")
&& gesture.params.get("text").and_then(Value::as_str).is_none())
.then(|| {
(
std::sync::Arc::downgrade(&gesture.completion),
facts.ready(gesture) && control::check_gesture_numbers(&gesture.method, &gesture.params).is_ok(),
)
})
})
.collect(),
);
facts
}
pub(crate) fn resolve_pending_gestures(&mut self, ctx: &egui::Context) {
@@ -107,8 +122,11 @@ impl LightcraftApp {
let mut keep = Vec::with_capacity(gestures.len());
for mut gesture in gestures.drain(..) {
// Allocation identity survives earlier removals; never undo a later progress refresh.
let Some((_, deadline)) = facts.deadlines.iter().find(|(id, _)| id.upgrade().is_some_and(|id| std::sync::Arc::ptr_eq(&id, &gesture.completion))) else {
keep.push(gesture); continue; // admitted after this body: wait for its own captured layout
let Some((_, deadline)) =
facts.deadlines.iter().find(|(id, _)| id.upgrade().is_some_and(|id| std::sync::Arc::ptr_eq(&id, &gesture.completion)))
else {
keep.push(gesture);
continue; // admitted after this body: wait for its own captured layout
};
gesture.deadline_ms = gesture.deadline_ms.max(*deadline);
if gesture.resolved_pass.is_some() {
@@ -138,8 +156,16 @@ impl LightcraftApp {
let before = self.synthetic.len();
let outcome = match &facts.pastes {
None => control::gesture_events(self, ctx, &gesture.method, &gesture.params),
Some(claims) => control::gesture_events_at(self, ctx, &gesture.method, &gesture.params,
facts.clipboard, control::PasteDispatch::OwnOutput(claims.iter().any(|(id, _)| id.upgrade().is_some_and(|id| std::sync::Arc::ptr_eq(&id, &gesture.completion))))),
Some(claims) => control::gesture_events_at(
self,
ctx,
&gesture.method,
&gesture.params,
facts.clipboard,
control::PasteDispatch::OwnOutput(
claims.iter().any(|(id, _)| id.upgrade().is_some_and(|id| std::sync::Arc::ptr_eq(&id, &gesture.completion))),
),
),
};
match outcome {
Ok(outcome) => {
+7 -4
View File
@@ -1,9 +1,9 @@
use super::completion::Snapshot;
use super::{
LightcraftApp, drop_overlay, export_task, focus_scan, import, lightroom_import, merge, monotonic_ms, panels, pick, recheck, shortcuts,
slideshow_export, state, sync, tasks, theme, updates_ui, widgets,
};
use crate::startup;
use super::completion::Snapshot;
impl LightcraftApp {
/// Install/refresh fonts once and watch the device and availability caches. Setup, not input.
@@ -382,11 +382,14 @@ impl LightcraftApp {
pub(super) fn presentation_snapshot(&mut self, ctx: &egui::Context) -> Snapshot {
Snapshot {
widgets: std::mem::take(&mut self.next_widgets), hits: std::mem::take(&mut self.next_widget_hits),
image: self.image_rect, ui_time: ctx.input(|i| i.time),
widgets: std::mem::take(&mut self.next_widgets),
hits: std::mem::take(&mut self.next_widget_hits),
image: self.image_rect,
ui_time: ctx.input(|i| i.time),
hidden: ctx.input(|i| i.viewport().visible() == Some(false)),
gestures: self.completion_gestures(ctx, self.layout_epoch.wrapping_add(1), self.ui_passes.wrapping_add(1)),
notice: panels::notices::capture_completion(self), library: panels::library_problem::capture_completion(self),
notice: panels::notices::capture_completion(self),
library: panels::library_problem::capture_completion(self),
}
}
pub(super) fn apply_ui_completion(&mut self, ctx: &egui::Context, body: Snapshot) {
+51 -17
View File
@@ -17,7 +17,6 @@ use super::LightcraftApp;
static SIZES: LazyLock<Arc<craft::theme::AppSizes>> =
LazyLock::new(|| Arc::new(craft::theme::AppSizes::parse_or_default(br#"{ "all": { "size.bar.title": 42, "size.rail.width": 48 } }"#)));
/// One current derived size set per context. Changes replace it rather than accumulating
/// width/theme/scale entries, while an unchanged extent retains the SDK token-cache identity.
fn shell_sizes(ctx: &egui::Context) -> Arc<craft::theme::AppSizes> {
@@ -138,8 +137,19 @@ mod intrinsic_shell_tests {
/// of the source-level intrinsic formula. It compares the actual old and new drawing paths.
#[test]
fn shell_matches_actual_legacy_canvas_and_rail_rectangles() {
const RAIL: &[&str] = &["icon:presets", "icon:edit", "icon:crop", "icon:remove", "icon:masking", "icon:redeye",
"icon:versions", "icon:activity", "icon:more", "icon:keywords", "icon:info"];
const RAIL: &[&str] = &[
"icon:presets",
"icon:edit",
"icon:crop",
"icon:remove",
"icon:masking",
"icon:redeye",
"icon:versions",
"icon:activity",
"icon:more",
"icon:keywords",
"icon:info",
];
for width in [1025.0, 1400.0] {
for scale in [1.0, 1.25] {
for zoom in [1.0, 1.25] {
@@ -163,9 +173,7 @@ mod intrinsic_shell_tests {
let b = shell_sizes(&ctx);
assert!(Arc::ptr_eq(&a, &b));
}
fn capture_side(width: f32, scale: f32, zoom: f32, rtl: bool, adapted: bool)
-> (egui::Rect, Vec<(String, egui::Rect, egui::Rect)>)
{
fn capture_side(width: f32, scale: f32, zoom: f32, rtl: bool, adapted: bool) -> (egui::Rect, Vec<(String, egui::Rect, egui::Rect)>) {
let mut app = LightcraftApp::new(lightcraft_engine::Session::new(), crate::Services::default());
let mut view = HeadlessView::new();
view.ctx.set_zoom_factor(zoom);
@@ -183,14 +191,20 @@ mod intrinsic_shell_tests {
let host_style = ui.style().clone();
AppShell::new(WindowKey::main())
.screen_mode(Bind::given(ScreenMode::Standard))
.allow_reveal(false).edge_reveal(false).document_tabs(false)
.allow_reveal(false)
.edge_reveal(false)
.document_tabs(false)
.title_bar(|ui, _cx, app| {
if craft::ui::runtime::measure::active(ui.ctx()) { return; }
if craft::ui::runtime::measure::active(ui.ctx()) {
return;
}
ui.set_style(host_style.clone());
crate::panels::topbar::show(app, ui);
})
.end(Slot::new("lightcraft.tools"), |ui, cx, app| {
if craft::ui::runtime::measure::active(ui.ctx()) { return; }
if craft::ui::runtime::measure::active(ui.ctx()) {
return;
}
ui.set_style(host_style.clone());
if adapted {
crate::panels::strip::show_in_shell(app, ui, cx.env.direction().is_rtl());
@@ -199,14 +213,32 @@ mod intrinsic_shell_tests {
}
})
.body(|ui, cx, _app| {
if craft::ui::runtime::measure::active(ui.ctx()) { return; }
if craft::ui::runtime::measure::active(ui.ctx()) {
return;
}
body = cx.shell().expect("shell body").regions().body;
}).show(ui, &mut app);
})
.show(ui, &mut app);
});
let (rects, registered) = crate::widgets::take_registries(&view.ctx);
hits = registered.iter().filter(|(id, _)| matches!(id.as_str(),
"icon:presets" | "icon:edit" | "icon:crop" | "icon:remove" | "icon:masking" |
"icon:redeye" | "icon:versions" | "icon:activity" | "icon:more" | "icon:keywords" | "icon:info"))
hits = registered
.iter()
.filter(|(id, _)| {
matches!(
id.as_str(),
"icon:presets"
| "icon:edit"
| "icon:crop"
| "icon:remove"
| "icon:masking"
| "icon:redeye"
| "icon:versions"
| "icon:activity"
| "icon:more"
| "icon:keywords"
| "icon:info"
)
})
.map(|(id, hit)| (id.clone(), rects.iter().find(|(name, _)| name == id).expect("registered rect").1, hit.interact_rect))
.collect();
}
@@ -225,12 +257,14 @@ mod intrinsic_shell_tests {
assert_eq!(new_hits, old_hits, "rectangles AND clipped interaction areas: width={width} scale={scale} zoom={zoom} rtl={rtl}");
assert_eq!((old_body.top(), old_body.bottom()), (new_body.top(), new_body.bottom()));
assert!(new_body.width() >= old_body.width(), "the workspace cannot lose more width");
if rtl { assert_eq!(old_body.right(), new_body.right()); }
else { assert_eq!(old_body.left(), new_body.left()); }
if rtl {
assert_eq!(old_body.right(), new_body.right());
} else {
assert_eq!(old_body.left(), new_body.left());
}
}
}
}
}
}
}
+35 -9
View File
@@ -692,12 +692,24 @@ impl ClipboardFacts {
}
Ok(())
}
pub(crate) fn append_paste(self, output: &mut egui::FullOutput, owner: egui::ViewportId, claim: &std::sync::atomic::AtomicU8, eligible: bool) -> bool {
pub(crate) fn append_paste(
self,
output: &mut egui::FullOutput,
owner: egui::ViewportId,
claim: &std::sync::atomic::AtomicU8,
eligible: bool,
) -> bool {
use std::sync::atomic::Ordering::SeqCst;
// State is an output fact, NOT identity: 0 unclaimed, 1 claimed/no paste, 2 appended.
if claim.compare_exchange(0, 1, SeqCst, SeqCst).is_err() { return claim.load(SeqCst) == 2; }
if !eligible { return false; }
if self.check().is_err() { return false; }
if claim.compare_exchange(0, 1, SeqCst, SeqCst).is_err() {
return claim.load(SeqCst) == 2;
}
if !eligible {
return false;
}
if self.check().is_err() {
return false;
}
let Some(viewport) = output.viewport_output.get_mut(&owner) else { return false };
viewport.commands.push(egui::ViewportCommand::RequestPaste);
claim.store(2, SeqCst);
@@ -723,7 +735,12 @@ pub(crate) fn gesture_events(app: &mut LightcraftApp, ctx: &egui::Context, metho
}
pub(crate) fn gesture_events_at(
app: &mut LightcraftApp, ctx: &egui::Context, method: &str, p: &Value, clipboard: ClipboardFacts, paste: PasteDispatch,
app: &mut LightcraftApp,
ctx: &egui::Context,
method: &str,
p: &Value,
clipboard: ClipboardFacts,
paste: PasteDispatch,
) -> Result<GestureOutcome, String> {
check_gesture_numbers(method, p)?;
let s = |k: &str| p.get(k).and_then(Value::as_str);
@@ -737,7 +754,11 @@ pub(crate) fn gesture_events_at(
let mut at = egui::pos2(r.left() + r.width() * fx as f32, r.top() + r.height() * fy as f32);
// With no point asked for, aim at the middle of the part a person can see: a row wider than its
// scrolled panel, or a control half under the edge of its pane, still takes a click there.
if f("fx").is_none() && f("fy").is_none() && let Some(seen) = visible_part(ctx, widget_hit(app, id), r) && !seen.contains(at) {
if f("fx").is_none()
&& f("fy").is_none()
&& let Some(seen) = visible_part(ctx, widget_hit(app, id), r)
&& !seen.contains(at)
{
at = seen.center();
}
if !fx.is_finite() || !fy.is_finite() || !at.is_finite() {
@@ -848,7 +869,9 @@ pub(crate) fn gesture_events_at(
// below cannot promise dispatch or delivery. With `text`, the synthetic
// Event::Paste is filtered and canceled like other injected input.
// The exact request's successful own-output witness already passed this one eligibility engine.
if !(matches!(paste, PasteDispatch::OwnOutput(true)) && s("action") == Some("paste") && s("text").is_none()) { clipboard.check()?; }
if !(matches!(paste, PasteDispatch::OwnOutput(true)) && s("action") == Some("paste") && s("text").is_none()) {
clipboard.check()?;
}
match s("action") {
Some("cut") => app.synthetic.push(egui::Event::Cut),
Some("copy") => app.synthetic.push(egui::Event::Copy),
@@ -856,7 +879,7 @@ pub(crate) fn gesture_events_at(
Some(text) => app.synthetic.push(egui::Event::Paste(text.to_string())),
None => match paste {
PasteDispatch::Context => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste),
PasteDispatch::OwnOutput(true) => {},
PasteDispatch::OwnOutput(true) => {}
PasteDispatch::OwnOutput(false) => return Err("ui.clipboard: its own paste output is unavailable".into()),
},
},
@@ -989,6 +1012,9 @@ mod completion_clipboard_tests {
assert!(app.synthetic.is_empty());
let claim = std::sync::atomic::AtomicU8::new(0);
assert!(!own.append_paste(&mut output, egui::ViewportId::ROOT, &claim, false));
assert!(!own.append_paste(&mut output, egui::ViewportId::ROOT, &claim, true), "a later candidate cannot revive the earlier refused completion");
assert!(
!own.append_paste(&mut output, egui::ViewportId::ROOT, &claim, true),
"a later candidate cannot revive the earlier refused completion"
);
}
}
+52 -90
View File
@@ -21,11 +21,11 @@ pub use confirm::confirm_dialog;
pub use cull::{MAX_BURST_GAP, clamp_cull_burst, cull_params, fmt_gap, parse_gap};
use export::group_checklist;
pub(crate) use export::preset_lzw_note;
pub use frame::{ConfirmStyle, confirm_style, list_height, prompt};
pub(crate) use frame::field_escape_closes;
pub use frame::{ConfirmStyle, confirm_style, list_height, prompt};
use frame::{
DIALOG_CHROME_GUESS, DIALOG_MIN_BODY, DIALOG_SCREEN_MARGIN, clicked_backdrop, dialog_field, escaped_field, field, fit_lists, just_opened, only_shows,
return_confirms,
DIALOG_CHROME_GUESS, DIALOG_MIN_BODY, DIALOG_SCREEN_MARGIN, clicked_backdrop, dialog_field, escaped_field, field, fit_lists, just_opened,
only_shows, return_confirms,
};
pub(crate) use rename::rename_preview;
use rename::{person_rename_plan, rename_body, rename_keyword_body, rename_person_body};
@@ -497,7 +497,8 @@ fn shell(app: &mut LightcraftApp, host: &mut egui::Ui, blocked: bool) {
let chrome_id = id.with("chrome");
let chrome = ctx.data(|d| d.get_temp::<f32>(chrome_id)).unwrap_or(DIALOG_CHROME_GUESS).max(DIALOG_CHROME_GUESS);
let body_max =
if settings { screen.height() - top - DIALOG_SCREEN_MARGIN - chrome } else { screen.height() - 2.0 * DIALOG_SCREEN_MARGIN - chrome }.max(DIALOG_MIN_BODY);
if settings { screen.height() - top - DIALOG_SCREEN_MARGIN - chrome } else { screen.height() - 2.0 * DIALOG_SCREEN_MARGIN - chrome }
.max(DIALOG_MIN_BODY);
// A press held from before this dialog was shown (on the dialog it replaced, or on the window under it) is not
// this dialog's either: its release must not land on what this dialog put under the pointer.
let shown_id = egui::Id::unique("lightcraft.dialog.shown-id");
@@ -668,7 +669,10 @@ fn shell(app: &mut LightcraftApp, host: &mut egui::Ui, blocked: bool) {
ctx.data_mut(|d| d.insert_temp(grown_id, content_w));
ctx.request_repaint();
}
if !popup_was_open && settled && let Some(band) = title_bar {
if !popup_was_open
&& settled
&& let Some(band) = title_bar
{
title_bar_handle(&ctx, band, window_rect);
}
// The startup dialog is recorded once it was presented, not when the logic tick picked it: a host that runs
@@ -1439,12 +1443,7 @@ fn capture_time_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg
}
/// The body of the LabelNames dialog.
fn label_names_body(
app: &mut LightcraftApp,
ui: &mut egui::Ui,
t: &Tokens,
dlg: &mut Dialog,
) -> bool {
fn label_names_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) -> bool {
let Dialog::LabelNames { names, save_as } = dlg else {
return false;
};
@@ -1459,28 +1458,16 @@ fn label_names_body(
let mut choices = |ui: &mut egui::Ui| {
for set in sets["sets"].as_array().into_iter().flatten() {
let name = set["name"].as_str().unwrap_or_default();
if crate::widgets::text_button(ui, &format!("labelSet-{name}"), name, false)
.clicked()
{
candidate_names = set["names"]
.as_array()
.into_iter()
.flatten()
.map(|n| n.as_str().unwrap_or_default().to_string())
.collect();
if crate::widgets::text_button(ui, &format!("labelSet-{name}"), name, false).clicked() {
candidate_names = set["names"].as_array().into_iter().flatten().map(|n| n.as_str().unwrap_or_default().to_string()).collect();
}
}
};
if craft::ui::runtime::measure::active(ui.ctx()) && !ui.is_sizing_pass() {
// A context-side measuring run alone is not an egui sizing Ui. Use the
// supported sizing-only presentation so no live SDK press can begin.
let mut sizing = ui.new_child(
egui::UiBuilder::new()
.max_rect(ui.available_rect_before_wrap())
.layout(*ui.layout())
.sizing_pass()
.invisible(),
);
let mut sizing =
ui.new_child(egui::UiBuilder::new().max_rect(ui.available_rect_before_wrap()).layout(*ui.layout()).sizing_pass().invisible());
choices(&mut sizing);
ui.advance_cursor_after_rect(sizing.min_rect());
} else {
@@ -1492,29 +1479,19 @@ fn label_names_body(
let colour = format!("{l:?}");
field(ui, &colour, |ui| {
let (r, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover());
ui.painter()
.circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l));
escaped |= label_name_field(
ui,
&format!("field:labelName-{}", colour.to_lowercase()),
&colour,
&mut candidate_names[i],
&colour,
);
ui.painter().circle_filled(r.center(), 6.0, crate::panels::grid::label_color(*l));
escaped |= label_name_field(ui, &format!("field:labelName-{}", colour.to_lowercase()), &colour, &mut candidate_names[i], &colour);
});
}
field(ui, "Save as set", |ui| {
escaped |= label_name_field(
ui,
"field:labelSetName",
"Save as set",
&mut candidate_save_as,
crate::i18n::tr("Optional name"),
);
escaped |= label_name_field(ui, "field:labelSetName", "Save as set", &mut candidate_save_as, crate::i18n::tr("Optional name"));
});
ui.label(egui::RichText::new(crate::i18n::tr(
"Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.",
)).color(t.text_dim));
ui.label(
egui::RichText::new(crate::i18n::tr(
"Names appear in the label menu, the filter bar and the Info panel, and are written to XMP. Empty = the colour's name.",
))
.color(t.text_dim),
);
if ui.is_enabled() && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
*names = candidate_names;
*save_as = candidate_save_as;
@@ -1522,19 +1499,10 @@ fn label_names_body(
escaped
}
fn label_name_field(
ui: &mut egui::Ui,
alias: &str,
label: &str,
value: &mut String,
hint: &str,
) -> bool {
fn label_name_field(ui: &mut egui::Ui, alias: &str, label: &str, value: &mut String, hint: &str) -> bool {
use craft::ui::contract::{Bind, Props as _, Show as _};
use craft::ui::text::TextField;
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_width().max(1.0), 24.0),
egui::Sense::hover(),
);
let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width().max(1.0), 24.0), egui::Sense::hover());
let eligible = ui.is_enabled()
&& ui.is_visible()
&& ui.clip_rect().intersects(rect)
@@ -1556,7 +1524,6 @@ fn label_name_field(
eligible && shown.escaped
}
/// The body of the MergeKeywords dialog.
fn merge_keywords_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, confirm: &mut bool, dlg: &mut Dialog) {
let Dialog::MergeKeywords { from, into } = dlg else { return };
@@ -1590,23 +1557,12 @@ fn merge_keywords_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, c
}
/// The body of the NewAlbum dialog.
fn new_album_body(
app: &mut LightcraftApp,
ui: &mut egui::Ui,
confirm: &mut bool,
dlg: &mut Dialog,
) {
fn new_album_body(app: &mut LightcraftApp, ui: &mut egui::Ui, confirm: &mut bool, dlg: &mut Dialog) {
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Props as _, Show as _};
// Respect an explicit native presentation scope without changing the
// installed generic dialog's supported-SDK default.
let Dialog::NewAlbum {
name,
folder,
include_selected,
..
} = dlg
else {
let Dialog::NewAlbum { name, folder, include_selected, .. } = dlg else {
return;
};
if new_album_name_field(ui, name) {
@@ -1619,16 +1575,11 @@ fn new_album_body(
.id_salt("albumIncludeSelected")
.label(crate::i18n::tr("Include selected photos").to_owned())
.show(ui);
if ui.is_enabled() && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx())
{
if ui.is_enabled() && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
*include_selected = candidate_include;
}
if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
crate::widgets::register_response(
"check:albumIncludeSelected",
shown.response.rect,
&shown.response,
);
crate::widgets::register_response("check:albumIncludeSelected", shown.response.rect, &shown.response);
}
}
}
@@ -1640,10 +1591,7 @@ fn new_album_name_field(ui: &mut egui::Ui, value: &mut String) -> bool {
use craft::ui::runtime::focus::{self, FocusTarget};
use craft::ui::text::TextField;
let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx());
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_width().max(1.0), 24.0),
egui::Sense::hover(),
);
let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width().max(1.0), 24.0), egui::Sense::hover());
let shown = TextField::new(crate::i18n::tr("Name").to_owned(), Bind::bound(value))
.id_salt("field:albumName")
.placeholder(crate::i18n::tr("Name").to_owned())
@@ -1668,7 +1616,6 @@ fn new_album_name_field(ui: &mut egui::Ui, value: &mut String) -> bool {
real && ui.is_enabled() && shown.submitted
}
/// The body of the PasteSettings dialog.
fn paste_settings_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) {
let Dialog::PasteSettings { groups } = dlg else { return };
@@ -1702,7 +1649,15 @@ fn contact_sheet_body(app: &mut LightcraftApp, ui: &mut egui::Ui, dlg: &mut Dial
craft::ui::contract::Entry::new("a4".to_owned(), "A4".to_owned()),
craft::ui::contract::Entry::new("letter".to_owned(), crate::i18n::tr("Letter").to_owned()),
];
if let Some(paper) = crate::widgets::select(ui, "combo:contactSheetPaper", crate::i18n::tr("Paper"), options.paper.clone(), &entries, Some(options.paper.clone()), None) {
if let Some(paper) = crate::widgets::select(
ui,
"combo:contactSheetPaper",
crate::i18n::tr("Paper"),
options.paper.clone(),
&entries,
Some(options.paper.clone()),
None,
) {
options.paper = paper;
}
});
@@ -1990,7 +1945,10 @@ pub(crate) fn show_root(app: &mut LightcraftApp, root: &mut egui::Ui, blocked: b
AboutLink::new(crate::i18n::tr("Source code on GitHub"), crate::links::GITHUB),
AboutLink::new(crate::i18n::tr("ArtCraft — more creative apps"), crate::links::WEBSITE),
])
.built_with(crate::i18n::tr_format!("MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.", crate::theme::font_credits(app.chinese_font.is_some())));
.built_with(crate::i18n::tr_format!(
"MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.",
crate::theme::font_credits(app.chinese_font.is_some())
));
let dialog = AboutDialog::new(&info, credits::framework_credits());
let ctx = root.ctx().clone();
let (out, record) = craft::ui::runtime::inspect::record(root, egui::Id::unique("about-app-contract"), |ui| {
@@ -2001,7 +1959,9 @@ pub(crate) fn show_root(app: &mut LightcraftApp, root: &mut egui::Ui, blocked: b
crate::widgets::register_response("dialog:window", out.response.rect, &out.response);
let ok = [crate::i18n::tr("OK"), crate::i18n::tr("Close")];
if let Some(element) = record.iter().flat_map(|record| record.elements.iter()).find(|element| {
element.component == "Button" && element.part.is_none() && element.facts.as_ref().and_then(|facts| facts.name.as_deref()).is_some_and(|name| ok.contains(&name))
element.component == "Button"
&& element.part.is_none()
&& element.facts.as_ref().and_then(|facts| facts.name.as_deref()).is_some_and(|name| ok.contains(&name))
}) && let Some(response) = root.ctx().read_response(element.id)
{
crate::widgets::register_response("button:dialogOk", element.rect, &response);
@@ -2031,7 +1991,9 @@ fn dialog_content(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, body_m
Dialog::SmartRules { .. } => smart_rules_body(app, ui, t, close, dlg),
Dialog::NewSmartAlbum { .. } => new_smart_album_body(app, ui, t, confirm, dlg),
Dialog::CaptureTime { .. } => capture_time_body(app, ui, t, dlg),
Dialog::LabelNames { .. } => { *close |= label_names_body(app, ui, t, dlg); },
Dialog::LabelNames { .. } => {
*close |= label_names_body(app, ui, t, dlg);
}
Dialog::Rename { .. } => rename_body(app, ui, t, dlg),
Dialog::RenamePerson { .. } => rename_person_body(app, ui, t, confirm, dlg),
Dialog::RenameKeyword { .. } => rename_keyword_body(app, ui, t, confirm, dlg),
@@ -2115,9 +2077,9 @@ mod new_album_port_tests;
#[path = "dialogs/new_album_sdk_route_tests.rs"]
mod new_album_sdk_route_tests;
#[cfg(test)]
#[path = "dialogs/label_names_flow_tests.rs"]
mod label_names_port_tests;
#[cfg(test)]
#[path = "dialogs/keyword_tag_options_flow_tests.rs"]
mod keyword_tag_options_flow_tests;
#[cfg(test)]
#[path = "dialogs/label_names_flow_tests.rs"]
mod label_names_port_tests;
+2 -5
View File
@@ -32,11 +32,8 @@ fn number(ui: &mut egui::Ui, id: &str, label: &str, value: &mut f32, similarity:
// editor remains immediately after the track for existing typed-entry clients.
let width = ui.spacing().slider_width;
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 24.0), egui::Sense::hover());
let slider = Slider::new(Bind::bound(&mut current), drag)
.id_salt((id, "track"))
.label(crate::i18n::tr(label).to_owned())
.step(step)
.show_at(ui, rect);
let slider =
Slider::new(Bind::bound(&mut current), drag).id_salt((id, "track")).label(crate::i18n::tr(label).to_owned()).step(step).show_at(ui, rect);
register(ui, &format!("slider:{id}"), &slider.response);
let mut exact = Some(current);
let (rect, _) = ui.allocate_exact_size(egui::vec2(68.0, 24.0), egui::Sense::hover());
@@ -94,7 +94,11 @@ fn production_cull_body_mounts_sdk_controls_without_clamping_typed_values() {
let (_, record) = craft::ui::runtime::inspect::record(ui, egui::Id::unique("wave110-cull-probe"), |ui| {
crate::dialogs::cull_body(&mut app, ui, &t, &mut dialog);
});
roles = record.iter().flat_map(|record| record.elements.iter()).filter_map(|element| element.facts.as_ref().map(|facts| facts.role.clone())).collect();
roles = record
.iter()
.flat_map(|record| record.elements.iter())
.filter_map(|element| element.facts.as_ref().map(|facts| facts.role.clone()))
.collect();
});
});
frame_out.textures_delta.clear();
+4 -1
View File
@@ -50,7 +50,10 @@ pub(super) fn choices<V: PartialEq + Copy + Send + Sync + 'static>(ui: &mut egui
let measure = |ui: &mut egui::Ui, width: f32| {
let mut measuring = *value;
let child = ui.new_child(
egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, f32::INFINITY))).sizing_pass().invisible(),
egui::UiBuilder::new()
.max_rect(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, f32::INFINITY)))
.sizing_pass()
.invisible(),
);
RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(&mut measuring)).id_salt(id).measure_in(&child, Proposal::Ideal, body)
};
+15 -3
View File
@@ -174,7 +174,8 @@ fn preset_entries(app: &LightcraftApp, ui: &egui::Ui) -> std::sync::Arc<Vec<craf
let generation = app.session.presets.generation();
let language = crate::i18n::language();
let cache = egui::Id::unique("import-preset-entries");
if let Some((_, _, entries)) = ui.data(|data| data.get_temp::<Cached>(cache)).filter(|(old, locale, _)| *old == generation && *locale == language) {
if let Some((_, _, entries)) = ui.data(|data| data.get_temp::<Cached>(cache)).filter(|(old, locale, _)| *old == generation && *locale == language)
{
return entries;
}
let mut entries = vec![Entry::new(String::new(), crate::i18n::tr("None").to_owned())];
@@ -252,7 +253,10 @@ fn body_inner(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog)
// so resizing the dialog resizes the grid
let below = ui.ctx().data(|m| m.get_temp::<f32>(egui::Id::unique(CONTENT_BOTTOM)));
// the room left in the dialog's body below this point ([`note_body_room`]), else what the ui has
let room = ui.ctx().data(|m| m.get_temp::<(f32, f32)>(egui::Id::unique((BODY_ROOM, controls::measuring(ui))))).map(|(top, room)| top + room - ui.cursor().top());
let room = ui
.ctx()
.data(|m| m.get_temp::<(f32, f32)>(egui::Id::unique((BODY_ROOM, controls::measuring(ui)))))
.map(|(top, room)| top + room - ui.cursor().top());
// (the room alone: a measuring run's ui may offer less height than the real run's, and the grid must be as tall
// in both, or the body measures shorter than it lays out and its last rows can't be scrolled to)
// (less one row gap: the body's content counts the gap after its last row, and a body a gap too tall scrolls)
@@ -504,7 +508,15 @@ fn body_inner(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog)
field(ui, "Preset", |ui| {
// "" is no preset; a preset that has gone shows as None until another is chosen
let entries = preset_entries(app, ui);
if let Some(pid) = crate::widgets::select(ui, "combo:importPreset", crate::i18n::tr("Preset"), d.preset.clone(), entries.as_slice(), Some(crate::i18n::tr("None").to_owned()), None) {
if let Some(pid) = crate::widgets::select(
ui,
"combo:importPreset",
crate::i18n::tr("Preset"),
d.preset.clone(),
entries.as_slice(),
Some(crate::i18n::tr("None").to_owned()),
None,
) {
d.preset = pid;
}
});
+2 -1
View File
@@ -69,7 +69,8 @@ pub(crate) fn template_field(ui: &mut egui::Ui, name: &str, label: &str, value:
use craft::ui::contract::{Bind, Props as _, Show as _};
use craft::ui::text::TextField;
let live = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx());
let pending = if live { ui.ctx().data_mut(|d| d.remove_temp::<String>(edit_id.with("lc-pending-tag"))).filter(|tag| !tag.is_empty()) } else { None };
let pending =
if live { ui.ctx().data_mut(|d| d.remove_temp::<String>(edit_id.with("lc-pending-tag"))).filter(|tag| !tag.is_empty()) } else { None };
let width = width.min(ui.available_width()).max(1.0);
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, ui.spacing().interact_size.y.max(24.0)), egui::Sense::hover());
let mut field = TextField::new(label.to_owned(), Bind::bound(value)).id(edit_id).placeholder(hint.to_owned()).limit(None);
+8 -15
View File
@@ -71,10 +71,8 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
}
});
});
let shown = Checkbox::new(Bind::bound(&mut show_all))
.id_salt(SHOW_ALL)
.label(crate::i18n::tr("Show commands without a shortcut").to_owned())
.show(ui);
let shown =
Checkbox::new(Bind::bound(&mut show_all)).id_salt(SHOW_ALL).label(crate::i18n::tr("Show commands without a shortcut").to_owned()).show(ui);
register(ui, "check:shortcuts.showAll", &shown.response);
if !measuring(ui) {
ui.data_mut(|d| {
@@ -142,11 +140,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc:
};
ui.label(name).on_hover_text(hover);
let recording = app.recording_shortcut.as_deref() == Some(b.id);
let text = if recording {
crate::i18n::tr("Press keys…").to_owned()
} else {
sc.map_or_else(|| "—".to_owned(), |sc| menu_text(sc, mac))
};
let text = if recording { crate::i18n::tr("Press keys…").to_owned() } else { sc.map_or_else(|| "—".to_owned(), |sc| menu_text(sc, mac)) };
// The SDK's stand-alone chord recorder is crate-private. A normal SDK Button
// routes Tab, activation and Escape as intents instead of leaving raw chords
// for capture(). Keep this one focus owner native until the recorder is public.
@@ -154,15 +148,14 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc:
register(ui, format!("button:shortcut-{}", b.id), &response);
if !measuring(ui) && response.clicked() {
app.recording_shortcut = if recording { None } else { Some(b.id.to_string()) };
if !recording { response.request_focus(); }
if !recording {
response.request_focus();
}
}
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
let shown = Button::new(crate::i18n::tr("Remove shortcut").to_owned())
.painted("×")
.id_salt(("shortcutClear", b.id))
.enabled(sc.is_some())
.show(ui);
let shown =
Button::new(crate::i18n::tr("Remove shortcut").to_owned()).painted("×").id_salt(("shortcutClear", b.id)).enabled(sc.is_some()).show(ui);
let clicked = !measuring(ui) && shown.clicked();
let response = shown.response.on_hover_text(crate::i18n::tr("Remove shortcut"));
register(ui, format!("button:shortcutClear-{}", b.id), &response);
@@ -113,13 +113,7 @@ fn keymap_external155_measuring_does_not_take_capture_or_register_controls() {
app.install_framework(&ctx);
app.recording_shortcut = Some("view.survey".into());
let raw = egui::RawInput {
events: vec![egui::Event::Key {
key: egui::Key::F9,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
}],
events: vec![egui::Event::Key { key: egui::Key::F9, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],
..Default::default()
};
let mut output = ctx.run_ui(raw, |ui| {
@@ -543,54 +543,28 @@ fn label_names_actual_parent_publishes_six_enabled_sdk_text_field_owners() {
for _ in 0..8 {
f.safe();
f.tick += 1;
let raw = HeadlessView::raw_input(
egui::vec2(1400.0, 1000.0),
1.0,
f64::from(f.tick) / 60.0,
vec![],
);
let raw = HeadlessView::raw_input(egui::vec2(1400.0, 1000.0), 1.0, f64::from(f.tick) / 60.0, vec![]);
let app = &mut f.app;
let ctx = f.ctx.clone();
let _drain = Drain(ctx.run_ui(raw, |root| {
crate::widgets::take_registries(&ctx);
let (_, recorded) = craft::ui::runtime::inspect::record(
root,
egui::Id::unique("label-names-sdk-route"),
|_| crate::dialogs::show(app, &ctx, false),
);
elements = recorded
.map(|recording| recording.elements.clone())
.unwrap_or_default();
let (_, recorded) =
craft::ui::runtime::inspect::record(root, egui::Id::unique("label-names-sdk-route"), |_| crate::dialogs::show(app, &ctx, false));
elements = recorded.map(|recording| recording.elements.clone()).unwrap_or_default();
}));
crate::widgets::take_registries(&ctx);
assert_eq!(document(&f.app), f.baseline);
assert_eq!(f.draft(), initial_draft);
f.safe();
}
let inputs = elements
.iter()
.filter(|element| element.part.is_none() && element.component.starts_with("TextField"))
.collect::<Vec<_>>();
assert_eq!(
inputs.len(),
6,
"six actual SDK text input owners; records={elements:#?}"
);
let inputs = elements.iter().filter(|element| element.part.is_none() && element.component.starts_with("TextField")).collect::<Vec<_>>();
assert_eq!(inputs.len(), 6, "six actual SDK text input owners; records={elements:#?}");
for name in ["Red", "Yellow", "Green", "Blue", "Purple", "Save as set"] {
let owners = inputs
.iter()
.filter(|element| {
element
.facts
.as_ref()
.is_some_and(|facts| facts.name.as_deref() == Some(name) && !facts.disabled)
})
.filter(|element| element.facts.as_ref().is_some_and(|facts| facts.name.as_deref() == Some(name) && !facts.disabled))
.collect::<Vec<_>>();
assert_eq!(
owners.len(),
1,
"one actual enabled SDK owner for {name}; records={elements:#?}"
);
assert_eq!(owners.len(), 1, "one actual enabled SDK owner for {name}; records={elements:#?}");
}
}
@@ -617,11 +591,7 @@ fn label_names_reverse_tab_all_twelve_owners_preserves_draft_and_escapes() {
assert!(f.focused(order[0]));
for target in order.iter().rev() {
f.key_mod(Key::Tab, Modifiers::SHIFT);
assert!(
f.focused(target),
"reverse Tab requires {target}; trace={:#?}",
f.trace
);
assert!(f.focused(target), "reverse Tab requires {target}; trace={:#?}", f.trace);
assert_eq!(f.draft(), draft);
}
f.key(Key::Escape);
+76 -30
View File
@@ -500,7 +500,6 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, opts: &mut MergeDialog)
});
}
/// Both layout systems can measure speculatively. Never publish automation hits or draft edits then.
fn measuring(ui: &egui::Ui) -> bool {
ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx())
@@ -530,17 +529,21 @@ fn choices(ui: &mut egui::Ui, id: &str, label: &str, options: &[(&str, &str)], v
register(ui, format!("button:{id}-{index}"), &response);
}
};
if horizontal { ui.horizontal_wrapped(members); } else { ui.vertical(members); }
if horizontal {
ui.horizontal_wrapped(members);
} else {
ui.vertical(members);
}
};
// Native columns and SDK containers do not share a flow cursor. Measure in the actual column,
// then mount once there, rather than filling the enclosing dialog a second time.
let width = ui.available_width().max(1.0);
let mut probe = value.clone();
let child = ui.new_child(egui::UiBuilder::new()
.max_rect(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, f32::INFINITY)))
.sizing_pass().invisible());
let size = RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(&mut probe))
.id_salt(id).measure_in(&child, Proposal::Width(width), body);
let child = ui.new_child(
egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, f32::INFINITY))).sizing_pass().invisible(),
);
let size =
RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(&mut probe)).id_salt(id).measure_in(&child, Proposal::Width(width), body);
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, size.y.max(24.0)), egui::Sense::hover());
RadioGroup::new(crate::i18n::tr(label).to_owned(), Bind::bound(value)).id_salt(id).show_at(ui, rect, body);
}
@@ -549,26 +552,42 @@ fn choices(ui: &mut egui::Ui, id: &str, label: &str, options: &[(&str, &str)], v
fn options(ui: &mut egui::Ui, opts: &mut MergeDialog, photo_count: usize) {
let mut draft = opts.clone();
if draft.is_pano() {
choices(ui, "mergeProjection", "Projection", &[("auto", "Auto Select"), ("spherical", "Spherical"),
("cylindrical", "Cylindrical"), ("perspective", "Perspective")], &mut draft.projection, false);
choices(
ui,
"mergeProjection",
"Projection",
&[("auto", "Auto Select"), ("spherical", "Spherical"), ("cylindrical", "Cylindrical"), ("perspective", "Perspective")],
&mut draft.projection,
false,
);
ui.add_space(4.0);
let mut warp = draft.boundary_warp;
if num(ui, &BOUNDARY_WARP, &mut warp) { draft.boundary_warp = warp.round(); }
if num(ui, &BOUNDARY_WARP, &mut warp) {
draft.boundary_warp = warp.round();
}
check(ui, "check:merge.fillEdges", "Fill Edges", &mut draft.fill_edges, true);
check(ui, "check:merge.autoCrop", "Auto Crop", &mut draft.auto_crop, true);
ui.add_space(4.0);
}
if draft.is_hdr() {
check(ui, "check:merge.align", "Auto Align", &mut draft.align, true);
choices(ui, "mergeDeghost", "Deghost Amount", &[("none", "None"), ("low", "Low"), ("medium", "Med"), ("high", "High")],
&mut draft.deghost, true);
choices(
ui,
"mergeDeghost",
"Deghost Amount",
&[("none", "None"), ("low", "Low"), ("medium", "Med"), ("high", "High")],
&mut draft.deghost,
true,
);
if draft.command == "merge.hdr" {
let enabled = draft.deghost != "none";
check(ui, "check:merge.showOverlay", "Show Deghost Overlay", &mut draft.show_overlay, enabled);
}
if draft.command == "merge.hdrPanorama" {
let mut bracket = f64::from(draft.bracket);
if num(ui, &BRACKET, &mut bracket) { draft.bracket = bracket.round() as u32; }
if num(ui, &BRACKET, &mut bracket) {
draft.bracket = bracket.round() as u32;
}
}
ui.add_space(4.0);
}
@@ -576,7 +595,9 @@ fn options(ui: &mut egui::Ui, opts: &mut MergeDialog, photo_count: usize) {
check(ui, "check:merge.stack", "Create Stack", &mut draft.stack, true);
ui.add_space(8.0);
Text::new(crate::i18n::tr_format!("{} photos", photo_count)).shade(Shade::Muted).show(ui);
if !measuring(ui) { *opts = draft; }
if !measuring(ui) {
*opts = draft;
}
}
const BOUNDARY_WARP: lightcraft_develop::ControlSpec = lightcraft_develop::ControlSpec {
@@ -605,8 +626,11 @@ const BRACKET: lightcraft_develop::ControlSpec = lightcraft_develop::ControlSpec
/// Keep the product's hover Up/Down shortcut (Shift = five steps) beside the SDK's
/// focused slider navigation. Text editing always owns its own arrow keys.
fn hover_keys(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, row: egui::Rect, track_key: egui::Id, value: &mut f64) {
if measuring(ui) || !ui.is_enabled() || !ui.rect_contains_pointer(row)
|| craft::ui::runtime::focus::focused_rec(ui.ctx()).is_some_and(|focus| focus.stop.text) {
if measuring(ui)
|| !ui.is_enabled()
|| !ui.rect_contains_pointer(row)
|| craft::ui::runtime::focus::focused_rec(ui.ctx()).is_some_and(|focus| focus.stop.text)
{
return;
}
let (up, down, shift) = ui.input_mut(|input| {
@@ -619,11 +643,16 @@ fn hover_keys(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, row: eg
// Settle only the matching move for this track: the app owns hovered Up/Down
// (Shift = 5), while the SDK still owns other axes, editing and accessibility.
use craft::ui::runtime::{focus, keys};
if let Some(track) = ui.data(|d| d.get_temp::<egui::Id>(track_key)).filter(|id| focus::focused_rec(ui.ctx()).is_some_and(|f| f.stop.id == *id)) {
if let Some(track) =
ui.data(|d| d.get_temp::<egui::Id>(track_key)).filter(|id| focus::focused_rec(ui.ctx()).is_some_and(|f| f.stop.id == *id))
{
let mut intents = keys::intents_of(ui.ctx(), Some(track), false);
let took = intents.take_move_where(|mv, mods| mods.extend == shift && !mods.fine && !mods.lead
&& ((up && mv == keys::NavMove::Up) || (down && mv == keys::NavMove::Down)));
if took.is_some() { keys::settle(ui.ctx(), Some(track), &intents); }
let took = intents.take_move_where(|mv, mods| {
mods.extend == shift && !mods.fine && !mods.lead && ((up && mv == keys::NavMove::Up) || (down && mv == keys::NavMove::Down))
});
if took.is_some() {
keys::settle(ui.ctx(), Some(track), &intents);
}
}
*value = crate::widgets::nudged(spec, *value, if up { 1.0 } else { -1.0 } * if shift { 5.0 } else { 1.0 });
}
@@ -639,7 +668,9 @@ fn hover_keys(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, row: eg
let total = (remainder + dx).clamp(-10.0 * unit, 10.0 * unit);
let steps = (total / unit).trunc();
ui.data_mut(|data| data.insert_temp(key, total - steps * unit));
if steps != 0.0 { *value = crate::widgets::nudged(spec, *value, f64::from(steps)); }
if steps != 0.0 {
*value = crate::widgets::nudged(spec, *value, f64::from(steps));
}
}
fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f64) -> bool {
@@ -655,7 +686,9 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f6
crate::panels::detail::host::Target::new(crate::i18n::tr(spec.label)).pointer_only(),
);
crate::widgets::register_response(format!("sliderLabel:{}", spec.id), label.rect, &caption.response);
if caption.double_clicked() { current = spec.default; }
if caption.double_clicked() {
current = spec.default;
}
}
let row = egui::Rect::from_min_max(label.rect.min, egui::pos2(ui.max_rect().right(), ui.cursor().min.y + 24.0));
let track_key = ui.scope_id().with(("merge-focused-track", spec.id));
@@ -666,15 +699,20 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f6
let record_id = ui.scope_id().with(("merge-track", spec.id));
let (shown, record) = craft::ui::runtime::inspect::record(ui, record_id, |ui| {
Slider::new(Bind::bound(&mut current).reset(spec.default), spec.min..=spec.max)
.id_salt(("merge-slider", spec.id)).label(crate::i18n::tr(spec.label)).step(spec.step)
.id_salt(("merge-slider", spec.id))
.label(crate::i18n::tr(spec.label))
.step(spec.step)
// LightCraft's slider keys: Shift steps five times, as the develop sliders do (`widgets::slider`).
.key_policy(craft::ui::runtime::keys::ScalarKeyPolicy::new(spec.step).model_step(spec.step).shift_factor(5.0))
.show_at(ui, rect)
});
// Automation fractions describe the value span, which runs between the endpoint thumb centres.
let half_thumb = record.as_ref().and_then(|record| record.hits.iter().find(|hit| {
hit.owner == shown.response.id && hit.part.is_some_and(|part| part.key == Slider::THUMB)
})).map_or(0.0, |hit| hit.bounds.width() * 0.5);
let half_thumb = record
.as_ref()
.and_then(|record| {
record.hits.iter().find(|hit| hit.owner == shown.response.id && hit.part.is_some_and(|part| part.key == Slider::THUMB))
})
.map_or(0.0, |hit| hit.bounds.width() * 0.5);
let span = shown.response.rect.shrink2(egui::vec2(half_thumb, 0.0));
if !measuring(ui) {
ui.data_mut(|d| d.insert_temp(track_key, shown.response.id));
@@ -683,8 +721,12 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f6
let mut exact = Some(current);
let (rect, _) = ui.allocate_exact_size(egui::vec2(64.0, 24.0), egui::Sense::hover());
let shown = NumberField::new(crate::i18n::tr(spec.label), Bind::bound(&mut exact).reset(Some(spec.default)))
.id_salt(("merge-number", spec.id)).range(spec.min..=spec.max).step(spec.step)
.snap_typed(true).commit_decimals(spec.decimals as usize).fixed_decimals(spec.decimals as usize)
.id_salt(("merge-number", spec.id))
.range(spec.min..=spec.max)
.step(spec.step)
.snap_typed(true)
.commit_decimals(spec.decimals as usize)
.fixed_decimals(spec.decimals as usize)
.show_at(ui, rect);
register(ui, format!("sliderValue:{}", spec.id), &shown.response);
register(ui, format!("sliderField:{}", spec.id), &shown.response);
@@ -692,9 +734,13 @@ fn num(ui: &mut egui::Ui, spec: &lightcraft_develop::ControlSpec, value: &mut f6
if !measuring(ui) && shown.events.iter().any(|event| matches!(event, craft::behavior::EditEvent::Cancel { .. })) {
crate::widgets::take_escape(ui.ctx());
}
if let Some(exact) = exact.filter(|v| v.is_finite()) { current = exact; }
if let Some(exact) = exact.filter(|v| v.is_finite()) {
current = exact;
}
});
if !measuring(ui) { *value = current; }
if !measuring(ui) {
*value = current;
}
*value != before
}
@@ -57,7 +57,9 @@ impl Controls {
}
fn settle(&mut self) {
for _ in 0..3 { self.frame(vec![]); }
for _ in 0..3 {
self.frame(vec![]);
}
}
fn click(&mut self, id: &str) {
@@ -87,7 +89,9 @@ impl Controls {
self.key(Key::Enter, Modifiers::NONE);
}
fn has(&self, id: &str) -> bool { self.frames.rects.iter().any(|(name, _)| name == id) }
fn has(&self, id: &str) -> bool {
self.frames.rects.iter().any(|(name, _)| name == id)
}
/// The framework convention: a pointer press activates a control without taking the keyboard, so a keyboard step
/// starts from a control given the focus.
@@ -219,12 +223,15 @@ fn sdk155_merge_cancel_discards_draft_and_invalid_confirm_cannot_start_or_save()
app.install_framework(&frames.ctx);
let opts = MergeDialog { stack: true, deghost: "high".into(), ..Default::default() };
app.ui.dialog = Some(crate::state::Dialog::Merge { opts: opts.clone() });
for _ in 0..3 { frames.frame(vec![], |ui| crate::dialogs::show(&mut app, ui.ctx(), false)); }
for _ in 0..3 {
frames.frame(vec![], |ui| crate::dialogs::show(&mut app, ui.ctx(), false));
}
let pos = frames.rect("button:dialogCancel").center();
frames.frame(vec![Event::PointerMoved(pos)], |ui| crate::dialogs::show(&mut app, ui.ctx(), false));
for pressed in [true, false] {
frames.frame(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }],
|ui| crate::dialogs::show(&mut app, ui.ctx(), false));
frames.frame(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], |ui| {
crate::dialogs::show(&mut app, ui.ctx(), false)
});
}
assert!(app.ui.dialog.is_none());
assert!(app.merge.final_task.is_none() && app.merge.preview_task.is_none());
@@ -48,7 +48,8 @@ impl Review {
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx);
app.install_framework(&ctx);
let mut this = Self { app, ctx, tick: 0, rects: vec![], hits: vec![], old_language: crate::i18n::language(), sdk_name_owner: false, covered: false };
let mut this =
Self { app, ctx, tick: 0, rects: vec![], hits: vec![], old_language: crate::i18n::language(), sdk_name_owner: false, covered: false };
// Production command opening, not menu-enabled/selected-photo acceptance.
this.app.run("dialog.print", json!({})).unwrap();
this.idle();
+10 -2
View File
@@ -270,7 +270,7 @@ fn templates_section(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut
// `escaped` also includes Escape-reason Revert; no such programmatic path is
// installed here, and this is not a general physical-key discriminator.
close |= eligible && shown.escaped;
if text_button(ui, "printSaveTemplate", "Save", false).clicked() && !pu.template_name.trim().is_empty() {
run(app, &ctx, "print.template.save", json!({"name": pu.template_name}));
}
@@ -599,7 +599,15 @@ fn print_job_color(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, color: &Pri
let _ = crate::widgets::menu_row(ui, ("printProfile", "icc"), None, &shown, None, true, true);
}
if app.services.pick_display_profile.is_some() {
pick |= crate::widgets::menu_row(ui, ("printProfile", "other"), Some("item:printProfile-other"), crate::i18n::tr("Other…"), None, false, true);
pick |= crate::widgets::menu_row(
ui,
("printProfile", "other"),
Some("item:printProfile-other"),
crate::i18n::tr("Other…"),
None,
false,
true,
);
}
});
});
@@ -33,7 +33,8 @@ pub(super) fn button(ui: &mut egui::Ui, id: &str, glyph: &str, label: &str, widt
/// The width [`button`] takes: at least `width`, else what its painted text needs.
pub(super) fn button_width(ui: &egui::Ui, glyph: &str, label: &str, width: f32) -> f32 {
let ideal = Button::new(crate::i18n::tr(label).to_owned()).painted(crate::i18n::tr(glyph).to_owned()).measure_in(ui, craft::behavior::Proposal::Ideal).x;
let ideal =
Button::new(crate::i18n::tr(label).to_owned()).painted(crate::i18n::tr(glyph).to_owned()).measure_in(ui, craft::behavior::Proposal::Ideal).x;
width.max(ideal.ceil())
}
+23 -22
View File
@@ -193,31 +193,32 @@ pub(crate) fn colour(ui: &mut egui::Ui, owner: egui::Id, name: &str, label: &str
}
let mut saved = false;
let _editor = Popover::new(words, Bind::bound(&mut open)).id_salt(("settings-colour-editor", name)).opened_by(&chip.response).show(ui, |ui, _| {
ui.set_min_width(240.0);
for (i, channel) in ["Red", "Green", "Blue"].into_iter().enumerate() {
let shape = Shape { label: channel, lo: 0.0, hi: 255.0, unit: "", step: 1.0, log: false };
let steps = ui
.horizontal(|ui| {
ui.add_sized(vec2(48.0, 24.0), egui::Label::new(crate::i18n::tr(channel)));
slider(ui, owner, &format!("{name}{channel}"), &shape, f64::from(rgb[i]))
})
.inner;
for step in steps {
match step {
Step::Begin(_) | Step::End => {}
Step::Preview(v) | Step::Save(v) => {
rgb[i] = v.round().clamp(0.0, 255.0) as u8;
saved |= matches!(step, Step::Save(_));
let _editor =
Popover::new(words, Bind::bound(&mut open)).id_salt(("settings-colour-editor", name)).opened_by(&chip.response).show(ui, |ui, _| {
ui.set_min_width(240.0);
for (i, channel) in ["Red", "Green", "Blue"].into_iter().enumerate() {
let shape = Shape { label: channel, lo: 0.0, hi: 255.0, unit: "", step: 1.0, log: false };
let steps = ui
.horizontal(|ui| {
ui.add_sized(vec2(48.0, 24.0), egui::Label::new(crate::i18n::tr(channel)));
slider(ui, owner, &format!("{name}{channel}"), &shape, f64::from(rgb[i]))
})
.inner;
for step in steps {
match step {
Step::Begin(_) | Step::End => {}
Step::Preview(v) | Step::Save(v) => {
rgb[i] = v.round().clamp(0.0, 255.0) as u8;
saved |= matches!(step, Step::Save(_));
}
}
}
}
}
if let Some(typed) = hex_field(ui, owner, name, rgb) {
rgb = typed;
saved = true;
}
});
if let Some(typed) = hex_field(ui, owner, name, rgb) {
rgb = typed;
saved = true;
}
});
let editing = open;
ui.data_mut(|d| {
d.insert_temp(open_key, open);
+7 -11
View File
@@ -172,12 +172,9 @@ pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui,
if ui.is_enabled() && craft::ui::contract::clicked(&face) {
open = !open;
}
Menu::new(name)
.id_salt(("view-options-menu", &id))
.values()
.opened_by(&face, Trigger::Manual)
.open(Bind::bound(&mut open))
.show(ui, |ui, _| {
Menu::new(name).id_salt(("view-options-menu", &id)).values().opened_by(&face, Trigger::Manual).open(Bind::bound(&mut open)).show(
ui,
|ui, _| {
for f in F::ALL {
let key = serde_json::to_value(f).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
let measuring = ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx());
@@ -193,26 +190,25 @@ pub(in super::super) fn view_options(app: &mut LightcraftApp, ui: &mut egui::Ui,
}
}
}
});
},
);
ui.data_mut(|data| data.insert_temp(slot, (pass, open)));
if ui.is_enabled()
&& let Some(field) = picked
{
*line = field;
}
}
use craft::ui::buttons::Button;
use craft::ui::contract::{Props as _, Show as _};
let r =
Button::new(crate::i18n::tr("Use Defaults").to_owned()).id_salt(("view-options-defaults", n)).enabled(*lines != defaults).show(ui);
let r = Button::new(crate::i18n::tr("Use Defaults").to_owned()).id_salt(("view-options-defaults", n)).enabled(*lines != defaults).show(ui);
if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
crate::widgets::register_response(format!("button:viewOptionsDefaults{n}"), r.response.rect, &r.response);
if ui.is_enabled() && *lines != defaults && r.clicked() {
*lines = defaults;
}
}
// one Info at most shows briefly: ticking one unticks the other
let info = if n == 1 { I::Basic } else { I::Exposure };
let mut briefly = app.ui.settings.loupe_info.briefly == info;
+3 -10
View File
@@ -105,12 +105,8 @@ fn library_launch_section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens
row(ui, t, crate::i18n::tr("At launch"), |ui| {
let mut at_launch = app.ui.settings.at_launch;
// Measurement/sizing may consume a native button result, but cannot change host UI state.
if choices(
ui,
"settingsAtLaunch",
&[(LaunchLibrary::Last, "Open the last library"), (LaunchLibrary::Ask, "Ask me")],
&mut at_launch,
) && library_launch_input(ui)
if choices(ui, "settingsAtLaunch", &[(LaunchLibrary::Last, "Open the last library"), (LaunchLibrary::Ask, "Ask me")], &mut at_launch)
&& library_launch_input(ui)
{
app.ui.settings.at_launch = at_launch;
}
@@ -128,10 +124,7 @@ fn library_launch_button(ui: &mut egui::Ui, alias: &str, label: &str, can: bool)
use craft::ui::contract::{Props as _, Show as _};
let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx());
let (response, clicked) = {
let shown = craft::ui::buttons::Button::new(crate::i18n::tr(label).to_owned())
.id_salt(alias)
.enabled(can && real)
.show(ui);
let shown = craft::ui::buttons::Button::new(crate::i18n::tr(label).to_owned()).id_salt(alias).enabled(can && real).show(ui);
let clicked = shown.clicked();
(shown.response, clicked)
};
+11 -2
View File
@@ -41,7 +41,8 @@ fn camera_entries(app: &LightcraftApp, ui: &egui::Ui, raw_default: &str) -> std:
let generation = app.session.presets.generation();
let language = crate::i18n::language();
let cache = egui::Id::unique("settings-camera-entries");
if let Some((_, _, entries)) = ui.data(|data| data.get_temp::<Cached>(cache)).filter(|(old, locale, _)| *old == generation && *locale == language) {
if let Some((_, _, entries)) = ui.data(|data| data.get_temp::<Cached>(cache)).filter(|(old, locale, _)| *old == generation && *locale == language)
{
return entries;
}
let mut entries = vec![
@@ -151,7 +152,15 @@ pub(super) fn import_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens)
let cur = d.metadata_preset.clone().unwrap_or_default();
let mut entries = vec![craft::ui::contract::Entry::new(String::new(), crate::i18n::tr("None").to_owned())];
entries.extend(app.session.metadata_presets.iter().map(|m| craft::ui::contract::Entry::new(m.name.clone(), m.name.clone())));
let pick = crate::widgets::select(ui, "combo:settingsMetaPreset", crate::i18n::tr("Metadata preset"), cur.clone(), &entries, Some(cur), Some(240.0));
let pick = crate::widgets::select(
ui,
"combo:settingsMetaPreset",
crate::i18n::tr("Metadata preset"),
cur.clone(),
&entries,
Some(cur),
Some(240.0),
);
if let Some(n) = pick {
let _ = app.run("library.preferences", json!({"import": {"metadataPreset": n}}));
}
@@ -189,26 +189,14 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
row(ui, t, "Colour", |ui| colour(app, ui, "slideshowPlateColor", "Colour", p.color, &|c| plate(json!({"color": c}))));
}
row(ui, t, "Size", |ui| {
slider(
app,
ui,
"slideshowPlateSize",
"Size",
p.size,
Range { lo: 0.01, hi: PLATE_SIZE_MAX, unit: Unit::Percent },
&|v| plate(json!({"size": v})),
)
slider(app, ui, "slideshowPlateSize", "Size", p.size, Range { lo: 0.01, hi: PLATE_SIZE_MAX, unit: Unit::Percent }, &|v| {
plate(json!({"size": v}))
})
});
row(ui, t, "Opacity", |ui| {
slider(
app,
ui,
"slideshowPlateOpacity",
"Opacity",
p.opacity,
Range { lo: 0.0, hi: 1.0, unit: Unit::Percent },
&|v| plate(json!({"opacity": v})),
)
slider(app, ui, "slideshowPlateOpacity", "Opacity", p.opacity, Range { lo: 0.0, hi: 1.0, unit: Unit::Percent }, &|v| {
plate(json!({"opacity": v}))
})
});
placement(app, ui, t, "slideshowPlate", &p.place, true, &plate);
toggle(app, ui, "slideshowPlateBehind", p.behind, "Render behind image", &|v| plate(json!({"behind": v})));
@@ -221,15 +209,9 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
if toggle(app, ui, "slideshowStars", r.enabled, "Rating stars", &|v| stars(json!({"enabled": v}))) {
row(ui, t, "Colour", |ui| colour(app, ui, "slideshowStarsColor", "Colour", r.color, &|c| stars(json!({"color": c}))));
row(ui, t, "Size", |ui| {
slider(
app,
ui,
"slideshowStarsSize",
"Size",
r.size,
Range { lo: 0.01, hi: STAR_SIZE_MAX, unit: Unit::Percent },
&|v| stars(json!({"size": v})),
)
slider(app, ui, "slideshowStarsSize", "Size", r.size, Range { lo: 0.01, hi: STAR_SIZE_MAX, unit: Unit::Percent }, &|v| {
stars(json!({"size": v}))
})
});
placement(app, ui, t, "slideshowStars", &r.place, true, &stars);
}
@@ -250,15 +232,9 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
if toggle(app, ui, "slideshowWatermark", s.show_watermark, "Watermark", &|v| json!({"showWatermark": v})) {
row(ui, t, "Text", |ui| text(app, ui, "slideshowWatermarkText", &w.text, "© Your Name", &|v| wm(json!({"text": v}))));
row(ui, t, "Size", |ui| {
slider(
app,
ui,
"slideshowWatermarkSize",
"Size",
w.size as f64,
Range { lo: 0.01, hi: 0.15, unit: Unit::Percent },
&|v| wm(json!({"size": v})),
)
slider(app, ui, "slideshowWatermarkSize", "Size", w.size as f64, Range { lo: 0.01, hi: 0.15, unit: Unit::Percent }, &|v| {
wm(json!({"size": v}))
})
});
row(ui, t, "Opacity", |ui| {
slider(app, ui, "slideshowWatermarkOpacity", "Opacity", w.opacity as f64, Range { lo: 0.05, hi: 1.0, unit: Unit::Percent }, &|v| {
@@ -106,9 +106,8 @@ fn text(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, t: Title, value: &
let mem = egui::Id::unique(("slideshow-title-field", id));
let pass = ui.ctx().cumulative_pass_nr();
// A hidden/rebound field starts from its own authoritative screen, never a stale draft.
let remembered = ui
.data(|d| d.get_temp::<TitleDraft>(mem))
.filter(|d| d.model == value && (d.pass == pass || d.pass.checked_add(1) == Some(pass)));
let remembered =
ui.data(|d| d.get_temp::<TitleDraft>(mem)).filter(|d| d.model == value && (d.pass == pass || d.pass.checked_add(1) == Some(pass)));
let mut draft = remembered.map_or_else(|| value.to_owned(), |d| d.text);
let widget = format!("field:{id}");
let width = ui.available_width().clamp(80.0, 260.0);
@@ -426,15 +426,3 @@ fn slideshow_launcher_sdk_11_physical_escape_cancels_parent() {
fn slideshow_launcher_sdk_12_natural_tab_and_activation() {
case_12_natural_tab_and_activation(false);
}
@@ -223,9 +223,15 @@ fn updates155_click_widget_hits_the_real_result_footer() {
let mut h = Headless::new(app, [1300.0, 820.0], 1.0);
let limit = Duration::from_secs(10);
check(&mut h.app).unwrap();
assert!(h.step_until(limit, |h| matches!(h.app.updates_rt.updater.status(), Status::UpToDate)
&& h.app.widget_hits.iter().any(|(id, _)| id == "button:updatesOk")), "missing registered result footer");
assert!(
h.step_until(limit, |h| matches!(h.app.updates_rt.updater.status(), Status::UpToDate)
&& h.app.widget_hits.iter().any(|(id, _)| id == "button:updatesOk")),
"missing registered result footer"
);
let answer = h.request("ui.clickWidget", serde_json::json!({"id":"button:updatesOk"}), limit);
assert_eq!(answer["ok"], true, "{answer}");
assert!(h.step_until(limit, |h| !blocks_input(&h.app) && !h.app.widgets.iter().any(|(id, _)| id == "button:updatesOk")), "registered click did not dismiss the actual result");
assert!(
h.step_until(limit, |h| !blocks_input(&h.app) && !h.app.widgets.iter().any(|(id, _)| id == "button:updatesOk")),
"registered click did not dismiss the actual result"
);
}
+6 -1
View File
@@ -339,7 +339,12 @@ fn show_web_result(ctx: &egui::Context, message: Option<&str>) -> bool {
use std::cell::Cell;
let dismissed = Cell::new(false);
crate::dialogs::host_ui(ctx, egui::Id::unique("lightcraft.updates.host"), |ui| {
let ok = [crate::dialogs::FooterSpec { label: crate::i18n::tr("OK").to_owned(), name: "button:updatesWebOk".into(), enabled: true, primary: true }];
let ok = [crate::dialogs::FooterSpec {
label: crate::i18n::tr("OK").to_owned(),
name: "button:updatesWebOk".into(),
enabled: true,
primary: true,
}];
let output = Dialog::new(crate::i18n::tr("LightCraft Updates").to_owned())
.id_salt("lightcraft.updates.web")
.opened(Bind::given(true))
+3 -1
View File
@@ -499,7 +499,9 @@ pub(crate) fn reveal_command(app: &mut crate::LightcraftApp, id: &str) -> Result
/// Check the target's actual egui layer even while a different widget owns the drag.
pub(crate) fn drop_target(ui: &egui::Ui, rect: egui::Rect, pointer: Option<egui::Pos2>) -> bool {
pointer.is_some_and(|pos| {
rect.intersect(ui.clip_rect()).contains(pos) && ui.ctx().layer_id_at(pos) == Some(ui.layer_id()) && !under_floating_window(ui.ctx(), rect.intersect(ui.clip_rect()), pos)
rect.intersect(ui.clip_rect()).contains(pos)
&& ui.ctx().layer_id_at(pos) == Some(ui.layer_id())
&& !under_floating_window(ui.ctx(), rect.intersect(ui.clip_rect()), pos)
})
}
+37 -8
View File
@@ -4269,28 +4269,57 @@ fn about_dialog_tabs_show_the_credits() {
let r = h.request("ui.menu.invoke", json!({"id": "app.about"}), t);
assert_eq!(r["ok"], true, "{r}");
assert_eq!(h.app.ui.dialog, Some(crate::state::Dialog::About));
let tree = |h: &Headless| craft::ui::runtime::inspect::recorded(&h.view.ctx, egui::Id::unique("about-app-contract")).expect("SDK About was painted");
let tree =
|h: &Headless| craft::ui::runtime::inspect::recorded(&h.view.ctx, egui::Id::unique("about-app-contract")).expect("SDK About was painted");
for (tab, evidence) in [("Models", "Models"), ("Contributors", "Contributors"), ("About", "Join the ArtCraft Discord")] {
for _ in 0..5 { h.step(); }
for _ in 0..5 {
h.step();
}
let nodes = tree(&h);
let target = nodes.elements.iter().find(|node| node.facts.as_ref().is_some_and(|f| f.role == "Tab" && f.name.as_deref() == Some(tab) && f.interactive && !f.disabled)).unwrap_or_else(|| panic!("missing enabled SDK tab {tab}"));
let target = nodes
.elements
.iter()
.find(|node| node.facts.as_ref().is_some_and(|f| f.role == "Tab" && f.name.as_deref() == Some(tab) && f.interactive && !f.disabled))
.unwrap_or_else(|| panic!("missing enabled SDK tab {tab}"));
let at = target.rect.center();
assert_eq!(h.request("ui.click", json!({"x":at.x,"y":at.y}), t)["ok"], true);
for _ in 0..4 { h.step(); }
for _ in 0..4 {
h.step();
}
if tab == "Contributors" {
// Initially the grab bag is visible. "Table" is a view selector, not the table name.
let nodes = tree(&h);
let at = nodes.elements.iter().find(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some("Table") && f.interactive && !f.disabled)).expect("Table view selector").rect.center();
let at = nodes
.elements
.iter()
.find(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some("Table") && f.interactive && !f.disabled))
.expect("Table view selector")
.rect
.center();
assert_eq!(h.request("ui.click", json!({"x":at.x,"y":at.y}), t)["ok"], true);
for _ in 0..4 { h.step(); }
for _ in 0..4 {
h.step();
}
}
assert!(tree(&h).elements.iter().any(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some(evidence) && (tab == "About" || f.role == "Table"))), "missing content after clicking {tab}");
assert!(
tree(&h)
.elements
.iter()
.any(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some(evidence) && (tab == "About" || f.role == "Table"))),
"missing content after clicking {tab}"
);
assert_eq!(h.app.ui.dialog, Some(crate::state::Dialog::About));
}
let img = h.snapshot(SETTLE);
assert_eq!(img.size, [1300, 820]);
let nodes = tree(&h);
let ok = nodes.elements.iter().find(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some("OK") && f.interactive && !f.disabled)).expect("real SDK footer").rect.center();
let ok = nodes
.elements
.iter()
.find(|node| node.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some("OK") && f.interactive && !f.disabled))
.expect("real SDK footer")
.rect
.center();
assert_eq!(h.request("ui.click", json!({"x":ok.x,"y":ok.y}), t)["ok"], true);
assert!(h.step_until(t, |frame| frame.app.ui.dialog.is_none()), "SDK OK closes the application dialog");
}
+4 -1
View File
@@ -266,7 +266,10 @@ pub(crate) fn framework_catalogs() -> &'static std::sync::Arc<craft::i18n::I18n>
static CATALOGS: OnceLock<std::sync::Arc<craft::i18n::I18n>> = OnceLock::new();
CATALOGS.get_or_init(|| {
let offered: Vec<&str> = Locale::ALL.iter().filter(|language| !language.catalog().is_empty()).map(|language| language.code()).collect();
let catalogs = offered.iter().filter_map(|code| Locale::parse(code)).map(|language| (language.code().to_owned(), String::new(), craft_catalog(language)));
let catalogs = offered
.iter()
.filter_map(|code| Locale::parse(code))
.map(|language| (language.code().to_owned(), String::new(), craft_catalog(language)));
let (i18n, problems) = craft::i18n::I18n::from_owned(catalogs.collect::<Vec<_>>(), &offered);
for problem in problems {
log::debug!("framework words: {problem}");
+5 -1
View File
@@ -1099,7 +1099,11 @@ pub fn show_in_window(app: &mut LightcraftApp, ui: &mut egui::Ui, max_width: f32
.collect();
// The bar is placed in its room, so the titles that do not fit go into its "…" or "Menu" title. A measuring
// or sizing run must never open a menu: disabled, its titles sense nothing.
MenuBar::new(crate::i18n::tr("Main menu").to_owned(), titles).id_salt("in-window-menu-bar").keyboard(keys).enabled(!measuring(ui)).show_at(ui, room)
MenuBar::new(crate::i18n::tr("Main menu").to_owned(), titles)
.id_salt("in-window-menu-bar")
.keyboard(keys)
.enabled(!measuring(ui))
.show_at(ui, room)
});
// the titles' own width is what the bar takes of the row
let used = shown.titles.width().max(0.0);
+13 -13
View File
@@ -302,20 +302,20 @@ fn right_side(app: &mut LightcraftApp, ui: &mut egui::Ui, full: Rect, compact_zo
let zr = dropdown_face(&mut child, "zoom", crate::i18n::tr(&zoom_label));
let mut zoom_pick = None;
if !measuring(&child) {
Menu::new(crate::i18n::tr("Zoom")).id_salt("zoom-menu").values().opened_by(&zr, Trigger::Click).show(&mut child, |ui, _| {
for (label, z) in [
("Fit", Zoom::Fit),
("Fill", Zoom::Fill),
("50%", Zoom::Percent(50.0)),
("100%", Zoom::Percent(100.0)),
("200%", Zoom::Percent(200.0)),
("400%", Zoom::Percent(400.0)),
] {
if value_row(ui, ("zoom", label), crate::i18n::tr(label), app.ui.zoom == z) {
zoom_pick = Some(z);
Menu::new(crate::i18n::tr("Zoom")).id_salt("zoom-menu").values().opened_by(&zr, Trigger::Click).show(&mut child, |ui, _| {
for (label, z) in [
("Fit", Zoom::Fit),
("Fill", Zoom::Fill),
("50%", Zoom::Percent(50.0)),
("100%", Zoom::Percent(100.0)),
("200%", Zoom::Percent(200.0)),
("400%", Zoom::Percent(400.0)),
] {
if value_row(ui, ("zoom", label), crate::i18n::tr(label), app.ui.zoom == z) {
zoom_pick = Some(z);
}
}
}
});
});
}
if let Some(z) = zoom_pick {
app.ui.zoom = z;
@@ -288,11 +288,7 @@ impl Review {
for alias in ["flag:unflag", PICK, "flag:reject"] {
// the three flags are framework buttons: none publishes a target in a measuring or sizing pass
let expected = usize::from(!(SDK_PICK && matches!(self.pass, Pass::Measure | Pass::Sizing)));
assert_eq!(
rects.iter().filter(|(name, _)| name == alias).count(),
expected,
"only real passes publish an interactive flag target"
);
assert_eq!(rects.iter().filter(|(name, _)| name == alias).count(), expected, "only real passes publish an interactive flag target");
}
self.rects = rects.into_iter().collect();
self.hits = hits.into_iter().collect();
@@ -34,7 +34,11 @@ fn fixture(random: bool, held: bool) -> (LightcraftApp, PhotoId) {
}
#[derive(Clone, Copy)]
enum Pass { Real, Measure, Sizing }
enum Pass {
Real,
Measure,
Sizing,
}
struct Frames {
ctx: egui::Context,
@@ -68,22 +72,21 @@ impl Frames {
self.rows.clear();
self.disabled.clear();
let mut output = self.ctx.run_ui(raw, |ui| {
let (_, record) = craft::ui::runtime::inspect::record(ui, egui::Id::unique("sort-popup-test-inspection"), |ui| {
match pass {
Pass::Real => show(&mut self.app, ui),
Pass::Measure => {
let ctx = ui.ctx().clone();
craft::ui::runtime::measure::run(&ctx, || show(&mut self.app, ui));
}
Pass::Sizing => {
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible());
show(&mut self.app, &mut child);
}
let (_, record) = craft::ui::runtime::inspect::record(ui, egui::Id::unique("sort-popup-test-inspection"), |ui| match pass {
Pass::Real => show(&mut self.app, ui),
Pass::Measure => {
let ctx = ui.ctx().clone();
craft::ui::runtime::measure::run(&ctx, || show(&mut self.app, ui));
}
Pass::Sizing => {
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible());
show(&mut self.app, &mut child);
}
});
if let Some(record) = record {
for element in &record.elements {
if element.component == "MenuItem" && element.part.is_none()
if element.component == "MenuItem"
&& element.part.is_none()
&& let Some(name) = element.facts.as_ref().and_then(|facts| facts.name.as_ref())
&& let Some(response) = ui.ctx().read_response(element.id)
{
@@ -100,7 +103,9 @@ impl Frames {
}
fn settle(&mut self) {
for _ in 0..8 { self.frame(vec![], Pass::Real); }
for _ in 0..8 {
self.frame(vec![], Pass::Real);
}
}
fn row(&self, label: &str) -> &Response {
@@ -122,7 +127,10 @@ impl Frames {
fn click_at(&mut self, pos: Pos2, long: bool) {
self.frame(vec![Event::PointerMoved(pos)], Pass::Real);
self.pointer(pos, true);
if long { self.time += 2.0; self.frame(vec![], Pass::Real); }
if long {
self.time += 2.0;
self.frame(vec![], Pass::Real);
}
self.pointer(pos, false);
self.settle();
}
@@ -170,7 +178,9 @@ fn external_sort_popup_action_visibility_and_real_refresh_locator() {
assert_eq!(f.rows.iter().any(|(name, _)| name == "Reshuffle"), random);
assert_eq!(f.rows.iter().any(|(name, _)| name == "Refresh View"), held);
assert_eq!(f.rects.iter().any(|(name, _)| name == "button:refreshView"), held);
if random { assert!(f.row("Reshuffle").interact_rect.is_positive()); }
if random {
assert!(f.row("Reshuffle").interact_rect.is_positive());
}
if held {
let row = f.row("Refresh View");
let hit = f.hit("button:refreshView");
@@ -260,9 +270,10 @@ fn external_sort_popup_measure_and_native_sizing_cannot_dispatch_actions() {
let before = f.snapshot();
let pos = response.interact_rect.center();
for pressed in [true, false] {
f.frame(vec![Event::PointerMoved(pos), Event::PointerButton {
pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE,
}], pass);
f.frame(
vec![Event::PointerMoved(pos), Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }],
pass,
);
}
for key in [Key::Enter, Key::Space] {
f.ctx.memory_mut(|memory| memory.request_focus(response.id));
@@ -274,7 +285,6 @@ fn external_sort_popup_measure_and_native_sizing_cannot_dispatch_actions() {
}
}
#[test]
fn library_sort_choices_change_order_direction_and_group_without_photo_edits() {
let mut f = Frames::new(false, false, 1.0);
@@ -290,7 +300,9 @@ fn library_sort_choices_change_order_direction_and_group_without_photo_edits() {
("sort:key:fileName", "File Name", json!({"key":"fileName"})),
("sort:ascending", "Ascending", json!({"ascending":true})),
] {
if !f.is_open() { f.open(); }
if !f.is_open() {
f.open();
}
let row = f.row(label).clone();
assert_eq!(f.hit(id).id, row.id);
assert!(row.enabled() && row.sense.is_focusable());
@@ -303,7 +315,9 @@ fn library_sort_choices_change_order_direction_and_group_without_photo_edits() {
assert_eq!(f.app.session.catalog.revision, revision);
assert_eq!(f.app.session.undo.len(), undo);
if id == "sort:key:random" {
if !f.is_open() { f.open(); }
if !f.is_open() {
f.open();
}
let dir = f.row("Ascending").clone();
assert!(f.disabled.iter().any(|name| name == "Ascending"), "a shuffle has no direction to choose: the row is disabled");
f.click_at(dir.interact_rect.center(), false);
@@ -313,7 +327,6 @@ fn library_sort_choices_change_order_direction_and_group_without_photo_edits() {
}
}
#[test]
fn library_sort_choices_measuring_release_is_inert_then_same_owner_changes_order() {
for pass in [Pass::Measure, Pass::Sizing] {
@@ -330,7 +343,9 @@ fn library_sort_choices_measuring_release_is_inert_then_same_owner_changes_order
assert!(!f.hits.iter().any(|(n, _)| n.starts_with("sort:")), "measurement published a sort hit");
f.settle();
assert_eq!(f.snapshot(), before, "measuring release changed the library or replayed");
if !f.is_open() { f.open(); }
if !f.is_open() {
f.open();
}
let recovered = f.hit(target);
assert_eq!(recovered.id, hit.id);
f.click_at(recovered.interact_rect.center(), false);
@@ -346,17 +361,20 @@ fn compact_view_sort_changes_rating_order_without_changing_photo_selection() {
let (mut oracle, _) = fixture(false, false);
oracle.run("library.sort", json!({"key":"rating"})).unwrap();
let mut ready = false;
let mut h = egui_kittest::Harness::builder().with_size(vec2(320.0, 700.0)).build_ui_state(move |ui, app: &mut LightcraftApp| {
if !ready {
crate::theme::install_fonts(ui.ctx());
crate::theme::apply(ui.ctx());
app.install_framework(ui.ctx());
ready = true;
return;
}
let _ = take_registries(ui.ctx());
show(app, ui);
}, app);
let mut h = egui_kittest::Harness::builder().with_size(vec2(320.0, 700.0)).build_ui_state(
move |ui, app: &mut LightcraftApp| {
if !ready {
crate::theme::install_fonts(ui.ctx());
crate::theme::apply(ui.ctx());
app.install_framework(ui.ctx());
ready = true;
return;
}
let _ = take_registries(ui.ctx());
show(app, ui);
},
app,
);
h.run_steps(8);
assert!(h.query_by_label("Sort").is_none(), "narrow layout should not show the wide Sort opener");
h.get_by_label("View").click();
@@ -397,7 +415,8 @@ fn capture_external_sort_popup_matched_old_new() {
}
let _ = take_registries(ui.ctx());
show(app, ui);
}, app,
},
app,
);
harness.input_mut().max_texture_side = Some(8192);
harness.run_steps(8);
@@ -35,13 +35,17 @@ fn open(h: &mut Headless, photo: u64, row: &str) {
// Aim at the part of this specific photo visible inside its real pane response.
let name = format!("cull:{photo}");
let image = h.app.widgets.iter().find(|(key, _)| key == &name).unwrap().1;
let pane = (0..=1u8).find_map(|slot| h.view.ctx.read_response(egui::Id::unique(("cull-tile", slot, photo))))
.expect("real pane for requested photo");
let pane =
(0..=1u8).find_map(|slot| h.view.ctx.read_response(egui::Id::unique(("cull-tile", slot, photo)))).expect("real pane for requested photo");
let visible = pane.interact_rect.intersect(image);
assert!(visible.is_positive(), "requested photo has no visible image area");
let at = visible.center();
ask(h, "ui.clickWidget", json!({"id": name, "button": "right",
"fx": (at.x - image.left()) / image.width(), "fy": (at.y - image.top()) / image.height()}));
ask(
h,
"ui.clickWidget",
json!({"id": name, "button": "right",
"fx": (at.x - image.left()) / image.width(), "fy": (at.y - image.top()) / image.height()}),
);
assert!(craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any));
assert!(h.app.widget_hits.iter().any(|(id, _)| id == row), "real menu response registered for {row}");
}
@@ -71,9 +75,7 @@ fn compare_external155_swap_real_press_release_preserves_active_pin_and_navigati
h.app.synthetic.push(egui::Event::PointerMoved(at));
h.step();
for pressed in [true, false] {
h.app.synthetic.push(egui::Event::PointerButton {
pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE,
});
h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
h.step();
h.step();
}
@@ -148,10 +150,7 @@ fn compare_external155_clear_reference_keyboard_activation_keeps_active_selectio
#[test]
fn compare_external155_escape_cancels_both_menus_without_retargeting_photos() {
let (mut h, ids) = setup();
for (view, photo, row) in [
(ViewMode::Compare, ids[0], "compare:swap"),
(ViewMode::Reference, ids[3], "compare:clearReference"),
] {
for (view, photo, row) in [(ViewMode::Compare, ids[0], "compare:swap"), (ViewMode::Reference, ids[3], "compare:clearReference")] {
h.app.ui.view = view;
h.settle(WAIT);
let before = snapshot(&h);
@@ -174,10 +173,13 @@ fn compare_external155_disabled_real_row_does_not_activate() {
let mut at = egui::Pos2::ZERO;
for frame in 0..5 {
let events = if frame == 2 || frame == 3 {
vec![egui::Event::PointerMoved(at), egui::Event::PointerButton {
pos: at, button: egui::PointerButton::Primary, pressed: frame == 2, modifiers: egui::Modifiers::NONE,
}]
} else { vec![] };
vec![
egui::Event::PointerMoved(at),
egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: frame == 2, modifiers: egui::Modifiers::NONE },
]
} else {
vec![]
};
let raw = HeadlessView::raw_input(egui::vec2(400.0, 200.0), 1.0, frame as f64 / 60.0, events);
view.run(raw, |ui| {
crate::widgets::take_registries(ui.ctx());
-2
View File
@@ -414,7 +414,6 @@ fn photos_queue_actions(ui: &mut egui::Ui, running: Option<(u64, u64)>, queued:
});
}
/// "Denoising {photo}: {done} of {total} tiles", and how many photos wait.
fn running_text(app: &LightcraftApp, status: &Value, done: u64, total: u64, queued: u64) -> String {
let name =
@@ -896,7 +895,6 @@ mod queue_actions_tests;
#[path = "denoise_qualified_work_flow_tests.rs"]
mod qualified_work_flow_tests;
#[cfg(test)]
#[path = "denoise_per_photo_qualified_flow_tests.rs"]
mod per_photo_qualified_flow_tests;
@@ -9,7 +9,10 @@ const QUEUE: &str = "denoise:queueAll";
const STOP: &str = "denoise:stop";
#[derive(Clone, Copy, Default)]
struct Pass { sizing: bool, measuring: bool }
struct Pass {
sizing: bool,
measuring: bool,
}
struct Frames {
ctx: egui::Context,
@@ -36,10 +39,22 @@ impl Frames {
craft::ui::install(
&ctx,
craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), std::sync::Arc::new(craft::window::system::NoWindows)),
).unwrap();
)
.unwrap();
Self {
ctx, time: 0.0, running, queued, disabled: false, pass: Pass::default(), size: vec2(1000.0, 300.0), scale: 1.0,
commands: vec![], rects: vec![], hits: vec![], elements: vec![], nodes: vec![],
ctx,
time: 0.0,
running,
queued,
disabled: false,
pass: Pass::default(),
size: vec2(1000.0, 300.0),
scale: 1.0,
commands: vec![],
rects: vec![],
hits: vec![],
elements: vec![],
nodes: vec![],
}
}
@@ -58,7 +73,9 @@ impl Frames {
self.commands.push((command.into(), params));
});
});
if let Some(record) = record { self.elements = record.elements.clone(); }
if let Some(record) = record {
self.elements = record.elements.clone();
}
};
if self.pass.sizing {
let mut child = ui.new_child(egui::UiBuilder::new().sizing_pass().max_rect(ui.max_rect()));
@@ -81,14 +98,19 @@ impl Frames {
(self.rects, self.hits) = take_registries(&ctx);
}
fn settle(&mut self) { for _ in 0..3 { self.frame(vec![]); } }
fn settle(&mut self) {
for _ in 0..3 {
self.frame(vec![]);
}
}
fn target(&self, id: &str) -> (Rect, WidgetHit) {
assert_eq!(self.rects.iter().filter(|(name, _)| name == id).count(), 1);
assert_eq!(self.hits.iter().filter(|(name, _)| name == id).count(), 1);
let rect = self.rects.iter().find(|(name, _)| name == id).unwrap().1;
let hit = self.hits.iter().find(|(name, _)| name == id).unwrap().1;
let element = self.elements.iter().find(|element| element.id == hit.id && element.part.is_none()).expect("real SDK response owner, not hover probe");
let element =
self.elements.iter().find(|element| element.id == hit.id && element.part.is_none()).expect("real SDK response owner, not hover probe");
assert_eq!(element.component, "Button");
assert_eq!(element.rect, rect);
assert!(rect.is_finite() && rect.is_positive());
@@ -127,8 +149,7 @@ fn pointer(pos: Pos2, button: PointerButton, pressed: bool) -> Event {
}
fn expected(id: &str) -> (String, Value) {
if id == QUEUE { ("denoise.queue".into(), json!({"scope": "withAmount"})) }
else { ("denoise.cancel".into(), json!({})) }
if id == QUEUE { ("denoise.queue".into(), json!({"scope": "withAmount"})) } else { ("denoise.cancel".into(), json!({})) }
}
#[test]
@@ -140,7 +161,9 @@ fn photos_queue_stop_visibility_is_running_or_queued_and_queue_is_always_present
let busy = running.is_some() || queued > 0;
assert_eq!(f.rects.iter().any(|(id, _)| id == STOP), busy);
assert_eq!(f.hits.iter().any(|(id, _)| id == STOP), busy);
if busy { f.target(STOP); }
if busy {
f.target(STOP);
}
assert!(f.commands.is_empty());
}
}
+1 -1
View File
@@ -16,8 +16,8 @@ use crate::widgets::{register, register_geometry};
mod crop;
mod filmstrip;
pub(crate) mod host;
mod geometry;
pub(crate) mod host;
mod info;
mod lens_blur;
mod look_ahead;
+132 -125
View File
@@ -1,4 +1,4 @@
use super::{host, Align2, Color32, LightcraftApp, PhotoId, Pos2, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, json, pos2, register, vec2};
use super::{Align2, Color32, LightcraftApp, PhotoId, Pos2, Rect, Sense, Slot, Stroke, StrokeKind, Tokens, host, json, pos2, register, vec2};
/// Size of the Navigator mini map (points).
const NAV_W: f32 = 180.0;
@@ -79,139 +79,146 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) {
// a wheel notch scrolls a third of its width; see `grid::wheel_step`
register(ui, "filmstrip", child.max_rect());
let wheel = crate::panels::grid::wheel_step(&child, egui::Id::unique("film-wheel"), child.max_rect(), child.max_rect().width(), true);
egui::ScrollArea::horizontal()
.id_salt("filmstrip")
.auto_shrink([false, false])
.scroll_source(crate::panels::grid::WHEEL_OFF)
.show_viewport(&mut child, |ui, vp| {
if wheel != egui::Vec2::ZERO {
ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none());
}
let (area, _) = ui.allocate_exact_size(vec2(ids.len() as f32 * cell_w, r.height() - 16.0), Sense::hover());
app.film_scroll = Some(vp.left());
for (i, id) in ids.iter().enumerate() {
let cr = Rect::from_min_size(pos2(area.left() + i as f32 * cell_w, area.top()), vec2(cell_w, area.height()));
let local = Rect::from_min_size(pos2(i as f32 * cell_w, 0.0), cr.size());
// centred when it is (partly) off screen; a click on a visible thumbnail leaves the strip alone
if follow && Some(*id) == active && !(local.left() >= vp.left() && local.right() <= vp.right()) {
ui.scroll_to_rect(cr, Some(egui::Align::Center));
egui::ScrollArea::horizontal().id_salt("filmstrip").auto_shrink([false, false]).scroll_source(crate::panels::grid::WHEEL_OFF).show_viewport(
&mut child,
|ui, vp| {
if wheel != egui::Vec2::ZERO {
ui.scroll_with_delta_animation(wheel, egui::style::ScrollAnimation::none());
}
if !local.intersects(vp.expand2(vec2(cell_w * 4.0, 0.0))) {
continue;
}
let failed = app.renderer.thumb(*id).is_none() && app.renderer.failure(Slot::Thumb(*id)).is_some();
let spoken = film_spoken(app.session.catalog.photo(*id).map_or("", |p| p.file_name.as_str()), failed);
let resp = host::target(ui, ("film", id.0), cr, host::Target::new(spoken).drag());
if host::live(ui) {
crate::widgets::register_response(format!("film:{}", id.0), cr, &resp);
}
let state = app.session.selection.state_of(*id);
let p = ui.painter();
let label = app.session.catalog.photo(*id).and_then(|ph| ph.label);
let selected = state != lightcraft_engine::SelectionState::NotSelected;
let base = if selected {
t.cell_selected
} else if resp.hovered() {
t.cell_selected.gamma_multiply(0.6)
} else {
t.canvas
};
p.rect_filled(cr, 0.0, crate::theme::label_background(base, label, selected));
let names = app.ui.settings.film_names;
if let Some(ph) = app.session.catalog.photo(*id).filter(|_| names) {
let name = ph.file_name.rsplit_once('.').map(|(n, _)| n).unwrap_or(&ph.file_name);
p.text(pos2(cr.left() + 8.0, cr.top() + 10.0), Align2::LEFT_CENTER, film_label(name), t.font(10.0), t.text_dim);
p.text(pos2(cr.right() - 8.0, cr.top() + 10.0), Align2::RIGHT_CENTER, &ph.format, t.semibold(8.5), t.text_dim);
}
let img_area = Rect::from_min_max(cr.min + vec2(10.0, 22.0), cr.max - vec2(10.0, 8.0));
crate::panels::grid::request_thumb(app, *id, (256.0 * ppp.min(2.0) / 2.0) as usize * 2, 8);
let thumb = app.renderer.thumb(*id);
if thumb.is_none() {
p.rect_filled(img_area, 0.0, t.skeleton);
if failed {
p.text(img_area.center(), Align2::CENTER_CENTER, "!", t.semibold(14.0), t.text);
let (area, _) = ui.allocate_exact_size(vec2(ids.len() as f32 * cell_w, r.height() - 16.0), Sense::hover());
app.film_scroll = Some(vp.left());
for (i, id) in ids.iter().enumerate() {
let cr = Rect::from_min_size(pos2(area.left() + i as f32 * cell_w, area.top()), vec2(cell_w, area.height()));
let local = Rect::from_min_size(pos2(i as f32 * cell_w, 0.0), cr.size());
// centred when it is (partly) off screen; a click on a visible thumbnail leaves the strip alone
if follow && Some(*id) == active && !(local.left() >= vp.left() && local.right() <= vp.right()) {
ui.scroll_to_rect(cr, Some(egui::Align::Center));
}
}
if let Some(tex) = thumb {
let [tw, th] = tex.size;
let s = (img_area.width() / tw as f32).min(img_area.height() / th as f32);
let fr = Rect::from_center_size(img_area.center(), vec2(tw as f32 * s, th as f32 * s));
p.image(tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
crate::panels::grid::selection_ring(p, &t, fr, state);
if app.ui.settings.film_badges
&& let Some(ph) = app.session.catalog.photo(*id)
{
film_badges(p, &t, fr, ph);
if !local.intersects(vp.expand2(vec2(cell_w * 4.0, 0.0))) {
continue;
}
if let Some(st) = app.session.catalog.stack_of(*id) {
let collapsed = st.collapsed;
let text =
if collapsed { st.photos.len().to_string() } else { format!("{}/{}", st.position(*id).unwrap_or(0) + 1, st.photos.len()) };
let g = p.layout_no_wrap(text, t.semibold(9.5), Color32::WHITE);
let br = Rect::from_min_size(fr.min + vec2(3.0, 3.0), vec2(g.size().x + 22.0, 15.0));
// like the grid's badge: a click expands / collapses the stack
let badge = host::target(
ui,
("film-stack-badge", id.0),
br,
host::Target::new(crate::i18n::tr(if collapsed { "Expand Stack" } else { "Collapse Stack" })).tooltip(if collapsed {
"Stack — click to expand"
} else {
"Stack — click to collapse"
}),
);
if host::live(ui) {
crate::widgets::register_response(format!("filmstack:{}", id.0), br, &badge);
}
let p = ui.painter();
let fill = if badge.hovered() { Color32::from_black_alpha(230) } else { Color32::from_black_alpha(170) };
p.rect_filled(br, 7.5, fill);
crate::icons::paint(p, Rect::from_min_size(br.min + vec2(4.0, 2.0), vec2(11.0, 11.0)), crate::icons::Icon::Stack, Color32::WHITE);
p.galley(pos2(br.min.x + 17.0, br.center().y - g.size().y / 2.0), g, Color32::WHITE);
if badge.clicked() {
crate::panels::grid::toggle_stack(app, ui.ctx(), *id);
}
let failed = app.renderer.thumb(*id).is_none() && app.renderer.failure(Slot::Thumb(*id)).is_some();
let spoken = film_spoken(app.session.catalog.photo(*id).map_or("", |p| p.file_name.as_str()), failed);
let resp = host::target(ui, ("film", id.0), cr, host::Target::new(spoken).drag());
if host::live(ui) {
crate::widgets::register_response(format!("film:{}", id.0), cr, &resp);
}
}
if resp.clicked() {
let m = ui.input(|i| i.modifiers);
let compare = app.ui.view == crate::state::ViewMode::Compare;
let r = if compare && !m.command && !m.shift {
// Compare: the clicked photo replaces the active side (or swaps with the other one)
app.run("compare.set", json!({"id": id.0}))
} else if compare {
// ⌘/Ctrl- and Shift-clicks change the selection; the pair on screen stays (#187)
crate::panels::compare::select_with_modifier(app, *id, !m.command)
let state = app.session.selection.state_of(*id);
let p = ui.painter();
let label = app.session.catalog.photo(*id).and_then(|ph| ph.label);
let selected = state != lightcraft_engine::SelectionState::NotSelected;
let base = if selected {
t.cell_selected
} else if resp.hovered() {
t.cell_selected.gamma_multiply(0.6)
} else {
let mode = if m.command {
"toggle"
} else if m.shift {
"range"
} else {
"replace"
};
app.run("library.select", json!({"ids": [id.0], "mode": mode}))
t.canvas
};
if compare && let Err(e) = r {
app.toast(ui.ctx(), e);
p.rect_filled(cr, 0.0, crate::theme::label_background(base, label, selected));
let names = app.ui.settings.film_names;
if let Some(ph) = app.session.catalog.photo(*id).filter(|_| names) {
let name = ph.file_name.rsplit_once('.').map(|(n, _)| n).unwrap_or(&ph.file_name);
p.text(pos2(cr.left() + 8.0, cr.top() + 10.0), Align2::LEFT_CENTER, film_label(name), t.font(10.0), t.text_dim);
p.text(pos2(cr.right() - 8.0, cr.top() + 10.0), Align2::RIGHT_CENTER, &ph.format, t.semibold(8.5), t.text_dim);
}
}
// drag the selection to a sidebar row, as from the grid (a plain click never starts one); in
// Compare an unselected photo is dragged alone, so the pair and its active photo stay (#744).
// Only the primary button drags: a right-button drag must not replace the selection
if resp.drag_started_by(egui::PointerButton::Primary) {
if app.ui.view == crate::state::ViewMode::Compare && !app.session.selection.contains(*id) {
app.ui.dragging_photos = Some(vec![id.0]);
} else {
crate::panels::grid::begin_photo_drag(app, *id);
let img_area = Rect::from_min_max(cr.min + vec2(10.0, 22.0), cr.max - vec2(10.0, 8.0));
crate::panels::grid::request_thumb(app, *id, (256.0 * ppp.min(2.0) / 2.0) as usize * 2, 8);
let thumb = app.renderer.thumb(*id);
if thumb.is_none() {
p.rect_filled(img_area, 0.0, t.skeleton);
if failed {
p.text(img_area.center(), Align2::CENTER_CENTER, "!", t.semibold(14.0), t.text);
}
}
if let Some(tex) = thumb {
let [tw, th] = tex.size;
let s = (img_area.width() / tw as f32).min(img_area.height() / th as f32);
let fr = Rect::from_center_size(img_area.center(), vec2(tw as f32 * s, th as f32 * s));
p.image(tex.id(), fr, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
crate::panels::grid::selection_ring(p, &t, fr, state);
if app.ui.settings.film_badges
&& let Some(ph) = app.session.catalog.photo(*id)
{
film_badges(p, &t, fr, ph);
}
if let Some(st) = app.session.catalog.stack_of(*id) {
let collapsed = st.collapsed;
let text = if collapsed {
st.photos.len().to_string()
} else {
format!("{}/{}", st.position(*id).unwrap_or(0) + 1, st.photos.len())
};
let g = p.layout_no_wrap(text, t.semibold(9.5), Color32::WHITE);
let br = Rect::from_min_size(fr.min + vec2(3.0, 3.0), vec2(g.size().x + 22.0, 15.0));
// like the grid's badge: a click expands / collapses the stack
let badge = host::target(
ui,
("film-stack-badge", id.0),
br,
host::Target::new(crate::i18n::tr(if collapsed { "Expand Stack" } else { "Collapse Stack" })).tooltip(if collapsed {
"Stack — click to expand"
} else {
"Stack — click to collapse"
}),
);
if host::live(ui) {
crate::widgets::register_response(format!("filmstack:{}", id.0), br, &badge);
}
let p = ui.painter();
let fill = if badge.hovered() { Color32::from_black_alpha(230) } else { Color32::from_black_alpha(170) };
p.rect_filled(br, 7.5, fill);
crate::icons::paint(
p,
Rect::from_min_size(br.min + vec2(4.0, 2.0), vec2(11.0, 11.0)),
crate::icons::Icon::Stack,
Color32::WHITE,
);
p.galley(pos2(br.min.x + 17.0, br.center().y - g.size().y / 2.0), g, Color32::WHITE);
if badge.clicked() {
crate::panels::grid::toggle_stack(app, ui.ctx(), *id);
}
}
}
if resp.clicked() {
let m = ui.input(|i| i.modifiers);
let compare = app.ui.view == crate::state::ViewMode::Compare;
let r = if compare && !m.command && !m.shift {
// Compare: the clicked photo replaces the active side (or swaps with the other one)
app.run("compare.set", json!({"id": id.0}))
} else if compare {
// ⌘/Ctrl- and Shift-clicks change the selection; the pair on screen stays (#187)
crate::panels::compare::select_with_modifier(app, *id, !m.command)
} else {
let mode = if m.command {
"toggle"
} else if m.shift {
"range"
} else {
"replace"
};
app.run("library.select", json!({"ids": [id.0], "mode": mode}))
};
if compare && let Err(e) = r {
app.toast(ui.ctx(), e);
}
}
// drag the selection to a sidebar row, as from the grid (a plain click never starts one); in
// Compare an unselected photo is dragged alone, so the pair and its active photo stay (#744).
// Only the primary button drags: a right-button drag must not replace the selection
if resp.drag_started_by(egui::PointerButton::Primary) {
if app.ui.view == crate::state::ViewMode::Compare && !app.session.selection.contains(*id) {
app.ui.dragging_photos = Some(vec![id.0]);
} else {
crate::panels::grid::begin_photo_drag(app, *id);
}
}
// the same photo actions as the grid and loupe (Restore / Delete Permanently in Recently Deleted)
host::context_menu(ui, &resp, crate::i18n::tr("Photo"), |ui| crate::panels::grid::context_menu(app, ui, *id));
}
// the same photo actions as the grid and loupe (Restore / Delete Permanently in Recently Deleted)
host::context_menu(ui, &resp, crate::i18n::tr("Photo"), |ui| crate::panels::grid::context_menu(app, ui, *id));
}
// Tab and focus requests keep the focused thumbnail in view
crate::panels::scroll_focus::reveal_focus(ui, egui::Id::unique("film-scroll-focus"));
});
// Tab and focus requests keep the focused thumbnail in view
crate::panels::scroll_focus::reveal_focus(ui, egui::Id::unique("film-scroll-focus"));
},
);
}
/// What a screen reader says for a filmstrip thumbnail: the file, and why there is no picture
+5 -5
View File
@@ -9,10 +9,10 @@ use std::hash::Hash;
use std::ops::Deref;
use craft::behavior::{Metrics, PressPhase, Sense};
use craft::ui::contract::{Common, Component, Cx, NoValue, Outcome, PaintUi, Pointer as _, Props as _, Role, Show as _};
use craft::ui::runtime::access::Access;
use craft::ui::menu::Menu;
use craft::ui::contract::ShowContainer as _;
use craft::ui::contract::{Common, Component, Cx, NoValue, Outcome, PaintUi, Pointer as _, Props as _, Role, Show as _};
use craft::ui::menu::Menu;
use craft::ui::runtime::access::Access;
use craft::ui::style::{ComponentStyle, FocusLook, StyleCx};
use egui::{Color32, Rect, Response, Ui};
@@ -122,7 +122,8 @@ impl HostOutput {
/// A secondary-button click landed on the target this pass. The SDK rewrites the response's own click flags
/// (`Response::clicked` is the primary activation), so this reads egui's raw verdict for the same widget.
pub fn secondary_clicked(&self) -> bool {
self.response.secondary_clicked() || self.response.ctx.read_response(self.response.id).is_some_and(|raw| raw.enabled() && raw.secondary_clicked())
self.response.secondary_clicked()
|| self.response.ctx.read_response(self.response.id).is_some_and(|raw| raw.enabled() && raw.secondary_clicked())
}
/// The activation was the second press of a double click.
@@ -206,7 +207,6 @@ impl<'a> Target<'a> {
self.mode = Mode::Pointer;
self
}
}
/// Show a host-painted target over `rect`, named `key` for egui. The caller registers its automation name with
+3 -3
View File
@@ -1,9 +1,9 @@
use super::geometry::CanvasMap;
use crate::panels::masking::controls::Hit;
use super::{
Color32, DevelopSettings, Gesture, LightcraftApp, MaskShape, Point, Pos2, Rect, Stroke, StrokeKind, Tokens, ToolOverlay, json, pos2,
register, vec2,
Color32, DevelopSettings, Gesture, LightcraftApp, MaskShape, Point, Pos2, Rect, Stroke, StrokeKind, Tokens, ToolOverlay, json, pos2, register,
vec2,
};
use crate::panels::masking::controls::Hit;
/// What the user did to a face box this frame.
pub(super) enum RegionEdit {
+70 -54
View File
@@ -1,10 +1,10 @@
use super::histogram::preview_histogram;
use crate::panels::detail::host;
use super::sliders::control;
use super::{
Align2, Color32, DevelopSettings, Icon, LightcraftApp, Mesh, PARAM_AMOUNTS, ParametricCurve, PhotoId, Point, Pos2, Rect, RichText, Sense, Stroke,
Tokens, Vertex, controls, hex, json, paint, pos2, text_button, vec2,
};
use crate::panels::detail::host;
// ------------------------------------------------------------------------------ tone curve
@@ -428,7 +428,8 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings)
let builtin = current.as_ref().is_none_or(|name| all_presets(&app.session).iter().any(|p| p.builtin && &p.name == name));
let label = crate::i18n::builtin_label(current.as_deref().unwrap_or("Custom"), builtin);
use craft::ui::contract::Show as _;
let face = craft::ui::buttons::Button::new(crate::i18n::tr("Point Curve preset")).painted(label.to_owned()).id_salt("curvePreset").show(ui);
let face =
craft::ui::buttons::Button::new(crate::i18n::tr("Point Curve preset")).painted(label.to_owned()).id_salt("curvePreset").show(ui);
let activated = face.clicked();
let r = face.response;
if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
@@ -437,74 +438,89 @@ fn curve_footer(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings)
let active = ui.is_enabled() && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx());
// Keep traversal, contextual actions and dismissal in the same SDK menu system.
// A framework-owned opener is reachable from other SDK controls before the menu is open.
use craft::ui::contract::{Props as _, ShowContainer as _};
use craft::ui::contract::overlay::Trigger;
use craft::ui::contract::{Props as _, ShowContainer as _};
use craft::ui::menu::Menu;
if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
// Use the button's SDK activation, not the external pointer-only press trigger.
// Forget the open state after the panel stops drawing, as in Presets options.
let pass = ui.ctx().cumulative_pass_nr();
let slot = r.id.with("menu-open");
let mut open = ui.data(|d| d.get_temp::<(u64, bool)>(slot))
let mut open = ui
.data(|d| d.get_temp::<(u64, bool)>(slot))
.filter(|(last, _)| *last == pass || last.saturating_add(1) == pass)
.is_some_and(|(_, open)| open);
if active && activated { open = !open; }
Menu::new(crate::i18n::tr("Point Curve")).id_salt("curve-preset-menu").tab_exits().opened_by(&r, Trigger::Manual)
.open(craft::ui::contract::Bind::bound(&mut open)).show(ui, |ui, _| {
ui.set_min_width(180.0);
let presets = all_presets(&app.session);
let mut user_seen = false;
for p in &presets {
if !p.builtin && !user_seen {
user_seen = true;
ui.separator();
if active && activated {
open = !open;
}
Menu::new(crate::i18n::tr("Point Curve"))
.id_salt("curve-preset-menu")
.tab_exits()
.opened_by(&r, Trigger::Manual)
.open(craft::ui::contract::Bind::bound(&mut open))
.show(ui, |ui, _| {
ui.set_min_width(180.0);
let presets = all_presets(&app.session);
let mut user_seen = false;
for p in &presets {
if !p.builtin && !user_seen {
user_seen = true;
ui.separator();
}
let id = format!("curvePreset:{}", p.name);
let (r, ran) = preset_item(
ui,
&id,
crate::i18n::builtin_label(&p.name, p.builtin),
Some(current.as_deref() == Some(p.name.as_str())),
active,
true,
);
if ran {
let _ = app.run("curve.applyPreset", json!({"name": p.name}));
}
if active && !p.builtin && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
Menu::context(crate::i18n::tr("Delete Preset"), &r).id_salt(("curve-preset-context", &p.name)).show(ui, |ui, _| {
if preset_item(ui, &format!("curvePresetDelete:{}", p.name), crate::i18n::tr("Delete Preset"), None, active, true)
.1
{
let _ = app.run("curve.deletePreset", json!({"name":p.name}));
}
});
}
}
let id = format!("curvePreset:{}", p.name);
let (r, ran) = preset_item(
ui.separator();
let shaped = current.as_deref() != Some("Linear");
if preset_item(ui, "curvePresetMenu:save", crate::i18n::tr("Save Point Curve…"), None, active, shaped).1 {
crate::panels::dialogs::prompt(app, "Save Point Curve Preset", "Preset name", "", "curve.savePreset", json!({}), "name");
}
if preset_item(
ui,
&id,
crate::i18n::builtin_label(&p.name, p.builtin),
Some(current.as_deref() == Some(p.name.as_str())),
"curvePresetMenu:import",
crate::i18n::tr("Import Presets…"),
None,
active,
true,
);
if ran {
let _ = app.run("curve.applyPreset", json!({"name": p.name}));
app.services.pick_curve_preset_files.is_some(),
)
.1
{
let _ = app.run("file.importCurvePresets", json!({}));
}
if active && !p.builtin && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
Menu::context(crate::i18n::tr("Delete Preset"), &r).id_salt(("curve-preset-context", &p.name)).show(ui, |ui, _| {
if preset_item(ui, &format!("curvePresetDelete:{}", p.name), crate::i18n::tr("Delete Preset"), None, active, true).1 {
let _ = app.run("curve.deletePreset", json!({"name":p.name}));
}
});
let can_export = app.services.save_curve_preset_file.is_some() && !app.session.curve_presets.is_empty();
if preset_item(ui, "curvePresetMenu:export", crate::i18n::tr("Export Presets…"), None, active, can_export).1 {
let _ = app.run("file.exportCurvePresets", json!({}));
}
}
ui.separator();
let shaped = current.as_deref() != Some("Linear");
if preset_item(ui, "curvePresetMenu:save", crate::i18n::tr("Save Point Curve…"), None, active, shaped).1 {
crate::panels::dialogs::prompt(app, "Save Point Curve Preset", "Preset name", "", "curve.savePreset", json!({}), "name");
}
if preset_item(
ui,
"curvePresetMenu:import",
crate::i18n::tr("Import Presets…"),
None,
active,
app.services.pick_curve_preset_files.is_some(),
)
.1
{
let _ = app.run("file.importCurvePresets", json!({}));
}
let can_export = app.services.save_curve_preset_file.is_some() && !app.session.curve_presets.is_empty();
if preset_item(ui, "curvePresetMenu:export", crate::i18n::tr("Export Presets…"), None, active, can_export).1 {
let _ = app.run("file.exportCurvePresets", json!({}));
}
if presets.iter().any(|p| !p.builtin) {
ui.label(RichText::new(crate::i18n::tr("Right-click a preset to delete it")).font(t.font(11.0)).color(t.text_dim));
if presets.iter().any(|p| !p.builtin) {
ui.label(RichText::new(crate::i18n::tr("Right-click a preset to delete it")).font(t.font(11.0)).color(t.text_dim));
}
});
ui.data_mut(|d| {
if open {
d.insert_temp(slot, (pass, true));
} else {
d.remove::<(u64, bool)>(slot);
}
});
ui.data_mut(|d| { if open { d.insert_temp(slot, (pass, true)); } else { d.remove::<(u64, bool)>(slot); } });
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let r = text_button(ui, "curveReset", crate::i18n::tr("Reset"), false).on_hover_text(crate::i18n::tr(
@@ -113,7 +113,7 @@ impl PresetFrames {
self.settle();
}
fn menu_open(&self) -> bool {
use craft::ui::runtime::overlay::{any_open, OpenFilter};
use craft::ui::runtime::overlay::{OpenFilter, any_open};
any_open(&self.ctx, OpenFilter::Keys)
}
fn open(&mut self) {
@@ -190,9 +190,13 @@ fn secondary_delete_cancel_does_not_leak_to_reopened_or_builtin_preset() {
key(&mut f, Key::Escape);
assert_ne!(craft::ui::runtime::overlay::top(&f.ctx), Some(context), "Escape must dismiss the context menu");
// The exiting layer can still paint, but must remove its registered row after the fade.
for _ in 0..20 { f.frame(vec![]); }
for _ in 0..20 {
f.frame(vec![]);
}
assert!(!f.hits.iter().any(|(name, _)| name.starts_with("curvePresetDelete:")));
if f.menu_open() { key(&mut f, Key::Escape); }
if f.menu_open() {
key(&mut f, Key::Escape);
}
assert!(!f.menu_open());
f.open();
assert!(!f.hits.iter().any(|(name, _)| name.starts_with("curvePresetDelete:")));
@@ -253,7 +257,9 @@ fn escape_dismisses_then_keyboard_reopens_and_applies_focused_preset() {
assert!(f.menu_open());
let owner = f.hit("curvePreset:Medium Contrast").id;
for _ in 0..3 {
if f.ctx.memory(|m| m.has_focus(owner)) { break; }
if f.ctx.memory(|m| m.has_focus(owner)) {
break;
}
key(&mut f, Key::ArrowDown);
}
assert!(f.ctx.memory(|m| m.has_focus(owner)));
@@ -294,7 +300,9 @@ fn tab_to_closed_opener_then_enter_arrows_and_enter_apply_once() {
let before = snapshot(&f.app);
f.frame(vec![Event::PointerGone]);
for _ in 0..40 {
if f.ctx.memory(|m| m.has_focus(opener)) { break; }
if f.ctx.memory(|m| m.has_focus(opener)) {
break;
}
key(&mut f, Key::Tab);
}
assert!(f.ctx.memory(|m| m.has_focus(opener)), "Tab must reach the closed preset opener");
@@ -303,7 +311,9 @@ fn tab_to_closed_opener_then_enter_arrows_and_enter_apply_once() {
assert!(f.menu_open());
let row = f.hit("curvePreset:Medium Contrast").id;
for _ in 0..3 {
if f.ctx.memory(|m| m.has_focus(row)) { break; }
if f.ctx.memory(|m| m.has_focus(row)) {
break;
}
key(&mut f, Key::ArrowDown);
}
assert!(f.ctx.memory(|m| m.has_focus(row)));
@@ -317,7 +327,10 @@ fn tab_to_closed_opener_then_enter_arrows_and_enter_apply_once() {
fn tab_direction(f: &mut PresetFrames, reverse: bool) {
let modifiers = Modifiers { shift: reverse, ..Modifiers::NONE };
for pressed in [true, false] {
f.frame(vec![Event::ModifiersChanged(modifiers), Event::Key { key: Key::Tab, physical_key: Some(Key::Tab), pressed, repeat: false, modifiers }]);
f.frame(vec![
Event::ModifiersChanged(modifiers),
Event::Key { key: Key::Tab, physical_key: Some(Key::Tab), pressed, repeat: false, modifiers },
]);
}
f.frame(vec![Event::ModifiersChanged(Modifiers::NONE)]);
f.settle();
@@ -325,7 +338,9 @@ fn tab_direction(f: &mut PresetFrames, reverse: bool) {
fn tab_to_opener(f: &mut PresetFrames) -> egui::Id {
let owner = f.hit("dropdown:curvePreset").id;
for _ in 0..40 {
if f.ctx.memory(|m| m.has_focus(owner)) { return owner; }
if f.ctx.memory(|m| m.has_focus(owner)) {
return owner;
}
key(f, Key::Tab);
}
panic!("Tab did not reach the closed Curve opener");
@@ -354,11 +369,17 @@ fn check_curve_exit(reverse: bool, escape: bool) {
assert_eq!(focus, Some(neighbor), "focus must continue to the real closed-menu neighbor");
}
#[test]
fn tab_leaves_curve_menu_for_next_control_without_applying() { check_curve_exit(false, false); }
fn tab_leaves_curve_menu_for_next_control_without_applying() {
check_curve_exit(false, false);
}
#[test]
fn shift_tab_leaves_curve_menu_for_previous_control_without_applying() { check_curve_exit(true, false); }
fn shift_tab_leaves_curve_menu_for_previous_control_without_applying() {
check_curve_exit(true, false);
}
#[test]
fn escape_returns_to_opener_then_tab_reaches_next_control() { check_curve_exit(false, true); }
fn escape_returns_to_opener_then_tab_reaches_next_control() {
check_curve_exit(false, true);
}
fn live_preset(mode: u8) {
let mut f = PresetFrames::new("master");
@@ -31,8 +31,14 @@ impl CurveResetFrames {
app.run("develop.curve", json!({"channel": channel, "points": [[0.0, 0.05], [0.4, 0.6], [1.0, 0.95]]})).unwrap();
}
for (control, value) in [
("curve.shadows", 25), ("curve.darks", -20), ("curve.lights", 30), ("curve.highlights", -35),
("curve.splitShadows", 20), ("curve.splitMid", 45), ("curve.splitHighlights", 80), ("curve.refineSaturation", 42),
("curve.shadows", 25),
("curve.darks", -20),
("curve.lights", 30),
("curve.highlights", -35),
("curve.splitShadows", 20),
("curve.splitMid", 45),
("curve.splitHighlights", 80),
("curve.refineSaturation", 42),
] {
app.run("develop.set", json!({"control": control, "value": value})).unwrap();
}
@@ -64,7 +70,9 @@ impl CurveResetFrames {
}
fn settle(&mut self) {
for _ in 0..3 { self.frame(vec![]); }
for _ in 0..3 {
self.frame(vec![]);
}
}
fn rect(&self, id: &str) -> Rect {
@@ -140,8 +148,11 @@ fn expected_current(mut before: ToneCurve, channel: &str) -> ToneCurve {
#[test]
fn sdk_curve_reset_current_keeps_channel_payload_and_restores_full_settings_on_undo() {
for (channel, label) in [
("parametric", "Reset Parametric Curve"), ("master", "Reset RGB Channel"),
("red", "Reset Red Channel"), ("green", "Reset Green Channel"), ("blue", "Reset Blue Channel"),
("parametric", "Reset Parametric Curve"),
("master", "Reset RGB Channel"),
("red", "Reset Red Channel"),
("green", "Reset Green Channel"),
("blue", "Reset Blue Channel"),
] {
let mut f = CurveResetFrames::new(channel);
let before = f.settings();
@@ -242,13 +253,19 @@ fn sdk_curve_reset_each_sizing_mode_suppresses_automation_and_commands() {
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
let mut draw = || {
let mut builder = egui::UiBuilder::new().max_rect(ui.max_rect());
if egui_sizing { builder = builder.sizing_pass(); }
if egui_sizing {
builder = builder.sizing_pass();
}
let mut child = ui.new_child(builder);
assert_eq!(child.is_sizing_pass(), egui_sizing);
assert_eq!(craft::ui::runtime::measure::active(child.ctx()), sdk_measure);
curve_reset_menu(&mut f.app, &mut child, "parametric");
};
if sdk_measure { craft::ui::runtime::measure::run(&ctx, draw); } else { draw(); }
if sdk_measure {
craft::ui::runtime::measure::run(&ctx, draw);
} else {
draw();
}
});
output.textures_delta.clear();
let (rects, hits) = take_registries(&ctx);
+9 -4
View File
@@ -51,9 +51,13 @@ fn eye_owns_pointer(ui: &egui::Ui, key: &str, eye: Rect) -> bool {
return false;
}
let id = egui::Id::unique(("wheelEyePress", key));
let began = ui.input(|input| input.events.iter().any(|event| matches!(event,
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } if eye.contains(*pos)
)));
let began = ui.input(|input| {
input.events.iter().any(|event| {
matches!(event,
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } if eye.contains(*pos)
)
})
});
let owned = began || ui.data(|data| data.get_temp::<bool>(id)).unwrap_or(false);
let down = ui.input(|input| input.pointer.primary_down());
ui.data_mut(|data| data.insert_temp(id, owned && down));
@@ -230,7 +234,8 @@ fn grading_wheel(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettings
if wheel_input && resp.drag_started() {
let _ = app.run("develop.beginInteraction", json!({"label": crate::i18n::tr_format!("{label} Grading", label = label)}));
}
if wheel_input && (resp.dragged() || resp.clicked())
if wheel_input
&& (resp.dragged() || resp.clicked())
&& let Some(q) = pointer
{
let (hue, sat) = grab.map_or_else(|| wheel_pick(q - c, rad, None), |g| g.pick(q - c, rad));
@@ -82,9 +82,13 @@ impl Frames {
self.last_eye_down = Some(hit.id);
}
// a button-role toggle reports its state as pressed (toggled), not selected
if let Some(node) =
ctx.accesskit_node_builder(hit.id, |n| (n.label().map(str::to_owned), n.toggled().and_then(|t| (t == egui::accesskit::Toggled::True).then_some(true)), n.description().map(str::to_owned)))
{
if let Some(node) = ctx.accesskit_node_builder(hit.id, |n| {
(
n.label().map(str::to_owned),
n.toggled().and_then(|t| (t == egui::accesskit::Toggled::True).then_some(true)),
n.description().map(str::to_owned),
)
}) {
self.nodes.insert(hit.id, node);
}
}
+33 -18
View File
@@ -79,7 +79,12 @@ pub(crate) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId)
// measuring run senses nothing.
let live = crate::panels::detail::host::live(ui);
let target = live.then(|| {
crate::panels::detail::host::target(ui, ("edit-histogram", id), r, crate::panels::detail::host::Target::new(crate::i18n::tr("Histogram")).drag())
crate::panels::detail::host::target(
ui,
("edit-histogram", id),
r,
crate::panels::detail::host::Target::new(crate::i18n::tr("Histogram")).drag(),
)
});
let resp = target.as_ref().map_or_else(|| ui.response(), |target| target.response.clone());
if let Some(target) = &target {
@@ -277,29 +282,39 @@ pub(super) fn soft_proofing(app: &mut LightcraftApp, ui: &mut egui::Ui, id: Phot
let shown = device.clone().unwrap_or_else(|| cur.label().to_string());
let mut pick = false;
let (_, face_rect) = ui.allocate_space(vec2(170.0, 24.0));
let face = Button::new(crate::i18n::tr("Profile")).painted(shown).trailing_icon(DisclosureGlyph::dropdown()).id_salt("proof-space").show_at(ui, face_rect);
let face = Button::new(crate::i18n::tr("Profile"))
.painted(shown)
.trailing_icon(DisclosureGlyph::dropdown())
.id_salt("proof-space")
.show_at(ui, face_rect);
let real = !proof_measuring(ui);
if real {
crate::widgets::register_response("dropdown:proofProfile", face_rect, &face.response);
}
Menu::new(crate::i18n::tr("Profile").to_owned()).id_salt("proof-space-menu").values().opened_by(&face.response, Trigger::Click).show(ui, |ui, _| {
let real = !proof_measuring(ui);
for s in OutputSpace::ALL {
let row = MenuItem::new(s.label().to_owned()).id_salt(("proof-space-item", s.label())).entry_checked(device.is_none() && cur == s).show(ui);
if real && row.ran {
let _ = app.run("view.softProof", json!({"space": s}));
Menu::new(crate::i18n::tr("Profile").to_owned()).id_salt("proof-space-menu").values().opened_by(&face.response, Trigger::Click).show(
ui,
|ui, _| {
let real = !proof_measuring(ui);
for s in OutputSpace::ALL {
let row = MenuItem::new(s.label().to_owned())
.id_salt(("proof-space-item", s.label()))
.entry_checked(device.is_none() && cur == s)
.show(ui);
if real && row.ran {
let _ = app.run("view.softProof", json!({"space": s}));
}
}
}
if let Some(n) = &device {
let _ = MenuItem::new(n.clone()).id_salt("proof-space-device").entry_checked(true).show(ui);
}
if app.services.pick_display_profile.is_some() {
let row = MenuItem::new(crate::i18n::tr("Other…").to_owned()).id_salt("proof-space-other").show(ui);
if real && row.ran {
pick = true;
if let Some(n) = &device {
let _ = MenuItem::new(n.clone()).id_salt("proof-space-device").entry_checked(true).show(ui);
}
}
});
if app.services.pick_display_profile.is_some() {
let row = MenuItem::new(crate::i18n::tr("Other…").to_owned()).id_salt("proof-space-other").show(ui);
if real && row.ran {
pick = true;
}
}
},
);
if pick
&& let Some(path) = app.services.pick_display_profile.as_mut().and_then(|pick| pick().into_iter().next())
&& let Err(e) = app.run("view.softProof", json!({"profile": path}))
+11 -4
View File
@@ -138,7 +138,14 @@ fn lens_blur_focus(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettin
.values()
.opened_by(&r, Trigger::Click)
.show(ui, |ui, _| {
if lens_blur_focus_item(ui, "lensBlurFocus:subject", crate::i18n::tr("Subject"), chosen.is_none() && auto, enabled, parent_measuring) {
if lens_blur_focus_item(
ui,
"lensBlurFocus:subject",
crate::i18n::tr("Subject"),
chosen.is_none() && auto,
enabled,
parent_measuring,
) {
pick = Some(None);
}
for m in &d.masks {
@@ -149,7 +156,8 @@ fn lens_blur_focus(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSettin
}
});
}
if !lens_blur_measuring(ui) && ui.is_enabled()
if !lens_blur_measuring(ui)
&& ui.is_enabled()
&& let Some(focus) = pick
{
// "Subject": the estimate again, not a fixed shape
@@ -240,8 +248,7 @@ fn focus_shape_row(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_de
paint_focus_shape(ui.painter(), out.response.rect.shrink(5.0), shape, colour);
// A selected preset is an action when moved, but a genuine no-op while already centered.
if interactive && app.session.active() == owner && out.clicked() && (!selected || b.area.is_some()) {
let _ =
app.run("develop.merge", json!({"settings": {"lens_blur": {"shape": name, "area": null}}, "label": "Lens Blur Shape"}));
let _ = app.run("develop.merge", json!({"settings": {"lens_blur": {"shape": name, "area": null}}, "label": "Lens Blur Shape"}));
}
}
});
@@ -52,7 +52,6 @@ fn controls(app: &mut LightcraftApp, ui: &mut Ui, adapter: Adapter) {
});
}
/// A popup is open: the previous native candidate's egui popup, or the framework menu that replaced it (a layer of
/// the framework's that takes keys).
fn popup_open(ctx: &egui::Context) -> bool {
@@ -19,9 +19,13 @@ struct Nudges {
}
fn available(app: &LightcraftApp) -> bool {
app.ui.right == crate::state::RightPanel::Edit && !app.ui.fullscreen
&& app.ui.section_open("light") && !app.ui.section_folded("light")
&& app.ui.dialog.is_none() && app.ui.name_edit.is_none() && app.recording_shortcut.is_none()
app.ui.right == crate::state::RightPanel::Edit
&& !app.ui.fullscreen
&& app.ui.section_open("light")
&& !app.ui.section_folded("light")
&& app.ui.dialog.is_none()
&& app.ui.name_edit.is_none()
&& app.recording_shortcut.is_none()
&& !crate::panels::notices::blocks_input(app)
&& !crate::panels::library_problem::blocks_dialog_input(app)
&& !crate::updates_ui::blocks_input(app)
@@ -138,12 +142,16 @@ pub(super) fn apply_pending(app: &mut LightcraftApp, ui: &egui::Ui) {
}
ctx.data_mut(|data| data.remove::<Nudges>(key));
for (id, steps) in TONAL.iter().zip(pending.steps) {
if steps == 0 { continue; }
if steps == 0 {
continue;
}
let Some(spec) = controls::find(id) else { continue };
let settings = app.session.develop_of(pending.photo).unwrap_or_default();
let before = controls::get(&settings, id).unwrap_or(spec.default);
let after = crate::widgets::nudged(spec, before, f64::from(steps));
if after == before { continue; }
if after == before {
continue;
}
let event = EditEvent::set(craft::behavior::Mixed::Same(before), after, spec.label.into(), None);
apply(app, ctx, spec, &event);
}
+3 -7
View File
@@ -174,9 +174,8 @@ fn point_color_swatches(ui: &mut egui::Ui, colors: &[Color32], selected: usize)
// Measured in an invisible sizing child, then shown at the room it takes in a real run only: the swatches join
// their group's arena in a real run alone, never in egui's sizing pass or an SDK measure.
let width = ui.available_width().max(1.0);
let child = ui.new_child(
egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(ui.cursor().min, vec2(width, f32::INFINITY))).sizing_pass().invisible(),
);
let child = ui
.new_child(egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(ui.cursor().min, vec2(width, f32::INFINITY))).sizing_pass().invisible());
let size = group().measure_in(&child, craft::behavior::Proposal::Ideal, body);
let (rect, _) = ui.allocate_exact_size(vec2(size.x.min(width), size.y.max(24.0)), Sense::hover());
if measuring {
@@ -193,10 +192,7 @@ fn point_color_swatches(ui: &mut egui::Ui, colors: &[Color32], selected: usize)
fn point_color_visualize(ui: &mut egui::Ui, value: &mut bool) {
let measuring = ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx());
let mut local = *value;
let shown = Checkbox::new(Bind::bound(&mut local))
.id_salt("pointColorVisualize")
.label(crate::i18n::tr("Visualize range").to_owned())
.show(ui);
let shown = Checkbox::new(Bind::bound(&mut local)).id_salt("pointColorVisualize").label(crate::i18n::tr("Visualize range").to_owned()).show(ui);
if measuring {
return;
}
+1 -3
View File
@@ -486,9 +486,7 @@ pub(super) fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize
("▶▶", Icon::ChevronDoubleRight, big),
] {
let tooltip = crate::i18n::tr_format!("{label} {d:+} on every selected photo", d = d, label = crate::i18n::tr(label));
let clicked = {
quick_arrow::show(ui, owner, ctl, txt, icon, tooltip)
};
let clicked = { quick_arrow::show(ui, owner, ctl, txt, icon, tooltip) };
if clicked && !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
let _ = app.run("develop.quickAdjust", json!({"control": ctl, "delta": d}));
}
@@ -30,7 +30,12 @@ fn fixture() -> (egui::Context, LightcraftApp, PhotoId) {
fn frame(ctx: &egui::Context, events: Vec<egui::Event>, mut body: impl FnMut(&mut egui::Ui)) -> Registries {
let time = ctx.input(|i| i.time) + 1.0 / 60.0;
let input = egui::RawInput { time: Some(time), screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 640.0))), events, ..Default::default() };
let input = egui::RawInput {
time: Some(time),
screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(360.0, 640.0))),
events,
..Default::default()
};
let mut output = ctx.run_ui(input, |root_ui| {
crate::widgets::take_registries(root_ui.ctx());
egui::CentralPanel::default().show(root_ui, |ui| body(ui));
@@ -47,7 +52,11 @@ fn at(reg: &Registries, name: &str) -> egui::Pos2 {
fn click(ctx: &egui::Context, pos: egui::Pos2, mut body: impl FnMut(&mut egui::Ui)) {
frame(ctx, vec![egui::Event::PointerMoved(pos)], &mut body);
for pressed in [true, false] {
frame(ctx, vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], &mut body);
frame(
ctx,
vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }],
&mut body,
);
}
frame(ctx, Vec::new(), body);
}
@@ -67,11 +76,22 @@ fn wave155_production_device_gate_and_real_sdk_hit_owners() {
});
}
let record = observed.expect("SDK region recorded");
for (name, label, role) in [(COPY, "Create Proof Copy", "Button"), (PERCEPTUAL, "Perceptual", "Button"), (RELATIVE, "Relative", "Button"), (PAPER, "Simulate Paper & Ink", "CheckBox")] {
for (name, label, role) in [
(COPY, "Create Proof Copy", "Button"),
(PERCEPTUAL, "Perceptual", "Button"),
(RELATIVE, "Relative", "Button"),
(PAPER, "Simulate Paper & Ink", "CheckBox"),
] {
let expected = device || name == COPY;
assert_eq!(reg.0.iter().filter(|(id, _)| id == name).count(), usize::from(expected), "{name} device={device}");
if !expected { continue; }
let element = record.elements.iter().find(|e| e.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some(label) && f.role == role)).unwrap_or_else(|| panic!("missing SDK {role} {label}"));
if !expected {
continue;
}
let element = record
.elements
.iter()
.find(|e| e.facts.as_ref().is_some_and(|f| f.name.as_deref() == Some(label) && f.role == role))
.unwrap_or_else(|| panic!("missing SDK {role} {label}"));
let hit = reg.1.iter().find(|(id, _)| id == name).unwrap().1;
assert_eq!(hit.id, element.id, "{name}: automation must own the real component, not a hover probe");
assert!(hit.interact_rect.contains(at(&reg, name)), "{name}: click center outside hit");
@@ -84,8 +104,16 @@ fn wave155_local_options_select_both_intents_and_toggle_paper_twice() {
let (ctx, _app, _) = fixture();
let (mut intent, mut paper) = (ProofIntent::Perceptual, false);
let mut reg = (Vec::new(), Vec::new());
for _ in 0..4 { reg = frame(&ctx, Vec::new(), |ui| proof_options(ui, &mut intent, &mut paper)); }
for (name, expected_intent, expected_paper) in [(RELATIVE, ProofIntent::Relative, false), (PERCEPTUAL, ProofIntent::Perceptual, false), (PERCEPTUAL, ProofIntent::Perceptual, false), (PAPER, ProofIntent::Perceptual, true), (PAPER, ProofIntent::Perceptual, false)] {
for _ in 0..4 {
reg = frame(&ctx, Vec::new(), |ui| proof_options(ui, &mut intent, &mut paper));
}
for (name, expected_intent, expected_paper) in [
(RELATIVE, ProofIntent::Relative, false),
(PERCEPTUAL, ProofIntent::Perceptual, false),
(PERCEPTUAL, ProofIntent::Perceptual, false),
(PAPER, ProofIntent::Perceptual, true),
(PAPER, ProofIntent::Perceptual, false),
] {
click(&ctx, at(&reg, name), |ui| proof_options(ui, &mut intent, &mut paper));
assert_eq!((intent, paper), (expected_intent, expected_paper), "{name}");
reg = frame(&ctx, Vec::new(), |ui| proof_options(ui, &mut intent, &mut paper));
@@ -145,7 +173,9 @@ fn wave155_real_copy_uses_displayed_photo_profile_name_and_success_toast() {
let source = app.session.catalog.photo(id).unwrap().clone();
let count = app.session.catalog.photos().count();
let mut reg = (Vec::new(), Vec::new());
for _ in 0..4 { reg = frame(&ctx, Vec::new(), |ui| soft_proofing(&mut app, ui, id)); }
for _ in 0..4 {
reg = frame(&ctx, Vec::new(), |ui| soft_proofing(&mut app, ui, id));
}
click(&ctx, at(&reg, COPY), |ui| soft_proofing(&mut app, ui, id));
assert_eq!(app.session.catalog.photos().count(), count + 1, "one activation, one copy");
let copy = app.session.catalog.photos().find(|p| p.copy_of == Some(id)).expect("copy of displayed photo");
@@ -168,7 +198,9 @@ fn wave155_disabled_sdk_controls_ignore_pointer_activation() {
});
};
let mut reg = (Vec::new(), Vec::new());
for _ in 0..4 { reg = frame(&ctx, Vec::new(), &mut draw); }
for _ in 0..4 {
reg = frame(&ctx, Vec::new(), &mut draw);
}
for name in [RELATIVE, PAPER, COPY] {
click(&ctx, at(&reg, name), &mut draw);
reg = frame(&ctx, Vec::new(), &mut draw);
@@ -180,7 +212,9 @@ fn wave155_disabled_sdk_controls_ignore_pointer_activation() {
fn proof_copy_after_selection_change_undo_restores_both_original_photos() {
let (ctx, mut app, previous) = fixture();
let next = *app.session.selection.ids.iter().find(|id| **id != previous).unwrap();
for _ in 0..4 { frame(&ctx, vec![], |ui| soft_proofing(&mut app, ui, previous)); }
for _ in 0..4 {
frame(&ctx, vec![], |ui| soft_proofing(&mut app, ui, previous));
}
app.session.execute("library.select", &json!({"ids": [next.0], "active": next.0})).unwrap();
let originals = [previous, next].map(|id| json!(app.session.catalog.photo(id).unwrap()));
let before_count = app.session.catalog.photos().count();
@@ -6,7 +6,14 @@ use egui_kittest::{Harness, kittest::Queryable};
use std::sync::{Arc, Mutex};
#[derive(Clone, Copy)]
enum Mode { Returns, Owner, Disabled, Measure, Sizing, NoActionGrid }
enum Mode {
Returns,
Owner,
Disabled,
Measure,
Sizing,
NoActionGrid,
}
struct Fixture {
app: LightcraftApp,
@@ -40,7 +47,10 @@ fn fixture(width: f32, mode: Mode, busy: bool) -> Harness<'static, Fixture> {
#[cfg(not(target_arch = "wasm32"))]
let blocked = busy.then(|| crate::lightroom_import::stall_import(&mut app));
#[cfg(target_arch = "wasm32")]
let blocked = { assert!(!busy); None };
let blocked = {
assert!(!busy);
None
};
let state = Fixture { app, mode, returned: Vec::new(), asked, _busy: blocked };
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx);
@@ -59,11 +69,14 @@ fn fixture(width: f32, mode: Mode, busy: bool) -> Harness<'static, Fixture> {
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible());
draw_return(&mut child, state);
}
Mode::Disabled => { ui.add_enabled_ui(false, |ui| draw_return(ui, state)); }
Mode::Disabled => {
ui.add_enabled_ui(false, |ui| draw_return(ui, state));
}
Mode::Returns => draw_return(ui, state),
}
(state.app.widgets, state.app.widget_hits) = crate::widgets::take_registries(ui.ctx());
}, state,
},
state,
);
h.run_steps(5);
h
@@ -114,7 +127,9 @@ fn tab_to(h: &mut Harness<'_, Fixture>, id: &str) {
let focus = h.ctx.memory(|memory| memory.focused());
let current = focus.and_then(|id| h.ctx.read_response(id)).map(|response| response.rect);
path.push((focus, current));
if current == Some(wanted) { return; }
if current == Some(wanted) {
return;
}
key(h, egui::Key::Tab, false);
}
panic!("natural Tab did not reach {id}: {path:?}");
@@ -135,10 +150,9 @@ fn empty_action_pointer_returns_each_exact_command_once() {
#[test]
fn empty_action_natural_tab_enter_and_space_return_once() {
for (id, command, activation) in [
("button:emptyImportPhotos", "file.addPhotos", egui::Key::Enter),
("button:emptyImportLightroom", "file.importLightroom", egui::Key::Space),
] {
for (id, command, activation) in
[("button:emptyImportPhotos", "file.addPhotos", egui::Key::Enter), ("button:emptyImportLightroom", "file.importLightroom", egui::Key::Space)]
{
let mut h = fixture(1000.0, Mode::Returns, false);
h.event(egui::Event::PointerGone);
h.run_steps(2);
@@ -204,7 +218,10 @@ fn empty_action_disabled_measure_and_sizing_probes_are_inert() {
fn empty_action_actual_owner_availability_labels_and_cancel_picker_once() {
let mut h = fixture(1000.0, Mode::Owner, false);
assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, crate::i18n::tr("Import Photos…").as_ref()).is_some());
assert_eq!(h.state().app.widgets.iter().filter(|(id, _)| id == "button:emptyImportLightroom").count(), usize::from(!cfg!(target_arch = "wasm32")));
assert_eq!(
h.state().app.widgets.iter().filter(|(id, _)| id == "button:emptyImportLightroom").count(),
usize::from(!cfg!(target_arch = "wasm32"))
);
click(&mut h, "button:emptyImportPhotos");
h.run_steps(10);
{
+2 -5
View File
@@ -229,11 +229,8 @@ fn kind_picker(app: &mut LightcraftApp, ui: &mut egui::Ui) {
/// Framework buttons own both pointer and keyboard activation; sizing must not publish targets or run actions.
fn filter_action(ui: &mut egui::Ui, widget: &str, label: &str, enabled: bool) -> bool {
let enabled = enabled && ui.is_enabled();
let shown = Button::new(crate::i18n::tr(label).to_owned())
.id(egui::Id::unique(widget))
.size(craft::theme::ControlSize::Sm)
.enabled(enabled)
.show(ui);
let shown =
Button::new(crate::i18n::tr(label).to_owned()).id(egui::Id::unique(widget)).size(craft::theme::ControlSize::Sm).enabled(enabled).show(ui);
if measuring(ui) {
return false;
}
@@ -189,7 +189,6 @@ fn filter_kind_tab_enter_navigation_preserves_opener_focus() {
assert_ne!(h.view.ctx.memory(|memory| memory.focused()), Some(focused), "Tab can leave the opener");
}
#[test]
fn filter_kind_pointer_cancel_keeps_the_grid_keyboard_owner() {
let mut h = fixture(1900.0);
@@ -39,12 +39,18 @@ fn pointer(h: &mut Headless, widget: &str, before_release: impl Fn(&Headless)) {
h.app.synthetic.push(egui::Event::PointerMoved(at));
h.step();
h.app.synthetic.push(egui::Event::PointerButton {
pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE,
pos: at,
button: egui::PointerButton::Primary,
pressed: true,
modifiers: egui::Modifiers::NONE,
});
h.step();
before_release(h);
h.app.synthetic.push(egui::Event::PointerButton {
pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE,
pos: at,
button: egui::PointerButton::Primary,
pressed: false,
modifiers: egui::Modifiers::NONE,
});
h.step();
h.step();
@@ -231,10 +237,13 @@ fn filterbar_actions_external155_inherited_disabled_button_keeps_target_but_cann
let mut at = egui::Pos2::ZERO;
for frame in 0..5 {
let events = if frame == 2 || frame == 3 {
vec![egui::Event::PointerMoved(at), egui::Event::PointerButton {
pos: at, button: egui::PointerButton::Primary, pressed: frame == 2, modifiers: egui::Modifiers::NONE,
}]
} else { vec![] };
vec![
egui::Event::PointerMoved(at),
egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: frame == 2, modifiers: egui::Modifiers::NONE },
]
} else {
vec![]
};
let raw = HeadlessView::raw_input(egui::vec2(500.0, 200.0), 1.0, frame as f64 / 60.0, events);
view.run(raw, |ui| {
crate::widgets::take_registries(ui.ctx());
+2 -2
View File
@@ -1,12 +1,12 @@
//! Photo Grid (justified rows) and Square Grid. Virtualized: only visible cells request thumbnails.
#[cfg(test)]
mod folder_header_boundary_flow_tests;
#[cfg(test)]
mod folder_header_flow_tests;
#[cfg(test)]
mod folder_header_sdk_flow_tests;
#[cfg(test)]
mod folder_header_boundary_flow_tests;
#[cfg(test)]
mod header_tests;
use std::collections::{HashMap, HashSet};
+4 -2
View File
@@ -3,9 +3,9 @@
//! keyword gives it to the selected photos or takes it away; the arrow shows the photos with it.
use craft::ui::buttons::IconButton;
use craft::ui::primitives::IconSpec;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::primitives::IconSpec;
use craft::ui::text::TextField;
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use lightcraft_catalog::keywords::{KeywordInfo, KeywordNode, same};
@@ -384,7 +384,9 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, r: &Row, selection: &[PhotoId
ui,
("keyword-list-shortcut", r.path.to_lowercase()),
plus,
crate::panels::detail::host::Target::new(crate::i18n::tr("Part of the keyword shortcut")).tooltip(crate::i18n::tr("Part of the keyword shortcut")).hover_only(),
crate::panels::detail::host::Target::new(crate::i18n::tr("Part of the keyword shortcut"))
.tooltip(crate::i18n::tr("Part of the keyword shortcut"))
.hover_only(),
);
register(ui, format!("keywordShortcut:{}", r.path), plus);
}
+21 -20
View File
@@ -27,21 +27,24 @@ pub fn view_switch(app: &mut LightcraftApp, ui: &mut egui::Ui) {
use crate::state::KeywordingView as V;
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = egui::vec2(4.0, 4.0);
for (view, id, label) in
[
for (view, id, label) in [
(V::Enter, "enter", "Enter Keywords"),
(V::Keywords, "keywords", "Keywords"),
(V::Containing, "containing", "& Containing"),
(V::WillExport, "willExport", "Will Export"),
]
{
] {
let key = format!("keywordView:{id}");
// (a toggle button: the chosen view stays pressed, in the framework's own on look)
let shown = craft::ui::buttons::ToggleButton::new(crate::i18n::tr(label).to_owned(), craft::ui::contract::Bind::given(app.ui.keywording_view == view))
.id_salt(&key)
.size(craft::theme::ControlSize::Sm)
.show(ui);
if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) { continue; }
let shown = craft::ui::buttons::ToggleButton::new(
crate::i18n::tr(label).to_owned(),
craft::ui::contract::Bind::given(app.ui.keywording_view == view),
)
.id_salt(&key)
.size(craft::theme::ControlSize::Sm)
.show(ui);
if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) {
continue;
}
crate::widgets::register_response(key, shown.response.rect, &shown.response);
if ui.is_enabled() && shown.events.committed().is_some() {
app.ui.keywording_view = view;
@@ -149,7 +152,8 @@ fn chip(ui: &mut egui::Ui, path: &str, name: &str, partial: bool, cross: bool, r
// spans the whole chip so that its outline holds the ×, which sits over its end (the later widget takes the press).
let body = Rect::from_min_max(rect.min, pos2(rect.right() - CROSS_W, rect.bottom()));
let end = Rect::from_min_max(pos2(rect.right() - CROSS_W, rect.top()), rect.max);
let mut name = Button::new(full.clone()).painted(shown).id(id).size(craft::theme::ControlSize::Sm).align(HAlign::Start).tooltip(tip).show_at(ui, rect);
let mut name =
Button::new(full.clone()).painted(shown).id(id).size(craft::theme::ControlSize::Sm).align(HAlign::Start).tooltip(tip).show_at(ui, rect);
// (the name answers as the part of the chip that is not the ×)
name.response.rect = body;
name.response.interact_rect = name.response.interact_rect.intersect(body);
@@ -278,9 +282,7 @@ fn chip_acts(app: &mut LightcraftApp, ui: &mut egui::Ui, c: &Chip, drawn: Drawn)
return;
}
let c = c.clone();
Menu::context(crate::i18n::tr("Keyword"), &drawn.body)
.id_salt(("keyword-chip-menu", c.path.to_lowercase()))
.show(ui, |ui, _| menu(app, ui, &c));
Menu::context(crate::i18n::tr("Keyword"), &drawn.body).id_salt(("keyword-chip-menu", c.path.to_lowercase())).show(ui, |ui, _| menu(app, ui, &c));
}
/// When a list is shortened, only this many chips are measured for it: more than the lines it
@@ -358,7 +360,10 @@ fn chip_groups(app: &mut LightcraftApp, ui: &mut egui::Ui, groups: &[Group], sel
}
Line::Fewer => {
ui.add_space(6.0);
let shown = Button::new(crate::i18n::tr("Show fewer")).id(egui::Id::unique(("keyword-chips-fewer", selection))).size(craft::theme::ControlSize::Sm).show(ui);
let shown = Button::new(crate::i18n::tr("Show fewer"))
.id(egui::Id::unique(("keyword-chips-fewer", selection)))
.size(craft::theme::ControlSize::Sm)
.show(ui);
if !measuring(ui) {
crate::widgets::register_response("keywordChipsFewer", shown.response.rect, &shown.response);
if ui.is_enabled() && shown.clicked() {
@@ -546,12 +551,8 @@ pub(crate) fn offers_below(ui: &egui::Ui, below: egui::Rect, offers: &Offers, at
let (r, _) = ui.allocate_exact_size(vec2(width, 24.0), Sense::hover());
let shown_name = chip_label(name, false, width - 16.0, |s| ui.painter().layout_no_wrap(s.to_string(), t.font(13.0), t.text).size().x);
let text = if place.is_empty() { shown_name } else { format!("{shown_name} · {}", place.replace(SEP, " › ")) };
let mut button = Button::new(said.to_owned())
.painted(text)
.id(id)
.variant(craft::theme::Variant::GHOST)
.align(HAlign::Start)
.selected(lit);
let mut button =
Button::new(said.to_owned()).painted(text).id(id).variant(craft::theme::Variant::GHOST).align(HAlign::Start).selected(lit);
if let Some(tip) = tip {
button = button.tooltip(tip);
}
@@ -49,7 +49,6 @@ fn focused(ctx: &egui::Context, field: egui::Id) -> bool {
craft::ui::runtime::focus::focused_rec(ctx).is_some_and(|rec| rec.stop.id == field)
}
/// The painter is a real sibling SDK stop, so Tab can leave the add field's typing run.
/// Its text remains an app preference; only Enter asks the existing Paint command to run.
pub(crate) fn painter_field(ui: &mut egui::Ui, text: &mut String) -> bool {
+4 -7
View File
@@ -1,8 +1,6 @@
use std::collections::HashMap;
use super::rows::{
AlbumDrag, MAX_DEPTH, MenuAt, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, side_list, submenu, tree_open,
};
use super::rows::{AlbumDrag, MAX_DEPTH, MenuAt, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, side_list, submenu, tree_open};
use super::{Album, AlbumId, Align2, LibrarySource, LightcraftApp, Rect, Tokens, json, pos2, register, vec2};
/// How far each level of the albums' tree steps in, for the line that shows where a dragged album
@@ -267,10 +265,9 @@ fn import_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, a: &Album) {
app.toast(ui.ctx(), e);
}
};
for (label, command, widget) in [
("Import Photos…", "file.addPhotos", "button:albumImportPhotos"),
("Import from Folder…", "file.addFolder", "button:albumImportFolder"),
] {
for (label, command, widget) in
[("Import Photos…", "file.addPhotos", "button:albumImportPhotos"), ("Import from Folder…", "file.addFolder", "button:albumImportFolder")]
{
if entry("import", crate::i18n::tr(label)).widget(widget).show(ui) {
run(app, ui, command, json!({"album": a.id.0}));
}
@@ -659,7 +659,12 @@ fn date_actual_section_has_supported_list_and_identity_keyed_tree_row_owners() {
.filter(|element| !element.facts.as_ref().is_some_and(|facts| facts.name.as_deref() == Some("By Date")))
.collect::<Vec<_>>();
assert_eq!(rows.len(), 5, "two roots and their three actual months; trace={:#?}", f.trace);
assert_eq!(rows.iter().filter(|element| element.facts.as_ref().is_some_and(|facts| facts.name.as_deref().is_some_and(|n| n.starts_with("March")))).count(), 2);
assert_eq!(
rows.iter()
.filter(|element| element.facts.as_ref().is_some_and(|facts| facts.name.as_deref().is_some_and(|n| n.starts_with("March"))))
.count(),
2
);
let root = lists[0];
let root_facts = root.facts.as_ref().expect("real collection root facts");
assert!(!root_facts.disabled && root_facts.interactive, "enabled actionable collection root: {root:#?}");
-2
View File
@@ -1,8 +1,6 @@
use super::rows::tree_open;
use super::{Icon, LibrarySource, LightcraftApp, json};
/// By Date and Keywords count every photo in the library, so choosing a row shows those photos
/// from All Photos, not from whatever album or folder happened to be open, where they could be
/// missing (issue #341). Only when choosing (`on`), not when clearing the row again.
+8 -4
View File
@@ -15,7 +15,14 @@ struct Meta<'a> {
}
/// The rows of `nodes` and, for the open ones, of the folders inside them.
fn flatten<'a>(app: &LightcraftApp, ui: &egui::Ui, nodes: &'a [FolderNode], depth: usize, rows: &mut Vec<SideRow>, meta: &mut HashMap<String, Meta<'a>>) {
fn flatten<'a>(
app: &LightcraftApp,
ui: &egui::Ui,
nodes: &'a [FolderNode],
depth: usize,
rows: &mut Vec<SideRow>,
meta: &mut HashMap<String, Meta<'a>>,
) {
for n in nodes {
let key = lightcraft_catalog::query::folder_key(&n.path);
let open_id = egui::Id::unique(("libfolder-open", key));
@@ -145,7 +152,6 @@ pub(crate) fn folder_row_of<'a>(tree: &'a [FolderNode], dir: &str) -> Option<&'a
/// can be reached.
const SPRING_OPEN_SECONDS: f64 = 0.7;
/// A Folders row while photos are dragged from the grid: a release moves their files there on
/// disk (`photo.moveToFolder`, one undo step). The row lights up and the dragged label says where
/// they will go, as the same gesture onto an album only adds them to it. Held over a closed row,
@@ -306,7 +312,6 @@ fn locate_missing_item(app: &mut LightcraftApp, ui: &mut egui::Ui, n: &FolderNod
}
}
/// The node Synchronize Folder… of a Local folder `path` works on, with the name its dialog shows:
/// the Folders row for that very folder, else (a folder above rows) the folder itself, as a folder
/// holding other folders. `None` when no library photo lies in `path` or inside it. Reads the
@@ -352,7 +357,6 @@ fn can_move_folder(app: &LightcraftApp) -> Result<(), String> {
Ok(())
}
/// Move Folder To… of a folder row (widget `folderMoveTo`): asks for the destination through the
/// shared folder dialog, off the UI thread where the host has one (issue #3140: a dialog on the UI
/// thread froze the window); `folder.move` then runs when it closes ([`crate::pick::poll`]).
+1 -3
View File
@@ -1,9 +1,7 @@
use std::collections::HashMap;
use super::folders::{library_node_for, move_folder_item, reveal_item, synchronize_item};
use super::rows::{
MAX_DEPTH, MenuAt, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, side_list, tree_open,
};
use super::rows::{MAX_DEPTH, MenuAt, SideEvent, SideRow, SideSpec, entry, host_menu, rule, set_tree_open, side_list, tree_open};
use super::{LibrarySource, LightcraftApp, SidebarSection, json};
/// Local's folders as they stand this frame, and the folder being browsed among them.
+11 -1
View File
@@ -529,7 +529,17 @@ pub(super) struct SideSpec<'a> {
impl<'a> SideSpec<'a> {
pub(super) fn new(salt: &'a str, name: &'a str, show_counts: bool) -> Self {
SideSpec { salt, name, selected: None, show_counts, tree: true, build_all: false, focus_on_press: true, section_drag: None, album_drag: false }
SideSpec {
salt,
name,
selected: None,
show_counts,
tree: true,
build_all: false,
focus_on_press: true,
section_drag: None,
album_drag: false,
}
}
pub(super) fn selected(mut self, key: Option<&'a str>) -> Self {
+11 -6
View File
@@ -2,9 +2,7 @@ use craft::ui::contract::{Props as _, ShowContainer as _, Trigger};
use craft::ui::menu::Menu;
use super::albums::top_level_drop_target;
use super::rows::{
AlbumDrag, MenuAt, ROW_HEIGHT, SectionDrag, SideEvent, SideRow, SideSpec, entry, host_menu, measuring, rule, side_list,
};
use super::rows::{AlbumDrag, MenuAt, ROW_HEIGHT, SectionDrag, SideEvent, SideRow, SideSpec, entry, host_menu, measuring, rule, side_list};
use super::{Icon, LightcraftApp, Rect, SidebarSection, Tokens, icon_button, json, pos2, register, vec2};
/// Space above a section's header.
@@ -253,7 +251,8 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSe
.unregistered();
let salt = format!("section-{widget}-{id}");
let mut header = ui.new_child(egui::UiBuilder::new().max_rect(list));
let out = side_list(&mut header, SideSpec::new(&salt, crate::i18n::tr("Sidebar section"), false).keep_focus().section_drag(section, pinned), vec![row]);
let out =
side_list(&mut header, SideSpec::new(&salt, crate::i18n::tr("Sidebar section"), false).keep_focus().section_drag(section, pinned), vec![row]);
let live = !measuring(ui) && ui.is_enabled();
if live {
register(ui, format!("{widget}:{id}"), r);
@@ -375,7 +374,8 @@ pub(super) fn sections_menu(app: &mut LightcraftApp, ui: &mut egui::Ui, on: Opti
rule(ui);
}
for s in app.ui.sidebar.sections().iter().filter(|s| s.id.available()) {
let shown = entry("sidebar-section", crate::i18n::tr(s.id.title())).checked(!s.hidden).widget(format!("sidebarMenu:section:{}", s.id.id())).show(ui);
let shown =
entry("sidebar-section", crate::i18n::tr(s.id.title())).checked(!s.hidden).widget(format!("sidebarMenu:section:{}", s.id.id())).show(ui);
if shown {
run = Some(("view.sidebarSection", json!({"section": s.id.id(), "show": s.hidden})));
}
@@ -425,7 +425,12 @@ fn new_album_menu(app: &mut LightcraftApp, ui: &mut egui::Ui) {
pub(super) fn sidebar_title(app: &mut LightcraftApp, ui: &mut egui::Ui) {
let (_, hr) = ui.allocate_space(vec2(ui.available_width(), TITLE_HEIGHT));
let library = crate::panels::settings::open_library_name(app);
let mut row = SideRow::new("sidebarTitle", "folder", crate::i18n::tr("My Photos")).no_icon().strong().role(craft::ui::style::TypeRole::Title).unregistered().detail(library.clone());
let mut row = SideRow::new("sidebarTitle", "folder", crate::i18n::tr("My Photos"))
.no_icon()
.strong()
.role(craft::ui::style::TypeRole::Title)
.unregistered()
.detail(library.clone());
if library.is_some()
&& let Some(l) = app.session.library.as_ref()
{
+43 -37
View File
@@ -256,7 +256,9 @@ pub(crate) fn capture_completion(app: &LightcraftApp) -> LibraryCompletion {
}
pub(crate) fn apply_completion(app: &mut LightcraftApp, completion: LibraryCompletion) {
let LibraryCompletion(barrier, visible, absent) = completion;
if visible_mode(app) != visible || app.library_problem.as_ref().is_none_or(|p| p.dismissed) != absent { return; }
if visible_mode(app) != visible || app.library_problem.as_ref().is_none_or(|p| p.dismissed) != absent {
return;
}
app.library_window_input = barrier;
if let Some(mode) = visible {
if app.library_window_input.drawn == Some(mode) && (!app.library_window_input.transition || app.library_window_input.shielded) {
@@ -1083,41 +1085,43 @@ fn blocking_window(
let mut shown = None;
// The dialog mounts its own modal layer; this area only gives it a parent `Ui`.
// Above the dialog it covers on the dialog stack, below a prompt.
craft::ui::runtime::overlay::stack_place(ctx, crate::dialogs::STACK_LIBRARY, window_id(id), || crate::dialogs::host_ui(ctx, egui::Id::unique((id, "host")), |ui| {
let output = Dialog::new(crate::i18n::tr(title).to_owned())
.id(window_id(id))
.opened(Bind::given(true))
.closable(false)
.backdrop(Backdrop::Scrim)
.footer(|ui, _| footer(ui))
.show(ui, |ui, _| {
// a fixed width: a wrapped label in an auto-sized, centred window would move it every frame
ui.set_width(width);
ui.spacing_mut().item_spacing.y = 8.0;
// The framework sizes the window from a measuring run of the body, where the list's scroll area and
// its rows (host targets only in a real pass) come out shorter: reserve the height the real body
// took, so the footer's buttons sit below the last row instead of over it.
let height_id = window_id(id).with("body-height");
let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx());
let top = ui.cursor().top();
if let Some(height) = ui.ctx().data(|d| d.get_temp::<f32>(height_id)) {
ui.set_min_height(height);
}
body(ui);
if real {
// where the content ends (the cursor, which the reserved height does not move), so it can shrink
let height = (ui.cursor().top() - ui.spacing().item_spacing.y - top).max(0.0);
if ui.ctx().data(|d| d.get_temp::<f32>(height_id)).is_none_or(|kept| (kept - height).abs() > 0.5) {
ui.ctx().data_mut(|d| d.insert_temp(height_id, height));
ui.ctx().request_repaint();
craft::ui::runtime::overlay::stack_place(ctx, crate::dialogs::STACK_LIBRARY, window_id(id), || {
crate::dialogs::host_ui(ctx, egui::Id::unique((id, "host")), |ui| {
let output = Dialog::new(crate::i18n::tr(title).to_owned())
.id(window_id(id))
.opened(Bind::given(true))
.closable(false)
.backdrop(Backdrop::Scrim)
.footer(|ui, _| footer(ui))
.show(ui, |ui, _| {
// a fixed width: a wrapped label in an auto-sized, centred window would move it every frame
ui.set_width(width);
ui.spacing_mut().item_spacing.y = 8.0;
// The framework sizes the window from a measuring run of the body, where the list's scroll area and
// its rows (host targets only in a real pass) come out shorter: reserve the height the real body
// took, so the footer's buttons sit below the last row instead of over it.
let height_id = window_id(id).with("body-height");
let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx());
let top = ui.cursor().top();
if let Some(height) = ui.ctx().data(|d| d.get_temp::<f32>(height_id)) {
ui.set_min_height(height);
}
}
})
.output;
if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ctx) {
shown = Some((output.closed, output.response));
}
}));
body(ui);
if real {
// where the content ends (the cursor, which the reserved height does not move), so it can shrink
let height = (ui.cursor().top() - ui.spacing().item_spacing.y - top).max(0.0);
if ui.ctx().data(|d| d.get_temp::<f32>(height_id)).is_none_or(|kept| (kept - height).abs() > 0.5) {
ui.ctx().data_mut(|d| d.insert_temp(height_id, height));
ui.ctx().request_repaint();
}
}
})
.output;
if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ctx) {
shown = Some((output.closed, output.response));
}
})
});
shown
}
@@ -1401,7 +1405,8 @@ pub fn banner(app: &mut LightcraftApp, ui: &mut egui::Ui) {
.color(t.canvas),
);
register(ui, "indicator:temporarySession", r.rect);
let b = Button::new(crate::i18n::tr("Open Library…").to_owned()).id_salt("libraryReopen").size(craft::theme::ControlSize::Sm).show(ui);
let b =
Button::new(crate::i18n::tr("Open Library…").to_owned()).id_salt("libraryReopen").size(craft::theme::ControlSize::Sm).show(ui);
if !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx()) {
crate::widgets::register_response("button:libraryReopen", b.response.rect, &b.response);
reopen = b.clicked() || crate::widgets::same_pass_click(&b.response);
@@ -1432,7 +1437,8 @@ mod completion_tests {
app.library_window_input.drawn = Some(super::WindowMode::Error);
app.library_window_input.shielded = true;
app.capture_ui_completion(ui.ctx());
}).drop_without_applying_deltas();
})
.drop_without_applying_deltas();
assert!(app.library_window_input.transition);
app.library_window_input.drawn = None;
app.drain_ui_completions(&ctx);
@@ -432,7 +432,6 @@ fn component_parent_disabled_measurement_and_sizing_refuse_actions_without_repla
}
}
/// Narrow first step: run only this selector before repeating the full eight journeys.
#[test]
fn component_parent_both_openers_binding_discriminator_and_shifted_owner_safety() {
+22 -6
View File
@@ -81,10 +81,8 @@ impl Component for MaskHit {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let plate = if cx.response.hovered() { self.fill.hover.or(self.fill.rest) } else { self.fill.rest };
let shapes: Vec<Shape> = plate
.map(|color| Shape::rect_filled(cx.rect, self.fill.radius, color.gamma_multiply(self.opacity)))
.into_iter()
.collect();
let shapes: Vec<Shape> =
plate.map(|color| Shape::rect_filled(cx.rect, self.fill.radius, color.gamma_multiply(self.opacity))).into_iter().collect();
ui.reserve_slot(cx.visible).extend(&cx.response.ctx, shapes);
}
@@ -180,7 +178,17 @@ pub(in crate::panels) struct Hit<'a> {
impl<'a> Hit<'a> {
/// A control registered for automation as `widget`, named `label` for a screen reader.
pub fn new(widget: &'a str, label: impl Into<String>) -> Self {
Self { widget, label: label.into(), fill: Fill::NONE, selected: false, drag: false, pointer_only: false, enabled: true, visual: None, id: None }
Self {
widget,
label: label.into(),
fill: Fill::NONE,
selected: false,
drag: false,
pointer_only: false,
enabled: true,
visual: None,
id: None,
}
}
pub fn fill(mut self, fill: Fill) -> Self {
@@ -226,7 +234,15 @@ impl<'a> Hit<'a> {
pub fn show_at(self, ui: &mut Ui, rect: Rect) -> HitOutput {
let t = Tokens::get(ui.ctx());
let hit = MaskHit { common: Common::new(), accent: t.accent, fill: self.fill, selected: self.selected, drag: self.drag, pointer_only: self.pointer_only, opacity: ui.opacity() };
let hit = MaskHit {
common: Common::new(),
accent: t.accent,
fill: self.fill,
selected: self.selected,
drag: self.drag,
pointer_only: self.pointer_only,
opacity: ui.opacity(),
};
let enabled = self.enabled && ui.is_enabled();
let shown = hit.label(self.label).id(self.id.unwrap_or_else(|| egui::Id::unique(self.widget))).enabled(enabled).show_at(ui, rect);
if !measuring(ui) {
+2 -8
View File
@@ -260,10 +260,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option
ui.set_max_width(320.0);
let mut st: MenuState = ui.data(|d| d.get_temp(state_id())).unwrap_or_default();
let before = st.search.clone();
let r = crate::text_field::TextField::singleline(SEARCH, &mut st.search)
.hint(crate::i18n::tr("Search effects"))
.width(f32::INFINITY)
.show(ui);
let r = crate::text_field::TextField::singleline(SEARCH, &mut st.search).hint(crate::i18n::tr("Search effects")).width(f32::INFINITY).show(ui);
// the search field takes the keyboard when the menu opens, in a live pass: a measuring run moves nothing
if !measuring(ui) && !st.focused {
crate::text_field::focus_id(ui.ctx(), r.response.id);
@@ -312,9 +309,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, mask: &Mask, current: Option
ui.painter().rect_filled(rect, 3.0, t.hover);
}
// (rows scrolled out of view can't be clicked)
let hit = ui
.is_rect_visible(rect)
.then(|| Hit::new(widget, display_name(name)).fill(Fill::on_hover(t.hover, 3.0)).show_at(ui, rect));
let hit = ui.is_rect_visible(rect).then(|| Hit::new(widget, display_name(name)).fill(Fill::on_hover(t.hover, 3.0)).show_at(ui, rect));
if current == Some(name.as_str()) {
ui.painter().text(rect.left_center() + vec2(4.0, 0.0), egui::Align2::LEFT_CENTER, "✓", t.font(12.0), t.accent);
}
@@ -841,7 +836,6 @@ pub fn manage_body(
}
ui.add(egui::Label::new(egui::RichText::new(info).color(t.text_dim).size(11.0)).truncate());
});
}
}
});
+19 -9
View File
@@ -290,7 +290,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
let plus = text_button(ui, &format!("maskPlus:{}", m.id), "+", false).on_hover_text(crate::i18n::tr("Add to this mask"));
opener_menu(ui, &plus, ("maskPlus", m.id), "Add to this mask", |ui| component_menu(app, ui, "add", ("maskPlus", m.id)));
let minus = text_button(ui, &format!("maskMinus:{}", m.id), "−", false).on_hover_text(crate::i18n::tr("Subtract from this mask"));
opener_menu(ui, &minus, ("maskMinus", m.id), "Subtract from this mask", |ui| component_menu(app, ui, "subtract", ("maskMinus", m.id)));
opener_menu(ui, &minus, ("maskMinus", m.id), "Subtract from this mask", |ui| {
component_menu(app, ui, "subtract", ("maskMinus", m.id))
});
});
describe_field(app, ui, false);
}
@@ -804,7 +806,6 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) {
let _ = app.run("view.maskOverlayMode", json!({"mode": mode}));
}
}
});
let colored = matches!(view, MaskView::Color | MaskView::ColorOnBw);
if colored {
@@ -849,8 +850,8 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) {
let label_rect = Rect::from_min_size(pos2(row.left() + 24.0, row.top() + 4.0), vec2(w - 46.0, 18.0));
let track_rect = Rect::from_min_max(pos2(row.left() + 24.0, row.top() + 22.0), pos2(row.right() - 22.0, row.top() + 40.0));
let value_rect = Rect::from_min_max(pos2(label_rect.right() - 64.0, label_rect.top()), label_rect.max);
// the reset hit area is the caption: the value field over the end of the row keeps its own presses
let label_hit = Rect::from_min_max(label_rect.min, pos2(value_rect.left(), label_rect.bottom()));
// the reset hit area is the caption: the value field over the end of the row keeps its own presses
let label_hit = Rect::from_min_max(label_rect.min, pos2(value_rect.left(), label_rect.bottom()));
let id = ui.scope_id().with(spec.id);
let mut value = app.ui.mask_overlay_opacity as f64;
let label = Hit::new("maskOverlayOpacityLabel", crate::i18n::tr_format!("Reset {name}", name = crate::i18n::tr("Opacity")))
@@ -1294,7 +1295,6 @@ impl ComponentMenuTarget {
}
}
enum ComponentRowAction {
Command(serde_json::Value),
Rename,
@@ -1438,7 +1438,9 @@ fn component_row_menu(
}
// Keep the existing component-creation menus and their model/download policy unchanged.
for (label, op) in [("Intersect with", "intersect"), ("Subtract", "subtract")] {
Menu::submenu_row_enabled(ui, crate::i18n::tr(label), ui.is_enabled(), |ui, _| component_menu(app, ui, op, ("mask-component-row", op, target.key())));
Menu::submenu_row_enabled(ui, crate::i18n::tr(label), ui.is_enabled(), |ui, _| {
component_menu(app, ui, op, ("mask-component-row", op, target.key()))
});
}
Divider::horizontal().show(ui);
if component_action(ui, target, "rename", crate::i18n::tr("Rename…"), targets) {
@@ -1455,7 +1457,6 @@ fn component_row_menu(
action
}
/// Whether the SAM 3 model is missing in a build that could use it: then the download is
/// offered (with `then` to start afterwards) instead of starting an AI mask.
fn needs_model(app: &mut LightcraftApp, kind: &str, op: &str) -> bool {
@@ -1604,7 +1605,13 @@ fn describe_field(app: &mut LightcraftApp, ui: &mut egui::Ui, new_mask: bool) {
/// The menu a button opens: the framework's, opened by the button's own activation (the pointer, a long
/// press and the keyboard alike) and closed by Escape, a click away or a pick. `key` tells this opener's
/// menu from the others'. Nothing is drawn while only measuring.
fn opener_menu(ui: &mut egui::Ui, opener: &crate::widgets::TextButtonOutput, key: impl std::hash::Hash + std::fmt::Debug, label: &str, mut body: impl FnMut(&mut egui::Ui)) {
fn opener_menu(
ui: &mut egui::Ui,
opener: &crate::widgets::TextButtonOutput,
key: impl std::hash::Hash + std::fmt::Debug,
label: &str,
mut body: impl FnMut(&mut egui::Ui),
) {
use craft::ui::contract::{Bind, Trigger};
if measuring(ui) {
return;
@@ -1612,7 +1619,10 @@ fn opener_menu(ui: &mut egui::Ui, opener: &crate::widgets::TextButtonOutput, key
// The open state lives here, a pass at a time: a menu whose opener stops drawing closes.
let pass = ui.ctx().cumulative_pass_nr();
let open_id = opener.response.id.with("mask-opener-menu-open");
let mut open = ui.data(|d| d.get_temp::<(u64, bool)>(open_id)).filter(|(last, _)| *last == pass || last.saturating_add(1) == pass).is_some_and(|(_, open)| open);
let mut open = ui
.data(|d| d.get_temp::<(u64, bool)>(open_id))
.filter(|(last, _)| *last == pass || last.saturating_add(1) == pass)
.is_some_and(|(_, open)| open);
// Escape closes it while the keyboard is still on the button, outside the menu: a long press opens it there, and
// the button has no use for the Escape the runtime hands it.
let opener_id = opener.response.id;
+70 -54
View File
@@ -374,7 +374,11 @@ pub(crate) fn prompt_allows_event(app: &LightcraftApp, event: &egui::Event) -> b
fn prompt_event(event: &egui::Event) -> bool {
matches!(
event,
egui::Event::Key { .. } | egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::PointerGone | egui::Event::AccessKitActionRequest(_)
egui::Event::Key { .. }
| egui::Event::PointerMoved(_)
| egui::Event::PointerButton { .. }
| egui::Event::PointerGone
| egui::Event::AccessKitActionRequest(_)
)
}
@@ -490,13 +494,17 @@ pub(crate) fn shield_pass(app: &LightcraftApp, ctx: &egui::Context) -> bool {
/// next host frame. A changed/dismissed prompt is reset here as well, so a queued next notice is
/// treated as a new transition.
pub(crate) struct PromptCompletion(Option<PromptKey>, bool);
pub(crate) fn begin_draw(app: &mut LightcraftApp) { app.notice_input.drawn = false; }
pub(crate) fn begin_draw(app: &mut LightcraftApp) {
app.notice_input.drawn = false;
}
pub(crate) fn capture_completion(app: &LightcraftApp) -> PromptCompletion {
PromptCompletion(prompt_key(app), app.notice_input.drawn)
}
pub(crate) fn apply_completion(app: &mut LightcraftApp, completion: PromptCompletion) {
let PromptCompletion(current, drawn) = completion;
if prompt_key(app) != current { return; }
if prompt_key(app) != current {
return;
}
if app.notice_input.key != current {
// A prompt can change during the draw itself (Tasks -> Unsaved, or OK -> next notice).
// Leave it in its transition state so the next host frame shields the new prompt too.
@@ -525,7 +533,12 @@ fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&s
let mut chosen = input.activate.take().filter(|index| *index <= last);
let specs: Vec<crate::dialogs::FooterSpec> = buttons
.iter()
.map(|(bid, label, _)| crate::dialogs::FooterSpec { label: crate::i18n::tr(label).to_string(), name: format!("button:{bid}"), enabled: true, primary: false })
.map(|(bid, label, _)| crate::dialogs::FooterSpec {
label: crate::i18n::tr(label).to_string(),
name: format!("button:{bid}"),
enabled: true,
primary: false,
})
.collect();
let picked = Cell::new(None);
let shown_layer: Cell<Option<egui::LayerId>> = Cell::new(None);
@@ -538,55 +551,57 @@ fn window(ctx: &egui::Context, id: &str, title: &str, text: &str, buttons: &[(&s
}
// The prompt is the top of the dialog stack (`STACK_PROMPT`), above a dialog or library window under it, however
// the layers appeared.
craft::ui::runtime::overlay::stack_place(ctx, crate::dialogs::STACK_PROMPT, egui::Id::unique(id), || crate::dialogs::host_ui(ctx, egui::Id::unique((id, "host")), |ui| {
let output = Dialog::new(crate::i18n::tr(title).to_owned())
.id(egui::Id::unique(id))
.opened(Bind::given(true))
.closable(false)
.backdrop(Backdrop::Scrim)
.footer(|ui, _| {
let (clicked, shown) = crate::dialogs::footer_button_responses(ui, id, &specs);
if clicked.is_some() {
picked.set(clicked);
}
if !shown.is_empty() {
*responses.borrow_mut() = shown;
}
})
.show(ui, |ui, _| {
// The first layout of a new layer is a sizing pass: finish its real hit areas in this same frame.
if ui.is_sizing_pass() {
ctx.request_discard("notice prompt: settle its buttons before input");
} else if !craft::ui::runtime::measure::active(ui.ctx()) {
shown_layer.set(Some(ui.layer_id()));
}
// a fixed width: a wrapped label in an auto-sized, centred window would move it every frame
ui.set_width(420.0);
ui.spacing_mut().item_spacing.y = 8.0;
ui.add(egui::Label::new(RichText::new(text).color(t.text_label)).wrap());
})
.output;
if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ctx) {
return;
}
if let Some(layer) = shown_layer.get() {
input.layer = Some(layer);
}
let responses = responses.borrow();
// The real response ids are the AccessKit nodes a screen reader targets.
input.button_ids = specs.iter().zip(responses.iter()).map(|(spec, response)| (spec.name.clone(), response.id)).collect();
// The safe Cancel/OK starts focused, and takes the focus back while nothing in the prompt has it.
if let Some(safe) = responses.get(cancel_index)
&& !responses.iter().any(egui::Response::has_focus)
{
focus::request(ctx, FocusTarget::Id(safe.id));
}
crate::widgets::announce_dialog(ctx, &output.response, crate::widgets::Modal::Alert);
crate::widgets::describe_dialog(ctx, &output.response, text);
if chosen.is_none() {
chosen = picked.get().filter(|index| *index <= last).or(output.closed.map(|_| cancel_index));
}
}));
craft::ui::runtime::overlay::stack_place(ctx, crate::dialogs::STACK_PROMPT, egui::Id::unique(id), || {
crate::dialogs::host_ui(ctx, egui::Id::unique((id, "host")), |ui| {
let output = Dialog::new(crate::i18n::tr(title).to_owned())
.id(egui::Id::unique(id))
.opened(Bind::given(true))
.closable(false)
.backdrop(Backdrop::Scrim)
.footer(|ui, _| {
let (clicked, shown) = crate::dialogs::footer_button_responses(ui, id, &specs);
if clicked.is_some() {
picked.set(clicked);
}
if !shown.is_empty() {
*responses.borrow_mut() = shown;
}
})
.show(ui, |ui, _| {
// The first layout of a new layer is a sizing pass: finish its real hit areas in this same frame.
if ui.is_sizing_pass() {
ctx.request_discard("notice prompt: settle its buttons before input");
} else if !craft::ui::runtime::measure::active(ui.ctx()) {
shown_layer.set(Some(ui.layer_id()));
}
// a fixed width: a wrapped label in an auto-sized, centred window would move it every frame
ui.set_width(420.0);
ui.spacing_mut().item_spacing.y = 8.0;
ui.add(egui::Label::new(RichText::new(text).color(t.text_label)).wrap());
})
.output;
if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ctx) {
return;
}
if let Some(layer) = shown_layer.get() {
input.layer = Some(layer);
}
let responses = responses.borrow();
// The real response ids are the AccessKit nodes a screen reader targets.
input.button_ids = specs.iter().zip(responses.iter()).map(|(spec, response)| (spec.name.clone(), response.id)).collect();
// The safe Cancel/OK starts focused, and takes the focus back while nothing in the prompt has it.
if let Some(safe) = responses.get(cancel_index)
&& !responses.iter().any(egui::Response::has_focus)
{
focus::request(ctx, FocusTarget::Id(safe.id));
}
crate::widgets::announce_dialog(ctx, &output.response, crate::widgets::Modal::Alert);
crate::widgets::describe_dialog(ctx, &output.response, text);
if chosen.is_none() {
chosen = picked.get().filter(|index| *index <= last).or(output.closed.map(|_| cancel_index));
}
})
});
if gave_back {
// and nothing drawn after the prompt sees it
ctx.input_mut(|live| live.events.retain(|event| !prompt_event(event)));
@@ -839,7 +854,8 @@ mod tests {
super::prepare_ui_pass(&mut app, ui.ctx());
super::show(&mut app, ui.ctx());
app.capture_ui_completion(ui.ctx());
}).drop_without_applying_deltas();
})
.drop_without_applying_deltas();
assert!(!app.notice_input.laid_out);
app.drain_ui_completions(&ctx);
assert!(app.notice_input.laid_out);
+16 -12
View File
@@ -177,10 +177,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, name: &str) {
ui.label(RichText::new(count).color(t.text_dim));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.add_space(PAD - 4.0);
let photos = Button::new(crate::i18n::tr("Show photos"))
.id_salt("person:photos")
.tooltip(crate::i18n::tr("Their photos in the grid"))
.show(ui);
let photos =
Button::new(crate::i18n::tr("Show photos")).id_salt("person:photos").tooltip(crate::i18n::tr("Their photos in the grid")).show(ui);
let clicked = photos.clicked();
let response = photos.response;
let real_pass = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx());
@@ -347,17 +345,23 @@ fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, spec: &TileSpec) -> Hit {
}
// the × is added after the tile, so it wins where they overlap
let x_rect = Rect::from_min_size(pos2(r.right() - 24.0, r.top() + 4.0), vec2(20.0, 20.0));
let x_resp = more.then(|| {
super::detail::host::target(ui, ("more-face-x", f.photo, f.index), x_rect, host(crate::i18n::tr("Hide this face").to_string()))
});
let x_resp =
more.then(|| super::detail::host::target(ui, ("more-face-x", f.photo, f.index), x_rect, host(crate::i18n::tr("Hide this face").to_string())));
let above_rect = Rect::from_min_size(pos2(r.left() + 4.0, r.top() + 4.0), vec2(24.0, 20.0));
let above_resp = more.then(|| {
let tip = format!(
"All above: confirm {above_count} faces as {name} (this face and every shown face with equal or higher similarity). Press A."
);
super::detail::host::target(ui, ("more-face-above", f.photo, f.index), above_rect, host(crate::i18n::tr("Confirm all above").to_string()).tooltip(tip))
let tip =
format!("All above: confirm {above_count} faces as {name} (this face and every shown face with equal or higher similarity). Press A.");
super::detail::host::target(
ui,
("more-face-above", f.photo, f.index),
above_rect,
host(crate::i18n::tr("Confirm all above").to_string()).tooltip(tip),
)
});
if more && real && let Some(above) = above_resp.as_ref() {
if more
&& real
&& let Some(above) = above_resp.as_ref()
{
register_response(format!("more-face-above:{}:{}", f.photo, f.index), above_rect, above);
}
let hovered = resp.hovered() || x_resp.as_ref().is_some_and(|x| x.hovered()) || above_resp.as_ref().is_some_and(|x| x.hovered());
+3 -5
View File
@@ -124,7 +124,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
if !measuring && !ui.is_sizing_pass() {
let pass = ui.ctx().cumulative_pass_nr();
let open_id = more.response.id.with("preset-options-open");
let mut open = ui.data(|data| data.get_temp::<(u64, bool)>(open_id))
let mut open = ui
.data(|data| data.get_temp::<(u64, bool)>(open_id))
.filter(|(last, _)| *last == pass || last.saturating_add(1) == pass)
.is_some_and(|(_, open)| open);
// Use the compact SDK button's activation, including keyboard and long release.
@@ -171,10 +172,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
}
}
let any_user = app.session.presets.iter().any(|p| !p.builtin);
let export = MenuItem::new(crate::i18n::tr("Export User Presets…"))
.id_salt("preset-options-export")
.enabled(any_user)
.show(ui);
let export = MenuItem::new(crate::i18n::tr("Export User Presets…")).id_salt("preset-options-export").enabled(any_user).show(ui);
if !measuring {
if crate::widgets::on_live_layer(&export.response) {
crate::widgets::register_response("presetMenu:export", export.response.rect, &export.response);
@@ -5,12 +5,14 @@ use crate::widgets::{WidgetHit, take_registries};
use egui::{Event, Key, Modifiers, PointerButton};
#[derive(Clone, Copy)]
enum Pass { Real, EguiSizing, SdkSizing }
enum Pass {
Real,
EguiSizing,
SdkSizing,
}
// Two groups deliberately share a title; count and source are independent of their display name.
const GROUPS: [(&str, bool, usize); 4] = [
("Artistic", false, 3), ("Artistic", true, 1), ("Favorites", false, 2), ("Empty folder", true, 0),
];
const GROUPS: [(&str, bool, usize); 4] = [("Artistic", false, 3), ("Artistic", true, 1), ("Favorites", false, 2), ("Empty folder", true, 0)];
struct Frames {
view: HeadlessView,
@@ -54,14 +56,21 @@ impl Frames {
});
if let Some(recorded) = recorded {
elements = recorded.elements.clone();
expanded = elements.iter().filter(|e| e.component == "ProfileGroupHeader" && e.part.is_none())
.map(|e| (e.id, ui.ctx().accesskit_node_builder(e.id, |n| n.is_expanded()).flatten())).collect();
expanded = elements
.iter()
.filter(|e| e.component == "ProfileGroupHeader" && e.part.is_none())
.map(|e| (e.id, ui.ctx().accesskit_node_builder(e.id, |n| n.is_expanded()).flatten()))
.collect();
}
};
match pass {
Pass::Real => draw(ui),
Pass::EguiSizing => { ui.scope_builder(egui::UiBuilder::new().sizing_pass().invisible(), |ui| draw(ui)); }
Pass::SdkSizing => { craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); }
Pass::EguiSizing => {
ui.scope_builder(egui::UiBuilder::new().sizing_pass().invisible(), |ui| draw(ui));
}
Pass::SdkSizing => {
craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui));
}
}
});
(self.rects, self.hits) = take_registries(&self.view.ctx);
@@ -70,11 +79,18 @@ impl Frames {
self.bodies = bodies;
}
fn settle(&mut self) { for _ in 0..3 { self.frame(vec![], Pass::Real); } }
fn settle(&mut self) {
for _ in 0..3 {
self.frame(vec![], Pass::Real);
}
}
fn key(&mut self, key: Key, shift: bool) {
let modifiers = Modifiers { shift, ..Modifiers::NONE };
for pressed in [true, false] {
self.frame(vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }], Pass::Real);
self.frame(
vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }],
Pass::Real,
);
}
}
fn target(&self, key: &str) -> (Rect, WidgetHit) {
@@ -92,12 +108,19 @@ impl Frames {
}
fn click(&mut self, at: egui::Pos2, button: PointerButton) {
self.frame(vec![Event::PointerMoved(at)], Pass::Real);
for pressed in [true, false] { self.frame(vec![pointer(at, button, pressed)], Pass::Real); }
for pressed in [true, false] {
self.frame(vec![pointer(at, button, pressed)], Pass::Real);
}
}
fn snapshot(&self) -> (serde_json::Value, usize, usize, u64, Vec<String>) {
let id = self.app.session.catalog.photos().next().unwrap().id;
(serde_json::to_value(self.app.session.develop_of(id).unwrap_or_default().as_ref()).unwrap(),
self.app.session.undo.len(), self.app.session.redo.len(), self.app.session.catalog.revision, self.app.session.profile_favorites.clone())
(
serde_json::to_value(self.app.session.develop_of(id).unwrap_or_default().as_ref()).unwrap(),
self.app.session.undo.len(),
self.app.session.redo.len(),
self.app.session.catalog.revision,
self.app.session.profile_favorites.clone(),
)
}
}
@@ -108,7 +131,9 @@ fn pointer(pos: egui::Pos2, button: PointerButton, pressed: bool) -> Event {
#[test]
fn profile_groups_default_open_empty_and_same_named_sources_have_single_real_owner() {
for width in [280.0, 420.0, 760.0] {
let mut f = Frames::new(); f.width = width; f.settle();
let mut f = Frames::new();
f.width = width;
f.settle();
assert_eq!(f.bodies, [true; 4]);
assert_eq!(f.rects.len(), 4);
assert_eq!(f.hits.len(), 4);
@@ -131,7 +156,8 @@ fn profile_groups_default_open_empty_and_same_named_sources_have_single_real_own
#[test]
fn profile_groups_chevron_title_count_and_blank_row_toggle_same_response_independently() {
for offset in [22.0, 48.0, 200.0, 370.0] {
let mut f = Frames::new(); f.settle();
let mut f = Frames::new();
f.settle();
let before = f.snapshot();
let (rect, hit) = f.target("profileGroup:Artistic");
let at = if offset == 370.0 { pos2(rect.right() - 22.0, rect.center().y) } else { pos2(rect.left() + offset, rect.center().y) };
@@ -143,12 +169,15 @@ fn profile_groups_chevron_title_count_and_blank_row_toggle_same_response_indepen
assert_eq!(f.target("profileGroup:Artistic").1.id, hit.id);
assert_eq!(f.expanded.iter().find(|(id, _)| *id == hit.id).unwrap().1, Some(false));
let imported = f.target("profileGroup:lut:Artistic").0.center();
f.click(imported, PointerButton::Primary); f.frame(vec![], Pass::Real);
f.click(imported, PointerButton::Primary);
f.frame(vec![], Pass::Real);
assert_eq!(f.bodies, [false, false, true, true]);
f.click(at, PointerButton::Primary); f.frame(vec![], Pass::Real);
f.click(at, PointerButton::Primary);
f.frame(vec![], Pass::Real);
assert_eq!(f.bodies, [true, false, true, true]);
let empty = f.target("profileGroup:lut:Empty folder").0.center();
f.click(empty, PointerButton::Primary); f.frame(vec![], Pass::Real);
f.click(empty, PointerButton::Primary);
f.frame(vec![], Pass::Real);
assert_eq!(f.state(true, "Empty folder"), Some(false));
assert_eq!(f.bodies, [true, false, true, false]);
assert!(f.view.painted_text().iter().any(|s| s == "0"));
@@ -158,7 +187,8 @@ fn profile_groups_chevron_title_count_and_blank_row_toggle_same_response_indepen
#[test]
fn profile_groups_unforced_tab_enter_space_and_shift_tab_visit_each_owner_once() {
let mut f = Frames::new(); f.settle();
let mut f = Frames::new();
f.settle();
let before = f.snapshot();
let first = f.target("profileGroup:Artistic").1.id;
let second = f.target("profileGroup:lut:Artistic").1.id;
@@ -181,7 +211,8 @@ fn profile_groups_unforced_tab_enter_space_and_shift_tab_visit_each_owner_once()
#[test]
fn profile_groups_secondary_cancelled_and_disabled_clicks_do_not_toggle() {
let mut f = Frames::new(); f.settle();
let mut f = Frames::new();
f.settle();
let at = f.target("profileGroup:Artistic").0.center();
f.click(at, PointerButton::Secondary);
assert_eq!(f.state(false, "Artistic"), None);
@@ -190,7 +221,8 @@ fn profile_groups_secondary_cancelled_and_disabled_clicks_do_not_toggle() {
f.frame(vec![Event::PointerMoved(outside)], Pass::Real);
f.frame(vec![pointer(outside, PointerButton::Primary, false)], Pass::Real);
assert_eq!(f.state(false, "Artistic"), None);
f.enabled = false; f.settle();
f.enabled = false;
f.settle();
f.click(at, PointerButton::Primary);
assert_eq!(f.state(false, "Artistic"), None);
}
@@ -198,14 +230,17 @@ fn profile_groups_secondary_cancelled_and_disabled_clicks_do_not_toggle() {
#[test]
fn profile_groups_both_sizing_modes_publish_nothing_and_cannot_persist_release() {
for pass in [Pass::EguiSizing, Pass::SdkSizing] {
let mut f = Frames::new(); f.settle();
let mut f = Frames::new();
f.settle();
let before = f.snapshot();
let at = f.target("profileGroup:Artistic").0.center();
f.frame(vec![Event::PointerMoved(at)], Pass::Real);
f.frame(vec![pointer(at, PointerButton::Primary, true)], Pass::Real);
f.frame(vec![pointer(at, PointerButton::Primary, false)], pass);
assert!(f.rects.is_empty() && f.hits.is_empty());
for (title, imported, _) in GROUPS { assert_eq!(f.state(imported, title), None); }
for (title, imported, _) in GROUPS {
assert_eq!(f.state(imported, title), None);
}
assert_eq!(f.snapshot(), before);
// Existing closed state also survives measurement without being reinitialized.
f.view.ctx.data_mut(|d| d.insert_temp(egui::Id::unique(("profile-group", true, "Artistic")), false));
@@ -218,24 +253,41 @@ fn profile_groups_both_sizing_modes_publish_nothing_and_cannot_persist_release()
#[test]
fn profile_groups_translation_count_and_original_face_positions_are_preserved() {
struct Restore(crate::i18n::Locale);
impl Drop for Restore { fn drop(&mut self) { crate::i18n::set_language(self.0); } }
impl Drop for Restore {
fn drop(&mut self) {
crate::i18n::set_language(self.0);
}
}
let _restore = Restore(crate::i18n::language());
crate::i18n::set_language(crate::i18n::Locale::De);
let mut f = Frames::new(); f.settle();
let mut f = Frames::new();
f.settle();
let painted = f.view.painted_text();
assert!(painted.iter().any(|s| s == crate::i18n::builtin_label("Favorites", true)));
assert!(painted.iter().any(|s| s == "Artistic"), "imported label stays literal");
for count in ["3", "1", "2", "0"] { assert!(painted.iter().any(|s| s == count)); }
for count in ["3", "1", "2", "0"] {
assert!(painted.iter().any(|s| s == count));
}
fn shapes<'a>(shape: &'a egui::Shape, texts: &mut Vec<&'a egui::epaint::TextShape>, paths: &mut Vec<&'a egui::epaint::PathShape>) {
match shape {
egui::Shape::Vec(v) => for s in v { shapes(s, texts, paths); },
egui::Shape::Text(s) => texts.push(s), egui::Shape::Path(s) => paths.push(s), _ => {},
egui::Shape::Vec(v) => {
for s in v {
shapes(s, texts, paths);
}
}
egui::Shape::Text(s) => texts.push(s),
egui::Shape::Path(s) => paths.push(s),
_ => {}
}
}
let mut texts = vec![]; let mut paths = vec![];
for s in &f.view.shapes { shapes(&s.shape, &mut texts, &mut paths); }
let mut texts = vec![];
let mut paths = vec![];
for s in &f.view.shapes {
shapes(&s.shape, &mut texts, &mut paths);
}
let r = f.target("profileGroup:Artistic").0;
assert!(texts.iter().any(|s| s.galley.job.text == "3" && (s.pos.x + s.galley.size().x - (r.right() - 22.0)).abs() < 0.01));
assert!(texts.iter().any(|s| (s.pos.x - (r.left() + 36.0)).abs() < 0.01 && (s.pos.y + s.galley.size().y / 2.0 - r.center().y).abs() < 0.01));
assert!(paths.iter().any(|s| s.points == vec![pos2(r.left() + 18.0, r.center().y - 2.0), pos2(r.left() + 22.0, r.center().y + 2.0), pos2(r.left() + 26.0, r.center().y - 2.0)]));
assert!(paths.iter().any(|s| s.points
== vec![pos2(r.left() + 18.0, r.center().y - 2.0), pos2(r.left() + 22.0, r.center().y + 2.0), pos2(r.left() + 26.0, r.center().y - 2.0)]));
}
@@ -7,7 +7,11 @@ use egui::{Event, Key, Modifiers, PointerButton};
const PROFILE: &str = "lc.cine.teal-amber";
const NAME: &str = "Teal & Amber";
#[derive(Clone, Copy)]
enum Pass { Real, EguiSizing, SdkSizing }
enum Pass {
Real,
EguiSizing,
SdkSizing,
}
struct Frames {
app: LightcraftApp,
@@ -28,14 +32,30 @@ struct Frames {
impl Frames {
fn new() -> Self {
let ctx = egui::Context::default();
crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx); ctx.enable_accesskit();
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx);
ctx.enable_accesskit();
let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default());
app.install_framework(&ctx);
let photo = app.session.visible_cloned()[0];
app.run("library.select", json!({"ids": [photo.0], "active": photo.0})).unwrap();
// Deliberately use a non-default amount to catch accidental star application/reset.
app.run("develop.profile", json!({"id": "lc.color", "amount": 37})).unwrap();
Self { app, ctx, photo, now: 0.0, enabled: true, rects: vec![], hits: vec![], elements: vec![], selections: vec![], visible_focus: vec![], intents: vec![], shapes: vec![], probe_guard: false }
Self {
app,
ctx,
photo,
now: 0.0,
enabled: true,
rects: vec![],
hits: vec![],
elements: vec![],
selections: vec![],
visible_focus: vec![],
intents: vec![],
shapes: vec![],
probe_guard: false,
}
}
fn frame(&mut self, events: Vec<Event>, pass: Pass) {
let _ = take_registries(&self.ctx);
@@ -63,9 +83,19 @@ impl Frames {
visible_focus.push((controls.star.id, controls.star_focus_visible));
for response in [&controls.tile, &controls.star] {
// button-role toggles report their state as pressed (toggled), not selected
selections.push((response.id, ui.ctx().accesskit_node_builder(response.id, |n| (n.toggled().and_then(|t| (t == egui::accesskit::Toggled::True).then_some(true)), n.description().map(str::to_owned)))));
selections.push((
response.id,
ui.ctx().accesskit_node_builder(response.id, |n| {
(
n.toggled().and_then(|t| (t == egui::accesskit::Toggled::True).then_some(true)),
n.description().map(str::to_owned),
)
}),
));
}
if controls.intent != ProfileCellIntent::None {
intents.push(controls.intent);
}
if controls.intent != ProfileCellIntent::None { intents.push(controls.intent); }
profile_cell_apply(app, ui, PROFILE, controls.intent);
}
if probe_guard {
@@ -75,27 +105,42 @@ impl Frames {
}
});
});
if let Some(record) = record { elements = record.elements.clone(); }
if let Some(record) = record {
elements = record.elements.clone();
}
};
match pass {
Pass::Real => draw(ui),
Pass::EguiSizing => { ui.scope_builder(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible(), |ui| draw(ui)); }
Pass::SdkSizing => { craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); }
Pass::EguiSizing => {
ui.scope_builder(egui::UiBuilder::new().max_rect(ui.max_rect()).sizing_pass().invisible(), |ui| draw(ui));
}
Pass::SdkSizing => {
craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui));
}
}
});
out.textures_delta.clear();
self.shapes = out.shapes;
(self.rects, self.hits) = take_registries(&self.ctx);
self.elements = elements; self.selections = selections; self.visible_focus = visible_focus; self.intents = intents;
self.elements = elements;
self.selections = selections;
self.visible_focus = visible_focus;
self.intents = intents;
}
fn settle(&mut self) {
for _ in 0..3 {
self.frame(vec![], Pass::Real);
}
}
fn settle(&mut self) { for _ in 0..3 { self.frame(vec![], Pass::Real); } }
fn target(&self, key: &str) -> (Rect, WidgetHit) {
assert_eq!(self.rects.iter().filter(|(id, _)| id == key).count(), 1);
assert_eq!(self.hits.iter().filter(|(id, _)| id == key).count(), 1);
let r = self.rects.iter().find(|(id, _)| id == key).unwrap().1;
let hit = self.hits.iter().find(|(id, _)| id == key).unwrap().1;
let element = self.elements.iter().find(|e| e.id == hit.id && e.part.is_none()).expect("locator points at actual SDK component, not a hover probe");
assert_eq!(element.component, "ProfileCellAction"); assert_eq!(element.rect, r);
let element =
self.elements.iter().find(|e| e.id == hit.id && e.part.is_none()).expect("locator points at actual SDK component, not a hover probe");
assert_eq!(element.component, "ProfileCellAction");
assert_eq!(element.rect, r);
assert_eq!(hit.interact_rect, r);
if self.enabled {
assert!(element.stop.is_some());
@@ -114,104 +159,168 @@ impl Frames {
fn key(&mut self, key: Key, shift: bool) {
let modifiers = Modifiers { shift, ..Modifiers::NONE };
for pressed in [true, false] {
self.frame(vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }], Pass::Real);
self.frame(
vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }],
Pass::Real,
);
}
}
fn assert_state(&self, owner: egui::Id, on: bool) {
let node = self.selections.iter().find(|(id,_)| *id==owner).expect("current SDK response").1.as_ref().expect("actual AX button node");
let node = self.selections.iter().find(|(id, _)| *id == owner).expect("current SDK response").1.as_ref().expect("actual AX button node");
// For Button the SDK reports the state as pressed (toggled); only On counts here. The explicit
// localized description must remain available in *both* states.
assert_eq!(node.0,on.then_some(true));
assert_eq!(node.1.as_deref(),Some(crate::i18n::tr(if on {"On"} else {"Off"})));
assert_eq!(node.0, on.then_some(true));
assert_eq!(node.1.as_deref(), Some(crate::i18n::tr(if on { "On" } else { "Off" })));
}
fn settings(&self) -> serde_json::Value {
serde_json::to_value(self.app.session.develop_of(self.photo).unwrap().as_ref()).unwrap()
}
fn settings(&self) -> serde_json::Value { serde_json::to_value(self.app.session.develop_of(self.photo).unwrap().as_ref()).unwrap() }
fn snapshot(&self) -> serde_json::Value {
json!({"settings":self.settings(), "undo":self.app.session.undo.len(), "redo":self.app.session.redo.len(),
"revision":self.app.session.catalog.revision, "favorites":self.app.session.profile_favorites, "recent":self.app.session.profile_recent})
}
}
fn pointer(pos: egui::Pos2, button: PointerButton, pressed: bool) -> Event { Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE } }
fn tile(tag: &str) -> String { if tag.is_empty() { format!("profileCell:{PROFILE}") } else { format!("profileCell:fav:{PROFILE}") } }
fn star(tag: &str) -> String { if tag.is_empty() { format!("profileStar:{PROFILE}") } else { format!("profileStar:fav:{PROFILE}") } }
fn pointer(pos: egui::Pos2, button: PointerButton, pressed: bool) -> Event {
Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }
}
fn tile(tag: &str) -> String {
if tag.is_empty() { format!("profileCell:{PROFILE}") } else { format!("profileCell:fav:{PROFILE}") }
}
fn star(tag: &str) -> String {
if tag.is_empty() { format!("profileStar:{PROFILE}") } else { format!("profileStar:fav:{PROFILE}") }
}
#[test]
fn profile_tile_favorite_four_real_owners_preserve_duplicate_locators_and_geometry() {
let mut f = Frames::new(); let before = f.snapshot(); f.settle();
let mut f = Frames::new();
let before = f.snapshot();
f.settle();
assert_eq!(f.snapshot(), before, "idle controls never apply or favorite");
assert_eq!(f.rects.len(), 4); assert_eq!(f.hits.len(), 4);
assert_eq!(f.rects.len(), 4);
assert_eq!(f.hits.len(), 4);
let mut ids = std::collections::HashSet::new();
for tag in ["", "fav"] {
let (cell, t) = f.target(&tile(tag)); let (s, sh) = f.target(&star(tag));
let (cell, t) = f.target(&tile(tag));
let (s, sh) = f.target(&star(tag));
assert!(ids.insert(t.id) && ids.insert(sh.id));
assert_eq!(cell.size(), vec2(160.0, 144.0)); assert_eq!(s.size(), vec2(20.0, 20.0));
assert_eq!(cell.size(), vec2(160.0, 144.0));
assert_eq!(s.size(), vec2(20.0, 20.0));
assert_eq!(s.center(), pos2(cell.right() - 13.0, cell.top() + 13.0));
f.assert_state(t.id,false);
f.assert_state(sh.id,false);
f.assert_state(t.id, false);
f.assert_state(sh.id, false);
}
assert_eq!(f.elements.iter().filter(|e| e.component == "ProfileCellAction").count(), 4, "no proxy nodes or extra focus stops");
}
#[test]
fn profile_tile_favorite_star_pointer_changes_only_favorites_never_applies_or_adds_history() {
let mut f = Frames::new(); f.settle();
let settings = f.settings(); let undo = f.app.session.undo.len(); let redo = f.app.session.redo.len();
let revision = f.app.session.catalog.revision; let recent = f.app.session.profile_recent.clone();
let main_id = f.target(&star("")).1.id; let duplicate_id = f.target(&star("fav")).1.id;
let mut f = Frames::new();
f.settle();
let settings = f.settings();
let undo = f.app.session.undo.len();
let redo = f.app.session.redo.len();
let revision = f.app.session.catalog.revision;
let recent = f.app.session.profile_recent.clone();
let main_id = f.target(&star("")).1.id;
let duplicate_id = f.target(&star("fav")).1.id;
f.click(&star(""));
assert_eq!(f.intents, [ProfileCellIntent::Favorite], "star overlap must not activate tile too");
assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE)); f.settle();
for owner in [main_id, duplicate_id] { f.assert_state(owner,true); }
f.click(&star("fav")); assert_eq!(f.intents, [ProfileCellIntent::Favorite]);
assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE));
f.settle();
for owner in [main_id, duplicate_id] {
f.assert_state(owner, true);
}
f.click(&star("fav"));
assert_eq!(f.intents, [ProfileCellIntent::Favorite]);
assert!(!f.app.session.profile_favorites.iter().any(|id| id == PROFILE));
f.settle();for owner in [main_id,duplicate_id] { f.assert_state(owner,false); }
assert_eq!(f.settings(), settings); assert_eq!(f.app.session.undo.len(), undo); assert_eq!(f.app.session.redo.len(), redo);
assert_eq!(f.app.session.catalog.revision, revision); assert_eq!(f.app.session.profile_recent, recent);
f.settle();
for owner in [main_id, duplicate_id] {
f.assert_state(owner, false);
}
assert_eq!(f.settings(), settings);
assert_eq!(f.app.session.undo.len(), undo);
assert_eq!(f.app.session.redo.len(), redo);
assert_eq!(f.app.session.catalog.revision, revision);
assert_eq!(f.app.session.profile_recent, recent);
}
#[test]
fn profile_tile_favorite_tile_pointer_applies_once_at_100_and_applied_tile_is_noop() {
let mut f = Frames::new(); f.settle(); let undo = f.app.session.undo.len();
let mut f = Frames::new();
f.settle();
let undo = f.app.session.undo.len();
let favorites = f.app.session.profile_favorites.clone();
f.click(&tile("")); assert_eq!(f.intents, [ProfileCellIntent::Apply]); f.settle();
f.click(&tile(""));
assert_eq!(f.intents, [ProfileCellIntent::Apply]);
f.settle();
let d = f.app.session.develop_of(f.photo).unwrap();
assert_eq!(d.profile.id, PROFILE); assert_eq!(d.profile.amount, 100.0);
assert_eq!(f.app.session.undo.len(), undo + 1); assert_eq!(f.app.session.profile_favorites, favorites);
for tag in ["","fav"] { f.assert_state(f.target(&tile(tag)).1.id,true); f.assert_state(f.target(&star(tag)).1.id,false); }
assert_eq!(d.profile.id, PROFILE);
assert_eq!(d.profile.amount, 100.0);
assert_eq!(f.app.session.undo.len(), undo + 1);
assert_eq!(f.app.session.profile_favorites, favorites);
for tag in ["", "fav"] {
f.assert_state(f.target(&tile(tag)).1.id, true);
f.assert_state(f.target(&star(tag)).1.id, false);
}
// Already-applied is a no-op even when its amount is not the tile's 100% default.
f.app.run("develop.profile", json!({"id":PROFILE,"amount":61})).unwrap(); f.settle();
let before = f.snapshot(); f.click(&tile("fav"));
assert!(f.intents.is_empty()); assert_eq!(f.snapshot(), before);
f.click(&star("fav")); assert_eq!(f.intents, [ProfileCellIntent::Favorite]);
assert_eq!(f.settings(), before["settings"]); assert_eq!(f.app.session.undo.len(), before["undo"].as_u64().unwrap() as usize);
f.app.run("develop.profile", json!({"id":PROFILE,"amount":61})).unwrap();
f.settle();
let before = f.snapshot();
f.click(&tile("fav"));
assert!(f.intents.is_empty());
assert_eq!(f.snapshot(), before);
f.click(&star("fav"));
assert_eq!(f.intents, [ProfileCellIntent::Favorite]);
assert_eq!(f.settings(), before["settings"]);
assert_eq!(f.app.session.undo.len(), before["undo"].as_u64().unwrap() as usize);
}
#[test]
fn profile_tile_favorite_natural_tab_enter_space_visit_separate_tile_and_star_owners() {
let mut f = Frames::new(); f.settle();
let mut f = Frames::new();
f.settle();
let ids = [f.target(&tile("")).1.id, f.target(&star("")).1.id, f.target(&tile("fav")).1.id, f.target(&star("fav")).1.id];
assert_eq!(f.ctx.memory(|m| m.focused()), None);
f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[0]));
f.key(Key::Enter, false); assert_eq!(f.app.session.develop_of(f.photo).unwrap().profile.id, PROFILE);
let settings = f.settings(); let undo = f.app.session.undo.len();
f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[1]));
f.key(Key::Space, false); assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE));
assert_eq!(f.settings(), settings); assert_eq!(f.app.session.undo.len(), undo);
f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2]));
f.key(Key::Space, false); assert_eq!(f.app.session.undo.len(), undo, "applied tile keyboard activation is no-op");
f.key(Key::Tab, false); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[3]));
f.key(Key::Enter, false); assert!(!f.app.session.profile_favorites.iter().any(|id| id == PROFILE));
f.key(Key::Tab, true); assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2]));
f.key(Key::Tab, false);
assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[0]));
f.key(Key::Enter, false);
assert_eq!(f.app.session.develop_of(f.photo).unwrap().profile.id, PROFILE);
let settings = f.settings();
let undo = f.app.session.undo.len();
f.key(Key::Tab, false);
assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[1]));
f.key(Key::Space, false);
assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE));
assert_eq!(f.settings(), settings);
assert_eq!(f.app.session.undo.len(), undo);
f.key(Key::Tab, false);
assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2]));
f.key(Key::Space, false);
assert_eq!(f.app.session.undo.len(), undo, "applied tile keyboard activation is no-op");
f.key(Key::Tab, false);
assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[3]));
f.key(Key::Enter, false);
assert!(!f.app.session.profile_favorites.iter().any(|id| id == PROFILE));
f.key(Key::Tab, true);
assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2]));
}
#[test]
fn profile_tile_favorite_each_keyboard_activation_key_works_on_each_owner_without_forced_focus() {
for key in [Key::Enter, Key::Space] {
for favorite in [false, true] {
let mut f = Frames::new(); f.settle(); let undo = f.app.session.undo.len();
f.key(Key::Tab, false); if favorite { f.key(Key::Tab, false); }
let before = f.settings(); f.key(key, false);
let mut f = Frames::new();
f.settle();
let undo = f.app.session.undo.len();
f.key(Key::Tab, false);
if favorite {
assert_eq!(f.settings(), before); assert_eq!(f.app.session.undo.len(), undo);
f.key(Key::Tab, false);
}
let before = f.settings();
f.key(key, false);
if favorite {
assert_eq!(f.settings(), before);
assert_eq!(f.app.session.undo.len(), undo);
assert!(f.app.session.profile_favorites.iter().any(|id| id == PROFILE));
} else {
assert_eq!(f.app.session.develop_of(f.photo).unwrap().profile.amount, 100.0);
@@ -225,16 +334,23 @@ fn profile_tile_favorite_each_keyboard_activation_key_works_on_each_owner_withou
#[test]
fn profile_tile_favorite_secondary_cancelled_and_disabled_owners_do_not_mutate() {
for target in [tile(""), star("")] {
let mut f = Frames::new(); f.settle(); let before = f.snapshot(); let at = f.target(&target).0.center();
let mut f = Frames::new();
f.settle();
let before = f.snapshot();
let at = f.target(&target).0.center();
f.frame(vec![Event::PointerMoved(at)], Pass::Real);
for pressed in [true, false] { f.frame(vec![pointer(at, PointerButton::Secondary, pressed)], Pass::Real); }
for pressed in [true, false] {
f.frame(vec![pointer(at, PointerButton::Secondary, pressed)], Pass::Real);
}
assert_eq!(f.snapshot(), before);
f.frame(vec![pointer(at, PointerButton::Primary, true)], Pass::Real);
let outside = pos2(430.0, 300.0);
f.frame(vec![Event::PointerMoved(outside)], Pass::Real);
f.frame(vec![pointer(outside, PointerButton::Primary, false)], Pass::Real);
assert_eq!(f.snapshot(), before);
f.enabled = false; f.settle(); f.click(&target);
f.enabled = false;
f.settle();
f.click(&target);
assert_eq!(f.snapshot(), before);
}
}
@@ -243,7 +359,10 @@ fn profile_tile_favorite_secondary_cancelled_and_disabled_owners_do_not_mutate()
fn profile_tile_favorite_independent_sizing_guards_reject_release_and_explicit_intents() {
for pass in [Pass::EguiSizing, Pass::SdkSizing] {
for target in [tile(""), star("")] {
let mut f = Frames::new(); f.settle(); let before = f.snapshot(); let at = f.target(&target).0.center();
let mut f = Frames::new();
f.settle();
let before = f.snapshot();
let at = f.target(&target).0.center();
f.frame(vec![Event::PointerMoved(at)], Pass::Real);
f.frame(vec![pointer(at, PointerButton::Primary, true)], Pass::Real);
f.probe_guard = true;
@@ -256,25 +375,31 @@ fn profile_tile_favorite_independent_sizing_guards_reject_release_and_explicit_i
#[test]
fn profile_tile_favorite_idle_and_pointer_move_never_dispatch_or_clear_last_profile_hover() {
let mut f = Frames::new(); f.settle(); let before = f.snapshot();
let mut f = Frames::new();
f.settle();
let before = f.snapshot();
let saved = (f.photo, PROFILE.to_string());
f.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("last-profile-hover"), saved.clone()));
for key in [tile(""), star(""), tile("fav"), star("fav")] {
let at = f.target(&key).0.center(); f.frame(vec![Event::PointerMoved(at)], Pass::Real);
assert!(f.intents.is_empty()); assert_eq!(f.snapshot(), before);
assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId,String)>(egui::Id::unique("last-profile-hover"))), Some(saved.clone()));
let at = f.target(&key).0.center();
f.frame(vec![Event::PointerMoved(at)], Pass::Real);
assert!(f.intents.is_empty());
assert_eq!(f.snapshot(), before);
assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))), Some(saved.clone()));
}
f.click(&star(""));
assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId,String)>(egui::Id::unique("last-profile-hover"))), Some(saved));
assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))), Some(saved));
f.click(&tile(""));
assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId,String)>(egui::Id::unique("last-profile-hover"))), None);
assert_eq!(f.ctx.data(|d| d.get_temp::<(PhotoId, String)>(egui::Id::unique("last-profile-hover"))), None);
}
#[test]
fn profile_tile_favorite_pointer_idle_stays_hidden_but_keyboard_star_focus_is_visible() {
let mut f = Frames::new(); f.settle();
let mut f = Frames::new();
f.settle();
let star_id = f.target(&star("")).1.id;
f.click(&star("")); f.click(&star(""));
f.click(&star(""));
f.click(&star(""));
assert!(!f.app.session.profile_favorites.iter().any(|id| id == PROFILE));
f.frame(vec![Event::PointerMoved(pos2(430.0, 300.0))], Pass::Real);
assert_eq!(f.visible_focus.iter().find(|(id, _)| *id == star_id).unwrap().1, false);
@@ -288,14 +413,16 @@ fn profile_tile_favorite_pointer_idle_stays_hidden_but_keyboard_star_focus_is_vi
let id = f.ctx.memory(|m| m.focused()).expect("Tab focuses a real owner");
assert!(ids.contains(&id) && !path.contains(&id), "unexpected Tab route: {path:?} then {id:?}");
path.push(id);
if id == star_id {break;}
if id == star_id {
break;
}
}
assert_eq!(path.last(), Some(&star_id), "ordinary, unfavorited star must be reachable: {path:?}");
assert!(f.visible_focus.iter().find(|(id, _)| *id == star_id).unwrap().1);
f.key(Key::Tab, false);
assert_eq!(f.ctx.memory(|m| m.focused()), Some(ids[2]));
assert!(!f.visible_focus.iter().find(|(id, _)| *id == star_id).unwrap().1);
assert_eq!(f.snapshot(),before);
assert_eq!(f.snapshot(), before);
}
// The real panel is drawn in every frame. Only delivery of thumbnail pixels is omitted:
+84 -27
View File
@@ -24,7 +24,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
show_with_thumbnail(app, ui, id, paint_thumbnail);
}
fn show_with_thumbnail(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, thumbnail: impl Fn(&mut LightcraftApp, &egui::Painter, PhotoId, &DevelopSettings, Rect)) {
fn show_with_thumbnail(
app: &mut LightcraftApp,
ui: &mut egui::Ui,
id: PhotoId,
thumbnail: impl Fn(&mut LightcraftApp, &egui::Painter, PhotoId, &DevelopSettings, Rect),
) {
let t = Tokens::get(ui.ctx());
let d = (*app.session.develop_of(id).unwrap_or_default()).clone();
// header: back + title
@@ -141,12 +146,12 @@ fn profile_group_header(ui: &mut egui::Ui, title: &str, imported: bool, count: u
/// leaf keeps the original face while the public SDK pipeline owns the single hit/focus stop,
/// binding, keyboard/AT activation, cancellation and expanded accessibility state.
mod group_header {
use std::sync::Arc;
use crate::theme::Tokens;
use craft::behavior::{Metrics, Sense};
use craft::ui::contract::{Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PaintUi, Pointer as _, Props as _, Role};
use craft::ui::style::{ComponentStyle, FocusLook, StyleCx};
use egui::{Color32, Galley, Stroke, Vec2, pos2, vec2};
use crate::theme::Tokens;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
pub(super) struct HeaderStyle {
@@ -175,11 +180,16 @@ mod group_header {
let t = Tokens::get(ui.ctx());
let label = crate::i18n::builtin_label(title, !imported);
Self {
common: Common::new(), open, focus: t.accent,
common: Common::new(),
open,
focus: t.accent,
label: ui.painter().layout_no_wrap(label.to_string(), t.semibold(13.0), t.text_label),
count: ui.painter().layout_no_wrap(count.to_string(), t.font(12.0), t.text_dim),
ink: t.text_label, dim: t.text_dim, opacity: ui.opacity(),
}.label(label.to_string())
ink: t.text_label,
dim: t.text_dim,
opacity: ui.opacity(),
}
.label(label.to_string())
}
}
@@ -193,11 +203,19 @@ mod group_header {
fn style(_: &StyleCx<'_>, key: ProfileGroupHeaderStyleKey) -> HeaderStyle {
HeaderStyle { metrics: Metrics::new(), focus: FocusLook::new(Stroke::new(2.0, key.focus), -2.0) }
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { vec2(0.0, 32.0) }
fn sense(&self) -> Sense { Sense::CLICK | Sense::FOCUS }
fn bind(&mut self) -> Option<BindMut<'_, bool>> { Some(self.open.reborrow()) }
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
vec2(0.0, 32.0)
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS
}
fn bind(&mut self) -> Option<BindMut<'_, bool>> {
Some(self.open.reborrow())
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
if cx.activation().is_some() { cx.set(!cx.value().copied().unwrap_or(true)); }
if cx.activation().is_some() {
cx.set(!cx.value().copied().unwrap_or(true));
}
}
fn access(&self, access: &mut craft::ui::contract::Access, cx: &Cx<'_, Self>) {
access.expanded(cx.value().copied().unwrap_or(true));
@@ -214,12 +232,18 @@ mod group_header {
let label_at = pos2(r.left() + 36.0, r.center().y - self.label.size().y / 2.0);
let count_at = pos2(r.right() - 22.0 - self.count.size().x, r.center().y - self.count.size().y / 2.0);
let text = |at, galley, color| egui::epaint::TextShape::new(at, galley, color).with_opacity_factor(self.opacity).into();
ui.reserve_slot(cx.visible).extend(&cx.response.ctx, vec![
egui::Shape::line(offsets.map(|offset| center + offset).to_vec(), Stroke::new(1.2, self.ink.gamma_multiply(self.opacity))),
text(label_at, Arc::clone(&self.label), self.ink), text(count_at, Arc::clone(&self.count), self.dim),
]);
ui.reserve_slot(cx.visible).extend(
&cx.response.ctx,
vec![
egui::Shape::line(offsets.map(|offset| center + offset).to_vec(), Stroke::new(1.2, self.ink.gamma_multiply(self.opacity))),
text(label_at, Arc::clone(&self.label), self.ink),
text(count_at, Arc::clone(&self.count), self.dim),
],
);
}
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<bool> {
cx.edit_response()
}
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<bool> { cx.edit_response() }
}
}
@@ -318,37 +342,66 @@ struct ProfileCellControls {
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ProfileCellIntent { None, Favorite, Apply }
enum ProfileCellIntent {
None,
Favorite,
Apply,
}
#[allow(clippy::too_many_arguments)]
fn profile_cell_controls(ui: &mut egui::Ui, tag: &str, p_id: &str, p_name: &str, cell: Rect, star: Rect, applied: bool, fav: bool) -> ProfileCellControls {
fn profile_cell_controls(
ui: &mut egui::Ui,
tag: &str,
p_id: &str,
p_name: &str,
cell: Rect,
star: Rect,
applied: bool,
fav: bool,
) -> ProfileCellControls {
use craft::ui::contract::{Props as _, Show as _};
let tile_key = if tag.is_empty() { format!("profileCell:{p_id}") } else { format!("profileCell:{tag}:{p_id}") };
let star_key = format!("profileStar:{}{}", if tag.is_empty() { "" } else { "fav:" }, p_id);
let label = crate::i18n::profile_label(p_id, p_name).to_string();
let tile = cell_action::ProfileCellAction::new(ui)
.id_salt(("profile-tile", tile_key.as_str())).label(label.clone()).description(crate::i18n::tr(if applied { "On" } else { "Off" }).to_string()).selected(applied).show_at(ui, cell);
.id_salt(("profile-tile", tile_key.as_str()))
.label(label.clone())
.description(crate::i18n::tr(if applied { "On" } else { "Off" }).to_string())
.selected(applied)
.show_at(ui, cell);
let star_out = cell_action::ProfileCellAction::new(ui)
.id_salt(("profile-star", star_key.as_str()))
.label(format!("{}: {}", crate::i18n::tr("Favorite"), label)).description(crate::i18n::tr(if fav { "On" } else { "Off" }).to_string()).selected(fav).show_at(ui, star);
.label(format!("{}: {}", crate::i18n::tr("Favorite"), label))
.description(crate::i18n::tr(if fav { "On" } else { "Off" }).to_string())
.selected(fav)
.show_at(ui, star);
let real = !ui.is_sizing_pass() && !craft::ui::runtime::measure::active(ui.ctx());
if real {
crate::widgets::register_response(tile_key, cell, &tile.response);
crate::widgets::register_response(star_key, star, &star_out.response);
}
// A single command at most, even if an activation source is ever shared by mistake.
let intent = if !real { ProfileCellIntent::None }
else if craft::ui::contract::clicked(&star_out.response) { ProfileCellIntent::Favorite }
else if !applied && craft::ui::contract::clicked(&tile.response) { ProfileCellIntent::Apply }
else { ProfileCellIntent::None };
let intent = if !real {
ProfileCellIntent::None
} else if craft::ui::contract::clicked(&star_out.response) {
ProfileCellIntent::Favorite
} else if !applied && craft::ui::contract::clicked(&tile.response) {
ProfileCellIntent::Apply
} else {
ProfileCellIntent::None
};
ProfileCellControls { tile: tile.response, star: star_out.response, star_focus_visible: star_out.focus_visible, intent }
}
/// Shared with in-memory tests: the real command boundary, not a model-mutating focus proxy.
fn profile_cell_apply(app: &mut LightcraftApp, ui: &egui::Ui, p_id: &str, intent: ProfileCellIntent) {
if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) { return; }
if ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx()) {
return;
}
match intent {
ProfileCellIntent::Favorite => { let _ = app.run("profile.favorite", json!({"id": p_id})); }
ProfileCellIntent::Favorite => {
let _ = app.run("profile.favorite", json!({"id": p_id}));
}
ProfileCellIntent::Apply => {
let _ = app.run("develop.profile", json!({"id": p_id, "amount": 100}));
ui.data_mut(|m| m.remove::<(PhotoId, String)>(egui::Id::unique("last-profile-hover")));
@@ -389,7 +442,9 @@ mod cell_action {
}
impl Outcome for ActionOutput {
type Value = NoValue;
fn response(&self) -> &egui::Response { &self.response }
fn response(&self) -> &egui::Response {
&self.response
}
}
impl Component for ProfileCellAction {
const ROLE: Role = Role::BUTTON;
@@ -400,7 +455,9 @@ mod cell_action {
fn style(_: &StyleCx<'_>, key: ProfileCellActionStyleKey) -> ActionStyle {
ActionStyle { metrics: Metrics::new(), focus: FocusLook::new(Stroke::new(2.0, key.accent), -2.0) }
}
fn sense(&self) -> Sense { Sense::CLICK | Sense::FOCUS }
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS
}
fn paint(&mut self, _: &mut PaintUi<'_>, _: &Cx<'_, Self>) {}
fn finish(self, cx: Cx<'_, Self>) -> ActionOutput {
ActionOutput { response: cx.response.clone(), focus_visible: cx.focus_visible() }
+3 -2
View File
@@ -95,7 +95,6 @@ fn custom_aspect(ui: &mut egui::Ui, owner: PhotoId) -> Option<serde_json::Value>
crate::widgets::register_response("button:cropCustomApply", go.response.rect, &go.response);
apply |= go.clicked();
}
});
if !aspect_real(ui) || !ui.is_enabled() {
return None;
@@ -357,7 +356,9 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
(O::None, "None", "none"),
];
// scoped to the photo: a menu opened (or a row held) for one photo never picks for another
let picked = ui.push_id(("crop-overlay", id), |ui| crate::widgets::labeled_dropdown(ui, "cropOverlay", "Overlay", "", &overlays, app.ui.crop_overlay)).inner;
let picked = ui
.push_id(("crop-overlay", id), |ui| crate::widgets::labeled_dropdown(ui, "cropOverlay", "Overlay", "", &overlays, app.ui.crop_overlay))
.inner;
if let Some(o) = picked
&& interactive
{
@@ -8,10 +8,18 @@ const VISUALIZE: &str = "check:remove.visualizeSpots";
const CATCHLIGHT: &str = "check:redeye.catchlight";
#[derive(Clone, Copy)]
enum Panel { Crop, Remove, Eye }
enum Panel {
Crop,
Remove,
Eye,
}
#[derive(Clone, Copy)]
enum Pass { Normal, NativeSizing, SdkMeasure }
enum Pass {
Normal,
NativeSizing,
SdkMeasure,
}
struct Controls {
app: LightcraftApp,
@@ -68,7 +76,9 @@ impl Controls {
}
fn settle(&mut self) {
for _ in 0..3 { self.frame(vec![], Pass::Normal); }
for _ in 0..3 {
self.frame(vec![], Pass::Normal);
}
}
fn has(&self, id: &str) -> bool {
@@ -212,7 +222,9 @@ fn crop_checkboxes_external155_catchlight_is_pet_only_and_uses_selected_index()
fn crop_checkboxes_external155_both_measurement_modes_publish_no_checkbox_targets_or_edits() {
for (panel, id) in [(Panel::Crop, CONSTRAIN), (Panel::Remove, VISUALIZE), (Panel::Eye, CATCHLIGHT)] {
let mut h = Controls::new(panel);
if matches!(panel, Panel::Eye) { h.eyes(); }
if matches!(panel, Panel::Eye) {
h.eyes();
}
for pass in [Pass::NativeSizing, Pass::SdkMeasure] {
h.settle();
h.focus(id);
@@ -326,14 +326,19 @@ impl Fixture {
assert_eq!(Some(self.hit(FACE).layer_id), self.record_layer, "the face belongs to the actual parent's layer");
assert!(self.panel.expand(1.0).contains_rect(face), "no panel widening: {face:?} panel={:?}", self.panel);
let shown = OPTIONS.iter().find(|(choice, _, _)| *choice == self.app.ui.crop_overlay).map_or("", |(_, label, _)| crate::i18n::tr(label));
assert!(self.texts.iter().any(|text| text.text == shown && face.expand(1.0).intersects(text.rect)), "the face says {shown}; texts={:?}", self.texts);
assert!(
self.texts.iter().any(|text| text.text == shown && face.expand(1.0).intersects(text.rect)),
"the face says {shown}; texts={:?}",
self.texts
);
let mut owners = std::collections::HashSet::new();
for (index, (_, label, _)) in OPTIONS.iter().enumerate() {
let name = locator(index);
let rect = self.rect(&name);
let hit = self.hit(&name);
assert!(owners.insert(hit.id), "one owner per row");
let painted: Vec<_> = self.texts.iter().filter(|text| text.text == crate::i18n::tr(label) && rect.expand(1.0).intersects(text.rect)).collect();
let painted: Vec<_> =
self.texts.iter().filter(|text| text.text == crate::i18n::tr(label) && rect.expand(1.0).intersects(text.rect)).collect();
assert_eq!(painted.len(), 1, "full localized label is painted once: {name}; texts={:?}", self.texts);
assert!(painted[0].clip.expand(1.0).contains_rect(painted[0].rect), "localized label must not be clipped: {name} {:?}", painted[0]);
if index > 0 {
+60 -36
View File
@@ -1,7 +1,7 @@
use super::{Align2, Icon, LightcraftApp, PhotoId, Rect, Tokens, header, json, padded, paint, pos2, text_button, vec2};
use crate::panels::detail::host;
use craft::ui::contract::{Props as _, Show as _, ShowContainer as _};
use craft::ui::display::Divider;
use crate::panels::detail::host;
use super::{Align2, Icon, LightcraftApp, PhotoId, Rect, Tokens, header, json, padded, paint, pos2, text_button, vec2};
pub(super) fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
let Some(p) = app.session.catalog.photo(id).cloned() else { return };
@@ -94,9 +94,9 @@ pub(super) fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId)
let mut targets = Vec::new();
let mut layer = None;
let mut action = None;
craft::ui::menu::Menu::context(crate::i18n::tr("Version"), &resp)
.id_salt(("history-menu", "version", id.0, i))
.show(ui, |ui, menu| {
craft::ui::menu::Menu::context(crate::i18n::tr("Version"), &resp).id_salt(("history-menu", "version", id.0, i)).show(
ui,
|ui, menu| {
layer = Some(ui.layer_id());
if !interactive {
ui.disable();
@@ -122,15 +122,34 @@ pub(super) fn versions(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId)
action = Some(VersionMenuAction::Delete);
menu.request_close();
}
});
},
);
let eligible = publish_history_menu(ui.ctx(), layer, targets);
if interactive && eligible {
match action {
Some(VersionMenuAction::Restore) => { let _ = app.run("version.restore", json!({"index": i})); }
Some(VersionMenuAction::Update) => { let _ = app.run("version.update", json!({"index": i})); }
Some(VersionMenuAction::Rename) => { crate::panels::dialogs::prompt(app, "Rename Version", "Version name", &v.name, "version.rename", json!({"index": i}), "name"); }
Some(VersionMenuAction::Before) => { let _ = app.run("beforeAfter.setBefore", json!({"source": "version", "name": v.name})); }
Some(VersionMenuAction::Delete) => { let _ = app.run("version.delete", json!({"index": i})); }
Some(VersionMenuAction::Restore) => {
let _ = app.run("version.restore", json!({"index": i}));
}
Some(VersionMenuAction::Update) => {
let _ = app.run("version.update", json!({"index": i}));
}
Some(VersionMenuAction::Rename) => {
crate::panels::dialogs::prompt(
app,
"Rename Version",
"Version name",
&v.name,
"version.rename",
json!({"index": i}),
"name",
);
}
Some(VersionMenuAction::Before) => {
let _ = app.run("beforeAfter.setBefore", json!({"source": "version", "name": v.name}));
}
Some(VersionMenuAction::Delete) => {
let _ = app.run("version.delete", json!({"index": i}));
}
None => {}
}
}
@@ -221,9 +240,9 @@ pub(super) fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId)
let mut targets = Vec::new();
let mut layer = None;
let mut action = None;
craft::ui::menu::Menu::context(crate::i18n::tr("History"), &resp)
.id_salt(("history-menu", "history", id.0, i))
.show(ui, |ui, menu| {
craft::ui::menu::Menu::context(crate::i18n::tr("History"), &resp).id_salt(("history-menu", "history", id.0, i)).show(
ui,
|ui, menu| {
layer = Some(ui.layer_id());
if !interactive {
ui.disable();
@@ -241,14 +260,21 @@ pub(super) fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId)
action = Some(HistoryMenuAction::Clear);
menu.request_close();
}
});
},
);
let eligible = publish_history_menu(ui.ctx(), layer, targets);
if interactive && eligible {
match action {
Some(HistoryMenuAction::Before) => { let _ = app.run("beforeAfter.setBefore", json!({"source": "history", "index": i})); }
Some(HistoryMenuAction::CreateVersion) => { let _ = app.run("history.restore", json!({"index": i}));
let _ = app.run("version.create", json!({"name": h.label})); }
Some(HistoryMenuAction::Clear) => { let _ = app.run("history.clear", json!({})); }
Some(HistoryMenuAction::Before) => {
let _ = app.run("beforeAfter.setBefore", json!({"source": "history", "index": i}));
}
Some(HistoryMenuAction::CreateVersion) => {
let _ = app.run("history.restore", json!({"index": i}));
let _ = app.run("version.create", json!({"name": h.label}));
}
Some(HistoryMenuAction::Clear) => {
let _ = app.run("history.clear", json!({}));
}
None => {}
}
}
@@ -258,20 +284,22 @@ pub(super) fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId)
});
}
enum VersionMenuAction { Restore, Update, Rename, Before, Delete }
enum HistoryMenuAction { Before, CreateVersion, Clear }
enum VersionMenuAction {
Restore,
Update,
Rename,
Before,
Delete,
}
enum HistoryMenuAction {
Before,
CreateVersion,
Clear,
}
/// Draw real SDK actions, but do not publish or run app effects from a fading exit body.
fn history_menu_action(
ui: &mut egui::Ui,
key: (&str, u64, usize, &str),
label: &'static str,
targets: &mut Vec<(String, egui::Response)>,
) -> bool {
let shown = craft::ui::menu::MenuItem::new(crate::i18n::tr(label))
.id_salt(("history-action", key))
.enabled(ui.is_enabled())
.show(ui);
fn history_menu_action(ui: &mut egui::Ui, key: (&str, u64, usize, &str), label: &'static str, targets: &mut Vec<(String, egui::Response)>) -> bool {
let shown = craft::ui::menu::MenuItem::new(crate::i18n::tr(label)).id_salt(("history-action", key)).enabled(ui.is_enabled()).show(ui);
let measuring = ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx());
if measuring {
return false;
@@ -283,11 +311,7 @@ fn history_menu_action(
/// The Area stores its CURRENT interactability after its body returns. Querying it inside
/// the closure would use the previous pass and break same-target reopen during the exit.
fn publish_history_menu(
ctx: &egui::Context,
layer: Option<egui::LayerId>,
targets: Vec<(String, egui::Response)>,
) -> bool {
fn publish_history_menu(ctx: &egui::Context, layer: Option<egui::LayerId>, targets: Vec<(String, egui::Response)>) -> bool {
let eligible = layer.and_then(|layer| egui::AreaState::load(ctx, layer.id)).is_some_and(|state| state.interactable);
if eligible {
for (name, response) in targets {
@@ -2,13 +2,17 @@
//! Authored for the existing integrator’s normal test consumer; execution results are reported separately.
use super::*;
use std::sync::Arc;
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Ui};
use crate::headless::HeadlessView;
use crate::widgets::{WidgetHit, take_registries};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Ui};
use std::sync::Arc;
#[derive(Clone, Copy)]
enum Pass { Real, Measure, Sizing }
enum Pass {
Real,
Measure,
Sizing,
}
struct Frames {
ctx: egui::Context,
@@ -32,10 +36,13 @@ impl Frames {
}
fn frame(&mut self, events: Vec<Event>, mut draw: impl FnMut(&mut Ui)) {
let requested: Vec<_> = events.iter().filter_map(|event| match event {
Event::Key { key, pressed, .. } => Some((*key, *pressed)),
_ => None,
}).collect();
let requested: Vec<_> = events
.iter()
.filter_map(|event| match event {
Event::Key { key, pressed, .. } => Some((*key, *pressed)),
_ => None,
})
.collect();
let mut live = Vec::new();
let mut published = (vec![], vec![]);
let mut publication = Vec::new();
@@ -47,10 +54,16 @@ impl Frames {
let enabled = self.enabled;
let mut output = self.ctx.run_ui(raw, |ui| {
if !requested.is_empty() {
let events: Vec<_> = ui.input(|input| input.events.iter().filter_map(|event| match event {
Event::Key { key, pressed, .. } => Some((*key, *pressed)),
_ => None,
}).collect());
let events: Vec<_> = ui.input(|input| {
input
.events
.iter()
.filter_map(|event| match event {
Event::Key { key, pressed, .. } => Some((*key, *pressed)),
_ => None,
})
.collect()
});
live.push((ui.ctx().cumulative_pass_nr(), events));
}
ui.set_max_width(350.0);
@@ -71,7 +84,12 @@ impl Frames {
let discarded = ui.ctx().will_discard();
if publication.len() < 8 {
let menus: Vec<_> = hits.iter().filter(|(name, _)| name.contains("Menu:")).map(|(name, hit)| (name.clone(), hit.id)).collect();
publication.push(format!("pass={} discarded={discarded} sdk_keys_open_last_pass={} native_popup={} menu_owners={menus:?}", ui.ctx().cumulative_pass_nr(), craft::ui::runtime::overlay::any_open(ui.ctx(), craft::ui::runtime::overlay::OpenFilter::Keys), egui::Popup::is_any_open(ui.ctx())));
publication.push(format!(
"pass={} discarded={discarded} sdk_keys_open_last_pass={} native_popup={} menu_owners={menus:?}",
ui.ctx().cumulative_pass_nr(),
craft::ui::runtime::overlay::any_open(ui.ctx(), craft::ui::runtime::overlay::OpenFilter::Keys),
egui::Popup::is_any_open(ui.ctx())
));
}
published = if discarded { (vec![], vec![]) } else { (rects, hits) };
});
@@ -85,7 +103,10 @@ impl Frames {
if self.key_trace.len() == 64 {
self.key_trace.remove(0);
}
self.key_trace.push(format!("requested={requested:?} live_after_hook={live:?} native={native:?} sdk={sdk:?} native_popup={} owners={owners:?}", egui::Popup::is_any_open(&self.ctx)));
self.key_trace.push(format!(
"requested={requested:?} live_after_hook={live:?} native={native:?} sdk={sdk:?} native_popup={} owners={owners:?}",
egui::Popup::is_any_open(&self.ctx)
));
}
}
@@ -108,9 +129,9 @@ impl Frames {
}
fn escape(&mut self, mut draw: impl FnMut(&mut Ui)) {
let events = [true, false].map(|pressed| Event::Key {
key: Key::Escape, physical_key: Some(Key::Escape), pressed, repeat: false, modifiers: Modifiers::NONE,
}).to_vec();
let events = [true, false]
.map(|pressed| Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed, repeat: false, modifiers: Modifiers::NONE })
.to_vec();
self.frame(events, &mut draw);
self.settle(draw);
}
@@ -151,7 +172,14 @@ impl Frames {
}
fn assert_dismissed(&self) {
assert!(!self.rects.iter().any(|(id, _)| id.starts_with("versionMenu:") || id.starts_with("historyMenu:")), "action popup must be dismissed; sdk_keys_open={} sdk_top={:?} native_popup={} publication={:?}", craft::ui::runtime::overlay::any_open(&self.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), craft::ui::runtime::overlay::top(&self.ctx), egui::Popup::is_any_open(&self.ctx), self.publication);
assert!(
!self.rects.iter().any(|(id, _)| id.starts_with("versionMenu:") || id.starts_with("historyMenu:")),
"action popup must be dismissed; sdk_keys_open={} sdk_top={:?} native_popup={} publication={:?}",
craft::ui::runtime::overlay::any_open(&self.ctx, craft::ui::runtime::overlay::OpenFilter::Keys),
craft::ui::runtime::overlay::top(&self.ctx),
egui::Popup::is_any_open(&self.ctx),
self.publication
);
}
}
@@ -346,16 +374,24 @@ fn sdk_history_missing_photo_is_a_control_and_command_no_op() {
assert_eq!(state(&app, active), before);
}
#[derive(Clone, Copy)]
enum Panel { Snapshots, History }
enum Panel {
Snapshots,
History,
}
fn draw_panel(panel: Panel, app: &mut LightcraftApp, ui: &mut Ui, id: PhotoId) {
match panel { Panel::Snapshots => versions(app, ui, id), Panel::History => activity(app, ui, id) }
match panel {
Panel::Snapshots => versions(app, ui, id),
Panel::History => activity(app, ui, id),
}
}
fn open_panel_menu(panel: Panel, f: &mut Frames, app: &mut LightcraftApp, id: PhotoId, index: usize) {
match panel { Panel::Snapshots => version_menu(f, app, id, index), Panel::History => history_menu(f, app, id, index) }
match panel {
Panel::Snapshots => version_menu(f, app, id, index),
Panel::History => history_menu(f, app, id, index),
}
}
fn document(app: &LightcraftApp) -> serde_json::Value {
@@ -529,7 +565,11 @@ fn history_actions_unforced_tab_enter_space_cancel_exit_and_real_reopen() {
assert_eq!(app.session.before.get(&id), Some(settings));
assert_eq!(photo(&app, id), initial);
assert_eq!(app.session.undo.len(), undo);
let params = if action == "history-before" { json!({"source":"history", "index":index}) } else { json!({"source":"version", "name":initial.versions[0].name}) };
let params = if action == "history-before" {
json!({"source":"history", "index":index})
} else {
json!({"source":"version", "name":initial.versions[0].name})
};
assert_one_command(&app, journal, "beforeAfter.setBefore", params);
}
}
@@ -544,8 +584,14 @@ fn history_already_open_disabled_popup_refuses_pointer_and_keys_then_recovers()
for panel in [Panel::Snapshots, Panel::History] {
let (mut app, id) = fixture();
let initial = photo(&app, id);
let index = match panel { Panel::Snapshots => 0, Panel::History => initial.history.len() - 3 };
let target = match panel { Panel::Snapshots => "versionMenu:0:restore".to_owned(), Panel::History => format!("historyMenu:{index}:before") };
let index = match panel {
Panel::Snapshots => 0,
Panel::History => initial.history.len() - 3,
};
let target = match panel {
Panel::Snapshots => "versionMenu:0:restore".to_owned(),
Panel::History => format!("historyMenu:{index}:before"),
};
let mut f = Frames::new();
open_panel_menu(panel, &mut f, &mut app, id, index);
f.tab_to(&target, |ui| draw_panel(panel, &mut app, ui, id));
@@ -577,19 +623,32 @@ fn history_measured_release_is_inert_then_the_same_row_and_action_recover() {
for pass in [Pass::Sizing, Pass::Measure] {
let (mut app, id) = fixture();
let initial = photo(&app, id);
let index = match panel { Panel::Snapshots => 0, Panel::History => initial.history.len() - 3 };
let target = match panel { Panel::Snapshots => "versionMenu:0:restore".to_owned(), Panel::History => format!("historyMenu:{index}:before") };
let row = match panel { Panel::Snapshots => "version:0".to_owned(), Panel::History => format!("history:{index}") };
let index = match panel {
Panel::Snapshots => 0,
Panel::History => initial.history.len() - 3,
};
let target = match panel {
Panel::Snapshots => "versionMenu:0:restore".to_owned(),
Panel::History => format!("historyMenu:{index}:before"),
};
let row = match panel {
Panel::Snapshots => "version:0".to_owned(),
Panel::History => format!("history:{index}"),
};
let mut f = Frames::new();
open_panel_menu(panel, &mut f, &mut app, id, index);
let owner = f.hit(&row).id;
let at = f.rect(&target).center();
let baseline = document(&app);
f.frame(vec![Event::PointerMoved(at)], |ui| draw_panel(panel, &mut app, ui, id));
f.frame(vec![Event::PointerButton { pos:at, button:PointerButton::Primary, pressed:true, modifiers:Modifiers::NONE }], |ui| draw_panel(panel, &mut app, ui, id));
f.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], |ui| {
draw_panel(panel, &mut app, ui, id)
});
assert_eq!(document(&app), baseline, "ordinary action press is not its release");
f.pass = pass;
f.frame(vec![Event::PointerButton { pos:at, button:PointerButton::Primary, pressed:false, modifiers:Modifiers::NONE }], |ui| draw_panel(panel, &mut app, ui, id));
f.frame(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], |ui| {
draw_panel(panel, &mut app, ui, id)
});
assert_eq!(document(&app), baseline);
assert!(!f.rects.iter().any(|(id, _)| id.starts_with("version:") || id.starts_with("history:") || id.contains("Menu:")));
assert!(!f.hits.iter().any(|(id, _)| id.starts_with("version:") || id.starts_with("history:") || id.contains("Menu:")));
@@ -629,8 +688,8 @@ fn history_stale_photo_and_other_panel_cannot_retarget_an_existing_popup() {
let (mut app, id) = fixture();
let other = app.session.catalog.photos().find(|p| p.id != id).unwrap().id;
let template = photo(&app, id);
app.session.catalog.apply(lightcraft_catalog::Op::SetVersions { id:other, versions:template.versions.clone() }).unwrap();
app.session.catalog.apply(lightcraft_catalog::Op::SetHistory { id:other, history:template.history.clone() }).unwrap();
app.session.catalog.apply(lightcraft_catalog::Op::SetVersions { id: other, versions: template.versions.clone() }).unwrap();
app.session.catalog.apply(lightcraft_catalog::Op::SetHistory { id: other, history: template.history.clone() }).unwrap();
let mut f = Frames::new();
version_menu(&mut f, &mut app, id, 0);
let owner = f.hit("version:0").id;
@@ -664,7 +723,6 @@ fn history_stale_photo_and_other_panel_cannot_retarget_an_existing_popup() {
assert_eq!(document(&app), baseline);
}
#[test]
fn history_sdk_context_layer_keeps_carry_move_and_no_settle_escape_reopen_on_the_same_target() {
for panel in [Panel::Snapshots, Panel::History] {
@@ -675,9 +733,18 @@ fn history_sdk_context_layer_keeps_carry_move_and_no_settle_escape_reopen_on_the
let baseline = document(&app);
let undo = app.session.undo.len();
let journal = app.session.journal.len();
let index = match panel { Panel::Snapshots => 0, Panel::History => initial.history.len() - 3 };
let row = match panel { Panel::Snapshots => "version:0".to_owned(), Panel::History => format!("history:{index}") };
let target = match panel { Panel::Snapshots => "versionMenu:0:restore".to_owned(), Panel::History => format!("historyMenu:{index}:before") };
let index = match panel {
Panel::Snapshots => 0,
Panel::History => initial.history.len() - 3,
};
let row = match panel {
Panel::Snapshots => "version:0".to_owned(),
Panel::History => format!("history:{index}"),
};
let target = match panel {
Panel::Snapshots => "versionMenu:0:restore".to_owned(),
Panel::History => format!("historyMenu:{index}:before"),
};
let mut f = Frames::new();
f.settle(|ui| draw_panel(panel, &mut app, ui, id));
let bounds = f.rect(&row);
@@ -700,14 +767,22 @@ fn history_sdk_context_layer_keeps_carry_move_and_no_settle_escape_reopen_on_the
eprintln!("History first-Tab boundary {target}: {:?}", f.key_trace);
// No idle/settle frame between cancel and the next genuine secondary press/release.
f.frame(vec![Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: true, repeat: false, modifiers: Modifiers::NONE }], |ui| draw_panel(panel, &mut app, ui, id));
f.frame(
vec![Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: true, repeat: false, modifiers: Modifiers::NONE }],
|ui| draw_panel(panel, &mut app, ui, id),
);
assert_eq!(document(&app), baseline, "Escape cannot replay the focused action");
f.frame(vec![
Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: false, repeat: false, modifiers: Modifiers::NONE },
Event::PointerMoved(right),
Event::PointerButton { pos: right, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
], |ui| draw_panel(panel, &mut app, ui, id));
f.frame(vec![Event::PointerButton { pos: right, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }], |ui| draw_panel(panel, &mut app, ui, id));
f.frame(
vec![
Event::Key { key: Key::Escape, physical_key: Some(Key::Escape), pressed: false, repeat: false, modifiers: Modifiers::NONE },
Event::PointerMoved(right),
Event::PointerButton { pos: right, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
],
|ui| draw_panel(panel, &mut app, ui, id),
);
f.frame(vec![Event::PointerButton { pos: right, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }], |ui| {
draw_panel(panel, &mut app, ui, id)
});
assert!(!egui::Popup::is_any_open(&f.ctx));
assert_eq!(document(&app), baseline, "immediate reopening is not activation or restoration");
f.tab_to(&target, |ui| draw_panel(panel, &mut app, ui, id));
@@ -734,7 +809,6 @@ fn history_sdk_context_layer_keeps_carry_move_and_no_settle_escape_reopen_on_the
}
}
#[test]
fn history_popup_publication_tracks_completed_pass_on_pointer_cancel_and_activate() {
for panel in [Panel::Snapshots, Panel::History] {
@@ -745,8 +819,14 @@ fn history_popup_publication_tracks_completed_pass_on_pointer_cancel_and_activat
let selection = app.session.selection.clone();
let undo = app.session.undo.len();
let journal = app.session.journal.len();
let index = match panel { Panel::Snapshots => 0, Panel::History => initial.history.len() - 3 };
let target = match panel { Panel::Snapshots => "versionMenu:0:restore".to_owned(), Panel::History => format!("historyMenu:{index}:before") };
let index = match panel {
Panel::Snapshots => 0,
Panel::History => initial.history.len() - 3,
};
let target = match panel {
Panel::Snapshots => "versionMenu:0:restore".to_owned(),
Panel::History => format!("historyMenu:{index}:before"),
};
let mut f = Frames::new();
open_panel_menu(panel, &mut f, &mut app, id, index);
assert!(craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys));
@@ -765,7 +845,11 @@ fn history_popup_publication_tracks_completed_pass_on_pointer_cancel_and_activat
eprintln!("History publication open {target}: {:?}", f.publication);
f.escape(|ui| draw_panel(panel, &mut app, ui, id));
eprintln!("History publication cancelled {target}: sdk_keys_open={} passes={:?}", craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), f.publication);
eprintln!(
"History publication cancelled {target}: sdk_keys_open={} passes={:?}",
craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys),
f.publication
);
f.assert_dismissed();
assert!(!craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys));
assert_eq!(document(&app), baseline, "cancel may neither edit nor replay an action");
@@ -788,7 +872,11 @@ fn history_popup_publication_tracks_completed_pass_on_pointer_cancel_and_activat
assert_one_command(&app, journal, "beforeAfter.setBefore", json!({"source": "history", "index": index}));
}
}
eprintln!("History publication activated {target}: sdk_keys_open={} passes={:?}", craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys), f.publication);
eprintln!(
"History publication activated {target}: sdk_keys_open={} passes={:?}",
craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys),
f.publication
);
f.assert_dismissed();
assert!(!craft::ui::runtime::overlay::any_open(&f.ctx, craft::ui::runtime::overlay::OpenFilter::Keys));
assert_eq!(other_photos(&app, id), others);
+7 -10
View File
@@ -433,10 +433,8 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcr
ui.label(egui::RichText::new(label).size(11.5).color(t.text_dim));
let measuring = ui.is_sizing_pass() || craft::ui::runtime::measure::active(ui.ctx());
let editable = ui.is_enabled() && !targets.is_empty() && !measuring;
let entries: Vec<_> = lightcraft_catalog::CopyrightStatus::ALL
.into_iter()
.map(|status| Entry::new(status, crate::i18n::tr(status.label())))
.collect();
let entries: Vec<_> =
lightcraft_catalog::CopyrightStatus::ALL.into_iter().map(|status| Entry::new(status, crate::i18n::tr(status.label()))).collect();
let value = if mixed { Mixed::Mixed } else { Mixed::Same(current) };
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().max(1.0), 24.0), Sense::hover());
// The fixed field has already reserved its measured size. A speculative pass must not
@@ -447,12 +445,11 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcr
}
// Keep LightCraft's translated Mixed label without replacing the SDK's mixed binding.
let words = WordRows::new().row(Word::keyed("select.mixed", MIXED), crate::i18n::tr(MIXED));
let shown = with_env(ui, |scope| scope.words = Some(WordsOverride::Overlay(words)), |ui| {
Select::new(label, Bind::given(value), &entries)
.id_salt("info-copyright-status")
.enabled(editable)
.show_at(ui, rect)
});
let shown = with_env(
ui,
|scope| scope.words = Some(WordsOverride::Overlay(words)),
|ui| Select::new(label, Bind::given(value), &entries).id_salt("info-copyright-status").enabled(editable).show_at(ui, rect),
);
if !measuring {
crate::widgets::register_response("field:copyrightStatus", shown.response.rect, &shown.response);
// The SDK owns drafts, keyboard navigation and dismissal. Only its commit edits the
@@ -259,7 +259,10 @@ fn keyboard_escape_drops_draft_and_reopen_has_original_value() {
assert_eq!(f.values(), [Status::PublicDomain, Status::PublicDomain, Status::Copyrighted]);
assert_eq!(f.app.session.undo.len(), 1);
assert_eq!(f.app.session.journal.len(), 1);
assert_eq!(f.app.session.journal[0], ("photo.setMeta".into(), json!({"ids":f.targets.iter().map(|id|id.0).collect::<Vec<_>>(),"copyrightStatus":Status::PublicDomain.id()})));
assert_eq!(
f.app.session.journal[0],
("photo.setMeta".into(), json!({"ids":f.targets.iter().map(|id|id.0).collect::<Vec<_>>(),"copyrightStatus":Status::PublicDomain.id()}))
);
f.app.session.undo_step().unwrap();
assert_eq!(metadata_state(&f.app, &f.ids)["photos"], original["photos"]);
assert_eq!(f.app.session.selection, selection);
@@ -419,7 +422,10 @@ fn measured_opener(pass: u8) {
assert_eq!(f.values(), [Status::Unknown, Status::Unknown, Status::PublicDomain]);
assert_eq!(f.app.session.undo.len(), 1);
assert_eq!(f.app.session.journal.len(), 1, "one accepted command, not a speculative release and a real pick");
assert_eq!(f.app.session.journal[0], ("photo.setMeta".into(), json!({"ids":f.targets.iter().map(|id|id.0).collect::<Vec<_>>(),"copyrightStatus":Status::Unknown.id()})));
assert_eq!(
f.app.session.journal[0],
("photo.setMeta".into(), json!({"ids":f.targets.iter().map(|id|id.0).collect::<Vec<_>>(),"copyrightStatus":Status::Unknown.id()}))
);
f.app.session.undo_step().unwrap();
assert_eq!(metadata_state(&f.app, &ids)["photos"], before["photos"], "Undo restores every photo, including the untouched third target");
assert_eq!(f.app.session.selection, selection);
+62 -45
View File
@@ -1,6 +1,6 @@
use super::{HOLD, LightcraftApp, PhotoId, Rect, Tokens, fold_header, json, padded, register, text_button, vec2};
use craft::ui::buttons::Button;
use craft::ui::contract::{Props as _, Show as _};
use super::{HOLD, LightcraftApp, PhotoId, Rect, Tokens, fold_header, json, padded, register, text_button, vec2};
pub(super) fn keywords(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
// (the box is the selection's: the active photo only says that there is one)
@@ -367,51 +367,68 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) {
let face = crate::i18n::builtin_label(&current, current == recent).to_owned();
// (the dropdown takes the rest of the line, so a long set name is not cut and the chevron stays)
let room = ui.available_width();
crate::widgets::dropdown_menu_sized(ui, "keywordSetCombo", crate::i18n::tr("Keyword Set"), &face, Some(room), craft::theme::ControlSize::Sm, |ui| {
for set in sets["sets"].as_array().into_iter().flatten() {
let name = set["name"].as_str().unwrap_or_default();
if crate::widgets::menu_row(ui, ("keywordSet", name), None, crate::i18n::builtin_label(name, name == recent), None, name == current, true) {
let _ = app.run("keyword.useSet", json!({"name": name}));
crate::widgets::dropdown_menu_sized(
ui,
"keywordSetCombo",
crate::i18n::tr("Keyword Set"),
&face,
Some(room),
craft::theme::ControlSize::Sm,
|ui| {
for set in sets["sets"].as_array().into_iter().flatten() {
let name = set["name"].as_str().unwrap_or_default();
if crate::widgets::menu_row(
ui,
("keywordSet", name),
None,
crate::i18n::builtin_label(name, name == recent),
None,
name == current,
true,
) {
let _ = app.run("keyword.useSet", json!({"name": name}));
}
}
}
crate::widgets::menu_divider(ui);
// Edit Set…: the current nine, slot by slot (named, Recent Keywords becomes a set)
if crate::widgets::menu_row(ui, "keywordSetMenu:edit", Some("keywordSetMenu:edit"), crate::i18n::tr("Edit Set…"), None, false, true) {
let mut slots: Vec<String> =
sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect();
slots.resize(9, String::new());
let named = current != recent;
app.ui.dialog = Some(crate::state::Dialog::KeywordSet {
replaces: named.then(|| current.clone()),
name: if named { current.clone() } else { String::new() },
slots,
as_new: false,
});
}
if crate::widgets::menu_row(ui, "keywordSetMenu:save", None, crate::i18n::tr("Save Current Keywords as Set…"), None, false, true) {
app.ui.dialog = Some(crate::state::Dialog::TextPrompt {
title: "Save Keyword Set".into(),
hint: "Set name".into(),
value: String::new(),
command: "keyword.saveSet".into(),
params: json!({}),
key: "name".into(),
});
}
if current != recent
&& crate::widgets::menu_row(
ui,
"keywordSetMenu:delete",
None,
&crate::i18n::tr_format!("Delete “{current}”", current = current),
None,
false,
true,
)
{
let _ = app.run("keyword.deleteSet", json!({"name": current}));
}
});
crate::widgets::menu_divider(ui);
// Edit Set…: the current nine, slot by slot (named, Recent Keywords becomes a set)
if crate::widgets::menu_row(ui, "keywordSetMenu:edit", Some("keywordSetMenu:edit"), crate::i18n::tr("Edit Set…"), None, false, true)
{
let mut slots: Vec<String> =
sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect();
slots.resize(9, String::new());
let named = current != recent;
app.ui.dialog = Some(crate::state::Dialog::KeywordSet {
replaces: named.then(|| current.clone()),
name: if named { current.clone() } else { String::new() },
slots,
as_new: false,
});
}
if crate::widgets::menu_row(ui, "keywordSetMenu:save", None, crate::i18n::tr("Save Current Keywords as Set…"), None, false, true) {
app.ui.dialog = Some(crate::state::Dialog::TextPrompt {
title: "Save Keyword Set".into(),
hint: "Set name".into(),
value: String::new(),
command: "keyword.saveSet".into(),
params: json!({}),
key: "name".into(),
});
}
if current != recent
&& crate::widgets::menu_row(
ui,
"keywordSetMenu:delete",
None,
&crate::i18n::tr_format!("Delete “{current}”", current = current),
None,
false,
true,
)
{
let _ = app.run("keyword.deleteSet", json!({"name": current}));
}
},
);
});
let kws: Vec<String> = sets["keywords"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(str::to_string)).collect();
if kws.is_empty() {
@@ -393,7 +393,11 @@ fn remove_natural_keyboard_modes_numeric_commit_and_slider_steps_use_the_real_fo
}
f.key(Key::ArrowDown);
}
assert!(craft::ui::runtime::focus::focused_rec(&f.ctx).is_some_and(|r| r.stop.id == f.hit("removeMode:heal").id), "arrows reach Heal; trace={:#?}", f.trace);
assert!(
craft::ui::runtime::focus::focused_rec(&f.ctx).is_some_and(|r| r.stop.id == f.hit("removeMode:heal").id),
"arrows reach Heal; trace={:#?}",
f.trace
);
f.key(Key::Space);
assert_eq!(f.app.ui.tool, "heal");
assert_eq!(f.app.session.undo.len(), undo);
+55 -66
View File
@@ -14,13 +14,9 @@ const BUTTON_H: f32 = 40.0;
/// Space between tool buttons.
const GAP: f32 = 6.0;
/// Keep one definition of the actual Panel frame for drawing and its intrinsic reservation.
fn panel_frame(t: &Tokens) -> egui::Frame {
egui::Frame::NONE
.fill(t.chrome)
.inner_margin(egui::Margin { left: 0, right: 0, top: 8, bottom: 8 })
.stroke(egui::Stroke::new(1.0, t.divider))
egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin { left: 0, right: 0, top: 8, bottom: 8 }).stroke(egui::Stroke::new(1.0, t.divider))
}
/// Panel's documented separator is outside the frame, in its inner-facing outer margin.
@@ -76,64 +72,59 @@ pub(crate) fn show_in_shell(app: &mut LightcraftApp, ui: &mut egui::Ui, rtl: boo
pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
egui::Panel::right("tool_strip")
.exact_size(t.strip_w)
.resizable(false)
.frame(panel_frame(&t))
.show(ui, |ui| {
crate::widgets::announce_region(ui, egui::accesskit::Role::Toolbar, crate::i18n::tr("Tool strip"));
let has_photo = app.session.active().is_some();
ui.vertical_centered(|ui| {
ui.spacing_mut().item_spacing.y = GAP;
let sz = vec2(t.strip_w, BUTTON_H);
if icon_button(ui, "presets", Icon::Presets, sz, app.ui.presets, has_photo, "Presets (Shift+P)").clicked() {
let _ = app.run("panel.presets", json!({}));
egui::Panel::right("tool_strip").exact_size(t.strip_w).resizable(false).frame(panel_frame(&t)).show(ui, |ui| {
crate::widgets::announce_region(ui, egui::accesskit::Role::Toolbar, crate::i18n::tr("Tool strip"));
let has_photo = app.session.active().is_some();
ui.vertical_centered(|ui| {
ui.spacing_mut().item_spacing.y = GAP;
let sz = vec2(t.strip_w, BUTTON_H);
if icon_button(ui, "presets", Icon::Presets, sz, app.ui.presets, has_photo, "Presets (Shift+P)").clicked() {
let _ = app.run("panel.presets", json!({}));
}
for (id, icon, panel, tip) in [
("edit", Icon::Sliders, RightPanel::Edit, "Edit (E)"),
("crop", Icon::Crop, RightPanel::Crop, "Crop & Rotate (C)"),
("remove", Icon::Eraser, RightPanel::Remove, "Remove (H)"),
("masking", Icon::Mask, RightPanel::Masking, "Masking (M)"),
("redeye", Icon::Eye, RightPanel::RedEye, "Red Eye"),
] {
let on = app.ui.right == panel || (panel == RightPanel::Edit && app.ui.right == RightPanel::Profiles);
if icon_button(ui, id, icon, sz, on, has_photo, tip).clicked() {
let _ = app.run(&format!("panel.{id}"), json!({}));
}
for (id, icon, panel, tip) in [
("edit", Icon::Sliders, RightPanel::Edit, "Edit (E)"),
("crop", Icon::Crop, RightPanel::Crop, "Crop & Rotate (C)"),
("remove", Icon::Eraser, RightPanel::Remove, "Remove (H)"),
("masking", Icon::Mask, RightPanel::Masking, "Masking (M)"),
("redeye", Icon::Eye, RightPanel::RedEye, "Red Eye"),
] {
let on = app.ui.right == panel || (panel == RightPanel::Edit && app.ui.right == RightPanel::Profiles);
if icon_button(ui, id, icon, sz, on, has_photo, tip).clicked() {
let _ = app.run(&format!("panel.{id}"), json!({}));
}
if id == "edit" {
separator(ui, &t);
}
if id == "edit" {
separator(ui, &t);
}
separator(ui, &t);
if icon_button(ui, "versions", Icon::Versions, sz, app.ui.right == RightPanel::Versions, has_photo, "Versions (Shift+V)").clicked() {
let _ = app.run("panel.versions", json!({}));
}
if icon_button(ui, "activity", Icon::Activity, sz, app.ui.right == RightPanel::Activity, true, "History & Activity (Y)").clicked() {
let _ = app.run("panel.activity", json!({}));
}
if icon_button(ui, "more", Icon::More, sz, false, true, "More").clicked() {
app.ui.dialog = Some(crate::state::Dialog::About);
}
});
// bottom icons: two buttons and one gap tall, so Info ends at the bottom margin as
// Presets starts at the top one
let bottom = ui.max_rect().bottom();
let mut child =
ui.new_child(egui::UiBuilder::new().max_rect(egui::Rect::from_min_max(
egui::pos2(ui.max_rect().left(), bottom - (2.0 * BUTTON_H + GAP)),
ui.max_rect().right_bottom(),
)));
child.vertical_centered(|ui| {
ui.spacing_mut().item_spacing.y = GAP;
let sz = vec2(t.strip_w, BUTTON_H);
if icon_button(ui, "keywords", Icon::Tag, sz, app.ui.right == RightPanel::Keywords, has_photo, "Keywords (K)").clicked() {
let _ = app.run("panel.keywords", json!({}));
}
if icon_button(ui, "info", Icon::Info, sz, app.ui.right == RightPanel::Info, has_photo, "Info (I)").clicked() {
let _ = app.run("panel.info", json!({}));
}
});
}
separator(ui, &t);
if icon_button(ui, "versions", Icon::Versions, sz, app.ui.right == RightPanel::Versions, has_photo, "Versions (Shift+V)").clicked() {
let _ = app.run("panel.versions", json!({}));
}
if icon_button(ui, "activity", Icon::Activity, sz, app.ui.right == RightPanel::Activity, true, "History & Activity (Y)").clicked() {
let _ = app.run("panel.activity", json!({}));
}
if icon_button(ui, "more", Icon::More, sz, false, true, "More").clicked() {
app.ui.dialog = Some(crate::state::Dialog::About);
}
});
// bottom icons: two buttons and one gap tall, so Info ends at the bottom margin as
// Presets starts at the top one
let bottom = ui.max_rect().bottom();
let mut child = ui.new_child(
egui::UiBuilder::new()
.max_rect(egui::Rect::from_min_max(egui::pos2(ui.max_rect().left(), bottom - (2.0 * BUTTON_H + GAP)), ui.max_rect().right_bottom())),
);
child.vertical_centered(|ui| {
ui.spacing_mut().item_spacing.y = GAP;
let sz = vec2(t.strip_w, BUTTON_H);
if icon_button(ui, "keywords", Icon::Tag, sz, app.ui.right == RightPanel::Keywords, has_photo, "Keywords (K)").clicked() {
let _ = app.run("panel.keywords", json!({}));
}
if icon_button(ui, "info", Icon::Info, sz, app.ui.right == RightPanel::Info, has_photo, "Info (I)").clicked() {
let _ = app.run("panel.info", json!({}));
}
});
});
}
fn separator(ui: &mut egui::Ui, t: &Tokens) {
@@ -183,13 +174,11 @@ mod intrinsic_reservation_tests {
let frame = egui::Frame::NONE.stroke(egui::Stroke::new(stroke, egui::Color32::GRAY));
let expected = centered_reservation(48.0, child_width, frame_with_separator(frame, ui.style()));
let root = ui.available_rect_before_wrap();
egui::Panel::right("intrinsic-regression")
.exact_size(48.0).resizable(false).frame(frame)
.show(ui, |ui| {
ui.vertical_centered(|ui| {
ui.allocate_exact_size(vec2(child_width, 40.0), egui::Sense::hover());
});
egui::Panel::right("intrinsic-regression").exact_size(48.0).resizable(false).frame(frame).show(ui, |ui| {
ui.vertical_centered(|ui| {
ui.allocate_exact_size(vec2(child_width, 40.0), egui::Sense::hover());
});
});
let actual = root.right() - ui.available_rect_before_wrap().right();
assert_eq!(actual, expected, "width={width} scale={scale} child={child_width} stroke={stroke}");
if child_width == 32.0 {
@@ -31,10 +31,8 @@ impl Frames {
crate::theme::install_fonts(&ctx);
crate::theme::apply(&ctx);
ctx.enable_accesskit();
craft::ui::install(
&ctx,
craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::window::system::NoWindows)),
).unwrap();
craft::ui::install(&ctx, craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::window::system::NoWindows)))
.unwrap();
let mut session = lightcraft_engine::Session::new();
for (n, name) in [(1, CANONICAL), (2, REQUESTED), (3, "John Roe")] {
let mut photo = Photo::new(PhotoId(n), Source::Demo { scene: 0 }, "synthetic.jpg", "JPEG", 32, 32, "2026-01-01T00:00:00");
@@ -50,7 +48,10 @@ impl Frames {
app.ui.view = ViewMode::People;
app.ui.person_page = Some(REQUESTED.into());
app.caches.person_page = Some((
REQUESTED.into(), app.session.catalog.revision, app.caches.faces_indexed, 0.0,
REQUESTED.into(),
app.session.catalog.revision,
app.caches.faces_indexed,
0.0,
Arc::new(PersonPage { name: CANONICAL.into(), ..Default::default() }),
));
Self { ctx, app, time: 0.0, rects: vec![], hits: vec![], sizing: false, measuring: false, disabled: false, nodes: vec![] }
@@ -86,7 +87,9 @@ impl Frames {
}
fn settle(&mut self) {
for _ in 0..3 { self.frame(vec![]); }
for _ in 0..3 {
self.frame(vec![]);
}
}
fn at(&self, id: &str) -> Pos2 {
+2 -1
View File
@@ -148,7 +148,8 @@ fn filter_button(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rec
crate::i18n::tr("Filter bar").into()
};
let accent = if filtering { Some(t.accent) } else { None };
let (fresp, live) = bar_icon(ui, fr, ("top", "filter"), "icon:filter", Icon::Filter, 16, accent.unwrap_or(t.icon), accent.unwrap_or(t.text), &tip);
let (fresp, live) =
bar_icon(ui, fr, ("top", "filter"), "icon:filter", Icon::Filter, 16, accent.unwrap_or(t.icon), accent.unwrap_or(t.text), &tip);
if live && active > 0 {
let c = fr.right_top() + vec2(-3.0, 8.0);
ui.painter().circle_filled(c, 7.0, t.accent);
@@ -4,7 +4,11 @@ use crate::headless::HeadlessView;
use crate::widgets::{WidgetHit, take_registries};
#[derive(Clone, Copy)]
enum Pass { Real, EguiSizing, SdkSizing }
enum Pass {
Real,
EguiSizing,
SdkSizing,
}
struct Panel {
app: LightcraftApp,
@@ -21,20 +25,27 @@ impl Panel {
let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), crate::Services::default());
let photo = app.session.catalog.photos().next().unwrap().id;
let mut meta = app.session.catalog.photo(photo).unwrap().meta.clone();
meta.regions = (0..3).map(|i| lightcraft_meta::Region {
rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.2, y0: 0.2, x1: 0.25 + f64::from(i) * 0.2, y1: 0.5 },
kind: lightcraft_meta::RegionKind::Face,
name: None,
description: None,
}).collect();
meta.regions = (0..3)
.map(|i| lightcraft_meta::Region {
rect: lightcraft_geom::Rect { x0: 0.1 + f64::from(i) * 0.2, y0: 0.2, x1: 0.25 + f64::from(i) * 0.2, y1: 0.5 },
kind: lightcraft_meta::RegionKind::Face,
name: None,
description: None,
})
.collect();
app.session.commit("unnamed port fixture", lightcraft_catalog::Op::SetMeta { id: photo, meta: Box::new(meta) }).unwrap();
let list = Unnamed {
total: 3, ready: true, ordered: true,
faces: (0..3).map(|index| UnnamedFace {
photo: photo.0, index,
view: lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.25, y1: 0.5 },
suggestion: None,
}).collect(),
total: 3,
ready: true,
ordered: true,
faces: (0..3)
.map(|index| UnnamedFace {
photo: photo.0,
index,
view: lightcraft_geom::Rect { x0: 0.1, y0: 0.2, x1: 0.25, y1: 0.5 },
suggestion: None,
})
.collect(),
};
app.caches.unnamed = Some((app.session.catalog.revision, app.caches.faces_indexed, 0.0, Arc::new(list.clone())));
let view = HeadlessView::new();
@@ -56,12 +67,18 @@ impl Panel {
naming_bar(app, ui);
});
});
if let Some(record) = record { elements = record.elements.clone(); }
if let Some(record) = record {
elements = record.elements.clone();
}
};
match pass {
Pass::Real => draw(ui),
Pass::EguiSizing => { ui.scope_builder(egui::UiBuilder::new().sizing_pass(), |ui| draw(ui)); }
Pass::SdkSizing => { craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui)); }
Pass::EguiSizing => {
ui.scope_builder(egui::UiBuilder::new().sizing_pass(), |ui| draw(ui));
}
Pass::SdkSizing => {
craft::ui::runtime::measure::run(&ui.ctx().clone(), || draw(ui));
}
}
});
(self.rects, self.hits) = take_registries(&self.view.ctx);
@@ -71,7 +88,11 @@ impl Panel {
fn target(&self, id: &str) -> Rect {
let rect = self.rects.iter().find(|(key, _)| key == id).unwrap().1;
let hit = self.hits.iter().find(|(key, _)| key == id).unwrap().1;
let element = self.elements.iter().find(|element| element.id == hit.id && element.part.is_none()).expect("automation points at the real SDK component, not a probe");
let element = self
.elements
.iter()
.find(|element| element.id == hit.id && element.part.is_none())
.expect("automation points at the real SDK component, not a probe");
assert_eq!(element.component, "Button");
assert_eq!(element.rect, rect);
assert_eq!(hit.interact_rect, rect.intersect(hit.interact_rect));
@@ -82,7 +103,10 @@ impl Panel {
let pos = self.target(id).center();
self.frame(vec![egui::Event::PointerMoved(pos)], Pass::Real);
for pressed in [true, false] {
self.frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], Pass::Real);
self.frame(
vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }],
Pass::Real,
);
}
self.frame(vec![], Pass::Real);
}
@@ -127,7 +151,10 @@ fn unnamed_port_select_all_then_type_and_return_names_exact_keys_in_one_undo() {
let undo = p.app.session.undo.len();
p.frame(vec![egui::Event::Text("Port Example".into())], Pass::Real);
for pressed in [true, false] {
p.frame(vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }], Pass::Real);
p.frame(
vec![egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }],
Pass::Real,
);
}
let photo = lightcraft_catalog::PhotoId(p.list.faces[0].photo);
assert!(p.app.session.catalog.photo(photo).unwrap().meta.regions.iter().all(|region| region.name.as_deref() == Some("Port Example")));
@@ -178,14 +205,29 @@ fn unnamed_port_sizing_never_registers_or_changes_selection_or_settings() {
p.frame(vec![], Pass::Real);
p.frame(vec![], Pass::Real);
let pos = p.target(target).center();
let before = (p.app.ui.unnamed_selected.clone(), p.app.ui.unnamed_name.clone(), p.app.ui.unnamed_anchor, p.app.ui.dialog.clone(), p.app.session.undo.len());
let before = (
p.app.ui.unnamed_selected.clone(),
p.app.ui.unnamed_name.clone(),
p.app.ui.unnamed_anchor,
p.app.ui.dialog.clone(),
p.app.session.undo.len(),
);
p.frame(vec![egui::Event::PointerMoved(pos)], pass);
for pressed in [true, false] {
p.frame(vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }], pass);
p.frame(
vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }],
pass,
);
assert!(!p.rects.iter().any(|(id, _)| id == target));
assert!(!p.hits.iter().any(|(id, _)| id == target));
}
let after = (p.app.ui.unnamed_selected.clone(), p.app.ui.unnamed_name.clone(), p.app.ui.unnamed_anchor, p.app.ui.dialog.clone(), p.app.session.undo.len());
let after = (
p.app.ui.unnamed_selected.clone(),
p.app.ui.unnamed_name.clone(),
p.app.ui.unnamed_anchor,
p.app.ui.dialog.clone(),
p.app.session.undo.len(),
);
assert_eq!(before, after);
}
}
+12 -8
View File
@@ -297,12 +297,11 @@ pub(crate) fn framework_commands(keymap: &Keymap) -> craft::ui::runtime::command
&& (bindable().iter().any(|b| binding(keymap, b.id, b.default).and_then(parse) == chord)
|| ALIASES.iter().any(|(alias, _, _)| parse(alias) == chord))
};
let unbound: Vec<&'static str> =
[(NavCommand::NextPane, "F6"), (NavCommand::PreviousPane, "Shift+F6"), (NavCommand::FocusMenuBar, "F10")]
.into_iter()
.filter(|(_, sc)| uses(sc))
.map(|(command, _)| command.id())
.collect();
let unbound: Vec<&'static str> = [(NavCommand::NextPane, "F6"), (NavCommand::PreviousPane, "Shift+F6"), (NavCommand::FocusMenuBar, "F10")]
.into_iter()
.filter(|(_, sc)| uses(sc))
.map(|(command, _)| command.id())
.collect();
// One `Arc` per unbound set: the runtime rebuilds its keymap only when the `Arc` changes.
static LAST: std::sync::Mutex<Option<(Vec<&'static str>, std::sync::Arc<craft::keymap::Overrides>)>> = std::sync::Mutex::new(None);
let mut last = LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
@@ -575,14 +574,19 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context) {
/// The keys pressed this frame: the commands to fire, the aliases (command and params) to run, and
/// whether an unmodified H that no keymap assignment has claimed was pressed (the Masking panel's
/// pin toggle, see `handle`).
fn pressed_commands(app: &LightcraftApp, ctx: &egui::Context, clips: Vec<egui::Event>) -> (Vec<String>, Vec<(&'static str, serde_json::Value)>, bool) {
fn pressed_commands(
app: &LightcraftApp,
ctx: &egui::Context,
clips: Vec<egui::Event>,
) -> (Vec<String>, Vec<(&'static str, serde_json::Value)>, bool) {
let mut fire: Vec<String> = Vec::new();
// An Escape no framework component took reaches the app as the window's Cancel (the runtime keeps the raw key):
// the app's own Escape bindings (View ▸ Back and the like) read it there, last in the pass.
// While a framework popup (a menu, a dropdown) is open the Escape is the popup's: the runtime lends the focused
// row's unused Escape to the window, so taking it here, before the popup is drawn, would leave the menu open.
let popup_owns_escape = craft::ui::runtime::overlay::any_open(ctx, craft::ui::runtime::overlay::OpenFilter::Keys);
let window_escape = !popup_owns_escape && craft::ui::runtime::keys::with_window_intents(ctx, false, |w| w.take(craft::ui::runtime::keys::Intent::Cancel));
let window_escape =
!popup_owns_escape && craft::ui::runtime::keys::with_window_intents(ctx, false, |w| w.take(craft::ui::runtime::keys::Intent::Cancel));
// The same for the clipboard events the runtime routed to the window as edit commands.
let mut window_edits: Vec<egui::Event> = clips;
craft::ui::runtime::keys::with_window_intents(ctx, false, |w| {
+4 -4
View File
@@ -13,7 +13,6 @@ fn settle_budget_only_expands_for_llvm_coverage_runs() {
}
mod activity;
mod dialog_settings_popup_contract;
mod album_picker;
mod album_remove;
mod alt_preview;
@@ -35,12 +34,13 @@ mod curve;
mod date_picker;
mod dialog_copy;
mod dialog_fit;
mod dialog_settings_blur_count;
mod dialog_primary;
mod dialog_settings;
mod dialog_settings_text;
mod dialog_settings_blur_count;
mod dialog_settings_keyboard_contract;
mod dialog_settings_keyboard_guards;
mod dialog_settings_popup_contract;
mod dialog_settings_text;
mod dialog_tab;
mod dialogs;
mod disk_space;
@@ -126,5 +126,5 @@ mod zoom_keys;
pub(super) mod fixtures;
pub(super) mod render_fixtures;
mod real_journey;
mod port_screenshots;
mod real_journey;
+12 -3
View File
@@ -281,7 +281,10 @@ fn a_press_on_a_menu_over_a_guide_selects_nothing() {
let r = h.request("ui.click", json!({"x": line.x - 30.0, "y": line.y - 30.0, "button": "right"}), T);
assert_eq!(r["ok"], true, "{r}");
h.settle(SETTLE);
assert!(craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), "the context menu is open over the photo");
assert!(
craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any),
"the context menu is open over the photo"
);
let img = h.app.image_rect.expect("the photo on screen");
let (lx, ly) = ((line.x - img.left()) / img.width(), (line.y - img.top()) / img.height());
let r = h.request("ui.pointer", json!({"events": [{"kind": "down", "x": lx, "y": ly}, {"kind": "up", "x": lx, "y": ly}]}), T);
@@ -310,7 +313,10 @@ fn a_press_on_a_menu_over_an_endpoint_moves_nothing() {
let r = h.request("ui.click", json!({"x": end.x - 30.0, "y": end.y - 30.0, "button": "right"}), T);
assert_eq!(r["ok"], true, "{r}");
h.settle(SETTLE);
assert!(craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), "the context menu is open over the photo");
assert!(
craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any),
"the context menu is open over the photo"
);
let img = h.app.image_rect.expect("the photo on screen");
let (ex, ey) = ((end.x - img.left()) / img.width(), (end.y - img.top()) / img.height());
let r = h.request(
@@ -344,7 +350,10 @@ fn a_press_that_leaves_the_menu_in_one_frame_draws_nothing() {
let r = h.request("ui.click", json!({"x": end.x - 30.0, "y": end.y - 30.0, "button": "right"}), T);
assert_eq!(r["ok"], true, "{r}");
h.settle(SETTLE);
assert!(craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any), "the context menu is open over the photo");
assert!(
craft::ui::runtime::overlay::any_open(&h.view.ctx, craft::ui::runtime::overlay::OpenFilter::Any),
"the context menu is open over the photo"
);
// one batch: go down 1px inside the menu, then straight off it to bare photo, far below
// both guides, and release there — the current pointer never sees the menu again
let img = h.app.image_rect.expect("the photo on screen");
+1 -8
View File
@@ -932,14 +932,7 @@ fn library_recovery_actions_155_retry_reaches_existing_switch_guard_without_disk
let (keep_pending, rx) = std::sync::mpsc::channel();
let mut rx = Some(rx);
h.app.services.picker = Some(Box::new(move |_| Ok(rx.take().expect("one fake pending picker"))));
let picked = crate::pick::ask(
&mut h.app,
"folder.move",
&json!({}),
"path",
crate::pick::PickRequest::folder("Fake pending move"),
|_| None,
);
let picked = crate::pick::ask(&mut h.app, "folder.move", &json!({}), "path", crate::pick::PickRequest::folder("Fake pending move"), |_| None);
assert!(matches!(picked, crate::pick::Picked::Later));
recovery_actions_155_click(&mut h, "button:libraryRetry");
let problem = h.app.library_problem.as_ref().expect("Retry keeps the error window");
+1 -3
View File
@@ -1847,9 +1847,7 @@ fn the_masking_panel_has_no_widget_id_clashes() {
h.settle(SETTLE);
h.step();
let clashes = id_clash_warnings(&h);
let near = |p: egui::Pos2| {
h.app.widgets.iter().filter(|(_, r)| r.expand(6.0).contains(p)).map(|(w, _)| w.clone()).collect::<Vec<_>>()
};
let near = |p: egui::Pos2| h.app.widgets.iter().filter(|(_, r)| r.expand(6.0).contains(p)).map(|(w, _)| w.clone()).collect::<Vec<_>>();
let said: Vec<_> = clashes.iter().map(|(t, p)| format!("{t} at {p:?} near {:?}", near(*p))).collect();
assert!(clashes.is_empty(), "{said:#?}");
}
+22 -6
View File
@@ -145,7 +145,10 @@ fn scenes() -> Vec<(&'static str, Scene)> {
// the menu bar with a menu open, and the photo menu
for title in ["File", "Edit", "Photo", "View", "Help"] {
all.push((
{ let name: &'static str = Box::leak(format!("menubar-{}", title.to_lowercase()).into_boxed_str()); name },
{
let name: &'static str = Box::leak(format!("menubar-{}", title.to_lowercase()).into_boxed_str());
name
},
Box::new(move |h| {
select(h, 2)?;
ui(h, json!({"view": "photoGrid", "leftPanel": true}))?;
@@ -252,9 +255,15 @@ fn scenes() -> Vec<(&'static str, Scene)> {
all.push(open_dialog("dlg-whats-new", json!({"kind": "whatsNew"})));
all.push(open_dialog("dlg-welcome-1", json!({"kind": "welcome", "page": 0})));
all.push(open_dialog("dlg-welcome-3", json!({"kind": "welcome", "page": 2})));
all.push(open_dialog("dlg-system-info", json!({"kind": "systemInfo", "rows": [["Version", "1.0"], ["Platform", "Linux"], ["Memory", "16 GiB"]]})));
all.push(open_dialog(
"dlg-system-info",
json!({"kind": "systemInfo", "rows": [["Version", "1.0"], ["Platform", "Linux"], ["Memory", "16 GiB"]]}),
));
all.push(open_dialog("dlg-confirm-delete", json!({"kind": "confirmDelete", "count": 3})));
all.push(open_dialog("dlg-remove-folder", json!({"kind": "removeFolder", "path": "/pics/trip", "name": "pics/trip", "count": 12, "disk": false})));
all.push(open_dialog(
"dlg-remove-folder",
json!({"kind": "removeFolder", "path": "/pics/trip", "name": "pics/trip", "count": 12, "disk": false}),
));
all.push(open_dialog(
"dlg-move-photos",
json!({"kind": "movePhotos", "ids": [1, 2], "folder": "/pics/trip", "name": "trip", "dont_ask": false, "library": 0}),
@@ -293,7 +302,10 @@ fn scenes() -> Vec<(&'static str, Scene)> {
all.push(open_dialog("dlg-denoise-model", json!({"kind": "denoiseModel", "info": {}, "accepted": false})));
all.push(open_dialog("dlg-sam-model", json!({"kind": "samModel", "then": null})));
all.push(open_dialog("dlg-lens-database", json!({"kind": "lensDatabase", "dir": "/tmp/lens", "mirrors": []})));
all.push(open_dialog("dlg-lightroom-catalog", json!({"kind": "lightroomCatalog", "folder": "/Lightroom", "catalog": "/Lightroom/Catalog.lrcat"})));
all.push(open_dialog(
"dlg-lightroom-catalog",
json!({"kind": "lightroomCatalog", "folder": "/Lightroom", "catalog": "/Lightroom/Catalog.lrcat"}),
));
all.push(open_dialog(
"dlg-lightroom-destination",
json!({"kind": "lightroomDestination", "catalog": "/Lightroom/Catalog.lrcat", "library": "Photos", "photos": 120, "new_library": false,
@@ -321,7 +333,8 @@ fn scenes() -> Vec<(&'static str, Scene)> {
let _ = std::fs::remove_dir_all(&folder);
std::fs::create_dir_all(folder.join("day 2")).map_err(|e| e.to_string())?;
for i in 0..8usize {
let img = lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [((x * 2 + i * 30) % 256) as u8, (y * 4 % 256) as u8, (60 + i * 25) as u8, 255]);
let img =
lightcraft_raster::Rgba8::from_fn(96, 64, |x, y| [((x * 2 + i * 30) % 256) as u8, (y * 4 % 256) as u8, (60 + i * 25) as u8, 255]);
let png = lightcraft_engine::export::encode_image(
&img,
&lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() },
@@ -378,7 +391,10 @@ fn port_screenshots() {
let why = match done {
Ok(Ok(())) => continue,
Ok(Err(e)) => e,
Err(panic) => format!("panicked: {}", panic.downcast_ref::<String>().cloned().or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default()),
Err(panic) => format!(
"panicked: {}",
panic.downcast_ref::<String>().cloned().or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default()
),
};
eprintln!("SHOT-MISSING {file}: {why}");
missing.push(format!("{file}: {}", why.lines().next().unwrap_or("")));
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more