Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ edit.reshape line
edit.rotate angle
edit.scale factor
edit.setGeometry layer? row geometry
edit.setValue layer? table? row field value
edit.setValue layer? table? row field value classStyle?
edit.settings showVertices?
edit.snap lon lat
edit.snapping on? tolerancePx? vertex? edge? end?
Expand Down Expand Up @@ -227,7 +227,7 @@ layer.addUrl url bytes? format? name? layer? zoom? x? y? wkt? crs? delimiter? pa
layer.addZarr path url variable? index? cells? bbox? crs? name? time? start? end? ran? summary? anonymous?
layer.aggregation layer? shape size?
layer.blend layer? mode
layer.classStyle layer? value? index? other? color? outline? label?
layer.classStyle layer? value? create? field? index? other? color? outline? label?
layer.clearDiagram layer?
layer.color layer? color
layer.copy layer? group?
Expand Down
111 changes: 72 additions & 39 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ pub fn commands() -> Vec<C> {
.when(super::design::need_editable_or_table)
.params(r#"{"layer"?, "table"?: name|id (a standalone table: adds a row, without geometry or template), "geometry": GeoJSON geometry (lon/lat; left out for a table), "attributes"?: {field: value}, "template"?: feature template}"#),
C::new("edit.delete", "Delete", "Edit › Features", delete).roles(&[]).effects(crate::policy::Effects::NONE).key("Delete").when(super::design::need_editable_selection),
C::new("edit.setValue", "Edit Attribute", "Attribute Table", set_value).roles(&[]).effects(crate::policy::Effects::NONE)
C::new("edit.setValue", "Edit Attribute", "Attribute Table", set_value).roles(&[]).effects(crate::policy::Effects::NONE).atomic()
.when(super::design::need_editable_or_table)
.params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "row": number, "field": string (the exact name first; a name matching several fields only ignoring case is refused), "value": any}"#),
C::new("edit.addField", "Add Field", "Data › Data Design › Fields", add_field).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "row": number, "field": string (the exact name first; a name matching several fields only ignoring case is refused), "value": any, "classStyle"?: bool (a layer text field: ensure the applied class has a Unique Values colour rule, in the same undoable transaction)}"#),
C::new("edit.addField", "Add Field", "Data › Data Design › Fields", add_field).roles(&[]).effects(crate::policy::Effects::NONE).atomic()
.when(need_layer_or_table)
.params(r#"{"layer"?, "table"?: name|id (a standalone table, instead of a layer), "name": string, "type": "long"|"double"|"text"|"boolean"|"date"|"datetime"}"#),
C::new("edit.deleteField", "Delete Field", "Data › Data Design › Fields", delete_field).roles(&[]).effects(crate::policy::Effects::NONE)
Expand Down Expand Up @@ -989,6 +989,14 @@ fn numeric_loss(input: &Value, v: &Value, ty: FieldType) -> Option<CellLoss> {
/// standalone table, as its field holds it ([`typed`]), saying what that lost. A table's first
/// copy of shared rows runs on the desktop table worker ([`table_ahead`]).
fn set_value(s: &mut Session, p: &Json) -> CmdResult {
let class_style = match p.get("classStyle") {
None => false,
Some(Json::Bool(on)) => *on,
Some(_) => return Err("classStyle must be true or false".into()),
};
if class_style && matches!(target(s, p)?, Target::Table(_)) {
return Err("automatic class styling requires a layer, not a standalone table".into());
}
if let Some(result) = land_table_edit(s, p, "edit.setValue") {
return result;
}
Expand Down Expand Up @@ -1022,6 +1030,12 @@ fn set_value(s: &mut Session, p: &Json) -> CmdResult {
let ty = l.dataset.fields.get(fi).map(|f| f.ty).ok_or("no field")?;
let field = l.dataset.fields.get(fi).map(|f| f.name.clone()).ok_or("no field")?;
let layer = l.dataset.name.clone();
if class_style && ty != FieldType::Text {
return Err("automatic class styling requires a text field".into());
}
if class_style && let Some(name) = raw.as_str() {
rustgis_map::symbology::validate_class_name(name)?;
}
let v = typed(raw, ty)?;
// Keep the existing finite coercion, but say when it discards information.
let loss = numeric_loss(&input, &v, ty);
Expand All @@ -1032,6 +1046,13 @@ fn set_value(s: &mut Session, p: &Json) -> CmdResult {
let cell = f.attrs.get_mut(fi).ok_or("no such row")?;
*cell = v;
super::design::apply(s, id, vec![super::design::Change { before: Some(before), row: Some(row) }])?;
if class_style {
let l = s.map_mut().layer_mut(id).ok_or("no layer")?;
let Value::Text(value) = l.dataset.value(row, fi) else { return Err("a class needs a non-empty text value".into()) };
let value = value.clone();
// The command transaction rolls back both the cell and styling if either refuses.
super::layer::ensure_unique_class(l, &field, &value)?;
Comment thread
robmarkcole marked this conversation as resolved.
Resolved
}
if let Some(key) = loss {
notify_loss(s, key, &layer, field, row);
}
Expand Down Expand Up @@ -1066,10 +1087,15 @@ fn typed(raw: Json, ty: FieldType) -> Result<Value, String> {
})
}

/// Adds an empty field of a type: long, double, text, boolean, date or datetime. Table rows
/// are filled on the desktop worker ([`table_ahead`]), with progress and Cancel.
/// Adds an empty field of a type: long, double, text, boolean, date or datetime. Layer and
/// table rows are filled on the desktop field-edit worker ([`table_ahead`]), with progress
/// and Cancel between rows. The shared row storage's first copy cannot be interrupted.
fn add_field(s: &mut Session, p: &Json) -> CmdResult {
if let Some(result) = land_table_edit(s, p, "edit.addField") {
let landed = match target(s, p)? {
Target::Layer(_) => land_layer_schema(s, p, "edit.addField"),
Target::Table(_) => land_table_edit(s, p, "edit.addField"),
};
if let Some(result) = landed {
return result;
}
let t = write_target(s, p)?;
Expand All @@ -1090,17 +1116,10 @@ fn add_field(s: &mut Session, p: &Json) -> CmdResult {
if ds.field_index(name).is_some() {
return Err(format!("a field named '{name}' already exists"));
}
let table = matches!(t, Target::Table(_));
ds.fields.push(Field::new(name, ty));
if table {
rustgis_data::progress::begin(ds.features.len());
}
// A table's edit runs ahead on a worker, with progress and Cancel ([`table_ahead`]).
ds.features.try_add_columns(
1,
Value::Null,
|| if table { rustgis_data::progress::step(1).map_err(|e| e.to_string()) } else { Ok(()) },
)?;
rustgis_data::progress::begin(ds.features.len());
// Shared rows are copied once, each at its new length, and Cancel is checked before each row.
ds.features.try_add_columns(1, Value::Null, || rustgis_data::progress::step(1).map_err(|e| e.to_string()))?;
Ok(Json::Null)
}

Expand All @@ -1118,7 +1137,7 @@ fn add_field(s: &mut Session, p: &Json) -> CmdResult {
fn convert_field(s: &mut Session, p: &Json) -> CmdResult {
// A prepared result has one concrete type: do not consume it while probing another type.
let landed = match target(s, p)? {
Target::Layer(_) => land_layer_dates(s, p),
Target::Layer(_) => land_layer_schema(s, p, "edit.convertField"),
Target::Table(_) => land_table_edit(s, p, "edit.convertField"),
};
if let Some(result) = landed {
Expand Down Expand Up @@ -1815,7 +1834,7 @@ pub(crate) const TABLE_EDITS: &[(&str, &str, fn(&mut Session, &Json) -> CmdResul
];

/// The registered command and progress label for a table write. Layer invocations keep their
/// existing path; the desktop uses this worker only when parameters name a standalone table.
/// existing path except Add Field and date conversion, which also prepare loaded layer rows.
pub fn table_edit_in_background(command: &str) -> Option<(&'static str, &'static str)> {
TABLE_EDITS.iter().find(|(id, ..)| *id == command).map(|(id, name, _)| (*id, *name))
}
Expand Down Expand Up @@ -1894,7 +1913,11 @@ pub(crate) fn script_table(
/// shared row storage's first copy and one expression evaluation cannot be interrupted.
pub(crate) fn table_ahead(s: &Session, command: &str, p: &Json) -> Result<Option<super::reads::ReadWork>, String> {
let Target::Table(i) = target(s, p)? else {
return if command == "edit.convertField" { layer_dates_ahead(s, p).map(Some) } else { Ok(None) };
return if matches!(command, "edit.convertField" | "edit.addField") {
layer_schema_ahead(s, command, p).map(Some)
} else {
Ok(None)
};
};
let &(_, name, handler) = TABLE_EDITS.iter().find(|(id, ..)| *id == command).ok_or("not a table edit")?;
let table = s.project.tables.get(i).ok_or("no such table")?.clone();
Expand All @@ -1916,8 +1939,8 @@ pub(crate) fn table_ahead(s: &Session, command: &str, p: &Json) -> Result<Option
})))
}

/// A layer conversion installs only its rows and fields, after checking its identity and schema.
struct LayerDates {
/// A layer field edit installs only its rows and fields, after checking its identity and schema.
struct LayerSchema {
opened: u64,
id: u32,
instance: u64,
Expand All @@ -1927,39 +1950,42 @@ struct LayerDates {

/// Captures shared rows only; the worker uses an isolated table session. Layer schema
/// consumers are checked before capture and again at landing, without cloning edit archives.
fn layer_dates_ahead(s: &Session, p: &Json) -> Result<super::reads::ReadWork, String> {
fn layer_schema_ahead(s: &Session, command: &str, p: &Json) -> Result<super::reads::ReadWork, String> {
let id = s.layer_id(p)?;
let layer = s.map().layer(id).ok_or("no layer")?;
let fi = field_of(s, Target::Layer(id), ps(p, "field").ok_or("field is required")?)?;
let ty = match ps(p, "type").unwrap_or("").to_ascii_lowercase().as_str() {
"date" => FieldType::Date,
"datetime" | "date-time" | "timestamp" => FieldType::DateTime,
_ => return Err("type must be date or datetime".into()),
};
check_layer_dates(s, id, fi, ty)?;
if command == "edit.convertField" {
let fi = field_of(s, Target::Layer(id), ps(p, "field").ok_or("field is required")?)?;
let ty = match ps(p, "type").unwrap_or("").to_ascii_lowercase().as_str() {
"date" => FieldType::Date,
"datetime" | "date-time" | "timestamp" => FieldType::DateTime,
_ => return Err("type must be date or datetime".into()),
};
check_layer_dates(s, id, fi, ty)?;
}
let &(command, name, handler) = TABLE_EDITS.iter().find(|(id, ..)| *id == command).ok_or("not a field edit")?;
let (opened, instance, input) = (s.opened, layer.instance_id(), layer.dataset.clone());
let (dataset, mut p) = (input.clone(), p.clone());
Ok(super::reads::ahead("Convert Field", "edit.convertField".into(), move || {
Ok(super::reads::ahead(name, command.into(), move || {
let result = (|| {
rustgis_data::progress::begin(0);
rustgis_data::progress::check().map_err(|e| e.to_string())?;
let mut copy = Session::new(crate::Project::default());
let table = copy.project.put_table(dataset);
p.as_object_mut().ok_or("parameters must be an object")?.remove("layer");
p["table"] = json!(table);
let answer = convert_field(&mut copy, &p)?;
let answer = handler(&mut copy, &p)?;
rustgis_data::progress::check().map_err(|e| e.to_string())?;
let output = copy.project.table(table).ok_or("no table")?.dataset.clone();
Ok((output, answer, copy.notices))
})();
LayerDates { opened, id, instance, input, result }
LayerSchema { opened, id, instance, input, result }
}))
}

/// Rejects stale worker output and rechecks current design constraints before installing one
/// conversion as one undo step. Changes to unrelated map properties remain in place.
fn land_layer_dates(s: &mut Session, p: &Json) -> Option<CmdResult> {
let ahead = super::reads::take::<LayerDates>(s, "edit.convertField")?;
/// field edit as one undo step. Changes to unrelated map properties remain in place.
fn land_layer_schema(s: &mut Session, p: &Json, command: &str) -> Option<CmdResult> {
let ahead = super::reads::take::<LayerSchema>(s, command)?;
Comment thread
robmarkcole marked this conversation as resolved.
Resolved
Some((|| {
let id = s.layer_id(p)?;
let layer = s.map().layer(id).ok_or("no layer")?;
Expand All @@ -1969,12 +1995,19 @@ fn land_layer_dates(s: &mut Session, p: &Json) -> Option<CmdResult> {
|| layer.dataset.fields != ahead.input.fields
|| !layer.dataset.features.shares(&ahead.input.features)
{
return Err("the layer changed while it was converted: run the conversion again".into());
return Err(if command == "edit.convertField" {
"the layer changed while it was converted: run the conversion again"
} else {
"the layer changed while its field was added: run Add Field again"
}
.into());
}
let (output, answer, notices) = ahead.result?;
let fi = field_of(s, Target::Layer(id), ps(p, "field").ok_or("field is required")?)?;
let ty = output.fields.get(fi).ok_or("no field")?.ty;
check_layer_dates(s, id, fi, ty)?;
if command == "edit.convertField" {
let fi = field_of(s, Target::Layer(id), ps(p, "field").ok_or("field is required")?)?;
let ty = output.fields.get(fi).ok_or("no field")?.ty;
check_layer_dates(s, id, fi, ty)?;
}
let layer = s.map_mut().layer_mut(id).ok_or("no layer")?;
(layer.dataset.fields, layer.dataset.features) = (output.fields, output.features);
// Each with its code, as a table's edit lands.
Expand Down
Loading
Loading