* claim: #11218 * Panels: add shared layout rules and retained content runtime * claim: #11304 * Panels: inspect and change layouts through shared commands (#11304) * Panels: account for layout commands in geometry coverage
This commit is contained in:
@@ -33,7 +33,7 @@ impl Refusal {
|
||||
/// The batch reply for a batch refused before its first step: as a failed step's reply,
|
||||
/// with nothing completed, nothing undone and every step not run.
|
||||
pub fn reply(&self, steps: usize) -> Value {
|
||||
json!({
|
||||
let mut reply = json!({
|
||||
"completed": 0,
|
||||
"results": [],
|
||||
"failed": {"index": self.index, "command": self.command, "error": self.error},
|
||||
@@ -41,7 +41,11 @@ impl Refusal {
|
||||
"rolled_back": false,
|
||||
"not_run": (0..steps).collect::<Vec<_>>(),
|
||||
"note": "nothing was run: the batch was checked before its first step",
|
||||
})
|
||||
});
|
||||
if let Some(reason) = crate::panels::commands::structured_error(&self.error) {
|
||||
reply["failed"]["panel_error"] = reason;
|
||||
}
|
||||
reply
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +86,15 @@ pub fn contracts(steps: &[Value]) -> Option<Refusal> {
|
||||
|
||||
/// Step `index`'s refusal when its parameters break the typed contract of its command `id`.
|
||||
fn contract_refusal(index: usize, id: &str, step: &Value) -> Option<Refusal> {
|
||||
if crate::panels::commands::is_command(id) {
|
||||
let empty = json!({});
|
||||
let params = step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty);
|
||||
return crate::panels::commands::parse_command(id, params).err().map(|reason| Refusal {
|
||||
index,
|
||||
command: Some(id.into()),
|
||||
error: crate::panels::commands::error_text(reason),
|
||||
});
|
||||
}
|
||||
let first = crate::schema::issues(id, step.get("params").unwrap_or(&Value::Null)).into_iter().next()?;
|
||||
Some(Refusal { index, command: Some(id.to_string()), error: crate::params::bad(id, first.message).to_string() })
|
||||
}
|
||||
|
||||
@@ -87,6 +87,7 @@ pub(crate) use measure_sel::{measure_items, shape_of};
|
||||
pub(crate) use measure_shape::Shape;
|
||||
#[cfg(test)]
|
||||
mod kernel_heal_tests;
|
||||
mod panels;
|
||||
mod parameter_sweep;
|
||||
mod parameters;
|
||||
mod plastic;
|
||||
@@ -340,6 +341,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
|
||||
v.extend(joints::COMMANDS.iter());
|
||||
v.extend(clearance::COMMANDS.iter());
|
||||
v.extend(motion::COMMANDS.iter());
|
||||
v.extend(panels::COMMANDS.iter());
|
||||
v.extend(config::COMMANDS.iter());
|
||||
v.extend(parts::COMMANDS.iter());
|
||||
v.extend(bom::COMMANDS.iter());
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! Registry metadata for externally injected application-layout commands.
|
||||
use super::CommandSpec;
|
||||
use crate::schema::panels as wire;
|
||||
|
||||
fn unavailable(_: &mut crate::Session, _: &serde_json::Value) -> crate::Result<serde_json::Value> {
|
||||
Err(crate::EngineError::Panel(crate::panels::error(crate::panels::Rule::Capability, "application layout backend was not injected")))
|
||||
}
|
||||
|
||||
macro_rules! command {
|
||||
($id:literal, $icon:literal, $label:literal, $input:ty, $output:ty, $params:literal) => {
|
||||
CommandSpec::new($id, $label, crate::checked!($id, unavailable))
|
||||
.icon($icon)
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&wire::CommandContract::<$input>::new($id))
|
||||
.output(wire::strict_output::<$output>)
|
||||
.params($params)
|
||||
};
|
||||
}
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
command!(
|
||||
"layout.apply",
|
||||
"open",
|
||||
"Apply Layout",
|
||||
wire::Apply,
|
||||
crate::panels::LayoutReply,
|
||||
"name, expected_revision?: apply preset to current workspace through retained runtime"
|
||||
),
|
||||
command!("layout.get", "list", "Inspect Layout", wire::Empty, wire::GetReply, "{}: committed state and registered workspace summaries"),
|
||||
command!(
|
||||
"layout.reset",
|
||||
"restore",
|
||||
"Reset Layout",
|
||||
wire::Revision,
|
||||
crate::panels::LayoutReply,
|
||||
"expected_revision?: restore current workspace's registered default"
|
||||
),
|
||||
command!(
|
||||
"layout.save",
|
||||
"save",
|
||||
"Save Layout",
|
||||
wire::Save,
|
||||
wire::SaveReply,
|
||||
"name, overwrite?: false, expected_revision?: save complete envelope in injected catalogue"
|
||||
),
|
||||
command!(
|
||||
"layout.workspace.select",
|
||||
"display",
|
||||
"Select Layout Workspace",
|
||||
wire::WorkspaceSelect,
|
||||
wire::WorkspaceReply,
|
||||
"workspace, expected_revision?: atomically remember outgoing and replace with destination"
|
||||
),
|
||||
command!(
|
||||
"panel.activate",
|
||||
"activate",
|
||||
"Activate Panel Tab",
|
||||
wire::Select,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, expected_revision?: activate open tab without focus"
|
||||
),
|
||||
command!(
|
||||
"panel.close",
|
||||
"close",
|
||||
"Close Panel",
|
||||
wire::Select,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, expected_revision?: explicit guarded close"
|
||||
),
|
||||
command!(
|
||||
"panel.collapse",
|
||||
"fold",
|
||||
"Collapse Panel Section",
|
||||
wire::Collapse,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, collapsed, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.dismiss",
|
||||
"close",
|
||||
"Dismiss Panel Peek",
|
||||
wire::Revision,
|
||||
crate::panels::LayoutReply,
|
||||
"expected_revision?: dismiss temporary collapsed-panel presentation"
|
||||
),
|
||||
command!(
|
||||
"panel.float",
|
||||
"move",
|
||||
"Float Panel",
|
||||
wire::Move,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, destination: new_section with floating location, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.focus",
|
||||
"fit",
|
||||
"Focus Panel",
|
||||
wire::Select,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, expected_revision?: reopen retained state, activate and request focus"
|
||||
),
|
||||
command!(
|
||||
"panel.list",
|
||||
"list",
|
||||
"List Panels",
|
||||
wire::Empty,
|
||||
wire::ListReply,
|
||||
"{}: committed state, active tabs, capabilities, availability and registered kinds"
|
||||
),
|
||||
command!(
|
||||
"panel.move",
|
||||
"move",
|
||||
"Move Panel",
|
||||
wire::Move,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, destination: new_section or join_tab, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.native_close",
|
||||
"restore",
|
||||
"Redock Native Panel Section",
|
||||
wire::Select,
|
||||
crate::panels::LayoutReply,
|
||||
"target: native_host, expected_revision?: native close redocks without cancelling content"
|
||||
),
|
||||
command!(
|
||||
"panel.open",
|
||||
"open",
|
||||
"Open Panel",
|
||||
wire::Open,
|
||||
crate::panels::LayoutReply,
|
||||
"kind, instance, destination?: required for new instance, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.peek",
|
||||
"eye",
|
||||
"Peek Collapsed Panel",
|
||||
wire::Select,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, expected_revision?: transient presentation without resizing"
|
||||
),
|
||||
command!(
|
||||
"panel.popout",
|
||||
"display",
|
||||
"Pop Out Panel",
|
||||
wire::Move,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, destination: new_section with window location, expected_revision?: web lowers to floating"
|
||||
),
|
||||
command!(
|
||||
"panel.reset_pair",
|
||||
"restore",
|
||||
"Reset Panel Sash",
|
||||
wire::ResetPair,
|
||||
crate::panels::LayoutReply,
|
||||
"first, second, expected_revision?: reset adjacent dock pair to registered default ratio"
|
||||
),
|
||||
command!(
|
||||
"panel.resize",
|
||||
"scale",
|
||||
"Resize Panel Section",
|
||||
wire::Resize,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, size: {width,height}, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.resize_pair",
|
||||
"scale",
|
||||
"Resize Panel Sash",
|
||||
wire::ResizePair,
|
||||
crate::panels::LayoutReply,
|
||||
"first, second, first_size, second_size, expected_revision?: conserve adjacent dock pair extent"
|
||||
),
|
||||
];
|
||||
@@ -81,9 +81,11 @@ fn classify(e: &EngineError) -> Outcome {
|
||||
let msg = e.to_string();
|
||||
match e {
|
||||
EngineError::Internal(..) => Outcome::new("panic", msg),
|
||||
EngineError::BadParams { .. } | EngineError::Disabled(..) | EngineError::Refused { .. } | EngineError::UnknownCommand(_) => {
|
||||
Outcome::new("rejected", msg)
|
||||
}
|
||||
EngineError::Panel(_)
|
||||
| EngineError::BadParams { .. }
|
||||
| EngineError::Disabled(..)
|
||||
| EngineError::Refused { .. }
|
||||
| EngineError::UnknownCommand(_) => Outcome::new("rejected", msg),
|
||||
// A failed boolean is a failure even when it says "not supported": those are the cases
|
||||
// to fix. Features the kernel doesn't do yet are limitations.
|
||||
// Picks the generator got wrong (a centroid off its face).
|
||||
|
||||
@@ -21,6 +21,7 @@ pub mod frames;
|
||||
pub mod fuzz;
|
||||
pub mod licences;
|
||||
pub mod occurrences;
|
||||
pub mod panels;
|
||||
pub mod params;
|
||||
pub mod product_scene;
|
||||
pub mod recovery;
|
||||
@@ -66,6 +67,8 @@ pub const MAX_LINE: usize = 16 << 20;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
#[error("{text}", text = panels::commands::error_text(.0.clone()))]
|
||||
Panel(#[from] panels::PanelError),
|
||||
#[error("unknown command `{0}`{hint}", hint = cmd::did_you_mean(.0))]
|
||||
UnknownCommand(String),
|
||||
#[error("`{0}` is not available right now: {1}")]
|
||||
@@ -1610,6 +1613,12 @@ impl Session {
|
||||
/// the model up to date before anything reads it.
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
if panels::commands::is_command(spec.id) {
|
||||
// Layout is application state. Even a missing capability must not
|
||||
// clear live links, map picks, snapshot, evaluate or refresh a design.
|
||||
panels::commands::parse_command(spec.id, params)?;
|
||||
return Err(EngineError::Panel(panels::error(panels::Rule::Capability, "application layout backend was not injected")));
|
||||
}
|
||||
// The command, the evaluation it causes and the refresh after it: one profiler span.
|
||||
let _span = solidcraft_profile::span("command", spec.id);
|
||||
let host_viewport = self.render_viewport.clone();
|
||||
|
||||
@@ -0,0 +1,946 @@
|
||||
//! Application-owned command execution shared by UI, control and headless MCP.
|
||||
//! No Session, document, geometry, dialogs or camera are reachable here.
|
||||
mod catalogue;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
use crate::schema::panels as wire;
|
||||
|
||||
pub const MAX_USER_PRESETS: usize = 64;
|
||||
pub const MAX_WORKSPACES: usize = 64;
|
||||
pub const MAX_CATALOGUE_BYTES: usize = 4 * 1024 * 1024;
|
||||
pub const MAX_CATALOGUE_METADATA_BYTES: usize = 16 * 1024;
|
||||
/// Framing is bounded separately from the aggregate payload/metadata budgets.
|
||||
pub const MAX_CATALOGUE_SNAPSHOT_BYTES: usize = MAX_CATALOGUE_BYTES + MAX_CATALOGUE_METADATA_BYTES + 8192;
|
||||
pub const MAX_COMMAND_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// Full envelope plus bounded rejected recovery intent. Arc makes catalogue
|
||||
/// preparation bounded without copying each maximum-sized envelope 64 times.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StoredEnvelope {
|
||||
bytes: Arc<[u8]>,
|
||||
rejected: Option<Arc<[u8]>>,
|
||||
}
|
||||
impl StoredEnvelope {
|
||||
pub fn new(envelope: &LayoutEnvelope, rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult<Self> {
|
||||
if rejected.is_some_and(|bytes| bytes.len() > MAX_ENVELOPE_BYTES) {
|
||||
return Err(error(Rule::CollectionLimit, "rejected recovery byte cap"));
|
||||
}
|
||||
Ok(Self { bytes: encode(envelope, registry)?.into(), rejected: rejected.map(Arc::from) })
|
||||
}
|
||||
/// Exact retained inspection, including saved instances whose kinds are now
|
||||
/// absent. This is not a live-layout admission check; stage with
|
||||
/// `project_envelope` before submitting through the authoritative sink.
|
||||
pub fn envelope(&self, registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult<LayoutEnvelope> {
|
||||
decode_retained(&self.bytes, registry, workspace)
|
||||
}
|
||||
/// Explicitly stage current-registry quarantine before a guarded live use.
|
||||
/// Exact inspection above deliberately keeps absent-kind saved instances.
|
||||
pub fn project_envelope(&self, registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult<LayoutEnvelope> {
|
||||
project_retained_record(&self.bytes, registry, workspace)
|
||||
}
|
||||
/// Hydration retains the original validated bytes. In particular, optional
|
||||
/// order/projection metadata is not filled and recounted against the cap.
|
||||
fn from_record(bytes: &[u8], rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult<Self> {
|
||||
if rejected.is_some_and(|bytes| bytes.len() > MAX_ENVELOPE_BYTES) {
|
||||
return Err(error(Rule::CollectionLimit, "rejected recovery byte cap"));
|
||||
}
|
||||
decode_retained_record(bytes, registry)?;
|
||||
Ok(Self { bytes: Arc::from(bytes), rejected: rejected.map(Arc::from) })
|
||||
}
|
||||
pub fn rejected(&self) -> Option<&[u8]> {
|
||||
self.rejected.as_deref()
|
||||
}
|
||||
pub fn bytes(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WorkspaceDescriptor {
|
||||
pub id: WorkspaceId,
|
||||
pub title_key: String,
|
||||
pub default_preset: String,
|
||||
}
|
||||
|
||||
/// Fields are private: registrations and prepared updates must obey aggregate
|
||||
/// bounds before cloning or publishing. There is no independently stored selection.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CatalogueState {
|
||||
workspaces: BTreeMap<WorkspaceId, WorkspaceDescriptor>,
|
||||
builtins: BTreeMap<String, StoredEnvelope>,
|
||||
users: BTreeMap<String, StoredEnvelope>,
|
||||
remembered: BTreeMap<WorkspaceId, StoredEnvelope>,
|
||||
}
|
||||
impl CatalogueState {
|
||||
pub fn summaries(&self) -> Vec<wire::WorkspaceSummary> {
|
||||
self.workspaces
|
||||
.values()
|
||||
.map(|item| wire::WorkspaceSummary {
|
||||
id: item.id.clone(),
|
||||
title_key: item.title_key.clone(),
|
||||
default_preset: item.default_preset.clone(),
|
||||
has_remembered_layout: self.remembered.contains_key(&item.id),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
pub fn user_count(&self) -> usize {
|
||||
self.users.len()
|
||||
}
|
||||
pub fn user_presets(&self) -> impl Iterator<Item = (&str, &StoredEnvelope)> {
|
||||
self.users.iter().map(|(name, record)| (name.as_str(), record))
|
||||
}
|
||||
pub fn remembered(&self, workspace: &WorkspaceId) -> Option<&StoredEnvelope> {
|
||||
self.remembered.get(workspace)
|
||||
}
|
||||
pub fn preset(&self, name: &str) -> PanelResult<&StoredEnvelope> {
|
||||
self.builtins.get(name).or_else(|| self.users.get(name)).ok_or_else(|| error(Rule::MissingTarget, "layout preset not registered"))
|
||||
}
|
||||
fn validate(&self) -> PanelResult<()> {
|
||||
if self.users.keys().any(|name| self.builtins.contains_key(name)) {
|
||||
return Err(error(Rule::DuplicateId, "user preset collides with immutable built-in"));
|
||||
}
|
||||
if self.users.len() > MAX_USER_PRESETS
|
||||
|| self.builtins.len() > MAX_USER_PRESETS
|
||||
|| self.workspaces.len() > MAX_WORKSPACES
|
||||
|| self.remembered.len() > MAX_WORKSPACES
|
||||
{
|
||||
return Err(error(Rule::CollectionLimit, "layout catalogue count cap"));
|
||||
}
|
||||
let mut metadata = 0_usize;
|
||||
for (id, item) in &self.workspaces {
|
||||
valid_id(&id.0)?;
|
||||
valid_id(&item.title_key)?;
|
||||
if item.id != *id || !self.builtins.contains_key(&item.default_preset) {
|
||||
return Err(error(Rule::MissingTarget, "workspace requires a registered immutable default"));
|
||||
}
|
||||
metadata = metadata.saturating_add(id.0.len() + item.title_key.len() + item.default_preset.len());
|
||||
}
|
||||
let mut bytes = 0_usize;
|
||||
for (name, stored) in self.builtins.iter().chain(&self.users) {
|
||||
if preset_name(name)? != *name {
|
||||
return Err(error(Rule::Schema, "preset name must be normalised"));
|
||||
}
|
||||
metadata = metadata.saturating_add(name.len());
|
||||
bytes = bytes.saturating_add(stored.bytes.len() + stored.rejected.as_ref().map_or(0, |r| r.len()));
|
||||
}
|
||||
for (id, stored) in &self.remembered {
|
||||
valid_id(&id.0)?;
|
||||
metadata = metadata.saturating_add(id.0.len());
|
||||
bytes = bytes.saturating_add(stored.bytes.len() + stored.rejected.as_ref().map_or(0, |r| r.len()));
|
||||
}
|
||||
if metadata > MAX_CATALOGUE_METADATA_BYTES || bytes > MAX_CATALOGUE_BYTES {
|
||||
return Err(error(Rule::CollectionLimit, "aggregate layout catalogue byte cap"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PreparedCatalogue(CatalogueState);
|
||||
impl PreparedCatalogue {
|
||||
pub fn new(state: CatalogueState) -> PanelResult<Self> {
|
||||
state.validate()?;
|
||||
Ok(Self(state))
|
||||
}
|
||||
pub fn state(&self) -> &CatalogueState {
|
||||
&self.0
|
||||
}
|
||||
pub fn into_state(self) -> CatalogueState {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare MUST stage every fallible storage operation. Publish MUST be infallible.
|
||||
/// The executor holds the exclusive catalogue borrow across guarded dispatch.
|
||||
pub trait LayoutCatalogue {
|
||||
fn state(&self) -> &CatalogueState;
|
||||
fn prepare(&mut self, next: CatalogueState) -> PanelResult<PreparedCatalogue>;
|
||||
fn publish(&mut self, prepared: PreparedCatalogue);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct InMemoryCatalogue {
|
||||
state: CatalogueState,
|
||||
/// Failure-injectable storage staging; no state has been published on failure.
|
||||
pub fail_stage: bool,
|
||||
}
|
||||
impl LayoutCatalogue for InMemoryCatalogue {
|
||||
fn state(&self) -> &CatalogueState {
|
||||
&self.state
|
||||
}
|
||||
fn prepare(&mut self, next: CatalogueState) -> PanelResult<PreparedCatalogue> {
|
||||
if self.fail_stage {
|
||||
return Err(error(Rule::Capability, "layout storage staging unavailable"));
|
||||
}
|
||||
PreparedCatalogue::new(next)
|
||||
}
|
||||
fn publish(&mut self, prepared: PreparedCatalogue) {
|
||||
self.state = prepared.into_state();
|
||||
}
|
||||
}
|
||||
impl InMemoryCatalogue {
|
||||
/// Hydration builds a validated candidate, without live dispatch or changing
|
||||
/// the mutability of saved user presets. Production storage remains external.
|
||||
pub fn from_snapshot(bytes: &[u8], registry: &PanelRegistry) -> PanelResult<Self> {
|
||||
Ok(Self { state: CatalogueState::hydrate(bytes, registry)?, fail_stage: false })
|
||||
}
|
||||
/// Explicit fixture/peer registration, never populated with invented products.
|
||||
pub fn register_builtin(&mut self, name: &str, envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
let name = preset_name(name)?;
|
||||
if self.state.builtins.contains_key(&name) || self.state.users.contains_key(&name) {
|
||||
return Err(error(Rule::DuplicateId, "preset already registered"));
|
||||
}
|
||||
let stored = StoredEnvelope::new(envelope, None, registry)?;
|
||||
let mut next = self.state.clone();
|
||||
next.builtins.insert(name, stored);
|
||||
let prepared = self.prepare(next)?;
|
||||
self.publish(prepared);
|
||||
Ok(())
|
||||
}
|
||||
pub fn register_workspace(&mut self, descriptor: WorkspaceDescriptor) -> PanelResult<()> {
|
||||
valid_id(&descriptor.id.0)?;
|
||||
valid_id(&descriptor.title_key)?;
|
||||
if self.state.workspaces.contains_key(&descriptor.id) {
|
||||
return Err(error(Rule::DuplicateId, "workspace already registered"));
|
||||
}
|
||||
let mut next = self.state.clone();
|
||||
next.workspaces.insert(descriptor.id.clone(), descriptor);
|
||||
let prepared = self.prepare(next)?;
|
||||
self.publish(prepared);
|
||||
Ok(())
|
||||
}
|
||||
pub fn remember(&mut self, envelope: &LayoutEnvelope, rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
let stored = StoredEnvelope::new(envelope, rejected, registry)?;
|
||||
let mut next = self.state.clone();
|
||||
next.remembered.insert(envelope.layout.workspace.clone(), stored);
|
||||
let prepared = self.prepare(next)?;
|
||||
self.publish(prepared);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn preset_name(raw: &str) -> PanelResult<String> {
|
||||
// Bound BEFORE trimming, allocating or iterating over scalars.
|
||||
if raw.len() > 1024 {
|
||||
return Err(error(Rule::CollectionLimit, "raw preset name byte cap"));
|
||||
}
|
||||
let name = raw.trim();
|
||||
if name.is_empty() || name.len() > 256 || name.chars().count() > 64 || raw.chars().any(char::is_control) {
|
||||
return Err(error(Rule::Schema, "preset name requires 1..64 Unicode scalars without controls"));
|
||||
}
|
||||
Ok(name.into())
|
||||
}
|
||||
|
||||
pub fn is_command(id: &str) -> bool {
|
||||
crate::find_command(id).is_some_and(|spec| IDS.contains(&spec.id))
|
||||
}
|
||||
pub const IDS: &[&str] = &[
|
||||
"layout.apply",
|
||||
"layout.get",
|
||||
"layout.reset",
|
||||
"layout.save",
|
||||
"layout.workspace.select",
|
||||
"panel.activate",
|
||||
"panel.close",
|
||||
"panel.collapse",
|
||||
"panel.dismiss",
|
||||
"panel.float",
|
||||
"panel.focus",
|
||||
"panel.list",
|
||||
"panel.move",
|
||||
"panel.native_close",
|
||||
"panel.open",
|
||||
"panel.peek",
|
||||
"panel.popout",
|
||||
"panel.reset_pair",
|
||||
"panel.resize",
|
||||
"panel.resize_pair",
|
||||
];
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PanelCommand {
|
||||
List,
|
||||
Get,
|
||||
Open(wire::Open),
|
||||
Select { operation: &'static str, params: wire::Select },
|
||||
Move { operation: &'static str, params: wire::Move },
|
||||
Resize(wire::Resize),
|
||||
Collapse(wire::Collapse),
|
||||
Dismiss(wire::Revision),
|
||||
ResizePair(wire::ResizePair),
|
||||
ResetPair(wire::ResetPair),
|
||||
Save(wire::Save),
|
||||
Apply(wire::Apply),
|
||||
Reset(wire::Revision),
|
||||
Workspace(wire::WorkspaceSelect),
|
||||
}
|
||||
fn read<T: DeserializeOwned>(value: &Value) -> PanelResult<T> {
|
||||
serde_json::from_value(value.clone()).map_err(|_| error(Rule::Schema, "invalid panel command fields or types"))
|
||||
}
|
||||
pub fn parse_command(id: &str, params: &Value) -> PanelResult<PanelCommand> {
|
||||
// Keep the engine/control convention: absent/null params mean an empty form.
|
||||
let empty = json!({});
|
||||
let params = if params.is_null() { &empty } else { params };
|
||||
if !params.is_object() {
|
||||
return Err(error(Rule::Schema, "panel command parameters must be an object"));
|
||||
}
|
||||
bounded_json(params)?;
|
||||
// Capped writer protects direct callers as well as transports, before clone.
|
||||
struct Counter(usize);
|
||||
impl std::io::Write for Counter {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
self.0 = self.0.saturating_add(bytes.len());
|
||||
if self.0 > MAX_COMMAND_BYTES {
|
||||
return Err(std::io::Error::other("command byte cap"));
|
||||
}
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
serde_json::to_writer(Counter(0), params).map_err(|_| error(Rule::CollectionLimit, "panel command byte cap"))?;
|
||||
let id = crate::find_command(id).map(|s| s.id).ok_or_else(|| error(Rule::MissingTarget, "unknown panel command"))?;
|
||||
let command = match id {
|
||||
"panel.list" => {
|
||||
let _: wire::Empty = read(params)?;
|
||||
PanelCommand::List
|
||||
}
|
||||
"layout.get" => {
|
||||
let _: wire::Empty = read(params)?;
|
||||
PanelCommand::Get
|
||||
}
|
||||
"panel.open" => PanelCommand::Open(read(params)?),
|
||||
"panel.close" | "panel.activate" | "panel.focus" | "panel.peek" | "panel.native_close" => {
|
||||
PanelCommand::Select { operation: id, params: read(params)? }
|
||||
}
|
||||
"panel.move" | "panel.float" | "panel.popout" => PanelCommand::Move { operation: id, params: read(params)? },
|
||||
"panel.resize" => PanelCommand::Resize(read(params)?),
|
||||
"panel.collapse" => PanelCommand::Collapse(read(params)?),
|
||||
"panel.dismiss" => PanelCommand::Dismiss(read(params)?),
|
||||
"panel.resize_pair" => PanelCommand::ResizePair(read(params)?),
|
||||
"panel.reset_pair" => PanelCommand::ResetPair(read(params)?),
|
||||
"layout.save" => PanelCommand::Save(read(params)?),
|
||||
"layout.apply" => PanelCommand::Apply(read(params)?),
|
||||
"layout.reset" => PanelCommand::Reset(read(params)?),
|
||||
"layout.workspace.select" => PanelCommand::Workspace(read(params)?),
|
||||
_ => return Err(error(Rule::MissingTarget, "not an application layout command")),
|
||||
};
|
||||
// Validate hostile values even when no application capability is injected.
|
||||
validate_command(&command)?;
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
fn validate_selector(target: &Option<wire::Target>, id: &Option<String>) -> PanelResult<()> {
|
||||
match (target, id) {
|
||||
(Some(target), None) => match target {
|
||||
wire::Target::Instance(id) => valid_id(&id.0),
|
||||
wire::Target::Section(id) => valid_id(&id.0),
|
||||
wire::Target::Workspace(id) => valid_id(&id.0),
|
||||
wire::Target::NativeHost(id) => valid_id(&id.0),
|
||||
},
|
||||
(None, Some(id)) => valid_id(id),
|
||||
_ => Err(error(Rule::Schema, "supply exactly one typed target or legacy id")),
|
||||
}
|
||||
}
|
||||
fn validate_destination(destination: Destination) -> PanelResult<()> {
|
||||
match destination {
|
||||
Destination::NewSection { section, index, location, size } => {
|
||||
valid_id(§ion.0)?;
|
||||
location.validate()?;
|
||||
size.validate()?;
|
||||
if index > MAX_SECTIONS {
|
||||
return Err(error(Rule::Bounds, "section index cap"));
|
||||
}
|
||||
}
|
||||
Destination::JoinTab { section, index } => {
|
||||
valid_id(§ion.0)?;
|
||||
if index >= MAX_TABS {
|
||||
return Err(error(Rule::Bounds, "tab index cap"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn validate_command(command: &PanelCommand) -> PanelResult<()> {
|
||||
match command {
|
||||
PanelCommand::Open(p) => {
|
||||
valid_id(&p.kind.0)?;
|
||||
valid_id(&p.instance.0)?;
|
||||
if let Some(destination) = &p.destination {
|
||||
validate_destination(destination.clone().into())?;
|
||||
}
|
||||
}
|
||||
PanelCommand::Select { params, .. } => validate_selector(¶ms.target, ¶ms.id)?,
|
||||
PanelCommand::Move { params, .. } => {
|
||||
validate_selector(¶ms.target, ¶ms.id)?;
|
||||
validate_destination(params.destination.clone().into())?;
|
||||
}
|
||||
PanelCommand::Resize(p) => {
|
||||
validate_selector(&p.target, &p.id)?;
|
||||
Size::from(p.size).validate()?;
|
||||
}
|
||||
PanelCommand::Collapse(p) => validate_selector(&p.target, &p.id)?,
|
||||
PanelCommand::ResizePair(p) => {
|
||||
valid_id(&p.first.0)?;
|
||||
valid_id(&p.second.0)?;
|
||||
Size::from(p.first_size).validate()?;
|
||||
Size::from(p.second_size).validate()?;
|
||||
}
|
||||
PanelCommand::ResetPair(p) => {
|
||||
valid_id(&p.first.0)?;
|
||||
valid_id(&p.second.0)?;
|
||||
}
|
||||
PanelCommand::Save(p) => {
|
||||
preset_name(&p.name)?;
|
||||
}
|
||||
PanelCommand::Apply(p) => {
|
||||
preset_name(&p.name)?;
|
||||
}
|
||||
PanelCommand::Workspace(p) => valid_id(&p.workspace.0)?,
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct PanelCommandContext<'a> {
|
||||
pub sink: &'a mut dyn ActionSink,
|
||||
pub registry: &'a PanelRegistry,
|
||||
pub catalogue: &'a mut dyn LayoutCatalogue,
|
||||
/// Web popout is an explicit host policy, never inferred from no native support.
|
||||
pub web: bool,
|
||||
}
|
||||
|
||||
fn target(target: Option<wire::Target>, legacy: Option<String>, layout: &Layout, registry: &PanelRegistry) -> PanelResult<LayoutTarget> {
|
||||
if let Some(target) = target {
|
||||
return Ok(target.into());
|
||||
}
|
||||
let id = legacy.ok_or_else(|| error(Rule::Schema, "target required"))?;
|
||||
let instance = InstanceId::new(id.clone())?;
|
||||
if layout.instance(&instance).is_ok() {
|
||||
return Ok(LayoutTarget::Instance(instance));
|
||||
}
|
||||
let kind = PanelKind::new(id)?;
|
||||
let spec = registry.get(&kind)?;
|
||||
if spec.features.multi_instance {
|
||||
return Err(error(Rule::ExactlyOnce, "kind selector is ambiguous for multi-instance panels; supply typed instance"));
|
||||
}
|
||||
let matches: Vec<_> = layout.instances.iter().filter(|p| p.kind == kind).collect();
|
||||
if matches.len() != 1 {
|
||||
return Err(error(Rule::MissingTarget, "kind requires one canonical retained instance"));
|
||||
}
|
||||
Ok(LayoutTarget::Instance(matches.first().ok_or_else(|| error(Rule::MissingTarget, "canonical instance absent"))?.id.clone()))
|
||||
}
|
||||
fn instance(target: LayoutTarget, layout: &Layout) -> PanelResult<InstanceId> {
|
||||
match target {
|
||||
LayoutTarget::Instance(id) => {
|
||||
layout.instance(&id)?;
|
||||
Ok(id)
|
||||
}
|
||||
_ => Err(error(Rule::Schema, "operation requires instance target")),
|
||||
}
|
||||
}
|
||||
fn section(target: LayoutTarget, layout: &Layout) -> PanelResult<SectionId> {
|
||||
match target {
|
||||
LayoutTarget::Section(id) => {
|
||||
layout.section(&id)?;
|
||||
Ok(id)
|
||||
}
|
||||
LayoutTarget::Instance(id) => Ok(layout.containing(&id)?.id.clone()),
|
||||
_ => Err(error(Rule::Schema, "operation requires section or open instance target")),
|
||||
}
|
||||
}
|
||||
fn revision(expected: Option<u64>, state: &LayoutReply) -> PanelResult<()> {
|
||||
if expected.is_some_and(|r| r != state.revision) {
|
||||
return Err(error(Rule::Revision, "stale layout revision"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lower(command: PanelCommand, state: &LayoutReply, registry: &PanelRegistry, web: bool) -> PanelResult<Mutation> {
|
||||
let layout = &state.layout;
|
||||
Ok(match command {
|
||||
PanelCommand::Open(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
Mutation::Open { kind: p.kind, instance: p.instance, destination: p.destination.map(Into::into) }
|
||||
}
|
||||
PanelCommand::Select { operation, params: p } => {
|
||||
revision(p.expected_revision, state)?;
|
||||
let selected = target(p.target, p.id, layout, registry)?;
|
||||
if operation == "panel.native_close" {
|
||||
let LayoutTarget::NativeHost(host) = selected else {
|
||||
return Err(error(Rule::Schema, "native close requires typed native_host target"));
|
||||
};
|
||||
Mutation::NativeClose { host }
|
||||
} else {
|
||||
let instance = instance(selected, layout)?;
|
||||
match operation {
|
||||
"panel.close" => Mutation::Close { instance },
|
||||
"panel.focus" => Mutation::Focus { instance },
|
||||
"panel.activate" => Mutation::Activate { instance },
|
||||
"panel.peek" => Mutation::Peek { instance },
|
||||
_ => return Err(error(Rule::Schema, "unknown target operation")),
|
||||
}
|
||||
}
|
||||
}
|
||||
PanelCommand::Move { operation, params: p } => {
|
||||
revision(p.expected_revision, state)?;
|
||||
let instance = instance(target(p.target, p.id, layout, registry)?, layout)?;
|
||||
let mut destination: Destination = p.destination.into();
|
||||
if operation == "panel.float" && !matches!(&destination, Destination::NewSection { location: SectionLocation::Floating { .. }, .. }) {
|
||||
return Err(error(Rule::Placement, "panel.float requires new_section with floating location"));
|
||||
}
|
||||
if operation == "panel.popout" {
|
||||
if !registry.get(&layout.instance(&instance)?.kind)?.features.popout {
|
||||
return Err(error(Rule::FeatureDisabled, "panel cannot pop out"));
|
||||
}
|
||||
match &mut destination {
|
||||
Destination::NewSection { location, .. } => match location {
|
||||
SectionLocation::Window { origin, .. } => {
|
||||
if web {
|
||||
*location = SectionLocation::Floating { origin: *origin };
|
||||
}
|
||||
}
|
||||
_ => return Err(error(Rule::Placement, "panel.popout requires new_section with window location")),
|
||||
},
|
||||
_ => return Err(error(Rule::Placement, "panel.popout requires a new section")),
|
||||
}
|
||||
}
|
||||
Mutation::Move { instance, destination }
|
||||
}
|
||||
PanelCommand::Resize(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
Mutation::SetSize { section: section(target(p.target, p.id, layout, registry)?, layout)?, size: p.size.into() }
|
||||
}
|
||||
PanelCommand::Collapse(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
Mutation::Collapse { section: section(target(p.target, p.id, layout, registry)?, layout)?, collapsed: p.collapsed }
|
||||
}
|
||||
PanelCommand::Dismiss(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
Mutation::DismissPeek
|
||||
}
|
||||
PanelCommand::ResizePair(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
Mutation::ResizePair { first: p.first, second: p.second, first_size: p.first_size.into(), second_size: p.second_size.into() }
|
||||
}
|
||||
PanelCommand::ResetPair(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
Mutation::ResetPair { first: p.first, second: p.second }
|
||||
}
|
||||
_ => return Err(error(Rule::Capability, "catalogue/query commands require individual transactions")),
|
||||
})
|
||||
}
|
||||
|
||||
fn current_envelope(catalogue: &CatalogueState, state: &LayoutReply, registry: &PanelRegistry) -> PanelResult<(LayoutEnvelope, Option<Arc<[u8]>>)> {
|
||||
let workspace = &state.layout.workspace;
|
||||
match catalogue.remembered.get(workspace) {
|
||||
Some(stored) => {
|
||||
Ok((with_live_layout(&stored.project_envelope(registry, workspace)?, state.layout.clone(), registry)?, stored.rejected.clone()))
|
||||
}
|
||||
None => Ok((LayoutEnvelope::new(state.layout.clone()), None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve all opaque sidecars. Reusing an identity with different opaque intent
|
||||
/// is an error, never silently resolved by choosing one preset's value.
|
||||
fn merge_envelopes(current: &LayoutEnvelope, mut next: LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<LayoutEnvelope> {
|
||||
next.layout.workspace = current.layout.workspace.clone();
|
||||
for item in ¤t.quarantine {
|
||||
if next.layout.instances.iter().any(|known| known.id == item.instance) {
|
||||
return Err(error(Rule::DuplicateId, "preset collides with quarantined identity"));
|
||||
}
|
||||
match next.quarantine.iter().find(|q| q.instance == item.instance) {
|
||||
Some(existing) if existing != item => return Err(error(Rule::DuplicateId, "quarantine sidecar collision")),
|
||||
Some(_) => {}
|
||||
None => next.quarantine.push(item.clone()),
|
||||
}
|
||||
}
|
||||
for (id, data) in ¤t.retained_data {
|
||||
if next.retained_data.get(id).is_some_and(|existing| existing != data) {
|
||||
return Err(error(Rule::DuplicateId, "retained data collision"));
|
||||
}
|
||||
if let (Ok(old), Ok(new)) = (current.layout.instance(id), next.layout.instance(id))
|
||||
&& old.kind != new.kind
|
||||
{
|
||||
return Err(error(Rule::DuplicateId, "retained instance kind collision"));
|
||||
}
|
||||
next.retained_data.insert(id.clone(), data.clone());
|
||||
}
|
||||
for (id, snapshot) in ¤t.section_snapshots {
|
||||
if next.section_snapshots.get(id).is_some_and(|existing| existing != snapshot) {
|
||||
return Err(error(Rule::DuplicateId, "section sidecar collision"));
|
||||
}
|
||||
next.section_snapshots.insert(id.clone(), snapshot.clone());
|
||||
}
|
||||
// Preserve dormant gaps from current; subsequent refresh overlays live order.
|
||||
let dormant: std::collections::BTreeSet<_> = next.quarantine.iter().filter_map(|q| q.section.clone()).collect();
|
||||
let live: std::collections::BTreeSet<_> = next.layout.sections.iter().map(|s| s.id.clone()).collect();
|
||||
let mut order: Vec<_> = current.section_order.iter().filter(|id| dormant.contains(*id) || live.contains(*id)).cloned().collect();
|
||||
for id in &next.section_order {
|
||||
if !order.contains(id) {
|
||||
order.push(id.clone());
|
||||
}
|
||||
}
|
||||
next.section_order = order;
|
||||
let layout = next.layout.clone();
|
||||
with_live_layout(&next, layout, registry)
|
||||
}
|
||||
|
||||
fn stage_current(
|
||||
context: &mut PanelCommandContext<'_>,
|
||||
state: &LayoutReply,
|
||||
action: &LayoutAction,
|
||||
envelope: &LayoutEnvelope,
|
||||
recovery: Option<Arc<[u8]>>,
|
||||
mut next: CatalogueState,
|
||||
) -> PanelResult<(LayoutReply, CatalogueState)> {
|
||||
let projected = context.sink.project(action.clone())?;
|
||||
let envelope = with_live_layout(envelope, projected, context.registry)?;
|
||||
let stored = StoredEnvelope::new(&envelope, recovery.as_deref(), context.registry)?;
|
||||
next.remembered.insert(envelope.layout.workspace.clone(), stored);
|
||||
let prepared = context.catalogue.prepare(next)?;
|
||||
// Inspect can change through external adapters between planning and dispatch.
|
||||
// Every action below includes the inspected revision; no stale catalogue publishes.
|
||||
if context.sink.inspect().revision != state.revision {
|
||||
return Err(error(Rule::Revision, "layout changed during storage staging"));
|
||||
}
|
||||
let committed = if *action == LayoutAction::Inspect {
|
||||
let current = context.sink.inspect();
|
||||
revision(Some(state.revision), ¤t)?;
|
||||
current
|
||||
} else {
|
||||
context.sink.dispatch(action.clone())?
|
||||
};
|
||||
context.catalogue.publish(prepared);
|
||||
Ok((committed, context.catalogue.state().clone()))
|
||||
}
|
||||
|
||||
pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<'_>) -> PanelResult<Value> {
|
||||
validate_command(&command)?;
|
||||
let state = context.sink.inspect();
|
||||
match command {
|
||||
PanelCommand::List => return value(wire::ListReply { state, kinds: context.registry.specs().cloned().collect() }),
|
||||
PanelCommand::Get => return value(wire::GetReply { state, workspaces: context.catalogue.state().summaries() }),
|
||||
PanelCommand::Workspace(ref p) if p.workspace == state.layout.workspace => {
|
||||
revision(p.expected_revision, &state)?;
|
||||
return value(wire::WorkspaceReply {
|
||||
previous_workspace: state.layout.workspace.clone(),
|
||||
source: wire::WorkspaceSource::Unchanged,
|
||||
state,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut next = context.catalogue.state().clone();
|
||||
let (current, recovery) = current_envelope(&next, &state, context.registry)?;
|
||||
match command {
|
||||
PanelCommand::Save(p) => {
|
||||
revision(p.expected_revision, &state)?;
|
||||
let name = preset_name(&p.name)?;
|
||||
if next.builtins.contains_key(&name) {
|
||||
return Err(error(Rule::Capability, "built-in presets are immutable"));
|
||||
}
|
||||
let overwritten = next.users.contains_key(&name);
|
||||
if overwritten && !p.overwrite {
|
||||
return Err(error(Rule::DuplicateId, "preset exists; overwrite must be explicit"));
|
||||
}
|
||||
if !overwritten && next.users.len() >= MAX_USER_PRESETS {
|
||||
return Err(error(Rule::CollectionLimit, "user preset count cap"));
|
||||
}
|
||||
next.users.insert(name.clone(), StoredEnvelope::new(¤t, recovery.as_deref(), context.registry)?);
|
||||
let action = LayoutAction::Inspect;
|
||||
let (state, _) = stage_current(context, &state, &action, ¤t, recovery, next)?;
|
||||
value(wire::SaveReply { name, overwritten, state })
|
||||
}
|
||||
PanelCommand::Apply(p) => {
|
||||
revision(p.expected_revision, &state)?;
|
||||
let stored = next.preset(&preset_name(&p.name)?)?;
|
||||
let mut envelope: LayoutEnvelope =
|
||||
serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid registered envelope"))?;
|
||||
// Decode using its original workspace before rebinding to the current one.
|
||||
envelope = stored.project_envelope(context.registry, &envelope.layout.workspace)?;
|
||||
let mut envelope = merge_envelopes(¤t, envelope, context.registry)?;
|
||||
restore_quarantine(&mut envelope, context.registry)?;
|
||||
let recovery = merge_recovery(recovery, stored.rejected.clone())?;
|
||||
let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() };
|
||||
value(stage_current(context, &state, &action, &envelope, recovery, next)?.0)
|
||||
}
|
||||
PanelCommand::Reset(p) => {
|
||||
revision(p.expected_revision, &state)?;
|
||||
let descriptor = next
|
||||
.workspaces
|
||||
.get(&state.layout.workspace)
|
||||
.ok_or_else(|| error(Rule::Capability, "selected workspace has no registered default"))?;
|
||||
let stored = next.preset(&descriptor.default_preset)?;
|
||||
let raw: LayoutEnvelope = serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid default envelope"))?;
|
||||
let mut envelope = merge_envelopes(¤t, stored.project_envelope(context.registry, &raw.layout.workspace)?, context.registry)?;
|
||||
restore_quarantine(&mut envelope, context.registry)?;
|
||||
let recovery = merge_recovery(recovery, stored.rejected.clone())?;
|
||||
let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() };
|
||||
value(stage_current(context, &state, &action, &envelope, recovery, next)?.0)
|
||||
}
|
||||
PanelCommand::Workspace(p) => {
|
||||
revision(p.expected_revision, &state)?;
|
||||
let previous_workspace = state.layout.workspace.clone();
|
||||
if p.workspace == previous_workspace {
|
||||
return value(wire::WorkspaceReply { previous_workspace, source: wire::WorkspaceSource::Unchanged, state });
|
||||
}
|
||||
let descriptor = next.workspaces.get(&p.workspace).ok_or_else(|| error(Rule::MissingTarget, "workspace not registered"))?;
|
||||
let (stored, source) = match next.remembered.get(&p.workspace) {
|
||||
Some(stored) => (stored, wire::WorkspaceSource::Remembered),
|
||||
None => (next.preset(&descriptor.default_preset)?, wire::WorkspaceSource::DefaultPreset),
|
||||
};
|
||||
let raw: LayoutEnvelope = serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid workspace envelope"))?;
|
||||
let mut envelope = stored.project_envelope(context.registry, &raw.layout.workspace)?;
|
||||
envelope.layout.workspace = p.workspace;
|
||||
restore_quarantine(&mut envelope, context.registry)?;
|
||||
let incoming_recovery = stored.rejected.clone();
|
||||
next.remembered.insert(previous_workspace.clone(), StoredEnvelope::new(¤t, recovery.as_deref(), context.registry)?);
|
||||
let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() };
|
||||
let (state, _) = stage_current(context, &state, &action, &envelope, incoming_recovery, next)?;
|
||||
value(wire::WorkspaceReply { previous_workspace, source, state })
|
||||
}
|
||||
command => {
|
||||
let mutation = lower(command, &state, context.registry, context.web)?;
|
||||
let action = LayoutAction::Apply { expected_revision: Some(state.revision), mutations: vec![mutation] };
|
||||
value(stage_current(context, &state, &action, ¤t, recovery, next)?.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn merge_recovery(first: Option<Arc<[u8]>>, second: Option<Arc<[u8]>>) -> PanelResult<Option<Arc<[u8]>>> {
|
||||
if first.is_some() && second.is_some() && first != second {
|
||||
return Err(error(Rule::DuplicateId, "rejected recovery intent collision"));
|
||||
}
|
||||
Ok(first.or(second))
|
||||
}
|
||||
fn value(value: impl serde::Serialize) -> PanelResult<Value> {
|
||||
serde_json::to_value(value).map_err(|_| error(Rule::Schema, "cannot encode committed layout reply"))
|
||||
}
|
||||
pub fn execute(id: &str, params: &Value, context: &mut PanelCommandContext<'_>) -> PanelResult<Value> {
|
||||
execute_command(parse_command(id, params)?, context)
|
||||
}
|
||||
|
||||
/// A private transaction planner reuses the common executor and the LIVE sink's
|
||||
/// pure projection. It owns no reducer or LayoutService and cannot publish live
|
||||
/// effects. Only the final guarded action and prepared catalogue are published.
|
||||
struct PlanningSink<'a> {
|
||||
authoritative: &'a dyn ActionSink,
|
||||
state: LayoutReply,
|
||||
mutations: Vec<Mutation>,
|
||||
replaced: bool,
|
||||
}
|
||||
impl ActionSink for PlanningSink<'_> {
|
||||
fn inspect(&self) -> LayoutReply {
|
||||
self.state.clone()
|
||||
}
|
||||
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
|
||||
match action {
|
||||
LayoutAction::Inspect => Ok(self.state.layout.clone()),
|
||||
LayoutAction::Replace { expected_revision, layout } => {
|
||||
revision(expected_revision, &self.state)?;
|
||||
if !self.mutations.is_empty() {
|
||||
return Err(error(
|
||||
Rule::Capability,
|
||||
"atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false",
|
||||
));
|
||||
}
|
||||
self.authoritative.project(LayoutAction::Replace { expected_revision: Some(self.state.revision), layout })
|
||||
}
|
||||
LayoutAction::Apply { expected_revision, mutations } => {
|
||||
revision(expected_revision, &self.state)?;
|
||||
if self.replaced {
|
||||
return Err(error(
|
||||
Rule::Capability,
|
||||
"atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false",
|
||||
));
|
||||
}
|
||||
if self.mutations.len().saturating_add(mutations.len()) > MAX_MUTATIONS {
|
||||
return Err(error(Rule::CollectionLimit, "layout batch mutation cap"));
|
||||
}
|
||||
let mut combined = self.mutations.clone();
|
||||
combined.extend(mutations);
|
||||
self.authoritative.project(LayoutAction::Apply { expected_revision: Some(self.state.revision), mutations: combined })
|
||||
}
|
||||
}
|
||||
}
|
||||
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
let layout = self.project(action.clone())?;
|
||||
match action {
|
||||
LayoutAction::Apply { mutations, .. } => self.mutations.extend(mutations),
|
||||
LayoutAction::Replace { .. } => {
|
||||
self.replaced = true;
|
||||
self.state.interaction = InteractionState::default();
|
||||
}
|
||||
LayoutAction::Inspect => {}
|
||||
}
|
||||
self.state.layout = layout;
|
||||
Ok(self.state.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure structural preflight, usable before application context publication.
|
||||
/// Same-workspace selection remains a no-op and may accompany mutations.
|
||||
pub fn preflight_batch(steps: &[Value], workspace: &WorkspaceId) -> PanelResult<()> {
|
||||
if steps.is_empty() || steps.len() > MAX_MUTATIONS {
|
||||
return Err(error(Rule::CollectionLimit, "layout batch requires 1..64 steps"));
|
||||
}
|
||||
let mut selected = workspace.clone();
|
||||
let mut replacement = false;
|
||||
let mut mutation = false;
|
||||
for step in steps {
|
||||
let id =
|
||||
step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or_else(|| error(Rule::Schema, "batch command required"))?;
|
||||
let empty = json!({});
|
||||
match parse_command(id, step.get("params").unwrap_or(&empty))? {
|
||||
PanelCommand::List | PanelCommand::Get | PanelCommand::Save(_) => {}
|
||||
PanelCommand::Apply(_) | PanelCommand::Reset(_) => replacement = true,
|
||||
PanelCommand::Workspace(params) => {
|
||||
replacement |= params.workspace != selected;
|
||||
selected = params.workspace;
|
||||
}
|
||||
_ => mutation = true,
|
||||
}
|
||||
}
|
||||
if replacement && mutation {
|
||||
return Err(error(Rule::Capability, "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Atomic batches use one Apply or Replace and one catalogue/native/controller
|
||||
/// preflight. Explicit lifecycle intent is never flattened into a replacement.
|
||||
pub fn execute_batch(steps: &[Value], context: &mut PanelCommandContext<'_>) -> PanelResult<Value> {
|
||||
if steps.is_empty() || steps.len() > MAX_MUTATIONS {
|
||||
return Err(error(Rule::CollectionLimit, "layout batch requires 1..64 steps"));
|
||||
}
|
||||
let state = context.sink.inspect();
|
||||
preflight_batch(steps, &state.layout.workspace)?;
|
||||
let mut planned = InMemoryCatalogue { state: context.catalogue.state().clone(), fail_stage: false };
|
||||
let mut sink = PlanningSink { authoritative: &*context.sink, state: state.clone(), mutations: Vec::new(), replaced: false };
|
||||
let mut rows = Vec::new();
|
||||
for step in steps {
|
||||
let id =
|
||||
step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or_else(|| error(Rule::Schema, "batch command required"))?;
|
||||
let id = crate::find_command(id).map(|spec| spec.id).ok_or_else(|| error(Rule::MissingTarget, "batch command not registered"))?;
|
||||
let empty = json!({});
|
||||
let result = execute(
|
||||
id,
|
||||
step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty),
|
||||
&mut PanelCommandContext { sink: &mut sink, registry: context.registry, catalogue: &mut planned, web: context.web },
|
||||
)?;
|
||||
rows.push((id, result));
|
||||
}
|
||||
let action = if sink.replaced {
|
||||
LayoutAction::Replace { expected_revision: Some(state.revision), layout: sink.state.layout.clone() }
|
||||
} else if !sink.mutations.is_empty() {
|
||||
LayoutAction::Apply { expected_revision: Some(state.revision), mutations: sink.mutations.clone() }
|
||||
} else {
|
||||
LayoutAction::Inspect
|
||||
};
|
||||
let planned_state = sink.state.clone();
|
||||
let changed = planned.state != *context.catalogue.state() || action != LayoutAction::Inspect;
|
||||
// Release the immutable authoritative borrow before committing through it.
|
||||
drop(sink);
|
||||
let committed = if changed {
|
||||
let (envelope, recovery) = current_envelope(&planned.state, &planned_state, context.registry)?;
|
||||
stage_current(context, &state, &action, &envelope, recovery, planned.state)?.0
|
||||
} else {
|
||||
context.sink.inspect()
|
||||
};
|
||||
let mut results = Vec::new();
|
||||
for (id, mut result) in rows {
|
||||
match id {
|
||||
"panel.list" => result = value(wire::ListReply { state: committed.clone(), kinds: context.registry.specs().cloned().collect() })?,
|
||||
"layout.get" => result = value(wire::GetReply { state: committed.clone(), workspaces: context.catalogue.state().summaries() })?,
|
||||
"layout.save" | "layout.workspace.select" => result["state"] = value(committed.clone())?,
|
||||
_ => result = value(committed.clone())?,
|
||||
}
|
||||
results.push(result);
|
||||
}
|
||||
Ok(json!({"completed":steps.len(),"results":results,"undone":0}))
|
||||
}
|
||||
|
||||
/// Transport-compatible error text retains the structured foundation identity.
|
||||
/// Control/MCP also expose this as panel_error beside their usual error string.
|
||||
pub fn error_text(reason: PanelError) -> String {
|
||||
serde_json::to_string(&reason).unwrap_or_else(|_| "{\"rule\":\"schema\",\"detail\":\"layout error encoding failed\"}".into())
|
||||
}
|
||||
pub fn structured_error(text: &str) -> Option<Value> {
|
||||
if text.len() > 4096 {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_str::<PanelError>(text).ok().and_then(|reason| value(error(reason.rule, reason.detail)).ok())
|
||||
}
|
||||
|
||||
pub fn sequential_failure(index: usize, command: Option<&str>, text: String, results: Vec<Value>) -> Value {
|
||||
let mut failed = json!({"index":index,"command":command,"error":text});
|
||||
if let Some(reason) = structured_error(&text) {
|
||||
failed["panel_error"] = reason;
|
||||
}
|
||||
json!({"completed":index,"results":results,"failed":failed,"undone":0,"rolled_back":false})
|
||||
}
|
||||
|
||||
/// One owned, persistent in-memory headless backend, outside Session. No kinds,
|
||||
/// presets or workspace descriptors are invented. Peers/fixtures may inject them.
|
||||
pub struct InMemoryPanelBackend {
|
||||
pub service: LayoutService,
|
||||
pub catalogue: InMemoryCatalogue,
|
||||
}
|
||||
|
||||
/// In-process layout has no native realization. Even a supplied service with
|
||||
/// native flags cannot make this adapter claim that it opened an OS window.
|
||||
struct HeadlessSink<'a>(&'a mut LayoutService);
|
||||
impl ActionSink for HeadlessSink<'_> {
|
||||
fn inspect(&self) -> LayoutReply {
|
||||
let mut state = self.0.inspect();
|
||||
state.capabilities.native_windows = false;
|
||||
state.capabilities.max_native_hosts = 0;
|
||||
state
|
||||
}
|
||||
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
|
||||
let prepared = self.0.prepare(action)?;
|
||||
if prepared.effects().iter().any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. })) {
|
||||
return Err(error(Rule::Capability, "headless has no native host adapter"));
|
||||
}
|
||||
Ok(prepared.layout().clone())
|
||||
}
|
||||
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
self.project(action.clone())?;
|
||||
let mut state = self.0.dispatch(action)?;
|
||||
state.capabilities.native_windows = false;
|
||||
state.capabilities.max_native_hosts = 0;
|
||||
Ok(state)
|
||||
}
|
||||
}
|
||||
impl InMemoryPanelBackend {
|
||||
pub fn new(service: LayoutService, catalogue: InMemoryCatalogue) -> Self {
|
||||
Self { service, catalogue }
|
||||
}
|
||||
pub fn empty() -> PanelResult<Self> {
|
||||
Ok(Self::new(
|
||||
LayoutService::new(PanelRegistry::default(), Layout::empty(WorkspaceId::new("headless")?), HostCapabilities::default())?,
|
||||
InMemoryCatalogue::default(),
|
||||
))
|
||||
}
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> PanelResult<Value> {
|
||||
let registry = self.service.registry().clone();
|
||||
execute(
|
||||
id,
|
||||
params,
|
||||
&mut PanelCommandContext { sink: &mut HeadlessSink(&mut self.service), registry: ®istry, catalogue: &mut self.catalogue, web: false },
|
||||
)
|
||||
}
|
||||
pub fn batch(&mut self, steps: &[Value]) -> PanelResult<Value> {
|
||||
let registry = self.service.registry().clone();
|
||||
execute_batch(
|
||||
steps,
|
||||
&mut PanelCommandContext { sink: &mut HeadlessSink(&mut self.service), registry: ®istry, catalogue: &mut self.catalogue, web: false },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Small versioned storage seam for application preferences, not design files.
|
||||
//! Length-prefixed records keep arbitrary recovery bytes exact and bound every
|
||||
//! allocation before copying. Envelopes retain their foundation JSON limits.
|
||||
use super::*;
|
||||
|
||||
const HEADER: &[u8] = b"SCPCAT01";
|
||||
|
||||
impl CatalogueState {
|
||||
/// Export all immutable registrations, mutable users and remembered full
|
||||
/// envelopes. No storage, live action, selection or Session is touched.
|
||||
pub fn export(&self) -> PanelResult<Vec<u8>> {
|
||||
self.validate()?;
|
||||
let mut writer = Writer(Vec::new());
|
||||
writer.put(HEADER)?;
|
||||
for presets in [&self.builtins, &self.users] {
|
||||
writer.count(presets.len())?;
|
||||
for (name, record) in presets {
|
||||
writer.bytes(name.as_bytes())?;
|
||||
writer.record(record)?;
|
||||
}
|
||||
}
|
||||
writer.count(self.workspaces.len())?;
|
||||
for descriptor in self.workspaces.values() {
|
||||
writer.bytes(descriptor.id.0.as_bytes())?;
|
||||
writer.bytes(descriptor.title_key.as_bytes())?;
|
||||
writer.bytes(descriptor.default_preset.as_bytes())?;
|
||||
}
|
||||
writer.count(self.remembered.len())?;
|
||||
for (workspace, record) in &self.remembered {
|
||||
writer.bytes(workspace.0.as_bytes())?;
|
||||
writer.record(record)?;
|
||||
}
|
||||
Ok(writer.0)
|
||||
}
|
||||
|
||||
/// Build a private validated candidate. Counts, duplicate identities,
|
||||
/// names/IDs, envelope node/depth/byte bounds, rejected recovery and total
|
||||
/// budgets are checked before the result can be published by any catalogue.
|
||||
pub fn hydrate(bytes: &[u8], registry: &PanelRegistry) -> PanelResult<Self> {
|
||||
if bytes.len() > MAX_CATALOGUE_SNAPSHOT_BYTES {
|
||||
return Err(error(Rule::CollectionLimit, "catalogue snapshot byte cap"));
|
||||
}
|
||||
let mut reader = Reader { bytes, at: 0 };
|
||||
if reader.take(HEADER.len())? != HEADER {
|
||||
return Err(error(Rule::Version, "unsupported catalogue snapshot"));
|
||||
}
|
||||
let mut next = Self::default();
|
||||
for builtin in [true, false] {
|
||||
let count = reader.count(MAX_USER_PRESETS)?;
|
||||
for _ in 0..count {
|
||||
let name = reader.text(256)?;
|
||||
if preset_name(&name)? != name {
|
||||
return Err(error(Rule::Schema, "stored preset name is not normalised"));
|
||||
}
|
||||
if next.builtins.contains_key(&name) || next.users.contains_key(&name) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate stored preset identity"));
|
||||
}
|
||||
let record = reader.record(registry)?;
|
||||
if builtin {
|
||||
next.builtins.insert(name, record);
|
||||
} else {
|
||||
next.users.insert(name, record);
|
||||
}
|
||||
}
|
||||
}
|
||||
for _ in 0..reader.count(MAX_WORKSPACES)? {
|
||||
let id = WorkspaceId::new(reader.text(MAX_ID_BYTES)?)?;
|
||||
let title_key = reader.text(MAX_ID_BYTES)?;
|
||||
valid_id(&title_key)?;
|
||||
let default_preset = reader.text(256)?;
|
||||
if next.workspaces.contains_key(&id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate stored workspace identity"));
|
||||
}
|
||||
next.workspaces.insert(id.clone(), WorkspaceDescriptor { id, title_key, default_preset });
|
||||
}
|
||||
for _ in 0..reader.count(MAX_WORKSPACES)? {
|
||||
let workspace = WorkspaceId::new(reader.text(MAX_ID_BYTES)?)?;
|
||||
if next.remembered.contains_key(&workspace) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate remembered workspace identity"));
|
||||
}
|
||||
let record = reader.record(registry)?;
|
||||
// A remembered record belongs to its key, unlike a reusable preset.
|
||||
record.envelope(registry, &workspace)?;
|
||||
next.remembered.insert(workspace, record);
|
||||
}
|
||||
if reader.at != bytes.len() {
|
||||
return Err(error(Rule::Schema, "trailing catalogue snapshot data"));
|
||||
}
|
||||
next.validate()?;
|
||||
Ok(next)
|
||||
}
|
||||
}
|
||||
|
||||
struct Writer(Vec<u8>);
|
||||
impl Writer {
|
||||
fn put(&mut self, bytes: &[u8]) -> PanelResult<()> {
|
||||
if self.0.len().saturating_add(bytes.len()) > MAX_CATALOGUE_SNAPSHOT_BYTES {
|
||||
return Err(error(Rule::CollectionLimit, "catalogue snapshot byte cap"));
|
||||
}
|
||||
self.0.extend_from_slice(bytes);
|
||||
Ok(())
|
||||
}
|
||||
fn count(&mut self, count: usize) -> PanelResult<()> {
|
||||
let count = u32::try_from(count).map_err(|_| error(Rule::CollectionLimit, "catalogue framing cap"))?;
|
||||
self.put(&count.to_le_bytes())
|
||||
}
|
||||
fn bytes(&mut self, bytes: &[u8]) -> PanelResult<()> {
|
||||
self.count(bytes.len())?;
|
||||
self.put(bytes)
|
||||
}
|
||||
fn record(&mut self, record: &StoredEnvelope) -> PanelResult<()> {
|
||||
self.bytes(record.bytes())?;
|
||||
match record.rejected() {
|
||||
Some(rejected) => {
|
||||
self.put(&[1])?;
|
||||
self.bytes(rejected)
|
||||
}
|
||||
None => self.put(&[0]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
bytes: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
impl<'a> Reader<'a> {
|
||||
fn take(&mut self, count: usize) -> PanelResult<&'a [u8]> {
|
||||
let end = self.at.checked_add(count).ok_or_else(|| error(Rule::CollectionLimit, "catalogue framing overflow"))?;
|
||||
let bytes = self.bytes.get(self.at..end).ok_or_else(|| error(Rule::Schema, "truncated catalogue snapshot"))?;
|
||||
self.at = end;
|
||||
Ok(bytes)
|
||||
}
|
||||
fn count(&mut self, max: usize) -> PanelResult<usize> {
|
||||
let raw = <[u8; 4]>::try_from(self.take(4)?).map_err(|_| error(Rule::Schema, "invalid catalogue length"))?;
|
||||
let count = usize::try_from(u32::from_le_bytes(raw)).map_err(|_| error(Rule::CollectionLimit, "catalogue length overflow"))?;
|
||||
if count > max {
|
||||
return Err(error(Rule::CollectionLimit, "catalogue record/count cap"));
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
fn bytes(&mut self, max: usize) -> PanelResult<&'a [u8]> {
|
||||
let count = self.count(max)?;
|
||||
self.take(count)
|
||||
}
|
||||
fn text(&mut self, max: usize) -> PanelResult<String> {
|
||||
std::str::from_utf8(self.bytes(max)?).map(str::to_owned).map_err(|_| error(Rule::Schema, "invalid catalogue UTF-8"))
|
||||
}
|
||||
fn record(&mut self, registry: &PanelRegistry) -> PanelResult<StoredEnvelope> {
|
||||
let bytes = self.bytes(MAX_ENVELOPE_BYTES)?;
|
||||
let rejected = match self.take(1)? {
|
||||
[0] => None,
|
||||
[1] => Some(self.bytes(MAX_ENVELOPE_BYTES)?),
|
||||
_ => return Err(error(Rule::Schema, "invalid catalogue recovery tag")),
|
||||
};
|
||||
StoredEnvelope::from_record(bytes, rejected, registry)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Executable synthetic contracts for independent host/command/persistence work.
|
||||
//! These identifiers are fixtures, never production registrations or UI strings.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::*;
|
||||
|
||||
pub const FIXTURE_LAYOUT_V1: &[u8] = include_bytes!("fixtures/layout-v1.json");
|
||||
|
||||
pub fn synthetic_registry() -> PanelResult<PanelRegistry> {
|
||||
let mut registry = PanelRegistry::default();
|
||||
for (kind, multi, pinned) in
|
||||
[("fixture.application", false, false), ("fixture.editor", false, false), ("fixture.log", true, false), ("fixture.pin", true, true)]
|
||||
{
|
||||
let mut allowed_zones: std::collections::BTreeSet<_> =
|
||||
[Zone::Left, Zone::Right, Zone::Bottom, Zone::Floating, Zone::Window].into_iter().collect();
|
||||
if pinned {
|
||||
allowed_zones.remove(&Zone::Bottom);
|
||||
}
|
||||
registry.register(PanelSpec {
|
||||
kind: PanelKind::new(kind)?,
|
||||
title_key: "ui.panel".into(),
|
||||
icon: "panel".into(),
|
||||
allowed_zones,
|
||||
default_zone: Zone::Left,
|
||||
min_size: Size { width: 160.0, height: 120.0 },
|
||||
default_size: Size { width: 280.0, height: 240.0 },
|
||||
max_size: Size { width: 1200.0, height: 1200.0 },
|
||||
edge_rule: if pinned { EdgeRule::PinOuter } else { EdgeRule::None },
|
||||
surface: PanelSurface::FollowZone,
|
||||
features: PanelFeatures { multi_instance: multi, ..PanelFeatures::default() },
|
||||
})?;
|
||||
}
|
||||
Ok(registry)
|
||||
}
|
||||
|
||||
pub fn fixture_open(kind: &str, instance: &str, section: &str, zone: Zone, index: usize) -> PanelResult<Mutation> {
|
||||
Ok(Mutation::Open {
|
||||
kind: PanelKind::new(kind)?,
|
||||
instance: InstanceId::new(instance)?,
|
||||
destination: Some(Destination::NewSection {
|
||||
section: SectionId::new(section)?,
|
||||
index,
|
||||
location: if zone == Zone::Floating {
|
||||
SectionLocation::Floating { origin: Point { x: 40.0, y: 40.0 } }
|
||||
} else {
|
||||
SectionLocation::Dock { zone }
|
||||
},
|
||||
size: Size { width: 280.0, height: 240.0 },
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fixture_service(native: bool) -> PanelResult<LayoutService> {
|
||||
LayoutService::new(
|
||||
synthetic_registry()?,
|
||||
Layout::empty(WorkspaceId::new("fixture.workspace")?),
|
||||
HostCapabilities { native_windows: native, max_native_hosts: if native { 8 } else { 0 }, persistence: true },
|
||||
)
|
||||
}
|
||||
|
||||
pub fn transaction(mutations: Vec<Mutation>) -> LayoutAction {
|
||||
LayoutAction::Apply { expected_revision: None, mutations }
|
||||
}
|
||||
|
||||
/// Synthetic catalogue shared by command/control/MCP tests; never registered by
|
||||
/// application startup. Two descriptors may deliberately share one default.
|
||||
pub fn fixture_command_catalogue(registry: &PanelRegistry) -> PanelResult<commands::InMemoryCatalogue> {
|
||||
let mut catalogue = commands::InMemoryCatalogue::default();
|
||||
let empty = LayoutEnvelope::new(Layout::empty(WorkspaceId::new("fixture.workspace")?));
|
||||
catalogue.register_builtin("Fixture default", &empty, registry)?;
|
||||
for id in ["fixture.workspace", "fixture.other"] {
|
||||
catalogue.register_workspace(commands::WorkspaceDescriptor {
|
||||
id: WorkspaceId::new(id)?,
|
||||
title_key: "ui.panel".into(),
|
||||
default_preset: "Fixture default".into(),
|
||||
})?;
|
||||
}
|
||||
Ok(catalogue)
|
||||
}
|
||||
|
||||
pub fn fixture_command_backend() -> PanelResult<commands::InMemoryPanelBackend> {
|
||||
let service = fixture_service(false)?;
|
||||
let catalogue = fixture_command_catalogue(service.registry())?;
|
||||
Ok(commands::InMemoryPanelBackend::new(service, catalogue))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FakePersistence {
|
||||
/// Deliberately separate map demonstrates that layout writes own one key.
|
||||
pub unrelated_preferences: BTreeMap<String, String>,
|
||||
pub layouts: BTreeMap<WorkspaceId, Vec<u8>>,
|
||||
pub fail_save: bool,
|
||||
}
|
||||
impl LayoutPersistence for FakePersistence {
|
||||
fn load(&mut self, workspace: &WorkspaceId) -> PanelResult<Option<Vec<u8>>> {
|
||||
valid_id(&workspace.0)?;
|
||||
Ok(self.layouts.get(workspace).cloned())
|
||||
}
|
||||
fn save(&mut self, workspace: &WorkspaceId, envelope: &[u8]) -> PanelResult<()> {
|
||||
valid_id(&workspace.0)?;
|
||||
if envelope.len() > MAX_ENVELOPE_BYTES || (!self.layouts.contains_key(workspace) && self.layouts.len() >= MAX_SECTIONS) {
|
||||
return Err(error(Rule::CollectionLimit, "fake persistence capacity"));
|
||||
}
|
||||
if self.fail_save {
|
||||
return Err(error(Rule::Capability, "synthetic atomic write failure"));
|
||||
}
|
||||
self.layouts.insert(workspace.clone(), envelope.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"format": "solidcraft.panel-layout",
|
||||
"version": 1,
|
||||
"layout": {
|
||||
"version": 1,
|
||||
"workspace": "fixture.workspace",
|
||||
"instances": [
|
||||
{
|
||||
"id": "editor",
|
||||
"kind": "fixture.editor",
|
||||
"requested_open": true,
|
||||
"memory": {
|
||||
"section": "editor-section",
|
||||
"location": { "type": "dock", "zone": "left" },
|
||||
"section_index": 0,
|
||||
"tab_index": 0,
|
||||
"size": { "width": 280.0, "height": 240.0 },
|
||||
"collapsed": false
|
||||
}
|
||||
}
|
||||
],
|
||||
"sections": [
|
||||
{
|
||||
"id": "editor-section",
|
||||
"location": { "type": "dock", "zone": "left" },
|
||||
"tabs": ["editor"],
|
||||
"active": "editor",
|
||||
"size": { "width": 280.0, "height": 240.0 },
|
||||
"collapsed": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"quarantine": [],
|
||||
"section_snapshots": {},
|
||||
"section_order": ["editor-section"],
|
||||
"retained_data": {}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct Point {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
}
|
||||
impl Point {
|
||||
pub fn validate(self) -> PanelResult<()> {
|
||||
if !self.x.is_finite() || !self.y.is_finite() || self.x.abs() > MAX_LOGICAL || self.y.abs() > MAX_LOGICAL {
|
||||
return Err(error(Rule::Bounds, "invalid logical position"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct LogicalRect {
|
||||
pub origin: Point,
|
||||
pub size: Size,
|
||||
}
|
||||
impl LogicalRect {
|
||||
pub fn validate(self) -> PanelResult<()> {
|
||||
self.origin.validate()?;
|
||||
self.size.validate()?;
|
||||
if (self.origin.x + self.size.width).abs() > MAX_LOGICAL || (self.origin.y + self.size.height).abs() > MAX_LOGICAL {
|
||||
return Err(error(Rule::Bounds, "logical rectangle extent out of range"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn contains(self, p: Point) -> bool {
|
||||
p.x >= self.origin.x && p.y >= self.origin.y && p.x <= self.origin.x + self.size.width && p.y <= self.origin.y + self.size.height
|
||||
}
|
||||
pub fn contains_rect(self, other: Self) -> bool {
|
||||
self.contains(other.origin) && self.contains(Point { x: other.origin.x + other.size.width, y: other.origin.y + other.size.height })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Flow {
|
||||
Tall,
|
||||
Wide,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SizeClass {
|
||||
Compact,
|
||||
Regular,
|
||||
Wide,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Direction {
|
||||
Ltr,
|
||||
Rtl,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PhysicalEdge {
|
||||
Left,
|
||||
Right,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
pub fn edge(self, zone: Zone) -> PanelResult<PhysicalEdge> {
|
||||
match (self, zone) {
|
||||
(Self::Ltr, Zone::Left) | (Self::Rtl, Zone::Right) => Ok(PhysicalEdge::Left),
|
||||
(Self::Ltr, Zone::Right) | (Self::Rtl, Zone::Left) => Ok(PhysicalEdge::Right),
|
||||
(_, Zone::Bottom) => Ok(PhysicalEdge::Bottom),
|
||||
_ => Err(error(Rule::Placement, "free host has no logical dock edge")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Usable logical units: egui applies scale exactly once, outside this contract.
|
||||
/// Free/native flow starts at aspect 1, switches Tall->Wide above 1.1, Wide->Tall
|
||||
/// below 0.9, and retains the previous flow inside that band.
|
||||
pub fn responsive(zone: Zone, usable: Size, previous: Option<Flow>) -> PanelResult<(Flow, SizeClass)> {
|
||||
usable.validate()?;
|
||||
let aspect = usable.width / usable.height;
|
||||
let flow = match zone {
|
||||
Zone::Left | Zone::Right => Flow::Tall,
|
||||
Zone::Bottom => Flow::Wide,
|
||||
Zone::Floating | Zone::Window => match previous {
|
||||
Some(Flow::Tall) if aspect <= 1.1 => Flow::Tall,
|
||||
Some(Flow::Wide) if aspect >= 0.9 => Flow::Wide,
|
||||
_ if aspect >= 1.0 => Flow::Wide,
|
||||
_ => Flow::Tall,
|
||||
},
|
||||
};
|
||||
let shorter = usable.width.min(usable.height);
|
||||
let class = if shorter < 240.0 {
|
||||
SizeClass::Compact
|
||||
} else if shorter <= 480.0 {
|
||||
SizeClass::Regular
|
||||
} else {
|
||||
SizeClass::Wide
|
||||
};
|
||||
Ok((flow, class))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InputRole {
|
||||
Surface,
|
||||
Header,
|
||||
Tab,
|
||||
Sash,
|
||||
Action,
|
||||
Rail,
|
||||
Overlay,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct InputRegion {
|
||||
pub control: ControlId,
|
||||
pub role: InputRole,
|
||||
pub bounds: LogicalRect,
|
||||
pub keyboard_focusable: bool,
|
||||
/// Translation key or a runtime title resolved by the host.
|
||||
pub accessible_name: String,
|
||||
}
|
||||
impl InputRegion {
|
||||
pub fn validate(&self) -> PanelResult<()> {
|
||||
valid_id(&self.control.0)?;
|
||||
self.bounds.validate()?;
|
||||
if self.accessible_name.is_empty() || self.accessible_name.len() > 256 {
|
||||
return Err(error(Rule::Bounds, "accessible name requires 1..256 bytes"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Host-resolved geometry has separate outer, body, paint and input bounds. No
|
||||
/// transparent/full-window input shield is implied by an overlay surface.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ResolvedPanel {
|
||||
pub instance: InstanceId,
|
||||
pub section: SectionId,
|
||||
pub zone: Zone,
|
||||
pub outer: LogicalRect,
|
||||
pub body: LogicalRect,
|
||||
pub painted: Vec<LogicalRect>,
|
||||
pub input: Vec<InputRegion>,
|
||||
}
|
||||
impl ResolvedPanel {
|
||||
pub fn validate(&self) -> PanelResult<()> {
|
||||
valid_id(&self.instance.0)?;
|
||||
valid_id(&self.section.0)?;
|
||||
self.outer.validate()?;
|
||||
self.body.validate()?;
|
||||
if !self.outer.contains_rect(self.body) {
|
||||
return Err(error(Rule::Bounds, "usable body outside outer host"));
|
||||
}
|
||||
if self.painted.is_empty() || self.painted.len() > MAX_TABS || self.input.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "resolved region count"));
|
||||
}
|
||||
for rect in &self.painted {
|
||||
rect.validate()?;
|
||||
if !self.outer.contains_rect(*rect) {
|
||||
return Err(error(Rule::Bounds, "paint outside host"));
|
||||
}
|
||||
}
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
for region in &self.input {
|
||||
region.validate()?;
|
||||
if !ids.insert(®ion.control) {
|
||||
return Err(error(Rule::DuplicateId, "semantic control id repeated"));
|
||||
}
|
||||
if !self.painted.iter().any(|r| r.contains_rect(region.bounds)) {
|
||||
return Err(error(Rule::Bounds, "input must be contained in painted area"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn consumes_pointer(&self, at: Point) -> bool {
|
||||
self.input.iter().any(|r| r.bounds.contains(at))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UnpresentedReason {
|
||||
MinimumOverflow,
|
||||
Unavailable,
|
||||
NativeUnsupported,
|
||||
Collapsed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct UnpresentedSection {
|
||||
pub section: SectionId,
|
||||
pub reason: UnpresentedReason,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ResolvedLayout {
|
||||
pub panels: Vec<ResolvedPanel>,
|
||||
/// Accessible rail controls are chrome, never sub-minimum content bodies.
|
||||
pub rails: Vec<InputRegion>,
|
||||
pub unpresented: Vec<UnpresentedSection>,
|
||||
}
|
||||
impl ResolvedLayout {
|
||||
pub fn validate(&self) -> PanelResult<()> {
|
||||
if self.panels.len() > MAX_SECTIONS || self.rails.len() > MAX_SECTIONS || self.unpresented.len() > MAX_SECTIONS {
|
||||
return Err(error(Rule::CollectionLimit, "resolved layout cap"));
|
||||
}
|
||||
let mut instances = std::collections::BTreeSet::new();
|
||||
let mut sections = std::collections::BTreeSet::new();
|
||||
let mut rails = std::collections::BTreeSet::new();
|
||||
for panel in &self.panels {
|
||||
panel.validate()?;
|
||||
if !instances.insert(&panel.instance) || !sections.insert(&panel.section) {
|
||||
return Err(error(Rule::ExactlyOnce, "duplicate resolved instance/section"));
|
||||
}
|
||||
}
|
||||
for rail in &self.rails {
|
||||
rail.validate()?;
|
||||
if rail.role != InputRole::Rail || !rails.insert(&rail.control) {
|
||||
return Err(error(Rule::DuplicateId, "invalid or duplicate rail control"));
|
||||
}
|
||||
}
|
||||
for record in &self.unpresented {
|
||||
valid_id(&record.section.0)?;
|
||||
if !sections.insert(&record.section) {
|
||||
return Err(error(Rule::ExactlyOnce, "section both presented/unpresented or duplicated"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference geometry for synthetic mounts. Production docking owns its richer
|
||||
/// resolver; both return the same meaningful geometry contract. No layout writes.
|
||||
pub fn resolve_geometry(service: &LayoutService, capacity: LogicalRect, direction: Direction, chrome: f32) -> PanelResult<ResolvedLayout> {
|
||||
capacity.validate()?;
|
||||
if !chrome.is_finite() || chrome < 0.0 || chrome > 256.0 {
|
||||
return Err(error(Rule::Bounds, "invalid header/footer chrome extent"));
|
||||
}
|
||||
let mut result = ResolvedLayout::default();
|
||||
let mut left = capacity.origin.x;
|
||||
let mut right = capacity.origin.x + capacity.size.width;
|
||||
let mut bottom = capacity.origin.y + capacity.size.height;
|
||||
let mut left_y = capacity.origin.y;
|
||||
let mut right_y = capacity.origin.y;
|
||||
let mut bottom_x = capacity.origin.x;
|
||||
let mut rail_y = capacity.origin.y;
|
||||
let mut occupied: Vec<LogicalRect> = Vec::new();
|
||||
for section in &service.layout().sections {
|
||||
let id = §ion.active;
|
||||
let zone = section.location.zone();
|
||||
let peek = &service.interaction().peek;
|
||||
let active = peek.as_ref().filter(|p| section.tabs.contains(p)).unwrap_or(id);
|
||||
let available = service.availability(active) == Availability::Available;
|
||||
let reason = if !available {
|
||||
Some(UnpresentedReason::Unavailable)
|
||||
} else if zone == Zone::Window && !service.capabilities().native_windows {
|
||||
Some(UnpresentedReason::NativeUnsupported)
|
||||
} else if section.collapsed && peek.as_ref() != Some(active) {
|
||||
Some(UnpresentedReason::Collapsed)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(reason) = reason {
|
||||
result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: reason.clone() });
|
||||
if reason == UnpresentedReason::Collapsed {
|
||||
append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let size = section.size;
|
||||
let origin = match §ion.location {
|
||||
SectionLocation::Floating { origin } | SectionLocation::Window { origin, .. } => *origin,
|
||||
SectionLocation::Dock { zone } => match direction.edge(*zone)? {
|
||||
PhysicalEdge::Left => Point { x: left, y: left_y },
|
||||
PhysicalEdge::Right => Point { x: right - size.width, y: right_y },
|
||||
PhysicalEdge::Bottom => Point { x: bottom_x, y: bottom - size.height },
|
||||
},
|
||||
};
|
||||
let outer = LogicalRect { origin, size };
|
||||
let overlaps_dock = zone.docked()
|
||||
&& !section.collapsed
|
||||
&& occupied.iter().any(|r| {
|
||||
r.origin.x < origin.x + size.width
|
||||
&& origin.x < r.origin.x + r.size.width
|
||||
&& r.origin.y < origin.y + size.height
|
||||
&& origin.y < r.origin.y + r.size.height
|
||||
});
|
||||
if !capacity.contains_rect(outer) || size.height <= chrome || overlaps_dock {
|
||||
result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: UnpresentedReason::MinimumOverflow });
|
||||
append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?;
|
||||
continue;
|
||||
}
|
||||
if zone.docked() && !section.collapsed {
|
||||
occupied.push(outer);
|
||||
match direction.edge(zone)? {
|
||||
PhysicalEdge::Left => {
|
||||
left_y += size.height;
|
||||
left = left.max(origin.x);
|
||||
}
|
||||
PhysicalEdge::Right => {
|
||||
right_y += size.height;
|
||||
right = right.min(origin.x + size.width);
|
||||
}
|
||||
PhysicalEdge::Bottom => {
|
||||
bottom_x += size.width;
|
||||
bottom = bottom.min(origin.y + size.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
let body =
|
||||
LogicalRect { origin: Point { x: origin.x, y: origin.y + chrome / 2.0 }, size: Size { width: size.width, height: size.height - chrome } };
|
||||
let panel = ResolvedPanel {
|
||||
instance: active.clone(),
|
||||
section: section.id.clone(),
|
||||
zone,
|
||||
outer,
|
||||
body,
|
||||
painted: vec![outer],
|
||||
input: vec![InputRegion {
|
||||
control: ControlId::new(format!("host.{}", section.id.0).chars().take(MAX_ID_BYTES).collect::<String>())?,
|
||||
role: InputRole::Surface,
|
||||
bounds: outer,
|
||||
keyboard_focusable: true,
|
||||
accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(),
|
||||
}],
|
||||
};
|
||||
panel.validate()?;
|
||||
result.panels.push(panel);
|
||||
}
|
||||
result.validate()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn append_rail(
|
||||
result: &mut ResolvedLayout,
|
||||
service: &LayoutService,
|
||||
active: &InstanceId,
|
||||
capacity: LogicalRect,
|
||||
direction: Direction,
|
||||
zone: Zone,
|
||||
rail_y: &mut f32,
|
||||
) -> PanelResult<()> {
|
||||
// Rails are bounded chrome, not below-minimum content bodies. If every entry
|
||||
// cannot fit, the complete unpresented list remains available to a host's rail.
|
||||
let width = 32.0_f32.min(capacity.size.width);
|
||||
let height = 32.0_f32.min(capacity.size.height);
|
||||
if *rail_y + height <= capacity.origin.y + capacity.size.height {
|
||||
let right = direction.edge(if zone.docked() { zone } else { Zone::Left })? == PhysicalEdge::Right;
|
||||
let x = if right { capacity.origin.x + capacity.size.width - width } else { capacity.origin.x };
|
||||
result.rails.push(InputRegion {
|
||||
control: ControlId::new(format!("rail.{}", result.rails.len()))?,
|
||||
role: InputRole::Rail,
|
||||
bounds: LogicalRect { origin: Point { x, y: *rail_y }, size: Size { width, height } },
|
||||
keyboard_focusable: true,
|
||||
accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(),
|
||||
});
|
||||
*rail_y += height;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Surfaces child resolves theme tokens. Invalid authored pairs retain raw import
|
||||
/// intent and last good tokens; they cannot be reported as accessible by recolouring.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "state", rename_all = "snake_case")]
|
||||
pub enum ContrastOutcome {
|
||||
Readable { effective_background_alpha: f32 },
|
||||
RetainReadableFallback { reason: ContrastFailure },
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ContrastFailure {
|
||||
InvalidTokens,
|
||||
UnreadableAtFullOpacity,
|
||||
}
|
||||
|
||||
impl ContrastOutcome {
|
||||
/// The surfaces adapter proves readability. This boundary enforces finite
|
||||
/// alpha and the policy that effective background alpha may only increase.
|
||||
pub fn validate(&self, requested_alpha: f32) -> PanelResult<()> {
|
||||
if !requested_alpha.is_finite() || !(0.0..=1.0).contains(&requested_alpha) {
|
||||
return Err(error(Rule::Bounds, "invalid requested background alpha"));
|
||||
}
|
||||
if let Self::Readable { effective_background_alpha } = self
|
||||
&& (!effective_background_alpha.is_finite() || *effective_background_alpha < requested_alpha || *effective_background_alpha > 1.0)
|
||||
{
|
||||
return Err(error(Rule::Bounds, "resolved background alpha must be finite and only raised"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared surface precedence: Opaque wins, then explicit Translucent, then zone
|
||||
/// default (bottom/native opaque, sides/free translucent). No colour implementation.
|
||||
pub fn group_surface<'a>(zone: Zone, specs: impl IntoIterator<Item = &'a PanelSpec>) -> PanelSurface {
|
||||
let mut translucent = false;
|
||||
for spec in specs {
|
||||
if spec.surface == PanelSurface::Opaque {
|
||||
return PanelSurface::Opaque;
|
||||
}
|
||||
translucent |= spec.surface == PanelSurface::Translucent;
|
||||
}
|
||||
if translucent || !matches!(zone, Zone::Bottom | Zone::Window) { PanelSurface::Translucent } else { PanelSurface::Opaque }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Application/workspace layout, deliberately independent of Session and egui.
|
||||
//! Consumers must use `LayoutService` (or its `ActionSink`) for committed mutations.
|
||||
//! The serde values are wire data, not proof of validity; see `validate` and `decode`.
|
||||
pub mod commands;
|
||||
mod fixtures;
|
||||
mod geometry;
|
||||
mod model;
|
||||
mod persistence;
|
||||
mod reducer;
|
||||
|
||||
pub use fixtures::*;
|
||||
pub use geometry::*;
|
||||
pub use model::*;
|
||||
pub use persistence::*;
|
||||
pub use reducer::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,480 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::geometry::Point;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const LAYOUT_VERSION: u32 = 1;
|
||||
pub const PANEL_API_VERSION: u32 = 1;
|
||||
pub const MAX_ID_BYTES: usize = 64;
|
||||
pub const MAX_INSTANCES: usize = 128;
|
||||
pub const MAX_SECTIONS: usize = 64;
|
||||
pub const MAX_TABS: usize = 32;
|
||||
pub const MAX_MUTATIONS: usize = 64;
|
||||
pub const MAX_LOGICAL: f32 = 32_768.0;
|
||||
pub const MAX_ENVELOPE_BYTES: usize = 262_144;
|
||||
|
||||
/// Classic is a permanent compatibility contract; this foundation does not
|
||||
/// select a new preset or migrate existing preferences.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CompatibilityPreset {
|
||||
Classic,
|
||||
}
|
||||
|
||||
/// Stable machine-readable rule names; presentation translates these in the adapter.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Rule {
|
||||
Availability,
|
||||
Bounds,
|
||||
Capability,
|
||||
CollectionLimit,
|
||||
DuplicateId,
|
||||
ExactlyOnce,
|
||||
FeatureDisabled,
|
||||
Id,
|
||||
IncompatibleTabs,
|
||||
Lifecycle,
|
||||
MissingTarget,
|
||||
PinConflict,
|
||||
PinOrder,
|
||||
Placement,
|
||||
Revision,
|
||||
Schema,
|
||||
Version,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, thiserror::Error)]
|
||||
#[error("{rule:?}: {detail}")]
|
||||
pub struct PanelError {
|
||||
pub rule: Rule,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
pub type PanelResult<T> = std::result::Result<T, PanelError>;
|
||||
|
||||
pub fn error(rule: Rule, detail: impl Into<String>) -> PanelError {
|
||||
// Error replies are bounded too; never echo a hostile payload in full.
|
||||
PanelError { rule, detail: detail.into().chars().take(256).collect() }
|
||||
}
|
||||
|
||||
pub fn valid_id(value: &str) -> PanelResult<()> {
|
||||
if value.is_empty() || value.len() > MAX_ID_BYTES || !value.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(&c)) {
|
||||
return Err(error(Rule::Id, "expected a nonempty bounded lowercase identifier"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
macro_rules! identity {
|
||||
($($name:ident),+ $(,)?) => {$ (
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(transparent)]
|
||||
pub struct $name(pub String);
|
||||
impl $name {
|
||||
pub fn new(value: impl Into<String>) -> PanelResult<Self> {
|
||||
let value = value.into();
|
||||
valid_id(&value)?;
|
||||
Ok(Self(value))
|
||||
}
|
||||
}
|
||||
)+};
|
||||
}
|
||||
identity!(PanelKind, InstanceId, SectionId, WorkspaceId, DocumentId, ViewportId, HostId, ControlId);
|
||||
|
||||
/// Leading/trailing logical sides, mirrored by a host for RTL. There is no Top zone.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Zone {
|
||||
Left,
|
||||
Right,
|
||||
Bottom,
|
||||
Floating,
|
||||
Window,
|
||||
}
|
||||
|
||||
impl Zone {
|
||||
pub fn docked(self) -> bool {
|
||||
matches!(self, Self::Left | Self::Right | Self::Bottom)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum EdgeRule {
|
||||
None,
|
||||
PinOuter,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PanelSurface {
|
||||
FollowZone,
|
||||
Opaque,
|
||||
Translucent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct Size {
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
impl Size {
|
||||
pub fn validate(self) -> PanelResult<()> {
|
||||
if !self.width.is_finite()
|
||||
|| !self.height.is_finite()
|
||||
|| self.width <= 0.0
|
||||
|| self.height <= 0.0
|
||||
|| self.width > MAX_LOGICAL
|
||||
|| self.height > MAX_LOGICAL
|
||||
{
|
||||
return Err(error(Rule::Bounds, "outer size must be finite and in (0, 32768] logical units"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn within(self, min: Self, max: Self) -> bool {
|
||||
self.width >= min.width && self.height >= min.height && self.width <= max.width && self.height <= max.height
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct PanelFeatures {
|
||||
pub collapsible: bool,
|
||||
pub closable: bool,
|
||||
pub popout: bool,
|
||||
pub tabbable: bool,
|
||||
pub multi_instance: bool,
|
||||
}
|
||||
|
||||
impl Default for PanelFeatures {
|
||||
fn default() -> Self {
|
||||
Self { collapsible: true, closable: true, popout: true, tabbable: true, multi_instance: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Immutable registration metadata. No callbacks, content state or model references.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct PanelSpec {
|
||||
pub kind: PanelKind,
|
||||
pub title_key: String,
|
||||
pub icon: String,
|
||||
pub allowed_zones: BTreeSet<Zone>,
|
||||
pub default_zone: Zone,
|
||||
pub min_size: Size,
|
||||
pub default_size: Size,
|
||||
pub max_size: Size,
|
||||
pub edge_rule: EdgeRule,
|
||||
pub surface: PanelSurface,
|
||||
pub features: PanelFeatures,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PanelRegistry {
|
||||
specs: BTreeMap<PanelKind, PanelSpec>,
|
||||
}
|
||||
|
||||
impl PanelRegistry {
|
||||
pub fn register(&mut self, spec: PanelSpec) -> PanelResult<()> {
|
||||
valid_id(&spec.kind.0)?;
|
||||
valid_id(&spec.title_key)?;
|
||||
valid_id(&spec.icon)?;
|
||||
spec.min_size.validate()?;
|
||||
spec.max_size.validate()?;
|
||||
spec.default_size.validate()?;
|
||||
if !spec.default_size.within(spec.min_size, spec.max_size) {
|
||||
return Err(error(Rule::Bounds, "min <= default <= max required in both dimensions"));
|
||||
}
|
||||
if !spec.allowed_zones.contains(&Zone::Floating) || !spec.allowed_zones.contains(&spec.default_zone) {
|
||||
return Err(error(Rule::Placement, "Floating and default_zone must be allowed"));
|
||||
}
|
||||
if spec.edge_rule == EdgeRule::PinOuter && spec.allowed_zones.contains(&Zone::Bottom) {
|
||||
return Err(error(Rule::Placement, "PinOuter must exclude Bottom"));
|
||||
}
|
||||
if self.specs.contains_key(&spec.kind) {
|
||||
return Err(error(Rule::DuplicateId, "panel kind already registered"));
|
||||
}
|
||||
if self.specs.len() >= MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "registry full"));
|
||||
}
|
||||
self.specs.insert(spec.kind.clone(), spec);
|
||||
Ok(())
|
||||
}
|
||||
pub fn get(&self, kind: &PanelKind) -> PanelResult<&PanelSpec> {
|
||||
self.specs.get(kind).ok_or_else(|| error(Rule::MissingTarget, "unregistered panel kind"))
|
||||
}
|
||||
pub fn specs(&self) -> impl Iterator<Item = &PanelSpec> {
|
||||
self.specs.values()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum SectionLocation {
|
||||
Dock { zone: Zone },
|
||||
Floating { origin: Point },
|
||||
Window { host: HostId, origin: Point, return_to: DockReturn },
|
||||
}
|
||||
|
||||
impl SectionLocation {
|
||||
pub fn zone(&self) -> Zone {
|
||||
match self {
|
||||
Self::Dock { zone } => *zone,
|
||||
Self::Floating { .. } => Zone::Floating,
|
||||
Self::Window { .. } => Zone::Window,
|
||||
}
|
||||
}
|
||||
pub fn validate(&self) -> PanelResult<()> {
|
||||
match self {
|
||||
Self::Dock { zone } if !zone.docked() => Err(error(Rule::Placement, "dock must name a docked zone")),
|
||||
Self::Dock { .. } => Ok(()),
|
||||
Self::Floating { origin } => origin.validate(),
|
||||
Self::Window { host, origin, return_to } => {
|
||||
valid_id(&host.0)?;
|
||||
origin.validate()?;
|
||||
return_to.validate()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Native return destinations never recursively contain another native host.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct DockReturn {
|
||||
pub zone: Zone,
|
||||
pub index: usize,
|
||||
pub size: Size,
|
||||
pub collapsed: bool,
|
||||
/// Restore a former tab group when it still occupies the recorded dock.
|
||||
/// Missing/reparented groups use the nonrecursive dock fallback above.
|
||||
#[serde(default)]
|
||||
pub join: Option<ReturnTab>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ReturnTab {
|
||||
pub section: SectionId,
|
||||
pub index: usize,
|
||||
}
|
||||
impl DockReturn {
|
||||
pub fn validate(&self) -> PanelResult<()> {
|
||||
if !self.zone.docked() || self.index > MAX_SECTIONS {
|
||||
return Err(error(Rule::Placement, "invalid native return destination"));
|
||||
}
|
||||
self.size.validate()?;
|
||||
if let Some(join) = &self.join {
|
||||
valid_id(&join.section.0)?;
|
||||
if join.index >= MAX_TABS {
|
||||
return Err(error(Rule::Bounds, "native return tab index cap"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct Section {
|
||||
pub id: SectionId,
|
||||
pub location: SectionLocation,
|
||||
pub tabs: Vec<InstanceId>,
|
||||
pub active: InstanceId,
|
||||
/// Desired outer dimensions; overflow resolution never modifies these.
|
||||
pub size: Size,
|
||||
pub collapsed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct PlacementMemory {
|
||||
pub section: SectionId,
|
||||
pub location: SectionLocation,
|
||||
pub section_index: usize,
|
||||
pub tab_index: usize,
|
||||
pub size: Size,
|
||||
pub collapsed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct PanelInstance {
|
||||
pub id: InstanceId,
|
||||
pub kind: PanelKind,
|
||||
pub requested_open: bool,
|
||||
pub memory: PlacementMemory,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct Layout {
|
||||
pub version: u32,
|
||||
pub workspace: WorkspaceId,
|
||||
pub instances: Vec<PanelInstance>,
|
||||
/// Stable order, outermost first within each logical dock edge.
|
||||
pub sections: Vec<Section>,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
pub fn empty(workspace: WorkspaceId) -> Self {
|
||||
Self { version: LAYOUT_VERSION, workspace, instances: Vec::new(), sections: Vec::new() }
|
||||
}
|
||||
pub fn instance(&self, id: &InstanceId) -> PanelResult<&PanelInstance> {
|
||||
self.instances.iter().find(|p| p.id == *id).ok_or_else(|| error(Rule::MissingTarget, "instance not found"))
|
||||
}
|
||||
pub fn section(&self, id: &SectionId) -> PanelResult<&Section> {
|
||||
self.sections.iter().find(|s| s.id == *id).ok_or_else(|| error(Rule::MissingTarget, "section not found"))
|
||||
}
|
||||
pub fn containing(&self, id: &InstanceId) -> PanelResult<&Section> {
|
||||
self.sections.iter().find(|s| s.tabs.contains(id)).ok_or_else(|| error(Rule::MissingTarget, "instance has no open section"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "state", rename_all = "snake_case")]
|
||||
pub enum Availability {
|
||||
Available,
|
||||
Unavailable { reason: String },
|
||||
}
|
||||
|
||||
impl Availability {
|
||||
pub fn require(&self) -> PanelResult<()> {
|
||||
match self {
|
||||
Self::Available => Ok(()),
|
||||
Self::Unavailable { reason } => Err(error(Rule::Availability, reason)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Missing entries mean available. Availability is live context, never layout persistence.
|
||||
pub type AvailabilityMap = BTreeMap<InstanceId, Availability>;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct HostCapabilities {
|
||||
pub native_windows: bool,
|
||||
pub persistence: bool,
|
||||
pub max_native_hosts: usize,
|
||||
}
|
||||
|
||||
pub fn tab_bounds(layout: &Layout, registry: &PanelRegistry, section: &Section) -> PanelResult<(Size, Size)> {
|
||||
let mut min = Size { width: 0.0, height: 0.0 };
|
||||
let mut max = Size { width: MAX_LOGICAL, height: MAX_LOGICAL };
|
||||
for id in §ion.tabs {
|
||||
let spec = registry.get(&layout.instance(id)?.kind)?;
|
||||
min.width = min.width.max(spec.min_size.width);
|
||||
min.height = min.height.max(spec.min_size.height);
|
||||
max.width = max.width.min(spec.max_size.width);
|
||||
max.height = max.height.min(spec.max_size.height);
|
||||
}
|
||||
if min.width > max.width || min.height > max.height {
|
||||
return Err(error(Rule::IncompatibleTabs, "tab size constraints have no intersection"));
|
||||
}
|
||||
Ok((min, max))
|
||||
}
|
||||
|
||||
/// Bounded semantic validation, also required after serde and every transaction.
|
||||
pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
if layout.version != LAYOUT_VERSION {
|
||||
return Err(error(Rule::Version, "unsupported layout version"));
|
||||
}
|
||||
valid_id(&layout.workspace.0)?;
|
||||
if layout.instances.len() > MAX_INSTANCES || layout.sections.len() > MAX_SECTIONS {
|
||||
return Err(error(Rule::CollectionLimit, "layout collection limit"));
|
||||
}
|
||||
let mut instances = BTreeSet::new();
|
||||
let mut kinds = BTreeSet::new();
|
||||
for p in &layout.instances {
|
||||
valid_id(&p.id.0)?;
|
||||
valid_id(&p.kind.0)?;
|
||||
valid_id(&p.memory.section.0)?;
|
||||
if !instances.insert(&p.id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate instance"));
|
||||
}
|
||||
let spec = registry.get(&p.kind)?;
|
||||
if !spec.features.multi_instance && !kinds.insert(&p.kind) {
|
||||
return Err(error(Rule::ExactlyOnce, "single-instance kind repeated, including closed instances"));
|
||||
}
|
||||
p.memory.location.validate()?;
|
||||
p.memory.size.validate()?;
|
||||
if p.memory.tab_index >= MAX_TABS || p.memory.section_index > MAX_SECTIONS {
|
||||
return Err(error(Rule::Bounds, "invalid placement memory"));
|
||||
}
|
||||
if !spec.allowed_zones.contains(&p.memory.location.zone()) {
|
||||
return Err(error(Rule::Placement, "remembered zone forbidden"));
|
||||
}
|
||||
}
|
||||
let mut sections = BTreeSet::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut hosts = BTreeSet::new();
|
||||
let mut pins = BTreeSet::new();
|
||||
let mut edges = BTreeSet::new();
|
||||
for s in &layout.sections {
|
||||
valid_id(&s.id.0)?;
|
||||
s.location.validate()?;
|
||||
s.size.validate()?;
|
||||
if !sections.insert(&s.id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate section"));
|
||||
}
|
||||
if s.tabs.is_empty() || s.tabs.len() > MAX_TABS {
|
||||
return Err(error(Rule::CollectionLimit, "section requires 1..32 tabs"));
|
||||
}
|
||||
if !s.tabs.contains(&s.active) {
|
||||
return Err(error(Rule::MissingTarget, "active tab outside section"));
|
||||
}
|
||||
if let SectionLocation::Window { host, .. } = &s.location
|
||||
&& !hosts.insert(host)
|
||||
{
|
||||
return Err(error(Rule::DuplicateId, "native host reused"));
|
||||
}
|
||||
let zone = s.location.zone();
|
||||
let first = edges.insert(zone);
|
||||
for id in &s.tabs {
|
||||
let instance = layout.instance(id)?;
|
||||
let spec = registry.get(&instance.kind)?;
|
||||
if !instance.requested_open || !seen.insert(id) {
|
||||
return Err(error(Rule::ExactlyOnce, "closed or duplicate presented instance"));
|
||||
}
|
||||
if !spec.allowed_zones.contains(&zone) {
|
||||
return Err(error(Rule::Placement, "panel zone forbidden"));
|
||||
}
|
||||
if s.tabs.len() > 1 && !spec.features.tabbable {
|
||||
return Err(error(Rule::FeatureDisabled, "panel cannot join tabs"));
|
||||
}
|
||||
if s.collapsed && !spec.features.collapsible {
|
||||
return Err(error(Rule::FeatureDisabled, "panel cannot collapse"));
|
||||
}
|
||||
if zone == Zone::Window && !spec.features.popout {
|
||||
return Err(error(Rule::FeatureDisabled, "panel cannot pop out"));
|
||||
}
|
||||
if spec.edge_rule == EdgeRule::PinOuter && matches!(zone, Zone::Left | Zone::Right) {
|
||||
if !pins.insert(zone) {
|
||||
return Err(error(Rule::PinConflict, "competing pins on logical edge, including same tab group"));
|
||||
}
|
||||
if !first {
|
||||
return Err(error(Rule::PinOrder, "pinned section must be outermost"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (min, max) = tab_bounds(layout, registry, s)?;
|
||||
if !s.size.within(min, max) {
|
||||
return Err(error(Rule::Bounds, "section outside intersected tab bounds"));
|
||||
}
|
||||
if let SectionLocation::Window { return_to, .. } = &s.location {
|
||||
for id in &s.tabs {
|
||||
let spec = registry.get(&layout.instance(id)?.kind)?;
|
||||
if !spec.allowed_zones.contains(&return_to.zone)
|
||||
|| !return_to.size.within(spec.min_size, spec.max_size)
|
||||
|| (return_to.collapsed && !spec.features.collapsible)
|
||||
{
|
||||
return Err(error(Rule::Placement, "native return violates member constraints"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for p in &layout.instances {
|
||||
// Diagnose impossible tab groups before their shared size can make an
|
||||
// individual member's remembered size appear invalid.
|
||||
let spec = registry.get(&p.kind)?;
|
||||
if !p.memory.size.within(spec.min_size, spec.max_size) {
|
||||
return Err(error(Rule::Bounds, "invalid placement memory"));
|
||||
}
|
||||
if p.requested_open != seen.contains(&p.id) {
|
||||
return Err(error(Rule::ExactlyOnce, "open instance must appear exactly once"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,762 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::*;
|
||||
|
||||
pub const ENVELOPE_FORMAT: &str = "solidcraft.panel-layout";
|
||||
pub const ENVELOPE_VERSION: u32 = 1;
|
||||
|
||||
/// Unknown panel wire values are retained verbatim as JSON values, including
|
||||
/// fields a future content adapter understands. Total encoded envelope is capped.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct QuarantinedPanel {
|
||||
pub instance: InstanceId,
|
||||
pub kind: PanelKind,
|
||||
pub instance_data: serde_json::Value,
|
||||
pub section: Option<SectionId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct SectionSnapshot {
|
||||
pub data: serde_json::Value,
|
||||
/// Latest complete rank; also permits reading earlier v1 envelopes without
|
||||
/// the envelope's explicit complete section_order list.
|
||||
pub index: usize,
|
||||
/// Last materialized section, so a live user edit can be distinguished from
|
||||
/// the fallback active tab/order produced while some members are dormant.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub projected: Option<Section>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct LayoutEnvelope {
|
||||
pub format: String,
|
||||
pub version: u32,
|
||||
pub layout: Layout,
|
||||
pub quarantine: Vec<QuarantinedPanel>,
|
||||
/// Shared, lossless section order/activation/future fields, stored once even
|
||||
/// when many unknown tabs refer to the same section. Retained after restore.
|
||||
#[serde(default)]
|
||||
pub section_snapshots: std::collections::BTreeMap<SectionId, SectionSnapshot>,
|
||||
/// Latest complete section ordering, including currently dormant sections.
|
||||
/// Retained snapshots alone cannot rank surviving sections without this list.
|
||||
#[serde(default)]
|
||||
pub section_order: Vec<SectionId>,
|
||||
/// Original unknown wire data remains available after registry reappearance.
|
||||
/// A content/persistence adapter may explicitly consume it; restoring placement
|
||||
/// alone must not erase a future field that this foundation cannot interpret.
|
||||
#[serde(default)]
|
||||
pub retained_data: std::collections::BTreeMap<InstanceId, serde_json::Value>,
|
||||
}
|
||||
impl LayoutEnvelope {
|
||||
pub fn new(layout: Layout) -> Self {
|
||||
let section_order = layout.sections.iter().map(|section| section.id.clone()).collect();
|
||||
Self {
|
||||
format: ENVELOPE_FORMAT.into(),
|
||||
version: ENVELOPE_VERSION,
|
||||
layout,
|
||||
quarantine: Vec::new(),
|
||||
section_snapshots: std::collections::BTreeMap::new(),
|
||||
section_order,
|
||||
retained_data: std::collections::BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LoadOutcome {
|
||||
pub envelope: LayoutEnvelope,
|
||||
/// Adapter reports this once; fallback never blocks startup or touches other preferences.
|
||||
pub notice: Option<PanelError>,
|
||||
/// Bounded corrupt/future input, available to a recovery adapter before replacement.
|
||||
pub rejected: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Implementations read/write ONLY the workspace panel-layout preference key.
|
||||
/// `save` must replace atomically, preserving unrelated preferences. Production
|
||||
/// preference migration is intentionally outside the foundation.
|
||||
pub trait LayoutPersistence {
|
||||
fn load(&mut self, workspace: &WorkspaceId) -> PanelResult<Option<Vec<u8>>>;
|
||||
fn save(&mut self, workspace: &WorkspaceId, envelope: &[u8]) -> PanelResult<()>;
|
||||
}
|
||||
|
||||
pub fn encode(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<Vec<u8>> {
|
||||
validate_envelope(envelope, registry)?;
|
||||
encode_record(envelope)
|
||||
}
|
||||
|
||||
fn encode_record(envelope: &LayoutEnvelope) -> PanelResult<Vec<u8>> {
|
||||
let mut writer = BoundedEnvelopeWriter { bytes: Vec::new() };
|
||||
serde_json::to_writer(&mut writer, envelope).map_err(|_| error(Rule::CollectionLimit, "cannot encode panel envelope within byte cap"))?;
|
||||
// Aggregated opaque entries must also fit the decoder's global node/depth
|
||||
// budget. Never persist bytes that this same version would reject on reopen.
|
||||
let value: serde_json::Value = serde_json::from_slice(&writer.bytes).map_err(|_| error(Rule::Schema, "invalid encoded panel envelope"))?;
|
||||
bounded_json(&value)?;
|
||||
Ok(writer.bytes)
|
||||
}
|
||||
|
||||
struct BoundedEnvelopeWriter {
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
impl std::io::Write for BoundedEnvelopeWriter {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
if self.bytes.len().saturating_add(bytes.len()) > MAX_ENVELOPE_BYTES {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "panel envelope byte cap"));
|
||||
}
|
||||
self.bytes.extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_envelope(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
if envelope.format != ENVELOPE_FORMAT {
|
||||
return Err(error(Rule::Schema, "unknown panel envelope format"));
|
||||
}
|
||||
if envelope.version != ENVELOPE_VERSION {
|
||||
return Err(error(Rule::Version, "unknown panel envelope version"));
|
||||
}
|
||||
validate(&envelope.layout, registry)?;
|
||||
validate_envelope_metadata(envelope)
|
||||
}
|
||||
|
||||
fn validate_envelope_metadata(envelope: &LayoutEnvelope) -> PanelResult<()> {
|
||||
if envelope.quarantine.len() + envelope.layout.instances.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "quarantine instance cap"));
|
||||
}
|
||||
if envelope.retained_data.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "retained data cap"));
|
||||
}
|
||||
for (id, data) in &envelope.retained_data {
|
||||
valid_id(&id.0)?;
|
||||
bounded_json(data)?;
|
||||
}
|
||||
if envelope.section_snapshots.len() > MAX_SECTIONS {
|
||||
return Err(error(Rule::CollectionLimit, "section snapshot cap"));
|
||||
}
|
||||
validate_section_order(&envelope.section_order)?;
|
||||
for (id, snapshot) in &envelope.section_snapshots {
|
||||
validate_snapshot(id, snapshot)?;
|
||||
}
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
for item in &envelope.quarantine {
|
||||
bounded_json(&item.instance_data)?;
|
||||
valid_id(&item.instance.0)?;
|
||||
valid_id(&item.kind.0)?;
|
||||
if !ids.insert(&item.instance) || envelope.layout.instances.iter().any(|p| p.id == item.instance) {
|
||||
return Err(error(Rule::DuplicateId, "quarantine identity or index invalid"));
|
||||
}
|
||||
let instance: PanelInstance =
|
||||
serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?;
|
||||
if instance.id != item.instance || instance.kind != item.kind {
|
||||
return Err(error(Rule::Id, "quarantine identity mismatch"));
|
||||
}
|
||||
if instance.requested_open != item.section.is_some() {
|
||||
return Err(error(Rule::ExactlyOnce, "quarantine open/section mismatch"));
|
||||
}
|
||||
valid_id(&instance.memory.section.0)?;
|
||||
instance.memory.location.validate()?;
|
||||
instance.memory.size.validate()?;
|
||||
if instance.memory.section_index > MAX_SECTIONS || instance.memory.tab_index >= MAX_TABS {
|
||||
return Err(error(Rule::CollectionLimit, "quarantine placement cap"));
|
||||
}
|
||||
if let Some(id) = &item.section {
|
||||
let snapshot = envelope.section_snapshots.get(id).ok_or_else(|| error(Rule::MissingTarget, "quarantined section snapshot absent"))?;
|
||||
let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined section"))?;
|
||||
if !section.tabs.contains(&item.instance) {
|
||||
return Err(error(Rule::ExactlyOnce, "quarantined instance absent from section snapshot"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_section_order(order: &[SectionId]) -> PanelResult<()> {
|
||||
if order.len() > MAX_SECTIONS {
|
||||
return Err(error(Rule::CollectionLimit, "complete section order cap"));
|
||||
}
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for id in order {
|
||||
valid_id(&id.0)?;
|
||||
if !seen.insert(id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate complete section rank"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_section_record(section: &Section) -> PanelResult<()> {
|
||||
valid_id(§ion.id.0)?;
|
||||
section.location.validate()?;
|
||||
section.size.validate()?;
|
||||
if section.tabs.is_empty() || section.tabs.len() > MAX_TABS || !section.tabs.contains(§ion.active) {
|
||||
return Err(error(Rule::CollectionLimit, "section snapshot tabs/active bound"));
|
||||
}
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for id in §ion.tabs {
|
||||
valid_id(&id.0)?;
|
||||
if !seen.insert(id) {
|
||||
return Err(error(Rule::ExactlyOnce, "section snapshot duplicate tab"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_snapshot(id: &SectionId, snapshot: &SectionSnapshot) -> PanelResult<()> {
|
||||
valid_id(&id.0)?;
|
||||
bounded_json(&snapshot.data)?;
|
||||
let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid shared section snapshot"))?;
|
||||
if section.id != *id || snapshot.index > MAX_SECTIONS {
|
||||
return Err(error(Rule::Id, "section snapshot identity/index mismatch"));
|
||||
}
|
||||
validate_section_record(§ion)?;
|
||||
if let Some(projected) = &snapshot.projected {
|
||||
if projected.id != *id {
|
||||
return Err(error(Rule::Id, "projected section identity mismatch"));
|
||||
}
|
||||
validate_section_record(projected)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Overlay the live relative order on its previous slots, keeping dormant gaps.
|
||||
/// New live entries attach before their next surviving live neighbour, rather
|
||||
/// than consuming a dormant slot or reversing a run of newly added entries.
|
||||
fn merge_visible_order<T: Clone + Ord>(saved: &[T], live: &[T], dormant: &std::collections::BTreeSet<T>) -> Vec<T> {
|
||||
let survivors: std::collections::BTreeSet<_> = saved.iter().filter(|id| live.contains(id)).cloned().collect();
|
||||
let mut live_survivors = live.iter().filter(|id| survivors.contains(*id));
|
||||
let mut merged = Vec::new();
|
||||
for id in saved {
|
||||
if dormant.contains(id) && !live.contains(id) {
|
||||
merged.push(id.clone());
|
||||
} else if survivors.contains(id)
|
||||
&& let Some(next) = live_survivors.next()
|
||||
{
|
||||
merged.push(next.clone());
|
||||
}
|
||||
}
|
||||
for (index, id) in live.iter().enumerate() {
|
||||
if survivors.contains(id) {
|
||||
continue;
|
||||
}
|
||||
let before = live.iter().skip(index + 1).find(|next| survivors.contains(*next));
|
||||
let at = before.and_then(|next| merged.iter().position(|old| old == next)).unwrap_or(merged.len());
|
||||
merged.insert(at, id.clone());
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// Refresh live semantics before a new quarantine episode, or before a direct
|
||||
/// restoration after the caller has edited the known layout. Opaque data stays
|
||||
/// shared; only semantic fields supplied by the current layout are refreshed.
|
||||
fn refresh_section_memory(
|
||||
envelope: &mut LayoutEnvelope,
|
||||
raw: Option<&serde_json::Value>,
|
||||
capture: &std::collections::BTreeSet<SectionId>,
|
||||
) -> PanelResult<()> {
|
||||
if envelope.section_snapshots.len() > MAX_SECTIONS || envelope.quarantine.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "section memory collection cap"));
|
||||
}
|
||||
validate_section_order(&envelope.section_order)?;
|
||||
for (id, snapshot) in &envelope.section_snapshots {
|
||||
validate_snapshot(id, snapshot)?;
|
||||
}
|
||||
let dormant_sections: std::collections::BTreeSet<_> = envelope.quarantine.iter().filter_map(|item| item.section.clone()).collect();
|
||||
let live_order: Vec<_> = envelope.layout.sections.iter().map(|section| section.id.clone()).collect();
|
||||
let mut saved_order = envelope.section_order.clone();
|
||||
if saved_order.is_empty() {
|
||||
// Read earlier v1 envelopes without the complete rank list. Sort missing
|
||||
// ranks before insertion, never in instance/quarantine processing order.
|
||||
saved_order = live_order.clone();
|
||||
let mut missing = Vec::new();
|
||||
for id in &dormant_sections {
|
||||
let snapshot = envelope.section_snapshots.get(id).ok_or_else(|| error(Rule::MissingTarget, "dormant section snapshot missing"))?;
|
||||
if !saved_order.contains(id) {
|
||||
missing.push((snapshot.index, id.clone()));
|
||||
}
|
||||
}
|
||||
missing.sort();
|
||||
for (index, id) in missing {
|
||||
saved_order.insert(index.min(saved_order.len()), id);
|
||||
}
|
||||
} else if dormant_sections.iter().any(|id| !saved_order.contains(id)) {
|
||||
return Err(error(Rule::MissingTarget, "complete order omits a dormant section"));
|
||||
}
|
||||
envelope.section_order = merge_visible_order(&saved_order, &live_order, &dormant_sections);
|
||||
validate_section_order(&envelope.section_order)?;
|
||||
for (index, section) in envelope.layout.sections.iter().enumerate() {
|
||||
let previous = envelope.section_snapshots.get(§ion.id);
|
||||
if previous.is_none() && !capture.contains(§ion.id) {
|
||||
continue;
|
||||
}
|
||||
let current = match raw {
|
||||
Some(raw) => raw
|
||||
.get("layout")
|
||||
.and_then(|layout| layout.get("sections"))
|
||||
.and_then(|sections| sections.get(index))
|
||||
.cloned()
|
||||
.ok_or_else(|| error(Rule::Schema, "saved section raw data missing"))?,
|
||||
None => serde_json::to_value(section).map_err(|_| error(Rule::Schema, "cannot encode live section semantics"))?,
|
||||
};
|
||||
let (mut data, projected) = match previous {
|
||||
Some(previous) => (previous.data.clone(), previous.projected.clone()),
|
||||
None => (serde_json::json!({}), None),
|
||||
};
|
||||
let dormant_tabs: std::collections::BTreeSet<_> =
|
||||
envelope.quarantine.iter().filter(|item| item.section.as_ref() == Some(§ion.id)).map(|item| item.instance.clone()).collect();
|
||||
let previous_section: Option<Section> = previous
|
||||
.map(|snapshot| serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid section memory")))
|
||||
.transpose()?;
|
||||
let tabs = match &previous_section {
|
||||
Some(saved) if !dormant_tabs.is_empty() => merge_visible_order(&saved.tabs, §ion.tabs, &dormant_tabs),
|
||||
_ => section.tabs.clone(),
|
||||
};
|
||||
if tabs.len() > MAX_TABS {
|
||||
return Err(error(Rule::CollectionLimit, "complete tab order cap"));
|
||||
}
|
||||
let active = match &previous_section {
|
||||
Some(saved)
|
||||
if dormant_tabs.contains(&saved.active)
|
||||
&& !section.tabs.contains(&saved.active)
|
||||
&& !projected.as_ref().is_some_and(|last| last.active != section.active) =>
|
||||
{
|
||||
saved.active.clone()
|
||||
}
|
||||
_ => section.active.clone(),
|
||||
};
|
||||
// Overlay current fields, preserving opaque keys absent from the typed
|
||||
// layout. A current raw value for the same key is the latest saved intent.
|
||||
let object = data.as_object_mut().ok_or_else(|| error(Rule::Schema, "section memory must be an object"))?;
|
||||
let current = current.as_object().ok_or_else(|| error(Rule::Schema, "saved section must be an object"))?;
|
||||
for (key, value) in current {
|
||||
object.insert(key.clone(), value.clone());
|
||||
}
|
||||
object.insert("tabs".into(), serde_json::to_value(tabs).map_err(|_| error(Rule::Schema, "cannot encode complete tab order"))?);
|
||||
object.insert("active".into(), serde_json::to_value(active).map_err(|_| error(Rule::Schema, "cannot encode complete activation"))?);
|
||||
let rank = envelope
|
||||
.section_order
|
||||
.iter()
|
||||
.position(|id| *id == section.id)
|
||||
.ok_or_else(|| error(Rule::MissingTarget, "live section has no complete rank"))?;
|
||||
envelope.section_snapshots.insert(section.id.clone(), SectionSnapshot { data, index: rank, projected });
|
||||
}
|
||||
for (id, snapshot) in &mut envelope.section_snapshots {
|
||||
if let Some(rank) = envelope.section_order.iter().position(|known| known == id) {
|
||||
snapshot.index = rank;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn record_section_projections(envelope: &mut LayoutEnvelope) {
|
||||
let layout = &envelope.layout;
|
||||
for (id, snapshot) in &mut envelope.section_snapshots {
|
||||
snapshot.projected = layout.sections.iter().find(|section| section.id == *id).cloned();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage live edits without losing dormant order, projected activation or opaque
|
||||
/// fields. The caller publishes only after its guarded layout dispatch succeeds.
|
||||
pub fn with_live_layout(envelope: &LayoutEnvelope, layout: Layout, registry: &PanelRegistry) -> PanelResult<LayoutEnvelope> {
|
||||
encode(envelope, registry)?;
|
||||
validate(&layout, registry)?;
|
||||
let mut next = envelope.clone();
|
||||
next.layout = layout;
|
||||
refresh_section_memory(&mut next, None, &std::collections::BTreeSet::new())?;
|
||||
record_section_projections(&mut next);
|
||||
encode(&next, registry)?;
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// Iterative traversal also bounds caller-constructed JSON, which did not pass
|
||||
/// through serde_json's parser/recursion limit.
|
||||
pub fn bounded_json(value: &serde_json::Value) -> PanelResult<()> {
|
||||
let mut stack = vec![(value, 0_usize)];
|
||||
let mut nodes = 0_usize;
|
||||
let mut bytes = 0_usize;
|
||||
while let Some((value, depth)) = stack.pop() {
|
||||
nodes = nodes.saturating_add(1);
|
||||
if nodes > 8192 || depth > 32 {
|
||||
return Err(error(Rule::CollectionLimit, "JSON node/depth cap"));
|
||||
}
|
||||
match value {
|
||||
serde_json::Value::String(s) => bytes = bytes.saturating_add(s.len()),
|
||||
serde_json::Value::Array(values) => {
|
||||
if values.len() > 8192 || stack.len().saturating_add(values.len()) > 8192 {
|
||||
return Err(error(Rule::CollectionLimit, "JSON array cap"));
|
||||
}
|
||||
stack.extend(values.iter().map(|value| (value, depth + 1)));
|
||||
}
|
||||
serde_json::Value::Object(values) => {
|
||||
if values.len() > 8192 || stack.len().saturating_add(values.len()) > 8192 {
|
||||
return Err(error(Rule::CollectionLimit, "JSON object cap"));
|
||||
}
|
||||
for (key, value) in values {
|
||||
bytes = bytes.saturating_add(key.len());
|
||||
stack.push((value, depth + 1));
|
||||
}
|
||||
}
|
||||
serde_json::Value::Number(n) if n.as_f64().is_some_and(|n| !n.is_finite()) => return Err(error(Rule::Bounds, "nonfinite JSON value")),
|
||||
_ => {}
|
||||
}
|
||||
if bytes > MAX_ENVELOPE_BYTES {
|
||||
return Err(error(Rule::CollectionLimit, "JSON byte cap"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decode bounded bytes, quarantine unknown kinds, and retry retained panels when
|
||||
/// registered again. Corrupt/future input returns a validated safe preset plus notice.
|
||||
pub fn decode(bytes: &[u8], registry: &PanelRegistry, fallback: &Layout) -> PanelResult<LoadOutcome> {
|
||||
validate(fallback, registry)?;
|
||||
match decode_inner(bytes, registry, &fallback.workspace, true) {
|
||||
Ok(envelope) => Ok(LoadOutcome { envelope, notice: None, rejected: None }),
|
||||
Err(reason) => Ok(LoadOutcome {
|
||||
envelope: LayoutEnvelope::new(fallback.clone()),
|
||||
notice: Some(reason),
|
||||
rejected: if bytes.len() <= MAX_ENVELOPE_BYTES { Some(bytes.to_vec()) } else { None },
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate an already-retained record exactly, without generating section order,
|
||||
/// projections or quarantine/restoration metadata. Missing registrations do not
|
||||
/// invalidate saved intent. Structure and every applicable known-kind constraint
|
||||
/// are still validated, but this retained layout is NOT permission to commit it
|
||||
/// to a live sink. Use `project_retained_record` to stage registry migration.
|
||||
pub fn decode_retained_record(bytes: &[u8], registry: &PanelRegistry) -> PanelResult<LayoutEnvelope> {
|
||||
if bytes.len() > MAX_ENVELOPE_BYTES {
|
||||
return Err(error(Rule::CollectionLimit, "panel envelope exceeds byte cap"));
|
||||
}
|
||||
let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?;
|
||||
bounded_json(&raw)?;
|
||||
let envelope: LayoutEnvelope = serde_json::from_value(raw).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?;
|
||||
if envelope.format != ENVELOPE_FORMAT {
|
||||
return Err(error(Rule::Schema, "unknown panel envelope format"));
|
||||
}
|
||||
if envelope.version != ENVELOPE_VERSION {
|
||||
return Err(error(Rule::Version, "unknown panel envelope version"));
|
||||
}
|
||||
validate_retained_layout(&envelope.layout, registry)?;
|
||||
validate_envelope_metadata(&envelope)?;
|
||||
// The same canonical encodability budget as admission, without filling any
|
||||
// metadata or requiring absent peers. The caller retains the ORIGINAL bytes.
|
||||
encode_record(&envelope)?;
|
||||
Ok(envelope)
|
||||
}
|
||||
|
||||
/// Read a retained record in its workspace without consuming a reappearance
|
||||
/// obligation or materializing absent order/projection metadata.
|
||||
pub fn decode_retained(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult<LayoutEnvelope> {
|
||||
valid_id(&workspace.0)?;
|
||||
let envelope = decode_retained_record(bytes, registry)?;
|
||||
if envelope.layout.workspace != *workspace {
|
||||
return Err(error(Rule::Schema, "panel envelope workspace mismatch"));
|
||||
}
|
||||
Ok(envelope)
|
||||
}
|
||||
|
||||
/// Stage a usable current-registry layout without consuming quarantined
|
||||
/// reappearance obligations. Newly absent kinds move to the foundation's
|
||||
/// lossless quarantine. Metadata expansion can fail at the existing caps; the
|
||||
/// original record remains available for retry and no live state is published.
|
||||
pub fn project_retained_record(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult<LayoutEnvelope> {
|
||||
let envelope = decode_retained(bytes, registry, workspace)?;
|
||||
if envelope.layout.instances.iter().any(|instance| registry.get(&instance.kind).is_err()) {
|
||||
decode_inner(bytes, registry, workspace, false)
|
||||
} else {
|
||||
Ok(envelope)
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_inner(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId, restore: bool) -> PanelResult<LayoutEnvelope> {
|
||||
if bytes.len() > MAX_ENVELOPE_BYTES {
|
||||
return Err(error(Rule::CollectionLimit, "panel envelope exceeds byte cap"));
|
||||
}
|
||||
// serde_json's recursion limit remains enabled. Parsing starts only after the
|
||||
// byte bound, so oversized arrays/strings cannot allocate without a bound.
|
||||
let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?;
|
||||
bounded_json(&raw)?;
|
||||
let mut envelope: LayoutEnvelope = serde_json::from_value(raw.clone()).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?;
|
||||
if envelope.version != ENVELOPE_VERSION || envelope.layout.version != LAYOUT_VERSION {
|
||||
return Err(error(Rule::Version, "future or unsupported panel layout"));
|
||||
}
|
||||
if envelope.format != ENVELOPE_FORMAT || envelope.layout.workspace != *workspace {
|
||||
return Err(error(Rule::Schema, "panel envelope format/workspace mismatch"));
|
||||
}
|
||||
if envelope.layout.instances.len() > MAX_INSTANCES
|
||||
|| envelope.layout.sections.len() > MAX_SECTIONS
|
||||
|| envelope.quarantine.len() > MAX_INSTANCES
|
||||
|| envelope.layout.sections.iter().any(|s| s.tabs.len() > MAX_TABS)
|
||||
{
|
||||
return Err(error(Rule::CollectionLimit, "panel collection limit"));
|
||||
}
|
||||
validate_retained_layout(&envelope.layout, registry)?;
|
||||
validate_envelope_metadata(&envelope)?;
|
||||
let unknown: Vec<_> = envelope.layout.instances.iter().filter(|p| registry.get(&p.kind).is_err()).cloned().collect();
|
||||
let capture: std::collections::BTreeSet<_> = envelope
|
||||
.layout
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|section| unknown.iter().any(|p| section.tabs.contains(&p.id)))
|
||||
.map(|section| section.id.clone())
|
||||
.collect();
|
||||
// Refresh from the saved live layout BEFORE newly unknown members are
|
||||
// removed. A previous fully-restored snapshot is opaque metadata, not an
|
||||
// authority that can overwrite intervening saved edits.
|
||||
refresh_section_memory(&mut envelope, Some(&raw), &capture)?;
|
||||
for instance in unknown {
|
||||
let section_index = envelope.layout.sections.iter().position(|s| s.tabs.contains(&instance.id));
|
||||
let instance_data = raw
|
||||
.get("layout")
|
||||
.and_then(|l| l.get("instances"))
|
||||
.and_then(|a| a.as_array())
|
||||
.and_then(|a| a.iter().find(|v| v.get("id").and_then(|s| s.as_str()) == Some(instance.id.0.as_str())))
|
||||
.cloned()
|
||||
.ok_or_else(|| error(Rule::Schema, "unknown instance raw data missing"))?;
|
||||
let section = if let Some(index) = section_index {
|
||||
let id = envelope.layout.sections.get(index).ok_or_else(|| error(Rule::MissingTarget, "unknown section absent"))?.id.clone();
|
||||
Some(id)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
envelope.quarantine.push(QuarantinedPanel { instance: instance.id.clone(), kind: instance.kind, instance_data, section });
|
||||
envelope.layout.instances.retain(|p| p.id != instance.id);
|
||||
}
|
||||
let retained: std::collections::BTreeSet<_> = envelope.layout.instances.iter().map(|p| p.id.clone()).collect();
|
||||
for section in &mut envelope.layout.sections {
|
||||
section.tabs.retain(|id| retained.contains(id));
|
||||
if !section.tabs.contains(§ion.active)
|
||||
&& let Some(first) = section.tabs.first()
|
||||
{
|
||||
section.active = first.clone();
|
||||
}
|
||||
}
|
||||
envelope.layout.sections.retain(|s| !s.tabs.is_empty());
|
||||
// Newly quarantining an active tab creates a fallback selection. That
|
||||
// projection is produced by us, not an intervening user activation.
|
||||
record_section_projections(&mut envelope);
|
||||
validate_envelope(&envelope, registry)?;
|
||||
if restore {
|
||||
restore_quarantine(&mut envelope, registry)?;
|
||||
}
|
||||
// Success means the lossless transformed envelope is itself persistable,
|
||||
// including its aggregate byte/node/depth budget. Otherwise retain recovery.
|
||||
encode(&envelope, registry)?;
|
||||
Ok(envelope)
|
||||
}
|
||||
|
||||
pub fn restore_quarantine(envelope: &mut LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
restore_quarantine_with_availability(envelope, registry, &AvailabilityMap::new())
|
||||
}
|
||||
|
||||
pub fn restore_quarantine_with_availability(
|
||||
envelope: &mut LayoutEnvelope,
|
||||
registry: &PanelRegistry,
|
||||
availability: &AvailabilityMap,
|
||||
) -> PanelResult<()> {
|
||||
validate_envelope(envelope, registry)?;
|
||||
if availability.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "reappearance availability cap"));
|
||||
}
|
||||
for (id, state) in availability {
|
||||
valid_id(&id.0)?;
|
||||
if matches!(state, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) {
|
||||
return Err(error(Rule::Availability, "invalid reappearance availability reason"));
|
||||
}
|
||||
}
|
||||
let mut working = envelope.clone();
|
||||
// Direct consumers may have edited the live layout since the last decode or
|
||||
// restore. Merge those edits before using saved ranks/activation again.
|
||||
refresh_section_memory(&mut working, None, &std::collections::BTreeSet::new())?;
|
||||
// Build a candidate for each entry. An incompatible reappearance stays in
|
||||
// quarantine instead of invalidating the known layout or erasing its wire data.
|
||||
let mut remaining = Vec::new();
|
||||
for item in &envelope.quarantine {
|
||||
if registry.get(&item.kind).is_err() || availability.get(&item.instance).is_some_and(|state| *state != Availability::Available) {
|
||||
remaining.push(item.clone());
|
||||
continue;
|
||||
}
|
||||
let mut candidate = working.layout.clone();
|
||||
let instance: PanelInstance =
|
||||
serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?;
|
||||
candidate.instances.push(instance.clone());
|
||||
if instance.requested_open {
|
||||
let Some(section_id) = &item.section else {
|
||||
remaining.push(item.clone());
|
||||
continue;
|
||||
};
|
||||
let snapshot = working.section_snapshots.get(section_id).ok_or_else(|| error(Rule::MissingTarget, "shared snapshot missing"))?;
|
||||
let mut saved: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined section"))?;
|
||||
if let Some(section) = candidate.sections.iter_mut().find(|s| s.id == saved.id) {
|
||||
let members: std::collections::BTreeSet<_> = section.tabs.iter().cloned().chain(std::iter::once(instance.id.clone())).collect();
|
||||
section.tabs = saved
|
||||
.tabs
|
||||
.iter()
|
||||
.filter(|id| members.contains(*id))
|
||||
.cloned()
|
||||
.chain(section.tabs.iter().filter(|id| !saved.tabs.contains(id)).cloned())
|
||||
.collect();
|
||||
if saved.active == instance.id {
|
||||
section.active = saved.active.clone();
|
||||
}
|
||||
} else {
|
||||
saved.tabs = vec![instance.id.clone()];
|
||||
saved.active = instance.id.clone();
|
||||
candidate.sections.push(saved);
|
||||
}
|
||||
}
|
||||
// Rank against the full saved order, not an index clamped into a partial
|
||||
// list. Sorting also includes surviving sections with no snapshot.
|
||||
candidate.sections.sort_by_key(|section| working.section_order.iter().position(|id| *id == section.id).unwrap_or(MAX_SECTIONS));
|
||||
if validate(&candidate, registry).is_ok() {
|
||||
if working.retained_data.len() >= MAX_INSTANCES && !working.retained_data.contains_key(&item.instance) {
|
||||
remaining.push(item.clone());
|
||||
continue;
|
||||
}
|
||||
working
|
||||
.retained_data
|
||||
.entry(item.instance.clone())
|
||||
.or_insert_with(|| serde_json::json!({"instance":item.instance_data,"section":item.section}));
|
||||
working.layout = candidate;
|
||||
} else {
|
||||
remaining.push(item.clone());
|
||||
}
|
||||
}
|
||||
working.quarantine = remaining;
|
||||
record_section_projections(&mut working);
|
||||
encode(&working, registry)?;
|
||||
*envelope = working;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate saved identities/ownership independently of optional peers, then use
|
||||
/// the ordinary validator for known members. The temporary known-only view is
|
||||
/// validation input only: it is never returned, encoded, or dispatched.
|
||||
fn validate_retained_layout(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
validate_wire_structure(layout)?;
|
||||
if layout.instances.iter().all(|instance| registry.get(&instance.kind).is_ok()) {
|
||||
return validate(layout, registry);
|
||||
}
|
||||
let mut edges = std::collections::BTreeSet::new();
|
||||
for section in &layout.sections {
|
||||
let zone = section.location.zone();
|
||||
let first = edges.insert(zone);
|
||||
for id in §ion.tabs {
|
||||
let instance = layout.instance(id)?;
|
||||
if let Ok(spec) = registry.get(&instance.kind) {
|
||||
// Filtering absent tabs/sections must not hide these constraints
|
||||
// of a known member in the ORIGINAL full saved placement.
|
||||
if section.tabs.len() > 1 && !spec.features.tabbable {
|
||||
return Err(error(Rule::FeatureDisabled, "panel cannot join tabs"));
|
||||
}
|
||||
if spec.edge_rule == EdgeRule::PinOuter && matches!(zone, Zone::Left | Zone::Right) && !first {
|
||||
return Err(error(Rule::PinOrder, "pinned section must be outermost"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut known = layout.clone();
|
||||
known.instances.retain(|instance| registry.get(&instance.kind).is_ok());
|
||||
let ids: std::collections::BTreeSet<_> = known.instances.iter().map(|instance| instance.id.clone()).collect();
|
||||
for section in &mut known.sections {
|
||||
section.tabs.retain(|id| ids.contains(id));
|
||||
if !section.tabs.contains(§ion.active)
|
||||
&& let Some(first) = section.tabs.first()
|
||||
{
|
||||
section.active = first.clone();
|
||||
}
|
||||
}
|
||||
known.sections.retain(|section| !section.tabs.is_empty());
|
||||
validate(&known, registry)
|
||||
}
|
||||
|
||||
fn validate_wire_structure(layout: &Layout) -> PanelResult<()> {
|
||||
if layout.version != LAYOUT_VERSION {
|
||||
return Err(error(Rule::Version, "unsupported layout version"));
|
||||
}
|
||||
valid_id(&layout.workspace.0)?;
|
||||
if layout.instances.len() > MAX_INSTANCES || layout.sections.len() > MAX_SECTIONS {
|
||||
return Err(error(Rule::CollectionLimit, "layout collection limit"));
|
||||
}
|
||||
let mut instances = std::collections::BTreeSet::new();
|
||||
let mut sections = std::collections::BTreeSet::new();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut hosts = std::collections::BTreeSet::new();
|
||||
for instance in &layout.instances {
|
||||
valid_id(&instance.id.0)?;
|
||||
valid_id(&instance.kind.0)?;
|
||||
valid_id(&instance.memory.section.0)?;
|
||||
instance.memory.location.validate()?;
|
||||
instance.memory.size.validate()?;
|
||||
if instance.memory.tab_index >= MAX_TABS || instance.memory.section_index > MAX_SECTIONS {
|
||||
return Err(error(Rule::Bounds, "invalid placement memory"));
|
||||
}
|
||||
if !instances.insert(&instance.id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate unknown/known instance"));
|
||||
}
|
||||
}
|
||||
for section in &layout.sections {
|
||||
valid_id(§ion.id.0)?;
|
||||
section.location.validate()?;
|
||||
section.size.validate()?;
|
||||
if !sections.insert(§ion.id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate unknown/known section"));
|
||||
}
|
||||
if section.tabs.len() > MAX_TABS {
|
||||
return Err(error(Rule::CollectionLimit, "section tab cap"));
|
||||
}
|
||||
if let SectionLocation::Window { host, .. } = §ion.location
|
||||
&& !hosts.insert(host)
|
||||
{
|
||||
return Err(error(Rule::DuplicateId, "native host reused"));
|
||||
}
|
||||
if section.tabs.is_empty() || !section.tabs.contains(§ion.active) {
|
||||
return Err(error(Rule::ExactlyOnce, "invalid unknown/known active tab"));
|
||||
}
|
||||
for id in §ion.tabs {
|
||||
if !instances.contains(id) || !seen.insert(id) {
|
||||
return Err(error(Rule::ExactlyOnce, "unknown/known tab ownership invalid"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for instance in &layout.instances {
|
||||
if instance.requested_open != seen.contains(&instance.id) {
|
||||
return Err(error(Rule::ExactlyOnce, "unknown/known open state invalid"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// JSON schema for the wire contract. Semantic constraints are enforced by decode
|
||||
/// and the reducer; schema alone is never treated as a validation proof.
|
||||
pub fn layout_action_schema() -> schemars::Schema {
|
||||
schemars::schema_for!(LayoutAction)
|
||||
}
|
||||
pub fn layout_reply_schema() -> schemars::Schema {
|
||||
schemars::schema_for!(LayoutReply)
|
||||
}
|
||||
pub fn layout_error_schema() -> schemars::Schema {
|
||||
schemars::schema_for!(PanelError)
|
||||
}
|
||||
pub fn layout_envelope_schema() -> schemars::Schema {
|
||||
schemars::schema_for!(LayoutEnvelope)
|
||||
}
|
||||
|
||||
pub fn decode_action(bytes: &[u8]) -> PanelResult<LayoutAction> {
|
||||
if bytes.len() > MAX_ENVELOPE_BYTES {
|
||||
return Err(error(Rule::CollectionLimit, "action byte cap"));
|
||||
}
|
||||
let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid action JSON"))?;
|
||||
bounded_json(&value)?;
|
||||
let action: LayoutAction = serde_json::from_value(value).map_err(|_| error(Rule::Schema, "invalid action shape"))?;
|
||||
if let LayoutAction::Apply { mutations, .. } = &action
|
||||
&& (mutations.is_empty() || mutations.len() > MAX_MUTATIONS)
|
||||
{
|
||||
return Err(error(Rule::CollectionLimit, "action mutation cap"));
|
||||
}
|
||||
Ok(action)
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Joining an existing tab group and creating a split are deliberately distinct.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Destination {
|
||||
NewSection { section: SectionId, index: usize, location: SectionLocation, size: Size },
|
||||
JoinTab { section: SectionId, index: usize },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Mutation {
|
||||
Open {
|
||||
kind: PanelKind,
|
||||
instance: InstanceId,
|
||||
destination: Option<Destination>,
|
||||
},
|
||||
Close {
|
||||
instance: InstanceId,
|
||||
},
|
||||
/// Explicit owner cleanup, only after close. Hiding is never destruction.
|
||||
Destroy {
|
||||
instance: InstanceId,
|
||||
},
|
||||
Move {
|
||||
instance: InstanceId,
|
||||
destination: Destination,
|
||||
},
|
||||
Activate {
|
||||
instance: InstanceId,
|
||||
},
|
||||
Focus {
|
||||
instance: InstanceId,
|
||||
},
|
||||
Peek {
|
||||
instance: InstanceId,
|
||||
},
|
||||
DismissPeek,
|
||||
Collapse {
|
||||
section: SectionId,
|
||||
collapsed: bool,
|
||||
},
|
||||
SetSize {
|
||||
section: SectionId,
|
||||
size: Size,
|
||||
},
|
||||
/// Both neighbours change together; their shared axis extent is conserved.
|
||||
ResizePair {
|
||||
first: SectionId,
|
||||
second: SectionId,
|
||||
first_size: Size,
|
||||
second_size: Size,
|
||||
},
|
||||
ResetPair {
|
||||
first: SectionId,
|
||||
second: SectionId,
|
||||
},
|
||||
/// A native window's close button redocks its whole section.
|
||||
NativeClose {
|
||||
host: HostId,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum LayoutAction {
|
||||
Inspect,
|
||||
Apply {
|
||||
expected_revision: Option<u64>,
|
||||
mutations: Vec<Mutation>,
|
||||
},
|
||||
/// Apply a complete saved layout/preset, including a workspace change.
|
||||
/// Omission and requested_open=false hide content without lifecycle intent.
|
||||
Replace {
|
||||
expected_revision: Option<u64>,
|
||||
layout: Layout,
|
||||
},
|
||||
}
|
||||
|
||||
/// Stable targets for a later command adapter; none are registered with Session yet.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", content = "id", rename_all = "snake_case")]
|
||||
pub enum LayoutTarget {
|
||||
Workspace(WorkspaceId),
|
||||
Instance(InstanceId),
|
||||
Section(SectionId),
|
||||
NativeHost(HostId),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum HostEffect {
|
||||
Focus { instance: InstanceId },
|
||||
Peek { instance: InstanceId },
|
||||
DismissPeek,
|
||||
CreateNative { host: HostId, section: SectionId },
|
||||
RebindNative { host: HostId, section: SectionId },
|
||||
ReleaseNative { host: HostId },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct InteractionState {
|
||||
pub focused: Option<InstanceId>,
|
||||
pub peek: Option<InstanceId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct LayoutReply {
|
||||
pub api_version: u32,
|
||||
pub revision: u64,
|
||||
pub layout: Layout,
|
||||
pub interaction: InteractionState,
|
||||
pub effects: Vec<HostEffect>,
|
||||
pub capabilities: HostCapabilities,
|
||||
pub availability: AvailabilityMap,
|
||||
}
|
||||
|
||||
/// Same boundary for GUI and programmatic callers. No mutable Session reference.
|
||||
pub trait ActionSink {
|
||||
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply>;
|
||||
fn inspect(&self) -> LayoutReply;
|
||||
/// Pure projection on the authoritative service. Adapters stage bounded
|
||||
/// envelope/storage changes from this before guarded dispatch publishes.
|
||||
fn project(&self, _action: LayoutAction) -> PanelResult<Layout> {
|
||||
Err(error(Rule::Capability, "layout sink cannot stage commands"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LayoutService {
|
||||
identity: std::sync::Arc<()>,
|
||||
registry: PanelRegistry,
|
||||
layout: Layout,
|
||||
revision: u64,
|
||||
availability: AvailabilityMap,
|
||||
interaction: InteractionState,
|
||||
capabilities: HostCapabilities,
|
||||
identities: std::collections::BTreeMap<InstanceId, PanelKind>,
|
||||
}
|
||||
|
||||
/// An optimistic, fully validated candidate. Fields stay private so it cannot be forged.
|
||||
pub struct PreparedLayout {
|
||||
service_identity: std::sync::Arc<()>,
|
||||
base_revision: u64,
|
||||
next: Layout,
|
||||
interaction: InteractionState,
|
||||
effects: Vec<HostEffect>,
|
||||
changed: bool,
|
||||
availability: AvailabilityMap,
|
||||
identities: std::collections::BTreeMap<InstanceId, PanelKind>,
|
||||
}
|
||||
|
||||
impl PreparedLayout {
|
||||
pub fn layout(&self) -> &Layout {
|
||||
&self.next
|
||||
}
|
||||
pub fn effects(&self) -> &[HostEffect] {
|
||||
&self.effects
|
||||
}
|
||||
/// Runtime availability is staged with the same atomic layout commit.
|
||||
pub fn set_availability(&mut self, availability: AvailabilityMap) -> PanelResult<()> {
|
||||
validate_availability(&availability)?;
|
||||
self.changed |= self.availability != availability;
|
||||
self.availability = availability;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutService {
|
||||
pub fn new(registry: PanelRegistry, layout: Layout, capabilities: HostCapabilities) -> PanelResult<Self> {
|
||||
validate(&layout, ®istry)?;
|
||||
if capabilities.max_native_hosts > MAX_SECTIONS {
|
||||
return Err(error(Rule::CollectionLimit, "native capability exceeds section cap"));
|
||||
}
|
||||
// Restored native entries remain data even on web; resolve_geometry marks them
|
||||
// unpresented. New native mutations still require a capable adapter.
|
||||
Ok(Self {
|
||||
identity: std::sync::Arc::new(()),
|
||||
registry,
|
||||
identities: layout.instances.iter().map(|p| (p.id.clone(), p.kind.clone())).collect(),
|
||||
layout,
|
||||
revision: 0,
|
||||
availability: AvailabilityMap::new(),
|
||||
interaction: InteractionState::default(),
|
||||
capabilities,
|
||||
})
|
||||
}
|
||||
pub fn registry(&self) -> &PanelRegistry {
|
||||
&self.registry
|
||||
}
|
||||
pub fn layout(&self) -> &Layout {
|
||||
&self.layout
|
||||
}
|
||||
pub fn interaction(&self) -> &InteractionState {
|
||||
&self.interaction
|
||||
}
|
||||
pub fn capabilities(&self) -> &HostCapabilities {
|
||||
&self.capabilities
|
||||
}
|
||||
pub fn availability(&self, id: &InstanceId) -> Availability {
|
||||
self.availability.get(id).cloned().unwrap_or(Availability::Available)
|
||||
}
|
||||
pub fn set_availability(&mut self, values: AvailabilityMap) -> PanelResult<()> {
|
||||
validate_availability(&values)?;
|
||||
if self.availability != values {
|
||||
let revision = self.revision.checked_add(1).ok_or_else(|| error(Rule::Revision, "layout revision exhausted"))?;
|
||||
self.availability = values;
|
||||
self.revision = revision;
|
||||
self.reconcile_interaction();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn reconcile_interaction(&mut self) {
|
||||
let layout = &self.layout;
|
||||
let availability = &self.availability;
|
||||
let visible = |id: &InstanceId| {
|
||||
layout.instance(id).is_ok_and(|p| p.requested_open) && availability.get(id).is_none_or(|state| *state == Availability::Available)
|
||||
};
|
||||
if self.interaction.focused.as_ref().is_some_and(|id| !visible(id)) {
|
||||
self.interaction.focused = None;
|
||||
}
|
||||
if self.interaction.peek.as_ref().is_some_and(|id| !visible(id)) {
|
||||
self.interaction.peek = None;
|
||||
}
|
||||
}
|
||||
pub fn prepare(&self, action: LayoutAction) -> PanelResult<PreparedLayout> {
|
||||
let mut next = self.layout.clone();
|
||||
let mut interaction = self.interaction.clone();
|
||||
let mut effects = Vec::new();
|
||||
let mut availability = self.availability.clone();
|
||||
let mut destroyed = std::collections::BTreeSet::new();
|
||||
if let LayoutAction::Replace { expected_revision, layout } = &action {
|
||||
if expected_revision.is_some_and(|r| r != self.revision) {
|
||||
return Err(error(Rule::Revision, "stale layout revision"));
|
||||
}
|
||||
validate(layout, &self.registry)?;
|
||||
next = layout.clone();
|
||||
availability.clear();
|
||||
interaction = InteractionState::default();
|
||||
}
|
||||
if let LayoutAction::Apply { expected_revision, mutations } = action {
|
||||
if expected_revision.is_some_and(|r| r != self.revision) {
|
||||
return Err(error(Rule::Revision, "stale layout revision"));
|
||||
}
|
||||
if mutations.is_empty() || mutations.len() > MAX_MUTATIONS {
|
||||
return Err(error(Rule::CollectionLimit, "transaction requires 1..64 mutations"));
|
||||
}
|
||||
validate_lifecycle_intents(&mutations)?;
|
||||
for mutation in &mutations {
|
||||
if let Mutation::Destroy { instance } = mutation {
|
||||
destroyed.insert(instance.clone());
|
||||
}
|
||||
}
|
||||
for mutation in mutations {
|
||||
apply(&mut next, &self.registry, &self.availability, &self.capabilities, &mut interaction, &mut effects, mutation)?;
|
||||
// A bounded intermediate state cannot smuggle oversized collections into
|
||||
// a later mutation. Semantic invariants are checked at atomic commit.
|
||||
if next.instances.len() > MAX_INSTANCES || next.sections.len() > MAX_SECTIONS || next.sections.iter().any(|s| s.tabs.len() > MAX_TABS)
|
||||
{
|
||||
return Err(error(Rule::CollectionLimit, "transaction collection limit"));
|
||||
}
|
||||
}
|
||||
validate(&next, &self.registry)?;
|
||||
for before in &self.layout.instances {
|
||||
if next.instances.iter().any(|after| after.id == before.id && after.kind != before.kind) {
|
||||
return Err(error(Rule::DuplicateId, "transaction cannot reuse an instance for another kind"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut identities = self.identities.clone();
|
||||
for id in destroyed {
|
||||
identities.remove(&id);
|
||||
}
|
||||
for p in &next.instances {
|
||||
if identities.get(&p.id).is_some_and(|kind| *kind != p.kind) {
|
||||
return Err(error(Rule::DuplicateId, "instance identity cannot change kind across layouts/workspaces"));
|
||||
}
|
||||
identities.insert(p.id.clone(), p.kind.clone());
|
||||
}
|
||||
if identities.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "retained instance identity cap"));
|
||||
}
|
||||
// Native effects describe the committed difference, never intermediate windows.
|
||||
let old = native_hosts(&self.layout);
|
||||
let new = native_hosts(&next);
|
||||
for (host, section) in &new {
|
||||
if !old.iter().any(|(h, _)| h == host) {
|
||||
if !self.capabilities.native_windows || new.len() > self.capabilities.max_native_hosts {
|
||||
return Err(error(Rule::Capability, "native hosts unavailable or at capacity"));
|
||||
}
|
||||
effects.push(HostEffect::CreateNative { host: host.clone(), section: section.clone() });
|
||||
} else if self.layout.workspace != next.workspace || old.iter().any(|(h, s)| h == host && s != section) {
|
||||
if !self.capabilities.native_windows {
|
||||
return Err(error(Rule::Capability, "cannot rebind unsupported native host"));
|
||||
}
|
||||
effects.push(HostEffect::RebindNative { host: host.clone(), section: section.clone() });
|
||||
}
|
||||
}
|
||||
for (host, _) in old {
|
||||
if !new.iter().any(|(h, _)| *h == host) {
|
||||
effects.push(HostEffect::ReleaseNative { host });
|
||||
}
|
||||
}
|
||||
if interaction.focused.as_ref().is_some_and(|id| !next.containing(id).is_ok_and(|s| !s.collapsed && s.active == *id)) {
|
||||
interaction.focused = None;
|
||||
}
|
||||
if interaction
|
||||
.peek
|
||||
.as_ref()
|
||||
.is_some_and(|id| !next.instance(id).is_ok_and(|p| p.requested_open) || !next.containing(id).is_ok_and(|s| s.collapsed))
|
||||
{
|
||||
interaction.peek = None;
|
||||
}
|
||||
effects.retain(|effect| match effect {
|
||||
HostEffect::Focus { instance } => interaction.focused.as_ref() == Some(instance),
|
||||
HostEffect::Peek { instance } => interaction.peek.as_ref() == Some(instance),
|
||||
_ => true,
|
||||
});
|
||||
let changed = next != self.layout || interaction != self.interaction || availability != self.availability || !effects.is_empty();
|
||||
if changed && self.revision == u64::MAX {
|
||||
return Err(error(Rule::Revision, "layout revision exhausted"));
|
||||
}
|
||||
Ok(PreparedLayout {
|
||||
service_identity: self.identity.clone(),
|
||||
base_revision: self.revision,
|
||||
next,
|
||||
interaction,
|
||||
effects,
|
||||
changed,
|
||||
availability,
|
||||
identities,
|
||||
})
|
||||
}
|
||||
pub fn commit(&mut self, prepared: PreparedLayout) -> PanelResult<LayoutReply> {
|
||||
if !std::sync::Arc::ptr_eq(&prepared.service_identity, &self.identity) || prepared.base_revision != self.revision {
|
||||
return Err(error(Rule::Revision, "candidate became stale"));
|
||||
}
|
||||
if prepared.changed {
|
||||
self.revision = self.revision.checked_add(1).ok_or_else(|| error(Rule::Revision, "layout revision exhausted"))?;
|
||||
}
|
||||
self.layout = prepared.next;
|
||||
self.interaction = prepared.interaction;
|
||||
self.availability = prepared.availability;
|
||||
self.identities = prepared.identities;
|
||||
self.reconcile_interaction();
|
||||
let mut reply = self.inspect();
|
||||
reply.effects = prepared.effects;
|
||||
Ok(reply)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_availability(values: &AvailabilityMap) -> PanelResult<()> {
|
||||
if values.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "availability map full"));
|
||||
}
|
||||
for (id, state) in values {
|
||||
valid_id(&id.0)?;
|
||||
if let Availability::Unavailable { reason } = state
|
||||
&& (reason.is_empty() || reason.len() > 256)
|
||||
{
|
||||
return Err(error(Rule::Availability, "availability reason must contain 1..256 bytes"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close/Destroy are explicit, irreversible content intents. Do not infer them
|
||||
/// solely from net layout differences, or permit later mutations to erase them.
|
||||
pub fn validate_lifecycle_intents(mutations: &[Mutation]) -> PanelResult<()> {
|
||||
if mutations.len() > MAX_MUTATIONS {
|
||||
return Err(error(Rule::CollectionLimit, "lifecycle intent batch cap"));
|
||||
}
|
||||
let mut counts = std::collections::BTreeMap::<&InstanceId, (usize, bool)>::new();
|
||||
for mutation in mutations {
|
||||
let (id, terminal) = match mutation {
|
||||
Mutation::Close { instance } | Mutation::Destroy { instance } => (instance, true),
|
||||
Mutation::Open { instance, .. }
|
||||
| Mutation::Move { instance, .. }
|
||||
| Mutation::Activate { instance }
|
||||
| Mutation::Focus { instance }
|
||||
| Mutation::Peek { instance } => (instance, false),
|
||||
_ => continue,
|
||||
};
|
||||
let entry = counts.entry(id).or_default();
|
||||
entry.0 += 1;
|
||||
entry.1 |= terminal;
|
||||
if entry.1 && entry.0 > 1 {
|
||||
return Err(error(Rule::Lifecycle, "Close/Destroy cannot share a batch with another operation on that instance"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl ActionSink for LayoutService {
|
||||
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
|
||||
Ok(self.prepare(action)?.layout().clone())
|
||||
}
|
||||
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
let prepared = self.prepare(action)?;
|
||||
self.commit(prepared)
|
||||
}
|
||||
fn inspect(&self) -> LayoutReply {
|
||||
LayoutReply {
|
||||
api_version: PANEL_API_VERSION,
|
||||
revision: self.revision,
|
||||
layout: self.layout.clone(),
|
||||
interaction: self.interaction.clone(),
|
||||
effects: Vec::new(),
|
||||
capabilities: self.capabilities.clone(),
|
||||
availability: self.availability.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn native_hosts(layout: &Layout) -> Vec<(HostId, SectionId)> {
|
||||
layout
|
||||
.sections
|
||||
.iter()
|
||||
.filter_map(|s| match &s.location {
|
||||
SectionLocation::Window { host, .. } => Some((host.clone(), s.id.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn available(map: &AvailabilityMap, id: &InstanceId) -> PanelResult<()> {
|
||||
if let Some(state) = map.get(id) {
|
||||
state.require()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn section_mut<'a>(layout: &'a mut Layout, id: &SectionId) -> PanelResult<&'a mut Section> {
|
||||
layout.sections.iter_mut().find(|s| s.id == *id).ok_or_else(|| error(Rule::MissingTarget, "section not found"))
|
||||
}
|
||||
|
||||
fn remember(layout: &mut Layout, id: &InstanceId) -> PanelResult<()> {
|
||||
let section = layout.containing(id)?.clone();
|
||||
let section_index = layout.sections.iter().position(|s| s.id == section.id).ok_or_else(|| error(Rule::MissingTarget, "section not found"))?;
|
||||
let tab_index = section.tabs.iter().position(|p| p == id).ok_or_else(|| error(Rule::MissingTarget, "tab not found"))?;
|
||||
let p = layout.instances.iter_mut().find(|p| p.id == *id).ok_or_else(|| error(Rule::MissingTarget, "instance not found"))?;
|
||||
p.memory = PlacementMemory {
|
||||
section: section.id,
|
||||
location: section.location,
|
||||
section_index,
|
||||
tab_index,
|
||||
size: section.size,
|
||||
collapsed: section.collapsed,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn detach(layout: &mut Layout, id: &InstanceId) {
|
||||
for s in &mut layout.sections {
|
||||
s.tabs.retain(|p| p != id);
|
||||
if s.active == *id
|
||||
&& let Some(first) = s.tabs.first()
|
||||
{
|
||||
s.active = first.clone();
|
||||
}
|
||||
}
|
||||
layout.sections.retain(|s| !s.tabs.is_empty());
|
||||
}
|
||||
|
||||
fn place(layout: &mut Layout, id: &InstanceId, destination: Destination) -> PanelResult<()> {
|
||||
match destination {
|
||||
Destination::NewSection { section, index, location, size } => {
|
||||
valid_id(§ion.0)?;
|
||||
location.validate()?;
|
||||
size.validate()?;
|
||||
if layout.sections.iter().any(|s| s.id == section) {
|
||||
return Err(error(Rule::DuplicateId, "new-section identity already exists"));
|
||||
}
|
||||
if index > layout.sections.len() {
|
||||
return Err(error(Rule::Bounds, "section insertion index out of bounds"));
|
||||
}
|
||||
layout.sections.insert(index, Section { id: section, location, tabs: vec![id.clone()], active: id.clone(), size, collapsed: false });
|
||||
}
|
||||
Destination::JoinTab { section, index } => {
|
||||
let s = section_mut(layout, §ion)?;
|
||||
if index > s.tabs.len() {
|
||||
return Err(error(Rule::Bounds, "tab insertion index out of bounds"));
|
||||
}
|
||||
s.tabs.insert(index, id.clone());
|
||||
// Joining never steals active tab or resizes the group.
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reopen_destination(layout: &Layout, p: &PanelInstance) -> Destination {
|
||||
if let Ok(s) = layout.section(&p.memory.section) {
|
||||
Destination::JoinTab { section: s.id.clone(), index: p.memory.tab_index.min(s.tabs.len()) }
|
||||
} else {
|
||||
Destination::NewSection {
|
||||
section: p.memory.section.clone(),
|
||||
index: p.memory.section_index.min(layout.sections.len()),
|
||||
location: p.memory.location.clone(),
|
||||
size: p.memory.size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(
|
||||
layout: &mut Layout,
|
||||
registry: &PanelRegistry,
|
||||
availability: &AvailabilityMap,
|
||||
caps: &HostCapabilities,
|
||||
interaction: &mut InteractionState,
|
||||
effects: &mut Vec<HostEffect>,
|
||||
mutation: Mutation,
|
||||
) -> PanelResult<()> {
|
||||
match mutation {
|
||||
Mutation::Open { kind, instance, destination } => {
|
||||
valid_id(&instance.0)?;
|
||||
registry.get(&kind)?;
|
||||
available(availability, &instance)?;
|
||||
if let Ok(existing) = layout.instance(&instance) {
|
||||
if existing.kind != kind {
|
||||
return Err(error(Rule::DuplicateId, "instance belongs to another kind"));
|
||||
}
|
||||
if existing.requested_open {
|
||||
if destination.is_some() {
|
||||
return Err(error(Rule::Placement, "use Move for an open instance"));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let p = existing.clone();
|
||||
let restore_collapsed = destination.is_none() && layout.section(&p.memory.section).is_err();
|
||||
let destination = destination.unwrap_or_else(|| reopen_destination(layout, &p));
|
||||
place(layout, &instance, destination)?;
|
||||
if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) {
|
||||
entry.requested_open = true;
|
||||
}
|
||||
if restore_collapsed && let Some(s) = layout.sections.iter_mut().find(|s| s.id == p.memory.section) {
|
||||
s.collapsed = p.memory.collapsed;
|
||||
}
|
||||
} else {
|
||||
let destination = destination.ok_or_else(|| error(Rule::Placement, "new instance requires explicit destination"))?;
|
||||
place(layout, &instance, destination)?;
|
||||
let s = layout.containing(&instance)?.clone();
|
||||
layout.instances.push(PanelInstance {
|
||||
id: instance.clone(),
|
||||
kind,
|
||||
requested_open: true,
|
||||
memory: PlacementMemory {
|
||||
section: s.id,
|
||||
location: s.location,
|
||||
section_index: 0,
|
||||
tab_index: 0,
|
||||
size: s.size,
|
||||
collapsed: s.collapsed,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
Mutation::Close { instance } => {
|
||||
let p = layout.instance(&instance)?;
|
||||
if !registry.get(&p.kind)?.features.closable {
|
||||
return Err(error(Rule::FeatureDisabled, "panel is not closable"));
|
||||
}
|
||||
if p.requested_open {
|
||||
remember(layout, &instance)?;
|
||||
detach(layout, &instance);
|
||||
if let Some(p) = layout.instances.iter_mut().find(|p| p.id == instance) {
|
||||
p.requested_open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Mutation::Destroy { instance } => {
|
||||
if layout.instance(&instance)?.requested_open {
|
||||
return Err(error(Rule::Lifecycle, "close before owner destruction"));
|
||||
}
|
||||
layout.instances.retain(|p| p.id != instance);
|
||||
}
|
||||
Mutation::Move { instance, destination } => {
|
||||
if !layout.instance(&instance)?.requested_open {
|
||||
return Err(error(Rule::Placement, "cannot move a closed instance"));
|
||||
}
|
||||
let collapsed = layout.containing(&instance)?.collapsed;
|
||||
remember(layout, &instance)?;
|
||||
detach(layout, &instance);
|
||||
let new_section = match &destination {
|
||||
Destination::NewSection { section, .. } => Some(section.clone()),
|
||||
_ => None,
|
||||
};
|
||||
place(layout, &instance, destination)?;
|
||||
if let Some(id) = new_section {
|
||||
section_mut(layout, &id)?.collapsed = collapsed;
|
||||
}
|
||||
}
|
||||
Mutation::Activate { instance } => {
|
||||
available(availability, &instance)?;
|
||||
let section = layout.containing(&instance)?.id.clone();
|
||||
section_mut(layout, §ion)?.active = instance;
|
||||
}
|
||||
Mutation::Focus { instance } => {
|
||||
available(availability, &instance)?;
|
||||
let p = layout.instance(&instance)?.clone();
|
||||
if !p.requested_open {
|
||||
let destination = reopen_destination(layout, &p);
|
||||
place(layout, &instance, destination)?;
|
||||
if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) {
|
||||
entry.requested_open = true;
|
||||
}
|
||||
}
|
||||
let section = layout.containing(&instance)?.id.clone();
|
||||
let s = section_mut(layout, §ion)?;
|
||||
s.active = instance.clone();
|
||||
s.collapsed = false;
|
||||
interaction.peek = None;
|
||||
interaction.focused = Some(instance.clone());
|
||||
effects.push(HostEffect::Focus { instance });
|
||||
}
|
||||
Mutation::Peek { instance } => {
|
||||
available(availability, &instance)?;
|
||||
let s = layout.containing(&instance)?;
|
||||
if !s.collapsed {
|
||||
return Err(error(Rule::Placement, "peek requires a collapsed section"));
|
||||
}
|
||||
interaction.peek = Some(instance.clone());
|
||||
effects.push(HostEffect::Peek { instance });
|
||||
}
|
||||
Mutation::DismissPeek => {
|
||||
interaction.peek = None;
|
||||
effects.push(HostEffect::DismissPeek);
|
||||
}
|
||||
Mutation::Collapse { section, collapsed } => {
|
||||
section_mut(layout, §ion)?.collapsed = collapsed;
|
||||
}
|
||||
Mutation::SetSize { section, size } => {
|
||||
size.validate()?;
|
||||
section_mut(layout, §ion)?.size = size;
|
||||
}
|
||||
Mutation::ResizePair { first, second, first_size, second_size } => {
|
||||
first_size.validate()?;
|
||||
second_size.validate()?;
|
||||
let (a, b, zone) = pair(layout, &first, &second)?;
|
||||
let sum = |a: Size, b: Size| if zone == Zone::Bottom { a.width + b.width } else { a.height + b.height };
|
||||
if (sum(a.size, b.size) - sum(first_size, second_size)).abs() > 0.01 {
|
||||
return Err(error(Rule::Bounds, "paired sash must conserve shared extent"));
|
||||
}
|
||||
if zone == Zone::Bottom && (first_size.height != a.size.height || second_size.height != b.size.height)
|
||||
|| zone != Zone::Bottom && (first_size.width != a.size.width || second_size.width != b.size.width)
|
||||
{
|
||||
return Err(error(Rule::Bounds, "paired sash changes only split axis"));
|
||||
}
|
||||
section_mut(layout, &first)?.size = first_size;
|
||||
section_mut(layout, &second)?.size = second_size;
|
||||
}
|
||||
Mutation::ResetPair { first, second } => {
|
||||
let (a, b, zone) = pair(layout, &first, &second)?;
|
||||
let mut a_size = a.size;
|
||||
let mut b_size = b.size;
|
||||
let (a_min, a_max) = tab_bounds(layout, registry, a)?;
|
||||
let (b_min, b_max) = tab_bounds(layout, registry, b)?;
|
||||
let axis = |s: Size| if zone == Zone::Bottom { s.width } else { s.height };
|
||||
let extent = axis(a_size) + axis(b_size);
|
||||
let lo = axis(a_min).max(extent - axis(b_max));
|
||||
let hi = axis(a_max).min(extent - axis(b_min));
|
||||
if lo > hi {
|
||||
return Err(error(Rule::Bounds, "pair cannot satisfy defaults within bounds"));
|
||||
}
|
||||
let a_default = registry.get(&layout.instance(&a.active)?.kind)?.default_size;
|
||||
let b_default = registry.get(&layout.instance(&b.active)?.kind)?.default_size;
|
||||
let preferred = extent * axis(a_default) / (axis(a_default) + axis(b_default));
|
||||
let split = preferred.clamp(lo, hi);
|
||||
if zone == Zone::Bottom {
|
||||
a_size.width = split;
|
||||
b_size.width = extent - split;
|
||||
} else {
|
||||
a_size.height = split;
|
||||
b_size.height = extent - split;
|
||||
}
|
||||
section_mut(layout, &first)?.size = a_size;
|
||||
section_mut(layout, &second)?.size = b_size;
|
||||
}
|
||||
Mutation::NativeClose { host } => {
|
||||
valid_id(&host.0)?;
|
||||
let index = layout
|
||||
.sections
|
||||
.iter()
|
||||
.position(|s| matches!(&s.location, SectionLocation::Window { host: h, .. } if *h == host))
|
||||
.ok_or_else(|| error(Rule::MissingTarget, "native host not found"))?;
|
||||
let mut section = layout.sections.remove(index);
|
||||
let SectionLocation::Window { return_to, .. } = section.location else {
|
||||
return Err(error(Rule::Placement, "not a native section"));
|
||||
};
|
||||
if let Some(join) = &return_to.join
|
||||
&& let Some(target) = layout.sections.iter_mut().find(|s| s.id == join.section && s.location.zone() == return_to.zone)
|
||||
{
|
||||
if target.tabs.len().saturating_add(section.tabs.len()) > MAX_TABS {
|
||||
return Err(error(Rule::CollectionLimit, "native return tab capacity"));
|
||||
}
|
||||
let index = join.index.min(target.tabs.len());
|
||||
drop(target.tabs.splice(index..index, section.tabs));
|
||||
return Ok(());
|
||||
}
|
||||
section.location = SectionLocation::Dock { zone: return_to.zone };
|
||||
section.size = return_to.size;
|
||||
section.collapsed = return_to.collapsed;
|
||||
layout.sections.insert(return_to.index.min(layout.sections.len()), section);
|
||||
}
|
||||
}
|
||||
let windows = native_hosts(layout);
|
||||
// Retained unsupported windows can be closed/redocked without native capability.
|
||||
if caps.native_windows && windows.len() > caps.max_native_hosts {
|
||||
return Err(error(Rule::Capability, "native host limit"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pair<'a>(layout: &'a Layout, first: &SectionId, second: &SectionId) -> PanelResult<(&'a Section, &'a Section, Zone)> {
|
||||
if first == second {
|
||||
return Err(error(Rule::Placement, "sash requires two distinct neighbours"));
|
||||
}
|
||||
let a = layout.section(first)?;
|
||||
let b = layout.section(second)?;
|
||||
let zone = a.location.zone();
|
||||
let edge: Vec<_> = layout.sections.iter().filter(|s| s.location.zone() == zone).collect();
|
||||
if !zone.docked()
|
||||
|| b.location.zone() != zone
|
||||
|| !edge.windows(2).any(|p| p.first().is_some_and(|s| s.id == *first) && p.get(1).is_some_and(|s| s.id == *second))
|
||||
{
|
||||
return Err(error(Rule::Placement, "sash requires ordered neighbours in one dock"));
|
||||
}
|
||||
Ok((a, b, zone))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -68,6 +68,7 @@ pub mod joints;
|
||||
pub mod libraries;
|
||||
pub mod mass_properties;
|
||||
pub mod motion;
|
||||
pub mod panels;
|
||||
pub mod print_face;
|
||||
pub mod render;
|
||||
pub mod render_lights;
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Strict external application-layout contracts. These are command parameters,
|
||||
//! not another persistent layout model.
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::panels::*;
|
||||
|
||||
/// Discovery and ParamCheck use the exact parser the injected executor uses.
|
||||
pub struct CommandContract<P> {
|
||||
id: &'static str,
|
||||
typed: super::TypedContract<P>,
|
||||
}
|
||||
impl<P> CommandContract<P> {
|
||||
pub const fn new(id: &'static str) -> Self {
|
||||
Self { id, typed: super::TypedContract::new() }
|
||||
}
|
||||
}
|
||||
impl<P: serde::de::DeserializeOwned + JsonSchema + 'static> super::Contract for CommandContract<P> {
|
||||
fn input_schema(&self) -> schemars::Schema {
|
||||
super::Contract::input_schema(&self.typed)
|
||||
}
|
||||
fn allowed_keys(&self) -> std::sync::Arc<std::collections::BTreeSet<String>> {
|
||||
super::Contract::allowed_keys(&self.typed)
|
||||
}
|
||||
fn check(&self, params: &serde_json::Value) -> Vec<super::Issue> {
|
||||
match crate::panels::commands::parse_command(self.id, params) {
|
||||
Ok(_) => Vec::new(),
|
||||
Err(reason) => {
|
||||
// Keep the shared parser's bounds ahead of deserialization, but
|
||||
// retain ordinary contract paths and unknown-key suggestions.
|
||||
if reason.rule == Rule::Schema {
|
||||
let issues = super::Contract::check(&self.typed, params);
|
||||
if !issues.is_empty() {
|
||||
return issues;
|
||||
}
|
||||
}
|
||||
vec![super::Issue { path: String::new(), message: reason.to_string(), suggestion: None }]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", content = "id", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Target {
|
||||
Workspace(WorkspaceId),
|
||||
Instance(InstanceId),
|
||||
Section(SectionId),
|
||||
NativeHost(HostId),
|
||||
}
|
||||
impl From<Target> for LayoutTarget {
|
||||
fn from(value: Target) -> Self {
|
||||
match value {
|
||||
Target::Workspace(id) => Self::Workspace(id),
|
||||
Target::Instance(id) => Self::Instance(id),
|
||||
Target::Section(id) => Self::Section(id),
|
||||
Target::NativeHost(id) => Self::NativeHost(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OuterSize {
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
impl From<OuterSize> for Size {
|
||||
fn from(value: OuterSize) -> Self {
|
||||
Self { width: value.width, height: value.height }
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Origin {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
}
|
||||
impl From<Origin> for Point {
|
||||
fn from(value: Origin) -> Self {
|
||||
Self { x: value.x, y: value.y }
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ReturnJoin {
|
||||
pub section: SectionId,
|
||||
pub index: usize,
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ReturnTo {
|
||||
pub zone: Zone,
|
||||
pub index: usize,
|
||||
pub size: OuterSize,
|
||||
pub collapsed: bool,
|
||||
#[serde(default)]
|
||||
pub join: Option<ReturnJoin>,
|
||||
}
|
||||
impl From<ReturnTo> for DockReturn {
|
||||
fn from(value: ReturnTo) -> Self {
|
||||
Self {
|
||||
zone: value.zone,
|
||||
index: value.index,
|
||||
size: value.size.into(),
|
||||
collapsed: value.collapsed,
|
||||
join: value.join.map(|join| ReturnTab { section: join.section, index: join.index }),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Location {
|
||||
Dock { zone: Zone },
|
||||
Floating { origin: Origin },
|
||||
Window { host: HostId, origin: Origin, return_to: ReturnTo },
|
||||
}
|
||||
impl From<Location> for SectionLocation {
|
||||
fn from(value: Location) -> Self {
|
||||
match value {
|
||||
Location::Dock { zone } => Self::Dock { zone },
|
||||
Location::Floating { origin } => Self::Floating { origin: origin.into() },
|
||||
Location::Window { host, origin, return_to } => Self::Window { host, origin: origin.into(), return_to: return_to.into() },
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Placement {
|
||||
NewSection { section: SectionId, index: usize, location: Location, size: OuterSize },
|
||||
JoinTab { section: SectionId, index: usize },
|
||||
}
|
||||
impl From<Placement> for Destination {
|
||||
fn from(value: Placement) -> Self {
|
||||
match value {
|
||||
Placement::NewSection { section, index, location, size } => {
|
||||
Self::NewSection { section, index, location: location.into(), size: size.into() }
|
||||
}
|
||||
Placement::JoinTab { section, index } => Self::JoinTab { section, index },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Empty {}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Open {
|
||||
pub kind: PanelKind,
|
||||
pub instance: InstanceId,
|
||||
pub destination: Option<Placement>,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Select {
|
||||
pub target: Option<Target>,
|
||||
/// Compatibility selector: exact instance, or a single-instance canonical kind.
|
||||
pub id: Option<String>,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Move {
|
||||
pub target: Option<Target>,
|
||||
pub id: Option<String>,
|
||||
pub destination: Placement,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Resize {
|
||||
pub target: Option<Target>,
|
||||
pub id: Option<String>,
|
||||
pub size: OuterSize,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Collapse {
|
||||
pub target: Option<Target>,
|
||||
pub id: Option<String>,
|
||||
pub collapsed: bool,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Revision {
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResizePair {
|
||||
pub first: SectionId,
|
||||
pub second: SectionId,
|
||||
pub first_size: OuterSize,
|
||||
pub second_size: OuterSize,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResetPair {
|
||||
pub first: SectionId,
|
||||
pub second: SectionId,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Save {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub overwrite: bool,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Apply {
|
||||
pub name: String,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WorkspaceSelect {
|
||||
pub workspace: WorkspaceId,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WorkspaceSummary {
|
||||
pub id: WorkspaceId,
|
||||
pub title_key: String,
|
||||
pub default_preset: String,
|
||||
pub has_remembered_layout: bool,
|
||||
}
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct GetReply {
|
||||
pub state: LayoutReply,
|
||||
pub workspaces: Vec<WorkspaceSummary>,
|
||||
}
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ListReply {
|
||||
pub state: LayoutReply,
|
||||
pub kinds: Vec<PanelSpec>,
|
||||
}
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SaveReply {
|
||||
pub name: String,
|
||||
pub overwritten: bool,
|
||||
pub state: LayoutReply,
|
||||
}
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WorkspaceSource {
|
||||
Remembered,
|
||||
DefaultPreset,
|
||||
Unchanged,
|
||||
}
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WorkspaceReply {
|
||||
pub previous_workspace: WorkspaceId,
|
||||
pub source: WorkspaceSource,
|
||||
pub state: LayoutReply,
|
||||
}
|
||||
|
||||
/// Successful wire replies have no extensible object fields. Maps (availability)
|
||||
/// remain maps. Persistence schemas intentionally retain their own opaque fields.
|
||||
pub fn strict_output<T: JsonSchema>() -> schemars::Schema {
|
||||
let mut schema = super::output_schema_for::<T>();
|
||||
fn seal(value: &mut serde_json::Value) {
|
||||
match value {
|
||||
serde_json::Value::Object(object) => {
|
||||
if object.contains_key("properties") {
|
||||
object.insert("additionalProperties".into(), false.into());
|
||||
}
|
||||
for value in object.values_mut() {
|
||||
seal(value);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(values) => values.iter_mut().for_each(seal),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(object) = schema.as_object_mut() {
|
||||
if object.contains_key("properties") {
|
||||
object.insert("additionalProperties".into(), false.into());
|
||||
}
|
||||
for value in object.values_mut() {
|
||||
seal(value);
|
||||
}
|
||||
}
|
||||
schema
|
||||
}
|
||||
@@ -1182,7 +1182,7 @@ fn only_own_ids_name_commands() {
|
||||
fn unknown_commands_suggest_the_closest_ids() {
|
||||
let mut s = Session::default();
|
||||
let mut msg = |id: &str| s.execute(id, &serde_json::json!({})).unwrap_err().to_string();
|
||||
assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open`?)");
|
||||
assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open` or `panel.open`?)");
|
||||
assert!(msg("solid.extrud").starts_with("unknown command `solid.extrud` (did you mean `solid.extrude`"), "{}", msg("solid.extrud"));
|
||||
assert!(msg("Extrude").contains("`solid.extrude`"), "{}", msg("Extrude"));
|
||||
assert_eq!(msg("FusionFilletEdgesCommand"), "unknown command `FusionFilletEdgesCommand`");
|
||||
|
||||
Reference in New Issue
Block a user