Compare commits

..
Author SHA1 Message Date
sorokin.oleg.edu c06a953b97 Sync agent instructions from main 2026-09-13 11:39:13 +03:00
sorokin.oleg.edu 7dcfb3cb10 WIP: save unverified diagram Delete candidate at user pause 2026-09-12 04:53:12 -07:00
sorokin.oleg.edu 5a7018117d Archive combined Windows allocation and repair baseline with review limits 2026-09-12 04:27:56 -07:00
sorokin.oleg.edu 85173a3c95 Refine allocation feedback to preserve collapsed-target reachability 2026-09-12 04:26:05 -07:00
sorokin.oleg.edu d9b3f0dc91 Format saved allocation readability regressions 2026-09-12 04:18:42 -07:00
sorokin.oleg.edu 94b5eecb1c Merge remote-tracking branch 'refs/remotes/gitea/release1-956atf' into codex/behavior-authoring-20260910 2026-09-12 04:18:04 -07:00
sorokin.oleg.edu 6b9cc77ece Save unverified allocation and repair work at user-requested pause 2026-09-12 04:01:44 -07:00
sorokin.oleg.edu bc8bc4f5a1 Archive exact a31b40d Windows and OA native acceptance evidence 2026-09-12 03:54:36 -07:00
sorokin.oleg.edu f52d81c1b9 Integrate allocation drag candidate with guarded input and atomic history 2026-09-12 03:47:45 -07:00
sorokin.oleg.edu 97c91cc06c Sync agent instructions from main 2026-09-12 13:43:41 +03:00
sorokin.oleg.edu 0bd7886608 Merge branch 'codex/behavior-authoring-20260910' of http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio into codex/behavior-authoring-20260910 2026-09-12 03:43:17 -07:00
sorokin.oleg.edu 563772dc62 Sync agent instructions from main 2026-09-12 13:43:11 +03:00
sorokin.oleg.edu eefdedaf47 Merge 2026-09-12 03:41:44 -07:00
sorokin.oleg.edu bc88acd932 Sync agent instructions from main 2026-09-12 13:40:24 +03:00
sorokin.oleg.edu 17d56c06f7 Sync agent instructions from main 2026-09-12 13:39:54 +03:00
sorokin.oleg.edu bcb7057ab2 Sync agent instructions from main 2026-09-12 13:16:01 +03:00
sorokin.oleg.edu 36eff7225a Sync agent instructions from main 2026-09-12 13:15:23 +03:00
sorokin.oleg.edu dd38c46a4b Record user pause and exact Windows acceptance handoff 2026-09-11 12:28:15 -07:00
sorokin.oleg.edu a31b40d0f8 Retire obsolete behavior canvas scroll and tool paths 2026-09-11 11:28:08 -07:00
sorokin.oleg.edu 88c17a448f Record verified canvas union gates and allocation drag contract 2026-09-11 11:24:41 -07:00
sorokin.oleg.edu abffa4b3f0 Simplify canvas control focus guard for strict lint 2026-09-11 11:08:37 -07:00
sorokin.oleg.edu 82fd0acf64 Update behavior guide for canvas palette and camera controls 2026-09-11 11:03:39 -07:00
sorokin.oleg.edu ff0175488a Keep concrete canvas App access within the desktop crate 2026-09-11 10:55:15 -07:00
sorokin.oleg.edu 06ec962129 Adapt mounted canvas tests to installed renderer and workflow APIs 2026-09-11 10:48:35 -07:00
sorokin.oleg.edu 6969c825a8 Integrate shared behavior canvas with current form focus and recovery 2026-09-11 10:45:44 -07:00
sorokin.oleg.edu 638d06c4e3 Merge remote-tracking branch 'gitea/release1-956atf' into codex/behavior-authoring-20260910 2026-09-11 10:30:29 -07:00
sorokin.oleg.edu 41fa5d530c Record Windows scenario and codec gates with shared handoff 2026-09-11 10:29:03 -07:00
sorokin.oleg.edu 828c50c491 Merge updated user goal and shared working agreement 2026-09-11 10:05:23 -07:00
sorokin.oleg.edu f8a6a5264a Sync agent instructions from main 2026-09-11 19:52:09 +03:00
sorokin.oleg.edu b4c8fd7102 Sync agent instructions from main 2026-09-11 19:51:34 +03:00
Codex e7491fb00a test(desktop): preserve final 720-test and strict lint acceptance 2026-09-11 09:25:52 -07:00
Codex bef1ea33e4 docs(harness): record Windows gates and defer Linux execution 2026-09-11 09:12:30 -07:00
Codex 3c9e6eeb64 fix(review): keep workflow messages compact 2026-09-11 09:08:46 -07:00
Codex 80f2588214 fix(forms): reset replacement sessions and preserve visible scroll 2026-09-11 08:33:06 -07:00
Codex 8895dd2e0f fix(scenario): restore focus only to the current parent form 2026-09-11 08:07:41 -07:00
Codex 8d55d2d2eb Save complete restart handoff for user-requested reboot 2026-09-11 06:47:37 -07:00
Codex 03d20ec296 Preserve exact numeric gate logs and bounded decoder review 2026-09-11 06:41:33 -07:00
sorokin.oleg.edu c0e66f94e3 Stage explicit prerequisite sources inside behavior creation forms 2026-09-11 06:26:16 -07:00
Codex 7f081ad457 Integrate scoped reference chooser and scenario form focus and reveal 2026-09-11 06:24:20 -07:00
Codex c7ed894900 Merge shared instruction checkpoint preserving exact authoritative goal 2026-09-11 06:14:11 -07:00
Codex 98427b9620 Adopt shared Gitea and harness maintenance instructions 2026-09-11 06:14:05 -07:00
sorokin.oleg.edu cab01c3d7f Sync agent instructions from main 2026-09-11 15:55:34 +03:00
sorokin.oleg.edu d8bdbd9e48 Sync agent instructions from main 2026-09-11 15:55:01 +03:00
Codex 7d14bd0dd1 Add exact analysis numbers units and bounded request work 2026-09-11 05:50:45 -07:00
Codex dc0f2e12f3 Import corrected creation oracle and record exact SA action history 2026-09-11 05:41:06 -07:00
sorokin.oleg.edu bc311bc076 Add source-first CLI with guarded writes and reviewed evidence 2026-09-11 05:27:16 -07:00
Codex a34558d3be Record OA native history and ratified analysis library decisions 2026-09-11 05:21:37 -07:00
Codex 2cc4d115d0 Specify baseline analysis and verified library contract compatibility 2026-09-11 04:48:44 -07:00
sorokin.oleg.edu 1e9f0c2a97 Sync agent instructions from main 2026-09-11 14:34:18 +03:00
sorokin.oleg.edu 1516949567 Add named behavior creation and verified textual authoring examples 2026-09-11 04:26:56 -07:00
Codex c4e1580bb0 Exercise bounded reference chooser with mounted input tests 2026-09-11 02:29:15 -07:00
2055 changed files with 124824 additions and 173135 deletions
+28 -48
View File
@@ -22,65 +22,45 @@ harness/history/2026-09-06-ledgers-before-consolidation/** -text
harness/history/2026-09-10-ledgers-before-continuation-refresh/** -text
harness/history/2026-09-10-ledgers-before-second-consolidation/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
harness/experiments/textual-authoring-20260911-local/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
harness/history/2026-09-11-ytr83r-integration/** -text whitespace=cr-at-eol
crates/oa-desktop/src/recovery/fixtures/*.json -text
crates/oa-core/src/analysis_numeric/fixtures/** -text whitespace=cr-at-eol
harness/fixtures/source7-native/** -text
harness/fixtures/basic-editing/** -text
harness/fixtures/scenario-authoring/base/** -text whitespace=cr-at-eol
harness/experiments/textual-authoring-20260911/** -text whitespace=cr-at-eol
harness/experiments/textual-authoring-20260911/observed/split-entry.arcadia whitespace=-blank-at-eol,cr-at-eol
harness/experiments/analysis-context-20260911/** -text whitespace=cr-at-eol
harness/experiments/constructor-defaults-20260911/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
harness/experiments/constructor-defaults-20260911/results/*.arcadia whitespace=-blank-at-eol,cr-at-eol
harness/experiments/behavior-creation-native-20260911/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
harness/experiments/analysis-baseline-20260911/** -text whitespace=cr-at-eol
harness/experiments/library-compatibility-20260911/** -text whitespace=cr-at-eol
harness/experiments/refined-contracts-review-20260911/** -text whitespace=cr-at-eol
harness/behavior-creation-contract.rs -text whitespace=cr-at-eol
harness/experiments/source-cli-independent-20260911/** -text whitespace=cr-at-eol
harness/fixtures/scenario-lifecycle-native/**/*.arcadia -text whitespace=cr-at-eol
harness/experiments/lifecycle-native-ytr83r-20260911/** -text whitespace=cr-at-eol
harness/experiments/lifecycle-native-ytr83r-20260911/*.log -text -whitespace
harness/experiments/lifecycle-native-ui-oa-20260911/** -text -whitespace
harness/experiments/lifecycle-native-ui-sa-20260911/** -text -whitespace
harness/experiments/wsl-postboot-ytr83r-20260911/** -text -whitespace
harness/experiments/authoring-prerelease-20260911/** -text whitespace=cr-at-eol
harness/experiments/cli-packaging-20260911/** -text whitespace=cr-at-eol
harness/experiments/cli-prerelease-20260911/** -text whitespace=cr-at-eol
harness/experiments/contextual-source-20260911/** -text whitespace=cr-at-eol
harness/experiments/contextual-source-20260911/**/*.log whitespace=-blank-at-eof,cr-at-eol
harness/fixtures/staged-source-authoring/** -text whitespace=cr-at-eol
harness/staged-source-authoring-contract.rs -text whitespace=cr-at-eol
# Preserve checksum-bound font notices verbatim through Git round trips.
scripts/windows-notices/GNOME-Cantarell-61362600e104-COPYING -text
scripts/windows-notices/Fira-OFL.txt -text
scripts/windows-notices/FiraSans-Regular-NOTICE.txt -text
scripts/windows-notices/llvm-6dfe1677ab8d-libunwind-LICENSE.TXT -text
harness/experiments/lifecycle-header-overflow-before-20260911/** -text -whitespace
harness/history/2026-09-11-ytr83r-record-migration/STATE-before.md -text -whitespace
harness/fixtures/staged-source-authoring/** -text whitespace=cr-at-eol
harness/staged-source-authoring-contract.rs -text whitespace=cr-at-eol
harness/experiments/contextual-lifecycle-integration-ytr83r-20260911/** -text -whitespace
harness/experiments/windows-runtime-321897f-20260911/** -text -whitespace
harness/child-work-native-contract.rs -text whitespace=cr-at-eol
harness/fixtures/child-work-native/** -text whitespace=cr-at-eol
harness/experiments/windows-gates-865483b-20260911/** -text -whitespace
harness/experiments/native-child-oa-865483b-20260911/** -text -whitespace
harness/experiments/packaged-server-865483b-20260911/** -text -whitespace
harness/experiments/canvas-union-a57c334-20260911/** -text -whitespace
harness/experiments/windows-gates-a57c334-20260911/** -text -whitespace
harness/experiments/native-child-continuation-865483b-20260911/** -text -whitespace
harness/experiments/lifecycle-header-correction-native-865483b-20260911/** -text -whitespace
harness/release-native-child-continuation-review-20260911.md -text -whitespace
harness/experiments/packaged-gui-close-865483b-20260911/** -text -whitespace
harness/release-grapheme-shortening-review-20260911.md -text -whitespace
harness/experiments/staged-source-native-a57c334-20260911/** -text -whitespace
harness/experiments/grapheme-windows-cb91525-20260911/** -text -whitespace
harness/experiments/canvas-native-close-a57c334-20260911/** -text -whitespace
harness/release-staged-native-a57-independent-review-20260911.md -text -whitespace
harness/release-saved-destination-independent-review-20260912.md -text -whitespace
harness/experiments/repair-union-windows-33e30c1-20260912/** -text -whitespace
harness/experiments/canvas-camera-a57c334-20260912/** -text -whitespace
harness/release-camera-a57-independent-review-20260912.md -text -whitespace
harness/experiments/canvas-repair-package-33e30c1-20260912/** -text -whitespace
harness/experiments/canvas-repair-native-33e30c1-20260912/** -text -whitespace
harness/experiments/canvas-repair-server-33e30c1-20260912/** -text -whitespace
harness/experiments/canvas-repair-publication-20260912/** -text -whitespace
harness/experiments/behavior-creation-native-20260911/** -text whitespace=cr-at-eol
harness/experiments/constructor-defaults-20260911/** -text whitespace=cr-at-eol
harness/experiments/constructor-defaults-20260911/results/*.arcadia whitespace=-blank-at-eol,cr-at-eol
harness/release-scenario-native-9e8r6t-20260911.md -text whitespace=cr-at-eol
harness/experiments/analysis-numeric-gate-20260911/** -text
harness/experiments/chooser-correction-20260911/** -text whitespace=-blank-at-eof,cr-at-eol
harness/experiments/chooser-lint-gate-20260911/** -text whitespace=-blank-at-eof,cr-at-eol
harness/history/2026-09-11-behavior-wiki-before-refresh.md -text whitespace=cr-at-eol
# Preserve the independently fingerprinted historical review verbatim.
harness/release-behavior-canvas-phase1-review-20260911.md -text whitespace=-blank-at-eof,cr-at-eol
harness/experiments/scenario-native-3c9e6ee-20260911/** -text whitespace=-blank-at-eof,cr-at-eol
harness/experiments/scenario-native-3c9e6ee-20260911/**/*.arcadia whitespace=-blank-at-eol,-blank-at-eof,cr-at-eol
harness/experiments/analysis-codec-windows-20260911/** -text whitespace=-blank-at-eof,cr-at-eol
harness/history/2026-09-11-ledgers-before-gitea-migration/** -text whitespace=-blank-at-eol,-blank-at-eof,cr-at-eol
harness/experiments/canvas-union-windows-20260911/** -text whitespace=-blank-at-eof,cr-at-eol
harness/experiments/canvas-a31b40d-windows-native-20260911/** -text whitespace=-blank-at-eol,-blank-at-eof,cr-at-eol
harness/experiments/allocation-d9b3f0d-windows-20260912/** -text whitespace=-blank-at-eol,-blank-at-eof,cr-at-eol
Generated
+22 -1
View File
@@ -2107,6 +2107,25 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "num-bigint"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2153,6 +2172,9 @@ name = "oa-core"
version = "0.2.0"
dependencies = [
"libc",
"num-bigint",
"num-integer",
"num-traits",
"same-file",
"serde",
"serde_json",
@@ -2176,7 +2198,6 @@ dependencies = [
"serde_json",
"tempfile",
"tokio",
"unicode-segmentation",
]
[[package]]
+3
View File
@@ -12,6 +12,9 @@ uuid.workspace = true
thiserror.workspace = true
tempfile = "3"
same-file = "1"
num-bigint = "0.5.1"
num-integer = "0.1.47"
num-traits = "0.2.19"
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2"
+103
View File
@@ -0,0 +1,103 @@
//! Exact numeric foundation for analysis; no model, expression, or package resolver.
//!
//! Values use reduced rational coordinates. All nontrivial arithmetic takes one
//! request-local [WorkMeter]. The future evaluator must also charge *expanded*
//! expression/call/property/list/target visits and retain the same logical walk on
//! cache hits. Stored AST size is not a dynamic execution limit.
//!
//! Approximate engineering functions/irrational unit scales require a subsequent
//! explicit numeric profile; rationals do not implement degree/radian conversion
//! or transcendental mathematics.
mod dimension;
mod exact;
mod meter;
mod quantity;
pub use dimension::{Dimension, DimensionAxis};
pub use exact::{Exact, ExactWire};
pub use meter::{
EvaluationStep, NumericOperation, WorkExhaustion, WorkLimits, WorkMeter, WorkResource,
WorkSite, WorkUsage,
};
pub use quantity::{NumericType, NumericValue, ResolvedKind, Unit};
use serde::{Deserialize, Serialize};
use thiserror::Error;
/// Profile identity includes the accounting rules, not crate-internal timing.
pub const WORK_PROFILE: &str = "Q1-logical-work-1";
pub const MAX_COMPONENT_BITS: u64 = 4096;
/// Cross products require 8192 bits; their sum can require one additional bit.
pub const MAX_INTERMEDIATE_BITS: u64 = 8193;
pub const MAX_COMPONENT_DIGITS: usize = 1234;
pub const MAX_DECIMAL_EXPONENT: i32 = 128;
pub const MAX_INTEGER_POWER: i8 = 16;
/// Includes ratio punctuation/whitespace without permitting unbounded scanning.
pub const MAX_LITERAL_BYTES: usize = 2 * MAX_COMPONENT_DIGITS + 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NumberComponent {
Numerator,
Denominator,
}
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
pub enum NumericLimit {
#[error("request work exhausted: {0}")]
Work(WorkExhaustion),
#[error("{component:?} uses {bits} bits, above the {limit}-bit {stage} limit")]
Bits {
component: NumberComponent,
bits: u64,
limit: u64,
stage: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
pub enum NumericError {
#[error("numeric limit: {0}")]
Limit(NumericLimit),
#[error("invalid numeric literal")]
InvalidLiteral,
#[error("numeric literal exceeds its digit or byte limit")]
LiteralTooLong,
#[error("decimal exponent is outside -128 through 128")]
DecimalExponent,
#[error("wire rational is not in canonical reduced form")]
NonCanonicalWire,
#[error("rational denominator is zero")]
ZeroDenominator,
#[error("division by zero")]
DivisionByZero,
#[error("zero to the power zero is undefined in this profile")]
ZeroPowerZero,
#[error("integer power is outside -16 through 16")]
IntegerPower,
#[error("dimension exponent at {axis:?} is outside -32 through 32: {value}")]
DimensionExponent { axis: DimensionAxis, value: i32 },
#[error("unit scale must be strictly positive")]
UnitScale,
#[error("a linear unit must have zero offset")]
LinearOffset,
#[error("an affine point must have a distinct linear difference kind")]
DifferenceKind,
#[error("numeric kinds or dimensions are incompatible")]
IncompatibleTypes,
#[error("operation is not defined for affine points")]
AffineOperation,
#[error("AsKind requires an anonymous matching dimension and a linear target")]
KindAssertion,
#[error("request work limits exceed the provisional reference ceilings")]
InvalidWorkLimits,
}
impl NumericError {
pub fn is_terminal_work_exhaustion(&self) -> bool {
matches!(self, Self::Limit(NumericLimit::Work(_)))
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,107 @@
use super::NumericError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DimensionAxis {
Length,
Mass,
Time,
ElectricCurrent,
Temperature,
Amount,
LuminousIntensity,
}
impl DimensionAxis {
pub const ALL: [Self; 7] = [
Self::Length,
Self::Mass,
Self::Time,
Self::ElectricCurrent,
Self::Temperature,
Self::Amount,
Self::LuminousIntensity,
];
}
/// SI base-dimension vector in DimensionAxis::ALL order, each entry -32..=32.
/// This is a dimension, never a nominal quantity-kind compatibility proof.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "[i16; 7]", into = "[i16; 7]")]
pub struct Dimension([i16; 7]);
impl Dimension {
pub const ZERO: Self = Self([0; 7]);
pub fn new(exponents: [i16; 7]) -> Result<Self, NumericError> {
for (index, value) in exponents.iter().copied().enumerate() {
if !(-32..=32).contains(&value) {
return Err(NumericError::DimensionExponent {
axis: DimensionAxis::ALL[index],
value: i32::from(value),
});
}
}
Ok(Self(exponents))
}
pub fn exponents(self) -> [i16; 7] {
self.0
}
pub fn is_dimensionless(self) -> bool {
self == Self::ZERO
}
pub fn checked_product(self, rhs: Self) -> Result<Self, NumericError> {
self.combine(rhs, 1)
}
pub fn checked_quotient(self, rhs: Self) -> Result<Self, NumericError> {
self.combine(rhs, -1)
}
pub fn checked_power(self, exponent: i8) -> Result<Self, NumericError> {
if !(-super::MAX_INTEGER_POWER..=super::MAX_INTEGER_POWER).contains(&exponent) {
return Err(NumericError::IntegerPower);
}
let mut output = [0; 7];
for (index, value) in self.0.iter().enumerate() {
output[index] = Self::checked_exponent(index, i32::from(*value) * i32::from(exponent))?;
}
Ok(Self(output))
}
fn combine(self, rhs: Self, sign: i32) -> Result<Self, NumericError> {
let mut output = [0; 7];
for (index, value) in self.0.iter().enumerate() {
output[index] =
Self::checked_exponent(index, i32::from(*value) + sign * i32::from(rhs.0[index]))?;
}
Ok(Self(output))
}
fn checked_exponent(index: usize, value: i32) -> Result<i16, NumericError> {
if !(-32..=32).contains(&value) {
return Err(NumericError::DimensionExponent {
axis: DimensionAxis::ALL[index],
value,
});
}
Ok(value as i16)
}
}
impl TryFrom<[i16; 7]> for Dimension {
type Error = NumericError;
fn try_from(value: [i16; 7]) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<Dimension> for [i16; 7] {
fn from(value: Dimension) -> Self {
value.0
}
}
@@ -0,0 +1,469 @@
use super::meter::{normalization_cost, parse_cost, product_cost, sum_cost, words};
use super::{
MAX_COMPONENT_BITS, MAX_COMPONENT_DIGITS, MAX_DECIMAL_EXPONENT, MAX_INTEGER_POWER,
MAX_INTERMEDIATE_BITS, MAX_LITERAL_BYTES, NumberComponent, NumericError, NumericLimit,
NumericOperation, WorkLimits, WorkMeter,
};
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Signed, Zero};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
/// The interchange representation deliberately does not use num-bigint's serde
/// format or JSON numeric values. Duplicate/missing/unknown fields reject.
/// Its derived decoder allocates String fields before numeric validation; a
/// transport/document adapter must bound the encoded envelope and decoded text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExactWire {
pub numerator: String,
pub denominator: String,
}
/// Reduced rational with positive denominator and <=4096-bit components.
///
/// There are no unmetered arithmetic/ordering traits. Eq is structural equality
/// of already normalized bounded values, not an expression comparison API.
/// Standalone serde admission bounds the subsequent BigInt validation, not the
/// preceding String decoding. Document adapters must bound encoded/decoded input
/// and aggregate admission work. Evaluation uses one explicit WorkMeter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ExactWire", into = "ExactWire")]
pub struct Exact {
numerator: BigInt,
denominator: BigInt,
}
impl Exact {
pub fn from_integer(value: i64) -> Self {
Self {
numerator: BigInt::from(value),
denominator: BigInt::one(),
}
}
pub fn is_zero(&self) -> bool {
self.numerator.is_zero()
}
pub fn is_positive(&self) -> bool {
self.numerator.is_positive()
}
pub fn component_bits(&self) -> (u64, u64) {
(self.numerator.bits(), self.denominator.bits())
}
pub fn to_wire(&self) -> ExactWire {
ExactWire {
numerator: self.numerator.to_string(),
denominator: self.denominator.to_string(),
}
}
/// Canonical *literal* spelling, not a generic expression formatter.
/// Negative literal nodes use ratio(-n,d), even when d=1. A leading minus
/// belongs to the future expression parser's UnaryNegate node instead.
pub fn canonical_literal(&self) -> String {
if self.denominator.is_one() && !self.numerator.is_negative() {
self.numerator.to_string()
} else {
format!("ratio({}, {})", self.numerator, self.denominator)
}
}
pub fn from_wire(wire: &ExactWire, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let n_digits = wire_digits(&wire.numerator, true)?;
let d_digits = wire_digits(&wire.denominator, false)?;
let n_bound = decimal_bits(n_digits.len());
let d_bound = decimal_bits(d_digits.len());
meter.numeric(
NumericOperation::ParseWire,
parse_cost(n_digits.len(), n_bound)
+ parse_cost(d_digits.len(), d_bound)
+ normalization_cost(n_bound, d_bound),
)?;
let numerator = parse_integer(&wire.numerator)?;
let denominator = parse_integer(&wire.denominator)?;
Self::check_bits(&numerator, &denominator, MAX_COMPONENT_BITS, "wire")?;
if denominator.is_zero() {
return Err(NumericError::ZeroDenominator);
}
if !numerator.gcd(&denominator).is_one() {
return Err(NumericError::NonCanonicalWire);
}
Ok(Self {
numerator,
denominator,
})
}
/// Reads one unsigned decimal/integer atom or a ratio(n,d) literal only.
/// It does not parse expressions, unary operators, units, calls or names.
/// Source ratios/decimals may reduce; wire values must already be canonical.
pub fn parse_literal(source: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
if source.len() > MAX_LITERAL_BYTES {
return Err(NumericError::LiteralTooLong);
}
let source = trim_ascii(source);
if let Some(body) = source.strip_prefix("ratio(") {
let body = body.strip_suffix(')').ok_or(NumericError::InvalidLiteral)?;
let (n, d) = body.split_once(',').ok_or(NumericError::InvalidLiteral)?;
return Self::parse_ratio(trim_ascii(n), trim_ascii(d), meter);
}
Self::parse_decimal(source, meter)
}
fn parse_ratio(n: &str, d: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
let n_digits = source_integer_digits(n, true)?;
let d_digits = source_integer_digits(d, false)?;
let n_bound = decimal_bits(n_digits.len());
let d_bound = decimal_bits(d_digits.len());
Self::check_estimates(n_bound, d_bound)?;
meter.numeric(
NumericOperation::ParseLiteral,
parse_cost(n_digits.len(), n_bound)
+ parse_cost(d_digits.len(), d_bound)
+ normalization_cost(n_bound, d_bound),
)?;
Self::normalize_precharged(parse_integer(n)?, parse_integer(d)?)
}
fn parse_decimal(source: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
let mut parts = source.split(['e', 'E']);
let mantissa = parts.next().ok_or(NumericError::InvalidLiteral)?;
let exponent = match parts.next() {
Some(text) => parse_exponent(text)?,
None => 0,
};
if parts.next().is_some() {
return Err(NumericError::InvalidLiteral);
}
let (whole, fraction) = match mantissa.split_once('.') {
Some((whole, fraction)) if !fraction.is_empty() => (whole, fraction),
Some(_) => return Err(NumericError::InvalidLiteral),
None => (mantissa, ""),
};
source_integer_digits(whole, false)?;
if !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(NumericError::InvalidLiteral);
}
let digit_count = whole.len() + fraction.len();
if digit_count > MAX_COMPONENT_DIGITS {
return Err(NumericError::LiteralTooLong);
}
let adjustment = exponent - fraction.len() as i32;
let power = adjustment.unsigned_abs();
let mantissa_bound = decimal_bits(digit_count);
let scale_bound = decimal_bits(power as usize + 1);
let (n_bound, d_bound) = if adjustment >= 0 {
(mantissa_bound + scale_bound, 1)
} else {
(mantissa_bound, scale_bound)
};
Self::check_estimates(n_bound, d_bound)?;
// Fixed logical allowance for constructing 10^power; independent of
// num-bigint's selected multiplication/exponentiation implementation.
let power_steps = 1 + 2 * u64::from(u32::BITS - power.leading_zeros());
meter.numeric(
NumericOperation::ParseLiteral,
parse_cost(digit_count, mantissa_bound)
+ power_steps * product_cost(scale_bound, scale_bound)
+ product_cost(mantissa_bound, scale_bound)
+ normalization_cost(n_bound, d_bound),
)?;
let digits = format!("{whole}{fraction}");
let mut numerator = parse_integer(&digits)?;
let scale = BigInt::from(10_u8).pow(power);
let denominator = if adjustment >= 0 {
numerator *= scale;
BigInt::one()
} else {
scale
};
Self::normalize_precharged(numerator, denominator)
}
pub fn add(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
self.add_or_subtract(rhs, false, meter)
}
pub fn subtract(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
self.add_or_subtract(rhs, true, meter)
}
fn add_or_subtract(
&self,
rhs: &Self,
subtract: bool,
meter: &mut WorkMeter,
) -> Result<Self, NumericError> {
let (a, b) = self.component_bits();
let (c, d) = rhs.component_bits();
let left_bound = a + d;
let right_bound = c + b;
let n_bound = left_bound.max(right_bound) + 1;
let d_bound = b + d;
Self::check_estimates(n_bound, d_bound)?;
meter.numeric(
if subtract {
NumericOperation::Subtract
} else {
NumericOperation::Add
},
product_cost(a, d)
+ product_cost(c, b)
+ sum_cost(left_bound, right_bound)
+ product_cost(b, d)
+ normalization_cost(n_bound, d_bound),
)?;
let left = &self.numerator * &rhs.denominator;
let right = &rhs.numerator * &self.denominator;
let numerator = if subtract { left - right } else { left + right };
let denominator = &self.denominator * &rhs.denominator;
Self::normalize_precharged(numerator, denominator)
}
pub fn multiply(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
let (a, b) = self.component_bits();
let (c, d) = rhs.component_bits();
Self::check_estimates(a + c, b + d)?;
meter.numeric(
NumericOperation::Multiply,
product_cost(a, c) + product_cost(b, d) + normalization_cost(a + c, b + d),
)?;
Self::normalize_precharged(
&self.numerator * &rhs.numerator,
&self.denominator * &rhs.denominator,
)
}
pub fn divide(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
let (a, b) = self.component_bits();
let (c, d) = rhs.component_bits();
Self::check_estimates(a + d, b + c)?;
meter.numeric(
NumericOperation::Divide,
product_cost(a, d) + product_cost(b, c) + normalization_cost(a + d, b + c),
)?;
if rhs.is_zero() {
return Err(NumericError::DivisionByZero);
}
Self::normalize_precharged(
&self.numerator * &rhs.denominator,
&self.denominator * &rhs.numerator,
)
}
pub fn compare(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Ordering, NumericError> {
let (a, b) = self.component_bits();
let (c, d) = rhs.component_bits();
Self::check_estimates((a + d).max(c + b), 1)?;
meter.numeric(
NumericOperation::Compare,
product_cost(a, d) + product_cost(c, b) + sum_cost(a + d, c + b),
)?;
Ok((&self.numerator * &rhs.denominator).cmp(&(&rhs.numerator * &self.denominator)))
}
pub fn negated(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.numeric(NumericOperation::Negate, self.copy_cost())?;
Ok(Self {
numerator: -&self.numerator,
denominator: self.denominator.clone(),
})
}
pub fn absolute(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.numeric(NumericOperation::Absolute, self.copy_cost())?;
Ok(Self {
numerator: self.numerator.abs(),
denominator: self.denominator.clone(),
})
}
pub fn reciprocal(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.numeric(NumericOperation::Reciprocal, self.copy_cost())?;
if self.is_zero() {
return Err(NumericError::DivisionByZero);
}
Ok(Self {
numerator: if self.numerator.is_negative() {
-&self.denominator
} else {
self.denominator.clone()
},
denominator: self.numerator.abs(),
})
}
/// Fixed left-to-right repeated multiplication, at most 16 multiplications.
/// Each reduced stage obeys the same component bound; no large power is
/// allocated and subsequently discarded after discovering it is oversized.
pub fn power(&self, exponent: i8, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.numeric(NumericOperation::Power, self.copy_cost())?;
if !(-MAX_INTEGER_POWER..=MAX_INTEGER_POWER).contains(&exponent) {
return Err(NumericError::IntegerPower);
}
if self.is_zero() && exponent == 0 {
return Err(NumericError::ZeroPowerZero);
}
let factor = if exponent < 0 {
self.reciprocal(meter)?
} else {
self.clone()
};
let mut value = Self::from_integer(1);
for _ in 0..exponent.unsigned_abs() {
value = value.multiply(&factor, meter)?;
}
Ok(value)
}
pub(super) fn copy_cost(&self) -> u64 {
let (n, d) = self.component_bits();
1 + words(n) + words(d)
}
fn normalize_precharged(
mut numerator: BigInt,
mut denominator: BigInt,
) -> Result<Self, NumericError> {
Self::check_bits(
&numerator,
&denominator,
MAX_INTERMEDIATE_BITS,
"intermediate",
)?;
if denominator.is_zero() {
return Err(NumericError::ZeroDenominator);
}
if denominator.is_negative() {
numerator = -numerator;
denominator = -denominator;
}
let gcd = numerator.gcd(&denominator);
numerator /= &gcd;
denominator /= gcd;
Self::check_bits(&numerator, &denominator, MAX_COMPONENT_BITS, "reduced")?;
Ok(Self {
numerator,
denominator,
})
}
fn check_estimates(n: u64, d: u64) -> Result<(), NumericError> {
Self::check_bit_count(
n,
NumberComponent::Numerator,
MAX_INTERMEDIATE_BITS,
"predicted",
)?;
Self::check_bit_count(
d,
NumberComponent::Denominator,
MAX_INTERMEDIATE_BITS,
"predicted",
)
}
fn check_bits(n: &BigInt, d: &BigInt, limit: u64, stage: &str) -> Result<(), NumericError> {
Self::check_bit_count(n.bits(), NumberComponent::Numerator, limit, stage)?;
Self::check_bit_count(d.bits(), NumberComponent::Denominator, limit, stage)
}
fn check_bit_count(
bits: u64,
component: NumberComponent,
limit: u64,
stage: &str,
) -> Result<(), NumericError> {
if bits > limit {
return Err(NumericError::Limit(NumericLimit::Bits {
component,
bits,
limit,
stage: stage.to_owned(),
}));
}
Ok(())
}
}
impl TryFrom<ExactWire> for Exact {
type Error = NumericError;
fn try_from(value: ExactWire) -> Result<Self, Self::Error> {
// BigInt validation is bounded after ExactWire strings have decoded.
// The adapter owns envelope/text/aggregate admission bounds and must not
// reset evaluation meters.
Self::from_wire(&value, &mut WorkMeter::new(WorkLimits::REFERENCE))
}
}
impl From<Exact> for ExactWire {
fn from(value: Exact) -> Self {
value.to_wire()
}
}
fn trim_ascii(text: &str) -> &str {
text.trim_matches(|ch: char| ch.is_ascii_whitespace())
}
fn source_integer_digits(text: &str, signed: bool) -> Result<&str, NumericError> {
let digits = if signed {
text.strip_prefix('-').unwrap_or(text)
} else {
text
};
if digits.len() > MAX_COMPONENT_DIGITS {
return Err(NumericError::LiteralTooLong);
}
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(NumericError::InvalidLiteral);
}
Ok(digits)
}
fn wire_digits(text: &str, signed: bool) -> Result<&str, NumericError> {
let digits = source_integer_digits(text, signed).map_err(|error| match error {
NumericError::LiteralTooLong => error,
_ => NumericError::NonCanonicalWire,
})?;
if (digits.len() > 1 && digits.starts_with('0')) || (text.starts_with('-') && digits == "0") {
return Err(NumericError::NonCanonicalWire);
}
Ok(digits)
}
fn parse_integer(text: &str) -> Result<BigInt, NumericError> {
BigInt::parse_bytes(text.as_bytes(), 10).ok_or(NumericError::InvalidLiteral)
}
fn parse_exponent(text: &str) -> Result<i32, NumericError> {
let (negative, digits) = if let Some(digits) = text.strip_prefix('-') {
(true, digits)
} else {
(false, text.strip_prefix('+').unwrap_or(text))
};
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(NumericError::InvalidLiteral);
}
let mut value = 0_i32;
for digit in digits.bytes() {
value = value * 10 + i32::from(digit - b'0');
if value > MAX_DECIMAL_EXPONENT {
return Err(NumericError::DecimalExponent);
}
}
Ok(if negative { -value } else { value })
}
fn decimal_bits(digits: usize) -> u64 {
// 3.322 exceeds log2(10); dimensions are bounded before this conversion.
(digits as u64 * 3322).div_ceil(1000).max(1)
}
@@ -0,0 +1,32 @@
[
{
"canonical_source": "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"expression": {
"Number": {
"denominator": "1",
"numerator": "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
},
"name": "ten_to_300"
},
{
"canonical_source": "ratio(1, 522194440706576253345876355358312191289982124523691890192116741641976953985778728424413405967498779170445053357219631418993786719092896803631618043925682638972978488271854999170180795067191859157214035005927973113188159419698856372836167342172293308748403954352901852035642024370059304557233988891799014503343469488440893892973452815095130470299789726716411734651513348221529512507986199933857107770846917779942645743159118957217248367043905936319748237550094520674504208530837546834166925275516486044134775384991808184705966507606898412918594045916828375610659246423184062775112999150206172392431297837246097308511903252956622805412865917690043804311051417135098849101156584508839003337597742539960818209685142687562392007453579567729991395256699805775897135553415567045292136442139895777424891477161767258532611634530697452993846501061481697843891439474220308003706472837459911525285821188577408160690315522951458068463354171428220365223949985950890732881736611925133626529949897998045399734600887312408859224933727829625089164535236559716582775403784110923285873186648442456409760158728501220463308455437074192539205964902261490928669488824051563042951500651206733594863336608245755565801460390869016718045121902354170201577095168)",
"expression": {
"Number": {
"denominator": "522194440706576253345876355358312191289982124523691890192116741641976953985778728424413405967498779170445053357219631418993786719092896803631618043925682638972978488271854999170180795067191859157214035005927973113188159419698856372836167342172293308748403954352901852035642024370059304557233988891799014503343469488440893892973452815095130470299789726716411734651513348221529512507986199933857107770846917779942645743159118957217248367043905936319748237550094520674504208530837546834166925275516486044134775384991808184705966507606898412918594045916828375610659246423184062775112999150206172392431297837246097308511903252956622805412865917690043804311051417135098849101156584508839003337597742539960818209685142687562392007453579567729991395256699805775897135553415567045292136442139895777424891477161767258532611634530697452993846501061481697843891439474220308003706472837459911525285821188577408160690315522951458068463354171428220365223949985950890732881736611925133626529949897998045399734600887312408859224933727829625089164535236559716582775403784110923285873186648442456409760158728501220463308455437074192539205964902261490928669488824051563042951500651206733594863336608245755565801460390869016718045121902354170201577095168",
"numerator": "1"
}
},
"name": "one_over_two_to_4095"
},
{
"canonical_source": "ratio(-1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335, 1)",
"expression": {
"Number": {
"denominator": "1",
"numerator": "-1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335"
}
},
"name": "negative_4096_bit_bound"
}
]
@@ -0,0 +1,240 @@
use super::{NumericError, NumericLimit};
use serde::{Deserialize, Serialize};
use thiserror::Error;
/// Every event is charged once per dynamic occurrence, before entering it.
///
/// A Call expression therefore charges Expression and CalculationEntry; a
/// Property read charges Expression and PropertyBinding. List element visits
/// are additional to evaluation of their expressions. Only executed branches
/// are charged. Targets are sorted by category (properties, then checks), then
/// stable UUID bytes, by the integrating evaluator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EvaluationStep {
Target,
Expression,
CalculationEntry,
PropertyBinding,
ListElement,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NumericOperation {
ParseWire,
ParseLiteral,
Add,
Subtract,
Multiply,
Divide,
Compare,
Negate,
Absolute,
Reciprocal,
Power,
KindAssertion,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkResource {
DynamicEvents,
NumericUnits,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkSite {
Evaluation(EvaluationStep),
Numeric(NumericOperation),
}
/// Failed reservations consume no partial charge. The first failure is latched.
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
#[error("{resource:?}: used {used}, requested {requested}, limit {limit}, at {site:?}")]
pub struct WorkExhaustion {
pub resource: WorkResource,
pub used: u64,
pub requested: u64,
pub limit: u64,
pub site: WorkSite,
}
/// Provisional calibration ceilings, not measured execution-time guarantees.
///
/// Effective limits, profile identity, capture, targets and context must all be
/// recorded in request/result/frozen identity. A caller may lower these ceilings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "WorkLimitsWire", into = "WorkLimitsWire")]
pub struct WorkLimits {
dynamic_events: u64,
numeric_units: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WorkLimitsWire {
dynamic_events: u64,
numeric_units: u64,
}
impl WorkLimits {
pub const REFERENCE: Self = Self {
dynamic_events: 1_000_000,
numeric_units: 50_000_000,
};
pub fn new(dynamic_events: u64, numeric_units: u64) -> Result<Self, NumericError> {
if dynamic_events > Self::REFERENCE.dynamic_events
|| numeric_units > Self::REFERENCE.numeric_units
{
return Err(NumericError::InvalidWorkLimits);
}
Ok(Self {
dynamic_events,
numeric_units,
})
}
pub fn dynamic_events(self) -> u64 {
self.dynamic_events
}
pub fn numeric_units(self) -> u64 {
self.numeric_units
}
}
impl TryFrom<WorkLimitsWire> for WorkLimits {
type Error = NumericError;
fn try_from(value: WorkLimitsWire) -> Result<Self, Self::Error> {
Self::new(value.dynamic_events, value.numeric_units)
}
}
impl From<WorkLimits> for WorkLimitsWire {
fn from(value: WorkLimits) -> Self {
Self {
dynamic_events: value.dynamic_events,
numeric_units: value.numeric_units,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkUsage {
pub dynamic_events: u64,
pub numeric_units: u64,
}
/// Intentionally neither Clone nor Default: pass the same mutable meter through
/// every target, numeric operation and expanded call in one evaluation request.
///
/// Exhaustion is terminal. Integrators must stop traversing siblings/targets and
/// mark already collected causes as incomplete. Replaying an aggregate cache
/// cost is insufficient if it changes the exact exhaustion location; initially
/// retain logical traversal even when numerical values come from a cache.
#[derive(Debug)]
pub struct WorkMeter {
limits: WorkLimits,
usage: WorkUsage,
exhausted: Option<WorkExhaustion>,
}
impl WorkMeter {
pub fn new(limits: WorkLimits) -> Self {
Self {
limits,
usage: WorkUsage::default(),
exhausted: None,
}
}
pub fn limits(&self) -> WorkLimits {
self.limits
}
pub fn usage(&self) -> WorkUsage {
self.usage
}
pub fn exhaustion(&self) -> Option<&WorkExhaustion> {
self.exhausted.as_ref()
}
pub fn ensure_active(&self) -> Result<(), NumericError> {
match &self.exhausted {
Some(failure) => Err(NumericError::Limit(NumericLimit::Work(failure.clone()))),
None => Ok(()),
}
}
pub fn visit(&mut self, step: EvaluationStep) -> Result<(), NumericError> {
self.reserve(WorkResource::DynamicEvents, 1, WorkSite::Evaluation(step))
}
pub(super) fn numeric(
&mut self,
operation: NumericOperation,
units: u64,
) -> Result<(), NumericError> {
self.reserve(
WorkResource::NumericUnits,
units,
WorkSite::Numeric(operation),
)
}
fn reserve(
&mut self,
resource: WorkResource,
requested: u64,
site: WorkSite,
) -> Result<(), NumericError> {
self.ensure_active()?;
let (used, limit) = match resource {
WorkResource::DynamicEvents => (self.usage.dynamic_events, self.limits.dynamic_events),
WorkResource::NumericUnits => (self.usage.numeric_units, self.limits.numeric_units),
};
// Subtraction is safe: only successful reservations update usage.
if requested > limit - used {
let failure = WorkExhaustion {
resource,
used,
requested,
limit,
site,
};
self.exhausted = Some(failure.clone());
return Err(NumericError::Limit(NumericLimit::Work(failure)));
}
match resource {
WorkResource::DynamicEvents => self.usage.dynamic_events += requested,
WorkResource::NumericUnits => self.usage.numeric_units += requested,
}
Ok(())
}
}
// Logical 64-bit words are platform independent. These are deterministic
// accounting weights, not a claim about num-bigint's internal algorithm/timing.
pub(super) fn words(bits: u64) -> u64 {
bits.max(1).div_ceil(64)
}
pub(super) fn product_cost(a_bits: u64, b_bits: u64) -> u64 {
1 + words(a_bits) * words(b_bits)
}
pub(super) fn sum_cost(a_bits: u64, b_bits: u64) -> u64 {
1 + words(a_bits.max(b_bits))
}
pub(super) fn normalization_cost(n_bits: u64, d_bits: u64) -> u64 {
let width = words(n_bits.max(d_bits));
// 64*w² for GCD plus 2*w² for the two quotient operations.
1 + 66 * width * width
}
pub(super) fn parse_cost(digits: usize, estimated_bits: u64) -> u64 {
1 + digits as u64 * words(estimated_bits)
}
@@ -0,0 +1,378 @@
use super::{Dimension, Exact, MAX_INTEGER_POWER, NumericError, NumericOperation, WorkMeter};
use std::cmp::Ordering;
/// K is supplied by the common resolver's verified nominal compatibility
/// relation. It is not inferred from dimension/name/symbol/archive bytes here.
/// Coordinate basis/algebra/difference-kind closure must be part of that proof.
/// Exact definition references and pins remain the caller's provenance.
/// K must be a bounded, cheap-to-clone/compare verified handle. Constructing or
/// comparing an unbounded rooted contract graph is resolver admission work and
/// must not be hidden inside K's Clone/Eq implementations. Rust trait bounds do
/// not enforce this resource contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedKind<K> {
key: K,
dimension: Dimension,
difference: Option<K>,
}
impl<K> ResolvedKind<K> {
pub fn linear(key: K, dimension: Dimension) -> Self {
Self {
key,
dimension,
difference: None,
}
}
pub fn key(&self) -> &K {
&self.key
}
pub fn dimension(&self) -> Dimension {
self.dimension
}
pub fn is_affine(&self) -> bool {
self.difference.is_some()
}
}
impl<K: Clone + Eq> ResolvedKind<K> {
pub fn affine(key: K, difference: &Self) -> Result<Self, NumericError> {
if difference.is_affine() || key == difference.key {
return Err(NumericError::DifferenceKind);
}
Ok(Self {
key,
dimension: difference.dimension,
difference: Some(difference.key.clone()),
})
}
pub fn difference_kind(&self) -> Option<Self> {
self.difference
.as_ref()
.map(|key| Self::linear(key.clone(), self.dimension))
}
}
/// Canonical coordinate = magnitude * scale + offset.
/// Unit symbols and display preferences are outside this numeric representation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unit<K> {
kind: ResolvedKind<K>,
scale: Exact,
offset: Exact,
}
impl<K: Clone + Eq> Unit<K> {
pub fn new(kind: ResolvedKind<K>, scale: Exact, offset: Exact) -> Result<Self, NumericError> {
if !scale.is_positive() {
return Err(NumericError::UnitScale);
}
if !kind.is_affine() && !offset.is_zero() {
return Err(NumericError::LinearOffset);
}
Ok(Self {
kind,
scale,
offset,
})
}
pub fn kind(&self) -> &ResolvedKind<K> {
&self.kind
}
pub fn scale(&self) -> &Exact {
&self.scale
}
pub fn offset(&self) -> &Exact {
&self.offset
}
/// Fixed multiply-then-add path. Each reduced arithmetic stage is bounded.
/// A mathematically cancelling wider intermediate still reports NumericLimit;
/// replacing this path with a fused operation requires a new work profile.
pub fn to_canonical(
&self,
magnitude: &Exact,
meter: &mut WorkMeter,
) -> Result<Exact, NumericError> {
magnitude
.multiply(&self.scale, meter)?
.add(&self.offset, meter)
}
/// Fixed subtract-then-divide path; never rounds a coordinate.
pub fn from_canonical(
&self,
coordinate: &Exact,
meter: &mut WorkMeter,
) -> Result<Exact, NumericError> {
coordinate
.subtract(&self.offset, meter)?
.divide(&self.scale, meter)
}
pub fn convert(
&self,
magnitude: &Exact,
target: &Self,
meter: &mut WorkMeter,
) -> Result<Exact, NumericError> {
meter.ensure_active()?;
if self.kind != target.kind {
return Err(NumericError::IncompatibleTypes);
}
target.from_canonical(&self.to_canonical(magnitude, meter)?, meter)
}
}
/// Internal numerical types. Boolean/list/check semantics belong to the common
/// expression evaluator. Anonymous zero dimension normalizes to Number.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NumericType<K> {
Number,
Named(ResolvedKind<K>),
Anonymous(Dimension),
}
impl<K> NumericType<K> {
pub fn dimension(&self) -> Dimension {
match self {
Self::Number => Dimension::ZERO,
Self::Named(kind) => kind.dimension,
Self::Anonymous(dimension) => *dimension,
}
}
pub fn is_affine(&self) -> bool {
matches!(self, Self::Named(kind) if kind.is_affine())
}
fn anonymous(dimension: Dimension) -> Self {
if dimension.is_dimensionless() {
Self::Number
} else {
Self::Anonymous(dimension)
}
}
fn normalized(self) -> Self {
match self {
Self::Anonymous(dimension) => Self::anonymous(dimension),
other => other,
}
}
}
/// A canonical rational coordinate with an internal numerical type.
///
/// Derived Eq compares stored representation. Formal equality/ordering must call
/// compare(), which rejects mismatched nominal kinds instead of treating them
/// as a false predicate. Public property output must still check its declared
/// type and anchor the result to that declaration's exact definition reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumericValue<K> {
value_type: NumericType<K>,
coordinate: Exact,
}
impl<K: Clone + Eq> NumericValue<K> {
pub fn new(value_type: NumericType<K>, coordinate: Exact) -> Self {
Self {
value_type: value_type.normalized(),
coordinate,
}
}
pub fn number(coordinate: Exact) -> Self {
Self::new(NumericType::Number, coordinate)
}
pub fn from_unit(
magnitude: &Exact,
unit: &Unit<K>,
meter: &mut WorkMeter,
) -> Result<Self, NumericError> {
meter.ensure_active()?;
Ok(Self::new(
NumericType::Named(unit.kind.clone()),
unit.to_canonical(magnitude, meter)?,
))
}
pub fn value_type(&self) -> &NumericType<K> {
&self.value_type
}
pub fn coordinate(&self) -> &Exact {
&self.coordinate
}
pub fn display_in(&self, unit: &Unit<K>, meter: &mut WorkMeter) -> Result<Exact, NumericError> {
meter.ensure_active()?;
if !matches!(&self.value_type, NumericType::Named(kind) if kind == &unit.kind) {
return Err(NumericError::IncompatibleTypes);
}
unit.from_canonical(&self.coordinate, meter)
}
pub fn add(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let output = self.additive_type(rhs, false)?;
Ok(Self::new(
output,
self.coordinate.add(&rhs.coordinate, meter)?,
))
}
pub fn subtract(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let output = self.additive_type(rhs, true)?;
Ok(Self::new(
output,
self.coordinate.subtract(&rhs.coordinate, meter)?,
))
}
fn additive_type(&self, rhs: &Self, subtract: bool) -> Result<NumericType<K>, NumericError> {
use NumericType::{Anonymous, Named, Number};
match (&self.value_type, &rhs.value_type) {
(Number, Number) => Ok(Number),
(Anonymous(left), Anonymous(right)) if left == right => Ok(Anonymous(*left)),
(Named(left), Named(right)) => match (&left.difference, &right.difference) {
(None, None) if left == right => Ok(Named(left.clone())),
(Some(difference), Some(_)) if subtract && left == right => Ok(Named(
ResolvedKind::linear(difference.clone(), left.dimension),
)),
(Some(difference), None)
if difference == &right.key && left.dimension == right.dimension =>
{
Ok(Named(left.clone()))
}
(None, Some(difference))
if !subtract
&& difference == &left.key
&& left.dimension == right.dimension =>
{
Ok(Named(right.clone()))
}
_ => Err(NumericError::IncompatibleTypes),
},
_ => Err(NumericError::IncompatibleTypes),
}
}
pub fn multiply(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let output = self.multiplicative_type(rhs, false)?;
Ok(Self::new(
output,
self.coordinate.multiply(&rhs.coordinate, meter)?,
))
}
pub fn divide(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let output = self.multiplicative_type(rhs, true)?;
Ok(Self::new(
output,
self.coordinate.divide(&rhs.coordinate, meter)?,
))
}
fn multiplicative_type(
&self,
rhs: &Self,
divide: bool,
) -> Result<NumericType<K>, NumericError> {
use NumericType::Number;
if self.value_type.is_affine() || rhs.value_type.is_affine() {
return Err(NumericError::AffineOperation);
}
match (&self.value_type, &rhs.value_type) {
(Number, Number) => Ok(Number),
(_, Number) => Ok(self.value_type.clone()),
(Number, _) if !divide => Ok(rhs.value_type.clone()),
_ => {
let left = self.value_type.dimension();
let right = rhs.value_type.dimension();
let dimension = if divide {
left.checked_quotient(right)?
} else {
left.checked_product(right)?
};
Ok(NumericType::anonymous(dimension))
}
}
}
pub fn negated(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
if self.value_type.is_affine() {
return Err(NumericError::AffineOperation);
}
Ok(Self::new(
self.value_type.clone(),
self.coordinate.negated(meter)?,
))
}
pub fn absolute(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
if self.value_type.is_affine() {
return Err(NumericError::AffineOperation);
}
Ok(Self::new(
self.value_type.clone(),
self.coordinate.absolute(meter)?,
))
}
pub fn power(&self, exponent: i8, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
if !(-MAX_INTEGER_POWER..=MAX_INTEGER_POWER).contains(&exponent) {
return Err(NumericError::IntegerPower);
}
if self.value_type.is_affine() {
return Err(NumericError::AffineOperation);
}
let output = match exponent {
0 => NumericType::Number,
1 => self.value_type.clone(),
_ => NumericType::anonymous(self.value_type.dimension().checked_power(exponent)?),
};
Ok(Self::new(output, self.coordinate.power(exponent, meter)?))
}
pub fn compare(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Ordering, NumericError> {
meter.ensure_active()?;
if self.value_type != rhs.value_type {
return Err(NumericError::IncompatibleTypes);
}
self.coordinate.compare(&rhs.coordinate, meter)
}
pub fn as_kind(
&self,
target: &ResolvedKind<K>,
meter: &mut WorkMeter,
) -> Result<Self, NumericError> {
meter.ensure_active()?;
if target.is_affine()
|| matches!(self.value_type, NumericType::Named(_))
|| self.value_type.dimension() != target.dimension
{
return Err(NumericError::KindAssertion);
}
meter.numeric(NumericOperation::KindAssertion, self.coordinate.copy_cost())?;
Ok(Self::new(
NumericType::Named(target.clone()),
self.coordinate.clone(),
))
}
}
@@ -0,0 +1,804 @@
use super::*;
use num_bigint::BigInt;
use num_traits::One;
use std::cmp::Ordering;
fn meter() -> WorkMeter {
WorkMeter::new(WorkLimits::REFERENCE)
}
fn exact(n: impl ToString, d: impl ToString) -> Exact {
Exact::from_wire(
&ExactWire {
numerator: n.to_string(),
denominator: d.to_string(),
},
&mut meter(),
)
.unwrap()
}
fn source(text: &str) -> Exact {
Exact::parse_literal(text, &mut meter()).unwrap()
}
fn assert_fraction(value: &Exact, n: impl ToString, d: impl ToString) {
assert_eq!(
value.to_wire(),
ExactWire {
numerator: n.to_string(),
denominator: d.to_string(),
}
);
}
// Independent bounded i128 oracle. It does not call the production Exact/GCD
// implementation when deriving expected arithmetic or ordering.
fn small_fraction(mut n: i128, mut d: i128) -> (i128, i128) {
assert_ne!(d, 0);
if d < 0 {
n = -n;
d = -d;
}
let (mut a, mut b) = (n.abs(), d);
while b != 0 {
(a, b) = (b, a % b);
}
(n / a, d / a)
}
#[test]
fn arithmetic_matches_independent_small_integer_oracle() {
for a in [-5_i128, -2, 0, 1, 4] {
for b in [1_i128, 2, 3, 7] {
for c in [-5_i128, -2, 0, 1, 4] {
for d in [1_i128, 2, 3, 7] {
let (an, ad) = small_fraction(a, b);
let (bn, bd) = small_fraction(c, d);
let left = exact(an, ad);
let right = exact(bn, bd);
let mut work = meter();
let (n, den) = small_fraction(a * d + c * b, b * d);
assert_fraction(&left.add(&right, &mut work).unwrap(), n, den);
let (n, den) = small_fraction(a * d - c * b, b * d);
assert_fraction(&left.subtract(&right, &mut work).unwrap(), n, den);
let (n, den) = small_fraction(a * c, b * d);
assert_fraction(&left.multiply(&right, &mut work).unwrap(), n, den);
if c != 0 {
let (n, den) = small_fraction(a * d, b * c);
assert_fraction(&left.divide(&right, &mut work).unwrap(), n, den);
} else {
assert_eq!(
left.divide(&right, &mut work),
Err(NumericError::DivisionByZero)
);
}
assert_eq!(
left.compare(&right, &mut work).unwrap(),
(a * d).cmp(&(c * b))
);
}
}
}
}
}
#[test]
fn decimals_are_exact_and_source_ratios_reduce() {
assert_fraction(
&source("0.1").add(&source("0.2"), &mut meter()).unwrap(),
3,
10,
);
assert_fraction(&source("0.50"), 1, 2);
assert_fraction(&source("12.50e-2"), 1, 8);
assert_fraction(&source("1e+3"), 1000, 1);
assert_fraction(&source("0001.2500"), 5, 4);
assert_fraction(&source(" ratio( -6, 8 ) "), -3, 4);
assert_fraction(&source("ratio(-0, 27)"), 0, 1);
assert_eq!(source("0.5").canonical_literal(), "ratio(1, 2)");
assert_eq!(source("42").canonical_literal(), "42");
}
#[test]
fn powers_and_signs_have_explicit_domains() {
let x = exact(-2, 3);
assert_fraction(&x.power(3, &mut meter()).unwrap(), -8, 27);
assert_fraction(&x.power(-3, &mut meter()).unwrap(), -27, 8);
assert_fraction(&x.power(0, &mut meter()).unwrap(), 1, 1);
assert_fraction(&x.absolute(&mut meter()).unwrap(), 2, 3);
assert_fraction(&x.negated(&mut meter()).unwrap(), 2, 3);
assert_fraction(&x.reciprocal(&mut meter()).unwrap(), -3, 2);
let zero = Exact::from_integer(0);
assert_eq!(
zero.power(0, &mut meter()),
Err(NumericError::ZeroPowerZero)
);
assert_eq!(
zero.power(-1, &mut meter()),
Err(NumericError::DivisionByZero)
);
assert_eq!(x.power(17, &mut meter()), Err(NumericError::IntegerPower));
assert_eq!(
x.power(i8::MIN, &mut meter()),
Err(NumericError::IntegerPower)
);
}
#[test]
fn canonical_wire_rejects_both_component_noncanonical_forms() {
for (n, d) in [
("+1", "1"),
("01", "1"),
("-0", "1"),
("1", "+1"),
("1", "-1"),
("1", "01"),
("2", "4"),
("0", "3"),
("", "1"),
("1", ""),
("1.0", "1"),
("1", "1.0"),
("1e1", "1"),
("1", "1e1"),
(" 1", "1"),
("1", "1 "),
] {
assert!(
Exact::from_wire(
&ExactWire {
numerator: n.into(),
denominator: d.into()
},
&mut meter(),
)
.is_err(),
"accepted {n}/{d}"
);
}
assert_eq!(
Exact::from_wire(
&ExactWire {
numerator: "1".into(),
denominator: "0".into()
},
&mut meter()
),
Err(NumericError::ZeroDenominator)
);
assert_fraction(&exact(0, 1), 0, 1);
assert_fraction(&exact(-1, 2), -1, 2);
}
#[test]
fn serde_uses_closed_canonical_string_wire() {
let value = exact(-3, 7);
let encoded = serde_json::to_value(&value).unwrap();
assert_eq!(
encoded,
serde_json::json!({"numerator":"-3","denominator":"7"})
);
assert_eq!(serde_json::from_value::<Exact>(encoded).unwrap(), value);
for invalid in [
r#"{"numerator":1,"denominator":"2"}"#,
r#"{"numerator":"1","denominator":2}"#,
r#"{"numerator":"1","denominator":"2","other":0}"#,
r#"{"numerator":"1","numerator":"2","denominator":"3"}"#,
r#"{"numerator":"1"}"#,
r#"{"numerator":"2","denominator":"4"}"#,
] {
assert!(serde_json::from_str::<Exact>(invalid).is_err(), "{invalid}");
}
}
#[test]
fn literal_reader_does_not_fold_expression_unary_minus() {
assert_eq!(
Exact::parse_literal("-2", &mut meter()),
Err(NumericError::InvalidLiteral)
);
let negative_literal = source("ratio(-2, 1)");
assert_eq!(negative_literal.canonical_literal(), "ratio(-2, 1)");
assert_eq!(source("2").negated(&mut meter()).unwrap(), negative_literal);
// Equality of coordinates does not claim AST equality. The expression
// parser must preserve UnaryNegate independently of its operand literal.
assert_eq!(source("2").canonical_literal(), "2");
}
#[test]
fn literal_syntax_and_decimal_exponent_are_bounded() {
for invalid in [
"",
"-",
"+1",
".5",
"1.",
"1.2.3",
"1e",
"1ee2",
"1e+-2",
"1_000",
"NaN",
"Infinity",
"1/2",
"ratio(1)",
"ratio(1,2,3)",
"ratio(1,-2)",
"ratio(+1,2)",
"ratio(1,2) + 1",
"12",
] {
assert!(
Exact::parse_literal(invalid, &mut meter()).is_err(),
"{invalid}"
);
}
for invalid in ["1e129", "1e-129", "1e9999999999999999999999"] {
assert_eq!(
Exact::parse_literal(invalid, &mut meter()),
Err(NumericError::DecimalExponent)
);
}
assert!(Exact::parse_literal("1e128", &mut meter()).is_ok());
assert!(Exact::parse_literal("1e-128", &mut meter()).is_ok());
assert_eq!(
Exact::parse_literal(&"1".repeat(MAX_COMPONENT_DIGITS + 1), &mut meter()),
Err(NumericError::LiteralTooLong)
);
assert_eq!(
Exact::parse_literal(&" ".repeat(MAX_LITERAL_BYTES + 1), &mut meter()),
Err(NumericError::LiteralTooLong)
);
}
#[test]
fn full_independent_r7_packets_round_trip_as_literals_and_wire() {
let packets: serde_json::Value =
serde_json::from_str(include_str!("fixtures/r7-literal-boundaries.json")).unwrap();
for packet in packets.as_array().unwrap() {
let wire: ExactWire =
serde_json::from_value(packet["expression"]["Number"].clone()).unwrap();
let expected = Exact::from_wire(&wire, &mut meter()).unwrap();
let spelling = packet["canonical_source"].as_str().unwrap();
assert_eq!(expected.canonical_literal(), spelling);
assert_eq!(
Exact::parse_literal(spelling, &mut meter()).unwrap(),
expected
);
let serialized = serde_json::to_string(&expected).unwrap();
assert_eq!(
serde_json::from_str::<Exact>(&serialized).unwrap(),
expected
);
assert_eq!(expected.to_wire(), wire);
}
}
#[test]
fn full_8193_bit_sum_intermediate_can_reduce_to_admitted_value() {
// N=(2^4096)-1, D=N-1. gcd(N,D)=1 and D is even.
// N/D + N/D = N/(D/2), although its un-reduced numerator needs 8193 bits.
let n = (BigInt::one() << 4096_usize) - 1_u8;
let d = &n - 1_u8;
let value = exact(&n, &d);
let result = value.add(&value, &mut meter()).unwrap();
assert_fraction(&result, &n, &d / 2_u8);
}
#[test]
fn cross_products_cancel_before_reduced_component_limit() {
let n = BigInt::one() << 4095_usize;
let d = &n - 1_u8;
let left = exact(&n, &d);
let right = exact(&d, &n);
assert_fraction(&left.multiply(&right, &mut meter()).unwrap(), 1, 1);
assert_fraction(
&left
.add(&left.negated(&mut meter()).unwrap(), &mut meter())
.unwrap(),
0,
1,
);
}
#[test]
fn both_reduced_component_overflows_are_reported() {
let n = BigInt::one() << 4095_usize;
let mut work = meter();
let failure = exact(&n, 1)
.multiply(&Exact::from_integer(2), &mut work)
.unwrap_err();
assert!(matches!(
failure,
NumericError::Limit(NumericLimit::Bits {
component: NumberComponent::Numerator,
bits: 4097,
..
})
));
assert!(work.exhaustion().is_none());
let failure = exact(1, &n)
.divide(&Exact::from_integer(2), &mut work)
.unwrap_err();
assert!(matches!(
failure,
NumericError::Limit(NumericLimit::Bits {
component: NumberComponent::Denominator,
bits: 4097,
..
})
));
// Value overflow is a nonterminal supported-operation failure; fuel
// exhaustion, in contrast, terminates the entire request.
assert_fraction(&source("1").add(&source("1"), &mut work).unwrap(), 2, 1);
}
#[test]
fn wire_rejects_4097_bits_before_gcd_can_reduce_them() {
let oversized = (BigInt::one() << 4096_usize).to_string();
for wire in [
ExactWire {
numerator: oversized.clone(),
denominator: "1".into(),
},
ExactWire {
numerator: "1".into(),
denominator: oversized.clone(),
},
ExactWire {
numerator: oversized.clone(),
denominator: oversized,
},
] {
assert!(matches!(
Exact::from_wire(&wire, &mut meter()),
Err(NumericError::Limit(NumericLimit::Bits { stage, .. })) if stage == "wire"
));
}
}
#[test]
fn numeric_precharge_precedes_big_integer_result_allocation() {
let n = BigInt::one() << 4095_usize;
let left = exact(&n, 1);
let mut work = WorkMeter::new(WorkLimits::new(10, 0).unwrap());
let failure = left
.multiply(&Exact::from_integer(2), &mut work)
.unwrap_err();
assert!(failure.is_terminal_work_exhaustion());
assert_eq!(work.usage().numeric_units, 0);
assert!(matches!(
work.exhaustion().unwrap().site,
WorkSite::Numeric(NumericOperation::Multiply)
));
// With available fuel the same operation reaches the 4097-bit result check.
assert!(matches!(
left.multiply(&Exact::from_integer(2), &mut meter()),
Err(NumericError::Limit(NumericLimit::Bits { .. }))
));
let too_wide_wire = ExactWire {
numerator: (BigInt::one() << 4096_usize).to_string(),
denominator: "1".into(),
};
let mut parse_work = WorkMeter::new(WorkLimits::new(0, 0).unwrap());
assert!(
Exact::from_wire(&too_wide_wire, &mut parse_work)
.unwrap_err()
.is_terminal_work_exhaustion()
);
}
#[test]
fn provisional_limits_and_effective_limits_round_trip() {
let limits = WorkLimits::new(500, 2000).unwrap();
let encoded = serde_json::to_value(limits).unwrap();
assert_eq!(
encoded,
serde_json::json!({"dynamic_events":500,"numeric_units":2000})
);
assert_eq!(
serde_json::from_value::<WorkLimits>(encoded).unwrap(),
limits
);
assert_eq!(
WorkLimits::new(1_000_001, 0),
Err(NumericError::InvalidWorkLimits)
);
assert_eq!(
WorkLimits::new(0, 50_000_001),
Err(NumericError::InvalidWorkLimits)
);
assert!(
serde_json::from_str::<WorkLimits>(r#"{"dynamic_events":1000001,"numeric_units":0}"#)
.is_err()
);
}
#[test]
fn exact_accounting_boundary_and_terminal_failure_are_stable() {
// One-word addition: three products at 2, one sum at 2,
// normalization at 67 => 75 logical numeric units.
let mut work = WorkMeter::new(WorkLimits::new(4, 75).unwrap());
assert_fraction(&exact(1, 2).add(&exact(1, 3), &mut work).unwrap(), 5, 6);
assert_eq!(work.usage().numeric_units, 75);
assert!(work.exhaustion().is_none());
let first = Exact::from_integer(1).negated(&mut work).unwrap_err();
let at_failure = work.usage();
assert_eq!(
work.exhaustion().unwrap(),
&WorkExhaustion {
resource: WorkResource::NumericUnits,
used: 75,
requested: 3,
limit: 75,
site: WorkSite::Numeric(NumericOperation::Negate),
}
);
assert_eq!(work.visit(EvaluationStep::Target).unwrap_err(), first);
assert_eq!(
Exact::from_integer(1)
.divide(&Exact::from_integer(0), &mut work)
.unwrap_err(),
first
);
assert_eq!(
work.numeric(NumericOperation::Compare, 0).unwrap_err(),
first
);
assert_eq!(work.usage(), at_failure);
}
#[test]
fn zero_cost_and_maximum_reservation_do_not_underflow_or_reactivate() {
let mut work = WorkMeter::new(WorkLimits::new(0, 0).unwrap());
work.numeric(NumericOperation::Compare, 0).unwrap();
let failure = work
.numeric(NumericOperation::Multiply, u64::MAX)
.unwrap_err();
assert!(failure.is_terminal_work_exhaustion());
assert_eq!(work.usage(), WorkUsage::default());
assert_eq!(
work.numeric(NumericOperation::Compare, 0).unwrap_err(),
failure
);
let mut dynamic = WorkMeter::new(WorkLimits::new(0, 5).unwrap());
assert!(dynamic.visit(EvaluationStep::Target).is_err());
assert_eq!(dynamic.usage(), WorkUsage::default());
}
#[test]
fn multiple_targets_share_one_aggregate_meter() {
let mut work = WorkMeter::new(WorkLimits::new(3, 50).unwrap());
work.visit(EvaluationStep::Target).unwrap();
work.visit(EvaluationStep::Expression).unwrap();
work.visit(EvaluationStep::Target).unwrap();
let failure = work.visit(EvaluationStep::Expression).unwrap_err();
assert!(failure.is_terminal_work_exhaustion());
assert_eq!(work.usage().dynamic_events, 3);
}
// A direct bounded call-tree workload, not an expression interpreter/dialect.
fn expanded_calls(
depth: u8,
x: u64,
work: &mut WorkMeter,
entered: &mut u64,
) -> Result<u64, NumericError> {
work.visit(EvaluationStep::CalculationEntry)?;
*entered += 1;
if depth == 0 {
return Ok(x);
}
let left = expanded_calls(depth - 1, 2 * x, work, entered)?;
let right = expanded_calls(depth - 1, 2 * x + 1, work, entered)?;
Ok(left + right)
}
#[test]
fn c1_expanded_call_witness_terminates_at_dynamic_limit() {
let mut work = WorkMeter::new(WorkLimits::new(10_000, 0).unwrap());
let mut entered = 0;
let failure = expanded_calls(30, 0, &mut work, &mut entered).unwrap_err();
assert!(failure.is_terminal_work_exhaustion());
assert_eq!(entered, 10_000);
assert_eq!(work.usage().dynamic_events, 10_000);
assert_eq!(
work.exhaustion().unwrap().site,
WorkSite::Evaluation(EvaluationStep::CalculationEntry)
);
// Nearby finite control: 63 invocations, leaves 0..31, sum 496.
let mut bounded = WorkMeter::new(WorkLimits::new(63, 0).unwrap());
let mut entered = 0;
assert_eq!(
expanded_calls(5, 0, &mut bounded, &mut entered).unwrap(),
496
);
assert_eq!(entered, 63);
assert!(bounded.exhaustion().is_none());
}
fn dim(value: [i16; 7]) -> Dimension {
Dimension::new(value).unwrap()
}
fn linear(key: &str, dimension: Dimension) -> ResolvedKind<String> {
ResolvedKind::linear(key.to_owned(), dimension)
}
fn named(n: i64, kind: &ResolvedKind<String>) -> NumericValue<String> {
NumericValue::new(NumericType::Named(kind.clone()), Exact::from_integer(n))
}
#[test]
fn dimensions_use_checked_seven_axis_integer_algebra() {
let length = dim([1, 0, 0, 0, 0, 0, 0]);
let mass = dim([0, 1, 0, 0, 0, 0, 0]);
let time = dim([0, 0, 1, 0, 0, 0, 0]);
assert_eq!(
mass.checked_product(length)
.unwrap()
.checked_quotient(time.checked_power(2).unwrap())
.unwrap(),
dim([1, 1, -2, 0, 0, 0, 0])
);
assert!(time.checked_quotient(time).unwrap().is_dimensionless());
assert!(matches!(
dim([32, 0, 0, 0, 0, 0, 0]).checked_product(length),
Err(NumericError::DimensionExponent {
axis: DimensionAxis::Length,
value: 33
})
));
assert!(dim([0, 0, -32, 0, 0, 0, 0]).checked_quotient(time).is_err());
assert!(length.checked_power(i8::MIN).is_err());
assert!(Dimension::new([33, 0, 0, 0, 0, 0, 0]).is_err());
assert_eq!(
serde_json::to_value(time).unwrap(),
serde_json::json!([0, 0, 1, 0, 0, 0, 0])
);
for invalid in ["[0,0,33,0,0,0,0]", "[0,0,1]", "[0,0,1,0,0,0,0,0]"] {
assert!(serde_json::from_str::<Dimension>(invalid).is_err());
}
}
#[test]
fn duration_unit_coordinates_are_exact_and_nominal() {
let duration = linear("duration", dim([0, 0, 1, 0, 0, 0, 0]));
let s = Unit::new(duration.clone(), source("1"), source("0")).unwrap();
let ms = Unit::new(duration.clone(), source("0.001"), source("0")).unwrap();
assert_fraction(&ms.convert(&source("750"), &s, &mut meter()).unwrap(), 3, 4);
let receive = NumericValue::from_unit(&source("750"), &ms, &mut meter()).unwrap();
let dispatch = NumericValue::from_unit(&source("1"), &s, &mut meter()).unwrap();
let total = receive.add(&dispatch, &mut meter()).unwrap();
assert_fraction(total.coordinate(), 7, 4);
assert_fraction(&total.display_in(&ms, &mut meter()).unwrap(), 1750, 1);
let different = Unit::new(
linear("different-kind", duration.dimension()),
source("1"),
source("0"),
)
.unwrap();
assert_eq!(
ms.convert(&source("750"), &different, &mut meter()),
Err(NumericError::IncompatibleTypes)
);
let inconsistent = Unit::new(
linear("duration", dim([1, 0, 0, 0, 0, 0, 0])),
source("1"),
source("0"),
)
.unwrap();
assert!(
ms.convert(&source("1"), &inconsistent, &mut meter())
.is_err()
);
assert!(Unit::new(duration.clone(), source("0"), source("0")).is_err());
assert!(Unit::new(duration.clone(), source("ratio(-1,1)"), source("0")).is_err());
assert_eq!(
Unit::new(duration, source("1"), source("1")).unwrap_err(),
NumericError::LinearOffset
);
}
#[test]
fn affine_point_and_difference_arithmetic_has_distinct_kinds() {
let interval = linear("temperature-difference", dim([0, 0, 0, 0, 1, 0, 0]));
let point = ResolvedKind::affine("temperature-point".to_owned(), &interval).unwrap();
let celsius = Unit::new(point.clone(), source("1"), source("273.15")).unwrap();
let fahrenheit = Unit::new(
point.clone(),
source("ratio(5,9)"),
source("ratio(45967,180)"),
)
.unwrap();
let kelvin_interval = Unit::new(interval.clone(), source("1"), source("0")).unwrap();
assert_fraction(
&celsius
.convert(&source("0"), &fahrenheit, &mut meter())
.unwrap(),
32,
1,
);
assert_fraction(
&fahrenheit
.convert(&source("70"), &celsius, &mut meter())
.unwrap(),
190,
9,
);
let p20 = NumericValue::from_unit(&source("20"), &celsius, &mut meter()).unwrap();
let p10 = NumericValue::from_unit(&source("10"), &celsius, &mut meter()).unwrap();
let difference = p20.subtract(&p10, &mut meter()).unwrap();
assert_eq!(
difference.value_type(),
&NumericType::Named(interval.clone())
);
assert_fraction(
&difference
.display_in(&kelvin_interval, &mut meter())
.unwrap(),
10,
1,
);
let delta5 = named(5, &interval);
let p25 = p20.add(&delta5, &mut meter()).unwrap();
assert_fraction(&p25.display_in(&celsius, &mut meter()).unwrap(), 25, 1);
assert_eq!(delta5.add(&p20, &mut meter()).unwrap(), p25);
assert!(p20.add(&p10, &mut meter()).is_err());
assert!(delta5.subtract(&p20, &mut meter()).is_err());
assert_eq!(
p20.power(1, &mut meter()),
Err(NumericError::AffineOperation)
);
assert_eq!(
p20.negated(&mut meter()),
Err(NumericError::AffineOperation)
);
assert_eq!(p20.compare(&p10, &mut meter()).unwrap(), Ordering::Greater);
assert!(p20.display_in(&kelvin_interval, &mut meter()).is_err());
assert!(ResolvedKind::affine(interval.key().clone(), &interval).is_err());
assert!(ResolvedKind::affine("other".to_owned(), &point).is_err());
}
#[test]
fn affine_conversion_rejects_a_wider_stage_even_when_the_final_value_would_fit() {
// A fused coordinate calculation 2*m-m equals m, where m=2^4095 fits.
// The fixed multiply stage produces 2^4096, so it must fail before offset
// cancellation. The inverse path likewise rejects (m-(-m))/2 at subtraction.
let large = BigInt::one() << 4095_usize;
let magnitude = exact(&large, 1);
let interval = linear("temperature-interval", dim([0, 0, 0, 0, 1, 0, 0]));
let point = ResolvedKind::affine("temperature-point".to_owned(), &interval).unwrap();
let unit = Unit::new(point, Exact::from_integer(2), exact(-&large, 1)).unwrap();
let mut work = meter();
for outcome in [
unit.to_canonical(&magnitude, &mut work),
unit.from_canonical(&magnitude, &mut work),
] {
assert!(matches!(
outcome,
Err(NumericError::Limit(NumericLimit::Bits {
component: NumberComponent::Numerator,
bits: 4097,
limit: MAX_COMPONENT_BITS,
..
}))
));
}
assert!(work.exhaustion().is_none());
let half = exact(&large >> 1_usize, 1);
assert_fraction(&unit.to_canonical(&half, &mut work).unwrap(), 0, 1);
assert_eq!(
unit.from_canonical(&Exact::from_integer(0), &mut work)
.unwrap(),
half
);
}
#[test]
fn r6_anonymous_compound_energy_needs_one_outer_assertion() {
let force = linear("force", dim([1, 1, -2, 0, 0, 0, 0]));
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
let energy = linear("energy", dim([2, 1, -2, 0, 0, 0, 0]));
let a = named(3, &force)
.multiply(&named(4, &length), &mut meter())
.unwrap();
let b = named(2, &force)
.multiply(&named(7, &length), &mut meter())
.unwrap();
assert_eq!(a.value_type(), &NumericType::Anonymous(energy.dimension()));
let sum = a.add(&b, &mut meter()).unwrap();
let result = sum.as_kind(&energy, &mut meter()).unwrap();
assert_fraction(result.coordinate(), 26, 1);
assert_eq!(result.value_type(), &NumericType::Named(energy.clone()));
assert_eq!(a.compare(&b, &mut meter()).unwrap(), Ordering::Less);
assert!(result.add(&sum, &mut meter()).is_err());
assert_eq!(
result.as_kind(&energy, &mut meter()),
Err(NumericError::KindAssertion)
);
}
#[test]
fn anonymous_product_then_quotient_closes_and_preserves_scaling() {
let mass = linear("mass", dim([0, 1, 0, 0, 0, 0, 0]));
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
let time = linear("duration", dim([0, 0, 1, 0, 0, 0, 0]));
let momentum = linear("momentum", dim([1, 1, -1, 0, 0, 0, 0]));
let result = named(2, &mass)
.multiply(&named(3, &length), &mut meter())
.unwrap()
.divide(&named(2, &time), &mut meter())
.unwrap()
.as_kind(&momentum, &mut meter())
.unwrap();
assert_fraction(result.coordinate(), 3, 1);
let scalar = NumericValue::number(source("2"));
let scaled = scalar.multiply(&named(3, &time), &mut meter()).unwrap();
assert_eq!(scaled.value_type(), &NumericType::Named(time.clone()));
assert_fraction(scaled.coordinate(), 6, 1);
assert_eq!(
named(3, &time)
.divide(&scalar, &mut meter())
.unwrap()
.value_type(),
&NumericType::Named(time.clone())
);
assert_eq!(
scalar
.divide(&named(3, &time), &mut meter())
.unwrap()
.value_type(),
&NumericType::Anonymous(dim([0, 0, -1, 0, 0, 0, 0]))
);
}
#[test]
fn nominal_kinds_survive_comparison_but_explicit_quotients_can_erase_dimension() {
let energy = linear("energy", dim([2, 1, -2, 0, 0, 0, 0]));
let torque = linear("torque", energy.dimension());
let left = named(7, &energy);
let right = named(7, &torque);
assert!(left.add(&right, &mut meter()).is_err());
assert!(left.compare(&right, &mut meter()).is_err());
let ratio = left.divide(&right, &mut meter()).unwrap();
assert_eq!(ratio.value_type(), &NumericType::Number);
assert_fraction(ratio.coordinate(), 1, 1);
let named_ratio = linear("chosen-ratio", Dimension::ZERO);
let asserted = ratio.as_kind(&named_ratio, &mut meter()).unwrap();
assert_eq!(
asserted.value_type(),
&NumericType::Named(named_ratio.clone())
);
assert!(asserted.add(&ratio, &mut meter()).is_err());
assert_eq!(
NumericValue::<String>::new(NumericType::Anonymous(Dimension::ZERO), source("1")),
NumericValue::number(source("1"))
);
}
#[test]
fn numerical_power_types_and_dimension_overflow_are_checked() {
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
let value = named(2, &length);
assert_eq!(
value.power(0, &mut meter()).unwrap().value_type(),
&NumericType::Number
);
assert_eq!(
value.power(1, &mut meter()).unwrap().value_type(),
value.value_type()
);
assert_eq!(
value.power(-2, &mut meter()).unwrap().value_type(),
&NumericType::Anonymous(dim([-2, 0, 0, 0, 0, 0, 0]))
);
let large_dimension = linear("large-dimension", dim([32, 0, 0, 0, 0, 0, 0]));
assert!(
named(1, &large_dimension)
.multiply(&value, &mut meter())
.is_err()
);
assert!(named(1, &large_dimension).power(2, &mut meter()).is_err());
}
+27 -160
View File
@@ -142,87 +142,12 @@ pub struct Analysis {
pub declarations: Vec<DeclarationSpan>,
}
/// Check the decoded spelling required by declaration-header UUID clauses.
/// This is the shared 36-byte/hyphen shape rule, not a hexadecimal parser:
/// callers must additionally parse the UUID. Uppercase hex and JSON escapes
/// that decode to this spelling remain accepted. URN/braced/compact forms do not.
pub fn has_uuid_header_shape(decoded: &str) -> bool {
decoded.len() == 36
&& [8, 13, 18, 23]
.into_iter()
.all(|index| decoded.as_bytes()[index] == b'-')
}
/// Budgets for one original source buffer. Policy is caller-owned; these
/// limits do not change the grammar or perform model admission.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutlineLimits {
pub max_source_bytes: usize,
pub max_tokens: usize,
pub max_declarations: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutlineResource {
SourceBytes,
Tokens,
Declarations,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutlineLimit {
pub resource: OutlineResource,
pub limit: usize,
pub observed_at_least: usize,
/// Original byte offset where admission stopped; never a rewritten offset.
pub offset: usize,
}
/// Roles discovered by the existing tolerant declaration walk. Keeping the
/// wrapper preserves DeclarationSpan and Analysis as existing public APIs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutlineDeclaration {
pub declaration: DeclarationSpan,
pub kind_span: Span,
pub alias_span: Span,
/// Whole quoted header ID token, even if it is not a valid UUID. In that
/// case declaration.id is None. Missing/non-string ID values have no span.
pub id_literal_span: Option<Span>,
}
/// A full-file tolerant scan, not a successful parse or validated model. Invalid
/// text remains available. Lexical errors and unmatched braces are facts only:
/// their absence does not establish syntactic or semantic validity.
///
/// A budget failure returns Err and no partial Outline. Include reachability,
/// project completeness and editor revision are intentionally not inferred here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outline<'a> {
pub source: &'a str,
pub tokens: Vec<TokenSpan>,
pub declarations: Vec<OutlineDeclaration>,
pub has_lexical_errors: bool,
pub has_unmatched_braces: bool,
}
/// Tolerant highlighting tokens cover the whole input, including incomplete
/// strings and unexpected characters. No model is created or modified.
pub fn tokenize(source: &str) -> Vec<TokenSpan> {
tokenize_with_limit(source, usize::MAX).expect("unlimited token scan")
}
fn tokenize_with_limit(source: &str, max_tokens: usize) -> Result<Vec<TokenSpan>, OutlineLimit> {
let mut tokens = Vec::new();
let mut cursor = 0;
while cursor < source.len() {
if tokens.len() == max_tokens {
return Err(OutlineLimit {
resource: OutlineResource::Tokens,
limit: max_tokens,
observed_at_least: tokens.len().saturating_add(1),
offset: cursor,
});
}
let start = cursor;
let ch = source[cursor..].chars().next().expect("in bounds");
let class = if matches!(ch, ' ' | '\t' | '\r' | '\n') {
@@ -299,7 +224,7 @@ fn tokenize_with_limit(source: &str, max_tokens: usize) -> Result<Vec<TokenSpan>
span: Span { start, end: cursor },
});
}
Ok(tokens)
tokens
}
pub fn lint(source: &str) -> Vec<Diagnostic> {
@@ -1305,7 +1230,11 @@ impl Parser<'_> {
self.cursor += 1;
let offset = self.current().span.start;
let value = self.quoted()?;
if !has_uuid_header_shape(&value) {
if value.len() != 36
|| ![8, 13, 18, 23]
.into_iter()
.all(|i| value.as_bytes()[i] == b'-')
{
return Err(Error {
code: "invalid_source",
offset,
@@ -2033,49 +1962,8 @@ fn take_required_id(fields: &mut Map<String, Value>, key: &str) -> Result<Id, St
/// Analyze an incomplete source buffer without adopting a candidate. Declaration
/// spans remain available even when a later declaration contains errors.
/// Invalid compact/braced/URN header IDs retain no authored identity, matching
/// the declaration parser rather than the UUID crate's broader accepted forms.
pub fn analyze(source: &str) -> Analysis {
let tokens = tokenize(source);
let (declarations, _) =
declaration_outline(source, &tokens, usize::MAX).expect("unlimited declaration walk");
Analysis {
tokens,
diagnostics: lint(source),
declarations: declarations.into_iter().map(|d| d.declaration).collect(),
}
}
/// Read exact current text without lint, parsing a model, stabilization or I/O.
/// Source bytes are admitted before token allocation; token/declaration limits
/// are checked before lexing the next token or materializing the next record.
pub fn outline(source: &str, limits: OutlineLimits) -> Result<Outline<'_>, OutlineLimit> {
if source.len() > limits.max_source_bytes {
return Err(OutlineLimit {
resource: OutlineResource::SourceBytes,
limit: limits.max_source_bytes,
observed_at_least: source.len(),
offset: 0,
});
}
let tokens = tokenize_with_limit(source, limits.max_tokens)?;
let has_lexical_errors = tokens.iter().any(|token| token.class == TokenClass::Error);
let (declarations, has_unmatched_braces) =
declaration_outline(source, &tokens, limits.max_declarations)?;
Ok(Outline {
source,
tokens,
declarations,
has_lexical_errors,
has_unmatched_braces,
})
}
fn declaration_outline(
source: &str,
tokens: &[TokenSpan],
max_declarations: usize,
) -> Result<(Vec<OutlineDeclaration>, bool), OutlineLimit> {
let significant = tokens
.iter()
.filter(|t| !matches!(t.class, TokenClass::Whitespace | TokenClass::Comment))
@@ -2084,21 +1972,17 @@ fn declaration_outline(
// again would make tolerant navigation quadratic on deeply nested drafts.
let mut body_ends = vec![None; significant.len()];
let mut bodies = Vec::new();
let mut unmatched_close = false;
for (index, token) in significant.iter().enumerate() {
match &source[token.span.start..token.span.end] {
"{" => bodies.push(index),
"}" => {
if let Some(open) = bodies.pop() {
body_ends[open] = Some(token.span.end);
} else {
unmatched_close = true;
}
}
_ => {}
}
}
let has_unmatched_braces = unmatched_close || !bodies.is_empty();
let mut declarations = Vec::new();
for (i, t) in significant.iter().enumerate() {
let word = &source[t.span.start..t.span.end];
@@ -2123,16 +2007,7 @@ fn declaration_outline(
}
j += 1;
}
if declarations.len() == max_declarations {
return Err(OutlineLimit {
resource: OutlineResource::Declarations,
limit: max_declarations,
observed_at_least: declarations.len().saturating_add(1),
offset: t.span.start,
});
}
let mut id = None;
let mut id_literal_span = None;
if significant
.get(j)
.is_some_and(|t| &source[t.span.start..t.span.end] == "id")
@@ -2140,51 +2015,39 @@ fn declaration_outline(
if let Some(value) = significant.get(j + 1)
&& value.class == TokenClass::String
{
id_literal_span = Some(value.span);
let text =
serde_json::from_str::<String>(&source[value.span.start..value.span.end])
.unwrap();
if has_uuid_header_shape(&text) {
id = Id::parse_str(&text).ok();
}
id = Id::parse_str(&text).ok();
}
j += 2;
}
// A recognized header ID at EOF must remain inside the whole span.
// Keep the old next-token/body behavior; only the EOF fallback changes.
let header_end = significant
.get(j.saturating_sub(1))
.or_else(|| significant.last())
.map_or(alias_token.span.end, |token| token.span.end);
let mut end = significant.get(j).map_or(header_end, |t| t.span.end);
let mut end = significant
.get(j)
.map_or(alias_token.span.end, |t| t.span.end);
if significant
.get(j)
.is_some_and(|t| &source[t.span.start..t.span.end] == "{")
{
end = body_ends[j].unwrap_or(source.len());
}
declarations.push(OutlineDeclaration {
declaration: DeclarationSpan {
alias: alias.into(),
id,
kind: word.into(),
span: Span {
start: t.span.start,
end,
},
declarations.push(DeclarationSpan {
alias: alias.into(),
id,
kind: word.into(),
span: Span {
start: t.span.start,
end,
},
kind_span: t.span,
alias_span: alias_token.span,
id_literal_span,
});
}
Ok((declarations, has_unmatched_braces))
Analysis {
tokens,
diagnostics: lint(source),
declarations,
}
}
#[cfg(test)]
#[path = "language_outline_tests.rs"]
mod outline_tests;
#[cfg(test)]
#[path = "language_nesting_tests.rs"]
mod nesting_tests;
@@ -2579,7 +2442,11 @@ pub(crate) mod legacy {
let value = self.quoted()?;
// Require the portable 8-4-4-4-12 spelling, not the UUID crate's URN,
// braces, or compact alternatives. Uppercase hexadecimal is accepted.
if !super::has_uuid_header_shape(&value) {
if value.len() != 36
|| ![8, 13, 18, 23]
.into_iter()
.all(|index| value.as_bytes()[index] == b'-')
{
return Err(Error {
code: "invalid_source",
offset,
@@ -1,386 +0,0 @@
//! Prepared outline tests. Explicit compatibility tests additionally exercise
//! the existing parsers/analyze; the outline entry itself never calls them.
use super::*;
fn limits() -> OutlineLimits {
OutlineLimits {
max_source_bytes: 1024 * 1024,
max_tokens: 100_000,
max_declarations: 1_000,
}
}
fn declaration<'a>(result: &'a Outline<'_>, alias: &str) -> &'a OutlineDeclaration {
result
.declarations
.iter()
.find(|d| d.declaration.alias == alias)
.unwrap()
}
fn text(source: &str, span: Span) -> &str {
&source[span.start..span.end]
}
#[test]
fn outline_roles_preserve_unicode_crlf_and_exact_escaped_uuid_literal() {
let source = "// 検査 🚒\r\noa_actor responder \"救助\" id \"\\u00300000000-0000-0000-0000-000000000001\" {}\r\nsource @ // 使用\r\n responder;";
let before = source.as_bytes().to_vec();
let result = outline(source, limits()).unwrap();
assert_eq!(result.source.as_bytes(), before);
assert_eq!(result.source.as_ptr(), source.as_ptr());
let d = declaration(&result, "responder");
assert_eq!(text(source, d.kind_span), "oa_actor");
assert_eq!(text(source, d.alias_span), "responder");
assert_eq!(
text(source, d.id_literal_span.unwrap()),
"\"\\u00300000000-0000-0000-0000-000000000001\""
);
assert_eq!(d.declaration.id, Some(Id::from_u128(1)));
assert_eq!(d.declaration.span.start, source.find("oa_actor").unwrap());
assert_eq!(d.declaration.span.end, source.find("{}\r\n").unwrap() + 2);
let mut end = 0;
for token in &result.tokens {
assert_eq!(token.span.start, end);
assert!(token.span.start < token.span.end);
assert!(source.is_char_boundary(token.span.start));
assert!(source.is_char_boundary(token.span.end));
end = token.span.end;
}
assert_eq!(end, source.len());
assert!(!result.has_lexical_errors);
assert!(!result.has_unmatched_braces);
}
#[test]
fn closed_id_at_eof_is_inside_the_declaration_extent() {
for source in [
"oa_actor a \"Actor\" id \"00000000-0000-0000-0000-000000000001\"",
"node placed id \"00000000-0000-0000-0000-000000000001\"",
] {
let result = outline(source, limits()).unwrap();
let d = &result.declarations[0];
let literal = d.id_literal_span.unwrap();
assert_eq!(d.declaration.id, Some(Id::from_u128(1)));
assert_eq!(d.declaration.span.end, source.len());
assert!(d.declaration.span.start <= literal.start);
assert!(literal.end <= d.declaration.span.end);
}
for source in ["oa_actor a \"Actor\"", "oa_actor a \"Actor\" id"] {
let result = outline(source, limits()).unwrap();
let d = &result.declarations[0];
assert_eq!(d.declaration.span.end, source.len());
assert_eq!(d.declaration.id, None);
assert_eq!(d.id_literal_span, None);
}
}
#[test]
fn missing_bad_and_historical_ids_never_allocate_authored_identity() {
let source = "oa_actor missing \"No ID\" {}\noa_actor bad \"Bad ID\" id \"not-a-uuid\" {}\noa_actor historical \"00000000-0000-0000-0000-000000000001\" { history uuid \"00000000-0000-0000-0000-000000000001\"; }";
let first = outline(source, limits()).unwrap();
let second = outline(source, limits()).unwrap();
assert_eq!(first, second);
assert!(
first
.declarations
.iter()
.all(|d| d.declaration.id.is_none())
);
assert_eq!(declaration(&first, "missing").id_literal_span, None);
assert_eq!(declaration(&first, "historical").id_literal_span, None);
assert_eq!(
text(source, declaration(&first, "bad").id_literal_span.unwrap()),
"\"not-a-uuid\""
);
// Balanced tokens are not a successful syntax/semantic validation claim.
assert!(!first.has_lexical_errors);
assert!(!first.has_unmatched_braces);
}
#[test]
fn invalid_full_scan_keeps_closed_children_and_reports_lexical_body_facts() {
let source = "oa_entity outer \"Outer\" {\n oa_actor ready \"Ready\" { description \"} stays text\"; }\n oa_actor pending \"Pending\" { description \"unfinished 🌊";
let result = outline(source, limits()).unwrap();
assert_eq!(result.source, source);
assert_eq!(result.tokens.last().unwrap().span.end, source.len());
assert!(result.has_lexical_errors);
assert!(result.has_unmatched_braces);
let ready = declaration(&result, "ready");
assert_eq!(
text(source, ready.declaration.span),
"oa_actor ready \"Ready\" { description \"} stays text\"; }"
);
assert_eq!(
declaration(&result, "outer").declaration.span.end,
source.len()
);
assert_eq!(
declaration(&result, "pending").declaration.span.end,
source.len()
);
let unmatched_close = outline("}\n// brace in comment {\n", limits()).unwrap();
assert!(unmatched_close.has_unmatched_braces);
assert!(!unmatched_close.has_lexical_errors);
}
#[test]
fn missing_body_syntax_is_unchecked_even_when_known_error_flags_are_clear() {
let source = "oa_actor a \"A\" id \"00000000-0000-0000-0000-000000000001\"";
let result = outline(source, limits()).unwrap();
assert_eq!(result.declarations.len(), 1);
assert!(!result.has_lexical_errors);
assert!(!result.has_unmatched_braces);
// There is deliberately no `valid` flag: the known-complete fact is scanning
// these bytes, not the missing body becoming legal or the draft being applied.
assert_eq!(result.source, source);
}
#[test]
fn keyword_alias_and_collisions_keep_every_source_ordered_header() {
let source = "project root_model \"Model\" {\n oa_actor oa_activity \"First\" id \"00000000-0000-0000-0000-000000000001\" {}\n oa_actor oa_activity \"Second\" id \"00000000-0000-0000-0000-000000000001\" {}\n diagram view_one \"View\" {}\n node placement { diagram @view_one; }\n}";
let result = outline(source, limits()).unwrap();
assert_eq!(result.declarations.len(), 5);
let duplicates: Vec<_> = result
.declarations
.iter()
.filter(|d| d.declaration.alias == "oa_activity")
.collect();
assert_eq!(duplicates.len(), 2);
assert!(duplicates[0].alias_span.start < duplicates[1].alias_span.start);
assert_eq!(duplicates[0].declaration.id, duplicates[1].declaration.id);
assert!(
result
.tokens
.iter()
.any(|t| t.span == duplicates[0].alias_span && t.class == TokenClass::Keyword)
);
assert_eq!(
text(source, declaration(&result, "placement").kind_span),
"node"
);
assert_eq!(declaration(&result, "placement").declaration.id, None);
}
#[test]
fn bounds_refuse_before_returning_a_partial_outline() {
let source = "oa_actor a \"A\" {}\noa_actor b \"B\" {}";
let admitted = outline(source, limits()).unwrap();
let exact = OutlineLimits {
max_source_bytes: source.len(),
max_tokens: admitted.tokens.len(),
max_declarations: 2,
};
assert_eq!(outline(source, exact).unwrap(), admitted);
for resource in [
OutlineResource::SourceBytes,
OutlineResource::Tokens,
OutlineResource::Declarations,
] {
let mut lower = exact;
match resource {
OutlineResource::SourceBytes => lower.max_source_bytes -= 1,
OutlineResource::Tokens => lower.max_tokens -= 1,
OutlineResource::Declarations => lower.max_declarations -= 1,
}
let error = outline(source, lower).unwrap_err();
assert_eq!(error.resource, resource);
assert!(error.observed_at_least > error.limit);
assert!(source.is_char_boundary(error.offset));
if resource == OutlineResource::Declarations {
assert_eq!(error.offset, source.find("oa_actor b").unwrap());
}
}
let empty = outline(
"",
OutlineLimits {
max_source_bytes: 0,
max_tokens: 0,
max_declarations: 0,
},
)
.unwrap();
assert!(empty.tokens.is_empty() && empty.declarations.is_empty());
let unicode = "// 🌊\r\noa_actor a \"A\" {}";
let error = outline(
unicode,
OutlineLimits {
max_source_bytes: 4,
..limits()
},
)
.unwrap_err();
assert_eq!(error.resource, OutlineResource::SourceBytes);
assert_eq!(error.offset, 0);
let error = outline(
unicode,
OutlineLimits {
max_tokens: 1,
..limits()
},
)
.unwrap_err();
assert_eq!(error.resource, OutlineResource::Tokens);
assert_eq!(error.offset, unicode.find('\n').unwrap());
}
#[test]
fn outline_ranges_follow_current_bytes_without_identity_stabilization() {
let old = "oa_actor a \"A\" {}\nsource @a;";
let current = format!("// 航海 🚒\r\n{old}");
let old_outline = outline(old, limits()).unwrap();
let current_outline = outline(&current, limits()).unwrap();
let shift = current.len() - old.len();
let old_role = &old_outline.declarations[0];
let current_role = &current_outline.declarations[0];
assert_eq!(
current_role.alias_span.start,
old_role.alias_span.start + shift
);
assert_eq!(
current_role.kind_span.start,
old_role.kind_span.start + shift
);
assert_eq!(
current_role.declaration.span.end,
old_role.declaration.span.end + shift
);
assert_eq!(current_outline.source, current);
assert_eq!(old_outline.source, old);
assert_eq!(current_role.declaration.id, None);
assert!(!current_outline.source.contains(" id "));
// Workspace revision/stale-handle rejection belongs to the query/adapter,
// not a claim that an old owned span can be applied to any other string.
}
#[test]
fn deeply_nested_bounds_use_the_same_iterative_walk_and_declaration_budget() {
let mut source = String::new();
for index in 0..600 {
source.push_str(&format!("oa_activity work_{index} \"Work\" {{\n"));
}
source.push_str(&"}\n".repeat(600));
let result = outline(&source, limits()).unwrap();
assert_eq!(result.declarations.len(), 600);
assert!(!result.has_unmatched_braces);
assert_eq!(
result.declarations[0].declaration.span.end,
source.len() - 1
);
let error = outline(
&source,
OutlineLimits {
max_declarations: 599,
..limits()
},
)
.unwrap_err();
assert_eq!(error.resource, OutlineResource::Declarations);
assert_eq!(error.observed_at_least, 600);
assert_eq!(error.offset, source.find("oa_activity work_599").unwrap());
}
#[test]
fn noncanonical_uuid_spellings_have_no_outline_or_analysis_identity() {
for raw in [
"00000000000000000000000000000001",
"{00000000-0000-0000-0000-000000000001}",
"urn:uuid:00000000-0000-0000-0000-000000000001",
] {
assert!(
Id::parse_str(raw).is_ok(),
"The UUID crate alone is too permissive"
);
assert!(!has_uuid_header_shape(raw));
let literal = format!("\"{raw}\"");
let modern = format!("arcadia 7; project model \"Model\" id {literal} {{}}");
let before = modern.clone();
let result = outline(&modern, limits()).unwrap();
let d = declaration(&result, "model");
assert_eq!(d.declaration.id, None);
assert_eq!(text(&modern, d.id_literal_span.unwrap()), literal);
assert_eq!(modern, before);
let errors = parse(&modern).unwrap_err();
assert!(
errors
.iter()
.any(|error| error.message.contains("8-4-4-4-12")
&& error.span.start == modern.find(&literal).unwrap())
);
// Intentional compatibility correction: old analyze yielded Some(Id(1))
// here despite lint rejecting the header. It now shares outline's None.
let analysis = analyze(&modern);
assert_eq!(
analysis
.declarations
.iter()
.find(|d| d.alias == "model")
.unwrap()
.id,
None
);
assert!(
analysis
.diagnostics
.iter()
.any(|error| error.message.contains("8-4-4-4-12"))
);
let legacy_source = format!("arcadia 1; project \"Legacy\" id {literal} {{}}");
let legacy_errors = legacy::parse(&legacy_source).unwrap_err();
assert!(
legacy_errors
.iter()
.any(|error| error.message.contains("8-4-4-4-12"))
);
}
}
#[test]
fn uppercase_and_json_escaped_header_ids_survive_both_parsers_and_outline() {
let expected = Id::from_u128(0xabcdef);
let canonical = expected.to_string();
let uppercase = canonical.to_uppercase();
assert_ne!(uppercase, canonical);
for raw in [uppercase.clone(), format!("\\u0030{}", &uppercase[1..])] {
let literal = format!("\"{raw}\"");
let decoded: String = serde_json::from_str(&literal).unwrap();
assert!(has_uuid_header_shape(&decoded));
let modern = format!("arcadia 7; project model \"Model\" id {literal} {{}}");
let result = outline(&modern, limits()).unwrap();
let d = declaration(&result, "model");
assert_eq!(d.declaration.id, Some(expected));
assert_eq!(text(&modern, d.id_literal_span.unwrap()), literal);
assert_eq!(result.source.as_bytes(), modern.as_bytes());
assert_eq!(parse(&modern).unwrap().id, expected);
let analysis = analyze(&modern);
assert_eq!(analysis.declarations[0].id, Some(expected));
assert!(
!analysis
.diagnostics
.iter()
.any(|error| error.severity == crate::validation::Severity::Error)
);
let legacy_source = format!("arcadia 1; project \"Legacy\" id {literal} {{}}");
assert_eq!(legacy::parse(&legacy_source).unwrap().id, expected);
}
}
#[test]
fn header_shape_still_requires_valid_hexadecimal_uuid_data() {
let raw = "00000000-0000-0000-0000-00000000000Z";
assert!(has_uuid_header_shape(raw));
assert!(Id::parse_str(raw).is_err());
let literal = format!("\"{raw}\"");
let source = format!("arcadia 7; project model \"Model\" id {literal} {{}}");
let result = outline(&source, limits()).unwrap();
let d = declaration(&result, "model");
assert_eq!(d.declaration.id, None);
assert_eq!(text(&source, d.id_literal_span.unwrap()), literal);
assert!(
parse(&source)
.unwrap_err()
.iter()
.any(|error| error.message == "Invalid UUID identity.")
);
assert_eq!(analyze(&source).declarations[0].id, None);
}
+1
View File
@@ -1,4 +1,5 @@
//! Framework-independent OA/SA model, transactional commands and editing services.
pub mod analysis_numeric;
pub mod data;
pub mod language;
pub mod model;
-1
View File
@@ -18,7 +18,6 @@ serde_json.workspace = true
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
tokio = { version = "1", features = ["rt", "time"] }
tempfile = "3"
unicode-segmentation = "1.13.3"
[dev-dependencies]
iced_runtime = "0.14"
+864
View File
@@ -0,0 +1,864 @@
//! Pure, bounded allocation-drag composition. See the v2 interaction contract.
//!
//! These values are not input capabilities. The App must independently admit a
//! clean press and retire its token on every document/input/camera lifetime
//! change. Cache a SemanticPlan per token and destination; only `place` belongs
//! on pointer motion. `finish` rechecks the live accepted Project and commands,
//! but Document::execute still owns source admission and atomic history.
use oa_core::{
projection::{self, ProjectedNode, ProjectedView},
validation::{self, Issue, Severity},
view_options::ViewIndex,
*,
};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Destination {
LayoutOnly,
Performer(Id),
OutsidePerformers,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Uniform {
Assigned(Id),
Unassigned,
MixedOrUnresolved,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Leaf {
pub direct: Option<Relation>,
pub role_assignments: Vec<Relation>,
pub role_realizations: Vec<Relation>,
pub effective_performer: Option<Id>,
}
/// Exact semantic scope S, leaf scope L and active placement scope Q, including
/// folded/unplaced leaves. Retaining records detects first-child responsibility
/// transfer. Revision and input-epoch guards remain the caller's responsibility.
#[derive(Debug, Clone, PartialEq)]
pub struct Scope {
pub project: Id,
pub work: Id,
pub placement: Id,
pub work_records: BTreeMap<Id, Element>,
pub leaves: BTreeMap<Id, Leaf>,
pub placements: BTreeMap<Id, NodePlacement>,
pub diagram: Diagram,
pub uniform: Uniform,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangedRecord {
pub id: Id,
pub name: String,
pub category: &'static str,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Refusal {
Ineligible(String),
StaleScope,
MixedLayoutRequired,
RoleExitRequired {
work: Id,
roles: Vec<Id>,
performers: Vec<Id>,
message: String,
},
MissingAllocationId(Id),
InvalidCandidate(String),
CollateralChangeRequired(Vec<ChangedRecord>),
LayoutRequired(String),
}
pub fn capture(p: &Project, diagram: Id, work: Id, placement: Id) -> Result<Scope, Refusal> {
validate_candidate(p).map_err(|e| Refusal::InvalidCandidate(e.to_string()))?;
let d = p.diagrams.get(&diagram).ok_or(Refusal::StaleScope)?;
let root = p.elements.get(&work).ok_or(Refusal::StaleScope)?;
if !root.kind().is_work()
|| d.projection != ProjectionKind::Allocation
|| d.layer != root.layer()
{
return Err(Refusal::Ineligible(
"Select an activity or function in an Allocation view.".into(),
));
}
if d.nodes.get(&placement).is_none_or(|n| n.element != work) {
return Err(Refusal::StaleScope);
}
let mut work_records = BTreeMap::new();
let mut leaves = BTreeMap::new();
let mut pending = vec![work];
while let Some(id) = pending.pop() {
let element = p.elements.get(&id).ok_or(Refusal::StaleScope)?;
if element.kind() != root.kind() || work_records.insert(id, element.clone()).is_some() {
return Err(Refusal::StaleScope);
}
let children: Vec<_> = p
.children(id)
.filter(|e| e.kind() == root.kind())
.map(|e| e.id)
.collect();
if !children.is_empty() {
pending.extend(children);
continue;
}
let direct: Vec<_> = p
.relations
.values()
.filter(|r| r.kind() == RelationKind::Allocation && r.target() == id)
.cloned()
.collect();
if direct.len() > 1 {
return Err(Refusal::StaleScope);
}
let role_assignments: Vec<_> = p
.relations
.values()
.filter(|r| r.kind() == RelationKind::RoleAssignment && r.target() == id)
.cloned()
.collect();
let roles: BTreeSet<_> = role_assignments.iter().map(Relation::source).collect();
let role_realizations = p
.relations
.values()
.filter(|r| r.kind() == RelationKind::RoleRealization && roles.contains(&r.target()))
.cloned()
.collect();
leaves.insert(
id,
Leaf {
direct: direct.into_iter().next(),
role_assignments,
role_realizations,
effective_performer: validation::effective_performer(p, id),
},
);
}
if leaves.is_empty() {
return Err(Refusal::StaleScope);
}
let uniform = if leaves
.values()
.all(|l| l.direct.is_none() && l.role_assignments.is_empty())
{
Uniform::Unassigned
} else if let Some(performer) = leaves.values().next().and_then(|l| l.effective_performer)
&& leaves
.values()
.all(|l| l.effective_performer == Some(performer))
{
Uniform::Assigned(performer)
} else {
Uniform::MixedOrUnresolved
};
let placements = d
.nodes
.iter()
.filter(|(_, n)| work_records.contains_key(&n.element))
.map(|(id, n)| (*id, n.clone()))
.collect();
Ok(Scope {
project: p.id,
work,
placement,
work_records,
leaves,
placements,
diagram: d.clone(),
uniform,
})
}
#[derive(Debug)]
pub struct SemanticPlan {
pub scope: Scope,
pub destination: Destination,
pub label: String,
pub warnings: Vec<Issue>,
accepted: Project,
candidate: Project,
index: ViewIndex,
commands: Vec<Command>,
before_visible: ProjectedView,
before_expanded: ProjectedView,
}
impl SemanticPlan {
/// All preview drawing, ports and routing must use this candidate and index.
pub fn project(&self) -> &Project {
&self.candidate
}
pub fn index(&self) -> &ViewIndex {
&self.index
}
}
/// Allocation identities are allocated once by the gesture owner, keyed by leaf,
/// and reused on target revisits and release. No random identity generation here.
pub fn plan_semantics(
p: &Project,
scope: &Scope,
destination: Destination,
allocation_ids: &BTreeMap<Id, Id>,
) -> Result<SemanticPlan, Refusal> {
if &capture(p, scope.diagram.id, scope.work, scope.placement)? != scope {
return Err(Refusal::StaleScope);
}
if scope.work_records.len() > 1 && scope.uniform == Uniform::MixedOrUnresolved {
return Err(Refusal::MixedLayoutRequired);
}
if let Destination::Performer(id) = destination {
let valid = p
.elements
.get(&id)
.is_some_and(|e| e.kind().is_performer() && e.layer() == scope.diagram.layer);
if !valid {
return Err(Refusal::Ineligible(
"Choose a performer in this layer.".into(),
));
}
}
let before_index = ViewIndex::new(p);
let before_visible = projection::project_diagram_with_index(p, &scope.diagram, &before_index);
let before_expanded = expanded_view(p, &scope.diagram, scope, &before_index);
if scope.work_records.len() > 1 && !coherent(scope, &before_expanded) {
return Err(Refusal::MixedLayoutRequired);
}
let same_performer =
matches!(destination, Destination::Performer(id) if scope.uniform == Uniform::Assigned(id));
let mut expected = p.clone();
let mut commands = Vec::new();
let mut deleted = BTreeSet::new();
if destination != Destination::LayoutOnly && !same_performer {
for (work, leaf) in &scope.leaves {
match destination {
Destination::Performer(performer) => {
if let Some(existing) = &leaf.direct {
if existing.source() != performer {
let mut edited = existing.clone();
edited.body = RelationBody::Allocation {
source: performer,
target: *work,
};
expected.relations.insert(edited.id, edited.clone());
commands.push(Command::EditRelation(edited.id, edited));
}
} else {
let id = *allocation_ids
.get(work)
.ok_or(Refusal::MissingAllocationId(*work))?;
if id.is_nil() || expected.contains(id) {
return Err(Refusal::InvalidCandidate(
"The gesture's allocation identity is already in use.".into(),
));
}
let name = format!("{} performs {}", p.named(performer), p.named(*work));
let relation = Relation {
id,
alias: expected.fresh_alias(&name, "allocation", id),
name,
description: String::new(),
body: RelationBody::Allocation {
source: performer,
target: *work,
},
};
expected.relations.insert(id, relation.clone());
commands.push(Command::CreateRelation(relation));
}
}
Destination::OutsidePerformers => {
if !leaf.role_assignments.is_empty() {
let roles: Vec<_> = leaf
.role_assignments
.iter()
.map(Relation::source)
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let performers: Vec<_> = leaf
.role_realizations
.iter()
.map(Relation::source)
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let message = if leaf.direct.is_some() && performers.len() == 1 {
format!(
"Removing direct assignment would place {} in {} through its role.",
p.named(*work),
p.named(performers[0])
)
} else {
format!(
"{} retains role responsibility through {}{}; edit that responsibility before moving outside performers.",
p.named(*work),
roles
.iter()
.map(|id| p.named(*id))
.collect::<Vec<_>>()
.join(", "),
if performers.is_empty() {
String::new()
} else {
format!(
" ({})",
performers
.iter()
.map(|id| p.named(*id))
.collect::<Vec<_>>()
.join(", ")
)
}
)
};
return Err(Refusal::RoleExitRequired {
work: *work,
roles,
performers,
message,
});
}
if let Some(existing) = &leaf.direct {
expected.relations.remove(&existing.id);
deleted.insert(existing.id);
commands.push(Command::Delete(existing.id));
}
}
Destination::LayoutOnly => unreachable!(),
}
}
}
// A route cannot survive the intentional deletion of its own edge, even in
// another diagram. No other saved-view cleanup is authorized by this drag.
for diagram in expected.diagrams.values_mut() {
diagram.routes.retain(|r| !deleted.contains(&r.edge));
}
let actual = prepare_command(p, &Command::Batch(commands.clone()))
.map_err(|e| Refusal::InvalidCandidate(e.to_string()))?
.project;
exact_project(&expected, &actual)?;
let retained_roles = scope
.leaves
.values()
.any(|l| !l.role_assignments.is_empty());
let label = match destination {
Destination::LayoutOnly => "Arrange only".into(),
Destination::Performer(id) if same_performer => format!("Arrange within {}", p.named(id)),
Destination::Performer(id) => format!(
"Assign {} leaf {} to {}{}",
scope.leaves.len(),
match (scope.diagram.layer, scope.leaves.len()) {
(Layer::Oa, 1) => "activity",
(Layer::Oa, _) => "activities",
(Layer::Sa, 1) => "function",
(Layer::Sa, _) => "functions",
},
p.named(id),
if retained_roles {
" — explicit assignment; role responsibility retained"
} else {
""
}
),
Destination::OutsidePerformers if commands.is_empty() => {
"Arrange unassigned work — decomposition retained".into()
}
Destination::OutsidePerformers => "Remove assignment — decomposition retained".into(),
};
let warnings = validation::validate(&actual)
.into_iter()
.filter(|i| i.severity == Severity::Warning)
.collect();
let index = ViewIndex::new(&actual);
Ok(SemanticPlan {
scope: scope.clone(),
destination,
label,
warnings,
accepted: p.clone(),
candidate: actual,
index,
commands,
before_visible,
before_expanded,
})
}
/// World-space rectangle in the gesture's frozen transform. The UI resolver
/// owns half-open pointer hits, semantic target precedence and occlusion.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
pub position: Position,
pub size: Size,
}
impl Rect {
fn valid(self) -> bool {
[
self.position.x,
self.position.y,
self.size.width,
self.size.height,
]
.iter()
.all(|n| n.is_finite() && n.abs() <= MAX_COORDINATE)
&& self.size.width > 0.
&& self.size.height > 0.
}
fn contains(self, other: Self) -> bool {
other.position.x >= self.position.x
&& other.position.y >= self.position.y
&& other.position.x + other.size.width <= self.position.x + self.size.width
&& other.position.y + other.size.height <= self.position.y + self.size.height
}
fn overlaps(self, other: Self) -> bool {
self.position.x < other.position.x + other.size.width
&& other.position.x < self.position.x + self.size.width
&& self.position.y < other.position.y + other.size.height
&& other.position.y < self.position.y + self.size.height
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TargetPresentation {
pub placement: Id,
/// Exact frozen painted label bounds, supplied by the renderer/resolver.
pub label: Rect,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PresentationContext {
/// Visible world rectangle derived from the actual captured pan/zoom/bounds.
pub viewport: Rect,
pub zoom: f32,
pub target: Option<TargetPresentation>,
}
#[derive(Debug)]
pub struct PlacementPlan {
pub diagram: Diagram,
pub view: ProjectedView,
pub delta: Position,
pub unfolded: Option<Id>,
requested: Position,
presentation: PresentationContext,
commands: Vec<Command>,
}
/// `requested` is the original selected placement position plus pointer motion
/// in the frozen transform (therefore preserving the press offset). Snap only
/// this root; apply the resulting identical delta to captured Q and its routes.
/// No whole Project clone, validator or semantic ViewIndex rebuild occurs here.
pub fn place(
plan: &SemanticPlan,
requested: Position,
presentation: PresentationContext,
) -> Result<PlacementPlan, Refusal> {
if !requested.x.is_finite()
|| !requested.y.is_finite()
|| !presentation.viewport.valid()
|| !presentation.zoom.is_finite()
|| presentation.zoom <= 0.
{
return Err(Refusal::LayoutRequired(
"Make room or adjust the view, then drag again.".into(),
));
}
let root = &plan.scope.placements[&plan.scope.placement];
let delta = Position {
x: (requested.x / 10.).round() * 10. - root.position.x,
y: (requested.y / 10.).round() * 10. - root.position.y,
};
let mut diagram = plan.candidate.diagrams[&plan.scope.diagram.id].clone();
let mut commands = Vec::new();
let mut deltas = BTreeMap::new();
for (id, original) in &plan.scope.placements {
let node = diagram.nodes.get_mut(id).ok_or(Refusal::StaleScope)?;
node.position = Position {
x: original.position.x + delta.x,
y: original.position.y + delta.y,
};
if !(Rect {
position: node.position,
size: node.size,
})
.valid()
{
return Err(Refusal::InvalidCandidate(
"Moved coordinates exceed the model bounds.".into(),
));
}
deltas.insert(*id, delta);
if node != original {
commands.push(Command::EditNode {
diagram: diagram.id,
original: *id,
node: node.clone(),
});
}
}
// Resolve endpoints using the captured accepted semantics, not a newly
// regrouped descendant walk. Own-edge deletions were removed above already.
for route in projection::translated_routes(&plan.accepted, &plan.scope.diagram, &deltas) {
if let Some(existing) = diagram.routes.iter_mut().find(|r| r.edge == route.edge) {
if route.waypoints.iter().any(|p| {
!p.x.is_finite()
|| !p.y.is_finite()
|| p.x.abs() > MAX_COORDINATE
|| p.y.abs() > MAX_COORDINATE
}) {
return Err(Refusal::InvalidCandidate(
"Moved route exceeds the model bounds.".into(),
));
}
*existing = route.clone();
commands.push(Command::SetEdgeRoute {
diagram: diagram.id,
route,
});
}
}
let mut unfolded = None;
if let Destination::Performer(performer) = plan.destination {
let target = presentation.target.ok_or_else(|| {
Refusal::LayoutRequired("The frozen performer label must be visible.".into())
})?;
let node = diagram
.nodes
.get_mut(&target.placement)
.ok_or(Refusal::StaleScope)?;
let frozen_header = plan
.before_visible
.nodes
.iter()
.find(|n| n.id == target.placement)
.map(|n| Rect {
position: n.position,
size: Size {
width: n.size.width,
height: n.size.height.min(62.),
},
});
if node.element != performer
|| frozen_header.is_none_or(|header| !header.contains(target.label))
|| !target.label.valid()
|| !presentation.viewport.contains(target.label)
{
return Err(Refusal::LayoutRequired(
"Make room or adjust the view, then drag again.".into(),
));
}
if node.collapsed && !plan.commands.is_empty() {
node.collapsed = false;
unfolded = Some(node.id);
commands.push(Command::EditNode {
diagram: diagram.id,
original: node.id,
node: node.clone(),
});
}
} else if presentation.target.is_some() {
return Err(Refusal::Ineligible(
"This layout/outside destination has no performer target.".into(),
));
}
let view = projection::project_diagram_with_index(&plan.candidate, &diagram, &plan.index);
let expanded = expanded_view(&plan.candidate, &diagram, &plan.scope, &plan.index);
check_geometry(plan, &view, &expanded, delta)?;
let selected = view
.nodes
.iter()
.find(|n| n.id == plan.scope.placement)
.ok_or_else(|| {
Refusal::LayoutRequired("The selected work header would be hidden.".into())
})?;
let header = Rect {
position: selected.position,
size: Size {
width: selected.size.width,
height: selected.size.height.min(62.),
},
};
if !presentation.viewport.contains(header) {
return Err(Refusal::LayoutRequired(
"Make room or adjust the view, then drag again.".into(),
));
}
// A performer may legitimately enclose the work, but its frozen feedback
// label is painted above the candidate. Check their joint readability after
// projection, including same-performer moves; never shift either rectangle.
if presentation
.target
.is_some_and(|target| header.overlaps(target.label))
{
return Err(Refusal::LayoutRequired(
"The work header overlaps the performer label. Aim below or beside the label, then drag again."
.into(),
));
}
Ok(PlacementPlan {
diagram,
view,
delta,
unfolded,
requested,
presentation,
commands,
})
}
/// Final semantic/presentation equality gate, after the App has checked its
/// current token, owner, revision, clean drafts, frozen target and transform.
/// Recompute geometry to avoid accepting a modified/stale placement result.
/// None means a snapped no-op: the caller must not execute or add history.
pub fn finish(
plan: &SemanticPlan,
live: &Project,
placement: &PlacementPlan,
) -> Result<Option<Command>, Refusal> {
if live != &plan.accepted {
return Err(Refusal::StaleScope);
}
let checked = place(plan, placement.requested, placement.presentation)?;
if checked.diagram != placement.diagram
|| checked.view != placement.view
|| checked.delta != placement.delta
|| checked.unfolded != placement.unfolded
|| checked.commands != placement.commands
{
return Err(Refusal::StaleScope);
}
let mut expected = plan.candidate.clone();
expected
.diagrams
.insert(checked.diagram.id, checked.diagram);
let mut commands = plan.commands.clone();
commands.extend(checked.commands);
let command = Command::Batch(commands);
let actual = prepare_command(live, &command)
.map_err(|e| Refusal::InvalidCandidate(e.to_string()))?
.project;
exact_project(&expected, &actual)?;
Ok((actual != *live).then_some(command))
}
fn expanded_view(
p: &Project,
diagram: &Diagram,
scope: &Scope,
index: &ViewIndex,
) -> ProjectedView {
let mut expanded = diagram.clone();
for id in scope.placements.keys() {
if let Some(node) = expanded.nodes.get_mut(id) {
node.collapsed = false;
}
}
projection::project_diagram_with_index(p, &expanded, index)
}
fn ancestors(view: &ProjectedView) -> BTreeMap<Id, BTreeSet<Id>> {
let parents: BTreeMap<_, _> = view.nodes.iter().map(|n| (n.id, n.visual_parent)).collect();
parents
.keys()
.map(|node| {
let mut current = parents[node];
let mut seen = BTreeSet::new();
while let Some(id) = current {
if !seen.insert(id) {
break;
}
current = parents.get(&id).copied().flatten();
}
(*node, seen)
})
.collect()
}
fn coherent(scope: &Scope, view: &ProjectedView) -> bool {
let ancestors = ancestors(view);
scope.placements.keys().all(|id| {
ancestors
.get(id)
.is_some_and(|parents| *id == scope.placement || parents.contains(&scope.placement))
})
}
fn overlap(a: &ProjectedNode, b: &ProjectedNode) -> f32 {
let width = (a.position.x + a.size.width).min(b.position.x + b.size.width)
- a.position.x.max(b.position.x);
let height = (a.position.y + a.size.height).min(b.position.y + b.size.height)
- a.position.y.max(b.position.y);
width.max(0.) * height.max(0.)
}
fn overlaps(before: &ProjectedView, after: &ProjectedView) -> bool {
// Build geometry ancestry once, avoiding a repeated descendant walk for
// every pair during pointer motion. Pairwise collision checking is bounded
// to these two projected scenes and does not traverse/clone model semantics.
let before_ancestors = ancestors(before);
let after_ancestors = ancestors(after);
let prior_nodes: BTreeMap<_, _> = before.nodes.iter().map(|n| (n.id, n)).collect();
for (i, a) in after.nodes.iter().enumerate() {
for b in &after.nodes[i + 1..] {
if after_ancestors[&a.id].contains(&b.id) || after_ancestors[&b.id].contains(&a.id) {
continue;
}
let prior = match (prior_nodes.get(&a.id), prior_nodes.get(&b.id)) {
(Some(x), Some(y))
if !before_ancestors[&x.id].contains(&y.id)
&& !before_ancestors[&y.id].contains(&x.id) =>
{
overlap(x, y)
}
_ => 0.,
};
if overlap(a, b) > prior + 0.01 {
return true;
}
}
}
false
}
fn check_geometry(
plan: &SemanticPlan,
visible: &ProjectedView,
expanded: &ProjectedView,
delta: Position,
) -> Result<(), Refusal> {
if visible.nodes.iter().chain(&expanded.nodes).any(|n| {
!(Rect {
position: n.position,
size: n.size,
})
.valid()
}) {
return Err(Refusal::InvalidCandidate(
"The projected enclosure exceeds the model bounds.".into(),
));
}
if plan.scope.work_records.len() > 1 {
if !coherent(&plan.scope, expanded) {
return Err(Refusal::MixedLayoutRequired);
}
for id in plan.scope.placements.keys() {
let old = plan
.before_expanded
.nodes
.iter()
.find(|n| n.id == *id)
.ok_or(Refusal::MixedLayoutRequired)?;
let new = expanded
.nodes
.iter()
.find(|n| n.id == *id)
.ok_or(Refusal::MixedLayoutRequired)?;
if (new.position.x - old.position.x - delta.x).abs() > 0.01
|| (new.position.y - old.position.y - delta.y).abs() > 0.01
|| (new.size.width - old.size.width).abs() > 0.01
|| (new.size.height - old.size.height).abs() > 0.01
{
return Err(Refusal::LayoutRequired("This work subtree requires an explicit layout; its footprint cannot be translated unchanged.".into()));
}
}
}
if overlaps(&plan.before_visible, visible) || overlaps(&plan.before_expanded, expanded) {
return Err(Refusal::LayoutRequired("Make room before moving work: the candidate would introduce or enlarge overlapping cards.".into()));
}
Ok(())
}
/// Compare complete records, not just removed IDs. Deleting an Allocation can
/// rewrite a surviving Constraint, remove artifacts/traces or prune view options.
fn exact_project(expected: &Project, actual: &Project) -> Result<(), Refusal> {
if expected == actual {
return Ok(());
}
let mut records = Vec::new();
fn changes<T: PartialEq>(
expected: &BTreeMap<Id, T>,
actual: &BTreeMap<Id, T>,
category: &'static str,
project: &Project,
other: &Project,
records: &mut Vec<ChangedRecord>,
) {
let ids: BTreeSet<_> = expected.keys().chain(actual.keys()).copied().collect();
for id in ids {
if expected.get(&id) != actual.get(&id) {
records.push(ChangedRecord {
id,
name: if project.contains(id) {
project.named(id)
} else {
other.named(id)
}
.into(),
category,
});
}
}
}
changes(
&expected.elements,
&actual.elements,
"element",
expected,
actual,
&mut records,
);
changes(
&expected.relations,
&actual.relations,
"relation",
expected,
actual,
&mut records,
);
changes(
&expected.diagrams,
&actual.diagrams,
"diagram",
expected,
actual,
&mut records,
);
changes(
&expected.artifact_links,
&actual.artifact_links,
"artifact",
expected,
actual,
&mut records,
);
changes(
&expected.traces,
&actual.traces,
"trace",
expected,
actual,
&mut records,
);
if expected.schema_version != actual.schema_version
|| expected.id != actual.id
|| expected.alias != actual.alias
|| expected.name != actual.name
|| expected.description != actual.description
{
records.push(ChangedRecord {
id: expected.id,
name: expected.name.clone(),
category: "project",
});
}
Err(Refusal::CollateralChangeRequired(records))
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large Load Diff
+266
View File
@@ -0,0 +1,266 @@
//! A narrow dispatch boundary for Allocation work gestures. Iced rows visit
//! siblings after capture; refusing inside Canvas alone still blurs an inspector
//! field. Refuse before dispatching that press to any ordinary child instead.
use crate::{
app::{
App, Message,
allocation_drag::{self, Event as WorkEvent},
},
diagram::DiagramCanvas,
};
use iced::advanced::{
Clipboard, Layout, Shell, Widget, layout, overlay, renderer,
widget::{Id, Operation, Tree, tree},
};
use iced::{
Element, Event, Length, Point, Rectangle, Renderer, Size, Theme, Vector, keyboard, mouse,
};
pub const CANVAS_ID: &str = "allocation-work-canvas";
pub const ARRANGE_SHORTCUT: &str = "Alt+A";
struct Root<'a> {
app: &'a App,
content: Element<'a, Message>,
}
#[derive(Default)]
struct State {
pointer: Option<Point>,
refused_left: bool,
}
#[derive(Default)]
struct CanvasBounds(Option<Rectangle>);
impl Operation for CanvasBounds {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation)) {
visit(self);
}
fn container(&mut self, id: Option<&Id>, bounds: Rectangle) {
if id == Some(&Id::new(CANVAS_ID)) {
self.0 = Some(bounds);
}
}
}
pub fn root<'a>(app: &'a App, content: impl Into<Element<'a, Message>>) -> Element<'a, Message> {
Element::new(Root {
app,
content: content.into(),
})
}
fn arrange_key(event: &Event) -> bool {
matches!(event, Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Character(key), modifiers, repeat: false, ..
}) if key.eq_ignore_ascii_case("a") && *modifiers == keyboard::Modifiers::ALT)
}
impl Root<'_> {
fn dirty_object(&self, bounds: Rectangle, screen: Point) -> bool {
let Some(diagram) = self.app.active_diagram else {
return false;
};
if !allocation_drag::contains(bounds, screen) {
return false;
}
let canvas = DiagramCanvas {
allocation: Some(self.app.allocation_capability()),
project: self.app.project(),
view_index: Some(self.app.document.view_index()),
diagram,
selected: self.app.selected,
zoom: self.app.zoom,
pan: self.app.pan,
context: self.app.route_context().unwrap(),
selected_bend: None,
editable: false,
placing: false,
connection: None,
};
canvas.work_dirty_point(bounds, screen)
}
}
impl Widget<Message, Theme, Renderer> for Root<'_> {
fn tag(&self) -> tree::Tag {
tree::Tag::of::<State>()
}
fn state(&self) -> tree::State {
tree::State::new(State::default())
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(self.content.as_widget())]
}
fn diff(&self, tree: &mut Tree) {
tree.diff_children(std::slice::from_ref(&self.content));
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(
&mut self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn Operation,
) {
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
let state = tree.state.downcast_mut::<State>();
match event {
Event::Mouse(mouse::Event::CursorMoved { position }) => state.pointer = Some(*position),
Event::Mouse(mouse::Event::CursorLeft) => state.pointer = None,
Event::Window(iced::window::Event::RedrawRequested(_)) => {
state.pointer = cursor.position()
}
Event::Window(iced::window::Event::Unfocused) => {
state.pointer = None;
state.refused_left = false;
}
_ => {}
}
if state.refused_left {
if matches!(
event,
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
) {
state.refused_left = false;
shell.capture_event();
return;
}
if matches!(event, Event::Mouse(mouse::Event::CursorMoved { .. })) {
shell.capture_event();
return;
}
}
if self.app.allocation_input_owner() && !shell.is_event_captured() {
if arrange_key(event) {
// App rechecks clean ownership before arming. A dirty field
// retains its actual widget focus and selection on refusal.
shell.publish(Message::WorkDrag(WorkEvent::ArrangeNext));
shell.capture_event();
return;
}
if self.app.allocation_drag.arrange_next
&& matches!(
event,
Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(keyboard::key::Named::Escape),
..
})
)
{
shell.publish(Message::Escape);
shell.capture_event();
return;
}
if !self.app.allocation_drag_clean()
&& matches!(
event,
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
)
&& let Some(screen) = state.pointer.or_else(|| cursor.position())
{
let mut canvas = CanvasBounds::default();
self.content.as_widget_mut().operate(
&mut tree.children[0],
layout,
renderer,
&mut canvas,
);
if canvas
.0
.is_some_and(|bounds| self.dirty_object(bounds, screen))
{
state.refused_left = true;
shell.publish(Message::WorkDrag(WorkEvent::Refused(
self.app.allocation_drag.epoch,
allocation_drag::FINISH_EDIT.into(),
)));
shell.capture_event();
return;
}
}
}
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'b>,
renderer: &Renderer,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
+83 -304
View File
@@ -1,16 +1,17 @@
pub(crate) mod allocation_drag;
pub(crate) mod architecture_authoring;
#[cfg(test)]
mod architecture_authoring_tests;
mod checkpoints;
mod diagram_reveal;
pub(crate) mod diagram_removal;
#[cfg(test)]
mod diagram_removal_tests;
#[cfg(test)]
mod diagram_selection_tests;
mod diagram_usages;
mod hosted;
mod reference_authoring;
#[cfg(test)]
mod review_navigation_tests;
mod source_symbols;
#[cfg(test)]
mod transition_context_tests;
#[cfg(test)]
@@ -330,6 +331,7 @@ pub struct FilePrompt {
#[derive(Debug, Clone)]
pub enum Message {
WorkDrag(allocation_drag::Event),
BehaviorControl(behavior::canvas_workspace::Intent),
Architecture(architecture_authoring::Event),
Home(crate::home::Event),
@@ -394,7 +396,9 @@ pub enum Message {
RelationKind(RelationKind),
Command(Command),
Delete,
ConfirmDelete,
ConfirmDelete(u64),
DiagramRemove(diagram_removal::Intent),
DiagramTraverse(bool),
CancelDelete,
Undo,
Redo,
@@ -430,18 +434,9 @@ pub enum Message {
Linted(u64, Result<Vec<SourceDiagnostic>, String>),
SourceDiagnostic(usize),
SourceRelated(SourceLocation),
SourceViewport(Option<Id>),
SourceSymbols(
crate::source_navigation::SymbolContext,
crate::source_navigation::SymbolEvent,
),
SourceSymbolsReady(crate::source_navigation::Completion),
DiagramUsage(crate::diagram_usage::Event),
DiagramUsagesReady(crate::diagram_usage::Completion),
DiagramRevealViewport(crate::diagram_usage::Context, u64, iced::Size),
SourceViewport,
SourceForSelection,
SourceNavigation(crate::source_navigation::Event),
SourceFindClose(crate::source_navigation::SymbolContext, Id),
Save(bool),
SavePath(Option<PathBuf>),
Saved(Result<Option<FileSnapshot>, SaveFailure>),
@@ -462,6 +457,7 @@ pub enum Message {
}
pub struct App {
pub allocation_drag: allocation_drag::State,
pub home: crate::home::State,
pub recovery: crate::recovery::State,
recent_target: Option<PathBuf>,
@@ -501,6 +497,7 @@ pub struct App {
pub busy: bool,
pub pending: Option<Pending>,
pub delete_pending: bool,
pub delete_target: Option<diagram_removal::Confirmation>,
pub path: Option<PathBuf>,
/// A disk transaction requiring an explicit action, independent of lint.
pub pending_recovery: Option<PathBuf>,
@@ -519,17 +516,6 @@ pub struct App {
pub source_jump: Option<text_editor::Cursor>,
source_select_line: bool,
pub source_navigation: crate::source_navigation::State,
source_find_instance: Id,
pub source_symbols: crate::source_navigation::SymbolState,
pub(crate) diagram_usages: Option<crate::diagram_usage::Panel>,
pub(crate) diagram_navigation_focus: Option<crate::diagram_usage::Focus>,
source_diagram_job: Option<Id>,
diagram_lookup_in_flight: Option<Id>,
pending_diagram_reveal: Option<(
crate::diagram_usage::Context,
crate::diagram_usage::Usage,
u64,
)>,
pub model_issues: Vec<validation::Issue>,
pub migration: Option<persistence::MigrationReport>,
source_version: u64,
@@ -580,6 +566,7 @@ impl App {
let explorer_index = crate::explorer::Index::new(&project, layer);
let explorer_collapsed = project.elements.values().filter_map(|e| e.parent).collect();
let mut app = Self {
allocation_drag: Default::default(),
home: Default::default(),
recovery: Default::default(),
recent_target: None,
@@ -621,6 +608,7 @@ impl App {
busy: false,
pending: None,
delete_pending: false,
delete_target: None,
path: None,
pending_recovery: None,
disk_project: None,
@@ -638,13 +626,6 @@ impl App {
source_jump: None,
source_select_line: false,
source_navigation: crate::source_navigation::State::default(),
source_find_instance: Id::new_v4(),
source_symbols: crate::source_navigation::SymbolState::default(),
diagram_usages: None,
diagram_navigation_focus: None,
source_diagram_job: None,
diagram_lookup_in_flight: None,
pending_diagram_reveal: None,
model_issues,
migration: None,
source_version: 0,
@@ -698,7 +679,6 @@ impl App {
self.lint_requested = None;
}
fn show_source_file(&mut self, restore_cursor: bool) {
self.source_symbols.reveal = None;
self.source_tree.reveal(&self.source_workspace.active);
self.source_select_line = false;
let source = self.source_workspace.text().to_owned();
@@ -713,9 +693,6 @@ impl App {
.map(|b| b.cursor)
})
.flatten();
if let Some(cursor) = self.source_jump {
self.queue_source_reveal(cursor, false);
}
}
fn selected_architecture_placement(&self) -> Option<Id> {
self.active_diagram
@@ -969,8 +946,6 @@ impl App {
let canvas_size = self.canvas_size;
let source_version = self.source_version + 1;
let lint_running = self.lint_running;
let navigation_in_flight = self.source_symbols.in_flight;
let diagram_lookup_in_flight = self.diagram_lookup_in_flight;
let guide = std::mem::take(&mut self.guide);
let mut hosted = std::mem::take(&mut self.hosted);
hosted.leave_document();
@@ -982,8 +957,6 @@ impl App {
self.canvas_size = canvas_size;
self.source_version = source_version;
self.lint_running = lint_running;
self.source_symbols.in_flight = navigation_in_flight;
self.diagram_lookup_in_flight = diagram_lookup_in_flight;
self.guide = guide;
self.path = path;
self.status = "Project ready".into();
@@ -1084,73 +1057,35 @@ impl App {
crate::model_menu::popup(self),
)
.into();
crate::source_navigation::interaction::observe(
crate::behavior::scenario::focus::root(
behavior::canvas_workspace::focus_root(
crate::hosted::view::overlay(
self,
self.reference_overlay(crate::diagram_usage::view::overlay(self, base)),
),
behavior::canvas_workspace::Scope::input_owner(self),
),
self.scenario_focus_owner(),
crate::behavior::scenario::focus::root(
behavior::canvas_workspace::focus_root(
crate::hosted::view::overlay(self, self.reference_overlay(base)),
behavior::canvas_workspace::Scope::input_owner(self),
),
self.source_symbols.raw_interaction.clone(),
self.scenario_focus_owner(),
)
}
pub fn subscription(&self) -> Subscription<Message> {
Subscription::batch([
self.diagram_usages
.as_ref()
.map_or_else(Subscription::none, |panel| {
iced::event::listen_with(|event, status, _| {
let iced::Event::Keyboard(keyboard::Event::KeyPressed {
key,
modifiers,
..
}) = event
else {
return None;
};
if !modifiers.is_empty() {
return None;
}
match key {
keyboard::Key::Named(keyboard::key::Named::ArrowUp) => Some(-1i8),
keyboard::Key::Named(keyboard::key::Named::ArrowDown) => Some(1i8),
keyboard::Key::Named(keyboard::key::Named::Enter)
if status == iced::event::Status::Ignored =>
{
Some(0i8)
}
_ => None,
}
})
.with(panel.token)
.map(|(token, step)| {
Message::DiagramUsage(if step == 0 {
crate::diagram_usage::Event::Activate(token)
} else {
crate::diagram_usage::Event::Move(token, step)
})
})
}),
iced::time::every(std::time::Duration::from_secs(10)).map(|_| Message::CheckpointTick),
window::close_requests().map(|id| Message::Request(Pending::Close(id))),
window::resize_events().map(|(_, size)| Message::WindowResized(size)),
architecture_authoring::subscription(self),
// Use one captured-Escape bridge: a focused Find input consumes
// Escape, while modal priority remains in the ordinary handler.
iced::event::listen_with(|event, _, _| {
matches!(
event,
iced::Event::Keyboard(keyboard::Event::KeyPressed { .. })
)
.then_some(Message::WorkDrag(allocation_drag::Event::KeyboardBoundary))
}),
behavior::creation::subscription(
self.behavior.creation.has_pending()
|| self.diagram_usages.is_some()
|| self.behavior.source_active()
|| (self.page == Page::Text
&& (self.source_symbols.open || self.source_navigation.open)
&& self.architecture.is_none()),
self.behavior.creation.has_pending() || self.behavior.source_active(),
)
.map(|()| Message::Escape),
iced::event::listen_with(|event, status, _| {
if matches!(event, iced::Event::Window(window::Event::Unfocused)) {
return Some(Message::WorkDrag(allocation_drag::Event::Unfocused));
}
let iced::Event::Keyboard(keyboard::Event::KeyPressed {
key,
modifiers: mods,
@@ -1194,17 +1129,11 @@ impl App {
])
}
pub fn update(&mut self, message: Message) -> Task<Message> {
let usage_viewport = self.diagram_reveal_viewport(&message);
let window_resized = matches!(&message, Message::WindowResized(_));
// Reject stale measurements before legacy viewport handlers can change
// dimensions or invalidate the exact pending destination epoch.
if self.pending_diagram_reveal.is_some()
&& Self::is_diagram_viewport(&message)
&& usage_viewport.is_none()
{
return Task::none();
self.allocation_before(&message);
if let Message::WorkDrag(event) = message {
return self.allocation_event(event);
}
self.reconcile_pending_diagram_reveal(&message);
let allocation_before = self.allocation_boundary();
if let Message::BehaviorControl(intent) = message {
return self.behavior_control(intent);
}
@@ -1215,18 +1144,8 @@ impl App {
);
let before = self.camera_boundary();
let task = self.update_inner(message);
if window_resized && let Some((_, _, epoch)) = &mut self.pending_diagram_reveal {
*epoch = self.canvas_epoch;
}
if let Some(surface) = usage_viewport {
self.finish_diagram_reveal(surface);
}
if self
.diagram_navigation_focus
.as_ref()
.is_some_and(|focus| self.diagram_focus(focus.usage.surface).is_none())
{
self.diagram_navigation_focus = None;
if self.allocation_boundary() != allocation_before {
self.allocation_retire();
}
if !camera && self.camera_boundary() != before {
self.camera_epoch = self.camera_epoch.wrapping_add(1);
@@ -1317,75 +1236,6 @@ impl App {
)
}
fn update_inner(&mut self, message: Message) -> Task<Message> {
let message = match message {
Message::SourceFindClose(context, instance) => {
if context != self.source_symbol_context()
|| instance != self.source_find_instance
|| !self.source_navigation.open
|| !self.source_navigation_available()
{
return Task::none();
}
// Only the checked envelope may enter the legacy Close handler.
Message::SourceNavigation(crate::source_navigation::Event::Close)
}
Message::SourceNavigation(crate::source_navigation::Event::Close) => {
return Task::none();
}
message => message,
};
if let Message::SourceSymbols(context, _) = &message
&& (context.session != self.source_workspace.session()
|| context.path != self.source_workspace.active)
{
return Task::none();
}
// Internal results and geometry do not constitute a new user intent.
// Process query completion even behind a modal to release its worker slot;
// its handler independently refuses navigation outside the live editor.
if let Message::SourceSymbolsReady(completion) = message {
return self.source_symbols_ready(completion);
}
if let Message::DiagramUsagesReady(completion) = message {
return self.diagram_usages_ready(completion);
}
if !matches!(
&message,
Message::CheckpointTick
| Message::CheckpointWritten(..)
| Message::Lint(_)
| Message::Linted(..)
| Message::SourceViewport(_)
| Message::WindowResized(_)
| Message::CanvasResized(_)
| Message::DiagramRevealViewport(..)
) {
self.source_interaction();
}
if let Message::DiagramUsage(event) = message {
return self.diagram_usage_event(event);
}
if let Some(panel) = &self.diagram_usages {
if matches!(&message, Message::Request(Pending::Close(_))) {
self.diagram_usages = None;
return self.update(message);
}
if matches!(&message, Message::Escape) {
return self.diagram_usage_event(crate::diagram_usage::Event::Close(panel.token));
}
if !matches!(
&message,
Message::CheckpointTick
| Message::CheckpointWritten(..)
| Message::Lint(_)
| Message::Linted(..)
| Message::WindowResized(_)
| Message::CanvasResized(_)
| Message::SourceViewport(_)
) {
return Task::none();
}
}
if let Some(task) = self.reference_message(&message) {
return task;
}
@@ -1453,7 +1303,7 @@ impl App {
| Message::CanvasResized(_)
| Message::Lint(_)
| Message::Linted(_, _)
| Message::SourceViewport(_)
| Message::SourceViewport
| Message::Request(Pending::Close(_))
)
{
@@ -1499,7 +1349,7 @@ impl App {
| Message::Exported(_)
| Message::WindowResized(_)
| Message::CanvasResized(_)
| Message::SourceViewport(_)
| Message::SourceViewport
)
{
return Task::none();
@@ -1523,6 +1373,8 @@ impl App {
}
if self.delete_pending {
self.delete_pending = false;
self.delete_target = None;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
return Task::none();
}
if self.pending.take().is_some() {
@@ -1537,7 +1389,7 @@ impl App {
| Message::CheckpointLoaded(..)
| Message::WindowResized(_)
| Message::CanvasResized(_)
| Message::SourceViewport(_)
| Message::SourceViewport
| Message::Lint(_)
| Message::Linted(_, _)
| Message::Saved(_)
@@ -1557,7 +1409,7 @@ impl App {
Message::FilePath(_) | Message::SubmitFile | Message::CancelFile
))
|| (self.delete_pending
&& !matches!(message, Message::ConfirmDelete | Message::CancelDelete))
&& !matches!(message, Message::ConfirmDelete(_) | Message::CancelDelete))
|| (self.pending.is_some()
&& self.file_prompt.is_none()
&& !matches!(
@@ -1695,6 +1547,7 @@ impl App {
}
fn handle(&mut self, message: Message) -> Task<Message> {
match message {
Message::WorkDrag(event) => return self.allocation_event(event),
Message::BehaviorControl(intent) => return self.behavior_control(intent),
Message::Architecture(event) => return self.architecture_event(event),
Message::Home(event) => return self.home_event(event),
@@ -2148,8 +2001,6 @@ impl App {
return self.update(Message::Add(child));
}
Message::Escape => {
let restore_source_focus = self.source_navigation_available()
&& (self.source_navigation.open || self.source_symbols.open);
if self.behavior.source_back() {
self.status =
"Returned to the unchanged parent form; no source was created.".into();
@@ -2166,12 +2017,6 @@ impl App {
self.status = "Drawing cancelled · Select / move is active".into();
}
self.source_navigation.open = false;
self.source_symbols.open = false;
self.source_symbols.results = None;
self.source_symbols.notice = None;
if restore_source_focus {
self.restore_source_editor_focus();
}
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
self.selected_bend = None;
}
@@ -2942,19 +2787,25 @@ impl App {
}
}
}
Message::DiagramRemove(intent) => self.remove_from_diagram(intent),
Message::DiagramTraverse(back) => {
return if back {
iced::widget::operation::focus_previous()
} else {
iced::widget::operation::focus_next()
};
}
Message::Delete => {
if self.selected != self.project().id && self.apply() {
self.delete_pending = true;
self.begin_model_delete(None);
}
}
Message::ConfirmDelete => {
if !self.delete_pending || self.behavior.has_pending() {
return Task::none();
}
Message::ConfirmDelete(token) => self.confirm_model_delete(token),
Message::CancelDelete => {
self.delete_pending = false;
self.execute(Command::Delete(self.selected));
self.delete_target = None;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
Message::CancelDelete => self.delete_pending = false,
Message::Undo | Message::Redo => {
let redo = matches!(message, Message::Redo);
if self.apply() {
@@ -3223,9 +3074,6 @@ impl App {
if self.path.is_none()
|| self.path.as_ref() == Some(&receipt.target)
{
if self.path.as_ref() != Some(&receipt.target) {
self.source_workspace.reset_navigation_session();
}
self.path = Some(receipt.target);
self.document.bind_repair_baseline(disk.reachable_bundle());
self.disk_project = Some(disk);
@@ -3294,28 +3142,13 @@ impl App {
}
}
Message::SourceRelated(location) => self.jump_to_source(location),
Message::SourceViewport(ticket) => return self.source_viewport(ticket),
Message::SourceFindClose(..) => return Task::none(), // update checks and unwraps it
Message::SourceSymbols(_, event) => return self.source_symbol_event(event),
Message::SourceSymbolsReady(completion) => {
return self.source_symbols_ready(completion);
}
Message::DiagramUsage(event) => return self.diagram_usage_event(event),
Message::DiagramUsagesReady(completion) => {
return self.diagram_usages_ready(completion);
}
Message::DiagramRevealViewport(context, epoch, size) => {
if self
.pending_diagram_reveal
.as_ref()
.is_some_and(|(c, _, e)| *c == context && *e == epoch)
&& self
.diagram_reveal_viewport(&Message::DiagramRevealViewport(
context, epoch, size,
))
.is_some()
{
return self.handle(Message::CanvasResized(size));
Message::SourceViewport => {
if let Some(cursor) = self.source_jump.take() {
self.source_editor.move_to(cursor);
if self.source_select_line && cursor.selection.is_none() {
self.source_editor.perform(text_editor::Action::SelectLine);
}
return iced::widget::operation::focus("source-editor");
}
}
Message::ApplySource => {
@@ -3362,7 +3195,6 @@ impl App {
return Task::none();
}
self.page = Page::Text;
self.source_find_instance = Id::new_v4();
self.source_navigation.open = true;
self.source_navigation.refresh(&self.source_editor.text());
return iced::widget::operation::focus(if go_to_line {
@@ -3371,22 +3203,13 @@ impl App {
"source-find"
});
}
Event::Close => {
let was_open = self.source_navigation.open;
self.source_navigation.open = false;
if was_open {
self.restore_source_editor_focus();
}
}
Event::Close => self.source_navigation.open = false,
Event::Query(query) => {
self.source_navigation.query = query;
self.source_navigation.refresh(&self.source_editor.text());
}
Event::Next(backwards) if self.page == Page::Text => {
self.source_jump = self.source_navigation.next(backwards);
if let Some(cursor) = self.source_jump {
self.queue_source_reveal(cursor, false);
}
if self.source_jump.is_none() {
self.status = "No matching source text.".into();
}
@@ -3397,7 +3220,8 @@ impl App {
.destination(self.source_editor.line_count())
{
Ok(cursor) => {
self.queue_source_reveal(cursor, true);
self.source_jump = Some(cursor);
self.source_select_line = true;
}
Err(error) => self.status = error,
},
@@ -3480,9 +3304,6 @@ impl App {
}
self.sync_source();
}
if self.path.as_ref() != Some(&receipt.path) {
self.source_workspace.reset_navigation_session();
}
self.disk_project = Some(disk);
self.path = Some(receipt.path);
self.hosted.session = None;
@@ -3694,52 +3515,6 @@ impl App {
id,
));
}
// Refining a leaf moves its explicit responsibilities to the new leaf.
// Later children inherit only the existing unambiguous performer summary.
if self.create_kind.is_work()
&& let Some(owner) = parent
&& self
.project()
.elements
.get(&owner)
.is_some_and(|e| e.layer() == self.layer && e.kind() == self.create_kind)
{
let performer = oa_core::validation::allocation_summary(self.project(), owner);
let leaf = !self
.project()
.children(owner)
.any(|e| e.kind() == self.create_kind);
let responsibilities: Vec<_> = self
.project()
.relations
.values()
.filter(|r| {
r.target() == owner
&& matches!(
r.kind(),
RelationKind::Allocation | RelationKind::RoleAssignment
)
})
.collect();
if leaf && !responsibilities.is_empty() {
for original in responsibilities {
let mut responsibility = original.clone();
match &mut responsibility.body {
RelationBody::Allocation { target, .. }
| RelationBody::RoleAssignment { target, .. } => *target = id,
_ => unreachable!(),
}
commands.push(Command::EditRelation(original.id, responsibility));
}
} else if let Some(performer) = performer {
commands.push(Command::Connect(
RelationKind::Allocation,
"Performs".into(),
performer,
id,
));
}
}
if self.create_kind == Kind::Occurrence
&& let Some(owner) = parent.and_then(|id| self.project().elements.get(&id))
&& let Some(steps) = owner.steps()
@@ -3757,13 +3532,19 @@ impl App {
.get(&diagram)
.is_none_or(|d| d.projection.includes(self.create_kind))
{
let mut p = match execute_batch(self.project(), &commands) {
Ok(candidate) => candidate,
Err(error) => {
self.status = error.to_string();
return;
let mut p = self.project().clone();
for command in &commands {
if let Command::CreateDiagram(d) = command {
p.diagrams.insert(d.id, d.clone());
}
};
}
p.elements.insert(
id,
match &commands[0] {
Command::CreateElement(e) => e.clone(),
_ => unreachable!(),
},
);
let owner = if allocated {
Some(self.selected)
} else {
@@ -4083,7 +3864,7 @@ impl App {
self.path = Some(path);
self.document.bind_repair_baseline(disk.reachable_bundle());
self.source_workspace = Workspace::new(&disk.bundle, false);
self.source_workspace.set_reachable(disk.reachable.clone());
self.source_workspace.reachable = disk.reachable.clone();
self.show_source_file(false);
self.source_diagnostics = error.diagnostics().to_vec();
self.source_version += 1;
@@ -4135,13 +3916,11 @@ impl App {
let column = prefix
.rfind('\n')
.map_or(offset, |start| offset - start - 1);
self.queue_source_reveal(
text_editor::Cursor {
position: text_editor::Position { line, column },
selection: None,
},
true,
);
self.source_jump = Some(text_editor::Cursor {
position: text_editor::Position { line, column },
selection: None,
});
self.source_select_line = true;
}
fn create_source_file(&mut self) -> Result<(), String> {
@@ -0,0 +1,601 @@
//! Allocation work-body input admission. Gesture authority lives here, while
//! the canvas retains ordered native pointer positions and frozen hit geometry.
use super::{App, Message, Page};
use crate::{allocation_drag as plan, route_edit::Context};
use iced::{Point, Rectangle, Task, Vector};
use oa_core::{projection::ProjectedView, routing::RoutedView, *};
use std::{collections::BTreeMap, sync::Arc};
pub const FINISH_EDIT: &str = "Finish or cancel the current edit before selecting or moving work.";
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stamp {
pub context: Context,
pub epoch: u64,
pub snapshot: usize,
pub bounds: Rectangle,
pub pan: Vector,
pub zoom: f32,
}
impl Stamp {
pub fn world(self, screen: Point) -> Point {
Point::new(
(screen.x - self.bounds.x - self.pan.x) / self.zoom,
(screen.y - self.bounds.y - self.pan.y) / self.zoom,
)
}
pub fn viewport(self) -> plan::Rect {
let p = self.world(Point::new(self.bounds.x, self.bounds.y));
plan::Rect {
position: Position { x: p.x, y: p.y },
size: Size {
width: self.bounds.width / self.zoom,
height: self.bounds.height / self.zoom,
},
}
}
}
#[derive(Debug, Clone)]
pub struct Target {
pub element: Id,
pub placement: Id,
pub region: Rectangle,
pub label: plan::Rect,
pub name: String,
pub ancestors: Vec<Id>,
}
#[derive(Debug, Clone)]
pub struct Frozen {
pub targets: Vec<Target>,
cards: Vec<Rectangle>,
controls: Vec<Rectangle>,
edges: Vec<(Point, Point)>,
radius: f32,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Hit {
Destination(plan::Destination, Option<usize>),
OutsideViewport,
Occluded,
Ambiguous(Vec<usize>),
}
pub fn contains(r: Rectangle, p: Point) -> bool {
p.x >= r.x && p.y >= r.y && p.x < r.x + r.width && p.y < r.y + r.height
}
impl Frozen {
pub fn capture(
project: &Project,
scope: &plan::Scope,
view: &ProjectedView,
routed: &RoutedView,
zoom: f32,
) -> Self {
let mut targets = Vec::new();
let mut cards = Vec::new();
for n in &view.nodes {
if scope.placements.contains_key(&n.id) {
continue;
}
let region = Rectangle::new(
Point::new(n.position.x, n.position.y),
iced::Size::new(n.size.width, n.size.height),
);
let Some(e) = project.elements.get(&n.element) else {
cards.push(region);
continue;
};
if e.kind().is_performer() && e.layer() == scope.diagram.layer {
let mut ancestors = Vec::new();
let mut parent = e.parent;
while let Some(id) = parent {
if ancestors.contains(&id) {
break;
}
ancestors.push(id);
parent = project.elements.get(&id).and_then(|e| e.parent);
}
// This is also the exact frozen label painted above the ghost.
let name = crate::views::short(
project.named(e.id),
(((region.width - 28.).max(10.) / 10.) as usize).min(34),
);
let label = plan::Rect {
position: Position {
x: region.x + 10.,
y: region.y + 31.,
},
size: Size {
width: (name.chars().count() as f32 * 10. + 8.)
.min((region.width - 20.).max(1.)),
height: 22.,
},
};
let collapsed = scope.diagram.nodes[&n.id].collapsed;
targets.push(Target {
element: e.id,
placement: n.id,
region: if collapsed {
Rectangle {
height: region.height.min(62.),
..region
}
} else {
region
},
label,
name,
ancestors,
});
} else {
cards.push(region);
}
}
let radius = (10. / zoom).max(10.);
let mut controls: Vec<_> = view
.ports
.iter()
.filter(|port| !scope.placements.contains_key(&port.owner))
.map(|port| {
Rectangle::new(
Point::new(port.position.x - radius, port.position.y - radius),
iced::Size::new(radius * 2., radius * 2.),
)
})
.collect();
let mut edges = Vec::new();
for edge in routed.edges.values() {
if let Some(relation) = project.relations.get(&edge.id) {
for end in routing::association_end_geometry(relation, edge) {
if !end.label.text.is_empty() {
controls.push(Rectangle::new(
Point::new(end.label.bounds.position.x, end.label.bounds.position.y),
iced::Size::new(
end.label.bounds.size.width,
end.label.bounds.size.height,
),
));
}
}
}
if !edge.label.text.is_empty() {
controls.push(Rectangle::new(
Point::new(edge.label.bounds.position.x, edge.label.bounds.position.y),
iced::Size::new(edge.label.bounds.size.width, edge.label.bounds.size.height),
));
}
for pin in &edge.pins {
controls.push(Rectangle::new(
Point::new(pin.x - 8. / zoom, pin.y - 8. / zoom),
iced::Size::new(16. / zoom, 16. / zoom),
));
}
for points in edge.points.windows(2) {
edges.push((
Point::new(points[0].x, points[0].y),
Point::new(points[1].x, points[1].y),
));
}
}
Self {
targets,
cards,
controls,
edges,
radius: 6. / zoom,
}
}
pub fn resolve(&self, stamp: Stamp, screen: Option<Point>, arrange: bool) -> Hit {
let Some(screen) = screen.filter(|p| contains(stamp.bounds, *p)) else {
return Hit::OutsideViewport;
};
let p = stamp.world(screen);
// Drag status lives in the toolbar, outside this actual canvas viewport.
if self
.controls
.iter()
.chain(&self.cards)
.any(|r| contains(*r, p))
|| self.edges.iter().any(|(a, b)| {
let d = *b - *a;
let length = d.x * d.x + d.y * d.y;
let t = if length == 0. {
0.
} else {
(((p.x - a.x) * d.x + (p.y - a.y) * d.y) / length).clamp(0., 1.)
};
p.distance(*a + d * t) <= self.radius
})
{
return Hit::Occluded;
}
if arrange {
return Hit::Destination(plan::Destination::LayoutOnly, None);
}
let hits: Vec<_> = self
.targets
.iter()
.enumerate()
.filter(|(_, t)| contains(t.region, p))
.map(|(i, _)| i)
.collect();
for (i, a) in hits.iter().enumerate() {
for b in &hits[i + 1..] {
let a = &self.targets[*a];
let b = &self.targets[*b];
if !a.ancestors.contains(&b.element) && !b.ancestors.contains(&a.element) {
return Hit::Ambiguous(hits);
}
}
}
match hits
.into_iter()
.max_by_key(|i| self.targets[*i].ancestors.len())
{
Some(i) => Hit::Destination(
plan::Destination::Performer(self.targets[i].element),
Some(i),
),
None => Hit::Destination(plan::Destination::OutsidePerformers, None),
}
}
}
#[derive(Debug, Clone)]
pub struct Press {
pub stamp: Stamp,
pub token: Id,
pub start: Point,
pub scope: plan::Scope,
pub frozen: Frozen,
pub arrange: bool,
}
#[derive(Debug, Clone)]
pub enum Event {
Press(Arc<Press>),
Preview(Stamp, Id, Option<Point>),
Release(Stamp, Id, Option<Point>),
Refused(u64, String),
Cancel(Id),
ArrangeNext,
Unfocused,
KeyboardBoundary,
}
pub struct Preview {
pub token: Id,
pub semantic: Arc<plan::SemanticPlan>,
pub placement: plan::PlacementPlan,
pub routed: Arc<RoutedView>,
}
struct Active {
press: Arc<Press>,
ids: BTreeMap<Id, Id>,
cache: Vec<(
plan::Destination,
Result<Arc<plan::SemanticPlan>, plan::Refusal>,
)>,
}
pub struct Feedback {
pub press: Arc<Press>,
pub targets: Vec<usize>,
pub text: String,
pub refused: bool,
}
#[derive(Default)]
pub struct State {
pub epoch: u64,
pub arrange_next: bool,
active: Option<Active>,
pub preview: Option<Arc<Preview>>,
pub feedback: Option<Feedback>,
}
#[derive(Clone, Copy)]
pub struct Capability<'a> {
pub state: &'a State,
pub clean: bool,
pub snapshot: usize,
}
impl State {
fn retire(&mut self) {
self.epoch = self.epoch.wrapping_add(1);
self.active = None;
self.preview = None;
self.feedback = None;
self.arrange_next = false;
}
}
pub fn refusal(r: &plan::Refusal) -> String {
match r {
plan::Refusal::Ineligible(s) | plan::Refusal::InvalidCandidate(s) | plan::Refusal::LayoutRequired(s) => s.clone(),
plan::Refusal::StaleScope => "The view changed. Start this drag again.".into(),
plan::Refusal::MixedLayoutRequired => "This work has a distributed or mixed assignment. Drag a specific leaf; arranging this group needs a layout step.".into(),
plan::Refusal::RoleExitRequired { message, .. } => message.clone(),
plan::Refusal::MissingAllocationId(_) => "Assignment identity expired. Start this drag again.".into(),
plan::Refusal::CollateralChangeRequired(records) => format!(
"Assignment needs dependent edits to {}. Resolve these before dragging again.",
records.iter().map(|r| r.name.as_str()).collect::<Vec<_>>().join(", ")
),
}
}
impl App {
pub fn allocation_drag_clean(&self) -> bool {
self.allocation_input_owner()
&& !self.draft_dirty()
&& !self.source_dirty()
&& !self.behavior.has_pending()
}
pub(crate) fn allocation_input_owner(&self) -> bool {
self.page == Page::Diagram
&& self
.active_diagram
.and_then(|id| self.project().diagrams.get(&id))
.is_some_and(|d| d.projection == ProjectionKind::Allocation)
&& self.architecture.is_none()
&& self.connection.is_none()
&& self.model_menu.is_none()
&& !self.reference_input_active()
&& !self.busy
&& !self.hosted.visible
&& self.workflow.is_none()
&& self.pending.is_none()
&& self.file_prompt.is_none()
&& !self.delete_pending
}
pub fn allocation_capability(&self) -> Capability<'_> {
Capability {
state: &self.allocation_drag,
clean: self.allocation_drag_clean(),
snapshot: Arc::as_ptr(&self.document.snapshot()) as usize,
}
}
fn allocation_stamp_valid(&self, stamp: Stamp) -> bool {
self.allocation_drag_clean()
&& self.route_context() == Some(stamp.context)
&& self.allocation_drag.epoch == stamp.epoch
&& Arc::as_ptr(&self.document.snapshot()) as usize == stamp.snapshot
&& self.pan == stamp.pan
&& self.zoom == stamp.zoom
&& self.canvas_size.is_none_or(|s| s == stamp.bounds.size())
&& stamp.bounds.width > 0.
&& stamp.bounds.height > 0.
}
/// Called before general input dispatch. Even equal-valued actions (Fit,
/// Undo/Redo, tool/modal round trips) retire old render-time capabilities.
pub(super) fn allocation_before(&mut self, message: &Message) {
if !matches!(
message,
Message::WorkDrag(_)
| Message::CheckpointTick
| Message::CheckpointWritten(..)
| Message::Lint(_)
| Message::Linted(..)
| Message::CanvasResized(_)
| Message::WindowResized(_)
| Message::SourceViewport
) {
self.allocation_drag.retire();
}
}
pub(super) fn allocation_boundary(&self) -> impl PartialEq + use<> {
(
self.route_context(),
self.pan,
self.zoom,
self.canvas_size,
self.window_size,
self.allocation_drag_clean(),
Arc::as_ptr(&self.document.snapshot()) as usize,
)
}
pub(super) fn allocation_retire(&mut self) {
self.allocation_drag.retire();
}
fn select_work_clean(&mut self, press: &Press) -> bool {
if !self.allocation_stamp_valid(press.stamp) {
return false;
}
self.selected = press.scope.work;
self.selected_node = Some(press.scope.placement);
self.selected_bend = None;
self.refresh_draft();
true
}
pub(super) fn allocation_event(&mut self, event: Event) -> Task<Message> {
match event {
Event::ArrangeNext => {
self.allocation_drag.retire();
if self.allocation_drag_clean() {
self.allocation_drag.arrange_next = true;
self.status = "Arrange next drag armed · moves work only · Esc cancels".into();
} else {
self.status = FINISH_EDIT.into();
}
}
Event::Unfocused => self.allocation_drag.retire(),
Event::KeyboardBoundary => {
if self.allocation_drag.active.is_some() {
self.allocation_drag.retire();
}
}
Event::Cancel(token) => {
if self
.allocation_drag
.active
.as_ref()
.is_some_and(|a| a.press.token == token)
{
self.allocation_drag.retire();
self.status = "Work drag canceled".into();
}
}
Event::Refused(epoch, text) => {
if epoch == self.allocation_drag.epoch {
self.allocation_drag.retire();
self.status = text;
}
}
Event::Press(press) => {
if self.allocation_drag.active.is_some() {
return Task::none();
}
if !self.allocation_stamp_valid(press.stamp)
|| press.arrange != self.allocation_drag.arrange_next
{
self.status = if self.allocation_drag_clean() {
"The view changed. Start this drag again.".into()
} else {
FINISH_EDIT.into()
};
return Task::none();
}
let checked = plan::capture(
self.project(),
press.scope.diagram.id,
press.scope.work,
press.scope.placement,
);
if checked.as_ref() != Ok(&press.scope) || !self.select_work_clean(&press) {
self.status = checked
.err()
.as_ref()
.map(refusal)
.unwrap_or_else(|| "The view changed. Start this drag again.".into());
self.allocation_drag.retire();
return Task::none();
}
let ids = press
.scope
.leaves
.keys()
.map(|id| (*id, Id::new_v4()))
.collect();
self.allocation_drag.arrange_next = false;
self.allocation_drag.preview = None;
self.allocation_drag.feedback = None;
self.allocation_drag.active = Some(Active {
press,
ids,
cache: Vec::new(),
});
}
Event::Preview(stamp, token, pointer) => {
self.allocation_motion(stamp, token, pointer, false)
}
Event::Release(stamp, token, pointer) => {
self.allocation_motion(stamp, token, pointer, true)
}
}
Task::none()
}
fn allocation_motion(
&mut self,
stamp: Stamp,
token: Id,
pointer: Option<Point>,
release: bool,
) {
if self
.allocation_drag
.active
.as_ref()
.is_none_or(|a| a.press.token != token)
{
return; // An old packet cannot cancel a newer gesture.
}
if !self.allocation_stamp_valid(stamp) {
self.allocation_drag.retire();
self.status = if self.allocation_drag_clean() {
"The view changed. Start this drag again.".into()
} else {
FINISH_EDIT.into()
};
return;
}
let Some(mut active) = self.allocation_drag.active.take() else {
return;
};
if active.press.token != token || active.press.stamp != stamp {
self.allocation_drag.active = Some(active);
return;
}
let press = active.press.clone();
let moved = pointer.is_some_and(|p| p.distance(press.start) > 3.);
let hit = press.frozen.resolve(stamp, pointer, press.arrange);
let mut targets = Vec::new();
let mut preview = None;
let result: Result<String, String> = match hit {
Hit::OutsideViewport => Err("Work drag canceled outside the canvas.".into()),
_ if !moved => Ok("Work selected".into()),
Hit::Occluded => Err("Aim at exposed performer space or empty canvas; this card, port, connection or control blocks the drop.".into()),
Hit::Ambiguous(indices) => {
targets = indices;
Err("Two unrelated performers overlap here. Use an exposed region.".into())
}
Hit::Destination(destination, target) => {
targets.extend(target);
let semantic = if let Some((_, result)) = active.cache.iter().find(|(d, _)| *d == destination) {
result.clone()
} else {
let result = plan::plan_semantics(self.project(), &press.scope, destination, &active.ids).map(Arc::new);
active.cache.push((destination, result.clone()));
result
};
semantic.map_err(|r| refusal(&r)).and_then(|semantic| {
if stamp.zoom * 16. < 9. {
return Err("Make room or adjust the view, then drag again. Zoom in to read the work and destination.".into());
}
let pointer = pointer.unwrap();
let delta = pointer - press.start;
let original = press.scope.placements[&press.scope.placement].position;
let requested = Position { x: original.x + delta.x / stamp.zoom, y: original.y + delta.y / stamp.zoom };
let presentation = plan::PresentationContext {
viewport: stamp.viewport(), zoom: stamp.zoom,
target: target.map(|i| {
let t = &press.frozen.targets[i];
plan::TargetPresentation { placement: t.placement, label: t.label }
}),
};
let placement = plan::place(&semantic, requested, presentation).map_err(|r| refusal(&r))?;
let label = if semantic.warnings.is_empty() { semantic.label.clone() } else {
format!("{} · {} model warning(s) retained", semantic.label, semantic.warnings.len())
};
if release {
let command = plan::finish(&semantic, self.project(), &placement).map_err(|r| refusal(&r))?;
if let Some(command) = command {
// Bypass applying selectors and unrelated repair helpers. The
// planner's exact Batch enters the authoritative source pipeline.
self.document.execute(command).map_err(|e| format!("{} · retry this drag after correcting the source issue", e))?;
self.sync();
self.selected = press.scope.work;
self.selected_node = Some(press.scope.placement);
self.refresh_draft();
}
} else {
let routed = Arc::new(routing::route_diagram(semantic.project(), &placement.diagram, &placement.view));
preview = Some(Arc::new(Preview { token, semantic, placement, routed }));
}
Ok(label)
})
}
};
let refused = result.is_err();
let text = result.unwrap_or_else(|text| text);
self.status = text.clone();
if release {
self.allocation_drag.retire();
} else {
self.allocation_drag.active = Some(active);
self.allocation_drag.preview = preview;
self.allocation_drag.feedback = Some(Feedback {
press,
targets,
text,
refused,
});
}
}
}
#[cfg(test)]
#[path = "allocation_drag_tests.rs"]
mod tests;
@@ -0,0 +1,290 @@
//! Actual App root, retained Iced tree, property widgets and production renderer.
//! Unlike packet-only tests, these prove the next key still reaches the field.
use super::*;
use crate::behavior::canvas_workspace::tests::{Mounted, key};
use iced::{Event as Input, keyboard};
fn character(text: &str, modifiers: keyboard::Modifiers) -> Input {
Input::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Character(text.into()),
modified_key: keyboard::Key::Character(text.into()),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::KeyA),
location: keyboard::Location::Standard,
modifiers,
text: Some(text.into()),
repeat: false,
})
}
async fn mount() -> (Fixture, Mounted) {
let mut f = fixture(Layer::Oa);
f.app.window_size = iced::Size::new(2000., 1400.);
let _ = f.app.update(Message::Select(f.work));
let mut mounted = Mounted::new(&mut f.app).await;
// First sensor measurement intentionally Fits; now use a fixed known camera.
f.app.zoom = 1.;
f.app.pan = Vector::ZERO;
f.app.fit_to_view = false;
mounted.settle(&mut f.app).await;
(f, mounted)
}
fn canvas_bounds(mounted: &mut Mounted, app: &App) -> Rectangle {
mounted
.geometry(app)
.bounds(crate::allocation_input::CANVAS_ID)
}
fn at(mounted: &mut Mounted, f: &Fixture, world: Position) -> Point {
let bounds = canvas_bounds(mounted, &f.app);
Point::new(
bounds.x + world.x * f.app.zoom + f.app.pan.x,
bounds.y + world.y * f.app.zoom + f.app.pan.y,
)
}
fn name_field(mounted: &mut Mounted, app: &App) -> Rectangle {
mounted
.geometry(app)
.text_inputs
.into_iter()
.filter(|b| b.x > app.window_size.width - 320.)
.min_by(|a, b| a.y.total_cmp(&b.y))
.expect("actual inspector Name TextInput")
}
fn description_field(mounted: &mut Mounted, app: &App) -> Rectangle {
mounted
.geometry(app)
.focused
.into_iter()
.map(|(_, bounds, _)| bounds)
.filter(|b| b.x > app.window_size.width - 320. && b.height >= 90.)
.min_by(|a, b| a.y.total_cmp(&b.y))
.expect("actual inspector Description TextEditor")
}
fn is_focused(mounted: &mut Mounted, app: &App, field: Rectangle) -> bool {
mounted
.geometry(app)
.focused
.iter()
.any(|(_, bounds, focused)| *bounds == field && *focused)
}
async fn type_key(mounted: &mut Mounted, app: &mut App, text: &str) -> Vec<Message> {
mounted
.batch(
app,
&[character(text, keyboard::Modifiers::empty())],
mouse::Cursor::Unavailable,
)
.await
}
async fn refused_click_keeps_field(mounted: &mut Mounted, f: &mut Fixture, field: Rectangle) {
let before = f.app.document.bundle().clone();
let selected = (f.app.selected, f.app.selected_node);
let point = at(mounted, f, xy(140., 535.));
let messages = mounted.click(&mut f.app, point).await;
assert!(
messages
.iter()
.any(|m| matches!(m, Message::WorkDrag(Event::Refused(..))))
);
assert!(!messages.iter().any(|m| matches!(
m,
Message::Select(_) | Message::SelectNode(_) | Message::MoveNode(..)
)));
assert_eq!(f.app.document.bundle(), &before);
assert_eq!((f.app.selected, f.app.selected_node), selected);
assert!(
is_focused(mounted, &f.app, field),
"refused press must not reach the outside-press unfocus handler"
);
}
#[tokio::test]
async fn actual_app_tree_dirty_name_retains_focus_and_middle_caret_for_next_key() {
let (mut f, mut mounted) = mount().await;
let field = name_field(&mut mounted, &f.app);
mounted.click(&mut f.app, field.center()).await;
mounted
.batch(
&mut f.app,
&[key(keyboard::key::Named::Home)],
mouse::Cursor::Unavailable,
)
.await;
type_key(&mut mounted, &mut f.app, "X").await;
mounted
.batch(
&mut f.app,
&[key(keyboard::key::Named::ArrowLeft)],
mouse::Cursor::Unavailable,
)
.await;
assert_eq!(f.app.draft.as_ref().unwrap().inputs["/name"].raw, "XWork");
refused_click_keeps_field(&mut mounted, &mut f, field).await;
let messages = type_key(&mut mounted, &mut f.app, "Y").await;
assert!(
messages
.iter()
.any(|m| matches!(m, Message::Field(path, _) if path == "/name"))
);
assert_eq!(f.app.draft.as_ref().unwrap().inputs["/name"].raw, "YXWork");
assert!(!f.app.document.can_undo());
}
#[tokio::test]
async fn actual_app_tree_dirty_description_retains_focus_and_middle_caret_for_next_key() {
let (mut f, mut mounted) = mount().await;
let field = description_field(&mut mounted, &f.app);
mounted
.click(&mut f.app, Point::new(field.x + 16., field.y + 16.))
.await;
type_key(&mut mounted, &mut f.app, "A").await;
type_key(&mut mounted, &mut f.app, "B").await;
mounted
.batch(
&mut f.app,
&[key(keyboard::key::Named::ArrowLeft)],
mouse::Cursor::Unavailable,
)
.await;
assert_eq!(
f.app.draft.as_ref().unwrap().inputs["/description"].raw,
"AB"
);
refused_click_keeps_field(&mut mounted, &mut f, field).await;
let messages = type_key(&mut mounted, &mut f.app, "X").await;
assert!(
messages
.iter()
.any(|m| matches!(m, Message::FieldText(path, _) if path == "/description"))
);
assert_eq!(
f.app.draft.as_ref().unwrap().inputs["/description"].raw,
"AXB"
);
assert!(!f.app.document.can_undo());
}
#[tokio::test]
async fn actual_keyboard_arrange_shortcut_consumes_once_escape_cancels_and_dirty_owner_refuses() {
let (mut f, mut mounted) = mount().await;
let shortcut = character("a", keyboard::Modifiers::ALT);
let messages = mounted
.batch(&mut f.app, &[shortcut.clone()], mouse::Cursor::Unavailable)
.await;
assert!(
messages
.iter()
.any(|m| matches!(m, Message::WorkDrag(Event::ArrangeNext)))
);
assert!(f.app.allocation_drag.arrange_next);
mounted
.batch(
&mut f.app,
&[key(keyboard::key::Named::Escape)],
mouse::Cursor::Unavailable,
)
.await;
assert!(!f.app.allocation_drag.arrange_next);
mounted
.batch(&mut f.app, &[shortcut.clone()], mouse::Cursor::Unavailable)
.await;
let from = at(&mut mounted, &f, xy(140., 535.));
let to = from + Vector::new(30., 0.);
let messages = mounted
.batch(
&mut f.app,
&[
Input::Mouse(mouse::Event::CursorMoved { position: from }),
Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Input::Mouse(mouse::Event::CursorMoved { position: to }),
Input::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
],
mouse::Cursor::Available(to),
)
.await;
assert!(
messages
.iter()
.any(|m| matches!(m, Message::WorkDrag(Event::Press(p)) if p.arrange))
);
assert!(!f.app.allocation_drag.arrange_next);
assert_eq!(f.app.document.revision(), 1, "{}", f.app.status);
assert!(f.app.project().relations.is_empty());
let field = name_field(&mut mounted, &f.app);
mounted.click(&mut f.app, field.center()).await;
type_key(&mut mounted, &mut f.app, "X").await;
let raw = f.app.draft.as_ref().unwrap().inputs["/name"].raw.clone();
let before = f.app.document.bundle().clone();
mounted
.batch(&mut f.app, &[shortcut], mouse::Cursor::Unavailable)
.await;
assert!(!f.app.allocation_drag.arrange_next);
assert_eq!(f.app.status, FINISH_EDIT);
assert!(is_focused(&mut mounted, &f.app, field));
assert_eq!(f.app.draft.as_ref().unwrap().inputs["/name"].raw, raw);
assert_eq!(f.app.document.bundle(), &before);
}
fn canvas_pixels(pixels: &[u8], width: usize, canvas: Rectangle) -> Vec<u8> {
let x = canvas.x.ceil() as usize;
let y = canvas.y.ceil() as usize;
let right = (canvas.x + canvas.width).floor() as usize;
let bottom = (canvas.y + canvas.height).floor() as usize;
(y..bottom)
.flat_map(|row| {
pixels[(row * width + x) * 4..(row * width + right) * 4]
.iter()
.copied()
})
.collect()
}
#[tokio::test]
async fn actual_rendered_canvas_pixels_do_not_change_when_toolbar_feedback_text_changes() {
let (mut f, mut mounted) = mount().await;
let mut project = f.app.project().clone();
let target = project
.diagrams
.get_mut(&f.diagram)
.unwrap()
.nodes
.values_mut()
.find(|n| n.element == f.a)
.unwrap();
target.position.y = -41.;
target.size.height = 300.;
replace(&mut f, project);
f.app.zoom = 0.75;
f.app.pan = Vector::new(15., 15.);
let from = at(&mut mounted, &f, xy(140., 535.));
let to = at(&mut mounted, &f, xy(200., 80.));
mounted
.batch(
&mut f.app,
&[
Input::Mouse(mouse::Event::CursorMoved { position: from }),
Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Input::Mouse(mouse::Event::CursorMoved { position: to }),
],
mouse::Cursor::Available(to),
)
.await;
let feedback = f
.app
.allocation_drag
.feedback
.as_ref()
.expect("active frozen destination");
assert!(!feedback.refused, "{}", feedback.text);
let target = &feedback.press.frozen.targets[feedback.targets[0]];
assert!(target.label.position.y * f.app.zoom + f.app.pan.y < 14.);
let canvas = canvas_bounds(&mut mounted, &f.app);
let first = mounted.pixels(&f.app);
f.app.allocation_drag.feedback.as_mut().unwrap().text =
"Very different drag status, retained outside the readable canvas. ".repeat(10);
let second = mounted.pixels(&f.app);
assert_ne!(first, second, "the actual toolbar status changes");
assert_eq!(
canvas_pixels(&first, f.app.window_size.width as usize, canvas),
canvas_pixels(&second, f.app.window_size.width as usize, canvas),
"status must not obscure any candidate header or frozen target label"
);
}
File diff suppressed because it is too large Load Diff
@@ -70,7 +70,6 @@ fn architecture_f2_routes_selected_node_to_inline_rename_and_exact_undo() {
view_index: None,
diagram: app.active_diagram.unwrap(),
selected: element,
navigation_focus: None,
zoom: app.zoom,
pan: app.pan,
context: app.route_context().unwrap(),
@@ -78,6 +77,7 @@ fn architecture_f2_routes_selected_node_to_inline_rename_and_exact_undo() {
editable: true,
placing: false,
connection: None,
allocation: None,
};
let mut state = crate::diagram::State::default();
let key = CanvasEvent::Keyboard(keyboard::Event::KeyPressed {
@@ -225,7 +225,6 @@ fn architecture_canvas_left_click_uses_world_coordinate_once_at_zoom_and_pan() {
view_index: None,
diagram: app.active_diagram.unwrap(),
selected: app.selected,
navigation_focus: None,
zoom: app.zoom,
pan: app.pan,
context: app.route_context().unwrap(),
@@ -233,6 +232,7 @@ fn architecture_canvas_left_click_uses_world_coordinate_once_at_zoom_and_pan() {
editable: true,
placing: true,
connection: None,
allocation: None,
};
let mut state = crate::diagram::State::default();
let action = canvas
@@ -300,7 +300,6 @@ fn architecture_f2_rename_preserves_identity_placement_and_atomic_history() {
view_index: None,
diagram: app.active_diagram.unwrap(),
selected: element,
navigation_focus: None,
zoom: app.zoom,
pan: app.pan,
context: app.route_context().unwrap(),
@@ -308,6 +307,7 @@ fn architecture_f2_rename_preserves_identity_placement_and_atomic_history() {
editable: true,
placing: false,
connection: None,
allocation: None,
};
let bounds = iced::Rectangle::with_size(iced::Size::new(800., 600.));
let cursor = mouse::Cursor::Available(iced::Point::new(500., 400.));
@@ -291,7 +291,7 @@ fn pending_behavior_blocks_navigation_property_edits_and_model_history() {
Message::BrowseGroup(crate::explorer::Group::Work),
Message::Field("/name".into(), "Overwrite properties".into()),
Message::Command(Command::Rename(fixture.source, "Overwrite model".into())),
Message::ConfirmDelete,
Message::ConfirmDelete(0),
Message::Undo,
Message::Redo,
Message::ShortcutUndo(false),
@@ -0,0 +1,152 @@
//! Captured diagram removal and model-confirmation lifetimes.
use super::*;
use crate::{model_menu, route_edit::Context};
#[derive(Debug, Clone)]
pub struct Intent {
pub context: Context,
pub object: Id,
pub placement: Option<Id>,
pub model: bool,
}
pub struct Confirmation {
pub snapshot: model_menu::Opened,
pub selection: Id,
pub placement: Option<Id>,
}
pub fn enabled(app: &App) -> bool {
crate::behavior::canvas_workspace::keyboard_enabled(app)
&& !app.draft_dirty()
&& !app.source_dirty()
&& !app.behavior.has_pending()
&& app
.architecture
.as_ref()
.is_none_or(|state| !state.inline())
}
impl App {
pub(super) fn remove_from_diagram(&mut self, intent: Intent) {
if !enabled(self) || self.connection.is_some() || self.selected_bend.is_some() {
return;
}
let current = match self.page {
Page::Diagram if self.architecture.as_ref().is_none_or(|s| !s.saved.placing) => {
self.route_context()
}
Page::Behavior
if self.behavior.diagram.tool == crate::behavior::state_edit::Tool::Select =>
{
self.state_context()
}
_ => None,
};
if current != Some(intent.context) || self.selected != intent.object {
return;
}
let view = projection::project_view(self.project(), intent.context.diagram);
let placement = if self.page == Page::Behavior {
self.behavior.diagram.placement
} else {
self.selected_node
};
if intent.placement != placement || intent.object == intent.context.diagram {
return;
}
let visible = if let Some(id) = intent.placement {
self.project().diagrams[&intent.context.diagram]
.nodes
.get(&id)
.is_some_and(|node| node.element == intent.object)
&& view
.nodes
.iter()
.any(|node| node.id == id && node.element == intent.object)
} else {
view.edges.iter().any(|edge| edge.id == intent.object)
|| view.ports.iter().any(|port| port.element == intent.object)
};
if !visible {
return;
}
if !intent.model
&& let Some(placement) = intent.placement
{
if self.execute(Command::Delete(placement)) {
self.selected_node = None;
self.behavior.diagram.placement = None;
self.selected_bend = None;
self.status = "Hidden from this diagram · Model element preserved · Undo restores the placement".into();
}
} else {
self.begin_model_delete(Some(intent.context));
}
}
pub(super) fn begin_model_delete(&mut self, canvas: Option<Context>) {
if self.selected == self.project().id || self.behavior.has_pending() {
return;
}
let mut request = model_menu::Request::object(self.selected, iced::Point::ORIGIN);
request.canvas = canvas;
request.placement = if self.page == Page::Behavior {
self.behavior.diagram.placement
} else {
self.selected_node
};
// Opening a modal retires any pending canvas intent before capturing
// the confirmation; every new dialog receives its own replay token.
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
if canvas.is_some() {
request.canvas = if self.page == Page::Behavior {
self.state_context()
} else {
self.route_context()
};
}
self.menu_sequence = self.menu_sequence.wrapping_add(1);
self.delete_target =
model_menu::Opened::new(self, request, self.menu_sequence).map(|snapshot| {
Confirmation {
snapshot,
selection: self.selected,
placement: if self.page == Page::Behavior {
self.behavior.diagram.placement
} else {
self.selected_node
},
}
});
self.delete_pending = self.delete_target.is_some();
}
pub(super) fn confirm_model_delete(&mut self, token: u64) {
let Some(target) = self.delete_target.as_ref() else {
return;
};
if target.snapshot.token != token {
return;
}
let valid = self.delete_pending
&& target.snapshot.valid(self)
&& target.selection == self.selected
&& target.placement
== if self.page == Page::Behavior {
self.behavior.diagram.placement
} else {
self.selected_node
}
&& !self.behavior.has_pending()
&& !self.source_dirty()
&& !self.draft_dirty();
let id = target.snapshot.request.object;
self.delete_pending = false;
self.delete_target = None;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
if valid {
self.execute(Command::Delete(id));
}
}
}
@@ -0,0 +1,681 @@
//! Real App tree regression tests; no private canvas focus or gesture seeding.
use super::*;
use crate::behavior::canvas_workspace::tests::{Mounted, key};
use iced::advanced::widget::{Operation, operation};
use iced::{Event as Input, Point, Rectangle, Size, Vector, keyboard, mouse};
struct Fixture {
app: App,
object: Id,
node: Id,
other: Id,
diagram: Id,
copy: Id,
}
fn fixture(layer: Layer) -> Fixture {
let mut p = Project::empty();
let kind = if layer == Layer::Oa {
Kind::Entity
} else {
Kind::System
};
let object = p.add_element(kind, layer, "Target", None).unwrap();
let other = p
.add_element(
if layer == Layer::Oa {
Kind::Actor
} else {
Kind::SystemActor
},
layer,
"Other",
None,
)
.unwrap();
let diagram = p.ensure_diagram(layer);
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Overview;
let node = p.place(diagram, object, Position { x: 80., y: 80. });
p.place(diagram, other, Position { x: 500., y: 80. });
let mut second = p.diagrams[&diagram].clone();
second.id = Id::new_v4();
second.name = "Other diagram".into();
second.alias = "other_diagram".into();
second.nodes.clear();
second.routes.clear();
let copy = second.id;
p.diagrams.insert(copy, second);
p.place(copy, object, Position { x: 70., y: 70. });
let mut app = App::with_project(p);
app.page = Page::Diagram;
app.layer = layer;
app.active_diagram = Some(diagram);
app.window_size = Size::new(2000., 1400.);
Fixture {
app,
object,
node,
other,
diagram,
copy,
}
}
async fn mount(layer: Layer) -> (Fixture, Mounted) {
let mut f = fixture(layer);
let mut mounted = Mounted::new(&mut f.app).await;
f.app.zoom = 1.;
f.app.pan = Vector::ZERO;
f.app.fit_to_view = false;
mounted.settle(&mut f.app).await;
select(&mut mounted, &mut f).await;
(f, mounted)
}
async fn select(mounted: &mut Mounted, f: &mut Fixture) {
let bounds = mounted
.geometry(&f.app)
.bounds(crate::allocation_input::CANVAS_ID);
let node = projection::project_view(f.app.project(), f.diagram)
.nodes
.into_iter()
.find(|node| node.id == f.node)
.unwrap();
let point = Point::new(
bounds.x + (node.position.x + 40.) * f.app.zoom + f.app.pan.x,
bounds.y + (node.position.y + 35.) * f.app.zoom + f.app.pan.y,
);
mounted.click(&mut f.app, point).await;
assert_eq!(f.app.selected, f.object);
assert_eq!(f.app.selected_node, Some(f.node));
}
fn modified(named: keyboard::key::Named, modifiers: keyboard::Modifiers) -> Input {
let mut input = key(named);
if let Input::Keyboard(keyboard::Event::KeyPressed {
modifiers: value, ..
}) = &mut input
{
*value = modifiers;
}
input
}
async fn delete(mounted: &mut Mounted, app: &mut App, shift: bool) -> Vec<Message> {
mounted
.batch(
app,
&[modified(
keyboard::key::Named::Delete,
if shift {
keyboard::Modifiers::SHIFT
} else {
keyboard::Modifiers::empty()
},
)],
mouse::Cursor::Unavailable,
)
.await
}
fn consistent(app: &App) {
assert_eq!(
source_project::compile_bundle(app.document.bundle(), LIMITS)
.unwrap()
.decoded
.project,
*app.project()
);
assert_eq!(
source_workspace::reachable(&app.source_workspace.bundle()).unwrap(),
*app.document.bundle()
);
}
#[tokio::test]
async fn mounted_oa_sa_delete_hides_exact_placement_and_round_trips_source_and_model() {
for layer in [Layer::Oa, Layer::Sa] {
let (mut f, mut mounted) = mount(layer).await;
let before = f.app.document.snapshot();
let messages = delete(&mut mounted, &mut f.app, false).await;
assert!(
messages
.iter()
.any(|message| matches!(message, Message::DiagramRemove(_)))
);
assert!(f.app.project().contains(f.object));
assert!(
!f.app.project().diagrams[&f.diagram]
.nodes
.contains_key(&f.node)
);
assert!(
f.app.project().diagrams[&f.copy]
.nodes
.values()
.any(|node| node.element == f.object)
);
assert!(!f.app.delete_pending);
consistent(&f.app);
let after = f.app.document.snapshot();
let task = f.app.update(Message::Undo);
mounted.perform(&mut f.app, task).await;
assert_eq!(f.app.project(), &before.decoded.project);
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.document.can_undo(), "one removal, one undo unit");
let task = f.app.update(Message::Redo);
mounted.perform(&mut f.app, task).await;
assert_eq!(f.app.project(), &after.decoded.project);
assert_eq!(f.app.document.bundle(), &after.bundle);
consistent(&f.app);
}
}
#[tokio::test]
async fn mounted_shift_delete_captures_target_cancel_escape_and_confirmation_replay() {
let (mut f, mut mounted) = mount(Layer::Oa).await;
let before = f.app.document.snapshot();
delete(&mut mounted, &mut f.app, true).await;
let target = f.app.delete_target.as_ref().unwrap();
assert_eq!(target.snapshot.request.object, f.object);
let stale_token = target.snapshot.token;
let task = f.app.update(Message::CancelDelete);
mounted.perform(&mut f.app, task).await;
let task = f.app.update(Message::ConfirmDelete(stale_token));
mounted.perform(&mut f.app, task).await;
assert_eq!(f.app.document.bundle(), &before.bundle);
select(&mut mounted, &mut f).await;
delete(&mut mounted, &mut f.app, true).await;
let token = f.app.delete_target.as_ref().unwrap().snapshot.token;
let task = f.app.update(Message::ConfirmDelete(stale_token));
mounted.perform(&mut f.app, task).await;
assert!(
f.app.delete_pending,
"old dialog must not accept a new confirmation"
);
let task = f.app.update(Message::ConfirmDelete(token));
mounted.perform(&mut f.app, task).await;
assert!(!f.app.project().contains(f.object));
assert!(f.app.project().contains(f.other));
consistent(&f.app);
let task = f.app.update(Message::Undo);
mounted.perform(&mut f.app, task).await;
assert_eq!(f.app.document.bundle(), &before.bundle);
select(&mut mounted, &mut f).await;
delete(&mut mounted, &mut f.app, true).await;
let task = f.app.update(Message::Escape);
mounted.perform(&mut f.app, task).await;
assert!(!f.app.delete_pending);
assert!(f.app.delete_target.is_none());
assert_eq!(f.app.document.bundle(), &before.bundle);
}
struct FocusField(Rectangle);
impl Operation for FocusField {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation)) {
visit(self);
}
fn focusable(
&mut self,
_: Option<&iced::advanced::widget::Id>,
bounds: Rectangle,
state: &mut dyn operation::Focusable,
) {
if bounds == self.0 {
state.focus();
} else {
state.unfocus();
}
}
}
fn name_field(mounted: &mut Mounted, app: &App) -> Rectangle {
mounted
.geometry(app)
.text_inputs
.into_iter()
.filter(|bounds| bounds.x > app.window_size.width - 320.)
.min_by(|a, b| a.y.total_cmp(&b.y))
.unwrap()
}
#[tokio::test]
async fn mounted_clean_text_programmatic_focus_and_tab_remove_canvas_keyboard_ownership() {
for programmatic in [true, false] {
let (mut f, mut mounted) = mount(Layer::Oa).await;
let before = f.app.document.snapshot();
let field = name_field(&mut mounted, &f.app);
if programmatic {
mounted.operate(&f.app, &mut FocusField(field));
} else {
let messages = mounted
.batch(
&mut f.app,
&[
key(keyboard::key::Named::Tab),
key(keyboard::key::Named::Delete),
],
mouse::Cursor::Unavailable,
)
.await;
assert!(
!messages
.iter()
.any(|message| matches!(message, Message::DiagramRemove(_))),
"Tab retires canvas admission before its queued focus operation runs"
);
}
let geometry = mounted.geometry(&f.app);
assert!(
geometry
.focused
.iter()
.any(|(_, bounds, focused)| *bounds == field && *focused),
"clean Inspector receives real focus"
);
assert!(!f.app.draft_dirty());
assert!(
delete(&mut mounted, &mut f.app, true)
.await
.iter()
.all(|message| !matches!(message, Message::DiagramRemove(_)))
);
assert!(!f.app.delete_pending);
mounted
.batch(
&mut f.app,
&[key(keyboard::key::Named::Home)],
mouse::Cursor::Unavailable,
)
.await;
let messages = delete(&mut mounted, &mut f.app, false).await;
assert!(
messages
.iter()
.any(|message| matches!(message, Message::Field(path, _) if path == "/name"))
);
assert_eq!(f.app.draft.as_ref().unwrap().inputs["/name"].raw, "arget");
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(f.app.project().contains(f.node));
assert!(!f.app.delete_pending);
}
}
#[tokio::test]
async fn mounted_removal_intents_reject_stale_selection_revision_owner_and_document() {
for boundary in 0..5 {
let (mut f, mut mounted) = mount(Layer::Oa).await;
let messages = mounted.input(
&f.app,
&[key(keyboard::key::Named::Delete)],
mouse::Cursor::Unavailable,
);
let intent = messages
.into_iter()
.find(|message| matches!(message, Message::DiagramRemove(_)))
.unwrap();
match boundary {
0 => {
let _ = f.app.update(Message::Select(f.other));
}
1 => {
f.app.canvas_epoch = f.app.canvas_epoch.wrapping_add(1);
}
2 => {
f.app.active_diagram = Some(f.copy);
}
3 => {
f.app.canvas_document = Id::new_v4();
}
_ => {
let _ = f
.app
.update(Message::Command(Command::Rename(f.other, "Renamed".into())));
}
}
let before = f.app.document.snapshot();
let task = f.app.update(intent);
mounted.perform(&mut f.app, task).await;
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(f.app.project().contains(f.node));
assert!(!f.app.delete_pending);
}
}
#[tokio::test]
async fn mounted_window_modal_dirty_and_modifier_boundaries_retire_delete_focus() {
for boundary in 0..5 {
let (mut f, mut mounted) = mount(Layer::Oa).await;
let before = f.app.document.snapshot();
match boundary {
0 => {
mounted
.batch(
&mut f.app,
&[Input::Window(iced::window::Event::Unfocused)],
mouse::Cursor::Unavailable,
)
.await;
}
1 => {
let _ = f.app.update(Message::Menu(crate::model_menu::Event::Open(
crate::model_menu::Request::object(f.object, Point::ORIGIN),
)));
mounted.settle(&mut f.app).await;
let _ = f.app.update(Message::Menu(crate::model_menu::Event::Close));
}
2 => {
let _ = f.app.update(Message::Field("/name".into(), "Dirty".into()));
}
3 => {
let _ = f.app.update(Message::Delete);
}
_ => {
f.app.canvas_epoch = f.app.canvas_epoch.wrapping_add(1);
}
}
delete(&mut mounted, &mut f.app, false).await;
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(f.app.project().contains(f.node));
}
let (mut f, mut mounted) = mount(Layer::Oa).await;
let before = f.app.document.snapshot();
mounted
.batch(
&mut f.app,
&[modified(
keyboard::key::Named::Delete,
keyboard::Modifiers::CTRL,
)],
mouse::Cursor::Unavailable,
)
.await;
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(!f.app.delete_pending);
// Refusal is temporary: a fresh live canvas click owns Delete again.
select(&mut mounted, &mut f).await;
delete(&mut mounted, &mut f.app, false).await;
assert!(!f.app.project().contains(f.node));
}
#[tokio::test]
async fn mounted_bend_delete_has_priority_and_semantic_edge_delete_is_confirmed() {
let mut p = Project::empty();
let a = p.add(Kind::Activity, "Send", 0., 0.);
let b = p.add(Kind::Activity, "Receive", 650., 0.);
let edge = p.relate(RelationKind::Interaction, "Report", a, b);
let diagram = p.ensure_diagram(Layer::Oa);
let p = execute_batch(
&p,
&[Command::SetEdgeRoute {
diagram,
route: EdgeRoute {
edge,
waypoints: vec![Position { x: 400., y: -100. }],
label: None,
},
}],
)
.unwrap();
let mut app = App::with_project(p);
app.page = Page::Diagram;
app.active_diagram = Some(diagram);
app.window_size = Size::new(2000., 1400.);
let _ = app.update(Message::Select(edge));
let mut mounted = Mounted::new(&mut app).await;
app.zoom = 1.;
app.pan = Vector::new(100., 250.);
app.fit_to_view = false;
mounted.settle(&mut app).await;
let bounds = mounted
.geometry(&app)
.bounds(crate::allocation_input::CANVAS_ID);
let pin = Point::new(bounds.x + 500., bounds.y + 150.);
mounted.click(&mut app, pin).await;
assert_eq!(
app.selected_bend,
Some((edge, 0)),
"real pointer selects route pin"
);
let before = app.document.snapshot();
let messages = delete(&mut mounted, &mut app, false).await;
assert!(messages.iter().any(|message| matches!(
message,
Message::Route(crate::route_edit::Event::RemoveBend)
)));
assert!(
!messages
.iter()
.any(|message| matches!(message, Message::DiagramRemove(_)))
);
assert!(app.project().contains(edge) && app.project().contains(a) && app.project().contains(b));
assert!(
crate::route_edit::stored_route(&app.project().diagrams[&diagram], edge)
.waypoints
.is_empty()
);
assert!(!app.delete_pending);
consistent(&app);
let task = app.update(Message::Undo);
mounted.perform(&mut app, task).await;
assert_eq!(app.document.bundle(), &before.bundle);
// Select a real edge segment away from its handle, then Delete opens the
// same semantic confirmation instead of inventing an edge hide operation.
let view = projection::project_view(app.project(), diagram);
let routed = routing::route_diagram(app.project(), &app.project().diagrams[&diagram], &view);
let route = &routed.edges[&edge];
let segment = route
.points
.windows(2)
.max_by(|a, b| {
let len = |s: &[Position]| (s[1].x - s[0].x).abs() + (s[1].y - s[0].y).abs();
len(a).total_cmp(&len(b))
})
.unwrap();
let at = Point::new(
bounds.x + (segment[0].x + segment[1].x) / 2. + app.pan.x,
bounds.y + (segment[0].y + segment[1].y) / 2. + app.pan.y,
);
mounted.click(&mut app, at).await;
assert_eq!(app.selected, edge);
assert!(app.selected_bend.is_none());
delete(&mut mounted, &mut app, false).await;
assert_eq!(
app.delete_target.as_ref().unwrap().snapshot.request.object,
edge
);
assert_eq!(app.document.bundle(), &before.bundle);
}
#[tokio::test]
async fn mounted_state_delete_uses_state_placement_and_preserves_architecture_placement() {
let mut p = Project::empty();
let machine = p
.add_element(Kind::StateMachine, Layer::Sa, "Machine", None)
.unwrap();
let region = p
.add_element(Kind::Region, Layer::Sa, "Main", Some(machine))
.unwrap();
let state = p
.add_element(Kind::State, Layer::Sa, "Ready", Some(region))
.unwrap();
let architecture = p.ensure_diagram(Layer::Sa);
let architecture_node = p.place(architecture, state, Position { x: 50., y: 50. });
let plan = crate::behavior::state_edit::create_view(&p, machine).unwrap();
let diagram = plan.diagram;
let p = execute_batch(&p, &[plan.command]).unwrap();
let node = p.diagrams[&diagram]
.nodes
.values()
.find(|node| node.element == state)
.unwrap()
.id;
let mut app = App::with_project(p);
app.layer = Layer::Sa;
app.page = Page::Behavior;
app.active_diagram = Some(architecture);
app.behavior.active_owner = Some(machine);
app.behavior.diagram.diagram = Some(diagram);
app.window_size = Size::new(2000., 1400.);
let _ = app.update(Message::Select(state));
let mut mounted = Mounted::new(&mut app).await;
let bounds = mounted
.geometry(&app)
.focused
.into_iter()
.find(|(id, _, _)| {
id.as_ref() == Some(&iced::advanced::widget::Id::from("diagram-keyboard-owner"))
})
.unwrap()
.1;
let projected = projection::project_view(app.project(), diagram)
.nodes
.into_iter()
.find(|n| n.id == node)
.unwrap();
let at = Point::new(
bounds.x
+ (projected.position.x + 35.) * app.behavior.diagram.zoom
+ app.behavior.diagram.pan.x,
bounds.y
+ (projected.position.y + 35.) * app.behavior.diagram.zoom
+ app.behavior.diagram.pan.y,
);
mounted.click(&mut app, at).await;
assert_eq!(app.selected, state);
assert_eq!(app.behavior.diagram.placement, Some(node));
let before = app.document.snapshot();
let messages = delete(&mut mounted, &mut app, false).await;
assert!(messages.iter().any(|message| matches!(
message,
Message::StateDiagram(crate::behavior::state_edit::Event::Remove(_))
)));
assert!(!app.project().contains(node));
assert!(app.project().contains(architecture_node) && app.project().contains(state));
consistent(&app);
let task = app.update(Message::Undo);
mounted.perform(&mut app, task).await;
assert_eq!(app.document.bundle(), &before.bundle);
}
#[tokio::test]
async fn captured_confirmation_rejects_selection_document_revision_and_placement_changes() {
for boundary in 0..5 {
let (mut f, mut mounted) = mount(Layer::Oa).await;
delete(&mut mounted, &mut f.app, true).await;
let token = f.app.delete_target.as_ref().unwrap().snapshot.token;
// Model asynchronous adoption / retained stale UI using a changed App
// state while preserving the old confirmation payload deliberately.
match boundary {
0 => {
f.app.selected = f.other;
}
1 => {
f.app.canvas_document = Id::new_v4();
}
2 => {
f.app.canvas_epoch = f.app.canvas_epoch.wrapping_add(1);
}
3 => {
f.app.selected_node = None;
}
_ => {
assert!(
f.app
.document
.execute(Command::Rename(f.other, "New revision".into()))
.is_ok()
);
}
}
let before = f.app.document.snapshot();
let task = f.app.update(Message::ConfirmDelete(token));
mounted.perform(&mut f.app, task).await;
assert_eq!(f.app.document.bundle(), &before.bundle);
assert!(f.app.project().contains(f.object));
assert!(!f.app.delete_pending);
}
}
#[tokio::test]
async fn mounted_programmatic_canvas_entry_needs_no_mouse_focus_boolean() {
let mut f = fixture(Layer::Oa);
let _ = f.app.update(Message::Select(f.object));
let mut mounted = Mounted::new(&mut f.app).await;
let task =
iced::widget::operation::focus(iced::advanced::widget::Id::from("diagram-keyboard-owner"));
mounted.perform(&mut f.app, task).await;
let messages = delete(&mut mounted, &mut f.app, false).await;
assert!(
messages
.iter()
.any(|message| matches!(message, Message::DiagramRemove(_)))
);
assert!(!f.app.project().contains(f.node));
assert!(f.app.project().contains(f.object));
}
#[tokio::test]
async fn mounted_allocation_work_click_then_delete_without_redraw_removes_placement_once() {
for layer in [Layer::Oa, Layer::Sa] {
let mut p = Project::empty();
let performer = p
.add_element(
if layer == Layer::Oa {
Kind::Entity
} else {
Kind::System
},
layer,
"Performer",
None,
)
.unwrap();
let work = p
.add_element(
if layer == Layer::Oa {
Kind::Activity
} else {
Kind::Function
},
layer,
"Work",
None,
)
.unwrap();
let diagram = p.ensure_diagram(layer);
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Allocation;
p.place(diagram, performer, Position { x: 100., y: 100. });
let node = p.place(diagram, work, Position { x: 100., y: 500. });
let mut app = App::with_project(p);
app.page = Page::Diagram;
app.layer = layer;
app.active_diagram = Some(diagram);
app.window_size = Size::new(2000., 1400.);
let mut mounted = Mounted::new(&mut app).await;
app.zoom = 1.;
app.pan = Vector::ZERO;
app.fit_to_view = false;
mounted.settle(&mut app).await;
let bounds = mounted
.geometry(&app)
.bounds(crate::allocation_input::CANVAS_ID);
let point = Point::new(bounds.x + 140., bounds.y + 535.);
let messages = mounted.click(&mut app, point).await;
assert!(messages.iter().any(|message| matches!(
message,
Message::WorkDrag(crate::app::allocation_drag::Event::Press(_))
)));
assert_eq!(app.selected, work);
assert_eq!(app.selected_node, Some(node));
let before = app.document.snapshot();
// Deliberately do not settle/redraw between completed click and key.
let messages = delete(&mut mounted, &mut app, false).await;
assert!(
messages
.iter()
.any(|message| matches!(message, Message::DiagramRemove(_))),
"retired allocation press cannot consume first Delete"
);
assert!(!app.project().contains(node));
assert!(app.project().contains(work) && app.project().contains(performer));
consistent(&app);
let task = app.update(Message::Undo);
mounted.perform(&mut app, task).await;
assert_eq!(app.document.bundle(), &before.bundle);
assert!(!app.document.can_undo());
}
}
-145
View File
@@ -1,145 +0,0 @@
//! Complete a navigation camera after the destination reports its real viewport.
use super::*;
use crate::diagram_usage::{Context, Surface};
#[cfg(test)]
mod tests;
impl App {
pub(super) fn is_diagram_viewport(message: &Message) -> bool {
matches!(
message,
Message::CanvasResized(_)
| Message::DiagramRevealViewport(..)
| Message::TopologyCanvas(behavior::topology::CanvasEvent::Viewport(..))
| Message::ScenarioCanvas(behavior::scenario::CanvasEvent::Viewport(..))
| Message::StateDiagram(behavior::state_edit::Event::Viewport(..))
)
}
pub(crate) fn architecture_reveal_stamp(&self, diagram: Id) -> Option<(Context, u64)> {
self.pending_diagram_reveal
.as_ref()
.filter(|(_, u, _)| u.surface == Surface::Saved(diagram))
.map(|(context, _, epoch)| (*context, *epoch))
}
pub(super) fn diagram_reveal_viewport(&self, message: &Message) -> Option<Surface> {
let (context, usage, epoch) = self.pending_diagram_reveal.as_ref()?;
if context.document != self.canvas_document
|| context.revision != self.document.revision()
|| *epoch != self.canvas_epoch
{
return None;
}
let (surface, size, valid) = match message {
Message::DiagramRevealViewport(c, e, size) => (
usage.surface,
*size,
c == context
&& e == epoch
&& self.page == Page::Diagram
&& Some(usage.surface.id()) == self.active_diagram,
),
Message::TopologyCanvas(behavior::topology::CanvasEvent::Viewport(c, size)) => (
Surface::Process(c.owner),
*size,
c.document == context.document
&& c.revision == context.revision
&& c.epoch == *epoch,
),
Message::ScenarioCanvas(behavior::scenario::CanvasEvent::Viewport(c, size)) => (
Surface::Scenario(c.scenario),
*size,
c.document == context.document
&& c.revision == context.revision
&& c.epoch == *epoch,
),
Message::StateDiagram(behavior::state_edit::Event::Viewport(c, size)) => (
Surface::Saved(c.diagram),
*size,
c.document == context.document
&& c.revision == context.revision
&& c.epoch == *epoch,
),
_ => return None,
};
(valid
&& surface == usage.surface
&& size.width.is_finite()
&& size.height.is_finite()
&& size.width > 0.
&& size.height > 0.)
.then_some(surface)
}
pub(super) fn reconcile_pending_diagram_reveal(&mut self, message: &Message) {
if !matches!(
message,
Message::CheckpointTick
| Message::CheckpointWritten(..)
| Message::Lint(_)
| Message::Linted(..)
| Message::SourceViewport(_)
| Message::WindowResized(_)
| Message::CanvasResized(_)
| Message::DiagramRevealViewport(..)
| Message::DiagramUsage(_)
| Message::DiagramUsagesReady(_)
| Message::SourceSymbolsReady(_)
| Message::TopologyCanvas(behavior::topology::CanvasEvent::Viewport(..))
| Message::ScenarioCanvas(behavior::scenario::CanvasEvent::Viewport(..))
| Message::StateDiagram(behavior::state_edit::Event::Viewport(..))
) {
self.pending_diagram_reveal = None;
if !Self::is_navigation_camera(message) {
self.diagram_navigation_focus = None;
}
}
}
fn is_navigation_camera(message: &Message) -> bool {
if let Message::BehaviorControl(intent) = message {
return Self::is_navigation_camera(&intent.message);
}
matches!(
message,
Message::Pan(_)
| Message::Zoom(_)
| Message::Fit
| Message::TopologyCanvas(
behavior::topology::CanvasEvent::Camera(..)
| behavior::topology::CanvasEvent::Zoom(..)
| behavior::topology::CanvasEvent::Scrolled(..)
| behavior::topology::CanvasEvent::Focus(..)
)
| Message::ScenarioCanvas(
behavior::scenario::CanvasEvent::Camera(..)
| behavior::scenario::CanvasEvent::Zoom(..)
| behavior::scenario::CanvasEvent::Scrolled(..)
| behavior::scenario::CanvasEvent::Focus(..)
)
| Message::StateDiagram(
behavior::state_edit::Event::Pan(..)
| behavior::state_edit::Event::Zoom(..)
| behavior::state_edit::Event::Fit(..)
)
)
}
pub(super) fn finish_diagram_reveal(&mut self, surface: Surface) {
let Some((context, usage, _)) = self.pending_diagram_reveal.take() else {
return;
};
if context.document == self.canvas_document
&& context.revision == self.document.revision()
&& usage.surface == surface
&& !self.draft_dirty()
&& !self.source_dirty()
&& !self.behavior.has_pending()
{
// The normal viewport handler has now stored the measured size.
// Target identity was validated for this revision before navigation.
self.reveal_diagram_usage(&usage);
}
self.pending_diagram_reveal = None;
}
}
@@ -1,403 +0,0 @@
//! Independent first-layout navigation oracles, through the real App boundary.
use super::*;
use crate::diagram_usage::{self as usage, Target, Usage};
use iced::{Size, Vector};
use std::collections::BTreeMap;
#[derive(Clone, Copy, Debug)]
enum Canvas {
Architecture,
Process,
Scenario,
State,
}
const CANVASES: [Canvas; 4] = [
Canvas::Architecture,
Canvas::Process,
Canvas::Scenario,
Canvas::State,
];
const WIDE: Size = Size::new(1200., 700.);
const ACTUAL: Size = Size::new(500., 300.);
fn send(app: &mut App, message: Message) {
let _ = app.update(message);
}
fn fixture(canvas: Canvas) -> (App, Usage) {
let mut p = Project::empty();
let work = p
.add_element(Kind::Activity, Layer::Oa, "Respond", None)
.unwrap();
let (surface, subject) = match canvas {
Canvas::Architecture => {
let diagram = p.ensure_diagram(Layer::Oa);
p.place(
diagram,
work,
Position {
x: 12_000.,
y: 9_000.,
},
);
(Surface::Saved(diagram), work)
}
Canvas::Process | Canvas::Scenario => {
let kind = if matches!(canvas, Canvas::Process) {
Kind::Process
} else {
Kind::Scenario
};
let owner = p.add_element(kind, Layer::Oa, "Response", None).unwrap();
let occurrence = p
.add_element(Kind::Occurrence, Layer::Oa, "Respond here", Some(owner))
.unwrap();
*p.elements
.get_mut(&occurrence)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Occurrence {
body: OccurrenceBody::Action {
action: Some(work),
lifeline: None,
},
precondition: String::new(),
postcondition: String::new(),
};
let steps = p.elements.get_mut(&owner).unwrap().steps_mut().unwrap();
if !steps.contains(&occurrence) {
steps.push(occurrence);
}
(
if matches!(canvas, Canvas::Process) {
Surface::Process(owner)
} else {
Surface::Scenario(owner)
},
occurrence,
)
}
Canvas::State => {
let machine = p
.add_element(Kind::StateMachine, Layer::Oa, "Modes", None)
.unwrap();
let region = p
.add_element(Kind::Region, Layer::Oa, "Main", Some(machine))
.unwrap();
let state = p
.add_element(Kind::State, Layer::Oa, "Ready", Some(region))
.unwrap();
let diagram = Id::new_v4();
p.diagrams.insert(
diagram,
Diagram {
id: diagram,
alias: "ready_view".into(),
name: "Ready view".into(),
description: String::new(),
layer: Layer::Oa,
projection: ProjectionKind::StateMachine { machine },
nodes: BTreeMap::new(),
routes: vec![],
view_options: Default::default(),
},
);
p.place(
diagram,
state,
Position {
x: 8_000.,
y: 11_000.,
},
);
(Surface::Saved(diagram), state)
}
};
let mut app = App::with_project(p);
let found = usage::collect(
app.project(),
subject,
&app.behavior.topology,
&app.behavior.scenario,
)
.into_iter()
.find(|u| u.surface == surface && u.target != Target::Whole)
.unwrap();
app.canvas_size = Some(WIDE);
app.behavior.diagram.viewport = Some(WIDE);
if let Surface::Process(owner) = surface {
app.behavior.topology.enter(app.canvas_document, owner);
app.behavior.topology.viewport(WIDE);
}
if let Surface::Scenario(owner) = surface {
app.behavior.scenario.enter(app.canvas_document, owner);
app.behavior.scenario.viewport(WIDE);
}
app.page = Page::Text;
(app, found)
}
fn measurement(
canvas: Canvas,
context: Context,
epoch: u64,
surface: Surface,
size: Size,
) -> Message {
match canvas {
Canvas::Architecture => Message::DiagramRevealViewport(context, epoch, size),
Canvas::Process => Message::TopologyCanvas(behavior::topology::CanvasEvent::Viewport(
behavior::topology::Context {
document: context.document,
owner: surface.id(),
revision: context.revision,
epoch,
},
size,
)),
Canvas::Scenario => Message::ScenarioCanvas(behavior::scenario::CanvasEvent::Viewport(
behavior::scenario::Context {
document: context.document,
scenario: surface.id(),
revision: context.revision,
epoch,
},
size,
)),
Canvas::State => Message::StateDiagram(behavior::state_edit::Event::Viewport(
behavior::state_edit::Context {
document: context.document,
diagram: surface.id(),
revision: context.revision,
epoch,
},
size,
)),
}
}
fn stamp(app: &App) -> (Context, u64) {
let (context, _, epoch) = app
.pending_diagram_reveal
.as_ref()
.expect("reveal awaits measured destination");
(*context, *epoch)
}
fn assert_centered(app: &App, canvas: Canvas, target: &Usage) {
// All independently authored fixture targets fit ACTUAL at the readable cap.
// This oracle does not call the production camera/reveal implementation.
let zoom = 1.25;
let pan = Vector::new(
250. - target.bounds.center_x() * zoom,
150. - target.bounds.center_y() * zoom,
);
match canvas {
Canvas::Architecture => {
assert_eq!(app.canvas_size, Some(ACTUAL));
assert_eq!(app.zoom, zoom);
assert_eq!(app.pan, pan);
assert!(!app.fit_to_view);
}
Canvas::State => {
assert_eq!(app.behavior.diagram.viewport, Some(ACTUAL));
assert_eq!(app.behavior.diagram.zoom, zoom);
assert_eq!(app.behavior.diagram.pan, pan);
assert!(!app.behavior.diagram.fit);
}
Canvas::Process => {
let mut expected = behavior::topology::State::default();
expected.enter(app.canvas_document, target.surface.id());
expected.viewport(ACTUAL);
expected.zoom(Some(zoom));
expected.camera(behavior::canvas_workspace::Event::Pan(pan));
assert!(app.behavior.topology.camera_boundary() == expected.camera_boundary());
}
Canvas::Scenario => {
let mut expected = behavior::scenario::State::default();
expected.enter(app.canvas_document, target.surface.id());
expected.choose_tool(target.surface.id(), behavior::scenario::CanvasTool::Select);
expected.viewport(ACTUAL);
expected.zoom(Some(zoom));
expected.camera(behavior::canvas_workspace::Event::Pan(pan));
assert!(app.behavior.scenario.camera_boundary() == expected.camera_boundary());
}
}
}
#[test]
fn all_reveal_surfaces_recenter_once_after_the_real_viewport_and_preserve_authored_state() {
for canvas in CANVASES {
let (mut app, target) = fixture(canvas);
let accepted = app.document.snapshot();
let drafts = app.source_workspace.bundle();
let revision = app.document.revision();
let history = (
app.document.can_undo(),
app.document.can_redo(),
app.document.dirty(),
);
assert!(app.reveal_diagram_usage(&target));
let (context, epoch) = stamp(&app);
send(
&mut app,
measurement(canvas, context, epoch, target.surface, ACTUAL),
);
assert!(app.pending_diagram_reveal.is_none());
assert_centered(&app, canvas, &target);
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
assert_eq!(app.source_workspace.bundle(), drafts);
assert_eq!(app.document.revision(), revision);
assert_eq!(
(
app.document.can_undo(),
app.document.can_redo(),
app.document.dirty()
),
history
);
// The exact delivered callback is a replay after the one-shot is consumed.
let camera = app.camera_boundary();
send(
&mut app,
measurement(canvas, context, epoch, target.surface, ACTUAL),
);
assert!(app.pending_diagram_reveal.is_none());
assert!(app.camera_boundary() == camera);
assert_centered(&app, canvas, &target);
}
}
#[test]
fn malformed_or_wrong_stamp_measurements_cannot_poison_a_pending_reveal() {
for canvas in CANVASES {
for invalid in 0..6 {
let (mut app, target) = fixture(canvas);
assert!(app.reveal_diagram_usage(&target));
let (context, epoch) = stamp(&app);
let camera = app.camera_boundary();
let mut stale = context;
let mut wrong_epoch = epoch;
let mut size = Size::new(111., 122.);
match invalid {
0 => stale.document = Id::new_v4(),
1 => stale.revision = stale.revision.wrapping_add(1),
2 => wrong_epoch = wrong_epoch.wrapping_add(1),
3 => size.width = f32::NAN,
4 => size.height = f32::INFINITY,
_ => size.width = 0.,
}
send(
&mut app,
measurement(canvas, stale, wrong_epoch, target.surface, size),
);
assert!(
app.pending_diagram_reveal.is_some(),
"{canvas:?} invalid case {invalid}"
);
assert_eq!(stamp(&app), (context, epoch));
assert_eq!(app.canvas_epoch, epoch);
assert!(
app.camera_boundary() == camera,
"{canvas:?} invalid case {invalid}"
);
send(
&mut app,
measurement(canvas, context, epoch, target.surface, ACTUAL),
);
assert!(app.pending_diagram_reveal.is_none());
assert_centered(&app, canvas, &target);
}
}
}
#[test]
fn actual_window_resize_before_first_measurement_retains_focus_for_the_new_context() {
for canvas in CANVASES {
let (mut app, target) = fixture(canvas);
let accepted = app.document.snapshot();
assert!(app.reveal_diagram_usage(&target));
let (context, old_epoch) = stamp(&app);
send(&mut app, Message::WindowResized(Size::new(1100., 700.)));
let (current, epoch) = stamp(&app);
assert_eq!(current, context);
assert_eq!(epoch, app.canvas_epoch);
if matches!(canvas, Canvas::Process | Canvas::Scenario) {
assert_ne!(epoch, old_epoch);
let camera = app.camera_boundary();
send(
&mut app,
measurement(canvas, context, old_epoch, target.surface, ACTUAL),
);
assert_eq!(stamp(&app), (current, epoch));
assert!(app.camera_boundary() == camera);
}
send(
&mut app,
measurement(canvas, current, epoch, target.surface, ACTUAL),
);
assert!(app.pending_diagram_reveal.is_none());
assert_centered(&app, canvas, &target);
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
}
}
#[test]
fn user_camera_edit_and_navigation_cancel_deferred_focus_without_late_snapping() {
for canvas in CANVASES {
for action in 0..3 {
let (mut app, target) = fixture(canvas);
let accepted = app.document.snapshot();
assert!(app.reveal_diagram_usage(&target));
let (context, epoch) = stamp(&app);
let event = match action {
0 => match canvas {
Canvas::Architecture => Message::Pan(Vector::new(31., -17.)),
Canvas::State => Message::StateDiagram(behavior::state_edit::Event::Pan(
app.state_context().unwrap(),
Vector::new(31., -17.),
)),
Canvas::Process => {
Message::TopologyCanvas(behavior::topology::CanvasEvent::Camera(
app.topology_context().unwrap(),
app.camera_epoch,
behavior::canvas_workspace::Event::Pan(Vector::new(31., -17.)),
))
}
Canvas::Scenario => {
Message::ScenarioCanvas(behavior::scenario::CanvasEvent::Camera(
app.scenario_context().unwrap(),
app.camera_epoch,
behavior::canvas_workspace::Event::Pan(Vector::new(31., -17.)),
))
}
},
1 => Message::Field("/name".into(), "Pending title edit".into()),
_ => Message::Page(Page::Catalog),
};
send(&mut app, event);
assert!(
app.pending_diagram_reveal.is_none(),
"{canvas:?} action {action}"
);
let camera = app.camera_boundary();
let page = app.page;
// A stale layout callback at the already retained size cannot
// restore the old navigation camera after deliberate user input.
send(
&mut app,
measurement(canvas, context, epoch, target.surface, WIDE),
);
assert!(app.pending_diagram_reveal.is_none());
assert!(
app.camera_boundary() == camera,
"{canvas:?} action {action}"
);
assert_eq!(app.page, page);
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
if action == 1 {
assert!(app.draft_dirty());
}
}
}
}
-445
View File
@@ -1,445 +0,0 @@
//! Navigation-only adapter: validates destinations before changing presentation.
use super::*;
use crate::diagram_usage::{self as usage, Context, Event, Panel, Surface, Target, Usage};
#[cfg(test)]
mod tests;
impl App {
pub(crate) fn diagram_usage_message(&self, subject: Id) -> Message {
Message::DiagramUsage(Event::Open(Context {
document: self.canvas_document,
revision: self.document.revision(),
subject,
}))
}
fn usage_navigation_available(&self) -> bool {
!self.busy
&& self.pending.is_none()
&& self.file_prompt.is_none()
&& !self.delete_pending
&& self.workflow.is_none()
&& !self.hosted.visible
&& self.architecture.is_none()
&& !self.reference_input_active()
&& !self.behavior.has_pending()
&& !self.draft_dirty()
&& !self.source_dirty()
}
/// Admit at most one expensive lookup, including one accepted Project clone.
/// A replacement panel waits for the previous worker's exact completion.
fn start_diagram_lookup(&mut self) -> Task<Message> {
let Some(panel) = self.diagram_usages.as_ref() else {
return Task::none();
};
if !panel.loading || self.diagram_lookup_in_flight.is_some() {
return Task::none();
}
let (token, context) = (panel.token, panel.context);
if context.document != self.canvas_document
|| context.revision != self.document.revision()
|| !self.usage_navigation_available()
{
let panel = self.diagram_usages.as_mut().unwrap();
panel.loading = false;
panel.notice = Some(
"The model or pending edits changed. Reopen diagram navigation when ready.".into(),
);
return Task::none();
}
let project = self.project().clone();
let presentation = self.behavior.topology.usage_snapshot();
self.diagram_lookup_in_flight = Some(token);
Task::perform(
async move {
let result = tokio::task::spawn_blocking(move || {
let process = presentation.into_query_state();
let scenario = behavior::scenario::State::default();
usage::collect(&project, context.subject, &process, &scenario)
})
.await
.map_err(|error| format!("Diagram lookup failed: {error}. Close and try again."));
usage::Completion {
token,
context,
result,
}
},
Message::DiagramUsagesReady,
)
}
fn refresh_diagram_lookup(&mut self, notice: &str) -> Task<Message> {
let Some(panel) = self.diagram_usages.as_mut() else {
return Task::none();
};
panel.token = Id::new_v4();
panel.context.revision = self.document.revision();
panel.usages.clear();
panel.loading = true;
panel.page = 0;
panel.cursor = 0;
panel.destination = None;
panel.notice = Some(notice.into());
self.start_diagram_lookup()
}
/// Must run before modal/input dispatch. A closed or replaced panel still
/// owns its worker slot until this exact completion arrives.
pub(super) fn diagram_usages_ready(&mut self, completion: usage::Completion) -> Task<Message> {
if self.diagram_lookup_in_flight != Some(completion.token) {
return Task::none();
}
self.diagram_lookup_in_flight = None;
let Some(panel) = self.diagram_usages.as_ref() else {
return Task::none();
};
if panel.context.document != self.canvas_document {
self.diagram_usages = None;
return Task::none();
}
if panel.context.revision != self.document.revision() {
return self
.refresh_diagram_lookup("The model changed. Review the refreshed destinations.");
}
if panel.token != completion.token {
// A newer Open/refresh waited without cloning or spawning a second job.
return self.start_diagram_lookup();
}
let panel = self.diagram_usages.as_mut().unwrap();
if panel.context != completion.context || !panel.loading {
panel.loading = false;
panel.notice = Some(
"This lookup no longer matches the requested model. Close and try again.".into(),
);
return Task::none();
}
panel.loading = false;
match completion.result {
Ok(usages) => panel.usages = usages,
Err(error) => panel.notice = Some(error),
}
Task::none()
}
/// Selection validates one destination only; opening the chooser does the
/// whole-project scan on its worker, never on the GUI thread.
fn current_surface_usages(&self, subject: Id, surface: Surface) -> Vec<Usage> {
match surface {
Surface::Saved(diagram) => {
usage::saved_usages_for(self.project(), subject, Some(diagram))
}
Surface::Process(owner) => {
self.behavior
.topology
.diagram_usages(self.project(), owner, subject)
}
Surface::Scenario(owner) => {
self.behavior
.scenario
.diagram_usages(self.project(), owner, subject)
}
}
}
pub(super) fn diagram_usage_event(&mut self, event: Event) -> Task<Message> {
if let Event::Open(context) = event {
if context.document != self.canvas_document
|| context.revision != self.document.revision()
|| !self.project().contains(context.subject)
{
return Task::none();
}
if !self.usage_navigation_available() {
self.status = "Apply or revert pending edits before opening diagram navigation. Your inputs are retained.".into();
return Task::none();
}
let mut panel = Panel::new(context, Vec::new());
panel.loading = true;
let filter_id = format!("diagram-usage-filter-{}", panel.token);
self.diagram_usages = Some(panel);
self.model_menu = None;
// Only an accepted new chooser supersedes the previous reveal.
// Rejected/stale panel envelopes leave its first measurement intact.
self.pending_diagram_reveal = None;
self.diagram_navigation_focus = None;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
return Task::batch([
self.start_diagram_lookup(),
iced::widget::operation::focus(filter_id),
]);
}
let token = match &event {
Event::Open(_) => unreachable!(),
Event::Close(t)
| Event::Search(t, _)
| Event::Page(t, _)
| Event::Move(t, _)
| Event::Activate(t)
| Event::Destination(t, _)
| Event::Choose(t, _) => *t,
};
let Some(panel) = &self.diagram_usages else {
return Task::none();
};
if panel.token != token {
return Task::none();
}
if matches!(event, Event::Close(_)) {
self.diagram_usages = None;
if self.page == Page::Text {
self.restore_source_editor_focus();
}
return Task::none();
}
if panel.context.document != self.canvas_document {
self.diagram_usages = None;
return Task::none();
}
if panel.context.revision != self.document.revision() {
return self
.refresh_diagram_lookup("The model changed. Review the refreshed destinations.");
}
if panel.loading {
// Search and Close remain useful while loading; queued activation
// must not perform a synchronous fallback or choose an old row.
if let Event::Search(_, query) = event {
self.diagram_usages.as_mut().unwrap().search = query;
}
return Task::none();
}
match event {
Event::Move(_, direction) => {
let panel = self.diagram_usages.as_ref().unwrap();
let count = panel.choices(self.project()).len();
let panel = self.diagram_usages.as_mut().unwrap();
if count > 0 {
panel.cursor = if direction < 0 {
(panel.cursor + count - 1) % count
} else {
(panel.cursor + 1) % count
};
panel.page = panel.cursor / 6;
}
}
Event::Activate(_) => {
let panel = self.diagram_usages.as_ref().unwrap();
if let Some(event) = panel.choices(self.project()).get(panel.cursor).cloned() {
return self.diagram_usage_event(event);
}
}
Event::Search(_, query) => {
let panel = self.diagram_usages.as_mut().unwrap();
panel.search = query;
panel.page = 0;
panel.cursor = 0;
}
Event::Page(_, page) => {
let panel = self.diagram_usages.as_mut().unwrap();
panel.page = page;
panel.cursor = page.saturating_mul(6);
}
Event::Destination(_, surface) => {
let panel = self.diagram_usages.as_mut().unwrap();
if surface.is_none() || panel.usages.iter().any(|u| Some(u.surface) == surface) {
panel.destination = surface;
panel.page = 0;
panel.cursor = 0;
}
}
Event::Choose(_, requested) => {
if !self.usage_navigation_available() {
return Task::none();
}
let subject = self.diagram_usages.as_ref().unwrap().context.subject;
let fresh = self
.current_surface_usages(subject, requested.surface)
.into_iter()
.find(|u| u.subject == requested.subject && u.target == requested.target);
let Some(fresh) = fresh else {
return self.refresh_diagram_lookup(
"This representation changed. Review the refreshed destinations.",
);
};
if self.reveal_diagram_usage(&fresh) {
self.diagram_usages = None;
self.status = format!(
"{} · {} in {}",
self.project().named(subject),
fresh.role,
self.project().named(fresh.surface.id())
);
return Task::batch(["model-explorer", "model-browser", "inspector"].map(
|id| {
iced::widget::operation::snap_to(
id,
iced::widget::scrollable::RelativeOffset::START,
)
},
));
}
}
Event::Open(_) | Event::Close(_) => unreachable!(),
}
Task::none()
}
pub(super) fn reveal_diagram_usage(&mut self, usage: &Usage) -> bool {
if !self.usage_navigation_available() {
return false;
}
let previous_layer = self.layer;
let p = self.document.project();
let (selected, placement) = match &usage.target {
Target::Whole => (usage.surface.id(), None),
Target::Placement(id) => {
let Some(node) = p
.diagrams
.get(&usage.surface.id())
.and_then(|d| d.nodes.get(id))
else {
return false;
};
(node.element, Some(*id))
}
Target::Port { port, placement } => (*port, Some(*placement)),
Target::StateRow {
placement,
relation,
} => (*relation, Some(*placement)),
Target::Edge(id)
| Target::ProcessLink(id)
| Target::ScenarioObject(id)
| Target::AllocationGrouping { relation: id, .. }
| Target::ProcessPreviewLink { relation: id, .. } => (*id, None),
Target::ProcessOccurrence(endpoint) => (
endpoint
.references
.first()
.copied()
.unwrap_or(endpoint.occurrence),
None,
),
};
match usage.surface {
Surface::Saved(id) => {
let Some(diagram) = p.diagrams.get(&id) else {
return false;
};
self.layer = diagram.layer;
self.active_diagram = Some(id);
if let Some(machine) = diagram.projection.state_machine() {
let viewport = self.behavior.diagram.viewport.unwrap_or(iced::Size::new(
(self.window_size.width - 610.).max(280.),
(self.window_size.height - 320.).max(240.),
));
let (zoom, pan) = usage::camera_for(&usage.target, usage.bounds, viewport);
self.behavior.diagram = behavior::state_view::State {
diagram: Some(id),
placement,
viewport: Some(viewport),
zoom,
pan,
fit: false,
..Default::default()
};
self.behavior.active_owner = Some(machine);
self.page = Page::Behavior;
} else {
let viewport = self.canvas_size.unwrap_or(iced::Size::new(
(self.window_size.width - 550.).max(280.),
(self.window_size.height - 284.).max(240.),
));
(self.zoom, self.pan) =
usage::camera_for(&usage.target, usage.bounds, viewport);
self.fit_to_view = false;
self.page = Page::Diagram;
}
}
Surface::Process(owner) => {
if !self.behavior.topology.reveal_usage(
p,
self.canvas_document,
owner,
&usage.target,
) {
return false;
}
self.layer = p.elements[&owner].layer();
self.behavior.active_owner = Some(owner);
self.page = Page::Behavior;
}
Surface::Scenario(owner) => {
if !self.behavior.scenario.reveal_usage(
p,
self.canvas_document,
owner,
&usage.target,
) {
return false;
}
self.layer = p.elements[&owner].layer();
self.behavior.active_owner = Some(owner);
self.page = Page::Behavior;
}
}
self.selected = selected;
self.selected_node = placement;
self.model_menu = None;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
self.selected_bend = None;
self.connection = None;
self.last_workspace_page = self.page;
if previous_layer != self.layer {
self.data_state = Default::default();
self.explorer_index = crate::explorer::Index::new(self.project(), self.layer);
self.explorer_focus = None;
self.explorer_group = None;
self.explorer_page = 0;
}
self.normalize_creation();
self.reveal_explorer_selection();
self.refresh_draft();
self.diagram_navigation_focus = Some(usage::Focus {
context: Context {
document: self.canvas_document,
revision: self.document.revision(),
subject: usage.subject,
},
usage: usage.clone(),
selected,
});
self.pending_diagram_reveal = Some((
Context {
document: self.canvas_document,
revision: self.document.revision(),
subject: usage.subject,
},
usage.clone(),
self.canvas_epoch,
));
true
}
/// Validated presentation identity. Edit selection and Delete capture remain
/// semantic; a port owner or allocation work box is only a visual marker.
pub(crate) fn diagram_focus(&self, surface: Surface) -> Option<&Usage> {
let focus = self.diagram_navigation_focus.as_ref()?;
let current_surface = match surface {
Surface::Saved(id) => {
self.active_diagram == Some(id)
&& matches!(self.page, Page::Diagram | Page::Behavior)
}
Surface::Process(owner) | Surface::Scenario(owner) => {
self.page == Page::Behavior && self.behavior.active_owner == Some(owner)
}
};
(current_surface
&& focus.usage.surface == surface
&& focus.context.document == self.canvas_document
&& focus.context.revision == self.document.revision()
&& focus.selected == self.selected)
.then_some(&focus.usage)
}
}
File diff suppressed because it is too large Load Diff
-16
View File
@@ -213,14 +213,6 @@ impl App {
self.pending = None;
return Task::none();
}
if self.path.is_some()
|| self.hosted.session.as_ref().is_none_or(|session| {
session.resource_id != remote.resource_id
|| session.connection.base() != request.connection.base()
})
{
self.source_workspace.reset_navigation_session();
}
self.hosted.session = Some(Session {
connection: request.connection.clone(),
resource_id: remote.resource_id,
@@ -353,14 +345,6 @@ impl App {
match self.document.apply_compiled((*remote.compiled).clone()) {
Ok(_) => {
self.document.mark_saved(remote.compiled.clone());
if self.path.is_some()
|| self.hosted.session.as_ref().is_none_or(|session| {
session.resource_id != remote.resource_id
|| session.connection.base() != connection.base()
})
{
self.source_workspace.reset_navigation_session();
}
self.hosted.session = Some(Session {
connection,
resource_id: remote.resource_id,
-507
View File
@@ -1,507 +0,0 @@
//! Current draft navigation, isolated from model application and disk discovery.
use super::*;
use crate::source_navigation::{self as nav, query};
use std::sync::atomic::Ordering;
fn admission_notice(error: query::AdmissionError) -> String {
use nav::symbols::{BuildError, InputProblem, Resource};
let (limit, resource) = match error {
query::AdmissionError::Index(BuildError::Limit { limit, resource, .. }) => (limit, resource),
query::AdmissionError::Outline { error, .. } => (error.limit, match error.resource {
language::OutlineResource::SourceBytes => Resource::SourceBytes,
language::OutlineResource::Tokens => Resource::Tokens,
language::OutlineResource::Declarations => Resource::Records,
}),
query::AdmissionError::Index(BuildError::Input { problem, .. }) => return match problem {
InputProblem::NonCanonicalPath | InputProblem::DuplicateOrCaseCollidingPath =>
"Navigation needs distinct relative source paths. Check file names and include paths.".into(),
_ => "Navigation could not verify the current source locations. Correct source errors and try again.".into(),
},
};
let unit = match resource {
Resource::Files => "loaded files",
Resource::SourceBytes => "source bytes",
Resource::PathBytes => "bytes in file paths",
Resource::Tokens => "source tokens",
Resource::Records => "declarations and references",
};
format!(
"Navigation reached its limit of {limit} {unit}. Reduce the loaded source size and try again."
)
}
impl App {
pub fn source_symbol_context(&self) -> nav::SymbolContext {
nav::SymbolContext {
session: self.source_workspace.session(),
path: self.source_workspace.active.clone(),
}
}
pub fn source_symbol_message(&self, event: nav::SymbolEvent) -> Message {
Message::SourceSymbols(self.source_symbol_context(), event)
}
pub fn source_find_close_message(&self) -> Message {
Message::SourceFindClose(self.source_symbol_context(), self.source_find_instance)
}
pub fn source_key(&self) -> query::SnapshotKey {
query::SnapshotKey {
workspace: self.source_workspace.session(),
revision: self.source_workspace.revision(),
}
}
fn with_source_input<T>(&self, use_input: impl FnOnce(query::Input<'_>) -> T) -> T {
let files: Vec<_> = self
.source_workspace
.files
.iter()
.map(|(path, buffer)| query::DraftFile {
path,
text: &buffer.text,
})
.collect();
let accepted = self.document.bundle();
let validated: Vec<_> = accepted
.files
.iter()
.map(|(path, text)| query::DraftFile { path, text })
.collect();
use_input(query::Input {
key: self.source_key(),
entry: &self.source_workspace.entry,
files: &files,
applied: self.source_workspace.applied,
validation: self
.source_workspace
.applied
.then_some(query::ValidatedSources {
entry: &accepted.entry,
files: &validated,
}),
})
}
fn source_snapshot_matches(&self, snapshot: &query::Snapshot) -> bool {
snapshot.key() == self.source_key()
&& self.with_source_input(|input| snapshot.matches(input))
}
pub fn source_navigation_available(&self) -> bool {
self.page == Page::Text
&& !self.busy
&& self.pending.is_none()
&& self.file_prompt.is_none()
&& !self.delete_pending
&& self.workflow.is_none()
&& !self.hosted.visible
&& self.model_menu.is_none()
&& self.diagram_usages.is_none()
&& !self.reference_input_active()
&& self.architecture.is_none()
&& !self.behavior.has_pending()
}
/// Mounted widget IDs change when another interaction supersedes a reveal.
/// A queued focus operation therefore cannot find a subsequently reused editor.
pub fn source_editor_id(&self) -> iced::widget::Id {
iced::widget::Id::from(format!(
"source-editor-{}-{}-{}",
self.source_workspace.session(),
self.source_workspace.active,
self.source_symbols.interaction
))
}
pub fn source_reveal_ticket(&self) -> Option<Id> {
self.source_symbols
.reveal
.as_ref()
.map(|reveal| reveal.ticket)
}
pub(super) fn source_interaction(&mut self) {
self.source_symbols.interaction = Id::new_v4();
self.source_symbols.request = None;
self.source_symbols.reveal = None;
self.source_jump = None;
}
pub(super) fn queue_source_reveal(&mut self, cursor: text_editor::Cursor, select_line: bool) {
self.source_jump = Some(cursor);
self.source_select_line = select_line;
self.source_symbols.reveal = Some(nav::Reveal {
ticket: Id::new_v4(),
interaction: self.source_symbols.interaction,
raw_interaction: self.source_symbols.raw_interaction.load(Ordering::SeqCst),
snapshot: self.source_key(),
path: self.source_workspace.active.clone(),
});
}
pub(super) fn restore_source_editor_focus(&mut self) {
let cursor = self.source_editor.cursor();
if self.source_navigation_available()
&& nav::exact_cursor(self.source_workspace.text(), cursor)
{
self.queue_source_reveal(cursor, false);
}
}
pub(super) fn source_viewport(&mut self, ticket: Option<Id>) -> Task<Message> {
let Some(reveal) = &self.source_symbols.reveal else {
return Task::none();
};
if Some(reveal.ticket) != ticket
|| reveal.interaction != self.source_symbols.interaction
|| !nav::interaction::is_current(
&self.source_symbols.raw_interaction,
reveal.raw_interaction,
)
|| reveal.snapshot != self.source_key()
|| reveal.path != self.source_workspace.active
|| !self.source_navigation_available()
{
return Task::none();
}
let raw_interaction = reveal.raw_interaction;
self.source_symbols.reveal = None;
if let Some(cursor) = self.source_jump.take() {
if !nav::exact_cursor(self.source_workspace.text(), cursor) {
return Task::none();
}
self.source_editor.move_to(cursor);
if self.source_select_line && cursor.selection.is_none() {
self.source_editor.perform(text_editor::Action::SelectLine);
}
return nav::interaction::guarded_focus(
self.source_editor_id(),
self.source_symbols.raw_interaction.clone(),
raw_interaction,
);
}
Task::none()
}
pub(super) fn source_symbol_event(&mut self, event: nav::SymbolEvent) -> Task<Message> {
if !self.source_navigation_available() {
return Task::none();
}
match event {
nav::SymbolEvent::DiagramUsages => {
if self.source_dirty() || !self.source_workspace.applied {
self.source_symbols.open = true;
self.source_symbols.notice = Some("Apply source before finding diagram representations. Your current text is retained.".into());
return Task::none();
}
let task = self.start_source_query(query::Action::Definition);
self.source_diagram_job = self
.source_symbols
.request
.as_ref()
.map(|request| request.job);
return task;
}
nav::SymbolEvent::Close => {
self.source_symbols.open = false;
self.source_symbols.results = None;
self.source_symbols.notice = None;
}
nav::SymbolEvent::Back => {
self.source_symbol_back();
// A successful Back needs no empty results panel. Retain an
// already open panel, or reveal an actionable return notice.
self.source_symbols.open |= self.source_symbols.notice.is_some();
}
nav::SymbolEvent::Choose {
stamp,
reference,
index,
} => {
let Some(results) = self.source_symbols.results.clone() else {
return Task::none();
};
if results.stamp != stamp
|| stamp.snapshot != self.source_key()
|| self
.source_symbols
.cache
.as_ref()
.is_none_or(|cache| !self.source_snapshot_matches(cache))
{
self.source_symbols.notice =
Some("Source changed. Run navigation again for current locations.".into());
return Task::none();
}
let destination = if reference {
results
.references
.get(index)
.map(|row| (&row.path, row.position, row.end_position))
} else {
results
.definitions
.get(index)
.map(|row| (&row.path, row.position, row.end_position))
};
if let Some((path, start, end)) = destination {
self.source_symbol_jump(path, start, end);
}
}
nav::SymbolEvent::Query(action) => return self.start_source_query(action),
}
Task::none()
}
fn start_source_query(&mut self, action: query::Action) -> Task<Message> {
self.source_symbols.open = true;
if !nav::interaction::is_current(
&self.source_symbols.raw_interaction,
self.source_symbols.raw_interaction.load(Ordering::SeqCst),
) {
self.source_symbols.notice = Some("Reopen this workspace to reset navigation.".into());
return Task::none();
}
if self.source_symbols.in_flight.is_some() {
self.source_symbols.notice = Some("Navigation is finishing. Try again shortly.".into());
return Task::none();
}
let cursor = self.source_editor.cursor();
let Some(offset) = nav::cursor_offset(self.source_workspace.text(), cursor) else {
self.source_symbols.notice =
Some("Place the cursor on an alias or its @ reference.".into());
return Task::none();
};
self.source_symbols.serial = match self.source_symbols.serial.checked_add(1) {
Some(serial) => serial,
None => {
self.source_workspace.reset_navigation_session();
self.source_symbols.back.clear();
self.source_symbols.cache = None;
0
}
};
let request = nav::Request {
job: Id::new_v4(),
interaction: self.source_symbols.interaction,
raw_interaction: self.source_symbols.raw_interaction.load(Ordering::SeqCst),
stamp: query::QueryStamp {
snapshot: self.source_key(),
serial: self.source_symbols.serial,
},
path: self.source_workspace.active.clone(),
offset,
cursor,
action,
};
let cache = self
.source_symbols
.cache
.as_ref()
.filter(|cache| self.source_snapshot_matches(cache))
.cloned();
let input = if cache.is_none() {
match self
.with_source_input(|input| query::admit_owned(input, query::Limits::default()))
{
Ok(input) => Some(input),
Err(error) => {
self.source_symbols.notice = Some(admission_notice(error));
return Task::none();
}
}
} else {
None
};
self.source_symbols.in_flight = Some(request.job);
self.source_symbols.request = Some(request.clone());
self.source_symbols.results = None;
self.source_symbols.notice = None;
Task::perform(
async move {
let worker_request = request.clone();
let result = tokio::task::spawn_blocking(move || {
let snapshot = match cache {
Some(cache) => cache,
None => Arc::new(
input
.expect("admitted input for uncached request")
.capture()
.map_err(admission_notice)?,
),
};
let results = snapshot
.query(query::Query {
stamp: worker_request.stamp,
path: &worker_request.path,
byte_offset: worker_request.offset,
action: worker_request.action,
})
.map_err(|error| match error {
query::QueryError::ResultEnvelopeLimit => "These result details exceed the display limit. Try literal Find for this alias.".to_owned(),
_ => "Navigation could not verify this location. Place the cursor on an alias and try again.".to_owned(),
})?;
Ok((snapshot, Arc::new(results)))
})
.await
.unwrap_or_else(|error| Err(format!("Navigation task failed: {error}")));
nav::Completion { request, result }
},
Message::SourceSymbolsReady,
)
}
pub(super) fn source_symbols_ready(&mut self, completion: nav::Completion) -> Task<Message> {
let request = completion.request;
if self.source_symbols.in_flight != Some(request.job) {
return Task::none();
}
self.source_symbols.in_flight = None;
let diagram_query = self.source_diagram_job == Some(request.job);
if diagram_query {
self.source_diagram_job = None;
}
let wanted = self
.source_symbols
.request
.take()
.is_some_and(|current| current.job == request.job)
&& request.interaction == self.source_symbols.interaction
&& request.stamp.snapshot == self.source_key()
&& nav::interaction::is_current(
&self.source_symbols.raw_interaction,
request.raw_interaction,
)
&& request.path == self.source_workspace.active
&& request.cursor == self.source_editor.cursor()
&& self.source_navigation_available();
if !wanted {
return Task::none();
}
match completion.result {
Ok((snapshot, results)) if self.source_snapshot_matches(&snapshot) => {
self.source_symbols.cache = Some(snapshot);
self.source_symbols.results = Some(results.clone());
if diagram_query {
if results.disposition == query::Disposition::Direct
&& results.scope.validated
&& results.omitted_definitions == 0
&& let [row] = results.definitions.as_slice()
&& let query::Identity::Unique(identity) = row.declaration.identity
&& row.membership == query::Membership::Included
&& row.evidence == query::Evidence::Validated
&& self.project().contains(identity.id())
&& crate::diagram_usage::alias(self.project(), identity.id())
== row.declaration.alias
{
self.source_symbols.open = false;
return self.diagram_usage_event(crate::diagram_usage::Event::Open(
crate::diagram_usage::Context {
document: self.canvas_document,
revision: self.document.revision(),
subject: identity.id(),
},
));
}
self.source_symbols.notice = Some("Place the caret on a uniquely resolved alias in applied source to find diagram representations.".into());
return Task::none();
}
if results.disposition == query::Disposition::Direct
&& let Some(row) = results.definitions.first()
{
self.source_symbol_jump(&row.path, row.position, row.end_position);
}
}
Ok(_) => {
self.source_symbols.notice = Some("Source changed. Run navigation again.".into())
}
Err(error) => self.source_symbols.notice = Some(error),
}
Task::none()
}
fn source_symbol_jump(&mut self, path: &str, start: query::Position, end: query::Position) {
let cursor = text_editor::Cursor {
position: text_editor::Position {
line: start.line,
column: start.byte_column,
},
selection: Some(text_editor::Position {
line: end.line,
column: end.byte_column,
}),
};
if self
.source_workspace
.files
.get(path)
.is_none_or(|buffer| !nav::exact_cursor(&buffer.text, cursor))
{
self.source_symbols.notice =
Some("That source location is no longer available. Run navigation again.".into());
return;
}
if let Some(buffer) = self
.source_workspace
.files
.get(&self.source_workspace.active)
{
let origin = nav::HistoryEntry {
session: self.source_workspace.session(),
path: self.source_workspace.active.clone(),
generation: buffer.generation(),
cursor: self.source_editor.cursor(),
};
self.source_symbols
.back
.retain(|entry| entry.session == origin.session);
if self.source_symbols.back.len() == 64 {
self.source_symbols.back.remove(0);
}
self.source_symbols.back.push(origin);
}
self.source_workspace
.switch(path, self.source_editor.cursor());
self.show_source_file(false);
self.queue_source_reveal(cursor, false);
}
fn source_symbol_back(&mut self) {
while let Some(origin) = self.source_symbols.back.pop() {
if origin.session != self.source_workspace.session() {
continue;
}
let Some(buffer) = self.source_workspace.files.get(&origin.path) else {
self.source_symbols.notice = Some("The previous file is no longer loaded.".into());
return;
};
let unchanged = origin.generation == buffer.generation();
let cursor = if unchanged {
origin.cursor
} else if origin.path == self.source_workspace.active {
self.source_editor.cursor()
} else {
buffer.cursor
};
if !nav::exact_cursor(&buffer.text, cursor) {
self.source_symbols.notice = Some(
"The previous location changed. Open the file to choose a current position."
.into(),
);
return;
}
self.source_workspace
.switch(&origin.path, self.source_editor.cursor());
self.show_source_file(false);
self.queue_source_reveal(cursor, false);
self.source_symbols.notice =
(!unchanged).then(|| "This draft changed; its current cursor was restored.".into());
return;
}
self.source_symbols.notice = Some("No previous source location in this workspace.".into());
}
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large Load Diff
@@ -114,6 +114,7 @@ impl App {
}
}
match event {
Event::Remove(intent) => self.remove_from_diagram(intent),
Event::Viewport(_, size) => {
if size.width.is_finite()
&& size.height.is_finite()
+67 -203
View File
@@ -20,6 +20,8 @@ mod contextual_source_tests;
pub(crate) mod creation;
mod form_session;
pub(crate) mod scenario;
// Projection acceptance precedes the coordinated scenario renderer integration.
#[cfg(test)]
mod scenario_lifecycle;
pub(crate) mod source_draft;
pub(crate) mod state_canvas;
@@ -1124,31 +1126,6 @@ struct BoxItem {
detail: String,
marker: Option<Kind>,
}
fn box_text_clip(
pan: iced::Vector,
rect: Rectangle,
scale: f32,
viewport: Size,
) -> Option<Rectangle> {
if !pan.x.is_finite()
|| !pan.y.is_finite()
|| !scale.is_finite()
|| scale <= 0.
|| rect.width <= 20.
|| rect.height <= 16.
{
return None;
}
Rectangle::new(
Point::new(
pan.x + (rect.x + 10.) * scale,
pan.y + (rect.y + 8.) * scale,
),
Size::new((rect.width - 20.) * scale, (rect.height - 16.) * scale),
)
.intersection(&Rectangle::new(Point::ORIGIN, viewport))
}
struct Line {
id: Id,
points: Vec<Point>,
@@ -1156,17 +1133,6 @@ struct Line {
label_at: Point,
dashed: bool,
}
impl Line {
fn label_bounds(&self) -> Rectangle {
Rectangle::new(
self.label_at,
Size::new(
(self.label.chars().count() as f32 * 6.8 + 8.).min(225.),
25.,
),
)
}
}
struct Scene {
boxes: Vec<BoxItem>,
lines: Vec<Line>,
@@ -1181,7 +1147,6 @@ struct Scene {
rows: BTreeMap<Id, (Id, f32)>,
open_calls: Vec<Point>,
sequence_bounds: BTreeMap<Id, (f32, f32)>,
lifecycle: scenario_lifecycle::render::Rendering,
}
struct SequenceSlot {
slot: scenario::Slot,
@@ -1240,7 +1205,6 @@ impl Scene {
rows: BTreeMap::new(),
open_calls: vec![],
sequence_bounds: BTreeMap::new(),
lifecycle: scenario_lifecycle::render::Rendering::default(),
};
let mut lanes = p
.children(owner)
@@ -1327,17 +1291,7 @@ impl Scene {
}
let mut y = if scenario { 148. } else { 120. };
scene.occurrences(p, owner, scenario, &lane_x, &mut y, 0);
scene.size.height = (y + 45.).max(210.);
if scenario {
scene.lifecycle = scenario_lifecycle::render::Rendering::new(
p,
owner,
&lane_x,
&scene.rows,
&scene.sequence_bounds,
scene.size.height,
);
scene.lifecycle.align_messages(&mut scene.lines);
let calls: Vec<_> = scene
.rows
.keys()
@@ -1362,28 +1316,23 @@ impl Scene {
scene.activation_sequence(p, p.elements[&call].parent.unwrap(), call, x, None);
}
}
scene.size.height = (y + 45.).max(210.);
for (id, name, detail) in lanes {
let x = lane_x[&id];
if !scenario {
scene.lines.insert(
0,
Line {
id,
points: vec![Point::new(x, 85.), Point::new(x, scene.size.height - 20.)],
label: String::new(),
label_at: Point::ORIGIN,
dashed: false,
},
);
}
scene.lines.insert(
0,
Line {
id,
points: vec![Point::new(x, 85.), Point::new(x, scene.size.height - 20.)],
label: String::new(),
label_at: Point::ORIGIN,
dashed: false,
},
);
scene.boxes.push(BoxItem {
id,
rect: Rectangle::new(Point::new(x - 102., 15.), Size::new(204., 70.)),
title: if scenario {
format!("Lane · {name}")
} else {
name
},
title: name,
detail,
marker: None,
});
@@ -1425,16 +1374,6 @@ impl Scene {
let Some(SharedBody::Occurrence { body, .. }) = e.shared() else {
continue;
};
if scenario
&& matches!(body, OccurrenceBody::Exchange {
sender: Some(sender), receiver: Some(receiver),
message_kind: MessageKind::Create | MessageKind::Delete, ..
} if sender == receiver)
{
// Self lifecycle elbows and their caption need clearance from
// the preceding action/state/reference box, before recording rows.
*y += 16.;
}
if ordered {
let slot = scenario::Slot {
parent: owner,
@@ -1654,27 +1593,17 @@ impl Scene {
});
}
}
fn activation_segment(
&mut self,
call: Id,
scope: Id,
receiver: Id,
x: f32,
top: f32,
bottom: f32,
) {
for span in self.lifecycle.alive_spans(receiver, scope, top, bottom) {
self.boxes.push(BoxItem {
id: call,
rect: Rectangle::new(
Point::new(x - 4., span.start),
Size::new(8., span.end - span.start),
),
title: String::new(),
detail: String::new(),
marker: None,
});
fn activation_segment(&mut self, call: Id, x: f32, top: f32, bottom: f32) {
if bottom <= top {
return;
}
self.boxes.push(BoxItem {
id: call,
rect: Rectangle::new(Point::new(x - 4., top), Size::new(8., bottom - top)),
title: String::new(),
detail: String::new(),
marker: None,
});
}
/// Follow a single correlation through the ordered tree. Branches are drawn
/// as independent segments, never as one chronological stretch through ALT
@@ -1687,18 +1616,6 @@ impl Scene {
x: f32,
mut start: Option<f32>,
) -> bool {
let Some(SharedBody::Occurrence {
body:
OccurrenceBody::Exchange {
receiver: Some(receiver),
..
},
..
}) = p.elements[&call].shared()
else {
return false;
};
let receiver = *receiver;
let entered_open = start.is_some();
let mut split = false;
for id in p.elements[&owner].steps().into_iter().flatten() {
@@ -1712,21 +1629,6 @@ impl Scene {
continue;
};
match p.elements[id].shared() {
Some(SharedBody::Occurrence {
body:
OccurrenceBody::Exchange {
message_kind: MessageKind::Delete,
receiver: Some(deleted),
..
},
..
}) if *deleted == receiver => {
// This path cannot show activation beyond its local death.
// Keep the unresolved-call cue; a Delete is not a Reply.
self.activation_segment(call, owner, receiver, x, top, y);
self.open_calls.push(Point::new(x + 12., y - 16.));
start = None;
}
Some(SharedBody::Occurrence {
body:
OccurrenceBody::Exchange {
@@ -1736,19 +1638,14 @@ impl Scene {
},
..
}) if *correlation == call => {
self.activation_segment(call, owner, receiver, x, top, y);
for span in self.lifecycle.alive_spans(receiver, owner, y - 1., y + 1.) {
self.boxes.push(BoxItem {
id: call,
rect: Rectangle::new(
Point::new(x - 7., span.start),
Size::new(14., span.end - span.start),
),
title: String::new(),
detail: String::new(),
marker: None,
});
}
self.activation_segment(call, x, top, y);
self.boxes.push(BoxItem {
id: call,
rect: Rectangle::new(Point::new(x - 7., y - 1.), Size::new(14., 2.)),
title: String::new(),
detail: String::new(),
marker: None,
});
start = None;
}
Some(SharedBody::Occurrence {
@@ -1756,7 +1653,7 @@ impl Scene {
..
}) => {
split = true;
self.activation_segment(call, owner, receiver, x, top, y);
self.activation_segment(call, x, top, y);
let bottom = self
.boxes
.iter()
@@ -1791,7 +1688,7 @@ impl Scene {
} else {
top + 26.
};
self.activation_segment(call, owner, receiver, x, top, bottom);
self.activation_segment(call, x, top, bottom);
self.open_calls.push(Point::new(x + 8., bottom - 7.));
}
start.is_some()
@@ -1824,12 +1721,6 @@ impl Scene {
))
}
fn hit(&self, point: Point) -> Option<Id> {
if !point.x.is_finite() || !point.y.is_finite() {
return None;
}
if let Some(id) = self.lifecycle.marker_at(point) {
return Some(id);
}
self.boxes
.iter()
.rev()
@@ -1842,10 +1733,23 @@ impl Scene {
.or_else(|| {
self.lines
.iter()
.find(|line| !line.label.is_empty() && line.label_bounds().contains(point))
.find(|line| {
!line.label.is_empty()
&& (Rectangle::new(
line.label_at,
Size::new(
(line.label.chars().count() as f32 * 6.8 + 8.).min(225.),
25.,
),
)
.contains(point)
|| line.points.windows(2).any(|p| {
crate::diagram::distance_to_segment(point, p[0], p[1])
< 8. / self.scale
}))
})
.map(|line| line.id)
})
.or_else(|| self.near_sequence_item(point))
.or_else(|| {
self.boxes
.iter()
@@ -1853,7 +1757,6 @@ impl Scene {
.find(|b| b.rect.contains(point) && b.title.is_empty())
.map(|b| b.id)
})
.or_else(|| self.lifecycle.lane_at(point, self.scale))
.or_else(|| self.lane_at(point))
.or_else(|| {
self.lines
@@ -1868,34 +1771,6 @@ impl Scene {
.map(|line| line.id)
})
}
fn near_sequence_item(&self, point: Point) -> Option<Id> {
if !self.scale.is_finite() || self.scale <= 0. {
return None;
}
let messages = self
.lines
.iter()
.filter(|line| !line.label.is_empty())
.map(|line| {
let distance = line
.points
.windows(2)
.map(|p| crate::diagram::distance_to_segment(point, p[0], p[1]))
.fold(f32::INFINITY, f32::min);
(line.id, distance)
});
// One distance comparison for both kinds of screen-sized hit tolerance.
// Dense minimum-Fit rows must not give the first message or last marker
// a larger hit priority than the visibly nearer item. UUID breaks ties.
self.lifecycle
.nearest_marker(point)
.into_iter()
.chain(messages)
.filter(|(_, distance)| *distance <= 8. / self.scale)
.min_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0)))
.map(|(id, _)| id)
}
}
impl canvas::Program<Message> for Scene {
type State = SequenceInput;
@@ -2157,7 +2032,6 @@ impl canvas::Program<Message> for Scene {
f.fill_rectangle(Point::ORIGIN, bounds.size(), Color::WHITE);
f.translate(self.camera_pan);
f.scale(self.scale);
self.lifecycle.draw_lanes(&mut f, self.selected);
for b in &self.boxes {
let outline = matches!(
b.marker,
@@ -2236,32 +2110,24 @@ impl canvas::Program<Message> for Scene {
}
}
for b in &self.boxes {
if let Some(clip) = box_text_clip(self.camera_pan, b.rect, self.scale, f.size()) {
// Clipped child frames start with an identity transform. Match
// the card's pan and scale, as for lifecycle Create labels.
f.with_clip(clip, |label| {
label.translate(self.camera_pan);
label.scale(self.scale);
label.fill_text(Text {
content: short(&b.title, ((b.rect.width - 25.) / 7.) as usize),
position: Point::new(b.rect.x + 12., b.rect.y + 12.),
size: 13.into(),
color: if b.id == self.selected {
style::TEAL
} else {
style::INK
},
..Default::default()
});
if !b.detail.is_empty() {
label.fill_text(Text {
content: short(&b.detail, ((b.rect.width - 25.) / 6.) as usize),
position: Point::new(b.rect.x + 12., b.rect.y + 39.),
size: 11.into(),
color: style::MUTED,
..Default::default()
});
}
f.fill_text(Text {
content: short(&b.title, ((b.rect.width - 25.) / 7.) as usize),
position: Point::new(b.rect.x + 12., b.rect.y + 12.),
size: 13.into(),
color: if b.id == self.selected {
style::TEAL
} else {
style::INK
},
..Default::default()
});
if !b.detail.is_empty() {
f.fill_text(Text {
content: short(&b.detail, ((b.rect.width - 25.) / 6.) as usize),
position: Point::new(b.rect.x + 12., b.rect.y + 39.),
size: 11.into(),
color: style::MUTED,
..Default::default()
});
}
}
@@ -2274,8 +2140,6 @@ impl canvas::Program<Message> for Scene {
..Default::default()
});
}
self.lifecycle
.draw_markers(&mut f, self.selected, self.scale, self.camera_pan);
if let Some((context, tool, editable)) = self.interaction {
let active = editable && state.context == Some(context) && state.tool == tool;
let point = cursor.position_in(bounds).map(|p| {
@@ -17,7 +17,6 @@ pub fn keyboard_enabled(app: &crate::app::App) -> bool {
&& !app.delete_pending
&& app.pending.is_none()
&& app.model_menu.is_none()
&& app.diagram_usages.is_none()
&& !app.reference_input_active()
}
+1 -6
View File
@@ -694,9 +694,7 @@ fn picker_view<'a, R: iced::advanced::text::Renderer + 'a>(
Picker::Owner => d.owner,
Picker::Context => d.context,
};
let staged_owner = picker == Picker::Owner && d.source.label(selected).is_some();
let title = match picker {
Picker::Owner if staged_owner => "Or choose an existing participant",
Picker::Owner => "Owned by participant",
Picker::Context => "Scenario context · optional",
};
@@ -707,16 +705,13 @@ fn picker_view<'a, R: iced::advanced::text::Renderer + 'a>(
.padding(6)
]
.spacing(5);
if let Some(id) = selected
&& !staged_owner
{
if let Some(id) = selected {
out = out.push(text(format!("Selected: {}", reference_label(p, id))).size(12));
} else if picker == Picker::Context {
out = out.push(text("No context selected").size(12));
}
if options.is_empty() {
out = out.push(text(match picker {
Picker::Owner if staged_owner => "No existing participants match this search. The new owner above remains selected.",
Picker::Owner => "No matching participant. Refine the search or choose Create new owner.",
Picker::Context => "No matching context. Refine the search, or leave this optional reference empty.",
}).size(12));
@@ -5,7 +5,6 @@ use super::*;
use iced::widget::{Column, column, text_input};
use std::{cell::RefCell, collections::BTreeSet};
pub(crate) mod focus;
mod usage;
mod workspace;
pub(crate) use workspace::NAME_INPUT;
pub use workspace::{Shelf, view};
@@ -1,207 +0,0 @@
//! Navigation is derived from the same opaque-reference scene that is painted.
use super::*;
use crate::diagram_usage::{Surface, Target, Usage};
/// The renderer collapses whitespace before shortening. Require at least one
/// actual character of this field, rather than an ellipsis at its start.
fn label_field_visible(full: &str, prefix: &str, value: &str) -> bool {
if value.trim().is_empty() {
return false;
}
let normalized = full.split_whitespace().collect::<Vec<_>>().join(" ");
let normalized_prefix = prefix.split_whitespace().collect::<Vec<_>>().join(" ");
let start = normalized_prefix.len()
+ usize::from(prefix.ends_with(char::is_whitespace) && !normalized_prefix.is_empty());
let painted = crate::views::short(full, 32);
let retained = normalized
.chars()
.zip(painted.chars())
.take_while(|(a, b)| a == b)
.map(|(c, _)| c.len_utf8())
.sum::<usize>();
start < retained
}
fn usages(p: &Project, owner: Id, subject: Id, scene: &Scene) -> Vec<Usage> {
let mut result = Vec::new();
let mut add = |id, bounds, role: &str| {
// Activation bars share the occurrence identity with a labelled message;
// they must not inflate its target count.
if !result
.iter()
.any(|u: &Usage| u.target == Target::ScenarioObject(id))
{
result.push(Usage {
subject,
surface: Surface::Scenario(owner),
target: Target::ScenarioObject(id),
role: role.into(),
bounds,
});
}
};
for item in scene.boxes.iter().filter(|item| !item.title.is_empty()) {
let Some(element) = p.elements.get(&item.id) else {
continue;
};
if subject == item.id {
// A fragment's selectable header is useful even when its frame is
// much larger than the viewport.
let mut bounds = item.rect;
if item.marker == Some(Kind::Occurrence) {
bounds.height = bounds.height.min(38.);
}
add(item.id, bounds, "scenario object");
}
let represented = match element.shared() {
Some(SharedBody::Lifeline { represented }) => represented.map(|id| (id, "lifeline")),
Some(SharedBody::Occurrence { body, .. }) => match body {
OccurrenceBody::Action { action, .. } => action.map(|id| (id, "action occurrence")),
OccurrenceBody::State { state, .. } => state.map(|id| (id, "state observation")),
OccurrenceBody::SequenceReference { sequence } => {
sequence.map(|id| (id, "process reference"))
}
OccurrenceBody::ScenarioUse { scenario, .. } => {
scenario.map(|id| (id, "scenario reference"))
}
// An incomplete message fallback box only paints the occurrence
// name and a repair hint, not its exchange or operation.
_ => None,
},
_ => None,
};
if let Some((id, role)) = represented.filter(|(id, _)| *id == subject) {
let _ = id;
add(item.id, item.rect, role);
}
}
for line in scene.lines.iter().filter(|line| !line.label.is_empty()) {
let Some(element) = p.elements.get(&line.id) else {
continue;
};
let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { exchange, .. },
..
}) = element.shared()
else {
continue;
};
let bounds = line.label_bounds();
if subject == line.id || *exchange == Some(subject) {
add(line.id, bounds, "message occurrence");
}
// Replies derive their operation from the exact call, matching the
// operation label formatter rather than scanning raw reference fields.
if let Ok(operations::OperationResolution::Selected(operation)) =
operations::resolve(p, line.id)
&& let Some(label) = crate::data_values::operation_label(p, element)
&& let Some(prefix) = line.label.strip_suffix(&label)
{
let allocation = &p.relations[&operation.allocation];
let operation_prefix = if matches!(
element.shared(),
Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
message_kind: MessageKind::Reply,
..
},
..
})
) {
"Reply operation from Call: "
} else {
"Operation: "
};
let fields = [
(allocation.source(), format!("{prefix}{operation_prefix}")),
(
allocation.target(),
format!(
"{prefix}{operation_prefix}{} / ",
p.named(allocation.source())
),
),
(
allocation.id,
format!(
"{prefix}{operation_prefix}{} / {} · ",
p.named(allocation.source()),
p.named(allocation.target())
),
),
];
for (id, prefix) in fields {
if id == subject && label_field_visible(&line.label, &prefix, p.named(id)) {
add(line.id, bounds, "operation label");
}
}
}
}
if subject == owner {
result.insert(
0,
Usage {
subject,
surface: Surface::Scenario(owner),
target: Target::Whole,
role: "scenario".into(),
bounds: Rectangle::new(Point::ORIGIN, scene.size),
},
);
}
result
}
impl State {
pub(crate) fn diagram_usages(&self, p: &Project, owner: Id, subject: Id) -> Vec<Usage> {
if !p
.elements
.get(&owner)
.is_some_and(|e| e.kind() == Kind::Scenario)
{
return vec![];
}
usages(p, owner, subject, &Scene::sequence(p, owner, subject))
}
pub(crate) fn reveal_usage(
&mut self,
p: &Project,
document: Id,
owner: Id,
target: &Target,
) -> bool {
if self.draft.is_some()
|| !p
.elements
.get(&owner)
.is_some_and(|e| e.kind() == Kind::Scenario)
{
return false;
}
let id = match target {
Target::Whole => owner,
Target::ScenarioObject(id) => *id,
_ => return false,
};
let Some(usage) = self
.diagram_usages(p, owner, id)
.into_iter()
.find(|u| &u.target == target)
else {
return false;
};
// Preserve an existing mounted viewport across enter's owner reset.
let viewport = self.presentation.viewport.unwrap_or(Size::new(500., 300.));
self.enter(document, owner);
self.presentation.viewport = Some(viewport);
self.canvas_tool = Some((owner, CanvasTool::Select));
let (zoom, pan) = crate::diagram_usage::camera_for(target, usage.bounds, viewport);
self.presentation.zoom(Some(zoom));
self.presentation.pan = pan;
true
}
}
#[cfg(test)]
mod tests;
@@ -1,276 +0,0 @@
use super::*;
fn add_occurrence(p: &mut Project, owner: Id, name: &str, body: OccurrenceBody) -> Id {
let layer = p.elements[&owner].layer();
let id = p
.add_element(Kind::Occurrence, layer, name, Some(owner))
.unwrap();
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::Occurrence {
body,
precondition: String::new(),
postcondition: String::new(),
};
if let Some(steps) = p.elements.get_mut(&owner).unwrap().steps_mut() {
if !steps.contains(&id) {
steps.push(id);
}
}
id
}
fn targets(state: &State, p: &Project, owner: Id, subject: Id) -> BTreeSet<Id> {
state
.diagram_usages(p, owner, subject)
.into_iter()
.filter_map(|u| match u.target {
Target::ScenarioObject(id) => Some(id),
_ => None,
})
.collect()
}
#[test]
fn scenario_usage_counts_nested_occurrences_and_lifelines_but_keeps_reuse_opaque() {
for (layer, work_kind, participant_kind) in [
(Layer::Oa, Kind::Activity, Kind::Entity),
(Layer::Sa, Kind::Function, Kind::SystemActor),
] {
let mut p = Project::empty();
let owner = p
.add_element(Kind::Scenario, layer, "Caller", None)
.unwrap();
let other = p
.add_element(Kind::Scenario, layer, "Definition", None)
.unwrap();
let work = p.add_element(work_kind, layer, "Respond", None).unwrap();
let unused = p.add_element(work_kind, layer, "Respond", None).unwrap();
let participant = p
.add_element(participant_kind, layer, "Operator", None)
.unwrap();
let lanes = ["First role", "Second role"].map(|name| {
let id = p
.add_element(Kind::Lifeline, layer, name, Some(owner))
.unwrap();
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::Lifeline {
represented: Some(participant),
};
id
});
let first = add_occurrence(
&mut p,
owner,
"First action",
OccurrenceBody::Action {
action: Some(work),
lifeline: Some(lanes[0]),
},
);
let fragment = add_occurrence(
&mut p,
owner,
"Decision",
OccurrenceBody::Fragment {
operator: FragmentOperator::Alternative,
branches: vec![],
},
);
let branch = add_occurrence(
&mut p,
fragment,
"When ready",
OccurrenceBody::Branch {
guard: "ready".into(),
occurrences: vec![],
},
);
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Fragment { branches, .. },
..
}) = p.elements.get_mut(&fragment).unwrap().shared_mut()
{
branches.push(branch);
}
let nested = add_occurrence(
&mut p,
branch,
"Again",
OccurrenceBody::Action {
action: Some(work),
lifeline: Some(lanes[1]),
},
);
let inside = add_occurrence(
&mut p,
other,
"Hidden inside definition",
OccurrenceBody::Action {
action: Some(unused),
lifeline: None,
},
);
let use_a = add_occurrence(
&mut p,
owner,
"Use A",
OccurrenceBody::ScenarioUse {
scenario: Some(other),
bindings: vec![],
},
);
let use_b = add_occurrence(
&mut p,
owner,
"Use B",
OccurrenceBody::ScenarioUse {
scenario: Some(other),
bindings: vec![],
},
);
let before = p.clone();
let state = State::default();
assert_eq!(
targets(&state, &p, owner, work),
BTreeSet::from([first, nested])
);
assert_eq!(
targets(&state, &p, owner, participant),
BTreeSet::from(lanes)
);
assert_eq!(
targets(&state, &p, owner, other),
BTreeSet::from([use_a, use_b])
);
assert!(targets(&state, &p, owner, unused).is_empty());
assert!(targets(&state, &p, owner, inside).is_empty());
assert_eq!(targets(&state, &p, owner, branch), BTreeSet::from([branch]));
assert_eq!(
state.diagram_usages(&p, owner, owner)[0].target,
Target::Whole
);
assert_eq!(p, before);
}
}
#[test]
fn scenario_usage_keeps_repeated_messages_and_reveal_is_read_only_and_revalidated() {
let f = super::super::direct_tests::fixture();
let mut p = f.project;
let mut state = State::default();
assert_eq!(
targets(&state, &p, f.owner, f.exchange),
BTreeSet::from([f.call, f.reply])
);
let before = p.clone();
let target = Target::ScenarioObject(f.reply);
state.viewport(Size::new(900., 500.));
assert!(state.reveal_usage(&p, Id::new_v4(), f.owner, &target));
let usage = state
.diagram_usages(&p, f.owner, f.reply)
.into_iter()
.find(|u| u.target == target)
.unwrap();
let zoom = state
.presentation
.scale(Scene::sequence(&p, f.owner, f.reply).size);
let centered = Point::new(
usage.bounds.center_x() * zoom,
usage.bounds.center_y() * zoom,
) + state.presentation.pan;
assert!((centered.x - 450.).abs() < 0.01 && (centered.y - 250.).abs() < 0.01);
assert!(zoom >= 0.5);
assert_eq!(p, before);
// Keeping an orphan semantic occurrence does not keep its painted target.
p.elements
.get_mut(&f.owner)
.unwrap()
.steps_mut()
.unwrap()
.retain(|id| *id != f.reply);
let camera = state.camera_boundary();
assert!(!state.reveal_usage(&p, Id::new_v4(), f.owner, &target));
assert!(camera == state.camera_boundary());
assert!(!state.reveal_usage(&p, Id::new_v4(), f.owner, &Target::Edge(f.exchange)));
// A message whose endpoints are incomplete paints only its repair box.
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { receiver, .. },
..
}) = p.elements.get_mut(&f.call).unwrap().shared_mut()
{
*receiver = None;
}
assert!(targets(&state, &p, f.owner, f.exchange).is_empty());
assert_eq!(
targets(&state, &p, f.owner, f.call),
BTreeSet::from([f.call])
);
}
#[test]
fn scenario_operation_label_membership_excludes_ellipsis_only_and_normalizes_whitespace() {
assert!(label_field_visible(
"1. call · X · Operation: I / O",
"1. call · X · Operation: ",
"I"
));
assert!(!label_field_visible(
"1234567890123456789012345678901Ixyz",
"1234567890123456789012345678901",
"Ixyz"
));
assert!(!label_field_visible(
"A very long occurrence label · Operation: I",
"A very long occurrence label · Operation: ",
"I"
));
assert!(label_field_visible(
"call\n\t· Operation: 界",
"call\n\t· Operation: ",
"界"
));
assert!(!label_field_visible("Operation: ", "Operation: ", ""));
}
#[test]
fn scenario_usage_only_reports_the_resolved_operation_fields_actually_in_the_label() {
let mut p = persistence::decode(include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../harness/fixtures/interface-operation-probe/output/boundary-only.json"
)))
.unwrap();
let id = |n| Id::parse_str(&format!("52060906-0000-4000-8000-{n:012x}")).unwrap();
let (owner, call, exchange, allocation) = (id(40), id(43), id(34), id(30));
let (interface, item) = (
p.relations[&allocation].source(),
p.relations[&allocation].target(),
);
for (id, name) in [(call, "x"), (interface, "I"), (item, "O")] {
p.elements.get_mut(&id).unwrap().name = name.into();
}
p.relations.get_mut(&exchange).unwrap().name = "x".into();
p.relations.get_mut(&allocation).unwrap().name = "A".into();
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { operation, .. },
..
}) = p.elements.get_mut(&call).unwrap().shared_mut()
{
*operation = Some(OperationUse {
allocation: Some(allocation),
});
}
assert!(matches!(
operations::resolve(&p, call),
Ok(operations::OperationResolution::Selected(_))
));
let state = State::default();
let before = p.clone();
assert_eq!(
targets(&state, &p, owner, interface),
BTreeSet::from([call])
);
assert_eq!(targets(&state, &p, owner, item), BTreeSet::from([call]));
assert!(targets(&state, &p, owner, allocation).is_empty());
assert_eq!(p, before);
p.elements.get_mut(&call).unwrap().name = "This occurrence has a deliberately long name".into();
assert!(targets(&state, &p, owner, interface).is_empty());
assert!(targets(&state, &p, owner, item).is_empty());
}
@@ -2,8 +2,6 @@
use oa_core::{FragmentOperator, Id, Kind, MessageKind, OccurrenceBody, Project, SharedBody};
use std::collections::{BTreeMap, BTreeSet};
pub(super) mod render;
/// Maps already recorded by the sequence renderer. Rows carry their owning sequence.
pub(crate) struct Geometry<'a> {
pub rows: &'a BTreeMap<Id, (Id, f32)>,
@@ -1,392 +0,0 @@
//! Scene bridge for local lifetime geometry; no authoring or model mutations.
use super::{Geometry, LaneLifetime, Life, Marker, MarkerKind, Span, project_lifetimes};
use crate::{behavior::Line, style, views::short};
use iced::{
Color, Point, Rectangle, Size,
widget::canvas::{self, Frame, Path, Stroke, Text},
};
use oa_core::{Id, OccurrenceBody, Project, SharedBody};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq)]
struct EventMarker {
event: Marker,
lifeline: Id,
center: Point,
capsule: Rectangle,
name: String,
sender_x: Option<f32>,
}
#[derive(Debug, Default, Clone, PartialEq)]
pub(in crate::behavior) struct Rendering {
// Complete rendering positions, including warning-admitted unassigned lanes.
// Scene.lanes independently retains the existing authoring eligibility rule.
lanes: BTreeMap<Id, f32>,
span: Option<Span>,
lifetimes: Vec<LaneLifetime>,
markers: Vec<EventMarker>,
}
impl Rendering {
pub(in crate::behavior) fn new(
project: &Project,
owner: Id,
lanes: &BTreeMap<Id, f32>,
rows: &BTreeMap<Id, (Id, f32)>,
insertion_scopes: &BTreeMap<Id, (f32, f32)>,
height: f32,
) -> Self {
let span = Span {
start: 85.,
end: height - 20.,
};
if !span.valid() {
return Self::default();
}
// Insertion scopes deliberately start later and end earlier. Empty and
// Create-only scenarios still have the full visible lifetime extent.
let mut scopes = insertion_scopes.clone();
for (scope, (start, end)) in &mut scopes {
if *scope != owner && *start == *end && start.is_finite() {
// An empty operand has 42 px between its insertion axis and
// frame end. Match the existing 26 px open-activation allowance.
*end = *start + 26.;
}
}
scopes.insert(owner, (span.start, span.end));
let lifetimes = project_lifetimes(
project,
owner,
&Geometry {
rows,
scopes: &scopes,
},
);
let lanes: BTreeMap<_, _> = lanes
.iter()
.filter(|(_, x)| x.is_finite())
.map(|(id, x)| (*id, *x))
.collect();
let mut markers = Vec::new();
for lane in &lifetimes {
let Some(&x) = lanes.get(&lane.lifeline) else {
continue;
};
for event in &lane.markers {
let sender_x = project
.elements
.get(&event.occurrence)
.and_then(|e| e.shared())
.and_then(|body| match body {
SharedBody::Occurrence {
body:
OccurrenceBody::Exchange {
sender: Some(sender),
..
},
..
} => lanes.get(sender).copied(),
_ => None,
});
markers.push(EventMarker {
event: *event,
lifeline: lane.lifeline,
center: Point::new(x, event.y),
capsule: Rectangle::new(
Point::new(x - 70., event.y - 14.),
Size::new(140., 28.),
),
name: project.named(lane.lifeline).to_owned(),
sender_x,
});
}
}
Self {
lanes,
span: Some(span),
lifetimes,
markers,
}
}
pub(in crate::behavior) fn align_messages(&self, lines: &mut [Line]) {
for marker in &self.markers {
let Some(sender) = marker.sender_x else {
continue;
};
let Some(line) = lines
.iter_mut()
.find(|line| line.id == marker.event.occurrence)
else {
continue;
};
let x = marker.center.x;
let y = marker.center.y;
let self_message = sender == x;
let end_x = match marker.event.kind {
MarkerKind::Birth if sender < x => marker.capsule.x,
MarkerKind::Birth => marker.capsule.x + marker.capsule.width,
MarkerKind::Death => x,
};
line.points = if self_message {
// The receiver is on the recorded occurrence row, including self
// lifecycle events. The elbow stays outside the birth capsule.
let elbow = x + 112.;
line.label_at = Point::new(x + 12., y - 52.);
vec![
Point::new(x, y - 24.),
Point::new(elbow, y - 24.),
Point::new(elbow, y),
Point::new(end_x, y),
]
} else {
if marker.event.kind == MarkerKind::Birth {
// Keep the label above the capsule, including right-to-left
// messages whose existing label starts beside the receiver.
line.label_at.y = y - 40.;
}
vec![Point::new(sender, y), Point::new(end_x, y)]
};
}
}
pub(in crate::behavior) fn alive_spans(
&self,
lifeline: Id,
scope: Id,
top: f32,
bottom: f32,
) -> Vec<Span> {
if !top.is_finite() || !bottom.is_finite() || bottom <= top {
return vec![];
}
self.lifetimes
.iter()
.find(|lane| lane.lifeline == lifeline)
.into_iter()
.flat_map(|lane| &lane.intervals)
.filter(|interval| interval.scope == scope && interval.life == Life::Alive)
.filter_map(|interval| {
let start = top.max(interval.span.start);
let end = bottom.min(interval.span.end);
(start < end).then_some(Span { start, end })
})
.collect()
}
pub(in crate::behavior) fn marker_at(&self, point: Point) -> Option<Id> {
self.markers
.iter()
.rev()
.find(|marker| match marker.event.kind {
MarkerKind::Birth => marker.capsule.contains(point),
MarkerKind::Death => marker_distance(marker, point) <= 1.25,
})
.map(|marker| marker.event.occurrence)
}
pub(in crate::behavior) fn nearest_marker(&self, point: Point) -> Option<(Id, f32)> {
if !point.x.is_finite() || !point.y.is_finite() {
return None;
}
// Exact visible shapes are tested first by Scene. A low-zoom tolerance
// must not outrank another marker's actual capsule, a header, or a label.
self.markers
.iter()
.map(|marker| (marker.event.occurrence, marker_distance(marker, point)))
.min_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0)))
}
pub(in crate::behavior) fn lane_at(&self, point: Point, scale: f32) -> Option<Id> {
let span = self.span?;
if !scale.is_finite() || scale <= 0. || point.y < span.start || point.y > span.end {
return None;
}
self.lanes
.iter()
.filter(|(_, x)| (**x - point.x).abs() < 12. / scale)
.min_by(|a, b| (a.1 - point.x).abs().total_cmp(&(b.1 - point.x).abs()))
.map(|(id, _)| *id)
}
pub(in crate::behavior) fn draw_lanes(&self, frame: &mut Frame, selected: Id) {
let Some(span) = self.span else {
return;
};
for (&id, &x) in &self.lanes {
frame.stroke(
&Path::line(Point::new(x, span.start), Point::new(x, span.end)),
Stroke {
line_dash: canvas::LineDash {
segments: &[2., 5.],
offset: 0,
},
..Stroke::default()
.with_width(1.)
.with_color(if id == selected {
Color::from_rgb8(148, 190, 187)
} else {
Color::from_rgb8(214, 222, 222)
})
},
);
}
for lifetime in &self.lifetimes {
let Some(&x) = self.lanes.get(&lifetime.lifeline) else {
continue;
};
for interval in &lifetime.intervals {
match interval.life {
Life::Alive => frame.stroke(
&Path::line(
Point::new(x, interval.span.start),
Point::new(x, interval.span.end),
),
Stroke::default().with_width(2.).with_color(
if lifetime.lifeline == selected {
style::TEAL
} else {
Color::from_rgb8(91, 113, 113)
},
),
),
Life::Unresolved if interval.span.end - interval.span.start >= 16. => {
frame.fill_text(Text {
content: "?".into(),
position: Point::new(x + 9., interval.span.start + 2.),
size: 11.into(),
color: style::MUTED,
..Default::default()
});
}
_ => {}
}
}
}
if !self.lanes.is_empty() {
frame.fill_text(Text {
content:
"Dotted: editing guide · Solid: local lifetime · ?: lifetime depends on path"
.into(),
position: Point::new(28., span.end + 4.),
size: 10.into(),
color: style::MUTED,
..Default::default()
});
}
}
pub(in crate::behavior) fn draw_markers(
&self,
frame: &mut Frame,
selected: Id,
scale: f32,
pan: iced::Vector,
) {
for marker in &self.markers {
let color = if selected == marker.event.occurrence || selected == marker.lifeline {
style::TEAL
} else {
style::INK
};
match marker.event.kind {
MarkerKind::Birth => {
let path = Path::rounded_rectangle(
marker.capsule.position(),
marker.capsule.size(),
6.into(),
);
frame.fill(&path, Color::from_rgb8(243, 248, 248));
frame.stroke(
&path,
Stroke::default().with_color(color).with_width(
if selected == marker.event.occurrence {
2.5
} else {
1.5
},
),
);
if let Some(clip) = birth_label_clip(pan, marker.capsule, scale, frame.size()) {
// WGPU clipped frames start with an identity transform;
// neither the parent's pan/scale nor its clip is inherited.
frame.with_clip(clip, |label| {
label.translate(pan);
label.scale(scale);
label.fill_text(Text {
content: short(&marker.name, 18),
position: marker.capsule.position() + iced::Vector::new(8., 6.),
size: 12.into(),
color,
..Default::default()
});
});
}
}
MarkerKind::Death => {
for (a, b) in death_strokes(marker.center) {
frame.stroke(
&Path::line(a, b),
Stroke::default().with_color(color).with_width(2.5),
);
}
}
}
}
}
}
fn birth_label_clip(
pan: iced::Vector,
capsule: Rectangle,
scale: f32,
viewport: Size,
) -> Option<Rectangle> {
if !pan.x.is_finite() || !pan.y.is_finite() || !scale.is_finite() || scale <= 0. {
return None;
}
Rectangle::new(
Point::new(
pan.x + (capsule.x + 8.) * scale,
pan.y + (capsule.y + 4.) * scale,
),
Size::new((capsule.width - 16.) * scale, (capsule.height - 8.) * scale),
)
.intersection(&Rectangle::new(Point::ORIGIN, viewport))
}
fn marker_distance(marker: &EventMarker, point: Point) -> f32 {
match marker.event.kind {
MarkerKind::Birth => {
let dx = (marker.capsule.x - point.x)
.max(point.x - marker.capsule.x - marker.capsule.width)
.max(0.);
let dy = (marker.capsule.y - point.y)
.max(point.y - marker.capsule.y - marker.capsule.height)
.max(0.);
dx.hypot(dy)
}
MarkerKind::Death => death_strokes(marker.center)
.iter()
.map(|(a, b)| crate::diagram::distance_to_segment(point, *a, *b))
.fold(f32::INFINITY, f32::min),
}
}
fn death_strokes(center: Point) -> [(Point, Point); 2] {
[
(
center + iced::Vector::new(-7., -7.),
center + iced::Vector::new(7., 7.),
),
(
center + iced::Vector::new(-7., 7.),
center + iced::Vector::new(7., -7.),
),
]
}
#[cfg(test)]
#[path = "render_tests.rs"]
mod tests;
@@ -1,973 +0,0 @@
use super::*;
use crate::{behavior::Scene, document::Document};
use iced::Size;
use oa_core::*;
struct Fixture {
project: Project,
owner: Id,
sender: Id,
receiver: Id,
work: Id,
exchange: Id,
}
impl Fixture {
fn new(layer: Layer) -> Self {
let mut project = Project::empty();
let kind = if layer == Layer::Oa {
Kind::Activity
} else {
Kind::Function
};
let a = project.add_element(kind, layer, "Request", None).unwrap();
let work = project.add_element(kind, layer, "Provide", None).unwrap();
let exchange = project.relate(
if layer == Layer::Oa {
RelationKind::Interaction
} else {
RelationKind::FunctionalExchange
},
"Service",
a,
work,
);
let owner = project
.add_element(Kind::Scenario, layer, "Lifecycle", None)
.unwrap();
let mut lane = |name, represented| {
let id = project
.add_element(Kind::Lifeline, layer, name, Some(owner))
.unwrap();
*project.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::Lifeline {
represented: Some(represented),
};
id
};
let sender = lane("Requester", a);
let receiver = lane("Provider", work);
Self {
project,
owner,
sender,
receiver,
work,
exchange,
}
}
fn occurrence(&mut self, parent: Id, name: &str, body: OccurrenceBody) -> Id {
let mut element = self
.project
.make_element(
Kind::Occurrence,
self.project.elements[&parent].layer(),
name,
Some(parent),
)
.unwrap();
let id = element.id;
*element.shared_mut().unwrap() = SharedBody::Occurrence {
body,
precondition: String::new(),
postcondition: String::new(),
};
self.project.elements.insert(id, element);
let parent = self.project.elements.get_mut(&parent).unwrap();
if let Some(steps) = parent.steps_mut() {
steps.push(id);
} else if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Fragment { branches, .. },
..
}) = parent.shared_mut()
{
branches.push(id);
} else {
panic!("fixture parent must own ordered occurrences or operands");
}
id
}
fn message(&mut self, parent: Id, kind: MessageKind) -> Id {
self.occurrence(
parent,
"Message",
OccurrenceBody::Exchange {
exchange: Some(self.exchange),
sender: Some(self.sender),
receiver: Some(self.receiver),
message_kind: kind,
operation: None,
reply_to: None,
values: vec![],
},
)
}
fn fragment(&mut self, parent: Id, operator: FragmentOperator) -> Id {
self.occurrence(
parent,
"Paths",
OccurrenceBody::Fragment {
operator,
branches: vec![],
},
)
}
fn branch(&mut self, fragment: Id) -> Id {
self.occurrence(
fragment,
"Operand",
OccurrenceBody::Branch {
guard: "condition".into(),
occurrences: vec![],
},
)
}
fn document(&self) -> Document {
validate_candidate(&self.project).expect("ordinary core admission must succeed");
let mut bundle = source_project::format_bundle(&self.project);
for text in bundle.files.values_mut() {
*text = format!(
"// Retain exact authored CRLF and Unicode Ω\r\n{}",
text.replace('\n', "\r\n")
);
}
let document =
Document::from_bundle(bundle.clone(), source_project::ProjectLimits::default())
.unwrap();
assert_eq!(document.project(), &self.project);
assert_eq!(document.bundle(), &bundle);
document
}
fn scene(&self) -> Scene {
let document = self.document();
let before = document.snapshot();
let scene = Scene::sequence(document.project(), self.owner, self.owner);
assert_eq!(document.project(), &before.decoded.project);
assert_eq!(document.bundle(), &before.bundle);
assert_eq!(document.revision(), 0);
assert!(!document.can_undo() && !document.can_redo() && !document.dirty());
assert_eq!(
scene.lifecycle,
Scene::sequence(document.project(), self.owner, self.owner).lifecycle
);
assert!(
scene
.lines
.iter()
.flat_map(|line| &line.points)
.all(|p| p.x.is_finite() && p.y.is_finite())
);
scene
}
}
fn intervals(scene: &Scene, lifeline: Id, scope: Id) -> Vec<(f32, f32, Life)> {
scene
.lifecycle
.lifetimes
.iter()
.find(|lane| lane.lifeline == lifeline)
.unwrap()
.intervals
.iter()
.filter(|i| i.scope == scope)
.map(|i| (i.span.start, i.span.end, i.life))
.collect()
}
#[test]
fn real_scene_long_header_title_and_detail_keep_names_and_have_bounded_clips() {
for layer in [Layer::Oa, Layer::Sa] {
for name in [
"W".repeat(18),
"界".repeat(24),
"e\u{301}".repeat(24),
"👩\u{200d}🔧".repeat(12),
] {
let mut f = Fixture::new(layer);
f.project.elements.get_mut(&f.receiver).unwrap().name = name.clone();
f.project.elements.get_mut(&f.work).unwrap().name = name.clone();
let scene = f.scene();
let header = scene.boxes.iter().find(|b| b.id == f.receiver).unwrap();
assert_eq!(header.title, format!("Lane · {name}"));
assert_eq!(header.detail, name);
assert_eq!(header.rect.size(), Size::new(204., 70.));
assert_eq!(scene.hit(header.rect.center()), Some(f.receiver));
// Scroll offset is handled by the existing outer canvas/scrollable;
// these are the local drawing frame's coordinates, not screen input.
for scale in [0.05, 0.5, 0.512, 0.64, 0.8, 1., 1.953125, 2.] {
let clip = crate::behavior::box_text_clip(
iced::Vector::ZERO,
header.rect,
scale,
Size::new(2000., 2000.),
)
.unwrap();
let world = Rectangle::new(
Point::new(clip.x / scale, clip.y / scale),
Size::new(clip.width / scale, clip.height / scale),
);
assert!((world.x - header.rect.x - 10.).abs() < 0.001);
assert!((world.y - header.rect.y - 8.).abs() < 0.001);
assert!((world.width - 184.).abs() < 0.001);
assert!((world.height - 54.).abs() < 0.001);
assert!(header.rect.contains(world.position()));
assert!(
header
.rect
.contains(Point::new(world.x + world.width, world.y + world.height,))
);
}
}
}
}
#[test]
fn box_text_clip_intersects_parent_viewport_and_rejects_empty_interiors() {
use crate::behavior::box_text_clip;
let card = Rectangle::new(Point::new(100., 200.), Size::new(204., 70.));
assert_eq!(
box_text_clip(iced::Vector::ZERO, card, 2., Size::new(300., 500.)),
Some(Rectangle::new(Point::new(220., 416.), Size::new(80., 84.)))
);
assert_eq!(
box_text_clip(
iced::Vector::ZERO,
Rectangle::new(Point::new(-20., -10.), card.size()),
2.,
Size::new(300., 500.),
),
Some(Rectangle::new(Point::ORIGIN, Size::new(300., 104.)))
);
for viewport in [Size::new(200., 500.), Size::new(300., 400.), Size::ZERO] {
assert_eq!(box_text_clip(iced::Vector::ZERO, card, 2., viewport), None);
}
for scale in [0., -1., f32::NAN, f32::INFINITY] {
assert_eq!(
box_text_clip(iced::Vector::ZERO, card, scale, Size::new(1000., 1000.)),
None
);
}
for size in [Size::new(20., 70.), Size::new(204., 16.), Size::ZERO] {
assert_eq!(
box_text_clip(
iced::Vector::ZERO,
Rectangle::new(Point::ORIGIN, size),
1.,
card.size()
),
None
);
}
}
#[test]
fn real_scene_wide_latin_header_exceeds_old_character_budget() {
use iced::advanced::text::{self, Paragraph as _};
let mut f = Fixture::new(Layer::Oa);
f.project.elements.get_mut(&f.receiver).unwrap().name = "W".repeat(18);
f.project.elements.get_mut(&f.work).unwrap().name = "W".repeat(24);
let scene = f.scene();
let header = scene.boxes.iter().find(|b| b.id == f.receiver).unwrap();
for (content, size, divisor) in [(&header.title, 13., 7.), (&header.detail, 11., 6.)] {
let label = iced::widget::canvas::Text {
content: crate::views::short(content, ((header.rect.width - 25.) / divisor) as usize),
size: size.into(),
..Default::default()
};
// Use the same real paragraph/font/shaping defaults as canvas Text.
// The native defect survives short(): glyph width, not scalar count,
// is what exceeds the card. This is a font witness, not a pixel gate.
let paragraph = <iced::Renderer as text::Renderer>::Paragraph::with_text(text::Text {
content: label.content.as_str(),
bounds: Size::INFINITE,
size: label.size,
line_height: label.line_height,
font: label.font,
align_x: label.align_x,
align_y: label.align_y,
shaping: label.shaping,
wrapping: text::Wrapping::default(),
});
let old_available = header.rect.width - 12.;
assert!(
paragraph.min_width() > old_available,
"wide glyph fixture must overflow the old unbounded card: {} <= {old_available}",
paragraph.min_width()
);
}
}
#[test]
fn birth_label_clip_keeps_padded_world_bounds_at_each_scene_scale() {
let capsule = Rectangle::new(Point::new(100., 200.), Size::new(140., 28.));
for (scale, expected) in [
(
0.05,
Rectangle::new(Point::new(5.4, 10.2), Size::new(6.2, 1.)),
),
(
0.5,
Rectangle::new(Point::new(54., 102.), Size::new(62., 10.)),
),
(
1.,
Rectangle::new(Point::new(108., 204.), Size::new(124., 20.)),
),
(
2.,
Rectangle::new(Point::new(216., 408.), Size::new(248., 40.)),
),
] {
let clip =
birth_label_clip(iced::Vector::ZERO, capsule, scale, Size::new(1000., 1000.)).unwrap();
for (actual, expected) in [
(clip.x, expected.x),
(clip.y, expected.y),
(clip.width, expected.width),
(clip.height, expected.height),
] {
assert!((actual - expected).abs() < 0.0001);
}
assert!(capsule.contains(Point::new(clip.x / scale, clip.y / scale)));
assert!(capsule.contains(Point::new(
(clip.x + clip.width) / scale,
(clip.y + clip.height) / scale,
)));
}
}
#[test]
fn birth_label_clip_preserves_parent_viewport_bounds() {
let capsule = Rectangle::new(Point::new(100., 200.), Size::new(140., 28.));
assert_eq!(
birth_label_clip(iced::Vector::ZERO, capsule, 2., Size::new(300., 420.)),
Some(Rectangle::new(Point::new(216., 408.), Size::new(84., 12.)))
);
let crossing_origin = Rectangle::new(Point::new(-20., -10.), Size::new(140., 28.));
assert_eq!(
birth_label_clip(
iced::Vector::ZERO,
crossing_origin,
2.,
Size::new(300., 420.)
),
Some(Rectangle::new(Point::ORIGIN, Size::new(224., 28.)))
);
for viewport in [Size::new(200., 420.), Size::new(300., 400.), Size::ZERO] {
assert_eq!(
birth_label_clip(iced::Vector::ZERO, capsule, 2., viewport),
None
);
}
for scale in [0., -1., f32::NAN, f32::INFINITY] {
assert_eq!(
birth_label_clip(iced::Vector::ZERO, capsule, scale, Size::new(1000., 1000.)),
None
);
}
}
#[test]
fn real_scene_empty_and_create_only_use_visible_root_extents_not_insertion_bounds() {
for layer in [Layer::Oa, Layer::Sa] {
let mut f = Fixture::new(layer);
let empty = f.scene();
assert_eq!(empty.sequence_bounds[&f.owner], (106., 106.));
assert_eq!(
intervals(&empty, f.receiver, f.owner),
vec![(85., empty.size.height - 20., Life::Alive)]
);
assert!(empty.lines.is_empty(), "lane guides are not message lines");
let create = f.message(f.owner, MessageKind::Create);
let scene = f.scene();
let birth = scene.rows[&create].1;
assert_eq!(birth, 148.);
assert_eq!(scene.sequence_bounds[&f.owner], (106., 198.));
assert_eq!(
intervals(&scene, f.receiver, f.owner),
vec![
(85., birth, Life::Absent),
(birth, scene.size.height - 20., Life::Alive),
]
);
assert_eq!(
intervals(&scene, f.sender, f.owner),
vec![(85., scene.size.height - 20., Life::Alive)]
);
assert_eq!(scene.slots[0].y, 106.);
assert_eq!(
scene.lane_at(Point::new(scene.lanes[&f.receiver], 90.)),
Some(f.receiver)
);
}
}
#[test]
fn real_scene_birth_death_markers_align_endpoints_and_win_selection_without_mutating_source() {
for layer in [Layer::Oa, Layer::Sa] {
let mut f = Fixture::new(layer);
let create = f.message(f.owner, MessageKind::Create);
f.occurrence(
f.owner,
"Work",
OccurrenceBody::Action {
action: Some(f.work),
lifeline: Some(f.receiver),
},
);
let delete = f.message(f.owner, MessageKind::Delete);
let mut scene = f.scene();
let birth = scene.rows[&create].1;
let death = scene.rows[&delete].1;
assert_eq!(
intervals(&scene, f.receiver, f.owner),
vec![
(85., birth, Life::Absent),
(birth, death, Life::Alive),
(death, scene.size.height - 20., Life::Absent),
]
);
let capsule = scene
.lifecycle
.markers
.iter()
.find(|m| m.event.occurrence == create)
.unwrap()
.capsule;
let line = scene.lines.iter().find(|l| l.id == create).unwrap();
let expected_x = if scene.lanes[&f.sender] < scene.lanes[&f.receiver] {
capsule.x
} else {
capsule.x + capsule.width
};
assert_eq!(line.points.last(), Some(&Point::new(expected_x, birth)));
assert!(
line.label_at.y + 22. < capsule.y,
"message caption clears birth capsule"
);
let line = scene.lines.iter().find(|l| l.id == delete).unwrap();
assert_eq!(
line.points.last(),
Some(&Point::new(scene.lanes[&f.receiver], death))
);
for scale in [0.5, 1., 2.] {
scene.scale = scale;
assert_eq!(
scene.hit(Point::new(scene.lanes[&f.receiver], birth)),
Some(create)
);
assert_eq!(
scene.hit(Point::new(scene.lanes[&f.receiver], death)),
Some(delete)
);
assert_eq!(
scene.hit(Point::new(
scene.lanes[&f.receiver],
scene.size.height - 25.
)),
Some(f.receiver)
);
assert_eq!(
scene.hit(Point::new(scene.lanes[&f.receiver], 40.)),
Some(f.receiver)
);
}
}
}
#[test]
fn real_scene_branch_delete_clips_only_its_activation_and_keeps_unanswered_call_visible() {
for layer in [Layer::Oa, Layer::Sa] {
let mut f = Fixture::new(layer);
let call = f.message(f.owner, MessageKind::Call);
let fragment = f.fragment(f.owner, FragmentOperator::Alternative);
let left = f.branch(fragment);
let delete = f.message(left, MessageKind::Delete);
let right = f.branch(fragment);
let scene = f.scene();
let death = scene.rows[&delete].1;
let (left_start, left_end) = scene.sequence_bounds[&left];
let (right_start, _) = scene.sequence_bounds[&right];
let bars: Vec<_> = scene
.boxes
.iter()
.filter(|b| b.id == call && b.rect.width == 8.)
.map(|b| b.rect)
.collect();
assert!(
bars.iter()
.any(|r| r.y == left_start && r.y + r.height == death)
);
assert!(
!bars
.iter()
.any(|r| r.y < left_end && r.y + r.height > death && r.y >= left_start)
);
assert!(
bars.iter().any(|r| r.y == right_start && r.height == 26.),
"empty exclusive sibling retains its own open activation"
);
assert_eq!(
intervals(&scene, f.receiver, right),
vec![(right_start, right_start + 26., Life::Alive)]
);
let frame_end = scene.boxes.iter().find(|b| b.id == fragment).unwrap().rect;
assert!(
!bars.iter().any(|r| r.y >= frame_end.y + frame_end.height),
"uncertain post-fragment lifetime cannot carry a definite activation bar"
);
assert!(
scene
.open_calls
.iter()
.any(|p| p.y < death && p.y > left_start)
);
assert!(scene.open_calls.iter().any(|p| p.y > right_start));
assert_eq!(
intervals(&scene, f.receiver, left),
vec![
(left_start, death, Life::Alive),
(death, left_end, Life::Absent)
]
);
assert_eq!(
intervals(&scene, f.receiver, f.owner).last().unwrap().2,
Life::Unresolved
);
assert!(!f.project.elements.values().any(|e| matches!(
e.shared(),
Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
message_kind: MessageKind::Reply,
..
},
..
})
)));
}
}
#[test]
fn real_scene_unassigned_lanes_and_explicit_incomplete_receiver_keep_real_marker_identity() {
for layer in [Layer::Oa, Layer::Sa] {
let mut f = Fixture::new(layer);
*f.project
.elements
.get_mut(&f.receiver)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Lifeline { represented: None };
let create = f.message(f.owner, MessageKind::Create);
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { exchange, .. },
..
}) = f.project.elements.get_mut(&create).unwrap().shared_mut()
{
*exchange = None;
}
let scene = f.scene();
assert!(
!scene.lanes.contains_key(&f.receiver),
"authoring eligibility remains separate"
);
let x = scene.lifecycle.lanes[&f.receiver];
assert_eq!(scene.lifecycle.markers[0].lifeline, f.receiver);
assert_eq!(
scene.hit(Point::new(x, scene.rows[&create].1)),
Some(create)
);
assert_eq!(scene.hit(Point::new(x, 40.)), Some(f.receiver));
assert_eq!(
scene.hit(Point::new(x, scene.size.height - 25.)),
Some(f.receiver)
);
assert_eq!(scene.lane_at(Point::new(x, 90.)), None);
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
receiver, exchange, ..
},
..
}) = f.project.elements.get_mut(&create).unwrap().shared_mut()
{
*receiver = None;
*exchange = Some(f.exchange);
}
let missing = f.scene();
assert!(
missing.lifecycle.markers.is_empty(),
"do not infer receiver from global exchange"
);
}
}
#[test]
fn real_scene_minimum_zoom_marker_halos_do_not_steal_adjacent_capsule_or_header_hits() {
let mut f = Fixture::new(Layer::Sa);
*f.project
.elements
.get_mut(&f.receiver)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Lifeline { represented: None };
let create = f.message(f.owner, MessageKind::Create);
let delete = f.message(f.owner, MessageKind::Delete);
for event in [create, delete] {
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { exchange, .. },
..
}) = f.project.elements.get_mut(&event).unwrap().shared_mut()
{
*exchange = None;
}
}
let mut scene = f.scene();
let x = scene.lifecycle.lanes[&f.receiver];
assert_eq!(scene.rows[&delete].1 - scene.rows[&create].1, 92.);
for scale in [0.05, 0.1, 0.5, 1., 2.] {
scene.scale = scale;
assert_eq!(
scene.hit(Point::new(x, scene.rows[&create].1)),
Some(create)
);
assert_eq!(
scene.hit(Point::new(x, scene.rows[&delete].1)),
Some(delete)
);
assert_eq!(scene.hit(Point::new(x, 40.)), Some(f.receiver));
if scale <= 0.1 {
for offset in [-25., -15., 15., 25.] {
assert_eq!(
scene.hit(Point::new(x, scene.rows[&delete].1 + offset)),
Some(delete),
"a nearby death halo must beat an earlier message's wider tolerance"
);
}
}
}
}
#[test]
fn real_scene_minimum_zoom_near_ordinary_message_wins_over_lifecycle_halos() {
let mut f = Fixture::new(Layer::Sa);
f.message(f.owner, MessageKind::Create);
let ordinary = f.message(f.owner, MessageKind::Asynchronous);
f.message(f.owner, MessageKind::Delete);
let mut scene = f.scene();
let x = (scene.lanes[&f.sender] + scene.lanes[&f.receiver]) / 2.;
for scale in [0.05, 0.1] {
scene.scale = scale;
assert_eq!(
scene.hit(Point::new(x, scene.rows[&ordinary].1 + 2.)),
Some(ordinary)
);
}
}
#[test]
fn real_scene_self_lifecycle_elbows_end_on_recorded_marker_rows() {
for layer in [Layer::Oa, Layer::Sa] {
for kind in [MessageKind::Create, MessageKind::Delete] {
let mut f = Fixture::new(layer);
let event = f.message(f.owner, kind);
if let Some(SharedBody::Occurrence {
body:
OccurrenceBody::Exchange {
exchange, sender, ..
},
..
}) = f.project.elements.get_mut(&event).unwrap().shared_mut()
{
*exchange = None;
*sender = Some(f.receiver);
}
let scene = f.scene();
let marker = &scene.lifecycle.markers[0];
let line = scene.lines.iter().find(|l| l.id == event).unwrap();
assert_eq!(line.points.len(), 4);
assert_eq!(line.points[0].y, marker.center.y - 24.);
assert_eq!(line.points[3].y, marker.center.y);
assert_eq!(
line.points[3].x,
if marker.event.kind == MarkerKind::Birth {
marker.capsule.x + marker.capsule.width
} else {
marker.center.x
}
);
assert!(line.points[1].x > marker.capsule.x + marker.capsule.width);
assert_eq!(scene.hit(marker.center), Some(event));
}
}
}
#[test]
fn real_scene_self_delete_caption_clears_the_preceding_action_box() {
let mut f = Fixture::new(Layer::Sa);
let action = f.occurrence(
f.owner,
"Finish work",
OccurrenceBody::Action {
action: Some(f.work),
lifeline: Some(f.receiver),
},
);
let delete = f.message(f.owner, MessageKind::Delete);
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
exchange, sender, ..
},
..
}) = f.project.elements.get_mut(&delete).unwrap().shared_mut()
{
*exchange = None;
*sender = Some(f.receiver);
}
let scene = f.scene();
let action = scene.boxes.iter().find(|b| b.id == action).unwrap();
let line = scene.lines.iter().find(|l| l.id == delete).unwrap();
assert!(line.label_at.y > action.rect.y + action.rect.height);
assert!(line.label_at.y + 22. < line.points[0].y);
assert_eq!(line.points[3].y, scene.rows[&delete].1);
assert_eq!(
scene
.slots
.iter()
.find(|s| s.slot.before == Some(delete))
.unwrap()
.y,
scene.rows[&delete].1 - 42.
);
}
#[test]
fn real_scene_conditional_repeated_and_parallel_scopes_do_not_claim_definite_continuation() {
for operator in [
FragmentOperator::Alternative,
FragmentOperator::Optional,
FragmentOperator::Loop,
FragmentOperator::Parallel,
] {
let mut f = Fixture::new(Layer::Sa);
let fragment = f.fragment(f.owner, operator);
let first = f.branch(fragment);
let create = f.message(first, MessageKind::Create);
let scene = f.scene();
assert_eq!(scene.lifecycle.markers[0].event.occurrence, create);
assert_eq!(
intervals(&scene, f.receiver, f.owner).first().unwrap().2,
Life::Unresolved
);
assert_eq!(
intervals(&scene, f.receiver, f.owner).last().unwrap().2,
Life::Unresolved
);
assert!(
scene
.lifecycle
.lifetimes
.iter()
.find(|l| l.lifeline == f.sender)
.unwrap()
.intervals
.iter()
.all(|i| i.life == Life::Alive)
);
}
}
#[test]
fn real_scene_lifecycle_edit_undo_redo_restores_exact_source_and_changed_geometry() {
for layer in [Layer::Oa, Layer::Sa] {
let mut f = Fixture::new(layer);
let create = f.message(f.owner, MessageKind::Create);
let mut document = f.document();
let before = document.snapshot();
let geometry = Scene::sequence(document.project(), f.owner, create).lifecycle;
let mut edited = document.project().elements[&create].clone();
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { message_kind, .. },
..
}) = edited.shared_mut()
{
*message_kind = MessageKind::Asynchronous;
}
document
.execute(Command::EditElement(create, edited))
.unwrap();
let after = document.snapshot();
let changed = Scene::sequence(document.project(), f.owner, create).lifecycle;
assert_ne!(geometry, changed);
assert!(changed.markers.is_empty());
assert_ne!(before.bundle, after.bundle);
assert!(document.undo());
assert_eq!(document.project(), &before.decoded.project);
assert_eq!(document.bundle(), &before.bundle);
assert_eq!(
Scene::sequence(document.project(), f.owner, create).lifecycle,
geometry
);
assert!(!document.can_undo() && document.can_redo());
assert!(document.redo());
assert_eq!(document.project(), &after.decoded.project);
assert_eq!(document.bundle(), &after.bundle);
assert_eq!(
Scene::sequence(document.project(), f.owner, create).lifecycle,
changed
);
assert!(!document.can_redo());
}
}
#[test]
fn panned_header_and_create_clips_use_screen_translation_and_actual_viewport() {
use crate::behavior::box_text_clip;
use iced::Vector;
let header = Rectangle::new(Point::new(100., 200.), Size::new(204., 70.));
let capsule = Rectangle::new(header.position(), Size::new(140., 28.));
let rect = |x, y, w, h| Rectangle::new(Point::new(x, y), Size::new(w, h));
for (pan, scale, viewport, header_expected, birth_expected) in [
(
Vector::new(37., -41.),
0.5,
Size::new(300., 400.),
rect(92., 63., 92., 27.),
rect(91., 61., 62., 10.),
),
(
Vector::new(37., -41.),
1.,
Size::new(300., 400.),
rect(147., 167., 153., 54.),
rect(145., 163., 124., 20.),
),
(
Vector::new(37., -41.),
2.,
Size::new(300., 400.),
rect(257., 375., 43., 25.),
rect(253., 367., 47., 33.),
),
(
Vector::new(-200., -400.),
2.,
Size::new(300., 100.),
rect(20., 16., 280., 84.),
rect(16., 8., 248., 40.),
),
(
Vector::new(-237., -411.),
2.,
Size::new(300., 100.),
rect(0., 5., 300., 95.),
rect(0., 0., 227., 37.),
),
] {
assert_eq!(
box_text_clip(pan, header, scale, viewport),
Some(header_expected)
);
assert_eq!(
birth_label_clip(pan, capsule, scale, viewport),
Some(birth_expected)
);
}
for pan in [
Vector::new(1000., 1000.),
Vector::new(-1000., -1000.),
Vector::new(f32::NAN, 0.),
Vector::new(0., f32::INFINITY),
] {
assert_eq!(box_text_clip(pan, header, 2., Size::new(300., 100.)), None);
assert_eq!(
birth_label_clip(pan, capsule, 2., Size::new(300., 100.)),
None
);
}
}
#[test]
fn real_scene_panned_zoomed_program_keeps_header_birth_and_death_hit_identity() {
use crate::{
app::Message,
behavior::{
SequenceInput,
scenario::{CanvasEvent, CanvasTool},
},
};
use iced::{Vector, mouse, widget::canvas};
for layer in [Layer::Oa, Layer::Sa] {
let mut f = Fixture::new(layer);
f.project.elements.get_mut(&f.receiver).unwrap().name = "界".repeat(24);
let create = f.message(f.owner, MessageKind::Create);
let delete = f.message(f.owner, MessageKind::Delete);
let document = f.document();
let before = document.snapshot();
for scale in [0.5, 1., 2.] {
for pan in [Vector::new(35., 40.), Vector::new(-35., -5.)] {
let mut scene = f.scene();
scene.scale = scale;
scene.camera_pan = pan;
let context = crate::behavior::scenario::direct_tests::context(f.owner);
scene.interaction = Some((context, CanvasTool::Select, true));
let header = scene.boxes.iter().find(|b| b.id == f.sender).unwrap();
let targets = [
(f.sender, header.rect.center()),
(
create,
scene
.lifecycle
.markers
.iter()
.find(|m| m.event.occurrence == create)
.unwrap()
.center,
),
(
delete,
scene
.lifecycle
.markers
.iter()
.find(|m| m.event.occurrence == delete)
.unwrap()
.center,
),
];
// Absolute widget origin models the outer layout/scroll translation;
// camera pan remains local screen units and must be subtracted once.
let bounds = Rectangle::new(Point::new(73., 119.), Size::new(2000., 1200.));
for (expected, world) in targets {
let screen =
bounds.position() + pan + Vector::new(world.x * scale, world.y * scale);
assert!(bounds.contains(screen));
let mut state = SequenceInput::default();
let mut published = Vec::new();
for event in [
mouse::Event::CursorMoved { position: screen },
mouse::Event::ButtonPressed(mouse::Button::Left),
mouse::Event::ButtonReleased(mouse::Button::Left),
] {
if let Some(message) = canvas::Program::update(
&scene,
&mut state,
&canvas::Event::Mouse(event),
bounds,
mouse::Cursor::Available(screen),
)
.and_then(|a| a.into_inner().0)
{
published.push(message);
}
}
assert!(
matches!(published.as_slice(), [Message::ScenarioCanvas(CanvasEvent::Select(actual_context, actual))] if *actual_context == context && *actual == expected),
"Pan/zoom must retain the typed hit identity"
);
}
assert_eq!(scene.lifecycle, f.scene().lifecycle);
}
}
assert_eq!(document.project(), &before.decoded.project);
assert_eq!(document.bundle(), &before.bundle);
assert!(!document.can_undo() && !document.dirty());
}
}
+37 -583
View File
@@ -325,73 +325,50 @@ impl State {
) -> Option<UiElement<'a, Event, iced::Theme, R>> {
let d = self.editing.as_ref()?;
let event = move |edit| Event::Edit(d.token, edit);
let kinds = d.scope.kinds(d.layer);
let determined = kinds.len() == 1 && d.kind == kinds.first().copied();
let mut fields = column![
text(if determined {
format!("New {} · {}", kinds[0], d.layer)
} else {
format!("New source · {}", d.layer)
text(format!("New source · {}", d.layer)).size(18),
text(match d.scope {
Scope::Lifeline { owner, viewpoint } =>
format!("For a lifeline in {} · {:?}", p.named(owner), viewpoint),
Scope::Work { owner } => format!("For a contribution in {}", p.named(owner)),
Scope::Machine { .. } => "Owner for the pending state machine".into(),
})
.size(14),
.size(12),
text("The parent form is retained. This source is created only with its consumer.")
.size(12)
]
.spacing(8);
for kind in d.scope.kinds(d.layer) {
fields = fields.push(
button(text(kind.to_string()))
.on_press(event(Edit::Kind(kind)))
.style(if d.kind == Some(kind) {
button::primary
} else {
button::secondary
}),
);
}
fields = fields.push(
text_input("Source name (independent of the consumer name)", &d.name)
.id(NAME_INPUT)
.on_input(move |v| event(Edit::Name(v)))
.size(14)
.padding(6),
]
.spacing(4);
if !determined {
let mut choices = row![].spacing(6);
for kind in kinds {
choices = choices.push(
container(
button(text(kind.to_string()).size(14))
.padding(4)
.on_press(event(Edit::Kind(kind)))
.style(if d.kind == Some(kind) {
button::primary
} else {
button::secondary
}),
)
.id(format!("behavior-source-kind-{kind:?}")),
);
}
fields = fields.push(choices.wrap());
}
.padding(8),
);
fields = fields.push(
container(
text(format!(
"Semantic parent: {}",
d.parent
.as_ref()
.map_or(format!("{} layer root", d.layer), |e| format!(
"{} · {} · @{}",
e.name,
e.kind(),
e.alias
))
))
.size(12),
)
.id("behavior-source-parent"),
text(format!(
"Semantic parent: {}",
d.parent
.as_ref()
.map_or(format!("{} layer root", d.layer), |e| format!(
"{} · {} · @{}",
e.name,
e.kind(),
e.alias
))
))
.size(12),
);
fields = fields
.push(
text(match d.scope {
Scope::Lifeline { owner, viewpoint } => {
format!("For a lifeline in {} · {:?}", p.named(owner), viewpoint)
}
Scope::Work { owner } => format!("For a contribution in {}", p.named(owner)),
Scope::Machine { .. } => "Owner for the pending state machine".into(),
})
.size(12),
)
.push(
text("The parent form is retained. This source is created only with its consumer.")
.size(12),
);
if let Some(kind) = d.kind {
fields = fields.push(button("Use layer root").on_press_maybe(
validation::can_parent(p, kind, d.layer, None).then(|| event(Edit::Parent(None))),
@@ -509,526 +486,3 @@ impl Draft {
Ok(command)
}
}
#[cfg(all(test, debug_assertions))]
mod layout_tests {
use super::*;
use iced::advanced::{Layout, Shell, graphics, layout, renderer, text as shaped, widget};
use iced::{Background, Color, Font, Pixels, Point, Rectangle, Size, Transformation, Vector};
// Use Iced's real paragraph shaping/measurement without a window or GPU.
// The unit renderer's zero-size paragraphs cannot detect this regression.
struct FontLayout;
impl renderer::Renderer for FontLayout {
fn start_layer(&mut self, _: Rectangle) {}
fn end_layer(&mut self) {}
fn start_transformation(&mut self, _: Transformation) {}
fn end_transformation(&mut self) {}
fn reset(&mut self, _: Rectangle) {}
fn fill_quad(&mut self, _: renderer::Quad, _: impl Into<Background>) {}
fn allocate_image(
&mut self,
handle: &iced::advanced::image::Handle,
callback: impl FnOnce(
Result<iced::advanced::image::Allocation, iced::advanced::image::Error>,
) + Send
+ 'static,
) {
renderer::Renderer::allocate_image(&mut (), handle, callback);
}
}
impl shaped::Renderer for FontLayout {
type Font = Font;
type Paragraph = graphics::text::Paragraph;
type Editor = ();
const ICON_FONT: Font = Font::DEFAULT;
const CHECKMARK_ICON: char = '0';
const ARROW_DOWN_ICON: char = '0';
const SCROLL_UP_ICON: char = '0';
const SCROLL_DOWN_ICON: char = '0';
const SCROLL_LEFT_ICON: char = '0';
const SCROLL_RIGHT_ICON: char = '0';
const ICED_LOGO: char = '0';
fn default_font(&self) -> Font {
Font::DEFAULT
}
fn default_size(&self) -> Pixels {
Pixels(16.)
}
fn fill_paragraph(&mut self, _: &Self::Paragraph, _: Point, _: Color, _: Rectangle) {}
fn fill_editor(&mut self, _: &Self::Editor, _: Point, _: Color, _: Rectangle) {}
fn fill_text(&mut self, _: shaped::Text, _: Point, _: Color, _: Rectangle) {}
}
#[derive(Default)]
struct Geometry {
fields: Option<Rectangle>,
content: Option<Rectangle>,
name: Option<Rectangle>,
parent: Option<Rectangle>,
actions: Option<Rectangle>,
kinds: BTreeMap<String, Rectangle>,
text: Vec<(String, Rectangle)>,
focus_name: bool,
}
impl widget::Operation for Geometry {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn widget::Operation)) {
visit(self);
}
fn container(&mut self, id: Option<&widget::Id>, bounds: Rectangle) {
if id == Some(&widget::Id::new("behavior-source-actions")) {
self.actions = Some(bounds);
}
if id == Some(&widget::Id::new("behavior-source-parent")) {
self.parent = Some(bounds);
}
for kind in [
Kind::Entity,
Kind::Actor,
Kind::Role,
Kind::System,
Kind::SystemActor,
Kind::Activity,
Kind::Function,
] {
if id == Some(&widget::Id::from(format!("behavior-source-kind-{kind:?}"))) {
self.kinds.insert(kind.to_string(), bounds);
}
}
}
fn scrollable(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
content: Rectangle,
offset: Vector,
_: &mut dyn widget::operation::Scrollable,
) {
if id == Some(&widget::Id::new("behavior-source-fields")) {
assert_eq!(
offset,
Vector::ZERO,
"Initial fields must be visible without scrolling"
);
self.fields = Some(bounds);
self.content = Some(content);
}
}
fn text_input(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
_: &mut dyn widget::operation::TextInput,
) {
if id == Some(&widget::Id::new(NAME_INPUT)) {
self.name = Some(bounds);
}
}
fn focusable(
&mut self,
id: Option<&widget::Id>,
_: Rectangle,
state: &mut dyn widget::operation::Focusable,
) {
if self.focus_name && id == Some(&widget::Id::new(NAME_INPUT)) {
state.focus();
}
}
fn text(&mut self, _: Option<&widget::Id>, bounds: Rectangle, text: &str) {
self.text.push((text.into(), bounds));
}
}
fn contains(outer: Rectangle, inner: Rectangle) -> bool {
inner.width > 0.
&& inner.height > 0.
&& inner.x >= outer.x - 0.1
&& inner.y >= outer.y - 0.1
&& inner.x + inner.width <= outer.x + outer.width + 0.1
&& inner.y + inner.height <= outer.y + outer.height + 0.1
}
fn host<'a>(
state: &'a State,
p: &'a Project,
caption: &str,
) -> UiElement<'a, Event, iced::Theme, FontLayout> {
iced::widget::column![text(caption.to_owned()).size(12), state.view(p).unwrap()]
.spacing(6)
.height(Fill)
.width(Fill)
.into()
}
fn geometry(
view: &mut UiElement<'_, Event, iced::Theme, FontLayout>,
tree: &mut widget::Tree,
size: Size,
) -> (layout::Node, Geometry) {
let node =
view.as_widget_mut()
.layout(tree, &FontLayout, &layout::Limits::new(Size::ZERO, size));
let mut geometry = Geometry::default();
view.as_widget_mut()
.operate(tree, Layout::new(&node), &FontLayout, &mut geometry);
(node, geometry)
}
fn fixture(layer: Layer, viewpoint: Option<ScenarioViewpoint>, work: bool) -> (Project, State) {
let mut p = Project::empty();
let scope = if work {
let owner = p
.add_element(
if layer == Layer::Oa {
Kind::Process
} else {
Kind::FunctionalChain
},
layer,
"Consumer",
None,
)
.unwrap();
Scope::Work { owner }
} else if let Some(viewpoint) = viewpoint {
let owner = p
.add_element(
Kind::Scenario,
layer,
"Incident coordination with a long contextual heading 雨 Ω",
None,
)
.unwrap();
if let Some(SharedBody::Scenario { viewpoint: v, .. }) =
p.elements.get_mut(&owner).unwrap().shared_mut()
{
*v = viewpoint;
}
Scope::Lifeline { owner, viewpoint }
} else {
Scope::Machine { layer }
};
let mut state = State::default();
let invocation = Id::new_v4();
state
.update(&p, scope, invocation, Event::Open(invocation))
.unwrap();
(p, state)
}
#[test]
fn contextual_source_layout_initial_essentials_fit_short_composed_host_with_real_paragraphs() {
for (layer, viewpoint, work) in [
(
Layer::Oa,
Some(ScenarioViewpoint::OperationalActivity),
false,
),
(Layer::Sa, Some(ScenarioViewpoint::Functional), false),
(
Layer::Oa,
Some(ScenarioViewpoint::ParticipantInteraction),
false,
),
(Layer::Sa, Some(ScenarioViewpoint::BoundaryInterface), false),
(Layer::Oa, None, false),
(Layer::Sa, None, false),
(Layer::Oa, None, true),
(Layer::Sa, None, true),
] {
let (p, state) = fixture(layer, viewpoint, work);
let raw = serde_json::to_value(&state).unwrap();
for width in [340., 500.] {
// The retained caption + 6px gap leaves approximately the observed 194px card.
let size = Size::new(width, 215.);
let mut view = host(&state, &p, "Consumer name: Assessment lifeline");
let mut tree = widget::Tree::new(view.as_widget());
let (_, g) = geometry(&mut view, &mut tree, size);
let fields = g.fields.unwrap();
assert!(
(125. ..=132.).contains(&fields.height),
"Measured field viewport: {fields:?}"
);
assert!(
contains(fields, g.name.unwrap()),
"Name clipped: {layer:?}/{viewpoint:?}/{work}/{width}"
);
assert!(
contains(fields, g.parent.unwrap()),
"Parent clipped: {layer:?}/{viewpoint:?}/{work}/{width}"
);
assert!(contains(
Rectangle::new(Point::ORIGIN, size),
g.actions.unwrap()
));
assert!(fields.y + fields.height <= g.actions.unwrap().y);
let expected = state.editing.as_ref().unwrap().scope.kinds(layer);
assert_eq!(
g.kinds.len(),
if expected.len() == 1 {
0
} else {
expected.len()
}
);
for bounds in g.kinds.values() {
assert!(
contains(fields, *bounds),
"Kind clipped: {bounds:?} in {fields:?}"
);
}
let parent_text = g
.text
.iter()
.find(|(s, _)| s.starts_with("Semantic parent:"))
.unwrap();
assert_eq!(
parent_text.0,
format!("Semantic parent: {layer} layer root")
);
assert!(
parent_text.1.height > 0.,
"Paragraph measurement must not be null"
);
let explanation = g
.text
.iter()
.find(|(s, _)| s.starts_with("The parent form"))
.unwrap();
assert!(explanation.1.y >= g.parent.unwrap().y + g.parent.unwrap().height);
}
assert_eq!(
serde_json::to_value(&state).unwrap(),
raw,
"Layout must not choose a kind or mutate the draft"
);
if state.editing.as_ref().unwrap().scope.kinds(layer).len() == 1 {
let mut incomplete = state.clone();
incomplete.editing.as_mut().unwrap().kind = None;
let mut view = host(&incomplete, &p, "Consumer name: Assessment lifeline");
let mut tree = widget::Tree::new(view.as_widget());
let (_, g) = geometry(&mut view, &mut tree, Size::new(340., 215.));
assert_eq!(
g.kinds.len(),
1,
"An incomplete recovery still needs an explicit repair choice"
);
assert!(contains(
g.fields.unwrap(),
*g.kinds.values().next().unwrap()
));
assert!(contains(g.fields.unwrap(), g.name.unwrap()));
assert_eq!(incomplete.editing.as_ref().unwrap().kind, None);
}
}
}
#[test]
fn contextual_source_layout_long_parent_wraps_after_visible_name_without_losing_raw_data() {
let (mut p, mut state) = fixture(Layer::Oa, None, true);
let parent = p
.add_element(
Kind::Activity,
Layer::Oa,
"Northern operations coordination — exact parent 雨",
None,
)
.unwrap();
let d = state.editing.as_ref().unwrap();
let token = d.token;
let scope = d.scope;
let invocation = Id::new_v4();
state
.update(
&p,
scope,
invocation,
Event::Edit(token, Edit::Parent(Some(parent))),
)
.unwrap();
state
.update(
&p,
scope,
invocation,
Event::Edit(token, Edit::Name(" Distinct source 雨 ".into())),
)
.unwrap();
let raw = serde_json::to_value(&state).unwrap();
for width in [340., 500.] {
let size = Size::new(width, 235.);
let mut view = host(
&state,
&p,
"Consumer name: Coordination with a long independent label 雨 Ω",
);
let mut tree = widget::Tree::new(view.as_widget());
let (_, g) = geometry(&mut view, &mut tree, size);
assert!(contains(g.fields.unwrap(), g.name.unwrap()));
assert!(contains(g.fields.unwrap(), g.parent.unwrap()));
assert!(contains(
Rectangle::new(Point::ORIGIN, size),
g.actions.unwrap()
));
let summary = g
.text
.iter()
.find(|(s, _)| s.starts_with("Semantic parent:"))
.unwrap();
assert!(summary.0.contains(&p.elements[&parent].name));
assert!(summary.0.contains(&p.elements[&parent].alias));
assert!(
summary.1.height > 15.,
"Long parent should exercise real wrapping"
);
}
assert_eq!(serde_json::to_value(&state).unwrap(), raw);
assert_eq!(
state.editing.as_ref().unwrap().name,
" Distinct source 雨 "
);
let (mut p, mut state) = fixture(
Layer::Oa,
Some(ScenarioViewpoint::ParticipantInteraction),
false,
);
let parent = p
.add_element(
Kind::Entity,
Layer::Oa,
// Eight repetitions need not exceed a whole viewport with the
// platform's measured font. Exercise substantial real overflow.
&"Northern operational responsibility 雨 ".repeat(32),
None,
)
.unwrap();
let d = state.editing.as_ref().unwrap();
let token = d.token;
let scope = d.scope;
state
.update(
&p,
scope,
Id::new_v4(),
Event::Edit(token, Edit::Kind(Kind::Actor)),
)
.unwrap();
state
.update(
&p,
scope,
Id::new_v4(),
Event::Edit(token, Edit::Parent(Some(parent))),
)
.unwrap();
let raw = serde_json::to_value(&state).unwrap();
let recovered: State = serde_json::from_value(raw.clone()).unwrap();
let mut view = host(&recovered, &p, "Consumer name: Assessment lifeline");
let mut tree = widget::Tree::new(view.as_widget());
let (_, g) = geometry(&mut view, &mut tree, Size::new(340., 215.));
let fields = g.fields.unwrap();
assert!(contains(fields, g.name.unwrap()));
assert_eq!(g.kinds.len(), 3);
for bounds in g.kinds.values() {
assert!(
contains(fields, *bounds),
"Long parent must not hide a semantic choice"
);
assert!(bounds.y + bounds.height <= g.parent.unwrap().y);
}
// Arbitrary authored detail may scroll, but its label and first line are
// visible after the required kind controls, never in front of them.
let parent_bounds = g.parent.unwrap();
assert!(parent_bounds.y + 16. <= fields.y + fields.height);
assert!(
parent_bounds.height > fields.height,
"Exercise genuinely overflowing parent text: {parent_bounds:?} in {fields:?}"
);
let content = g.content.unwrap();
assert!(
content.height > fields.height && contains(content, parent_bounds),
"Full parent must remain in scrollable content: {parent_bounds:?}, {content:?}, {fields:?}"
);
let summary = g
.text
.iter()
.find(|(s, _)| s.starts_with("Semantic parent:"))
.unwrap();
assert!(summary.0.contains(&p.elements[&parent].name));
assert!(summary.0.contains(&p.elements[&parent].alias));
assert!(contains(
Rectangle::new(Point::ORIGIN, Size::new(340., 215.)),
g.actions.unwrap()
));
assert_eq!(serde_json::to_value(&recovered).unwrap(), raw);
}
#[test]
fn contextual_source_layout_visible_kind_click_keeps_choice_explicit_and_name_input_works() {
let (p, mut state) = fixture(
Layer::Oa,
Some(ScenarioViewpoint::ParticipantInteraction),
false,
);
let original = p.clone();
let token = state.editing.as_ref().unwrap().token;
let scope = state.editing.as_ref().unwrap().scope;
assert_eq!(state.editing.as_ref().unwrap().kind, None);
let size = Size::new(340., 215.);
let mut view = host(&state, &p, "Consumer name: Assessment lifeline");
let mut tree = widget::Tree::new(view.as_widget());
let (node, g) = geometry(&mut view, &mut tree, size);
let mut messages = Vec::new();
for kind in [Kind::Entity, Kind::Actor, Kind::Role] {
let bounds = g.kinds[&kind.to_string()];
assert!(contains(g.fields.unwrap(), bounds));
for action in [
iced::mouse::Event::ButtonPressed(iced::mouse::Button::Left),
iced::mouse::Event::ButtonReleased(iced::mouse::Button::Left),
] {
view.as_widget_mut().update(
&mut tree,
&iced::Event::Mouse(action),
Layout::new(&node),
iced::mouse::Cursor::Available(bounds.center()),
&FontLayout,
&mut iced::advanced::clipboard::Null,
&mut Shell::new(&mut messages),
&Rectangle::new(Point::ORIGIN, size),
);
}
assert!(
matches!(messages.pop(), Some(Event::Edit(id, Edit::Kind(k))) if id == token && k == kind)
);
}
let mut focus = Geometry {
focus_name: true,
..Geometry::default()
};
view.as_widget_mut()
.operate(&mut tree, Layout::new(&node), &FontLayout, &mut focus);
let event = iced::Event::Keyboard(iced::keyboard::Event::KeyPressed {
key: iced::keyboard::Key::Character("Ω".into()),
modified_key: iced::keyboard::Key::Character("Ω".into()),
physical_key: iced::keyboard::key::Physical::Code(iced::keyboard::key::Code::KeyA),
location: iced::keyboard::Location::Standard,
modifiers: iced::keyboard::Modifiers::empty(),
text: Some("Ω".into()),
repeat: false,
});
view.as_widget_mut().update(
&mut tree,
&event,
Layout::new(&node),
iced::mouse::Cursor::Unavailable,
&FontLayout,
&mut iced::advanced::clipboard::Null,
&mut Shell::new(&mut messages),
&Rectangle::new(Point::ORIGIN, size),
);
let edit = messages.pop().unwrap();
assert!(matches!(&edit, Event::Edit(id, Edit::Name(name)) if *id == token && name == "Ω"));
drop(view);
state.update(&p, scope, Id::new_v4(), edit).unwrap();
assert_eq!(
state.editing.as_ref().unwrap().kind,
None,
"Rendering/click event production must not silently adopt a kind"
);
assert_eq!(state.editing.as_ref().unwrap().name, "Ω");
assert_eq!(p, original);
}
}
+29 -365
View File
@@ -27,8 +27,6 @@ pub struct StateCanvas<'a> {
pub diagram: Id,
pub context: Context,
pub selected: Id,
/// Presentation-only navigation marker; never an authoring placement.
pub navigation_focus: Option<Rectangle>,
pub tool: Tool,
pub zoom: f32,
pub pan: Vector,
@@ -40,7 +38,6 @@ pub struct State {
context: Option<Context>,
tool: Option<Tool>,
pointer: Option<Point>,
focused: bool,
press: Option<Press>,
source: Option<Id>,
preview: Option<(Id, Position)>,
@@ -417,171 +414,6 @@ fn state_action_label(project: &Project, relation: &Relation) -> String {
format!("{phase} / {}", project.named(target))
}
/// Match a typed label field by its structural offset, never by a display-name
/// substring (names may duplicate or also occur in free-form guards).
fn retained_label_field(full: &str, painted: &str, start: usize) -> bool {
start
< full
.chars()
.zip(painted.chars())
.take_while(|(a, b)| a == b)
.map(|(c, _)| c.len_utf8())
.sum::<usize>()
}
fn transition_label_role(
project: &Project,
relation: &Relation,
subject: Id,
width: f32,
) -> Option<&'static str> {
let full = routing::state_transition_summary(project, relation);
transition_label_role_in_text(project, relation, subject, &short(&full, width, 10.))
}
fn transition_label_role_in_text(
project: &Project,
relation: &Relation,
subject: Id,
painted: &str,
) -> Option<&'static str> {
let RelationBody::StateTransition {
transition_kind,
triggers,
effects,
effect,
..
} = &relation.body
else {
return None;
};
if project.named(subject).trim().is_empty() {
return None;
}
let full = routing::state_transition_summary(project, relation);
let mut offset = format!("{transition_kind:?} · ").len();
for id in triggers {
if *id == subject && retained_label_field(&full, painted, offset) {
return Some("transition trigger");
}
offset += project.named(*id).len() + " OR ".len();
}
if !effects.is_empty() {
// The canonical routing summary appends typed effects before optional
// authored effect prose. Derive its offset from that exact suffix.
let mut suffix = format!(
" / {}",
effects
.iter()
.map(|id| project.named(*id))
.collect::<Vec<_>>()
.join(", ")
);
if !effect.is_empty() {
suffix.push_str(&format!(" / {effect}"));
}
if let Some(prefix) = full.strip_suffix(&suffix) {
offset = prefix.len() + " / ".len();
for id in effects {
if *id == subject && retained_label_field(&full, painted, offset) {
return Some("transition effect");
}
offset += project.named(*id).len() + ", ".len();
}
}
}
None
}
/// Actual state compartments and painted transition-reference labels. Generic
/// projected node/edge identities are handled by the shared saved-view query.
pub(crate) fn diagram_usages(
project: &Project,
diagram: &Diagram,
view: &ProjectedView,
subject: Id,
) -> Vec<crate::diagram_usage::Usage> {
use crate::diagram_usage::{Surface, Target, Usage};
if diagram.projection.state_machine().is_none() {
return vec![];
}
let mut result = Vec::new();
for node in &view.nodes {
for (relation, bounds) in state_action_rows(project, node) {
let label = state_action_label(project, relation);
let painted = short(&label, bounds.width - 12., 11.);
let role = if relation.id == subject {
Some("state action")
} else if relation.target() == subject
&& retained_label_field(
&label,
&painted,
label.len() - project.named(subject).len(),
)
{
Some("state action work")
} else {
None
};
if let Some(role) = role {
result.push(Usage {
subject,
surface: Surface::Saved(diagram.id),
target: Target::StateRow {
placement: node.id,
relation: relation.id,
},
role: role.into(),
bounds,
});
}
}
for (relation, bounds) in internal_rows(project, node) {
let role = if relation.id == subject {
Some("internal transition")
} else {
transition_label_role(project, relation, subject, bounds.width - 12.)
};
if let Some(role) = role {
result.push(Usage {
subject,
surface: Surface::Saved(diagram.id),
target: Target::StateRow {
placement: node.id,
relation: relation.id,
},
role: role.into(),
bounds,
});
}
}
}
for edge in routing::route_diagram(project, diagram, view)
.edges
.values()
{
let Some(relation) = project.relations.get(&edge.id) else {
continue;
};
if edge.id == subject || edge.label.text.is_empty() {
continue;
}
// Routing already shortens external summaries before the canvas applies
// its width limit. Compare against precisely that doubly shortened text.
let painted = short(&edge.label.text, edge.label.bounds.size.width - 10., 10.);
if let Some(role) = transition_label_role_in_text(project, relation, subject, &painted) {
result.push(Usage {
subject,
surface: Surface::Saved(diagram.id),
target: Target::Edge(edge.id),
role: role.into(),
bounds: crate::diagram_usage::edge_focus_bounds(edge),
});
}
}
result
}
impl StateCanvas<'_> {
fn scale(&self) -> f32 {
if self.zoom.is_finite() {
@@ -938,7 +770,6 @@ impl canvas::Program<Event> for StateCanvas<'_> {
}
canvas::Event::Window(iced::window::Event::Unfocused) => {
state.reset();
state.focused = false;
return None;
}
_ => cursor,
@@ -946,14 +777,40 @@ impl canvas::Program<Event> for StateCanvas<'_> {
let window = cursor.position();
let local = window.map(|p| Point::new(p.x - bounds.x, p.y - bounds.y));
let inside = local.is_some_and(|p| Self::content(bounds).contains(p));
if let canvas::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event
&& state.focused
{
if let canvas::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event {
use keyboard::{Key, key::Named};
if *key == Key::Named(Named::Escape) {
state.reset();
return Some(Action::publish(Event::Choose(Tool::Select)).and_capture());
}
if *key == Key::Named(Named::Delete)
&& self.editable
&& self.tool == Tool::Select
&& state.press.is_none()
&& state.pan_from.is_none()
&& state.source.is_none()
&& (modifiers.is_empty() || *modifiers == keyboard::Modifiers::SHIFT)
{
let scene = self.scene(state)?;
let placement = scene
.view
.nodes
.iter()
.find(|node| node.element == self.selected || node.id == self.selected);
let object = placement.map_or(self.selected, |node| node.element);
if placement.is_none() && !scene.view.edges.iter().any(|edge| edge.id == object) {
return None;
}
return Some(
Action::publish(Event::Remove(crate::app::diagram_removal::Intent {
context: self.context,
object,
placement: placement.map(|node| node.id),
model: modifiers.shift(),
}))
.and_capture(),
);
}
if modifiers.is_empty() {
let pan = match key.as_ref() {
Key::Named(Named::ArrowLeft) => Some(Vector::new(60., 0.)),
@@ -971,7 +828,6 @@ impl canvas::Program<Event> for StateCanvas<'_> {
let scene = self.scene(state)?;
match event {
canvas::Event::Mouse(mouse::Event::ButtonPressed(button)) => {
state.focused = inside;
if !inside {
return None;
}
@@ -1315,14 +1171,6 @@ impl canvas::Program<Event> for StateCanvas<'_> {
overlay.with_clip(content, |frame| {
frame.translate(self.offset());
frame.scale(self.scale());
if let Some(bounds) = self.navigation_focus {
frame.stroke(
&Path::rectangle(bounds.position(), bounds.size()),
Stroke::default()
.with_color(style::TEAL)
.with_width(2.5 / self.scale()),
);
}
if let Some(at) = world
&& self.editable
{
@@ -1750,189 +1598,6 @@ mod tests {
}
}
#[test]
fn diagram_usage_state_rows_and_label_references_follow_actual_projection() {
use crate::diagram_usage::Target;
let mut f = fixture();
let work = f
.project
.add_element(Kind::Function, Layer::Sa, "Act", None)
.unwrap();
let event = f
.project
.add_element(Kind::Event, Layer::Sa, "E", None)
.unwrap();
let unused = f
.project
.add_element(Kind::Event, Layer::Sa, "E", None)
.unwrap();
let action = f
.project
.relate(RelationKind::StateAction, "Entry", f.a, work);
let internal = f
.project
.relate(RelationKind::StateTransition, "Internal", f.a, f.a);
let external = f
.project
.relate(RelationKind::StateTransition, "External", f.a, f.b);
for (id, kind) in [
(internal, TransitionKind::Internal),
(external, TransitionKind::External),
] {
if let RelationBody::StateTransition {
transition_kind,
triggers,
effects,
..
} = &mut f.project.relations.get_mut(&id).unwrap().body
{
*transition_kind = kind;
*triggers = vec![event];
*effects = vec![work];
}
}
let before = f.project.clone();
let diagram = &f.project.diagrams[&f.diagram];
let view = projection::project_diagram(&f.project, diagram);
let placement = view.nodes.iter().find(|n| n.element == f.a).unwrap().id;
let action_target = Target::StateRow {
placement,
relation: action,
};
let internal_target = Target::StateRow {
placement,
relation: internal,
};
assert_eq!(
diagram_usages(&f.project, diagram, &view, action)[0].target,
action_target
);
assert_eq!(
diagram_usages(&f.project, diagram, &view, internal)[0].target,
internal_target
);
let events = diagram_usages(&f.project, diagram, &view, event);
assert_eq!(events.len(), 2);
assert!(events.iter().any(|u| u.target == internal_target));
assert!(events.iter().any(|u| u.target == Target::Edge(external)));
assert!(diagram_usages(&f.project, diagram, &view, unused).is_empty());
// External edge identity belongs to the shared saved-view adapter.
assert!(diagram_usages(&f.project, diagram, &view, external).is_empty());
let work_usages = diagram_usages(&f.project, diagram, &view, work);
assert!(work_usages.iter().any(|u| u.target == action_target));
assert!(work_usages.iter().any(|u| u.target == internal_target));
let row = work_usages
.iter()
.find(|u| u.target == action_target)
.unwrap();
let canvas = canvas(&f, Tool::Select, 1.);
let scene = canvas.scene(&State::default()).unwrap();
assert_eq!(
canvas.hit(&scene, row.bounds.center()),
Some(Hit::StateAction(action))
);
assert_eq!(f.project, before);
f.project
.diagrams
.get_mut(&f.diagram)
.unwrap()
.nodes
.get_mut(&placement)
.unwrap()
.collapsed = true;
let diagram = &f.project.diagrams[&f.diagram];
let folded = projection::project_diagram(&f.project, diagram);
assert!(diagram_usages(&f.project, diagram, &folded, action).is_empty());
assert!(diagram_usages(&f.project, diagram, &folded, internal).is_empty());
}
#[test]
fn diagram_usage_transition_labels_do_not_match_prose_or_fields_beyond_cutoff() {
let mut f = fixture();
let early = f
.project
.add_element(Kind::Event, Layer::Sa, "A", None)
.unwrap();
let late = f
.project
.add_element(Kind::Event, Layer::Sa, "B", None)
.unwrap();
let relation = f
.project
.relate(RelationKind::StateTransition, "Transition", f.a, f.b);
if let RelationBody::StateTransition {
triggers, guard, ..
} = &mut f.project.relations.get_mut(&relation).unwrap().body
{
*triggers = vec![early, late];
*guard = "B".into();
}
let relation = &f.project.relations[&relation];
assert_eq!(
transition_label_role(&f.project, relation, early, 84.),
Some("transition trigger")
);
assert_eq!(transition_label_role(&f.project, relation, late, 84.), None);
assert_eq!(
transition_label_role(&f.project, relation, late, 800.),
Some("transition trigger")
);
assert!(!retained_label_field("1234A678", "1234…", 4));
}
#[test]
fn diagram_usage_external_labels_obey_routing_cutoff_while_internal_rows_retain_full_summary() {
use crate::diagram_usage::Target;
let mut f = fixture();
let first = f
.project
.add_element(Kind::Event, Layer::Sa, &"A".repeat(35), None)
.unwrap();
let second = f
.project
.add_element(Kind::Event, Layer::Sa, "Second", None)
.unwrap();
let external = f
.project
.relate(RelationKind::StateTransition, "External", f.a, f.b);
let internal = f
.project
.relate(RelationKind::StateTransition, "Internal", f.a, f.a);
for (id, kind) in [
(external, TransitionKind::External),
(internal, TransitionKind::Internal),
] {
if let RelationBody::StateTransition {
transition_kind,
triggers,
..
} = &mut f.project.relations.get_mut(&id).unwrap().body
{
*transition_kind = kind;
*triggers = vec![first, second];
}
}
let diagram = &f.project.diagrams[&f.diagram];
let view = projection::project_diagram(&f.project, diagram);
let routed = routing::route_diagram(&f.project, diagram, &view);
let edge = &routed.edges[&external];
let painted = short(&edge.label.text, edge.label.bounds.size.width - 10., 10.);
// Independent painted-text oracle: 11 prefix characters + 35 As, then
// only the space before OR survives the routing limit.
assert_eq!(edge.label.text, format!("External · {} …", "A".repeat(35)));
assert!(!painted.contains("Second"));
let usages = diagram_usages(&f.project, diagram, &view, second);
assert!(!usages.iter().any(|u| u.target == Target::Edge(external)));
assert!(usages.iter().any(
|u| matches!(u.target, Target::StateRow { relation, .. } if relation == internal)
));
assert!(
diagram_usages(&f.project, diagram, &view, first)
.iter()
.any(|u| u.target == Target::Edge(external))
);
}
fn canvas(f: &Fixture, tool: Tool, zoom: f32) -> StateCanvas<'_> {
StateCanvas {
project: &f.project,
@@ -1944,7 +1609,6 @@ mod tests {
epoch: 3,
},
selected: f.machine,
navigation_focus: None,
tool,
zoom,
pan: Vector::new(20., 30.),
@@ -24,6 +24,7 @@ pub enum Tool {
#[derive(Debug, Clone)]
pub enum Event {
Remove(crate::app::diagram_removal::Intent),
Choose(Tool),
CreateView(Id),
Select(Context, Id),
@@ -70,6 +71,7 @@ pub enum Event {
impl Event {
pub fn context(&self) -> Option<Context> {
match self {
Self::Remove(intent) => Some(intent.context),
Self::Choose(_) | Self::CreateView(_) => None,
Self::Select(c, _)
| Self::Pan(c, _)
+26 -6
View File
@@ -139,11 +139,14 @@ pub fn popup(app: &App, opened: &Opened, clean: bool) -> Option<Menu<Message>> {
true,
));
}
entries.push(item(
"Hide from this diagram",
Message::Command(Command::Delete(node.id)),
true,
));
entries.push(
item(
"Hide from this diagram",
Message::Command(Command::Delete(node.id)),
true,
)
.shortcut("Delete"),
);
}
}
if let Some(relation) = project.relations.get(&id)
@@ -184,7 +187,24 @@ pub fn popup(app: &App, opened: &Opened, clean: bool) -> Option<Menu<Message>> {
}
if id != project.id {
entries.push(Entry::separator());
entries.push(item("Delete from model…", Message::Delete, true));
entries.push(item("Delete from model…", Message::Delete, true).shortcut(
if context.is_some_and(|context| {
context.diagram != id
&& (request.placement.is_some()
|| projection::project_view(project, context.diagram)
.edges
.iter()
.any(|edge| edge.id == id))
}) {
if request.placement.is_some() {
"Shift+Delete"
} else {
"Delete / Shift+Delete"
}
} else {
""
},
));
}
}
Some(Menu {
+6 -4
View File
@@ -165,9 +165,6 @@ pub fn view<'a>(app: &'a App, machine: Id, mut out: Column<'a, Message>) -> Elem
diagram: id,
context,
selected: app.selected,
navigation_focus: app
.diagram_focus(crate::diagram_usage::Surface::Saved(id))
.map(|usage| usage.bounds),
tool: state.tool,
zoom: state.zoom,
pan: state.pan,
@@ -176,7 +173,12 @@ pub fn view<'a>(app: &'a App, machine: Id, mut out: Column<'a, Message>) -> Elem
.width(Fill)
.height(Fill)
.into();
out = out.push(canvas.map(event));
out = out.push(crate::diagram::focus::wrap(
canvas.map(event),
context,
crate::app::diagram_removal::enabled(app),
Message::DiagramTraverse,
));
let base: Element<'_, Message> = container(out.spacing(8))
.padding(14)
.width(Fill)
+45 -130
View File
@@ -5,7 +5,6 @@ use iced::widget::{Column, text_input};
use std::collections::BTreeSet;
pub(crate) mod contextual;
mod direct;
mod usages;
mod view;
use direct::Input;
pub(crate) use direct::{
@@ -911,13 +910,6 @@ fn sequence_links(p: &Project, owner: Id) -> Vec<&Relation> {
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct PreviewLink {
relation: Id,
source: OccurrenceEndpoint,
target: OccurrenceEndpoint,
}
struct GraphNode {
id: Id,
rect: Rectangle,
@@ -926,98 +918,26 @@ struct GraphNode {
control: Option<ControlKind>,
source: Option<Id>,
preview: Vec<(OccurrenceEndpoint, String)>,
preview_links: Vec<PreviewLink>,
preview_links: Vec<(OccurrenceEndpoint, OccurrenceEndpoint)>,
preview_total: usize,
}
impl GraphNode {
fn preview_link_points(&self, link: &PreviewLink) -> Option<[Point; 2]> {
if ![&link.source, &link.target]
.into_iter()
.all(|endpoint| self.preview.iter().any(|(shown, _)| shown == endpoint))
{
return None;
}
let a = self.endpoint_rect(&link.source);
let b = self.endpoint_rect(&link.target);
Some([
Point::new(a.x + a.width, a.center_y()),
Point::new(b.x, b.center_y()),
])
}
fn preview_link_visible_segment(&self, link: &PreviewLink) -> Option<[Point; 2]> {
visible_preview_segment(
self.preview_link_points(link)?,
(0..self.preview.len()).map(|index| self.preview_rect(index)),
)
}
fn preview_rect(&self, index: usize) -> Rectangle {
Rectangle::new(
Point::new(
self.rect.x + 12. + (index % 2) as f32 * 125.,
self.rect.y + 118. + (index / 2) as f32 * 44.,
),
Size::new(113., 32.),
)
}
fn endpoint_rect(&self, endpoint: &OccurrenceEndpoint) -> Rectangle {
self.preview
.iter()
.position(|(candidate, _)| candidate == endpoint)
.map(|index| self.preview_rect(index))
.map(|i| {
Rectangle::new(
Point::new(
self.rect.x + 12. + (i % 2) as f32 * 125.,
self.rect.y + 118. + (i / 2) as f32 * 44.,
),
Size::new(113., 32.),
)
})
.unwrap_or(self.rect)
}
}
/// Preview tiles are painted after their arrows. Focus only a remaining line
/// segment, excluding opaque tile interiors and their one-pixel borders.
fn visible_preview_segment(
[a, b]: [Point; 2],
tiles: impl Iterator<Item = Rectangle>,
) -> Option<[Point; 2]> {
let delta = b - a;
let length = (delta.x * delta.x + delta.y * delta.y).sqrt();
if !length.is_finite() || length <= 0.5 {
return None;
}
let mut hidden = Vec::new();
for tile in tiles {
let mut low = 0_f32;
let mut high = 1_f32;
for (origin, step, min, max) in [
(a.x, delta.x, tile.x - 1., tile.x + tile.width + 1.),
(a.y, delta.y, tile.y - 1., tile.y + tile.height + 1.),
] {
if step.abs() <= f32::EPSILON {
if origin < min || origin > max {
high = -1.;
break;
}
} else {
let first = (min - origin) / step;
let last = (max - origin) / step;
low = low.max(first.min(last));
high = high.min(first.max(last));
}
}
if high > low {
hidden.push((low, high));
}
}
hidden.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut cursor = 0_f32;
let mut best = (0_f32, 0_f32);
for (low, high) in hidden.into_iter().chain([(1., 1.)]) {
if low - cursor > best.1 - best.0 {
best = (cursor, low);
}
cursor = cursor.max(high);
}
((best.1 - best.0) * length > 0.5).then(|| [a + delta * best.0, a + delta * best.1])
}
struct GraphEdge {
id: Id,
source: Id,
@@ -1066,8 +986,6 @@ struct Graph<'a> {
ordered: bool,
size: Size,
selected: Id,
selected_preview: Option<OccurrenceEndpoint>,
selected_preview_link: Option<PreviewLink>,
scale: f32,
}
impl<'a> Graph<'a> {
@@ -1216,16 +1134,17 @@ impl<'a> Graph<'a> {
occurrence: r.target(),
})
})
.map(|r| PreviewLink {
relation: r.id,
source: OccurrenceEndpoint {
references: vec![e.id],
occurrence: r.source(),
},
target: OccurrenceEndpoint {
references: vec![e.id],
occurrence: r.target(),
},
.map(|r| {
(
OccurrenceEndpoint {
references: vec![e.id],
occurrence: r.source(),
},
OccurrenceEndpoint {
references: vec![e.id],
occurrence: r.target(),
},
)
})
.collect();
}
@@ -1400,8 +1319,6 @@ impl<'a> Graph<'a> {
ordered: !order.is_empty(),
size,
selected,
selected_preview: None,
selected_preview_link: None,
scale: 1.,
}
}
@@ -1631,41 +1548,39 @@ impl canvas::Program<Message> for Graph<'_> {
let mini: BTreeMap<_, _> = n
.preview
.iter()
.map(|(id, _)| (id.clone(), n.endpoint_rect(id)))
.enumerate()
.map(|(i, (id, _))| {
(
id.clone(),
Rectangle::new(
Point::new(
n.rect.x + 12. + (i % 2) as f32 * 125.,
n.rect.y + 118. + (i / 2) as f32 * 44.,
),
Size::new(113., 32.),
),
)
})
.collect();
for link in &n.preview_links {
let Some(points) = n.preview_link_points(link) else {
continue;
};
let selected = self.selected_preview_link.as_ref() == Some(link);
for (a, b) in &n.preview_links {
let a = mini[a];
let b = mini[b];
draw_arrow(
&mut f,
&points,
if selected { style::TEAL } else { style::MUTED },
if selected { 3. } else { 1. },
&[
Point::new(a.x + a.width, a.center_y()),
Point::new(b.x, b.center_y()),
],
style::MUTED,
1.,
);
}
for (id, name) in &n.preview {
let r = mini[id];
let selected = self.selected_preview.as_ref() == Some(id);
f.fill_rectangle(
r.position(),
r.size(),
if selected {
Color::from_rgb8(224, 247, 242)
} else {
Color::WHITE
},
);
f.fill_rectangle(r.position(), r.size(), Color::WHITE);
f.stroke(
&Path::rectangle(r.position(), r.size()),
Stroke::default()
.with_color(if selected {
style::TEAL
} else {
style::LINE
})
.with_width(if selected { 2.5 } else { 1. }),
Stroke::default().with_color(style::LINE),
);
draw_text(
&mut f,
@@ -1,274 +0,0 @@
//! Read-only usages of the actual process graph, including bounded reuse tiles.
use super::*;
use crate::diagram_usage::{Surface, Target, Usage};
/// The only presentation inputs needed by a background usage query. Drafts,
/// focus, camera, history and widget state never cross the worker boundary.
#[derive(Clone)]
pub(crate) struct UsageSnapshot {
identity: Option<(Id, Id)>,
expanded: BTreeSet<Id>,
contextual_expanded: BTreeSet<OccurrenceEndpoint>,
}
impl UsageSnapshot {
pub(crate) fn into_query_state(self) -> State {
State {
identity: self.identity,
expanded: self.expanded,
contextual_expanded: self.contextual_expanded,
..State::default()
}
}
}
impl State {
pub(crate) fn usage_snapshot(&self) -> UsageSnapshot {
UsageSnapshot {
identity: self.identity,
expanded: self.expanded.clone(),
contextual_expanded: self.contextual_expanded.clone(),
}
}
}
fn owner_exists(p: &Project, owner: Id) -> bool {
p.elements
.get(&owner)
.is_some_and(|e| matches!(e.kind(), Kind::Process | Kind::FunctionalChain))
}
fn occurrence_role(p: &Project, occurrence: Id, subject: Id) -> Option<&'static str> {
let e = p.elements.get(&occurrence)?;
if occurrence == subject {
return Some("contribution");
}
match e.shared()? {
SharedBody::Occurrence {
body: OccurrenceBody::Action {
action: Some(id), ..
},
..
} if *id == subject => Some("action occurrence"),
SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
exchange: Some(id), ..
},
..
} if *id == subject => Some("exchange occurrence"),
SharedBody::Occurrence {
body: OccurrenceBody::SequenceReference { sequence: Some(id) },
..
} if *id == subject => Some("reused process / chain"),
_ => None,
}
}
impl Graph<'_> {
fn usage_bounds(&self, target: &Target) -> Option<Rectangle> {
match target {
Target::Whole => Some(Rectangle::new(Point::ORIGIN, self.size)),
Target::ProcessOccurrence(endpoint) => {
let root = endpoint
.references
.first()
.copied()
.unwrap_or(endpoint.occurrence);
let node = self.nodes.iter().find(|node| node.id == root)?;
if endpoint.references.is_empty() {
Some(node.rect)
} else {
// endpoint_rect intentionally has a proxy fallback for other callers;
// a usage promises an actual tile and must never take that fallback.
node.preview
.iter()
.any(|(shown, _)| shown == endpoint)
.then(|| node.endpoint_rect(endpoint))
}
}
Target::ProcessLink(id) => {
let edge = self.edges.iter().find(|edge| edge.id == *id)?;
if !edge.guard.is_empty() {
Some(edge.label)
} else {
let segment = edge
.points
.windows(2)
.nth(edge.points.len().saturating_sub(1) / 2)?;
let center = Point::new(
(segment[0].x + segment[1].x) / 2.,
(segment[0].y + segment[1].y) / 2.,
);
Some(Rectangle::new(
center - iced::Vector::new(16., 16.),
Size::new(32., 32.),
))
}
}
Target::ProcessPreviewLink {
relation,
source,
target,
} => {
let node = self
.nodes
.iter()
.find(|node| source.references.first() == Some(&node.id))?;
let link = node.preview_links.iter().find(|link| {
link.relation == *relation && link.source == *source && link.target == *target
})?;
let [a, b] = node.preview_link_visible_segment(link)?;
Some(Rectangle::new(
Point::new((a.x + b.x) / 2. - 16., (a.y + b.y) / 2. - 16.),
Size::new(32., 32.),
))
}
_ => None,
}
}
}
impl State {
/// Inactive owners use the same default preview policy as entering their canvas.
fn usage_graph<'a>(&self, p: &'a Project, owner: Id) -> Graph<'a> {
if self.identity.is_some_and(|(_, current)| current == owner) {
Graph::expanded_qualified(p, owner, owner, &self.expanded, &self.contextual_expanded)
} else {
Graph::new(p, owner, owner)
}
}
pub(crate) fn diagram_usages(&self, p: &Project, owner: Id, subject: Id) -> Vec<Usage> {
if !owner_exists(p, owner)
|| !(p.elements.contains_key(&subject) || p.relations.contains_key(&subject))
{
return vec![];
}
let graph = self.usage_graph(p, owner);
let mut usages = vec![];
let mut add = |target: Target, role: &str| {
if let Some(bounds) = graph.usage_bounds(&target) {
usages.push(Usage {
subject,
surface: Surface::Process(owner),
target,
role: role.into(),
bounds,
});
}
};
if subject == owner {
add(Target::Whole, "process / chain canvas");
}
for node in &graph.nodes {
if let Some(role) = occurrence_role(p, node.id, subject) {
add(
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: node.id,
}),
role,
);
}
for (endpoint, _) in &node.preview {
if let Some(role) = occurrence_role(p, endpoint.occurrence, subject) {
add(
Target::ProcessOccurrence(endpoint.clone()),
&format!("reused {role}"),
);
}
}
for link in &node.preview_links {
if link.relation == subject {
add(
Target::ProcessPreviewLink {
relation: link.relation,
source: link.source.clone(),
target: link.target.clone(),
},
"reused sequence link",
);
}
}
}
for edge in &graph.edges {
let role = if edge.id == subject {
Some("process link")
} else {
match p.relations.get(&edge.id).map(|r| &r.body) {
Some(RelationBody::ContextualLink {
purpose: ContextualLinkPurpose::Exchange { exchange },
..
}) if *exchange == subject => Some("assembly exchange"),
Some(RelationBody::ContextualLink {
purpose: ContextualLinkPurpose::CommonWork { work },
..
}) if *work == subject => Some("common work"),
_ => None,
}
};
if let Some(role) = role {
add(Target::ProcessLink(edge.id), role);
}
}
usages
}
/// Returns success, not whether the camera changed. App must separately guard
/// its other drafts and revalidate the queried subject's current usage.
pub(crate) fn reveal_usage(
&mut self,
p: &Project,
document: Id,
owner: Id,
target: &Target,
) -> bool {
if !owner_exists(p, owner) || self.draft.is_some() {
return false;
}
let same = self.identity == Some((document, owner));
let graph = if same {
self.usage_graph(p, owner)
} else {
Graph::new(p, owner, owner)
};
let Some(bounds) = graph.usage_bounds(target) else {
return false;
};
let address = if let Target::ProcessOccurrence(endpoint) = target {
let Ok(resolved) =
oa_core::topology_context::TopologyIndex::new(p).resolve(owner, endpoint)
else {
return false;
};
(!endpoint.references.is_empty()).then_some(resolved.address)
} else {
None
};
let viewport = self.viewport.unwrap_or(Size::new(500., 300.));
self.enter(document, owner);
if !same {
self.contextual_expanded.clear();
}
self.selected_context = address;
self.tool = CanvasTool::Select;
self.viewport = Some(viewport);
let fit = ((viewport.width - 48.).max(1.) / bounds.width.max(1.))
.min((viewport.height - 48.).max(1.) / bounds.height.max(1.));
let scale = if matches!(target, Target::Whole) {
fit.clamp(0.0001, 1.)
} else {
fit.clamp(0.6, 1.25)
};
self.zoom = Some(scale);
self.fit = false;
self.pan = iced::Vector::new(
viewport.width / 2. - bounds.center_x() * scale,
viewport.height / 2. - bounds.center_y() * scale,
);
true
}
}
#[cfg(test)]
mod tests;
@@ -1,439 +0,0 @@
use super::*;
fn add(p: &mut Project, owner: Id, name: &str, body: OccurrenceBody) -> Id {
let e = occurrence(p, owner, name, body);
let id = e.id;
*p = execute_batch(p, &[Command::CreateElement(e)]).unwrap();
id
}
fn reused_fixture() -> (Project, Id, Id, Id, [Id; 2], Vec<Id>) {
let f = super::super::direct_tests::fixture(Layer::Oa);
let mut p = f.p;
let sequence = p
.make_element(Kind::Process, Layer::Oa, "Reviewed checks", None)
.unwrap();
let sequence_id = sequence.id;
p = execute_batch(&p, &[Command::CreateElement(sequence)]).unwrap();
let mut leaves = vec![];
for name in [
"Check one",
"Check two",
"Check three",
"Check four",
"Check five",
] {
leaves.push(add(
&mut p,
sequence_id,
name,
OccurrenceBody::Action {
action: Some(f.work[0]),
lifeline: None,
},
));
}
let first = add(
&mut p,
f.owner,
"First invocation",
OccurrenceBody::SequenceReference {
sequence: Some(sequence_id),
},
);
let second = add(
&mut p,
f.owner,
"Second invocation",
OccurrenceBody::SequenceReference {
sequence: Some(sequence_id),
},
);
(p, f.owner, sequence_id, f.work[0], [first, second], leaves)
}
#[test]
fn process_usages_exclude_endpoint_coincidence_and_keep_actual_occurrences_and_links() {
for layer in [Layer::Oa, Layer::Sa] {
let f = super::super::direct_tests::fixture(layer);
let mut p = f.p;
let state = State::default();
// Both exchange endpoints have Action contributions, but there is no
// Exchange occurrence and no exchange arrow in this process.
assert!(state.diagram_usages(&p, f.owner, f.exchange).is_empty());
let direct = state.diagram_usages(&p, f.owner, f.work[0]);
assert_eq!(direct.len(), 1);
assert_eq!(
direct[0].target,
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: f.nodes[0]
})
);
let link = state.diagram_usages(&p, f.owner, f.link);
assert_eq!(link.len(), 1);
assert_eq!(link[0].target, Target::ProcessLink(f.link));
let first = add(
&mut p,
f.owner,
"First exchange",
OccurrenceBody::Exchange {
exchange: Some(f.exchange),
sender: None,
receiver: None,
message_kind: MessageKind::Asynchronous,
reply_to: None,
values: vec![],
operation: None,
},
);
let second = add(
&mut p,
f.owner,
"Second exchange",
OccurrenceBody::Exchange {
exchange: Some(f.exchange),
sender: None,
receiver: None,
message_kind: MessageKind::Asynchronous,
reply_to: None,
values: vec![],
operation: None,
},
);
let usages = state.diagram_usages(&p, f.owner, f.exchange);
assert_eq!(usages.len(), 2);
assert_eq!(
usages
.iter()
.map(|usage| usage.target.clone())
.collect::<Vec<_>>(),
vec![
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: first
}),
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![],
occurrence: second
}),
]
);
}
}
#[test]
fn process_usages_keep_caller_paths_and_exclude_unshown_fifth_preview() {
let (p, owner, sequence, work, calls, leaves) = reused_fixture();
let before = p.clone();
let mut state = State::default();
let leaf = state.diagram_usages(&p, owner, leaves[0]);
assert_eq!(leaf.len(), 2);
for (usage, call) in leaf.iter().zip(calls) {
assert_eq!(
usage.target,
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![call],
occurrence: leaves[0]
})
);
}
assert_ne!(leaf[0].bounds, leaf[1].bounds);
assert!(state.diagram_usages(&p, owner, leaves[4]).is_empty());
assert_eq!(state.diagram_usages(&p, owner, sequence).len(), 2);
// One local action and four tiles in each of two caller boxes.
assert_eq!(state.diagram_usages(&p, owner, work).len(), 9);
state.enter(Id::new_v4(), owner);
assert!(state.expand(&p, owner, calls[0]));
let fifth = state.diagram_usages(&p, owner, leaves[4]);
assert_eq!(fifth.len(), 1);
assert_eq!(
fifth[0].target,
Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![calls[0]],
occurrence: leaves[4]
})
);
// Another active owner must not leak its expansion to this queried canvas.
state.enter(Id::new_v4(), sequence);
assert!(state.diagram_usages(&p, owner, leaves[4]).is_empty());
assert_eq!(p, before);
}
#[test]
fn process_usage_reveal_validates_before_state_changes_and_centers_the_exact_tile() {
let (p, owner, _, _, calls, leaves) = reused_fixture();
let before = p.clone();
let document = Id::new_v4();
let mut state = State::default();
state.enter(document, owner);
state.viewport(Size::new(880., 460.));
state.pan = iced::Vector::new(-3000., -900.);
let hidden = Target::ProcessOccurrence(OccurrenceEndpoint {
references: vec![calls[0]],
occurrence: leaves[4],
});
let prior = (
state.identity,
state.pan,
state.zoom,
state.fit,
state.selected_context.clone(),
);
assert!(!state.reveal_usage(&p, document, owner, &hidden));
assert_eq!(
(
state.identity,
state.pan,
state.zoom,
state.fit,
state.selected_context.clone()
),
prior
);
assert!(!state.reveal_usage(&p, document, Id::new_v4(), &Target::Whole));
assert_eq!(
(
state.identity,
state.pan,
state.zoom,
state.fit,
state.selected_context.clone()
),
prior
);
let endpoint = OccurrenceEndpoint {
references: vec![calls[1]],
occurrence: leaves[0],
};
let target = Target::ProcessOccurrence(endpoint.clone());
assert!(state.reveal_usage(&p, document, owner, &target));
assert_eq!(state.selected_context.as_ref().unwrap().endpoint, endpoint);
let bounds = state
.diagram_usages(&p, owner, leaves[0])
.into_iter()
.find(|usage| usage.target == target)
.unwrap()
.bounds;
let scale = state.zoom.unwrap();
assert!(scale >= 0.6);
assert!((bounds.center_x() * scale + state.pan.x - 440.).abs() < 0.01);
assert!((bounds.center_y() * scale + state.pan.y - 230.).abs() < 0.01);
assert!(state.reveal_usage(&p, document, owner, &Target::Whole));
assert!(state.selected_context.is_none());
state
.update(&p, Event::Start(owner, Tool::Work, None))
.unwrap();
let draft = state.recovery_snapshot().unwrap();
let camera = (state.pan, state.zoom, state.fit);
assert!(!state.reveal_usage(&p, document, owner, &target));
assert_eq!(state.recovery_snapshot().unwrap(), draft);
assert_eq!((state.pan, state.zoom, state.fit), camera);
assert_eq!(p, before);
}
#[test]
fn process_contextual_purpose_and_painted_preview_links_keep_distinct_identities() {
let (mut p, owner, sequence, work, calls, leaves) = reused_fixture();
let source = OccurrenceEndpoint {
references: vec![calls[0]],
occurrence: leaves[0],
};
let target = OccurrenceEndpoint {
references: vec![calls[1]],
occurrence: leaves[0],
};
let relation = Relation {
id: Id::new_v4(),
alias: "same_check".into(),
name: "One common check".into(),
description: String::new(),
body: RelationBody::ContextualLink {
owner,
source,
target,
purpose: ContextualLinkPurpose::CommonWork { work },
},
};
let contextual = relation.id;
p = execute_batch(&p, &[Command::CreateRelation(relation)]).unwrap();
let Command::CreateRelation(relation) = link(&p, leaves[0], leaves[1], "next") else {
unreachable!()
};
let local_link = relation.id;
p = execute_batch(&p, &[Command::CreateRelation(relation)]).unwrap();
let state = State::default();
assert!(
state
.diagram_usages(&p, owner, work)
.iter()
.any(|usage| usage.target == Target::ProcessLink(contextual)
&& usage.role == "common work")
);
assert_eq!(state.diagram_usages(&p, owner, contextual).len(), 1);
let previews = state.diagram_usages(&p, owner, local_link);
assert_eq!(previews.len(), 2);
for (usage, call) in previews.iter().zip(calls) {
assert_eq!(
usage.target,
Target::ProcessPreviewLink {
relation: local_link,
source: OccurrenceEndpoint {
references: vec![call],
occurrence: leaves[0]
},
target: OccurrenceEndpoint {
references: vec![call],
occurrence: leaves[1]
},
}
);
}
assert_eq!(state.diagram_usages(&p, sequence, local_link).len(), 1);
}
#[test]
fn preview_arrow_focus_is_in_the_painted_gap_and_hidden_endpoints_never_fallback() {
let (mut p, owner, _, _, calls, leaves) = reused_fixture();
let Command::CreateRelation(shown) = link(&p, leaves[0], leaves[1], "next") else {
unreachable!()
};
let shown_id = shown.id;
p = execute_batch(&p, &[Command::CreateRelation(shown)]).unwrap();
let Command::CreateRelation(hidden) = link(&p, leaves[0], leaves[4], "later") else {
unreachable!()
};
let hidden_id = hidden.id;
p = execute_batch(&p, &[Command::CreateRelation(hidden)]).unwrap();
let before = p.clone();
let document = Id::new_v4();
let mut state = State::default();
state.enter(document, owner);
state.viewport(Size::new(800., 460.));
let rows = state.diagram_usages(&p, owner, shown_id);
assert_eq!(rows.len(), 2);
let graph = Graph::new(&p, owner, owner);
for (row, call) in rows.iter().zip(calls) {
let node = graph.nodes.iter().find(|n| n.id == call).unwrap();
// The painter places 113px tiles 125px apart, beginning 12px in.
// The 12px gap is centered 131px into the caller, 134px below its top.
assert_eq!(
row.bounds.center(),
Point::new(node.rect.x + 131., node.rect.y + 134.)
);
assert!(
node.preview
.iter()
.all(|(e, _)| !node.endpoint_rect(e).contains(row.bounds.center()))
);
}
assert_ne!(rows[0].bounds, rows[1].bounds);
assert!(state.diagram_usages(&p, owner, hidden_id).is_empty());
assert!(state.reveal_usage(&p, document, owner, &rows[1].target));
assert!(
state.selected_context.is_none(),
"an arrow is not an occurrence authoring context"
);
let zoom = state.zoom.unwrap();
assert!((rows[1].bounds.center_x() * zoom + state.pan.x - 400.).abs() < 0.01);
assert!((rows[1].bounds.center_y() * zoom + state.pan.y - 230.).abs() < 0.01);
assert!(state.expand(&p, owner, calls[0]));
let expanded = state.diagram_usages(&p, owner, hidden_id);
assert_eq!(expanded.len(), 1);
assert!(
matches!(&expanded[0].target, Target::ProcessPreviewLink { source, .. }
if source.references == vec![calls[0]])
);
let mut stale = rows[1].target.clone();
if let Target::ProcessPreviewLink { source, .. } = &mut stale {
source.references = vec![Id::new_v4()];
}
let prior = (state.pan, state.zoom, state.fit);
assert!(!state.reveal_usage(&p, document, owner, &stale));
assert_eq!((state.pan, state.zoom, state.fit), prior);
assert_eq!(p, before);
}
#[test]
fn visible_preview_segment_excludes_all_opaque_tiles_for_reverse_and_cross_row_arrows() {
let tiles = [
Rectangle::new(Point::new(12., 118.), Size::new(113., 32.)),
Rectangle::new(Point::new(137., 118.), Size::new(113., 32.)),
Rectangle::new(Point::new(12., 162.), Size::new(113., 32.)),
Rectangle::new(Point::new(137., 162.), Size::new(113., 32.)),
];
for points in [
[Point::new(250., 134.), Point::new(12., 134.)],
[Point::new(125., 134.), Point::new(137., 178.)],
[Point::new(250., 178.), Point::new(12., 134.)],
] {
let [a, b] = visible_preview_segment(points, tiles.into_iter()).unwrap();
for fraction in [0.1, 0.5, 0.9] {
let point = a + (b - a) * fraction;
assert!(tiles.iter().all(|tile| !tile.contains(point)));
}
}
assert!(
visible_preview_segment(
[Point::new(30., 134.), Point::new(100., 134.)],
tiles.into_iter()
)
.is_none()
);
assert!(
visible_preview_segment([Point::new(1., 1.), Point::new(1., 1.)], tiles.into_iter())
.is_none()
);
}
#[test]
fn expanded_nested_tiles_do_not_invent_links_the_preview_painter_does_not_emit() {
let (mut p, owner, sequence, work, calls, _) = reused_fixture();
let nested = p
.make_element(Kind::Process, Layer::Oa, "Nested checks", None)
.unwrap();
let nested_id = nested.id;
p = execute_batch(&p, &[Command::CreateElement(nested)]).unwrap();
let leaves: Vec<_> = ["Nested one", "Nested two"]
.into_iter()
.map(|name| {
add(
&mut p,
nested_id,
name,
OccurrenceBody::Action {
action: Some(work),
lifeline: None,
},
)
})
.collect();
let Command::CreateRelation(relation) = link(&p, leaves[0], leaves[1], "next") else {
unreachable!()
};
let relation_id = relation.id;
p = execute_batch(&p, &[Command::CreateRelation(relation)]).unwrap();
let reference = add(
&mut p,
sequence,
"Nested invocation",
OccurrenceBody::SequenceReference {
sequence: Some(nested_id),
},
);
let mut state = State::default();
state.enter(Id::new_v4(), owner);
state.expanded.insert(calls[0]);
state.contextual_expanded.insert(OccurrenceEndpoint {
references: vec![calls[0]],
occurrence: reference,
});
let shown = state.diagram_usages(&p, owner, leaves[0]);
assert_eq!(shown.len(), 1);
assert!(
matches!(&shown[0].target, Target::ProcessOccurrence(endpoint)
if endpoint.references == vec![calls[0], reference])
);
assert!(state.diagram_usages(&p, owner, relation_id).is_empty());
assert_eq!(state.diagram_usages(&p, nested_id, relation_id).len(), 1);
}
@@ -183,32 +183,6 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
&state.expanded,
&state.contextual_expanded,
);
graph.selected_preview = state
.qualified_selection(p, owner)
.filter(|address| {
address
.endpoint
.references
.first()
.copied()
.unwrap_or(address.endpoint.occurrence)
== app.selected
})
.map(|address| address.endpoint.clone());
graph.selected_preview_link = app
.diagram_focus(crate::diagram_usage::Surface::Process(owner))
.and_then(|usage| match &usage.target {
crate::diagram_usage::Target::ProcessPreviewLink {
relation,
source,
target,
} => Some(PreviewLink {
relation: *relation,
source: source.clone(),
target: target.clone(),
}),
_ => None,
});
graph.scale = state.scale(graph.size, (app.window_size.width - 600.).max(200.));
graph.camera_pan = state.pan;
graph.pending_insertion = state
+164 -41
View File
@@ -34,15 +34,19 @@ mod view_options_tests;
#[path = "diagram/port_labels.rs"]
mod port_labels;
pub use port_labels::PortLabels;
#[path = "diagram/focus.rs"]
pub(crate) mod focus;
#[path = "diagram/work_drag.rs"]
mod work_drag;
pub use work_drag::WorkFeedback;
#[derive(Clone, Copy)]
pub struct DiagramCanvas<'a> {
pub allocation: Option<crate::app::allocation_drag::Capability<'a>>,
pub project: &'a Project,
pub view_index: Option<&'a oa_core::view_options::ViewIndex>,
pub diagram: Id,
pub selected: Id,
/// Presentation-only navigation marker; never used by hit tests or edits.
pub navigation_focus: Option<Rectangle>,
pub zoom: f32,
pub pan: Vector,
pub context: Context,
@@ -53,8 +57,9 @@ pub struct DiagramCanvas<'a> {
}
#[derive(Default)]
pub struct State {
work: Option<Arc<crate::app::allocation_drag::Press>>,
work_cache: RefCell<Option<Arc<Scene>>>,
pointer: Option<Point>,
keyboard_focus: bool,
drag: Option<(Id, Point, Position)>,
preview: Option<Position>,
pan_start: Option<(mouse::Button, Point)>,
@@ -66,6 +71,7 @@ pub struct State {
cache: RefCell<Option<CachedScene>>,
}
struct Scene {
work: Option<Arc<crate::app::allocation_drag::Preview>>,
view: ProjectedView,
routed: Arc<RoutedView>,
}
@@ -452,6 +458,26 @@ impl DiagramCanvas<'_> {
}
}
fn scene(&self, state: &State) -> Arc<Scene> {
if let Some(preview) = self.work_preview()
&& state
.work
.as_ref()
.is_some_and(|p| p.token == preview.token)
{
if let Some(scene) = state.work_cache.borrow().as_ref()
&& scene.work.as_ref().is_some_and(|p| Arc::ptr_eq(p, preview))
{
return scene.clone();
}
let scene = Arc::new(Scene {
work: Some(preview.clone()),
view: preview.placement.view.clone(),
routed: preview.routed.clone(),
});
*state.work_cache.borrow_mut() = Some(scene.clone());
return scene;
}
*state.work_cache.borrow_mut() = None;
let preview = if state.context == Some(self.context) {
state.preview
} else {
@@ -498,7 +524,11 @@ impl DiagramCanvas<'_> {
route_diagram(self.project, &diagram, &view)
},
);
let scene = Arc::new(Scene { view, routed });
let scene = Arc::new(Scene {
work: None,
view,
routed,
});
*state.cache.borrow_mut() = Some(CachedScene {
context: self.context,
preview,
@@ -529,7 +559,26 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Option<Action<Message>> {
// A completed work click retires App's allocation epoch before the
// retained canvas sees a redraw. Its already-idle press must not eat
// the first Delete. A live or not-yet-dispatched press stays guarded.
if matches!(event, canvas::Event::Keyboard(iced::keyboard::Event::KeyPressed { key, .. })
if *key == iced::keyboard::Key::Named(iced::keyboard::key::Named::Delete))
&& self.allocation.is_some_and(|capability| {
capability.clean
&& state
.work
.as_ref()
.is_some_and(|press| press.stamp.epoch != capability.state.epoch)
})
{
state.work = None;
}
if let Some(action) = self.work_lifetime(state, event, bounds) {
return Some(action);
}
if state.context != Some(self.context) {
state.work = None;
state.pointer = None;
state.port_drag = None;
state.connection_press = None;
@@ -595,9 +644,6 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
let local = cursor
.position()
.map(|p| Point::new(p.x - bounds.x, p.y - bounds.y));
if matches!(event, canvas::Event::Mouse(mouse::Event::ButtonPressed(_))) {
state.keyboard_focus = cursor.is_over(bounds);
}
match event {
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right))
if cursor.is_over(bounds) =>
@@ -617,7 +663,8 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
}
canvas::Event::Keyboard(iced::keyboard::Event::KeyPressed {
key, modifiers, ..
}) if state.keyboard_focus => {
}) => {
// The mounted focus::Owner is the sole keyboard admission gate.
use iced::keyboard::{Key, key::Named};
match key.as_ref() {
Key::Named(Named::F2)
@@ -672,10 +719,37 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
Key::Named(Named::Delete)
if self.editable
&& self.connection.is_none()
&& modifiers.is_empty()
&& self.selected_bend.is_some() =>
&& !self.placing
&& state.drag.is_none()
&& state.route_drag.is_none()
&& state.port_drag.is_none()
&& state.pan_start.is_none()
&& state.work.is_none()
&& (modifiers.is_empty()
|| *modifiers == iced::keyboard::Modifiers::SHIFT) =>
{
Some(Action::publish(Message::Route(RouteEvent::RemoveBend)).and_capture())
// An invalid/stale bend never falls through to whole-item removal.
if self.selected_bend.is_some() {
return modifiers.is_empty().then(|| {
Action::publish(Message::Route(RouteEvent::RemoveBend))
.and_capture()
});
}
let request = self.selection_context_request(state, bounds);
if request.object == self.diagram {
return None;
}
Some(
Action::publish(Message::DiagramRemove(
crate::app::diagram_removal::Intent {
context: self.context,
object: request.object,
placement: request.placement,
model: modifiers.shift(),
},
))
.and_capture(),
)
}
_ => None,
}
@@ -716,6 +790,22 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
let scene = self.scene(state);
let view = &scene.view;
let world = self.world(p);
if self.work_dirty_press(view, &scene.routed, p) {
state.work = None;
state.drag = None;
state.preview = None;
state.port_drag = None;
state.route_drag = None;
return Some(
Action::publish(Message::WorkDrag(
crate::app::allocation_drag::Event::Refused(
self.allocation.unwrap().state.epoch,
crate::app::allocation_drag::FINISH_EDIT.into(),
),
))
.and_capture(),
);
}
if self.placing && self.editable {
return Some(
Action::publish(Message::Architecture(
@@ -797,6 +887,16 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
return Some(Action::publish(Message::Select(port.element)).and_capture());
}
if let Some(id) = self.hit(view, p) {
if self.work_eligible(id) {
return Some(self.begin_work(
state,
id,
cursor.position()?,
bounds,
view,
&scene.routed,
));
}
let position = self
.project
.diagrams
@@ -835,6 +935,18 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
}
}
canvas::Event::Mouse(mouse::Event::CursorMoved { .. }) => {
if let Some(press) = &state.work {
return Some(
Action::publish(Message::WorkDrag(
crate::app::allocation_drag::Event::Preview(
press.stamp,
press.token,
cursor.position(),
),
))
.and_capture(),
);
}
let p = local?;
if let Some((button, start)) = state.pan_start {
state.pan_start = Some((button, p));
@@ -867,6 +979,18 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
None
}
canvas::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
if let Some(press) = state.work.take() {
return Some(
Action::publish(Message::WorkDrag(
crate::app::allocation_drag::Event::Release(
press.stamp,
press.token,
cursor.position(),
),
))
.and_capture(),
);
}
if let Some((button, start)) = state.pan_start {
if button == mouse::Button::Middle {
return Some(Action::capture());
@@ -1013,6 +1137,10 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
f.translate(self.pan);
f.scale(self.zoom);
let scene = self.scene(state);
let project = scene
.work
.as_ref()
.map_or(self.project, |p| p.semantic.project());
let view = &scene.view;
let containers = view
.nodes
@@ -1021,10 +1149,10 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
.collect::<BTreeSet<_>>();
for n in &view.nodes {
if containers.contains(&n.id) {
paint_node(&mut f, self.project, n, self.selected, true);
paint_node(&mut f, project, n, self.selected, true);
}
}
let highlighted = highlighted_exchanges(self.project, self.selected);
let highlighted = highlighted_exchanges(project, self.selected);
for edge in &view.edges {
let Some(routed) = scene.routed.edges.get(&edge.id) else {
continue;
@@ -1047,7 +1175,7 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
} else {
Color::from_rgb8(144, 158, 173)
};
let capability_label = relationship_stereotype(self.project, edge.id);
let capability_label = relationship_stereotype(project, edge.id);
let mut stroke =
Stroke::default()
.with_color(color)
@@ -1095,7 +1223,7 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
..Default::default()
});
}
if let Some(relation) = self.project.relations.get(&edge.id) {
if let Some(relation) = project.relations.get(&edge.id) {
for end in routing::association_end_geometry(relation, routed) {
if end.navigable {
let [a, tip, b] = navigation_mark(end.tip, end.inward);
@@ -1129,13 +1257,13 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
}
for n in &view.nodes {
if !containers.contains(&n.id) {
paint_node(&mut f, self.project, n, self.selected, false);
paint_node(&mut f, project, n, self.selected, false);
} else {
// Container headers stay readable when relationships traverse
// the allocation enclosure. Children remain on top.
let mut header = n.clone();
header.size.height = 62.;
paint_node(&mut f, self.project, &header, self.selected, true);
paint_node(&mut f, project, &header, self.selected, true);
}
}
for port in &view.ports {
@@ -1143,17 +1271,17 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
style::TEAL
} else {
style::kind_color(
self.project.elements[&port.element]
project.elements[&port.element]
.parent
.and_then(|id| self.project.elements.get(&id))
.and_then(|id| project.elements.get(&id))
.map(|e| e.kind())
.unwrap_or(Kind::Port),
)
};
let origin = Point::new(port.position.x - 7., port.position.y - 7.);
let glyph = port_glyph(&self.project.elements[&port.element]);
let glyph = port_glyph(&project.elements[&port.element]);
let path = if glyph == PortGlyph::Function {
let corners = port_triangle(&self.project.elements[&port.element], port);
let corners = port_triangle(&project.elements[&port.element], port);
Path::new(|p| {
p.move_to(corners[0]);
p.line_to(corners[1]);
@@ -1183,7 +1311,7 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
if matches!(glyph, PortGlyph::Flow(_)) {
f.stroke(
&Path::new(|p| {
for [a, b] in flow_mark(&self.project.elements[&port.element], port) {
for [a, b] in flow_mark(&project.elements[&port.element], port) {
p.move_to(a);
p.line_to(b);
}
@@ -1195,14 +1323,6 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
f.fill(&Path::circle(center, 1.5), color);
}
}
if let Some(bounds) = self.navigation_focus {
f.stroke(
&Path::rectangle(bounds.position(), bounds.size()),
Stroke::default()
.with_color(style::TEAL)
.with_width(2.5 / self.zoom),
);
}
if let Some(edge) = scene.routed.edges.get(&self.selected)
&& !edge.custom_suspended
{
@@ -1353,7 +1473,8 @@ impl canvas::Program<Message> for DiagramCanvas<'_> {
) -> mouse::Interaction {
if (self.connection.is_some() || self.placing) && cursor.is_over(bounds) {
mouse::Interaction::Crosshair
} else if state.drag.is_some()
} else if state.work.is_some()
|| state.drag.is_some()
|| state.pan_start.is_some()
|| state.route_drag.is_some()
|| state.port_drag.is_some()
@@ -1910,9 +2031,9 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
diagram,
selected: p.id,
navigation_focus: None,
zoom: 1.,
pan: Vector::ZERO,
};
@@ -1985,9 +2106,9 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
diagram,
selected: p.id,
navigation_focus: None,
zoom: 0.6,
pan: Vector::new(10., 20.),
};
@@ -2104,13 +2225,13 @@ mod tests {
diagram,
context,
selected: p.id,
navigation_focus: None,
selected_bend: None,
zoom,
pan: Vector::new(20., 30.),
editable: true,
placing: false,
connection: Some(&session),
allocation: None,
};
let bounds = Rectangle::new(Point::new(260., 300.), Size::new(2400., 1600.));
let at = |port: &oa_core::projection::ProjectedPort| {
@@ -2184,6 +2305,7 @@ mod tests {
armed.start(&p, &view, source.element);
let armed_canvas = DiagramCanvas {
connection: Some(&armed),
allocation: None,
..canvas
};
// Winit updates cursor coordinates through CursorMoved, not the
@@ -2213,6 +2335,7 @@ mod tests {
// A tool cancellation or navigation invalidates a queued release.
let cancelled = DiagramCanvas {
connection: None,
allocation: None,
context: Context {
epoch: 1,
..context
@@ -2272,7 +2395,6 @@ mod tests {
view_index: None,
diagram,
selected: edge,
navigation_focus: None,
zoom,
pan: Vector::new(150., 300.),
context: Context {
@@ -2285,6 +2407,7 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
};
let mut state = State::default();
let pin = Point::new(400. * zoom + 150., -100. * zoom + 300.);
@@ -2348,7 +2471,6 @@ mod tests {
view_index: None,
diagram,
selected: edge,
navigation_focus: None,
zoom: 0.5,
pan: Vector::new(150., 300.),
context: Context {
@@ -2361,6 +2483,7 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
};
let mut state = State::default();
let pin = Point::new(350., 250.);
@@ -2445,7 +2568,6 @@ mod tests {
view_index: None,
diagram,
selected: edge,
navigation_focus: None,
zoom: 1.,
pan: Vector::new(150., 300.),
context: Context {
@@ -2458,6 +2580,7 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
};
let mut state = State::default();
let first = canvas.scene(&state);
@@ -2573,7 +2696,6 @@ mod tests {
view_index: None,
diagram,
selected: edge,
navigation_focus: None,
zoom: 0.7,
pan: Vector::new(350., 350.),
context: Context {
@@ -2586,6 +2708,7 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
};
for end in ends {
assert!(svg.contains(&format!(
@@ -2627,7 +2750,6 @@ mod tests {
view_index: None,
diagram,
selected: p.id,
navigation_focus: None,
zoom: 1.,
pan: Vector::new(100., 400.),
context: Context {
@@ -2640,6 +2762,7 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
};
let mut state = State::default();
let scene = canvas.scene(&state);
@@ -2701,7 +2824,6 @@ mod tests {
view_index: None,
diagram,
selected: edge,
navigation_focus: None,
zoom: 1.,
pan: Vector::new(100., 400.),
context: Context {
@@ -2714,6 +2836,7 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
};
assert!(
matches!(pointer(&canvas,&mut state,mouse::Event::ButtonPressed(mouse::Button::Left),point(cover)+canvas.pan),Some(Message::SelectNode(id)) if id==node.id)
@@ -2734,7 +2857,6 @@ mod tests {
view_index: None,
diagram,
selected,
navigation_focus: None,
zoom: 1.,
pan: Vector::ZERO,
context: Context {
@@ -2747,6 +2869,7 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
};
let span = &routed.edges[&edge].points;
let pick = point(oa_core::routing::point_along_polyline(span, 0.4).unwrap());
+244
View File
@@ -0,0 +1,244 @@
//! Iced focus ownership shared by architecture and persisted state canvases.
//! Focus operations (including clean Inspector focus) unfocus this widget.
use crate::route_edit::Context;
use iced::advanced::widget::{Operation, Tree, operation};
use iced::advanced::{Clipboard, Layout, Shell, Widget, layout, overlay, renderer};
use iced::{Element, Event as InputEvent, Length, Point, Rectangle, Size, Theme, Vector, mouse};
#[derive(Default)]
struct Input {
context: Option<Context>,
focused: bool,
traversing: bool,
pointer: Option<Point>,
}
impl operation::Focusable for Input {
fn is_focused(&self) -> bool {
self.focused
}
fn focus(&mut self) {
self.focused = true;
self.traversing = false;
}
fn unfocus(&mut self) {
self.focused = false;
self.traversing = false;
}
}
struct Owner<'a, Message, R: renderer::Renderer> {
context: Context,
enabled: bool,
traverse: Box<dyn Fn(bool) -> Message + 'a>,
content: Element<'a, Message, Theme, R>,
}
pub fn wrap<'a, Message: 'a, R: renderer::Renderer + 'a>(
content: impl Into<Element<'a, Message, Theme, R>>,
context: Context,
enabled: bool,
traverse: impl Fn(bool) -> Message + 'a,
) -> Element<'a, Message, Theme, R> {
Element::new(Owner {
context,
enabled,
traverse: Box::new(traverse),
content: content.into(),
})
}
impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Owner<'_, Message, R> {
fn tag(&self) -> iced::advanced::widget::tree::Tag {
iced::advanced::widget::tree::Tag::of::<Input>()
}
fn state(&self) -> iced::advanced::widget::tree::State {
iced::advanced::widget::tree::State::new(Input {
context: Some(self.context),
..Default::default()
})
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(self.content.as_widget())]
}
fn diff(&self, tree: &mut Tree) {
let state = tree.state.downcast_mut::<Input>();
if state.context != Some(self.context) || !self.enabled {
state.focused = false;
state.traversing = false;
state.pointer = None;
}
state.context = Some(self.context);
tree.diff_children(std::slice::from_ref(&self.content));
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(&mut self, tree: &mut Tree, renderer: &R, limits: &layout::Limits) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
operation: &mut dyn Operation,
) {
if self.enabled {
operation.focusable(
Some(&iced::advanced::widget::Id::from("diagram-keyboard-owner")),
layout.bounds(),
tree.state.downcast_mut::<Input>(),
);
}
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &InputEvent,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
let state = tree.state.downcast_mut::<Input>();
if let InputEvent::Mouse(mouse::Event::CursorMoved { position }) = event {
state.pointer = Some(*position);
}
if matches!(
event,
InputEvent::Window(iced::window::Event::Unfocused | iced::window::Event::Resized(_))
) || !self.enabled
{
state.focused = false;
state.traversing = false;
state.pointer = None;
}
if matches!(event, InputEvent::Mouse(mouse::Event::ButtonPressed(_))) {
state.traversing = false;
let pointer = state.pointer.or_else(|| cursor.position());
state.focused = self.enabled
&& !shell.is_event_captured()
&& cursor.position().is_some()
&& pointer.is_some_and(|p| {
layout
.bounds()
.intersection(viewport)
.is_some_and(|b| b.contains(p))
});
}
if let InputEvent::Keyboard(iced::keyboard::Event::KeyPressed {
key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Tab),
modifiers,
..
}) = event
&& state.focused
&& !state.traversing
&& self.enabled
&& !shell.is_event_captured()
&& (*modifiers == iced::keyboard::Modifiers::SHIFT || modifiers.is_empty())
{
// The focus task runs after the native batch. Retain focus for its
// traversal count, but reject later keys in this same batch now.
state.traversing = true;
shell.publish((self.traverse)(modifiers.shift()));
shell.capture_event();
return;
}
if matches!(event, InputEvent::Keyboard(_))
&& (!state.focused || state.traversing || !self.enabled)
{
return;
}
if shell.is_event_captured() {
return;
}
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
fn draw(
&self,
tree: &Tree,
renderer: &mut R,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
let state = tree.state.downcast_ref::<Input>();
if state.focused && !state.traversing && self.enabled {
renderer.fill_quad(
renderer::Quad {
bounds: layout.bounds(),
border: iced::Border {
color: crate::style::TEAL,
width: 1.,
..Default::default()
},
..Default::default()
},
iced::Color::TRANSPARENT,
);
}
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &R,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'b>,
renderer: &R,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, R>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
@@ -57,7 +57,6 @@ fn canvas(app: &App) -> DiagramCanvas<'_> {
view_index: None,
diagram: app.active_diagram.unwrap(),
selected: app.selected,
navigation_focus: None,
zoom: 1.,
pan: app.pan,
context: app.route_context().unwrap(),
@@ -65,6 +64,7 @@ fn canvas(app: &App) -> DiagramCanvas<'_> {
editable: true,
placing: false,
connection: app.connection.as_ref(),
allocation: None,
}
}
fn screen(app: &App, id: Id) -> Point {
@@ -65,7 +65,6 @@ fn canvas(app: &App, zoom: f32) -> DiagramCanvas<'_> {
view_index: None,
diagram: app.active_diagram.unwrap(),
selected: app.selected,
navigation_focus: None,
zoom,
pan: app.pan,
context: app.route_context().unwrap(),
@@ -73,6 +72,7 @@ fn canvas(app: &App, zoom: f32) -> DiagramCanvas<'_> {
editable: true,
placing: false,
connection: app.connection.as_ref(),
allocation: None,
}
}
fn event(
@@ -6,7 +6,6 @@ fn canvas(project: &Project, diagram: Id, zoom: f32) -> DiagramCanvas<'_> {
view_index: None,
diagram,
selected: Id::nil(),
navigation_focus: None,
zoom,
pan: Vector::new(17., 23.),
context: Context {
@@ -19,6 +18,7 @@ fn canvas(project: &Project, diagram: Id, zoom: f32) -> DiagramCanvas<'_> {
editable: true,
placing: false,
connection: None,
allocation: None,
}
}
+4 -1
View File
@@ -58,6 +58,9 @@ impl canvas::Program<Message> for PortLabels<'_> {
bounds: Rectangle,
cursor: mouse::Cursor,
) -> Vec<canvas::Geometry> {
if self.0.work_preview().is_some() {
return vec![]; // The candidate canvas already paints its own ports.
}
if state.context == Some(self.0.context) && state.held_buttons != 0 {
return vec![];
}
@@ -178,7 +181,6 @@ mod tests {
view_index: None,
diagram: app.active_diagram.unwrap(),
selected: app.selected,
navigation_focus: None,
zoom: 1.,
pan: Vector::ZERO,
context: app.route_context().unwrap(),
@@ -186,6 +188,7 @@ mod tests {
editable: true,
placing: false,
connection: None,
allocation: None,
})
}
+205
View File
@@ -0,0 +1,205 @@
use super::*;
use crate::app::allocation_drag::{self as input, Event, Press, Stamp};
impl DiagramCanvas<'_> {
pub(crate) fn work_dirty_point(&self, bounds: Rectangle, screen: Point) -> bool {
let diagram = &self.project.diagrams[&self.diagram];
let view = self.projected(diagram);
let routed = routing::route_diagram(self.project, diagram, &view);
self.work_dirty_press(
&view,
&routed,
Point::new(screen.x - bounds.x, screen.y - bounds.y),
)
}
pub(super) fn work_preview(&self) -> Option<&Arc<input::Preview>> {
let capability = self.allocation?;
let feedback = capability.state.feedback.as_ref()?;
(capability.clean
&& feedback.press.stamp.context == self.context
&& feedback.press.stamp.epoch == capability.state.epoch
&& feedback.press.stamp.pan == self.pan
&& feedback.press.stamp.zoom == self.zoom)
.then_some(capability.state.preview.as_ref())
.flatten()
}
pub(super) fn work_eligible(&self, placement: Id) -> bool {
self.allocation.is_some()
&& self.project.diagrams[&self.diagram].projection == ProjectionKind::Allocation
&& self.project.diagrams[&self.diagram]
.nodes
.get(&placement)
.and_then(|n| self.project.elements.get(&n.element))
.is_some_and(|e| e.kind().is_work())
}
pub(super) fn work_dirty_press(
&self,
view: &ProjectedView,
routed: &RoutedView,
local: Point,
) -> bool {
self.allocation.is_some_and(|c| !c.clean)
&& !self.placing
&& self.connection.is_none()
&& self.project.diagrams[&self.diagram].projection == ProjectionKind::Allocation
&& (self.hit(view, local).is_some()
|| self.hit_port(view, local).is_some()
|| self.hit_edge(routed, local).is_some()
|| self.hit_label(routed, local).is_some()
|| self.hit_association_label(routed, local).is_some())
}
pub(super) fn begin_work(
&self,
state: &mut State,
node: Id,
screen: Point,
bounds: Rectangle,
view: &ProjectedView,
routed: &RoutedView,
) -> Action<Message> {
let capability = self.allocation.unwrap();
state.drag = None;
state.preview = None;
state.port_drag = None;
state.route_drag = None;
if !capability.clean {
return Action::publish(Message::WorkDrag(Event::Refused(
capability.state.epoch,
input::FINISH_EDIT.into(),
)))
.and_capture();
}
let work = self.project.diagrams[&self.diagram].nodes[&node].element;
let scope = match crate::allocation_drag::capture(self.project, self.diagram, work, node) {
Ok(scope) => scope,
Err(reason) => {
return Action::publish(Message::WorkDrag(Event::Refused(
capability.state.epoch,
input::refusal(&reason),
)))
.and_capture();
}
};
let frozen = input::Frozen::capture(self.project, &scope, view, routed, self.zoom);
let press = Arc::new(Press {
stamp: Stamp {
context: self.context,
epoch: capability.state.epoch,
snapshot: capability.snapshot,
bounds,
pan: self.pan,
zoom: self.zoom,
},
token: Id::new_v4(),
start: screen,
scope,
frozen,
arrange: capability.state.arrange_next,
});
state.work = Some(press.clone());
Action::publish(Message::WorkDrag(Event::Press(press))).and_capture()
}
pub(super) fn work_lifetime(
&self,
state: &mut State,
event: &canvas::Event,
bounds: Rectangle,
) -> Option<Action<Message>> {
let press = state.work.as_ref()?;
let cancel = self
.allocation
.is_none_or(|c| !c.clean || c.state.epoch != press.stamp.epoch)
|| press.stamp.context != self.context
|| press.stamp.bounds != bounds
|| press.stamp.pan != self.pan
|| press.stamp.zoom != self.zoom
|| matches!(
event,
canvas::Event::Window(iced::window::Event::Unfocused)
| canvas::Event::Mouse(mouse::Event::CursorLeft)
| canvas::Event::Mouse(mouse::Event::ButtonPressed(
mouse::Button::Middle | mouse::Button::Right
))
| canvas::Event::Mouse(mouse::Event::WheelScrolled { .. })
)
|| matches!(event, canvas::Event::Keyboard(iced::keyboard::Event::KeyPressed { key, .. })
if *key == iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape));
if cancel {
let token = press.token;
state.work = None;
state.pointer = None;
return Some(Action::publish(Message::WorkDrag(Event::Cancel(token))).and_capture());
}
None
}
}
/// Separate passive layer: frozen target labels remain above all candidate card
/// text. It does not acquire input or use a second independent semantic scene.
pub struct WorkFeedback<'a>(pub DiagramCanvas<'a>);
impl canvas::Program<Message> for WorkFeedback<'_> {
type State = ();
fn draw(
&self,
_: &(),
renderer: &Renderer,
_: &Theme,
bounds: Rectangle,
_: mouse::Cursor,
) -> Vec<canvas::Geometry> {
let Some(capability) = self.0.allocation else {
return vec![];
};
let Some(feedback) = &capability.state.feedback else {
return vec![];
};
if feedback.press.stamp.epoch != capability.state.epoch
|| feedback.press.stamp.context != self.0.context
|| feedback.press.stamp.bounds != bounds
{
return vec![];
}
let mut frame = Frame::new(renderer, bounds.size());
let color = if feedback.refused {
Color::from_rgb8(173, 66, 41)
} else {
style::TEAL
};
for index in &feedback.targets {
let target = &feedback.press.frozen.targets[*index];
let region = target.region;
let top = Point::new(
region.x * self.0.zoom + self.0.pan.x,
region.y * self.0.zoom + self.0.pan.y,
);
frame.stroke(
&Path::rectangle(
top,
iced::Size::new(region.width * self.0.zoom, region.height * self.0.zoom),
),
Stroke::default().with_color(color).with_width(3.),
);
let label = target.label;
let top = Point::new(
label.position.x * self.0.zoom + self.0.pan.x,
label.position.y * self.0.zoom + self.0.pan.y,
);
frame.fill_rectangle(
top,
iced::Size::new(
label.size.width * self.0.zoom,
label.size.height * self.0.zoom,
),
Color::WHITE,
);
frame.fill_text(Text {
content: target.name.clone(),
position: top,
size: (16. * self.0.zoom).into(),
color,
..Default::default()
});
}
vec![frame.into_geometry()]
}
}
-472
View File
@@ -1,472 +0,0 @@
//! Read-only identities for objects actually represented by a diagram renderer.
use iced::Rectangle;
use oa_core::{Id, OccurrenceEndpoint, Project, projection, routing, view_options::ViewIndex};
pub(crate) mod view;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Context {
pub document: Id,
pub revision: u64,
pub subject: Id,
}
#[derive(Debug, Clone)]
pub(crate) enum Event {
Open(Context),
Close(Id),
Search(Id, String),
Page(Id, usize),
Destination(Id, Option<Surface>),
Choose(Id, Usage),
Move(Id, i8),
Activate(Id),
}
/// One completed immutable accepted-model lookup. The token owns one worker slot.
#[derive(Debug, Clone)]
pub(crate) struct Completion {
pub token: Id,
pub context: Context,
pub result: Result<Vec<Usage>, String>,
}
pub(crate) struct Panel {
pub token: Id,
pub context: Context,
pub usages: Vec<Usage>,
pub loading: bool,
pub search: String,
pub page: usize,
pub cursor: usize,
pub destination: Option<Surface>,
pub notice: Option<String>,
}
impl Panel {
pub fn new(context: Context, usages: Vec<Usage>) -> Self {
Self {
token: Id::new_v4(),
context,
usages,
loading: false,
search: String::new(),
page: 0,
cursor: 0,
destination: None,
notice: None,
}
}
pub fn matches<'a>(&'a self, p: &Project) -> Vec<&'a Usage> {
let query = self.search.to_lowercase();
if query.is_empty() {
return self.usages.iter().collect();
}
self.usages
.iter()
.filter(|usage| {
let surface = usage.surface;
let searchable = format!(
"{} {} {} {} {}",
surface.category(p),
p.named(surface.id()),
alias(p, surface.id()),
target_name(p, usage),
usage.role
);
searchable.to_lowercase().contains(&query)
})
.collect()
}
pub fn choices(&self, p: &Project) -> Vec<Event> {
if self.loading {
return Vec::new();
}
let matches = self.matches(p);
if let Some(surface) = self.destination {
matches
.into_iter()
.filter(|u| u.surface == surface)
.map(|u| Event::Choose(self.token, u.clone()))
.collect()
} else {
let mut seen = std::collections::BTreeSet::new();
matches
.into_iter()
.filter(|u| seen.insert(u.surface))
.map(|u| Event::Destination(self.token, Some(u.surface)))
.collect()
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Surface {
Saved(Id),
Process(Id),
Scenario(Id),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Target {
Whole,
Placement(Id),
Port {
port: Id,
placement: Id,
},
Edge(Id),
StateRow {
placement: Id,
relation: Id,
},
AllocationGrouping {
relation: Id,
work_placement: Id,
performer_placement: Id,
},
ProcessOccurrence(OccurrenceEndpoint),
ProcessLink(Id),
ProcessPreviewLink {
relation: Id,
source: OccurrenceEndpoint,
target: OccurrenceEndpoint,
},
ScenarioObject(Id),
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Usage {
pub subject: Id,
pub surface: Surface,
pub target: Target,
/// Concise, truthful explanation, e.g. "action occurrence" or "entry action".
pub role: String,
/// Actual current renderer coordinates. Recompute before activation.
pub bounds: Rectangle,
}
/// A navigation highlight is presentation state, never an edit/Delete target.
pub(crate) struct Focus {
pub context: Context,
pub usage: Usage,
pub selected: Id,
}
impl Surface {
pub fn id(self) -> Id {
match self {
Self::Saved(id) | Self::Process(id) | Self::Scenario(id) => id,
}
}
pub fn category(self, p: &Project) -> &'static str {
match self {
Self::Saved(id)
if p.diagrams
.get(&id)
.is_some_and(|d| d.projection.state_machine().is_some()) =>
{
"State views"
}
Self::Saved(_) => "Architecture",
Self::Process(_) => "Processes and chains",
Self::Scenario(_) => "Scenarios",
}
}
}
pub(crate) fn collect(
p: &Project,
subject: Id,
process: &crate::behavior::topology::State,
scenario: &crate::behavior::scenario::State,
) -> Vec<Usage> {
let mut usages = saved_usages(p, subject);
for element in p.elements.values() {
match element.kind() {
oa_core::Kind::Process | oa_core::Kind::FunctionalChain => {
usages.extend(process.diagram_usages(p, element.id, subject));
}
oa_core::Kind::Scenario => {
usages.extend(scenario.diagram_usages(p, element.id, subject));
}
_ => {}
}
}
usages.sort_by_cached_key(|u| {
(
u.surface.category(p),
p.named(u.surface.id()).to_lowercase(),
u.surface,
target_name(p, u).to_lowercase(),
)
});
usages
.dedup_by(|a, b| a.subject == b.subject && a.surface == b.surface && a.target == b.target);
usages
}
pub(crate) fn alias(p: &Project, id: Id) -> &str {
p.elements
.get(&id)
.map(|e| e.alias.as_str())
.or_else(|| p.relations.get(&id).map(|r| r.alias.as_str()))
.or_else(|| p.diagrams.get(&id).map(|d| d.alias.as_str()))
.or_else(|| p.traces.get(&id).map(|t| t.alias.as_str()))
.or_else(|| {
p.diagrams
.values()
.find_map(|d| d.nodes.get(&id).map(|n| n.alias.as_str()))
})
.unwrap_or("")
}
pub(crate) fn target_name(p: &Project, usage: &Usage) -> String {
let id = match &usage.target {
Target::Whole => usage.surface.id(),
Target::Placement(id) => p
.diagrams
.get(&usage.surface.id())
.and_then(|d| d.nodes.get(id))
.map_or(*id, |n| n.element),
Target::Port { port, .. } => *port,
Target::Edge(id)
| Target::StateRow { relation: id, .. }
| Target::AllocationGrouping { relation: id, .. }
| Target::ProcessLink(id)
| Target::ScenarioObject(id) => *id,
Target::ProcessOccurrence(endpoint) => {
return endpoint
.references
.iter()
.copied()
.chain([endpoint.occurrence])
.map(|id| format!("{} (@{})", p.named(id), alias(p, id)))
.collect::<Vec<_>>()
.join(" / ");
}
Target::ProcessPreviewLink {
relation, source, ..
} => {
return source
.references
.iter()
.copied()
.chain([*relation])
.map(|id| format!("{} (@{})", p.named(id), alias(p, id)))
.collect::<Vec<_>>()
.join(" / ");
}
};
format!("{} (@{})", p.named(id), alias(p, id))
}
/// Saved view membership is the renderer's final projection, including folds,
/// projection-kind exclusions and explicit view filters. Stored route metadata
/// and merely having both relation endpoints placed do not imply visibility.
pub(crate) fn saved_usages(p: &Project, subject: Id) -> Vec<Usage> {
saved_usages_for(p, subject, None)
}
/// Revalidate only the requested saved surface before activation. The optional
/// filter is applied before projection and routing, never after a whole lookup.
pub(crate) fn saved_usages_for(p: &Project, subject: Id, only_diagram: Option<Id>) -> Vec<Usage> {
if only_diagram.is_some_and(|id| !p.diagrams.contains_key(&id)) {
return Vec::new();
}
let index = ViewIndex::new(p);
let mut usages = Vec::new();
for diagram in p
.diagrams
.values()
.filter(|diagram| only_diagram.is_none_or(|id| diagram.id == id))
{
let view = projection::project_diagram_with_index(p, diagram, &index);
let surface = Surface::Saved(diagram.id);
if subject == diagram.id || diagram.projection.state_machine() == Some(subject) {
usages.push(Usage {
subject,
surface,
target: Target::Whole,
role: if subject == diagram.id {
"diagram"
} else {
"state machine view"
}
.into(),
bounds: routed_bounds(routing::route_diagram(p, diagram, &view).bounds),
});
}
for node in &view.nodes {
if subject == node.element || subject == node.id {
usages.push(Usage {
subject,
surface,
target: Target::Placement(node.id),
role: "node".into(),
bounds: Rectangle {
x: node.position.x,
y: node.position.y,
// Reveal the labelled header, not the empty interior of
// a large expanded container at the minimum zoom.
width: node.size.width.min(420.),
height: node.size.height.min(64.),
},
});
}
}
for port in &view.ports {
if subject == port.element {
usages.push(Usage {
subject,
surface,
target: Target::Port {
port: port.element,
placement: port.owner,
},
role: "port".into(),
bounds: Rectangle {
x: port.position.x - 12.,
y: port.position.y - 12.,
width: 24.,
height: 24.,
},
});
}
}
// Allocation arrows are suppressed in this projection. A direct
// relation is represented only by its actual visible containment chain;
// aggregate summaries never manufacture inherited relations.
if diagram.projection == oa_core::ProjectionKind::Allocation
&& let Some(relation) = p.relations.get(&subject)
&& relation.kind() == oa_core::RelationKind::Allocation
{
let placements: std::collections::BTreeMap<_, _> =
view.nodes.iter().map(|node| (node.id, node)).collect();
for work in view.nodes.iter().filter(|n| n.element == relation.target()) {
let mut parent = work.visual_parent;
let mut seen = std::collections::BTreeSet::new();
while let Some(id) = parent.filter(|id| seen.insert(*id)) {
let Some(performer) = placements.get(&id) else {
break;
};
if performer.element == relation.source() {
usages.push(Usage {
subject,
surface,
target: Target::AllocationGrouping {
relation: subject,
work_placement: work.id,
performer_placement: performer.id,
},
role: "allocation grouping".into(),
bounds: Rectangle {
x: work.position.x,
y: work.position.y,
width: work.size.width.min(420.),
height: work.size.height.min(64.),
},
});
break;
}
parent = performer.visual_parent;
}
}
}
if view.edges.iter().any(|edge| edge.id == subject)
&& let Some(edge) = routing::route_diagram(p, diagram, &view)
.edges
.get(&subject)
{
usages.push(Usage {
subject,
surface,
target: Target::Edge(subject),
role: "relationship".into(),
bounds: edge_focus_bounds(edge),
});
}
if diagram.projection.state_machine().is_some() {
usages.extend(crate::behavior::state_canvas::diagram_usages(
p, diagram, &view, subject,
));
}
}
usages
}
pub(crate) fn routed_bounds(bounds: routing::RoutingBounds) -> Rectangle {
Rectangle {
x: bounds.position.x,
y: bounds.position.y,
width: bounds.size.width,
height: bounds.size.height,
}
}
/// Focus a named edge at its label. For an unlabelled line, focus its middle
/// segment instead of shrinking a long connector to fit the whole diagram.
pub(crate) fn edge_focus_bounds(edge: &routing::RoutedEdge) -> Rectangle {
if !edge.label.text.is_empty() {
return routed_bounds(edge.label.bounds);
}
let point = edge
.points
.get(edge.points.len() / 2)
.copied()
.unwrap_or(edge.label.center);
Rectangle {
x: point.x - 40.,
y: point.y - 24.,
width: 80.,
height: 48.,
}
}
/// Whole-canvas navigation fits its entire extent; an individual target keeps
/// the readable minimum zoom of `camera` rather than shrinking unrelated space.
pub(crate) fn camera_for(
target: &Target,
bounds: Rectangle,
viewport: iced::Size,
) -> (f32, iced::Vector) {
if !matches!(target, Target::Whole) {
return camera(bounds, viewport);
}
let available = iced::Size::new(
(viewport.width - 64.).max(1.),
(viewport.height - 64.).max(1.),
);
let zoom = (available.width / bounds.width.max(1.))
.min(available.height / bounds.height.max(1.))
.clamp(0.0001, 1.25);
let pan = iced::Vector::new(
viewport.width / 2. - bounds.center_x() * zoom,
viewport.height / 2. - bounds.center_y() * zoom,
);
(zoom, pan)
}
/// Return a readable, centered camera without modifying authored geometry.
pub(crate) fn camera(bounds: Rectangle, viewport: iced::Size) -> (f32, iced::Vector) {
let available = iced::Size::new(
(viewport.width - 64.).max(1.),
(viewport.height - 64.).max(1.),
);
let zoom = (available.width / bounds.width.max(1.))
.min(available.height / bounds.height.max(1.))
.clamp(0.5, 1.25);
let pan = iced::Vector::new(
viewport.width / 2. - bounds.center_x() * zoom,
viewport.height / 2. - bounds.center_y() * zoom,
);
(zoom, pan)
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod coverage_tests;
@@ -1,386 +0,0 @@
//! Independent allocation membership oracles. Expected targets and coordinates
//! come from handwritten fixtures, never from the usage predicate under test.
use super::{Surface, Target, Usage, saved_usages, saved_usages_for};
use iced::Rectangle;
use oa_core::{
Id, Kind, Layer, Position, Project, ProjectionKind, RelationKind, Size, projection, validation,
};
struct AllocationFixture {
project: Project,
diagram: Id,
performer: Id,
work: Id,
relation: Id,
performer_node: Id,
work_node: Id,
}
fn assert_valid(project: &Project) {
let errors: Vec<_> = validation::validate(project)
.into_iter()
.filter(|issue| issue.severity == validation::Severity::Error)
.collect();
assert!(
errors.is_empty(),
"fixture must be structurally valid: {errors:?}"
);
}
fn fixture() -> AllocationFixture {
let mut project = Project::empty();
let performer = project
.add_element(Kind::Entity, Layer::Oa, "Rescue team", None)
.unwrap();
let work = project
.add_element(Kind::Activity, Layer::Oa, "Dispatch", None)
.unwrap();
let relation = project.relate(RelationKind::Allocation, "Performs", performer, work);
let diagram = project.ensure_diagram(Layer::Oa);
project.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Allocation;
let performer_node = project.place(diagram, performer, Position { x: 20., y: 40. });
let work_node = project.place(diagram, work, Position { x: 240., y: 320. });
project
.diagrams
.get_mut(&diagram)
.unwrap()
.nodes
.get_mut(&work_node)
.unwrap()
.size = Size {
width: 320.,
height: 110.,
};
assert_valid(&project);
AllocationFixture {
project,
diagram,
performer,
work,
relation,
performer_node,
work_node,
}
}
fn expected(f: &AllocationFixture) -> Usage {
Usage {
subject: f.relation,
surface: Surface::Saved(f.diagram),
target: Target::AllocationGrouping {
relation: f.relation,
work_placement: f.work_node,
performer_placement: f.performer_node,
},
role: "allocation grouping".into(),
bounds: Rectangle {
x: 240.,
y: 320.,
width: 320.,
height: 64.,
},
}
}
/// Two semantic decomposition levels, both summaries of the one allocated leaf.
/// No Allocation relation targets either summary.
fn nest_under_summaries(f: &mut AllocationFixture) -> (Id, Id, Id, Id) {
let top = f
.project
.add_element(Kind::Activity, Layer::Oa, "Respond", None)
.unwrap();
let middle = f
.project
.add_element(Kind::Activity, Layer::Oa, "Coordinate", Some(top))
.unwrap();
f.project.elements.get_mut(&f.work).unwrap().parent = Some(middle);
let top_node = f
.project
.place(f.diagram, top, Position { x: 70., y: 120. });
let middle_node = f
.project
.place(f.diagram, middle, Position { x: 130., y: 210. });
assert_valid(&f.project);
(top, middle, top_node, middle_node)
}
#[test]
fn allocation_grouping_has_exact_relation_placements_and_readable_work_geometry() {
let f = fixture();
let before = f.project.clone();
let view = projection::project_view(&f.project, f.diagram);
let work = view
.nodes
.iter()
.find(|node| node.id == f.work_node)
.unwrap();
assert_eq!(work.visual_parent, Some(f.performer_node));
assert_eq!(work.position, Position { x: 240., y: 320. });
assert_eq!(
work.size,
Size {
width: 320.,
height: 110.
}
);
assert!(!view.edges.iter().any(|edge| edge.id == f.relation));
assert_eq!(saved_usages(&f.project, f.relation), vec![expected(&f)]);
assert_eq!(
saved_usages_for(&f.project, f.relation, Some(f.diagram)),
vec![expected(&f)]
);
assert!(saved_usages_for(&f.project, f.relation, Some(Id::new_v4())).is_empty());
// The semantic work and its placement remain ordinary node selections.
for subject in [f.work, f.work_node] {
let usages = saved_usages(&f.project, subject);
assert_eq!(usages.len(), 1);
assert_eq!(usages[0].target, Target::Placement(f.work_node));
}
assert_eq!(f.project, before);
}
#[test]
fn allocation_grouping_walks_two_visible_summary_levels_without_inventing_allocations() {
let mut f = fixture();
let (top, middle, top_node, middle_node) = nest_under_summaries(&mut f);
let before = f.project.clone();
let view = projection::project_view(&f.project, f.diagram);
for (node_id, parent, summary) in [
(f.work_node, Some(middle_node), false),
(middle_node, Some(top_node), true),
(top_node, Some(f.performer_node), true),
] {
let node = view.nodes.iter().find(|node| node.id == node_id).unwrap();
assert_eq!(node.visual_parent, parent);
assert_eq!(node.allocation_summary, summary);
}
assert_eq!(f.project.relations.len(), 1);
assert_eq!(saved_usages(&f.project, f.relation), vec![expected(&f)]);
for (element, node) in [(top, top_node), (middle, middle_node)] {
let usages = saved_usages(&f.project, element);
assert_eq!(usages.len(), 1);
assert_eq!(usages[0].target, Target::Placement(node));
}
assert_eq!(f.project, before);
}
#[test]
fn folded_summary_or_performer_does_not_substitute_a_visible_ancestor_for_the_leaf() {
let mut f = fixture();
let (_, _, top_node, middle_node) = nest_under_summaries(&mut f);
for folded in [f.performer_node, top_node, middle_node] {
let mut project = f.project.clone();
project
.diagrams
.get_mut(&f.diagram)
.unwrap()
.nodes
.get_mut(&folded)
.unwrap()
.collapsed = true;
assert_valid(&project);
let before = project.clone();
let view = projection::project_view(&project, f.diagram);
assert!(view.nodes.iter().any(|node| node.id == folded));
assert!(!view.nodes.iter().any(|node| node.id == f.work_node));
assert!(saved_usages(&project, f.relation).is_empty());
assert_eq!(project, before);
}
}
#[test]
fn absent_endpoint_placements_and_hidden_performer_do_not_create_grouping_targets() {
let mut f = fixture();
let (_, _, top_node, _) = nest_under_summaries(&mut f);
for absent in [f.performer_node, f.work_node] {
let mut project = f.project.clone();
project
.diagrams
.get_mut(&f.diagram)
.unwrap()
.nodes
.remove(&absent);
assert_valid(&project);
let before = project.clone();
let view = projection::project_view(&project, f.diagram);
// The aggregate card remains visible even when the actual leaf or its
// actual performer has no placement. It cannot stand in for that end.
assert!(
view.nodes
.iter()
.any(|node| node.id == top_node && node.allocation_summary)
);
assert!(saved_usages(&project, f.relation).is_empty());
assert_eq!(project, before);
}
let outer = f
.project
.add_element(Kind::Entity, Layer::Oa, "Organization", None)
.unwrap();
f.project.elements.get_mut(&f.performer).unwrap().parent = Some(outer);
let outer_node = f
.project
.place(f.diagram, outer, Position { x: -40., y: -60. });
f.project
.diagrams
.get_mut(&f.diagram)
.unwrap()
.nodes
.get_mut(&outer_node)
.unwrap()
.collapsed = true;
assert_valid(&f.project);
let before = f.project.clone();
let view = projection::project_view(&f.project, f.diagram);
assert!(view.nodes.iter().any(|node| node.id == outer_node));
assert!(!view.nodes.iter().any(|node| node.id == f.performer_node));
assert!(saved_usages(&f.project, f.relation).is_empty());
assert_eq!(f.project, before);
}
#[test]
fn collapsed_leaf_and_edge_filter_still_leave_the_actual_nesting_visible() {
let mut f = fixture();
let diagram = f.project.diagrams.get_mut(&f.diagram).unwrap();
diagram.nodes.get_mut(&f.work_node).unwrap().collapsed = true;
// hidden_edges controls arrows. Allocation is drawn as nesting, which is
// still visible; do not mistake the filter for a hidden node/grouping.
diagram.view_options.hidden_edges.push(f.relation);
assert_valid(&f.project);
let before = f.project.clone();
let view = projection::project_view(&f.project, f.diagram);
let work = view
.nodes
.iter()
.find(|node| node.id == f.work_node)
.unwrap();
assert!(work.collapsed);
assert_eq!(work.visual_parent, Some(f.performer_node));
assert_eq!(saved_usages(&f.project, f.relation), vec![expected(&f)]);
assert_eq!(f.project, before);
}
#[test]
fn other_projections_do_not_report_allocation_nesting_when_only_an_arrow_or_nothing_is_drawn() {
let mut f = fixture();
f.project.diagrams.get_mut(&f.diagram).unwrap().projection = ProjectionKind::Overview;
assert_valid(&f.project);
let before = f.project.clone();
let view = projection::project_view(&f.project, f.diagram);
assert!(view.edges.iter().any(|edge| edge.id == f.relation));
assert!(view.nodes.iter().all(|node| node.visual_parent.is_none()));
let usages = saved_usages(&f.project, f.relation);
assert_eq!(usages.len(), 1);
assert_eq!(usages[0].subject, f.relation);
assert_eq!(usages[0].surface, Surface::Saved(f.diagram));
assert_eq!(usages[0].target, Target::Edge(f.relation));
assert_eq!(f.project, before);
f.project.diagrams.get_mut(&f.diagram).unwrap().projection = ProjectionKind::FunctionalDataflow;
assert_valid(&f.project);
let before = f.project.clone();
let view = projection::project_view(&f.project, f.diagram);
assert!(view.nodes.iter().any(|node| node.id == f.work_node));
assert!(!view.nodes.iter().any(|node| node.id == f.performer_node));
assert!(saved_usages(&f.project, f.relation).is_empty());
assert_eq!(f.project, before);
}
#[test]
fn repeated_saved_views_keep_allocation_placement_identity_and_geometry_independent() {
let mut f = fixture();
// The first diagram is Allocation, so this creates a different Overview.
let second = f.project.ensure_diagram(Layer::Oa);
assert_ne!(second, f.diagram);
f.project.diagrams.get_mut(&second).unwrap().projection = ProjectionKind::Allocation;
let second_performer = f
.project
.place(second, f.performer, Position { x: 900., y: 600. });
let second_work = f
.project
.place(second, f.work, Position { x: 1000., y: 700. });
f.project
.diagrams
.get_mut(&second)
.unwrap()
.nodes
.get_mut(&second_work)
.unwrap()
.size = Size {
width: 520.,
height: 130.,
};
assert_ne!(second_performer, f.performer_node);
assert_ne!(second_work, f.work_node);
assert_valid(&f.project);
let before = f.project.clone();
let other = Usage {
subject: f.relation,
surface: Surface::Saved(second),
target: Target::AllocationGrouping {
relation: f.relation,
work_placement: second_work,
performer_placement: second_performer,
},
role: "allocation grouping".into(),
bounds: Rectangle {
x: 1000.,
y: 700.,
width: 420.,
height: 64.,
},
};
let usages = saved_usages(&f.project, f.relation);
assert_eq!(usages.len(), 2);
assert!(usages.contains(&expected(&f)));
assert!(usages.contains(&other));
assert_eq!(
saved_usages_for(&f.project, f.relation, Some(second)),
vec![other]
);
assert_eq!(f.project, before);
}
#[test]
fn role_derived_nesting_without_a_direct_allocation_does_not_invent_one() {
let mut f = fixture();
f.project.relations.remove(&f.relation);
let role = f
.project
.add_element(Kind::Role, Layer::Oa, "Dispatcher", None)
.unwrap();
let realization = f.project.relate(
RelationKind::RoleRealization,
"Realizes dispatcher",
f.performer,
role,
);
let assignment = f
.project
.relate(RelationKind::RoleAssignment, "Dispatches", role, f.work);
assert_valid(&f.project);
let before = f.project.clone();
let view = projection::project_view(&f.project, f.diagram);
let work = view
.nodes
.iter()
.find(|node| node.id == f.work_node)
.unwrap();
assert_eq!(work.visual_parent, Some(f.performer_node));
assert!(work.allocation_summary);
assert!(
f.project
.relations
.values()
.all(|relation| relation.kind() != RelationKind::Allocation)
);
for subject in [f.relation, realization, assignment] {
assert!(saved_usages(&f.project, subject).is_empty());
}
let usages = saved_usages(&f.project, f.work);
assert_eq!(usages.len(), 1);
assert_eq!(usages[0].target, Target::Placement(f.work_node));
assert_eq!(f.project, before);
}
@@ -1,196 +0,0 @@
use super::*;
use oa_core::{Kind, Layer, Position, RelationKind};
#[test]
fn saved_membership_respects_filters_and_does_not_change_project() {
let mut p = Project::empty();
let first = p.add(Kind::Activity, "Same name", 20., 20.);
let second = p.add(Kind::Activity, "Same name", 340., 20.);
let relation = p.relate(RelationKind::Interaction, "Handoff", first, second);
let shown = p.ensure_diagram(Layer::Oa);
let mut hidden = p.diagrams[&shown].clone();
hidden.id = Id::new_v4();
hidden.alias = "filtered_copy".into();
hidden.nodes = hidden
.nodes
.into_values()
.map(|mut node| {
node.id = Id::new_v4();
node.alias = format!("filtered_{}", node.alias);
(node.id, node)
})
.collect();
hidden.view_options.hidden_edges.push(relation);
let hidden_id = hidden.id;
p.diagrams.insert(hidden_id, hidden);
let before = p.clone();
let hits = saved_usages(&p, relation);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].surface, Surface::Saved(shown));
assert_eq!(hits[0].target, Target::Edge(relation));
let hits = saved_usages(&p, first);
assert_eq!(hits.len(), 2);
assert!(hits.iter().all(|hit| match hit.target {
Target::Placement(node) => p.diagrams[&hit.surface.id()].nodes[&node].element == first,
_ => false,
}));
assert_eq!(p, before);
}
#[test]
fn folded_child_is_not_a_visible_node_and_placement_identity_stays_exact() {
let mut p = Project::empty();
let parent = p.add(Kind::Activity, "Container", 20., 20.);
let child = p
.add_element(Kind::Activity, Layer::Oa, "Nested", Some(parent))
.unwrap();
let diagram = p.ensure_diagram(Layer::Oa);
let child_node = p.place(diagram, child, Position { x: 50., y: 100. });
let parent_node = p.diagrams[&diagram]
.nodes
.values()
.find(|n| n.element == parent)
.unwrap()
.id;
let hits = saved_usages(&p, child_node);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].target, Target::Placement(child_node));
p.diagrams
.get_mut(&diagram)
.unwrap()
.nodes
.get_mut(&parent_node)
.unwrap()
.collapsed = true;
let before = p.clone();
assert!(saved_usages(&p, child).is_empty());
assert!(saved_usages(&p, child_node).is_empty());
assert_eq!(saved_usages(&p, parent).len(), 1);
assert_eq!(p, before);
}
#[test]
fn ports_are_found_at_the_visible_owner_and_unplaced_elements_do_not_match_names() {
let mut p = Project::empty();
let owner = p.add(Kind::Function, "Compute", 20., 20.);
let port = Id::new_v4();
let element = oa_core::ports::make_port(
&p,
port,
owner,
"Input",
oa_core::PortContract::FunctionInput {
incoming_items: vec![],
},
)
.unwrap();
p = oa_core::execute_batch(&p, &[oa_core::Command::CreateElement(element)]).unwrap();
let unrelated = p
.add_element(Kind::Function, Layer::Sa, "Compute", None)
.unwrap();
let hits = saved_usages(&p, port);
assert_eq!(hits.len(), 1);
let view = projection::project_view(&p, hits[0].surface.id());
let painted = view
.ports
.iter()
.find(|shown| shown.element == port)
.unwrap();
assert_eq!(
hits[0].target,
Target::Port {
port,
placement: painted.owner
}
);
assert_eq!(
hits[0].bounds.center(),
iced::Point::new(painted.position.x, painted.position.y)
);
assert!(saved_usages(&p, unrelated).is_empty());
assert!(saved_usages(&p, Id::new_v4()).is_empty());
}
#[test]
fn reveal_camera_centers_target_without_whole_view_shrink() {
let bounds = Rectangle {
x: 100_000.,
y: -50_000.,
width: 224.,
height: 94.,
};
let viewport = iced::Size::new(700., 500.);
let (zoom, pan) = camera(bounds, viewport);
assert_eq!(zoom, 1.25);
assert!((bounds.center_x() * zoom + pan.x - 350.).abs() < 0.01);
assert!((bounds.center_y() * zoom + pan.y - 250.).abs() < 0.01);
}
#[test]
fn oversized_container_reveal_targets_its_labelled_header() {
let mut p = Project::empty();
let container = p.add(Kind::Activity, "Large enclosing activity", 40., 70.);
let diagram = p.ensure_diagram(Layer::Oa);
let node = p
.diagrams
.get_mut(&diagram)
.unwrap()
.nodes
.values_mut()
.next()
.unwrap();
node.size = oa_core::Size {
width: 4000.,
height: 4000.,
};
let before = p.clone();
let hits = saved_usages(&p, container);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].bounds.x, 40.);
assert_eq!(hits[0].bounds.y, 70.);
assert!(hits[0].bounds.width <= 420.);
assert!(hits[0].bounds.height <= 64.);
let (zoom, pan) = camera(hits[0].bounds, iced::Size::new(500., 300.));
assert!((hits[0].bounds.center_x() * zoom + pan.x - 250.).abs() < 0.01);
assert!(70. * zoom + pan.y >= 0.);
assert_eq!(p, before);
}
#[test]
fn state_machine_owner_finds_its_view_without_a_machine_placement() {
let mut p = Project::empty();
let machine = p
.add_element(Kind::StateMachine, Layer::Sa, "Monitor", None)
.unwrap();
let unrelated = p
.add_element(Kind::StateMachine, Layer::Sa, "Other", None)
.unwrap();
let diagram = p.ensure_diagram(Layer::Sa);
p.diagrams.get_mut(&diagram).unwrap().projection =
oa_core::ProjectionKind::StateMachine { machine };
let before = p.clone();
let hits = saved_usages(&p, machine);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].surface, Surface::Saved(diagram));
assert_eq!(hits[0].target, Target::Whole);
assert_eq!(hits[0].role, "state machine view");
assert!(saved_usages(&p, unrelated).is_empty());
assert_eq!(p, before);
}
#[test]
fn whole_diagram_camera_fits_large_bounds_instead_of_individual_object_scale() {
let bounds = Rectangle {
x: 2000.,
y: -4000.,
width: 100_000.,
height: 80_000.,
};
let (zoom, pan) = camera_for(&Target::Whole, bounds, iced::Size::new(500., 300.));
assert!(zoom < 0.01);
assert!(bounds.x * zoom + pan.x >= 0.);
assert!(bounds.y * zoom + pan.y >= 0.);
assert!((bounds.x + bounds.width) * zoom + pan.x <= 500.);
assert!((bounds.y + bounds.height) * zoom + pan.y <= 300.);
}
-220
View File
@@ -1,220 +0,0 @@
use super::*;
use crate::{
app::{App, Message},
style,
views::{action, short},
};
use iced::{
Element, Fill,
widget::{self, column, container, row, text, text_input, tooltip},
};
use std::collections::BTreeSet;
const PAGE_SIZE: usize = 6;
pub(crate) fn overlay<'a>(app: &'a App, base: Element<'a, Message>) -> Element<'a, Message> {
let Some(panel) = &app.diagram_usages else {
return base;
};
let p = app.project();
let token = panel.token;
let message = |event| Message::DiagramUsage(event);
let matched = panel.matches(p);
let mut surfaces = Vec::new();
let mut seen = BTreeSet::new();
for usage in &matched {
if seen.insert(usage.surface) {
surfaces.push(usage.surface);
}
}
let targets: Vec<_> = matched
.iter()
.copied()
.filter(|usage| Some(usage.surface) == panel.destination)
.collect();
let count = if panel.destination.is_some() {
targets.len()
} else {
surfaces.len()
};
let last = count.saturating_sub(1) / PAGE_SIZE;
let page = panel.page.min(last);
let total_surfaces = panel
.usages
.iter()
.map(|u| u.surface)
.collect::<BTreeSet<_>>()
.len();
let mut content = column![
row![
text("Show in diagrams").size(22).width(Fill),
action("Close", message(Event::Close(token)))
]
.spacing(12),
tooltip(
text(format!(
"{} · @{}",
short(p.named(panel.context.subject), 48),
short(alias(p, panel.context.subject), 48)
))
.size(14),
container(
widget::scrollable(
text(format!(
"{}\n@{}",
p.named(panel.context.subject),
alias(p, panel.context.subject)
))
.size(13)
)
.height(220)
)
.padding(10)
.width(620)
.style(style::card),
tooltip::Position::Bottom
),
text(if panel.loading {
"Searching rendered objects…".into()
} else {
format!(
"{} diagram destinations · {} representations",
total_surfaces,
panel.usages.len()
)
})
.size(12)
.color(style::MUTED),
text_input("Filter diagram, occurrence, or alias", &panel.search)
.id(format!("diagram-usage-filter-{}", panel.token))
.padding(9)
.on_input(move |value| Message::DiagramUsage(Event::Search(token, value)))
.on_submit(message(Event::Activate(token))),
]
.spacing(10);
if let Some(notice) = &panel.notice {
content = content.push(text(notice).size(13));
}
if let Some(surface) = panel.destination {
content = content.push(
row![
action("All diagrams", message(Event::Destination(token, None))),
text(short(p.named(surface.id()), 55)).size(15),
]
.spacing(10),
);
for (index, usage) in targets
.into_iter()
.enumerate()
.skip(page * PAGE_SIZE)
.take(PAGE_SIZE)
{
let name = target_name(p, usage);
content = content.push(tooltip(
action(
&format!("{} · {}", usage.role, short(&name, 70)),
message(Event::Choose(token, usage.clone())),
)
.width(Fill)
.style(if panel.cursor == index {
style::selected
} else {
style::nav
}),
container(text(name).size(13))
.padding(10)
.max_width(680)
.style(style::card),
tooltip::Position::Top,
));
}
} else {
for (index, surface) in surfaces
.into_iter()
.enumerate()
.skip(page * PAGE_SIZE)
.take(PAGE_SIZE)
{
let targets = matched.iter().filter(|u| u.surface == surface).count();
let name = format!(
"{} · {} (@{}) · {} representations",
surface.category(p),
p.named(surface.id()),
alias(p, surface.id()),
targets
);
let layer = p
.diagrams
.get(&surface.id())
.map(|d| d.layer)
.or_else(|| p.layer_of(surface.id()))
.map(|l| l.to_string())
.unwrap_or_default();
content = content.push(tooltip(
action(
&format!(
"{} · {} · {} · {}",
surface.category(p),
layer,
short(p.named(surface.id()), 34),
targets
),
message(Event::Destination(token, Some(surface))),
)
.width(Fill)
.style(if panel.cursor == index {
style::selected
} else {
style::nav
}),
container(text(name).size(13))
.padding(10)
.max_width(680)
.style(style::card),
tooltip::Position::Top,
));
}
}
if panel.loading {
content = content.push(text("Finding diagram representations…").size(13));
} else if count == 0 {
content = content.push(text(if panel.usages.is_empty() {
"No currently rendered representation found. Folded or filtered objects and unexpanded reuse contents are excluded."
} else { "No results match this filter." }).size(13));
}
let mut paging = row![
text(format!(
"Page {} of {} · {} matches",
page + 1,
last + 1,
count
))
.size(12)
.width(Fill)
]
.spacing(8);
if page > 0 {
paging = paging.push(action("Previous", message(Event::Page(token, page - 1))));
}
if page < last {
paging = paging.push(action("Next", message(Event::Page(token, page + 1))));
}
content = content.push(paging).push(text("↑ ↓ choose · Enter opens · Escape closes. Source and saved view settings are preserved.").size(12).color(style::MUTED));
widget::stack![
base,
widget::opaque(
container(
container(content)
.padding(22)
.width((app.window_size.width - 80.).clamp(620., 820.))
.style(style::card)
)
.center(Fill)
.style(|_| container::Style {
background: Some(iced::Color::from_rgba(0.08, 0.12, 0.18, 0.38).into()),
..Default::default()
})
)
]
.into()
}
+16 -28
View File
@@ -188,7 +188,7 @@ fn article(topic: Topic) -> Article {
"Choose New in the top bar. Use Project properties to name the model and describe its purpose. Apply changes commits the property draft.",
"On Architecture, choose Create architecture view. Architecture · allocated work shows work inside its performer.",
"Expand the diagram's side palette to see tool names. Choose Entity, click its position in the diagram, enter Rescue coordinator and press Enter. Escape cancels the draft. Use Actor for an external participant such as a Vessel in distress. Right-clicking a blank area also offers Create Entity here.",
"Right-click Rescue coordinator and choose Add activity. Enter Assess incident and press Enter to create the activity and its performer allocation together. Ordinary Activity creation in the palette leaves work unallocated; use + Relationship with Allocation to assign existing work. The allocated-work view shows work inside its performer.",
"Right-click Rescue coordinator and choose Add activity. Enter Assess incident and press Enter to create the activity and its performer allocation together. Ordinary Activity creation in the palette leaves work unallocated. In the allocated-work view, drag existing work into exposed space inside its performer to assign it; the highlighted performer and status explain the proposed change.",
"Use Add existing to place an element that is already in the model. The initial choices match this view; no search is required. Include already shown offers Locate for elements already placed here.",
"Add a second activity for another participant. Select an activity, choose + Relationship, select Interaction and choose the compatible target. Name the exchange after what is conveyed.",
"Visit Model checks to review unfinished work. Save all writes the accepted model and applied drafts to your chosen file.",
@@ -263,7 +263,7 @@ fn article(topic: Topic) -> Article {
&[
"Choose the Operational or System perspective. Create participants using Entity/Actor in OA or System/System actor in SA.",
"In the diagram's side palette, choose Activity in OA or Function in SA, click its position, enter a name and press Enter. Escape cancels without creating an element. Select a card and press F2 to rename it in place. For semantic decomposition, use Model explorer, select existing work and use + In selected to create smaller work units.",
"Right-click a participant and choose Add activity or Add function to create new work and its allocation together. To assign existing leaf work, use + Relationship with Allocation from the participant to the work. Model explorer also offers + Allocated when a participant and the appropriate work kind are selected.",
"Right-click a participant and choose Add activity or Add function to create new work and its allocation together. In Architecture · allocated work, drag existing work into a performer to assign it, between performers to reassign it, or onto empty canvas to remove its direct assignment. + Relationship with Allocation and Model explorer's + Allocated provide explicit alternatives.",
"Choose Architecture · allocated work to review responsibilities. Choose Functional dataflow to review the activity/function hierarchy and its exchanges independently.",
],
),
@@ -289,7 +289,7 @@ fn article(topic: Topic) -> Article {
const {
Article {
summary: "A diagram is a view of the model. Its boxes, positions and nesting reveal selected relationships; moving a box does not redefine engineering ownership.",
keywords: "containment semantic parent hierarchy nested nesting allocation deployment diagram placement arrange fit fold hide zoom resize routing connection bend waypoint detour label reset selective visibility category categories coverage process context duplicate copy items",
keywords: "containment semantic parent hierarchy nested nesting allocation deployment diagram placement arrange next drag Alt+A auto-layout fit fold hide zoom resize routing connection bend waypoint detour label reset selective visibility category categories coverage process context duplicate copy items",
sections: &[
explain(
"Three things to distinguish",
@@ -309,7 +309,7 @@ fn article(topic: Topic) -> Article {
"Use the diagram selector or + View to work with a focused diagram. View properties edits its name, perspective, projection and Saved view visibility. Apply changes commits the view settings.",
"Choose Containment for semantic children, Architecture · allocated work for responsibilities, Functional dataflow for work and exchanges, or Missions & capabilities for outcomes. All relationships is a broader exploration view; OA ↔ SA traceability displays counterparts.",
"Select an element and edit Semantic parent to change ownership. Use an Allocation relationship to change responsibility. Apply changes validates the semantic change.",
"Drag nodes to arrange the current view, scroll to zoom and use Fit to frame its contents. Arrange changes diagram geometry. Export SVG produces a shareable view.",
"Scroll to zoom and use Fit to frame the current view. In allocated-work views, dragging work changes its assignment and placement together. Choose Arrange next drag or press Alt+A to move work without changing responsibility for that one drag; Escape cancels the armed action. Auto-layout arranges the whole view. Export SVG produces a shareable view.",
"Select a diagram node to access Placement, Fold / unfold and Hide. Hide removes its view placement; Delete from model removes model records and requires review of the affected references.",
],
),
@@ -317,6 +317,14 @@ fn article(topic: Topic) -> Article {
"Keep diagrams readable",
"Use separate views for responsibility, decomposition and cross-layer coverage. Place existing elements with Show in this diagram. A placement's Diagram field can relocate it while preserving its identity and artifact references. Do not duplicate a semantic element merely to show it in another view.",
),
walkthrough(
"Move work between performers",
&[
"Finish or cancel property and source edits, then drag an Activity or Function body in Architecture · allocated work. Aim at exposed performer space. Read the highlighted destination and status before releasing; release outside the canvas or press Escape to cancel.",
"The move preserves work ownership and identities. A uniformly assigned work group moves its leaves together; a group distributed across performers asks you to choose a leaf. Role responsibilities remain explicit: an outward drag that would leave a role-derived performer explains why it cannot remove that responsibility.",
"Make room when headers, labels or other cards would overlap. Move the view or zoom in if the work and destination are not readable. A refused drop keeps the model and history unchanged. One Undo reverses an accepted assignment and placement together; Save all writes the corresponding source changes.",
],
),
walkthrough(
"Save a focused exchange view",
&[
@@ -336,7 +344,7 @@ fn article(topic: Topic) -> Article {
&[
"Select an architecture connection and drag a segment to add a bend. Right-click a line for Add bend here; right-click a circle for Remove bend. With the canvas focused, Insert adds a bend and Delete removes the selected bend. Drag the label independently. Escape cancels a gesture; Undo reverses one completed drag. Shift+F10 opens the selected diagram item's context menu; use arrow keys and Enter to choose an action.",
"Automatic orthogonal routing avoids cards and container headers where space permits. Amber connections need attention: move an obstructing element or a bend. In Select / move, drag a port to any border of its owner. Manual positions are per diagram; right-click Reset automatic position restores connection-aware placement. Ports remain attached to their actual owners. Manual routes are saved separately for each diagram and appear in source, API and SVG export.",
"Right-click a connection and choose Reset routing to clear its pins and label position in this view. The Properties Actions menu provides the same commands. Arrange preserves pins. Moving one endpoint keeps pins fixed; moving a container carrying both endpoints translates their pins. When folding promotes an endpoint, expand it again to resume and edit its saved route.",
"Right-click a connection and choose Reset routing to clear its pins and label position in this view. The Properties Actions menu provides the same commands. Auto-layout preserves pins. Moving one endpoint keeps pins fixed; moving a container carrying both endpoints translates their pins. When folding promotes an endpoint, expand it again to resume and edit its saved route.",
],
),
explain(
@@ -445,7 +453,7 @@ fn article(topic: Topic) -> Article {
walkthrough(
"Describe a path through exchanges",
&[
"On an empty path, choose Work (W) from the right palette and click the canvas. You can use existing work or stage a new source in that form; exchanges still need explicit compatible source and target work.",
"A blank path offers Add first activity/function contribution. You can use existing work or stage a new source in that form; exchanges still need explicit compatible source and target work.",
"Open Behavior & scenarios → New. Choose Operational process in OA or Functional chain in SA, enter its exact name, then Create and open. The new behavior belongs at the layer root and opens immediately; Undo removes the creation as one edit.",
"Choose Work (W) or Exchange (E) from the permanent palette on the right, then a highlighted position. Hover a palette button to read its tool name. In Work, Create new source keeps the contribution name and position while you name its Activity/Function and choose its semantic parent. Use this new source stages it; Create commits source and contribution in one Undo. An adjacent exchange may require a particular existing work identity.",
"Choose Sequence link (->) and click or drag from the preceding contribution to the following contribution. Choose Select contributions or paths (S) to drag a selected path endpoint and reconnect it. A contribution's ↕ handle reorders contributions within the same column; links determine the columns. These are local contributions and sequence links, not new architecture exchanges.",
@@ -488,7 +496,7 @@ fn article(topic: Topic) -> Article {
const {
Article {
summary: "Use a scenario to tell a concrete behavioral story, including repeated messages, actions, state observations and guarded alternatives.",
keywords: "scenario sequence lifeline lifetime lifecycle birth death capsule sender receiver fragment branch alternative loop guard parallel strict optional occurrence exchange action state interface operation allocation call reply unresolved",
keywords: "scenario sequence lifeline sender receiver fragment branch alternative loop guard parallel strict optional occurrence exchange action state interface operation allocation call reply unresolved",
sections: &[
walkthrough(
"Create a scenario",
@@ -514,14 +522,6 @@ fn article(topic: Topic) -> Article {
"Inspect the scenario projection and Model checks. State exactly what each guard means, including units and assumptions where relevant.",
],
),
explain(
"Read lifeline creation and deletion",
"The Lane header and dotted guide identify a lifeline; the guide alone does not establish its lifetime. The stronger solid line shows where the lifeline is known to exist on this scenario path. Create starts that line at a named capsule; Delete ends it at an X. Select the capsule or X to edit that message occurrence. Select the header or guide to inspect the lifeline.",
),
explain(
"Distinguish uncertain lifetime from an unanswered call",
"A ? means lifetime depends on an alternative, optional, repeated or parallel path. Operands have independent lifetimes: Delete in one alternative does not delete a lifeline in another. Beyond such a fragment, the guide can continue without a definite solid line. This uncertainty is not by itself a model error. The … beside an activation marks a Call that remains unanswered on that path. A reused scenario's internal Create/Delete events appear when you choose Open definition; they do not create or delete the caller's lifelines.",
),
walkthrough(
"Invoke an interface operation",
&[
@@ -805,7 +805,7 @@ fn article(topic: Topic) -> Article {
const {
Article {
summary: "The text editor and graphical forms edit the same model. Source projects preserve file organization and comments for human review, automation and version control.",
keywords: "text textual source language syntax highlighting lint parser git aliases uuid identity rename diff merge restructuredtext spec canonical parity definition references lexical navigation F12 back",
keywords: "text textual source language syntax highlighting lint parser git aliases uuid identity rename diff merge restructuredtext spec canonical parity",
sections: &[
walkthrough(
"Edit and review source",
@@ -818,18 +818,6 @@ fn article(topic: Topic) -> Article {
"Save all writes the entry and its included UTF-8 files. Review the Git diff before committing, including relationships, traces and diagram changes that belong to the same engineering edit.",
],
),
explain(
"Follow definitions and lexical references",
"Place the caret on a declaration alias or an @reference. Choose Definition (F12) to locate its declaration, or References (Shift+F12) to list lexical uses. Choose a row when a definition is ambiguous, draft or detached. Lexical uses exclude comments and strings; they do not establish typed relationships or resolve an ambiguous alias to one declaration. Back (Alt+Left) returns to the previous source location; if that draft changed, it restores the current cursor instead of an obsolete selection. These shortcuts work while the source editor has focus; the Text toolbar also offers the actions.",
),
explain(
"Read the navigation scope",
"Queries inspect bounded snapshots of currently loaded drafts, without applying them or loading missing included files. The panel identifies partial scope, draft evidence, detached or unverified files, and alias or ID collisions. Counts show total, displayed and omitted rows. A missing result in partial scope does not establish that the whole project has no match. If sources change, stale rows are disabled; run Definition or References again. Row locations use one-based lines and UTF-8 byte columns. Navigation preserves your source drafts and the accepted model.",
),
explain(
"Find the record in diagrams",
"Choose Show in diagrams from the Text toolbar on a unique verified alias in clean sources, or from the chosen model-tree record's context menu. Choose a diagram destination, then an exact representation. Results follow visible projection: ports, state rows, repeated caller tiles and their drawn sequence links remain distinct. Hidden tiles and nested links that are not drawn are excluded. A direct allocation can be represented by visible grouping; aggregate summaries do not invent allocation relations. A visual marker locates the port, row or grouped work while keeping the queried semantic record selected for model actions. Moving the camera preserves that marker. Finish pending edits first; navigation preserves accepted geometry, sources and history.",
),
explain(
"Names, aliases and IDs serve different purposes",
"The displayed name is engineering prose. A stable @alias is the readable source reference and need not change when the name changes. UUID identity distinguishes the persistent record. Preserve IDs when revising the same engineering object; changing identity is a deliberate operation that affects references.",
+2 -1
View File
@@ -1,4 +1,6 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod allocation_drag;
mod allocation_input;
mod app;
mod behavior;
mod connection_edit;
@@ -7,7 +9,6 @@ mod context_menu;
mod data_values;
mod data_view;
mod diagram;
mod diagram_usage;
mod document;
mod explorer;
mod explorer_view;
+22 -7
View File
@@ -281,11 +281,6 @@ pub fn popup(app: &App) -> Option<Menu<Message>> {
}
entries.push(item("Properties", Message::EditProperties(id), true));
entries.push(item("Open source", Message::SourceForSelection, true));
entries.push(item(
"Show in diagrams…",
app.diagram_usage_message(id),
true,
));
entries.push(item(
"Connections & references",
Message::InspectorTab(crate::navigation::InspectorTab::Connections),
@@ -420,7 +415,9 @@ pub fn popup(app: &App) -> Option<Menu<Message>> {
true,
));
entries.push(item("Placement properties", Message::Select(node.id), true));
entries.push(item("Hide from this diagram", Message::HideSelected, true));
entries.push(
item("Hide from this diagram", Message::HideSelected, true).shortcut("Delete"),
);
} else if e.kind() != Kind::Port
&& let Some(d) = app.active_diagram.and_then(|d| p.diagrams.get(&d))
{
@@ -470,7 +467,25 @@ pub fn popup(app: &App) -> Option<Menu<Message>> {
true,
));
if id != p.id {
entries.push(item("Delete from model…", Message::Delete, true));
entries.push(
item("Delete from model…", Message::Delete, true).shortcut(
if request.canvas.is_some_and(|context| context.diagram != id)
&& (request.placement.is_some()
|| p.relations.contains_key(&id)
|| p.elements
.get(&id)
.is_some_and(|element| element.kind() == Kind::Port))
{
if request.placement.is_some() {
"Shift+Delete"
} else {
"Delete / Shift+Delete"
}
} else {
""
},
),
);
}
}
Some(Menu {
+41 -4
View File
@@ -126,8 +126,28 @@ fn groups(p: &Project, selected: Id) -> Vec<Group> {
]
}
pub fn view(app: &crate::app::App, selected: Id) -> Element<'_, Message> {
let p = app.project();
pub fn diagrams_containing(p: &Project, selected: Id) -> Vec<Id> {
let endpoints = p.relations.get(&selected).map(|r| [r.source(), r.target()]);
p.diagrams
.values()
.filter(|d| {
let placed = |id| {
let e = p.elements.get(&id);
let owner = e
.filter(|e| e.kind() == Kind::Port)
.and_then(|e| e.parent)
.unwrap_or(id);
let kind = p.elements.get(&owner).map(|e| e.kind());
kind.is_none_or(|kind| d.projection.includes(kind))
&& d.nodes.values().any(|n| n.element == owner || n.id == id)
};
placed(selected) || endpoints.is_some_and(|ends| ends.into_iter().all(placed))
})
.map(|d| d.id)
.collect()
}
pub fn view(p: &Project, selected: Id) -> Element<'_, Message> {
let mut content = column![
text(short(p.named(selected), 50)).size(18),
text("Follow ownership, usage and engineering relationships.")
@@ -183,8 +203,25 @@ pub fn view(app: &crate::app::App, selected: Id) -> Element<'_, Message> {
content = content.push(container(entry).padding(8).style(style::subtle));
}
}
content =
content.push(action("Show in diagrams…", app.diagram_usage_message(selected)).width(Fill));
let diagrams = diagrams_containing(p, selected);
if !diagrams.is_empty() {
content = content.push(label("SHOWN IN DIAGRAMS"));
for id in diagrams {
content = content.push(
action(
&short(p.named(id), 42),
Message::RevealInDiagram(id, selected),
)
.width(Fill),
);
}
} else if p.elements.contains_key(&selected) {
content = content.push(
text("This element has no diagram placement yet.")
.size(12)
.color(style::MUTED),
);
}
if count == 0 {
content = content.push(text("No semantic connections yet. Use Actions or right-click an element to add relationships.").size(12).color(style::MUTED));
}
@@ -1,9 +1,4 @@
//! Literal source search and line navigation, independent of accepted model state.
mod controller;
pub mod interaction;
pub mod query;
pub mod symbols;
pub use controller::*;
use iced::widget::text_editor::{Cursor, Position};
#[derive(Debug, Clone)]
@@ -1,126 +0,0 @@
//! Ephemeral editor navigation; no model commands or filesystem operations.
use super::query;
use iced::widget::text_editor::{Cursor, Position};
use oa_core::Id;
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
#[derive(Debug, Clone)]
pub enum SymbolEvent {
DiagramUsages,
Query(query::Action),
Back,
Close,
Choose {
stamp: query::QueryStamp,
reference: bool,
index: usize,
},
}
/// Identity of the mounted source view that emitted an action. Message queues
/// may outlive that view; request-time stamping alone cannot detect replay.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SymbolContext {
pub session: Id,
pub path: String,
}
#[derive(Debug, Clone)]
pub struct HistoryEntry {
pub session: Id,
pub path: String,
pub generation: u64,
pub cursor: Cursor,
}
#[derive(Debug, Clone)]
pub struct Request {
pub job: Id,
pub interaction: Id,
pub raw_interaction: u64,
pub stamp: query::QueryStamp,
pub path: String,
pub offset: usize,
pub cursor: Cursor,
pub action: query::Action,
}
#[derive(Debug, Clone)]
pub struct Completion {
pub request: Request,
pub result: Result<(Arc<query::Snapshot>, Arc<query::Results>), String>,
}
pub struct Reveal {
pub ticket: Id,
pub interaction: Id,
pub raw_interaction: u64,
pub snapshot: query::SnapshotKey,
pub path: String,
}
pub struct SymbolState {
pub open: bool,
pub interaction: Id,
pub raw_interaction: Arc<AtomicU64>,
pub serial: u64,
pub in_flight: Option<Id>,
pub request: Option<Request>,
pub cache: Option<Arc<query::Snapshot>>,
pub results: Option<Arc<query::Results>>,
pub notice: Option<String>,
pub back: Vec<HistoryEntry>,
pub reveal: Option<Reveal>,
}
impl Default for SymbolState {
fn default() -> Self {
Self {
open: false,
interaction: Id::new_v4(),
raw_interaction: Arc::new(AtomicU64::new(0)),
serial: 0,
in_flight: None,
request: None,
cache: None,
results: None,
notice: None,
back: Vec::new(),
reveal: None,
}
}
}
/// Iced uses zero-based UTF-8 byte columns. Reject stale or split-codepoint
/// coordinates; do not normalize CRLF or silently clamp query destinations.
pub fn byte_offset(text: &str, position: Position) -> Option<usize> {
let start = if position.line == 0 {
0
} else {
text.match_indices('\n').nth(position.line - 1)?.0 + 1
};
let end = text[start..]
.find('\n')
.map_or(text.len(), |end| start + end);
let offset = start.checked_add(position.column)?;
(offset <= end && text.is_char_boundary(offset)).then_some(offset)
}
pub fn cursor_offset(text: &str, cursor: Cursor) -> Option<usize> {
let position = cursor.selection.map_or(cursor.position, |selection| {
if (selection.line, selection.column) < (cursor.position.line, cursor.position.column) {
selection
} else {
cursor.position
}
});
byte_offset(text, position)
}
pub fn exact_cursor(text: &str, cursor: Cursor) -> bool {
byte_offset(text, cursor.position).is_some()
&& cursor
.selection
.is_none_or(|position| byte_offset(text, position).is_some())
}
@@ -1,284 +0,0 @@
//! Raw input invalidation and focus checks at widget-operation execution time.
use iced::advanced::{Clipboard, Layout, Shell, Widget, layout, overlay, renderer, widget};
use iced::{Element, Event, Length, Rectangle, Size, Task, Vector, keyboard, mouse, touch};
use std::sync::{
Arc,
atomic::{AtomicU64, Ordering},
};
/// Exhaustion fails closed: a saturated clock can never authorize navigation.
/// Replace the clock with a new workspace/controller, rather than wrapping it.
pub fn is_current(clock: &AtomicU64, expected: u64) -> bool {
expected != u64::MAX && clock.load(Ordering::Acquire) == expected
}
fn invalidate(clock: &AtomicU64, event: &Event) {
if matches!(
event,
Event::Keyboard(keyboard::Event::KeyPressed { .. })
| Event::Mouse(mouse::Event::ButtonPressed(_) | mouse::Event::WheelScrolled { .. })
| Event::Touch(touch::Event::FingerPressed { .. })
| Event::Window(iced::window::Event::Unfocused)
) {
let _ = clock.fetch_update(Ordering::AcqRel, Ordering::Acquire, |value| {
Some(value.saturating_add(1))
});
}
}
/// Transparent, including overlays: invalidate before the child can capture input.
pub fn observe<'a, Message: 'a, Theme: 'a, Renderer: renderer::Renderer + 'a>(
content: Element<'a, Message, Theme, Renderer>,
clock: Arc<AtomicU64>,
) -> Element<'a, Message, Theme, Renderer> {
Element::new(Observed { content, clock })
}
struct Observed<'a, Message, Theme, Renderer> {
content: Element<'a, Message, Theme, Renderer>,
clock: Arc<AtomicU64>,
}
impl<Message, Theme, Renderer: renderer::Renderer> Widget<Message, Theme, Renderer>
for Observed<'_, Message, Theme, Renderer>
{
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn size_hint(&self) -> Size<Length> {
self.content.as_widget().size_hint()
}
fn tag(&self) -> widget::tree::Tag {
self.content.as_widget().tag()
}
fn state(&self) -> widget::tree::State {
self.content.as_widget().state()
}
fn children(&self) -> Vec<widget::Tree> {
self.content.as_widget().children()
}
fn diff(&self, tree: &mut widget::Tree) {
self.content.as_widget().diff(tree);
}
fn layout(
&mut self,
tree: &mut widget::Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.content.as_widget_mut().layout(tree, renderer, limits)
}
fn draw(
&self,
tree: &widget::Tree,
renderer: &mut Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content
.as_widget()
.draw(tree, renderer, theme, style, layout, cursor, viewport);
}
fn operate(
&mut self,
tree: &mut widget::Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn widget::Operation,
) {
self.content
.as_widget_mut()
.operate(tree, layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut widget::Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
invalidate(&self.clock, event);
self.content.as_widget_mut().update(
tree, event, layout, cursor, renderer, clipboard, shell, viewport,
);
}
fn mouse_interaction(
&self,
tree: &widget::Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
self.content
.as_widget()
.mouse_interaction(tree, layout, cursor, viewport, renderer)
}
fn overlay<'a>(
&'a mut self,
tree: &'a mut widget::Tree,
layout: Layout<'a>,
renderer: &Renderer,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'a, Message, Theme, Renderer>> {
let clock = self.clock.clone();
self.content
.as_widget_mut()
.overlay(tree, layout, renderer, viewport, translation)
.map(|content| overlay::Element::new(Box::new(ObservedOverlay { content, clock })))
}
}
struct ObservedOverlay<'a, Message, Theme, Renderer> {
content: overlay::Element<'a, Message, Theme, Renderer>,
clock: Arc<AtomicU64>,
}
impl<Message, Theme, Renderer: renderer::Renderer> overlay::Overlay<Message, Theme, Renderer>
for ObservedOverlay<'_, Message, Theme, Renderer>
{
fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node {
self.content.as_overlay_mut().layout(renderer, bounds)
}
fn draw(
&self,
renderer: &mut Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
) {
self.content
.as_overlay()
.draw(renderer, theme, style, layout, cursor);
}
fn operate(
&mut self,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn widget::Operation,
) {
self.content
.as_overlay_mut()
.operate(layout, renderer, operation);
}
fn update(
&mut self,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
) {
invalidate(&self.clock, event);
self.content
.as_overlay_mut()
.update(event, layout, cursor, renderer, clipboard, shell);
}
fn mouse_interaction(
&self,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
) -> mouse::Interaction {
self.content
.as_overlay()
.mouse_interaction(layout, cursor, renderer)
}
fn overlay<'a>(
&'a mut self,
layout: Layout<'a>,
renderer: &Renderer,
) -> Option<overlay::Element<'a, Message, Theme, Renderer>> {
let clock = self.clock.clone();
self.content
.as_overlay_mut()
.overlay(layout, renderer)
.map(|content| overlay::Element::new(Box::new(ObservedOverlay { content, clock })))
}
fn index(&self) -> f32 {
self.content.as_overlay().index()
}
}
/// Inspect all focus owners, then focus only the mounted target. Iced executes
/// Operation::Chain synchronously, without an intervening input event. Both
/// traversals recheck the raw clock; no result message authorizes later focus.
pub fn guarded_focus<Message: Send + 'static>(
target: widget::Id,
clock: Arc<AtomicU64>,
expected: u64,
) -> Task<Message> {
widget::operate(GuardedFocus::new(target, clock, expected))
}
struct GuardedFocus {
target: widget::Id,
clock: Arc<AtomicU64>,
expected: u64,
target_count: usize,
foreign_focus: bool,
apply: bool,
}
impl GuardedFocus {
fn new(target: widget::Id, clock: Arc<AtomicU64>, expected: u64) -> Self {
Self {
target,
clock,
expected,
target_count: 0,
foreign_focus: false,
apply: false,
}
}
}
impl<Message: 'static> widget::Operation<Message> for GuardedFocus {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn widget::Operation<Message>)) {
if is_current(&self.clock, self.expected) {
visit(self);
}
}
fn focusable(
&mut self,
id: Option<&widget::Id>,
_: Rectangle,
state: &mut dyn widget::operation::Focusable,
) {
if !is_current(&self.clock, self.expected) {
return;
}
if id == Some(&self.target) {
self.target_count += 1;
if self.apply {
state.focus();
}
} else if state.is_focused() {
self.foreign_focus = true;
}
}
fn finish(&self) -> widget::operation::Outcome<Message> {
if !self.apply
&& self.target_count == 1
&& !self.foreign_focus
&& is_current(&self.clock, self.expected)
{
widget::operation::Outcome::Chain(Box::new(Self {
apply: true,
..Self::new(self.target.clone(), self.clock.clone(), self.expected)
}))
} else {
widget::operation::Outcome::None
}
}
}
#[cfg(all(test, debug_assertions))]
mod tests;
@@ -1,190 +0,0 @@
use super::*;
use iced::advanced::widget::operation::{Focusable, Outcome};
use iced::widget::{column, text_input};
use iced::{Point, Theme};
#[derive(Default)]
struct FocusMap(Vec<(Option<widget::Id>, Rectangle, bool)>);
impl widget::Operation for FocusMap {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn widget::Operation)) {
visit(self);
}
fn focusable(&mut self, id: Option<&widget::Id>, bounds: Rectangle, state: &mut dyn Focusable) {
self.0.push((id.cloned(), bounds, state.is_focused()));
}
}
struct Mounted {
element: Element<'static, (), Theme, ()>,
tree: widget::Tree,
node: layout::Node,
}
impl Mounted {
fn new(clock: Arc<AtomicU64>) -> Self {
let content = column![
text_input("Editor", "source")
.id("editor")
.on_input(|_| ())
.padding(12),
text_input("Find", "")
.id("find")
.on_input(|_| ())
.padding(12),
]
.spacing(10)
.into();
let mut element = observe(content, clock);
let mut tree = widget::Tree::new(element.as_widget());
let node = element.as_widget_mut().layout(
&mut tree,
&(),
&layout::Limits::new(Size::ZERO, Size::new(400., 200.)),
);
Self {
element,
tree,
node,
}
}
fn pass(&mut self, operation: &mut dyn widget::Operation) {
self.element.as_widget_mut().operate(
&mut self.tree,
Layout::new(&self.node),
&(),
operation,
);
}
fn run(&mut self, operation: impl widget::Operation + 'static) {
let mut next: Box<dyn widget::Operation> = Box::new(operation);
loop {
self.pass(next.as_mut());
match next.finish() {
Outcome::Chain(chained) => next = chained,
Outcome::None => break,
Outcome::Some(()) => panic!("focus must not publish an application message"),
}
}
}
fn focus(&mut self) -> FocusMap {
let mut focus = FocusMap::default();
self.pass(&mut focus);
focus
}
fn click(&mut self, id: &str) {
let bounds = self
.focus()
.0
.into_iter()
.find(|(found, _, _)| found.as_ref() == Some(&widget::Id::from(id.to_owned())))
.unwrap()
.1;
let mut messages = Vec::new();
let mut shell = Shell::new(&mut messages);
self.element.as_widget_mut().update(
&mut self.tree,
&Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Layout::new(&self.node),
mouse::Cursor::Available(bounds.center()),
&(),
&mut iced::advanced::clipboard::Null,
&mut shell,
&Rectangle::with_size(Size::new(400., 200.)),
);
assert!(shell.is_event_captured());
assert!(
messages.is_empty(),
"focus-only click must not rely on App messages"
);
}
fn focused(&mut self, id: &str) -> bool {
self.focus()
.0
.into_iter()
.find(|(found, _, _)| found.as_ref() == Some(&widget::Id::from(id.to_owned())))
.unwrap()
.2
}
}
#[test]
fn captured_find_click_invalidates_without_app_message_and_preserves_focus() {
let clock = Arc::new(AtomicU64::new(0));
let mut ui = Mounted::new(clock.clone());
ui.run(GuardedFocus::new("editor".into(), clock.clone(), 0));
assert!(ui.focused("editor"));
ui.click("find");
assert!(!is_current(&clock, 0));
assert!(ui.focused("find"));
ui.run(GuardedFocus::new("editor".into(), clock.clone(), 0));
assert!(ui.focused("find"));
// Even a matching clock cannot authorize stealing another widget's focus.
ui.run(GuardedFocus::new(
"editor".into(),
clock.clone(),
clock.load(Ordering::Acquire),
));
assert!(ui.focused("find"));
assert!(!ui.focused("editor"));
}
#[test]
fn focus_rechecks_clock_between_inspection_and_application_and_missing_target_is_inert() {
let clock = Arc::new(AtomicU64::new(0));
let mut ui = Mounted::new(clock.clone());
let mut operation = GuardedFocus::new("editor".into(), clock.clone(), 0);
ui.pass(&mut operation);
let Outcome::Chain(mut apply) = <GuardedFocus as widget::Operation<()>>::finish(&operation)
else {
panic!("mounted, unopposed target must be eligible");
};
clock.store(1, Ordering::Release);
ui.pass(apply.as_mut());
assert!(!ui.focused("editor"));
ui.run(GuardedFocus::new("editor".into(), clock.clone(), 1));
assert!(ui.focused("editor"));
ui.run(GuardedFocus::new("removed-editor".into(), clock, 1));
assert!(ui.focused("editor"));
}
#[test]
fn raw_navigation_inputs_advance_but_passive_geometry_does_not_and_exhaustion_refuses() {
let clock = AtomicU64::new(0);
let events = [
Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(keyboard::key::Named::ArrowLeft),
modified_key: keyboard::Key::Named(keyboard::key::Named::ArrowLeft),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::ArrowLeft),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::empty(),
text: None,
repeat: false,
}),
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Event::Mouse(mouse::Event::WheelScrolled {
delta: mouse::ScrollDelta::Lines { x: 0., y: 1. },
}),
Event::Touch(touch::Event::FingerPressed {
id: touch::Finger(1),
position: Point::ORIGIN,
}),
Event::Window(iced::window::Event::Unfocused),
];
for (index, event) in events.iter().enumerate() {
invalidate(&clock, event);
assert_eq!(clock.load(Ordering::Acquire), index as u64 + 1);
}
invalidate(
&clock,
&Event::Mouse(mouse::Event::CursorMoved {
position: Point::ORIGIN,
}),
);
invalidate(&clock, &Event::Window(iced::window::Event::Focused));
assert!(is_current(&clock, 5));
clock.store(u64::MAX - 1, Ordering::Release);
invalidate(&clock, &events[0]);
assert!(!is_current(&clock, u64::MAX));
invalidate(&clock, &events[0]);
assert_eq!(clock.load(Ordering::Acquire), u64::MAX);
assert!(!is_current(&clock, 0));
}
File diff suppressed because it is too large Load Diff
@@ -1,989 +0,0 @@
use super::*;
const PROJECT: &str = "00000000-0000-0000-0000-000000000001";
const PUMP: &str = "00000000-0000-0000-0000-000000000002";
const LINK: &str = "00000000-0000-0000-0000-000000000003";
#[derive(Clone)]
struct Fixture {
entry: String,
files: Vec<(String, String)>,
}
impl Fixture {
fn standard() -> Self {
Self {
entry: "project.arcadia".into(),
files: vec![
(
"project.arcadia".into(),
format!(
"arcadia 7;\r\nproject model \"Harbour\" id \"{PROJECT}\" {{\r\n include \"模块/活動.arcadia\";\r\n include \"links.arcadia\";\r\n}}\r\n"
),
),
(
"模块/活動.arcadia".into(),
format!(
"// 原文 remains exact\r\noa_activity pump \"泵 🚀\" id \"{PUMP}\" {{}}\r\n"
),
),
(
"links.arcadia".into(),
format!(
"// 航海\r\ninteraction connection \"流れ\" id \"{LINK}\" {{\r\n source @ // separator @pump\r\n pump;\r\n description \"船 @pump\"; target @pump;\r\n}}\r\n"
),
),
],
}
}
fn borrowed(&self) -> Vec<DraftFile<'_>> {
self.files
.iter()
.map(|(path, text)| DraftFile { path, text })
.collect()
}
fn text(&self, path: &str) -> &str {
&self
.files
.iter()
.find(|(candidate, _)| candidate == path)
.unwrap()
.1
}
fn text_mut(&mut self, path: &str) -> &mut String {
&mut self
.files
.iter_mut()
.find(|(candidate, _)| candidate == path)
.unwrap()
.1
}
fn snapshot(&self, validated: Option<&Self>, applied: bool, limits: Limits) -> Snapshot {
let current = self.borrowed();
let old = validated.map(Self::borrowed);
capture(
Input {
key: key(1),
entry: &self.entry,
files: &current,
applied,
validation: old.as_ref().map(|files| ValidatedSources {
entry: &validated.unwrap().entry,
files,
}),
},
limits,
)
.unwrap()
}
}
fn key(revision: u64) -> SnapshotKey {
SnapshotKey {
workspace: Id::from_u128(100),
revision,
}
}
fn query(snapshot: &Snapshot, path: &str, byte_offset: usize, action: Action) -> Results {
snapshot
.query(Query {
stamp: QueryStamp {
snapshot: snapshot.key(),
serial: 37,
},
path,
byte_offset,
action,
})
.unwrap()
}
fn reference_offset(fixture: &Fixture) -> usize {
fixture.text("links.arcadia").find("source @").unwrap() + "source ".len()
}
#[test]
fn exact_multifile_unicode_crlf_definition_and_repeated_lexical_references() {
let fixture = Fixture::standard();
let original = fixture.files.clone();
let snapshot = fixture.snapshot(Some(&fixture), true, Limits::default());
assert!(snapshot.scope().closure_complete && snapshot.scope().validated);
assert_eq!(
(
snapshot.scope().included_files,
snapshot.scope().detached_files
),
(3, 0)
);
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&fixture),
Action::Definition,
);
assert_eq!(result.disposition, Disposition::Direct);
assert_eq!(
(result.total_definitions, result.omitted_definitions),
(1, 0)
);
let definition = &result.definitions[0];
assert_eq!(definition.path, "模块/活動.arcadia");
assert_eq!(definition.declaration.kind, "oa_activity");
assert_eq!(definition.declaration.name.as_deref(), Some("泵 🚀"));
assert_eq!(
definition.declaration.authored_id,
Some(Id::parse_str(PUMP).unwrap())
);
assert_eq!(
definition.position,
Position {
line: 1,
byte_column: "oa_activity ".len()
}
);
assert_eq!(
&fixture.text(&definition.path)[definition.span.start..definition.span.end],
"pump"
);
let uses = query(
&snapshot,
&definition.path,
definition.span.start,
Action::References,
);
assert_eq!(uses.disposition, Disposition::LexicalReferences);
assert_eq!((uses.total_references, uses.omitted_references), (2, 0));
assert_eq!(
uses.references[0].position,
Position {
line: 3,
byte_column: 3
}
);
let target_prefix = " description \"船 @pump\"; target @";
assert_ne!(target_prefix.len(), target_prefix.chars().count());
assert_eq!(
uses.references[1].position,
Position {
line: 4,
byte_column: target_prefix.len()
}
);
for row in &uses.references {
let text = fixture.text(&row.path);
assert_eq!(&text[row.span.start..row.span.end], "pump");
assert_eq!(&text[row.marker.start..row.marker.end], "@");
let context = row.context.as_ref().unwrap();
assert_eq!(context.alias, "connection");
assert_eq!(context.kind, "interaction");
assert_eq!(context.name.as_deref(), Some("流れ"));
assert_eq!(row.evidence, Evidence::Validated);
}
assert_eq!(
uses.stamp,
QueryStamp {
snapshot: key(1),
serial: 37
}
);
assert_eq!(
fixture.files, original,
"no stabilization, newline rewrite or accepted adoption"
);
for (index, (path, text)) in original.iter().enumerate() {
let owned = snapshot.file(index).unwrap();
assert_eq!((owned.path, owned.text), (path.as_str(), text.as_str()));
}
}
#[test]
fn comments_strings_and_comment_gap_are_not_navigation_hits() {
let fixture = Fixture::standard();
let snapshot = fixture.snapshot(None, true, Limits::default());
let text = fixture.text("links.arcadia");
for offset in [
text.find("separator @pump").unwrap() + "separator ".len(),
text.find("船 @pump").unwrap() + "船 ".len(),
text.find("@ //").unwrap() + 1,
] {
let result = query(&snapshot, "links.arcadia", offset, Action::Definition);
assert_eq!(result.disposition, Disposition::NoSymbol);
assert_eq!(result.total_definitions, 0);
}
assert_eq!(
query(
&snapshot,
"links.arcadia",
text.find(" pump;").unwrap() + 3,
Action::Definition
)
.total_definitions,
1
);
let inside_utf8 = text.find('船').unwrap() + 1;
assert_eq!(
snapshot.query(Query {
stamp: QueryStamp {
snapshot: key(1),
serial: 1
},
path: "links.arcadia",
byte_offset: inside_utf8,
action: Action::Definition
}),
Err(QueryError::Query(symbols::QueryError::InvalidBytePosition))
);
}
#[test]
fn dirty_but_parseable_text_has_current_names_and_no_validated_fallback() {
let original = Fixture::standard();
let mut dirty = original.clone();
*dirty.text_mut("模块/活動.arcadia") = dirty
.text("模块/活動.arcadia")
.replace("泵 🚀", "Edited 泵\\nwith detail");
let snapshot = dirty.snapshot(Some(&original), true, Limits::default());
assert!(snapshot.scope().closure_complete);
assert!(!snapshot.scope().validated);
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&dirty),
Action::Definition,
);
assert_eq!(result.disposition, Disposition::Choices);
assert_eq!(
result.definitions[0].declaration.name.as_deref(),
Some("Edited 泵\nwith detail")
);
assert_eq!(result.definitions[0].evidence, Evidence::Draft);
assert_eq!(
snapshot.file(1).unwrap().text,
dirty.text("模块/活動.arcadia")
);
assert_ne!(
snapshot.file(1).unwrap().text,
original.text("模块/活動.arcadia")
);
}
#[test]
fn invalid_include_syntax_never_borrows_the_old_reachable_file_set() {
let original = Fixture::standard();
let mut invalid = original.clone();
*invalid.text_mut("project.arcadia") = invalid
.text("project.arcadia")
.replace("include \"links.arcadia\";", "include \"links.arcadia\"");
let snapshot = invalid.snapshot(Some(&original), true, Limits::default());
assert!(snapshot.scope().partial());
assert!(!snapshot.scope().validated);
assert!(
snapshot
.scope()
.issues
.iter()
.any(|issue| issue.kind == ScopeIssueKind::InvalidIncludes)
);
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&invalid),
Action::Definition,
);
assert_eq!(result.total_definitions, 1);
assert_eq!(result.disposition, Disposition::Choices);
assert_eq!(result.definitions[0].membership, Membership::Unverified);
}
#[test]
fn missing_include_partial_scope_does_not_resurrect_witness_text() {
let original = Fixture::standard();
let mut missing = original.clone();
missing
.files
.retain(|(path, _)| path != "模块/活動.arcadia");
let snapshot = missing.snapshot(Some(&original), true, Limits::default());
assert!(snapshot.scope().partial());
assert!(
snapshot
.scope()
.issues
.iter()
.any(|issue| issue.kind == ScopeIssueKind::MissingInclude)
);
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&missing),
Action::Definition,
);
assert_eq!(result.disposition, Disposition::NoDefinition);
assert!(result.definitions.is_empty());
assert!(
result.scope.partial(),
"zero means no loaded definition, not no project definition"
);
assert!(snapshot.file(2).is_none());
}
#[test]
fn detached_alias_and_identity_collisions_never_auto_select() {
let accepted = Fixture::standard();
for (alias, id) in [
("pump", "00000000-0000-0000-0000-000000000099"),
("other", PUMP),
] {
let mut loaded = accepted.clone();
loaded.files.push((
"detached.arcadia".into(),
format!("oa_activity {alias} \"Detached\" id \"{id}\" {{}}"),
));
let snapshot = loaded.snapshot(Some(&accepted), true, Limits::default());
assert!(snapshot.scope().validated);
assert_eq!(snapshot.scope().detached_files, 1);
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&loaded),
Action::Definition,
);
assert_eq!(result.disposition, Disposition::Choices);
if alias == "pump" {
assert_eq!(result.total_definitions, 2);
assert!(result.definitions.iter().any(
|row| row.membership == Membership::Detached && row.evidence == Evidence::Draft
));
} else {
assert_eq!(result.total_definitions, 1);
assert_eq!(
result.definitions[0].declaration.identity,
Identity::Collision { count: 2 }
);
}
}
}
#[test]
fn sole_detached_candidate_and_unapplied_equal_bytes_require_choice() {
let accepted = Fixture::standard();
let mut detached = accepted.clone();
*detached.text_mut("project.arcadia") = detached
.text("project.arcadia")
.replace(" include \"模块/活動.arcadia\";\r\n", "");
let snapshot = detached.snapshot(None, true, Limits::default());
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&detached),
Action::Definition,
);
assert_eq!(result.disposition, Disposition::Choices);
assert_eq!(result.definitions[0].membership, Membership::Detached);
let unapplied = accepted.snapshot(Some(&accepted), false, Limits::default());
assert!(unapplied.scope().closure_complete && unapplied.scope().partial());
assert!(!unapplied.scope().validated);
assert_eq!(
query(
&unapplied,
"links.arcadia",
reference_offset(&accepted),
Action::Definition
)
.disposition,
Disposition::Choices
);
}
#[test]
fn include_cycle_depth_and_aggregate_edges_are_explicit_partial_outcomes() {
let mut fixture = Fixture::standard();
fixture
.text_mut("模块/活動.arcadia")
.push_str("include \"../project.arcadia\";\r\n");
let cycle = fixture.snapshot(None, true, Limits::default());
assert!(
cycle
.scope()
.issues
.iter()
.any(|issue| issue.kind == ScopeIssueKind::IncludeCycle)
);
let fixture = Fixture::standard();
for (depth, edges, expected) in [
(0, 1024, ScopeIssueKind::IncludeDepth),
(32, 1, ScopeIssueKind::IncludeBudget),
] {
let snapshot = fixture.snapshot(
None,
true,
Limits {
include_depth: depth,
include_edges: edges,
..Limits::default()
},
);
assert!(snapshot.scope().partial());
assert!(
snapshot
.scope()
.issues
.iter()
.any(|issue| issue.kind == expected)
);
assert_eq!(
query(
&snapshot,
"links.arcadia",
reference_offset(&fixture),
Action::Definition
)
.disposition,
Disposition::Choices
);
}
}
#[test]
fn exact_snapshot_readback_rejects_same_key_byte_membership_and_evidence_changes() {
let fixture = Fixture::standard();
let files = fixture.borrowed();
let validation = Some(ValidatedSources {
entry: &fixture.entry,
files: &files,
});
let input = Input {
key: key(1),
entry: &fixture.entry,
files: &files,
applied: true,
validation,
};
let snapshot = capture(input, Limits::default()).unwrap();
assert!(snapshot.matches(input));
assert!(!snapshot.matches(Input {
key: key(2),
..input
}));
assert!(!snapshot.matches(Input {
validation: None,
..input
}));
assert!(!snapshot.matches(Input {
applied: false,
..input
}));
let mut reversed = files.clone();
reversed.reverse();
assert!(snapshot.matches(Input {
files: &reversed,
..input
}));
let mut changed = fixture.clone();
changed.text_mut("links.arcadia").push(' ');
let altered = changed.borrowed();
assert!(!snapshot.matches(Input {
files: &altered,
..input
}));
let missing = &files[..files.len() - 1];
assert!(!snapshot.matches(Input {
files: missing,
..input
}));
let duplicated = [files[0], files[0], files[2]];
assert!(!snapshot.matches(Input {
files: &duplicated,
..input
}));
assert_eq!(
snapshot.query(Query {
stamp: QueryStamp {
snapshot: key(2),
serial: 37
},
path: "links.arcadia",
byte_offset: 0,
action: Action::Definition
}),
Err(QueryError::Query(symbols::QueryError::StaleSnapshot))
);
}
#[test]
fn omitted_rows_are_counted_before_result_allocation_and_never_confer_uniqueness() {
let fixture = Fixture::standard();
let snapshot = fixture.snapshot(
Some(&fixture),
true,
Limits {
result_rows: 2,
..Limits::default()
},
);
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&fixture),
Action::References,
);
assert_eq!((result.total_definitions, result.total_references), (1, 2));
assert_eq!(
(
result.definitions.len(),
result.references.len(),
result.omitted_references
),
(1, 1, 1)
);
let zero = fixture.snapshot(
Some(&fixture),
true,
Limits {
result_rows: 0,
..Limits::default()
},
);
let result = query(
&zero,
"links.arcadia",
reference_offset(&fixture),
Action::Definition,
);
assert_eq!(
(
result.definitions.len(),
result.total_definitions,
result.omitted_definitions
),
(0, 1, 1)
);
assert_eq!(result.disposition, Disposition::Choices);
let envelope = fixture.snapshot(
Some(&fixture),
true,
Limits {
result_bytes: 0,
..Limits::default()
},
);
assert_eq!(
envelope.query(Query {
stamp: QueryStamp {
snapshot: key(1),
serial: 1
},
path: "links.arcadia",
byte_offset: reference_offset(&fixture),
action: Action::Definition
}),
Err(QueryError::ResultEnvelopeLimit)
);
}
#[test]
fn large_display_name_cannot_escape_the_owned_row_string_budget() {
let mut fixture = Fixture::standard();
*fixture.text_mut("模块/活動.arcadia") = fixture
.text("模块/活動.arcadia")
.replace("泵 🚀", &"長".repeat(8192));
let original = fixture.files.clone();
let snapshot = fixture.snapshot(
None,
true,
Limits {
result_bytes: 64,
..Limits::default()
},
);
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&fixture),
Action::Definition,
);
assert_eq!(
(result.total_definitions, result.omitted_definitions),
(1, 1)
);
assert!(result.definitions.is_empty());
assert_eq!(result.disposition, Disposition::Choices);
assert_eq!(fixture.files, original);
}
#[test]
fn validation_witness_must_match_entry_and_complete_included_file_set() {
let fixture = Fixture::standard();
for mutation in 0..3 {
let mut witness = fixture.clone();
match mutation {
0 => witness.entry = "other.arcadia".into(),
1 => {
witness.files.pop();
}
_ => witness.files.push(("unused.arcadia".into(), String::new())),
}
let snapshot = fixture.snapshot(Some(&witness), true, Limits::default());
assert!(snapshot.scope().closure_complete);
assert!(!snapshot.scope().validated);
assert_eq!(
query(
&snapshot,
"links.arcadia",
reference_offset(&fixture),
Action::Definition
)
.disposition,
Disposition::Choices
);
}
}
#[test]
fn raw_aggregate_limits_refuse_before_outline_or_copied_snapshot() {
// Token budget zero and malformed paths/text would fail later. Raw byte/path
// limits must win, including a large second file; no partial Snapshot exists.
let large = "not a model \0".repeat(16_384);
let files = [
DraftFile {
path: "../bad.arcadia",
text: "?",
},
DraftFile {
path: "large.arcadia",
text: &large,
},
];
let input = Input {
key: key(1),
entry: "project.arcadia",
files: &files,
applied: true,
validation: None,
};
for (resource, files_limit, bytes_limit, paths_limit) in [
(symbols::Resource::Files, 1, usize::MAX, usize::MAX),
(symbols::Resource::SourceBytes, 8, 1, usize::MAX),
(symbols::Resource::PathBytes, 8, usize::MAX, 1),
] {
let limits = Limits {
index: symbols::Limits {
files: files_limit,
source_bytes: bytes_limit,
path_bytes: paths_limit,
tokens: 0,
records: 0,
},
..Limits::default()
};
assert!(
matches!(capture(input, limits), Err(AdmissionError::Index(symbols::BuildError::Limit { resource: actual, .. })) if actual == resource)
);
}
assert_eq!(files[1].text, large);
}
#[test]
fn token_declaration_and_live_reference_limits_are_aggregate_not_per_file() {
let files = [
DraftFile {
path: "a.arcadia",
text: "oa_activity a \"A\" {}",
},
DraftFile {
path: "b.arcadia",
text: "oa_activity b \"B\" {}",
},
];
let input = Input {
key: key(1),
entry: "a.arcadia",
files: &files,
applied: false,
validation: None,
};
let limits = Limits {
index: symbols::Limits {
tokens: 10,
..Limits::default().index
},
..Limits::default()
};
assert!(matches!(
capture(input, limits),
Err(AdmissionError::Outline {
file: 1,
error: language::OutlineLimit {
resource: language::OutlineResource::Tokens,
..
}
})
));
let limits = Limits {
index: symbols::Limits {
records: 1,
..Limits::default().index
},
..Limits::default()
};
assert!(matches!(
capture(input, limits),
Err(AdmissionError::Outline {
file: 1,
error: language::OutlineLimit {
resource: language::OutlineResource::Declarations,
..
}
})
));
let use_files = [
files[0],
DraftFile {
path: "uses.arcadia",
text: "source @a; target @a; // @a ignored\n",
},
];
let limits = Limits {
index: symbols::Limits {
records: 2,
..Limits::default().index
},
..Limits::default()
};
assert!(matches!(
capture(
Input {
files: &use_files,
..input
},
limits
),
Err(AdmissionError::Index(symbols::BuildError::Limit {
resource: symbols::Resource::Records,
observed_at_least: 3,
..
}))
));
}
#[test]
fn missing_and_noncanonical_authored_ids_remain_draft_spans_without_generated_anchors() {
let fixture = Fixture::standard();
for replacement in [
String::new(),
" id \"00000000000000000000000000000002\"".into(),
] {
let mut draft = fixture.clone();
let original_id = format!(" id \"{PUMP}\"");
*draft.text_mut("模块/活動.arcadia") = draft
.text("模块/活動.arcadia")
.replace(&original_id, &replacement);
draft
.text_mut("模块/活動.arcadia")
.push_str(&format!("// Historical UUID {PUMP} and @pump\r\n"));
let before = draft.files.clone();
let snapshot = draft.snapshot(None, false, Limits::default());
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&draft),
Action::Definition,
);
assert_eq!(result.definitions[0].declaration.authored_id, None);
assert_eq!(
result.definitions[0].declaration.identity,
Identity::Missing
);
assert_eq!(result.disposition, Disposition::Choices);
assert_eq!(draft.files, before);
assert_eq!(
snapshot.file(1).unwrap().text,
draft.text("模块/活動.arcadia")
);
}
}
#[test]
fn keyword_alias_and_loaded_path_case_collisions_use_reviewed_index_rules() {
let mut fixture = Fixture::standard();
for (_, text) in &mut fixture.files {
*text = text.replace("pump", "source");
}
let snapshot = fixture.snapshot(None, true, Limits::default());
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&fixture),
Action::Definition,
);
assert_eq!(result.alias.as_deref(), Some("source"));
assert_eq!(result.total_definitions, 1);
fixture.files.push(("LINKS.arcadia".into(), String::new()));
let files = fixture.borrowed();
assert!(matches!(
capture(
Input {
key: key(1),
entry: &fixture.entry,
files: &files,
applied: true,
validation: None
},
Limits::default()
),
Err(AdmissionError::Index(symbols::BuildError::Input {
problem: symbols::InputProblem::DuplicateOrCaseCollidingPath,
..
}))
));
}
#[test]
fn owned_request_moves_exact_text_into_worker_snapshot_and_matches_sync_results() {
let fixture = Fixture::standard();
let files = fixture.borrowed();
let input = Input {
key: key(1),
entry: &fixture.entry,
files: &files,
applied: true,
validation: Some(ValidatedSources {
entry: &fixture.entry,
files: &files,
}),
};
let owned = admit_owned(input, Limits::default()).unwrap();
let allocations: Vec<_> = owned.files.iter().map(|file| file.text.as_ptr()).collect();
let snapshot = owned.capture().unwrap();
for (file, allocation) in allocations.iter().enumerate() {
assert_eq!(
snapshot.file(file).unwrap().text.as_ptr(),
*allocation,
"worker moves the one current-text copy"
);
}
assert!(snapshot.matches(input));
let synchronous = capture(input, Limits::default()).unwrap();
assert_eq!(
query(
&snapshot,
"links.arcadia",
reference_offset(&fixture),
Action::References
),
query(
&synchronous,
"links.arcadia",
reference_offset(&fixture),
Action::References
)
);
let mut edited = fixture.clone();
edited
.text_mut("links.arcadia")
.push_str("// edited after request\r\n");
let changed = edited.borrowed();
assert!(!snapshot.matches(Input {
files: &changed,
..input
}));
assert!(!snapshot.matches(Input {
validation: None,
..input
}));
}
#[test]
fn owned_request_checks_raw_limits_immediately_and_extracts_only_on_worker() {
let fixture = Fixture::standard();
let files = fixture.borrowed();
let input = Input {
key: key(1),
entry: &fixture.entry,
files: &files,
applied: true,
validation: None,
};
let no_tokens = Limits {
index: symbols::Limits {
tokens: 0,
..Limits::default().index
},
..Limits::default()
};
let owned = admit_owned(input, no_tokens).expect("request admission does not lex or parse");
assert!(matches!(
owned.capture(),
Err(AdmissionError::Outline {
file: 0,
error: language::OutlineLimit {
resource: language::OutlineResource::Tokens,
..
}
})
));
let no_bytes = Limits {
index: symbols::Limits {
source_bytes: 1,
..Limits::default().index
},
..Limits::default()
};
assert!(matches!(
admit_owned(input, no_bytes),
Err(AdmissionError::Index(symbols::BuildError::Limit {
resource: symbols::Resource::SourceBytes,
..
}))
));
assert_eq!(files[1].text, fixture.text("模块/活動.arcadia"));
}
#[test]
fn owned_validation_proof_preserves_full_witness_count_and_partial_scope() {
let accepted = Fixture::standard();
for missing_include in [false, true] {
let mut current = accepted.clone();
current
.files
.retain(|(path, _)| path != "模块/活動.arcadia");
if !missing_include {
*current.text_mut("project.arcadia") = current
.text("project.arcadia")
.replace(" include \"模块/活動.arcadia\";\r\n", "");
}
let files = current.borrowed();
let old = accepted.borrowed();
let input = Input {
key: key(1),
entry: &current.entry,
files: &files,
applied: true,
validation: Some(ValidatedSources {
entry: &accepted.entry,
files: &old,
}),
};
let snapshot = admit_owned(input, Limits::default())
.unwrap()
.capture()
.unwrap();
assert_eq!(snapshot.scope().closure_complete, !missing_include);
assert!(
!snapshot.scope().validated,
"the old witness is not silently reduced to matching loaded files"
);
let result = query(
&snapshot,
"links.arcadia",
reference_offset(&current),
Action::Definition,
);
assert_eq!(result.disposition, Disposition::NoDefinition);
assert!(snapshot.matches(input));
}
}
File diff suppressed because it is too large Load Diff
+4 -217
View File
@@ -1,7 +1,7 @@
//! Per-file drafts and navigation. Accepted model/source history lives in Document.
use iced::widget::text_editor::Cursor;
use oa_core::{
Id, language,
language,
source_project::{self, CompiledSourceProject, ProjectLimits, SourceBundle, SourceDiagnostic},
};
use std::collections::{BTreeMap, BTreeSet};
@@ -86,7 +86,6 @@ pub struct Buffer {
pub cursor: Cursor,
past: Vec<String>,
future: Vec<String>,
generation: u64,
}
impl Buffer {
@@ -100,20 +99,14 @@ impl Buffer {
},
past: Vec::new(),
future: Vec::new(),
generation: 0,
}
}
pub fn dirty(&self) -> bool {
self.text != self.baseline
}
pub fn generation(&self) -> u64 {
self.generation
}
}
pub struct Workspace {
session: Id,
revision: u64,
pub entry: String,
pub active: String,
pub files: BTreeMap<String, Buffer>,
@@ -124,35 +117,6 @@ pub struct Workspace {
}
impl Workspace {
/// Ephemeral editor identity, never a model identity or recovery payload.
pub fn session(&self) -> Id {
self.session
}
pub fn revision(&self) -> u64 {
self.revision
}
fn advance(&mut self) -> u64 {
if let Some(revision) = self.revision.checked_add(1) {
self.revision = revision;
} else {
self.reset_navigation_session();
}
self.revision
}
/// A changed filesystem root must not reuse queued navigation from Save As.
pub fn reset_navigation_session(&mut self) {
self.session = Id::new_v4();
self.revision = 0;
for buffer in self.files.values_mut() {
buffer.generation = 0;
}
}
pub fn set_reachable(&mut self, reachable: BTreeSet<String>) {
if self.reachable != reachable {
self.advance();
self.reachable = reachable;
}
}
pub fn recovery_snapshot(&self) -> RecoveryWorkspace {
RecoveryWorkspace {
entry: self.entry.clone(),
@@ -172,8 +136,6 @@ impl Workspace {
pub fn from_recovery(saved: RecoveryWorkspace) -> Result<Self, String> {
saved.validate()?;
Ok(Self {
session: Id::new_v4(),
revision: 0,
entry: saved.entry,
active: saved.active,
files: saved
@@ -192,8 +154,6 @@ impl Workspace {
}
pub fn new(bundle: &SourceBundle, applied: bool) -> Self {
Self {
session: Id::new_v4(),
revision: 0,
entry: bundle.entry.clone(),
active: bundle.entry.clone(),
files: bundle
@@ -231,20 +191,11 @@ impl Workspace {
}
}
pub fn edit(&mut self, text: String, cursor: Cursor) {
let changed = self.files.get(&self.active).is_none_or(|b| b.text != text);
let generation = if changed {
self.advance()
} else {
self.revision
};
let buffer = self
.files
.entry(self.active.clone())
.or_insert_with(|| Buffer::new(String::new()));
buffer.cursor = cursor;
if changed {
buffer.generation = generation;
}
if text != buffer.text {
buffer.past.push(std::mem::replace(&mut buffer.text, text));
if buffer.past.len() > 100 {
@@ -317,8 +268,6 @@ impl Workspace {
} else {
buffer.future.push(previous);
}
let generation = self.advance();
self.files.get_mut(&self.active).unwrap().generation = generation;
self.trim_history(DRAFT_HISTORY_BYTES);
true
}
@@ -332,7 +281,6 @@ impl Workspace {
}
}
pub fn accept(&mut self, bundle: &SourceBundle) {
let generation = self.advance();
if self.entry != bundle.entry
&& !bundle.files.contains_key(&self.entry)
&& self.files.get(&self.entry).is_some_and(|b| !b.dirty())
@@ -343,13 +291,7 @@ impl Workspace {
self.reachable = bundle.files.keys().cloned().collect();
for (path, text) in &bundle.files {
let cursor = self.files.get(path).map(|b| b.cursor);
let previous_generation = self
.files
.get(path)
.filter(|b| b.text == *text)
.map(|b| b.generation);
let mut buffer = Buffer::new(text.clone());
buffer.generation = previous_generation.unwrap_or(generation);
if let Some(cursor) = cursor {
buffer.cursor = cursor;
}
@@ -361,22 +303,10 @@ impl Workspace {
self.applied = true;
}
pub fn discovered(&mut self, bundle: &SourceBundle, reachable: BTreeSet<String>) {
let changed = self.reachable != reachable
|| bundle
.files
.keys()
.any(|path| !self.files.contains_key(path));
let generation = if changed {
self.advance()
} else {
self.revision
};
for (path, text) in &bundle.files {
self.files.entry(path.clone()).or_insert_with(|| {
let mut buffer = Buffer::new(text.clone());
buffer.generation = generation;
buffer
});
self.files
.entry(path.clone())
.or_insert_with(|| Buffer::new(text.clone()));
}
self.reachable = reachable;
}
@@ -384,7 +314,6 @@ impl Workspace {
if self.reachable.contains(path) || self.files.get(path).is_none_or(Buffer::dirty) {
return false;
}
self.advance();
self.files.remove(path);
if self.active == path {
self.active = self.entry.clone();
@@ -447,148 +376,6 @@ pub fn lint(bundle: &SourceBundle) -> Vec<SourceDiagnostic> {
mod tests {
use super::*;
use oa_core::Project;
#[test]
fn fresh_session_cannot_reuse_a_retained_buffer_generation() {
let bundle = SourceBundle {
entry: "main.arcadia".into(),
files: BTreeMap::from([
("main.arcadia".into(), "first".into()),
("other.arcadia".into(), "other".into()),
]),
};
let mut workspace = Workspace::new(&bundle, true);
let cursor = workspace.files["main.arcadia"].cursor;
workspace.edit("second".into(), cursor);
workspace.reset_navigation_session();
let before = workspace.files["main.arcadia"].generation();
workspace.edit("third".into(), cursor);
assert_ne!(workspace.files["main.arcadia"].generation(), before);
workspace.switch("other.arcadia", cursor);
workspace.revision = u64::MAX;
workspace.edit("changed other".into(), cursor);
let after_wrap = workspace.files["main.arcadia"].generation();
workspace.switch("main.arcadia", cursor);
workspace.edit("fourth".into(), cursor);
assert_ne!(workspace.files["main.arcadia"].generation(), after_wrap);
assert!(workspace.undo(false));
assert_eq!(workspace.text(), "third");
}
#[test]
fn navigation_versions_distinguish_reopened_recovered_and_changed_drafts() {
let bundle = SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([
("project.arcadia".into(), "entry\r\n".into()),
("part.arcadia".into(), "雨 draft\r\n".into()),
]),
};
let mut workspace = Workspace::new(&bundle, true);
let reopened = Workspace::new(&bundle, true);
let recovered = Workspace::from_recovery(workspace.recovery_snapshot()).unwrap();
assert_ne!(workspace.session(), reopened.session());
assert_ne!(workspace.session(), recovered.session());
assert_eq!(workspace.bundle(), recovered.bundle());
let saved = serde_json::to_value(workspace.recovery_snapshot()).unwrap();
assert!(saved.get("session").is_none() && saved.get("revision").is_none());
let cursor = Cursor {
position: iced::widget::text_editor::Position { line: 0, column: 3 },
selection: None,
};
let revision = workspace.revision();
workspace.edit(workspace.text().into(), cursor);
assert_eq!(
workspace.revision(),
revision,
"selection is not a text change"
);
workspace.switch("part.arcadia", cursor);
assert_eq!(
workspace.revision(),
revision,
"switching retains the snapshot"
);
let untouched = workspace.files["project.arcadia"].generation();
workspace.edit("雨 unfinished !\r\n".into(), cursor);
let edited = workspace.files["part.arcadia"].generation();
assert!(workspace.revision() > revision);
assert_eq!(workspace.files["project.arcadia"].generation(), untouched);
assert!(workspace.undo(false));
assert_eq!(workspace.bundle(), bundle);
assert!(workspace.files["part.arcadia"].generation() > edited);
assert!(workspace.undo(true));
assert_eq!(workspace.text(), "雨 unfinished !\r\n");
let previous_session = workspace.session();
let previous_text = workspace.bundle();
workspace.reset_navigation_session();
assert_ne!(workspace.session(), previous_session);
assert_eq!(workspace.bundle(), previous_text);
assert!(
workspace.undo(false),
"session reset preserves text history"
);
}
#[test]
fn navigation_scope_changes_invalidate_without_changing_unchanged_positions() {
let bundle = SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([
("project.arcadia".into(), "entry".into()),
("part.arcadia".into(), "part".into()),
]),
};
let mut workspace = Workspace::new(&bundle, true);
let entry_generation = workspace.files[&bundle.entry].generation();
let initial_revision = workspace.revision();
workspace.set_reachable(BTreeSet::from([bundle.entry.clone()]));
assert!(workspace.revision() > initial_revision);
let membership_revision = workspace.revision();
workspace.set_reachable(workspace.reachable.clone());
assert_eq!(workspace.revision(), membership_revision);
assert!(workspace.discard_detached("part.arcadia"));
assert!(workspace.revision() > membership_revision);
let closed_revision = workspace.revision();
workspace.discovered(&bundle, BTreeSet::from([bundle.entry.clone()]));
assert!(workspace.revision() > closed_revision);
assert_eq!(
workspace.files[&bundle.entry].generation(),
entry_generation
);
assert!(workspace.files["part.arcadia"].generation() > closed_revision);
let discovered_revision = workspace.revision();
workspace.discovered(&bundle, workspace.reachable.clone());
assert_eq!(workspace.revision(), discovered_revision);
workspace.accept(&bundle);
assert!(
workspace.revision() > discovered_revision,
"validation evidence changed"
);
assert_eq!(
workspace.files[&bundle.entry].generation(),
entry_generation
);
assert_eq!(workspace.bundle(), bundle);
}
#[test]
fn navigation_revision_wrap_cannot_reuse_an_old_workspace_key() {
let bundle = SourceBundle {
entry: "project.arcadia".into(),
files: BTreeMap::from([("project.arcadia".into(), "original".into())]),
};
let mut workspace = Workspace::new(&bundle, true);
workspace.revision = u64::MAX;
let before = workspace.session();
let cursor = workspace.files[&bundle.entry].cursor;
workspace.edit("changed".into(), cursor);
assert_ne!(workspace.session(), before);
assert_eq!(workspace.revision(), 0);
assert!(workspace.undo(false));
assert_eq!(workspace.bundle(), bundle);
}
#[test]
fn draft_history_budget_covers_inactive_files_without_discarding_drafts() {
let bundle = SourceBundle {
+3 -415
View File
@@ -377,8 +377,7 @@ fn source_navigation_waits_for_editor_layout_and_cancels_on_edit() {
send(&mut app, Message::SourceForSelection);
assert_eq!(app.page, Page::Text);
assert!(app.source_jump.is_some());
let ticket = app.source_reveal_ticket();
send(&mut app, Message::SourceViewport(ticket));
send(&mut app, Message::SourceViewport);
assert!(app.source_jump.is_none());
send(&mut app, Message::SourceForSelection);
assert!(app.source_jump.is_some());
@@ -410,8 +409,7 @@ fn source_find_navigates_an_invalid_draft_without_applying_or_losing_it() {
cursor.selection,
Some(text_editor::Position { line: 0, column: 9 })
);
let ticket = app.source_reveal_ticket();
send(&mut app, Message::SourceViewport(ticket));
send(&mut app, Message::SourceViewport);
assert_eq!(app.source_editor.cursor(), cursor);
send(
&mut app,
@@ -1271,26 +1269,7 @@ fn revealing_an_implicit_function_port_unfolds_its_visible_architecture_owner()
.get_mut(&ancestor)
.unwrap()
.collapsed = true;
// The usage query reports rendered objects; this port's owner is folded.
// The legacy authoring reveal below explicitly expands its saved ancestor.
assert!(
!oa_core::projection::project_view(&p, diagram)
.ports
.iter()
.any(|shown| shown.element == port)
);
assert!(crate::diagram_usage::saved_usages_for(&p, port, Some(diagram)).is_empty());
// Other saved views of this function may still paint the port.
let elsewhere = crate::diagram_usage::saved_usages(&p, port);
assert!(
!elsewhere.is_empty(),
"the demo still paints this port in another saved view"
);
assert!(
elsewhere
.iter()
.all(|usage| usage.surface != crate::diagram_usage::Surface::Saved(diagram))
);
assert!(crate::navigation::diagrams_containing(&p, port).contains(&diagram));
let mut app = App::with_project(p);
send(&mut app, Message::RevealInDiagram(diagram, port));
assert_eq!(app.selected, port);
@@ -1302,12 +1281,6 @@ fn revealing_an_implicit_function_port_unfolds_its_visible_architecture_owner()
.iter()
.any(|p| p.element == port)
);
assert!(
crate::diagram_usage::saved_usages_for(app.project(), port, Some(diagram))
.iter()
.any(|usage| matches!(usage.target,
crate::diagram_usage::Target::Port { port: found, .. } if found == port))
);
}
#[test]
@@ -1690,388 +1663,3 @@ fn adding_bend_between_close_ports_stays_outside_owner_clearance() {
}]
);
}
#[test]
fn child_work_preserves_allocated_context_and_atomic_history() {
use oa_core::projection::project_view;
for (layer, performer_kind, work_kind) in [
(Layer::Oa, Kind::Entity, Kind::Activity),
(Layer::Sa, Kind::System, Kind::Function),
] {
for folded in [false, true] {
let mut p = Project::empty();
let performer = p
.add_element(performer_kind, layer, "Performer", None)
.unwrap();
let work = p
.add_element(work_kind, layer, "Parent work", None)
.unwrap();
let allocation = p.relate(
RelationKind::Allocation,
"Engineering assignment",
performer,
work,
);
p.relations.get_mut(&allocation).unwrap().description =
"Retain assignment metadata".into();
let original = p.relations[&allocation].clone();
let diagram = p.ensure_diagram(layer);
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Allocation;
let performer_node = p.place(diagram, performer, Position { x: 60., y: 60. });
let work_node = p.place(diagram, work, Position { x: 84., y: 124. });
p = execute_batch(&p, &[Command::Layout(diagram)]).unwrap();
for node in [performer_node, work_node] {
p.diagrams
.get_mut(&diagram)
.unwrap()
.nodes
.get_mut(&node)
.unwrap()
.collapsed = folded;
}
let mut app = App::with_project(p);
send(&mut app, Message::Layer(layer));
send(&mut app, Message::Page(Page::Diagram));
send(
&mut app,
Message::Diagram(crate::app::Choice {
id: diagram,
label: String::new(),
}),
);
let mut first = None;
for step in 0..3 {
let parent = if step == 2 { first.unwrap() } else { work };
send(&mut app, Message::Select(parent));
let before = app.project().clone();
let before_source = app.document.bundle().clone();
send(&mut app, Message::CreateContextElement(work_kind, true));
let created = app.selected;
assert!(
!before.elements.contains_key(&created),
"{layer:?} step {step}: {}",
app.status
);
assert_eq!(app.project().elements.len(), before.elements.len() + 1);
assert_eq!(app.project().elements[&created].parent, Some(parent));
for (id, element) in &before.elements {
assert_eq!(&app.project().elements[id], element);
}
assert!(
!oa_core::validation::validate(app.project())
.iter()
.any(|i| i.severity == oa_core::validation::Severity::Error)
);
assert_eq!(
oa_core::validation::allocation_summary(app.project(), work),
Some(performer)
);
assert_eq!(
oa_core::validation::effective_performer(app.project(), created),
Some(performer)
);
assert!(
!app.project()
.relations
.values()
.any(|r| r.kind() == RelationKind::Allocation && r.target() == parent)
);
if step != 1 {
let mut expected = original.clone();
if let RelationBody::Allocation { target, .. } = &mut expected.body {
*target = created;
}
assert_eq!(app.project().relations[&allocation], expected);
} else {
assert_eq!(
app.project().relations[&allocation],
before.relations[&allocation]
);
}
assert_eq!(
app.project().relations.len(),
before.relations.len() + usize::from(step == 1)
);
let view = project_view(app.project(), diagram);
let parent_node = view.nodes.iter().find(|n| n.element == parent).unwrap();
let child_node = view.nodes.iter().find(|n| n.element == created).unwrap();
let root_node = view.nodes.iter().find(|n| n.element == work).unwrap();
assert_eq!(root_node.visual_parent, Some(performer_node));
assert_eq!(child_node.visual_parent, Some(parent_node.id));
assert!(!app.project().diagrams[&diagram].nodes[&performer_node].collapsed);
assert!(!app.project().diagrams[&diagram].nodes[&parent_node.id].collapsed);
assert!(child_node.position.x >= parent_node.position.x);
assert!(child_node.position.y >= parent_node.position.y + 64.);
assert!(
child_node.position.x + child_node.size.width
<= parent_node.position.x + parent_node.size.width
);
assert!(
child_node.position.y + child_node.size.height
<= parent_node.position.y + parent_node.size.height
);
for sibling in view
.nodes
.iter()
.filter(|n| n.visual_parent == Some(parent_node.id) && n.id != child_node.id)
{
assert!(sibling.position.y + sibling.size.height <= child_node.position.y);
}
let after = app.project().clone();
let after_source = app.document.bundle().clone();
send(&mut app, Message::Undo);
assert_eq!(
app.project(),
&before,
"creation, allocation and reveal/reflow undo together"
);
assert_eq!(app.document.bundle(), &before_source);
send(&mut app, Message::Redo);
assert_eq!(app.project(), &after);
assert_eq!(app.document.bundle(), &after_source);
if step == 0 {
first = Some(created);
}
}
}
}
}
#[test]
fn child_work_does_not_invent_unallocated_or_mixed_performers() {
for (layer, performer_kind, other_kind, work_kind) in [
(Layer::Oa, Kind::Entity, Kind::Entity, Kind::Activity),
(Layer::Sa, Kind::System, Kind::SystemActor, Kind::Function),
] {
// Root leaf, partly unallocated composite, and mixed-performer composite.
for context in 0..3 {
let mut p = Project::empty();
let performer = p
.add_element(performer_kind, layer, "Performer", None)
.unwrap();
let other = p
.add_element(other_kind, layer, "Other performer", None)
.unwrap();
let work = p
.add_element(work_kind, layer, "Parent work", None)
.unwrap();
let mut placed = vec![performer, other, work];
if context != 0 {
let first = p
.add_element(work_kind, layer, "First leaf", Some(work))
.unwrap();
let second = p
.add_element(work_kind, layer, "Second leaf", Some(work))
.unwrap();
p.relate(
RelationKind::Allocation,
"First assignment",
performer,
first,
);
if context == 2 {
p.relate(RelationKind::Allocation, "Other assignment", other, second);
}
placed.extend([first, second]);
}
assert_eq!(oa_core::validation::allocation_summary(&p, work), None);
let diagram = p.ensure_diagram(layer);
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Allocation;
for id in placed {
p.place(diagram, id, Position { x: 60., y: 60. });
}
p = execute_batch(&p, &[Command::Layout(diagram)]).unwrap();
let mut app = App::with_project(p);
send(&mut app, Message::Layer(layer));
send(&mut app, Message::Page(Page::Diagram));
send(
&mut app,
Message::Diagram(crate::app::Choice {
id: diagram,
label: String::new(),
}),
);
send(&mut app, Message::Select(work));
let before = app.project().clone();
let before_source = app.document.bundle().clone();
send(&mut app, Message::CreateContextElement(work_kind, true));
let child = app.selected;
assert!(!before.elements.contains_key(&child), "{}", app.status);
assert_eq!(app.project().elements[&child].parent, Some(work));
assert_eq!(app.project().relations, before.relations);
assert_eq!(
oa_core::validation::effective_performer(app.project(), child),
None
);
assert_eq!(
oa_core::validation::allocation_summary(app.project(), work),
None
);
let after = app.project().clone();
let after_source = app.document.bundle().clone();
send(&mut app, Message::Undo);
assert_eq!(app.project(), &before);
assert_eq!(app.document.bundle(), &before_source);
send(&mut app, Message::Redo);
assert_eq!(app.project(), &after);
assert_eq!(app.document.bundle(), &after_source);
}
}
}
#[test]
fn child_work_transfers_leaf_roles_without_fabricating_responsibilities() {
// Direct allocation + matching roles, uniquely realized roles only,
// unresolved roles, and roles realized by different performers.
for context in 0..4 {
let mut p = Project::empty();
let performer = p
.add_element(Kind::Entity, Layer::Oa, "Performer", None)
.unwrap();
let other = p
.add_element(Kind::Entity, Layer::Oa, "Other performer", None)
.unwrap();
let work = p
.add_element(Kind::Activity, Layer::Oa, "Responsible work", None)
.unwrap();
let mut responsibilities = Vec::new();
if context == 0 {
responsibilities.push(p.relate(
RelationKind::Allocation,
"Direct responsibility",
performer,
work,
));
}
for index in 0..2 {
let role = p
.add_element(Kind::Role, Layer::Oa, &format!("Role {index}"), None)
.unwrap();
responsibilities.push(p.relate(
RelationKind::RoleAssignment,
&format!("Assigned role {index}"),
role,
work,
));
if context != 2 {
let source = if context == 3 && index == 1 {
other
} else {
performer
};
p.relate(RelationKind::RoleRealization, "Realizes role", source, role);
}
}
for (index, id) in responsibilities.iter().enumerate() {
let relation = p.relations.get_mut(id).unwrap();
relation.description =
format!("Responsibility {index}: preserve engineering rationale");
let link = Id::new_v4();
p.artifact_links.insert(
link,
ArtifactLink {
id: link,
alias: format!("responsibility_evidence_{index}"),
name: format!("Responsibility evidence {index}"),
description: "Preserve the reference to this exact relation".into(),
owner: *id,
relation: ArtifactRelation::References,
uri: format!("https://example.invalid/responsibility/{index}"),
revision: Some("review-7".into()),
fragment: Some("assignment".into()),
},
);
}
let original_relations = p.relations.clone();
let diagram = p.ensure_diagram(Layer::Oa);
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Allocation;
p.place(diagram, performer, Position { x: 60., y: 60. });
p.place(diagram, work, Position { x: 84., y: 124. });
p = execute_batch(&p, &[Command::Layout(diagram)]).unwrap();
let expected_performer = (context < 2).then_some(performer);
assert_eq!(
oa_core::validation::allocation_summary(&p, work),
expected_performer
);
let mut app = App::with_project(p);
send(&mut app, Message::Page(Page::Diagram));
send(
&mut app,
Message::Diagram(crate::app::Choice {
id: diagram,
label: String::new(),
}),
);
let mut first = None;
for step in 0..2 {
send(&mut app, Message::Select(work));
let before = app.project().clone();
let before_source = app.document.bundle().clone();
send(
&mut app,
Message::CreateContextElement(Kind::Activity, true),
);
let child = app.selected;
assert!(
!before.elements.contains_key(&child),
"context {context}, step {step}: {}",
app.status
);
assert_eq!(app.project().elements[&child].parent, Some(work));
if step == 0 {
first = Some(child);
}
for (id, original) in &original_relations {
let mut expected = original.clone();
if responsibilities.contains(id) {
match &mut expected.body {
RelationBody::Allocation { target, .. }
| RelationBody::RoleAssignment { target, .. } => *target = first.unwrap(),
_ => unreachable!(),
}
}
assert_eq!(app.project().relations[id], expected);
}
assert_eq!(app.project().artifact_links, before.artifact_links);
assert!(!app.project().artifact_links.is_empty());
let added = usize::from(step == 1 && expected_performer.is_some());
assert_eq!(
app.project().relations.len(),
before.relations.len() + added
);
assert_eq!(
oa_core::validation::effective_performer(app.project(), child),
expected_performer
);
assert_eq!(
app.project()
.relations
.values()
.filter(|r| r.kind() == RelationKind::RoleAssignment && r.target() == child)
.count(),
if step == 0 { 2 } else { 0 }
);
if context != 0 && step == 0 {
assert!(
!app.project()
.relations
.values()
.any(|r| r.kind() == RelationKind::Allocation)
);
}
assert!(
!oa_core::validation::validate(app.project())
.iter()
.any(|i| i.severity == oa_core::validation::Severity::Error)
);
let after = app.project().clone();
let after_source = app.document.bundle().clone();
send(&mut app, Message::Undo);
assert_eq!(app.project(), &before);
assert_eq!(app.document.bundle(), &before_source);
send(&mut app, Message::Redo);
assert_eq!(app.project(), &after);
assert_eq!(app.document.bundle(), &after_source);
}
}
}
+59 -575
View File
@@ -1,4 +1,3 @@
mod source_symbols;
pub(crate) mod traceability;
use crate::{
app::{App, Choice, FileOperation, Message, Page, Pending},
@@ -13,7 +12,6 @@ use iced::{
},
};
use oa_core::*;
use unicode_segmentation::UnicodeSegmentation;
pub fn label<'a>(s: impl Into<String>) -> widget::Text<'a> {
text(s.into()).size(11).color(style::MUTED)
@@ -26,12 +24,10 @@ pub fn action<'a>(s: &str, m: Message) -> widget::Button<'a, Message> {
}
pub fn short(s: &str, limit: usize) -> String {
let s = s.split_whitespace().collect::<Vec<_>>().join(" ");
if s.graphemes(true).count() > limit {
if s.chars().count() > limit {
format!(
"{}…",
s.graphemes(true)
.take(limit.saturating_sub(1))
.collect::<String>()
s.chars().take(limit.saturating_sub(1)).collect::<String>()
)
} else {
s
@@ -288,7 +284,7 @@ pub fn view(app: &App) -> View<'_, Message> {
)
.padding([4, 16])
.style(style::panel);
let root: View<'_, Message> = column![header, task_nav, body, footer].into();
let root = crate::allocation_input::root(app, column![header, task_nav, body, footer]);
if app.architecture.as_ref().is_some_and(|s| s.modal()) {
return modal_width(
root,
@@ -347,8 +343,8 @@ pub fn view(app: &App) -> View<'_, Message> {
.into(),
);
}
if app.delete_pending {
return modal(root,column![text("Delete from model?").size(21),text(format!("{} and its owned elements will be removed. Incident relationships, occurrences and view placements are updated together. Counterparts in the other layer remain.",p.named(app.selected))).size(13),label("Undo restores the complete change. Use Hide for diagram-only removal."),row![action("Cancel",Message::CancelDelete),button("Delete from model").style(button::danger).padding(10).on_press(Message::ConfirmDelete)].spacing(10)].spacing(16).into());
if let Some(target) = app.delete_target.as_ref().filter(|_| app.delete_pending) {
return modal(root,column![text("Delete from model?").size(21),text(format!("{} and its owned elements will be removed. Incident relationships, occurrences and view placements are updated together. Counterparts in the other layer remain.",p.named(target.snapshot.request.object))).size(13),label("Undo restores the complete change. Use Hide for diagram-only removal."),row![action("Cancel",Message::CancelDelete),button("Delete from model").style(button::danger).padding(10).on_press(Message::ConfirmDelete(target.snapshot.token))].spacing(10)].spacing(16).into());
}
if app.pending.is_some() {
return modal(root,column![text("Keep your changes?").size(21),text("Save the model and pending edits before continuing. Invalid drafts stay available for correction.").size(13),row![action("Cancel",Message::Cancel),action("Discard changes",Message::Discard),button("Save & continue").padding(10).on_press(Message::SaveAndContinue)].spacing(8)].spacing(16).into());
@@ -418,7 +414,7 @@ fn diagram(app: &App) -> View<'_, Message> {
.align_y(iced::Center);
if let Some(id) = app.active_diagram {
chooser = chooser.push(action("View properties", Message::Select(id)));
controls = controls.push(action("Arrange", Message::Command(Command::Layout(id))));
controls = controls.push(action("Auto-layout", Message::Command(Command::Layout(id))));
}
let toolbar = column![chooser, controls].spacing(6);
let projection = app
@@ -446,13 +442,11 @@ fn diagram(app: &App) -> View<'_, Message> {
.align_y(iced::Center);
let canvas: View<'_, Message> = if let Some(id) = app.active_diagram {
let program = DiagramCanvas {
allocation: Some(app.allocation_capability()),
project: app.project(),
view_index: Some(app.document.view_index()),
diagram: id,
selected: app.selected,
navigation_focus: app
.diagram_focus(crate::diagram_usage::Surface::Saved(id))
.map(|usage| usage.bounds),
zoom: app.zoom,
pan: app.pan,
context: app.route_context().unwrap(),
@@ -465,25 +459,31 @@ fn diagram(app: &App) -> View<'_, Message> {
connection: app.connection.as_ref(),
};
let mut scene = widget::stack![
widget::canvas(program).width(Fill).height(Fill),
crate::diagram::focus::wrap(
widget::canvas(program).width(Fill).height(Fill),
program.context,
crate::app::diagram_removal::enabled(app),
Message::DiagramTraverse
),
widget::canvas(crate::diagram::PortLabels(program))
.width(Fill)
.height(Fill),
widget::canvas(crate::diagram::WorkFeedback(program))
.width(Fill)
.height(Fill),
];
if let Some(editor) = crate::app::architecture_authoring::inline_editor(app) {
scene = scene.push(editor);
}
let reveal = app.architecture_reveal_stamp(id);
row![
widget::sensor(scene)
.on_show(move |size| reveal
.map_or(Message::CanvasResized(size), |(context, epoch)| {
Message::DiagramRevealViewport(context, epoch, size)
}))
.on_resize(move |size| reveal
.map_or(Message::CanvasResized(size), |(context, epoch)| {
Message::DiagramRevealViewport(context, epoch, size)
})),
widget::sensor(
container(scene)
.id(crate::allocation_input::CANVAS_ID)
.width(Fill)
.height(Fill)
)
.on_show(Message::CanvasResized)
.on_resize(Message::CanvasResized),
crate::app::architecture_authoring::palette(app)
]
.height(Fill)
@@ -514,6 +514,27 @@ fn diagram(app: &App) -> View<'_, Message> {
if app.active_diagram.is_some() {
tools = tools.push(modes);
}
if projection == Some(ProjectionKind::Allocation) {
tools = tools.push(
row![
action(
&format!(
"{} · {}",
if app.allocation_drag.arrange_next {
"Arrange next drag: armed"
} else {
"Arrange next drag"
},
crate::allocation_input::ARRANGE_SHORTCUT
),
Message::WorkDrag(crate::app::allocation_drag::Event::ArrangeNext)
),
label("Drag work into a performer to assign · out to remove assignment")
]
.spacing(8)
.align_y(iced::Center),
);
}
if let Some(diagram) = app.active_diagram {
let view = oa_core::projection::project_view(app.project(), diagram);
let edge = view.edges.iter().find(|edge| edge.id == app.selected);
@@ -525,7 +546,9 @@ fn diagram(app: &App) -> View<'_, Message> {
)
.is_some_and(|(source, target)| source != edge.source || target != edge.target)
});
let hint = if let Some(session) = &app.connection {
let hint = if let Some(feedback) = &app.allocation_drag.feedback {
feedback.text.as_str()
} else if let Some(session) = &app.connection {
if session.source.is_some() {
if session.candidates.is_empty() {
"No compatible targets are visible. Expand containers or show an endpoint · Esc cancels"
@@ -542,7 +565,9 @@ fn diagram(app: &App) -> View<'_, Message> {
} else {
"Right-click for actions · drag to arrange · scroll to zoom"
};
tools = tools.push(container(label(hint)).height(30));
// Status is outside the measured canvas. Clipping prevents long text
// from painting over work headers or frozen target labels below it.
tools = tools.push(container(label(hint)).height(30).width(Fill).clip(true));
}
column![container(tools).padding(14), canvas].into()
}
@@ -599,7 +624,7 @@ fn inspector(app: &App) -> View<'_, Message> {
return container(
column![
tabs,
scrollable(crate::navigation::view(app, app.selected)).height(Fill)
scrollable(crate::navigation::view(p, app.selected)).height(Fill)
]
.spacing(14),
)
@@ -1033,7 +1058,7 @@ fn source(app: &App) -> View<'_, Message> {
),
action("Next", Message::SourceNavigation(SourceEvent::Next(false))),
label(app.source_navigation.label()),
action("Close", app.source_find_close_message()),
action("Close", Message::SourceNavigation(SourceEvent::Close)),
]
.spacing(6)
.align_y(iced::Center),
@@ -1127,12 +1152,8 @@ fn source(app: &App) -> View<'_, Message> {
}
}
let editor = widget::text_editor(&app.source_editor)
.id(app.source_editor_id())
.id("source-editor")
.on_action(Message::SourceEdit)
.key_binding({
let context = app.source_symbol_context();
move |press| source_binding(press, &context)
})
.font(Font::MONOSPACE)
.size(14)
.padding(16)
@@ -1141,7 +1162,8 @@ fn source(app: &App) -> View<'_, Message> {
app.source_snapshot.clone(),
crate::highlight::format,
);
let header = container(
column![
container(
column![
row![
container(heading(
@@ -1184,501 +1206,17 @@ fn source(app: &App) -> View<'_, Message> {
"Undo text affects this file's draft. Model Undo restores accepted files together (100 changes / about 32 MiB)."
}),
navigation,
row![
action("Definition · F12", app.source_symbol_message(crate::source_navigation::SymbolEvent::Query(crate::source_navigation::query::Action::Definition))),
action("References · Shift F12", app.source_symbol_message(crate::source_navigation::SymbolEvent::Query(crate::source_navigation::query::Action::References))),
action("Show in diagrams…", app.source_symbol_message(crate::source_navigation::SymbolEvent::DiagramUsages)),
button(text("Back · Alt ←").size(12)).padding([8, 10]).style(style::nav)
.on_press_maybe((app.source_symbols.back.iter().any(|entry| entry.session == app.source_workspace.session())).then(|| app.source_symbol_message(crate::source_navigation::SymbolEvent::Back))),
].spacing(7),
scrollable(diagnostics)
.height((visible_diagnostics as f32 * 32.).min(132.))
]
.spacing(12)
)
.padding(18);
let editor = widget::sensor(editor)
.key((
app.source_workspace.active.clone(),
app.source_reveal_ticket(),
))
.on_show({
let ticket = app.source_reveal_ticket();
move |_| Message::SourceViewport(ticket)
})
.on_resize({
let ticket = app.source_reveal_ticket();
move |_| Message::SourceViewport(ticket)
});
let workspace: View<'_, Message> = if app.source_symbols.open {
row![
container(editor).width(Fill).height(Fill),
container(scrollable(source_symbols::panel(app)))
.width(300)
.height(Fill),
]
.height(Fill)
.into()
} else {
container(editor).width(Fill).height(Fill).into()
};
source_layout(header.into(), workspace, app.window_size.height)
}
fn source_layout<'a, Renderer: iced::advanced::text::Renderer + 'a>(
header: View<'a, Message, iced::Theme, Renderer>,
workspace: View<'a, Message, iced::Theme, Renderer>,
window_height: f32,
) -> View<'a, Message, iced::Theme, Renderer> {
// Lint clears and repopulates diagnostics asynchronously. Reserve the same
// outer slot so a pointer aimed at the editor cannot land in the header.
column![
container(scrollable(header).id("source-header")).height((window_height * 0.42).max(180.)),
workspace,
.padding(18),
widget::sensor(editor).key((app.source_workspace.active.clone(),app.source_jump))
.on_show(|_| Message::SourceViewport).on_resize(|_| Message::SourceViewport)
]
.height(Fill)
.into()
}
fn source_binding(
press: widget::text_editor::KeyPress,
context: &crate::source_navigation::SymbolContext,
) -> Option<widget::text_editor::Binding<Message>> {
use crate::source_navigation::{SymbolEvent, query::Action};
use iced::keyboard::{Key, key::Named};
use widget::text_editor::{Binding, Status};
// Windows owns Alt+Space for its window menu. Iced's default binding would
// otherwise insert a supplied space payload, even after that menu closes.
// Keep Ctrl+Alt (AltGr), shifted input, and ordinary Space unchanged.
#[cfg(target_os = "windows")]
if matches!(press.status, Status::Focused { .. })
&& press.modifiers == iced::keyboard::Modifiers::ALT
&& matches!(
press.key.as_ref(),
Key::Named(Named::Space) | Key::Character(" ")
)
{
return None;
}
if matches!(press.status, Status::Focused { .. })
&& !press.modifiers.control()
&& !press.modifiers.logo()
{
let event = match &press.key {
Key::Named(Named::F12) if !press.modifiers.alt() => {
Some(SymbolEvent::Query(if press.modifiers.shift() {
Action::References
} else {
Action::Definition
}))
}
Key::Named(Named::ArrowLeft) if press.modifiers.alt() && !press.modifiers.shift() => {
Some(SymbolEvent::Back)
}
_ => None,
};
if let Some(event) = event {
return Some(Binding::Custom(Message::SourceSymbols(
context.clone(),
event,
)));
}
}
Binding::from_key_press(press)
}
#[cfg(all(test, debug_assertions))]
mod source_tests {
use super::*;
use iced::advanced::{
Layout, Shell, graphics, layout, renderer, text as shaped, widget as core_widget,
};
use iced::widget::column;
use iced::{Background, Color, Pixels, Point, Rectangle, Size, Transformation, Vector};
// Measure real Iced paragraphs/editor text without constructing a window or GPU.
struct FontLayout;
impl renderer::Renderer for FontLayout {
fn start_layer(&mut self, _: Rectangle) {}
fn end_layer(&mut self) {}
fn start_transformation(&mut self, _: Transformation) {}
fn end_transformation(&mut self) {}
fn reset(&mut self, _: Rectangle) {}
fn fill_quad(&mut self, _: renderer::Quad, _: impl Into<Background>) {}
fn allocate_image(
&mut self,
handle: &iced::advanced::image::Handle,
callback: impl FnOnce(
Result<iced::advanced::image::Allocation, iced::advanced::image::Error>,
) + Send
+ 'static,
) {
renderer::Renderer::allocate_image(&mut (), handle, callback);
}
}
impl shaped::Renderer for FontLayout {
type Font = Font;
type Paragraph = graphics::text::Paragraph;
type Editor = graphics::text::Editor;
const ICON_FONT: Font = Font::DEFAULT;
const CHECKMARK_ICON: char = '0';
const ARROW_DOWN_ICON: char = '0';
const SCROLL_UP_ICON: char = '0';
const SCROLL_DOWN_ICON: char = '0';
const SCROLL_LEFT_ICON: char = '0';
const SCROLL_RIGHT_ICON: char = '0';
const ICED_LOGO: char = '0';
fn default_font(&self) -> Font {
Font::DEFAULT
}
fn default_size(&self) -> Pixels {
Pixels(16.)
}
fn fill_paragraph(&mut self, _: &Self::Paragraph, _: Point, _: Color, _: Rectangle) {}
fn fill_editor(&mut self, _: &Self::Editor, _: Point, _: Color, _: Rectangle) {}
fn fill_text(&mut self, _: shaped::Text, _: Point, _: Color, _: Rectangle) {}
}
#[derive(Default)]
struct Geometry {
header: Option<(Rectangle, Rectangle, Vector)>,
editor: Option<Rectangle>,
}
impl core_widget::Operation for Geometry {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn core_widget::Operation)) {
visit(self);
}
fn container(&mut self, id: Option<&core_widget::Id>, bounds: Rectangle) {
if id == Some(&core_widget::Id::new("test-source-editor")) {
self.editor = Some(bounds);
}
}
fn scrollable(
&mut self,
id: Option<&core_widget::Id>,
bounds: Rectangle,
content: Rectangle,
offset: Vector,
_: &mut dyn core_widget::operation::Scrollable,
) {
if id == Some(&core_widget::Id::new("source-header")) {
self.header = Some((bounds, content, offset));
}
}
}
fn mounted_source<'a>(
content: &'a widget::text_editor::Content<FontLayout>,
diagnostics: usize,
find: bool,
window_height: f32,
) -> View<'a, Message, iced::Theme, FontLayout> {
let mut notices = column![].spacing(5);
for index in 0..diagnostics {
notices = notices.push(button(text(format!(
"救援/assess.arcadia:{}:5 · Warning: verify this participant's engineering allocation", index + 1,
)).size(12)).padding([4, 6]).width(Fill));
}
let find: View<'_, Message, iced::Theme, FontLayout> = if find {
column![
text_input("Find literal text", "assess").on_input(|s| Message::SourceNavigation(
crate::source_navigation::Event::Query(s)
)),
text_input("Line", "1").on_input(|s| Message::SourceNavigation(
crate::source_navigation::Event::Line(s)
)),
]
.spacing(8)
.into()
} else {
Space::new().into()
};
let header = container(
column![
text("Textual model").size(24),
text("Edit the current file. Apply text validates the complete included model.")
.size(11),
row![
button(text("Apply text")),
button(text("Undo text")),
button(text("Model Undo"))
]
.spacing(8),
text("救援/assess.arcadia · All files applied to the accepted model").size(11),
text("Undo text affects this draft. Model Undo restores accepted files together.")
.size(11),
find,
row![
button(text("Definition · F12")),
button(text("References · Shift F12")),
button(text("Back"))
]
.spacing(7),
scrollable(notices).height((diagnostics as f32 * 32.).min(132.)),
]
.spacing(12),
)
.padding(18);
let editor = container(
widget::text_editor(content)
.on_action(Message::SourceEdit)
.font(Font::MONOSPACE)
.size(14)
.padding(16)
.height(Fill),
)
.id("test-source-editor")
.height(Fill)
.width(Fill);
source_layout(header.into(), editor.into(), window_height)
}
#[test]
fn source_header_keeps_editor_bounds_stable_through_lint_and_find_rebuilds() {
for (host, window_height) in [
(Size::new(720., 540.), 700.),
(Size::new(1180., 890.), 1080.),
] {
let content = widget::text_editor::Content::<FontLayout>::with_text(
"// is excluded\r\n// 雨\r\n",
);
let mut tree = core_widget::Tree::empty();
let mut baseline = None;
for (diagnostics, find) in [
(0, false),
(6, false),
(0, false),
(6, true),
(1, true),
(0, false),
] {
let mut ui = mounted_source(&content, diagnostics, find, window_height);
tree.diff(ui.as_widget());
let node = ui.as_widget_mut().layout(
&mut tree,
&FontLayout,
&layout::Limits::new(Size::ZERO, host),
);
let mut geometry = Geometry::default();
ui.as_widget_mut().operate(
&mut tree,
Layout::new(&node),
&FontLayout,
&mut geometry,
);
let editor = geometry.editor.unwrap();
let (header, _, _) = geometry.header.unwrap();
let slot = node.children()[0].bounds();
assert_eq!(slot.height, (window_height * 0.42).max(180.));
assert!(
header.height <= slot.height,
"short content may shrink inside the fixed slot"
);
assert!(
editor.height >= 240.,
"remaining editor must stay usable: {editor:?}"
);
assert_eq!(editor.y, slot.y + slot.height);
if let Some(expected) = baseline {
assert_eq!(editor, expected, "diagnostics={diagnostics}, find={find}");
} else {
baseline = Some(editor);
}
}
}
}
#[test]
fn source_header_remains_scrollable_and_preserves_offset_across_diagnostic_refresh() {
let content = widget::text_editor::Content::<FontLayout>::with_text("// 雨\r\n");
let host = Size::new(720., 540.);
let mut tree = core_widget::Tree::empty();
let mut saved = None;
for diagnostics in [6, 7] {
let mut ui = mounted_source(&content, diagnostics, true, 700.);
tree.diff(ui.as_widget());
let node = ui.as_widget_mut().layout(
&mut tree,
&FontLayout,
&layout::Limits::new(Size::ZERO, host),
);
let mut geometry = Geometry::default();
ui.as_widget_mut()
.operate(&mut tree, Layout::new(&node), &FontLayout, &mut geometry);
let (bounds, contents, _) = geometry.header.unwrap();
assert!(
contents.height > bounds.height,
"fixture must actually overflow"
);
if saved.is_none() {
let mut messages = Vec::new();
let mut shell = Shell::new(&mut messages);
ui.as_widget_mut().update(
&mut tree,
&iced::Event::Mouse(iced::mouse::Event::WheelScrolled {
delta: iced::mouse::ScrollDelta::Pixels { x: 0., y: -45. },
}),
Layout::new(&node),
iced::mouse::Cursor::Available(Point::new(bounds.x + 8., bounds.y + 8.)),
&FontLayout,
&mut iced::advanced::clipboard::Null,
&mut shell,
&Rectangle::with_size(host),
);
assert!(shell.is_event_captured());
}
let mut geometry = Geometry::default();
ui.as_widget_mut()
.operate(&mut tree, Layout::new(&node), &FontLayout, &mut geometry);
let offset = geometry.header.unwrap().2;
assert!(offset.y > 0., "the actual mounted Scrollable must move");
if let Some(before) = saved {
assert_eq!(offset, before);
} else {
saved = Some(offset);
}
}
}
#[cfg(target_os = "windows")]
#[test]
fn source_editor_windows_menu_payload_is_inert_but_space_and_altgr_still_edit() {
use core_widget::operation::Focusable;
use iced::keyboard::{
self, Key, Modifiers,
key::{Code, Named, Physical},
};
use widget::text_editor::{Binding, Content, KeyPress, State, Status};
let baseline = "// is excluded\r\n// 雨\r\n";
let context = crate::source_navigation::SymbolContext {
session: Id::new_v4(),
path: "救援/assess.arcadia".into(),
};
for (key, physical_key, modifiers, payload, inserted) in [
(
Key::Named(Named::Space),
Physical::Code(Code::Space),
Modifiers::ALT,
" ",
false,
),
(
Key::Character(" ".into()),
Physical::Code(Code::Space),
Modifiers::ALT,
" ",
false,
),
(
Key::Named(Named::Space),
Physical::Code(Code::Space),
Modifiers::empty(),
" ",
true,
),
(
Key::Named(Named::Space),
Physical::Code(Code::Space),
Modifiers::CTRL | Modifiers::ALT,
" ",
true,
),
(
Key::Character("e".into()),
Physical::Code(Code::KeyE),
Modifiers::CTRL | Modifiers::ALT,
"€",
true,
),
(
Key::Named(Named::Space),
Physical::Code(Code::Space),
Modifiers::ALT | Modifiers::SHIFT,
" ",
true,
),
] {
let mut content = Content::<FontLayout>::with_text(baseline);
content.move_to(widget::text_editor::Cursor {
position: widget::text_editor::Position { line: 0, column: 5 },
selection: None,
});
let press = KeyPress {
key: key.clone(),
modified_key: key.clone(),
physical_key,
modifiers,
text: Some(payload.into()),
status: Status::Focused { is_hovered: false },
};
assert!(
matches!(
Binding::<Message>::from_key_press(press),
Some(Binding::Insert(_))
),
"the supplied event must expose the default insertion path"
);
let mut messages = Vec::new();
{
let mut editor: View<'_, Message, iced::Theme, FontLayout> =
widget::text_editor(&content)
.on_action(Message::SourceEdit)
.font(Font::MONOSPACE)
.size(14)
.padding(16)
.height(Fill)
.key_binding(|press| source_binding(press, &context))
.into();
let mut tree = core_widget::Tree::new(editor.as_widget());
let size = Size::new(600., 240.);
let node = editor.as_widget_mut().layout(
&mut tree,
&FontLayout,
&layout::Limits::new(Size::ZERO, size),
);
tree.state
.downcast_mut::<State<shaped::highlighter::PlainText>>()
.focus();
let event = iced::Event::Keyboard(keyboard::Event::KeyPressed {
key: key.clone(),
modified_key: key,
physical_key,
location: keyboard::Location::Standard,
modifiers,
text: Some(payload.into()),
repeat: false,
});
let mut shell = Shell::new(&mut messages);
editor.as_widget_mut().update(
&mut tree,
&event,
Layout::new(&node),
iced::mouse::Cursor::Unavailable,
&FontLayout,
&mut iced::advanced::clipboard::Null,
&mut shell,
&Rectangle::with_size(size),
);
}
assert_eq!(
messages.len(),
usize::from(inserted),
"modifiers={modifiers:?}"
);
for message in messages {
let Message::SourceEdit(action) = message else {
panic!("unexpected navigation action");
};
content.perform(action);
}
let expected = if inserted {
format!("// is{payload} excluded\r\n// 雨\r\n")
} else {
baseline.into()
};
assert_eq!(content.text(), expected);
}
}
}
fn checks(app: &App) -> View<'_, Message> {
let issues = &app.model_issues;
let mut out = column![heading(
@@ -1791,57 +1329,3 @@ fn checks(app: &App) -> View<'_, Message> {
}
scrollable(out.padding(24)).into()
}
#[cfg(test)]
mod tests {
use super::short;
#[test]
fn short_preserves_native_lifeline_clusters_at_cutoff() {
let oa = "abcdefghijklmnope\u{0301}尾";
assert_eq!(short(oa, 17), "abcdefghijklmnop…");
assert_eq!(short(oa, 18), oa);
assert_eq!(short(oa, 19), oa);
let sa = "abcdefghijklmnop👩\u{200d}🔬 tail";
assert_eq!(short(sa, 17), "abcdefghijklmnop…");
assert_eq!(short(sa, 18), "abcdefghijklmnop👩\u{200d}🔬…");
assert_eq!(short(sa, 19), "abcdefghijklmnop👩\u{200d}🔬 …");
assert_eq!(short(sa, 22), sa);
}
#[test]
fn short_never_splits_retained_extended_graphemes() {
for cluster in ["e\u{0301}", "👩\u{200d}🔬", "👍🏽", "🇫🇷"] {
let value = format!("A{cluster}BC");
assert_eq!(short(&value, 2), "A…");
assert_eq!(short(&value, 3), format!("A{cluster}…"));
assert_eq!(short(&value, 4), value);
}
}
#[test]
fn short_preserves_ascii_cjk_and_whitespace_policy() {
assert_eq!(short("abcd", 3), "ab…");
assert_eq!(short("abcd", 4), "abcd");
assert_eq!(short("abcd", 5), "abcd");
assert_eq!(short("甲乙丙丁", 3), "甲乙…");
assert_eq!(short("甲乙丙丁", 4), "甲乙丙丁");
assert_eq!(short(" \tA\r\n e\u{0301}\u{2003}B ", 5), "A e\u{0301} B");
assert_eq!(short(" \tA\r\n e\u{0301}\u{2003}B ", 4), "A e\u{0301}…");
}
#[test]
fn short_preserves_empty_and_small_limit_policy() {
for limit in [0, 1, 2] {
assert_eq!(short("", limit), "");
assert_eq!(short(" \t\r\n", limit), "");
}
assert_eq!(short("A", 0), "…");
assert_eq!(short("A", 1), "A");
assert_eq!(short("AB", 1), "…");
assert_eq!(short("e\u{0301}", 0), "…");
assert_eq!(short("e\u{0301}", 1), "e\u{0301}");
assert_eq!(short("e\u{0301}B", 1), "…");
}
}
@@ -1,260 +0,0 @@
use crate::{
app::{App, Message},
source_navigation::{
SymbolEvent,
query::{self, Declaration, Disposition, Evidence, Identity, Membership, Position},
},
style,
};
use iced::{
Element, Fill,
widget::{Space, button, column, container, row, scrollable, text, tooltip},
};
pub(super) fn panel(app: &App) -> Element<'_, Message> {
let state = &app.source_symbols;
if !state.open
|| (state.results.is_none() && state.in_flight.is_none() && state.notice.is_none())
{
return column![].into();
}
let title = state.results.as_ref().map_or_else(
|| "Source symbols".to_owned(),
|results| {
let action = match results.action {
query::Action::Definition => "Definitions",
query::Action::References => "References",
};
results.alias.as_ref().map_or_else(
|| action.to_owned(),
|alias| format!("{action} · @{}", preview(alias, 40)),
)
},
);
let mut content = column![
row![
text(title).size(13),
Space::new().width(Fill),
button(text("Close").size(11))
.padding([3, 8])
.style(style::nav)
.on_press(app.source_symbol_message(SymbolEvent::Close)),
]
.align_y(iced::Center)
]
.spacing(5);
if let Some(notice) = &state.notice {
content = content.push(super::label(preview(notice, 240)));
}
if state.in_flight.is_some() {
content = content.push(super::label("Finding source symbols…"));
} else if let Some(results) = &state.results {
let stale = results.stamp.snapshot != app.source_key();
if stale {
content = content.push(super::label(
"Stale results — source changed. Run Definition or References again.",
));
}
let scope = &results.scope;
content = content.push(super::label(format!(
"{} · {} · {} included / {} detached / {} unverified files · {} scope issues",
if scope.partial() {
"Partial scope"
} else {
"Complete include scope"
},
if !scope.applied {
"Unapplied drafts"
} else if scope.validated {
"Validated sources"
} else {
"Draft sources"
},
scope.included_files,
scope.detached_files,
scope.unverified_files,
scope.issues.len(),
)));
let explanation = match results.disposition {
Disposition::NoSymbol => "Place the caret on a declaration alias or an @reference.",
Disposition::NoDefinition => "No matching declaration in the loaded sources.",
Disposition::Choices => {
"Choose a declaration; draft and detached candidates need an explicit choice."
}
Disposition::Direct => "Definition in the current sources.",
Disposition::LexicalReferences => {
"Lexical uses of this alias; these do not establish a semantic target."
}
};
content = content.push(super::label(explanation));
if results.total_definitions > 1 {
content = content.push(super::label(format!(
"Alias collision: {} declarations. Uses are not attributed to a single declaration.",
results.total_definitions,
)));
}
let enabled = !stale && !app.busy;
let mut rows = column![super::label(counts(
"Declarations",
results.definitions.len(),
results.total_definitions,
results.omitted_definitions,
))]
.spacing(4);
for (index, definition) in results.definitions.iter().enumerate() {
rows = rows.push(location_row(
declaration_title(&definition.declaration),
&definition.path,
definition.position,
provenance(
definition.membership,
definition.evidence,
definition.declaration.identity,
false,
),
enabled.then(|| {
app.source_symbol_message(SymbolEvent::Choose {
stamp: results.stamp,
reference: false,
index,
})
}),
));
}
rows = rows.push(super::label(counts(
"Lexical uses",
results.references.len(),
results.total_references,
results.omitted_references,
)));
for (index, reference) in results.references.iter().enumerate() {
let title = reference.context.as_ref().map_or_else(
|| format!("@{} · lexical use", preview(&reference.alias, 48)),
|context| {
format!(
"@{} · inside {}",
preview(&reference.alias, 48),
declaration_title(context)
)
},
);
rows = rows.push(location_row(
title,
&reference.path,
reference.position,
provenance(
reference.membership,
reference.evidence,
reference
.context
.as_ref()
.map_or(Identity::Missing, |context| context.identity),
true,
),
enabled.then(|| {
app.source_symbol_message(SymbolEvent::Choose {
stamp: results.stamp,
reference: true,
index,
})
}),
));
}
let row_count = results.definitions.len() + results.references.len();
content =
content.push(scrollable(rows).height((44.0 + row_count as f32 * 48.0).min(180.0)));
}
container(content)
.padding(8)
.width(Fill)
.style(style::subtle)
.into()
}
fn counts(label: &str, shown: usize, total: usize, omitted: usize) -> String {
format!("{label}: {total} total · {shown} shown · {omitted} omitted")
}
fn declaration_title(declaration: &Declaration) -> String {
let name = declaration
.name
.as_ref()
.map_or_else(String::new, |name| format!(" \"{}\"", preview(name, 48)));
format!(
"{}{} · @{}",
preview(&declaration.kind, 24),
name,
preview(&declaration.alias, 48)
)
}
fn provenance(
membership: Membership,
evidence: Evidence,
identity: Identity,
context: bool,
) -> String {
let membership = match membership {
Membership::Included => "Included",
Membership::Detached => "Detached",
Membership::Unverified => "Unverified",
};
let evidence = match evidence {
Evidence::Validated => "Validated",
Evidence::Draft => "Draft",
};
let collision = match identity {
Identity::Collision { count } => format!(
" · {}ID collision ({count})",
if context { "Context " } else { "" },
),
Identity::Missing | Identity::Unique(_) => String::new(),
};
format!("{membership} · {evidence}{collision}")
}
fn location_row(
title: String,
path: &str,
position: Position,
status: String,
event: Option<Message>,
) -> Element<'static, Message> {
let line = position.line.saturating_add(1);
let column = position.byte_column.saturating_add(1);
let location = format!("{}:{line}:{column}", preview(path, 72));
tooltip(
button(
column![
text(title).size(12),
super::label(format!("{location} · {status}"))
]
.spacing(2),
)
.padding([4, 6])
.width(Fill)
.style(style::nav)
.on_press_maybe(event),
text(format!(
"{path}:{line}:{column} (1-based line and UTF-8 byte column)"
))
.size(11),
tooltip::Position::Top,
)
.into()
}
/// Keep headings compact without copying the remainder of a long admitted value.
fn preview(value: &str, limit: usize) -> String {
let mut chars = value.chars();
let mut result: String = chars
.by_ref()
.take(limit)
.map(|ch| if ch.is_whitespace() { ' ' } else { ch })
.collect();
if chars.next().is_some() {
result.push('…');
}
result
}
-106
View File
@@ -1,106 +0,0 @@
Diagram representation navigation
=================================
This contract derives from user issues `14: Text symbol usages
<http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/14>`_
and `17: tree-to-diagram navigation
<http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/17>`_.
Implementation and acceptance status belong to those issues. The source language
and identity rules remain in ``language.rst``.
Identity and membership
-----------------------
A result identifies the queried subject, a diagram destination, and a specific
graphical representation. A destination is a saved diagram UUID, a process or
functional-chain UUID, or a scenario UUID. Saved state diagrams retain their own
diagram UUID; membership in the same state machine does not make their contents
interchangeable.
Representation identities are node placement, port plus owner placement, edge,
state row plus owner placement, process occurrence plus qualified reference path,
process link, or scenario lifeline/occurrence. Opening an owner itself is a
separate whole-diagram target. Names and aliases describe these identities; they
are never replacement identities. Repeated occurrences remain independently
selectable even when they represent the same activity or exchange.
The current renderer determines membership:
* Saved node, port, and edge results come from the final projection, including
folds, projection-kind rules, and view filters. A stored route or two placed
endpoints does not establish a visible edge.
* Process results use the displayed contribution graph. A contextual preview
retains its full caller path and is included only while its actual tile is
present. An inactive process uses the same initial preview policy as entering
its canvas. Preview adjacency has no invented relation UUID.
* Scenario results use the actual scene, preserving lifeline and message
occurrence identities, nested fragment operands, and repeated messages.
A scenario-reference box represents its called scenario. It does not also
represent the called scenario's messages or lifelines.
* State action and internal-transition rows retain their relation identity.
Visible named references, such as a state action's work or a transition's
trigger, can target the row or edge whose label displays that reference.
Label-only membership must account for the renderer's shortening policy.
An arbitrary semantic reference is insufficient. A description mentioning a
name, an exchange item hidden by the selected label mode, or an unexpanded callee
does not automatically add a diagram result. The result count describes
currently rendered representations, not all semantic dependencies. Folded,
filtered, and unexpanded representations are explicitly excluded by this version;
an empty result must disclose this scope and must not claim that an object is
unused everywhere. Semantic dependencies remain available through Connections.
Two additional representation forms remain gaps in this branch: allocation
relations expressed through nesting, and persisted sequence links drawn inside
qualified caller previews. These must either receive precise grouping/qualified
edge targets or remain explicitly disclosed limitations; a passing direct-edge
test does not establish their coverage.
Interaction and lifecycle
-------------------------
``Show in diagrams`` opens one searchable destination list from the Text caret,
an object's context/Actions menu, or Connections. It identifies the subject by
name and alias, groups targets by destination, reports counts, and presents a
bounded page. A destination then exposes its individual representations. Search
matches destination names, aliases, categories, representation names, and roles.
Long descriptions remain available without replacing stable identities.
The Text entry point uses the exact current caret and the source-symbol service's
immutable snapshot. It requires a unique, validated, included declaration whose
authored identity and alias still match the accepted model. It never substitutes
the previously selected tree object. Unapplied source is retained with an explicit
instruction to apply it before diagram lookup. Comment, prose, ambiguous, missing,
detached, and stale symbols cannot trigger a diagram jump.
Every open request captures the document instance, accepted revision, and subject.
Every chooser action captures that chooser's unique token. Before opening a
representation, re-resolve the full subject-to-target relationship and renderer
geometry. If the model or presentation changed, refresh the list and require a
fresh choice. Matching names, reused aliases, or surviving endpoints cannot make
a stale target current. An asynchronous source response must also match its job,
source session/revision, raw interaction, active file, and caret.
Lookup and reveal do not execute model commands, Apply, Revert, or Save. They do
not expand persisted folds, change filters, rewrite source, or alter undo/redo.
Pending edits that would be displaced prevent the jump and remain intact.
Successful reveal updates only the navigation owner/page, precise selection,
tool lifetime, and camera. The camera centers the target at a readable scale;
fitting a huge whole diagram is not sufficient evidence of locating one object.
Escape closes the chooser and restores Text focus/caret when invoked there.
Verification obligations
------------------------
Independent fixtures must cover actual versus filtered edges, folded children,
ports, same-name distinct identities, repeated work/message/lifeline occurrences,
qualified reuse paths, opaque scenario references, state rows and label references.
For each activation, compare the complete accepted Project, SourceBundle, raw
buffers, revision, dirty flags, and undo/redo reachability before and after.
Exercise stale document/revision/token/subject relationships and retained drafts.
Native acceptance additionally checks keyboard and pointer selection, exact
visible target highlight, camera behavior after the destination's first layout,
empty and multi-result states, readable long Unicode names, minimum-window layout,
return to editing, and representative large-model latency. Unit tests and a
successful build do not by themselves establish these interaction outcomes.
+5 -89
View File
@@ -1319,25 +1319,16 @@ references a Call occurrence in the same scenario. The call MUST precede the
reply on a guaranteed common sequence/enclosing branch path. Reply lifelines
reverse the call's sender/receiver; it may reuse the call's exchange in reverse
or use an explicit reverse-direction exchange. A second reply to the same call
that can follow another reply on a shared execution path, including conditional
or parallel operands, is an error. Missing reply correlation is a draft
on that guaranteed path is an error. Missing reply correlation is a draft
warning; non-Reply messages MUST NOT have <span class="docutils literal">reply_to</span>.</p>
<p>Create identifies the receiver lifeline's creation. Another use that can precede
its creation on a shared execution path is an error. Delete identifies its
destruction; another use that can follow it on a shared execution path is an
error. These checks include conditional and parallel operands but exclude
mutually exclusive alternatives. Ordering checks respect branch ownership; they
MUST NOT flatten alternative branches into a false unconditional order. A Timer is
<p>Create identifies the receiver lifeline's creation. An earlier guaranteed use
of that lifeline is an error. Delete identifies its destruction; a later
guaranteed use is an error. Ordering checks respect branch ownership; they MUST
NOT flatten alternative branches into a false unconditional order. A Timer is
local to its sender lifeline, has no global exchange or values, and has either
no receiver or the same receiver as sender. Its nonempty expression describes
the delay/deadline; an empty expression warns. Conditions and expressions are
stored engineering annotations, not an executable simulation language.</p>
<p>These ordering checks compare distinct stored occurrences along structural
paths; they do not simulate repeated loop iterations. Repetition risks use
<span class="docutils literal">reply_repetition</span> and <span class="docutils literal">lifeline_repetition</span> warnings separately. For example,
a loop containing one Reply to an outer Call can warn about repetition without
containing two distinct replies; a same-operand Create/use/Delete lifetime can
repeat without its previous iteration being treated as an earlier stored use.</p>
<p>Each MessageValue is <span class="docutils literal">{ path [&#64;parameter]; field &#64;data_field; expression &quot;value expression&quot;; }</span>.
Its identity is the pair (path, field), so two uses of one Record can have
different values for the same terminal field. Path contains enclosing DataField
@@ -2642,46 +2633,6 @@ trace links, occurrence identity, comments and file ownership. Each open file
retains its own unapplied draft across file navigation. Located lint diagnostics
refer to the raw draft bytes rather than an identity-stabilized intermediate.
Property editing MUST NOT silently discard a pending source draft.</p>
<p>In Textual model, place the caret on a declaration alias or an <span class="docutils literal">&#64;reference</span>
and choose <strong>Definition</strong> (<span class="docutils literal">F12</span>) or <strong>References</strong> (<span class="docutils literal">Shift+F12</span>).
<strong>Back</strong> (<span class="docutils literal">Alt+Left</span>) returns to the previous source location in this
workspace. These shortcuts act while the source editor has focus; the Text
toolbar also exposes the actions. If the previous draft changed, Back restores
its current cursor rather than reusing an obsolete selection.</p>
<p>Symbol navigation reads bounded snapshots of the currently loaded source
drafts. It does not apply drafts or load missing included files. The results
identify partial scope, draft evidence, detached or unverified files, alias
ambiguity and authored-ID collisions. Draft, detached and ambiguous definition
candidates require an explicit row choice. References are lexical uses of an
alias, not a list of resolved typed relationships; comments and strings are
excluded. Declaration and use counts include any rows omitted by the result
limits. If sources change, stale rows cannot navigate: run the query again.
Navigation MUST preserve the accepted model and every source draft, and select
locations in the original UTF-8 bytes. Displayed locations use one-based lines
and UTF-8 byte columns.</p>
<p><strong>Show in diagrams</strong> finds representations of a model record in saved diagrams,
process/chain canvases and scenarios. Use the Text toolbar with the caret on a
unique, verified alias in clean accepted sources, or the model tree's context
menu for the chosen record. Choose a destination, then its exact representation.
Lookup runs from an accepted-model snapshot; navigation preserves source drafts,
accepted geometry and history. Pending edits or modal operations must be
finished first. Changed or stale results cannot activate a different target.</p>
<p>Membership follows the actual projection, including visible ports, state action
and internal-transition rows, qualified reuse tiles, and SequenceLink arrows
painted inside caller previews. Repeated callers have distinct destinations
within the same canvas. Hidden preview endpoints and deeper nested links that
the renderer does not draw are excluded; projected adjacency without an actual
relation is not a SequenceLink usage. Preview-arrow focus lies on a visible
line segment outside opaque tiles.</p>
<p>An Allocation projection represents a direct Allocation relation by grouping
only when its visible source performer placement occurs on the visible target
work placement's actual visual-parent chain. Aggregate-only allocation summaries
do not create direct relation usages. The navigation marker can focus a work
header, port owner or state row independently of semantic selection: selecting
an Allocation or state-action relation retains that relation as the model action
target. Camera movement preserves a valid marker; changing the selected record,
document, accepted revision or represented context retires it. Navigation does
not alter allocation ownership or the meaning of Delete.</p>
<p>Changing a graphical UUID must atomically update map keys and every reference.
Alias changes preserve UUID identity. Deletion must account for owned elements,
incident relationships, ordered occurrences, and diagram placements without
@@ -2689,41 +2640,6 @@ leaving dangling references. Deleting a sequence does not delete the semantic
exchanges it references. Cross-layer counterparts are not owned descendants.
Text edits describe a complete candidate and must remove or repair dependencies
explicitly before Apply succeeds.</p>
<section id="scenario-lifetime-presentation">
<h3>8.1. Scenario lifetime presentation</h3>
<p>Scenario lifetime geometry is derived from the stored occurrences and their
sequence/operand ownership. It adds no model records, source annotations or
history entries. A lifeline's identity header and neutral editing guide remain
available before creation, after deletion and when its represented element is
unfinished. The guide MUST be visually distinguishable from a live interval;
it is an editing axis, not a statement that the participant exists.</p>
<p>A directly ordered Create starts the receiver's live interval at its occurrence;
Delete ends that receiver's interval at its occurrence. Create uses a named birth
marker and Delete an X, each selectable through the original occurrence identity.
The message's receiving endpoint MUST align with its marker, including self
messages. A pre-existing lifeline without a creation has a live interval from
below its header; without deletion it extends to the visible scenario bottom,
including in an empty scenario. A missing lifecycle receiver MUST NOT be inferred from
the exchange. An explicit local receiver remains meaningful when its exchange
reference is unfinished.</p>
<p>Operands MUST be projected independently from their enclosing entry context.
A lifetime change in an alternative, optional, loop or parallel operand MUST
NOT imply the same change in its displayed sibling or a definite lifetime
after the fragment. When local structure does not establish one lifetime across
the represented paths, the continuation is visually unresolved. A subsequent
explicit Create or Delete in the enclosing sequence can establish a definite interval.
Neither guard text, screen order nor a guessed loop count proves execution.
ScenarioUse remains opaque: opening its definition may show its lifecycle,
but a callee's geometry MUST NOT create or destroy a caller lifeline.</p>
<p>Call activation is distinct from lifetime. A branch-local Delete clips that
branch's visible activation at the death marker without inventing a Reply,
removing an unresolved-call warning or terminating sibling paths.
Solid activation bars are restricted to definite live intervals; an unresolved
continuation retains its uncertainty/call diagnostic rather than depicting
definite survival after a possible deletion. Selection,
insertion slots, source edits and Undo/Redo retain the same semantic identities
and validation boundary regardless of the rendered intervals.</p>
</section>
</section>
<section id="persistence-and-explicit-migration">
<h2>9. Persistence and explicit migration</h2>
+22 -99
View File
@@ -680,28 +680,18 @@ references a Call occurrence in the same scenario. The call MUST precede the
reply on a guaranteed common sequence/enclosing branch path. Reply lifelines
reverse the call's sender/receiver; it may reuse the call's exchange in reverse
or use an explicit reverse-direction exchange. A second reply to the same call
that can follow another reply on a shared execution path, including conditional
or parallel operands, is an error. Missing reply correlation is a draft
on that guaranteed path is an error. Missing reply correlation is a draft
warning; non-Reply messages MUST NOT have ``reply_to``.
Create identifies the receiver lifeline's creation. Another use that can precede
its creation on a shared execution path is an error. Delete identifies its
destruction; another use that can follow it on a shared execution path is an
error. These checks include conditional and parallel operands but exclude
mutually exclusive alternatives. Ordering checks respect branch ownership; they
MUST NOT flatten alternative branches into a false unconditional order. A Timer is
Create identifies the receiver lifeline's creation. An earlier guaranteed use
of that lifeline is an error. Delete identifies its destruction; a later
guaranteed use is an error. Ordering checks respect branch ownership; they MUST
NOT flatten alternative branches into a false unconditional order. A Timer is
local to its sender lifeline, has no global exchange or values, and has either
no receiver or the same receiver as sender. Its nonempty expression describes
the delay/deadline; an empty expression warns. Conditions and expressions are
stored engineering annotations, not an executable simulation language.
These ordering checks compare distinct stored occurrences along structural
paths; they do not simulate repeated loop iterations. Repetition risks use
``reply_repetition`` and ``lifeline_repetition`` warnings separately. For example,
a loop containing one Reply to an outer Call can warn about repetition without
containing two distinct replies; a same-operand Create/use/Delete lifetime can
repeat without its previous iteration being treated as an earlier stored use.
Each MessageValue is ``{ path [@parameter]; field @data_field; expression "value expression"; }``.
Its identity is the pair (path, field), so two uses of one Record can have
different values for the same terminal field. Path contains enclosing DataField
@@ -2047,6 +2037,23 @@ will occur. Reparenting work must not silently change its performer. A computed
parent summary must remain distinguishable from direct allocation. A collapse
operation hides presentation detail without deleting the children.
In an Allocation view, dragging an Activity or Function body MAY combine a
performer change with diagram placement. The preview MUST identify the
destination and preserve readable work and performer labels. A clean click
selects without applying unrelated drafts. A refused work press with an unapplied
property draft MUST preserve its text, caret and focused editor. An accepted drag is one atomic
model/source/history transaction: semantic ownership and work identities are
preserved; only leaf direct Allocation relations, their own retired routes and
the affected view geometry change. Existing Allocation identities are retained on reassignment. Role
realizations and assignments MUST NOT be silently changed. Uniform work groups
may move their leaf responsibilities together; ambiguous or distributed groups
and changes requiring collateral record edits MUST be refused with an explanation.
Moving outside performer regions removes direct assignment only when the
effective role responsibility is also absent. Releasing outside the viewport
cancels the gesture. Explicit Arrange next drag applies geometry alone for one
gesture. Refused and snapped no-op drops MUST NOT create history entries or
discard Redo. Undo restores the exact source bundle and identities together.
Applying a reachable source bundle is one model transaction. Graphical edits
update its owning declarations through the source-preserving updater. Both
paths validate their candidate and model/source equality before
@@ -2064,51 +2071,6 @@ retains its own unapplied draft across file navigation. Located lint diagnostics
refer to the raw draft bytes rather than an identity-stabilized intermediate.
Property editing MUST NOT silently discard a pending source draft.
In Textual model, place the caret on a declaration alias or an ``@reference``
and choose **Definition** (``F12``) or **References** (``Shift+F12``).
**Back** (``Alt+Left``) returns to the previous source location in this
workspace. These shortcuts act while the source editor has focus; the Text
toolbar also exposes the actions. If the previous draft changed, Back restores
its current cursor rather than reusing an obsolete selection.
Symbol navigation reads bounded snapshots of the currently loaded source
drafts. It does not apply drafts or load missing included files. The results
identify partial scope, draft evidence, detached or unverified files, alias
ambiguity and authored-ID collisions. Draft, detached and ambiguous definition
candidates require an explicit row choice. References are lexical uses of an
alias, not a list of resolved typed relationships; comments and strings are
excluded. Declaration and use counts include any rows omitted by the result
limits. If sources change, stale rows cannot navigate: run the query again.
Navigation MUST preserve the accepted model and every source draft, and select
locations in the original UTF-8 bytes. Displayed locations use one-based lines
and UTF-8 byte columns.
**Show in diagrams** finds representations of a model record in saved diagrams,
process/chain canvases and scenarios. Use the Text toolbar with the caret on a
unique, verified alias in clean accepted sources, or the model tree's context
menu for the chosen record. Choose a destination, then its exact representation.
Lookup runs from an accepted-model snapshot; navigation preserves source drafts,
accepted geometry and history. Pending edits or modal operations must be
finished first. Changed or stale results cannot activate a different target.
Membership follows the actual projection, including visible ports, state action
and internal-transition rows, qualified reuse tiles, and SequenceLink arrows
painted inside caller previews. Repeated callers have distinct destinations
within the same canvas. Hidden preview endpoints and deeper nested links that
the renderer does not draw are excluded; projected adjacency without an actual
relation is not a SequenceLink usage. Preview-arrow focus lies on a visible
line segment outside opaque tiles.
An Allocation projection represents a direct Allocation relation by grouping
only when its visible source performer placement occurs on the visible target
work placement's actual visual-parent chain. Aggregate-only allocation summaries
do not create direct relation usages. The navigation marker can focus a work
header, port owner or state row independently of semantic selection: selecting
an Allocation or state-action relation retains that relation as the model action
target. Camera movement preserves a valid marker; changing the selected record,
document, accepted revision or represented context retires it. Navigation does
not alter allocation ownership or the meaning of Delete.
Changing a graphical UUID must atomically update map keys and every reference.
Alias changes preserve UUID identity. Deletion must account for owned elements,
incident relationships, ordered occurrences, and diagram placements without
@@ -2117,45 +2079,6 @@ exchanges it references. Cross-layer counterparts are not owned descendants.
Text edits describe a complete candidate and must remove or repair dependencies
explicitly before Apply succeeds.
8.1. Scenario lifetime presentation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Scenario lifetime geometry is derived from the stored occurrences and their
sequence/operand ownership. It adds no model records, source annotations or
history entries. A lifeline's identity header and neutral editing guide remain
available before creation, after deletion and when its represented element is
unfinished. The guide MUST be visually distinguishable from a live interval;
it is an editing axis, not a statement that the participant exists.
A directly ordered Create starts the receiver's live interval at its occurrence;
Delete ends that receiver's interval at its occurrence. Create uses a named birth
marker and Delete an X, each selectable through the original occurrence identity.
The message's receiving endpoint MUST align with its marker, including self
messages. A pre-existing lifeline without a creation has a live interval from
below its header; without deletion it extends to the visible scenario bottom,
including in an empty scenario. A missing lifecycle receiver MUST NOT be inferred from
the exchange. An explicit local receiver remains meaningful when its exchange
reference is unfinished.
Operands MUST be projected independently from their enclosing entry context.
A lifetime change in an alternative, optional, loop or parallel operand MUST
NOT imply the same change in its displayed sibling or a definite lifetime
after the fragment. When local structure does not establish one lifetime across
the represented paths, the continuation is visually unresolved. A subsequent
explicit Create or Delete in the enclosing sequence can establish a definite interval.
Neither guard text, screen order nor a guessed loop count proves execution.
ScenarioUse remains opaque: opening its definition may show its lifecycle,
but a callee's geometry MUST NOT create or destroy a caller lifeline.
Call activation is distinct from lifetime. A branch-local Delete clips that
branch's visible activation at the death marker without inventing a Reply,
removing an unresolved-call warning or terminating sibling paths.
Solid activation bars are restricted to definite live intervals; an unresolved
continuation retains its uncertainty/call diagnostic rather than depicting
definite survival after a possible deletion. Selection,
insertion slots, source edits and Undo/Redo retain the same semantic identities
and validation boundary regardless of the rendered intervals.
9. Persistence and explicit migration
-------------------------------------
+8 -10
View File
@@ -1,6 +1,6 @@
# Linux packaging and deployment inputs
The packaging command stages **already-built** desktop, server and source CLI executables for `x86_64-unknown-linux-gnu`. It runs on Windows PowerShell 5.1 or PowerShell 7 (including Linux) with Python 3.11+ standard library, Git, and the matching Rust/Cargo dependency cache. It does not build, download, install runtime libraries or launch the application. Python creates and reads back the tar archive; end users do not need Python, PowerShell or Rust.
The packaging command stages **already-built** desktop/server executables for `x86_64-unknown-linux-gnu`. It runs on Windows PowerShell 5.1 or PowerShell 7 (including Linux) with Python 3.11+ standard library, Git, and the matching Rust/Cargo dependency cache. It does not build, download, install runtime libraries or launch the application. Python creates and reads back the tar archive; end users do not need Python, PowerShell or Rust.
Build and validate first in a source checkout. The current runtime validation baseline is Ubuntu 24.04 x86-64. A glibc symbol inventory is not a claim that every distribution with that glibc version supports the renderer and dialogs.
@@ -9,25 +9,23 @@ Build and validate first in a source checkout. The current runtime validation ba
-Version 0.2.0-rc1 -BinaryDirectory ./target/release -Python python3
```
For an explicit-target build, use `target/x86_64-unknown-linux-gnu/release`. A cross-build may supply another directory containing all three executables: `arcadia-studio`, `arcadia-server` and `arcadia`. Select the Rust compiler used for the intended build before packaging; its Linux target libraries, copyright reports and locked source/archive cache must be installed. Read-only `cargo metadata --locked --offline --filter-platform x86_64-unknown-linux-gnu` and Rust version/sysroot queries are the only Rust commands run by packaging. When packaging from Windows, `-Python C:/path/to/python.exe` selects Python explicitly.
For an explicit-target build, use `target/x86_64-unknown-linux-gnu/release`. A cross-build may supply another directory containing both `arcadia-studio` and `arcadia-server`. Select the Rust compiler used for the intended build before packaging; its Linux target libraries, copyright reports and locked source/archive cache must be installed. Read-only `cargo metadata --locked --offline --filter-platform x86_64-unknown-linux-gnu` and Rust version/sysroot queries are the only Rust commands run by packaging. When packaging from Windows, `-Python C:/path/to/python.exe` selects Python explicitly.
The script refuses existing output/claim names. It creates `dist/ArcadiaStudio-<version>-x86_64-unknown-linux-gnu/`, a `.tar.gz`, and an adjacent `.sha256`. A failed attempt leaves its claim and any partial outputs for diagnosis; choose a fresh version or output root rather than overwriting them. Archives use sorted paths, zero timestamps and uid/gid, 0755 for the three Linux executables and 0644 for other files. Every entry is read back and compared against staging, including permissions. The same unchanged inputs on the same Python/zlib implementation produce the same bytes; this does not promise reproducible compiler output.
The script refuses existing output/claim names. It creates `dist/ArcadiaStudio-<version>-x86_64-unknown-linux-gnu/`, a `.tar.gz`, and an adjacent `.sha256`. A failed attempt leaves its claim and any partial outputs for diagnosis; choose a fresh version or output root rather than overwriting them. Archives use sorted paths, zero timestamps and uid/gid, 0755 for the two Linux executables and 0644 for other files. Every entry is read back and compared against staging, including permissions. The same unchanged inputs on the same Python/zlib implementation produce the same bytes; this does not promise reproducible compiler output.
## Contents and provenance
All three executables, the MIT license, a package-specific README, complete tracked examples (including all water-pressure teaching/evidence files), deployment references and the reachable documentation closure are included. Relative Markdown/reST/HTML file links are checked before archiving; upstream license texts are preserved verbatim and their internal source-tree hyperlinks are outside that documentation check. Untracked private files, caches and unrelated harness history are not included merely because they exist on disk.
Both executables, the MIT license, a package-specific README, complete tracked examples (including all water-pressure teaching/evidence files), deployment references and the reachable documentation closure are included. Relative Markdown/reST/HTML file links are checked before archiving; upstream license texts are preserved verbatim and their internal source-tree hyperlinks are outside that documentation check. Untracked private files, caches and unrelated harness history are not included merely because they exist on disk.
`package.json` records input hashes and static ELF dependencies. `SHA256SUMS.txt` inventories every file except itself; the archive checksum covers that inventory too. `dependency-notices.json`, `THIRD-PARTY-NOTICES.txt` and `licenses/` use the same strict collector as Windows: exact target-filtered normal/build dependency graph rooted at `oa-desktop`, `oa-server` and `oa-cli`, locked crate archives, actual source hashes, checksum-bound supplements and embedded fonts, Rust distribution notices and target-library hashes. Unknown sources, absent notices or changed supplements stop packaging. No Linux system libraries are bundled by this pipeline; their runtime distribution supplies them and its notices.
`package.json` records input hashes and static ELF dependencies. `SHA256SUMS.txt` inventories every file except itself; the archive checksum covers that inventory too. `dependency-notices.json`, `THIRD-PARTY-NOTICES.txt` and `licenses/` use the same strict collector as Windows: exact target-filtered normal/build dependency graph, locked crate archives, actual source hashes, checksum-bound supplements and embedded fonts, Rust distribution notices and target-library hashes. Unknown sources, absent notices or changed supplements stop packaging. No Linux system libraries are bundled by this pipeline; their runtime distribution supplies them and its notices.
ELF preflight requires little-endian x86-64 executables/PIE, the glibc dynamic loader, no RPATH/RUNPATH and a reviewed set of direct libc/compiler-runtime imports. Unknown libraries require an explicit packaging design instead of being silently copied from a developer machine. Graphics/window/portal libraries loaded at runtime are outside that static import list.
Optionally pass `-BuildEvidence <json-file>`, containing nonempty `source_identity`, `profile`, `compiler`, exact `target`, and `binary_sha256` keyed by `arcadia-studio`, `arcadia-server` and `arcadia`. Hash strings must be lowercase SHA256. Target and binary hashes are checked; other fields remain explicit caller assertions. Omission records build provenance as unknown. Never label a development binary an optimized release because of its directory or package version.
Optionally pass `-BuildEvidence <json-file>`, containing nonempty `source_identity`, `profile`, `compiler`, exact `target`, and `binary_sha256` keyed by `arcadia-studio` and `arcadia-server`. Hash strings must be lowercase SHA256. Target and binary hashes are checked; other fields remain explicit caller assertions. Omission records build provenance as unknown. Never label a development binary an optimized release because of its directory or package version.
## Native extracted-bundle checks
The source authoring CLI is `./arcadia`. Run `./arcadia --help` for `check`, `lint`, `stabilize` and `rename-alias`; each takes an explicit `.arcadia` entry file. Mutation commands preview by default and require `--write` to apply their candidate; `--json` produces a machine-readable report. Test writes on a separate project copy. CLI use does not require a display, a server or Rust. Include CLI check, preview, write and unchanged-repeat checks in extracted-bundle acceptance, alongside desktop and server checks.
Extract into a fresh user-writable Linux directory and run from an unrelated working directory. Verify SHA256SUMS, file permissions, `file`/`ldd` and actual desktop/runtime libraries. A typical Ubuntu runtime needs X11/XKB and Wayland clients and Vulkan loader/Mesa Vulkan drivers. Linux Open/Save uses the application's path-entry dialog and does not require an xdg-desktop-portal backend. A successful `ldd` alone is insufficient because graphics/window libraries can be loaded dynamically.
Extract into a fresh user-writable Linux directory and run from an unrelated working directory. Verify SHA256SUMS, file permissions, `file`/`ldd` and actual desktop/runtime libraries. A typical Ubuntu runtime needs X11/XKB and Wayland clients, Vulkan loader/Mesa Vulkan drivers, and working session DBus plus an xdg-desktop-portal backend for file dialogs. A successful `ldd` alone is insufficient because these libraries can be loaded dynamically.
For a software Vulkan trial, first locate the installed lavapipe ICD; only if it exists, use:
@@ -35,7 +33,7 @@ For a software Vulkan trial, first locate the installed lavapipe ICD; only if it
WGPU_BACKEND=vulkan VK_DRIVER_FILES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json ./arcadia-studio
```
A compatible native GPU may run without these variables. WSLg uses real Linux user space with a particular display environment; record the actual X11/Wayland backend and do not infer support for all Linux sessions from one trial. Exercise Home walkthrough, Help/search, Linux Open/Save path entry, existing-file handling, SVG export overwrite confirmation, a multi-file project, diagram/source edits, Undo/Redo and reopening at normal/minimum window sizes. Compare complete saved model/source and inspect stderr, not merely whether a window appeared.
A compatible native GPU may run without these variables. WSLg uses real Linux user space with a particular display environment; record the actual X11/Wayland backend and do not infer support for all Linux sessions from one trial. Exercise Home walkthrough, Help/search, native Open/Save dialogs, a multi-file project, diagram/source edits, Undo/Redo and reopening at normal/minimum window sizes. Compare complete saved model/source and inspect stderr, not merely whether a window appeared.
Run the server against a separate local data directory and unused loopback port. Follow [server configuration](server.md) for health, authentication, ETags, restart and backup/restore. Test create/import, a changed conditional update, unchanged no-op, stale/invalid rejection, and persistence after a clean restart. Record exact binary/archive/source/compiler hashes and platform. Packaging verification is separate from current-tree release acceptance.
+1 -1
View File
@@ -22,7 +22,7 @@ Graphical and textual parity applies to the persistent fields of this profile. D
- OA captures operational needs; SA defines the selected system contribution. SA contains no internal logical/physical components, and Studio does not decompose SA Actors. The System may be absent while authoring, with a completeness warning.
- Work decomposition and performer allocation are independent. Only leaves have direct allocations. A parent drawn within one performer can be a computed leaf summary, not an additional allocation. Role sharing does not create several direct performers for one function.
- Nesting expresses semantic containment or the selected allocation projection. Placement movement does not change ownership or allocation. Hide and delete have different effects.
- Nesting expresses semantic containment or the selected allocation projection. A placement edit preserves ownership and allocation. In an Allocation view, a work-body drag previews and commits performer reassignment and placement as one transaction; Arrange next drag (Alt+A) keeps that gesture limited to geometry. Role responsibilities remain unchanged, and drops requiring ambiguous responsibility or collateral edits are refused. Hide and delete have different effects. Current verification and native limits are recorded in [issue 3](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/3).
- Counterpart creation copies mapped typed content and required references. Existing-counterpart semantic review compares typed facts and prior observations, with explicit keep, take or final-value decisions for supported scalar, structural, constructor and individual collection-row changes. Reference mapping and candidate validation apply before an undoable transaction. Ordered collections have explicit final-order review with retained rejected drafts. Included trace rows can combine multiple source contributions into one validated model/history transaction; conflicting decisions and incompatible reference mappings remain explicit blockers. Existing Child/Incident attachment fields and artifact lifecycle review are implemented. Artifact creation reserves an explicit counterpart identity and requires all seven metadata decisions; identified source-owner absence can delete a link, while destination-only Take retains it. Owner moves and kept Presence must agree. Latest attachment/artifact native acceptance remains pending. Review does not automatically synchronize arbitrary structure or overwrite the other perspective. Creation scope follows ownership/reference dependencies, not every incident relationship.
- Processes/chains use contributions and explicit sequence links; imported ordered exchange paths retain their implied order until topology conversion. Rich fragments belong to scenarios. Guards, expressions and state behavior text are descriptive; there is no execution engine. Mixed states and modes are permitted by this Studio profile.
- OA Communication means connect Entities/Actors directly and can allocate Interactions whose actual performers match their endpoints and direction. Transition to SA requires explicit compatible boundary-port decisions; the tool does not guess system ports. Preserved OA boundary exchanges use Legacy ports. Capability grouping is containment; include, extend and generalization use separate typed relationships in OA and SA. Data/item references remain within their layer and can have explicit transitioned counterparts.
+84 -55
View File
@@ -320,68 +320,97 @@ wrong-context edits or inability to preserve reproducible independent studies.
The comparison establishes semantic/text maintenance evidence, not human task
timings or full quantity/library integration acceptance.
## Scenario lifetime rendering integration — 2026-09-11
## Analysis and library contract convergence — 2026-09-11
Codex-ytr83r /root. Adopt the [scoped lifecycle proposal](release-scenario-lifecycle-design-20260910.md)
as derived presentation over existing source-7 semantics. Always retain a neutral
identity header/editing guide; depict definite live intervals separately, with
original-occurrence Create capsules and Delete crosses. Alternative, optional,
loop and parallel operands inherit their enclosing entry independently and leave
an unresolved continuation after a local lifetime change. Reused scenarios remain
opaque. This does not execute guards or add model/source/history records.
Root Codex-956atf read the complete [baseline refinement](release-analysis-baseline-contract-20260911.md),
[library refinement](release-library-compatibility-contract-20260911.md), their
complete fixtures and [independent review](release-refined-contracts-review-20260911.md).
Select the following architecture for production implementation:
Full-height ordinary spines fail to communicate creation/deletion; one global
earliest-birth/latest-death range would falsely order exclusive operands. Both
alternatives lose to the scoped projection. The [independent review](release-scenario-lifecycle-independent-review-20260911.md)
requires true visible root bounds, a complete rendering lane map and local
activation clipping at Delete; insertion bounds/eligible lanes must keep their
separate roles. Receiver endpoints and selectable markers must agree, including
self messages. Those findings determine the integration contract in language
section 8.1 and the real-Scene/native acceptance fixtures.
- Required property-owned Binding values, explicit ModelBaseline/Case selection,
one level of complete-case override maps and shared root checks. Clear removes
an override; Unbound masks the base. Inherited formulas evaluate dependencies
in the requested context. Pure calculations see only explicit parameters.
- Same-layer property dependencies and case targets, with explicit analysis
selection for transitions and exports. Check/case subjects may be absent;
architectural containment must not infer their selection. Validate every
effective dependency graph, including statically referenced unused branches.
- The refined R6 closed algebra, exact rational R7 literal/AST preservation,
affine point/difference distinction and declared-output kind anchoring.
Strict expression operands gather actual missing/failure causes; Boolean
control flow evaluates only the selected branch. Supported domain failures
are distinct from violated predicates and missing values.
- Whole accepted PortableDocument freeze with exact SourceBundle, local
definitions, all imported package contents/pins and validated provenance.
Replay resolves only that immutable private capture. A result report, shallow
case copy or current cache is not a reproducible freeze.
- Exact archive/reference/history identity alongside verified same-origin
typed-contract equivalence. Different nominal origins remain distinct.
Compatibility supplies a scoped expected/actual field-path and operation
correspondence; it never advances a pin or rewrites outside record identities.
Keep qualified neutral definitions, immutable mapped layered definitions and
ordinary editable pattern instances for the first coherent implementation.
- Explicit source preparation/acceptance with complete version-controlled
package/base/map/lineage state, recomputed admission and stale-input rejection.
Exact three-way facets retain independent local edits. Mounted OA/SA transfer
requires a verified exact target-layer export or an explicitly independent
editable local derivative; no relabeling or silent mutation of a mount.
Core/source semantics are unchanged. In section 4.3, replacing the old
guaranteed-only lifetime/duplicate-reply wording with possible shared-path wording
corrects documentation to `validation.rs` and the existing conditional/parallel
regressions; it does not broaden admission or add a new rule. Compilation and
native acceptance of the renderer are still pending at this decision. Revisit the
visual encoding if actual minimum-size engineering workflows make marker identity,
uncertain continuation or the distinction between guide and existence unclear.
These are architecture decisions, not claims that the proposed schema8 examples
are admitted by current source7. Before real consumer integration, enumerate and
implement the class-specific canonical contract over all interpretation-bearing
fields and use sites, exact transitive archive closure and full source/history
boundaries. Retain the frozen120-assertion prototype with its documented C2
threshold-unit coverage gap; production typing must check every operand.
## Diagram representation navigation — 2026-09-12
Close independent C1 before evaluator expansion: a request-local, profile-versioned
logical work meter must bound dynamic expression visits, calls, list traversal
and exact-number work. Static acyclicity/depth/node limits do not bound expanded
execution. Cache warmth must not change outcomes; terminal exhaustion stops
further traversal and marks collected causes as incomplete. Numeric ceilings and
the precise charging table require measured foundation implementation before
publishing the profile. The333-node/31-level counterexample and a nearby successful
case are mandatory tests across direct/API/frozen replay.
Codex-ytr83r /root. User issues [14](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/14)
and [17](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/17)
share one typed query and destination chooser; the [contract](../docs/diagram-navigation.rst)
defines identity, visible membership, source freshness and nonmutation. A result
retains its representation identity separately from its queried semantic subject.
Use the actual saved projection, process Graph, scenario Scene and state row
geometry. Repeated occurrences and qualified reuse paths remain distinct.
The exact numeric foundation is the next bounded core implementation. Ordinary
engineering approximations, a complete low-noise text workflow, two-project
library maintenance and native/API/source parity remain required release work.
An exact-only slice cannot complete the user's first release.
Reject endpoint-only membership and generic semantic-reference enumeration:
they admit suppressed edges and opaque callee contents while missing behavioral
occurrences and state rows. Reject a destination submenu containing every use or
always-visible per-line lenses: both add noise and scale poorly for the user's
editing workflow. An explicitly invoked, searchable chooser groups destinations
and exposes their occurrences on demand. Independent design work identified
minimum-window, repeated-name, source-caret, stale-result and full-history oracles
before implementation; passing those evaluators remains necessary for acceptance.
## Analysis production staging — 2026-09-11
Ordinary navigation must not reuse the legacy reveal action's implicit Apply and
persisted fold expansion. Resolve the exact target before changing presentation;
center that target at readable scale. This first implementation lists currently
rendered representations and explicitly discloses folded/filtered/unexpanded
exclusions. It does not claim complete authored-membership discovery. Revisit
transient hidden-object reveal after measured user workflows; adding a result
must never imply an invisible object was actually shown or silently edit a view.
Root accepts the concrete [production integration sequence](release-analysis-production-integration-plan-20260911.md).
Allocate schema8 to the next coherent production analysis integration. Start with
the actual Project's neutral definition catalog, three analysis element kinds,
typed expressions and a closed Local definition-reference environment. Imported
references will be admitted only with the real package environment; no placeholder
resolver, guessed pin, implicit type compatibility or competing package format.
This stages implementation and does not defer the required maintained libraries.
The Text entry point builds on delivered source navigation from33c6d83, including
eeeaa12 native corrections, while preserving the later canvas/chooser/repair
integration. It requires verified applied-source identity and never substitutes
model selection for the caret. Dirty-source semantic lookup remains a disclosed
limitation. Implementation is branch-specific at this decision; Windows build,
combined tests and native acceptance are not established by this record.
The first useful gate is the complete persisted/source-authored response budget,
shared two-parameter calculation and check: baseline7/4 seconds versus degraded9/4,
with explicit request context and the same core result through CLI and REST.
Required property fields cannot come from generic factory guesses. Existing
descriptive expressions/unit labels retain their exact old meaning and bytes.
Freeze older top-level wire DTOs before making definitions required in schema8;
reject new fields/constructors in older versions instead of silently dropping them.
Global, scoped parameter, imported and historical identities remain distinct.
Implement pure static numeric type helpers once and reuse them for admission and
runtime. Validate every effective case graph and unused branch before accepting a
candidate; deleting dependencies requires explicit same-batch repair. Numeric
domain failure is not a static type failure. Full evaluator traversal and actual
C1 input, provenance, terminal incomplete causes and immutable replay are required
before claiming evaluated engineering behavior. Until explicit analysis review/
transition facets exist, those entry points must reject unsupported analysis with
a clear capability error, including manual-trace paths that could otherwise appear
to reconcile headers alone.
## 2026-09-12 — Cross-machine coordination evidence
User clarification: independent Gitea peer sessions run on different machines and cannot access this session’s `.local` directory. In-thread delegated agents share this workspace. Publish required source, reviews and runtime evidence through versioned Gitea commits or attachments before handing them to peers; verify access and link the exact version. Local paths are provenance only for remote peers. Local compiler, process and native-window observations do not establish another machine’s state or a shared hardware lease.
Logical expression depth128 must be reconciled with bounded actual JSON/source
decoding; do not simply disable recursion limits. Raw byte, decoded string and
aggregate literal/graph/case-admission limits are separate from evaluation fuel.
Concrete decoder/admission ceilings remain subject to bounded boundary and timing
experiments; the implementer must surface those choices before locking the profile.
The current local numeric gate runs against frozen root source. New core contract
work proceeds in an isolated checkout, preserving root's Cargo/native leases and
the other hosts' CLI, staged-source and B4 ownership.
+13 -74
View File
@@ -1,77 +1,16 @@
> Superseded on 2026-09-11. This document is a preserved historical checkpoint.
> Live plans, priorities, ownership and handoffs now reside in [Gitea issue 1](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/1#issuecomment-410) and [issue 2](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/2).
> Do not resume synchronizing this ledger. See [STATE.md](STATE.md) for the integrated checkpoint.
# Historical execution plan — superseded
# First release execution plan
Live plans, ownership, dependencies and handoffs moved once to
[Gitea issue1 comment412](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/1#issuecomment-412)
and the linked canvas issue on2026-09-11, following the shared working agreement.
This document is retained as a stable navigation target, not a live ledger.
Updated 2026-09-11 for the published Codex-ytr83r B4 source checkpoint.
[PROJECT_GOAL.md](../PROJECT_GOAL.md) defines the full outcome;
[STATE.md](STATE.md) scopes evidence/ownership and
[TASK_LEDGER.md](TASK_LEDGER.md) separates facts from decisions.
The [complete original PLAN.md](history/2026-09-11-ledgers-before-gitea-migration/PLAN.md)
is byte-preserved with the [archive manifest](history/2026-09-11-ledgers-before-gitea-migration/manifest.json).
Its decisions, rationale, examples and historical evidence remain available;
relative links inside it resolve from the original `harness/` directory.
## Immediate integration and verification
1. Preserve completed integration c81e285/e207b04/b853a1e and reviewed B4 source
52f6e17 on codex/release1-ytr83r. Do not replay equivalent3978/d114 changes.
CLI-only01b76a1 was reviewed and imported as023e3a8 without core/dependency
changes. Preserve the new AGENTS maintenance instruction and exact goal bytes.
2. Core433, independent lifecycle-oracle admission, focused lifecycle22 and full
desktop675 passed on this host. Production freeze2908405 is unchanged by
evidence checkpoint3ade397. GUI build, both-layer history/reopen and corrected
workspace strict Clippy passed. Finish the affected test and Unicode/native
workflows below. Do not repeat the passed suites without a
source change or new finding. Root serializes writers and records exact scope.
3. Use the imported evidence2ec creation-oracle v2 for native Undo comparisons.
Reject unknown/changed detached files while allowing exact files
retained from an explicit pre-Undo origin. Preserve full Project and reachable
SourceBundle equality and original role identities through Redo/reopen.
4. Exercise current Windows UI at minimum/wide sizes: creation name/owner/viewpoint,
one-step history, stale/raw-draft rejection, first Escape/modal priority,
recovery, clicked root/ALT action/observation/reuse, exact caller return,
same-size Fit and natural subsequent scrolling. Use independent semantic
predictions, not only screenshots or serialization of observed outputs.
5. Review current external Gitea handoffs before importing staged prerequisites,
empty-state actions, contextual chooser or source CLI. Validate final combined
workflows and preserve explicit ownership/qualification semantics.
6. After actual B4 test/native acceptance, prepare a distinct runnable Windows
prerelease with current-toolchain notices and exact executable/source hashes.
Existing MCP credentials have now completed a scoped branch push and remote
readback; release attachment upload still needs concrete-artifact verification.
Codex-9e8r6t retains the earlier named-authoring prerelease ownership.
7. Linux setup/downloads/builds/checking are paused by direct user instruction.
Wait for the user to resolve WSL2 networking and explicitly instruct resumption.
Preserve installed Ubuntu, exact VirtioProxy configuration and complete/partial
offline inputs. Networking remains unresolved; preparation is not Linux
acceptance. Follow the current WSL/offline records rather than old reboot plans.
8. Incorporate the owner clarification in issue2: process/scenario interaction
should use consistent direct canvas workflows while preserving domain
constraints. Codex-956atf owns the shared canvas design; B4 rendering and
prerequisite forms support it but do not close this requirement.
## Capability milestones
| Outcome | Work and acceptance |
| --- | --- |
| Usable direct behavior/state engineering | Continuous ordered/explicit process authoring, clicked root/nested scenario insertion, exact reuse bindings/caller return, state naming/creation, recovery and source-preserving history. Complete B4 lifetime rendering with actual lifetime bounds, branch-local Delete activation clipping, incomplete lanes and self-arrow endpoints. |
| Precise engineering analysis | Refine property-owned baseline values/formulas plus explicit ModelBaseline/Case one-level overrides. Close quantity kind/unit/value, exact/approximate numerical policy, dependencies/cycles, false/missing/error, complete freeze and definition provenance. Implement coherent validated core/source/REST/GUI/history contracts. An exact-duration slice alone cannot satisfy the full goal. |
| Maintained reusable libraries | Resolve source-only normalization, pinned offline definitions/closure, provenance versus checked same-origin compatibility, source→local instance maps, explicit three-way updates/local divergence, subjectless analysis closure and OA/SA mounted-data transition policy. Demonstrate two projects/two instances, cosmetic and semantic upgrades, conflicts/detach and rollback. |
| Practical complete textual and graphical tasks | Measure small/large text-only creation, cross-file reference navigation, safe alias rename and lossless patch preview. Integrate source CLI and bounded contextual choices; actual keyboard/IME, repeated names, stale events, recovery and minimum geometry must pass. Keep offline guide/examples and normative source documentation aligned. |
| Complete engineering stories | Close OA↔SA transition/reconciliation, typed data/interfaces/state, artifacts, saved views, hosted workflows and tutorial tasks against the full current goal. Confirm parity and precise specification rather than inheriting historical exclusions. |
| Reproducible Windows/Linux release | Current tests/format/strict Clippy, reST/OpenAPI/migration/example gates; real GUI and REST transport/restart/ETag conflict acceptance; matching optimized desktop/server packages, complete notices/archive hashes and clean-runtime launch. Fresh independent requirements/domain/parity/architecture/UX/runtime review resolves material findings before release. |
Milestones run adaptively where independent work helps. Analysis and libraries
share definition/identity assumptions and must converge before broad migrations.
Other-host slices remain coordinated through issue #1 and Wiki. Native/Cargo
leases are host-local; source ownership and exact transfer heads are shared.
## Evaluator boundaries and replanning
Use authoritative source semantics, exact UUID/source preservation and actual
user workflows. Source-only experiments are not accepted new grammar; mounted
widget tests are not native readability; synthetic packaging checks are not
Linux runtime. Preserve old environmental failures as evidence without inventing
current blockers. Continue independent work when platform or transfer work waits.
[Archived prior plans](history/2026-09-11-ytr83r-integration/README.md) preserve
all previous milestone detail. Update this plan when a counterexample changes
the right next action; do not lower completion criteria after substantial effort.
Use [STATE.md](STATE.md) for the verified branch checkpoint,
[DECISIONS.md](DECISIONS.md) for durable decisions, and
[PROJECT_GOAL.md](../PROJECT_GOAL.md) for the unchanged user requirements.
Do not repeat the migration or revive the duplicated live ledger.
-41
View File
@@ -1,41 +0,0 @@
# Current engineering work and evidence
Start with the [user goal](../PROJECT_GOAL.md), [current status](STATE.md),
[execution plan](PLAN.md), [task ledger](TASK_LEDGER.md) and
[decisions](DECISIONS.md). Follow [AGENTS.md](../AGENTS.md) and current
[Gitea coordination](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/1)
before changing shared work. Dated reports describe their own source, host and
artifact; they are not current instructions or acceptance of later changes.
## Runnable milestones
- [Windows Studio and REST server authoring preview](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/releases/tag/v0.2.0-preview.authoring.20260911)
- [Standalone Windows source CLI preview](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/releases/tag/cli-v0.2.0-preview.authoring.20260911)
These are unfinished development milestones. Their release notes and validation
attachments define exactly what was shipped and tested. Full OA/SA engineering,
analysis, maintained libraries and current Linux acceptance remain unfinished.
## Current local evidence
| Question | Authoritative record |
| --- | --- |
| Which source was integrated? | [Integration audit](release-integration-ytr83r-20260911.md), [CLI import review](release-cli-integration-ytr83r-20260911.md) |
| What does lifetime rendering mean? | [Implementation and corrected review findings](release-lifecycle-render-ytr83r-20260911.md), [language specification](../docs/language.rst) |
| What will native behavior be compared against? | [Independent fixture and procedure](fixtures/scenario-lifecycle-native/README.md), [exact pre-native evidence](experiments/lifecycle-native-ytr83r-20260911/) |
| Which checks ran on this host? | [Host build record](release-host-bootstrap-ytr83r-20260911.md), [current status](STATE.md) |
| What remains for Windows packaging? | [Current runtime/notice preflight](release-b4-package-preflight-ytr83r-20260911.md), [publication path](release-publication-path-ytr83r-20260911.md) |
| Is Linux available? | [WSL outcomes and current user pause](release-wsl-postboot-ytr83r-20260911.md), [preserved offline inputs](release-linux-offline-preparation-ytr83r-20260911.md); setup/build/checking waits for the user's networking-resolution signal |
| What changed for Linux delivery? | [Three-binary CLI packaging and checks](release-linux-cli-packaging-ytr83r-20260911.md), [portable REST restart probe](release-rest-probe-portability-ytr83r-20260911.md); native execution remains pending |
| Which bounded follow-ups are proposals? | [Explicit Action allocation](release-qualified-action-design-ytr83r-20260911.md), [inheritance scaling diagnosis](release-inheritance-scaling-diagnosis-ytr83r-20260911.md) |
External staged-source, chooser and analysis/library owners maintain their current
handoffs in Gitea and the [shared Wiki](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/wiki/Home).
Import exact coherent source checkpoints before transferring conclusions to this checkout.
## History
[Archived integration ledgers](history/2026-09-11-ytr83r-integration/README.md)
preserve source-specific facts and earlier ownership. Existing dated evidence and
Git history remain available. Preserve unique findings and update links before
moving or removing material; active issue #1 remains open for the unfinished goal.
+121
View File
@@ -0,0 +1,121 @@
# User-requested reboot checkpoint — 2026-09-11
Codex-956atf `/root`. The user will install Ubuntu26.04 in WSL2 and reboot, and
explicitly requested progress preservation and a safe-reboot signal. Work is
**paused**, not completed. Resume only after the user returns. All three local
agents stopped and saved their work; root stopped its sole Cargo build. No machine
restart, installation, Windows feature change or credential change was performed.
## Saved source and ownership
- Main checkout `codex/behavior-authoring-20260910`: numeric foundation7d14bd0,
CLIbc311bc, corrected external evidence dc0f2e1, instructions ancestryc7ed894,
chooser/workspace7f081ad, staged prerequisites c0e66f9 (externaldf6f595), numeric
evidence/decoder review03d20ec, followed by this reboot checkpoint. Remote branch
is `codex/release1-956atf`. New desktop source is **uncompiled/unaccepted**.
- Isolated `.local/analysis-core-worktree-20260911/`, local branch
`codex/analysis-core-20260911`, remote `codex/analysis-core-956atf-20260911`:
Checkpoint `b96ff3935ab3f36b7144566e46559a05a29292a5`: WIP actual schema8
definitions/Expr/records, commands/references/migration and
static admission, based at7d14bd0. Its
`harness/release-analysis-core-schema8-wip-20260911.md` inventories20 code/test
paths and22 prepared, unexecuted tests. No source8/evaluator/transport closure.
- Isolated `.local/behavior-canvas-worktree-20260911/`, local branch
`codex/behavior-canvas-20260911`, remote `codex/behavior-canvas-956atf-20260911`:
WIP shared camera/viewport, based atc0e66f9. Checkpoint
`e511c4153fb5bb484652434340e0e4c7000c93d0` is deliberately
not compile-coherent: missing test module, missing App Camera handlers and old
production Scrollables still active. Its
`harness/release-behavior-canvas-reboot-handoff-20260911.md` lists exact paths
and ten remaining steps. Do not merge it as a finished canvas implementation.
Both WIP branches are independent of the main branch. Preserve them, finish their
bounded slices and review before integration. No worker may run Cargo/native or
edit the root checkout without a new root lease. Separate-host9e8r6t owns incoming
prerequisite-form refinements; ytr83r owns B4/lifecycle/Linux work. Re-read Gitea
issues1/2 and current Wiki before resuming; their progress may have changed.
## Verified gates and interrupted build
- Numeric26/26 at7d14bd0,0.29s execution; strict core all-target Clippy with
warnings denied passes11m49s. Exact162-input/binary/log provenance is in
[the numeric gate](release-analysis-numeric-gate-20260911.md).
- Local `cargo test --locked -p oa-cli -- --test-threads=1`:12/12 integration
tests, zero failures/ignored,3.00s execution after42.86s compile. The initial
`--bin arcadia` invocation ran zero tests and counts only as compilation.
Full log: `.local/logs/source-cli-full-local-20260911.log`.
- Previous desktop676/676, formatting and strict Clippy passed at2cc4d11.
No acceptance transfers to new7f081ad/c0e66f9 source.
- `cargo test --locked -p oa-desktop --bin arcadia-studio --no-run` was deliberately
stopped for this reboot while compiling oa-core after renderer dependencies.
Cargo exit101 follows the explicitly stopped owned rustc process (`0xffffffff`);
no source diagnostic or test failure was reported, and no desktop tests ran.
Preserve `.local/logs/desktop-chooser-contextual-first-20260911.log`. Root
verified no Cargo/rustc/Clippy processes remained after stopping its process tree.
## Two new focus findings to fix first
[Paused independent integration review](release-chooser-contextual-integration-review-20260911.md)
contains16 source hashes and two source-derived, unexecuted P2 findings:
1. Initial parent FormShown consumes its one-time focus. Child source Open removes
that parent widget tree; Back/Use remounts it without a new focus intent.
2. FormShown validates context before creating a global NAME_INPUT focus Task,
but the delayed operation is not bound to the still-current mount/session.
It can act on a replacement parent or clear current child/Review input focus.
Implement a live-session/mount-scoped focus operation covering initial mount and
source→parent return. Add actual mounted regressions for Open→Back/Use, changed
document/owner/modal/session between Task creation and execution, raw/source/history
preservation, and then continue the combined compile/focused/full/Clippy/native
gates. Do not misstate the popup search-input counterexample: the root Popup
operation traverses its ordinary content; the separate picker input is excluded.
## Native session and exact private backup
Immutable GUI80cf197 remains the native test binary; SHA256
`A5ED6DF334B1BFB620425AFDF3E863F0B522990E6FB47C6C401A71CF4443954A`.
All four OA create/history checkpoints and final reopen pass. Separate SA Action
Save/Undo/Redo passes, with63 accepted objects. Working entry:
`.local/native-qa/scenario-20260911/sa/project.arcadia`.
The current **unapplied** State draft has literal name `SA native state`, captured
by clicking SA A inspector at the inner chosen operand before SA Inner anchor.
Its lifeline is preselected, but SA Ready is not chosen and Create was not pressed.
It must not be described as a passed SA State checkpoint. Old GUI again required
scrolling its new form back upward to find Name; new fixes have not run natively.
Private backup `.local/reboot-20260911-1344/` contains the complete accepted SA
source directory, exact64,935-byte recovery JSON, build/CLI logs and hash manifest.
Recovery id `30511014-b831-47e3-afd2-6c4e44835a8f`; copied recovery SHA256
`5C7B90BE613AF35463C563B9AA85A7AB1F8D48561EA935ABC6FC1E79549DF0E8`.
Root verified its project/origin and raw draft name before copying. The original
checkpoint remains under `%LOCALAPPDATA%/ArcadiaStudio/recovery/`. The saved-model
backup passes `check sa-action` and exact `same` against sa-action-verified.
No private recovery data is committed or sent to Gitea.
After reboot prefer the application's Home recovery entry to resume this raw draft.
If needed, preserve any newer checkpoint before restoring the exact private backup
to that same recovery directory. Use the independent scenario oracle for subsequent
State/Reuse/Fragment/history/reopen checks. Old window handles/screenshot ids and
process ids are invalid after reboot; select the actual returned Studio window.
## Linux and resumption
Before installation, this account had WSL2.7.13/kernel6.18.33.2-2 and default2 but
no registered distribution or Ubuntu Appx package. VirtualMachinePlatform was
enabled, hypervisor present, common reboot flags absent; elevated feature detail
was unavailable. No Linux startup/build pass follows from those checks.
On return, inspect `wsl --list --verbose` and actually execute `uname -sr` inside
the installed Ubuntu. Verify the user's installed distribution/version, then set
up the project's Linux dependencies and perform real Linux build/test/runtime
gates. Keep Windows compilation serialized using `.local/toolchain/env.ps1`.
The isolated core's first proposed gate is its22 prepared analysis tests, plus
numeric regressions, after review of its WIP handoff. Full depth128 JSON decoding,
allocation/lifecycle/output caps and exact save/readback remain required; see
[the decoder review](release-analysis-decoder-review-20260911.md).
Continue the original complete OA/SA release goal, preserving issue2's modern
canvas requirement and analysis/library/source/REST/GUI parity. This reboot pause
does not alter completion criteria or authorize marking the project complete.
-64
View File
@@ -1,64 +0,0 @@
# Resume after the user-requested reboot — 2026-09-11
Codex-ytr83r /root. The complete first-release goal remains active and unfinished.
Read AGENTS.md, PROJECT_GOAL.md, current Gitea issues1/2 and Wiki before resuming.
This is a pause for the user's reboot, not a completed milestone or failed test.
## Saved source and evidence
Branch: codex/release1-ytr83r. Production source is B4 lifetime rendering52f6e17
plus CLI01b imported as023e3a8. b96286e records exact core/oracle evidence and
current harness index. d041212 preserves owner instruction-sync history and the
byte-exact supplied PROJECT_GOAL. a9a5768 records the Linux trial and contextual
source integration review. Later checkpoint commits add this resumption note.
Core all-targets passed433 tests, one intentionally ignored probe; the optional
probe separately passed. The independent lifecycle oracle and all six frozen
baseline/rename files passed before any native GUI launch. See the harness index.
No current desktop compile/test/native acceptance has been established.
## Interrupted Windows build
Cargo session93786 was interrupted at the user's request while compiling Iced
dependencies (last log entry cc1.4.5). It exited1 from interruption; no final gate
status JSON was emitted. A readback found no cargo.exe/rustc.exe process. Exact
partial log and explicit interruption record are in
experiments/lifecycle-native-ytr83r-20260911/. Preserve cached target outputs.
Use the existing ignored task-local toolchain, one Cargo job, after checking no
other writer is active. From the repository root in PowerShell:
```powershell
& '.local\run-gate.ps1' -GateName 'ytr83r-desktop-lifecycle-resume' -CargoArgs @('test','--locked','--offline','-p','oa-desktop','scenario_lifecycle','--','--test-threads=1')
```
The wrapper loads .local/toolchain/env.ps1. Then run appropriate direct-canvas,
full/strict desktop, server/CLI and GUI build gates serially. Review the new
typography report: wide Unicode Create labels can overflow the fixed capsule.
The proposed clipping correction is not implemented; preserve existing fixtures
and define separate expected Unicode cases before native output. Actual Windows
wide/minimum/Fit/Save/Undo/Redo/reopen acceptance and B4 packaging remain pending.
## Linux after reboot
Recheck wsl --status and wsl --list --verbose. Before reboot, no distribution was
installed; WSL reported virtualization unavailable and Windows had a pending
reboot. Hardware virtualization must be available (firmware or nested VM host).
No host setting was changed and no reboot was performed by the agent.
Prefer a working WSL2 Ubuntu for real Linux build/runtime validation. The verified
Ubuntu image and QEMU cache remain under .local/linux-host-ytr83r. Its bounded
UEFI/TCG pilot ended without guest-ready evidence; all owned pilot processes
stopped. Do not repeat failed delivery or infer Linux acceptance from the image.
## Coordination and next integration
Codex-9e8r6t owns contextual prerequisites; df6f5956 is available locally and has
a reviewed minimal import path, with two B4-preserving merges. Later short-host
layout and Save-procedure corrections are separate; inspect the current remote
handoff before import. Codex-956atf owns chooser, shared constrained canvas design
for issue2, and analysis/library contracts. Local audit agents have stopped their
assigned work. They must recheck coordination before taking new tasks.
The two published Windows authoring/CLI prereleases remain available. No B4
release should be published until actual current tests/native acceptance pass.
+76 -42
View File
@@ -1,57 +1,91 @@
# Integrated checkpoint — 2026-09-12
# Verified branch checkpoint — 2026-09-12
Codex-ytr83r, isolated branch `codex/canvas-union-ytr83r-20260911`. Current source `33e30c1` combines the a57 canvas, cb91525 grapheme and narrow saved-destination repair corrections. Its 530 frozen inputs match HEAD; independent repair review found no actionable finding. Windows desktop tests, strict Clippy, GUI build and bounded matching native/package acceptance passed. The [canvas-repair Windows prerelease](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/releases/tag/v0.2.0-preview.canvas-repair.20260912) is published; ZIP, checksum and validation attachments were downloaded and hash-verified. [Publication record](release-canvas-repair-publication-20260912.md) preserves the exact identities. This is not a full [user-goal](../PROJECT_GOAL.md) completion claim. Live [canvas integration](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/2), [native/release acceptance](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/5), [saved-destination repair](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/6) and [project overview](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/1) retain ownership and plans. Earlier production `865483b` and its package remain preserved.
This checkpoint describes Codex-956atf's contribution, not a combined release.
[PROJECT_GOAL.md](../PROJECT_GOAL.md) remains authoritative; the complete OA/SA
release is unfinished. Current user guidance emphasizes close study of Capella
semantics and practical, ergonomic engineering workflows.
## Verified code and capabilities
**Linux/WSL builds and all checks are paused until the user explicitly reports
networking resolved.** No guest diagnosis, restart or cache transfer is active.
Completed Linux evidence remains historical; the VPN remains untouched.
Source `33e30c1` binds repair dirty state to the actual saved destination, preserving accepted-model history even when Apply is an identical-content no-op. It selectively incorporates peer `33c6d83` in three files. Windows focused repair **5**, full desktop **761**, strict desktop all-targets Clippy and GUI build passed; the five are included in 761. All **530 files / 9,727,025 bytes** remained unchanged between gates and matched HEAD after the build. The preserved GUI `50486253…` passed matching repair/history/recovery and Unicode selection/passive-save checks, packaged walkthrough/help smoke and normal exit0 with empty logs. All559 package files stayed unchanged; fresh extracted server25-request editing/persistence checks passed. [Current validation and artifact hashes](release-canvas-repair-validation-20260912.md) links the exact raw archives and independent reviews. [Repair union and limits](release-repair-union-ytr83r-20260912.md), [closed gates and exact inputs](experiments/repair-union-windows-33e30c1-20260912/README.md), [verbatim independent review](release-saved-destination-independent-review-20260912.md).
## Verified implementation
Source `cb91525` preserves extended grapheme clusters in the shared display helper. Its four focused tests, full desktop 756 and strict desktop Clippy passed; the four overlap the 756. Its GUI build was intentionally superseded by the repair union; matching combined33e native Unicode evidence is recorded above, without reattributing that result to cb91525. [Correction and limits](release-grapheme-shortening-ytr83r-20260911.md), [closed Windows evidence](experiments/grapheme-windows-cb91525-20260911/README.md).
Previous native acceptance uses source **3c9e6eeb64ce3efc03b29890b82199a42c21f335** on
`codex/behavior-authoring-20260910`. It passes 720/720 Windows desktop tests and strict
all-target desktop Clippy. It includes direct scenario/process authoring,
parent-focus and editing-session/chooser corrections, and boxed workflow events.
Evidence checkpoint e7491fb preserves exact logs. Instruction-only merge828c50c
retains the incoming user-owned AGENTS/PROJECT_GOAL files unchanged. The actual
remote default branch `main` was checked after that merge; its current guidance
was read without overwriting the user's local specification.
The isolated `a57c334` union selectively combines peer `a31b40d` canvas/chooser/form prerequisites with B4 lifetime rendering and contextual source/child-work corrections. Windows lifecycle **27**, full desktop **752**, strict desktop Clippy and Studio build passed on 529 unchanged frozen inputs. GUI `69DBB90F…` passed bounded staged source/consumer creation, Cancel, Save, Undo/Redo and reopen checks: 13 oracles and 45 screenshots at the default wide window only. [Canvas checkpoint](release-canvas-union-ytr83r-20260911.md), [staged archive](experiments/staged-source-native-a57c334-20260911/README.md), [independent review](release-staged-native-a57-independent-review-20260911.md). A fresh a57 camera session subsequently passed bounded OA 100%/125%/Fit and minimum 1100×700 client Fit66 checks, OA/SA pan and moved Create/Delete hit selection, exact passive Save equality and normal exit 0. The 18 images support bounded clipping without toolbar bleed; labels are small at 66%. [Camera archive and limits](experiments/canvas-camera-a57c334-20260912/README.md), [verbatim independent review](release-camera-a57-independent-review-20260912.md). The [earlier picker failure](experiments/canvas-native-close-a57c334-20260911/README.md) remains historical evidence. These pre-grapheme a57 results do not establish current `33e30c1` native or complete usability acceptance.
The matching GUI built warning-free and passed recovered SA State, clicked Reuse,
and ALT Fragment creation with exact Save/Undo/Redo and final native Open/Save at
the 1100x700 client minimum. The whole Project, all identities and both source files
match every required history checkpoint. The native session is closed.
Earlier published checkpoint `3ade397008cffe826d5f5a70e7c0233159e3bd42` contains production `29084050a7c020e0fb488be37c6e1ab235769cc0`; push and exact remote readback passed. It combines prior named behavior creation/history integration (`c81e285`, `e207b04`), corrected creation-oracle evidence (`b853a1e`), CLI-only integration (`023e3a8`) and B4 lifecycle rendering.
- [Windows regression/lint evidence](release-chooser-correction-gate-20260911.md)
- [Previous native SA evidence](release-scenario-native-3c9e6ee-20260911.md)
- [Earlier native OA/SA Action evidence, scoped to 80cf197](release-scenario-native-20260911.md)
- [Scenario oracle and reproducible procedure](fixtures/scenario-authoring/README.md)
B4 renders local lifetimes, branch-local activation termination, neutral incomplete lanes, Create capsules and Delete markers with original occurrence identity. Real Windows OA/SA six-case matrices and separate name-only Save/Undo/Redo/reopen workflows passed complete independent Project, reachable-source and physical-file comparisons. These are bounded fixture checks, not complete product usability acceptance.
## Isolated contributions and material limits
- [Native lifecycle observations and limits](release-lifecycle-native-ytr83r-20260911.md).
- [OA evidence archive](lifecycle-native-ui-oa-archive-20260911.md) and [SA evidence archive](lifecycle-native-ui-sa-archive-20260911.md).
- [Lifecycle implementation and independent findings](release-lifecycle-render-ytr83r-20260911.md).
- [Creation and source integration evidence](release-staged-source-integration-ytr83r-20260911.md).
Core candidate **847b1caa7e75bb82f6ce5193c45bcfc45973ad1a** is on the separate
`codex/analysis-core-956atf-20260911` publication branch. Windows execution passes
the 128 KiB-thread lifecycle subprocess, all 6 codec tests, 28 analysis tests, 26 numeric
tests and strict all-target core Clippy. These counts are separate scopes; the
subprocess driver is included in the 6. Production `DEPTH_128_VALIDATED` remains
false. Legacy/migration/save integration, release memory measurements and complete
source8/transport/evaluator acceptance remain open.
[Windows codec evidence](release-analysis-codec-windows-gate-20260911.md).
Source `321897fd55af9e07afa2c6ebf1e50be49e86f7d9` integrates the published contextual source-creation/minimum-card corrections from b2c3e540 with B4 and the header clipping correction. Its own Windows desktop all-targets gate passed 704 tests. [Exact selective integration, independent union review and Windows results](release-contextual-integration-update-ytr83r-20260911.md).
The cleaned R123 canvas at **a31b40d0f8551ed87c8cd66250b9afb4809b3a79** passes
729/729 Windows desktop tests, strict all-target Clippy and the matching GUI build.
All 518 input identities agree with Git and the closed receipts. Actual minimum-size
OA action, nested state, bound reuse and ALT creation passed Save and exact one-step
Undo/Redo Project/SourceBundle comparisons. All 85 archived files match their Git
index bytes. Reopen was interrupted by physical Escape and remains unverified;
Computer Use remains paused. [Exact gates and bounded native evidence](release-behavior-canvas-a31b40d-native-20260911.md)
supersede the earlier pre-cleanup gate as this source's checkpoint.
Published production `865483b4c66361a01fe0d9e731859220bafb4136` adds the reviewed child-work correction: first refinement transfers existing Allocation and RoleAssignment identities, metadata and artifact references to the child; later siblings inherit only a unique performer. OA/SA regressions cover nested children, roles, folded grouping, unallocated/mixed controls and exact history. The old extracted Studio `BF9C2E61…` passed OA first-child, sibling and grandchild Save/Undo/Redo checks, then confirmed OA reopen/Save and the SA first/sibling/grandchild, Undo/Redo and reopen/Save continuation. Original identity carriers and complete source/physical snapshots matched. These are native results for **865483b/BF9**, not a57/69DB. [Original OA evidence](experiments/native-child-oa-865483b-20260911/README.md), [closed continuation](experiments/native-child-continuation-865483b-20260911/README.md), [independent continuation review](release-native-child-continuation-review-20260911.md), [fixture/oracle](fixtures/child-work-native/README.md) and [issue4](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/4) preserve the exact scope.
Allocation candidate **f52d81c1b96a34bb78b8ada27b7761dc0b009f5d** preserves the
canvas source and passes its first 54 focused Windows planner/App/widget tests,
including four actual App-tree focus/keyboard/render cases; all 525 inputs remained
unchanged. This is not a full-suite, strict-lint, native or release gate. Independent
review found a frozen performer label can still obscure the dragged work header;
that repair and broader integration remain unverified. [Issue 3](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/3)
owns its live work. Parent/child native focus, complete direct manipulation,
persistent process placement/lanes and coherent peer integration remain open.
## Verification scope
The combined allocation/saved-destination repair baseline **d9b3f0dc91e8882e6efc262c2e8d971998d2694e**
passes 792/792 Windows desktop tests with all 526 source inputs unchanged.
[Exact baseline evidence and independent review](release-allocation-d9b3f0d-windows-20260912.md).
Review found the fixed-label overlap refusal makes a collapsed long-name target
unreachable with an ordinary grab offset. The [feedback decision](release-allocation-feedback-decision-20260912.md)
replaces duplicate canvas labels with a dedicated toolbar identity; that correction
and current strict-lint/native acceptance remain unverified.
On this Windows host, core all-targets passed433 tests with one intentionally ignored scaling probe; that probe separately passed with unoptimized timings. Production29084050 passed focused lifecycle22 and full desktop675 tests (the22 are included in675), and the ordinary GUI build/launch. An equivalent test-helper let-chain correction subsequently passed strict workspace/all-targets Clippy and its focused regression1/1. These results predate the newly identified header-rendering correction.
Complete quantities/calculations/constraints, maintained libraries, graphical/
source/REST parity, transitions and engineering-task usability, aligned reST/help,
optimized packages and final independent acceptance remain required. Finite
prototypes and published previews are intermediate results.
- [Exact current-host logs and inputs](experiments/lifecycle-native-ytr83r-20260911/).
- [Test-only Clippy correction](lifecycle-clippy-correction-ytr83r-20260911.md).
- [Current-host toolchain setup](release-host-bootstrap-ytr83r-20260911.md).
- [Independent Windows gap review](release-windows-gap-review-ytr83r-20260911.md).
## Authoritative records
The closed 321897f Windows gate passed 704 desktop tests with zero failed/ignored/filtered; all 261 recorded build inputs remained unchanged. Matching server `ABA87A5F…` passed semantic HTTP checks (204 schemas, 19 values, 9 rejected invalid shapes) and the corrected REST probe's 25 requests. [Closed runtime evidence](experiments/windows-runtime-321897f-20260911/README.md) preserves both earlier source-version failures. [Earlier integration checkpoint evidence](experiments/contextual-lifecycle-integration-ytr83r-20260911/README.md) preserves server/CLI 68 across 7 targets, schema 72/204 after the missing-jsonschema correction, and the old GUI's wide-name passive Save comparison.
- [Project overview and historical coordination](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/1)
- [Direct process/scenario canvas work](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/2)
- [Activity allocation drag](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/3)
- [Analysis, codec and source/API integration](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/7)
- [Maintained reusable libraries](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/8)
- [Decisions and reusable evidence](DECISIONS.md)
- [Shared overview](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/wiki/BehaviorAuthoring20260911)
- [Published milestones and their exact limitations](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/releases)
- [Historical Linux gate before deferral](release-linux-core-cli-gate-956atf-20260911.md)
The later 865483b Windows desktop gate passed **707 tests**, including the three focused child-work regressions, with zero failed/ignored/filtered. All 261 recorded build inputs stayed unchanged. The matching debug GUI build and strict **desktop-only** all-targets Clippy passed; child-work and staged-source checker compilation/admission also passed. [Closed gates and exact inputs](experiments/windows-gates-865483b-20260911/README.md). These checks do not establish the remaining native rendering or packaged acceptance.
The extracted package's unchanged server `ABA87A5F…` passed the actual HTTP schema checks (204/19/9) and 25-request REST editing/persistence/restart probe with a restricted process PATH and unrelated working directory. Seven raw response pairs and exact source snapshots matched; all five test-owned server processes stopped. The first REST run's PowerShell-added PATH directory is preserved as historical evidence; the corrected restricted-PATH rerun is authoritative. [Packaged server evidence](experiments/packaged-server-865483b-20260911/README.md). This completed the earlier bounded server runtime acceptance. Fresh33e package/server/GUI results are linked above; the old receipts retain their own source attribution.
## Material limitations
Earlier native wide Latin/CJK checks found neutral lifeline header text overflowing its card while Create labels stayed contained. The [header correction](lifecycle-header-overflow-correction-ytr83r-20260911.md) is included in 865483b and retained in a57. Actual corrected wide-W/CJK observations in BF9 show bounded headers and Create labels, including selected zoom, scroll and minimum-window cases. Both complete wide and cluster sources remained unchanged after passive Save. Cluster checks exposed a separate scalar-shortening defect: an accent or joined emoji can be split at the label cutoff. The later cb91525 correction and current33e accent/ZWJ selection/passive-save checks resolve the observed string-splitting case. Long wide labels can still be hard-clipped and arbitrary font/DPI presentation is unverified; see the historical [native typography record](experiments/lifecycle-header-correction-native-865483b-20260911/README.md).
The earlier capture failures and pending Open dialog are historical: later confirmed OA and SA reopen/Save actions are preserved in the [continuation archive](experiments/native-child-continuation-865483b-20260911/README.md). Its first OA `reopened-1948` receipts remain data-only evidence. Bounded a57 staged and camera workflows above are complete; full focus/keyboard, every clipping edge/zoom and accessibility remain unverified. Bounded combined `33e30c1` native/package acceptance is now linked above. Small 66% labels are a recorded limitation. The BF9 Home page, scenario guide and bundled water-pressure example opened; one normal Alt+F4 then completed, with the process absent and empty stdout/stderr. The [old Home/Guide/close archive](experiments/packaged-gui-close-865483b-20260911/README.md) preserves those old865/BF9 observations and package readback. No exit code was captured for that older BF9 process; the separate a57 exit 0 does not change its evidence.
The selected chooser/canvas union now has a57 source and Windows gate evidence; broader persistent graphical manipulation and separate text-navigation contributions retain their own integration/acceptance boundaries. Calculations, quantities/units, maintained libraries, practical large-model textual workflows, complete OA↔SA engineering parity, documentation and fresh cross-disciplinary review remain full-goal requirements. See the [analysis proposal](release-analysis-semantics-design-20260910.md), [library proposal](release-libraries-semantics-design-20260910.md), [text-authoring design](release-textual-authoring-design-20260911.md) and [decisions](DECISIONS.md) for attributed design evidence, not completed implementation claims.
## Platform and published deliverables
**Linux setup, downloads, builds and checks are paused by explicit user instruction until the user reports networking resolved and instructs resumption.** Ubuntu26.04/WSL2 shell execution was observed; guest networking remained unavailable. Offline preparation was a workaround, not a network fix or Linux acceptance. Host VPN settings were not inspected or changed. [WSL evidence](release-wsl-postboot-ytr83r-20260911.md) and [preserved offline inputs](release-linux-offline-preparation-ytr83r-20260911.md) retain exact outcomes.
Peer Codex-9e8r6t published the separately verified [Windows contextual prerelease](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/releases/tag/v0.2.0-preview.contextual.20260911), source `b2c3e540`; [its publication handoff](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/2#issuecomment-406) binds its artifacts and original-host checks. It is not a B4 release from this branch.
## Record navigation
The [one-time record migration](history/2026-09-11-ytr83r-record-migration/README.md) preserves the exact prior STATE ledger and marks PLAN/TASK_LEDGER superseded. [Earlier integration history](history/2026-09-11-ytr83r-integration/README.md) preserves source-attributed older results. Historical leases, failed approaches and next-step wording do not override current Gitea coordination or the Linux pause.
The duplicated live ledgers were migrated once into Gitea comment412. Their
[complete original bytes and manifest](history/2026-09-11-ledgers-before-gitea-migration/manifest.json)
preserve historical assumptions, decisions, experiments, limitations and links.
Links inside the archived documents retain their original `harness/` base.
Do not maintain live plans in this checkpoint or repeat that migration.
+13 -142
View File
@@ -1,145 +1,16 @@
> Superseded on 2026-09-11. This document is a preserved historical checkpoint.
> Live plans, priorities, ownership and handoffs now reside in [Gitea issue 1](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/1#issuecomment-410) and [issue 2](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/2).
> Do not resume synchronizing this ledger. See [STATE.md](STATE.md) for the integrated checkpoint.
# Historical task ledger — superseded
# Task Ledger — first release
Live plans, ownership, dependencies and handoffs moved once to
[Gitea issue1 comment412](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/1#issuecomment-412)
and the linked canvas issue on2026-09-11, following the shared working agreement.
This document is retained as a stable navigation target, not a live ledger.
Updated 2026-09-11 for Codex-ytr83r. The full
[user goal](../PROJECT_GOAL.md) and [current progress](STATE.md) remain authoritative.
[Exact host ledger archives](history/2026-09-11-ytr83r-integration/README.md)
preserve prior facts, dates and reasoning without transferring their acceptance.
The [complete original TASK_LEDGER.md](history/2026-09-11-ledgers-before-gitea-migration/TASK_LEDGER.md)
is byte-preserved with the [archive manifest](history/2026-09-11-ledgers-before-gitea-migration/manifest.json).
Its decisions, rationale, examples and historical evidence remain available;
relative links inside it resolve from the original `harness/` directory.
## Goal and given requirements
Deliver a complete, usable OA/SA release on Windows and Linux, with one explicit
reST semantic contract and equivalent graphical, textual and REST access. Include
constraints/calculations, quantities/units, maintained libraries, behavior/state,
traceability and navigable offline help. Reduce cognitive load and visual clutter;
small and large models must be practical using text alone. Later Arcadia layers
remain future scope. Compilation or a pleasant happy path is not completion.
Issue2 further requires consistent direct process/scenario canvas interaction;
the owner's clarification allows domain constraints rather than arbitrary movement.
At15:28UTC on2026-09-11, the user explicitly deferred Linux builds and checking
until they resolve WSL2 networking and instruct resumption. Linux setup/downloads
are paused with inputs preserved. Continue independent Windows work; do not treat
offline preparation as a networking fix or Linux acceptance.
## Verified facts
- Local start was cleanff615d0. Root decoded/hash-verified/imported published3978,
c6 and4bb bundles; merged c6 as c81e285 and integrated creation4bb at e207b04. There were
no production cherry-pick conflicts; docs/attributes require evidence union.
The current goal is copied from the user's latest file.
- Read-only integration comparison finds equivalent workspace/Sensor code in c6;
replaying3978 or d114 is unnecessary. Core source is unchanged betweenff andc6.
B4 now has a production Scene bridge and independently reviewed source, with
focused lifecycle22/22 and full desktop675/675 passed on source2908405. The
ordinary GUI build and real OA/SA lifecycle matrices now ran; OA full name-only
Save/Undo/Redo/reopen and the corresponding SA workflow passed exact independent
comparisons. Corrected workspace/all-targets strict Clippy also passed0;
Unicode appearance remains open. See the
[native record](release-lifecycle-native-ytr83r-20260911.md) for exact scope.
- Imported source implements named behavior creation, exact prepared-batch
correlation, success-only selection, raw-draft guards, recoverable original
layer and modal-priority Escape. These are source facts; combined local runtime
acceptance is pending.
- Earlier-host desktop642 and653 suites, scoped native scenarios/creation,
packaging25 notices and source experiments retain exact attribution in
[STATE.md](STATE.md). They are not new local passes.
- The original transferred creation oracle incorrectly equates physical disk files
with reachable sources during Undo. Later external v2 corrects the evaluator
with explicit origin/retained-byte rules; exact v2/evidence2ec was imported at
b853a1e after complete path/hash preflight. New host execution is still pending.
- Isolated Rust1.98.1/LLVM23.1.1 and locked dependencies are available. Packaging
11/11 and synthetic Windows notice checks pass. Current core all-targets passed
433 tests; its optional inheritance probe separately passed with slow debug
timings that require controlled optimized interpretation. Focused lifecycle
passed22/22 after two installed-Iced API corrections; full desktop passed675/675.
Strict reST/HTML generation passes with Docutils0.22.2.
- B4 independent criticism found and resolved self-caption overlap and two dense
minimum-Fit hit-selection counterexamples. Shared nearest marker/message-stroke
arbitration preserves exact marker/header/label selection. Ten real-Scene tests
and two clip geometry tests passed in the22-test focused gate. The independent twelve-scenario native oracle passed compile,
admission, self-check and exact baseline/name-only predictions before GUI output.
- The separate baseline-context experiment passed218 assertions; explicit
one-level overrides reduce repeated stable assumptions while complete frozen
definition environments remain necessary. Proposed syntax is not source7.
- After the user's virtualization/reboot change, supported Ubuntu26.04 install
completed exit0 and a real x86_64 WSL2 kernel shell completed. Later VM startups
timed out before apt. Owner328's exact VirtioProxy configuration now supports
a persistent root shell, but requested IP/DNS/HTTPS checks failed. Signed offline
dependency preparation advances without host VPN inspection or changes. This
establishes guest execution, not Linux builds or GUI acceptance; exact outcomes are
in the [WSL record](release-wsl-postboot-ytr83r-20260911.md).
## Assumptions and unresolved questions
- Combining already coherent desktop slices should preserve behavior; fresh build,
automated and native gates must test that assumption.
- The baseline/library designs can fit existing atomic Project/Command/source
boundaries; exact references, deletion, transition, imports, freezing and
numeric rules still need ratified contracts and falsification.
- Pinned package provenance must be distinguished from checked type compatibility;
unchanged quantity kinds cannot become incompatible merely through cosmetic
repackaging without a deliberate policy. Energy and Torque remain distinct.
- Ubuntu26.04/WSL2 is the current supported Linux route; reliable repeat startup,
guest toolchain/dependencies and GUI/service/package execution remain open.
Initial shell success does not erase later startup timeouts. Old QEMU work is
retained as history, not the next route to repeat.
- Large-model human/AI task usability, cross-file refactoring, actual chooser
latency/keyboard/minimum geometry and complete native lifecycle behavior remain
to be measured. Parser admission or a widget experiment is insufficient.
## Candidate designs and selected directions
The imported [analysis proposal](release-analysis-semantics-design-20260910.md),
[library proposal](release-libraries-semantics-design-20260910.md),
[paired critique](release-semantic-proposals-review-20260910.md) and
[textual authoring design](release-textual-authoring-design-20260911.md) retain
alternatives and counterexamples. Metadata-only analysis and bare source includes
do not meet evaluated quantities or maintained libraries.
Codex-956atf root selected property-owned baseline values/formulas with explicit
ModelBaseline/Case evaluation and one-level case overrides for contract refinement.
No hidden default case or UI-dependent evaluation; inherited formulas use the
effective requested case, and complete freeze captures definitions/provenance.
Exact numeric, library normalization/type compatibility and transition details
remain open. This direction is recorded in [DECISIONS.md](DECISIONS.md), not silently
treated as completed production semantics.
The external staged prerequisite design reserves source/consumer identities,
keeps the parent context/rawtext/slot, stages locally and creates source+consumer
in one atomic final command. It must not implicitly allocate work, involve
capabilities, retarget an Exchange-fixed endpoint or accept a different editor.
Qualified Action allocation remains a distinct engineering choice.
## Retained implementation decisions
- Keep one authoritative typed Project, validated atomic Commands, stable
identities and explicit references. Semantic ownership/allocation/order and
diagram geometry remain distinct; forms are adapters, not a second metamodel.
- Preserve source ownership/comments/includes and exact model/source history.
Writeback succeeds before adoption. Invalid/rejected raw drafts survive and
browsing/tool selection does not silently accept another editor. Recovery
validates/replans rather than trusting serialized commands.
- Semantic reconciliation uses finite typed facets, frozen baselines, explicit
mappings and one atomic candidate. Names alone never establish identity.
- OA↔SA transitions are explicit engineering decisions. New persistent semantics
need validation/reference/deletion/transition/source/API/UI/history parity.
- Exact evidence bytes and host attribution survive integration. No focused
test total is added to a full-suite count; old binary acceptance does not
transfer to newly merged code.
## Current strategy and coordination
Root owns local integration, serialized builds, native inputs and final synthesis.
The local audit resolves evidence and reviews source; independent server review
has its own report. Codex-9e8r6t owns staged sources/first actions and source CLI;
Codex-956atf owns chooser, semantic contracts and the shared canvas design. Read Gitea issues #1/#2 and Wiki before
resuming, obtain exact coherent transfer heads, and respect their source ownership.
First finish and verify the integrated current source using the imported corrected
evaluator and newly prepared independent lifetime oracle. Then close remaining modeling/textual,
analysis/library and platform gates with independent criticism and whole-task
acceptance. Update facts, assumptions and decisions as evidence changes them.
Use [STATE.md](STATE.md) for the verified branch checkpoint,
[DECISIONS.md](DECISIONS.md) for durable decisions, and
[PROJECT_GOAL.md](../PROJECT_GOAL.md) for the unchanged user requirements.
Do not repeat the migration or revive the duplicated live ledger.
-156
View File
@@ -1,156 +0,0 @@
//! Native issue4 fixture/oracle. generate DIR | check oa|sa STAGE ENTRY
//! snapshot ENTRY DIR | compare ENTRY DIR | self-check
use oa_core::{source_project::*, *};
use std::{collections::{BTreeMap, BTreeSet}, fs, path::Path};
fn id(n: u128) -> Id { Id::from_u128(0xc1140000000040008000000000000000 + n) }
fn work(layer: Layer) -> Kind { if layer == Layer::Oa { Kind::Activity } else { Kind::Function } }
fn fixture(layer: Layer) -> Project {
let mut p = Project::empty();
p.id = id(1); p.alias = "child_work_native".into(); p.name = format!("Issue4 {layer:?} child work");
for (n, kind, name) in [(10, if layer == Layer::Oa { Kind::Entity } else { Kind::System }, "Performer"), (11, work(layer), "Parent work")] {
p.elements.insert(id(n), Element { id: id(n), alias: format!("seed_{n}"), name: name.into(), description: format!("Preserve original {name}"), parent: None, body: ElementBody::new(kind, layer).unwrap() });
}
p.relations.insert(id(20), Relation { id:id(20), alias:"original_allocation".into(), name:"Original responsibility".into(), description:"Preserve allocation engineering rationale 雨".into(), body:RelationBody::Allocation { source:id(10), target:id(11) } });
if layer == Layer::Oa {
for n in [12,13] {
p.elements.insert(id(n), Element { id:id(n), alias:format!("role_{n}"), name:format!("Responsibility role {n}"), description:"Preserve role".into(), parent:None, body:ElementBody::new(Kind::Role, layer).unwrap() });
for (r, kind, source, target) in [(n+10,RelationKind::RoleAssignment,id(n),id(11)),(n+20,RelationKind::RoleRealization,id(10),id(n))] {
p.relations.insert(id(r), Relation { id:id(r), alias:format!("responsibility_{r}"), name:format!("Role link {r}"), description:format!("Retain role link metadata {r}"), body:RelationBody::new(kind,source,target) });
}
}
}
for (index, owner) in [id(20),id(22),id(23)].into_iter().filter(|owner| p.relations.contains_key(owner)).enumerate() {
let key=id(50+index as u128);
p.artifact_links.insert(key, ArtifactLink { id:key, alias:format!("evidence_{index}"), name:format!("Responsibility evidence {index}"), description:"Keep owner identity and evidence metadata".into(), owner, relation:ArtifactRelation::References, uri:format!("https://example.invalid/evidence/{index}"), revision:Some("review-7".into()), fragment:Some("assignment".into()) });
}
p.diagrams.insert(id(2), Diagram { id:id(2), alias:"allocation_view".into(), name:format!("{layer:?} allocated work"), description:"Native child-work fixture".into(), layer, projection:ProjectionKind::Allocation, routes:vec![], view_options:Default::default(), nodes:BTreeMap::new() });
for (n,element,x,y,collapsed) in [(40,id(10),60.,60.,false),(41,id(11),84.,124.,true)] {
p.diagrams.get_mut(&id(2)).unwrap().nodes.insert(id(n), NodePlacement { id:id(n), alias:format!("seed_view_{n}"), element, position:Position{x,y}, size:Size{width:224.,height:94.}, collapsed, port_anchors:vec![] });
}
execute_batch(&p,&[]).unwrap()
}
fn bundle(p:&Project)->CompiledSourceProject {
let source=language::format(p).replacen("{\n","{\n include \"rationale.arcadia\";\n",1);
let raw=SourceBundle { entry:"project.arcadia".into(), files:BTreeMap::from([("project.arcadia".into(),source),("rationale.arcadia".into(),"// Preserve included note bytes: responsibility 雨.\r\n".into())]) };
let result=compile_bundle(&raw,ProjectLimits::default()).unwrap();
assert_eq!(result.bundle,raw); assert_eq!(&result.decoded.project,p); result
}
fn load(entry:&Path)->CompiledSourceProject {
let raw=source_files::load_project(entry,ProjectLimits::default()).unwrap().reachable_bundle();
let result=compile_bundle(&raw,ProjectLimits::default()).unwrap();
assert_eq!(result.bundle,raw,"No source normalization permitted");
execute_batch(&result.decoded.project,&[]).unwrap(); result
}
fn advance(base:&mut CompiledSourceProject,commands:Vec<Command>) {
let expected=execute_batch(&base.decoded.project,&commands).unwrap();
*base=update_bundle(base,&expected,ProjectLimits::default()).unwrap();
}
#[derive(Clone, Copy)]
struct Keys { children:[Id;3], nodes:[Id;3], allocation:Id }
fn expected(layer:Layer,stage:usize,k:Keys)->CompiledSourceProject {
assert!(stage<=3);
let mut base=bundle(&fixture(layer));
for step in 0..stage {
let p=&base.decoded.project;
let key=k.children[step];
let name=format!("New {}",work(layer).label().to_lowercase());
let element=Element { id:key, alias:p.fresh_alias(&name,"element",key), name, description:String::new(), parent:Some(if step==2 { k.children[0] } else { id(11) }), body:ElementBody::new(work(layer),layer).unwrap() };
let mut commands=vec![Command::CreateElement(element.clone())];
if step==1 {
commands.push(Command::CreateRelation(Relation { id:k.allocation, alias:p.fresh_alias("Performs","relation",k.allocation), name:"Performs".into(), description:String::new(), body:RelationBody::Allocation { source:id(10),target:key } }));
} else {
for original in p.relations.values().filter(|r| [id(20),id(22),id(23)].contains(&r.id)) {
let mut r=original.clone();
match &mut r.body { RelationBody::Allocation{target,..}|RelationBody::RoleAssignment{target,..}=>*target=key,_=>unreachable!() }
commands.push(Command::EditRelation(r.id,r));
}
}
if step==0 {
let mut node=p.diagrams[&id(2)].nodes[&id(41)].clone(); node.collapsed=false;
commands.push(Command::EditNode{diagram:id(2),original:node.id,node});
}
let mut with_element=p.clone(); with_element.elements.insert(key,element);
let (x,y)=[(108.,188.),(108.,298.),(132.,252.)][step];
commands.push(Command::CreateNode { diagram:id(2), node:NodePlacement { id:k.nodes[step], alias:with_element.fresh_alias(&format!("view_{}",with_element.named(key)),"node",k.nodes[step]), element:key,position:Position{x,y},size:Size{width:224.,height:94.},collapsed:false,port_anchors:vec![] } });
if step==2 {
// Grandchild expands first child to bottom370; sibling follows at394
// (24px reflow gap), independently predicted for this fixed fixture.
let mut sibling=p.diagrams[&id(2)].nodes[&k.nodes[1]].clone(); sibling.position.y=394.;
commands.push(Command::EditNode{diagram:id(2),original:sibling.id,node:sibling});
}
advance(&mut base,commands);
}
base
}
fn only(ids:Vec<Id>,role:&str)->Id { assert_eq!(ids.len(),1,"Exactly one {role}"); ids[0] }
fn admit(actual:&Project,layer:Layer,stage:usize)->Keys {
let mut k=Keys{children:[Id::nil();3],nodes:[Id::nil();3],allocation:Id::nil()};
if stage==0 { return k; }
let target=actual.relations[&id(20)].target();
k.children[0]=if stage==3 { actual.elements[&target].parent.unwrap() } else { target };
if stage>=2 {
k.children[1]=only(actual.elements.values().filter(|e|e.parent==Some(id(11))&&e.id!=k.children[0]&&e.kind()==work(layer)).map(|e|e.id).collect(),"second child");
k.allocation=only(actual.relations.values().filter(|r|r.kind()==RelationKind::Allocation&&r.source()==id(10)&&r.target()==k.children[1]).map(|r|r.id).collect(),"new sibling allocation");
}
if stage==3 { k.children[2]=target; }
for step in 0..stage {
let e=&actual.elements[&k.children[step]];
assert_eq!(e.kind(),work(layer)); assert_eq!(e.layer(),layer);
assert_eq!(e.parent,Some(if step==2{k.children[0]}else{id(11)}));
k.nodes[step]=only(actual.diagrams[&id(2)].nodes.values().filter(|n|n.element==e.id).map(|n|n.id).collect(),"child placement");
}
let seed=fixture(layer); let mut used=BTreeSet::new();
for key in k.children[..stage].iter().chain(&k.nodes[..stage]).copied().chain((stage>=2).then_some(k.allocation)) {
assert_eq!(key.get_version_num(),4,"Native fresh UUIDv4 required");
assert!(!seed.contains(key)&&used.insert(key),"Fresh distinct role identity required");
}
k
}
fn check(actual:&CompiledSourceProject,layer:Layer,stage:usize) {
let prediction=expected(layer,stage,admit(&actual.decoded.project,layer,stage));
assert_eq!(actual.decoded.project,prediction.decoded.project,"Complete typed model mismatch, including placements and references");
assert_eq!(actual.bundle,prediction.bundle,"Exact source mismatch, including included note bytes");
}
fn history(actual:&CompiledSourceProject,layer:Layer,stage:usize,first:&CompiledSourceProject,second:Option<&CompiledSourceProject>) {
check(first,layer,1);
let first_keys=admit(&first.decoded.project,layer,1);
let current_keys=admit(&actual.decoded.project,layer,stage);
assert_eq!(current_keys.children[0],first_keys.children[0],"First child identity must match original first-commit carrier");
assert_eq!(current_keys.nodes[0],first_keys.nodes[0],"First placement identity must match original first-commit carrier");
if stage==3 {
let second=second.expect("Original second-commit carrier required");
check(second,layer,2);
history(second,layer,2,first,None);
let second_keys=admit(&second.decoded.project,layer,2);
assert_eq!(current_keys.children[1],second_keys.children[1],"Sibling identity must persist");
assert_eq!(current_keys.nodes[1],second_keys.nodes[1],"Sibling placement identity must persist");
assert_eq!(current_keys.allocation,second_keys.allocation,"Sibling allocation identity must persist");
}
}
fn write_bundle(dir:&Path,raw:&SourceBundle) {
assert!(!dir.exists(),"Use a new evidence directory"); fs::create_dir_all(dir).unwrap();
for (name,bytes) in &raw.files { let path=dir.join(name); if let Some(parent)=path.parent(){fs::create_dir_all(parent).unwrap();} fs::write(path,bytes).unwrap(); }
}
fn main() {
assert_eq!(SCHEMA_VERSION,7);
let args:Vec<_>=std::env::args().collect();
match args.get(1).map(String::as_str) {
Some("generate")=>{assert_eq!(args.len(),3);let dir=Path::new(&args[2]);assert!(!dir.exists()); for (name,layer) in [("oa",Layer::Oa),("sa",Layer::Sa)] {write_bundle(&dir.join(name),&bundle(&fixture(layer)).bundle);} println!("PASS deterministic OA/SA native fixtures generated");}
Some("check")=>{
let layer=match args[2].as_str(){"oa"=>Layer::Oa,"sa"=>Layer::Sa,_=>panic!("oa|sa")};
let stage=args[3].parse::<usize>().unwrap();assert!(stage<=3);
assert_eq!(args.len(),5+stage.saturating_sub(1),"Stages2/3 require original stage1/stage2 checkpoint directories");
let actual=load(Path::new(&args[4]));check(&actual,layer,stage);
if stage>=2 {
let first=load(&Path::new(&args[5]).join("project.arcadia"));
let second=if stage==3 {Some(load(&Path::new(&args[6]).join("project.arcadia")))} else {None};
history(&actual,layer,stage,&first,second.as_ref());
}
println!("PASS complete model, exact source and pinned history stage {stage}");
}
Some("snapshot")=>{assert_eq!(args.len(),4);let actual=load(Path::new(&args[2]));write_bundle(Path::new(&args[3]),&actual.bundle);println!("PASS immutable source checkpoint");}
Some("compare")=>{assert_eq!(args.len(),4);let actual=load(Path::new(&args[2]));let checkpoint=load(&Path::new(&args[3]).join(&actual.bundle.entry));assert_eq!(actual.bundle,checkpoint.bundle,"Saved reachable source bytes changed");assert_eq!(actual.decoded.project,checkpoint.decoded.project);println!("PASS exact checkpoint bytes and model");}
Some("self-check")=>{for layer in [Layer::Oa,Layer::Sa]{let keys=Keys{children:std::array::from_fn(|_|Id::new_v4()),nodes:std::array::from_fn(|_|Id::new_v4()),allocation:Id::new_v4()};for stage in 0..=3 {let candidate=expected(layer,stage,keys);check(&candidate,layer,stage);if stage>=2 {history(&candidate,layer,stage,&expected(layer,1,keys),(stage==3).then(||expected(layer,2,keys)).as_ref());}let mut altered=candidate.decoded.project.clone();altered.elements.get_mut(&id(11)).unwrap().description="Unrequested mutation".into();assert_ne!(expected(layer,stage,admit(&altered,layer,stage)).decoded.project,altered);}}println!("PASS oracle fixed points and unrelated-mutation discriminator");}
_=>panic!("generate DIR | check oa|sa STAGE ENTRY [STAGE1DIR] [STAGE2DIR] | snapshot ENTRY DIR | compare ENTRY DIR | self-check"),
}
}
@@ -0,0 +1,63 @@
# Diagram Delete candidate handoff — 2026-09-12
Frozen, uncommitted implementation on `codex/diagram-delete-956atf-20260912`, isolated worktree `C:\Users\User\Documents\Git\ARCADIA-Studio\.local\diagram-delete-20260912`, HEAD/base `5a70181`. Parent owns issue 15 comment 551, review, Windows verification and integration. No Gitea, Git index/commit, compiler/cargo, native application, WSL or VPN operations performed by this worker. Files are ready for parent review/copy; do not interpret this as verified or complete issue 15.
## Candidate behavior
- Architecture OA/SA and persisted state diagrams: focused canvas Delete hides the selected explicit placement through ordinary `execute(Command::Delete(placement))`; semantic object remains. Shift+Delete opens the existing model-removal dialog. Visible architecture edges/ports and state transitions without explicit placements use confirmed model removal for Delete too.
- Captured `diagram_removal::Intent` carries diagram document/revision/epoch, object and explicit placement. App independently checks clean draft/source/behavior, modal/menu/reference state, selected object/placement, current diagram/page/tool and visible projected membership. Keyboard path never calls `apply()`.
- `diagram/focus.rs` supplies actual Iced Focusable ownership around the architecture/state canvas. It draws the existing behavior viewport style (1 px teal border) while keyboard-focused, without changing layout. It registers for standard focus operations; programmatic focus of any other field unfocuses it. It rejects captured/unfocused/disabled keys and resets at context/window boundaries. The old mouse-only DiagramCanvas.keyboard_focus and StateCanvas.focused gates were removed: the wrapper is the single keyboard authority. Standalone Program tests still exercise already-admitted events.
- Canvas Tab uses ordinary Iced next/previous focus operations. A transient traversal flag rejects subsequent keys in the same native event batch before that task runs, while retaining focus for the operation's traversal count.
- Delete requires selection mode and no active pointer/route/port/pan/work gesture. Existing bend Delete takes priority and a selected invalid bend cannot fall through to object removal. Unsupported modifiers are rejected. Diagram background is never a shortcut target.
- A completed allocation work click retires its epoch before retained canvas state necessarily sees redraw. `diagram.rs` clears only an already-retired local work press before Delete; same-epoch/live work presses remain guarded. This avoids consuming the first Delete merely to send stale WorkDrag::Cancel. `diagram/work_drag.rs` and app/allocation_drag.rs are untouched.
- Model confirmation is captured through existing model_menu::Opened plus selected identity/placement and a unique token. Rendered text uses the captured object. ConfirmDelete now requires the token. Cancel/Escape clear the snapshot and advance the canvas epoch. Old tokens cannot confirm a later dialog; changed document/revision/epoch/page/layer/diagram/object selection or placement refuses the command. Existing pointer/model menu deletion still invokes apply as before, then creates the captured confirmation.
- Existing architecture/state menus gain scope-appropriate Delete/Shift+Delete hints. Diagram background and unsupported state-action rows do not claim a removal shortcut.
## Changed files
New:
- `crates/oa-desktop/src/app/diagram_removal.rs` — intent validation, confirmation lifetime, shared keyboard admission predicate.
- `crates/oa-desktop/src/diagram/focus.rs` — actual Iced Focusable wrapper.
- `crates/oa-desktop/src/app/diagram_removal_tests.rs` — 10 mounted App-tree test functions.
Modified:
- `crates/oa-desktop/src/app.rs` — module/fields/messages, tokenized modal handling and focused delegation hunks.
- `crates/oa-desktop/src/app/behavior_lifecycle_tests.rs` — existing ConfirmDelete constructor updated to token signature.
- `crates/oa-desktop/src/app/state_diagram.rs` — delegates the captured removal event.
- `crates/oa-desktop/src/behavior/state_canvas.rs` — admitted Delete events; removes obsolete private focus boolean.
- `crates/oa-desktop/src/behavior/state_edit.rs` — captured removal event/context.
- `crates/oa-desktop/src/behavior/state_menu.rs` — shortcut hints.
- `crates/oa-desktop/src/behavior/state_view.rs` — focused wrapper.
- `crates/oa-desktop/src/diagram.rs` — admitted Delete, bend/gesture priority, retired work-press cleanup; removes obsolete private focus boolean.
- `crates/oa-desktop/src/model_menu.rs` — shortcut hints.
- `crates/oa-desktop/src/views.rs` — captured confirmation text/token and architecture canvas wrapper only. Allocation toolbar region untouched.
## Authored verification, not executed
Reuses production `behavior::canvas_workspace::tests::Mounted`, real App::view/UserInterface/renderer, retained widget cache, ordered input batches and task/widget-operation draining. Tests never seed canvas private gesture or focus booleans.
1. OA/SA real pointer selection → Delete exact placement; other diagram placement and semantic object retained; source/model agreement and complete one-unit Undo/Redo.
2. Shift+Delete captured target; Cancel, Escape, old-token replay versus a new dialog; intended object removal and Undo source round trip.
3. CLEAN Inspector focus by actual widget operation and canvas Tab; Tab+Delete in one native batch cannot remove model; Shift+Delete cannot reach canvas; Home/Delete edits Name while project/source remain accepted and unchanged.
4. Captured emitted removal intent replay after selection, epoch, owner diagram, document or revision change.
5. Window Unfocused, menu open/close, dirty draft, modal, epoch and unsupported modifier refusal, followed by explicit reacquisition.
6. Real route-pin selection → Delete only bend; source round trip; actual edge segment selection → confirmed semantic deletion.
7. Real state-canvas pointer selection → deletes state placement while architecture placement and state semantic object survive; Undo/source round trip.
8. Captured confirmation refuses changed selection/document/epoch/placement/revision.
9. Programmatic canvas focus without preceding mouse entry → Delete works through the single focus owner.
10. OA/SA Allocation work body click → first Delete without intervening redraw hides exact placement once; semantic work/performer preserved; Undo restores source.
Static checks performed: scoped rustfmt --edition 2024 --config skip_children=true on the 13 owned files; `git diff --check` passes. Formatter exit 0 is only a syntax-formatting check. No compilation or tests were run. Parent should run new `diagram_removal_tests` plus existing state/lifecycle, behavior lifecycle, model-menu, architecture and allocation full-tree tests on the combined integrated candidate.
## Explicit remaining gaps / review risks
- Process and scenario occurrence/link/fragment removal remains unimplemented; do not route their selections through architecture/state context or delete referenced reusable actors/functions. Scenario's modeled Delete participant event is untouched.
- Explorer keyboard removal remains unimplemented; existing Actions/pointer menu remains available.
- State action labels (state-action relation identities represented outside projected edges) remain pointer-menu deletion only. No shortcut hint is claimed for them.
- Mounted tests have not executed. Inspector Tab order, route-segment geometry, state selection hit geometry and the allocation no-redraw case are particularly important concrete checks. No screenshot/native UI acceptance has been done.
- Added tests exercise generated modal state and dispatch actual modal action messages through App; they do not locate/click the rendered confirmation buttons or read rendered glyph text. Parent native QA should confirm target wording and Cancel/Confirm accessibility.
- Tool/gesture admission guards are authored, but dedicated new mounted drag/connection/creation/reconnect and stale-invalid-bend cases are not yet authored. Existing relevant regression tests should be retained and broadened if they expose missing coverage.
- Intent validation compares current selection plus document/context lifetime. Switching selection away and back without any context/revision change is not recorded by a distinct selection-generation counter. Immediate changed-selection replay is covered. Parent should judge whether a stronger input-generation token is required for issue acceptance.
- `delete_pending` boolean remains for compatibility with existing guards/tests; production opening always also creates delete_target. Legacy tests that manually set only the boolean do not create a rendered target dialog, though App modal admission still blocks underlying action messages.
All candidate source files are frozen after this handoff. Further edits require parent follow-up.
@@ -0,0 +1,47 @@
# Allocation label checkpoint review — 2026-09-12
Reviewer: `/root/allocation_checkpoint_review`. Read-only source review of the saved `6b9cc77` allocation change, initially at `94b5eec`; the parent subsequently formatted it at `d9b3f0dc91e8882e6efc262c2e8d971998d2694e`. Read applicable AGENTS/PROJECT_GOAL, the v2 contract, prior repair review, planner, App, rendering and tests. Root owns remote/shared coordination. No compiler, tests, native UI, Gitea or Git/source mutations were performed; this report is the sole write. Findings are source-derived, not runtime observations.
## [P2] Joint-label refusal removes every destination point for an ordinary collapsed-performer drag
Primary location: `crates/oa-desktop/src/allocation_drag.rs:593` (new rejection at 597–602). Related: `app/allocation_drag.rs:98` (label geometry), `:120` (collapsed hit-region height), `:188` (frozen resolver), `:554` (pointer-relative requested placement).
Concrete OA/SA counterexample using `app/allocation_drag_tests.rs:28` fixture:
1. Rename A to `Receiving subsystem` (19 characters), and set its existing placement's `collapsed` flag. Keep A at `(100,100)` with default `224×94` size, Work at `(100,500)` with the same default size, and zoom 1/zero pan. No ports or other content are needed. The default size is defined at `oa-core/src/model.rs:1944`; neither the collapsed projection nor port minimum-size logic expands the width for this name (`projection.rs:314`, `projection/port_layout.rs:131`).
2. Press the work name at `(140,535)`, the normal fixture grab offset `(40,35)` (`app/allocation_drag_tests.rs:95`). Attempt to move/release anywhere in A's entire exposed header.
3. A's frozen targetable rectangle is half-open `[100,324) × [100,162)`. Its frozen label is `[110,308) × [131,153)` (19 characters × 10 + 8 = 198 wide).
4. For **every** pointer in that targetable rectangle, requested work coordinates are `(pointer.x−40,pointer.y−35)`. Grid snapping gives work-header left in `{60,70,…,280}` and top in `{70,80,…,130}`. The header remains `224×62`: the work is a leaf and only its new performer ancestor expands (`oa-core/src/projection.rs:541`).
5. Every such header has left < 308 and right ≥ 284 > 110, plus top ≤ 130 < 153 and bottom ≥ 132 > 131. Thus every position has positive-area overlap with the label and the new check refuses it. Moving below the label as instructed leaves the collapsed hit rectangle; this resolves to OutsidePerformers and cannot allocate/unfold A. Moving beside cannot clear the label while the pointer remains in A for this grab offset.
The attempted assignment is otherwise semantically valid and the candidate can unfold A (`allocation_drag.rs:557`). This makes successful ordinary collapsed-target assignment depend on knowing to restart with a different grab offset or manually expand the target. It contradicts the adopted collapsed-header workflow and makes the refusal's “Aim below or beside” recovery impossible within this held gesture. It is a regression caused by composing the new readability gate with existing frozen target geometry, not a request to weaken collision safety.
The existing collapsed-target resolver test (`app/allocation_drag_tests.rs:758`) checks only the header hit boundary. Planner success tests (`allocation_drag/tests.rs:986`, `:1491`) directly supply a destination and requested position; they do not prove an actual pointer inside a collapsed target can produce that position. They therefore miss this counterexample.
## What the saved fix does establish
- The original `Receiver` counterexample is rejected: selected projected header `(120,110)224×62` intersects the actual frozen `(110,131)88×22` label. Preview and release share `place`, and `finish` repeats it (`allocation_drag.rs:633`). Failure occurs before source execution (`app/allocation_drag.rs:563` onward). Existing model/source/history should consequently remain untouched on this path.
- The new check distinguishes label occlusion from legitimate performer enclosure; it does not remove the ancestor/descendant exemption from general card collision checks. Nearby ordinary expanded-target placement `(120,160)` remains valid by the inspected geometry.
- Existing packet test destinations changed from y140 to y190 while their semantic, identity, source and history assertions remain. This repairs formerly unreadable test inputs; it does not weaken those assertions. The new overlap test retains the old input as an explicit refusal and adds transformed OA/SA, preserved redo, exact nearby placement, semantic-cache reuse and one-step commit/Undo/Redo coverage (`app/allocation_drag_tests.rs:958`).
- The same-performer test preserves a readable snapped no-op and allocation identity (`allocation_drag/tests.rs:1115`). It does not independently cover same-performer occlusion, although that path shares the new check.
## Remedies compared against the actual workflow
The specification should distinguish **frozen hit geometry** from **readable destination identity presentation**. The user's requirements need clear nesting, readable work/destination and exact preview; they do not require a duplicate opaque target name to stay at its old world coordinates. Resolve the source contract before encoding further refusals.
| Candidate | Ordinary drag / frozen target / exact placement / readability | Tradeoff |
| --- | --- | --- |
| **Recommended: retain the frozen target outline; present its identity in a dedicated, reliably visible toolbar/status slot outside the canvas; remove its opaque duplicate name overlay.** | Preserves all destination hit rules and pointer placement, including collapsed targets; removes the overlay collision without moving work or target. | Amend the contract's frozen-label-in-header requirement and corresponding planner context. The identity slot must remain visible at narrow widths and with long names/refusal text; do not rely on arbitrary clipped status prose to preserve the name. Existing toolbar infrastructure at `views.rs:543` provides a starting point. |
| **Bounded alternative proposed by root: use the frozen badge if readable; otherwise use the same target's candidate projected header.** | Preserves frozen hit resolution, exact pointer placement and model geometry. Solves both the Receiver and collapsed long-name counterexamples at the fixture camera. | Store exact chosen badge bounds/text in PlacementPlan and consume those bounds in both admission and renderer; change the old requirement that the badge remain within the frozen accepted header. A toolbar fallback is still needed to guarantee reachability when the candidate header is outside the viewport. |
| Keep an in-canvas name badge but place it in a collision-free viewport location, separately from the frozen hit outline. | Can preserve frozen target resolution and exact work placement while keeping both labels readable. | Requires a deterministic badge-placement policy, explicit relation to its target, and fallback when no space exists. More geometry and crowded-view cases than the toolbar approach; changing badge position must never change target resolution. |
| Offset/pack the work below the frozen label, expand the hit zone, or merely ask the user to expand/regrab. | Packing breaks exact pointer placement; enlarging hidden target area breaks visible frozen resolution; expand/regrab leaves this ordinary valid gesture unsupported. | Reject as the default remedy for this finding. These alter the interaction contract or transfer the failure to users rather than resolving the presentation conflict. |
The candidate-header alternative has a useful source-level invariant: for a direct performer ancestor, candidate target top is at most work top minus 64 (`projection.rs:568`). A badge at target top + 31 with height 22 therefore ends at least 11 units above the work header. The Receiver root y110 gives candidate badge y77–99; the collapsed example roots y70–130 give badge tops y37–97. Both clear the selected header. Indirect ancestors through coherently projected work parents retain additional header separation. Keep the frozen name/size or explicitly derive and store any changed truncation so geometry and actual text do not diverge.
Its unresolved viewport case is concrete: use the same collapsed long-name fixture with pan y−100 so the target starts at the canvas top (world viewport top=100). Every reachable header still intersects the frozen label. Only work roots y100–130 satisfy selected-header viewport containment, while candidate badge tops are y67–97, all above the viewport. Frozen-first/candidate-second therefore still admits no point in the collapsed target for that grab. A named viewport refusal would be truthful, but would retain the reachability limitation; a toolbar destination fallback avoids it without moving the camera or work. This should be an explicit decision and regression, rather than silently claiming the candidate-header fallback solves all valid collapsed drops.
## Regression evidence still needed
A full-tree regression is warranted because the defect is a composition of pointer admission, frozen targets, projection and a separately stacked feedback canvas (`views.rs:462`). Exercise OA and SA with the long-name collapsed target above and the ordinary `(40,35)` grab; require a successful exact-placement assignment/unfold, readable selected work and destination identity, and single-step Undo/Redo. Pair it with the original Receiver geometry and transformed camera. Assert the actual visible presentation appropriate to the chosen remedy, not just planner acceptance or unchanged pixels when unrelated toolbar text varies.
The current full-tree pixel test (`app/allocation_drag_full_tree_tests.rs:252`) proves toolbar isolation by changing only feedback prose. It cannot establish joint label readability or collapsed-target reachability. Minimum-window layout and packaged native acceptance remain root-owned gates; this review alone does not establish them.
@@ -0,0 +1,25 @@
{
"source": "d9b3f0dc91e8882e6efc262c2e8d971998d2694e",
"files": [
{
"path": "full-d9b3f0d.log",
"bytes": 90091,
"sha256": "368c9d12327a6c5df0c8aab3db4fc950a0b6045348bf47ac5aaba5739dd02d00"
},
{
"path": "full-d9b3f0d.inputs.json",
"bytes": 98013,
"sha256": "5183c5000c41bd392733b111131e3b2f6da084bc58e92002cdf5b14e29512f77"
},
{
"path": "full-d9b3f0d.result.json",
"bytes": 385,
"sha256": "92a5dc936a1920da3c787f66c7b1c80e29a85d19a68c64df5528d3ba29205782"
},
{
"path": "allocation-checkpoint-review-20260912.md",
"bytes": 10048,
"sha256": "bcc1a368283ba2e1f9dc798f14f71ffbe530daf27ec88953594a39afa0f8b543"
}
]
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,19 @@
{
"source": "d9b3f0dc91e8882e6efc262c2e8d971998d2694e",
"start": "2026-09-12T11:18:56.702179+00:00",
"end": "2026-09-12T11:26:43.562705+00:00",
"exit": 0,
"command": [
"cargo",
"test",
"--locked",
"-p",
"oa-desktop",
"--bin",
"arcadia-studio",
"--",
"--test-threads=1"
],
"inputs": "full-d9b3f0d.inputs.json",
"changed_inputs": []
}
@@ -0,0 +1,15 @@
# Baseline contract fixtures
Companion to [the candidate contract](../../release-analysis-baseline-contract-20260911.md). This is proposed schema/source/JSON, not implemented Studio syntax.
- active.arcadia.proposed is a complete UUID-bearing local model with four base bindings, two cases and one shared check.
- evaluate-*.json are complete candidate REST request bodies.
- portable-document.json.proposed exposes the complete candidate Project, exact source, local definitions and explicitly empty library collections.
- freeze-degraded.json.proposed retains those exact document bytes, a SHA256 commitment, complete effective bindings/checks, and private definition inventory.
- expected-observations.json records hand-derived arithmetic/context expectations, not evaluator output.
- r7-literal-boundaries.json contains full exact JSON literal nodes and their expected canonical source, including 301-digit and 4096-bit boundaries.
- fixture-integrity.json records only transport/source/UUID checks and size counts.
Run build-fixtures.ps1 with PowerShell 7 to regenerate the JSON fixtures. It writes only within this directory. The script constructs the proposed typed data; it does not parse source, evaluate expressions, run Rust, or establish Project/source semantic equality. Changing the fixture file's exact line endings changes the captured document and digest; preserve these snapshot bytes when publishing.
The full local capture has no imports, so empty pins/package content are complete for this example. Nonempty pinned-package capture and offline replay remain a required paired library/evaluator acceptance test, not something this local transport fixture has proved.
@@ -0,0 +1,55 @@
arcadia 8;
project response_budget "Response budget" id "4210b9f2-7046-47f0-aa3b-153f626a579d" {
description "A complete proposed analysis model. Schema 8 and the new declarations are not implemented source7 syntax.";
quantity_kind duration "Duration" id "188b911c-5f8b-431c-9eea-2d41f3953767" {
dimension { time: 1; }
algebra Linear;
}
unit second "Second" id "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce" {
kind @duration; scale 1; offset 0; symbol "s";
}
unit millisecond "Millisecond" id "39053f37-fec9-4708-9f0a-3959d223f891" {
kind @duration; scale ratio(1, 1000); offset 0; symbol "ms";
}
calculation combine "Combine durations" id "fd7ce7ab-f789-40bc-b699-0c37f1b6902f" {
input a id "28ff40b0-1b8f-4735-8536-5a6ab21b56cb" : Quantity(@duration);
input b id "7a47cc1e-8ae5-4551-b2d8-8a68108e0976" : Quantity(@duration);
result Quantity(@duration);
body $a + $b;
}
oa_activity respond "Respond" id "cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59" {
oa_activity receive "Receive" id "4ab9a8a7-7552-488d-9862-e14b89e7b353" {}
oa_activity dispatch "Dispatch" id "6df991ba-4c5e-4535-99e2-524ae274ee8b" {}
}
oa_property receive_time "Receive time" id "63a931c2-675a-4fce-89e5-04361cb99450" {
subject @receive; type Quantity(@duration); display_unit @millisecond;
base 750 [@millisecond];
}
oa_property dispatch_time "Dispatch time" id "c33fc772-2a60-4044-9af9-73c61c563ace" {
subject @dispatch; type Quantity(@duration); display_unit @second;
base 1 [@second];
}
oa_property total_time "Total time" id "bd5b68e8-65fc-4e35-9071-a73061316a4b" {
subject @respond; type Quantity(@duration); display_unit @second;
// The formula is shared. Every read uses the requested evaluation context.
base @combine(a: @receive_time, b: @dispatch_time);
}
oa_property limit "Allowed duration" id "437bedbb-2cf4-44ee-a139-6563cc5086ec" {
subject @respond; type Quantity(@duration); display_unit @second;
base 2 [@second];
}
oa_check budget "Response budget" id "bac0de99-9d2f-4e53-9158-d424ecac61bf" {
subject none; documented_constraint none;
predicate @total_time <= @limit;
}
oa_analysis degraded "Degraded radio" id "38036c65-16d4-449c-837b-91eb141c1d93" {
subject none; base ModelBaseline;
overrides { @receive_time = 1250 [@millisecond]; }
}
oa_analysis unmeasured "Unmeasured radio" id "99d3e09a-0ec3-4194-9dd4-9f3de6625cde" {
subject none; base ModelBaseline;
overrides { @receive_time = unbound; }
}
}
@@ -0,0 +1,216 @@
# Fixture construction only. This does not parse/evaluate the proposed language.
$ErrorActionPreference = 'Stop'
$taskDir = $PSScriptRoot
$ids = @{
project = '4210b9f2-7046-47f0-aa3b-153f626a579d'
duration = '188b911c-5f8b-431c-9eea-2d41f3953767'
second = '534f4672-1ba5-4157-8b0a-b9cf41d0a3ce'
millisecond = '39053f37-fec9-4708-9f0a-3959d223f891'
combine = 'fd7ce7ab-f789-40bc-b699-0c37f1b6902f'
input_a = '28ff40b0-1b8f-4735-8536-5a6ab21b56cb'
input_b = '7a47cc1e-8ae5-4551-b2d8-8a68108e0976'
respond = 'cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59'
receive = '4ab9a8a7-7552-488d-9862-e14b89e7b353'
dispatch = '6df991ba-4c5e-4535-99e2-524ae274ee8b'
receive_time = '63a931c2-675a-4fce-89e5-04361cb99450'
dispatch_time = 'c33fc772-2a60-4044-9af9-73c61c563ace'
total_time = 'bd5b68e8-65fc-4e35-9071-a73061316a4b'
limit = '437bedbb-2cf4-44ee-a139-6563cc5086ec'
degraded = '38036c65-16d4-449c-837b-91eb141c1d93'
unmeasured = '99d3e09a-0ec3-4194-9dd4-9f3de6625cde'
budget = 'bac0de99-9d2f-4e53-9158-d424ecac61bf'
}
function Exact([string]$n, [string]$d = '1') {
return @{ numerator = $n; denominator = $d }
}
function Local([string]$name) { return @{ Local = $ids[$name] } }
function ReadProperty([string]$name) { return @{ Property = $ids[$name] } }
function Literal([string]$n, [string]$unit) {
return @{ Quantity = @{ magnitude = (Exact $n); unit = (Local $unit) } }
}
function Bound($expr) { return @{ Expression = $expr } }
function Record([string]$key, [string]$name, $body) {
return @{
id = $ids[$key]; alias = $key; name = $name; description = ''; body = $body
}
}
function Element([string]$key, [string]$name, $body, $parent = $null) {
$r = Record $key $name $body
$r.parent = $parent
return $r
}
function Property([string]$key, [string]$name, [string]$subject, [string]$unit, $binding) {
return Element $key $name @{ Oa = @{ Shared = @{ EngineeringProperty = @{
subject = @{ Element = $ids[$subject] }
value_type = $quantityType
display_unit = (Local $unit)
base = $binding
} } } }
}
function OrderedCopy($value) {
if ($null -eq $value) { return $null }
if ($value -is [Collections.IDictionary]) {
$copy = [ordered]@{}
[string[]]$keys = @($value.Keys)
[Array]::Sort($keys, [StringComparer]::Ordinal)
foreach ($key in $keys) { $copy[$key] = OrderedCopy $value[$key] }
return $copy
}
if ($value -is [Collections.IEnumerable] -and $value -isnot [string]) {
$copy = @()
foreach ($item in $value) { $copy += ,(OrderedCopy $item) }
return ,$copy
}
return $value
}
function JsonBytes($value) {
$json = (OrderedCopy $value) | ConvertTo-Json -Depth 100
$json = $json.Replace([string][char]13 + [string][char]10, [string][char]10)
return [Text.UTF8Encoding]::new($false).GetBytes($json + [string][char]10)
}
function SaveBytes([string]$name, [byte[]]$bytes) {
[IO.File]::WriteAllBytes((Join-Path $taskDir $name), $bytes)
}
$quantityType = @{ Scalar = @{ Quantity = (Local 'duration') } }
$definitions = @{}
$definitions[$ids.duration] = Record 'duration' 'Duration' @{ QuantityKind = @{
dimension = @(0, 0, 1, 0, 0, 0, 0); algebra = 'Linear'
} }
$definitions[$ids.second] = Record 'second' 'Second' @{ Unit = @{
kind = (Local 'duration'); scale = (Exact '1'); offset = (Exact '0'); symbol = 's'
} }
$definitions[$ids.millisecond] = Record 'millisecond' 'Millisecond' @{ Unit = @{
kind = (Local 'duration'); scale = (Exact '1' '1000'); offset = (Exact '0'); symbol = 'ms'
} }
$definitions[$ids.combine] = Record 'combine' 'Combine durations' @{ Calculation = @{
parameters = @(
@{ id = $ids.input_a; name = 'a'; value_type = $quantityType },
@{ id = $ids.input_b; name = 'b'; value_type = $quantityType }
)
result = $quantityType
body = (Bound @{ Binary = @{
op = 'Add'; left = @{ Parameter = $ids.input_a }; right = @{ Parameter = $ids.input_b }
} })
} }
$receiveBase = Bound (Literal '750' 'millisecond')
$dispatchBase = Bound (Literal '1' 'second')
$totalBase = Bound @{ Call = @{
definition = (Local 'combine')
arguments = @{
$ids.input_a = (ReadProperty 'receive_time')
$ids.input_b = (ReadProperty 'dispatch_time')
}
} }
$limitBase = Bound (Literal '2' 'second')
$degradedBinding = Bound (Literal '1250' 'millisecond')
$predicate = Bound @{ Binary = @{
op = 'LessOrEqual'; left = (ReadProperty 'total_time'); right = (ReadProperty 'limit')
} }
$elements = @{}
$elements[$ids.respond] = Element 'respond' 'Respond' @{ Oa = 'Activity' }
$elements[$ids.receive] = Element 'receive' 'Receive' @{ Oa = 'Activity' } $ids.respond
$elements[$ids.dispatch] = Element 'dispatch' 'Dispatch' @{ Oa = 'Activity' } $ids.respond
$elements[$ids.receive_time] = Property 'receive_time' 'Receive time' 'receive' 'millisecond' $receiveBase
$elements[$ids.dispatch_time] = Property 'dispatch_time' 'Dispatch time' 'dispatch' 'second' $dispatchBase
$elements[$ids.total_time] = Property 'total_time' 'Total time' 'respond' 'second' $totalBase
$elements[$ids.limit] = Property 'limit' 'Allowed duration' 'respond' 'second' $limitBase
$elements[$ids.budget] = Element 'budget' 'Response budget' @{ Oa = @{ Shared = @{ AnalysisCheck = @{
subject = $null; documented_constraint = $null; predicate = $predicate
} } } }
$elements[$ids.degraded] = Element 'degraded' 'Degraded radio' @{ Oa = @{ Shared = @{ AnalysisCase = @{
subject = $null; base = 'ModelBaseline'; overrides = @{ $ids.receive_time = $degradedBinding }
} } } }
$elements[$ids.unmeasured] = Element 'unmeasured' 'Unmeasured radio' @{ Oa = @{ Shared = @{ AnalysisCase = @{
subject = $null; base = 'ModelBaseline'; overrides = @{ $ids.receive_time = 'Unbound' }
} } } }
$sourceBytes = [IO.File]::ReadAllBytes((Join-Path $taskDir 'active.arcadia.proposed'))
$source = [Text.UTF8Encoding]::new($false, $true).GetString($sourceBytes)
$project = @{
schema_version = 8; id = $ids.project; alias = 'response_budget'; name = 'Response budget'
description = 'A complete proposed analysis model. Schema 8 and the new declarations are not implemented source7 syntax.'
elements = $elements; relations = @{}; diagrams = @{}; artifact_links = @{}; traces = @{}
definitions = $definitions; imports = @{}; definition_mounts = @{}; library_instances = @{}
}
$document = @{
model = $project
source = @{ entry = 'active.arcadia'; files = @{ 'active.arcadia' = $source } }
packages = @{}
}
[byte[]]$documentBytes = JsonBytes $document
SaveBytes 'portable-document.json.proposed' $documentBytes
$documentDigest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($documentBytes)).ToLowerInvariant()
$manifest = @(
@{ property = $ids.receive_time; binding = $degradedBinding; origin = @{ CaseOverride = $ids.degraded } },
@{ property = $ids.dispatch_time; binding = $dispatchBase; origin = 'ModelBaseline' },
@{ property = $ids.total_time; binding = $totalBase; origin = 'ModelBaseline' },
@{ property = $ids.limit; binding = $limitBase; origin = 'ModelBaseline' }
) | Sort-Object { $_.property }
$freeze = @{
format = 'arcadia-analysis-freeze-1-proposal'
captured_document = @{
media_type = 'application/vnd.arcadia.portable-document+json'
sha256 = $documentDigest
bytes_base64 = [Convert]::ToBase64String($documentBytes)
}
origin = @{ Local = @{
document_instance = 'd911a3c0-8adb-4203-850c-b16e9b4e4d0a'; accepted_revision = 1
} }
model_id = $ids.project
context = @{ Case = $ids.degraded }
targets = @{ properties = @($ids.total_time); checks = @($ids.budget) }
numeric_profile = 'Q1-exact-1'
effective_bindings = @($manifest)
check_predicates = @(@{ check = $ids.budget; predicate = $predicate })
definition_capture = @{
document_sha256 = $documentDigest
local_definitions = @($ids.duration, $ids.second, $ids.millisecond, $ids.combine | Sort-Object)
imports = @()
}
}
SaveBytes 'freeze-degraded.json.proposed' (JsonBytes $freeze)
$expected = @{
status = 'Hand-derived expectations, not evaluator output'
baseline = @{ total_canonical_seconds = (Exact '7' '4'); check = 'Satisfied' }
degraded = @{ total_canonical_seconds = (Exact '9' '4'); check = 'Violated' }
unmeasured = @{ total = 'Missing'; input = $ids.receive_time; check = 'Unresolved' }
after_clear_unmeasured_override = @{ total_canonical_seconds = (Exact '7' '4'); check = 'Satisfied' }
after_baseline_dispatch_changes_to_two_seconds = @{
active_degraded_total = (Exact '13' '4'); frozen_degraded_total = (Exact '9' '4')
}
}
SaveBytes 'expected-observations.json' (JsonBytes $expected)
$largeInteger = [Numerics.BigInteger]::Pow([Numerics.BigInteger]10, 300).ToString()
$smallDenominator = [Numerics.BigInteger]::Pow([Numerics.BigInteger]2, 4095).ToString()
$boundInteger = ([Numerics.BigInteger]::Pow([Numerics.BigInteger]2, 4096) - 1).ToString()
$literalFixtures = @(
@{ name = 'ten_to_300'; expression = @{ Number = (Exact $largeInteger) }; canonical_source = $largeInteger },
@{ name = 'one_over_two_to_4095'; expression = @{ Number = (Exact '1' $smallDenominator) }; canonical_source = ('ratio(1, ' + $smallDenominator + ')') },
@{ name = 'negative_4096_bit_bound'; expression = @{ Number = (Exact ('-' + $boundInteger)) }; canonical_source = ('ratio(-' + $boundInteger + ', 1)') }
)
SaveBytes 'r7-literal-boundaries.json' (JsonBytes $literalFixtures)
# Verify only JSON transport, UUID completeness, raw source retention and hashes.
$parsed = Get-Content -LiteralPath (Join-Path $taskDir 'freeze-degraded.json.proposed') -Raw | ConvertFrom-Json
$decoded = [Convert]::FromBase64String($parsed.captured_document.bytes_base64)
if ([Convert]::ToBase64String($decoded) -cne [Convert]::ToBase64String($documentBytes)) { throw 'Document capsule differs' }
$parsedDoc = [Text.Encoding]::UTF8.GetString($decoded) | ConvertFrom-Json
if ($parsedDoc.source.files.'active.arcadia' -cne $source) { throw 'Source changed' }
if ($ids.Count -ne (@($ids.Values | Sort-Object -Unique)).Count) { throw 'Duplicate fixture UUID' }
foreach ($value in $ids.Values) {
[void][guid]::ParseExact($value, 'D')
if (-not $source.Contains('id "' + $value + '"')) { throw "Missing source identity $value" }
}
$stats = @{
source_lines = ($source -split [string][char]10).Count - 1
source_utf8_bytes = $sourceBytes.Length
explicit_source_uuids = $ids.Count
project_elements = $elements.Count
local_definitions = $definitions.Count
scoped_parameters = 2
base_bindings = 4
override_bindings = 2
shared_checks = 1
portable_document_sha256 = $documentDigest
verified = 'JSON transport, 17 syntactically valid distinct UUIDs, exact source bytes, capsule equality. No proposed parser/evaluator execution.'
}
SaveBytes 'fixture-integrity.json' (JsonBytes $stats)
$stats | ConvertTo-Json

Some files were not shown because too many files have changed in this diff Show More