diff --git a/crates/ocs_plugin_api/src/dialog.rs b/crates/ocs_plugin_api/src/dialog.rs index 799961b4e7..8bcc586d26 100644 --- a/crates/ocs_plugin_api/src/dialog.rs +++ b/crates/ocs_plugin_api/src/dialog.rs @@ -158,12 +158,10 @@ fn dialog_decode_add_nodes(count: usize) -> Result<(), String> { fn budgeted_controls<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { - dialog_decode_enter() - .map_err(::custom)?; + dialog_decode_enter().map_err(::custom)?; let _guard = DialogDecodeGuard; let controls = Vec::::deserialize(deserializer)?; - dialog_decode_add_nodes(controls.len()) - .map_err(::custom)?; + dialog_decode_add_nodes(controls.len()).map_err(::custom)?; Ok(controls) } @@ -171,12 +169,10 @@ fn budgeted_controls<'de, D: serde::Deserializer<'de>>( fn budgeted_dialog_value_map<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { - dialog_decode_enter() - .map_err(::custom)?; + dialog_decode_enter().map_err(::custom)?; let _guard = DialogDecodeGuard; let map = HashMap::::deserialize(deserializer)?; - dialog_decode_add_nodes(map.len()) - .map_err(::custom)?; + dialog_decode_add_nodes(map.len()).map_err(::custom)?; Ok(map) } @@ -622,7 +618,10 @@ pub enum DialogValue { Text(String), Number(f64), Bool(bool), - Choice { index: usize, text: String }, + Choice { + index: usize, + text: String, + }, Color([u8; 3]), FilePath(String), Fields(#[serde(deserialize_with = "budgeted_dialog_value_map")] HashMap), @@ -1012,7 +1011,8 @@ mod tests { }; let evt_bytes = bincode::serialize(&event).expect("serialize event"); - let restored_evt: DialogEvent = bincode::deserialize(&evt_bytes).expect("deserialize event"); + let restored_evt: DialogEvent = + bincode::deserialize(&evt_bytes).expect("deserialize event"); assert_eq!(event, restored_evt); let mut update_values = HashMap::new(); @@ -1020,7 +1020,10 @@ mod tests { "startup_scripts".to_string(), DialogValue::Table(vec![vec!["C:/scripts/test.lsp".to_string()]]), ); - update_values.insert("status_label".to_string(), DialogValue::Text("Script added".to_string())); + update_values.insert( + "status_label".to_string(), + DialogValue::Text("Script added".to_string()), + ); let action_resp = DialogActionResponse::UpdateValues(update_values); let resp_bytes = bincode::serialize(&action_resp).expect("serialize action response"); @@ -1069,8 +1072,7 @@ mod tests { // Old plugin's InfoText layout: discriminant 0u32 + String + Option let mut legacy_info_bytes = Vec::new(); legacy_info_bytes.extend_from_slice(&0u32.to_le_bytes()); - legacy_info_bytes - .extend_from_slice(&bincode::serialize(&"Hello".to_string()).unwrap()); + legacy_info_bytes.extend_from_slice(&bincode::serialize(&"Hello".to_string()).unwrap()); legacy_info_bytes .extend_from_slice(&bincode::serialize(&Some(HorizontalAlign::Center)).unwrap()); @@ -1185,4 +1187,3 @@ mod tests { assert_eq!(parsed_default.style, PanelStyle::Palette); } } - diff --git a/crates/ocs_plugin_api/src/entity_coverage.rs b/crates/ocs_plugin_api/src/entity_coverage.rs index dfd970a06e..c41fb23726 100644 --- a/crates/ocs_plugin_api/src/entity_coverage.rs +++ b/crates/ocs_plugin_api/src/entity_coverage.rs @@ -109,10 +109,14 @@ fn validate_hatch_paths( } BoundaryEdge::CircularArc(arc) => { if !arc.center.x.is_finite() || !arc.center.y.is_finite() { - return Err(format!("Hatch boundary path {pi} edge {ei} arc center has non-finite coordinates")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} arc center has non-finite coordinates" + )); } if !arc.radius.is_finite() || arc.radius <= 0.0 { - return Err(format!("Hatch boundary path {pi} edge {ei} arc radius must be finite and positive")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} arc radius must be finite and positive" + )); } if !arc.start_angle.is_finite() || !arc.end_angle.is_finite() { return Err(format!( @@ -134,12 +138,16 @@ fn validate_hatch_paths( } BoundaryEdge::EllipticArc(arc) => { if !arc.center.x.is_finite() || !arc.center.y.is_finite() { - return Err(format!("Hatch boundary path {pi} edge {ei} ellipse center has non-finite coordinates")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} ellipse center has non-finite coordinates" + )); } if !arc.major_axis_endpoint.x.is_finite() || !arc.major_axis_endpoint.y.is_finite() { - return Err(format!("Hatch boundary path {pi} edge {ei} ellipse major axis has non-finite coordinates")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} ellipse major axis has non-finite coordinates" + )); } if arc.major_axis_endpoint.x.hypot(arc.major_axis_endpoint.y) < 1e-12 { return Err(format!( @@ -150,7 +158,9 @@ fn validate_hatch_paths( || !(0.0..=1.0).contains(&arc.minor_axis_ratio) || arc.minor_axis_ratio == 0.0 { - return Err(format!("Hatch boundary path {pi} edge {ei} ellipse ratio must be within (0, 1]")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} ellipse ratio must be within (0, 1]" + )); } if !arc.start_angle.is_finite() || !arc.end_angle.is_finite() { return Err(format!( @@ -177,11 +187,15 @@ fn validate_hatch_paths( } BoundaryEdge::Polyline(poly) => { if poly.vertices.len() < 3 { - return Err(format!("Hatch boundary path {pi} edge {ei} polyline must have at least 3 vertices")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} polyline must have at least 3 vertices" + )); } for (vi, v) in poly.vertices.iter().enumerate() { if !v.x.is_finite() || !v.y.is_finite() || !v.z.is_finite() { - return Err(format!("Hatch boundary path {pi} edge {ei} vertex {vi} has non-finite coordinates")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} vertex {vi} has non-finite coordinates" + )); } } if !poly.is_closed { @@ -202,28 +216,38 @@ fn validate_hatch_paths( )); } if spline.control_points.len() < spline.degree as usize + 1 { - return Err(format!("Hatch boundary path {pi} edge {ei} spline has too few control points for its degree")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} spline has too few control points for its degree" + )); } if spline.knots.iter().any(|knot| !knot.is_finite()) || spline.knots.windows(2).any(|pair| pair[0] > pair[1]) { - return Err(format!("Hatch boundary path {pi} edge {ei} spline knots must be finite and nondecreasing")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} spline knots must be finite and nondecreasing" + )); } for (ci, cp) in spline.control_points.iter().enumerate() { if !cp.x.is_finite() || !cp.y.is_finite() || !cp.z.is_finite() { - return Err(format!("Hatch boundary path {pi} edge {ei} control point {ci} has non-finite coordinates")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} control point {ci} has non-finite coordinates" + )); } } for (fi, fp) in spline.fit_points.iter().enumerate() { if !fp.x.is_finite() || !fp.y.is_finite() { - return Err(format!("Hatch boundary path {pi} edge {ei} fit point {fi} has non-finite coordinates")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} fit point {fi} has non-finite coordinates" + )); } } for (name, tangent) in [("start", spline.start_tangent), ("end", spline.end_tangent)] { if !tangent.x.is_finite() || !tangent.y.is_finite() { - return Err(format!("Hatch boundary path {pi} edge {ei} spline {name} tangent is non-finite")); + return Err(format!( + "Hatch boundary path {pi} edge {ei} spline {name} tangent is non-finite" + )); } } let points = if spline.fit_points.len() >= 2 { @@ -2521,7 +2545,9 @@ pub fn validate_canvas_entity_references( .iter() .any(|style| style.handle == handle) { - return Err(format!("Table.rows[{ri}].cells[{ci}] text style handle {handle:?} does not exist")); + return Err(format!( + "Table.rows[{ri}].cells[{ci}] text style handle {handle:?} does not exist" + )); } } if let Some(handle) = content.block_handle.filter(|handle| !handle.is_null()) { @@ -2530,7 +2556,9 @@ pub fn validate_canvas_entity_references( .iter() .any(|record| record.handle == handle) { - return Err(format!("Table.rows[{ri}].cells[{ci}] block handle {handle:?} does not exist")); + return Err(format!( + "Table.rows[{ri}].cells[{ci}] block handle {handle:?} does not exist" + )); } } } @@ -2866,7 +2894,7 @@ pub fn patch_canvas_layer( #[cfg(test)] mod tests { use super::*; - use crate::{get_embedded_type_registry_json, TypeId, TypeRegistry}; + use crate::{TypeId, TypeRegistry, get_embedded_type_registry_json}; #[test] fn every_entity_variant_has_exactly_one_classification() { @@ -2880,18 +2908,24 @@ mod tests { for entry in &catalog.entity_kinds { assert!(names.insert(&entry.kind), "duplicate kind {}", entry.kind); assert!(variants.iter().any(|v| v.name == entry.kind)); - assert!(entry - .properties - .iter() - .any(|p| p.name == "handle" && p.model_access == ModelAccess::ReadOnly)); - assert!(entry - .properties - .iter() - .any(|p| p.name == "kind" && p.model_access == ModelAccess::ReadOnly)); - assert!(entry - .properties - .iter() - .any(|p| p.name == "owner_handle" && p.model_access == ModelAccess::ReadOnly)); + assert!( + entry + .properties + .iter() + .any(|p| p.name == "handle" && p.model_access == ModelAccess::ReadOnly) + ); + assert!( + entry + .properties + .iter() + .any(|p| p.name == "kind" && p.model_access == ModelAccess::ReadOnly) + ); + assert!( + entry + .properties + .iter() + .any(|p| p.name == "owner_handle" && p.model_access == ModelAccess::ReadOnly) + ); let mut source_paths = std::collections::HashSet::new(); for property in &entry.properties { assert!( @@ -3364,12 +3398,14 @@ mod tests { ); tolerance.direction = Vector3::UNIT_X; tolerance.dimension_style_name = "Missing".into(); - assert!(validate_canvas_entity_references( - &document, - &document::EntityType::Tolerance(tolerance) - ) - .unwrap_err() - .contains("does not exist")); + assert!( + validate_canvas_entity_references( + &document, + &document::EntityType::Tolerance(tolerance) + ) + .unwrap_err() + .contains("does not exist") + ); } #[cfg(feature = "host")] @@ -3394,20 +3430,18 @@ mod tests { let mut wrong_kind = leader.clone(); wrong_kind.creation_type = LeaderCreationType::WithTolerance; - assert!(validate_canvas_entity_references( - &document, - &document::EntityType::Leader(wrong_kind) - ) - .unwrap_err() - .contains("does not match")); + assert!( + validate_canvas_entity_references(&document, &document::EntityType::Leader(wrong_kind)) + .unwrap_err() + .contains("does not match") + ); let mut missing = leader.clone(); missing.annotation_handle = document::Handle::new(0xdead); - assert!(validate_canvas_entity_references( - &document, - &document::EntityType::Leader(missing) - ) - .unwrap_err() - .contains("does not exist")); + assert!( + validate_canvas_entity_references(&document, &document::EntityType::Leader(missing)) + .unwrap_err() + .contains("does not exist") + ); let mut none_with_handle = leader.clone(); none_with_handle.creation_type = LeaderCreationType::NoAnnotation; assert!( @@ -3424,21 +3458,22 @@ mod tests { ); let mut bad_style = leader.clone(); bad_style.dimension_style = "Missing".into(); - assert!(validate_canvas_entity_references( - &document, - &document::EntityType::Leader(bad_style) - ) - .unwrap_err() - .contains("dimension style")); + assert!( + validate_canvas_entity_references(&document, &document::EntityType::Leader(bad_style)) + .unwrap_err() + .contains("dimension style") + ); let mut edited = leader.clone(); edited.vertices[1] = Vector3::new(f64::NAN, 0.0, 0.0); - assert!(validate_entity_mutation( - &document::EntityType::Leader(leader.clone()), - &document::EntityType::Leader(edited) - ) - .unwrap_err() - .contains("finite")); + assert!( + validate_entity_mutation( + &document::EntityType::Leader(leader.clone()), + &document::EntityType::Leader(edited) + ) + .unwrap_err() + .contains("finite") + ); } #[cfg(feature = "host")] @@ -3461,20 +3496,21 @@ mod tests { let mut missing = mline.clone(); missing.style_name = "Missing".into(); - assert!(bind_canvas_entity_references( - &document, - &mut document::EntityType::MLine(missing) - ) - .unwrap_err() - .contains("does not exist")); + assert!( + bind_canvas_entity_references(&document, &mut document::EntityType::MLine(missing)) + .unwrap_err() + .contains("does not exist") + ); let mut wrong_segments = mline.clone(); wrong_segments.vertices[0].init_segments(3); - assert!(bind_canvas_entity_references( - &document, - &mut document::EntityType::MLine(wrong_segments) - ) - .unwrap_err() - .contains("segments but style")); + assert!( + bind_canvas_entity_references( + &document, + &mut document::EntityType::MLine(wrong_segments) + ) + .unwrap_err() + .contains("segments but style") + ); let mut one = mline.clone(); one.vertices.truncate(1); assert!( @@ -3620,19 +3656,23 @@ mod tests { before.radius = f64::NAN; let mut layer_only = before.clone(); layer_only.common.layer = "OTHER".into(); - assert!(validate_entity_mutation( - &document::EntityType::Circle(before.clone()), - &document::EntityType::Circle(layer_only), - ) - .is_ok()); + assert!( + validate_entity_mutation( + &document::EntityType::Circle(before.clone()), + &document::EntityType::Circle(layer_only), + ) + .is_ok() + ); let mut bad_radius = before.clone(); bad_radius.radius = -1.0; - assert!(validate_entity_mutation( - &document::EntityType::Circle(before), - &document::EntityType::Circle(bad_radius), - ) - .unwrap_err() - .contains("Circle.radius")); + assert!( + validate_entity_mutation( + &document::EntityType::Circle(before), + &document::EntityType::Circle(bad_radius), + ) + .unwrap_err() + .contains("Circle.radius") + ); } #[cfg(feature = "host")] @@ -3668,12 +3708,14 @@ mod tests { ); let mut changed = solid.clone(); changed.thickness = f64::INFINITY; - assert!(validate_entity_mutation( - &document::EntityType::Solid(solid), - &document::EntityType::Solid(changed) - ) - .unwrap_err() - .contains("Solid.thickness")); + assert!( + validate_entity_mutation( + &document::EntityType::Solid(solid), + &document::EntityType::Solid(changed) + ) + .unwrap_err() + .contains("Solid.thickness") + ); let face = document::entities::Face3D::new( Vector3::ZERO, @@ -3683,12 +3725,14 @@ mod tests { ); let mut changed = face.clone(); changed.invisible_edges = document::entities::InvisibleEdgeFlags::from_bits(0x10); - assert!(validate_entity_mutation( - &document::EntityType::Face3D(face), - &document::EntityType::Face3D(changed) - ) - .unwrap_err() - .contains("Face3D.invisible_edges")); + assert!( + validate_entity_mutation( + &document::EntityType::Face3D(face), + &document::EntityType::Face3D(changed) + ) + .unwrap_err() + .contains("Face3D.invisible_edges") + ); } #[cfg(feature = "host")] @@ -3699,35 +3743,43 @@ mod tests { let mut moved = before.clone(); moved.insert_point = Vector3::new(5.0, 6.0, 0.0); moved.set_x_scale(2.0); - assert!(validate_entity_mutation( - &document::EntityType::Insert(before.clone()), - &document::EntityType::Insert(moved) - ) - .is_ok()); + assert!( + validate_entity_mutation( + &document::EntityType::Insert(before.clone()), + &document::EntityType::Insert(moved) + ) + .is_ok() + ); let mut bad = before.clone(); bad.set_y_scale(f64::NAN); - assert!(validate_entity_mutation( - &document::EntityType::Insert(before.clone()), - &document::EntityType::Insert(bad) - ) - .unwrap_err() - .contains("Insert.y_scale")); + assert!( + validate_entity_mutation( + &document::EntityType::Insert(before.clone()), + &document::EntityType::Insert(bad) + ) + .unwrap_err() + .contains("Insert.y_scale") + ); let mut bad = before.clone(); bad.column_count = 0; - assert!(validate_entity_mutation( - &document::EntityType::Insert(before.clone()), - &document::EntityType::Insert(bad) - ) - .unwrap_err() - .contains("array counts")); + assert!( + validate_entity_mutation( + &document::EntityType::Insert(before.clone()), + &document::EntityType::Insert(bad) + ) + .unwrap_err() + .contains("array counts") + ); let mut bad = before.clone(); bad.block_name = "OTHER".into(); - assert!(validate_entity_mutation( - &document::EntityType::Insert(before), - &document::EntityType::Insert(bad) - ) - .unwrap_err() - .contains("block identity")); + assert!( + validate_entity_mutation( + &document::EntityType::Insert(before), + &document::EntityType::Insert(bad) + ) + .unwrap_err() + .contains("block identity") + ); } #[cfg(feature = "host")] @@ -3787,20 +3839,24 @@ mod tests { validate_canvas_entity_references(&document, &entity).unwrap(); definition.common.owner_handle = Handle::NULL; - assert!(validate_canvas_entity_references( - &document, - &document::EntityType::AttributeDefinition(definition.clone()) - ) - .unwrap_err() - .contains("block-record owner")); + assert!( + validate_canvas_entity_references( + &document, + &document::EntityType::AttributeDefinition(definition.clone()) + ) + .unwrap_err() + .contains("block-record owner") + ); definition.common.owner_handle = record_handle; definition.text_style = "Missing".into(); - assert!(validate_canvas_entity_references( - &document, - &document::EntityType::AttributeDefinition(definition.clone()) - ) - .unwrap_err() - .contains("does not exist")); + assert!( + validate_canvas_entity_references( + &document, + &document::EntityType::AttributeDefinition(definition.clone()) + ) + .unwrap_err() + .contains("does not exist") + ); definition.text_style = "Standard".into(); definition.tag = "BAD TAG".into(); assert!( @@ -3877,12 +3933,14 @@ mod tests { bound.attdef_handle = definition_handle; let mut moved = bound.clone(); moved.attdef_handle = insert_handle; - assert!(validate_entity_mutation( - &document::EntityType::AttributeEntity(bound), - &document::EntityType::AttributeEntity(moved) - ) - .unwrap_err() - .contains("read-only")); + assert!( + validate_entity_mutation( + &document::EntityType::AttributeEntity(bound), + &document::EntityType::AttributeEntity(moved) + ) + .unwrap_err() + .contains("read-only") + ); } #[cfg(feature = "host")] #[test] @@ -3943,11 +4001,13 @@ mod tests { ) .unwrap(); associative.paths[0].boundary_handles[0] = document::Handle::new(u64::MAX); - assert!(validate_canvas_entity_references( - &document, - &document::EntityType::Hatch(Box::new(associative)), - ) - .unwrap_err() - .contains("does not exist")); + assert!( + validate_canvas_entity_references( + &document, + &document::EntityType::Hatch(Box::new(associative)), + ) + .unwrap_err() + .contains("does not exist") + ); } } diff --git a/crates/ocs_plugin_api/src/host.rs b/crates/ocs_plugin_api/src/host.rs index 7a0543073a..45235cb37c 100644 --- a/crates/ocs_plugin_api/src/host.rs +++ b/crates/ocs_plugin_api/src/host.rs @@ -34,7 +34,7 @@ pub use document::xdata::{ExtendedDataRecord, XDataValue}; pub use document::{Document, EntityType, Handle}; use crate::ipc::protocol::{PluginRequest, PluginResponse}; -use crate::scene::{PanelSurface, SceneRevision, SurfaceReject, SurfaceRejectCode}; +use crate::scene::{PanelScene, PanelSurface, SceneRevision, SurfaceReject, SurfaceRejectCode}; /// Thread-safe handle that can issue host requests from plugin worker threads. /// Out-of-process V4 plugins implement this; in-process hosts may return `None`. @@ -2438,9 +2438,9 @@ pub trait HostApi { fn panel_surface_publish( &mut self, _panel_id: &str, - surface: PanelSurface, + scene: PanelScene, ) -> Result { - Err(surface_reject_default(&surface)) + Err(surface_reject_default_scene(&scene)) } /// [`Self::panel_surface_publish`] for the transport's authenticated @@ -2449,9 +2449,36 @@ pub trait HostApi { &mut self, _plugin_id: &str, panel_id: &str, - surface: PanelSurface, + scene: PanelScene, ) -> Result { - self.panel_surface_publish(panel_id, surface) + self.panel_surface_publish(panel_id, scene) + } + + /// Publish (or replace) a panel's WIDGET surface (API v29, additive): + /// the semantic tree/list the host renders with native widgets. + /// Independent revision space (finding F1). The default is the + /// transport-era stub (Unattached; nothing stored); surface-aware + /// hosts override [`HostApi::panel_widget_publish_for_plugin`]. + fn panel_widget_publish( + &mut self, + _panel_id: &str, + _surface: crate::widget::WidgetSurface, + ) -> Result { + Err(crate::widget::WidgetReject { + code: crate::widget::WidgetRejectCode::Unattached, + current_revision: None, + }) + } + + /// [`Self::panel_widget_publish`] for the transport's authenticated + /// `plugin_id`. + fn panel_widget_publish_for_plugin( + &mut self, + _plugin_id: &str, + panel_id: &str, + surface: crate::widget::WidgetSurface, + ) -> Result { + self.panel_widget_publish(panel_id, surface) } /// Patch a panel's stored scene atomically (API v29, additive): the @@ -2483,14 +2510,40 @@ pub trait HostApi { ) -> Result { self.panel_surface_patch(panel_id, patch) } + + /// Install a bounded widget page into the panel's widget surface + /// (API v29, additive): the lazy-expansion/paging primitive. The + /// default is the transport-era stub (Unattached; nothing stored). + /// Surface-aware hosts override + /// [`HostApi::panel_surface_page_for_plugin`]. + fn panel_surface_page( + &mut self, + _panel_id: &str, + _page: crate::widget::WidgetPage, + ) -> Result { + Err(crate::widget::WidgetReject { + code: crate::widget::WidgetRejectCode::Unattached, + current_revision: None, + }) + } + + /// Install from the host's authenticated transport identity. The + /// default keeps the direct-host behavior; surface-aware hosts + /// override it. + fn panel_surface_page_for_plugin( + &mut self, + _plugin_id: &str, + panel_id: &str, + page: crate::widget::WidgetPage, + ) -> Result { + self.panel_surface_page(panel_id, page) + } } /// The answer of a host without surface support: `InvalidSurface` for an /// invalid scene, otherwise `Unattached`. -pub(crate) fn surface_reject_default(surface: &PanelSurface) -> SurfaceReject { - let structural = match surface { - PanelSurface::Scene(scene) => scene.validate().is_ok(), - }; +pub(crate) fn surface_reject_default_scene(scene: &PanelScene) -> SurfaceReject { + let structural = scene.validate().is_ok(); SurfaceReject { code: if structural { SurfaceRejectCode::Unattached diff --git a/crates/ocs_plugin_api/src/host_v4.rs b/crates/ocs_plugin_api/src/host_v4.rs index 869348beb8..3a0279e1ab 100644 --- a/crates/ocs_plugin_api/src/host_v4.rs +++ b/crates/ocs_plugin_api/src/host_v4.rs @@ -133,9 +133,7 @@ impl HostV4SnapshotManager { let bytes = match data.to_rkyv_bytes() { Ok(bytes) => bytes, Err(e) => { - let msg = format!( - "failed to serialize V4 document view for tab {tab_id}: {e}" - ); + let msg = format!("failed to serialize V4 document view for tab {tab_id}: {e}"); eprintln!("[host] {msg}"); return Err(msg); } @@ -157,9 +155,8 @@ impl HostV4SnapshotManager { // then retire the old store (keep its file alive) instead // of deleting it out from under existing readers. if let Err(e) = store.publish_bytes(&bytes) { - let msg = format!( - "failed to publish V4 document view for tab {tab_id}: {e}" - ); + let msg = + format!("failed to publish V4 document view for tab {tab_id}: {e}"); eprintln!("[host] {msg}"); return Err(msg); } diff --git a/crates/ocs_plugin_api/src/ipc/client.rs b/crates/ocs_plugin_api/src/ipc/client.rs index adce62cee1..9b508e5d0a 100644 --- a/crates/ocs_plugin_api/src/ipc/client.rs +++ b/crates/ocs_plugin_api/src/ipc/client.rs @@ -16,8 +16,9 @@ use crate::ipc::protocol::{ HostResponse, HostToPlugin, PluginRequest, PluginResponse, PluginToHost, RunnerHandshake, }; use crate::ipc::transport::{recv, send}; -use crate::scene::{PanelSurface, SceneRevision, SurfaceReject, SurfaceRejectCode}; +use crate::scene::{PanelScene, PanelSurface, SceneRevision, SurfaceReject, SurfaceRejectCode}; use crate::shm::{DocumentViewData, DocumentViewInfo, SharedDocumentReader}; +use crate::widget::{WidgetReject, WidgetRejectCode, WidgetRevision, WidgetSurface}; /// Shared registry of active interactive commands, keyed by host-assigned id. pub type InteractiveRegistry = Rc>>>; @@ -1131,11 +1132,11 @@ impl HostApi for PluginHostApi { fn panel_surface_publish( &mut self, panel_id: &str, - surface: PanelSurface, + scene: PanelScene, ) -> Result { match self.client.request(PluginRequest::PanelSurfacePublish { panel_id: panel_id.to_string(), - surface, + surface: PanelSurface::Scene(scene), }) { Ok(PluginResponse::PanelSurfacePublished(result)) => result, Ok(other) => { @@ -1155,6 +1156,33 @@ impl HostApi for PluginHostApi { } } + fn panel_widget_publish( + &mut self, + panel_id: &str, + surface: WidgetSurface, + ) -> Result { + match self.client.request(PluginRequest::PanelSurfacePublish { + panel_id: panel_id.to_string(), + surface: PanelSurface::Widgets(surface), + }) { + Ok(PluginResponse::PanelWidgetPublished(result)) => result, + Ok(other) => { + eprintln!("[plugin] unexpected widget publish response: {other:?}"); + Err(WidgetReject { + code: WidgetRejectCode::Unattached, + current_revision: None, + }) + } + Err(e) => { + eprintln!("[plugin] widget publish request failed: {e}"); + Err(WidgetReject { + code: WidgetRejectCode::Unattached, + current_revision: None, + }) + } + } + } + fn panel_surface_patch( &mut self, panel_id: &str, @@ -1182,6 +1210,33 @@ impl HostApi for PluginHostApi { } } + fn panel_surface_page( + &mut self, + panel_id: &str, + page: crate::widget::WidgetPage, + ) -> Result { + match self.client.request(PluginRequest::PanelSurfacePage { + panel_id: panel_id.to_string(), + page, + }) { + Ok(PluginResponse::PanelSurfacePageResult(result)) => result, + Ok(other) => { + eprintln!("[plugin] unexpected PanelSurfacePage response: {other:?}"); + Err(WidgetReject { + code: WidgetRejectCode::Unattached, + current_revision: None, + }) + } + Err(e) => { + eprintln!("[plugin] PanelSurfacePage request failed: {e}"); + Err(WidgetReject { + code: WidgetRejectCode::Unattached, + current_revision: None, + }) + } + } + } + fn panel_snapshot(&self, panel_id: &str) -> Result { match self.client.request(PluginRequest::PanelSnapshot { panel_id: panel_id.to_string(), diff --git a/crates/ocs_plugin_api/src/ipc/protocol.rs b/crates/ocs_plugin_api/src/ipc/protocol.rs index 1726648a6d..f13de53c38 100644 --- a/crates/ocs_plugin_api/src/ipc/protocol.rs +++ b/crates/ocs_plugin_api/src/ipc/protocol.rs @@ -452,6 +452,14 @@ pub enum PluginRequest { panel_id: String, patch: crate::scene::ScenePatch, }, + /// V29 (additive): install a bounded, revision-checked page of widget + /// rows into the panel's widget surface atomically (all-or-nothing) — + /// the lazy-expansion and paging primitive (finding F4): installing + /// another page never replaces the whole surface. + PanelSurfacePage { + panel_id: String, + page: crate::widget::WidgetPage, + }, } /// Responses the host sends back for `PluginRequest`. @@ -555,6 +563,13 @@ pub enum PluginResponse { /// foreign ownership, unknown ids, budget overflow); the stored scene /// never ends up partially patched. PanelSurfacePatchResult(Result), + /// V29 (additive): outcome of a widget page install — the stored + /// widget revision after the atomic install, or the typed refusal. + PanelSurfacePageResult(Result), + /// V29 (additive): outcome of a WIDGET surface publish — the stored + /// widget revision (the widget tier's independent revision space), or + /// the typed refusal. + PanelWidgetPublished(Result), } /// Messages sent from the host to the plugin runner. @@ -858,4 +873,46 @@ mod tests { other => panic!("unexpected: {other:?}"), } } + + /// The S05 widget tier is pinned: the surface envelope grows + /// `Widgets` = 1 (after `Scene` = 0), the page install is request + /// variant 65 (right after the patch 64), and the typed page/widget + /// answers are response variants 51 and 52. Appends only. + #[test] + fn panel_widget_s05_wire_tails_are_pinned() { + let surface = crate::widget::WidgetSurface::new(crate::widget::WidgetRevision(1)); + assert_eq!( + discriminant_of(&PanelSurface::Scene(crate::scene::PanelScene { + revision: SceneRevision(1), + elements: Vec::new(), + })), + 0 + ); + assert_eq!(discriminant_of(&PanelSurface::Widgets(surface.clone())), 1); + assert_eq!( + discriminant_of(&PluginRequest::PanelSurfacePage { + panel_id: "acme:tree".into(), + page: crate::widget::WidgetPage { + base_revision: crate::widget::WidgetRevision(1), + parent: None, + after: None, + rows: Vec::new(), + next: None, + }, + }), + 65 + ); + assert_eq!( + discriminant_of(&PluginResponse::PanelSurfacePageResult(Ok( + crate::widget::WidgetRevision(2) + ))), + 51 + ); + assert_eq!( + discriminant_of(&PluginResponse::PanelWidgetPublished(Ok( + crate::widget::WidgetRevision(1) + ))), + 52 + ); + } } diff --git a/crates/ocs_plugin_api/src/ipc/server.rs b/crates/ocs_plugin_api/src/ipc/server.rs index 23bb349ecd..ceb4e9b57e 100644 --- a/crates/ocs_plugin_api/src/ipc/server.rs +++ b/crates/ocs_plugin_api/src/ipc/server.rs @@ -394,12 +394,20 @@ pub fn handle_plugin_request( PanelSnapshot { panel_id } => { PluginResponse::PanelSnapshot(host.panel_snapshot_for_plugin(plugin_id, &panel_id)) } - PanelSurfacePublish { panel_id, surface } => PluginResponse::PanelSurfacePublished( - host.panel_surface_publish_for_plugin(plugin_id, &panel_id, surface), - ), + PanelSurfacePublish { panel_id, surface } => match surface { + crate::scene::PanelSurface::Scene(scene) => PluginResponse::PanelSurfacePublished( + host.panel_surface_publish_for_plugin(plugin_id, &panel_id, scene), + ), + crate::scene::PanelSurface::Widgets(widgets) => PluginResponse::PanelWidgetPublished( + host.panel_widget_publish_for_plugin(plugin_id, &panel_id, widgets), + ), + }, PanelSurfacePatch { panel_id, patch } => PluginResponse::PanelSurfacePatchResult( host.panel_surface_patch_for_plugin(plugin_id, &panel_id, patch), ), + PanelSurfacePage { panel_id, page } => PluginResponse::PanelSurfacePageResult( + host.panel_surface_page_for_plugin(plugin_id, &panel_id, page), + ), SetGeoLocation { location } => { PluginResponse::GeoLocationSet(host.set_geo_location(&location)) } diff --git a/crates/ocs_plugin_api/src/ipc/snapshot_patch.rs b/crates/ocs_plugin_api/src/ipc/snapshot_patch.rs index 98e4d95067..5053ba9df9 100644 --- a/crates/ocs_plugin_api/src/ipc/snapshot_patch.rs +++ b/crates/ocs_plugin_api/src/ipc/snapshot_patch.rs @@ -62,7 +62,9 @@ pub(crate) fn apply_refreshed( /// Remove `handle` the way the host does: the document keeps a block record's /// member list apart from the entity store, so the handle leaves that too. fn remove_cached(doc: &mut Document, handle: Handle) { - let owner = doc.get_entity(handle).map(|entity| entity.common().owner_handle); + let owner = doc + .get_entity(handle) + .map(|entity| entity.common().owner_handle); doc.remove_entity(handle); if let Some(owner) = owner { if let Some(record) = doc.block_records.iter_mut().find(|r| r.handle == owner) { @@ -171,10 +173,11 @@ mod tests { record.entity_handles.push(handle); } assert!(apply_refreshed(&mut doc, &[], Vec::new(), &[handle])); - assert!(!doc - .block_records - .iter() - .any(|record| record.entity_handles.contains(&handle))); + assert!( + !doc.block_records + .iter() + .any(|record| record.entity_handles.contains(&handle)) + ); } #[test] @@ -185,7 +188,12 @@ mod tests { document::types::Vector3::ZERO, )); insert.common_mut().handle = handle; - assert!(!apply_refreshed(&mut doc, &[handle], vec![Some(insert)], &[])); + assert!(!apply_refreshed( + &mut doc, + &[handle], + vec![Some(insert)], + &[] + )); } #[test] diff --git a/crates/ocs_plugin_api/src/lib.rs b/crates/ocs_plugin_api/src/lib.rs index 519b6d7079..6bd3d7905e 100644 --- a/crates/ocs_plugin_api/src/lib.rs +++ b/crates/ocs_plugin_api/src/lib.rs @@ -41,6 +41,7 @@ pub mod scene; pub mod type_registry; pub mod type_registry_types; pub mod version_info; +pub mod widget; /// Runtime host surface — only built with the `host` feature (pulls `document`). #[cfg(feature = "host")] @@ -70,12 +71,12 @@ pub mod runner; pub use dialog::*; pub use entity_coverage::{ - get_embedded_entity_coverage_json, EntityCoverageCatalog, EntityKindCoverage, EntityScope, - ModelAccess, PropertyCoverage, + EntityCoverageCatalog, EntityKindCoverage, EntityScope, ModelAccess, PropertyCoverage, + get_embedded_entity_coverage_json, }; pub use manifest::{ - effective_max_api_version, host_accepts_plugin_version, ApiVersion, PluginManifest, - API_VERSION, API_VERSION_MIN_SUPPORTED, MAX_API_VERSION_ENV, + API_VERSION, API_VERSION_MIN_SUPPORTED, ApiVersion, MAX_API_VERSION_ENV, PluginManifest, + effective_max_api_version, host_accepts_plugin_version, }; pub use ribbon::{CadModule, IconKind, ModuleEvent, RibbonGroup, RibbonItem, StyleKey, ToolDef}; pub use scene::{ @@ -83,10 +84,14 @@ pub use scene::{ SceneRevision, StableId, Stroke, SurfaceReject, SurfaceRejectCode, ThemeColor, Vec2, }; pub use type_registry::{ - get_embedded_type_registry_json, EnumVariantInfo, FieldInfo, MethodInfo, ParameterInfo, TypeId, - TypeInfo, TypeKind, TypeRegistry, + EnumVariantInfo, FieldInfo, MethodInfo, ParameterInfo, TypeId, TypeInfo, TypeKind, + TypeRegistry, get_embedded_type_registry_json, }; pub use version_info::get_embedded_version_info_json; +pub use widget::{ + MAX_PAGE_ROWS, MAX_WIDGET_NODES, WidgetChildren, WidgetError, WidgetPage, WidgetRevision, + WidgetRow, WidgetSurface, +}; #[cfg(feature = "host")] pub use process::{DispatchResult, PluginError, PluginManager, PluginProcess}; diff --git a/crates/ocs_plugin_api/src/process.rs b/crates/ocs_plugin_api/src/process.rs index 28c9bc72b6..fa8db62f62 100644 --- a/crates/ocs_plugin_api/src/process.rs +++ b/crates/ocs_plugin_api/src/process.rs @@ -22,9 +22,9 @@ use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; +use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc; -use std::sync::Mutex; use std::time::{Duration, Instant}; use interprocess::local_socket::traits::Listener; @@ -35,7 +35,7 @@ use crate::host::{ }; use crate::ipc::protocol::{ Document, EntityType, Handle, HostRequest, HostResponse, HostToPlugin, InteractiveEvent, - PluginToHost, RunnerHandshake, PLUGIN_TOKEN_ENV, + PLUGIN_TOKEN_ENV, PluginToHost, RunnerHandshake, }; use crate::ipc::server::handle_plugin_request; use crate::ipc::transport::{recv, send}; @@ -109,9 +109,9 @@ fn create_kill_on_close_job(child: &Child) -> windows_sys::Win32::Foundation::HA use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::JobObjects::{ - AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, - SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, - JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation, + SetInformationJobObject, }; // SAFETY: all calls use plain OS handles and zeroed-parameter patterns @@ -667,8 +667,7 @@ impl PluginProcess { base_handler(&id, command_id, notification); }) }; - let v4_conn = - V4Connection::new(stream, handler_for_v4, Some(Arc::clone(&child)))?; + let v4_conn = V4Connection::new(stream, handler_for_v4, Some(Arc::clone(&child)))?; // Owner-scoped declarations (entity classes, quad panels, custom // grips) arrive as nested requests while GetManifest is in // flight — the plugin registers them as part of its own boot. @@ -1562,14 +1561,7 @@ fn pump_stream_lines( } } if !buffer.is_empty() || truncated { - emit( - &buffer, - truncated, - source, - io_tx, - plugin_id, - last_stderr, - ); + emit(&buffer, truncated, source, io_tx, plugin_id, last_stderr); } if eof_reached { break 'stream; @@ -2020,9 +2012,10 @@ mod tests { "NullHost ensure_plugin_state must degrade, not panic: {:?}", outcome.err() ); - assert!(null - .ensure_plugin_state_any("opencad.demo", &mut || Box::new(7u32)) - .is_none()); + assert!( + null.ensure_plugin_state_any("opencad.demo", &mut || Box::new(7u32)) + .is_none() + ); } } @@ -2040,11 +2033,11 @@ mod timeout_tests { use document::xdata::ExtendedDataRecord; use document::{Document, EntityType, Handle}; use interprocess::local_socket::{ - traits::{Listener, Stream as StreamTrait}, GenericNamespaced, ListenerOptions, Stream, ToNsName, + traits::{Listener, Stream as StreamTrait}, }; - use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex as StdMutex; + use std::sync::atomic::{AtomicU64, Ordering}; use std::thread; use std::time::Instant; diff --git a/crates/ocs_plugin_api/src/process/manager.rs b/crates/ocs_plugin_api/src/process/manager.rs index 84154447b9..f7d2fac242 100644 --- a/crates/ocs_plugin_api/src/process/manager.rs +++ b/crates/ocs_plugin_api/src/process/manager.rs @@ -16,13 +16,13 @@ //! and must not block. For heavy work, forward the notification to a channel. use std::path::Path; -use std::sync::atomic::Ordering; use std::sync::Arc; +use std::sync::atomic::Ordering; use std::time::Duration; use crate::host::{HostApi, HostNotification, PluginNotification}; use crate::process::{PluginError, PluginProcess}; -use crate::ribbon::owned::{to_shared_module, OwnedEntityClasses, SharedCadModule}; +use crate::ribbon::owned::{OwnedEntityClasses, SharedCadModule, to_shared_module}; /// Maximum notifications parked in the boot-window `attach.pending` queue /// (review finding 6): a plugin that never acks its ChannelReady cannot grow @@ -556,10 +556,7 @@ impl PluginManager { /// confirm the id before the load returns). This is the declaration law's /// gate ONLY — grip event routing keeps the stricter live-channel check. pub fn declaration_endpoint_alive(&self, id: &str) -> bool { - if self - .grip_endpoint(id) - .is_some_and(|(_, _, alive)| alive) - { + if self.grip_endpoint(id).is_some_and(|(_, _, alive)| alive) { return true; } self.booting @@ -922,8 +919,8 @@ mod tests { manifest: crate::ribbon::owned::OwnedPluginManifest, ) -> (PluginProcess, interprocess::local_socket::Stream) { use interprocess::local_socket::{ - traits::{Listener, Stream as StreamTrait}, GenericNamespaced, ListenerOptions, ToNsName, + traits::{Listener, Stream as StreamTrait}, }; static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); diff --git a/crates/ocs_plugin_api/src/process/v4.rs b/crates/ocs_plugin_api/src/process/v4.rs index 3d816b95d6..aa23f10965 100644 --- a/crates/ocs_plugin_api/src/process/v4.rs +++ b/crates/ocs_plugin_api/src/process/v4.rs @@ -2,11 +2,11 @@ use std::collections::VecDeque; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{mpsc, Arc, Mutex, TryLockError}; +use std::sync::{Arc, Mutex, TryLockError, mpsc}; use std::time::{Duration, Instant}; -use interprocess::local_socket::Stream; use interprocess::TryClone; +use interprocess::local_socket::Stream; use crate::host::{CommandSource, ExecutionResult, HostApi, HostNotification, PluginNotification}; use crate::ipc::protocol::{HostRequest, HostResponse, PluginRequest, PluginResponse}; @@ -14,9 +14,9 @@ use crate::ipc::server::handle_plugin_request; use crate::ipc::transport::send; use crate::ipc::v4::protocol::{HostToPluginV4, NotificationEnvelope}; use crate::ipc::v4::server::{ - default_notify_rate_limit, run_host_reader_thread, HostIncoming, RateLimiter, V4HostShared, + HostIncoming, RateLimiter, V4HostShared, default_notify_rate_limit, run_host_reader_thread, }; -use crate::process::{request_kind, request_timeout, PluginError}; +use crate::process::{PluginError, request_kind, request_timeout}; type DeferredRequest = (u64, Option, Box); @@ -33,9 +33,7 @@ fn park_bounded(queue: &Mutex>, cap: usize, what: &str, item: T) let mut queue = queue.lock().unwrap_or_else(|e| e.into_inner()); if queue.len() >= cap { queue.pop_front(); - eprintln!( - "[plugin] dropped the oldest parked V4 {what}: the queue exceeded {cap}" - ); + eprintln!("[plugin] dropped the oldest parked V4 {what}: the queue exceeded {cap}"); } queue.push_back(item); } @@ -234,8 +232,8 @@ impl V4Connection { let incoming = self.incoming.lock().unwrap_or_else(|e| e.into_inner()); loop { let remaining = deadline.saturating_duration_since(Instant::now()); - let hard_remaining = hard_deadline - .and_then(|end| end.checked_duration_since(Instant::now())); + let hard_remaining = + hard_deadline.and_then(|end| end.checked_duration_since(Instant::now())); if hard_remaining.map(|r| r.is_zero()).unwrap_or(false) { // Always logged: the process may still run after the // connection is marked dead, and this is the only record. @@ -776,8 +774,8 @@ mod tests { use crate::ipc::v4::protocol::{HostToPluginV4, PluginToHostV4}; use document::{Document, Handle}; use interprocess::local_socket::{ - traits::{Listener, Stream as StreamTrait}, GenericNamespaced, ListenerOptions, ToNsName, + traits::{Listener, Stream as StreamTrait}, }; fn unique_socket_name() -> String { diff --git a/crates/ocs_plugin_api/src/scene.rs b/crates/ocs_plugin_api/src/scene.rs index c231bec100..a617a94926 100644 --- a/crates/ocs_plugin_api/src/scene.rs +++ b/crates/ocs_plugin_api/src/scene.rs @@ -805,6 +805,11 @@ impl SceneBuilder { pub enum PanelSurface { /// The panel's declarative scene snapshot (bounded, validated). Scene(PanelScene), + /// The panel's semantic tree/list surface (api v29, S05): bounded rows + /// the host renders with NATIVE widgets; expansion/selection stay + /// host-local, and children a plugin has not pushed yet page in via + /// `WidgetPage` installs. + Widgets(crate::widget::WidgetSurface), } /// Why a panel surface publish was refused; a refusal changes nothing. @@ -862,6 +867,17 @@ pub enum SurfaceEvent { /// The drag was cancelled (escape, focus loss, teardown). `origin` is /// the PRE-DRAG origin, so the plugin can restore losslessly. DragCancelled { element: StableId, origin: Vec2 }, + /// A widget row was ACTIVATED (the host's activation gesture — enter + /// or the platform double-click) on a widget surface (api v29, S05). + /// Best-effort like every surface event; expansion/selection stay + /// host-local and are NOT notified — except `NodeExpanded` below, + /// which the plugin needs to page children in. + NodeActivated { node: StableId }, + /// The user expanded an `Unloaded` row on a widget surface: the + /// plugin should push a `WidgetPage` for that node's children (the + /// one expansion case that is NOT host-local — the plugin is the + /// data source). + NodeExpanded { node: StableId }, } /// Maximum patch ops accepted in one patch frame, bounding allocation and diff --git a/crates/ocs_plugin_api/src/shm.rs b/crates/ocs_plugin_api/src/shm.rs index a5d319293b..784690e54f 100644 --- a/crates/ocs_plugin_api/src/shm.rs +++ b/crates/ocs_plugin_api/src/shm.rs @@ -27,11 +27,11 @@ use std::fs::OpenOptions; use std::io; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use document::{Document, EntityType, Handle}; use memmap2::{Mmap, MmapMut, MmapOptions}; -use rkyv::{check_archived_root, to_bytes, Archive, Deserialize, Serialize}; +use rkyv::{Archive, Deserialize, Serialize, check_archived_root, to_bytes}; use crate::host::{DocumentReader, ReaderEntity, ReaderEntityKind, ReaderPoint}; diff --git a/crates/ocs_plugin_api/src/version_info.rs b/crates/ocs_plugin_api/src/version_info.rs index f2a02a42ad..722bc9898e 100644 --- a/crates/ocs_plugin_api/src/version_info.rs +++ b/crates/ocs_plugin_api/src/version_info.rs @@ -263,10 +263,12 @@ mod tests { assert!(acadrust_source_hash("").is_none()); assert!(acadrust_source_hash("registry+https://crates.io").is_none()); assert!(acadrust_source_hash("git+https://github.com/foo/bar.git#short").is_none()); - assert!(acadrust_source_hash( - "git+https://github.com/foo/bar.git#gggggggggggggggggggggggggggggggggggggggg" - ) - .is_none()); + assert!( + acadrust_source_hash( + "git+https://github.com/foo/bar.git#gggggggggggggggggggggggggggggggggggggggg" + ) + .is_none() + ); } #[test] diff --git a/crates/ocs_plugin_api/src/widget.rs b/crates/ocs_plugin_api/src/widget.rs new file mode 100644 index 0000000000..b3c7aa3081 --- /dev/null +++ b/crates/ocs_plugin_api/src/widget.rs @@ -0,0 +1,466 @@ +//! The widget surface data model (api v29, S05): semantic trees and +//! lists the host renders with NATIVE widgets. +//! +//! Ownership split mirrors the scene tier: the plugin owns the semantics +//! (what the rows mean); the host owns selection, expansion, scroll and +//! focus (host-local transient state), and renders the structure with its +//! own widgets. Plugin and host share nothing but this serializable +//! vocabulary. +//! +//! Layout is FLAT by design (finding F4): a surface holds every row in a +//! bounded map plus the display order of roots and of each loaded child +//! list. Children a plugin has not pushed yet are `Unloaded` — expanding +//! such a row asks the plugin for a keyed page, which installs +//! atomically; installing another page never replaces the whole surface. +//! Rows carry no nested subtrees, so pages stay small and the model has +//! no recursive traversal costs. +//! +//! Bounded everywhere: surface node budget, per-page row budget, and the +//! dialog text budget for labels. Deserialization of the whole surface is +//! likewise bounded before it can reach the store (same law as scenes). + +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashSet}; + +use crate::scene::StableId; + +/// Maximum rows in one widget surface, bounding allocation and CPU per +/// surface (mirrors [`crate::scene::MAX_SCENE_NODES`]'s spirit). +pub const MAX_WIDGET_NODES: usize = 10_000; + +/// Maximum rows in ONE page install: a page is a bounded window, not a +/// whole subtree. Plugins that need more rows install more pages. +pub const MAX_PAGE_ROWS: usize = 1_000; + +/// A widget surface's own revision — INDEPENDENT of any scene revision +/// (finding F1: scene and widget surfaces advance separately). +#[derive( + Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, +)] +pub struct WidgetRevision(pub u64); + +/// One row's child state: `Loaded` carries the ordered child ids actually +/// present in this surface; `Unloaded` marks children that exist but must +/// be paged in on expansion; `Leaf` cannot expand at all. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum WidgetChildren { + Leaf, + Unloaded, + Loaded(Vec), +} + +/// One row: its display label and its child state. Identity is the +/// plugin-assigned [`StableId`] (the map key, not repeated here). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WidgetRow { + pub label: String, + pub children: WidgetChildren, +} + +/// A keyed page of rows (finding F4): installs under `parent` +/// (`None` = roots), optionally positioned after an existing sibling, and +/// optionally continues from `next` — the cursor the NEXT page must name +/// in `after`. Revision-checked and atomic like the scene patch. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct WidgetPage { + pub base_revision: WidgetRevision, + pub parent: Option, + /// Install position: after this existing sibling of the new rows + /// (`None` = append at the end of the parent's list). + pub after: Option, + /// The rows to install (bounded by [`MAX_PAGE_ROWS`]); ids must be new. + pub rows: Vec<(StableId, WidgetRow)>, + /// When set, more rows exist after the last installed sibling; the + /// NEXT page names this cursor in `after`. + pub next: Option, +} + +/// Why a widget page install refused. Codes append at the end. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WidgetError { + /// The page's `base_revision` is not the surface's current revision. + StaleBase, + /// The page carries more rows than [`MAX_PAGE_ROWS`]. + PageTooLarge, + /// The surface would exceed [`MAX_WIDGET_NODES`]. + SurfaceTooLarge, + /// The page names a parent that is not in the surface. + UnknownParent, + /// The page names a parent that cannot have children (`Leaf`). + ParentCannotExpand, + /// The page positions itself after a row that is not a current child + /// of the parent. + UnknownAfter, + /// A structural walk named a row that is not in the surface. + UnknownElement(StableId), + /// A row id collides with an existing row (or appears twice). + DuplicateRow, + /// A row's label exceeds the text budget. + LabelTooLong, + /// The resulting surface would hold rows unreachable from the roots. + OrphanRows, +} + +impl core::fmt::Display for WidgetError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + WidgetError::StaleBase => write!(f, "page base is not the current surface revision"), + WidgetError::PageTooLarge => write!(f, "page carries too many rows"), + WidgetError::SurfaceTooLarge => write!(f, "surface node budget exceeded"), + WidgetError::UnknownParent => write!(f, "page parent is not in the surface"), + WidgetError::ParentCannotExpand => write!(f, "page parent cannot have children"), + WidgetError::UnknownAfter => write!(f, "page after-cursor is not a current child"), + WidgetError::UnknownElement(id) => { + write!(f, "row id {} is not in the surface", id.0) + } + WidgetError::DuplicateRow => write!(f, "page row id collides with an existing row"), + WidgetError::LabelTooLong => write!(f, "row label exceeds the text budget"), + WidgetError::OrphanRows => write!(f, "page would orphan rows from the roots"), + } + } +} + +/// The stored widget surface: every row in a bounded map, display order +/// for the roots and for each loaded child list. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct WidgetSurface { + pub revision: WidgetRevision, + pub rows: BTreeMap, + pub roots: Vec, +} + +impl WidgetSurface { + /// A fresh, empty surface at `revision`. + pub fn new(revision: WidgetRevision) -> Self { + Self { + revision, + rows: BTreeMap::new(), + roots: Vec::new(), + } + } + + /// Validate the whole surface: bounded row count, bounded labels, and + /// every row reachable from the roots exactly once (reachability + /// forces acyclicity and no orphans). + pub fn validate(&self) -> Result<(), WidgetError> { + if self.rows.len() > MAX_WIDGET_NODES { + return Err(WidgetError::SurfaceTooLarge); + } + for row in self.rows.values() { + if row.label.len() > crate::scene::MAX_TEXT_BYTES { + return Err(WidgetError::LabelTooLong); + } + } + let mut seen = HashSet::new(); + let mut stack: Vec = self.roots.iter().copied().collect(); + while let Some(id) = stack.pop() { + if !seen.insert(id) { + return Err(WidgetError::OrphanRows); + } + let Some(row) = self.rows.get(&id) else { + return Err(WidgetError::UnknownElement(id)); + }; + if let WidgetChildren::Loaded(children) = &row.children { + for child in children { + stack.push(*child); + } + } + } + if seen.len() != self.rows.len() { + return Err(WidgetError::OrphanRows); + } + Ok(()) + } + + /// Apply a page atomically: on any refusal the surface is + /// byte-for-byte unchanged; on success the revision advances by one + /// and the whole surface re-validates. + pub fn apply_page(&mut self, page: &WidgetPage) -> Result { + if page.base_revision != self.revision { + return Err(WidgetError::StaleBase); + } + if page.rows.len() > MAX_PAGE_ROWS { + return Err(WidgetError::PageTooLarge); + } + // All-or-nothing: stage the candidate, swap only on full success. + let mut candidate = self.clone(); + // Ids must be new and labels bounded (checked while inserting). + let mut new_ids = Vec::with_capacity(page.rows.len()); + for (id, row) in &page.rows { + if candidate.rows.contains_key(id) || new_ids.contains(id) { + return Err(WidgetError::DuplicateRow); + } + if row.label.len() > crate::scene::MAX_TEXT_BYTES { + return Err(WidgetError::LabelTooLong); + } + new_ids.push(*id); + } + // Attachment: parent must exist and be expandable; `after` must be + // a current child of the parent. + let child_list: &mut Vec = match page.parent { + None => &mut candidate.roots, + Some(parent_id) => { + let Some(parent) = candidate.rows.get_mut(&parent_id) else { + return Err(WidgetError::UnknownParent); + }; + match &mut parent.children { + WidgetChildren::Leaf => return Err(WidgetError::ParentCannotExpand), + WidgetChildren::Unloaded => { + parent.children = WidgetChildren::Loaded(Vec::new()); + match &mut parent.children { + WidgetChildren::Loaded(children) => children, + _ => unreachable!("just set Loaded"), + } + } + WidgetChildren::Loaded(children) => children, + } + } + }; + let insert_at = match page.after { + None => child_list.len(), + Some(after_id) => { + let position = child_list + .iter() + .position(|child| *child == after_id) + .ok_or(WidgetError::UnknownAfter)?; + position + 1 + } + }; + for (index, id) in new_ids.iter().enumerate() { + child_list.insert(insert_at + index, *id); + } + for (id, row) in &page.rows { + candidate.rows.insert(*id, row.clone()); + } + // The page's own `next` cursor stays a promise: nothing to install + // now, but the row list must still end consistently (the next page + // positions AFTER the last installed row). + let _ = page.next; + candidate.revision = WidgetRevision(self.revision.0 + 1); + candidate.validate()?; + *self = candidate; + Ok(self.revision) + } +} + +/// Why a widget-tier wire request refused. The widget tier carries its +/// own rejection type so its independent revision space (finding F1) is +/// type-safe end to end; codes append at the end. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WidgetRejectCode { + /// Nothing is attached for this panel (no host attach, or the panel + /// is not registered by the authenticated plugin), or the surface + /// was never published so it cannot be paged. + Unattached, + /// The surface is owned by a different verified plugin. + OwnedByOther, + /// The request is structurally invalid; refused without any state + /// change. + InvalidSurface, + /// The request's revision is not usable against the stored head. + NonMonotonicRevision, +} + +/// Typed rejection of a widget-tier request: the machine-readable code +/// plus the stored head when the refusal is revision-related. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct WidgetReject { + pub code: WidgetRejectCode, + /// The stored head when the refusal is revision-related; `None` + /// otherwise. + pub current_revision: Option, +} + +impl From for WidgetRejectCode { + fn from(code: crate::scene::SurfaceRejectCode) -> Self { + match code { + crate::scene::SurfaceRejectCode::Unattached => WidgetRejectCode::Unattached, + crate::scene::SurfaceRejectCode::OwnedByOther => WidgetRejectCode::OwnedByOther, + _ => WidgetRejectCode::InvalidSurface, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PARENT: StableId = StableId(1); + const A: StableId = StableId(10); + const B: StableId = StableId(11); + + fn row(label: &str, children: WidgetChildren) -> WidgetRow { + WidgetRow { + label: label.to_owned(), + children, + } + } + + fn surface_with_parent() -> WidgetSurface { + let mut surface = WidgetSurface::new(WidgetRevision(3)); + surface + .rows + .insert(PARENT, row("parent", WidgetChildren::Unloaded)); + surface.roots = vec![PARENT]; + surface + } + + #[test] + fn lazy_expansion_installs_a_page_under_an_unloaded_parent() { + let mut surface = surface_with_parent(); + let page = WidgetPage { + base_revision: WidgetRevision(3), + parent: Some(PARENT), + after: None, + rows: vec![(A, row("alpha", WidgetChildren::Leaf))], + next: None, + }; + assert_eq!(surface.apply_page(&page), Ok(WidgetRevision(4))); + assert_eq!( + surface.rows.get(&PARENT).unwrap().children, + WidgetChildren::Loaded(vec![A]) + ); + } + + #[test] + fn after_cursor_positions_rows_and_next_continues() { + let mut surface = surface_with_parent(); + let page = WidgetPage { + base_revision: WidgetRevision(3), + parent: Some(PARENT), + after: None, + rows: vec![(A, row("alpha", WidgetChildren::Leaf))], + next: Some(A), + }; + surface.apply_page(&page).expect("first page"); + let page = WidgetPage { + base_revision: WidgetRevision(4), + parent: Some(PARENT), + after: Some(A), + rows: vec![(B, row("beta", WidgetChildren::Leaf))], + next: None, + }; + surface.apply_page(&page).expect("second page"); + assert_eq!( + surface.rows.get(&PARENT).unwrap().children, + WidgetChildren::Loaded(vec![A, B]) + ); + } + + #[test] + fn stale_base_refuses_with_no_mutation() { + let mut surface = surface_with_parent(); + let page = WidgetPage { + base_revision: WidgetRevision(2), + parent: Some(PARENT), + after: None, + rows: vec![(A, row("alpha", WidgetChildren::Leaf))], + next: None, + }; + assert_eq!(surface.apply_page(&page), Err(WidgetError::StaleBase)); + assert!(matches!( + surface.rows.get(&PARENT).unwrap().children, + WidgetChildren::Unloaded + )); + assert_eq!(surface.revision, WidgetRevision(3)); + } + + #[test] + fn atomic_patch_refuses_without_partial_install() { + let mut surface = surface_with_parent(); + // Two valid rows and a duplicate id in the SAME page: nothing may + // install. + let page = WidgetPage { + base_revision: WidgetRevision(3), + parent: Some(PARENT), + after: None, + rows: vec![ + (A, row("alpha", WidgetChildren::Leaf)), + (A, row("alpha-again", WidgetChildren::Leaf)), + ], + next: None, + }; + assert_eq!(surface.apply_page(&page), Err(WidgetError::DuplicateRow)); + assert_eq!(surface.rows.len(), 1, "no row installed"); + assert!(matches!( + surface.rows.get(&PARENT).unwrap().children, + WidgetChildren::Unloaded + )); + } + + #[test] + fn leaf_parent_and_unknown_parent_refuse() { + let mut surface = WidgetSurface::new(WidgetRevision(1)); + surface + .rows + .insert(PARENT, row("leaf", WidgetChildren::Leaf)); + surface.roots = vec![PARENT]; + let page = WidgetPage { + base_revision: WidgetRevision(1), + parent: Some(PARENT), + after: None, + rows: vec![(A, row("alpha", WidgetChildren::Leaf))], + next: None, + }; + assert_eq!( + surface.apply_page(&page), + Err(WidgetError::ParentCannotExpand) + ); + + let page = WidgetPage { + base_revision: WidgetRevision(1), + parent: Some(StableId(999)), + after: None, + rows: vec![(A, row("alpha", WidgetChildren::Leaf))], + next: None, + }; + assert_eq!(surface.apply_page(&page), Err(WidgetError::UnknownParent)); + } + + #[test] + fn unknown_after_cursor_refuses() { + let mut surface = surface_with_parent(); + let page = WidgetPage { + base_revision: WidgetRevision(3), + parent: Some(PARENT), + after: Some(B), + rows: vec![(A, row("alpha", WidgetChildren::Leaf))], + next: None, + }; + assert_eq!(surface.apply_page(&page), Err(WidgetError::UnknownAfter)); + } + + #[test] + fn page_row_budget_is_enforced() { + let mut surface = surface_with_parent(); + let rows: Vec<_> = (0..=MAX_PAGE_ROWS) + .map(|i| (StableId(100 + i as u64), row("r", WidgetChildren::Leaf))) + .collect(); + let page = WidgetPage { + base_revision: WidgetRevision(3), + parent: Some(PARENT), + after: None, + rows, + next: None, + }; + assert_eq!(surface.apply_page(&page), Err(WidgetError::PageTooLarge)); + } + + #[test] + fn orphan_rows_are_rejected_by_validate() { + let mut surface = surface_with_parent(); + // A second root whose child list references a missing row. + surface.roots = vec![PARENT, StableId(50)]; + surface.rows.insert( + StableId(50), + row("bad", WidgetChildren::Loaded(vec![StableId(51)])), + ); + assert_eq!( + surface.validate(), + Err(WidgetError::UnknownElement(StableId(51))) + ); + } +} diff --git a/src/app/dock/view.rs b/src/app/dock/view.rs index 1e8d8faec1..1f35adbf05 100644 --- a/src/app/dock/view.rs +++ b/src/app/dock/view.rs @@ -758,14 +758,28 @@ impl OpenCADStudio { crate::ui::dock::PanelId::Plugin(num) => { if let Some(panel_id) = self.plugin_panel_by_num.get(&num) { if let Some(state) = self.plugin_panels.get(panel_id) { - // A published scene surface (api v29) replaces the - // panel body with the host's native canvas; panels - // without a scene keep their exact legacy tree. - if let Some(scene) = state.owner_plugin_id.as_deref().and_then(|owner| { - self.panel_surfaces - .scene(owner, panel_id) - .map(|scene| (owner.to_owned(), scene)) - }) { + // A panel may own a scene AND a widget surface side + // by side (finding F1): the widget view wins the + // body when present, then the scene canvas, then + // the exact legacy tree. + let widget_ui = self.panel_widget_ui.get(panel_id); + if let (Some(owner), Some(surface)) = ( + state.owner_plugin_id.as_deref(), + state + .owner_plugin_id + .as_deref() + .and_then(|owner| self.panel_surfaces.widget(owner, panel_id)), + ) { + crate::ui::window::plugin_widgets::widget_view( + owner, panel_id, surface, widget_ui, + ) + } else if let Some(scene) = + state.owner_plugin_id.as_deref().and_then(|owner| { + self.panel_surfaces + .scene(owner, panel_id) + .map(|scene| (owner.to_owned(), scene)) + }) + { let (owner, scene) = scene; let preview = self.panel_event_router.drag_preview(panel_id); crate::ui::window::plugin_scene::scene_view( diff --git a/src/app/message.rs b/src/app/message.rs index 241b20e9ef..8e7266ff8d 100644 --- a/src/app/message.rs +++ b/src/app/message.rs @@ -537,6 +537,20 @@ pub enum Message { element: Option, pos: ocs_plugin_api::scene::Vec2, }, + /// A widget row was ACTIVATED on a plugin widget surface (api v29). + PanelWidgetNodeActivated { + owner: String, + panel: String, + node: ocs_plugin_api::scene::StableId, + }, + /// An expand affordance was toggled on a plugin widget surface; the + /// dispatch decides host-local toggle vs `NodeExpanded` notification + /// (only expanding an `Unloaded` row needs the plugin). + PanelWidgetExpandToggled { + owner: String, + panel: String, + node: ocs_plugin_api::scene::StableId, + }, /// Checkbox toggle in a plugin modal dialog control. PluginDialogBoolToggle(String, bool), /// Dropdown choice selection in a plugin modal dialog control. diff --git a/src/app/mod.rs b/src/app/mod.rs index e5b1b5114d..58b53ed716 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1646,6 +1646,13 @@ pub(super) struct OpenCADStudio { /// drag, move coalescing, settle/cancel; per-surface event identity. pub(crate) panel_event_router: crate::app::panel_events::PanelEventRouter, + /// Host-local widget view state per panel id (api v29): expansion and + /// selection stay host-local (finding F2's host-local law) — nothing + /// here is authoritative about the data. + pub(crate) panel_widget_ui: std::collections::BTreeMap< + String, + crate::ui::window::plugin_widgets::WidgetUiState, + >, /// Numeric mapping for PanelId::Plugin(u32). pub(crate) plugin_panel_ids: std::collections::HashMap, pub(crate) plugin_panel_by_num: std::collections::HashMap, @@ -3253,6 +3260,7 @@ impl OpenCADStudio { crate::app::panel_surfaces::PanelSurfaceStore::default(), panel_event_router: crate::app::panel_events::PanelEventRouter::new(), + panel_widget_ui: std::collections::BTreeMap::new(), plugin_panel_ids: std::collections::HashMap::new(), plugin_panel_by_num: std::collections::HashMap::new(), hyperlink_editor_handles: Vec::new(), diff --git a/src/app/panel_events.rs b/src/app/panel_events.rs index 78016331cc..e28e8add09 100644 --- a/src/app/panel_events.rs +++ b/src/app/panel_events.rs @@ -218,6 +218,29 @@ impl PanelEventRouter { ) } + /// Widget-tier notifications reuse the per-surface sequence for their + /// explicit identity: activation gestures and lazy-expansion requests + /// (expanding an `Unloaded` row asks the plugin for a page). + pub fn on_node_activated(&mut self, panel_id: &str, node: StableId) -> RoutedEvent { + let sequence = self.next_sequence(panel_id); + RoutedEvent { + panel_id: panel_id.to_owned(), + sequence, + event: SurfaceEvent::NodeActivated { node }, + } + } + + /// The one expansion case that is not host-local: expanding an + /// `Unloaded` row asks the plugin (the data source) for a page. + pub fn on_node_expanded(&mut self, panel_id: &str, node: StableId) -> RoutedEvent { + let sequence = self.next_sequence(panel_id); + RoutedEvent { + panel_id: panel_id.to_owned(), + sequence, + event: SurfaceEvent::NodeExpanded { node }, + } + } + /// Settle the active drag (whatever panel owns it): a `DragSettled` /// at the latest known position when started, or a silent drop when /// the drag never began. The single-pointer law: a new press steals diff --git a/src/app/panel_surfaces.rs b/src/app/panel_surfaces.rs index 7a706eaebe..0341bae28d 100644 --- a/src/app/panel_surfaces.rs +++ b/src/app/panel_surfaces.rs @@ -2,14 +2,16 @@ //! attachment; this store applies the revision rules of a publish and keeps //! no renderer state. -use ocs_plugin_api::scene::{PanelScene, SceneRevision}; -use ocs_plugin_api::scene::{PanelSurface, SurfaceReject, SurfaceRejectCode}; +use ocs_plugin_api::scene::{PanelScene, SceneRevision, SurfaceReject, SurfaceRejectCode}; /// Stored surface per panel id: strictly one authoritative record per -/// panel, owned by the authenticated plugin that published it. +/// panel, owned by the authenticated plugin that published it. A panel +/// owns ONE scene AND one widget surface side by side (finding F1: the +/// two kinds advance on independent revisions). #[derive(Debug, Default)] pub struct PanelSurfaceStore { scenes: std::collections::BTreeMap, + widgets: std::collections::BTreeMap, } #[derive(Debug, Clone, PartialEq)] @@ -18,6 +20,12 @@ struct SceneRecord { scene: PanelScene, } +#[derive(Debug, Clone, PartialEq)] +struct WidgetRecord { + owner_plugin_id: String, + surface: ocs_plugin_api::widget::WidgetSurface, +} + impl PanelSurfaceStore { /// Publish a scene for `panel_id` from the authenticated `plugin_id`. /// The caller has already resolved attachment (the panel is registered) @@ -28,7 +36,7 @@ impl PanelSurfaceStore { &mut self, plugin_id: &str, panel_id: &str, - surface: PanelSurface, + scene: PanelScene, ) -> Result { if plugin_id.is_empty() || panel_id.trim().is_empty() { return Err(SurfaceReject { @@ -36,7 +44,6 @@ impl PanelSurfaceStore { current_revision: None, }); } - let PanelSurface::Scene(scene) = surface; if scene.validate().is_err() { return Err(SurfaceReject { code: SurfaceRejectCode::InvalidSurface, @@ -146,6 +153,122 @@ impl PanelSurfaceStore { pub fn retain_owners(&mut self, mut keep: impl FnMut(&str) -> bool) { self.scenes .retain(|_, record| keep(&record.owner_plugin_id)); + self.widgets + .retain(|_, record| keep(&record.owner_plugin_id)); + } + + /// Publish (or replace) the panel's WIDGET surface (api v29, S05): + /// the same ownership/revision rules as scene publishes, on the + /// widget tier's independent revision space. + pub fn publish_widget( + &mut self, + plugin_id: &str, + panel_id: &str, + surface: ocs_plugin_api::widget::WidgetSurface, + ) -> Result { + use ocs_plugin_api::widget::{WidgetReject, WidgetRejectCode}; + if plugin_id.is_empty() || panel_id.trim().is_empty() { + return Err(WidgetReject { + code: WidgetRejectCode::Unattached, + current_revision: None, + }); + } + if surface.validate().is_err() { + return Err(WidgetReject { + code: WidgetRejectCode::InvalidSurface, + current_revision: None, + }); + } + if let Some(record) = self.widgets.get(panel_id) { + if record.owner_plugin_id != plugin_id { + return Err(WidgetReject { + code: WidgetRejectCode::OwnedByOther, + current_revision: Some(record.surface.revision), + }); + } + let head = record.surface.revision; + if surface.revision == head { + if surface == record.surface { + return Ok(head); // idempotent: identical at the head + } + return Err(WidgetReject { + code: WidgetRejectCode::NonMonotonicRevision, + current_revision: Some(head), + }); + } + if surface.revision < head { + return Err(WidgetReject { + code: WidgetRejectCode::NonMonotonicRevision, + current_revision: Some(head), + }); + } + } + let revision = surface.revision; + self.widgets.insert( + panel_id.to_string(), + WidgetRecord { + owner_plugin_id: plugin_id.to_string(), + surface, + }, + ); + Ok(revision) + } + + /// Install a bounded widget page atomically (the lazy-expansion and + /// paging primitive). Only a previously published widget surface can + /// be paged; ownership and revision rules match publishing. + pub fn install_widget_page( + &mut self, + plugin_id: &str, + panel_id: &str, + page: ocs_plugin_api::widget::WidgetPage, + ) -> Result { + use ocs_plugin_api::widget::{WidgetReject, WidgetRejectCode}; + if plugin_id.is_empty() || panel_id.trim().is_empty() { + return Err(WidgetReject { + code: WidgetRejectCode::Unattached, + current_revision: None, + }); + } + let Some(record) = self.widgets.get_mut(panel_id) else { + return Err(WidgetReject { + code: WidgetRejectCode::Unattached, + current_revision: None, + }); + }; + if record.owner_plugin_id != plugin_id { + return Err(WidgetReject { + code: WidgetRejectCode::OwnedByOther, + current_revision: Some(record.surface.revision), + }); + } + match record.surface.apply_page(&page) { + Ok(revision) => Ok(revision), + Err(ocs_plugin_api::widget::WidgetError::StaleBase) => Err(WidgetReject { + code: WidgetRejectCode::NonMonotonicRevision, + current_revision: Some(record.surface.revision), + }), + Err(_) => Err(WidgetReject { + code: WidgetRejectCode::InvalidSurface, + current_revision: None, + }), + } + } + + /// Ownership-checked widget read (api v29): a widget surface reads + /// back only for its authenticated owner. + pub fn widget( + &self, + plugin_id: &str, + panel_id: &str, + ) -> Option<&ocs_plugin_api::widget::WidgetSurface> { + if plugin_id.is_empty() { + return None; + } + self.widgets + .get(panel_id) + .filter(|record| record.owner_plugin_id == plugin_id) + .map(|record| &record.surface) } } @@ -176,7 +299,7 @@ mod tests { let mut store = PanelSurfaceStore::default(); let scene = one_rect_scene(7); assert_eq!( - store.publish(PLUGIN, PANEL, PanelSurface::Scene(scene.clone())), + store.publish(PLUGIN, PANEL, scene.clone()), Ok(SceneRevision(7)) ); assert_eq!(store.scene(PLUGIN, PANEL), Some(&scene)); @@ -186,22 +309,18 @@ mod tests { fn a_dead_owner_or_a_new_registration_forgets_the_scene() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(9))) + .publish(PLUGIN, PANEL, one_rect_scene(9)) .expect("first publish"); store.retain_owners(|owner| owner != PLUGIN); assert_eq!(store.scene(PLUGIN, PANEL), None); // A restarted plugin starts again from revision 1. assert_eq!( - store.publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(1))), + store.publish(PLUGIN, PANEL, one_rect_scene(1)), Ok(SceneRevision(1)) ); store.remove(PANEL); assert_eq!( - store.publish( - "other.plugin", - PANEL, - PanelSurface::Scene(one_rect_scene(1)) - ), + store.publish("other.plugin", PANEL, one_rect_scene(1)), Ok(SceneRevision(1)) ); } @@ -210,10 +329,10 @@ mod tests { fn identical_resurface_at_head_is_idempotent() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(3))) + .publish(PLUGIN, PANEL, one_rect_scene(3)) .expect("first publish"); assert_eq!( - store.publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(3))), + store.publish(PLUGIN, PANEL, one_rect_scene(3)), Ok(SceneRevision(3)) ); } @@ -222,14 +341,14 @@ mod tests { fn same_revision_different_content_is_refused_without_mutation() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(3))) + .publish(PLUGIN, PANEL, one_rect_scene(3)) .expect("first publish"); let mut changed = one_rect_scene(3); if let SceneElement::Rect { size, .. } = &mut changed.elements[0] { size.0[0] = 99.0; } assert_eq!( - store.publish(PLUGIN, PANEL, PanelSurface::Scene(changed)), + store.publish(PLUGIN, PANEL, changed), Err(SurfaceReject { code: SurfaceRejectCode::NonMonotonicRevision, current_revision: Some(SceneRevision(3)), @@ -241,10 +360,10 @@ mod tests { fn stale_revision_is_refused_with_the_stored_head() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(5))) + .publish(PLUGIN, PANEL, one_rect_scene(5)) .expect("first publish"); assert_eq!( - store.publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(4))), + store.publish(PLUGIN, PANEL, one_rect_scene(4)), Err(SurfaceReject { code: SurfaceRejectCode::NonMonotonicRevision, current_revision: Some(SceneRevision(5)), @@ -256,10 +375,10 @@ mod tests { fn advancing_revision_replaces_wholesale() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(5))) + .publish(PLUGIN, PANEL, one_rect_scene(5)) .expect("first publish"); assert_eq!( - store.publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(6))), + store.publish(PLUGIN, PANEL, one_rect_scene(6)), Ok(SceneRevision(6)) ); assert_eq!( @@ -272,14 +391,14 @@ mod tests { fn invalid_scene_is_refused_and_touches_nothing() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(5))) + .publish(PLUGIN, PANEL, one_rect_scene(5)) .expect("first publish"); let mut invalid = one_rect_scene(9); if let SceneElement::Rect { size, .. } = &mut invalid.elements[0] { size.0[1] = 0.0; // zero height: InvalidRect } assert_eq!( - store.publish(PLUGIN, PANEL, PanelSurface::Scene(invalid)), + store.publish(PLUGIN, PANEL, invalid), Err(SurfaceReject { code: SurfaceRejectCode::InvalidSurface, current_revision: None, @@ -295,14 +414,10 @@ mod tests { fn foreign_owner_is_refused_and_cannot_read() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(2))) + .publish(PLUGIN, PANEL, one_rect_scene(2)) .expect("first publish"); assert_eq!( - store.publish( - "other.plugin", - PANEL, - PanelSurface::Scene(one_rect_scene(3)) - ), + store.publish("other.plugin", PANEL, one_rect_scene(3)), Err(SurfaceReject { code: SurfaceRejectCode::OwnedByOther, current_revision: Some(SceneRevision(2)), @@ -320,14 +435,14 @@ mod tests { fn blank_identities_are_refused() { let mut store = PanelSurfaceStore::default(); assert!(matches!( - store.publish("", PANEL, PanelSurface::Scene(one_rect_scene(1))), + store.publish("", PANEL, one_rect_scene(1)), Err(SurfaceReject { code: SurfaceRejectCode::Unattached, .. }) )); assert!(matches!( - store.publish(PLUGIN, " ", PanelSurface::Scene(one_rect_scene(1))), + store.publish(PLUGIN, " ", one_rect_scene(1)), Err(SurfaceReject { code: SurfaceRejectCode::Unattached, .. @@ -347,7 +462,7 @@ mod tests { fn patch_applies_atomically_and_advances_one_revision() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(5))) + .publish(PLUGIN, PANEL, one_rect_scene(5)) .expect("publish"); let patch = ocs_plugin_api::scene::ScenePatch { base_revision: ocs_plugin_api::scene::SceneRevision(5), @@ -382,7 +497,7 @@ mod tests { fn stale_base_patch_refuses_with_the_head() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(5))) + .publish(PLUGIN, PANEL, one_rect_scene(5)) .expect("publish"); let patch = ocs_plugin_api::scene::ScenePatch { base_revision: ocs_plugin_api::scene::SceneRevision(4), @@ -406,7 +521,7 @@ mod tests { fn foreign_patch_is_refused() { let mut store = PanelSurfaceStore::default(); store - .publish(PLUGIN, PANEL, PanelSurface::Scene(one_rect_scene(2))) + .publish(PLUGIN, PANEL, one_rect_scene(2)) .expect("publish"); let patch = ocs_plugin_api::scene::ScenePatch { base_revision: ocs_plugin_api::scene::SceneRevision(2), diff --git a/src/app/plugin_host/classes.rs b/src/app/plugin_host/classes.rs index d9689e951d..135689265e 100644 --- a/src/app/plugin_host/classes.rs +++ b/src/app/plugin_host/classes.rs @@ -456,7 +456,7 @@ pub(in crate::app) fn rows_from_entries( "parameter {:?} of class {:?} is declared a Real; the record row \ carries {other:?}", row.name, binding.class_id - )) + )); } }, PluginClassParameterKind::Integer => match &value_entry.value { @@ -468,7 +468,7 @@ pub(in crate::app) fn rows_from_entries( "parameter {:?} of class {:?} is declared an Integer; the record \ row carries {other:?}", row.name, binding.class_id - )) + )); } }, PluginClassParameterKind::Text => match &value_entry.value { @@ -478,7 +478,7 @@ pub(in crate::app) fn rows_from_entries( "parameter {:?} of class {:?} is declared Text; the record row \ carries {other:?}", row.name, binding.class_id - )) + )); } }, }; diff --git a/src/app/plugin_host/host_api.rs b/src/app/plugin_host/host_api.rs index 3c697b54fa..aa75495d9e 100644 --- a/src/app/plugin_host/host_api.rs +++ b/src/app/plugin_host/host_api.rs @@ -471,43 +471,59 @@ impl HostApi for HostSession<'_> { /// V29: publish the panel's scene for the authenticated owner. Attachment /// and ownership resolve here; the store applies the revision rules and /// checks the owner again. + fn panel_surface_publish_for_plugin( &mut self, plugin_id: &str, panel_id: &str, - surface: ocs_plugin_api::scene::PanelSurface, + scene: ocs_plugin_api::scene::PanelScene, ) -> Result { - use ocs_plugin_api::scene::SurfaceRejectCode; - if plugin_id.is_empty() || panel_id.trim().is_empty() { - return Err(ocs_plugin_api::scene::SurfaceReject { - code: SurfaceRejectCode::Unattached, - current_revision: None, - }); - } - // Alias-resolve, then enforce F5's honest distinctions: a panel this - // plugin never registered is `Unattached`; one registered by a - // different plugin is `OwnedByOther`. - let Some(resolved) = resolve_toggle_panel_id(self.app, panel_id) else { - return Err(ocs_plugin_api::scene::SurfaceReject { - code: SurfaceRejectCode::Unattached, + let resolved = self + .resolve_surface_panel(plugin_id, panel_id) + .map_err(|code| ocs_plugin_api::scene::SurfaceReject { + code, current_revision: None, - }); - }; - let Some(registered) = self.app.plugin_panels.get(&resolved) else { - return Err(ocs_plugin_api::scene::SurfaceReject { - code: SurfaceRejectCode::Unattached, + })?; + self.app.panel_surfaces.publish(plugin_id, &resolved, scene) + } + + /// V29 (additive): publish the panel's WIDGET surface from the + /// authenticated transport owner; the widget tier's independent + /// revision space. + fn panel_widget_publish_for_plugin( + &mut self, + plugin_id: &str, + panel_id: &str, + surface: ocs_plugin_api::widget::WidgetSurface, + ) -> Result { + let resolved = self + .resolve_surface_panel(plugin_id, panel_id) + .map_err(|code| ocs_plugin_api::widget::WidgetReject { + code: code.into(), current_revision: None, - }); - }; - if registered.owner_plugin_id.as_deref() != Some(plugin_id) { - return Err(ocs_plugin_api::scene::SurfaceReject { - code: SurfaceRejectCode::OwnedByOther, + })?; + self.app + .panel_surfaces + .publish_widget(plugin_id, &resolved, surface) + } + + /// V29 (additive): install a bounded widget page atomically from the + /// authenticated transport owner (lazy expansion / paging). + fn panel_surface_page_for_plugin( + &mut self, + plugin_id: &str, + panel_id: &str, + page: ocs_plugin_api::widget::WidgetPage, + ) -> Result { + let resolved = self + .resolve_surface_panel(plugin_id, panel_id) + .map_err(|code| ocs_plugin_api::widget::WidgetReject { + code: code.into(), current_revision: None, - }); - } + })?; self.app .panel_surfaces - .publish(plugin_id, &resolved, surface) + .install_widget_page(plugin_id, &resolved, page) } /// V29 (additive): patch the panel's stored scene atomically from the diff --git a/src/app/plugin_host/interactive.rs b/src/app/plugin_host/interactive.rs index c8130b440f..ae6dfd97a8 100644 --- a/src/app/plugin_host/interactive.rs +++ b/src/app/plugin_host/interactive.rs @@ -10,9 +10,7 @@ fn plugin_input_kind_to_host( ocs_plugin_api::host::InteractiveInputKind::SingleToken => { crate::command::InputKind::SingleToken } - ocs_plugin_api::host::InteractiveInputKind::FreeText => { - crate::command::InputKind::FreeText - } + ocs_plugin_api::host::InteractiveInputKind::FreeText => crate::command::InputKind::FreeText, } } @@ -209,7 +207,10 @@ impl PluginProcessInteractiveAdapter { fn refresh(&mut self) { self.prompt = self.process.get_prompt(self.command_id).ok(); - self.input_kind = self.process.get_input_kind(self.command_id).unwrap_or_default(); + self.input_kind = self + .process + .get_input_kind(self.command_id) + .unwrap_or_default(); self.needs_entity_pick = self.process.needs_entity_pick(self.command_id).ok(); self.is_selection_gathering = self.process.is_selection_gathering(self.command_id).ok(); self.accepts_drag_selection = self.process.accepts_drag_selection(self.command_id).ok(); @@ -446,7 +447,10 @@ impl crate::command::CadCommand for PluginProcessInteractiveAdapter { use ocs_plugin_api::ipc::protocol::InteractiveEvent; let result = self .process - .interactive_event(self.command_id, InteractiveEvent::TextInput(text.to_string())) + .interactive_event( + self.command_id, + InteractiveEvent::TextInput(text.to_string()), + ) .map(plugin_step_to_result) .unwrap_or(crate::command::CmdResult::Cancel); if matches!( diff --git a/src/app/plugin_host/mod.rs b/src/app/plugin_host/mod.rs index 6593bdf06a..58547e7cdb 100644 --- a/src/app/plugin_host/mod.rs +++ b/src/app/plugin_host/mod.rs @@ -82,11 +82,11 @@ mod validation; mod xrecords; pub(in crate::app) use self::classes::{ - find_design_record_entries, resolve_plugin_class_binding, rows_from_entries, rows_from_schema, - PluginClassInstanceBinding, + PluginClassInstanceBinding, find_design_record_entries, resolve_plugin_class_binding, + rows_from_entries, rows_from_schema, }; -pub(in crate::app) use self::interactive::convert_preview_wires; pub(crate) use self::interactive::PluginProcessInteractiveAdapter; +pub(in crate::app) use self::interactive::convert_preview_wires; pub use self::quad::plugin_quad_panels; use self::validation::resolve_toggle_panel_id; @@ -121,6 +121,30 @@ impl<'a> HostSession<'a> { } } + /// Shared attachment/ownership resolution for the surface tier: an + /// unregistered alias is `Unattached`, a foreign-registered panel is + /// `OwnedByOther`. Lives on the session (not the trait) — callers map + /// the code into their own tier's rejection type. + fn resolve_surface_panel( + &self, + plugin_id: &str, + panel_id: &str, + ) -> Result { + if plugin_id.is_empty() || panel_id.trim().is_empty() { + return Err(ocs_plugin_api::scene::SurfaceRejectCode::Unattached); + } + let Some(resolved) = resolve_toggle_panel_id(self.app, panel_id) else { + return Err(ocs_plugin_api::scene::SurfaceRejectCode::Unattached); + }; + let Some(registered) = self.app.plugin_panels.get(&resolved) else { + return Err(ocs_plugin_api::scene::SurfaceRejectCode::Unattached); + }; + if registered.owner_plugin_id.as_deref() != Some(plugin_id) { + return Err(ocs_plugin_api::scene::SurfaceRejectCode::OwnedByOther); + } + Ok(resolved) + } + pub fn document_path(&self, tab_id: u64) -> Option { self.app .tabs diff --git a/src/app/plugin_host/plugin_host_tests.rs b/src/app/plugin_host/plugin_host_tests.rs index 0f7bb7ce81..1c1a7b859b 100644 --- a/src/app/plugin_host/plugin_host_tests.rs +++ b/src/app/plugin_host/plugin_host_tests.rs @@ -26,12 +26,14 @@ fn linetype_operations_follow_the_shared_rules() { app.tabs[0].is_start = false; let mut host = HostSession::new(&mut app, 0); - assert!(host - .linetype_operation(create("Gap First", &[-1.0, 1.0])) - .is_err()); - assert!(host - .linetype_operation(create("Comma,Name", &[1.0, -1.0])) - .is_err()); + assert!( + host.linetype_operation(create("Gap First", &[-1.0, 1.0])) + .is_err() + ); + assert!( + host.linetype_operation(create("Comma,Name", &[1.0, -1.0])) + .is_err() + ); assert!( host.linetype_operation(create("dashed", &[1.0, -1.0])) .is_err(), @@ -344,10 +346,11 @@ fn nested_insert_attribute_crud_uses_parent_storage_and_undo() { assert!(matches!(host.host_model_entity(attribute_handle), Some(EntityType::AttributeEntity(value)) if value.value == "PN-101")); let view = ocs_plugin_api::shm::DocumentViewDataV4::from(host.document()); - assert!(view - .entities - .iter() - .any(|entity| entity.handle == attribute_handle.value())); + assert!( + view.entities + .iter() + .any(|entity| entity.handle == attribute_handle.value()) + ); let mut changed = host.host_model_entity(attribute_handle).unwrap(); let EntityType::AttributeEntity(value) = &mut changed else { @@ -426,17 +429,19 @@ fn entity_transaction_validates_before_mutation_and_undoes_as_one_step() { } let mut invalid = b.clone(); invalid.common_mut().owner_handle = Handle::new(99999); - assert!(host - .update_entities_transaction("Move points", vec![a.clone(), invalid]) - .is_err()); + assert!( + host.update_entities_transaction("Move points", vec![a.clone(), invalid]) + .is_err() + ); let mut invalid_geometry = b.clone(); if let EntityType::Point(p) = &mut invalid_geometry { p.location.x = f64::NAN; } - assert!(host - .update_entities_transaction("Move points", vec![a.clone(), invalid_geometry]) - .unwrap_err() - .contains("Point.location")); + assert!( + host.update_entities_transaction("Move points", vec![a.clone(), invalid_geometry]) + .unwrap_err() + .contains("Point.location") + ); assert_eq!(host.app.tabs[0].history.undo_stack.len(), 0); assert!( matches!(host.document().get_entity(first), Some(EntityType::Point(p)) if p.location.x == 1.0) @@ -508,9 +513,11 @@ fn run_mesh_lifecycle(case: &MeshCase) { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last_output = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); @@ -715,9 +722,13 @@ fn run_mesh_lifecycle(case: &MeshCase) { ); } let (first_patch, _) = case.rejects[0]; - dispatch(&mut host, &format!( + dispatch( + &mut host, + &format!( "PY_EVAL ocs.update_many('Atomic', [{{'handle':{h}, 'layer':'Other'}}, {{'handle':{h}, {first_patch}}}])", - h = handle.value())); + h = handle.value() + ), + ); assert_eq!(host.document().get_entity(handle), Some(&expected)); let dwg = crate::io::load_bytes( @@ -801,10 +812,12 @@ fn run_mesh_lifecycle(case: &MeshCase) { .unwrap(), ), ] { - assert!(crate::io::load_bytes(name, bytes) - .unwrap() - .get_entity(handle) - .is_none()); + assert!( + crate::io::load_bytes(name, bytes) + .unwrap() + .get_entity(handle) + .is_none() + ); } drop(process); drop(host); @@ -834,88 +847,124 @@ fn run_mesh_lifecycle(case: &MeshCase) { #[test] fn staged_python_polygon_mesh_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!( - "verts = [{'location': P(i, j, 0.0)} for i in range(3) for j in range(3)]\n", - "doc.create_entity('PolygonMesh', m_vertex_count=3, n_vertex_count=3, vertices=verts)\n"), - edit: concat!( - "mesh = doc.entities[HANDLE]\n", - "verts = mesh.vertices\n", - "verts[4]['location'] = P(1.0, 1.0, 2.5)\n", - "with doc.transaction('Edit mesh'):\n", - " mesh.vertices = verts\n", - " mesh.m_smooth_density = 6\n", - " mesh.n_smooth_density = 6\n", - " mesh.smooth_type = 'Cubic'\n", - "doc.selection = [mesh]\n"), - rejects: &[ - ("'m_vertex_count':4", "requires 12"), - ("'n_vertex_count':1", "at least 2"), - ("'m_smooth_density':-1", "non-negative"), - ("'elevation':float('nan')", "finite"), - ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), - ("'vertices':[{'location':{'x':float('nan'),'y':0.0,'z':0.0}}]*9", "finite"), - ("'smooth_type':'Spline'", "unsupported"), - ], - is_kind: |entity| matches!(entity, EntityType::PolygonMesh(_)), - digest: |entity| match entity { - EntityType::PolygonMesh(m) => format!("{}x{} v{} z{} d{}/{} {:?}", m.m_vertex_count, m.n_vertex_count, - m.vertices.len(), m.vertices[4].location.z, m.m_smooth_density, m.n_smooth_density, m.smooth_type), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::PolygonMesh(m) = entity { m.vertices[0].location.z = 1.0; }, - expect_created: "3x3 v9 z0 d0/0 NoSmooth", - expect_edited: "3x3 v9 z2.5 d6/6 Cubic", - expect_reedited: "3x3 v9 z2.5 d6/6 Cubic", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: concat!( + "verts = [{'location': P(i, j, 0.0)} for i in range(3) for j in range(3)]\n", + "doc.create_entity('PolygonMesh', m_vertex_count=3, n_vertex_count=3, vertices=verts)\n" + ), + edit: concat!( + "mesh = doc.entities[HANDLE]\n", + "verts = mesh.vertices\n", + "verts[4]['location'] = P(1.0, 1.0, 2.5)\n", + "with doc.transaction('Edit mesh'):\n", + " mesh.vertices = verts\n", + " mesh.m_smooth_density = 6\n", + " mesh.n_smooth_density = 6\n", + " mesh.smooth_type = 'Cubic'\n", + "doc.selection = [mesh]\n" + ), + rejects: &[ + ("'m_vertex_count':4", "requires 12"), + ("'n_vertex_count':1", "at least 2"), + ("'m_smooth_density':-1", "non-negative"), + ("'elevation':float('nan')", "finite"), + ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), + ( + "'vertices':[{'location':{'x':float('nan'),'y':0.0,'z':0.0}}]*9", + "finite", + ), + ("'smooth_type':'Spline'", "unsupported"), + ], + is_kind: |entity| matches!(entity, EntityType::PolygonMesh(_)), + digest: |entity| match entity { + EntityType::PolygonMesh(m) => format!( + "{}x{} v{} z{} d{}/{} {:?}", + m.m_vertex_count, + m.n_vertex_count, + m.vertices.len(), + m.vertices[4].location.z, + m.m_smooth_density, + m.n_smooth_density, + m.smooth_type + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::PolygonMesh(m) = entity { + m.vertices[0].location.z = 1.0; + } + }, + expect_created: "3x3 v9 z0 d0/0 NoSmooth", + expect_edited: "3x3 v9 z2.5 d6/6 Cubic", + expect_reedited: "3x3 v9 z2.5 d6/6 Cubic", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] fn staged_python_polyface_mesh_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!( - "verts = [{'location': P(0.0, 0.0, 0.0)}, {'location': P(4.0, 0.0, 0.0)},\n", - " {'location': P(4.0, 4.0, 0.0)}, {'location': P(0.0, 4.0, 0.0)}]\n", - "faces = [{'index1': 1, 'index2': 2, 'index3': 3}, {'index1': 1, 'index2': 3, 'index3': 4}]\n", - "doc.create_entity('PolyfaceMesh', vertices=verts, faces=faces)\n"), - edit: concat!( - "mesh = doc.entities[HANDLE]\n", - "verts = mesh.vertices\n", - "verts[2]['location'] = P(4.0, 4.0, 3.0)\n", - "verts.append({'location': P(2.0, 6.0, 0.0)})\n", - "faces = mesh.faces\n", - "faces.append({'index1': 3, 'index2': -4, 'index3': 5})\n", - "with doc.transaction('Edit mesh'):\n", - " mesh.vertices = verts\n", - " mesh.faces = faces\n", - "doc.selection = [mesh]\n"), - rejects: &[ - ("'faces':[{'index1':1,'index2':2,'index3':9}]", "references vertex 9"), - ("'faces':[{'index1':1,'index2':2}]", "at least 3 vertex indices"), - ("'faces':[]", "at least 1 face"), - ("'vertices':[{'location':{'x':0.0,'y':0.0,'z':0.0}}]", "at least 3"), - ("'thickness':float('inf')", "finite"), - ("'seqend_handle':5", "read-only"), - ], - is_kind: |entity| matches!(entity, EntityType::PolyfaceMesh(_)), - digest: |entity| match entity { - EntityType::PolyfaceMesh(m) => format!("v{} f{} z{} last {:?}", m.vertices.len(), m.faces.len(), - m.vertices[2].location.z, - m.faces.last().map(|f| (f.index1, f.index2, f.index3))), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::PolyfaceMesh(m) = entity { m.vertices[0].location.z = 1.0; }, - expect_created: "v4 f2 z0 last Some((1, 3, 4))", - expect_edited: "v5 f3 z3 last Some((3, -4, 5))", - expect_reedited: "v5 f3 z3 last Some((3, -4, 5))", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: concat!( + "verts = [{'location': P(0.0, 0.0, 0.0)}, {'location': P(4.0, 0.0, 0.0)},\n", + " {'location': P(4.0, 4.0, 0.0)}, {'location': P(0.0, 4.0, 0.0)}]\n", + "faces = [{'index1': 1, 'index2': 2, 'index3': 3}, {'index1': 1, 'index2': 3, 'index3': 4}]\n", + "doc.create_entity('PolyfaceMesh', vertices=verts, faces=faces)\n" + ), + edit: concat!( + "mesh = doc.entities[HANDLE]\n", + "verts = mesh.vertices\n", + "verts[2]['location'] = P(4.0, 4.0, 3.0)\n", + "verts.append({'location': P(2.0, 6.0, 0.0)})\n", + "faces = mesh.faces\n", + "faces.append({'index1': 3, 'index2': -4, 'index3': 5})\n", + "with doc.transaction('Edit mesh'):\n", + " mesh.vertices = verts\n", + " mesh.faces = faces\n", + "doc.selection = [mesh]\n" + ), + rejects: &[ + ( + "'faces':[{'index1':1,'index2':2,'index3':9}]", + "references vertex 9", + ), + ( + "'faces':[{'index1':1,'index2':2}]", + "at least 3 vertex indices", + ), + ("'faces':[]", "at least 1 face"), + ( + "'vertices':[{'location':{'x':0.0,'y':0.0,'z':0.0}}]", + "at least 3", + ), + ("'thickness':float('inf')", "finite"), + ("'seqend_handle':5", "read-only"), + ], + is_kind: |entity| matches!(entity, EntityType::PolyfaceMesh(_)), + digest: |entity| match entity { + EntityType::PolyfaceMesh(m) => format!( + "v{} f{} z{} last {:?}", + m.vertices.len(), + m.faces.len(), + m.vertices[2].location.z, + m.faces.last().map(|f| (f.index1, f.index2, f.index3)) + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::PolyfaceMesh(m) = entity { + m.vertices[0].location.z = 1.0; + } + }, + expect_created: "v4 f2 z0 last Some((1, 3, 4))", + expect_edited: "v5 f3 z3 last Some((3, -4, 5))", + expect_reedited: "v5 f3 z3 last Some((3, -4, 5))", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] @@ -980,40 +1029,52 @@ fn staged_python_mesh_lifecycle_over_real_ipc() { #[test] fn staged_python_helix_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!( - "doc.create_entity('Helix', axis_base_point=P(0.0, 0.0, 0.0), axis_vector=P(0.0, 0.0, 1.0),\n", - " start_point=P(5.0, 0.0, 0.0), radius=5.0, turns=3.0, turn_height=2.0)\n"), - edit: concat!( - "helix = doc.entities[HANDLE]\n", - "with doc.transaction('Edit helix'):\n", - " helix.turns = 5.0\n", - " helix.handedness = False\n", - "doc.selection = [helix]\n"), - rejects: &[ - ("'radius':0.0", "greater than zero"), - ("'turns':-1.0", "greater than zero"), - ("'turn_height':float('nan')", "greater than zero"), - ("'axis_vector':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), - ("'start_point':{'x':0.0,'y':0.0,'z':3.0}", "on the axis"), - ("'spline':{}", "read-only"), - ("'major_version':1", "read-only"), - ], - is_kind: |entity| matches!(entity, EntityType::Helix(_)), - digest: |entity| match entity { - EntityType::Helix(h) => format!("r{} t{} h{} endz{:.1} ccw{} cp{}", h.radius, h.turns, h.turn_height, - h.spline.control_points.last().map_or(f64::NAN, |p| p.z), h.handedness, - !h.spline.control_points.is_empty()), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::Helix(h) = entity { h.turns = 6.0; }, - expect_created: "r5 t3 h2 endz6.0 ccwtrue cptrue", - expect_edited: "r5 t5 h2 endz10.0 ccwfalse cptrue", - expect_reedited: "r5 t6 h2 endz10.0 ccwfalse cptrue", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: concat!( + "doc.create_entity('Helix', axis_base_point=P(0.0, 0.0, 0.0), axis_vector=P(0.0, 0.0, 1.0),\n", + " start_point=P(5.0, 0.0, 0.0), radius=5.0, turns=3.0, turn_height=2.0)\n" + ), + edit: concat!( + "helix = doc.entities[HANDLE]\n", + "with doc.transaction('Edit helix'):\n", + " helix.turns = 5.0\n", + " helix.handedness = False\n", + "doc.selection = [helix]\n" + ), + rejects: &[ + ("'radius':0.0", "greater than zero"), + ("'turns':-1.0", "greater than zero"), + ("'turn_height':float('nan')", "greater than zero"), + ("'axis_vector':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), + ("'start_point':{'x':0.0,'y':0.0,'z':3.0}", "on the axis"), + ("'spline':{}", "read-only"), + ("'major_version':1", "read-only"), + ], + is_kind: |entity| matches!(entity, EntityType::Helix(_)), + digest: |entity| match entity { + EntityType::Helix(h) => format!( + "r{} t{} h{} endz{:.1} ccw{} cp{}", + h.radius, + h.turns, + h.turn_height, + h.spline.control_points.last().map_or(f64::NAN, |p| p.z), + h.handedness, + !h.spline.control_points.is_empty() + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::Helix(h) = entity { + h.turns = 6.0; + } + }, + expect_created: "r5 t3 h2 endz6.0 ccwtrue cptrue", + expect_edited: "r5 t5 h2 endz10.0 ccwfalse cptrue", + expect_reedited: "r5 t6 h2 endz10.0 ccwfalse cptrue", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] @@ -1022,92 +1083,129 @@ fn staged_python_raster_image_lifecycle_over_real_ipc() { .save(std::env::temp_dir().join("ocs_raster_test.png")) .unwrap(); run_mesh_lifecycle(&MeshCase { - create: concat!( - "doc.create_entity('RasterImage', file_path='TMPDIR/ocs_raster_test.png',\n", - " insertion_point=P(10.0, 20.0, 0.0), u_vector=P(0.5, 0.0, 0.0), v_vector=P(0.0, 0.5, 0.0))\n"), - edit: concat!( - "img = doc.entities[HANDLE]\n", - "cb = img.clip_boundary\n", - "cb['vertices'] = [{'x': 1.0, 'y': 1.0}, {'x': 7.0, 'y': 3.0}]\n", - "with doc.transaction('Edit image'):\n", - " img.insertion_point = (12.0, 22.0, 0.0)\n", - " img.u_vector = (1.0, 0.0, 0.0)\n", - " img.brightness = 70\n", - " img.contrast = 40\n", - " img.fade = 10\n", - " img.clip_boundary = cb\n", - " img.clipping_enabled = True\n", - "doc.selection = [img]\n"), - rejects: &[ - ("'file_path':'other.png'", "fixed at creation"), - ("'brightness':101", "within 0..=100"), - ("'u_vector':{'x':0.0,'y':0.0,'z':0.0}", "not parallel"), - ("'v_vector':{'x':2.0,'y':0.0,'z':0.0}", "not parallel"), - ("'size':{'x':5.0,'y':5.0}", "read-only"), - ("'definition_handle':5", "read-only"), - ("'flags':64", "unknown or out-of-range bits"), - ("'clip_boundary':{'vertices':[]}", "at least 2"), - ], - is_kind: |entity| matches!(entity, EntityType::RasterImage(_)), - digest: |entity| match entity { - EntityType::RasterImage(i) => format!("{} {:.1},{:.1} u{:.1} b{} c{} f{} clip{} n{} {}x{} def{}", - std::path::Path::new(&i.file_path).file_name().unwrap().to_string_lossy(), - i.insertion_point.x, i.insertion_point.y, i.u_vector.x, i.brightness, i.contrast, i.fade, - i.clipping_enabled, i.clip_boundary.vertices.len(), i.size.x, i.size.y, i.definition_handle.is_some()), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::RasterImage(i) = entity { i.brightness = 80; }, - expect_created: "ocs_raster_test.png 10.0,20.0 u0.5 b50 c50 f0 clipfalse n2 8x4 deftrue", - expect_edited: "ocs_raster_test.png 12.0,22.0 u1.0 b70 c40 f10 cliptrue n2 8x4 deftrue", - expect_reedited: "ocs_raster_test.png 12.0,22.0 u1.0 b80 c40 f10 cliptrue n2 8x4 deftrue", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: concat!( + "doc.create_entity('RasterImage', file_path='TMPDIR/ocs_raster_test.png',\n", + " insertion_point=P(10.0, 20.0, 0.0), u_vector=P(0.5, 0.0, 0.0), v_vector=P(0.0, 0.5, 0.0))\n" + ), + edit: concat!( + "img = doc.entities[HANDLE]\n", + "cb = img.clip_boundary\n", + "cb['vertices'] = [{'x': 1.0, 'y': 1.0}, {'x': 7.0, 'y': 3.0}]\n", + "with doc.transaction('Edit image'):\n", + " img.insertion_point = (12.0, 22.0, 0.0)\n", + " img.u_vector = (1.0, 0.0, 0.0)\n", + " img.brightness = 70\n", + " img.contrast = 40\n", + " img.fade = 10\n", + " img.clip_boundary = cb\n", + " img.clipping_enabled = True\n", + "doc.selection = [img]\n" + ), + rejects: &[ + ("'file_path':'other.png'", "fixed at creation"), + ("'brightness':101", "within 0..=100"), + ("'u_vector':{'x':0.0,'y':0.0,'z':0.0}", "not parallel"), + ("'v_vector':{'x':2.0,'y':0.0,'z':0.0}", "not parallel"), + ("'size':{'x':5.0,'y':5.0}", "read-only"), + ("'definition_handle':5", "read-only"), + ("'flags':64", "unknown or out-of-range bits"), + ("'clip_boundary':{'vertices':[]}", "at least 2"), + ], + is_kind: |entity| matches!(entity, EntityType::RasterImage(_)), + digest: |entity| match entity { + EntityType::RasterImage(i) => format!( + "{} {:.1},{:.1} u{:.1} b{} c{} f{} clip{} n{} {}x{} def{}", + std::path::Path::new(&i.file_path) + .file_name() + .unwrap() + .to_string_lossy(), + i.insertion_point.x, + i.insertion_point.y, + i.u_vector.x, + i.brightness, + i.contrast, + i.fade, + i.clipping_enabled, + i.clip_boundary.vertices.len(), + i.size.x, + i.size.y, + i.definition_handle.is_some() + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::RasterImage(i) = entity { + i.brightness = 80; + } + }, + expect_created: "ocs_raster_test.png 10.0,20.0 u0.5 b50 c50 f0 clipfalse n2 8x4 deftrue", + expect_edited: "ocs_raster_test.png 12.0,22.0 u1.0 b70 c40 f10 cliptrue n2 8x4 deftrue", + expect_reedited: "ocs_raster_test.png 12.0,22.0 u1.0 b80 c40 f10 cliptrue n2 8x4 deftrue", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] fn staged_python_wipeout_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!( - "doc.create_entity('Wipeout', insertion_point=P(0.0, 0.0, 0.0),\n", - " u_vector=P(10.0, 0.0, 0.0), v_vector=P(0.0, 6.0, 0.0))\n"), - edit: concat!( - "w = doc.entities[HANDLE]\n", - "with doc.transaction('Edit wipeout'):\n", - " w.clip_type = 'Polygonal'\n", - " w.clip_boundary_vertices = [{'x': -0.5, 'y': -0.5}, {'x': 0.5, 'y': -0.5}, {'x': 0.0, 'y': 0.5}]\n", - " w.insertion_point = (2.0, 3.0, 0.0)\n", - " w.clip_mode = 'Inside'\n", - "doc.selection = [w]\n"), - rejects: &[ - ("'clip_boundary_vertices':[{'x':0.0,'y':0.0}]", "at least 3"), - ("'clip_type':'Rectangular'", "exactly 2"), - ("'u_vector':{'x':0.0,'y':0.0,'z':0.0}", "not parallel"), - ("'brightness':200", "within 0..=100"), - ("'size':{'x':0.0,'y':1.0}", "greater than zero"), - ("'insertion_point':{'x':float('nan'),'y':0.0,'z':0.0}", "finite"), - ("'definition_handle':5", "read-only"), - ("'clip_type':'Circle'", "unsupported"), - ], - is_kind: |entity| matches!(entity, EntityType::Wipeout(_)), - digest: |entity| match entity { - EntityType::Wipeout(w) => format!("{:?} {:?} n{} at{:.1},{:.1} u{:.1} v{:.1}", w.clip_type, w.clip_mode, - w.clip_boundary_vertices.len(), w.insertion_point.x, w.insertion_point.y, w.u_vector.x, w.v_vector.y), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::Wipeout(w) = entity { w.u_vector.x = 12.0; }, - expect_created: "Rectangular Outside n2 at0.0,0.0 u10.0 v6.0", - expect_edited: "Polygonal Inside n3 at2.0,3.0 u10.0 v6.0", - expect_reedited: "Polygonal Inside n3 at2.0,3.0 u12.0 v6.0", - expect_edited_dwg: "", - expect_reedited_dwg: "", - // DXF writes a polygonal boundary closed (the first vertex - // again at the end), and reads it back that way. - expect_edited_dxf: "Polygonal Inside n4 at2.0,3.0 u10.0 v6.0", - expect_reedited_dxf: "Polygonal Inside n4 at2.0,3.0 u12.0 v6.0", - }); + create: concat!( + "doc.create_entity('Wipeout', insertion_point=P(0.0, 0.0, 0.0),\n", + " u_vector=P(10.0, 0.0, 0.0), v_vector=P(0.0, 6.0, 0.0))\n" + ), + edit: concat!( + "w = doc.entities[HANDLE]\n", + "with doc.transaction('Edit wipeout'):\n", + " w.clip_type = 'Polygonal'\n", + " w.clip_boundary_vertices = [{'x': -0.5, 'y': -0.5}, {'x': 0.5, 'y': -0.5}, {'x': 0.0, 'y': 0.5}]\n", + " w.insertion_point = (2.0, 3.0, 0.0)\n", + " w.clip_mode = 'Inside'\n", + "doc.selection = [w]\n" + ), + rejects: &[ + ("'clip_boundary_vertices':[{'x':0.0,'y':0.0}]", "at least 3"), + ("'clip_type':'Rectangular'", "exactly 2"), + ("'u_vector':{'x':0.0,'y':0.0,'z':0.0}", "not parallel"), + ("'brightness':200", "within 0..=100"), + ("'size':{'x':0.0,'y':1.0}", "greater than zero"), + ( + "'insertion_point':{'x':float('nan'),'y':0.0,'z':0.0}", + "finite", + ), + ("'definition_handle':5", "read-only"), + ("'clip_type':'Circle'", "unsupported"), + ], + is_kind: |entity| matches!(entity, EntityType::Wipeout(_)), + digest: |entity| match entity { + EntityType::Wipeout(w) => format!( + "{:?} {:?} n{} at{:.1},{:.1} u{:.1} v{:.1}", + w.clip_type, + w.clip_mode, + w.clip_boundary_vertices.len(), + w.insertion_point.x, + w.insertion_point.y, + w.u_vector.x, + w.v_vector.y + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::Wipeout(w) = entity { + w.u_vector.x = 12.0; + } + }, + expect_created: "Rectangular Outside n2 at0.0,0.0 u10.0 v6.0", + expect_edited: "Polygonal Inside n3 at2.0,3.0 u10.0 v6.0", + expect_reedited: "Polygonal Inside n3 at2.0,3.0 u12.0 v6.0", + expect_edited_dwg: "", + expect_reedited_dwg: "", + // DXF writes a polygonal boundary closed (the first vertex + // again at the end), and reads it back that way. + expect_edited_dxf: "Polygonal Inside n4 at2.0,3.0 u10.0 v6.0", + expect_reedited_dxf: "Polygonal Inside n4 at2.0,3.0 u12.0 v6.0", + }); } #[test] @@ -1227,41 +1325,49 @@ fn staged_python_viewport_lifecycle_over_real_ipc() { #[test] fn staged_python_view_border_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!( - "doc.create_entity('ViewBorder', min=[0.0, 0.0], max=[40.0, 30.0], center=[20.0, 15.0], scale=1.0,\n", - " active_viewport=VIEWPORTHANDLE, scale_handle=SCALEHANDLE)\n"), - edit: concat!( - "vb = doc.entities[HANDLE]\n", - "with doc.transaction('Edit view border'):\n", - " vb.max = [60.0, 45.0]\n", - " vb.center = [30.0, 22.5]\n", - " vb.scale = 2.0\n", - " vb.rotation_angle = 0.3\n", - "doc.selection = [vb]\n"), - rejects: &[ - ("'max':[-1.0, 5.0]", "below max"), - ("'scale':0.0", "greater than zero"), - ("'rotation_angle':float('nan')", "finite"), - ("'center':[float('inf'), 0.0]", "finite"), - ("'active_viewport':999999", "does not exist"), - ("'scale_handle':999999", "does not exist"), - ("'version':3", "read-only"), - ], - is_kind: |entity| matches!(entity, EntityType::ViewBorder(_)), - digest: |entity| match entity { - EntityType::ViewBorder(v) => format!("max{:.1},{:.1} c{:.1},{:.1} s{:.1} r{:.1}", v.max[0], v.max[1], - v.center[0], v.center[1], v.scale, v.rotation_angle), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::ViewBorder(v) = entity { v.scale = 3.0; }, - expect_created: "max40.0,30.0 c20.0,15.0 s1.0 r0.0", - expect_edited: "max60.0,45.0 c30.0,22.5 s2.0 r0.3", - expect_reedited: "max60.0,45.0 c30.0,22.5 s3.0 r0.3", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: concat!( + "doc.create_entity('ViewBorder', min=[0.0, 0.0], max=[40.0, 30.0], center=[20.0, 15.0], scale=1.0,\n", + " active_viewport=VIEWPORTHANDLE, scale_handle=SCALEHANDLE)\n" + ), + edit: concat!( + "vb = doc.entities[HANDLE]\n", + "with doc.transaction('Edit view border'):\n", + " vb.max = [60.0, 45.0]\n", + " vb.center = [30.0, 22.5]\n", + " vb.scale = 2.0\n", + " vb.rotation_angle = 0.3\n", + "doc.selection = [vb]\n" + ), + rejects: &[ + ("'max':[-1.0, 5.0]", "below max"), + ("'scale':0.0", "greater than zero"), + ("'rotation_angle':float('nan')", "finite"), + ("'center':[float('inf'), 0.0]", "finite"), + ("'active_viewport':999999", "does not exist"), + ("'scale_handle':999999", "does not exist"), + ("'version':3", "read-only"), + ], + is_kind: |entity| matches!(entity, EntityType::ViewBorder(_)), + digest: |entity| match entity { + EntityType::ViewBorder(v) => format!( + "max{:.1},{:.1} c{:.1},{:.1} s{:.1} r{:.1}", + v.max[0], v.max[1], v.center[0], v.center[1], v.scale, v.rotation_angle + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::ViewBorder(v) = entity { + v.scale = 3.0; + } + }, + expect_created: "max40.0,30.0 c20.0,15.0 s1.0 r0.0", + expect_edited: "max60.0,45.0 c30.0,22.5 s2.0 r0.3", + expect_reedited: "max60.0,45.0 c30.0,22.5 s3.0 r0.3", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] @@ -1356,9 +1462,11 @@ fn audit_python_ole2frame_creation_rules_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); let frames = |host: &HostSession<'_>| { @@ -1384,7 +1492,9 @@ fn audit_python_ole2frame_creation_rules_over_real_ipc() { }; let embed = |file: &std::path::Path, extra: &str| { format!( - "PY_EVAL ocs.active_document.embed_picture({:?}, origin=(1, 2, 3), width=16{extra}).handle", file.display().to_string()) + "PY_EVAL ocs.active_document.embed_picture({:?}, origin=(1, 2, 3), width=16{extra}).handle", + file.display().to_string() + ) }; // C: PNG and JPEG are stored as read, a TIFF is re-encoded as PNG, and @@ -1497,9 +1607,11 @@ fn audit_python_viewport_ids_and_scale_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); let viewports = |host: &HostSession<'_>| { @@ -1516,7 +1628,9 @@ fn audit_python_viewport_ids_and_scale_over_real_ipc() { }; let create = |width: f64, height: f64, view_height: f64| { format!( - "PY_EVAL ocs.active_document.create_entity('Viewport', owner_handle={}, center=(50, 50, 0), width={width}, height={height}, view_height={view_height}).handle", paper.value()) + "PY_EVAL ocs.active_document.create_entity('Viewport', owner_handle={}, center=(50, 50, 0), width={width}, height={height}, view_height={view_height}).handle", + paper.value() + ) }; dispatch(&mut host, &create(80.0, 60.0, 50.0)); dispatch(&mut host, &create(40.0, 30.0, 10.0)); @@ -1668,10 +1782,17 @@ fn spike_raster_image_definition_persistence() { .count(); let dicts = document.objects.values().filter(|o| matches!(o, document::objects::ObjectType::Dictionary(d) if d.entries.iter().any(|(k, _)| k.contains("IMAGE")))).count(); match entity { - Some(EntityType::RasterImage(i)) => eprintln!("SPIKE linked={linked} {label}: file_path_ok={} definition={:?} reactor={:?} defs={defs} reactors={reactors} image_dicts={dicts}", - i.file_path == path, i.definition_handle.map(|h| h.value()), i.definition_reactor_handle.map(|h| h.value())), - other => eprintln!("SPIKE linked={linked} {label}: came back as {:?}", other.map(|e| format!("{e:?}").chars().take(24).collect::())), - } + Some(EntityType::RasterImage(i)) => eprintln!( + "SPIKE linked={linked} {label}: file_path_ok={} definition={:?} reactor={:?} defs={defs} reactors={reactors} image_dicts={dicts}", + i.file_path == path, + i.definition_handle.map(|h| h.value()), + i.definition_reactor_handle.map(|h| h.value()) + ), + other => eprintln!( + "SPIKE linked={linked} {label}: came back as {:?}", + other.map(|e| format!("{e:?}").chars().take(24).collect::()) + ), + } } } } @@ -1725,9 +1846,11 @@ fn modify_wrappers_audit_body() { "{body}\n", "L.create(('REPORT ' + str(len(refused)) + ' ~ ' + ' '.join(failed))[:250])\n", ), body = body)).unwrap(); - assert!(process - .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) - .unwrap()); + assert!( + process + .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) + .unwrap() + ); let _ = std::fs::remove_file(&script); }; let report = |document: &Document| -> (usize, Vec) { @@ -2140,13 +2263,15 @@ fn audit_python_nested_input_is_validated_over_real_ipc() { "good2 = doc.create_entity('Polyline2D', vertices=[{'location': P(0, 0)}, {'location': P(5, 5)}])\n", "L.create('REPORT ' + str(len(refused)) + ' ~ ' + ' '.join(problems))\n", )).unwrap(); - assert!(process - .dispatch( - &mut host, - &format!("PY_RUN {}", script.display()), - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + &format!("PY_RUN {}", script.display()), + &mut |_| {} + ) + .unwrap() + ); let _ = std::fs::remove_file(&script); let name = host .document() @@ -2178,9 +2303,11 @@ fn audit_python_nested_input_is_validated_over_real_ipc() { .count(), 1 ); - assert!(!document - .entities() - .any(|e| matches!(e, EntityType::PolygonMesh(_)))); + assert!( + !document + .entities() + .any(|e| matches!(e, EntityType::PolygonMesh(_))) + ); drop(process); } @@ -2327,13 +2454,15 @@ fn audit_python_raster_image_definition_linkage_over_real_ipc() { ), ) .unwrap(); - assert!(process - .dispatch( - &mut host, - &format!("PY_RUN {}", script.display()), - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + &format!("PY_RUN {}", script.display()), + &mut |_| {} + ) + .unwrap() + ); let _ = std::fs::remove_file(&script); // The structure: one definition per file, registered and owned by ACAD_IMAGE_DICT. @@ -2467,9 +2596,11 @@ fn staged_python_point_pick_and_cancel_over_real_ipc() { "request_point" }; let cmd = format!("PY_EVAL ocs.active_document.{method}('{prompt}')"); - assert!(process - .dispatch(&mut host, &cmd, &mut |id| started = Some(id)) - .unwrap()); + assert!( + process + .dispatch(&mut host, &cmd, &mut |id| started = Some(id)) + .unwrap() + ); } let output = app.command_line.history.last().unwrap().text.clone(); let token = output @@ -2497,21 +2628,24 @@ fn staged_python_point_pick_and_cancel_over_real_ipc() { assert!(app.tabs[0].active_cmd.is_none()); { let mut host = HostSession::new(&mut app, 0); - assert!(process - .dispatch( - &mut host, - &format!("PY_EVAL ocs.active_document.poll_input({picked_token})"), - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + &format!("PY_EVAL ocs.active_document.poll_input({picked_token})"), + &mut |_| {} + ) + .unwrap() + ); } - assert!(app - .command_line - .history - .last() - .unwrap() - .text - .contains("point")); + assert!( + app.command_line + .history + .last() + .unwrap() + .text + .contains("point") + ); let target = { let mut host = HostSession::new(&mut app, 0); @@ -2530,49 +2664,56 @@ fn staged_python_point_pick_and_cancel_over_real_ipc() { let _ = app.apply_cmd_result(result); { let mut host = HostSession::new(&mut app, 0); - assert!(process - .dispatch( - &mut host, - &format!("PY_EVAL ocs.active_document.poll_input({entity_token})"), - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + &format!("PY_EVAL ocs.active_document.poll_input({entity_token})"), + &mut |_| {} + ) + .unwrap() + ); } - assert!(app - .command_line - .history - .last() - .unwrap() - .text - .contains("entity")); - assert!(app - .command_line - .history - .last() - .unwrap() - .text - .contains(&target.value().to_string())); + assert!( + app.command_line + .history + .last() + .unwrap() + .text + .contains("entity") + ); + assert!( + app.command_line + .history + .last() + .unwrap() + .text + .contains(&target.value().to_string()) + ); let cancelled_token = request(&mut app, "Cancel a point", false); let result = app.tabs[0].active_cmd.as_mut().unwrap().on_enter(); let _ = app.apply_cmd_result(result); { let mut host = HostSession::new(&mut app, 0); - assert!(process - .dispatch( - &mut host, - &format!("PY_EVAL ocs.active_document.poll_input({cancelled_token})"), - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + &format!("PY_EVAL ocs.active_document.poll_input({cancelled_token})"), + &mut |_| {} + ) + .unwrap() + ); } - assert!(app - .command_line - .history - .last() - .unwrap() - .text - .contains("cancelled")); + assert!( + app.command_line + .history + .last() + .unwrap() + .text + .contains("cancelled") + ); } /// A script asks for an array drag: the plugin previews the copies while the @@ -2627,14 +2768,19 @@ else: let mut started = None; { let mut host = HostSession::new(&mut app, 0); - assert!(process - .dispatch(&mut host, &format!("PY_RUN {script_path}"), &mut |id| { - started = Some(id) - }) - .unwrap()); + assert!( + process + .dispatch(&mut host, &format!("PY_RUN {script_path}"), &mut |id| { + started = Some(id) + }) + .unwrap() + ); } let text = history(&app); - assert!(text.contains("refused: request_drag: an array takes 3 prompts"), "{text}"); + assert!( + text.contains("refused: request_drag: an array takes 3 prompts"), + "{text}" + ); let id = started.unwrap_or_else(|| panic!("no drag started: {text}")); app.set_active_command( 0, @@ -2645,10 +2791,15 @@ else: ); let command = app.tabs[0].active_cmd.as_mut().unwrap(); assert_eq!(command.prompt(), "Base"); - assert!(command - .on_preview_wires(glam::DVec3::new(9.0, 9.0, 0.0)) - .is_empty()); - for point in [glam::DVec3::new(10.0, 0.0, 0.0), glam::DVec3::new(12.0, 0.0, 0.0)] { + assert!( + command + .on_preview_wires(glam::DVec3::new(9.0, 9.0, 0.0)) + .is_empty() + ); + for point in [ + glam::DVec3::new(10.0, 0.0, 0.0), + glam::DVec3::new(12.0, 0.0, 0.0), + ] { assert!(matches!( command.on_point(point), crate::command::CmdResult::NeedPoint @@ -2673,7 +2824,10 @@ else: assert!(process.dispatch(&mut host, &line, &mut |_| {}).unwrap()); } let text = history(&app); - assert!(text.contains("resumed drag 3 seven [16.5, 3.0, 0.0]"), "{text}"); + assert!( + text.contains("resumed drag 3 seven [16.5, 3.0, 0.0]"), + "{text}" + ); // the result is read once: the same line again is a first run { let mut host = HostSession::new(&mut app, 0); @@ -2719,7 +2873,10 @@ fn staged_python_typed_line_leaves_the_requested_point_prompt_open() { .0 }; let _ = app.run_command_line(&format!("PY_RUN {script_path}")); - let prompt = app.tabs[0].active_cmd.as_ref().map(|command| command.prompt()); + let prompt = app.tabs[0] + .active_cmd + .as_ref() + .map(|command| command.prompt()); if let Some(command) = app.tabs[0].active_cmd.as_mut() { let _ = command.on_enter(); } @@ -2769,13 +2926,15 @@ fn staged_python_tabs_isolate_tokens_and_notifications() { let mut started = None; { let mut host = HostSession::new(&mut app, 0); - assert!(process - .dispatch( - &mut host, - "PY_EVAL ocs.active_document.request_point('Tab zero')", - &mut |id| started = Some(id) - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + "PY_EVAL ocs.active_document.request_point('Tab zero')", + &mut |id| started = Some(id) + ) + .unwrap() + ); } let token = app .command_line @@ -2795,13 +2954,15 @@ fn staged_python_tabs_isolate_tokens_and_notifications() { ); { let mut host = HostSession::new(&mut app, 1); - assert!(process - .dispatch( - &mut host, - &format!("PY_EVAL ocs.active_document.poll_input({token})"), - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + &format!("PY_EVAL ocs.active_document.poll_input({token})"), + &mut |_| {} + ) + .unwrap() + ); } assert!( app.command_line @@ -2820,38 +2981,44 @@ fn staged_python_tabs_isolate_tokens_and_notifications() { let _ = app.apply_cmd_result(result); { let mut host = HostSession::new(&mut app, 1); - assert!(process - .dispatch( - &mut host, - &format!("PY_EVAL ocs.active_document.poll_input({token})"), - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + &format!("PY_EVAL ocs.active_document.poll_input({token})"), + &mut |_| {} + ) + .unwrap() + ); } - assert!(app - .command_line - .history - .last() - .unwrap() - .text - .contains("None")); + assert!( + app.command_line + .history + .last() + .unwrap() + .text + .contains("None") + ); { let mut host = HostSession::new(&mut app, 0); - assert!(process - .dispatch( - &mut host, - &format!("PY_EVAL ocs.active_document.poll_input({token})"), - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + &format!("PY_EVAL ocs.active_document.poll_input({token})"), + &mut |_| {} + ) + .unwrap() + ); } - assert!(app - .command_line - .history - .last() - .unwrap() - .text - .contains("point")); + assert!( + app.command_line + .history + .last() + .unwrap() + .text + .contains("point") + ); use ocs_plugin_api::host::HostNotification; process @@ -2880,13 +3047,15 @@ fn staged_python_tabs_isolate_tokens_and_notifications() { for _ in 0..10 { { let mut host = HostSession::new(app, tab); - assert!(process - .dispatch( - &mut host, - "PY_EVAL ocs.active_document.poll_events()", - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + "PY_EVAL ocs.active_document.poll_events()", + &mut |_| {} + ) + .unwrap() + ); } output = app.command_line.history.last().unwrap().text.clone(); if output.contains(epoch) { @@ -2921,13 +3090,15 @@ fn staged_python_tabs_isolate_tokens_and_notifications() { std::thread::sleep(std::time::Duration::from_millis(100)); { let mut host = HostSession::new(&mut app, 0); - assert!(process - .dispatch( - &mut host, - "PY_EVAL ocs.active_document.poll_events()", - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + "PY_EVAL ocs.active_document.poll_events()", + &mut |_| {} + ) + .unwrap() + ); } let overflow = &app.command_line.history.last().unwrap().text; assert!( @@ -2950,13 +3121,15 @@ fn staged_python_tabs_isolate_tokens_and_notifications() { std::thread::sleep(std::time::Duration::from_millis(50)); { let mut host = HostSession::new(&mut app, 0); - assert!(process - .dispatch( - &mut host, - "PY_EVAL ocs.active_document.poll_events()", - &mut |_| {} - ) - .unwrap()); + assert!( + process + .dispatch( + &mut host, + "PY_EVAL ocs.active_document.poll_events()", + &mut |_| {} + ) + .unwrap() + ); } assert!( app.command_line.history.last().unwrap().text.contains("[]"), @@ -3041,9 +3214,10 @@ fn system_variables_change_without_command_reentry() { host.system_variable("SNAPANG"), Some(HostSettingValue::Number(0.0)) ); - assert!(host - .set_system_variable("CLAYER", HostSettingValue::Text("Missing".into())) - .is_err()); + assert!( + host.set_system_variable("CLAYER", HostSettingValue::Text("Missing".into())) + .is_err() + ); assert_eq!( host.system_variable("CLAYER"), Some(HostSettingValue::Text("0".into())) @@ -3073,12 +3247,14 @@ fn system_variables_change_without_command_reentry() { host.system_variable("SNAPANG"), Some(HostSettingValue::Number(90.0)) ); - assert!(host - .set_system_variable("SNAPANG", HostSettingValue::Number(f64::INFINITY)) - .is_err()); - assert!(host - .set_system_variable("SNAPANG", HostSettingValue::Number(f64::MAX)) - .is_err()); + assert!( + host.set_system_variable("SNAPANG", HostSettingValue::Number(f64::INFINITY)) + .is_err() + ); + assert!( + host.set_system_variable("SNAPANG", HostSettingValue::Number(f64::MAX)) + .is_err() + ); assert_eq!( host.system_variable("SNAPANG"), Some(HostSettingValue::Number(90.0)) @@ -3806,16 +3982,19 @@ fn entity_creation_with_novel_layer_refreshes_gui() { app.tabs[0].is_start = false; // Verify DYNAMIC_PLUGIN_LINES does not exist initially - assert!(!app.tabs[0] - .scene - .document - .layers - .contains("DYNAMIC_PLUGIN_LINES")); - assert!(!app - .ribbon - .layer_infos - .iter() - .any(|l| l.name == "DYNAMIC_PLUGIN_LINES")); + assert!( + !app.tabs[0] + .scene + .document + .layers + .contains("DYNAMIC_PLUGIN_LINES") + ); + assert!( + !app.ribbon + .layer_infos + .iter() + .any(|l| l.name == "DYNAMIC_PLUGIN_LINES") + ); // 1. Add entity via HostSession (simulating plugin add_entity / add_line) { @@ -3827,11 +4006,13 @@ fn entity_creation_with_novel_layer_refreshes_gui() { } // Verify layer is created in document AND refreshed in ribbon + layer panel - assert!(app.tabs[0] - .scene - .document - .layers - .contains("DYNAMIC_PLUGIN_LINES")); + assert!( + app.tabs[0] + .scene + .document + .layers + .contains("DYNAMIC_PLUGIN_LINES") + ); assert!( app.ribbon .layer_infos @@ -3854,11 +4035,13 @@ fn entity_creation_with_novel_layer_refreshes_gui() { let _ = app.commit_entity_handle_preserve_layer(document::EntityType::Line(line2)); // Verify SURVEY_TRAVERSE layer is created and refreshed in ribbon + layer panel - assert!(app.tabs[0] - .scene - .document - .layers - .contains("SURVEY_TRAVERSE")); + assert!( + app.tabs[0] + .scene + .document + .layers + .contains("SURVEY_TRAVERSE") + ); assert!( app.ribbon .layer_infos @@ -4187,9 +4370,11 @@ fn parametric_validation_is_pure_and_rejects_a_hard_corner() { segments: Vec::new(), ..chain.clone() }; - assert!(HostApi::validate_parametric_chain(&host, &empty, 1e-3) - .unwrap_err() - .contains("at least one segment")); + assert!( + HostApi::validate_parametric_chain(&host, &empty, 1e-3) + .unwrap_err() + .contains("at least one segment") + ); assert_eq!(host.app.tabs[0].scene.geometry_epoch, epoch_before); assert_eq!(host.document(), &document_before); @@ -4290,9 +4475,10 @@ fn grip_edit_restage_updates_the_display_set_in_place() { let handles; { let mut host = HostSession::new(&mut app, 0); - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); let mut instance = traverse_instance(); instance.design = ocs_plugin_api::host::PluginDisplayDescriptor::ParametricChain(crest_profile_chain()); diff --git a/src/app/plugin_host/plugin_host_tests/audit_entity_lifecycle.rs b/src/app/plugin_host/plugin_host_tests/audit_entity_lifecycle.rs index 05bbf23d75..0cc525d4ac 100644 --- a/src/app/plugin_host/plugin_host_tests/audit_entity_lifecycle.rs +++ b/src/app/plugin_host/plugin_host_tests/audit_entity_lifecycle.rs @@ -118,53 +118,77 @@ fn audit_python_circle_lifecycle_over_real_ipc() { #[test] fn audit_python_arc_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: "doc.create_entity('Arc', center=P(0.0, 0.0, 0.0), radius=5.0, start_angle=0.0, end_angle=1.5)", - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.end_angle = 2.0\n", " e.radius = 6.0\n", "doc.selection = [e]\n"), - rejects: &[ - ("'radius':0.0", "radius"), - ("'end_angle':float('nan')", "finite"), - ("'center':{'x':float('nan'),'y':0.0,'z':0.0}", "finite"), - ], - is_kind: |entity| matches!(entity, EntityType::Arc(_)), - digest: |entity| match entity { - EntityType::Arc(v) => format!("r{:.1} {:.1}..{:.1}", v.radius, v.start_angle, v.end_angle), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::Arc(v) = entity { v.start_angle = 0.5; }, - expect_created: "r5.0 0.0..1.5", - expect_edited: "r6.0 0.0..2.0", - expect_reedited: "r6.0 0.5..2.0", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: "doc.create_entity('Arc', center=P(0.0, 0.0, 0.0), radius=5.0, start_angle=0.0, end_angle=1.5)", + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.end_angle = 2.0\n", + " e.radius = 6.0\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ("'radius':0.0", "radius"), + ("'end_angle':float('nan')", "finite"), + ("'center':{'x':float('nan'),'y':0.0,'z':0.0}", "finite"), + ], + is_kind: |entity| matches!(entity, EntityType::Arc(_)), + digest: |entity| match entity { + EntityType::Arc(v) => { + format!("r{:.1} {:.1}..{:.1}", v.radius, v.start_angle, v.end_angle) + } + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::Arc(v) = entity { + v.start_angle = 0.5; + } + }, + expect_created: "r5.0 0.0..1.5", + expect_edited: "r6.0 0.0..2.0", + expect_reedited: "r6.0 0.5..2.0", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] fn audit_python_ellipse_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: "doc.create_entity('Ellipse', center=P(0.0, 0.0, 0.0), major_axis=P(10.0, 0.0, 0.0), minor_axis_ratio=0.5)", - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.minor_axis_ratio = 0.25\n", " e.end_parameter = 3.0\n", "doc.selection = [e]\n"), - rejects: &[ - ("'minor_axis_ratio':0.0", "ratio"), - ("'minor_axis_ratio':2.0", "ratio"), - ("'major_axis':{'x':0.0,'y':0.0,'z':0.0}", "axis"), - ], - is_kind: |entity| matches!(entity, EntityType::Ellipse(_)), - digest: |entity| match entity { - EntityType::Ellipse(v) => format!("q{:.2} ..{:.1}", v.minor_axis_ratio, v.end_parameter), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::Ellipse(v) = entity { v.minor_axis_ratio = 0.75; }, - expect_created: "q0.50 ..6.3", - expect_edited: "q0.25 ..3.0", - expect_reedited: "q0.75 ..3.0", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: "doc.create_entity('Ellipse', center=P(0.0, 0.0, 0.0), major_axis=P(10.0, 0.0, 0.0), minor_axis_ratio=0.5)", + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.minor_axis_ratio = 0.25\n", + " e.end_parameter = 3.0\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ("'minor_axis_ratio':0.0", "ratio"), + ("'minor_axis_ratio':2.0", "ratio"), + ("'major_axis':{'x':0.0,'y':0.0,'z':0.0}", "axis"), + ], + is_kind: |entity| matches!(entity, EntityType::Ellipse(_)), + digest: |entity| match entity { + EntityType::Ellipse(v) => { + format!("q{:.2} ..{:.1}", v.minor_axis_ratio, v.end_parameter) + } + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::Ellipse(v) = entity { + v.minor_axis_ratio = 0.75; + } + }, + expect_created: "q0.50 ..6.3", + expect_edited: "q0.25 ..3.0", + expect_reedited: "q0.75 ..3.0", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] @@ -208,8 +232,7 @@ fn audit_python_ray_lifecycle_over_real_ipc() { #[test] fn audit_python_xline_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: - "doc.create_entity('XLine', base_point=P(0.0, 0.0, 0.0), direction=P(1.0, 0.0, 0.0))", + create: "doc.create_entity('XLine', base_point=P(0.0, 0.0, 0.0), direction=P(1.0, 0.0, 0.0))", edit: concat!( "e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", @@ -247,52 +270,83 @@ fn audit_python_xline_lifecycle_over_real_ipc() { #[test] fn audit_python_solid_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: "doc.create_entity('Solid', first_corner=P(0.0, 0.0, 0.0), second_corner=P(4.0, 0.0, 0.0), third_corner=P(0.0, 4.0, 0.0), fourth_corner=P(4.0, 4.0, 0.0))", - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.fourth_corner = (5.0, 5.0, 0.0)\n", " e.thickness = 2.0\n", "doc.selection = [e]\n"), - rejects: &[ - ("'first_corner':{'x':float('nan'),'y':0.0,'z':0.0}", "finite"), - ("'thickness':float('inf')", "finite"), - ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), - ], - is_kind: |entity| matches!(entity, EntityType::Solid(_)), - digest: |entity| match entity { - EntityType::Solid(v) => format!("{:.1},{:.1} th{:.1}", v.fourth_corner.x, v.fourth_corner.y, v.thickness), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::Solid(v) = entity { v.first_corner.x = 1.0; }, - expect_created: "4.0,4.0 th0.0", - expect_edited: "5.0,5.0 th2.0", - expect_reedited: "5.0,5.0 th2.0", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: "doc.create_entity('Solid', first_corner=P(0.0, 0.0, 0.0), second_corner=P(4.0, 0.0, 0.0), third_corner=P(0.0, 4.0, 0.0), fourth_corner=P(4.0, 4.0, 0.0))", + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.fourth_corner = (5.0, 5.0, 0.0)\n", + " e.thickness = 2.0\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ( + "'first_corner':{'x':float('nan'),'y':0.0,'z':0.0}", + "finite", + ), + ("'thickness':float('inf')", "finite"), + ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), + ], + is_kind: |entity| matches!(entity, EntityType::Solid(_)), + digest: |entity| match entity { + EntityType::Solid(v) => format!( + "{:.1},{:.1} th{:.1}", + v.fourth_corner.x, v.fourth_corner.y, v.thickness + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::Solid(v) = entity { + v.first_corner.x = 1.0; + } + }, + expect_created: "4.0,4.0 th0.0", + expect_edited: "5.0,5.0 th2.0", + expect_reedited: "5.0,5.0 th2.0", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] fn audit_python_face3d_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: "doc.create_entity('Face3D', first_corner=P(0.0, 0.0, 0.0), second_corner=P(4.0, 0.0, 0.0), third_corner=P(4.0, 4.0, 1.0), fourth_corner=P(0.0, 4.0, 1.0))", - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.third_corner = (4.0, 4.0, 2.0)\n", " e.invisible_edges = 3\n", "doc.selection = [e]\n"), - rejects: &[ - ("'first_corner':{'x':float('nan'),'y':0.0,'z':0.0}", "finite"), - ("'invisible_edges':64", "bits"), - ], - is_kind: |entity| matches!(entity, EntityType::Face3D(_)), - digest: |entity| match entity { - EntityType::Face3D(v) => format!("z{:.1} inv{}", v.third_corner.z, v.invisible_edges.bits()), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::Face3D(v) = entity { v.first_corner.x = 1.0; }, - expect_created: "z1.0 inv0", - expect_edited: "z2.0 inv3", - expect_reedited: "z2.0 inv3", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: "doc.create_entity('Face3D', first_corner=P(0.0, 0.0, 0.0), second_corner=P(4.0, 0.0, 0.0), third_corner=P(4.0, 4.0, 1.0), fourth_corner=P(0.0, 4.0, 1.0))", + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.third_corner = (4.0, 4.0, 2.0)\n", + " e.invisible_edges = 3\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ( + "'first_corner':{'x':float('nan'),'y':0.0,'z':0.0}", + "finite", + ), + ("'invisible_edges':64", "bits"), + ], + is_kind: |entity| matches!(entity, EntityType::Face3D(_)), + digest: |entity| match entity { + EntityType::Face3D(v) => { + format!("z{:.1} inv{}", v.third_corner.z, v.invisible_edges.bits()) + } + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::Face3D(v) = entity { + v.first_corner.x = 1.0; + } + }, + expect_created: "z1.0 inv0", + expect_edited: "z2.0 inv3", + expect_reedited: "z2.0 inv3", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] @@ -335,163 +389,293 @@ fn audit_python_text_lifecycle_over_real_ipc() { #[test] fn audit_python_mtext_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: "doc.create_entity('MText', text='Line one', insertion=P(1.0, 2.0, 0.0), height=2.5, rectangle_width=30.0)", - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.text = 'Line two'\n", " e.rectangle_width = 40.0\n", " e.rotation = 0.5\n", "doc.selection = [e]\n"), - rejects: &[ - ("'height':0.0", "height"), - ("'rectangle_width':-1.0", "width"), - ("'insertion':{'x':float('nan'),'y':0.0,'z':0.0}", "finite"), - ], - is_kind: |entity| matches!(entity, EntityType::MText(_)), - digest: |entity| match entity { - EntityType::MText(v) => format!("{} w{:.1} r{:.1}", v.value, v.rectangle_width, v.rotation), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::MText(v) = entity { v.rectangle_width = 50.0; }, - expect_created: "Line one w30.0 r0.0", - expect_edited: "Line two w40.0 r0.5", - expect_reedited: "Line two w50.0 r0.5", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: "doc.create_entity('MText', text='Line one', insertion=P(1.0, 2.0, 0.0), height=2.5, rectangle_width=30.0)", + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.text = 'Line two'\n", + " e.rectangle_width = 40.0\n", + " e.rotation = 0.5\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ("'height':0.0", "height"), + ("'rectangle_width':-1.0", "width"), + ("'insertion':{'x':float('nan'),'y':0.0,'z':0.0}", "finite"), + ], + is_kind: |entity| matches!(entity, EntityType::MText(_)), + digest: |entity| match entity { + EntityType::MText(v) => { + format!("{} w{:.1} r{:.1}", v.value, v.rectangle_width, v.rotation) + } + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::MText(v) = entity { + v.rectangle_width = 50.0; + } + }, + expect_created: "Line one w30.0 r0.0", + expect_edited: "Line two w40.0 r0.5", + expect_reedited: "Line two w50.0 r0.5", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] fn audit_python_lwpolyline_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!("doc.create_entity('LwPolyline', vertices=[{'location': {'x': 0.0, 'y': 0.0}}, {'location': {'x': 10.0, 'y': 0.0}}, {'location': {'x': 10.0, 'y': 5.0}}])\n"), - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.vertices = [{'location': {'x': 0.0, 'y': 0.0}}, {'location': {'x': 10.0, 'y': 0.0}}, {'location': {'x': 10.0, 'y': 8.0}, 'bulge': 0.5}, {'location': {'x': 0.0, 'y': 8.0}}]\n", " e.is_closed = True\n", " e.constant_width = 0.5\n", "doc.selection = [e]\n"), - rejects: &[ - ("'vertices':[{'location':{'x':0.0,'y':0.0}}]", "at least 2"), - ("'constant_width':-1.0", "non-negative"), - ("'vertices':[{'location':{'x':float('nan'),'y':0.0}},{'location':{'x':1.0,'y':0.0}}]", "finite"), - ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), - ], - is_kind: |entity| matches!(entity, EntityType::LwPolyline(_)), - digest: |entity| match entity { - EntityType::LwPolyline(v) => format!("n{} closed{} w{:.1} bulge{:.1}", v.vertices.len(), v.is_closed, v.constant_width, v.vertices.get(2).map_or(0.0, |x| x.bulge)), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::LwPolyline(v) = entity { v.constant_width = 1.0; }, - expect_created: "n3 closedfalse w0.0 bulge0.0", - expect_edited: "n4 closedtrue w0.5 bulge0.5", - expect_reedited: "n4 closedtrue w1.0 bulge0.5", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: concat!( + "doc.create_entity('LwPolyline', vertices=[{'location': {'x': 0.0, 'y': 0.0}}, {'location': {'x': 10.0, 'y': 0.0}}, {'location': {'x': 10.0, 'y': 5.0}}])\n" + ), + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.vertices = [{'location': {'x': 0.0, 'y': 0.0}}, {'location': {'x': 10.0, 'y': 0.0}}, {'location': {'x': 10.0, 'y': 8.0}, 'bulge': 0.5}, {'location': {'x': 0.0, 'y': 8.0}}]\n", + " e.is_closed = True\n", + " e.constant_width = 0.5\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ("'vertices':[{'location':{'x':0.0,'y':0.0}}]", "at least 2"), + ("'constant_width':-1.0", "non-negative"), + ( + "'vertices':[{'location':{'x':float('nan'),'y':0.0}},{'location':{'x':1.0,'y':0.0}}]", + "finite", + ), + ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), + ], + is_kind: |entity| matches!(entity, EntityType::LwPolyline(_)), + digest: |entity| match entity { + EntityType::LwPolyline(v) => format!( + "n{} closed{} w{:.1} bulge{:.1}", + v.vertices.len(), + v.is_closed, + v.constant_width, + v.vertices.get(2).map_or(0.0, |x| x.bulge) + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::LwPolyline(v) = entity { + v.constant_width = 1.0; + } + }, + expect_created: "n3 closedfalse w0.0 bulge0.0", + expect_edited: "n4 closedtrue w0.5 bulge0.5", + expect_reedited: "n4 closedtrue w1.0 bulge0.5", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] fn audit_python_polyline2d_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!("doc.create_entity('Polyline2D', vertices=[{'location': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 5.0, 'z': 0.0}}])\n"), - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.vertices = [{'location': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 8.0, 'z': 0.0}}, {'location': {'x': 0.0, 'y': 8.0, 'z': 0.0}}]\n", " e.closed = True\n", " e.thickness = 1.0\n", "doc.selection = [e]\n"), - rejects: &[ - ("'vertices':[{'location':{'x':0.0,'y':0.0,'z':0.0}}]", "at least 2"), - ("'thickness':float('inf')", "finite"), - ("'vertices':[{'location':{'x':float('nan'),'y':0.0,'z':0.0}},{'location':{'x':1.0,'y':0.0,'z':0.0}}]", "finite"), - ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), - ], - is_kind: |entity| matches!(entity, EntityType::Polyline2D(_)), - digest: |entity| match entity { - EntityType::Polyline2D(v) => format!("n{} closed{} th{:.1}", v.vertices.len(), v.flags.is_closed(), v.thickness), - other => format!("wrong kind {}", format!("{other:?}").split('(').next().unwrap()), - }, - reedit: |entity| if let EntityType::Polyline2D(v) = entity { v.thickness = 2.0; }, - expect_created: "n3 closedfalse th0.0", - expect_edited: "n4 closedtrue th1.0", - expect_reedited: "n4 closedtrue th2.0", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "wrong kind LwPolyline", - expect_reedited_dxf: "wrong kind LwPolyline", - }); + create: concat!( + "doc.create_entity('Polyline2D', vertices=[{'location': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 5.0, 'z': 0.0}}])\n" + ), + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.vertices = [{'location': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 8.0, 'z': 0.0}}, {'location': {'x': 0.0, 'y': 8.0, 'z': 0.0}}]\n", + " e.closed = True\n", + " e.thickness = 1.0\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ( + "'vertices':[{'location':{'x':0.0,'y':0.0,'z':0.0}}]", + "at least 2", + ), + ("'thickness':float('inf')", "finite"), + ( + "'vertices':[{'location':{'x':float('nan'),'y':0.0,'z':0.0}},{'location':{'x':1.0,'y':0.0,'z':0.0}}]", + "finite", + ), + ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), + ], + is_kind: |entity| matches!(entity, EntityType::Polyline2D(_)), + digest: |entity| match entity { + EntityType::Polyline2D(v) => format!( + "n{} closed{} th{:.1}", + v.vertices.len(), + v.flags.is_closed(), + v.thickness + ), + other => format!( + "wrong kind {}", + format!("{other:?}").split('(').next().unwrap() + ), + }, + reedit: |entity| { + if let EntityType::Polyline2D(v) = entity { + v.thickness = 2.0; + } + }, + expect_created: "n3 closedfalse th0.0", + expect_edited: "n4 closedtrue th1.0", + expect_reedited: "n4 closedtrue th2.0", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "wrong kind LwPolyline", + expect_reedited_dxf: "wrong kind LwPolyline", + }); } #[test] fn audit_python_polyline_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: "# MAKEPOLYLINE + create: "# MAKEPOLYLINE ", - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.vertices = [{'location': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 0.0, 'z': 2.0}}, {'location': {'x': 10.0, 'y': 8.0, 'z': 6.0}}, {'location': {'x': 0.0, 'y': 8.0, 'z': 6.0}}]\n", " e.closed = True\n", "doc.selection = [e]\n"), - rejects: &[ - ("'vertices':[{'location':{'x':0.0,'y':0.0,'z':0.0}}]", "at least 2"), - ("'vertices':[{'location':{'x':float('nan'),'y':0.0,'z':0.0}},{'location':{'x':1.0,'y':0.0,'z':0.0}}]", "finite"), - ], - is_kind: |entity| matches!(entity, EntityType::Polyline(_)), - digest: |entity| match entity { - EntityType::Polyline(v) => format!("n{} closed{} lastz{:.1}", v.vertices.len(), v.flags.is_closed(), v.vertices.last().map_or(0.0, |x| x.location.z)), - other => format!("wrong kind {}", format!("{other:?}").split('(').next().unwrap()), - }, - reedit: |entity| if let EntityType::Polyline(v) = entity { v.vertices[0].location.z = 1.0; }, - expect_created: "n3 closedfalse lastz4.0", - expect_edited: "n4 closedtrue lastz6.0", - expect_reedited: "n4 closedtrue lastz6.0", - expect_edited_dwg: "wrong kind Polyline3D", - expect_reedited_dwg: "wrong kind Polyline3D", - expect_edited_dxf: "wrong kind Polyline3D", - expect_reedited_dxf: "wrong kind Polyline3D", - }); + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.vertices = [{'location': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'location': {'x': 10.0, 'y': 0.0, 'z': 2.0}}, {'location': {'x': 10.0, 'y': 8.0, 'z': 6.0}}, {'location': {'x': 0.0, 'y': 8.0, 'z': 6.0}}]\n", + " e.closed = True\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ( + "'vertices':[{'location':{'x':0.0,'y':0.0,'z':0.0}}]", + "at least 2", + ), + ( + "'vertices':[{'location':{'x':float('nan'),'y':0.0,'z':0.0}},{'location':{'x':1.0,'y':0.0,'z':0.0}}]", + "finite", + ), + ], + is_kind: |entity| matches!(entity, EntityType::Polyline(_)), + digest: |entity| match entity { + EntityType::Polyline(v) => format!( + "n{} closed{} lastz{:.1}", + v.vertices.len(), + v.flags.is_closed(), + v.vertices.last().map_or(0.0, |x| x.location.z) + ), + other => format!( + "wrong kind {}", + format!("{other:?}").split('(').next().unwrap() + ), + }, + reedit: |entity| { + if let EntityType::Polyline(v) = entity { + v.vertices[0].location.z = 1.0; + } + }, + expect_created: "n3 closedfalse lastz4.0", + expect_edited: "n4 closedtrue lastz6.0", + expect_reedited: "n4 closedtrue lastz6.0", + expect_edited_dwg: "wrong kind Polyline3D", + expect_reedited_dwg: "wrong kind Polyline3D", + expect_edited_dxf: "wrong kind Polyline3D", + expect_reedited_dxf: "wrong kind Polyline3D", + }); } #[test] fn audit_python_polyline3d_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!("doc.create_entity('Polyline3D', vertices=[{'position': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'position': {'x': 10.0, 'y': 0.0, 'z': 2.0}}, {'position': {'x': 10.0, 'y': 5.0, 'z': 4.0}}])\n"), - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.vertices = [{'position': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'position': {'x': 10.0, 'y': 0.0, 'z': 2.0}}, {'position': {'x': 10.0, 'y': 8.0, 'z': 6.0}}, {'position': {'x': 0.0, 'y': 8.0, 'z': 6.0}}]\n", " e.elevation = 1.5\n", "doc.selection = [e]\n"), - rejects: &[ - ("'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}}]", "at least 2"), - ("'elevation':float('inf')", "finite"), - ("'vertices':[{'position':{'x':float('nan'),'y':0.0,'z':0.0}},{'position':{'x':1.0,'y':0.0,'z':0.0}}]", "finite"), - ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), - ], - is_kind: |entity| matches!(entity, EntityType::Polyline3D(_)), - digest: |entity| match entity { - EntityType::Polyline3D(v) => format!("n{} el{:.1} lastz{:.1}", v.vertices.len(), v.elevation, v.vertices.last().map_or(0.0, |x| x.position.z)), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::Polyline3D(v) = entity { v.elevation = 2.5; }, - expect_created: "n3 el0.0 lastz4.0", - expect_edited: "n4 el1.5 lastz6.0", - expect_reedited: "n4 el2.5 lastz6.0", - expect_edited_dwg: "n4 el0.0 lastz6.0", - expect_reedited_dwg: "n4 el0.0 lastz6.0", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: concat!( + "doc.create_entity('Polyline3D', vertices=[{'position': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'position': {'x': 10.0, 'y': 0.0, 'z': 2.0}}, {'position': {'x': 10.0, 'y': 5.0, 'z': 4.0}}])\n" + ), + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.vertices = [{'position': {'x': 0.0, 'y': 0.0, 'z': 0.0}}, {'position': {'x': 10.0, 'y': 0.0, 'z': 2.0}}, {'position': {'x': 10.0, 'y': 8.0, 'z': 6.0}}, {'position': {'x': 0.0, 'y': 8.0, 'z': 6.0}}]\n", + " e.elevation = 1.5\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ( + "'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}}]", + "at least 2", + ), + ("'elevation':float('inf')", "finite"), + ( + "'vertices':[{'position':{'x':float('nan'),'y':0.0,'z':0.0}},{'position':{'x':1.0,'y':0.0,'z':0.0}}]", + "finite", + ), + ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), + ], + is_kind: |entity| matches!(entity, EntityType::Polyline3D(_)), + digest: |entity| match entity { + EntityType::Polyline3D(v) => format!( + "n{} el{:.1} lastz{:.1}", + v.vertices.len(), + v.elevation, + v.vertices.last().map_or(0.0, |x| x.position.z) + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::Polyline3D(v) = entity { + v.elevation = 2.5; + } + }, + expect_created: "n3 el0.0 lastz4.0", + expect_edited: "n4 el1.5 lastz6.0", + expect_reedited: "n4 el2.5 lastz6.0", + expect_edited_dwg: "n4 el0.0 lastz6.0", + expect_reedited_dwg: "n4 el0.0 lastz6.0", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] fn audit_python_spline_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!("doc.create_entity('Spline', degree=2, knots=[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], control_points=[{'x': 0.0, 'y': 0.0, 'z': 0.0}, {'x': 5.0, 'y': 5.0, 'z': 0.0}, {'x': 10.0, 'y': 0.0, 'z': 0.0}])\n"), - edit: concat!("e = doc.entities[HANDLE]\n", "with doc.transaction('Edit'):\n", " e.control_points = [{'x': 0.0, 'y': 0.0, 'z': 0.0}, {'x': 5.0, 'y': 8.0, 'z': 0.0}, {'x': 10.0, 'y': 0.0, 'z': 0.0}]\n", " e.weights = [1.0, 2.0, 1.0]\n", "doc.selection = [e]\n"), - rejects: &[ - ("'degree':0", "at least 1"), - ("'knots':[0.0,1.0]", "must hold"), - ("'weights':[1.0,0.0,1.0]", "greater than zero"), - ("'weights':[1.0]", "match"), - ("'control_points':[{'x':float('nan'),'y':0.0,'z':0.0},{'x':1.0,'y':0.0,'z':0.0},{'x':2.0,'y':0.0,'z':0.0}]", "finite"), - ("'knots':[0.0,0.0,1.0,0.5,1.0,1.0]", "nondecreasing"), - ], - is_kind: |entity| matches!(entity, EntityType::Spline(_)), - digest: |entity| match entity { - EntityType::Spline(v) => format!("deg{} cp{} y{:.1} w{:?}", v.degree, v.control_points.len(), v.control_points[1].y, v.weights), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::Spline(v) = entity { v.control_points[1].y = 9.0; }, - expect_created: "deg2 cp3 y5.0 w[]", - expect_edited: "deg2 cp3 y8.0 w[1.0, 2.0, 1.0]", - expect_reedited: "deg2 cp3 y9.0 w[1.0, 2.0, 1.0]", - expect_edited_dwg: "", - expect_reedited_dwg: "", - expect_edited_dxf: "", - expect_reedited_dxf: "", - }); + create: concat!( + "doc.create_entity('Spline', degree=2, knots=[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], control_points=[{'x': 0.0, 'y': 0.0, 'z': 0.0}, {'x': 5.0, 'y': 5.0, 'z': 0.0}, {'x': 10.0, 'y': 0.0, 'z': 0.0}])\n" + ), + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.control_points = [{'x': 0.0, 'y': 0.0, 'z': 0.0}, {'x': 5.0, 'y': 8.0, 'z': 0.0}, {'x': 10.0, 'y': 0.0, 'z': 0.0}]\n", + " e.weights = [1.0, 2.0, 1.0]\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ("'degree':0", "at least 1"), + ("'knots':[0.0,1.0]", "must hold"), + ("'weights':[1.0,0.0,1.0]", "greater than zero"), + ("'weights':[1.0]", "match"), + ( + "'control_points':[{'x':float('nan'),'y':0.0,'z':0.0},{'x':1.0,'y':0.0,'z':0.0},{'x':2.0,'y':0.0,'z':0.0}]", + "finite", + ), + ("'knots':[0.0,0.0,1.0,0.5,1.0,1.0]", "nondecreasing"), + ], + is_kind: |entity| matches!(entity, EntityType::Spline(_)), + digest: |entity| match entity { + EntityType::Spline(v) => format!( + "deg{} cp{} y{:.1} w{:?}", + v.degree, + v.control_points.len(), + v.control_points[1].y, + v.weights + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::Spline(v) = entity { + v.control_points[1].y = 9.0; + } + }, + expect_created: "deg2 cp3 y5.0 w[]", + expect_edited: "deg2 cp3 y8.0 w[1.0, 2.0, 1.0]", + expect_reedited: "deg2 cp3 y9.0 w[1.0, 2.0, 1.0]", + expect_edited_dwg: "", + expect_reedited_dwg: "", + expect_edited_dxf: "", + expect_reedited_dxf: "", + }); } #[test] @@ -556,60 +740,82 @@ fn audit_python_insert_lifecycle_over_real_ipc() { #[test] fn audit_python_attribute_definition_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!( - "# MAKEBLOCK\n", - "doc.create_entity('AttributeDefinition', owner_handle=BLOCKRECORD, tag='PART_NO', prompt='Part number',\n", - " default_value='PN-001', insertion_point=P(1.0, 2.0, 0.0), height=2.5, width_factor=1.25, oblique_angle=0.1,\n", - " rotation=0.25, horizontal_alignment='Center', vertical_alignment='Top', alignment_point=P(3.0, 4.0, 0.0),\n", - " flags={'invisible': True, 'constant': False, 'verify': True, 'preset': False, 'locked_position': False, 'annotative': False},\n", - " field_length=12, text_generation_flags=2, lock_position=True)\n"), - edit: concat!( - "e = doc.entities[HANDLE]\n", - "with doc.transaction('Edit'):\n", - " e.insertion_point = (4.0, 5.0, 0.0)\n", - " e.default_value = 'PN-002'\n", - " e.prompt = 'Serial'\n", - " e.height = 3.0\n", - " e.width_factor = 0.8\n", - " e.rotation = 0.5\n", - " e.oblique_angle = 0.2\n", - " e.horizontal_alignment = 'Right'\n", - " e.vertical_alignment = 'Middle'\n", - " e.flags = {'invisible': False, 'constant': True, 'verify': False, 'preset': True, 'locked_position': False, 'annotative': False}\n", - " e.field_length = 20\n", - "doc.selection = [e]\n"), - rejects: &[ - ("'tag':'BAD TAG'", "whitespace"), - ("'height':0.0", "greater than zero"), - ("'width_factor':0.0", "width_factor"), - ("'text_style':'Missing'", "does not exist"), - ("'owner_handle':999999", "read-only"), - ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), - ("'rotation':float('nan')", "finite"), - ("'horizontal_alignment':'Nowhere'", "unsupported"), - ], - is_kind: |entity| matches!(entity, EntityType::AttributeDefinition(_)), - digest: |entity| match entity { - EntityType::AttributeDefinition(v) => format!( - "{}|{}|{} ins{:.1},{:.1} al{:.1},{:.1} h{:.1} r{:.2} wf{:.2} ob{:.2} {:?}/{:?} f{}{}{}{} fl{} tg{} lock{}", - v.tag, v.prompt, v.default_value, v.insertion_point.x, v.insertion_point.y, - v.alignment_point.x, v.alignment_point.y, v.height, v.rotation, v.width_factor, v.oblique_angle, - v.horizontal_alignment, v.vertical_alignment, - u8::from(v.flags.invisible), u8::from(v.flags.constant), u8::from(v.flags.verify), u8::from(v.flags.preset), - v.field_length, v.text_generation_flags, u8::from(v.lock_position)), - _ => "wrong kind".into(), - }, - reedit: |entity| if let EntityType::AttributeDefinition(v) = entity { v.default_value = "PN-003".into(); }, - expect_created: "PART_NO|Part number|PN-001 ins1.0,2.0 al3.0,4.0 h2.5 r0.25 wf1.25 ob0.10 Center/Top f1010 fl12 tg2 lock1", - expect_edited: "PART_NO|Serial|PN-002 ins4.0,5.0 al3.0,4.0 h3.0 r0.50 wf0.80 ob0.20 Right/Middle f0101 fl20 tg2 lock1", - expect_reedited: "PART_NO|Serial|PN-003 ins4.0,5.0 al3.0,4.0 h3.0 r0.50 wf0.80 ob0.20 Right/Middle f0101 fl20 tg2 lock1", - // Reading a DXF derives a justified attribute's insertion point - // from its alignment point (#2728). - expect_edited_dxf: "PART_NO|Serial|PN-002 ins-11.0,-5.4 al3.0,4.0 h3.0 r0.50 wf0.80 ob0.20 Right/Middle f0101 fl20 tg2 lock1", - expect_reedited_dxf: "PART_NO|Serial|PN-003 ins-11.0,-5.4 al3.0,4.0 h3.0 r0.50 wf0.80 ob0.20 Right/Middle f0101 fl20 tg2 lock1", - expect_edited_dwg: "", - expect_reedited_dwg: "", - }); + create: concat!( + "# MAKEBLOCK\n", + "doc.create_entity('AttributeDefinition', owner_handle=BLOCKRECORD, tag='PART_NO', prompt='Part number',\n", + " default_value='PN-001', insertion_point=P(1.0, 2.0, 0.0), height=2.5, width_factor=1.25, oblique_angle=0.1,\n", + " rotation=0.25, horizontal_alignment='Center', vertical_alignment='Top', alignment_point=P(3.0, 4.0, 0.0),\n", + " flags={'invisible': True, 'constant': False, 'verify': True, 'preset': False, 'locked_position': False, 'annotative': False},\n", + " field_length=12, text_generation_flags=2, lock_position=True)\n" + ), + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.insertion_point = (4.0, 5.0, 0.0)\n", + " e.default_value = 'PN-002'\n", + " e.prompt = 'Serial'\n", + " e.height = 3.0\n", + " e.width_factor = 0.8\n", + " e.rotation = 0.5\n", + " e.oblique_angle = 0.2\n", + " e.horizontal_alignment = 'Right'\n", + " e.vertical_alignment = 'Middle'\n", + " e.flags = {'invisible': False, 'constant': True, 'verify': False, 'preset': True, 'locked_position': False, 'annotative': False}\n", + " e.field_length = 20\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ("'tag':'BAD TAG'", "whitespace"), + ("'height':0.0", "greater than zero"), + ("'width_factor':0.0", "width_factor"), + ("'text_style':'Missing'", "does not exist"), + ("'owner_handle':999999", "read-only"), + ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), + ("'rotation':float('nan')", "finite"), + ("'horizontal_alignment':'Nowhere'", "unsupported"), + ], + is_kind: |entity| matches!(entity, EntityType::AttributeDefinition(_)), + digest: |entity| match entity { + EntityType::AttributeDefinition(v) => format!( + "{}|{}|{} ins{:.1},{:.1} al{:.1},{:.1} h{:.1} r{:.2} wf{:.2} ob{:.2} {:?}/{:?} f{}{}{}{} fl{} tg{} lock{}", + v.tag, + v.prompt, + v.default_value, + v.insertion_point.x, + v.insertion_point.y, + v.alignment_point.x, + v.alignment_point.y, + v.height, + v.rotation, + v.width_factor, + v.oblique_angle, + v.horizontal_alignment, + v.vertical_alignment, + u8::from(v.flags.invisible), + u8::from(v.flags.constant), + u8::from(v.flags.verify), + u8::from(v.flags.preset), + v.field_length, + v.text_generation_flags, + u8::from(v.lock_position) + ), + _ => "wrong kind".into(), + }, + reedit: |entity| { + if let EntityType::AttributeDefinition(v) = entity { + v.default_value = "PN-003".into(); + } + }, + expect_created: "PART_NO|Part number|PN-001 ins1.0,2.0 al3.0,4.0 h2.5 r0.25 wf1.25 ob0.10 Center/Top f1010 fl12 tg2 lock1", + expect_edited: "PART_NO|Serial|PN-002 ins4.0,5.0 al3.0,4.0 h3.0 r0.50 wf0.80 ob0.20 Right/Middle f0101 fl20 tg2 lock1", + expect_reedited: "PART_NO|Serial|PN-003 ins4.0,5.0 al3.0,4.0 h3.0 r0.50 wf0.80 ob0.20 Right/Middle f0101 fl20 tg2 lock1", + // Reading a DXF derives a justified attribute's insertion point + // from its alignment point (#2728). + expect_edited_dxf: "PART_NO|Serial|PN-002 ins-11.0,-5.4 al3.0,4.0 h3.0 r0.50 wf0.80 ob0.20 Right/Middle f0101 fl20 tg2 lock1", + expect_reedited_dxf: "PART_NO|Serial|PN-003 ins-11.0,-5.4 al3.0,4.0 h3.0 r0.50 wf0.80 ob0.20 Right/Middle f0101 fl20 tg2 lock1", + expect_edited_dwg: "", + expect_reedited_dwg: "", + }); } #[test] @@ -655,9 +861,11 @@ fn audit_python_insert_creation_rules_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); let count = |host: &HostSession<'_>| { @@ -668,7 +876,8 @@ fn audit_python_insert_creation_rules_over_real_ipc() { }; let create = |name: &str, extra: &str| { format!( - "PY_EVAL ocs.active_document.create_entity('Insert', block_name='{name}', insert_point={{'x':0.0,'y':0.0,'z':0.0}}{extra})") + "PY_EVAL ocs.active_document.create_entity('Insert', block_name='{name}', insert_point={{'x':0.0,'y':0.0,'z':0.0}}{extra})" + ) }; // A valid insert of INNER into the drawing works. diff --git a/src/app/plugin_host/plugin_host_tests/class_registration.rs b/src/app/plugin_host/plugin_host_tests/class_registration.rs index cf9babb3a1..867b88fc81 100644 --- a/src/app/plugin_host/plugin_host_tests/class_registration.rs +++ b/src/app/plugin_host/plugin_host_tests/class_registration.rs @@ -25,9 +25,10 @@ fn boot_time_declaration_is_attributed_to_the_declared_package_id() { // The declared package id in its boot window passes the law. crate::plugin::external::with_manager(|m| m.begin_boot("opencad.example")); - assert!(host - .register_plugin_class("opencad.example", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("opencad.example", &traverse_class()) + .is_ok() + ); // After the boot window closes (and without a registry entry at // that id) the law refuses again: a different class key under the @@ -65,12 +66,14 @@ fn plugin_class_registration_is_owned_idempotent_and_refusing() { ); install_class_owner(); // Register, then re-register identical: idempotent, still one entry. - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); assert_eq!(host.app.tabs[0].plugin_classes.total(), 1); // A different schema refuses without touching the live class. let mut bumped = traverse_class(); @@ -114,9 +117,10 @@ fn plugin_class_registry_survives_across_request_sessions() { install_class_owner(); { let mut host = HostSession::new(&mut app, 0); - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); } // Session B: a DIFFERENT HostSession over the same tab (the IPC // server's per-request reality) stages the instance. @@ -139,9 +143,10 @@ fn selectable_custom_instances_are_selectable_but_native_edit_disabled() { app.tabs[0].is_start = false; install_class_owner(); let mut host = HostSession::new(&mut app, 0); - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); let mut instance = traverse_instance(); instance.selectable_custom = true; instance.design_record.clear(); @@ -191,9 +196,10 @@ fn plugin_class_instances_refuse_foreign_owners() { app.tabs[0].is_start = false; install_class_owner(); let mut host = HostSession::new(&mut app, 0); - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); // Another alive plugin sees the class but cannot stage it. crate::plugin::grip_points::install_in_process_sink("PLUGIN_RIVAL", |_host, _event| { ocs_plugin_api::host::CustomGripResponse::default() @@ -215,9 +221,10 @@ fn plugin_class_instance_stages_reference_only_with_identity_stamp() { let handles; { let mut host = HostSession::new(&mut app, 0); - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); handles = host .stage_plugin_class_instance("PLUGIN", &instance) .expect("the class instance stages"); @@ -273,9 +280,10 @@ fn class_stamp_and_display_set_survive_dxf_and_dwg_round_trips() { let handles; { let mut host = HostSession::new(&mut app, 0); - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); let mut instance = traverse_instance(); instance.selectable_custom = true; handles = host @@ -348,9 +356,10 @@ fn plugin_class_instance_refusals_change_nothing_and_record_no_steps() { app.tabs[0].is_start = false; install_class_owner(); let mut host = HostSession::new(&mut app, 0); - assert!(host - .register_plugin_class("PLUGIN", &traverse_class()) - .is_ok()); + assert!( + host.register_plugin_class("PLUGIN", &traverse_class()) + .is_ok() + ); let epoch_before = host.app.tabs[0].scene.geometry_epoch; // Unregistered class. let mut ghost = traverse_instance(); @@ -359,9 +368,10 @@ fn plugin_class_instance_refusals_change_nothing_and_record_no_steps() { // Schema version mismatch. let mut mismatch = traverse_instance(); mismatch.schema_version = 5; - assert!(host - .stage_plugin_class_instance("PLUGIN", &mismatch) - .is_err()); + assert!( + host.stage_plugin_class_instance("PLUGIN", &mismatch) + .is_err() + ); // Broken design parameter (the chain audit refuses at the contract). let mut broken = traverse_instance(); let ocs_plugin_api::host::PluginDisplayDescriptor::ParametricChain(chain) = &mut broken.design; @@ -369,9 +379,10 @@ fn plugin_class_instance_refusals_change_nothing_and_record_no_steps() { broken.tolerance = 1e-3; assert!(host.stage_plugin_class_instance("PLUGIN", &broken).is_err()); // Broken tolerance. - assert!(host - .stage_plugin_class_instance("PLUGIN", &traverse_instance_for(0.0)) - .is_err()); + assert!( + host.stage_plugin_class_instance("PLUGIN", &traverse_instance_for(0.0)) + .is_err() + ); assert_eq!(host.document().entities().count(), 0); assert_eq!(host.app.tabs[0].scene.geometry_epoch, epoch_before); } diff --git a/src/app/plugin_host/plugin_host_tests/host_entity_writes.rs b/src/app/plugin_host/plugin_host_tests/host_entity_writes.rs index 47c5f56838..c04d08de5c 100644 --- a/src/app/plugin_host/plugin_host_tests/host_entity_writes.rs +++ b/src/app/plugin_host/plugin_host_tests/host_entity_writes.rs @@ -177,14 +177,15 @@ fn reference_only_designation_is_not_written_to_dwg_or_dxf() { // The host writes nothing of its own into the document: no APPID // registration, no marker XDATA on the designated entity. assert!(host.document().app_ids.get("OCS").is_none()); - assert!(host - .document() - .get_entity(handle) - .expect("designated entity") - .common() - .extended_data - .get_record("OCS") - .is_none()); + assert!( + host.document() + .get_entity(handle) + .expect("designated entity") + .common() + .extended_data + .get_record("OCS") + .is_none() + ); let contains_marker = |bytes: &[u8]| bytes.windows(15).any(|window| window == b"REFERENCE_ONLY"); @@ -198,13 +199,15 @@ fn reference_only_designation_is_not_written_to_dwg_or_dxf() { ); let reloaded = crate::io::load_bytes("reference-only.dwg", dwg).unwrap(); assert!(reloaded.app_ids.get("OCS").is_none()); - assert!(reloaded - .get_entity(handle) - .expect("the line survives the round trip") - .common() - .extended_data - .get_record("OCS") - .is_none()); + assert!( + reloaded + .get_entity(handle) + .expect("the line survives the round trip") + .common() + .extended_data + .get_record("OCS") + .is_none() + ); assert!( !contains_marker(&document::DwgWriter::write_to_vec(&reloaded).unwrap()), "a re-save of the reopened file stays marker-free" @@ -220,13 +223,15 @@ fn reference_only_designation_is_not_written_to_dwg_or_dxf() { ); let reloaded = crate::io::load_bytes("reference-only.dxf", dxf).unwrap(); assert!(reloaded.app_ids.get("OCS").is_none()); - assert!(reloaded - .get_entity(handle) - .expect("the line survives the round trip") - .common() - .extended_data - .get_record("OCS") - .is_none()); + assert!( + reloaded + .get_entity(handle) + .expect("the line survives the round trip") + .common() + .extended_data + .get_record("OCS") + .is_none() + ); } #[test] @@ -285,9 +290,11 @@ fn user_paths_refuse_and_plugin_paths_write_reference_only_entities() { // The user in-place update refuses; the user batch skips only the // reference-only member; the plugin-owned variants write through. - assert!(!host.app.tabs[0] - .scene - .update_entity(reference_test_line(20.0, 0.0, handle))); + assert!( + !host.app.tabs[0] + .scene + .update_entity(reference_test_line(20.0, 0.0, handle)) + ); let applied = host.app.tabs[0].scene.update_entities(vec![ reference_test_line(20.0, 0.0, handle), reference_test_line(20.0, 5.0, plain), diff --git a/src/app/plugin_host/plugin_host_tests/kernel_boolean_audits.rs b/src/app/plugin_host/plugin_host_tests/kernel_boolean_audits.rs index 92651f0617..9494896a05 100644 --- a/src/app/plugin_host/plugin_host_tests/kernel_boolean_audits.rs +++ b/src/app/plugin_host/plugin_host_tests/kernel_boolean_audits.rs @@ -187,7 +187,9 @@ fn spike_kernel_timings() { "{}", sm::by_matrix( &boxed, - [1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 5., 5., 5., 1.] + [ + 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 5., 5., 5., 1. + ] ) .is_some() ) @@ -245,9 +247,11 @@ fn audit_python_solid3d_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); let solids = |host: &HostSession<'_>| -> Vec { @@ -328,11 +332,13 @@ fn audit_python_solid3d_lifecycle_over_real_ipc() { dispatch(host, &format!("PY_EVAL {expression}")); last(host) }; - assert!(read( - &mut host, - &format!("ocs.active_document.entities[{}].kind", list[0].value()) - ) - .contains("Solid3D")); + assert!( + read( + &mut host, + &format!("ocs.active_document.entities[{}].kind", list[0].value()) + ) + .contains("Solid3D") + ); // E: rigid moves keep the volume and move the extent exactly. let box_handle = list[0]; @@ -355,7 +361,13 @@ fn audit_python_solid3d_lifecycle_over_real_ipc() { close(low[0], 0.0, 1e-6) && close(high[1], 8.0, 1e-6) && close(high[2], 7.0, 1e-6), "{low:?} {high:?}" ); - dispatch(&mut host, &format!("PY_EVAL ocs.active_document.solids.rotate({}, 'z', 0.7853981633974483, (5, 5, 5)).handle", box_handle.value())); + dispatch( + &mut host, + &format!( + "PY_EVAL ocs.active_document.solids.rotate({}, 'z', 0.7853981633974483, (5, 5, 5)).handle", + box_handle.value() + ), + ); dispatch( &mut host, &format!( @@ -590,9 +602,11 @@ fn audit_python_body_transform_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let extent = |host: &HostSession<'_>| { let Some(EntityType::Body(b)) = host.document().get_entity(handle) else { @@ -609,14 +623,15 @@ fn audit_python_body_transform_over_real_ipc() { handle.value() ), ); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains("Body")); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains("Body") + ); dispatch( &mut host, &format!( @@ -673,9 +688,11 @@ fn audit_python_region_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); let regions = |host: &HostSession<'_>| -> Vec { @@ -949,9 +966,11 @@ fn audit_python_surface_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); let sorted = |mut list: Vec| { @@ -1339,9 +1358,11 @@ fn audit_python_boolean_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); let solids_in = |document: &Document| { @@ -1661,9 +1682,11 @@ fn audit_python_boolean_kernel_refusal_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let script = std::env::temp_dir().join(format!("ocs_boolean_refusal_{}.py", std::process::id())); @@ -1689,42 +1712,68 @@ fn audit_python_boolean_kernel_refusal_over_real_ipc() { #[test] fn audit_python_section_symbol_lifecycle_over_real_ipc() { run_mesh_lifecycle(&MeshCase { - create: concat!( - "doc.create_entity('SectionSymbol', symbol_scale=1.0, points=[\n", - " {'point': P(0.0, 0.0, 0.0), 'label': 'A', 'label_offset': P(0.0, 2.0, 0.0)},\n", - " {'point': P(40.0, 0.0, 0.0), 'label': 'A', 'label_offset': P(0.0, 2.0, 0.0)}])\n"), - edit: concat!( - "e = doc.entities[HANDLE]\n", - "with doc.transaction('Edit'):\n", - " e.points = [{'point': P(0.0, 0.0, 0.0), 'label': 'B', 'label_offset': P(0.0, 3.0, 0.0)},\n", - " {'point': P(20.0, 10.0, 0.0), 'bulge': 0.0}, {'point': P(40.0, 0.0, 0.0), 'label': 'B', 'label_offset': P(0.0, -3.0, 0.0)}]\n", - " e.symbol_scale = 2.0\n", - "doc.selection = [e]\n"), - rejects: &[ - ("'points':[{'point':{'x':0.0,'y':0.0,'z':0.0}}]", "at least 2 points"), - ("'points':[{'point':{'x':float('nan'),'y':0.0,'z':0.0}},{'point':{'x':1.0,'y':0.0,'z':0.0}}]", "finite"), - ("'symbol_scale':0.0", "greater than zero"), - ("'style_handle':999999", "not an existing SectionViewStyle"), - ("'view_rep_handle':999999", "not an existing ViewRep"), - ("'raw_point_count_90':9", "read-only"), - ("'end_a':[1.0, 1.0]", "read-only"), - ], - is_kind: |entity| matches!(entity, EntityType::SectionSymbol(_)), - digest: |entity| match entity { - EntityType::SectionSymbol(v) => format!("n{} ends {:.1},{:.1}->{:.1},{:.1} label{} tick{:.1}/{:.1} scale{:.1} counts{}/{}", - v.points.len(), v.end_a[0], v.end_a[1], v.end_b[0], v.end_b[1], v.label, v.tick_a, v.tick_b, - v.symbol_scale, v.raw_point_count_90, v.raw_point_record_count), - other => format!("wrong kind {}", format!("{other:?}").split('(').next().unwrap()), - }, - reedit: |entity| if let EntityType::SectionSymbol(v) = entity { v.symbol_scale = 3.0; }, - expect_created: "n2 ends 0.0,0.0->40.0,0.0 labelA tick2.0/2.0 scale1.0 counts2/2", - expect_edited: "n3 ends 0.0,0.0->40.0,0.0 labelB tick3.0/-3.0 scale2.0 counts3/3", - expect_reedited: "n3 ends 0.0,0.0->40.0,0.0 labelB tick3.0/-3.0 scale3.0 counts3/3", - expect_edited_dxf: "", - expect_reedited_dxf: "", - expect_edited_dwg: "", - expect_reedited_dwg: "", - }); + create: concat!( + "doc.create_entity('SectionSymbol', symbol_scale=1.0, points=[\n", + " {'point': P(0.0, 0.0, 0.0), 'label': 'A', 'label_offset': P(0.0, 2.0, 0.0)},\n", + " {'point': P(40.0, 0.0, 0.0), 'label': 'A', 'label_offset': P(0.0, 2.0, 0.0)}])\n" + ), + edit: concat!( + "e = doc.entities[HANDLE]\n", + "with doc.transaction('Edit'):\n", + " e.points = [{'point': P(0.0, 0.0, 0.0), 'label': 'B', 'label_offset': P(0.0, 3.0, 0.0)},\n", + " {'point': P(20.0, 10.0, 0.0), 'bulge': 0.0}, {'point': P(40.0, 0.0, 0.0), 'label': 'B', 'label_offset': P(0.0, -3.0, 0.0)}]\n", + " e.symbol_scale = 2.0\n", + "doc.selection = [e]\n" + ), + rejects: &[ + ( + "'points':[{'point':{'x':0.0,'y':0.0,'z':0.0}}]", + "at least 2 points", + ), + ( + "'points':[{'point':{'x':float('nan'),'y':0.0,'z':0.0}},{'point':{'x':1.0,'y':0.0,'z':0.0}}]", + "finite", + ), + ("'symbol_scale':0.0", "greater than zero"), + ("'style_handle':999999", "not an existing SectionViewStyle"), + ("'view_rep_handle':999999", "not an existing ViewRep"), + ("'raw_point_count_90':9", "read-only"), + ("'end_a':[1.0, 1.0]", "read-only"), + ], + is_kind: |entity| matches!(entity, EntityType::SectionSymbol(_)), + digest: |entity| match entity { + EntityType::SectionSymbol(v) => format!( + "n{} ends {:.1},{:.1}->{:.1},{:.1} label{} tick{:.1}/{:.1} scale{:.1} counts{}/{}", + v.points.len(), + v.end_a[0], + v.end_a[1], + v.end_b[0], + v.end_b[1], + v.label, + v.tick_a, + v.tick_b, + v.symbol_scale, + v.raw_point_count_90, + v.raw_point_record_count + ), + other => format!( + "wrong kind {}", + format!("{other:?}").split('(').next().unwrap() + ), + }, + reedit: |entity| { + if let EntityType::SectionSymbol(v) = entity { + v.symbol_scale = 3.0; + } + }, + expect_created: "n2 ends 0.0,0.0->40.0,0.0 labelA tick2.0/2.0 scale1.0 counts2/2", + expect_edited: "n3 ends 0.0,0.0->40.0,0.0 labelB tick3.0/-3.0 scale2.0 counts3/3", + expect_reedited: "n3 ends 0.0,0.0->40.0,0.0 labelB tick3.0/-3.0 scale3.0 counts3/3", + expect_edited_dxf: "", + expect_reedited_dxf: "", + expect_edited_dwg: "", + expect_reedited_dwg: "", + }); } #[test] @@ -1764,9 +1813,11 @@ fn audit_python_section_symbol_references_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); let count = |host: &HostSession<'_>| { @@ -1777,7 +1828,8 @@ fn audit_python_section_symbol_references_over_real_ipc() { }; let create = |extra: &str| { format!( - "PY_EVAL ocs.active_document.create_entity('SectionSymbol', points=[{{'point': {{'x': 0.0, 'y': 0.0, 'z': 0.0}}}}, {{'point': {{'x': 10.0, 'y': 0.0, 'z': 0.0}}}}]{extra}).handle") + "PY_EVAL ocs.active_document.create_entity('SectionSymbol', points=[{{'point': {{'x': 0.0, 'y': 0.0, 'z': 0.0}}}}, {{'point': {{'x': 10.0, 'y': 0.0, 'z': 0.0}}}}]{extra}).handle" + ) }; // A symbol may reference the drawing's own style and view representation. dispatch( diff --git a/src/app/plugin_host/plugin_host_tests/staged_entity_lifecycle.rs b/src/app/plugin_host/plugin_host_tests/staged_entity_lifecycle.rs index 6c375a880b..b7a125e80e 100644 --- a/src/app/plugin_host/plugin_host_tests/staged_entity_lifecycle.rs +++ b/src/app/plugin_host/plugin_host_tests/staged_entity_lifecycle.rs @@ -31,9 +31,11 @@ fn staged_python_plugin_line_lifecycle_over_real_ipc() { .expect("spawn staged Python plugin"); assert_eq!(process.id(), "opencad.python"); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; dispatch( &mut host, @@ -54,10 +56,13 @@ fn staged_python_plugin_line_lifecycle_over_real_ipc() { matches!(host.document().get_entity(handle), Some(EntityType::Line(line)) if line.end.x == 1.0) ); let before_edit = host.document().get_entity(handle).unwrap().clone(); - dispatch(&mut host, &format!( + dispatch( + &mut host, + &format!( "PY_EVAL ocs.update_many('Move line', [{{'handle':{},'end':{{'x':5.0,'y':0.0,'z':0.0}}}}])", handle.value() - )); + ), + ); let mut expected_after_edit = before_edit; let EntityType::Line(expected_line) = &mut expected_after_edit else { unreachable!() @@ -68,27 +73,35 @@ fn staged_python_plugin_line_lifecycle_over_real_ipc() { Some(&expected_after_edit), "partial Python edit must preserve every unmentioned common and geometry field" ); - dispatch(&mut host, &format!( + dispatch( + &mut host, + &format!( "PY_EVAL ocs.update_many('Reject NaN', [{{'handle':{},'start':{{'x':float('nan'),'y':0.0,'z':0.0}}}}])", handle.value() - )); + ), + ); assert_eq!( host.document().get_entity(handle), Some(&expected_after_edit), "invalid geometry changed the line" ); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains("finite coordinates")); - dispatch(&mut host, &format!( + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains("finite coordinates") + ); + dispatch( + &mut host, + &format!( "PY_EVAL ocs.update_many('Reject duplicate', [{{'handle':{},'end':{{'x':8.0,'y':0.0,'z':0.0}}}},{{'handle':{},'end':{{'x':9.0,'y':0.0,'z':0.0}}}}])", - handle.value(), handle.value() - )); + handle.value(), + handle.value() + ), + ); assert!( matches!(host.document().get_entity(handle), Some(EntityType::Line(line)) if line.end.x == 5.0), "rejected batch changed the line" @@ -162,9 +175,11 @@ fn staged_python_tolerance_lifecycle_over_real_ipc() { ) .expect("spawn staged Python plugin"); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; dispatch( &mut host, @@ -197,14 +212,15 @@ fn staged_python_tolerance_lifecycle_over_real_ipc() { handle.value() ), ); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains("POSITION%%v0.1")); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains("POSITION%%v0.1") + ); let script_path = std::env::temp_dir().join(format!( "ocs_tolerance_document_model_{}.py", @@ -254,30 +270,40 @@ fn staged_python_tolerance_lifecycle_over_real_ipc() { "Python selection did not reach the canvas" ); - dispatch(&mut host, &format!( + dispatch( + &mut host, + &format!( "PY_EVAL ocs.update_many('Reject direction', [{{'handle':{},'direction':{{'x':2.0,'y':0.0,'z':0.0}}}}])", - handle.value())); + handle.value() + ), + ); assert_eq!(host.document().get_entity(handle), Some(&expected)); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains("unit vector")); - dispatch(&mut host, &format!( + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains("unit vector") + ); + dispatch( + &mut host, + &format!( "PY_EVAL ocs.update_many('Reject style', [{{'handle':{},'dimension_style_name':'Missing'}}])", - handle.value())); + handle.value() + ), + ); assert_eq!(host.document().get_entity(handle), Some(&expected)); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains("does not exist")); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains("does not exist") + ); let dwg_bytes = document::DwgWriter::write_to_vec(host.document()).unwrap(); let dwg_doc = document::DwgReader::from_stream(std::io::Cursor::new(dwg_bytes)) @@ -362,9 +388,11 @@ fn staged_python_shape_lifecycle_over_real_ipc() { ) .expect("spawn staged Python plugin"); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; dispatch( &mut host, @@ -393,14 +421,15 @@ fn staged_python_shape_lifecycle_over_real_ipc() { handle.value() ), ); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains("ARROW")); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains("ARROW") + ); let script_path = std::env::temp_dir().join(format!( "ocs_shape_document_model_{}.py", @@ -479,14 +508,15 @@ fn staged_python_shape_lifecycle_over_real_ipc() { ), ); assert_eq!(host.document().get_entity(handle), Some(&expected)); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains("does not exist")); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains("does not exist") + ); let dwg_bytes = document::DwgWriter::write_to_vec(host.document()).unwrap(); let dwg_doc = crate::io::load_bytes("shape.dwg", dwg_bytes).unwrap(); @@ -580,9 +610,11 @@ fn staged_python_attribute_definition_lifecycle_over_real_ipc() { ) .expect("spawn staged Python plugin"); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; dispatch( &mut host, @@ -608,17 +640,23 @@ fn staged_python_attribute_definition_lifecycle_over_real_ipc() { assert_eq!(created.common.owner_handle, block_record_handle); assert_eq!(created.tag, "PART_NO"); assert_eq!(created.text_style, "Standard"); - assert!(host - .document() - .block_records - .get("TAGBLOCK") - .unwrap() - .entity_handles - .contains(&handle)); + assert!( + host.document() + .block_records + .get("TAGBLOCK") + .unwrap() + .entity_handles + .contains(&handle) + ); let created = created.clone(); - dispatch(&mut host, &format!( + dispatch( + &mut host, + &format!( "PY_EVAL (ocs.active_document.entities[{}].tag, ocs.active_document.entities[{}].owner_handle)", - handle.value(), handle.value())); + handle.value(), + handle.value() + ), + ); let readback = &host.app.command_line.history.last().unwrap().text; assert!( readback.contains("PART_NO") && readback.contains(&block_record_handle.value().to_string()) @@ -677,10 +715,12 @@ fn staged_python_attribute_definition_lifecycle_over_real_ipc() { panic!("expected attribute definition text"); }; assert!(!strokes.is_empty()); - assert!(strokes.iter().any(|stroke| stroke - .run - .as_ref() - .is_some_and(|run| run.text.contains("PART_NO")))); + assert!(strokes.iter().any(|stroke| { + stroke + .run + .as_ref() + .is_some_and(|run| run.text.contains("PART_NO")) + })); for (label, patch, message) in [ ("Reject tag", "'tag':'BAD TAG'", "whitespace"), @@ -696,14 +736,15 @@ fn staged_python_attribute_definition_lifecycle_over_real_ipc() { ), ); assert_eq!(host.document().get_entity(handle), Some(&expected)); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains(message)); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains(message) + ); } let assert_persisted = |label: &str, document: &Document, full_text_state: bool| { @@ -724,12 +765,14 @@ fn staged_python_attribute_definition_lifecycle_over_real_ipc() { "{label}: {actual:?}" ); } - assert!(document - .block_records - .get("TAGBLOCK") - .unwrap() - .entity_handles - .contains(&handle)); + assert!( + document + .block_records + .get("TAGBLOCK") + .unwrap() + .entity_handles + .contains(&handle) + ); assert!( matches!(document.get_entity(insert_handle), Some(EntityType::Insert(value)) if value.block_name == "TAGBLOCK") @@ -854,9 +897,11 @@ fn staged_python_attribute_entity_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; dispatch( &mut host, @@ -944,14 +989,15 @@ fn staged_python_attribute_entity_lifecycle_over_real_ipc() { host.nested_attribute(attribute_handle), Some(expected.clone()) ); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains(message)); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains(message) + ); } let assert_saved = |document: &Document| { @@ -1056,9 +1102,11 @@ fn staged_python_hatch_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let script = std::env::temp_dir().join(format!("ocs_hatch_create_{}.py", std::process::id())); std::fs::write(&script, concat!( @@ -1090,11 +1138,13 @@ fn staged_python_hatch_lifecycle_over_real_ipc() { ) }); let created = host.document().get_entity(hatch_handle).unwrap().clone(); - assert!(host.app.tabs[0] - .scene - .hatches - .get(&hatch_handle) - .is_some_and(|model| model.boundary.len() >= 4 && model.name == "SOLID")); + assert!( + host.app.tabs[0] + .scene + .hatches + .get(&hatch_handle) + .is_some_and(|model| model.boundary.len() >= 4 && model.name == "SOLID") + ); dispatch( &mut host, &format!( @@ -1102,14 +1152,15 @@ fn staged_python_hatch_lifecycle_over_real_ipc() { hatch_handle.value() ), ); - assert!(host - .app - .command_line - .history - .last() - .unwrap() - .text - .contains("SOLID")); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains("SOLID") + ); let script = std::env::temp_dir().join(format!("ocs_hatch_edit_{}.py", std::process::id())); std::fs::write(&script, format!(concat!( @@ -1148,28 +1199,45 @@ fn staged_python_hatch_lifecycle_over_real_ipc() { } ); assert_eq!(host.selection(), vec![hatch_handle]); - assert!(host.app.tabs[0] - .scene - .hatches - .get(&hatch_handle) - .is_some_and(|model| model.boundary.len() >= 4 - && model.name == "TEST" - && matches!(&model.pattern, + assert!( + host.app.tabs[0] + .scene + .hatches + .get(&hatch_handle) + .is_some_and(|model| model.boundary.len() >= 4 + && model.name == "TEST" + && matches!(&model.pattern, crate::scene::model::hatch_model::HatchPattern::Pattern(lines) - if !lines.is_empty()))); + if !lines.is_empty())) + ); for (patch, message) in [ - ("'pattern_scale':0.0", "greater than zero"), - ("'is_associative':True", "requires boundary handles"), - ("'gradient_color':{}", "outside the editable schema"), - ("'paths':[{'flags':1,'edges':[{'kind':'Line','value':{'start':{'x':0.0,'y':0.0},'end':{'x':1.0,'y':0.0}}}],'boundary_handles':[]}]", "not closed"), - ] { - dispatch(&mut host, &format!( + ("'pattern_scale':0.0", "greater than zero"), + ("'is_associative':True", "requires boundary handles"), + ("'gradient_color':{}", "outside the editable schema"), + ( + "'paths':[{'flags':1,'edges':[{'kind':'Line','value':{'start':{'x':0.0,'y':0.0},'end':{'x':1.0,'y':0.0}}}],'boundary_handles':[]}]", + "not closed", + ), + ] { + dispatch( + &mut host, + &format!( "PY_EVAL ocs.update_many('Reject hatch', [{{'handle':{}, {patch}}}])", - hatch_handle.value())); - assert_eq!(host.document().get_entity(hatch_handle), Some(&expected)); - assert!(host.app.command_line.history.last().unwrap().text.contains(message)); - } + hatch_handle.value() + ), + ); + assert_eq!(host.document().get_entity(hatch_handle), Some(&expected)); + assert!( + host.app + .command_line + .history + .last() + .unwrap() + .text + .contains(message) + ); + } let assert_saved = |document: &Document| { assert!( @@ -1235,10 +1303,12 @@ fn staged_python_hatch_lifecycle_over_real_ipc() { .unwrap(), ), ] { - assert!(crate::io::load_bytes(name, bytes) - .unwrap() - .get_entity(hatch_handle) - .is_none()); + assert!( + crate::io::load_bytes(name, bytes) + .unwrap() + .get_entity(hatch_handle) + .is_none() + ); } drop(process); drop(host); @@ -1255,17 +1325,21 @@ fn staged_python_hatch_lifecycle_over_real_ipc() { Some(&created) ); app.undo_steps(1); - assert!(app.tabs[0] - .scene - .document - .get_entity(hatch_handle) - .is_none()); + assert!( + app.tabs[0] + .scene + .document + .get_entity(hatch_handle) + .is_none() + ); app.redo_steps(3); - assert!(app.tabs[0] - .scene - .document - .get_entity(hatch_handle) - .is_none()); + assert!( + app.tabs[0] + .scene + .document + .get_entity(hatch_handle) + .is_none() + ); } #[test] @@ -1287,9 +1361,11 @@ fn staged_python_leader_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last_output = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); @@ -1350,10 +1426,12 @@ fn staged_python_leader_lifecycle_over_real_ipc() { panic!("expected leader linework"); }; assert!(points.len() >= leader.vertices.len()); - assert!(points - .iter() - .flatten() - .all(|value| value.is_nan() || value.is_finite())); + assert!( + points + .iter() + .flatten() + .all(|value| value.is_nan() || value.is_finite()) + ); }; assert_geometry(&created, host.document()); dispatch( @@ -1594,20 +1672,24 @@ fn staged_python_leader_lifecycle_over_real_ipc() { Some(&created) ); app.undo_steps(1); - assert!(app.tabs[0] - .scene - .document - .get_entity(leader_handle) - .is_none()); + assert!( + app.tabs[0] + .scene + .document + .get_entity(leader_handle) + .is_none() + ); assert!(app.tabs[0].scene.document.get_entity(text_handle).is_some()); app.undo_steps(1); assert!(app.tabs[0].scene.document.get_entity(text_handle).is_none()); app.redo_steps(4); - assert!(app.tabs[0] - .scene - .document - .get_entity(leader_handle) - .is_none()); + assert!( + app.tabs[0] + .scene + .document + .get_entity(leader_handle) + .is_none() + ); assert!(app.tabs[0].scene.document.get_entity(text_handle).is_none()); } @@ -1630,9 +1712,11 @@ fn staged_python_mline_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last_output = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); @@ -1693,11 +1777,13 @@ fn staged_python_mline_lifecycle_over_real_ipc() { assert_eq!(mline.vertices.len(), expected_vertices); let lines = crate::entities::mline::mline_lines(mline, document); assert!(lines.len() >= 2, "expected styled element lines"); - assert!(lines - .iter() - .flat_map(|line| &line.points) - .flatten() - .all(|v| v.is_finite())); + assert!( + lines + .iter() + .flat_map(|line| &line.points) + .flatten() + .all(|v| v.is_finite()) + ); }; assert_lines(&created, host.document(), 2); @@ -1757,21 +1843,49 @@ fn staged_python_mline_lifecycle_over_real_ipc() { assert_eq!(host.selection(), vec![handle]); for (patch, message) in [ - ("'style_name':'Missing'", "does not exist"), - ("'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}}]", "at least 2"), - ("'scale_factor':0.0", "nonzero"), - ("'flags':64", "unknown bits"), - ("'flags':3,'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}},{'position':{'x':1.0,'y':0.0,'z':0.0}}]", "requires at least 3"), - ("'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}},{'position':{'x':0.0,'y':0.0,'z':0.0}}]", "coincide"), - ("'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}},{'position':{'x':1.0,'y':float('nan'),'z':0.0}}]", "finite"), - ("'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0},'segments':[{}]},{'position':{'x':1.0,'y':0.0,'z':0.0}}]", "segments but style"), - ("'start_point':{'x':5.0,'y':5.0,'z':0.0}", "read-only"), - ] { - dispatch(&mut host, &format!( - "PY_EVAL ocs.update_many('Reject mline', [{{'handle':{}, {patch}}}])", handle.value())); - assert_eq!(host.document().get_entity(handle), Some(&expected), "{patch}"); - assert!(last_output(&host).contains(message), "{patch}: {}", last_output(&host)); - } + ("'style_name':'Missing'", "does not exist"), + ( + "'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}}]", + "at least 2", + ), + ("'scale_factor':0.0", "nonzero"), + ("'flags':64", "unknown bits"), + ( + "'flags':3,'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}},{'position':{'x':1.0,'y':0.0,'z':0.0}}]", + "requires at least 3", + ), + ( + "'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}},{'position':{'x':0.0,'y':0.0,'z':0.0}}]", + "coincide", + ), + ( + "'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0}},{'position':{'x':1.0,'y':float('nan'),'z':0.0}}]", + "finite", + ), + ( + "'vertices':[{'position':{'x':0.0,'y':0.0,'z':0.0},'segments':[{}]},{'position':{'x':1.0,'y':0.0,'z':0.0}}]", + "segments but style", + ), + ("'start_point':{'x':5.0,'y':5.0,'z':0.0}", "read-only"), + ] { + dispatch( + &mut host, + &format!( + "PY_EVAL ocs.update_many('Reject mline', [{{'handle':{}, {patch}}}])", + handle.value() + ), + ); + assert_eq!( + host.document().get_entity(handle), + Some(&expected), + "{patch}" + ); + assert!( + last_output(&host).contains(message), + "{patch}: {}", + last_output(&host) + ); + } dispatch( &mut host, &format!( @@ -1874,10 +1988,12 @@ fn staged_python_mline_lifecycle_over_real_ipc() { .unwrap(), ), ] { - assert!(crate::io::load_bytes(name, bytes) - .unwrap() - .get_entity(handle) - .is_none()); + assert!( + crate::io::load_bytes(name, bytes) + .unwrap() + .get_entity(handle) + .is_none() + ); } drop(process); drop(host); @@ -1918,25 +2034,63 @@ fn staged_python_dimension_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last_output = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); // (subtype, python fields, expected measurement) let fixtures: [(&str, &str, f64); 9] = [ - ("Linear", "definition_point=P(10,5), first_point=P(0,0), second_point=P(10,0)", 10.0), - ("Aligned", "definition_point=P(1,5.5), first_point=P(0,0), second_point=P(3,4)", 5.0), - ("Radius", "definition_point=P(5,0), angle_vertex=P(0,0)", 5.0), - ("Diameter", "definition_point=P(10,0), angle_vertex=P(0,0)", 10.0), - ("Angular3Pt", "definition_point=P(3,3), first_point=P(5,0), second_point=P(0,5), angle_vertex=P(0,0)", std::f64::consts::FRAC_PI_2), - ("Angular2Ln", "definition_point=P(0,5), dimension_arc=P(3,3), first_point=P(0,0), second_point=P(5,0), angle_vertex=P(0,0)", std::f64::consts::FRAC_PI_2), - ("Ordinate", "feature_location=P(5,3), leader_endpoint=P(5,8), is_ordinate_type_x=True", 5.0), - ("Arc", "definition_point=P(3.5,3.5), first_extension_point=P(5,0), second_extension_point=P(0,5), center_point=P(0,0), arc_start_parameter=0.0, arc_end_parameter=1.5707963267948966", 5.0 * std::f64::consts::FRAC_PI_2), - ("LargeRadial", "definition_point=P(10,0), chord_point=P(4,0)", 6.0), - ]; + ( + "Linear", + "definition_point=P(10,5), first_point=P(0,0), second_point=P(10,0)", + 10.0, + ), + ( + "Aligned", + "definition_point=P(1,5.5), first_point=P(0,0), second_point=P(3,4)", + 5.0, + ), + ( + "Radius", + "definition_point=P(5,0), angle_vertex=P(0,0)", + 5.0, + ), + ( + "Diameter", + "definition_point=P(10,0), angle_vertex=P(0,0)", + 10.0, + ), + ( + "Angular3Pt", + "definition_point=P(3,3), first_point=P(5,0), second_point=P(0,5), angle_vertex=P(0,0)", + std::f64::consts::FRAC_PI_2, + ), + ( + "Angular2Ln", + "definition_point=P(0,5), dimension_arc=P(3,3), first_point=P(0,0), second_point=P(5,0), angle_vertex=P(0,0)", + std::f64::consts::FRAC_PI_2, + ), + ( + "Ordinate", + "feature_location=P(5,3), leader_endpoint=P(5,8), is_ordinate_type_x=True", + 5.0, + ), + ( + "Arc", + "definition_point=P(3.5,3.5), first_extension_point=P(5,0), second_extension_point=P(0,5), center_point=P(0,0), arc_start_parameter=0.0, arc_end_parameter=1.5707963267948966", + 5.0 * std::f64::consts::FRAC_PI_2, + ), + ( + "LargeRadial", + "definition_point=P(10,0), chord_point=P(4,0)", + 6.0, + ), + ]; let mut script = String::from("def P(x, y): return {'x': x, 'y': y, 'z': 0.0}\ndoc = ocs.active_document\n"); for (subtype, fields, _) in &fixtures { @@ -2129,14 +2283,30 @@ fn staged_python_dimension_lifecycle_over_real_ipc() { ); assert_eq!(host.document().get_entity(linear), Some(&expected_linear)); for (patch, message) in [ - ("ocs.active_document.create_entity('Dimension', definition_point=P(0,0))", "requires subtype"), - ("ocs.active_document.create_entity('Dimension', subtype='Cone')", "unsupported Dimension subtype"), - ("ocs.active_document.create_entity('Dimension', subtype='Linear', first_point=P(0,0), second_point=P(1,0))", "requires definition_point"), - ] { - dispatch(&mut host, &format!("PY_EVAL (lambda P: {patch})(lambda x, y: {{'x': x, 'y': y, 'z': 0.0}})")); - assert_eq!(handles_by_subtype(host.document()).len(), 9, "{patch}"); - assert!(last_output(&host).contains(message), "{patch}: {}", last_output(&host)); - } + ( + "ocs.active_document.create_entity('Dimension', definition_point=P(0,0))", + "requires subtype", + ), + ( + "ocs.active_document.create_entity('Dimension', subtype='Cone')", + "unsupported Dimension subtype", + ), + ( + "ocs.active_document.create_entity('Dimension', subtype='Linear', first_point=P(0,0), second_point=P(1,0))", + "requires definition_point", + ), + ] { + dispatch( + &mut host, + &format!("PY_EVAL (lambda P: {patch})(lambda x, y: {{'x': x, 'y': y, 'z': 0.0}})"), + ); + assert_eq!(handles_by_subtype(host.document()).len(), 9, "{patch}"); + assert!( + last_output(&host).contains(message), + "{patch}: {}", + last_output(&host) + ); + } // DWG and DXF: every subtype is recorded separately. let mut failures = Vec::new(); @@ -2254,9 +2424,11 @@ fn staged_python_multileader_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last_output = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); @@ -2477,10 +2649,12 @@ fn staged_python_multileader_lifecycle_over_real_ipc() { .unwrap(), ), ] { - assert!(crate::io::load_bytes(name, bytes) - .unwrap() - .get_entity(handle) - .is_none()); + assert!( + crate::io::load_bytes(name, bytes) + .unwrap() + .get_entity(handle) + .is_none() + ); } drop(process); drop(host); @@ -2521,14 +2695,19 @@ fn staged_python_table_lifecycle_over_real_ipc() { ) .unwrap(); let dispatch = |host: &mut HostSession<'_>, command: &str| { - assert!(process - .dispatch(host, command, &mut |_| {}) - .expect("Python dispatch")); + assert!( + process + .dispatch(host, command, &mut |_| {}) + .expect("Python dispatch") + ); }; let last_output = |host: &HostSession<'_>| host.app.command_line.history.last().unwrap().text.clone(); - dispatch(&mut host, "PY_EVAL ocs.active_document.create_entity('Table', insertion_point={'x':5.0,'y':5.0,'z':0.0}).handle"); + dispatch( + &mut host, + "PY_EVAL ocs.active_document.create_entity('Table', insertion_point={'x':5.0,'y':5.0,'z':0.0}).handle", + ); let handle = host .document() .entities() @@ -2592,22 +2771,50 @@ fn staged_python_table_lifecycle_over_real_ipc() { assert!(!host.app.tabs[0].scene.wire_models_for(&[handle]).is_empty()); for (patch, message) in [ - ("'columns':[{'name':'A','width':0.0},{'width':1.0},{'width':1.0}]", "greater than zero"), - ("'columns':[{'width':5.0}]", "cells but the table has 1 columns"), - ("'columns':[]", "at least one row and one column"), - ("'merged_ranges':[{'top_row':0,'left_col':0,'bottom_row':9,'right_col':0}]", "outside the"), - ("'merged_ranges':[{'top_row':1,'left_col':0,'bottom_row':2,'right_col':1},{'top_row':2,'left_col':1,'bottom_row':3,'right_col':2}]", "overlaps"), - ("'table_style_handle':999999", "does not exist"), - ("'block_name':'x'", "read-only"), - ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), - ("'break_spacing':-1.0", "non-negative"), - ("'insertion_point':{'x':float('nan'),'y':0.0,'z':0.0}", "finite"), - ] { - dispatch(&mut host, &format!( - "PY_EVAL ocs.update_many('Reject table', [{{'handle':{}, {patch}}}])", handle.value())); - assert_eq!(host.document().get_entity(handle), Some(&expected), "{patch}"); - assert!(last_output(&host).contains(message), "{patch}: {}", last_output(&host)); - } + ( + "'columns':[{'name':'A','width':0.0},{'width':1.0},{'width':1.0}]", + "greater than zero", + ), + ( + "'columns':[{'width':5.0}]", + "cells but the table has 1 columns", + ), + ("'columns':[]", "at least one row and one column"), + ( + "'merged_ranges':[{'top_row':0,'left_col':0,'bottom_row':9,'right_col':0}]", + "outside the", + ), + ( + "'merged_ranges':[{'top_row':1,'left_col':0,'bottom_row':2,'right_col':1},{'top_row':2,'left_col':1,'bottom_row':3,'right_col':2}]", + "overlaps", + ), + ("'table_style_handle':999999", "does not exist"), + ("'block_name':'x'", "read-only"), + ("'normal':{'x':0.0,'y':0.0,'z':0.0}", "nonzero"), + ("'break_spacing':-1.0", "non-negative"), + ( + "'insertion_point':{'x':float('nan'),'y':0.0,'z':0.0}", + "finite", + ), + ] { + dispatch( + &mut host, + &format!( + "PY_EVAL ocs.update_many('Reject table', [{{'handle':{}, {patch}}}])", + handle.value() + ), + ); + assert_eq!( + host.document().get_entity(handle), + Some(&expected), + "{patch}" + ); + assert!( + last_output(&host).contains(message), + "{patch}: {}", + last_output(&host) + ); + } dispatch( &mut host, &format!( @@ -2721,10 +2928,12 @@ fn staged_python_table_lifecycle_over_real_ipc() { .unwrap(), ), ] { - assert!(crate::io::load_bytes(name, bytes) - .unwrap() - .get_entity(handle) - .is_none()); + assert!( + crate::io::load_bytes(name, bytes) + .unwrap() + .get_entity(handle) + .is_none() + ); } drop(process); drop(host); diff --git a/src/app/plugin_host/plugin_host_tests/table_style_block_audits.rs b/src/app/plugin_host/plugin_host_tests/table_style_block_audits.rs index 8ac6525044..1024af11ec 100644 --- a/src/app/plugin_host/plugin_host_tests/table_style_block_audits.rs +++ b/src/app/plugin_host/plugin_host_tests/table_style_block_audits.rs @@ -34,9 +34,11 @@ fn audit_python_layer_table_over_real_ipc() { " accepted.append('SCRIPTERROR_' + ''.join(c if c.isalnum() else '_' for c in str(error))[:120])\n", "L.create('REPORT ' + ' '.join(refused) + ' ~ ' + ' '.join(accepted))\n", ), body = body.lines().map(|line| format!(" {line}")).collect::>().join("\n"))).unwrap(); - assert!(process - .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) - .unwrap()); + assert!( + process + .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) + .unwrap() + ); let _ = std::fs::remove_file(&script); }; let report = |document: &Document| -> (Vec, Vec) { @@ -236,9 +238,11 @@ fn audit_python_text_and_dim_styles_over_real_ipc() { " accepted.append('SCRIPTERROR_' + ''.join(c if c.isalnum() else '_' for c in str(error))[:120])\n", "L.create('REPORT ' + str(len(refused)) + ' ~ ' + ' '.join(accepted))\n", ), body = body.lines().map(|line| format!(" {line}")).collect::>().join("\n"))).unwrap(); - assert!(process - .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) - .unwrap()); + assert!( + process + .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) + .unwrap() + ); let _ = std::fs::remove_file(&script); }; let report = |document: &Document| -> (usize, Vec) { @@ -472,9 +476,11 @@ fn audit_python_blocks_over_real_ipc() { " accepted.append('SCRIPTERROR_' + ''.join(c if c.isalnum() else '_' for c in str(error))[:120])\n", "L.create('REPORT ' + str(len(refused)) + ' ~ ' + ' '.join(accepted))\n", ), body = body.lines().map(|line| format!(" {line}")).collect::>().join("\n"))).unwrap(); - assert!(process - .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) - .unwrap()); + assert!( + process + .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) + .unwrap() + ); let _ = std::fs::remove_file(&script); }; let report = |document: &Document| -> (usize, Vec) { @@ -737,9 +743,11 @@ fn audit_python_block_contents_over_real_ipc() { " accepted.append('SCRIPTERROR_' + ''.join(c if c.isalnum() else '_' for c in str(error))[:120])\n", "L.create('REPORT ' + str(len(refused)) + ' ~ ' + ' '.join(accepted))\n", ), body = body.lines().map(|line| format!(" {line}")).collect::>().join("\n"))).unwrap(); - assert!(process - .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) - .unwrap()); + assert!( + process + .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) + .unwrap() + ); let _ = std::fs::remove_file(&script); }; let report = |document: &Document| -> (usize, Vec) { @@ -940,9 +948,11 @@ fn audit_python_linetypes_and_layouts_over_real_ipc() { " accepted.append('SCRIPTERROR_' + ''.join(c if c.isalnum() else '_' for c in str(error))[:120])\n", "L.create('REPORT ' + str(len(refused)) + ' ~ ' + ' '.join(accepted))\n", ), body = body.lines().map(|line| format!(" {line}")).collect::>().join("\n"))).unwrap(); - assert!(process - .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) - .unwrap()); + assert!( + process + .dispatch(host, &format!("PY_RUN {}", script.display()), &mut |_| {}) + .unwrap() + ); let _ = std::fs::remove_file(&script); }; let report = |document: &Document| -> (usize, Vec) { diff --git a/src/app/plugin_host/plugin_host_tests/xrecord.rs b/src/app/plugin_host/plugin_host_tests/xrecord.rs index d314de8fbd..53c7453708 100644 --- a/src/app/plugin_host/plugin_host_tests/xrecord.rs +++ b/src/app/plugin_host/plugin_host_tests/xrecord.rs @@ -25,10 +25,11 @@ fn xrecord_crud_round_trips_refusals_and_list() { // Dictionary lookup is case-insensitive, both for the path … assert_eq!(host.read_xrecord(&["plugin"], "alpha").unwrap(), entries()); // … and re-creating an existing name is refused without any change. - assert!(host - .create_xrecord(&["plugin"], "ALPHA", entries()) - .unwrap_err() - .contains("already exists")); + assert!( + host.create_xrecord(&["plugin"], "ALPHA", entries()) + .unwrap_err() + .contains("already exists") + ); // Namespace reuse is idempotent: the root still holds one PLUGIN entry. let beta = host.create_xrecord(&["PLUGIN"], "beta", entries()).unwrap(); @@ -58,15 +59,18 @@ fn xrecord_crud_round_trips_refusals_and_list() { // The root dictionary holds non-XRecord entries (ACAD_LAYOUT et al.); // listing only reports XRecords. let root_names = host.list_xrecords(&[]).unwrap(); - assert!(!root_names - .iter() - .any(|n| n.eq_ignore_ascii_case("ACAD_LAYOUT"))); + assert!( + !root_names + .iter() + .any(|n| n.eq_ignore_ascii_case("ACAD_LAYOUT")) + ); // Update refuses on a missing name and never creates anything. - assert!(host - .update_xrecord(&["PLUGIN"], "gamma", entries()) - .unwrap_err() - .contains("does not exist")); + assert!( + host.update_xrecord(&["PLUGIN"], "gamma", entries()) + .unwrap_err() + .contains("does not exist") + ); // Case-insensitive resolution finds the stored ALPHA and replaces its // entries atomically; the handle is stable. assert_eq!( @@ -85,54 +89,61 @@ fn xrecord_crud_round_trips_refusals_and_list() { // Entries are validated before any change: reserved and out-of-range // group codes refuse (5 and 105 are the object handle codes). - assert!(host - .create_xrecord( + assert!( + host.create_xrecord( &["PLUGIN"], "gamma", vec![document::objects::XRecordEntry::int16(5, 1)] ) .unwrap_err() - .contains("reserved")); - assert!(host - .create_xrecord( + .contains("reserved") + ); + assert!( + host.create_xrecord( &["PLUGIN"], "gamma", vec![document::objects::XRecordEntry::int16(400, 1)] ) .unwrap_err() - .contains("out of range")); - assert!(host - .update_xrecord( + .contains("out of range") + ); + assert!( + host.update_xrecord( &["PLUGIN"], "alpha", vec![document::objects::XRecordEntry::int16(105, 1)] ) - .is_err()); + .is_err() + ); assert_eq!( host.read_xrecord(&["PLUGIN"], "alpha").unwrap(), vec![document::objects::XRecordEntry::string(1, "v2")] ); // Dictionary and record names are symbol names. assert!(host.create_xrecord(&["PLUGIN"], " ", entries()).is_err()); - assert!(host - .create_xrecord(&["PLUGIN", "A|B"], "gamma", entries()) - .is_err()); + assert!( + host.create_xrecord(&["PLUGIN", "A|B"], "gamma", entries()) + .is_err() + ); assert!(host.create_xrecord(&["PLUGIN"], "a HostSession<'a> { return Err( "transform applies to Solid3D, Body, Region and Surface entities" .into(), - ) + ); } } self.push_undo("Transform solid"); diff --git a/src/app/plugin_host/tables.rs b/src/app/plugin_host/tables.rs index c2b48ee73b..3d499fd48b 100644 --- a/src/app/plugin_host/tables.rs +++ b/src/app/plugin_host/tables.rs @@ -561,7 +561,9 @@ impl<'a> HostSession<'a> { Some(180) => Some(document::objects::PlotRotation::Degrees180), Some(270) => Some(document::objects::PlotRotation::Degrees270), Some(_) => { - return Err("the plot rotation must be 0, 90, 180 or 270 degrees".to_owned()) + return Err( + "the plot rotation must be 0, 90, 180 or 270 degrees".to_owned() + ); } }; if let Some([numerator, denominator]) = scale { diff --git a/src/app/update/dispatch.rs b/src/app/update/dispatch.rs index 2a3792176e..5cf1a3d72d 100644 --- a/src/app/update/dispatch.rs +++ b/src/app/update/dispatch.rs @@ -2118,6 +2118,52 @@ impl OpenCADStudio { Task::none() } + Message::PanelWidgetNodeActivated { + owner, + panel, + node, + } => { + // Activation is the one widget gesture the plugin needs: + // best-effort, owner-targeted, sequence-identified. + let routed = self.panel_event_router.on_node_activated(&panel, node); + #[cfg(not(target_arch = "wasm32"))] + crate::plugin::v4_support::publish_surface_event_to_plugin( + &owner, routed.panel_id, routed.sequence, routed.event, + ); + #[cfg(target_arch = "wasm32")] + let _ = (owner, routed); + Task::none() + } + Message::PanelWidgetExpandToggled { + owner, + panel, + node, + } => { + // Host-local toggle; ONLY expanding an `Unloaded` row + // notifies the plugin — it is the data source for those + // children (lazy expansion, finding F4). + let children = self + .panel_surfaces + .widget(&owner, &panel) + .and_then(|surface| surface.rows.get(&node)) + .map(|row| row.children.clone()); + let ui = self.panel_widget_ui.entry(panel.clone()).or_default(); + let notify = match children.as_ref() { + Some(children) => ui.toggle_expanded(node, children), + None => false, + }; + if notify { + let routed = self.panel_event_router.on_node_expanded(&panel, node); + #[cfg(not(target_arch = "wasm32"))] + crate::plugin::v4_support::publish_surface_event_to_plugin( + &owner, routed.panel_id, routed.sequence, routed.event, + ); + #[cfg(target_arch = "wasm32")] + let _ = routed; + } + Task::none() + } + Message::PluginDialogTextChange(id, val) => { if let Some(state) = &mut self.plugin_dialog_state { state.text_values.insert(id, val); diff --git a/src/ui/window/about.rs b/src/ui/window/about.rs index 9c6415ea13..f9b5adf807 100644 --- a/src/ui/window/about.rs +++ b/src/ui/window/about.rs @@ -2,7 +2,7 @@ use crate::app::Message; use crate::t; use crate::ui::style::common::muted_style; use crate::ui::style::form::dialog_button; -use iced::widget::{column, container, row, svg, text, Space}; +use iced::widget::{Space, column, container, row, svg, text}; use iced::{Background, Border, Element, Fill, Length, Shrink, Theme}; fn primary_style(theme: &Theme) -> iced::widget::text::Style { diff --git a/src/ui/window/alias_editor.rs b/src/ui/window/alias_editor.rs index f107fda444..676103dc60 100644 --- a/src/ui/window/alias_editor.rs +++ b/src/ui/window/alias_editor.rs @@ -9,8 +9,8 @@ use crate::app::Message; use crate::t; use crate::ui::style::common::muted_style; -use crate::ui::style::editor_table::{danger_input_style, danger_text_style, EDITOR_TABLE_GUTTER}; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use crate::ui::style::editor_table::{EDITOR_TABLE_GUTTER, danger_input_style, danger_text_style}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Background, Element, Length, Theme}; /// Which column of an alias row a text edit targets. @@ -118,13 +118,15 @@ pub fn view_window<'a>( .spacing(4) .align_y(iced::Center) } else { - row![button(crate::ui::icons::themed_danger_text( - crate::ui::icons::TRASH, - 12.0, - )) - .on_press(Message::AliasEditorRemove(idx)) - .padding([2, 6]) - .style(button::danger)] + row![ + button(crate::ui::icons::themed_danger_text( + crate::ui::icons::TRASH, + 12.0, + )) + .on_press(Message::AliasEditorRemove(idx)) + .padding([2, 6]) + .style(button::danger) + ] .align_y(iced::Center) }; list = list.push( @@ -152,9 +154,11 @@ pub fn view_window<'a>( let stats = if reset_confirm { row![Space::new().width(Length::Fixed(0.0))] } else { - row![text(format!("{}: {}", t!("Number of aliases"), rows.len())) - .size(12) - .style(muted_style)] + row![ + text(format!("{}: {}", t!("Number of aliases"), rows.len())) + .size(12) + .style(muted_style) + ] }; // Reset asks for confirmation in place: the add/reset buttons are // replaced by the question with Yes / No. diff --git a/src/ui/window/anno_scale_prompt.rs b/src/ui/window/anno_scale_prompt.rs index 6290807e2f..c7ec8d72de 100644 --- a/src/ui/window/anno_scale_prompt.rs +++ b/src/ui/window/anno_scale_prompt.rs @@ -2,7 +2,7 @@ //! a session: the scale the annotation is meant to show at, and whether to //! ask again. -use iced::widget::{checkbox, column, pick_list, row, text, Space}; +use iced::widget::{Space, checkbox, column, pick_list, row, text}; use iced::{Element, Fill}; use crate::app::Message; @@ -55,9 +55,11 @@ pub fn view<'a>( .spacing(12), row![ text(crate::tr!("anno-scale-prompt", "scale")).size(12), - pick_list(Some(state.picked.clone()), state.scales.clone(), |scale| scale.clone()) - .on_select(|scale| msg(AnnoScaleMsg::Pick(scale))) - .text_size(12) + pick_list(Some(state.picked.clone()), state.scales.clone(), |scale| { + scale.clone() + }) + .on_select(|scale| msg(AnnoScaleMsg::Pick(scale))) + .text_size(12) .width(Fill), ] .spacing(10) diff --git a/src/ui/window/annotation_data.rs b/src/ui/window/annotation_data.rs index cac9975fc4..8c1659a5f5 100644 --- a/src/ui/window/annotation_data.rs +++ b/src/ui/window/annotation_data.rs @@ -10,7 +10,7 @@ use std::fmt; use document::types::Handle; use iced::widget::{ - button, checkbox, column, container, pick_list, row, scrollable, text, text_input, Space, + Space, button, checkbox, column, container, pick_list, row, scrollable, text, text_input, }; use iced::{Border, Element, Fill, Length, Theme}; @@ -580,8 +580,8 @@ impl iced::widget::canvas::Program for InsertTablePreview { bounds: iced::Rectangle, _cursor: iced::mouse::Cursor, ) -> Vec { - use iced::widget::canvas::{Frame, Path, Stroke, Text}; use iced::Point; + use iced::widget::canvas::{Frame, Path, Stroke, Text}; let mut frame = Frame::new(renderer, bounds.size()); let ink = theme.palette().background.base.text; frame.fill( diff --git a/src/ui/window/assistant.rs b/src/ui/window/assistant.rs index a0ad806a2c..1cdc0c512e 100644 --- a/src/ui/window/assistant.rs +++ b/src/ui/window/assistant.rs @@ -16,7 +16,7 @@ use std::time::{Duration, Instant}; use base64::Engine as _; use iced::widget::{ - column, container, image, markdown, mouse_area, row, scrollable, text, text_input, Space, + Space, column, container, image, markdown, mouse_area, row, scrollable, text, text_input, }; use iced::{Background, Border, Element, Fill, Font, Length, Padding, Task, Theme}; @@ -283,11 +283,7 @@ impl AssistantPalette { self.send(serde_json::json!({"type": "refresh"})); } } - if grew { - scroll_to_end() - } else { - Task::none() - } + if grew { scroll_to_end() } else { Task::none() } } fn apply(&mut self, ev: serde_json::Value) { @@ -926,9 +922,11 @@ fn card_view<'a>(i: usize, card: &'a Card) -> Element<'a, Message> { ] .spacing(km::TOOL_GAP) .align_y(iced::Center); - let mut col = column![mouse_area(summary) - .on_press(m(AssistantMsg::ToggleCard(i))) - .interaction(iced::mouse::Interaction::Pointer)] + let mut col = column![ + mouse_area(summary) + .on_press(m(AssistantMsg::ToggleCard(i))) + .interaction(iced::mouse::Interaction::Pointer) + ] .spacing(km::TOOL_GAP); if card.open { let mono = |s: &'a str| { diff --git a/src/ui/window/attdef_dialog.rs b/src/ui/window/attdef_dialog.rs index 1c49da4d93..3c63b7c6d4 100644 --- a/src/ui/window/attdef_dialog.rs +++ b/src/ui/window/attdef_dialog.rs @@ -2,13 +2,13 @@ //! cards with accent headings, a help button on the left and the named //! action on the right, like the other drawing dialogs. -use iced::widget::{button, checkbox, column, container, pick_list, row, text, text_input, Space}; +use iced::widget::{Space, button, checkbox, column, container, pick_list, row, text, text_input}; use iced::{Element, Fill, Length}; use crate::app::Message; use crate::modules::draw::draw::attdef::{ - Justify, AFLAG_CONSTANT, AFLAG_INVISIBLE, AFLAG_LOCK, AFLAG_MULTILINE, AFLAG_PRESET, - AFLAG_VERIFY, + AFLAG_CONSTANT, AFLAG_INVISIBLE, AFLAG_LOCK, AFLAG_MULTILINE, AFLAG_PRESET, AFLAG_VERIFY, + Justify, }; use crate::t; use crate::ui::style::common::muted_style; @@ -569,9 +569,9 @@ mod tests { /// Whether `label` is laid out and in view in the dialog. fn shows(state: &AttdefDialogState, label: &str) -> bool { + use iced_test::Selector; use iced_test::core::widget; use iced_test::runtime::user_interface::{Cache, UserInterface}; - use iced_test::Selector; let _one = crate::headless_ui_lock(); let mut renderer = iced_test::futures::futures::executor::block_on( ::new( diff --git a/src/ui/window/attman_dialog.rs b/src/ui/window/attman_dialog.rs index 5c93a14e92..89ec7e0dd4 100644 --- a/src/ui/window/attman_dialog.rs +++ b/src/ui/window/attman_dialog.rs @@ -7,10 +7,10 @@ //! edited in a card below (Attribute / Text / Properties) and the settings //! are switches in the footer. -use document::entities::AttributeDefinition; use document::Handle; +use document::entities::AttributeDefinition; use iced::widget::{ - button, column, container, pick_list, row, scrollable, text, text_input, toggler, Space, + Space, button, column, container, pick_list, row, scrollable, text, text_input, toggler, }; use iced::{Background, Border, Color, Element, Fill, Length, Theme}; @@ -1102,9 +1102,9 @@ mod tests { /// Whether `label` is laid out and in view in the dialog. fn shows(state: &AttManState, label: &str) -> bool { + use iced_test::Selector; use iced_test::core::widget; use iced_test::runtime::user_interface::{Cache, UserInterface}; - use iced_test::Selector; let _one = crate::headless_ui_lock(); let mut renderer = iced_test::futures::futures::executor::block_on( ::new( diff --git a/src/ui/window/attribute_editor.rs b/src/ui/window/attribute_editor.rs index f0d4e83594..c9f25dd3b3 100644 --- a/src/ui/window/attribute_editor.rs +++ b/src/ui/window/attribute_editor.rs @@ -21,12 +21,12 @@ use crate::app::Message; use crate::t; use document::entities::{HorizontalAlignment, VerticalAlignment}; use document::types::{Color as AcadColor, LineWeight}; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Background, Border, Element, Fill, Length, Theme}; use std::borrow::Cow; use std::fmt; -use crate::ui::properties::{lw_options, LwItem}; +use crate::ui::properties::{LwItem, lw_options}; use crate::ui::style::common::muted_style; use crate::ui::style::form::{button_style, dialog_button, dialog_button_styled_opt, field_style}; use crate::ui::window::pdf_dialogs::{accent_text, card, card_style, chip, well_style}; @@ -116,31 +116,85 @@ pub fn one_line(value: &str) -> String { /// standard text-justification list. The stored labels are the English source /// texts; `justify_label` / `justify_from_label` translate both directions. pub const JUSTIFY: &[(&str, HorizontalAlignment, VerticalAlignment)] = &[ - ("Left", HorizontalAlignment::Left, VerticalAlignment::Baseline), - ("Aligned", HorizontalAlignment::Aligned, VerticalAlignment::Baseline), + ( + "Left", + HorizontalAlignment::Left, + VerticalAlignment::Baseline, + ), + ( + "Aligned", + HorizontalAlignment::Aligned, + VerticalAlignment::Baseline, + ), ("Fit", HorizontalAlignment::Fit, VerticalAlignment::Baseline), - ("Center", HorizontalAlignment::Center, VerticalAlignment::Baseline), - ("Middle", HorizontalAlignment::Middle, VerticalAlignment::Baseline), - ("Right", HorizontalAlignment::Right, VerticalAlignment::Baseline), - ("Top Left", HorizontalAlignment::Left, VerticalAlignment::Top), - ("Top Center", HorizontalAlignment::Center, VerticalAlignment::Top), - ("Top Right", HorizontalAlignment::Right, VerticalAlignment::Top), - ("Middle Left", HorizontalAlignment::Left, VerticalAlignment::Middle), - ("Middle Center", HorizontalAlignment::Center, VerticalAlignment::Middle), - ("Middle Right", HorizontalAlignment::Right, VerticalAlignment::Middle), - ("Bottom Left", HorizontalAlignment::Left, VerticalAlignment::Bottom), - ("Bottom Center", HorizontalAlignment::Center, VerticalAlignment::Bottom), - ("Bottom Right", HorizontalAlignment::Right, VerticalAlignment::Bottom), + ( + "Center", + HorizontalAlignment::Center, + VerticalAlignment::Baseline, + ), + ( + "Middle", + HorizontalAlignment::Middle, + VerticalAlignment::Baseline, + ), + ( + "Right", + HorizontalAlignment::Right, + VerticalAlignment::Baseline, + ), + ( + "Top Left", + HorizontalAlignment::Left, + VerticalAlignment::Top, + ), + ( + "Top Center", + HorizontalAlignment::Center, + VerticalAlignment::Top, + ), + ( + "Top Right", + HorizontalAlignment::Right, + VerticalAlignment::Top, + ), + ( + "Middle Left", + HorizontalAlignment::Left, + VerticalAlignment::Middle, + ), + ( + "Middle Center", + HorizontalAlignment::Center, + VerticalAlignment::Middle, + ), + ( + "Middle Right", + HorizontalAlignment::Right, + VerticalAlignment::Middle, + ), + ( + "Bottom Left", + HorizontalAlignment::Left, + VerticalAlignment::Bottom, + ), + ( + "Bottom Center", + HorizontalAlignment::Center, + VerticalAlignment::Bottom, + ), + ( + "Bottom Right", + HorizontalAlignment::Right, + VerticalAlignment::Bottom, + ), ]; /// A multi-line attribute is placed by one of the nine corners and sides of /// its text box: the last nine entries of [`JUSTIFY`]. -pub fn justify_options(multiline: bool) -> &'static [(&'static str, HorizontalAlignment, VerticalAlignment)] { - if multiline { - &JUSTIFY[6..] - } else { - JUSTIFY - } +pub fn justify_options( + multiline: bool, +) -> &'static [(&'static str, HorizontalAlignment, VerticalAlignment)] { + if multiline { &JUSTIFY[6..] } else { JUSTIFY } } /// The justification label for an (h, v) pair (defaults to "Left"). Kept in @@ -200,7 +254,6 @@ pub fn color_from_label(label: &str) -> Option { }) } - /// A Text Options field that is checked as the cursor leaves it. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum AttrField { @@ -284,9 +337,7 @@ fn edit_field<'a>( .width(Fill) .style(field_style); if enabled { - input = input - .on_input(on_input) - .on_submit(Message::AttrEditorApply); + input = input.on_input(on_input).on_submit(Message::AttrEditorApply); } row![label(name, enabled), input] .spacing(6) @@ -569,7 +620,13 @@ fn text_options_tab<'a>(view: &AttrEditorView<'a>) -> Element<'a, Message> { true, Message::AttrEditorJustify ), - edit_field(t!("Height"), AttrField::Height, &r.height, true, Message::AttrEditorHeight), + edit_field( + t!("Height"), + AttrField::Height, + &r.height, + true, + Message::AttrEditorHeight + ), edit_field( t!("Rotation"), AttrField::Rotation, @@ -663,7 +720,13 @@ fn properties_tab<'a>(view: &AttrEditorView<'a>) -> Element<'a, Message> { Message::AttrEditorLinetype ), row![ - pick_field(t!("Color"), colors, Some(current), true, Message::AttrEditorColor), + pick_field( + t!("Color"), + colors, + Some(current), + true, + Message::AttrEditorColor + ), row![label(t!("Lineweight"), true), lw] .spacing(6) .align_y(iced::Center), diff --git a/src/ui/window/authoring_palettes.rs b/src/ui/window/authoring_palettes.rs index 14e2f55962..439f1d9a69 100644 --- a/src/ui/window/authoring_palettes.rs +++ b/src/ui/window/authoring_palettes.rs @@ -1,12 +1,12 @@ //! The Block Editor's authoring catalogs, using the shared dock chrome. use crate::app::Message; -use crate::modules::{parametric, IconKind, ToolDef}; +use crate::modules::{IconKind, ToolDef, parametric}; use crate::ui::dock::{self, Chrome, PanelId}; use crate::ui::icons; use crate::ui::kit; use crate::ui::style::kit_metrics as km; -use iced::widget::{button, column, container, row, stack, text, Space}; +use iced::widget::{Space, button, column, container, row, stack, text}; use iced::{Element, Fill}; /// Size of a tool's icon in the catalog, and the height of its row. diff --git a/src/ui/window/auto_constrain_settings.rs b/src/ui/window/auto_constrain_settings.rs index 45eb6a47ac..3f1cc56ad6 100644 --- a/src/ui/window/auto_constrain_settings.rs +++ b/src/ui/window/auto_constrain_settings.rs @@ -1,7 +1,7 @@ -use crate::app::settings::AutoConstrainSettings; use crate::app::Message; +use crate::app::settings::AutoConstrainSettings; use crate::ui::style::form::dialog_button; -use iced::widget::{button, checkbox, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, scrollable, text, text_input}; use iced::{Element, Fill}; pub fn view_window<'a>( diff --git a/src/ui/window/block_action_bars.rs b/src/ui/window/block_action_bars.rs index ad4db5fa8e..efcdd3f59e 100644 --- a/src/ui/window/block_action_bars.rs +++ b/src/ui/window/block_action_bars.rs @@ -4,8 +4,8 @@ use crate::{ }; use document::Handle; use iced::{ - widget::{button, canvas, column, container, row, text, tooltip, Space}, Color, Element, Fill, Point, Rectangle, Vector, + widget::{Space, button, canvas, column, container, row, text, tooltip}, }; #[derive(Default)] diff --git a/src/ui/window/block_cycle_order.rs b/src/ui/window/block_cycle_order.rs index 0c9dfbd259..a10537bfe7 100644 --- a/src/ui/window/block_cycle_order.rs +++ b/src/ui/window/block_cycle_order.rs @@ -1,8 +1,8 @@ use crate::app::Message; use document::{Document, Handle}; use iced::{ - widget::{button, checkbox, column, container, row, scrollable, text, Space}, Element, Fill, + widget::{Space, button, checkbox, column, container, row, scrollable, text}, }; pub(crate) struct Row { diff --git a/src/ui/window/block_definition.rs b/src/ui/window/block_definition.rs index 2d5ab951ea..a8bec0ce00 100644 --- a/src/ui/window/block_definition.rs +++ b/src/ui/window/block_definition.rs @@ -5,8 +5,8 @@ use std::fmt; use document::Handle; use iced::widget::{ - button, checkbox, column, combo_box, container, mouse_area, pick_list, row, stack, text, - text_editor, text_input, Space, + Space, button, checkbox, column, combo_box, container, mouse_area, pick_list, row, stack, text, + text_editor, text_input, }; use iced::{Background, Border, Element, Fill, Length, Theme}; @@ -477,11 +477,13 @@ pub fn view_window<'a>( .align_y(iced::Center) .into() } else { - row![text(crate::tf!("{count} objects selected")) - .size(10) - .style(|theme: &Theme| text::Style { - color: Some(theme.palette().primary.base.color), - }),] + row![ + text(crate::tf!("{count} objects selected")) + .size(10) + .style(|theme: &Theme| text::Style { + color: Some(theme.palette().primary.base.color), + }), + ] .spacing(5) .align_y(iced::Center) .into() diff --git a/src/ui/window/block_edit_picker.rs b/src/ui/window/block_edit_picker.rs index 789800c4aa..8d3bc4ff6f 100644 --- a/src/ui/window/block_edit_picker.rs +++ b/src/ui/window/block_edit_picker.rs @@ -2,7 +2,7 @@ use crate::app::Message; use crate::scene::WireModel; use crate::ui::style::common::muted_style; use crate::ui::style::form::{hdivider, vsep}; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Element, Fill, Length, Theme}; pub(crate) struct State { diff --git a/src/ui/window/block_editor_settings.rs b/src/ui/window/block_editor_settings.rs index 38e5e8f0e8..d9e8755a28 100644 --- a/src/ui/window/block_editor_settings.rs +++ b/src/ui/window/block_editor_settings.rs @@ -1,10 +1,10 @@ use crate::app::{ - settings::{BlockEditorPreferences, BLOCK_DISPLAY_VARIABLES}, Message, + settings::{BLOCK_DISPLAY_VARIABLES, BlockEditorPreferences}, }; use iced::{ - widget::{button, checkbox, column, container, row, scrollable, text, text_input, Space}, Element, Fill, + widget::{Space, button, checkbox, column, container, row, scrollable, text, text_input}, }; #[derive(Clone, Debug)] diff --git a/src/ui/window/block_lookup.rs b/src/ui/window/block_lookup.rs index e75095f8cb..92b935e9f1 100644 --- a/src/ui/window/block_lookup.rs +++ b/src/ui/window/block_lookup.rs @@ -1,14 +1,14 @@ use crate::app::Message; use crate::scene::block_lookup::{self, Property}; use document::{ - objects::{BlockLookupAction, BlockLookupParameter}, Handle, + objects::{BlockLookupAction, BlockLookupParameter}, }; use iced::{ + Element, Fill, widget::{ - button, checkbox, column, container, pick_list, row, scrollable, text, text_input, Space, + Space, button, checkbox, column, container, pick_list, row, scrollable, text, text_input, }, - Element, Fill, }; #[derive(Debug, Clone)] diff --git a/src/ui/window/block_palette.rs b/src/ui/window/block_palette.rs index d1ef9b68e8..7960cb6d06 100644 --- a/src/ui/window/block_palette.rs +++ b/src/ui/window/block_palette.rs @@ -6,8 +6,8 @@ use std::path::PathBuf; use std::rc::Rc; -use crate::app::settings::{BlockInsertOptions, PaletteBlockRef}; use crate::app::Message; +use crate::app::settings::{BlockInsertOptions, PaletteBlockRef}; use crate::modules::IconKind; use crate::scene::model::wire_model::WireModel; use crate::ui::dock::PanelId; @@ -17,8 +17,8 @@ use crate::ui::style::{chrome, kit_metrics as km}; use crate::ui::window::pdf_dialogs::accent_text; use iced::widget::canvas::{Frame, Path, Program, Stroke}; use iced::widget::{ - button, canvas, checkbox, column, container, image, mouse_area, pick_list, row, scrollable, - text, text_input, Space, + Space, button, canvas, checkbox, column, container, image, mouse_area, pick_list, row, + scrollable, text, text_input, }; use iced::{Background, Border, Color, Element, Fill, Length, Theme}; @@ -1528,9 +1528,9 @@ mod tests { /// Centre of text `label` in `element` laid out very tall: where it is /// in view (`visible`), or wherever it is laid out. fn locate(element: Element<'_, Message>, label: &str, visible: bool) -> Option { + use iced_test::Selector; use iced_test::core::widget; use iced_test::runtime::user_interface::{Cache, UserInterface}; - use iced_test::Selector; let _one = crate::headless_ui_lock(); let mut renderer = iced_test::futures::futures::executor::block_on( ::new( diff --git a/src/ui/window/block_properties_table.rs b/src/ui/window/block_properties_table.rs index fa7c9e9ec8..29e0150d53 100644 --- a/src/ui/window/block_properties_table.rs +++ b/src/ui/window/block_properties_table.rs @@ -2,8 +2,8 @@ use crate::app::Message; use crate::scene::block_properties_table::{Column, TableView}; use document::Handle; use iced::{ - widget::{button, column, container, pick_list, row, scrollable, text, text_input, Space}, Element, Fill, + widget::{Space, button, column, container, pick_list, row, scrollable, text, text_input}, }; #[derive(Debug, Clone)] diff --git a/src/ui/window/block_save_as.rs b/src/ui/window/block_save_as.rs index 280d98ffd6..65af8d8de5 100644 --- a/src/ui/window/block_save_as.rs +++ b/src/ui/window/block_save_as.rs @@ -1,6 +1,6 @@ use crate::app::Message; use crate::scene::WireModel; -use iced::widget::{button, column, container, pick_list, row, text, text_input, Space}; +use iced::widget::{Space, button, column, container, pick_list, row, text, text_input}; use iced::{Element, Fill}; pub(crate) struct State { diff --git a/src/ui/window/block_visibility.rs b/src/ui/window/block_visibility.rs index 12f2e07b05..e2b57cb18e 100644 --- a/src/ui/window/block_visibility.rs +++ b/src/ui/window/block_visibility.rs @@ -1,7 +1,7 @@ -use document::objects::BlockVisibilityParameter; use document::Handle; +use document::objects::BlockVisibilityParameter; use iced::widget::{ - button, column, container, pick_list, row, scrollable, text, text_input, Space, + Space, button, column, container, pick_list, row, scrollable, text, text_input, }; use iced::{Element, Fill}; diff --git a/src/ui/window/browser.rs b/src/ui/window/browser.rs index b79d213542..f1a1b6c6fe 100644 --- a/src/ui/window/browser.rs +++ b/src/ui/window/browser.rs @@ -20,8 +20,8 @@ use crate::ui::dock::PanelId; use crate::ui::kit; use document::objects::SolidHistoryOperation; use document::{Document, EntityType, Handle}; -use iced::widget::column; use iced::Element; +use iced::widget::column; /// The three world planes, with the argument `CREATESKETCH` takes for each. const ORIGIN_PLANES: [(&str, &str); 3] = [("XY", "XY"), ("XZ", "XZ"), ("YZ", "YZ")]; diff --git a/src/ui/window/count_palette.rs b/src/ui/window/count_palette.rs index 1274229fa7..2025a3c170 100644 --- a/src/ui/window/count_palette.rs +++ b/src/ui/window/count_palette.rs @@ -11,7 +11,7 @@ use crate::ui::style::form::button_style; use crate::ui::style::kit_metrics as km; use document::count::{BlockInstance, CountKey}; use document::{Document, Handle}; -use iced::widget::{button, checkbox, column, container, row, text, tooltip, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, text, tooltip}; use iced::{Background, Border, Element, Fill, Length, Padding, Theme}; const BLOCK_ICON: &[u8] = include_bytes!("../../../assets/icons/blocks/block.svg"); diff --git a/src/ui/window/design_center.rs b/src/ui/window/design_center.rs index 66910d83f1..9346613cba 100644 --- a/src/ui/window/design_center.rs +++ b/src/ui/window/design_center.rs @@ -3,7 +3,7 @@ use crate::app::Message; use crate::ui::style::form::hdivider; -use iced::widget::{button, column, container, row, scrollable, text, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text}; use iced::{Element, Fill, Length, Theme}; /// The kinds of named content, as the Rename service names them. @@ -73,14 +73,15 @@ fn list<'a>(rows: Vec>) -> Element<'a, Message> { } pub(crate) fn view(state: &State, sizing: crate::ui::modal::ModalSizing) -> Element<'_, Message> { - let row_button = |label: String, selected: bool, msg: DesignCenterMsg| -> Element<'_, Message> { - button(text(label).size(12)) - .on_press(Message::DesignCenter(msg)) - .style(list_item_style(selected)) - .padding([4, 8]) - .width(Fill) - .into() - }; + let row_button = + |label: String, selected: bool, msg: DesignCenterMsg| -> Element<'_, Message> { + button(text(label).size(12)) + .on_press(Message::DesignCenter(msg)) + .style(list_item_style(selected)) + .padding([4, 8]) + .width(Fill) + .into() + }; let sources = state .sources .iter() @@ -140,11 +141,9 @@ pub(crate) fn view(state: &State, sizing: crate::ui::modal::ModalSizing) -> Elem let send = |msg| Message::DesignCenter(msg); let buttons = row![ - button(text(crate::tr!("design-center", "browse"))) - .on_press(send(DesignCenterMsg::Browse)), - button(text(crate::tr!("design-center", "select-all"))).on_press_maybe( - (!state.items.is_empty()).then_some(send(DesignCenterMsg::SelectAll)) - ), + button(text(crate::tr!("design-center", "browse"))).on_press(send(DesignCenterMsg::Browse)), + button(text(crate::tr!("design-center", "select-all"))) + .on_press_maybe((!state.items.is_empty()).then_some(send(DesignCenterMsg::SelectAll))), Space::new().width(Fill), button(text(crate::tr!("design-center", "add"))) .on_press_maybe((!state.picked.is_empty()).then_some(send(DesignCenterMsg::Add))) diff --git a/src/ui/window/dim_inspect_dialog.rs b/src/ui/window/dim_inspect_dialog.rs index 5ade3b2b45..85c8ab4e8d 100644 --- a/src/ui/window/dim_inspect_dialog.rs +++ b/src/ui/window/dim_inspect_dialog.rs @@ -2,7 +2,7 @@ //! the frame shape shown as three live samples, and the label and inspection //! rate switches with their values. -use iced::widget::{button, column, container, row, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, text, text_input}; use iced::{Element, Fill, Length, Theme}; use crate::app::Message; diff --git a/src/ui/window/drafting_settings.rs b/src/ui/window/drafting_settings.rs index 69c1efc807..06f0c12836 100644 --- a/src/ui/window/drafting_settings.rs +++ b/src/ui/window/drafting_settings.rs @@ -1,8 +1,8 @@ -use crate::app::settings::IsoPlane; use crate::app::Message; -use crate::snap::{SnapType, ALL_3D_SNAP_MODES, ALL_SNAP_MODES}; +use crate::app::settings::IsoPlane; +use crate::snap::{ALL_3D_SNAP_MODES, ALL_SNAP_MODES, SnapType}; use crate::ui::style::form::{dialog_button, dialog_button_styled_opt}; -use iced::widget::{button, checkbox, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, scrollable, text, text_input}; use iced::{Background, Border, Element, Fill, Theme}; use std::borrow::Cow; @@ -690,15 +690,17 @@ pub fn view_window<'a>( let prompt_group = group( crate::t!("Dynamic Prompts"), - column![row![ - checkbox(true).size(14), - text(crate::t!( - "Show command prompting and command input near crosshairs" - )) - .size(11), + column![ + row![ + checkbox(true).size(14), + text(crate::t!( + "Show command prompting and command input near crosshairs" + )) + .size(11), + ] + .spacing(7) + .align_y(iced::Center), ] - .spacing(7) - .align_y(iced::Center),] .spacing(6), ); diff --git a/src/ui/window/drawing_properties.rs b/src/ui/window/drawing_properties.rs index 28d01f98e6..f5e68b4eaf 100644 --- a/src/ui/window/drawing_properties.rs +++ b/src/ui/window/drawing_properties.rs @@ -3,7 +3,7 @@ use crate::app::Message; use crate::ui::style::form::{dialog_button, field_style, hdivider, labeled_field}; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Background, Border, Element, Fill, Theme}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -144,16 +144,18 @@ pub(crate) fn view(state: &State, sizing: crate::ui::modal::ModalSizing) -> Elem .into() } Tab::Custom => { - let mut rows = column![row![ - text(crate::tr!("dwgprops-dialog", "name")) - .size(11) - .width(Fill), - text(crate::tr!("dwgprops-dialog", "value")) - .size(11) - .width(Fill), - Space::new().width(70), + let mut rows = column![ + row![ + text(crate::tr!("dwgprops-dialog", "name")) + .size(11) + .width(Fill), + text(crate::tr!("dwgprops-dialog", "value")) + .size(11) + .width(Fill), + Space::new().width(70), + ] + .spacing(6) ] - .spacing(6)] .spacing(6); for (index, (name, value)) in state.summary.custom_properties.iter().enumerate() { rows = rows.push( diff --git a/src/ui/window/drawing_units.rs b/src/ui/window/drawing_units.rs index 4b39494196..fa92f24354 100644 --- a/src/ui/window/drawing_units.rs +++ b/src/ui/window/drawing_units.rs @@ -12,7 +12,7 @@ use std::fmt; -use iced::widget::{checkbox, column, container, row, text, text_input, Space}; +use iced::widget::{Space, checkbox, column, container, row, text, text_input}; use iced::{Border, Element, Fill, Length, Theme}; use crate::app::Message; @@ -301,7 +301,7 @@ fn sample_angle(state: &State) -> String { /// of the frame is drawing with. Without the restore the sample would leak its /// settings into every widget drawn after it. fn with_context(state: &State, body: impl FnOnce() -> String) -> String { - use crate::entities::common::{set_unit_context, unit_context, UnitContext}; + use crate::entities::common::{UnitContext, set_unit_context, unit_context}; let previous = unit_context(); set_unit_context(UnitContext { lunits: state.linear_format, diff --git a/src/ui/window/extraction_outdated.rs b/src/ui/window/extraction_outdated.rs index 074495f33e..648c785188 100644 --- a/src/ui/window/extraction_outdated.rs +++ b/src/ui/window/extraction_outdated.rs @@ -2,7 +2,7 @@ //! an extraction table no longer shows the drawing's data: update it, all of //! them, or leave it / all of them as they are. -use iced::widget::{button, column, container, row, text, Space}; +use iced::widget::{Space, button, column, container, row, text}; use iced::{Background, Border, Element, Fill, Theme}; use crate::app::Message; diff --git a/src/ui/window/field_dialog.rs b/src/ui/window/field_dialog.rs index f426b0e9e9..07d447f4ba 100644 --- a/src/ui/window/field_dialog.rs +++ b/src/ui/window/field_dialog.rs @@ -3,7 +3,7 @@ //! format on the right, a live preview and the field expression below. use iced::widget::{ - button, checkbox, column, container, pick_list, row, scrollable, text, text_input, Space, + Space, button, checkbox, column, container, pick_list, row, scrollable, text, text_input, }; use iced::{Element, Fill, Length}; @@ -140,7 +140,7 @@ pub fn nav_nodes( db: &document::sheet_set::SheetSetDatabase, views: bool, ) -> Vec<(u16, String, String, bool)> { - use document::sheet_set::{number_and_title, ComponentKind, Element as SsElement}; + use document::sheet_set::{ComponentKind, Element as SsElement, number_and_title}; let set = db.sheet_set(); let mut out = vec![(0, set.id().to_string(), db.name().to_string(), false)]; if views { @@ -203,7 +203,7 @@ pub fn nav_props( id: &str, ) -> Vec<(String, String, &'static str)> { use document::sheet_set::{ - custom_properties, ComponentKind, CUSTOM_SHEET_PROP, CUSTOM_SHEET_SET_PROP, + CUSTOM_SHEET_PROP, CUSTOM_SHEET_SET_PROP, ComponentKind, custom_properties, }; let Some(el) = db.find(id) else { return Vec::new(); @@ -1457,9 +1457,11 @@ fn format_panel<'a>(state: &'a FieldDialogState) -> Element<'a, Message> { .spacing(8) .into(), FieldKind::BlockPlaceholder => match &state.placeholder_block { - None => column![text(t!("Only accessible in the block editor")) - .size(12) - .style(muted_style)] + None => column![ + text(t!("Only accessible in the block editor")) + .size(12) + .style(muted_style) + ] .into(), Some(block) => { let (_, _, format) = diff --git a/src/ui/window/find_replace.rs b/src/ui/window/find_replace.rs index c4d2968475..39e3b0cd6d 100644 --- a/src/ui/window/find_replace.rs +++ b/src/ui/window/find_replace.rs @@ -8,7 +8,7 @@ use crate::app::{FindReplaceState, Message}; use crate::ui::style::common::muted_style; use crate::ui::style::form::{button_style, dialog_button, dialog_button_styled_opt, field_style}; use crate::ui::window::pdf_dialogs::{card, chip, well_style}; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Background, Border, Element, Fill, Length, Theme}; pub const FIND_INPUT_ID: &str = "find-replace-search"; @@ -206,7 +206,10 @@ impl FindKind { /// The card shown at the end of a search. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FindNotice { - Finished { found: usize, changed: usize }, + Finished { + found: usize, + changed: usize, + }, /// The listed objects are in more than one space. CannotSelect, } @@ -338,7 +341,11 @@ fn option_chips<'a>(state: &'a FindReplaceState, opts: &[FindOpt]) -> Element<'a /// A search option as a small toggle beside the search field, its name on /// hover. Whole words is off while wildcards are on. -fn option_toggle<'a>(state: &'a FindReplaceState, opt: FindOpt, glyph: &'static str) -> Element<'a, Message> { +fn option_toggle<'a>( + state: &'a FindReplaceState, + opt: FindOpt, + glyph: &'static str, +) -> Element<'a, Message> { let mut options = state.options; let on = *opt.slot(&mut options); let enabled = !(opt == FindOpt::WholeWords && state.options.wildcards); @@ -387,19 +394,21 @@ fn history_input<'a>( if let Some(submit) = submit { input = input.on_submit(msg(submit)); } - let picker = crate::ui::dropdown_list::pick_list(None::, history.to_vec(), |s: &String| { - s.clone() - }) - .on_select(move |v| msg(on(v))) - .text_size(11) - .padding([6, 6]) - .width(Length::Fixed(30.0)); + let picker = + crate::ui::dropdown_list::pick_list(None::, history.to_vec(), |s: &String| { + s.clone() + }) + .on_select(move |v| msg(on(v))) + .text_size(11) + .padding([6, 6]) + .width(Length::Fixed(30.0)); row![input, picker].spacing(4).align_y(iced::Center).into() } /// A result's text with every match shaded. fn marked_text<'a>(value: &str, state: &FindReplaceState, selected: bool) -> Element<'a, Message> { - let ranges = crate::app::text_match::str_ranges(value, &state.search, &state.options.matching()); + let ranges = + crate::app::text_match::str_ranges(value, &state.search, &state.options.matching()); let mut spans: Vec> = Vec::new(); let mut at = 0; for (start, end) in ranges { @@ -433,7 +442,9 @@ fn results_card<'a>(state: &'a FindReplaceState, busy: bool) -> Element<'a, Mess .size(11) .style(muted_style) .width(Length::Fixed(150.0)), - text(crate::tr!("find", "col-text")).size(11).style(muted_style), + text(crate::tr!("find", "col-text")) + .size(11) + .style(muted_style), ] .spacing(8); let mut rows = column![].spacing(1); @@ -443,12 +454,18 @@ fn results_card<'a>(state: &'a FindReplaceState, busy: bool) -> Element<'a, Mess text(result.location.clone()) .size(11) .width(Length::Fixed(90.0)), - text(result.kind.label()).size(11).width(Length::Fixed(150.0)), + text(result.kind.label()) + .size(11) + .width(Length::Fixed(150.0)), marked_text(&result.text, state, selected), ] .spacing(8); let b = button(line) - .style(if selected { button::primary } else { button::text }) + .style(if selected { + button::primary + } else { + button::text + }) .padding([3, 6]) .width(Fill); rows = rows.push(if busy { @@ -485,7 +502,12 @@ fn results_card<'a>(state: &'a FindReplaceState, busy: bool) -> Element<'a, Mess has_row, FindMsg::SelectHighlighted, ), - tool(ICON_SELECT_ALL, crate::tr!("find", "select-all"), has_any, FindMsg::SelectAll), + tool( + ICON_SELECT_ALL, + crate::tr!("find", "select-all"), + has_any, + FindMsg::SelectAll + ), ] .spacing(6) .align_y(iced::Center); @@ -545,9 +567,21 @@ fn message_card<'a>(state: &'a FindReplaceState) -> Option> crate::tr!("find", "locked-question"), ], vec![ - answer(crate::tr!("find", "locked-keep"), FindAnswer::KeepLocked, true), - answer(crate::tr!("find", "locked-unlock"), FindAnswer::Unlock, false), - answer(crate::tr!("find", "locked-skip"), FindAnswer::SkipLocked, false), + answer( + crate::tr!("find", "locked-keep"), + FindAnswer::KeepLocked, + true, + ), + answer( + crate::tr!("find", "locked-unlock"), + FindAnswer::Unlock, + false, + ), + answer( + crate::tr!("find", "locked-skip"), + FindAnswer::SkipLocked, + false, + ), ], ), FindPrompt::Block(name) => ( @@ -557,8 +591,16 @@ fn message_card<'a>(state: &'a FindReplaceState) -> Option> ], vec![ answer(crate::tr!("find", "block-all"), FindAnswer::AllBlocks, true), - answer(crate::tr!("find", "block-this"), FindAnswer::ThisBlock, false), - answer(crate::tr!("find", "block-skip"), FindAnswer::SkipBlock, false), + answer( + crate::tr!("find", "block-this"), + FindAnswer::ThisBlock, + false, + ), + answer( + crate::tr!("find", "block-skip"), + FindAnswer::SkipBlock, + false, + ), ], ), FindPrompt::Xref(path) => ( @@ -620,7 +662,11 @@ fn message_card<'a>(state: &'a FindReplaceState) -> Option> } else if changed == 1 { crate::tr!("find", "changed-one") } else { - crate::i18n::plain(crate::tr!("find", "changed-many", count = changed.to_string())) + crate::i18n::plain(crate::tr!( + "find", + "changed-many", + count = changed.to_string() + )) }, ], ), diff --git a/src/ui/window/geographic_location.rs b/src/ui/window/geographic_location.rs index d430407615..7092e288f0 100644 --- a/src/ui/window/geographic_location.rs +++ b/src/ui/window/geographic_location.rs @@ -2,7 +2,7 @@ use crate::app::Message; use crate::ui::style::form::{dialog_button, field_style}; -use iced::widget::{column, container, row, text, text_input, Space}; +use iced::widget::{Space, column, container, row, text, text_input}; use iced::{Element, Fill}; #[derive(Debug, Clone)] diff --git a/src/ui/window/geometric_tolerance.rs b/src/ui/window/geometric_tolerance.rs index 1d031f74e6..1a9236ab43 100644 --- a/src/ui/window/geometric_tolerance.rs +++ b/src/ui/window/geometric_tolerance.rs @@ -8,7 +8,7 @@ use std::fmt; use document::Handle; -use iced::widget::{button, checkbox, column, container, row, text, text_input, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, text, text_input}; use iced::{Border, Element, Fill, Length, Theme}; use crate::app::Message; diff --git a/src/ui/window/gradient_editor.rs b/src/ui/window/gradient_editor.rs index 02256b4a49..d8c1832e49 100644 --- a/src/ui/window/gradient_editor.rs +++ b/src/ui/window/gradient_editor.rs @@ -7,7 +7,7 @@ use crate::ui::style::{chrome, kit_metrics as km, text as ui_text}; use crate::ui::window::graphic_attributes::GraphicAttributesMsg; use document::types::Color as AcadColor; use iced::widget::{ - button, checkbox, column, container, image, mouse_area, row, slider, text, text_input, Space, + Space, button, checkbox, column, container, image, mouse_area, row, slider, text, text_input, }; use iced::{Background, Color, Element, Fill, Length, Theme}; diff --git a/src/ui/window/graphic_attributes.rs b/src/ui/window/graphic_attributes.rs index 6d8b8cc486..7ee0f2fabf 100644 --- a/src/ui/window/graphic_attributes.rs +++ b/src/ui/window/graphic_attributes.rs @@ -12,7 +12,7 @@ use document::entities::{EntityCommon, Hatch, HatchGradientPattern}; use document::types::{Color as AcadColor, LineWeight, Transparency}; use document::{Document, EntityType, Handle}; use iced::widget::{ - button, column, combo_box, container, image, row, slider, text, text_input, Space, + Space, button, column, combo_box, container, image, row, slider, text, text_input, }; use iced::{Background, Border, Element, Fill, Length, Theme}; use rustc_hash::{FxHashMap, FxHashSet}; diff --git a/src/ui/window/hatch_dialogs.rs b/src/ui/window/hatch_dialogs.rs index 71bbc2dfcc..d8c04650af 100644 --- a/src/ui/window/hatch_dialogs.rs +++ b/src/ui/window/hatch_dialogs.rs @@ -1,6 +1,6 @@ //! The boundary warning an empty HATCH / GRADIENT pick shows. -use iced::widget::{button, column, container, row, text, Space}; +use iced::widget::{Space, button, column, container, row, text}; use iced::{Element, Fill}; use crate::app::Message; diff --git a/src/ui/window/hatch_panel.rs b/src/ui/window/hatch_panel.rs index f9edc9895f..ef9eb6a0a0 100644 --- a/src/ui/window/hatch_panel.rs +++ b/src/ui/window/hatch_panel.rs @@ -6,8 +6,8 @@ use crate::app::Message; use crate::modules::draw::draw::hatch::{HatchFill, HatchSettings}; use crate::scene::model::hatch_model::GradientKind; -use crate::ui::style::form::{self, dialog_button, form_radio, LABEL_WIDTH}; -use crate::ui::window::attman_dialog::{color_label, COLORS}; +use crate::ui::style::form::{self, LABEL_WIDTH, dialog_button, form_radio}; +use crate::ui::window::attman_dialog::{COLORS, color_label}; use document::entities::HatchStyleType; use iced::widget::{checkbox, column, container, row, text, text_input}; use iced::{Background, Border, Element, Length, Theme}; diff --git a/src/ui/window/hyperlink_dialog.rs b/src/ui/window/hyperlink_dialog.rs index 77f54dcd85..a58cd7cf41 100644 --- a/src/ui/window/hyperlink_dialog.rs +++ b/src/ui/window/hyperlink_dialog.rs @@ -3,7 +3,7 @@ //! address is stored. Used by HYPERLINK, the Properties Hyperlink row and //! the block definition windows. -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Element, Fill, Length, Theme}; use crate::app::Message; diff --git a/src/ui/window/import_dialogs.rs b/src/ui/window/import_dialogs.rs index 04d411b5b4..eb765086df 100644 --- a/src/ui/window/import_dialogs.rs +++ b/src/ui/window/import_dialogs.rs @@ -5,7 +5,7 @@ //! mesh with several materials becomes). use iced::widget::{ - button, column, container, image, pick_list, row, scrollable, text, text_input, Space, + Space, button, column, container, image, pick_list, row, scrollable, text, text_input, }; use iced::{Background, Border, Element, Fill, Length, Theme}; @@ -13,7 +13,7 @@ use crate::app::Message; use crate::t; use crate::ui::style::common::muted_style; use crate::ui::style::form::{button_style, dialog_button, dialog_button_styled_opt, field_style}; -use crate::ui::window::pdf_dialogs::{card, well_style, PageThumb}; +use crate::ui::window::pdf_dialogs::{PageThumb, card, well_style}; /// Which read of an import window (3D Studio Import, DGN Import, Import /// PDF) a result belongs to: its number, and whether its window was open @@ -496,21 +496,23 @@ pub fn view_import_file<'a>( msg(ImportDialogMsg::Recent(n)), )); } - let mut file = column![row![ - text_input("", &state.path) - .on_input(|s| msg(ImportDialogMsg::Path(s))) - .on_submit(msg(ImportDialogMsg::ImportOk)) - .size(12) - .padding([6, 8]) - .width(Fill) - .style(field_style), - button(text(t!("Browse...")).size(11)) - .on_press(msg(ImportDialogMsg::Browse)) - .style(button_style(false)) - .padding([6, 14]), + let mut file = column![ + row![ + text_input("", &state.path) + .on_input(|s| msg(ImportDialogMsg::Path(s))) + .on_submit(msg(ImportDialogMsg::ImportOk)) + .size(12) + .padding([6, 8]) + .width(Fill) + .style(field_style), + button(text(t!("Browse...")).size(11)) + .on_press(msg(ImportDialogMsg::Browse)) + .style(button_style(false)) + .padding([6, 14]), + ] + .spacing(8) + .align_y(iced::Center) ] - .spacing(8) - .align_y(iced::Center)] .spacing(8); if !recent.is_empty() { file = file.push(chips); @@ -923,13 +925,15 @@ pub fn view_tds_material<'a>( }, ..Default::default() }); - let mut chips = row![text(crate::tr!( - "import-3ds", - "materials", - n = (materials.len() as i64) - )) - .size(11) - .style(muted_style)] + let mut chips = row![ + text(crate::tr!( + "import-3ds", + "materials", + n = (materials.len() as i64) + )) + .size(11) + .style(muted_style) + ] .spacing(6) .align_y(iced::Center); for (material, color) in materials { @@ -1297,17 +1301,19 @@ pub fn view_dgn_import<'a>( let code_page_card: Element<'_, Message> = if state.version == "V7" { card( t!("V7 text code page").into_owned(), - row![pick_list( - Some(crate::modules::insert::dgn_import::code_page_label( - state.code_page - )), - crate::modules::insert::dgn_import::code_page_choices(), - |label: &String| label.clone(), - ) - .on_select(|label| msg(ImportDialogMsg::DgnCodePage(label))) - .text_size(11) - .padding([4, 8]) - .width(Fill),] + row![ + pick_list( + Some(crate::modules::insert::dgn_import::code_page_label( + state.code_page + )), + crate::modules::insert::dgn_import::code_page_choices(), + |label: &String| label.clone(), + ) + .on_select(|label| msg(ImportDialogMsg::DgnCodePage(label))) + .text_size(11) + .padding([4, 8]) + .width(Fill), + ] .spacing(8), ) .into() diff --git a/src/ui/window/insert_attr_dialog.rs b/src/ui/window/insert_attr_dialog.rs index d8aacf4609..38bcc8d8b2 100644 --- a/src/ui/window/insert_attr_dialog.rs +++ b/src/ui/window/insert_attr_dialog.rs @@ -5,7 +5,7 @@ use crate::app::Message; use crate::ui::style::form::{dialog_button, dialog_button_styled_opt, field_style}; use crate::ui::window::pdf_dialogs::card_style; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Element, Fill, Length}; /// One attribute the operator answers while the block is being placed. @@ -144,7 +144,10 @@ pub fn view( .edit .as_ref() .is_some_and(|e| e.multiline.get(index).copied().unwrap_or(false)); - body = body.push(line(caption(&row.label), slot(&row.value, index, multiline))); + body = body.push(line( + caption(&row.label), + slot(&row.value, index, multiline), + )); } let step = |label: &str, go: bool, msg: InsertAttrMsg| { dialog_button_styled_opt( @@ -163,7 +166,11 @@ pub fn view( spread(), dialog_button(crate::t!("Cancel").into_owned(), Message::CloseModal, false), spread(), - step(&crate::t!("Previous"), state.has_previous(), InsertAttrMsg::Previous), + step( + &crate::t!("Previous"), + state.has_previous(), + InsertAttrMsg::Previous + ), spread(), step(&crate::t!("Next"), state.has_next(), InsertAttrMsg::Next), spread(), diff --git a/src/ui/window/layer_state_manager.rs b/src/ui/window/layer_state_manager.rs index bfe1e1c6f5..53e866a211 100644 --- a/src/ui/window/layer_state_manager.rs +++ b/src/ui/window/layer_state_manager.rs @@ -2,10 +2,10 @@ use crate::app::{LayerStateLayerFlag, LayerStateProperty, Message}; use crate::t; -use crate::ui::properties::{lw_options, LwItem}; -use crate::ui::style::form::{hdivider, LABEL_WIDTH}; +use crate::ui::properties::{LwItem, lw_options}; +use crate::ui::style::form::{LABEL_WIDTH, hdivider}; use document::{LayerState, LayerStateMask}; -use iced::widget::{button, checkbox, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, scrollable, text, text_input}; use iced::{Background, Border, Element, Fill, Length, Theme}; use std::borrow::Cow; use std::fmt; diff --git a/src/ui/window/layer_translator.rs b/src/ui/window/layer_translator.rs index e97502a48d..b27d556e06 100644 --- a/src/ui/window/layer_translator.rs +++ b/src/ui/window/layer_translator.rs @@ -6,7 +6,7 @@ //! which is only applied when Translate is pressed — so a mapping can be //! reconsidered, and a translation is one undo step rather than many. -use iced::widget::{button, checkbox, column, container, row, scrollable, text, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, scrollable, text}; use iced::{Background, Border, Element, Fill, Length, Theme}; use crate::app::Message; diff --git a/src/ui/window/layer_walk.rs b/src/ui/window/layer_walk.rs index 32d81724dc..30d9d1f9ca 100644 --- a/src/ui/window/layer_walk.rs +++ b/src/ui/window/layer_walk.rs @@ -17,12 +17,12 @@ use crate::t; use crate::ui::kit; use crate::ui::style::text as ui_text; use crate::ui::style::{chrome, kit_metrics as km}; -use document::tables::layer::Layer as DocLayer; use document::tables::Table; +use document::tables::layer::Layer as DocLayer; +use iced::Padding; use iced::widget::{ button, checkbox, column, combo_box, container, mouse_area, row, scrollable, text, }; -use iced::Padding; use iced::{Background, Element, Fill, Length, Theme}; use rustc_hash::{FxHashMap, FxHashSet}; use std::borrow::Cow; @@ -282,11 +282,7 @@ fn sort_rows(rows: &mut [LayerWalkRow], sort: LayerWalkSort, asc: bool) { .cmp(&b.count) .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())), }; - if asc { - ord - } else { - ord.reverse() - } + if asc { ord } else { ord.reverse() } }); } diff --git a/src/ui/window/layers.rs b/src/ui/window/layers.rs index 18b973680d..c1fd4ed1a1 100644 --- a/src/ui/window/layers.rs +++ b/src/ui/window/layers.rs @@ -4,18 +4,18 @@ use crate::app::Message; use crate::t; use crate::ui::kit; use crate::ui::kit::menu::{self, Item, Mark}; -use crate::ui::properties::{lw_options, LinetypeItem, LwItem}; +use crate::ui::properties::{LinetypeItem, LwItem, lw_options}; use crate::ui::style::common::muted_style; use crate::ui::style::text as ui_text; use crate::ui::style::{chrome, kit_metrics as km}; -use document::tables::layer::Layer as DocLayer; +use document::Handle; use document::tables::Table; +use document::tables::layer::Layer as DocLayer; use document::types::{Color as AcadColor, LineWeight}; -use document::Handle; +use iced::Padding; use iced::widget::{ button, checkbox, column, combo_box, container, mouse_area, row, scrollable, text, text_input, }; -use iced::Padding; use iced::{Background, Border, Color, Element, Fill, Length, Theme}; use std::borrow::Cow; use std::collections::HashMap; @@ -1894,10 +1894,12 @@ fn sortable_header<'a>( active: Option, asc: bool, ) -> Element<'a, Message> { - let mut content = row![kit::one_line(text(label)) - .size(ui_text::UI) - .line_height(ui_line()) - .font(kit::SEMIBOLD)] + let mut content = row![ + kit::one_line(text(label)) + .size(ui_text::UI) + .line_height(ui_line()) + .font(kit::SEMIBOLD) + ] .spacing(km::TOOL_GAP) .align_y(iced::Center); if active == Some(col) { diff --git a/src/ui/window/layout_manager.rs b/src/ui/window/layout_manager.rs index 9e4bc93eb1..8bb799af48 100644 --- a/src/ui/window/layout_manager.rs +++ b/src/ui/window/layout_manager.rs @@ -4,7 +4,7 @@ use crate::app::Message; use crate::t; use crate::ui::style::common::muted_style; use crate::ui::style::form::{hdivider, vsep}; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Background, Element, Theme}; fn primary_style(theme: &Theme) -> iced::widget::text::Style { diff --git a/src/ui/window/missing_fonts.rs b/src/ui/window/missing_fonts.rs index cca76af6ef..5a8319c5ba 100644 --- a/src/ui/window/missing_fonts.rs +++ b/src/ui/window/missing_fonts.rs @@ -5,7 +5,7 @@ use crate::app::Message; use crate::ui::style::form::dialog_button_styled_opt; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Element, Fill, Length, Shrink, Theme}; fn muted_style(theme: &Theme) -> text::Style { diff --git a/src/ui/window/mod.rs b/src/ui/window/mod.rs index aec25037d5..230e47f76e 100644 --- a/src/ui/window/mod.rs +++ b/src/ui/window/mod.rs @@ -1,9 +1,7 @@ pub mod about; pub mod alias_editor; -pub mod annotation_data; pub mod anno_scale_prompt; -pub mod mtext_dialogs; -pub mod mtext_tool_dialogs; +pub mod annotation_data; pub mod assistant; pub mod attdef_dialog; pub mod attman_dialog; @@ -15,7 +13,6 @@ pub(crate) mod block_cycle_order; pub mod block_definition; pub mod block_edit_picker; pub(crate) mod block_editor_settings; -pub(crate) mod visual_styles; pub mod block_lookup; pub mod block_palette; pub mod block_properties_table; @@ -23,6 +20,7 @@ pub mod block_save_as; pub mod block_visibility; pub mod browser; pub mod count_palette; +pub mod design_center; pub mod dim_inspect_dialog; pub mod drafting_settings; pub mod drawing_properties; @@ -46,6 +44,8 @@ pub mod layer_walk; pub mod layers; pub mod layout_manager; pub mod missing_fonts; +pub mod mtext_dialogs; +pub mod mtext_tool_dialogs; pub mod named_parameters; pub mod open_progress; pub mod options; @@ -61,13 +61,14 @@ pub mod plugin_manager; pub mod plugin_panel; /// Native scene-surface projection for plugin panels (api v29). pub mod plugin_scene; +/// Native widget-surface rendering for plugin panels (api v29). +pub mod plugin_widgets; pub mod print_all; pub mod purge; pub mod quick_calc; pub mod recovery; pub mod refedit_dialog; pub mod rename; -pub mod design_center; pub mod ribbon_customize; pub mod select_similar; pub mod sheet_set; @@ -76,6 +77,7 @@ pub mod spell_dialog; pub mod table_cell_dialog; pub mod tool_palettes; pub mod update_notice; +pub(crate) mod visual_styles; pub mod wblock; pub mod xref_attach; pub mod xref_help; diff --git a/src/ui/window/mtext_dialogs.rs b/src/ui/window/mtext_dialogs.rs index 2be3883f75..db3843a49f 100644 --- a/src/ui/window/mtext_dialogs.rs +++ b/src/ui/window/mtext_dialogs.rs @@ -3,7 +3,7 @@ //! column settings, the background mask and find and replace. Each holds a //! draft; OK writes it to the editor in one step, Cancel drops it. -use iced::widget::{button, column, container, pick_list, row, text, text_input, Space}; +use iced::widget::{Space, button, column, container, pick_list, row, text, text_input}; use iced::{Element, Fill, Length}; use crate::app::Message; @@ -259,7 +259,11 @@ fn segmented<'a, T: Copy + PartialEq + 'a>( fn footer<'a>(ok: bool) -> Element<'a, Message> { row![ Space::new().width(Fill), - dialog_button_styled_opt(crate::t!("Cancel"), Some(Message::CloseModal), button::secondary), + dialog_button_styled_opt( + crate::t!("Cancel"), + Some(Message::CloseModal), + button::secondary + ), dialog_button_styled_opt( crate::t!("OK"), ok.then(|| msg(MTextDialogMsg::Ok)), @@ -342,7 +346,12 @@ pub fn view_paragraph<'a>( container(tab_list).height(Length::Fixed(72.0)).width(Fill), labelled( t("Decimal style"), - segmented(separators, d.decimal, d.tab_kind == TabKind::Decimal, M::Decimal) + segmented( + separators, + d.decimal, + d.tab_kind == TabKind::Decimal, + M::Decimal + ) ), ] .spacing(8), @@ -366,7 +375,11 @@ pub fn view_paragraph<'a>( let alignment = card( t("Paragraph alignment"), column![ - chip(t("Set the alignment"), d.align_on, msg(M::AlignOn(!d.align_on))), + chip( + t("Set the alignment"), + d.align_on, + msg(M::AlignOn(!d.align_on)) + ), segmented(aligns, d.align, d.align_on, M::Align), ] .spacing(6), @@ -377,8 +390,15 @@ pub fn view_paragraph<'a>( let spacing = card( t("Paragraph spacing"), column![ - chip(t("Set the spacing"), d.spacing_on, msg(M::SpacingOn(!d.spacing_on))), - labelled(t("Before"), spacing_input(&d.before, M::Before, d.spacing_on)), + chip( + t("Set the spacing"), + d.spacing_on, + msg(M::SpacingOn(!d.spacing_on)) + ), + labelled( + t("Before"), + spacing_input(&d.before, M::Before, d.spacing_on) + ), labelled(t("After"), spacing_input(&d.after, M::After, d.spacing_on)), ] .spacing(6), @@ -391,7 +411,11 @@ pub fn view_paragraph<'a>( let line = card( t("Paragraph line spacing"), column![ - chip(t("Set the line spacing"), d.line_on, msg(M::LineOn(!d.line_on))), + chip( + t("Set the line spacing"), + d.line_on, + msg(M::LineOn(!d.line_on)) + ), segmented(modes, d.line_mode, d.line_on, M::LineMode), labelled(t("At"), spacing_input(&d.line_at, M::LineAt, d.line_on)), ] @@ -438,10 +462,34 @@ pub fn view_columns<'a>( let size = card( t("Size"), column![ - labelled(t("Columns"), input(&d.number, number.then_some(M::ColumnNumber as fn(String) -> MTextDialogMsg))), - labelled(t("Height"), input(&d.height, height.then_some(M::ColumnHeight as fn(String) -> MTextDialogMsg))), - labelled(t("Column width"), input(&d.width, columns.then_some(M::ColumnWidth as fn(String) -> MTextDialogMsg))), - labelled(t("Gutter"), input(&d.gutter, columns.then_some(M::ColumnGutter as fn(String) -> MTextDialogMsg))), + labelled( + t("Columns"), + input( + &d.number, + number.then_some(M::ColumnNumber as fn(String) -> MTextDialogMsg) + ) + ), + labelled( + t("Height"), + input( + &d.height, + height.then_some(M::ColumnHeight as fn(String) -> MTextDialogMsg) + ) + ), + labelled( + t("Column width"), + input( + &d.width, + columns.then_some(M::ColumnWidth as fn(String) -> MTextDialogMsg) + ) + ), + labelled( + t("Gutter"), + input( + &d.gutter, + columns.then_some(M::ColumnGutter as fn(String) -> MTextDialogMsg) + ) + ), labelled( t("Total width"), text(if columns { d.total() } else { String::new() }) @@ -481,7 +529,11 @@ pub fn view_mask<'a>( .iter() .find(|(color, _)| *color == d.color) .map(|(_, name)| name.clone()) - .unwrap_or_else(|| crate::ui::properties::acad_color_display(d.color).1.to_string()); + .unwrap_or_else(|| { + crate::ui::properties::acad_color_display(d.color) + .1 + .to_string() + }); let fill_on = d.on && !d.background; let color_list = pick_list(Some(current), names, |name| name.clone()) .on_select(move |name| { @@ -498,10 +550,14 @@ pub fn view_mask<'a>( let color: Element<'a, Message> = if fill_on { color_list.into() } else { - text(crate::ui::properties::acad_color_display(d.color).1.to_string()) - .size(11) - .style(muted_style) - .into() + text( + crate::ui::properties::acad_color_display(d.color) + .1 + .to_string(), + ) + .size(11) + .style(muted_style) + .into() }; let mask = card( t("Background mask"), @@ -509,7 +565,10 @@ pub fn view_mask<'a>( chip(t("Use background mask"), d.on, msg(M::MaskOn(!d.on))), labelled( t("Border offset factor"), - input(&d.factor, d.on.then_some(M::MaskFactor as fn(String) -> MTextDialogMsg)) + input( + &d.factor, + d.on.then_some(M::MaskFactor as fn(String) -> MTextDialogMsg) + ) ), ] .spacing(6), @@ -579,10 +638,26 @@ pub fn view_find<'a>( let options = card( t("Options"), column![ - chip(t("Match case"), d.match_case, msg(M::MatchCase(!d.match_case))), - chip(t("Find whole words only"), d.whole_words, msg(M::WholeWords(!d.whole_words))), - chip(t("Use wildcards"), d.wildcards, msg(M::Wildcards(!d.wildcards))), - chip(t("Match diacritics"), d.diacritics, msg(M::Diacritics(!d.diacritics))), + chip( + t("Match case"), + d.match_case, + msg(M::MatchCase(!d.match_case)) + ), + chip( + t("Find whole words only"), + d.whole_words, + msg(M::WholeWords(!d.whole_words)) + ), + chip( + t("Use wildcards"), + d.wildcards, + msg(M::Wildcards(!d.wildcards)) + ), + chip( + t("Match diacritics"), + d.diacritics, + msg(M::Diacritics(!d.diacritics)) + ), chip( t("Match half/full width forms (East Asian languages)"), d.half_full, @@ -630,7 +705,11 @@ pub fn view_find<'a>( action(t("Find Next"), M::FindNext), action(t("Replace"), M::ReplaceOne), action(t("Replace All"), M::ReplaceAll), - dialog_button_styled_opt(crate::t!("Close"), Some(Message::CloseModal), button::secondary), + dialog_button_styled_opt( + crate::t!("Close"), + Some(Message::CloseModal), + button::secondary + ), ] .spacing(6) .align_y(iced::Center), diff --git a/src/ui/window/mtext_tool_dialogs.rs b/src/ui/window/mtext_tool_dialogs.rs index 4dedb42774..ff23f6b4f9 100644 --- a/src/ui/window/mtext_tool_dialogs.rs +++ b/src/ui/window/mtext_tool_dialogs.rs @@ -3,7 +3,7 @@ //! spelling settings, the selection highlight colour, and the stack and //! AutoStack properties. Drafts as in `mtext_dialogs`; OK writes them. -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Element, Fill, Length}; use crate::app::Message; @@ -201,9 +201,11 @@ pub fn view_charset<'a>(d: &'a CharsetDraft) -> Element<'a, Message> { card( t("Character Set"), column![ - text(t("The code page the selected TrueType text is written with.")) - .size(11) - .style(muted_style), + text(t( + "The code page the selected TrueType text is written with." + )) + .size(11) + .style(muted_style), choice_list(items, d.charset, M::Charset, 280.0), ] .spacing(6), @@ -311,9 +313,13 @@ pub fn view_dictionaries<'a>(d: &'a DictionariesDraft) -> Element<'a, Message> { .text_size(11) .width(Fill), ); - let mut sources: Vec<(Option, String)> = - vec![(None, t("Profile word list"))]; - sources.extend(d.files.iter().enumerate().map(|(n, path)| (Some(n), file_name(path)))); + let mut sources: Vec<(Option, String)> = vec![(None, t("Profile word list"))]; + sources.extend( + d.files + .iter() + .enumerate() + .map(|(n, path)| (Some(n), file_name(path))), + ); let mut source_row = row![].spacing(4); for (index, name) in sources { source_row = source_row.push( @@ -338,7 +344,9 @@ pub fn view_dictionaries<'a>(d: &'a DictionariesDraft) -> Element<'a, Message> { t("Custom dictionary"), column![ scrollable(source_row).direction(iced::widget::scrollable::Direction::Horizontal( - iced::widget::scrollable::Scrollbar::new().width(3).scroller_width(3) + iced::widget::scrollable::Scrollbar::new() + .width(3) + .scroller_width(3) )), row![ text_input(&t("Add word here"), &d.word) @@ -392,7 +400,10 @@ pub fn view_dictionaries<'a>(d: &'a DictionariesDraft) -> Element<'a, Message> { .width(Fill), text(path).size(10).style(muted_style), row![ - small_button(crate::tr!("text-editor-menu", "new-dictionary"), Some(msg(M::DictNewFile))), + small_button( + crate::tr!("text-editor-menu", "new-dictionary"), + Some(msg(M::DictNewFile)) + ), small_button(t("Add..."), Some(msg(M::DictAddFile))), small_button( t("Remove"), @@ -409,7 +420,11 @@ pub fn view_dictionaries<'a>(d: &'a DictionariesDraft) -> Element<'a, Message> { row![ small_button(t("Help"), Some(msg(M::DictHelp))), Space::new().width(Fill), - dialog_button_styled_opt(crate::t!("Close"), Some(Message::CloseModal), button::primary), + dialog_button_styled_opt( + crate::t!("Close"), + Some(Message::CloseModal), + button::primary + ), ] .spacing(6), ] @@ -430,10 +445,26 @@ pub fn view_spell_settings<'a>(d: &'a SpellSettingsDraft) -> Element<'a, Message card( t("Options"), column![ - option("Ignore capitalized words", o.ignore_capitalized, SpellSetting::IgnoreCapitalized), - option("Ignore words with mixed cases", o.ignore_mixed, SpellSetting::IgnoreMixed), - option("Ignore words in uppercase", o.ignore_upper, SpellSetting::IgnoreUpper), - option("Ignore words with numbers", o.ignore_numbers, SpellSetting::IgnoreNumbers), + option( + "Ignore capitalized words", + o.ignore_capitalized, + SpellSetting::IgnoreCapitalized + ), + option( + "Ignore words with mixed cases", + o.ignore_mixed, + SpellSetting::IgnoreMixed + ), + option( + "Ignore words in uppercase", + o.ignore_upper, + SpellSetting::IgnoreUpper + ), + option( + "Ignore words with numbers", + o.ignore_numbers, + SpellSetting::IgnoreNumbers + ), option( "Ignore words containing punctuation", o.ignore_punctuation, @@ -442,9 +473,11 @@ pub fn view_spell_settings<'a>(d: &'a SpellSettingsDraft) -> Element<'a, Message ] .spacing(4), ), - text(t("Dimension text, block attributes and external references are checked by SPELL.")) - .size(10) - .style(muted_style), + text(t( + "Dimension text, block attributes and external references are checked by SPELL." + )) + .size(10) + .style(muted_style), footer(msg(M::Ok), Message::CloseModal), ] .spacing(10) @@ -535,13 +568,15 @@ pub fn view_stack<'a>(d: &'a StackDraft) -> Element<'a, Message> { .width(Length::Fixed(70.0)) .style(field_style) .on_input(|v| msg(M::StackSize(v))), - row(["100%", "90%", "80%", "75%", "70%", "66%", "50%"].into_iter().map(|s| { - button(text(s).size(10)) - .on_press(msg(M::StackSize(s.to_string()))) - .style(button_style(d.size.trim() == s)) - .padding([2, 5]) - .into() - })) + row(["100%", "90%", "80%", "75%", "70%", "66%", "50%"] + .into_iter() + .map(|s| { + button(text(s).size(10)) + .on_press(msg(M::StackSize(s.to_string()))) + .style(button_style(d.size.trim() == s)) + .padding([2, 5]) + .into() + })) .spacing(2), ] .spacing(6) @@ -587,13 +622,20 @@ pub fn view_stack<'a>(d: &'a StackDraft) -> Element<'a, Message> { /// AutoStack: whether and how numbers typed around `/`, `#` and `^` stack. pub fn view_autostack<'a>(d: &'a AutoStackDraft) -> Element<'a, Message> { - let fraction = vec![(false, t("Horizontal fraction")), (true, t("Diagonal fraction"))]; + let fraction = vec![ + (false, t("Horizontal fraction")), + (true, t("Diagonal fraction")), + ]; column![ card( t("AutoStack"), column![ text(t("Stack fractions automatically as you type")).size(12), - chip(t("Enable AutoStacking"), d.enabled, msg(M::AutoEnabled(!d.enabled))), + chip( + t("Enable AutoStacking"), + d.enabled, + msg(M::AutoEnabled(!d.enabled)) + ), row![ text(t("x/y becomes")).size(11).width(Length::Fixed(100.0)), segmented(fraction, d.diagonal, M::AutoDiagonal), diff --git a/src/ui/window/named_parameters.rs b/src/ui/window/named_parameters.rs index 3865019ae4..bde3721fe1 100644 --- a/src/ui/window/named_parameters.rs +++ b/src/ui/window/named_parameters.rs @@ -14,14 +14,14 @@ //! undefined-reference problems across rows immediately, before Apply. use crate::app::Message; -use crate::scene::named_parameters::ParameterTable; use crate::scene::Scene; +use crate::scene::named_parameters::ParameterTable; use crate::t; use crate::ui::style::common::muted_style; -use document::types::Handle; use document::EntityType; +use document::types::Handle; use iced::widget::tooltip::Position as TipPos; -use iced::widget::{button, column, container, row, scrollable, text, text_input, tooltip, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input, tooltip}; use iced::{Background, Element, Length, Theme}; /// Short "Kind handle" label for an entity without a user-facing name. diff --git a/src/ui/window/open_progress.rs b/src/ui/window/open_progress.rs index eef0599f72..725c543651 100644 --- a/src/ui/window/open_progress.rs +++ b/src/ui/window/open_progress.rs @@ -5,14 +5,14 @@ use crate::t; use iced::time::Instant; -use iced::widget::{button, column, container, row, stack, text, Space}; +use iced::widget::{Space, button, column, container, row, stack, text}; use iced::{Background, Border, Element, Fill, Length, Theme}; use std::borrow::Cow; use std::sync::atomic::Ordering; use crate::app::{ - Message, OpenProgress, OPEN_PHASE_CACHING, OPEN_PHASE_FINALIZING, OPEN_PHASE_PARSING, - OPEN_PHASE_READING, OPEN_PHASE_XREF, + Message, OPEN_PHASE_CACHING, OPEN_PHASE_FINALIZING, OPEN_PHASE_PARSING, OPEN_PHASE_READING, + OPEN_PHASE_XREF, OpenProgress, }; const CARD_WIDTH: f32 = 420.0; diff --git a/src/ui/window/options.rs b/src/ui/window/options.rs index a08431dd4b..d661e66ba1 100644 --- a/src/ui/window/options.rs +++ b/src/ui/window/options.rs @@ -1,12 +1,12 @@ #[cfg(not(target_arch = "wasm32"))] pub(crate) mod graphics; pub(crate) mod spacemouse; +use crate::app::Message; use crate::app::config::UiThemeConfig; use crate::app::settings; use crate::app::settings::{CursorType, RightClickMode}; -use crate::app::Message; use crate::ui::style::form::{dialog_button, dialog_button_styled_opt}; -use iced::widget::{button, column, container, row, scrollable, slider, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, slider, text, text_input}; use iced::{Background, Border, Element, Fill, Theme}; use std::fmt; diff --git a/src/ui/window/options/graphics.rs b/src/ui/window/options/graphics.rs index 27f7ff4378..9b7ad71bf6 100644 --- a/src/ui/window/options/graphics.rs +++ b/src/ui/window/options/graphics.rs @@ -6,7 +6,7 @@ use crate::app::Message; use crate::gpu_backend::{ActiveGpu, BackendChoice, GraphicsPrefs}; -use iced::widget::{checkbox, column, pick_list, row, text, Space}; +use iced::widget::{Space, checkbox, column, pick_list, row, text}; use iced::{Element, Fill}; fn current_row(label: std::borrow::Cow<'static, str>, value: String) -> Element<'static, Message> { diff --git a/src/ui/window/options/spacemouse.rs b/src/ui/window/options/spacemouse.rs index f2f0f11c76..28e4b86706 100644 --- a/src/ui/window/options/spacemouse.rs +++ b/src/ui/window/options/spacemouse.rs @@ -1,6 +1,6 @@ use crate::app::Message; use crate::input::spacemouse::{NavigationMode, Preferences, Status}; -use iced::widget::{button, checkbox, column, container, pick_list, row, slider, text, Space}; +use iced::widget::{Space, button, checkbox, column, container, pick_list, row, slider, text}; use iced::{Element, Fill}; pub(crate) const ICON: &[u8] = include_bytes!("../../../../assets/icons/ui/spacemouse.svg"); diff --git a/src/ui/window/overkill.rs b/src/ui/window/overkill.rs index 1fb6fb07ac..db36b69988 100644 --- a/src/ui/window/overkill.rs +++ b/src/ui/window/overkill.rs @@ -2,7 +2,7 @@ use crate::app::Message; use crate::modules::draw::modify::overkill::Settings; use crate::t; use crate::ui::style::form::{dialog_button, dialog_button_styled_opt}; -use iced::widget::{button, checkbox, column, row, text, text_input, Space}; +use iced::widget::{Space, button, checkbox, column, row, text, text_input}; use iced::{Element, Fill, Length, Shrink}; /// Properties that can be left out of the comparison, by ignore bit. diff --git a/src/ui/window/parameters_manager.rs b/src/ui/window/parameters_manager.rs index d46d6e485c..d5fc43cbec 100644 --- a/src/ui/window/parameters_manager.rs +++ b/src/ui/window/parameters_manager.rs @@ -4,7 +4,7 @@ use crate::scene::block_parameters_manager::{self as manager, Group, Row}; use crate::ui::dock::{self, Chrome, PanelId}; use crate::ui::kit; use crate::ui::style::{chrome, kit_metrics as km}; -use iced::widget::{button, canvas, column, container, mouse_area, row, text, text_input, Space}; +use iced::widget::{Space, button, canvas, column, container, mouse_area, row, text, text_input}; use iced::{Element, Fill, Length, Point, Rectangle, Size}; /// Every column stays visible in the panel's default width, so the fixed cells @@ -1084,9 +1084,9 @@ mod tests { /// Where `label` is drawn in the pane built from `panel`, if anywhere. /// The pane is laid out very tall so no row is scrolled out of view. fn locate(panel: &Panel, label: &str) -> Option { + use iced_test::Selector; use iced_test::core::widget; use iced_test::runtime::user_interface::{Cache, UserInterface}; - use iced_test::Selector; let _one = crate::headless_ui_lock(); let mut renderer = iced_test::futures::futures::executor::block_on( ::new( diff --git a/src/ui/window/pdf_dialogs.rs b/src/ui/window/pdf_dialogs.rs index cd7991ea0c..03157a5133 100644 --- a/src/ui/window/pdf_dialogs.rs +++ b/src/ui/window/pdf_dialogs.rs @@ -6,8 +6,8 @@ use std::fmt; use iced::widget::{ - button, checkbox, column, combo_box, container, image, pick_list, row, scrollable, text, - text_input, Space, + Space, button, checkbox, column, combo_box, container, image, pick_list, row, scrollable, text, + text_input, }; use iced::{Background, Border, Element, Fill, Length, Theme}; @@ -522,10 +522,12 @@ fn footer<'a>( action: std::borrow::Cow<'static, str>, ok: PdfDialogMsg, ) -> Element<'a, Message> { - let mut left = row![button(text("?").size(12)) - .on_press(msg(PdfDialogMsg::Help(help))) - .style(button_style(false)) - .padding([5, 11])] + let mut left = row![ + button(text("?").size(12)) + .on_press(msg(PdfDialogMsg::Help(help))) + .style(button_style(false)) + .padding([5, 11]) + ] .spacing(6) .align_y(iced::Center); if let Some(extra) = extra { @@ -2443,10 +2445,12 @@ pub fn view_point_cloud_color_map<'a>( ] .spacing(10); - let mut left = row![button(text("?").size(12)) - .on_press(msg(PdfDialogMsg::Help("pointcloudcolormap"))) - .style(button_style(false)) - .padding([5, 11])] + let mut left = row![ + button(text("?").size(12)) + .on_press(msg(PdfDialogMsg::Help("pointcloudcolormap"))) + .style(button_style(false)) + .padding([5, 11]) + ] .spacing(8) .align_y(iced::Center); if has_cloud { diff --git a/src/ui/window/pdf_password_dialog.rs b/src/ui/window/pdf_password_dialog.rs index 4389605950..1c54d8dc63 100644 --- a/src/ui/window/pdf_password_dialog.rs +++ b/src/ui/window/pdf_password_dialog.rs @@ -3,7 +3,7 @@ //! step bar, a wrong-password band inside the window and a session switch //! that offers the password to the other PDFs opened later. -use iced::widget::{button, column, container, row, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, text, text_input}; use iced::{Element, Fill, Length, Theme}; use crate::app::Message; @@ -242,16 +242,18 @@ pub fn view<'a>( .on_press(msg(PdfPasswordMsg::Show(!state.show))) .style(button_style(false)) .padding([4, 6]); - let mut body = column![row![ - text(crate::tr!("pdf-password", "password")) - .size(11) - .style(muted_style) - .width(Length::Fixed(70.0)), - input, - eye + let mut body = column![ + row![ + text(crate::tr!("pdf-password", "password")) + .size(11) + .style(muted_style) + .width(Length::Fixed(70.0)), + input, + eye + ] + .spacing(6) + .align_y(iced::Center) ] - .spacing(6) - .align_y(iced::Center)] .spacing(8); if state.wrong { body = body.push(wrong_band()); diff --git a/src/ui/window/pdf_shx_dialog.rs b/src/ui/window/pdf_shx_dialog.rs index 8c480dd3f7..d40dab8de3 100644 --- a/src/ui/window/pdf_shx_dialog.rs +++ b/src/ui/window/pdf_shx_dialog.rs @@ -5,7 +5,7 @@ //! recognition threshold and "use best matching font". use iced::widget::{ - button, column, container, mouse_area, row, scrollable, text, text_input, toggler, Space, + Space, button, column, container, mouse_area, row, scrollable, text, text_input, toggler, }; use iced::{Background, Border, Element, Fill, Length, Theme}; diff --git a/src/ui/window/plot.rs b/src/ui/window/plot.rs index d7125219e8..5ec74d7414 100644 --- a/src/ui/window/plot.rs +++ b/src/ui/window/plot.rs @@ -14,7 +14,7 @@ use crate::ui::style::common::muted_style; use crate::ui::style::form; use crate::ui::style::form::{hdivider, vseparator as vsep}; use iced::widget::{ - button, checkbox, column, container, mouse_area, row, scrollable, text, text_input, Space, + Space, button, checkbox, column, container, mouse_area, row, scrollable, text, text_input, }; use iced::{Background, Border, Element, Fit, Length, Theme}; use std::borrow::Cow; @@ -89,7 +89,7 @@ impl fmt::Display for PlotChoice { #[cfg(test)] mod tests { use super::{CustomPaperDraft, CustomPaperError, PlotChoice, PlotDialogState}; - use crate::io::paper_catalog::{resolve, Margins, PaperUnits}; + use crate::io::paper_catalog::{Margins, PaperUnits, resolve}; #[test] fn non_scaling_stroke_defaults_off_and_copies_with_plot_preferences() { diff --git a/src/ui/window/plugin_dialog.rs b/src/ui/window/plugin_dialog.rs index 183c0ec3a7..51892c6c3d 100644 --- a/src/ui/window/plugin_dialog.rs +++ b/src/ui/window/plugin_dialog.rs @@ -4,15 +4,15 @@ //! widget trees with rows, columns, inputs, checkboxes, pick lists, and buttons, //! matching the OpenCADStudio design system and theme. -use std::collections::{HashMap, HashSet}; use iced::widget::{ - button, checkbox, column, container, pick_list, row, rule, scrollable, text, text_input, Space, + Space, button, checkbox, column, container, pick_list, row, rule, scrollable, text, text_input, }; use iced::{Element, Fill, Length, Theme}; use ocs_plugin_api::dialog::{ DialogControl, DialogDef, DialogResponse, DialogValue, HorizontalAlign, TextStyle, VerticalAlign, }; +use std::collections::{HashMap, HashSet}; use crate::app::Message; use crate::ui::style::form::{button_style, dialog_button, field_style}; @@ -392,8 +392,17 @@ impl PluginDialogState { let val = self.bool_values.get(id).copied().unwrap_or(*default); Some((id.clone(), DialogValue::Bool(val))) } - DialogControl::Choice { id, options, default_index, .. } => { - let idx = self.choice_values.get(id).copied().unwrap_or(*default_index); + DialogControl::Choice { + id, + options, + default_index, + .. + } => { + let idx = self + .choice_values + .get(id) + .copied() + .unwrap_or(*default_index); let effective_options = self.dynamic_choice_options.get(id).unwrap_or(options); let text = effective_options.get(idx).cloned().unwrap_or_default(); Some((id.clone(), DialogValue::Choice { index: idx, text })) @@ -533,7 +542,10 @@ impl PluginDialogState { let mut any_visible = false; for control in &r.controls { - if control.id().is_some_and(|id| self.hidden_controls.contains(id)) { + if control + .id() + .is_some_and(|id| self.hidden_controls.contains(id)) + { continue; } any_visible = true; @@ -545,15 +557,18 @@ impl PluginDialogState { } let row_container: Element<'a, Message> = match r.align_h { - Some(HorizontalAlign::Left) => { - container(row_widget).width(Fill).align_x(iced::alignment::Horizontal::Left).into() - } - Some(HorizontalAlign::Center) => { - container(row_widget).width(Fill).align_x(iced::alignment::Horizontal::Center).into() - } - Some(HorizontalAlign::Right) => { - container(row_widget).width(Fill).align_x(iced::alignment::Horizontal::Right).into() - } + Some(HorizontalAlign::Left) => container(row_widget) + .width(Fill) + .align_x(iced::alignment::Horizontal::Left) + .into(), + Some(HorizontalAlign::Center) => container(row_widget) + .width(Fill) + .align_x(iced::alignment::Horizontal::Center) + .into(), + Some(HorizontalAlign::Right) => container(row_widget) + .width(Fill) + .align_x(iced::alignment::Horizontal::Right) + .into(), None => row_widget.into(), }; @@ -647,8 +662,10 @@ impl<'a> FormControlView<'a> { return Space::new().width(0).height(0).into(); } } - let is_disabled = - parent_disabled || control.id().is_some_and(|id| self.disabled_controls.contains(id)); + let is_disabled = parent_disabled + || control + .id() + .is_some_and(|id| self.disabled_controls.contains(id)); let panel_id = self.panel_id.map(str::to_string); const LABEL_WIDTH: f32 = 110.0; match control { @@ -683,10 +700,7 @@ impl<'a> FormControlView<'a> { let current = self.bool_values.get(id).copied().unwrap_or(false); let id_clone = id.clone(); let pid = panel_id.clone(); - let mut cb = checkbox(current) - .label(label) - .size(14) - .text_size(12); + let mut cb = checkbox(current).label(label).size(14).text_size(12); if !is_disabled { cb = cb.on_toggle(move |checked| { if let Some(p) = pid.clone() { @@ -749,15 +763,19 @@ impl<'a> FormControlView<'a> { } DialogControl::Color { id, label, .. } => { let rgb = self.color_values.get(id).copied().unwrap_or([255, 0, 0]); - let color_preview = container(Space::new().width(24).height(16)) - .style(move |theme: &Theme| container::Style { - background: Some(iced::Background::Color(iced::Color::from_rgb8(rgb[0], rgb[1], rgb[2]))), - border: iced::Border { - color: theme.palette().background.neutral.color, - width: 1.0, - radius: 2.0.into(), - }, - ..Default::default() + let color_preview = + container(Space::new().width(24).height(16)).style(move |theme: &Theme| { + container::Style { + background: Some(iced::Background::Color(iced::Color::from_rgb8( + rgb[0], rgb[1], rgb[2], + ))), + border: iced::Border { + color: theme.palette().background.neutral.color, + width: 1.0, + radius: 2.0.into(), + }, + ..Default::default() + } }); row![ @@ -832,8 +850,10 @@ impl<'a> FormControlView<'a> { return Space::new().width(0).height(0).into(); } } - let is_disabled = - parent_disabled || control.id().is_some_and(|id| self.disabled_controls.contains(id)); + let is_disabled = parent_disabled + || control + .id() + .is_some_and(|id| self.disabled_controls.contains(id)); let panel_id = self.panel_id.map(str::to_string); match control { DialogControl::InfoText { text: msg, align_h } @@ -844,9 +864,11 @@ impl<'a> FormControlView<'a> { .id() .and_then(|id| self.text_values.get(id)) .map_or(msg.as_str(), String::as_str); - let mut t = text(display_msg).size(12).style(|theme: &Theme| text::Style { - color: Some(crate::ui::style::readable::muted_text(theme)), - }); + let mut t = text(display_msg) + .size(12) + .style(|theme: &Theme| text::Style { + color: Some(crate::ui::style::readable::muted_text(theme)), + }); if let Some(h) = align_h { match h { HorizontalAlign::Left => { @@ -897,15 +919,18 @@ impl<'a> FormControlView<'a> { row_el = row_el.push(self.view_control_inner(c, is_disabled)); } match align_h { - Some(HorizontalAlign::Left) => { - container(row_el).width(Fill).align_x(iced::alignment::Horizontal::Left).into() - } - Some(HorizontalAlign::Center) => { - container(row_el).width(Fill).align_x(iced::alignment::Horizontal::Center).into() - } - Some(HorizontalAlign::Right) => { - container(row_el).width(Fill).align_x(iced::alignment::Horizontal::Right).into() - } + Some(HorizontalAlign::Left) => container(row_el) + .width(Fill) + .align_x(iced::alignment::Horizontal::Left) + .into(), + Some(HorizontalAlign::Center) => container(row_el) + .width(Fill) + .align_x(iced::alignment::Horizontal::Center) + .into(), + Some(HorizontalAlign::Right) => container(row_el) + .width(Fill) + .align_x(iced::alignment::Horizontal::Right) + .into(), None => row_el.width(Fill).into(), } } @@ -934,15 +959,18 @@ impl<'a> FormControlView<'a> { col_el = col_el.push(self.view_control_inner(c, is_disabled)); } match align_v { - Some(VerticalAlign::Top) => { - container(col_el).height(Fill).align_y(iced::alignment::Vertical::Top).into() - } - Some(VerticalAlign::Middle) => { - container(col_el).height(Fill).align_y(iced::alignment::Vertical::Center).into() - } - Some(VerticalAlign::Bottom) => { - container(col_el).height(Fill).align_y(iced::alignment::Vertical::Bottom).into() - } + Some(VerticalAlign::Top) => container(col_el) + .height(Fill) + .align_y(iced::alignment::Vertical::Top) + .into(), + Some(VerticalAlign::Middle) => container(col_el) + .height(Fill) + .align_y(iced::alignment::Vertical::Center) + .into(), + Some(VerticalAlign::Bottom) => container(col_el) + .height(Fill) + .align_y(iced::alignment::Vertical::Bottom) + .into(), None => col_el.into(), } } @@ -1020,10 +1048,7 @@ impl<'a> FormControlView<'a> { let current = self.bool_values.get(id).copied().unwrap_or(false); let id_clone = id.clone(); let pid = panel_id.clone(); - let mut cb = checkbox(current) - .label(label) - .size(14) - .text_size(12); + let mut cb = checkbox(current).label(label).size(14).text_size(12); if !is_disabled { cb = cb.on_toggle(move |checked| { if let Some(p) = pid.clone() { @@ -1077,15 +1102,19 @@ impl<'a> FormControlView<'a> { } DialogControl::Color { id, label, .. } => { let rgb = self.color_values.get(id).copied().unwrap_or([255, 0, 0]); - let color_preview = container(Space::new().width(24).height(18)) - .style(move |theme: &Theme| container::Style { - background: Some(iced::Background::Color(iced::Color::from_rgb8(rgb[0], rgb[1], rgb[2]))), - border: iced::Border { - color: theme.palette().background.neutral.color, - width: 1.0, - radius: 2.0.into(), - }, - ..Default::default() + let color_preview = + container(Space::new().width(24).height(18)).style(move |theme: &Theme| { + container::Style { + background: Some(iced::Background::Color(iced::Color::from_rgb8( + rgb[0], rgb[1], rgb[2], + ))), + border: iced::Border { + color: theme.palette().background.neutral.color, + width: 1.0, + radius: 2.0.into(), + }, + ..Default::default() + } }); column![ @@ -1171,7 +1200,7 @@ impl<'a> FormControlView<'a> { text(t).size(12), ] .spacing(6) - .align_y(iced::Alignment::Center) + .align_y(iced::Alignment::Center), ) .on_press(toggle_msg) .style(button::text) @@ -1251,7 +1280,7 @@ impl<'a> FormControlView<'a> { radius: 0.0.into(), }, ..Default::default() - }) + }), ); } if *allow_delete { @@ -1273,7 +1302,7 @@ impl<'a> FormControlView<'a> { ..Default::default() } }) - .width(Fill) + .width(Fill), ); // Table data rows @@ -1388,9 +1417,10 @@ impl<'a> FormControlView<'a> { if *allow_delete { let id_del = id.clone(); let pid_del = panel_id.clone(); - let mut del_btn = button( - crate::ui::icons::themed_secondary(crate::ui::icons::CLOSE, 10.0) - ) + let mut del_btn = button(crate::ui::icons::themed_secondary( + crate::ui::icons::CLOSE, + 10.0, + )) .style(button::text) .padding([3, 8]); if !is_disabled { @@ -1477,9 +1507,7 @@ impl<'a> FormControlView<'a> { }; add_btn = add_btn.on_press(msg); } - table_col = table_col.push( - row![Space::new().width(Fill), add_btn].width(Fill) - ); + table_col = table_col.push(row![Space::new().width(Fill), add_btn].width(Fill)); } container(table_col) @@ -1544,10 +1572,8 @@ pub(crate) fn styled_text<'a>( }), TextStyle::Strong => text(msg).size(12).font(bold), TextStyle::Heading => text(msg).size(15).font(bold), - TextStyle::Success | TextStyle::Warning | TextStyle::Danger => text(msg) - .size(12) - .font(bold) - .style(move |theme: &Theme| { + TextStyle::Success | TextStyle::Warning | TextStyle::Danger => { + text(msg).size(12).font(bold).style(move |theme: &Theme| { let palette = theme.palette(); let accent = match style { TextStyle::Success => palette.success.base.color, @@ -1557,7 +1583,8 @@ pub(crate) fn styled_text<'a>( text::Style { color: Some(crate::ui::style::readable::icon_accent(accent, theme)), } - }), + }) + } }; match align_h { Some(h) => { @@ -1644,7 +1671,10 @@ mod tests { assert_eq!(state.choice_option_text("nested_choice", 1), "Static B"); let mut updates = HashMap::new(); - updates.insert("status".to_string(), DialogValue::Text("Updated Status".to_string())); + updates.insert( + "status".to_string(), + DialogValue::Text("Updated Status".to_string()), + ); updates.insert( "scripts".to_string(), DialogValue::Table(vec![vec!["C:/path/script1.lsp".to_string()]]), @@ -1652,7 +1682,11 @@ mod tests { updates.insert( "category".to_string(), DialogValue::ChoiceOptions { - options: vec!["Opt A".to_string(), "Opt B".to_string(), "Opt C".to_string()], + options: vec![ + "Opt A".to_string(), + "Opt B".to_string(), + "Opt C".to_string(), + ], selected_index: 2, }, ); @@ -1669,7 +1703,11 @@ mod tests { assert_eq!(*state.choice_values.get("category").unwrap(), 2); assert_eq!( state.dynamic_choice_options.get("category").unwrap(), - &vec!["Opt A".to_string(), "Opt B".to_string(), "Opt C".to_string()] + &vec![ + "Opt A".to_string(), + "Opt B".to_string(), + "Opt C".to_string() + ] ); assert_eq!(state.choice_option_text("category", 2), "Opt C"); assert!(state.disabled_controls.contains("apply_btn")); @@ -1695,27 +1733,26 @@ mod tests { use crate::ui::window::plugin_panel::PluginPanelState; use ocs_plugin_api::dialog::PanelDef; - let def = PanelDef::new("my_panel", "My Panel") - .with_control(DialogControl::Fields { - id: "sec1".to_string(), - title: Some("Section".to_string()), - controls: vec![ - DialogControl::Choice { - id: "p_choice".to_string(), - label: "Choice".to_string(), - options: vec!["One".to_string(), "Two".to_string()], - default_index: 0, - }, - DialogControl::Button { - id: "p_btn".to_string(), - label: "Click".to_string(), - action: None, - align_h: None, - width: None, - }, - ], - collapsed: false, - }); + let def = PanelDef::new("my_panel", "My Panel").with_control(DialogControl::Fields { + id: "sec1".to_string(), + title: Some("Section".to_string()), + controls: vec![ + DialogControl::Choice { + id: "p_choice".to_string(), + label: "Choice".to_string(), + options: vec!["One".to_string(), "Two".to_string()], + default_index: 0, + }, + DialogControl::Button { + id: "p_btn".to_string(), + label: "Click".to_string(), + action: None, + align_h: None, + width: None, + }, + ], + collapsed: false, + }); let mut panel = PluginPanelState::from_def(def); assert_eq!(panel.choice_option_text("p_choice", 1), "Two"); diff --git a/src/ui/window/plugin_manager.rs b/src/ui/window/plugin_manager.rs index 41678936a8..7cac7ec55f 100644 --- a/src/ui/window/plugin_manager.rs +++ b/src/ui/window/plugin_manager.rs @@ -11,7 +11,7 @@ use crate::plugin::external::{ExternalPlugin, RegistryEntry, ReleaseInfo}; use crate::t; use crate::ui::style::common::muted_style; use iced::widget::{ - button, canvas, column, container, markdown, row, rule, scrollable, text, text_input, Space, + Space, button, canvas, column, container, markdown, row, rule, scrollable, text, text_input, }; use iced::{Background, Border, Element, Fill, Length, Theme}; use rustc_hash::{FxHashMap, FxHashSet}; @@ -411,9 +411,9 @@ fn progress_action<'a>(m: &MarketView, repo: &str) -> Option( .into() }; let action = match selected_release { - Some(release) if release_compatible(release) => { - pill_button( - t!("Install"), - Message::PluginInstall(repo_s.clone()), - button::success, - ) - } + Some(release) if release_compatible(release) => pill_button( + t!("Install"), + Message::PluginInstall(repo_s.clone()), + button::success, + ), Some(_) => status_badge(t!("Incompatible"), StatusKind::Danger), None => status_badge(t!("Unavailable"), StatusKind::Muted), }; @@ -781,7 +779,14 @@ fn marketplace_section<'a>( .on_press(Message::PluginReadmeSelect(e.repo.clone())); let actions = row![ Space::new().width(Fill), - install_controls(m, &e.repo, tags, selected, false, progress_action(m, &e.repo)), + install_controls( + m, + &e.repo, + tags, + selected, + false, + progress_action(m, &e.repo) + ), ] .align_y(iced::Center); let card = market_card( diff --git a/src/ui/window/plugin_panel.rs b/src/ui/window/plugin_panel.rs index fe55e8c413..2506c6fad5 100644 --- a/src/ui/window/plugin_panel.rs +++ b/src/ui/window/plugin_panel.rs @@ -5,22 +5,21 @@ //! and data tables, integrated with OpenCADStudio's docking system. use iced::widget::{ - button, checkbox, column, container, pick_list, row, scrollable, text, text_input, Space, + Space, button, checkbox, column, container, pick_list, row, scrollable, text, text_input, }; use iced::{Element, Fill, Length, Padding, Theme}; use ocs_plugin_api::dialog::{ - DialogControl, DialogValue, HorizontalAlign, PanelDef, PanelSnapshot, PanelStyle, - VerticalAlign, + DialogControl, DialogValue, HorizontalAlign, PanelDef, PanelSnapshot, PanelStyle, VerticalAlign, }; use std::collections::{HashMap, HashSet}; use crate::app::Message; -use crate::ui::dock::{title_bar, Chrome, PanelId}; +use crate::ui::dock::{Chrome, PanelId, title_bar}; use crate::ui::kit; use crate::ui::style::{chrome, kit_metrics as km, text as ui_text}; use crate::ui::window::plugin_dialog::{ - apply_control_value_updates, collect_svg_handles, find_choice_option_in_controls, styled_text, - svg_image, ChoiceOption, FormControlView, + ChoiceOption, FormControlView, apply_control_value_updates, collect_svg_handles, + find_choice_option_in_controls, styled_text, svg_image, }; /// Height cap of a table's scroll box in a dock panel. @@ -1424,10 +1423,12 @@ mod tests { !snapshot.values.contains_key(id), "unexpected value for {id}" ); - assert!(snapshot - .errors - .iter() - .any(|error| error.contains(&format!("control id '{id}'")))); + assert!( + snapshot + .errors + .iter() + .any(|error| error.contains(&format!("control id '{id}'"))) + ); } assert_eq!( snapshot.values.get("valid"), @@ -1544,14 +1545,18 @@ mod tests { assert_eq!(first.errors, second.errors); assert!(first.errors.windows(2).all(|pair| pair[0] <= pair[1])); - assert!(first - .errors - .iter() - .any(|error| error == "duplicate control id 'duplicate'")); - assert!(first - .errors - .iter() - .any(|error| error == "control has a missing id")); + assert!( + first + .errors + .iter() + .any(|error| error == "duplicate control id 'duplicate'") + ); + assert!( + first + .errors + .iter() + .any(|error| error == "control has a missing id") + ); assert_eq!( first.raw_text.get("").map(String::as_str), Some("current unnamed") @@ -1649,6 +1654,9 @@ mod tests { let palette_state = PluginPanelState::from_def(palette_def); let _ = palette_state.view(2, TEST_PANEL_W, Chrome::default()); - assert_eq!(form_state.snapshot(1).values, palette_state.snapshot(1).values); + assert_eq!( + form_state.snapshot(1).values, + palette_state.snapshot(1).values + ); } } diff --git a/src/ui/window/plugin_widgets.rs b/src/ui/window/plugin_widgets.rs new file mode 100644 index 0000000000..8f23811725 --- /dev/null +++ b/src/ui/window/plugin_widgets.rs @@ -0,0 +1,224 @@ +//! Native rendering of plugin widget surfaces (api v29, S05): trees and +//! lists rendered with the host's OWN widgets. +//! +//! Ownership split (the scene tier's law, applied to widgets): the plugin +//! owns the semantics — what rows mean; the host owns selection, +//! expansion, scroll and focus — all HOST-LOCAL transient state here, in +//! [`WidgetUiState`]. The one exception (finding F2's "unless the plugin +//! explicitly needs it"): expanding an `Unloaded` row notifies the plugin +//! (`SurfaceEvent::NodeExpanded`), because the plugin is the data source +//! for those children — the host cannot page them itself. +//! +//! The renderer walks the validated surface (bounds enforced by the +//! store) depth-first with a hard depth cap, so a hostile tree cannot +//! overflow the view-building stack. Clicks publish regular `Message`s — +//! no canvas, no hit-testing: native widgets route their own events. + +use crate::app::Message; +use iced::widget::{button, column, container, row, scrollable, text}; +use iced::{Element, Length}; +use ocs_plugin_api::scene::StableId; +use ocs_plugin_api::widget::{WidgetChildren, WidgetSurface}; +use std::collections::HashSet; + +/// Hard cap on render recursion depth (a validated surface can still be +/// deep; the view builder refuses to follow deeper chains). +const MAX_RENDER_DEPTH: usize = 64; + +/// Host-local transient state for one panel's widget surface: which rows +/// are expanded and which row is selected. Nothing here is authoritative +/// about the DATA — the surface snapshot is; this is view state only. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct WidgetUiState { + pub expanded: HashSet, + pub selected: Option, +} + +impl WidgetUiState { + /// Toggle expansion. Returns `true` when the host must notify the + /// plugin (`NodeExpanded`): only expanding an `Unloaded` row needs + /// the plugin — it is the data source for those children. + pub fn toggle_expanded(&mut self, node: StableId, children: &WidgetChildren) -> bool { + if !self.expanded.remove(&node) { + self.expanded.insert(node); + return matches!(children, WidgetChildren::Unloaded); + } + false + } + + /// Select a row (host-local highlight; no notification — selection + /// stays host-local unless a later stage demonstrates a consumer). + pub fn select(&mut self, node: StableId) { + self.selected = Some(node); + } +} + +/// Render one widget surface with the host's native widgets. `owner`/ +/// `panel` identify the surface for the event messages; `ui` is the +/// caller's host-local state (borrowed — the dispatch mutates it). +pub(crate) fn widget_view<'a>( + owner: &'a str, + panel: &'a str, + surface: &WidgetSurface, + ui: Option<&WidgetUiState>, +) -> Element<'a, Message> { + // Panels render before their first interaction has created view state: + // a missing entry is the empty host-local state, never an error. + let default_ui = WidgetUiState::default(); + let ui = ui.unwrap_or(&default_ui); + let list = render_level(surface, ui, &surface.roots.clone(), 0, owner, panel); + scrollable(container(list.width(Length::Fill))).into() +} + +fn render_level<'a>( + surface: &WidgetSurface, + ui: &WidgetUiState, + ids: &[StableId], + depth: usize, + owner: &'a str, + panel: &'a str, +) -> iced::widget::Column<'a, Message> { + let mut column = column![].spacing(2); + if depth > MAX_RENDER_DEPTH { + return column; + } + for id in ids { + let Some(row) = surface.rows.get(id) else { + continue; + }; + let expanded = ui.expanded.contains(id); + let selected = ui.selected == Some(*id); + let (marker, has_children) = match &row.children { + WidgetChildren::Leaf => ("", false), + WidgetChildren::Unloaded if expanded => ("▾", true), + WidgetChildren::Unloaded => ("▸", true), + WidgetChildren::Loaded(children) => { + if children.is_empty() { + ("", false) + } else if expanded { + ("▾", true) + } else { + ("▸", true) + } + } + }; + let marker_text = marker.to_owned(); + let row_id = *id; + let expand_btn: Element<'a, Message> = if has_children { + button(text(marker_text).size(12)) + .on_press(Message::PanelWidgetExpandToggled { + owner: owner.to_owned(), + panel: panel.to_owned(), + node: row_id, + }) + .into() + } else { + text(" ").size(12).into() + }; + let label = row.label.clone(); + let activate_btn = button(row![text(label).size(13)].spacing(4)) + .on_press(Message::PanelWidgetNodeActivated { + owner: owner.to_owned(), + panel: panel.to_owned(), + node: row_id, + }) + .style(move |_, status| { + let mut style = iced::widget::button::Style::default(); + if selected && status != iced::widget::button::Status::Disabled { + style.background = Some(iced::Background::Color(iced::Color::from_rgba8( + 120, 120, 160, 0.25, + ))); + } + style + }); + column = column.push( + row![expand_btn, container(activate_btn).width(Length::Fill)] + .spacing(4) + .width(Length::Fill), + ); + // Loaded children render under the row when expanded (host-local). + if expanded { + if let WidgetChildren::Loaded(children) = &row.children { + if depth + 1 <= MAX_RENDER_DEPTH { + let indent = + container(render_level(surface, ui, children, depth + 1, owner, panel)) + .padding(iced::Padding { + top: 0.0, + right: 0.0, + bottom: 0.0, + left: 18.0, + }); + column = column.push(indent); + } + } + // Unloaded + expanded: children arrive when the plugin pushes + // its page (the dispatch already notified NodeExpanded at + // toggle time). Until then the row simply shows none. + } + } + column +} + +#[cfg(test)] +mod tests { + use super::*; + use ocs_plugin_api::widget::{WidgetRevision, WidgetRow, WidgetSurface}; + + fn surface_with_unloaded_parent() -> WidgetSurface { + let mut surface = WidgetSurface::new(WidgetRevision(1)); + surface + .rows + .insert(StableId(1), row("parent", WidgetChildren::Unloaded)); + surface.roots = vec![StableId(1)]; + surface + } + + fn row(label: &str, children: WidgetChildren) -> WidgetRow { + WidgetRow { + label: label.to_owned(), + children, + } + } + + #[test] + fn expanding_an_unloaded_row_requests_a_page_exactly_once() { + let mut ui = WidgetUiState::default(); + assert!( + ui.toggle_expanded(StableId(1), &WidgetChildren::Unloaded), + "first expand of Unloaded must notify the plugin" + ); + assert!( + !ui.toggle_expanded(StableId(1), &WidgetChildren::Unloaded), + "collapse must NOT notify" + ); + assert!( + ui.toggle_expanded(StableId(1), &WidgetChildren::Unloaded), + "re-expanding an Unloaded row notifies again (data may have changed)" + ); + } + + #[test] + fn loaded_and_leaf_rows_never_request_pages() { + let mut ui = WidgetUiState::default(); + assert!(!ui.toggle_expanded(StableId(1), &WidgetChildren::Leaf)); + assert!(!ui.toggle_expanded(StableId(2), &WidgetChildren::Loaded(vec![StableId(3)]))); + } + + #[test] + fn selection_is_host_local_and_single() { + let mut ui = WidgetUiState::default(); + ui.select(StableId(1)); + ui.select(StableId(2)); + assert_eq!(ui.selected, Some(StableId(2)), "single selection"); + } + + #[test] + fn expansion_state_is_host_local_and_idempotent() { + let mut ui = WidgetUiState::default(); + let children = WidgetChildren::Loaded(vec![StableId(3)]); + assert!(ui.toggle_expanded(StableId(1), &children)); + assert!(ui.expanded.contains(&StableId(1))); + assert!(!ui.toggle_expanded(StableId(1), &children)); + assert!(!ui.expanded.contains(&StableId(1))); + } +} diff --git a/src/ui/window/print_all.rs b/src/ui/window/print_all.rs index 99b8e9db1d..e096a05f2e 100644 --- a/src/ui/window/print_all.rs +++ b/src/ui/window/print_all.rs @@ -1,7 +1,7 @@ use crate::app::Message; use crate::t; use crate::ui::style::common::muted_style as muted; -use iced::widget::{button, checkbox, column, container, row, scrollable, text, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, scrollable, text}; use iced::{Background, Border, Element, Length, Theme}; pub fn view_window<'a>( diff --git a/src/ui/window/purge.rs b/src/ui/window/purge.rs index 8150afc329..63440500c0 100644 --- a/src/ui/window/purge.rs +++ b/src/ui/window/purge.rs @@ -2,7 +2,7 @@ use crate::app::Message; use crate::ui::style::form::hdivider; -use iced::widget::{button, checkbox, column, container, row, scrollable, text, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, scrollable, text}; use iced::{Element, Fill}; use crate::app::commands::purge as pk; diff --git a/src/ui/window/quick_calc.rs b/src/ui/window/quick_calc.rs index 559b087471..dd60f0c93e 100644 --- a/src/ui/window/quick_calc.rs +++ b/src/ui/window/quick_calc.rs @@ -473,7 +473,7 @@ mod variables_view; mod view; pub use keypad::{Flyout, Key, KeypadMode, MemoryOp}; pub use variables::{FormMsg, StoredValue, VarForm, VarKind, VarMsg, Variable}; -pub use view::{float_height, view, Inputs, ICON}; +pub use view::{ICON, Inputs, float_height, view}; #[cfg(test)] mod tests; diff --git a/src/ui/window/quick_calc/keypad.rs b/src/ui/window/quick_calc/keypad.rs index 7b385dafd7..f0dfcb8b74 100644 --- a/src/ui/window/quick_calc/keypad.rs +++ b/src/ui/window/quick_calc/keypad.rs @@ -155,11 +155,7 @@ fn paren(o: &str) -> String { /// Drop one bracket pair that a function call's own brackets make redundant. fn strip(o: &str) -> &str { - if wrapped(o) { - &o[1..o.len() - 1] - } else { - o - } + if wrapped(o) { &o[1..o.len() - 1] } else { o } } /// The input as `head` + last operand, or `None` when it has no operand. @@ -252,7 +248,7 @@ impl QuickCalcPalette { Key::Eval => {} Key::Postfix(suffix) => return self.on_operand(|o| paren(o) + suffix, None), Key::Prefix(prefix) => { - return self.on_operand(|o| format!("{prefix}{}", paren(o)), Some(prefix)) + return self.on_operand(|o| format!("{prefix}{}", paren(o)), Some(prefix)); } Key::Func(name) => return self.on_operand(call(name), Some(&format!("{name}("))), Key::Trig { name, hyp } => { @@ -263,7 +259,7 @@ impl QuickCalcPalette { return self.on_operand( |o| format!("{name}({}, ", strip(o)), Some(&format!("{name}(")), - ) + ); } Key::Negate => { return self.on_operand( @@ -272,7 +268,7 @@ impl QuickCalcPalette { None => format!("(-{o})"), }, Some("(-"), - ) + ); } Key::Second => self.second ^= true, Key::Hyp => self.hyp ^= true, diff --git a/src/ui/window/quick_calc/keypad_view.rs b/src/ui/window/quick_calc/keypad_view.rs index db867cd209..67aec6dac9 100644 --- a/src/ui/window/quick_calc/keypad_view.rs +++ b/src/ui/window/quick_calc/keypad_view.rs @@ -3,14 +3,14 @@ use iced::widget::text::Span; use iced::widget::{ - button, column, container, mouse_area, opaque, rich_text, row, scrollable, stack, text, Space, + Space, button, column, container, mouse_area, opaque, rich_text, row, scrollable, stack, text, }; -use iced::{font, mouse, Background, Border, Color, Element, Fill, Font, Padding, Shadow, Theme}; +use iced::{Background, Border, Color, Element, Fill, Font, Padding, Shadow, Theme, font, mouse}; -use super::view::{icon, m, mix, muted, strong, tip, tokens, POINT, STRONG}; +use super::view::{POINT, STRONG, icon, m, mix, muted, strong, tip, tokens}; use super::{Flyout, Key, KeypadMode, MemoryOp, QuickCalcMsg, QuickCalcPalette}; -use crate::app::calc::Value; use crate::app::Message; +use crate::app::calc::Value; use crate::ui::icons::TRI_DOWN; const BACKSPACE: &[u8] = include_bytes!("../../../../assets/icons/quickcalc/backspace.svg"); diff --git a/src/ui/window/quick_calc/variables_view.rs b/src/ui/window/quick_calc/variables_view.rs index 0d392cb791..5c4d8306a9 100644 --- a/src/ui/window/quick_calc/variables_view.rs +++ b/src/ui/window/quick_calc/variables_view.rs @@ -3,15 +3,15 @@ use std::collections::HashMap; -use iced::widget::{button, column, container, mouse_area, row, text, text_input, tooltip, Space}; -use iced::{font, Background, Border, Color, Element, Fill, Font, Theme}; +use iced::widget::{Space, button, column, container, mouse_area, row, text, text_input, tooltip}; +use iced::{Background, Border, Color, Element, Fill, Font, Theme, font}; use super::view::{ - field_style, icon, m, mix, muted, segment, segmented, strong, text_button, tokens, STRONG, + STRONG, field_style, icon, m, mix, muted, segment, segmented, strong, text_button, tokens, }; use super::{FormMsg, QuickCalcMsg, QuickCalcPalette, VarForm, VarKind, VarMsg, Variable}; -use crate::app::calc::{CalcContext, CalcError, Value}; use crate::app::Message; +use crate::app::calc::{CalcContext, CalcError, Value}; use crate::ui::icons::{TRI_DOWN, TRI_RIGHT}; const NEW: &[u8] = include_bytes!("../../../../assets/icons/quickcalc/var_new.svg"); diff --git a/src/ui/window/quick_calc/view.rs b/src/ui/window/quick_calc/view.rs index f93c53d9a0..c28da48850 100644 --- a/src/ui/window/quick_calc/view.rs +++ b/src/ui/window/quick_calc/view.rs @@ -3,16 +3,16 @@ use iced::widget::text::{Ellipsis, Span, Wrapping}; use iced::widget::{ - button, column, container, rich_text, row, scrollable, svg, text, text_input, tooltip, Space, + Space, button, column, container, rich_text, row, scrollable, svg, text, text_input, tooltip, }; use iced::{Background, Border, Color, Element, Fill, Font, Length, Theme}; use super::{ - continues_ans, has_length_suffix, KeypadMode, Preview, QuickCalcMsg, QuickCalcPalette, Section, - UnitCat, INPUT_ID, + INPUT_ID, KeypadMode, Preview, QuickCalcMsg, QuickCalcPalette, Section, UnitCat, continues_ans, + has_length_suffix, }; -use crate::app::calc::{AngleMode, Value}; use crate::app::Message; +use crate::app::calc::{AngleMode, Value}; use crate::modules::draw::inquiry::calc_pick::PickKind; use crate::ui::dock::{Chrome, PanelId}; use crate::ui::icons::SWAP; diff --git a/src/ui/window/recovery.rs b/src/ui/window/recovery.rs index beae8d90c8..670d27b757 100644 --- a/src/ui/window/recovery.rs +++ b/src/ui/window/recovery.rs @@ -1,7 +1,7 @@ use crate::app::Message; use crate::io::recovery::{RecoveryReport, RecoveryStatus}; use crate::ui::style::common::muted_style; -use iced::widget::{button, column, container, row, scrollable, text, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text}; use iced::{Background, Border, Element, Fill, Length, Shrink, Theme}; fn status_style(status: RecoveryStatus) -> impl Fn(&Theme) -> iced::widget::text::Style + Copy { diff --git a/src/ui/window/refedit_dialog.rs b/src/ui/window/refedit_dialog.rs index 7951fcf77f..7249a1d294 100644 --- a/src/ui/window/refedit_dialog.rs +++ b/src/ui/window/refedit_dialog.rs @@ -4,7 +4,7 @@ //! session settings (lock what is outside the working set, give clashing //! named objects of an external reference unique names). -use iced::widget::{button, column, container, row, text, toggler, Space}; +use iced::widget::{Space, button, column, container, row, text, toggler}; use iced::{Border, Element, Fill, Length, Theme}; use crate::app::Message; @@ -144,9 +144,11 @@ pub fn view<'a>( } chips = chips.push(level_chip(&level.name, index, index == state.level)); } - let mut about = column![text(crate::tr!("ref-edit", "dialog-chain-hint")) - .size(11) - .style(muted_style)] + let mut about = column![ + text(crate::tr!("ref-edit", "dialog-chain-hint")) + .size(11) + .style(muted_style) + ] .spacing(4); if let Some(path) = current.and_then(|l| l.xref_path.as_deref()) { // A long path keeps its end, where the file name is. diff --git a/src/ui/window/rename.rs b/src/ui/window/rename.rs index e85ffad701..020dcde2db 100644 --- a/src/ui/window/rename.rs +++ b/src/ui/window/rename.rs @@ -3,7 +3,7 @@ use crate::app::Message; use crate::ui::style::form::hdivider; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Element, Fill, Length, Theme}; /// The kinds of named object, as the rename service names them. diff --git a/src/ui/window/ribbon_customize.rs b/src/ui/window/ribbon_customize.rs index 2609d8c730..1c0b557862 100644 --- a/src/ui/window/ribbon_customize.rs +++ b/src/ui/window/ribbon_customize.rs @@ -8,7 +8,7 @@ use crate::app::Message; use crate::ui::ribbon::CustomPanel; use crate::ui::style::common::muted_style; use crate::ui::style::form::dialog_button; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Element, Length}; #[derive(Debug, Clone, Default)] diff --git a/src/ui/window/select_similar.rs b/src/ui/window/select_similar.rs index f0d8ed77d9..9d972aa059 100644 --- a/src/ui/window/select_similar.rs +++ b/src/ui/window/select_similar.rs @@ -1,7 +1,7 @@ //! Select Similar settings: which properties besides the type must match. use crate::app::Message; -use iced::widget::{button, checkbox, column, container, row, text, Space}; +use iced::widget::{Space, button, checkbox, column, container, row, text}; use iced::{Element, Fill}; pub(crate) fn view_window(mode: u16) -> Element<'static, Message> { diff --git a/src/ui/window/sheet_set.rs b/src/ui/window/sheet_set.rs index cfd3928fc5..78d00f0028 100644 --- a/src/ui/window/sheet_set.rs +++ b/src/ui/window/sheet_set.rs @@ -14,10 +14,10 @@ use crate::ui::style::form::{button_style, dialog_button, field_style}; use crate::ui::style::{chrome, kit_metrics as km, text as text_size}; use crate::ui::window::pdf_dialogs::{accent_text, card_style}; use document::sheet_set::{self as ss, ComponentKind, Element as SsElement, SheetSetDatabase}; +use iced::Padding; use iced::widget::{ - button, checkbox, column, container, pick_list, row, scrollable, text, text_input, Space, + Space, button, checkbox, column, container, pick_list, row, scrollable, text, text_input, }; -use iced::Padding; use iced::{Background, Border, Element, Fill, Length, Theme}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; @@ -1276,10 +1276,12 @@ fn footer<'a>( left: Vec>, right: Vec>, ) -> Element<'a, Message> { - let mut r = row![button(text("?").size(crate::ui::style::text::UI_LARGE)) - .on_press(msg(SheetSetMsg::Help)) - .style(button_style(false)) - .padding([5, 11])] + let mut r = row![ + button(text("?").size(crate::ui::style::text::UI_LARGE)) + .on_press(msg(SheetSetMsg::Help)) + .style(button_style(false)) + .padding([5, 11]) + ] .spacing(6) .align_y(iced::Center); for e in left { diff --git a/src/ui/window/shortcuts.rs b/src/ui/window/shortcuts.rs index 4e24d3e196..0d347c2fac 100644 --- a/src/ui/window/shortcuts.rs +++ b/src/ui/window/shortcuts.rs @@ -3,8 +3,8 @@ use crate::app::Message; use crate::t; use crate::ui::style::common::muted_style; -use crate::ui::style::editor_table::{danger_input_style, danger_text_style, EDITOR_TABLE_GUTTER}; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use crate::ui::style::editor_table::{EDITOR_TABLE_GUTTER, danger_input_style, danger_text_style}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Background, Element, Length, Theme}; #[derive(Clone, Copy, Debug)] @@ -215,13 +215,15 @@ pub fn view_window<'a>( .spacing(4) .align_y(iced::Center) } else { - row![button(crate::ui::icons::themed_danger_text( - crate::ui::icons::TRASH, - 12.0, - )) - .on_press(Message::ShortcutEditorRemove(idx)) - .padding([2, 6]) - .style(button::danger)] + row![ + button(crate::ui::icons::themed_danger_text( + crate::ui::icons::TRASH, + 12.0, + )) + .on_press(Message::ShortcutEditorRemove(idx)) + .padding([2, 6]) + .style(button::danger) + ] .align_y(iced::Center) }; list = list.push( @@ -340,7 +342,11 @@ pub fn view_window<'a>( column![ title, hint, - crate::ui::kit::search_field(t!("Search…").as_ref(), filter, Message::ShortcutEditorFilter), + crate::ui::kit::search_field( + t!("Search…").as_ref(), + filter, + Message::ShortcutEditorFilter + ), Space::new().height(6), head, scrollable(container(list).padding(gutter)).height(sizing.height), diff --git a/src/ui/window/spell_dialog.rs b/src/ui/window/spell_dialog.rs index 85361e0b3a..cc259c8c1b 100644 --- a/src/ui/window/spell_dialog.rs +++ b/src/ui/window/spell_dialog.rs @@ -3,7 +3,7 @@ //! the word, the main dictionary, and the checking options with the words //! added to the user's dictionary. -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text, text_input}; use iced::{Element, Fill, Length}; use crate::app::Message; diff --git a/src/ui/window/table_cell_dialog.rs b/src/ui/window/table_cell_dialog.rs index c32336880a..f05ae63aca 100644 --- a/src/ui/window/table_cell_dialog.rs +++ b/src/ui/window/table_cell_dialog.rs @@ -4,7 +4,7 @@ //! content of the picked cells) and Cell Data Format (how their values //! read). -use iced::widget::{button, column, container, pick_list, row, text, text_input, Space}; +use iced::widget::{Space, button, column, container, pick_list, row, text, text_input}; use iced::{Element, Fill, Length}; use crate::app::Message; @@ -935,7 +935,10 @@ pub fn view_format<'a>( let mut settings = column![].spacing(8); let units = state.units(); if !units.is_empty() { - let labels: Vec = units.iter().map(|name| crate::t!(*name).to_string()).collect(); + let labels: Vec = units + .iter() + .map(|name| crate::t!(*name).to_string()) + .collect(); let selected = labels.get(state.unit).cloned(); let options = labels.clone(); settings = settings.push(labelled( @@ -943,7 +946,10 @@ pub fn view_format<'a>( pick_list(selected, labels, |value: &String| value.clone()) .on_select(move |value: String| { msg(M::FormatUnit( - options.iter().position(|label| *label == value).unwrap_or(0), + options + .iter() + .position(|label| *label == value) + .unwrap_or(0), )) }) .text_size(11) @@ -1146,9 +1152,8 @@ pub fn view_format<'a>( button( row![ text(crate::t!(*name).to_string()).size(11).width(Fill), - container(text(badge).size(10)) - .padding([1, 7]) - .style(move |theme: &iced::Theme| container::Style { + container(text(badge).size(10)).padding([1, 7]).style( + move |theme: &iced::Theme| container::Style { background: Some(iced::Background::Color(if on { iced::Color::BLACK.scale_alpha(0.18) } else { @@ -1159,7 +1164,8 @@ pub fn view_format<'a>( ..Default::default() }, ..Default::default() - }), + } + ), ] .spacing(8) .align_y(iced::Center), @@ -1187,7 +1193,7 @@ pub fn view_format<'a>( .spacing(10) .width(Fill), ) - .padding(iced::Padding::ZERO.right(10)), + .padding(iced::Padding::ZERO.right(10)), ) .width(Fill) .height(Fill), diff --git a/src/ui/window/tool_palettes.rs b/src/ui/window/tool_palettes.rs index ac29dc6412..73e16cae60 100644 --- a/src/ui/window/tool_palettes.rs +++ b/src/ui/window/tool_palettes.rs @@ -10,8 +10,8 @@ use crate::app::{ClipboardDeps, Message}; use crate::ui::dock::{self, Chrome, PanelId}; use crate::ui::kit; use crate::ui::style::{chrome, kit_metrics as km}; -use crate::ui::window::block_palette::{preview_canvas, BlockPreview}; -use iced::widget::{button, checkbox, column, container, pick_list, row, text, Space}; +use crate::ui::window::block_palette::{BlockPreview, preview_canvas}; +use iced::widget::{Space, button, checkbox, column, container, pick_list, row, text}; use iced::{Background, Element, Fill, Length, Theme}; use serde::{Deserialize, Serialize}; use std::rc::Rc; diff --git a/src/ui/window/update_notice.rs b/src/ui/window/update_notice.rs index d54652a603..80e5bb22f2 100644 --- a/src/ui/window/update_notice.rs +++ b/src/ui/window/update_notice.rs @@ -1,7 +1,7 @@ use crate::app::Message; use crate::t; use crate::ui::style::common::muted_style; -use iced::widget::{button, column, container, row, scrollable, text, Space}; +use iced::widget::{Space, button, column, container, row, scrollable, text}; use iced::{Background, Border, Element, Theme}; use std::borrow::Cow; diff --git a/src/ui/window/visual_styles.rs b/src/ui/window/visual_styles.rs index 3453a6198d..c6aef5b50e 100644 --- a/src/ui/window/visual_styles.rs +++ b/src/ui/window/visual_styles.rs @@ -5,8 +5,8 @@ use crate::app::Message; use crate::modules::view::visual_style::VISUAL_STYLES; use document::entities::ViewportRenderMode; use iced::{ - widget::{button, checkbox, column, container, row, text, text_input, Space}, Element, Fill, + widget::{Space, button, checkbox, column, container, row, text, text_input}, }; /// What the window shows: the active viewport's style and the live edge @@ -34,7 +34,9 @@ pub(crate) fn view_window(v: View<'_>) -> Element<'_, Message> { let edges = column![ text(crate::t!("Edge Settings")).size(13), row![ - text(crate::t!("Crease angle (VSEDGESMOOTH)")).size(12).width(220), + text(crate::t!("Crease angle (VSEDGESMOOTH)")) + .size(12) + .width(220), text_input("1", v.crease) .on_input(Message::VisualStylesCreaseInput) .on_submit(Message::VisualStylesCreaseApply) @@ -48,7 +50,9 @@ pub(crate) fn view_window(v: View<'_>) -> Element<'_, Message> { )) .size(11), checkbox(v.occluded) - .label(crate::t!("Show occluded edges dashed in Hidden Line (VSOCCLUDEDEDGES)")) + .label(crate::t!( + "Show occluded edges dashed in Hidden Line (VSOCCLUDEDEDGES)" + )) .text_size(12) .on_toggle(Message::VisualStylesOccludedEdges), checkbox(v.silhouette) diff --git a/src/ui/window/wblock.rs b/src/ui/window/wblock.rs index 6aab9e4dbe..3bd4344672 100644 --- a/src/ui/window/wblock.rs +++ b/src/ui/window/wblock.rs @@ -3,7 +3,7 @@ use std::fmt; use document::Handle; -use iced::widget::{button, column, combo_box, container, pick_list, row, text, text_input, Space}; +use iced::widget::{Space, button, column, combo_box, container, pick_list, row, text, text_input}; use iced::{Background, Border, Element, Fill, Length, Theme}; use crate::app::Message; @@ -373,11 +373,13 @@ pub fn view_window<'a>( .align_y(iced::Center) .into() } else { - row![text(crate::tf!("{count} objects selected")) - .size(10) - .style(|theme: &Theme| text::Style { - color: Some(theme.palette().primary.base.color), - }),] + row![ + text(crate::tf!("{count} objects selected")) + .size(10) + .style(|theme: &Theme| text::Style { + color: Some(theme.palette().primary.base.color), + }), + ] .spacing(5) .align_y(iced::Center) .into() diff --git a/src/ui/window/xref_attach.rs b/src/ui/window/xref_attach.rs index 9b4bad8926..327b354a6d 100644 --- a/src/ui/window/xref_attach.rs +++ b/src/ui/window/xref_attach.rs @@ -5,7 +5,7 @@ use std::fmt; use iced::widget::{ - button, column, combo_box, container, image, pick_list, row, text, text_input, Space, + Space, button, column, combo_box, container, image, pick_list, row, text, text_input, }; use iced::{Element, Fill, Length, Theme}; @@ -13,7 +13,7 @@ use crate::app::Message; use crate::io::xref_model::Pathtype; use crate::t; use crate::ui::style::common::muted_style; -use crate::ui::style::form::{button_style, dialog_button, field_style, form_radio, LABEL_WIDTH}; +use crate::ui::style::form::{LABEL_WIDTH, button_style, dialog_button, field_style, form_radio}; use crate::ui::window::block_definition::{group, labeled_checkbox}; /// What the read for an attach's placement ghost found in a file: its diff --git a/src/ui/window/xref_help.rs b/src/ui/window/xref_help.rs index 6f7e58a310..f602a72934 100644 --- a/src/ui/window/xref_help.rs +++ b/src/ui/window/xref_help.rs @@ -7,7 +7,7 @@ use crate::app::Message; use crate::ui::style::common::muted_style; use crate::ui::style::form::dialog_button; -use iced::widget::{column, container, row, text, Space}; +use iced::widget::{Space, column, container, row, text}; use iced::{Background, Element, Fill, Length, Theme}; /// GitHub issues page linked from the help window, so web users can report diff --git a/src/ui/window/xref_manager.rs b/src/ui/window/xref_manager.rs index 67fdf7927e..875d12afa0 100644 --- a/src/ui/window/xref_manager.rs +++ b/src/ui/window/xref_manager.rs @@ -8,7 +8,7 @@ use crate::app::Message; use crate::io::xref::collect_entries_with_prev; use crate::io::xref_model::{ - normalize_lexical, Pathtype, RefKind, RefStatus, RefType, ReferenceEntry, + Pathtype, RefKind, RefStatus, RefType, ReferenceEntry, normalize_lexical, }; use crate::ui::kit; use crate::ui::kit::menu::{self, Item}; @@ -16,8 +16,8 @@ use crate::ui::style::common::muted_style; use crate::ui::style::text as ui_text; use crate::ui::style::{chrome, kit_metrics as km}; use document::Document; -use iced::widget::{button, column, container, mouse_area, row, scrollable, text}; use iced::Padding; +use iced::widget::{button, column, container, mouse_area, row, scrollable, text}; use iced::{Background, Element, Fill, Length, Theme}; use std::collections::{HashMap, HashSet}; use std::path::Path; @@ -2021,7 +2021,7 @@ mod tests { #[test] fn status_icons_are_unique_per_status() { - use super::{status_icon_key, RefStatus}; + use super::{RefStatus, status_icon_key}; let all = [ RefStatus::Loaded, RefStatus::Unloaded,