From e952bf9b7d1777b9af62495074292a5339f91d26 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 12:15:35 -0600 Subject: [PATCH 01/10] feat(ui): Select By Attributes lists a field's values to pick from A Values button beside the field buttons lists the distinct values of the field last clicked, or the one a value typed at the cursor is compared with, read once when the list is opened (query::field_values: a sample of at most 10,000 features, a streamed layer's view). A click writes what query::complete_at says the clause takes at its end, so it still reads: only the value where a value compared with a field goes (a bracket left open is closed, BETWEEN takes it for both ends), a list of one after a bare IN, the comparison anywhere else. --- crates/ui-egui/src/dialogs.rs | 190 +++++++++++++++++++++- crates/ui-egui/src/exprcomplete.rs | 37 ++++- crates/ui-egui/src/fieldvalues.rs | 243 +++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 1 + docs/user-guide/expressions.md | 12 ++ 5 files changed, 479 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/fieldvalues.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ef0d3dc4c5..abfabc218e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -83,6 +83,8 @@ pub struct Dialogs { pub csv_crs_dirty: bool, /// Import DXF's file, picked before the dialog opens. pub dxf: Option, + /// Select By Attributes' Values list: its field, and the values read for it. + pub values: crate::fieldvalues::Form, /// Reset collapsed then closed dialogs when reopening pub reset_collapse: bool, } @@ -1008,6 +1010,8 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { }); if (!open || close) && app.dialogs.open == Some(which) { app.dialogs.open = None; + // Its values read are dropped with the dialog. + app.dialogs.values = Default::default(); if which == "addDxf" { app.dialogs.dxf = None; } @@ -2851,12 +2855,27 @@ const MAX_FIELD_CHIPS: usize = 40; /// offer. A field an earlier one shadows (`name` after `Name`: the expression reads the first, /// letter case aside) gets no button, as the completion list doesn't offer it. pub(crate) fn field_chips(ui: &mut egui::Ui, fields: &[rustgis_engine::data::Field], text: &mut String) { + field_chips_with(ui, fields, text, |_| {}); +} + +/// [`field_chips`] with `first` drawn right after the "Fields:" label, in the row of the buttons +/// (Select By Attributes' Values button). Returns the name of the field whose button was clicked +/// this frame, for what depends on the field last chosen. +pub(crate) fn field_chips_with( + ui: &mut egui::Ui, + fields: &[rustgis_engine::data::Field], + text: &mut String, + first: impl FnOnce(&mut egui::Ui), +) -> Option { + let mut clicked = None; ui.horizontal_wrapped(|ui| { ui.label(egui::RichText::new(tl!("Fields:")).small().weak()); + first(ui); let mut seen = std::collections::HashSet::new(); for f in fields.iter().filter(|f| seen.insert(f.name.to_ascii_lowercase())).take(MAX_FIELD_CHIPS) { if ui.small_button(&f.name).clicked() { add_word(text, &crate::exprcomplete::field_ref(&f.name)); + clicked = Some(f.name.clone()); } } }); @@ -2871,6 +2890,7 @@ pub(crate) fn field_chips(ui: &mut egui::Ui, fields: &[rustgis_engine::data::Fie add_word(text, &word); } }); + clicked } fn select_by_attributes(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) -> bool { @@ -2915,7 +2935,7 @@ fn select_by_attributes(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) -> // Suggestions as it's typed: the fields, functions, variables and keywords (#1240). let ds = app.session.map().layer_by_name(&app.dialogs.layer).map(|l| &l.dataset); let id = egui::Id::unique("sba_where"); - crate::exprcomplete::expr_edit_lines(ui, id, &mut app.dialogs.text, ds, |text| { + let edit = crate::exprcomplete::expr_edit_lines(ui, id, &mut app.dialogs.text, ds, |text| { text_box(text) .hint_text(tl!("e.g. pop_est > 100000000 AND continent = 'Asia'")) .desired_rows(3) @@ -2923,8 +2943,23 @@ fn select_by_attributes(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) -> .font(egui::TextStyle::Monospace) }) .labelled_by(input_label.id); + // The Values list is of the field last clicked, or typed in the box. + app.dialogs.values.follow(&app.dialogs.layer); + if let Some(ds) = ds.filter(|_| edit.has_focus()) { + app.dialogs.values.follow_box(ui, id, &app.dialogs.text, ds); + } let fields = ds.map(|d| d.fields.as_slice()).unwrap_or_default(); - field_chips(ui, fields, &mut app.dialogs.text); + let mut picked = None; + let clicked = field_chips_with(ui, fields, &mut app.dialogs.text, |ui| { + picked = crate::fieldvalues::button(ui, &mut app.dialogs.values, ds); + }); + if let Some(field) = clicked { + app.dialogs.values.choose(&field); + } + if let (Some((field, value)), Some(ds)) = (picked, ds) { + crate::fieldvalues::insert(&mut app.dialogs.text, &field, &value, ds); + } + crate::fieldvalues::said(ui, &app.dialogs.values); // Live validation, once no suggestion is offered: a word still being chosen isn't an error yet. let offering = crate::exprcomplete::offering(ui, id); let check = app @@ -4389,6 +4424,157 @@ mod tests { assert!(h.query_by_label_contains("Invalid:").is_some(), "the error once the list is closed"); } + /// Select By Attributes' Values list: the distinct values of the field last clicked, typed or + /// put the cursor in; a click writes the comparison with the field, or only the value after an + /// operator. Read once when the list is opened, not each frame it stays open, and dropped when + /// the field or the layer changes. + #[test] + fn select_by_attributes_values_list_writes_what_it_lists() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("ui.dialog", json!({"name": "selectByAttributes"})).unwrap(); + app.dialogs.layer = "Countries".into(); + let mut h = app_harness(app); + h.run_steps(3); + let values = |h: &mut egui_kittest::Harness<'static, RustGisApp>| { + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + }; + let pick = |h: &mut egui_kittest::Harness<'static, RustGisApp>, value: &str| { + h.get_by_role_and_label(Role::Button, value).click(); + h.run(); + }; + // No field chosen yet: it says what to do, as the list has nothing to show. + values(&mut h); + assert!(h.query_by_label("Click a field, or put the cursor in one, to list its values").is_some()); + // A field clicked: its values are listed, read once however long the list stays open. + h.get_by_role_and_label(Role::Button, "continent").click(); + h.run(); + assert!(h.query_by_label("Click a field, or put the cursor in one, to list its values").is_none(), "said no more"); + h.state_mut().dialogs.text.clear(); + values(&mut h); + h.run_steps(5); + assert_eq!(h.state().dialogs.values.reads, 1); + assert!(h.query_by_label_contains("evenly spread").is_none() && h.query_by_label_contains("read for the view").is_none()); + pick(&mut h, "'Asia'"); + assert_eq!(h.state().dialogs.text, "continent = 'Asia' ", "the comparison, the value quoted"); + assert!(h.query_by_role_and_label(Role::Button, "'Africa'").is_none(), "the list closed"); + // Opened again for the same field: the values are kept. + values(&mut h); + assert_eq!(h.state().dialogs.values.reads, 1, "kept while the dialog stays on the field"); + // After an operator only the value goes. + h.state_mut().dialogs.text = "continent <> ".into(); + pick(&mut h, "'Africa'"); + assert_eq!(h.state().dialogs.text, "continent <> 'Africa' "); + h.state_mut().dialogs.text = "name IN (".into(); + values(&mut h); + pick(&mut h, "'Asia'"); + assert_eq!(h.state().dialogs.text, "name IN ('Asia') ", "a list of one, closed so the clause reads"); + // Another field reads its own values. + h.get_by_role_and_label(Role::Button, "name").click(); + h.run(); + h.state_mut().dialogs.text.clear(); + values(&mut h); + assert_eq!(h.state().dialogs.values.reads, 2); + assert!(h.query_by_role_and_label(Role::Button, "'Asia'").is_none(), "not the last field's values"); + // Another layer has no field chosen: the list is dropped with the layer. + h.key_press(egui::Key::Escape); + h.run(); + h.state_mut().dialogs.layer = "Cities".into(); + h.run_steps(2); + values(&mut h); + assert!(h.query_by_label("Click a field, or put the cursor in one, to list its values").is_some()); + // Dropped with the dialog. + h.state_mut().dialogs.layer = "Countries".into(); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "continent").click(); + h.run(); + values(&mut h); + assert_eq!(h.state().dialogs.values.reads, 3); + h.key_press(egui::Key::Escape); + h.run(); + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run(); + assert_eq!((h.state().dialogs.open, h.state().dialogs.values.reads), (None, 0)); + } + + /// A field typed in the box is the one listed, as one clicked is. + #[test] + fn select_by_attributes_values_list_follows_the_field_typed() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("ui.dialog", json!({"name": "selectByAttributes"})).unwrap(); + app.dialogs.layer = "Countries".into(); + let mut h = app_harness(app); + h.run_steps(3); + h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("sba_where"))); + h.run(); + h.event(egui::Event::Text("continent".into())); + h.run(); + h.event(egui::Event::Text(" = ".into())); + h.run(); + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + h.get_by_role_and_label(Role::Button, "'Asia'").click(); + h.run(); + assert_eq!(h.state().dialogs.text, "continent = 'Asia' ", "the operator typed, only the value added"); + } + + /// A value holding a single quote is written with it doubled, and the clause picks the row. + /// A list of values read from a sample says so (`read` of `of` features), a streamed layer's + /// says they are of the features in view, and the whole of a layer says nothing. + #[test] + fn select_by_attributes_values_list_quotes_values_and_says_where_they_come_from() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let points = |names: Vec| { + let features = names.iter().enumerate().map( + |(i, n)| json!({"type": "Feature", "geometry": {"type": "Point", "coordinates": [i % 90, 0]}, "properties": {"name": n}}), + ); + json!({"type": "FeatureCollection", "features": features.collect::>()}).to_string() + }; + let open = |text: String| { + let mut app = RustGisApp::new(Session::new(rustgis_engine::Project::default())); + app.run("layer.addDataText", json!({"fileName": "people.geojson", "text": text})).unwrap(); + app.run("ui.dialog", json!({"name": "selectByAttributes"})).unwrap(); + let mut h = app_harness(app); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "name").click(); + h.run(); + h.state_mut().dialogs.text.clear(); + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + h + }; + let mut h = open(points(vec!["O'Brien".into(), "Paul".into()])); + h.get_by_role_and_label(Role::Button, "'O''Brien'").click(); + h.run(); + let text = h.state().dialogs.text.clone(); + assert_eq!(text, "name = 'O''Brien' "); + let layer = h.state().session.map().layer_by_name(&h.state().dialogs.layer).map(|l| l.dataset.clone()); + let layer = layer.unwrap(); + assert_eq!(rustgis_engine::data::query::select(&text, &layer), Ok(vec![0]), "the clause picks the feature it was made from"); + + // All of the layer: nothing said. As a streamed layer's view: said. + let mut h = open(points(vec!["a".into(), "b".into(), "a".into()])); + assert!(h.query_by_label_contains("evenly spread").is_none() && h.query_by_label_contains("read for the view").is_none()); + let id = h.state().session.map().layer_by_name(&h.state().dialogs.layer).map(|l| l.id).unwrap(); + h.state_mut().session.map_mut().layer_mut(id).unwrap().dataset.windowed = true; + h.run(); + assert!(h.query_by_label("Values of the 3 features read for the view").is_some()); + + // More features than are read: a sample, and how much of it. + let names = (0..rustgis_engine::data::query::VALUES_READ + 50).map(|i| format!("n{}", i % 7)).collect(); + let h = open(points(names)); + let layer = h.state().session.map().layer_by_name(&h.state().dialogs.layer).map(|l| l.dataset.clone()).unwrap(); + let got = rustgis_engine::data::query::field_values(&layer, 0, rustgis_engine::data::query::VALUES_READ); + assert!(got.read < got.of, "a sample was read"); + let said = format!("Values of {} of {} features, evenly spread", got.read, got.of); + assert!(h.query_by_label(&said).is_some(), "the list says {said:?}"); + } + /// Calculate Field previews what it would write (#2817): the first three rows of a table, as /// the field holds them, with what writing them loses; nothing for an expression that doesn't /// read, or while a suggestion is offered. diff --git a/crates/ui-egui/src/exprcomplete.rs b/crates/ui-egui/src/exprcomplete.rs index 43ad6953c5..b72d3e6592 100644 --- a/crates/ui-egui/src/exprcomplete.rs +++ b/crates/ui-egui/src/exprcomplete.rs @@ -44,7 +44,7 @@ enum Item { /// Which features a field's values were read from, for the help to say when it isn't all of the /// layer's (`query::field_values`). #[derive(Clone, Copy, Debug, PartialEq)] -struct ValuesRead { +pub(crate) struct ValuesRead { read: usize, of: usize, /// A streamed layer's: its dataset holds the features read for the view. @@ -52,6 +52,12 @@ struct ValuesRead { } impl ValuesRead { + /// Where `got` was read from, in `ds`: a streamed layer's dataset holds the features read for + /// the view (`Dataset::windowed`). + pub(crate) fn of(got: &query::FieldValues, ds: &Dataset) -> Self { + Self { read: got.read, of: got.of, view: ds.windowed } + } + /// What the help says of where the values come from; None when they are all the layer's. fn note(self) -> Option { let (read, of) = (self.read.to_string(), self.of.to_string()); @@ -189,7 +195,7 @@ fn values(c: &Completion, text: &str, ds: &Dataset, asked: bool) -> Vec { return Vec::new(); } let got = query::field_values(ds, i, query::VALUES_READ); - let read = ValuesRead { read: got.read, of: got.of, view: ds.windowed }; + let read = ValuesRead::of(&got, ds); let lower = c.prefix.to_lowercase(); got.values .into_iter() @@ -646,6 +652,33 @@ pub(crate) fn menu(ui: &mut Ui, label: impl Into, menu: Menu) }) } +/// A button `label` that opens the list of a field's values, as the Functions and Variables menus +/// do, each value's help naming its `field` and, when the values aren't all of the layer's, where +/// they were read from. `values` gives the values as an expression writes them (`'Paris'`, `10`) +/// and where they were read from; it is called each frame the list is open, so it should hold +/// what it worked out. Returns the value accepted, as written. +pub(crate) fn values_menu( + ui: &mut Ui, + label: impl Into, + field: &str, + values: impl FnOnce() -> (Vec, ValuesRead), +) -> Option { + // Given with the values, and wanted by the help drawn after them. + let read = std::cell::Cell::new(None); + let items = || { + let (items, from) = values(); + read.set(Some(from)); + items + }; + let help = |ui: &mut Ui, value: &str, width: f32| { + if let Some(read) = read.get() { + draw_help(ui, &Item::Value(value.to_string(), field.to_string(), read), None, width); + } + }; + let spoken = |_: usize| read.get().map(|read| spoken_item(&Item::Value(String::new(), field.to_string(), read), None)); + crate::completion::menu(ui, label, items, |_| None, spoken, true, help).1 +} + /// The Functions and Variables menus beside a clause's buttons (`menu`). Returns what to add for /// the entry accepted in either. pub(crate) fn menus(ui: &mut Ui) -> Option { diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs new file mode 100644 index 0000000000..7d08714ae3 --- /dev/null +++ b/crates/ui-egui/src/fieldvalues.rs @@ -0,0 +1,243 @@ +//! Select By Attributes' Values list: the distinct values of a field, to pick from. A user who +//! clicked a field and wonders what it holds sees them without opening the table, and a click +//! writes the comparison, the value quoted as the expression needs it. +//! +//! The values are what the completion offers after `"field" = '` (`query::field_values`): read +//! from an evenly spread sample of at most `query::VALUES_READ` features, a streamed layer's from +//! the features in view. They are read once, when the list is opened for a field, and kept while +//! the dialog stays on that layer and field and the layer's rows don't change. + +use std::sync::Weak; + +use egui::Ui; +use egui::widgets::text_edit::TextEditState; +use rustgis_engine::data::query::{self, Completion, FieldValues, Kw, Place}; +use rustgis_engine::data::{Dataset, Feature}; + +use crate::exprcomplete::{ValuesRead, field_ref, fields_key}; + +/// The Values list between frames, held by the dialog (`Dialogs::values`): which field it lists, +/// and the values read for it. +#[derive(Default)] +pub struct Form { + /// The layer the field belongs to, by the name the dialog has it under. + layer: String, + /// The field last clicked, or the cursor was last in, as the layer names it. + field: Option, + read: Option, + /// Why there is no list to show, for the dialog to say under the buttons. + said: Option, + /// How many times the values were read: once per list opened, not once per frame. + #[cfg(test)] + pub(crate) reads: usize, +} + +/// The values of a field, as read, and the rows and fields they were read from: another set of +/// rows (an edit, a reload, a streamed layer's next view) or another type of field reads them +/// again. +struct Read { + rows: Weak>, + fields: u64, + got: FieldValues, + /// What the list shows for each value: as the expression writes it. + written: Vec, +} + +impl Form { + /// Follows the layer the dialog is on: the list is of one layer's field, so another layer + /// has none until a field of it is chosen. + pub(crate) fn follow(&mut self, layer: &str) { + if self.layer != layer { + self.layer = layer.to_string(); + self.field = None; + self.read = None; + self.said = None; + } + } + + /// Lists `field` from now on. Another field drops the values read for the last. + pub(crate) fn choose(&mut self, field: &str) { + if self.field.as_deref() != Some(field) { + self.field = Some(field.to_string()); + self.read = None; + self.said = None; + } + } + + /// Lists the field the box `id` (holding `text`, with the focus) has its cursor where a value + /// compared with one of `ds`'s goes (`name = ▮`, `name IN ('a', ▮`): a field typed is a field + /// chosen, as `query::complete_at` reads it. + pub(crate) fn follow_box(&mut self, ui: &Ui, id: egui::Id, text: &str, ds: &Dataset) { + let cursor = TextEditState::load(ui.ctx(), id).and_then(|s| s.cursor.char_range()).map(|r| r.primary.index.0); + let field = cursor.and_then(|at| query::complete_at(text, at, ds)).and_then(|c| c.field); + if let Some(field) = field.and_then(|i| ds.fields.get(i)) { + self.choose(&field.name); + } + } + + /// The values of field `field` of `ds`, as written, and where they were read from, read + /// unless they are held from the rows and fields `ds` has now. Says why there is nothing to + /// list when there is none. + fn list(&mut self, ds: &Dataset, field: usize) -> (Vec, ValuesRead) { + let (rows, fields) = (ds.features.allocation_key(), fields_key(ds)); + if !self.read.as_ref().is_some_and(|r| r.fields == fields && r.rows.ptr_eq(&rows)) { + self.read = None; + } + #[cfg(test)] + let reads = &mut self.reads; + let read = self.read.get_or_insert_with(|| { + #[cfg(test)] + { + *reads += 1; + } + let got = query::field_values(ds, field, query::VALUES_READ); + let written = got.values.iter().map(|v| v.written.clone()).collect(); + Read { rows, fields, got, written } + }); + let name = ds.fields.get(field).map(|f| f.name.as_str()).unwrap_or_default(); + self.said = read.written.is_empty().then(|| crate::i18n::fmt("{field} has no values to list", &[("field", &field_ref(name))])); + (read.written.clone(), ValuesRead::of(&read.got, ds)) + } +} + +/// The Values button, beside a clause's field buttons: opens the list of the chosen field's +/// values. Returns the field and the value accepted, as the expression writes it (`insert` +/// puts them in the clause). Without a field chosen, says to choose one. +pub(crate) fn button(ui: &mut Ui, form: &mut Form, ds: Option<&Dataset>) -> Option<(String, String)> { + let label = tl!("Values ▾"); + let chosen = ds.zip(form.field.clone()).and_then(|(ds, name)| Some((ds, ds.fields.iter().position(|f| f.name == name)?, name))); + let Some((ds, field, name)) = chosen else { + if ui.button(label).clicked() { + form.said = Some(tl!("Click a field, or put the cursor in one, to list its values").to_string()); + } + return None; + }; + let accepted = crate::exprcomplete::values_menu(ui, label, &name, || form.list(ds, field)); + accepted.map(|value| (name, value)) +} + +/// What the dialog says under its buttons about the list, when there is nothing to list. +pub(crate) fn said(ui: &mut Ui, form: &Form) { + if let Some(said) = &form.said { + ui.label(egui::RichText::new(said).small().weak()); + } +} + +/// Adds `value` (as the expression writes it) of `field` to the end of the clause `text`, where +/// `query::complete_at` says the clause stands at its end (`ds` has the fields): +/// - where a value compared with a field goes (`name = `, `pop >`, `name IN (`, `pop BETWEEN `), +/// only the value, which `BETWEEN` takes for both ends (`BETWEEN 10 AND 10`, to edit) and a +/// bracket left open (`IN (`) is closed after; +/// - after a bare `IN` (a list is next), the value as a list of one (`IN ('Asia')`); +/// - anywhere else, the comparison with the field (`"Pop Est" = 10`). +/// +/// A text or a quoted name begun and left open (`name = 'As`) is replaced by what is added, as the +/// completion does; a clause that can't be read at all gets the comparison, and the box says why +/// it doesn't read. +pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset) { + let mut at = at_end(text, ds); + if let Some(open) = at.as_ref().filter(|c| c.place != Place::Code) { + let keep = text.char_indices().nth(open.word.start).map_or(text.len(), |(i, _)| i); + text.truncate(keep); + at = at_end(text, ds); + } + let put = match &at { + Some(c) if c.operand && c.field.is_some() => value.to_string(), + Some(c) if !c.operand && c.symbols == ["("] => format!("({value})"), + _ => format!("{} = {value}", field_ref(field)), + }; + crate::dialogs::add_word(text, &put); + // What the value left to finish (the end of the clause is where it was added). + let then = at_end(text, ds); + if then.as_ref().is_some_and(|c| !c.operand && c.keywords == [Kw::And]) { + // `BETWEEN 10` needs `AND` and a second end. + crate::dialogs::add_word(text, &format!("AND {value}")); + } + if at_end(text, ds).is_some_and(|c| c.symbols.contains(&")")) { + text.pop(); + text.push_str(") "); + } +} + +/// What may go at the end of `text`, where a value is added: read with a space after it, so a +/// name or keyword typed last (`IN`) is a word complete, not one being typed. +fn at_end(text: &str, ds: &Dataset) -> Option { + let text = format!("{} ", text.trim_end()); + query::complete_at(&text, text.chars().count(), ds) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn countries() -> Dataset { + let app = crate::RustGisApp::with_sample(); + let layer = app.session.map().layer_by_name("Countries"); + layer.expect("the sample has Countries").dataset.clone() + } + + /// The value goes where a value compared with a field goes, a list of one after a bare `IN`, + /// and the comparison anywhere else; each result is the exact text, and reads on Countries. + /// Every case is checked before the test fails, so one run shows them all. + #[test] + fn a_value_is_added_where_the_clause_takes_it_and_the_clause_still_reads() { + let ds = countries(); + // (the clause, the field listed, the value listed, what the clause becomes) + let cases = [ + // A clause starting, or a new one: the comparison, the field quoted if it needs it. + ("", "continent", "'Asia'", "continent = 'Asia' "), + ("continent = 'Asia' AND ", "pop_est", "10", "continent = 'Asia' AND pop_est = 10 "), + ("continent = 'Asia' AND", "pop_est", "10", "continent = 'Asia' AND pop_est = 10 "), + // After a comparison operator: the value alone, whatever field was listed. + ("continent = ", "continent", "'Asia'", "continent = 'Asia' "), + ("continent =", "continent", "'Asia'", "continent = 'Asia' "), + ("pop_est >=", "pop_est", "10", "pop_est >= 10 "), + ("continent LIKE", "continent", "'Asia'", "continent LIKE 'Asia' "), + // A value with a quote is written as given (the list doubles it). + ("", "name", "'O''Brien'", "name = 'O''Brien' "), + ("name = ", "name", "'O''Brien'", "name = 'O''Brien' "), + // In a list: the value, and the list closed. + ("continent IN (", "continent", "'Asia'", "continent IN ('Asia') "), + ("continent IN ('Asia',", "continent", "'Africa'", "continent IN ('Asia', 'Africa') "), + // After a bare `IN` or `NOT IN`, a list is next. + ("continent IN", "continent", "'Asia'", "continent IN ('Asia') "), + ("continent not in ", "continent", "'Asia'", "continent not in ('Asia') "), + // `BETWEEN` takes both ends: the value for each, to edit, or the upper end after `AND`. + ("pop_est BETWEEN", "pop_est", "10", "pop_est BETWEEN 10 AND 10 "), + ("pop_est BETWEEN 1 AND", "pop_est", "10", "pop_est BETWEEN 1 AND 10 "), + ("(pop_est BETWEEN ", "pop_est", "10", "(pop_est BETWEEN 10 AND 10) "), + // A text begun is replaced by the value. + ("continent = 'As", "continent", "'Asia'", "continent = 'Asia' "), + ]; + let mut wrong = Vec::new(); + for (clause, field, value, expected) in cases { + let mut text = clause.to_string(); + insert(&mut text, field, value, &ds); + if text != expected { + wrong.push(format!("`{clause}` + {value} wrote `{text}`, not `{expected}`")); + } + if let Err(e) = query::select(&text, &ds) { + wrong.push(format!("`{clause}` + {value} wrote `{text}`, which doesn't read: {e}")); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); + // A clause that doesn't read at all gets the comparison, and the box says why. + let mut text = "pop_est > 1 ) AND".to_string(); + insert(&mut text, "continent", "'Asia'", &ds); + assert_eq!(text, "pop_est > 1 ) AND continent = 'Asia' "); + } + + /// The field a value typed at the cursor is compared with (what `follow_box` lists) is the + /// one `complete_at` reads there, wherever in the clause; none outside a comparison. + #[test] + fn the_field_listed_is_the_one_the_value_at_the_cursor_is_compared_with() { + let ds = countries(); + let of = |text: &str, cursor: usize| { + query::complete_at(text, cursor, &ds).and_then(|c| c.field).and_then(|i| ds.fields.get(i)).map(|f| f.name.clone()) + }; + assert_eq!(of("continent = ", 12).as_deref(), Some("continent")); + assert_eq!(of("pop_est > 1 AND continent IN ('a', ", 36).as_deref(), Some("continent")); + assert_eq!(of("continent = 'x' AND pop_est > 1", 12).as_deref(), Some("continent"), "the text before the cursor only"); + assert_eq!(of("continent", 9), None, "no operator yet"); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dd31c685bb..28804ec08c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -49,6 +49,7 @@ mod extensionsui; mod failureui; mod fieldlists; mod fieldmenu; +mod fieldvalues; #[cfg(not(target_arch = "wasm32"))] mod filedialog; mod fill_editor; diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index abd2d70ab6..f423057e7f 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -274,6 +274,18 @@ which **Set Filter** applies, those boxes apply what's written when they lose fo in the list keeps the focus, so a field taken from it isn't applied half written; while the list is open Escape closes it, not the box nor the Display Filters menu. +Select By Attributes also has a **Values** menu beside the field buttons. It lists the distinct +values of the field last clicked, or the one a value typed at the cursor would be compared with +(`continent = ` lists `continent`), in the same list. Choosing a value adds what the clause takes +there, so it still reads: the comparison (`continent = 'Asia'`, the field in double quotes when its +name needs them, a `'` in the value doubled) where none is open; only the value after `=`, `<>`, +`<`, `>`, `<=`, `>=`, `LIKE`, `ILIKE`, in a list (`IN ('Asia', 'Africa')`, closed for you) or after +`BETWEEN` (which takes the value for both ends, to edit); a list of one after `IN`; and in place +of a text begun and left open. The values are read as the suggestions' are, once when the list is +opened, and the help says when they come from a sample of the layer or, for a streamed layer, from +the features read for the view. A field with nothing to list (all null, true or false, or only +text too long) says so under the buttons. + They help too in the clause boxes of several lines: Select By Attributes' **Where**, the Layer Properties **Query** tab and a label class's SQL query. There the list shows under the cursor's line and the signature over the line of its call. While the list is open, Enter takes its item From cefad9580e3f85298e5d836fffd9436e767e8e07 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 20:30:45 -0600 Subject: [PATCH 02/10] fix(ui): Values fills the clause where the cursor was, and says which values it leaves out - A value goes at the cursor the field came from, keeping the rest of the clause; after a field button, it adds `= value`; a computed left side (`upper(name) =`) gets only the value (`Completion::compared`). - Nothing is written for a `%`/`_` value after LIKE or past MAX_LEN, and the box says why. - The list is held as read while it is open, so Enter takes what was highlighted. - `field_values` counts the values it leaves out (too long, several lines), and the help says how many. - `completion::menu` borrows its items; the values are held once. --- crates/data/src/query.rs | 17 +- crates/data/src/query/complete.rs | 48 ++++- crates/ui-egui/src/completion.rs | 15 +- crates/ui-egui/src/dialogs.rs | 111 +++++++++- crates/ui-egui/src/exprcomplete.rs | 42 +++- crates/ui-egui/src/fieldvalues.rs | 319 ++++++++++++++++++++++++----- docs/user-guide/expressions.md | 21 +- 7 files changed, 494 insertions(+), 79 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 98b9e9e2ad..c0cbd23416 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -821,6 +821,8 @@ struct Probe { field: Option, /// Whether that value is a `LIKE` / `ILIKE` pattern (`name LIKE ▮`). pattern: bool, + /// Whether the value at the end is compared, whatever the left side is (`upper(name) = ▮`). + compared: bool, } /// How a token is written, for the symbols [`Probe`] notes. @@ -864,18 +866,19 @@ impl Parser<'_> { what(&mut p); } } - /// Notes that a value at the end would be compared with `l`, when `l` is a field. + /// Notes that a value at the end would be compared with `l`, and with which field when `l` is + /// one. fn note_compared(&self, l: &Expr) { self.note_compared_as(l, false); } /// As [`note_compared`](Self::note_compared), the value a `LIKE` pattern when `pattern`. fn note_compared_as(&self, l: &Expr, pattern: bool) { - if let Expr::Field(f) = l { - self.note(self.pos, |p| { - p.field = Some(*f); - p.pattern = pattern; - }); - } + let field = if let Expr::Field(f) = l { Some(*f) } else { None }; + self.note(self.pos, |p| { + p.compared = true; + p.field = field; + p.pattern = pattern; + }); } fn probing(&self) -> bool { self.probe.is_some() diff --git a/crates/data/src/query/complete.rs b/crates/data/src/query/complete.rs index 5164eff249..7d6e77b6a3 100644 --- a/crates/data/src/query/complete.rs +++ b/crates/data/src/query/complete.rs @@ -50,6 +50,10 @@ pub struct Completion { /// Whether the value typed here is a `LIKE` / `ILIKE` pattern, where `%` and `_` match more /// than themselves (`name LIKE '▮`). pub pattern: bool, + /// Whether a value typed here is the right-hand side of a comparison, `LIKE`, `IN` or + /// `BETWEEN`, whatever its left side is: a field ([`field`](Self::field) says which) or + /// something computed (`upper(name) = ▮`), which has no field to take values from. + pub compared: bool, } /// A call the cursor is in, from [`complete_at`]: its function, which argument (from 0), and @@ -134,6 +138,7 @@ pub fn complete_at(text: &str, cursor: usize, ds: &Dataset) -> Option FieldValues { let step = usize::try_from(crate::source::stride(of as u64, most.max(1))).unwrap_or(usize::MAX); let mut seen = std::collections::HashSet::new(); let mut values = Vec::new(); - let mut read = 0; + let (mut read, mut left_out) = (0, 0); for f in ds.features.iter().step_by(step) { read += 1; let Some(v) = f.attrs.get(field) else { continue }; if matches!(v, Value::Text(t) if t.chars().nth(VALUE_CHARS).is_some() || t.chars().any(char::is_control)) { + left_out += 1; continue; } + let written = literal(v); // A float is written in full (`1e300` as 301 digits): too long to list, as a text is. - if let Some(written) = literal(v).filter(|w| !matches!(v, Value::Float(_)) || w.len() <= VALUE_CHARS) + if matches!(v, Value::Float(_)) && written.as_ref().is_some_and(|w| w.len() > VALUE_CHARS) { + left_out += 1; + continue; + } + if let Some(written) = written && !seen.contains(&written) { seen.insert(written.clone()); @@ -198,7 +213,7 @@ pub fn field_values(ds: &Dataset, field: usize, most: usize) -> FieldValues { let by_number = ClassText::numeric(values.iter().map(|(t, _)| t)); values.sort_by(|a, b| if by_number { a.0.cmp(&b.0) } else { a.0.text().cmp(b.0.text()) }); let values = values.into_iter().map(|(text, written)| FieldValue { written, text: text.into_text() }).collect(); - FieldValues { values, read, of } + FieldValues { values, read, of, left_out } } /// `v` as an expression writes it, to compare a field with: a number as it is (in full, `3.25`, @@ -311,6 +326,10 @@ mod tests { let written = |field| field_values(&d, field, VALUES_READ).values.into_iter().map(|v| v.written).collect::>(); let v = field_values(&d, 0, VALUES_READ); assert_eq!((v.read, v.of), (9, 9)); + // The text of two lines and the one too long are counted as left out; null and NaN are no + // value to list, not one left out. + assert_eq!(v.left_out, 2); + assert_eq!(field_values(&d, 1, VALUES_READ).left_out, 2, "1e300 and -1e-300 in full"); let longest = "x".repeat(VALUE_CHARS); assert_eq!(written(0), ["'A'".to_string(), "'b'".to_string(), format!("'{longest}'")], "up to the longest text listed"); assert_eq!(v.values.first(), Some(&FieldValue { written: "'A'".into(), text: "A".into() })); @@ -398,6 +417,29 @@ mod tests { assert_eq!(at_end("upper(name) = ").field, None); } + /// A value is compared whatever its left side is: a field, or something computed that has no + /// field to list values of. + #[test] + fn a_value_compared_with_anything_is_said_compared() { + for text in [ + "name = ", + "pop >= ", + "name LIKE ", + "name IN ('a', ", + "pop BETWEEN ", + "pop BETWEEN 1 AND ", + "upper(name) = ", + "upper(name) LIKE '", + "pop + 1 BETWEEN ", + "pop * 2 IN (", + ] { + assert!(at_end(text).compared, "{text}"); + } + for text in ["", "pop ", "pop > 5 ", "upper(", "name = 'a' AND ", "pop BETWEEN 1 "] { + assert!(!at_end(text).compared, "{text}"); + } + } + #[test] fn a_call_says_its_function_and_argument() { let call = |c: &Completion| c.call.map(|c| (c.spec.func, c.arg, c.open)); diff --git a/crates/ui-egui/src/completion.rs b/crates/ui-egui/src/completion.rs index 5a26d500e7..edb1eb2f89 100644 --- a/crates/ui-egui/src/completion.rs +++ b/crates/ui-egui/src/completion.rs @@ -878,15 +878,18 @@ struct MenuState { /// and what it says (`describe`) given to a screen reader with each. The same from the keyboard: /// Tab to the button, Enter (or Space) opens it, and Tab on to another widget closes it. Returns /// the button, and the item accepted. -pub(crate) fn menu( +pub(crate) fn menu( ui: &mut Ui, label: impl Into, - items: impl FnOnce() -> Vec, + items: impl FnOnce() -> L, icon: impl Fn(&str) -> Option<&'static str>, describe: impl Fn(usize) -> Option, has_help: bool, help: impl FnOnce(&mut Ui, &str, f32), -) -> (egui::Response, Option) { +) -> (egui::Response, Option) +where + L: std::ops::Deref, +{ let button = ui.button(label); let id = button.id.with("menu"); let pass = ui.ctx().cumulative_pass_nr(); @@ -910,7 +913,9 @@ pub(crate) fn menu( }); } s.pass = pass; - let items = if s.open { items() } else { Vec::new() }; + // Lent, not copied: a field's values can run to thousands (`fieldvalues`). + let held = s.open.then(items); + let items: &[String] = held.as_deref().unwrap_or_default(); let n = items.len(); // While it's open the arrows and Escape are the list's, not egui's: they'd move the focus off // the button (to another button, which Enter would then press) or drop it. A focused row's @@ -980,7 +985,7 @@ pub(crate) fn menu( let scroll = &mut s.scroll; let mut got = Rows::default(); let drawn = popup(ui, id, corner, room, |ui| { - got = rows(ui, &items, selected, pointer_leads, scroll, follow, has_help, icon, describe, help) + got = rows(ui, items, selected, pointer_leads, scroll, follow, has_help, icon, describe, help) }); // The arrows move the highlight with the focus on the button: the highlighted row is the // button's active descendant, read as a box's list's is (`List::show`). diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index abfabc218e..1364faf7bd 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2957,7 +2957,7 @@ fn select_by_attributes(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) -> app.dialogs.values.choose(&field); } if let (Some((field, value)), Some(ds)) = (picked, ds) { - crate::fieldvalues::insert(&mut app.dialogs.text, &field, &value, ds); + app.dialogs.values.accept(&mut app.dialogs.text, &field, &value, ds); } crate::fieldvalues::said(ui, &app.dialogs.values); // Live validation, once no suggestion is offered: a word still being chosen isn't an error yet. @@ -4452,7 +4452,9 @@ mod tests { h.get_by_role_and_label(Role::Button, "continent").click(); h.run(); assert!(h.query_by_label("Click a field, or put the cursor in one, to list its values").is_none(), "said no more"); - h.state_mut().dialogs.text.clear(); + // The button wrote the field into the box, and the box is not cleared: the value adds the + // comparison to it, not the field again. + assert_eq!(h.state().dialogs.text, "continent "); values(&mut h); h.run_steps(5); assert_eq!(h.state().dialogs.values.reads, 1); @@ -4499,6 +4501,107 @@ mod tests { assert_eq!((h.state().dialogs.open, h.state().dialogs.values.reads), (None, 0)); } + /// The value goes where the cursor was that the field came from, not at the end of the clause. + #[test] + fn select_by_attributes_values_list_fills_the_gap_at_the_cursor() { + use egui::accesskit::Role; + use egui::text::{CCursor, CCursorRange}; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("ui.dialog", json!({"name": "selectByAttributes"})).unwrap(); + app.dialogs.layer = "Countries".into(); + let mut h = app_harness(app); + h.run_steps(3); + let id = egui::Id::unique("sba_where"); + h.state_mut().dialogs.text = "continent = AND pop_est > 1".into(); + h.ctx.memory_mut(|m| m.request_focus(id)); + h.run(); + let mut state = egui::widgets::text_edit::TextEditState::load(&h.ctx, id).unwrap_or_default(); + state.cursor.set_char_range(Some(CCursorRange::one(CCursor::new(12)))); + state.store(&h.ctx, id); + h.run(); + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + h.get_by_role_and_label(Role::Button, "'Asia'").click(); + h.run(); + assert_eq!(h.state().dialogs.text, "continent = 'Asia' AND pop_est > 1", "the gap filled, the rest kept"); + } + + /// The list stays as it was read while it is open: rows that change under it (a streamed + /// layer's next view) don't change what Enter takes. Opened again, it reads the rows then. + #[test] + fn select_by_attributes_values_list_does_not_change_while_open() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + use rustgis_engine::data::Value; + let mut app = RustGisApp::with_sample(); + app.run("ui.dialog", json!({"name": "selectByAttributes"})).unwrap(); + app.dialogs.layer = "Countries".into(); + let mut h = app_harness(app); + h.run_steps(3); + let layer = |h: &egui_kittest::Harness<'static, RustGisApp>| { + h.state().session.map().layer_by_name("Countries").map(|l| (l.id, l.dataset.clone())) + }; + let (id, ds) = layer(&h).unwrap(); + let field = ds.fields.iter().position(|f| f.name == "continent").unwrap(); + let first = + rustgis_engine::data::query::field_values(&ds, field, rustgis_engine::data::query::VALUES_READ).values[0].written.clone(); + h.get_by_role_and_label(Role::Button, "continent").click(); + h.run(); + h.state_mut().dialogs.text.clear(); + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + assert_eq!(h.state().dialogs.values.reads, 1); + // A new value that sorts before the rest arrives while the list is open. + let mut attrs = vec![Value::Null; ds.fields.len()]; + attrs[field] = Value::Text("Aaa".into()); + h.state_mut().session.map_mut().layer_mut(id).unwrap().dataset.push(None, attrs); + h.run_steps(3); + assert!(h.query_by_role_and_label(Role::Button, "'Aaa'").is_none(), "the list is as it was opened"); + assert_eq!(h.state().dialogs.values.reads, 1, "not read again while open"); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(h.state().dialogs.text, format!("continent = {first} "), "Enter takes the value that was highlighted"); + // Opened again: the rows now. + h.state_mut().dialogs.text.clear(); + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + assert_eq!(h.state().dialogs.values.reads, 2); + assert!(h.query_by_role_and_label(Role::Button, "'Aaa'").is_some(), "read again on the next opening"); + } + + /// A value with a `%` or `_` after `LIKE` is not written, and the box says why. + #[test] + fn select_by_attributes_values_list_says_why_a_wildcard_value_is_not_added_after_like() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let features = ["a_b", "plain"] + .iter() + .map(|n| json!({"type": "Feature", "geometry": {"type": "Point", "coordinates": [0, 0]}, "properties": {"name": n}})); + let text = json!({"type": "FeatureCollection", "features": features.collect::>()}).to_string(); + let mut app = RustGisApp::new(Session::new(rustgis_engine::Project::default())); + app.run("layer.addDataText", json!({"fileName": "people.geojson", "text": text})).unwrap(); + app.run("ui.dialog", json!({"name": "selectByAttributes"})).unwrap(); + let mut h = app_harness(app); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "name").click(); + h.run(); + h.state_mut().dialogs.text = "name LIKE ".into(); + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + h.get_by_role_and_label(Role::Button, "'a_b'").click(); + h.run(); + assert_eq!(h.state().dialogs.text, "name LIKE ", "nothing written"); + assert!(h.query_by_label_contains("matches more than itself").is_some(), "and it says why"); + // Another value goes in, and the note goes. + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + h.get_by_role_and_label(Role::Button, "'plain'").click(); + h.run(); + assert_eq!(h.state().dialogs.text, "name LIKE 'plain' "); + assert!(h.query_by_label_contains("matches more than itself").is_none()); + } + /// A field typed in the box is the one listed, as one clicked is. #[test] fn select_by_attributes_values_list_follows_the_field_typed() { @@ -4562,6 +4665,10 @@ mod tests { assert!(h.query_by_label_contains("evenly spread").is_none() && h.query_by_label_contains("read for the view").is_none()); let id = h.state().session.map().layer_by_name(&h.state().dialogs.layer).map(|l| l.id).unwrap(); h.state_mut().session.map_mut().layer_mut(id).unwrap().dataset.windowed = true; + // The list stays as it was read while it is open; opened again, it says so. + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + h.get_by_role_and_label(Role::Button, "Values ▾").click(); h.run(); assert!(h.query_by_label("Values of the 3 features read for the view").is_some()); diff --git a/crates/ui-egui/src/exprcomplete.rs b/crates/ui-egui/src/exprcomplete.rs index b72d3e6592..e9314b14af 100644 --- a/crates/ui-egui/src/exprcomplete.rs +++ b/crates/ui-egui/src/exprcomplete.rs @@ -48,18 +48,37 @@ pub(crate) struct ValuesRead { read: usize, of: usize, /// A streamed layer's: its dataset holds the features read for the view. - view: bool, + pub(crate) view: bool, + /// How many of the features read have a value too long to list or of several lines. + pub(crate) left_out: usize, } impl ValuesRead { /// Where `got` was read from, in `ds`: a streamed layer's dataset holds the features read for /// the view (`Dataset::windowed`). pub(crate) fn of(got: &query::FieldValues, ds: &Dataset) -> Self { - Self { read: got.read, of: got.of, view: ds.windowed } + Self { read: got.read, of: got.of, view: ds.windowed, left_out: got.left_out } } - /// What the help says of where the values come from; None when they are all the layer's. + /// What the help says of where the values come from, and of values not listed; None when + /// they are all the layer's. fn note(self) -> Option { + let from = self.from(); + let left = (self.left_out > 0).then(|| self.left_out_note()); + match (from, left) { + (Some(from), Some(left)) => Some(format!("{from}\n{left}")), + (from, left) => from.or(left), + } + } + + /// That the values of `left_out` features aren't listed, and why. + pub(crate) fn left_out_note(self) -> String { + let n = self.left_out.to_string(); + crate::i18n::fmt("The values of {n} features aren't listed: longer than 100 characters, or of several lines", &[("n", &n)]) + } + + /// Where the values come from; None when they are all the layer's. + fn from(self) -> Option { let (read, of) = (self.read.to_string(), self.of.to_string()); let args = [("read", read.as_str()), ("of", of.as_str())]; match (self.view, self.read < self.of) { @@ -644,7 +663,7 @@ pub(crate) fn menu(ui: &mut Ui, label: impl Into, menu: Menu) } }; let describe = |i: usize| catalog.get(i).map(|(_, item)| spoken_item(item, None)); - let items = || catalog.iter().map(|(s, _)| s.clone()).collect(); + let items = || catalog.iter().map(|(s, _)| s.clone()).collect::>(); let (_, accepted) = crate::completion::menu(ui, label, items, |_| None, describe, true, help); find(&accepted?).map(|item| match item { Item::Function(f) if f.max > 0 => format!("{}(", f.name), @@ -661,7 +680,7 @@ pub(crate) fn values_menu( ui: &mut Ui, label: impl Into, field: &str, - values: impl FnOnce() -> (Vec, ValuesRead), + values: impl FnOnce() -> (std::rc::Rc<[String]>, ValuesRead), ) -> Option { // Given with the values, and wanted by the help drawn after them. let read = std::cell::Cell::new(None); @@ -953,15 +972,24 @@ mod tests { /// layer's view. #[test] fn a_values_help_says_what_they_were_read_from() { - let note = |read, of, view| ValuesRead { read, of, view }.note(); + let note = |read, of, view| ValuesRead { read, of, view, left_out: 0 }.note(); assert_eq!(note(4, 4, false), None); assert_eq!(note(10_000, 25_000, false).as_deref(), Some("Values of 10000 of 25000 features, evenly spread")); assert_eq!(note(40, 40, true).as_deref(), Some("Values of the 40 features read for the view")); assert_eq!(note(10_000, 30_000, true).as_deref(), Some("Values of 10000 of the 30000 features read for the view, evenly spread")); + // Values left out are said, with or without a sample. + let left = "The values of 3 features aren't listed: longer than 100 characters, or of several lines"; + assert_eq!(ValuesRead { read: 4, of: 4, view: false, left_out: 3 }.note().as_deref(), Some(left)); + assert_eq!( + ValuesRead { read: 10, of: 20, view: false, left_out: 3 }.note(), + Some(format!("Values of 10 of 20 features, evenly spread\n{left}")) + ); let mut streamed = places(); streamed.windowed = true; let offer = offer_at("name = '", 8, &streamed, false).unwrap(); - assert!(matches!(offer.of.first(), Some(Item::Value(_, field, ValuesRead { read: 5, of: 5, view: true })) if field == "name")); + assert!( + matches!(offer.of.first(), Some(Item::Value(_, field, ValuesRead { read: 5, of: 5, view: true, left_out: 0 })) if field == "name") + ); } fn catalog_harness(size: egui::Vec2) -> egui_kittest::Harness<'static, ()> { diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index 7d08714ae3..59a8c2f94b 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -5,13 +5,15 @@ //! The values are what the completion offers after `"field" = '` (`query::field_values`): read //! from an evenly spread sample of at most `query::VALUES_READ` features, a streamed layer's from //! the features in view. They are read once, when the list is opened for a field, and kept while -//! the dialog stays on that layer and field and the layer's rows don't change. +//! the dialog stays on that layer and field and the layer's rows don't change, and not read +//! again while the list stays open: it changes only as it opens. +use std::rc::Rc; use std::sync::Weak; use egui::Ui; use egui::widgets::text_edit::TextEditState; -use rustgis_engine::data::query::{self, Completion, FieldValues, Kw, Place}; +use rustgis_engine::data::query::{self, Completion, Kw, Place}; use rustgis_engine::data::{Dataset, Feature}; use crate::exprcomplete::{ValuesRead, field_ref, fields_key}; @@ -25,6 +27,11 @@ pub struct Form { /// The field last clicked, or the cursor was last in, as the layer names it. field: Option, read: Option, + /// Where the cursor was (a char index) when `field` came from it, and the text it was in: a + /// value picked goes there while the text is as it was. A field clicked has none. + cursor: Option<(usize, String)>, + /// The frame the list was last drawn in: drawn the frame before, it is still the one open. + drawn: Option, /// Why there is no list to show, for the dialog to say under the buttons. said: Option, /// How many times the values were read: once per list opened, not once per frame. @@ -38,9 +45,11 @@ pub struct Form { struct Read { rows: Weak>, fields: u64, - got: FieldValues, - /// What the list shows for each value: as the expression writes it. - written: Vec, + /// Which features they were read from, and how many have a value not listed. + from: ValuesRead, + /// What the list shows for each value: as the expression writes it. Shared with the list + /// each frame it is open, not copied. + written: Rc<[String]>, } impl Form { @@ -51,12 +60,15 @@ impl Form { self.layer = layer.to_string(); self.field = None; self.read = None; + self.cursor = None; self.said = None; } } - /// Lists `field` from now on. Another field drops the values read for the last. + /// Lists `field` from now on, as one clicked: a value picked is added at the end. Another + /// field drops the values read for the last. pub(crate) fn choose(&mut self, field: &str) { + self.cursor = None; if self.field.as_deref() != Some(field) { self.field = Some(field.to_string()); self.read = None; @@ -69,19 +81,34 @@ impl Form { /// chosen, as `query::complete_at` reads it. pub(crate) fn follow_box(&mut self, ui: &Ui, id: egui::Id, text: &str, ds: &Dataset) { let cursor = TextEditState::load(ui.ctx(), id).and_then(|s| s.cursor.char_range()).map(|r| r.primary.index.0); - let field = cursor.and_then(|at| query::complete_at(text, at, ds)).and_then(|c| c.field); - if let Some(field) = field.and_then(|i| ds.fields.get(i)) { - self.choose(&field.name); + let at = cursor.and_then(|at| Some((at, query::complete_at(text, at, ds)?.field?))); + let Some((at, field)) = at.and_then(|(at, i)| Some((at, ds.fields.get(i)?))) else { + // The cursor is not where a value goes: a value picked goes at the end. + self.cursor = None; + return; + }; + self.choose(&field.name); + // Where the field came from: a value picked goes there (a clause with a gap in it is + // filled, not added to). + if self.cursor.as_ref().is_none_or(|(was, held)| *was != at || held != text) { + self.cursor = Some((at, text.to_string())); } } - /// The values of field `field` of `ds`, as written, and where they were read from, read - /// unless they are held from the rows and fields `ds` has now. Says why there is nothing to - /// list when there is none. - fn list(&mut self, ds: &Dataset, field: usize) -> (Vec, ValuesRead) { - let (rows, fields) = (ds.features.allocation_key(), fields_key(ds)); - if !self.read.as_ref().is_some_and(|r| r.fields == fields && r.rows.ptr_eq(&rows)) { - self.read = None; + /// The values of field `field` of `ds`, as written, and where they were read from. Read as + /// the list opens, unless held from the rows and fields `ds` has now; then kept while it stays + /// open (`frame`: it was drawn in the frame before), however the rows change under it, so + /// what is highlighted and what a screen reader was told stay what Enter takes. Says why there + /// is nothing to list when there is none. + fn list(&mut self, ds: &Dataset, field: usize, frame: u64) -> (Rc<[String]>, ValuesRead) { + let open = self.drawn.is_some_and(|was| was + 1 >= frame); + self.drawn = Some(frame); + if !open { + let (rows, fields) = (ds.features.allocation_key(), fields_key(ds)); + let held = |r: &Read| r.fields == fields && r.rows.ptr_eq(&rows) && r.from.view == ds.windowed; + if !self.read.as_ref().is_some_and(held) { + self.read = None; + } } #[cfg(test)] let reads = &mut self.reads; @@ -91,12 +118,30 @@ impl Form { *reads += 1; } let got = query::field_values(ds, field, query::VALUES_READ); - let written = got.values.iter().map(|v| v.written.clone()).collect(); - Read { rows, fields, got, written } + let from = ValuesRead::of(&got, ds); + let written = got.values.into_iter().map(|v| v.written).collect(); + Read { rows: ds.features.allocation_key(), fields: fields_key(ds), from, written } }); let name = ds.fields.get(field).map(|f| f.name.as_str()).unwrap_or_default(); - self.said = read.written.is_empty().then(|| crate::i18n::fmt("{field} has no values to list", &[("field", &field_ref(name))])); - (read.written.clone(), ValuesRead::of(&read.got, ds)) + self.said = read.written.is_empty().then(|| { + let none = crate::i18n::fmt("{field} has no values to list", &[("field", &field_ref(name))]); + match read.from.left_out { + 0 => none, + _ => format!("{none}. {}", read.from.left_out_note()), + } + }); + (Rc::clone(&read.written), read.from) + } + + /// Adds the value picked to `text`: at the cursor the field came from while the text is as it + /// was then, else at the end. When it can't be added, the text stays as it is and the box + /// says why. + pub(crate) fn accept(&mut self, text: &mut String, field: &str, value: &str, ds: &Dataset) { + let at = self.cursor.as_ref().filter(|(_, held)| held == text).map(|(at, _)| *at); + self.said = insert(text, field, value, ds, at).err(); + if self.said.is_none() { + self.cursor = None; + } } } @@ -112,7 +157,8 @@ pub(crate) fn button(ui: &mut Ui, form: &mut Form, ds: Option<&Dataset>) -> Opti } return None; }; - let accepted = crate::exprcomplete::values_menu(ui, label, &name, || form.list(ds, field)); + let frame = ui.ctx().cumulative_frame_nr(); + let accepted = crate::exprcomplete::values_menu(ui, label, &name, || form.list(ds, field, frame)); accepted.map(|value| (name, value)) } @@ -123,40 +169,108 @@ pub(crate) fn said(ui: &mut Ui, form: &Form) { } } -/// Adds `value` (as the expression writes it) of `field` to the end of the clause `text`, where -/// `query::complete_at` says the clause stands at its end (`ds` has the fields): -/// - where a value compared with a field goes (`name = `, `pop >`, `name IN (`, `pop BETWEEN `), -/// only the value, which `BETWEEN` takes for both ends (`BETWEEN 10 AND 10`, to edit) and a -/// bracket left open (`IN (`) is closed after; +/// Adds `value` (as the expression writes it) of `field` to the clause `text`, at char `at` (the +/// cursor the field came from; the end without one), where `query::complete_at` says the clause +/// stands there (`ds` has the fields). What follows `at` is kept. +/// - where a value compared with something goes (`name = `, `pop >`, `upper(name) =`, `name IN (`, +/// `pop BETWEEN `), only the value, which `BETWEEN` takes for both ends (`BETWEEN 10 AND 10`, to +/// edit) and a bracket left open (`IN (`) is closed after; /// - after a bare `IN` (a list is next), the value as a list of one (`IN ('Asia')`); +/// - after the field itself, as its button writes it (`continent `), what goes after it +/// (`= 'Asia'`); /// - anywhere else, the comparison with the field (`"Pop Est" = 10`). /// -/// A text or a quoted name begun and left open (`name = 'As`) is replaced by what is added, as the -/// completion does; a clause that can't be read at all gets the comparison, and the box says why -/// it doesn't read. -pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset) { - let mut at = at_end(text, ds); - if let Some(open) = at.as_ref().filter(|c| c.place != Place::Code) { - let keep = text.char_indices().nth(open.word.start).map_or(text.len(), |(i, _)| i); - text.truncate(keep); - at = at_end(text, ds); - } - let put = match &at { - Some(c) if c.operand && c.field.is_some() => value.to_string(), +/// A text or a quoted name begun and left open (`name = 'As`) is replaced by what is added, to its +/// closing quote, as the completion does; a clause that can't be read at all gets the comparison, +/// and the box says why it doesn't read. +/// +/// Nothing is added, and the reason is returned, when the value has a `%` or `_` where a `LIKE` +/// pattern goes (it would match more than itself) or the clause would pass `query::MAX_LEN`. +pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, at: Option) -> Result<(), String> { + let split = at.and_then(|at| text.char_indices().nth(at)).map_or(text.len(), |(i, _)| i); + let (before, mut after) = text.split_at(split); + let mut head = before.to_string(); + let mut here = at_end(&head, ds); + if let Some(open) = here.as_ref().filter(|c| c.place != Place::Code) { + let keep = head.char_indices().nth(open.word.start).map_or(head.len(), |(i, _)| i); + // What is left of the text, up to its closing quote, goes with what was typed of it. + if let Some(quote) = head.get(keep..).unwrap_or_default().chars().next().filter(|q| matches!(q, '\'' | '"')) { + after = after_quote(after, quote); + } + head.truncate(keep); + here = at_end(&head, ds); + } + if here.as_ref().is_some_and(|c| c.pattern) && value.contains(['%', '_']) { + return Err(crate::i18n::fmt("{value} has a % or _, which matches more than itself after LIKE: use = for it", &[("value", value)])); + } + let put = match &here { + Some(c) if c.operand && c.compared => value.to_string(), Some(c) if !c.operand && c.symbols == ["("] => format!("({value})"), + Some(c) if !c.operand && c.symbols.contains(&"=") && ends_with_field(&head, field) => format!("= {value}"), _ => format!("{} = {value}", field_ref(field)), }; - crate::dialogs::add_word(text, &put); - // What the value left to finish (the end of the clause is where it was added). - let then = at_end(text, ds); - if then.as_ref().is_some_and(|c| !c.operand && c.keywords == [Kw::And]) { + crate::dialogs::add_word(&mut head, &put); + // What was after it, from its first word. + let after = after.trim_start(); + // What the value left to finish (the end of `head` is where it was added). + let then = at_end(&head, ds); + if then.as_ref().is_some_and(|c| !c.operand && c.keywords == [Kw::And]) && !starts_with_word(after, "and") { // `BETWEEN 10` needs `AND` and a second end. - crate::dialogs::add_word(text, &format!("AND {value}")); + crate::dialogs::add_word(&mut head, &format!("AND {value}")); + } + let join = |head: &str| match after.starts_with([')', ',']) { + true => format!("{}{after}", head.trim_end()), + false => format!("{head}{after}"), + }; + let mut done = join(&head); + // A bracket left open is closed, unless what follows it does. + if at_end(&head, ds).is_some_and(|c| c.symbols.contains(&")")) && (after.is_empty() || query::parse(&done, ds).is_err()) { + head.pop(); + head.push_str(") "); + done = join(&head); } - if at_end(text, ds).is_some_and(|c| c.symbols.contains(&")")) { - text.pop(); - text.push_str(") "); + if done.chars().count() > query::MAX_LEN { + return Err(crate::i18n::fmt( + "Not added: the clause would be longer than {max} characters", + &[("max", &query::MAX_LEN.to_string())], + )); } + *text = done; + Ok(()) +} + +/// What is left of `text` after the quoted text or name that began before it, up to its closing +/// quote (a doubled quote is a quote in it): none of it when the quote is never closed. +fn after_quote(text: &str, quote: char) -> &str { + let mut chars = text.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + if c == quote { + if chars.next_if(|&(_, next)| next == quote).is_some() { + continue; + } + return text.get(i + c.len_utf8()..).unwrap_or_default(); + } + } + "" +} + +/// Whether `text` starts with the word `word`, letter case aside (not a longer name that starts +/// with it). +fn starts_with_word(text: &str, word: &str) -> bool { + text.get(..word.len()).is_some_and(|start| start.eq_ignore_ascii_case(word)) + && !text.get(word.len()..).unwrap_or_default().starts_with(|c: char| c.is_alphanumeric() || c == '_') +} + +/// Whether `text` (trailing space aside) ends with `field` as its button writes it, and not as the +/// end of a longer name: what a click on the field's button leaves, to go on from. +fn ends_with_field(text: &str, field: &str) -> bool { + let (text, written) = (text.trim_end(), field_ref(field)); + let (n, len) = (written.chars().count(), text.chars().count()); + let Some(start) = len.checked_sub(n) else { return false }; + let at = text.char_indices().nth(start).map_or(text.len(), |(i, _)| i); + text.get(at..).is_some_and(|end| end.eq_ignore_ascii_case(&written)) + && (written.starts_with('"') + || !text.get(..at).unwrap_or_default().ends_with(|c: char| c.is_alphanumeric() || matches!(c, '_' | '@' | '$' | '.'))) } /// What may go at the end of `text`, where a value is added: read with a space after it, so a @@ -208,11 +322,21 @@ mod tests { ("(pop_est BETWEEN ", "pop_est", "10", "(pop_est BETWEEN 10 AND 10) "), // A text begun is replaced by the value. ("continent = 'As", "continent", "'Asia'", "continent = 'Asia' "), + // The field's button was clicked, then Values: the field is there, so only what + // follows it is added. + ("continent ", "continent", "'Asia'", "continent = 'Asia' "), + ("continent", "continent", "'Asia'", "continent = 'Asia' "), + ("pop_est > 1 AND continent ", "continent", "'Asia'", "pop_est > 1 AND continent = 'Asia' "), + ("CONTINENT ", "continent", "'Asia'", "CONTINENT = 'Asia' "), + // A computed left side has no field to repeat: only the value. + ("upper(name) = ", "name", "'PARIS'", "upper(name) = 'PARIS' "), + ("upper(name) LIKE ", "name", "'PARIS'", "upper(name) LIKE 'PARIS' "), + ("pop_est + 1 BETWEEN ", "pop_est", "10", "pop_est + 1 BETWEEN 10 AND 10 "), ]; let mut wrong = Vec::new(); for (clause, field, value, expected) in cases { let mut text = clause.to_string(); - insert(&mut text, field, value, &ds); + insert(&mut text, field, value, &ds, None).unwrap(); if text != expected { wrong.push(format!("`{clause}` + {value} wrote `{text}`, not `{expected}`")); } @@ -223,10 +347,109 @@ mod tests { assert!(wrong.is_empty(), "{}", wrong.join("\n")); // A clause that doesn't read at all gets the comparison, and the box says why. let mut text = "pop_est > 1 ) AND".to_string(); - insert(&mut text, "continent", "'Asia'", &ds); + insert(&mut text, "continent", "'Asia'", &ds, None).unwrap(); assert_eq!(text, "pop_est > 1 ) AND continent = 'Asia' "); } + /// With the cursor where the field came from, the value goes there and the text after it is + /// kept: a gap in the middle of a clause is filled, not the end of it added to. + #[test] + fn a_value_goes_at_the_cursor_the_field_came_from() { + let ds = countries(); + // (the text, the cursor in chars, the field listed, the value, what the text becomes) + let cases = [ + ("continent = AND pop_est > 1", 12, "continent", "'Asia'", "continent = 'Asia' AND pop_est > 1"), + ("continent IN ( AND pop_est > 1", 14, "continent", "'Asia'", "continent IN ('Asia') AND pop_est > 1"), + ("(continent = ) AND pop_est > 1", 13, "continent", "'Asia'", "(continent = 'Asia') AND pop_est > 1"), + ("continent IN (, 'Africa')", 14, "continent", "'Asia'", "continent IN ('Asia', 'Africa')"), + // `BETWEEN`'s upper end is already there. + ("pop_est BETWEEN AND 5", 16, "pop_est", "10", "pop_est BETWEEN 10 AND 5"), + // A text begun is replaced as far as its closing quote, not just up to the cursor. + ("continent = 'As' AND pop_est > 1", 15, "continent", "'Asia'", "continent = 'Asia' AND pop_est > 1"), + ("continent = 'Af' AND name = 'x'", 15, "continent", "'Asia'", "continent = 'Asia' AND name = 'x'"), + // The cursor at the end is the end; past it is the end too. + ("continent = ", 12, "continent", "'Asia'", "continent = 'Asia' "), + ("continent = ", 99, "continent", "'Asia'", "continent = 'Asia' "), + ]; + let mut wrong = Vec::new(); + for (clause, at, field, value, expected) in cases { + let mut text = clause.to_string(); + insert(&mut text, field, value, &ds, Some(at)).unwrap(); + if text != expected { + wrong.push(format!("`{clause}` at {at} + {value} wrote `{text}`, not `{expected}`")); + } + if let Err(e) = query::select(&text, &ds) { + wrong.push(format!("`{clause}` at {at} + {value} wrote `{text}`, which doesn't read: {e}")); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); + } + + /// The cursor remembered is the one the field came from, while the text is as it was: typed in + /// since, the cursor says nothing and the value goes at the end; a field clicked is the end. + #[test] + fn the_cursor_is_kept_only_while_the_text_is_as_it_was() { + let ds = countries(); + let text = "continent = AND pop_est > 1"; + let mut form = Form { cursor: Some((12, text.to_string())), ..Form::default() }; + let mut now = text.to_string(); + form.accept(&mut now, "continent", "'Asia'", &ds); + assert_eq!(now, "continent = 'Asia' AND pop_est > 1", "at the cursor"); + assert!(form.cursor.is_none(), "used"); + // Typed since: the cursor is not where it was. + form.cursor = Some((12, text.to_string())); + let mut typed = format!("{text} OR "); + form.accept(&mut typed, "continent", "'Asia'", &ds); + assert_eq!(typed, "continent = AND pop_est > 1 OR continent = 'Asia' ", "at the end"); + // A field clicked leaves the cursor behind. + form.cursor = Some((12, text.to_string())); + form.choose("name"); + assert!(form.cursor.is_none()); + } + + /// A value with a `%` or `_` after `LIKE` would match more than itself: nothing is written, and + /// it says why. Anywhere else such a value is written as any other. + #[test] + fn a_wildcard_value_is_not_written_after_like() { + let ds = countries(); + for (clause, value) in [("name LIKE ", "'a_b'"), ("name NOT LIKE ", "'100%'"), ("name ILIKE", "'x_'"), ("name LIKE 'a", "'a_b'")] { + let mut text = clause.to_string(); + let said = insert(&mut text, "name", value, &ds, None).expect_err(clause); + assert_eq!(text, clause, "the draft is left as it was"); + assert!(said.contains(value) && said.contains('%') && said.contains('='), "{said}"); + } + for (clause, value, expected) in [ + ("name = ", "'a_b'", "name = 'a_b' "), + ("name IN (", "'a_b'", "name IN ('a_b') "), + ("name LIKE ", "'abc'", "name LIKE 'abc' "), + ("", "'a_b'", "name = 'a_b' "), + ] { + let mut text = clause.to_string(); + insert(&mut text, "name", value, &ds, None).unwrap(); + assert_eq!(text, expected); + } + } + + /// An insertion that would take the draft past `query::MAX_LEN` leaves it as it is and says so; + /// one that reaches the limit exactly is written. + #[test] + fn a_value_that_would_pass_the_length_limit_is_not_written() { + let ds = countries(); + let fits = format!("{}continent = ", " ".repeat(query::MAX_LEN - 19)); + let mut text = fits.clone(); + insert(&mut text, "continent", "'Asia'", &ds, None).unwrap(); + assert_eq!(text.chars().count(), query::MAX_LEN); + assert!(text.ends_with("continent = 'Asia' ")); + let full = format!(" {fits}"); + let mut text = full.clone(); + let said = insert(&mut text, "continent", "'Asia'", &ds, None).expect_err("one char too many"); + assert_eq!(text, full, "left as it was"); + assert!(said.contains(&query::MAX_LEN.to_string()), "{said}"); + // The same with the cursor in the middle. + let mut text = format!("{full} AND x"); + assert!(insert(&mut text, "continent", "'Asia'", &ds, Some(full.chars().count())).is_err()); + } + /// The field a value typed at the cursor is compared with (what `follow_box` lists) is the /// one `complete_at` reads there, wherever in the clause; none outside a comparison. #[test] diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index f423057e7f..66c96435ae 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -278,13 +278,20 @@ Select By Attributes also has a **Values** menu beside the field buttons. It lis values of the field last clicked, or the one a value typed at the cursor would be compared with (`continent = ` lists `continent`), in the same list. Choosing a value adds what the clause takes there, so it still reads: the comparison (`continent = 'Asia'`, the field in double quotes when its -name needs them, a `'` in the value doubled) where none is open; only the value after `=`, `<>`, -`<`, `>`, `<=`, `>=`, `LIKE`, `ILIKE`, in a list (`IN ('Asia', 'Africa')`, closed for you) or after -`BETWEEN` (which takes the value for both ends, to edit); a list of one after `IN`; and in place -of a text begun and left open. The values are read as the suggestions' are, once when the list is -opened, and the help says when they come from a sample of the layer or, for a streamed layer, from -the features read for the view. A field with nothing to list (all null, true or false, or only -text too long) says so under the buttons. +name needs them, a `'` in the value doubled) where none is open, or what follows a field button +just clicked (`continent ` becomes `continent = 'Asia'`); only the value after `=`, `<>`, `<`, `>`, +`<=`, `>=`, `LIKE`, `ILIKE` (whatever is compared, `upper(name) = 'PARIS'` too), in a list +(`IN ('Asia', 'Africa')`, closed for you) or after `BETWEEN` (which takes the value for both ends, +to edit); a list of one after `IN`; and in place of a text begun and left open. When the field +came from the cursor, the value goes where the cursor was and the rest of the clause is kept +(`continent = ▮ AND pop_est > 1`). After `LIKE` a value with a `%` or `_` isn't added, as the +suggestions leave it out: it would match more than itself, and the box says to use `=`. Nor is +a value that would take the clause past its longest length. The values are read as the +suggestions' are, once when the list is opened and kept while it stays open, and the help says +when they come from a sample of the layer or, for a streamed layer, from the features read for the +view, and how many features have a value not listed (longer than 100 characters, or of several +lines). A field with nothing to list (all null, true or false, or only text too long) says so +under the buttons. They help too in the clause boxes of several lines: Select By Attributes' **Where**, the Layer Properties **Query** tab and a label class's SQL query. There the list shows under the cursor's From 7c3836d19be8b19aad42232219e34f7e7fe392a9 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 22:32:32 -0600 Subject: [PATCH 03/10] fix(ui): Values writes nothing beside a value already there, and closes every bracket left open - A value isn't written before one that follows the cursor, nor after a field a button wrote after an operator; the box says why. - Each bracket left open is closed, and none for an unfinished clause after it. - A computed left side lists no field, not the one chosen before. - A pick ends the list held, so a reopening reads the rows then. - Infinite and too-large numbers count as values left out; the note has a singular and takes its limit from VALUE_CHARS. --- crates/data/src/query.rs | 2 +- crates/data/src/query/complete.rs | 26 +++++-- crates/ui-egui/src/dialogs.rs | 28 +++++++ crates/ui-egui/src/exprcomplete.rs | 23 ++++-- crates/ui-egui/src/fieldvalues.rs | 116 +++++++++++++++++++++++++++-- 5 files changed, 178 insertions(+), 17 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index c0cbd23416..7ebf44294e 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -35,7 +35,7 @@ mod complete; #[cfg(test)] mod legacy; -pub use complete::{Call, Completion, FieldValue, FieldValues, Place, VALUES_READ, complete_at, field_values, literal}; +pub use complete::{Call, Completion, FieldValue, FieldValues, Place, VALUE_CHARS, VALUES_READ, complete_at, field_values, literal}; #[derive(Clone, Debug, PartialEq)] pub enum Expr { diff --git a/crates/data/src/query/complete.rs b/crates/data/src/query/complete.rs index 7d6e77b6a3..cbd65bbc2b 100644 --- a/crates/data/src/query/complete.rs +++ b/crates/data/src/query/complete.rs @@ -152,7 +152,7 @@ pub const VALUES_READ: usize = 10_000; /// The longest text [`field_values`] gives, in chars. A longer one is a description, not a /// value anyone compares with by typing it, and a list as wide as its widest item would run off /// the screen with it. -pub(crate) const VALUE_CHARS: usize = 100; +pub const VALUE_CHARS: usize = 100; /// A value of a field, from [`field_values`]: as an expression writes it ([`literal`]: `'O''Br'`, /// `3.25`), and as it reads (`O'Br`), what is typed inside its quotes. @@ -174,9 +174,10 @@ pub struct FieldValues { pub read: usize, /// How many features the dataset holds: more than `read` when a sample was read. pub of: usize, - /// How many of the features read have a value left out of `values` for its length (a text or - /// float written longer than [`VALUE_CHARS`]) or for breaking a line, for a list of `values` - /// to say it isn't all of them. + /// How many of the features read have a value left out of `values`: a text or float written + /// longer than [`VALUE_CHARS`], a text that breaks a line, an infinite float or a whole number + /// too large to write exactly ([`literal`]), for a list of `values` to say it isn't all of + /// them. Null and NaN are no value, and aren't counted. pub left_out: usize, } @@ -198,8 +199,14 @@ pub fn field_values(ds: &Dataset, field: usize, most: usize) -> FieldValues { continue; } let written = literal(v); - // A float is written in full (`1e300` as 301 digits): too long to list, as a text is. - if matches!(v, Value::Float(_)) && written.as_ref().is_some_and(|w| w.len() > VALUE_CHARS) { + let unlisted = match v { + // A float is written in full (`1e300` as 301 digits): too long to list, as a text is. + Value::Float(x) => x.is_infinite() || written.as_ref().is_some_and(|w| w.len() > VALUE_CHARS), + // 9e15 or more, which the lexer would read as a float. + Value::Int(_) => written.is_none(), + _ => false, + }; + if unlisted { left_out += 1; continue; } @@ -330,6 +337,13 @@ mod tests { // value to list, not one left out. assert_eq!(v.left_out, 2); assert_eq!(field_values(&d, 1, VALUES_READ).left_out, 2, "1e300 and -1e-300 in full"); + // A number too large to write exactly, and an infinite one, are left out and counted. + let mut big = Dataset::new("t", GeometryType::Point, vec![Field::new("n", FieldType::Double)]); + for n in [Value::Int(9_000_000_000_000_000), Value::Float(f64::INFINITY), Value::Float(f64::NEG_INFINITY), Value::Int(7)] { + big.push(None, vec![n]); + } + let got = field_values(&big, 0, VALUES_READ); + assert_eq!((got.left_out, got.values.len()), (3, 1)); let longest = "x".repeat(VALUE_CHARS); assert_eq!(written(0), ["'A'".to_string(), "'b'".to_string(), format!("'{longest}'")], "up to the longest text listed"); assert_eq!(v.values.first(), Some(&FieldValue { written: "'A'".into(), text: "A".into() })); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1364faf7bd..7f8be111f8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4527,6 +4527,34 @@ mod tests { assert_eq!(h.state().dialogs.text, "continent = 'Asia' AND pop_est > 1", "the gap filled, the rest kept"); } + /// Compared with something computed (`upper(name) = ▮`), there is no field to list: not the one + /// clicked before. + #[test] + fn select_by_attributes_values_list_lists_nothing_beside_a_computed_left_side() { + use egui::accesskit::Role; + use egui::text::{CCursor, CCursorRange}; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("ui.dialog", json!({"name": "selectByAttributes"})).unwrap(); + app.dialogs.layer = "Countries".into(); + let mut h = app_harness(app); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "continent").click(); + h.run(); + let id = egui::Id::unique("sba_where"); + h.state_mut().dialogs.text = "upper(name) = ".into(); + h.ctx.memory_mut(|m| m.request_focus(id)); + h.run(); + let mut state = egui::widgets::text_edit::TextEditState::load(&h.ctx, id).unwrap_or_default(); + state.cursor.set_char_range(Some(CCursorRange::one(CCursor::new(14)))); + state.store(&h.ctx, id); + h.run(); + h.get_by_role_and_label(Role::Button, "Values ▾").click(); + h.run(); + assert!(h.query_by_label("Click a field, or put the cursor in one, to list its values").is_some(), "no field chosen"); + assert!(h.query_by_role_and_label(Role::Button, "'Asia'").is_none(), "continent isn't listed"); + } + /// The list stays as it was read while it is open: rows that change under it (a streamed /// layer's next view) don't change what Enter takes. Opened again, it reads the rows then. #[test] diff --git a/crates/ui-egui/src/exprcomplete.rs b/crates/ui-egui/src/exprcomplete.rs index e9314b14af..f092fff1a4 100644 --- a/crates/ui-egui/src/exprcomplete.rs +++ b/crates/ui-egui/src/exprcomplete.rs @@ -63,7 +63,7 @@ impl ValuesRead { /// What the help says of where the values come from, and of values not listed; None when /// they are all the layer's. fn note(self) -> Option { - let from = self.from(); + let from = self.source(); let left = (self.left_out > 0).then(|| self.left_out_note()); match (from, left) { (Some(from), Some(left)) => Some(format!("{from}\n{left}")), @@ -73,12 +73,21 @@ impl ValuesRead { /// That the values of `left_out` features aren't listed, and why. pub(crate) fn left_out_note(self) -> String { - let n = self.left_out.to_string(); - crate::i18n::fmt("The values of {n} features aren't listed: longer than 100 characters, or of several lines", &[("n", &n)]) + let (n, max) = (self.left_out.to_string(), query::VALUE_CHARS.to_string()); + let args = [("n", n.as_str()), ("max", max.as_str())]; + match self.left_out { + 1 => { + crate::i18n::fmt("The value of 1 feature isn't listed: longer than {max} characters, of several lines or too large", &args) + } + _ => crate::i18n::fmt( + "The values of {n} features aren't listed: longer than {max} characters, of several lines or too large", + &args, + ), + } } /// Where the values come from; None when they are all the layer's. - fn from(self) -> Option { + fn source(self) -> Option { let (read, of) = (self.read.to_string(), self.of.to_string()); let args = [("read", read.as_str()), ("of", of.as_str())]; match (self.view, self.read < self.of) { @@ -978,7 +987,11 @@ mod tests { assert_eq!(note(40, 40, true).as_deref(), Some("Values of the 40 features read for the view")); assert_eq!(note(10_000, 30_000, true).as_deref(), Some("Values of 10000 of the 30000 features read for the view, evenly spread")); // Values left out are said, with or without a sample. - let left = "The values of 3 features aren't listed: longer than 100 characters, or of several lines"; + let left = "The values of 3 features aren't listed: longer than 100 characters, of several lines or too large"; + assert_eq!( + ValuesRead { read: 4, of: 4, view: false, left_out: 1 }.note().as_deref(), + Some("The value of 1 feature isn't listed: longer than 100 characters, of several lines or too large") + ); assert_eq!(ValuesRead { read: 4, of: 4, view: false, left_out: 3 }.note().as_deref(), Some(left)); assert_eq!( ValuesRead { read: 10, of: 20, view: false, left_out: 3 }.note(), diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index 59a8c2f94b..ac0ba7c34c 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -81,7 +81,16 @@ impl Form { /// chosen, as `query::complete_at` reads it. pub(crate) fn follow_box(&mut self, ui: &Ui, id: egui::Id, text: &str, ds: &Dataset) { let cursor = TextEditState::load(ui.ctx(), id).and_then(|s| s.cursor.char_range()).map(|r| r.primary.index.0); - let at = cursor.and_then(|at| Some((at, query::complete_at(text, at, ds)?.field?))); + let here = cursor.and_then(|at| Some((at, query::complete_at(text, at, ds)?))); + if here.as_ref().is_some_and(|(_, c)| c.compared && c.field.is_none()) { + // Compared with something computed (`upper(name) = ▮`): no field's values to list, + // not the one chosen before. + self.field = None; + self.read = None; + self.cursor = None; + return; + } + let at = here.and_then(|(at, c)| Some((at, c.field?))); let Some((at, field)) = at.and_then(|(at, i)| Some((at, ds.fields.get(i)?))) else { // The cursor is not where a value goes: a value picked goes at the end. self.cursor = None; @@ -138,6 +147,8 @@ impl Form { /// says why. pub(crate) fn accept(&mut self, text: &mut String, field: &str, value: &str, ds: &Dataset) { let at = self.cursor.as_ref().filter(|(_, held)| held == text).map(|(at, _)| *at); + // The list closed with the pick: opened again, even in the next frame, it is a new one. + self.drawn = None; self.said = insert(text, field, value, ds, at).err(); if self.said.is_none() { self.cursor = None; @@ -200,6 +211,16 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, head.truncate(keep); here = at_end(&head, ds); } + if starts_an_operand(after) { + return Err(tl!("Not added: a value follows the cursor already. Put the cursor where none is, or delete that one").to_string()); + } + if !here.as_ref().is_some_and(|c| c.operand || c.symbols.contains(&"=")) && ends_with_field(&head, field) { + // `pop_est > continent ▮`: the field is the value of a comparison already. + return Err(crate::i18n::fmt( + "Not added: {field} is already a value here. Type an operator after it, or put the cursor after one", + &[("field", &field_ref(field))], + )); + } if here.as_ref().is_some_and(|c| c.pattern) && value.contains(['%', '_']) { return Err(crate::i18n::fmt("{value} has a % or _, which matches more than itself after LIKE: use = for it", &[("value", value)])); } @@ -222,13 +243,18 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, true => format!("{}{after}", head.trim_end()), false => format!("{head}{after}"), }; - let mut done = join(&head); - // A bracket left open is closed, unless what follows it does. - if at_end(&head, ds).is_some_and(|c| c.symbols.contains(&")")) && (after.is_empty() || query::parse(&done, ds).is_err()) { + // Each bracket left open is closed, unless what follows the value closes it or goes on in it + // (`IN (▮, 'Africa')`); what follows doesn't otherwise count (an unfinished clause after it + // isn't a bracket left open). At most as many as were opened. + let opened = head.matches('(').count(); + for _ in 0..opened { + if after.starts_with([')', ',']) || !at_end(&head, ds).is_some_and(|c| c.symbols.contains(&")")) { + break; + } head.pop(); head.push_str(") "); - done = join(&head); } + let done = join(&head); if done.chars().count() > query::MAX_LEN { return Err(crate::i18n::fmt( "Not added: the clause would be longer than {max} characters", @@ -239,6 +265,22 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, Ok(()) } +/// Whether `text` (what follows the cursor a value goes at) starts with a value, which the value +/// added would stand beside (`= ▮'Africa'`): a text or quoted name, a number, a bracket, or a name +/// that isn't a word coming after a value (`AND`, `THEN`, `LIKE`…). +fn starts_an_operand(text: &str) -> bool { + let text = text.trim_start(); + let Some(first) = text.chars().next() else { return false }; + if matches!(first, '\'' | '"' | '(' | '@' | '$' | '.') || first.is_ascii_digit() { + return true; + } + if !(first.is_alphabetic() || first == '_') { + return false; + } + let after_a_value = [Kw::And, Kw::Or, Kw::Not, Kw::Is, Kw::Like, Kw::Ilike, Kw::In, Kw::Between, Kw::When, Kw::Then, Kw::Else, Kw::End]; + !after_a_value.iter().any(|k| starts_with_word(text, k.word())) +} + /// What is left of `text` after the quoted text or name that began before it, up to its closing /// quote (a doubled quote is a quote in it): none of it when the quote is never closed. fn after_quote(text: &str, quote: char) -> &str { @@ -385,6 +427,70 @@ mod tests { assert!(wrong.is_empty(), "{}", wrong.join("\n")); } + /// Brackets: each left open is closed, however many, but not one that what follows the value + /// closes, and not for an unfinished clause after it. + #[test] + fn every_bracket_left_open_is_closed_and_no_other() { + let ds = countries(); + let mut text = "((continent = ".to_string(); + insert(&mut text, "continent", "'Asia'", &ds, None).unwrap(); + assert_eq!(text, "((continent = 'Asia')) "); + assert!(query::select(&text, &ds).is_ok()); + // The list is closed; the comparison after it is unfinished, and stays so. + let mut text = "continent IN () AND pop_est > ".to_string(); + insert(&mut text, "continent", "'Asia'", &ds, Some(14)).unwrap(); + assert_eq!(text, "continent IN ('Asia') AND pop_est > "); + } + + /// What would stand beside a value or a field already there is not written: the draft stays, + /// and the box says why. + #[test] + fn a_value_is_not_written_beside_another() { + let ds = countries(); + // (the text, the cursor in chars, the field) + for (clause, at, field) in [ + ("continent = 'Africa' AND pop_est > 1", Some(12), "continent"), + ("continent = 'Africa'", Some(12), "continent"), + ("pop_est > 5", Some(10), "pop_est"), + ("continent = name", Some(12), "continent"), + // The field's button clicked after an operator: the field is the value already. + ("pop_est > continent ", None, "continent"), + ("name = continent", None, "continent"), + ] { + let mut text = clause.to_string(); + let said = insert(&mut text, field, "'Asia'", &ds, at).expect_err(clause); + assert_eq!(text, clause, "left as it was"); + assert!(said.starts_with("Not added"), "{said}"); + } + // Words that come after a value leave the gap open to fill. + for (clause, at) in [("continent = AND pop_est > 1", 12), ("continent = OR pop_est > 1", 12)] { + let mut text = clause.to_string(); + insert(&mut text, "continent", "'Asia'", &ds, Some(at)).unwrap(); + assert!(query::select(&text, &ds).is_ok(), "{text}"); + } + } + + /// The list is held while it stays open, but a pick closes it: opened again, even in the next + /// frame, it reads the rows as they are then. + #[test] + fn a_pick_ends_the_list_held() { + let ds = countries(); + let field = ds.fields.iter().position(|f| f.name == "continent").unwrap(); + // Rows of their own: one more feature. + let mut other = ds.clone(); + other.push(None, vec![rustgis_engine::data::Value::Null; ds.fields.len()]); + assert!(!other.features.allocation_key().ptr_eq(&ds.features.allocation_key())); + let mut form = Form::default(); + form.choose("continent"); + let _ = form.list(&ds, field, 1); + let _ = form.list(&other, field, 2); + assert_eq!(form.reads, 1, "held while open, whatever the rows"); + let mut text = String::new(); + form.accept(&mut text, "continent", "'Asia'", &ds); + let _ = form.list(&other, field, 3); + assert_eq!(form.reads, 2, "opened again in the next frame: read again"); + } + /// The cursor remembered is the one the field came from, while the text is as it was: typed in /// since, the cursor says nothing and the value goes at the end; a field clicked is the end. #[test] From 2bd41f5796418f85f7a17bfbb2ea25d07bee3e5b Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 07:55:32 -0600 Subject: [PATCH 04/10] fix(ui): Values closes only the brackets left open, compares inside a bracket, lists true and false, and writes nothing before a sign --- crates/data/src/query.rs | 23 +++++++++++- crates/data/src/query/complete.rs | 42 +++++++++++++-------- crates/ui-egui/src/fieldvalues.rs | 61 ++++++++++++++++++++++++++----- docs/user-guide/expressions.md | 8 ++-- 4 files changed, 105 insertions(+), 29 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 7ebf44294e..3948c451f3 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -823,6 +823,9 @@ struct Probe { pattern: bool, /// Whether the value at the end is compared, whatever the left side is (`upper(name) = ▮`). compared: bool, + /// Where the last compared value starts (a token), with `field` and `pattern` for it: a + /// bracket opened there compares the value just inside it too (`name = (▮`). + compared_from: Option<(usize, Option, bool)>, } /// How a token is written, for the symbols [`Probe`] notes. @@ -874,12 +877,29 @@ impl Parser<'_> { /// As [`note_compared`](Self::note_compared), the value a `LIKE` pattern when `pattern`. fn note_compared_as(&self, l: &Expr, pattern: bool) { let field = if let Expr::Field(f) = l { Some(*f) } else { None }; - self.note(self.pos, |p| { + self.note_compared_at(self.pos, field, pattern); + } + /// Notes that the value starting at token `i` is compared, with `field` when one. + fn note_compared_at(&self, i: usize, field: Option, pattern: bool) { + if let Some(probe) = &self.probe { + probe.borrow_mut().compared_from = Some((i, field, pattern)); + } + self.note(i, |p| { p.compared = true; p.field = field; p.pattern = pattern; }); } + /// Notes, for a bracket at token `open` where a compared value starts, that the value just + /// inside it is compared as well (`name = (▮`, `pop > ((▮`). + fn note_compared_within(&self, open: usize) { + let from = self.probe.as_ref().and_then(|p| p.borrow().compared_from); + if let Some((at, field, pattern)) = from + && at == open + { + self.note_compared_at(open + 1, field, pattern); + } + } fn probing(&self) -> bool { self.probe.is_some() } @@ -1257,6 +1277,7 @@ impl Parser<'_> { self.note(self.pos, |p| p.operand = true); match self.next() { Some(Tok::LParen) => { + self.note_compared_within(self.pos.saturating_sub(1)); let e = self.or()?; self.note(self.pos, |p| p.symbols.push(")")); if self.next() != Some(Tok::RParen) { diff --git a/crates/data/src/query/complete.rs b/crates/data/src/query/complete.rs index cbd65bbc2b..ff93544c7d 100644 --- a/crates/data/src/query/complete.rs +++ b/crates/data/src/query/complete.rs @@ -225,8 +225,8 @@ pub fn field_values(ds: &Dataset, field: usize, most: usize) -> FieldValues { /// `v` as an expression writes it, to compare a field with: a number as it is (in full, `3.25`, /// not rounded as a table shows it), a text, date or date-time in single quotes (a `'` in it -/// doubled, as the lexer reads it). None for what is no literal: null, true or false (keywords), -/// a number that isn't finite, and a whole number of 9e15 or more, which the lexer reads as a +/// doubled, as the lexer reads it), true or false as `TRUE` or `FALSE`. None for what is no +/// literal: null, a number that isn't finite, and a whole number of 9e15 or more, which the lexer reads as a /// float (`query::num`), so that it would pick no feature, or its neighbour's. pub fn literal(v: &Value) -> Option { match v { @@ -235,7 +235,8 @@ pub fn literal(v: &Value) -> Option { Value::Float(x) if x.is_finite() => Some(if *x == 0.0 { 0.0 } else { *x }.to_string()), Value::Text(t) => Some(format!("'{}'", t.replace('\'', "''"))), Value::Date(_) | Value::DateTime(_) => Some(format!("'{v}'")), - Value::Int(_) | Value::Float(_) | Value::Null | Value::Bool(_) => None, + Value::Bool(b) => Some(if *b { "TRUE" } else { "FALSE" }.to_string()), + Value::Int(_) | Value::Float(_) | Value::Null => None, } } @@ -265,27 +266,30 @@ mod tests { Field::new("r", FieldType::Double), Field::new("d", FieldType::Date), Field::new("s", FieldType::DateTime), + Field::new("b", FieldType::Boolean), ]; let mut d = Dataset::new("t", GeometryType::Point, fields); + // Each boolean is one feature's, so `b = …` picks only that one: the other rows' are null. let rows = [ - ("O'Brien", -5, 3.25, "2026-03-05", "2026-03-05T08:00:00Z"), - ("Pop Est", 7, 0.1 + 0.2, "1999-12-31", "2026-03-05T08:00:00+02:00"), - ("", 0, 1e-7, "2000-02-29", "2026-03-05T08:00:00.250"), - ("x", 8_999_999_999_999_999, 2.5, "2000-03-01", "2026-03-05T09:00:00Z"), - ("y", 8_999_999_999_999_998, 3.5, "2000-03-02", "2026-03-05T10:00:00Z"), + ("O'Brien", -5, 3.25, "2026-03-05", "2026-03-05T08:00:00Z", Value::Bool(true)), + ("Pop Est", 7, 0.1 + 0.2, "1999-12-31", "2026-03-05T08:00:00+02:00", Value::Bool(false)), + ("", 0, 1e-7, "2000-02-29", "2026-03-05T08:00:00.250", Value::Null), + ("x", 8_999_999_999_999_999, 2.5, "2000-03-01", "2026-03-05T09:00:00Z", Value::Null), + ("y", 8_999_999_999_999_998, 3.5, "2000-03-02", "2026-03-05T10:00:00Z", Value::Null), ]; - for (t, i, r, day, at) in rows { + for (t, i, r, day, at, b) in rows { let attrs = vec![ Value::Text(t.into()), Value::Int(i), Value::Float(r), Value::Date(Date::parse(day).unwrap()), Value::DateTime(DateTime::parse(at).unwrap()), + b, ]; d.push(None, attrs); } for (row, f) in d.features.clone().iter().enumerate() { - for (i, v) in f.attrs.iter().enumerate() { + for (i, v) in f.attrs.iter().enumerate().filter(|(_, v)| **v != Value::Null) { let written = literal(v).unwrap(); let name = &d.fields[i].name; assert_eq!(crate::query::select(&format!("{name} = {written}"), &d), Ok(vec![row]), "{name} = {written}"); @@ -296,9 +300,9 @@ mod tests { assert_eq!(literal(&Value::Float(-0.0)).as_deref(), Some("0")); assert_eq!(literal(&Value::Int(8_999_999_999_999_999)).as_deref(), Some("8999999999999999")); assert_eq!(literal(&Value::Int(-8_999_999_999_999_999)).as_deref(), Some("-8999999999999999")); + assert_eq!(literal(&Value::Bool(false)).as_deref(), Some("FALSE")); for v in [ Value::Null, - Value::Bool(true), Value::Float(f64::NAN), Value::Float(f64::INFINITY), Value::Int(9_000_000_000_000_000), @@ -309,9 +313,8 @@ mod tests { } } - /// A field's values: each once, in Unique Values' order, without what is no literal (null, - /// true, false, a text that breaks a line or too long to list); of a large layer, an evenly - /// spread sample. + /// A field's values: each once, in Unique Values' order, without what is no literal (null, a + /// text that breaks a line or too long to list); of a large layer, an evenly spread sample. #[test] fn a_fields_values_are_read_once_each_from_a_bounded_sample() { let fields = vec![Field::new("t", FieldType::Text), Field::new("n", FieldType::Double), Field::new("b", FieldType::Boolean)]; @@ -348,7 +351,8 @@ mod tests { assert_eq!(written(0), ["'A'".to_string(), "'b'".to_string(), format!("'{longest}'")], "up to the longest text listed"); assert_eq!(v.values.first(), Some(&FieldValue { written: "'A'".into(), text: "A".into() })); assert_eq!(written(1), ["-1.5", "9", "10"], "by number, `10` and `10.0` once, none written too long"); - assert!(field_values(&d, 2, VALUES_READ).values.is_empty(), "true and false are keywords"); + assert_eq!(written(2), ["TRUE"], "as the keyword, once"); + assert_eq!(field_values(&d, 2, VALUES_READ).left_out, 0); assert!(field_values(&d, 9, VALUES_READ).values.is_empty(), "no such field"); // Past the most read: every other feature, from the first. let mut big = Dataset::new("t", GeometryType::Point, vec![Field::new("i", FieldType::Integer)]); @@ -446,10 +450,16 @@ mod tests { "upper(name) LIKE '", "pop + 1 BETWEEN ", "pop * 2 IN (", + // A bracket where the value goes holds the value. + "name = (", + "pop > ((", + "name IN ((", ] { assert!(at_end(text).compared, "{text}"); } - for text in ["", "pop ", "pop > 5 ", "upper(", "name = 'a' AND ", "pop BETWEEN 1 "] { + assert_eq!(at_end("name = (").field, Some(0)); + // A bracket that starts a clause, or holds one, compares nothing. + for text in ["", "pop ", "pop > 5 ", "upper(", "name = 'a' AND ", "pop BETWEEN 1 ", "(", "pop > 5 AND (", "name = (pop > 1 AND "] { assert!(!at_end(text).compared, "{text}"); } } diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index ac0ba7c34c..b5fd306a44 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -243,12 +243,15 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, true => format!("{}{after}", head.trim_end()), false => format!("{head}{after}"), }; - // Each bracket left open is closed, unless what follows the value closes it or goes on in it - // (`IN (▮, 'Africa')`); what follows doesn't otherwise count (an unfinished clause after it - // isn't a bracket left open). At most as many as were opened. - let opened = head.matches('(').count(); - for _ in 0..opened { - if after.starts_with([')', ',']) || !at_end(&head, ds).is_some_and(|c| c.symbols.contains(&")")) { + // Each bracket left open is closed after the value, unless what follows closes it + // (`(continent = ▮ AND pop_est > 1)`) or the value goes on in it (`IN (▮, 'Africa')`); what + // follows doesn't otherwise count (an unfinished clause after it isn't a bracket left open). + let missing = match after.starts_with(',') { + true => 0, + false => brackets(&head).0.saturating_sub(brackets(after).1), + }; + for _ in 0..missing { + if !at_end(&head, ds).is_some_and(|c| c.symbols.contains(&")")) { break; } head.pop(); @@ -265,13 +268,35 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, Ok(()) } +/// The brackets `text` leaves open, and those it closes that it didn't open, outside its texts +/// and quoted names. +fn brackets(text: &str) -> (usize, usize) { + let (mut open, mut unopened, mut quote) = (0usize, 0usize, None); + for c in text.chars() { + match (quote, c) { + // A doubled quote in a text closes it and opens it again, which counts the same. + (Some(q), c) if c == q => quote = None, + (Some(_), _) => {} + (None, '\'' | '"') => quote = Some(c), + (None, '(') => open += 1, + (None, ')') => match open.checked_sub(1) { + Some(n) => open = n, + None => unopened += 1, + }, + _ => {} + } + } + (open, unopened) +} + /// Whether `text` (what follows the cursor a value goes at) starts with a value, which the value -/// added would stand beside (`= ▮'Africa'`): a text or quoted name, a number, a bracket, or a name -/// that isn't a word coming after a value (`AND`, `THEN`, `LIKE`…). +/// added would stand beside (`= ▮'Africa'`): a text or quoted name, a number or a sign (a value +/// before `-5` would subtract it), a bracket, or a name that isn't a word coming after a value +/// (`AND`, `THEN`, `LIKE`…). fn starts_an_operand(text: &str) -> bool { let text = text.trim_start(); let Some(first) = text.chars().next() else { return false }; - if matches!(first, '\'' | '"' | '(' | '@' | '$' | '.') || first.is_ascii_digit() { + if matches!(first, '\'' | '"' | '(' | '@' | '$' | '.' | '-' | '+') || first.is_ascii_digit() { return true; } if !(first.is_alphabetic() || first == '_') { @@ -355,6 +380,9 @@ mod tests { // In a list: the value, and the list closed. ("continent IN (", "continent", "'Asia'", "continent IN ('Asia') "), ("continent IN ('Asia',", "continent", "'Africa'", "continent IN ('Asia', 'Africa') "), + // In a bracket where the value goes: the value, and the bracket closed. + ("continent = (", "continent", "'Asia'", "continent = ('Asia') "), + ("pop_est > ((", "pop_est", "10", "pop_est > ((10)) "), // After a bare `IN` or `NOT IN`, a list is next. ("continent IN", "continent", "'Asia'", "continent IN ('Asia') "), ("continent not in ", "continent", "'Asia'", "continent not in ('Asia') "), @@ -440,6 +468,19 @@ mod tests { let mut text = "continent IN () AND pop_est > ".to_string(); insert(&mut text, "continent", "'Asia'", &ds, Some(14)).unwrap(); assert_eq!(text, "continent IN ('Asia') AND pop_est > "); + // What follows closes some of them, or all, later on: only the rest are closed. A bracket + // in a text isn't one. + for (clause, at, expected) in [ + ("((continent = )", 14, "((continent = 'Asia'))"), + ("(continent = AND pop_est > 1)", 13, "(continent = 'Asia' AND pop_est > 1)"), + ("((continent = AND pop_est > 1)", 14, "((continent = 'Asia') AND pop_est > 1)"), + ("((continent = AND name <> ')')", 14, "((continent = 'Asia') AND name <> ')')"), + ("(name <> '(' AND continent = ", 29, "(name <> '(' AND continent = 'Asia') "), + ] { + let mut text = clause.to_string(); + insert(&mut text, "continent", "'Asia'", &ds, Some(at)).unwrap(); + assert_eq!(text, expected, "{clause}"); + } } /// What would stand beside a value or a field already there is not written: the draft stays, @@ -453,6 +494,8 @@ mod tests { ("continent = 'Africa'", Some(12), "continent"), ("pop_est > 5", Some(10), "pop_est"), ("continent = name", Some(12), "continent"), + ("pop_est > -5", Some(10), "pop_est"), + ("pop_est > +5", Some(10), "pop_est"), // The field's button clicked after an operator: the field is the value already. ("pop_est > continent ", None, "continent"), ("name = continent", None, "continent"), diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 66c96435ae..96b23b552d 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -289,9 +289,11 @@ suggestions leave it out: it would match more than itself, and the box says to u a value that would take the clause past its longest length. The values are read as the suggestions' are, once when the list is opened and kept while it stays open, and the help says when they come from a sample of the layer or, for a streamed layer, from the features read for the -view, and how many features have a value not listed (longer than 100 characters, or of several -lines). A field with nothing to list (all null, true or false, or only text too long) says so -under the buttons. +view, and how many features have a value not listed (longer than 100 characters, of several +lines, or a number too large to write in full). True and false are listed as `TRUE` and `FALSE`, +and a value inside a bracket where one goes is the value alone (`continent = ('Asia')`), each +bracket left open closed after it. A field with nothing to list (all null, or only values not +listed) says so under the buttons. They help too in the clause boxes of several lines: Select By Attributes' **Where**, the Layer Properties **Query** tab and a label class's SQL query. There the list shows under the cursor's From 303f793e54155f26067f2057247ad7d83fef76bc Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 10:29:49 -0600 Subject: [PATCH 05/10] fix(ui): Values reads what follows the cursor with the lexer, and finishes BETWEEN after a bracket it closes --- crates/data/src/query.rs | 5 +- crates/data/src/query/complete.rs | 52 +++++++++++++++++++- crates/ui-egui/src/fieldvalues.rs | 79 ++++++++++--------------------- 3 files changed, 80 insertions(+), 56 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index 3948c451f3..e9d7417d65 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -35,7 +35,10 @@ mod complete; #[cfg(test)] mod legacy; -pub use complete::{Call, Completion, FieldValue, FieldValues, Place, VALUE_CHARS, VALUES_READ, complete_at, field_values, literal}; +pub use complete::{ + Call, Completion, FieldValue, FieldValues, Place, VALUE_CHARS, VALUES_READ, brackets, complete_at, field_values, literal, + starts_with_value, +}; #[derive(Clone, Debug, PartialEq)] pub enum Expr { diff --git a/crates/data/src/query/complete.rs b/crates/data/src/query/complete.rs index ff93544c7d..e3c1e92fdb 100644 --- a/crates/data/src/query/complete.rs +++ b/crates/data/src/query/complete.rs @@ -6,7 +6,7 @@ use std::cell::{OnceCell, RefCell}; use std::ops::Range; -use super::{FuncSpec, Kw, Lexed, Open, Parser, Probe, Tok, lex_spans}; +use super::{Arith, FuncSpec, Kw, Lexed, Open, Parser, Probe, Tok, lex_spans}; use crate::value::ClassText; use crate::{Dataset, Value}; @@ -142,6 +142,40 @@ pub fn complete_at(text: &str, cursor: usize, ds: &Dataset) -> Option Option<(usize, usize)> { + let (mut open, mut unopened) = (0usize, 0usize); + for t in lex_spans(text, true).ok()?.toks { + match t { + Tok::LParen => open += 1, + Tok::RParen => match open.checked_sub(1) { + Some(n) => open = n, + None => unopened += 1, + }, + _ => {} + } + } + Some((open, unopened)) +} + +/// Whether `text`, what follows a cursor where a value goes, starts with a value that a value +/// written there would stand beside (`= ▮'Africa'`, `▮!name!`): a text, a quoted name, a number, +/// a sign (a value before `-5` would subtract it), a bracket, a variable, or a name that isn't a +/// word coming after a value (`AND`, `THEN`, `LIKE`…). Its first word is read as the lexer reads +/// it, so `!=` is an operator; what can't be read is no value. +pub fn starts_with_value(text: &str) -> bool { + let first = lex_spans(text, true).ok().and_then(|l| l.toks.into_iter().next()); + let after_a_value = [Kw::And, Kw::Or, Kw::Not, Kw::Is, Kw::Like, Kw::Ilike, Kw::In, Kw::Between, Kw::When, Kw::Then, Kw::Else, Kw::End]; + match first { + Some(Tok::Str(_) | Tok::QuotedIdent(_) | Tok::Num(_) | Tok::Var(_) | Tok::LParen | Tok::Arith(Arith::Add | Arith::Sub)) => true, + Some(Tok::Ident(word)) => !after_a_value.iter().any(|k| k.word().eq_ignore_ascii_case(&word)), + _ => false, + } +} + /// The most features [`field_values`] reads of a layer. Where a value compared with a field is /// typed, its values are read again as the text changes, on the thread that draws, so a layer of /// millions mustn't be read whole each time (nor kept read: an edit, a reload or a view read would @@ -313,6 +347,22 @@ mod tests { } } + /// What follows a cursor is read as the lexer reads it: `!=` is an operator, `!a!` a name, and + /// a bracket in a text or quoted name is no bracket. + #[test] + fn what_follows_is_read_as_the_lexer_reads_it() { + for text in ["'a'", " !a b!", "\"a\"", "-5", "+5", "(1)", "@row_number", "name", "upper(name)"] { + assert!(starts_with_value(text), "{text}"); + } + for text in ["", " != 1", "<> 1", ") AND", ", 'b')", "AND pop > 1", "then 1", "|| 'x'", "* 2", "#"] { + assert!(!starts_with_value(text), "{text}"); + } + assert_eq!(brackets("((a = ')' AND \"b)\" = !c)! "), Some((2, 0))); + assert_eq!(brackets(" AND b = 1)) "), Some((0, 2))); + assert_eq!(brackets("(a = 'open ("), Some((1, 0))); + assert_eq!(brackets("#"), None); + } + /// A field's values: each once, in Unique Values' order, without what is no literal (null, a /// text that breaks a line or too long to list); of a large layer, an evenly spread sample. #[test] diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index b5fd306a44..a0cf59dd1b 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -211,7 +211,7 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, head.truncate(keep); here = at_end(&head, ds); } - if starts_an_operand(after) { + if query::starts_with_value(after) { return Err(tl!("Not added: a value follows the cursor already. Put the cursor where none is, or delete that one").to_string()); } if !here.as_ref().is_some_and(|c| c.operand || c.symbols.contains(&"=")) && ends_with_field(&head, field) { @@ -233,29 +233,34 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, crate::dialogs::add_word(&mut head, &put); // What was after it, from its first word. let after = after.trim_start(); - // What the value left to finish (the end of `head` is where it was added). - let then = at_end(&head, ds); - if then.as_ref().is_some_and(|c| !c.operand && c.keywords == [Kw::And]) && !starts_with_word(after, "and") { - // `BETWEEN 10` needs `AND` and a second end. - crate::dialogs::add_word(&mut head, &format!("AND {value}")); - } let join = |head: &str| match after.starts_with([')', ',']) { true => format!("{}{after}", head.trim_end()), false => format!("{head}{after}"), }; - // Each bracket left open is closed after the value, unless what follows closes it - // (`(continent = ▮ AND pop_est > 1)`) or the value goes on in it (`IN (▮, 'Africa')`); what - // follows doesn't otherwise count (an unfinished clause after it isn't a bracket left open). - let missing = match after.starts_with(',') { + // What the value left to finish (the end of `head` is where it was added), in the order the + // clause asks for it: `BETWEEN 10` needs `AND` and a second end, which `BETWEEN (10` needs once + // its bracket is closed. Each bracket left open is closed after the value, unless what follows + // closes it (`(continent = ▮ AND pop_est > 1)`) or the value goes on in it + // (`IN (▮, 'Africa')`); what follows doesn't otherwise count (an unfinished clause after it + // isn't a bracket left open). + let opened = |text: &str| query::brackets(text).unwrap_or_default(); + let mut missing = match after.starts_with(',') { true => 0, - false => brackets(&head).0.saturating_sub(brackets(after).1), + false => opened(&head).0.saturating_sub(opened(after).1), }; - for _ in 0..missing { - if !at_end(&head, ds).is_some_and(|c| c.symbols.contains(&")")) { + let mut second_end = !starts_with_word(after, "and"); + loop { + let then = at_end(&head, ds); + if second_end && then.as_ref().is_some_and(|c| !c.operand && c.keywords == [Kw::And]) { + crate::dialogs::add_word(&mut head, &format!("AND {value}")); + second_end = false; + } else if missing > 0 && then.is_some_and(|c| c.symbols.contains(&")")) { + head.pop(); + head.push_str(") "); + missing -= 1; + } else { break; } - head.pop(); - head.push_str(") "); } let done = join(&head); if done.chars().count() > query::MAX_LEN { @@ -268,44 +273,6 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, Ok(()) } -/// The brackets `text` leaves open, and those it closes that it didn't open, outside its texts -/// and quoted names. -fn brackets(text: &str) -> (usize, usize) { - let (mut open, mut unopened, mut quote) = (0usize, 0usize, None); - for c in text.chars() { - match (quote, c) { - // A doubled quote in a text closes it and opens it again, which counts the same. - (Some(q), c) if c == q => quote = None, - (Some(_), _) => {} - (None, '\'' | '"') => quote = Some(c), - (None, '(') => open += 1, - (None, ')') => match open.checked_sub(1) { - Some(n) => open = n, - None => unopened += 1, - }, - _ => {} - } - } - (open, unopened) -} - -/// Whether `text` (what follows the cursor a value goes at) starts with a value, which the value -/// added would stand beside (`= ▮'Africa'`): a text or quoted name, a number or a sign (a value -/// before `-5` would subtract it), a bracket, or a name that isn't a word coming after a value -/// (`AND`, `THEN`, `LIKE`…). -fn starts_an_operand(text: &str) -> bool { - let text = text.trim_start(); - let Some(first) = text.chars().next() else { return false }; - if matches!(first, '\'' | '"' | '(' | '@' | '$' | '.' | '-' | '+') || first.is_ascii_digit() { - return true; - } - if !(first.is_alphabetic() || first == '_') { - return false; - } - let after_a_value = [Kw::And, Kw::Or, Kw::Not, Kw::Is, Kw::Like, Kw::Ilike, Kw::In, Kw::Between, Kw::When, Kw::Then, Kw::Else, Kw::End]; - !after_a_value.iter().any(|k| starts_with_word(text, k.word())) -} - /// What is left of `text` after the quoted text or name that began before it, up to its closing /// quote (a doubled quote is a quote in it): none of it when the quote is never closed. fn after_quote(text: &str, quote: char) -> &str { @@ -390,6 +357,7 @@ mod tests { ("pop_est BETWEEN", "pop_est", "10", "pop_est BETWEEN 10 AND 10 "), ("pop_est BETWEEN 1 AND", "pop_est", "10", "pop_est BETWEEN 1 AND 10 "), ("(pop_est BETWEEN ", "pop_est", "10", "(pop_est BETWEEN 10 AND 10) "), + ("pop_est BETWEEN (", "pop_est", "10", "pop_est BETWEEN (10) AND 10 "), // A text begun is replaced by the value. ("continent = 'As", "continent", "'Asia'", "continent = 'Asia' "), // The field's button was clicked, then Values: the field is there, so only what @@ -476,6 +444,8 @@ mod tests { ("((continent = AND pop_est > 1)", 14, "((continent = 'Asia') AND pop_est > 1)"), ("((continent = AND name <> ')')", 14, "((continent = 'Asia') AND name <> ')')"), ("(name <> '(' AND continent = ", 29, "(name <> '(' AND continent = 'Asia') "), + ("(continent = AND !tag)! = 1", 13, "(continent = 'Asia') AND !tag)! = 1"), + ("(continent = AND \"a)\" = 1)", 13, "(continent = 'Asia' AND \"a)\" = 1)"), ] { let mut text = clause.to_string(); insert(&mut text, "continent", "'Asia'", &ds, Some(at)).unwrap(); @@ -496,6 +466,7 @@ mod tests { ("continent = name", Some(12), "continent"), ("pop_est > -5", Some(10), "pop_est"), ("pop_est > +5", Some(10), "pop_est"), + ("continent = !name!", Some(12), "continent"), // The field's button clicked after an operator: the field is the value already. ("pop_est > continent ", None, "continent"), ("name = continent", None, "continent"), From 9fb811f4c1e7df9a1edb1d97ad9e5d9c9873c213 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 12:17:30 -0600 Subject: [PATCH 06/10] fix(ui): Values joins a whole clause with AND, writes nothing before an operator or into a quote that holds the rest, and replaces a name begun in ! --- crates/data/src/query.rs | 4 +- crates/data/src/query/complete.rs | 82 ++++++++++++++++++++++++------- crates/ui-egui/src/fieldvalues.rs | 75 +++++++++++++++++++++++----- 3 files changed, 128 insertions(+), 33 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index e9d7417d65..c9c5691f53 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -36,8 +36,8 @@ mod complete; mod legacy; pub use complete::{ - Call, Completion, FieldValue, FieldValues, Place, VALUE_CHARS, VALUES_READ, brackets, complete_at, field_values, literal, - starts_with_value, + Call, Completion, FieldValue, FieldValues, Follows, Place, VALUE_CHARS, VALUES_READ, brackets, complete_at, field_values, follows, + literal, }; #[derive(Clone, Debug, PartialEq)] diff --git a/crates/data/src/query/complete.rs b/crates/data/src/query/complete.rs index e3c1e92fdb..d7b8cf34b9 100644 --- a/crates/data/src/query/complete.rs +++ b/crates/data/src/query/complete.rs @@ -161,18 +161,40 @@ pub fn brackets(text: &str) -> Option<(usize, usize)> { Some((open, unopened)) } -/// Whether `text`, what follows a cursor where a value goes, starts with a value that a value -/// written there would stand beside (`= ▮'Africa'`, `▮!name!`): a text, a quoted name, a number, -/// a sign (a value before `-5` would subtract it), a bracket, a variable, or a name that isn't a -/// word coming after a value (`AND`, `THEN`, `LIKE`…). Its first word is read as the lexer reads -/// it, so `!=` is an operator; what can't be read is no value. -pub fn starts_with_value(text: &str) -> bool { - let first = lex_spans(text, true).ok().and_then(|l| l.toks.into_iter().next()); - let after_a_value = [Kw::And, Kw::Or, Kw::Not, Kw::Is, Kw::Like, Kw::Ilike, Kw::In, Kw::Between, Kw::When, Kw::Then, Kw::Else, Kw::End]; - match first { - Some(Tok::Str(_) | Tok::QuotedIdent(_) | Tok::Num(_) | Tok::Var(_) | Tok::LParen | Tok::Arith(Arith::Add | Arith::Sub)) => true, - Some(Tok::Ident(word)) => !after_a_value.iter().any(|k| k.word().eq_ignore_ascii_case(&word)), - _ => false, +/// What `text`, what follows a cursor where a value goes, starts with, as [`follows`] reads it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Follows { + /// A value, which a value written there would stand beside (`= ▮'Africa'`, `▮!name!`): a + /// text or quoted name (finished or not), a number, a sign (a value before `-5` would + /// subtract it), a bracket, a variable, or a name that isn't a word coming after a value. + Value, + /// What takes the value before it as its left side: an operator (`▮= 'Old'`, `▮* 2`, `▮||`) + /// or `IS`, `NOT`, `LIKE`, `ILIKE`, `IN`, `BETWEEN`. + Operator, + /// Anything else: nothing, a closing bracket, a comma, `AND`, `OR`, a `CASE` word, or what + /// can't be read into words. + Other, +} + +/// What `text`, what follows a cursor where a value goes, starts with: its first word read as +/// the lexer reads it, so `!=` is an operator and `!a!` a name. +pub fn follows(text: &str) -> Follows { + let Some(Lexed { toks, open, .. }) = lex_spans(text, true).ok() else { return Follows::Other }; + let left_side = [Kw::Is, Kw::Not, Kw::Like, Kw::Ilike, Kw::In, Kw::Between]; + let joins = [Kw::And, Kw::Or, Kw::When, Kw::Then, Kw::Else, Kw::End]; + let is = |word: &str, kws: &[Kw]| kws.iter().any(|k| k.word().eq_ignore_ascii_case(word)); + match toks.into_iter().next() { + Some(Tok::Str(_) | Tok::QuotedIdent(_) | Tok::Num(_) | Tok::Var(_) | Tok::LParen | Tok::Arith(Arith::Add | Arith::Sub)) => { + Follows::Value + } + Some(Tok::Op(_) | Tok::Concat | Tok::Arith(_)) => Follows::Operator, + Some(Tok::Ident(word)) if is(&word, &left_side) => Follows::Operator, + Some(Tok::Ident(word)) if is(&word, &joins) => Follows::Other, + Some(Tok::Ident(_)) => Follows::Value, + Some(Tok::RParen | Tok::Comma) => Follows::Other, + // A text or name begun and never closed holds the rest. + None if open.is_some() => Follows::Value, + None => Follows::Other, } } @@ -347,15 +369,37 @@ mod tests { } } - /// What follows a cursor is read as the lexer reads it: `!=` is an operator, `!a!` a name, and - /// a bracket in a text or quoted name is no bracket. + /// What follows a cursor is read as the lexer reads it: `!=` is an operator, `!a!` a name, a + /// text never closed a value, and a bracket in a text or quoted name is no bracket. #[test] fn what_follows_is_read_as_the_lexer_reads_it() { - for text in ["'a'", " !a b!", "\"a\"", "-5", "+5", "(1)", "@row_number", "name", "upper(name)"] { - assert!(starts_with_value(text), "{text}"); - } - for text in ["", " != 1", "<> 1", ") AND", ", 'b')", "AND pop > 1", "then 1", "|| 'x'", "* 2", "#"] { - assert!(!starts_with_value(text), "{text}"); + for (text, then) in [ + ("'a'", Follows::Value), + (" !a b!", Follows::Value), + ("\"a\"", Follows::Value), + ("'Afr", Follows::Value), + ("!Af", Follows::Value), + ("-5", Follows::Value), + ("+5", Follows::Value), + ("(1)", Follows::Value), + ("@row_number", Follows::Value), + ("name", Follows::Value), + ("upper(name)", Follows::Value), + (" != 1", Follows::Operator), + ("<> 1", Follows::Operator), + ("= 'Old'", Follows::Operator), + ("|| 'x'", Follows::Operator), + ("* 2", Follows::Operator), + ("IN ('a')", Follows::Operator), + ("not like 'a%'", Follows::Operator), + ("", Follows::Other), + (") AND", Follows::Other), + (", 'b')", Follows::Other), + ("AND pop > 1", Follows::Other), + ("then 1", Follows::Other), + ("#", Follows::Other), + ] { + assert_eq!(follows(text), then, "{text}"); } assert_eq!(brackets("((a = ')' AND \"b)\" = !c)! "), Some((2, 0))); assert_eq!(brackets(" AND b = 1)) "), Some((0, 2))); diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index a0cf59dd1b..da97c1dd03 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -189,6 +189,8 @@ pub(crate) fn said(ui: &mut Ui, form: &Form) { /// - after a bare `IN` (a list is next), the value as a list of one (`IN ('Asia')`); /// - after the field itself, as its button writes it (`continent `), what goes after it /// (`= 'Asia'`); +/// - after the first end of a `BETWEEN` (`pop_est BETWEEN 1 `), `AND` and the value; +/// - after a whole clause (`pop_est > 1 `), the comparison joined to it with `AND`; /// - anywhere else, the comparison with the field (`"Pop Est" = 10`). /// /// A text or a quoted name begun and left open (`name = 'As`) is replaced by what is added, to its @@ -196,7 +198,9 @@ pub(crate) fn said(ui: &mut Ui, form: &Form) { /// and the box says why it doesn't read. /// /// Nothing is added, and the reason is returned, when the value has a `%` or `_` where a `LIKE` -/// pattern goes (it would match more than itself) or the clause would pass `query::MAX_LEN`. +/// pattern goes (it would match more than itself), a value follows the cursor already, an operator +/// follows it where more than the value would be added, a quote at the cursor is never closed and +/// holds the rest of the clause, or the clause would pass `query::MAX_LEN`. pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, at: Option) -> Result<(), String> { let split = at.and_then(|at| text.char_indices().nth(at)).map_or(text.len(), |(i, _)| i); let (before, mut after) = text.split_at(split); @@ -205,13 +209,24 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, if let Some(open) = here.as_ref().filter(|c| c.place != Place::Code) { let keep = head.char_indices().nth(open.word.start).map_or(head.len(), |(i, _)| i); // What is left of the text, up to its closing quote, goes with what was typed of it. - if let Some(quote) = head.get(keep..).unwrap_or_default().chars().next().filter(|q| matches!(q, '\'' | '"')) { - after = after_quote(after, quote); + if let Some(quote) = head.get(keep..).unwrap_or_default().chars().next().filter(|q| matches!(q, '\'' | '"' | '!')) { + after = match after_quote(after, quote) { + Some(rest) => rest, + None if after.trim().is_empty() => "", + // Never closed, it holds the rest of the clause, which would go with it. + None => { + return Err(tl!( + "Not added: the quote at the cursor is never closed, so the rest of the clause is in it. Close it first" + ) + .to_string()); + } + }; } head.truncate(keep); here = at_end(&head, ds); } - if query::starts_with_value(after) { + let next = query::follows(after); + if next == query::Follows::Value { return Err(tl!("Not added: a value follows the cursor already. Put the cursor where none is, or delete that one").to_string()); } if !here.as_ref().is_some_and(|c| c.operand || c.symbols.contains(&"=")) && ends_with_field(&head, field) { @@ -224,10 +239,21 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, if here.as_ref().is_some_and(|c| c.pattern) && value.contains(['%', '_']) { return Err(crate::i18n::fmt("{value} has a % or _, which matches more than itself after LIKE: use = for it", &[("value", value)])); } + let alone = here.as_ref().is_some_and(|c| c.operand && c.compared); + if !alone && next == query::Follows::Operator { + // `continent▮ = 'Old'`: what follows would compare what is added. + return Err(tl!("Not added: an operator follows the cursor. Put the cursor after it, where its value goes").to_string()); + } let put = match &here { - Some(c) if c.operand && c.compared => value.to_string(), + _ if alone => value.to_string(), Some(c) if !c.operand && c.symbols == ["("] => format!("({value})"), Some(c) if !c.operand && c.symbols.contains(&"=") && ends_with_field(&head, field) => format!("= {value}"), + // `pop_est BETWEEN 1 ▮`: the second end. + Some(c) if !c.operand && c.keywords == [Kw::And] => format!("AND {value}"), + // After a whole clause (`pop_est > 1 ▮`), the comparison joined to it. + Some(c) if !c.operand && c.keywords.contains(&Kw::Or) && !c.symbols.contains(&"=") => { + format!("AND {} = {value}", field_ref(field)) + } _ => format!("{} = {value}", field_ref(field)), }; crate::dialogs::add_word(&mut head, &put); @@ -274,18 +300,19 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, } /// What is left of `text` after the quoted text or name that began before it, up to its closing -/// quote (a doubled quote is a quote in it): none of it when the quote is never closed. -fn after_quote(text: &str, quote: char) -> &str { +/// quote (a doubled `'` or `"` is that quote in it; `!` has no such escape, as the lexer reads +/// it): `None` when the quote is never closed. +fn after_quote(text: &str, quote: char) -> Option<&str> { let mut chars = text.char_indices().peekable(); while let Some((i, c)) = chars.next() { if c == quote { - if chars.next_if(|&(_, next)| next == quote).is_some() { + if quote != '!' && chars.next_if(|&(_, next)| next == quote).is_some() { continue; } - return text.get(i + c.len_utf8()..).unwrap_or_default(); + return Some(text.get(i + c.len_utf8()..).unwrap_or_default()); } } - "" + None } /// Whether `text` starts with the word `word`, letter case aside (not a longer name that starts @@ -358,6 +385,10 @@ mod tests { ("pop_est BETWEEN 1 AND", "pop_est", "10", "pop_est BETWEEN 1 AND 10 "), ("(pop_est BETWEEN ", "pop_est", "10", "(pop_est BETWEEN 10 AND 10) "), ("pop_est BETWEEN (", "pop_est", "10", "pop_est BETWEEN (10) AND 10 "), + ("pop_est BETWEEN 1 ", "pop_est", "10", "pop_est BETWEEN 1 AND 10 "), + // After a whole clause, the comparison joined to it. + ("pop_est > 1 ", "continent", "'Asia'", "pop_est > 1 AND continent = 'Asia' "), + ("pop_est > 1", "continent", "'Asia'", "pop_est > 1 AND continent = 'Asia' "), // A text begun is replaced by the value. ("continent = 'As", "continent", "'Asia'", "continent = 'Asia' "), // The field's button was clicked, then Values: the field is there, so only what @@ -453,8 +484,22 @@ mod tests { } } - /// What would stand beside a value or a field already there is not written: the draft stays, - /// and the box says why. + /// A name begun in `!` at the cursor is replaced to its closing `!`, which has no doubling. + #[test] + fn a_name_begun_in_bangs_is_replaced_to_its_close() { + let ds = countries(); + for (clause, at, expected) in [ + ("continent = !Af!", 15, "continent = 'Asia' "), + ("continent = !Af! AND pop_est > 1", 15, "continent = 'Asia' AND pop_est > 1"), + ] { + let mut text = clause.to_string(); + insert(&mut text, "continent", "'Asia'", &ds, Some(at)).unwrap(); + assert_eq!(text, expected, "{clause}"); + } + } + + /// What would stand beside a value or a field already there, after an operator, or in a quote + /// that holds the rest is not written: the draft stays, and the box says why. #[test] fn a_value_is_not_written_beside_another() { let ds = countries(); @@ -467,6 +512,12 @@ mod tests { ("pop_est > -5", Some(10), "pop_est"), ("pop_est > +5", Some(10), "pop_est"), ("continent = !name!", Some(12), "continent"), + ("continent = 'Afr", Some(12), "continent"), + // An operator after the cursor, where more than the value would go. + ("continent = 'Old'", Some(9), "continent"), + ("continent IN ('Old')", Some(9), "continent"), + // A quote never closed holds the rest of the clause. + ("continent = 'As AND pop_est > 1", Some(15), "continent"), // The field's button clicked after an operator: the field is the value already. ("pop_est > continent ", None, "continent"), ("name = continent", None, "continent"), From 0efdbc91b65e3dc57c3ee0e6c04a9edae4b14f08 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 13:12:01 -0600 Subject: [PATCH 07/10] fix(ui): Values refuses a pick that would stop the clause reading, before a comparison, and before a value however the rest reads; joins a bracketed clause --- crates/data/src/query/complete.rs | 36 ++++++++++++++++++------------ crates/ui-egui/src/exprcomplete.rs | 20 ++++++++++------- crates/ui-egui/src/fieldvalues.rs | 30 ++++++++++++++++++++----- docs/user-guide/expressions.md | 4 ++-- 4 files changed, 61 insertions(+), 29 deletions(-) diff --git a/crates/data/src/query/complete.rs b/crates/data/src/query/complete.rs index d7b8cf34b9..abc729136e 100644 --- a/crates/data/src/query/complete.rs +++ b/crates/data/src/query/complete.rs @@ -166,20 +166,25 @@ pub fn brackets(text: &str) -> Option<(usize, usize)> { pub enum Follows { /// A value, which a value written there would stand beside (`= ▮'Africa'`, `▮!name!`): a /// text or quoted name (finished or not), a number, a sign (a value before `-5` would - /// subtract it), a bracket, a variable, or a name that isn't a word coming after a value. + /// subtract it), a bracket, a variable, a `CASE`, or a name that isn't a word coming after a + /// value. Value, - /// What takes the value before it as its left side: an operator (`▮= 'Old'`, `▮* 2`, `▮||`) - /// or `IS`, `NOT`, `LIKE`, `ILIKE`, `IN`, `BETWEEN`. + /// A comparison, which takes the value before it as its left side: a comparison operator + /// (`▮= 'Old'`, `▮!= 'Old'`) or `IS`, `NOT`, `LIKE`, `ILIKE`, `IN`, `BETWEEN`. + Comparison, + /// An operator that makes a value of the one before it (`▮* 2`, `▮|| 'x'`). Operator, - /// Anything else: nothing, a closing bracket, a comma, `AND`, `OR`, a `CASE` word, or what - /// can't be read into words. + /// Anything else: nothing, a closing bracket, a comma, `AND`, `OR`, `WHEN`, `THEN`, `ELSE`, + /// `END`, or what can't be read into words. Other, } /// What `text`, what follows a cursor where a value goes, starts with: its first word read as -/// the lexer reads it, so `!=` is an operator and `!a!` a name. +/// the lexer reads it, so `!=` is an operator and `!a!` a name. Where something later can't be +/// read (`'Africa' AND pop > #`), its first word alone is read. pub fn follows(text: &str) -> Follows { - let Some(Lexed { toks, open, .. }) = lex_spans(text, true).ok() else { return Follows::Other }; + let first_word = || text.split_whitespace().next().and_then(|w| lex_spans(w, true).ok()); + let Some(Lexed { toks, open, .. }) = lex_spans(text, true).ok().or_else(first_word) else { return Follows::Other }; let left_side = [Kw::Is, Kw::Not, Kw::Like, Kw::Ilike, Kw::In, Kw::Between]; let joins = [Kw::And, Kw::Or, Kw::When, Kw::Then, Kw::Else, Kw::End]; let is = |word: &str, kws: &[Kw]| kws.iter().any(|k| k.word().eq_ignore_ascii_case(word)); @@ -187,8 +192,9 @@ pub fn follows(text: &str) -> Follows { Some(Tok::Str(_) | Tok::QuotedIdent(_) | Tok::Num(_) | Tok::Var(_) | Tok::LParen | Tok::Arith(Arith::Add | Arith::Sub)) => { Follows::Value } - Some(Tok::Op(_) | Tok::Concat | Tok::Arith(_)) => Follows::Operator, - Some(Tok::Ident(word)) if is(&word, &left_side) => Follows::Operator, + Some(Tok::Op(_)) => Follows::Comparison, + Some(Tok::Concat | Tok::Arith(_)) => Follows::Operator, + Some(Tok::Ident(word)) if is(&word, &left_side) => Follows::Comparison, Some(Tok::Ident(word)) if is(&word, &joins) => Follows::Other, Some(Tok::Ident(_)) => Follows::Value, Some(Tok::RParen | Tok::Comma) => Follows::Other, @@ -385,13 +391,15 @@ mod tests { ("@row_number", Follows::Value), ("name", Follows::Value), ("upper(name)", Follows::Value), - (" != 1", Follows::Operator), - ("<> 1", Follows::Operator), - ("= 'Old'", Follows::Operator), + ("CASE WHEN 1 THEN 2 END", Follows::Value), + ("'Africa' AND pop > #", Follows::Value), + (" != 1", Follows::Comparison), + ("<> 1", Follows::Comparison), + ("= 'Old'", Follows::Comparison), + ("IN ('a')", Follows::Comparison), + ("not like 'a%'", Follows::Comparison), ("|| 'x'", Follows::Operator), ("* 2", Follows::Operator), - ("IN ('a')", Follows::Operator), - ("not like 'a%'", Follows::Operator), ("", Follows::Other), (") AND", Follows::Other), (", 'b')", Follows::Other), diff --git a/crates/ui-egui/src/exprcomplete.rs b/crates/ui-egui/src/exprcomplete.rs index f092fff1a4..7f241715e1 100644 --- a/crates/ui-egui/src/exprcomplete.rs +++ b/crates/ui-egui/src/exprcomplete.rs @@ -49,7 +49,8 @@ pub(crate) struct ValuesRead { of: usize, /// A streamed layer's: its dataset holds the features read for the view. pub(crate) view: bool, - /// How many of the features read have a value too long to list or of several lines. + /// How many of the features read have a value too long to list, with a control character, or too + /// large to write in full. pub(crate) left_out: usize, } @@ -66,7 +67,7 @@ impl ValuesRead { let from = self.source(); let left = (self.left_out > 0).then(|| self.left_out_note()); match (from, left) { - (Some(from), Some(left)) => Some(format!("{from}\n{left}")), + (Some(from), Some(left)) => Some(crate::i18n::fmt("{from}\n{left_out}", &[("from", &from), ("left_out", &left)])), (from, left) => from.or(left), } } @@ -76,11 +77,12 @@ impl ValuesRead { let (n, max) = (self.left_out.to_string(), query::VALUE_CHARS.to_string()); let args = [("n", n.as_str()), ("max", max.as_str())]; match self.left_out { - 1 => { - crate::i18n::fmt("The value of 1 feature isn't listed: longer than {max} characters, of several lines or too large", &args) - } + 1 => crate::i18n::fmt( + "The value of 1 feature isn't listed: longer than {max} characters, with a line break or other control character, or too large", + &args, + ), _ => crate::i18n::fmt( - "The values of {n} features aren't listed: longer than {max} characters, of several lines or too large", + "The values of {n} features aren't listed: longer than {max} characters, with a line break or other control character, or too large", &args, ), } @@ -987,10 +989,12 @@ mod tests { assert_eq!(note(40, 40, true).as_deref(), Some("Values of the 40 features read for the view")); assert_eq!(note(10_000, 30_000, true).as_deref(), Some("Values of 10000 of the 30000 features read for the view, evenly spread")); // Values left out are said, with or without a sample. - let left = "The values of 3 features aren't listed: longer than 100 characters, of several lines or too large"; + let left = "The values of 3 features aren't listed: longer than 100 characters, with a line break or other control character, or too large"; assert_eq!( ValuesRead { read: 4, of: 4, view: false, left_out: 1 }.note().as_deref(), - Some("The value of 1 feature isn't listed: longer than 100 characters, of several lines or too large") + Some( + "The value of 1 feature isn't listed: longer than 100 characters, with a line break or other control character, or too large" + ) ); assert_eq!(ValuesRead { read: 4, of: 4, view: false, left_out: 3 }.note().as_deref(), Some(left)); assert_eq!( diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index da97c1dd03..c0c96e9d02 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -136,7 +136,7 @@ impl Form { let none = crate::i18n::fmt("{field} has no values to list", &[("field", &field_ref(name))]); match read.from.left_out { 0 => none, - _ => format!("{none}. {}", read.from.left_out_note()), + _ => crate::i18n::fmt("{none}. {left_out}", &[("none", &none), ("left_out", &read.from.left_out_note())]), } }); (Rc::clone(&read.written), read.from) @@ -240,8 +240,9 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, return Err(crate::i18n::fmt("{value} has a % or _, which matches more than itself after LIKE: use = for it", &[("value", value)])); } let alone = here.as_ref().is_some_and(|c| c.operand && c.compared); - if !alone && next == query::Follows::Operator { - // `continent▮ = 'Old'`: what follows would compare what is added. + // `continent▮ = 'Old'`, `continent = ▮ != 'Old'`: what follows would compare what is added. + // A value alone may go before an operator that makes a value of it (`pop_est > ▮ * 2`). + if next == query::Follows::Comparison || (!alone && next == query::Follows::Operator) { return Err(tl!("Not added: an operator follows the cursor. Put the cursor after it, where its value goes").to_string()); } let put = match &here { @@ -250,8 +251,8 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, Some(c) if !c.operand && c.symbols.contains(&"=") && ends_with_field(&head, field) => format!("= {value}"), // `pop_est BETWEEN 1 ▮`: the second end. Some(c) if !c.operand && c.keywords == [Kw::And] => format!("AND {value}"), - // After a whole clause (`pop_est > 1 ▮`), the comparison joined to it. - Some(c) if !c.operand && c.keywords.contains(&Kw::Or) && !c.symbols.contains(&"=") => { + // After a whole clause (`pop_est > 1 ▮`, `(pop_est > 1) ▮`), the comparison joined to it. + Some(c) if !c.operand && c.keywords.contains(&Kw::Or) && query::parse_fields(&head, ds).is_ok_and(|e| is_condition(&e)) => { format!("AND {} = {value}", field_ref(field)) } _ => format!("{} = {value}", field_ref(field)), @@ -295,10 +296,23 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, &[("max", &query::MAX_LEN.to_string())], )); } + // What these rules miss: a clause that read as far as it went doesn't stop reading. + let reads = |text: &str| query::complete_at(text, text.chars().count(), ds).is_some(); + if reads(text) && !reads(&done) { + return Err(tl!("Not added: the clause wouldn't read with it there. Put the cursor where a value or a comparison goes").to_string()); + } *text = done; Ok(()) } +/// Whether `e` is a condition, true or false, which `AND` can join another to (`pop_est > 1`), +/// and not a value that a comparison could still follow (`upper(name)`, `pop_est + 1`). +fn is_condition(e: &query::Expr) -> bool { + use query::Expr as E; + !matches!(e, E::Field(_) | E::Lit(_) | E::Var(_) | E::Call(..) | E::Concat(_) | E::Chain(..) | E::Case { .. }) + || matches!(e, E::Lit(rustgis_engine::data::Value::Bool(_))) +} + /// What is left of `text` after the quoted text or name that began before it, up to its closing /// quote (a doubled `'` or `"` is that quote in it; `!` has no such escape, as the lexer reads /// it): `None` when the quote is never closed. @@ -389,6 +403,7 @@ mod tests { // After a whole clause, the comparison joined to it. ("pop_est > 1 ", "continent", "'Asia'", "pop_est > 1 AND continent = 'Asia' "), ("pop_est > 1", "continent", "'Asia'", "pop_est > 1 AND continent = 'Asia' "), + ("(pop_est > 1) ", "continent", "'Asia'", "(pop_est > 1) AND continent = 'Asia' "), // A text begun is replaced by the value. ("continent = 'As", "continent", "'Asia'", "continent = 'Asia' "), // The field's button was clicked, then Values: the field is there, so only what @@ -516,6 +531,11 @@ mod tests { // An operator after the cursor, where more than the value would go. ("continent = 'Old'", Some(9), "continent"), ("continent IN ('Old')", Some(9), "continent"), + ("continent = != 'Old'", Some(12), "continent"), + // A value after the cursor, though something later doesn't read. + ("continent = 'Africa' AND pop_est > #", Some(12), "continent"), + // Nothing above refuses it, but the clause would stop reading there. + ("(pop_est > 1", None, "continent"), // A quote never closed holds the rest of the clause. ("continent = 'As AND pop_est > 1", Some(15), "continent"), // The field's button clicked after an operator: the field is the value already. diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 96b23b552d..ce69221c90 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -289,8 +289,8 @@ suggestions leave it out: it would match more than itself, and the box says to u a value that would take the clause past its longest length. The values are read as the suggestions' are, once when the list is opened and kept while it stays open, and the help says when they come from a sample of the layer or, for a streamed layer, from the features read for the -view, and how many features have a value not listed (longer than 100 characters, of several -lines, or a number too large to write in full). True and false are listed as `TRUE` and `FALSE`, +view, and how many features have a value not listed (longer than 100 characters, with a +line break or other control character, or a number too large to write in full). True and false are listed as `TRUE` and `FALSE`, and a value inside a bracket where one goes is the value alone (`continent = ('Asia')`), each bracket left open closed after it. A field with nothing to list (all null, or only values not listed) says so under the buttons. From 96d29de89a03c22acc30d744297ffc1f6c0c218c Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 13:49:35 -0600 Subject: [PATCH 08/10] fix(ui): Values reads only the first word after the cursor, and puts its notes in display form once --- crates/data/src/query.rs | 10 +++++++++- crates/data/src/query/complete.rs | 11 ++++++----- crates/ui-egui/src/exprcomplete.rs | 29 ++++++++++++++++------------- crates/ui-egui/src/fieldvalues.rs | 22 ++++++++++++++++++++-- crates/ui-egui/src/i18n/mod.rs | 7 +++++++ 5 files changed, 58 insertions(+), 21 deletions(-) diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index c9c5691f53..982d4e0e9e 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -652,6 +652,12 @@ struct Lexed { /// `@` or `$` that is the last character, ends it instead of being an error. Anything else that /// can't be read is an error either way. fn lex_spans(s: &str, tolerant: bool) -> Result { + lex_first(s, tolerant, usize::MAX) +} + +/// As [`lex_spans`], reading no more than the first `most` tokens: what comes after them, which +/// may not read (`'a'#`), isn't looked at. +fn lex_first(s: &str, tolerant: bool, most: usize) -> Result { if s.chars().count() > MAX_LEN { return Err("the expression is too long".into()); } @@ -667,7 +673,9 @@ fn lex_spans(s: &str, tolerant: bool) -> Result { } cs.get(st..*i).map(|s| s.iter().collect()).unwrap_or_default() }; - while let Some(&c) = cs.get(i) { + while let Some(&c) = cs.get(i) + && out.len() < most + { let start = i; let before = out.len(); match c { diff --git a/crates/data/src/query/complete.rs b/crates/data/src/query/complete.rs index abc729136e..0787ff009e 100644 --- a/crates/data/src/query/complete.rs +++ b/crates/data/src/query/complete.rs @@ -6,7 +6,7 @@ use std::cell::{OnceCell, RefCell}; use std::ops::Range; -use super::{Arith, FuncSpec, Kw, Lexed, Open, Parser, Probe, Tok, lex_spans}; +use super::{Arith, FuncSpec, Kw, Lexed, Open, Parser, Probe, Tok, lex_first, lex_spans}; use crate::value::ClassText; use crate::{Dataset, Value}; @@ -180,11 +180,10 @@ pub enum Follows { } /// What `text`, what follows a cursor where a value goes, starts with: its first word read as -/// the lexer reads it, so `!=` is an operator and `!a!` a name. Where something later can't be -/// read (`'Africa' AND pop > #`), its first word alone is read. +/// the lexer reads it, so `!=` is an operator and `!a!` a name. Only that word is read, so what +/// comes after it needn't read (`'Africa'#`). pub fn follows(text: &str) -> Follows { - let first_word = || text.split_whitespace().next().and_then(|w| lex_spans(w, true).ok()); - let Some(Lexed { toks, open, .. }) = lex_spans(text, true).ok().or_else(first_word) else { return Follows::Other }; + let Some(Lexed { toks, open, .. }) = lex_first(text, true, 1).ok() else { return Follows::Other }; let left_side = [Kw::Is, Kw::Not, Kw::Like, Kw::Ilike, Kw::In, Kw::Between]; let joins = [Kw::And, Kw::Or, Kw::When, Kw::Then, Kw::Else, Kw::End]; let is = |word: &str, kws: &[Kw]| kws.iter().any(|k| k.word().eq_ignore_ascii_case(word)); @@ -393,6 +392,8 @@ mod tests { ("upper(name)", Follows::Value), ("CASE WHEN 1 THEN 2 END", Follows::Value), ("'Africa' AND pop > #", Follows::Value), + ("'Africa'#", Follows::Value), + ("!=#", Follows::Comparison), (" != 1", Follows::Comparison), ("<> 1", Follows::Comparison), ("= 'Old'", Follows::Comparison), diff --git a/crates/ui-egui/src/exprcomplete.rs b/crates/ui-egui/src/exprcomplete.rs index 7f241715e1..802407672e 100644 --- a/crates/ui-egui/src/exprcomplete.rs +++ b/crates/ui-egui/src/exprcomplete.rs @@ -61,42 +61,45 @@ impl ValuesRead { Self { read: got.read, of: got.of, view: ds.windowed, left_out: got.left_out } } - /// What the help says of where the values come from, and of values not listed; None when - /// they are all the layer's. + /// What the help says of where the values come from, and of values not listed, in display + /// form (put in it once, as a whole); None when they are all the layer's. fn note(self) -> Option { let from = self.source(); let left = (self.left_out > 0).then(|| self.left_out_note()); - match (from, left) { - (Some(from), Some(left)) => Some(crate::i18n::fmt("{from}\n{left_out}", &[("from", &from), ("left_out", &left)])), - (from, left) => from.or(left), - } + let note = match (from, left) { + (Some(from), Some(left)) => crate::i18n::fmt_raw("{from}\n{left_out}", &[("from", &from), ("left_out", &left)]), + (from, left) => from.or(left)?, + }; + Some(crate::i18n::display(¬e)) } - /// That the values of `left_out` features aren't listed, and why. + /// That the values of `left_out` features aren't listed, and why, in logical order: a part + /// of a message, which [`i18n::fmt`](crate::i18n::fmt) puts in display form as a whole. pub(crate) fn left_out_note(self) -> String { let (n, max) = (self.left_out.to_string(), query::VALUE_CHARS.to_string()); let args = [("n", n.as_str()), ("max", max.as_str())]; match self.left_out { - 1 => crate::i18n::fmt( + 1 => crate::i18n::fmt_raw( "The value of 1 feature isn't listed: longer than {max} characters, with a line break or other control character, or too large", &args, ), - _ => crate::i18n::fmt( + _ => crate::i18n::fmt_raw( "The values of {n} features aren't listed: longer than {max} characters, with a line break or other control character, or too large", &args, ), } } - /// Where the values come from; None when they are all the layer's. + /// Where the values come from, in logical order as [`left_out_note`](Self::left_out_note); + /// None when they are all the layer's. fn source(self) -> Option { let (read, of) = (self.read.to_string(), self.of.to_string()); let args = [("read", read.as_str()), ("of", of.as_str())]; match (self.view, self.read < self.of) { (false, false) => None, - (false, true) => Some(crate::i18n::fmt("Values of {read} of {of} features, evenly spread", &args)), - (true, false) => Some(crate::i18n::fmt("Values of the {of} features read for the view", &args)), - (true, true) => Some(crate::i18n::fmt("Values of {read} of the {of} features read for the view, evenly spread", &args)), + (false, true) => Some(crate::i18n::fmt_raw("Values of {read} of {of} features, evenly spread", &args)), + (true, false) => Some(crate::i18n::fmt_raw("Values of the {of} features read for the view", &args)), + (true, true) => Some(crate::i18n::fmt_raw("Values of {read} of the {of} features read for the view, evenly spread", &args)), } } } diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index c0c96e9d02..4967af756d 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -133,9 +133,11 @@ impl Form { }); let name = ds.fields.get(field).map(|f| f.name.as_str()).unwrap_or_default(); self.said = read.written.is_empty().then(|| { - let none = crate::i18n::fmt("{field} has no values to list", &[("field", &field_ref(name))]); + // The parts in logical order, and the whole put in display form once. + let field = field_ref(name); + let none = crate::i18n::fmt_raw("{field} has no values to list", &[("field", &field)]); match read.from.left_out { - 0 => none, + 0 => crate::i18n::display(&none), _ => crate::i18n::fmt("{none}. {left_out}", &[("none", &none), ("left_out", &read.from.left_out_note())]), } }); @@ -499,6 +501,21 @@ mod tests { } } + /// The note under the buttons is put in display form once, as a whole: a field named in + /// right-to-left letters starts the line, which then reads as `i18n::fmt` writes it, its + /// Latin runs (and the limit, `100`) reversed once, not twice. + #[test] + fn the_note_of_values_not_listed_is_put_in_display_form_once() { + use rustgis_engine::data::{Field, FieldType, GeometryType, Value}; + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("نام", FieldType::Text)]); + ds.push(None, vec![Value::Text("x".repeat(query::VALUE_CHARS + 1))]); + let mut form = Form::default(); + form.list(&ds, 0, 1); + let logical = "نام has no values to list. The value of 1 feature isn't listed: longer than 100 characters, with a line break or other control character, or too large"; + assert_eq!(form.said.as_deref(), Some(crate::i18n::display(logical).as_str())); + assert_ne!(crate::i18n::display(logical), logical, "the line is laid out back to front"); + } + /// A name begun in `!` at the cursor is replaced to its closing `!`, which has no doubling. #[test] fn a_name_begun_in_bangs_is_replaced_to_its_close() { @@ -534,6 +551,7 @@ mod tests { ("continent = != 'Old'", Some(12), "continent"), // A value after the cursor, though something later doesn't read. ("continent = 'Africa' AND pop_est > #", Some(12), "continent"), + ("continent = 'Africa'#", Some(12), "continent"), // Nothing above refuses it, but the clause would stop reading there. ("(pop_est > 1", None, "continent"), // A quote never closed holds the rest of the clause. diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 11b4d2b6f9..2372491ece 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -528,6 +528,13 @@ pub fn note_raw(n: &rustgis_assistant::provider::Note) -> String { fmt_raw(n.template, &args) } +/// `logical`, a message made in logical order (of parts from [`fmt_raw`] and [`t_raw`]), in +/// display form, as [`fmt`] gives its message: for a message put together from parts, which +/// is put in display form once, as a whole. +pub(crate) fn display(logical: &str) -> String { + rtl::visual(logical) +} + /// [`fmt`] in logical order, without the display form: for a message shown with /// [`paragraph`], which fits a right-to-left message to its rows and puts each row in /// display form itself. From 1c238b6258a30eb52758f583a1542595880e5c3b Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 14:25:09 -0600 Subject: [PATCH 09/10] fix(ui): Values finishes nothing before an operator that goes on with the value --- crates/ui-egui/src/fieldvalues.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index 4967af756d..ec0c147912 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -273,11 +273,14 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, // (`IN (▮, 'Africa')`); what follows doesn't otherwise count (an unfinished clause after it // isn't a bracket left open). let opened = |text: &str| query::brackets(text).unwrap_or_default(); - let mut missing = match after.starts_with(',') { + // Before an operator that goes on with it (`BETWEEN ▮ * 2`, `IN (▮ * 2`), the value isn't + // finished, so nothing is added after it. + let goes_on = next == query::Follows::Operator; + let mut missing = match after.starts_with(',') || goes_on { true => 0, false => opened(&head).0.saturating_sub(opened(after).1), }; - let mut second_end = !starts_with_word(after, "and"); + let mut second_end = !goes_on && !starts_with_word(after, "and"); loop { let then = at_end(&head, ds); if second_end && then.as_ref().is_some_and(|c| !c.operand && c.keywords == [Kw::And]) { @@ -499,6 +502,14 @@ mod tests { insert(&mut text, "continent", "'Asia'", &ds, Some(at)).unwrap(); assert_eq!(text, expected, "{clause}"); } + // What follows goes on with the value (`* 2`): nothing is finished before it. + for (clause, at, expected) in + [("pop_est BETWEEN * 2 AND 50", 16, "pop_est BETWEEN 10 * 2 AND 50"), ("pop_est IN ( * 2", 12, "pop_est IN (10 * 2")] + { + let mut text = clause.to_string(); + insert(&mut text, "pop_est", "10", &ds, Some(at)).unwrap(); + assert_eq!(text, expected, "{clause}"); + } } /// The note under the buttons is put in display form once, as a whole: a field named in From 37da1eba4ac3ece41aff20387a36bec47df8155e Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 15:04:11 -0600 Subject: [PATCH 10/10] fix(ui): Values adds no bracket where what follows can't be read --- crates/ui-egui/src/fieldvalues.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/fieldvalues.rs b/crates/ui-egui/src/fieldvalues.rs index ec0c147912..40c1405089 100644 --- a/crates/ui-egui/src/fieldvalues.rs +++ b/crates/ui-egui/src/fieldvalues.rs @@ -278,7 +278,8 @@ pub(crate) fn insert(text: &mut String, field: &str, value: &str, ds: &Dataset, let goes_on = next == query::Follows::Operator; let mut missing = match after.starts_with(',') || goes_on { true => 0, - false => opened(&head).0.saturating_sub(opened(after).1), + // What follows that can't be read is kept as it is, its brackets not guessed at. + false => query::brackets(after).map_or(0, |(_, closed)| opened(&head).0.saturating_sub(closed)), }; let mut second_end = !goes_on && !starts_with_word(after, "and"); loop { @@ -510,6 +511,10 @@ mod tests { insert(&mut text, "pop_est", "10", &ds, Some(at)).unwrap(); assert_eq!(text, expected, "{clause}"); } + // What follows doesn't read (`#`): its bracket is kept, and none added. + let mut text = "(continent = ) AND name = 'x' #".to_string(); + insert(&mut text, "continent", "'Asia'", &ds, Some(13)).unwrap(); + assert_eq!(text, "(continent = 'Asia') AND name = 'x' #"); } /// The note under the buttons is put in display form once, as a whole: a field named in