diff --git a/crates/ocs_plugin_api/src/host.rs b/crates/ocs_plugin_api/src/host.rs index 45235cb37c..2b6bcc8b96 100644 --- a/crates/ocs_plugin_api/src/host.rs +++ b/crates/ocs_plugin_api/src/host.rs @@ -2538,6 +2538,57 @@ pub trait HostApi { ) -> Result { self.panel_surface_page(panel_id, page) } + + /// Publish (or replace) a panel's TABLE surface (API v29, additive): + /// stable row keys, typed scalar cells. The default is the + /// transport-era stub (Unattached; nothing stored); surface-aware + /// hosts override [`HostApi::panel_table_publish_for_plugin`]. + fn panel_table_publish( + &mut self, + _panel_id: &str, + _surface: crate::tables::TableSurface, + ) -> Result { + Err(crate::tables::TableReject { + code: crate::tables::TableRejectCode::Unattached, + current_revision: None, + }) + } + + /// [`Self::panel_table_publish`] for the transport's authenticated + /// `plugin_id`. + fn panel_table_publish_for_plugin( + &mut self, + _plugin_id: &str, + panel_id: &str, + surface: crate::tables::TableSurface, + ) -> Result { + self.panel_table_publish(panel_id, surface) + } + + /// Patch a panel's stored TABLE atomically (API v29, additive): + /// cell/row ops apply all-or-nothing against the stored head. The + /// default is the transport-era stub (Unattached; nothing stored). + fn panel_surface_table_patch( + &mut self, + _panel_id: &str, + _patch: crate::tables::TablePatch, + ) -> Result { + Err(crate::tables::TableReject { + code: crate::tables::TableRejectCode::Unattached, + current_revision: None, + }) + } + + /// [`Self::panel_surface_table_patch`] for the transport's + /// authenticated `plugin_id`. + fn panel_surface_table_patch_for_plugin( + &mut self, + _plugin_id: &str, + panel_id: &str, + patch: crate::tables::TablePatch, + ) -> Result { + self.panel_surface_table_patch(panel_id, patch) + } } /// The answer of a host without surface support: `InvalidSurface` for an diff --git a/crates/ocs_plugin_api/src/ipc/client.rs b/crates/ocs_plugin_api/src/ipc/client.rs index 9b508e5d0a..e8f57de67b 100644 --- a/crates/ocs_plugin_api/src/ipc/client.rs +++ b/crates/ocs_plugin_api/src/ipc/client.rs @@ -1237,6 +1237,60 @@ impl HostApi for PluginHostApi { } } + fn panel_table_publish( + &mut self, + panel_id: &str, + surface: crate::tables::TableSurface, + ) -> Result { + match self.client.request(PluginRequest::PanelSurfacePublish { + panel_id: panel_id.to_string(), + surface: PanelSurface::Tables(surface), + }) { + Ok(PluginResponse::PanelTablePublished(result)) => result, + Ok(other) => { + eprintln!("[plugin] unexpected table publish response: {other:?}"); + Err(crate::tables::TableReject { + code: crate::tables::TableRejectCode::Unattached, + current_revision: None, + }) + } + Err(e) => { + eprintln!("[plugin] table publish request failed: {e}"); + Err(crate::tables::TableReject { + code: crate::tables::TableRejectCode::Unattached, + current_revision: None, + }) + } + } + } + + fn panel_surface_table_patch( + &mut self, + panel_id: &str, + patch: crate::tables::TablePatch, + ) -> Result { + match self.client.request(PluginRequest::PanelSurfaceTablePatch { + panel_id: panel_id.to_string(), + patch, + }) { + Ok(PluginResponse::PanelTablePatchResult(result)) => result, + Ok(other) => { + eprintln!("[plugin] unexpected table patch response: {other:?}"); + Err(crate::tables::TableReject { + code: crate::tables::TableRejectCode::Unattached, + current_revision: None, + }) + } + Err(e) => { + eprintln!("[plugin] table patch request failed: {e}"); + Err(crate::tables::TableReject { + code: crate::tables::TableRejectCode::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 f13de53c38..fcb5e070bf 100644 --- a/crates/ocs_plugin_api/src/ipc/protocol.rs +++ b/crates/ocs_plugin_api/src/ipc/protocol.rs @@ -460,6 +460,13 @@ pub enum PluginRequest { panel_id: String, page: crate::widget::WidgetPage, }, + /// V29 (additive): apply a bounded, revision-checked table patch + /// (cell/row ops) to the panel's stored table atomically + /// (all-or-nothing) — the cell-edit and row-update primitive. + PanelSurfaceTablePatch { + panel_id: String, + patch: crate::tables::TablePatch, + }, } /// Responses the host sends back for `PluginRequest`. @@ -570,6 +577,14 @@ pub enum PluginResponse { /// widget revision (the widget tier's independent revision space), or /// the typed refusal. PanelWidgetPublished(Result), + /// V29 (additive): outcome of a TABLE surface publish — the stored + /// table revision (the table tier's independent revision space), or + /// the typed refusal. + PanelTablePublished(Result), + /// V29 (additive): outcome of a table patch — the stored revision + /// after the atomic apply, or the typed refusal; the stored table + /// never ends up partially patched. + PanelTablePatchResult(Result), } /// Messages sent from the host to the plugin runner. diff --git a/crates/ocs_plugin_api/src/ipc/server.rs b/crates/ocs_plugin_api/src/ipc/server.rs index ceb4e9b57e..a978a8bd58 100644 --- a/crates/ocs_plugin_api/src/ipc/server.rs +++ b/crates/ocs_plugin_api/src/ipc/server.rs @@ -401,6 +401,9 @@ pub fn handle_plugin_request( crate::scene::PanelSurface::Widgets(widgets) => PluginResponse::PanelWidgetPublished( host.panel_widget_publish_for_plugin(plugin_id, &panel_id, widgets), ), + crate::scene::PanelSurface::Tables(tables) => PluginResponse::PanelTablePublished( + host.panel_table_publish_for_plugin(plugin_id, &panel_id, tables), + ), }, PanelSurfacePatch { panel_id, patch } => PluginResponse::PanelSurfacePatchResult( host.panel_surface_patch_for_plugin(plugin_id, &panel_id, patch), @@ -408,6 +411,9 @@ pub fn handle_plugin_request( PanelSurfacePage { panel_id, page } => PluginResponse::PanelSurfacePageResult( host.panel_surface_page_for_plugin(plugin_id, &panel_id, page), ), + PanelSurfaceTablePatch { panel_id, patch } => PluginResponse::PanelTablePatchResult( + host.panel_surface_table_patch_for_plugin(plugin_id, &panel_id, patch), + ), SetGeoLocation { location } => { PluginResponse::GeoLocationSet(host.set_geo_location(&location)) } diff --git a/crates/ocs_plugin_api/src/lib.rs b/crates/ocs_plugin_api/src/lib.rs index 6bd3d7905e..25f0e0734e 100644 --- a/crates/ocs_plugin_api/src/lib.rs +++ b/crates/ocs_plugin_api/src/lib.rs @@ -38,6 +38,7 @@ pub mod entity_coverage_types; pub mod manifest; pub mod ribbon; pub mod scene; +pub mod tables; pub mod type_registry; pub mod type_registry_types; pub mod version_info; @@ -83,6 +84,10 @@ pub use scene::{ PanelScene, PanelSurface, Rect2D, Rgba8, SceneBuilder, SceneColor, SceneElement, SceneError, SceneRevision, StableId, Stroke, SurfaceReject, SurfaceRejectCode, ThemeColor, Vec2, }; +pub use tables::{ + CellValue, MAX_TABLE_OPS, MAX_TABLE_ROWS, TableColumn, TableError, TableOp, TablePatch, + TableRevision, TableSurface, +}; pub use type_registry::{ EnumVariantInfo, FieldInfo, MethodInfo, ParameterInfo, TypeId, TypeInfo, TypeKind, TypeRegistry, get_embedded_type_registry_json, diff --git a/crates/ocs_plugin_api/src/scene.rs b/crates/ocs_plugin_api/src/scene.rs index a617a94926..36a38e06d0 100644 --- a/crates/ocs_plugin_api/src/scene.rs +++ b/crates/ocs_plugin_api/src/scene.rs @@ -810,6 +810,11 @@ pub enum PanelSurface { /// host-local, and children a plugin has not pushed yet page in via /// `WidgetPage` installs. Widgets(crate::widget::WidgetSurface), + /// The panel's typed-table surface (api v29, S07): stable row keys, + /// typed scalar cells, atomic cell/row patches — rendered and edited + /// with NATIVE host widgets (edits are host-local drafts until the + /// plugin canonicalizes them with its own patch). + Tables(crate::tables::TableSurface), } /// Why a panel surface publish was refused; a refusal changes nothing. @@ -878,6 +883,16 @@ pub enum SurfaceEvent { /// one expansion case that is NOT host-local — the plugin is the /// data source). NodeExpanded { node: StableId }, + /// A committed cell edit on a table surface (api v29, S07): the + /// host-local editing session committed a draft under the + /// typed-commit rule; the plugin remains the data authority and + /// canonicalizes by pushing its own table patch. Best-effort like + /// every surface event. + CellEdited { + row: StableId, + column: StableId, + value: crate::tables::CellValue, + }, } /// Maximum patch ops accepted in one patch frame, bounding allocation and diff --git a/crates/ocs_plugin_api/src/tables.rs b/crates/ocs_plugin_api/src/tables.rs new file mode 100644 index 0000000000..007bb71aa2 --- /dev/null +++ b/crates/ocs_plugin_api/src/tables.rs @@ -0,0 +1,434 @@ +//! The typed-table surface data model (api v29, S07): tables with STABLE +//! row keys, TYPED SCALAR cells, and atomic cell/row patches. +//! +//! Ownership split (the scene/widget tier law): the plugin owns the +//! semantics; the host owns selection, scroll and the editing session +//! (host-local transient state), rendering natively. The wire carries +//! only this serializable vocabulary. +//! +//! Finding F4's table requirements, minimally: STABLE row keys survive +//! edits and paging; CELL patches update one cell without republishing +//! the table; row patches add/remove whole rows; a page is a batch of +//! `InsertRow` ops positioned after an existing row. Finding-scope +//! exclusions honored: no shared-table reference machinery, no +//! non-scalar presentation cells (a concrete example will introduce +//! them). +//! +//! Atomic everywhere: a patch stages a candidate and swaps only on full +//! success — a failing op never leaves a partial table. + +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashSet}; + +use crate::scene::StableId; + +/// A table surface's own revision — independent of scene/widget +/// revisions (finding F1). +#[derive( + Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, +)] +pub struct TableRevision(pub u64); + +/// Maximum rows in one table surface (mirrors the widget budget). +pub const MAX_TABLE_ROWS: usize = 10_000; + +/// Maximum ops in one table patch (mirrors the scene patch budget). +pub const MAX_TABLE_OPS: usize = 10_000; + +/// A typed scalar cell value (finding-scope exclusion: non-scalar +/// presentation types wait for a concrete example). Numbers must be +/// finite; text is bounded by the dialog text budget. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum CellValue { + Text(String), + Number(f64), + Bool(bool), +} + +/// One column: a stable key (the cell index is DERIVED from the column +/// order, never stored per cell) and a display label. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TableColumn { + pub id: StableId, + pub label: String, +} + +/// Why a table patch refused. Codes append at the end. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TableError { + /// The patch's base revision is not the table's current revision. + StaleBase, + /// The patch carries more ops than [`MAX_TABLE_OPS`]. + PatchTooLarge, + /// The table would exceed [`MAX_TABLE_ROWS`]. + TableTooLarge, + /// The op names a row that is not in the table. + UnknownRow, + /// The op names a column that is not in the table. + UnknownColumn, + /// A row id collides with an existing row (or appears twice). + DuplicateRow, + /// A cell count does not match the column count. + ArityMismatch, + /// A number cell is not finite (NaN/inf are rejected). + NonFiniteNumber, + /// A text cell exceeds the text budget. + TextTooLong, +} + +impl core::fmt::Display for TableError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + TableError::StaleBase => write!(f, "patch base is not the current table revision"), + TableError::PatchTooLarge => write!(f, "table patch carries too many ops"), + TableError::TableTooLarge => write!(f, "table row budget exceeded"), + TableError::UnknownRow => write!(f, "table row is not in the surface"), + TableError::UnknownColumn => write!(f, "table column is not in the surface"), + TableError::DuplicateRow => write!(f, "table row id collides"), + TableError::ArityMismatch => write!(f, "row cells do not match the column count"), + TableError::NonFiniteNumber => write!(f, "number cell is not finite"), + TableError::TextTooLong => write!(f, "text cell exceeds the text budget"), + } + } +} + +/// The stored table surface: columns (ordered, stable keys), rows keyed +/// by stable id, and the display order. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct TableSurface { + pub revision: TableRevision, + pub columns: Vec, + pub rows: BTreeMap>, + pub order: Vec, +} + +impl TableSurface { + /// A fresh, empty table with `columns` (labels bounded). + pub fn new(revision: TableRevision, columns: Vec) -> Self { + Self { + revision, + columns, + rows: BTreeMap::new(), + order: Vec::new(), + } + } + + fn check_cells(&self, cells: &[CellValue]) -> Result<(), TableError> { + if cells.len() != self.columns.len() { + return Err(TableError::ArityMismatch); + } + for cell in cells { + match cell { + CellValue::Number(n) if !n.is_finite() => return Err(TableError::NonFiniteNumber), + CellValue::Text(t) if t.len() > crate::scene::MAX_TEXT_BYTES => { + return Err(TableError::TextTooLong); + } + _ => {} + } + } + Ok(()) + } + + /// Validate the whole table: budgets, arity, and every row reachable + /// from the display order exactly once. + pub fn validate(&self) -> Result<(), TableError> { + if self.rows.len() > MAX_TABLE_ROWS { + return Err(TableError::TableTooLarge); + } + for cells in self.rows.values() { + self.check_cells(cells)?; + } + let mut seen = HashSet::new(); + for id in &self.order { + if !seen.insert(*id) { + return Err(TableError::DuplicateRow); + } + if !self.rows.contains_key(id) { + return Err(TableError::UnknownRow); + } + } + if seen.len() != self.rows.len() { + return Err(TableError::UnknownRow); + } + Ok(()) + } + + /// Apply a patch atomically: on any refusal the table is + /// byte-for-byte unchanged; on success the revision advances by one + /// and the whole table re-validates. + pub fn apply_patch(&mut self, patch: &TablePatch) -> Result { + if patch.base_revision != self.revision { + return Err(TableError::StaleBase); + } + if patch.ops.len() > MAX_TABLE_OPS { + return Err(TableError::PatchTooLarge); + } + let mut candidate = self.clone(); + for op in &patch.ops { + apply_op(&mut candidate, op)?; + } + candidate.revision = TableRevision(self.revision.0 + 1); + candidate.validate()?; + *self = candidate; + Ok(self.revision) + } +} + +/// One atomic table update op. New ops append at the end; never renumber. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum TableOp { + /// Update ONE cell: the single-cell edit path (the proof obligation + /// for finding F4 — a cell update never republishes the table). + SetCell { + row: StableId, + column: StableId, + value: CellValue, + }, + /// Insert a whole row (a PAGE is a positioned batch of these). + InsertRow { + after: Option, + row: StableId, + cells: Vec, + }, + /// Remove a row by its stable key. + RemoveRow { row: StableId }, +} + +/// A revision-checked table patch: ops apply atomically against the +/// table whose revision equals `base_revision`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TablePatch { + pub base_revision: TableRevision, + pub ops: Vec, +} + +fn apply_op(table: &mut TableSurface, op: &TableOp) -> Result<(), TableError> { + match op { + TableOp::SetCell { row, column, value } => { + let Some(cells) = table.rows.get_mut(row) else { + return Err(TableError::UnknownRow); + }; + let Some(index) = table.columns.iter().position(|c| c.id == *column) else { + return Err(TableError::UnknownColumn); + }; + match value { + CellValue::Number(n) if !n.is_finite() => return Err(TableError::NonFiniteNumber), + CellValue::Text(t) if t.len() > crate::scene::MAX_TEXT_BYTES => { + return Err(TableError::TextTooLong); + } + _ => {} + } + cells[index] = value.clone(); + } + TableOp::InsertRow { after, row, cells } => { + if table.rows.contains_key(row) { + return Err(TableError::DuplicateRow); + } + table.check_cells(cells)?; + let position = match after { + None => table.order.len(), + Some(after_id) => { + table + .order + .iter() + .position(|id| id == after_id) + .ok_or(TableError::UnknownRow)? + + 1 + } + }; + if table.rows.len() + 1 > MAX_TABLE_ROWS { + return Err(TableError::TableTooLarge); + } + table.order.insert(position, *row); + table.rows.insert(*row, cells.clone()); + } + TableOp::RemoveRow { row } => { + let Some(position) = table.order.iter().position(|id| id == row) else { + return Err(TableError::UnknownRow); + }; + table.order.remove(position); + table.rows.remove(row); + } + } + Ok(()) +} + +/// Why a table-tier wire request refused. The table 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 TableRejectCode { + /// Nothing is attached for this panel (no host attach, or the panel + /// is not registered by the authenticated plugin), or the table was + /// never published so it cannot be patched. + 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 table-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 TableReject { + pub code: TableRejectCode, + /// The stored head when the refusal is revision-related; `None` + /// otherwise. + pub current_revision: Option, +} + +impl From for TableRejectCode { + fn from(code: crate::scene::SurfaceRejectCode) -> Self { + match code { + crate::scene::SurfaceRejectCode::Unattached => TableRejectCode::Unattached, + crate::scene::SurfaceRejectCode::OwnedByOther => TableRejectCode::OwnedByOther, + _ => TableRejectCode::InvalidSurface, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const ROW_A: StableId = StableId(10); + const ROW_B: StableId = StableId(11); + const COL_NAME: StableId = StableId(1); + const COL_LEN: StableId = StableId(2); + + fn table() -> TableSurface { + let mut t = TableSurface::new( + TableRevision(1), + vec![ + TableColumn { + id: COL_NAME, + label: "name".to_owned(), + }, + TableColumn { + id: COL_LEN, + label: "len".to_owned(), + }, + ], + ); + t.apply_patch(&TablePatch { + base_revision: TableRevision(1), + ops: vec![TableOp::InsertRow { + after: None, + row: ROW_A, + cells: vec![CellValue::Text("alpha".to_owned()), CellValue::Number(1.0)], + }], + }) + .expect("seed row"); + t + } + + #[test] + fn single_cell_update_changes_one_cell_and_bumps_one_revision() { + let mut t = table(); + let before = t.clone(); + let revision = t + .apply_patch(&TablePatch { + base_revision: TableRevision(2), + ops: vec![TableOp::SetCell { + row: ROW_A, + column: COL_LEN, + value: CellValue::Number(42.0), + }], + }) + .expect("cell update"); + assert_eq!(revision, TableRevision(3)); + assert_eq!( + t.rows.get(&ROW_A).unwrap()[1], + CellValue::Number(42.0), + "exactly the addressed cell changed" + ); + assert_eq!( + t.rows.get(&ROW_A).unwrap()[0], + CellValue::Text("alpha".to_owned()) + ); + assert_eq!(t.order, vec![ROW_A]); + assert_ne!(t, before, "the revision moved"); + } + + #[test] + fn atomic_patch_refuses_without_partial_mutation() { + let mut t = table(); + let patch = TablePatch { + base_revision: TableRevision(2), + ops: vec![ + TableOp::SetCell { + row: ROW_A, + column: COL_LEN, + value: CellValue::Number(7.0), + }, + TableOp::RemoveRow { row: ROW_B }, // unknown row: fails + ], + }; + assert_eq!(t.apply_patch(&patch), Err(TableError::UnknownRow)); + assert_eq!( + t.rows.get(&ROW_A).unwrap()[1], + CellValue::Number(1.0), + "the valid op must not survive a failed patch" + ); + } + + #[test] + fn page_install_is_a_positioned_row_batch() { + let mut t = table(); + let patch = TablePatch { + base_revision: TableRevision(2), + ops: vec![ + TableOp::InsertRow { + after: Some(ROW_A), + row: ROW_B, + cells: vec![CellValue::Text("beta".to_owned()), CellValue::Number(2.0)], + }, + TableOp::InsertRow { + after: Some(ROW_B), + row: StableId(12), + cells: vec![CellValue::Text("gamma".to_owned()), CellValue::Bool(true)], + }, + ], + }; + t.apply_patch(&patch).expect("page"); + assert_eq!(t.order, vec![ROW_A, ROW_B, StableId(12)]); + } + + #[test] + fn stale_base_and_arity_and_finiteness_are_refused() { + let mut t = table(); + let stale = TablePatch { + base_revision: TableRevision(9), + ops: vec![TableOp::RemoveRow { row: ROW_A }], + }; + assert_eq!(t.apply_patch(&stale), Err(TableError::StaleBase)); + + let arity = TablePatch { + base_revision: TableRevision(2), + ops: vec![TableOp::InsertRow { + after: None, + row: ROW_B, + cells: vec![CellValue::Bool(false)], + }], + }; + assert_eq!(t.apply_patch(&arity), Err(TableError::ArityMismatch)); + + let nonfinite = TablePatch { + base_revision: TableRevision(2), + ops: vec![TableOp::SetCell { + row: ROW_A, + column: COL_LEN, + value: CellValue::Number(f64::NAN), + }], + }; + assert_eq!(t.apply_patch(&nonfinite), Err(TableError::NonFiniteNumber)); + assert_eq!(t.rows.get(&ROW_A).unwrap()[1], CellValue::Number(1.0)); + } +} diff --git a/src/app/dock/view.rs b/src/app/dock/view.rs index 1f35adbf05..b246d56192 100644 --- a/src/app/dock/view.rs +++ b/src/app/dock/view.rs @@ -763,7 +763,18 @@ impl OpenCADStudio { // 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)) = ( + if let (Some(owner), Some(table)) = ( + state.owner_plugin_id.as_deref(), + state + .owner_plugin_id + .as_deref() + .and_then(|owner| self.panel_surfaces.table(owner, panel_id)), + ) { + let table_ui = self.panel_table_ui.get(panel_id); + crate::ui::window::plugin_tables::table_view( + owner, panel_id, table, table_ui, + ) + } else if let (Some(owner), Some(surface)) = ( state.owner_plugin_id.as_deref(), state .owner_plugin_id diff --git a/src/app/message.rs b/src/app/message.rs index b4a45cbee5..792dcac702 100644 --- a/src/app/message.rs +++ b/src/app/message.rs @@ -551,6 +551,29 @@ pub enum Message { panel: String, node: ocs_plugin_api::scene::StableId, }, + /// A keystroke in a table cell editor: host-local draft state only. + PanelTableCellDraft { + owner: String, + panel: String, + row: ocs_plugin_api::scene::StableId, + column: ocs_plugin_api::scene::StableId, + text: String, + }, + /// A table cell editor was submitted: the typed-commit rule runs and + /// a successful commit notifies `SurfaceEvent::CellEdited`. + PanelTableCellCommitted { + owner: String, + panel: String, + row: ocs_plugin_api::scene::StableId, + column: ocs_plugin_api::scene::StableId, + }, + /// A table cell editor gained focus: host-local selection. + PanelTableCellSelected { + owner: String, + panel: String, + row: ocs_plugin_api::scene::StableId, + column: 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 a4c093f21c..0996fa64a0 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1650,6 +1650,12 @@ pub(super) struct OpenCADStudio { String, crate::ui::window::plugin_widgets::WidgetUiState, >, + /// Host-local EDITING session per panel id (api v29): draft cells + /// and selection. The plugin stays the data authority. + pub(crate) panel_table_ui: std::collections::BTreeMap< + String, + crate::ui::window::plugin_tables::TableUiState, + >, /// Numeric mapping for PanelId::Plugin(u32). pub(crate) plugin_panel_ids: std::collections::HashMap, pub(crate) plugin_panel_by_num: std::collections::HashMap, @@ -3261,6 +3267,7 @@ impl OpenCADStudio { panel_event_router: crate::app::panel_events::PanelEventRouter::new(), panel_widget_ui: std::collections::BTreeMap::new(), + panel_table_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 e28e8add09..27e5608ae1 100644 --- a/src/app/panel_events.rs +++ b/src/app/panel_events.rs @@ -230,6 +230,24 @@ impl PanelEventRouter { } } + /// A committed cell edit on a table surface (api v29, S07): the + /// explicit event identity is the per-surface sequence, as + /// everywhere. + pub fn on_cell_edited( + &mut self, + panel_id: &str, + row: StableId, + column: StableId, + value: ocs_plugin_api::tables::CellValue, + ) -> RoutedEvent { + let sequence = self.next_sequence(panel_id); + RoutedEvent { + panel_id: panel_id.to_owned(), + sequence, + event: SurfaceEvent::CellEdited { row, column, value }, + } + } + /// 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 { diff --git a/src/app/panel_surfaces.rs b/src/app/panel_surfaces.rs index 0341bae28d..3ee87fe8b1 100644 --- a/src/app/panel_surfaces.rs +++ b/src/app/panel_surfaces.rs @@ -12,6 +12,13 @@ use ocs_plugin_api::scene::{PanelScene, SceneRevision, SurfaceReject, SurfaceRej pub struct PanelSurfaceStore { scenes: std::collections::BTreeMap, widgets: std::collections::BTreeMap, + tables: std::collections::BTreeMap, +} + +#[derive(Debug, Clone, PartialEq)] +struct TableRecord { + owner_plugin_id: String, + surface: ocs_plugin_api::tables::TableSurface, } #[derive(Debug, Clone, PartialEq)] @@ -155,6 +162,8 @@ impl PanelSurfaceStore { .retain(|_, record| keep(&record.owner_plugin_id)); self.widgets .retain(|_, record| keep(&record.owner_plugin_id)); + self.tables + .retain(|_, record| keep(&record.owner_plugin_id)); } /// Publish (or replace) the panel's WIDGET surface (api v29, S05): @@ -270,6 +279,119 @@ impl PanelSurfaceStore { .filter(|record| record.owner_plugin_id == plugin_id) .map(|record| &record.surface) } + + /// Publish (or replace) the panel's TABLE surface (api v29, S07): + /// the same ownership/revision rules, on the table tier's independent + /// revision space. + pub fn publish_table( + &mut self, + plugin_id: &str, + panel_id: &str, + surface: ocs_plugin_api::tables::TableSurface, + ) -> Result { + use ocs_plugin_api::tables::{TableReject, TableRejectCode}; + if plugin_id.is_empty() || panel_id.trim().is_empty() { + return Err(TableReject { + code: TableRejectCode::Unattached, + current_revision: None, + }); + } + if surface.validate().is_err() { + return Err(TableReject { + code: TableRejectCode::InvalidSurface, + current_revision: None, + }); + } + if let Some(record) = self.tables.get(panel_id) { + if record.owner_plugin_id != plugin_id { + return Err(TableReject { + code: TableRejectCode::OwnedByOther, + current_revision: Some(record.surface.revision), + }); + } + let head = record.surface.revision; + if surface.revision == head { + if surface == record.surface { + return Ok(head); + } + return Err(TableReject { + code: TableRejectCode::NonMonotonicRevision, + current_revision: Some(head), + }); + } + if surface.revision < head { + return Err(TableReject { + code: TableRejectCode::NonMonotonicRevision, + current_revision: Some(head), + }); + } + } + let revision = surface.revision; + self.tables.insert( + panel_id.to_string(), + TableRecord { + owner_plugin_id: plugin_id.to_string(), + surface, + }, + ); + Ok(revision) + } + + /// Apply a bounded table patch atomically (cell/row ops). Only a + /// previously published table can be patched; ownership and revision + /// rules match publishing. + pub fn patch_table( + &mut self, + plugin_id: &str, + panel_id: &str, + patch: ocs_plugin_api::tables::TablePatch, + ) -> Result { + use ocs_plugin_api::tables::{TableReject, TableRejectCode}; + if plugin_id.is_empty() || panel_id.trim().is_empty() { + return Err(TableReject { + code: TableRejectCode::Unattached, + current_revision: None, + }); + } + let Some(record) = self.tables.get_mut(panel_id) else { + return Err(TableReject { + code: TableRejectCode::Unattached, + current_revision: None, + }); + }; + if record.owner_plugin_id != plugin_id { + return Err(TableReject { + code: TableRejectCode::OwnedByOther, + current_revision: Some(record.surface.revision), + }); + } + match record.surface.apply_patch(&patch) { + Ok(revision) => Ok(revision), + Err(ocs_plugin_api::tables::TableError::StaleBase) => Err(TableReject { + code: TableRejectCode::NonMonotonicRevision, + current_revision: Some(record.surface.revision), + }), + Err(_) => Err(TableReject { + code: TableRejectCode::InvalidSurface, + current_revision: None, + }), + } + } + + /// Ownership-checked table read (api v29). + pub fn table( + &self, + plugin_id: &str, + panel_id: &str, + ) -> Option<&ocs_plugin_api::tables::TableSurface> { + if plugin_id.is_empty() { + return None; + } + self.tables + .get(panel_id) + .filter(|record| record.owner_plugin_id == plugin_id) + .map(|record| &record.surface) + } } #[cfg(test)] diff --git a/src/app/plugin_host/host_api.rs b/src/app/plugin_host/host_api.rs index aa75495d9e..27dc2a74e1 100644 --- a/src/app/plugin_host/host_api.rs +++ b/src/app/plugin_host/host_api.rs @@ -526,6 +526,45 @@ impl HostApi for HostSession<'_> { .install_widget_page(plugin_id, &resolved, page) } + /// V29 (additive): publish the panel's TABLE surface from the + /// authenticated transport owner; the table tier's independent + /// revision space. + fn panel_table_publish_for_plugin( + &mut self, + plugin_id: &str, + panel_id: &str, + surface: ocs_plugin_api::tables::TableSurface, + ) -> Result { + let resolved = self + .resolve_surface_panel(plugin_id, panel_id) + .map_err(|code| ocs_plugin_api::tables::TableReject { + code: code.into(), + current_revision: None, + })?; + self.app + .panel_surfaces + .publish_table(plugin_id, &resolved, surface) + } + + /// V29 (additive): patch the panel's stored TABLE atomically from + /// the authenticated transport owner (cell/row ops). + fn panel_surface_table_patch_for_plugin( + &mut self, + plugin_id: &str, + panel_id: &str, + patch: ocs_plugin_api::tables::TablePatch, + ) -> Result { + let resolved = self + .resolve_surface_panel(plugin_id, panel_id) + .map_err(|code| ocs_plugin_api::tables::TableReject { + code: code.into(), + current_revision: None, + })?; + self.app + .panel_surfaces + .patch_table(plugin_id, &resolved, patch) + } + /// V29 (additive): patch the panel's stored scene atomically from the /// authenticated transport owner. Same attachment/ownership /// resolution as publishing; the store owns structural and revision diff --git a/src/app/update/dispatch.rs b/src/app/update/dispatch.rs index dc1360eb03..53dbf2be03 100644 --- a/src/app/update/dispatch.rs +++ b/src/app/update/dispatch.rs @@ -2164,6 +2164,70 @@ impl OpenCADStudio { Task::none() } + Message::PanelTableCellDraft { + owner, + panel, + row, + column, + text, + } => { + // Host-local draft state; the stored table is untouched. + self.panel_table_ui + .entry(panel.clone()) + .or_default() + .set_draft(row, column, text); + let _ = owner; + Task::none() + } + Message::PanelTableCellSelected { owner, panel, row, column } => { + self.panel_table_ui + .entry(panel.clone()) + .or_default() + .select((row, column)); + let _ = owner; + Task::none() + } + Message::PanelTableCellCommitted { + owner, + panel, + row, + column, + } => { + // Typed-commit rule: the edited value takes the existing + // cell's type; a failed parse keeps the draft. A commit + // notifies the plugin (best-effort, owner-targeted) — the + // plugin stays the data authority and canonicalizes with + // its own table patch. + let stored = self + .panel_surfaces + .table(&owner, &panel) + .and_then(|surface| { + let index = surface.columns.iter().position(|c| c.id == column)?; + surface + .rows + .get(&row) + .and_then(|cells| cells.get(index)) + .cloned() + }); + let value = self + .panel_table_ui + .entry(panel.clone()) + .or_default() + .commit_draft(row, column, stored.as_ref()); + if let Ok(value) = value { + let routed = self + .panel_event_router + .on_cell_edited(&panel, row, column, value); + #[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/mod.rs b/src/ui/window/mod.rs index 230e47f76e..f9652e49c6 100644 --- a/src/ui/window/mod.rs +++ b/src/ui/window/mod.rs @@ -61,6 +61,8 @@ pub mod plugin_manager; pub mod plugin_panel; /// Native scene-surface projection for plugin panels (api v29). pub mod plugin_scene; +/// Native EDITABLE table rendering for plugin panels (api v29). +pub mod plugin_tables; /// Native widget-surface rendering for plugin panels (api v29). pub mod plugin_widgets; pub mod print_all; diff --git a/src/ui/window/plugin_tables.rs b/src/ui/window/plugin_tables.rs new file mode 100644 index 0000000000..812b1a7f24 --- /dev/null +++ b/src/ui/window/plugin_tables.rs @@ -0,0 +1,285 @@ +//! Native rendering + host-local EDITING of plugin table surfaces +//! (api v29, S07). +//! +//! Ownership split (the scene/widget tier law): the plugin owns the +//! DATA; the host owns the editing session — draft cells are HOST-LOCAL +//! transient state, and a committed edit is a best-effort +//! `SurfaceEvent::CellEdited` notification. The plugin stays the data +//! authority: it canonicalizes by pushing its own `TablePatch` through +//! the normal wire path; until then the host shows its local draft. +//! +//! Rendering is native widgets only — a scrollable grid of header + +//! row cells, edits through text inputs bound to the draft state. The +//! typed-commit rule: an edit takes the TYPE of the cell it replaces +//! (Number edits parse, Bool edits parse true/false, Text is free); a +//! failed parse keeps the draft uncommitted. + +use crate::app::Message; +use crate::app::panel_events::PanelEventRouter; +use iced::widget::{column, container, row, scrollable, text, text_input}; +use iced::{Element, Length}; +use ocs_plugin_api::scene::StableId; +use ocs_plugin_api::tables::{CellValue, TableSurface}; +use std::collections::{BTreeMap, HashSet}; + +/// Hard cap on render recursion (tables are flat; this bounds the row +/// walk defensively). +const MAX_RENDER_ROWS: usize = 10_000; + +/// Host-local editing session for one panel's table surface: draft cell +/// texts keyed by (row id, column id), and the selected cell. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TableUiState { + /// In-progress edits: the TEXT the user typed, keyed by cell. + pub drafts: BTreeMap<(StableId, StableId), String>, + pub selected: Option<(StableId, StableId)>, +} + +impl TableUiState { + /// The value a cell should DISPLAY: the draft while editing, else + /// the stored cell's text. + pub fn display_text( + &self, + row: StableId, + column: StableId, + stored: Option<&CellValue>, + ) -> String { + if let Some(draft) = self.drafts.get(&(row, column)) { + return draft.clone(); + } + match stored { + Some(CellValue::Text(t)) => t.clone(), + Some(CellValue::Number(n)) => n.to_string(), + Some(CellValue::Bool(b)) => b.to_string(), + None => String::new(), + } + } + + /// Record a keystroke: the draft updates (or is created); the stored + /// table is untouched. + pub fn set_draft(&mut self, row: StableId, column: StableId, text: String) { + self.drafts.insert((row, column), text); + } + + /// Commit a draft under the typed-commit rule: `Ok(value)` carries + /// the typed cell (the existing cell's type governs the parse); + /// `Err(())` keeps the draft (a failed Number/Bool parse is not a + /// commit). The draft clears ONLY on success — the user's text + /// survives until the plugin canonicalizes. + pub fn commit_draft( + &mut self, + row: StableId, + column: StableId, + stored: Option<&CellValue>, + ) -> Result { + let draft = self.drafts.remove(&(row, column)).ok_or(())?; + let text = draft.trim().to_owned(); + match stored { + Some(CellValue::Number(_)) => text + .parse::() + .map(|n| CellValue::Number(n)) + .map_err(|_| { + self.drafts.insert((row, column), draft); + }), + Some(CellValue::Bool(_)) => match text.as_str() { + "true" => Ok(CellValue::Bool(true)), + "false" => Ok(CellValue::Bool(false)), + _ => { + self.drafts.insert((row, column), draft); + Err(()) + } + }, + Some(CellValue::Text(_)) | None => Ok(CellValue::Text(text)), + } + } + + /// Select a cell (host-local highlight). + pub fn select(&mut self, cell: (StableId, StableId)) { + self.selected = Some(cell); + } +} + +/// Render one table surface with the host's native widgets. `drafts_out` +/// is unused by the view itself; edits flow as Messages and the dispatch +/// mutates the caller's [`TableUiState`]. +pub(crate) fn table_view<'a>( + owner: &'a str, + panel: &'a str, + surface: &TableSurface, + ui: Option<&TableUiState>, +) -> Element<'a, Message> { + let default_ui = TableUiState::default(); + let ui = ui.unwrap_or(&default_ui); + // Header row. + let mut header = row![].spacing(2); + for col in &surface.columns { + header = header.push( + container(text(col.label.clone()).size(12)) + .width(Length::Fill) + .padding(iced::Padding { + top: 2.0, + right: 2.0, + bottom: 2.0, + left: 2.0, + }), + ); + } + let mut grid = column![header].spacing(2); + let mut count = 0usize; + for row_id in &surface.order { + if count >= MAX_RENDER_ROWS { + break; + } + count += 1; + let Some(cells) = surface.rows.get(row_id) else { + continue; + }; + let mut row_widget = row![].spacing(2); + for (index, col) in surface.columns.iter().enumerate() { + let stored = cells.get(index); + let display = ui.display_text(*row_id, col.id, stored); + let (owner, panel) = (owner.to_owned(), panel.to_owned()); + let (r, c) = (*row_id, col.id); + let (owner_in, panel_in) = (owner.clone(), panel.clone()); + let (owner_sub, panel_sub) = (owner.clone(), panel.clone()); + let cell = text_input("", display.as_str()) + .size(12) + .width(Length::Fill) + .on_input(move |text| Message::PanelTableCellDraft { + owner: owner_in.clone(), + panel: panel_in.clone(), + row: r, + column: c, + text, + }) + .on_submit(Message::PanelTableCellCommitted { + owner: owner_sub, + panel: panel_sub, + row: r, + column: c, + }); + row_widget = row_widget.push(container(cell).width(Length::Fill)); + } + grid = grid.push(row_widget); + } + scrollable(container(grid.width(Length::Fill))).into() +} + +/// The typed-commit helper shared by the dispatch: resolves the typed +/// value for a cell against the stored surface, or `None` when the draft +/// must stay (failed parse) or the cell/column is unknown. +pub(crate) fn typed_commit( + surface: &TableSurface, + row: StableId, + column: StableId, + draft: &str, +) -> Option { + let cells = surface.rows.get(&row)?; + let index = surface.columns.iter().position(|c| c.id == column)?; + let stored = cells.get(index); + let trimmed = draft.trim().to_owned(); + match stored { + Some(CellValue::Number(_)) => trimmed.parse::().ok().map(CellValue::Number), + Some(CellValue::Bool(_)) => match trimmed.as_str() { + "true" => Some(CellValue::Bool(true)), + "false" => Some(CellValue::Bool(false)), + _ => None, + }, + _ => Some(CellValue::Text(trimmed)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ocs_plugin_api::tables::{TableColumn, TableRevision}; + + fn table() -> TableSurface { + let mut t = TableSurface::new( + TableRevision(1), + vec![ + TableColumn { + id: StableId(1), + label: "name".to_owned(), + }, + TableColumn { + id: StableId(2), + label: "len".to_owned(), + }, + ], + ); + t.apply_patch(&ocs_plugin_api::tables::TablePatch { + base_revision: TableRevision(1), + ops: vec![ocs_plugin_api::tables::TableOp::InsertRow { + after: None, + row: StableId(10), + cells: vec![CellValue::Text("alpha".to_owned()), CellValue::Number(1.0)], + }], + }) + .expect("seed"); + t + } + + #[test] + fn drafts_shadow_the_stored_value_until_committed() { + let mut ui = TableUiState::default(); + let t = table(); + ui.set_draft(StableId(10), StableId(2), "99".to_owned()); + assert_eq!( + ui.display_text(StableId(10), StableId(2), Some(&CellValue::Number(1.0))), + "99", + "the draft shadows the stored cell" + ); + ui.set_draft(StableId(10), StableId(1), "beta".to_owned()); + assert_eq!( + ui.display_text( + StableId(10), + StableId(1), + Some(&CellValue::Text("alpha".to_owned())) + ), + "beta" + ); + let _ = t; + } + + #[test] + fn typed_commit_takes_the_existing_cell_type() { + let mut ui = TableUiState::default(); + let t = table(); + ui.set_draft(StableId(10), StableId(2), "42".to_owned()); + assert_eq!( + typed_commit(&t, StableId(10), StableId(2), "42"), + Some(CellValue::Number(42.0)), + "a Number cell parses the edit" + ); + ui.set_draft(StableId(10), StableId(1), "beta".to_owned()); + assert_eq!( + typed_commit(&t, StableId(10), StableId(1), "beta"), + Some(CellValue::Text("beta".to_owned())) + ); + } + + #[test] + fn failed_parse_keeps_the_draft_and_commits_nothing() { + let mut ui = TableUiState::default(); + let t = table(); + ui.set_draft(StableId(10), StableId(2), "not-a-number".to_owned()); + assert_eq!( + typed_commit(&t, StableId(10), StableId(2), "not-a-number"), + None + ); + assert_eq!( + ui.drafts + .get(&(StableId(10), StableId(2))) + .map(String::as_str), + Some("not-a-number"), + "the user's text survives a failed parse" + ); + // A later valid draft commits. + ui.set_draft(StableId(10), StableId(2), "7".to_owned()); + assert_eq!( + typed_commit(&t, StableId(10), StableId(2), "7"), + Some(CellValue::Number(7.0)) + ); + } +}