Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ea7518e7b | ||
|
|
f1fdca3713 | ||
|
|
ea23e22926 | ||
|
|
6e7c4ddaf0 | ||
|
|
5657a996ed | ||
|
|
f83068757a | ||
|
|
e0812b3932 | ||
|
|
715036e132 | ||
|
|
a9cd364eac | ||
|
|
8ddfadf440 | ||
|
|
897d9f0494 | ||
|
|
4deced53b9 | ||
|
|
9e99618cc3 | ||
|
|
a6b9f6029a | ||
|
|
a8c959fed4 | ||
|
|
359bea3949 | ||
|
|
17eaa03fd6 | ||
|
|
6ae75fb2cc | ||
|
|
542b10ac58 | ||
|
|
62d3ffe9cb | ||
|
|
c1b78acb9a | ||
|
|
3e916f623c | ||
|
|
e9167f5cc8 | ||
|
|
495464e84b | ||
|
|
1006b496ae | ||
|
|
16b30a6760 | ||
|
|
33e880103c | ||
|
|
a2a326f183 | ||
|
|
eed80ffd6e | ||
|
|
9b83f7ca0d | ||
|
|
8dbbaf262e | ||
|
|
3a7923b96d | ||
|
|
6d99aacab8 | ||
|
|
b743a10d51 | ||
|
|
ff712b2419 | ||
|
|
e34ba27e26 | ||
|
|
b15345123a | ||
|
|
1711bff650 | ||
|
|
bed7f825fd | ||
|
|
3480b54201 | ||
|
|
2a3b9ba822 | ||
|
|
301126f609 | ||
|
|
7e348d967d | ||
|
|
f6a6010bae | ||
|
|
f82e29d6b8 | ||
|
|
c4897485b7 | ||
|
|
12a7352dde | ||
|
|
015273ac8a | ||
|
|
5e04800be1 | ||
|
|
cf37c36be1 | ||
|
|
f3dd8356bf | ||
|
|
846cae81e7 | ||
|
|
2a0579daaf | ||
|
|
ffa7b16003 | ||
|
|
a9b9c81eab | ||
|
|
0b61771d07 | ||
|
|
6f4dfc67b3 | ||
|
|
5960563b23 | ||
|
|
df4256cb2b | ||
|
|
1d56386708 | ||
|
|
c87a0c2bd9 | ||
|
|
cc3d6a4875 | ||
|
|
6a6cc83bc8 | ||
|
|
9f88938632 | ||
|
|
17f1f89fef | ||
|
|
4fbdf6f385 | ||
|
|
bfc259854f | ||
|
|
b8685416f5 | ||
|
|
26979c1093 | ||
|
|
4ffff0d9d9 | ||
|
|
836f9e14e7 | ||
|
|
031c4dbdbb | ||
|
|
b278866e8c | ||
|
|
3733a657bb | ||
|
|
84434d55a0 | ||
|
|
f95d031048 | ||
|
|
8abc144cf2 | ||
|
|
9e51cd72ba | ||
|
|
3c22fe2629 | ||
|
|
cccd66c5d5 | ||
|
|
355f6d4d24 |
@@ -4,12 +4,12 @@
|
||||
|
||||
- Follow `PROJECT_GOAL.md` and the user's current instructions. Work autonomously within scope. Resolve discoverable questions yourself; record, test, and revise reversible assumptions. Ask only when a consequential decision needs information or authorization not already available. Continue independent useful work while blocked elsewhere.
|
||||
- Map unfamiliar domains through primary sources, comparable systems, and real user workflows. Identify underlying needs, valuable concepts, and avoidable friction; evaluate improvements rather than merely reproducing features. Synthesize findings into decisions or experiments, and stop research when another action offers greater value.
|
||||
- Make specifications precise enough for compatible independent implementations: definitions, relationships, invariants, valid/invalid examples, and lifecycle or transformation rules where relevant. Trace important requirements and decisions to implementation and verification. Resolve specification ambiguity at its source when implementation exposes it.
|
||||
- Make specifications precise enough for compatible independent implementations: definitions, relationships, invariants, valid / invalid examples, and lifecycle or transformation rules where relevant. Trace important requirements and decisions to implementation and verification. Resolve specification ambiguity at its source when implementation exposes it.
|
||||
- For consequential uncertain choices, compare materially different candidates against explicit user-derived criteria. Ask independent critics to challenge assumptions and attempt to falsify proposals; refine or replace candidates as evidence warrants. Record the choice, evidence, tradeoffs, rejected approaches, and reasons to revisit it. Use proportionate effort for reversible local choices.
|
||||
- Plan milestones that resolve uncertainty or deliver useful capability, with explicit dependencies. Test foundational assumptions before substantial downstream work. At checkpoints, assess progress toward the actual objective and replan when evidence invalidates the strategy or progress stalls.
|
||||
- Define observable success and suitable evaluators before repeated improvement: invariants, examples, round trips, transformations, performance checks, realistic user tasks, or explicit review rubrics. Ensure the evaluator measures the intended outcome. For experiments, record the question, expectations, method, result, and implications; isolate exploratory prototypes from production architecture.
|
||||
- Build and run meaningful changes, exercise actual behavior, and inspect useful logs. Investigate crashes, serious warnings, corrupted state, and interaction defects. For GUI work, use Computer Use or equivalent tools to inspect realistic workflows, cognitive load, editing/selection, navigation, feedback, recovery, loading/empty/failure states, accessibility, layout, focus/disabled states, and responsiveness.
|
||||
- Match independent reviews to the artifact and risks. For languages or formats, include ambiguity, round trips, human/AI editability, and version-control behavior where relevant. Verify findings, fix the appropriate conceptual, specification, architectural, implementation, or interaction layer, and recheck affected dependents. Reuse valid evidence; repeat checks for concrete risks, changes, findings, or required gates. Compilation, screenshots, and worker reports alone do not establish correctness or usability.
|
||||
- Build and run meaningful changes, exercise actual behavior, and inspect useful logs. Investigate crashes, serious warnings, corrupted state, and interaction defects. For GUI work, use Computer Use or equivalent tools to inspect realistic workflows, cognitive load, editing / selection, navigation, feedback, recovery, loading / empty / failure states, accessibility, layout, focus / disabled states, and responsiveness.
|
||||
- Match independent reviews to the artifact and risks. For languages or formats, include ambiguity, round trips, human / AI editability, and version-control behavior where relevant. Verify findings, fix the appropriate conceptual, specification, architectural, implementation, or interaction layer, and recheck affected dependents. Reuse valid evidence; repeat checks for concrete risks, changes, findings, or required gates. Compilation, screenshots, and worker reports alone do not establish correctness or usability.
|
||||
- Favor the simplest maintainable design satisfying known requirements and justified extensibility. Avoid speculative abstraction, unrelated refactoring, and repeating approaches already invalidated by evidence.
|
||||
|
||||
## User input
|
||||
@@ -24,10 +24,10 @@ Keep one authoritative home for each kind of information. Use links and brief sc
|
||||
|
||||
| Information | Authoritative home |
|
||||
| --- | --- |
|
||||
| Live plans, priorities, dependencies, ownership, status, blockers, and handoffs | Gitea issues/milestones; linked PRs hold change review and validation. |
|
||||
| Specifications, architecture, interfaces, and build/run documentation | Established version-controlled project documents. |
|
||||
| Live plans, priorities, dependencies, ownership, status, blockers, and handoffs | Gitea issues / milestones; linked PRs hold change review and validation. |
|
||||
| Specifications, architecture, interfaces, and build / run documentation | Established version-controlled project documents. |
|
||||
| Durable decisions and reusable evidence | `harness/DECISIONS.md` and relevant topic notes, or existing equivalents. |
|
||||
| Navigation and integrated-state checkpoint | `harness/STATE.md`: links, verified code commit/release, capabilities, and material limitations. No live task ledger. |
|
||||
| Navigation and integrated-state checkpoint | `harness/STATE.md`: links, verified code commit / release, capabilities, and material limitations. No live task ledger. |
|
||||
| Shared entrypoint | Gitea Wiki: overview and links, without duplicating versioned documentation. |
|
||||
| Published deliverables | Gitea releases, tied to source commits and verification. |
|
||||
|
||||
@@ -38,9 +38,9 @@ Use Gitea for live coordination and the relevant code version for implementation
|
||||
All independent agents coordinating through Gitea run on completely separate machines, each with its own clone, filesystem, tools, processes, and runtime. Gitea and pushed Git history are the shared communication and delivery channels. Local files (including `harness`), unpushed commits, worktrees, test results, and localhost services are not accessible to peers. Matching branch names or paths do not imply synchronized contents.
|
||||
|
||||
1. On starting or resuming, including after compaction, inspect the working branch, local changes, applicable instructions, relevant shared records, and existing implementation. Recover context from authoritative records. Check for newer shared instructions on the actual remote default branch without overwriting local work. Read what is relevant; avoid repeated full-history scans and constant polling.
|
||||
2. Search before creating tasks. Claim a meaningful outcome in its Gitea issue with a stable session identity, scope, remote repository/branch, and acceptance criteria. Keep small steps within that task. Recheck after claiming; comments are not atomic locks. Respect existing ownership and resolve overlapping claims before overlapping work.
|
||||
3. Independent sessions are peers. Each owns its contribution and delegated work on its own machine. Record one integration/release owner when a milestone needs shared coordination. Use distinct remote work branches, partition files/interfaces, and coordinate changes to shared specifications and documents. Worktrees provide local isolation only; they do not share work between machines.
|
||||
4. At meaningful checkpoints or handoffs, record changed results, commit/PR links, verification commands and environment, blockers, and next actions. Identify the tested code version and label uncommitted or unpublished work as local-only. Before asking peers to consume results, push the required code and versioned documentation, including relevant `harness` updates; publish other required artifacts in Gitea and link them. Use repository-relative paths with commit references, reproducible commands, and necessary environment details; local paths and localhost URLs alone are not handoffs. Do not assume another agent is running or has read a message; silence alone does not establish abandonment. Record evidence and preserve existing work when reassigning a task.
|
||||
2. Search before creating tasks. Claim a meaningful outcome in its Gitea issue with a stable session identity, scope, remote repository / branch, and acceptance criteria. Keep small steps within that task. Recheck after claiming; comments are not atomic locks. Respect existing ownership and resolve overlapping claims before overlapping work.
|
||||
3. Independent sessions are peers. Each owns its contribution and delegated work on its own machine. Record one integration / release owner when a milestone needs shared coordination. Use distinct remote work branches, partition files / interfaces, and coordinate changes to shared specifications and documents. Worktrees provide local isolation only; they do not share work between machines.
|
||||
4. At meaningful checkpoints or handoffs, record changed results, commit / PR links, verification commands and environment, blockers, and next actions. Identify the tested code version and label uncommitted or unpublished work as local-only. Before asking peers to consume results, push the required code and versioned documentation, including relevant `harness` updates; publish other required artifacts in Gitea and link them. Use repository-relative paths with commit references, reproducible commands, and necessary environment details; local paths and localhost URLs alone are not handoffs. Do not assume another agent is running or has read a message; silence alone does not establish abandonment. Record evidence and preserve existing work when reassigning a task.
|
||||
5. Follow project review and merge conventions. Fetch the relevant remote branches and inspect the identified commits before reviewing or integrating another machine's work. Resolve conflicts while preserving others' edits, and verify the combined result locally; report material environment differences. Local instruction-file edits reach peers only after publication and retrieval. Do not overwrite others' work or force-push shared history to resolve coordination problems.
|
||||
6. Close work when its acceptance criteria are met and the result is integrated or delivered as appropriate. Mark duplicates and superseded tasks explicitly with replacement links. Then choose further useful unowned work while the requested objective remains incomplete.
|
||||
|
||||
@@ -64,10 +64,10 @@ Preserve concise records of decisions and rationale, useful experiments, failed
|
||||
|
||||
Consolidate duplicates, repair stale guidance, and remove obsolete temporary files alongside useful project work. Before removing material, check references, active ownership, and ongoing use; preserve unique knowledge and update affected links. Prefer closing, superseding, or archiving history over deletion. User input is excluded from autonomous cleanup.
|
||||
|
||||
If legacy local task ledgers or plans duplicate Gitea, migrate their live content once into existing or appropriately scoped issues, preserve useful decisions/evidence, and mark the old records superseded. Record the migration so later sessions do not repeat it. Do not create empty documents or maintain records for ceremony.
|
||||
If legacy local task ledgers or plans duplicate Gitea, migrate their live content once into existing or appropriately scoped issues, preserve useful decisions / evidence, and mark the old records superseded. Record the migration so later sessions do not repeat it. Do not create empty documents or maintain records for ceremony.
|
||||
|
||||
## Delivery
|
||||
|
||||
Publish versioned Gitea releases at meaningful working milestones; mark unfinished versions as prereleases. Check existing releases/tags and coordinate one owner and version before publishing. Build from an identified integrated commit and verify the packaged result and launch steps.
|
||||
Publish versioned Gitea releases at meaningful working milestones; mark unfinished versions as prereleases. Check existing releases / tags and coordinate one owner and version before publishing. Build from an identified integrated commit and verify the packaged result and launch steps.
|
||||
|
||||
Include runnable builds or appropriate artifacts, concise release notes, build/run/deployment instructions as applicable, known limitations, tested platforms, and verification evidence. Confirm publication and artifact availability. Use existing authorized API access or project tooling when MCP lacks a needed release/upload operation. Do not silently replace published versions with different contents.
|
||||
Include runnable builds or appropriate artifacts, concise release notes, build / run / deployment instructions as applicable, known limitations, tested platforms, and verification evidence. Confirm publication and artifact availability. Use existing authorized API access or project tooling when MCP lacks a needed release / upload operation. Do not silently replace published versions with different contents.
|
||||
|
||||
+2
-2
@@ -17,14 +17,14 @@ Apply these criteria to the scope requested by the user:
|
||||
- Consequential decisions have evidence and rationale. Major assumptions have been validated, explicitly accepted, or isolated without compromising required behavior.
|
||||
- The result builds, runs, and operates on the required platforms. Relevant tests and evaluators pass; integrations, edge cases, and failure states have been exercised against the actual result.
|
||||
- User-facing behavior and usability have been exercised directly, using representative data and workflows.
|
||||
- A fresh independent review covers requirements, domain/semantic consistency, usability, architecture, correctness, regressions, runtime behavior, documentation, and remaining risks. Valid material findings are addressed, blocking and high-impact issues resolved, and affected behavior reverified; no known blocker or high-severity defect remains.
|
||||
- A fresh independent review covers requirements, domain / semantic consistency, usability, architecture, correctness, regressions, runtime behavior, documentation, and remaining risks. Valid material findings are addressed, blocking and high-impact issues resolved, and affected behavior reverified; no known blocker or high-severity defect remains.
|
||||
- Deliverables are maintainable, appropriately extensible, documented, and published as required by `AGENTS.md`. Obsolete scaffolding is removed; documentation and shared state accurately describe the result. Another engineer or agent can reproduce the verification and continue the work.
|
||||
|
||||
If required work or verification is blocked, record the specific gap and continue independent useful work without claiming completion.
|
||||
|
||||
## Final handoff
|
||||
|
||||
Link the delivered result and summarize capabilities, discoveries, architecture and decisions, relevant rejected approaches, verification and independent review, remaining limitations, and exact build/run/deployment/verification instructions. Refer to authoritative records instead of repeating the project history.
|
||||
Link the delivered result and summarize capabilities, discoveries, architecture and decisions, relevant rejected approaches, verification and independent review, remaining limitations, and exact build / run / deployment / verification instructions. Refer to authoritative records instead of repeating the project history.
|
||||
|
||||
## USER-OWNED APPLICATION SPECIFICATION
|
||||
|
||||
|
||||
@@ -94,11 +94,13 @@ Create named **Exchange categories** at the perspective root to group Work excha
|
||||
|
||||
In **Select / move**, drag cards on a 10-unit grid, drag empty space to pan, and scroll to zoom. Drag ports along their owner's border or onto any of its four sides. Automatic sides account for direction and visible connections. Manual positions are per diagram and remain relative to the owner through movement or resize; right-click **Reset automatic position** restores automatic placement. **Arrange** changes the current view layout; **Fit** frames its projected bounds. SVG exports the current architecture diagram as a view, not an editable model file.
|
||||
|
||||
In saved architecture and State views, **Shift+click** adds or removes an exact displayed item; its context menu also offers **Add to selection** and **Remove from selection**. Properties edits only the primary item. Drag a selected member to move a placement-only group in one operation, including visual descendants once and the authored pins of connections whose endpoint owners move together. A stationary click selects only that member; Escape during a drag cancels it and keeps the group. **Hide selected** removes only selected placements, preserving model elements, unselected descendant placements and other views; one Undo restores the operation. Groups containing connections, ports or State action/internal-transition rows cannot be moved or hidden as placement groups. State rows select their relation, never their owning placement. Dragging a group of allocated work cards and deleting a group from the model remain unavailable; these actions refuse the whole group instead of editing just its primary item. Selection itself is temporary and is not saved.
|
||||
|
||||
Connections start with orthogonal routes that avoid cards and container headers. In Select mode, select a connection and drag a segment to add a bend, or right-click for **Add bend here**. Drag its circles to adjust the route; the menu offers **Remove bend** and **Reset routing**. With the canvas focused, Insert adds a bend and Delete removes the selected bend. Shift+F10 opens the selected item's menu; **Actions** in Properties provides the same commands. Drag the connection label independently. Each completed gesture is one undoable edit; Escape cancels a drag. Routes belong to the current diagram and persist in source, JSON, REST and SVG export. Folding an endpoint container temporarily uses an automatic route; expanding it restores your authored route. Dense diagrams can still need manual adjustment; automatic routing is bounded and does not guarantee an overlap-free result.
|
||||
|
||||
For state diagrams, use **+ Region** inside a highlighted machine or State/Mode, then choose **+ State / symbol** and click its owning region. **Transition** supports dragging between compatible vertices or clicking the source and then the target. Select a drawn transition and drag its endpoint handle, or right-click **Reconnect source/target**. Right-click a state or the background for **New transition with details…** to create Local, Internal or timed transitions; an existing transition's **Edit transition** form edits its kind, triggers, guard and effects. EntryPoint outgoing transitions use Local.
|
||||
|
||||
In the state view, **Select / move** drags vertices and containers without reparenting; container movement includes its descendants. Middle-button drag pans, scroll or **−/+** zooms, and **Fit** frames the view. Right-click for **Fold contents**, **Unfold contents**, **Placement properties**, or **Hide from this diagram**. The **Show an element not yet in this view…** selector restores missing placements. Escape cancels a gesture; **Undo** restores a completed edit. **+ View** creates an independent layout. The persisted diagram's machine reference and placements are the same records in source, JSON and REST; opening the page alone creates no diagram.
|
||||
In the state view, **Select / move** drags vertices and containers without reparenting or grid snapping; container movement includes its descendants. Multiple selected placements share the same fractional displacement, including authored positions of boundary symbols. State route bends retain their separate 5-unit grid. Middle-button drag pans, scroll or **−/+** zooms, and **Fit** frames the view. Right-click for **Fold contents**, **Unfold contents**, **Placement properties**, or **Hide from this diagram**. The **Show an element not yet in this view…** selector restores missing placements. Escape cancels a gesture; **Undo** restores a completed edit. **+ View** creates an independent layout. The persisted diagram's machine reference and placements are the same records in source, JSON and REST; opening the page alone creates no diagram.
|
||||
|
||||
## Edit the same model as text
|
||||
|
||||
|
||||
@@ -0,0 +1,768 @@
|
||||
//! Deterministic native fixture and literal complete-Project Allocation oracle.
|
||||
//! No desktop planner, inferred output delta, or GUI input is used by this oracle.
|
||||
use oa_core::{source_project::*, *};
|
||||
use std::{collections::BTreeMap, fs, io::Write, path::Path};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
const MODES: [&str; 6] = [
|
||||
"unchanged",
|
||||
"oa-assigned",
|
||||
"sa-assigned",
|
||||
"oa-arranged",
|
||||
"sa-arranged",
|
||||
"oa-performers",
|
||||
];
|
||||
|
||||
fn id(alias: &str) -> Id {
|
||||
if alias == "oa_assign" {
|
||||
return Id::from_u128(0x292609230001);
|
||||
}
|
||||
Id::new_v5(
|
||||
&Id::from_u128(0xc1192026_0923_5000_8000_000000002931),
|
||||
alias.as_bytes(),
|
||||
)
|
||||
}
|
||||
fn xy(x: f32, y: f32) -> Position {
|
||||
Position { x, y }
|
||||
}
|
||||
fn named(scope: &str, suffix: &str) -> String {
|
||||
format!("{scope}_{suffix}")
|
||||
}
|
||||
fn need(ok: bool, message: impl Into<String>) -> Result<()> {
|
||||
if ok {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(message.into().into())
|
||||
}
|
||||
}
|
||||
fn element(p: &mut Project, alias: &str, name: &str, kind: Kind, layer: Layer) {
|
||||
p.elements.insert(
|
||||
id(alias),
|
||||
Element {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: format!("Preserve engineering record {alias}."),
|
||||
parent: None,
|
||||
body: ElementBody::new(kind, layer).unwrap(),
|
||||
},
|
||||
);
|
||||
}
|
||||
fn diagram(p: &mut Project, alias: &str, name: &str, layer: Layer, projection: ProjectionKind) {
|
||||
p.diagrams.insert(
|
||||
id(alias),
|
||||
Diagram {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: "Native group fixture; preserve unrelated records exactly.".into(),
|
||||
layer,
|
||||
projection,
|
||||
layout: None,
|
||||
view_options: Default::default(),
|
||||
nodes: Default::default(),
|
||||
routes: vec![],
|
||||
},
|
||||
);
|
||||
}
|
||||
fn place(p: &mut Project, scope: &str, suffix: &str, position: Position) {
|
||||
let alias = named(scope, &format!("node_{suffix}"));
|
||||
p.diagrams.get_mut(&id(scope)).unwrap().nodes.insert(
|
||||
id(&alias),
|
||||
NodePlacement {
|
||||
id: id(&alias),
|
||||
alias,
|
||||
element: id(&named(scope, suffix)),
|
||||
position,
|
||||
size: Size {
|
||||
width: 224.,
|
||||
height: 94.,
|
||||
},
|
||||
collapsed: false,
|
||||
port_anchors: vec![],
|
||||
},
|
||||
);
|
||||
}
|
||||
fn relation(
|
||||
p: &mut Project,
|
||||
scope: &str,
|
||||
suffix: &str,
|
||||
kind: RelationKind,
|
||||
from: &str,
|
||||
to: &str,
|
||||
) -> Result<()> {
|
||||
let alias = named(scope, suffix);
|
||||
let old = p.relate(
|
||||
kind,
|
||||
&format!("{scope} {suffix}"),
|
||||
id(&named(scope, from)),
|
||||
id(&named(scope, to)),
|
||||
);
|
||||
reidentify(p, old, id(&alias))?;
|
||||
let r = p.relations.get_mut(&id(&alias)).unwrap();
|
||||
r.alias = alias.clone();
|
||||
r.description = format!("Reviewed identity and provenance {alias} must survive.");
|
||||
// The actual constructor creates proper SA function contracts. Normalize
|
||||
// every generated identity/alias; no random UUID can leak into the fixture.
|
||||
let ports = match r.body {
|
||||
RelationBody::FunctionalExchange {
|
||||
source_port,
|
||||
target_port,
|
||||
..
|
||||
} => Some([source_port, target_port]),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(ports) = ports {
|
||||
for (old_port, suffix) in ports.into_iter().zip(["output", "input"]) {
|
||||
let alias = format!("{alias}_{suffix}");
|
||||
reidentify(p, old_port, id(&alias))?;
|
||||
let port = p.elements.get_mut(&id(&alias)).unwrap();
|
||||
port.alias = alias.clone();
|
||||
port.name = format!("{scope} {suffix}");
|
||||
port.description = format!("Preserved typed endpoint {alias}.");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn route(scope: &str, pins: [Position; 2]) -> EdgeRoute {
|
||||
EdgeRoute {
|
||||
edge: id(&named(scope, "exchange")),
|
||||
waypoints: pins.to_vec(),
|
||||
source_attachment: None,
|
||||
target_attachment: None,
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.45,
|
||||
offset: xy(7., -19.),
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn fixture() -> Result<Project> {
|
||||
let mut p = Project::empty();
|
||||
p.id = id("project");
|
||||
p.alias = "allocation_multiselect_native".into();
|
||||
p.name = "Allocation group native".into();
|
||||
p.description = "Four independent compact OA/SA assignment and Arrange trials; ordinary performers use fresh OA assign baseline.".into();
|
||||
for (layer, prefix, work, performer) in [
|
||||
(Layer::Oa, "oa", Kind::Activity, Kind::Entity),
|
||||
(Layer::Sa, "sa", Kind::Function, Kind::SystemActor),
|
||||
] {
|
||||
for arrange in [false, true] {
|
||||
let scope = format!("{prefix}_{}", if arrange { "arrange" } else { "assign" });
|
||||
let number = match (prefix, arrange) {
|
||||
("oa", false) => "01",
|
||||
("sa", false) => "02",
|
||||
("oa", true) => "03",
|
||||
_ => "04",
|
||||
};
|
||||
diagram(
|
||||
&mut p,
|
||||
&scope,
|
||||
&format!(
|
||||
"{number} {} {}",
|
||||
prefix.to_uppercase(),
|
||||
if arrange { "arrange" } else { "assign" }
|
||||
),
|
||||
layer,
|
||||
ProjectionKind::Allocation,
|
||||
);
|
||||
let records: Vec<_> = if arrange {
|
||||
vec![
|
||||
("p", "P - team", performer, xy(40., 40.)),
|
||||
("u", "U - contained work", work, xy(80., 140.)),
|
||||
("v", "V - independent work", work, xy(440., 140.)),
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
("a", "A - origin team", performer, xy(43., 47.)),
|
||||
// Leave room for SA Y's automatic top port stub below
|
||||
// B's 64-unit header plus 12-unit routing clearance.
|
||||
("b", "B - other team", performer, xy(43., 337.)),
|
||||
("c", "C - destination", performer, xy(500., 40.)),
|
||||
("x", "X - receive", work, xy(80., 140.)),
|
||||
("y", "Y - assess", work, xy(80., 440.)),
|
||||
]
|
||||
};
|
||||
for (suffix, label, kind, pos) in records {
|
||||
// SA admits one System for the entire project, not one per view.
|
||||
let kind = if layer == Layer::Sa && !arrange && suffix == "a" {
|
||||
Kind::System
|
||||
} else {
|
||||
kind
|
||||
};
|
||||
element(&mut p, &named(&scope, suffix), label, kind, layer);
|
||||
place(&mut p, &scope, suffix, pos);
|
||||
}
|
||||
let (from, to, pins) = if arrange {
|
||||
relation(&mut p, &scope, "pu", RelationKind::Allocation, "p", "u")?;
|
||||
("u", "v", [xy(360., 180.), xy(360., 230.)])
|
||||
} else {
|
||||
p.diagrams
|
||||
.get_mut(&id(&scope))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id(&named(&scope, "node_c")))
|
||||
.unwrap()
|
||||
.size = Size {
|
||||
width: 360.,
|
||||
height: 600.,
|
||||
};
|
||||
relation(&mut p, &scope, "ax", RelationKind::Allocation, "a", "x")?;
|
||||
relation(&mut p, &scope, "by", RelationKind::Allocation, "b", "y")?;
|
||||
("x", "y", [xy(340., 260.), xy(340., 400.)])
|
||||
};
|
||||
relation(
|
||||
&mut p,
|
||||
&scope,
|
||||
"exchange",
|
||||
if layer == Layer::Oa {
|
||||
RelationKind::Interaction
|
||||
} else {
|
||||
RelationKind::FunctionalExchange
|
||||
},
|
||||
from,
|
||||
to,
|
||||
)?;
|
||||
p.diagrams
|
||||
.get_mut(&id(&scope))
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(route(&scope, pins));
|
||||
}
|
||||
}
|
||||
diagram(
|
||||
&mut p,
|
||||
"other_view",
|
||||
"05 Other saved view - preserve",
|
||||
Layer::Oa,
|
||||
ProjectionKind::Overview,
|
||||
);
|
||||
for (suffix, pos) in [("x", xy(40., 60.)), ("y", xy(410., 180.))] {
|
||||
let alias = named("other_view", suffix);
|
||||
p.diagrams.get_mut(&id("other_view")).unwrap().nodes.insert(
|
||||
id(&alias),
|
||||
NodePlacement {
|
||||
id: id(&alias),
|
||||
alias,
|
||||
element: id(&named("oa_assign", suffix)),
|
||||
position: pos,
|
||||
size: Size {
|
||||
width: 224.,
|
||||
height: 94.,
|
||||
},
|
||||
collapsed: false,
|
||||
port_anchors: vec![],
|
||||
},
|
||||
);
|
||||
}
|
||||
validate_candidate(&p)?;
|
||||
Ok(p)
|
||||
}
|
||||
fn node_mut<'a>(p: &'a mut Project, scope: &str, suffix: &str) -> &'a mut NodePlacement {
|
||||
p.diagrams
|
||||
.get_mut(&id(scope))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id(&named(scope, &format!("node_{suffix}"))))
|
||||
.unwrap()
|
||||
}
|
||||
fn expected(before: &Project, mode: &str) -> Result<Project> {
|
||||
let mut p = before.clone();
|
||||
match mode {
|
||||
"unchanged" => {}
|
||||
"oa-assigned" | "sa-assigned" => {
|
||||
let scope = if mode == "oa-assigned" {
|
||||
"oa_assign"
|
||||
} else {
|
||||
"sa_assign"
|
||||
};
|
||||
for (rel, work) in [("ax", "x"), ("by", "y")] {
|
||||
p.relations.get_mut(&id(&named(scope, rel))).unwrap().body =
|
||||
RelationBody::Allocation {
|
||||
source: id(&named(scope, "c")),
|
||||
target: id(&named(scope, work)),
|
||||
};
|
||||
}
|
||||
node_mut(&mut p, scope, "x").position = xy(560., 140.);
|
||||
node_mut(&mut p, scope, "y").position = xy(560., 440.);
|
||||
p.diagrams.get_mut(&id(scope)).unwrap().routes[0].waypoints =
|
||||
vec![xy(820., 260.), xy(820., 400.)];
|
||||
}
|
||||
"oa-arranged" | "sa-arranged" => {
|
||||
let scope = if mode == "oa-arranged" {
|
||||
"oa_arrange"
|
||||
} else {
|
||||
"sa_arrange"
|
||||
};
|
||||
for (suffix, pos) in [
|
||||
("p", xy(40., 280.)),
|
||||
("u", xy(80., 380.)),
|
||||
("v", xy(440., 380.)),
|
||||
] {
|
||||
node_mut(&mut p, scope, suffix).position = pos;
|
||||
}
|
||||
p.diagrams.get_mut(&id(scope)).unwrap().routes[0].waypoints =
|
||||
vec![xy(360., 420.), xy(360., 470.)];
|
||||
}
|
||||
"oa-performers" => {
|
||||
for (suffix, pos) in [
|
||||
("a", xy(120., 90.)),
|
||||
("b", xy(120., 380.)),
|
||||
("x", xy(157., 183.)),
|
||||
("y", xy(157., 483.)),
|
||||
] {
|
||||
node_mut(&mut p, "oa_assign", suffix).position = pos;
|
||||
}
|
||||
p.diagrams.get_mut(&id("oa_assign")).unwrap().routes[0].waypoints =
|
||||
vec![xy(417., 303.), xy(417., 443.)];
|
||||
}
|
||||
_ => return Err(format!("Unknown mode {mode}; expected {MODES:?}").into()),
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
fn ancestor(view: &projection::ProjectedView, parent: Id, child: Id) -> bool {
|
||||
let mut next = view
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.id == child)
|
||||
.and_then(|n| n.visual_parent);
|
||||
for _ in 0..view.nodes.len() {
|
||||
let Some(current) = next else {
|
||||
return false;
|
||||
};
|
||||
if current == parent {
|
||||
return true;
|
||||
}
|
||||
next = view
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.id == current)
|
||||
.and_then(|n| n.visual_parent);
|
||||
}
|
||||
false
|
||||
}
|
||||
/// Fixture-usability preflight only: never calculates expected mutations.
|
||||
fn preflight(p: &Project) -> Result<serde_json::Value> {
|
||||
validate_candidate(p)?;
|
||||
let mut scenes = Vec::new();
|
||||
for scope in ["oa_assign", "sa_assign", "oa_arrange", "sa_arrange"] {
|
||||
let d = &p.diagrams[&id(scope)];
|
||||
let view = projection::project_view(p, d.id);
|
||||
need(
|
||||
view.nodes.len() == d.nodes.len(),
|
||||
format!("{scope}: hidden/missing fixture placement"),
|
||||
)?;
|
||||
for n in &view.nodes {
|
||||
need(
|
||||
n.position == d.nodes[&n.id].position,
|
||||
format!("{scope}: unexpectedly shifted projected origin {}", n.id),
|
||||
)?;
|
||||
need(
|
||||
n.position.x >= 0.
|
||||
&& n.position.y >= 0.
|
||||
&& n.position.x + n.size.width <= 900.
|
||||
&& n.position.y + n.size.height <= 750.,
|
||||
format!("{scope}: fixture exceeds declared compact world envelope: {n:?}"),
|
||||
)?;
|
||||
if p.elements[&n.element].kind().is_work() {
|
||||
let height = if d.layer == Layer::Sa { 132. } else { 94. };
|
||||
need(
|
||||
n.size
|
||||
== Size {
|
||||
width: 224.,
|
||||
height,
|
||||
},
|
||||
format!("{scope}: unexpected work/port extent {n:?}"),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
for (i, a) in view.nodes.iter().enumerate() {
|
||||
for b in &view.nodes[i + 1..] {
|
||||
if ancestor(&view, a.id, b.id) || ancestor(&view, b.id, a.id) {
|
||||
continue;
|
||||
}
|
||||
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);
|
||||
need(
|
||||
width <= 0. || height <= 0.,
|
||||
format!("{scope}: unrelated projected overlap {} {}", a.id, b.id),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
let routed = routing::route_diagram(p, d, &view);
|
||||
let edge = id(&named(scope, "exchange"));
|
||||
let r = routed
|
||||
.edges
|
||||
.get(&edge)
|
||||
.ok_or("Authored exchange route is missing")?;
|
||||
need(
|
||||
!r.custom_suspended && r.pins == d.routes[0].waypoints,
|
||||
format!("{scope}: authored pins are not active"),
|
||||
)?;
|
||||
need(
|
||||
r.warnings.is_empty(),
|
||||
format!(
|
||||
"{scope}: route warnings require fixture review: {:?}; ports={:?}; points={:?}; nodes={:?}",
|
||||
r.warnings, view.ports, r.points, view.nodes
|
||||
),
|
||||
)?;
|
||||
need(
|
||||
view.ports.len() == if d.layer == Layer::Sa { 2 } else { 0 },
|
||||
format!("{scope}: unexpected visible typed ports"),
|
||||
)?;
|
||||
scenes.push(serde_json::json!({"diagram":scope,"nodes":view.nodes,"ports":view.ports,"active_pins":r.pins,"route_warnings":r.warnings.iter().map(ToString::to_string).collect::<Vec<_>>()}));
|
||||
}
|
||||
Ok(serde_json::json!(scenes))
|
||||
}
|
||||
fn load(path: &Path) -> Result<Project> {
|
||||
if path
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("arcadia"))
|
||||
{
|
||||
let disk = source_files::load_project(path, ProjectLimits::default())?;
|
||||
need(
|
||||
!disk
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.diagnostic.severity == validation::Severity::Error),
|
||||
format!("Source discovery errors: {:?}", disk.diagnostics),
|
||||
)?;
|
||||
let compiled = compile_bundle(&disk.reachable_bundle(), ProjectLimits::default())
|
||||
.map_err(|e| format!("Source compile: {e:?}"))?;
|
||||
Ok(compiled.decoded.project)
|
||||
} else {
|
||||
Ok(persistence::load(path)?)
|
||||
}
|
||||
}
|
||||
fn equal(expected: &Project, actual: &Project) -> Result<()> {
|
||||
if expected == actual {
|
||||
return Ok(());
|
||||
}
|
||||
let e = serde_json::to_value(expected)?;
|
||||
let a = serde_json::to_value(actual)?;
|
||||
let fields: Vec<_> = e
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.filter(|key| e[*key] != a[*key])
|
||||
.cloned()
|
||||
.collect();
|
||||
Err(format!("Whole Project mismatch in {fields:?}; no partial PASS").into())
|
||||
}
|
||||
fn roundtrip(p: &Project) -> Result<SourceBundle> {
|
||||
validate_candidate(p)?;
|
||||
equal(p, &persistence::decode(&serde_json::to_vec(p)?)?)?;
|
||||
let mut bundle = format_bundle(p);
|
||||
for (path, text) in &mut bundle.files {
|
||||
*text = format!("// Native preservation sentinel: {path}\n{text}");
|
||||
}
|
||||
let parsed = compile_bundle(&bundle, ProjectLimits::default())
|
||||
.map_err(|e| format!("Source roundtrip: {e:?}"))?;
|
||||
equal(p, &parsed.decoded.project)?;
|
||||
Ok(bundle)
|
||||
}
|
||||
fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
fs::create_dir_all(path.parent().ok_or("Missing parent directory")?)?;
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)?
|
||||
.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
fn generate(out: &Path) -> Result<()> {
|
||||
need(!out.exists(), "Output exists; choose a fresh directory")?;
|
||||
let p = fixture()?;
|
||||
let bundle = roundtrip(&p)?;
|
||||
let mut geometry = BTreeMap::new();
|
||||
// All literal candidates must satisfy the same compact-fixture prerequisites
|
||||
// before any bytes are published for a native run.
|
||||
for mode in MODES {
|
||||
let candidate = expected(&p, mode)?;
|
||||
roundtrip(&candidate)?;
|
||||
geometry.insert(mode, preflight(&candidate)?);
|
||||
}
|
||||
let mut ids = BTreeMap::from([(p.alias.clone(), p.id)]);
|
||||
ids.extend(p.elements.values().map(|v| (v.alias.clone(), v.id)));
|
||||
ids.extend(p.relations.values().map(|v| (v.alias.clone(), v.id)));
|
||||
ids.extend(p.diagrams.values().map(|v| (v.alias.clone(), v.id)));
|
||||
ids.extend(
|
||||
p.diagrams
|
||||
.values()
|
||||
.flat_map(|d| d.nodes.values().map(|v| (v.alias.clone(), v.id))),
|
||||
);
|
||||
write_new(&out.join("baseline.json"), &serde_json::to_vec_pretty(&p)?)?;
|
||||
for (path, text) in &bundle.files {
|
||||
write_new(&out.join("source").join(path), text.as_bytes())?;
|
||||
}
|
||||
let paths: BTreeMap<_, _> = ids
|
||||
.iter()
|
||||
.map(|(alias, id)| {
|
||||
let needle = id.to_string();
|
||||
let files: Vec<_> = bundle
|
||||
.files
|
||||
.iter()
|
||||
.filter(|(_, text)| text.contains(&needle))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
(alias.clone(), files)
|
||||
})
|
||||
.collect();
|
||||
write_new(
|
||||
&out.join("manifest.json"),
|
||||
&serde_json::to_vec_pretty(&serde_json::json!({
|
||||
"fixture":"allocation-multiselect-native-20260923","source_entry":bundle.entry,"ids":ids,
|
||||
"source_files":bundle.files.keys().collect::<Vec<_>>(),"id_text_occurrence_files":paths,
|
||||
"modes":MODES,"geometry_preflight":geometry,
|
||||
"literal_deltas":{"oa-assigned":[480,0],"sa-assigned":[480,0],"oa-arranged":[0,240],"sa-arranged":[0,240],"oa-performers":[77,43]},
|
||||
"selection":{"assigned":["X","Y"],"arranged":["P","V"],"ordinary_performers":["A","B"]},
|
||||
"ordinary_anchor_target":[120,90],
|
||||
"evaluation":"Literal complete Project oracle, never inferred from saved geometry; baseline pinned to deterministic original",
|
||||
"limits":"Geometry preflight is not GUI/planner admission. Source comments/history bytes, focus, exact selection, pointer delivery and one Undo/Redo require separate observation/checks. Each mode is one operation from baseline."
|
||||
}))?,
|
||||
)?;
|
||||
equal(&p, &load(&out.join("baseline.json"))?)?;
|
||||
equal(&p, &load(&out.join("source").join(&bundle.entry))?)?;
|
||||
println!("PASS generated and reloaded fixture: {}", out.display());
|
||||
Ok(())
|
||||
}
|
||||
fn check(mode: &str, baseline: &Path, saved: &Path) -> Result<()> {
|
||||
let before = load(baseline)?;
|
||||
equal(&fixture()?, &before).map_err(|e| format!("Baseline is not immutable original: {e}"))?;
|
||||
let actual = load(saved)?;
|
||||
validate_candidate(&actual)?;
|
||||
equal(&expected(&before, mode)?, &actual)?;
|
||||
roundtrip(&actual)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"result":"PASS","mode":mode,"baseline":baseline,"saved":saved,
|
||||
"comparison":"complete Project equality; literal fixed record edits",
|
||||
"limits":"No pointer, selection, source-byte preservation, focus, Undo/Redo, or native acceptance claim"
|
||||
}))?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
match args.as_slice() {
|
||||
[command,out] if command=="generate" => generate(Path::new(out)),
|
||||
[command,mode,baseline,saved] if command=="check" => check(mode,Path::new(baseline),Path::new(saved)),
|
||||
_=>Err(format!("Usage: allocation_multiselect_native generate DIRECTORY | check MODE BASELINE SAVED; modes={MODES:?}").into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn through_json(mode: &str, before: &Project, actual: &Project) -> Result<()> {
|
||||
validate_candidate(before).expect("baseline valid");
|
||||
validate_candidate(actual).expect("falsifier must remain core-valid");
|
||||
let dir = tempfile::tempdir()?;
|
||||
let baseline = dir.path().join("baseline.json");
|
||||
let saved = dir.path().join("saved.json");
|
||||
persistence::save(&baseline, before)?;
|
||||
persistence::save(&saved, actual)?;
|
||||
check(mode, &baseline, &saved)
|
||||
}
|
||||
fn mismatch(mode: &str, before: &Project, actual: &Project) {
|
||||
let error = through_json(mode, before, actual).unwrap_err().to_string();
|
||||
assert!(
|
||||
error.contains("Whole Project mismatch"),
|
||||
"wrong failure cause: {error}"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn deterministic_create_only_generation_and_all_literal_modes() {
|
||||
let p = fixture().unwrap();
|
||||
assert_eq!(p, fixture().unwrap());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let out = dir.path().join("fixture");
|
||||
generate(&out).unwrap();
|
||||
let before = fs::read(out.join("baseline.json")).unwrap();
|
||||
assert!(generate(&out).is_err());
|
||||
assert_eq!(before, fs::read(out.join("baseline.json")).unwrap());
|
||||
for mode in MODES {
|
||||
let candidate = expected(&p, mode).unwrap();
|
||||
preflight(&candidate).unwrap();
|
||||
through_json(mode, &p, &candidate).unwrap();
|
||||
if mode != "unchanged" {
|
||||
mismatch(mode, &p, &p);
|
||||
}
|
||||
}
|
||||
assert!(expected(&p, "invented").is_err());
|
||||
let changed = expected(&p, "oa-assigned").unwrap();
|
||||
assert!(
|
||||
through_json("unchanged", &changed, &changed)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("immutable original")
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn actual_core_assignment_batch_matches_literal_oracle_and_one_step_history() {
|
||||
let before = fixture().unwrap();
|
||||
for (mode, scope) in [("oa-assigned", "oa_assign"), ("sa-assigned", "sa_assign")] {
|
||||
let mut commands = Vec::new();
|
||||
for (alias, work) in [("ax", "x"), ("by", "y")] {
|
||||
let relation = id(&named(scope, alias));
|
||||
let mut value = before.relations[&relation].clone();
|
||||
value.body = RelationBody::Allocation {
|
||||
source: id(&named(scope, "c")),
|
||||
target: id(&named(scope, work)),
|
||||
};
|
||||
commands.push(Command::EditRelation(relation, value));
|
||||
}
|
||||
for (suffix, position) in [("x", xy(560., 140.)), ("y", xy(560., 440.))] {
|
||||
let original = id(&named(scope, &format!("node_{suffix}")));
|
||||
let mut node = before.diagrams[&id(scope)].nodes[&original].clone();
|
||||
node.position = position;
|
||||
commands.push(Command::EditNode {
|
||||
diagram: id(scope),
|
||||
original,
|
||||
node,
|
||||
});
|
||||
}
|
||||
let mut route = before.diagrams[&id(scope)].routes[0].clone();
|
||||
route.waypoints = vec![xy(820., 260.), xy(820., 400.)];
|
||||
commands.push(Command::SetEdgeRoute {
|
||||
diagram: id(scope),
|
||||
route,
|
||||
});
|
||||
let mut session = Session::new(before.clone());
|
||||
session.execute(Command::Batch(commands)).unwrap();
|
||||
through_json(mode, &before, session.project()).unwrap();
|
||||
let after = session.project().clone();
|
||||
session.undo();
|
||||
assert_eq!(session.project(), &before);
|
||||
assert!(!session.can_undo());
|
||||
session.redo();
|
||||
assert_eq!(session.project(), &after);
|
||||
assert!(!session.can_redo());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn assignment_rejects_singleton_semantic_identity_and_route_drift() {
|
||||
let before = fixture().unwrap();
|
||||
for mode in ["oa-assigned", "sa-assigned"] {
|
||||
let scope = if mode == "oa-assigned" {
|
||||
"oa_assign"
|
||||
} else {
|
||||
"sa_assign"
|
||||
};
|
||||
let good = expected(&before, mode).unwrap();
|
||||
let mut bad = good.clone();
|
||||
node_mut(&mut bad, scope, "y").position = xy(80., 440.);
|
||||
mismatch(mode, &before, &bad);
|
||||
let mut bad = good.clone();
|
||||
bad.relations.insert(
|
||||
id(&named(scope, "by")),
|
||||
before.relations[&id(&named(scope, "by"))].clone(),
|
||||
);
|
||||
mismatch(mode, &before, &bad);
|
||||
let mut bad = good.clone();
|
||||
reidentify(
|
||||
&mut bad,
|
||||
id(&named(scope, "ax")),
|
||||
id("replacement_allocation"),
|
||||
)
|
||||
.unwrap();
|
||||
mismatch(mode, &before, &bad);
|
||||
let mut bad = good.clone();
|
||||
bad.relations
|
||||
.get_mut(&id(&named(scope, "ax")))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift");
|
||||
mismatch(mode, &before, &bad);
|
||||
for pins in [
|
||||
vec![xy(340., 260.), xy(340., 400.)],
|
||||
vec![xy(1300., 260.), xy(1300., 400.)],
|
||||
] {
|
||||
let mut bad = good.clone();
|
||||
bad.diagrams.get_mut(&id(scope)).unwrap().routes[0].waypoints = pins;
|
||||
mismatch(mode, &before, &bad);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn arrange_and_ordinary_closure_falsifiers_remain_core_valid() {
|
||||
let before = fixture().unwrap();
|
||||
for mode in ["oa-arranged", "sa-arranged"] {
|
||||
let scope = if mode == "oa-arranged" {
|
||||
"oa_arrange"
|
||||
} else {
|
||||
"sa_arrange"
|
||||
};
|
||||
let good = expected(&before, mode).unwrap();
|
||||
for (suffix, pos) in [("u", xy(80., 140.)), ("v", xy(440., 140.))] {
|
||||
let mut bad = good.clone();
|
||||
node_mut(&mut bad, scope, suffix).position = pos;
|
||||
mismatch(mode, &before, &bad);
|
||||
}
|
||||
let mut bad = good.clone();
|
||||
bad.relations.remove(&id(&named(scope, "pu")));
|
||||
mismatch(mode, &before, &bad);
|
||||
}
|
||||
let good = expected(&before, "oa-performers").unwrap();
|
||||
let mut bad = good.clone();
|
||||
node_mut(&mut bad, "oa_assign", "x").position = xy(80., 140.);
|
||||
mismatch("oa-performers", &before, &bad);
|
||||
let mut bad = good;
|
||||
bad.relations.get_mut(&id("oa_assign_ax")).unwrap().body = RelationBody::Allocation {
|
||||
source: id("oa_assign_c"),
|
||||
target: id("oa_assign_x"),
|
||||
};
|
||||
mismatch("oa-performers", &before, &bad);
|
||||
}
|
||||
#[test]
|
||||
fn whole_project_sentinels_and_real_saved_source_are_checked() {
|
||||
let before = fixture().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let baseline = dir.path().join("baseline.json");
|
||||
persistence::save(&baseline, &before).unwrap();
|
||||
for mode in MODES {
|
||||
let good = expected(&before, mode).unwrap();
|
||||
for corrupt in [false, true] {
|
||||
let mut actual = good.clone();
|
||||
if corrupt {
|
||||
actual
|
||||
.elements
|
||||
.get_mut(&id("sa_arrange_v"))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift");
|
||||
}
|
||||
let bundle = roundtrip(&actual).unwrap();
|
||||
let folder = dir.path().join(format!("{mode}-{corrupt}"));
|
||||
for (path, text) in &bundle.files {
|
||||
write_new(&folder.join(path), text.as_bytes()).unwrap();
|
||||
}
|
||||
let result = check(mode, &baseline, &folder.join(&bundle.entry));
|
||||
if corrupt {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Whole Project mismatch")
|
||||
);
|
||||
} else {
|
||||
result.unwrap();
|
||||
}
|
||||
}
|
||||
let mut bad = good;
|
||||
bad.diagrams
|
||||
.get_mut(&id("other_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id("other_view_x"))
|
||||
.unwrap()
|
||||
.position
|
||||
.x += 10.;
|
||||
mismatch(mode, &before, &bad);
|
||||
}
|
||||
let invalid = dir.path().join("invalid.arcadia");
|
||||
write_new(&invalid, b"project {").unwrap();
|
||||
assert!(load(&invalid).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
//! Native evidence fixture/checker; install as a temporary oa-core example.
|
||||
//! This invariant evaluator derives delta from saved A, NOT from pointer input.
|
||||
use oa_core::{source_project::*, *};
|
||||
use std::{fs, io::Write, path::Path};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn id(alias: &str) -> Id {
|
||||
// Make the intended OA view first for default UUID-ordered view selection.
|
||||
if alias == "oa_view" {
|
||||
return Id::from_u128(0x29_0001);
|
||||
}
|
||||
Id::new_v5(
|
||||
&Id::from_u128(0xc1192026_0923_5000_8000_000000000029),
|
||||
alias.as_bytes(),
|
||||
)
|
||||
}
|
||||
fn point(x: f32, y: f32) -> Position {
|
||||
Position { x, y }
|
||||
}
|
||||
fn element(p: &mut Project, alias: &str, name: &str, kind: Kind, layer: Layer, parent: Option<Id>) {
|
||||
p.elements.insert(
|
||||
id(alias),
|
||||
Element {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: format!("Preserve engineering record {alias}."),
|
||||
parent,
|
||||
body: ElementBody::new(kind, layer).unwrap(),
|
||||
},
|
||||
);
|
||||
}
|
||||
fn diagram(p: &mut Project, alias: &str, name: &str, layer: Layer) {
|
||||
p.diagrams.insert(
|
||||
id(alias),
|
||||
Diagram {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: "Selection changes placement geometry only.".into(),
|
||||
layer,
|
||||
projection: ProjectionKind::Overview,
|
||||
view_options: Default::default(),
|
||||
layout: None,
|
||||
nodes: Default::default(),
|
||||
routes: vec![],
|
||||
},
|
||||
);
|
||||
}
|
||||
fn place(p: &mut Project, view: &str, alias: &str, object: &str, position: Position, size: Size) {
|
||||
p.diagrams.get_mut(&id(view)).unwrap().nodes.insert(
|
||||
id(alias),
|
||||
NodePlacement {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
element: id(object),
|
||||
position,
|
||||
size,
|
||||
collapsed: false,
|
||||
port_anchors: vec![],
|
||||
},
|
||||
);
|
||||
}
|
||||
fn route(edge: &str, pins: Vec<Position>) -> EdgeRoute {
|
||||
EdgeRoute {
|
||||
edge: id(edge),
|
||||
waypoints: pins,
|
||||
source_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Right,
|
||||
offset: 0.25,
|
||||
}),
|
||||
target_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Left,
|
||||
offset: 0.7,
|
||||
}),
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.45,
|
||||
offset: point(7., -19.),
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn fixture() -> Result<Project> {
|
||||
let mut p = Project::empty();
|
||||
p.id = id("project");
|
||||
p.alias = "multiselect_native".into();
|
||||
p.name = "Multiselect native".into();
|
||||
p.description =
|
||||
"Shift-select A and B; move together, retain C and engineering semantics.".into();
|
||||
for (alias, name, parent) in [
|
||||
("activity_a", "A - receive request", None),
|
||||
("activity_b", "B - assess request", None),
|
||||
("activity_c", "C - dispatch response", None),
|
||||
(
|
||||
"activity_child",
|
||||
"A.1 - classify request",
|
||||
Some(id("activity_a")),
|
||||
),
|
||||
] {
|
||||
element(&mut p, alias, name, Kind::Activity, Layer::Oa, parent);
|
||||
}
|
||||
element(
|
||||
&mut p,
|
||||
"sa_function",
|
||||
"Technical request processing",
|
||||
Kind::Function,
|
||||
Layer::Sa,
|
||||
None,
|
||||
);
|
||||
for (alias, name, source, target) in [
|
||||
("internal", "Request assessment", "activity_a", "activity_b"),
|
||||
("external", "Response decision", "activity_b", "activity_c"),
|
||||
] {
|
||||
let old = p.relate(RelationKind::Interaction, name, id(source), id(target));
|
||||
reidentify(&mut p, old, id(alias))?;
|
||||
p.relations.get_mut(&id(alias)).unwrap().alias = alias.into();
|
||||
}
|
||||
diagram(
|
||||
&mut p,
|
||||
"oa_view",
|
||||
"Multiselect native - OA overview",
|
||||
Layer::Oa,
|
||||
);
|
||||
diagram(&mut p, "oa_other", "Other OA view - preserve", Layer::Oa);
|
||||
diagram(&mut p, "sa_view", "SA engineering - preserve", Layer::Sa);
|
||||
let size = Size {
|
||||
width: 224.,
|
||||
height: 94.,
|
||||
};
|
||||
place(
|
||||
&mut p,
|
||||
"oa_view",
|
||||
"node_a",
|
||||
"activity_a",
|
||||
point(80., 80.),
|
||||
Size {
|
||||
width: 310.,
|
||||
height: 260.,
|
||||
},
|
||||
);
|
||||
place(
|
||||
&mut p,
|
||||
"oa_view",
|
||||
"node_b",
|
||||
"activity_b",
|
||||
point(470., 120.),
|
||||
size,
|
||||
);
|
||||
place(
|
||||
&mut p,
|
||||
"oa_view",
|
||||
"node_c",
|
||||
"activity_c",
|
||||
point(780., 270.),
|
||||
size,
|
||||
);
|
||||
place(
|
||||
&mut p,
|
||||
"oa_view",
|
||||
"node_child",
|
||||
"activity_child",
|
||||
point(120., 210.),
|
||||
size,
|
||||
);
|
||||
place(
|
||||
&mut p,
|
||||
"oa_other",
|
||||
"other_a",
|
||||
"activity_a",
|
||||
point(40., 60.),
|
||||
size,
|
||||
);
|
||||
place(
|
||||
&mut p,
|
||||
"sa_view",
|
||||
"sa_node",
|
||||
"sa_function",
|
||||
point(100., 110.),
|
||||
size,
|
||||
);
|
||||
p.diagrams.get_mut(&id("oa_view")).unwrap().routes = vec![
|
||||
route("internal", vec![point(420., 145.), point(420., 186.)]),
|
||||
route("external", vec![point(725., 150.), point(725., 336.)]),
|
||||
];
|
||||
p.traces.insert(
|
||||
id("trace"),
|
||||
Trace {
|
||||
id: id("trace"),
|
||||
alias: "preserved_refinement".into(),
|
||||
name: "Reviewed request refinement".into(),
|
||||
description: "Group geometry and Hide preserve this trace and both endpoints.".into(),
|
||||
oa: id("activity_a"),
|
||||
sa: id("sa_function"),
|
||||
kind: TraceKind::Refinement,
|
||||
baseline: Some(TraceBaseline {
|
||||
oa: p.properties(id("activity_a")).unwrap(),
|
||||
sa: p.properties(id("sa_function")).unwrap(),
|
||||
semantic: None,
|
||||
}),
|
||||
},
|
||||
);
|
||||
validate_candidate(&p)?;
|
||||
Ok(p)
|
||||
}
|
||||
fn load(path: &Path) -> Result<Project> {
|
||||
if path
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("arcadia"))
|
||||
{
|
||||
let disk = source_files::load_project(path, ProjectLimits::default())?;
|
||||
// This deliberately partial engineering fixture has completeness
|
||||
// warnings (allocation/behavior context). They are not source errors.
|
||||
// Compilation, candidate validation and whole-Project equality still
|
||||
// reject malformed source or any unexpected model change.
|
||||
if disk
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.diagnostic.severity == validation::Severity::Error)
|
||||
{
|
||||
return Err(format!("Source discovery diagnostics: {:?}", disk.diagnostics).into());
|
||||
}
|
||||
let compiled = compile_bundle(&disk.reachable_bundle(), ProjectLimits::default())
|
||||
.map_err(|e| format!("Source compile diagnostics: {e:?}"))?;
|
||||
Ok(compiled.decoded.project)
|
||||
} else {
|
||||
Ok(persistence::load(path)?)
|
||||
}
|
||||
}
|
||||
fn equal(expected: &Project, actual: &Project) -> Result<()> {
|
||||
if expected == actual {
|
||||
return Ok(());
|
||||
}
|
||||
let e = serde_json::to_value(expected)?;
|
||||
let a = serde_json::to_value(actual)?;
|
||||
let fields: Vec<_> = e
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.filter(|key| e[*key] != a[*key])
|
||||
.cloned()
|
||||
.collect();
|
||||
Err(format!("Whole Project mismatch in {fields:?}; no partial PASS").into())
|
||||
}
|
||||
fn roundtrip(p: &Project) -> Result<SourceBundle> {
|
||||
validate_candidate(p)?;
|
||||
equal(p, &persistence::decode(&serde_json::to_vec(p)?)?)?;
|
||||
let bundle = format_bundle(p);
|
||||
let compiled = compile_bundle(&bundle, ProjectLimits::default())
|
||||
.map_err(|e| format!("Roundtrip: {e:?}"))?;
|
||||
equal(p, &compiled.decoded.project)?;
|
||||
Ok(bundle)
|
||||
}
|
||||
fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
fs::create_dir_all(path.parent().ok_or("Missing parent directory")?)?;
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)?
|
||||
.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
fn generate(out: &Path) -> Result<()> {
|
||||
if out.exists() {
|
||||
return Err("Output directory already exists; choose a fresh path".into());
|
||||
}
|
||||
let p = fixture()?;
|
||||
let bundle = roundtrip(&p)?;
|
||||
write_new(&out.join("baseline.json"), &serde_json::to_vec_pretty(&p)?)?;
|
||||
for (path, source) in &bundle.files {
|
||||
write_new(&out.join("source").join(path), source.as_bytes())?;
|
||||
}
|
||||
let names = [
|
||||
"project",
|
||||
"oa_view",
|
||||
"oa_other",
|
||||
"sa_view",
|
||||
"activity_a",
|
||||
"activity_b",
|
||||
"activity_c",
|
||||
"activity_child",
|
||||
"node_a",
|
||||
"node_b",
|
||||
"node_c",
|
||||
"node_child",
|
||||
"internal",
|
||||
"external",
|
||||
"trace",
|
||||
"sa_function",
|
||||
"sa_node",
|
||||
"other_a",
|
||||
];
|
||||
let ids: std::collections::BTreeMap<_, _> =
|
||||
names.into_iter().map(|name| (name, id(name))).collect();
|
||||
write_new(
|
||||
&out.join("manifest.json"),
|
||||
&serde_json::to_vec_pretty(&serde_json::json!({
|
||||
"fixture": "multiselect-native-20260923", "ids": ids, "source_entry": bundle.entry,
|
||||
"move_members": ["node_a", "node_b", "node_child"], "fixed_member": "node_c",
|
||||
"evaluation": "Whole Project invariant comparison; saved A supplies bounded shared delta, not an exact pointer oracle",
|
||||
"hide": "Remove node_a/node_b only; retain child, stored routes, all model records and other views",
|
||||
}))?,
|
||||
)?;
|
||||
equal(&p, &load(&out.join("baseline.json"))?)?;
|
||||
equal(&p, &load(&out.join("source/project.arcadia"))?)?;
|
||||
println!("PASS generated JSON and source bundle: {}", out.display());
|
||||
Ok(())
|
||||
}
|
||||
fn check(mode: &str, baseline: &Path, saved: &Path) -> Result<()> {
|
||||
let before = load(baseline)?;
|
||||
let actual = load(saved)?;
|
||||
validate_candidate(&before)?;
|
||||
validate_candidate(&actual)?;
|
||||
if before.id != id("project") {
|
||||
return Err("Not this fixture's baseline project".into());
|
||||
}
|
||||
let mut expected = before.clone();
|
||||
let mut delta = None;
|
||||
match mode {
|
||||
"unchanged" => {}
|
||||
"hide" => {
|
||||
let view = expected
|
||||
.diagrams
|
||||
.get_mut(&id("oa_view"))
|
||||
.ok_or("Missing OA view")?;
|
||||
for alias in ["node_a", "node_b"] {
|
||||
view.nodes
|
||||
.remove(&id(alias))
|
||||
.ok_or("Baseline selected placement missing")?;
|
||||
}
|
||||
// references::remove_objects removes routes only when their semantic
|
||||
// edge is deleted. Hide deletes placements; both routes MUST survive.
|
||||
}
|
||||
"moved" => {
|
||||
let old = before
|
||||
.diagrams
|
||||
.get(&id("oa_view"))
|
||||
.ok_or("Missing baseline OA view")?;
|
||||
let new = actual
|
||||
.diagrams
|
||||
.get(&id("oa_view"))
|
||||
.ok_or("Missing saved OA view")?;
|
||||
let a = old
|
||||
.nodes
|
||||
.get(&id("node_a"))
|
||||
.ok_or("Missing baseline A")?
|
||||
.position;
|
||||
let moved_a = new
|
||||
.nodes
|
||||
.get(&id("node_a"))
|
||||
.ok_or("Missing saved A")?
|
||||
.position;
|
||||
let d = point(moved_a.x - a.x, moved_a.y - a.y);
|
||||
if !d.x.is_finite()
|
||||
|| !d.y.is_finite()
|
||||
|| d.x.abs().max(d.y.abs()) > 500.
|
||||
|| d.x.hypot(d.y) < 10.
|
||||
{
|
||||
return Err(format!(
|
||||
"Move delta must have length >=10 and each axis <=500 world units: {d:?}"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
if moved_a.x % 10. != 0. || moved_a.y % 10. != 0. {
|
||||
return Err("Saved anchor is not on 10-unit grid".into());
|
||||
}
|
||||
let view = expected.diagrams.get_mut(&id("oa_view")).unwrap();
|
||||
// Independent explicit fixture enumeration: no group/descendant/
|
||||
// routing planner is called to predict the result.
|
||||
for alias in ["node_a", "node_b", "node_child"] {
|
||||
let node = view
|
||||
.nodes
|
||||
.get_mut(&id(alias))
|
||||
.ok_or("Missing expected moved placement")?;
|
||||
node.position.x += d.x;
|
||||
node.position.y += d.y;
|
||||
}
|
||||
let internal = view
|
||||
.routes
|
||||
.iter_mut()
|
||||
.find(|route| route.edge == id("internal"))
|
||||
.ok_or("Missing internal pins")?;
|
||||
for pin in &mut internal.waypoints {
|
||||
pin.x += d.x;
|
||||
pin.y += d.y;
|
||||
}
|
||||
delta = Some(d);
|
||||
}
|
||||
_ => return Err("Mode must be moved, hide, or unchanged".into()),
|
||||
}
|
||||
equal(&expected, &actual)?;
|
||||
roundtrip(&actual)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"result": "PASS", "mode": mode, "baseline": baseline, "saved": saved,
|
||||
"comparison": "complete Project equality", "inferred_common_delta": delta,
|
||||
"limits": "Invariant evaluator only; no pointer/action/focus/Undo/source-byte acceptance claim",
|
||||
}))?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
match args.as_slice() {
|
||||
[command, out] if command == "generate" => generate(Path::new(out)),
|
||||
[command, mode, baseline, saved] if command == "check" => check(mode, Path::new(baseline), Path::new(saved)),
|
||||
_ => Err("Usage: multiselect-native-producer generate DIRECTORY | check moved|hide|unchanged BASELINE SAVED".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
// Produce evidence through real validated commands; the checker itself uses
|
||||
// explicit fixture enumeration and never calls this movement implementation.
|
||||
fn moved(before: &Project, delta: Position) -> Project {
|
||||
let command = diagram_edit::translate_placements(
|
||||
before,
|
||||
id("oa_view"),
|
||||
&BTreeSet::from([id("node_a"), id("node_b")]),
|
||||
delta,
|
||||
)
|
||||
.unwrap();
|
||||
let mut session = Session::new(before.clone());
|
||||
session.execute(command).unwrap();
|
||||
session.project().clone()
|
||||
}
|
||||
fn hidden(before: &Project) -> Project {
|
||||
let mut session = Session::new(before.clone());
|
||||
session
|
||||
.execute(Command::Batch(vec![
|
||||
Command::Delete(id("node_a")),
|
||||
Command::Delete(id("node_b")),
|
||||
]))
|
||||
.unwrap();
|
||||
session.project().clone()
|
||||
}
|
||||
fn through_saved_json(mode: &str, baseline: &Project, actual: &Project) -> Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let before = dir.path().join("before.json");
|
||||
let saved = dir.path().join("saved.json");
|
||||
// These assertions distinguish meaningful invariant corruptions from
|
||||
// malformed projects rejected before the evaluator even sees them.
|
||||
validate_candidate(baseline).expect("test baseline must be valid");
|
||||
validate_candidate(actual).expect("corruption must remain a valid model");
|
||||
persistence::save(&before, baseline)?;
|
||||
persistence::save(&saved, actual)?;
|
||||
check(mode, &before, &saved)
|
||||
}
|
||||
fn mismatch(mode: &str, before: &Project, actual: &Project, case: &str) {
|
||||
let error = through_saved_json(mode, before, actual)
|
||||
.expect_err(case)
|
||||
.to_string();
|
||||
assert!(
|
||||
error.contains("Whole Project mismatch"),
|
||||
"{case}: unexpected rejection: {error}"
|
||||
);
|
||||
}
|
||||
fn edge<'a>(p: &'a mut Project, alias: &str) -> &'a mut EdgeRoute {
|
||||
p.diagrams
|
||||
.get_mut(&id("oa_view"))
|
||||
.unwrap()
|
||||
.routes
|
||||
.iter_mut()
|
||||
.find(|route| route.edge == id(alias))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_json_and_real_source_bundle_are_accepted_unchanged() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let out = dir.path().join("fixture");
|
||||
generate(&out).unwrap();
|
||||
let baseline = out.join("baseline.json");
|
||||
let saved = out.join("saved.json");
|
||||
persistence::save(&saved, &fixture().unwrap()).unwrap();
|
||||
check("unchanged", &baseline, &saved).unwrap();
|
||||
check("unchanged", &baseline, &out.join("source/project.arcadia")).unwrap();
|
||||
let bytes = fs::read(&baseline).unwrap();
|
||||
assert!(
|
||||
generate(&out).is_err(),
|
||||
"generation cannot overwrite evidence"
|
||||
);
|
||||
assert_eq!(fs::read(&baseline).unwrap(), bytes);
|
||||
let invalid = dir.path().join("invalid.arcadia");
|
||||
fs::write(&invalid, "project {").unwrap();
|
||||
assert!(load(&invalid).is_err(), "source errors must still reject");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_group_command_outputs_pass_and_are_not_unchanged() {
|
||||
let before = fixture().unwrap();
|
||||
for delta in [point(40., 60.), point(-20., 30.)] {
|
||||
let actual = moved(&before, delta);
|
||||
through_saved_json("moved", &before, &actual).unwrap();
|
||||
mismatch(
|
||||
"unchanged",
|
||||
&before,
|
||||
&actual,
|
||||
"real movement cannot count as unchanged",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_hide_command_outputs_pass_before_and_after_movement() {
|
||||
let initial = fixture().unwrap();
|
||||
for before in [initial.clone(), moved(&initial, point(40., 60.))] {
|
||||
let actual = hidden(&before);
|
||||
through_saved_json("hide", &before, &actual).unwrap();
|
||||
mismatch(
|
||||
"unchanged",
|
||||
&before,
|
||||
&actual,
|
||||
"real Hide cannot count as unchanged",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_and_double_moved_child_are_rejected() {
|
||||
let before = fixture().unwrap();
|
||||
let delta = point(40., 60.);
|
||||
let correct = moved(&before, delta);
|
||||
let initial = before.diagrams[&id("oa_view")].nodes[&id("node_child")].position;
|
||||
for position in [
|
||||
initial,
|
||||
point(initial.x + 2. * delta.x, initial.y + 2. * delta.y),
|
||||
] {
|
||||
let mut bad = correct.clone();
|
||||
bad.diagrams
|
||||
.get_mut(&id("oa_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id("node_child"))
|
||||
.unwrap()
|
||||
.position = position;
|
||||
mismatch("moved", &before, &bad, "child did not move exactly once");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_pins_left_behind_and_external_pins_moved_are_rejected() {
|
||||
let mut before = fixture().unwrap();
|
||||
let original_pins = edge(&mut before, "internal").waypoints.clone();
|
||||
let correct = moved(&before, point(40., 60.));
|
||||
let mut bad = correct.clone();
|
||||
edge(&mut bad, "internal").waypoints = original_pins;
|
||||
mismatch("moved", &before, &bad, "internal pins left behind");
|
||||
let mut bad = correct;
|
||||
for pin in &mut edge(&mut bad, "external").waypoints {
|
||||
pin.x += 40.;
|
||||
pin.y += 60.;
|
||||
}
|
||||
mismatch("moved", &before, &bad, "one-ended pins moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_attachments_and_label_data_must_remain_exact() {
|
||||
let before = fixture().unwrap();
|
||||
let correct = moved(&before, point(40., 60.));
|
||||
let mutations: [fn(&mut EdgeRoute); 4] = [
|
||||
|r| r.source_attachment.as_mut().unwrap().offset = 0.65,
|
||||
|r| r.target_attachment.as_mut().unwrap().side = PortAnchorSide::Top,
|
||||
|r| r.label.as_mut().unwrap().offset.x += 40.,
|
||||
|r| r.label.as_mut().unwrap().fraction = 0.75,
|
||||
];
|
||||
for mutate in mutations {
|
||||
let mut bad = correct.clone();
|
||||
mutate(edge(&mut bad, "internal"));
|
||||
mismatch("moved", &before, &bad, "relative route metadata changed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_other_view_fixed_node_and_trace_drift_are_rejected() {
|
||||
let before = fixture().unwrap();
|
||||
let correct = moved(&before, point(40., 60.));
|
||||
let mutations: [fn(&mut Project); 5] = [
|
||||
|p| {
|
||||
p.elements
|
||||
.get_mut(&id("activity_a"))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift")
|
||||
},
|
||||
|p| {
|
||||
p.diagrams
|
||||
.get_mut(&id("oa_other"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id("other_a"))
|
||||
.unwrap()
|
||||
.position
|
||||
.x += 40.
|
||||
},
|
||||
|p| {
|
||||
p.diagrams
|
||||
.get_mut(&id("sa_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id("sa_node"))
|
||||
.unwrap()
|
||||
.position
|
||||
.y += 60.
|
||||
},
|
||||
|p| {
|
||||
p.diagrams
|
||||
.get_mut(&id("oa_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id("node_c"))
|
||||
.unwrap()
|
||||
.position
|
||||
.x += 40.
|
||||
},
|
||||
|p| {
|
||||
p.traces
|
||||
.get_mut(&id("trace"))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift")
|
||||
},
|
||||
];
|
||||
for mutate in mutations {
|
||||
let mut bad = correct.clone();
|
||||
mutate(&mut bad);
|
||||
mismatch(
|
||||
"moved",
|
||||
&before,
|
||||
&bad,
|
||||
"record outside permitted movement changed",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_small_excessive_and_offgrid_moves_cannot_satisfy_move_evidence() {
|
||||
let before = fixture().unwrap();
|
||||
for (delta, reason) in [
|
||||
(point(0., 0.), "length >=10"),
|
||||
(point(3., 0.), "length >=10"),
|
||||
(point(510., 0.), "each axis <=500"),
|
||||
(point(20.5, 0.), "10-unit grid"),
|
||||
] {
|
||||
let actual = moved(&before, delta);
|
||||
let error = through_saved_json("moved", &before, &actual)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains(reason), "{delta:?}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_must_preserve_child_routes_and_semantic_objects() {
|
||||
let before = fixture().unwrap();
|
||||
let correct = hidden(&before);
|
||||
let mut missing_child = correct.clone();
|
||||
missing_child
|
||||
.diagrams
|
||||
.get_mut(&id("oa_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.remove(&id("node_child"));
|
||||
mismatch(
|
||||
"hide",
|
||||
&before,
|
||||
&missing_child,
|
||||
"Hide removed unselected child placement",
|
||||
);
|
||||
let mut missing_routes = correct;
|
||||
missing_routes
|
||||
.diagrams
|
||||
.get_mut(&id("oa_view"))
|
||||
.unwrap()
|
||||
.routes
|
||||
.clear();
|
||||
mismatch(
|
||||
"hide",
|
||||
&before,
|
||||
&missing_routes,
|
||||
"Hide removed persistent route records",
|
||||
);
|
||||
let mut semantic_delete = Session::new(before.clone());
|
||||
semantic_delete
|
||||
.execute(Command::Batch(vec![
|
||||
Command::Delete(id("activity_a")),
|
||||
Command::Delete(id("activity_b")),
|
||||
]))
|
||||
.unwrap();
|
||||
mismatch(
|
||||
"hide",
|
||||
&before,
|
||||
semantic_delete.project(),
|
||||
"Hide became semantic deletion",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_rejects_valid_semantic_drift_without_geometry_changes() {
|
||||
let before = fixture().unwrap();
|
||||
let mut actual = before.clone();
|
||||
actual
|
||||
.elements
|
||||
.get_mut(&id("activity_b"))
|
||||
.unwrap()
|
||||
.name
|
||||
.push_str(" edited");
|
||||
mismatch(
|
||||
"unchanged",
|
||||
&before,
|
||||
&actual,
|
||||
"geometry equality is not complete Project equality",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
//! Deterministic Process native fixture and independent complete-Project oracle.
|
||||
//! Expected order is literal; no desktop reorder/layout planner is used here.
|
||||
use oa_core::{source_project::*, *};
|
||||
use std::{fs, io::Write, path::Path};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn id(alias: &str) -> Id {
|
||||
Id::new_v5(
|
||||
&Id::from_u128(0xc1192026_0923_5000_8000_000000002930),
|
||||
alias.as_bytes(),
|
||||
)
|
||||
}
|
||||
fn element(p: &mut Project, alias: &str, name: &str, kind: Kind, layer: Layer, parent: Option<Id>) {
|
||||
p.elements.insert(
|
||||
id(alias),
|
||||
Element {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: format!("Preserve engineering record {alias}."),
|
||||
parent,
|
||||
body: ElementBody::new(kind, layer).unwrap(),
|
||||
},
|
||||
);
|
||||
}
|
||||
fn occurrence(
|
||||
p: &mut Project,
|
||||
alias: &str,
|
||||
name: &str,
|
||||
layer: Layer,
|
||||
owner: &str,
|
||||
value: OccurrenceBody,
|
||||
) {
|
||||
element(p, alias, name, Kind::Occurrence, layer, Some(id(owner)));
|
||||
let Some(SharedBody::Occurrence { body, .. }) =
|
||||
p.elements.get_mut(&id(alias)).unwrap().shared_mut()
|
||||
else {
|
||||
panic!("Occurrence body");
|
||||
};
|
||||
*body = value;
|
||||
}
|
||||
fn set_steps(p: &mut Project, owner: &str, aliases: &[&str]) {
|
||||
*p.elements.get_mut(&id(owner)).unwrap().steps_mut().unwrap() =
|
||||
aliases.iter().map(|alias| id(alias)).collect();
|
||||
}
|
||||
fn sequence_link(
|
||||
p: &mut Project,
|
||||
alias: &str,
|
||||
name: &str,
|
||||
source: &str,
|
||||
target: &str,
|
||||
) -> Result<()> {
|
||||
let old = p.relate(RelationKind::SequenceLink, name, id(source), id(target));
|
||||
reidentify(p, old, id(alias))?;
|
||||
let relation = p.relations.get_mut(&id(alias)).unwrap();
|
||||
relation.alias = alias.into();
|
||||
relation.description = format!("Preserve link {alias} exactly.");
|
||||
if let RelationBody::SequenceLink { guard, .. } = &mut relation.body {
|
||||
*guard = "ready".into();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn fixture() -> Result<Project> {
|
||||
let mut p = Project::empty();
|
||||
p.id = id("project");
|
||||
p.alias = "process_multiselect_native".into();
|
||||
p.name = "Process group native".into();
|
||||
p.description = "Select Card C then Shift-select Card A; drop after Card B. Other columns and reusable engineering records remain exact.".into();
|
||||
for (layer, prefix, owner, name, owner_kind, work_kind) in [
|
||||
(
|
||||
Layer::Oa,
|
||||
"oa",
|
||||
"oa_process",
|
||||
"01 OA group order",
|
||||
Kind::Process,
|
||||
Kind::Activity,
|
||||
),
|
||||
(
|
||||
Layer::Sa,
|
||||
"sa",
|
||||
"sa_chain",
|
||||
"SA chain - preserve",
|
||||
Kind::FunctionalChain,
|
||||
Kind::Function,
|
||||
),
|
||||
] {
|
||||
element(&mut p, owner, name, owner_kind, layer, None);
|
||||
let shared = format!("{prefix}_shared_work");
|
||||
let downstream = format!("{prefix}_downstream_work");
|
||||
element(
|
||||
&mut p,
|
||||
&shared,
|
||||
"Shared request work",
|
||||
work_kind,
|
||||
layer,
|
||||
None,
|
||||
);
|
||||
element(
|
||||
&mut p,
|
||||
&downstream,
|
||||
"Downstream verification",
|
||||
work_kind,
|
||||
layer,
|
||||
None,
|
||||
);
|
||||
for (suffix, label) in [
|
||||
("a", "Card A"),
|
||||
("u", "Downstream U"),
|
||||
("b", "Card B"),
|
||||
("v", "Downstream V"),
|
||||
("c", "Card C"),
|
||||
] {
|
||||
let body = if suffix == "b" {
|
||||
OccurrenceBody::Control {
|
||||
kind: ControlKind::Choice,
|
||||
}
|
||||
} else {
|
||||
OccurrenceBody::Action {
|
||||
action: Some(id(if suffix == "a" || suffix == "c" {
|
||||
&shared
|
||||
} else {
|
||||
&downstream
|
||||
})),
|
||||
lifeline: None,
|
||||
}
|
||||
};
|
||||
occurrence(
|
||||
&mut p,
|
||||
&format!("{prefix}_{suffix}"),
|
||||
label,
|
||||
layer,
|
||||
owner,
|
||||
body,
|
||||
);
|
||||
}
|
||||
let order: Vec<_> = ["a", "u", "b", "v", "c"]
|
||||
.map(|suffix| format!("{prefix}_{suffix}"))
|
||||
.into_iter()
|
||||
.collect();
|
||||
set_steps(
|
||||
&mut p,
|
||||
owner,
|
||||
&order.iter().map(String::as_str).collect::<Vec<_>>(),
|
||||
);
|
||||
sequence_link(
|
||||
&mut p,
|
||||
&format!("{prefix}_a_u"),
|
||||
"A to U",
|
||||
&format!("{prefix}_a"),
|
||||
&format!("{prefix}_u"),
|
||||
)?;
|
||||
sequence_link(
|
||||
&mut p,
|
||||
&format!("{prefix}_b_v"),
|
||||
"B to V",
|
||||
&format!("{prefix}_b"),
|
||||
&format!("{prefix}_v"),
|
||||
)?;
|
||||
}
|
||||
element(
|
||||
&mut p,
|
||||
"reusable",
|
||||
"Reusable request detail",
|
||||
Kind::Process,
|
||||
Layer::Oa,
|
||||
None,
|
||||
);
|
||||
occurrence(
|
||||
&mut p,
|
||||
"reused_leaf",
|
||||
"Shared detail",
|
||||
Layer::Oa,
|
||||
"reusable",
|
||||
OccurrenceBody::Action {
|
||||
action: Some(id("oa_shared_work")),
|
||||
lifeline: None,
|
||||
},
|
||||
);
|
||||
set_steps(&mut p, "reusable", &["reused_leaf"]);
|
||||
element(
|
||||
&mut p,
|
||||
"reuse_trial",
|
||||
"02 Read-only preview trial",
|
||||
Kind::Process,
|
||||
Layer::Oa,
|
||||
None,
|
||||
);
|
||||
for (alias, name) in [
|
||||
("reference_one", "First use"),
|
||||
("reference_two", "Second use"),
|
||||
] {
|
||||
occurrence(
|
||||
&mut p,
|
||||
alias,
|
||||
name,
|
||||
Layer::Oa,
|
||||
"reuse_trial",
|
||||
OccurrenceBody::SequenceReference {
|
||||
sequence: Some(id("reusable")),
|
||||
},
|
||||
);
|
||||
}
|
||||
set_steps(&mut p, "reuse_trial", &["reference_one", "reference_two"]);
|
||||
p.traces.insert(
|
||||
id("trace"),
|
||||
Trace {
|
||||
id: id("trace"),
|
||||
alias: "preserved_work_refinement".into(),
|
||||
name: "Shared request refinement".into(),
|
||||
description: "Process arrangement must preserve cross-layer correspondence.".into(),
|
||||
oa: id("oa_shared_work"),
|
||||
sa: id("sa_shared_work"),
|
||||
kind: TraceKind::Refinement,
|
||||
baseline: Some(TraceBaseline {
|
||||
oa: p.properties(id("oa_shared_work")).unwrap(),
|
||||
sa: p.properties(id("sa_shared_work")).unwrap(),
|
||||
semantic: None,
|
||||
}),
|
||||
},
|
||||
);
|
||||
validate_candidate(&p)?;
|
||||
Ok(p)
|
||||
}
|
||||
fn load(path: &Path) -> Result<Project> {
|
||||
if path
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("arcadia"))
|
||||
{
|
||||
let disk = source_files::load_project(path, ProjectLimits::default())?;
|
||||
if disk
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.diagnostic.severity == validation::Severity::Error)
|
||||
{
|
||||
return Err(format!("Source discovery diagnostics: {:?}", disk.diagnostics).into());
|
||||
}
|
||||
let compiled = compile_bundle(&disk.reachable_bundle(), ProjectLimits::default())
|
||||
.map_err(|e| format!("Source compile diagnostics: {e:?}"))?;
|
||||
Ok(compiled.decoded.project)
|
||||
} else {
|
||||
Ok(persistence::load(path)?)
|
||||
}
|
||||
}
|
||||
fn equal(expected: &Project, actual: &Project) -> Result<()> {
|
||||
if expected == actual {
|
||||
return Ok(());
|
||||
}
|
||||
let expected = serde_json::to_value(expected)?;
|
||||
let actual = serde_json::to_value(actual)?;
|
||||
let fields: Vec<_> = expected
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.filter(|key| expected[*key] != actual[*key])
|
||||
.cloned()
|
||||
.collect();
|
||||
Err(format!("Whole Project mismatch in {fields:?}; no partial PASS").into())
|
||||
}
|
||||
fn roundtrip(p: &Project) -> Result<SourceBundle> {
|
||||
validate_candidate(p)?;
|
||||
equal(p, &persistence::decode(&serde_json::to_vec(p)?)?)?;
|
||||
let bundle = format_bundle(p);
|
||||
let compiled = compile_bundle(&bundle, ProjectLimits::default())
|
||||
.map_err(|e| format!("Roundtrip: {e:?}"))?;
|
||||
equal(p, &compiled.decoded.project)?;
|
||||
Ok(bundle)
|
||||
}
|
||||
fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
fs::create_dir_all(path.parent().ok_or("Missing parent directory")?)?;
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)?
|
||||
.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
fn generate(out: &Path) -> Result<()> {
|
||||
if out.exists() {
|
||||
return Err("Output directory already exists; choose a fresh path".into());
|
||||
}
|
||||
let p = fixture()?;
|
||||
let bundle = roundtrip(&p)?;
|
||||
write_new(&out.join("baseline.json"), &serde_json::to_vec_pretty(&p)?)?;
|
||||
for (path, source) in &bundle.files {
|
||||
write_new(&out.join("source").join(path), source.as_bytes())?;
|
||||
}
|
||||
let ids: std::collections::BTreeMap<_, _> = [
|
||||
"project",
|
||||
"oa_process",
|
||||
"oa_a",
|
||||
"oa_u",
|
||||
"oa_b",
|
||||
"oa_v",
|
||||
"oa_c",
|
||||
"oa_a_u",
|
||||
"oa_b_v",
|
||||
"oa_shared_work",
|
||||
"oa_downstream_work",
|
||||
"sa_chain",
|
||||
"sa_shared_work",
|
||||
"sa_downstream_work",
|
||||
"sa_a",
|
||||
"sa_u",
|
||||
"sa_b",
|
||||
"sa_v",
|
||||
"sa_c",
|
||||
"sa_a_u",
|
||||
"sa_b_v",
|
||||
"trace",
|
||||
"reusable",
|
||||
"reused_leaf",
|
||||
"reuse_trial",
|
||||
"reference_one",
|
||||
"reference_two",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|name| (name, id(name)))
|
||||
.collect();
|
||||
write_new(
|
||||
&out.join("manifest.json"),
|
||||
&serde_json::to_vec_pretty(&serde_json::json!({
|
||||
"fixture": "process-multiselect-native-20260923", "ids": ids, "source_entry": bundle.entry,
|
||||
"original_oa_steps": ["oa_a", "oa_u", "oa_b", "oa_v", "oa_c"],
|
||||
"reordered_oa_steps": ["oa_b", "oa_u", "oa_a", "oa_v", "oa_c"],
|
||||
"gesture": "Select Card C then add Card A; Inspect Card C without changing membership, then drag Card C to After Card B",
|
||||
"fixed_slots": {"1": "oa_u", "3": "oa_v"},
|
||||
"read_only_trial": "02 Read-only preview trial has two qualified tiles of reused_leaf through distinct references",
|
||||
"receipt": "Pin baseline.json, manifest.json and generation command externally before interaction. Never replace baseline with a later saved snapshot.",
|
||||
"evaluation": "Literal expected OA steps and complete Project equality; all SA/reuse/trace records exact",
|
||||
"limits": "No pointer, focus, selection-paint, history or source-byte acceptance claim",
|
||||
}))?,
|
||||
)?;
|
||||
equal(&p, &load(&out.join("baseline.json"))?)?;
|
||||
equal(&p, &load(&out.join("source").join(&bundle.entry))?)?;
|
||||
println!("PASS generated JSON and source bundle: {}", out.display());
|
||||
Ok(())
|
||||
}
|
||||
fn check(mode: &str, baseline: &Path, saved: &Path) -> Result<()> {
|
||||
let before = load(baseline)?;
|
||||
let actual = load(saved)?;
|
||||
validate_candidate(&before)?;
|
||||
validate_candidate(&actual)?;
|
||||
// Pin the exact deterministic original, not merely a reusable project UUID.
|
||||
equal(&fixture()?, &before)
|
||||
.map_err(|e| format!("Baseline is not the immutable original: {e}"))?;
|
||||
let mut expected = before;
|
||||
match mode {
|
||||
"unchanged" => {}
|
||||
"reordered" => set_steps(
|
||||
&mut expected,
|
||||
"oa_process",
|
||||
&["oa_b", "oa_u", "oa_a", "oa_v", "oa_c"],
|
||||
),
|
||||
_ => return Err("Mode must be reordered or unchanged".into()),
|
||||
}
|
||||
equal(&expected, &actual)?;
|
||||
roundtrip(&actual)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"result": "PASS", "mode": mode, "baseline": baseline, "saved": saved,
|
||||
"comparison": "complete Project equality; literal expected order",
|
||||
"limits": "No pointer/action/focus/Undo/source-byte acceptance claim",
|
||||
}))?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
match args.as_slice() {
|
||||
[command, out] if command == "generate" => generate(Path::new(out)),
|
||||
[command, mode, baseline, saved] if command == "check" => check(mode, Path::new(baseline), Path::new(saved)),
|
||||
_ => Err("Usage: process_multiselect_native generate DIRECTORY | check reordered|unchanged BASELINE SAVED".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn reordered(before: &Project) -> Project {
|
||||
let mut session = Session::new(before.clone());
|
||||
session
|
||||
.execute(Command::SetSteps(
|
||||
id("oa_process"),
|
||||
["oa_b", "oa_u", "oa_a", "oa_v", "oa_c"].map(id).to_vec(),
|
||||
))
|
||||
.unwrap();
|
||||
session.project().clone()
|
||||
}
|
||||
fn through_json(mode: &str, baseline: &Project, actual: &Project) -> Result<()> {
|
||||
validate_candidate(baseline).expect("Baseline must be valid");
|
||||
validate_candidate(actual).expect("Corruption must remain semantically valid");
|
||||
let dir = tempfile::tempdir()?;
|
||||
let before = dir.path().join("before.json");
|
||||
let saved = dir.path().join("saved.json");
|
||||
persistence::save(&before, baseline)?;
|
||||
persistence::save(&saved, actual)?;
|
||||
check(mode, &before, &saved)
|
||||
}
|
||||
fn mismatch(before: &Project, actual: &Project) {
|
||||
let error = through_json("reordered", before, actual)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(
|
||||
error.contains("Whole Project mismatch"),
|
||||
"Unexpected rejection: {error}"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn generate_is_deterministic_create_only_and_checks_real_source() {
|
||||
equal(&fixture().unwrap(), &fixture().unwrap()).unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let out = dir.path().join("fixture");
|
||||
generate(&out).unwrap();
|
||||
let baseline = out.join("baseline.json");
|
||||
let bytes = fs::read(&baseline).unwrap();
|
||||
check("unchanged", &baseline, &out.join("source/project.arcadia")).unwrap();
|
||||
assert!(generate(&out).is_err());
|
||||
assert_eq!(fs::read(&baseline).unwrap(), bytes);
|
||||
let invalid = dir.path().join("invalid.arcadia");
|
||||
fs::write(&invalid, "project {").unwrap();
|
||||
assert!(load(&invalid).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn real_set_steps_passes_but_unchanged_and_mutated_baseline_do_not() {
|
||||
let before = fixture().unwrap();
|
||||
let actual = reordered(&before);
|
||||
through_json("reordered", &before, &actual).unwrap();
|
||||
through_json("unchanged", &before, &before).unwrap();
|
||||
mismatch(&before, &before);
|
||||
assert!(through_json("unchanged", &before, &actual).is_err());
|
||||
let error = through_json("unchanged", &actual, &actual)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("immutable original"), "{error}");
|
||||
}
|
||||
#[test]
|
||||
fn global_splice_reversed_block_and_singleton_c_results_are_rejected() {
|
||||
let before = fixture().unwrap();
|
||||
// Native primary/pressed C is already after B, so a singleton C move
|
||||
// is unchanged. Group {C,A} instead puts B before both selected cards.
|
||||
// If A were primary, its singleton result could equal the group result.
|
||||
mismatch(&before, &before);
|
||||
for order in [
|
||||
["oa_u", "oa_b", "oa_a", "oa_c", "oa_v"],
|
||||
["oa_b", "oa_u", "oa_c", "oa_v", "oa_a"],
|
||||
["oa_a", "oa_u", "oa_b", "oa_c", "oa_v"],
|
||||
] {
|
||||
let mut actual = before.clone();
|
||||
set_steps(&mut actual, "oa_process", &order);
|
||||
mismatch(&before, &actual);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn semantic_link_work_sa_reuse_and_trace_changes_are_rejected() {
|
||||
let before = fixture().unwrap();
|
||||
let correct = reordered(&before);
|
||||
let mutations: [fn(&mut Project); 7] = [
|
||||
|p| {
|
||||
if let RelationBody::SequenceLink { guard, .. } =
|
||||
&mut p.relations.get_mut(&id("oa_a_u")).unwrap().body
|
||||
{
|
||||
*guard = "changed".into();
|
||||
}
|
||||
},
|
||||
|p| {
|
||||
if let RelationBody::SequenceLink { target, .. } =
|
||||
&mut p.relations.get_mut(&id("oa_a_u")).unwrap().body
|
||||
{
|
||||
*target = id("oa_v");
|
||||
}
|
||||
},
|
||||
|p| {
|
||||
p.elements
|
||||
.get_mut(&id("oa_shared_work"))
|
||||
.unwrap()
|
||||
.name
|
||||
.push_str(" drift");
|
||||
},
|
||||
|p| {
|
||||
p.elements
|
||||
.get_mut(&id("sa_shared_work"))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift");
|
||||
},
|
||||
|p| {
|
||||
set_steps(p, "sa_chain", &["sa_b", "sa_u", "sa_a", "sa_v", "sa_c"]);
|
||||
},
|
||||
|p| {
|
||||
p.elements
|
||||
.get_mut(&id("reused_leaf"))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift");
|
||||
},
|
||||
|p| {
|
||||
p.traces.get_mut(&id("trace")).unwrap().baseline = None;
|
||||
},
|
||||
];
|
||||
for mutate in mutations {
|
||||
let mut bad = correct.clone();
|
||||
mutate(&mut bad);
|
||||
mismatch(&before, &bad);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn changed_source_roundtrip_preserves_both_layers_and_checker_rejects_source_drift() {
|
||||
let before = fixture().unwrap();
|
||||
let actual = reordered(&before);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let baseline = dir.path().join("baseline.json");
|
||||
persistence::save(&baseline, &before).unwrap();
|
||||
for corrupt in [false, true] {
|
||||
let mut saved = actual.clone();
|
||||
if corrupt {
|
||||
saved
|
||||
.elements
|
||||
.get_mut(&id("sa_c"))
|
||||
.unwrap()
|
||||
.name
|
||||
.push_str(" drift");
|
||||
}
|
||||
let bundle = roundtrip(&saved).unwrap();
|
||||
let folder = dir.path().join(if corrupt { "corrupt" } else { "saved" });
|
||||
for (path, text) in &bundle.files {
|
||||
write_new(&folder.join(path), text.as_bytes()).unwrap();
|
||||
}
|
||||
let parsed = load(&folder.join(&bundle.entry)).unwrap();
|
||||
assert_eq!(parsed.elements[&id("oa_process")].kind(), Kind::Process);
|
||||
assert_eq!(
|
||||
parsed.elements[&id("sa_chain")].kind(),
|
||||
Kind::FunctionalChain
|
||||
);
|
||||
let result = check("reordered", &baseline, &folder.join(&bundle.entry));
|
||||
if corrupt {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Whole Project mismatch")
|
||||
);
|
||||
} else {
|
||||
result.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -230,7 +230,7 @@ fn fixture() -> (Project, Id, Vec<Id>, Vec<Id>, Vec<Id>) {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
p.diagrams.insert(diagram, Diagram { id: diagram, alias: "forty_exchange_view".into(), name: "Forty service exchanges · all concerns".into(), description: "Start with All. Compare first category, overlapping concerns, global coverage and chosen processes. No hand-routed edges.".into(), layer: Layer::Oa, projection: ProjectionKind::FunctionalDataflow, view_options: ViewOptions::default(), nodes, routes: vec![] });
|
||||
p.diagrams.insert(diagram, Diagram { id: diagram, alias: "forty_exchange_view".into(), name: "Forty service exchanges · all concerns".into(), description: "Start with All. Compare first category, overlapping concerns, global coverage and chosen processes. No hand-routed edges.".into(), layer: Layer::Oa, projection: ProjectionKind::FunctionalDataflow, view_options: ViewOptions::default(), nodes, layout: None, routes: vec![] });
|
||||
(p, diagram, exchanges, categories, contexts)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Read-only saved-State geometry evidence for a predeclared native bend trial.
|
||||
//!
|
||||
//! Usage:
|
||||
//! state_bend_routing_snapshot INPUT.arcadia NEW_OUTPUT.json
|
||||
//!
|
||||
//! Loads and validates the complete Project, then independently projects/routes
|
||||
//! every saved State view through core APIs. The complete Project permits exact
|
||||
//! semantic and presentation comparison; derived geometry permits declaring a
|
||||
//! segment and insertion position before native actions. No desktop command,
|
||||
//! planner, gesture, or pin insertion helper is called. Input is never written;
|
||||
//! output uses create_new and fails rather than overwriting an existing file.
|
||||
//!
|
||||
//! Limits: this shares production core routing, so it is not an independent
|
||||
//! mathematical test of that router, nor evidence of UI picking/gesture success.
|
||||
//! It does not generate expected mutations or adapt an oracle to observed edits.
|
||||
//! The acceptance recipe must declare the intended segment/index/point and exact
|
||||
//! Project mutation before UI execution, and bind this executable/source/input
|
||||
//! and output hashes externally. Warning strings are diagnostic Debug output,
|
||||
//! not a stable interchange schema. Missing/hidden/internal transitions have no
|
||||
//! routed edge; their semantic records remain in the complete Project snapshot.
|
||||
|
||||
use oa_core::{persistence, projection, routing, validate_candidate};
|
||||
use serde_json::json;
|
||||
use std::{fs::OpenOptions, io::Write, path::Path};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
if args.len() != 2 {
|
||||
return Err("Expected input source/JSON and a new output JSON path".into());
|
||||
}
|
||||
let project = persistence::load(Path::new(&args[0]))?;
|
||||
validate_candidate(&project)?;
|
||||
let mut views = Vec::new();
|
||||
for (diagram_id, diagram) in &project.diagrams {
|
||||
let Some(machine) = diagram.projection.state_machine() else {
|
||||
continue;
|
||||
};
|
||||
let projected = projection::project_diagram(&project, diagram);
|
||||
let routed = routing::route_diagram(&project, diagram, &projected);
|
||||
let edges: Vec<_> = routed
|
||||
.edges
|
||||
.iter()
|
||||
.map(|(edge_id, edge)| {
|
||||
json!({
|
||||
"edge": edge_id,
|
||||
"id": edge.id,
|
||||
"points": edge.points,
|
||||
"pins": edge.pins,
|
||||
"pin_fractions": edge.pin_fractions,
|
||||
"custom_suspended": edge.custom_suspended,
|
||||
"warnings": edge.warnings.iter().map(|warning| format!("{warning:?}")).collect::<Vec<_>>(),
|
||||
"label": {
|
||||
"text": edge.label.text,
|
||||
"fraction": edge.label.fraction,
|
||||
"anchor": edge.label.anchor,
|
||||
"center": edge.label.center,
|
||||
"bounds": {
|
||||
"position": edge.label.bounds.position,
|
||||
"size": edge.label.bounds.size
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
views.push(json!({
|
||||
"diagram": diagram_id,
|
||||
"machine": machine,
|
||||
"projected": projected,
|
||||
"routed_bounds": {
|
||||
"position": routed.bounds.position,
|
||||
"size": routed.bounds.size
|
||||
},
|
||||
"routed_edges": edges
|
||||
}));
|
||||
}
|
||||
// Preserve the canonical typed Project serialization (including f32
|
||||
// formatting). Serializing it through Value directly promotes f32 to f64.
|
||||
let project_json: serde_json::Value = serde_json::from_slice(&serde_json::to_vec(&project)?)?;
|
||||
let snapshot = json!({
|
||||
"schema": "state-bend-routing-snapshot/v1",
|
||||
"project": project_json,
|
||||
"state_views": views
|
||||
});
|
||||
// Finish all reading, validation, routing and serialization before creating
|
||||
// the new evidence file. A failed load cannot leave an apparent snapshot.
|
||||
let mut bytes = serde_json::to_vec_pretty(&snapshot)?;
|
||||
bytes.push(b'\n');
|
||||
let mut output = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&args[1])?;
|
||||
output.write_all(&bytes)?;
|
||||
output.sync_all()?;
|
||||
println!(
|
||||
"Validated {} objects and {} saved views; snapshotted {} State views and the complete Project",
|
||||
project.identities().len(),
|
||||
project.diagrams.len(),
|
||||
views.len()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,912 @@
|
||||
//! Deterministic persisted-State native fixture and complete-Project checker.
|
||||
//! This invariant evaluator derives delta from saved A, NOT from pointer input.
|
||||
use oa_core::{source_project::*, *};
|
||||
use std::{fs, io::Write, path::Path};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn id(alias: &str) -> Id {
|
||||
// Dedicated State view is the smallest diagram UUID, for native opening.
|
||||
if alias == "state_view" {
|
||||
return Id::from_u128(0x29_0101);
|
||||
}
|
||||
Id::new_v5(
|
||||
&Id::from_u128(0xc1192026_0923_5000_8000_000000002929),
|
||||
alias.as_bytes(),
|
||||
)
|
||||
}
|
||||
fn point(x: f32, y: f32) -> Position {
|
||||
Position { x, y }
|
||||
}
|
||||
fn element(p: &mut Project, alias: &str, name: &str, kind: Kind, layer: Layer, parent: Option<Id>) {
|
||||
p.elements.insert(
|
||||
id(alias),
|
||||
Element {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: format!("Preserve engineering record {alias}."),
|
||||
parent,
|
||||
body: ElementBody::new(kind, layer).unwrap(),
|
||||
},
|
||||
);
|
||||
}
|
||||
fn diagram(p: &mut Project, alias: &str, name: &str, layer: Layer) {
|
||||
p.diagrams.insert(
|
||||
id(alias),
|
||||
Diagram {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: "Selection changes placement geometry only.".into(),
|
||||
layer,
|
||||
projection: ProjectionKind::Overview,
|
||||
view_options: Default::default(),
|
||||
layout: None,
|
||||
nodes: Default::default(),
|
||||
routes: vec![],
|
||||
},
|
||||
);
|
||||
}
|
||||
fn place(p: &mut Project, view: &str, alias: &str, object: &str, position: Position, size: Size) {
|
||||
p.diagrams.get_mut(&id(view)).unwrap().nodes.insert(
|
||||
id(alias),
|
||||
NodePlacement {
|
||||
id: id(alias),
|
||||
alias: alias.into(),
|
||||
element: id(object),
|
||||
position,
|
||||
size,
|
||||
collapsed: false,
|
||||
port_anchors: vec![],
|
||||
},
|
||||
);
|
||||
}
|
||||
fn route(edge: &str, pins: Vec<Position>) -> EdgeRoute {
|
||||
EdgeRoute {
|
||||
edge: id(edge),
|
||||
waypoints: pins,
|
||||
source_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Right,
|
||||
offset: 0.25,
|
||||
}),
|
||||
target_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Left,
|
||||
offset: 0.7,
|
||||
}),
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.45,
|
||||
offset: point(7., -19.),
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn transition(
|
||||
p: &mut Project,
|
||||
alias: &str,
|
||||
name: &str,
|
||||
source: &str,
|
||||
target: &str,
|
||||
kind: TransitionKind,
|
||||
) -> Result<()> {
|
||||
let old = p.relate(RelationKind::StateTransition, name, id(source), id(target));
|
||||
reidentify(p, old, id(alias))?;
|
||||
let relation = p.relations.get_mut(&id(alias)).unwrap();
|
||||
relation.alias = alias.into();
|
||||
relation.description = format!("Preserve transition {alias}.");
|
||||
if let RelationBody::StateTransition {
|
||||
transition_kind,
|
||||
guard,
|
||||
..
|
||||
} = &mut relation.body
|
||||
{
|
||||
*transition_kind = kind;
|
||||
*guard = if alias == "between" {
|
||||
"request_ready"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
.into();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn fixture() -> Result<Project> {
|
||||
let mut p = Project::empty();
|
||||
p.id = id("project");
|
||||
p.alias = "state_multiselect_native".into();
|
||||
p.name = "State group native".into();
|
||||
p.description = "Shift-select A and B; move their placements together. C and shared engineering records stay fixed.".into();
|
||||
for (alias, name, kind, parent) in [
|
||||
("crew", "Operations crew", Kind::Entity, None),
|
||||
(
|
||||
"machine",
|
||||
"Request lifecycle",
|
||||
Kind::StateMachine,
|
||||
Some(id("crew")),
|
||||
),
|
||||
("region", "Main region", Kind::Region, Some(id("machine"))),
|
||||
("state_a", "A - Processing", Kind::State, Some(id("region"))),
|
||||
("state_b", "B - Ready", Kind::State, Some(id("region"))),
|
||||
("state_c", "C - Complete", Kind::State, Some(id("region"))),
|
||||
(
|
||||
"inner",
|
||||
"A nested region",
|
||||
Kind::Region,
|
||||
Some(id("state_a")),
|
||||
),
|
||||
(
|
||||
"state_leaf",
|
||||
"A.1 - Classify",
|
||||
Kind::State,
|
||||
Some(id("inner")),
|
||||
),
|
||||
("entry", "Enter A", Kind::EntryPoint, Some(id("inner"))),
|
||||
("exit", "Leave A", Kind::ExitPoint, Some(id("inner"))),
|
||||
("shared_work", "Record request", Kind::Activity, None),
|
||||
] {
|
||||
element(&mut p, alias, name, kind, Layer::Oa, parent);
|
||||
}
|
||||
element(
|
||||
&mut p,
|
||||
"sa_function",
|
||||
"Technical record request",
|
||||
Kind::Function,
|
||||
Layer::Sa,
|
||||
None,
|
||||
);
|
||||
for (alias, name, source, target, kind) in [
|
||||
(
|
||||
"between",
|
||||
"Ready\nfor review",
|
||||
"state_a",
|
||||
"state_b",
|
||||
TransitionKind::External,
|
||||
),
|
||||
(
|
||||
"external",
|
||||
"Complete request",
|
||||
"state_b",
|
||||
"state_c",
|
||||
TransitionKind::External,
|
||||
),
|
||||
(
|
||||
"entry_route",
|
||||
"Begin classification",
|
||||
"entry",
|
||||
"state_leaf",
|
||||
TransitionKind::Local,
|
||||
),
|
||||
(
|
||||
"exit_route",
|
||||
"Classification complete",
|
||||
"state_leaf",
|
||||
"exit",
|
||||
TransitionKind::External,
|
||||
),
|
||||
(
|
||||
"refresh",
|
||||
"Refresh record",
|
||||
"state_a",
|
||||
"state_a",
|
||||
TransitionKind::Internal,
|
||||
),
|
||||
] {
|
||||
transition(&mut p, alias, name, source, target, kind)?;
|
||||
}
|
||||
for (alias, source, phase) in [
|
||||
("action_a", "state_a", StateActionKind::Entry),
|
||||
("action_c", "state_c", StateActionKind::Do),
|
||||
] {
|
||||
let old = p.relate(
|
||||
RelationKind::StateAction,
|
||||
"Record shared work",
|
||||
id(source),
|
||||
id("shared_work"),
|
||||
);
|
||||
reidentify(&mut p, old, id(alias))?;
|
||||
let relation = p.relations.get_mut(&id(alias)).unwrap();
|
||||
relation.alias = alias.into();
|
||||
relation.description = format!("Preserve shared-work action {alias}.");
|
||||
if let RelationBody::StateAction { phase: value, .. } = &mut relation.body {
|
||||
*value = phase;
|
||||
}
|
||||
}
|
||||
for (alias, name) in [
|
||||
("state_view", "State multiselect - main"),
|
||||
("state_other", "Other State view - preserve"),
|
||||
] {
|
||||
diagram(&mut p, alias, name, Layer::Oa);
|
||||
p.diagrams.get_mut(&id(alias)).unwrap().projection = ProjectionKind::StateMachine {
|
||||
machine: id("machine"),
|
||||
};
|
||||
}
|
||||
diagram(&mut p, "sa_view", "SA engineering - preserve", Layer::Sa);
|
||||
// The main machine and outer Region are deliberately unplaced to keep
|
||||
// the target headers readable in a 1442 x 932 native window after Fit.
|
||||
// A starts at the authored origin so saved A recovers the exact f32 delta;
|
||||
// subtracting a nonzero original can round it differently from sibling XY.
|
||||
for (alias, object, x, y, width, height) in [
|
||||
("node_a", "state_a", 0., 0., 340., 450.),
|
||||
("node_b", "state_b", 410., 30., 210., 150.),
|
||||
("node_c", "state_c", 410., 330., 210., 140.),
|
||||
("node_inner", "inner", 25., 220., 290., 200.),
|
||||
("node_leaf", "state_leaf", 60., 290., 180., 90.),
|
||||
("node_entry", "entry", -210., 280., 24., 24.),
|
||||
("node_exit", "exit", 870., 350., 24., 24.),
|
||||
] {
|
||||
place(
|
||||
&mut p,
|
||||
"state_view",
|
||||
alias,
|
||||
object,
|
||||
point(x, y),
|
||||
Size { width, height },
|
||||
);
|
||||
}
|
||||
let size = Size {
|
||||
width: 224.,
|
||||
height: 94.,
|
||||
};
|
||||
place(
|
||||
&mut p,
|
||||
"state_other",
|
||||
"other_a",
|
||||
"state_a",
|
||||
point(40., 60.),
|
||||
Size {
|
||||
width: 340.,
|
||||
height: 220.,
|
||||
},
|
||||
);
|
||||
place(
|
||||
&mut p,
|
||||
"state_other",
|
||||
"other_b",
|
||||
"state_b",
|
||||
point(460., 80.),
|
||||
size,
|
||||
);
|
||||
place(
|
||||
&mut p,
|
||||
"sa_view",
|
||||
"sa_node",
|
||||
"sa_function",
|
||||
point(100., 110.),
|
||||
size,
|
||||
);
|
||||
p.diagrams.get_mut(&id("state_view")).unwrap().routes = vec![
|
||||
route("between", vec![point(365., 70.), point(365., 120.)]),
|
||||
route("external", vec![point(660., 140.), point(660., 360.)]),
|
||||
route("entry_route", vec![point(40., 280.), point(40., 320.)]),
|
||||
route("exit_route", vec![point(290., 335.), point(290., 370.)]),
|
||||
];
|
||||
p.traces.insert(
|
||||
id("trace"),
|
||||
Trace {
|
||||
id: id("trace"),
|
||||
alias: "preserved_refinement".into(),
|
||||
name: "Reviewed recording refinement".into(),
|
||||
description:
|
||||
"Moving states or hiding placements must preserve shared work and its refinement."
|
||||
.into(),
|
||||
oa: id("shared_work"),
|
||||
sa: id("sa_function"),
|
||||
kind: TraceKind::Refinement,
|
||||
baseline: Some(TraceBaseline {
|
||||
oa: p.properties(id("shared_work")).unwrap(),
|
||||
sa: p.properties(id("sa_function")).unwrap(),
|
||||
semantic: None,
|
||||
}),
|
||||
},
|
||||
);
|
||||
validate_candidate(&p)?;
|
||||
Ok(p)
|
||||
}
|
||||
fn load(path: &Path) -> Result<Project> {
|
||||
if path
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("arcadia"))
|
||||
{
|
||||
let disk = source_files::load_project(path, ProjectLimits::default())?;
|
||||
// This deliberately partial engineering fixture has completeness
|
||||
// warnings (allocation/behavior context). They are not source errors.
|
||||
// Compilation, candidate validation and whole-Project equality still
|
||||
// reject malformed source or any unexpected model change.
|
||||
if disk
|
||||
.diagnostics
|
||||
.iter()
|
||||
.any(|d| d.diagnostic.severity == validation::Severity::Error)
|
||||
{
|
||||
return Err(format!("Source discovery diagnostics: {:?}", disk.diagnostics).into());
|
||||
}
|
||||
let compiled = compile_bundle(&disk.reachable_bundle(), ProjectLimits::default())
|
||||
.map_err(|e| format!("Source compile diagnostics: {e:?}"))?;
|
||||
Ok(compiled.decoded.project)
|
||||
} else {
|
||||
Ok(persistence::load(path)?)
|
||||
}
|
||||
}
|
||||
fn equal(expected: &Project, actual: &Project) -> Result<()> {
|
||||
if expected == actual {
|
||||
return Ok(());
|
||||
}
|
||||
let e = serde_json::to_value(expected)?;
|
||||
let a = serde_json::to_value(actual)?;
|
||||
let fields: Vec<_> = e
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.keys()
|
||||
.filter(|key| e[*key] != a[*key])
|
||||
.cloned()
|
||||
.collect();
|
||||
Err(format!("Whole Project mismatch in {fields:?}; no partial PASS").into())
|
||||
}
|
||||
fn roundtrip(p: &Project) -> Result<SourceBundle> {
|
||||
validate_candidate(p)?;
|
||||
equal(p, &persistence::decode(&serde_json::to_vec(p)?)?)?;
|
||||
let bundle = format_bundle(p);
|
||||
let compiled = compile_bundle(&bundle, ProjectLimits::default())
|
||||
.map_err(|e| format!("Roundtrip: {e:?}"))?;
|
||||
equal(p, &compiled.decoded.project)?;
|
||||
Ok(bundle)
|
||||
}
|
||||
fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
fs::create_dir_all(path.parent().ok_or("Missing parent directory")?)?;
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)?
|
||||
.write_all(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
fn generate(out: &Path) -> Result<()> {
|
||||
if out.exists() {
|
||||
return Err("Output directory already exists; choose a fresh path".into());
|
||||
}
|
||||
let p = fixture()?;
|
||||
let bundle = roundtrip(&p)?;
|
||||
write_new(&out.join("baseline.json"), &serde_json::to_vec_pretty(&p)?)?;
|
||||
for (path, source) in &bundle.files {
|
||||
write_new(&out.join("source").join(path), source.as_bytes())?;
|
||||
}
|
||||
let names = [
|
||||
"crew",
|
||||
"machine",
|
||||
"region",
|
||||
"inner",
|
||||
"entry",
|
||||
"exit",
|
||||
"shared_work",
|
||||
"node_inner",
|
||||
"node_entry",
|
||||
"node_exit",
|
||||
"entry_route",
|
||||
"exit_route",
|
||||
"refresh",
|
||||
"action_a",
|
||||
"action_c",
|
||||
"other_b",
|
||||
"project",
|
||||
"state_view",
|
||||
"state_other",
|
||||
"sa_view",
|
||||
"state_a",
|
||||
"state_b",
|
||||
"state_c",
|
||||
"state_leaf",
|
||||
"node_a",
|
||||
"node_b",
|
||||
"node_c",
|
||||
"node_leaf",
|
||||
"between",
|
||||
"external",
|
||||
"trace",
|
||||
"sa_function",
|
||||
"sa_node",
|
||||
"other_a",
|
||||
];
|
||||
let ids: std::collections::BTreeMap<_, _> =
|
||||
names.into_iter().map(|name| (name, id(name))).collect();
|
||||
write_new(
|
||||
&out.join("manifest.json"),
|
||||
&serde_json::to_vec_pretty(&serde_json::json!({
|
||||
"fixture": "state-multiselect-native-20260923", "ids": ids, "source_entry": bundle.entry,
|
||||
"move_members": ["node_a", "node_b", "node_inner", "node_leaf", "node_entry", "node_exit"],
|
||||
"translated_routes": ["between", "entry_route", "exit_route"],
|
||||
"fixed_route": "external",
|
||||
"window": [1442, 932],
|
||||
"target_headers_world": {"A": [40, 35], "B": [450, 65]},
|
||||
"delta_limits": "finite, nonzero length >=0.01, each axis <=300; no grid quantization",
|
||||
"receipt": "Pin baseline.json, manifest.json and generation command externally before interaction; baseline identity alone does not authenticate evidence", "fixed_member": "node_c",
|
||||
"evaluation": "Whole Project invariant comparison; saved A supplies bounded shared delta, not an exact pointer oracle",
|
||||
"hide": "Remove node_a/node_b only; retain nested Region/leaf/entry/exit, stored routes, all model records and other views",
|
||||
}))?,
|
||||
)?;
|
||||
equal(&p, &load(&out.join("baseline.json"))?)?;
|
||||
equal(&p, &load(&out.join("source/project.arcadia"))?)?;
|
||||
println!("PASS generated JSON and source bundle: {}", out.display());
|
||||
Ok(())
|
||||
}
|
||||
fn check(mode: &str, baseline: &Path, saved: &Path) -> Result<()> {
|
||||
let before = load(baseline)?;
|
||||
let actual = load(saved)?;
|
||||
validate_candidate(&before)?;
|
||||
validate_candidate(&actual)?;
|
||||
if before.id != id("project") {
|
||||
return Err("Not this fixture's baseline project".into());
|
||||
}
|
||||
let mut expected = before.clone();
|
||||
let mut delta = None;
|
||||
match mode {
|
||||
"unchanged" => {}
|
||||
"hide" => {
|
||||
let view = expected
|
||||
.diagrams
|
||||
.get_mut(&id("state_view"))
|
||||
.ok_or("Missing State view")?;
|
||||
for alias in ["node_a", "node_b"] {
|
||||
view.nodes
|
||||
.remove(&id(alias))
|
||||
.ok_or("Baseline selected placement missing")?;
|
||||
}
|
||||
// references::remove_objects removes routes only when their semantic
|
||||
// edge is deleted. Hide deletes placements; both routes MUST survive.
|
||||
}
|
||||
"moved" => {
|
||||
let old = before
|
||||
.diagrams
|
||||
.get(&id("state_view"))
|
||||
.ok_or("Missing baseline State view")?;
|
||||
let new = actual
|
||||
.diagrams
|
||||
.get(&id("state_view"))
|
||||
.ok_or("Missing saved State view")?;
|
||||
let a = old
|
||||
.nodes
|
||||
.get(&id("node_a"))
|
||||
.ok_or("Missing baseline A")?
|
||||
.position;
|
||||
let moved_a = new
|
||||
.nodes
|
||||
.get(&id("node_a"))
|
||||
.ok_or("Missing saved A")?
|
||||
.position;
|
||||
let d = point(moved_a.x - a.x, moved_a.y - a.y);
|
||||
if !d.x.is_finite()
|
||||
|| !d.y.is_finite()
|
||||
|| d.x.abs().max(d.y.abs()) > 300.
|
||||
|| d.x.hypot(d.y) < 0.01
|
||||
{
|
||||
return Err(format!(
|
||||
"Move delta must have length >=0.01 and each axis <=300 world units: {d:?}"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let view = expected.diagrams.get_mut(&id("state_view")).unwrap();
|
||||
// Independent explicit fixture enumeration: no group/descendant/
|
||||
// routing planner is called to predict the result.
|
||||
for alias in [
|
||||
"node_a",
|
||||
"node_b",
|
||||
"node_inner",
|
||||
"node_leaf",
|
||||
"node_entry",
|
||||
"node_exit",
|
||||
] {
|
||||
let node = view
|
||||
.nodes
|
||||
.get_mut(&id(alias))
|
||||
.ok_or("Missing expected moved placement")?;
|
||||
node.position.x += d.x;
|
||||
node.position.y += d.y;
|
||||
}
|
||||
for alias in ["between", "entry_route", "exit_route"] {
|
||||
let route = view
|
||||
.routes
|
||||
.iter_mut()
|
||||
.find(|route| route.edge == id(alias))
|
||||
.ok_or("Missing explicitly expected moved route")?;
|
||||
for pin in &mut route.waypoints {
|
||||
pin.x += d.x;
|
||||
pin.y += d.y;
|
||||
}
|
||||
}
|
||||
delta = Some(d);
|
||||
}
|
||||
_ => return Err("Mode must be moved, hide, or unchanged".into()),
|
||||
}
|
||||
equal(&expected, &actual)?;
|
||||
roundtrip(&actual)?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"result": "PASS", "mode": mode, "baseline": baseline, "saved": saved,
|
||||
"comparison": "complete Project equality", "inferred_common_delta": delta,
|
||||
"limits": "Invariant evaluator only; no pointer/action/focus/Undo/source-byte acceptance claim",
|
||||
}))?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
match args.as_slice() {
|
||||
[command, out] if command == "generate" => generate(Path::new(out)),
|
||||
[command, mode, baseline, saved] if command == "check" => check(mode, Path::new(baseline), Path::new(saved)),
|
||||
_ => Err("Usage: state_multiselect_native generate DIRECTORY | check moved|hide|unchanged BASELINE SAVED".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
// Produce evidence through real validated commands; the checker itself uses
|
||||
// explicit fixture enumeration and never calls this movement implementation.
|
||||
fn moved(before: &Project, delta: Position) -> Project {
|
||||
let command = diagram_edit::translate_placements(
|
||||
before,
|
||||
id("state_view"),
|
||||
&BTreeSet::from([id("node_a"), id("node_b")]),
|
||||
delta,
|
||||
)
|
||||
.unwrap();
|
||||
let mut session = Session::new(before.clone());
|
||||
session.execute(command).unwrap();
|
||||
session.project().clone()
|
||||
}
|
||||
fn hidden(before: &Project) -> Project {
|
||||
let mut session = Session::new(before.clone());
|
||||
session
|
||||
.execute(Command::Batch(vec![
|
||||
Command::Delete(id("node_a")),
|
||||
Command::Delete(id("node_b")),
|
||||
]))
|
||||
.unwrap();
|
||||
session.project().clone()
|
||||
}
|
||||
fn through_saved_json(mode: &str, baseline: &Project, actual: &Project) -> Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let before = dir.path().join("before.json");
|
||||
let saved = dir.path().join("saved.json");
|
||||
// These assertions distinguish meaningful invariant corruptions from
|
||||
// malformed projects rejected before the evaluator even sees them.
|
||||
validate_candidate(baseline).expect("test baseline must be valid");
|
||||
validate_candidate(actual).expect("corruption must remain a valid model");
|
||||
persistence::save(&before, baseline)?;
|
||||
persistence::save(&saved, actual)?;
|
||||
check(mode, &before, &saved)
|
||||
}
|
||||
fn mismatch(mode: &str, before: &Project, actual: &Project, case: &str) {
|
||||
let error = through_saved_json(mode, before, actual)
|
||||
.expect_err(case)
|
||||
.to_string();
|
||||
assert!(
|
||||
error.contains("Whole Project mismatch"),
|
||||
"{case}: unexpected rejection: {error}"
|
||||
);
|
||||
}
|
||||
fn edge<'a>(p: &'a mut Project, alias: &str) -> &'a mut EdgeRoute {
|
||||
p.diagrams
|
||||
.get_mut(&id("state_view"))
|
||||
.unwrap()
|
||||
.routes
|
||||
.iter_mut()
|
||||
.find(|route| route.edge == id(alias))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_json_and_real_source_bundle_are_accepted_unchanged() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let out = dir.path().join("fixture");
|
||||
generate(&out).unwrap();
|
||||
let baseline = out.join("baseline.json");
|
||||
let saved = out.join("saved.json");
|
||||
persistence::save(&saved, &fixture().unwrap()).unwrap();
|
||||
check("unchanged", &baseline, &saved).unwrap();
|
||||
check("unchanged", &baseline, &out.join("source/project.arcadia")).unwrap();
|
||||
let bytes = fs::read(&baseline).unwrap();
|
||||
assert!(
|
||||
generate(&out).is_err(),
|
||||
"generation cannot overwrite evidence"
|
||||
);
|
||||
assert_eq!(fs::read(&baseline).unwrap(), bytes);
|
||||
let invalid = dir.path().join("invalid.arcadia");
|
||||
fs::write(&invalid, "project {").unwrap();
|
||||
assert!(load(&invalid).is_err(), "source errors must still reject");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_group_command_outputs_pass_and_are_not_unchanged() {
|
||||
let before = fixture().unwrap();
|
||||
for delta in [
|
||||
point(7.25, -2.75),
|
||||
point(-20.5, 30.125),
|
||||
point(0.25, 0.),
|
||||
point(0.01, 10.),
|
||||
point(0.1, -0.2),
|
||||
] {
|
||||
let actual = moved(&before, delta);
|
||||
through_saved_json("moved", &before, &actual).unwrap();
|
||||
mismatch(
|
||||
"unchanged",
|
||||
&before,
|
||||
&actual,
|
||||
"real movement cannot count as unchanged",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_hide_command_outputs_pass_before_and_after_movement() {
|
||||
let initial = fixture().unwrap();
|
||||
for before in [initial.clone(), moved(&initial, point(40., 60.))] {
|
||||
let actual = hidden(&before);
|
||||
through_saved_json("hide", &before, &actual).unwrap();
|
||||
mismatch(
|
||||
"unchanged",
|
||||
&before,
|
||||
&actual,
|
||||
"real Hide cannot count as unchanged",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_and_double_moved_child_are_rejected() {
|
||||
let before = fixture().unwrap();
|
||||
let delta = point(40., 60.);
|
||||
let correct = moved(&before, delta);
|
||||
for alias in ["node_inner", "node_leaf", "node_entry", "node_exit"] {
|
||||
let initial = before.diagrams[&id("state_view")].nodes[&id(alias)].position;
|
||||
for position in [
|
||||
initial,
|
||||
point(initial.x + 2. * delta.x, initial.y + 2. * delta.y),
|
||||
] {
|
||||
let mut bad = correct.clone();
|
||||
bad.diagrams
|
||||
.get_mut(&id("state_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id(alias))
|
||||
.unwrap()
|
||||
.position = position;
|
||||
mismatch("moved", &before, &bad, "child did not move exactly once");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_pins_left_behind_and_external_pins_moved_are_rejected() {
|
||||
let mut before = fixture().unwrap();
|
||||
let correct = moved(&before, point(40., 60.));
|
||||
for alias in ["between", "entry_route", "exit_route"] {
|
||||
let original_pins = edge(&mut before, alias).waypoints.clone();
|
||||
let mut bad = correct.clone();
|
||||
edge(&mut bad, alias).waypoints = original_pins;
|
||||
mismatch("moved", &before, &bad, "internal pins left behind");
|
||||
}
|
||||
let mut bad = correct;
|
||||
for pin in &mut edge(&mut bad, "external").waypoints {
|
||||
pin.x += 40.;
|
||||
pin.y += 60.;
|
||||
}
|
||||
mismatch("moved", &before, &bad, "one-ended pins moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_attachments_and_label_data_must_remain_exact() {
|
||||
let before = fixture().unwrap();
|
||||
let correct = moved(&before, point(40., 60.));
|
||||
let mutations: [fn(&mut EdgeRoute); 4] = [
|
||||
|r| r.source_attachment.as_mut().unwrap().offset = 0.65,
|
||||
|r| r.target_attachment.as_mut().unwrap().side = PortAnchorSide::Top,
|
||||
|r| r.label.as_mut().unwrap().offset.x += 40.,
|
||||
|r| r.label.as_mut().unwrap().fraction = 0.75,
|
||||
];
|
||||
for mutate in mutations {
|
||||
let mut bad = correct.clone();
|
||||
mutate(edge(&mut bad, "between"));
|
||||
mismatch("moved", &before, &bad, "relative route metadata changed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_other_view_fixed_node_and_trace_drift_are_rejected() {
|
||||
let before = fixture().unwrap();
|
||||
let correct = moved(&before, point(40., 60.));
|
||||
let mutations: [fn(&mut Project); 9] = [
|
||||
|p| p.traces.get_mut(&id("trace")).unwrap().baseline = None,
|
||||
|p| {
|
||||
p.elements
|
||||
.get_mut(&id("shared_work"))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift")
|
||||
},
|
||||
|p| {
|
||||
if let RelationBody::StateAction { phase, .. } =
|
||||
&mut p.relations.get_mut(&id("action_a")).unwrap().body
|
||||
{
|
||||
*phase = StateActionKind::Exit;
|
||||
}
|
||||
},
|
||||
|p| {
|
||||
if let RelationBody::StateTransition { guard, .. } =
|
||||
&mut p.relations.get_mut(&id("refresh")).unwrap().body
|
||||
{
|
||||
*guard = "changed_refresh_guard".into();
|
||||
}
|
||||
},
|
||||
|p| {
|
||||
p.elements
|
||||
.get_mut(&id("state_a"))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift")
|
||||
},
|
||||
|p| {
|
||||
p.diagrams
|
||||
.get_mut(&id("state_other"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id("other_a"))
|
||||
.unwrap()
|
||||
.position
|
||||
.x += 40.
|
||||
},
|
||||
|p| {
|
||||
p.diagrams
|
||||
.get_mut(&id("sa_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id("sa_node"))
|
||||
.unwrap()
|
||||
.position
|
||||
.y += 60.
|
||||
},
|
||||
|p| {
|
||||
p.diagrams
|
||||
.get_mut(&id("state_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&id("node_c"))
|
||||
.unwrap()
|
||||
.position
|
||||
.x += 40.
|
||||
},
|
||||
|p| {
|
||||
p.traces
|
||||
.get_mut(&id("trace"))
|
||||
.unwrap()
|
||||
.description
|
||||
.push_str(" drift")
|
||||
},
|
||||
];
|
||||
for mutate in mutations {
|
||||
let mut bad = correct.clone();
|
||||
mutate(&mut bad);
|
||||
mismatch(
|
||||
"moved",
|
||||
&before,
|
||||
&bad,
|
||||
"record outside permitted movement changed",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_and_excessive_moves_cannot_satisfy_move_evidence() {
|
||||
let before = fixture().unwrap();
|
||||
for (delta, reason) in [
|
||||
(point(0., 0.), "length >=0.01"),
|
||||
(point(310., 0.), "each axis <=300"),
|
||||
] {
|
||||
let actual = moved(&before, delta);
|
||||
let error = through_saved_json("moved", &before, &actual)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains(reason), "{delta:?}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_must_preserve_child_routes_and_semantic_objects() {
|
||||
let before = fixture().unwrap();
|
||||
let correct = hidden(&before);
|
||||
let mut missing_child = correct.clone();
|
||||
missing_child
|
||||
.diagrams
|
||||
.get_mut(&id("state_view"))
|
||||
.unwrap()
|
||||
.nodes
|
||||
.remove(&id("node_leaf"));
|
||||
mismatch(
|
||||
"hide",
|
||||
&before,
|
||||
&missing_child,
|
||||
"Hide removed unselected child placement",
|
||||
);
|
||||
let mut missing_routes = correct;
|
||||
missing_routes
|
||||
.diagrams
|
||||
.get_mut(&id("state_view"))
|
||||
.unwrap()
|
||||
.routes
|
||||
.clear();
|
||||
mismatch(
|
||||
"hide",
|
||||
&before,
|
||||
&missing_routes,
|
||||
"Hide removed persistent route records",
|
||||
);
|
||||
let mut semantic_delete = Session::new(before.clone());
|
||||
semantic_delete
|
||||
.execute(Command::Batch(vec![
|
||||
Command::Delete(id("state_a")),
|
||||
Command::Delete(id("state_b")),
|
||||
]))
|
||||
.unwrap();
|
||||
mismatch(
|
||||
"hide",
|
||||
&before,
|
||||
semantic_delete.project(),
|
||||
"Hide became semantic deletion",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_rejects_valid_semantic_drift_without_geometry_changes() {
|
||||
let before = fixture().unwrap();
|
||||
let mut actual = before.clone();
|
||||
actual
|
||||
.elements
|
||||
.get_mut(&id("state_b"))
|
||||
.unwrap()
|
||||
.name
|
||||
.push_str(" edited");
|
||||
mismatch(
|
||||
"unchanged",
|
||||
&before,
|
||||
&actual,
|
||||
"geometry equality is not complete Project equality",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moved_and_hidden_source_inputs_are_checked_against_complete_expected_projects() {
|
||||
let before = fixture().unwrap();
|
||||
for (mode, actual) in [
|
||||
("moved", moved(&before, point(7.25, -2.75))),
|
||||
("hide", hidden(&before)),
|
||||
] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let baseline = dir.path().join("baseline.json");
|
||||
persistence::save(&baseline, &before).unwrap();
|
||||
let bundle = roundtrip(&actual).unwrap();
|
||||
for (path, source) in &bundle.files {
|
||||
write_new(&dir.path().join("saved").join(path), source.as_bytes()).unwrap();
|
||||
}
|
||||
check(
|
||||
mode,
|
||||
&baseline,
|
||||
&dir.path().join("saved").join(&bundle.entry),
|
||||
)
|
||||
.unwrap();
|
||||
let mut corrupt = actual.clone();
|
||||
corrupt.elements.get_mut(&id("shared_work")).unwrap().name =
|
||||
"Unrequested source edit".into();
|
||||
let bundle = roundtrip(&corrupt).unwrap();
|
||||
for (path, source) in &bundle.files {
|
||||
write_new(&dir.path().join("corrupt").join(path), source.as_bytes()).unwrap();
|
||||
}
|
||||
let error = check(
|
||||
mode,
|
||||
&baseline,
|
||||
&dir.path().join("corrupt").join(&bundle.entry),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("Whole Project mismatch"), "{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,7 @@ fn diagram(
|
||||
projection,
|
||||
view_options: Default::default(),
|
||||
nodes: BTreeMap::new(),
|
||||
layout: None,
|
||||
routes: vec![],
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Pure diagram edits shared by movement previews and committed transactions.
|
||||
use crate::{Command, Id, MAX_COORDINATE, ModelError, Position, Project, projection};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// Translate selected placements and their projected descendants simultaneously.
|
||||
///
|
||||
/// Membership and geometry are read from one snapshot, including folded children.
|
||||
/// Overlapping roots move each placement once. Route pins follow the combined
|
||||
/// movement of their actual endpoint owners (and State boundaries). Semantic
|
||||
/// ownership and other views are untouched. Apply the returned batch through the
|
||||
/// normal validated command path; its selected identity is not a primary selection.
|
||||
pub fn translate_placements(
|
||||
project: &Project,
|
||||
diagram: Id,
|
||||
selected: &BTreeSet<Id>,
|
||||
delta: Position,
|
||||
) -> Result<Command, ModelError> {
|
||||
let view = project
|
||||
.diagrams
|
||||
.get(&diagram)
|
||||
.ok_or_else(|| ModelError("Movement requires an existing diagram.".into()))?;
|
||||
if selected.is_empty() {
|
||||
return Err(ModelError(
|
||||
"Movement requires at least one placement.".into(),
|
||||
));
|
||||
}
|
||||
if selected.iter().any(|id| !view.nodes.contains_key(id)) {
|
||||
return Err(ModelError(
|
||||
"Every selected placement must belong to the diagram.".into(),
|
||||
));
|
||||
}
|
||||
if !delta.x.is_finite() || !delta.y.is_finite() {
|
||||
return Err(ModelError("Movement displacement must be finite.".into()));
|
||||
}
|
||||
if delta.x == 0. && delta.y == 0. {
|
||||
return Ok(Command::Batch(vec![]));
|
||||
}
|
||||
let mut children: BTreeMap<Id, Vec<Id>> = BTreeMap::new();
|
||||
for (child, parent) in projection::parents(project, view) {
|
||||
if let Some(parent) = parent {
|
||||
children.entry(parent).or_default().push(child);
|
||||
}
|
||||
}
|
||||
let mut moved = BTreeSet::new();
|
||||
let mut pending: Vec<_> = selected.iter().copied().collect();
|
||||
while let Some(id) = pending.pop() {
|
||||
if moved.insert(id) {
|
||||
pending.extend(children.get(&id).into_iter().flatten().copied());
|
||||
}
|
||||
}
|
||||
let deltas: BTreeMap<_, _> = moved.iter().map(|id| (*id, delta)).collect();
|
||||
let routes = projection::translated_routes(project, view, &deltas);
|
||||
let bounded = |value: f32| value.is_finite() && value.abs() <= MAX_COORDINATE;
|
||||
let mut commands = Vec::with_capacity(moved.len() + routes.len());
|
||||
for id in moved {
|
||||
let mut node = view.nodes[&id].clone();
|
||||
node.position.x += delta.x;
|
||||
node.position.y += delta.y;
|
||||
if ![
|
||||
node.position.x,
|
||||
node.position.y,
|
||||
node.size.width,
|
||||
node.size.height,
|
||||
]
|
||||
.into_iter()
|
||||
.all(bounded)
|
||||
|| node.size.width <= 0.
|
||||
|| node.size.height <= 0.
|
||||
{
|
||||
return Err(ModelError(
|
||||
"Movement produces invalid placement bounds.".into(),
|
||||
));
|
||||
}
|
||||
commands.push(Command::EditNode {
|
||||
diagram,
|
||||
original: id,
|
||||
node,
|
||||
});
|
||||
}
|
||||
for route in routes {
|
||||
if route
|
||||
.waypoints
|
||||
.iter()
|
||||
.any(|point| !bounded(point.x) || !bounded(point.y))
|
||||
{
|
||||
return Err(ModelError("Movement produces invalid route bounds.".into()));
|
||||
}
|
||||
commands.push(Command::SetEdgeRoute { diagram, route });
|
||||
}
|
||||
Ok(Command::Batch(commands))
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Framework-independent OA/SA model, transactional commands and editing services.
|
||||
pub mod analysis_numeric;
|
||||
pub mod data;
|
||||
pub mod diagram_edit;
|
||||
pub mod language;
|
||||
pub mod model;
|
||||
pub mod operations;
|
||||
@@ -9,6 +10,7 @@ pub mod ports;
|
||||
pub mod projection;
|
||||
pub mod references;
|
||||
pub mod routing;
|
||||
pub mod scenario_layout;
|
||||
pub mod semantic;
|
||||
pub mod session;
|
||||
mod source_defaults;
|
||||
@@ -20,6 +22,9 @@ pub mod validation;
|
||||
pub mod view_options;
|
||||
pub use model::*;
|
||||
pub use ports::*;
|
||||
pub use scenario_layout::{
|
||||
DiagramLayout, ScenarioLanePosition, ScenarioLayout, ScenarioMessagePosition,
|
||||
};
|
||||
pub use semantic::*;
|
||||
pub use session::*;
|
||||
mod demo;
|
||||
|
||||
@@ -1436,6 +1436,7 @@ pub enum ProjectionKind {
|
||||
FunctionalDataflow,
|
||||
Capabilities,
|
||||
StateMachine { machine: Id },
|
||||
Scenario { scenario: Id },
|
||||
}
|
||||
impl ProjectionKind {
|
||||
pub fn state_machine(self) -> Option<Id> {
|
||||
@@ -1445,8 +1446,30 @@ impl ProjectionKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// The semantic owner of a saved Scenario representation.
|
||||
pub fn scenario(self) -> Option<Id> {
|
||||
match self {
|
||||
Self::Scenario { scenario } => Some(scenario),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicitly classify architecture views; absence of a state machine is insufficient.
|
||||
pub fn is_architecture(self) -> bool {
|
||||
match self {
|
||||
Self::Overview
|
||||
| Self::Decomposition
|
||||
| Self::Allocation
|
||||
| Self::Traceability
|
||||
| Self::FunctionalDataflow
|
||||
| Self::Capabilities => true,
|
||||
Self::StateMachine { .. } | Self::Scenario { .. } => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn includes(self, kind: Kind) -> bool {
|
||||
match self {
|
||||
Self::Scenario { .. } => false,
|
||||
Self::StateMachine { .. } => {
|
||||
matches!(kind, Kind::StateMachine | Kind::Region) || kind.is_state()
|
||||
}
|
||||
@@ -1471,6 +1494,7 @@ impl std::fmt::Display for ProjectionKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::StateMachine { .. } => "State machine",
|
||||
Self::Scenario { .. } => "Scenario",
|
||||
Self::Allocation => "Architecture · allocated work",
|
||||
Self::FunctionalDataflow => "Functional dataflow",
|
||||
Self::Capabilities => "Missions & capabilities",
|
||||
@@ -1495,6 +1519,8 @@ pub struct Diagram {
|
||||
pub nodes: BTreeMap<Id, NodePlacement>,
|
||||
#[serde(default)]
|
||||
pub routes: Vec<EdgeRoute>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub layout: Option<crate::scenario_layout::DiagramLayout>,
|
||||
}
|
||||
/// Authored presentation for one existing relation or trace in one diagram.
|
||||
/// Computed endpoints and automatic routing elbows are never persisted here.
|
||||
@@ -1955,6 +1981,7 @@ impl Project {
|
||||
view_options: crate::view_options::ViewOptions::default(),
|
||||
nodes: BTreeMap::new(),
|
||||
routes: vec![],
|
||||
layout: None,
|
||||
},
|
||||
);
|
||||
id
|
||||
|
||||
@@ -278,6 +278,11 @@ fn project_diagram_impl(
|
||||
mut availability: Option<&mut BTreeMap<Id, crate::view_options::EdgeAvailability>>,
|
||||
index: Option<&crate::view_options::ViewIndex>,
|
||||
) -> ProjectedView {
|
||||
// Saved Scenario layout is not an architecture/state projection. Its dedicated
|
||||
// renderer is not wired yet; never interpret its payload through this fallback.
|
||||
if d.projection.scenario().is_some() {
|
||||
return ProjectedView::default();
|
||||
}
|
||||
let parents = parents(p, d);
|
||||
let mut nodes = Vec::new();
|
||||
for n in d.nodes.values() {
|
||||
@@ -394,6 +399,7 @@ fn project_diagram_impl(
|
||||
continue;
|
||||
}
|
||||
let included = match d.projection {
|
||||
ProjectionKind::Scenario { .. } => false,
|
||||
ProjectionKind::StateMachine { machine } => matches!(&r.body,
|
||||
RelationBody::StateTransition { transition_kind, .. }
|
||||
if *transition_kind != TransitionKind::Internal
|
||||
|
||||
@@ -203,7 +203,81 @@ pub fn visit_relation_refs(r: &mut Relation, mut visit: impl FnMut(&mut Id)) {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
pub fn remap_references(p: &mut Project, old: Id, new: Id) {
|
||||
/// Every semantic/presentation reference in a diagram, excluding its own identities.
|
||||
pub fn diagram_references(d: &Diagram) -> Vec<Id> {
|
||||
let mut copy = d.clone();
|
||||
let mut refs = Vec::new();
|
||||
visit_diagram_refs(&mut copy, |id| refs.push(*id));
|
||||
refs
|
||||
}
|
||||
|
||||
pub fn visit_diagram_refs(d: &mut Diagram, mut visit: impl FnMut(&mut Id)) {
|
||||
d.view_options.visit_references(&mut visit);
|
||||
match &mut d.projection {
|
||||
ProjectionKind::StateMachine { machine } => visit(machine),
|
||||
ProjectionKind::Scenario { scenario } => visit(scenario),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(layout) = &mut d.layout {
|
||||
layout.visit_references(&mut visit);
|
||||
}
|
||||
for route in &mut d.routes {
|
||||
visit(&mut route.edge);
|
||||
}
|
||||
for node in d.nodes.values_mut() {
|
||||
for anchor in &mut node.port_anchors {
|
||||
visit(&mut anchor.port);
|
||||
}
|
||||
visit(&mut node.element);
|
||||
}
|
||||
}
|
||||
|
||||
/// Preflight reference-key collisions before the caller changes object identities.
|
||||
/// Fresh targets are allowed. This is not whole-project admission: unrelated
|
||||
/// invalid records remain repairable within a transaction. Future typed reference
|
||||
/// domains must compose their own preflight here before any remap mutation.
|
||||
pub fn check_remap(p: &Project, old: Id, new: Id) -> Result<(), ModelError> {
|
||||
if old == new {
|
||||
return Ok(());
|
||||
}
|
||||
let remap = |id: Id| if id == old { new } else { id };
|
||||
for diagram in p.diagrams.values() {
|
||||
let Some(DiagramLayout::Scenario(layout)) = &diagram.layout else {
|
||||
continue;
|
||||
};
|
||||
let mut lanes = std::collections::BTreeMap::new();
|
||||
for lane in &layout.lanes {
|
||||
let affected = lane.lifeline == old;
|
||||
if let Some(previous_affected) = lanes.insert(remap(lane.lifeline), affected)
|
||||
&& (affected || previous_affected)
|
||||
{
|
||||
return Err(ModelError(
|
||||
"Identity remap would collide with a Scenario lane position.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut messages = std::collections::BTreeMap::new();
|
||||
for message in &layout.messages {
|
||||
let mut address = message.address.clone();
|
||||
let affected = address.occurrence == old || address.references.contains(&old);
|
||||
address.occurrence = remap(address.occurrence);
|
||||
for reference in &mut address.references {
|
||||
*reference = remap(*reference);
|
||||
}
|
||||
if let Some(previous_affected) = messages.insert(address, affected)
|
||||
&& (affected || previous_affected)
|
||||
{
|
||||
return Err(ModelError(
|
||||
"Identity remap would collide with a Scenario message position.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remap_references(p: &mut Project, old: Id, new: Id) -> Result<(), ModelError> {
|
||||
check_remap(p, old, new)?;
|
||||
for e in p.elements.values_mut() {
|
||||
visit_element_refs(e, |id| {
|
||||
if *id == old {
|
||||
@@ -219,31 +293,11 @@ pub fn remap_references(p: &mut Project, old: Id, new: Id) {
|
||||
});
|
||||
}
|
||||
for d in p.diagrams.values_mut() {
|
||||
d.view_options.visit_references(|id| {
|
||||
visit_diagram_refs(d, |id| {
|
||||
if *id == old {
|
||||
*id = new;
|
||||
}
|
||||
});
|
||||
if let ProjectionKind::StateMachine { machine } = &mut d.projection
|
||||
&& *machine == old
|
||||
{
|
||||
*machine = new;
|
||||
}
|
||||
for route in &mut d.routes {
|
||||
if route.edge == old {
|
||||
route.edge = new;
|
||||
}
|
||||
}
|
||||
for n in d.nodes.values_mut() {
|
||||
for anchor in &mut n.port_anchors {
|
||||
if anchor.port == old {
|
||||
anchor.port = new;
|
||||
}
|
||||
}
|
||||
if n.element == old {
|
||||
n.element = new;
|
||||
}
|
||||
}
|
||||
}
|
||||
for a in p.artifact_links.values_mut() {
|
||||
if a.owner == old {
|
||||
@@ -265,6 +319,7 @@ pub fn remap_references(p: &mut Project, old: Id, new: Id) {
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// IDs removed by a cascade. Cross-layer traced counterparts are never included.
|
||||
pub fn deletion_impact(p: &Project, id: Id) -> BTreeSet<Id> {
|
||||
@@ -339,7 +394,8 @@ fn deletion_impact_inner(p: &Project, id: Id, defer_exchange_allocations: bool)
|
||||
for d in p.diagrams.values() {
|
||||
if d.projection
|
||||
.state_machine()
|
||||
.is_some_and(|machine| removed.contains(&machine))
|
||||
.or_else(|| d.projection.scenario())
|
||||
.is_some_and(|owner| removed.contains(&owner))
|
||||
{
|
||||
removed.insert(d.id);
|
||||
}
|
||||
@@ -412,6 +468,7 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
|
||||
p.artifact_links.retain(|id, _| !removed.contains(id));
|
||||
for d in p.diagrams.values_mut() {
|
||||
d.view_options.retain_references(|id| !removed.contains(id));
|
||||
crate::scenario_layout::prune_deleted(d, &removed);
|
||||
d.nodes.retain(|id, _| !removed.contains(id));
|
||||
d.routes.retain(|route| !removed.contains(&route.edge));
|
||||
for node in d.nodes.values_mut() {
|
||||
@@ -589,3 +646,7 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "references/scenario_layout_tests.rs"]
|
||||
mod scenario_layout_tests;
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
struct Fixture {
|
||||
project: Project,
|
||||
owner: Id,
|
||||
lanes: [Id; 2],
|
||||
messages: [Id; 2],
|
||||
views: [Id; 2],
|
||||
}
|
||||
|
||||
fn address(occurrence: Id) -> OccurrenceEndpoint {
|
||||
OccurrenceEndpoint {
|
||||
references: vec![],
|
||||
occurrence,
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(project: &Project, view: Id) -> &ScenarioLayout {
|
||||
let Some(DiagramLayout::Scenario(layout)) = &project.diagrams[&view].layout else {
|
||||
panic!("expected authored Scenario positions")
|
||||
};
|
||||
layout
|
||||
}
|
||||
|
||||
fn layout_mut(project: &mut Project, view: Id) -> &mut ScenarioLayout {
|
||||
let Some(DiagramLayout::Scenario(layout)) =
|
||||
&mut project.diagrams.get_mut(&view).unwrap().layout
|
||||
else {
|
||||
panic!("expected authored Scenario positions")
|
||||
};
|
||||
layout
|
||||
}
|
||||
|
||||
fn admitted(project: &Project) {
|
||||
let errors: Vec<_> = crate::validation::validate(project)
|
||||
.into_iter()
|
||||
.filter(|issue| issue.severity == crate::validation::Severity::Error)
|
||||
.collect();
|
||||
assert!(errors.is_empty(), "{errors:?}");
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
let mut project = Project::empty();
|
||||
let owner = project
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Delivery", None)
|
||||
.unwrap();
|
||||
let lanes = ["Sender", "Receiver"].map(|name| {
|
||||
project
|
||||
.add_element(Kind::Lifeline, Layer::Oa, name, Some(owner))
|
||||
.unwrap()
|
||||
});
|
||||
let messages = ["First message", "Second message"].map(|name| {
|
||||
let id = project
|
||||
.add_element(Kind::Occurrence, Layer::Oa, name, Some(owner))
|
||||
.unwrap();
|
||||
*project.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange {
|
||||
exchange: None,
|
||||
sender: Some(lanes[0]),
|
||||
receiver: Some(lanes[1]),
|
||||
message_kind: MessageKind::Asynchronous,
|
||||
reply_to: None,
|
||||
values: vec![],
|
||||
operation: None,
|
||||
},
|
||||
precondition: String::new(),
|
||||
postcondition: String::new(),
|
||||
};
|
||||
id
|
||||
});
|
||||
*project
|
||||
.elements
|
||||
.get_mut(&owner)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap() = messages.to_vec();
|
||||
let views = ["delivery_view", "review_view"].map(|alias| {
|
||||
let id = Id::new_v4();
|
||||
project.diagrams.insert(
|
||||
id,
|
||||
Diagram {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: alias.into(),
|
||||
description: String::new(),
|
||||
layer: Layer::Oa,
|
||||
projection: ProjectionKind::Scenario { scenario: owner },
|
||||
view_options: Default::default(),
|
||||
nodes: BTreeMap::new(),
|
||||
routes: vec![],
|
||||
layout: Some(DiagramLayout::Scenario(ScenarioLayout {
|
||||
lanes: vec![
|
||||
ScenarioLanePosition {
|
||||
lifeline: lanes[0],
|
||||
x: 120.,
|
||||
},
|
||||
ScenarioLanePosition {
|
||||
lifeline: lanes[1],
|
||||
x: 420.,
|
||||
},
|
||||
],
|
||||
messages: vec![
|
||||
ScenarioMessagePosition {
|
||||
address: address(messages[0]),
|
||||
send_y: 220.,
|
||||
},
|
||||
ScenarioMessagePosition {
|
||||
address: address(messages[1]),
|
||||
send_y: 360.,
|
||||
},
|
||||
],
|
||||
})),
|
||||
},
|
||||
);
|
||||
id
|
||||
});
|
||||
admitted(&project);
|
||||
Fixture {
|
||||
project,
|
||||
owner,
|
||||
lanes,
|
||||
messages,
|
||||
views,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_identity_swap_preserves_coordinates_and_semantic_sequence() {
|
||||
let mut f = fixture();
|
||||
let before = f.project.clone();
|
||||
let temporary = Id::new_v4();
|
||||
for ids in [f.lanes, f.messages] {
|
||||
f.project = crate::execute_batch(
|
||||
&f.project,
|
||||
&[
|
||||
Command::Reidentify(ids[0], temporary),
|
||||
Command::Reidentify(ids[1], ids[0]),
|
||||
Command::Reidentify(temporary, ids[1]),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
admitted(&f.project);
|
||||
assert_eq!(
|
||||
f.project.elements[&f.owner].steps().unwrap(),
|
||||
&vec![f.messages[1], f.messages[0]]
|
||||
);
|
||||
for view in f.views {
|
||||
let rows = layout(&f.project, view);
|
||||
assert_eq!(
|
||||
rows.lanes,
|
||||
vec![
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lanes[1],
|
||||
x: 120.
|
||||
},
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lanes[0],
|
||||
x: 420.
|
||||
}
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
rows.messages,
|
||||
vec![
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.messages[1]),
|
||||
send_y: 220.
|
||||
},
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.messages[0]),
|
||||
send_y: 360.
|
||||
}
|
||||
]
|
||||
);
|
||||
}
|
||||
// Reverse the swaps: no values or identities other than those requested drift.
|
||||
for ids in [f.lanes, f.messages] {
|
||||
f.project = crate::execute_batch(
|
||||
&f.project,
|
||||
&[
|
||||
Command::Reidentify(ids[0], temporary),
|
||||
Command::Reidentify(ids[1], ids[0]),
|
||||
Command::Reidentify(temporary, ids[1]),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(f.project, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colliding_lane_or_message_remap_rejects_before_any_reference_changes() {
|
||||
for message in [false, true] {
|
||||
let mut f = fixture();
|
||||
let [old, new] = if message { f.messages } else { f.lanes };
|
||||
let before = f.project.clone();
|
||||
assert!(check_remap(&f.project, old, new).is_err());
|
||||
assert!(remap_references(&mut f.project, old, new).is_err());
|
||||
assert_eq!(f.project, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reidentify_preflight_precedes_object_map_mutation_for_fresh_colliding_target() {
|
||||
let mut f = fixture();
|
||||
let fresh = Id::new_v4();
|
||||
// A repair candidate can already have a dangling coordinate key. It must not
|
||||
// silently merge with the live lane, even though the destination ID is vacant.
|
||||
layout_mut(&mut f.project, f.views[0]).lanes[1].lifeline = fresh;
|
||||
let before = f.project.clone();
|
||||
assert!(crate::session::reidentify(&mut f.project, f.lanes[0], fresh).is_err());
|
||||
assert_eq!(f.project, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_address_paths_are_walked_and_collision_checked_without_admitting_expansion() {
|
||||
let mut f = fixture();
|
||||
let [old, new] = [Id::new_v4(), Id::new_v4()];
|
||||
let rows = layout_mut(&mut f.project, f.views[0]);
|
||||
// Future/invalid expanded candidates still participate in reference safety.
|
||||
rows.messages[0].address.references = vec![old];
|
||||
rows.messages[1].address = OccurrenceEndpoint {
|
||||
references: vec![new],
|
||||
occurrence: f.messages[0],
|
||||
};
|
||||
let refs = diagram_references(&f.project.diagrams[&f.views[0]]);
|
||||
assert!(refs.contains(&f.owner) && refs.contains(&old) && refs.contains(&new));
|
||||
let before = f.project.clone();
|
||||
assert!(remap_references(&mut f.project, old, new).is_err());
|
||||
assert_eq!(f.project, before);
|
||||
let fresh = Id::new_v4();
|
||||
remap_references(&mut f.project, old, fresh).unwrap();
|
||||
let rows = layout(&f.project, f.views[0]);
|
||||
assert_eq!(rows.messages[0].address.references, vec![fresh]);
|
||||
assert_eq!(rows.messages[0].address.occurrence, f.messages[0]);
|
||||
assert_eq!(rows.messages[1].address.references, vec![new]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_reidentify_and_delete_cover_all_saved_views_without_deleting_other_owners() {
|
||||
let mut f = fixture();
|
||||
let other_owner = f
|
||||
.project
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Independent", None)
|
||||
.unwrap();
|
||||
let mut other_view = f.project.diagrams[&f.views[0]].clone();
|
||||
other_view.id = Id::new_v4();
|
||||
other_view.alias = "independent_view".into();
|
||||
other_view.projection = ProjectionKind::Scenario {
|
||||
scenario: other_owner,
|
||||
};
|
||||
other_view.layout = None;
|
||||
f.project.diagrams.insert(other_view.id, other_view.clone());
|
||||
admitted(&f.project);
|
||||
let fresh_owner = Id::new_v4();
|
||||
f.project = crate::prepare_command(&f.project, &Command::Reidentify(f.owner, fresh_owner))
|
||||
.unwrap()
|
||||
.project;
|
||||
for view in f.views {
|
||||
assert_eq!(
|
||||
f.project.diagrams[&view].projection.scenario(),
|
||||
Some(fresh_owner)
|
||||
);
|
||||
}
|
||||
let impact = deletion_impact(&f.project, fresh_owner);
|
||||
assert!(
|
||||
f.views
|
||||
.iter()
|
||||
.chain(&f.lanes)
|
||||
.chain(&f.messages)
|
||||
.all(|id| impact.contains(id))
|
||||
);
|
||||
assert!(!impact.contains(&other_owner) && !impact.contains(&other_view.id));
|
||||
delete_cascade(&mut f.project, fresh_owner);
|
||||
assert_eq!(f.project.diagrams[&other_view.id], other_view);
|
||||
assert!(
|
||||
f.views
|
||||
.iter()
|
||||
.all(|id| !f.project.diagrams.contains_key(id))
|
||||
);
|
||||
admitted(&f.project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_then_recreation_never_resurrects_lane_or_message_coordinates() {
|
||||
let mut f = fixture();
|
||||
let lane = f.project.elements[&f.lanes[0]].clone();
|
||||
let message = f.project.elements[&f.messages[0]].clone();
|
||||
delete_cascade(&mut f.project, lane.id);
|
||||
for view in f.views {
|
||||
let rows = layout(&f.project, view);
|
||||
assert_eq!(rows.lanes.len(), 1);
|
||||
assert_eq!(rows.lanes[0].lifeline, f.lanes[1]);
|
||||
// Missing endpoint assignment does not erase a still-live message's spacing.
|
||||
assert_eq!(rows.messages.len(), 2);
|
||||
}
|
||||
let mut pending = BTreeSet::new();
|
||||
delete_cascade_deferred(&mut f.project, message.id, &mut pending);
|
||||
// Pruning happens during deletion, before later batch commands can recreate IDs.
|
||||
assert!(
|
||||
layout(&f.project, f.views[0])
|
||||
.messages
|
||||
.iter()
|
||||
.all(|row| row.address.occurrence != message.id)
|
||||
);
|
||||
f.project.elements.insert(lane.id, lane);
|
||||
f.project.elements.insert(message.id, message);
|
||||
f.project
|
||||
.elements
|
||||
.get_mut(&f.owner)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap()
|
||||
.insert(0, f.messages[0]);
|
||||
finish_deletions(&mut f.project, &pending);
|
||||
for view in f.views {
|
||||
let rows = layout(&f.project, view);
|
||||
assert_eq!(rows.lanes.len(), 1);
|
||||
assert_eq!(
|
||||
rows.messages,
|
||||
vec![ScenarioMessagePosition {
|
||||
address: address(f.messages[1]),
|
||||
send_y: 360.
|
||||
}]
|
||||
);
|
||||
}
|
||||
admitted(&f.project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_invalid_records_do_not_block_scoped_remap_or_get_repaired_implicitly() {
|
||||
let mut f = fixture();
|
||||
let unrelated = Id::new_v4();
|
||||
let rows = layout_mut(&mut f.project, f.views[1]);
|
||||
let invalid = ScenarioLanePosition {
|
||||
lifeline: unrelated,
|
||||
x: MAX_COORDINATE * 2.,
|
||||
};
|
||||
rows.lanes.extend([invalid.clone(), invalid]);
|
||||
let fresh = Id::new_v4();
|
||||
let untouched = f.project.diagrams[&f.views[1]].clone();
|
||||
let before = f.project.clone();
|
||||
remap_references(&mut f.project, f.owner, f.owner).unwrap();
|
||||
assert_eq!(f.project, before);
|
||||
// The duplicate lane records do not involve the remapped message identity.
|
||||
remap_references(&mut f.project, f.messages[0], fresh).unwrap();
|
||||
assert_eq!(
|
||||
layout(&f.project, f.views[1]).lanes,
|
||||
layout_from(&untouched).lanes
|
||||
);
|
||||
assert_eq!(
|
||||
layout(&f.project, f.views[1]).messages[0]
|
||||
.address
|
||||
.occurrence,
|
||||
fresh
|
||||
);
|
||||
assert_eq!(layout(&f.project, f.views[1]).messages[0].send_y, 220.);
|
||||
}
|
||||
|
||||
fn layout_from(diagram: &Diagram) -> &ScenarioLayout {
|
||||
let Some(DiagramLayout::Scenario(layout)) = &diagram.layout else {
|
||||
panic!("missing layout")
|
||||
};
|
||||
layout
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_prunes_an_explicit_address_path_without_pruning_other_message_rows() {
|
||||
let mut f = fixture();
|
||||
// Expanded addresses are not admitted in this slice, but deleting their
|
||||
// explicit references must still make an intermediate repair candidate safe.
|
||||
layout_mut(&mut f.project, f.views[0]).messages[0]
|
||||
.address
|
||||
.references = vec![f.lanes[0]];
|
||||
delete_cascade(&mut f.project, f.lanes[0]);
|
||||
assert_eq!(
|
||||
layout(&f.project, f.views[0]).messages,
|
||||
vec![ScenarioMessagePosition {
|
||||
address: address(f.messages[1]),
|
||||
send_y: 360.
|
||||
}]
|
||||
);
|
||||
assert_eq!(layout(&f.project, f.views[1]).messages.len(), 2);
|
||||
assert!(f.project.elements.contains_key(&f.messages[0]));
|
||||
admitted(&f.project);
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
//! Authored Scenario presentation. Structural admission never changes event order.
|
||||
use crate::{
|
||||
Diagram, Id, Kind, Layer, MAX_COORDINATE, ModelError, OccurrenceBody, OccurrenceEndpoint,
|
||||
Project, SharedBody, validation,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum DiagramLayout {
|
||||
Scenario(ScenarioLayout),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ScenarioLayout {
|
||||
#[serde(default)]
|
||||
pub lanes: Vec<ScenarioLanePosition>,
|
||||
#[serde(default)]
|
||||
pub messages: Vec<ScenarioMessagePosition>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ScenarioLanePosition {
|
||||
pub lifeline: Id,
|
||||
pub x: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ScenarioMessagePosition {
|
||||
pub address: OccurrenceEndpoint,
|
||||
/// Actual send endpoint, not the renderer's receive-oriented lifecycle row.
|
||||
pub send_y: f32,
|
||||
}
|
||||
|
||||
impl DiagramLayout {
|
||||
/// Visit every explicit reference, including unsupported paths in a candidate.
|
||||
/// The caller owns remap preflight and final atomic validation.
|
||||
pub fn visit_references(&mut self, mut visit: impl FnMut(&mut Id)) {
|
||||
match self {
|
||||
Self::Scenario(layout) => {
|
||||
for lane in &mut layout.lanes {
|
||||
visit(&mut lane.lifeline);
|
||||
}
|
||||
for message in &mut layout.messages {
|
||||
for reference in &mut message.address.references {
|
||||
visit(reference);
|
||||
}
|
||||
visit(&mut message.address.occurrence);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Proposed aggregate accounting contribution; the shared admission owner applies it.
|
||||
/// One payload plus one record per lane/message. No graph objects are introduced.
|
||||
pub fn record_count(diagram: &Diagram) -> usize {
|
||||
match &diagram.layout {
|
||||
None => 0,
|
||||
Some(DiagramLayout::Scenario(layout)) => 1usize
|
||||
.saturating_add(layout.lanes.len())
|
||||
.saturating_add(layout.messages.len()),
|
||||
}
|
||||
}
|
||||
|
||||
fn coordinate(value: f32) -> bool {
|
||||
value.is_finite() && value.abs() <= MAX_COORDINATE
|
||||
}
|
||||
|
||||
fn owner(p: &Project, diagram: &Diagram) -> Result<Id, ModelError> {
|
||||
let scenario = diagram
|
||||
.projection
|
||||
.scenario()
|
||||
.ok_or_else(|| ModelError("Scenario layout requires a Scenario projection.".into()))?;
|
||||
if !p
|
||||
.elements
|
||||
.get(&scenario)
|
||||
.is_some_and(|element| element.kind() == Kind::Scenario && element.layer() == diagram.layer)
|
||||
{
|
||||
return Err(ModelError(
|
||||
"Scenario projection requires an existing Scenario in the diagram layer.".into(),
|
||||
));
|
||||
}
|
||||
Ok(scenario)
|
||||
}
|
||||
|
||||
fn lane_member(p: &Project, owner: Id, layer: Layer, lifeline: Id) -> bool {
|
||||
p.elements.get(&lifeline).is_some_and(|element| {
|
||||
element.kind() == Kind::Lifeline
|
||||
&& element.parent == Some(owner)
|
||||
&& element.layer() == layer
|
||||
})
|
||||
}
|
||||
|
||||
/// Only actual steps of this Scenario and its own Fragment/Branch sequences.
|
||||
/// ScenarioUse/SequenceReference are deliberately never expanded. Invalid graph
|
||||
/// cycles terminate, and malformed parent/step links do not manufacture membership.
|
||||
fn direct_messages(p: &Project, owner: Id, layer: Layer) -> BTreeSet<Id> {
|
||||
let mut messages = BTreeSet::new();
|
||||
let mut visited = BTreeSet::new();
|
||||
let mut pending = vec![owner];
|
||||
while let Some(scope) = pending.pop() {
|
||||
if !visited.insert(scope) {
|
||||
continue;
|
||||
}
|
||||
let Some(element) = p.elements.get(&scope) else {
|
||||
continue;
|
||||
};
|
||||
for id in element.steps().into_iter().flatten() {
|
||||
let Some(item) = p.elements.get(id) else {
|
||||
continue;
|
||||
};
|
||||
if item.parent != Some(scope) || item.layer() != layer {
|
||||
continue;
|
||||
}
|
||||
match item.shared() {
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange { .. },
|
||||
..
|
||||
}) => {
|
||||
messages.insert(*id);
|
||||
}
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Fragment { branches, .. },
|
||||
..
|
||||
}) => {
|
||||
for branch in branches {
|
||||
if p.elements.get(branch).is_some_and(|operand| {
|
||||
operand.parent == Some(*id)
|
||||
&& operand.layer() == layer
|
||||
&& matches!(
|
||||
operand.shared(),
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Branch { .. },
|
||||
..
|
||||
})
|
||||
)
|
||||
}) {
|
||||
pending.push(*branch);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
messages
|
||||
}
|
||||
|
||||
pub(crate) fn validate_diagram(p: &Project, diagram: &Diagram, out: &mut Vec<validation::Issue>) {
|
||||
if diagram.projection.scenario().is_none() {
|
||||
if diagram.layout.is_some() {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"scenario_layout_projection",
|
||||
"layout",
|
||||
"Only a Scenario projection accepts a Scenario layout, including an empty payload.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let scenario = match owner(p, diagram) {
|
||||
Ok(owner) => owner,
|
||||
Err(error) => {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"scenario_diagram_context",
|
||||
"projection",
|
||||
error.0,
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if !diagram.nodes.is_empty() || !diagram.routes.is_empty() {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"scenario_diagram_content",
|
||||
"layout",
|
||||
"Scenario views do not accept architecture node placements or edge routes.",
|
||||
);
|
||||
}
|
||||
let Some(DiagramLayout::Scenario(layout)) = &diagram.layout else {
|
||||
return;
|
||||
};
|
||||
let mut lanes = BTreeSet::new();
|
||||
for lane in &layout.lanes {
|
||||
if !lanes.insert(lane.lifeline) {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"duplicate_scenario_lane",
|
||||
"layout",
|
||||
"A Scenario layout has at most one position per lifeline.",
|
||||
);
|
||||
}
|
||||
if !lane_member(p, scenario, diagram.layer, lane.lifeline) {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"scenario_layout_lifeline",
|
||||
"layout",
|
||||
"Lane positions reference a Lifeline directly owned by the projected Scenario.",
|
||||
);
|
||||
}
|
||||
if !coordinate(lane.x) {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"scenario_layout_coordinate",
|
||||
"layout",
|
||||
"Scenario positions must be finite and within the shared coordinate bounds.",
|
||||
);
|
||||
}
|
||||
}
|
||||
let members = direct_messages(p, scenario, diagram.layer);
|
||||
let mut addresses = BTreeSet::new();
|
||||
for message in &layout.messages {
|
||||
// Reject expanded paths without cloning or indexing their potentially large contents.
|
||||
if !message.address.references.is_empty() {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"scenario_layout_address",
|
||||
"layout",
|
||||
"Expanded-reference message positions are not supported; references must be empty.",
|
||||
);
|
||||
} else if !addresses.insert(message.address.occurrence) {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"duplicate_scenario_message",
|
||||
"layout",
|
||||
"A Scenario layout has at most one position per message address.",
|
||||
);
|
||||
}
|
||||
if !members.contains(&message.address.occurrence) {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"scenario_layout_message",
|
||||
"layout",
|
||||
"Message positions reference Exchange occurrences in the Scenario's own ordered sequence tree.",
|
||||
);
|
||||
}
|
||||
if !coordinate(message.send_y) {
|
||||
validation::error(
|
||||
out,
|
||||
diagram.id,
|
||||
"scenario_layout_coordinate",
|
||||
"layout",
|
||||
"Scenario positions must be finite and within the shared coordinate bounds.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn editable(p: &Project, id: Id) -> Result<(&Diagram, Id), ModelError> {
|
||||
let diagram = p
|
||||
.diagrams
|
||||
.get(&id)
|
||||
.ok_or_else(|| ModelError("Scenario diagram does not exist.".into()))?;
|
||||
let scenario = owner(p, diagram)?;
|
||||
if !diagram.nodes.is_empty() || !diagram.routes.is_empty() {
|
||||
return Err(ModelError(
|
||||
"Scenario views do not accept architecture node placements or edge routes.".into(),
|
||||
));
|
||||
}
|
||||
Ok((diagram, scenario))
|
||||
}
|
||||
|
||||
fn check_message(
|
||||
p: &Project,
|
||||
diagram: &Diagram,
|
||||
owner: Id,
|
||||
address: &OccurrenceEndpoint,
|
||||
) -> Result<(), ModelError> {
|
||||
if !address.references.is_empty() {
|
||||
return Err(ModelError(
|
||||
"Expanded-reference message positions are not supported; references must be empty."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if !direct_messages(p, owner, diagram.layer).contains(&address.occurrence) {
|
||||
return Err(ModelError("Message position requires an Exchange occurrence in the Scenario's own ordered sequence tree.".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn payload(diagram: &mut Diagram) -> &mut ScenarioLayout {
|
||||
let DiagramLayout::Scenario(layout) = diagram
|
||||
.layout
|
||||
.get_or_insert_with(|| DiagramLayout::Scenario(ScenarioLayout::default()));
|
||||
layout
|
||||
}
|
||||
|
||||
/// Target-scoped preparation, not whole-project or whole-layout validation.
|
||||
/// Unrelated intermediate errors remain repairable by later commands in a batch.
|
||||
pub fn set_lane(
|
||||
p: &Project,
|
||||
diagram: Id,
|
||||
position: ScenarioLanePosition,
|
||||
) -> Result<Diagram, ModelError> {
|
||||
let (current, owner) = editable(p, diagram)?;
|
||||
if !lane_member(p, owner, current.layer, position.lifeline) || !coordinate(position.x) {
|
||||
return Err(ModelError(
|
||||
"Lane position requires an owned Lifeline and a finite bounded x coordinate.".into(),
|
||||
));
|
||||
}
|
||||
let mut result = current.clone();
|
||||
let layout = payload(&mut result);
|
||||
if layout
|
||||
.lanes
|
||||
.iter()
|
||||
.filter(|row| row.lifeline == position.lifeline)
|
||||
.count()
|
||||
> 1
|
||||
{
|
||||
return Err(ModelError(
|
||||
"Cannot set an ambiguous duplicate lane position.".into(),
|
||||
));
|
||||
}
|
||||
if let Some(existing) = layout
|
||||
.lanes
|
||||
.iter_mut()
|
||||
.find(|row| row.lifeline == position.lifeline)
|
||||
{
|
||||
if existing.x != position.x {
|
||||
*existing = position;
|
||||
}
|
||||
} else {
|
||||
layout.lanes.push(position);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn remove_lane(p: &Project, diagram: Id, lifeline: Id) -> Result<Diagram, ModelError> {
|
||||
let (current, owner) = editable(p, diagram)?;
|
||||
if !lane_member(p, owner, current.layer, lifeline) {
|
||||
return Err(ModelError(
|
||||
"Removing a lane position requires an owned Lifeline.".into(),
|
||||
));
|
||||
}
|
||||
let mut result = current.clone();
|
||||
if let Some(DiagramLayout::Scenario(layout)) = &mut result.layout {
|
||||
layout.lanes.retain(|row| row.lifeline != lifeline);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn set_message(
|
||||
p: &Project,
|
||||
diagram: Id,
|
||||
position: ScenarioMessagePosition,
|
||||
) -> Result<Diagram, ModelError> {
|
||||
let (current, owner) = editable(p, diagram)?;
|
||||
check_message(p, current, owner, &position.address)?;
|
||||
if !coordinate(position.send_y) {
|
||||
return Err(ModelError(
|
||||
"Message position requires a finite bounded send_y coordinate.".into(),
|
||||
));
|
||||
}
|
||||
let mut result = current.clone();
|
||||
let layout = payload(&mut result);
|
||||
if layout
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|row| row.address == position.address)
|
||||
.count()
|
||||
> 1
|
||||
{
|
||||
return Err(ModelError(
|
||||
"Cannot set an ambiguous duplicate message position.".into(),
|
||||
));
|
||||
}
|
||||
if let Some(existing) = layout
|
||||
.messages
|
||||
.iter_mut()
|
||||
.find(|row| row.address == position.address)
|
||||
{
|
||||
if existing.send_y != position.send_y {
|
||||
*existing = position;
|
||||
}
|
||||
} else {
|
||||
layout.messages.push(position);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn remove_message(
|
||||
p: &Project,
|
||||
diagram: Id,
|
||||
address: &OccurrenceEndpoint,
|
||||
) -> Result<Diagram, ModelError> {
|
||||
let (current, owner) = editable(p, diagram)?;
|
||||
check_message(p, current, owner, address)?;
|
||||
let mut result = current.clone();
|
||||
if let Some(DiagramLayout::Scenario(layout)) = &mut result.layout {
|
||||
layout.messages.retain(|row| &row.address != address);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Prune only identities in the caller's actual deletion closure, never visibility
|
||||
/// or missing endpoint assignments. Owner-view cascade remains the caller's job.
|
||||
pub fn prune_deleted(diagram: &mut Diagram, deleted: &BTreeSet<Id>) {
|
||||
if let Some(DiagramLayout::Scenario(layout)) = &mut diagram.layout {
|
||||
layout
|
||||
.lanes
|
||||
.retain(|lane| !deleted.contains(&lane.lifeline));
|
||||
layout.messages.retain(|message| {
|
||||
!deleted.contains(&message.address.occurrence)
|
||||
&& !message
|
||||
.address
|
||||
.references
|
||||
.iter()
|
||||
.any(|id| deleted.contains(id))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,802 @@
|
||||
use super::*;
|
||||
use crate::{
|
||||
Element, FragmentOperator, MessageKind, ProjectionKind, Relation, RelationBody, RelationKind,
|
||||
ScenarioViewpoint,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
struct Fixture {
|
||||
project: Project,
|
||||
owner: Id,
|
||||
performer: Id,
|
||||
lane: Id,
|
||||
repeated_lane: Id,
|
||||
first: Id,
|
||||
second: Id,
|
||||
nested: Id,
|
||||
fragment: Id,
|
||||
branch: Id,
|
||||
view: Id,
|
||||
other_view: Id,
|
||||
exchange: Id,
|
||||
}
|
||||
|
||||
fn set_body(element: &mut Element, body: OccurrenceBody) {
|
||||
*element.shared_mut().unwrap() = SharedBody::Occurrence {
|
||||
body,
|
||||
precondition: String::new(),
|
||||
postcondition: String::new(),
|
||||
};
|
||||
}
|
||||
fn address(occurrence: Id) -> OccurrenceEndpoint {
|
||||
OccurrenceEndpoint {
|
||||
references: vec![],
|
||||
occurrence,
|
||||
}
|
||||
}
|
||||
fn diagram(owner: Id, alias: &str) -> Diagram {
|
||||
Diagram {
|
||||
id: Id::new_v4(),
|
||||
alias: alias.into(),
|
||||
name: alias.into(),
|
||||
description: String::new(),
|
||||
layer: Layer::Oa,
|
||||
projection: ProjectionKind::Scenario { scenario: owner },
|
||||
view_options: Default::default(),
|
||||
nodes: BTreeMap::new(),
|
||||
routes: vec![],
|
||||
layout: None,
|
||||
}
|
||||
}
|
||||
fn assert_admitted(project: &Project) {
|
||||
let errors: Vec<_> = validation::validate(project)
|
||||
.into_iter()
|
||||
.filter(|issue| issue.severity == validation::Severity::Error)
|
||||
.collect();
|
||||
assert!(errors.is_empty(), "{errors:?}");
|
||||
}
|
||||
fn has_code(project: &Project, code: &str) -> bool {
|
||||
validation::validate(project)
|
||||
.iter()
|
||||
.any(|issue| issue.code == code)
|
||||
}
|
||||
fn layout(diagram: &Diagram) -> &ScenarioLayout {
|
||||
let Some(DiagramLayout::Scenario(layout)) = &diagram.layout else {
|
||||
panic!("expected saved payload")
|
||||
};
|
||||
layout
|
||||
}
|
||||
fn save(project: &mut Project, replacement: Diagram) {
|
||||
project.diagrams.insert(replacement.id, replacement);
|
||||
}
|
||||
fn fixture() -> Fixture {
|
||||
let mut project = Project::empty();
|
||||
let owner = project
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Nominal", None)
|
||||
.unwrap();
|
||||
let Some(SharedBody::Scenario { viewpoint, .. }) =
|
||||
project.elements.get_mut(&owner).unwrap().shared_mut()
|
||||
else {
|
||||
panic!("Scenario fixture body");
|
||||
};
|
||||
*viewpoint = ScenarioViewpoint::ParticipantInteraction;
|
||||
let performer = project
|
||||
.add_element(Kind::Entity, Layer::Oa, "Controller", None)
|
||||
.unwrap();
|
||||
let receiver = project
|
||||
.add_element(Kind::Entity, Layer::Oa, "Provider", None)
|
||||
.unwrap();
|
||||
let lane = project
|
||||
.add_element(Kind::Lifeline, Layer::Oa, "Controller lane", Some(owner))
|
||||
.unwrap();
|
||||
let repeated_lane = project
|
||||
.add_element(
|
||||
Kind::Lifeline,
|
||||
Layer::Oa,
|
||||
"Controller review lane",
|
||||
Some(owner),
|
||||
)
|
||||
.unwrap();
|
||||
let receiver_lane = project
|
||||
.add_element(Kind::Lifeline, Layer::Oa, "Provider lane", Some(owner))
|
||||
.unwrap();
|
||||
for (id, represented) in [
|
||||
(lane, performer),
|
||||
(repeated_lane, performer),
|
||||
(receiver_lane, receiver),
|
||||
] {
|
||||
*project.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::Lifeline {
|
||||
represented: Some(represented),
|
||||
};
|
||||
}
|
||||
let exchange = Id::new_v4();
|
||||
project.relations.insert(
|
||||
exchange,
|
||||
Relation {
|
||||
id: exchange,
|
||||
alias: "delivery_channel".into(),
|
||||
name: "Delivery".into(),
|
||||
description: String::new(),
|
||||
body: RelationBody::new(RelationKind::CommunicationMean, performer, receiver),
|
||||
},
|
||||
);
|
||||
let first = project
|
||||
.add_element(Kind::Occurrence, Layer::Oa, "First delivery", Some(owner))
|
||||
.unwrap();
|
||||
let second = project
|
||||
.add_element(Kind::Occurrence, Layer::Oa, "Second delivery", Some(owner))
|
||||
.unwrap();
|
||||
for (id, sender) in [(first, lane), (second, repeated_lane)] {
|
||||
set_body(
|
||||
project.elements.get_mut(&id).unwrap(),
|
||||
OccurrenceBody::Exchange {
|
||||
exchange: Some(exchange),
|
||||
sender: Some(sender),
|
||||
receiver: Some(receiver_lane),
|
||||
message_kind: MessageKind::Asynchronous,
|
||||
reply_to: None,
|
||||
values: vec![],
|
||||
operation: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
let fragment = project
|
||||
.add_element(
|
||||
Kind::Occurrence,
|
||||
Layer::Oa,
|
||||
"Optional delivery",
|
||||
Some(owner),
|
||||
)
|
||||
.unwrap();
|
||||
set_body(
|
||||
project.elements.get_mut(&fragment).unwrap(),
|
||||
OccurrenceBody::Fragment {
|
||||
operator: FragmentOperator::Optional,
|
||||
branches: vec![],
|
||||
},
|
||||
);
|
||||
let branch = project
|
||||
.add_element(Kind::Occurrence, Layer::Oa, "Option body", Some(fragment))
|
||||
.unwrap();
|
||||
let nested = project
|
||||
.add_element(
|
||||
Kind::Occurrence,
|
||||
Layer::Oa,
|
||||
"Unfinished nested delivery",
|
||||
Some(branch),
|
||||
)
|
||||
.unwrap();
|
||||
set_body(
|
||||
project.elements.get_mut(&nested).unwrap(),
|
||||
OccurrenceBody::Exchange {
|
||||
exchange: None,
|
||||
sender: None,
|
||||
receiver: None,
|
||||
message_kind: MessageKind::Asynchronous,
|
||||
reply_to: None,
|
||||
values: vec![],
|
||||
operation: None,
|
||||
},
|
||||
);
|
||||
set_body(
|
||||
project.elements.get_mut(&branch).unwrap(),
|
||||
OccurrenceBody::Branch {
|
||||
guard: "requested".into(),
|
||||
occurrences: vec![nested],
|
||||
},
|
||||
);
|
||||
set_body(
|
||||
project.elements.get_mut(&fragment).unwrap(),
|
||||
OccurrenceBody::Fragment {
|
||||
operator: FragmentOperator::Optional,
|
||||
branches: vec![branch],
|
||||
},
|
||||
);
|
||||
*project
|
||||
.elements
|
||||
.get_mut(&owner)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap() = vec![first, second, fragment];
|
||||
let view_record = diagram(owner, "nominal_view");
|
||||
let other_record = diagram(owner, "review_view");
|
||||
let view = view_record.id;
|
||||
let other_view = other_record.id;
|
||||
save(&mut project, view_record);
|
||||
save(&mut project, other_record);
|
||||
assert_admitted(&project);
|
||||
Fixture {
|
||||
project,
|
||||
owner,
|
||||
performer,
|
||||
lane,
|
||||
repeated_lane,
|
||||
first,
|
||||
second,
|
||||
nested,
|
||||
fragment,
|
||||
branch,
|
||||
view,
|
||||
other_view,
|
||||
exchange,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_views_and_repeated_semantic_definitions_keep_independent_overrides() {
|
||||
let mut f = fixture();
|
||||
let semantics = (f.project.elements.clone(), f.project.relations.clone());
|
||||
for (view, line, x) in [
|
||||
(f.view, f.lane, 420.),
|
||||
(f.view, f.repeated_lane, 680.),
|
||||
(f.other_view, f.lane, 900.),
|
||||
] {
|
||||
let result =
|
||||
set_lane(&f.project, view, ScenarioLanePosition { lifeline: line, x }).unwrap();
|
||||
save(&mut f.project, result);
|
||||
}
|
||||
for (view, id, y) in [
|
||||
(f.view, f.first, 200.),
|
||||
(f.view, f.second, 350.),
|
||||
(f.other_view, f.first, 260.),
|
||||
] {
|
||||
let result = set_message(
|
||||
&f.project,
|
||||
view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(id),
|
||||
send_y: y,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
}
|
||||
assert_eq!(
|
||||
layout(&f.project.diagrams[&f.view]).lanes,
|
||||
vec![
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: 420.
|
||||
},
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.repeated_lane,
|
||||
x: 680.
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
layout(&f.project.diagrams[&f.view])
|
||||
.messages
|
||||
.iter()
|
||||
.map(|r| (r.address.occurrence, r.send_y))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![(f.first, 200.), (f.second, 350.)]
|
||||
);
|
||||
assert_eq!(
|
||||
layout(&f.project.diagrams[&f.other_view]).messages[0].send_y,
|
||||
260.
|
||||
);
|
||||
assert_eq!(layout(&f.project.diagrams[&f.other_view]).lanes[0].x, 900.);
|
||||
assert_eq!(
|
||||
(f.project.elements.clone(), f.project.relations.clone()),
|
||||
semantics
|
||||
);
|
||||
assert_admitted(&f.project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_nested_unfinished_message_is_admitted_but_expansion_is_not() {
|
||||
let mut f = fixture();
|
||||
let result = set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.nested),
|
||||
send_y: -80.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
assert_admitted(&f.project);
|
||||
let before = f.project.clone();
|
||||
let expanded = OccurrenceEndpoint {
|
||||
references: vec![f.fragment],
|
||||
occurrence: f.nested,
|
||||
};
|
||||
assert!(
|
||||
set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: expanded.clone(),
|
||||
send_y: 400.
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(remove_message(&f.project, f.view, &expanded).is_err());
|
||||
assert_eq!(f.project, before);
|
||||
payload(f.project.diagrams.get_mut(&f.view).unwrap()).messages[0].address = expanded;
|
||||
assert!(has_code(&f.project, "scenario_layout_address"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_ordered_message_appearances_and_owned_lifelines_are_targets() {
|
||||
let mut f = fixture();
|
||||
assert!(
|
||||
set_lane(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.performer,
|
||||
x: 10.
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
for id in [f.exchange, f.fragment, f.branch, f.owner, Id::new_v4()] {
|
||||
assert!(
|
||||
set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(id),
|
||||
send_y: 100.
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let foreign = f
|
||||
.project
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Foreign", None)
|
||||
.unwrap();
|
||||
let foreign_lane = f
|
||||
.project
|
||||
.add_element(Kind::Lifeline, Layer::Oa, "Foreign lane", Some(foreign))
|
||||
.unwrap();
|
||||
assert!(remove_lane(&f.project, f.view, foreign_lane).is_err());
|
||||
f.project.elements.get_mut(&f.first).unwrap().parent = Some(foreign);
|
||||
assert!(
|
||||
set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: 100.
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
f.project.elements.get_mut(&f.first).unwrap().parent = Some(f.owner);
|
||||
f.project
|
||||
.elements
|
||||
.get_mut(&f.owner)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap()
|
||||
.retain(|id| *id != f.first);
|
||||
assert!(
|
||||
set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: 100.
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_positions_reject_even_when_values_match() {
|
||||
let mut f = fixture();
|
||||
let lane = ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: 10.,
|
||||
};
|
||||
let message = ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: 100.,
|
||||
};
|
||||
let entries = payload(f.project.diagrams.get_mut(&f.view).unwrap());
|
||||
entries.lanes = vec![lane.clone(), lane.clone()];
|
||||
entries.messages = vec![message.clone(), message.clone()];
|
||||
assert!(has_code(&f.project, "duplicate_scenario_lane"));
|
||||
assert!(has_code(&f.project, "duplicate_scenario_message"));
|
||||
assert!(set_lane(&f.project, f.view, lane).is_err());
|
||||
assert!(set_message(&f.project, f.view, message).is_err());
|
||||
// Explicit removal can repair all duplicates of the targeted identity.
|
||||
let result = remove_lane(&f.project, f.view, f.lane).unwrap();
|
||||
save(&mut f.project, result);
|
||||
let result = remove_message(&f.project, f.view, &address(f.first)).unwrap();
|
||||
save(&mut f.project, result);
|
||||
assert_admitted(&f.project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_absence_empty_payload_and_signed_zero_are_preserved() {
|
||||
let mut f = fixture();
|
||||
let absent = f.project.diagrams[&f.view].clone();
|
||||
assert_eq!(remove_lane(&f.project, f.view, f.lane).unwrap(), absent);
|
||||
assert_eq!(
|
||||
remove_message(&f.project, f.view, &address(f.first)).unwrap(),
|
||||
absent
|
||||
);
|
||||
assert!(
|
||||
serde_json::to_value(&absent)
|
||||
.unwrap()
|
||||
.get("layout")
|
||||
.is_none()
|
||||
);
|
||||
let result = set_lane(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: -0.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
let result = set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: -0.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
let result = set_lane(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: 0.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(layout(&result).lanes[0].x.to_bits(), (-0.0_f32).to_bits());
|
||||
let result = set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: 0.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
layout(&result).messages[0].send_y.to_bits(),
|
||||
(-0.0_f32).to_bits()
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&result).unwrap(),
|
||||
serde_json::to_string(&f.project.diagrams[&f.view]).unwrap()
|
||||
);
|
||||
let result = remove_lane(&f.project, f.view, f.lane).unwrap();
|
||||
save(&mut f.project, result);
|
||||
let result = remove_message(&f.project, f.view, &address(f.first)).unwrap();
|
||||
assert_eq!(
|
||||
result.layout,
|
||||
Some(DiagramLayout::Scenario(ScenarioLayout::default()))
|
||||
);
|
||||
assert_ne!(result, absent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_are_structural_and_rejected_helpers_do_not_mutate_project() {
|
||||
let mut f = fixture();
|
||||
for value in [-MAX_COORDINATE, MAX_COORDINATE, -7., 0.] {
|
||||
let result = set_lane(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: value,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
let result = set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: value,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
assert_admitted(&f.project);
|
||||
}
|
||||
let before = serde_json::to_string(&f.project).unwrap();
|
||||
for value in [
|
||||
f32::NAN,
|
||||
f32::INFINITY,
|
||||
f32::NEG_INFINITY,
|
||||
MAX_COORDINATE + 1.,
|
||||
] {
|
||||
assert!(
|
||||
set_lane(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: value
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: value
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(serde_json::to_string(&f.project).unwrap(), before);
|
||||
payload(f.project.diagrams.get_mut(&f.view).unwrap()).messages[0].send_y = f32::NAN;
|
||||
assert!(has_code(&f.project, "scenario_layout_coordinate"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helpers_do_not_validate_unrelated_transient_records_in_repair_batches() {
|
||||
let mut f = fixture();
|
||||
payload(f.project.diagrams.get_mut(&f.view).unwrap())
|
||||
.messages
|
||||
.push(ScenarioMessagePosition {
|
||||
address: address(f.second),
|
||||
send_y: f32::INFINITY,
|
||||
});
|
||||
let result = set_lane(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: 420.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
assert!(has_code(&f.project, "scenario_layout_coordinate"));
|
||||
let result = set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.second),
|
||||
send_y: 300.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
assert_admitted(&f.project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_context_and_architecture_payloads_are_explicitly_separate() {
|
||||
let mut f = fixture();
|
||||
let scenario = f.project.diagrams[&f.view].projection;
|
||||
assert_eq!(scenario.scenario(), Some(f.owner));
|
||||
assert!(!scenario.is_architecture());
|
||||
assert!(!scenario.includes(Kind::Lifeline));
|
||||
assert!(ProjectionKind::Overview.is_architecture());
|
||||
assert!(!ProjectionKind::StateMachine { machine: f.owner }.is_architecture());
|
||||
f.project.diagrams.get_mut(&f.view).unwrap().layer = Layer::Sa;
|
||||
assert!(has_code(&f.project, "scenario_diagram_context"));
|
||||
assert!(remove_lane(&f.project, f.view, f.lane).is_err());
|
||||
f.project.diagrams.get_mut(&f.view).unwrap().layer = Layer::Oa;
|
||||
f.project
|
||||
.diagrams
|
||||
.get_mut(&f.view)
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(crate::EdgeRoute {
|
||||
edge: f.exchange,
|
||||
source_attachment: None,
|
||||
target_attachment: None,
|
||||
waypoints: vec![],
|
||||
label: None,
|
||||
});
|
||||
assert!(has_code(&f.project, "scenario_diagram_content"));
|
||||
f.project.diagrams.get_mut(&f.view).unwrap().routes.clear();
|
||||
payload(f.project.diagrams.get_mut(&f.view).unwrap());
|
||||
f.project.diagrams.get_mut(&f.view).unwrap().projection = ProjectionKind::Overview;
|
||||
assert!(has_code(&f.project, "scenario_layout_projection"));
|
||||
assert!(
|
||||
set_lane(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: 10.
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_json_records_round_trip_and_reject_unknown_or_missing_fields() {
|
||||
let mut f = fixture();
|
||||
let result = set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: 200.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
let encoded = serde_json::to_value(&f.project.diagrams[&f.view]).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_value::<Diagram>(encoded.clone()).unwrap(),
|
||||
f.project.diagrams[&f.view]
|
||||
);
|
||||
assert_eq!(
|
||||
encoded["layout"]["Scenario"]["messages"][0]["address"]["occurrence"],
|
||||
serde_json::json!(f.first)
|
||||
);
|
||||
let mut unknown = encoded.clone();
|
||||
unknown["layout"]["Scenario"]["messages"][0]["extra"] = serde_json::json!(1);
|
||||
assert!(serde_json::from_value::<Diagram>(unknown).is_err());
|
||||
let mut missing = encoded;
|
||||
missing["layout"]["Scenario"]["messages"][0]["address"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("references");
|
||||
assert!(serde_json::from_value::<Diagram>(missing).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_only_actual_ids_preserves_latent_message_positions_and_other_views() {
|
||||
let mut f = fixture();
|
||||
let result = set_lane(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: 420.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
let result = set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: 200.,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
save(&mut f.project, result);
|
||||
let mut copied = f.project.diagrams[&f.view].clone();
|
||||
copied.id = f.other_view;
|
||||
copied.alias = "review_view".into();
|
||||
copied.name = "Review view".into();
|
||||
save(&mut f.project, copied.clone());
|
||||
assert_admitted(&f.project);
|
||||
assert_eq!(layout(&copied).messages[0].address.occurrence, f.first);
|
||||
let mut candidate = f.project.diagrams[&f.view].clone();
|
||||
prune_deleted(&mut candidate, &BTreeSet::from([f.lane, f.exchange]));
|
||||
assert!(layout(&candidate).lanes.is_empty());
|
||||
assert_eq!(layout(&candidate).messages.len(), 1);
|
||||
prune_deleted(&mut candidate, &BTreeSet::from([f.first]));
|
||||
assert!(layout(&candidate).messages.is_empty());
|
||||
assert!(candidate.layout.is_some());
|
||||
assert_eq!(f.project.diagrams[&f.other_view], copied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_visitor_and_record_count_cover_explicit_rows() {
|
||||
let f = fixture();
|
||||
let mut d = f.project.diagrams[&f.view].clone();
|
||||
assert_eq!(record_count(&d), 0);
|
||||
let rows = payload(&mut d);
|
||||
rows.lanes.push(ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: 50.,
|
||||
});
|
||||
rows.messages.push(ScenarioMessagePosition {
|
||||
address: address(f.first),
|
||||
send_y: 100.,
|
||||
});
|
||||
assert_eq!(record_count(&d), 3);
|
||||
let replacement = Id::new_v4();
|
||||
d.layout.as_mut().unwrap().visit_references(|id| {
|
||||
if *id == f.first {
|
||||
*id = replacement;
|
||||
}
|
||||
});
|
||||
assert_eq!(layout(&d).messages[0].address.occurrence, replacement);
|
||||
assert_eq!(layout(&d).messages[0].send_y, 100.);
|
||||
assert_eq!(layout(&d).lanes[0].lifeline, f.lane);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_scenario_use_never_imports_its_called_message_as_a_direct_target() {
|
||||
let mut f = fixture();
|
||||
let called = f
|
||||
.project
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Called sequence", None)
|
||||
.unwrap();
|
||||
let Some(SharedBody::Scenario { viewpoint, .. }) =
|
||||
f.project.elements.get_mut(&called).unwrap().shared_mut()
|
||||
else {
|
||||
panic!("Called Scenario fixture body");
|
||||
};
|
||||
*viewpoint = ScenarioViewpoint::ParticipantInteraction;
|
||||
let called_message = f
|
||||
.project
|
||||
.add_element(Kind::Occurrence, Layer::Oa, "Called delivery", Some(called))
|
||||
.unwrap();
|
||||
set_body(
|
||||
f.project.elements.get_mut(&called_message).unwrap(),
|
||||
OccurrenceBody::Exchange {
|
||||
exchange: None,
|
||||
sender: None,
|
||||
receiver: None,
|
||||
message_kind: MessageKind::Asynchronous,
|
||||
reply_to: None,
|
||||
values: vec![],
|
||||
operation: None,
|
||||
},
|
||||
);
|
||||
*f.project
|
||||
.elements
|
||||
.get_mut(&called)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap() = vec![called_message];
|
||||
let usage = f
|
||||
.project
|
||||
.add_element(Kind::Occurrence, Layer::Oa, "Call sequence", Some(f.owner))
|
||||
.unwrap();
|
||||
set_body(
|
||||
f.project.elements.get_mut(&usage).unwrap(),
|
||||
OccurrenceBody::ScenarioUse {
|
||||
scenario: Some(called),
|
||||
bindings: vec![],
|
||||
},
|
||||
);
|
||||
f.project
|
||||
.elements
|
||||
.get_mut(&f.owner)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap()
|
||||
.push(usage);
|
||||
assert_admitted(&f.project);
|
||||
for target in [
|
||||
address(called_message),
|
||||
address(usage),
|
||||
OccurrenceEndpoint {
|
||||
references: vec![usage],
|
||||
occurrence: called_message,
|
||||
},
|
||||
] {
|
||||
assert!(
|
||||
set_message(
|
||||
&f.project,
|
||||
f.view,
|
||||
ScenarioMessagePosition {
|
||||
address: target,
|
||||
send_y: 200.
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
mod source_lifecycle;
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Source/command lifecycle checks for the candidate payload. Public version
|
||||
//! assignment remains the coordinated codec integration gate.
|
||||
use super::*;
|
||||
use crate::{Command, Session, language, prepare_command, source_project::*};
|
||||
|
||||
fn authored(f: &Fixture) -> CompiledSourceProject {
|
||||
let mut bundle = format_bundle(&f.project);
|
||||
let initial = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
|
||||
let location = &initial.index.declarations[&f.view];
|
||||
let source = bundle.files.get_mut(&location.path).unwrap();
|
||||
let text = format!(
|
||||
r#"diagram nominal_view "Nominal review" id "{}" {{
|
||||
projection {{ Scenario {{ scenario @{}; }}; }};
|
||||
layout {{ Scenario {{
|
||||
lanes [
|
||||
// Controller spacing rationale.
|
||||
{{ lifeline @ // first lane identity
|
||||
{}; x 4.20e2; }},
|
||||
// Repeated performer has its own lane.
|
||||
{{ lifeline @{}; x 680; }}
|
||||
];
|
||||
messages [
|
||||
// First delivery timing rationale.
|
||||
{{ address {{ references []; occurrence @{}; }}; send_y 2.00e2; }},
|
||||
// Second delivery timing rationale.
|
||||
{{ address {{ references []; occurrence @{}; }}; send_y 350; }}
|
||||
];
|
||||
}}; }};
|
||||
}}
|
||||
"#,
|
||||
f.view,
|
||||
f.project.elements[&f.owner].alias,
|
||||
f.project.elements[&f.lane].alias,
|
||||
f.project.elements[&f.repeated_lane].alias,
|
||||
f.project.elements[&f.first].alias,
|
||||
f.project.elements[&f.second].alias
|
||||
);
|
||||
source.replace_range(location.span.start..location.span.end, &text);
|
||||
compile_bundle(&bundle, ProjectLimits::default()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_rows_follow_identity_order_and_keep_comments_numeric_spelling_and_file_ownership() {
|
||||
let f = fixture();
|
||||
let original = authored(&f);
|
||||
let mut changed = original.decoded.project.clone();
|
||||
let rows = payload(changed.diagrams.get_mut(&f.view).unwrap());
|
||||
rows.lanes.swap(0, 1);
|
||||
rows.messages.swap(0, 1);
|
||||
rows.messages[0].send_y = 390.;
|
||||
changed.elements.get_mut(&f.lane).unwrap().alias = "renamed_controller_lane".into();
|
||||
let updated = update_bundle(&original, &changed, ProjectLimits::default()).unwrap();
|
||||
assert_eq!(updated.decoded.project, changed);
|
||||
let path = &original.index.declarations[&f.view].path;
|
||||
assert_eq!(&updated.index.declarations[&f.view].path, path);
|
||||
let text = &updated.bundle.files[path];
|
||||
assert!(
|
||||
text.find("// Repeated performer").unwrap() < text.find("// Controller spacing").unwrap(),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.find("// Second delivery").unwrap() < text.find("// First delivery").unwrap(),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains(
|
||||
"lifeline @ // first lane identity\n renamed_controller_lane; x 4.20e2;"
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains("send_y 2.00e2"), "{text}");
|
||||
assert!(text.contains("send_y 390"), "{text}");
|
||||
for (other, bytes) in &original.bundle.files {
|
||||
if other != path && !bytes.contains(&f.project.elements[&f.lane].alias) {
|
||||
assert_eq!(&updated.bundle.files[other], bytes);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
compile_bundle(&updated.bundle, ProjectLimits::default())
|
||||
.unwrap()
|
||||
.decoded
|
||||
.project,
|
||||
changed
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_identity_swap_keeps_each_coordinate_comment_with_its_original_object() {
|
||||
let f = fixture();
|
||||
let original = authored(&f);
|
||||
let temporary = Id::new_v4();
|
||||
let command = Command::Batch(vec![
|
||||
Command::Reidentify(f.first, temporary),
|
||||
Command::Reidentify(f.second, f.first),
|
||||
Command::Reidentify(temporary, f.second),
|
||||
]);
|
||||
let prepared = prepare_command(&original.decoded.project, &command).unwrap();
|
||||
let mut changed = prepared.project;
|
||||
payload(changed.diagrams.get_mut(&f.view).unwrap())
|
||||
.messages
|
||||
.swap(0, 1);
|
||||
let updated = update_bundle_with_identity_map(
|
||||
&original,
|
||||
&changed,
|
||||
&prepared.identity_map,
|
||||
ProjectLimits::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(updated.decoded.project, changed);
|
||||
let path = &original.index.declarations[&f.view].path;
|
||||
let text = &updated.bundle.files[path];
|
||||
assert!(
|
||||
text.find("// Second delivery").unwrap() < text.find("// First delivery").unwrap(),
|
||||
"{text}"
|
||||
);
|
||||
let first_comment = text.find("// First delivery").unwrap();
|
||||
assert!(text[first_comment..].contains(&format!(
|
||||
"occurrence @{}",
|
||||
changed.elements[&f.second].alias
|
||||
)));
|
||||
assert!(text[first_comment..].contains("send_y 2.00e2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coordinate_batch_is_one_undo_and_numeric_noop_keeps_source_exact() {
|
||||
let f = fixture();
|
||||
let original = authored(&f);
|
||||
let mut session = Session::new(original.decoded.project.clone());
|
||||
session
|
||||
.execute(Command::Batch(vec![
|
||||
Command::SetScenarioLanePosition {
|
||||
diagram: f.view,
|
||||
position: ScenarioLanePosition {
|
||||
lifeline: f.lane,
|
||||
x: 510.,
|
||||
},
|
||||
},
|
||||
Command::SetScenarioMessagePosition {
|
||||
diagram: f.view,
|
||||
position: ScenarioMessagePosition {
|
||||
address: address(f.second),
|
||||
send_y: 430.,
|
||||
},
|
||||
},
|
||||
]))
|
||||
.unwrap();
|
||||
let changed = session.project().clone();
|
||||
assert_eq!(session.revision(), 1);
|
||||
assert_eq!(changed.elements, original.decoded.project.elements);
|
||||
assert_eq!(changed.relations, original.decoded.project.relations);
|
||||
let updated = update_bundle(&original, &changed, ProjectLimits::default()).unwrap();
|
||||
session.undo();
|
||||
assert_eq!(session.project(), &original.decoded.project);
|
||||
assert!(!session.can_undo());
|
||||
session.redo();
|
||||
assert_eq!(session.project(), &changed);
|
||||
session
|
||||
.execute(Command::SetScenarioMessagePosition {
|
||||
diagram: f.view,
|
||||
position: ScenarioMessagePosition {
|
||||
address: address(f.second),
|
||||
send_y: 430.,
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(session.revision(), 3);
|
||||
let noop = update_bundle(&updated, session.project(), ProjectLimits::default()).unwrap();
|
||||
assert_eq!(noop.bundle, updated.bundle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_and_empty_payload_round_trip_distinctly_and_remove_does_not_materialize_absence() {
|
||||
let f = fixture();
|
||||
let before = language::format(&f.project);
|
||||
let mut session = Session::new(f.project.clone());
|
||||
session
|
||||
.execute(Command::RemoveScenarioLanePosition {
|
||||
diagram: f.view,
|
||||
lifeline: f.lane,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(session.project(), &f.project);
|
||||
assert!(!session.can_undo());
|
||||
assert_eq!(language::format(session.project()), before);
|
||||
let mut present = f.project.clone();
|
||||
present.diagrams.get_mut(&f.view).unwrap().layout =
|
||||
Some(DiagramLayout::Scenario(ScenarioLayout::default()));
|
||||
let text = language::format(&present);
|
||||
assert_ne!(text, before);
|
||||
assert_eq!(language::parse(&text).unwrap(), present);
|
||||
assert_eq!(language::parse(&before).unwrap(), f.project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_layout_source_rejects_without_changing_last_compiled_workspace() {
|
||||
let f = fixture();
|
||||
let original = authored(&f);
|
||||
let before = original.bundle.clone();
|
||||
let path = original.index.declarations[&f.view].path.clone();
|
||||
for replacement in ["x 1e30", "x not_a_number"] {
|
||||
let mut candidate = before.clone();
|
||||
let source = candidate.files.get_mut(&path).unwrap();
|
||||
*source = source.replace("x 4.20e2", replacement);
|
||||
assert!(compile_bundle(&candidate, ProjectLimits::default()).is_err());
|
||||
assert_eq!(original.bundle, before);
|
||||
}
|
||||
let mut candidate = before.clone();
|
||||
let source = candidate.files.get_mut(&path).unwrap();
|
||||
*source = source.replace(
|
||||
&format!("occurrence @{}", f.project.elements[&f.first].alias),
|
||||
&format!("occurrence @{}", f.project.elements[&f.performer].alias),
|
||||
);
|
||||
assert!(compile_bundle(&candidate, ProjectLimits::default()).is_err());
|
||||
assert_eq!(original.bundle, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_none_survives_other_edits_while_real_payload_clear_removes_values() {
|
||||
let f = fixture();
|
||||
let mut bundle = format_bundle(&f.project);
|
||||
let compiled = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
|
||||
let location = &compiled.index.declarations[&f.view];
|
||||
let path = location.path.clone();
|
||||
bundle.files.get_mut(&path).unwrap().insert_str(
|
||||
location.span.end - 1,
|
||||
"\n layout // explicitly automatic\n none;\n",
|
||||
);
|
||||
let original = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
|
||||
let mut described = original.decoded.project.clone();
|
||||
described.diagrams.get_mut(&f.view).unwrap().description =
|
||||
"Review spacing independently".into();
|
||||
let updated = update_bundle(&original, &described, ProjectLimits::default()).unwrap();
|
||||
assert!(updated.bundle.files[&path].contains("layout // explicitly automatic\n none;"));
|
||||
assert_eq!(updated.decoded.project, described);
|
||||
let mut empty = described.clone();
|
||||
empty.diagrams.get_mut(&f.view).unwrap().layout =
|
||||
Some(DiagramLayout::Scenario(ScenarioLayout::default()));
|
||||
let present = update_bundle(&updated, &empty, ProjectLimits::default()).unwrap();
|
||||
assert_eq!(present.decoded.project, empty);
|
||||
assert!(present.bundle.files[&path].contains("// explicitly automatic"));
|
||||
let cleared = update_bundle(&present, &described, ProjectLimits::default()).unwrap();
|
||||
assert_eq!(cleared.decoded.project, described);
|
||||
assert!(!cleared.bundle.files[&path].contains("layout"));
|
||||
assert!(cleared.bundle.files[&path].contains("// explicitly automatic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_defaults_and_scenario_row_identity_compose_through_rename_and_clear() {
|
||||
let f = fixture();
|
||||
let initial = authored(&f);
|
||||
let mut bundle = initial.bundle.clone();
|
||||
let location = &initial.index.declarations[&f.performer];
|
||||
bundle.files.get_mut(&location.path).unwrap().insert_str(
|
||||
location.span.end - 1,
|
||||
"\n description // explicitly default prose\n \"\";\n",
|
||||
);
|
||||
let original = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
|
||||
let mut expected = original.decoded.project.clone();
|
||||
let performer = expected.elements.get_mut(&f.performer).unwrap();
|
||||
performer.name = "Reviewed controller".into();
|
||||
performer.alias = "reviewed_controller".into();
|
||||
expected.elements.get_mut(&f.lane).unwrap().alias = "reviewed_lane".into();
|
||||
let rows = payload(expected.diagrams.get_mut(&f.view).unwrap());
|
||||
rows.lanes.swap(0, 1);
|
||||
rows.messages.swap(0, 1);
|
||||
rows.messages[0].send_y = 390.;
|
||||
let updated = update_bundle(&original, &expected, ProjectLimits::default()).unwrap();
|
||||
assert_eq!(updated.decoded.project, expected);
|
||||
let element = &updated.index.declarations[&f.performer];
|
||||
let text = &updated.bundle.files[&element.path][element.span.start..element.span.end];
|
||||
assert!(
|
||||
text.contains("description // explicitly default prose\n \"\";"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
!text.contains("categories"),
|
||||
"an omitted default must stay omitted: {text}"
|
||||
);
|
||||
let diagram = &updated.index.declarations[&f.view];
|
||||
let text = &updated.bundle.files[&diagram.path][diagram.span.start..diagram.span.end];
|
||||
assert!(
|
||||
text.find("// Repeated performer").unwrap() < text.find("// Controller spacing").unwrap()
|
||||
);
|
||||
assert!(text.contains("reviewed_lane; x 4.20e2;"), "{text}");
|
||||
assert!(text.find("// Second delivery").unwrap() < text.find("// First delivery").unwrap());
|
||||
assert!(text.contains("send_y 2.00e2"), "{text}");
|
||||
assert!(!text.contains("view_options"), "{text}");
|
||||
expected.diagrams.get_mut(&f.view).unwrap().layout = None;
|
||||
let cleared = update_bundle(&updated, &expected, ProjectLimits::default()).unwrap();
|
||||
assert_eq!(cleared.decoded.project, expected);
|
||||
let declaration = &cleared.index.declarations[&f.view];
|
||||
let text =
|
||||
&cleared.bundle.files[&declaration.path][declaration.span.start..declaration.span.end];
|
||||
assert!(!text.contains("layout"), "{text}");
|
||||
assert!(text.contains("// Controller spacing rationale."), "{text}");
|
||||
assert_eq!(
|
||||
update_bundle(&cleared, &expected, ProjectLimits::default())
|
||||
.unwrap()
|
||||
.bundle,
|
||||
cleared.bundle,
|
||||
);
|
||||
}
|
||||
@@ -23,6 +23,22 @@ pub enum Command {
|
||||
EditRelation(Id, Relation),
|
||||
CreateDiagram(Diagram),
|
||||
EditDiagram(Id, Diagram),
|
||||
SetScenarioLanePosition {
|
||||
diagram: Id,
|
||||
position: ScenarioLanePosition,
|
||||
},
|
||||
RemoveScenarioLanePosition {
|
||||
diagram: Id,
|
||||
lifeline: Id,
|
||||
},
|
||||
SetScenarioMessagePosition {
|
||||
diagram: Id,
|
||||
position: ScenarioMessagePosition,
|
||||
},
|
||||
RemoveScenarioMessagePosition {
|
||||
diagram: Id,
|
||||
address: OccurrenceEndpoint,
|
||||
},
|
||||
CreateArtifact(ArtifactLink),
|
||||
EditArtifact(Id, ArtifactLink),
|
||||
CreateTrace(Trace),
|
||||
@@ -488,6 +504,26 @@ fn apply_command(
|
||||
reidentify_tracked(p, *old, value.id, provenance)?;
|
||||
Some(value.id)
|
||||
}
|
||||
Command::SetScenarioLanePosition { diagram, position } => {
|
||||
let replacement = crate::scenario_layout::set_lane(p, *diagram, position.clone())?;
|
||||
p.diagrams.insert(*diagram, replacement);
|
||||
Some(*diagram)
|
||||
}
|
||||
Command::RemoveScenarioLanePosition { diagram, lifeline } => {
|
||||
let replacement = crate::scenario_layout::remove_lane(p, *diagram, *lifeline)?;
|
||||
p.diagrams.insert(*diagram, replacement);
|
||||
Some(*diagram)
|
||||
}
|
||||
Command::SetScenarioMessagePosition { diagram, position } => {
|
||||
let replacement = crate::scenario_layout::set_message(p, *diagram, position.clone())?;
|
||||
p.diagrams.insert(*diagram, replacement);
|
||||
Some(*diagram)
|
||||
}
|
||||
Command::RemoveScenarioMessagePosition { diagram, address } => {
|
||||
let replacement = crate::scenario_layout::remove_message(p, *diagram, address)?;
|
||||
p.diagrams.insert(*diagram, replacement);
|
||||
Some(*diagram)
|
||||
}
|
||||
Command::CreateArtifact(value) => {
|
||||
vacant(p, value.id)?;
|
||||
p.artifact_links.insert(value.id, value.clone());
|
||||
@@ -878,6 +914,7 @@ pub fn reidentify(p: &mut Project, old: Id, new: Id) -> Result<(), ModelError> {
|
||||
return Ok(());
|
||||
}
|
||||
vacant(p, new)?;
|
||||
crate::references::check_remap(p, old, new)?;
|
||||
if p.id == old {
|
||||
p.id = new;
|
||||
} else if let Some(mut v) = p.elements.remove(&old) {
|
||||
@@ -904,12 +941,17 @@ pub fn reidentify(p: &mut Project, old: Id, new: Id) -> Result<(), ModelError> {
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::references::remap_references(p, old, new);
|
||||
crate::references::remap_references(p, old, new)?;
|
||||
Ok(())
|
||||
}
|
||||
fn layout(p: &mut Project, diagram: Id) -> Result<(), ModelError> {
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
let d = p.diagrams.get(&diagram).ok_or_else(missing)?;
|
||||
if d.projection.scenario().is_some() {
|
||||
return Err(ModelError(
|
||||
"Scenario layout requires the Scenario geometry operation.".into(),
|
||||
));
|
||||
}
|
||||
let parents = crate::projection::parents(p, d);
|
||||
let mut children: BTreeMap<Option<Id>, Vec<Id>> = BTreeMap::new();
|
||||
for (id, parent) in &parents {
|
||||
|
||||
@@ -52,7 +52,13 @@ pub(crate) fn parser_fields(context: Context) -> Map<String, Value> {
|
||||
_ => &["source", "target"],
|
||||
}
|
||||
}
|
||||
Context::Diagram => &[],
|
||||
Context::Diagram => {
|
||||
// Admit the optional payload without restoring a synthetic null in
|
||||
// CompleteForEdit: absence there distinguishes a real layout clear
|
||||
// from an unrelated edit beside an authored explicit `layout none`.
|
||||
fields.insert("layout".into(), Value::Null);
|
||||
&[]
|
||||
}
|
||||
Context::Node => &["element"],
|
||||
Context::Artifact => &["owner"],
|
||||
Context::Trace => &["oa", "sa"],
|
||||
|
||||
@@ -972,7 +972,18 @@ pub fn update_bundle_with_identity_map(
|
||||
};
|
||||
let local = edits.entry(path.clone()).or_default();
|
||||
update.header(&actual.header, &previous.header, &next.header, local);
|
||||
update.value(&actual.fields, Some(&previous.fields), &next.fields, local);
|
||||
let context = if old.diagrams.contains_key(&id) {
|
||||
EditContext::Diagram
|
||||
} else {
|
||||
EditContext::Other
|
||||
};
|
||||
update.value(
|
||||
&actual.fields,
|
||||
Some(&previous.fields),
|
||||
&next.fields,
|
||||
context,
|
||||
local,
|
||||
);
|
||||
}
|
||||
}
|
||||
if old.id != project.id || old.alias != project.alias || old.name != project.name {
|
||||
@@ -1224,6 +1235,29 @@ impl<'a> InsertionSyntax<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// Schema context is explicit: similarly named fields in arbitrary records must
|
||||
// never acquire Scenario row identity or move their authored trivia.
|
||||
#[derive(Clone, Copy)]
|
||||
enum EditContext {
|
||||
Other,
|
||||
Diagram,
|
||||
Layout,
|
||||
Scenario,
|
||||
Lanes,
|
||||
Messages,
|
||||
}
|
||||
impl EditContext {
|
||||
fn field(self, name: &str) -> Self {
|
||||
match (self, name) {
|
||||
(Self::Diagram, "layout") => Self::Layout,
|
||||
(Self::Layout, "Scenario") => Self::Scenario,
|
||||
(Self::Scenario, "lanes") => Self::Lanes,
|
||||
(Self::Scenario, "messages") => Self::Messages,
|
||||
_ => Self::Other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SyntaxUpdate<'a> {
|
||||
source: &'a str,
|
||||
before: &'a str,
|
||||
@@ -1301,6 +1335,7 @@ impl SyntaxUpdate<'_> {
|
||||
actual: &language::EditValue,
|
||||
before: Option<&language::EditValue>,
|
||||
after: &language::EditValue,
|
||||
context: EditContext,
|
||||
edits: &mut LocalEdits,
|
||||
) {
|
||||
use language::EditKind;
|
||||
@@ -1316,7 +1351,7 @@ impl SyntaxUpdate<'_> {
|
||||
None
|
||||
}
|
||||
});
|
||||
self.record(actual.span, fields, previous, next, edits);
|
||||
self.record(actual.span, fields, previous, next, context, edits);
|
||||
}
|
||||
(EditKind::List(items), EditKind::List(next)) => {
|
||||
let previous = before.and_then(|old| {
|
||||
@@ -1326,7 +1361,7 @@ impl SyntaxUpdate<'_> {
|
||||
None
|
||||
}
|
||||
});
|
||||
self.list(actual.span, items, previous, next, edits);
|
||||
self.list(actual.span, items, previous, next, context, edits);
|
||||
}
|
||||
(EditKind::Reference(_), EditKind::Reference(alias)) => {
|
||||
let token = significant(&self.source[actual.span.start..actual.span.end])
|
||||
@@ -1379,6 +1414,7 @@ impl SyntaxUpdate<'_> {
|
||||
actual: &BTreeMap<String, language::EditField>,
|
||||
before: Option<&BTreeMap<String, language::EditField>>,
|
||||
after: &BTreeMap<String, language::EditField>,
|
||||
context: EditContext,
|
||||
edits: &mut LocalEdits,
|
||||
) {
|
||||
// A typed constructor tag change retains shared fields and their trivia.
|
||||
@@ -1402,7 +1438,13 @@ impl SyntaxUpdate<'_> {
|
||||
},
|
||||
new_key.clone(),
|
||||
));
|
||||
self.value(&field.value, Some(&old.value), &new.value, edits);
|
||||
self.value(
|
||||
&field.value,
|
||||
Some(&old.value),
|
||||
&new.value,
|
||||
context.field(new_key),
|
||||
edits,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1414,9 +1456,16 @@ impl SyntaxUpdate<'_> {
|
||||
.and_then(|fields| fields.get(key))
|
||||
.map(|field| &field.value),
|
||||
&next.value,
|
||||
context.field(key),
|
||||
edits,
|
||||
);
|
||||
} else {
|
||||
} else if !(matches!(context, EditContext::Diagram)
|
||||
&& key == "layout"
|
||||
&& before.is_some_and(|fields| !fields.contains_key(key)))
|
||||
{
|
||||
// Canonical None omits layout. Preserve an authored explicit
|
||||
// none while another field changes; a real Some->None clear
|
||||
// still removes the former payload and retains its trivia.
|
||||
erase_syntax(self.source, field.span, edits);
|
||||
}
|
||||
}
|
||||
@@ -1470,6 +1519,7 @@ impl SyntaxUpdate<'_> {
|
||||
actual: &[language::EditValue],
|
||||
before: Option<&[language::EditValue]>,
|
||||
after: &[language::EditValue],
|
||||
context: EditContext,
|
||||
edits: &mut LocalEdits,
|
||||
) {
|
||||
let previous = before.unwrap_or(&[]);
|
||||
@@ -1482,6 +1532,7 @@ impl SyntaxUpdate<'_> {
|
||||
self.old_aliases,
|
||||
self.legacy_value_paths,
|
||||
None,
|
||||
context,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -1494,6 +1545,7 @@ impl SyntaxUpdate<'_> {
|
||||
self.new_aliases,
|
||||
self.legacy_value_paths,
|
||||
self.identity_origins,
|
||||
context,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -1522,7 +1574,7 @@ impl SyntaxUpdate<'_> {
|
||||
.all(|(i, source)| *source == Some(i))
|
||||
{
|
||||
for (i, (current, next)) in actual.iter().zip(after).enumerate() {
|
||||
self.value(current, previous.get(i), next, edits);
|
||||
self.value(current, previous.get(i), next, EditContext::Other, edits);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1555,7 +1607,13 @@ impl SyntaxUpdate<'_> {
|
||||
let chunk = chunks[index];
|
||||
text.push_str(&self.source[chunk.start..current.span.start]);
|
||||
let mut local = Vec::new();
|
||||
self.value(current, previous.get(index), next, &mut local);
|
||||
self.value(
|
||||
current,
|
||||
previous.get(index),
|
||||
next,
|
||||
EditContext::Other,
|
||||
&mut local,
|
||||
);
|
||||
text.push_str(&changed_text(self.source, current.span, local));
|
||||
suffix = &self.source[current.span.end..chunk.end];
|
||||
} else {
|
||||
@@ -1594,14 +1652,58 @@ impl SyntaxUpdate<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn scenario_item_key(
|
||||
value: &language::EditValue,
|
||||
aliases: &BTreeMap<String, String>,
|
||||
context: EditContext,
|
||||
) -> Option<String> {
|
||||
use language::EditKind;
|
||||
let EditKind::Record(fields) = &value.kind else {
|
||||
return None;
|
||||
};
|
||||
let reference = |value: &language::EditValue| {
|
||||
if let EditKind::Reference(alias) = &value.kind {
|
||||
aliases.get(alias).cloned()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
match context {
|
||||
EditContext::Lanes => {
|
||||
reference(&fields.get("lifeline")?.value).map(|id| format!("scenario-lane:{id}"))
|
||||
}
|
||||
EditContext::Messages => {
|
||||
let EditKind::Record(address) = &fields.get("address")?.value.kind else {
|
||||
return None;
|
||||
};
|
||||
let occurrence = reference(&address.get("occurrence")?.value)?;
|
||||
let path: Vec<_> = match address.get("references") {
|
||||
None => Vec::new(),
|
||||
Some(field) => {
|
||||
let EditKind::List(path) = &field.value.kind else {
|
||||
return None;
|
||||
};
|
||||
path.iter().map(reference).collect::<Option<Vec<_>>>()?
|
||||
}
|
||||
};
|
||||
Some(format!("scenario-message:{}:{occurrence}", path.join("/")))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn item_key(
|
||||
value: &language::EditValue,
|
||||
source: &str,
|
||||
aliases: &BTreeMap<String, String>,
|
||||
legacy_value_paths: bool,
|
||||
origins: Option<&BTreeMap<Id, Id>>,
|
||||
context: EditContext,
|
||||
) -> Option<String> {
|
||||
use language::EditKind;
|
||||
if matches!(context, EditContext::Lanes | EditContext::Messages) {
|
||||
return scenario_item_key(value, aliases, context);
|
||||
}
|
||||
if matches!(value.kind, EditKind::Record(_))
|
||||
&& let Some(key) = language::semantic_row_key(
|
||||
&source[value.span.start..value.span.end],
|
||||
|
||||
@@ -72,6 +72,11 @@ pub(super) fn upgrade(
|
||||
&actual.fields,
|
||||
Some(&actual.fields),
|
||||
&next.fields,
|
||||
if project.diagrams.contains_key(&id) {
|
||||
EditContext::Diagram
|
||||
} else {
|
||||
EditContext::Other
|
||||
},
|
||||
edits.entry(path.clone()).or_default(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -750,7 +750,7 @@ pub fn plan_transition(
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if !compatible_existing(project, *source, target, request.direction) {
|
||||
if !counterpart_compatible(project, *source, target, request.direction) {
|
||||
conflict(
|
||||
&mut plan,
|
||||
Some(*source),
|
||||
@@ -1317,12 +1317,22 @@ fn compatible_kinds(source: Kind, target: Kind, direction: TransitionDirection)
|
||||
}
|
||||
inferred_kind(source, direction) == Some(target)
|
||||
}
|
||||
fn compatible_existing(
|
||||
/// Whether existing records have compatible layers, categories and kinds for
|
||||
/// an ordinary transition. This is candidate eligibility, not approval of a
|
||||
/// complete plan: properties, dependencies and structural conflicts still need
|
||||
/// the normal preview and apply validation. Manual traces are not restricted
|
||||
/// by this predicate.
|
||||
pub fn counterpart_compatible(
|
||||
p: &Project,
|
||||
source: Id,
|
||||
target: Id,
|
||||
direction: TransitionDirection,
|
||||
) -> bool {
|
||||
if p.layer_of(source) != Some(direction.source_layer())
|
||||
|| p.layer_of(target) != Some(direction.target_layer())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match (p.elements.get(&source), p.elements.get(&target)) {
|
||||
(Some(a), Some(b)) => compatible_kinds(a.kind(), b.kind(), direction),
|
||||
_ => match (p.relations.get(&source), p.relations.get(&target)) {
|
||||
|
||||
@@ -619,6 +619,7 @@ pub fn validate(p: &Project) -> Vec<Issue> {
|
||||
}
|
||||
text(&mut out, d.id, "name", &d.name);
|
||||
text(&mut out, d.id, "description", &d.description);
|
||||
crate::scenario_layout::validate_diagram(p, d, &mut out);
|
||||
let option_issues = if d.projection == ProjectionKind::Traceability {
|
||||
crate::view_options::validate_options_cross_layer(p, &d.view_options)
|
||||
} else {
|
||||
|
||||
@@ -231,6 +231,7 @@ fn node_project() -> Project {
|
||||
},
|
||||
)]),
|
||||
routes: vec![],
|
||||
layout: None,
|
||||
},
|
||||
);
|
||||
expected
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
use oa_core::{diagram_edit::translate_placements, source_project::*, *};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn point(x: f32, y: f32) -> Position {
|
||||
Position { x, y }
|
||||
}
|
||||
fn route(edge: Id, x: f32, y: f32) -> EdgeRoute {
|
||||
EdgeRoute {
|
||||
edge,
|
||||
source_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Bottom,
|
||||
offset: 0.2,
|
||||
}),
|
||||
target_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Top,
|
||||
offset: 0.8,
|
||||
}),
|
||||
waypoints: vec![point(x, y)],
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.4,
|
||||
offset: point(3., -9.),
|
||||
}),
|
||||
}
|
||||
}
|
||||
struct Fixture {
|
||||
project: Project,
|
||||
diagram: Id,
|
||||
a: Id,
|
||||
b: Id,
|
||||
child: Id,
|
||||
foreign: Id,
|
||||
}
|
||||
fn fixture() -> Fixture {
|
||||
let mut p = Project::empty();
|
||||
let a = p.add_element(Kind::Activity, Layer::Oa, "A", None).unwrap();
|
||||
let b = p.add_element(Kind::Activity, Layer::Oa, "B", None).unwrap();
|
||||
let c = p.add_element(Kind::Activity, Layer::Oa, "C", None).unwrap();
|
||||
let child = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "Child", Some(a))
|
||||
.unwrap();
|
||||
let internal = p.relate(RelationKind::Interaction, "Internal", a, b);
|
||||
let external = p.relate(RelationKind::Interaction, "External", b, c);
|
||||
let d = p.ensure_diagram(Layer::Oa);
|
||||
let na = p.place(d, a, point(10., 20.));
|
||||
let nb = p.place(d, b, point(400., 20.));
|
||||
let nc = p.place(d, child, point(30., 80.));
|
||||
p.place(d, c, point(800., 20.));
|
||||
p.diagrams.get_mut(&d).unwrap().routes =
|
||||
vec![route(internal, 320., 150.), route(external, 720., 170.)];
|
||||
p.diagrams
|
||||
.get_mut(&d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&na)
|
||||
.unwrap()
|
||||
.collapsed = true;
|
||||
let other = Id::new_v4();
|
||||
let mut other_view = p.diagrams[&d].clone();
|
||||
other_view.id = other;
|
||||
other_view.alias = "other_view".into();
|
||||
other_view.nodes.clear();
|
||||
other_view.routes.clear();
|
||||
p.diagrams.insert(other, other_view);
|
||||
let foreign = p.place(other, a, point(-40., -50.));
|
||||
validate_candidate(&p).unwrap();
|
||||
Fixture {
|
||||
project: p,
|
||||
diagram: d,
|
||||
a: na,
|
||||
b: nb,
|
||||
child: nc,
|
||||
foreign,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_siblings_translate_internal_pins_once_and_preserve_complete_project() {
|
||||
let f = fixture();
|
||||
let before = f.project.clone();
|
||||
let command = translate_placements(
|
||||
&before,
|
||||
f.diagram,
|
||||
&BTreeSet::from([f.a, f.b]),
|
||||
point(40., 60.),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
before, f.project,
|
||||
"command construction must not mutate input"
|
||||
);
|
||||
// Independently enumerated expected edits, without the projection helpers.
|
||||
let mut expected = before.clone();
|
||||
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
|
||||
view.nodes.get_mut(&f.a).unwrap().position = point(50., 80.);
|
||||
view.nodes.get_mut(&f.b).unwrap().position = point(440., 80.);
|
||||
view.nodes.get_mut(&f.child).unwrap().position = point(70., 140.);
|
||||
view.routes[0].waypoints = vec![point(360., 210.)];
|
||||
let mut session = Session::new(before.clone());
|
||||
session.execute(command.clone()).unwrap();
|
||||
assert_eq!(session.project(), &expected);
|
||||
session.undo();
|
||||
assert_eq!(session.project(), &before);
|
||||
assert!(
|
||||
!session.can_undo(),
|
||||
"one movement must be one history entry"
|
||||
);
|
||||
session.redo();
|
||||
assert_eq!(session.project(), &expected);
|
||||
assert!(!session.can_redo());
|
||||
|
||||
// Independent one-node moves cannot see the shared endpoint displacement.
|
||||
let mut sequential = Session::new(before.clone());
|
||||
for (node, position) in [(f.a, point(50., 80.)), (f.b, point(440., 80.))] {
|
||||
sequential
|
||||
.execute(Command::MoveNode {
|
||||
diagram: f.diagram,
|
||||
node,
|
||||
position,
|
||||
with_descendants: true,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
sequential.project().diagrams[&f.diagram].routes[0],
|
||||
before.diagrams[&f.diagram].routes[0]
|
||||
);
|
||||
assert_ne!(sequential.project(), &expected);
|
||||
|
||||
let json = serde_json::to_string(&expected).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Project>(&json).unwrap(), expected);
|
||||
let mut bundle = format_bundle(&before);
|
||||
bundle
|
||||
.files
|
||||
.get_mut(&bundle.entry.clone())
|
||||
.unwrap()
|
||||
.insert_str(0, "// preserve movement rationale\n");
|
||||
let original = compile_bundle(&bundle, ProjectLimits::default()).unwrap();
|
||||
let prepared = prepare_command(&before, &command).unwrap();
|
||||
let updated = update_bundle_with_identity_map(
|
||||
&original,
|
||||
&prepared.project,
|
||||
&prepared.identity_map,
|
||||
ProjectLimits::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(updated.decoded.project, expected);
|
||||
assert!(updated.bundle.files[&bundle.entry].starts_with("// preserve movement rationale\n"));
|
||||
let reread = compile_bundle(&updated.bundle, ProjectLimits::default()).unwrap();
|
||||
assert_eq!(reread.decoded.project, expected);
|
||||
assert_eq!(reread.bundle, updated.bundle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_folded_ancestor_and_hidden_descendant_moves_each_once() {
|
||||
let f = fixture();
|
||||
assert!(
|
||||
!projection::project_view(&f.project, f.diagram)
|
||||
.nodes
|
||||
.iter()
|
||||
.any(|n| n.id == f.child)
|
||||
);
|
||||
let ancestor = translate_placements(
|
||||
&f.project,
|
||||
f.diagram,
|
||||
&BTreeSet::from([f.a]),
|
||||
point(-15., 25.),
|
||||
)
|
||||
.unwrap();
|
||||
let overlap = translate_placements(
|
||||
&f.project,
|
||||
f.diagram,
|
||||
&BTreeSet::from([f.a, f.child]),
|
||||
point(-15., 25.),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(overlap, ancestor);
|
||||
let after = prepare_command(&f.project, &overlap).unwrap().project;
|
||||
assert_eq!(
|
||||
after.diagrams[&f.diagram].nodes[&f.child].position,
|
||||
point(15., 105.)
|
||||
);
|
||||
assert_eq!(
|
||||
after.diagrams[&f.diagram].routes,
|
||||
f.project.diagrams[&f.diagram].routes
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_movements_refuse_atomically_and_zero_has_no_history() {
|
||||
let f = fixture();
|
||||
let selected = BTreeSet::from([f.a, f.b]);
|
||||
for (diagram, ids, delta) in [
|
||||
(Id::new_v4(), selected.clone(), point(1., 1.)),
|
||||
(f.diagram, BTreeSet::new(), point(1., 1.)),
|
||||
(
|
||||
f.diagram,
|
||||
BTreeSet::from([f.a, Id::new_v4()]),
|
||||
point(1., 1.),
|
||||
),
|
||||
(f.diagram, BTreeSet::from([f.a, f.foreign]), point(0., 0.)),
|
||||
(f.diagram, selected.clone(), point(f32::NAN, 1.)),
|
||||
(f.diagram, selected.clone(), point(1., f32::INFINITY)),
|
||||
(f.diagram, selected.clone(), point(MAX_COORDINATE, 0.)),
|
||||
(f.diagram, selected.clone(), point(f32::MAX, f32::MAX)),
|
||||
] {
|
||||
let before = f.project.clone();
|
||||
assert!(translate_placements(&f.project, diagram, &ids, delta).is_err());
|
||||
assert_eq!(f.project, before);
|
||||
}
|
||||
let mut bad_route = f.project.clone();
|
||||
bad_route.diagrams.get_mut(&f.diagram).unwrap().routes[0].waypoints =
|
||||
vec![point(MAX_COORDINATE, 0.)];
|
||||
validate_candidate(&bad_route).unwrap();
|
||||
let snapshot = bad_route.clone();
|
||||
assert!(translate_placements(&bad_route, f.diagram, &selected, point(1., 0.)).is_err());
|
||||
assert_eq!(bad_route, snapshot);
|
||||
let zero = translate_placements(&f.project, f.diagram, &selected, point(0., -0.)).unwrap();
|
||||
assert_eq!(zero, Command::Batch(vec![]));
|
||||
let mut session = Session::new(f.project.clone());
|
||||
session.execute(zero).unwrap();
|
||||
assert_eq!(session.project(), &f.project);
|
||||
assert!(!session.can_undo());
|
||||
assert_eq!(session.revision(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_component_port_endpoints_follow_their_owner_placements() {
|
||||
let mut p = Project::empty();
|
||||
let a = p
|
||||
.add_element(Kind::System, Layer::Sa, "System", None)
|
||||
.unwrap();
|
||||
let b = p
|
||||
.add_element(Kind::SystemActor, Layer::Sa, "Actor", None)
|
||||
.unwrap();
|
||||
let output = Id::new_v4();
|
||||
let input = Id::new_v4();
|
||||
for (id, owner, name, orientation) in [
|
||||
(output, a, "Output", ComponentPortOrientation::Out),
|
||||
(input, b, "Input", ComponentPortOrientation::In),
|
||||
] {
|
||||
let port = make_port(
|
||||
&p,
|
||||
id,
|
||||
owner,
|
||||
name,
|
||||
PortContract::Component {
|
||||
kind: ComponentPortKind::Flow,
|
||||
orientation,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
p.elements.insert(id, port);
|
||||
}
|
||||
let edge = p.relate(RelationKind::BoundaryExchange, "Boundary", output, input);
|
||||
let d = p.ensure_diagram(Layer::Sa);
|
||||
let na = p.place(d, a, point(0., 0.));
|
||||
let nb = p.place(d, b, point(400., 0.));
|
||||
for (node, port, side, offset) in [
|
||||
(na, output, PortAnchorSide::Bottom, 0.3),
|
||||
(nb, input, PortAnchorSide::Top, 0.7),
|
||||
] {
|
||||
p.diagrams
|
||||
.get_mut(&d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&node)
|
||||
.unwrap()
|
||||
.port_anchors
|
||||
.push(PortAnchor { port, side, offset });
|
||||
}
|
||||
p.diagrams
|
||||
.get_mut(&d)
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(route(edge, 300., 100.));
|
||||
validate_candidate(&p).unwrap();
|
||||
let command = translate_placements(&p, d, &BTreeSet::from([na, nb]), point(10., -20.)).unwrap();
|
||||
let after = prepare_command(&p, &command).unwrap().project;
|
||||
let mut expected = p.clone();
|
||||
let view = expected.diagrams.get_mut(&d).unwrap();
|
||||
view.nodes.get_mut(&na).unwrap().position = point(10., -20.);
|
||||
view.nodes.get_mut(&nb).unwrap().position = point(410., -20.);
|
||||
view.routes[0].waypoints = vec![point(310., 80.)];
|
||||
assert_eq!(after, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allocation_movement_follows_visual_performers_and_same_performer_work_groups() {
|
||||
let mut p = Project::empty();
|
||||
let performer_a = p
|
||||
.add_element(Kind::Entity, Layer::Oa, "Performer A", None)
|
||||
.unwrap();
|
||||
let performer_b = p
|
||||
.add_element(Kind::Entity, Layer::Oa, "Performer B", None)
|
||||
.unwrap();
|
||||
let mixed = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "Mixed work", None)
|
||||
.unwrap();
|
||||
let branch = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "A work", Some(mixed))
|
||||
.unwrap();
|
||||
let leaf_a = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "A leaf", Some(branch))
|
||||
.unwrap();
|
||||
let leaf_b = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "B leaf", Some(mixed))
|
||||
.unwrap();
|
||||
p.relate(RelationKind::Allocation, "A performs", performer_a, leaf_a);
|
||||
p.relate(RelationKind::Allocation, "B performs", performer_b, leaf_b);
|
||||
let d = p.ensure_diagram(Layer::Oa);
|
||||
p.diagrams.get_mut(&d).unwrap().projection = ProjectionKind::Allocation;
|
||||
let na = p.place(d, performer_a, point(0., 0.));
|
||||
p.place(d, performer_b, point(600., 0.));
|
||||
let nm = p.place(d, mixed, point(1000., 0.));
|
||||
let branch_node = p.place(d, branch, point(20., 80.));
|
||||
let leaf_node = p.place(d, leaf_a, point(40., 160.));
|
||||
p.place(d, leaf_b, point(620., 80.));
|
||||
validate_candidate(&p).unwrap();
|
||||
|
||||
// Mixed work retains semantic ownership of both branches, but its leaves
|
||||
// have different performers. A work is visually nested under Performer A,
|
||||
// with its own same-performer leaf nested inside it.
|
||||
let command =
|
||||
translate_placements(&p, d, &BTreeSet::from([na, branch_node]), point(15., -25.)).unwrap();
|
||||
let after = prepare_command(&p, &command).unwrap().project;
|
||||
let mut expected = p.clone();
|
||||
let view = expected.diagrams.get_mut(&d).unwrap();
|
||||
view.nodes.get_mut(&na).unwrap().position = point(15., -25.);
|
||||
view.nodes.get_mut(&branch_node).unwrap().position = point(35., 55.);
|
||||
view.nodes.get_mut(&leaf_node).unwrap().position = point(55., 135.);
|
||||
assert_eq!(after, expected);
|
||||
|
||||
// Moving the semantic parent does not move children displayed elsewhere.
|
||||
let command = translate_placements(&p, d, &BTreeSet::from([nm]), point(15., -25.)).unwrap();
|
||||
let after = prepare_command(&p, &command).unwrap().project;
|
||||
let mut expected = p.clone();
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&nm)
|
||||
.unwrap()
|
||||
.position = point(1015., -25.);
|
||||
assert_eq!(after, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traceability_movement_is_flat_even_for_a_semantic_parent() {
|
||||
let mut f = fixture();
|
||||
f.project.diagrams.get_mut(&f.diagram).unwrap().projection = ProjectionKind::Traceability;
|
||||
validate_candidate(&f.project).unwrap();
|
||||
let command = translate_placements(
|
||||
&f.project,
|
||||
f.diagram,
|
||||
&BTreeSet::from([f.a]),
|
||||
point(40., 60.),
|
||||
)
|
||||
.unwrap();
|
||||
let after = prepare_command(&f.project, &command).unwrap().project;
|
||||
let mut expected = f.project.clone();
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&f.diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&f.a)
|
||||
.unwrap()
|
||||
.position = point(50., 80.);
|
||||
assert_eq!(
|
||||
after, expected,
|
||||
"flat view movement must preserve semantic descendants, routes, other views and all semantics"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_entry_pins_follow_the_boundary_only_when_it_also_moves() {
|
||||
let mut p = Project::empty();
|
||||
let machine = p
|
||||
.add_element(Kind::StateMachine, Layer::Oa, "Machine", None)
|
||||
.unwrap();
|
||||
let region = p
|
||||
.add_element(Kind::Region, Layer::Oa, "Region", Some(machine))
|
||||
.unwrap();
|
||||
let composite = p
|
||||
.add_element(Kind::State, Layer::Oa, "Composite", Some(region))
|
||||
.unwrap();
|
||||
let inner = p
|
||||
.add_element(Kind::Region, Layer::Oa, "Inner", Some(composite))
|
||||
.unwrap();
|
||||
let entry = p
|
||||
.add_element(Kind::EntryPoint, Layer::Oa, "Entry", Some(inner))
|
||||
.unwrap();
|
||||
let leaf = p
|
||||
.add_element(Kind::State, Layer::Oa, "Leaf", Some(inner))
|
||||
.unwrap();
|
||||
let edge = p.relate(RelationKind::StateTransition, "Enter", entry, leaf);
|
||||
if let RelationBody::StateTransition {
|
||||
transition_kind, ..
|
||||
} = &mut p.relations.get_mut(&edge).unwrap().body
|
||||
{
|
||||
*transition_kind = TransitionKind::Local;
|
||||
}
|
||||
let d = p.ensure_diagram(Layer::Oa);
|
||||
p.diagrams.get_mut(&d).unwrap().projection = ProjectionKind::StateMachine { machine };
|
||||
let boundary = p.place(d, composite, point(0., 0.));
|
||||
let ne = p.place(d, entry, point(20., 80.));
|
||||
let nl = p.place(d, leaf, point(100., 80.));
|
||||
p.diagrams
|
||||
.get_mut(&d)
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(route(edge, 90., 100.));
|
||||
validate_candidate(&p).unwrap();
|
||||
let endpoints =
|
||||
translate_placements(&p, d, &BTreeSet::from([ne, nl]), point(10., 20.)).unwrap();
|
||||
let after = prepare_command(&p, &endpoints).unwrap().project;
|
||||
assert_eq!(after.diagrams[&d].routes, p.diagrams[&d].routes);
|
||||
let with_boundary =
|
||||
translate_placements(&p, d, &BTreeSet::from([boundary, ne, nl]), point(10., 20.)).unwrap();
|
||||
let after = prepare_command(&p, &with_boundary).unwrap().project;
|
||||
assert_eq!(
|
||||
after.diagrams[&d].routes[0].waypoints,
|
||||
vec![point(100., 120.)]
|
||||
);
|
||||
assert_eq!(after.diagrams[&d].nodes[&ne].position, point(30., 100.));
|
||||
}
|
||||
@@ -41,6 +41,7 @@ fn fixture() -> Fixture {
|
||||
projection: ProjectionKind::Overview,
|
||||
view_options: Default::default(),
|
||||
nodes: BTreeMap::new(),
|
||||
layout: None,
|
||||
routes: vec![],
|
||||
},
|
||||
);
|
||||
|
||||
@@ -261,7 +261,7 @@ fn source7_context_lifecycle_source_history_and_closed_admission() {
|
||||
assert_eq!(session.project(), &after);
|
||||
let fresh = Id::new_v4();
|
||||
let mut reidentified = after.clone();
|
||||
references::remap_references(&mut reidentified, f.r1, fresh);
|
||||
references::remap_references(&mut reidentified, f.r1, fresh).unwrap();
|
||||
let mut e = reidentified.elements.remove(&f.r1).unwrap();
|
||||
e.id = fresh;
|
||||
reidentified.elements.insert(fresh, e);
|
||||
|
||||
@@ -20,6 +20,7 @@ fn view(p: &mut Project, machine: Id, alias: &str) -> Id {
|
||||
projection: ProjectionKind::StateMachine { machine },
|
||||
view_options: Default::default(),
|
||||
nodes: BTreeMap::new(),
|
||||
layout: None,
|
||||
routes: vec![],
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//! Existing counterpart eligibility is a layer/category/kind decision, not
|
||||
//! validation or acceptance of an entire transition plan. The catalog fixtures
|
||||
//! below intentionally contain partial records (unowned states, etc.). The
|
||||
//! final regression separately starts from a structurally valid real project.
|
||||
use oa_core::{transitions::*, *};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
fn element(p: &mut Project, layer: Layer, kind: Kind) -> Id {
|
||||
let id = Id::new_v4();
|
||||
let body = if kind == Kind::Port {
|
||||
// Legacy ports can exist in preserved OA models. This does not offer
|
||||
// new typed SA implementation ports for creation in portless OA.
|
||||
ElementBody::shared_in(
|
||||
layer,
|
||||
SharedBody::Port {
|
||||
contract: PortContract::Legacy,
|
||||
legacy: None,
|
||||
},
|
||||
)
|
||||
} else {
|
||||
ElementBody::new(kind, layer).unwrap()
|
||||
};
|
||||
p.elements.insert(
|
||||
id,
|
||||
Element {
|
||||
id,
|
||||
alias: format!("candidate_{}", id.simple()),
|
||||
name: "Identical candidate label".into(),
|
||||
description: String::new(),
|
||||
parent: None,
|
||||
body,
|
||||
},
|
||||
);
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_element_candidates_obey_explicit_engineering_families_in_both_directions() {
|
||||
// Contract: language.rst §5 trace families and the explicit capability /
|
||||
// mission alternative. State constructors remain eligible for explicit
|
||||
// review across the state family; selecting a candidate does not accept a
|
||||
// constructor change or make invalid ownership legal.
|
||||
let mut allowed: BTreeSet<(Kind, Kind)> = [
|
||||
(Kind::Activity, Kind::Function),
|
||||
(Kind::Entity, Kind::System),
|
||||
(Kind::Entity, Kind::SystemActor),
|
||||
(Kind::Actor, Kind::System),
|
||||
(Kind::Actor, Kind::SystemActor),
|
||||
(Kind::Capability, Kind::SystemCapability),
|
||||
(Kind::OperationalMission, Kind::Mission),
|
||||
(Kind::Capability, Kind::Mission),
|
||||
(Kind::Process, Kind::FunctionalChain),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
for kind in [
|
||||
Kind::ExchangeItem,
|
||||
Kind::ExchangeCategory,
|
||||
Kind::DataType,
|
||||
Kind::DataField,
|
||||
Kind::Interface,
|
||||
Kind::Port,
|
||||
Kind::Scenario,
|
||||
Kind::Lifeline,
|
||||
Kind::Occurrence,
|
||||
Kind::StateMachine,
|
||||
Kind::Region,
|
||||
Kind::Event,
|
||||
Kind::Constraint,
|
||||
] {
|
||||
allowed.insert((kind, kind));
|
||||
}
|
||||
let vertices = [
|
||||
Kind::State,
|
||||
Kind::Mode,
|
||||
Kind::Initial,
|
||||
Kind::Final,
|
||||
Kind::Choice,
|
||||
Kind::Junction,
|
||||
Kind::Fork,
|
||||
Kind::Join,
|
||||
Kind::ShallowHistory,
|
||||
Kind::DeepHistory,
|
||||
Kind::EntryPoint,
|
||||
Kind::ExitPoint,
|
||||
Kind::Terminate,
|
||||
];
|
||||
for oa in vertices {
|
||||
for sa in vertices {
|
||||
allowed.insert((oa, sa));
|
||||
}
|
||||
}
|
||||
let mut p = Project::empty();
|
||||
let oa: BTreeMap<_, _> = Kind::ALL
|
||||
.into_iter()
|
||||
.filter(|kind| kind.supports(Layer::Oa))
|
||||
.map(|kind| (kind, element(&mut p, Layer::Oa, kind)))
|
||||
.collect();
|
||||
let sa: BTreeMap<_, _> = Kind::ALL
|
||||
.into_iter()
|
||||
.filter(|kind| kind.supports(Layer::Sa))
|
||||
.map(|kind| (kind, element(&mut p, Layer::Sa, kind)))
|
||||
.collect();
|
||||
let original = p.clone();
|
||||
for (&oa_kind, &oa_id) in &oa {
|
||||
for (&sa_kind, &sa_id) in &sa {
|
||||
let expected = allowed.contains(&(oa_kind, sa_kind));
|
||||
assert_eq!(
|
||||
counterpart_compatible(&p, oa_id, sa_id, TransitionDirection::OaToSa),
|
||||
expected,
|
||||
"OA {oa_kind:?} → SA {sa_kind:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
counterpart_compatible(&p, sa_id, oa_id, TransitionDirection::SaToOa),
|
||||
expected,
|
||||
"SA {sa_kind:?} → OA {oa_kind:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
p, original,
|
||||
"Eligibility must not establish correspondence or edit records"
|
||||
);
|
||||
}
|
||||
|
||||
fn relation(p: &mut Project, kind: RelationKind, anchor: Id) -> Id {
|
||||
let id = Id::new_v4();
|
||||
// Only the semantic layer and relation category participate in candidate
|
||||
// eligibility. Endpoint compatibility belongs to full plan validation.
|
||||
p.relations.insert(
|
||||
id,
|
||||
Relation {
|
||||
id,
|
||||
alias: format!("relation_{}", id.simple()),
|
||||
name: "Identical relation label".into(),
|
||||
description: String::new(),
|
||||
body: RelationBody::new(kind, anchor, anchor),
|
||||
},
|
||||
);
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_relation_candidates_distinguish_work_boundary_and_shared_relations() {
|
||||
// Work and boundary exchanges are different families. The boundary /
|
||||
// boundary pair permits preserved legacy OA boundary records; ordinary
|
||||
// portless OA communication means map to SA boundary exchanges.
|
||||
let mut allowed = vec![
|
||||
(RelationKind::Interaction, RelationKind::FunctionalExchange),
|
||||
(
|
||||
RelationKind::CommunicationMean,
|
||||
RelationKind::BoundaryExchange,
|
||||
),
|
||||
(
|
||||
RelationKind::BoundaryExchange,
|
||||
RelationKind::BoundaryExchange,
|
||||
),
|
||||
];
|
||||
let shared = [
|
||||
RelationKind::Allocation,
|
||||
RelationKind::InterfaceItemAllocation,
|
||||
RelationKind::DataAssociation,
|
||||
RelationKind::ExchangeAllocation,
|
||||
RelationKind::CapabilityInvolvement,
|
||||
RelationKind::CapabilityInclude,
|
||||
RelationKind::CapabilityExtend,
|
||||
RelationKind::CapabilityGeneralization,
|
||||
RelationKind::MissionInvolvement,
|
||||
RelationKind::MissionCapability,
|
||||
RelationKind::SequenceLink,
|
||||
RelationKind::ContextualLink,
|
||||
RelationKind::ChainInvolvement,
|
||||
RelationKind::InterfaceProvision,
|
||||
RelationKind::InterfaceRequirement,
|
||||
RelationKind::StateTransition,
|
||||
RelationKind::Availability,
|
||||
RelationKind::StateAction,
|
||||
];
|
||||
for kind in shared {
|
||||
allowed.push((kind, kind));
|
||||
}
|
||||
let mut p = Project::empty();
|
||||
let oa_anchor = element(&mut p, Layer::Oa, Kind::Activity);
|
||||
let sa_anchor = element(&mut p, Layer::Sa, Kind::Function);
|
||||
let oa: Vec<_> = shared
|
||||
.into_iter()
|
||||
.chain([
|
||||
RelationKind::Interaction,
|
||||
RelationKind::CommunicationMean,
|
||||
RelationKind::BoundaryExchange,
|
||||
RelationKind::RoleRealization,
|
||||
RelationKind::RoleAssignment,
|
||||
])
|
||||
.map(|kind| (kind, relation(&mut p, kind, oa_anchor)))
|
||||
.collect();
|
||||
let sa: Vec<_> = shared
|
||||
.into_iter()
|
||||
.chain([
|
||||
RelationKind::FunctionalExchange,
|
||||
RelationKind::BoundaryExchange,
|
||||
RelationKind::PortAllocation,
|
||||
])
|
||||
.map(|kind| (kind, relation(&mut p, kind, sa_anchor)))
|
||||
.collect();
|
||||
for &(oa_kind, oa_id) in &oa {
|
||||
for &(sa_kind, sa_id) in &sa {
|
||||
let expected = allowed.contains(&(oa_kind, sa_kind));
|
||||
assert_eq!(
|
||||
counterpart_compatible(&p, oa_id, sa_id, TransitionDirection::OaToSa),
|
||||
expected,
|
||||
"OA {oa_kind:?} → SA {sa_kind:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
counterpart_compatible(&p, sa_id, oa_id, TransitionDirection::SaToOa),
|
||||
expected,
|
||||
"SA {sa_kind:?} → OA {oa_kind:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidate_eligibility_rejects_wrong_layers_categories_and_missing_identities() {
|
||||
let mut p = Project::empty();
|
||||
let oa = element(&mut p, Layer::Oa, Kind::Activity);
|
||||
let sa = element(&mut p, Layer::Sa, Kind::Function);
|
||||
let oa_exchange = relation(&mut p, RelationKind::Interaction, oa);
|
||||
let sa_exchange = relation(&mut p, RelationKind::FunctionalExchange, sa);
|
||||
let diagram = p.ensure_diagram(Layer::Sa);
|
||||
let node = p.place(diagram, sa, Position { x: 1., y: 2. });
|
||||
for (direction, source, target, source_relation, target_relation) in [
|
||||
(
|
||||
TransitionDirection::OaToSa,
|
||||
oa,
|
||||
sa,
|
||||
oa_exchange,
|
||||
sa_exchange,
|
||||
),
|
||||
(
|
||||
TransitionDirection::SaToOa,
|
||||
sa,
|
||||
oa,
|
||||
sa_exchange,
|
||||
oa_exchange,
|
||||
),
|
||||
] {
|
||||
assert!(counterpart_compatible(&p, source, target, direction));
|
||||
assert!(counterpart_compatible(
|
||||
&p,
|
||||
source_relation,
|
||||
target_relation,
|
||||
direction
|
||||
));
|
||||
for (a, b) in [
|
||||
(target, source),
|
||||
(source, source),
|
||||
(target, target),
|
||||
(target_relation, source_relation),
|
||||
(source_relation, source_relation),
|
||||
(source, target_relation),
|
||||
(source_relation, target),
|
||||
] {
|
||||
assert!(!counterpart_compatible(&p, a, b, direction));
|
||||
}
|
||||
for absent_or_nonsemantic in [Id::nil(), Id::new_v4(), p.id, diagram, node] {
|
||||
assert!(!counterpart_compatible(
|
||||
&p,
|
||||
source,
|
||||
absent_or_nonsemantic,
|
||||
direction
|
||||
));
|
||||
assert!(!counterpart_compatible(
|
||||
&p,
|
||||
absent_or_nonsemantic,
|
||||
target,
|
||||
direction
|
||||
));
|
||||
}
|
||||
}
|
||||
p.elements.remove(&sa);
|
||||
assert!(!counterpart_compatible(
|
||||
&p,
|
||||
oa,
|
||||
sa,
|
||||
TransitionDirection::OaToSa
|
||||
));
|
||||
assert!(!counterpart_compatible(
|
||||
&p,
|
||||
sa,
|
||||
oa,
|
||||
TransitionDirection::SaToOa
|
||||
));
|
||||
// The retained relation header cannot borrow a layer from a deleted owner.
|
||||
assert!(!counterpart_compatible(
|
||||
&p,
|
||||
oa_exchange,
|
||||
sa_exchange,
|
||||
TransitionDirection::OaToSa
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activity_picker_rejects_real_sa_port_and_agrees_with_explicit_plan_refusal() {
|
||||
let p = Project::demo();
|
||||
let original = p.clone();
|
||||
assert!(validation::validate(&p).is_empty());
|
||||
let source = p
|
||||
.elements
|
||||
.values()
|
||||
.find(|e| e.kind() == Kind::Activity)
|
||||
.unwrap()
|
||||
.id;
|
||||
let port = p
|
||||
.elements
|
||||
.values()
|
||||
.find(|e| e.layer() == Layer::Sa && e.kind() == Kind::Port)
|
||||
.unwrap()
|
||||
.id;
|
||||
let function = p
|
||||
.elements
|
||||
.values()
|
||||
.find(|e| e.kind() == Kind::Function)
|
||||
.unwrap()
|
||||
.id;
|
||||
assert!(counterpart_compatible(
|
||||
&p,
|
||||
source,
|
||||
function,
|
||||
TransitionDirection::OaToSa
|
||||
));
|
||||
assert!(!counterpart_compatible(
|
||||
&p,
|
||||
source,
|
||||
port,
|
||||
TransitionDirection::OaToSa
|
||||
));
|
||||
let mut request = TransitionRequest::new(TransitionDirection::OaToSa, vec![source]);
|
||||
request.mappings.push(TransitionMapping {
|
||||
source,
|
||||
target: Some(port),
|
||||
target_kind: None,
|
||||
});
|
||||
let plan = plan_transition(&p, &request).unwrap();
|
||||
assert!(
|
||||
plan.conflicts
|
||||
.iter()
|
||||
.any(|conflict| conflict.source == Some(source)
|
||||
&& conflict.target == Some(port)
|
||||
&& conflict.field.is_none())
|
||||
);
|
||||
assert!(apply_transition(&p, &plan).is_err());
|
||||
assert_eq!(p, original);
|
||||
}
|
||||
@@ -0,0 +1,638 @@
|
||||
//! Endpoint lifecycle acceptance for the ordinary, prose-reviewed transition API.
|
||||
//! OA is portless; the SA half contains typed ports. Deletion expectations below
|
||||
//! are fixture-owned identity lists, never results of the deletion implementation.
|
||||
use oa_core::{
|
||||
language, persistence,
|
||||
source_project::{ProjectLimits, SourceBundle, compile_bundle},
|
||||
transitions::*,
|
||||
validation::{self, Severity},
|
||||
*,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
struct Side {
|
||||
root: Id,
|
||||
elements: Vec<Id>,
|
||||
exchange: Id,
|
||||
diagram: Id,
|
||||
nodes: Vec<Id>,
|
||||
artifacts: Vec<Id>,
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
project: Project,
|
||||
source: Side,
|
||||
target: Side,
|
||||
trace: Id,
|
||||
trace_artifact: Id,
|
||||
}
|
||||
|
||||
fn artifact(p: &mut Project, owner: Id, label: &str) -> Id {
|
||||
let id = Id::new_v4();
|
||||
p.artifact_links.insert(
|
||||
id,
|
||||
ArtifactLink {
|
||||
id,
|
||||
alias: p.fresh_alias(label, "evidence", id),
|
||||
name: label.into(),
|
||||
description: "Independently authored rationale".into(),
|
||||
owner,
|
||||
relation: ArtifactRelation::References,
|
||||
uri: "git:engineering/design.md".into(),
|
||||
revision: Some("review-17".into()),
|
||||
fragment: Some("retained-decision".into()),
|
||||
},
|
||||
);
|
||||
id
|
||||
}
|
||||
|
||||
fn side(p: &mut Project, layer: Layer) -> Side {
|
||||
let (kind, prefix, relation) = match layer {
|
||||
Layer::Oa => (Kind::Activity, "Operational", RelationKind::Interaction),
|
||||
Layer::Sa => (
|
||||
Kind::Function,
|
||||
"Technical",
|
||||
RelationKind::FunctionalExchange,
|
||||
),
|
||||
};
|
||||
let root = p
|
||||
.add_element(kind, layer, &format!("{prefix} design"), None)
|
||||
.unwrap();
|
||||
p.elements.get_mut(&root).unwrap().description =
|
||||
format!("{prefix} independently reviewed intent");
|
||||
let send = p
|
||||
.add_element(kind, layer, &format!("{prefix} send"), Some(root))
|
||||
.unwrap();
|
||||
let receive = p
|
||||
.add_element(kind, layer, &format!("{prefix} receive"), Some(root))
|
||||
.unwrap();
|
||||
p.elements.get_mut(&send).unwrap().description =
|
||||
"Preserve the detailed sending responsibility".into();
|
||||
p.elements.get_mut(&receive).unwrap().description =
|
||||
"Preserve the detailed receiving responsibility".into();
|
||||
// A shared, separately owned definition survives deletion of its users.
|
||||
let item = p
|
||||
.add_element(
|
||||
Kind::ExchangeItem,
|
||||
layer,
|
||||
&format!("{prefix} information"),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
*p.elements.get_mut(&item).unwrap().shared_mut().unwrap() = SharedBody::ExchangeItem {
|
||||
kind: ExchangeItemKind::Information,
|
||||
mechanism: ExchangeMechanism::Flow,
|
||||
supertype: None,
|
||||
};
|
||||
p.add_element(
|
||||
Kind::DataField,
|
||||
layer,
|
||||
&format!("{prefix} payload"),
|
||||
Some(item),
|
||||
)
|
||||
.unwrap();
|
||||
let exchange = p.relate(relation, &format!("{prefix} delivery"), send, receive);
|
||||
let mut elements = vec![root, send, receive];
|
||||
match &mut p.relations.get_mut(&exchange).unwrap().body {
|
||||
RelationBody::Interaction { items, .. } => *items = vec![item],
|
||||
RelationBody::FunctionalExchange {
|
||||
items,
|
||||
source_port,
|
||||
target_port,
|
||||
..
|
||||
} => {
|
||||
*items = vec![item];
|
||||
let (output, input) = (*source_port, *target_port);
|
||||
*p.elements.get_mut(&output).unwrap().shared_mut().unwrap() = SharedBody::Port {
|
||||
contract: PortContract::FunctionOutput {
|
||||
outgoing_items: vec![item],
|
||||
},
|
||||
legacy: None,
|
||||
};
|
||||
*p.elements.get_mut(&input).unwrap().shared_mut().unwrap() = SharedBody::Port {
|
||||
contract: PortContract::FunctionInput {
|
||||
incoming_items: vec![item],
|
||||
},
|
||||
legacy: None,
|
||||
};
|
||||
elements.extend([output, input]);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
p.relations.get_mut(&exchange).unwrap().description =
|
||||
"Retain direction, item contract and relation identity".into();
|
||||
let diagram = p.ensure_diagram(layer);
|
||||
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Decomposition;
|
||||
let nodes = [root, send, receive]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, element)| {
|
||||
p.place(
|
||||
diagram,
|
||||
element,
|
||||
Position {
|
||||
x: 43.25 + index as f32 * 271.,
|
||||
y: 97.5 + index as f32 * 83.,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let root_node = p
|
||||
.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&nodes[0])
|
||||
.unwrap();
|
||||
root_node.size = Size {
|
||||
width: 611.,
|
||||
height: 319.,
|
||||
};
|
||||
root_node.collapsed = true;
|
||||
p.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(EdgeRoute {
|
||||
edge: exchange,
|
||||
// Both directions must preserve authored endpoint preferences,
|
||||
// including dormant preferences on the SA semantic-port edge.
|
||||
source_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Bottom,
|
||||
offset: 0.2,
|
||||
}),
|
||||
target_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Top,
|
||||
offset: 0.8,
|
||||
}),
|
||||
waypoints: vec![Position {
|
||||
x: 337.5,
|
||||
y: 423.25,
|
||||
}],
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.7,
|
||||
offset: Position { x: 11., y: -17. },
|
||||
}),
|
||||
});
|
||||
let artifacts = [root, send, exchange, nodes[0]]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, owner)| artifact(p, owner, &format!("{prefix} evidence {index}")))
|
||||
.collect();
|
||||
artifact(p, item, &format!("{prefix} shared item evidence"));
|
||||
Side {
|
||||
root,
|
||||
elements,
|
||||
exchange,
|
||||
diagram,
|
||||
nodes,
|
||||
artifacts,
|
||||
}
|
||||
}
|
||||
|
||||
fn accepted(p: &Project) {
|
||||
let issues = validation::validate(p);
|
||||
// This fixture deliberately isolates decomposition and correspondence from
|
||||
// performer allocation and process/chain/scenario inclusion. Each surviving
|
||||
// leaf (including a newly transitioned root) must have exactly those two
|
||||
// incomplete-work warnings; each surviving local exchange lacks a behavior
|
||||
// context. Check exact record IDs and fields, including duplicate warnings.
|
||||
// The system of interest and item contracts are complete fixture facts.
|
||||
assert!(
|
||||
issues
|
||||
.iter()
|
||||
.all(|issue| issue.severity == Severity::Warning),
|
||||
"{issues:?}"
|
||||
);
|
||||
let mut expected = Vec::new();
|
||||
for element in p.elements.values().filter(|element| {
|
||||
matches!(element.kind(), Kind::Activity | Kind::Function)
|
||||
&& !p
|
||||
.elements
|
||||
.values()
|
||||
.any(|child| child.parent == Some(element.id) && child.kind() == element.kind())
|
||||
}) {
|
||||
expected.push(("unallocated_leaf", Some(element.id), Some("allocation")));
|
||||
expected.push(("work_without_behavior_context", Some(element.id), None));
|
||||
}
|
||||
for relation in p.relations.values().filter(|relation| {
|
||||
matches!(
|
||||
relation.kind(),
|
||||
RelationKind::Interaction | RelationKind::FunctionalExchange
|
||||
)
|
||||
}) {
|
||||
expected.push(("exchange_without_behavior_context", Some(relation.id), None));
|
||||
}
|
||||
let mut actual = issues
|
||||
.iter()
|
||||
.map(|issue| (issue.code.as_str(), issue.element, issue.field.as_deref()))
|
||||
.collect::<Vec<_>>();
|
||||
expected.sort();
|
||||
actual.sort();
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"Unexpected fixture diagnostics: {issues:?}"
|
||||
);
|
||||
}
|
||||
|
||||
fn round_trip(p: &Project) -> String {
|
||||
accepted(p);
|
||||
let json = serde_json::to_vec_pretty(p).unwrap();
|
||||
assert_eq!(persistence::decode(&json).unwrap(), *p);
|
||||
let source = language::format(p);
|
||||
let compiled = compile_bundle(
|
||||
&SourceBundle {
|
||||
entry: "project.arcadia".into(),
|
||||
files: BTreeMap::from([("project.arcadia".into(), source.clone())]),
|
||||
},
|
||||
ProjectLimits::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(compiled.decoded.project, *p);
|
||||
assert_eq!(language::format(&compiled.decoded.project), source);
|
||||
source
|
||||
}
|
||||
|
||||
fn explicit(direction: TransitionDirection, source: Id, target: Id) -> TransitionRequest {
|
||||
let mut request = TransitionRequest::new(direction, vec![source]);
|
||||
request.mappings.push(TransitionMapping {
|
||||
source,
|
||||
target: Some(target),
|
||||
target_kind: None,
|
||||
});
|
||||
request
|
||||
}
|
||||
|
||||
fn fixture(direction: TransitionDirection) -> Fixture {
|
||||
let mut project = Project::empty();
|
||||
project.name = "Endpoint lifecycle conservation".into();
|
||||
project
|
||||
.add_element(Kind::System, Layer::Sa, "System of interest", None)
|
||||
.unwrap();
|
||||
let oa = side(&mut project, Layer::Oa);
|
||||
let sa = side(&mut project, Layer::Sa);
|
||||
let (source, target) = match direction {
|
||||
TransitionDirection::OaToSa => (oa, sa),
|
||||
TransitionDirection::SaToOa => (sa, oa),
|
||||
};
|
||||
accepted(&project);
|
||||
let before = project.clone();
|
||||
let mut request = explicit(direction, source.root, target.root);
|
||||
for field in [TransitionField::Name, TransitionField::Description] {
|
||||
request.resolutions.push(FieldResolution {
|
||||
source: source.root,
|
||||
field,
|
||||
decision: FieldDecision::KeepTarget,
|
||||
});
|
||||
}
|
||||
let plan = plan_transition(&project, &request).unwrap();
|
||||
assert!(plan.conflicts.is_empty(), "{:?}", plan.conflicts);
|
||||
project = apply_transition(&project, &plan).unwrap();
|
||||
let trace = assert_only_new_trace(&before, &project, direction, source.root, target.root);
|
||||
let mut without_trace = project.clone();
|
||||
without_trace.traces.remove(&trace);
|
||||
assert_eq!(
|
||||
without_trace, before,
|
||||
"Initial review must only add correspondence"
|
||||
);
|
||||
let trace_artifact = artifact(&mut project, trace, "Correspondence rationale");
|
||||
round_trip(&project);
|
||||
Fixture {
|
||||
project,
|
||||
source,
|
||||
target,
|
||||
trace,
|
||||
trace_artifact,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_only_new_trace(
|
||||
before: &Project,
|
||||
after: &Project,
|
||||
direction: TransitionDirection,
|
||||
source: Id,
|
||||
target: Id,
|
||||
) -> Id {
|
||||
let added = after
|
||||
.traces
|
||||
.values()
|
||||
.filter(|trace| !before.traces.contains_key(&trace.id))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(added.len(), 1);
|
||||
assert_eq!(after.traces.len(), before.traces.len() + 1);
|
||||
let trace = added[0];
|
||||
let (oa, sa) = match direction {
|
||||
TransitionDirection::OaToSa => (source, target),
|
||||
TransitionDirection::SaToOa => (target, source),
|
||||
};
|
||||
assert_eq!(
|
||||
(trace.oa, trace.sa, trace.kind),
|
||||
(oa, sa, TraceKind::Refinement)
|
||||
);
|
||||
assert_eq!(
|
||||
trace.baseline,
|
||||
Some(TraceBaseline {
|
||||
oa: after.properties(oa).unwrap(),
|
||||
sa: after.properties(sa).unwrap(),
|
||||
semantic: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(trace_drift(after, trace), Drift::Unchanged);
|
||||
trace.id
|
||||
}
|
||||
|
||||
fn expected_deletion(fixture: &Fixture, side: &Side) -> Project {
|
||||
let mut expected = fixture.project.clone();
|
||||
for id in &side.elements {
|
||||
assert!(expected.elements.remove(id).is_some());
|
||||
}
|
||||
assert!(expected.relations.remove(&side.exchange).is_some());
|
||||
assert!(expected.traces.remove(&fixture.trace).is_some());
|
||||
for id in side.artifacts.iter().chain([&fixture.trace_artifact]) {
|
||||
assert!(expected.artifact_links.remove(id).is_some());
|
||||
}
|
||||
let diagram = expected.diagrams.get_mut(&side.diagram).unwrap();
|
||||
for id in &side.nodes {
|
||||
assert!(diagram.nodes.remove(id).is_some());
|
||||
}
|
||||
// This fixture authored exactly one route, for its removed local exchange.
|
||||
assert_eq!(diagram.routes.len(), 1);
|
||||
assert_eq!(diagram.routes[0].edge, side.exchange);
|
||||
diagram.routes.clear();
|
||||
expected
|
||||
}
|
||||
|
||||
fn unchanged_retry(p: &Project, direction: TransitionDirection, source: Id, target: Id) {
|
||||
let request = TransitionRequest::new(direction, vec![source]);
|
||||
let plan = plan_transition(p, &request).unwrap();
|
||||
assert!(plan.conflicts.is_empty(), "{:?}", plan.conflicts);
|
||||
assert_eq!(plan.changes.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
plan.changes[0].source,
|
||||
plan.changes[0].target,
|
||||
plan.changes[0].action
|
||||
),
|
||||
(source, target, TransitionAction::Reuse)
|
||||
);
|
||||
assert!(plan.changes[0].fields.is_empty());
|
||||
assert!(plan.commands.is_empty(), "{:?}", plan.commands);
|
||||
let mut session = Session::new(p.clone());
|
||||
let revision = session.revision();
|
||||
session
|
||||
.execute(Command::Replace(apply_transition(p, &plan).unwrap()))
|
||||
.unwrap();
|
||||
assert_eq!(session.project(), p);
|
||||
assert_eq!(session.revision(), revision);
|
||||
assert!(!session.can_undo());
|
||||
}
|
||||
|
||||
fn source_deletion(direction: TransitionDirection) {
|
||||
let fixture = fixture(direction);
|
||||
let original_source = round_trip(&fixture.project);
|
||||
let expected = expected_deletion(&fixture, &fixture.source);
|
||||
let mut session = Session::new(fixture.project.clone());
|
||||
session
|
||||
.execute(Command::Delete(fixture.source.root))
|
||||
.unwrap();
|
||||
// Whole-project equality covers every retained target child, typed SA port,
|
||||
// exchange, placement, route, artifact, shared item and unchanged identity.
|
||||
assert_eq!(session.project(), &expected);
|
||||
let deleted_source = round_trip(session.project());
|
||||
session.undo();
|
||||
assert_eq!(session.project(), &fixture.project);
|
||||
assert_eq!(round_trip(session.project()), original_source);
|
||||
assert!(!session.can_undo(), "Deletion is one history transaction");
|
||||
session.redo();
|
||||
assert_eq!(session.project(), &expected);
|
||||
assert_eq!(round_trip(session.project()), deleted_source);
|
||||
}
|
||||
|
||||
fn implicit_creation(
|
||||
p: &Project,
|
||||
direction: TransitionDirection,
|
||||
source: Id,
|
||||
forbidden_target: Id,
|
||||
) -> (Project, Id) {
|
||||
let request = TransitionRequest::new(direction, vec![source]);
|
||||
let plan = plan_transition(p, &request).unwrap();
|
||||
assert!(plan.conflicts.is_empty(), "{:?}", plan.conflicts);
|
||||
assert_eq!(plan.changes.len(), 1);
|
||||
let change = &plan.changes[0];
|
||||
assert_eq!(change.source, source);
|
||||
assert_eq!(change.action, TransitionAction::Create);
|
||||
let target = change.target;
|
||||
assert_ne!(target, forbidden_target);
|
||||
assert!(!p.contains(target));
|
||||
let after = apply_transition(p, &plan).unwrap();
|
||||
let trace = assert_only_new_trace(p, &after, direction, source, target);
|
||||
let created = &after.elements[&target];
|
||||
assert_eq!(created.id, target, "Apply preserves the preview identity");
|
||||
assert_eq!(created.name, p.elements[&source].name);
|
||||
assert_eq!(created.description, p.elements[&source].description);
|
||||
assert_eq!(created.parent, None);
|
||||
assert_eq!(
|
||||
created.body,
|
||||
match direction {
|
||||
TransitionDirection::OaToSa => ElementBody::Sa(SaBody::Function),
|
||||
TransitionDirection::SaToOa => ElementBody::Oa(OaBody::Activity),
|
||||
}
|
||||
);
|
||||
assert!(!created.alias.is_empty());
|
||||
assert!(
|
||||
!p.identities()
|
||||
.iter()
|
||||
.any(|(_, alias)| *alias == created.alias)
|
||||
);
|
||||
// Remove only the independently expected two additions. Any incidental
|
||||
// mutation, clone of target children or extra correspondence fails here.
|
||||
let mut retained = after.clone();
|
||||
retained.elements.remove(&target);
|
||||
retained.traces.remove(&trace);
|
||||
assert_eq!(retained, *p);
|
||||
round_trip(&after);
|
||||
// Replaying a creation plan after acceptance violates its snapshot, while
|
||||
// a fresh unchanged request reuses the accepted counterpart.
|
||||
assert!(
|
||||
apply_transition(&after, &plan)
|
||||
.unwrap_err()
|
||||
.0
|
||||
.contains("stale")
|
||||
);
|
||||
unchanged_retry(&after, direction, source, target);
|
||||
(after, target)
|
||||
}
|
||||
|
||||
fn target_deletion(direction: TransitionDirection) {
|
||||
let fixture = fixture(direction);
|
||||
let request = TransitionRequest::new(direction, vec![fixture.source.root]);
|
||||
let old_plan = plan_transition(&fixture.project, &request).unwrap();
|
||||
assert!(old_plan.conflicts.is_empty());
|
||||
let expected = expected_deletion(&fixture, &fixture.target);
|
||||
let mut session = Session::new(fixture.project.clone());
|
||||
session
|
||||
.execute(Command::Delete(fixture.target.root))
|
||||
.unwrap();
|
||||
assert_eq!(session.project(), &expected);
|
||||
round_trip(session.project());
|
||||
let revision = session.revision();
|
||||
assert!(
|
||||
apply_transition(session.project(), &old_plan)
|
||||
.unwrap_err()
|
||||
.0
|
||||
.contains("stale")
|
||||
);
|
||||
let explicit_plan = plan_transition(
|
||||
session.project(),
|
||||
&explicit(direction, fixture.source.root, fixture.target.root),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
explicit_plan
|
||||
.conflicts
|
||||
.iter()
|
||||
.any(|conflict| conflict.source == Some(fixture.source.root)
|
||||
&& conflict.target == Some(fixture.target.root)
|
||||
&& conflict.field.is_none())
|
||||
);
|
||||
assert!(apply_transition(session.project(), &explicit_plan).is_err());
|
||||
assert_eq!(session.project(), &expected);
|
||||
assert_eq!(session.revision(), revision);
|
||||
let (created, _) = implicit_creation(
|
||||
session.project(),
|
||||
direction,
|
||||
fixture.source.root,
|
||||
fixture.target.root,
|
||||
);
|
||||
session.execute(Command::Replace(created.clone())).unwrap();
|
||||
session.undo();
|
||||
assert_eq!(session.project(), &expected);
|
||||
session.undo();
|
||||
assert_eq!(session.project(), &fixture.project);
|
||||
assert!(!session.can_undo());
|
||||
session.redo();
|
||||
session.redo();
|
||||
assert_eq!(session.project(), &created);
|
||||
round_trip(session.project());
|
||||
}
|
||||
|
||||
fn source_recreation(direction: TransitionDirection) {
|
||||
let fixture = fixture(direction);
|
||||
let mut replacement = fixture.project.elements[&fixture.source.root].clone();
|
||||
replacement.id = Id::new_v4();
|
||||
let source = replacement.id;
|
||||
// Same alias, name and prose, different UUID: name matching must never
|
||||
// silently relink the retained engineering design.
|
||||
assert_ne!(source, fixture.source.root);
|
||||
let deleted = execute_batch(&fixture.project, &[Command::Delete(fixture.source.root)]).unwrap();
|
||||
assert_eq!(deleted, expected_deletion(&fixture, &fixture.source));
|
||||
let recreated =
|
||||
execute_batch(&deleted, &[Command::CreateElement(replacement.clone())]).unwrap();
|
||||
let mut expected = deleted.clone();
|
||||
expected.elements.insert(source, replacement);
|
||||
assert_eq!(recreated, expected);
|
||||
round_trip(&recreated);
|
||||
let (implicit, new_target) =
|
||||
implicit_creation(&recreated, direction, source, fixture.target.root);
|
||||
assert!(implicit.elements.contains_key(&fixture.target.root));
|
||||
assert_ne!(new_target, fixture.target.root);
|
||||
|
||||
// The explicit branch starts from exactly the same recreated project.
|
||||
let mut request = explicit(direction, source, fixture.target.root);
|
||||
let unreviewed = plan_transition(&recreated, &request).unwrap();
|
||||
for field in [TransitionField::Name, TransitionField::Description] {
|
||||
assert!(
|
||||
unreviewed
|
||||
.conflicts
|
||||
.iter()
|
||||
.any(|conflict| conflict.source == Some(source)
|
||||
&& conflict.target == Some(fixture.target.root)
|
||||
&& conflict.field == Some(field))
|
||||
);
|
||||
}
|
||||
assert!(apply_transition(&recreated, &unreviewed).is_err());
|
||||
request.resolutions = vec![
|
||||
FieldResolution {
|
||||
source,
|
||||
field: TransitionField::Name,
|
||||
decision: FieldDecision::TakeSource,
|
||||
},
|
||||
FieldResolution {
|
||||
source,
|
||||
field: TransitionField::Description,
|
||||
decision: FieldDecision::KeepTarget,
|
||||
},
|
||||
];
|
||||
let plan = plan_transition(&recreated, &request).unwrap();
|
||||
assert!(plan.conflicts.is_empty(), "{:?}", plan.conflicts);
|
||||
assert_eq!(plan.changes.len(), 1);
|
||||
assert_eq!(
|
||||
(plan.changes[0].target, plan.changes[0].action),
|
||||
(fixture.target.root, TransitionAction::Update)
|
||||
);
|
||||
assert_eq!(
|
||||
plan.changes[0].fields,
|
||||
vec![FieldChange {
|
||||
field: TransitionField::Name,
|
||||
before: recreated.elements[&fixture.target.root].name.clone(),
|
||||
after: recreated.elements[&source].name.clone(),
|
||||
}]
|
||||
);
|
||||
let relinked = apply_transition(&recreated, &plan).unwrap();
|
||||
let new_trace = assert_only_new_trace(
|
||||
&recreated,
|
||||
&relinked,
|
||||
direction,
|
||||
source,
|
||||
fixture.target.root,
|
||||
);
|
||||
assert_ne!(
|
||||
new_trace, fixture.trace,
|
||||
"Deleted correspondence is not silently resurrected"
|
||||
);
|
||||
let mut expected = recreated.clone();
|
||||
expected
|
||||
.elements
|
||||
.get_mut(&fixture.target.root)
|
||||
.unwrap()
|
||||
.name = recreated.elements[&source].name.clone();
|
||||
let mut without_trace = relinked.clone();
|
||||
without_trace.traces.remove(&new_trace);
|
||||
assert_eq!(
|
||||
without_trace, expected,
|
||||
"Only the reviewed target name may change; rich target design survives"
|
||||
);
|
||||
round_trip(&relinked);
|
||||
unchanged_retry(&relinked, direction, source, fixture.target.root);
|
||||
let original_source = round_trip(&recreated);
|
||||
let mut session = Session::new(recreated.clone());
|
||||
session.execute(Command::Replace(relinked)).unwrap();
|
||||
session.undo();
|
||||
assert_eq!(session.project(), &recreated);
|
||||
assert_eq!(round_trip(session.project()), original_source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oa_source_deletion_preserves_rich_sa_design_and_exact_undo() {
|
||||
source_deletion(TransitionDirection::OaToSa);
|
||||
}
|
||||
#[test]
|
||||
fn sa_source_deletion_preserves_rich_portless_oa_design_and_exact_undo() {
|
||||
source_deletion(TransitionDirection::SaToOa);
|
||||
}
|
||||
#[test]
|
||||
fn deleted_sa_target_refuses_old_plans_and_implicit_retry_creates_once() {
|
||||
target_deletion(TransitionDirection::OaToSa);
|
||||
}
|
||||
#[test]
|
||||
fn deleted_oa_target_refuses_old_plans_and_implicit_retry_creates_once() {
|
||||
target_deletion(TransitionDirection::SaToOa);
|
||||
}
|
||||
#[test]
|
||||
fn recreated_oa_identity_requires_explicit_relink_to_retained_sa_design() {
|
||||
source_recreation(TransitionDirection::OaToSa);
|
||||
}
|
||||
#[test]
|
||||
fn recreated_sa_identity_requires_explicit_relink_to_retained_oa_design() {
|
||||
source_recreation(TransitionDirection::SaToOa);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Focused test harness for the production Allocation planner and Document.
|
||||
//! This does not exercise App input, painting, or native gestures.
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(dead_code)] // App-facing entry points are intentionally absent here.
|
||||
#[path = "../src/allocation_drag.rs"]
|
||||
mod allocation_drag;
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(dead_code, unused_imports)] // App-facing API and reexports are absent here.
|
||||
#[path = "../src/document.rs"]
|
||||
mod document;
|
||||
|
||||
fn main() {}
|
||||
@@ -13,6 +13,19 @@ use oa_core::{
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
// The pure planner is verified before its App gesture adapter is connected.
|
||||
#[allow(dead_code)]
|
||||
#[path = "allocation_drag/arrange.rs"]
|
||||
pub mod arrange;
|
||||
|
||||
#[path = "allocation_drag/geometry.rs"]
|
||||
mod geometry;
|
||||
|
||||
// The combined semantic planner is verified before connecting its App adapter.
|
||||
#[allow(dead_code)]
|
||||
#[path = "allocation_drag/assignment.rs"]
|
||||
pub mod assignment;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Destination {
|
||||
LayoutOnly,
|
||||
@@ -76,6 +89,11 @@ pub enum Refusal {
|
||||
|
||||
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()))?;
|
||||
capture_validated(p, diagram, work, placement)
|
||||
}
|
||||
|
||||
/// Collect work facts after the caller's single complete Project validation.
|
||||
fn capture_validated(p: &Project, diagram: Id, work: Id, placement: Id) -> Result<Scope, Refusal> {
|
||||
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()
|
||||
@@ -232,8 +250,93 @@ pub fn plan_semantics(
|
||||
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();
|
||||
let mut edits = IntendedEdits::default();
|
||||
append_semantic_edits(
|
||||
p,
|
||||
scope,
|
||||
destination,
|
||||
allocation_ids,
|
||||
&mut expected,
|
||||
&mut edits,
|
||||
)?;
|
||||
// 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| !edits.deleted.contains(&r.edge));
|
||||
}
|
||||
let actual = prepare_command(p, &Command::Batch(edits.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 edits.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: edits.commands,
|
||||
before_visible,
|
||||
before_expanded,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct IntendedEdits {
|
||||
commands: Vec<Command>,
|
||||
deleted: BTreeSet<Id>,
|
||||
changed: BTreeSet<Id>,
|
||||
}
|
||||
|
||||
/// Read each root's accepted responsibility while accumulating one intended
|
||||
/// Project, reserving relation identities and aliases across every root.
|
||||
fn append_semantic_edits(
|
||||
p: &Project,
|
||||
scope: &Scope,
|
||||
destination: Destination,
|
||||
allocation_ids: &BTreeMap<Id, Id>,
|
||||
expected: &mut Project,
|
||||
edits: &mut IntendedEdits,
|
||||
) -> Result<(), Refusal> {
|
||||
let same_performer =
|
||||
matches!(destination, Destination::Performer(id) if scope.uniform == Uniform::Assigned(id));
|
||||
let commands = &mut edits.commands;
|
||||
let deleted = &mut edits.deleted;
|
||||
let changed = &mut edits.changed;
|
||||
if destination != Destination::LayoutOnly && !same_performer {
|
||||
for (work, leaf) in &scope.leaves {
|
||||
match destination {
|
||||
@@ -246,6 +349,7 @@ pub fn plan_semantics(
|
||||
target: *work,
|
||||
};
|
||||
expected.relations.insert(edited.id, edited.clone());
|
||||
changed.insert(*work);
|
||||
commands.push(Command::EditRelation(edited.id, edited));
|
||||
}
|
||||
} else {
|
||||
@@ -269,6 +373,7 @@ pub fn plan_semantics(
|
||||
},
|
||||
};
|
||||
expected.relations.insert(id, relation.clone());
|
||||
changed.insert(*work);
|
||||
commands.push(Command::CreateRelation(relation));
|
||||
}
|
||||
}
|
||||
@@ -327,6 +432,7 @@ pub fn plan_semantics(
|
||||
if let Some(existing) = &leaf.direct {
|
||||
expected.relations.remove(&existing.id);
|
||||
deleted.insert(existing.id);
|
||||
changed.insert(*work);
|
||||
commands.push(Command::Delete(existing.id));
|
||||
}
|
||||
}
|
||||
@@ -334,60 +440,7 @@ pub fn plan_semantics(
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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,
|
||||
})
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// World-space rectangle in the gesture's frozen transform. The UI resolver
|
||||
@@ -462,60 +515,18 @@ pub fn place(
|
||||
"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 geometry::Translation {
|
||||
mut diagram,
|
||||
mut commands,
|
||||
delta,
|
||||
} = geometry::translate(
|
||||
&plan.accepted,
|
||||
&plan.scope.diagram,
|
||||
&plan.candidate.diagrams[&plan.scope.diagram.id],
|
||||
&plan.scope.placements,
|
||||
plan.scope.placement,
|
||||
requested,
|
||||
)?;
|
||||
let mut unfolded = None;
|
||||
if let Destination::Performer(performer) = plan.destination {
|
||||
let target = presentation.target.ok_or_else(|| {
|
||||
@@ -833,4 +844,5 @@ fn exact_project(expected: &Project, actual: &Project) -> Result<(), Refusal> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "allocation_drag/tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Explicit, semantics-preserving arrangement of one or more Allocation cards.
|
||||
//!
|
||||
//! The App must admit the entire original typed selection before converting it
|
||||
//! to placement/element identities. These values do not grant input authority.
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Plan {
|
||||
accepted: Project,
|
||||
diagram: Id,
|
||||
selected: BTreeMap<Id, Id>,
|
||||
anchor: Id,
|
||||
placements: BTreeMap<Id, NodePlacement>,
|
||||
expanded_ids: BTreeSet<Id>,
|
||||
index: ViewIndex,
|
||||
before_visible: ProjectedView,
|
||||
before_expanded: ProjectedView,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
pub fn project(&self) -> &Project {
|
||||
&self.accepted
|
||||
}
|
||||
|
||||
pub fn index(&self) -> &ViewIndex {
|
||||
&self.index
|
||||
}
|
||||
|
||||
pub fn affected(&self) -> &BTreeMap<Id, NodePlacement> {
|
||||
&self.placements
|
||||
}
|
||||
|
||||
pub fn selected(&self) -> &BTreeMap<Id, Id> {
|
||||
&self.selected
|
||||
}
|
||||
|
||||
pub fn anchor(&self) -> Id {
|
||||
self.anchor
|
||||
}
|
||||
|
||||
pub fn diagram(&self) -> &Diagram {
|
||||
&self.accepted.diagrams[&self.diagram]
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture every original placement identity before normalizing semantic roots.
|
||||
/// Document/revision/selection-generation and clean-owner guards belong to App.
|
||||
pub fn capture(
|
||||
p: &Project,
|
||||
diagram: Id,
|
||||
selected: &BTreeMap<Id, Id>,
|
||||
anchor: Id,
|
||||
) -> Result<Plan, Refusal> {
|
||||
validate_candidate(p).map_err(|e| Refusal::InvalidCandidate(e.to_string()))?;
|
||||
let d = p.diagrams.get(&diagram).ok_or(Refusal::StaleScope)?;
|
||||
if d.projection != ProjectionKind::Allocation
|
||||
|| selected.is_empty()
|
||||
|| !selected.contains_key(&anchor)
|
||||
{
|
||||
return Err(Refusal::Ineligible(
|
||||
"Arrange requires selected placements and a selected anchor in an Allocation view."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let index = ViewIndex::new(p);
|
||||
let before_visible = projection::project_diagram_with_index(p, d, &index);
|
||||
let visible: BTreeMap<_, _> = before_visible
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|n| (n.id, n.element))
|
||||
.collect();
|
||||
let mut work = BTreeMap::new();
|
||||
let mut performers = Vec::new();
|
||||
for (placement, element) in selected {
|
||||
let node = d.nodes.get(placement).ok_or(Refusal::StaleScope)?;
|
||||
let record = p.elements.get(element).ok_or(Refusal::StaleScope)?;
|
||||
if node.element != *element || visible.get(placement) != Some(element) {
|
||||
return Err(Refusal::StaleScope);
|
||||
}
|
||||
if record.layer() != d.layer || !(record.kind().is_work() || record.kind().is_performer()) {
|
||||
return Err(Refusal::Ineligible(
|
||||
"Arrange requires only activities, functions or performers in this layer.".into(),
|
||||
));
|
||||
}
|
||||
if record.kind().is_work() {
|
||||
work.insert(*element, *placement);
|
||||
} else {
|
||||
performers.push(*placement);
|
||||
}
|
||||
}
|
||||
|
||||
let mut placements = BTreeMap::new();
|
||||
for (element, placement) in &work {
|
||||
let root = &p.elements[element];
|
||||
let mut ancestor = root.parent;
|
||||
let mut covered = false;
|
||||
let mut seen = BTreeSet::new();
|
||||
while let Some(id) = ancestor {
|
||||
if !seen.insert(id) {
|
||||
return Err(Refusal::StaleScope);
|
||||
}
|
||||
let parent = p.elements.get(&id).ok_or(Refusal::StaleScope)?;
|
||||
if parent.kind() != root.kind() {
|
||||
break;
|
||||
}
|
||||
if work.contains_key(&id) {
|
||||
covered = true;
|
||||
break;
|
||||
}
|
||||
ancestor = parent.parent;
|
||||
}
|
||||
if !covered {
|
||||
placements.extend(capture_validated(p, diagram, *element, *placement)?.placements);
|
||||
}
|
||||
}
|
||||
for performer in performers {
|
||||
for id in
|
||||
std::iter::once(performer).chain(projection::descendant_nodes(p, diagram, performer))
|
||||
{
|
||||
placements.insert(id, d.nodes.get(&id).ok_or(Refusal::StaleScope)?.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// Arrange preserves ancestry, so accepted diagnostic identities also apply
|
||||
// to every translated candidate.
|
||||
let expanded_ids = geometry::expansion_ids(p, d, &index, &placements)?;
|
||||
let before_expanded = geometry::expanded_view(p, d, &index, &expanded_ids);
|
||||
Ok(Plan {
|
||||
accepted: p.clone(),
|
||||
diagram,
|
||||
selected: selected.clone(),
|
||||
anchor,
|
||||
placements,
|
||||
expanded_ids,
|
||||
index,
|
||||
before_visible,
|
||||
before_expanded,
|
||||
})
|
||||
}
|
||||
|
||||
/// Snap the captured anchor once; preview the complete union without cloning or
|
||||
/// validating a Project, rebuilding its semantic index, or expanding scope.
|
||||
pub fn place(
|
||||
plan: &Plan,
|
||||
requested: Position,
|
||||
presentation: PresentationContext,
|
||||
) -> Result<PlacementPlan, Refusal> {
|
||||
if presentation.target.is_some() {
|
||||
return Err(Refusal::Ineligible(
|
||||
"Arrange only has no performer destination.".into(),
|
||||
));
|
||||
}
|
||||
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 geometry::Translation {
|
||||
diagram,
|
||||
commands,
|
||||
delta,
|
||||
} = geometry::translate(
|
||||
&plan.accepted,
|
||||
plan.diagram(),
|
||||
plan.diagram(),
|
||||
&plan.placements,
|
||||
plan.anchor,
|
||||
requested,
|
||||
)?;
|
||||
let view = projection::project_diagram_with_index(&plan.accepted, &diagram, &plan.index);
|
||||
let expanded =
|
||||
geometry::expanded_view(&plan.accepted, &diagram, &plan.index, &plan.expanded_ids);
|
||||
// Preserve Arrange's refusal precedence: projected bounds, then rigidity,
|
||||
// then overlap growth. The shared scene check combines bounds and overlaps.
|
||||
let scenes = match geometry::check_scenes(
|
||||
&plan.before_visible,
|
||||
&plan.before_expanded,
|
||||
&view,
|
||||
&expanded,
|
||||
) {
|
||||
Err(error @ Refusal::InvalidCandidate(_)) => return Err(error),
|
||||
result => result,
|
||||
};
|
||||
geometry::check_rigid(&plan.before_expanded, &expanded, &plan.placements, delta)?;
|
||||
scenes?;
|
||||
geometry::check_headers(&view, &plan.selected, presentation.viewport)?;
|
||||
Ok(PlacementPlan {
|
||||
diagram,
|
||||
view,
|
||||
delta,
|
||||
unfolded: None,
|
||||
requested,
|
||||
presentation,
|
||||
commands,
|
||||
})
|
||||
}
|
||||
|
||||
/// Recompute the candidate and compare the complete expected Project before the
|
||||
/// caller performs one source-admitted transaction. None means no history entry.
|
||||
pub fn finish(
|
||||
plan: &Plan,
|
||||
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.accepted.clone();
|
||||
expected
|
||||
.diagrams
|
||||
.insert(checked.diagram.id, checked.diagram);
|
||||
let command = Command::Batch(checked.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))
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
use super::*;
|
||||
|
||||
struct Distributed {
|
||||
f: Fixture,
|
||||
a: Id,
|
||||
b: Id,
|
||||
x: Id,
|
||||
y: Id,
|
||||
internal: Id,
|
||||
}
|
||||
|
||||
fn distributed(layer: Layer, folded: bool) -> Distributed {
|
||||
let mut f = fixture(layer);
|
||||
let kind = f.p.elements[&f.w].kind();
|
||||
let x = f.p.add_element(kind, layer, "X", Some(f.w)).unwrap();
|
||||
let y = f.p.add_element(kind, layer, "Y", Some(f.w)).unwrap();
|
||||
let outside = f.p.add_element(kind, layer, "Outside", None).unwrap();
|
||||
let xn = f.p.place(f.d, x, xy(140., 200.));
|
||||
let yn = f.p.place(f.d, y, xy(940., 200.));
|
||||
f.p.place(f.d, outside, xy(1800., 800.));
|
||||
f.p.relate(RelationKind::Allocation, "A owns X", f.a, x);
|
||||
f.p.relate(RelationKind::Allocation, "B owns Y", f.b, y);
|
||||
let exchange = match layer {
|
||||
Layer::Oa => RelationKind::Interaction,
|
||||
Layer::Sa => RelationKind::FunctionalExchange,
|
||||
};
|
||||
let internal = f.p.relate(exchange, "X to Y", x, y);
|
||||
let external = f.p.relate(exchange, "Y to Outside", y, outside);
|
||||
let d = f.p.diagrams.get_mut(&f.d).unwrap();
|
||||
let a = d.nodes.values().find(|n| n.element == f.a).unwrap().id;
|
||||
let b = d.nodes.values().find(|n| n.element == f.b).unwrap().id;
|
||||
d.nodes.get_mut(&a).unwrap().collapsed = folded;
|
||||
d.nodes.get_mut(&f.n).unwrap().position = xy(100., 800.);
|
||||
d.routes = vec![route(internal), route(external)];
|
||||
validate_candidate(&f.p).unwrap();
|
||||
Distributed {
|
||||
f,
|
||||
a,
|
||||
b,
|
||||
x: xn,
|
||||
y: yn,
|
||||
internal,
|
||||
}
|
||||
}
|
||||
|
||||
fn identities(m: &Distributed, ids: &[Id]) -> BTreeMap<Id, Id> {
|
||||
ids.iter()
|
||||
.map(|id| (*id, m.f.p.diagrams[&m.f.d].nodes[id].element))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn expected(m: &Distributed, include_a: bool) -> Project {
|
||||
let mut p = m.f.p.clone();
|
||||
let d = p.diagrams.get_mut(&m.f.d).unwrap();
|
||||
for (id, position) in [
|
||||
(m.f.n, xy(500., 800.)),
|
||||
(m.x, xy(540., 200.)),
|
||||
(m.y, xy(1340., 200.)),
|
||||
] {
|
||||
d.nodes.get_mut(&id).unwrap().position = position;
|
||||
}
|
||||
if include_a {
|
||||
d.nodes.get_mut(&m.a).unwrap().position = xy(500., 100.);
|
||||
}
|
||||
d.routes
|
||||
.iter_mut()
|
||||
.find(|r| r.edge == m.internal)
|
||||
.unwrap()
|
||||
.waypoints = vec![xy(820., 400.), xy(820., 550.)];
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_distributed_oa_sa_exact_scope_routes_source_history_and_anchor() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
for folded in [false, true] {
|
||||
for include_a in [false, true] {
|
||||
let m = distributed(layer, folded);
|
||||
let members = if include_a {
|
||||
vec![m.f.n, m.a]
|
||||
} else {
|
||||
vec![m.f.n]
|
||||
};
|
||||
let selected = identities(&m, &members);
|
||||
for anchor in selected.keys().copied() {
|
||||
let plan = arrange::capture(&m.f.p, m.f.d, &selected, anchor).unwrap();
|
||||
assert_eq!(plan.selected(), &selected);
|
||||
let mut affected = BTreeSet::from([m.f.n, m.x, m.y]);
|
||||
if include_a {
|
||||
affected.insert(m.a);
|
||||
}
|
||||
assert_eq!(
|
||||
plan.affected().keys().copied().collect::<BTreeSet<_>>(),
|
||||
affected
|
||||
);
|
||||
let requested = if anchor == m.a {
|
||||
xy(503., 102.)
|
||||
} else {
|
||||
xy(503., 802.)
|
||||
};
|
||||
let placed =
|
||||
arrange::place(&plan, requested, presentation(&m.f.p, m.f.d, None))
|
||||
.unwrap();
|
||||
assert_eq!(placed.delta, xy(400., 0.));
|
||||
assert_eq!(placed.unfolded, None);
|
||||
let command = arrange::finish(&plan, &m.f.p, &placed).unwrap().unwrap();
|
||||
assert_eq!(roundtrip(&m.f.p, command), expected(&m, include_a));
|
||||
// Explicit Arrange does not widen ordinary distributed assignment.
|
||||
assert!(matches!(
|
||||
plan_semantics(
|
||||
&m.f.p,
|
||||
&scope(&m.f),
|
||||
Destination::Performer(m.f.a),
|
||||
&BTreeMap::new()
|
||||
),
|
||||
Err(Refusal::MixedLayoutRequired)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_performer_closure_does_not_acquire_incidental_semantic_root() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let m = distributed(layer, true);
|
||||
let selected = identities(&m, &[m.a]);
|
||||
let plan = arrange::capture(&m.f.p, m.f.d, &selected, m.a).unwrap();
|
||||
assert_eq!(
|
||||
plan.affected().keys().copied().collect::<BTreeSet<_>>(),
|
||||
BTreeSet::from([m.a, m.x])
|
||||
);
|
||||
let placed =
|
||||
arrange::place(&plan, xy(500., 100.), presentation(&m.f.p, m.f.d, None)).unwrap();
|
||||
let mut expected = m.f.p.clone();
|
||||
let d = expected.diagrams.get_mut(&m.f.d).unwrap();
|
||||
d.nodes.get_mut(&m.a).unwrap().position = xy(500., 100.);
|
||||
d.nodes.get_mut(&m.x).unwrap().position = xy(540., 200.);
|
||||
// X-to-Y is now one-ended; all saved pins remain byte-for-byte unchanged.
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&m.f.p,
|
||||
arrange::finish(&plan, &m.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_validates_all_original_members_before_normalizing() {
|
||||
let mut m = distributed(Layer::Oa, false);
|
||||
let selected = identities(&m, &[m.f.n, m.x]);
|
||||
let plan = arrange::capture(&m.f.p, m.f.d, &selected, m.x).unwrap();
|
||||
assert_eq!(plan.selected(), &selected);
|
||||
assert_eq!(plan.affected().len(), 3);
|
||||
let placed = arrange::place(&plan, xy(540., 200.), presentation(&m.f.p, m.f.d, None)).unwrap();
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&m.f.p,
|
||||
arrange::finish(&plan, &m.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected(&m, false)
|
||||
);
|
||||
let mut stale = selected.clone();
|
||||
stale.insert(m.x, m.f.w);
|
||||
assert!(arrange::capture(&m.f.p, m.f.d, &stale, m.f.n).is_err());
|
||||
m.f.p
|
||||
.diagrams
|
||||
.get_mut(&m.f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&m.a)
|
||||
.unwrap()
|
||||
.collapsed = true;
|
||||
assert!(
|
||||
arrange::capture(&m.f.p, m.f.d, &selected, m.f.n).is_err(),
|
||||
"covered selected X is hidden and cannot disappear in normalization"
|
||||
);
|
||||
assert!(arrange::capture(&m.f.p, m.f.d, &BTreeMap::new(), m.f.n).is_err());
|
||||
assert!(arrange::capture(&m.f.p, m.f.d, &identities(&m, &[m.f.n]), m.a).is_err());
|
||||
assert!(arrange::capture(&m.f.p, m.f.second, &identities(&m, &[m.f.n]), m.f.n).is_err());
|
||||
let foreign = Id::new_v4();
|
||||
assert!(
|
||||
arrange::capture(
|
||||
&m.f.p,
|
||||
m.f.d,
|
||||
&BTreeMap::from([(m.f.n, m.f.w), (foreign, m.f.w)]),
|
||||
m.f.n
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
m.f.p.diagrams.get_mut(&m.f.d).unwrap().projection = ProjectionKind::Overview;
|
||||
assert!(arrange::capture(&m.f.p, m.f.d, &identities(&m, &[m.f.n]), m.f.n).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_simultaneous_roots_may_enter_each_others_vacated_bounds() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut f = fixture(layer);
|
||||
let kind = f.p.elements[&f.w].kind();
|
||||
let y = f.p.add_element(kind, layer, "Second root", None).unwrap();
|
||||
let yn = f.p.place(f.d, y, xy(400., 500.));
|
||||
let relation = f.p.relate(
|
||||
if layer == Layer::Oa {
|
||||
RelationKind::Interaction
|
||||
} else {
|
||||
RelationKind::FunctionalExchange
|
||||
},
|
||||
"Between roots",
|
||||
f.w,
|
||||
y,
|
||||
);
|
||||
f.p.diagrams.get_mut(&f.d).unwrap().routes = vec![route(relation)];
|
||||
let context = presentation(&f.p, f.d, None);
|
||||
let single = arrange::capture(&f.p, f.d, &BTreeMap::from([(f.n, f.w)]), f.n).unwrap();
|
||||
assert!(
|
||||
arrange::place(&single, xy(400., 500.), context).is_err(),
|
||||
"singleton would collide with stationary Y"
|
||||
);
|
||||
let plan =
|
||||
arrange::capture(&f.p, f.d, &BTreeMap::from([(f.n, f.w), (yn, y)]), f.n).unwrap();
|
||||
let placed = arrange::place(&plan, xy(400., 500.), context).unwrap();
|
||||
let mut expected = f.p.clone();
|
||||
let d = expected.diagrams.get_mut(&f.d).unwrap();
|
||||
d.nodes.get_mut(&f.n).unwrap().position = xy(400., 500.);
|
||||
d.nodes.get_mut(&yn).unwrap().position = xy(700., 500.);
|
||||
d.routes[0].waypoints = vec![xy(720., 400.), xy(720., 550.)];
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&f.p,
|
||||
arrange::finish(&plan, &f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_preserves_roles_and_does_not_invent_unplaced_descendants() {
|
||||
let mut f = fixture(Layer::Oa);
|
||||
let a = f.a;
|
||||
role(&mut f, Some(a));
|
||||
f.p.diagrams
|
||||
.get_mut(&f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&f.n)
|
||||
.unwrap()
|
||||
.position = xy(150., 200.);
|
||||
let plan = arrange::capture(&f.p, f.d, &BTreeMap::from([(f.n, f.w)]), f.n).unwrap();
|
||||
let placed = arrange::place(&plan, xy(160., 210.), presentation(&f.p, f.d, None)).unwrap();
|
||||
let mut role_expected = f.p.clone();
|
||||
role_expected
|
||||
.diagrams
|
||||
.get_mut(&f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&f.n)
|
||||
.unwrap()
|
||||
.position = xy(160., 210.);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&f.p,
|
||||
arrange::finish(&plan, &f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
role_expected
|
||||
);
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut m = distributed(layer, true);
|
||||
let kind = m.f.p.elements[&m.f.w].kind();
|
||||
m.f.p
|
||||
.add_element(kind, layer, "Unplaced leaf", Some(m.f.w))
|
||||
.unwrap();
|
||||
let plan = arrange::capture(&m.f.p, m.f.d, &identities(&m, &[m.f.n]), m.f.n).unwrap();
|
||||
assert_eq!(plan.affected().len(), 3);
|
||||
let placed =
|
||||
arrange::place(&plan, xy(500., 800.), presentation(&m.f.p, m.f.d, None)).unwrap();
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&m.f.p,
|
||||
arrange::finish(&plan, &m.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected(&m, false)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_detects_hidden_moved_child_and_stationary_enclosure_growth() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
for hidden in [false, true] {
|
||||
let mut m = distributed(layer, hidden);
|
||||
let kind = m.f.p.elements[&m.f.w].kind();
|
||||
let z = m.f.p.add_element(kind, layer, "Obstacle", None).unwrap();
|
||||
let zn = m.f.p.place(
|
||||
m.f.d,
|
||||
z,
|
||||
if hidden {
|
||||
xy(550., 230.)
|
||||
} else {
|
||||
xy(1200., 100.)
|
||||
},
|
||||
);
|
||||
// The independent candidate differs only by literal admitted edits.
|
||||
// Establish which geometric case the real planner must reject.
|
||||
let candidate = expected(&m, true);
|
||||
let before = projection::project_view(&m.f.p, m.f.d);
|
||||
let after = projection::project_view(&candidate, m.f.d);
|
||||
let find =
|
||||
|view: &ProjectedView, id| view.nodes.iter().find(|n| n.id == id).unwrap().clone();
|
||||
if hidden {
|
||||
assert!(!overlaps(&before, &after));
|
||||
assert!(!after.nodes.iter().any(|n| n.id == m.x));
|
||||
let mut diagnostic = candidate.diagrams[&m.f.d].clone();
|
||||
diagnostic.nodes.get_mut(&m.a).unwrap().collapsed = false;
|
||||
let expanded = projection::project_diagram(&candidate, &diagnostic);
|
||||
assert_eq!(
|
||||
overlap(&find(&expanded, m.x), &find(&expanded, zn)),
|
||||
if layer == Layer::Oa { 13696. } else { 20116. }
|
||||
);
|
||||
} else {
|
||||
assert_eq!(overlap(&find(&before, m.b), &find(&before, zn)), 0.);
|
||||
assert_eq!(overlap(&find(&after, m.b), &find(&after, zn)), 21056.);
|
||||
for id in [m.a, m.f.n, m.x, m.y] {
|
||||
assert_eq!(overlap(&find(&after, id), &find(&after, zn)), 0.);
|
||||
}
|
||||
assert_eq!(
|
||||
candidate.diagrams[&m.f.d].nodes[&m.b],
|
||||
m.f.p.diagrams[&m.f.d].nodes[&m.b]
|
||||
);
|
||||
}
|
||||
let plan =
|
||||
arrange::capture(&m.f.p, m.f.d, &identities(&m, &[m.a, m.f.n]), m.f.n).unwrap();
|
||||
assert!(matches!(
|
||||
arrange::place(&plan, xy(500., 800.), presentation(&m.f.p, m.f.d, None)),
|
||||
Err(Refusal::LayoutRequired(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_preserves_existing_overlap_but_refuses_its_growth() {
|
||||
let mut f = fixture(Layer::Oa);
|
||||
let y =
|
||||
f.p.add_element(Kind::Activity, Layer::Oa, "Existing overlap", None)
|
||||
.unwrap();
|
||||
let yn = f.p.place(f.d, y, xy(250., 500.));
|
||||
let context = presentation(&f.p, f.d, None);
|
||||
let single = arrange::capture(&f.p, f.d, &BTreeMap::from([(f.n, f.w)]), f.n).unwrap();
|
||||
assert!(arrange::place(&single, xy(110., 500.), context).is_err());
|
||||
let plan = arrange::capture(&f.p, f.d, &BTreeMap::from([(f.n, f.w), (yn, y)]), f.n).unwrap();
|
||||
let placed = arrange::place(&plan, xy(400., 500.), context).unwrap();
|
||||
let mut expected = f.p.clone();
|
||||
let d = expected.diagrams.get_mut(&f.d).unwrap();
|
||||
d.nodes.get_mut(&f.n).unwrap().position = xy(400., 500.);
|
||||
d.nodes.get_mut(&yn).unwrap().position = xy(550., 500.);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&f.p,
|
||||
arrange::finish(&plan, &f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_preserves_unrelated_folded_interior_diagnostic_boundary() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut m = distributed(layer, true);
|
||||
let performer = if layer == Layer::Oa {
|
||||
Kind::Actor
|
||||
} else {
|
||||
Kind::SystemActor
|
||||
};
|
||||
let d = m.f.p.add_element(performer, layer, "D", None).unwrap();
|
||||
let z =
|
||||
m.f.p
|
||||
.add_element(m.f.p.elements[&m.f.w].kind(), layer, "Hidden Z", None)
|
||||
.unwrap();
|
||||
m.f.p.relate(RelationKind::Allocation, "D owns Z", d, z);
|
||||
let dn = m.f.p.place(m.f.d, d, xy(2500., 100.));
|
||||
m.f.p.place(m.f.d, z, xy(550., 230.));
|
||||
m.f.p
|
||||
.diagrams
|
||||
.get_mut(&m.f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&dn)
|
||||
.unwrap()
|
||||
.collapsed = true;
|
||||
let plan = arrange::capture(&m.f.p, m.f.d, &identities(&m, &[m.a, m.f.n]), m.f.n).unwrap();
|
||||
let placed =
|
||||
arrange::place(&plan, xy(500., 800.), presentation(&m.f.p, m.f.d, None)).unwrap();
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&m.f.p,
|
||||
arrange::finish(&plan, &m.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected(&m, true)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_arrange_noop_stale_tamper_target_and_all_selected_headers() {
|
||||
let m = distributed(Layer::Sa, false);
|
||||
let selected = identities(&m, &[m.a, m.f.n]);
|
||||
let plan = arrange::capture(&m.f.p, m.f.d, &selected, m.f.n).unwrap();
|
||||
let context = presentation(&m.f.p, m.f.d, None);
|
||||
let noop = arrange::place(&plan, xy(103., 802.), context).unwrap();
|
||||
assert!(arrange::finish(&plan, &m.f.p, &noop).unwrap().is_none());
|
||||
let mut placed = arrange::place(&plan, xy(500., 800.), context).unwrap();
|
||||
let mut stale = m.f.p.clone();
|
||||
stale.name.push_str(" changed");
|
||||
assert!(matches!(
|
||||
arrange::finish(&plan, &stale, &placed),
|
||||
Err(Refusal::StaleScope)
|
||||
));
|
||||
placed.diagram.nodes.get_mut(&m.b).unwrap().position.x += 1.;
|
||||
assert!(matches!(
|
||||
arrange::finish(&plan, &m.f.p, &placed),
|
||||
Err(Refusal::StaleScope)
|
||||
));
|
||||
assert!(
|
||||
arrange::place(
|
||||
&plan,
|
||||
xy(500., 800.),
|
||||
presentation(&m.f.p, m.f.d, Some(m.f.b))
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut clipped = context;
|
||||
clipped.viewport.position = xy(400., 700.);
|
||||
assert!(
|
||||
arrange::place(&plan, xy(500., 800.), clipped).is_err(),
|
||||
"anchor C visible, other selected A header clipped"
|
||||
);
|
||||
assert!(arrange::place(&plan, xy(f32::NAN, 800.), context).is_err());
|
||||
assert!(arrange::place(&plan, xy(MAX_COORDINATE, 800.), context).is_err());
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
//! Ordinary work-only group assignment, with one combined semantic/geometry plan.
|
||||
//! App retains authority over the complete typed selection and gesture lifetime.
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Captured {
|
||||
accepted: Project,
|
||||
diagram: Id,
|
||||
selected: BTreeMap<Id, Id>,
|
||||
anchor: Id,
|
||||
roots: Vec<super::Scope>,
|
||||
placements: BTreeMap<Id, NodePlacement>,
|
||||
leaves: BTreeMap<Id, Leaf>,
|
||||
index: ViewIndex,
|
||||
before_visible: ProjectedView,
|
||||
before_expanded: ProjectedView,
|
||||
}
|
||||
|
||||
/// Destination plans share one immutable accepted capture.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Scope(Arc<Captured>);
|
||||
|
||||
impl Scope {
|
||||
pub fn project(&self) -> &Project {
|
||||
&self.0.accepted
|
||||
}
|
||||
|
||||
pub fn index(&self) -> &ViewIndex {
|
||||
&self.0.index
|
||||
}
|
||||
|
||||
pub fn diagram(&self) -> &Diagram {
|
||||
&self.0.accepted.diagrams[&self.0.diagram]
|
||||
}
|
||||
|
||||
pub fn selected(&self) -> &BTreeMap<Id, Id> {
|
||||
&self.0.selected
|
||||
}
|
||||
|
||||
pub fn affected(&self) -> &BTreeMap<Id, NodePlacement> {
|
||||
&self.0.placements
|
||||
}
|
||||
|
||||
pub fn anchor(&self) -> Id {
|
||||
self.0.anchor
|
||||
}
|
||||
|
||||
pub fn leaves(&self) -> &BTreeMap<Id, Leaf> {
|
||||
&self.0.leaves
|
||||
}
|
||||
}
|
||||
|
||||
/// App must reject non-placement members before constructing this complete map.
|
||||
/// Every original identity is checked before redundant work roots are removed.
|
||||
pub fn capture(
|
||||
p: &Project,
|
||||
diagram: Id,
|
||||
selected: &BTreeMap<Id, Id>,
|
||||
anchor: 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)?;
|
||||
if d.projection != ProjectionKind::Allocation
|
||||
|| selected.is_empty()
|
||||
|| !selected.contains_key(&anchor)
|
||||
{
|
||||
return Err(Refusal::Ineligible(
|
||||
"Assignment requires selected work placements and a selected anchor in an Allocation view."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let index = ViewIndex::new(p);
|
||||
let before_visible = projection::project_diagram_with_index(p, d, &index);
|
||||
let visible: BTreeMap<_, _> = before_visible
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|node| (node.id, node.element))
|
||||
.collect();
|
||||
let mut work = BTreeMap::new();
|
||||
for (placement, element) in selected {
|
||||
let node = d.nodes.get(placement).ok_or(Refusal::StaleScope)?;
|
||||
let record = p.elements.get(element).ok_or(Refusal::StaleScope)?;
|
||||
if node.element != *element || visible.get(placement) != Some(element) {
|
||||
return Err(Refusal::StaleScope);
|
||||
}
|
||||
if !record.kind().is_work() || record.layer() != d.layer {
|
||||
return Err(Refusal::Ineligible(
|
||||
"Assignment requires only activities or functions in this layer. Use Arrange only for a supported mixed selection."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
work.insert(*element, *placement);
|
||||
}
|
||||
|
||||
let mut roots = Vec::new();
|
||||
let mut placements = BTreeMap::new();
|
||||
let mut leaves = BTreeMap::new();
|
||||
for (element, placement) in &work {
|
||||
let record = &p.elements[element];
|
||||
let mut ancestor = record.parent;
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut covered = false;
|
||||
while let Some(id) = ancestor {
|
||||
if !seen.insert(id) {
|
||||
return Err(Refusal::StaleScope);
|
||||
}
|
||||
let parent = p.elements.get(&id).ok_or(Refusal::StaleScope)?;
|
||||
if parent.kind() != record.kind() {
|
||||
break;
|
||||
}
|
||||
if work.contains_key(&id) {
|
||||
covered = true;
|
||||
break;
|
||||
}
|
||||
ancestor = parent.parent;
|
||||
}
|
||||
if covered {
|
||||
continue;
|
||||
}
|
||||
let root = capture_validated(p, diagram, *element, *placement)?;
|
||||
if root.work_records.len() > 1 && root.uniform == Uniform::MixedOrUnresolved {
|
||||
return Err(Refusal::MixedLayoutRequired);
|
||||
}
|
||||
for (id, leaf) in &root.leaves {
|
||||
if leaves.insert(*id, leaf.clone()).is_some() {
|
||||
return Err(Refusal::StaleScope);
|
||||
}
|
||||
}
|
||||
placements.extend(root.placements.clone());
|
||||
roots.push(root);
|
||||
}
|
||||
let expansion = geometry::expansion_ids(p, d, &index, &placements)?;
|
||||
let before_expanded = geometry::expanded_view(p, d, &index, &expansion);
|
||||
if roots
|
||||
.iter()
|
||||
.any(|root| root.work_records.len() > 1 && !coherent(root, &before_expanded))
|
||||
{
|
||||
return Err(Refusal::MixedLayoutRequired);
|
||||
}
|
||||
Ok(Scope(Arc::new(Captured {
|
||||
accepted: p.clone(),
|
||||
diagram,
|
||||
selected: selected.clone(),
|
||||
anchor,
|
||||
roots,
|
||||
placements,
|
||||
leaves,
|
||||
index,
|
||||
before_visible,
|
||||
before_expanded,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SemanticPlan {
|
||||
scope: Scope,
|
||||
destination: Destination,
|
||||
candidate: Project,
|
||||
index: ViewIndex,
|
||||
commands: Vec<Command>,
|
||||
changed: BTreeSet<Id>,
|
||||
expanded_ids: BTreeSet<Id>,
|
||||
label: String,
|
||||
warnings: Vec<Issue>,
|
||||
}
|
||||
|
||||
impl SemanticPlan {
|
||||
pub fn scope(&self) -> &Scope {
|
||||
&self.scope
|
||||
}
|
||||
|
||||
pub fn project(&self) -> &Project {
|
||||
&self.candidate
|
||||
}
|
||||
|
||||
pub fn index(&self) -> &ViewIndex {
|
||||
&self.index
|
||||
}
|
||||
|
||||
pub fn destination(&self) -> Destination {
|
||||
self.destination
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &str {
|
||||
&self.label
|
||||
}
|
||||
|
||||
pub fn warnings(&self) -> &[Issue] {
|
||||
&self.warnings
|
||||
}
|
||||
|
||||
pub fn changed_count(&self) -> usize {
|
||||
self.changed.len()
|
||||
}
|
||||
|
||||
/// Already effective at the performer, or already unassigned for Outside.
|
||||
pub fn already_correct_count(&self) -> usize {
|
||||
self.scope.leaves().len() - self.changed.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Build one destination candidate. Per-root decisions read accepted facts;
|
||||
/// aliases and new identities are reserved in the combined expected Project.
|
||||
pub fn plan_semantics(
|
||||
scope: &Scope,
|
||||
destination: Destination,
|
||||
allocation_ids: &BTreeMap<Id, Id>,
|
||||
) -> Result<SemanticPlan, Refusal> {
|
||||
let accepted = scope.project();
|
||||
match destination {
|
||||
Destination::LayoutOnly => {
|
||||
return Err(Refusal::Ineligible(
|
||||
"Use the explicit Arrange only planner for presentation-only movement.".into(),
|
||||
));
|
||||
}
|
||||
Destination::Performer(id) => {
|
||||
if !accepted.elements.get(&id).is_some_and(|element| {
|
||||
element.kind().is_performer() && element.layer() == scope.diagram().layer
|
||||
}) {
|
||||
return Err(Refusal::Ineligible(
|
||||
"Choose a performer in this layer.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Destination::OutsidePerformers => {}
|
||||
}
|
||||
let mut expected = accepted.clone();
|
||||
let mut edits = IntendedEdits::default();
|
||||
for root in &scope.0.roots {
|
||||
append_semantic_edits(
|
||||
accepted,
|
||||
root,
|
||||
destination,
|
||||
allocation_ids,
|
||||
&mut expected,
|
||||
&mut edits,
|
||||
)?;
|
||||
}
|
||||
for diagram in expected.diagrams.values_mut() {
|
||||
diagram
|
||||
.routes
|
||||
.retain(|route| !edits.deleted.contains(&route.edge));
|
||||
}
|
||||
let candidate = prepare_command(accepted, &Command::Batch(edits.commands.clone()))
|
||||
.map_err(|e| Refusal::InvalidCandidate(e.to_string()))?
|
||||
.project;
|
||||
exact_project(&expected, &candidate)?;
|
||||
let warnings = validation::validate(&candidate)
|
||||
.into_iter()
|
||||
.filter(|issue| issue.severity == Severity::Warning)
|
||||
.collect();
|
||||
let index = ViewIndex::new(&candidate);
|
||||
// Assignment may change visual ancestry: never reuse accepted expansion IDs.
|
||||
let expanded_ids = geometry::expansion_ids(
|
||||
&candidate,
|
||||
&candidate.diagrams[&scope.0.diagram],
|
||||
&index,
|
||||
scope.affected(),
|
||||
)?;
|
||||
let total = scope.leaves().len();
|
||||
let changed = edits.changed.len();
|
||||
let already_correct = total - changed;
|
||||
let noun = match (scope.diagram().layer, total) {
|
||||
(Layer::Oa, 1) => "activity",
|
||||
(Layer::Oa, _) => "activities",
|
||||
(Layer::Sa, 1) => "function",
|
||||
(Layer::Sa, _) => "functions",
|
||||
};
|
||||
let retained_roles = scope
|
||||
.leaves()
|
||||
.values()
|
||||
.any(|leaf| !leaf.role_assignments.is_empty());
|
||||
let label = match destination {
|
||||
Destination::Performer(id) if changed == 0 => {
|
||||
format!(
|
||||
"Arrange within {} — all {total} leaf {noun} already assigned",
|
||||
accepted.named(id)
|
||||
)
|
||||
}
|
||||
Destination::Performer(id) => format!(
|
||||
"Assign {changed} of {total} leaf {noun} to {}{}{}",
|
||||
accepted.named(id),
|
||||
if already_correct > 0 {
|
||||
format!(" · {already_correct} already assigned")
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
if retained_roles {
|
||||
" — role responsibility retained"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
),
|
||||
Destination::OutsidePerformers if changed == 0 => {
|
||||
"Arrange unassigned work — decomposition retained".into()
|
||||
}
|
||||
Destination::OutsidePerformers => format!(
|
||||
"Remove assignments from {changed} of {total} leaf {noun} — decomposition retained"
|
||||
),
|
||||
Destination::LayoutOnly => unreachable!(),
|
||||
};
|
||||
Ok(SemanticPlan {
|
||||
scope: scope.clone(),
|
||||
destination,
|
||||
candidate,
|
||||
index,
|
||||
commands: edits.commands,
|
||||
changed: edits.changed,
|
||||
expanded_ids,
|
||||
label,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
/// Translate the entire captured Q once, then evaluate the combined candidate.
|
||||
/// This path does not clone/validate a Project or rebuild semantic indexes.
|
||||
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 scope = &plan.scope;
|
||||
let geometry::Translation {
|
||||
mut diagram,
|
||||
mut commands,
|
||||
delta,
|
||||
} = geometry::translate(
|
||||
scope.project(),
|
||||
scope.diagram(),
|
||||
&plan.candidate.diagrams[&scope.0.diagram],
|
||||
scope.affected(),
|
||||
scope.anchor(),
|
||||
requested,
|
||||
)?;
|
||||
let mut unfolded = None;
|
||||
if let Destination::Performer(performer) = plan.destination {
|
||||
let target = presentation.target.ok_or_else(|| {
|
||||
Refusal::LayoutRequired("A visible accepted performer target is required.".into())
|
||||
})?;
|
||||
if !scope
|
||||
.0
|
||||
.before_visible
|
||||
.nodes
|
||||
.iter()
|
||||
.any(|node| node.id == target.placement && node.element == performer)
|
||||
{
|
||||
return Err(Refusal::LayoutRequired(
|
||||
"Make room or adjust the view, then drag again.".into(),
|
||||
));
|
||||
}
|
||||
let target_node = diagram
|
||||
.nodes
|
||||
.get_mut(&target.placement)
|
||||
.ok_or(Refusal::StaleScope)?;
|
||||
if target_node.element != performer {
|
||||
return Err(Refusal::StaleScope);
|
||||
}
|
||||
if !plan.changed.is_empty() && target_node.collapsed {
|
||||
target_node.collapsed = false;
|
||||
unfolded = Some(target_node.id);
|
||||
commands.push(Command::EditNode {
|
||||
diagram: diagram.id,
|
||||
original: target_node.id,
|
||||
node: target_node.clone(),
|
||||
});
|
||||
}
|
||||
} else if presentation.target.is_some() {
|
||||
return Err(Refusal::Ineligible(
|
||||
"An outside destination has no performer target.".into(),
|
||||
));
|
||||
}
|
||||
let view = projection::project_diagram_with_index(&plan.candidate, &diagram, &plan.index);
|
||||
let expanded =
|
||||
geometry::expanded_view(&plan.candidate, &diagram, &plan.index, &plan.expanded_ids);
|
||||
if scope
|
||||
.0
|
||||
.roots
|
||||
.iter()
|
||||
.any(|root| root.work_records.len() > 1 && !coherent(root, &expanded))
|
||||
{
|
||||
return Err(Refusal::MixedLayoutRequired);
|
||||
}
|
||||
geometry::check_scenes(
|
||||
&scope.0.before_visible,
|
||||
&scope.0.before_expanded,
|
||||
&view,
|
||||
&expanded,
|
||||
)?;
|
||||
geometry::check_rigid(&scope.0.before_expanded, &expanded, scope.affected(), delta)?;
|
||||
geometry::check_headers(&view, scope.selected(), presentation.viewport)?;
|
||||
Ok(PlacementPlan {
|
||||
diagram,
|
||||
view,
|
||||
delta,
|
||||
unfolded,
|
||||
requested,
|
||||
presentation,
|
||||
commands,
|
||||
})
|
||||
}
|
||||
|
||||
/// Recheck immutable facts and recompute geometry before one final source batch.
|
||||
/// Zero delta remains a transaction when assignment semantics changed.
|
||||
pub fn finish(
|
||||
plan: &SemanticPlan,
|
||||
live: &Project,
|
||||
placement: &PlacementPlan,
|
||||
) -> Result<Option<Command>, Refusal> {
|
||||
if live != plan.scope.project() {
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
use super::*;
|
||||
|
||||
struct Composite {
|
||||
f: Fixture,
|
||||
child: Id,
|
||||
child_node: Id,
|
||||
unplaced: Id,
|
||||
}
|
||||
|
||||
fn composite(layer: Layer) -> Composite {
|
||||
let mut f = fixture(layer);
|
||||
let kind = f.p.elements[&f.w].kind();
|
||||
let child =
|
||||
f.p.add_element(kind, layer, "Placed child", Some(f.w))
|
||||
.unwrap();
|
||||
let unplaced =
|
||||
f.p.add_element(kind, layer, "Unplaced leaf", Some(f.w))
|
||||
.unwrap();
|
||||
let child_node = f.p.place(f.d, child, xy(140., 600.));
|
||||
validate_candidate(&f.p).unwrap();
|
||||
Composite {
|
||||
f,
|
||||
child,
|
||||
child_node,
|
||||
unplaced,
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_allocation(id: Id, alias: &str, name: &str, performer: Id, work: Id) -> Relation {
|
||||
Relation {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
body: RelationBody::Allocation {
|
||||
source: performer,
|
||||
target: work,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_checks_original_identity_and_visibility_before_normalization() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let c = composite(layer);
|
||||
let valid = BTreeMap::from([(c.f.n, c.f.w), (c.child_node, c.child)]);
|
||||
let admitted = assignment::capture(&c.f.p, c.f.d, &valid, c.f.n).unwrap();
|
||||
assert_eq!(admitted.selected(), &valid);
|
||||
let foreign = c.f.p.diagrams[&c.f.second]
|
||||
.nodes
|
||||
.values()
|
||||
.find(|node| node.element == c.f.w)
|
||||
.unwrap()
|
||||
.id;
|
||||
// Each extra member is semantically covered by the valid selected parent.
|
||||
// Normalizing first would incorrectly hide its invalid original identity.
|
||||
for invalid in [
|
||||
BTreeMap::from([(c.f.n, c.f.w), (c.child_node, c.unplaced)]),
|
||||
BTreeMap::from([(c.f.n, c.f.w), (Id::new_v4(), c.child)]),
|
||||
BTreeMap::from([(c.f.n, c.f.w), (foreign, c.f.w)]),
|
||||
] {
|
||||
assert!(matches!(
|
||||
assignment::capture(&c.f.p, c.f.d, &invalid, c.f.n),
|
||||
Err(Refusal::StaleScope)
|
||||
));
|
||||
}
|
||||
let mut folded = c.f.p.clone();
|
||||
folded
|
||||
.diagrams
|
||||
.get_mut(&c.f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&c.f.n)
|
||||
.unwrap()
|
||||
.collapsed = true;
|
||||
validate_candidate(&folded).unwrap();
|
||||
assert!(
|
||||
!projection::project_view(&folded, c.f.d)
|
||||
.nodes
|
||||
.iter()
|
||||
.any(|node| node.id == c.child_node)
|
||||
);
|
||||
// Hidden descendants remain in Q when only the visible parent is selected.
|
||||
let parent_only =
|
||||
assignment::capture(&folded, c.f.d, &BTreeMap::from([(c.f.n, c.f.w)]), c.f.n).unwrap();
|
||||
assert!(parent_only.affected().contains_key(&c.child_node));
|
||||
assert!(matches!(
|
||||
assignment::capture(&folded, c.f.d, &valid, c.f.n),
|
||||
Err(Refusal::StaleScope)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_normalizes_parent_child_and_assigns_unplaced_leaf_once() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let c = composite(layer);
|
||||
let selected = BTreeMap::from([(c.f.n, c.f.w), (c.child_node, c.child)]);
|
||||
let scope = assignment::capture(&c.f.p, c.f.d, &selected, c.f.n).unwrap();
|
||||
assert_eq!(scope.selected(), &selected);
|
||||
assert_eq!(
|
||||
scope.affected().keys().copied().collect::<BTreeSet<_>>(),
|
||||
BTreeSet::from([c.f.n, c.child_node])
|
||||
);
|
||||
assert_eq!(
|
||||
scope.leaves().keys().copied().collect::<BTreeSet<_>>(),
|
||||
BTreeSet::from([c.child, c.unplaced])
|
||||
);
|
||||
let child_allocation = Id::new_v4();
|
||||
let unplaced_allocation = Id::new_v4();
|
||||
let ids = BTreeMap::from([
|
||||
(c.child, child_allocation),
|
||||
(c.unplaced, unplaced_allocation),
|
||||
]);
|
||||
let plan = assignment::plan_semantics(&scope, Destination::Performer(c.f.a), &ids).unwrap();
|
||||
assert_eq!(plan.changed_count(), 2);
|
||||
let mut expected = c.f.p.clone();
|
||||
expected.relations.insert(
|
||||
child_allocation,
|
||||
expected_allocation(
|
||||
child_allocation,
|
||||
"a_performs_placed_child",
|
||||
"A performs Placed child",
|
||||
c.f.a,
|
||||
c.child,
|
||||
),
|
||||
);
|
||||
expected.relations.insert(
|
||||
unplaced_allocation,
|
||||
expected_allocation(
|
||||
unplaced_allocation,
|
||||
"a_performs_unplaced_leaf",
|
||||
"A performs Unplaced leaf",
|
||||
c.f.a,
|
||||
c.unplaced,
|
||||
),
|
||||
);
|
||||
assert_eq!(plan.project(), &expected);
|
||||
let placed = assignment::place(
|
||||
&plan,
|
||||
xy(140., 200.),
|
||||
presentation(&c.f.p, c.f.d, Some(c.f.a)),
|
||||
)
|
||||
.unwrap();
|
||||
let mut clipped = presentation(&c.f.p, c.f.d, Some(c.f.a));
|
||||
clipped.viewport.size.height = 450.; // bottom350: parent header fits; selected child ends362.
|
||||
for (id, should_fit) in [(c.f.n, true), (c.child_node, false)] {
|
||||
let node = placed.view.nodes.iter().find(|node| node.id == id).unwrap();
|
||||
let header = Rect {
|
||||
position: node.position,
|
||||
size: Size {
|
||||
width: node.size.width,
|
||||
height: 62.,
|
||||
},
|
||||
};
|
||||
assert_eq!(clipped.viewport.contains(header), should_fit);
|
||||
}
|
||||
assert!(
|
||||
matches!(
|
||||
assignment::place(&plan, xy(140., 200.), clipped),
|
||||
Err(Refusal::LayoutRequired(_))
|
||||
),
|
||||
"normalized-away selected child still requires its header"
|
||||
);
|
||||
let d = expected.diagrams.get_mut(&c.f.d).unwrap();
|
||||
d.nodes.get_mut(&c.f.n).unwrap().position = xy(140., 200.);
|
||||
d.nodes.get_mut(&c.child_node).unwrap().position = xy(180., 300.);
|
||||
assert_eq!(placed.delta, xy(40., -300.));
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&c.f.p,
|
||||
assignment::finish(&plan, &c.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
expected.diagrams[&c.f.d].nodes.len(),
|
||||
c.f.p.diagrams[&c.f.d].nodes.len()
|
||||
);
|
||||
assert!(
|
||||
!expected.diagrams[&c.f.d]
|
||||
.nodes
|
||||
.values()
|
||||
.any(|node| node.element == c.unplaced)
|
||||
);
|
||||
assert!(
|
||||
!expected
|
||||
.relations
|
||||
.values()
|
||||
.any(|relation| relation.kind() == RelationKind::Allocation
|
||||
&& relation.target() == c.f.w)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_distributed_parent_refuses_but_its_independent_leaves_can_reassign() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut c = composite(layer);
|
||||
let second_node = c.f.p.place(c.f.d, c.unplaced, xy(940., 200.));
|
||||
let performer =
|
||||
c.f.p
|
||||
.add_element(
|
||||
if layer == Layer::Oa {
|
||||
Kind::Actor
|
||||
} else {
|
||||
Kind::SystemActor
|
||||
},
|
||||
layer,
|
||||
"C",
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
c.f.p.place(c.f.d, performer, xy(1700., 100.));
|
||||
let d = c.f.p.diagrams.get_mut(&c.f.d).unwrap();
|
||||
d.nodes.get_mut(&c.f.n).unwrap().position = xy(1700., 800.);
|
||||
d.nodes.get_mut(&c.child_node).unwrap().position = xy(140., 200.);
|
||||
let ax =
|
||||
c.f.p
|
||||
.relate(RelationKind::Allocation, "A child", c.f.a, c.child);
|
||||
let by =
|
||||
c.f.p
|
||||
.relate(RelationKind::Allocation, "B child", c.f.b, c.unplaced);
|
||||
validate_candidate(&c.f.p).unwrap();
|
||||
let visible = projection::project_view(&c.f.p, c.f.d);
|
||||
for id in [c.f.n, c.child_node, second_node] {
|
||||
assert!(visible.nodes.iter().any(|node| node.id == id));
|
||||
}
|
||||
assert_eq!(scope(&c.f).uniform, Uniform::MixedOrUnresolved);
|
||||
assert!(matches!(
|
||||
assignment::capture(&c.f.p, c.f.d, &BTreeMap::from([(c.f.n, c.f.w)]), c.f.n,),
|
||||
Err(Refusal::MixedLayoutRequired)
|
||||
));
|
||||
let selected = BTreeMap::from([(c.child_node, c.child), (second_node, c.unplaced)]);
|
||||
let captured = assignment::capture(&c.f.p, c.f.d, &selected, c.child_node).unwrap();
|
||||
let plan = assignment::plan_semantics(
|
||||
&captured,
|
||||
Destination::Performer(performer),
|
||||
&BTreeMap::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut expected = c.f.p.clone();
|
||||
expected.relations.get_mut(&ax).unwrap().body = RelationBody::Allocation {
|
||||
source: performer,
|
||||
target: c.child,
|
||||
};
|
||||
expected.relations.get_mut(&by).unwrap().body = RelationBody::Allocation {
|
||||
source: performer,
|
||||
target: c.unplaced,
|
||||
};
|
||||
assert_eq!(plan.project(), &expected);
|
||||
// One delta moves both leaves. The unselected semantic parent remains
|
||||
// authored at (1700,800), while its derived enclosure may change.
|
||||
let placed = assignment::place(
|
||||
&plan,
|
||||
xy(1740., 120.),
|
||||
presentation(&c.f.p, c.f.d, Some(performer)),
|
||||
)
|
||||
.unwrap();
|
||||
let d = expected.diagrams.get_mut(&c.f.d).unwrap();
|
||||
d.nodes.get_mut(&c.child_node).unwrap().position = xy(1740., 120.);
|
||||
d.nodes.get_mut(&second_node).unwrap().position = xy(2540., 120.);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&c.f.p,
|
||||
assignment::finish(&plan, &c.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn separate_unassigned(layer: Layer) -> (Fixture, Id, Id) {
|
||||
let mut f = fixture(layer);
|
||||
let companion =
|
||||
f.p.add_element(f.p.elements[&f.w].kind(), layer, "Companion", None)
|
||||
.unwrap();
|
||||
let companion_node = f.p.place(f.d, companion, xy(100., 1000.));
|
||||
validate_candidate(&f.p).unwrap();
|
||||
(f, companion, companion_node)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_finish_rejects_stale_project_and_each_tampered_result() {
|
||||
let (f, companion, companion_node) = separate_unassigned(Layer::Oa);
|
||||
let selected = BTreeMap::from([(f.n, f.w), (companion_node, companion)]);
|
||||
let captured = assignment::capture(&f.p, f.d, &selected, f.n).unwrap();
|
||||
let plan =
|
||||
assignment::plan_semantics(&captured, Destination::OutsidePerformers, &BTreeMap::new())
|
||||
.unwrap();
|
||||
let context = presentation(&f.p, f.d, None);
|
||||
let valid = assignment::place(&plan, xy(500., 500.), context).unwrap();
|
||||
let mut expected = f.p.clone();
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&f.n)
|
||||
.unwrap()
|
||||
.position = xy(500., 500.);
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&companion_node)
|
||||
.unwrap()
|
||||
.position = xy(500., 1000.);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&f.p,
|
||||
assignment::finish(&plan, &f.p, &valid).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
let mut stale = f.p.clone();
|
||||
stale.elements.get_mut(&f.b).unwrap().description = "Changed unrelated accepted record".into();
|
||||
validate_candidate(&stale).unwrap();
|
||||
assert!(matches!(
|
||||
assignment::finish(&plan, &stale, &valid),
|
||||
Err(Refusal::StaleScope)
|
||||
));
|
||||
for field in 0..6 {
|
||||
let mut altered = assignment::place(&plan, xy(500., 500.), context).unwrap();
|
||||
match field {
|
||||
0 => altered.diagram.nodes.get_mut(&f.n).unwrap().position.x += 20.,
|
||||
1 => {
|
||||
altered
|
||||
.view
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|node| node.id == f.n)
|
||||
.unwrap()
|
||||
.position
|
||||
.x += 20.
|
||||
}
|
||||
2 => altered.delta.x += 20.,
|
||||
3 => altered.unfolded = Some(f.n),
|
||||
4 => altered.commands.clear(),
|
||||
5 => altered.requested.x += 10.,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert!(
|
||||
matches!(
|
||||
assignment::finish(&plan, &f.p, &altered),
|
||||
Err(Refusal::StaleScope)
|
||||
),
|
||||
"tampered result field {field}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_requires_non_anchor_selected_header_inside_viewport() {
|
||||
let (f, companion, companion_node) = separate_unassigned(Layer::Oa);
|
||||
let captured = assignment::capture(
|
||||
&f.p,
|
||||
f.d,
|
||||
&BTreeMap::from([(f.n, f.w), (companion_node, companion)]),
|
||||
f.n,
|
||||
)
|
||||
.unwrap();
|
||||
let plan =
|
||||
assignment::plan_semantics(&captured, Destination::OutsidePerformers, &BTreeMap::new())
|
||||
.unwrap();
|
||||
let wide = presentation(&f.p, f.d, None);
|
||||
let placed = assignment::place(&plan, xy(500., 500.), wide).unwrap();
|
||||
let mut narrow = wide;
|
||||
narrow.viewport.size.height = 800.; // world bottom700: anchor header fits, companion does not.
|
||||
let header = |id| {
|
||||
let node = placed.view.nodes.iter().find(|node| node.id == id).unwrap();
|
||||
Rect {
|
||||
position: node.position,
|
||||
size: Size {
|
||||
width: node.size.width,
|
||||
height: 62.,
|
||||
},
|
||||
}
|
||||
};
|
||||
assert!(narrow.viewport.contains(header(f.n)));
|
||||
assert!(!narrow.viewport.contains(header(companion_node)));
|
||||
// Only the viewport differs from the already admitted identical geometry.
|
||||
assert!(matches!(
|
||||
assignment::place(&plan, xy(500., 500.), narrow),
|
||||
Err(Refusal::LayoutRequired(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_unresolved_oa_role_leaf_accepts_explicit_target_but_not_outside() {
|
||||
for ambiguous in [false, true] {
|
||||
let (mut f, companion, companion_node) = separate_unassigned(Layer::Oa);
|
||||
let (role_id, role_assignment) = role(&mut f, None);
|
||||
if ambiguous {
|
||||
f.p.relate(
|
||||
RelationKind::RoleRealization,
|
||||
"A realizes responsibility",
|
||||
f.a,
|
||||
role_id,
|
||||
);
|
||||
f.p.relate(
|
||||
RelationKind::RoleRealization,
|
||||
"B realizes responsibility",
|
||||
f.b,
|
||||
role_id,
|
||||
);
|
||||
}
|
||||
validate_candidate(&f.p).unwrap();
|
||||
assert_eq!(validation::effective_performer(&f.p, f.w), None);
|
||||
let captured = assignment::capture(
|
||||
&f.p,
|
||||
f.d,
|
||||
&BTreeMap::from([(f.n, f.w), (companion_node, companion)]),
|
||||
f.n,
|
||||
)
|
||||
.unwrap();
|
||||
let Refusal::RoleExitRequired {
|
||||
work,
|
||||
roles,
|
||||
performers,
|
||||
..
|
||||
} = assignment::plan_semantics(&captured, Destination::OutsidePerformers, &BTreeMap::new())
|
||||
.unwrap_err()
|
||||
else {
|
||||
panic!("unresolved role must produce its specific outward refusal");
|
||||
};
|
||||
assert_eq!(work, f.w);
|
||||
assert_eq!(roles, vec![role_id]);
|
||||
assert_eq!(
|
||||
performers.into_iter().collect::<BTreeSet<_>>(),
|
||||
if ambiguous {
|
||||
BTreeSet::from([f.a, f.b])
|
||||
} else {
|
||||
BTreeSet::new()
|
||||
}
|
||||
);
|
||||
let work_allocation = Id::new_v4();
|
||||
let companion_allocation = Id::new_v4();
|
||||
let ids = BTreeMap::from([(f.w, work_allocation), (companion, companion_allocation)]);
|
||||
let plan =
|
||||
assignment::plan_semantics(&captured, Destination::Performer(f.b), &ids).unwrap();
|
||||
assert_eq!(plan.changed_count(), 2);
|
||||
assert!(plan.label().contains("role responsibility retained"));
|
||||
let mut expected = f.p.clone();
|
||||
expected.relations.insert(
|
||||
work_allocation,
|
||||
expected_allocation(
|
||||
work_allocation,
|
||||
"b_performs_work",
|
||||
"B performs Work",
|
||||
f.b,
|
||||
f.w,
|
||||
),
|
||||
);
|
||||
expected.relations.insert(
|
||||
companion_allocation,
|
||||
expected_allocation(
|
||||
companion_allocation,
|
||||
"b_performs_companion",
|
||||
"B performs Companion",
|
||||
f.b,
|
||||
companion,
|
||||
),
|
||||
);
|
||||
assert_eq!(plan.project(), &expected);
|
||||
assert_eq!(
|
||||
plan.project().relations[&role_assignment],
|
||||
f.p.relations[&role_assignment]
|
||||
);
|
||||
let placed =
|
||||
assignment::place(&plan, xy(940., 200.), presentation(&f.p, f.d, Some(f.b))).unwrap();
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&f.n)
|
||||
.unwrap()
|
||||
.position = xy(940., 200.);
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&companion_node)
|
||||
.unwrap()
|
||||
.position = xy(940., 700.);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&f.p,
|
||||
assignment::finish(&plan, &f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
use super::*;
|
||||
|
||||
struct Roots {
|
||||
f: Fixture,
|
||||
c: Id,
|
||||
cn: Id,
|
||||
y: Id,
|
||||
yn: Id,
|
||||
z: Id,
|
||||
zn: Id,
|
||||
ax: Id,
|
||||
by: Id,
|
||||
}
|
||||
|
||||
fn roots(layer: Layer) -> Roots {
|
||||
let mut f = fixture(layer);
|
||||
let kind = f.p.elements[&f.w].kind();
|
||||
let c =
|
||||
f.p.add_element(
|
||||
if layer == Layer::Oa {
|
||||
Kind::Actor
|
||||
} else {
|
||||
Kind::SystemActor
|
||||
},
|
||||
layer,
|
||||
"C",
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let y = f.p.add_element(kind, layer, "Y", None).unwrap();
|
||||
let z = f.p.add_element(kind, layer, "Z", None).unwrap();
|
||||
let cn = f.p.place(f.d, c, xy(1500., 100.));
|
||||
let yn = f.p.place(f.d, y, xy(140., 800.));
|
||||
let zn = f.p.place(f.d, z, xy(1540., 1400.));
|
||||
let d = f.p.diagrams.get_mut(&f.d).unwrap();
|
||||
d.nodes.get_mut(&f.n).unwrap().position = xy(140., 200.);
|
||||
d.nodes
|
||||
.values_mut()
|
||||
.find(|n| n.element == f.b)
|
||||
.unwrap()
|
||||
.position = xy(100., 700.);
|
||||
let ax = f.p.relate(
|
||||
RelationKind::Allocation,
|
||||
"Original X responsibility",
|
||||
f.a,
|
||||
f.w,
|
||||
);
|
||||
let by = f.p.relate(
|
||||
RelationKind::Allocation,
|
||||
"Original Y responsibility",
|
||||
f.b,
|
||||
y,
|
||||
);
|
||||
f.p.relations.get_mut(&ax).unwrap().description = "Reviewed X identity must survive".into();
|
||||
f.p.relations.get_mut(&by).unwrap().description = "Reviewed Y identity must survive".into();
|
||||
if layer == Layer::Oa {
|
||||
let r =
|
||||
f.p.add_element(Kind::Role, layer, "Responsibility", None)
|
||||
.unwrap();
|
||||
f.p.relate(RelationKind::RoleAssignment, "Z role", r, z);
|
||||
f.p.relate(RelationKind::RoleRealization, "C role", c, r);
|
||||
} else {
|
||||
f.p.relate(RelationKind::Allocation, "Z already assigned", c, z);
|
||||
}
|
||||
validate_candidate(&f.p).unwrap();
|
||||
Roots {
|
||||
f,
|
||||
c,
|
||||
cn,
|
||||
y,
|
||||
yn,
|
||||
z,
|
||||
zn,
|
||||
ax,
|
||||
by,
|
||||
}
|
||||
}
|
||||
|
||||
fn wide(p: &Project, d: Id, target: Option<Id>) -> PresentationContext {
|
||||
let mut context = presentation(p, d, target);
|
||||
context.viewport.size = Size {
|
||||
width: 5000.,
|
||||
height: 3000.,
|
||||
};
|
||||
context
|
||||
}
|
||||
|
||||
fn selected(r: &Roots, with_z: bool) -> BTreeMap<Id, Id> {
|
||||
let mut ids = BTreeMap::from([(r.f.n, r.f.w), (r.yn, r.y)]);
|
||||
if with_z {
|
||||
ids.insert(r.zn, r.z);
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
fn retarget(p: &mut Project, relation: Id, target: Id) {
|
||||
let r = p.relations.get_mut(&relation).unwrap();
|
||||
r.body = RelationBody::Allocation {
|
||||
source: target,
|
||||
target: r.target(),
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_independent_performers_preserves_already_correct_provenance() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let r = roots(layer);
|
||||
let selected = selected(&r, true);
|
||||
let scope = assignment::capture(&r.f.p, r.f.d, &selected, r.f.n).unwrap();
|
||||
let plan =
|
||||
assignment::plan_semantics(&scope, Destination::Performer(r.c), &BTreeMap::new())
|
||||
.unwrap();
|
||||
assert_eq!(plan.changed_count(), 2);
|
||||
assert_eq!(plan.already_correct_count(), 1);
|
||||
let placed =
|
||||
assignment::place(&plan, xy(1540., 200.), wide(&r.f.p, r.f.d, Some(r.c))).unwrap();
|
||||
let mut expected = r.f.p.clone();
|
||||
retarget(&mut expected, r.ax, r.c);
|
||||
retarget(&mut expected, r.by, r.c);
|
||||
let d = expected.diagrams.get_mut(&r.f.d).unwrap();
|
||||
d.nodes.get_mut(&r.f.n).unwrap().position = xy(1540., 200.);
|
||||
d.nodes.get_mut(&r.yn).unwrap().position = xy(1540., 800.);
|
||||
d.nodes.get_mut(&r.zn).unwrap().position = xy(2940., 1400.);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&r.f.p,
|
||||
assignment::finish(&plan, &r.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
if layer == Layer::Oa {
|
||||
assert!(
|
||||
!plan
|
||||
.project()
|
||||
.relations
|
||||
.values()
|
||||
.any(|relation| relation.kind() == RelationKind::Allocation
|
||||
&& relation.target() == r.z)
|
||||
);
|
||||
assert!(matches!(
|
||||
assignment::plan_semantics(
|
||||
&scope,
|
||||
Destination::OutsidePerformers,
|
||||
&BTreeMap::new()
|
||||
),
|
||||
Err(Refusal::RoleExitRequired { .. })
|
||||
));
|
||||
}
|
||||
assert!(
|
||||
assignment::plan_semantics(&scope, Destination::LayoutOnly, &BTreeMap::new()).is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_zero_delta_changes_semantics_once_and_then_is_noop() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut f = fixture(layer);
|
||||
let d = f.p.diagrams.get_mut(&f.d).unwrap();
|
||||
d.nodes
|
||||
.values_mut()
|
||||
.find(|n| n.element == f.a)
|
||||
.unwrap()
|
||||
.size = Size {
|
||||
width: 600.,
|
||||
height: 400.,
|
||||
};
|
||||
d.nodes.get_mut(&f.n).unwrap().position = xy(140., 200.);
|
||||
let scope = assignment::capture(&f.p, f.d, &BTreeMap::from([(f.n, f.w)]), f.n).unwrap();
|
||||
let id = Id::new_v4();
|
||||
let plan = assignment::plan_semantics(
|
||||
&scope,
|
||||
Destination::Performer(f.a),
|
||||
&BTreeMap::from([(f.w, id)]),
|
||||
)
|
||||
.unwrap();
|
||||
let placed = assignment::place(&plan, xy(140., 200.), wide(&f.p, f.d, Some(f.a))).unwrap();
|
||||
assert_eq!(placed.delta, xy(0., 0.));
|
||||
let mut expected = f.p.clone();
|
||||
expected.relations.insert(
|
||||
id,
|
||||
Relation {
|
||||
id,
|
||||
alias: "a_performs_work".into(),
|
||||
name: "A performs Work".into(),
|
||||
description: String::new(),
|
||||
body: RelationBody::Allocation {
|
||||
source: f.a,
|
||||
target: f.w,
|
||||
},
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&f.p,
|
||||
assignment::finish(&plan, &f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
let scope =
|
||||
assignment::capture(&expected, f.d, &BTreeMap::from([(f.n, f.w)]), f.n).unwrap();
|
||||
let noop =
|
||||
assignment::plan_semantics(&scope, Destination::Performer(f.a), &BTreeMap::new())
|
||||
.unwrap();
|
||||
let placed =
|
||||
assignment::place(&noop, xy(140., 200.), wide(&expected, f.d, Some(f.a))).unwrap();
|
||||
assert!(
|
||||
assignment::finish(&noop, &expected, &placed)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_unfolds_only_changed_destination_and_refuses_newly_exposed_overlap() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
for obstacle in [false, true] {
|
||||
let mut r = roots(layer);
|
||||
let d = r.f.p.diagrams.get_mut(&r.f.d).unwrap();
|
||||
d.nodes
|
||||
.values_mut()
|
||||
.find(|n| n.element == r.f.b)
|
||||
.unwrap()
|
||||
.position = xy(100., 400.);
|
||||
d.nodes.get_mut(&r.yn).unwrap().position = xy(140., 500.);
|
||||
d.nodes.get_mut(&r.zn).unwrap().position = xy(1540., 800.);
|
||||
d.nodes.get_mut(&r.cn).unwrap().collapsed = true;
|
||||
if obstacle {
|
||||
let k =
|
||||
r.f.p
|
||||
.add_element(r.f.p.elements[&r.f.w].kind(), layer, "Hidden overlap", None)
|
||||
.unwrap();
|
||||
r.f.p
|
||||
.relate(RelationKind::Allocation, "C also owns K", r.c, k);
|
||||
r.f.p.place(r.f.d, k, xy(1540., 800.));
|
||||
}
|
||||
assert!(
|
||||
!projection::project_view(&r.f.p, r.f.d)
|
||||
.nodes
|
||||
.iter()
|
||||
.any(|n| n.id == r.zn)
|
||||
);
|
||||
assert!(
|
||||
assignment::capture(&r.f.p, r.f.d, &selected(&r, true), r.f.n).is_err(),
|
||||
"hidden selected member is not normalized away"
|
||||
);
|
||||
let scope = assignment::capture(&r.f.p, r.f.d, &selected(&r, false), r.f.n).unwrap();
|
||||
let plan =
|
||||
assignment::plan_semantics(&scope, Destination::Performer(r.c), &BTreeMap::new())
|
||||
.unwrap();
|
||||
let placed = assignment::place(&plan, xy(1540., 120.), wide(&r.f.p, r.f.d, Some(r.c)));
|
||||
if obstacle {
|
||||
assert!(matches!(placed, Err(Refusal::LayoutRequired(_))));
|
||||
continue;
|
||||
}
|
||||
let placed = placed.unwrap();
|
||||
assert_eq!(placed.unfolded, Some(r.cn));
|
||||
let mut expected = r.f.p.clone();
|
||||
retarget(&mut expected, r.ax, r.c);
|
||||
retarget(&mut expected, r.by, r.c);
|
||||
let d = expected.diagrams.get_mut(&r.f.d).unwrap();
|
||||
d.nodes.get_mut(&r.cn).unwrap().collapsed = false;
|
||||
d.nodes.get_mut(&r.f.n).unwrap().position = xy(1540., 120.);
|
||||
d.nodes.get_mut(&r.yn).unwrap().position = xy(1540., 420.);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&r.f.p,
|
||||
assignment::finish(&plan, &r.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_accumulates_stable_ids_and_aliases_without_partial_reuse() {
|
||||
let mut f = fixture(Layer::Oa);
|
||||
let y =
|
||||
f.p.add_element(Kind::Activity, Layer::Oa, "Work", None)
|
||||
.unwrap();
|
||||
let yn = f.p.place(f.d, y, xy(400., 500.));
|
||||
let selected = BTreeMap::from([(f.n, f.w), (yn, y)]);
|
||||
let scope = assignment::capture(&f.p, f.d, &selected, f.n).unwrap();
|
||||
let ids = BTreeMap::from([(f.w, Id::new_v4()), (y, Id::new_v4())]);
|
||||
let first = assignment::plan_semantics(&scope, Destination::Performer(f.a), &ids).unwrap();
|
||||
let other = assignment::plan_semantics(&scope, Destination::Performer(f.b), &ids).unwrap();
|
||||
let repeated = assignment::plan_semantics(&scope, Destination::Performer(f.a), &ids).unwrap();
|
||||
assert_eq!(first.project(), repeated.project());
|
||||
assert_eq!(first.changed_count(), 2);
|
||||
let mut expected = f.p.clone();
|
||||
let aliases: BTreeSet<_> = ids
|
||||
.values()
|
||||
.map(|id| first.project().relations[id].alias.clone())
|
||||
.collect();
|
||||
assert_eq!(aliases.len(), 2);
|
||||
assert!(aliases.contains("a_performs_work"));
|
||||
for (ordinal, (work, id)) in ids.iter().enumerate() {
|
||||
let relation = &first.project().relations[id];
|
||||
let expected_relation = Relation {
|
||||
id: *id,
|
||||
alias: if ordinal == 0 {
|
||||
"a_performs_work".into()
|
||||
} else {
|
||||
format!("a_performs_work_{}", &id.simple().to_string()[..8])
|
||||
},
|
||||
name: "A performs Work".into(),
|
||||
description: String::new(),
|
||||
body: RelationBody::Allocation {
|
||||
source: f.a,
|
||||
target: *work,
|
||||
},
|
||||
};
|
||||
assert_eq!(relation, &expected_relation);
|
||||
assert_eq!(
|
||||
other.project().relations[id].body,
|
||||
RelationBody::Allocation {
|
||||
source: f.b,
|
||||
target: *work
|
||||
}
|
||||
);
|
||||
expected.relations.insert(*id, expected_relation);
|
||||
}
|
||||
assert_eq!(first.project(), &expected);
|
||||
let duplicate = Id::new_v4();
|
||||
for bad in [
|
||||
BTreeMap::from([(f.w, duplicate), (y, duplicate)]),
|
||||
BTreeMap::from([(f.w, Id::nil()), (y, ids[&y])]),
|
||||
BTreeMap::from([(f.w, f.a), (y, ids[&y])]),
|
||||
] {
|
||||
assert!(assignment::plan_semantics(&scope, Destination::Performer(f.a), &bad).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_source_failure_preserves_existing_history_and_retry_ids() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut f = fixture(layer);
|
||||
let y =
|
||||
f.p.add_element(f.p.elements[&f.w].kind(), layer, "Y", None)
|
||||
.unwrap();
|
||||
let yn = f.p.place(f.d, y, xy(400., 800.));
|
||||
let mut bundle = format_bundle(&f.p);
|
||||
bundle
|
||||
.files
|
||||
.get_mut(&bundle.entry.clone())
|
||||
.unwrap()
|
||||
.insert_str(
|
||||
0,
|
||||
"// Keep reviewed source through a refused group assignment.\n",
|
||||
);
|
||||
let mut limits = ProjectLimits::default();
|
||||
limits.model.max_source_bytes = bundle.files.values().map(String::len).sum::<usize>() + 128;
|
||||
let mut document = Document::from_bundle(bundle, limits).unwrap();
|
||||
document
|
||||
.execute(Command::Describe(f.w, "Reviewed".into()))
|
||||
.unwrap();
|
||||
document
|
||||
.execute(Command::Rename(y, "Future Y".into()))
|
||||
.unwrap();
|
||||
let redo_project = document.project().clone();
|
||||
let redo_source = document.bundle().clone();
|
||||
assert!(document.undo());
|
||||
assert!(document.can_undo() && document.can_redo());
|
||||
let accepted = document.project().clone();
|
||||
let source = document.bundle().clone();
|
||||
let revision = document.revision();
|
||||
let ids = BTreeMap::from([(f.w, Id::new_v4()), (y, Id::new_v4())]);
|
||||
let scope =
|
||||
assignment::capture(&accepted, f.d, &BTreeMap::from([(f.n, f.w), (yn, y)]), f.n)
|
||||
.unwrap();
|
||||
let plan = assignment::plan_semantics(&scope, Destination::Performer(f.a), &ids).unwrap();
|
||||
let placed =
|
||||
assignment::place(&plan, xy(150., 200.), wide(&accepted, f.d, Some(f.a))).unwrap();
|
||||
let command = assignment::finish(&plan, &accepted, &placed)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
document.execute(command.clone()),
|
||||
Err(crate::document::DocumentError::Source(_))
|
||||
));
|
||||
assert_eq!(document.project(), &accepted);
|
||||
assert_eq!(document.bundle(), &source);
|
||||
assert_eq!(document.revision(), revision);
|
||||
assert!(document.can_undo() && document.can_redo());
|
||||
assert!(document.redo());
|
||||
assert_eq!(document.project(), &redo_project);
|
||||
assert_eq!(document.bundle(), &redo_source);
|
||||
assert!(document.undo());
|
||||
assert_eq!(document.project(), &accepted);
|
||||
assert_eq!(document.bundle(), &source);
|
||||
let mut expected = accepted.clone();
|
||||
for (work, name, alias) in [
|
||||
(f.w, "A performs Work", "a_performs_work"),
|
||||
(y, "A performs Y", "a_performs_y"),
|
||||
] {
|
||||
expected.relations.insert(
|
||||
ids[&work],
|
||||
Relation {
|
||||
id: ids[&work],
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
body: RelationBody::Allocation {
|
||||
source: f.a,
|
||||
target: work,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
let d = expected.diagrams.get_mut(&f.d).unwrap();
|
||||
d.nodes.get_mut(&f.n).unwrap().position = xy(150., 200.);
|
||||
d.nodes.get_mut(&yn).unwrap().position = xy(450., 500.);
|
||||
assert_eq!(roundtrip(&accepted, command), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_collateral_surviving_constraint_refuses_whole_semantic_candidate() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut r = roots(layer);
|
||||
let k =
|
||||
r.f.p
|
||||
.add_element(Kind::Constraint, layer, "Keep reviewed assignment", None)
|
||||
.unwrap();
|
||||
*r.f.p.elements.get_mut(&k).unwrap().shared_mut().unwrap() = SharedBody::Constraint {
|
||||
expression: "reviewed assignment".into(),
|
||||
constrained: vec![r.ax, r.f.w],
|
||||
};
|
||||
let core = prepare_command(&r.f.p, &Command::Delete(r.ax))
|
||||
.unwrap()
|
||||
.project;
|
||||
validate_candidate(&core).unwrap();
|
||||
assert!(core.elements.contains_key(&k));
|
||||
assert_ne!(core.elements[&k], r.f.p.elements[&k]);
|
||||
let scope = assignment::capture(&r.f.p, r.f.d, &selected(&r, false), r.f.n).unwrap();
|
||||
let Err(Refusal::CollateralChangeRequired(changed)) =
|
||||
assignment::plan_semantics(&scope, Destination::OutsidePerformers, &BTreeMap::new())
|
||||
else {
|
||||
panic!("surviving constraint edit must refuse the entire plan");
|
||||
};
|
||||
assert!(changed.iter().any(|record| record.id == k));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_uses_vacated_space_and_one_complete_route_owner_map() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut f = fixture(layer);
|
||||
let kind = f.p.elements[&f.w].kind();
|
||||
let y = f.p.add_element(kind, layer, "Y", None).unwrap();
|
||||
let outside = f.p.add_element(kind, layer, "Outside", None).unwrap();
|
||||
let yn = f.p.place(f.d, y, xy(400., 500.));
|
||||
f.p.place(f.d, outside, xy(1600., 500.));
|
||||
let d = f.p.diagrams.get_mut(&f.d).unwrap();
|
||||
let a = d.nodes.values_mut().find(|n| n.element == f.a).unwrap();
|
||||
a.position = xy(350., 350.);
|
||||
a.size = Size {
|
||||
width: 1000.,
|
||||
height: 600.,
|
||||
};
|
||||
let edge_kind = if layer == Layer::Oa {
|
||||
RelationKind::Interaction
|
||||
} else {
|
||||
RelationKind::FunctionalExchange
|
||||
};
|
||||
let internal = f.p.relate(edge_kind, "Internal", f.w, y);
|
||||
let external = f.p.relate(edge_kind, "External", y, outside);
|
||||
let mut internal_route = route(internal);
|
||||
internal_route.waypoints = vec![xy(370., 550.), xy(370., 650.)];
|
||||
internal_route.source_attachment = Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Bottom,
|
||||
offset: 0.3,
|
||||
});
|
||||
internal_route.target_attachment = Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Top,
|
||||
offset: 0.7,
|
||||
});
|
||||
let mut external_route = internal_route.clone();
|
||||
external_route.edge = external;
|
||||
external_route.waypoints = vec![xy(1200., 550.), xy(1300., 650.)];
|
||||
for diagram in [f.d, f.second] {
|
||||
f.p.diagrams.get_mut(&diagram).unwrap().routes =
|
||||
vec![internal_route.clone(), external_route.clone()];
|
||||
}
|
||||
if let RelationBody::FunctionalExchange { source_port, .. } = f.p.relations[&internal].body
|
||||
{
|
||||
f.p.diagrams
|
||||
.get_mut(&f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&f.n)
|
||||
.unwrap()
|
||||
.port_anchors
|
||||
.push(PortAnchor {
|
||||
port: source_port,
|
||||
side: PortAnchorSide::Bottom,
|
||||
offset: 0.4,
|
||||
});
|
||||
}
|
||||
validate_candidate(&f.p).unwrap();
|
||||
let ids = BTreeMap::from([(f.w, Id::new_v4()), (y, Id::new_v4())]);
|
||||
// The singleton candidate really occupies stationary Y's card. The
|
||||
// combined candidate must not inherit that sequential-planning veto.
|
||||
let mut singleton = f.p.clone();
|
||||
singleton
|
||||
.diagrams
|
||||
.get_mut(&f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&f.n)
|
||||
.unwrap()
|
||||
.position = xy(400., 500.);
|
||||
let projected = projection::project_view(&singleton, f.d);
|
||||
let x_card = projected.nodes.iter().find(|n| n.id == f.n).unwrap();
|
||||
let y_card = projected.nodes.iter().find(|n| n.id == yn).unwrap();
|
||||
assert_eq!(
|
||||
overlap(x_card, y_card),
|
||||
if layer == Layer::Oa { 21056. } else { 29568. }
|
||||
);
|
||||
let single = assignment::capture(&f.p, f.d, &BTreeMap::from([(f.n, f.w)]), f.n).unwrap();
|
||||
let single =
|
||||
assignment::plan_semantics(&single, Destination::Performer(f.a), &ids).unwrap();
|
||||
assert!(matches!(
|
||||
assignment::place(&single, xy(400., 500.), wide(&f.p, f.d, Some(f.a))),
|
||||
Err(Refusal::LayoutRequired(_))
|
||||
));
|
||||
let scope =
|
||||
assignment::capture(&f.p, f.d, &BTreeMap::from([(f.n, f.w), (yn, y)]), f.n).unwrap();
|
||||
let plan = assignment::plan_semantics(&scope, Destination::Performer(f.a), &ids).unwrap();
|
||||
let placed = assignment::place(&plan, xy(400., 500.), wide(&f.p, f.d, Some(f.a))).unwrap();
|
||||
let mut expected = f.p.clone();
|
||||
for (work, name, alias) in [
|
||||
(f.w, "A performs Work", "a_performs_work"),
|
||||
(y, "A performs Y", "a_performs_y"),
|
||||
] {
|
||||
expected.relations.insert(
|
||||
ids[&work],
|
||||
Relation {
|
||||
id: ids[&work],
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
body: RelationBody::Allocation {
|
||||
source: f.a,
|
||||
target: work,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
let d = expected.diagrams.get_mut(&f.d).unwrap();
|
||||
d.nodes.get_mut(&f.n).unwrap().position = xy(400., 500.);
|
||||
d.nodes.get_mut(&yn).unwrap().position = xy(700., 500.);
|
||||
d.routes[0].waypoints = vec![xy(670., 550.), xy(670., 650.)];
|
||||
assert_eq!(placed.diagram.routes[1], external_route);
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&f.p,
|
||||
assignment::finish(&plan, &f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_deletes_only_own_routes_across_views_and_keeps_internal_flow() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut r = roots(layer);
|
||||
let kind = if layer == Layer::Oa {
|
||||
RelationKind::Interaction
|
||||
} else {
|
||||
RelationKind::FunctionalExchange
|
||||
};
|
||||
let internal = r.f.p.relate(kind, "Keep internal flow", r.f.w, r.y);
|
||||
for diagram in [r.f.d, r.f.second] {
|
||||
r.f.p.diagrams.get_mut(&diagram).unwrap().routes =
|
||||
vec![route(r.ax), route(internal), route(r.by)];
|
||||
}
|
||||
validate_candidate(&r.f.p).unwrap();
|
||||
let scope = assignment::capture(&r.f.p, r.f.d, &selected(&r, false), r.f.n).unwrap();
|
||||
let plan =
|
||||
assignment::plan_semantics(&scope, Destination::OutsidePerformers, &BTreeMap::new())
|
||||
.unwrap();
|
||||
assert_eq!(plan.changed_count(), 2);
|
||||
let placed = assignment::place(&plan, xy(640., 200.), wide(&r.f.p, r.f.d, None)).unwrap();
|
||||
let mut expected = r.f.p.clone();
|
||||
expected.relations.remove(&r.ax);
|
||||
expected.relations.remove(&r.by);
|
||||
for diagram in [r.f.d, r.f.second] {
|
||||
expected.diagrams.get_mut(&diagram).unwrap().routes = vec![route(internal)];
|
||||
}
|
||||
let d = expected.diagrams.get_mut(&r.f.d).unwrap();
|
||||
d.nodes.get_mut(&r.f.n).unwrap().position = xy(640., 200.);
|
||||
d.nodes.get_mut(&r.yn).unwrap().position = xy(640., 800.);
|
||||
d.routes[0].waypoints = vec![xy(920., 400.), xy(920., 550.)];
|
||||
assert_eq!(
|
||||
roundtrip(
|
||||
&r.f.p,
|
||||
assignment::finish(&plan, &r.f.p, &placed).unwrap().unwrap()
|
||||
),
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Geometry operations over an explicitly captured placement set.
|
||||
use super::*;
|
||||
|
||||
pub(super) struct Translation {
|
||||
pub diagram: Diagram,
|
||||
pub commands: Vec<Command>,
|
||||
pub delta: Position,
|
||||
}
|
||||
|
||||
/// Translate exactly `placements` using one snapped anchor delta. `base` must
|
||||
/// come from an exact, validated semantic candidate; absent routes are permitted
|
||||
/// only because that candidate has already admitted their semantic deletion.
|
||||
pub(super) fn translate(
|
||||
accepted: &Project,
|
||||
original: &Diagram,
|
||||
base: &Diagram,
|
||||
placements: &BTreeMap<Id, NodePlacement>,
|
||||
anchor: Id,
|
||||
requested: Position,
|
||||
) -> Result<Translation, Refusal> {
|
||||
let anchor = placements.get(&anchor).ok_or(Refusal::StaleScope)?;
|
||||
let delta = Position {
|
||||
x: (requested.x / 10.).round() * 10. - anchor.position.x,
|
||||
y: (requested.y / 10.).round() * 10. - anchor.position.y,
|
||||
};
|
||||
let mut diagram = base.clone();
|
||||
let mut commands = Vec::new();
|
||||
let mut deltas = BTreeMap::new();
|
||||
for (id, captured) in placements {
|
||||
let node = diagram.nodes.get_mut(id).ok_or(Refusal::StaleScope)?;
|
||||
node.position = Position {
|
||||
x: captured.position.x + delta.x,
|
||||
y: captured.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 != captured {
|
||||
commands.push(Command::EditNode {
|
||||
diagram: diagram.id,
|
||||
original: *id,
|
||||
node: node.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
// Resolve actual endpoint owners once against accepted semantics and the
|
||||
// complete delta map. Never reinsert a semantically deleted saved route.
|
||||
for route in projection::translated_routes(accepted, original, &deltas) {
|
||||
if let Some(stored) = diagram.routes.iter_mut().find(|r| r.edge == route.edge) {
|
||||
if route.waypoints.iter().any(|point| {
|
||||
!point.x.is_finite()
|
||||
|| !point.y.is_finite()
|
||||
|| point.x.abs() > MAX_COORDINATE
|
||||
|| point.y.abs() > MAX_COORDINATE
|
||||
}) {
|
||||
return Err(Refusal::InvalidCandidate(
|
||||
"Moved route exceeds the model bounds.".into(),
|
||||
));
|
||||
}
|
||||
*stored = route.clone();
|
||||
commands.push(Command::SetEdgeRoute {
|
||||
diagram: diagram.id,
|
||||
route,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Translation {
|
||||
diagram,
|
||||
commands,
|
||||
delta,
|
||||
})
|
||||
}
|
||||
|
||||
/// Recover hidden ancestry for identity lookup only. The all-unfolded scene is
|
||||
/// never used for collision admission; only affected nodes and their ancestors
|
||||
/// enter the required diagnostic expansion.
|
||||
pub(super) fn expansion_ids(
|
||||
p: &Project,
|
||||
d: &Diagram,
|
||||
index: &ViewIndex,
|
||||
placements: &BTreeMap<Id, NodePlacement>,
|
||||
) -> Result<BTreeSet<Id>, Refusal> {
|
||||
let mut all_unfolded = d.clone();
|
||||
for node in all_unfolded.nodes.values_mut() {
|
||||
node.collapsed = false;
|
||||
}
|
||||
let all_view = projection::project_diagram_with_index(p, &all_unfolded, index);
|
||||
let ancestry = ancestors(&all_view);
|
||||
let mut ids: BTreeSet<_> = placements.keys().copied().collect();
|
||||
for id in placements.keys() {
|
||||
ids.extend(ancestry.get(id).ok_or(Refusal::StaleScope)?.iter().copied());
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub(super) fn expanded_view(
|
||||
p: &Project,
|
||||
d: &Diagram,
|
||||
index: &ViewIndex,
|
||||
ids: &BTreeSet<Id>,
|
||||
) -> ProjectedView {
|
||||
let mut expanded = d.clone();
|
||||
for id in ids {
|
||||
if let Some(node) = expanded.nodes.get_mut(id) {
|
||||
node.collapsed = false;
|
||||
}
|
||||
}
|
||||
projection::project_diagram_with_index(p, &expanded, index)
|
||||
}
|
||||
|
||||
pub(super) fn check_scenes(
|
||||
before_visible: &ProjectedView,
|
||||
before_expanded: &ProjectedView,
|
||||
visible: &ProjectedView,
|
||||
expanded: &ProjectedView,
|
||||
) -> Result<(), Refusal> {
|
||||
if visible.nodes.iter().chain(&expanded.nodes).any(|node| {
|
||||
!(Rect {
|
||||
position: node.position,
|
||||
size: node.size,
|
||||
})
|
||||
.valid()
|
||||
}) {
|
||||
return Err(Refusal::InvalidCandidate(
|
||||
"The projected enclosure exceeds the model bounds.".into(),
|
||||
));
|
||||
}
|
||||
if overlaps(before_visible, visible) || overlaps(before_expanded, expanded) {
|
||||
return Err(Refusal::LayoutRequired(
|
||||
"Make room before arranging: the candidate would introduce or enlarge overlapping cards."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn check_rigid(
|
||||
before: &ProjectedView,
|
||||
after: &ProjectedView,
|
||||
placements: &BTreeMap<Id, NodePlacement>,
|
||||
delta: Position,
|
||||
) -> Result<(), Refusal> {
|
||||
let before: BTreeMap<_, _> = before.nodes.iter().map(|n| (n.id, n)).collect();
|
||||
let after: BTreeMap<_, _> = after.nodes.iter().map(|n| (n.id, n)).collect();
|
||||
for id in placements.keys() {
|
||||
let old = before.get(id).ok_or(Refusal::StaleScope)?;
|
||||
let new = after.get(id).ok_or(Refusal::StaleScope)?;
|
||||
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 selection requires an explicit layout; its footprint cannot be translated unchanged."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn check_headers(
|
||||
view: &ProjectedView,
|
||||
selected: &BTreeMap<Id, Id>,
|
||||
viewport: Rect,
|
||||
) -> Result<(), Refusal> {
|
||||
for (id, element) in selected {
|
||||
let node = view
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|node| node.id == *id && node.element == *element)
|
||||
.ok_or_else(|| Refusal::LayoutRequired("A selected header would be hidden.".into()))?;
|
||||
let header = Rect {
|
||||
position: node.position,
|
||||
size: Size {
|
||||
width: node.size.width,
|
||||
height: node.size.height.min(62.),
|
||||
},
|
||||
};
|
||||
if !viewport.contains(header) {
|
||||
return Err(Refusal::LayoutRequired(
|
||||
"Make room or adjust the view, then drag again.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
//! Reviewed policy experiment using the production projection and translator.
|
||||
//! No production admission or atomic-refusal behavior is tested here.
|
||||
use super::*;
|
||||
|
||||
struct Mixed {
|
||||
f: Fixture,
|
||||
an: Id,
|
||||
xn: Id,
|
||||
yn: Id,
|
||||
internal: Id,
|
||||
include_performer: bool,
|
||||
}
|
||||
|
||||
fn mixed(layer: Layer, collapsed: bool, obstacle: bool, include_performer: bool) -> Mixed {
|
||||
let mut f = fixture(layer);
|
||||
let work = f.p.elements[&f.w].kind();
|
||||
let exchange = match layer {
|
||||
Layer::Oa => RelationKind::Interaction,
|
||||
Layer::Sa => RelationKind::FunctionalExchange,
|
||||
};
|
||||
let x = f.p.add_element(work, layer, "X", Some(f.w)).unwrap();
|
||||
let y = f.p.add_element(work, layer, "Y", Some(f.w)).unwrap();
|
||||
let outside = f.p.add_element(work, layer, "Outside", None).unwrap();
|
||||
let xn = f.p.place(f.d, x, xy(140., 200.));
|
||||
let yn = f.p.place(f.d, y, xy(940., 200.));
|
||||
f.p.place(f.d, outside, xy(1800., 800.));
|
||||
f.p.relate(RelationKind::Allocation, "A owns X", f.a, x);
|
||||
f.p.relate(RelationKind::Allocation, "B owns Y", f.b, y);
|
||||
// FunctionalExchange's actual builder creates valid function input/output
|
||||
// ports; do not manufacture Interaction records between SA Functions.
|
||||
let internal = f.p.relate(exchange, "X to Y", x, y);
|
||||
let external = f.p.relate(exchange, "Y to Outside", y, outside);
|
||||
let an = f.p.diagrams[&f.d]
|
||||
.nodes
|
||||
.values()
|
||||
.find(|n| n.element == f.a)
|
||||
.unwrap()
|
||||
.id;
|
||||
let d = f.p.diagrams.get_mut(&f.d).unwrap();
|
||||
d.nodes.get_mut(&f.n).unwrap().position = xy(100., 800.);
|
||||
d.nodes.get_mut(&an).unwrap().collapsed = collapsed;
|
||||
d.routes = vec![route(internal), route(external)];
|
||||
if obstacle {
|
||||
let id =
|
||||
f.p.add_element(work, layer, "Stationary obstacle", None)
|
||||
.unwrap();
|
||||
f.p.place(f.d, id, xy(550., 230.));
|
||||
}
|
||||
validate_candidate(&f.p).unwrap();
|
||||
let captured = scope(&f);
|
||||
assert_eq!(captured.uniform, Uniform::MixedOrUnresolved);
|
||||
assert_eq!(
|
||||
captured.placements.keys().copied().collect::<BTreeSet<_>>(),
|
||||
BTreeSet::from([f.n, xn, yn])
|
||||
);
|
||||
// Explicit control: the real current API still refuses Arrange for this root.
|
||||
assert!(matches!(
|
||||
plan_semantics(&f.p, &captured, Destination::LayoutOnly, &BTreeMap::new()),
|
||||
Err(Refusal::MixedLayoutRequired)
|
||||
));
|
||||
assert!(matches!(
|
||||
plan_semantics(
|
||||
&f.p,
|
||||
&captured,
|
||||
Destination::Performer(f.a),
|
||||
&BTreeMap::new()
|
||||
),
|
||||
Err(Refusal::MixedLayoutRequired)
|
||||
));
|
||||
Mixed {
|
||||
f,
|
||||
an,
|
||||
xn,
|
||||
yn,
|
||||
internal,
|
||||
include_performer,
|
||||
}
|
||||
}
|
||||
|
||||
fn affected(m: &Mixed) -> BTreeSet<Id> {
|
||||
let mut ids: BTreeSet<_> = scope(&m.f).placements.keys().copied().collect();
|
||||
let mut expected = BTreeSet::from([m.f.n, m.xn, m.yn]);
|
||||
if m.include_performer {
|
||||
ids.insert(m.an);
|
||||
ids.extend(projection::descendant_nodes(&m.f.p, m.f.d, m.an));
|
||||
expected.insert(m.an);
|
||||
}
|
||||
assert_eq!(ids, expected);
|
||||
ids
|
||||
}
|
||||
|
||||
// Diagnostic expansion changes only a temporary Diagram. Include affected
|
||||
// descendants and ancestors even when the normal projection hides them.
|
||||
// Unrelated folded interiors are intentionally OUTSIDE this diagnostic domain.
|
||||
fn diagnostic(p: &Project, diagram: Id, ids: &BTreeSet<Id>) -> ProjectedView {
|
||||
let mut d = p.diagrams[&diagram].clone();
|
||||
for (id, node) in &mut d.nodes {
|
||||
if ids.contains(id)
|
||||
|| projection::descendant_nodes(p, diagram, *id)
|
||||
.iter()
|
||||
.any(|n| ids.contains(n))
|
||||
{
|
||||
node.collapsed = false;
|
||||
}
|
||||
}
|
||||
projection::project_diagram(p, &d)
|
||||
}
|
||||
|
||||
fn rigid(before: &ProjectedView, after: &ProjectedView, ids: &BTreeSet<Id>) {
|
||||
for id in ids {
|
||||
let old = before.nodes.iter().find(|n| n.id == *id).unwrap();
|
||||
let new = after.nodes.iter().find(|n| n.id == *id).unwrap();
|
||||
assert_eq!(new.position, xy(old.position.x + 400., old.position.y));
|
||||
assert_eq!(new.size, old.size, "no reflow of an affected footprint");
|
||||
}
|
||||
}
|
||||
|
||||
// The only experimental bypass: use the pure general geometry command instead
|
||||
// of plan_semantics(LayoutOnly), whose mixed-root pre-veto is asserted above.
|
||||
// This is not a fabricated Scope or a call to singleton check_geometry with a
|
||||
// falsely enlarged Scope. The combined scene uses the real overlap predicate.
|
||||
fn candidate(m: &Mixed) -> (Command, Project) {
|
||||
let ids = affected(m);
|
||||
let command =
|
||||
oa_core::diagram_edit::translate_placements(&m.f.p, m.f.d, &ids, xy(400., 0.)).unwrap();
|
||||
let actual = prepare_command(&m.f.p, &command).unwrap().project;
|
||||
validate_candidate(&actual).unwrap();
|
||||
// Independent literal expected Project: no planner or route helper oracle.
|
||||
let mut expected = m.f.p.clone();
|
||||
let d = expected.diagrams.get_mut(&m.f.d).unwrap();
|
||||
for (id, position) in [
|
||||
(m.f.n, xy(500., 800.)),
|
||||
(m.xn, xy(540., 200.)),
|
||||
(m.yn, xy(1340., 200.)),
|
||||
] {
|
||||
d.nodes.get_mut(&id).unwrap().position = position;
|
||||
}
|
||||
if m.include_performer {
|
||||
d.nodes.get_mut(&m.an).unwrap().position = xy(500., 100.);
|
||||
}
|
||||
let internal = d.routes.iter_mut().find(|r| r.edge == m.internal).unwrap();
|
||||
internal.waypoints = vec![xy(820., 400.), xy(820., 550.)];
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"complete records, including folds, routes, other view and relations"
|
||||
);
|
||||
(command, actual)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_arrange_experiment_distributed_root_and_performer_can_translate_rigidly() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let enclosure_height = match layer {
|
||||
Layer::Oa => 218.,
|
||||
Layer::Sa => 256.,
|
||||
};
|
||||
for include_performer in [false, true] {
|
||||
for collapsed in [false, true] {
|
||||
let m = mixed(layer, collapsed, false, include_performer);
|
||||
let accepted = m.f.p.clone();
|
||||
let (command, actual) = candidate(&m);
|
||||
let ids = affected(&m);
|
||||
let before = projection::project_view(&accepted, m.f.d);
|
||||
let after = projection::project_view(&actual, m.f.d);
|
||||
let before_expanded = diagnostic(&accepted, m.f.d, &ids);
|
||||
let after_expanded = diagnostic(&actual, m.f.d, &ids);
|
||||
assert!(
|
||||
!overlaps(&before, &after),
|
||||
"visible scene must admit the combined move"
|
||||
);
|
||||
assert!(
|
||||
!overlaps(&before_expanded, &after_expanded),
|
||||
"expanded scene must admit the combined move"
|
||||
);
|
||||
rigid(&before_expanded, &after_expanded, &ids);
|
||||
for node in after.nodes.iter().chain(&after_expanded.nodes) {
|
||||
assert!(
|
||||
(Rect {
|
||||
position: node.position,
|
||||
size: node.size
|
||||
})
|
||||
.valid()
|
||||
);
|
||||
}
|
||||
// Explicit selected headers remain visible. Native clipping/readability
|
||||
// and complete group gesture admission are intentionally not claimed.
|
||||
assert!(after.nodes.iter().any(|n| n.id == m.f.n));
|
||||
if include_performer {
|
||||
assert!(after.nodes.iter().any(|n| n.id == m.an));
|
||||
} else {
|
||||
assert_eq!(
|
||||
actual.diagrams[&m.f.d].nodes[&m.an],
|
||||
accepted.diagrams[&m.f.d].nodes[&m.an]
|
||||
);
|
||||
assert_eq!(node(&before_expanded, m.an).position, xy(100., 100.));
|
||||
assert_eq!(
|
||||
node(&before_expanded, m.an).size,
|
||||
Size {
|
||||
width: 288.,
|
||||
height: enclosure_height
|
||||
}
|
||||
);
|
||||
assert_eq!(node(&after_expanded, m.an).position, xy(100., 100.));
|
||||
assert_eq!(
|
||||
node(&after_expanded, m.an).size,
|
||||
Size {
|
||||
width: 688.,
|
||||
height: enclosure_height
|
||||
}
|
||||
);
|
||||
}
|
||||
assert_eq!(roundtrip(&accepted, command), actual);
|
||||
assert_eq!(m.f.p, accepted);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_arrange_experiment_detects_moved_folded_child_collision() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let expected_overlap = match layer {
|
||||
Layer::Oa => 13696.,
|
||||
Layer::Sa => 20116.,
|
||||
};
|
||||
let m = mixed(layer, true, true, true);
|
||||
let accepted = m.f.p.clone();
|
||||
let (_, actual) = candidate(&m);
|
||||
let ids = affected(&m);
|
||||
let before = projection::project_view(&accepted, m.f.d);
|
||||
let after = projection::project_view(&actual, m.f.d);
|
||||
assert!(!before.nodes.iter().any(|n| n.id == m.xn));
|
||||
assert!(!after.nodes.iter().any(|n| n.id == m.xn));
|
||||
assert!(
|
||||
!overlaps(&before, &after),
|
||||
"must distinguish hidden collision from ordinary visible refusal"
|
||||
);
|
||||
let before_expanded = diagnostic(&accepted, m.f.d, &ids);
|
||||
let after_expanded = diagnostic(&actual, m.f.d, &ids);
|
||||
rigid(&before_expanded, &after_expanded, &ids);
|
||||
let obstacle = before_expanded
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.position == xy(550., 230.))
|
||||
.unwrap()
|
||||
.id;
|
||||
assert_eq!(
|
||||
overlap(
|
||||
node(&before_expanded, m.xn),
|
||||
node(&before_expanded, obstacle)
|
||||
),
|
||||
0.
|
||||
);
|
||||
assert_eq!(
|
||||
overlap(node(&after_expanded, m.xn), node(&after_expanded, obstacle)),
|
||||
expected_overlap
|
||||
);
|
||||
assert!(
|
||||
overlaps(&before_expanded, &after_expanded),
|
||||
"combined diagnostic scene must refuse"
|
||||
);
|
||||
// Detection only: there is no production group admission/commit API here.
|
||||
assert_eq!(m.f.p, accepted);
|
||||
}
|
||||
}
|
||||
|
||||
fn node(view: &ProjectedView, id: Id) -> &ProjectedNode {
|
||||
view.nodes.iter().find(|n| n.id == id).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_arrange_experiment_detects_stationary_enclosure_growth_collision() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let enclosure_height = match layer {
|
||||
Layer::Oa => 218.,
|
||||
Layer::Sa => 256.,
|
||||
};
|
||||
let mut m = mixed(layer, false, false, true);
|
||||
let kind = m.f.p.elements[&m.f.w].kind();
|
||||
let z =
|
||||
m.f.p
|
||||
.add_element(kind, layer, "Stationary Z", None)
|
||||
.unwrap();
|
||||
let zn = m.f.p.place(m.f.d, z, xy(1200., 100.));
|
||||
validate_candidate(&m.f.p).unwrap();
|
||||
let accepted = m.f.p.clone();
|
||||
let (_, actual) = candidate(&m);
|
||||
let bn = accepted.diagrams[&m.f.d]
|
||||
.nodes
|
||||
.values()
|
||||
.find(|n| n.element == m.f.b)
|
||||
.unwrap()
|
||||
.id;
|
||||
let before = projection::project_view(&accepted, m.f.d);
|
||||
let after = projection::project_view(&actual, m.f.d);
|
||||
assert_eq!(node(&before, bn).position, xy(900., 100.));
|
||||
assert_eq!(
|
||||
node(&before, bn).size,
|
||||
Size {
|
||||
width: 288.,
|
||||
height: enclosure_height
|
||||
}
|
||||
);
|
||||
assert_eq!(node(&after, bn).position, xy(900., 100.));
|
||||
assert_eq!(
|
||||
node(&after, bn).size,
|
||||
Size {
|
||||
width: 688.,
|
||||
height: enclosure_height
|
||||
}
|
||||
);
|
||||
assert_eq!(node(&after, zn).position, xy(1200., 100.));
|
||||
assert_eq!(
|
||||
node(&after, zn).size,
|
||||
Size {
|
||||
width: 224.,
|
||||
height: 94.
|
||||
}
|
||||
);
|
||||
assert_eq!(overlap(node(&before, bn), node(&before, zn)), 0.);
|
||||
assert_eq!(overlap(node(&after, bn), node(&after, zn)), 21056.);
|
||||
assert_eq!(node(&after, m.yn).position, xy(1340., 200.));
|
||||
assert_eq!(
|
||||
node(&after, m.yn).position.y
|
||||
- (node(&after, zn).position.y + node(&after, zn).size.height),
|
||||
6.
|
||||
);
|
||||
for id in affected(&m) {
|
||||
assert_eq!(overlap(node(&before, id), node(&before, zn)), 0.);
|
||||
assert_eq!(overlap(node(&after, id), node(&after, zn)), 0.);
|
||||
}
|
||||
assert_eq!(
|
||||
actual.diagrams[&m.f.d].nodes[&bn],
|
||||
accepted.diagrams[&m.f.d].nodes[&bn]
|
||||
);
|
||||
assert_eq!(
|
||||
actual.diagrams[&m.f.d].nodes[&zn],
|
||||
accepted.diagrams[&m.f.d].nodes[&zn]
|
||||
);
|
||||
assert!(
|
||||
overlaps(&before, &after),
|
||||
"complete scene must detect stationary enclosure growth"
|
||||
);
|
||||
let ids = affected(&m);
|
||||
assert!(overlaps(
|
||||
&diagnostic(&accepted, m.f.d, &ids),
|
||||
&diagnostic(&actual, m.f.d, &ids)
|
||||
));
|
||||
assert_eq!(m.f.p, accepted);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_arrange_experiment_unrelated_folded_interiors_are_outside_diagnostic_domain() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
// Independent source-derived literals: SA's auto-created function ports
|
||||
// raise projected X/Y height to 76 + 28 * (1 + 1), while Z is port-free.
|
||||
let (work_height, expected_overlap) = match layer {
|
||||
Layer::Oa => (94., 13696.),
|
||||
Layer::Sa => (132., 20116.),
|
||||
};
|
||||
let mut m = mixed(layer, true, false, true);
|
||||
let performer = match layer {
|
||||
Layer::Oa => Kind::Actor,
|
||||
Layer::Sa => Kind::SystemActor,
|
||||
};
|
||||
let kind = m.f.p.elements[&m.f.w].kind();
|
||||
let d =
|
||||
m.f.p
|
||||
.add_element(performer, layer, "Unrelated D", None)
|
||||
.unwrap();
|
||||
let z =
|
||||
m.f.p
|
||||
.add_element(kind, layer, "Unrelated hidden Z", None)
|
||||
.unwrap();
|
||||
m.f.p.relate(RelationKind::Allocation, "D owns Z", d, z);
|
||||
let dn = m.f.p.place(m.f.d, d, xy(2500., 100.));
|
||||
let zn = m.f.p.place(m.f.d, z, xy(550., 230.));
|
||||
m.f.p
|
||||
.diagrams
|
||||
.get_mut(&m.f.d)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&dn)
|
||||
.unwrap()
|
||||
.collapsed = true;
|
||||
validate_candidate(&m.f.p).unwrap();
|
||||
let accepted = m.f.p.clone();
|
||||
let (_, actual) = candidate(&m);
|
||||
let ids = affected(&m);
|
||||
let before = diagnostic(&accepted, m.f.d, &ids);
|
||||
let after = diagnostic(&actual, m.f.d, &ids);
|
||||
assert!(!before.nodes.iter().any(|n| n.id == zn));
|
||||
assert!(!after.nodes.iter().any(|n| n.id == zn));
|
||||
assert!(
|
||||
!overlaps(&before, &after),
|
||||
"chosen diagnostic domain excludes unrelated folded contents"
|
||||
);
|
||||
assert!(!overlaps(
|
||||
&projection::project_view(&accepted, m.f.d),
|
||||
&projection::project_view(&actual, m.f.d)
|
||||
));
|
||||
let all_unfolded = |p: &Project| {
|
||||
let mut diagram = p.diagrams[&m.f.d].clone();
|
||||
for n in diagram.nodes.values_mut() {
|
||||
n.collapsed = false;
|
||||
}
|
||||
projection::project_diagram(p, &diagram)
|
||||
};
|
||||
let broad_before = all_unfolded(&accepted);
|
||||
let broad_after = all_unfolded(&actual);
|
||||
assert_eq!(node(&broad_before, m.xn).position, xy(140., 200.));
|
||||
assert_eq!(node(&broad_after, m.xn).position, xy(540., 200.));
|
||||
assert_eq!(
|
||||
node(&broad_after, m.xn).size,
|
||||
Size {
|
||||
width: 224.,
|
||||
height: work_height
|
||||
}
|
||||
);
|
||||
assert_eq!(node(&broad_before, zn).position, xy(550., 230.));
|
||||
assert_eq!(node(&broad_after, zn).position, xy(550., 230.));
|
||||
assert_eq!(
|
||||
node(&broad_after, zn).size,
|
||||
Size {
|
||||
width: 224.,
|
||||
height: 94.
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
overlap(node(&broad_before, m.xn), node(&broad_before, zn)),
|
||||
0.
|
||||
);
|
||||
assert_eq!(
|
||||
overlap(node(&broad_after, m.xn), node(&broad_after, zn)),
|
||||
expected_overlap
|
||||
);
|
||||
// Other newly exposed enclosure pairs may also overlap. X/Z is a
|
||||
// concrete discriminator, not a claim that it is the only cause.
|
||||
assert!(overlaps(&broad_before, &broad_after));
|
||||
for id in [dn, zn] {
|
||||
assert_eq!(
|
||||
actual.diagrams[&m.f.d].nodes[&id],
|
||||
accepted.diagrams[&m.f.d].nodes[&id]
|
||||
);
|
||||
}
|
||||
assert!(actual.diagrams[&m.f.d].nodes[&dn].collapsed);
|
||||
assert_eq!(m.f.p, accepted);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,18 @@ use super::*;
|
||||
use crate::document::Document;
|
||||
use oa_core::source_project::{ProjectLimits, compile_bundle, format_bundle};
|
||||
|
||||
#[path = "group_arrange_experiment.rs"]
|
||||
mod group_arrange_experiment;
|
||||
|
||||
#[path = "arrange_tests.rs"]
|
||||
mod arrange_tests;
|
||||
|
||||
#[path = "assignment_tests.rs"]
|
||||
mod assignment_tests;
|
||||
|
||||
#[path = "assignment_boundary_tests.rs"]
|
||||
mod assignment_boundary_tests;
|
||||
|
||||
struct Fixture {
|
||||
p: Project,
|
||||
d: Id,
|
||||
|
||||
@@ -60,6 +60,7 @@ impl Root<'_> {
|
||||
return false;
|
||||
}
|
||||
let canvas = DiagramCanvas {
|
||||
selection: self.app.diagram_selection.as_ref(),
|
||||
allocation: Some(self.app.allocation_capability()),
|
||||
project: self.app.project(),
|
||||
view_index: Some(self.app.document.view_index()),
|
||||
|
||||
+985
-61
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,22 @@
|
||||
//! 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 crate::{
|
||||
allocation_drag as plan,
|
||||
diagram_selection::Snapshot,
|
||||
diagram_usage::{Surface, Target as SelectionTarget},
|
||||
route_edit::Context,
|
||||
};
|
||||
use iced::{Point, Rectangle, Task, Vector};
|
||||
use oa_core::{projection::ProjectedView, routing::RoutedView, *};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
pub const FINISH_EDIT: &str = "Finish or cancel the current edit before selecting or moving work.";
|
||||
pub const FINISH_EDIT: &str =
|
||||
"Finish or cancel the current edit before selecting or moving elements.";
|
||||
const ARRANGE_ARMED: &str = "Arrange next drag armed · presentation only · Esc cancels";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Stamp {
|
||||
@@ -65,7 +75,8 @@ pub fn contains(r: Rectangle, p: Point) -> bool {
|
||||
impl Frozen {
|
||||
pub fn capture(
|
||||
project: &Project,
|
||||
scope: &plan::Scope,
|
||||
diagram: &Diagram,
|
||||
affected: &BTreeMap<Id, NodePlacement>,
|
||||
view: &ProjectedView,
|
||||
routed: &RoutedView,
|
||||
zoom: f32,
|
||||
@@ -73,7 +84,7 @@ impl Frozen {
|
||||
let mut targets = Vec::new();
|
||||
let mut cards = Vec::new();
|
||||
for n in &view.nodes {
|
||||
if scope.placements.contains_key(&n.id) {
|
||||
if affected.contains_key(&n.id) {
|
||||
continue;
|
||||
}
|
||||
let region = Rectangle::new(
|
||||
@@ -84,7 +95,7 @@ impl Frozen {
|
||||
cards.push(region);
|
||||
continue;
|
||||
};
|
||||
if e.kind().is_performer() && e.layer() == scope.diagram.layer {
|
||||
if e.kind().is_performer() && e.layer() == diagram.layer {
|
||||
let mut ancestors = Vec::new();
|
||||
let mut parent = e.parent;
|
||||
while let Some(id) = parent {
|
||||
@@ -95,7 +106,7 @@ impl Frozen {
|
||||
parent = project.elements.get(&id).and_then(|e| e.parent);
|
||||
}
|
||||
let name = project.named(e.id).to_owned();
|
||||
let collapsed = scope.diagram.nodes[&n.id].collapsed;
|
||||
let collapsed = diagram.nodes[&n.id].collapsed;
|
||||
targets.push(Target {
|
||||
element: e.id,
|
||||
placement: n.id,
|
||||
@@ -118,7 +129,7 @@ impl Frozen {
|
||||
let mut controls: Vec<_> = view
|
||||
.ports
|
||||
.iter()
|
||||
.filter(|port| !scope.placements.contains_key(&port.owner))
|
||||
.filter(|port| !affected.contains_key(&port.owner))
|
||||
.map(|port| {
|
||||
Rectangle::new(
|
||||
Point::new(port.position.x - radius, port.position.y - radius),
|
||||
@@ -224,17 +235,23 @@ impl Frozen {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Assign,
|
||||
Arrange,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Press {
|
||||
pub(crate) struct Press {
|
||||
pub stamp: Stamp,
|
||||
pub token: Id,
|
||||
pub start: Point,
|
||||
pub scope: plan::Scope,
|
||||
pub frozen: Frozen,
|
||||
pub arrange: bool,
|
||||
pub selection: Snapshot,
|
||||
pub target: SelectionTarget,
|
||||
pub mode: Mode,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Event {
|
||||
pub(crate) enum Event {
|
||||
Press(Arc<Press>),
|
||||
Preview(Stamp, Id, Option<Point>),
|
||||
Release(Stamp, Id, Option<Point>),
|
||||
@@ -244,23 +261,266 @@ pub enum Event {
|
||||
Unfocused,
|
||||
KeyboardBoundary,
|
||||
}
|
||||
pub struct PreviewPlacement {
|
||||
pub diagram: Diagram,
|
||||
pub view: ProjectedView,
|
||||
pub delta: Position,
|
||||
}
|
||||
|
||||
pub struct Preview {
|
||||
pub token: Id,
|
||||
pub semantic: Arc<plan::SemanticPlan>,
|
||||
pub placement: plan::PlacementPlan,
|
||||
pub candidate: Candidate,
|
||||
pub placement: PreviewPlacement,
|
||||
pub routed: Arc<RoutedView>,
|
||||
}
|
||||
impl Preview {
|
||||
pub fn project(&self) -> &Project {
|
||||
self.candidate.project()
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn index(&self) -> &view_options::ViewIndex {
|
||||
self.candidate.index()
|
||||
}
|
||||
}
|
||||
|
||||
enum Prepared {
|
||||
Singleton(Box<plan::Scope>),
|
||||
Assignment(plan::assignment::Scope),
|
||||
Arrange(Arc<plan::arrange::Plan>),
|
||||
Performers(Arc<PerformerPlan>),
|
||||
Refused(String),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Candidate {
|
||||
Singleton(Arc<plan::SemanticPlan>),
|
||||
Assignment(Arc<plan::assignment::SemanticPlan>),
|
||||
Arrange(Arc<plan::arrange::Plan>),
|
||||
Performers(Arc<PerformerPlan>),
|
||||
}
|
||||
|
||||
enum Placed {
|
||||
Planned(plan::PlacementPlan),
|
||||
Performers {
|
||||
preview: PreviewPlacement,
|
||||
command: Box<Command>,
|
||||
requested: Position,
|
||||
},
|
||||
}
|
||||
|
||||
impl Placed {
|
||||
fn diagram(&self) -> &Diagram {
|
||||
match self {
|
||||
Self::Planned(p) => &p.diagram,
|
||||
Self::Performers { preview, .. } => &preview.diagram,
|
||||
}
|
||||
}
|
||||
fn view(&self) -> &ProjectedView {
|
||||
match self {
|
||||
Self::Planned(p) => &p.view,
|
||||
Self::Performers { preview, .. } => &preview.view,
|
||||
}
|
||||
}
|
||||
fn into_preview(self) -> PreviewPlacement {
|
||||
match self {
|
||||
Self::Planned(p) => PreviewPlacement {
|
||||
diagram: p.diagram,
|
||||
view: p.view,
|
||||
delta: p.delta,
|
||||
},
|
||||
Self::Performers { preview, .. } => preview,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ordinary performer movement preserves the established core translation policy.
|
||||
/// It shares input provenance, not the explicit Arrange geometry restrictions.
|
||||
pub struct PerformerPlan {
|
||||
accepted: Project,
|
||||
index: view_options::ViewIndex,
|
||||
diagram: Id,
|
||||
selected: BTreeSet<Id>,
|
||||
anchor: Id,
|
||||
affected: BTreeMap<Id, NodePlacement>,
|
||||
}
|
||||
impl PerformerPlan {
|
||||
fn place(&self, requested: Position) -> Result<Placed, plan::Refusal> {
|
||||
let original = &self.accepted.diagrams[&self.diagram];
|
||||
let anchor = original.nodes[&self.anchor].position;
|
||||
let delta = if requested == anchor {
|
||||
Position { x: 0., y: 0. }
|
||||
} else {
|
||||
Position {
|
||||
x: (requested.x / 10.).round() * 10. - anchor.x,
|
||||
y: (requested.y / 10.).round() * 10. - anchor.y,
|
||||
}
|
||||
};
|
||||
let command =
|
||||
diagram_edit::translate_placements(&self.accepted, self.diagram, &self.selected, delta)
|
||||
.map_err(|e| plan::Refusal::InvalidCandidate(e.to_string()))?;
|
||||
let mut diagram = original.clone();
|
||||
let Command::Batch(edits) = &command else {
|
||||
unreachable!("translation is an atomic batch")
|
||||
};
|
||||
for edit in edits {
|
||||
match edit {
|
||||
Command::EditNode {
|
||||
diagram: id,
|
||||
original,
|
||||
node,
|
||||
} if *id == self.diagram => {
|
||||
diagram.nodes.insert(*original, node.clone());
|
||||
}
|
||||
Command::SetEdgeRoute { diagram: id, route } if *id == self.diagram => {
|
||||
let stored = diagram
|
||||
.routes
|
||||
.iter_mut()
|
||||
.find(|r| r.edge == route.edge)
|
||||
.ok_or(plan::Refusal::StaleScope)?;
|
||||
*stored = route.clone();
|
||||
}
|
||||
_ => {
|
||||
return Err(plan::Refusal::InvalidCandidate(
|
||||
"Unexpected performer movement edit.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let view = projection::project_diagram_with_index(&self.accepted, &diagram, &self.index);
|
||||
Ok(Placed::Performers {
|
||||
preview: PreviewPlacement {
|
||||
diagram,
|
||||
view,
|
||||
delta,
|
||||
},
|
||||
command: Box::new(command),
|
||||
requested,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Candidate {
|
||||
pub fn project(&self) -> &Project {
|
||||
match self {
|
||||
Self::Singleton(p) => p.project(),
|
||||
Self::Assignment(p) => p.project(),
|
||||
Self::Arrange(p) => p.project(),
|
||||
Self::Performers(p) => &p.accepted,
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn index(&self) -> &view_options::ViewIndex {
|
||||
match self {
|
||||
Self::Singleton(p) => p.index(),
|
||||
Self::Assignment(p) => p.index(),
|
||||
Self::Arrange(p) => p.index(),
|
||||
Self::Performers(p) => &p.index,
|
||||
}
|
||||
}
|
||||
fn place(
|
||||
&self,
|
||||
requested: Position,
|
||||
presentation: plan::PresentationContext,
|
||||
) -> Result<Placed, plan::Refusal> {
|
||||
match self {
|
||||
Self::Singleton(p) => plan::place(p, requested, presentation).map(Placed::Planned),
|
||||
Self::Assignment(p) => {
|
||||
plan::assignment::place(p, requested, presentation).map(Placed::Planned)
|
||||
}
|
||||
Self::Arrange(p) => {
|
||||
plan::arrange::place(p, requested, presentation).map(Placed::Planned)
|
||||
}
|
||||
Self::Performers(p) => p.place(requested),
|
||||
}
|
||||
}
|
||||
fn finish(&self, live: &Project, placed: &Placed) -> Result<Option<Command>, plan::Refusal> {
|
||||
match (self, placed) {
|
||||
(Self::Singleton(p), Placed::Planned(result)) => plan::finish(p, live, result),
|
||||
(Self::Assignment(p), Placed::Planned(result)) => {
|
||||
plan::assignment::finish(p, live, result)
|
||||
}
|
||||
(Self::Arrange(p), Placed::Planned(result)) => plan::arrange::finish(p, live, result),
|
||||
(
|
||||
Self::Performers(p),
|
||||
Placed::Performers {
|
||||
preview,
|
||||
command,
|
||||
requested,
|
||||
},
|
||||
) => {
|
||||
if live != &p.accepted {
|
||||
return Err(plan::Refusal::StaleScope);
|
||||
}
|
||||
let checked = p.place(*requested)?;
|
||||
let Placed::Performers {
|
||||
preview: checked,
|
||||
command: checked_command,
|
||||
..
|
||||
} = checked
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
if checked.diagram != preview.diagram
|
||||
|| checked.view != preview.view
|
||||
|| checked.delta != preview.delta
|
||||
|| &checked_command != command
|
||||
{
|
||||
return Err(plan::Refusal::StaleScope);
|
||||
}
|
||||
let mut expected = p.accepted.clone();
|
||||
expected.diagrams.insert(p.diagram, checked.diagram);
|
||||
let actual = prepare_command(live, &checked_command)
|
||||
.map_err(|e| plan::Refusal::InvalidCandidate(e.to_string()))?
|
||||
.project;
|
||||
if actual != expected {
|
||||
return Err(plan::Refusal::InvalidCandidate(
|
||||
"Performer movement would change unrelated records.".into(),
|
||||
));
|
||||
}
|
||||
Ok((actual != *live).then_some(*checked_command))
|
||||
}
|
||||
_ => Err(plan::Refusal::StaleScope),
|
||||
}
|
||||
}
|
||||
fn label(&self) -> String {
|
||||
let (label, warnings) = match self {
|
||||
Self::Singleton(p) => (p.label.clone(), p.warnings.len()),
|
||||
Self::Assignment(p) => (p.label().to_owned(), p.warnings().len()),
|
||||
Self::Arrange(p) => (
|
||||
format!(
|
||||
"Arrange {} selected elements · {} affected placements",
|
||||
p.selected().len(),
|
||||
p.affected().len()
|
||||
),
|
||||
0,
|
||||
),
|
||||
Self::Performers(p) => (
|
||||
format!("Move {} selected performer(s)", p.selected.len()),
|
||||
0,
|
||||
),
|
||||
};
|
||||
if warnings == 0 {
|
||||
label
|
||||
} else {
|
||||
format!("{label} · {warnings} model warning(s) retained")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Active {
|
||||
press: Arc<Press>,
|
||||
selection: Snapshot,
|
||||
crossed: bool,
|
||||
prepared: Prepared,
|
||||
frozen: Option<Arc<Frozen>>,
|
||||
inspection_targets: Vec<usize>,
|
||||
ids: BTreeMap<Id, Id>,
|
||||
cache: Vec<(
|
||||
plan::Destination,
|
||||
Result<Arc<plan::SemanticPlan>, plan::Refusal>,
|
||||
)>,
|
||||
cache: Vec<(plan::Destination, Result<Candidate, plan::Refusal>)>,
|
||||
}
|
||||
pub struct Feedback {
|
||||
pub(crate) struct Feedback {
|
||||
pub press: Arc<Press>,
|
||||
pub frozen: Option<Arc<Frozen>>,
|
||||
ordinary_performers: bool,
|
||||
pub targets: Vec<usize>,
|
||||
/// Last captured target names for inspection only; never resolver input.
|
||||
pub inspection_targets: Vec<usize>,
|
||||
@@ -273,7 +533,13 @@ impl Feedback {
|
||||
let names = self
|
||||
.inspection_targets
|
||||
.iter()
|
||||
.map(|index| self.press.frozen.targets[*index].name.as_str())
|
||||
.filter_map(|index| {
|
||||
self.frozen
|
||||
.as_ref()?
|
||||
.targets
|
||||
.get(*index)
|
||||
.map(|t| t.name.as_str())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" / ");
|
||||
format!(
|
||||
@@ -293,7 +559,9 @@ impl Feedback {
|
||||
/// Captured accepted names, independent of clipped status/refusal prose.
|
||||
pub fn destination_identity(&self) -> String {
|
||||
match self.targets.as_slice() {
|
||||
[] => if self.press.arrange {
|
||||
[] => if self.ordinary_performers {
|
||||
"Move performers"
|
||||
} else if self.press.mode == Mode::Arrange {
|
||||
"Arrange only"
|
||||
} else if self.refused {
|
||||
"No eligible destination"
|
||||
@@ -301,12 +569,22 @@ impl Feedback {
|
||||
"Outside performers"
|
||||
}
|
||||
.into(),
|
||||
[index] => self.press.frozen.targets[*index].name.clone(),
|
||||
[index] => self
|
||||
.frozen
|
||||
.as_ref()
|
||||
.and_then(|f| f.targets.get(*index))
|
||||
.map(|t| t.name.clone())
|
||||
.unwrap_or_else(|| "No eligible destination".into()),
|
||||
indices => format!(
|
||||
"Ambiguous: {}",
|
||||
indices
|
||||
.iter()
|
||||
.map(|index| self.press.frozen.targets[*index].name.as_str())
|
||||
.filter_map(|index| self
|
||||
.frozen
|
||||
.as_ref()?
|
||||
.targets
|
||||
.get(*index)
|
||||
.map(|t| t.name.as_str()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" / ")
|
||||
),
|
||||
@@ -358,6 +636,7 @@ impl App {
|
||||
}
|
||||
pub(crate) fn allocation_input_owner(&self) -> bool {
|
||||
self.page == Page::Diagram
|
||||
&& !self.context_help
|
||||
&& self
|
||||
.active_diagram
|
||||
.and_then(|id| self.project().diagrams.get(&id))
|
||||
@@ -391,6 +670,18 @@ impl App {
|
||||
&& self.canvas_size.is_none_or(|s| s == stamp.bounds.size())
|
||||
&& stamp.bounds.width > 0.
|
||||
&& stamp.bounds.height > 0.
|
||||
&& stamp.zoom > 0.
|
||||
&& [
|
||||
stamp.bounds.x,
|
||||
stamp.bounds.y,
|
||||
stamp.bounds.width,
|
||||
stamp.bounds.height,
|
||||
stamp.pan.x,
|
||||
stamp.pan.y,
|
||||
stamp.zoom,
|
||||
]
|
||||
.iter()
|
||||
.all(|value| value.is_finite())
|
||||
}
|
||||
/// Called before general input dispatch. Even equal-valued actions (Fit,
|
||||
/// Undo/Redo, tool/modal round trips) retire old render-time capabilities.
|
||||
@@ -410,7 +701,12 @@ impl App {
|
||||
| Message::DiagramUsagesReady(_)
|
||||
| Message::DiagramRevealViewport(..)
|
||||
) {
|
||||
let clear_armed_status =
|
||||
self.allocation_drag.arrange_next && self.status == ARRANGE_ARMED;
|
||||
self.allocation_drag.retire();
|
||||
if clear_armed_status {
|
||||
self.status = "Arrange cancelled".into();
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn allocation_boundary(&self) -> impl PartialEq + use<> {
|
||||
@@ -427,20 +723,54 @@ impl App {
|
||||
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
|
||||
fn allocation_selection_valid(&self, snapshot: &Snapshot) -> bool {
|
||||
self.multiselect_context().is_some_and(|current| {
|
||||
self.diagram_selection
|
||||
.as_ref()
|
||||
.is_some_and(|selection| selection.matches(snapshot, current))
|
||||
})
|
||||
}
|
||||
pub(super) fn allocation_press_owns_current_view(&self, press: &Press) -> bool {
|
||||
self.allocation_drag.active.is_none()
|
||||
&& self.allocation_stamp_valid(press.stamp)
|
||||
&& press.arrange == self.allocation_drag.arrange_next
|
||||
if self.allocation_drag.active.is_some()
|
||||
|| !self.allocation_stamp_valid(press.stamp)
|
||||
|| (press.mode == Mode::Arrange) != self.allocation_drag.arrange_next
|
||||
|| !self.allocation_selection_valid(&press.selection)
|
||||
|| press.selection.context().scope.surface
|
||||
!= Surface::Saved(press.stamp.context.diagram)
|
||||
|| !press.start.x.is_finite()
|
||||
|| !press.start.y.is_finite()
|
||||
|| !contains(press.stamp.bounds, press.start)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let view = projection::project_view_with_index(
|
||||
self.project(),
|
||||
press.stamp.context.diagram,
|
||||
self.document.view_index(),
|
||||
);
|
||||
super::multiselect::visible(
|
||||
self.project(),
|
||||
press.stamp.context.diagram,
|
||||
&view,
|
||||
&press.target,
|
||||
)
|
||||
}
|
||||
/// Bare Allocation movement has no lifetime provenance. All actual Allocation
|
||||
/// placement gestures now enter Press/Active, including ordinary performers.
|
||||
pub(super) fn allocation_legacy_move(&self, message: &Message) -> bool {
|
||||
let allocation = |diagram| {
|
||||
self.project()
|
||||
.diagrams
|
||||
.get(&diagram)
|
||||
.is_some_and(|d| d.projection == ProjectionKind::Allocation)
|
||||
};
|
||||
match message {
|
||||
Message::MoveNode(..) => self.active_diagram.is_some_and(allocation),
|
||||
Message::DiagramSelection(super::multiselect::Event::Move(snapshot, _)) => {
|
||||
matches!(snapshot.context().scope.surface, Surface::Saved(diagram) if allocation(diagram))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
pub(super) fn allocation_event_envelope(&self, event: &Event) -> bool {
|
||||
match event {
|
||||
@@ -451,11 +781,64 @@ impl App {
|
||||
.is_some_and(|active| active.press.token == *token)
|
||||
}
|
||||
Event::Refused(epoch, _) => *epoch == self.allocation_drag.epoch,
|
||||
// Invalid Press packets deliberately report why the view or draft
|
||||
// changed. Leave their existing validation and feedback intact.
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
fn allocation_prepare(&self, press: &Press, selection: &Snapshot) -> Prepared {
|
||||
let SelectionTarget::Placement(anchor) = &press.target else {
|
||||
return Prepared::Refused("Move requires only placed work or performers; ports and connections cannot be moved with this selection.".into());
|
||||
};
|
||||
let anchor = *anchor;
|
||||
let Some(ids) = super::multiselect::placements(selection) else {
|
||||
return Prepared::Refused("Move requires only placed work or performers; remove ports, rows and connections from the selection.".into());
|
||||
};
|
||||
let project = self.project();
|
||||
let diagram = press.stamp.context.diagram;
|
||||
let d = &project.diagrams[&diagram];
|
||||
let selected: BTreeMap<_, _> = ids.iter().map(|id| (*id, d.nodes[id].element)).collect();
|
||||
let result = if press.mode == Mode::Arrange {
|
||||
plan::arrange::capture(project, diagram, &selected, anchor)
|
||||
.map(|p| Prepared::Arrange(Arc::new(p)))
|
||||
} else if selected
|
||||
.values()
|
||||
.all(|id| project.elements[id].kind().is_work())
|
||||
{
|
||||
if selected.len() == 1 {
|
||||
plan::capture(project, diagram, selected[&anchor], anchor)
|
||||
.map(|scope| Prepared::Singleton(Box::new(scope)))
|
||||
} else {
|
||||
plan::assignment::capture(project, diagram, &selected, anchor)
|
||||
.map(Prepared::Assignment)
|
||||
}
|
||||
} else if selected
|
||||
.values()
|
||||
.all(|id| project.elements[id].kind().is_performer())
|
||||
{
|
||||
validate_candidate(project)
|
||||
.map_err(|e| plan::Refusal::InvalidCandidate(e.to_string()))
|
||||
.map(|_| {
|
||||
let mut affected = BTreeMap::new();
|
||||
for id in &ids {
|
||||
for member in std::iter::once(*id)
|
||||
.chain(projection::descendant_nodes(project, diagram, *id))
|
||||
{
|
||||
affected.insert(member, d.nodes[&member].clone());
|
||||
}
|
||||
}
|
||||
Prepared::Performers(Arc::new(PerformerPlan {
|
||||
accepted: project.clone(),
|
||||
index: view_options::ViewIndex::new(project),
|
||||
diagram,
|
||||
selected: ids,
|
||||
anchor,
|
||||
affected,
|
||||
}))
|
||||
})
|
||||
} else {
|
||||
Err(plan::Refusal::Ineligible("Assignment requires only work. Arm Arrange next drag to arrange a supported work/performer selection.".into()))
|
||||
};
|
||||
result.unwrap_or_else(|reason| Prepared::Refused(refusal(&reason)))
|
||||
}
|
||||
pub(super) fn allocation_event(&mut self, event: Event) -> Task<Message> {
|
||||
if !self.allocation_event_envelope(&event) {
|
||||
return Task::none();
|
||||
@@ -465,7 +848,7 @@ impl App {
|
||||
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();
|
||||
self.status = ARRANGE_ARMED.into();
|
||||
} else {
|
||||
self.status = FINISH_EDIT.into();
|
||||
}
|
||||
@@ -476,22 +859,13 @@ impl App {
|
||||
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::Cancel(_) => {
|
||||
self.allocation_drag.retire();
|
||||
self.status = "Drag canceled".into();
|
||||
}
|
||||
Event::Refused(epoch, text) => {
|
||||
if epoch == self.allocation_drag.epoch {
|
||||
self.allocation_drag.retire();
|
||||
self.status = text;
|
||||
}
|
||||
Event::Refused(_, text) => {
|
||||
self.allocation_drag.retire();
|
||||
self.status = text;
|
||||
}
|
||||
Event::Press(press) => {
|
||||
if self.allocation_drag.active.is_some() {
|
||||
@@ -505,32 +879,73 @@ impl App {
|
||||
};
|
||||
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();
|
||||
// A selected-member press has no selection or inspector effect.
|
||||
// An unselected press replaces selection atomically in this handler.
|
||||
if !press.selection.targets().contains(&press.target) {
|
||||
self.multiselect_event(super::multiselect::Event::Choose(
|
||||
press.selection.context(),
|
||||
press.target.clone(),
|
||||
super::multiselect::Choice::Replace,
|
||||
));
|
||||
}
|
||||
let Some(selection) = self.multiselect_snapshot() else {
|
||||
return Task::none();
|
||||
};
|
||||
if !selection.targets().contains(&press.target)
|
||||
|| (!press.selection.targets().contains(&press.target)
|
||||
&& selection.targets() != [press.target.clone()])
|
||||
{
|
||||
return Task::none();
|
||||
}
|
||||
let ids = press
|
||||
.scope
|
||||
.leaves
|
||||
.keys()
|
||||
.map(|id| (*id, Id::new_v4()))
|
||||
.collect();
|
||||
let diagram = press.stamp.context.diagram;
|
||||
let view = projection::project_view_with_index(
|
||||
self.project(),
|
||||
diagram,
|
||||
self.document.view_index(),
|
||||
);
|
||||
if !selection.targets().iter().all(|target| {
|
||||
super::multiselect::visible(self.project(), diagram, &view, target)
|
||||
}) {
|
||||
self.allocation_drag.retire();
|
||||
self.status = "The view changed. Start this drag again.".into();
|
||||
return Task::none();
|
||||
}
|
||||
let prepared = self.allocation_prepare(&press, &selection);
|
||||
let (affected, leaf_ids) = match &prepared {
|
||||
Prepared::Singleton(scope) => (
|
||||
Some(&scope.placements),
|
||||
scope.leaves.keys().copied().collect::<Vec<_>>(),
|
||||
),
|
||||
Prepared::Assignment(scope) => (
|
||||
Some(scope.affected()),
|
||||
scope.leaves().keys().copied().collect(),
|
||||
),
|
||||
Prepared::Arrange(plan) => (Some(plan.affected()), Vec::new()),
|
||||
Prepared::Performers(plan) => (Some(&plan.affected), Vec::new()),
|
||||
Prepared::Refused(_) => (None, Vec::new()),
|
||||
};
|
||||
let frozen = affected.map(|affected| {
|
||||
let d = &self.project().diagrams[&diagram];
|
||||
let routed = routing::route_diagram(self.project(), d, &view);
|
||||
Arc::new(Frozen::capture(
|
||||
self.project(),
|
||||
d,
|
||||
affected,
|
||||
&view,
|
||||
&routed,
|
||||
press.stamp.zoom,
|
||||
))
|
||||
});
|
||||
let ids = leaf_ids.into_iter().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,
|
||||
selection,
|
||||
crossed: false,
|
||||
prepared,
|
||||
frozen,
|
||||
inspection_targets: Vec::new(),
|
||||
ids,
|
||||
cache: Vec::new(),
|
||||
@@ -552,15 +967,16 @@ impl App {
|
||||
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.
|
||||
let Some(active) = self.allocation_drag.active.as_ref() else {
|
||||
return;
|
||||
};
|
||||
if active.press.token != token {
|
||||
return;
|
||||
}
|
||||
if !self.allocation_stamp_valid(stamp) {
|
||||
if !self.allocation_stamp_valid(stamp)
|
||||
|| !self.allocation_selection_valid(&active.selection)
|
||||
|| active.press.stamp != stamp
|
||||
{
|
||||
self.allocation_drag.retire();
|
||||
self.status = if self.allocation_drag_clean() {
|
||||
"The view changed. Start this drag again.".into()
|
||||
@@ -569,17 +985,35 @@ impl App {
|
||||
};
|
||||
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);
|
||||
let mut active = self.allocation_drag.active.take().unwrap();
|
||||
let press = active.press.clone();
|
||||
active.crossed |= pointer.is_some_and(|p| p.distance(press.start) > 3.);
|
||||
let in_bounds = pointer
|
||||
.is_some_and(|p| p.x.is_finite() && p.y.is_finite() && contains(stamp.bounds, p));
|
||||
if !active.crossed && in_bounds {
|
||||
if release {
|
||||
self.multiselect_event(super::multiselect::Event::Collapse(
|
||||
active.selection,
|
||||
press.target.clone(),
|
||||
));
|
||||
self.allocation_drag.retire();
|
||||
self.status = "Element selected".into();
|
||||
} else {
|
||||
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);
|
||||
if moved {
|
||||
let ordinary_performers = matches!(&active.prepared, Prepared::Performers(_));
|
||||
let hit = if !in_bounds {
|
||||
Hit::OutsideViewport
|
||||
} else if ordinary_performers {
|
||||
Hit::Destination(plan::Destination::LayoutOnly, None)
|
||||
} else {
|
||||
active.frozen.as_ref().map_or(Hit::Occluded, |f| {
|
||||
f.resolve(stamp, pointer, press.mode == Mode::Arrange)
|
||||
})
|
||||
};
|
||||
if active.crossed {
|
||||
match &hit {
|
||||
Hit::Destination(_, Some(target)) => active.inspection_targets = vec![*target],
|
||||
Hit::Ambiguous(targets) => active.inspection_targets = targets.clone(),
|
||||
@@ -588,64 +1022,63 @@ impl App {
|
||||
}
|
||||
let mut targets = Vec::new();
|
||||
let mut preview = None;
|
||||
let result: Result<String, String> = match hit {
|
||||
Hit::OutsideViewport => Err(if release {
|
||||
"Work drag canceled outside the canvas."
|
||||
} else {
|
||||
"Pointer outside canvas · return to choose a destination; releasing here cancels the drag."
|
||||
}.into()),
|
||||
_ if !moved => Ok("Work selected".into()),
|
||||
let result: Result<String, String> = if matches!(hit, Hit::OutsideViewport) {
|
||||
Err(if release { "Drag canceled outside the canvas." }
|
||||
else { "Pointer outside canvas · return to choose a destination; releasing here cancels the drag." }.into())
|
||||
} else if let Prepared::Refused(reason) = &active.prepared {
|
||||
Err(reason.clone())
|
||||
} else {
|
||||
match hit {
|
||||
Hit::OutsideViewport => unreachable!(),
|
||||
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())
|
||||
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
|
||||
let candidate = if let Some((_, cached)) = active.cache.iter().find(|(d, _)| *d == destination) { cached.clone() }
|
||||
else {
|
||||
let candidate = match &active.prepared {
|
||||
Prepared::Singleton(scope) => plan::plan_semantics(self.project(), scope, destination, &active.ids)
|
||||
.map(|p| Candidate::Singleton(Arc::new(p))),
|
||||
Prepared::Assignment(scope) => plan::assignment::plan_semantics(scope, destination, &active.ids)
|
||||
.map(|p| Candidate::Assignment(Arc::new(p))),
|
||||
Prepared::Arrange(plan) => Ok(Candidate::Arrange(plan.clone())),
|
||||
Prepared::Performers(plan) => Ok(Candidate::Performers(plan.clone())),
|
||||
Prepared::Refused(_) => unreachable!(),
|
||||
};
|
||||
active.cache.push((destination, candidate.clone())); candidate
|
||||
};
|
||||
semantic.map_err(|r| refusal(&r)).and_then(|semantic| {
|
||||
if stamp.zoom * 16. < 9. {
|
||||
candidate.map_err(|r| refusal(&r)).and_then(|candidate| {
|
||||
if !ordinary_performers && 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 SelectionTarget::Placement(anchor) = &press.target else { unreachable!("supported placement") };
|
||||
let original = self.project().diagrams[&stamp.context.diagram].nodes[anchor].position;
|
||||
let delta = pointer.unwrap() - press.start;
|
||||
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 }
|
||||
}),
|
||||
};
|
||||
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())
|
||||
target: target.map(|i| plan::TargetPresentation { placement: active.frozen.as_ref().unwrap().targets[i].placement }),
|
||||
};
|
||||
let placed = candidate.place(requested, presentation).map_err(|r| refusal(&r))?;
|
||||
let label = candidate.label();
|
||||
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))?;
|
||||
if let Some(command) = candidate.finish(self.project(), &placed).map_err(|r| refusal(&r))? {
|
||||
self.document.execute(command)
|
||||
.map_err(|e| format!("{e} · retry this drag after correcting the source issue"))?;
|
||||
// sync refreshes the retained primary once; no anchor promotion.
|
||||
self.sync();
|
||||
self.selected = press.scope.work;
|
||||
self.selected_node = Some(press.scope.placement);
|
||||
self.refresh_draft();
|
||||
self.reconcile_multiselect();
|
||||
}
|
||||
} else {
|
||||
let routed = Arc::new(routing::route_diagram(semantic.project(), &placement.diagram, &placement.view));
|
||||
preview = Some(Arc::new(Preview { token, semantic, placement, routed }));
|
||||
let routed = Arc::new(routing::route_diagram(candidate.project(), placed.diagram(), placed.view()));
|
||||
preview = Some(Arc::new(Preview { token, candidate, placement: placed.into_preview(), routed }));
|
||||
}
|
||||
Ok(label)
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
let refused = result.is_err();
|
||||
let text = result.unwrap_or_else(|text| text);
|
||||
@@ -654,10 +1087,13 @@ impl App {
|
||||
self.allocation_drag.retire();
|
||||
} else {
|
||||
let inspection_targets = active.inspection_targets.clone();
|
||||
let frozen = active.frozen.clone();
|
||||
self.allocation_drag.active = Some(active);
|
||||
self.allocation_drag.preview = preview;
|
||||
self.allocation_drag.feedback = Some(Feedback {
|
||||
press,
|
||||
frozen,
|
||||
ordinary_performers,
|
||||
targets,
|
||||
inspection_targets,
|
||||
text,
|
||||
|
||||
@@ -4,6 +4,9 @@ use super::*;
|
||||
use crate::behavior::canvas_workspace::tests::{Mounted, key};
|
||||
use iced::{Event as Input, keyboard};
|
||||
|
||||
#[path = "allocation_drag_tests/control_focus.rs"]
|
||||
mod control_focus;
|
||||
|
||||
fn character(text: &str, modifiers: keyboard::Modifiers) -> Input {
|
||||
Input::Keyboard(keyboard::Event::KeyPressed {
|
||||
key: keyboard::Key::Character(text.into()),
|
||||
@@ -187,6 +190,7 @@ async fn actual_keyboard_arrange_shortcut_consumes_once_escape_cancels_and_dirty
|
||||
)
|
||||
.await;
|
||||
assert!(!f.app.allocation_drag.arrange_next);
|
||||
assert_eq!(f.app.status, "Arrange cancelled");
|
||||
mounted
|
||||
.batch(
|
||||
&mut f.app,
|
||||
@@ -211,7 +215,7 @@ async fn actual_keyboard_arrange_shortcut_consumes_once_escape_cancels_and_dirty
|
||||
assert!(
|
||||
messages
|
||||
.iter()
|
||||
.any(|m| matches!(m, Message::WorkDrag(Event::Press(p)) if p.arrange))
|
||||
.any(|m| matches!(m, Message::WorkDrag(Event::Press(p)) if p.mode == Mode::Arrange))
|
||||
);
|
||||
assert!(!f.app.allocation_drag.arrange_next);
|
||||
assert_eq!(f.app.document.revision(), 1, "{}", f.app.status);
|
||||
@@ -282,7 +286,7 @@ async fn actual_rendered_canvas_pixels_do_not_change_when_toolbar_feedback_text_
|
||||
.as_ref()
|
||||
.expect("active frozen destination");
|
||||
assert!(!feedback.refused, "{}", feedback.text);
|
||||
let target = &feedback.press.frozen.targets[feedback.targets[0]];
|
||||
let target = &feedback.frozen.as_ref().unwrap().targets[feedback.targets[0]];
|
||||
assert!(target.region.y * f.app.zoom + f.app.pan.y < 0.);
|
||||
assert_eq!(feedback.destination_identity(), "A");
|
||||
let canvas = canvas_bounds(&mut mounted, &f.app);
|
||||
@@ -434,7 +438,7 @@ async fn actual_app_tree_exact_incoming_drag_keeps_destination_visible_and_canva
|
||||
selected_header.x + selected_header.width <= canvas.x + canvas.width
|
||||
&& selected_header.y + selected_header.height <= canvas.y + canvas.height
|
||||
);
|
||||
let mut expected = preview.semantic.project().clone();
|
||||
let mut expected = preview.project().clone();
|
||||
expected
|
||||
.diagrams
|
||||
.insert(f.diagram, preview.placement.diagram.clone());
|
||||
@@ -689,7 +693,7 @@ async fn actual_toolbar_hover_inspects_last_full_name_without_authorizing_an_out
|
||||
.await;
|
||||
assert!(f.app.allocation_drag.active.is_none());
|
||||
assert!(f.app.allocation_drag.feedback.is_none());
|
||||
assert_eq!(f.app.status, "Work drag canceled outside the canvas.");
|
||||
assert_eq!(f.app.status, "Drag canceled outside the canvas.");
|
||||
assert_eq!(f.app.document.bundle(), &before);
|
||||
assert!(!f.app.document.can_undo());
|
||||
// A fresh gesture cannot inherit the previous inspection name.
|
||||
|
||||
@@ -8,6 +8,9 @@ use iced::{
|
||||
#[path = "allocation_drag_full_tree_tests.rs"]
|
||||
mod full_tree;
|
||||
|
||||
#[path = "allocation_drag_tests/group.rs"]
|
||||
mod group;
|
||||
|
||||
#[path = "allocation_drag_tests/navigation_union.rs"]
|
||||
mod navigation_union;
|
||||
|
||||
@@ -48,6 +51,7 @@ fn fixture(layer: Layer) -> Fixture {
|
||||
app.zoom = 1.;
|
||||
app.pan = Vector::ZERO;
|
||||
app.fit_to_view = false;
|
||||
app.reconcile_multiselect();
|
||||
Fixture {
|
||||
app,
|
||||
a,
|
||||
@@ -59,6 +63,7 @@ fn fixture(layer: Layer) -> Fixture {
|
||||
}
|
||||
fn canvas(app: &App) -> DiagramCanvas<'_> {
|
||||
DiagramCanvas {
|
||||
selection: app.diagram_selection.as_ref(),
|
||||
allocation: Some(app.allocation_capability()),
|
||||
project: app.project(),
|
||||
view_index: Some(app.document.view_index()),
|
||||
@@ -121,6 +126,18 @@ fn press(f: &Fixture) -> Arc<Press> {
|
||||
})
|
||||
.expect("actual clean work-body press")
|
||||
}
|
||||
fn admit_press(f: &mut Fixture) -> Arc<Press> {
|
||||
let p = press(f);
|
||||
let _ = f.app.update(Message::WorkDrag(Event::Press(p.clone())));
|
||||
assert!(f.app.allocation_drag.active.is_some(), "{}", f.app.status);
|
||||
p
|
||||
}
|
||||
fn singleton(candidate: &Candidate) -> &Arc<plan::SemanticPlan> {
|
||||
let Candidate::Singleton(plan) = candidate else {
|
||||
panic!("legacy singleton candidate")
|
||||
};
|
||||
plan
|
||||
}
|
||||
fn drag(f: &mut Fixture, to: Point) {
|
||||
let events = batch(&f.app, start(f), to);
|
||||
assert!(matches!(
|
||||
@@ -358,7 +375,7 @@ fn arrange_is_one_gesture_and_snapped_noop_preserves_redo_and_source() {
|
||||
assert!(f.app.allocation_drag.arrange_next);
|
||||
let p = press(&f);
|
||||
let _ = f.app.update(Message::WorkDrag(Event::Press(p.clone())));
|
||||
assert!(p.arrange);
|
||||
assert_eq!(p.mode, Mode::Arrange);
|
||||
assert!(!f.app.allocation_drag.arrange_next);
|
||||
let _ = f.app.update(Message::WorkDrag(Event::Release(
|
||||
p.stamp,
|
||||
@@ -369,7 +386,7 @@ fn arrange_is_one_gesture_and_snapped_noop_preserves_redo_and_source() {
|
||||
assert_eq!(f.app.document.revision(), revision);
|
||||
assert!(f.app.document.can_redo());
|
||||
assert!(f.app.project().relations.is_empty());
|
||||
assert!(!press(&f).arrange);
|
||||
assert_eq!(press(&f).mode, Mode::Assign);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -396,14 +413,15 @@ fn candidate_semantics_are_cached_per_destination_with_stable_ids_and_own_index(
|
||||
let _ = f
|
||||
.app
|
||||
.update(Message::WorkDrag(Event::Preview(p.stamp, p.token, Some(a))));
|
||||
let first = f
|
||||
.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.expect(&f.app.status)
|
||||
.semantic
|
||||
.clone();
|
||||
let first = singleton(
|
||||
&f.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.expect(&f.app.status)
|
||||
.candidate,
|
||||
)
|
||||
.clone();
|
||||
let stable = first
|
||||
.project()
|
||||
.relations
|
||||
@@ -418,20 +436,20 @@ fn candidate_semantics_are_cached_per_destination_with_stable_ids_and_own_index(
|
||||
)));
|
||||
assert!(Arc::ptr_eq(
|
||||
&first,
|
||||
&f.app.allocation_drag.preview.as_ref().unwrap().semantic
|
||||
singleton(&f.app.allocation_drag.preview.as_ref().unwrap().candidate)
|
||||
));
|
||||
let _ = f
|
||||
.app
|
||||
.update(Message::WorkDrag(Event::Preview(p.stamp, p.token, Some(b))));
|
||||
let preview = f.app.allocation_drag.preview.as_ref().expect(&f.app.status);
|
||||
assert!(!Arc::ptr_eq(&first, &preview.semantic));
|
||||
assert_eq!(preview.semantic.project().relations[&stable].source(), f.b);
|
||||
assert!(!Arc::ptr_eq(&first, singleton(&preview.candidate)));
|
||||
assert_eq!(preview.project().relations[&stable].source(), f.b);
|
||||
assert_eq!(
|
||||
preview.placement.view,
|
||||
projection::project_diagram_with_index(
|
||||
preview.semantic.project(),
|
||||
preview.project(),
|
||||
&preview.placement.diagram,
|
||||
preview.semantic.index()
|
||||
preview.index()
|
||||
)
|
||||
);
|
||||
assert_ne!(
|
||||
@@ -447,7 +465,7 @@ fn candidate_semantics_are_cached_per_destination_with_stable_ids_and_own_index(
|
||||
.update(Message::WorkDrag(Event::Preview(p.stamp, p.token, Some(a))));
|
||||
assert!(Arc::ptr_eq(
|
||||
&first,
|
||||
&f.app.allocation_drag.preview.as_ref().unwrap().semantic
|
||||
singleton(&f.app.allocation_drag.preview.as_ref().unwrap().candidate)
|
||||
));
|
||||
assert_eq!(
|
||||
f.app.allocation_drag.active.as_ref().unwrap().cache.len(),
|
||||
@@ -457,9 +475,19 @@ fn candidate_semantics_are_cached_per_destination_with_stable_ids_and_own_index(
|
||||
|
||||
#[test]
|
||||
fn frozen_targets_use_half_open_semantic_priority_and_refuse_incomparable_overlap() {
|
||||
let f = fixture(Layer::Oa);
|
||||
let p = press(&f);
|
||||
let mut frozen = p.frozen.clone();
|
||||
let mut f = fixture(Layer::Oa);
|
||||
let p = admit_press(&mut f);
|
||||
let mut frozen = f
|
||||
.app
|
||||
.allocation_drag
|
||||
.active
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.frozen
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.clone();
|
||||
let ai = frozen
|
||||
.targets
|
||||
.iter()
|
||||
@@ -539,6 +567,7 @@ fn release_uses_ordered_native_position_before_later_motion_in_same_batch() {
|
||||
fn replace(f: &mut Fixture, project: Project) {
|
||||
f.app.document = crate::document::Document::from_project(project, Default::default()).unwrap();
|
||||
f.app.sync();
|
||||
f.app.reconcile_multiselect();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -587,7 +616,7 @@ fn same_snapped_position_on_opposite_shared_border_rebuilds_semantics_even_if_la
|
||||
.1
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
assert!(!Arc::ptr_eq(a, b));
|
||||
assert!(!Arc::ptr_eq(singleton(a), singleton(b)));
|
||||
let stable = a
|
||||
.project()
|
||||
.relations
|
||||
@@ -654,13 +683,24 @@ fn mounted_role_only_outgoing_refusal_retains_placement_and_same_performer_creat
|
||||
"{}",
|
||||
f.app.status
|
||||
);
|
||||
let target = press(&f)
|
||||
let admitted = admit_press(&mut f);
|
||||
let target = f
|
||||
.app
|
||||
.allocation_drag
|
||||
.active
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.frozen
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.targets
|
||||
.iter()
|
||||
.find(|t| t.element == f.a)
|
||||
.unwrap()
|
||||
.region;
|
||||
let _ = f
|
||||
.app
|
||||
.update(Message::WorkDrag(Event::Cancel(admitted.token)));
|
||||
drag(&mut f, screen(xy(target.x + 45., target.y + 100.)));
|
||||
assert_eq!(f.app.document.revision(), 1, "{}", f.app.status);
|
||||
assert_eq!(f.app.project().relations, relations);
|
||||
@@ -773,8 +813,18 @@ fn frozen_collapsed_target_uses_only_visible_header_and_port_edge_controls_occlu
|
||||
.unwrap()
|
||||
.collapsed = true;
|
||||
replace(&mut f, project);
|
||||
let p = press(&f);
|
||||
let mut frozen = p.frozen.clone();
|
||||
let p = admit_press(&mut f);
|
||||
let mut frozen = f
|
||||
.app
|
||||
.allocation_drag
|
||||
.active
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.frozen
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.clone();
|
||||
let t = frozen.targets.iter().find(|t| t.element == f.a).unwrap();
|
||||
let bottom = xy(t.region.x + 30., t.region.y + t.region.height);
|
||||
assert!(t.region.height <= 62.);
|
||||
@@ -944,7 +994,7 @@ fn toolbar_destination_names_transformed_target_whose_header_is_clipped() {
|
||||
send(&mut f.app, events);
|
||||
let feedback = f.app.allocation_drag.feedback.as_ref().unwrap();
|
||||
assert!(!feedback.refused, "{}", feedback.text);
|
||||
let target = &feedback.press.frozen.targets[feedback.targets[0]];
|
||||
let target = &feedback.frozen.as_ref().unwrap().targets[feedback.targets[0]];
|
||||
assert!(screen(xy(target.region.x, target.region.y)).y < bounds().y);
|
||||
assert_eq!(feedback.destination_identity(), "A");
|
||||
assert!(f.app.allocation_drag.preview.is_some());
|
||||
@@ -1003,7 +1053,7 @@ fn oa_sa_clipped_selected_header_refuses_preview_release_and_retries_without_par
|
||||
assert!(feedback.refused, "{}", feedback.text);
|
||||
assert!(feedback.text.contains("Make room or adjust the view"));
|
||||
assert_eq!(
|
||||
feedback.press.frozen.targets[feedback.targets[0]].element,
|
||||
feedback.frozen.as_ref().unwrap().targets[feedback.targets[0]].element,
|
||||
f.a
|
||||
);
|
||||
assert_eq!(f.app.project(), &accepted);
|
||||
@@ -1028,14 +1078,14 @@ fn oa_sa_clipped_selected_header_refuses_preview_release_and_retries_without_par
|
||||
send(&mut f.app, events);
|
||||
let active = f.app.allocation_drag.active.as_ref().unwrap();
|
||||
let p = active.press.clone();
|
||||
let semantic = active.cache[0].1.as_ref().unwrap().clone();
|
||||
let semantic = singleton(active.cache[0].1.as_ref().unwrap()).clone();
|
||||
let _ = f.app.update(Message::WorkDrag(Event::Preview(
|
||||
p.stamp,
|
||||
p.token,
|
||||
Some(clear),
|
||||
)));
|
||||
let preview = f.app.allocation_drag.preview.as_ref().expect(&f.app.status);
|
||||
assert!(Arc::ptr_eq(&semantic, &preview.semantic));
|
||||
assert!(Arc::ptr_eq(&semantic, singleton(&preview.candidate)));
|
||||
assert_eq!(
|
||||
preview.placement.diagram.nodes[&f.node].position,
|
||||
xy(120., 160.)
|
||||
@@ -1131,7 +1181,7 @@ fn oa_sa_toolbar_identity_accepts_exact_receiver_and_collapsed_header_drag() {
|
||||
assert!(!feedback.refused, "{}", feedback.text);
|
||||
assert_eq!(feedback.destination_identity(), name);
|
||||
assert_eq!(
|
||||
feedback.press.frozen.targets[feedback.targets[0]].placement,
|
||||
feedback.frozen.as_ref().unwrap().targets[feedback.targets[0]].placement,
|
||||
target_id
|
||||
);
|
||||
let preview = f.app.allocation_drag.preview.as_ref().expect(&f.app.status);
|
||||
@@ -1143,12 +1193,12 @@ fn oa_sa_toolbar_identity_accepts_exact_receiver_and_collapsed_header_drag() {
|
||||
assert_eq!(
|
||||
preview.placement.view,
|
||||
projection::project_diagram_with_index(
|
||||
preview.semantic.project(),
|
||||
preview.project(),
|
||||
&preview.placement.diagram,
|
||||
preview.semantic.index()
|
||||
preview.index()
|
||||
)
|
||||
);
|
||||
let mut expected = preview.semantic.project().clone();
|
||||
let mut expected = preview.project().clone();
|
||||
expected
|
||||
.diagrams
|
||||
.insert(f.diagram, preview.placement.diagram.clone());
|
||||
@@ -1183,6 +1233,8 @@ fn destination_identity_does_not_describe_blocked_or_outside_viewport_as_unalloc
|
||||
let p = press(&f);
|
||||
let mut feedback = Feedback {
|
||||
press: p,
|
||||
frozen: None,
|
||||
ordinary_performers: false,
|
||||
targets: vec![],
|
||||
inspection_targets: vec![],
|
||||
text: "A card blocks this drop".into(),
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn dirty_selected_pin_outer_ring_keeps_real_name_focus_and_caret() {
|
||||
let mut f = fixture(Layer::Oa);
|
||||
let mut p = f.app.project().clone();
|
||||
let peer = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "Peer", None)
|
||||
.unwrap();
|
||||
p.place(f.diagram, peer, xy(700., 500.));
|
||||
let edge = p.relate(RelationKind::Interaction, "Flow", f.work, peer);
|
||||
let pin = xy(450., 547.);
|
||||
p.diagrams
|
||||
.get_mut(&f.diagram)
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(EdgeRoute {
|
||||
edge,
|
||||
source_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Right,
|
||||
offset: 0.5,
|
||||
}),
|
||||
target_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Left,
|
||||
offset: 0.5,
|
||||
}),
|
||||
waypoints: vec![pin],
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.8,
|
||||
offset: xy(0., -60.),
|
||||
}),
|
||||
});
|
||||
validate_candidate(&p).unwrap();
|
||||
let view = projection::project_view(&p, f.diagram);
|
||||
let routed = routing::route_diagram(&p, &p.diagrams[&f.diagram], &view);
|
||||
assert_eq!(routed.edges[&edge].pins, vec![pin]);
|
||||
assert!(!routed.edges[&edge].custom_suspended);
|
||||
assert!(
|
||||
routed.edges[&edge]
|
||||
.points
|
||||
.iter()
|
||||
.all(|point| point.y == 547.)
|
||||
);
|
||||
f.app = App::with_project(p);
|
||||
f.app.active_diagram = Some(f.diagram);
|
||||
f.app.window_size = iced::Size::new(2000., 1400.);
|
||||
let _ = f.app.update(Message::Select(edge));
|
||||
f.app.reconcile_multiselect();
|
||||
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;
|
||||
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, "XFlow");
|
||||
assert!(f.app.draft_dirty());
|
||||
let accepted = f.app.document.snapshot();
|
||||
let source = f.app.document.bundle().clone();
|
||||
let selection = f.app.multiselect_snapshot().unwrap();
|
||||
let pan = f.app.pan;
|
||||
// Exposed straight-run bend: outside the 7px line hit, within the 8px handle.
|
||||
let point = at(&mut mounted, &f, xy(pin.x, pin.y + 7.5));
|
||||
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::Pan(_)
|
||||
| Message::Select(_)
|
||||
| Message::SelectNode(_)
|
||||
| Message::MoveNode(..)
|
||||
| Message::Route(_)
|
||||
| Message::DiagramSelection(_)
|
||||
)));
|
||||
assert!(Arc::ptr_eq(&accepted, &f.app.document.snapshot()));
|
||||
assert_eq!(f.app.document.bundle(), &source);
|
||||
assert_eq!(f.app.multiselect_snapshot().unwrap(), selection);
|
||||
assert_eq!(f.app.pan, pan);
|
||||
assert!(
|
||||
is_focused(&mut mounted, &f.app, field),
|
||||
"dirty handle press must stop before outside-press unfocus"
|
||||
);
|
||||
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, "YXFlow");
|
||||
assert_eq!(f.app.document.bundle(), &source);
|
||||
assert!(!f.app.document.can_undo());
|
||||
}
|
||||
@@ -0,0 +1,904 @@
|
||||
use super::*;
|
||||
use crate::app::multiselect::{self, Choice};
|
||||
use crate::diagram_usage::Target as SelectionTarget;
|
||||
use iced::widget::text_editor;
|
||||
|
||||
#[path = "group/connection_lifetime.rs"]
|
||||
mod connection_lifetime;
|
||||
#[path = "group/route_lifetime.rs"]
|
||||
mod route_lifetime;
|
||||
|
||||
struct Group {
|
||||
f: Fixture,
|
||||
y: Id,
|
||||
yn: Id,
|
||||
c: Id,
|
||||
cn: Id,
|
||||
an: Id,
|
||||
ax: Id,
|
||||
by: Id,
|
||||
}
|
||||
|
||||
fn group(layer: Layer) -> Group {
|
||||
let mut f = fixture(layer);
|
||||
let mut p = f.app.project().clone();
|
||||
let y = p
|
||||
.add_element(p.elements[&f.work].kind(), layer, "Y", None)
|
||||
.unwrap();
|
||||
let c = p
|
||||
.add_element(
|
||||
if layer == Layer::Oa {
|
||||
Kind::Actor
|
||||
} else {
|
||||
Kind::SystemActor
|
||||
},
|
||||
layer,
|
||||
"C",
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let yn = p.place(f.diagram, y, xy(140., 600.));
|
||||
let cn = p.place(f.diagram, c, xy(1500., 100.));
|
||||
let d = p.diagrams.get_mut(&f.diagram).unwrap();
|
||||
d.nodes.get_mut(&f.node).unwrap().position = xy(140., 200.);
|
||||
d.nodes
|
||||
.values_mut()
|
||||
.find(|n| n.element == f.b)
|
||||
.unwrap()
|
||||
.position = xy(100., 500.);
|
||||
d.nodes.get_mut(&cn).unwrap().size = Size {
|
||||
width: 600.,
|
||||
height: 900.,
|
||||
};
|
||||
let an = d.nodes.values().find(|n| n.element == f.a).unwrap().id;
|
||||
let ax = p.relate(
|
||||
RelationKind::Allocation,
|
||||
"Reviewed X responsibility",
|
||||
f.a,
|
||||
f.work,
|
||||
);
|
||||
let by = p.relate(
|
||||
RelationKind::Allocation,
|
||||
"Reviewed Y responsibility",
|
||||
f.b,
|
||||
y,
|
||||
);
|
||||
p.relations.get_mut(&ax).unwrap().description = "Keep X provenance".into();
|
||||
p.relations.get_mut(&by).unwrap().description = "Keep Y provenance".into();
|
||||
validate_candidate(&p).unwrap();
|
||||
f.app = App::with_project(p);
|
||||
f.app.active_diagram = Some(f.diagram);
|
||||
f.app.zoom = 1.;
|
||||
f.app.pan = Vector::ZERO;
|
||||
f.app.fit_to_view = false;
|
||||
f.app.reconcile_multiselect();
|
||||
Group {
|
||||
f,
|
||||
y,
|
||||
yn,
|
||||
c,
|
||||
cn,
|
||||
an,
|
||||
ax,
|
||||
by,
|
||||
}
|
||||
}
|
||||
|
||||
fn choose(app: &mut App, target: SelectionTarget, choice: Choice) {
|
||||
let context = multiselect::context(app.route_context().unwrap());
|
||||
let _ = app.update(Message::DiagramSelection(multiselect::Event::Choose(
|
||||
context, target, choice,
|
||||
)));
|
||||
}
|
||||
|
||||
fn select(app: &mut App, ids: &[Id]) {
|
||||
for (i, id) in ids.iter().enumerate() {
|
||||
choose(
|
||||
app,
|
||||
SelectionTarget::Placement(*id),
|
||||
if i == 0 { Choice::Replace } else { Choice::Add },
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
app.diagram_selection.as_ref().unwrap().targets(),
|
||||
&ids.iter()
|
||||
.copied()
|
||||
.map(SelectionTarget::Placement)
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
fn selection(
|
||||
app: &App,
|
||||
) -> (
|
||||
Vec<SelectionTarget>,
|
||||
Option<SelectionTarget>,
|
||||
Id,
|
||||
Option<Id>,
|
||||
) {
|
||||
let s = app.diagram_selection.as_ref().unwrap();
|
||||
(
|
||||
s.targets().to_vec(),
|
||||
s.primary().cloned(),
|
||||
app.selected,
|
||||
app.selected_node,
|
||||
)
|
||||
}
|
||||
|
||||
fn node_point(app: &App, node: Id) -> Point {
|
||||
let view = projection::project_view(app.project(), app.active_diagram.unwrap());
|
||||
let n = view.nodes.iter().find(|n| n.id == node).unwrap();
|
||||
screen(xy(n.position.x + 40., n.position.y + 35.))
|
||||
}
|
||||
|
||||
fn input(app: &mut App, state: &mut CanvasState, event: mouse::Event, at: Point) {
|
||||
if let Some(message) = pointer(&canvas(app), state, event, at) {
|
||||
let _ = app.update(message);
|
||||
}
|
||||
}
|
||||
|
||||
fn begin(app: &mut App, state: &mut CanvasState, from: Point) -> Arc<Press> {
|
||||
input(
|
||||
app,
|
||||
state,
|
||||
mouse::Event::CursorMoved { position: from },
|
||||
from,
|
||||
);
|
||||
let message = pointer(
|
||||
&canvas(app),
|
||||
state,
|
||||
mouse::Event::ButtonPressed(mouse::Button::Left),
|
||||
from,
|
||||
)
|
||||
.unwrap();
|
||||
let Message::WorkDrag(Event::Press(packet)) = &message else {
|
||||
panic!("Allocation placement must enter its captured lifetime: {message:?}");
|
||||
};
|
||||
let packet = packet.clone();
|
||||
let _ = app.update(message);
|
||||
packet
|
||||
}
|
||||
|
||||
fn move_pointer(app: &mut App, state: &mut CanvasState, to: Point) {
|
||||
input(app, state, mouse::Event::CursorMoved { position: to }, to);
|
||||
}
|
||||
|
||||
fn release(app: &mut App, state: &mut CanvasState, to: Point) {
|
||||
input(
|
||||
app,
|
||||
state,
|
||||
mouse::Event::ButtonReleased(mouse::Button::Left),
|
||||
to,
|
||||
);
|
||||
}
|
||||
|
||||
fn exact_history(
|
||||
app: &mut App,
|
||||
before: &Project,
|
||||
source: &oa_core::source_project::SourceBundle,
|
||||
expected: &Project,
|
||||
) {
|
||||
assert_eq!(app.project(), expected);
|
||||
let after = app.document.bundle().clone();
|
||||
let reopened =
|
||||
crate::document::Document::from_bundle(after.clone(), Default::default()).unwrap();
|
||||
assert_eq!(reopened.project(), expected);
|
||||
let _ = app.update(Message::Undo);
|
||||
assert_eq!(app.project(), before);
|
||||
assert_eq!(app.document.bundle(), source);
|
||||
assert!(
|
||||
!app.document.can_undo(),
|
||||
"one group drag is one history step"
|
||||
);
|
||||
let _ = app.update(Message::Redo);
|
||||
assert_eq!(app.project(), expected);
|
||||
assert_eq!(app.document.bundle(), &after);
|
||||
assert!(!app.document.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_text_apply_rejects_old_allocation_packets_without_retiring_a_new_drag() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut g = group(layer);
|
||||
select(&mut g.f.app, &[g.f.node, g.yn]);
|
||||
let before = g.f.app.document.snapshot();
|
||||
assert!(!g.f.app.document.can_undo());
|
||||
let from = node_point(&g.f.app, g.f.node);
|
||||
let mut old_canvas = CanvasState::default();
|
||||
let old = begin(&mut g.f.app, &mut old_canvas, from);
|
||||
assert!(g.f.app.allocation_drag.active.is_some());
|
||||
let location = g.f.app.document.compiled().index.declarations[&g.f.work].clone();
|
||||
let original = &before.bundle.files[&location.path];
|
||||
let quoted_name = format!("\"{}\"", g.f.app.project().elements[&g.f.work].name);
|
||||
assert_eq!(original.matches(quoted_name.as_str()).count(), 1);
|
||||
let edited = original.replace(quoted_name.as_str(), "\"Changed through Text\"");
|
||||
let mut expected = before.decoded.project.clone();
|
||||
expected.elements.get_mut(&g.f.work).unwrap().name = "Changed through Text".into();
|
||||
let mut expected_bundle = before.bundle.clone();
|
||||
expected_bundle
|
||||
.files
|
||||
.insert(location.path.clone(), edited.clone());
|
||||
|
||||
let _ = g.f.app.update(Message::Page(Page::Text));
|
||||
assert!(g.f.app.allocation_drag.active.is_none());
|
||||
let _ = g.f.app.update(Message::SourceFile(location.path));
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::SourceEdit(text_editor::Action::SelectAll));
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::SourceEdit(text_editor::Action::Edit(
|
||||
text_editor::Edit::Paste(Arc::new(edited.clone())),
|
||||
)));
|
||||
assert!(g.f.app.source_dirty());
|
||||
assert_eq!(g.f.app.source_editor.text(), edited);
|
||||
assert!(Arc::ptr_eq(&before, &g.f.app.document.snapshot()));
|
||||
let _ = g.f.app.update(Message::ApplySource);
|
||||
assert!(!g.f.app.source_dirty(), "{}", g.f.app.status);
|
||||
assert_eq!(g.f.app.project(), &expected);
|
||||
assert_eq!(g.f.app.document.bundle(), &expected_bundle);
|
||||
|
||||
let _ = g.f.app.update(Message::Page(Page::Diagram));
|
||||
assert_eq!(g.f.app.active_diagram, Some(g.f.diagram));
|
||||
select(&mut g.f.app, &[g.f.node, g.yn]);
|
||||
let from = node_point(&g.f.app, g.f.node);
|
||||
let to = from + Vector::new(1400., 0.);
|
||||
let mut current_canvas = CanvasState::default();
|
||||
let current = begin(&mut g.f.app, &mut current_canvas, from);
|
||||
assert_ne!(current.token, old.token);
|
||||
assert_ne!(current.stamp.context, old.stamp.context);
|
||||
move_pointer(&mut g.f.app, &mut current_canvas, to);
|
||||
let preview =
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.expect(&g.f.app.status)
|
||||
.clone();
|
||||
let Candidate::Assignment(plan) = &preview.candidate else {
|
||||
panic!("the current gesture must be a real group assignment");
|
||||
};
|
||||
assert_eq!(plan.changed_count(), 2);
|
||||
let accepted = g.f.app.document.snapshot();
|
||||
let revision = g.f.app.document.revision();
|
||||
let held = selection(&g.f.app);
|
||||
let selected = g.f.app.multiselect_snapshot().unwrap();
|
||||
let workspace = g.f.app.source_workspace.bundle();
|
||||
let editor = g.f.app.source_editor.text();
|
||||
let camera = (
|
||||
g.f.app.zoom,
|
||||
g.f.app.pan,
|
||||
g.f.app.fit_to_view,
|
||||
g.f.app.canvas_size,
|
||||
);
|
||||
let epochs = (
|
||||
g.f.app.canvas_epoch,
|
||||
g.f.app.camera_epoch,
|
||||
g.f.app.allocation_drag.epoch,
|
||||
);
|
||||
let draft =
|
||||
g.f.app
|
||||
.draft
|
||||
.as_ref()
|
||||
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap());
|
||||
let form = g.f.app.behavior.recovery_snapshot();
|
||||
let status = g.f.app.status.clone();
|
||||
let pending_reveal = g.f.app.pending_diagram_reveal.clone();
|
||||
let arrange = g.f.app.allocation_drag.arrange_next;
|
||||
// An idle obsolete press intentionally reports a stale-view explanation.
|
||||
// With a newer real gesture active, both old packets must be fully inert.
|
||||
for event in [
|
||||
Event::Press(old.clone()),
|
||||
Event::Release(old.stamp, old.token, Some(to)),
|
||||
] {
|
||||
let _ = g.f.app.update(Message::WorkDrag(event));
|
||||
assert!(Arc::ptr_eq(&accepted, &g.f.app.document.snapshot()));
|
||||
assert_eq!(g.f.app.project(), &expected);
|
||||
assert_eq!(g.f.app.document.bundle(), &expected_bundle);
|
||||
assert_eq!(g.f.app.document.revision(), revision);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
assert_eq!(g.f.app.multiselect_snapshot(), Some(selected.clone()));
|
||||
assert!(Arc::ptr_eq(
|
||||
&g.f.app.allocation_drag.active.as_ref().unwrap().press,
|
||||
¤t
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
g.f.app.allocation_drag.preview.as_ref().unwrap(),
|
||||
&preview
|
||||
));
|
||||
assert_eq!(g.f.app.source_workspace.bundle(), workspace);
|
||||
assert_eq!(g.f.app.source_editor.text(), editor);
|
||||
assert_eq!(
|
||||
(
|
||||
g.f.app.zoom,
|
||||
g.f.app.pan,
|
||||
g.f.app.fit_to_view,
|
||||
g.f.app.canvas_size
|
||||
),
|
||||
camera
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
g.f.app.canvas_epoch,
|
||||
g.f.app.camera_epoch,
|
||||
g.f.app.allocation_drag.epoch
|
||||
),
|
||||
epochs
|
||||
);
|
||||
assert_eq!(
|
||||
g.f.app
|
||||
.draft
|
||||
.as_ref()
|
||||
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap()),
|
||||
draft
|
||||
);
|
||||
assert_eq!(g.f.app.behavior.recovery_snapshot(), form);
|
||||
assert_eq!(g.f.app.pending_diagram_reveal, pending_reveal);
|
||||
assert_eq!(g.f.app.allocation_drag.arrange_next, arrange);
|
||||
assert_eq!(g.f.app.status, status);
|
||||
assert!(!g.f.app.source_dirty());
|
||||
assert!(g.f.app.document.can_undo());
|
||||
assert!(!g.f.app.document.can_redo());
|
||||
}
|
||||
// The current gesture remains only a preview. History contains solely
|
||||
// the accepted text rename, never either stale assignment packet.
|
||||
let _ = g.f.app.update(Message::Undo);
|
||||
assert_eq!(g.f.app.project(), &before.decoded.project);
|
||||
assert_eq!(g.f.app.document.bundle(), &before.bundle);
|
||||
assert!(!g.f.app.document.can_undo());
|
||||
assert!(g.f.app.document.can_redo());
|
||||
let _ = g.f.app.update(Message::Redo);
|
||||
assert_eq!(g.f.app.project(), &expected);
|
||||
assert_eq!(g.f.app.document.bundle(), &expected_bundle);
|
||||
assert!(g.f.app.document.can_undo());
|
||||
assert!(!g.f.app.document.can_redo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_assignment_split_rebuild_preserves_primary_and_commits_one_complete_candidate() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
for anchor_is_primary in [false, true] {
|
||||
let mut g = group(layer);
|
||||
select(&mut g.f.app, &[g.f.node, g.yn]);
|
||||
let held = selection(&g.f.app);
|
||||
let before = g.f.app.project().clone();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let anchor = if anchor_is_primary { g.yn } else { g.f.node };
|
||||
let from = node_point(&g.f.app, anchor);
|
||||
let to = from + Vector::new(1400., 0.);
|
||||
let mut state = CanvasState::default();
|
||||
let packet = begin(&mut g.f.app, &mut state, from);
|
||||
assert_eq!(packet.target, SelectionTarget::Placement(anchor));
|
||||
assert_eq!(
|
||||
selection(&g.f.app),
|
||||
held,
|
||||
"member press must not inspect/collapse"
|
||||
);
|
||||
assert_eq!(g.f.app.document.bundle(), &source);
|
||||
move_pointer(&mut g.f.app, &mut state, to);
|
||||
let preview =
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.expect(&g.f.app.status);
|
||||
let Candidate::Assignment(plan) = &preview.candidate else {
|
||||
panic!("group must use combined assignment");
|
||||
};
|
||||
assert_eq!(plan.changed_count(), 2);
|
||||
assert_eq!(plan.already_correct_count(), 0);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
assert_eq!(g.f.app.project(), &before, "preview is immutable");
|
||||
release(&mut g.f.app, &mut state, to);
|
||||
let mut expected = before.clone();
|
||||
for (relation, work) in [(g.ax, g.f.work), (g.by, g.y)] {
|
||||
expected.relations.get_mut(&relation).unwrap().body = RelationBody::Allocation {
|
||||
source: g.c,
|
||||
target: work,
|
||||
};
|
||||
}
|
||||
let d = expected.diagrams.get_mut(&g.f.diagram).unwrap();
|
||||
d.nodes.get_mut(&g.f.node).unwrap().position = xy(1540., 200.);
|
||||
d.nodes.get_mut(&g.yn).unwrap().position = xy(1540., 600.);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
exact_history(&mut g.f.app, &before, &source, &expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_arrange_work_and_performer_anchors_preserve_every_responsibility() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
for performer_anchor in [false, true] {
|
||||
let mut g = group(layer);
|
||||
select(&mut g.f.app, &[g.an, g.yn]);
|
||||
let held = selection(&g.f.app);
|
||||
let before = g.f.app.project().clone();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::ArrangeNext));
|
||||
assert!(g.f.app.allocation_drag.arrange_next);
|
||||
let from = node_point(&g.f.app, if performer_anchor { g.an } else { g.yn });
|
||||
let to = from + Vector::new(400., 0.);
|
||||
let mut state = CanvasState::default();
|
||||
let packet = begin(&mut g.f.app, &mut state, from);
|
||||
assert_eq!(packet.mode, Mode::Arrange);
|
||||
assert!(!g.f.app.allocation_drag.arrange_next);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
move_pointer(&mut g.f.app, &mut state, to);
|
||||
assert!(
|
||||
matches!(
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.map(|p| &p.candidate),
|
||||
Some(Candidate::Arrange(_))
|
||||
),
|
||||
"{}",
|
||||
g.f.app.status
|
||||
);
|
||||
release(&mut g.f.app, &mut state, to);
|
||||
let mut expected = before.clone();
|
||||
let d = expected.diagrams.get_mut(&g.f.diagram).unwrap();
|
||||
d.nodes.get_mut(&g.an).unwrap().position = xy(500., 100.);
|
||||
d.nodes.get_mut(&g.f.node).unwrap().position = xy(540., 200.);
|
||||
d.nodes.get_mut(&g.yn).unwrap().position = xy(540., 600.);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
exact_history(&mut g.f.app, &before, &source, &expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_group_click_collapses_but_threshold_crossing_never_becomes_click() {
|
||||
for performer_anchor in [false, true] {
|
||||
for distance in [0., 3., 3.25] {
|
||||
let mut g = group(Layer::Oa);
|
||||
select(&mut g.f.app, &[g.an, g.f.node]);
|
||||
let held = selection(&g.f.app);
|
||||
let before = g.f.app.document.snapshot();
|
||||
let anchor = if performer_anchor { g.an } else { g.f.node };
|
||||
let from = node_point(&g.f.app, anchor);
|
||||
let mut state = CanvasState::default();
|
||||
begin(&mut g.f.app, &mut state, from);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
move_pointer(&mut g.f.app, &mut state, from + Vector::new(distance, 0.));
|
||||
if distance > 3. {
|
||||
assert!(
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.feedback
|
||||
.as_ref()
|
||||
.is_some_and(|f| f.refused)
|
||||
);
|
||||
assert!(g.f.app.allocation_drag.preview.is_none());
|
||||
}
|
||||
move_pointer(&mut g.f.app, &mut state, from);
|
||||
release(&mut g.f.app, &mut state, from);
|
||||
assert!(g.f.app.allocation_drag.active.is_none());
|
||||
assert!(Arc::ptr_eq(&before, &g.f.app.document.snapshot()));
|
||||
if distance > 3. {
|
||||
assert_eq!(
|
||||
selection(&g.f.app),
|
||||
held,
|
||||
"crossed-and-returned refusal must retain group"
|
||||
);
|
||||
} else {
|
||||
let s = g.f.app.diagram_selection.as_ref().unwrap();
|
||||
assert_eq!(s.targets(), &[SelectionTarget::Placement(anchor)]);
|
||||
assert_eq!(s.primary(), Some(&SelectionTarget::Placement(anchor)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allocation_bare_moves_cannot_bypass_armed_active_or_retired_lifetime() {
|
||||
for (stage, singleton) in (0..3).flat_map(|stage| [(stage, false), (stage, true)]) {
|
||||
let mut g = group(Layer::Oa);
|
||||
let ids = if singleton {
|
||||
vec![g.an]
|
||||
} else {
|
||||
vec![g.an, g.cn]
|
||||
};
|
||||
select(&mut g.f.app, &ids);
|
||||
let snapshot = g.f.app.multiselect_snapshot().unwrap();
|
||||
let held = selection(&g.f.app);
|
||||
let before = g.f.app.document.snapshot();
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::ArrangeNext));
|
||||
let mut state = CanvasState::default();
|
||||
let from = node_point(&g.f.app, g.an);
|
||||
if stage > 0 {
|
||||
let press = begin(&mut g.f.app, &mut state, from);
|
||||
if stage == 2 {
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::WorkDrag(Event::Cancel(press.token)));
|
||||
}
|
||||
}
|
||||
let epoch = g.f.app.allocation_drag.epoch;
|
||||
let armed = g.f.app.allocation_drag.arrange_next;
|
||||
let token =
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.active
|
||||
.as_ref()
|
||||
.map(|a| a.press.token);
|
||||
let _ = g.f.app.update(Message::MoveNode(g.an, xy(500., 100.)));
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::DiagramSelection(multiselect::Event::Move(
|
||||
snapshot,
|
||||
xy(400., 0.),
|
||||
)));
|
||||
assert!(Arc::ptr_eq(&before, &g.f.app.document.snapshot()));
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
assert_eq!(g.f.app.allocation_drag.epoch, epoch);
|
||||
assert_eq!(g.f.app.allocation_drag.arrange_next, armed);
|
||||
assert_eq!(
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.active
|
||||
.as_ref()
|
||||
.map(|a| a.press.token),
|
||||
token
|
||||
);
|
||||
}
|
||||
// A fresh ordinary performer gesture still uses the existing layout policy.
|
||||
// C's right edge leaves the viewport: explicit Arrange's header gate must not
|
||||
// accidentally become a new restriction on ordinary performer movement.
|
||||
let mut g = group(Layer::Oa);
|
||||
select(&mut g.f.app, &[g.an, g.cn]);
|
||||
let held = selection(&g.f.app);
|
||||
let before = g.f.app.project().clone();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::ArrangeNext));
|
||||
let from = node_point(&g.f.app, g.an);
|
||||
let mut state = CanvasState::default();
|
||||
let old = begin(&mut g.f.app, &mut state, from);
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::Cancel(old.token)));
|
||||
let mut state = CanvasState::default();
|
||||
let fresh = begin(&mut g.f.app, &mut state, from);
|
||||
assert_eq!(fresh.mode, Mode::Assign);
|
||||
let to = from + Vector::new(300., 0.);
|
||||
move_pointer(&mut g.f.app, &mut state, to);
|
||||
assert!(
|
||||
matches!(
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.map(|p| &p.candidate),
|
||||
Some(Candidate::Performers(_))
|
||||
),
|
||||
"{}",
|
||||
g.f.app.status
|
||||
);
|
||||
release(&mut g.f.app, &mut state, to);
|
||||
let mut expected = before.clone();
|
||||
let d = expected.diagrams.get_mut(&g.f.diagram).unwrap();
|
||||
d.nodes.get_mut(&g.an).unwrap().position = xy(400., 100.);
|
||||
d.nodes.get_mut(&g.f.node).unwrap().position = xy(440., 200.);
|
||||
d.nodes.get_mut(&g.cn).unwrap().position = xy(1800., 100.);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
exact_history(&mut g.f.app, &before, &source, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_group_press_rejects_selection_generation_aba_with_unchanged_other_stamps() {
|
||||
for membership_aba in [false, true] {
|
||||
let mut g = group(Layer::Oa);
|
||||
select(&mut g.f.app, &[g.f.node, g.yn]);
|
||||
let old = press(&g.f);
|
||||
let before = g.f.app.document.snapshot();
|
||||
let held = selection(&g.f.app);
|
||||
let epoch = g.f.app.allocation_drag.epoch;
|
||||
// Deliberately isolate selection generation from App message retirement.
|
||||
// Final selection/primary/context/Document values are unchanged; this
|
||||
// exercises the snapshot boundary, not an ordinary user-input sequence.
|
||||
let s = g.f.app.diagram_selection.as_mut().unwrap();
|
||||
if membership_aba {
|
||||
assert!(s.remove(&SelectionTarget::Placement(g.yn)));
|
||||
assert!(s.add(SelectionTarget::Placement(g.yn), |_| true));
|
||||
} else {
|
||||
assert!(s.set_primary(&SelectionTarget::Placement(g.f.node)));
|
||||
assert!(s.set_primary(&SelectionTarget::Placement(g.yn)));
|
||||
}
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
assert_eq!(g.f.app.allocation_drag.epoch, epoch);
|
||||
assert_eq!(g.f.app.route_context(), Some(old.stamp.context));
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::Press(old.clone())));
|
||||
assert!(
|
||||
g.f.app.allocation_drag.active.is_none(),
|
||||
"generation-only stale selection must not acquire input"
|
||||
);
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::Release(
|
||||
old.stamp,
|
||||
old.token,
|
||||
Some(start(&g.f)),
|
||||
)));
|
||||
assert!(Arc::ptr_eq(&before, &g.f.app.document.snapshot()));
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_selection_aba_and_old_press_cannot_retire_a_new_token() {
|
||||
let mut g = group(Layer::Oa);
|
||||
select(&mut g.f.app, &[g.f.node, g.yn]);
|
||||
let old = press(&g.f);
|
||||
choose(
|
||||
&mut g.f.app,
|
||||
SelectionTarget::Placement(g.f.node),
|
||||
Choice::Inspect,
|
||||
);
|
||||
choose(
|
||||
&mut g.f.app,
|
||||
SelectionTarget::Placement(g.yn),
|
||||
Choice::Inspect,
|
||||
);
|
||||
let before = g.f.app.document.snapshot();
|
||||
let from = node_point(&g.f.app, g.f.node);
|
||||
let mut state = CanvasState::default();
|
||||
let fresh = begin(&mut g.f.app, &mut state, from);
|
||||
let held = selection(&g.f.app);
|
||||
let epoch = g.f.app.allocation_drag.epoch;
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::Press(old.clone())));
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::Release(
|
||||
old.stamp,
|
||||
old.token,
|
||||
Some(from + Vector::new(1400., 0.)),
|
||||
)));
|
||||
assert_eq!(
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.active
|
||||
.as_ref()
|
||||
.map(|a| a.press.token),
|
||||
Some(fresh.token)
|
||||
);
|
||||
assert_eq!(g.f.app.allocation_drag.epoch, epoch);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
assert!(Arc::ptr_eq(&before, &g.f.app.document.snapshot()));
|
||||
release(&mut g.f.app, &mut state, from);
|
||||
}
|
||||
|
||||
fn unassign(g: &mut Group, inside_c: bool) {
|
||||
let mut project = g.f.app.project().clone();
|
||||
project.relations.remove(&g.ax);
|
||||
project.relations.remove(&g.by);
|
||||
if inside_c {
|
||||
let d = project.diagrams.get_mut(&g.f.diagram).unwrap();
|
||||
// These unassigned cards overlap an unrelated empty performer at the
|
||||
// same depth. Paint C first so the intended work press is visible and
|
||||
// independent of random UUID ordering; no semantic containment exists.
|
||||
let mut target = d.nodes.remove(&g.cn).unwrap();
|
||||
g.cn = Id::from_u128(1);
|
||||
target.id = g.cn;
|
||||
assert!(d.nodes.insert(g.cn, target).is_none());
|
||||
d.nodes.get_mut(&g.f.node).unwrap().position = xy(1540., 200.);
|
||||
d.nodes.get_mut(&g.yn).unwrap().position = xy(1540., 600.);
|
||||
}
|
||||
g.f.app = App::with_project(project);
|
||||
g.f.app.active_diagram = Some(g.f.diagram);
|
||||
g.f.app.zoom = 1.;
|
||||
g.f.app.pan = Vector::ZERO;
|
||||
g.f.app.fit_to_view = false;
|
||||
g.f.app.reconcile_multiselect();
|
||||
}
|
||||
|
||||
fn c_allocations(expected: &mut Project, g: &Group, ids: &BTreeMap<Id, Id>) {
|
||||
for (work, name, alias) in [
|
||||
(g.f.work, "C performs Work", "c_performs_work"),
|
||||
(g.y, "C performs Y", "c_performs_y"),
|
||||
] {
|
||||
expected.relations.insert(
|
||||
ids[&work],
|
||||
Relation {
|
||||
id: ids[&work],
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
body: RelationBody::Allocation {
|
||||
source: g.c,
|
||||
target: work,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_out_and_back_assigns_at_zero_delta_then_true_noop_preserves_redo() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut g = group(layer);
|
||||
unassign(&mut g, true);
|
||||
select(&mut g.f.app, &[g.f.node, g.yn]);
|
||||
let held = selection(&g.f.app);
|
||||
let before = g.f.app.project().clone();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let from = node_point(&g.f.app, g.f.node);
|
||||
let mut state = CanvasState::default();
|
||||
let press = begin(&mut g.f.app, &mut state, from);
|
||||
assert_eq!(press.target, SelectionTarget::Placement(g.f.node));
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
move_pointer(&mut g.f.app, &mut state, from + Vector::new(4., 0.));
|
||||
let preview =
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.expect(&g.f.app.status);
|
||||
assert_eq!(preview.placement.delta, xy(0., 0.));
|
||||
let Candidate::Assignment(candidate) = &preview.candidate else {
|
||||
panic!("exact work group must preview assignment");
|
||||
};
|
||||
assert_eq!(candidate.destination(), plan::Destination::Performer(g.c));
|
||||
assert_eq!(candidate.changed_count(), 2);
|
||||
let ids: BTreeMap<_, _> = preview
|
||||
.project()
|
||||
.relations
|
||||
.values()
|
||||
.filter(|r| r.kind() == RelationKind::Allocation)
|
||||
.map(|r| (r.target(), r.id))
|
||||
.collect();
|
||||
assert_eq!(ids.len(), 2);
|
||||
move_pointer(&mut g.f.app, &mut state, from);
|
||||
release(&mut g.f.app, &mut state, from);
|
||||
let mut expected = before.clone();
|
||||
c_allocations(&mut expected, &g, &ids);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
exact_history(&mut g.f.app, &before, &source, &expected);
|
||||
g.f.app
|
||||
.document
|
||||
.execute(Command::Describe(g.y, "Future rationale".into()))
|
||||
.unwrap();
|
||||
g.f.app.sync();
|
||||
let future = g.f.app.document.bundle().clone();
|
||||
let _ = g.f.app.update(Message::Undo);
|
||||
assert!(g.f.app.document.can_undo() && g.f.app.document.can_redo());
|
||||
let snapshot = g.f.app.document.snapshot();
|
||||
let revision = g.f.app.document.revision();
|
||||
let held = selection(&g.f.app);
|
||||
let from = node_point(&g.f.app, g.f.node);
|
||||
let mut state = CanvasState::default();
|
||||
begin(&mut g.f.app, &mut state, from);
|
||||
move_pointer(&mut g.f.app, &mut state, from + Vector::new(4., 0.));
|
||||
move_pointer(&mut g.f.app, &mut state, from);
|
||||
release(&mut g.f.app, &mut state, from);
|
||||
assert!(
|
||||
Arc::ptr_eq(&snapshot, &g.f.app.document.snapshot()),
|
||||
"{}",
|
||||
g.f.app.status
|
||||
);
|
||||
assert_eq!(g.f.app.document.revision(), revision);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
assert!(g.f.app.document.can_undo() && g.f.app.document.can_redo());
|
||||
let _ = g.f.app.update(Message::Redo);
|
||||
assert_eq!(g.f.app.document.bundle(), &future);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_source_refusal_retains_primary_source_and_both_history_paths() {
|
||||
let mut g = group(Layer::Oa);
|
||||
unassign(&mut g, false);
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let mut limits = oa_core::source_project::ProjectLimits::default();
|
||||
limits.model.max_source_bytes = source.files.values().map(String::len).sum::<usize>() + 128;
|
||||
g.f.app.document = crate::document::Document::from_bundle(source, limits).unwrap();
|
||||
g.f.app
|
||||
.document
|
||||
.execute(Command::Describe(g.f.work, "Reviewed".into()))
|
||||
.unwrap();
|
||||
g.f.app
|
||||
.document
|
||||
.execute(Command::Rename(g.y, "Future Y".into()))
|
||||
.unwrap();
|
||||
let future = g.f.app.document.bundle().clone();
|
||||
assert!(g.f.app.document.undo());
|
||||
g.f.app.sync();
|
||||
g.f.app.reconcile_multiselect();
|
||||
select(&mut g.f.app, &[g.f.node, g.yn]);
|
||||
let held = selection(&g.f.app);
|
||||
let before = g.f.app.document.snapshot();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let revision = g.f.app.document.revision();
|
||||
assert!(g.f.app.document.can_undo() && g.f.app.document.can_redo());
|
||||
let from = node_point(&g.f.app, g.f.node);
|
||||
let to = from + Vector::new(1400., 0.);
|
||||
let mut state = CanvasState::default();
|
||||
begin(&mut g.f.app, &mut state, from);
|
||||
move_pointer(&mut g.f.app, &mut state, to);
|
||||
assert!(
|
||||
g.f.app.allocation_drag.preview.is_some(),
|
||||
"geometry and semantics pass before source refusal: {}",
|
||||
g.f.app.status
|
||||
);
|
||||
release(&mut g.f.app, &mut state, to);
|
||||
assert!(g.f.app.status.contains("retry"), "{}", g.f.app.status);
|
||||
assert!(g.f.app.allocation_drag.active.is_none());
|
||||
assert!(Arc::ptr_eq(&before, &g.f.app.document.snapshot()));
|
||||
assert_eq!(g.f.app.document.bundle(), &source);
|
||||
assert_eq!(g.f.app.document.revision(), revision);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
assert!(g.f.app.document.can_undo() && g.f.app.document.can_redo());
|
||||
let _ = g.f.app.update(Message::Redo);
|
||||
assert_eq!(g.f.app.document.bundle(), &future);
|
||||
let _ = g.f.app.update(Message::Undo);
|
||||
assert_eq!(g.f.app.document.bundle(), &source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_off_grid_performer_out_and_back_is_noop_with_redo() {
|
||||
for singleton in [false, true] {
|
||||
let mut g = group(Layer::Oa);
|
||||
let mut project = g.f.app.project().clone();
|
||||
project
|
||||
.diagrams
|
||||
.get_mut(&g.f.diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&g.an)
|
||||
.unwrap()
|
||||
.position = xy(103., 107.);
|
||||
g.f.app = App::with_project(project);
|
||||
g.f.app.active_diagram = Some(g.f.diagram);
|
||||
g.f.app.zoom = 1.;
|
||||
g.f.app.pan = Vector::ZERO;
|
||||
g.f.app.fit_to_view = false;
|
||||
g.f.app
|
||||
.document
|
||||
.execute(Command::Describe(g.f.work, "Reviewed".into()))
|
||||
.unwrap();
|
||||
g.f.app
|
||||
.document
|
||||
.execute(Command::Describe(g.y, "Future".into()))
|
||||
.unwrap();
|
||||
let future = g.f.app.document.bundle().clone();
|
||||
assert!(g.f.app.document.undo());
|
||||
g.f.app.sync();
|
||||
g.f.app.reconcile_multiselect();
|
||||
select(
|
||||
&mut g.f.app,
|
||||
&if singleton {
|
||||
vec![g.an]
|
||||
} else {
|
||||
vec![g.an, g.cn]
|
||||
},
|
||||
);
|
||||
let held = selection(&g.f.app);
|
||||
let before = g.f.app.document.snapshot();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let revision = g.f.app.document.revision();
|
||||
let from = node_point(&g.f.app, g.an);
|
||||
let mut state = CanvasState::default();
|
||||
begin(&mut g.f.app, &mut state, from);
|
||||
move_pointer(&mut g.f.app, &mut state, from + Vector::new(20., 0.));
|
||||
assert!(
|
||||
g.f.app.allocation_drag.preview.is_some(),
|
||||
"{}",
|
||||
g.f.app.status
|
||||
);
|
||||
move_pointer(&mut g.f.app, &mut state, from);
|
||||
assert_eq!(
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.placement
|
||||
.delta,
|
||||
xy(0., 0.)
|
||||
);
|
||||
release(&mut g.f.app, &mut state, from);
|
||||
assert!(Arc::ptr_eq(&before, &g.f.app.document.snapshot()));
|
||||
assert_eq!(g.f.app.document.bundle(), &source);
|
||||
assert_eq!(g.f.app.document.revision(), revision);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
assert!(g.f.app.document.can_undo() && g.f.app.document.can_redo());
|
||||
let _ = g.f.app.update(Message::Redo);
|
||||
assert_eq!(g.f.app.document.bundle(), &future);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Delayed captured drawing packets must not retire a newer Allocation owner.
|
||||
use super::*;
|
||||
use crate::connection_edit::Event as ConnectionEvent;
|
||||
use crate::connection_tool::Tool;
|
||||
|
||||
fn drawing_tool(layer: Layer) -> Tool {
|
||||
match layer {
|
||||
Layer::Oa => Tool::Interaction,
|
||||
Layer::Sa => Tool::FunctionalExchange,
|
||||
}
|
||||
}
|
||||
|
||||
fn drawing_source(g: &mut Group, layer: Layer) -> crate::route_edit::Context {
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::Connection(ConnectionEvent::Choose(Some(
|
||||
drawing_tool(layer),
|
||||
))));
|
||||
let context = g.f.app.route_context().unwrap();
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::Connection(ConnectionEvent::Endpoint(
|
||||
context, g.f.work,
|
||||
)));
|
||||
let session = g.f.app.connection.as_ref().unwrap();
|
||||
assert_eq!(session.context, context);
|
||||
assert_eq!(session.source, Some(g.f.work));
|
||||
assert!(session.candidates.contains(&g.y));
|
||||
assert_eq!(g.f.app.route_context(), Some(context));
|
||||
context
|
||||
}
|
||||
|
||||
fn assert_captured_noop(app: &mut App, captured: crate::route_edit::Context, target: Id) {
|
||||
for event in [
|
||||
ConnectionEvent::Endpoint(captured, target),
|
||||
ConnectionEvent::Restart(captured),
|
||||
] {
|
||||
assert_connection_noop(app, event);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_connection_noop(app: &mut App, event: ConnectionEvent) {
|
||||
let document = app.document.snapshot();
|
||||
let selected = selection(app);
|
||||
let context = app.route_context();
|
||||
let camera = (app.pan, app.zoom, app.canvas_epoch, app.camera_epoch);
|
||||
let ownership = (app.allocation_drag.epoch, app.allocation_drag.arrange_next);
|
||||
let active = app
|
||||
.allocation_drag
|
||||
.active
|
||||
.as_ref()
|
||||
.map(|a| (a.press.clone(), a.crossed, a.cache.len()));
|
||||
let preview = app.allocation_drag.preview.as_ref().map(|p| {
|
||||
(
|
||||
p.token,
|
||||
p.placement.diagram.clone(),
|
||||
p.placement.delta,
|
||||
p.project().clone(),
|
||||
p.routed.clone(),
|
||||
)
|
||||
});
|
||||
let feedback = app.allocation_drag.feedback.as_ref().map(|f| {
|
||||
(
|
||||
f.press.token,
|
||||
f.text.clone(),
|
||||
f.refused,
|
||||
f.targets.clone(),
|
||||
f.inspection_targets.clone(),
|
||||
)
|
||||
});
|
||||
let connection = |app: &App| {
|
||||
app.connection
|
||||
.as_ref()
|
||||
.map(|s| (s.context, s.tool, s.source, s.candidates.clone()))
|
||||
};
|
||||
let session = connection(app);
|
||||
let interaction = app.source_symbols.interaction;
|
||||
let status = app.status.clone();
|
||||
let _ = app.update(Message::Connection(event));
|
||||
assert_eq!(selection(app), selected);
|
||||
assert_eq!(app.route_context(), context);
|
||||
assert_eq!(
|
||||
(app.pan, app.zoom, app.canvas_epoch, app.camera_epoch),
|
||||
camera
|
||||
);
|
||||
assert_eq!(
|
||||
(app.allocation_drag.epoch, app.allocation_drag.arrange_next),
|
||||
ownership,
|
||||
"rejected drawing packet must not retire the newer input owner"
|
||||
);
|
||||
match (active, app.allocation_drag.active.as_ref()) {
|
||||
(Some((press, crossed, cached)), Some(current)) => {
|
||||
assert!(Arc::ptr_eq(&press, ¤t.press));
|
||||
assert_eq!((current.crossed, current.cache.len()), (crossed, cached));
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => panic!("rejected drawing packet changed the active Allocation token"),
|
||||
}
|
||||
match (preview, app.allocation_drag.preview.as_ref()) {
|
||||
(Some((token, diagram, delta, project, routed)), Some(current)) => {
|
||||
assert_eq!(current.token, token);
|
||||
assert_eq!(current.placement.diagram, diagram);
|
||||
assert_eq!(current.placement.delta, delta);
|
||||
assert_eq!(current.project(), &project);
|
||||
assert!(Arc::ptr_eq(¤t.routed, &routed));
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => panic!("rejected drawing packet changed the Allocation preview"),
|
||||
}
|
||||
assert_eq!(
|
||||
app.allocation_drag.feedback.as_ref().map(|f| (
|
||||
f.press.token,
|
||||
f.text.clone(),
|
||||
f.refused,
|
||||
f.targets.clone(),
|
||||
f.inspection_targets.clone(),
|
||||
)),
|
||||
feedback
|
||||
);
|
||||
assert_eq!(connection(app), session);
|
||||
assert_eq!(app.source_symbols.interaction, interaction);
|
||||
assert_eq!(app.status, status);
|
||||
assert!(Arc::ptr_eq(&document, &app.document.snapshot()));
|
||||
assert_eq!(app.source_workspace.bundle(), document.bundle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_connection_after_cancel_preserves_arrange_arm_and_live_group() {
|
||||
for layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut g = group(layer);
|
||||
let old = drawing_source(&mut g, layer);
|
||||
let _ = g.f.app.update(Message::Escape);
|
||||
assert!(g.f.app.connection.is_none());
|
||||
select(&mut g.f.app, &[g.an, g.yn]);
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::ArrangeNext));
|
||||
assert!(g.f.app.allocation_drag.arrange_next);
|
||||
let current = g.f.app.route_context().unwrap();
|
||||
assert_captured_noop(&mut g.f.app, old, g.y);
|
||||
// Matching context with no session isolates the missing-owner guard.
|
||||
assert_captured_noop(&mut g.f.app, current, g.y);
|
||||
|
||||
let before = g.f.app.project().clone();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let held = selection(&g.f.app);
|
||||
let from = node_point(&g.f.app, g.an);
|
||||
let to = from + Vector::new(400., 0.);
|
||||
let mut state = CanvasState::default();
|
||||
let press = begin(&mut g.f.app, &mut state, from);
|
||||
assert_eq!(press.mode, Mode::Arrange);
|
||||
assert!(!g.f.app.allocation_drag.arrange_next);
|
||||
move_pointer(&mut g.f.app, &mut state, to);
|
||||
assert!(matches!(
|
||||
g.f.app
|
||||
.allocation_drag
|
||||
.preview
|
||||
.as_ref()
|
||||
.map(|p| &p.candidate),
|
||||
Some(Candidate::Arrange(_))
|
||||
));
|
||||
let current = g.f.app.route_context().unwrap();
|
||||
assert_captured_noop(&mut g.f.app, old, g.y);
|
||||
assert_captured_noop(&mut g.f.app, current, g.y);
|
||||
release(&mut g.f.app, &mut state, to);
|
||||
let mut expected = before.clone();
|
||||
let diagram = expected.diagrams.get_mut(&g.f.diagram).unwrap();
|
||||
diagram.nodes.get_mut(&g.an).unwrap().position = xy(500., 100.);
|
||||
diagram.nodes.get_mut(&g.f.node).unwrap().position = xy(540., 200.);
|
||||
diagram.nodes.get_mut(&g.yn).unwrap().position = xy(540., 600.);
|
||||
assert_eq!(selection(&g.f.app), held);
|
||||
exact_history(&mut g.f.app, &before, &source, &expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_connection_context_mismatches_preserve_the_current_session() {
|
||||
let mut g = group(Layer::Oa);
|
||||
let current = drawing_source(&mut g, Layer::Oa);
|
||||
// Session and current context agree: each old captured field is the sole
|
||||
// invalid relationship, not hidden behind a missing session.
|
||||
for captured in [
|
||||
crate::route_edit::Context {
|
||||
document: Id::new_v4(),
|
||||
..current
|
||||
},
|
||||
crate::route_edit::Context {
|
||||
diagram: Id::new_v4(),
|
||||
..current
|
||||
},
|
||||
crate::route_edit::Context {
|
||||
revision: current.revision + 1,
|
||||
..current
|
||||
},
|
||||
crate::route_edit::Context {
|
||||
epoch: current.epoch + 1,
|
||||
..current
|
||||
},
|
||||
] {
|
||||
assert_eq!(g.f.app.connection.as_ref().unwrap().context, current);
|
||||
assert_captured_noop(&mut g.f.app, captured, g.y);
|
||||
}
|
||||
// Captured/session contexts agree, but the rendered view has advanced.
|
||||
// This isolates the live-route predicate from session ownership.
|
||||
g.f.app.canvas_epoch += 1;
|
||||
assert_ne!(g.f.app.route_context(), Some(current));
|
||||
assert_eq!(g.f.app.connection.as_ref().unwrap().context, current);
|
||||
assert_captured_noop(&mut g.f.app, current, g.y);
|
||||
g.f.app.canvas_epoch = current.epoch;
|
||||
|
||||
// Conversely, incoming/current contexts agree. Retain obsolete session
|
||||
// metadata explicitly to isolate the session-context admission branch.
|
||||
g.f.app.connection.as_mut().unwrap().context.epoch += 1;
|
||||
assert_eq!(g.f.app.route_context(), Some(current));
|
||||
assert_captured_noop(&mut g.f.app, current, g.y);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_connection_current_restart_and_pair_commit_after_tool_boundary() {
|
||||
for begin_tool in [false, true] {
|
||||
let mut g = group(Layer::Oa);
|
||||
select(&mut g.f.app, &[g.an, g.yn]);
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::ArrangeNext));
|
||||
let from = node_point(&g.f.app, g.an);
|
||||
let mut state = CanvasState::default();
|
||||
begin(&mut g.f.app, &mut state, from);
|
||||
move_pointer(&mut g.f.app, &mut state, from + Vector::new(400., 0.));
|
||||
assert!(g.f.app.allocation_drag.preview.is_some());
|
||||
let before = g.f.app.project().clone();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let epoch = g.f.app.allocation_drag.epoch;
|
||||
let event = if begin_tool {
|
||||
ConnectionEvent::Begin(Tool::Interaction, g.f.work)
|
||||
} else {
|
||||
ConnectionEvent::Choose(Some(Tool::Interaction))
|
||||
};
|
||||
let _ = g.f.app.update(Message::Connection(event));
|
||||
assert!(g.f.app.allocation_drag.epoch > epoch);
|
||||
assert!(g.f.app.allocation_drag.active.is_none());
|
||||
assert!(g.f.app.allocation_drag.preview.is_none());
|
||||
assert!(!g.f.app.allocation_drag.arrange_next);
|
||||
let context = g.f.app.route_context().unwrap();
|
||||
if !begin_tool {
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::Connection(ConnectionEvent::Endpoint(
|
||||
context, g.f.work,
|
||||
)));
|
||||
}
|
||||
assert_eq!(g.f.app.connection.as_ref().unwrap().source, Some(g.f.work));
|
||||
assert!(
|
||||
g.f.app
|
||||
.connection
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.candidates
|
||||
.contains(&g.y)
|
||||
);
|
||||
let document = g.f.app.document.snapshot();
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::Connection(ConnectionEvent::Restart(context)));
|
||||
let context = g.f.app.route_context().unwrap();
|
||||
let restarted = g.f.app.connection.as_ref().unwrap();
|
||||
assert_eq!(restarted.context, context);
|
||||
assert_eq!(restarted.tool, Tool::Interaction);
|
||||
assert_eq!(restarted.source, None);
|
||||
assert!(restarted.candidates.contains(&g.f.work));
|
||||
assert!(Arc::ptr_eq(&document, &g.f.app.document.snapshot()));
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::Connection(ConnectionEvent::Endpoint(
|
||||
context, g.f.work,
|
||||
)));
|
||||
assert_eq!(g.f.app.connection.as_ref().unwrap().source, Some(g.f.work));
|
||||
let revision = g.f.app.document.revision();
|
||||
let _ =
|
||||
g.f.app
|
||||
.update(Message::Connection(ConnectionEvent::Endpoint(context, g.y)));
|
||||
assert!(g.f.app.connection.is_none());
|
||||
assert_eq!(g.f.app.document.revision(), revision + 1);
|
||||
let relation = &g.f.app.project().relations[&g.f.app.selected];
|
||||
assert_eq!(relation.kind(), RelationKind::Interaction);
|
||||
assert_eq!((relation.source(), relation.target()), (g.f.work, g.y));
|
||||
let mut expected = before.clone();
|
||||
assert!(
|
||||
expected
|
||||
.relations
|
||||
.insert(relation.id, relation.clone())
|
||||
.is_none()
|
||||
);
|
||||
exact_history(&mut g.f.app, &before, &source, &expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
//! Captured route commits cannot retire a newer Allocation input owner.
|
||||
use super::*;
|
||||
use crate::route_edit::{Context, Event as RouteEvent};
|
||||
|
||||
fn routed_group() -> (Group, Id) {
|
||||
let mut g = group(Layer::Oa);
|
||||
let mut project = g.f.app.project().clone();
|
||||
let edge = project.relate(
|
||||
RelationKind::Interaction,
|
||||
"Reviewed exchange",
|
||||
g.f.work,
|
||||
g.y,
|
||||
);
|
||||
project
|
||||
.diagrams
|
||||
.get_mut(&g.f.diagram)
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(EdgeRoute {
|
||||
edge,
|
||||
waypoints: vec![xy(700., 400.)],
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.4,
|
||||
offset: xy(5., 10.),
|
||||
}),
|
||||
source_attachment: None,
|
||||
target_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Left,
|
||||
offset: 0.6,
|
||||
}),
|
||||
});
|
||||
validate_candidate(&project).unwrap();
|
||||
g.f.app = App::with_project(project);
|
||||
g.f.app.active_diagram = Some(g.f.diagram);
|
||||
g.f.app.zoom = 1.;
|
||||
g.f.app.pan = Vector::ZERO;
|
||||
g.f.app.fit_to_view = false;
|
||||
choose(&mut g.f.app, SelectionTarget::Edge(edge), Choice::Replace);
|
||||
assert_eq!(g.f.app.selected, edge);
|
||||
let view = projection::project_view(g.f.app.project(), g.f.diagram);
|
||||
assert!(view.edges.iter().any(|e| e.id == edge));
|
||||
assert_eq!(
|
||||
crate::route_edit::attachment_node(
|
||||
g.f.app.project(),
|
||||
&g.f.app.project().diagrams[&g.f.diagram],
|
||||
&view,
|
||||
edge,
|
||||
EdgeEnd::Source,
|
||||
)
|
||||
.unwrap()
|
||||
.id,
|
||||
g.f.node
|
||||
);
|
||||
(g, edge)
|
||||
}
|
||||
|
||||
fn packet(g: &Group, edge: Id, captured: Context, attachment: bool) -> RouteEvent {
|
||||
let mut route =
|
||||
crate::route_edit::stored_route(&g.f.app.project().diagrams[&g.f.diagram], edge);
|
||||
if attachment {
|
||||
route.source_attachment = Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Top,
|
||||
offset: 0.25,
|
||||
});
|
||||
RouteEvent::CommitAttachment(captured, route, EdgeEnd::Source, g.f.node)
|
||||
} else {
|
||||
route.waypoints[0] = xy(750., 450.);
|
||||
RouteEvent::Commit(captured, route, Some(0))
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_route_noop(app: &mut App, event: RouteEvent) {
|
||||
let document = app.document.snapshot();
|
||||
let selected = selection(app);
|
||||
let context = app.route_context();
|
||||
let camera = (app.pan, app.zoom, app.canvas_epoch, app.camera_epoch);
|
||||
let ownership = (app.allocation_drag.epoch, app.allocation_drag.arrange_next);
|
||||
let press = app.allocation_drag.active.as_ref().map(|a| a.press.clone());
|
||||
let preview = app.allocation_drag.preview.clone();
|
||||
let feedback = app.allocation_drag.feedback.as_ref().map(|f| {
|
||||
(
|
||||
f.press.token,
|
||||
f.text.clone(),
|
||||
f.refused,
|
||||
f.targets.clone(),
|
||||
f.inspection_targets.clone(),
|
||||
)
|
||||
});
|
||||
let handles = (app.selected_bend, app.selected_attachment);
|
||||
let interaction = app.source_symbols.interaction;
|
||||
let status = app.status.clone();
|
||||
let _ = app.update(Message::Route(event));
|
||||
assert_eq!(selection(app), selected);
|
||||
assert_eq!(app.route_context(), context);
|
||||
assert_eq!(
|
||||
(app.pan, app.zoom, app.canvas_epoch, app.camera_epoch),
|
||||
camera
|
||||
);
|
||||
assert_eq!(
|
||||
(app.allocation_drag.epoch, app.allocation_drag.arrange_next),
|
||||
ownership
|
||||
);
|
||||
match (press, app.allocation_drag.active.as_ref()) {
|
||||
(Some(before), Some(after)) => assert!(Arc::ptr_eq(&before, &after.press)),
|
||||
(None, None) => {}
|
||||
_ => panic!("stale route packet changed the active Allocation token"),
|
||||
}
|
||||
match (preview, app.allocation_drag.preview.as_ref()) {
|
||||
(Some(before), Some(after)) => assert!(Arc::ptr_eq(&before, after)),
|
||||
(None, None) => {}
|
||||
_ => panic!("stale route packet changed the Allocation preview"),
|
||||
}
|
||||
assert_eq!(
|
||||
app.allocation_drag.feedback.as_ref().map(|f| (
|
||||
f.press.token,
|
||||
f.text.clone(),
|
||||
f.refused,
|
||||
f.targets.clone(),
|
||||
f.inspection_targets.clone(),
|
||||
)),
|
||||
feedback
|
||||
);
|
||||
assert_eq!((app.selected_bend, app.selected_attachment), handles);
|
||||
assert_eq!(app.source_symbols.interaction, interaction);
|
||||
assert_eq!(app.status, status);
|
||||
assert!(Arc::ptr_eq(&document, &app.document.snapshot()));
|
||||
assert_eq!(app.source_workspace.bundle(), document.bundle);
|
||||
}
|
||||
|
||||
fn stale_route_preserves_new_group(attachment: bool, escape: bool) {
|
||||
let (mut g, edge) = routed_group();
|
||||
let old = g.f.app.route_context().unwrap();
|
||||
let delayed = packet(&g, edge, old, attachment);
|
||||
if escape {
|
||||
let _ = g.f.app.update(Message::Escape);
|
||||
assert_ne!(g.f.app.route_context(), Some(old));
|
||||
}
|
||||
select(&mut g.f.app, &[g.an, g.yn]);
|
||||
let _ = g.f.app.update(Message::WorkDrag(Event::ArrangeNext));
|
||||
assert!(g.f.app.allocation_drag.arrange_next);
|
||||
if !escape {
|
||||
assert_eq!(g.f.app.route_context(), Some(old));
|
||||
assert_ne!(g.f.app.selected, edge);
|
||||
}
|
||||
assert_route_noop(&mut g.f.app, delayed.clone());
|
||||
let before = g.f.app.project().clone();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let selected = selection(&g.f.app);
|
||||
let from = node_point(&g.f.app, g.an);
|
||||
let to = from + Vector::new(400., 0.);
|
||||
let mut state = CanvasState::default();
|
||||
let press = begin(&mut g.f.app, &mut state, from);
|
||||
assert_eq!(press.mode, Mode::Arrange);
|
||||
move_pointer(&mut g.f.app, &mut state, to);
|
||||
assert!(g.f.app.allocation_drag.preview.is_some());
|
||||
if !escape {
|
||||
assert_eq!(g.f.app.route_context(), Some(old));
|
||||
assert_ne!(g.f.app.selected, edge);
|
||||
}
|
||||
assert_route_noop(&mut g.f.app, delayed);
|
||||
release(&mut g.f.app, &mut state, to);
|
||||
let mut expected = before.clone();
|
||||
let diagram = expected.diagrams.get_mut(&g.f.diagram).unwrap();
|
||||
diagram.nodes.get_mut(&g.an).unwrap().position = xy(500., 100.);
|
||||
diagram.nodes.get_mut(&g.f.node).unwrap().position = xy(540., 200.);
|
||||
diagram.nodes.get_mut(&g.yn).unwrap().position = xy(540., 600.);
|
||||
// Both endpoint placements move by (400, 0); the saved pin follows once,
|
||||
// while label offset and endpoint attachment settings stay unchanged.
|
||||
diagram
|
||||
.routes
|
||||
.iter_mut()
|
||||
.find(|r| r.edge == edge)
|
||||
.unwrap()
|
||||
.waypoints = vec![xy(1100., 400.)];
|
||||
assert_eq!(selection(&g.f.app), selected);
|
||||
exact_history(&mut g.f.app, &before, &source, &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_route_commit_preserves_arrange_arm_and_live_group() {
|
||||
stale_route_preserves_new_group(false, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_route_attachment_preserves_arrange_arm_and_live_group() {
|
||||
stale_route_preserves_new_group(true, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_context_route_commit_after_selection_preserves_arrange_arm_and_live_group() {
|
||||
stale_route_preserves_new_group(false, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_context_route_attachment_after_selection_preserves_arrange_arm_and_live_group() {
|
||||
stale_route_preserves_new_group(true, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_route_context_fields_independently_reject_before_retirement() {
|
||||
for attachment in [false, true] {
|
||||
let (mut g, edge) = routed_group();
|
||||
let current = g.f.app.route_context().unwrap();
|
||||
// The selected edge and route payload are valid. Each capture mismatch
|
||||
// is isolated; no nonexistent route session can mask admission.
|
||||
for captured in [
|
||||
Context {
|
||||
document: Id::new_v4(),
|
||||
..current
|
||||
},
|
||||
Context {
|
||||
diagram: Id::new_v4(),
|
||||
..current
|
||||
},
|
||||
Context {
|
||||
revision: current.revision + 1,
|
||||
..current
|
||||
},
|
||||
Context {
|
||||
epoch: current.epoch + 1,
|
||||
..current
|
||||
},
|
||||
] {
|
||||
let event = packet(&g, edge, captured, attachment);
|
||||
assert_route_noop(&mut g.f.app, event);
|
||||
}
|
||||
// Hold the captured packet fixed and advance the live context instead.
|
||||
let event = packet(&g, edge, current, attachment);
|
||||
g.f.app.canvas_epoch += 1;
|
||||
assert_route_noop(&mut g.f.app, event.clone());
|
||||
g.f.app.canvas_epoch = current.epoch;
|
||||
g.f.app.active_diagram = None;
|
||||
assert_route_noop(&mut g.f.app, event);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_route_commits_without_session_preserve_exact_route_history() {
|
||||
for attachment in [false, true] {
|
||||
let (mut g, edge) = routed_group();
|
||||
let current = g.f.app.route_context().unwrap();
|
||||
let event = packet(&g, edge, current, attachment);
|
||||
let before = g.f.app.project().clone();
|
||||
let source = g.f.app.document.bundle().clone();
|
||||
let revision = g.f.app.document.revision();
|
||||
assert!(g.f.app.connection.is_none());
|
||||
assert!(g.f.app.selected_attachment.is_none());
|
||||
let _ = g.f.app.update(Message::Route(event));
|
||||
assert_eq!(g.f.app.document.revision(), revision + 1);
|
||||
assert_eq!(g.f.app.selected, edge);
|
||||
assert_eq!(
|
||||
g.f.app.selected_bend,
|
||||
if attachment { None } else { Some((edge, 0)) }
|
||||
);
|
||||
let mut expected = before.clone();
|
||||
let route = expected
|
||||
.diagrams
|
||||
.get_mut(&g.f.diagram)
|
||||
.unwrap()
|
||||
.routes
|
||||
.iter_mut()
|
||||
.find(|r| r.edge == edge)
|
||||
.unwrap();
|
||||
if attachment {
|
||||
route.source_attachment = Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Top,
|
||||
offset: 0.25,
|
||||
});
|
||||
} else {
|
||||
route.waypoints = vec![xy(750., 450.)];
|
||||
}
|
||||
exact_history(&mut g.f.app, &before, &source, &expected);
|
||||
}
|
||||
}
|
||||
@@ -161,7 +161,7 @@ fn stale_gesture_packets_preserve_navigation_and_a_new_live_cancel_still_works()
|
||||
.update(Message::WorkDrag(Event::Cancel(current.token)));
|
||||
assert!(f.app.allocation_drag.active.is_none());
|
||||
assert!(f.app.allocation_drag.epoch > epoch);
|
||||
assert_eq!(f.app.status, "Work drag canceled");
|
||||
assert_eq!(f.app.status, "Drag canceled");
|
||||
assert!(Arc::ptr_eq(&before, &f.app.document.snapshot()));
|
||||
assert_eq!(f.app.source_workspace.bundle(), before.bundle);
|
||||
}
|
||||
|
||||
@@ -27,30 +27,11 @@ pub enum Event {
|
||||
Cancel,
|
||||
}
|
||||
|
||||
pub fn subscription(app: &App) -> Subscription<Message> {
|
||||
if app.architecture.as_ref().is_some_and(State::inline) {
|
||||
iced::event::listen_with(captured_escape)
|
||||
} else {
|
||||
Subscription::none()
|
||||
}
|
||||
}
|
||||
|
||||
fn captured_escape(
|
||||
event: iced::Event,
|
||||
status: iced::event::Status,
|
||||
_: iced::window::Id,
|
||||
) -> Option<Message> {
|
||||
// A focused Iced text input captures Escape while dropping its focus. Only
|
||||
// inline architecture naming opts into also cancelling that same keypress.
|
||||
(status == iced::event::Status::Captured
|
||||
&& matches!(
|
||||
event,
|
||||
iced::Event::Keyboard(iced::keyboard::Event::KeyPressed {
|
||||
key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
|
||||
..
|
||||
})
|
||||
))
|
||||
.then_some(Message::Architecture(Event::CapturedEscape))
|
||||
pub(super) fn captured_escape_message(app: &App) -> Option<Message> {
|
||||
app.architecture
|
||||
.as_ref()
|
||||
.is_some_and(State::inline)
|
||||
.then_some(Message::Architecture(Event::CapturedEscape))
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -138,7 +119,7 @@ pub fn validate_saved(p: &Project, s: &Saved) -> Result<(), String> {
|
||||
.diagrams
|
||||
.get(&s.diagram)
|
||||
.ok_or("The creation draft's diagram is missing.")?;
|
||||
if matches!(d.projection, ProjectionKind::StateMachine { .. })
|
||||
if !d.projection.is_architecture()
|
||||
|| s.query.len() > 16384
|
||||
|| s.page > 1_000_000
|
||||
|| s.point
|
||||
@@ -180,7 +161,7 @@ pub fn validate_saved(p: &Project, s: &Saved) -> Result<(), String> {
|
||||
}
|
||||
fn context_kinds(p: &Project, d: &Diagram) -> Vec<Kind> {
|
||||
let mut values = match (d.layer, d.projection) {
|
||||
(_, ProjectionKind::StateMachine { .. }) => vec![],
|
||||
(_, ProjectionKind::StateMachine { .. } | ProjectionKind::Scenario { .. }) => vec![],
|
||||
(Layer::Oa, ProjectionKind::FunctionalDataflow) => vec![Kind::Activity],
|
||||
(Layer::Sa, ProjectionKind::FunctionalDataflow) => vec![Kind::Function],
|
||||
(Layer::Oa, ProjectionKind::Capabilities) => vec![
|
||||
@@ -208,11 +189,12 @@ pub fn kinds(app: &App) -> Vec<Kind> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
fn compatible(p: &Project, d: &Diagram, id: Id) -> bool {
|
||||
p.elements.get(&id).is_some_and(|e| {
|
||||
e.kind() != Kind::Port
|
||||
&& d.projection.includes(e.kind())
|
||||
&& (e.layer() == d.layer || d.projection == ProjectionKind::Traceability)
|
||||
})
|
||||
d.projection.is_architecture()
|
||||
&& p.elements.get(&id).is_some_and(|e| {
|
||||
e.kind() != Kind::Port
|
||||
&& d.projection.includes(e.kind())
|
||||
&& (e.layer() == d.layer || d.projection == ProjectionKind::Traceability)
|
||||
})
|
||||
}
|
||||
fn suggested(p: &Project, d: &Diagram, kind: Kind) -> bool {
|
||||
// Existing System remains a useful choice even when the singleton exists.
|
||||
@@ -257,6 +239,17 @@ pub fn candidates(app: &App) -> Vec<(Id, String, bool)> {
|
||||
}
|
||||
impl App {
|
||||
pub(super) fn architecture_event(&mut self, event: Event) -> Task<Message> {
|
||||
if matches!(
|
||||
&event,
|
||||
Event::Start(..) | Event::Allocate(..) | Event::Existing(..)
|
||||
) && !self
|
||||
.active_diagram
|
||||
.and_then(|id| self.project().diagrams.get(&id))
|
||||
.is_some_and(|d| d.projection.is_architecture())
|
||||
{
|
||||
self.status = "Choose an architecture view before adding architecture content.".into();
|
||||
return Task::none();
|
||||
}
|
||||
match event {
|
||||
Event::Start(_, point) | Event::Allocate(_, _, point) | Event::Existing(point) => {
|
||||
if self.architecture.is_some() {
|
||||
@@ -301,6 +294,17 @@ impl App {
|
||||
_ => return Task::none(),
|
||||
};
|
||||
let placing = point.is_none() && matches!(intent, Intent::Create { .. });
|
||||
let filter = if matches!(intent, Intent::Existing { .. })
|
||||
&& self
|
||||
.project()
|
||||
.diagrams
|
||||
.get(&diagram)
|
||||
.is_some_and(|d| d.projection == ProjectionKind::Traceability)
|
||||
{
|
||||
Filter::AllCompatible
|
||||
} else {
|
||||
Filter::Context
|
||||
};
|
||||
let saved = Saved {
|
||||
version: 1,
|
||||
base: oa_core::transitions::project_fingerprint(self.project()),
|
||||
@@ -309,7 +313,7 @@ impl App {
|
||||
point,
|
||||
placing,
|
||||
query: String::new(),
|
||||
filter: Filter::Context,
|
||||
filter,
|
||||
show_placed: false,
|
||||
page: 0,
|
||||
};
|
||||
|
||||
@@ -229,13 +229,7 @@ pub fn view(app: &App) -> Element<'_, Message> {
|
||||
content = content.push(group("Connections"));
|
||||
for connection in crate::connection_tool::Tool::for_layer(app.layer) {
|
||||
let d = &app.project().diagrams[&app.active_diagram.unwrap()];
|
||||
let kind = match connection {
|
||||
crate::connection_tool::Tool::Interaction => Kind::Activity,
|
||||
crate::connection_tool::Tool::FunctionalExchange => Kind::Function,
|
||||
crate::connection_tool::Tool::CommunicationMean => Kind::Entity,
|
||||
crate::connection_tool::Tool::BoundaryExchange => Kind::System,
|
||||
};
|
||||
if !d.projection.includes(kind) {
|
||||
if !connection.available_in(app.layer, d.projection) {
|
||||
continue;
|
||||
}
|
||||
content = content.push(tool(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
mod traceability;
|
||||
|
||||
fn setup(layer: Layer) -> App {
|
||||
let mut app = App::with_project(Project::empty());
|
||||
@@ -66,6 +67,7 @@ fn architecture_f2_routes_selected_node_to_inline_rename_and_exact_undo() {
|
||||
let camera = (app.zoom, app.pan);
|
||||
let bounds = iced::Rectangle::new(iced::Point::ORIGIN, iced::Size::new(600., 380.));
|
||||
let canvas = crate::diagram::DiagramCanvas {
|
||||
selection: None,
|
||||
project: app.project(),
|
||||
view_index: None,
|
||||
diagram: app.active_diagram.unwrap(),
|
||||
@@ -232,65 +234,6 @@ fn architecture_stale_submit_keeps_create_and_rename_visible_and_exact() {
|
||||
}
|
||||
}
|
||||
|
||||
fn key_event(named: iced::keyboard::key::Named) -> iced::Event {
|
||||
use iced::keyboard;
|
||||
iced::Event::Keyboard(keyboard::Event::KeyPressed {
|
||||
key: keyboard::Key::Named(named),
|
||||
modified_key: keyboard::Key::Named(named),
|
||||
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::Escape),
|
||||
location: keyboard::Location::Standard,
|
||||
modifiers: keyboard::Modifiers::empty(),
|
||||
text: None,
|
||||
repeat: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn focused_text_input_escape(name: &str) -> Message {
|
||||
use iced::advanced::{Layout, Shell, layout, widget};
|
||||
let mut field: iced::Element<'_, (), iced::Theme, ()> = text_input("Engineering name", name)
|
||||
.id("architecture-name")
|
||||
.on_input(|_| ())
|
||||
.into();
|
||||
let mut tree = widget::Tree::new(field.as_widget());
|
||||
let size = iced::Size::new(300., 40.);
|
||||
let node =
|
||||
field
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree, &(), &layout::Limits::new(iced::Size::ZERO, size));
|
||||
tree.state
|
||||
.downcast_mut::<iced::widget::text_input::State<()>>()
|
||||
.focus();
|
||||
let escape = key_event(iced::keyboard::key::Named::Escape);
|
||||
let mut messages = Vec::new();
|
||||
let mut shell = Shell::new(&mut messages);
|
||||
field.as_widget_mut().update(
|
||||
&mut tree,
|
||||
&escape,
|
||||
Layout::new(&node),
|
||||
iced::mouse::Cursor::Unavailable,
|
||||
&(),
|
||||
&mut iced::advanced::clipboard::Null,
|
||||
&mut shell,
|
||||
&iced::Rectangle::new(iced::Point::ORIGIN, size),
|
||||
);
|
||||
assert!(
|
||||
shell.is_event_captured(),
|
||||
"Iced consumes focused-input Escape"
|
||||
);
|
||||
assert!(
|
||||
!tree
|
||||
.state
|
||||
.downcast_ref::<iced::widget::text_input::State<()>>()
|
||||
.is_focused()
|
||||
);
|
||||
captured_escape(
|
||||
escape,
|
||||
iced::event::Status::Captured,
|
||||
iced::window::Id::unique(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn architecture_first_focused_input_escape_cancels_create_and_rename() {
|
||||
for rename in [false, true] {
|
||||
@@ -310,8 +253,9 @@ fn architecture_first_focused_input_escape_cancels_create_and_rename() {
|
||||
let name = " Unaccepted long engineering name 雨 ";
|
||||
send(&mut app, Event::Name(name.into()));
|
||||
assert!(app.architecture.as_ref().unwrap().inline());
|
||||
let message = focused_text_input_escape(name);
|
||||
let _ = app.update(message);
|
||||
let mut messages = crate::app::escape::tests::focused_input_messages(&app);
|
||||
assert_eq!(messages.len(), 1);
|
||||
let _ = app.update(messages.remove(0));
|
||||
assert!(app.architecture.is_none());
|
||||
assert!(inline_editor(&app).is_none());
|
||||
assert_eq!(app.status, "Cancelled · Select / move");
|
||||
@@ -341,8 +285,8 @@ fn architecture_captured_escape_does_not_cancel_other_controls_or_placement() {
|
||||
let before = app.document.bundle().clone();
|
||||
let status = app.status.clone();
|
||||
let epoch = app.canvas_epoch;
|
||||
let message = focused_text_input_escape("Other field or existing-element search");
|
||||
let _ = app.update(message);
|
||||
let messages = crate::app::escape::tests::focused_input_messages(&app);
|
||||
assert!(messages.is_empty());
|
||||
assert_eq!(
|
||||
app.architecture
|
||||
.as_ref()
|
||||
@@ -354,19 +298,7 @@ fn architecture_captured_escape_does_not_cancel_other_controls_or_placement() {
|
||||
assert_eq!(app.canvas_epoch, epoch);
|
||||
}
|
||||
assert!(
|
||||
captured_escape(
|
||||
key_event(iced::keyboard::key::Named::Escape),
|
||||
iced::event::Status::Ignored,
|
||||
iced::window::Id::unique(),
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
captured_escape(
|
||||
key_event(iced::keyboard::key::Named::Enter),
|
||||
iced::event::Status::Captured,
|
||||
iced::window::Id::unique(),
|
||||
)
|
||||
.is_none()
|
||||
crate::app::escape::tests::focused_input_key(&app, iced::keyboard::key::Named::Enter,)
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn traceability_existing_defaults_show_opposite_layer_and_place_only_one_node() {
|
||||
let mut project = Project::empty();
|
||||
let sa = project
|
||||
.add_element(Kind::Function, Layer::Sa, "Deliver report", None)
|
||||
.unwrap();
|
||||
let system = project
|
||||
.add_element(Kind::System, Layer::Sa, "System", None)
|
||||
.unwrap();
|
||||
let diagram = project.ensure_diagram(Layer::Oa);
|
||||
project.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Traceability;
|
||||
let mut app = App::with_project(project);
|
||||
app.page = Page::Diagram;
|
||||
app.layer = Layer::Oa;
|
||||
app.active_diagram = Some(diagram);
|
||||
let before = app.document.snapshot();
|
||||
send(&mut app, Event::Existing(None));
|
||||
assert_eq!(
|
||||
app.architecture.as_ref().unwrap().saved.filter,
|
||||
Filter::AllCompatible
|
||||
);
|
||||
let listed = candidates(&app);
|
||||
assert!(listed.iter().any(|(id, _, shown)| *id == sa && !shown));
|
||||
assert!(listed.iter().any(|(id, _, shown)| *id == system && !shown));
|
||||
send(&mut app, Event::Pick(sa));
|
||||
assert!(app.architecture.as_ref().unwrap().saved.placing);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
let context = app.route_context().unwrap();
|
||||
let point = Position { x: 345., y: 215. };
|
||||
send(&mut app, Event::Click(context, point));
|
||||
assert!(app.architecture.is_none(), "{}", app.status);
|
||||
assert_eq!(app.active_diagram, Some(diagram));
|
||||
let placed = app.project().diagrams[&diagram]
|
||||
.nodes
|
||||
.values()
|
||||
.find(|n| n.element == sa)
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert_eq!(placed.position, point);
|
||||
let mut expected = before.decoded.project.clone();
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.insert(placed.id, placed);
|
||||
assert_eq!(app.project(), &expected);
|
||||
let accepted = app.document.bundle().clone();
|
||||
let _ = app.update(Message::Undo);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
let _ = app.update(Message::Redo);
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_eq!(app.document.bundle(), &accepted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traceability_default_does_not_change_creation_or_ordinary_picker_guards() {
|
||||
let mut app = setup(Layer::Oa);
|
||||
let diagram = app.active_diagram.unwrap();
|
||||
send(&mut app, Event::Existing(None));
|
||||
assert_eq!(
|
||||
app.architecture.as_ref().unwrap().saved.filter,
|
||||
Filter::Context
|
||||
);
|
||||
send(&mut app, Event::Cancel);
|
||||
let _ = app.update(Message::Projection(ProjectionKind::Traceability));
|
||||
send(&mut app, Event::Start(Kind::Entity, None));
|
||||
assert_eq!(
|
||||
app.architecture.as_ref().unwrap().saved.filter,
|
||||
Filter::Context
|
||||
);
|
||||
send(&mut app, Event::Cancel);
|
||||
assert_eq!(app.active_diagram, Some(diagram));
|
||||
|
||||
let mut project = app.project().clone();
|
||||
let sa = project
|
||||
.add_element(Kind::Function, Layer::Sa, "Other layer", None)
|
||||
.unwrap();
|
||||
let port = Id::new_v4();
|
||||
project.elements.insert(
|
||||
port,
|
||||
oa_core::Element {
|
||||
id: port,
|
||||
alias: "legacy_port".into(),
|
||||
name: "Port".into(),
|
||||
description: String::new(),
|
||||
parent: Some(sa),
|
||||
body: ElementBody::shared_in(
|
||||
Layer::Sa,
|
||||
SharedBody::Port {
|
||||
contract: PortContract::Legacy,
|
||||
legacy: Some(LegacyPortContract {
|
||||
direction: PortDirection::InOut,
|
||||
interface: None,
|
||||
}),
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
oa_core::validate_candidate(&project).unwrap();
|
||||
for projection in [ProjectionKind::Overview, ProjectionKind::Traceability] {
|
||||
let mut p = project.clone();
|
||||
p.diagrams.get_mut(&diagram).unwrap().projection = projection;
|
||||
let mut trial = App::with_project(p);
|
||||
trial.page = Page::Diagram;
|
||||
trial.active_diagram = Some(diagram);
|
||||
trial.layer = Layer::Oa;
|
||||
let before = trial.document.bundle().clone();
|
||||
send(&mut trial, Event::Existing(None));
|
||||
send(&mut trial, Event::Filter(Filter::AllCompatible));
|
||||
assert_eq!(
|
||||
candidates(&trial).iter().any(|(id, _, _)| *id == sa),
|
||||
projection == ProjectionKind::Traceability
|
||||
);
|
||||
assert!(!candidates(&trial).iter().any(|(id, _, _)| *id == port));
|
||||
send(&mut trial, Event::Pick(port));
|
||||
assert!(!trial.architecture.as_ref().unwrap().saved.placing);
|
||||
send(&mut trial, Event::Cancel);
|
||||
assert_eq!(trial.document.bundle(), &before);
|
||||
}
|
||||
}
|
||||
@@ -221,6 +221,7 @@ fn architecture_canvas_left_click_uses_world_coordinate_once_at_zoom_and_pan() {
|
||||
y: (local.y - app.pan.y) / app.zoom,
|
||||
};
|
||||
let canvas = crate::diagram::DiagramCanvas {
|
||||
selection: None,
|
||||
project: app.project(),
|
||||
view_index: None,
|
||||
diagram: app.active_diagram.unwrap(),
|
||||
@@ -298,6 +299,7 @@ fn architecture_f2_rename_preserves_identity_placement_and_atomic_history() {
|
||||
let diagrams = app.project().diagrams.clone();
|
||||
let camera = (app.zoom, app.pan);
|
||||
let canvas = crate::diagram::DiagramCanvas {
|
||||
selection: None,
|
||||
project: app.project(),
|
||||
view_index: None,
|
||||
diagram: app.active_diagram.unwrap(),
|
||||
|
||||
@@ -180,10 +180,36 @@ async fn mounted_scenario_use_delete_keeps_definition_and_second_use_and_rejects
|
||||
send(&mut mounted, &mut app, Message::ConfirmDelete(stale)).await;
|
||||
assert!(app.delete_pending, "old token does not cancel new dialog");
|
||||
// Keep selection and epoch deliberately unchanged: owner is an independent witness.
|
||||
let captured = app.scenario_context().unwrap();
|
||||
assert_eq!(captured.scenario, owners[0]);
|
||||
assert_eq!(
|
||||
app.delete_target.as_ref().unwrap().behavior_owner,
|
||||
Some(owners[0])
|
||||
);
|
||||
app.behavior.active_owner = Some(owners[1]);
|
||||
app.reconcile_scenario_workspace();
|
||||
let other = app.scenario_context().unwrap();
|
||||
assert_eq!(other.scenario, owners[1]);
|
||||
assert_eq!(
|
||||
other.representation,
|
||||
crate::behavior::scenario_layout::Representation::Derived { owner: owners[1] }
|
||||
);
|
||||
assert_eq!(other.epoch, captured.epoch);
|
||||
assert_eq!(app.selected, uses[0]);
|
||||
assert!(
|
||||
app.delete_target.as_ref().unwrap().snapshot.valid(&app),
|
||||
"the independent owner guard must reject an otherwise current token"
|
||||
);
|
||||
send(&mut mounted, &mut app, Message::ConfirmDelete(token)).await;
|
||||
assert_eq!(app.document.bundle(), &original);
|
||||
assert!(!app.delete_pending && app.delete_target.is_none());
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
app.behavior.active_owner = Some(owners[0]);
|
||||
// Restore both owner and qualified presentation before mounting pointer input.
|
||||
// Passive reports from the previous owner cannot repair an inconsistent fixture.
|
||||
app.reconcile_scenario_workspace();
|
||||
assert_eq!(app.scenario_context().unwrap().scenario, owners[0]);
|
||||
assert_eq!(app.selected, uses[0]);
|
||||
mounted.settle(&mut app).await;
|
||||
select(&mut mounted, &mut app, uses[0]).await;
|
||||
let token = delete(&mut mounted, &mut app, false).await;
|
||||
@@ -518,9 +544,16 @@ async fn mounted_qualified_process_child_delete_refuses_outer_reference_and_shar
|
||||
.await;
|
||||
assert!(messages.iter().any(|message| matches!(
|
||||
message,
|
||||
Message::TopologyCanvas(topology::CanvasEvent::SelectQualified(..))
|
||||
Message::DiagramSelection(multiselect::Event::Choose(
|
||||
_, crate::diagram_usage::Target::ProcessOccurrence(actual), multiselect::Choice::Replace
|
||||
)) if actual == &endpoint
|
||||
)));
|
||||
assert_eq!(app.selected, references[0]);
|
||||
assert_eq!(app.selected, f.nodes[0]);
|
||||
assert!(app.draft.is_none(), "Qualified inspection stays read-only");
|
||||
assert_eq!(
|
||||
app.behavior.topology.selection_address().unwrap().endpoint,
|
||||
endpoint
|
||||
);
|
||||
assert!(
|
||||
app.behavior
|
||||
.topology
|
||||
|
||||
@@ -0,0 +1,723 @@
|
||||
//! Context help is a reading overlay, not a workspace navigation or edit.
|
||||
use super::*;
|
||||
use crate::diagram_usage::Target;
|
||||
use crate::guide::Topic;
|
||||
|
||||
fn send(app: &mut App, message: Message) {
|
||||
// Do not poll I/O tasks: exercise the same admission boundary as the UI.
|
||||
let _ = app.update(message);
|
||||
}
|
||||
|
||||
fn architecture() -> (App, Id, Id, Id) {
|
||||
let mut project = Project::empty();
|
||||
let a = project
|
||||
.add_element(Kind::Function, Layer::Sa, "Send", None)
|
||||
.unwrap();
|
||||
let b = project
|
||||
.add_element(Kind::Function, Layer::Sa, "Receive", None)
|
||||
.unwrap();
|
||||
let diagram = project.ensure_diagram(Layer::Sa);
|
||||
project.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::FunctionalDataflow;
|
||||
let a = project.place(diagram, a, Position { x: 20., y: 20. });
|
||||
let b = project.place(diagram, b, Position { x: 400., y: 20. });
|
||||
let mut app = App::with_project(project);
|
||||
app.page = Page::Diagram;
|
||||
app.layer = Layer::Sa;
|
||||
app.active_diagram = Some(diagram);
|
||||
app.selected = diagram;
|
||||
app.refresh_draft();
|
||||
app.reconcile_multiselect();
|
||||
(app, diagram, a, b)
|
||||
}
|
||||
|
||||
fn choose(app: &mut App, placement: Id, choice: multiselect::Choice) {
|
||||
let context = app.multiselect_context().unwrap();
|
||||
send(
|
||||
app,
|
||||
Message::DiagramSelection(multiselect::Event::Choose(
|
||||
context,
|
||||
Target::Placement(placement),
|
||||
choice,
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_help_preserves_group_property_draft_camera_and_model() {
|
||||
let (mut app, diagram, a, b) = architecture();
|
||||
choose(&mut app, a, multiselect::Choice::Replace);
|
||||
choose(&mut app, b, multiselect::Choice::Toggle);
|
||||
send(
|
||||
&mut app,
|
||||
Message::Field("/name".into(), "Uncommitted name 雨".into()),
|
||||
);
|
||||
assert!(app.draft_dirty());
|
||||
app.zoom = 0.73;
|
||||
app.pan = iced::Vector::new(31., -57.);
|
||||
let selected = app.selected;
|
||||
let selection = app.multiselect_snapshot().unwrap().targets().to_vec();
|
||||
assert_eq!(selection.len(), 2);
|
||||
let draft = serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap();
|
||||
let before = app.document.snapshot();
|
||||
let camera = (app.zoom, app.pan);
|
||||
|
||||
send(&mut app, Message::ContextHelp(Topic::Nesting));
|
||||
assert!(app.context_help);
|
||||
for message in [
|
||||
Message::Page(Page::Catalog),
|
||||
Message::Select(diagram),
|
||||
Message::Apply,
|
||||
Message::RevertProperties,
|
||||
Message::Undo,
|
||||
Message::Delete,
|
||||
Message::Field("/name".into(), "Background mutation".into()),
|
||||
] {
|
||||
send(&mut app, message);
|
||||
}
|
||||
assert!(app.context_help);
|
||||
send(
|
||||
&mut app,
|
||||
Message::Guide(crate::guide::Event::Topic(Topic::Exchanges)),
|
||||
);
|
||||
assert_eq!(app.guide.topic, Topic::Exchanges);
|
||||
send(&mut app, Message::CloseContextHelp);
|
||||
|
||||
assert!(!app.context_help);
|
||||
assert_eq!(app.page, Page::Diagram);
|
||||
assert_eq!(app.active_diagram, Some(diagram));
|
||||
assert_eq!(app.selected, selected);
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
selection.as_slice()
|
||||
);
|
||||
assert_eq!((app.zoom, app.pan), camera);
|
||||
assert_eq!(
|
||||
serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap(),
|
||||
draft
|
||||
);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_help_escape_preserves_pending_behavior_form_and_blocks_submit() {
|
||||
use crate::behavior::states;
|
||||
let mut project = Project::empty();
|
||||
let system = project
|
||||
.add_element(Kind::System, Layer::Sa, "System", None)
|
||||
.unwrap();
|
||||
let machine = project
|
||||
.add_element(Kind::StateMachine, Layer::Sa, "Modes", Some(system))
|
||||
.unwrap();
|
||||
let region = project
|
||||
.add_element(Kind::Region, Layer::Sa, "Main", Some(machine))
|
||||
.unwrap();
|
||||
let state = project
|
||||
.add_element(Kind::State, Layer::Sa, "Ready", Some(region))
|
||||
.unwrap();
|
||||
let mut app = App::with_project(project);
|
||||
send(&mut app, Message::Select(state));
|
||||
send(&mut app, Message::Page(Page::Behavior));
|
||||
send(
|
||||
&mut app,
|
||||
Message::Behavior(behavior::Event::States(states::Event::Start(
|
||||
machine,
|
||||
states::Tool::Transition,
|
||||
state,
|
||||
))),
|
||||
);
|
||||
send(
|
||||
&mut app,
|
||||
Message::Behavior(behavior::Event::States(states::Event::Name(
|
||||
"Pending transition 雨".into(),
|
||||
))),
|
||||
);
|
||||
assert!(app.behavior.has_pending());
|
||||
let draft = app.behavior.recovery_snapshot().unwrap();
|
||||
let before = app.document.snapshot();
|
||||
let selected = app.selected;
|
||||
send(&mut app, Message::Help);
|
||||
assert!(app.context_help);
|
||||
assert_eq!(app.guide.topic, Topic::States);
|
||||
for event in [
|
||||
states::Event::Cancel,
|
||||
states::Event::Submit,
|
||||
states::Event::Name("Lost".into()),
|
||||
] {
|
||||
send(&mut app, Message::Behavior(behavior::Event::States(event)));
|
||||
}
|
||||
send(&mut app, Message::Page(Page::Catalog));
|
||||
send(&mut app, Message::Escape);
|
||||
assert!(!app.context_help);
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(app.selected, selected);
|
||||
assert_eq!(app.behavior.active_owner, Some(machine));
|
||||
assert!(app.behavior.has_pending());
|
||||
assert_eq!(app.behavior.recovery_snapshot().unwrap(), draft);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_help_retains_source_draft_and_rejects_background_source_input() {
|
||||
let (mut app, diagram, _, _) = architecture();
|
||||
send(&mut app, Message::Page(Page::Text));
|
||||
send(
|
||||
&mut app,
|
||||
Message::SourceEdit(text_editor::Action::SelectAll),
|
||||
);
|
||||
send(
|
||||
&mut app,
|
||||
Message::SourceEdit(text_editor::Action::Edit(text_editor::Edit::Paste(
|
||||
Arc::new("invalid unfinished source 雨".into()),
|
||||
))),
|
||||
);
|
||||
assert!(app.source_dirty());
|
||||
send(&mut app, Message::Page(Page::Diagram));
|
||||
let source = app.source_editor.text();
|
||||
let version = app.source_version;
|
||||
let before = app.document.snapshot();
|
||||
send(&mut app, Message::Help);
|
||||
assert!(app.context_help);
|
||||
assert_eq!(app.guide.topic, Topic::Nesting);
|
||||
for message in [
|
||||
Message::ApplySource,
|
||||
Message::RevertSource,
|
||||
Message::SourceEdit(text_editor::Action::Edit(text_editor::Edit::Paste(
|
||||
Arc::new("overwrite".into()),
|
||||
))),
|
||||
] {
|
||||
send(&mut app, message);
|
||||
}
|
||||
send(&mut app, Message::Escape);
|
||||
assert_eq!(app.page, Page::Diagram);
|
||||
assert_eq!(app.active_diagram, Some(diagram));
|
||||
assert!(app.source_dirty());
|
||||
assert_eq!(app.source_editor.text(), source);
|
||||
assert_eq!(app.source_version, version);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_help_f1_selects_scenario_topic_without_leaving_the_workspace() {
|
||||
let fixture = behavior::scenario::direct_tests::fixture();
|
||||
let mut app = App::with_project(fixture.project);
|
||||
send(&mut app, Message::Select(fixture.owner));
|
||||
send(&mut app, Message::Page(Page::Behavior));
|
||||
let before = app.document.snapshot();
|
||||
send(&mut app, Message::Help);
|
||||
assert!(app.context_help);
|
||||
assert_eq!(app.guide.topic, Topic::Scenarios);
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert!(app.scenario_focus_owner().is_none());
|
||||
assert!(!behavior::canvas_workspace::keyboard_owner_enabled(&app));
|
||||
send(&mut app, Message::Escape);
|
||||
assert!(!app.context_help);
|
||||
assert_eq!(app.selected, fixture.owner);
|
||||
assert_eq!(app.behavior.active_owner, Some(fixture.owner));
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_help_disables_allocation_input_including_early_work_drag_dispatch() {
|
||||
let mut project = Project::empty();
|
||||
let diagram = project.ensure_diagram(Layer::Oa);
|
||||
project.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Allocation;
|
||||
let mut app = App::with_project(project);
|
||||
assert!(app.allocation_input_owner());
|
||||
send(
|
||||
&mut app,
|
||||
Message::WorkDrag(allocation_drag::Event::ArrangeNext),
|
||||
);
|
||||
assert!(app.allocation_drag.arrange_next);
|
||||
send(&mut app, Message::Help);
|
||||
assert!(app.context_help);
|
||||
assert!(!app.allocation_input_owner());
|
||||
assert!(!app.allocation_drag.arrange_next);
|
||||
assert_eq!(app.status, "Arrange cancelled");
|
||||
let before = app.document.snapshot();
|
||||
send(
|
||||
&mut app,
|
||||
Message::WorkDrag(allocation_drag::Event::ArrangeNext),
|
||||
);
|
||||
assert!(!app.allocation_drag.arrange_next);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
send(&mut app, Message::Escape);
|
||||
assert!(app.allocation_input_owner());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_help_rejects_a_reference_picker_open_queued_from_the_inspector() {
|
||||
let mut project = Project::empty();
|
||||
let owner = project
|
||||
.add_element(Kind::DataType, Layer::Oa, "Record", None)
|
||||
.unwrap();
|
||||
if let Some(SharedBody::DataType { definition, .. }) =
|
||||
project.elements.get_mut(&owner).unwrap().shared_mut()
|
||||
{
|
||||
*definition = DataTypeDefinition::Record { supertype: None };
|
||||
}
|
||||
let mut app = App::with_project(project);
|
||||
send(&mut app, Message::Select(owner));
|
||||
let request = app.draft.as_ref().unwrap().reference_open(
|
||||
app.project(),
|
||||
"/body/Oa/Shared/DataType/definition/Record/supertype",
|
||||
iced::Rectangle {
|
||||
x: 790.,
|
||||
y: 400.,
|
||||
width: 278.,
|
||||
height: 32.,
|
||||
},
|
||||
);
|
||||
let before = serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap();
|
||||
send(&mut app, Message::ContextHelp(Topic::Nesting));
|
||||
assert!(app.context_help);
|
||||
send(&mut app, Message::FieldReferenceOpen(request));
|
||||
assert!(!app.reference_input_active());
|
||||
send(&mut app, Message::Escape);
|
||||
assert!(!app.context_help);
|
||||
assert_eq!(
|
||||
serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap(),
|
||||
before
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_help_accepts_live_process_viewport_and_rejects_stale_measurements() {
|
||||
use crate::behavior::topology::CanvasEvent;
|
||||
let mut project = Project::empty();
|
||||
let owner = project
|
||||
.add_element(Kind::Process, Layer::Oa, "Response process", None)
|
||||
.unwrap();
|
||||
let mut app = App::with_project(project);
|
||||
send(&mut app, Message::Select(owner));
|
||||
send(&mut app, Message::Page(Page::Behavior));
|
||||
let context = app.topology_context().unwrap();
|
||||
send(
|
||||
&mut app,
|
||||
Message::TopologyCanvas(CanvasEvent::Viewport(context, iced::Size::new(640., 480.))),
|
||||
);
|
||||
let initial = app.behavior.topology.camera_boundary();
|
||||
let before = app.document.snapshot();
|
||||
send(&mut app, Message::Help);
|
||||
assert!(app.context_help);
|
||||
assert_eq!(app.guide.topic, Topic::Chains);
|
||||
|
||||
let resized = iced::Size::new(420., 330.);
|
||||
let context = app.topology_context().unwrap();
|
||||
send(
|
||||
&mut app,
|
||||
Message::TopologyCanvas(CanvasEvent::Viewport(context, resized)),
|
||||
);
|
||||
let measured = app.behavior.topology.camera_boundary();
|
||||
assert!(
|
||||
measured != initial,
|
||||
"Help must admit passive viewport measurements"
|
||||
);
|
||||
assert!(app.context_help);
|
||||
let epoch = app.canvas_epoch;
|
||||
for field in 0..3 {
|
||||
let mut stale = app.topology_context().unwrap();
|
||||
match field {
|
||||
0 => stale.document = Id::new_v4(),
|
||||
1 => stale.owner = Id::new_v4(),
|
||||
_ => stale.revision += 1,
|
||||
}
|
||||
send(
|
||||
&mut app,
|
||||
Message::TopologyCanvas(CanvasEvent::Viewport(stale, iced::Size::new(999., 777.))),
|
||||
);
|
||||
assert!(app.behavior.topology.camera_boundary() == measured);
|
||||
assert_eq!(app.canvas_epoch, epoch);
|
||||
}
|
||||
|
||||
send(&mut app, Message::CloseContextHelp);
|
||||
assert!(!app.context_help);
|
||||
assert!(app.behavior.topology.camera_boundary() == measured);
|
||||
let context = app.topology_context().unwrap();
|
||||
let epoch = app.canvas_epoch;
|
||||
send(
|
||||
&mut app,
|
||||
Message::TopologyCanvas(CanvasEvent::Viewport(context, resized)),
|
||||
);
|
||||
assert_eq!(
|
||||
app.canvas_epoch, epoch,
|
||||
"The size observed behind Help is already current"
|
||||
);
|
||||
let context = app.topology_context().unwrap();
|
||||
send(
|
||||
&mut app,
|
||||
Message::TopologyCanvas(CanvasEvent::Viewport(context, iced::Size::new(700., 500.))),
|
||||
);
|
||||
assert!(app.behavior.topology.camera_boundary() != measured);
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(app.selected, owner);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
|
||||
async fn help_key(
|
||||
mounted: &mut crate::behavior::canvas_workspace::tests::Mounted,
|
||||
app: &mut App,
|
||||
event: iced::Event,
|
||||
) -> Vec<Message> {
|
||||
let (mut messages, statuses) = mounted.input_with_status(
|
||||
app,
|
||||
std::slice::from_ref(&event),
|
||||
iced::mouse::Cursor::Unavailable,
|
||||
);
|
||||
super::escape::tests::subscriptions(app, event, statuses[0], &mut messages);
|
||||
for message in messages.iter().cloned() {
|
||||
let task = app.update(message);
|
||||
mounted.perform(app, task).await;
|
||||
}
|
||||
messages
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_context_help_keyboard_scroll_preserves_inspector_focus_and_exact_caret() {
|
||||
use crate::behavior::canvas_workspace::tests::{Mounted, character, key};
|
||||
use iced::keyboard::key::Named;
|
||||
let (mut app, diagram, a, _) = architecture();
|
||||
let element = app.project().diagrams[&diagram].nodes[&a].element;
|
||||
send(&mut app, Message::Select(element));
|
||||
let before = app.document.snapshot();
|
||||
let mut mounted = Mounted::new(&mut app).await;
|
||||
let field = 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))
|
||||
.expect("visible Inspector Name input");
|
||||
mounted.click(&mut app, field.center()).await;
|
||||
help_key(&mut mounted, &mut app, key(Named::Home)).await;
|
||||
for character_value in "DRAFT ".chars() {
|
||||
help_key(
|
||||
&mut mounted,
|
||||
&mut app,
|
||||
character(&character_value.to_string()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
help_key(&mut mounted, &mut app, key(Named::ArrowLeft)).await;
|
||||
assert_eq!(
|
||||
app.draft.as_ref().unwrap().inputs["/name"].raw,
|
||||
"DRAFT Send"
|
||||
);
|
||||
let camera = (app.zoom, app.pan);
|
||||
help_key(&mut mounted, &mut app, key(Named::F1)).await;
|
||||
assert!(app.context_help);
|
||||
let article = iced::advanced::widget::Id::new(crate::guide::ARTICLE_SCROLL_ID);
|
||||
let geometry = mounted.geometry(&app);
|
||||
let background_scrolls = geometry
|
||||
.scrolls
|
||||
.iter()
|
||||
.filter(|(id, _)| **id != article)
|
||||
.map(|(id, (_, offset))| (id.clone(), *offset))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(geometry.scrolls[&article].1.y, 0.);
|
||||
|
||||
help_key(&mut mounted, &mut app, key(Named::PageDown)).await;
|
||||
let down = mounted.geometry(&app).scrolls[&article].1.y;
|
||||
assert!(down > 0., "PageDown scrolls the mounted Help article");
|
||||
help_key(&mut mounted, &mut app, key(Named::End)).await;
|
||||
let end = mounted.geometry(&app).scrolls[&article].1.y;
|
||||
assert!(end > down);
|
||||
help_key(&mut mounted, &mut app, key(Named::PageDown)).await;
|
||||
assert_eq!(mounted.geometry(&app).scrolls[&article].1.y, end);
|
||||
help_key(&mut mounted, &mut app, key(Named::PageUp)).await;
|
||||
assert!(mounted.geometry(&app).scrolls[&article].1.y < end);
|
||||
help_key(&mut mounted, &mut app, key(Named::Home)).await;
|
||||
assert_eq!(mounted.geometry(&app).scrolls[&article].1.y, 0.);
|
||||
help_key(&mut mounted, &mut app, key(Named::ArrowDown)).await;
|
||||
assert_eq!(mounted.geometry(&app).scrolls[&article].1.y, 40.);
|
||||
help_key(&mut mounted, &mut app, key(Named::ArrowUp)).await;
|
||||
help_key(&mut mounted, &mut app, key(Named::PageUp)).await;
|
||||
let geometry = mounted.geometry(&app);
|
||||
assert_eq!(geometry.scrolls[&article].1.y, 0.);
|
||||
for (id, offset) in background_scrolls {
|
||||
assert_eq!(
|
||||
geometry.scrolls[&id].1, offset,
|
||||
"Help only scrolls its own article"
|
||||
);
|
||||
}
|
||||
for character_value in "IGNORED".chars() {
|
||||
help_key(
|
||||
&mut mounted,
|
||||
&mut app,
|
||||
character(&character_value.to_string()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let messages = mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[
|
||||
iced::Event::InputMethod(iced::advanced::input_method::Event::Preedit(
|
||||
"雨".into(),
|
||||
None,
|
||||
)),
|
||||
iced::Event::InputMethod(iced::advanced::input_method::Event::Commit("雨".into())),
|
||||
],
|
||||
iced::mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
assert!(!messages.iter().any(|m| matches!(m, Message::Field(..))));
|
||||
assert_eq!(
|
||||
app.draft.as_ref().unwrap().inputs["/name"].raw,
|
||||
"DRAFT Send"
|
||||
);
|
||||
help_key(&mut mounted, &mut app, key(Named::Escape)).await;
|
||||
assert!(!app.context_help);
|
||||
help_key(&mut mounted, &mut app, character("X")).await;
|
||||
assert_eq!(
|
||||
app.draft.as_ref().unwrap().inputs["/name"].raw,
|
||||
"DRAFTX Send",
|
||||
"Return keeps the actual mid-string caret without refocusing a guessed field"
|
||||
);
|
||||
assert_eq!((app.zoom, app.pan), camera);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
let messages = help_key(&mut mounted, &mut app, key(Named::PageDown)).await;
|
||||
assert!(
|
||||
!messages
|
||||
.iter()
|
||||
.any(|m| matches!(m, Message::ContextHelpScroll(_)))
|
||||
);
|
||||
assert!(
|
||||
iced_runtime::task::into_stream(
|
||||
app.update(Message::ContextHelpScroll(crate::guide::ContextScroll::End,))
|
||||
)
|
||||
.is_none(),
|
||||
"A late Help scroll cannot operate after closing"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_context_help_observes_modifier_release_before_plain_canvas_click() {
|
||||
use crate::behavior::canvas_workspace::tests::{Mounted, key};
|
||||
use iced::{
|
||||
keyboard::{Event, Modifiers, key::Named},
|
||||
mouse,
|
||||
};
|
||||
let (mut app, diagram, a, b) = architecture();
|
||||
choose(&mut app, a, multiselect::Choice::Replace);
|
||||
app.window_size = iced::Size::new(2000., 1400.);
|
||||
let mut mounted = Mounted::new(&mut app).await;
|
||||
app.zoom = 1.;
|
||||
app.pan = iced::Vector::ZERO;
|
||||
app.fit_to_view = false;
|
||||
mounted.settle(&mut app).await;
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[iced::Event::Keyboard(Event::ModifiersChanged(
|
||||
Modifiers::SHIFT,
|
||||
))],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
help_key(&mut mounted, &mut app, key(Named::F1)).await;
|
||||
assert!(app.context_help);
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[iced::Event::Keyboard(Event::ModifiersChanged(
|
||||
Modifiers::empty(),
|
||||
))],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
help_key(&mut mounted, &mut app, key(Named::Escape)).await;
|
||||
let bounds = mounted
|
||||
.geometry(&app)
|
||||
.bounds(crate::allocation_input::CANVAS_ID);
|
||||
let node = projection::project_view(app.project(), diagram)
|
||||
.nodes
|
||||
.into_iter()
|
||||
.find(|node| node.id == b)
|
||||
.unwrap();
|
||||
let at = iced::Point::new(
|
||||
bounds.x + node.position.x + 40.,
|
||||
bounds.y + node.position.y + 35.,
|
||||
);
|
||||
mounted.click(&mut app, at).await;
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(b)],
|
||||
"Shift released during Help must not add the next card to the previous selection"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_context_help_retires_held_pan_without_replaying_its_release() {
|
||||
use crate::behavior::canvas_workspace::tests::{Mounted, key};
|
||||
use iced::{keyboard::key::Named, mouse};
|
||||
let (mut app, _, _, _) = architecture();
|
||||
let mut mounted = Mounted::new(&mut app).await;
|
||||
let canvas = mounted
|
||||
.geometry(&app)
|
||||
.bounds(crate::allocation_input::CANVAS_ID);
|
||||
let start = canvas.center();
|
||||
let moved = start + iced::Vector::new(20., 10.);
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[
|
||||
iced::Event::Mouse(mouse::Event::CursorMoved { position: start }),
|
||||
iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)),
|
||||
iced::Event::Mouse(mouse::Event::CursorMoved { position: moved }),
|
||||
],
|
||||
mouse::Cursor::Available(moved),
|
||||
)
|
||||
.await;
|
||||
let camera = (app.zoom, app.pan);
|
||||
let before = app.document.snapshot();
|
||||
help_key(&mut mounted, &mut app, key(Named::F1)).await;
|
||||
assert!(app.context_help);
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[iced::Event::Mouse(mouse::Event::ButtonReleased(
|
||||
mouse::Button::Middle,
|
||||
))],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
help_key(&mut mounted, &mut app, key(Named::Escape)).await;
|
||||
let next = moved + iced::Vector::new(90., 50.);
|
||||
let messages = mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[iced::Event::Mouse(mouse::Event::CursorMoved {
|
||||
position: next,
|
||||
})],
|
||||
mouse::Cursor::Available(next),
|
||||
)
|
||||
.await;
|
||||
assert!(!messages.iter().any(|m| matches!(m, Message::Pan(_))));
|
||||
assert_eq!(
|
||||
(app.zoom, app.pan),
|
||||
camera,
|
||||
"Moving without a held button cannot resume the pre-Help pan"
|
||||
);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn context_help_barrier_retires_text_selection_drag_without_changing_the_caret() {
|
||||
use iced::advanced::{Layout, layout, widget};
|
||||
use iced::{Element, Event, Rectangle, mouse};
|
||||
type InputState = iced::widget::text_input::State<
|
||||
<iced::Renderer as iced::advanced::text::Renderer>::Paragraph,
|
||||
>;
|
||||
fn input(open: bool) -> Element<'static, Message> {
|
||||
crate::guide::protect_workspace(
|
||||
open,
|
||||
iced::widget::text_input("Name", "A long retained property name")
|
||||
.on_input(|value| Message::Field("/name".into(), value))
|
||||
.width(400)
|
||||
.padding(8)
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
fn dispatch(
|
||||
root: &mut Element<'_, Message>,
|
||||
tree: &mut widget::Tree,
|
||||
node: &layout::Node,
|
||||
renderer: &iced::Renderer,
|
||||
event: Event,
|
||||
cursor: mouse::Cursor,
|
||||
) -> Vec<Message> {
|
||||
let mut messages = Vec::new();
|
||||
root.as_widget_mut().update(
|
||||
tree,
|
||||
&event,
|
||||
Layout::new(node),
|
||||
cursor,
|
||||
renderer,
|
||||
&mut iced::advanced::clipboard::Null,
|
||||
&mut iced::advanced::Shell::new(&mut messages),
|
||||
&Rectangle::new(iced::Point::ORIGIN, iced::Size::new(400., 60.)),
|
||||
);
|
||||
messages
|
||||
}
|
||||
let mounted = crate::behavior::canvas_workspace::tests::Mounted::unshown().await;
|
||||
let renderer = &mounted.renderer;
|
||||
let mut root = input(false);
|
||||
let mut tree = widget::Tree::new(root.as_widget());
|
||||
let node = root.as_widget_mut().layout(
|
||||
&mut tree,
|
||||
renderer,
|
||||
&layout::Limits::new(iced::Size::ZERO, iced::Size::new(400., 60.)),
|
||||
);
|
||||
let start = iced::Point::new(20., 18.);
|
||||
let end = iced::Point::new(110., 18.);
|
||||
for event in [
|
||||
mouse::Event::CursorMoved { position: start },
|
||||
mouse::Event::ButtonPressed(mouse::Button::Left),
|
||||
mouse::Event::CursorMoved { position: end },
|
||||
] {
|
||||
let cursor = if matches!(event, mouse::Event::CursorMoved { position } if position == end) {
|
||||
mouse::Cursor::Available(end)
|
||||
} else {
|
||||
mouse::Cursor::Available(start)
|
||||
};
|
||||
dispatch(
|
||||
&mut root,
|
||||
&mut tree,
|
||||
&node,
|
||||
renderer,
|
||||
Event::Mouse(event),
|
||||
cursor,
|
||||
);
|
||||
}
|
||||
let caret = tree.children[0].state.downcast_ref::<InputState>().cursor();
|
||||
assert!(
|
||||
tree.children[0]
|
||||
.state
|
||||
.downcast_ref::<InputState>()
|
||||
.is_focused()
|
||||
);
|
||||
root = input(true);
|
||||
tree.diff(root.as_widget());
|
||||
let messages = dispatch(
|
||||
&mut root,
|
||||
&mut tree,
|
||||
&node,
|
||||
renderer,
|
||||
Event::Window(iced::window::Event::RedrawRequested(
|
||||
std::time::Instant::now(),
|
||||
)),
|
||||
mouse::Cursor::Unavailable,
|
||||
);
|
||||
assert!(
|
||||
messages.is_empty(),
|
||||
"Gesture retirement discards release actions"
|
||||
);
|
||||
dispatch(
|
||||
&mut root,
|
||||
&mut tree,
|
||||
&node,
|
||||
renderer,
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
|
||||
mouse::Cursor::Unavailable,
|
||||
);
|
||||
root = input(false);
|
||||
tree.diff(root.as_widget());
|
||||
let later = iced::Point::new(300., 18.);
|
||||
dispatch(
|
||||
&mut root,
|
||||
&mut tree,
|
||||
&node,
|
||||
renderer,
|
||||
Event::Mouse(mouse::Event::CursorMoved { position: later }),
|
||||
mouse::Cursor::Available(later),
|
||||
);
|
||||
let state = tree.children[0].state.downcast_ref::<InputState>();
|
||||
assert!(state.is_focused());
|
||||
assert_eq!(
|
||||
state.cursor(),
|
||||
caret,
|
||||
"An unheld pointer no longer extends the pre-Help text selection"
|
||||
);
|
||||
}
|
||||
@@ -154,3 +154,440 @@ async fn mounted_f2_requires_canvas_focus_and_yields_to_clean_inspector() {
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn modifier_focus_fixture() -> (App, Mounted, Id, Id, Id) {
|
||||
let mut project = Project::empty();
|
||||
let a = project
|
||||
.add_element(Kind::Entity, Layer::Oa, "First team", None)
|
||||
.unwrap();
|
||||
let b = project
|
||||
.add_element(Kind::Entity, Layer::Oa, "Second team", None)
|
||||
.unwrap();
|
||||
let diagram = project.ensure_diagram(Layer::Oa);
|
||||
let first = project.place(diagram, a, Position { x: 80., y: 80. });
|
||||
let second = project.place(diagram, b, Position { x: 500., y: 80. });
|
||||
let mut app = App::with_project(project);
|
||||
app.page = Page::Diagram;
|
||||
app.layer = Layer::Oa;
|
||||
app.active_diagram = Some(diagram);
|
||||
app.window_size = Size::new(2000., 1400.);
|
||||
let _ = app.update(Message::Select(a));
|
||||
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;
|
||||
(app, mounted, diagram, first, second)
|
||||
}
|
||||
|
||||
fn modifier_node_point(mounted: &mut Mounted, app: &App, diagram: Id, placement: Id) -> Point {
|
||||
let bounds = mounted
|
||||
.geometry(app)
|
||||
.bounds(crate::allocation_input::CANVAS_ID);
|
||||
let node = projection::project_view(app.project(), diagram)
|
||||
.nodes
|
||||
.into_iter()
|
||||
.find(|n| n.id == placement)
|
||||
.unwrap();
|
||||
Point::new(
|
||||
bounds.x + node.position.x + 40.,
|
||||
bounds.y + node.position.y + 35.,
|
||||
)
|
||||
}
|
||||
|
||||
fn modifier_canvas_focused(mounted: &mut Mounted, app: &App) -> bool {
|
||||
mounted
|
||||
.geometry(app)
|
||||
.focused
|
||||
.iter()
|
||||
.find(|(id, _, _)| {
|
||||
id.as_ref() == Some(&iced::advanced::widget::Id::from("diagram-keyboard-owner"))
|
||||
})
|
||||
.expect("production focus::Owner is mounted")
|
||||
.2
|
||||
}
|
||||
|
||||
fn modifier_event(shift: bool) -> iced::Event {
|
||||
iced::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(if shift {
|
||||
iced::keyboard::Modifiers::SHIFT
|
||||
} else {
|
||||
iced::keyboard::Modifiers::default()
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_shift_before_canvas_focus_toggles_exact_node_without_granting_keyboard_focus() {
|
||||
use crate::diagram_usage::Target;
|
||||
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
|
||||
let before = app.document.snapshot();
|
||||
let field = 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))
|
||||
.expect("clean Inspector name input");
|
||||
mounted.operate(&app, &mut FocusField(field));
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(first)]
|
||||
);
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[modifier_event(true)],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
!modifier_canvas_focused(&mut mounted, &app),
|
||||
"modifier tracking must not acquire focus"
|
||||
);
|
||||
let at = modifier_node_point(&mut mounted, &app, diagram, second);
|
||||
let messages = mounted.click(&mut app, at).await;
|
||||
assert!(messages.iter().any(|m| matches!(m,
|
||||
Message::DiagramSelection(multiselect::Event::Choose(_, Target::Placement(id), multiselect::Choice::Toggle)) if *id == second
|
||||
)), "Shift already held before the first canvas press must reach its exact-target adapter");
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(first), Target::Placement(second)]
|
||||
);
|
||||
assert_eq!(app.selected_node, Some(second));
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
assert!(!app.draft_dirty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_unfocused_typing_and_delete_remain_denied_after_passive_modifiers() {
|
||||
use crate::diagram_usage::Target;
|
||||
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[modifier_event(true)],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
let at = modifier_node_point(&mut mounted, &app, diagram, second);
|
||||
mounted.click(&mut app, at).await;
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(first), Target::Placement(second)]
|
||||
);
|
||||
// Revoke every field's focus through the real widget operation. No widget
|
||||
// has this off-window rectangle, so neither Inspector nor canvas owns keys.
|
||||
mounted.operate(
|
||||
&app,
|
||||
&mut FocusField(Rectangle {
|
||||
x: -1000.,
|
||||
y: -1000.,
|
||||
width: 1.,
|
||||
height: 1.,
|
||||
}),
|
||||
);
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
let before = app.document.snapshot();
|
||||
let selection = app.multiselect_snapshot().unwrap();
|
||||
let messages = mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[
|
||||
modifier_event(false),
|
||||
crate::behavior::canvas_workspace::tests::character("x"),
|
||||
key(Named::Delete),
|
||||
key(Named::F2),
|
||||
],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
assert!(!messages.iter().any(|m| matches!(
|
||||
m,
|
||||
Message::DiagramSelection(_)
|
||||
| Message::DiagramRemove(_)
|
||||
| Message::HideSelected
|
||||
| Message::Delete
|
||||
)));
|
||||
assert!(!rename_emitted(&messages));
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
selection.targets()
|
||||
);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
assert!(!app.draft_dirty());
|
||||
assert!(!app.delete_pending);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_suspended_modifiers_are_passive_and_survive_until_resumed_click() {
|
||||
use crate::diagram_usage::Target;
|
||||
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
|
||||
let before = app.document.snapshot();
|
||||
let at = modifier_node_point(&mut mounted, &app, diagram, second);
|
||||
app.busy = true;
|
||||
mounted.settle(&mut app).await;
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[modifier_event(true), key(Named::Delete)],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
mounted.click(&mut app, at).await;
|
||||
assert!(
|
||||
!modifier_canvas_focused(&mut mounted, &app),
|
||||
"passive I/O cannot grant canvas focus"
|
||||
);
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(first)]
|
||||
);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
app.busy = false;
|
||||
mounted.settle(&mut app).await;
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
mounted.click(&mut app, at).await;
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(first), Target::Placement(second)]
|
||||
);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_shift_held_before_suspension_survives_without_another_modifier_event() {
|
||||
use crate::diagram_usage::Target;
|
||||
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
|
||||
let before = app.document.snapshot();
|
||||
let field = 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))
|
||||
.expect("clean Inspector name input");
|
||||
mounted.operate(&app, &mut FocusField(field));
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[modifier_event(true)],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
app.busy = true;
|
||||
mounted.settle(&mut app).await;
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
app.busy = false;
|
||||
mounted.settle(&mut app).await;
|
||||
assert!(
|
||||
!modifier_canvas_focused(&mut mounted, &app),
|
||||
"restoring passive modifiers must not grant keyboard focus"
|
||||
);
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(first)]
|
||||
);
|
||||
// No modifier transition follows the subtree replacement during I/O.
|
||||
let at = modifier_node_point(&mut mounted, &app, diagram, second);
|
||||
let messages = mounted.click(&mut app, at).await;
|
||||
assert!(messages.iter().any(|m| matches!(m,
|
||||
Message::DiagramSelection(multiselect::Event::Choose(_, Target::Placement(id), multiselect::Choice::Toggle)) if *id == second
|
||||
)));
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(first), Target::Placement(second)]
|
||||
);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
assert!(!app.draft_dirty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_shift_release_or_window_unfocus_during_suspension_does_not_restore_stale_shift() {
|
||||
use crate::diagram_usage::Target;
|
||||
for release in [
|
||||
modifier_event(false),
|
||||
iced::Event::Window(iced::window::Event::Unfocused),
|
||||
] {
|
||||
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
|
||||
let before = app.document.snapshot();
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[modifier_event(true)],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
app.busy = true;
|
||||
mounted.settle(&mut app).await;
|
||||
mounted
|
||||
.batch(&mut app, &[release], mouse::Cursor::Unavailable)
|
||||
.await;
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
app.busy = false;
|
||||
mounted.settle(&mut app).await;
|
||||
// A further I/O cycle must restore the updated owner state too.
|
||||
app.busy = true;
|
||||
mounted.settle(&mut app).await;
|
||||
app.busy = false;
|
||||
mounted.settle(&mut app).await;
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(first)]
|
||||
);
|
||||
let at = modifier_node_point(&mut mounted, &app, diagram, second);
|
||||
let messages = mounted.click(&mut app, at).await;
|
||||
assert!(!messages.iter().any(|m| matches!(
|
||||
m,
|
||||
Message::DiagramSelection(multiselect::Event::Choose(
|
||||
_,
|
||||
_,
|
||||
multiselect::Choice::Toggle
|
||||
))
|
||||
)));
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(second)]
|
||||
);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
assert!(!app.draft_dirty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_window_unfocus_resets_held_shift_before_next_canvas_press() {
|
||||
use crate::diagram_usage::Target;
|
||||
let (mut app, mut mounted, diagram, first, second) = modifier_focus_fixture().await;
|
||||
let at_first = modifier_node_point(&mut mounted, &app, diagram, first);
|
||||
mounted.click(&mut app, at_first).await;
|
||||
let before = app.document.snapshot();
|
||||
mounted
|
||||
.batch(
|
||||
&mut app,
|
||||
&[
|
||||
modifier_event(true),
|
||||
iced::Event::Window(iced::window::Event::Unfocused),
|
||||
],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
assert!(!modifier_canvas_focused(&mut mounted, &app));
|
||||
// No ModifiersChanged(empty) follows: a lost window must itself reset it.
|
||||
let at_second = modifier_node_point(&mut mounted, &app, diagram, second);
|
||||
mounted.click(&mut app, at_second).await;
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(second)]
|
||||
);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_selection_strip_keeps_canvas_and_fitted_camera_fixed_for_empty_single_group_and_mixed()
|
||||
{
|
||||
use crate::diagram_usage::Target;
|
||||
let mut project = Project::empty();
|
||||
let a = project
|
||||
.add_element(Kind::Activity, Layer::Oa, "First activity", None)
|
||||
.unwrap();
|
||||
let b = project
|
||||
.add_element(
|
||||
Kind::Activity,
|
||||
Layer::Oa,
|
||||
&format!(
|
||||
"Second activity {}",
|
||||
"with a very long primary name ".repeat(20)
|
||||
),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let edge = project.relate(RelationKind::Interaction, "Activity exchange", a, b);
|
||||
let diagram = project.ensure_diagram(Layer::Oa);
|
||||
project.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::Overview;
|
||||
let first = project.place(diagram, a, Position { x: 80., y: 80. });
|
||||
let second = project.place(diagram, b, Position { x: 500., y: 80. });
|
||||
let mut app = App::with_project(project);
|
||||
app.page = Page::Diagram;
|
||||
app.layer = Layer::Oa;
|
||||
app.active_diagram = Some(diagram);
|
||||
app.window_size = Size::new(1442., 932.);
|
||||
let _ = app.update(Message::Select(diagram));
|
||||
app.fit_to_view = true;
|
||||
let mut mounted = Mounted::new(&mut app).await;
|
||||
let baseline = app.document.snapshot();
|
||||
let bounds = mounted
|
||||
.geometry(&app)
|
||||
.bounds(crate::allocation_input::CANVAS_ID);
|
||||
let camera = (app.zoom, app.pan, app.fit_to_view, app.canvas_size);
|
||||
assert!(camera.2, "exercise the native resize-triggered refit path");
|
||||
assert!(app.multiselect_snapshot().unwrap().targets().is_empty());
|
||||
assert!(bounds.width > 500. && bounds.height > 300.);
|
||||
for (target, expected) in [
|
||||
(
|
||||
Some(Target::Placement(first)),
|
||||
vec![Target::Placement(first)],
|
||||
),
|
||||
(
|
||||
Some(Target::Placement(second)),
|
||||
vec![Target::Placement(first), Target::Placement(second)],
|
||||
),
|
||||
(
|
||||
Some(Target::Edge(edge)),
|
||||
vec![
|
||||
Target::Placement(first),
|
||||
Target::Placement(second),
|
||||
Target::Edge(edge),
|
||||
],
|
||||
),
|
||||
(
|
||||
Some(Target::Edge(edge)),
|
||||
vec![Target::Placement(first), Target::Placement(second)],
|
||||
),
|
||||
(
|
||||
Some(Target::Placement(second)),
|
||||
vec![Target::Placement(first)],
|
||||
),
|
||||
(None, vec![]),
|
||||
] {
|
||||
let context = app.multiselect_context().unwrap();
|
||||
let event = match target {
|
||||
Some(target) => {
|
||||
multiselect::Event::Choose(context, target, multiselect::Choice::Toggle)
|
||||
}
|
||||
None => multiselect::Event::Clear(context),
|
||||
};
|
||||
let task = app.update(Message::DiagramSelection(event));
|
||||
mounted.perform(&mut app, task).await;
|
||||
mounted.settle(&mut app).await;
|
||||
assert_eq!(app.multiselect_snapshot().unwrap().targets(), expected);
|
||||
assert_eq!(
|
||||
mounted
|
||||
.geometry(&app)
|
||||
.bounds(crate::allocation_input::CANVAS_ID),
|
||||
bounds,
|
||||
"selection feedback must not change the measured canvas rectangle"
|
||||
);
|
||||
assert_eq!(
|
||||
(app.zoom, app.pan, app.fit_to_view, app.canvas_size),
|
||||
camera
|
||||
);
|
||||
assert_eq!(app.project(), &baseline.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &baseline.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
assert!(!app.draft_dirty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Complete a navigation camera after the destination reports its real viewport.
|
||||
use super::*;
|
||||
use crate::behavior::scenario_layout::Representation;
|
||||
use crate::diagram_usage::{Context, Surface};
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -47,11 +48,23 @@ impl App {
|
||||
&& c.epoch == *epoch,
|
||||
),
|
||||
Message::ScenarioCanvas(behavior::scenario::CanvasEvent::Viewport(c, size)) => (
|
||||
Surface::Scenario(c.scenario),
|
||||
match c.representation {
|
||||
Representation::Derived { owner } => Surface::Scenario(owner),
|
||||
Representation::Saved { diagram } => Surface::Saved(diagram),
|
||||
},
|
||||
*size,
|
||||
c.document == context.document
|
||||
&& c.revision == context.revision
|
||||
&& c.epoch == *epoch,
|
||||
&& c.epoch == *epoch
|
||||
&& self.pending_scenario_reveal_visit == Some(c.visit)
|
||||
&& self.page == Page::Behavior
|
||||
&& self.behavior.active_owner == Some(c.scenario)
|
||||
&& self.behavior.scenario.context(
|
||||
self.canvas_document,
|
||||
c.scenario,
|
||||
self.document.revision(),
|
||||
self.canvas_epoch,
|
||||
) == Some(*c),
|
||||
),
|
||||
Message::StateDiagram(behavior::state_edit::Event::Viewport(c, size)) => (
|
||||
Surface::Saved(c.diagram),
|
||||
@@ -93,6 +106,7 @@ impl App {
|
||||
| Message::StateDiagram(behavior::state_edit::Event::Viewport(..))
|
||||
) {
|
||||
self.pending_diagram_reveal = None;
|
||||
self.pending_scenario_reveal_visit = None;
|
||||
if !Self::is_navigation_camera(message) {
|
||||
self.diagram_navigation_focus = None;
|
||||
}
|
||||
@@ -142,5 +156,6 @@ impl App {
|
||||
self.reveal_diagram_usage(&usage);
|
||||
}
|
||||
self.pending_diagram_reveal = None;
|
||||
self.pending_scenario_reveal_visit = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ fn fixture(canvas: Canvas) -> (App, Usage) {
|
||||
layer: Layer::Oa,
|
||||
projection: ProjectionKind::StateMachine { machine },
|
||||
nodes: BTreeMap::new(),
|
||||
layout: None,
|
||||
routes: vec![],
|
||||
view_options: Default::default(),
|
||||
},
|
||||
@@ -143,6 +144,7 @@ fn measurement(
|
||||
epoch: u64,
|
||||
surface: Surface,
|
||||
size: Size,
|
||||
visit: Id,
|
||||
) -> Message {
|
||||
match canvas {
|
||||
Canvas::Architecture => Message::DiagramRevealViewport(context, epoch, size),
|
||||
@@ -159,6 +161,10 @@ fn measurement(
|
||||
behavior::scenario::Context {
|
||||
document: context.document,
|
||||
scenario: surface.id(),
|
||||
representation: Representation::Derived {
|
||||
owner: surface.id(),
|
||||
},
|
||||
visit,
|
||||
revision: context.revision,
|
||||
epoch,
|
||||
},
|
||||
@@ -176,12 +182,16 @@ fn measurement(
|
||||
}
|
||||
}
|
||||
|
||||
fn stamp(app: &App) -> (Context, u64) {
|
||||
fn stamp(app: &App) -> (Context, u64, Id) {
|
||||
let (context, _, epoch) = app
|
||||
.pending_diagram_reveal
|
||||
.as_ref()
|
||||
.expect("reveal awaits measured destination");
|
||||
(*context, *epoch)
|
||||
(
|
||||
*context,
|
||||
*epoch,
|
||||
app.pending_scenario_reveal_visit.unwrap_or(Id::nil()),
|
||||
)
|
||||
}
|
||||
|
||||
fn assert_centered(app: &App, canvas: Canvas, target: &Usage) {
|
||||
@@ -219,7 +229,11 @@ fn assert_centered(app: &App, canvas: Canvas, target: &Usage) {
|
||||
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));
|
||||
expected.camera(
|
||||
app.project(),
|
||||
target.surface.id(),
|
||||
behavior::canvas_workspace::Event::Pan(pan),
|
||||
);
|
||||
assert!(app.behavior.scenario.camera_boundary() == expected.camera_boundary());
|
||||
}
|
||||
}
|
||||
@@ -238,10 +252,10 @@ fn all_reveal_surfaces_recenter_once_after_the_real_viewport_and_preserve_author
|
||||
app.document.dirty(),
|
||||
);
|
||||
assert!(app.reveal_diagram_usage(&target));
|
||||
let (context, epoch) = stamp(&app);
|
||||
let (context, epoch, visit) = stamp(&app);
|
||||
send(
|
||||
&mut app,
|
||||
measurement(canvas, context, epoch, target.surface, ACTUAL),
|
||||
measurement(canvas, context, epoch, target.surface, ACTUAL, visit),
|
||||
);
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert_centered(&app, canvas, &target);
|
||||
@@ -260,7 +274,7 @@ fn all_reveal_surfaces_recenter_once_after_the_real_viewport_and_preserve_author
|
||||
let camera = app.camera_boundary();
|
||||
send(
|
||||
&mut app,
|
||||
measurement(canvas, context, epoch, target.surface, ACTUAL),
|
||||
measurement(canvas, context, epoch, target.surface, ACTUAL, visit),
|
||||
);
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert!(app.camera_boundary() == camera);
|
||||
@@ -274,7 +288,7 @@ fn malformed_or_wrong_stamp_measurements_cannot_poison_a_pending_reveal() {
|
||||
for invalid in 0..6 {
|
||||
let (mut app, target) = fixture(canvas);
|
||||
assert!(app.reveal_diagram_usage(&target));
|
||||
let (context, epoch) = stamp(&app);
|
||||
let (context, epoch, visit) = stamp(&app);
|
||||
let camera = app.camera_boundary();
|
||||
let mut stale = context;
|
||||
let mut wrong_epoch = epoch;
|
||||
@@ -289,13 +303,13 @@ fn malformed_or_wrong_stamp_measurements_cannot_poison_a_pending_reveal() {
|
||||
}
|
||||
send(
|
||||
&mut app,
|
||||
measurement(canvas, stale, wrong_epoch, target.surface, size),
|
||||
measurement(canvas, stale, wrong_epoch, target.surface, size, visit),
|
||||
);
|
||||
assert!(
|
||||
app.pending_diagram_reveal.is_some(),
|
||||
"{canvas:?} invalid case {invalid}"
|
||||
);
|
||||
assert_eq!(stamp(&app), (context, epoch));
|
||||
assert_eq!(stamp(&app), (context, epoch, visit));
|
||||
assert_eq!(app.canvas_epoch, epoch);
|
||||
assert!(
|
||||
app.camera_boundary() == camera,
|
||||
@@ -303,7 +317,7 @@ fn malformed_or_wrong_stamp_measurements_cannot_poison_a_pending_reveal() {
|
||||
);
|
||||
send(
|
||||
&mut app,
|
||||
measurement(canvas, context, epoch, target.surface, ACTUAL),
|
||||
measurement(canvas, context, epoch, target.surface, ACTUAL, visit),
|
||||
);
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert_centered(&app, canvas, &target);
|
||||
@@ -317,9 +331,10 @@ fn actual_window_resize_before_first_measurement_retains_focus_for_the_new_conte
|
||||
let (mut app, target) = fixture(canvas);
|
||||
let accepted = app.document.snapshot();
|
||||
assert!(app.reveal_diagram_usage(&target));
|
||||
let (context, old_epoch) = stamp(&app);
|
||||
let (context, old_epoch, visit) = stamp(&app);
|
||||
send(&mut app, Message::WindowResized(Size::new(1100., 700.)));
|
||||
let (current, epoch) = stamp(&app);
|
||||
let (current, epoch, current_visit) = stamp(&app);
|
||||
assert_eq!(current_visit, visit);
|
||||
assert_eq!(current, context);
|
||||
assert_eq!(epoch, app.canvas_epoch);
|
||||
if matches!(canvas, Canvas::Process | Canvas::Scenario) {
|
||||
@@ -327,14 +342,14 @@ fn actual_window_resize_before_first_measurement_retains_focus_for_the_new_conte
|
||||
let camera = app.camera_boundary();
|
||||
send(
|
||||
&mut app,
|
||||
measurement(canvas, context, old_epoch, target.surface, ACTUAL),
|
||||
measurement(canvas, context, old_epoch, target.surface, ACTUAL, visit),
|
||||
);
|
||||
assert_eq!(stamp(&app), (current, epoch));
|
||||
assert_eq!(stamp(&app), (current, epoch, visit));
|
||||
assert!(app.camera_boundary() == camera);
|
||||
}
|
||||
send(
|
||||
&mut app,
|
||||
measurement(canvas, current, epoch, target.surface, ACTUAL),
|
||||
measurement(canvas, current, epoch, target.surface, ACTUAL, visit),
|
||||
);
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert_centered(&app, canvas, &target);
|
||||
@@ -349,7 +364,7 @@ fn user_camera_edit_and_navigation_cancel_deferred_focus_without_late_snapping()
|
||||
let (mut app, target) = fixture(canvas);
|
||||
let accepted = app.document.snapshot();
|
||||
assert!(app.reveal_diagram_usage(&target));
|
||||
let (context, epoch) = stamp(&app);
|
||||
let (context, epoch, visit) = stamp(&app);
|
||||
let event = match action {
|
||||
0 => match canvas {
|
||||
Canvas::Architecture => Message::Pan(Vector::new(31., -17.)),
|
||||
@@ -386,7 +401,7 @@ fn user_camera_edit_and_navigation_cancel_deferred_focus_without_late_snapping()
|
||||
// restore the old navigation camera after deliberate user input.
|
||||
send(
|
||||
&mut app,
|
||||
measurement(canvas, context, epoch, target.surface, WIDE),
|
||||
measurement(canvas, context, epoch, target.surface, WIDE, visit),
|
||||
);
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert!(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Navigation-only adapter: validates destinations before changing presentation.
|
||||
use super::*;
|
||||
use crate::behavior::scenario_layout::{Representation, presentation};
|
||||
use crate::diagram_usage::{self as usage, Context, Event, Panel, Surface, Target, Usage};
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -181,6 +182,7 @@ impl App {
|
||||
// Only an accepted new chooser supersedes the previous reveal.
|
||||
// Rejected/stale panel envelopes leave its first measurement intact.
|
||||
self.pending_diagram_reveal = None;
|
||||
self.pending_scenario_reveal_visit = None;
|
||||
self.diagram_navigation_focus = None;
|
||||
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
|
||||
return Task::batch([
|
||||
@@ -291,11 +293,78 @@ impl App {
|
||||
Task::none()
|
||||
}
|
||||
|
||||
/// Explicit saved-Scenario reveal runs before generic Apply. An absent target
|
||||
/// never selects the owner or another saved arrangement as a fallback.
|
||||
pub(super) fn reveal_saved_scenario(&mut self, diagram: Id, selected: Id) -> Task<Message> {
|
||||
if self.diagram_usages.is_some() || !self.usage_navigation_available() {
|
||||
self.status = "Apply or revert pending edits before revealing a saved Scenario. Your inputs are retained.".into();
|
||||
return Task::none();
|
||||
}
|
||||
if presentation::checked_owner(self.project(), Representation::Saved { diagram }).is_none()
|
||||
{
|
||||
return Task::none();
|
||||
}
|
||||
let Some(found) = self
|
||||
.current_surface_usages(selected, Surface::Saved(diagram))
|
||||
.into_iter()
|
||||
.find(|row| matches!(row.target, Target::Whole | Target::ScenarioObject(_)))
|
||||
else {
|
||||
self.status = "This object has no visible target in that saved Scenario.".into();
|
||||
return Task::none();
|
||||
};
|
||||
self.reveal_diagram_usage(&found);
|
||||
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 scenario_representation = match usage.surface {
|
||||
Surface::Saved(diagram) if self.saved_scenario_diagram(diagram) => {
|
||||
Some(Representation::Saved { diagram })
|
||||
}
|
||||
Surface::Scenario(owner) => Some(Representation::Derived { owner }),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(representation) = scenario_representation {
|
||||
let Some(owner) = presentation::checked_owner(self.project(), representation) else {
|
||||
return false;
|
||||
};
|
||||
if !self
|
||||
.behavior
|
||||
.scenario
|
||||
.representation_usages(self.project(), representation, usage.subject)
|
||||
.iter()
|
||||
.any(|row| row == usage)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// Finish target/camera admission before changing the App route. The
|
||||
// checked immutable owner also makes the following entry infallible.
|
||||
let revealed = match representation {
|
||||
Representation::Derived { .. } => self.behavior.scenario.reveal_usage(
|
||||
self.document.project(),
|
||||
self.canvas_document,
|
||||
owner,
|
||||
&usage.target,
|
||||
),
|
||||
Representation::Saved { .. } => self.behavior.scenario.reveal_representation_usage(
|
||||
self.document.project(),
|
||||
self.canvas_document,
|
||||
owner,
|
||||
representation,
|
||||
&usage.target,
|
||||
),
|
||||
};
|
||||
if !revealed {
|
||||
return false;
|
||||
}
|
||||
if !self.enter_scenario_representation(representation) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let p = self.document.project();
|
||||
let (selected, placement) = match &usage.target {
|
||||
Target::Whole => (usage.surface.id(), None),
|
||||
@@ -319,14 +388,7 @@ impl App {
|
||||
| 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,
|
||||
),
|
||||
Target::ProcessOccurrence(endpoint) => (endpoint.occurrence, None),
|
||||
};
|
||||
match usage.surface {
|
||||
Surface::Saved(id) => {
|
||||
@@ -335,7 +397,10 @@ impl App {
|
||||
};
|
||||
self.layer = diagram.layer;
|
||||
self.active_diagram = Some(id);
|
||||
if let Some(machine) = diagram.projection.state_machine() {
|
||||
if let Some(owner) = diagram.projection.scenario() {
|
||||
self.behavior.active_owner = Some(owner);
|
||||
self.page = Page::Behavior;
|
||||
} else 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.),
|
||||
@@ -377,19 +442,14 @@ impl App {
|
||||
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;
|
||||
}
|
||||
}
|
||||
if scenario_representation.is_none() {
|
||||
self.behavior.scenario.forget_view();
|
||||
}
|
||||
self.selected = selected;
|
||||
self.selected_node = placement;
|
||||
self.model_menu = None;
|
||||
@@ -416,6 +476,18 @@ impl App {
|
||||
usage: usage.clone(),
|
||||
selected,
|
||||
});
|
||||
self.pending_scenario_reveal_visit = scenario_representation.and_then(|representation| {
|
||||
let owner = presentation::checked_owner(self.project(), representation)?;
|
||||
self.behavior
|
||||
.scenario
|
||||
.context(
|
||||
self.canvas_document,
|
||||
owner,
|
||||
self.document.revision(),
|
||||
self.canvas_epoch,
|
||||
)
|
||||
.map(|context| context.visit)
|
||||
});
|
||||
self.pending_diagram_reveal = Some((
|
||||
Context {
|
||||
document: self.canvas_document,
|
||||
@@ -436,10 +508,20 @@ impl App {
|
||||
Surface::Saved(id) => {
|
||||
self.active_diagram == Some(id)
|
||||
&& matches!(self.page, Page::Diagram | Page::Behavior)
|
||||
&& (!self.saved_scenario_diagram(id)
|
||||
|| (self.page == Page::Behavior
|
||||
&& self.behavior.scenario.representation()
|
||||
== Some(Representation::Saved { diagram: id })))
|
||||
}
|
||||
Surface::Process(owner) | Surface::Scenario(owner) => {
|
||||
Surface::Process(owner) => {
|
||||
self.page == Page::Behavior && self.behavior.active_owner == Some(owner)
|
||||
}
|
||||
Surface::Scenario(owner) => {
|
||||
self.page == Page::Behavior
|
||||
&& self.behavior.active_owner == Some(owner)
|
||||
&& self.behavior.scenario.representation()
|
||||
== Some(Representation::Derived { owner })
|
||||
}
|
||||
};
|
||||
(current_surface
|
||||
&& focus.usage.surface == surface
|
||||
|
||||
@@ -881,7 +881,32 @@ fn repeated_process_calls_reveal_the_chosen_caller_and_distinct_tile_camera() {
|
||||
.unwrap()
|
||||
.clone();
|
||||
choose(&mut app, token, row);
|
||||
assert_eq!(app.selected, first);
|
||||
assert_eq!(app.selected, leaf);
|
||||
let context = app.topology_context().unwrap();
|
||||
send(
|
||||
&mut app,
|
||||
Message::TopologyCanvas(behavior::topology::CanvasEvent::Viewport(
|
||||
context,
|
||||
iced::Size::new(850., 460.),
|
||||
)),
|
||||
);
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert_eq!(
|
||||
app.behavior.topology.selection_address().unwrap().endpoint,
|
||||
OccurrenceEndpoint {
|
||||
references: vec![first],
|
||||
occurrence: leaf
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().primary(),
|
||||
Some(&Target::ProcessOccurrence(OccurrenceEndpoint {
|
||||
references: vec![first],
|
||||
occurrence: leaf
|
||||
}))
|
||||
);
|
||||
assert!(app.process_preview_primary().is_some());
|
||||
assert!(app.draft.is_none());
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(app.behavior.active_owner, Some(fixture.owner));
|
||||
let first_camera = app.behavior.topology.camera_boundary();
|
||||
@@ -898,7 +923,33 @@ fn repeated_process_calls_reveal_the_chosen_caller_and_distinct_tile_camera() {
|
||||
})
|
||||
.unwrap();
|
||||
choose(&mut app, token, row);
|
||||
assert_eq!(app.selected, second);
|
||||
assert_eq!(app.selected, leaf);
|
||||
let context = app.topology_context().unwrap();
|
||||
send(
|
||||
&mut app,
|
||||
Message::TopologyCanvas(behavior::topology::CanvasEvent::Viewport(
|
||||
context,
|
||||
iced::Size::new(850., 460.),
|
||||
)),
|
||||
);
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert_eq!(app.behavior.active_owner, Some(fixture.owner));
|
||||
assert_eq!(
|
||||
app.behavior.topology.selection_address().unwrap().endpoint,
|
||||
OccurrenceEndpoint {
|
||||
references: vec![second],
|
||||
occurrence: leaf
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
app.multiselect_snapshot().unwrap().primary(),
|
||||
Some(&Target::ProcessOccurrence(OccurrenceEndpoint {
|
||||
references: vec![second],
|
||||
occurrence: leaf
|
||||
}))
|
||||
);
|
||||
assert!(app.process_preview_primary().is_some());
|
||||
assert!(app.draft.is_none());
|
||||
assert_eq!(app.selected_node, None);
|
||||
assert!(app.behavior.topology.camera_boundary() != first_camera);
|
||||
assert_eq!(authored(&app), before);
|
||||
@@ -1400,3 +1451,5 @@ fn completion_releases_worker_behind_busy_modal_without_navigation() {
|
||||
assert_eq!(location(&app), prior);
|
||||
assert_eq!(authored(&app), before);
|
||||
}
|
||||
|
||||
mod saved_scenario;
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
arcadia 7;
|
||||
project incident_workspace "Incident report review" id "70200000-0000-4000-8000-000000000001" {
|
||||
// Two operational activities, with one lifeline appearance per Scenario.
|
||||
oa_activity report_incident "Report incident" id "70200000-0000-4000-8000-000000000002" {}
|
||||
oa_activity assess_incident "Assess incident" id "70200000-0000-4000-8000-000000000003" {}
|
||||
interaction incident_report "Incident report" id "70200000-0000-4000-8000-000000000004" {
|
||||
source @report_incident;
|
||||
target @assess_incident;
|
||||
}
|
||||
|
||||
oa_scenario incident_response "Review a reported incident" id "70200000-0000-4000-8000-000000000010" {
|
||||
viewpoint OperationalActivity;
|
||||
steps [@initial_report, @updated_report, @assess_call, @assess_reply, @unfinished_notice, @use_review];
|
||||
}
|
||||
oa_lifeline reporter "Reporting activity" id "70200000-0000-4000-8000-000000000011" {
|
||||
parent @incident_response; represented @report_incident;
|
||||
}
|
||||
oa_lifeline assessor "Assessment activity" id "70200000-0000-4000-8000-000000000012" {
|
||||
parent @incident_response; represented @assess_incident;
|
||||
}
|
||||
// Both appearances reuse one definition. Navigation must retain the occurrence.
|
||||
oa_occurrence initial_report "Initial incident report" id "70200000-0000-4000-8000-000000000020" {
|
||||
parent @incident_response;
|
||||
body { Exchange { exchange @incident_report; sender @reporter; receiver @assessor; message_kind Asynchronous; }; };
|
||||
}
|
||||
oa_occurrence updated_report "Updated incident report" id "70200000-0000-4000-8000-000000000021" {
|
||||
parent @incident_response;
|
||||
body { Exchange { exchange @incident_report; sender @reporter; receiver @assessor; message_kind Asynchronous; }; };
|
||||
}
|
||||
// A correlated self call/reply with deliberately unassigned exchange definitions.
|
||||
oa_occurrence assess_call "Assess report details" id "70200000-0000-4000-8000-000000000022" {
|
||||
parent @incident_response;
|
||||
body { Exchange { exchange none; sender @assessor; receiver @assessor; message_kind Call; }; };
|
||||
}
|
||||
oa_occurrence assess_reply "Assessment ready" id "70200000-0000-4000-8000-000000000023" {
|
||||
parent @incident_response;
|
||||
body { Exchange { exchange none; sender @assessor; receiver @assessor; message_kind Reply; reply_to @assess_call; }; };
|
||||
}
|
||||
// Intentional unfinished work: no receiver and therefore no fabricated arrow.
|
||||
oa_occurrence unfinished_notice "Follow-up recipient undecided" id "70200000-0000-4000-8000-000000000024" {
|
||||
parent @incident_response;
|
||||
body { Exchange { exchange @incident_report; sender @reporter; receiver none; message_kind Asynchronous; }; };
|
||||
}
|
||||
oa_occurrence use_review "Use the reviewed reporting procedure" id "70200000-0000-4000-8000-000000000025" {
|
||||
parent @incident_response;
|
||||
body { ScenarioUse {
|
||||
bindings [{ local @reporter; referenced @review_reporter; }, { local @assessor; referenced @review_assessor; }];
|
||||
scenario @reporting_review;
|
||||
}; };
|
||||
}
|
||||
|
||||
// This definition stays opaque in the caller. Open it, then Back to the saved view.
|
||||
oa_scenario reporting_review "Reporting procedure detail" id "70200000-0000-4000-8000-000000000030" {
|
||||
viewpoint OperationalActivity;
|
||||
steps [@review_delivery];
|
||||
}
|
||||
oa_lifeline review_reporter "Reporting activity in detail" id "70200000-0000-4000-8000-000000000031" {
|
||||
parent @reporting_review; represented @report_incident;
|
||||
}
|
||||
oa_lifeline review_assessor "Assessment activity in detail" id "70200000-0000-4000-8000-000000000032" {
|
||||
parent @reporting_review; represented @assess_incident;
|
||||
}
|
||||
oa_occurrence review_delivery "Check the incident report" id "70200000-0000-4000-8000-000000000033" {
|
||||
parent @reporting_review;
|
||||
body { Exchange { exchange @incident_report; sender @review_reporter; receiver @review_assessor; message_kind Asynchronous; }; };
|
||||
}
|
||||
|
||||
diagram incident_readable "A - Incident review readable" id "70200000-0000-4000-8000-000000000040" {
|
||||
layer Oa;
|
||||
projection { Scenario { scenario @incident_response; }; };
|
||||
layout { Scenario {
|
||||
lanes [{ lifeline @reporter; x 160; }, { lifeline @assessor; x 640; }];
|
||||
messages [
|
||||
{ address { references []; occurrence @initial_report; }; send_y 160; },
|
||||
{ address { references []; occurrence @updated_report; }; send_y 252; },
|
||||
{ address { references []; occurrence @assess_call; }; send_y 344; },
|
||||
{ address { references []; occurrence @assess_reply; }; send_y 436; }
|
||||
];
|
||||
}; };
|
||||
}
|
||||
diagram incident_wide "B - Incident review negative and far" id "70200000-0000-4000-8000-000000000041" {
|
||||
layer Oa;
|
||||
projection { Scenario { scenario @incident_response; }; };
|
||||
layout { Scenario {
|
||||
lanes [{ lifeline @reporter; x -500; }, { lifeline @assessor; x 50000; }];
|
||||
messages [
|
||||
{ address { references []; occurrence @initial_report; }; send_y 160; },
|
||||
{ address { references []; occurrence @updated_report; }; send_y 252; },
|
||||
{ address { references []; occurrence @assess_call; }; send_y 344; },
|
||||
{ address { references []; occurrence @assess_reply; }; send_y 436; }
|
||||
];
|
||||
}; };
|
||||
}
|
||||
diagram incident_repair "C - Incident review needs layout repair" id "70200000-0000-4000-8000-000000000042" {
|
||||
layer Oa;
|
||||
projection { Scenario { scenario @incident_response; }; };
|
||||
layout { Scenario {
|
||||
// These valid authored lanes must remain saved during complete fallback.
|
||||
lanes [{ lifeline @reporter; x 900; }, { lifeline @assessor; x -500; }];
|
||||
messages [
|
||||
// REPAIR: change only this 300 to 424, then Undo and Redo the edit.
|
||||
{ address { references []; occurrence @assess_reply; }; send_y 300; },
|
||||
// This authored value stays latent while the receiver is missing.
|
||||
{ address { references []; occurrence @unfinished_notice; }; send_y 2000; }
|
||||
];
|
||||
}; };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
//! Actual App chooser/explicit-reveal checks for saved Scenario identity and source history.
|
||||
use super::*;
|
||||
use crate::behavior::scenario::{CanvasEvent, State};
|
||||
use crate::behavior::scenario_layout::{
|
||||
Representation,
|
||||
presentation::{self, PresentationStatus},
|
||||
};
|
||||
use iced::{Size, Vector};
|
||||
|
||||
fn fixture() -> App {
|
||||
let p = language::parse(include_str!("saved_scenario.arcadia")).unwrap();
|
||||
let errors: Vec<_> = oa_core::validation::validate(&p)
|
||||
.into_iter()
|
||||
.filter(|d| d.severity == oa_core::validation::Severity::Error)
|
||||
.collect();
|
||||
assert!(errors.is_empty(), "{errors:?}");
|
||||
App::with_project(p)
|
||||
}
|
||||
fn id(app: &App, alias: &str) -> Id {
|
||||
app.project()
|
||||
.identities()
|
||||
.into_iter()
|
||||
.find(|(_, a)| *a == alias)
|
||||
.unwrap()
|
||||
.0
|
||||
}
|
||||
fn representation(view: Id) -> Representation {
|
||||
Representation::Saved { diagram: view }
|
||||
}
|
||||
fn find(app: &App, subject: Id, view: Id) -> Usage {
|
||||
usage::saved_usages_for(app.project(), subject, Some(view))
|
||||
.into_iter()
|
||||
.find(|row| row.target == Target::ScenarioObject(subject))
|
||||
.expect("exact saved occurrence")
|
||||
}
|
||||
fn context(app: &App) -> behavior::scenario::Context {
|
||||
let owner = app.behavior.active_owner.unwrap();
|
||||
app.behavior
|
||||
.scenario
|
||||
.context(
|
||||
app.canvas_document,
|
||||
owner,
|
||||
app.document.revision(),
|
||||
app.canvas_epoch,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn navigate(app: &mut App, subject: Id, view: Id) -> Id {
|
||||
let (token, rows) = open(app, subject);
|
||||
let found = rows
|
||||
.into_iter()
|
||||
.find(|u| u.surface == Surface::Saved(view) && u.target == Target::ScenarioObject(subject))
|
||||
.expect("saved chooser destination");
|
||||
choose(app, token, found);
|
||||
assert!(app.diagram_usages.is_none());
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(app.active_diagram, Some(view));
|
||||
assert_eq!(
|
||||
app.behavior.scenario.representation(),
|
||||
Some(representation(view))
|
||||
);
|
||||
assert_eq!(app.selected, subject);
|
||||
token
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_queries_use_each_actual_presentation_and_keep_repeated_appearances_and_references_opaque()
|
||||
{
|
||||
let app = fixture();
|
||||
let owner = id(&app, "incident_response");
|
||||
let first = id(&app, "initial_report");
|
||||
let second = id(&app, "updated_report");
|
||||
let exchange = id(&app, "incident_report");
|
||||
let latent = id(&app, "unfinished_notice");
|
||||
let callee_message = id(&app, "review_delivery");
|
||||
let views = ["incident_readable", "incident_wide", "incident_repair"].map(|a| id(&app, a));
|
||||
let derived = app
|
||||
.behavior
|
||||
.scenario
|
||||
.diagram_usages(app.project(), owner, first)
|
||||
.pop()
|
||||
.unwrap();
|
||||
let rows = views.map(|view| find(&app, first, view));
|
||||
assert_eq!(rows[0].bounds.y - derived.bounds.y, 12.);
|
||||
assert_ne!(rows[0].bounds, rows[1].bounds);
|
||||
assert_eq!(
|
||||
rows[2].bounds, derived.bounds,
|
||||
"complete fallback cannot retain the authored lane override"
|
||||
);
|
||||
for view in views {
|
||||
let represented = usage::saved_usages_for(app.project(), exchange, Some(view));
|
||||
assert_eq!(represented.len(), 2);
|
||||
assert!(
|
||||
represented
|
||||
.iter()
|
||||
.any(|u| u.target == Target::ScenarioObject(first))
|
||||
);
|
||||
assert!(
|
||||
represented
|
||||
.iter()
|
||||
.any(|u| u.target == Target::ScenarioObject(second))
|
||||
);
|
||||
assert!(
|
||||
represented
|
||||
.iter()
|
||||
.all(|u| u.surface == Surface::Saved(view))
|
||||
);
|
||||
assert!(usage::saved_usages_for(app.project(), callee_message, Some(view)).is_empty());
|
||||
assert_eq!(
|
||||
find(&app, latent, view).target,
|
||||
Target::ScenarioObject(latent)
|
||||
);
|
||||
let shown = presentation::present(app.project(), representation(view), owner);
|
||||
let whole = usage::saved_usages_for(app.project(), view, Some(view));
|
||||
assert_eq!(whole.len(), 1);
|
||||
assert_eq!(whole[0].target, Target::Whole);
|
||||
assert_eq!(Some(whole[0].bounds), shown.bounds());
|
||||
}
|
||||
let wide = presentation::present(app.project(), representation(views[1]), owner)
|
||||
.bounds()
|
||||
.unwrap();
|
||||
assert!(wide.x < -500. && wide.x + wide.width > 50000.);
|
||||
let fallback = presentation::present(app.project(), representation(views[2]), owner);
|
||||
assert!(matches!(
|
||||
fallback.status(),
|
||||
PresentationStatus::Fallback { .. }
|
||||
));
|
||||
assert_eq!(fallback.latent_messages(), &[latent]);
|
||||
assert!(!fallback.capabilities().coordinate_input);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_chooser_and_explicit_reveal_preserve_complete_source_and_actual_undo_redo() {
|
||||
for alias in ["incident_readable", "incident_wide", "incident_repair"] {
|
||||
let mut app = fixture();
|
||||
let view = id(&app, alias);
|
||||
let first = id(&app, "initial_report");
|
||||
let owner = id(&app, "incident_response");
|
||||
let original = app.document.snapshot();
|
||||
app.document
|
||||
.execute(Command::Rename(first, "Reviewed incident report".into()))
|
||||
.unwrap();
|
||||
let edited = app.document.snapshot();
|
||||
app.sync_source();
|
||||
app.refresh_draft();
|
||||
let before = authored(&app);
|
||||
navigate(&mut app, first, view);
|
||||
assert_eq!(app.behavior.active_owner, Some(owner));
|
||||
assert_eq!(authored(&app), before);
|
||||
send(&mut app, Message::RevealInDiagram(view, first));
|
||||
assert_eq!(app.active_diagram, Some(view));
|
||||
assert_eq!(authored(&app), before);
|
||||
assert!(app.document.undo());
|
||||
assert_eq!(app.project(), &original.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
assert!(app.document.redo());
|
||||
assert_eq!(app.project(), &edited.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &edited.bundle);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_reveal_and_chooser_refuse_source_property_and_behavior_drafts() {
|
||||
for chooser in [false, true] {
|
||||
for block in 0..3 {
|
||||
let mut app = fixture();
|
||||
let view = id(&app, "incident_repair");
|
||||
let first = id(&app, "initial_report");
|
||||
let choice = chooser.then(|| {
|
||||
let (token, rows) = open(&mut app, first);
|
||||
(
|
||||
token,
|
||||
rows.into_iter()
|
||||
.find(|u| u.surface == Surface::Saved(view))
|
||||
.unwrap(),
|
||||
)
|
||||
});
|
||||
match block {
|
||||
0 => {
|
||||
let cursor = app.source_editor.cursor();
|
||||
app.source_workspace
|
||||
.edit("? preserve unfinished source".into(), cursor);
|
||||
}
|
||||
1 => {
|
||||
app.draft
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.input("/name", "Unapplied inspector value".into());
|
||||
assert!(app.draft_dirty());
|
||||
}
|
||||
_ => {
|
||||
let p = app.project().clone();
|
||||
app.behavior
|
||||
.creation
|
||||
.update(&p, behavior::creation::Event::Open(Layer::Oa))
|
||||
.unwrap();
|
||||
assert!(app.behavior.has_pending());
|
||||
}
|
||||
}
|
||||
let before = authored(&app);
|
||||
let prior = location(&app);
|
||||
let draft = app
|
||||
.draft
|
||||
.as_ref()
|
||||
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap());
|
||||
if let Some((token, row)) = choice {
|
||||
choose(&mut app, token, row);
|
||||
} else {
|
||||
send(&mut app, Message::RevealInDiagram(view, first));
|
||||
}
|
||||
assert_eq!(authored(&app), before);
|
||||
assert_eq!(location(&app), prior);
|
||||
assert_eq!(
|
||||
app.draft
|
||||
.as_ref()
|
||||
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap()),
|
||||
draft
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_a_b_a_rejects_old_visit_and_panel_callbacks_before_deferred_measurement() {
|
||||
let mut app = fixture();
|
||||
let a = id(&app, "incident_readable");
|
||||
let b = id(&app, "incident_wide");
|
||||
let first = id(&app, "initial_report");
|
||||
let before = authored(&app);
|
||||
let old_token = navigate(&mut app, first, a);
|
||||
let old = context(&app);
|
||||
navigate(&mut app, first, b);
|
||||
navigate(&mut app, first, a);
|
||||
let current = context(&app);
|
||||
assert_ne!(old.visit, current.visit);
|
||||
let held = behavior::scenario::Context {
|
||||
epoch: current.epoch,
|
||||
..old
|
||||
};
|
||||
let camera = app.behavior.scenario.camera_boundary();
|
||||
send(
|
||||
&mut app,
|
||||
Message::ScenarioCanvas(CanvasEvent::Viewport(held, Size::new(900., 900.))),
|
||||
);
|
||||
send(
|
||||
&mut app,
|
||||
Message::ScenarioCanvas(CanvasEvent::Shelf(
|
||||
held,
|
||||
crate::behavior::scenario::Shelf::Selection,
|
||||
)),
|
||||
);
|
||||
send(
|
||||
&mut app,
|
||||
Message::DiagramUsage(Event::Search(old_token, "obsolete filter".into())),
|
||||
);
|
||||
send(&mut app, Message::DiagramUsage(Event::Close(old_token)));
|
||||
assert_eq!(app.pending_scenario_reveal_visit, Some(current.visit));
|
||||
assert!(app.pending_diagram_reveal.is_some());
|
||||
assert!(app.behavior.scenario.camera_boundary() == camera);
|
||||
let bounds = find(&app, first, a).bounds;
|
||||
send(
|
||||
&mut app,
|
||||
Message::ScenarioCanvas(CanvasEvent::Viewport(current, Size::new(500., 300.))),
|
||||
);
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert_eq!(context(&app).visit, current.visit);
|
||||
let mut expected = State::default();
|
||||
expected.enter_representation(app.canvas_document, current.scenario, representation(a));
|
||||
expected.viewport(Size::new(500., 300.));
|
||||
expected.zoom(Some(1.25));
|
||||
expected.camera(
|
||||
app.project(),
|
||||
current.scenario,
|
||||
behavior::canvas_workspace::Event::Pan(Vector::new(
|
||||
250. - bounds.center_x() * 1.25,
|
||||
150. - bounds.center_y() * 1.25,
|
||||
)),
|
||||
);
|
||||
assert!(app.behavior.scenario.camera_boundary() == expected.camera_boundary());
|
||||
assert_eq!(authored(&app), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retargeted_saved_view_cannot_reveal_a_former_owner_occurrence() {
|
||||
let mut app = fixture();
|
||||
let first = id(&app, "initial_report");
|
||||
let view = id(&app, "incident_readable");
|
||||
let other = id(&app, "reporting_review");
|
||||
let (token, rows) = open(&mut app, first);
|
||||
let old = rows
|
||||
.into_iter()
|
||||
.find(|u| u.surface == Surface::Saved(view))
|
||||
.unwrap();
|
||||
let mut replacement = app.project().diagrams[&view].clone();
|
||||
replacement.projection = ProjectionKind::Scenario { scenario: other };
|
||||
replacement.layout = None;
|
||||
app.document
|
||||
.execute(Command::EditDiagram(view, replacement))
|
||||
.unwrap();
|
||||
app.sync_source();
|
||||
app.refresh_draft();
|
||||
let before = authored(&app);
|
||||
let prior = location(&app);
|
||||
choose(&mut app, token, old);
|
||||
assert_eq!(location(&app), prior);
|
||||
assert_eq!(authored(&app), before);
|
||||
finish_lookup(&mut app);
|
||||
let token = app.diagram_usages.as_ref().unwrap().token;
|
||||
assert!(
|
||||
app.diagram_usages
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.usages
|
||||
.iter()
|
||||
.all(|u| u.surface != Surface::Saved(view))
|
||||
);
|
||||
send(&mut app, Message::DiagramUsage(Event::Close(token)));
|
||||
send(&mut app, Message::RevealInDiagram(view, first));
|
||||
assert_eq!(location(&app), prior);
|
||||
assert_eq!(authored(&app), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_saved_layout_repair_undo_redo_requeries_authored_and_fallback_geometry_without_extra_history()
|
||||
{
|
||||
let mut app = fixture();
|
||||
let view = id(&app, "incident_repair");
|
||||
let first = id(&app, "initial_report");
|
||||
let reply = id(&app, "assess_reply");
|
||||
let before = app.document.snapshot();
|
||||
let fallback = find(&app, first, view);
|
||||
app.document
|
||||
.execute(Command::SetScenarioMessagePosition {
|
||||
diagram: view,
|
||||
position: oa_core::ScenarioMessagePosition {
|
||||
address: oa_core::OccurrenceEndpoint {
|
||||
references: vec![],
|
||||
occurrence: reply,
|
||||
},
|
||||
send_y: 424.,
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
app.sync_source();
|
||||
app.refresh_draft();
|
||||
let repaired = app.document.snapshot();
|
||||
let authored_row = find(&app, first, view);
|
||||
assert_ne!(authored_row.bounds, fallback.bounds);
|
||||
navigate(&mut app, first, view);
|
||||
assert!(app.document.undo());
|
||||
app.sync_source();
|
||||
app.refresh_draft();
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert_eq!(find(&app, first, view).bounds, fallback.bounds);
|
||||
assert!(app.document.redo());
|
||||
app.sync_source();
|
||||
app.refresh_draft();
|
||||
assert_eq!(app.project(), &repaired.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &repaired.bundle);
|
||||
assert_eq!(find(&app, first, view).bounds, authored_row.bounds);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! Keep overlay Escape ahead of modal cancellation in the ordinary widget tree.
|
||||
//!
|
||||
//! Iced skips root.update when an overlay captures an event. Keeping this
|
||||
//! wrapper present even when inactive preserves the child's widget state. A
|
||||
//! current-overlay preflight also handles pickers opened mid-batch. Passive
|
||||
//! overlays may see an ignored Escape again: the raw-input observer only makes
|
||||
//! pending focus requests stale; it does not publish modal cancellation.
|
||||
use super::{App, Message, Page, architecture_authoring};
|
||||
use iced::advanced::{Clipboard, Layout, Shell, Widget, layout, overlay, renderer, widget};
|
||||
use iced::{Element, Event, Length, Rectangle, Size, Theme, Vector, keyboard, mouse};
|
||||
|
||||
pub(crate) fn root<'a, R: renderer::Renderer + 'a>(
|
||||
app: &App,
|
||||
content: Element<'a, Message, Theme, R>,
|
||||
) -> Element<'a, Message, Theme, R> {
|
||||
let modal = app.text_workspace.menu().is_none()
|
||||
&& (app.context_help
|
||||
|| app.behavior.creation.has_pending()
|
||||
|| app.diagram_usages.is_some()
|
||||
|| app.behavior.source_active()
|
||||
|| (app.page == Page::Text
|
||||
&& (app.text_workspace.drawer().is_some()
|
||||
|| app.source_navigation.open
|
||||
|| app.source_rename.open())
|
||||
&& app.architecture.is_none()));
|
||||
Element::new(Bridge {
|
||||
content,
|
||||
messages: [
|
||||
architecture_authoring::captured_escape_message(app),
|
||||
modal.then_some(Message::Escape),
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
struct Bridge<'a, R> {
|
||||
content: Element<'a, Message, Theme, R>,
|
||||
messages: [Option<Message>; 2],
|
||||
}
|
||||
|
||||
impl<R: renderer::Renderer> Widget<Message, Theme, R> for Bridge<'_, R> {
|
||||
fn children(&self) -> Vec<widget::Tree> {
|
||||
vec![widget::Tree::new(self.content.as_widget())]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut widget::Tree) {
|
||||
tree.diff_children(std::slice::from_ref(&self.content));
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
self.content.as_widget().size()
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Size<Length> {
|
||||
self.content.as_widget().size_hint()
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
tree: &mut widget::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 widget::Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &R,
|
||||
operation: &mut dyn widget::Operation,
|
||||
) {
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.operate(&mut tree.children[0], layout, renderer, operation);
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
tree: &mut widget::Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &R,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let escape = matches!(
|
||||
event,
|
||||
Event::Keyboard(keyboard::Event::KeyPressed {
|
||||
key: keyboard::Key::Named(keyboard::key::Named::Escape),
|
||||
..
|
||||
})
|
||||
);
|
||||
// Iced collects overlays before processing a batch of base events. A
|
||||
// preceding click in that batch can therefore open a picker whose
|
||||
// Escape would otherwise reach focused fields underneath it. Offer only
|
||||
// Escape to the current overlay before updating the ordinary tree.
|
||||
if escape {
|
||||
if let Some(element) = self.content.as_widget_mut().overlay(
|
||||
&mut tree.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
Vector::ZERO,
|
||||
) {
|
||||
let mut overlay = overlay::Nested::new(element);
|
||||
let node = overlay.layout(renderer, viewport.size());
|
||||
overlay.update(
|
||||
event,
|
||||
Layout::new(&node),
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
);
|
||||
}
|
||||
if shell.is_event_captured() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.content.as_widget_mut().update(
|
||||
&mut tree.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
if shell.is_event_captured() && escape {
|
||||
for message in self.messages.iter().flatten() {
|
||||
shell.publish(message.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &widget::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,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &widget::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 widget::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,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
@@ -0,0 +1,618 @@
|
||||
use super::*;
|
||||
use crate::behavior::canvas_workspace::tests::key;
|
||||
use iced::advanced::{subscription, widget::operation};
|
||||
use iced::futures::{StreamExt, stream, task::noop_waker_ref};
|
||||
use iced::keyboard::key::Named;
|
||||
use iced::widget::{column, container, pick_list, text_input};
|
||||
use iced_runtime::user_interface::{Cache, UserInterface};
|
||||
use oa_core::{Layer, Project};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
struct FocusInputs;
|
||||
impl widget::Operation for FocusInputs {
|
||||
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn widget::Operation)) {
|
||||
visit(self);
|
||||
}
|
||||
fn focusable(
|
||||
&mut self,
|
||||
_: Option<&widget::Id>,
|
||||
_: Rectangle,
|
||||
state: &mut dyn operation::Focusable,
|
||||
) {
|
||||
state.focus();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn subscriptions(
|
||||
app: &App,
|
||||
event: Event,
|
||||
status: iced::event::Status,
|
||||
messages: &mut Vec<Message>,
|
||||
) {
|
||||
let interaction = subscription::Event::Interaction {
|
||||
window: iced::window::Id::unique(),
|
||||
event,
|
||||
status,
|
||||
};
|
||||
let mut boundaries = 0;
|
||||
for recipe in subscription::into_recipes(app.subscription()) {
|
||||
let mut output = recipe.stream(Box::pin(stream::iter([interaction.clone()])));
|
||||
let mut cx = Context::from_waker(noop_waker_ref());
|
||||
while let Poll::Ready(Some(message)) = output.poll_next_unpin(&mut cx) {
|
||||
if matches!(
|
||||
message,
|
||||
Message::WorkDrag(crate::app::allocation_drag::Event::KeyboardBoundary)
|
||||
) {
|
||||
boundaries += 1;
|
||||
} else {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
boundaries, 1,
|
||||
"one passive allocation keyboard notification"
|
||||
);
|
||||
}
|
||||
|
||||
/// A real focused text input, production root bridge, UserInterface dispatch,
|
||||
/// and actual subscriptions. Existing app-policy tests use this instead of
|
||||
/// pretending every captured event came from a text control.
|
||||
pub(crate) fn focused_input_messages(app: &App) -> Vec<Message> {
|
||||
focused_input_key(app, Named::Escape)
|
||||
}
|
||||
|
||||
pub(crate) fn focused_input_key(app: &App, named: Named) -> Vec<Message> {
|
||||
input_messages(app, named, true)
|
||||
}
|
||||
|
||||
pub(crate) fn input_messages(app: &App, named: Named, focused: bool) -> Vec<Message> {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
let _entered = runtime.enter();
|
||||
let input: Element<'_, Message, Theme, ()> = text_input("Retained input", "Uncommitted 雨")
|
||||
.on_input(|_| Message::Escape)
|
||||
.into();
|
||||
let mut renderer = ();
|
||||
let mut ui = UserInterface::build(
|
||||
root(app, input),
|
||||
Size::new(400., 100.),
|
||||
Cache::new(),
|
||||
&mut renderer,
|
||||
);
|
||||
if focused {
|
||||
ui.operate(&renderer, &mut FocusInputs);
|
||||
}
|
||||
let event = key(named);
|
||||
let mut messages = vec![];
|
||||
let (_, statuses) = ui.update(
|
||||
std::slice::from_ref(&event),
|
||||
mouse::Cursor::Unavailable,
|
||||
&mut renderer,
|
||||
&mut iced::advanced::clipboard::Null,
|
||||
&mut messages,
|
||||
);
|
||||
if named == Named::Escape {
|
||||
assert_eq!(
|
||||
statuses,
|
||||
[if focused {
|
||||
iced::event::Status::Captured
|
||||
} else {
|
||||
iced::event::Status::Ignored
|
||||
}]
|
||||
);
|
||||
}
|
||||
subscriptions(app, event, statuses[0], &mut messages);
|
||||
messages
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum PickMessage {
|
||||
Selected(&'static str),
|
||||
Opened,
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn picker(
|
||||
selected: Option<&'static str>,
|
||||
notify: bool,
|
||||
) -> Element<'static, PickMessage, Theme, ()> {
|
||||
let list = pick_list(["Alpha", "Beta"], selected, PickMessage::Selected)
|
||||
.width(200)
|
||||
.padding(10)
|
||||
.text_size(16)
|
||||
.on_open(PickMessage::Opened);
|
||||
if notify {
|
||||
list.on_close(PickMessage::Closed).into()
|
||||
} else {
|
||||
list.into()
|
||||
}
|
||||
}
|
||||
|
||||
fn update<M>(
|
||||
ui: &mut UserInterface<'_, M, Theme, ()>,
|
||||
events: &[Event],
|
||||
cursor: mouse::Cursor,
|
||||
) -> (Vec<M>, Vec<iced::event::Status>) {
|
||||
let mut messages = vec![];
|
||||
let (_, statuses) = ui.update(
|
||||
events,
|
||||
cursor,
|
||||
&mut (),
|
||||
&mut iced::advanced::clipboard::Null,
|
||||
&mut messages,
|
||||
);
|
||||
(messages, statuses)
|
||||
}
|
||||
|
||||
fn press_at(point: iced::Point) -> (Vec<Event>, mouse::Cursor) {
|
||||
(
|
||||
vec![
|
||||
Event::Mouse(mouse::Event::CursorMoved { position: point }),
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
|
||||
],
|
||||
mouse::Cursor::Available(point),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picker_overlay_escape_closes_once_reopens_selects_and_retains_outside_click() {
|
||||
for selected in [None, Some("Alpha")] {
|
||||
for notify in [false, true] {
|
||||
let mut ui = UserInterface::build(
|
||||
picker(selected, notify),
|
||||
Size::new(400., 300.),
|
||||
Cache::new(),
|
||||
&mut (),
|
||||
);
|
||||
let (click, cursor) = press_at(iced::Point::new(50., 15.));
|
||||
assert_eq!(update(&mut ui, &click, cursor).0, [PickMessage::Opened]);
|
||||
let cache = ui.into_cache();
|
||||
let mut ui = UserInterface::build(
|
||||
picker(selected, notify),
|
||||
Size::new(400., 300.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
let (messages, statuses) = update(
|
||||
&mut ui,
|
||||
&[key(Named::Escape), key(Named::Escape)],
|
||||
mouse::Cursor::Unavailable,
|
||||
);
|
||||
assert_eq!(
|
||||
messages,
|
||||
if notify {
|
||||
vec![PickMessage::Closed]
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
statuses,
|
||||
[iced::event::Status::Captured, iced::event::Status::Ignored]
|
||||
);
|
||||
let cache = ui.into_cache();
|
||||
let mut ui = UserInterface::build(
|
||||
picker(selected, notify),
|
||||
Size::new(400., 300.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
assert_eq!(update(&mut ui, &click, cursor).0, [PickMessage::Opened]);
|
||||
let cache = ui.into_cache();
|
||||
let mut ui = UserInterface::build(
|
||||
picker(selected, notify),
|
||||
Size::new(400., 300.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
let (outside, cursor) = press_at(iced::Point::new(350., 250.));
|
||||
assert_eq!(
|
||||
update(&mut ui, &outside, cursor).0,
|
||||
if notify {
|
||||
vec![PickMessage::Closed]
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
);
|
||||
let cache = ui.into_cache();
|
||||
let mut ui = UserInterface::build(
|
||||
picker(selected, notify),
|
||||
Size::new(400., 300.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
let (click, cursor) = press_at(iced::Point::new(50., 15.));
|
||||
assert_eq!(update(&mut ui, &click, cursor).0, [PickMessage::Opened]);
|
||||
let cache = ui.into_cache();
|
||||
let mut ui = UserInterface::build(
|
||||
picker(selected, notify),
|
||||
Size::new(400., 300.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
// Default 16px text uses 1.3 line-height: button/option height 40.8.
|
||||
let (option, cursor) = press_at(iced::Point::new(50., 100.));
|
||||
assert_eq!(
|
||||
update(&mut ui, &option, cursor).0,
|
||||
[PickMessage::Selected("Beta")]
|
||||
);
|
||||
let cache = ui.into_cache();
|
||||
let mut ui = UserInterface::build(
|
||||
picker(Some("Beta"), notify),
|
||||
Size::new(400., 300.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
assert_eq!(
|
||||
update(&mut ui, &[key(Named::Escape)], mouse::Cursor::Unavailable),
|
||||
(vec![], vec![iced::event::Status::Ignored])
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initially_closed_picker_handles_open_then_escape_in_one_runtime_batch() {
|
||||
for notify in [false, true] {
|
||||
let mut ui = UserInterface::build(
|
||||
picker(Some("Alpha"), notify),
|
||||
Size::new(400., 300.),
|
||||
Cache::new(),
|
||||
&mut (),
|
||||
);
|
||||
let (mut events, cursor) = press_at(iced::Point::new(50., 15.));
|
||||
events.push(key(Named::Escape));
|
||||
let (messages, statuses) = update(&mut ui, &events, cursor);
|
||||
assert_eq!(
|
||||
messages,
|
||||
if notify {
|
||||
vec![PickMessage::Opened, PickMessage::Closed]
|
||||
} else {
|
||||
vec![PickMessage::Opened]
|
||||
}
|
||||
);
|
||||
assert_eq!(statuses.last(), Some(&iced::event::Status::Captured));
|
||||
assert_eq!(
|
||||
update(&mut ui, &[key(Named::Escape)], mouse::Cursor::Unavailable),
|
||||
(vec![], vec![iced::event::Status::Ignored])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dismissed_picker_ignores_a_queued_click_in_its_old_option_area() {
|
||||
let mut ui = UserInterface::build(
|
||||
picker(Some("Alpha"), true),
|
||||
Size::new(400., 300.),
|
||||
Cache::new(),
|
||||
&mut (),
|
||||
);
|
||||
let (click, cursor) = press_at(iced::Point::new(50., 15.));
|
||||
assert_eq!(update(&mut ui, &click, cursor).0, [PickMessage::Opened]);
|
||||
let cache = ui.into_cache();
|
||||
let mut ui = UserInterface::build(
|
||||
picker(Some("Alpha"), true),
|
||||
Size::new(400., 300.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
let (click, cursor) = press_at(iced::Point::new(50., 100.));
|
||||
let mut batch = vec![key(Named::Escape)];
|
||||
batch.extend(click);
|
||||
let (messages, _) = update(&mut ui, &batch, cursor);
|
||||
assert_eq!(
|
||||
messages,
|
||||
[PickMessage::Closed],
|
||||
"queued old-option click must not select Beta"
|
||||
);
|
||||
}
|
||||
|
||||
fn draft_with_picker(app: &App) -> Element<'_, Message, Theme, ()> {
|
||||
// This composition deliberately keeps a focused input beneath the actual
|
||||
// picker overlay. It tests event ownership, not a claimed production form.
|
||||
root(
|
||||
app,
|
||||
crate::source_navigation::interaction::observe(
|
||||
column![
|
||||
container(
|
||||
text_input("Raw draft", "Keep exact bytes 雨").on_input(|_| Message::Escape)
|
||||
)
|
||||
.height(40),
|
||||
pick_list([Layer::Oa, Layer::Sa], Some(Layer::Oa), Message::Layer)
|
||||
.width(200)
|
||||
.padding(10),
|
||||
]
|
||||
.into(),
|
||||
app.source_symbols.raw_interaction.clone(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picker_overlay_precedes_focused_input_and_creation_source_drafts() {
|
||||
use crate::behavior::{Event as BehaviorEvent, creation, source_draft};
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
let _entered = runtime.enter();
|
||||
for (source, same_batch) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let mut app = App::with_project(Project::empty());
|
||||
let send = |app: &mut App, event| {
|
||||
let _ = app.update(Message::Behavior(BehaviorEvent::Creation(event)));
|
||||
};
|
||||
send(&mut app, creation::Event::Open(Layer::Oa));
|
||||
send(&mut app, creation::Event::Choose(creation::Family::Machine));
|
||||
send(
|
||||
&mut app,
|
||||
creation::Event::Name("Retained machine 雨".into()),
|
||||
);
|
||||
if source {
|
||||
let recovery = app.behavior.creation.recovery_snapshot().unwrap().unwrap();
|
||||
let invocation = serde_json::from_value(recovery["invocation"].clone()).unwrap();
|
||||
send(
|
||||
&mut app,
|
||||
creation::Event::Source(source_draft::Event::Open(invocation)),
|
||||
);
|
||||
let recovery = app.behavior.creation.recovery_snapshot().unwrap().unwrap();
|
||||
let token =
|
||||
serde_json::from_value(recovery["source"]["editing"]["token"].clone()).unwrap();
|
||||
send(
|
||||
&mut app,
|
||||
creation::Event::Source(source_draft::Event::Edit(
|
||||
token,
|
||||
source_draft::Edit::Name("Uncommitted owner 雨".into()),
|
||||
)),
|
||||
);
|
||||
assert_eq!(
|
||||
app.behavior.creation.recovery_snapshot().unwrap().unwrap()["source"]["editing"]["name"],
|
||||
"Uncommitted owner 雨"
|
||||
);
|
||||
}
|
||||
let draft = app.behavior.recovery_snapshot().unwrap();
|
||||
let project = app.project().clone();
|
||||
let bundle = app.document.bundle().clone();
|
||||
let revision = app.document.revision();
|
||||
let selection = (app.selected, app.selected_node, app.active_diagram);
|
||||
let camera = (app.pan, app.zoom);
|
||||
let raw_epoch = app
|
||||
.source_symbols
|
||||
.raw_interaction
|
||||
.load(std::sync::atomic::Ordering::Acquire);
|
||||
let mut ui = UserInterface::build(
|
||||
draft_with_picker(&app),
|
||||
Size::new(500., 400.),
|
||||
Cache::new(),
|
||||
&mut (),
|
||||
);
|
||||
let event = key(Named::Escape);
|
||||
let (mut click, cursor) = press_at(iced::Point::new(50., 55.));
|
||||
let (mut messages, statuses) = if same_batch {
|
||||
ui.operate(&(), &mut FocusInputs);
|
||||
click.push(event.clone());
|
||||
update(&mut ui, &click, cursor)
|
||||
} else {
|
||||
assert!(update(&mut ui, &click, cursor).0.is_empty());
|
||||
let cache = ui.into_cache();
|
||||
ui = UserInterface::build(
|
||||
draft_with_picker(&app),
|
||||
Size::new(500., 400.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
ui.operate(&(), &mut FocusInputs);
|
||||
update(
|
||||
&mut ui,
|
||||
std::slice::from_ref(&event),
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
};
|
||||
assert_eq!(statuses.last(), Some(&iced::event::Status::Captured));
|
||||
subscriptions(&app, event, *statuses.last().unwrap(), &mut messages);
|
||||
assert!(
|
||||
messages.is_empty(),
|
||||
"picker must not forward global modal cancellation"
|
||||
);
|
||||
let cache = ui.into_cache();
|
||||
assert_eq!(app.behavior.recovery_snapshot().unwrap(), draft);
|
||||
assert!(!crate::source_navigation::interaction::is_current(
|
||||
&app.source_symbols.raw_interaction,
|
||||
raw_epoch,
|
||||
));
|
||||
let mut ui = UserInterface::build(
|
||||
draft_with_picker(&app),
|
||||
Size::new(500., 400.),
|
||||
cache,
|
||||
&mut (),
|
||||
);
|
||||
let event = key(Named::Escape);
|
||||
let (mut messages, statuses) = update(
|
||||
&mut ui,
|
||||
std::slice::from_ref(&event),
|
||||
mouse::Cursor::Unavailable,
|
||||
);
|
||||
subscriptions(&app, event, statuses[0], &mut messages);
|
||||
assert_eq!(messages.len(), 1);
|
||||
assert!(matches!(messages[0], Message::Escape));
|
||||
drop(ui);
|
||||
let _ = app.update(messages.remove(0));
|
||||
if source {
|
||||
assert!(app.behavior.creation.has_pending());
|
||||
assert!(!app.behavior.creation.source_open());
|
||||
assert_eq!(
|
||||
app.behavior.creation.recovery_snapshot().unwrap().unwrap()["name"],
|
||||
"Retained machine 雨"
|
||||
);
|
||||
} else {
|
||||
assert!(!app.behavior.creation.has_pending());
|
||||
}
|
||||
assert_eq!(app.project(), &project);
|
||||
assert_eq!(app.document.bundle(), &bundle);
|
||||
assert_eq!(app.document.revision(), revision);
|
||||
assert_eq!(
|
||||
(app.selected, app.selected_node, app.active_diagram),
|
||||
selection
|
||||
);
|
||||
assert_eq!((app.pan, app.zoom), camera);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_tooltip_escape_preserves_modal_priority_and_rejects_stale_focus() {
|
||||
use crate::source_navigation::interaction;
|
||||
use iced::widget::{text, tooltip};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
let _entered = runtime.enter();
|
||||
let mut app = App::with_project(Project::empty());
|
||||
app.page = Page::Text;
|
||||
app.source_navigation.open = true;
|
||||
let project = app.project().clone();
|
||||
let source = app.document.bundle().clone();
|
||||
let context = (
|
||||
app.selected,
|
||||
app.selected_node,
|
||||
app.active_diagram,
|
||||
app.pan,
|
||||
app.zoom,
|
||||
);
|
||||
let content = || -> Element<'_, Message, Theme, ()> {
|
||||
let field = text_input("Find", "Retained query 雨").on_input(|_| Message::Escape);
|
||||
let tip = tooltip(field, text("Help"), tooltip::Position::Bottom)
|
||||
.delay(std::time::Duration::ZERO);
|
||||
root(
|
||||
&app,
|
||||
interaction::observe(tip.into(), app.source_symbols.raw_interaction.clone()),
|
||||
)
|
||||
};
|
||||
let mut ui = UserInterface::build(content(), Size::new(400., 180.), Cache::new(), &mut ());
|
||||
let point = iced::Point::new(10., 10.);
|
||||
let cursor = mouse::Cursor::Available(point);
|
||||
assert!(
|
||||
update(
|
||||
&mut ui,
|
||||
&[Event::Mouse(mouse::Event::CursorMoved { position: point })],
|
||||
cursor
|
||||
)
|
||||
.0
|
||||
.is_empty()
|
||||
);
|
||||
let cache = ui.into_cache();
|
||||
let mut ui = UserInterface::build(content(), Size::new(400., 180.), cache, &mut ());
|
||||
ui.operate(&(), &mut FocusInputs);
|
||||
let epoch = app.source_symbols.raw_interaction.load(Ordering::Acquire);
|
||||
let event = key(Named::Escape);
|
||||
let (mut messages, statuses) = update(&mut ui, std::slice::from_ref(&event), cursor);
|
||||
assert_eq!(statuses, [iced::event::Status::Captured]);
|
||||
subscriptions(&app, event, statuses[0], &mut messages);
|
||||
assert_eq!(messages.len(), 1);
|
||||
assert!(matches!(messages[0], Message::Escape));
|
||||
assert!(!interaction::is_current(
|
||||
&app.source_symbols.raw_interaction,
|
||||
epoch
|
||||
));
|
||||
drop(ui);
|
||||
let _ = app.update(messages.remove(0));
|
||||
assert!(!app.source_navigation.open);
|
||||
assert_eq!(app.project(), &project);
|
||||
assert_eq!(app.document.bundle(), &source);
|
||||
assert_eq!(
|
||||
(
|
||||
app.selected,
|
||||
app.selected_node,
|
||||
app.active_diagram,
|
||||
app.pan,
|
||||
app.zoom
|
||||
),
|
||||
context
|
||||
);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggling_bridge_policy_retains_focused_child_state() {
|
||||
let mut app = App::with_project(Project::empty());
|
||||
let content = || -> Element<'static, Message, Theme, ()> {
|
||||
text_input("Raw field", "Still focused")
|
||||
.on_input(|_| Message::Escape)
|
||||
.into()
|
||||
};
|
||||
let mut ui = UserInterface::build(
|
||||
root(&app, content()),
|
||||
Size::new(400., 100.),
|
||||
Cache::new(),
|
||||
&mut (),
|
||||
);
|
||||
ui.operate(&(), &mut FocusInputs);
|
||||
let cache = ui.into_cache();
|
||||
app.page = Page::Text;
|
||||
app.source_navigation.open = true;
|
||||
let mut ui = UserInterface::build(root(&app, content()), Size::new(400., 100.), cache, &mut ());
|
||||
let (messages, status) = update(&mut ui, &[key(Named::Escape)], mouse::Cursor::Unavailable);
|
||||
assert_eq!(status, [iced::event::Status::Captured]);
|
||||
assert_eq!(messages.len(), 1);
|
||||
assert!(matches!(messages[0], Message::Escape));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_creation_name_escape_keeps_pending_modal_priority() {
|
||||
use crate::behavior::canvas_workspace::tests::Mounted;
|
||||
use crate::behavior::{Event as BehaviorEvent, creation};
|
||||
for pending in [false, true] {
|
||||
let mut app = App::with_project(Project::empty());
|
||||
for event in [
|
||||
creation::Event::Open(Layer::Oa),
|
||||
creation::Event::Choose(creation::Family::Sequence),
|
||||
creation::Event::Name("Exact unfinished process 雨".into()),
|
||||
] {
|
||||
let _ = app.update(Message::Behavior(BehaviorEvent::Creation(event)));
|
||||
}
|
||||
app.page = Page::Behavior;
|
||||
let mut mounted = Mounted::new(&mut app).await;
|
||||
mounted
|
||||
.perform(
|
||||
&mut app,
|
||||
iced::widget::operation::focus(creation::NAME_INPUT),
|
||||
)
|
||||
.await;
|
||||
if pending {
|
||||
app.pending = Some(super::super::Pending::Walkthrough);
|
||||
}
|
||||
let before = app.document.snapshot();
|
||||
let draft = app.behavior.recovery_snapshot().unwrap();
|
||||
let event = key(Named::Escape);
|
||||
let (mut messages, statuses) = mounted.input_with_status(
|
||||
&app,
|
||||
std::slice::from_ref(&event),
|
||||
mouse::Cursor::Unavailable,
|
||||
);
|
||||
subscriptions(&app, event, statuses[0], &mut messages);
|
||||
assert_eq!(
|
||||
messages
|
||||
.iter()
|
||||
.filter(|message| matches!(message, Message::Escape))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
for message in messages {
|
||||
let _ = app.update(message);
|
||||
}
|
||||
if pending {
|
||||
assert!(app.pending.is_none());
|
||||
assert_eq!(app.behavior.recovery_snapshot().unwrap(), draft);
|
||||
} else {
|
||||
assert!(!app.behavior.creation.has_pending());
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
//! Exact saved-view selection and atomic group commands.
|
||||
use super::*;
|
||||
use crate::diagram_selection::{Context, Scope, Selection, Snapshot};
|
||||
use crate::diagram_usage::{Surface, Target};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum Choice {
|
||||
Replace,
|
||||
Add,
|
||||
Remove,
|
||||
Toggle,
|
||||
Inspect,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum Event {
|
||||
Choose(Context, Target, Choice),
|
||||
Collapse(Snapshot, Target),
|
||||
Clear(Context),
|
||||
Move(Snapshot, Position),
|
||||
Hide(Snapshot),
|
||||
ProcessReorder(
|
||||
Snapshot,
|
||||
crate::behavior::topology::group_reorder::Destination,
|
||||
),
|
||||
Refuse(Snapshot, String),
|
||||
}
|
||||
|
||||
pub(crate) fn context(c: crate::route_edit::Context) -> Context {
|
||||
Context {
|
||||
scope: Scope {
|
||||
document: c.document,
|
||||
surface: Surface::Saved(c.diagram),
|
||||
},
|
||||
revision: c.revision,
|
||||
epoch: c.epoch,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn process_context(c: crate::behavior::topology::Context) -> Context {
|
||||
Context {
|
||||
scope: Scope {
|
||||
document: c.document,
|
||||
surface: Surface::Process(c.owner),
|
||||
},
|
||||
revision: c.revision,
|
||||
epoch: c.epoch,
|
||||
}
|
||||
}
|
||||
|
||||
/// The entire typed set must support a placement action. Never filter a mixture.
|
||||
pub(crate) fn placements(snapshot: &Snapshot) -> Option<std::collections::BTreeSet<Id>> {
|
||||
snapshot.primary()?;
|
||||
if snapshot.targets().is_empty() {
|
||||
return None;
|
||||
}
|
||||
snapshot
|
||||
.targets()
|
||||
.iter()
|
||||
.map(|target| match target {
|
||||
Target::Placement(id) => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn visible(
|
||||
project: &Project,
|
||||
diagram: Id,
|
||||
view: &projection::ProjectedView,
|
||||
target: &Target,
|
||||
) -> bool {
|
||||
match target {
|
||||
Target::Placement(id) => view.nodes.iter().any(|n| n.id == *id),
|
||||
Target::Port { port, placement } => view
|
||||
.ports
|
||||
.iter()
|
||||
.any(|p| p.element == *port && p.owner == *placement),
|
||||
Target::Edge(id) => view.edges.iter().any(|e| e.id == *id),
|
||||
Target::StateRow {
|
||||
placement,
|
||||
relation,
|
||||
} => crate::behavior::state_canvas::visible_row_target(
|
||||
project, diagram, view, *placement, *relation,
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(crate) fn multiselect_boundary(&self) -> impl PartialEq + use<> {
|
||||
(
|
||||
self.canvas_document,
|
||||
self.document.revision(),
|
||||
self.page,
|
||||
self.active_diagram,
|
||||
self.selected,
|
||||
self.selected_node,
|
||||
(self.page == Page::Behavior).then(|| self.state_view_identity()),
|
||||
(self.page == Page::Behavior).then_some(self.behavior.diagram.placement),
|
||||
self.topology_context(),
|
||||
self.behavior.topology.selection_address(),
|
||||
)
|
||||
}
|
||||
pub(crate) fn multiselect_context(&self) -> Option<Context> {
|
||||
match self.page {
|
||||
Page::Diagram => self.route_context().map(context),
|
||||
Page::Behavior => {
|
||||
if let Some(current) = self.topology_context() {
|
||||
return Some(process_context(current));
|
||||
}
|
||||
let current = self.state_context()?;
|
||||
crate::behavior::state_edit::validate_context(self.project(), current, current)
|
||||
.ok()?;
|
||||
Some(context(current))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn multiselect_target_visible(&self, target: &Target) -> bool {
|
||||
if let Some(context) = self.topology_context() {
|
||||
return self
|
||||
.behavior
|
||||
.topology
|
||||
.selection_targets(self.project(), context.owner)
|
||||
.contains(target);
|
||||
}
|
||||
let Some(Context {
|
||||
scope:
|
||||
Scope {
|
||||
surface: Surface::Saved(diagram),
|
||||
..
|
||||
},
|
||||
..
|
||||
}) = self.multiselect_context()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let view = projection::project_view_with_index(
|
||||
self.project(),
|
||||
diagram,
|
||||
self.document.view_index(),
|
||||
);
|
||||
visible(self.project(), diagram, &view, target)
|
||||
}
|
||||
|
||||
pub(crate) fn multiselect_snapshot(&self) -> Option<Snapshot> {
|
||||
self.diagram_selection
|
||||
.as_ref()?
|
||||
.snapshot(self.multiselect_context()?)
|
||||
}
|
||||
|
||||
pub(crate) fn multiselect_envelope(&self, event: &Event) -> bool {
|
||||
let Some(current) = self.multiselect_context() else {
|
||||
return false;
|
||||
};
|
||||
match event {
|
||||
Event::Choose(c, ..) | Event::Clear(c) => *c == current,
|
||||
Event::Move(s, _)
|
||||
| Event::Hide(s)
|
||||
| Event::ProcessReorder(s, _)
|
||||
| Event::Refuse(s, _)
|
||||
| Event::Collapse(s, _) => self
|
||||
.diagram_selection
|
||||
.as_ref()
|
||||
.is_some_and(|selection| selection.matches(s, current)),
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_target(&self, diagram: Id, view: &projection::ProjectedView) -> Option<Target> {
|
||||
let placement = if self.page == Page::Behavior {
|
||||
self.behavior.diagram.placement
|
||||
} else {
|
||||
self.selected_node
|
||||
};
|
||||
if let Some(id) = placement
|
||||
&& view.nodes.iter().any(|node| {
|
||||
node.id == id && (node.element == self.selected || node.id == self.selected)
|
||||
})
|
||||
{
|
||||
return Some(Target::Placement(id));
|
||||
}
|
||||
if self.page == Page::Behavior {
|
||||
// Keep a row's exact occurrence while inspecting its relation.
|
||||
// Its owner placement is never a node-inspection or Hide target.
|
||||
if let Some(target @ Target::StateRow { relation, .. }) =
|
||||
self.diagram_selection.as_ref().and_then(|s| s.primary())
|
||||
&& *relation == self.selected
|
||||
&& visible(self.project(), diagram, view, target)
|
||||
{
|
||||
return Some(target.clone());
|
||||
}
|
||||
if let Some(node) = view.nodes.iter().find(|node| {
|
||||
crate::behavior::state_canvas::visible_row_target(
|
||||
self.project(),
|
||||
diagram,
|
||||
view,
|
||||
node.id,
|
||||
self.selected,
|
||||
)
|
||||
}) {
|
||||
return Some(Target::StateRow {
|
||||
placement: node.id,
|
||||
relation: self.selected,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(port) = view.ports.iter().find(|port| port.element == self.selected) {
|
||||
return Some(Target::Port {
|
||||
port: port.element,
|
||||
placement: port.owner,
|
||||
});
|
||||
}
|
||||
view.edges
|
||||
.iter()
|
||||
.any(|edge| edge.id == self.selected)
|
||||
.then_some(Target::Edge(self.selected))
|
||||
}
|
||||
|
||||
pub(crate) fn reconcile_multiselect(&mut self) {
|
||||
if self.topology_context().is_some() {
|
||||
self.reconcile_process_multiselect();
|
||||
return;
|
||||
}
|
||||
let Some(current) = self.multiselect_context() else {
|
||||
self.diagram_selection = None;
|
||||
return;
|
||||
};
|
||||
let Surface::Saved(diagram) = current.scope.surface else {
|
||||
return;
|
||||
};
|
||||
let view = projection::project_view_with_index(
|
||||
self.project(),
|
||||
diagram,
|
||||
self.document.view_index(),
|
||||
);
|
||||
let legacy = self.legacy_target(diagram, &view);
|
||||
let lost_primary = self
|
||||
.diagram_selection
|
||||
.as_ref()
|
||||
.filter(|s| s.scope() == current.scope)
|
||||
.and_then(|s| s.primary())
|
||||
.is_some_and(|target| !visible(self.project(), diagram, &view, target));
|
||||
let primary_placement = if self.page == Page::Behavior {
|
||||
self.behavior.diagram.placement
|
||||
} else {
|
||||
self.selected_node
|
||||
};
|
||||
let held_primary = self
|
||||
.diagram_selection
|
||||
.as_ref()
|
||||
.filter(|s| s.scope() == current.scope)
|
||||
.and_then(|s| s.primary())
|
||||
.is_some_and(|target| match target {
|
||||
Target::Placement(id) => primary_placement == Some(*id),
|
||||
Target::Port { port, .. } => self.selected == *port,
|
||||
Target::Edge(id) => self.selected == *id,
|
||||
Target::StateRow { relation, .. } => {
|
||||
self.selected == *relation && primary_placement.is_none()
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
let project = self.document.project();
|
||||
let selection = self
|
||||
.diagram_selection
|
||||
.get_or_insert_with(|| Selection::new(current.scope));
|
||||
selection.reconcile(current.scope, |target| {
|
||||
visible(project, diagram, &view, target)
|
||||
});
|
||||
// Navigation/property selection remains explicit. A removed exact target
|
||||
// is never rebound through its semantic identity to a different placement.
|
||||
if held_primary || lost_primary {
|
||||
if selection.primary() != legacy.as_ref() {
|
||||
self.inspect_multiselect_primary();
|
||||
}
|
||||
} else if selection.primary() != legacy.as_ref() {
|
||||
if let Some(target) = legacy {
|
||||
selection.replace(target, |target| visible(project, diagram, &view, target));
|
||||
} else {
|
||||
selection.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn inspect_multiselect_primary(&mut self) {
|
||||
if self.topology_context().is_some() {
|
||||
self.inspect_process_multiselect_primary();
|
||||
return;
|
||||
}
|
||||
let diagram = self
|
||||
.multiselect_context()
|
||||
.and_then(|c| match c.scope.surface {
|
||||
Surface::Saved(diagram) => Some(diagram),
|
||||
_ => None,
|
||||
});
|
||||
let primary = self
|
||||
.diagram_selection
|
||||
.as_ref()
|
||||
.and_then(|s| s.primary())
|
||||
.cloned();
|
||||
self.selected_node = None;
|
||||
if self.page == Page::Behavior {
|
||||
self.behavior.diagram.placement = None;
|
||||
}
|
||||
match primary {
|
||||
Some(Target::Placement(id)) => {
|
||||
if let Some(node) = diagram
|
||||
.and_then(|d| self.project().diagrams.get(&d))
|
||||
.and_then(|d| d.nodes.get(&id))
|
||||
{
|
||||
self.selected = node.element;
|
||||
if self.page == Page::Behavior {
|
||||
self.behavior.diagram.placement = Some(id);
|
||||
} else {
|
||||
self.selected_node = Some(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Target::Port { port, .. }) => self.selected = port,
|
||||
Some(Target::Edge(id)) => self.selected = id,
|
||||
Some(Target::StateRow { relation, .. }) => self.selected = relation,
|
||||
_ => self.selected = diagram.unwrap_or(self.project().id),
|
||||
}
|
||||
self.selected_bend = None;
|
||||
self.selected_attachment = None;
|
||||
self.refresh_draft();
|
||||
}
|
||||
|
||||
pub(crate) fn multiselect_event(&mut self, event: Event) {
|
||||
if !self.multiselect_envelope(&event) {
|
||||
return;
|
||||
}
|
||||
if self.topology_context().is_some() {
|
||||
self.process_multiselect_event(event);
|
||||
return;
|
||||
}
|
||||
if !diagram_removal::enabled(self)
|
||||
|| self.architecture.is_some()
|
||||
|| self.connection.is_some()
|
||||
|| (self.page == Page::Behavior
|
||||
&& self.behavior.diagram.tool != crate::behavior::state_edit::Tool::Select)
|
||||
{
|
||||
self.status =
|
||||
"Finish or cancel the active edit before changing the diagram selection.".into();
|
||||
return;
|
||||
}
|
||||
let current = self.multiselect_context().unwrap();
|
||||
let Surface::Saved(diagram) = current.scope.surface else {
|
||||
return;
|
||||
};
|
||||
let view = projection::project_view_with_index(
|
||||
self.project(),
|
||||
diagram,
|
||||
self.document.view_index(),
|
||||
);
|
||||
match event {
|
||||
Event::ProcessReorder(..) => {}
|
||||
Event::Collapse(_, target) => {
|
||||
if !visible(self.project(), diagram, &view, &target) {
|
||||
return;
|
||||
}
|
||||
let project = self.document.project();
|
||||
self.diagram_selection
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.replace(target, |target| visible(project, diagram, &view, target));
|
||||
self.inspect_multiselect_primary();
|
||||
}
|
||||
Event::Choose(_, target, choice) => {
|
||||
if !visible(self.project(), diagram, &view, &target) {
|
||||
return;
|
||||
}
|
||||
self.reconcile_multiselect();
|
||||
let project = self.document.project();
|
||||
let selection = self.diagram_selection.as_mut().unwrap();
|
||||
let valid = |target: &Target| visible(project, diagram, &view, target);
|
||||
match choice {
|
||||
Choice::Replace => {
|
||||
selection.replace(target, valid);
|
||||
}
|
||||
Choice::Add => {
|
||||
selection.add(target, valid);
|
||||
}
|
||||
Choice::Remove => {
|
||||
selection.remove(&target);
|
||||
}
|
||||
Choice::Toggle => {
|
||||
selection.toggle(target, valid);
|
||||
}
|
||||
Choice::Inspect => {
|
||||
selection.set_primary(&target);
|
||||
}
|
||||
}
|
||||
self.inspect_multiselect_primary();
|
||||
}
|
||||
Event::Clear(_) => {
|
||||
if let Some(selection) = &mut self.diagram_selection {
|
||||
selection.clear();
|
||||
}
|
||||
self.inspect_multiselect_primary();
|
||||
}
|
||||
Event::Refuse(_, reason) => self.status = reason,
|
||||
Event::Move(snapshot, delta) => {
|
||||
let Some(ids) = placements(&snapshot) else {
|
||||
self.status = "Move requires only placed elements. Remove ports, rows and connections from the selection.".into();
|
||||
return;
|
||||
};
|
||||
if !snapshot
|
||||
.targets()
|
||||
.iter()
|
||||
.all(|target| visible(self.project(), diagram, &view, target))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.project().diagrams[&diagram].projection == ProjectionKind::Allocation
|
||||
&& ids.iter().any(|id| {
|
||||
self.project().elements
|
||||
[&self.project().diagrams[&diagram].nodes[id].element]
|
||||
.kind()
|
||||
.is_work()
|
||||
})
|
||||
{
|
||||
self.status =
|
||||
"Use an Allocation drag to assign this selection, or arm Arrange next drag."
|
||||
.into();
|
||||
return;
|
||||
}
|
||||
if delta.x == 0. && delta.y == 0. {
|
||||
return;
|
||||
}
|
||||
match oa_core::diagram_edit::translate_placements(
|
||||
self.project(),
|
||||
diagram,
|
||||
&ids,
|
||||
delta,
|
||||
) {
|
||||
Ok(command) => {
|
||||
if self.execute(command) {
|
||||
self.inspect_multiselect_primary();
|
||||
self.status = format!(
|
||||
"Moved {} selected elements · Undo restores the group",
|
||||
ids.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(error) => self.status = error.to_string(),
|
||||
}
|
||||
}
|
||||
Event::Hide(snapshot) => {
|
||||
let Some(ids) = placements(&snapshot) else {
|
||||
self.status =
|
||||
"Hide requires only placed elements. Model objects remain unchanged."
|
||||
.into();
|
||||
return;
|
||||
};
|
||||
if !snapshot
|
||||
.targets()
|
||||
.iter()
|
||||
.all(|target| visible(self.project(), diagram, &view, target))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.execute(Command::Batch(
|
||||
ids.iter().copied().map(Command::Delete).collect(),
|
||||
)) {
|
||||
if let Some(selection) = &mut self.diagram_selection {
|
||||
selection.clear();
|
||||
}
|
||||
self.inspect_multiselect_primary();
|
||||
self.status = format!("Hid {} placements · Model objects retained", ids.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,798 @@
|
||||
//! Saved-view group operations through the real App message boundary.
|
||||
use super::multiselect::{Choice as GroupChoice, Event as GroupEvent};
|
||||
use super::*;
|
||||
use crate::diagram_usage::Target;
|
||||
|
||||
fn point(x: f32, y: f32) -> Position {
|
||||
Position { x, y }
|
||||
}
|
||||
|
||||
struct Fixture {
|
||||
app: App,
|
||||
diagram: Id,
|
||||
a: Id,
|
||||
b: Id,
|
||||
child: Id,
|
||||
edge: Id,
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
let mut p = Project::empty();
|
||||
let a = p
|
||||
.add_element(Kind::Function, Layer::Sa, "Send", None)
|
||||
.unwrap();
|
||||
let b = p
|
||||
.add_element(Kind::Function, Layer::Sa, "Receive", None)
|
||||
.unwrap();
|
||||
let child = p
|
||||
.add_element(Kind::Function, Layer::Sa, "Prepare", Some(a))
|
||||
.unwrap();
|
||||
let edge = p.relate(RelationKind::FunctionalExchange, "Signal", a, b);
|
||||
let diagram = p.ensure_diagram(Layer::Sa);
|
||||
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::FunctionalDataflow;
|
||||
let a = p.place(diagram, a, point(10., 20.));
|
||||
let b = p.place(diagram, b, point(500., 20.));
|
||||
let child = p.place(diagram, child, point(40., 100.));
|
||||
p.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(EdgeRoute {
|
||||
edge,
|
||||
source_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Bottom,
|
||||
offset: 0.3,
|
||||
}),
|
||||
target_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Top,
|
||||
offset: 0.7,
|
||||
}),
|
||||
waypoints: vec![point(370., 150.)],
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.4,
|
||||
offset: point(5., -9.),
|
||||
}),
|
||||
});
|
||||
let other = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "Operational work", None)
|
||||
.unwrap();
|
||||
let other_diagram = p.ensure_diagram(Layer::Oa);
|
||||
p.place(other_diagram, other, point(-50., -100.));
|
||||
let mut app = App::with_project(p);
|
||||
app.page = Page::Diagram;
|
||||
app.layer = Layer::Sa;
|
||||
app.active_diagram = Some(diagram);
|
||||
app.selected = diagram;
|
||||
app.selected_node = None;
|
||||
app.refresh_draft();
|
||||
app.reconcile_multiselect();
|
||||
Fixture {
|
||||
app,
|
||||
diagram,
|
||||
a,
|
||||
b,
|
||||
child,
|
||||
edge,
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch(app: &mut App, event: GroupEvent) {
|
||||
let _ = app.update(Message::DiagramSelection(event));
|
||||
}
|
||||
fn choose(app: &mut App, target: Target, choice: GroupChoice) {
|
||||
let context = app.multiselect_context().unwrap();
|
||||
dispatch(app, GroupEvent::Choose(context, target, choice));
|
||||
}
|
||||
fn select_pair(f: &mut Fixture) {
|
||||
choose(&mut f.app, Target::Placement(f.a), GroupChoice::Replace);
|
||||
choose(&mut f.app, Target::Placement(f.b), GroupChoice::Toggle);
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(f.a), Target::Placement(f.b)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_singleton_move_or_delete_cannot_partially_edit_a_new_group() {
|
||||
for model in [false, true] {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let before = f.app.document.snapshot();
|
||||
let selected = f.app.multiselect_snapshot().unwrap();
|
||||
let object = f.app.project().diagrams[&f.diagram].nodes[&f.b].element;
|
||||
for message in [
|
||||
Message::MoveNode(f.b, point(700., 600.)),
|
||||
Message::DiagramRemove(super::diagram_removal::Intent {
|
||||
context: f.app.route_context().unwrap(),
|
||||
object,
|
||||
placement: Some(f.b),
|
||||
model,
|
||||
}),
|
||||
Message::Delete,
|
||||
] {
|
||||
let _ = f.app.update(message);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
selected.targets()
|
||||
);
|
||||
assert!(!f.app.delete_pending);
|
||||
assert!(!f.app.document.can_undo());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_hide_action_applies_to_the_complete_visible_group() {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let before = f.app.document.snapshot();
|
||||
let mut expected = f.app.project().clone();
|
||||
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
|
||||
view.nodes.remove(&f.a);
|
||||
view.nodes.remove(&f.b);
|
||||
let _ = f.app.update(Message::HideSelected);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_source_matches_model(&f.app);
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
}
|
||||
fn assert_source_matches_model(app: &App) {
|
||||
let compiled = oa_core::source_project::compile_bundle(app.document.bundle(), LIMITS).unwrap();
|
||||
assert_eq!(&compiled.decoded.project, app.project());
|
||||
assert_eq!(&compiled.bundle, app.document.bundle());
|
||||
}
|
||||
|
||||
fn text_apply_group_fixture(state: bool) -> (App, Id, Id, Id) {
|
||||
let ordinary = fixture();
|
||||
if !state {
|
||||
return (ordinary.app, ordinary.diagram, ordinary.a, ordinary.b);
|
||||
}
|
||||
// Keep the ordinary diagram, routes and opposite-layer view in the same
|
||||
// Project so the complete-model oracle also protects non-active surfaces.
|
||||
let mut project = ordinary.app.project().clone();
|
||||
let ordinary_view = project.diagrams[&ordinary.diagram].clone();
|
||||
let system = project
|
||||
.add_element(Kind::System, Layer::Sa, "System", None)
|
||||
.unwrap();
|
||||
let machine = project
|
||||
.add_element(Kind::StateMachine, Layer::Sa, "Modes", Some(system))
|
||||
.unwrap();
|
||||
let region = project
|
||||
.add_element(Kind::Region, Layer::Sa, "Region", Some(machine))
|
||||
.unwrap();
|
||||
let first = project
|
||||
.add_element(Kind::State, Layer::Sa, "Before text", Some(region))
|
||||
.unwrap();
|
||||
let second = project
|
||||
.add_element(Kind::State, Layer::Sa, "Other state", Some(region))
|
||||
.unwrap();
|
||||
let diagram = project.ensure_diagram(Layer::Sa);
|
||||
assert_ne!(diagram, ordinary.diagram);
|
||||
project.diagrams.get_mut(&diagram).unwrap().projection =
|
||||
ProjectionKind::StateMachine { machine };
|
||||
let a = project.place(diagram, first, point(20., 30.));
|
||||
let b = project.place(diagram, second, point(420., 30.));
|
||||
assert_eq!(project.diagrams[&ordinary.diagram], ordinary_view);
|
||||
let mut app = App::with_project(project);
|
||||
app.page = Page::Behavior;
|
||||
app.layer = Layer::Sa;
|
||||
app.active_diagram = Some(ordinary.diagram);
|
||||
app.behavior.active_owner = Some(machine);
|
||||
app.behavior.diagram = crate::behavior::state_view::State {
|
||||
diagram: Some(diagram),
|
||||
..Default::default()
|
||||
};
|
||||
app.selected = diagram;
|
||||
app.selected_node = None;
|
||||
app.refresh_draft();
|
||||
app.reconcile_multiselect();
|
||||
assert_eq!(app.state_context().unwrap().diagram, diagram);
|
||||
(app, diagram, a, b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_text_apply_rejects_captured_ordinary_and_state_group_actions() {
|
||||
for state in [false, true] {
|
||||
let (mut app, diagram, a, b) = text_apply_group_fixture(state);
|
||||
choose(&mut app, Target::Placement(a), GroupChoice::Replace);
|
||||
choose(&mut app, Target::Placement(b), GroupChoice::Add);
|
||||
let stale = app.multiselect_snapshot().unwrap();
|
||||
let before = app.document.snapshot();
|
||||
assert!(!app.document.can_undo());
|
||||
let element = app.project().diagrams[&diagram].nodes[&a].element;
|
||||
let location = app.document.compiled().index.declarations[&element].clone();
|
||||
let old_name = if state { "Before text" } else { "Send" };
|
||||
assert_eq!(app.project().elements[&element].name, old_name);
|
||||
let quoted_name = format!("\"{old_name}\"");
|
||||
let original = &before.bundle.files[&location.path];
|
||||
assert_eq!(original.matches(quoted_name.as_str()).count(), 1);
|
||||
let edited = original.replace(quoted_name.as_str(), "\"Changed through Text\"");
|
||||
let mut expected_model = before.decoded.project.clone();
|
||||
expected_model.elements.get_mut(&element).unwrap().name = "Changed through Text".into();
|
||||
let mut expected_bundle = before.bundle.clone();
|
||||
expected_bundle
|
||||
.files
|
||||
.insert(location.path.clone(), edited.clone());
|
||||
|
||||
let _ = app.update(Message::Page(Page::Text));
|
||||
let _ = app.update(Message::SourceFile(location.path));
|
||||
let _ = app.update(Message::SourceEdit(text_editor::Action::SelectAll));
|
||||
let _ = app.update(Message::SourceEdit(text_editor::Action::Edit(
|
||||
text_editor::Edit::Paste(Arc::new(edited.clone())),
|
||||
)));
|
||||
assert!(app.source_dirty());
|
||||
assert_eq!(app.source_editor.text(), edited);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
let _ = app.update(Message::ApplySource);
|
||||
assert!(!app.source_dirty(), "{}", app.status);
|
||||
assert_eq!(app.project(), &expected_model);
|
||||
assert_eq!(app.document.bundle(), &expected_bundle);
|
||||
assert!(app.document.can_undo());
|
||||
assert!(!app.document.can_redo());
|
||||
assert_source_matches_model(&app);
|
||||
|
||||
let _ = app.update(Message::Page(if state {
|
||||
Page::Behavior
|
||||
} else {
|
||||
Page::Diagram
|
||||
}));
|
||||
choose(&mut app, Target::Placement(a), GroupChoice::Replace);
|
||||
choose(&mut app, Target::Placement(b), GroupChoice::Add);
|
||||
let current = app.multiselect_snapshot().unwrap();
|
||||
assert_eq!(
|
||||
current.targets(),
|
||||
&[Target::Placement(a), Target::Placement(b)]
|
||||
);
|
||||
assert_eq!(current.primary(), Some(&Target::Placement(b)));
|
||||
assert_ne!(current.context(), stale.context());
|
||||
assert!(app.multiselect_envelope(&GroupEvent::Hide(current.clone())));
|
||||
app.status = "Feedback after completed Text Apply".into();
|
||||
app.allocation_drag.arrange_next = true;
|
||||
let revision = app.document.revision();
|
||||
let epochs = (
|
||||
app.canvas_epoch,
|
||||
app.camera_epoch,
|
||||
app.allocation_drag.epoch,
|
||||
);
|
||||
let legacy = (
|
||||
app.selected,
|
||||
app.selected_node,
|
||||
app.behavior.diagram.placement,
|
||||
);
|
||||
let camera = (app.zoom, app.pan, app.fit_to_view, app.canvas_size);
|
||||
let state_camera = (
|
||||
app.behavior.diagram.zoom,
|
||||
app.behavior.diagram.pan,
|
||||
app.behavior.diagram.fit,
|
||||
app.behavior.diagram.viewport,
|
||||
);
|
||||
let draft = app
|
||||
.draft
|
||||
.as_ref()
|
||||
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap());
|
||||
for event in [
|
||||
GroupEvent::Move(stale.clone(), point(900., 800.)),
|
||||
GroupEvent::Hide(stale.clone()),
|
||||
GroupEvent::Collapse(stale.clone(), Target::Placement(a)),
|
||||
GroupEvent::Refuse(stale.clone(), "Obsolete refusal".into()),
|
||||
] {
|
||||
dispatch(&mut app, event);
|
||||
assert_eq!(app.project(), &expected_model);
|
||||
assert_eq!(app.document.bundle(), &expected_bundle);
|
||||
assert_eq!(app.document.revision(), revision);
|
||||
assert_eq!(app.multiselect_snapshot(), Some(current.clone()));
|
||||
assert_eq!(
|
||||
(
|
||||
app.selected,
|
||||
app.selected_node,
|
||||
app.behavior.diagram.placement
|
||||
),
|
||||
legacy
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
app.canvas_epoch,
|
||||
app.camera_epoch,
|
||||
app.allocation_drag.epoch
|
||||
),
|
||||
epochs
|
||||
);
|
||||
assert_eq!(
|
||||
(app.zoom, app.pan, app.fit_to_view, app.canvas_size),
|
||||
camera
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
app.behavior.diagram.zoom,
|
||||
app.behavior.diagram.pan,
|
||||
app.behavior.diagram.fit,
|
||||
app.behavior.diagram.viewport
|
||||
),
|
||||
state_camera
|
||||
);
|
||||
assert_eq!(app.status, "Feedback after completed Text Apply");
|
||||
assert!(app.allocation_drag.arrange_next);
|
||||
assert!(!app.source_dirty());
|
||||
assert_eq!(
|
||||
app.draft
|
||||
.as_ref()
|
||||
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap()),
|
||||
draft
|
||||
);
|
||||
assert!(app.document.can_undo());
|
||||
assert!(!app.document.can_redo());
|
||||
}
|
||||
// Actual Text Apply is the sole history entry; no stale group action
|
||||
// can create a hidden second edit or damage either round-trip snapshot.
|
||||
let _ = app.update(Message::Undo);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
assert!(app.document.can_redo());
|
||||
let _ = app.update(Message::Redo);
|
||||
assert_eq!(app.project(), &expected_model);
|
||||
assert_eq!(app.document.bundle(), &expected_bundle);
|
||||
assert!(app.document.can_undo());
|
||||
assert!(!app.document.can_redo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggled_group_moves_model_and_source_once_and_keeps_primary_through_history() {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let before = f.app.document.snapshot();
|
||||
let snapshot = f.app.multiselect_snapshot().unwrap();
|
||||
assert_eq!(snapshot.primary(), Some(&Target::Placement(f.b)));
|
||||
let mut expected = f.app.project().clone();
|
||||
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
|
||||
view.nodes.get_mut(&f.a).unwrap().position = point(50., 80.);
|
||||
view.nodes.get_mut(&f.b).unwrap().position = point(540., 80.);
|
||||
view.nodes.get_mut(&f.child).unwrap().position = point(80., 160.);
|
||||
view.routes[0].waypoints = vec![point(410., 210.)];
|
||||
dispatch(
|
||||
&mut f.app,
|
||||
GroupEvent::Move(snapshot.clone(), point(40., 60.)),
|
||||
);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_source_matches_model(&f.app);
|
||||
assert_eq!(f.app.selected_node, Some(f.b));
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
snapshot.targets()
|
||||
);
|
||||
let after = f.app.document.snapshot();
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
let _ = f.app.update(Message::Redo);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_eq!(f.app.document.bundle(), &after.bundle);
|
||||
assert!(!f.app.document.can_redo());
|
||||
assert_eq!(f.app.selected_node, Some(f.b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ancestor_and_child_selection_moves_child_exactly_once() {
|
||||
let mut f = fixture();
|
||||
choose(&mut f.app, Target::Placement(f.a), GroupChoice::Replace);
|
||||
choose(&mut f.app, Target::Placement(f.child), GroupChoice::Toggle);
|
||||
let snapshot = f.app.multiselect_snapshot().unwrap();
|
||||
assert_eq!(snapshot.targets().len(), 2);
|
||||
let mut expected = f.app.project().clone();
|
||||
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
|
||||
view.nodes.get_mut(&f.a).unwrap().position = point(0., 45.);
|
||||
view.nodes.get_mut(&f.child).unwrap().position = point(30., 125.);
|
||||
dispatch(&mut f.app, GroupEvent::Move(snapshot, point(-10., 25.)));
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_eq!(f.app.selected_node, Some(f.child));
|
||||
assert_source_matches_model(&f.app);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_edge_or_port_selection_refuses_the_entire_move() {
|
||||
for include_port in [false, true] {
|
||||
let mut f = fixture();
|
||||
choose(&mut f.app, Target::Placement(f.a), GroupChoice::Replace);
|
||||
let extra = if include_port {
|
||||
let view = projection::project_view(f.app.project(), f.diagram);
|
||||
let port = view
|
||||
.ports
|
||||
.iter()
|
||||
.find(|p| p.owner == f.a)
|
||||
.expect("functional exchange exposes its typed owner port");
|
||||
Target::Port {
|
||||
port: port.element,
|
||||
placement: port.owner,
|
||||
}
|
||||
} else {
|
||||
Target::Edge(f.edge)
|
||||
};
|
||||
choose(&mut f.app, extra.clone(), GroupChoice::Toggle);
|
||||
let selection = f.app.multiselect_snapshot().unwrap();
|
||||
assert_eq!(selection.targets(), &[Target::Placement(f.a), extra]);
|
||||
let before = f.app.document.snapshot();
|
||||
let revision = f.app.document.revision();
|
||||
dispatch(
|
||||
&mut f.app,
|
||||
GroupEvent::Move(selection.clone(), point(40., 60.)),
|
||||
);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert_eq!(f.app.document.revision(), revision);
|
||||
assert!(!f.app.document.can_undo());
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
selection.targets()
|
||||
);
|
||||
assert!(f.app.status.contains("Move requires only placed elements"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_operation_envelopes_have_no_selection_history_status_or_allocation_side_effects() {
|
||||
// Isolate each lifetime component, including the same visible set recreated
|
||||
// by a remove/re-add cycle. Accepted setup changes are outside the assertion.
|
||||
for stale_by in ["epoch", "revision", "document", "selection generation"] {
|
||||
for action in ["move", "hide", "refuse", "collapse"] {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let stale = f.app.multiselect_snapshot().unwrap();
|
||||
match stale_by {
|
||||
"epoch" => f.app.canvas_epoch += 1,
|
||||
"revision" => {
|
||||
let semantic = f.app.project().diagrams[&f.diagram].nodes[&f.a].element;
|
||||
// Advance only the document revision, retaining this canvas
|
||||
// and selection epoch to independently test revision checking.
|
||||
f.app
|
||||
.document
|
||||
.execute(Command::Describe(semantic, "New revision".into()))
|
||||
.unwrap();
|
||||
}
|
||||
"document" => f.app.canvas_document = Id::new_v4(),
|
||||
_ => {
|
||||
choose(&mut f.app, Target::Placement(f.b), GroupChoice::Toggle);
|
||||
choose(&mut f.app, Target::Placement(f.b), GroupChoice::Toggle);
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
stale.targets()
|
||||
);
|
||||
}
|
||||
}
|
||||
f.app.status = "Current feedback must survive".into();
|
||||
f.app.allocation_drag.arrange_next = true;
|
||||
let before = f.app.document.snapshot();
|
||||
let selection = f.app.multiselect_snapshot();
|
||||
let legacy = (f.app.selected, f.app.selected_node);
|
||||
let revision = f.app.document.revision();
|
||||
let epochs = (
|
||||
f.app.canvas_epoch,
|
||||
f.app.camera_epoch,
|
||||
f.app.allocation_drag.epoch,
|
||||
);
|
||||
let history = (f.app.document.can_undo(), f.app.document.can_redo());
|
||||
let draft = f
|
||||
.app
|
||||
.draft
|
||||
.as_ref()
|
||||
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap());
|
||||
let event = match action {
|
||||
"move" => GroupEvent::Move(stale, point(99., 100.)),
|
||||
"hide" => GroupEvent::Hide(stale),
|
||||
"collapse" => GroupEvent::Collapse(stale, Target::Placement(f.a)),
|
||||
_ => GroupEvent::Refuse(stale, "Obsolete refusal".into()),
|
||||
};
|
||||
dispatch(&mut f.app, event);
|
||||
assert_eq!(
|
||||
f.app.project(),
|
||||
&before.decoded.project,
|
||||
"{stale_by}/{action}"
|
||||
);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert_eq!(f.app.document.revision(), revision);
|
||||
assert_eq!(f.app.multiselect_snapshot(), selection);
|
||||
assert_eq!((f.app.selected, f.app.selected_node), legacy);
|
||||
assert_eq!(
|
||||
(
|
||||
f.app.canvas_epoch,
|
||||
f.app.camera_epoch,
|
||||
f.app.allocation_drag.epoch
|
||||
),
|
||||
epochs
|
||||
);
|
||||
assert_eq!(
|
||||
(f.app.document.can_undo(), f.app.document.can_redo()),
|
||||
history
|
||||
);
|
||||
assert_eq!(f.app.status, "Current feedback must survive");
|
||||
assert!(f.app.allocation_drag.arrange_next);
|
||||
assert_eq!(
|
||||
f.app
|
||||
.draft
|
||||
.as_ref()
|
||||
.map(|d| serde_json::to_value(d.recovery_snapshot()).unwrap()),
|
||||
draft
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_valid_and_invalid_property_drafts_refuse_group_edits_without_applying_them() {
|
||||
for (path, value) in [("/name", "Unapplied name"), ("/id", "-")] {
|
||||
for hide in [false, true] {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let _ = f.app.update(Message::Field(path.into(), value.into()));
|
||||
assert!(f.app.draft_dirty());
|
||||
let snapshot = f.app.multiselect_snapshot().unwrap();
|
||||
let before = f.app.document.snapshot();
|
||||
let draft =
|
||||
serde_json::to_value(f.app.draft.as_ref().unwrap().recovery_snapshot()).unwrap();
|
||||
let event = if hide {
|
||||
GroupEvent::Hide(snapshot.clone())
|
||||
} else {
|
||||
GroupEvent::Move(snapshot.clone(), point(20., 30.))
|
||||
};
|
||||
dispatch(&mut f.app, event);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
snapshot.targets()
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(f.app.draft.as_ref().unwrap().recovery_snapshot()).unwrap(),
|
||||
draft
|
||||
);
|
||||
assert!(f.app.status.contains("Finish or cancel"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hiding_a_group_removes_only_exact_placements_and_roundtrips_in_one_history_step() {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let snapshot = f.app.multiselect_snapshot().unwrap();
|
||||
let before = f.app.document.snapshot();
|
||||
let mut expected = f.app.project().clone();
|
||||
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
|
||||
view.nodes.remove(&f.a);
|
||||
view.nodes.remove(&f.b);
|
||||
dispatch(&mut f.app, GroupEvent::Hide(snapshot));
|
||||
assert_eq!(
|
||||
f.app.project(),
|
||||
&expected,
|
||||
"engineering objects, descendant placement, authored route and opposite-layer view survive"
|
||||
);
|
||||
assert!(f.app.multiselect_snapshot().unwrap().targets().is_empty());
|
||||
assert_source_matches_model(&f.app);
|
||||
let after = f.app.document.snapshot();
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
let _ = f.app.update(Message::Redo);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_eq!(f.app.document.bundle(), &after.bundle);
|
||||
assert!(!f.app.document.can_redo());
|
||||
}
|
||||
fn assert_surviving_primary(f: &Fixture) {
|
||||
let selection = f.app.multiselect_snapshot().unwrap();
|
||||
assert_eq!(selection.targets(), &[Target::Placement(f.a)]);
|
||||
assert_eq!(selection.primary(), Some(&Target::Placement(f.a)));
|
||||
assert_eq!(f.app.selected_node, Some(f.a));
|
||||
assert_eq!(
|
||||
f.app.selected,
|
||||
f.app.project().diagrams[&f.diagram].nodes[&f.a].element
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_primary_placement_from_model_preserves_exact_survivor_after_undo() {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let before = f.app.document.snapshot();
|
||||
let _ = f.app.update(Message::Command(Command::Delete(f.b)));
|
||||
assert!(
|
||||
!f.app.project().diagrams[&f.diagram]
|
||||
.nodes
|
||||
.contains_key(&f.b)
|
||||
);
|
||||
assert_surviving_primary(&f);
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert_surviving_primary(&f);
|
||||
let _ = f.app.update(Message::Redo);
|
||||
assert_surviving_primary(&f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_primary_model_object_then_undo_does_not_restore_removed_selection_membership() {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let before = f.app.document.snapshot();
|
||||
let semantic = f.app.project().diagrams[&f.diagram].nodes[&f.b].element;
|
||||
let _ = f.app.update(Message::Command(Command::Delete(semantic)));
|
||||
assert!(!f.app.project().elements.contains_key(&semantic));
|
||||
assert_surviving_primary(&f);
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert_surviving_primary(&f);
|
||||
let _ = f.app.update(Message::Redo);
|
||||
assert_surviving_primary(&f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_primary_occurrence_with_same_semantic_placement_does_not_retarget_selection() {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let mut candidate = f.app.project().clone();
|
||||
let view = candidate.diagrams.get_mut(&f.diagram).unwrap();
|
||||
let mut replacement = view.nodes.remove(&f.b).unwrap();
|
||||
let replacement_id = Id::new_v4();
|
||||
replacement.id = replacement_id;
|
||||
replacement.alias = "replacement_receive".into();
|
||||
replacement.position = point(800., 300.);
|
||||
view.nodes.insert(replacement_id, replacement);
|
||||
// Replace preserves the semantic inspector identity. Its normal sync used
|
||||
// to rediscover the new occurrence through that identity and steal the set.
|
||||
let _ = f
|
||||
.app
|
||||
.update(Message::Command(Command::Replace(candidate.clone())));
|
||||
assert_eq!(f.app.project(), &candidate);
|
||||
assert_surviving_primary(&f);
|
||||
assert!(
|
||||
!f.app
|
||||
.multiselect_snapshot()
|
||||
.unwrap()
|
||||
.targets()
|
||||
.contains(&Target::Placement(replacement_id))
|
||||
);
|
||||
assert_source_matches_model(&f.app);
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert!(
|
||||
f.app.project().diagrams[&f.diagram]
|
||||
.nodes
|
||||
.contains_key(&f.b)
|
||||
);
|
||||
assert_surviving_primary(&f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_surface_navigation_and_return_never_resurrect_the_group() {
|
||||
for destination in [Page::Catalog, Page::Behavior] {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let before = f.app.document.snapshot();
|
||||
let stale = f.app.multiselect_snapshot().unwrap();
|
||||
let _ = f.app.update(Message::Page(destination));
|
||||
assert!(f.app.multiselect_snapshot().is_none());
|
||||
let _ = f.app.update(Message::Page(Page::Diagram));
|
||||
let live = f.app.multiselect_snapshot().unwrap();
|
||||
assert!(
|
||||
live.targets().len() <= 1,
|
||||
"navigation may inspect one exact member but must not restore the group"
|
||||
);
|
||||
dispatch(&mut f.app, GroupEvent::Move(stale, point(400., 500.)));
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
}
|
||||
}
|
||||
|
||||
fn open_placement_menu(f: &mut Fixture, placement: Id) {
|
||||
let semantic = f.app.project().diagrams[&f.diagram].nodes[&placement].element;
|
||||
let mut request = crate::model_menu::Request::object(semantic, iced::Point::new(100., 100.));
|
||||
request.placement = Some(placement);
|
||||
request.canvas = f.app.route_context();
|
||||
let _ = f
|
||||
.app
|
||||
.update(Message::Menu(crate::model_menu::Event::Open(request)));
|
||||
assert!(f.app.model_menu.is_some());
|
||||
}
|
||||
|
||||
fn menu_action(app: &App, caption: &str) -> Message {
|
||||
crate::model_menu::popup(app)
|
||||
.unwrap()
|
||||
.entries
|
||||
.into_iter()
|
||||
.find_map(|entry| match entry {
|
||||
crate::context_menu::Entry::Action { label, message, .. } if label == caption => {
|
||||
message
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("enabled menu action {caption:?} must exist"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_dismissal_preserves_group_and_add_keeps_pre_menu_members() {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let before = f.app.document.snapshot();
|
||||
let selected = f.app.multiselect_snapshot().unwrap();
|
||||
let child = f.child;
|
||||
open_placement_menu(&mut f, child);
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
selected.targets()
|
||||
);
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().primary(),
|
||||
selected.primary()
|
||||
);
|
||||
let _ = f.app.update(Message::Menu(crate::model_menu::Event::Close));
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
selected.targets()
|
||||
);
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().primary(),
|
||||
selected.primary()
|
||||
);
|
||||
open_placement_menu(&mut f, child);
|
||||
let add = menu_action(&f.app, "Add to selection");
|
||||
let _ = f.app.update(add);
|
||||
let selected = f.app.multiselect_snapshot().unwrap();
|
||||
assert_eq!(
|
||||
selected.targets(),
|
||||
&[
|
||||
Target::Placement(f.a),
|
||||
Target::Placement(f.b),
|
||||
Target::Placement(child)
|
||||
]
|
||||
);
|
||||
assert_eq!(selected.primary(), Some(&Target::Placement(child)));
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_member_context_menu_exposes_and_executes_group_hide_not_singleton_deletion() {
|
||||
let mut f = fixture();
|
||||
select_pair(&mut f);
|
||||
let before = f.app.document.snapshot();
|
||||
let member = f.a;
|
||||
open_placement_menu(&mut f, member);
|
||||
let popup = crate::model_menu::popup(&f.app).unwrap();
|
||||
for entry in &popup.entries {
|
||||
if let crate::context_menu::Entry::Action {
|
||||
message: Some(Message::Menu(crate::model_menu::Event::Invoke(_, action))),
|
||||
..
|
||||
} = entry
|
||||
{
|
||||
assert!(
|
||||
!matches!(
|
||||
action.as_ref(),
|
||||
Message::HideSelected | Message::Delete | Message::DiagramRemove(_)
|
||||
),
|
||||
"a selected-member group menu must not expose singleton removal"
|
||||
);
|
||||
}
|
||||
}
|
||||
let hide = menu_action(&f.app, "Hide selected placements");
|
||||
let _ = f.app.update(hide);
|
||||
let mut expected = before.decoded.project.clone();
|
||||
let view = expected.diagrams.get_mut(&f.diagram).unwrap();
|
||||
view.nodes.remove(&f.a);
|
||||
view.nodes.remove(&f.b);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert!(!f.app.delete_pending);
|
||||
assert!(f.app.model_menu.is_none());
|
||||
assert_source_matches_model(&f.app);
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
}
|
||||
@@ -65,6 +65,7 @@ impl App {
|
||||
owner: context.owner,
|
||||
revision: context.revision,
|
||||
epoch: lifetime,
|
||||
scenario_view: None,
|
||||
};
|
||||
if self.behavior.has_pending()
|
||||
|| self.draft_dirty()
|
||||
@@ -128,6 +129,12 @@ impl App {
|
||||
let resolved = oa_core::topology_context::TopologyIndex::new(self.project())
|
||||
.resolve(context.owner, &endpoint);
|
||||
if let Ok(resolved) = resolved {
|
||||
// The definition may be opened from a nonprimary context
|
||||
// target. Remember that exact invocation, not whichever
|
||||
// qualified occurrence happened to be primary beforehand.
|
||||
self.behavior
|
||||
.topology
|
||||
.select_context(resolved.address.clone());
|
||||
self.behavior.topology.remember(
|
||||
context.owner,
|
||||
endpoint
|
||||
@@ -137,27 +144,18 @@ impl App {
|
||||
.unwrap_or(endpoint.occurrence),
|
||||
resolved.defining_sequence,
|
||||
);
|
||||
self.behavior.topology.clear_context();
|
||||
self.behavior.active_owner = Some(resolved.defining_sequence);
|
||||
self.select(endpoint.occurrence);
|
||||
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
CanvasEvent::SelectQualified(_, endpoint) => {
|
||||
if !self.behavior.has_pending()
|
||||
&& !self.draft_dirty()
|
||||
&& !self.source_dirty()
|
||||
&& let Ok(resolved) =
|
||||
oa_core::topology_context::TopologyIndex::new(self.project())
|
||||
.resolve(context.owner, &endpoint)
|
||||
{
|
||||
let reference = endpoint
|
||||
.references
|
||||
.first()
|
||||
.copied()
|
||||
.unwrap_or(endpoint.occurrence);
|
||||
self.select(reference);
|
||||
self.behavior.topology.select_context(resolved.address);
|
||||
}
|
||||
self.multiselect_event(multiselect::Event::Choose(
|
||||
multiselect::process_context(context),
|
||||
crate::diagram_usage::Target::ProcessOccurrence(endpoint),
|
||||
multiselect::Choice::Replace,
|
||||
));
|
||||
}
|
||||
CanvasEvent::Select(_, id) => {
|
||||
if !self.behavior.has_pending()
|
||||
@@ -198,6 +196,9 @@ impl App {
|
||||
if let Some(target) =
|
||||
topology::referenced(self.project(), context.owner, occurrence)
|
||||
{
|
||||
// Opening a local card returns to that local use, even if
|
||||
// a qualified tile was the previous inspection target.
|
||||
self.behavior.topology.clear_context();
|
||||
if self
|
||||
.project()
|
||||
.elements
|
||||
@@ -222,8 +223,20 @@ impl App {
|
||||
self.behavior.topology = state;
|
||||
if let Some((owner, occurrence)) = back {
|
||||
self.behavior.active_owner = Some(owner);
|
||||
self.select(occurrence);
|
||||
// Back restores a use, whereas ordinary select navigates
|
||||
// to a defining object. The validated return address owns
|
||||
// the exact subject; never infer it from the outer card ID.
|
||||
self.selected = self
|
||||
.behavior
|
||||
.topology
|
||||
.selection_address()
|
||||
.filter(|address| address.owner == owner)
|
||||
.map_or(occurrence, |address| address.endpoint.occurrence);
|
||||
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
|
||||
// Synchronize the exact primary and inspector before the
|
||||
// returned caller is drawn or accepts property edits.
|
||||
self.reconcile_process_multiselect();
|
||||
self.inspect_process_multiselect_primary();
|
||||
}
|
||||
}
|
||||
mutation => {
|
||||
@@ -293,8 +306,9 @@ impl App {
|
||||
occurrence, before, ..
|
||||
} => {
|
||||
match topology::reorder(self.project(), context.owner, occurrence, before) {
|
||||
Ok(command) => {
|
||||
if self.execute(command) {
|
||||
Ok(topology::group_reorder::Plan::Noop) => {}
|
||||
Ok(topology::group_reorder::Plan::Change(command)) => {
|
||||
if self.execute(*command) {
|
||||
self.selected = occurrence;
|
||||
self.refresh_draft();
|
||||
return self.reveal_process_selection();
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Exact Process presentation selection and one atomic order transaction.
|
||||
use super::*;
|
||||
use crate::behavior::topology::group_reorder::{Plan, Prepared};
|
||||
use crate::diagram_selection::Selection;
|
||||
use crate::diagram_usage::{Surface, Target};
|
||||
use multiselect::{Choice, Event};
|
||||
|
||||
fn subject(target: &Target) -> Option<Id> {
|
||||
match target {
|
||||
Target::ProcessOccurrence(endpoint) => Some(endpoint.occurrence),
|
||||
Target::ProcessLink(id) | Target::ProcessPreviewLink { relation: id, .. } => Some(*id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(crate) fn process_preview_primary(&self) -> Option<&Target> {
|
||||
let context = self.topology_context()?;
|
||||
let selection = self.diagram_selection.as_ref()?;
|
||||
if selection.scope() != multiselect::process_context(context).scope {
|
||||
return None;
|
||||
}
|
||||
selection
|
||||
.primary()
|
||||
.filter(|target| subject(target) == Some(self.selected))
|
||||
.filter(|target| match target {
|
||||
Target::ProcessOccurrence(endpoint) => !endpoint.references.is_empty(),
|
||||
Target::ProcessPreviewLink { .. } => true,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn reconcile_process_multiselect(&mut self) {
|
||||
let Some(context) = self.topology_context() else {
|
||||
return;
|
||||
};
|
||||
let current = multiselect::process_context(context);
|
||||
let visible = self
|
||||
.behavior
|
||||
.topology
|
||||
.selection_targets(self.project(), context.owner);
|
||||
let old = self
|
||||
.diagram_selection
|
||||
.as_ref()
|
||||
.filter(|s| s.scope() == current.scope)
|
||||
.and_then(Selection::primary)
|
||||
.cloned();
|
||||
let address = self.behavior.topology.selection_address();
|
||||
let focused = self
|
||||
.diagram_focus(Surface::Process(context.owner))
|
||||
.map(|usage| usage.target.clone());
|
||||
let legacy = focused
|
||||
.clone()
|
||||
.or_else(|| {
|
||||
address
|
||||
.as_ref()
|
||||
.filter(|a| a.owner == context.owner && a.endpoint.occurrence == self.selected)
|
||||
.map(|a| Target::ProcessOccurrence(a.endpoint.clone()))
|
||||
})
|
||||
.or_else(|| {
|
||||
visible
|
||||
.iter()
|
||||
.find(|target| match target {
|
||||
Target::ProcessOccurrence(endpoint) => {
|
||||
endpoint.references.is_empty() && endpoint.occurrence == self.selected
|
||||
}
|
||||
Target::ProcessLink(id) => *id == self.selected,
|
||||
_ => false,
|
||||
})
|
||||
.cloned()
|
||||
})
|
||||
.filter(|target| visible.contains(target));
|
||||
let held = old.as_ref().is_some_and(|target| {
|
||||
subject(target) == Some(self.selected)
|
||||
&& focused.as_ref().is_none_or(|focused| focused == target)
|
||||
&& match target {
|
||||
Target::ProcessOccurrence(endpoint) if !endpoint.references.is_empty() => {
|
||||
address
|
||||
.as_ref()
|
||||
.is_some_and(|a| a.owner == context.owner && a.endpoint == *endpoint)
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
});
|
||||
let lost = old.as_ref().is_some_and(|target| !visible.contains(target));
|
||||
let selection = self
|
||||
.diagram_selection
|
||||
.get_or_insert_with(|| Selection::new(current.scope));
|
||||
selection.reconcile(current.scope, |target| visible.contains(target));
|
||||
if held || lost {
|
||||
if selection.primary() != old.as_ref() {
|
||||
self.inspect_process_multiselect_primary();
|
||||
}
|
||||
} else if selection.primary() != legacy.as_ref() {
|
||||
if let Some(target) = legacy {
|
||||
selection.replace(target, |t| visible.contains(t));
|
||||
} else {
|
||||
selection.clear();
|
||||
}
|
||||
}
|
||||
if self.process_preview_primary().is_some() {
|
||||
self.draft = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn inspect_process_multiselect_primary(&mut self) {
|
||||
let Some(context) = self.topology_context() else {
|
||||
return;
|
||||
};
|
||||
let primary = self
|
||||
.diagram_selection
|
||||
.as_ref()
|
||||
.and_then(Selection::primary)
|
||||
.cloned();
|
||||
self.behavior.topology.clear_context();
|
||||
self.selected = primary.as_ref().and_then(subject).unwrap_or(context.owner);
|
||||
self.selected_node = None;
|
||||
self.selected_bend = None;
|
||||
self.selected_attachment = None;
|
||||
self.diagram_navigation_focus = None;
|
||||
if let Some(Target::ProcessOccurrence(endpoint)) = primary
|
||||
&& !endpoint.references.is_empty()
|
||||
&& let Ok(resolved) = oa_core::topology_context::TopologyIndex::new(self.project())
|
||||
.resolve(context.owner, &endpoint)
|
||||
{
|
||||
self.behavior.topology.select_context(resolved.address);
|
||||
}
|
||||
self.refresh_draft();
|
||||
if self.process_preview_primary().is_some() {
|
||||
self.draft = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn process_multiselect_event(&mut self, event: Event) {
|
||||
let Some(context) = self.topology_context() else {
|
||||
return;
|
||||
};
|
||||
if let Event::Refuse(_, reason) = &event
|
||||
&& diagram_removal::enabled(self)
|
||||
{
|
||||
self.status = reason.clone();
|
||||
return;
|
||||
}
|
||||
if !diagram_removal::enabled(self) || !self.behavior.topology.selecting() {
|
||||
self.status =
|
||||
"Finish or cancel the active edit before changing the process selection.".into();
|
||||
return;
|
||||
}
|
||||
let visible = self
|
||||
.behavior
|
||||
.topology
|
||||
.selection_targets(self.project(), context.owner);
|
||||
match event {
|
||||
Event::Choose(_, target, choice) => {
|
||||
if !visible.contains(&target) {
|
||||
return;
|
||||
}
|
||||
self.reconcile_process_multiselect();
|
||||
let selection = self.diagram_selection.as_mut().unwrap();
|
||||
let valid = |t: &Target| visible.contains(t);
|
||||
match choice {
|
||||
Choice::Replace => {
|
||||
selection.replace(target, valid);
|
||||
}
|
||||
Choice::Add => {
|
||||
selection.add(target, valid);
|
||||
}
|
||||
Choice::Remove => {
|
||||
selection.remove(&target);
|
||||
}
|
||||
Choice::Toggle => {
|
||||
selection.toggle(target, valid);
|
||||
}
|
||||
Choice::Inspect => {
|
||||
selection.set_primary(&target);
|
||||
}
|
||||
}
|
||||
self.inspect_process_multiselect_primary();
|
||||
}
|
||||
Event::Collapse(_, target) => {
|
||||
if !visible.contains(&target) {
|
||||
return;
|
||||
}
|
||||
self.diagram_selection
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.replace(target, |t| visible.contains(t));
|
||||
self.inspect_process_multiselect_primary();
|
||||
}
|
||||
Event::Clear(_) => {
|
||||
self.diagram_selection.as_mut().unwrap().clear();
|
||||
self.inspect_process_multiselect_primary();
|
||||
}
|
||||
Event::Refuse(_, reason) => self.status = reason,
|
||||
Event::Hide(_) => {
|
||||
self.status =
|
||||
"Process cards are model contributions, not placements. Hide is unavailable."
|
||||
.into()
|
||||
}
|
||||
Event::Move(..) => {
|
||||
self.status =
|
||||
"Process positions come from their paths. Reorder within one column instead."
|
||||
.into()
|
||||
}
|
||||
Event::ProcessReorder(snapshot, destination) => {
|
||||
if !snapshot
|
||||
.targets()
|
||||
.iter()
|
||||
.all(|target| visible.contains(target))
|
||||
{
|
||||
return;
|
||||
}
|
||||
match Prepared::new(self.project(), context.owner, snapshot.targets())
|
||||
.and_then(|prepared| prepared.plan(destination))
|
||||
{
|
||||
Ok(Plan::Noop) => {}
|
||||
Ok(Plan::Change(command)) => {
|
||||
if self.execute(*command) {
|
||||
self.inspect_process_multiselect_primary();
|
||||
self.status = format!(
|
||||
"Reordered {} contributions · Undo restores their order",
|
||||
snapshot.targets().len()
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(error) => self.status = error,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A no-op must not retire a pending reveal or allocate a history entry.
|
||||
pub(super) fn process_order_noop(&self, message: &Message) -> bool {
|
||||
let Some(context) = self.topology_context() else {
|
||||
return false;
|
||||
};
|
||||
match message {
|
||||
Message::DiagramSelection(Event::ProcessReorder(snapshot, destination)) => {
|
||||
Prepared::new(self.project(), context.owner, snapshot.targets())
|
||||
.and_then(|prepared| prepared.plan(*destination))
|
||||
.is_ok_and(|p| matches!(p, Plan::Noop))
|
||||
}
|
||||
Message::TopologyCanvas(crate::behavior::topology::CanvasEvent::Reorder {
|
||||
context: captured,
|
||||
occurrence,
|
||||
before,
|
||||
}) if *captured == context => crate::behavior::topology::reorder(
|
||||
self.project(),
|
||||
context.owner,
|
||||
*occurrence,
|
||||
*before,
|
||||
)
|
||||
.is_ok_and(|p| matches!(p, Plan::Noop)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,279 @@
|
||||
//! Actual arrangement selection and current-record Details admission.
|
||||
use super::*;
|
||||
use crate::behavior::canvas_workspace::tests::Mounted;
|
||||
use crate::behavior::scenario::{CanvasEvent, Context, Shelf};
|
||||
use crate::behavior::scenario_layout::Representation;
|
||||
use iced::{Point, Size, advanced::widget};
|
||||
|
||||
const FIXTURE: &str = include_str!("diagram_usages/tests/saved_scenario.arcadia");
|
||||
|
||||
fn id(app: &App, alias: &str) -> Id {
|
||||
app.project()
|
||||
.identities()
|
||||
.into_iter()
|
||||
.find(|(_, name)| *name == alias)
|
||||
.unwrap()
|
||||
.0
|
||||
}
|
||||
fn setup() -> (App, Id, Id, Id) {
|
||||
let mut app = App::with_project(oa_core::language::parse(FIXTURE).unwrap());
|
||||
let a = id(&app, "incident_readable");
|
||||
let b = id(&app, "incident_wide");
|
||||
let owner = id(&app, "incident_response");
|
||||
let _ = app.update(Message::Select(owner));
|
||||
let _ = app.update(Message::Page(Page::Behavior));
|
||||
choose(&mut app, Representation::Saved { diagram: a });
|
||||
let _ = app.update(Message::Select(a));
|
||||
app.window_size = Size::new(1440., 1000.);
|
||||
(app, a, b, owner)
|
||||
}
|
||||
fn send(app: &mut App, event: impl FnOnce(Context) -> CanvasEvent) {
|
||||
let context = app.scenario_context().unwrap();
|
||||
let _ = app.update(Message::ScenarioCanvas(event(context)));
|
||||
}
|
||||
fn choose(app: &mut App, representation: Representation) {
|
||||
send(app, |context| {
|
||||
CanvasEvent::Representation(context, representation)
|
||||
});
|
||||
}
|
||||
fn model_state(app: &App) -> (u64, bool, bool, bool) {
|
||||
(
|
||||
app.document.revision(),
|
||||
app.document.dirty(),
|
||||
app.document.can_undo(),
|
||||
app.document.can_redo(),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_arrangement_picker_follows_selected_saved_record_and_opens_b_properties() {
|
||||
let (mut app, a, b, _) = setup();
|
||||
let mut mounted = Mounted::new(&mut app).await;
|
||||
let snapshot = app.document.snapshot();
|
||||
let before = model_state(&app);
|
||||
let captured = app.scenario_context().unwrap();
|
||||
let picker = mounted.geometry(&app).bounds("scenario-arrangement-picker");
|
||||
assert!(
|
||||
app.window_size.height - (picker.y + picker.height) > picker.y,
|
||||
"fixture has room for Iced's menu below the actual picker"
|
||||
);
|
||||
assert_eq!(app.selected, a);
|
||||
mounted.click(&mut app, picker.center()).await;
|
||||
// iced_widget 0.14.2 overlay/menu.rs uses default line height plus
|
||||
// vertical padding for each row. The real workspace orders Automatic,
|
||||
// then the fixture's A/B/C Diagram IDs. Select B from the actual overlay.
|
||||
let row_height =
|
||||
f32::from(iced::advanced::text::LineHeight::default().to_absolute(12.into())) + 10.;
|
||||
let b_row = Point::new(
|
||||
picker.center_x(),
|
||||
picker.y + picker.height + row_height * 2.5,
|
||||
);
|
||||
assert!(b_row.y < app.window_size.height);
|
||||
let events = mounted.click(&mut app, b_row).await;
|
||||
assert!(events.iter().any(|event| matches!(event,
|
||||
Message::ScenarioCanvas(CanvasEvent::Representation(context, Representation::Saved { diagram }))
|
||||
if *context == captured && *diagram == b)), "must exercise the actual arrangement callback");
|
||||
assert_eq!(app.selected, b);
|
||||
assert_eq!(app.draft.as_ref().unwrap().original, b);
|
||||
assert_eq!(
|
||||
app.draft.as_ref().unwrap().value["name"],
|
||||
"B - Incident review negative and far"
|
||||
);
|
||||
assert_eq!(app.active_diagram, Some(b));
|
||||
assert_eq!(
|
||||
app.scenario_context().unwrap().representation,
|
||||
Representation::Saved { diagram: b }
|
||||
);
|
||||
assert_ne!(app.scenario_context().unwrap().visit, captured.visit);
|
||||
|
||||
send(&mut app, |context| {
|
||||
CanvasEvent::Shelf(context, Shelf::Selection)
|
||||
});
|
||||
mounted.settle(&mut app).await;
|
||||
let geometry = mounted.geometry(&app);
|
||||
let (details, offset) = geometry.scrolls[&widget::Id::new("scenario-details")];
|
||||
let point = geometry.bounds("scenario-properties").center() - offset;
|
||||
assert!(details.contains(point));
|
||||
let events = mounted.click(&mut app, point).await;
|
||||
assert!(events.iter().any(|event| matches!(event,
|
||||
Message::ScenarioCanvas(CanvasEvent::Properties(_, selected)) if *selected == b)));
|
||||
mounted.settle(&mut app).await;
|
||||
let geometry = mounted.geometry(&app);
|
||||
let (inspector, offset) = geometry.scrolls[&widget::Id::new("inspector")];
|
||||
assert!(
|
||||
geometry
|
||||
.text_inputs
|
||||
.iter()
|
||||
.any(|bounds| inspector.contains(bounds.center() - offset)),
|
||||
"current B Properties must expose an actual editable field"
|
||||
);
|
||||
assert!(
|
||||
!geometry
|
||||
.scrolls
|
||||
.contains_key(&widget::Id::new("scenario-details"))
|
||||
);
|
||||
assert_eq!(
|
||||
app.inspector_tab,
|
||||
crate::navigation::InspectorTab::Properties
|
||||
);
|
||||
assert_eq!(app.selected, b);
|
||||
assert_eq!(app.draft.as_ref().unwrap().original, b);
|
||||
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
|
||||
assert_eq!(app.project(), &snapshot.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &snapshot.bundle);
|
||||
assert_eq!(model_state(&app), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrangement_change_preserves_independent_semantic_and_foreign_view_selection() {
|
||||
for alias in [
|
||||
"initial_report",
|
||||
"reporter",
|
||||
"incident_response",
|
||||
"incident_repair",
|
||||
] {
|
||||
let (mut app, _, b, _) = setup();
|
||||
let selected = id(&app, alias);
|
||||
let _ = app.update(Message::Select(selected));
|
||||
let snapshot = app.document.snapshot();
|
||||
let before = model_state(&app);
|
||||
choose(&mut app, Representation::Saved { diagram: b });
|
||||
assert_eq!(app.selected, selected, "independent selection {alias}");
|
||||
assert_eq!(app.draft.as_ref().unwrap().original, selected);
|
||||
assert_eq!(app.active_diagram, Some(b));
|
||||
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
|
||||
assert_eq!(app.document.bundle(), &snapshot.bundle);
|
||||
assert_eq!(model_state(&app), before);
|
||||
if alias == "incident_repair" {
|
||||
assert!(!behavior::scenario::properties_target(
|
||||
app.project(),
|
||||
app.scenario_context().unwrap(),
|
||||
selected
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrangement_follows_view_record_to_automatic_owner_but_not_owner_back_to_saved() {
|
||||
let (mut app, _, b, owner) = setup();
|
||||
let snapshot = app.document.snapshot();
|
||||
let before = model_state(&app);
|
||||
choose(&mut app, Representation::Derived { owner });
|
||||
assert_eq!(app.selected, owner);
|
||||
assert_eq!(app.draft.as_ref().unwrap().original, owner);
|
||||
assert_eq!(app.active_diagram, None);
|
||||
assert!(behavior::scenario::properties_target(
|
||||
app.project(),
|
||||
app.scenario_context().unwrap(),
|
||||
owner
|
||||
));
|
||||
choose(&mut app, Representation::Saved { diagram: b });
|
||||
assert_eq!(
|
||||
app.selected, owner,
|
||||
"Scenario owner is now independent semantic selection"
|
||||
);
|
||||
assert_eq!(app.draft.as_ref().unwrap().original, owner);
|
||||
assert_eq!(app.active_diagram, Some(b));
|
||||
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
|
||||
assert_eq!(app.document.bundle(), &snapshot.bundle);
|
||||
assert_eq!(model_state(&app), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrangement_applies_only_the_old_view_draft_then_follows_b_with_one_undo() {
|
||||
let (mut app, a, b, _) = setup();
|
||||
let snapshot = app.document.snapshot();
|
||||
let mut expected = app.project().clone();
|
||||
expected.diagrams.get_mut(&a).unwrap().name = "Reviewed A".into();
|
||||
let revision = app.document.revision();
|
||||
let _ = app.update(Message::Field("/name".into(), "Reviewed A".into()));
|
||||
choose(&mut app, Representation::Saved { diagram: b });
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_eq!(app.selected, b);
|
||||
assert_eq!(app.draft.as_ref().unwrap().original, b);
|
||||
assert!(!app.draft_dirty());
|
||||
assert_eq!(app.document.revision(), revision + 1);
|
||||
let accepted = app.document.snapshot();
|
||||
let _ = app.update(Message::Undo);
|
||||
assert_eq!(app.project(), &snapshot.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &snapshot.bundle);
|
||||
assert!(!app.document.can_undo() && app.document.can_redo());
|
||||
let _ = app.update(Message::Redo);
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_eq!(app.document.bundle(), &accepted.bundle);
|
||||
assert!(app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_arrangement_uuid_edit_follows_the_reidentified_record_and_round_trips_source() {
|
||||
let (mut app, a, _, _) = setup();
|
||||
let snapshot = app.document.snapshot();
|
||||
let replacement = Id::parse_str("70200000-0000-4000-8000-000000000099").unwrap();
|
||||
let mut expected = app.project().clone();
|
||||
let mut diagram = expected.diagrams.remove(&a).unwrap();
|
||||
diagram.id = replacement;
|
||||
expected.diagrams.insert(replacement, diagram);
|
||||
let _ = app.update(Message::Field("/id".into(), replacement.to_string()));
|
||||
choose(&mut app, Representation::Saved { diagram: a });
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_eq!(app.selected, replacement);
|
||||
assert_eq!(app.draft.as_ref().unwrap().original, replacement);
|
||||
assert_eq!(app.active_diagram, Some(replacement));
|
||||
assert_eq!(
|
||||
app.scenario_context().unwrap().representation,
|
||||
Representation::Saved {
|
||||
diagram: replacement
|
||||
}
|
||||
);
|
||||
let accepted = app.document.snapshot();
|
||||
let _ = app.update(Message::Undo);
|
||||
assert_eq!(app.project(), &snapshot.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &snapshot.bundle);
|
||||
assert!(!app.document.can_undo() && app.document.can_redo());
|
||||
let _ = app.update(Message::Redo);
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_eq!(app.document.bundle(), &accepted.bundle);
|
||||
assert!(!app.document.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_draft_and_stale_arrangement_preserve_selection_inputs_and_accepted_state() {
|
||||
let (mut app, a, b, _) = setup();
|
||||
let old = app.scenario_context().unwrap();
|
||||
let snapshot = app.document.snapshot();
|
||||
let before = model_state(&app);
|
||||
let _ = app.update(Message::Field("/id".into(), "not-a-uuid".into()));
|
||||
let draft_value = app.draft.as_ref().unwrap().value.clone();
|
||||
choose(&mut app, Representation::Saved { diagram: b });
|
||||
assert_eq!(app.selected, a);
|
||||
assert_eq!(app.active_diagram, Some(a));
|
||||
assert_eq!(
|
||||
app.scenario_context().unwrap().representation,
|
||||
old.representation
|
||||
);
|
||||
assert_eq!(app.draft.as_ref().unwrap().value, draft_value);
|
||||
assert_eq!(app.draft.as_ref().unwrap().inputs["/id"].raw, "not-a-uuid");
|
||||
assert!(app.draft_dirty());
|
||||
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
|
||||
assert_eq!(model_state(&app), before);
|
||||
let _ = app.update(Message::RevertProperties);
|
||||
choose(&mut app, Representation::Saved { diagram: b });
|
||||
let current = app.scenario_context().unwrap();
|
||||
let _ = app.update(Message::Field("/name".into(), "Retained B input".into()));
|
||||
let selected = app.selected;
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Representation(
|
||||
old,
|
||||
Representation::Saved { diagram: a },
|
||||
)));
|
||||
assert_eq!(app.selected, selected);
|
||||
assert_eq!(app.active_diagram, Some(b));
|
||||
assert_eq!(app.scenario_context().unwrap().visit, current.visit);
|
||||
assert_eq!(
|
||||
app.draft.as_ref().unwrap().inputs["/name"].raw,
|
||||
"Retained B input"
|
||||
);
|
||||
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
|
||||
assert_eq!(app.document.bundle(), &snapshot.bundle);
|
||||
assert_eq!(model_state(&app), before);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Saved Scenario navigation is presentation state, never a document edit.
|
||||
use super::*;
|
||||
use crate::behavior::scenario_layout::{Representation, presentation::checked_owner};
|
||||
|
||||
impl App {
|
||||
pub(super) fn enter_scenario_representation(&mut self, representation: Representation) -> bool {
|
||||
let Some(owner) = checked_owner(self.project(), representation) else {
|
||||
self.status =
|
||||
"This Scenario view is no longer available or has an incompatible owner.".into();
|
||||
return false;
|
||||
};
|
||||
self.layer = self.project().elements[&owner].layer();
|
||||
self.page = Page::Behavior;
|
||||
self.behavior.active_owner = Some(owner);
|
||||
match representation {
|
||||
Representation::Saved { diagram } => self.active_diagram = Some(diagram),
|
||||
Representation::Derived { .. } => {
|
||||
if self
|
||||
.active_diagram
|
||||
.is_some_and(|id| self.saved_scenario_diagram(id))
|
||||
{
|
||||
self.active_diagram = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.selected_node = None;
|
||||
if self
|
||||
.behavior
|
||||
.scenario
|
||||
.enter_representation(self.canvas_document, owner, representation)
|
||||
{
|
||||
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Reconcile after navigation/adoption without selecting or applying a draft.
|
||||
/// A retained invalid Saved identity remains unavailable; it must not silently
|
||||
/// turn into a different automatic Scenario or another saved arrangement.
|
||||
pub(super) fn reconcile_scenario_workspace(&mut self) {
|
||||
if self.page == Page::Diagram
|
||||
&& !self.behavior.has_pending()
|
||||
&& let Some(diagram) = self
|
||||
.active_diagram
|
||||
.filter(|id| self.saved_scenario_diagram(*id))
|
||||
{
|
||||
self.enter_scenario_representation(Representation::Saved { diagram });
|
||||
}
|
||||
if self.page != Page::Behavior {
|
||||
self.behavior.scenario.leave();
|
||||
return;
|
||||
}
|
||||
if let Some(rep @ Representation::Saved { diagram }) =
|
||||
self.behavior.scenario.representation()
|
||||
{
|
||||
// The requested view is authoritative until explicit navigation
|
||||
// retires it. This also recovers the same view when Undo restores it.
|
||||
if let Some(owner) = checked_owner(self.project(), rep) {
|
||||
self.active_diagram = Some(diagram);
|
||||
self.layer = self.project().elements[&owner].layer();
|
||||
self.behavior.active_owner = Some(owner);
|
||||
self.behavior
|
||||
.scenario
|
||||
.enter_representation(self.canvas_document, owner, rep);
|
||||
} else if let Some(owner) = self.behavior.scenario.owner() {
|
||||
self.behavior
|
||||
.scenario
|
||||
.enter_representation(self.canvas_document, owner, rep);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(owner) = behavior::selected_owner(self) else {
|
||||
self.behavior.scenario.leave();
|
||||
return;
|
||||
};
|
||||
if self
|
||||
.project()
|
||||
.elements
|
||||
.get(&owner)
|
||||
.is_some_and(|e| e.kind() == Kind::Scenario)
|
||||
{
|
||||
self.behavior.scenario.enter(self.canvas_document, owner);
|
||||
} else {
|
||||
self.behavior.scenario.leave();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod adoption_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod owner_navigation_tests;
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Independent adoption oracles: expected Projects are edited directly in the
|
||||
//! fixture, then admitted through the actual source editor/Document transaction.
|
||||
//! Navigation is checked separately from the expected authored mutation.
|
||||
use super::*;
|
||||
use crate::behavior::canvas_workspace::tests::Mounted;
|
||||
use iced::advanced::widget;
|
||||
use iced::widget::text_editor;
|
||||
use oa_core::language;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct Fixture {
|
||||
app: App,
|
||||
owner: Id,
|
||||
same_layer: Id,
|
||||
other_layer: Id,
|
||||
view: Id,
|
||||
spare_view: Id,
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
let mut project = Project::empty();
|
||||
let owner = project
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Original owner", None)
|
||||
.unwrap();
|
||||
let same_layer = project
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Other OA owner", None)
|
||||
.unwrap();
|
||||
let other_layer = project
|
||||
.add_element(Kind::Scenario, Layer::Sa, "SA owner", None)
|
||||
.unwrap();
|
||||
// A remaining topology makes silent fallback observably different from the
|
||||
// required unavailable Saved view after its owner is deleted.
|
||||
project
|
||||
.add_element(Kind::Process, Layer::Oa, "Remaining process", None)
|
||||
.unwrap();
|
||||
let mut make_view = |alias: &str, name: &str, owner| {
|
||||
let id = Id::new_v4();
|
||||
project.diagrams.insert(
|
||||
id,
|
||||
Diagram {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
layer: Layer::Oa,
|
||||
projection: ProjectionKind::Scenario { scenario: owner },
|
||||
layout: None,
|
||||
nodes: Default::default(),
|
||||
routes: vec![],
|
||||
view_options: Default::default(),
|
||||
},
|
||||
);
|
||||
id
|
||||
};
|
||||
let view = make_view("retained_view", "Retained arrangement", owner);
|
||||
let spare_view = make_view("spare_view", "Spare arrangement", same_layer);
|
||||
let mut app = App::with_project(project);
|
||||
let _ = app.update(Message::Select(owner));
|
||||
choose(&mut app, view);
|
||||
assert_saved(&app, view, owner, Layer::Oa);
|
||||
assert!(!app.document.can_undo());
|
||||
Fixture {
|
||||
app,
|
||||
owner,
|
||||
same_layer,
|
||||
other_layer,
|
||||
view,
|
||||
spare_view,
|
||||
}
|
||||
}
|
||||
|
||||
fn choose(app: &mut App, id: Id) {
|
||||
let _ = app.update(Message::Diagram(Choice {
|
||||
id,
|
||||
label: "Previously captured picker item".into(),
|
||||
}));
|
||||
}
|
||||
|
||||
fn assert_saved(app: &App, view: Id, owner: Id, layer: Layer) {
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(app.layer, layer);
|
||||
assert_eq!(app.active_diagram, Some(view));
|
||||
let context = app
|
||||
.scenario_context()
|
||||
.expect("saved owner remains the visible context");
|
||||
assert_eq!(context.scenario, owner);
|
||||
assert_eq!(
|
||||
context.representation,
|
||||
Representation::Saved { diagram: view }
|
||||
);
|
||||
assert!(!context.visit.is_nil());
|
||||
}
|
||||
|
||||
fn adopt_from_source(app: &mut App, expected: &Project) {
|
||||
let text = language::format(expected);
|
||||
// Parser equality is a fixture precondition, not the navigation oracle.
|
||||
assert_eq!(language::parse(&text).unwrap(), *expected);
|
||||
let _ = app.update(Message::Page(Page::Text));
|
||||
let _ = app.update(Message::SourceEdit(text_editor::Action::SelectAll));
|
||||
let _ = app.update(Message::SourceEdit(text_editor::Action::Edit(
|
||||
text_editor::Edit::Paste(Arc::new(text)),
|
||||
)));
|
||||
assert!(app.source_dirty());
|
||||
let _ = app.update(Message::ApplySource);
|
||||
assert!(!app.source_dirty(), "{}", app.status);
|
||||
assert_eq!(
|
||||
app.project(),
|
||||
expected,
|
||||
"actual source transaction must adopt exactly the fixture change"
|
||||
);
|
||||
let _ = app.update(Message::Page(Page::Behavior));
|
||||
}
|
||||
|
||||
fn retarget(cross_layer: bool) {
|
||||
let mut f = fixture();
|
||||
let before = f.app.document.snapshot();
|
||||
let old_context = f.app.scenario_context().unwrap();
|
||||
let revision = f.app.document.revision();
|
||||
let target = if cross_layer {
|
||||
f.other_layer
|
||||
} else {
|
||||
f.same_layer
|
||||
};
|
||||
let layer = if cross_layer { Layer::Sa } else { Layer::Oa };
|
||||
let mut expected = before.decoded.project.clone();
|
||||
let view = expected.diagrams.get_mut(&f.view).unwrap();
|
||||
view.projection = ProjectionKind::Scenario { scenario: target };
|
||||
view.layer = layer;
|
||||
|
||||
adopt_from_source(&mut f.app, &expected);
|
||||
assert_saved(&f.app, f.view, target, layer);
|
||||
assert_ne!(f.app.scenario_context().unwrap().visit, old_context.visit);
|
||||
assert_eq!(
|
||||
f.app.document.revision(),
|
||||
revision + 1,
|
||||
"routing must not create a second transaction"
|
||||
);
|
||||
assert_eq!(
|
||||
f.app.project().diagrams[&f.spare_view],
|
||||
before.decoded.project.diagrams[&f.spare_view]
|
||||
);
|
||||
let adopted_bundle = f.app.document.bundle().clone();
|
||||
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_saved(&f.app, f.view, f.owner, Layer::Oa);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(
|
||||
!f.app.document.can_undo(),
|
||||
"exactly one authored adoption must be undone"
|
||||
);
|
||||
let _ = f.app.update(Message::Redo);
|
||||
assert_saved(&f.app, f.view, target, layer);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_eq!(f.app.document.bundle(), &adopted_bundle);
|
||||
assert!(!f.app.document.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_same_layer_owner_retarget_undo_redo_keeps_requested_saved_uuid() {
|
||||
retarget(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_cross_layer_owner_retarget_undo_redo_keeps_requested_saved_uuid() {
|
||||
retarget(true);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_deleted_owner_and_saved_view_mount_unavailable_instead_of_another_behavior() {
|
||||
let mut f = fixture();
|
||||
let before = f.app.document.snapshot();
|
||||
let mut expected = before.decoded.project.clone();
|
||||
assert!(expected.elements.remove(&f.owner).is_some());
|
||||
assert!(expected.diagrams.remove(&f.view).is_some());
|
||||
assert!(expected.elements.contains_key(&f.same_layer));
|
||||
assert!(
|
||||
expected
|
||||
.elements
|
||||
.values()
|
||||
.any(|e| e.kind() == Kind::Process)
|
||||
);
|
||||
adopt_from_source(&mut f.app, &expected);
|
||||
assert_eq!(
|
||||
f.app.behavior.scenario.representation(),
|
||||
Some(Representation::Saved { diagram: f.view })
|
||||
);
|
||||
let adopted = f.app.document.snapshot();
|
||||
let revision = f.app.document.revision();
|
||||
let mut mounted = Mounted::new(&mut f.app).await;
|
||||
let geometry = mounted.geometry(&f.app);
|
||||
assert!(
|
||||
geometry
|
||||
.containers
|
||||
.contains_key(&widget::Id::from("scenario-viewport-unavailable"))
|
||||
);
|
||||
assert!(
|
||||
!geometry
|
||||
.containers
|
||||
.contains_key(&widget::Id::from("scenario-viewport"))
|
||||
);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_eq!(f.app.document.bundle(), &adopted.bundle);
|
||||
assert_eq!(
|
||||
f.app.document.revision(),
|
||||
revision,
|
||||
"mounting unavailable must remain passive"
|
||||
);
|
||||
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_saved(&f.app, f.view, f.owner, Layer::Oa);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
let _ = f.app.update(Message::Redo);
|
||||
assert_eq!(
|
||||
f.app.behavior.scenario.representation(),
|
||||
Some(Representation::Saved { diagram: f.view })
|
||||
);
|
||||
mounted.settle(&mut f.app).await;
|
||||
assert!(
|
||||
mounted
|
||||
.geometry(&f.app)
|
||||
.containers
|
||||
.contains_key(&widget::Id::from("scenario-viewport-unavailable"))
|
||||
);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_eq!(f.app.document.bundle(), &adopted.bundle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_and_deleted_picker_ids_cannot_apply_an_unrelated_valid_property_draft() {
|
||||
let mut f = fixture();
|
||||
let mut expected = f.app.project().clone();
|
||||
expected.diagrams.remove(&f.spare_view).unwrap();
|
||||
adopt_from_source(&mut f.app, &expected);
|
||||
let _ = f.app.update(Message::Select(f.owner));
|
||||
let _ = f.app.update(Message::Field(
|
||||
"/name".into(),
|
||||
"Pending valid owner rename".into(),
|
||||
));
|
||||
assert!(f.app.draft_dirty());
|
||||
let before = f.app.document.snapshot();
|
||||
let revision = f.app.document.revision();
|
||||
let selected = f.app.selected;
|
||||
for invalid in [Id::nil(), f.spare_view] {
|
||||
choose(&mut f.app, invalid);
|
||||
assert_saved(&f.app, f.view, f.owner, Layer::Oa);
|
||||
assert_eq!(f.app.selected, selected);
|
||||
assert!(f.app.draft_dirty());
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert_eq!(f.app.document.revision(), revision);
|
||||
}
|
||||
// Establish that the retained draft really was valid, not merely refused by
|
||||
// the property validator: explicit Apply commits it in exactly one step.
|
||||
assert!(f.app.apply(), "{}", f.app.status);
|
||||
assert_eq!(
|
||||
f.app.project().elements[&f.owner].name,
|
||||
"Pending valid owner rename"
|
||||
);
|
||||
assert_eq!(f.app.document.revision(), revision + 1);
|
||||
let _ = f.app.update(Message::Undo);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Explicit owner navigation must retire a retained Saved Scenario, including
|
||||
//! when selection was made on a different page. These are real App events.
|
||||
use super::*;
|
||||
use crate::behavior::scenario::CanvasEvent;
|
||||
|
||||
fn setup(kind: Kind) -> (App, Id, Id) {
|
||||
let mut project = Project::empty();
|
||||
let scenario = project
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Incident review", None)
|
||||
.unwrap();
|
||||
let target = project
|
||||
.add_element(kind, Layer::Oa, "Explicit destination", None)
|
||||
.unwrap();
|
||||
let view = Id::new_v4();
|
||||
project.diagrams.insert(
|
||||
view,
|
||||
Diagram {
|
||||
id: view,
|
||||
alias: "incident_saved".into(),
|
||||
name: "Incident saved arrangement".into(),
|
||||
description: String::new(),
|
||||
layer: Layer::Oa,
|
||||
projection: ProjectionKind::Scenario { scenario },
|
||||
layout: None,
|
||||
nodes: Default::default(),
|
||||
routes: vec![],
|
||||
view_options: Default::default(),
|
||||
},
|
||||
);
|
||||
let errors: Vec<_> = oa_core::validation::validate(&project)
|
||||
.into_iter()
|
||||
.filter(|issue| issue.severity == oa_core::validation::Severity::Error)
|
||||
.collect();
|
||||
assert!(errors.is_empty(), "{errors:?}");
|
||||
let mut app = App::with_project(project);
|
||||
let _ = app.update(Message::Select(scenario));
|
||||
let _ = app.update(Message::Diagram(Choice {
|
||||
id: view,
|
||||
label: "Incident saved arrangement".into(),
|
||||
}));
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(
|
||||
app.scenario_context().unwrap().representation,
|
||||
Representation::Saved { diagram: view }
|
||||
);
|
||||
assert_eq!(app.selected, scenario);
|
||||
(app, scenario, target)
|
||||
}
|
||||
|
||||
fn assert_destination(app: &App, target: Id) {
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(app.selected, target);
|
||||
assert_eq!(app.behavior.active_owner, Some(target));
|
||||
assert_eq!(behavior::selected_owner(app), Some(target));
|
||||
assert_eq!(
|
||||
app.behavior.scenario.representation(),
|
||||
None,
|
||||
"explicit non-Scenario destination must not retain an overriding Saved request"
|
||||
);
|
||||
assert!(app.scenario_context().is_none());
|
||||
}
|
||||
|
||||
fn exercise(via_guide: bool) {
|
||||
for kind in [Kind::Process, Kind::StateMachine] {
|
||||
let (mut app, scenario, target) = setup(kind);
|
||||
assert_ne!(scenario, target);
|
||||
let held = app.scenario_context().unwrap();
|
||||
let accepted = app.document.snapshot();
|
||||
let drafts = app.source_workspace.bundle();
|
||||
let revision = app.document.revision();
|
||||
let dirty = (app.document.dirty(), app.dirty(), app.source_dirty());
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
if via_guide {
|
||||
let _ = app.update(Message::Page(Page::Guide));
|
||||
assert_eq!(app.page, Page::Guide);
|
||||
assert!(app.scenario_context().is_none());
|
||||
}
|
||||
let _ = app.update(Message::Select(target));
|
||||
if via_guide {
|
||||
assert_eq!(
|
||||
app.page,
|
||||
Page::Guide,
|
||||
"explorer selection must not itself switch the page"
|
||||
);
|
||||
let _ = app.update(Message::Page(Page::Behavior));
|
||||
}
|
||||
assert_destination(&app, target);
|
||||
let camera = app.camera_boundary();
|
||||
// The prior saved canvas cannot open its outline after either owner route.
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Shelf(
|
||||
held,
|
||||
crate::behavior::scenario::Shelf::Selection,
|
||||
)));
|
||||
assert_destination(&app, target);
|
||||
assert!(app.camera_boundary() == camera);
|
||||
assert_eq!(app.project(), &accepted.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &accepted.bundle);
|
||||
assert_eq!(app.source_workspace.bundle(), drafts);
|
||||
assert_eq!(app.document.revision(), revision);
|
||||
assert_eq!(
|
||||
(app.document.dirty(), app.dirty(), app.source_dirty()),
|
||||
dirty
|
||||
);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_scenario_guide_selection_returns_to_explicit_process_or_state_owner() {
|
||||
exercise(true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_scenario_direct_behavior_selection_enters_explicit_process_or_state_owner() {
|
||||
exercise(false);
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
use super::*;
|
||||
use crate::behavior::scenario::{CanvasEvent, ScrollArea};
|
||||
|
||||
fn saved(p: &mut Project, owner: Id, name: &str) -> Id {
|
||||
let id = Id::new_v4();
|
||||
p.diagrams.insert(
|
||||
id,
|
||||
Diagram {
|
||||
id,
|
||||
alias: format!("view_{}", p.diagrams.len()),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
layer: Layer::Oa,
|
||||
projection: ProjectionKind::Scenario { scenario: owner },
|
||||
layout: None,
|
||||
routes: vec![],
|
||||
nodes: Default::default(),
|
||||
view_options: Default::default(),
|
||||
},
|
||||
);
|
||||
id
|
||||
}
|
||||
fn setup() -> (App, Id, Id, Id, Id) {
|
||||
let (mut p, [owner, callee, _], [reference, _, _]) =
|
||||
behavior::scenario::direct_tests::navigation_fixture();
|
||||
let a = saved(&mut p, owner, "Review A");
|
||||
let b = saved(&mut p, owner, "Review B");
|
||||
let mut app = App::with_project(p);
|
||||
app.select(owner);
|
||||
(app, a, b, reference, callee)
|
||||
}
|
||||
fn choose(app: &mut App, diagram: Id) {
|
||||
let _ = app.update(Message::Diagram(Choice {
|
||||
id: diagram,
|
||||
label: "Captured view".into(),
|
||||
}));
|
||||
}
|
||||
fn event(app: &mut App, f: impl FnOnce(behavior::scenario::Context) -> CanvasEvent) {
|
||||
let context = app.scenario_context().unwrap();
|
||||
let _ = app.update(Message::ScenarioCanvas(f(context)));
|
||||
}
|
||||
#[test]
|
||||
fn saved_view_switches_are_distinct_passive_visits_and_preserve_actual_history() {
|
||||
let (mut app, a, b, _, _) = setup();
|
||||
let original = app.document.snapshot();
|
||||
let owner = app.selected;
|
||||
assert!(app.execute(Command::Rename(owner, "Previously edited caller".into())));
|
||||
let edited = app.document.snapshot();
|
||||
let edited_revision = app.document.revision();
|
||||
choose(&mut app, a);
|
||||
let first = app.scenario_context().unwrap();
|
||||
choose(&mut app, b);
|
||||
let second = app.scenario_context().unwrap();
|
||||
choose(&mut app, a);
|
||||
let third = app.scenario_context().unwrap();
|
||||
assert_eq!(first.scenario, owner);
|
||||
assert_eq!(first.representation, Representation::Saved { diagram: a });
|
||||
assert_eq!(second.representation, Representation::Saved { diagram: b });
|
||||
assert_ne!(first.visit, second.visit);
|
||||
assert_ne!(first.visit, third.visit);
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(app.selected, owner);
|
||||
assert_eq!(app.document.bundle(), &edited.bundle);
|
||||
assert_eq!(app.project(), &edited.decoded.project);
|
||||
assert_eq!(app.document.revision(), edited_revision);
|
||||
let _ = app.update(Message::Undo);
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
assert_eq!(app.project(), &original.decoded.project);
|
||||
let _ = app.update(Message::Redo);
|
||||
assert_eq!(app.document.bundle(), &edited.bundle);
|
||||
assert_eq!(app.project(), &edited.decoded.project);
|
||||
}
|
||||
#[test]
|
||||
fn saved_view_return_rejects_old_passive_events_without_an_intermediate_frame() {
|
||||
let (mut app, a, b, _, _) = setup();
|
||||
choose(&mut app, a);
|
||||
let old = app.scenario_context().unwrap();
|
||||
choose(&mut app, b);
|
||||
choose(&mut app, a);
|
||||
let current = app.scenario_context().unwrap();
|
||||
let camera = app.behavior.scenario.camera_boundary();
|
||||
let before = app.document.snapshot();
|
||||
for stale in [
|
||||
CanvasEvent::Viewport(old, iced::Size::new(432., 321.)),
|
||||
CanvasEvent::Scrolled(old, ScrollArea::Page, iced::Vector::new(0., 800.)),
|
||||
CanvasEvent::FormShown(old, Id::new_v4()),
|
||||
CanvasEvent::Restored(
|
||||
old,
|
||||
Id::new_v4(),
|
||||
ScrollArea::Page,
|
||||
iced::Vector::new(0., 800.),
|
||||
),
|
||||
CanvasEvent::Camera(
|
||||
old,
|
||||
app.camera_epoch,
|
||||
behavior::canvas_workspace::Event::Pan(iced::Vector::new(90., 80.)),
|
||||
),
|
||||
] {
|
||||
let _ = app.update(Message::ScenarioCanvas(stale));
|
||||
assert_eq!(app.scenario_context(), Some(current));
|
||||
assert!(app.behavior.scenario.camera_boundary() == camera);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn saved_reference_back_restores_exact_view_with_a_fresh_visit() {
|
||||
let (mut app, a, _, reference, callee) = setup();
|
||||
choose(&mut app, a);
|
||||
let caller = app.scenario_context().unwrap();
|
||||
let before = app.document.snapshot();
|
||||
event(&mut app, |ctx| CanvasEvent::OpenUse(ctx, reference));
|
||||
let target = app.scenario_context().unwrap();
|
||||
assert_eq!(target.scenario, callee);
|
||||
assert_eq!(
|
||||
target.representation,
|
||||
Representation::Derived { owner: callee }
|
||||
);
|
||||
assert_eq!(app.active_diagram, None);
|
||||
event(&mut app, CanvasEvent::Back);
|
||||
let returned = app.scenario_context().unwrap();
|
||||
assert_eq!(returned.representation, caller.representation);
|
||||
assert_eq!(app.active_diagram, Some(a));
|
||||
assert_eq!(app.selected, reference);
|
||||
assert_ne!(returned.visit, caller.visit);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
#[test]
|
||||
fn saved_picker_applies_valid_old_draft_and_uuid_edit_follows_that_same_view() {
|
||||
let (mut app, a, b, _, _) = setup();
|
||||
choose(&mut app, a);
|
||||
let _ = app.update(Message::Select(a));
|
||||
let before = app.document.snapshot();
|
||||
let _ = app.update(Message::Field("/name".into(), "Renamed A".into()));
|
||||
choose(&mut app, b);
|
||||
assert_eq!(app.project().diagrams[&a].name, "Renamed A");
|
||||
assert_eq!(app.selected, b);
|
||||
assert_eq!(
|
||||
app.scenario_context().unwrap().representation,
|
||||
Representation::Saved { diagram: b }
|
||||
);
|
||||
let _ = app.update(Message::Undo);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
choose(&mut app, a);
|
||||
let replacement = Id::new_v4();
|
||||
let _ = app.update(Message::Field("/id".into(), replacement.to_string()));
|
||||
choose(&mut app, a);
|
||||
assert!(!app.project().diagrams.contains_key(&a));
|
||||
assert_eq!(app.active_diagram, Some(replacement));
|
||||
assert_eq!(app.selected, replacement);
|
||||
assert_eq!(
|
||||
app.scenario_context().unwrap().representation,
|
||||
Representation::Saved {
|
||||
diagram: replacement
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn leaving_and_reentering_saved_view_preserves_source_and_retires_passive_visit() {
|
||||
let (mut app, a, _, _, _) = setup();
|
||||
choose(&mut app, a);
|
||||
let old = app.scenario_context().unwrap();
|
||||
let before = app.document.snapshot();
|
||||
let _ = app.update(Message::Page(Page::Guide));
|
||||
assert!(app.scenario_context().is_none());
|
||||
let _ = app.update(Message::Page(Page::Behavior));
|
||||
let fresh = app.scenario_context().unwrap();
|
||||
assert_eq!(fresh.representation, old.representation);
|
||||
assert_ne!(fresh.visit, old.visit);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrangement_picker_rejects_previous_visit_and_switches_automatic_without_model_changes() {
|
||||
let (mut app, a, b, _, _) = setup();
|
||||
choose(&mut app, a);
|
||||
let stale = app.scenario_context().unwrap();
|
||||
choose(&mut app, b);
|
||||
let current = app.scenario_context().unwrap();
|
||||
let before = app.document.snapshot();
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Representation(
|
||||
stale,
|
||||
Representation::Saved { diagram: a },
|
||||
)));
|
||||
assert_eq!(app.scenario_context(), Some(current));
|
||||
event(&mut app, |context| {
|
||||
CanvasEvent::Representation(
|
||||
context,
|
||||
Representation::Derived {
|
||||
owner: context.scenario,
|
||||
},
|
||||
)
|
||||
});
|
||||
assert_eq!(
|
||||
app.scenario_context().unwrap().representation,
|
||||
Representation::Derived {
|
||||
owner: current.scenario
|
||||
}
|
||||
);
|
||||
assert_eq!(app.active_diagram, None);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Admit spacing packets before ordinary navigation can retire a newer reveal.
|
||||
use super::*;
|
||||
use behavior::scenario::spacing::{Event, controller::Finish};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
impl App {
|
||||
pub(super) fn spacing_enabled(&self) -> bool {
|
||||
self.pending_diagram_reveal.is_none()
|
||||
&& !self.behavior.has_pending()
|
||||
&& !self.draft_dirty()
|
||||
&& !self.source_dirty()
|
||||
&& !self.source_rename.open()
|
||||
&& behavior::canvas_workspace::keyboard_enabled(self)
|
||||
}
|
||||
|
||||
pub(super) fn scenario_spacing(&mut self, event: Event) -> Task<Message> {
|
||||
let stamp = event.stamp();
|
||||
if self.scenario_context() != Some(stamp.context) || self.camera_epoch != stamp.camera_epoch
|
||||
{
|
||||
return Task::none();
|
||||
}
|
||||
let state = &self.behavior.scenario;
|
||||
let matches =
|
||||
state.spacing_token() == Some(event.token()) && state.spacing_stamp() == Some(stamp);
|
||||
if match event {
|
||||
Event::Begin { token, .. } => token.is_nil() || state.spacing_token().is_some(),
|
||||
_ => !matches,
|
||||
} {
|
||||
return Task::none();
|
||||
}
|
||||
if matches!(event, Event::Cancel { .. }) || !self.spacing_enabled() {
|
||||
if self.behavior.scenario.cancel_spacing() {
|
||||
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
|
||||
}
|
||||
return Task::none();
|
||||
}
|
||||
match event {
|
||||
Event::Begin { .. } => {
|
||||
let mut state = std::mem::take(&mut self.behavior.scenario);
|
||||
let result = state.begin_spacing(self.project(), event);
|
||||
self.behavior.scenario = state;
|
||||
if result.is_err() {
|
||||
self.status = "The drag could not start in this view. Try again.".into();
|
||||
}
|
||||
}
|
||||
Event::Move { screen, .. } => self.behavior.scenario.move_spacing(screen),
|
||||
Event::Finish { screen, .. } => {
|
||||
let finished = self.behavior.scenario.finish_spacing(screen);
|
||||
// Retire queued packets even for zero motion or a refused finish.
|
||||
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
|
||||
match finished {
|
||||
Ok(Finish::Click(target)) => self.select(target),
|
||||
Ok(Finish::Noop) => {}
|
||||
Ok(Finish::Commit {
|
||||
command,
|
||||
selected,
|
||||
scale,
|
||||
pan,
|
||||
}) => {
|
||||
// Document prepares and writes the source candidate before
|
||||
// committing its snapshot. Failure leaves camera/selection
|
||||
// and source/history at their accepted values.
|
||||
match self.document.execute(*command) {
|
||||
Ok(_) => {
|
||||
self.selected = selected;
|
||||
self.selected_node = None;
|
||||
self.diagram_navigation_focus = None;
|
||||
self.behavior.scenario.accept_spacing_camera(scale, pan);
|
||||
self.sync();
|
||||
self.status = "Scenario spacing updated.".into();
|
||||
}
|
||||
Err(error) => self.status = format!("Spacing was not applied: {error}"),
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
self.status =
|
||||
"That position cannot be applied. The saved arrangement is unchanged."
|
||||
.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Cancel { .. } => unreachable!(),
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
use super::*;
|
||||
use behavior::scenario::{
|
||||
CanvasEvent,
|
||||
spacing::{
|
||||
Target,
|
||||
controller::tests::{fixture, packet},
|
||||
},
|
||||
};
|
||||
use iced::{Point, Size, Vector};
|
||||
|
||||
fn setup() -> (App, Id, Id) {
|
||||
let (document, owner, diagram, lane, message) = fixture();
|
||||
let mut app = App::with_project(document.project().clone());
|
||||
let _ = app.update(Message::Select(owner));
|
||||
let _ = app.update(Message::Diagram(Choice {
|
||||
id: diagram,
|
||||
label: "Saved".into(),
|
||||
}));
|
||||
let c = app.scenario_context().unwrap();
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Viewport(
|
||||
c,
|
||||
Size::new(900., 600.),
|
||||
)));
|
||||
assert!(app.spacing_enabled());
|
||||
(app, lane, message)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_text_and_scenario_messages_do_not_retire_a_new_saved_spacing_gesture() {
|
||||
let (mut app, lane, _) = setup();
|
||||
let previous = app.scenario_context().unwrap();
|
||||
let diagram = match previous.representation {
|
||||
behavior::scenario_layout::Representation::Saved { diagram } => diagram,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let _ = app.update(Message::Page(Page::Text));
|
||||
let old_indent = Message::SourceIndent(app.source_symbol_context(), false);
|
||||
let old_drawer = Message::TextWorkspace(text_workspace::Event::ShowDrawer(
|
||||
app.text_drawer_context(),
|
||||
text_workspace::DrawerTab::Problems,
|
||||
));
|
||||
let old_command = app.text_command_message(text_workspace::Command::ShowStatus);
|
||||
let _ = app.update(Message::Diagram(Choice {
|
||||
id: diagram,
|
||||
label: "Saved".into(),
|
||||
}));
|
||||
let context = app.scenario_context().unwrap();
|
||||
assert_ne!(context.visit, previous.visit);
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Viewport(
|
||||
context,
|
||||
Size::new(900., 600.),
|
||||
)));
|
||||
let context = app.scenario_context().unwrap();
|
||||
let (event, start, _) = begin(&mut app, Target::Lane(lane));
|
||||
move_to(&mut app, event, start + Vector::new(24., 0.));
|
||||
let accepted = app.document.snapshot();
|
||||
let source = app.source_workspace.bundle();
|
||||
let source_version = app.source_version;
|
||||
let camera = app.camera_boundary();
|
||||
let selected = app.selected;
|
||||
let events = [
|
||||
old_indent,
|
||||
old_drawer,
|
||||
old_command,
|
||||
Message::ScenarioCanvas(CanvasEvent::Shelf(
|
||||
previous,
|
||||
behavior::scenario::Shelf::Selection,
|
||||
)),
|
||||
Message::ScenarioCanvas(CanvasEvent::Properties(previous, lane)),
|
||||
];
|
||||
for rejected in events {
|
||||
let _ = app.update(rejected);
|
||||
assert_eq!(app.scenario_context(), Some(context));
|
||||
assert_eq!(app.behavior.scenario.spacing_token(), Some(event.token()));
|
||||
assert_eq!(app.behavior.scenario.spacing_stamp(), Some(event.stamp()));
|
||||
assert!(app.camera_boundary() == camera);
|
||||
assert_eq!(app.selected, selected);
|
||||
assert_eq!(app.source_version, source_version);
|
||||
assert_eq!(app.source_workspace.bundle(), source);
|
||||
assert_eq!(app.document.bundle(), &accepted.bundle);
|
||||
assert_eq!(app.project(), &accepted.decoded.project);
|
||||
assert!(app.text_workspace.drawer().is_none());
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
finish(&mut app, event, start + Vector::new(24., 0.));
|
||||
assert!(
|
||||
app.document.can_undo(),
|
||||
"the current gesture remains usable"
|
||||
);
|
||||
}
|
||||
fn begin(app: &mut App, target: Target) -> (Event, Point, f32) {
|
||||
let event = packet(
|
||||
app.project(),
|
||||
&app.behavior.scenario,
|
||||
app.scenario_context().unwrap(),
|
||||
app.camera_epoch,
|
||||
target,
|
||||
);
|
||||
let Event::Begin {
|
||||
press_screen,
|
||||
scale,
|
||||
..
|
||||
} = event
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Spacing(event)));
|
||||
assert_eq!(app.behavior.scenario.spacing_token(), Some(event.token()));
|
||||
(event, press_screen, scale)
|
||||
}
|
||||
fn send(app: &mut App, event: Event) {
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Spacing(event)));
|
||||
}
|
||||
fn move_to(app: &mut App, begin: Event, screen: Point) {
|
||||
send(
|
||||
app,
|
||||
Event::Move {
|
||||
stamp: begin.stamp(),
|
||||
token: begin.token(),
|
||||
screen,
|
||||
},
|
||||
);
|
||||
}
|
||||
fn finish(app: &mut App, begin: Event, screen: Point) {
|
||||
send(
|
||||
app,
|
||||
Event::Finish {
|
||||
stamp: begin.stamp(),
|
||||
token: begin.token(),
|
||||
screen,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_batch_preview_is_immutable_and_one_commit_undo_redo_has_exact_source_parity() {
|
||||
let (mut app, lane, _) = setup();
|
||||
let original = app.document.snapshot();
|
||||
let source = app.source_workspace.bundle();
|
||||
let selected = app.selected;
|
||||
let epoch = app.canvas_epoch;
|
||||
let (event, start, scale) = begin(&mut app, Target::Lane(lane));
|
||||
move_to(&mut app, event, start + Vector::new(40., 300.));
|
||||
assert_eq!(app.selected, selected);
|
||||
assert_eq!(app.canvas_epoch, epoch);
|
||||
assert_eq!(app.project(), &original.decoded.project);
|
||||
assert_eq!(app.source_workspace.bundle(), source);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
finish(&mut app, event, start + Vector::new(40., 300.));
|
||||
assert_eq!(app.selected, lane);
|
||||
assert!(app.document.can_undo() && !app.document.can_redo());
|
||||
let accepted = app.document.snapshot();
|
||||
assert_ne!(accepted.bundle, original.bundle);
|
||||
let expected = behavior::scenario::spacing::controller::tests::expected(
|
||||
&original.decoded.project,
|
||||
match event.stamp().context.representation {
|
||||
behavior::scenario_layout::Representation::Saved { diagram } => diagram,
|
||||
_ => unreachable!(),
|
||||
},
|
||||
Target::Lane(lane),
|
||||
40. / scale,
|
||||
);
|
||||
assert_eq!(app.project(), &expected);
|
||||
let _ = app.update(Message::ShortcutUndo(false));
|
||||
assert_eq!(app.project(), &original.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
assert!(!app.document.can_undo() && app.document.can_redo());
|
||||
let _ = app.update(Message::ShortcutUndo(true));
|
||||
assert_eq!(app.project(), &accepted.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &accepted.bundle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn click_selects_but_crossed_return_and_cancel_preserve_selection_camera_and_history() {
|
||||
let (mut app, lane, message) = setup();
|
||||
let original = app.document.snapshot();
|
||||
let camera = app.behavior.scenario.camera_boundary();
|
||||
let (event, start, _) = begin(&mut app, Target::Message(message));
|
||||
finish(&mut app, event, start + Vector::new(30., 2.));
|
||||
assert_eq!(app.selected, message);
|
||||
assert!(camera == app.behavior.scenario.camera_boundary());
|
||||
for cancel in [false, true] {
|
||||
let (event, start, _) = begin(&mut app, Target::Lane(lane));
|
||||
move_to(&mut app, event, start + Vector::new(30., 0.));
|
||||
if cancel {
|
||||
send(
|
||||
&mut app,
|
||||
Event::Cancel {
|
||||
stamp: event.stamp(),
|
||||
token: event.token(),
|
||||
},
|
||||
);
|
||||
} else {
|
||||
finish(&mut app, event, start);
|
||||
}
|
||||
assert_eq!(app.selected, message);
|
||||
assert!(camera == app.behavior.scenario.camera_boundary());
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
assert_eq!(app.project(), &original.decoded.project);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_finish_after_new_view_and_forged_token_are_inert_before_reveal_reconciliation() {
|
||||
let (mut app, lane, _) = setup();
|
||||
let (event, start, _) = begin(&mut app, Target::Lane(lane));
|
||||
let held_epoch = app.canvas_epoch;
|
||||
send(
|
||||
&mut app,
|
||||
Event::Finish {
|
||||
stamp: event.stamp(),
|
||||
token: Id::new_v4(),
|
||||
screen: start + Vector::new(30., 0.),
|
||||
},
|
||||
);
|
||||
assert_eq!(app.canvas_epoch, held_epoch);
|
||||
assert_eq!(app.behavior.scenario.spacing_token(), Some(event.token()));
|
||||
let owner = event.stamp().context.scenario;
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Representation(
|
||||
event.stamp().context,
|
||||
behavior::scenario_layout::Representation::Derived { owner },
|
||||
)));
|
||||
let current = app.scenario_context();
|
||||
let epoch = app.canvas_epoch;
|
||||
let original = app.document.snapshot();
|
||||
finish(&mut app, event, start + Vector::new(50., 0.));
|
||||
assert_eq!(app.scenario_context(), current);
|
||||
assert_eq!(app.canvas_epoch, epoch);
|
||||
assert!(app.behavior.scenario.spacing_token().is_none());
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_write_failure_cannot_commit_candidate_or_materialize_camera() {
|
||||
let (mut app, lane, _) = setup();
|
||||
let bundle = app.document.bundle().clone();
|
||||
let mut limits = oa_core::source_project::ProjectLimits::default();
|
||||
limits.model.max_source_bytes = bundle.files.values().map(String::len).sum();
|
||||
app.document = Document::from_bundle(bundle, limits).unwrap();
|
||||
app.sync();
|
||||
let original = app.document.snapshot();
|
||||
let selected = app.selected;
|
||||
let camera = app.behavior.scenario.camera_boundary();
|
||||
let (event, start, _) = begin(&mut app, Target::Lane(lane));
|
||||
move_to(&mut app, event, start + Vector::new(40., 0.));
|
||||
finish(&mut app, event, start + Vector::new(40., 0.));
|
||||
assert!(
|
||||
app.status.starts_with("Spacing was not applied:"),
|
||||
"{}",
|
||||
app.status
|
||||
);
|
||||
assert_eq!(app.selected, selected);
|
||||
assert!(camera == app.behavior.scenario.camera_boundary());
|
||||
assert_eq!(app.project(), &original.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
assert!(app.behavior.scenario.spacing_token().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_semantic_draft_and_source_edit_cancel_and_reject_held_finish() {
|
||||
for source in [false, true] {
|
||||
let (mut app, lane, _) = setup();
|
||||
let original = app.document.snapshot();
|
||||
let selected = app.selected;
|
||||
let (event, start, _) = begin(&mut app, Target::Lane(lane));
|
||||
move_to(&mut app, event, start + Vector::new(30., 0.));
|
||||
if source {
|
||||
let _ = app.update(Message::SourceEdit(text_editor::Action::Edit(
|
||||
text_editor::Edit::Insert(' '),
|
||||
)));
|
||||
assert!(app.source_dirty());
|
||||
} else {
|
||||
let _ = app.update(Message::Behavior(behavior::Event::Scenario(
|
||||
behavior::scenario::Event::Start(
|
||||
event.stamp().context.scenario,
|
||||
behavior::scenario::Tool::Lifeline,
|
||||
),
|
||||
)));
|
||||
assert!(app.behavior.has_pending());
|
||||
}
|
||||
let draft = app.source_workspace.bundle();
|
||||
assert!(app.behavior.scenario.spacing_token().is_none());
|
||||
finish(&mut app, event, start + Vector::new(30., 0.));
|
||||
assert_eq!(app.project(), &original.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
assert_eq!(app.source_workspace.bundle(), draft);
|
||||
assert_eq!(app.selected, selected);
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_finish_cannot_remove_new_same_view_deferred_reveal() {
|
||||
let (mut app, lane, message) = setup();
|
||||
let (event, start, _) = begin(&mut app, Target::Lane(lane));
|
||||
let behavior::scenario_layout::Representation::Saved { diagram } =
|
||||
event.stamp().context.representation
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
let _ = app.update(Message::RevealInDiagram(diagram, message));
|
||||
assert!(app.pending_diagram_reveal.is_some());
|
||||
let epoch = app.canvas_epoch;
|
||||
let selected = app.selected;
|
||||
let visit = app.pending_scenario_reveal_visit;
|
||||
let original = app.document.snapshot();
|
||||
finish(&mut app, event, start + Vector::new(50., 0.));
|
||||
assert_eq!(app.canvas_epoch, epoch);
|
||||
assert_eq!(app.pending_scenario_reveal_visit, visit);
|
||||
assert!(app.pending_diagram_reveal.is_some());
|
||||
assert_eq!(app.selected, selected);
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_active_actions_cannot_remove_new_same_visit_deferred_reveal() {
|
||||
let (mut app, lane, message) = setup();
|
||||
let old = app.scenario_context().unwrap();
|
||||
let behavior::scenario_layout::Representation::Saved { diagram } = old.representation else {
|
||||
unreachable!()
|
||||
};
|
||||
let accepted = app.document.snapshot();
|
||||
let source = app.source_workspace.bundle();
|
||||
let _ = app.update(Message::RevealInDiagram(diagram, message));
|
||||
let current = app.scenario_context().unwrap();
|
||||
assert_eq!(current.visit, old.visit);
|
||||
assert_eq!(current.representation, old.representation);
|
||||
assert_eq!(current.revision, old.revision);
|
||||
assert_ne!(current.epoch, old.epoch);
|
||||
let pending = app.pending_diagram_reveal.clone();
|
||||
assert!(pending.is_some());
|
||||
let focus = app.diagram_navigation_focus.as_ref().unwrap();
|
||||
let focus = (focus.context, focus.usage.clone(), focus.selected);
|
||||
let camera = app.camera_boundary();
|
||||
for event in [
|
||||
CanvasEvent::Representation(old, old.representation),
|
||||
CanvasEvent::Shelf(old, behavior::scenario::Shelf::Selection),
|
||||
CanvasEvent::Select(old, lane),
|
||||
CanvasEvent::Zoom(old, Some(1.)),
|
||||
] {
|
||||
let _ = app.update(Message::ScenarioCanvas(event));
|
||||
assert_eq!(app.scenario_context(), Some(current));
|
||||
assert_eq!(app.pending_diagram_reveal, pending);
|
||||
assert_eq!(app.pending_scenario_reveal_visit, Some(current.visit));
|
||||
let actual = app.diagram_navigation_focus.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
(actual.context, actual.usage.clone(), actual.selected),
|
||||
focus
|
||||
);
|
||||
assert!(app.camera_boundary() == camera);
|
||||
assert_eq!(app.selected, message);
|
||||
assert_eq!(app.document.bundle(), &accepted.bundle);
|
||||
assert_eq!(app.project(), &accepted.decoded.project);
|
||||
assert_eq!(app.source_workspace.bundle(), source);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Viewport(
|
||||
current,
|
||||
Size::new(800., 500.),
|
||||
)));
|
||||
assert!(app.pending_diagram_reveal.is_none());
|
||||
assert!(app.pending_scenario_reveal_visit.is_none());
|
||||
assert!(
|
||||
app.diagram_focus(crate::diagram_usage::Surface::Saved(diagram))
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(app.selected, message);
|
||||
assert_eq!(app.document.bundle(), &accepted.bundle);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modal_open_cancels_preview_and_captured_begin_stays_retired_after_close() {
|
||||
let (mut app, lane, _) = setup();
|
||||
let original = app.document.snapshot();
|
||||
let camera = app.behavior.scenario.camera_boundary();
|
||||
let (event, start, _) = begin(&mut app, Target::Lane(lane));
|
||||
move_to(&mut app, event, start + Vector::new(30., 0.));
|
||||
let _ = app.update(Message::Delete);
|
||||
assert!(app.delete_pending);
|
||||
assert!(app.behavior.scenario.spacing_token().is_none());
|
||||
finish(&mut app, event, start + Vector::new(30., 0.));
|
||||
let _ = app.update(Message::CancelDelete);
|
||||
send(&mut app, event);
|
||||
assert!(app.behavior.scenario.spacing_token().is_none());
|
||||
assert_eq!(app.project(), &original.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &original.bundle);
|
||||
assert!(camera == app.behavior.scenario.camera_boundary());
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Controller acceptance: one indentation gesture is one draft transaction.
|
||||
use super::*;
|
||||
|
||||
fn fixture(source: &str) -> App {
|
||||
let mut app = App::with_project(Project::empty());
|
||||
app.page = Page::Text;
|
||||
app.source_workspace = Workspace::new(
|
||||
&oa_core::source_project::SourceBundle {
|
||||
entry: "project.arcadia".into(),
|
||||
files: std::collections::BTreeMap::from([("project.arcadia".into(), source.into())]),
|
||||
},
|
||||
true,
|
||||
);
|
||||
app.show_source_file(false);
|
||||
app
|
||||
}
|
||||
fn indent(app: &mut App, outdent: bool) {
|
||||
let message = Message::SourceIndent(app.source_symbol_context(), outdent);
|
||||
let _ = app.update(message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indentation_updates_draft_snapshot_version_and_single_undo_redo_without_model_change() {
|
||||
let source = "雨\r\n🚀\r\n";
|
||||
let mut app = fixture(source);
|
||||
app.source_editor.perform(text_editor::Action::SelectAll);
|
||||
let version = app.source_version;
|
||||
let revision = app.source_workspace.revision();
|
||||
let model = app.document.revision();
|
||||
indent(&mut app, false);
|
||||
let after = " 雨\r\n 🚀\r\n";
|
||||
assert_eq!(app.source_editor.text(), after);
|
||||
assert_eq!(app.source_snapshot.as_ref(), after);
|
||||
assert_eq!(app.source_workspace.files["project.arcadia"].text, after);
|
||||
assert!(app.source_workspace.has_edits());
|
||||
assert_eq!(app.source_version, version + 1);
|
||||
assert_eq!(app.source_workspace.revision(), revision + 1);
|
||||
assert_eq!(app.document.revision(), model);
|
||||
let _ = app.update(Message::SourceUndo);
|
||||
assert_eq!(app.source_editor.text(), source);
|
||||
assert!(!app.source_workspace.has_edits());
|
||||
let _ = app.update(Message::SourceRedo);
|
||||
assert_eq!(app.source_editor.text(), after);
|
||||
assert_eq!(app.document.revision(), model);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_hidden_and_modal_indentation_is_rejected_before_navigation_invalidation() {
|
||||
for rejected in 0..7 {
|
||||
let mut app = fixture("alpha");
|
||||
let mut context = app.source_symbol_context();
|
||||
match rejected {
|
||||
0 => context.path = "elsewhere.arcadia".into(),
|
||||
1 => context.session = Id::new_v4(),
|
||||
2 => app.page = Page::Home,
|
||||
3 => app.busy = true,
|
||||
4 => app.delete_pending = true,
|
||||
5 => app.hosted.visible = true,
|
||||
_ => app.pending = Some(Pending::New),
|
||||
}
|
||||
let interaction = app.source_symbols.interaction;
|
||||
let version = app.source_version;
|
||||
let _ = app.update(Message::SourceIndent(context, false));
|
||||
assert_eq!(app.source_editor.text(), "alpha");
|
||||
assert_eq!(app.source_version, version);
|
||||
assert_eq!(app.source_symbols.interaction, interaction);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_op_outdent_does_not_add_history_or_increment_source_version() {
|
||||
let mut app = fixture("alpha");
|
||||
let version = app.source_version;
|
||||
indent(&mut app, true);
|
||||
assert_eq!(app.source_version, version);
|
||||
assert!(!app.source_workspace.undo(false));
|
||||
}
|
||||
@@ -754,76 +754,7 @@ fn invalid_open_retains_accepted_document_but_refuses_alias_rename() {
|
||||
}
|
||||
|
||||
fn captured_escape(app: &App) -> Vec<Message> {
|
||||
use iced::advanced::{Layout, Shell, layout, subscription, widget};
|
||||
use iced::futures::{StreamExt, stream, task::noop_waker_ref};
|
||||
use iced::keyboard::{self, key::Named};
|
||||
use std::task::{Context as PollContext, Poll};
|
||||
let mut input: iced::Element<'_, (), iced::Theme, ()> =
|
||||
iced::widget::text_input("Source alias", "retained_alias")
|
||||
.on_input(|_| ())
|
||||
.into();
|
||||
let mut tree = widget::Tree::new(input.as_widget());
|
||||
let size = iced::Size::new(300., 40.);
|
||||
let node =
|
||||
input
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree, &(), &layout::Limits::new(iced::Size::ZERO, size));
|
||||
tree.state
|
||||
.downcast_mut::<iced::widget::text_input::State<()>>()
|
||||
.focus();
|
||||
let event = iced::Event::Keyboard(keyboard::Event::KeyPressed {
|
||||
key: keyboard::Key::Named(Named::Escape),
|
||||
modified_key: keyboard::Key::Named(Named::Escape),
|
||||
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::Escape),
|
||||
location: keyboard::Location::Standard,
|
||||
modifiers: keyboard::Modifiers::empty(),
|
||||
text: None,
|
||||
repeat: false,
|
||||
});
|
||||
let mut widget_messages = Vec::new();
|
||||
let mut shell = Shell::new(&mut widget_messages);
|
||||
input.as_widget_mut().update(
|
||||
&mut tree,
|
||||
&event,
|
||||
Layout::new(&node),
|
||||
iced::mouse::Cursor::Unavailable,
|
||||
&(),
|
||||
&mut iced::advanced::clipboard::Null,
|
||||
&mut shell,
|
||||
&iced::Rectangle::new(iced::Point::ORIGIN, size),
|
||||
);
|
||||
assert!(shell.is_event_captured());
|
||||
let event = subscription::Event::Interaction {
|
||||
window: iced::window::Id::unique(),
|
||||
event,
|
||||
status: iced::event::Status::Captured,
|
||||
};
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
let _entered = runtime.enter();
|
||||
let mut messages = Vec::new();
|
||||
let mut keyboard_boundaries = 0;
|
||||
for recipe in subscription::into_recipes(app.subscription()) {
|
||||
let mut output = recipe.stream(Box::pin(stream::iter([event.clone()])));
|
||||
let mut context = PollContext::from_waker(noop_waker_ref());
|
||||
while let Poll::Ready(Some(message)) = output.poll_next_unpin(&mut context) {
|
||||
if matches!(
|
||||
&message,
|
||||
Message::WorkDrag(crate::app::allocation_drag::Event::KeyboardBoundary)
|
||||
) {
|
||||
keyboard_boundaries += 1;
|
||||
} else {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
keyboard_boundaries, 1,
|
||||
"each key has exactly one passive allocation notification"
|
||||
);
|
||||
messages
|
||||
crate::app::escape::tests::focused_input_messages(app)
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -33,6 +33,9 @@ fn admission_notice(error: query::AdmissionError) -> String {
|
||||
impl App {
|
||||
pub(super) fn source_input_envelope(&self, message: &Message) -> bool {
|
||||
match message {
|
||||
Message::SourceIndent(context, _) => {
|
||||
context == &self.source_symbol_context() && self.source_navigation_available()
|
||||
}
|
||||
Message::SourceSymbols(context, event) => {
|
||||
context.session == self.source_workspace.session()
|
||||
&& context.path == self.source_workspace.active
|
||||
|
||||
@@ -864,99 +864,11 @@ fn captured_input_subscription_messages(app: &App) -> Vec<Message> {
|
||||
}
|
||||
|
||||
fn input_subscription_messages(app: &App, focused: bool) -> Vec<Message> {
|
||||
use iced::advanced::{Layout, Shell, layout, subscription, widget};
|
||||
use iced::futures::{StreamExt, stream, task::noop_waker_ref};
|
||||
use iced::keyboard::{self, key::Named};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
let mut input: iced::Element<'_, (), iced::Theme, ()> =
|
||||
iced::widget::text_input("Find / modal input", "Retain exact text 雨")
|
||||
.on_input(|_| ())
|
||||
.into();
|
||||
let mut tree = widget::Tree::new(input.as_widget());
|
||||
let size = iced::Size::new(300., 40.);
|
||||
let node =
|
||||
input
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree, &(), &layout::Limits::new(iced::Size::ZERO, size));
|
||||
if focused {
|
||||
tree.state
|
||||
.downcast_mut::<iced::widget::text_input::State<()>>()
|
||||
.focus();
|
||||
}
|
||||
let event = iced::Event::Keyboard(keyboard::Event::KeyPressed {
|
||||
key: keyboard::Key::Named(Named::Escape),
|
||||
modified_key: keyboard::Key::Named(Named::Escape),
|
||||
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::Escape),
|
||||
location: keyboard::Location::Standard,
|
||||
modifiers: keyboard::Modifiers::empty(),
|
||||
text: None,
|
||||
repeat: false,
|
||||
});
|
||||
let mut input_messages = Vec::new();
|
||||
let mut shell = Shell::new(&mut input_messages);
|
||||
input.as_widget_mut().update(
|
||||
&mut tree,
|
||||
&event,
|
||||
Layout::new(&node),
|
||||
iced::mouse::Cursor::Unavailable,
|
||||
&(),
|
||||
&mut iced::advanced::clipboard::Null,
|
||||
&mut shell,
|
||||
&iced::Rectangle::new(iced::Point::ORIGIN, size),
|
||||
);
|
||||
let captured = shell.is_event_captured();
|
||||
assert_eq!(captured, focused);
|
||||
assert!(input_messages.is_empty());
|
||||
assert!(
|
||||
!tree
|
||||
.state
|
||||
.downcast_ref::<iced::widget::text_input::State<()>>()
|
||||
.is_focused()
|
||||
);
|
||||
let event = subscription::Event::Interaction {
|
||||
window: iced::window::Id::unique(),
|
||||
event,
|
||||
status: if captured {
|
||||
iced::event::Status::Captured
|
||||
} else {
|
||||
iced::event::Status::Ignored
|
||||
},
|
||||
};
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
let _entered = runtime.enter();
|
||||
let mut messages = Vec::new();
|
||||
let mut keyboard_boundaries = 0;
|
||||
for recipe in subscription::into_recipes(app.subscription()) {
|
||||
let mut output = recipe.stream(Box::pin(stream::iter([event.clone()])));
|
||||
let mut context = Context::from_waker(noop_waker_ref());
|
||||
while let Poll::Ready(Some(message)) = output.poll_next_unpin(&mut context) {
|
||||
assert!(
|
||||
!matches!(message, Message::CheckpointTick),
|
||||
"timer must remain pending"
|
||||
);
|
||||
if matches!(
|
||||
&message,
|
||||
Message::WorkDrag(crate::app::allocation_drag::Event::KeyboardBoundary)
|
||||
) {
|
||||
keyboard_boundaries += 1;
|
||||
} else {
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
keyboard_boundaries, 1,
|
||||
"each key has exactly one passive allocation notification"
|
||||
);
|
||||
messages
|
||||
crate::app::escape::tests::input_messages(app, iced::keyboard::key::Named::Escape, focused)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_find_and_modal_escape_use_one_actual_subscription_and_preserve_pending_work() {
|
||||
fn captured_find_and_modal_escape_use_one_actual_delivery_and_preserve_pending_work() {
|
||||
for pending in [false, true] {
|
||||
for modal in 0..4 {
|
||||
let mut app = fixture();
|
||||
@@ -1053,7 +965,7 @@ fn captured_find_and_modal_escape_use_one_actual_subscription_and_preserve_pendi
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_subscription_does_not_duplicate_existing_behavior_or_architecture_routes() {
|
||||
fn captured_delivery_does_not_duplicate_existing_behavior_or_architecture_routes() {
|
||||
let mut app = fixture();
|
||||
app.text_workspace.show_drawer(Some(DrawerTab::References));
|
||||
let project = app.project().clone();
|
||||
|
||||
@@ -53,7 +53,10 @@ async fn armed() -> (App, Mounted, Id) {
|
||||
context,
|
||||
object: relation,
|
||||
placement: None,
|
||||
selection_target: None,
|
||||
anchor: iced::Point::new(450., 400.),
|
||||
bend: None,
|
||||
route_segment: None,
|
||||
},
|
||||
);
|
||||
mounted.settle(&mut app).await;
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn state_bend_delayed_commit_after_same_view_selection_is_inert_and_live_commit_works() {
|
||||
let (mut app, _, relation, _) = setup();
|
||||
let context = app.state_context().unwrap();
|
||||
let next = app.project().relations[&relation].target();
|
||||
let waypoints = vec![Position { x: 715., y: -425. }];
|
||||
let delayed = Event::SetBends {
|
||||
context,
|
||||
relation,
|
||||
waypoints: waypoints.clone(),
|
||||
};
|
||||
send(&mut app, Message::Select(next));
|
||||
assert_eq!(app.selected, next);
|
||||
assert_eq!(
|
||||
app.state_context(),
|
||||
Some(context),
|
||||
"same-view selection does not retire the context stamp"
|
||||
);
|
||||
let before = app.document.snapshot();
|
||||
let camera = (
|
||||
app.behavior.diagram.zoom,
|
||||
app.behavior.diagram.pan,
|
||||
app.behavior.diagram.fit,
|
||||
);
|
||||
event(&mut app, delayed);
|
||||
assert_eq!(app.selected, next);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
assert_eq!(
|
||||
(
|
||||
app.behavior.diagram.zoom,
|
||||
app.behavior.diagram.pan,
|
||||
app.behavior.diagram.fit
|
||||
),
|
||||
camera
|
||||
);
|
||||
send(&mut app, Message::Select(relation));
|
||||
let context = app.state_context().unwrap();
|
||||
event(
|
||||
&mut app,
|
||||
Event::SetBends {
|
||||
context,
|
||||
relation,
|
||||
waypoints: waypoints.clone(),
|
||||
},
|
||||
);
|
||||
let mut expected = before.decoded.project.clone();
|
||||
let route = expected
|
||||
.diagrams
|
||||
.get_mut(&context.diagram)
|
||||
.unwrap()
|
||||
.routes
|
||||
.iter_mut()
|
||||
.find(|route| route.edge == relation)
|
||||
.unwrap();
|
||||
route.waypoints = waypoints;
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_source_model_agree(&app);
|
||||
send(&mut app, Message::Undo);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(
|
||||
!app.document.can_undo(),
|
||||
"live drag remains a single transaction"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_bend_menu_carries_exact_segment_and_pin_without_changing_delete_action() {
|
||||
let (mut app, _, relation, _) = setup();
|
||||
let context = app.state_context().unwrap();
|
||||
let point = Position { x: 500., y: -400. };
|
||||
event(
|
||||
&mut app,
|
||||
Event::ContextMenu {
|
||||
context,
|
||||
object: relation,
|
||||
placement: None,
|
||||
selection_target: None,
|
||||
anchor: iced::Point::ORIGIN,
|
||||
bend: Some(1),
|
||||
route_segment: Some((2, point)),
|
||||
},
|
||||
);
|
||||
let menu = crate::model_menu::popup(&app).unwrap();
|
||||
let mut add = false;
|
||||
let mut remove = false;
|
||||
let mut delete = false;
|
||||
for entry in menu.entries {
|
||||
if let crate::context_menu::Entry::Action {
|
||||
message: Some(Message::Menu(crate::model_menu::Event::Invoke(_, message))),
|
||||
..
|
||||
} = entry
|
||||
{
|
||||
match *message {
|
||||
Message::StateDiagram(Event::AddBend {
|
||||
relation: id,
|
||||
segment: Some((2, at)),
|
||||
..
|
||||
}) => {
|
||||
assert_eq!(id, relation);
|
||||
assert_eq!(at, point);
|
||||
add = true;
|
||||
}
|
||||
Message::StateDiagram(Event::RemoveBend {
|
||||
relation: id,
|
||||
index: 1,
|
||||
..
|
||||
}) => {
|
||||
assert_eq!(id, relation);
|
||||
remove = true;
|
||||
}
|
||||
Message::Delete => delete = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(add && remove && delete);
|
||||
}
|
||||
|
||||
fn setup() -> (App, Id, Id, Id) {
|
||||
let mut f = fixture();
|
||||
let diagram = create_view(&mut f).diagram;
|
||||
let mut project = f.app.project().clone();
|
||||
let relation = project.relate(RelationKind::StateTransition, "Bend trial", f.leaf, f.b);
|
||||
let second = state_edit::create_view(&project, f.machine).unwrap();
|
||||
project = prepare_command(&project, &second.command).unwrap().project;
|
||||
project
|
||||
.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.routes
|
||||
.push(EdgeRoute {
|
||||
edge: relation,
|
||||
waypoints: vec![
|
||||
Position { x: 650., y: -400. },
|
||||
Position { x: 300., y: -400. },
|
||||
Position { x: 650., y: -400. },
|
||||
],
|
||||
label: Some(EdgeLabel {
|
||||
fraction: 0.35,
|
||||
offset: Position { x: 9., y: -23. },
|
||||
}),
|
||||
source_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Top,
|
||||
offset: 0.234567,
|
||||
}),
|
||||
target_attachment: Some(EdgeAttachment {
|
||||
side: PortAnchorSide::Bottom,
|
||||
offset: 0.75,
|
||||
}),
|
||||
});
|
||||
let mut app = App::with_project(project);
|
||||
send(&mut app, Message::RevealInDiagram(diagram, relation));
|
||||
(app, diagram, relation, f.a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_bend_commands_preserve_other_fields_views_and_exact_history() {
|
||||
let (mut app, diagram, relation, _) = setup();
|
||||
let baseline = app.document.snapshot();
|
||||
let points = vec![Position { x: 715., y: 425. }];
|
||||
let mut expected = app.project().clone();
|
||||
expected.diagrams.get_mut(&diagram).unwrap().routes[0].waypoints = points.clone();
|
||||
let context = app.state_context().unwrap();
|
||||
event(
|
||||
&mut app,
|
||||
Event::SetBends {
|
||||
context,
|
||||
relation,
|
||||
waypoints: points.clone(),
|
||||
},
|
||||
);
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_source_model_agree(&app);
|
||||
let changed = app.document.snapshot();
|
||||
let context = app.state_context().unwrap();
|
||||
event(
|
||||
&mut app,
|
||||
Event::SetBends {
|
||||
context,
|
||||
relation,
|
||||
waypoints: points,
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
Arc::ptr_eq(&changed, &app.document.snapshot()),
|
||||
"equal bends must not add history"
|
||||
);
|
||||
send(&mut app, Message::Undo);
|
||||
assert_eq!(app.project(), &baseline.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &baseline.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
send(&mut app, Message::Redo);
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_eq!(app.document.bundle(), &changed.bundle);
|
||||
let context = app.state_context().unwrap();
|
||||
event(&mut app, Event::ClearBends { context, relation });
|
||||
expected.diagrams.get_mut(&diagram).unwrap().routes[0]
|
||||
.waypoints
|
||||
.clear();
|
||||
assert_eq!(app.project(), &expected);
|
||||
let cleared = app.document.snapshot();
|
||||
let context = app.state_context().unwrap();
|
||||
event(&mut app, Event::ClearBends { context, relation });
|
||||
assert!(Arc::ptr_eq(&cleared, &app.document.snapshot()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_bend_self_loop_add_move_remove_clear_preserves_project_and_source_history() {
|
||||
let (app, diagram, relation, _) = setup();
|
||||
let mut project = app.project().clone();
|
||||
let RelationBody::StateTransition { source, target, .. } =
|
||||
&mut project.relations.get_mut(&relation).unwrap().body
|
||||
else {
|
||||
panic!("State transition fixture")
|
||||
};
|
||||
*target = *source;
|
||||
project.diagrams.get_mut(&diagram).unwrap().routes[0]
|
||||
.waypoints
|
||||
.clear();
|
||||
oa_core::validate_candidate(&project).unwrap();
|
||||
let mut app = App::with_project(project);
|
||||
send(&mut app, Message::RevealInDiagram(diagram, relation));
|
||||
let baseline = app.document.snapshot();
|
||||
let geometry = state_edit::bend_route(app.project(), diagram, relation).unwrap();
|
||||
assert!(!geometry.custom_suspended);
|
||||
assert!(geometry.pins.is_empty());
|
||||
assert!(
|
||||
geometry.points.len() >= 4,
|
||||
"actual external self-loop routing"
|
||||
);
|
||||
let segment = 1;
|
||||
let point = Position {
|
||||
x: (geometry.points[segment].x + geometry.points[segment + 1].x) / 2.,
|
||||
y: (geometry.points[segment].y + geometry.points[segment + 1].y) / 2.,
|
||||
};
|
||||
|
||||
// Each operation must alter only the complete Project's waypoint list;
|
||||
// Undo and Redo must restore exact serialized source, not just geometry.
|
||||
fn check(app: &mut App, diagram: Id, mutation: Event, points: Vec<Position>) {
|
||||
let before = app.document.snapshot();
|
||||
let mut expected = before.decoded.project.clone();
|
||||
expected.diagrams.get_mut(&diagram).unwrap().routes[0].waypoints = points;
|
||||
event(app, mutation);
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_source_model_agree(app);
|
||||
let after = app.document.snapshot();
|
||||
assert_ne!(after.bundle, before.bundle);
|
||||
send(app, Message::Undo);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
send(app, Message::Redo);
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_eq!(app.document.bundle(), &after.bundle);
|
||||
assert_source_model_agree(app);
|
||||
}
|
||||
|
||||
let context = app.state_context().unwrap();
|
||||
check(
|
||||
&mut app,
|
||||
diagram,
|
||||
Event::AddBend {
|
||||
context,
|
||||
relation,
|
||||
segment: Some((segment, point)),
|
||||
},
|
||||
vec![point],
|
||||
);
|
||||
let moved = Position {
|
||||
x: point.x + 45.,
|
||||
y: point.y - 35.,
|
||||
};
|
||||
let context = app.state_context().unwrap();
|
||||
check(
|
||||
&mut app,
|
||||
diagram,
|
||||
Event::SetBends {
|
||||
context,
|
||||
relation,
|
||||
waypoints: vec![moved],
|
||||
},
|
||||
vec![moved],
|
||||
);
|
||||
let context = app.state_context().unwrap();
|
||||
check(
|
||||
&mut app,
|
||||
diagram,
|
||||
Event::RemoveBend {
|
||||
context,
|
||||
relation,
|
||||
index: 0,
|
||||
},
|
||||
vec![],
|
||||
);
|
||||
assert_eq!(app.project(), &baseline.decoded.project);
|
||||
send(&mut app, Message::Undo);
|
||||
let context = app.state_context().unwrap();
|
||||
check(
|
||||
&mut app,
|
||||
diagram,
|
||||
Event::ClearBends { context, relation },
|
||||
vec![],
|
||||
);
|
||||
assert_eq!(app.project(), &baseline.decoded.project);
|
||||
assert_source_model_agree(&app);
|
||||
// Clear is a new source-preserving edit and may retain empty-list trivia.
|
||||
// Exact original bytes are restored by history, not by reauthoring a value.
|
||||
for _ in 0..3 {
|
||||
assert!(app.document.can_undo());
|
||||
send(&mut app, Message::Undo);
|
||||
}
|
||||
assert_eq!(app.project(), &baseline.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &baseline.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_bend_insertion_uses_captured_traversal_segment_and_removal_only_changes_pins() {
|
||||
let (app, diagram, relation, _) = setup();
|
||||
let context = app.state_context().unwrap();
|
||||
let p = app.project();
|
||||
let geometry = state_edit::bend_route(p, diagram, relation).unwrap();
|
||||
let original = &p.diagrams[&diagram].routes[0];
|
||||
let reverse = geometry
|
||||
.points
|
||||
.windows(2)
|
||||
.position(|pair| pair[0] == original.waypoints[0] && pair[1] == original.waypoints[1])
|
||||
.unwrap();
|
||||
for (segment, expected_index) in [(reverse, 1), (reverse + 1, 2)] {
|
||||
let point = Position { x: 500., y: -400. };
|
||||
let planned = state_edit::plan(
|
||||
p,
|
||||
context,
|
||||
&Event::AddBend {
|
||||
context,
|
||||
relation,
|
||||
segment: Some((segment, point)),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let actual = prepare_command(p, &planned.command).unwrap().project;
|
||||
let mut expected = p.clone();
|
||||
expected.diagrams.get_mut(&diagram).unwrap().routes[0]
|
||||
.waypoints
|
||||
.insert(expected_index, point);
|
||||
assert_eq!(actual, expected);
|
||||
let removed = state_edit::plan(
|
||||
&actual,
|
||||
context,
|
||||
&Event::RemoveBend {
|
||||
context,
|
||||
relation,
|
||||
index: expected_index,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
prepare_command(&actual, &removed.command).unwrap().project,
|
||||
*p
|
||||
);
|
||||
}
|
||||
let default = state_edit::plan(
|
||||
p,
|
||||
context,
|
||||
&Event::AddBend {
|
||||
context,
|
||||
relation,
|
||||
segment: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let Command::SetEdgeRoute { route, .. } = default.command else {
|
||||
panic!("route command")
|
||||
};
|
||||
assert_eq!(route.waypoints.len(), original.waypoints.len() + 1);
|
||||
assert_eq!(route.source_attachment, original.source_attachment);
|
||||
assert_eq!(route.target_attachment, original.target_attachment);
|
||||
assert_eq!(route.label, original.label);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_bend_stale_nonfinite_capacity_hidden_and_folded_requests_are_inert() {
|
||||
let (mut app, diagram, relation, composite) = setup();
|
||||
let context = app.state_context().unwrap();
|
||||
let baseline = app.document.snapshot();
|
||||
for mutation in [
|
||||
Event::SetBends {
|
||||
context: Context {
|
||||
epoch: context.epoch + 1,
|
||||
..context
|
||||
},
|
||||
relation,
|
||||
waypoints: vec![],
|
||||
},
|
||||
Event::SetBends {
|
||||
context,
|
||||
relation,
|
||||
waypoints: vec![Position { x: f32::NAN, y: 0. }],
|
||||
},
|
||||
Event::SetBends {
|
||||
context,
|
||||
relation,
|
||||
waypoints: vec![Position { x: 0., y: 0. }; 129],
|
||||
},
|
||||
Event::AddBend {
|
||||
context,
|
||||
relation,
|
||||
segment: Some((usize::MAX, Position { x: 0., y: 0. })),
|
||||
},
|
||||
Event::RemoveBend {
|
||||
context,
|
||||
relation,
|
||||
index: usize::MAX,
|
||||
},
|
||||
] {
|
||||
event(&mut app, mutation);
|
||||
assert!(Arc::ptr_eq(&baseline, &app.document.snapshot()));
|
||||
}
|
||||
let mut p = app.project().clone();
|
||||
p.diagrams.get_mut(&diagram).unwrap().routes[0].waypoints =
|
||||
vec![Position { x: 500., y: -400. }; 128];
|
||||
assert!(
|
||||
state_edit::plan(
|
||||
&p,
|
||||
context,
|
||||
&Event::AddBend {
|
||||
context,
|
||||
relation,
|
||||
segment: Some((1, Position { x: 500., y: -400. }))
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let mut hidden = app.project().clone();
|
||||
hidden
|
||||
.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.view_options
|
||||
.hidden_edges
|
||||
.push(relation);
|
||||
assert!(state_edit::bend_route(&hidden, diagram, relation).is_none());
|
||||
assert!(state_edit::plan(&hidden, context, &Event::ClearBends { context, relation }).is_err());
|
||||
let owner = node(&app, diagram, composite);
|
||||
let mut folded = app.project().clone();
|
||||
folded
|
||||
.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&owner)
|
||||
.unwrap()
|
||||
.collapsed = true;
|
||||
assert!(state_edit::bend_route(&folded, diagram, relation).is_none());
|
||||
assert!(state_edit::plan(&folded, context, &Event::ClearBends { context, relation }).is_err());
|
||||
let mut internal = app.project().clone();
|
||||
internal.diagrams.get_mut(&diagram).unwrap().routes.clear();
|
||||
if let RelationBody::StateTransition {
|
||||
source,
|
||||
target,
|
||||
transition_kind,
|
||||
..
|
||||
} = &mut internal.relations.get_mut(&relation).unwrap().body
|
||||
{
|
||||
*target = *source;
|
||||
*transition_kind = TransitionKind::Internal;
|
||||
}
|
||||
assert!(state_edit::bend_route(&internal, diagram, relation).is_none());
|
||||
send(
|
||||
&mut app,
|
||||
Message::Field("/name".into(), "Unapplied bend owner name".into()),
|
||||
);
|
||||
let draft = app.draft.as_ref().unwrap().value.clone();
|
||||
event(&mut app, Event::ClearBends { context, relation });
|
||||
assert!(Arc::ptr_eq(&baseline, &app.document.snapshot()));
|
||||
assert_eq!(app.draft.as_ref().unwrap().value, draft);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ impl App {
|
||||
if self.behavior.has_pending() {
|
||||
return;
|
||||
}
|
||||
self.behavior.scenario.forget_view();
|
||||
self.layer = layer;
|
||||
self.page = Page::Behavior;
|
||||
self.behavior.active_owner = Some(machine);
|
||||
@@ -114,6 +115,7 @@ impl App {
|
||||
}
|
||||
}
|
||||
match event {
|
||||
Event::Selection(event) => self.multiselect_event(event),
|
||||
Event::Remove(intent) => self.remove_from_diagram(intent),
|
||||
Event::Viewport(_, size) => {
|
||||
if size.width.is_finite()
|
||||
@@ -156,11 +158,17 @@ impl App {
|
||||
context,
|
||||
object,
|
||||
placement,
|
||||
selection_target,
|
||||
anchor,
|
||||
bend,
|
||||
route_segment,
|
||||
} => {
|
||||
let mut request = crate::model_menu::Request::object(object, anchor);
|
||||
request.canvas = Some(context);
|
||||
request.placement = placement;
|
||||
request.selection_target = selection_target.map(Box::new);
|
||||
request.bend = bend;
|
||||
request.route_segment = route_segment;
|
||||
return self.handle(Message::Menu(crate::model_menu::Event::Open(request)));
|
||||
}
|
||||
Event::EditTransition(_, id) => {
|
||||
@@ -228,6 +236,11 @@ impl App {
|
||||
let Some(context) = self.state_context() else {
|
||||
return Task::none();
|
||||
};
|
||||
if let Event::SetBends { relation, .. } = &mutation
|
||||
&& *relation != self.selected
|
||||
{
|
||||
return Task::none();
|
||||
}
|
||||
if let Event::SetAttachment {
|
||||
relation,
|
||||
end,
|
||||
@@ -246,6 +259,14 @@ impl App {
|
||||
}
|
||||
match state_edit::plan(self.project(), context, &mutation) {
|
||||
Ok(plan) => {
|
||||
if let Command::SetEdgeRoute { diagram, route } = &plan.command
|
||||
&& crate::route_edit::stored_route(
|
||||
&self.project().diagrams[diagram],
|
||||
route.edge,
|
||||
) == *route
|
||||
{
|
||||
return Task::none();
|
||||
}
|
||||
if self.execute(plan.command) {
|
||||
self.behavior.diagram.diagram = Some(plan.diagram);
|
||||
self.behavior.diagram.placement = plan.placement;
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
use super::*;
|
||||
#[path = "state_attachment_escape_tests.rs"]
|
||||
mod attachment_escape;
|
||||
#[path = "state_bend_tests.rs"]
|
||||
mod bends;
|
||||
#[path = "state_picker_escape_tests.rs"]
|
||||
mod picker_escape;
|
||||
use crate::behavior::{
|
||||
self,
|
||||
state_edit::{self, Context, Endpoint, Event, Tool},
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
//! State selection layout and modifier admission on the mounted production App.
|
||||
use super::*;
|
||||
use crate::behavior::{
|
||||
canvas_workspace::tests::{Mounted, key},
|
||||
state_edit,
|
||||
};
|
||||
use crate::diagram_usage::Target;
|
||||
use iced::advanced::widget::{Operation, operation};
|
||||
use iced::{Point, Rectangle, Size, Vector, keyboard, mouse};
|
||||
|
||||
struct Fixture {
|
||||
app: App,
|
||||
diagram: Id,
|
||||
a: Id,
|
||||
b: Id,
|
||||
a_element: Id,
|
||||
b_element: Id,
|
||||
edge: Id,
|
||||
action: Id,
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
let mut p = Project::empty();
|
||||
let machine = p
|
||||
.add_element(Kind::StateMachine, Layer::Oa, "Operating modes", None)
|
||||
.unwrap();
|
||||
let region = p
|
||||
.add_element(Kind::Region, Layer::Oa, "Main region", Some(machine))
|
||||
.unwrap();
|
||||
let a_element = p
|
||||
.add_element(Kind::State, Layer::Oa, "First state", Some(region))
|
||||
.unwrap();
|
||||
let b_element = p
|
||||
.add_element(
|
||||
Kind::State,
|
||||
Layer::Oa,
|
||||
&format!("Second state {}", "with a long primary name ".repeat(20)),
|
||||
Some(region),
|
||||
)
|
||||
.unwrap();
|
||||
let work = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "Reusable work", None)
|
||||
.unwrap();
|
||||
let action = p.relate(RelationKind::StateAction, "On entry", a_element, work);
|
||||
let edge = p.relate(
|
||||
RelationKind::StateTransition,
|
||||
"Next state",
|
||||
a_element,
|
||||
b_element,
|
||||
);
|
||||
let diagram = p.ensure_diagram(Layer::Oa);
|
||||
p.diagrams.get_mut(&diagram).unwrap().projection = ProjectionKind::StateMachine { machine };
|
||||
let mut placements = vec![];
|
||||
// All State elements, including machine/Region, are initially placed.
|
||||
// A fixture already missing its containers would not test picker insertion.
|
||||
for (element, x, y, width, height) in [
|
||||
(machine, 0., 0., 800., 500.),
|
||||
(region, 20., 70., 760., 410.),
|
||||
(a_element, 60., 160., 230., 180.),
|
||||
(b_element, 430., 160., 260., 180.),
|
||||
] {
|
||||
let node = p.place(diagram, element, Position { x, y });
|
||||
p.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&node)
|
||||
.unwrap()
|
||||
.size = oa_core::Size { width, height };
|
||||
placements.push(node);
|
||||
}
|
||||
let a = placements[2];
|
||||
let b = placements[3];
|
||||
validate_candidate(&p).unwrap();
|
||||
assert!(state_edit::unplaced(&p, diagram).is_empty());
|
||||
let mut app = App::with_project(p);
|
||||
app.page = Page::Behavior;
|
||||
app.layer = Layer::Oa;
|
||||
app.behavior.active_owner = Some(machine);
|
||||
app.behavior.diagram = crate::behavior::state_view::State {
|
||||
diagram: Some(diagram),
|
||||
fit: true,
|
||||
..Default::default()
|
||||
};
|
||||
app.selected = diagram;
|
||||
app.selected_node = None;
|
||||
app.window_size = Size::new(1442., 932.);
|
||||
app.refresh_draft();
|
||||
app.reconcile_multiselect();
|
||||
assert_eq!(app.state_context().unwrap().diagram, diagram);
|
||||
Fixture {
|
||||
app,
|
||||
diagram,
|
||||
a,
|
||||
b,
|
||||
a_element,
|
||||
b_element,
|
||||
edge,
|
||||
action,
|
||||
}
|
||||
}
|
||||
|
||||
fn owner(mounted: &mut Mounted, app: &App) -> (Rectangle, bool) {
|
||||
let geometry = mounted.geometry(app);
|
||||
let (_, bounds, focused) = geometry
|
||||
.focused
|
||||
.into_iter()
|
||||
.find(|(id, _, _)| {
|
||||
id.as_ref() == Some(&iced::advanced::widget::Id::from("diagram-keyboard-owner"))
|
||||
})
|
||||
.expect("real State focus::Owner rectangle must be measurable");
|
||||
(bounds, focused)
|
||||
}
|
||||
fn camera(app: &App) -> (f32, Vector, bool, Option<Size>) {
|
||||
let state = &app.behavior.diagram;
|
||||
(state.zoom, state.pan, state.fit, state.viewport)
|
||||
}
|
||||
async fn selection(mounted: &mut Mounted, app: &mut App, target: Option<Target>) {
|
||||
let context = app.multiselect_context().unwrap();
|
||||
let event = match target {
|
||||
Some(target) => multiselect::Event::Choose(context, target, multiselect::Choice::Toggle),
|
||||
None => multiselect::Event::Clear(context),
|
||||
};
|
||||
let task = app.update(Message::DiagramSelection(event));
|
||||
mounted.perform(app, task).await;
|
||||
mounted.settle(app).await;
|
||||
}
|
||||
fn node_point(mounted: &mut Mounted, f: &Fixture, placement: Id) -> Point {
|
||||
let bounds = owner(mounted, &f.app).0;
|
||||
let node = &f.app.project().diagrams[&f.diagram].nodes[&placement];
|
||||
let state = &f.app.behavior.diagram;
|
||||
Point::new(
|
||||
bounds.x + (node.position.x + 40.) * state.zoom + state.pan.x,
|
||||
bounds.y + (node.position.y + 25.) * state.zoom + state.pan.y,
|
||||
)
|
||||
}
|
||||
fn modifiers(shift: bool) -> iced::Event {
|
||||
iced::Event::Keyboard(keyboard::Event::ModifiersChanged(if shift {
|
||||
keyboard::Modifiers::SHIFT
|
||||
} else {
|
||||
keyboard::Modifiers::default()
|
||||
}))
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_state_selection_and_missing_picker_never_resize_or_refit_the_canvas() {
|
||||
let mut f = fixture();
|
||||
let mut mounted = Mounted::new(&mut f.app).await;
|
||||
let baseline = f.app.document.snapshot();
|
||||
let bounds = owner(&mut mounted, &f.app).0;
|
||||
let fitted = camera(&f.app);
|
||||
assert!(
|
||||
fitted.2,
|
||||
"keep Fit active to expose any resize-triggered camera jump"
|
||||
);
|
||||
assert!(fitted.3.is_some());
|
||||
assert!(bounds.width > 400. && bounds.height > 200.);
|
||||
assert!(state_edit::unplaced(f.app.project(), f.diagram).is_empty());
|
||||
assert!(f.app.multiselect_snapshot().unwrap().targets().is_empty());
|
||||
for (target, expected) in [
|
||||
(Some(Target::Placement(f.a)), vec![Target::Placement(f.a)]),
|
||||
(
|
||||
Some(Target::Placement(f.b)),
|
||||
vec![Target::Placement(f.a), Target::Placement(f.b)],
|
||||
),
|
||||
(
|
||||
Some(Target::Edge(f.edge)),
|
||||
vec![
|
||||
Target::Placement(f.a),
|
||||
Target::Placement(f.b),
|
||||
Target::Edge(f.edge),
|
||||
],
|
||||
),
|
||||
(
|
||||
Some(Target::Edge(f.edge)),
|
||||
vec![Target::Placement(f.a), Target::Placement(f.b)],
|
||||
),
|
||||
(
|
||||
Some(Target::StateRow {
|
||||
placement: f.a,
|
||||
relation: f.action,
|
||||
}),
|
||||
vec![
|
||||
Target::Placement(f.a),
|
||||
Target::Placement(f.b),
|
||||
Target::StateRow {
|
||||
placement: f.a,
|
||||
relation: f.action,
|
||||
},
|
||||
],
|
||||
),
|
||||
(None, vec![]),
|
||||
] {
|
||||
selection(&mut mounted, &mut f.app, target).await;
|
||||
assert_eq!(f.app.multiselect_snapshot().unwrap().targets(), expected);
|
||||
assert_eq!(
|
||||
owner(&mut mounted, &f.app).0,
|
||||
bounds,
|
||||
"selection strip changed the measured State canvas rectangle"
|
||||
);
|
||||
assert_eq!(
|
||||
camera(&f.app),
|
||||
fitted,
|
||||
"selection feedback silently refitted the camera"
|
||||
);
|
||||
assert_eq!(f.app.project(), &baseline.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &baseline.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
assert!(!f.app.draft_dirty());
|
||||
}
|
||||
selection(&mut mounted, &mut f.app, Some(Target::Placement(f.a))).await;
|
||||
selection(&mut mounted, &mut f.app, Some(Target::Placement(f.b))).await;
|
||||
let captured = f.app.multiselect_snapshot().unwrap();
|
||||
let task = f
|
||||
.app
|
||||
.update(Message::DiagramSelection(multiselect::Event::Hide(
|
||||
captured,
|
||||
)));
|
||||
mounted.perform(&mut f.app, task).await;
|
||||
mounted.settle(&mut f.app).await;
|
||||
let missing: std::collections::BTreeSet<_> = state_edit::unplaced(f.app.project(), f.diagram)
|
||||
.into_iter()
|
||||
.collect();
|
||||
assert_eq!(
|
||||
missing,
|
||||
std::collections::BTreeSet::from([f.a_element, f.b_element])
|
||||
);
|
||||
let mut expected = baseline.decoded.project.clone();
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&f.diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.remove(&f.a);
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&f.diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.remove(&f.b);
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_eq!(
|
||||
owner(&mut mounted, &f.app).0,
|
||||
bounds,
|
||||
"the first unplaced picker changed canvas bounds"
|
||||
);
|
||||
assert_eq!(camera(&f.app), fitted);
|
||||
let hidden_source = f.app.document.bundle().clone();
|
||||
let task = f.app.update(Message::Undo);
|
||||
mounted.perform(&mut f.app, task).await;
|
||||
mounted.settle(&mut f.app).await;
|
||||
assert!(state_edit::unplaced(f.app.project(), f.diagram).is_empty());
|
||||
assert_eq!(f.app.project(), &baseline.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &baseline.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
assert_eq!(
|
||||
owner(&mut mounted, &f.app).0,
|
||||
bounds,
|
||||
"removing the unplaced picker changed canvas bounds"
|
||||
);
|
||||
assert_eq!(camera(&f.app), fitted);
|
||||
let task = f.app.update(Message::Redo);
|
||||
mounted.perform(&mut f.app, task).await;
|
||||
mounted.settle(&mut f.app).await;
|
||||
assert_eq!(f.app.project(), &expected);
|
||||
assert_eq!(f.app.document.bundle(), &hidden_source);
|
||||
assert_eq!(owner(&mut mounted, &f.app).0, bounds);
|
||||
assert_eq!(camera(&f.app), fitted);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_state_shift_held_in_clean_inspector_toggles_on_first_canvas_press() {
|
||||
let mut f = fixture();
|
||||
let mut mounted = Mounted::new(&mut f.app).await;
|
||||
selection(&mut mounted, &mut f.app, Some(Target::Placement(f.a))).await;
|
||||
let field = mounted
|
||||
.geometry(&f.app)
|
||||
.text_inputs
|
||||
.into_iter()
|
||||
.filter(|bounds| bounds.x > f.app.window_size.width - 320.)
|
||||
.min_by(|a, b| a.y.total_cmp(&b.y))
|
||||
.expect("State Inspector field is mounted");
|
||||
mounted.operate(&f.app, &mut FocusField(field));
|
||||
assert!(!owner(&mut mounted, &f.app).1);
|
||||
let before = f.app.document.snapshot();
|
||||
mounted
|
||||
.batch(&mut f.app, &[modifiers(true)], mouse::Cursor::Unavailable)
|
||||
.await;
|
||||
assert!(
|
||||
!owner(&mut mounted, &f.app).1,
|
||||
"passive Shift must not acquire State canvas focus"
|
||||
);
|
||||
let at = node_point(&mut mounted, &f, f.b);
|
||||
let messages = mounted.click(&mut f.app, at).await;
|
||||
assert!(messages.iter().any(|message| matches!(message,
|
||||
Message::DiagramSelection(multiselect::Event::Choose(_, Target::Placement(id), multiselect::Choice::Toggle)) if *id == f.b
|
||||
)), "StateCanvas must map its typed selection event to the common App boundary");
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(f.a), Target::Placement(f.b)]
|
||||
);
|
||||
assert_eq!(f.app.behavior.diagram.placement, Some(f.b));
|
||||
assert_eq!(f.app.selected_node, None);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
assert!(!f.app.draft_dirty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_state_busy_suspension_tracks_shift_without_granting_focus_or_commands() {
|
||||
let mut f = fixture();
|
||||
let mut mounted = Mounted::new(&mut f.app).await;
|
||||
selection(&mut mounted, &mut f.app, Some(Target::Placement(f.a))).await;
|
||||
// Explicitly revoke focus rather than relying on incidental initial focus.
|
||||
mounted.operate(
|
||||
&f.app,
|
||||
&mut FocusField(Rectangle {
|
||||
x: -1000.,
|
||||
y: -1000.,
|
||||
width: 1.,
|
||||
height: 1.,
|
||||
}),
|
||||
);
|
||||
let before = f.app.document.snapshot();
|
||||
let at = node_point(&mut mounted, &f, f.b);
|
||||
f.app.busy = true;
|
||||
mounted.settle(&mut f.app).await;
|
||||
mounted
|
||||
.batch(
|
||||
&mut f.app,
|
||||
&[modifiers(true), key(keyboard::key::Named::Delete)],
|
||||
mouse::Cursor::Unavailable,
|
||||
)
|
||||
.await;
|
||||
mounted.click(&mut f.app, at).await;
|
||||
assert!(!owner(&mut mounted, &f.app).1);
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(f.a)]
|
||||
);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
f.app.busy = false;
|
||||
mounted.settle(&mut f.app).await;
|
||||
assert!(!owner(&mut mounted, &f.app).1);
|
||||
// No second modifier event: the passive suspended update must survive.
|
||||
mounted.click(&mut f.app, at).await;
|
||||
assert_eq!(
|
||||
f.app.multiselect_snapshot().unwrap().targets(),
|
||||
&[Target::Placement(f.a), Target::Placement(f.b)]
|
||||
);
|
||||
assert_eq!(f.app.project(), &before.decoded.project);
|
||||
assert_eq!(f.app.document.bundle(), &before.bundle);
|
||||
assert!(!f.app.document.can_undo());
|
||||
assert!(!f.app.delete_pending);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,104 @@
|
||||
//! The actual State workspace picker, App root and subscriptions.
|
||||
use super::*;
|
||||
use crate::behavior::canvas_workspace::tests::{Mounted, key};
|
||||
use iced::{keyboard::key::Named, mouse};
|
||||
|
||||
async fn press_escape(mounted: &mut Mounted, app: &mut App) -> Vec<Message> {
|
||||
let input = key(Named::Escape);
|
||||
let (mut messages, statuses) = mounted.input_with_status(
|
||||
app,
|
||||
std::slice::from_ref(&input),
|
||||
mouse::Cursor::Unavailable,
|
||||
);
|
||||
assert_eq!(
|
||||
statuses,
|
||||
[iced::event::Status::Captured],
|
||||
"the mounted picker must capture Escape before App subscriptions"
|
||||
);
|
||||
crate::app::escape::tests::subscriptions(app, input, statuses[0], &mut messages);
|
||||
for message in messages.iter().cloned() {
|
||||
let task = app.update(message);
|
||||
mounted.perform(app, task).await;
|
||||
}
|
||||
mounted.settle(app).await;
|
||||
messages
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_state_missing_picker_escape_preserves_exact_document_then_reopens_and_places() {
|
||||
let mut f = fixture();
|
||||
let diagram = create_view(&mut f).diagram;
|
||||
let mut project = f.app.project().clone();
|
||||
project
|
||||
.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.retain(|_, node| node.element != f.b);
|
||||
let mut app = App::with_project(project);
|
||||
app.window_size = iced::Size::new(1800., 1100.);
|
||||
send(&mut app, Message::Select(f.a));
|
||||
send(&mut app, Message::Page(Page::Behavior));
|
||||
let choice = Choice {
|
||||
id: diagram,
|
||||
label: app.project().diagrams[&diagram].name.clone(),
|
||||
};
|
||||
send(&mut app, Message::BehaviorDiagram(choice));
|
||||
let mut mounted = Mounted::new(&mut app).await;
|
||||
assert_eq!(state_edit::unplaced(app.project(), diagram), vec![f.b]);
|
||||
// Locate the stable picker slot itself: selection controls may sit between
|
||||
// it and the canvas. The single menu option opens below this slot.
|
||||
let bounds = mounted.geometry(&app).bounds("state-missing-picker");
|
||||
let picker = bounds.center();
|
||||
let option = iced::Point::new(picker.x, bounds.y + bounds.height * 1.5);
|
||||
let before = app.document.snapshot();
|
||||
let original = app.project().clone();
|
||||
let source = app.document.bundle().clone();
|
||||
let selection = (
|
||||
app.selected,
|
||||
app.selected_node,
|
||||
app.behavior.diagram.placement,
|
||||
);
|
||||
let camera = (
|
||||
app.behavior.diagram.zoom,
|
||||
app.behavior.diagram.pan,
|
||||
app.behavior.diagram.fit,
|
||||
);
|
||||
let revision = app.document.revision();
|
||||
let history = (app.document.can_undo(), app.document.can_redo());
|
||||
mounted.click(&mut app, picker).await;
|
||||
assert!(
|
||||
press_escape(&mut mounted, &mut app).await.is_empty(),
|
||||
"open picker owns Escape, not the State canvas or App"
|
||||
);
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
assert_eq!(app.document.bundle(), &source);
|
||||
assert_eq!(
|
||||
(
|
||||
app.selected,
|
||||
app.selected_node,
|
||||
app.behavior.diagram.placement
|
||||
),
|
||||
selection
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
app.behavior.diagram.zoom,
|
||||
app.behavior.diagram.pan,
|
||||
app.behavior.diagram.fit
|
||||
),
|
||||
camera
|
||||
);
|
||||
assert_eq!(app.document.revision(), revision);
|
||||
assert_eq!((app.document.can_undo(), app.document.can_redo()), history);
|
||||
// If Escape left the menu open this click would close it, and the following
|
||||
// option click would fail to place. This checks actual overlay dismissal.
|
||||
mounted.click(&mut app, picker).await;
|
||||
let messages = mounted.click(&mut app, option).await;
|
||||
assert!(messages.iter().any(|message| matches!(message, Message::StateDiagram(Event::Place { element, .. }) if *element == f.b)));
|
||||
assert!(state_edit::unplaced(app.project(), diagram).is_empty());
|
||||
assert_eq!(app.project().elements, original.elements);
|
||||
assert_eq!(app.project().relations, original.relations);
|
||||
let _ = app.update(Message::Undo);
|
||||
assert_eq!(app.document.bundle(), &source);
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
use super::*;
|
||||
use crate::{context_menu::Entry, model_menu, views::traceability::Filter};
|
||||
|
||||
fn send(app: &mut App, message: Message) {
|
||||
let _ = app.update(message);
|
||||
}
|
||||
|
||||
fn fixture() -> (App, Id, Id, Id, Id) {
|
||||
let mut p = Project::empty();
|
||||
let oa = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "Observe", None)
|
||||
.unwrap();
|
||||
let sa = p
|
||||
.add_element(Kind::Function, Layer::Sa, "Detect", None)
|
||||
.unwrap();
|
||||
let mixed = p.ensure_diagram(Layer::Oa);
|
||||
p.diagrams.get_mut(&mixed).unwrap().projection = ProjectionKind::Traceability;
|
||||
p.place(mixed, oa, Position { x: 300., y: 200. });
|
||||
let system = p.ensure_diagram(Layer::Sa);
|
||||
p.place(system, sa, Position { x: 700., y: 200. });
|
||||
oa_core::validate_candidate(&p).unwrap();
|
||||
let mut app = App::with_project(p);
|
||||
app.page = Page::Diagram;
|
||||
app.layer = Layer::Oa;
|
||||
app.active_diagram = Some(mixed);
|
||||
app.selected = oa;
|
||||
app.refresh_draft();
|
||||
app.traceability.filter = Filter::Artifacts;
|
||||
app.traceability.query = "stale artifact query".into();
|
||||
(app, mixed, system, oa, sa)
|
||||
}
|
||||
|
||||
fn show_action(app: &mut App, element: Id) -> Message {
|
||||
send(app, model_menu::open(element, iced::Point::ORIGIN));
|
||||
model_menu::popup(app)
|
||||
.unwrap()
|
||||
.entries
|
||||
.into_iter()
|
||||
.find_map(|entry| match entry {
|
||||
Entry::Action { label, message, .. } if label == "Show in this diagram" => {
|
||||
Some(message)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("eligible real menu action")
|
||||
.expect("eligible menu action must be enabled")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_layer_traces_resets_inventory_without_applying_property_or_source_drafts() {
|
||||
for source_draft in [false, true] {
|
||||
let (mut app, mixed, _, oa, _) = fixture();
|
||||
if source_draft {
|
||||
send(&mut app, Message::Page(Page::Text));
|
||||
send(
|
||||
&mut app,
|
||||
Message::SourceEdit(iced::widget::text_editor::Action::Edit(
|
||||
iced::widget::text_editor::Edit::Insert('x'),
|
||||
)),
|
||||
);
|
||||
assert!(app.source_dirty());
|
||||
} else {
|
||||
send(
|
||||
&mut app,
|
||||
Message::Field("/alias".into(), "invalid alias".into()),
|
||||
);
|
||||
assert!(app.draft_dirty());
|
||||
}
|
||||
let raw = serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap();
|
||||
let source = app.source_editor.text();
|
||||
let before = app.document.snapshot();
|
||||
let camera = (app.zoom, app.pan);
|
||||
send(&mut app, Message::ReviewLayerTraces);
|
||||
assert_eq!(app.page, Page::Traces);
|
||||
assert_eq!(app.traceability.filter, Filter::Traces);
|
||||
assert!(app.traceability.query.is_empty());
|
||||
assert_eq!(
|
||||
(app.layer, app.active_diagram, app.selected),
|
||||
(Layer::Oa, Some(mixed), oa)
|
||||
);
|
||||
assert_eq!((app.zoom, app.pan), camera);
|
||||
assert_eq!(
|
||||
serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap(),
|
||||
raw
|
||||
);
|
||||
assert_eq!(app.source_editor.text(), source);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_layer_traces_respects_busy_modal_and_active_placement_guards() {
|
||||
for already_traces in [false, true] {
|
||||
for guard in 0..5 {
|
||||
let (mut app, mixed, _, oa, _) = fixture();
|
||||
match guard {
|
||||
0 => app.busy = true,
|
||||
1 => app.delete_pending = true,
|
||||
2 => app.hosted.visible = true,
|
||||
3 => send(
|
||||
&mut app,
|
||||
Message::Architecture(architecture_authoring::Event::Existing(None)),
|
||||
),
|
||||
4 => {
|
||||
app.page = Page::Behavior;
|
||||
let p = app.project().clone();
|
||||
app.behavior
|
||||
.creation
|
||||
.update(&p, behavior::creation::Event::Open(Layer::Oa))
|
||||
.unwrap();
|
||||
assert!(app.behavior.has_pending());
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
if already_traces {
|
||||
app.page = Page::Traces;
|
||||
}
|
||||
let original_page = app.page;
|
||||
let before = app.document.snapshot();
|
||||
let behavior_before = app.behavior.recovery_snapshot().unwrap();
|
||||
send(&mut app, Message::ReviewLayerTraces);
|
||||
assert_eq!(
|
||||
app.page, original_page,
|
||||
"guard {guard}, already traces {already_traces}"
|
||||
);
|
||||
assert_eq!(app.traceability.filter, Filter::Artifacts);
|
||||
assert_eq!(app.traceability.query, "stale artifact query");
|
||||
assert_eq!(
|
||||
(app.layer, app.active_diagram, app.selected),
|
||||
(Layer::Oa, Some(mixed), oa)
|
||||
);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
assert_eq!(app.behavior.recovery_snapshot().unwrap(), behavior_before);
|
||||
if guard == 3 {
|
||||
assert!(app.architecture.is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_view_show_keeps_its_context_for_every_diagram_app_and_target_layer() {
|
||||
for diagram_layer in [Layer::Oa, Layer::Sa] {
|
||||
for app_layer in [Layer::Oa, Layer::Sa] {
|
||||
for target_layer in [Layer::Oa, Layer::Sa] {
|
||||
let mut p = Project::empty();
|
||||
let oa = p
|
||||
.add_element(Kind::Activity, Layer::Oa, "Observe", None)
|
||||
.unwrap();
|
||||
let sa = p
|
||||
.add_element(Kind::Function, Layer::Sa, "Detect", None)
|
||||
.unwrap();
|
||||
let target = if target_layer == Layer::Oa { oa } else { sa };
|
||||
let other = if target_layer == Layer::Oa { sa } else { oa };
|
||||
let mixed = p.ensure_diagram(diagram_layer);
|
||||
p.diagrams.get_mut(&mixed).unwrap().projection = ProjectionKind::Traceability;
|
||||
// An attractive same-layer alternative makes accidental
|
||||
// semantic-selection navigation observable in both directions.
|
||||
let mut alternative = p.diagrams[&mixed].clone();
|
||||
alternative.id = Id::new_v4();
|
||||
alternative.alias = "same_layer_alternative".into();
|
||||
alternative.layer = target_layer;
|
||||
alternative.projection = ProjectionKind::Overview;
|
||||
let alternative_id = alternative.id;
|
||||
p.diagrams.insert(alternative_id, alternative);
|
||||
p.place(alternative_id, target, Position { x: 700., y: 200. });
|
||||
oa_core::validate_candidate(&p).unwrap();
|
||||
let mut app = App::with_project(p);
|
||||
app.page = Page::Diagram;
|
||||
app.layer = app_layer;
|
||||
app.active_diagram = Some(mixed);
|
||||
app.selected = other;
|
||||
app.refresh_draft();
|
||||
let before = app.project().clone();
|
||||
let action = show_action(&mut app, target);
|
||||
send(&mut app, action);
|
||||
// The existing RevealInDiagram action synchronizes the layer
|
||||
// to the captured view, even if the prior perspective differed.
|
||||
assert_eq!(
|
||||
(app.active_diagram, app.layer, app.selected),
|
||||
(Some(mixed), diagram_layer, target)
|
||||
);
|
||||
let added = app.project().diagrams[&mixed]
|
||||
.nodes
|
||||
.values()
|
||||
.find(|n| n.element == target)
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert_eq!(app.selected_node, Some(added.id));
|
||||
let mut expected = before;
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&mixed)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.insert(added.id, added);
|
||||
assert_eq!(app.project(), &expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_view_show_menu_places_in_captured_view_with_exact_undo_redo() {
|
||||
let (mut app, mixed, system, _, sa) = fixture();
|
||||
let before = app.document.snapshot();
|
||||
let action = show_action(&mut app, sa);
|
||||
send(&mut app, action);
|
||||
assert_eq!(
|
||||
(app.active_diagram, app.layer, app.selected),
|
||||
(Some(mixed), Layer::Oa, sa)
|
||||
);
|
||||
let added = app.project().diagrams[&mixed]
|
||||
.nodes
|
||||
.values()
|
||||
.find(|n| n.element == sa)
|
||||
.unwrap()
|
||||
.clone();
|
||||
assert_eq!(added.position, Position { x: 60., y: 60. });
|
||||
let mut expected = before.decoded.project.clone();
|
||||
expected
|
||||
.diagrams
|
||||
.get_mut(&mixed)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.insert(added.id, added);
|
||||
assert_eq!(app.project(), &expected);
|
||||
assert_eq!(
|
||||
app.project().diagrams[&system],
|
||||
before.decoded.project.diagrams[&system]
|
||||
);
|
||||
let after = app.document.snapshot();
|
||||
send(&mut app, Message::Undo);
|
||||
assert_eq!(app.project(), &before.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &before.bundle);
|
||||
assert!(!app.document.can_undo());
|
||||
send(&mut app, Message::Redo);
|
||||
assert_eq!(app.project(), &after.decoded.project);
|
||||
assert_eq!(app.document.bundle(), &after.bundle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_view_show_menu_rejects_stale_context_and_pending_property_changes() {
|
||||
for refusal in 0..3 {
|
||||
let (mut app, mixed, system, oa, sa) = fixture();
|
||||
let action = show_action(&mut app, sa);
|
||||
match refusal {
|
||||
0 => app.active_diagram = Some(system),
|
||||
1 => app.canvas_epoch = app.canvas_epoch.wrapping_add(1),
|
||||
2 => {
|
||||
// A queued action must not apply a draft that became dirty
|
||||
// after the menu was rendered, even when its context is valid.
|
||||
app.draft
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.input("/name", "Unapplied name".into());
|
||||
assert!(app.draft_dirty());
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let before = app.document.snapshot();
|
||||
let raw = serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap();
|
||||
send(&mut app, action);
|
||||
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
|
||||
assert_eq!(app.selected, oa);
|
||||
assert_eq!(
|
||||
app.active_diagram,
|
||||
Some(if refusal == 0 { system } else { mixed })
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap(),
|
||||
raw
|
||||
);
|
||||
assert!(!app.document.can_undo());
|
||||
}
|
||||
}
|
||||
@@ -49,11 +49,28 @@ fn fixture(layer: Layer, kind: Kind) -> (App, Id, Id, Id) {
|
||||
p.diagrams.get_mut(&view).unwrap().name = "Unrelated architecture".into();
|
||||
p.place(view, reused, Position { x: 873., y: 421. });
|
||||
let mut app = App::with_project(p);
|
||||
app.layer = layer;
|
||||
app.page = Page::Behavior;
|
||||
app.selected = root;
|
||||
app.behavior.active_owner = Some(root);
|
||||
app.refresh_draft();
|
||||
let accepted = app.document.snapshot();
|
||||
// Enter through the actual navigation path: assigning Page/owner alone does
|
||||
// not create the representation and live visit required by canvas events.
|
||||
send(&mut app, Message::Select(root));
|
||||
send(&mut app, Message::Page(Page::Behavior));
|
||||
assert_eq!(app.layer, layer);
|
||||
assert_eq!(app.page, Page::Behavior);
|
||||
assert_eq!(app.selected, root);
|
||||
assert_eq!(app.behavior.active_owner, Some(root));
|
||||
if kind == Kind::Scenario {
|
||||
let context = app.scenario_context().unwrap();
|
||||
assert_eq!(context.document, app.canvas_document);
|
||||
assert_eq!(context.scenario, root);
|
||||
assert_eq!(
|
||||
context.representation,
|
||||
crate::behavior::scenario_layout::Representation::Derived { owner: root }
|
||||
);
|
||||
assert!(!context.visit.is_nil());
|
||||
}
|
||||
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
|
||||
assert_eq!(app.source_workspace.bundle(), accepted.bundle);
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
(app, root, work, reused)
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,11 @@ pub(crate) mod creation;
|
||||
mod form_session;
|
||||
pub(crate) mod scenario;
|
||||
mod scenario_activation;
|
||||
#[cfg(test)]
|
||||
mod scenario_hit_tests;
|
||||
// Pure saved-geometry bridge; workspace integration is a separate checkpoint.
|
||||
#[allow(dead_code)]
|
||||
pub(crate) mod scenario_layout;
|
||||
mod scenario_lifecycle;
|
||||
pub(crate) mod source_draft;
|
||||
pub(crate) mod state_canvas;
|
||||
@@ -59,9 +64,18 @@ mod scenario_scroll {
|
||||
process: bool,
|
||||
restore: Option<scenario::ScrollRestore>,
|
||||
}
|
||||
type Report = Option<(bool, Id, Id, Vector)>;
|
||||
type Identity = (Id, Id, scenario_layout::Representation, Id);
|
||||
fn identity(context: scenario::Context) -> Identity {
|
||||
(
|
||||
context.document,
|
||||
context.scenario,
|
||||
context.representation,
|
||||
context.visit,
|
||||
)
|
||||
}
|
||||
type Report = Option<(bool, Identity, Vector)>;
|
||||
struct ObservedScroll {
|
||||
identity: (Id, Id),
|
||||
identity: Identity,
|
||||
report: Report,
|
||||
restored: Option<Id>,
|
||||
}
|
||||
@@ -112,8 +126,12 @@ mod scenario_scroll {
|
||||
) {
|
||||
let restore = self.restore.filter(|request| {
|
||||
!self.process
|
||||
&& (request.document, request.owner)
|
||||
== (self.context.document, self.context.scenario)
|
||||
&& (
|
||||
request.document,
|
||||
request.owner,
|
||||
request.representation,
|
||||
request.visit,
|
||||
) == identity(self.context)
|
||||
&& tree.state.downcast_ref::<ObservedScroll>().restored != Some(request.token)
|
||||
});
|
||||
let receipt = restore.and_then(|request| {
|
||||
@@ -137,12 +155,7 @@ mod scenario_scroll {
|
||||
&mut offset,
|
||||
);
|
||||
if let Some(offset) = offset.0 {
|
||||
let next = Some((
|
||||
self.process,
|
||||
self.context.document,
|
||||
self.context.scenario,
|
||||
offset,
|
||||
));
|
||||
let next = Some((self.process, identity(self.context), offset));
|
||||
let state = tree.state.downcast_mut::<ObservedScroll>();
|
||||
if let Some(token) = receipt {
|
||||
state.restored = Some(token);
|
||||
@@ -186,7 +199,7 @@ mod scenario_scroll {
|
||||
}
|
||||
fn state(&self) -> widget::tree::State {
|
||||
widget::tree::State::new(ObservedScroll {
|
||||
identity: (self.context.document, self.context.scenario),
|
||||
identity: identity(self.context),
|
||||
report: None,
|
||||
restored: None,
|
||||
})
|
||||
@@ -195,9 +208,7 @@ mod scenario_scroll {
|
||||
vec![widget::Tree::new(self.content.as_widget())]
|
||||
}
|
||||
fn diff(&self, tree: &mut widget::Tree) {
|
||||
if tree.state.downcast_ref::<ObservedScroll>().identity
|
||||
!= (self.context.document, self.context.scenario)
|
||||
{
|
||||
if tree.state.downcast_ref::<ObservedScroll>().identity != identity(self.context) {
|
||||
// A new owner/document needs fresh real scroll state, not merely
|
||||
// cleared mirrored offsets. Edits and tool/form changes retain it.
|
||||
tree.state = self.state();
|
||||
@@ -486,17 +497,25 @@ mod scenario_scroll {
|
||||
}
|
||||
#[test]
|
||||
fn direct_scenario_restore_cannot_scroll_another_document_owner_or_process_view() {
|
||||
for mismatch in 0..3 {
|
||||
for mismatch in 0..5 {
|
||||
let context = scenario::direct_tests::context(Id::new_v4());
|
||||
let mut request = scenario::ScrollRestore {
|
||||
document: context.document,
|
||||
owner: context.scenario,
|
||||
representation: context.representation,
|
||||
visit: context.visit,
|
||||
token: Id::new_v4(),
|
||||
offset: Vector::new(0., 180.),
|
||||
};
|
||||
match mismatch {
|
||||
0 => request.document = Id::new_v4(),
|
||||
1 => request.owner = Id::new_v4(),
|
||||
3 => {
|
||||
request.representation = scenario_layout::Representation::Saved {
|
||||
diagram: Id::new_v4(),
|
||||
}
|
||||
}
|
||||
4 => request.visit = Id::new_v4(),
|
||||
_ => {}
|
||||
}
|
||||
let mut view = observer(600., context);
|
||||
@@ -583,7 +602,7 @@ mod scenario_scroll {
|
||||
use widget::operation::scrollable::{AbsoluteOffset, scroll_to};
|
||||
for process in [false, true] {
|
||||
let area = scenario::ScrollArea::Page;
|
||||
for change in 0..4 {
|
||||
for change in 0..6 {
|
||||
let context = scenario::direct_tests::context(Id::new_v4());
|
||||
let mut view = observer(600., context);
|
||||
view.process = process;
|
||||
@@ -612,6 +631,12 @@ mod scenario_scroll {
|
||||
next.revision += 1;
|
||||
next.epoch += 5;
|
||||
}
|
||||
4 => {
|
||||
next.representation = scenario_layout::Representation::Saved {
|
||||
diagram: Id::new_v4(),
|
||||
}
|
||||
}
|
||||
5 => next.visit = Id::new_v4(),
|
||||
_ => {}
|
||||
}
|
||||
view = observer(if change == 3 { 800. } else { 600. }, next);
|
||||
@@ -659,7 +684,7 @@ mod scenario_scroll {
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
actual,
|
||||
vec![if change < 2 {
|
||||
vec![if !(2..4).contains(&change) {
|
||||
Vector::ZERO
|
||||
} else {
|
||||
Vector::new(0., 180.)
|
||||
@@ -973,6 +998,19 @@ pub fn view(app: &App) -> Element<'_, Message> {
|
||||
return container(out).padding(16).width(Fill).height(Fill).into();
|
||||
}
|
||||
}
|
||||
// A requested saved view remains the destination even after its model is removed.
|
||||
// The shared display adapter reports unavailable instead of choosing another behavior.
|
||||
if matches!(
|
||||
app.behavior.scenario.representation(),
|
||||
Some(scenario_layout::Representation::Saved { .. })
|
||||
) && let Some(owner) = app.behavior.scenario.owner()
|
||||
&& !p
|
||||
.elements
|
||||
.get(&owner)
|
||||
.is_some_and(|element| element.kind() == Kind::Scenario && element.layer() == app.layer)
|
||||
{
|
||||
return scenario::view(app, owner, column![].spacing(6));
|
||||
}
|
||||
let choices = p
|
||||
.elements
|
||||
.values()
|
||||
@@ -984,7 +1022,14 @@ pub fn view(app: &App) -> Element<'_, Message> {
|
||||
label: format!("{} · {}", e.kind(), e.name),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let owner = selected_owner(app);
|
||||
let owner = if matches!(
|
||||
app.behavior.scenario.representation(),
|
||||
Some(scenario_layout::Representation::Saved { .. })
|
||||
) {
|
||||
app.behavior.scenario.owner()
|
||||
} else {
|
||||
selected_owner(app)
|
||||
};
|
||||
let selected = owner
|
||||
.and_then(|id| choices.iter().find(|c| c.id == id))
|
||||
.or(choices.first())
|
||||
@@ -1118,8 +1163,27 @@ fn in_machine(p: &Project, id: Id, machine: Id) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Identifies the drawn primitive that won selection, not an authoring permission.
|
||||
/// In particular an activation and its message can share an occurrence UUID.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum SceneHitRole {
|
||||
LifelineHeader,
|
||||
MessageBody,
|
||||
MessageLabel,
|
||||
Activation,
|
||||
LifecycleMarker,
|
||||
LifelineGuide,
|
||||
Box,
|
||||
OtherLine,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct SceneHit {
|
||||
id: Id,
|
||||
role: SceneHitRole,
|
||||
}
|
||||
struct BoxItem {
|
||||
id: Id,
|
||||
role: SceneHitRole,
|
||||
rect: Rectangle,
|
||||
title: String,
|
||||
detail: String,
|
||||
@@ -1152,6 +1216,7 @@ fn box_text_clip(
|
||||
|
||||
struct Line {
|
||||
id: Id,
|
||||
role: SceneHitRole,
|
||||
points: Vec<Point>,
|
||||
label: String,
|
||||
label_at: Point,
|
||||
@@ -1172,12 +1237,17 @@ struct Scene {
|
||||
boxes: Vec<BoxItem>,
|
||||
lines: Vec<Line>,
|
||||
size: Size,
|
||||
layout_origin: Point,
|
||||
selected: Id,
|
||||
scale: f32,
|
||||
camera_pan: iced::Vector,
|
||||
interaction: Option<(scenario::Context, scenario::CanvasTool, bool)>,
|
||||
spacing_stamp: Option<scenario::spacing::Stamp>,
|
||||
coordinate_input: bool,
|
||||
pending_placement: Option<(scenario::Slot, Option<Id>)>,
|
||||
lanes: BTreeMap<Id, f32>,
|
||||
// Exact render coordinates include unassigned lanes; do not derive from cards.
|
||||
render_lanes: BTreeMap<Id, f32>,
|
||||
slots: Vec<SequenceSlot>,
|
||||
rows: BTreeMap<Id, (Id, f32)>,
|
||||
activations: Vec<scenario_activation::Segment>,
|
||||
@@ -1201,6 +1271,10 @@ struct SequenceInput {
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
enum SequencePress {
|
||||
Spacing {
|
||||
stamp: scenario::spacing::Stamp,
|
||||
token: Id,
|
||||
},
|
||||
Occurrence {
|
||||
tool: scenario::Tool,
|
||||
slot: scenario::Slot,
|
||||
@@ -1221,6 +1295,19 @@ enum SequencePress {
|
||||
},
|
||||
}
|
||||
impl SequenceInput {
|
||||
fn cancel_spacing(&mut self) -> Option<Action<Message>> {
|
||||
let cancel = match self.press {
|
||||
Some(SequencePress::Spacing { stamp, token }) => Some(
|
||||
Action::publish(Message::ScenarioCanvas(scenario::CanvasEvent::Spacing(
|
||||
scenario::spacing::Event::Cancel { stamp, token },
|
||||
)))
|
||||
.and_capture(),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
self.cancel();
|
||||
cancel
|
||||
}
|
||||
fn cancel(&mut self) {
|
||||
self.source = None;
|
||||
self.press = None;
|
||||
@@ -1232,17 +1319,31 @@ impl Scene {
|
||||
&& (self.boxes.iter().any(|item| item.id == id)
|
||||
|| self.lines.iter().any(|item| item.id == id))
|
||||
}
|
||||
// The integrated removal guard also needs the derived semantic hit set.
|
||||
fn sequence(p: &Project, owner: Id, selected: Id) -> Self {
|
||||
Self::sequence_geometry(p, owner, selected, None, None)
|
||||
}
|
||||
fn sequence_geometry(
|
||||
p: &Project,
|
||||
owner: Id,
|
||||
selected: Id,
|
||||
lane_override: Option<&BTreeMap<Id, f32>>,
|
||||
plan: Option<&scenario_layout::Plan>,
|
||||
) -> Self {
|
||||
let mut scene = Self {
|
||||
scale: 1.,
|
||||
camera_pan: iced::Vector::ZERO,
|
||||
boxes: vec![],
|
||||
lines: vec![],
|
||||
size: Size::new(700., 200.),
|
||||
layout_origin: Point::ORIGIN,
|
||||
selected,
|
||||
interaction: None,
|
||||
spacing_stamp: None,
|
||||
coordinate_input: true,
|
||||
pending_placement: None,
|
||||
lanes: BTreeMap::new(),
|
||||
render_lanes: BTreeMap::new(),
|
||||
slots: vec![],
|
||||
rows: BTreeMap::new(),
|
||||
activations: vec![],
|
||||
@@ -1313,12 +1414,32 @@ impl Scene {
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let lane_x = lanes
|
||||
let mut lane_x = lanes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (id, ..))| (*id, 160. + i as f32 * 240.))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
if let Some(values) = lane_override {
|
||||
for (id, x) in values {
|
||||
if let Some(lane) = lane_x.get_mut(id) {
|
||||
*lane = *x;
|
||||
}
|
||||
}
|
||||
}
|
||||
scene.render_lanes = lane_x.clone();
|
||||
scene.size.width = (lanes.len() as f32 * 240. + 80.).max(680.);
|
||||
let layout_left = if lane_override.is_some() {
|
||||
lane_x.values().fold(0_f32, |left, x| left.min(*x - 160.))
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
scene.layout_origin.x = layout_left;
|
||||
if lane_override.is_some() {
|
||||
scene.size.width = lane_x
|
||||
.values()
|
||||
.fold(scene.size.width, |right, x| right.max(*x + 240.))
|
||||
- layout_left;
|
||||
}
|
||||
if scenario {
|
||||
scene.lanes = lane_x
|
||||
.iter()
|
||||
@@ -1334,8 +1455,26 @@ impl Scene {
|
||||
.collect();
|
||||
}
|
||||
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.);
|
||||
scene.occurrences(p, owner, scenario, &lane_x, &mut y, 0, plan);
|
||||
if layout_left != 0. {
|
||||
for item in &mut scene.boxes {
|
||||
let body = scenario_layout::occurrence(p, item.id);
|
||||
if matches!(
|
||||
body,
|
||||
Some(
|
||||
OccurrenceBody::Branch { .. }
|
||||
| OccurrenceBody::ScenarioUse { .. }
|
||||
| OccurrenceBody::Control { .. }
|
||||
| OccurrenceBody::SequenceReference { .. }
|
||||
| OccurrenceBody::Exchange { .. }
|
||||
)
|
||||
) || (plan.is_none() && matches!(body, Some(OccurrenceBody::Fragment { .. })))
|
||||
{
|
||||
item.rect.x += layout_left;
|
||||
}
|
||||
}
|
||||
}
|
||||
scene.size.height = plan.map_or((y + 45.).max(210.), |plan| plan.height);
|
||||
if scenario {
|
||||
scene.lifecycle = scenario_lifecycle::render::Rendering::new(
|
||||
p,
|
||||
@@ -1346,6 +1485,9 @@ impl Scene {
|
||||
scene.size.height,
|
||||
);
|
||||
scene.lifecycle.align_messages(&mut scene.lines);
|
||||
if let Some(plan) = plan {
|
||||
plan.align_message_anchors(&mut scene.lines);
|
||||
}
|
||||
scene.layout_activations(p, &lane_x);
|
||||
}
|
||||
for (id, name, detail) in lanes {
|
||||
@@ -1355,6 +1497,7 @@ impl Scene {
|
||||
0,
|
||||
Line {
|
||||
id,
|
||||
role: SceneHitRole::LifelineGuide,
|
||||
points: vec![Point::new(x, 85.), Point::new(x, scene.size.height - 20.)],
|
||||
label: String::new(),
|
||||
label_at: Point::ORIGIN,
|
||||
@@ -1364,6 +1507,11 @@ impl Scene {
|
||||
}
|
||||
scene.boxes.push(BoxItem {
|
||||
id,
|
||||
role: if scenario {
|
||||
SceneHitRole::LifelineHeader
|
||||
} else {
|
||||
SceneHitRole::Box
|
||||
},
|
||||
rect: Rectangle::new(Point::new(x - 102., 15.), Size::new(204., 70.)),
|
||||
title: name,
|
||||
detail,
|
||||
@@ -1372,6 +1520,7 @@ impl Scene {
|
||||
}
|
||||
scene
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)] // Explicit complete plan replaces ambient geometry state.
|
||||
fn occurrences(
|
||||
&mut self,
|
||||
p: &Project,
|
||||
@@ -1380,6 +1529,7 @@ impl Scene {
|
||||
lanes: &BTreeMap<Id, f32>,
|
||||
y: &mut f32,
|
||||
depth: usize,
|
||||
plan: Option<&scenario_layout::Plan>,
|
||||
) {
|
||||
let steps = p
|
||||
.elements
|
||||
@@ -1419,6 +1569,9 @@ impl Scene {
|
||||
}
|
||||
#[cfg(test)]
|
||||
scenario_lifecycle::render::apply_test_row_offset(*id, y);
|
||||
if let Some(plan) = plan {
|
||||
*y = plan.anchors[id].y;
|
||||
}
|
||||
if ordered {
|
||||
let slot = scenario::Slot {
|
||||
parent: owner,
|
||||
@@ -1435,7 +1588,7 @@ impl Scene {
|
||||
OccurrenceBody::Fragment { operator, .. } => {
|
||||
let top = *y;
|
||||
*y += 55.;
|
||||
self.occurrences(p, *id, scenario, lanes, y, depth + 1);
|
||||
self.occurrences(p, *id, scenario, lanes, y, depth + 1, plan);
|
||||
let rect = Rectangle::new(
|
||||
Point::new(18. + depth as f32 * 10., top),
|
||||
Size::new(
|
||||
@@ -1443,10 +1596,12 @@ impl Scene {
|
||||
(*y - top).max(95.),
|
||||
),
|
||||
);
|
||||
let rect = plan.map_or(rect, |plan| plan.frames[id]);
|
||||
self.boxes.insert(
|
||||
0,
|
||||
BoxItem {
|
||||
id: *id,
|
||||
role: SceneHitRole::Box,
|
||||
rect,
|
||||
title: format!("{operator:?} · {}", e.name),
|
||||
detail: String::new(),
|
||||
@@ -1458,6 +1613,7 @@ impl Scene {
|
||||
OccurrenceBody::Branch { guard, .. } => {
|
||||
self.boxes.push(BoxItem {
|
||||
id: *id,
|
||||
role: SceneHitRole::Box,
|
||||
rect: Rectangle::new(
|
||||
Point::new(36. + depth as f32 * 10., *y),
|
||||
Size::new(self.size.width - 85. - depth as f32 * 20., 43.),
|
||||
@@ -1474,7 +1630,7 @@ impl Scene {
|
||||
marker: Some(Kind::Occurrence),
|
||||
});
|
||||
*y += if scenario { 90. } else { 62. };
|
||||
self.occurrences(p, *id, scenario, lanes, y, depth + 1);
|
||||
self.occurrences(p, *id, scenario, lanes, y, depth + 1, plan);
|
||||
}
|
||||
OccurrenceBody::Exchange {
|
||||
exchange,
|
||||
@@ -1502,7 +1658,7 @@ impl Scene {
|
||||
source.and_then(|id| lanes.get(&id)),
|
||||
target.and_then(|id| lanes.get(&id)),
|
||||
) {
|
||||
let points = if a == b {
|
||||
let points = if source == target {
|
||||
vec![
|
||||
Point::new(*a, *y),
|
||||
Point::new(a + 75., *y),
|
||||
@@ -1541,6 +1697,7 @@ impl Scene {
|
||||
}
|
||||
self.lines.push(Line {
|
||||
id: *id,
|
||||
role: SceneHitRole::MessageBody,
|
||||
points,
|
||||
label: format!("{}. {kind}{}", index + 1, message_label),
|
||||
label_at: Point::new(a.min(*b) + 12., *y - 26.),
|
||||
@@ -1549,6 +1706,7 @@ impl Scene {
|
||||
} else {
|
||||
self.boxes.push(BoxItem {
|
||||
id: *id,
|
||||
role: SceneHitRole::Box,
|
||||
rect: Rectangle::new(
|
||||
Point::new(65., *y - 20.),
|
||||
Size::new(self.size.width - 130., 65.),
|
||||
@@ -1571,6 +1729,7 @@ impl Scene {
|
||||
.unwrap_or(180.);
|
||||
self.boxes.push(BoxItem {
|
||||
id: *id,
|
||||
role: SceneHitRole::Box,
|
||||
rect: Rectangle::new(Point::new(x - 110., *y - 20.), Size::new(220., 70.)),
|
||||
title: e.name.clone(),
|
||||
detail: action
|
||||
@@ -1583,6 +1742,7 @@ impl Scene {
|
||||
OccurrenceBody::Control { kind } => {
|
||||
self.boxes.push(BoxItem {
|
||||
id: *id,
|
||||
role: SceneHitRole::Box,
|
||||
rect: Rectangle::new(Point::new(65., *y - 20.), Size::new(240., 70.)),
|
||||
title: format!("{kind:?} · {}", e.name),
|
||||
detail: "Contextual process control".into(),
|
||||
@@ -1593,6 +1753,7 @@ impl Scene {
|
||||
OccurrenceBody::SequenceReference { sequence } => {
|
||||
self.boxes.push(BoxItem {
|
||||
id: *id,
|
||||
role: SceneHitRole::Box,
|
||||
rect: Rectangle::new(Point::new(65., *y - 20.), Size::new(280., 70.)),
|
||||
title: e.name.clone(),
|
||||
detail: sequence
|
||||
@@ -1605,6 +1766,7 @@ impl Scene {
|
||||
OccurrenceBody::ScenarioUse { scenario, bindings } => {
|
||||
self.boxes.push(BoxItem {
|
||||
id: *id,
|
||||
role: SceneHitRole::Box,
|
||||
rect: Rectangle::new(
|
||||
Point::new(65., *y - 20.),
|
||||
Size::new(self.size.width - 130., 70.),
|
||||
@@ -1627,6 +1789,10 @@ impl Scene {
|
||||
}
|
||||
if ordered {
|
||||
self.sequence_bounds.insert(owner, (sequence_top, *y - 42.));
|
||||
if let Some(plan) = plan {
|
||||
self.sequence_bounds.insert(owner, plan.scopes[&owner]);
|
||||
*y = plan.scopes[&owner].1 + 42.;
|
||||
}
|
||||
let slot = scenario::Slot {
|
||||
parent: owner,
|
||||
before: None,
|
||||
@@ -1666,11 +1832,21 @@ impl Scene {
|
||||
))
|
||||
}
|
||||
fn hit(&self, point: Point) -> Option<Id> {
|
||||
self.hit_item(point).map(|hit| hit.id)
|
||||
}
|
||||
|
||||
/// Preserve the semantic selection order and tolerance while retaining the
|
||||
/// primitive's identity. Future spacing admission must also validate the
|
||||
/// saved view, owner and core occurrence kind; a hit alone grants no edit.
|
||||
fn hit_item(&self, point: Point) -> Option<SceneHit> {
|
||||
if !point.x.is_finite() || !point.y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if let Some(id) = self.lifecycle.marker_at(point) {
|
||||
return Some(id);
|
||||
return Some(SceneHit {
|
||||
id,
|
||||
role: SceneHitRole::LifecycleMarker,
|
||||
});
|
||||
}
|
||||
self.boxes
|
||||
.iter()
|
||||
@@ -1680,7 +1856,10 @@ impl Scene {
|
||||
&& b.rect.contains(point)
|
||||
&& (b.marker != Some(Kind::Occurrence) || point.y < b.rect.y + 38.)
|
||||
})
|
||||
.map(|b| b.id)
|
||||
.map(|b| SceneHit {
|
||||
id: b.id,
|
||||
role: b.role,
|
||||
})
|
||||
.or_else(|| {
|
||||
self.lines
|
||||
.iter()
|
||||
@@ -1690,26 +1869,51 @@ impl Scene {
|
||||
crate::diagram::distance_to_segment(point, p[0], p[1]) < 1.5
|
||||
})
|
||||
})
|
||||
.map(|line| line.id)
|
||||
.map(|line| SceneHit {
|
||||
id: line.id,
|
||||
role: line.role,
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
self.activations
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|b| b.rect.contains(point))
|
||||
.map(|b| b.call)
|
||||
.map(|b| SceneHit {
|
||||
id: b.call,
|
||||
role: SceneHitRole::Activation,
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
self.lines
|
||||
.iter()
|
||||
.find(|line| !line.label.is_empty() && line.label_bounds().contains(point))
|
||||
.map(|line| line.id)
|
||||
.map(|line| SceneHit {
|
||||
id: line.id,
|
||||
role: if line.role == SceneHitRole::MessageBody {
|
||||
SceneHitRole::MessageLabel
|
||||
} else {
|
||||
SceneHitRole::OtherLine
|
||||
},
|
||||
})
|
||||
})
|
||||
// The generous message tolerance must not steal the exposed
|
||||
// shoulder of another call's execution when the view is zoomed out.
|
||||
.or_else(|| self.near_sequence_item(point))
|
||||
.or_else(|| self.lifecycle.lane_at(point, self.scale))
|
||||
.or_else(|| self.lane_at(point))
|
||||
.or_else(|| {
|
||||
self.lifecycle
|
||||
.lane_at(point, self.scale)
|
||||
.map(|id| SceneHit {
|
||||
id,
|
||||
role: SceneHitRole::LifelineGuide,
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
self.lane_at(point).map(|id| SceneHit {
|
||||
id,
|
||||
role: SceneHitRole::LifelineGuide,
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
self.lines
|
||||
.iter()
|
||||
@@ -1720,11 +1924,14 @@ impl Scene {
|
||||
< 8. / self.scale
|
||||
})
|
||||
})
|
||||
.map(|line| line.id)
|
||||
.map(|line| SceneHit {
|
||||
id: line.id,
|
||||
role: line.role,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn near_sequence_item(&self, point: Point) -> Option<Id> {
|
||||
fn near_sequence_item(&self, point: Point) -> Option<SceneHit> {
|
||||
if !self.scale.is_finite() || self.scale <= 0. {
|
||||
return None;
|
||||
}
|
||||
@@ -1738,17 +1945,32 @@ impl Scene {
|
||||
.windows(2)
|
||||
.map(|p| crate::diagram::distance_to_segment(point, p[0], p[1]))
|
||||
.fold(f32::INFINITY, f32::min);
|
||||
(line.id, distance)
|
||||
(
|
||||
SceneHit {
|
||||
id: line.id,
|
||||
role: line.role,
|
||||
},
|
||||
distance,
|
||||
)
|
||||
});
|
||||
// Compare broad message and lifecycle-marker tolerance together after
|
||||
// exact shapes, so dense minimum-Fit rows choose the nearer item.
|
||||
self.lifecycle
|
||||
.nearest_marker(point)
|
||||
.map(|(id, distance)| {
|
||||
(
|
||||
SceneHit {
|
||||
id,
|
||||
role: SceneHitRole::LifecycleMarker,
|
||||
},
|
||||
distance,
|
||||
)
|
||||
})
|
||||
.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)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.id.cmp(&b.0.id)))
|
||||
.map(|(hit, _)| hit)
|
||||
}
|
||||
}
|
||||
impl canvas::Program<Message> for Scene {
|
||||
@@ -1776,15 +1998,33 @@ impl canvas::Program<Message> for Scene {
|
||||
// captured insertion slot belongs to the previous view, even if the
|
||||
// pointer itself did not move and the semantic context is unchanged.
|
||||
if state.bounds.is_some_and(|previous| previous != bounds) {
|
||||
state.cancel();
|
||||
let cancelled = state.cancel_spacing();
|
||||
state.pointer = None;
|
||||
state.bounds = Some(bounds);
|
||||
if cancelled.is_some() {
|
||||
return cancelled;
|
||||
}
|
||||
}
|
||||
state.bounds = Some(bounds);
|
||||
if !editable {
|
||||
state.cancel();
|
||||
if (!editable || !self.coordinate_input)
|
||||
&& let Some(cancelled) = state.cancel_spacing()
|
||||
{
|
||||
return Some(cancelled);
|
||||
}
|
||||
// The viewport masks input outside its visible canvas bounds.
|
||||
let visible = cursor.position().is_some();
|
||||
if !visible
|
||||
&& matches!(state.press, Some(SequencePress::Spacing { .. }))
|
||||
&& matches!(
|
||||
event,
|
||||
canvas::Event::Mouse(
|
||||
mouse::Event::CursorMoved { .. }
|
||||
| mouse::Event::ButtonReleased(mouse::Button::Left)
|
||||
)
|
||||
)
|
||||
{
|
||||
return state.cancel_spacing();
|
||||
}
|
||||
if !visible
|
||||
&& matches!(
|
||||
event,
|
||||
@@ -1803,7 +2043,7 @@ impl canvas::Program<Message> for Scene {
|
||||
| SequencePress::Reorder { start, moved, .. } => {
|
||||
*moved |= position.distance(*start) >= 3.
|
||||
}
|
||||
SequencePress::Occurrence { .. } => {}
|
||||
SequencePress::Occurrence { .. } | SequencePress::Spacing { .. } => {}
|
||||
}
|
||||
}
|
||||
mouse::Cursor::Available(*position)
|
||||
@@ -1812,9 +2052,9 @@ impl canvas::Program<Message> for Scene {
|
||||
| canvas::Event::Window(iced::window::Event::Resized(_))
|
||||
| canvas::Event::Mouse(mouse::Event::CursorLeft)
|
||||
| canvas::Event::Window(iced::window::Event::Unfocused) => {
|
||||
state.cancel();
|
||||
let cancelled = state.cancel_spacing();
|
||||
state.pointer = None;
|
||||
return Some(Action::request_redraw());
|
||||
return cancelled.or_else(|| Some(Action::request_redraw()));
|
||||
}
|
||||
canvas::Event::Mouse(
|
||||
mouse::Event::ButtonPressed(_) | mouse::Event::ButtonReleased(_),
|
||||
@@ -1850,8 +2090,9 @@ impl canvas::Program<Message> for Scene {
|
||||
key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
|
||||
..
|
||||
}) if state.source.is_some() || state.press.is_some() => {
|
||||
state.cancel();
|
||||
return Some(Action::request_redraw().and_capture());
|
||||
return state
|
||||
.cancel_spacing()
|
||||
.or_else(|| Some(Action::request_redraw().and_capture()));
|
||||
}
|
||||
_ => cursor,
|
||||
};
|
||||
@@ -1871,6 +2112,14 @@ impl canvas::Program<Message> for Scene {
|
||||
if !editable {
|
||||
return None;
|
||||
}
|
||||
if !self.coordinate_input {
|
||||
return self.hit(point).map(|id| {
|
||||
Action::publish(Message::ScenarioCanvas(CanvasEvent::Select(
|
||||
context, id,
|
||||
)))
|
||||
.and_capture()
|
||||
});
|
||||
}
|
||||
if let CanvasTool::Message(_) = tool {
|
||||
let first = state.source.is_none();
|
||||
let (source, slot) = state.source.or_else(|| {
|
||||
@@ -1897,6 +2146,48 @@ impl canvas::Program<Message> for Scene {
|
||||
});
|
||||
return Some(Action::request_redraw().and_capture());
|
||||
}
|
||||
if matches!(
|
||||
context.representation,
|
||||
scenario_layout::Representation::Saved { .. }
|
||||
) {
|
||||
let hit = self.hit_item(point)?;
|
||||
let target = match hit.role {
|
||||
SceneHitRole::LifelineHeader => {
|
||||
Some(scenario::spacing::Target::Lane(hit.id))
|
||||
}
|
||||
SceneHitRole::MessageBody | SceneHitRole::MessageLabel => {
|
||||
Some(scenario::spacing::Target::Message(hit.id))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some((target, stamp)) = target.zip(self.spacing_stamp)
|
||||
&& stamp.context == context
|
||||
{
|
||||
let token = Id::new_v4();
|
||||
state.press = Some(SequencePress::Spacing { stamp, token });
|
||||
return Some(
|
||||
Action::publish(Message::ScenarioCanvas(CanvasEvent::Spacing(
|
||||
scenario::spacing::Event::Begin {
|
||||
stamp,
|
||||
token,
|
||||
target,
|
||||
press_screen: cursor.position()?,
|
||||
canvas_bounds: bounds,
|
||||
scale: self.scale,
|
||||
pan: self.camera_pan,
|
||||
},
|
||||
)))
|
||||
.and_capture(),
|
||||
);
|
||||
}
|
||||
// Saved spacing never silently changes the shared Scenario order.
|
||||
return Some(
|
||||
Action::publish(Message::ScenarioCanvas(CanvasEvent::Select(
|
||||
context, hit.id,
|
||||
)))
|
||||
.and_capture(),
|
||||
);
|
||||
}
|
||||
if let Some(occurrence) = self
|
||||
.hit(point)
|
||||
.filter(|id| self.rows.contains_key(id))
|
||||
@@ -1926,6 +2217,22 @@ impl canvas::Program<Message> for Scene {
|
||||
let press = state.press.take()?;
|
||||
let context = context?;
|
||||
match press {
|
||||
SequencePress::Spacing { stamp, token } => {
|
||||
state.source = None;
|
||||
let event = if world.is_some() {
|
||||
scenario::spacing::Event::Finish {
|
||||
stamp,
|
||||
token,
|
||||
screen: cursor.position()?,
|
||||
}
|
||||
} else {
|
||||
scenario::spacing::Event::Cancel { stamp, token }
|
||||
};
|
||||
return Some(
|
||||
Action::publish(Message::ScenarioCanvas(CanvasEvent::Spacing(event)))
|
||||
.and_capture(),
|
||||
);
|
||||
}
|
||||
SequencePress::Occurrence {
|
||||
tool: captured,
|
||||
slot,
|
||||
@@ -2017,6 +2324,18 @@ impl canvas::Program<Message> for Scene {
|
||||
Some(Action::request_redraw().and_capture())
|
||||
}
|
||||
canvas::Event::Mouse(mouse::Event::CursorMoved { .. }) if context.is_some() => {
|
||||
if let Some(SequencePress::Spacing { stamp, token }) = state.press {
|
||||
return Some(
|
||||
Action::publish(Message::ScenarioCanvas(CanvasEvent::Spacing(
|
||||
scenario::spacing::Event::Move {
|
||||
stamp,
|
||||
token,
|
||||
screen: cursor.position()?,
|
||||
},
|
||||
)))
|
||||
.and_capture(),
|
||||
);
|
||||
}
|
||||
Some(Action::request_redraw())
|
||||
}
|
||||
_ => None,
|
||||
@@ -2198,7 +2517,10 @@ impl canvas::Program<Message> for Scene {
|
||||
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 active = editable
|
||||
&& self.coordinate_input
|
||||
&& state.context == Some(context)
|
||||
&& state.tool == tool;
|
||||
let point = cursor.position_in(bounds).map(|p| {
|
||||
Point::new(
|
||||
(p.x - self.camera_pan.x) / self.scale,
|
||||
@@ -2214,7 +2536,12 @@ impl canvas::Program<Message> for Scene {
|
||||
}
|
||||
});
|
||||
if editable
|
||||
&& self.coordinate_input
|
||||
&& tool == scenario::CanvasTool::Select
|
||||
&& matches!(
|
||||
context.representation,
|
||||
scenario_layout::Representation::Derived { .. }
|
||||
)
|
||||
&& let Some(handle) = self.reorder_handle()
|
||||
{
|
||||
f.fill_rectangle(handle.position(), handle.size(), style::TEAL);
|
||||
|
||||
@@ -16,6 +16,7 @@ pub fn keyboard_enabled(app: &crate::app::App) -> bool {
|
||||
/// Passive I/O suspends commands without changing the logical input owner.
|
||||
pub(crate) fn keyboard_owner_enabled(app: &crate::app::App) -> bool {
|
||||
!app.hosted.visible
|
||||
&& !app.context_help
|
||||
&& app.workflow.is_none()
|
||||
&& app.file_prompt.is_none()
|
||||
&& !app.delete_pending
|
||||
@@ -50,7 +51,7 @@ pub fn controls<'a>(
|
||||
control("Details", "Details", Some(details)),
|
||||
control("Fit", "Fit", Some(zoom(None))),
|
||||
control("ZoomOut", "−", Some(zoom(Some(scale / 1.25)))),
|
||||
text(format!("{:.0}%", scale * 100.)).size(12),
|
||||
text(zoom_label(scale)).size(12),
|
||||
control("ZoomIn", "+", Some(zoom(Some(scale * 1.25)))),
|
||||
control("ActualSize", "100%", Some(zoom(Some(1.)))),
|
||||
]
|
||||
@@ -65,6 +66,7 @@ pub fn controls<'a>(
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Scope {
|
||||
pub(crate) scenario_view: Option<(super::scenario_layout::Representation, Id)>,
|
||||
pub document: Id,
|
||||
pub owner: Id,
|
||||
pub revision: u64,
|
||||
@@ -76,6 +78,7 @@ impl Scope {
|
||||
Some(Self {
|
||||
document: context.document,
|
||||
owner: context.scenario,
|
||||
scenario_view: Some((context.representation, context.visit)),
|
||||
revision: context.revision,
|
||||
epoch: app.camera_epoch,
|
||||
})
|
||||
@@ -84,6 +87,7 @@ impl Scope {
|
||||
Some(Self {
|
||||
document: context.document,
|
||||
owner: context.owner,
|
||||
scenario_view: None,
|
||||
revision: context.revision,
|
||||
epoch: app.camera_epoch,
|
||||
})
|
||||
@@ -103,8 +107,8 @@ impl Scope {
|
||||
|
||||
pub fn control_id(self, name: &str) -> iced::advanced::widget::Id {
|
||||
iced::advanced::widget::Id::from(format!(
|
||||
"behavior-control:{}:{}:{}:{name}",
|
||||
self.document, self.owner, self.revision
|
||||
"behavior-control:{}:{}:{}:{:?}:{name}",
|
||||
self.document, self.owner, self.revision, self.scenario_view
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -137,6 +141,20 @@ pub enum Event {
|
||||
pub use focus::{focus_task, root as focus_root};
|
||||
/// Fold relative input in event order. The base scale is used only on leaving Fit.
|
||||
pub fn change(pan: &mut Vector, zoom: &mut Option<f32>, fit: &mut bool, event: Event) -> bool {
|
||||
change_with_minimum(pan, zoom, fit, event, 0.05)
|
||||
}
|
||||
|
||||
/// Scenario extents can require scales below the topology canvas's 5% floor.
|
||||
pub(super) fn change_with_minimum(
|
||||
pan: &mut Vector,
|
||||
zoom: &mut Option<f32>,
|
||||
fit: &mut bool,
|
||||
event: Event,
|
||||
minimum: f32,
|
||||
) -> bool {
|
||||
if !minimum.is_finite() || minimum <= 0. || minimum > 3. {
|
||||
return false;
|
||||
}
|
||||
match event {
|
||||
Event::Pan(delta) if delta.x.is_finite() && delta.y.is_finite() => {
|
||||
let next = *pan + delta;
|
||||
@@ -156,7 +174,10 @@ pub fn change(pan: &mut Vector, zoom: &mut Option<f32>, fit: &mut bool, event: E
|
||||
&& at.y.is_finite() =>
|
||||
{
|
||||
let old = if *fit { base } else { zoom.unwrap_or(base) };
|
||||
let next = (old * factor).clamp(0.05, 3.);
|
||||
if !old.is_finite() || old <= 0. {
|
||||
return false;
|
||||
}
|
||||
let next = (old * factor).clamp(minimum, 3.);
|
||||
if old == next {
|
||||
return false;
|
||||
}
|
||||
@@ -174,6 +195,51 @@ pub fn change(pan: &mut Vector, zoom: &mut Option<f32>, fit: &mut bool, event: E
|
||||
}
|
||||
}
|
||||
|
||||
fn zoom_label(scale: f32) -> String {
|
||||
let percent = f64::from(scale) * 100.;
|
||||
if !percent.is_finite() || percent <= 0. {
|
||||
return "—".into();
|
||||
}
|
||||
if percent >= 1. {
|
||||
format!("{percent:.0}%")
|
||||
} else if percent >= 0.01 {
|
||||
format!("{percent:.3}%")
|
||||
} else {
|
||||
format!("{percent:.2e}%")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod camera_policy_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn topology_retains_five_percent_floor() {
|
||||
let (mut pan, mut zoom, mut fit) = (Vector::ZERO, Some(0.06), false);
|
||||
assert!(change(
|
||||
&mut pan,
|
||||
&mut zoom,
|
||||
&mut fit,
|
||||
Event::Zoom {
|
||||
factor: 0.1,
|
||||
at: Point::ORIGIN,
|
||||
base: 0.06,
|
||||
}
|
||||
));
|
||||
assert_eq!(zoom, Some(0.05));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiny_zoom_label_is_nonzero_and_changes_with_zoom() {
|
||||
assert_eq!(zoom_label(1.), "100%");
|
||||
assert_eq!(zoom_label(0.05), "5%");
|
||||
assert_eq!(zoom_label(0.00034193), "0.034%");
|
||||
assert_eq!(zoom_label(0.00034193 * 1.25), "0.043%");
|
||||
assert_eq!(zoom_label(1e-7), "1.00e-5%");
|
||||
assert_ne!(zoom_label(f32::from_bits(1)), "0%");
|
||||
}
|
||||
}
|
||||
|
||||
/// Constant-width labelled palette. Arming a tool never reallocates the canvas.
|
||||
pub fn palette<'a>(
|
||||
scope: Scope,
|
||||
|
||||
@@ -379,6 +379,7 @@ fn relative_camera_zoom_keeps_the_cursor_world_point_and_rejects_nonfinite_input
|
||||
fn viewport_ordered_batch_uses_each_event_position_and_cancels_before_camera_motion() {
|
||||
use iced::widget::Space;
|
||||
let scope = Scope {
|
||||
scenario_view: None,
|
||||
document: Id::new_v4(),
|
||||
owner: Id::new_v4(),
|
||||
revision: 2,
|
||||
@@ -438,6 +439,7 @@ pub(crate) fn scope(app: &App) -> Scope {
|
||||
Scope {
|
||||
document: context.document,
|
||||
owner: context.scenario,
|
||||
scenario_view: Some((context.representation, context.visit)),
|
||||
revision: context.revision,
|
||||
epoch: app.camera_epoch,
|
||||
}
|
||||
@@ -446,6 +448,7 @@ pub(crate) fn scope(app: &App) -> Scope {
|
||||
Scope {
|
||||
document: context.document,
|
||||
owner: context.owner,
|
||||
scenario_view: None,
|
||||
revision: context.revision,
|
||||
epoch: app.camera_epoch,
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ struct Input {
|
||||
pan: Option<(mouse::Button, Point)>,
|
||||
space: bool,
|
||||
bounds: Option<Rectangle>,
|
||||
modifiers: keyboard::Modifiers,
|
||||
}
|
||||
impl operation::Focusable for Input {
|
||||
fn is_focused(&self) -> bool {
|
||||
@@ -83,7 +84,11 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Viewport<'_,
|
||||
(s.document, s.owner, s.revision)
|
||||
!= (self.scope.document, self.scope.owner, self.scope.revision)
|
||||
}) {
|
||||
*state = Input::default();
|
||||
let modifiers = state.modifiers;
|
||||
*state = Input {
|
||||
modifiers,
|
||||
..Input::default()
|
||||
};
|
||||
}
|
||||
if state
|
||||
.scope
|
||||
@@ -143,10 +148,29 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Viewport<'_,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let state = tree.state.downcast_mut::<Input>();
|
||||
if let Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) = event {
|
||||
// Physical modifiers outlive focus, busy-state child replacement,
|
||||
// and semantic revisions. Observing these emits no camera command.
|
||||
state.modifiers = *modifiers;
|
||||
self.content.as_widget_mut().update(
|
||||
&mut tree.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if matches!(event, Event::Window(iced::window::Event::Unfocused)) {
|
||||
state.modifiers = keyboard::Modifiers::default();
|
||||
}
|
||||
if shell.is_event_captured() {
|
||||
return;
|
||||
}
|
||||
let state = tree.state.downcast_mut::<Input>();
|
||||
// A traversal operation is applied after this Iced event batch. Keep
|
||||
// its focus witness, but retire keyboard admission immediately.
|
||||
if state.focus_pending && matches!(event, Event::Keyboard(_)) {
|
||||
@@ -334,6 +358,20 @@ impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Viewport<'_,
|
||||
} else {
|
||||
mouse::Cursor::Unavailable
|
||||
};
|
||||
if matches!(event, Event::Mouse(mouse::Event::ButtonPressed(_))) {
|
||||
// A canvas may have been rebuilt while focus/commands were denied.
|
||||
// Restore held (or released) Shift before this new pointer gesture.
|
||||
self.content.as_widget_mut().update(
|
||||
&mut tree.children[0],
|
||||
&Event::Keyboard(keyboard::Event::ModifiersChanged(state.modifiers)),
|
||||
layout,
|
||||
child_cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
self.content.as_widget_mut().update(
|
||||
&mut tree.children[0],
|
||||
event,
|
||||
|
||||
@@ -893,11 +893,14 @@ fn contextual_source_empty_palette_lifeline_cannot_open_a_previous_owner_or_laye
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Second scenario", None)
|
||||
.unwrap();
|
||||
let mut app = App::with_project(p.clone());
|
||||
app.page = Page::Behavior;
|
||||
app.layer = Layer::Oa;
|
||||
app.behavior.active_owner = Some(a);
|
||||
app.selected = a;
|
||||
// Capture the context created by actual navigation, including its visit.
|
||||
// Merely assigning active_owner/selected does not mount a Scenario anymore.
|
||||
let _ = app.update(Message::Select(a));
|
||||
let _ = app.update(Message::Page(Page::Behavior));
|
||||
let context = app.scenario_context().unwrap();
|
||||
assert_eq!(context.scenario, a);
|
||||
assert!(!context.visit.is_nil());
|
||||
let snapshot = app.document.snapshot();
|
||||
let source = app.document.bundle().clone();
|
||||
let begin = |context| scenario::CanvasEvent::BeginOccurrence {
|
||||
context,
|
||||
@@ -908,23 +911,40 @@ fn contextual_source_empty_palette_lifeline_cannot_open_a_previous_owner_or_laye
|
||||
},
|
||||
lifeline: None,
|
||||
};
|
||||
app.behavior.active_owner = Some(b);
|
||||
app.selected = b;
|
||||
let _ = app.update(Message::Select(b));
|
||||
let second = app.scenario_context().unwrap();
|
||||
assert_eq!(second.scenario, b);
|
||||
assert_ne!(second.visit, context.visit);
|
||||
let _ = app.update(Message::ScenarioCanvas(begin(context)));
|
||||
assert!(!app.behavior.has_pending());
|
||||
assert_eq!(app.project(), &p);
|
||||
app.behavior.active_owner = Some(a);
|
||||
app.selected = a;
|
||||
app.layer = Layer::Sa;
|
||||
let _ = app.update(Message::ScenarioCanvas(begin(context)));
|
||||
|
||||
let _ = app.update(Message::Select(a));
|
||||
let before_layer_change = app.scenario_context().unwrap();
|
||||
assert_eq!(before_layer_change.scenario, a);
|
||||
assert_ne!(before_layer_change.visit, context.visit);
|
||||
let _ = app.update(Message::Layer(Layer::Sa));
|
||||
assert_eq!(app.layer, Layer::Sa);
|
||||
assert!(app.scenario_context().is_none());
|
||||
let _ = app.update(Message::ScenarioCanvas(begin(before_layer_change)));
|
||||
assert!(!app.behavior.has_pending());
|
||||
app.layer = Layer::Oa;
|
||||
|
||||
let _ = app.update(Message::Layer(Layer::Oa));
|
||||
let _ = app.update(Message::Select(a));
|
||||
let current = app.scenario_context().unwrap();
|
||||
assert_eq!(current.scenario, a);
|
||||
assert_ne!(current.visit, before_layer_change.visit);
|
||||
// Returning to the same owner/layer must not revive either retired packet.
|
||||
for retired in [context, before_layer_change] {
|
||||
let _ = app.update(Message::ScenarioCanvas(begin(retired)));
|
||||
assert!(!app.behavior.has_pending());
|
||||
}
|
||||
assert!(std::sync::Arc::ptr_eq(&snapshot, &app.document.snapshot()));
|
||||
let _ = app.update(Message::ScenarioCanvas(begin(current)));
|
||||
assert_eq!(app.behavior.pending_owner(), Some(a));
|
||||
assert_eq!(app.project(), &p);
|
||||
assert_eq!(app.document.bundle(), &source);
|
||||
assert!(!app.document.can_undo());
|
||||
assert!(!app.document.can_undo() && !app.document.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -10,32 +10,6 @@ use serde::{Deserialize, Serialize};
|
||||
const PAGE_SIZE: usize = 6;
|
||||
pub const NAME_INPUT: &str = "behavior-creation-name";
|
||||
|
||||
// A focused text input consumes Escape. Preserve the application's modal
|
||||
// priority by emitting its ordinary Escape message from this narrow bridge.
|
||||
pub fn subscription(active: bool) -> iced::Subscription<()> {
|
||||
if active {
|
||||
iced::event::listen_with(captured_escape)
|
||||
} else {
|
||||
iced::Subscription::none()
|
||||
}
|
||||
}
|
||||
|
||||
fn captured_escape(
|
||||
event: iced::Event,
|
||||
status: iced::event::Status,
|
||||
_: iced::window::Id,
|
||||
) -> Option<()> {
|
||||
(status == iced::event::Status::Captured
|
||||
&& matches!(
|
||||
event,
|
||||
iced::Event::Keyboard(iced::keyboard::Event::KeyPressed {
|
||||
key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
|
||||
..
|
||||
})
|
||||
))
|
||||
.then_some(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Family {
|
||||
Sequence,
|
||||
|
||||
@@ -18,59 +18,11 @@ fn begin(app: &mut App, layer: Layer, family: Family, name: &str) {
|
||||
send(app, Event::Name(name.into()));
|
||||
}
|
||||
|
||||
fn focused_escape() -> Message {
|
||||
use iced::advanced::{Layout, Shell, layout, widget};
|
||||
use iced::keyboard::{self, key::Named};
|
||||
let mut input: iced::Element<'_, (), iced::Theme, ()> = text_input("Name", "Unfinished name")
|
||||
.id(NAME_INPUT)
|
||||
.on_input(|_| ())
|
||||
.into();
|
||||
let mut tree = widget::Tree::new(input.as_widget());
|
||||
let size = iced::Size::new(300., 40.);
|
||||
let node =
|
||||
input
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree, &(), &layout::Limits::new(iced::Size::ZERO, size));
|
||||
tree.state
|
||||
.downcast_mut::<iced::widget::text_input::State<()>>()
|
||||
.focus();
|
||||
let event = iced::Event::Keyboard(keyboard::Event::KeyPressed {
|
||||
key: keyboard::Key::Named(Named::Escape),
|
||||
modified_key: keyboard::Key::Named(Named::Escape),
|
||||
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::Escape),
|
||||
location: keyboard::Location::Standard,
|
||||
modifiers: keyboard::Modifiers::empty(),
|
||||
text: None,
|
||||
repeat: false,
|
||||
});
|
||||
let mut messages = Vec::new();
|
||||
let mut shell = Shell::new(&mut messages);
|
||||
input.as_widget_mut().update(
|
||||
&mut tree,
|
||||
&event,
|
||||
Layout::new(&node),
|
||||
iced::mouse::Cursor::Unavailable,
|
||||
&(),
|
||||
&mut iced::advanced::clipboard::Null,
|
||||
&mut shell,
|
||||
&iced::Rectangle::new(iced::Point::ORIGIN, size),
|
||||
);
|
||||
assert!(shell.is_event_captured());
|
||||
assert_eq!(
|
||||
captured_escape(
|
||||
event.clone(),
|
||||
iced::event::Status::Ignored,
|
||||
iced::window::Id::unique()
|
||||
),
|
||||
None
|
||||
);
|
||||
captured_escape(
|
||||
event,
|
||||
iced::event::Status::Captured,
|
||||
iced::window::Id::unique(),
|
||||
)
|
||||
.unwrap();
|
||||
Message::Escape
|
||||
fn focused_escape(app: &App) -> Message {
|
||||
let mut messages = crate::app::escape::tests::focused_input_messages(app);
|
||||
assert_eq!(messages.len(), 1);
|
||||
assert!(matches!(messages[0], Message::Escape));
|
||||
messages.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -94,12 +46,12 @@ fn app_first_captured_escape_dismisses_file_or_pending_overlay_before_creation()
|
||||
} else {
|
||||
app.pending = Some(Pending::Walkthrough);
|
||||
}
|
||||
let _ = app.update(focused_escape());
|
||||
let _ = app.update(focused_escape(&app));
|
||||
assert!(app.file_prompt.is_none());
|
||||
assert!(app.pending.is_none());
|
||||
assert_eq!(app.behavior.recovery_snapshot().unwrap(), raw);
|
||||
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
|
||||
let _ = app.update(focused_escape());
|
||||
let _ = app.update(focused_escape(&app));
|
||||
assert!(!app.behavior.has_pending());
|
||||
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
|
||||
assert!(!app.document.can_undo());
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user