Record Measurements: warn and record nothing when no data point is enabled for the source (#17407)

Recording with no data point set for the measured source (Selection, Ruler Tool or Count Tool) wrote an
empty "Measurement N" row. The command now returns the reference application's warning and records
nothing; the menu shows it as an alert with OK and "Set Data Points…", which opens Select Data Points.
This commit is contained in:
qvest-ssels committed 2026-11-29 01:44:19 +01:00
1 parent 81fe7ba596
commit 2ad09cd72a
5 files changed
+226 -2

No files matched your search

@@ -1058,6 +1058,27 @@ fn feature_values(m: &mut Map<String, Value>, f: &Feature, count: usize, factor:
m.insert("histogram".into(), json!(f.histogram));
}
/// The start of Record Measurements' error when no data point is enabled for the source it records; the source's
/// name and a full stop follow (#17407).
pub const NO_DATA_POINTS: &str = "There are no measurement data points currently enabled for the ";
/// The second line of that alert.
pub const NO_DATA_POINTS_DETAIL: &str = "Data points must be set before measurements can be recorded.";
/// The name the alert gives source `source` (`selection`, `ruler` or `count`).
pub fn data_points_source_name(source: &str) -> &'static str {
match source {
"ruler" => "Ruler Tool",
"count" => "Count Tool",
_ => "Selection",
}
}
/// Record Measurements' error for `source` with no data point enabled: the alert's two lines.
fn no_data_points(source: &str) -> String {
format!("{NO_DATA_POINTS}{}.\n{NO_DATA_POINTS_DETAIL}", data_points_source_name(source))
}
fn record(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "image.analysis.recordMeasurements";
let d = doc(s)?;
@@ -1117,6 +1138,11 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {
rows.push(m);
}
}
// No data point enabled for the source: the reference application's alert, and nothing is recorded (no
// empty row, no label number used up, #17407).
if s.analysis.data_points.of(source).is_empty() {
return Err(EngineError::Other(no_data_points(source)));
}
s.analysis.next_measurement += 1;
let keep = s.analysis.data_points.of(source).to_vec();
let mut ids = Vec::new();
@@ -1414,4 +1440,6 @@ mod analysis_straighten_selection_tests;
#[cfg(test)]
mod data_points_empty_set_tests;
#[cfg(test)]
mod record_no_data_points_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,72 @@
//! #17407: Record Measurements with no data point enabled for the source it records refuses with the reference
//! application's alert text, records nothing and does not use up a label number. Ruler and Count get the same check,
//! naming their tool.
use super::*;
const RECORD: &str = "image.analysis.recordMeasurements";
const POINTS: &str = "image.analysis.selectDataPoints";
fn session() -> Session {
let mut s = crate::session();
s.execute("file.new", json!({"width": 200, "height": 120, "background": "white"})).unwrap();
s
}
fn log_len(s: &mut Session) -> usize {
s.execute("measurementLog.list", json!({})).unwrap()["rows"].as_array().map_or(0, Vec::len)
}
fn message(e: &EngineError) -> String {
e.to_string()
}
#[test]
fn a_selection_with_only_ruler_points_on_warns_and_records_nothing() {
let mut s = session();
s.execute(POINTS, json!({"selection": [], "ruler": ["length", "angle"], "count": []})).unwrap();
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
let e = s.execute(RECORD, json!({})).unwrap_err();
assert_eq!(
message(&e),
"There are no measurement data points currently enabled for the Selection.\nData points must be set before measurements can be recorded."
);
assert!(message(&e).starts_with(NO_DATA_POINTS));
assert_eq!(log_len(&mut s), 0, "no empty row");
// The label number was not used up: after setting a point, the first row is "Measurement 1".
s.execute(POINTS, json!({"selection": ["label", "area"]})).unwrap();
let r = s.execute(RECORD, json!({})).unwrap();
assert_eq!(r["rows"][0]["values"]["label"], json!("Measurement 1"), "{r}");
assert_eq!(log_len(&mut s), 1);
}
#[test]
fn ruler_and_count_get_the_same_check_with_their_tool_name() {
let mut s = session();
s.execute(POINTS, json!({"selection": ["area"], "ruler": [], "count": []})).unwrap();
s.execute("image.analysis.rulerTool", json!({"start": [10, 50], "end": [40, 10]})).unwrap();
let e = s.execute(RECORD, json!({"source": "ruler"})).unwrap_err();
assert_eq!(message(&e), format!("{NO_DATA_POINTS}Ruler Tool.\n{NO_DATA_POINTS_DETAIL}"));
s.execute("count.add", json!({"x": 20, "y": 20})).unwrap();
let e = s.execute(RECORD, json!({"source": "count"})).unwrap_err();
assert_eq!(message(&e), format!("{NO_DATA_POINTS}Count Tool.\n{NO_DATA_POINTS_DETAIL}"));
assert_eq!(log_len(&mut s), 0);
// With a point on, each source records as before.
s.execute(POINTS, json!({"ruler": ["length"], "count": ["count"]})).unwrap();
assert!(s.execute(RECORD, json!({"source": "ruler"})).is_ok());
assert!(s.execute(RECORD, json!({"source": "count"})).is_ok());
assert_eq!(log_len(&mut s), 2);
}
#[test]
fn a_source_that_has_points_records_whatever_the_other_sources_hold() {
let mut s = session();
s.execute(POINTS, json!({"selection": ["area"], "ruler": [], "count": []})).unwrap();
s.execute("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
let r = s.execute(RECORD, json!({})).unwrap();
assert_eq!(r["rows"][0]["values"]["area"], json!(5000.0), "{r}");
}
+1
View File
@@ -440,6 +440,7 @@ pub(crate) type PromptRow = fn(&mut PhotocraftApp, &egui::Context, &mut PromptAn
pub(crate) const PROMPTS: &[PromptRow] = &[
crate::tools::tool_reset::answer,
crate::analysis::note_alerts::answer,
crate::analysis::no_data_points_answer,
delete_layer_prompt::answer,
mask_trash_prompt::answer,
disk_change_prompt::answer,
+49 -2
View File
@@ -8,6 +8,8 @@
//! [`note_alerts`].
use craft::behavior::Selection;
use craft::ui::dialog::{PromptAnswer, PromptChoice, StandardPrompt};
use photocraft_engine::analysis_cmds;
use photocraft_engine::color_cmds::ColorExt;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -172,8 +174,12 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<
_ => "auto",
};
let r = app.run(id, json!({"source": source}));
if r.is_ok() {
let _ = crate::panel_docking::show_panel(app, MEASUREMENT_LOG, Some(true));
match &r {
Ok(_) => {
let _ = crate::panel_docking::show_panel(app, MEASUREMENT_LOG, Some(true));
}
Err(e) if e.starts_with(analysis_cmds::NO_DATA_POINTS) => no_data_points_alert(app, e),
Err(_) => {}
}
r
}
@@ -199,6 +205,43 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<
})
}
/// The tag of the alert Record Measurements shows when no data point is enabled for the source (#17407).
pub(crate) struct NoDataPoints;
/// The reference's warning when Record Measurements has no data point to record for the source named in `error`:
/// OK, or Set Data Points… to open Select Data Points with the current set. Nothing was recorded.
fn no_data_points_alert(app: &mut PhotocraftApp, error: &str) {
let source = error.strip_prefix(analysis_cmds::NO_DATA_POINTS).and_then(|rest| rest.split_once('.')).map_or("", |(name, _)| name);
let name = match source {
"Ruler Tool" => tl!("Ruler Tool"),
"Count Tool" => tl!("Count Tool"),
_ => tl!("Selection"),
};
let message = crate::i18n::fmt(tl!("There are no measurement data points currently enabled for the {source}."), &[("source", name)]);
let prompt = StandardPrompt::custom(message)
.title(tl!("PhotoCraft"))
.paragraph(tl!("Data points must be set before measurements can be recorded."))
.icon(craft::behavior::IconId::new("warning"))
.button(PromptChoice::Proceed, tl!("OK"))
.button(PromptChoice::Alternate, tl!("Set Data Points…"))
.escape(PromptChoice::Proceed)
.tag(NoDataPoints);
let _ = crate::dialogs::alerts::open_prompt(app, prompt);
}
/// The `PROMPTS` entry of that alert: Set Data Points… opens Select Data Points, whose OK only stores the set.
pub(crate) fn no_data_points_answer(app: &mut PhotocraftApp, _ctx: &egui::Context, answer: &mut PromptAnswer) -> bool {
if answer.take_tag::<NoDataPoints>().is_none() {
return false;
}
if answer.choice == PromptChoice::Alternate
&& let Err(error) = dialogs::open(app, dialogs::Kind::DataPoints)
{
crate::dialogs::alerts::report_error(app, error);
}
true
}
/// Export the Measurement Log (or the given rows) as CSV through the save picker.
pub(crate) fn export_log(app: &mut PhotocraftApp, rows: Option<Vec<u64>>) -> Result<Value, String> {
let p = rows.map_or(json!({}), |r| json!({"rows": r}));
@@ -251,3 +294,7 @@ pub(super) fn status_on_err(app: &mut PhotocraftApp, r: Result<Value, String>) {
app.ui.status_error = false;
}
}
#[cfg(test)]
#[path = "record_no_data_points_alert_tests.rs"]
mod record_no_data_points_alert_tests;
@@ -0,0 +1,76 @@
//! #17407: Image › Analysis › Record Measurements with no data point enabled for the source shows the warning with
//! OK and Set Data Points…; the latter opens Select Data Points with the current set, whose OK only stores the set.
use craft::ui::dialog::{DialogId, StandardPrompt};
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use serde_json::json;
use super::NoDataPoints;
use crate::PhotocraftApp;
const RECORD: &str = "image.analysis.recordMeasurements";
fn app() -> (Box<PhotocraftApp>, egui::Context) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 120})).unwrap();
app.run("image.analysis.selectDataPoints", json!({"selection": [], "ruler": ["length", "angle"], "count": []})).unwrap();
app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
let ctx = app.ctx().clone();
(app, ctx)
}
fn rows(app: &mut PhotocraftApp) -> usize {
app.run("measurementLog.list", json!({})).unwrap()["rows"].as_array().map_or(0, Vec::len)
}
/// The open alert: its id, and its message, paragraphs and buttons as shown.
fn alert(app: &PhotocraftApp) -> Option<(DialogId, String, Vec<String>, Vec<String>)> {
let id = crate::dialogs::alerts::prompt_tagged::<NoDataPoints>(app)?;
let prompt = app.framework.dialogs.get::<StandardPrompt>()?;
let host = app.framework.host();
let buttons = prompt.shown_buttons(host).into_iter().map(|(_, label)| label).collect();
Some((id, prompt.shown_message(host), prompt.shown_paragraphs(host), buttons))
}
#[test]
fn record_measurements_shows_the_warning_with_ok_and_set_data_points() {
let (mut app, ctx) = app();
assert!(crate::menus::invoke(&mut app, &ctx, RECORD, json!({})).is_err());
let (id, message, paragraphs, buttons) = alert(&app).expect("the warning is open");
assert_eq!(message, "There are no measurement data points currently enabled for the Selection.");
assert_eq!(paragraphs, ["Data points must be set before measurements can be recorded."]);
assert_eq!(buttons, ["OK", "Set Data Points…"]);
assert_eq!(rows(&mut app), 0, "nothing is recorded");
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
assert!(alert(&app).is_none(), "OK closes it");
assert!(app.framework.dialogs.get::<HostedParamDialog>().is_none(), "OK opens nothing");
}
#[test]
fn set_data_points_opens_select_data_points_whose_ok_only_stores_the_set() {
let (mut app, ctx) = app();
let _ = crate::menus::invoke(&mut app, &ctx, RECORD, json!({}));
let (id, ..) = alert(&app).unwrap();
app.framework.dialogs.set_json_field(&ctx, id, "choice", json!("alternate")).unwrap();
crate::dialogs::confirm(&mut app, &ctx, id).unwrap();
assert!(alert(&app).is_none());
let dialog = app.framework.dialogs.get::<HostedParamDialog>().map(craft::ui::dialog::StackDialog::id).expect("Select Data Points is open");
// The current set: Ruler Length is ticked, Selection Area is not.
let fields = serde_json::to_value(app.framework.dialogs.get_by_id::<HostedParamDialog>(dialog).unwrap().fields()).unwrap();
assert_eq!(fields["ruler:length"], json!(true), "{fields}");
assert_ne!(fields["selection:area"], json!(true), "{fields}");
crate::dialogs::confirm(&mut app, &ctx, dialog).unwrap();
assert_eq!(rows(&mut app), 0, "its OK records nothing");
assert!(alert(&app).is_none(), "its OK does not record, so it does not warn again");
let points = app.run("image.analysis.selectDataPoints", json!({})).unwrap();
assert_eq!(points["dataPoints"]["ruler"], json!(["length", "angle"]), "its OK stores the set it shows: {points}");
app.run("image.analysis.selectDataPoints", json!({"selection": ["area"], "ruler": [], "count": []})).unwrap();
// Now Record Measurements records, as "Measurement 1".
crate::menus::invoke(&mut app, &ctx, RECORD, json!({})).unwrap();
assert_eq!(rows(&mut app), 1);
assert!(alert(&app).is_none());
}