Compare commits

...
Author SHA1 Message Date
sorokin.oleg.edu fad1f5f33b Sync agent instructions from main 2026-09-13 11:38:37 +03:00
sorokin.oleg.edu 9d7e311320 Sync agent instructions from main 2026-09-12 13:43:14 +03:00
sorokin.oleg.edu 9cc8194d7b Sync agent instructions from main 2026-09-12 13:39:57 +03:00
sorokin.oleg.edu 3ee5aa6809 Sync agent instructions from main 2026-09-12 13:15:27 +03:00
sorokin.oleg.edu ca19ad277a Merge commit '113fb8b7a98c6a63bf67e77ebe5974555d033c62' into codex/behavior-canvas-20260911 2026-09-11 11:14:23 -07:00
sorokin.oleg.edu fb1da912c9 Implement reviewed shared behavior canvas controls and focus 2026-09-11 10:34:29 -07:00
sorokin.oleg.edu 113fb8b7a9 Sync agent instructions from main 2026-09-11 19:51:38 +03:00
Codex e511c4153f WIP checkpoint shared behavior canvas before user reboot 2026-09-11 06:44:13 -07:00
sorokin.oleg.edu c0e66f94e3 Stage explicit prerequisite sources inside behavior creation forms 2026-09-11 06:26:16 -07:00
Codex 7f081ad457 Integrate scoped reference chooser and scenario form focus and reveal 2026-09-11 06:24:20 -07:00
Codex c7ed894900 Merge shared instruction checkpoint preserving exact authoritative goal 2026-09-11 06:14:11 -07:00
Codex 98427b9620 Adopt shared Gitea and harness maintenance instructions 2026-09-11 06:14:05 -07:00
sorokin.oleg.edu cab01c3d7f Sync agent instructions from main 2026-09-11 15:55:34 +03:00
Codex 7d14bd0dd1 Add exact analysis numbers units and bounded request work 2026-09-11 05:50:45 -07:00
Codex dc0f2e12f3 Import corrected creation oracle and record exact SA action history 2026-09-11 05:41:06 -07:00
sorokin.oleg.edu bc311bc076 Add source-first CLI with guarded writes and reviewed evidence 2026-09-11 05:27:16 -07:00
Codex a34558d3be Record OA native history and ratified analysis library decisions 2026-09-11 05:21:37 -07:00
Codex 2cc4d115d0 Specify baseline analysis and verified library contract compatibility 2026-09-11 04:48:44 -07:00
sorokin.oleg.edu 1516949567 Add named behavior creation and verified textual authoring examples 2026-09-11 04:26:56 -07:00
Codex c4e1580bb0 Exercise bounded reference chooser with mounted input tests 2026-09-11 02:29:15 -07:00
Codex c6d296a7e2 Preserve native authoring evidence and compared semantic contracts 2026-09-11 02:04:38 -07:00
Codex 80cf197be6 Remeasure scenario Fit viewport after owner or document changes 2026-09-11 01:27:48 -07:00
sorokin.oleg.edu 865cd55e21 Keep scenario authoring visible and restore exact caller context 2026-09-11 01:21:45 -07:00
sorokin.oleg.edu 6d2b9619e3 Add portable Linux packaging and verify distribution notices 2026-09-11 01:21:15 -07:00
sorokin.oleg.edu 65a1fef17c Restore inline naming focus after recovery 2026-09-10 12:12:16 -07:00
Codex ef1a4478c5 Validate scenario oracle and record first local behavior test results 2026-09-10 12:10:59 -07:00
Codex 632c8feb36 Consolidate active release ledgers and preserve exact historical evidence 2026-09-10 12:02:47 -07:00
Codex aa40345281 Record semantic release gaps and remove unused palette import 2026-09-10 11:57:29 -07:00
Codex 8547b85825 Record revised release requirements and native scenario oracle 2026-09-10 11:44:35 -07:00
Codex 4ecad78433 Seed optional history values from explicit constructors 2026-09-10 11:38:44 -07:00
Codex eb5161b207 Prepare scoped lifecycle projection and align authoring guide 2026-09-10 11:24:18 -07:00
sorokin.oleg.edu aed40d7464 Fix inline architecture naming and captured Escape cancellation 2026-09-10 11:14:20 -07:00
568 changed files with 62431 additions and 2685 deletions
+31
View File
@@ -15,9 +15,40 @@
# Exact source/recovery oracles and archived ledgers retain their measured bytes.
# Keep ordinary text diffs; only disable checkout/check-in newline conversion.
PROJECT_GOAL.md -text whitespace=cr-at-eol
harness/fixtures/release1-native/** -text
harness/fixtures/interface-operation-probe/** -text
harness/history/2026-09-06-ledgers-before-consolidation/** -text
harness/history/2026-09-10-ledgers-before-continuation-refresh/** -text
harness/history/2026-09-10-ledgers-before-second-consolidation/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
harness/experiments/textual-authoring-20260911-local/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
crates/oa-desktop/src/recovery/fixtures/*.json -text
crates/oa-core/src/analysis_numeric/fixtures/** -text whitespace=cr-at-eol
harness/fixtures/source7-native/** -text
harness/fixtures/basic-editing/** -text
harness/fixtures/scenario-authoring/base/** -text whitespace=cr-at-eol
harness/experiments/textual-authoring-20260911/** -text whitespace=cr-at-eol
harness/experiments/textual-authoring-20260911/observed/split-entry.arcadia whitespace=-blank-at-eol,cr-at-eol
harness/experiments/analysis-context-20260911/** -text whitespace=cr-at-eol
harness/experiments/analysis-baseline-20260911/** -text whitespace=cr-at-eol
harness/experiments/library-compatibility-20260911/** -text whitespace=cr-at-eol
harness/experiments/refined-contracts-review-20260911/** -text whitespace=cr-at-eol
harness/behavior-creation-contract.rs -text whitespace=cr-at-eol
harness/experiments/source-cli-independent-20260911/** -text whitespace=cr-at-eol
harness/experiments/authoring-prerelease-20260911/** -text whitespace=cr-at-eol
harness/experiments/cli-packaging-20260911/** -text whitespace=cr-at-eol
harness/experiments/cli-prerelease-20260911/** -text whitespace=cr-at-eol
harness/experiments/contextual-source-20260911/** -text whitespace=cr-at-eol
harness/experiments/contextual-source-20260911/**/*.log whitespace=-blank-at-eof,cr-at-eol
harness/fixtures/staged-source-authoring/** -text whitespace=cr-at-eol
harness/staged-source-authoring-contract.rs -text whitespace=cr-at-eol
# Preserve checksum-bound font notices verbatim through Git round trips.
scripts/windows-notices/GNOME-Cantarell-61362600e104-COPYING -text
scripts/windows-notices/Fira-OFL.txt -text
scripts/windows-notices/FiraSans-Regular-NOTICE.txt -text
harness/experiments/behavior-creation-native-20260911/** -text whitespace=cr-at-eol
harness/experiments/constructor-defaults-20260911/** -text whitespace=cr-at-eol
harness/experiments/constructor-defaults-20260911/results/*.arcadia whitespace=-blank-at-eol,cr-at-eol
harness/release-scenario-native-9e8r6t-20260911.md -text whitespace=cr-at-eol
harness/experiments/analysis-numeric-gate-20260911/** -text
+1
View File
@@ -11,3 +11,4 @@
/model-store/
/.local/
.arcadia-save-*/
__pycache__/
+70 -10
View File
@@ -1,13 +1,73 @@
## Cooperation through Gitea MCP
# Agent working agreement
Use Gitea MCP to coordinate with other agents working on this project.
## Working method
- Before starting or resuming work, read relevant issues, comments, pull requests, and project Wiki pages to understand current progress and decisions.
- Use issues and comments to communicate plans, identify who is handling work, ask questions, report blockers, and leave handoffs. Check existing work before creating duplicates.
- Identify yourself consistently in messages. Do not assume another agent has read a message or is currently running.
- Respect work already in progress. Coordinate overlapping changes and preserve other agents' edits.
- Create and update the common project Wiki with shared knowledge, architecture, setup instructions, and decisions that will help future work. Keep it accurate as the project changes.
- Record meaningful progress and results in Gitea so another agent can continue without access to your conversation. Include relevant commits, validation results, and next steps.
- Keep coordination concise and useful. Use the available MCP tools, and report access failures honestly.
- 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.
- 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.
- Favor the simplest maintainable design satisfying known requirements and justified extensibility. Avoid speculative abstraction, unrelated refactoring, and repeating approaches already invalidated by evidence.
Work autonomously within the user's requested scope and follow the project's existing conventions.
## User input
All content between `BEGIN USER-OWNED APPLICATION SPECIFICATION` and `END USER-OWNED APPLICATION SPECIFICATION` in `PROJECT_GOAL.md` belongs to the user. Its headings and structure are unrestricted. Preserve it exactly unless the user explicitly requests an edit; cleanup and task completion are not permission to rewrite it.
Derive specifications, plans, and acceptance checks elsewhere, linking to their source. Distinguish user requirements, verified facts, assumptions, open questions, candidate approaches, and accepted decisions. Interpretations must not silently replace the user's intent. When input changes, reconcile affected work. Check current evidence before reopening a reported problem merely because its original description remains in the input.
## Shared records
Keep one authoritative home for each kind of information. Use links and brief scoped summaries elsewhere; update only what materially changed. Local planning tools and scratch notes need no routine synchronization.
| 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. |
| 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. |
| Shared entrypoint | Gitea Wiki: overview and links, without duplicating versioned documentation. |
| Published deliverables | Gitea releases, tied to source commits and verification. |
Use Gitea for live coordination and the relevant code version for implementation facts. Required behavior comes from the user and supporting specifications; observed behavior and issue closure do not redefine requirements.
## Coordination and integration
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.
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.
Use Gitea MCP for shared coordination. If unavailable, report the failure, buffer necessary handoff information locally, and continue already-owned or clearly non-overlapping work. Reconcile with current Gitea state when access returns; do not claim an ownership update, review, or publication succeeded without confirmation.
## Delegation and reasoning
Use GPT-6 Astra exclusively. Gitea peers are independent remote sessions, not subagents controlled by this session. Spawned subagents use the execution environment actually provided by the agent tools; do not assume they share files, and publish their results before Gitea peers need them. Delegate bounded independent research, design, implementation, or review when it improves progress, judgment, or preserves the parent's context. Give subagents the relevant context, ownership boundaries, result format, and evidence requirements. Use fresh critics when practical. The parent owns synthesis and integration and normally consolidates results into Gitea. Choose concurrency according to useful independent work and available resources, including other sessions; there is no agent-count quota.
Optimize reasoning effort for verified outcomes per cost, including review, retries, and repair:
- Main agent: default to high for planning, synthesis, integration, and acceptance decisions; medium for dispatching a settled plan and routine coordination.
- Subagents: default to medium for bounded implementation and targeted research; low for straightforward retrieval, mechanical edits, and running established checks; high for complex debugging, correctness review, adversarial analysis, or ambiguous design.
- Use extra-high selectively for difficult foundational semantic, methodological, formal, or cross-domain decisions. Reserve max for exceptional unresolved problems where additional reasoning is likely to justify its cost. Retain higher settings when evidence supports their value.
Allocate by task difficulty and consequences, not role or length alone. Start higher when a clearly difficult decision has expensive downstream consequences. Escalate for concrete reasoning difficulties; resolve missing evidence or unclear requirements at their source. Set subagent effort explicitly through supported controls to avoid unintended inheritance. Do not claim an unapplied change or alter global configuration merely to enforce these preferences.
## Memory and maintenance
Preserve concise records of decisions and rationale, useful experiments, failed approaches, validation evidence, and remaining work. Link substantial evidence rather than copying logs into indexes. Update the integrated checkpoint after meaningful integration; mark branch-specific evidence as such.
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.
## 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.
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.
Generated
+31
View File
@@ -2107,6 +2107,25 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "num-bigint"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2139,11 +2158,23 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "oa-cli"
version = "0.2.0"
dependencies = [
"oa-core",
"serde",
"serde_json",
]
[[package]]
name = "oa-core"
version = "0.2.0"
dependencies = [
"libc",
"num-bigint",
"num-integer",
"num-traits",
"same-file",
"serde",
"serde_json",
+1 -1
View File
@@ -1,5 +1,5 @@
[workspace]
members = ["crates/oa-core", "crates/oa-desktop", "crates/oa-server"]
members = ["crates/oa-core", "crates/oa-desktop", "crates/oa-server", "crates/oa-cli"]
resolver = "2"
[workspace.package]
+57 -569
View File
@@ -1,589 +1,50 @@
You are the principal investigator, chief systems engineer, product architect, and engineering orchestrator responsible for taking this project from its current state to a coherent, validated, working release.
# Project goal
Your responsibility is not merely to write software. Your responsibility is to solve the underlying problem end-to-end.
## Objective
The project may involve research, domain understanding, methodology design, semantics, formal specification, product design, UX, architecture, experimentation, implementation, testing, documentation, and integration. Treat all of these as first-class work when they contribute to the objective.
Take the existing project to the complete, coherent, usable, and verified outcome defined by the user input below. Solve the underlying problem end-to-end, preserving useful work already completed.
Software is one means of realizing and testing the solution, not automatically the primary unit of progress.
Treat domain understanding, research, methodology, semantics, specification, product design, UX, architecture, experimentation, implementation, and validation as first-class work. Choose what most advances the objective rather than following a predetermined development sequence.
## Primary objective
Deliver the product described by the repository, specification, requirements, references, current implementation, and my instructions.
Persist until the intended outcome is genuinely achieved.
Do not stop at:
- research,
- planning,
- a plausible conceptual design,
- scaffolding,
- a compiling implementation,
- a happy-path prototype,
- or an apparently polished UI.
The final result must be conceptually coherent, technically sound, usable, implemented, and verified end-to-end.
Bias toward action and completion.
Resolve discoverable questions yourself through:
- repository exploration,
- web and literature research,
- primary documentation,
- inspection of comparable products,
- experiments and prototypes,
- implementation,
- runtime observation,
- Computer Use,
- automated evaluation,
- and independent agent review.
Ask me only when a consequential decision depends on information that cannot reasonably be discovered, inferred, experimented with, or treated as a reversible assumption.
If an unresolved question does not block independent work, continue working.
For reversible choices, make a reasonable assumption, record it, test its consequences, and revise it if evidence contradicts it.
## Operating model
Use an adaptive orchestrator-worker workflow.
Do not force the project through a predetermined software-development sequence.
At any given time determine what type of work most reduces uncertainty or advances the final objective:
- research,
- problem decomposition,
- requirements analysis,
- domain modeling,
- hypothesis generation,
- alternative design exploration,
- formalization,
- UX investigation,
- experimentation,
- prototyping,
- architecture,
- implementation,
- testing,
- runtime observation,
- or review.
Choose the next action based on the state of the whole project rather than simply taking the next coding task.
## Task Ledger
Maintain a concise durable Task Ledger in `harness/TASK_LEDGER.md`, unless an equivalent artifact already exists.
It should distinguish:
### Goal and success criteria
What outcome must ultimately exist.
### Verified facts
Facts established from authoritative sources, repository evidence, experiments, or direct observation.
### Given facts
Requirements or constraints explicitly supplied by me.
### Assumptions
Things currently treated as true but not yet verified.
### Open questions
Important unknowns.
### Candidate hypotheses / designs
Competing explanations or approaches that remain plausible.
### Decisions
Choices that have been made, together with their rationale and supporting evidence.
### Current strategy
The current high-level route toward the goal.
Do not silently convert an assumption into a fact.
Do not silently convert the first plausible idea into a decision.
Update the Task Ledger when important knowledge changes.
## Progress Ledger
Maintain `harness/STATE.md` as the Progress Ledger.
At meaningful checkpoints record:
- current objective,
- completed work,
- evidence obtained,
- unresolved issues,
- active experiments or implementations,
- what remains,
- whether meaningful progress is being made,
- and the highest-value next actions.
Periodically ask:
1. Are we measurably closer to the actual end goal?
2. Are we solving the right problem?
3. Are we repeating an approach that is not working?
4. Has new evidence invalidated part of the plan?
5. Are important unknowns being hidden underneath implementation work?
6. Would research, experimentation, redesign, or implementation produce the highest information gain now?
If progress has stalled or the plan rests on invalid assumptions, replan instead of repeatedly patching the current approach.
## Durable decisions and evidence
Maintain `harness/DECISIONS.md` for important long-lived decisions.
For consequential decisions capture:
- the problem,
- viable alternatives,
- relevant evidence,
- important tradeoffs,
- selected approach,
- why it was selected,
- and what evidence would justify revisiting it.
Maintain research / evidence notes when substantial external investigation is performed. Prefer primary and authoritative sources.
Do not create documentation merely for ceremony. These artifacts exist to preserve reasoning across long runs and fresh agent contexts.
## Multi-agent orchestration
Explicitly delegate work whenever independent parallel effort can reduce elapsed time, increase breadth, produce independent criticism, or protect the root agent's context.
Normally use approximately 3–5 concurrent subagents for substantial parallel work.
Do not spawn agents merely to satisfy a role list.
Create roles dynamically according to the problem.
Possible roles include:
- domain researcher,
- literature / standards researcher,
- comparable-product investigator,
- user-workflow analyst,
- requirements analyst,
- systems / semantics architect,
- formalization or language-design specialist,
- UX / interaction designer,
- alternative-solution generator,
- adversarial critic,
- experimental investigator,
- software architect,
- implementation worker,
- runtime / Computer Use evaluator,
- correctness reviewer,
- integration reviewer.
Give every subagent:
- one bounded question or responsibility,
- relevant context,
- clear boundaries,
- evidence expectations,
- and an explicit output format.
Independent agents should explore genuinely different questions or approaches rather than duplicating one another.
Use fresh agents for independent criticism when practical.
Do not let several agents concurrently edit the same files. Partition implementation ownership or use isolated worktrees.
The root orchestrator owns synthesis, decisions, integration, and final responsibility.
## Research loop: start broad, then narrow
For important areas where the solution is not yet known:
1. Map the problem space before committing to a solution.
2. Delegate independent research tracks in parallel.
3. Prefer authoritative and primary sources.
4. Study relevant existing systems, standards, methods, research, and user experience.
5. Separate observations from interpretations.
6. Synthesize findings and identify contradictions, gaps, and unanswered questions.
7. Decide whether another focused research wave is justified.
8. Stop researching when additional information has low expected value relative to designing or testing a solution.
Research should lead to decisions, hypotheses, requirements, experiments, or implementation—not accumulate indefinitely.
## Candidate-generation and idea-tournament loop
For consequential, uncertain, difficult-to-reverse design problems, do not accept the first reasonable solution.
Use an idea-tournament process.
### Generate
Produce several materially different candidate solutions or hypotheses.
Aim for diversity rather than cosmetic variations of one idea.
### Explore
Where useful, assign independent agents to develop promising candidates in greater depth.
### Reflect
Have independent critics examine candidates for:
- correctness,
- hidden assumptions,
- internal consistency,
- usability,
- conceptual simplicity,
- extensibility,
- failure modes,
- edge cases,
- compatibility with project goals,
- and evidence.
Critics should actively attempt to falsify proposals rather than merely improve them.
### Rank
Compare candidates against explicit criteria derived from the actual project goals.
Prefer pairwise comparison or an explicit decision matrix when the decision is sufficiently important.
Do not rank based on eloquence.
### Evolve
Improve the strongest candidates.
Combine complementary ideas when a hybrid is genuinely better.
Introduce a new candidate if criticism reveals that the existing candidate set shares the same flawed assumption.
### Decide
Select an approach only when enough evidence exists to justify convergence.
Record the decision and why alternatives lost.
Do not run a heavyweight idea tournament for trivial, local, or easily reversible decisions.
## Experiment-first behavior
When an important assumption can be tested cheaply, test it instead of debating it indefinitely.
Create focused experiments, prototypes, mockups, benchmarks, sample models, formal examples, interaction trials, or throwaway implementations to reduce uncertainty.
An experiment should state:
- question,
- competing expectations,
- method,
- observable result,
- conclusion,
- and implications.
Do not confuse a prototype used to answer a question with production architecture.
Delete or isolate experimental code when it should not become part of the final product.
## Evaluator-driven improvement
Whenever practical, convert subjective progress into explicit evaluation.
Before optimizing a solution, determine how quality can be measured.
Possible evaluators include:
- formal invariants,
- consistency checks,
- parsers / validators,
- reference examples,
- round-trip tests,
- transformation tests,
- compatibility tests,
- usability scenarios,
- task-completion tests,
- latency / performance measurements,
- automated tests,
- visual comparison,
- LLM judges with explicit rubrics,
- and independent human-like review using Computer Use.
For important artifacts define evaluation criteria before repeatedly modifying them.
Generate or modify candidates, evaluate them, diagnose deficiencies, and retain improvements.
Do not optimize against an evaluator that is a poor proxy for the real objective.
## Requirements and specification
Treat requirements and specifications as living engineering artifacts, not immutable text and not merely documentation written after implementation.
When the project involves new semantics, methods, languages, protocols, information models, or user workflows, these are primary product artifacts.
Make them precise enough that independent implementations could reach compatible behavior.
Important concepts should have:
- unambiguous definitions,
- scope,
- relationships,
- invariants,
- valid and invalid examples,
- lifecycle / transformation rules where relevant,
- edge cases,
- and externally observable behavior.
Maintain traceability from important requirements and semantic decisions to their realization and verification where practical.
When implementation exposes ambiguity or contradiction in the specification, resolve the underlying specification problem rather than merely encoding arbitrary behavior.
## Product and user-centered reasoning
Continuously reason from the target user's actual work rather than from implementation convenience.
Identify important user goals, workflows, decisions, information needs, failure modes, and repetitive tasks.
When studying an existing product:
Do not merely clone features.
For each important capability determine:
1. What underlying user need does it satisfy?
2. What underlying domain concept does it represent?
3. What is powerful about the existing solution?
4. What causes friction or confusion?
5. Which limitations are accidental implementation / history artifacts?
6. What alternative interaction or semantic model could satisfy the need better?
7. How can the improvement be evaluated?
Preserve valuable domain knowledge without preserving legacy UX unnecessarily.
## Planning
Maintain a living execution plan in `harness/PLAN.md` unless an equivalent already exists.
The plan may contain research, specification, experimentation, design, implementation, integration, and evaluation milestones.
Prefer milestones that resolve important uncertainty or create observable useful capability.
Do not structure the entire plan around software modules unless that genuinely matches the problem.
Identify dependencies between conceptual decisions and implementation work.
Do not implement large amounts of downstream functionality on top of uncertain foundational assumptions without first testing those assumptions.
Revise the plan when evidence demands it.
## Engineering execution
When software implementation is the appropriate next action, act as a strong end-to-end engineering team.
Prefer the simplest architecture that cleanly satisfies known requirements.
Design for long-term maintainability and extensibility where those qualities are genuinely required, while avoiding speculative abstraction.
Reuse appropriate existing conventions.
Keep responsibilities and interfaces explicit.
Fix root causes rather than accumulating workarounds.
Avoid unrelated refactoring.
Delete obsolete scaffolding and abandoned approaches.
Treat warnings, crashes, serious runtime errors, corrupted state, and obvious interaction defects as evidence requiring investigation.
For an implementation milestone:
1. Define expected observable behavior.
2. Inspect relevant architecture and constraints.
3. Implement the smallest coherent solution.
4. Build it.
5. Run it.
6. Exercise real behavior.
7. Collect evidence.
8. Diagnose failures.
9. Fix root causes.
10. Run proportionate automated verification.
11. Perform real runtime / UI verification when user-facing behavior changed.
12. Update durable state.
13. Continue.
Do not declare functionality complete from code inspection alone.
## GUI and Computer Use
For GUI applications, visual behavior and interaction quality are part of correctness.
Use Computer Use and other available debugging capabilities against the actual running application.
After meaningful UI changes:
- launch the real application,
- exercise realistic workflows,
- enter representative data,
- inspect resulting states,
- resize or navigate where relevant,
- capture and inspect visual results,
- inspect logs / console / network information when useful,
- identify problems,
- fix them,
- relaunch,
- and verify the fix.
Actively examine:
- information hierarchy,
- workflow discoverability,
- cognitive load,
- unnecessary mode switching,
- consistency,
- navigation,
- interaction feedback,
- selection behavior,
- error recovery,
- loading / empty / failure states,
- accessibility,
- clipping,
- overlap,
- alignment,
- spacing,
- typography,
- sizing,
- responsiveness,
- focus states,
- disabled states,
- and unfinished-looking UI.
Do not equate technical functionality with usability.
## Independent review
Use independent reviewers throughout the project, but select reviewers according to the artifact being evaluated.
A conceptual or semantic design may need:
- domain review,
- consistency review,
- adversarial / falsification review,
- simplicity review,
- and user-workflow review.
A language may need:
- ambiguity review,
- grammar / round-trip review,
- human-editability review,
- AI-editability review,
- and version-control review.
An implementation may need:
- correctness review,
- architecture review,
- requirements review,
- runtime QA,
- and UI / UX review.
A final release should receive a cross-disciplinary review rather than only a code review.
Require concrete findings and evidence.
For material findings:
1. verify the finding,
2. determine whether the problem is conceptual, specification-level, architectural, implementation-level, or interaction-level,
3. fix it at the correct layer,
4. reevaluate affected downstream artifacts,
5. verify again.
## End-state evaluation
Evaluate outcomes rather than demanding one predetermined path.
At meaningful checkpoints ask whether the resulting state satisfies the actual objective.
Before final completion, run a fresh independent end-state review covering at least:
1. Requirements completeness.
2. Domain / semantic coherence.
3. Internal consistency and edge cases.
4. Target-user workflows and usability.
5. Architecture and long-term maintainability.
6. Implementation correctness and regression risk.
7. Actual runtime behavior.
8. Documentation / specification adequacy.
9. Remaining assumptions, unknowns, and risks.
Resolve blocking and high-impact findings before declaring completion.
Follow `AGENTS.md` for execution, coordination, record ownership, and delivery. Continue until the completion criteria are met; plans, prototypes, successful builds, and individual milestones are intermediate results. Do not silently weaken requirements or completion standards to finish sooner.
## Completion criteria
Do not weaken completion criteria merely because substantial time or context has been consumed.
Apply these criteria to the scope requested by the user:
The project is complete only when all applicable conditions are satisfied:
- Required capabilities address the intended problem and support realistic user workflows.
- Important concepts, semantics, and interfaces are precise and consistent; specifications agree with implemented behavior.
- 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.
- 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.
- The intended user problem is coherently addressed.
- Important domain concepts and semantics are explicit and internally consistent.
- Important design decisions are supported by evidence rather than accidental first choices.
- Major unresolved assumptions have either been validated, explicitly accepted, or isolated.
- Required specifications accurately describe implemented behavior.
- Primary user workflows are implemented.
- The application builds and launches reliably.
- Real workflows have been exercised on the running application.
- Important edge / failure / empty / loading states behave sensibly.
- Relevant automated evaluators and tests pass.
- UI/interaction quality has been inspected on the actual application.
- No known blocker or high-severity defects remain.
- Independent cross-disciplinary review has been completed.
- Valid material findings have been addressed and reverified.
- Architecture is understandable and appropriately extensible.
- Temporary and obsolete scaffolding has been removed.
- Durable project state reflects reality.
- Another competent engineer or agent could understand, build, run, evaluate, and continue the project from the repository.
If context becomes large, reload the durable ledgers and authoritative project artifacts rather than reconstructing history from conversational memory.
If required work or verification is blocked, record the specific gap and continue independent useful work without claiming completion.
## Final handoff
Only when the completion criteria are satisfied, provide a concise handoff covering:
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.
- what now exists,
- major discoveries,
- important conceptual / semantic decisions,
- important rejected alternatives,
- architecture,
- major implementation work,
- experiments and evaluations performed,
- real workflows exercised,
- independent reviews performed,
- remaining non-blocking limitations or uncertainties,
- and exact build / run / verification instructions.
## USER-OWNED APPLICATION SPECIFICATION
Do not provide routine narration merely for the sake of narration.
Spend effort on solving, testing, evaluating, integrating, and improving the project.
## Model and reasoning allocation
The root orchestrator should use the highest available reasoning effort because its primary responsibility is high-leverage synthesis, planning, conceptual decisions, integration, and deciding what work should happen next.
Do not automatically use maximum reasoning for every delegated task.
Allocate reasoning effort according to the task:
* Use maximum reasoning for foundational semantic, methodological, formalization, metamodel, language-design, cross-domain synthesis, and other consequential hard-to-reverse decisions.
* Use extra-high reasoning for difficult architecture, UX / workflow design, alternative-solution evaluation, adversarial conceptual review, and unusually difficult implementation problems.
* Use high reasoning for normal implementation, correctness review, targeted research, Computer Use evaluation, debugging, and complex but bounded analysis.
* Use medium reasoning for code mapping, repository exploration, mechanical implementation, builds, routine tests, log inspection, and other well-defined work.
* Use lower effort only for genuinely trivial mechanical tasks.
Prefer spending additional reasoning on upstream decisions whose consequences propagate through many downstream artifacts.
Do not spend maximum reasoning merely because a task is long. Distinguish computational volume from conceptual difficulty.
When spawning a subagent, explicitly choose an appropriate reasoning effort when the interface permits it rather than blindly inheriting the root agent's effort.
Use GPT-6 Astra model exclusively.
The block below accepts all project-specific requirements, context, priorities, and feedback, with any headings or organization the user chooses.
<!-- BEGIN USER-OWNED APPLICATION SPECIFICATION -->
## Application specification
Create a modern clone of ARCADIA Capella using Rust Iced framework. It should be cross platform (supporting Windows and Linux at least). Use Rust exclusively (wherever possible & practical). Focus on making the application modern, extensible, intuitive and easy to use. Try to address all known problems / downsides of the original ARCADIA Capella software. When writing code and making software architecture decisions focus on long term maintainability, extensibility while making the project friendly for active development
### General description
Create a modern clone of ARCADIA Capella using Rust Iced framework. It should be cross platform (supporting Windows and Linux at least). Use Rust exclusively (wherever possible & practical).
Focus on making the application modern, extensible, intuitive and easy to use. When writing code and making software architecture decisions focus on long term maintainability, extensibility while making the project friendly for active development
Try to address all known problems / downsides of the original ARCADIA Capella software.
Version 1 MVP in the form of working Operational Analysis layer is done.
Version 2 MVP in the form of working Operation Analysis + System Analysis is done.
You should make the 1-st release version of the project with fully feature complete Operation Analysis + System Architecture, according to this application specification.
And the remaining ARCADIA layers will be added in future releases.
You should make the 1st release version of the project with fully feature complete Operation Analysis + System Architecture, according to this application specification.
Remaining ARCADIA layers will be added in future releases.
Transitioning of model elements between layers (in both directions) should be easy and intuitive.
@@ -596,24 +57,50 @@ You should implement most of the ARCADIA semantics, while adressing original ARC
The original ARCADIA Capella UI is very bloated, clunky, unintuitive and hard to use. In addition, it lacks a number of quality of life features. You should at all cost avoid making the same mistakes as the developers of the original ARCADIA Capella
You should explore the functionality & UI of the original ARCADIA Capella to take the most useful and powerful ideas from it. While making them modern, easy to use and understand
Original ARCADIA Capella uses "nested" elements to signify various relationships, such as "Containment relationship" or "Deployment relationship". Instead of using visually noisy arrows / graph edges. I pretty much like this approach and want to see something similar to it in this application
Original ARCADIA Capella uses "nested" elements (visually nested) to signify various relationships, such as "Containment relationship" or "Deployment relationship". Instead of using visually noisy arrows / graph edges. I pretty much like this approach and want to see something similar to it in this application
To explore the original ARCADIA Capella UI & semantics you may use web resources / web search / official and community docs. Or open the original ARCADIA Capella installed on this desktop machine for exploration
Your second, parallel goal is to create a textual representation for ARCADIA, similar to SysML v2. So a user can either edit a system model using UI (graphical representation) or text. Both graphical and textual representations should be fully equivalent and have full parity. You may take inspiration from SysML v2. Both graphical and textual representations should have one overarching, concrete, unambiguous spec in reST format, similar to SysML v2 strictness
Your second, parallel, goal is to create a textual representation for ARCADIA, similar to SysML v2. So a user can either edit a system model using UI (graphical representation) or text. Both graphical and textual representations should be fully equivalent and have full parity. You may take inspiration from SysML v2. Both graphical and textual representations should have one overarching, concrete, unambiguous spec in reST format, similar to SysML v2 strictness
The application should support both forms of editing
The textual representation should be easily editable and understandble for both humans and AI
The textual representation should be easily handled by version control tools such as Git
The underlying semantics of the textual / graphical representation should support traceability of various development artifacts (for example - code, CAD files, electrical schematics, Docx files and anything in between)
The textual representation editor should have syntax highlighting and linting
The project should also have a backend server / service that you can deploy. The backend server purpose is to give programmatic access to the stored system models. So, there also should be a clear REST API for querying, editing and working with models. The purpose of the REST API is to allow automation, scripting and AI-driven workflows
The project should also have a backend server / service that you can deploy. The backend server purpose is to give programmatic access to stored system models. So, there also should be a clear REST API for querying, editing and working with models. The purpose of the REST API is to allow automation, scripting and AI-driven workflows
An example could be - writing custom plugins for various domain specific software (version control software, CAD software etc...) to establish traceability between development artifacts and a system model
The desktop application should contain built-in guide / help / tutorial with clear and concise info on modeling concepts, underlying semantics, common modeling scenarios and application features / how to use the app. It should be easy to navigate and explore
@Computer
### Semantic model / metamodel
Requirements:
- Textual notation.
- Graphical notation.
- Constraints and calculations.
- Quantities and units.
- State and behavior modeling.
- Reusable model libraries.
- Strong, standardized specification.
- Strong, standardized API.
#### Textual notation
Requirements:
- Should not have visual noise and clutter.
- Should have means to reduce cognitive load when developing system models.
- Should be easily editable by humans. And AI agents.
- System engineers should be able to easily develop system models (both big and small) using textual notation only.
### UI
The focus should be on reducing system engineer's cognitive load when creating / working with a system model. Regardless of the model size (big or small).
Long, homogeneous lists in the UI that require user to scroll far or search for a desired option for too long - is a bad design.
## Active issues / current guidance
Right now, the behavior & scenarios UI is hard to use. It contains static / uneditable diagrams, which is highly dubious. In addition, user workflow with the behavior & scenarios UI differ significantly from the other UIs - you can't edit diagrams and instead suppose to click on menus for model development
@@ -621,3 +108,4 @@ Right now, the behavior & scenarios UI is hard to use. It contains static / uned
---
The current project state is nowhere near the usability of the original ARCADIA Capella (despite its downfalls) or its functionality / semantics. You should focus on that by studying original ARCADIA Capella very closely and implementing its features in a modern, ergonomic and easy to use way
<!-- END USER-OWNED APPLICATION SPECIFICATION -->
+23 -2
View File
@@ -18,12 +18,14 @@ From the repository root:
cargo run --locked -p oa-desktop --bin arcadia-studio
```
Build both desktop and server release executables:
Build the desktop, server and source CLI release executables:
```sh
cargo build --release --workspace --locked
```
Stage the complete teaching examples beside these executables so **Home → Open water-pressure walkthrough** works in an optimized source build. From the repository root, use `Copy-Item -Recurse -Force examples target/release/` in PowerShell or `cp -R examples target/release/` on Linux. If you set a different Cargo target directory or pass `--target`, use that build's executable directory instead of `target/release`. The packaging scripts include these examples automatically.
Run `target/release/arcadia-studio.exe` on Windows or `./target/release/arcadia-studio` on Linux. No task-specific cache directory is required. A graphical desktop and compatible graphics driver are required; the application uses Iced 0.14 with WGPU and X11/Wayland support. It does not require Java, Eclipse, a browser, an account or a running server.
An optional Windows path uses the `stable-x86_64-pc-windows-gnullvm` Rust toolchain with LLVM-MinGW. Put LLVM-MinGW's `bin` directory on `PATH`, including `clang.exe` and `llvm-windres.exe`, then run:
@@ -49,17 +51,34 @@ The earlier V2 package record describes `dist/ArcadiaStudio-Windows.zip` and `di
The current [Windows packaging instructions](docs/windows-packaging.md) stage both executables, verify their runtime DLL dependencies, and produce an archive with checksums and provenance. Native acceptance fixtures and independent expected results are retained in [the release fixture directory](harness/fixtures/release1-native/README.md).
## Work with source files from the command line
The `arcadia` CLI checks an explicit `.arcadia` entry file and its includes without
starting the desktop or server:
```sh
cargo run --locked -p oa-cli --bin arcadia -- check examples/text-first/project.arcadia
```
`stabilize ROOT` previews the identities needed for persistent editing;
`rename-alias ROOT OLD NEW` previews an alias change and its references. Add
`--write` to save that invocation's candidate, or `--json` for structured
diagnostics and changed-file text/diffs. Preview leaves files untouched.
See [source CLI commands](docs/source-cli.md) for examples and exit codes.
## Model operational needs and system responsibilities
The desktop starts at **Home**, where you can create a model, open a local project, continue recent files or recover retained work. Missing recent files stay visible with **Locate**; **Remove** only forgets their history entry. Choose **Explore rescue example** for a model combining people, an organization, a System of Interest, information and physical exchange items, normal/degraded behavior and code/CAD evidence.
The example opens in an architecture view with work nested inside its performers. Each layer also has dedicated functional dataflow and mission/capability views. Regenerate both example formats with matching identities using `cargo run --locked -p oa-core --example generate_demo`; the command verifies both saved models. Historical migration fixtures remain separate.
The architecture diagram has a compact side palette; expand it to see tool names. Choose an element tool, click its position, enter its name in place and press **Enter**. **Escape** cancels the draft. Select a card and press **F2** to rename it. Right-click a participant and choose **Add activity** or **Add function** to create work with its performer allocation in one undoable edit. Ordinary palette creation leaves work unallocated. **Add existing** places a compatible model element in the current view; **Include already shown** offers **Locate** for existing placements.
1. In **Operational Analysis**, create entities, actors, activities and capabilities. Use **In selected** for semantic decomposition and **Allocated** for new leaf work performed by a participant. Activities can decompose independently of their performer; roles capture shared operational responsibility. **Communication means** connects operational Entities or Actors directly, with direction and carried items; **Exchange allocation** associates the Interactions it carries. Operational communication requires no system ports.
2. Switch to **System Analysis**. Define one System of Interest and external Actors, then functions, missions, capabilities and functional chains. The system boundary has no internal LA/PA components in this version.
3. Select a System or System Actor and choose **Add port** in the browser or Properties. Choose Standard or Flow, then **Create port**. Use **Boundary exchange** in the diagram palette, or **Draw boundary exchange** on a selected visible source port, to connect compatible component ports directly. Create the other participant's matching port first if none exists. Functions expose separate input/output port actions; the **Functional exchange** palette tool connects them. **Actions** exposes other engineering relationships and off-diagram configuration; **Data & interfaces** holds reusable payloads and contracts.
4. Create focused views. **Containment** nests semantic children; **Architecture · allocated work** nests work within performers; **Functional dataflow** shows work decomposition and exchanges; **Missions & capabilities** shows objectives and participation. Dashed, italic parent work denotes an allocation summary inferred from its leaves. Ports appear on their owner's boundary. **View properties** stages saved line-kind, category, behavior-coverage, context, label and individual-hide choices. Right-click empty diagram space for **Duplicate view**, retaining the same semantic records in an independent presentation. Placement **Hide** removes a placement; line hiding retains its relationship; **Delete from model** removes semantics and dependent references.
5. In **Behavior & scenarios**, author processes/chains, scenario lifelines and ordered occurrences, including repeated uses of the same exchange and explicit fragments/branches. Select a State machine and choose **Create diagram** to place its existing regions and states/modes in a saved view. State machines also support availability and state-action links. Conditions are descriptive, not executable simulation code. Behavior and Data authoring preserve your other diagram layouts.
5. In **Behavior & scenarios**, choose **New**, select Operational process (OA), Functional chain (SA), Scenario or State machine, then enter its name. For a scenario, choose what its lifelines represent; **Add optional context…** links a context without changing its layer-root ownership. For a state machine, search for its existing participant owner; optionally select **Create the first state view**. Choose **Create and open** to start authoring work contributions, lifelines, ordered occurrences or states. **Cancel · Esc** discards the creation draft; if another dialog is open, Escape dismisses that dialog first. Creation and its optional first view form one Undo operation. A new state machine starts without regions or states; **Create diagram** can later place its existing contents in a saved view. Behavior supports repeated exchanges, fragments/branches, availability and state-action links. Conditions are descriptive, not executable simulation code. Behavior and Data authoring preserve your other diagram layouts.
6. Select an OA or SA element and choose **Create / update counterpart**. Review dependency scope and counterpart choices, then apply one undoable transaction. For an existing trace, **Review semantics…** compares typed content and prior observations, with explicit keep, take or final-value decisions for supported structural, scalar, constructor, individual-row and ordered-collection changes. Open additional trace rows and choose **Include this row** to combine reviewed source contributions into one validated Apply/Undo transaction; conflicting decisions require resolution. Review does not automatically synchronize the perspectives. **Attachments** reviews an existing child’s parent or a relationship endpoint. **Artifact links** reviews metadata, owner moves, explicit source-absence deletion and creation of a reserved counterpart after all introduced metadata is reviewed. These controls have automated coverage; their native acceptance remains pending. Manual traces link other engineering correspondences. **Traceability** also edits artifact URI, revision and fragment metadata.
7. Review **Model checks**, then save `.arcadia` source or `.json`. Warnings allow incomplete authoring; structural errors preserve the committed model and rejected draft.
@@ -83,6 +102,8 @@ In the state view, **Select / move** drags vertices and containers without repar
## Edit the same model as text
For a short text-only start, open [the distress-response model](examples/text-first/project.arcadia) and follow [its three-step walkthrough](examples/text-first/README.md). Four declarations and three explicit relationships describe participants, work, responsibility and an exchange; no diagram or handwritten UUID is needed.
**Textual model** has a source-file folder tree, per-file drafts, syntax highlighting, live linting and explicit **Apply all**. Collapse/Locate navigate the hierarchy; collapsed folders retain draft and diagnostic indicators. Right-click a file for contextual actions. Projects can use relative includes to organize source into files. For example:
```text
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "oa-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[[bin]]
name = "arcadia"
path = "src/main.rs"
[dependencies]
oa-core = { path = "../oa-core" }
serde.workspace = true
serde_json.workspace = true
+451
View File
@@ -0,0 +1,451 @@
//! Source-only authoring. Preparation captures bytes; only core owns disk writes.
use oa_core::{
Command, language,
persistence::MigrationReport,
prepare_command,
source_files::{self, DiskProject, SourceFileError},
source_project::{self, CompiledSourceProject, ProjectLimits, SourceDiagnostic},
validation::Severity,
};
use serde::Serialize;
use std::path::{Path, PathBuf};
pub const LIMITS: ProjectLimits = ProjectLimits {
max_files: 256,
max_include_depth: 32,
max_include_edges: 1024,
model: language::ParseLimits {
max_source_bytes: 64 * 1024 * 1024,
max_graph_objects: 100_000,
max_records: 250_000,
max_step_references: 500_000,
},
};
#[derive(Debug, Clone)]
pub enum Operation {
Check,
Stabilize,
RenameAlias { old: String, new: String },
}
#[derive(Debug, Clone, Serialize)]
pub struct Location {
pub path: String,
/// Half-open UTF-8 byte offsets. Line/column are one-based Unicode scalars.
pub start: usize,
pub end: usize,
pub line: Option<usize>,
pub column: Option<usize>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Diagnostic {
pub severity: String,
pub code: String,
pub message: String,
pub coordinate_space: String,
pub location: Option<Location>,
pub related: Vec<Location>,
pub object_id: Option<String>,
pub field: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Change {
pub path: String,
/// Exact captured and proposed UTF-8 text, including line endings.
pub before: String,
pub after: String,
pub diff: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct Report {
pub format_version: u32,
pub entry: String,
pub operation: String,
pub status: String,
pub exit_code: u8,
/// True only after a successful changed save. False on failure does not
/// promise rollback: consult the specific error/recovery outcome.
pub written: bool,
pub diagnostics: Vec<Diagnostic>,
pub changes: Vec<Change>,
pub identities_to_stabilize: usize,
pub migration: Option<MigrationReport>,
pub notes: Vec<String>,
}
impl Report {
pub fn failure(
entry: &Path,
operation: &str,
exit_code: u8,
code: &str,
message: String,
) -> Self {
let mut report = Self::empty(entry, operation);
report.fail(exit_code, code, message);
report
}
fn empty(entry: &Path, operation: &str) -> Self {
Self {
format_version: 1,
entry: entry.to_string_lossy().into_owned(),
operation: operation.into(),
status: "checked".into(),
exit_code: 0,
written: false,
diagnostics: vec![],
changes: vec![],
identities_to_stabilize: 0,
migration: None,
notes: vec![],
}
}
fn fail(&mut self, exit_code: u8, code: &str, message: String) {
self.status = "rejected".into();
self.exit_code = exit_code;
self.diagnostics.push(Diagnostic {
severity: "error".into(),
code: code.into(),
message,
coordinate_space: "operation".into(),
location: None,
related: vec![],
object_id: None,
field: None,
});
}
}
fn located(issue: SourceDiagnostic, space: &str) -> Diagnostic {
let d = issue.diagnostic;
Diagnostic {
severity: match d.severity {
Severity::Error => "error",
Severity::Warning => "warning",
}
.into(),
code: d.code,
message: d.message,
coordinate_space: space.into(),
location: Some(Location {
path: issue.path,
start: d.span.start,
end: d.span.end,
line: Some(d.line),
column: Some(d.column),
}),
related: issue
.related
.into_iter()
.map(|at| Location {
path: at.path,
start: at.span.start,
end: at.span.end,
line: None,
column: None,
})
.collect(),
object_id: d.object_id.map(|id| id.to_string()),
field: d.field,
}
}
fn disk_error(report: &mut Report, error: SourceFileError) {
let code = match &error {
SourceFileError::Conflict(_) => "external_change",
SourceFileError::RecoveryRequired(_) => "recovery_required",
SourceFileError::RecoveryFailed { .. } => "recovery_failed",
SourceFileError::Path(_) => "unsafe_path",
SourceFileError::Limit(_) => "source_limit",
SourceFileError::UnknownExpectation(_) => "unknown_disk_expectation",
SourceFileError::Invalid(_) => "invalid_save_candidate",
SourceFileError::Io { .. } => "io_error",
};
report.fail(3, code, error.to_string());
}
/// A candidate owns its original expectations and is consumed by saving.
/// Callers cannot replace its source/model/expectations after preparation.
pub struct Prepared {
report: Report,
snapshot: DiskProject,
compiled: CompiledSourceProject,
mutable: bool,
}
impl Prepared {
pub fn report(&self) -> &Report {
&self.report
}
pub fn into_report(self) -> Report {
self.report
}
pub fn write(mut self) -> Report {
if !self.mutable {
self.report
.fail(2, "usage", "check/lint does not accept --write".into());
return self.report;
}
match source_files::save_project(&self.snapshot, &self.compiled, LIMITS) {
Ok(_) => {
self.report.written = !self.report.changes.is_empty();
self.report.status = if self.report.written {
"written"
} else {
"unchanged"
}
.into();
}
Err(error) => disk_error(&mut self.report, error),
}
self.report
}
}
pub fn prepare(entry: &Path, operation: Operation) -> Result<Prepared, Box<Report>> {
let name = match operation {
Operation::Check => "check",
Operation::Stabilize => "stabilize",
Operation::RenameAlias { .. } => "rename-alias",
};
let mut report = Report::empty(entry, name);
let snapshot = source_files::load_project(entry, LIMITS).map_err(|error| {
disk_error(&mut report, error);
Box::new(report.clone())
})?;
let raw = snapshot.reachable_bundle();
// The loader may include warnings from stabilized compilation. Only its
// discovery/IO diagnostics are authoritative on the original bytes.
let mut diagnostics: Vec<_> = snapshot
.diagnostics
.iter()
.filter(|d| {
matches!(
d.diagnostic.code.as_str(),
"pending_save"
| "source_encoding"
| "source_limit"
| "invalid_path"
| "missing_include"
| "project_limit"
)
})
.cloned()
.collect();
for diagnostic in source_project::lint_bundle(&raw, LIMITS) {
if !diagnostics.contains(&diagnostic) {
diagnostics.push(diagnostic);
}
}
let disk_refusal = snapshot.diagnostics.iter().any(|d| {
matches!(
d.diagnostic.code.as_str(),
"pending_save" | "missing_include" | "invalid_path"
)
});
let invalid = diagnostics
.iter()
.any(|d| d.diagnostic.severity == Severity::Error);
report.diagnostics = diagnostics
.into_iter()
.map(|d| located(d, "input"))
.collect();
if invalid {
// Do not run declaration analysis or any updater on invalid raw text.
// Failed lint may also have allocated provisional object identities.
for diagnostic in &mut report.diagnostics {
diagnostic.object_id = None;
}
report.status = "invalid".into();
report.exit_code = if disk_refusal { 3 } else { 1 };
return Err(Box::new(report));
}
let explicit_ids: std::collections::BTreeSet<_> = raw
.files
.values()
.flat_map(|text| language::analyze(text).declarations)
.filter_map(|d| d.id.map(|id| id.to_string()))
.collect();
for diagnostic in &mut report.diagnostics {
if diagnostic
.object_id
.as_ref()
.is_some_and(|id| !explicit_ids.contains(id))
{
diagnostic.object_id = None;
}
}
let mut compiled = source_project::compile_bundle(&raw, LIMITS).map_err(|diagnostics| {
report.status = "invalid".into();
report.exit_code = 1;
report
.diagnostics
.extend(diagnostics.into_iter().map(|d| located(d, "candidate")));
Box::new(report.clone())
})?;
report.identities_to_stabilize = raw
.files
.values()
.map(|text| {
language::analyze(text)
.declarations
.into_iter()
.filter(|d| d.id.is_none())
.count()
})
.sum();
report.migration = compiled.decoded.migration.clone();
let mutable = !matches!(operation, Operation::Check);
if let Operation::RenameAlias { old, new } = operation {
let project = &compiled.decoded.project;
let Some((id, _)) = project
.identities()
.into_iter()
.find(|(_, alias)| *alias == old)
else {
report.fail(
1,
"unknown_alias",
format!("No declaration has alias '{old}'."),
);
return Err(Box::new(report));
};
let command = prepare_command(project, &Command::SetAlias(id, new)).map_err(|error| {
report.fail(1, "semantic_command_rejected", error.to_string());
Box::new(report.clone())
})?;
compiled = source_project::update_bundle_with_identity_map(
&compiled,
&command.project,
&command.identity_map,
LIMITS,
)
.map_err(|diagnostics| {
report.status = "invalid".into();
report.exit_code = 1;
report
.diagnostics
.extend(diagnostics.into_iter().map(|d| located(d, "candidate")));
Box::new(report.clone())
})?;
}
if mutable {
for (path, after) in &compiled.bundle.files {
let before = raw.files.get(path).cloned().unwrap_or_default();
if &before != after {
report.changes.push(Change {
path: path.clone(),
diff: unified_diff(path, &before, after),
before,
after: after.clone(),
});
}
}
report.status = "preview".into();
report.notes.push("This invocation's complete proposed changed-file texts and diffs are reported. Without --write nothing is saved; a later invocation may allocate different missing UUIDs. This is not a saved plan or a digest of unchanged dependencies.".into());
}
report.notes.push("Diagnostic object IDs are omitted for declarations without authored IDs; lint's temporary identities are not the candidate's identities.".into());
report.notes.push("Disk writes use the core journal/conflict checks. This is not cross-process atomic visibility or a power-loss durability guarantee; pending saves are never implicitly recovered. A failed write may require explicit journal recovery.".into());
Ok(Prepared {
report,
snapshot,
compiled,
mutable,
})
}
/// One bounded hunk per file: common prefix/suffix plus three context lines.
/// Linear in input size; no quadratic LCS allocation for large modules.
fn unified_diff(path: &str, before: &str, after: &str) -> String {
let a: Vec<_> = before.split_inclusive('\n').collect();
let b: Vec<_> = after.split_inclusive('\n').collect();
let prefix = a.iter().zip(&b).take_while(|(a, b)| a == b).count();
let suffix = a[prefix..]
.iter()
.rev()
.zip(b[prefix..].iter().rev())
.take_while(|(a, b)| a == b)
.count();
let start = prefix.saturating_sub(3);
let a_end = (a.len() - suffix + 3).min(a.len());
let b_end = (b.len() - suffix + 3).min(b.len());
let a_start = if a_end == start { start } else { start + 1 };
let b_start = if b_end == start { start } else { start + 1 };
let mut out = format!(
"--- a/{path}\n+++ b/{path}\n@@ -{a_start},{} +{b_start},{} @@\n",
a_end - start,
b_end - start
);
let mut emit = |prefix: char, line: &str| {
out.push(prefix);
out.push_str(line);
if !line.ends_with('\n') {
out.push_str("\n\\ No newline at end of file\n");
}
};
for line in &a[start..prefix] {
emit(' ', line);
}
for line in &a[prefix..a.len() - suffix] {
emit('-', line);
}
for line in &b[prefix..b.len() - suffix] {
emit('+', line);
}
for line in &a[a.len() - suffix..a_end] {
emit(' ', line);
}
out
}
pub struct Arguments {
pub entry: PathBuf,
pub operation: Operation,
pub write: bool,
pub json: bool,
}
pub const HELP: &str = "arcadia check ROOT [--json]\narcadia lint ROOT [--json]\narcadia stabilize ROOT [--write] [--json]\narcadia rename-alias ROOT OLD NEW [--write] [--json]\n\nROOT is an explicit .arcadia entry file; includes resolve relative to it.\nMutation commands preview by default. --write applies this invocation's candidate.\nMissing UUIDs in a preview are provisional until written. No canonical formatting.\nExit: 0 valid/success (engineering warnings allowed), 1 invalid source or semantic\ncommand rejection, 2 usage, 3 disk/path/conflict/pending-journal/output failure.\nNo implicit journal recovery. Limits: 64 MiB, 256 files, include depth32/edges1024,\n100000 graph objects, 250000 records, 500000 ordered references.\n";
pub fn arguments(args: &[std::ffi::OsString]) -> Result<Arguments, String> {
let mut positional = Vec::new();
let (mut write, mut json) = (false, false);
for arg in args {
if arg == "--write" && !write {
write = true;
} else if arg == "--json" && !json {
json = true;
} else if arg.to_string_lossy().starts_with('-') {
return Err(format!(
"Unknown or repeated option: {}",
arg.to_string_lossy()
));
} else {
positional.push(arg);
}
}
let command = positional.first().and_then(|s| s.to_str()).unwrap_or("");
let operation = match (command, positional.len()) {
("check" | "lint", 2) if !write => Operation::Check,
("stabilize", 2) => Operation::Stabilize,
("rename-alias", 4) => Operation::RenameAlias {
old: positional[2].to_str().ok_or("Alias must be UTF-8")?.into(),
new: positional[3].to_str().ok_or("Alias must be UTF-8")?.into(),
},
_ => return Err(HELP.into()),
};
Ok(Arguments {
entry: PathBuf::from(positional[1]),
operation,
write,
json,
})
}
+102
View File
@@ -0,0 +1,102 @@
use oa_cli::{Report, arguments, prepare};
use std::{
io::{self, Write},
path::Path,
process::ExitCode,
};
fn human_report(report: &Report, show_diff: bool) -> io::Result<()> {
let mut err = io::stderr().lock();
for d in &report.diagnostics {
let at = d
.location
.as_ref()
.map(|l| {
format!(
"{}:{}:{}",
l.path,
l.line.unwrap_or(0),
l.column.unwrap_or(0)
)
})
.unwrap_or_else(|| report.entry.clone());
writeln!(
err,
"{at}: {}[{}] ({}): {}",
d.severity, d.code, d.coordinate_space, d.message
)?;
}
writeln!(
err,
"{}: {} file changes; {} identities to stabilize",
report.status,
report.changes.len(),
report.identities_to_stabilize
)?;
if let Some(migration) = &report.migration {
writeln!(
err,
"Source migration: schema {} → {} (separate from identity stabilization)",
migration.from_schema, migration.to_schema
)?;
}
for note in &report.notes {
writeln!(err, "{note}")?;
}
if show_diff {
let mut out = io::stdout().lock();
for change in &report.changes {
write!(out, "{}", change.diff)?;
}
out.flush()?;
}
err.flush()
}
fn run() -> io::Result<u8> {
let args: Vec<_> = std::env::args_os().skip(1).collect();
if args.len() == 1 && (args[0] == "--help" || args[0] == "-h") {
io::stdout().write_all(oa_cli::HELP.as_bytes())?;
return Ok(0);
}
if args.len() == 1 && args[0] == "--version" {
writeln!(io::stdout(), "arcadia {}", env!("CARGO_PKG_VERSION"))?;
return Ok(0);
}
let json = args.iter().any(|a| a == "--json");
let mut displayed = false;
let report = match arguments(&args) {
Err(error) => Report::failure(Path::new(""), "usage", 2, "usage", error),
Ok(args) => match prepare(&args.entry, args.operation) {
Err(report) => *report,
Ok(prepared) => {
if args.write {
if !args.json {
human_report(prepared.report(), true)?;
displayed = true;
}
prepared.write()
} else {
prepared.into_report()
}
}
},
};
if json {
serde_json::to_writer_pretty(io::stdout().lock(), &report)?;
writeln!(io::stdout())?;
} else {
human_report(&report, !displayed)?;
}
Ok(report.exit_code)
}
fn main() -> ExitCode {
match run() {
Ok(code) => ExitCode::from(code),
Err(error) => {
let _ = writeln!(io::stderr(), "Output failed: {error}");
ExitCode::from(3)
}
}
}
+425
View File
@@ -0,0 +1,425 @@
use oa_cli::{LIMITS, Operation, Prepared, prepare};
use oa_core::{Id, Project, source_files, source_project};
use serde_json::Value;
use std::{
collections::BTreeMap,
fs,
path::{Path, PathBuf},
process::Command,
};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let path = std::env::temp_dir().join(format!("arcadia-cli-test-{}", Id::new_v4()));
fs::create_dir(&path).unwrap();
Self(path)
}
fn put(&self, name: &str, text: &str) {
let path = self.0.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
fn entry(&self) -> PathBuf {
self.0.join("project.arcadia")
}
fn read(&self, name: &str) -> String {
fs::read_to_string(self.0.join(name)).unwrap()
}
fn prepare(&self, op: Operation) -> Prepared {
prepare(&self.entry(), op).unwrap_or_else(|report| panic!("{report:#?}"))
}
fn model(&self) -> Project {
let disk = source_files::load_project(&self.entry(), LIMITS).unwrap();
source_project::compile_bundle(&disk.reachable_bundle(), LIMITS)
.unwrap()
.decoded
.project
}
fn cli(&self, args: &[&str]) -> (i32, Value) {
let mut command = Command::new(env!("CARGO_BIN_EXE_arcadia"));
command
.arg(args[0])
.arg(self.entry())
.args(&args[1..])
.arg("--json");
let output = command.output().unwrap();
assert!(
output.stderr.is_empty(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
(
output.status.code().unwrap(),
serde_json::from_slice(&output.stdout).unwrap(),
)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
const SIMPLE: &str = "// 雨: authored defaults stay omitted\r\narcadia 7;\r\nproject rescue \"Rescue\" {\r\n oa_entity team \"Team\" {}\r\n}\r\n";
#[test]
fn complete_alarm_example_preview_then_write_and_fixed_point() {
let fixture = Fixture::new();
let source = include_str!(
"../../../harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
);
fixture.put("project.arcadia", source);
let (code, check) = fixture.cli(&["check"]);
assert_eq!(code, 0);
assert_eq!(check["diagnostics"], serde_json::json!([]));
let (code, preview) = fixture.cli(&["stabilize"]);
assert_eq!(code, 0);
assert_eq!(preview["identities_to_stabilize"], 40);
assert_eq!(preview["status"], "preview");
assert_eq!(fixture.read("project.arcadia"), source);
assert!(
preview["changes"][0]["diff"]
.as_str()
.unwrap()
.contains("+project alarm_response")
);
let (code, written) = fixture.cli(&["stabilize", "--write"]);
assert_eq!(code, 0);
let saved = fixture.read("project.arcadia");
assert_eq!(written["changes"][0]["after"], saved);
let project = fixture.model();
assert_eq!(project.identities().len(), 40);
let mut stripped = saved.clone();
for (id, _) in project.identities() {
stripped = stripped.replace(&format!(" id \"{id}\""), "");
}
assert_eq!(stripped, source, "only identity clauses may be inserted");
let (code, again) = fixture.cli(&["stabilize", "--write"]);
assert_eq!(code, 0);
assert_eq!(again["changes"], serde_json::json!([]));
assert_eq!(again["status"], "unchanged");
assert_eq!(fixture.model(), project);
assert_eq!(fixture.read("project.arcadia"), saved);
}
#[test]
fn captured_candidate_exact_write_preserves_crlf_comments_and_noop_metadata() {
let fixture = Fixture::new();
fixture.put("project.arcadia", SIMPLE);
let candidate = fixture.prepare(Operation::Stabilize);
let expected = candidate.report().changes[0].after.clone();
assert_eq!(candidate.report().identities_to_stabilize, 2);
assert_eq!(fixture.read("project.arcadia"), SIMPLE);
assert_eq!(candidate.write().exit_code, 0);
assert_eq!(fixture.read("project.arcadia"), expected);
assert!(expected.contains("// 雨: authored defaults stay omitted\r\n"));
assert!(!expected.contains("description"));
let metadata = fs::metadata(fixture.entry()).unwrap().modified().unwrap();
let report = fixture.prepare(Operation::Stabilize).write();
assert_eq!(report.status, "unchanged");
assert!(!report.written);
assert_eq!(
fs::metadata(fixture.entry()).unwrap().modified().unwrap(),
metadata
);
assert_eq!(fs::read_dir(&fixture.0).unwrap().count(), 1);
}
#[test]
fn alias_rename_across_modules_changes_only_live_tokens_and_retains_all_identity() {
let fixture = Fixture::new();
fixture.put("project.arcadia", "arcadia 7; project rescue \"Rescue\" { include \"participants.arcadia\"; include \"work.arcadia\"; }\n");
fixture.put(
"participants.arcadia",
"// @team is quoted documentation\noa_entity team \"Team @team\" {}\n",
);
fixture.put("work.arcadia", "oa_activity assess \"Assess\" {}\noa_activity report \"Report\" {}\nallocation assigned \"Assigned\" { source @team; target @assess; }\ninteraction transfer \"Transfer\" { source @assess; target @report; }\n");
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
let before = fixture.model();
let original: BTreeMap<_, _> = ["project.arcadia", "participants.arcadia", "work.arcadia"]
.into_iter()
.map(|p| (p, fixture.read(p)))
.collect();
let team = before
.identities()
.into_iter()
.find(|(_, alias)| *alias == "team")
.unwrap()
.0;
let candidate = fixture.prepare(Operation::RenameAlias {
old: "team".into(),
new: "rescue_team".into(),
});
assert_eq!(candidate.report().changes.len(), 2);
assert_eq!(fixture.model(), before, "preview cannot mutate");
assert_eq!(candidate.write().exit_code, 0);
let mut expected = before;
expected.elements.get_mut(&team).unwrap().alias = "rescue_team".into();
assert_eq!(fixture.model(), expected);
assert_eq!(fixture.read("project.arcadia"), original["project.arcadia"]);
assert_eq!(
fixture.read("participants.arcadia"),
original["participants.arcadia"].replacen("oa_entity team ", "oa_entity rescue_team ", 1)
);
assert_eq!(
fixture.read("work.arcadia"),
original["work.arcadia"].replace("source @team;", "source @rescue_team;")
);
}
#[test]
fn invalid_unicode_raw_edit_is_located_and_never_stabilized_or_written() {
let fixture = Fixture::new();
let raw = "arcadia 7; project p \"雨\" {\n oa_activity a \"A\" {}\n allocation alloc \"Alloc\" { source @missing; target @a; }\n}\n";
fixture.put("project.arcadia", raw);
for command in [
vec!["check"],
vec!["stabilize", "--write"],
vec!["rename-alias", "a", "b", "--write"],
] {
let (code, report) = fixture.cli(&command);
assert_eq!(code, 1);
assert_eq!(fixture.read("project.arcadia"), raw);
let diagnostics = report["diagnostics"].as_array().unwrap();
assert!(!diagnostics.is_empty());
for d in diagnostics {
assert_eq!(d["coordinate_space"], "input");
let at = &d["location"];
let start = at["start"].as_u64().unwrap() as usize;
assert!(raw.is_char_boundary(start));
assert_eq!(
at["line"].as_u64().unwrap() as usize,
raw[..start].bytes().filter(|b| *b == b'\n').count() + 1
);
let line = raw[..start]
.rsplit_once('\n')
.map_or(&raw[..start], |(_, tail)| tail);
assert_eq!(
at["column"].as_u64().unwrap() as usize,
line.chars().count() + 1
);
}
}
}
#[test]
fn missing_id_warning_uses_raw_location_and_never_exposes_ephemeral_lint_id() {
let fixture = Fixture::new();
let raw = "arcadia 7;\nproject p \"雨\" {\n oa_activity work \"Work\" {}\n}\n";
fixture.put("project.arcadia", raw);
let (code, result) = fixture.cli(&["lint"]);
assert_eq!(code, 0, "engineering warnings do not reject admission");
let warning = result["diagnostics"]
.as_array()
.unwrap()
.iter()
.find(|d| d["code"] == "work_without_behavior_context")
.unwrap();
assert_eq!(warning["severity"], "warning");
assert_eq!(
warning["location"]["start"],
raw.find("oa_activity").unwrap()
);
assert_eq!(warning["location"]["line"], 3);
assert_eq!(warning["location"]["column"], 5);
assert!(warning["object_id"].is_null());
assert_eq!(fixture.read("project.arcadia"), raw);
}
#[test]
fn captured_dependency_change_refuses_all_writes_even_on_noop() {
let fixture = Fixture::new();
fixture.put("project.arcadia", SIMPLE);
let pending = fixture.prepare(Operation::Stabilize);
let external = format!("{SIMPLE}// editor changed this\n");
fixture.put("project.arcadia", &external);
let result = pending.write();
assert_eq!(result.exit_code, 3);
assert_eq!(result.diagnostics.last().unwrap().code, "external_change");
assert_eq!(fixture.read("project.arcadia"), external);
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
let noop = fixture.prepare(Operation::Stabilize);
assert!(noop.report().changes.is_empty());
let latest = format!("{}// another edit\n", fixture.read("project.arcadia"));
fixture.put("project.arcadia", &latest);
assert_eq!(noop.write().exit_code, 3);
assert_eq!(fixture.read("project.arcadia"), latest);
}
#[test]
fn pending_journal_refuses_read_preview_and_write_without_recovery() {
let fixture = Fixture::new();
fixture.put("project.arcadia", SIMPLE);
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
let noop = fixture.prepare(Operation::Stabilize);
let source = fixture.read("project.arcadia");
// An opaque incomplete journal must never be interpreted/recovered by CLI.
let journal = fixture.0.join(".arcadia-save-project.arcadia.journal");
fs::create_dir(&journal).unwrap();
fs::write(journal.join("sentinel"), b"retain").unwrap();
for op in [Operation::Check, Operation::Stabilize] {
let report = prepare(&fixture.entry(), op).err().unwrap();
assert_eq!(report.exit_code, 3);
assert!(report.diagnostics.iter().any(|d| d.code == "pending_save"));
}
assert_eq!(
noop.write().exit_code,
3,
"saver must recheck after preview"
);
assert_eq!(fixture.read("project.arcadia"), source);
assert_eq!(fs::read(journal.join("sentinel")).unwrap(), b"retain");
}
#[test]
fn rejected_alias_and_same_alias_preserve_source() {
let fixture = Fixture::new();
fixture.put("project.arcadia", SIMPLE);
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
let source = fixture.read("project.arcadia");
for (old, new) in [
("team", "rescue"),
("team", "invalid alias"),
("absent", "valid"),
] {
let (code, result) = fixture.cli(&["rename-alias", old, new, "--write"]);
assert_eq!(code, 1);
assert_eq!(result["status"], "rejected");
assert_eq!(fixture.read("project.arcadia"), source);
}
let (code, result) = fixture.cli(&["rename-alias", "team", "team", "--write"]);
assert_eq!(code, 0);
assert_eq!(result["status"], "unchanged");
assert_eq!(fixture.read("project.arcadia"), source);
}
#[test]
fn rename_shows_missing_identity_and_separate_source_migration() {
let fixture = Fixture::new();
let old = "// retain\narcadia 5; project p \"P\" { oa_entity team \"Team\" {} }\n";
fixture.put("project.arcadia", old);
let candidate = fixture.prepare(Operation::RenameAlias {
old: "team".into(),
new: "crew".into(),
});
let report = candidate.report();
assert_eq!(report.identities_to_stabilize, 2);
assert_eq!(report.migration.as_ref().unwrap().from_schema, 5);
assert_eq!(report.migration.as_ref().unwrap().to_schema, 7);
assert!(report.changes[0].diff.contains("-arcadia 5;"));
assert!(report.changes[0].diff.contains("+arcadia 7;"));
assert!(report.changes[0].after.contains("oa_entity crew"));
assert_eq!(fixture.read("project.arcadia"), old);
assert_eq!(candidate.write().exit_code, 0);
}
#[test]
fn entry_is_explicit_and_machine_readable_usage_errors_do_not_write() {
let fixture = Fixture::new();
fixture.put("project.arcadia", SIMPLE);
let output = Command::new(env!("CARGO_BIN_EXE_arcadia"))
.current_dir(&fixture.0)
.args(["check", "--json"])
.output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
let error: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(error["diagnostics"][0]["code"], "usage");
assert_eq!(fixture.read("project.arcadia"), SIMPLE);
let (code, _) = fixture.cli(&["check", "--write"]);
assert_eq!(code, 2);
assert!(Path::new(env!("CARGO_BIN_EXE_arcadia")).is_file());
}
#[test]
fn loader_encoding_missing_dependency_and_invalid_old_source_keep_original_bytes() {
let fixture = Fixture::new();
let entry = "arcadia 7; project p \"P\" { include \"part.arcadia\"; }";
fixture.put("project.arcadia", entry);
let (code, report) = fixture.cli(&["stabilize", "--write"]);
assert_eq!(code, 3, "a disk dependency could not be read");
assert!(
report["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|d| d["code"] == "missing_include")
);
fs::write(fixture.0.join("part.arcadia"), [0xff, 0xfe]).unwrap();
let (code, report) = fixture.cli(&["stabilize", "--write"]);
assert_eq!(code, 1, "invalid encoding is invalid raw source");
assert!(
report["diagnostics"]
.as_array()
.unwrap()
.iter()
.any(|d| d["code"] == "source_encoding")
);
assert_eq!(fixture.read("project.arcadia"), entry);
assert_eq!(
fs::read(fixture.0.join("part.arcadia")).unwrap(),
[0xff, 0xfe]
);
for raw in [
"arcadia 5; project p \"P\" { oa_entity a \"A\" { ??? } }",
"arcadia 2; project p \"P\" {}",
] {
fixture.put("project.arcadia", raw);
let (code, _) = fixture.cli(&["stabilize", "--write"]);
assert_eq!(code, 1);
assert_eq!(fixture.read("project.arcadia"), raw);
}
}
#[test]
fn non_element_alias_detached_file_and_unchanged_dependency_conflict() {
let fixture = Fixture::new();
fixture.put("project.arcadia", "arcadia 7; project p \"P\" { include \"part.arcadia\"; oa_activity a \"A\" {} allocation responsible \"Responsible\" { source @ // keep edge comment\nteam; target @a; } }");
fixture.put("part.arcadia", "oa_entity team \"Team\" {}");
fixture.put(
"detached.arcadia",
"invalid detached draft must stay exact 雨",
);
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
let before = fixture.model();
let relation = before
.identities()
.into_iter()
.find(|(_, alias)| *alias == "responsible")
.unwrap()
.0;
let (code, _) = fixture.cli(&["rename-alias", "responsible", "performs", "--write"]);
assert_eq!(code, 0);
let mut expected = before;
expected.relations.get_mut(&relation).unwrap().alias = "performs".into();
assert_eq!(fixture.model(), expected);
assert!(
fixture
.read("project.arcadia")
.contains("@ // keep edge comment\nteam")
);
let captured = fixture.prepare(Operation::RenameAlias {
old: "p".into(),
new: "rescue".into(),
});
assert!(
captured
.report()
.changes
.iter()
.all(|c| c.path != "part.arcadia")
);
let root_before = fixture.read("project.arcadia");
fixture.put("part.arcadia", "// external unchanged-dependency edit\n");
assert_eq!(captured.write().exit_code, 3);
assert_eq!(fixture.read("project.arcadia"), root_before);
assert_eq!(
fixture.read("part.arcadia"),
"// external unchanged-dependency edit\n"
);
assert_eq!(
fixture.read("detached.arcadia"),
"invalid detached draft must stay exact 雨"
);
}
+3
View File
@@ -12,6 +12,9 @@ uuid.workspace = true
thiserror.workspace = true
tempfile = "3"
same-file = "1"
num-bigint = "0.5.1"
num-integer = "0.1.47"
num-traits = "0.2.19"
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2"
+103
View File
@@ -0,0 +1,103 @@
//! Exact numeric foundation for analysis; no model, expression, or package resolver.
//!
//! Values use reduced rational coordinates. All nontrivial arithmetic takes one
//! request-local [WorkMeter]. The future evaluator must also charge *expanded*
//! expression/call/property/list/target visits and retain the same logical walk on
//! cache hits. Stored AST size is not a dynamic execution limit.
//!
//! Approximate engineering functions/irrational unit scales require a subsequent
//! explicit numeric profile; rationals do not implement degree/radian conversion
//! or transcendental mathematics.
mod dimension;
mod exact;
mod meter;
mod quantity;
pub use dimension::{Dimension, DimensionAxis};
pub use exact::{Exact, ExactWire};
pub use meter::{
EvaluationStep, NumericOperation, WorkExhaustion, WorkLimits, WorkMeter, WorkResource,
WorkSite, WorkUsage,
};
pub use quantity::{NumericType, NumericValue, ResolvedKind, Unit};
use serde::{Deserialize, Serialize};
use thiserror::Error;
/// Profile identity includes the accounting rules, not crate-internal timing.
pub const WORK_PROFILE: &str = "Q1-logical-work-1";
pub const MAX_COMPONENT_BITS: u64 = 4096;
/// Cross products require 8192 bits; their sum can require one additional bit.
pub const MAX_INTERMEDIATE_BITS: u64 = 8193;
pub const MAX_COMPONENT_DIGITS: usize = 1234;
pub const MAX_DECIMAL_EXPONENT: i32 = 128;
pub const MAX_INTEGER_POWER: i8 = 16;
/// Includes ratio punctuation/whitespace without permitting unbounded scanning.
pub const MAX_LITERAL_BYTES: usize = 2 * MAX_COMPONENT_DIGITS + 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NumberComponent {
Numerator,
Denominator,
}
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
pub enum NumericLimit {
#[error("request work exhausted: {0}")]
Work(WorkExhaustion),
#[error("{component:?} uses {bits} bits, above the {limit}-bit {stage} limit")]
Bits {
component: NumberComponent,
bits: u64,
limit: u64,
stage: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
pub enum NumericError {
#[error("numeric limit: {0}")]
Limit(NumericLimit),
#[error("invalid numeric literal")]
InvalidLiteral,
#[error("numeric literal exceeds its digit or byte limit")]
LiteralTooLong,
#[error("decimal exponent is outside -128 through 128")]
DecimalExponent,
#[error("wire rational is not in canonical reduced form")]
NonCanonicalWire,
#[error("rational denominator is zero")]
ZeroDenominator,
#[error("division by zero")]
DivisionByZero,
#[error("zero to the power zero is undefined in this profile")]
ZeroPowerZero,
#[error("integer power is outside -16 through 16")]
IntegerPower,
#[error("dimension exponent at {axis:?} is outside -32 through 32: {value}")]
DimensionExponent { axis: DimensionAxis, value: i32 },
#[error("unit scale must be strictly positive")]
UnitScale,
#[error("a linear unit must have zero offset")]
LinearOffset,
#[error("an affine point must have a distinct linear difference kind")]
DifferenceKind,
#[error("numeric kinds or dimensions are incompatible")]
IncompatibleTypes,
#[error("operation is not defined for affine points")]
AffineOperation,
#[error("AsKind requires an anonymous matching dimension and a linear target")]
KindAssertion,
#[error("request work limits exceed the provisional reference ceilings")]
InvalidWorkLimits,
}
impl NumericError {
pub fn is_terminal_work_exhaustion(&self) -> bool {
matches!(self, Self::Limit(NumericLimit::Work(_)))
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,107 @@
use super::NumericError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DimensionAxis {
Length,
Mass,
Time,
ElectricCurrent,
Temperature,
Amount,
LuminousIntensity,
}
impl DimensionAxis {
pub const ALL: [Self; 7] = [
Self::Length,
Self::Mass,
Self::Time,
Self::ElectricCurrent,
Self::Temperature,
Self::Amount,
Self::LuminousIntensity,
];
}
/// SI base-dimension vector in DimensionAxis::ALL order, each entry -32..=32.
/// This is a dimension, never a nominal quantity-kind compatibility proof.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "[i16; 7]", into = "[i16; 7]")]
pub struct Dimension([i16; 7]);
impl Dimension {
pub const ZERO: Self = Self([0; 7]);
pub fn new(exponents: [i16; 7]) -> Result<Self, NumericError> {
for (index, value) in exponents.iter().copied().enumerate() {
if !(-32..=32).contains(&value) {
return Err(NumericError::DimensionExponent {
axis: DimensionAxis::ALL[index],
value: i32::from(value),
});
}
}
Ok(Self(exponents))
}
pub fn exponents(self) -> [i16; 7] {
self.0
}
pub fn is_dimensionless(self) -> bool {
self == Self::ZERO
}
pub fn checked_product(self, rhs: Self) -> Result<Self, NumericError> {
self.combine(rhs, 1)
}
pub fn checked_quotient(self, rhs: Self) -> Result<Self, NumericError> {
self.combine(rhs, -1)
}
pub fn checked_power(self, exponent: i8) -> Result<Self, NumericError> {
if !(-super::MAX_INTEGER_POWER..=super::MAX_INTEGER_POWER).contains(&exponent) {
return Err(NumericError::IntegerPower);
}
let mut output = [0; 7];
for (index, value) in self.0.iter().enumerate() {
output[index] = Self::checked_exponent(index, i32::from(*value) * i32::from(exponent))?;
}
Ok(Self(output))
}
fn combine(self, rhs: Self, sign: i32) -> Result<Self, NumericError> {
let mut output = [0; 7];
for (index, value) in self.0.iter().enumerate() {
output[index] =
Self::checked_exponent(index, i32::from(*value) + sign * i32::from(rhs.0[index]))?;
}
Ok(Self(output))
}
fn checked_exponent(index: usize, value: i32) -> Result<i16, NumericError> {
if !(-32..=32).contains(&value) {
return Err(NumericError::DimensionExponent {
axis: DimensionAxis::ALL[index],
value,
});
}
Ok(value as i16)
}
}
impl TryFrom<[i16; 7]> for Dimension {
type Error = NumericError;
fn try_from(value: [i16; 7]) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<Dimension> for [i16; 7] {
fn from(value: Dimension) -> Self {
value.0
}
}
@@ -0,0 +1,469 @@
use super::meter::{normalization_cost, parse_cost, product_cost, sum_cost, words};
use super::{
MAX_COMPONENT_BITS, MAX_COMPONENT_DIGITS, MAX_DECIMAL_EXPONENT, MAX_INTEGER_POWER,
MAX_INTERMEDIATE_BITS, MAX_LITERAL_BYTES, NumberComponent, NumericError, NumericLimit,
NumericOperation, WorkLimits, WorkMeter,
};
use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Signed, Zero};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
/// The interchange representation deliberately does not use num-bigint's serde
/// format or JSON numeric values. Duplicate/missing/unknown fields reject.
/// Its derived decoder allocates String fields before numeric validation; a
/// transport/document adapter must bound the encoded envelope and decoded text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExactWire {
pub numerator: String,
pub denominator: String,
}
/// Reduced rational with positive denominator and <=4096-bit components.
///
/// There are no unmetered arithmetic/ordering traits. Eq is structural equality
/// of already normalized bounded values, not an expression comparison API.
/// Standalone serde admission bounds the subsequent BigInt validation, not the
/// preceding String decoding. Document adapters must bound encoded/decoded input
/// and aggregate admission work. Evaluation uses one explicit WorkMeter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ExactWire", into = "ExactWire")]
pub struct Exact {
numerator: BigInt,
denominator: BigInt,
}
impl Exact {
pub fn from_integer(value: i64) -> Self {
Self {
numerator: BigInt::from(value),
denominator: BigInt::one(),
}
}
pub fn is_zero(&self) -> bool {
self.numerator.is_zero()
}
pub fn is_positive(&self) -> bool {
self.numerator.is_positive()
}
pub fn component_bits(&self) -> (u64, u64) {
(self.numerator.bits(), self.denominator.bits())
}
pub fn to_wire(&self) -> ExactWire {
ExactWire {
numerator: self.numerator.to_string(),
denominator: self.denominator.to_string(),
}
}
/// Canonical *literal* spelling, not a generic expression formatter.
/// Negative literal nodes use ratio(-n,d), even when d=1. A leading minus
/// belongs to the future expression parser's UnaryNegate node instead.
pub fn canonical_literal(&self) -> String {
if self.denominator.is_one() && !self.numerator.is_negative() {
self.numerator.to_string()
} else {
format!("ratio({}, {})", self.numerator, self.denominator)
}
}
pub fn from_wire(wire: &ExactWire, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let n_digits = wire_digits(&wire.numerator, true)?;
let d_digits = wire_digits(&wire.denominator, false)?;
let n_bound = decimal_bits(n_digits.len());
let d_bound = decimal_bits(d_digits.len());
meter.numeric(
NumericOperation::ParseWire,
parse_cost(n_digits.len(), n_bound)
+ parse_cost(d_digits.len(), d_bound)
+ normalization_cost(n_bound, d_bound),
)?;
let numerator = parse_integer(&wire.numerator)?;
let denominator = parse_integer(&wire.denominator)?;
Self::check_bits(&numerator, &denominator, MAX_COMPONENT_BITS, "wire")?;
if denominator.is_zero() {
return Err(NumericError::ZeroDenominator);
}
if !numerator.gcd(&denominator).is_one() {
return Err(NumericError::NonCanonicalWire);
}
Ok(Self {
numerator,
denominator,
})
}
/// Reads one unsigned decimal/integer atom or a ratio(n,d) literal only.
/// It does not parse expressions, unary operators, units, calls or names.
/// Source ratios/decimals may reduce; wire values must already be canonical.
pub fn parse_literal(source: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
if source.len() > MAX_LITERAL_BYTES {
return Err(NumericError::LiteralTooLong);
}
let source = trim_ascii(source);
if let Some(body) = source.strip_prefix("ratio(") {
let body = body.strip_suffix(')').ok_or(NumericError::InvalidLiteral)?;
let (n, d) = body.split_once(',').ok_or(NumericError::InvalidLiteral)?;
return Self::parse_ratio(trim_ascii(n), trim_ascii(d), meter);
}
Self::parse_decimal(source, meter)
}
fn parse_ratio(n: &str, d: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
let n_digits = source_integer_digits(n, true)?;
let d_digits = source_integer_digits(d, false)?;
let n_bound = decimal_bits(n_digits.len());
let d_bound = decimal_bits(d_digits.len());
Self::check_estimates(n_bound, d_bound)?;
meter.numeric(
NumericOperation::ParseLiteral,
parse_cost(n_digits.len(), n_bound)
+ parse_cost(d_digits.len(), d_bound)
+ normalization_cost(n_bound, d_bound),
)?;
Self::normalize_precharged(parse_integer(n)?, parse_integer(d)?)
}
fn parse_decimal(source: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
let mut parts = source.split(['e', 'E']);
let mantissa = parts.next().ok_or(NumericError::InvalidLiteral)?;
let exponent = match parts.next() {
Some(text) => parse_exponent(text)?,
None => 0,
};
if parts.next().is_some() {
return Err(NumericError::InvalidLiteral);
}
let (whole, fraction) = match mantissa.split_once('.') {
Some((whole, fraction)) if !fraction.is_empty() => (whole, fraction),
Some(_) => return Err(NumericError::InvalidLiteral),
None => (mantissa, ""),
};
source_integer_digits(whole, false)?;
if !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(NumericError::InvalidLiteral);
}
let digit_count = whole.len() + fraction.len();
if digit_count > MAX_COMPONENT_DIGITS {
return Err(NumericError::LiteralTooLong);
}
let adjustment = exponent - fraction.len() as i32;
let power = adjustment.unsigned_abs();
let mantissa_bound = decimal_bits(digit_count);
let scale_bound = decimal_bits(power as usize + 1);
let (n_bound, d_bound) = if adjustment >= 0 {
(mantissa_bound + scale_bound, 1)
} else {
(mantissa_bound, scale_bound)
};
Self::check_estimates(n_bound, d_bound)?;
// Fixed logical allowance for constructing 10^power; independent of
// num-bigint's selected multiplication/exponentiation implementation.
let power_steps = 1 + 2 * u64::from(u32::BITS - power.leading_zeros());
meter.numeric(
NumericOperation::ParseLiteral,
parse_cost(digit_count, mantissa_bound)
+ power_steps * product_cost(scale_bound, scale_bound)
+ product_cost(mantissa_bound, scale_bound)
+ normalization_cost(n_bound, d_bound),
)?;
let digits = format!("{whole}{fraction}");
let mut numerator = parse_integer(&digits)?;
let scale = BigInt::from(10_u8).pow(power);
let denominator = if adjustment >= 0 {
numerator *= scale;
BigInt::one()
} else {
scale
};
Self::normalize_precharged(numerator, denominator)
}
pub fn add(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
self.add_or_subtract(rhs, false, meter)
}
pub fn subtract(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
self.add_or_subtract(rhs, true, meter)
}
fn add_or_subtract(
&self,
rhs: &Self,
subtract: bool,
meter: &mut WorkMeter,
) -> Result<Self, NumericError> {
let (a, b) = self.component_bits();
let (c, d) = rhs.component_bits();
let left_bound = a + d;
let right_bound = c + b;
let n_bound = left_bound.max(right_bound) + 1;
let d_bound = b + d;
Self::check_estimates(n_bound, d_bound)?;
meter.numeric(
if subtract {
NumericOperation::Subtract
} else {
NumericOperation::Add
},
product_cost(a, d)
+ product_cost(c, b)
+ sum_cost(left_bound, right_bound)
+ product_cost(b, d)
+ normalization_cost(n_bound, d_bound),
)?;
let left = &self.numerator * &rhs.denominator;
let right = &rhs.numerator * &self.denominator;
let numerator = if subtract { left - right } else { left + right };
let denominator = &self.denominator * &rhs.denominator;
Self::normalize_precharged(numerator, denominator)
}
pub fn multiply(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
let (a, b) = self.component_bits();
let (c, d) = rhs.component_bits();
Self::check_estimates(a + c, b + d)?;
meter.numeric(
NumericOperation::Multiply,
product_cost(a, c) + product_cost(b, d) + normalization_cost(a + c, b + d),
)?;
Self::normalize_precharged(
&self.numerator * &rhs.numerator,
&self.denominator * &rhs.denominator,
)
}
pub fn divide(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
let (a, b) = self.component_bits();
let (c, d) = rhs.component_bits();
Self::check_estimates(a + d, b + c)?;
meter.numeric(
NumericOperation::Divide,
product_cost(a, d) + product_cost(b, c) + normalization_cost(a + d, b + c),
)?;
if rhs.is_zero() {
return Err(NumericError::DivisionByZero);
}
Self::normalize_precharged(
&self.numerator * &rhs.denominator,
&self.denominator * &rhs.numerator,
)
}
pub fn compare(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Ordering, NumericError> {
let (a, b) = self.component_bits();
let (c, d) = rhs.component_bits();
Self::check_estimates((a + d).max(c + b), 1)?;
meter.numeric(
NumericOperation::Compare,
product_cost(a, d) + product_cost(c, b) + sum_cost(a + d, c + b),
)?;
Ok((&self.numerator * &rhs.denominator).cmp(&(&rhs.numerator * &self.denominator)))
}
pub fn negated(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.numeric(NumericOperation::Negate, self.copy_cost())?;
Ok(Self {
numerator: -&self.numerator,
denominator: self.denominator.clone(),
})
}
pub fn absolute(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.numeric(NumericOperation::Absolute, self.copy_cost())?;
Ok(Self {
numerator: self.numerator.abs(),
denominator: self.denominator.clone(),
})
}
pub fn reciprocal(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.numeric(NumericOperation::Reciprocal, self.copy_cost())?;
if self.is_zero() {
return Err(NumericError::DivisionByZero);
}
Ok(Self {
numerator: if self.numerator.is_negative() {
-&self.denominator
} else {
self.denominator.clone()
},
denominator: self.numerator.abs(),
})
}
/// Fixed left-to-right repeated multiplication, at most 16 multiplications.
/// Each reduced stage obeys the same component bound; no large power is
/// allocated and subsequently discarded after discovering it is oversized.
pub fn power(&self, exponent: i8, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.numeric(NumericOperation::Power, self.copy_cost())?;
if !(-MAX_INTEGER_POWER..=MAX_INTEGER_POWER).contains(&exponent) {
return Err(NumericError::IntegerPower);
}
if self.is_zero() && exponent == 0 {
return Err(NumericError::ZeroPowerZero);
}
let factor = if exponent < 0 {
self.reciprocal(meter)?
} else {
self.clone()
};
let mut value = Self::from_integer(1);
for _ in 0..exponent.unsigned_abs() {
value = value.multiply(&factor, meter)?;
}
Ok(value)
}
pub(super) fn copy_cost(&self) -> u64 {
let (n, d) = self.component_bits();
1 + words(n) + words(d)
}
fn normalize_precharged(
mut numerator: BigInt,
mut denominator: BigInt,
) -> Result<Self, NumericError> {
Self::check_bits(
&numerator,
&denominator,
MAX_INTERMEDIATE_BITS,
"intermediate",
)?;
if denominator.is_zero() {
return Err(NumericError::ZeroDenominator);
}
if denominator.is_negative() {
numerator = -numerator;
denominator = -denominator;
}
let gcd = numerator.gcd(&denominator);
numerator /= &gcd;
denominator /= gcd;
Self::check_bits(&numerator, &denominator, MAX_COMPONENT_BITS, "reduced")?;
Ok(Self {
numerator,
denominator,
})
}
fn check_estimates(n: u64, d: u64) -> Result<(), NumericError> {
Self::check_bit_count(
n,
NumberComponent::Numerator,
MAX_INTERMEDIATE_BITS,
"predicted",
)?;
Self::check_bit_count(
d,
NumberComponent::Denominator,
MAX_INTERMEDIATE_BITS,
"predicted",
)
}
fn check_bits(n: &BigInt, d: &BigInt, limit: u64, stage: &str) -> Result<(), NumericError> {
Self::check_bit_count(n.bits(), NumberComponent::Numerator, limit, stage)?;
Self::check_bit_count(d.bits(), NumberComponent::Denominator, limit, stage)
}
fn check_bit_count(
bits: u64,
component: NumberComponent,
limit: u64,
stage: &str,
) -> Result<(), NumericError> {
if bits > limit {
return Err(NumericError::Limit(NumericLimit::Bits {
component,
bits,
limit,
stage: stage.to_owned(),
}));
}
Ok(())
}
}
impl TryFrom<ExactWire> for Exact {
type Error = NumericError;
fn try_from(value: ExactWire) -> Result<Self, Self::Error> {
// BigInt validation is bounded after ExactWire strings have decoded.
// The adapter owns envelope/text/aggregate admission bounds and must not
// reset evaluation meters.
Self::from_wire(&value, &mut WorkMeter::new(WorkLimits::REFERENCE))
}
}
impl From<Exact> for ExactWire {
fn from(value: Exact) -> Self {
value.to_wire()
}
}
fn trim_ascii(text: &str) -> &str {
text.trim_matches(|ch: char| ch.is_ascii_whitespace())
}
fn source_integer_digits(text: &str, signed: bool) -> Result<&str, NumericError> {
let digits = if signed {
text.strip_prefix('-').unwrap_or(text)
} else {
text
};
if digits.len() > MAX_COMPONENT_DIGITS {
return Err(NumericError::LiteralTooLong);
}
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(NumericError::InvalidLiteral);
}
Ok(digits)
}
fn wire_digits(text: &str, signed: bool) -> Result<&str, NumericError> {
let digits = source_integer_digits(text, signed).map_err(|error| match error {
NumericError::LiteralTooLong => error,
_ => NumericError::NonCanonicalWire,
})?;
if (digits.len() > 1 && digits.starts_with('0')) || (text.starts_with('-') && digits == "0") {
return Err(NumericError::NonCanonicalWire);
}
Ok(digits)
}
fn parse_integer(text: &str) -> Result<BigInt, NumericError> {
BigInt::parse_bytes(text.as_bytes(), 10).ok_or(NumericError::InvalidLiteral)
}
fn parse_exponent(text: &str) -> Result<i32, NumericError> {
let (negative, digits) = if let Some(digits) = text.strip_prefix('-') {
(true, digits)
} else {
(false, text.strip_prefix('+').unwrap_or(text))
};
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(NumericError::InvalidLiteral);
}
let mut value = 0_i32;
for digit in digits.bytes() {
value = value * 10 + i32::from(digit - b'0');
if value > MAX_DECIMAL_EXPONENT {
return Err(NumericError::DecimalExponent);
}
}
Ok(if negative { -value } else { value })
}
fn decimal_bits(digits: usize) -> u64 {
// 3.322 exceeds log2(10); dimensions are bounded before this conversion.
(digits as u64 * 3322).div_ceil(1000).max(1)
}
@@ -0,0 +1,32 @@
[
{
"canonical_source": "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"expression": {
"Number": {
"denominator": "1",
"numerator": "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
},
"name": "ten_to_300"
},
{
"canonical_source": "ratio(1, 522194440706576253345876355358312191289982124523691890192116741641976953985778728424413405967498779170445053357219631418993786719092896803631618043925682638972978488271854999170180795067191859157214035005927973113188159419698856372836167342172293308748403954352901852035642024370059304557233988891799014503343469488440893892973452815095130470299789726716411734651513348221529512507986199933857107770846917779942645743159118957217248367043905936319748237550094520674504208530837546834166925275516486044134775384991808184705966507606898412918594045916828375610659246423184062775112999150206172392431297837246097308511903252956622805412865917690043804311051417135098849101156584508839003337597742539960818209685142687562392007453579567729991395256699805775897135553415567045292136442139895777424891477161767258532611634530697452993846501061481697843891439474220308003706472837459911525285821188577408160690315522951458068463354171428220365223949985950890732881736611925133626529949897998045399734600887312408859224933727829625089164535236559716582775403784110923285873186648442456409760158728501220463308455437074192539205964902261490928669488824051563042951500651206733594863336608245755565801460390869016718045121902354170201577095168)",
"expression": {
"Number": {
"denominator": "522194440706576253345876355358312191289982124523691890192116741641976953985778728424413405967498779170445053357219631418993786719092896803631618043925682638972978488271854999170180795067191859157214035005927973113188159419698856372836167342172293308748403954352901852035642024370059304557233988891799014503343469488440893892973452815095130470299789726716411734651513348221529512507986199933857107770846917779942645743159118957217248367043905936319748237550094520674504208530837546834166925275516486044134775384991808184705966507606898412918594045916828375610659246423184062775112999150206172392431297837246097308511903252956622805412865917690043804311051417135098849101156584508839003337597742539960818209685142687562392007453579567729991395256699805775897135553415567045292136442139895777424891477161767258532611634530697452993846501061481697843891439474220308003706472837459911525285821188577408160690315522951458068463354171428220365223949985950890732881736611925133626529949897998045399734600887312408859224933727829625089164535236559716582775403784110923285873186648442456409760158728501220463308455437074192539205964902261490928669488824051563042951500651206733594863336608245755565801460390869016718045121902354170201577095168",
"numerator": "1"
}
},
"name": "one_over_two_to_4095"
},
{
"canonical_source": "ratio(-1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335, 1)",
"expression": {
"Number": {
"denominator": "1",
"numerator": "-1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335"
}
},
"name": "negative_4096_bit_bound"
}
]
@@ -0,0 +1,240 @@
use super::{NumericError, NumericLimit};
use serde::{Deserialize, Serialize};
use thiserror::Error;
/// Every event is charged once per dynamic occurrence, before entering it.
///
/// A Call expression therefore charges Expression and CalculationEntry; a
/// Property read charges Expression and PropertyBinding. List element visits
/// are additional to evaluation of their expressions. Only executed branches
/// are charged. Targets are sorted by category (properties, then checks), then
/// stable UUID bytes, by the integrating evaluator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EvaluationStep {
Target,
Expression,
CalculationEntry,
PropertyBinding,
ListElement,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NumericOperation {
ParseWire,
ParseLiteral,
Add,
Subtract,
Multiply,
Divide,
Compare,
Negate,
Absolute,
Reciprocal,
Power,
KindAssertion,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkResource {
DynamicEvents,
NumericUnits,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkSite {
Evaluation(EvaluationStep),
Numeric(NumericOperation),
}
/// Failed reservations consume no partial charge. The first failure is latched.
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
#[error("{resource:?}: used {used}, requested {requested}, limit {limit}, at {site:?}")]
pub struct WorkExhaustion {
pub resource: WorkResource,
pub used: u64,
pub requested: u64,
pub limit: u64,
pub site: WorkSite,
}
/// Provisional calibration ceilings, not measured execution-time guarantees.
///
/// Effective limits, profile identity, capture, targets and context must all be
/// recorded in request/result/frozen identity. A caller may lower these ceilings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "WorkLimitsWire", into = "WorkLimitsWire")]
pub struct WorkLimits {
dynamic_events: u64,
numeric_units: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct WorkLimitsWire {
dynamic_events: u64,
numeric_units: u64,
}
impl WorkLimits {
pub const REFERENCE: Self = Self {
dynamic_events: 1_000_000,
numeric_units: 50_000_000,
};
pub fn new(dynamic_events: u64, numeric_units: u64) -> Result<Self, NumericError> {
if dynamic_events > Self::REFERENCE.dynamic_events
|| numeric_units > Self::REFERENCE.numeric_units
{
return Err(NumericError::InvalidWorkLimits);
}
Ok(Self {
dynamic_events,
numeric_units,
})
}
pub fn dynamic_events(self) -> u64 {
self.dynamic_events
}
pub fn numeric_units(self) -> u64 {
self.numeric_units
}
}
impl TryFrom<WorkLimitsWire> for WorkLimits {
type Error = NumericError;
fn try_from(value: WorkLimitsWire) -> Result<Self, Self::Error> {
Self::new(value.dynamic_events, value.numeric_units)
}
}
impl From<WorkLimits> for WorkLimitsWire {
fn from(value: WorkLimits) -> Self {
Self {
dynamic_events: value.dynamic_events,
numeric_units: value.numeric_units,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkUsage {
pub dynamic_events: u64,
pub numeric_units: u64,
}
/// Intentionally neither Clone nor Default: pass the same mutable meter through
/// every target, numeric operation and expanded call in one evaluation request.
///
/// Exhaustion is terminal. Integrators must stop traversing siblings/targets and
/// mark already collected causes as incomplete. Replaying an aggregate cache
/// cost is insufficient if it changes the exact exhaustion location; initially
/// retain logical traversal even when numerical values come from a cache.
#[derive(Debug)]
pub struct WorkMeter {
limits: WorkLimits,
usage: WorkUsage,
exhausted: Option<WorkExhaustion>,
}
impl WorkMeter {
pub fn new(limits: WorkLimits) -> Self {
Self {
limits,
usage: WorkUsage::default(),
exhausted: None,
}
}
pub fn limits(&self) -> WorkLimits {
self.limits
}
pub fn usage(&self) -> WorkUsage {
self.usage
}
pub fn exhaustion(&self) -> Option<&WorkExhaustion> {
self.exhausted.as_ref()
}
pub fn ensure_active(&self) -> Result<(), NumericError> {
match &self.exhausted {
Some(failure) => Err(NumericError::Limit(NumericLimit::Work(failure.clone()))),
None => Ok(()),
}
}
pub fn visit(&mut self, step: EvaluationStep) -> Result<(), NumericError> {
self.reserve(WorkResource::DynamicEvents, 1, WorkSite::Evaluation(step))
}
pub(super) fn numeric(
&mut self,
operation: NumericOperation,
units: u64,
) -> Result<(), NumericError> {
self.reserve(
WorkResource::NumericUnits,
units,
WorkSite::Numeric(operation),
)
}
fn reserve(
&mut self,
resource: WorkResource,
requested: u64,
site: WorkSite,
) -> Result<(), NumericError> {
self.ensure_active()?;
let (used, limit) = match resource {
WorkResource::DynamicEvents => (self.usage.dynamic_events, self.limits.dynamic_events),
WorkResource::NumericUnits => (self.usage.numeric_units, self.limits.numeric_units),
};
// Subtraction is safe: only successful reservations update usage.
if requested > limit - used {
let failure = WorkExhaustion {
resource,
used,
requested,
limit,
site,
};
self.exhausted = Some(failure.clone());
return Err(NumericError::Limit(NumericLimit::Work(failure)));
}
match resource {
WorkResource::DynamicEvents => self.usage.dynamic_events += requested,
WorkResource::NumericUnits => self.usage.numeric_units += requested,
}
Ok(())
}
}
// Logical 64-bit words are platform independent. These are deterministic
// accounting weights, not a claim about num-bigint's internal algorithm/timing.
pub(super) fn words(bits: u64) -> u64 {
bits.max(1).div_ceil(64)
}
pub(super) fn product_cost(a_bits: u64, b_bits: u64) -> u64 {
1 + words(a_bits) * words(b_bits)
}
pub(super) fn sum_cost(a_bits: u64, b_bits: u64) -> u64 {
1 + words(a_bits.max(b_bits))
}
pub(super) fn normalization_cost(n_bits: u64, d_bits: u64) -> u64 {
let width = words(n_bits.max(d_bits));
// 64*w² for GCD plus 2*w² for the two quotient operations.
1 + 66 * width * width
}
pub(super) fn parse_cost(digits: usize, estimated_bits: u64) -> u64 {
1 + digits as u64 * words(estimated_bits)
}
@@ -0,0 +1,378 @@
use super::{Dimension, Exact, MAX_INTEGER_POWER, NumericError, NumericOperation, WorkMeter};
use std::cmp::Ordering;
/// K is supplied by the common resolver's verified nominal compatibility
/// relation. It is not inferred from dimension/name/symbol/archive bytes here.
/// Coordinate basis/algebra/difference-kind closure must be part of that proof.
/// Exact definition references and pins remain the caller's provenance.
/// K must be a bounded, cheap-to-clone/compare verified handle. Constructing or
/// comparing an unbounded rooted contract graph is resolver admission work and
/// must not be hidden inside K's Clone/Eq implementations. Rust trait bounds do
/// not enforce this resource contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedKind<K> {
key: K,
dimension: Dimension,
difference: Option<K>,
}
impl<K> ResolvedKind<K> {
pub fn linear(key: K, dimension: Dimension) -> Self {
Self {
key,
dimension,
difference: None,
}
}
pub fn key(&self) -> &K {
&self.key
}
pub fn dimension(&self) -> Dimension {
self.dimension
}
pub fn is_affine(&self) -> bool {
self.difference.is_some()
}
}
impl<K: Clone + Eq> ResolvedKind<K> {
pub fn affine(key: K, difference: &Self) -> Result<Self, NumericError> {
if difference.is_affine() || key == difference.key {
return Err(NumericError::DifferenceKind);
}
Ok(Self {
key,
dimension: difference.dimension,
difference: Some(difference.key.clone()),
})
}
pub fn difference_kind(&self) -> Option<Self> {
self.difference
.as_ref()
.map(|key| Self::linear(key.clone(), self.dimension))
}
}
/// Canonical coordinate = magnitude * scale + offset.
/// Unit symbols and display preferences are outside this numeric representation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unit<K> {
kind: ResolvedKind<K>,
scale: Exact,
offset: Exact,
}
impl<K: Clone + Eq> Unit<K> {
pub fn new(kind: ResolvedKind<K>, scale: Exact, offset: Exact) -> Result<Self, NumericError> {
if !scale.is_positive() {
return Err(NumericError::UnitScale);
}
if !kind.is_affine() && !offset.is_zero() {
return Err(NumericError::LinearOffset);
}
Ok(Self {
kind,
scale,
offset,
})
}
pub fn kind(&self) -> &ResolvedKind<K> {
&self.kind
}
pub fn scale(&self) -> &Exact {
&self.scale
}
pub fn offset(&self) -> &Exact {
&self.offset
}
/// Fixed multiply-then-add path. Each reduced arithmetic stage is bounded.
/// A mathematically cancelling wider intermediate still reports NumericLimit;
/// replacing this path with a fused operation requires a new work profile.
pub fn to_canonical(
&self,
magnitude: &Exact,
meter: &mut WorkMeter,
) -> Result<Exact, NumericError> {
magnitude
.multiply(&self.scale, meter)?
.add(&self.offset, meter)
}
/// Fixed subtract-then-divide path; never rounds a coordinate.
pub fn from_canonical(
&self,
coordinate: &Exact,
meter: &mut WorkMeter,
) -> Result<Exact, NumericError> {
coordinate
.subtract(&self.offset, meter)?
.divide(&self.scale, meter)
}
pub fn convert(
&self,
magnitude: &Exact,
target: &Self,
meter: &mut WorkMeter,
) -> Result<Exact, NumericError> {
meter.ensure_active()?;
if self.kind != target.kind {
return Err(NumericError::IncompatibleTypes);
}
target.from_canonical(&self.to_canonical(magnitude, meter)?, meter)
}
}
/// Internal numerical types. Boolean/list/check semantics belong to the common
/// expression evaluator. Anonymous zero dimension normalizes to Number.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NumericType<K> {
Number,
Named(ResolvedKind<K>),
Anonymous(Dimension),
}
impl<K> NumericType<K> {
pub fn dimension(&self) -> Dimension {
match self {
Self::Number => Dimension::ZERO,
Self::Named(kind) => kind.dimension,
Self::Anonymous(dimension) => *dimension,
}
}
pub fn is_affine(&self) -> bool {
matches!(self, Self::Named(kind) if kind.is_affine())
}
fn anonymous(dimension: Dimension) -> Self {
if dimension.is_dimensionless() {
Self::Number
} else {
Self::Anonymous(dimension)
}
}
fn normalized(self) -> Self {
match self {
Self::Anonymous(dimension) => Self::anonymous(dimension),
other => other,
}
}
}
/// A canonical rational coordinate with an internal numerical type.
///
/// Derived Eq compares stored representation. Formal equality/ordering must call
/// compare(), which rejects mismatched nominal kinds instead of treating them
/// as a false predicate. Public property output must still check its declared
/// type and anchor the result to that declaration's exact definition reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumericValue<K> {
value_type: NumericType<K>,
coordinate: Exact,
}
impl<K: Clone + Eq> NumericValue<K> {
pub fn new(value_type: NumericType<K>, coordinate: Exact) -> Self {
Self {
value_type: value_type.normalized(),
coordinate,
}
}
pub fn number(coordinate: Exact) -> Self {
Self::new(NumericType::Number, coordinate)
}
pub fn from_unit(
magnitude: &Exact,
unit: &Unit<K>,
meter: &mut WorkMeter,
) -> Result<Self, NumericError> {
meter.ensure_active()?;
Ok(Self::new(
NumericType::Named(unit.kind.clone()),
unit.to_canonical(magnitude, meter)?,
))
}
pub fn value_type(&self) -> &NumericType<K> {
&self.value_type
}
pub fn coordinate(&self) -> &Exact {
&self.coordinate
}
pub fn display_in(&self, unit: &Unit<K>, meter: &mut WorkMeter) -> Result<Exact, NumericError> {
meter.ensure_active()?;
if !matches!(&self.value_type, NumericType::Named(kind) if kind == &unit.kind) {
return Err(NumericError::IncompatibleTypes);
}
unit.from_canonical(&self.coordinate, meter)
}
pub fn add(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let output = self.additive_type(rhs, false)?;
Ok(Self::new(
output,
self.coordinate.add(&rhs.coordinate, meter)?,
))
}
pub fn subtract(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let output = self.additive_type(rhs, true)?;
Ok(Self::new(
output,
self.coordinate.subtract(&rhs.coordinate, meter)?,
))
}
fn additive_type(&self, rhs: &Self, subtract: bool) -> Result<NumericType<K>, NumericError> {
use NumericType::{Anonymous, Named, Number};
match (&self.value_type, &rhs.value_type) {
(Number, Number) => Ok(Number),
(Anonymous(left), Anonymous(right)) if left == right => Ok(Anonymous(*left)),
(Named(left), Named(right)) => match (&left.difference, &right.difference) {
(None, None) if left == right => Ok(Named(left.clone())),
(Some(difference), Some(_)) if subtract && left == right => Ok(Named(
ResolvedKind::linear(difference.clone(), left.dimension),
)),
(Some(difference), None)
if difference == &right.key && left.dimension == right.dimension =>
{
Ok(Named(left.clone()))
}
(None, Some(difference))
if !subtract
&& difference == &left.key
&& left.dimension == right.dimension =>
{
Ok(Named(right.clone()))
}
_ => Err(NumericError::IncompatibleTypes),
},
_ => Err(NumericError::IncompatibleTypes),
}
}
pub fn multiply(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let output = self.multiplicative_type(rhs, false)?;
Ok(Self::new(
output,
self.coordinate.multiply(&rhs.coordinate, meter)?,
))
}
pub fn divide(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
let output = self.multiplicative_type(rhs, true)?;
Ok(Self::new(
output,
self.coordinate.divide(&rhs.coordinate, meter)?,
))
}
fn multiplicative_type(
&self,
rhs: &Self,
divide: bool,
) -> Result<NumericType<K>, NumericError> {
use NumericType::Number;
if self.value_type.is_affine() || rhs.value_type.is_affine() {
return Err(NumericError::AffineOperation);
}
match (&self.value_type, &rhs.value_type) {
(Number, Number) => Ok(Number),
(_, Number) => Ok(self.value_type.clone()),
(Number, _) if !divide => Ok(rhs.value_type.clone()),
_ => {
let left = self.value_type.dimension();
let right = rhs.value_type.dimension();
let dimension = if divide {
left.checked_quotient(right)?
} else {
left.checked_product(right)?
};
Ok(NumericType::anonymous(dimension))
}
}
}
pub fn negated(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
if self.value_type.is_affine() {
return Err(NumericError::AffineOperation);
}
Ok(Self::new(
self.value_type.clone(),
self.coordinate.negated(meter)?,
))
}
pub fn absolute(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
if self.value_type.is_affine() {
return Err(NumericError::AffineOperation);
}
Ok(Self::new(
self.value_type.clone(),
self.coordinate.absolute(meter)?,
))
}
pub fn power(&self, exponent: i8, meter: &mut WorkMeter) -> Result<Self, NumericError> {
meter.ensure_active()?;
if !(-MAX_INTEGER_POWER..=MAX_INTEGER_POWER).contains(&exponent) {
return Err(NumericError::IntegerPower);
}
if self.value_type.is_affine() {
return Err(NumericError::AffineOperation);
}
let output = match exponent {
0 => NumericType::Number,
1 => self.value_type.clone(),
_ => NumericType::anonymous(self.value_type.dimension().checked_power(exponent)?),
};
Ok(Self::new(output, self.coordinate.power(exponent, meter)?))
}
pub fn compare(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Ordering, NumericError> {
meter.ensure_active()?;
if self.value_type != rhs.value_type {
return Err(NumericError::IncompatibleTypes);
}
self.coordinate.compare(&rhs.coordinate, meter)
}
pub fn as_kind(
&self,
target: &ResolvedKind<K>,
meter: &mut WorkMeter,
) -> Result<Self, NumericError> {
meter.ensure_active()?;
if target.is_affine()
|| matches!(self.value_type, NumericType::Named(_))
|| self.value_type.dimension() != target.dimension
{
return Err(NumericError::KindAssertion);
}
meter.numeric(NumericOperation::KindAssertion, self.coordinate.copy_cost())?;
Ok(Self::new(
NumericType::Named(target.clone()),
self.coordinate.clone(),
))
}
}
@@ -0,0 +1,804 @@
use super::*;
use num_bigint::BigInt;
use num_traits::One;
use std::cmp::Ordering;
fn meter() -> WorkMeter {
WorkMeter::new(WorkLimits::REFERENCE)
}
fn exact(n: impl ToString, d: impl ToString) -> Exact {
Exact::from_wire(
&ExactWire {
numerator: n.to_string(),
denominator: d.to_string(),
},
&mut meter(),
)
.unwrap()
}
fn source(text: &str) -> Exact {
Exact::parse_literal(text, &mut meter()).unwrap()
}
fn assert_fraction(value: &Exact, n: impl ToString, d: impl ToString) {
assert_eq!(
value.to_wire(),
ExactWire {
numerator: n.to_string(),
denominator: d.to_string(),
}
);
}
// Independent bounded i128 oracle. It does not call the production Exact/GCD
// implementation when deriving expected arithmetic or ordering.
fn small_fraction(mut n: i128, mut d: i128) -> (i128, i128) {
assert_ne!(d, 0);
if d < 0 {
n = -n;
d = -d;
}
let (mut a, mut b) = (n.abs(), d);
while b != 0 {
(a, b) = (b, a % b);
}
(n / a, d / a)
}
#[test]
fn arithmetic_matches_independent_small_integer_oracle() {
for a in [-5_i128, -2, 0, 1, 4] {
for b in [1_i128, 2, 3, 7] {
for c in [-5_i128, -2, 0, 1, 4] {
for d in [1_i128, 2, 3, 7] {
let (an, ad) = small_fraction(a, b);
let (bn, bd) = small_fraction(c, d);
let left = exact(an, ad);
let right = exact(bn, bd);
let mut work = meter();
let (n, den) = small_fraction(a * d + c * b, b * d);
assert_fraction(&left.add(&right, &mut work).unwrap(), n, den);
let (n, den) = small_fraction(a * d - c * b, b * d);
assert_fraction(&left.subtract(&right, &mut work).unwrap(), n, den);
let (n, den) = small_fraction(a * c, b * d);
assert_fraction(&left.multiply(&right, &mut work).unwrap(), n, den);
if c != 0 {
let (n, den) = small_fraction(a * d, b * c);
assert_fraction(&left.divide(&right, &mut work).unwrap(), n, den);
} else {
assert_eq!(
left.divide(&right, &mut work),
Err(NumericError::DivisionByZero)
);
}
assert_eq!(
left.compare(&right, &mut work).unwrap(),
(a * d).cmp(&(c * b))
);
}
}
}
}
}
#[test]
fn decimals_are_exact_and_source_ratios_reduce() {
assert_fraction(
&source("0.1").add(&source("0.2"), &mut meter()).unwrap(),
3,
10,
);
assert_fraction(&source("0.50"), 1, 2);
assert_fraction(&source("12.50e-2"), 1, 8);
assert_fraction(&source("1e+3"), 1000, 1);
assert_fraction(&source("0001.2500"), 5, 4);
assert_fraction(&source(" ratio( -6, 8 ) "), -3, 4);
assert_fraction(&source("ratio(-0, 27)"), 0, 1);
assert_eq!(source("0.5").canonical_literal(), "ratio(1, 2)");
assert_eq!(source("42").canonical_literal(), "42");
}
#[test]
fn powers_and_signs_have_explicit_domains() {
let x = exact(-2, 3);
assert_fraction(&x.power(3, &mut meter()).unwrap(), -8, 27);
assert_fraction(&x.power(-3, &mut meter()).unwrap(), -27, 8);
assert_fraction(&x.power(0, &mut meter()).unwrap(), 1, 1);
assert_fraction(&x.absolute(&mut meter()).unwrap(), 2, 3);
assert_fraction(&x.negated(&mut meter()).unwrap(), 2, 3);
assert_fraction(&x.reciprocal(&mut meter()).unwrap(), -3, 2);
let zero = Exact::from_integer(0);
assert_eq!(
zero.power(0, &mut meter()),
Err(NumericError::ZeroPowerZero)
);
assert_eq!(
zero.power(-1, &mut meter()),
Err(NumericError::DivisionByZero)
);
assert_eq!(x.power(17, &mut meter()), Err(NumericError::IntegerPower));
assert_eq!(
x.power(i8::MIN, &mut meter()),
Err(NumericError::IntegerPower)
);
}
#[test]
fn canonical_wire_rejects_both_component_noncanonical_forms() {
for (n, d) in [
("+1", "1"),
("01", "1"),
("-0", "1"),
("1", "+1"),
("1", "-1"),
("1", "01"),
("2", "4"),
("0", "3"),
("", "1"),
("1", ""),
("1.0", "1"),
("1", "1.0"),
("1e1", "1"),
("1", "1e1"),
(" 1", "1"),
("1", "1 "),
] {
assert!(
Exact::from_wire(
&ExactWire {
numerator: n.into(),
denominator: d.into()
},
&mut meter(),
)
.is_err(),
"accepted {n}/{d}"
);
}
assert_eq!(
Exact::from_wire(
&ExactWire {
numerator: "1".into(),
denominator: "0".into()
},
&mut meter()
),
Err(NumericError::ZeroDenominator)
);
assert_fraction(&exact(0, 1), 0, 1);
assert_fraction(&exact(-1, 2), -1, 2);
}
#[test]
fn serde_uses_closed_canonical_string_wire() {
let value = exact(-3, 7);
let encoded = serde_json::to_value(&value).unwrap();
assert_eq!(
encoded,
serde_json::json!({"numerator":"-3","denominator":"7"})
);
assert_eq!(serde_json::from_value::<Exact>(encoded).unwrap(), value);
for invalid in [
r#"{"numerator":1,"denominator":"2"}"#,
r#"{"numerator":"1","denominator":2}"#,
r#"{"numerator":"1","denominator":"2","other":0}"#,
r#"{"numerator":"1","numerator":"2","denominator":"3"}"#,
r#"{"numerator":"1"}"#,
r#"{"numerator":"2","denominator":"4"}"#,
] {
assert!(serde_json::from_str::<Exact>(invalid).is_err(), "{invalid}");
}
}
#[test]
fn literal_reader_does_not_fold_expression_unary_minus() {
assert_eq!(
Exact::parse_literal("-2", &mut meter()),
Err(NumericError::InvalidLiteral)
);
let negative_literal = source("ratio(-2, 1)");
assert_eq!(negative_literal.canonical_literal(), "ratio(-2, 1)");
assert_eq!(source("2").negated(&mut meter()).unwrap(), negative_literal);
// Equality of coordinates does not claim AST equality. The expression
// parser must preserve UnaryNegate independently of its operand literal.
assert_eq!(source("2").canonical_literal(), "2");
}
#[test]
fn literal_syntax_and_decimal_exponent_are_bounded() {
for invalid in [
"",
"-",
"+1",
".5",
"1.",
"1.2.3",
"1e",
"1ee2",
"1e+-2",
"1_000",
"NaN",
"Infinity",
"1/2",
"ratio(1)",
"ratio(1,2,3)",
"ratio(1,-2)",
"ratio(+1,2)",
"ratio(1,2) + 1",
"12",
] {
assert!(
Exact::parse_literal(invalid, &mut meter()).is_err(),
"{invalid}"
);
}
for invalid in ["1e129", "1e-129", "1e9999999999999999999999"] {
assert_eq!(
Exact::parse_literal(invalid, &mut meter()),
Err(NumericError::DecimalExponent)
);
}
assert!(Exact::parse_literal("1e128", &mut meter()).is_ok());
assert!(Exact::parse_literal("1e-128", &mut meter()).is_ok());
assert_eq!(
Exact::parse_literal(&"1".repeat(MAX_COMPONENT_DIGITS + 1), &mut meter()),
Err(NumericError::LiteralTooLong)
);
assert_eq!(
Exact::parse_literal(&" ".repeat(MAX_LITERAL_BYTES + 1), &mut meter()),
Err(NumericError::LiteralTooLong)
);
}
#[test]
fn full_independent_r7_packets_round_trip_as_literals_and_wire() {
let packets: serde_json::Value =
serde_json::from_str(include_str!("fixtures/r7-literal-boundaries.json")).unwrap();
for packet in packets.as_array().unwrap() {
let wire: ExactWire =
serde_json::from_value(packet["expression"]["Number"].clone()).unwrap();
let expected = Exact::from_wire(&wire, &mut meter()).unwrap();
let spelling = packet["canonical_source"].as_str().unwrap();
assert_eq!(expected.canonical_literal(), spelling);
assert_eq!(
Exact::parse_literal(spelling, &mut meter()).unwrap(),
expected
);
let serialized = serde_json::to_string(&expected).unwrap();
assert_eq!(
serde_json::from_str::<Exact>(&serialized).unwrap(),
expected
);
assert_eq!(expected.to_wire(), wire);
}
}
#[test]
fn full_8193_bit_sum_intermediate_can_reduce_to_admitted_value() {
// N=(2^4096)-1, D=N-1. gcd(N,D)=1 and D is even.
// N/D + N/D = N/(D/2), although its un-reduced numerator needs 8193 bits.
let n = (BigInt::one() << 4096_usize) - 1_u8;
let d = &n - 1_u8;
let value = exact(&n, &d);
let result = value.add(&value, &mut meter()).unwrap();
assert_fraction(&result, &n, &d / 2_u8);
}
#[test]
fn cross_products_cancel_before_reduced_component_limit() {
let n = BigInt::one() << 4095_usize;
let d = &n - 1_u8;
let left = exact(&n, &d);
let right = exact(&d, &n);
assert_fraction(&left.multiply(&right, &mut meter()).unwrap(), 1, 1);
assert_fraction(
&left
.add(&left.negated(&mut meter()).unwrap(), &mut meter())
.unwrap(),
0,
1,
);
}
#[test]
fn both_reduced_component_overflows_are_reported() {
let n = BigInt::one() << 4095_usize;
let mut work = meter();
let failure = exact(&n, 1)
.multiply(&Exact::from_integer(2), &mut work)
.unwrap_err();
assert!(matches!(
failure,
NumericError::Limit(NumericLimit::Bits {
component: NumberComponent::Numerator,
bits: 4097,
..
})
));
assert!(work.exhaustion().is_none());
let failure = exact(1, &n)
.divide(&Exact::from_integer(2), &mut work)
.unwrap_err();
assert!(matches!(
failure,
NumericError::Limit(NumericLimit::Bits {
component: NumberComponent::Denominator,
bits: 4097,
..
})
));
// Value overflow is a nonterminal supported-operation failure; fuel
// exhaustion, in contrast, terminates the entire request.
assert_fraction(&source("1").add(&source("1"), &mut work).unwrap(), 2, 1);
}
#[test]
fn wire_rejects_4097_bits_before_gcd_can_reduce_them() {
let oversized = (BigInt::one() << 4096_usize).to_string();
for wire in [
ExactWire {
numerator: oversized.clone(),
denominator: "1".into(),
},
ExactWire {
numerator: "1".into(),
denominator: oversized.clone(),
},
ExactWire {
numerator: oversized.clone(),
denominator: oversized,
},
] {
assert!(matches!(
Exact::from_wire(&wire, &mut meter()),
Err(NumericError::Limit(NumericLimit::Bits { stage, .. })) if stage == "wire"
));
}
}
#[test]
fn numeric_precharge_precedes_big_integer_result_allocation() {
let n = BigInt::one() << 4095_usize;
let left = exact(&n, 1);
let mut work = WorkMeter::new(WorkLimits::new(10, 0).unwrap());
let failure = left
.multiply(&Exact::from_integer(2), &mut work)
.unwrap_err();
assert!(failure.is_terminal_work_exhaustion());
assert_eq!(work.usage().numeric_units, 0);
assert!(matches!(
work.exhaustion().unwrap().site,
WorkSite::Numeric(NumericOperation::Multiply)
));
// With available fuel the same operation reaches the 4097-bit result check.
assert!(matches!(
left.multiply(&Exact::from_integer(2), &mut meter()),
Err(NumericError::Limit(NumericLimit::Bits { .. }))
));
let too_wide_wire = ExactWire {
numerator: (BigInt::one() << 4096_usize).to_string(),
denominator: "1".into(),
};
let mut parse_work = WorkMeter::new(WorkLimits::new(0, 0).unwrap());
assert!(
Exact::from_wire(&too_wide_wire, &mut parse_work)
.unwrap_err()
.is_terminal_work_exhaustion()
);
}
#[test]
fn provisional_limits_and_effective_limits_round_trip() {
let limits = WorkLimits::new(500, 2000).unwrap();
let encoded = serde_json::to_value(limits).unwrap();
assert_eq!(
encoded,
serde_json::json!({"dynamic_events":500,"numeric_units":2000})
);
assert_eq!(
serde_json::from_value::<WorkLimits>(encoded).unwrap(),
limits
);
assert_eq!(
WorkLimits::new(1_000_001, 0),
Err(NumericError::InvalidWorkLimits)
);
assert_eq!(
WorkLimits::new(0, 50_000_001),
Err(NumericError::InvalidWorkLimits)
);
assert!(
serde_json::from_str::<WorkLimits>(r#"{"dynamic_events":1000001,"numeric_units":0}"#)
.is_err()
);
}
#[test]
fn exact_accounting_boundary_and_terminal_failure_are_stable() {
// One-word addition: three products at 2, one sum at 2,
// normalization at 67 => 75 logical numeric units.
let mut work = WorkMeter::new(WorkLimits::new(4, 75).unwrap());
assert_fraction(&exact(1, 2).add(&exact(1, 3), &mut work).unwrap(), 5, 6);
assert_eq!(work.usage().numeric_units, 75);
assert!(work.exhaustion().is_none());
let first = Exact::from_integer(1).negated(&mut work).unwrap_err();
let at_failure = work.usage();
assert_eq!(
work.exhaustion().unwrap(),
&WorkExhaustion {
resource: WorkResource::NumericUnits,
used: 75,
requested: 3,
limit: 75,
site: WorkSite::Numeric(NumericOperation::Negate),
}
);
assert_eq!(work.visit(EvaluationStep::Target).unwrap_err(), first);
assert_eq!(
Exact::from_integer(1)
.divide(&Exact::from_integer(0), &mut work)
.unwrap_err(),
first
);
assert_eq!(
work.numeric(NumericOperation::Compare, 0).unwrap_err(),
first
);
assert_eq!(work.usage(), at_failure);
}
#[test]
fn zero_cost_and_maximum_reservation_do_not_underflow_or_reactivate() {
let mut work = WorkMeter::new(WorkLimits::new(0, 0).unwrap());
work.numeric(NumericOperation::Compare, 0).unwrap();
let failure = work
.numeric(NumericOperation::Multiply, u64::MAX)
.unwrap_err();
assert!(failure.is_terminal_work_exhaustion());
assert_eq!(work.usage(), WorkUsage::default());
assert_eq!(
work.numeric(NumericOperation::Compare, 0).unwrap_err(),
failure
);
let mut dynamic = WorkMeter::new(WorkLimits::new(0, 5).unwrap());
assert!(dynamic.visit(EvaluationStep::Target).is_err());
assert_eq!(dynamic.usage(), WorkUsage::default());
}
#[test]
fn multiple_targets_share_one_aggregate_meter() {
let mut work = WorkMeter::new(WorkLimits::new(3, 50).unwrap());
work.visit(EvaluationStep::Target).unwrap();
work.visit(EvaluationStep::Expression).unwrap();
work.visit(EvaluationStep::Target).unwrap();
let failure = work.visit(EvaluationStep::Expression).unwrap_err();
assert!(failure.is_terminal_work_exhaustion());
assert_eq!(work.usage().dynamic_events, 3);
}
// A direct bounded call-tree workload, not an expression interpreter/dialect.
fn expanded_calls(
depth: u8,
x: u64,
work: &mut WorkMeter,
entered: &mut u64,
) -> Result<u64, NumericError> {
work.visit(EvaluationStep::CalculationEntry)?;
*entered += 1;
if depth == 0 {
return Ok(x);
}
let left = expanded_calls(depth - 1, 2 * x, work, entered)?;
let right = expanded_calls(depth - 1, 2 * x + 1, work, entered)?;
Ok(left + right)
}
#[test]
fn c1_expanded_call_witness_terminates_at_dynamic_limit() {
let mut work = WorkMeter::new(WorkLimits::new(10_000, 0).unwrap());
let mut entered = 0;
let failure = expanded_calls(30, 0, &mut work, &mut entered).unwrap_err();
assert!(failure.is_terminal_work_exhaustion());
assert_eq!(entered, 10_000);
assert_eq!(work.usage().dynamic_events, 10_000);
assert_eq!(
work.exhaustion().unwrap().site,
WorkSite::Evaluation(EvaluationStep::CalculationEntry)
);
// Nearby finite control: 63 invocations, leaves 0..31, sum 496.
let mut bounded = WorkMeter::new(WorkLimits::new(63, 0).unwrap());
let mut entered = 0;
assert_eq!(
expanded_calls(5, 0, &mut bounded, &mut entered).unwrap(),
496
);
assert_eq!(entered, 63);
assert!(bounded.exhaustion().is_none());
}
fn dim(value: [i16; 7]) -> Dimension {
Dimension::new(value).unwrap()
}
fn linear(key: &str, dimension: Dimension) -> ResolvedKind<String> {
ResolvedKind::linear(key.to_owned(), dimension)
}
fn named(n: i64, kind: &ResolvedKind<String>) -> NumericValue<String> {
NumericValue::new(NumericType::Named(kind.clone()), Exact::from_integer(n))
}
#[test]
fn dimensions_use_checked_seven_axis_integer_algebra() {
let length = dim([1, 0, 0, 0, 0, 0, 0]);
let mass = dim([0, 1, 0, 0, 0, 0, 0]);
let time = dim([0, 0, 1, 0, 0, 0, 0]);
assert_eq!(
mass.checked_product(length)
.unwrap()
.checked_quotient(time.checked_power(2).unwrap())
.unwrap(),
dim([1, 1, -2, 0, 0, 0, 0])
);
assert!(time.checked_quotient(time).unwrap().is_dimensionless());
assert!(matches!(
dim([32, 0, 0, 0, 0, 0, 0]).checked_product(length),
Err(NumericError::DimensionExponent {
axis: DimensionAxis::Length,
value: 33
})
));
assert!(dim([0, 0, -32, 0, 0, 0, 0]).checked_quotient(time).is_err());
assert!(length.checked_power(i8::MIN).is_err());
assert!(Dimension::new([33, 0, 0, 0, 0, 0, 0]).is_err());
assert_eq!(
serde_json::to_value(time).unwrap(),
serde_json::json!([0, 0, 1, 0, 0, 0, 0])
);
for invalid in ["[0,0,33,0,0,0,0]", "[0,0,1]", "[0,0,1,0,0,0,0,0]"] {
assert!(serde_json::from_str::<Dimension>(invalid).is_err());
}
}
#[test]
fn duration_unit_coordinates_are_exact_and_nominal() {
let duration = linear("duration", dim([0, 0, 1, 0, 0, 0, 0]));
let s = Unit::new(duration.clone(), source("1"), source("0")).unwrap();
let ms = Unit::new(duration.clone(), source("0.001"), source("0")).unwrap();
assert_fraction(&ms.convert(&source("750"), &s, &mut meter()).unwrap(), 3, 4);
let receive = NumericValue::from_unit(&source("750"), &ms, &mut meter()).unwrap();
let dispatch = NumericValue::from_unit(&source("1"), &s, &mut meter()).unwrap();
let total = receive.add(&dispatch, &mut meter()).unwrap();
assert_fraction(total.coordinate(), 7, 4);
assert_fraction(&total.display_in(&ms, &mut meter()).unwrap(), 1750, 1);
let different = Unit::new(
linear("different-kind", duration.dimension()),
source("1"),
source("0"),
)
.unwrap();
assert_eq!(
ms.convert(&source("750"), &different, &mut meter()),
Err(NumericError::IncompatibleTypes)
);
let inconsistent = Unit::new(
linear("duration", dim([1, 0, 0, 0, 0, 0, 0])),
source("1"),
source("0"),
)
.unwrap();
assert!(
ms.convert(&source("1"), &inconsistent, &mut meter())
.is_err()
);
assert!(Unit::new(duration.clone(), source("0"), source("0")).is_err());
assert!(Unit::new(duration.clone(), source("ratio(-1,1)"), source("0")).is_err());
assert_eq!(
Unit::new(duration, source("1"), source("1")).unwrap_err(),
NumericError::LinearOffset
);
}
#[test]
fn affine_point_and_difference_arithmetic_has_distinct_kinds() {
let interval = linear("temperature-difference", dim([0, 0, 0, 0, 1, 0, 0]));
let point = ResolvedKind::affine("temperature-point".to_owned(), &interval).unwrap();
let celsius = Unit::new(point.clone(), source("1"), source("273.15")).unwrap();
let fahrenheit = Unit::new(
point.clone(),
source("ratio(5,9)"),
source("ratio(45967,180)"),
)
.unwrap();
let kelvin_interval = Unit::new(interval.clone(), source("1"), source("0")).unwrap();
assert_fraction(
&celsius
.convert(&source("0"), &fahrenheit, &mut meter())
.unwrap(),
32,
1,
);
assert_fraction(
&fahrenheit
.convert(&source("70"), &celsius, &mut meter())
.unwrap(),
190,
9,
);
let p20 = NumericValue::from_unit(&source("20"), &celsius, &mut meter()).unwrap();
let p10 = NumericValue::from_unit(&source("10"), &celsius, &mut meter()).unwrap();
let difference = p20.subtract(&p10, &mut meter()).unwrap();
assert_eq!(
difference.value_type(),
&NumericType::Named(interval.clone())
);
assert_fraction(
&difference
.display_in(&kelvin_interval, &mut meter())
.unwrap(),
10,
1,
);
let delta5 = named(5, &interval);
let p25 = p20.add(&delta5, &mut meter()).unwrap();
assert_fraction(&p25.display_in(&celsius, &mut meter()).unwrap(), 25, 1);
assert_eq!(delta5.add(&p20, &mut meter()).unwrap(), p25);
assert!(p20.add(&p10, &mut meter()).is_err());
assert!(delta5.subtract(&p20, &mut meter()).is_err());
assert_eq!(
p20.power(1, &mut meter()),
Err(NumericError::AffineOperation)
);
assert_eq!(
p20.negated(&mut meter()),
Err(NumericError::AffineOperation)
);
assert_eq!(p20.compare(&p10, &mut meter()).unwrap(), Ordering::Greater);
assert!(p20.display_in(&kelvin_interval, &mut meter()).is_err());
assert!(ResolvedKind::affine(interval.key().clone(), &interval).is_err());
assert!(ResolvedKind::affine("other".to_owned(), &point).is_err());
}
#[test]
fn affine_conversion_rejects_a_wider_stage_even_when_the_final_value_would_fit() {
// A fused coordinate calculation 2*m-m equals m, where m=2^4095 fits.
// The fixed multiply stage produces 2^4096, so it must fail before offset
// cancellation. The inverse path likewise rejects (m-(-m))/2 at subtraction.
let large = BigInt::one() << 4095_usize;
let magnitude = exact(&large, 1);
let interval = linear("temperature-interval", dim([0, 0, 0, 0, 1, 0, 0]));
let point = ResolvedKind::affine("temperature-point".to_owned(), &interval).unwrap();
let unit = Unit::new(point, Exact::from_integer(2), exact(-&large, 1)).unwrap();
let mut work = meter();
for outcome in [
unit.to_canonical(&magnitude, &mut work),
unit.from_canonical(&magnitude, &mut work),
] {
assert!(matches!(
outcome,
Err(NumericError::Limit(NumericLimit::Bits {
component: NumberComponent::Numerator,
bits: 4097,
limit: MAX_COMPONENT_BITS,
..
}))
));
}
assert!(work.exhaustion().is_none());
let half = exact(&large >> 1_usize, 1);
assert_fraction(&unit.to_canonical(&half, &mut work).unwrap(), 0, 1);
assert_eq!(
unit.from_canonical(&Exact::from_integer(0), &mut work)
.unwrap(),
half
);
}
#[test]
fn r6_anonymous_compound_energy_needs_one_outer_assertion() {
let force = linear("force", dim([1, 1, -2, 0, 0, 0, 0]));
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
let energy = linear("energy", dim([2, 1, -2, 0, 0, 0, 0]));
let a = named(3, &force)
.multiply(&named(4, &length), &mut meter())
.unwrap();
let b = named(2, &force)
.multiply(&named(7, &length), &mut meter())
.unwrap();
assert_eq!(a.value_type(), &NumericType::Anonymous(energy.dimension()));
let sum = a.add(&b, &mut meter()).unwrap();
let result = sum.as_kind(&energy, &mut meter()).unwrap();
assert_fraction(result.coordinate(), 26, 1);
assert_eq!(result.value_type(), &NumericType::Named(energy.clone()));
assert_eq!(a.compare(&b, &mut meter()).unwrap(), Ordering::Less);
assert!(result.add(&sum, &mut meter()).is_err());
assert_eq!(
result.as_kind(&energy, &mut meter()),
Err(NumericError::KindAssertion)
);
}
#[test]
fn anonymous_product_then_quotient_closes_and_preserves_scaling() {
let mass = linear("mass", dim([0, 1, 0, 0, 0, 0, 0]));
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
let time = linear("duration", dim([0, 0, 1, 0, 0, 0, 0]));
let momentum = linear("momentum", dim([1, 1, -1, 0, 0, 0, 0]));
let result = named(2, &mass)
.multiply(&named(3, &length), &mut meter())
.unwrap()
.divide(&named(2, &time), &mut meter())
.unwrap()
.as_kind(&momentum, &mut meter())
.unwrap();
assert_fraction(result.coordinate(), 3, 1);
let scalar = NumericValue::number(source("2"));
let scaled = scalar.multiply(&named(3, &time), &mut meter()).unwrap();
assert_eq!(scaled.value_type(), &NumericType::Named(time.clone()));
assert_fraction(scaled.coordinate(), 6, 1);
assert_eq!(
named(3, &time)
.divide(&scalar, &mut meter())
.unwrap()
.value_type(),
&NumericType::Named(time.clone())
);
assert_eq!(
scalar
.divide(&named(3, &time), &mut meter())
.unwrap()
.value_type(),
&NumericType::Anonymous(dim([0, 0, -1, 0, 0, 0, 0]))
);
}
#[test]
fn nominal_kinds_survive_comparison_but_explicit_quotients_can_erase_dimension() {
let energy = linear("energy", dim([2, 1, -2, 0, 0, 0, 0]));
let torque = linear("torque", energy.dimension());
let left = named(7, &energy);
let right = named(7, &torque);
assert!(left.add(&right, &mut meter()).is_err());
assert!(left.compare(&right, &mut meter()).is_err());
let ratio = left.divide(&right, &mut meter()).unwrap();
assert_eq!(ratio.value_type(), &NumericType::Number);
assert_fraction(ratio.coordinate(), 1, 1);
let named_ratio = linear("chosen-ratio", Dimension::ZERO);
let asserted = ratio.as_kind(&named_ratio, &mut meter()).unwrap();
assert_eq!(
asserted.value_type(),
&NumericType::Named(named_ratio.clone())
);
assert!(asserted.add(&ratio, &mut meter()).is_err());
assert_eq!(
NumericValue::<String>::new(NumericType::Anonymous(Dimension::ZERO), source("1")),
NumericValue::number(source("1"))
);
}
#[test]
fn numerical_power_types_and_dimension_overflow_are_checked() {
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
let value = named(2, &length);
assert_eq!(
value.power(0, &mut meter()).unwrap().value_type(),
&NumericType::Number
);
assert_eq!(
value.power(1, &mut meter()).unwrap().value_type(),
value.value_type()
);
assert_eq!(
value.power(-2, &mut meter()).unwrap().value_type(),
&NumericType::Anonymous(dim([-2, 0, 0, 0, 0, 0, 0]))
);
let large_dimension = linear("large-dimension", dim([32, 0, 0, 0, 0, 0, 0]));
assert!(
named(1, &large_dimension)
.multiply(&value, &mut meter())
.is_err()
);
assert!(named(1, &large_dimension).power(2, &mut meter()).is_err());
}
+1
View File
@@ -1,4 +1,5 @@
//! Framework-independent OA/SA model, transactional commands and editing services.
pub mod analysis_numeric;
pub mod data;
pub mod language;
pub mod model;
+357 -23
View File
@@ -5,6 +5,7 @@ mod checkpoints;
#[cfg(test)]
mod diagram_selection_tests;
mod hosted;
mod reference_authoring;
#[cfg(test)]
mod review_navigation_tests;
#[cfg(test)]
@@ -13,6 +14,7 @@ mod transition_context_tests;
mod view_copy_tests;
use crate::forms::Draft;
use crate::{
behavior,
document::Document,
source_workspace::{self, LIMITS, Workspace},
};
@@ -317,6 +319,7 @@ pub struct FilePrompt {
#[derive(Debug, Clone)]
pub enum Message {
BehaviorControl(behavior::canvas_workspace::Intent),
Architecture(architecture_authoring::Event),
Home(crate::home::Event),
CheckpointTick,
@@ -370,6 +373,8 @@ pub enum Message {
FieldValuePath(String, crate::data_values::FieldPathKey),
FieldValueBrowse(String, Option<crate::data_values::FieldPathKey>, usize),
FieldReferenceBrowse(String, String, usize),
FieldReferenceOpen(crate::forms::reference_chooser::adapter::Open),
FieldReferenceEvent(crate::forms::reference_chooser::Event),
FieldVariant(String, Value),
FieldArray(String, Option<usize>, i32),
Apply,
@@ -444,10 +449,14 @@ pub struct App {
pub hosted: crate::hosted::State,
pub connection: Option<crate::connection_edit::Session>,
pub model_menu: Option<crate::model_menu::Opened>,
reference_authoring: reference_authoring::State,
pub source_tree: crate::source_tree::State,
menu_sequence: u64,
pub canvas_document: Id,
pub canvas_epoch: u64,
/// Camera batches survive their own updates, never external presentation changes.
pub camera_epoch: u64,
camera_boundary_epoch: u64,
pub selected_bend: Option<(Id, usize)>,
pub exact_strings: bool,
pub document: Document,
@@ -546,10 +555,13 @@ impl App {
checkpoint_close: None,
connection: None,
model_menu: None,
reference_authoring: Default::default(),
source_tree: Default::default(),
menu_sequence: 0,
canvas_document: Id::new_v4(),
canvas_epoch: 0,
camera_epoch: 0,
camera_boundary_epoch: 0,
selected_bend: None,
exact_strings: false,
document,
@@ -849,14 +861,28 @@ impl App {
}
fn execute(&mut self, command: Command) -> bool {
let command = crate::port_edit::repair_owner_change(self.project(), command);
let created = self.behavior.creation.created_by(self.project(), &command);
let scenario_selection = self
.behavior
.scenario
.created_selection(&command)
.or_else(|| self.behavior.topology.created_selection(&command));
.created_selection(self.project(), &command)
.or_else(|| {
self.behavior
.topology
.created_selection(self.project(), &command)
});
match self.document.execute(command) {
Ok(selected) => {
if let Some(id) = scenario_selection.or(selected) {
if let Some(created) = created {
self.layer = created.layer;
self.selected = created.behavior;
self.selected_node = None;
self.behavior.active_owner = Some(created.behavior);
self.behavior.diagram = behavior::state_view::State::default();
self.behavior.diagram.diagram = created.diagram;
self.page = Page::Behavior;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
} else if let Some(id) = scenario_selection.or(selected) {
self.selected = id;
}
self.sync();
@@ -1012,13 +1038,21 @@ impl App {
crate::model_menu::popup(self),
)
.into();
crate::hosted::view::overlay(self, base)
behavior::canvas_workspace::focus_root(
crate::hosted::view::overlay(self, self.reference_overlay(base)),
behavior::canvas_workspace::Scope::input_owner(self),
)
}
pub fn subscription(&self) -> Subscription<Message> {
Subscription::batch([
iced::time::every(std::time::Duration::from_secs(10)).map(|_| Message::CheckpointTick),
window::close_requests().map(|id| Message::Request(Pending::Close(id))),
window::resize_events().map(|(_, size)| Message::WindowResized(size)),
architecture_authoring::subscription(self),
behavior::creation::subscription(
self.behavior.creation.has_pending() || self.behavior.source_active(),
)
.map(|()| Message::Escape),
iced::event::listen_with(|event, status, _| {
let iced::Event::Keyboard(keyboard::Event::KeyPressed {
key,
@@ -1063,6 +1097,108 @@ impl App {
])
}
pub fn update(&mut self, message: Message) -> Task<Message> {
if let Message::BehaviorControl(intent) = message {
return self.behavior_control(intent);
}
let camera = matches!(
&message,
Message::ScenarioCanvas(crate::behavior::scenario::CanvasEvent::Camera(..))
| Message::TopologyCanvas(crate::behavior::topology::CanvasEvent::Camera(..))
);
let before = self.camera_boundary();
let task = self.update_inner(message);
if !camera && self.camera_boundary() != before {
self.camera_epoch = self.camera_epoch.wrapping_add(1);
self.camera_boundary_epoch = self.canvas_epoch;
}
task
}
fn behavior_control(&mut self, intent: behavior::canvas_workspace::Intent) -> Task<Message> {
use behavior::canvas_workspace::{self, Event as Camera, Scope};
use behavior::scenario::CanvasEvent as Scenario;
use behavior::topology::CanvasEvent as Process;
if Scope::input_owner(self) != Some(intent.scope) {
return Task::none();
}
let mut message = *intent.message;
let scope = intent.scope;
let valid_scenario = |c: behavior::scenario::Context| {
c.document == scope.document
&& c.scenario == scope.owner
&& c.revision == scope.revision
&& self.camera_toolbar_epoch(c.epoch)
};
let valid_process = |c: behavior::topology::Context| {
c.document == scope.document
&& c.owner == scope.owner
&& c.revision == scope.revision
&& self.camera_toolbar_epoch(c.epoch)
};
// This whitelist contains only the production presentation controls.
// A stamped toolbar cannot smuggle an arbitrary authoring command.
match &mut message {
Message::ScenarioCanvas(Scenario::Camera(c, lifetime, Camera::Focus))
if valid_scenario(*c) && *lifetime == scope.epoch =>
{
return canvas_workspace::focus_task(scope, Camera::Focus);
}
Message::TopologyCanvas(Process::Camera(c, lifetime, Camera::Focus))
if valid_process(*c) && *lifetime == scope.epoch =>
{
return canvas_workspace::focus_task(scope, Camera::Focus);
}
Message::ScenarioCanvas(
Scenario::Zoom(c, _)
| Scenario::Choose(c, _)
| Scenario::Focus(c)
| Scenario::Shelf(c, _),
) if valid_scenario(*c) => {
c.epoch = self.canvas_epoch;
}
Message::TopologyCanvas(
Process::Zoom(c, _) | Process::Choose(c, _) | Process::Focus(c),
) if valid_process(*c) => {
c.epoch = self.canvas_epoch;
}
Message::Behavior(behavior::Event::Topology(behavior::topology::Event::Shelf(_)))
if self.topology_context().is_some() => {}
_ => return Task::none(),
}
let task = self.update(message);
// Reapplying Fit or a tool also ends a held gesture. Focus is stamped
// after the action, for Iced's final-view ordering.
if self.camera_epoch == scope.epoch {
self.camera_epoch = self.camera_epoch.wrapping_add(1);
self.camera_boundary_epoch = self.canvas_epoch;
}
let focus = Scope::input_owner(self).map_or_else(Task::none, |scope| {
canvas_workspace::focus_task(scope, Camera::ControlFocus(intent.name))
});
Task::batch([task, focus])
}
fn camera_toolbar_epoch(&self, epoch: u64) -> bool {
epoch >= self.camera_boundary_epoch && epoch <= self.canvas_epoch
}
fn camera_boundary(&self) -> impl PartialEq + use<> {
(
self.canvas_epoch,
self.canvas_document,
self.document.revision(),
crate::behavior::selected_owner(self),
self.page,
self.window_size,
crate::behavior::canvas_workspace::keyboard_enabled(self),
self.behavior.has_pending(),
self.draft_dirty(),
self.source_dirty(),
self.behavior.topology.camera_boundary(),
self.behavior.scenario.camera_boundary(),
)
}
fn update_inner(&mut self, message: Message) -> Task<Message> {
if let Some(task) = self.reference_message(&message) {
return task;
}
if matches!(&message, Message::Connection(_))
&& self
.architecture
@@ -1076,9 +1212,7 @@ impl App {
// navigation and close retain raw input until explicit completion/cancel.
if self.architecture.is_some() {
if matches!(message, Message::Escape) {
self.architecture = None;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
return Task::none();
return self.architecture_event(architecture_authoring::Event::Cancel);
}
let placing = self.architecture.as_ref().is_some_and(|s| s.saved.placing);
if !matches!(
@@ -1104,6 +1238,7 @@ impl App {
Message::ScenarioCanvas(
crate::behavior::scenario::CanvasEvent::Scrolled(..)
| crate::behavior::scenario::CanvasEvent::Restored(..)
| crate::behavior::scenario::CanvasEvent::Viewport(..)
) | Message::TopologyCanvas(
crate::behavior::topology::CanvasEvent::Scrolled(..)
| crate::behavior::topology::CanvasEvent::Viewport(..)
@@ -1286,6 +1421,7 @@ impl App {
self.last_workspace_page = self.page;
}
let mut task = self.handle(message);
self.reconcile_reference_chooser();
self.route_state_diagram_workspace();
if self.page != Page::Home {
self.last_workspace_page = self.page;
@@ -1295,6 +1431,11 @@ impl App {
.topology
.enter(context.document, context.owner);
}
if let Some(context) = self.scenario_context() {
self.behavior
.scenario
.enter(context.document, context.scenario);
}
if self.connection.as_ref().is_some_and(|session| {
Some(session.context) != self.route_context()
|| self.page != Page::Diagram
@@ -1350,6 +1491,7 @@ impl App {
}
fn handle(&mut self, message: Message) -> Task<Message> {
match message {
Message::BehaviorControl(intent) => return self.behavior_control(intent),
Message::Architecture(event) => return self.architecture_event(event),
Message::Home(event) => return self.home_event(event),
Message::CheckpointTick => return self.checkpoint_tick(),
@@ -1365,6 +1507,28 @@ impl App {
Message::ScenarioCanvas(event) => {
use crate::behavior::scenario::{self, CanvasEvent};
let context = event.context();
if let CanvasEvent::FormShown(_, session) = event {
if self.scenario_context().is_some_and(|current| {
current.document == context.document
&& current.scenario == context.scenario
&& current.revision == context.revision
}) && self.behavior.scenario.take_form_focus(session)
{
return iced::widget::operation::focus(scenario::NAME_INPUT);
}
return Task::none();
}
if let CanvasEvent::Viewport(_, size) = event {
if self.scenario_context().is_some_and(|current| {
current.document == context.document
&& current.scenario == context.scenario
&& current.revision == context.revision
}) && self.behavior.scenario.viewport(size)
{
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
return Task::none();
}
if let CanvasEvent::Restored(_, token, area, offset) = event {
if self.scenario_context().is_some_and(|current| {
current.document == context.document && current.scenario == context.scenario
@@ -1378,7 +1542,7 @@ impl App {
return Task::none();
}
if let CanvasEvent::Scrolled(_, area, offset) = event {
// Inner and outer scroll notifications may come from the
// Canvas and outline notifications may come from the
// same frame. Accept both across the first epoch bump,
// while still rejecting another owner/document/revision.
if self.scenario_context().is_some_and(|current| {
@@ -1391,10 +1555,68 @@ impl App {
}
return Task::none();
}
if let CanvasEvent::Camera(_, lifetime, input) = event {
use crate::behavior::canvas_workspace::{self, Event};
if lifetime != self.camera_epoch
|| !self.scenario_context().is_some_and(|c| {
c.document == context.document
&& c.scenario == context.scenario
&& c.revision == context.revision
})
{
return Task::none();
}
let scope = canvas_workspace::Scope {
document: context.document,
owner: context.scenario,
revision: context.revision,
epoch: lifetime,
};
if self.behavior.has_pending()
|| self.draft_dirty()
|| self.source_dirty()
|| !canvas_workspace::keyboard_enabled(self)
{
return Task::none();
}
match input {
Event::Focus
| Event::Traverse(_)
| Event::ControlFocus(_)
| Event::ToggleFocus
| Event::Leave => {
return canvas_workspace::focus_task(scope, input);
}
Event::CancelGesture => {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1)
}
input => {
if self.behavior.scenario.camera(input) {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
}
}
return Task::none();
}
if self.scenario_context() != Some(context) {
return Task::none();
}
match event {
CanvasEvent::Focus(_) => {
self.behavior.scenario.toggle_focus();
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
CanvasEvent::Shelf(_, shelf) => {
self.behavior.scenario.toggle_shelf(shelf);
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
CanvasEvent::Zoom(_, scale) => {
let mut state = std::mem::take(&mut self.behavior.scenario);
if state.camera_zoom(self.project(), context.scenario, scale) {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
self.behavior.scenario = state;
}
CanvasEvent::OpenUse(_, occurrence) => {
if self.behavior.has_pending() || self.draft_dirty() || self.source_dirty()
{
@@ -1406,6 +1628,9 @@ impl App {
self.behavior.scenario = state;
match target {
Ok(target) => {
// A command can preselect this target while the
// caller remains visible, bypassing select below.
self.behavior.active_owner = Some(target);
self.select(target);
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
@@ -1424,12 +1649,23 @@ impl App {
let caller = state.back(self.project(), context);
self.behavior.scenario = state;
if let Some(caller) = caller {
// A command may already have selected this UUID while
// leaving the referenced definition open. select's
// same-UUID fast path must not keep that old owner.
self.behavior.active_owner = Some(caller.owner);
self.select(caller.occurrence);
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
if let Some(context) = self.scenario_context() {
self.behavior.scenario.restore_caller(context, caller);
}
} else {
// An edit can select a retargeted caller outside the
// definition that remains visible after rejected Back.
if crate::behavior::selected_behavior(self.project(), self.selected)
!= Some(context.scenario)
{
self.select(context.scenario);
}
self.status =
"The calling scenario reference is no longer available.".into();
}
@@ -1444,7 +1680,11 @@ impl App {
}
}
CanvasEvent::Choose(_, tool) => {
if self.behavior.has_pending() || !self.apply() {
if self.behavior.has_pending() || self.draft_dirty() || self.source_dirty()
{
self.status =
"Apply or cancel pending edits before choosing a scenario tool."
.into();
return Task::none();
}
self.behavior.scenario.choose_tool(context.scenario, tool);
@@ -1459,6 +1699,37 @@ impl App {
return Task::none();
}
match mutation {
CanvasEvent::First(_, tool) => {
let empty = match tool {
scenario::Tool::Lifeline => !self
.project()
.children(context.scenario)
.any(|e| e.kind() == Kind::Lifeline),
scenario::Tool::Message | scenario::Tool::Action => {
self.project()
.children(context.scenario)
.any(|e| e.kind() == Kind::Lifeline)
&& !self
.project()
.children(context.scenario)
.any(|e| e.kind() == Kind::Occurrence)
}
_ => false,
};
if !empty {
self.status="This scenario already has content. Use its current authoring tools.".into();
return Task::none();
}
let mut state = std::mem::take(&mut self.behavior.scenario);
let result = state.update(
self.project(),
scenario::Event::Start(context.scenario, tool),
);
self.behavior.scenario = state;
if let Err(error) = result {
self.status = error;
}
}
CanvasEvent::BeginOccurrence {
tool,
slot,
@@ -1466,13 +1737,22 @@ impl App {
..
} => {
let mut state = std::mem::take(&mut self.behavior.scenario);
let result = state.begin_occurrence(
self.project(),
context,
tool,
slot,
lifeline,
);
let result = if tool == scenario::Tool::Lifeline {
state
.update(
self.project(),
scenario::Event::Start(context.scenario, tool),
)
.map(|_| ())
} else {
state.begin_occurrence(
self.project(),
context,
tool,
slot,
lifeline,
)
};
self.behavior.scenario = state;
match result {
Ok(()) => {
@@ -1694,6 +1974,18 @@ impl App {
return self.update(Message::Add(child));
}
Message::Escape => {
if self.behavior.source_back() {
self.status =
"Returned to the unchanged parent form; no source was created.".into();
return Task::none();
}
if self.behavior.source_active() {
self.behavior.acknowledge_commit();
self.status = "Behavior form cancelled; no staged source was created.".into();
} else if self.behavior.creation.has_pending() {
self.behavior.creation.acknowledge_commit();
self.status = "Behavior creation cancelled".into();
}
if self.connection.take().is_some() {
self.status = "Drawing cancelled · Select / move is active".into();
}
@@ -1753,6 +2045,9 @@ impl App {
.insert(path, crate::forms::ValueBrowser { scope, page });
}
}
Message::FieldReferenceOpen(_) | Message::FieldReferenceEvent(_) => {
return Task::none();
}
Message::FieldReferenceBrowse(path, query, page) => {
if let Some(draft) = &mut self.draft {
let page = if draft
@@ -2237,9 +2532,33 @@ impl App {
}
Message::InspectorTab(tab) => self.inspector_tab = tab,
Message::Behavior(event) => {
if event.starts_form() && !self.behavior.has_pending() && !self.apply() {
if matches!(&event, behavior::Event::Creation(behavior::creation::Event::Open(layer)) if *layer != self.layer)
{
self.status =
"The active layer changed. Choose New in the current layer.".into();
return Task::none();
}
let creating = matches!(
&event,
behavior::Event::Creation(behavior::creation::Event::Open(..))
);
let focus_name = matches!(
&event,
behavior::Event::Creation(behavior::creation::Event::Choose(..))
);
if creating
&& (self.behavior.has_pending() || self.source_dirty() || self.draft_dirty())
{
self.status = "Apply or cancel the current draft before starting a new behavior. Your inputs are retained.".into();
return Task::none();
}
if (event.starts_form() || (event.is_source() && !event.is_source_back()))
&& (self.source_dirty() || self.draft_dirty())
{
self.status="Apply or cancel the other editors before starting this form. Your inputs are retained.".into();
return Task::none();
}
let source_was_open = self.behavior.source_open();
if event.is_submit() && (self.source_dirty() || self.draft_dirty()) {
self.status = "Revert the other drafts before applying the behavior form. Your inputs are retained.".into();
return Task::none();
@@ -2256,7 +2575,16 @@ impl App {
}
}
}
Ok(None) => {}
Ok(None) => {
if !source_was_open && self.behavior.source_open() {
return iced::widget::operation::focus(
behavior::source_draft::NAME_INPUT,
);
}
if focus_name {
return iced::widget::operation::focus(behavior::creation::NAME_INPUT);
}
}
Err(error) => self.status = error,
}
}
@@ -2448,13 +2776,19 @@ impl App {
Message::Undo | Message::Redo => {
let redo = matches!(message, Message::Redo);
if self.apply() {
if redo {
self.document.redo();
let changed = if redo {
self.document.redo()
} else {
self.document.undo();
self.document.undo()
};
if changed {
self.sync();
}
self.sync();
self.status = if redo {
self.status = if !changed && redo {
"Nothing to redo"
} else if !changed {
"Nothing to undo"
} else if redo {
"Model change redone"
} else {
"Model change undone"
@@ -3,6 +3,8 @@ use super::*;
use iced::widget::{button, column, pick_list, row, scrollable, text, text_input};
use serde::{Deserialize, Serialize};
mod palette;
#[cfg(test)]
mod tests;
pub use palette::view as palette;
#[derive(Debug, Clone)]
@@ -21,9 +23,35 @@ pub enum Event {
Filter(Filter),
ShowPlaced(bool),
Page(usize),
Edit,
CapturedEscape,
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))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum Filter {
@@ -336,9 +364,15 @@ impl App {
}
return iced::widget::operation::focus("architecture-name");
}
Event::CapturedEscape => {
if self.architecture.as_ref().is_some_and(State::inline) {
return self.architecture_event(Event::Cancel);
}
}
Event::Cancel => {
self.architecture = None;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
self.status = "Cancelled · Select / move".into();
}
Event::Name(value) => {
if value.len() <= 16384
@@ -375,13 +409,6 @@ impl App {
s.saved.page = page.min(1_000_000);
}
}
Event::Edit => {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
if let Some(s) = &mut self.architecture {
s.saved.placing = false;
}
return iced::widget::operation::focus("architecture-name");
}
Event::Pick(id) => {
if !candidates(self)
.iter()
@@ -560,9 +587,10 @@ pub fn inline_editor(app: &App) -> Option<Element<'_, Message>> {
row![
iced::widget::Space::new().width(x),
iced::widget::opaque(
iced::widget::container(name_editor(app))
iced::widget::container(scrollable(name_editor(app)))
.padding(10)
.width(width)
.max_height((size.height - y - 8.).max(0.))
.style(crate::style::card)
)
]
@@ -4,7 +4,7 @@ use iced::{
Point, Rectangle, Size, Theme, mouse,
widget::{
canvas::{self, Frame, Geometry, Path, Stroke},
column, container, tooltip,
container, tooltip,
},
};
@@ -165,7 +165,7 @@ fn tool<'a>(
.into()
}
pub fn view(app: &App) -> Element<'_, Message> {
let mut content = column![tool(
let mut content = iced::widget::column![tool(
app,
Icon::Collapse(app.architecture_palette_expanded),
if app.architecture_palette_expanded {
@@ -0,0 +1,378 @@
use super::*;
fn setup(layer: Layer) -> App {
let mut app = App::with_project(Project::empty());
app.layer = layer;
app.active_diagram = None;
let _ = app.update(Message::AddDiagram);
app.zoom = 0.75;
app.pan = iced::Vector::new(37., -19.);
app
}
fn send(app: &mut App, event: Event) {
let _ = app.update(Message::Architecture(event));
}
fn create(app: &mut App, kind: Kind, name: &str) -> Id {
send(app, Event::Start(kind, Some(Position { x: 120., y: 160. })));
send(app, Event::Name(name.into()));
send(app, Event::Submit);
assert!(app.architecture.is_none(), "{}", app.status);
app.selected
}
#[test]
fn architecture_allocated_work_is_root_owned_and_one_exact_history_change() {
for (layer, participant, work) in [
(Layer::Oa, Kind::Entity, Kind::Activity),
(Layer::Sa, Kind::System, Kind::Function),
] {
let mut app = setup(layer);
let performer = create(&mut app, participant, "Control team");
let before = app.document.bundle().clone();
let camera = (app.zoom, app.pan);
let point = Position { x: 151., y: 221. };
send(&mut app, Event::Allocate(work, performer, Some(point)));
send(&mut app, Event::Name(" Report 雨 ".into()));
assert_eq!(app.document.bundle(), &before);
send(&mut app, Event::Submit);
assert!(app.architecture.is_none(), "{}", app.status);
let created = app.selected;
let element = &app.project().elements[&created];
assert_eq!(element.kind(), work);
assert_eq!(element.name, " Report 雨 ");
assert_eq!(element.parent, None);
assert!(app.project().relations.values().any(|r| {
r.kind() == RelationKind::Allocation && r.source() == performer && r.target() == created
}));
let d = &app.project().diagrams[&app.active_diagram.unwrap()];
assert_eq!(d.nodes[&app.selected_node.unwrap()].position, point);
assert_eq!((app.zoom, app.pan), camera);
let accepted = app.document.bundle().clone();
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &before);
let _ = app.update(Message::Redo);
assert_eq!(app.document.bundle(), &accepted);
}
}
#[test]
fn architecture_f2_routes_selected_node_to_inline_rename_and_exact_undo() {
use iced::widget::canvas::{Event as CanvasEvent, Program};
use iced::{keyboard, mouse};
let mut app = setup(Layer::Oa);
let element = create(&mut app, Kind::Entity, "Original team");
let before = app.document.bundle().clone();
let diagrams = app.project().diagrams.clone();
let camera = (app.zoom, app.pan);
let bounds = iced::Rectangle::new(iced::Point::ORIGIN, iced::Size::new(600., 380.));
let canvas = crate::diagram::DiagramCanvas {
project: app.project(),
view_index: None,
diagram: app.active_diagram.unwrap(),
selected: element,
zoom: app.zoom,
pan: app.pan,
context: app.route_context().unwrap(),
selected_bend: None,
editable: true,
placing: false,
connection: None,
};
let mut state = crate::diagram::State::default();
let key = CanvasEvent::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(keyboard::key::Named::F2),
modified_key: keyboard::Key::Named(keyboard::key::Named::F2),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::F2),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::empty(),
text: None,
repeat: false,
});
assert!(
canvas
.update(&mut state, &key, bounds, mouse::Cursor::Unavailable)
.is_none()
);
let _ = canvas.update(
&mut state,
&CanvasEvent::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
bounds,
mouse::Cursor::Available(iced::Point::new(150., 120.)),
);
let action = canvas
.update(&mut state, &key, bounds, mouse::Cursor::Unavailable)
.unwrap();
let message = action.into_inner().0.unwrap();
let _ = app.update(message);
assert!(app.architecture.as_ref().unwrap().inline());
assert!(matches!(&app.architecture.as_ref().unwrap().saved.intent,
Intent::Rename { element: id, name } if *id == element && name == "Original team"));
send(&mut app, Event::Name(" Renamed team 雨 ".into()));
assert_eq!(app.document.bundle(), &before);
send(&mut app, Event::Submit);
assert!(app.architecture.is_none(), "{}", app.status);
assert_eq!(app.project().elements[&element].name, " Renamed team 雨 ");
assert_eq!(app.project().diagrams, diagrams);
assert_eq!((app.zoom, app.pan), camera);
let accepted = app.document.bundle().clone();
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &before);
let _ = app.update(Message::Redo);
assert_eq!(app.document.bundle(), &accepted);
}
#[test]
fn architecture_blank_names_and_escape_never_accept_placeholder_or_rename() {
let mut app = setup(Layer::Oa);
let element = create(&mut app, Kind::Actor, "Dispatcher");
let before = app.document.bundle().clone();
let context = app.route_context().unwrap();
for event in [
Event::Start(Kind::Activity, Some(Position { x: 220., y: 330. })),
Event::Rename(context, element, Position { x: 150., y: 200. }),
] {
// Every cancel changes the gesture context; use the current context for F2.
let event = match event {
Event::Rename(_, element, point) => {
Event::Rename(app.route_context().unwrap(), element, point)
}
event => event,
};
send(&mut app, event);
send(&mut app, Event::Name(" \t ".into()));
send(&mut app, Event::Submit);
assert!(app.architecture.as_ref().unwrap().inline());
assert!(app.architecture.as_ref().unwrap().error.is_some());
assert_eq!(app.document.bundle(), &before);
let _ = app.update(Message::Escape);
assert!(app.architecture.is_none());
assert_eq!(app.document.bundle(), &before);
}
}
#[test]
fn architecture_invalid_click_cannot_poison_inline_or_checkpoint_geometry() {
let mut app = setup(Layer::Oa);
send(&mut app, Event::Start(Kind::Entity, None));
let before = app.document.bundle().clone();
let context = app.route_context().unwrap();
for point in [
Position { x: f32::NAN, y: 0. },
Position {
x: 0.,
y: f32::INFINITY,
},
] {
send(&mut app, Event::Click(context, point));
let draft = app.architecture.as_ref().unwrap();
assert!(draft.unnamed_tool());
assert!(validate_saved(app.project(), &draft.saved).is_ok());
assert_eq!(app.document.bundle(), &before);
}
send(&mut app, Event::Click(context, Position { x: 25., y: 30. }));
assert!(app.architecture.as_ref().unwrap().inline());
}
#[test]
fn architecture_stale_submit_keeps_create_and_rename_visible_and_exact() {
for rename in [false, true] {
for stale_document in [false, true] {
let mut app = setup(Layer::Oa);
let element = create(&mut app, Kind::Entity, "Accepted team");
let point = Position {
x: 151.5,
y: 227.25,
};
let event = if rename {
Event::Rename(app.route_context().unwrap(), element, point)
} else {
Event::Start(Kind::Activity, Some(point))
};
send(&mut app, event);
send(
&mut app,
Event::Name(" Retained engineering name 雨 ".into()),
);
// Change only the binding. The accepted model/source must not be
// rewritten or a rejected draft silently rebound to the new context.
if stale_document {
app.architecture.as_mut().unwrap().document = Id::new_v4();
} else {
app.architecture.as_mut().unwrap().revision = app.document.revision() + 1;
}
let draft = app.architecture.as_ref().unwrap();
let saved = serde_json::to_value(&draft.saved).unwrap();
let binding = (draft.document, draft.revision);
let model = app.project().clone();
let source = app.document.bundle().clone();
let revision = app.document.revision();
let camera = (app.zoom, app.pan);
for _ in 0..2 {
send(&mut app, Event::Submit);
let draft = app.architecture.as_ref().unwrap();
assert!(
draft.inline(),
"rename={rename}, stale_document={stale_document}"
);
assert!(inline_editor(&app).is_some());
assert_eq!(draft.error.as_deref(), Some(app.status.as_str()));
assert!(app.status.contains("cancel and restart"));
assert_eq!(serde_json::to_value(&draft.saved).unwrap(), saved);
assert_eq!((draft.document, draft.revision), binding);
assert_eq!(app.project(), &model);
assert_eq!(app.document.bundle(), &source);
assert_eq!(app.document.revision(), revision);
assert_eq!((app.zoom, app.pan), camera);
}
let _ = app.update(Message::Escape);
assert!(app.architecture.is_none());
assert_eq!(app.project(), &model);
assert_eq!(app.document.bundle(), &source);
let fresh = create(&mut app, Kind::Actor, "Fresh context");
assert_eq!(app.project().elements[&fresh].name, "Fresh context");
let _ = app.update(Message::Undo);
assert_eq!(app.project(), &model);
assert_eq!(app.document.bundle(), &source);
}
}
}
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] {
let mut app = setup(Layer::Oa);
let element = create(&mut app, Kind::Actor, "Accepted dispatcher");
let model = app.project().clone();
let source = app.document.bundle().clone();
let revision = app.document.revision();
let camera = (app.zoom, app.pan);
let point = Position { x: 439., y: 328.2 };
let event = if rename {
Event::Rename(app.route_context().unwrap(), element, point)
} else {
Event::Start(Kind::Actor, Some(point))
};
send(&mut app, event);
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);
assert!(app.architecture.is_none());
assert!(inline_editor(&app).is_none());
assert_eq!(app.status, "Cancelled · Select / move");
assert_eq!(app.project(), &model);
assert_eq!(app.document.bundle(), &source);
assert_eq!(app.document.revision(), revision);
assert_eq!((app.zoom, app.pan), camera);
}
}
#[test]
fn architecture_captured_escape_does_not_cancel_other_controls_or_placement() {
let mut app = setup(Layer::Oa);
for event in [
None,
Some(Event::Start(Kind::Entity, None)),
Some(Event::Existing(None)),
] {
send(&mut app, Event::Cancel);
if let Some(event) = event {
send(&mut app, event);
}
let saved = app
.architecture
.as_ref()
.map(|s| serde_json::to_value(&s.saved).unwrap());
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);
assert_eq!(
app.architecture
.as_ref()
.map(|s| serde_json::to_value(&s.saved).unwrap()),
saved
);
assert_eq!(app.document.bundle(), &before);
assert_eq!(app.status, status);
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()
);
}
+197 -2
View File
@@ -173,7 +173,12 @@ impl App {
self.behavior = restored.behavior;
self.workflow = restored.workflow;
let focus = self.behavior.pending_owner().unwrap_or(self.selected);
if let Some(layer) = self.project().layer_of(focus) {
if let Some(layer) = self
.behavior
.creation
.pending_layer()
.or_else(|| self.project().layer_of(focus))
{
self.layer = layer;
self.explorer_index = crate::explorer::Index::new(self.project(), layer);
self.active_diagram = self.diagram_for(layer, focus);
@@ -202,7 +207,26 @@ impl App {
} else {
"Recovered an unsaved local copy. Choose Save as to save it; the original file and hosted model are unchanged.".into()
};
self.request_lint()
let lint = self.request_lint();
if self
.architecture
.as_ref()
.is_some_and(architecture_authoring::State::inline)
{
Task::batch([lint, iced::widget::operation::focus("architecture-name")])
} else if self.page == Page::Behavior && self.behavior.source_open() {
Task::batch([
lint,
iced::widget::operation::focus(behavior::source_draft::NAME_INPUT),
])
} else if self.page == Page::Behavior && self.behavior.creation.created().is_some() {
Task::batch([
lint,
iced::widget::operation::focus(behavior::creation::NAME_INPUT),
])
} else {
lint
}
}
}
@@ -331,6 +355,177 @@ mod tests {
.unwrap()
}
async fn run_recovery_tasks(app: &mut App, task: Task<Message>) -> (usize, bool, bool) {
use iced::advanced::{Layout, layout, widget};
use iced::futures::StreamExt;
// Mount real inputs, with focus initially in another control. This
// verifies the returned operation targets the naming field by its ID.
let mut fields: iced::Element<'_, (), iced::Theme, ()> = iced::widget::column![
iced::widget::text_input("Engineering name", "Retained name")
.id("architecture-name")
.on_input(|_| ()),
iced::widget::text_input("Other control", "Other value")
.id("unrelated-field")
.on_input(|_| ())
]
.into();
let mut tree = widget::Tree::new(fields.as_widget());
let node = fields.as_widget_mut().layout(
&mut tree,
&(),
&layout::Limits::new(iced::Size::ZERO, iced::Size::new(320., 100.)),
);
tree.children[1]
.state
.downcast_mut::<iced::widget::text_input::State<()>>()
.focus();
let mut operations = 0;
let mut lint_completions = 0;
let mut stream = iced_runtime::task::into_stream(task).expect("Recovery must still lint");
while let Some(action) = stream.next().await {
match action {
iced_runtime::Action::Widget(mut operation) => {
operations += 1;
fields.as_widget_mut().operate(
&mut tree,
Layout::new(&node),
&(),
operation.as_mut(),
);
}
iced_runtime::Action::Output(message @ Message::Linted(_, _)) => {
lint_completions += 1;
let _ = app.update(message);
}
_ => panic!("Unexpected recovery task action"),
}
}
assert_eq!(
lint_completions, 1,
"Autofocus must not replace request_lint"
);
assert!(app.lint_running.is_none());
let focused = |index: usize| {
tree.children[index]
.state
.downcast_ref::<iced::widget::text_input::State<()>>()
.is_focused()
};
(operations, focused(0), focused(1))
}
fn architecture_recovery_app() -> App {
let mut app = App::with_project(Project::empty());
let _ = app.update(Message::AddDiagram);
let _ = app.update(Message::Architecture(architecture_authoring::Event::Start(
Kind::Entity,
Some(Position { x: 80., y: 90. }),
)));
let _ = app.update(Message::Architecture(architecture_authoring::Event::Name(
"Accepted team".into(),
)));
let _ = app.update(Message::Architecture(architecture_authoring::Event::Submit));
assert!(app.architecture.is_none());
app
}
#[tokio::test]
async fn checkpoint_inline_create_and_rename_restore_focus_without_changing_drafts_or_history()
{
use architecture_authoring::Event;
for rename in [false, true] {
let mut app = architecture_recovery_app();
let point = Position { x: 439., y: 328.2 };
let event = if rename {
Event::Rename(app.route_context().unwrap(), app.selected, point)
} else {
Event::Start(Kind::Actor, Some(point))
};
let _ = app.update(Message::Architecture(event));
let _ = app.update(Message::Architecture(Event::Name(
" Recovered engineering name 雨 ".into(),
)));
let saved = serde_json::to_value(&app.architecture.as_ref().unwrap().saved).unwrap();
let snapshot = retained_snapshot(&app).with_architecture(app.architecture.as_ref());
let expected = snapshot.clone().restore().unwrap();
let checkpoint = snapshot.id;
let mut recovered = App::with_project(Project::empty());
let task = recovered.checkpoint_loaded(Ok(Arc::new(snapshot)));
assert_eq!(
run_recovery_tasks(&mut recovered, task).await,
(1, true, false)
);
assert_eq!(recovered.page, Page::Diagram);
assert!(recovered.architecture.as_ref().unwrap().inline());
assert_eq!(
serde_json::to_value(&recovered.architecture.as_ref().unwrap().saved).unwrap(),
saved
);
assert_eq!(recovered.project(), expected.document.project());
assert_eq!(recovered.document.bundle(), expected.document.bundle());
assert_eq!(recovered.document.revision(), expected.document.revision());
assert_eq!(recovered.document.can_undo(), expected.document.can_undo());
assert_eq!(recovered.document.can_redo(), expected.document.can_redo());
assert_eq!(
recovered.source_workspace.bundle(),
expected.workspace.bundle()
);
assert_eq!(recovered.recovery.restored, Some(checkpoint));
assert!(recovered.path.is_none());
}
}
#[tokio::test]
async fn checkpoint_noninline_contexts_keep_other_focus_and_still_lint() {
use architecture_authoring::Event;
for context in ["accepted", "armed", "picker", "property", "source"] {
let mut app = architecture_recovery_app();
match context {
"armed" => {
let _ = app.update(Message::Architecture(Event::Start(Kind::Actor, None)));
}
"picker" => {
let _ = app.update(Message::Architecture(Event::Existing(None)));
}
"property" => {
app.draft
.as_mut()
.unwrap()
.input("/name", "Unapplied property".into());
assert!(app.draft_dirty());
}
"source" => {
app.source_workspace
.edit("incomplete source 雨".into(), app.source_editor.cursor());
assert!(app.source_dirty());
}
_ => {}
}
let snapshot = retained_snapshot(&app).with_architecture(app.architecture.as_ref());
let expected = snapshot.clone().restore().unwrap();
let mut recovered = App::with_project(Project::empty());
let task = recovered.checkpoint_loaded(Ok(Arc::new(snapshot)));
assert_eq!(
run_recovery_tasks(&mut recovered, task).await,
(0, false, true),
"{context}"
);
assert!(
!recovered
.architecture
.as_ref()
.is_some_and(architecture_authoring::State::inline)
);
assert_eq!(recovered.project(), expected.document.project());
assert_eq!(recovered.document.bundle(), expected.document.bundle());
assert_eq!(recovered.document.revision(), expected.document.revision());
assert_eq!(
recovered.source_workspace.bundle(),
expected.workspace.bundle()
);
}
}
#[test]
fn saving_an_older_snapshot_keeps_recovery_for_newer_unsaved_work() {
let directory = tempfile::tempdir().unwrap();
+60 -15
View File
@@ -15,18 +15,15 @@ impl App {
epoch: self.canvas_epoch,
})
}
pub(super) fn reveal_process_selection(&self) -> Task<Message> {
let Some(context) = self.topology_context() else {
return Task::none();
};
let Some(offset) =
self.behavior
.topology
.selection_offset(self.project(), context.owner, self.selected)
else {
return Task::none();
};
iced::widget::operation::scroll_to("process-canvas", offset)
pub(super) fn reveal_process_selection(&mut self) -> Task<Message> {
if let Some(context) = self.topology_context() {
let mut state = std::mem::take(&mut self.behavior.topology);
if state.reveal_selection(self.project(), context.owner, self.selected) {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
self.behavior.topology = state;
}
Task::none()
}
pub(super) fn edit_process_canvas(&mut self, event: CanvasEvent) -> Task<Message> {
let context = event.context();
@@ -52,6 +49,47 @@ impl App {
}
return Task::none();
}
if let CanvasEvent::Camera(_, lifetime, input) = event {
use crate::behavior::canvas_workspace::{self, Event};
if lifetime != self.camera_epoch
|| !self.topology_context().is_some_and(|c| {
c.document == context.document
&& c.owner == context.owner
&& c.revision == context.revision
})
{
return Task::none();
}
let scope = canvas_workspace::Scope {
document: context.document,
owner: context.owner,
revision: context.revision,
epoch: lifetime,
};
if self.behavior.has_pending()
|| self.draft_dirty()
|| self.source_dirty()
|| !canvas_workspace::keyboard_enabled(self)
{
return Task::none();
}
match input {
Event::Focus
| Event::Traverse(_)
| Event::ControlFocus(_)
| Event::ToggleFocus
| Event::Leave => {
return canvas_workspace::focus_task(scope, input);
}
Event::CancelGesture => self.canvas_epoch = self.canvas_epoch.wrapping_add(1),
input => {
if self.behavior.topology.camera(input) {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
}
}
return Task::none();
}
if self.topology_context() != Some(context) {
return Task::none();
}
@@ -81,6 +119,7 @@ impl App {
.first()
.copied()
.unwrap_or(endpoint.occurrence),
resolved.defining_sequence,
);
self.behavior.active_owner = Some(resolved.defining_sequence);
self.select(endpoint.occurrence);
@@ -118,14 +157,18 @@ impl App {
}
}
CanvasEvent::Choose(_, tool) => {
if self.behavior.has_pending() || !self.apply() {
if self.behavior.has_pending() || self.draft_dirty() || self.source_dirty() {
self.status =
"Apply or cancel pending edits before choosing a process tool.".into();
return Task::none();
}
self.behavior.topology.choose(tool);
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
CanvasEvent::Zoom(_, zoom) => {
self.behavior.topology.zoom(zoom);
let mut state = std::mem::take(&mut self.behavior.topology);
state.camera_zoom(self.project(), context.owner, zoom);
self.behavior.topology = state;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
CanvasEvent::Expand(_, id) => {
@@ -149,7 +192,9 @@ impl App {
.get(&target)
.is_some_and(|e| matches!(e.kind(), Kind::Process | Kind::FunctionalChain))
{
self.behavior.topology.remember(context.owner, occurrence);
self.behavior
.topology
.remember(context.owner, occurrence, target);
self.behavior.active_owner = Some(target);
}
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
@@ -0,0 +1,300 @@
//! One transient chooser for the currently mounted Inspector or review field.
//! Browsing never calls a draft setter or semantic planner.
use super::{App, Message, Page, Pending};
use crate::{
forms::{
Draft,
reference_chooser::{self as chooser, Action, Close, Outcome, adapter, trigger},
},
navigation::InspectorTab,
semantic_review::{self, RowAddress, RowEvent},
workflow,
};
use iced::{Element, Rectangle, Task};
use oa_core::{FacetSelector, Id, Layer};
#[derive(Debug, Clone, PartialEq, Eq)]
enum Host {
Inspector,
Review {
address: Option<RowAddress>,
facet: FacetSelector,
},
}
impl Host {
fn message(&self, event: chooser::Event) -> Message {
match self {
Self::Inspector => Message::FieldReferenceEvent(event),
Self::Review { address, facet } => {
Message::Workflow(workflow::Event::Semantic(semantic_review::Event::Row {
address: *address,
facet: Some(facet.clone()),
event: RowEvent::ReferenceEvent(event),
}))
}
}
}
}
struct Opened {
host: Host,
request: adapter::Open,
document_session: Id,
page: Page,
layer: Layer,
chooser: chooser::State,
}
#[derive(Default)]
pub(super) struct State {
opened: Option<Opened>,
}
impl App {
pub(crate) fn reference_input_active(&self) -> bool {
self.reference_authoring.opened.is_some()
}
fn reference_draft(&self, host: &Host, path: &str) -> Option<&Draft> {
match host {
Host::Inspector
if self.workflow.is_none() && self.inspector_tab == InspectorTab::Properties =>
{
self.draft.as_ref()
}
Host::Review { address, facet } => match self.workflow.as_ref()? {
workflow::Workflow::Semantic(state) => {
state.reference_draft(self.project(), *address, facet, path)
}
_ => None,
},
_ => None,
}
}
fn reference_available(&self) -> bool {
!self.busy
&& !self.hosted.visible
&& self.architecture.is_none()
&& self.model_menu.is_none()
&& self.file_prompt.is_none()
&& !self.delete_pending
&& self.pending.is_none()
&& !self.source_dirty()
&& !self.behavior.has_pending()
&& !matches!(self.page, Page::Home | Page::Guide | Page::Text)
}
fn reference_valid(&self, opened: &Opened) -> bool {
self.reference_available()
&& self.canvas_document == opened.document_session
&& self.page == opened.page
&& self.layer == opened.layer
&& self.document.revision() == opened.chooser.stamp().context.revision
&& self.project().id == opened.request.document
&& self
.reference_draft(&opened.host, &opened.request.path)
.is_some_and(|draft| draft.reference_matches(&opened.request))
}
pub(super) fn reconcile_reference_chooser(&mut self) {
if self
.reference_authoring
.opened
.as_ref()
.is_some_and(|opened| !self.reference_valid(opened))
{
self.reference_authoring
.opened
.as_mut()
.unwrap()
.chooser
.invalidate();
self.reference_authoring.opened = None;
}
}
fn open_reference(&mut self, host: Host, request: adapter::Open) -> Task<Message> {
if !self.reference_available() {
return Task::none();
}
let Some(draft) = self.reference_draft(&host, &request.path) else {
return Task::none();
};
let Ok(chooser) =
draft.reference_catalog(self.project(), &request, self.document.revision())
else {
return Task::none();
};
self.reference_authoring.opened = Some(Opened {
host,
request,
document_session: self.canvas_document,
page: self.page,
layer: self.layer,
chooser,
});
Task::none()
}
fn reference_event(&mut self, host: Host, event: chooser::Event) -> Task<Message> {
let Some(mut opened) = self.reference_authoring.opened.take() else {
return Task::none();
};
if !self.reference_valid(&opened) {
return Task::none();
}
if opened.host != host {
self.reference_authoring.opened = Some(opened);
return Task::none();
}
match opened.chooser.update(event) {
Outcome::Ignored | Outcome::Browsed => {
self.reference_authoring.opened = Some(opened);
Task::none()
}
Outcome::Closed(reason) => self.reference_focus(
&opened,
match reason {
Close::Escape => Some(0),
Close::Tab { backwards } => Some(if backwards { -1 } else { 1 }),
Close::Outside | Close::WindowChanged => None,
},
),
Outcome::Write { context, value } => {
let intent = adapter::Set {
context,
generation: opened.request.generation,
value,
};
let result = match &opened.host {
Host::Inspector => self
.draft
.as_mut()
.ok_or_else(|| "The property editor closed.".to_owned())
.and_then(|draft| draft.reference_set(self.document.project(), &intent)),
Host::Review { address, facet } => match self.workflow.as_mut() {
Some(workflow::Workflow::Semantic(state)) => {
state.set_reference(self.document.project(), *address, facet, intent)
}
_ => Err("The review editor closed.".into()),
},
};
if let Err(error) = result {
self.status = error;
}
// A scoped write rotates field generation. The task targets the
// newly rendered field, while a later structural edit makes it inert.
self.reference_focus(&opened, Some(0))
}
}
}
fn reference_focus(&self, opened: &Opened, step: Option<i32>) -> Task<Message> {
let Some(step) = step else {
return Task::none();
};
let Some(draft) = self.reference_draft(&opened.host, &opened.request.path) else {
return Task::none();
};
if draft.reference_session() != opened.request.session {
return Task::none();
}
trigger::focus(
draft.reference_session(),
draft.reference_generation(),
&opened.request.path,
step,
)
}
/// Called before generic modal dispatch: the review owns a modal, and this
/// chooser owns only its active field. All browser events stop here.
pub(super) fn reference_message(&mut self, message: &Message) -> Option<Task<Message>> {
self.reconcile_reference_chooser();
match message {
Message::FieldReferenceOpen(request) => {
Some(self.open_reference(Host::Inspector, request.clone()))
}
Message::FieldReferenceEvent(event) => {
Some(self.reference_event(Host::Inspector, event.clone()))
}
Message::Workflow(workflow::Event::Semantic(semantic_review::Event::Row {
address,
facet: Some(facet),
event,
})) => {
let host = Host::Review {
address: *address,
facet: facet.clone(),
};
match event {
RowEvent::ReferenceOpen(request) => {
Some(self.open_reference(host, request.clone()))
}
RowEvent::ReferenceEvent(event) => {
Some(self.reference_event(host, event.clone()))
}
_ => None,
}
}
Message::Escape | Message::Request(Pending::Close(_))
if self.reference_authoring.opened.is_some() =>
{
let opened = self.reference_authoring.opened.as_ref().unwrap();
let host = opened.host.clone();
let event = opened.chooser.event(Action::Close(Close::Escape));
Some(self.reference_event(host, event))
}
// Global shortcuts are also emitted for keys captured by the search
// input. They must not apply drafts, navigate, or undo the model.
Message::Save(_)
| Message::ShortcutUndo(_)
| Message::Request(Pending::Open | Pending::New)
| Message::SourceNavigation(_)
| Message::Page(Page::Guide)
if self.reference_authoring.opened.is_some() =>
{
Some(Task::none())
}
_ => None,
}
}
pub(super) fn reference_overlay<
'a,
R: iced::advanced::text::Renderer<Font = iced::Font> + 'a,
>(
&'a self,
content: Element<'a, Message, iced::Theme, R>,
) -> Element<'a, Message, iced::Theme, R> {
let opened = self
.reference_authoring
.opened
.as_ref()
.filter(|opened| self.reference_valid(opened));
let host = opened
.map(|opened| opened.host.clone())
.unwrap_or(Host::Inspector);
let focus_scope = if self.reference_available() {
match self.workflow.as_ref() {
None if self.inspector_tab == InspectorTab::Properties => {
self.draft.as_ref().map(|draft| trigger::FormScope {
session: draft.reference_session(),
modal: false,
})
}
Some(workflow::Workflow::Semantic(state)) => state
.reference_form(self.project())
.map(|draft| trigger::FormScope {
session: draft.reference_session(),
modal: true,
}),
_ => None,
}
} else {
None
};
chooser::widget::Popup::new(
content,
opened.map(|opened| &opened.chooser),
opened.map_or(Rectangle::default(), |opened| opened.request.anchor),
move |event| host.message(event),
)
.focus_scope(focus_scope)
.into()
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,550 @@
use super::*;
use crate::forms::Draft;
use oa_core::*;
use serde_json::{Value, json};
const OWNER: Id = Id::from_u128(100);
const BASE: u128 = 10_000;
const PATH: &str = "/body/Oa/Shared/DataType/definition/Record/supertype";
fn element(p: &mut Project, id: Id, kind: Kind, layer: Layer, name: &str, parent: Option<Id>) {
let generated = p.add_element(kind, layer, name, parent).unwrap();
let mut element = p.elements.remove(&generated).unwrap();
element.id = id;
element.alias = format!("object_{}", id.as_u128());
if let Some(SharedBody::DataType { definition, .. }) = element.shared_mut() {
*definition = DataTypeDefinition::Record { supertype: None };
}
p.elements.insert(id, element);
}
fn catalog() -> Project {
let mut p = Project::empty();
p.id = Id::from_u128(1);
p.name = "Reference catalog".into();
element(
&mut p,
OWNER,
Kind::DataType,
Layer::Oa,
"Edited record",
None,
);
for n in (0..1_000).rev() {
let id = Id::from_u128(BASE + n);
element(&mut p, id, Kind::DataType, Layer::Oa, "Controller", None);
p.elements.get_mut(&id).unwrap().alias = format!("controller_{n:04}");
}
element(
&mut p,
Id::from_u128(200),
Kind::DataType,
Layer::Sa,
"Controller",
None,
);
element(
&mut p,
Id::from_u128(201),
Kind::Activity,
Layer::Oa,
"Controller",
None,
);
p
}
fn inspector(p: Project, selected: Id) -> App {
let mut app = App::with_project(p);
let _ = app.update(Message::Select(selected));
app
}
fn request(app: &App, host: &Host, path: &str) -> adapter::Open {
app.reference_draft(host, path).unwrap().reference_open(
app.project(),
path,
Rectangle {
x: 790.,
y: 640.,
width: 278.,
height: 32.,
},
)
}
fn open(app: &mut App, host: &Host, path: &str) {
let request = request(app, host, path);
let message = match host {
Host::Inspector => Message::FieldReferenceOpen(request),
Host::Review { address, facet } => {
Message::Workflow(workflow::Event::Semantic(semantic_review::Event::Row {
address: *address,
facet: Some(facet.clone()),
event: RowEvent::ReferenceOpen(request),
}))
}
};
let _ = app.update(message);
assert!(
app.reference_authoring.opened.is_some(),
"field must open: {}",
app.status
);
}
fn event(app: &App, action: Action) -> Message {
let opened = app.reference_authoring.opened.as_ref().unwrap();
opened.host.message(opened.chooser.event(action))
}
fn search(app: &mut App, query: &str) {
let serial = app
.reference_authoring
.opened
.as_ref()
.unwrap()
.chooser
.query_serial()
+ 1;
let event = event(
app,
Action::Query {
text: query.into(),
serial,
},
);
let _ = app.update(event);
}
fn choose(app: &mut App, id: Id) {
let event = event(app, Action::Choose(id));
let _ = app.update(event);
}
fn raw(app: &App) -> Value {
serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap()
}
fn review(app: &App) -> &semantic_review::State {
let Some(workflow::Workflow::Semantic(state)) = app.workflow.as_ref() else {
panic!("Review is open")
};
state
}
fn send_review(app: &mut App, event: RowEvent) {
let addressed = review(app).address_event(event);
let _ = app.update(Message::Workflow(workflow::Event::Semantic(addressed)));
}
fn review_host(app: &App) -> Host {
let semantic_review::Event::Row {
address,
facet: Some(facet),
..
} = review(app).address_event(RowEvent::Preview)
else {
panic!("Active facet")
};
Host::Review { address, facet }
}
fn trace(p: &mut Project, id: Id, oa: Id, sa: Id) {
p.traces.insert(
id,
Trace {
id,
alias: format!("trace_{}", id.as_u128()),
name: "Rationale".into(),
description: String::new(),
oa,
sa,
kind: TraceKind::Manual,
baseline: None,
},
);
}
#[test]
fn inspector_reference_browse_is_read_only_then_one_scoped_value_applies_with_exact_undo_redo() {
let p = catalog();
let mut app = inspector(p.clone(), OWNER);
let before = app.document.bundle().clone();
let revision = app.document.revision();
// Malformed escaped text is unrelated to the selected reference. Browsing
// and the scoped write must keep its exact spelling and inactive payload.
app.draft.as_mut().unwrap().set_exact(true).unwrap();
let _ = app.update(Message::Field("/name".into(), "\"unfinished".into()));
let raw_before = raw(&app);
open(&mut app, &Host::Inspector, PATH);
assert_eq!(
app.reference_authoring
.opened
.as_ref()
.unwrap()
.chooser
.count(),
1_000
);
search(&mut app, "controller @controller_0720 OA");
let picker = &app.reference_authoring.opened.as_ref().unwrap().chooser;
assert_eq!(picker.count(), 1);
assert_eq!(picker.highlighted().unwrap().id, Id::from_u128(BASE + 720));
assert_eq!(raw(&app), raw_before);
assert_eq!(app.document.bundle(), &before);
assert_eq!(app.document.revision(), revision);
assert!(!app.document.can_undo());
// Captured search shortcuts cannot accidentally save/apply or undo a model.
let _ = app.update(Message::Save(false));
let _ = app.update(Message::ShortcutUndo(false));
assert_eq!(raw(&app), raw_before);
assert_eq!(app.document.bundle(), &before);
choose(&mut app, Id::from_u128(BASE + 720));
let mut expected_raw = raw_before;
*expected_raw["value"].pointer_mut(PATH).unwrap() = json!(Id::from_u128(BASE + 720));
expected_raw["inputs"][PATH] = json!(Id::from_u128(BASE + 720).to_string());
assert_eq!(raw(&app), expected_raw);
assert_eq!(app.document.bundle(), &before);
assert!(!app.document.can_undo());
let _ = app.update(Message::Apply);
assert_eq!(
app.document.bundle(),
&before,
"Unrelated invalid text remains an Apply error"
);
let _ = app.update(Message::Field("/name".into(), "\"Edited record\"".into()));
let _ = app.update(Message::Apply);
let mut expected = p;
if let Some(SharedBody::DataType { definition, .. }) =
expected.elements.get_mut(&OWNER).unwrap().shared_mut()
{
*definition = DataTypeDefinition::Record {
supertype: Some(Id::from_u128(BASE + 720)),
};
}
assert_eq!(app.project(), &expected);
let accepted = app.document.bundle().clone();
assert_ne!(accepted, before);
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &before);
let _ = app.update(Message::Redo);
assert_eq!(app.document.bundle(), &accepted);
assert_eq!(app.project(), &expected);
}
#[test]
fn inspector_reference_retains_invalid_missing_and_incompatible_current_until_explicit_clear() {
for (raw_id, expected) in [
("-".into(), "invalid"),
(Id::from_u128(999).to_string(), "missing"),
(Id::from_u128(200).to_string(), "incompatible"),
] {
let mut app = inspector(catalog(), OWNER);
app.draft
.as_mut()
.unwrap()
.shape_scoped(PATH, json!(raw_id))
.unwrap();
let original = raw(&app);
let accepted = app.document.bundle().clone();
open(&mut app, &Host::Inspector, PATH);
let current = &app
.reference_authoring
.opened
.as_ref()
.unwrap()
.chooser
.current;
assert!(matches!(
(expected, current),
("invalid", chooser::Current::InvalidRaw(_))
| ("missing", chooser::Current::Missing(_))
| ("incompatible", chooser::Current::Incompatible(_))
));
let _ = app.update(Message::Escape);
assert_eq!(raw(&app), original);
open(&mut app, &Host::Inspector, PATH);
let clear = event(&app, Action::Clear);
let _ = app.update(clear);
assert!(
app.draft
.as_ref()
.unwrap()
.value
.pointer(PATH)
.unwrap()
.is_null()
);
assert_eq!(app.document.bundle(), &accepted);
assert!(!app.document.can_undo());
}
}
#[test]
fn chooser_rejects_old_results_after_context_recovery_reload_or_modal_and_keeps_history_text_out() {
for change in 0..7 {
let mut app = inspector(catalog(), OWNER);
open(&mut app, &Host::Inspector, PATH);
let delayed = event(&app, Action::Choose(Id::from_u128(BASE + 1)));
match change {
0 => {
app.draft
.as_mut()
.unwrap()
.shape_scoped(PATH, json!(Id::from_u128(BASE + 2)))
.unwrap();
}
1 => {
let saved = app.draft.as_ref().unwrap().recovery_snapshot();
app.draft = Some(Draft::from_recovery(app.project(), saved).unwrap());
}
2 => {
app.canvas_document = Id::new_v4();
}
3 => {
app.hosted.visible = true;
}
4 => {
app.draft
.as_mut()
.unwrap()
.set_context(Some(json!({"different":"scope"})));
}
5 => {
let _ = app.update(Message::Command(Command::Rename(
Id::from_u128(BASE + 3),
"Changed model".into(),
)));
}
_ => {
app.source_workspace
.edit("unfinished source".into(), Default::default());
}
}
let expected = raw(&app);
let source = app.document.bundle().clone();
let _ = app.update(delayed);
assert!(app.reference_authoring.opened.is_none());
assert_eq!(raw(&app), expected);
assert_eq!(app.document.bundle(), &source);
}
let mut p = catalog();
trace(&mut p, Id::from_u128(300), OWNER, Id::from_u128(200));
let app = inspector(p, Id::from_u128(300));
let draft = app.draft.as_ref().unwrap();
let request = draft.reference_open(
app.project(),
"/baseline/semantic/facets/0/references/0/target",
Rectangle::default(),
);
assert!(draft.reference_catalog(app.project(), &request, 0).is_err());
}
#[test]
fn reference_array_row_reorder_and_constructor_switch_invalidate_exact_old_field() {
let mut p = Project::empty();
for n in 0..3 {
element(
&mut p,
Id::from_u128(BASE + n),
Kind::ExchangeItem,
Layer::Oa,
"Signal item",
None,
);
}
element(&mut p, OWNER, Kind::Event, Layer::Oa, "Signal", None);
*p.elements.get_mut(&OWNER).unwrap().shared_mut().unwrap() = SharedBody::Event {
body: EventBody::Signal {
items: vec![Id::from_u128(BASE), Id::from_u128(BASE + 1)],
},
};
let mut app = inspector(p, OWNER);
let list = "/body/Oa/Shared/Event/body/Signal/items";
let path = format!("{list}/0");
open(&mut app, &Host::Inspector, &path);
let delayed = event(&app, Action::Choose(Id::from_u128(BASE + 2)));
let _ = app.update(Message::FieldArray(list.into(), Some(0), 1));
let expected = raw(&app);
assert_eq!(
app.draft.as_ref().unwrap().value.pointer(list),
Some(&json!([Id::from_u128(BASE + 1), Id::from_u128(BASE)]))
);
let _ = app.update(delayed);
assert_eq!(raw(&app), expected);
open(&mut app, &Host::Inspector, &path);
let delayed = event(&app, Action::Choose(Id::from_u128(BASE + 2)));
let _ = app.update(Message::FieldVariant(
"/body/Oa/Shared/Event/body".into(),
json!({"Change":{"expression":"unfinished"}}),
));
let expected = raw(&app);
let _ = app.update(delayed);
assert_eq!(raw(&app), expected);
assert!(!app.document.can_undo());
}
#[test]
fn review_reference_facets_groups_and_attachment_hosts_browse_without_replanning_and_reject_old_facet()
{
for mode in 0..3 {
let mut p = Project::empty();
p.id = Id::from_u128(1);
for (id, layer, parent) in [
(100, Layer::Oa, None),
(101, Layer::Sa, None),
(102, Layer::Sa, None),
(103, Layer::Oa, Some(Id::from_u128(100))),
(104, Layer::Sa, Some(Id::from_u128(101))),
] {
element(
&mut p,
Id::from_u128(id),
if parent.is_some() {
Kind::DataField
} else {
Kind::DataType
},
layer,
"Record",
parent,
);
}
trace(
&mut p,
Id::from_u128(300),
Id::from_u128(100),
Id::from_u128(101),
);
let facet = match mode {
0 => FacetSelector::Data(DataFacet::RecordSupertype),
1 => FacetSelector::Data(DataFacet::Constructor),
_ => FacetSelector::Child(KeyPair {
oa: Some(Id::from_u128(103)),
sa: Some(Id::from_u128(104)),
}),
};
let path = if mode == 2 {
"/parent"
} else {
"/body/Sa/Shared/DataType/definition/Record/supertype"
};
let mut app = App::with_project(p.clone());
let _ = app.update(Message::StartSemanticReview(Id::from_u128(100)));
send_review(&mut app, RowEvent::Select(facet.clone()));
send_review(
&mut app,
RowEvent::Decide(facet.clone(), Some(SemanticDecision::Candidate)),
);
let host = review_host(&app);
let record = if mode == 2 {
Id::from_u128(104)
} else {
Id::from_u128(101)
};
assert_eq!(app.reference_draft(&host, path).unwrap().original, record);
let before = review(&app).recovery_snapshot().unwrap();
let plan = serde_json::to_value(&review(&app).plan).unwrap();
let proposed = review(&app).proposed.clone();
let source = app.document.bundle().clone();
open(&mut app, &host, path);
search(&mut app, "@object_102 SA");
assert_eq!(
app.reference_authoring
.opened
.as_ref()
.unwrap()
.chooser
.count(),
1
);
assert_eq!(review(&app).recovery_snapshot().unwrap(), before);
assert_eq!(serde_json::to_value(&review(&app).plan).unwrap(), plan);
assert_eq!(review(&app).proposed, proposed);
assert_eq!(app.document.bundle(), &source);
let old = event(&app, Action::Choose(Id::from_u128(102)));
send_review(
&mut app,
RowEvent::Select(FacetSelector::Header(HeaderFacet::Name)),
);
let switched = review(&app).recovery_snapshot().unwrap();
let _ = app.update(old);
assert_eq!(review(&app).recovery_snapshot().unwrap(), switched);
send_review(&mut app, RowEvent::Select(facet));
open(&mut app, &host, path);
choose(&mut app, Id::from_u128(102));
let draft = app.reference_draft(&host, path).unwrap();
let mut expected_record = serde_json::to_value(&p.elements[&record]).unwrap();
*expected_record.pointer_mut(path).unwrap() = json!(Id::from_u128(102));
assert_eq!(draft.materialize().unwrap(), expected_record);
assert_eq!(app.document.bundle(), &source);
assert!(
!app.document.can_undo(),
"A choice only stages the active review candidate"
);
}
}
mod mounted;
#[test]
fn review_reference_cannot_reopen_or_write_a_banked_row_after_another_row_takes_focus() {
let mut p = Project::empty();
for (id, layer) in [
(100, Layer::Oa),
(101, Layer::Sa),
(102, Layer::Sa),
(110, Layer::Oa),
(111, Layer::Sa),
] {
element(
&mut p,
Id::from_u128(id),
Kind::DataType,
layer,
"Record",
None,
);
}
trace(
&mut p,
Id::from_u128(300),
Id::from_u128(100),
Id::from_u128(101),
);
trace(
&mut p,
Id::from_u128(310),
Id::from_u128(110),
Id::from_u128(111),
);
let mut app = App::with_project(p);
let _ = app.update(Message::StartSemanticReview(Id::from_u128(300)));
let facet = FacetSelector::Data(DataFacet::RecordSupertype);
send_review(&mut app, RowEvent::Select(facet.clone()));
send_review(
&mut app,
RowEvent::Decide(facet, Some(SemanticDecision::Candidate)),
);
let host = review_host(&app);
let path = "/body/Sa/Shared/DataType/definition/Record/supertype";
let old_open = request(&app, &host, path);
open(&mut app, &host, path);
let old_choice = event(&app, Action::Choose(Id::from_u128(102)));
for event in [
semantic_review::Event::ChooseTrace(crate::app::Choice {
id: Id::from_u128(310),
label: "Second exact trace".into(),
}),
semantic_review::Event::OpenTrace,
] {
let _ = app.update(Message::Workflow(workflow::Event::Semantic(event)));
}
assert_eq!(review(&app).target(app.project()), Some(Id::from_u128(111)));
let expected = review(&app).recovery_snapshot().unwrap();
let source = app.document.bundle().clone();
let _ = app.update(old_choice);
let Host::Review { address, facet } = host else {
unreachable!()
};
let _ = app.update(Message::Workflow(workflow::Event::Semantic(
semantic_review::Event::Row {
address,
facet: Some(facet),
event: RowEvent::ReferenceOpen(old_open),
},
)));
assert!(app.reference_authoring.opened.is_none());
assert_eq!(review(&app).recovery_snapshot().unwrap(), expected);
assert_eq!(app.document.bundle(), &source);
assert!(!app.document.can_undo());
}
@@ -0,0 +1,890 @@
//! Real field + app-root overlay interaction. The null text renderer lets the
//! same retained widget tree exercise focus and geometry without a GPU/window.
use super::*;
use iced::futures::StreamExt;
use iced::{
Event as Input, Point, Size, Theme, Vector,
advanced::{
Layout, Shell, layout,
widget::{Id as WidgetId, Operation, Tree, operation},
},
keyboard, mouse,
widget::{Space, column, container, opaque, scrollable, stack, text_input},
};
#[derive(Default)]
struct Clipboard;
impl iced::advanced::Clipboard for Clipboard {
fn read(&self, _: iced::advanced::clipboard::Kind) -> Option<String> {
None
}
fn write(&mut self, _: iced::advanced::clipboard::Kind, _: String) {}
}
#[derive(Default)]
struct Fields {
values: Vec<(WidgetId, Rectangle, bool)>,
scrolls: Vec<(Rectangle, Vector)>,
}
impl Operation for Fields {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation)) {
visit(self);
}
fn focusable(
&mut self,
id: Option<&WidgetId>,
bounds: Rectangle,
state: &mut dyn operation::Focusable,
) {
if let Some(id) = id {
self.values.push((id.clone(), bounds, state.is_focused()));
}
}
fn scrollable(
&mut self,
_: Option<&WidgetId>,
bounds: Rectangle,
_: Rectangle,
translation: Vector,
_: &mut dyn operation::Scrollable,
) {
self.scrolls.push((bounds, translation));
}
}
impl Fields {
fn field(&self, id: &WidgetId) -> (Rectangle, bool) {
self.values
.iter()
.find(|(actual, _, _)| actual == id)
.map(|(_, bounds, focused)| (*bounds, *focused))
.expect("Mounted field identity")
}
}
fn view(
app: &App,
scrolled: bool,
nested: bool,
show_review: bool,
) -> Element<'_, Message, Theme, ()> {
let draft = app.draft.as_ref().unwrap();
let form = column![
text_input("Name", &draft.inputs["/name"].raw)
.id("before-reference")
.on_input(|raw| Message::Field("/name".into(), raw)),
adapter::field(draft, app.project(), PATH),
text_input("Description", &draft.inputs["/description"].raw)
.id("after-reference")
.on_input(|raw| Message::Field("/description".into(), raw)),
]
.spacing(9);
let form = trigger::scope(form, draft.reference_session());
let base: Element<'_, Message, Theme, ()> = if scrolled {
container(
scrollable(column![Space::new().height(500), form])
.id("reference-scroll")
.height(180),
)
.width(300)
.into()
} else {
container(form).width(300).height(iced::Fill).into()
};
let base: Element<'_, Message, Theme, ()> = if nested {
scrollable(column![Space::new().height(400), base])
.id("outer-reference-scroll")
.height(180)
.width(300)
.into()
} else {
base
};
let base = if show_review {
let review: Element<'_, Message, Theme, ()> = match app.workflow.as_ref() {
Some(workflow::Workflow::Semantic(state)) => {
match state.reference_form(app.project()) {
Some(draft) => {
let mut content = column![];
if let Some(raw) = &state.operation_omission {
content = content.push(
text_input("Required engineering rationale", raw)
.id("review-rationale")
.on_input(|raw| {
Message::Workflow(workflow::Event::Semantic(
state.address_event(RowEvent::OperationRationale(raw)),
))
}),
);
}
content = content.push(trigger::scope(
adapter::field(draft, app.project(), "/parent").map(|message| {
match message {
Message::FieldReferenceOpen(request) => {
Message::Workflow(workflow::Event::Semantic(
state.address_event(RowEvent::ReferenceOpen(request)),
))
}
other => other,
}
}),
draft.reference_session(),
));
opaque(container(trigger::modal(content)).width(300).height(180)).into()
}
None => Space::new().into(),
}
}
_ => Space::new().into(),
};
stack![base, review].into()
} else {
base
};
app.reference_overlay(base)
}
struct Mount {
tree: Option<Tree>,
size: Size,
scrolled: bool,
nested: bool,
show_review: bool,
}
impl Default for Mount {
fn default() -> Self {
Self {
tree: None,
size: Size::new(360., 320.),
scrolled: false,
nested: false,
show_review: false,
}
}
}
impl Mount {
fn frame(
&mut self,
app: &App,
events: &[(Input, Option<Point>)],
) -> (Vec<Message>, Fields, Option<Rectangle>) {
let mut view = view(app, self.scrolled, self.nested, self.show_review);
let tree = self.tree.get_or_insert_with(|| Tree::new(view.as_widget()));
view.as_widget().diff(tree);
let node =
view.as_widget_mut()
.layout(tree, &(), &layout::Limits::new(Size::ZERO, self.size));
let viewport = Rectangle::with_size(self.size);
let overlay_node = view
.as_widget_mut()
.overlay(tree, Layout::new(&node), &(), &viewport, Vector::ZERO)
.map(|mut overlay| overlay.as_overlay_mut().layout(&(), self.size));
let mut messages = Vec::new();
for (input, point) in events {
let mut shell = Shell::new(&mut messages);
let cursor = point.map_or(mouse::Cursor::Unavailable, mouse::Cursor::Available);
if let Some(overlay_node) = &overlay_node {
let mut overlay = view
.as_widget_mut()
.overlay(tree, Layout::new(&node), &(), &viewport, Vector::ZERO)
.unwrap();
overlay.as_overlay_mut().update(
input,
Layout::new(overlay_node),
cursor,
&(),
&mut Clipboard,
&mut shell,
);
assert!(shell.is_event_captured());
} else {
view.as_widget_mut().update(
tree,
input,
Layout::new(&node),
cursor,
&(),
&mut Clipboard,
&mut shell,
&viewport,
);
}
}
let mut fields = Fields::default();
view.as_widget_mut()
.operate(tree, Layout::new(&node), &(), &mut fields);
(
messages,
fields,
overlay_node.map(|node| node.children()[0].bounds()),
)
}
fn click(&mut self, app: &App, point: Point) -> Vec<Message> {
self.frame(
app,
&[
(
Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Some(point),
),
(
Input::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
Some(point),
),
],
)
.0
}
async fn perform(&mut self, app: &App, task: Task<Message>) {
let Some(mut stream) = iced_runtime::task::into_stream(task) else {
return;
};
while let Some(action) = stream.next().await {
let iced_runtime::Action::Widget(mut operation) = action else {
panic!("Chooser only requests scoped widget focus")
};
let mut view = view(app, self.scrolled, self.nested, self.show_review);
let tree = self.tree.get_or_insert_with(|| Tree::new(view.as_widget()));
view.as_widget().diff(tree);
let node =
view.as_widget_mut()
.layout(tree, &(), &layout::Limits::new(Size::ZERO, self.size));
loop {
view.as_widget_mut()
.operate(tree, Layout::new(&node), &(), operation.as_mut());
match operation.finish() {
operation::Outcome::Chain(next) => operation = next,
_ => break,
}
}
}
}
async fn dispatch(&mut self, app: &mut App, messages: Vec<Message>) {
for message in messages {
let task = app.update(message);
self.perform(app, task).await;
}
}
}
fn key(key: keyboard::key::Named, shift: bool) -> Input {
Input::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(key),
modified_key: keyboard::Key::Named(key),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::Space),
location: keyboard::Location::Standard,
modifiers: if shift {
keyboard::Modifiers::SHIFT
} else {
keyboard::Modifiers::empty()
},
text: None,
repeat: false,
})
}
fn typing(raw: &str) -> Vec<(Input, Option<Point>)> {
raw.chars()
.map(|character| {
let raw = character.to_string();
(
Input::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Character(raw.clone().into()),
modified_key: keyboard::Key::Character(raw.clone().into()),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::KeyA),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::empty(),
text: Some(raw.into()),
repeat: false,
}),
None,
)
})
.collect()
}
#[tokio::test]
async fn mounted_reference_trigger_tabs_to_root_popup_search_escape_and_exact_adjacent_fields() {
let mut app = inspector(catalog(), OWNER);
let accepted = app.document.bundle().clone();
let original = raw(&app);
let mut mount = Mount::default();
let fields = mount.frame(&app, &[]).1;
let messages = mount.click(
&app,
fields.field(&WidgetId::new("before-reference")).0.center(),
);
mount.dispatch(&mut app, messages).await;
let (_, fields, _) = mount.frame(&app, &[(key(keyboard::key::Named::Tab, false), None)]);
let id = trigger::field_id(app.draft.as_ref().unwrap().reference_generation(), PATH);
assert!(
fields.field(&id).1,
"Tab reaches the real reference trigger"
);
let messages = mount
.frame(&app, &[(key(keyboard::key::Named::Enter, false), None)])
.0;
assert_eq!(messages.len(), 1, "One keyboard activation opens one field");
mount.dispatch(&mut app, messages).await;
let popup = mount
.frame(&app, &[])
.2
.expect("App root overlay is mounted");
assert!(
popup.x >= 0.
&& popup.y >= 0.
&& popup.x + popup.width <= 360.
&& popup.y + popup.height <= 320.
);
let mut inputs = typing("@controller_0720");
inputs.push((key(keyboard::key::Named::Escape, false), None));
let messages = mount.frame(&app, &inputs).0;
mount.dispatch(&mut app, messages).await;
let (_, fields, popup) = mount.frame(&app, &[]);
assert!(popup.is_none());
assert!(
fields.field(&id).1,
"Escape returns to its exact reference field"
);
assert_eq!(raw(&app), original);
assert_eq!(app.document.bundle(), &accepted);
for (backwards, expected) in [(false, "after-reference"), (true, "before-reference")] {
let messages = mount.click(&app, fields.field(&id).0.center());
mount.dispatch(&mut app, messages).await;
let messages = mount
.frame(&app, &[(key(keyboard::key::Named::Tab, backwards), None)])
.0;
mount.dispatch(&mut app, messages).await;
let (_, fields, popup) = mount.frame(&app, &[]);
assert!(popup.is_none());
assert!(
fields.field(&WidgetId::new(expected)).1,
"Chooser Tab stays within the originating form"
);
}
assert_eq!(app.document.bundle(), &accepted);
}
#[tokio::test]
async fn mounted_reference_choice_stages_literal_identity_and_delayed_focus_cannot_hit_replacement_field()
{
let mut app = inspector(catalog(), OWNER);
let accepted = app.document.bundle().clone();
let mut mount = Mount::default();
let id = trigger::field_id(app.draft.as_ref().unwrap().reference_generation(), PATH);
let fields = mount.frame(&app, &[]).1;
let messages = mount.click(&app, fields.field(&id).0.center());
mount.dispatch(&mut app, messages).await;
let messages = mount.frame(&app, &typing("@controller_0720")).0;
mount.dispatch(&mut app, messages).await;
assert_eq!(
app.reference_authoring
.opened
.as_ref()
.unwrap()
.chooser
.count(),
1
);
let messages = mount
.frame(&app, &[(key(keyboard::key::Named::Enter, false), None)])
.0;
assert_eq!(messages.len(), 1);
let delayed_focus = app.update(messages.into_iter().next().unwrap());
assert_eq!(
app.draft.as_ref().unwrap().value.pointer(PATH),
Some(&json!(Id::from_u128(BASE + 720)))
);
assert_eq!(app.document.bundle(), &accepted);
// A structural edit occurs after Choose but before its asynchronous focus.
app.draft
.as_mut()
.unwrap()
.shape_scoped(PATH, Value::Null)
.unwrap();
let fields = mount.frame(&app, &[]).1;
let messages = mount.click(
&app,
fields.field(&WidgetId::new("after-reference")).0.center(),
);
mount.dispatch(&mut app, messages).await;
mount.perform(&app, delayed_focus).await;
let fields = mount.frame(&app, &[]).1;
assert!(
fields.field(&WidgetId::new("after-reference")).1,
"A missing old field target makes no focus changes"
);
assert!(
!fields
.field(&trigger::field_id(
app.draft.as_ref().unwrap().reference_generation(),
PATH
))
.1
);
assert_eq!(app.document.bundle(), &accepted);
}
#[tokio::test]
async fn mounted_scrolled_reference_anchor_uses_window_geometry_for_pointer_and_keyboard() {
let mut app = inspector(catalog(), OWNER);
let mut mount = Mount {
scrolled: true,
..Default::default()
};
mount.frame(&app, &[]);
mount
.perform(
&app,
iced::widget::operation::snap_to("reference-scroll", scrollable::RelativeOffset::END),
)
.await;
let fields = mount.frame(&app, &[]).1;
let id = trigger::field_id(app.draft.as_ref().unwrap().reference_generation(), PATH);
let content = fields.field(&id).0;
let (viewport, offset) = fields.scrolls[0];
assert!(offset.y > 400., "Fixture is genuinely scrolled");
let expected = Rectangle {
x: content.x - offset.x,
y: content.y - offset.y,
..content
}
.intersection(&viewport)
.unwrap();
let messages = mount.click(&app, expected.center());
let [Message::FieldReferenceOpen(request)] = messages.as_slice() else {
panic!("Scrolled field should emit one actual Open")
};
assert_eq!(request.anchor, expected);
mount.dispatch(&mut app, messages).await;
let close = app.update(Message::Escape);
mount.perform(&app, close).await;
let messages = mount
.frame(&app, &[(key(keyboard::key::Named::Enter, false), None)])
.0;
let [Message::FieldReferenceOpen(request)] = messages.as_slice() else {
panic!("Focused scrolled field opens without a pointer")
};
assert_eq!(request.anchor, expected);
}
#[tokio::test]
async fn mounted_fresh_tab_reveals_offscreen_reference_and_return_reveals_it_again() {
for nested in [false, true] {
let mut app = inspector(catalog(), OWNER);
let original = raw(&app);
let source = app.document.bundle().clone();
let mut mount = Mount {
scrolled: true,
nested,
..Default::default()
};
let fields = mount.frame(&app, &[]).1;
assert!(
fields
.scrolls
.iter()
.all(|(_, offset)| *offset == Vector::ZERO)
);
assert!(fields.field(&WidgetId::new("before-reference")).0.y > 180.);
let messages = mount
.frame(&app, &[(key(keyboard::key::Named::Tab, false), None)])
.0;
assert!(
messages.is_empty(),
"Keyboard reveal must not author any input"
);
let fields = mount.frame(&app, &[]).1;
assert!(fields.field(&WidgetId::new("before-reference")).1);
assert!(
fields.scrolls.iter().all(|(_, offset)| offset.y > 0.),
"Every enclosing viewport reveals fresh focus"
);
let id = trigger::field_id(app.draft.as_ref().unwrap().reference_generation(), PATH);
let offset: f32 = fields.scrolls.iter().map(|(_, offset)| offset.y).sum();
assert!(
fields.field(&id).0.y - offset >= 180.,
"The next reference starts below the fold"
);
let messages = mount
.frame(&app, &[(key(keyboard::key::Named::Tab, false), None)])
.0;
assert!(messages.is_empty());
let fields = mount.frame(&app, &[]).1;
let offset: f32 = fields.scrolls.iter().map(|(_, offset)| offset.y).sum();
let (bounds, focused) = fields.field(&id);
assert!(focused);
assert!(bounds.y - offset >= -0.01 && bounds.y + bounds.height - offset <= 180.01);
let messages = mount
.frame(&app, &[(key(keyboard::key::Named::Enter, false), None)])
.0;
assert_eq!(
messages.len(),
1,
"A newly revealed field opens through Enter"
);
mount.dispatch(&mut app, messages).await;
let return_focus = app.update(Message::Escape);
mount
.perform(
&app,
iced::widget::operation::snap_to(
"reference-scroll",
scrollable::RelativeOffset::START,
),
)
.await;
if nested {
mount
.perform(
&app,
iced::widget::operation::snap_to(
"outer-reference-scroll",
scrollable::RelativeOffset::START,
),
)
.await;
}
assert!(
mount
.frame(&app, &[])
.1
.scrolls
.iter()
.all(|(_, offset)| *offset == Vector::ZERO)
);
mount.perform(&app, return_focus).await;
let fields = mount.frame(&app, &[]).1;
let offset: f32 = fields.scrolls.iter().map(|(_, offset)| offset.y).sum();
let (bounds, focused) = fields.field(&id);
assert!(
focused && bounds.y - offset >= -0.01 && bounds.y + bounds.height - offset <= 180.01
);
assert_eq!(raw(&app), original);
assert_eq!(app.document.bundle(), &source);
}
}
#[tokio::test]
async fn mounted_form_tab_enters_in_both_directions_and_cycles_boundaries_without_losing_focus() {
for backwards in [false, true] {
let app = inspector(catalog(), OWNER);
let original = raw(&app);
let mut mount = Mount::default();
let reference = trigger::field_id(app.draft.as_ref().unwrap().reference_generation(), PATH);
let forward = [
WidgetId::new("before-reference"),
reference.clone(),
WidgetId::new("after-reference"),
];
let reverse = [
WidgetId::new("after-reference"),
reference,
WidgetId::new("before-reference"),
];
let expected = if backwards { &reverse } else { &forward };
for n in 0..7 {
let (messages, fields, popup) =
mount.frame(&app, &[(key(keyboard::key::Named::Tab, backwards), None)]);
assert!(messages.is_empty() && popup.is_none());
assert!(fields.field(&expected[n % 3]).1);
assert_eq!(
fields
.values
.iter()
.filter(|(_, _, focused)| *focused)
.count(),
1
);
}
assert_eq!(raw(&app), original);
assert!(!app.document.can_undo());
}
}
#[tokio::test]
async fn mounted_delayed_return_cannot_focus_under_review_and_fresh_modal_tab_owns_its_form() {
let mut p = catalog();
trace(&mut p, Id::from_u128(300), OWNER, Id::from_u128(200));
let mut app = inspector(p, OWNER);
let source = app.document.bundle().clone();
let original = raw(&app);
let mut mount = Mount {
show_review: true,
..Default::default()
};
let id = trigger::field_id(app.draft.as_ref().unwrap().reference_generation(), PATH);
let session = app.draft.as_ref().unwrap().reference_session();
let fields = mount.frame(&app, &[]).1;
let messages = mount.click(&app, fields.field(&id).0.center());
mount.dispatch(&mut app, messages).await;
let return_focus = app.update(Message::Escape);
let fields = mount.frame(&app, &[]).1;
let messages = mount.click(
&app,
fields.field(&WidgetId::new("after-reference")).0.center(),
);
mount.dispatch(&mut app, messages).await;
let _ = app.update(Message::StartSemanticReview(Id::from_u128(300)));
let facet = FacetSelector::Header(HeaderFacet::Parent);
send_review(&mut app, RowEvent::Select(facet.clone()));
send_review(
&mut app,
RowEvent::Decide(facet, Some(SemanticDecision::Candidate)),
);
assert_eq!(
app.draft.as_ref().unwrap().reference_session(),
session,
"Old Inspector really remains mounted"
);
assert_eq!(
trigger::field_id(app.draft.as_ref().unwrap().reference_generation(), PATH),
id
);
let review_before = review(&app).recovery_snapshot().unwrap();
let review_field = trigger::field_id(
review(&app)
.reference_form(app.project())
.unwrap()
.reference_generation(),
"/parent",
);
mount.perform(&app, return_focus).await;
let fields = mount.frame(&app, &[]).1;
assert!(
!fields.field(&id).1,
"A live old field underneath a modal cannot receive the stale focus task"
);
assert!(fields.field(&WidgetId::new("after-reference")).1);
assert!(!fields.field(&review_field).1);
let (messages, fields, _) = mount.frame(&app, &[(key(keyboard::key::Named::Tab, false), None)]);
assert!(messages.is_empty());
assert!(
fields.field(&review_field).1,
"Review entry ignores retained focus under its modal"
);
assert!(
!fields.field(&WidgetId::new("after-reference")).1,
"Modal focus acquisition deactivates background inputs"
);
let messages = mount.frame(&app, &typing("x")).0;
assert!(
messages.is_empty(),
"A character at the focused Review trigger cannot type into the Inspector below it"
);
let (messages, fields, _) = mount.frame(&app, &[(key(keyboard::key::Named::Tab, true), None)]);
assert!(messages.is_empty());
assert!(fields.field(&review_field).1);
assert!(!fields.field(&id).1);
assert_eq!(review(&app).recovery_snapshot().unwrap(), review_before);
assert_eq!(raw(&app), original);
assert_eq!(app.document.bundle(), &source);
}
#[tokio::test]
async fn mounted_review_pointer_open_and_outside_dismissal_keep_background_input_inactive() {
let mut p = catalog();
trace(&mut p, Id::from_u128(300), OWNER, Id::from_u128(200));
let mut app = inspector(p, OWNER);
let original = raw(&app);
let source = app.document.bundle().clone();
let mut mount = Mount {
show_review: true,
..Default::default()
};
let fields = mount.frame(&app, &[]).1;
let messages = mount.click(
&app,
fields.field(&WidgetId::new("after-reference")).0.center(),
);
mount.dispatch(&mut app, messages).await;
let _ = app.update(Message::StartSemanticReview(Id::from_u128(300)));
let facet = FacetSelector::Header(HeaderFacet::Parent);
send_review(&mut app, RowEvent::Select(facet.clone()));
send_review(
&mut app,
RowEvent::Decide(facet, Some(SemanticDecision::Candidate)),
);
let saved = review(&app).recovery_snapshot().unwrap();
let id = trigger::field_id(
review(&app)
.reference_form(app.project())
.unwrap()
.reference_generation(),
"/parent",
);
let fields = mount.frame(&app, &[]).1;
assert!(
fields.field(&WidgetId::new("after-reference")).1,
"Fixture retains Inspector focus before the modal receives input"
);
let messages = mount.click(&app, fields.field(&id).0.center());
mount.dispatch(&mut app, messages).await;
assert!(matches!(
&app.reference_authoring.opened.as_ref().unwrap().host,
Host::Review { .. }
));
let fields = mount.frame(&app, &[]).1;
assert!(!fields.field(&WidgetId::new("after-reference")).1);
let messages = mount.click(&app, Point::new(359., 319.));
assert!(matches!(
messages.as_slice(),
[Message::Workflow(workflow::Event::Semantic(
semantic_review::Event::Row {
event: RowEvent::ReferenceEvent(chooser::Event {
action: Action::Close(Close::Outside),
..
}),
..
}
))]
));
for message in messages {
let task = app.update(message);
assert!(
iced_runtime::task::into_stream(task).is_none(),
"Outside dismissal must not request focus or apply"
);
}
let (messages, fields, popup) = mount.frame(&app, &typing("x"));
assert!(messages.is_empty() && popup.is_none());
assert!(!fields.field(&WidgetId::new("after-reference")).1);
assert_eq!(review(&app).recovery_snapshot().unwrap(), saved);
assert_eq!(raw(&app), original);
assert_eq!(app.document.bundle(), &source);
}
#[tokio::test]
async fn mounted_reverse_review_required_rationale_remains_editable_beside_candidate_reference_form()
{
let mut p = persistence::decode(include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../harness/fixtures/interface-operation-probe/output/boundary-only.json"
)))
.unwrap();
let sa = p
.elements
.values()
.find(|element| {
element.layer() == Layer::Sa
&& matches!(
element.shared(),
Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
operation: Some(_),
message_kind: MessageKind::Call | MessageKind::Asynchronous,
..
},
..
})
)
})
.unwrap()
.id;
let inspector_id = Id::new_v4();
element(
&mut p,
inspector_id,
Kind::DataType,
Layer::Oa,
"Inspector record",
None,
);
let scenario = p
.add_element(Kind::Scenario, Layer::Oa, "Operational counterpart", None)
.unwrap();
let oa = p
.add_element(
Kind::Occurrence,
Layer::Oa,
"Operational message",
Some(scenario),
)
.unwrap();
*p.elements.get_mut(&oa).unwrap().shared_mut().unwrap() = SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
exchange: None,
sender: None,
receiver: None,
message_kind: MessageKind::Asynchronous,
reply_to: None,
values: vec![],
operation: None,
},
precondition: String::new(),
postcondition: String::new(),
};
p.elements
.get_mut(&scenario)
.unwrap()
.steps_mut()
.unwrap()
.push(oa);
let trace_id = Id::new_v4();
trace(&mut p, trace_id, oa, sa);
let mut app = inspector(p, inspector_id);
let source = app.document.bundle().clone();
let inspector_raw = raw(&app);
let _ = app.update(Message::StartSemanticReview(trace_id));
let _ = app.update(Message::Workflow(workflow::Event::Semantic(
semantic_review::Event::Direction(TransitionDirection::SaToOa),
)));
let facet = FacetSelector::Header(HeaderFacet::Parent);
send_review(&mut app, RowEvent::Select(facet.clone()));
send_review(
&mut app,
RowEvent::Decide(facet, Some(SemanticDecision::Candidate)),
);
send_review(&mut app, RowEvent::OperationOmission(true));
assert_eq!(review(&app).direction, TransitionDirection::SaToOa);
assert_eq!(review(&app).operation_omission.as_deref(), Some(""));
let candidate = serde_json::to_value(
review(&app)
.reference_form(app.project())
.unwrap()
.recovery_snapshot(),
)
.unwrap();
let mut mount = Mount {
show_review: true,
..Default::default()
};
let fields = mount.frame(&app, &[]).1;
let messages = mount.click(
&app,
fields.field(&WidgetId::new("review-rationale")).0.center(),
);
mount.dispatch(&mut app, messages).await;
let messages = mount.frame(&app, &typing("Engineering reason")).0;
assert_eq!(
messages.len(),
"Engineering reason".chars().count(),
"Every key reaches the legitimate sibling inside Review"
);
assert!(messages.iter().all(|message| matches!(
message,
Message::Workflow(workflow::Event::Semantic(semantic_review::Event::Row {
event: RowEvent::OperationRationale(_),
..
}))
)));
mount.dispatch(&mut app, messages).await;
assert_eq!(
review(&app).operation_omission.as_deref(),
Some("Engineering reason")
);
assert!(
mount
.frame(&app, &[])
.1
.field(&WidgetId::new("review-rationale"))
.1
);
assert_eq!(
serde_json::to_value(
review(&app)
.reference_form(app.project())
.unwrap()
.recovery_snapshot()
)
.unwrap(),
candidate
);
assert_eq!(raw(&app), inspector_raw);
assert_eq!(app.document.bundle(), &source);
assert!(!app.document.can_undo());
}
+184 -48
View File
@@ -14,7 +14,16 @@ use iced::{
};
use oa_core::*;
use std::collections::BTreeMap;
pub(crate) mod canvas_workspace;
#[cfg(test)]
mod contextual_source_tests;
pub(crate) mod creation;
mod form_session;
pub(crate) mod scenario;
// Projection acceptance precedes the coordinated scenario renderer integration.
#[cfg(test)]
mod scenario_lifecycle;
pub(crate) mod source_draft;
pub(crate) mod state_canvas;
pub(crate) mod state_edit;
pub(crate) mod state_menu;
@@ -29,38 +38,21 @@ mod scenario_scroll {
use iced::advanced::{Clipboard, Layout, Shell, Widget, layout, renderer, widget};
use iced::{Length, Vector, overlay};
pub(super) fn observe<'a>(
pub(super) fn observe<'a, R: renderer::Renderer + 'a>(
context: scenario::Context,
area: scenario::ScrollArea,
process: bool,
restore: Option<scenario::ScrollRestore>,
content: impl Into<Element<'a, Message>>,
) -> Element<'a, Message> {
content: impl Into<Element<'a, Message, Theme, R>>,
) -> Element<'a, Message, Theme, R> {
Element::new(Observer {
content: content.into(),
context,
area,
process: false,
process,
restore,
})
}
pub(super) fn observe_topology<'a>(
context: topology::Context,
area: scenario::ScrollArea,
content: impl Into<Element<'a, Message>>,
) -> Element<'a, Message> {
Element::new(Observer {
content: content.into(),
context: scenario::Context {
document: context.document,
scenario: context.owner,
revision: context.revision,
epoch: context.epoch,
},
area,
process: true,
restore: None,
})
}
struct Observer<'a, R = Renderer> {
content: Element<'a, Message, Theme, R>,
context: scenario::Context,
@@ -331,7 +323,7 @@ mod scenario_scroll {
fn observer(height: f32, context: scenario::Context) -> Observer<'static, ()> {
Observer {
context,
area: scenario::ScrollArea::Canvas,
area: scenario::ScrollArea::Page,
process: false,
restore: None,
content: scrollable(iced::widget::Space::new().width(200.).height(height))
@@ -401,7 +393,7 @@ mod scenario_scroll {
std::time::Instant::now(),
))
};
for area in [ScrollArea::Canvas, ScrollArea::Page] {
for area in [ScrollArea::Page] {
for returned_height in [600., 250.] {
let (project, [a, _, _], [use_id, _, _]) = navigation_fixture();
let mut app = App::with_project(project.clone());
@@ -731,16 +723,41 @@ mod scenario_scroll {
}
#[derive(Debug, Clone)]
pub enum Event {
Creation(creation::Event),
Topology(topology::Event),
Scenario(scenario::Event),
States(states::Event),
Submit,
}
impl Event {
pub fn is_source_back(&self) -> bool {
matches!(
self,
Self::Creation(creation::Event::Source(source_draft::Event::Edit(
_,
source_draft::Edit::Back
))) | Self::Scenario(scenario::Event::Source(source_draft::Event::Edit(
_,
source_draft::Edit::Back
))) | Self::Topology(topology::Event::Source(source_draft::Event::Edit(
_,
source_draft::Edit::Back
)))
)
}
pub fn is_source(&self) -> bool {
matches!(
self,
Self::Creation(creation::Event::Source(_))
| Self::Scenario(scenario::Event::Source(_))
| Self::Topology(topology::Event::Source(_))
)
}
pub fn starts_form(&self) -> bool {
matches!(
self,
Self::Topology(topology::Event::Start(..))
Self::Creation(creation::Event::Open(..))
| Self::Topology(topology::Event::Start(..))
| Self::Scenario(scenario::Event::Start(..))
| Self::States(states::Event::Start(..) | states::Event::Edit(..))
)
@@ -749,6 +766,7 @@ impl Event {
matches!(
self,
Self::Submit
| Self::Creation(creation::Event::Submit)
| Self::Topology(topology::Event::Submit)
| Self::Scenario(scenario::Event::Submit)
| Self::States(states::Event::Submit)
@@ -757,6 +775,7 @@ impl Event {
}
#[derive(Default)]
pub struct State {
pub(crate) creation: creation::State,
pub active_owner: Option<Id>,
pub diagram: state_view::State,
pub(crate) topology: topology::State,
@@ -773,6 +792,7 @@ struct RecoveryDraft {
}
#[derive(serde::Serialize, serde::Deserialize)]
enum RecoveryKind {
Creation,
State,
Scenario,
Process,
@@ -782,6 +802,7 @@ impl State {
/// viewport geometry and document/revision tokens never cross a restart.
pub fn recovery_snapshot(&self) -> Result<Option<serde_json::Value>, String> {
let drafts = [
(RecoveryKind::Creation, self.creation.recovery_snapshot()?),
(RecoveryKind::State, self.states.recovery_snapshot()?),
(RecoveryKind::Scenario, self.scenario.recovery_snapshot()?),
(RecoveryKind::Process, self.topology.recovery_snapshot()?),
@@ -817,6 +838,9 @@ impl State {
}
let mut restored = Self::default();
match saved.kind {
RecoveryKind::Creation => {
restored.creation = creation::State::from_recovery(saved.draft)?
}
RecoveryKind::State => restored.states = states::State::from_recovery(saved.draft)?,
RecoveryKind::Scenario => {
restored.scenario = scenario::State::from_recovery(saved.draft)?
@@ -831,7 +855,7 @@ impl State {
}
pub fn has_pending(&self) -> bool {
self.pending_owner().is_some()
self.creation.has_pending() || self.pending_owner().is_some()
}
pub fn pending_owner(&self) -> Option<Id> {
@@ -844,7 +868,9 @@ impl State {
/// Prepare the active form without discarding inputs. The caller must execute
/// this exact command and acknowledge only a successful document transaction.
pub fn prepare_pending(&self, p: &Project) -> Result<Option<Command>, String> {
if self.topology.pending_owner().is_some() {
if self.creation.has_pending() {
self.creation.prepare_pending(p).map(Some)
} else if self.topology.pending_owner().is_some() {
self.topology.prepare_pending(p).map(Some)
} else if self.scenario.pending_owner().is_some() {
self.scenario.prepare_pending(p).map(Some)
@@ -857,7 +883,20 @@ impl State {
/// Clear the active form after its prepared command commits successfully.
/// Rejected commands must leave the form available for repair and retry.
pub fn source_active(&self) -> bool {
self.creation.source_active()
|| self.scenario.source_active()
|| self.topology.source_active()
}
pub fn source_open(&self) -> bool {
self.creation.source_open() || self.scenario.source_open() || self.topology.source_open()
}
pub fn source_back(&mut self) -> bool {
self.creation.source_back() || self.scenario.source_back() || self.topology.source_back()
}
pub fn acknowledge_commit(&mut self) {
self.creation.acknowledge_commit();
self.topology.acknowledge_commit();
self.scenario.acknowledge_commit();
self.states.acknowledge_commit();
@@ -867,7 +906,8 @@ impl State {
if self.has_pending()
&& matches!(
&event,
Event::Topology(topology::Event::Start(..))
Event::Creation(creation::Event::Open(..))
| Event::Topology(topology::Event::Start(..))
| Event::Scenario(scenario::Event::Start(..))
| Event::States(states::Event::Start(..) | states::Event::Edit(..))
)
@@ -885,6 +925,7 @@ impl State {
return Ok(None);
}
match event {
Event::Creation(event) => self.creation.update(p, event),
Event::Topology(event) => self.topology.update(p, event),
Event::Scenario(event) => self.scenario.update(p, event),
Event::States(event) => self.states.update(p, event),
@@ -898,6 +939,43 @@ impl State {
pub fn view(app: &App) -> Element<'_, Message> {
let p = app.project();
if let Some(card) = app.behavior.creation.view(p) {
return card.map(|event| Message::Behavior(Event::Creation(event)));
}
if let Some(owner) = app.behavior.pending_owner() {
let kind = p.elements.get(&owner).map(oa_core::Element::kind);
let unavailable = p.layer_of(owner) != Some(app.layer)
|| (app.behavior.scenario.pending_owner().is_some() && kind != Some(Kind::Scenario))
|| (app.behavior.topology.pending_owner().is_some()
&& !matches!(kind, Some(Kind::Process | Kind::FunctionalChain)));
if unavailable {
let mut out=column![text("The pending behavior owner is unavailable").size(20),text("Your inputs are retained. Return from the source form or cancel this parent draft before choosing another behavior.").size(13)].spacing(12);
if let Some(name) = app
.behavior
.scenario
.pending_name()
.or_else(|| app.behavior.topology.pending_name())
{
out =
out.push(text(format!("Pending consumer name: {}", short(name, 80))).size(14));
}
if let Some(child) = app.behavior.scenario.source_view(p) {
out = out.push(child.map(|e| Message::Behavior(Event::Scenario(e))));
} else if let Some(child) = app.behavior.topology.source_view(p) {
out = out.push(child.map(|e| Message::Behavior(Event::Topology(e))));
} else {
let cancel = if app.behavior.scenario.pending_owner().is_some() {
Event::Scenario(scenario::Event::Cancel)
} else if app.behavior.topology.pending_owner().is_some() {
Event::Topology(topology::Event::Cancel)
} else {
Event::States(states::Event::Cancel)
};
out = out.push(button("Cancel retained draft").on_press(Message::Behavior(cancel)));
}
return container(out).padding(16).width(Fill).height(Fill).into();
}
}
let choices = p
.elements
.values()
@@ -916,23 +994,40 @@ pub fn view(app: &App) -> Element<'_, Message> {
.cloned();
let mut out = column![heading("Behavior & scenarios", "Follow exchanges and operating conditions. Select a message, state or transition to edit it.")].spacing(14);
let Some(selected) = selected else {
return out.push(label("Start with a Process, Scenario or State machine using Create element. Add occurrences or regions inside it to describe behavior.")).padding(24).into();
return out
.push(label(
"Start a named process, scenario or state machine, then model its behavior here.",
))
.push(action(
"New",
Message::Behavior(Event::Creation(creation::Event::Open(app.layer))),
))
.padding(24)
.into();
};
let e = &p.elements[&selected.id];
let compact_process = matches!(e.kind(), Kind::Process | Kind::FunctionalChain);
let compact_canvas = matches!(
e.kind(),
Kind::Process | Kind::FunctionalChain | Kind::Scenario
);
if e.kind() == Kind::StateMachine {
out = column![text("States & modes").size(20)].spacing(8);
} else if compact_process {
// The process canvas owns its compact header and remaining-height layout.
} else if compact_canvas {
// The process/scenario canvas owns its compact remaining-height layout.
out = column![].spacing(6);
} else if matches!(e.kind(), Kind::Process | Kind::FunctionalChain) {
out = column![text("Processes & functional chains").size(20)].spacing(8);
}
out = out.push(
pick_list(choices, Some(selected), Message::BehaviorOwner)
.width(Fill)
.text_size(13)
.padding(if compact_process { 6 } else { 10 }),
row![
pick_list(choices, Some(selected), Message::BehaviorOwner)
.width(Fill)
.text_size(13)
.padding(if compact_canvas { 6 } else { 10 }),
action(
"New",
Message::Behavior(Event::Creation(creation::Event::Open(app.layer)))
)
]
.spacing(8),
);
if matches!(e.kind(), Kind::Process | Kind::FunctionalChain) {
return topology::view(app, e.id, out);
@@ -1047,6 +1142,7 @@ struct Scene {
selected: Id,
scale: f32,
scroll_offset: iced::Vector,
camera_pan: iced::Vector,
interaction: Option<(scenario::Context, scenario::CanvasTool, bool)>,
pending_placement: Option<(scenario::Slot, Option<Id>)>,
lanes: BTreeMap<Id, f32>,
@@ -1101,6 +1197,7 @@ impl Scene {
let mut scene = Self {
scale: 1.,
scroll_offset: iced::Vector::ZERO,
camera_pan: iced::Vector::ZERO,
boxes: vec![],
lines: vec![],
size: Size::new(700., 200.),
@@ -1763,9 +1860,12 @@ impl canvas::Program<Message> for Scene {
}
_ => cursor,
};
let world = cursor
.position_in(bounds)
.map(|p| Point::new(p.x / self.scale, p.y / self.scale));
let world = cursor.position_in(bounds).map(|p| {
Point::new(
(p.x - self.camera_pan.x) / self.scale,
(p.y - self.camera_pan.y) / self.scale,
)
});
match event {
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
if !visible {
@@ -1792,7 +1892,7 @@ impl canvas::Program<Message> for Scene {
return Some(Action::request_redraw().and_capture());
}
if let CanvasTool::Add(tool) = tool {
if !tool.canvas_occurrence() {
if !tool.canvas_occurrence() && tool != scenario::Tool::Lifeline {
return None;
}
state.press = Some(SequencePress::Occurrence {
@@ -1802,10 +1902,18 @@ impl canvas::Program<Message> for Scene {
});
return Some(Action::request_redraw().and_capture());
}
if self.reorder_handle().is_some_and(|r| r.contains(point)) {
if let Some(occurrence) = self
.hit(point)
.filter(|id| self.rows.contains_key(id))
.or_else(|| {
self.reorder_handle()
.filter(|r| r.contains(point))
.map(|_| self.selected)
})
{
state.press = Some(SequencePress::Reorder {
occurrence: self.selected,
parent: self.rows[&self.selected].0,
occurrence,
parent: self.rows[&occurrence].0,
start: cursor.position()? - self.scroll_offset,
moved: false,
});
@@ -1880,6 +1988,18 @@ impl canvas::Program<Message> for Scene {
);
}
}
SequencePress::Reorder {
occurrence,
moved: false,
..
} => {
return Some(
Action::publish(Message::ScenarioCanvas(CanvasEvent::Select(
context, occurrence,
)))
.and_capture(),
);
}
SequencePress::Reorder {
occurrence,
parent,
@@ -1917,6 +2037,7 @@ impl canvas::Program<Message> for Scene {
) -> Vec<canvas::Geometry> {
let mut f = Frame::new(renderer, bounds.size());
f.fill_rectangle(Point::ORIGIN, bounds.size(), Color::WHITE);
f.translate(self.camera_pan);
f.scale(self.scale);
for b in &self.boxes {
let outline = matches!(
@@ -2028,9 +2149,12 @@ impl canvas::Program<Message> for Scene {
}
if let Some((context, tool, editable)) = self.interaction {
let active = editable && state.context == Some(context) && state.tool == tool;
let point = cursor
.position_in(bounds)
.map(|p| Point::new(p.x / self.scale, p.y / self.scale));
let point = cursor.position_in(bounds).map(|p| {
Point::new(
(p.x - self.camera_pan.x) / self.scale,
(p.y - self.camera_pan.y) / self.scale,
)
});
let source = active.then_some(state.source).flatten();
let reorder = active.then_some(state.press).flatten().and_then(|press| {
if let SequencePress::Reorder { parent, .. } = press {
@@ -2075,6 +2199,18 @@ impl canvas::Program<Message> for Scene {
} else {
None
};
if reorder.is_some()
&& slot.is_none()
&& let Some(point) = point
{
f.fill_text(Text {
content: "Other operand: move stays in the current sequence".into(),
position: Point::new(point.x + 8., point.y + 12.),
size: (11. / self.scale).into(),
color: Color::from_rgb(0.75, 0.2, 0.15),
..Default::default()
});
}
if let Some(slot) = slot {
f.stroke(
&Path::line(
@@ -0,0 +1,243 @@
//! Shared presentation and input contract; contains no model commands.
use crate::app::{App, Message};
use iced::widget::{button, column, container, opaque, row, scrollable, stack, text, tooltip};
use iced::{Element, Length::Fill, Point, Theme, Vector};
use oa_core::Id;
mod control;
mod focus;
mod viewport;
pub use control::Control;
pub use viewport::Viewport;
pub fn keyboard_enabled(app: &crate::app::App) -> bool {
!app.busy
&& !app.hosted.visible
&& app.workflow.is_none()
&& app.file_prompt.is_none()
&& !app.delete_pending
&& app.pending.is_none()
&& app.model_menu.is_none()
&& !app.reference_input_active()
}
pub fn controls<'a>(
scope: Scope,
keyboard: bool,
scale: f32,
details: Message,
focus: Option<Message>,
zoom: impl Fn(Option<f32>) -> Message,
publish: impl Fn(Event) -> Message + Copy + 'a,
) -> Element<'a, Message> {
let control = |name: &'static str, label: &'static str, message: Option<Message>| {
let message = message.map(|message| intent(scope, name, message));
Control::new(
button(text(label).size(12))
.padding(6)
.on_press_maybe(message.clone()),
scope,
name,
keyboard,
message,
publish,
)
};
row![
control("Details", "Details", Some(details)),
tooltip(control("Canvas", "Canvas", focus),
container(text("F6: enter/leave canvas controls · Tab: next · Enter/Space: activate · Esc: leave").size(12)).padding(7).style(crate::style::card),
tooltip::Position::Bottom),
control("Fit", "Fit", Some(zoom(None))),
control("ZoomOut", "−", Some(zoom(Some(scale / 1.25)))),
text(format!("{:.0}%", scale * 100.)).size(12),
control("ZoomIn", "+", Some(zoom(Some(scale * 1.25)))),
control("ActualSize", "100%", Some(zoom(Some(1.)))),
].spacing(4).align_y(iced::Center).into()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scope {
pub document: Id,
pub owner: Id,
pub revision: u64,
pub epoch: u64,
}
impl Scope {
pub fn current(app: &App) -> Option<Self> {
if let Some(context) = app.scenario_context() {
Some(Self {
document: context.document,
owner: context.scenario,
revision: context.revision,
epoch: app.camera_epoch,
})
} else {
let context = app.topology_context()?;
Some(Self {
document: context.document,
owner: context.owner,
revision: context.revision,
epoch: app.camera_epoch,
})
}
}
pub fn input_owner(app: &App) -> Option<Self> {
if keyboard_enabled(app)
&& !app.behavior.has_pending()
&& !app.draft_dirty()
&& !app.source_dirty()
{
Self::current(app)
} else {
None
}
}
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
))
}
}
/// Only a live presentation intent may carry a toolbar action across its own pan.
#[derive(Debug, Clone)]
pub struct Intent {
pub scope: Scope,
pub name: &'static str,
pub message: Box<Message>,
}
pub fn intent(scope: Scope, name: &'static str, message: Message) -> Message {
Message::BehaviorControl(Intent {
scope,
name,
message: Box::new(message),
})
}
#[derive(Debug, Clone, Copy)]
pub enum Event {
CancelGesture,
Pan(Vector),
Zoom { factor: f32, at: Point, base: f32 },
Focus,
Traverse(bool),
ControlFocus(&'static str),
ToggleFocus,
Leave,
}
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 {
match event {
Event::Pan(delta) if delta.x.is_finite() && delta.y.is_finite() => {
let next = *pan + delta;
if next.x.is_finite() && next.y.is_finite() && next != *pan {
*pan = next;
true
} else {
false
}
}
Event::Zoom { factor, at, base }
if factor.is_finite()
&& factor > 0.
&& base.is_finite()
&& base > 0.
&& at.x.is_finite()
&& at.y.is_finite() =>
{
let old = if *fit { base } else { zoom.unwrap_or(base) };
let next = (old * factor).clamp(0.05, 3.);
if old == next {
return false;
}
let anchor = Vector::new(at.x, at.y);
let next_pan = anchor - (anchor - *pan) * (next / old);
if !next_pan.x.is_finite() || !next_pan.y.is_finite() {
return false;
}
*pan = next_pan;
*zoom = Some(next);
*fit = false;
true
}
_ => false,
}
}
/// Constant-width labelled palette. Arming a tool never reallocates the canvas.
pub fn palette<'a>(
scope: Scope,
keyboard: bool,
publish: impl Fn(Event) -> Message + Copy + 'a,
entries: impl IntoIterator<Item = (&'static str, &'static str, bool, Option<Message>)>,
) -> Element<'a, Message> {
let mut tools = column![].spacing(3);
for (glyph, label, selected, message) in entries {
let message = message.map(|message| intent(scope, glyph, message));
tools = tools.push(tooltip(
container(Control::new(
button(text(glyph).size(12))
.width(34)
.height(30)
.padding(3)
.style(if selected {
button::primary
} else {
crate::style::nav
})
.on_press_maybe(message.clone()),
scope,
glyph,
keyboard,
message,
publish,
))
.id(format!("behavior-tool:{glyph}")),
container(text(label).size(12))
.padding(7)
.style(crate::style::card),
tooltip::Position::Left,
));
}
container(scrollable(tools).id(scope.control_id("palette-scroll")))
.width(40)
.height(Fill)
.padding(3)
.style(crate::style::panel)
.into()
}
/// Header and palette are permanent. Details/editors overlay the same viewport.
pub fn host<'a, Message: 'a, R: iced::advanced::text::Renderer + 'a>(
header: Element<'a, Message, Theme, R>,
palette: Element<'a, Message, Theme, R>,
canvas: Element<'a, Message, Theme, R>,
editor: Option<Element<'a, Message, Theme, R>>,
) -> Element<'a, Message, Theme, R> {
let mut body = stack![canvas];
if let Some(editor) = editor {
body = body.push(
container(opaque(
container(editor)
.width(300)
.height(Fill)
.style(crate::style::card),
))
.align_right(Fill)
.height(Fill)
.padding(8),
);
}
column![header, row![body, palette].height(Fill)]
.spacing(6)
.padding(8)
.width(Fill)
.height(Fill)
.into()
}
#[cfg(test)]
pub(crate) mod tests;
@@ -0,0 +1,258 @@
//! A real focusable keyboard target around the existing styled pointer button.
use super::{Event as CameraEvent, Scope, focus::Member};
use iced::advanced::{
Clipboard, Layout, Shell, Widget, layout, overlay, renderer,
widget::{Operation, Tree, operation, tree},
};
use iced::{Border, Element, Event, Length, Rectangle, Size, Theme, Vector, keyboard, mouse};
#[derive(Default)]
struct Input {
identity: Option<iced::advanced::widget::Id>,
focused: bool,
}
impl operation::Focusable for Input {
fn is_focused(&self) -> bool {
self.focused
}
fn focus(&mut self) {
self.focused = true;
}
fn unfocus(&mut self) {
self.focused = false;
}
}
pub struct Control<'a, Message, R = iced::Renderer>
where
R: renderer::Renderer,
{
content: Element<'a, Message, Theme, R>,
scope: Scope,
name: &'static str,
enabled: bool,
activate: Option<Message>,
publish: Box<dyn Fn(CameraEvent) -> Message + 'a>,
}
impl<'a, Message, R: renderer::Renderer> Control<'a, Message, R> {
pub fn new(
content: impl Into<Element<'a, Message, Theme, R>>,
scope: Scope,
name: &'static str,
enabled: bool,
activate: Option<Message>,
publish: impl Fn(CameraEvent) -> Message + 'a,
) -> Self {
Self {
content: content.into(),
scope,
name,
enabled: enabled && activate.is_some(),
activate,
publish: Box::new(publish),
}
}
}
impl<Message: Clone, R: renderer::Renderer> Widget<Message, Theme, R> for Control<'_, Message, R> {
fn tag(&self) -> tree::Tag {
tree::Tag::of::<Input>()
}
fn state(&self) -> tree::State {
tree::State::new(Input {
identity: Some(self.scope.control_id(self.name)),
focused: false,
})
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(self.content.as_widget())]
}
fn diff(&self, tree: &mut Tree) {
let state = tree.state.downcast_mut::<Input>();
let identity = self.scope.control_id(self.name);
if state.identity.as_ref() != Some(&identity) || !self.enabled {
*state = Input {
identity: Some(identity),
focused: false,
};
}
tree.diff_children(std::slice::from_ref(&self.content));
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(&mut self, tree: &mut Tree, renderer: &R, limits: &layout::Limits) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
operation: &mut dyn Operation,
) {
let id = self.scope.control_id(self.name);
operation.container(Some(&id), layout.bounds());
if self.enabled {
operation.custom(Some(&id), layout.bounds(), &mut Member(self.scope));
operation.focusable(
Some(&id),
layout.bounds(),
tree.state.downcast_mut::<Input>(),
);
}
operation.traverse(&mut |operation| {
self.content.as_widget_mut().operate(
&mut tree.children[0],
layout,
renderer,
operation,
);
});
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
if shell.is_event_captured() {
return;
}
let state = tree.state.downcast_mut::<Input>();
if self.enabled {
if let Event::Keyboard(keyboard::Event::KeyPressed {
key,
modifiers,
repeat,
..
}) = event
&& state.focused
{
use keyboard::{Key, key::Named};
let action = match key.as_ref() {
Key::Named(Named::Tab) => {
Some((self.publish)(CameraEvent::Traverse(modifiers.shift())))
}
Key::Named(Named::Escape) => Some((self.publish)(CameraEvent::Leave)),
Key::Named(Named::F6) if modifiers.is_empty() && !repeat => {
Some((self.publish)(CameraEvent::ToggleFocus))
}
Key::Named(Named::Enter | Named::Space) if modifiers.is_empty() && !repeat => {
self.activate.clone()
}
_ => None,
};
if let Some(action) = action {
shell.publish(action);
shell.capture_event();
shell.request_redraw();
return;
}
}
if matches!(
event,
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
) {
if !layout
.bounds()
.intersection(viewport)
.is_some_and(|bounds| cursor.is_over(bounds))
{
state.focused = false;
}
}
}
if matches!(event, Event::Window(iced::window::Event::Unfocused)) {
state.focused = false;
}
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
fn draw(
&self,
tree: &Tree,
renderer: &mut R,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
if self.enabled && tree.state.downcast_ref::<Input>().focused {
renderer.fill_quad(
renderer::Quad {
bounds: layout.bounds(),
border: Border {
color: crate::style::INK,
width: 2.,
..Default::default()
},
..Default::default()
},
iced::Color::TRANSPARENT,
);
}
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &R,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn overlay<'a>(
&'a mut self,
tree: &'a mut Tree,
layout: Layout<'a>,
renderer: &R,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'a, Message, Theme, R>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
impl<'a, Message: Clone + 'a, R: renderer::Renderer + 'a> From<Control<'a, Message, R>>
for Element<'a, Message, Theme, R>
{
fn from(control: Control<'a, Message, R>) -> Self {
Element::new(control)
}
}
@@ -0,0 +1,293 @@
//! Explicit canvas entry; ordinary initial Tab continues to belong to Inspector.
use super::{Event, Scope};
use iced::advanced::widget::{Id, Operation, Tree, operation};
use iced::advanced::{Clipboard, Layout, Shell, Widget, layout, overlay, renderer};
use iced::{Element, Event as InputEvent, Length, Rectangle, Size, Theme, Vector, mouse};
pub(super) struct Member(pub Scope);
pub fn focus_task<Message: Send + 'static>(scope: Scope, event: Event) -> iced::Task<Message> {
iced::advanced::widget::operate(Collect {
scope,
valid: false,
event,
members: vec![],
focused: None,
palette: None,
})
}
struct Collect {
scope: Scope,
valid: bool,
event: Event,
members: Vec<(Id, Rectangle)>,
focused: Option<usize>,
palette: Option<(Rectangle, Rectangle)>,
}
impl<T: Send + 'static> Operation<T> for Collect {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation<T>)) {
visit(self);
}
fn custom(&mut self, id: Option<&Id>, bounds: Rectangle, value: &mut dyn std::any::Any) {
if let Some(owner) = value.downcast_ref::<Owner>() {
self.valid = owner.0 == Some(self.scope);
}
if self.valid
&& value
.downcast_ref::<Member>()
.is_some_and(|m| m.0 == self.scope)
&& let Some(id) = id
{
self.members.push((id.clone(), bounds));
}
}
fn focusable(&mut self, id: Option<&Id>, _: Rectangle, value: &mut dyn operation::Focusable) {
if value.is_focused() {
self.focused = self
.members
.iter()
.position(|(member, _)| Some(member) == id)
.or(self.focused);
}
}
fn scrollable(
&mut self,
id: Option<&Id>,
bounds: Rectangle,
content: Rectangle,
_: Vector,
_: &mut dyn operation::Scrollable,
) {
if id == Some(&self.scope.control_id("palette-scroll")) {
self.palette = Some((bounds, content));
}
}
fn finish(&self) -> operation::Outcome<T> {
let canvas = self.scope.control_id("viewport");
// An enabled viewport witnesses the live lifetime. Hidden/dirty/modal
// owners expose no members; a delayed request cannot clear their focus.
if !self.valid || !self.members.iter().any(|(id, _)| *id == canvas) {
return operation::Outcome::None;
}
let target = match self.event {
Event::Focus => Some(canvas),
Event::ControlFocus(name) => Some(self.scope.control_id(name)),
Event::ToggleFocus if self.focused.is_none() => Some(canvas),
Event::ToggleFocus | Event::Leave if self.focused.is_some() => None,
Event::Traverse(back) => {
let Some(current) = self.focused else {
return operation::Outcome::None;
};
let next = if back {
(current + self.members.len() - 1) % self.members.len()
} else {
(current + 1) % self.members.len()
};
Some(self.members[next].0.clone())
}
_ => return operation::Outcome::None,
};
if target
.as_ref()
.is_some_and(|target| !self.members.iter().any(|(id, _)| id == target))
{
return operation::Outcome::None;
}
let reveal = target.as_ref().and_then(|target| {
let (_, field) = self.members.iter().find(|(id, _)| id == target)?;
let (bounds, content) = self.palette?;
// Only the palette has member controls inside this scrollable.
(field.x >= bounds.x && field.x < bounds.x + bounds.width).then(|| {
(field.center_y() - bounds.y - bounds.height / 2.)
.clamp(0., (content.height - bounds.height).max(0.))
})
});
operation::Outcome::Chain(Box::new(Apply {
scope: self.scope,
valid: false,
target,
members: self.members.iter().map(|(id, _)| id.clone()).collect(),
palette: self.scope.control_id("palette-scroll"),
reveal,
}))
}
}
struct Apply {
scope: Scope,
valid: bool,
target: Option<Id>,
members: Vec<Id>,
palette: Id,
reveal: Option<f32>,
}
impl<T> Operation<T> for Apply {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation<T>)) {
visit(self);
}
fn custom(&mut self, _: Option<&Id>, _: Rectangle, value: &mut dyn std::any::Any) {
if let Some(owner) = value.downcast_ref::<Owner>() {
self.valid = owner.0 == Some(self.scope);
}
}
fn focusable(&mut self, id: Option<&Id>, _: Rectangle, state: &mut dyn operation::Focusable) {
if !self.valid {
return;
}
if self
.target
.as_ref()
.is_some_and(|target| Some(target) == id)
{
state.focus();
} else if self.target.is_some() || id.is_some_and(|id| self.members.contains(id)) {
state.unfocus();
}
}
fn scrollable(
&mut self,
id: Option<&Id>,
_: Rectangle,
_: Rectangle,
_: Vector,
state: &mut dyn operation::Scrollable,
) {
if self.valid
&& id == Some(&self.palette)
&& let Some(y) = self.reveal
{
state.scroll_to(operation::scrollable::AbsoluteOffset {
x: None,
y: Some(y),
});
}
}
}
// Every Collect/Apply pass observes current ownership before touching any field.
struct Owner(Option<Scope>);
struct Root<'a, Message, R: renderer::Renderer> {
owner: Option<Scope>,
content: Element<'a, Message, Theme, R>,
}
pub fn root<'a, Message: 'a, R: renderer::Renderer + 'a>(
content: impl Into<Element<'a, Message, Theme, R>>,
owner: Option<Scope>,
) -> Element<'a, Message, Theme, R> {
Element::new(Root {
owner,
content: content.into(),
})
}
impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Root<'_, Message, R> {
fn children(&self) -> Vec<Tree> {
vec![Tree::new(self.content.as_widget())]
}
fn diff(&self, tree: &mut Tree) {
tree.diff_children(std::slice::from_ref(&self.content));
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(&mut self, tree: &mut Tree, renderer: &R, limits: &layout::Limits) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
operation: &mut dyn Operation,
) {
operation.custom(None, layout.bounds(), &mut Owner(self.owner));
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &InputEvent,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
fn draw(
&self,
tree: &Tree,
renderer: &mut R,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &R,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'b>,
renderer: &R,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, R>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
@@ -0,0 +1,753 @@
use super::*;
use crate::app::{App, Message};
use iced::advanced::{Layout, Shell, layout, widget};
use iced::futures::{
StreamExt,
stream::{BoxStream, SelectAll},
};
use iced::{Rectangle, Size, mouse};
use iced_runtime::{
Action,
user_interface::{Cache, UserInterface},
};
use std::collections::HashMap;
type Pending = SelectAll<BoxStream<'static, Action<Message>>>;
// iced_winit drains messages while collecting immediately ready actions. A
// pending Task stream survives until its widget operation sends its result.
fn enqueue(task: iced::Task<Message>, ready: &mut Vec<Action<Message>>, pending: &mut Pending) {
if let Some(mut stream) = iced_runtime::task::into_stream(task) {
let waker = iced::futures::task::noop_waker();
let mut context = std::task::Context::from_waker(&waker);
loop {
match stream.poll_next_unpin(&mut context) {
std::task::Poll::Ready(Some(action)) => ready.push(action),
std::task::Poll::Ready(None) => break,
std::task::Poll::Pending => {
pending.push(stream);
break;
}
}
}
}
}
#[derive(Default)]
pub(crate) struct Geometry {
pub containers: HashMap<widget::Id, Rectangle>,
pub focused: Vec<(Option<widget::Id>, Rectangle, bool)>,
pub text_inputs: Vec<Rectangle>,
pub scrolls: HashMap<widget::Id, (Rectangle, Vector)>,
}
impl widget::Operation for Geometry {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn widget::Operation)) {
visit(self);
}
fn focusable(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
state: &mut dyn widget::operation::Focusable,
) {
self.focused.push((id.cloned(), bounds, state.is_focused()));
}
fn text_input(
&mut self,
_: Option<&widget::Id>,
bounds: Rectangle,
_: &mut dyn widget::operation::TextInput,
) {
self.text_inputs.push(bounds);
}
fn container(&mut self, id: Option<&widget::Id>, bounds: Rectangle) {
if let Some(id) = id {
self.containers.insert(id.clone(), bounds);
}
}
fn scrollable(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
_: Rectangle,
offset: Vector,
_: &mut dyn widget::operation::Scrollable,
) {
if let Some(id) = id {
self.scrolls.insert(id.clone(), (bounds, offset));
}
}
}
impl Geometry {
pub fn bounds(&self, id: &str) -> Rectangle {
self.containers[&widget::Id::from(id.to_owned())]
}
}
/// Mount the actual App root, production widgets and renderer. Events are
/// delivered in order with Iced's final-batch cursor, then fed through App::update.
/// This deliberately does not seed any private canvas gesture state.
pub(crate) struct Mounted {
pub renderer: iced::Renderer,
cache: Cache,
pub operations: usize,
}
impl Mounted {
pub async fn new(app: &mut App) -> Self {
use iced::advanced::renderer::Headless;
let renderer = <iced::Renderer as Headless>::new(iced::Font::DEFAULT, 16.into(), None)
.await
.expect("production mounted tests require the supported WGPU headless renderer");
let mut mounted = Self {
renderer,
cache: Cache::new(),
operations: 0,
};
mounted.settle(app).await;
mounted
}
pub fn geometry(&mut self, app: &App) -> Geometry {
let mut geometry = Geometry::default();
self.operate(app, &mut geometry);
geometry
}
/// One operation pass, including every nested overlay, via installed Iced.
pub fn operate(&mut self, app: &App, operation: &mut dyn widget::Operation) {
let mut ui = UserInterface::build(
app.view(),
app.window_size,
std::mem::take(&mut self.cache),
&mut self.renderer,
);
ui.operate(&self.renderer, operation);
self.cache = ui.into_cache();
}
pub async fn settle(&mut self, app: &mut App) {
for _ in 0..3 {
self.batch(
app,
&[iced::Event::Window(iced::window::Event::RedrawRequested(
std::time::Instant::now(),
))],
mouse::Cursor::Unavailable,
)
.await;
}
}
pub async fn batch(
&mut self,
app: &mut App,
events: &[iced::Event],
cursor: mouse::Cursor,
) -> Vec<Message> {
let messages = self.input(app, events, cursor);
let mut ready = vec![];
let mut pending = Pending::new();
for message in messages.iter().cloned() {
enqueue(app.update(message), &mut ready, &mut pending);
}
self.drain(app, ready, pending).await;
messages
}
pub fn input(
&mut self,
app: &App,
events: &[iced::Event],
cursor: mouse::Cursor,
) -> Vec<Message> {
let mut messages = vec![];
let mut ui = UserInterface::build(
app.view(),
app.window_size,
std::mem::take(&mut self.cache),
&mut self.renderer,
);
let _ = ui.update(
events,
cursor,
&mut self.renderer,
&mut iced::advanced::clipboard::Null,
&mut messages,
);
self.cache = ui.into_cache();
messages
}
pub async fn perform(&mut self, app: &mut App, task: iced::Task<Message>) {
let mut ready = vec![];
let mut pending = Pending::new();
enqueue(task, &mut ready, &mut pending);
self.drain(app, ready, pending).await;
}
async fn drain(
&mut self,
app: &mut App,
mut ready: Vec<Action<Message>>,
mut pending: Pending,
) {
loop {
let mut outputs = vec![];
if !ready.is_empty() {
// Build only after all App messages in this cycle have run.
let mut ui = UserInterface::build(
app.view(),
app.window_size,
std::mem::take(&mut self.cache),
&mut self.renderer,
);
for action in ready.drain(..) {
match action {
Action::Output(message) => outputs.push(message),
Action::Widget(mut operation) => {
self.operations += 1;
loop {
ui.operate(&self.renderer, &mut *operation);
match operation.finish() {
widget::operation::Outcome::Chain(next) => operation = next,
widget::operation::Outcome::None
| widget::operation::Outcome::Some(()) => break,
}
}
}
action => {
panic!("Unexpected native action in mounted App harness: {action:?}")
}
}
}
self.cache = ui.into_cache();
}
for message in outputs {
enqueue(app.update(message), &mut ready, &mut pending);
}
if !ready.is_empty() {
continue;
}
let Some(action) = pending.next().await else {
break;
};
ready.push(action);
let waker = iced::futures::task::noop_waker();
let mut context = std::task::Context::from_waker(&waker);
while let std::task::Poll::Ready(Some(action)) = pending.poll_next_unpin(&mut context) {
ready.push(action);
}
}
}
pub fn pixels(&mut self, app: &App) -> Vec<u8> {
use iced::advanced::renderer::Headless;
let mut ui = UserInterface::build(
app.view(),
app.window_size,
std::mem::take(&mut self.cache),
&mut self.renderer,
);
// update initializes the nested overlay layout used by draw.
let mut messages = vec![];
let _ = ui.update(
&[],
mouse::Cursor::Unavailable,
&mut self.renderer,
&mut iced::advanced::clipboard::Null,
&mut messages,
);
assert!(
messages.is_empty(),
"An empty draw preparation must not drop App messages"
);
ui.draw(
&mut self.renderer,
&crate::style::theme(),
&iced::advanced::renderer::Style {
text_color: crate::style::INK,
},
mouse::Cursor::Unavailable,
);
self.cache = ui.into_cache();
self.renderer.screenshot(
Size::new(app.window_size.width as u32, app.window_size.height as u32),
1.,
crate::style::BG,
)
}
pub async fn click(&mut self, app: &mut App, point: Point) -> Vec<Message> {
self.batch(
app,
&[
iced::Event::Mouse(mouse::Event::CursorMoved { position: point }),
iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
iced::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
],
mouse::Cursor::Available(point),
)
.await
}
pub async fn pan(&mut self, app: &mut App, start: Point, end: Point) -> Vec<Message> {
self.batch(
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: end }),
iced::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Middle)),
],
mouse::Cursor::Available(end),
)
.await
}
pub fn scroll(&mut self, app: &App, id: &str, offset: f32) {
let mut operation = widget::operation::scrollable::scroll_to::<()>(
widget::Id::from(id.to_owned()),
widget::operation::scrollable::AbsoluteOffset {
x: None,
y: Some(offset),
},
);
self.operate(app, &mut operation);
}
}
pub(crate) fn key(named: iced::keyboard::key::Named) -> iced::Event {
use iced::keyboard::{self, Key};
iced::Event::Keyboard(keyboard::Event::KeyPressed {
key: Key::Named(named),
modified_key: Key::Named(named),
physical_key: keyboard::key::Physical::Unidentified(
keyboard::key::NativeCode::Unidentified,
),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::empty(),
text: None,
repeat: false,
})
}
#[test]
fn relative_camera_zoom_keeps_the_cursor_world_point_and_rejects_nonfinite_inputs() {
for scale in [0.05, 0.5, 1., 2.] {
let mut pan = Vector::new(-130., 75.);
let mut zoom = Some(scale);
let mut fit = false;
let at = Point::new(171., 93.);
let world = (at - Point::ORIGIN - pan) / scale;
change(
&mut pan,
&mut zoom,
&mut fit,
Event::Zoom {
factor: 1.25,
at,
base: scale,
},
);
let after = (at - Point::ORIGIN - pan) / zoom.unwrap();
assert!((after.x - world.x).abs() < 0.001 && (after.y - world.y).abs() < 0.001);
let before = (pan, zoom, fit);
for input in [
Event::Pan(Vector::new(f32::INFINITY, 0.)),
Event::Zoom {
factor: f32::NAN,
at,
base: scale,
},
Event::Zoom {
factor: 0.,
at,
base: scale,
},
] {
assert!(!change(&mut pan, &mut zoom, &mut fit, input));
assert_eq!((pan, zoom, fit), before);
}
}
}
#[test]
fn viewport_ordered_batch_uses_each_event_position_and_cancels_before_camera_motion() {
use iced::widget::Space;
let scope = Scope {
document: Id::new_v4(),
owner: Id::new_v4(),
revision: 2,
epoch: 0,
};
let mut view: Element<'_, Event, Theme, ()> = Viewport::new(
Space::new().width(Fill).height(Fill),
scope,
1.,
true,
|e| e,
)
.into();
let mut tree = widget::Tree::new(view.as_widget());
let node = view
.as_widget_mut()
.layout(
&mut tree,
&(),
&layout::Limits::new(Size::ZERO, Size::new(400., 300.)),
)
.move_to(Point::new(30., 80.));
let start = Point::new(90., 160.);
let middle = Point::new(125., 175.);
let end = Point::new(145., 185.);
let mut messages = vec![];
for event in [
mouse::Event::CursorMoved { position: start },
mouse::Event::ButtonPressed(mouse::Button::Middle),
mouse::Event::CursorMoved { position: middle },
mouse::Event::CursorMoved { position: end },
mouse::Event::ButtonReleased(mouse::Button::Middle),
] {
view.as_widget_mut().update(
&mut tree,
&iced::Event::Mouse(event),
Layout::new(&node),
mouse::Cursor::Available(end),
&(),
&mut iced::advanced::clipboard::Null,
&mut Shell::new(&mut messages),
&Rectangle::with_size(Size::new(700., 600.)),
);
}
assert!(matches!(messages.first(), Some(Event::CancelGesture)));
let total = messages
.iter()
.fold(Vector::ZERO, |total, event| match event {
Event::Pan(delta) => total + *delta,
_ => total,
});
assert_eq!(total, end - start);
}
pub(crate) fn scope(app: &App) -> Scope {
if let Some(context) = app.scenario_context() {
Scope {
document: context.document,
owner: context.scenario,
revision: context.revision,
epoch: app.camera_epoch,
}
} else {
let context = app.topology_context().expect("mounted behavior owner");
Scope {
document: context.document,
owner: context.owner,
revision: context.revision,
epoch: app.camera_epoch,
}
}
}
pub(crate) fn focused(mounted: &mut Mounted, app: &App, name: &str) -> bool {
let id = scope(app).control_id(name);
mounted
.geometry(app)
.focused
.iter()
.any(|(member, _, focused)| member.as_ref() == Some(&id) && *focused)
}
pub(crate) async fn tab_to(mounted: &mut Mounted, app: &mut App, name: &str) {
for _ in 0..32 {
if focused(mounted, app, name) {
return;
}
mounted
.batch(
app,
&[key(iced::keyboard::key::Named::Tab)],
mouse::Cursor::Unavailable,
)
.await;
}
panic!("Keyboard traversal did not reach {name}");
}
pub(crate) fn camera_delta(messages: &[Message]) -> Message {
messages.iter().find(|m| matches!(m,
Message::ScenarioCanvas(crate::behavior::scenario::CanvasEvent::Camera(_, _, Event::Pan(delta)))
| Message::TopologyCanvas(crate::behavior::topology::CanvasEvent::Camera(_, _, Event::Pan(delta))) if *delta != Vector::ZERO
)).expect("actual nonzero camera delta from a mounted gesture").clone()
}
pub(crate) async fn press_middle(mounted: &mut Mounted, app: &mut App, point: Point) {
mounted
.batch(
app,
&[
iced::Event::Mouse(mouse::Event::CursorMoved { position: point }),
iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)),
],
mouse::Cursor::Available(point),
)
.await;
}
pub(crate) async fn release_middle(
mounted: &mut Mounted,
app: &mut App,
point: Point,
) -> Vec<Message> {
mounted
.batch(
app,
&[
iced::Event::Mouse(mouse::Event::CursorMoved { position: point }),
iced::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Middle)),
],
mouse::Cursor::Available(point),
)
.await
}
pub(crate) fn assert_drawn_focus(before: &[u8], after: &[u8], size: Size, bounds: Rectangle) {
let width = size.width as usize;
assert_eq!(before.len(), width * size.height as usize * 4);
assert_eq!(after.len(), before.len());
let mut changed = 0;
for y in bounds.y.ceil() as usize..(bounds.y + bounds.height).floor() as usize {
for x in bounds.x.ceil() as usize..(bounds.x + bounds.width).floor() as usize {
if x as f32 - bounds.x > 2.
&& bounds.x + bounds.width - x as f32 > 2.
&& y as f32 - bounds.y > 2.
&& bounds.y + bounds.height - y as f32 > 2.
{
continue;
}
let start = (y * width + x) * 4;
if before[start..start + 3] != after[start..start + 3] {
changed += 1;
}
}
}
assert!(
changed >= bounds.width.min(bounds.height) as usize,
"Focus must change visible border pixels, changed={changed}, bounds={bounds:?}"
);
}
pub(crate) fn character(value: &str) -> iced::Event {
let mut event = key(iced::keyboard::key::Named::Space);
if let iced::Event::Keyboard(iced::keyboard::Event::KeyPressed {
key,
modified_key,
text,
..
}) = &mut event
{
*key = iced::keyboard::Key::Character(value.into());
*modified_key = key.clone();
*text = Some(value.into());
}
event
}
/// Inspect the action without stripping the lifetime from retained packets.
pub(crate) fn intent_action(message: &Message) -> &Message {
match message {
Message::BehaviorControl(intent) => &intent.message,
message => message,
}
}
/// Deliberately retain a returned Chain to test the stronger ownership invariant.
/// Native Iced runs Chain passes synchronously; this is not a native interleaving.
pub(crate) async fn retained_focus_apply(
mounted: &mut Mounted,
app: &mut App,
) -> Box<dyn widget::Operation> {
let entry = mounted.input(
app,
&[key(iced::keyboard::key::Named::F6)],
mouse::Cursor::Unavailable,
);
assert_eq!(
entry.len(),
1,
"actual initial F6 must emit one canvas focus request"
);
let mut stream = iced_runtime::task::into_stream(app.update(entry[0].clone()))
.expect("F6 returns a widget Task");
let Some(Action::Widget(mut operation)) = stream.next().await else {
panic!("F6 first action must be Collect");
};
mounted.operate(app, &mut *operation);
match operation.finish() {
widget::operation::Outcome::Chain(apply) => apply,
_ => panic!("Live Collect must produce its guarded Apply pass"),
}
}
pub(crate) async fn overflow_last_tool(mounted: &mut Mounted, app: &mut App, last: &'static str) {
use iced::keyboard::key::Named;
let geometry = mounted.geometry(app);
let last_bounds = geometry.containers[&scope(app).control_id(last)];
let (rail, offset) = geometry.scrolls[&scope(app).control_id("palette-scroll")];
assert_eq!(offset.y, 0.);
assert!(
last_bounds.y >= rail.y + rail.height,
"last tool starts fully below the overflowing palette: tool={last_bounds:?}, rail={rail:?}"
);
mounted
.batch(app, &[key(Named::F6)], mouse::Cursor::Unavailable)
.await;
tab_to(mounted, app, last).await;
let geometry = mounted.geometry(app);
let mut visible = geometry.containers[&scope(app).control_id(last)];
let (rail, offset) = geometry.scrolls[&scope(app).control_id("palette-scroll")];
assert!(offset.y > 0., "keyboard traversal must scroll the palette");
visible.x -= offset.x;
visible.y -= offset.y;
assert!(
visible.y >= rail.y && visible.y + visible.height <= rail.y + rail.height + 0.5,
"the entire last tool is revealed: tool={visible:?}, rail={rail:?}"
);
let messages = mounted
.batch(app, &[key(Named::Enter)], mouse::Cursor::Unavailable)
.await;
assert!(
messages.iter().any(
|message| matches!(message, Message::BehaviorControl(intent) if intent.name == last)
),
"the revealed last tool is keyboard activated"
);
assert!(focused(mounted, app, last));
let on = mounted.pixels(app);
mounted
.batch(app, &[key(Named::Escape)], mouse::Cursor::Unavailable)
.await;
let off = mounted.pixels(app);
assert_drawn_focus(&off, &on, app.window_size, visible);
}
pub(crate) async fn retained_toolbar_boundaries(
mounted: &mut Mounted,
app: &mut App,
tool: &'static str,
) {
use iced::keyboard::key::Named;
for boundary in ["Chooser", "Dirty", "Picker"] {
let mut packets = vec![];
for name in ["Fit", tool, "Details", "Panels", "Canvas"] {
packets.push(capture_toolbar(mounted, app, name));
}
let lifetime = app.camera_epoch;
let epoch = app.canvas_epoch;
let process = app.behavior.topology.camera_boundary();
let scenario = app.behavior.scenario.camera_boundary();
match boundary {
"Chooser" => {
let draft = app.draft.as_ref().unwrap();
let id = crate::forms::reference_chooser::trigger::field_id(
draft.reference_generation(),
"/parent",
);
let bounds = mounted
.geometry(app)
.focused
.iter()
.find(|(field, _, _)| field.as_ref() == Some(&id))
.expect("real Inspector parent reference trigger")
.1;
let request = draft.reference_open(app.project(), "/parent", bounds);
let task = app.update(Message::FieldReferenceOpen(request));
mounted.perform(app, task).await;
assert!(app.reference_input_active());
mounted
.batch(app, &[key(Named::Escape)], mouse::Cursor::Unavailable)
.await;
assert!(!app.reference_input_active());
}
"Dirty" => {
let task = app.update(Message::Field(
"/name".into(),
"Unsaved camera boundary".into(),
));
mounted.perform(app, task).await;
assert!(app.draft_dirty());
// Every retained packet is also rejected while the owner is dirty.
for packet in packets.iter().cloned() {
let task = app.update(packet);
mounted.perform(app, task).await;
}
assert!(app.draft_dirty());
let task = app.update(Message::RevertProperties);
mounted.perform(app, task).await;
assert!(!app.draft_dirty());
}
"Picker" => {
// Public transitions, with cancellation injected at the external
// picker boundary. Never poll the native dialog future here.
let picker = app.update(Message::Save(true));
if cfg!(target_os = "linux") {
assert!(app.file_prompt.is_some());
mounted.perform(app, picker).await;
let task = app.update(Message::CancelFile);
mounted.perform(app, task).await;
} else {
assert!(app.busy, "Save As enters the real native-picker busy state");
drop(picker);
for packet in packets.iter().cloned() {
let task = app.update(packet);
mounted.perform(app, task).await;
}
let task = app.update(Message::SavePath(None));
mounted.perform(app, task).await;
assert!(!app.busy);
}
}
_ => unreachable!(),
}
assert_ne!(
app.camera_epoch, lifetime,
"{boundary} changes the presentation lifetime"
);
assert_eq!(
app.canvas_epoch, epoch,
"{boundary} cycle leaves semantic context unchanged"
);
let focus_before = mounted
.geometry(app)
.focused
.into_iter()
.filter(|(_, _, value)| *value)
.collect::<Vec<_>>();
let current_lifetime = app.camera_epoch;
for packet in packets {
let task = app.update(packet);
mounted.perform(app, task).await;
}
assert_eq!(
app.camera_epoch, current_lifetime,
"{boundary} retained intents cannot start a new lifetime"
);
assert!(
app.behavior.topology.camera_boundary() == process,
"{boundary} retained toolbar packet changed process presentation"
);
assert!(
app.behavior.scenario.camera_boundary() == scenario,
"{boundary} retained toolbar packet changed scenario presentation"
);
assert_eq!(
mounted
.geometry(app)
.focused
.into_iter()
.filter(|(_, _, value)| *value)
.collect::<Vec<_>>(),
focus_before,
"{boundary} retained toolbar packet stole field focus"
);
}
}
pub(crate) fn capture_toolbar(mounted: &mut Mounted, app: &App, name: &'static str) -> Message {
let point = mounted.geometry(app).containers[&scope(app).control_id(name)].center();
mounted
.input(
app,
&[
iced::Event::Mouse(mouse::Event::CursorMoved { position: point }),
iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
iced::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
],
mouse::Cursor::Available(point),
)
.into_iter()
.find(|message| matches!(message, Message::BehaviorControl(intent) if intent.name == name))
.expect("actual production toolbar packet")
}
@@ -0,0 +1,426 @@
use super::{Event as CameraEvent, Scope};
use iced::advanced::{
Clipboard, Layout, Shell, Widget, layout, overlay, renderer,
widget::{Operation, Tree, operation, tree},
};
use iced::{Border, Element, Event, Length, Point, Rectangle, Size, Theme, Vector};
use iced::{keyboard, mouse};
#[derive(Default)]
struct Input {
scope: Option<Scope>,
focused: bool,
pointer: Option<Point>,
pan: Option<(mouse::Button, Point)>,
space: bool,
bounds: Option<Rectangle>,
}
impl operation::Focusable for Input {
fn is_focused(&self) -> bool {
self.focused
}
fn focus(&mut self) {
self.focused = true;
}
fn unfocus(&mut self) {
self.focused = false;
self.pan = None;
self.space = false;
}
}
pub struct Viewport<'a, Message, R = iced::Renderer>
where
R: renderer::Renderer,
{
content: Element<'a, Message, Theme, R>,
scope: Scope,
scale: f32,
keyboard: bool,
blank_pan: bool,
publish: Box<dyn Fn(CameraEvent) -> Message + 'a>,
}
impl<'a, Message, R: renderer::Renderer> Viewport<'a, Message, R> {
pub fn new(
content: impl Into<Element<'a, Message, Theme, R>>,
scope: Scope,
scale: f32,
keyboard: bool,
publish: impl Fn(CameraEvent) -> Message + 'a,
) -> Self {
Self {
content: content.into(),
scope,
scale,
keyboard,
blank_pan: false,
publish: Box::new(publish),
}
}
pub fn pan_background(mut self, enabled: bool) -> Self {
self.blank_pan = enabled;
self
}
}
impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Viewport<'_, Message, R> {
fn tag(&self) -> tree::Tag {
tree::Tag::of::<Input>()
}
fn state(&self) -> tree::State {
tree::State::new(Input {
scope: Some(self.scope),
..Default::default()
})
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(self.content.as_widget())]
}
fn diff(&self, tree: &mut Tree) {
let state = tree.state.downcast_mut::<Input>();
if state.scope.is_none_or(|s| {
(s.document, s.owner, s.revision)
!= (self.scope.document, self.scope.owner, self.scope.revision)
}) {
*state = Input::default();
}
if state
.scope
.is_some_and(|scope| scope.epoch != self.scope.epoch)
|| !self.keyboard
{
state.pan = None;
state.space = false;
}
if !self.keyboard {
state.focused = false;
}
state.scope = Some(self.scope);
tree.diff_children(std::slice::from_ref(&self.content));
}
fn size(&self) -> Size<Length> {
Size::new(Length::Fill, Length::Fill)
}
fn layout(&mut self, tree: &mut Tree, renderer: &R, limits: &layout::Limits) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
operation: &mut dyn Operation,
) {
if self.keyboard {
let id = self.scope.control_id("viewport");
operation.custom(
Some(&id),
layout.bounds(),
&mut super::focus::Member(self.scope),
);
operation.focusable(
Some(&id),
layout.bounds(),
tree.state.downcast_mut::<Input>(),
);
}
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
if shell.is_event_captured() {
return;
}
let state = tree.state.downcast_mut::<Input>();
let changed_bounds = state.bounds.is_some_and(|bounds| bounds != layout.bounds());
state.bounds = Some(layout.bounds());
if changed_bounds || !self.keyboard {
state.pan = None;
state.space = false;
}
if !self.keyboard {
state.focused = false;
}
if let Event::Mouse(mouse::Event::CursorMoved { position }) = event {
state.pointer = Some(*position);
}
let pointer = match event {
Event::Mouse(
mouse::Event::ButtonPressed(_)
| mouse::Event::ButtonReleased(_)
| mouse::Event::WheelScrolled { .. },
) => state.pointer.or_else(|| cursor.position()),
Event::Mouse(mouse::Event::CursorMoved { position }) => Some(*position),
_ => cursor.position().or(state.pointer),
};
let visible = layout.bounds().intersection(viewport);
let inside = pointer.is_some_and(|p| visible.is_some_and(|v| v.contains(p)))
&& cursor.position().is_some();
if !self.keyboard {
state.space = false;
}
let mut cancel = changed_bounds;
let mut camera = None;
let mut capture = false;
match event {
Event::Window(iced::window::Event::Unfocused | iced::window::Event::Resized(_)) => {
state.pan = None;
state.space = false;
state.focused = false;
}
Event::Mouse(mouse::Event::CursorLeft) => {
state.pan = None;
state.pointer = None;
}
Event::Mouse(mouse::Event::ButtonPressed(button)) => {
if state.pan.is_some_and(|(held, _)| held != *button) || !inside {
state.pan = None;
state.space = false;
cancel = true;
}
state.focused = inside && self.keyboard;
if inside
&& self.keyboard
&& (*button == mouse::Button::Middle
|| (*button == mouse::Button::Left && state.space))
{
state.pan = pointer.map(|p| (*button, p));
cancel = true;
camera = Some(CameraEvent::CancelGesture);
capture = true;
}
}
Event::Mouse(mouse::Event::CursorMoved { position }) => {
if let Some((button, previous)) = state.pan {
state.pan = Some((button, *position));
camera = Some(CameraEvent::Pan(*position - previous));
capture = true;
}
}
Event::Mouse(mouse::Event::ButtonReleased(button)) => {
if let Some((held, previous)) = state.pan
&& held == *button
{
state.pan = None;
camera = pointer
.filter(|_| inside)
.map(|p| CameraEvent::Pan(p - previous));
capture = true;
}
}
Event::Mouse(mouse::Event::WheelScrolled { delta }) if inside && state.focused => {
state.pan = None;
cancel = true;
let y = match delta {
mouse::ScrollDelta::Lines { y, .. } => *y,
mouse::ScrollDelta::Pixels { y, .. } => *y / 40.,
};
if y != 0. {
let at = pointer.unwrap() - Vector::new(layout.bounds().x, layout.bounds().y);
camera = Some(CameraEvent::Zoom {
factor: 1.1_f32.powf(y.clamp(-8., 8.)),
at,
base: self.scale,
});
capture = true;
}
}
Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(keyboard::key::Named::F6),
modifiers,
repeat: false,
..
}) if self.keyboard && modifiers.is_empty() => {
camera = Some(CameraEvent::ToggleFocus);
capture = true;
cancel = true;
}
Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. })
if state.focused && self.keyboard =>
{
use keyboard::{Key, key::Named};
match key.as_ref() {
Key::Named(Named::Space) => {
state.space = true;
cancel = true;
camera = Some(CameraEvent::CancelGesture);
capture = true;
}
Key::Named(Named::Tab) => {
camera = Some(CameraEvent::Traverse(modifiers.shift()));
capture = true;
}
Key::Named(Named::Escape) => {
state.pan = None;
state.space = false;
camera = Some(CameraEvent::Leave);
capture = true;
}
Key::Named(key) if modifiers.is_empty() => {
let delta = match key {
Named::ArrowLeft => Some(Vector::new(60., 0.)),
Named::ArrowRight => Some(Vector::new(-60., 0.)),
Named::ArrowUp => Some(Vector::new(0., 60.)),
Named::ArrowDown => Some(Vector::new(0., -60.)),
_ => None,
};
camera = delta.map(CameraEvent::Pan);
capture = camera.is_some();
cancel = capture;
}
_ => {}
}
}
Event::Keyboard(keyboard::Event::KeyReleased { key, .. })
if *key == keyboard::Key::Named(keyboard::key::Named::Space) =>
{
state.space = false;
}
_ => {}
}
if cancel {
self.content.as_widget_mut().update(
&mut tree.children[0],
&Event::Window(iced::window::Event::Unfocused),
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
if let Some(event) = camera {
shell.publish((self.publish)(event));
}
if capture {
shell.capture_event();
shell.request_redraw();
return;
}
if matches!(event, Event::Keyboard(_)) && (!state.focused || !self.keyboard) {
return;
}
let child_cursor = if inside {
pointer.map_or(mouse::Cursor::Unavailable, mouse::Cursor::Available)
} else {
mouse::Cursor::Unavailable
};
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
child_cursor,
renderer,
clipboard,
shell,
viewport,
);
// A semantic hit or armed creation tool gets first refusal. In Select,
// an otherwise unused blank press starts the same camera gesture.
if self.blank_pan
&& self.keyboard
&& inside
&& !shell.is_event_captured()
&& matches!(
event,
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
)
{
state.pan = pointer.map(|p| (mouse::Button::Left, p));
shell.publish((self.publish)(CameraEvent::CancelGesture));
shell.capture_event();
shell.request_redraw();
}
}
fn draw(
&self,
tree: &Tree,
renderer: &mut R,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
renderer.with_layer(layout.bounds(), |renderer| {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
});
if tree.state.downcast_ref::<Input>().focused && self.keyboard {
renderer.fill_quad(
renderer::Quad {
bounds: layout.bounds(),
border: Border {
color: crate::style::TEAL,
width: 1.,
..Default::default()
},
..Default::default()
},
iced::Color::TRANSPARENT,
);
}
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &R,
) -> mouse::Interaction {
if tree.state.downcast_ref::<Input>().pan.is_some() {
mouse::Interaction::Grabbing
} else {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
}
fn overlay<'a>(
&'a mut self,
tree: &'a mut Tree,
layout: Layout<'a>,
renderer: &R,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'a, Message, Theme, R>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
impl<'a, Message: 'a, R: renderer::Renderer + 'a> From<Viewport<'a, Message, R>>
for Element<'a, Message, Theme, R>
{
fn from(viewport: Viewport<'a, Message, R>) -> Self {
Element::new(viewport)
}
}
File diff suppressed because it is too large Load Diff
+761
View File
@@ -0,0 +1,761 @@
//! Local behavior creation. A draft is not a model object: only its validated
//! batch may cross Document::execute, and acknowledgement follows success.
use iced::{
Element as UiElement, Fill,
widget::{button, checkbox, column, container, row, scrollable, text, text_input},
};
use oa_core::*;
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,
Scenario,
Machine,
}
impl Family {
fn kind(self, layer: Layer) -> Kind {
match (self, layer) {
(Self::Sequence, Layer::Oa) => Kind::Process,
(Self::Sequence, Layer::Sa) => Kind::FunctionalChain,
(Self::Scenario, _) => Kind::Scenario,
(Self::Machine, _) => Kind::StateMachine,
}
}
fn title(self, layer: Layer) -> &'static str {
match (self, layer) {
(Self::Sequence, Layer::Oa) => "Operational process",
(Self::Sequence, Layer::Sa) => "Functional chain",
(Self::Scenario, _) => "Scenario",
(Self::Machine, _) => "State machine",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Picker {
Owner,
Context,
}
impl Picker {
fn index(self) -> usize {
match self {
Self::Owner => 0,
Self::Context => 1,
}
}
}
#[derive(Debug, Clone)]
pub enum Event {
Source(super::source_draft::Event),
Open(Layer),
Choose(Family),
Name(String),
Owner(Id),
Viewpoint(ScenarioViewpoint),
Context(Option<Id>),
ContextOptions(bool),
FirstView(bool),
Search(Picker, String),
Page(Picker, usize),
Cancel,
Submit,
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Browser {
query: String,
page: usize,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Draft {
#[serde(default)]
source: super::source_draft::State,
#[serde(default = "Id::new_v4")]
invocation: Id,
version: u32,
document: Id,
layer: Layer,
family: Option<Family>,
name: String,
owner: Option<Id>,
viewpoint: Option<ScenarioViewpoint>,
context: Option<Id>,
#[serde(default)]
context_open: bool,
first_view: bool,
element: Id,
diagram: Id,
placement: Id,
browsers: [Browser; 2],
}
#[derive(Default)]
pub struct State {
draft: Option<Draft>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Created {
pub behavior: Id,
pub layer: Layer,
pub diagram: Option<Id>,
}
impl State {
pub fn source_active(&self) -> bool {
self.draft.as_ref().is_some_and(|d| d.source.engaged())
}
pub fn source_open(&self) -> bool {
self.draft.as_ref().is_some_and(|d| d.source.is_open())
}
pub fn source_back(&mut self) -> bool {
self.draft.as_mut().is_some_and(|d| d.source.back())
}
pub fn has_pending(&self) -> bool {
self.draft.is_some()
}
pub fn pending_layer(&self) -> Option<Layer> {
self.draft.as_ref().map(|d| d.layer)
}
/// Capture this before successful acknowledgement; never select these IDs
/// on mere planning or a rejected source/model transaction.
pub fn created(&self) -> Option<Created> {
let d = self.draft.as_ref()?;
d.family.map(|family| Created {
behavior: d.element,
layer: d.layer,
diagram: (family == Family::Machine && d.first_view).then_some(d.diagram),
})
}
/// Match before execution, then apply this target only after success.
/// Identity alone is insufficient: changed bodies or trailing operations
/// must not inherit the prepared creation's selection/opening contract.
pub fn created_by(&self, p: &Project, command: &Command) -> Option<Created> {
let target = self.created()?;
(self.prepare_pending(p).ok().as_ref() == Some(command)).then_some(target)
}
pub fn recovery_snapshot(&self) -> Result<Option<serde_json::Value>, String> {
self.draft
.as_ref()
.map(serde_json::to_value)
.transpose()
.map_err(|e| e.to_string())
}
pub fn from_recovery(value: serde_json::Value) -> Result<Self, String> {
let draft: Draft = serde_json::from_value(value).map_err(|e| e.to_string())?;
if draft.version != 1 {
return Err("Unsupported behavior creation draft version.".into());
}
// Raw values and stale references remain editable; planning validates
// against the current document rather than silently fixing the draft.
Ok(Self { draft: Some(draft) })
}
pub fn acknowledge_commit(&mut self) {
self.draft = None;
}
pub fn prepare_pending(&self, p: &Project) -> Result<Command, String> {
self.draft
.as_ref()
.ok_or("Choose New to start a behavior.")?
.command(p)
}
pub fn update(&mut self, p: &Project, event: Event) -> Result<Option<Command>, String> {
if let Event::Source(event) = event {
if self
.draft
.as_mut()
.ok_or("Start the consumer form first.")?
.source
.dismiss(&event)?
{
return Ok(None);
}
let d = self
.draft
.as_ref()
.ok_or("Start the consumer form first.")?;
if d.family != Some(Family::Machine) {
return Err("This reference does not support staged source creation.".into());
}
if d.document != p.id {
return Err("This behavior draft belongs to another document.".into());
}
let mut next = d.clone();
if let Some(id) = next.source.update(
p,
super::source_draft::Scope::Machine { layer: d.layer },
d.invocation,
event,
)? {
next.owner = Some(id);
let preview = next
.source
.preview(p, next.owner)?
.ok_or("New owner preview is missing.")?;
if !eligible(&preview, next.layer, Picker::Owner, id) {
return Err("This participant cannot own the machine.".into());
}
}
self.draft = Some(next);
return Ok(None);
}
if self.source_open() && !matches!(&event, Event::Cancel) {
return Err("Use the new source or go Back before editing the parent form.".into());
}
match event {
Event::Cancel => {
self.draft = None;
return Ok(None);
}
Event::Open(layer) => {
if self.has_pending() {
return Err("Create or cancel the pending behavior first.".into());
}
self.draft = Some(Draft {
source: Default::default(),
invocation: Id::new_v4(),
version: 1,
document: p.id,
layer,
family: None,
name: String::new(),
owner: None,
viewpoint: None,
context: None,
context_open: false,
first_view: false,
element: Id::new_v4(),
diagram: Id::new_v4(),
placement: Id::new_v4(),
browsers: Default::default(),
});
return Ok(None);
}
Event::Submit => return self.prepare_pending(p).map(Some),
_ => {}
}
let d = self
.draft
.as_mut()
.ok_or("Choose New to start a behavior.")?;
if d.document != p.id {
return Err("This draft belongs to another document. Cancel it to start here.".into());
}
match event {
Event::Choose(family) => {
if d.family.is_some_and(|old| old != family) {
return Err(
"Cancel this draft before choosing a different behavior family.".into(),
);
}
d.family = Some(family);
}
Event::Name(name) => d.name = name,
Event::Owner(id) if d.family == Some(Family::Machine) => {
if !eligible(p, d.layer, Picker::Owner, id) {
return Err("Choose an existing participant in this layer.".into());
}
d.owner = Some(id);
}
Event::Viewpoint(viewpoint) if d.family == Some(Family::Scenario) => {
if !viewpoints(d.layer).contains(&viewpoint) {
return Err("Choose a scenario viewpoint from this layer.".into());
}
d.viewpoint = Some(viewpoint);
}
Event::Context(id) if d.family == Some(Family::Scenario) => {
if id.is_some_and(|id| !eligible(p, d.layer, Picker::Context, id)) {
return Err("Choose an existing same-layer scenario context.".into());
}
d.context = id;
}
Event::ContextOptions(open) if d.family == Some(Family::Scenario) => {
d.context_open = open;
}
Event::FirstView(value) if d.family == Some(Family::Machine) => d.first_view = value,
Event::Search(picker, query) => d.browsers[picker.index()] = Browser { query, page: 0 },
Event::Page(picker, page) => d.browsers[picker.index()].page = page,
Event::Cancel | Event::Open(_) | Event::Submit => unreachable!(),
_ => return Err("That field does not apply to this behavior family.".into()),
}
Ok(None)
}
}
fn viewpoints(layer: Layer) -> [ScenarioViewpoint; 2] {
match layer {
Layer::Oa => [
ScenarioViewpoint::OperationalActivity,
ScenarioViewpoint::ParticipantInteraction,
],
Layer::Sa => [
ScenarioViewpoint::Functional,
ScenarioViewpoint::BoundaryInterface,
],
}
}
fn viewpoint_title(viewpoint: ScenarioViewpoint) -> &'static str {
match viewpoint {
ScenarioViewpoint::OperationalActivity => "Activities · operational exchanges",
ScenarioViewpoint::ParticipantInteraction => "Participants · interactions",
ScenarioViewpoint::Functional => "Functions · functional exchanges",
ScenarioViewpoint::BoundaryInterface => "System boundary · interface exchanges",
ScenarioViewpoint::MixedLegacy => "Legacy mixed viewpoint",
}
}
fn eligible(p: &Project, layer: Layer, picker: Picker, id: Id) -> bool {
p.elements.get(&id).is_some_and(|e| {
e.layer() == layer
&& match picker {
Picker::Owner => validation::parent_permits(e.kind(), Kind::StateMachine),
Picker::Context => {
e.kind().is_sequence()
|| e.kind().is_work()
|| e.kind().is_performer()
|| matches!(
e.kind(),
Kind::Capability
| Kind::SystemCapability
| Kind::OperationalMission
| Kind::Mission
)
}
}
})
}
fn choices<'a>(p: &'a Project, layer: Layer, picker: Picker, query: &str) -> Vec<&'a Element> {
let query = query.trim().to_lowercase();
let mut matches: Vec<_> = p
.elements
.values()
.filter(|e| eligible(p, layer, picker, e.id))
.filter(|e| query.is_empty() || reference_label(p, e.id).to_lowercase().contains(&query))
.collect();
matches.sort_by(|a, b| {
a.name
.to_lowercase()
.cmp(&b.name.to_lowercase())
.then(a.id.cmp(&b.id))
});
matches
}
fn reference_context(p: &Project, e: &Element) -> String {
let mut names = Vec::new();
let mut parent = e.parent;
let mut seen = std::collections::BTreeSet::new();
while let Some(id) = parent {
if !seen.insert(id) {
break;
}
let Some(ancestor) = p.elements.get(&id) else {
break;
};
names.push(ancestor.name.as_str());
parent = ancestor.parent;
}
names.reverse();
let location = if names.is_empty() {
format!("{} root", e.layer())
} else {
format!("{} / {}", e.layer(), names.join(" / "))
};
format!("{} · {} · {location}", e.kind(), e.alias)
}
pub(super) fn reference_label(p: &Project, id: Id) -> String {
p.elements
.get(&id)
.map(|e| format!("{} · {}", e.name, reference_context(p, e)))
.unwrap_or_else(|| "Missing element — choose a replacement".into())
}
impl Draft {
fn command(&self, p: &Project) -> Result<Command, String> {
self.source.check_scope(
super::source_draft::Scope::Machine { layer: self.layer },
self.owner,
)?;
let preview = self.source.preview(p, self.owner)?;
let command = self.consumer_command(preview.as_ref().unwrap_or(p))?;
self.source.combine(p, self.owner, command)
}
fn consumer_command(&self, p: &Project) -> Result<Command, String> {
if self.document != p.id {
return Err("This draft belongs to another document.".into());
}
let family = self
.family
.ok_or("Choose the behavior you want to create.")?;
if self.name.trim().is_empty() {
return Err("Enter the behavior's name before creating it.".into());
}
if [self.element, self.diagram, self.placement]
.into_iter()
.any(|id| p.contains(id))
|| self.element == self.diagram
|| self.element == self.placement
|| self.diagram == self.placement
{
return Err(
"A reserved creation identity is already in use. Cancel and start a fresh draft."
.into(),
);
}
let kind = family.kind(self.layer);
let parent = if family == Family::Machine {
Some(
self.owner
.filter(|id| eligible(p, self.layer, Picker::Owner, *id))
.ok_or("Choose the participant that owns this state machine.")?,
)
} else {
if self.owner.is_some() {
return Err("Processes and scenarios belong at the layer root; context is a separate reference.".into());
}
None
};
if family != Family::Machine && self.first_view {
return Err("A state view can only accompany a state machine.".into());
}
let mut body = ElementBody::new(kind, self.layer)
.ok_or("This behavior is unavailable in this layer.")?;
if family == Family::Scenario {
let viewpoint = self
.viewpoint
.filter(|v| viewpoints(self.layer).contains(v))
.ok_or("Choose the scenario's viewpoint explicitly.")?;
if self
.context
.is_some_and(|id| !eligible(p, self.layer, Picker::Context, id))
{
return Err(
"The selected scenario context is missing or no longer compatible.".into(),
);
}
body = ElementBody::shared_in(
self.layer,
SharedBody::Scenario {
viewpoint,
context: self.context,
precondition: String::new(),
postcondition: String::new(),
steps: Vec::new(),
},
);
} else if self.viewpoint.is_some() || self.context.is_some() {
return Err(
"Scenario viewpoint and context cannot be applied to another behavior family."
.into(),
);
}
let element = Element {
id: self.element,
alias: p.fresh_alias(&self.name, "behavior", self.element),
name: self.name.clone(),
description: String::new(),
parent,
body,
};
let mut commands = vec![Command::CreateElement(element)];
if self.first_view {
let working = execute_batch(p, &commands).map_err(|e| e.to_string())?;
// Reuse the state editor's geometry contract. A new machine has one
// root placement; reserve both presentation IDs across retries.
let plan = super::state_edit::create_view(&working, self.element)
.map_err(|e| e.to_string())?;
let Command::Batch(mut view_commands) = plan.command else {
return Err("Unexpected state-view plan.".into());
};
if view_commands.len() != 2 {
return Err("Unexpected additional operation in the first state-view plan.".into());
}
let Some(Command::Layout(layout)) = view_commands.pop() else {
return Err("State-view plan must finish with its layout operation.".into());
};
let Some(Command::CreateDiagram(mut diagram)) = view_commands.pop() else {
return Err("State-view plan is missing its diagram.".into());
};
if diagram.id != layout || diagram.nodes.len() != 1 {
return Err("A first state view must contain only its new machine.".into());
}
let mut node = diagram
.nodes
.into_values()
.next()
.ok_or("State-view root is missing.")?;
if node.element != self.element {
return Err("State-view root differs from the new machine.".into());
}
diagram.id = self.diagram;
diagram.alias = working.fresh_alias(&diagram.name, "state_view", self.diagram);
node.id = self.placement;
node.alias = working.fresh_alias(
&format!("{} placement", self.name),
"placement",
self.placement,
);
diagram.nodes = [(node.id, node)].into_iter().collect();
commands.push(Command::CreateDiagram(diagram));
commands.push(Command::Layout(self.diagram));
}
let command = Command::Batch(commands);
execute_batch(p, std::slice::from_ref(&command)).map_err(|e| e.to_string())?;
Ok(command)
}
}
impl State {
/// Parent maps these local events into the existing guarded Behavior route.
/// The card's fields scroll; Create/Cancel stay outside that scroll region.
pub fn view<'a>(&'a self, p: &'a Project) -> Option<UiElement<'a, Event>> {
self.view_with(p)
}
fn view_with<'a, R: iced::advanced::text::Renderer + 'a>(
&'a self,
p: &'a Project,
) -> Option<UiElement<'a, Event, iced::Theme, R>> {
let d = self.draft.as_ref()?;
if let Some(view) = d.source.view(p) {
return Some(
column![
text(format!(
"State machine name: {}",
crate::views::short(&d.name, 60)
))
.size(12),
view.map(Event::Source)
]
.spacing(6)
.height(Fill)
.into(),
);
}
let mut fields = column![].spacing(10);
let title = if let Some(family) = d.family {
fields = fields.push(
text_input("Exact behavior name", &d.name)
.id(NAME_INPUT)
.on_input(Event::Name)
.on_submit(Event::Submit)
.padding(8),
);
match family {
Family::Sequence => {
fields = fields.push(
text(format!(
"Owned by the {} layer root. Add work and exchange contributions after creation.",
d.layer
))
.size(12),
);
}
Family::Scenario => {
fields = fields.push(
text(format!(
"Owned by the {} layer root. Choose what the lifelines represent:",
d.layer
))
.size(12),
);
for viewpoint in viewpoints(d.layer) {
fields = fields.push(
button(text(viewpoint_title(viewpoint)).size(13))
.style(if d.viewpoint == Some(viewpoint) {
button::primary
} else {
button::secondary
})
.on_press(Event::Viewpoint(viewpoint))
.padding(7),
);
}
let context_label = if d.context_open {
"Hide optional context".into()
} else if let Some(id) = d.context {
format!("Context: {} · Change…", reference_label(p, id))
} else {
"Add optional context…".into()
};
fields = fields.push(
button(text(context_label).size(12))
.on_press(Event::ContextOptions(!d.context_open))
.padding(6),
);
if d.context_open {
fields = fields.push(picker_view(p, d, Picker::Context));
}
}
Family::Machine => {
if let Some(label) = d.source.label(d.owner) {
fields = fields.push(text(label).size(13)).push(text("Create and open commits the new owner and machine together, including the first view only when selected.").size(12));
}
fields = fields.push(picker_view(p, d, Picker::Owner));
fields = fields.push(
button("Create new owner…")
.on_press(Event::Source(super::source_draft::Event::Open(
d.invocation,
)))
.padding(7),
);
fields = fields.push(
checkbox(d.first_view)
.label("Create the first state view")
.on_toggle(Event::FirstView),
);
fields = fields.push(text("The machine starts without regions or states. Add those explicitly in its workspace.").size(12));
}
}
format!("New {}", family.title(d.layer))
} else {
for family in [Family::Sequence, Family::Scenario, Family::Machine] {
let purpose = match family {
Family::Sequence => "A path through work and exchanges",
Family::Scenario => "Ordered interactions from an explicit viewpoint",
Family::Machine => "States and modes of an explicitly chosen participant",
};
fields = fields.push(
button(
column![text(family.title(d.layer)).size(15), text(purpose).size(12)]
.spacing(3),
)
.on_press(Event::Choose(family))
.padding(10)
.width(Fill),
);
}
format!("New behavior · {}", d.layer)
};
let mut actions =
row![button("Cancel · Esc").on_press(Event::Cancel).padding(8)].spacing(8);
if d.family.is_some() {
actions = actions.push(button("Create and open").on_press(Event::Submit).padding(8));
}
Some(
container(
column![
text(title).size(20),
scrollable(fields)
.id("behavior-creation-fields")
.height(Fill),
container(actions).id("behavior-creation-actions")
]
.spacing(12),
)
.padding(18)
.max_width(680)
.height(Fill)
.style(crate::style::card)
.into(),
)
}
}
fn picker_view<'a, R: iced::advanced::text::Renderer + 'a>(
p: &'a Project,
d: &'a Draft,
picker: Picker,
) -> UiElement<'a, Event, iced::Theme, R> {
let browser = &d.browsers[picker.index()];
let options = choices(p, d.layer, picker, &browser.query);
let page = browser
.page
.min(options.len().saturating_sub(1) / PAGE_SIZE);
let selected = match picker {
Picker::Owner => d.owner,
Picker::Context => d.context,
};
let title = match picker {
Picker::Owner => "Owned by participant",
Picker::Context => "Scenario context · optional",
};
let mut out = column![
text(title).size(13),
text_input("Search names, aliases or parent context", &browser.query)
.on_input(move |query| Event::Search(picker, query))
.padding(6)
]
.spacing(5);
if let Some(id) = selected {
out = out.push(text(format!("Selected: {}", reference_label(p, id))).size(12));
} else if picker == Picker::Context {
out = out.push(text("No context selected").size(12));
}
if options.is_empty() {
out = out.push(text(match picker {
Picker::Owner => "No matching participant. Refine the search or choose Create new owner.",
Picker::Context => "No matching context. Refine the search, or leave this optional reference empty.",
}).size(12));
}
for e in options.iter().skip(page * PAGE_SIZE).take(PAGE_SIZE) {
let message = match picker {
Picker::Owner => Event::Owner(e.id),
Picker::Context => Event::Context(Some(e.id)),
};
out = out.push(
container(
button(
column![
text(&e.name).size(13),
text(reference_context(p, e)).size(11)
]
.spacing(2),
)
.style(if selected == Some(e.id) {
button::primary
} else {
button::secondary
})
.on_press(message)
.padding(6)
.width(Fill),
)
.id(format!("behavior-creation-candidate-{}", e.id)),
);
}
let mut navigation = row![text(format!("{} matches", options.len())).size(11)].spacing(8);
if page > 0 {
navigation = navigation.push(button("Previous").on_press(Event::Page(picker, page - 1)));
}
if (page + 1) * PAGE_SIZE < options.len() {
navigation = navigation.push(button("Next").on_press(Event::Page(picker, page + 1)));
}
if picker == Picker::Context && selected.is_some() {
navigation = navigation.push(button("Clear context").on_press(Event::Context(None)));
}
out.push(navigation).into()
}
#[cfg(test)]
mod app_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,340 @@
//! App-boundary regressions for the coordinated parent wiring. No I/O task is
//! polled: file dialogs, checkpoint writes and lesson loading remain inactive.
use super::*;
use crate::app::{App, Message, Page, Pending};
use std::sync::Arc;
fn send(app: &mut App, event: Event) {
let _ = app.update(Message::Behavior(crate::behavior::Event::Creation(event)));
}
fn raw_property(app: &App) -> serde_json::Value {
serde_json::to_value(app.draft.as_ref().unwrap().recovery_snapshot()).unwrap()
}
fn begin(app: &mut App, layer: Layer, family: Family, name: &str) {
let _ = app.update(Message::Layer(layer));
let _ = app.update(Message::Page(Page::Behavior));
send(app, Event::Open(layer));
send(app, Event::Choose(family));
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
}
#[test]
fn app_first_captured_escape_dismisses_file_or_pending_overlay_before_creation() {
for file in [false, true] {
let mut app = App::with_project(Project::empty());
begin(
&mut app,
Layer::Oa,
Family::Sequence,
"Keep while overlay closes",
);
let raw = app.behavior.recovery_snapshot().unwrap();
let accepted = app.document.snapshot();
if file {
app.file_prompt = Some(crate::app::FilePrompt {
operation: crate::app::FileOperation::Save,
path: "unsubmitted-name.arcadia".into(),
overwrite: false,
});
} else {
app.pending = Some(Pending::Walkthrough);
}
let _ = app.update(focused_escape());
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());
assert!(!app.behavior.has_pending());
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
assert!(!app.document.can_undo());
}
}
#[test]
fn app_creation_opens_the_actual_new_owner_instead_of_first_or_previously_active_behavior() {
for layer in [Layer::Oa, Layer::Sa] {
let mut p = Project::empty();
let old = p
.add_element(Family::Sequence.kind(layer), layer, "Old behavior", None)
.unwrap();
let mut app = App::with_project(p.clone());
let _ = app.update(Message::Select(old));
begin(&mut app, layer, Family::Sequence, " New exact path 雨 ");
let target = app.behavior.creation.created().unwrap();
assert_ne!(target.behavior, old);
let before = app.document.bundle().clone();
send(&mut app, Event::Submit);
assert_eq!(app.page, Page::Behavior);
assert_eq!(app.layer, layer);
assert_eq!(app.selected, target.behavior);
assert_eq!(app.behavior.active_owner, Some(target.behavior));
assert_eq!(crate::behavior::selected_owner(&app), Some(target.behavior));
assert_eq!(
app.project().elements[&target.behavior].name,
" New exact path 雨 "
);
assert!(!app.behavior.has_pending());
let after = app.document.bundle().clone();
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &before);
assert!(!app.document.can_undo());
let _ = app.update(Message::Redo);
assert_eq!(app.document.bundle(), &after);
assert_eq!(app.project().elements[&old], p.elements[&old]);
}
}
#[test]
fn app_machine_behavior_submit_opens_its_opted_in_view_as_one_undoable_transaction() {
for first_view in [false, true] {
let mut p = Project::empty();
let owner = p
.add_element(Kind::System, Layer::Sa, "Flight system", None)
.unwrap();
let mut app = App::with_project(p.clone());
begin(&mut app, Layer::Sa, Family::Machine, " Flight modes 雨 ");
send(&mut app, Event::Owner(owner));
send(&mut app, Event::FirstView(first_view));
let target = app.behavior.creation.created().unwrap();
let before = app.document.bundle().clone();
let _ = app.update(Message::Behavior(crate::behavior::Event::Submit));
assert!(!app.behavior.has_pending(), "{}", app.status);
assert_eq!(app.selected, target.behavior);
assert_eq!(app.behavior.active_owner, Some(target.behavior));
assert_eq!(app.behavior.diagram.diagram, target.diagram);
assert_eq!(
crate::behavior::state_view::diagram(&app, target.behavior),
target.diagram
);
assert_eq!(app.project().elements[&target.behavior].parent, Some(owner));
assert_eq!(app.page, Page::Behavior);
let after = app.document.bundle().clone();
let _ = app.update(Message::Undo);
assert_eq!(app.document.bundle(), &before);
assert_eq!(app.project(), &p);
assert!(!app.document.can_undo());
let _ = app.update(Message::Redo);
assert_eq!(app.document.bundle(), &after);
}
}
#[test]
fn app_stale_layer_open_never_starts_or_replaces_a_draft() {
let mut app = App::with_project(Project::empty());
let _ = app.update(Message::Layer(Layer::Sa));
app.page = Page::Behavior;
let accepted = app.document.snapshot();
send(&mut app, Event::Open(Layer::Oa));
assert!(!app.behavior.has_pending());
assert_eq!(app.layer, Layer::Sa);
send(&mut app, Event::Open(Layer::Sa));
send(&mut app, Event::Choose(Family::Sequence));
send(&mut app, Event::Name("Retained system chain".into()));
let raw = app.behavior.recovery_snapshot().unwrap();
send(&mut app, Event::Open(Layer::Oa));
assert_eq!(app.behavior.recovery_snapshot().unwrap(), raw);
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
}
#[test]
fn app_new_never_auto_applies_valid_or_invalid_property_and_source_drafts() {
for dirty in [
"property-valid",
"property-invalid",
"source-valid",
"source-invalid",
] {
let mut app = App::with_project(Project::empty());
app.page = Page::Behavior;
match dirty {
"property-valid" => app
.draft
.as_mut()
.unwrap()
.input("/name", "Raw property name".into()),
"property-invalid" => app.draft.as_mut().unwrap().input("/id", "-".into()),
"source-valid" => app.source_workspace.edit(
format!("{}\n// Retained comment\n", app.source_workspace.text()),
app.source_editor.cursor(),
),
_ => app
.source_workspace
.edit("unfinished source 雨".into(), app.source_editor.cursor()),
}
let accepted = app.document.snapshot();
let property = raw_property(&app);
let workspace = app.source_workspace.recovery_snapshot();
send(&mut app, Event::Open(Layer::Oa));
assert!(
!app.behavior.creation.has_pending(),
"{dirty}: New must refuse without applying another editor"
);
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
assert_eq!(raw_property(&app), property);
assert_eq!(
serde_json::to_value(app.source_workspace.recovery_snapshot()).unwrap(),
serde_json::to_value(workspace).unwrap()
);
assert!(!app.document.can_undo());
}
}
#[test]
fn app_choosing_another_behavior_or_layer_cannot_commit_a_creation_draft() {
let mut p = Project::empty();
let old = p
.add_element(Kind::Process, Layer::Oa, "Old process", None)
.unwrap();
let mut app = App::with_project(p);
begin(&mut app, Layer::Oa, Family::Sequence, "Retain this process");
let raw = app.behavior.recovery_snapshot().unwrap();
let accepted = app.document.snapshot();
let _ = app.update(Message::Layer(Layer::Sa));
let _ = app.update(Message::BehaviorOwner(crate::app::Choice {
id: old,
label: "Old process".into(),
}));
assert_eq!(app.layer, Layer::Oa);
assert_eq!(app.behavior.recovery_snapshot().unwrap(), raw);
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
let _ = app.update(Message::Escape);
assert!(!app.behavior.has_pending());
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
assert!(!app.document.can_undo());
}
#[test]
fn app_lesson_request_cancel_retains_creation_then_escape_discards_only_the_draft() {
let mut app = App::with_project(Project::empty());
begin(
&mut app,
Layer::Oa,
Family::Sequence,
"Unfinished engineering path",
);
let raw = app.behavior.recovery_snapshot().unwrap();
let accepted = app.document.snapshot();
let task = app.update(Message::Home(crate::home::Event::Walkthrough));
assert!(matches!(app.pending, Some(Pending::Walkthrough)));
assert!(iced_runtime::task::into_stream(task).is_none());
let _ = app.update(Message::Escape);
assert!(app.pending.is_none());
assert_eq!(app.behavior.recovery_snapshot().unwrap(), raw);
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
let _ = app.update(Message::Escape);
assert!(!app.behavior.has_pending());
assert!(Arc::ptr_eq(&accepted, &app.document.snapshot()));
}
#[test]
fn app_recovered_rootless_sa_creation_retains_layer_ids_and_other_raw_drafts() {
let mut app = App::with_project(Project::empty());
begin(
&mut app,
Layer::Sa,
Family::Scenario,
" Recovered system scenario 雨 ",
);
send(
&mut app,
Event::Viewpoint(ScenarioViewpoint::BoundaryInterface),
);
// Recovery can contain simultaneous drafts even though new input is guarded.
app.draft
.as_mut()
.unwrap()
.input("/name", "Retained property".into());
app.source_workspace.edit(
"unfinished source preserved".into(),
app.source_editor.cursor(),
);
let snapshot = crate::recovery::Snapshot::capture(
app.canvas_document,
&app.document,
&app.source_workspace,
app.draft.as_ref(),
&app.behavior,
None,
app.selected,
)
.unwrap();
let expected = snapshot.clone().restore().unwrap();
let raw = app.behavior.recovery_snapshot().unwrap();
let mut restored = App::with_project(Project::empty());
let _ = restored.update(Message::CheckpointLoaded(Ok(Arc::new(snapshot))));
assert_eq!(restored.page, Page::Behavior);
assert_eq!(restored.layer, Layer::Sa);
assert_eq!(restored.behavior.recovery_snapshot().unwrap(), raw);
assert_eq!(
restored.behavior.creation.created(),
app.behavior.creation.created()
);
assert_eq!(restored.project(), expected.document.project());
assert_eq!(restored.document.bundle(), expected.document.bundle());
assert_eq!(
restored.source_workspace.bundle(),
expected.workspace.bundle()
);
assert_eq!(raw_property(&restored), raw_property(&app));
let before = restored.document.snapshot();
send(&mut restored, Event::Submit);
assert!(Arc::ptr_eq(&before, &restored.document.snapshot()));
assert_eq!(restored.behavior.recovery_snapshot().unwrap(), raw);
assert_eq!(raw_property(&restored), raw_property(&app));
}
@@ -0,0 +1,599 @@
use super::*;
use crate::document::Document;
use oa_core::source_project::ProjectLimits;
fn start(p: &Project, layer: Layer, family: Family, name: &str) -> State {
let mut state = State::default();
assert!(state.update(p, Event::Open(layer)).unwrap().is_none());
state.update(p, Event::Choose(family)).unwrap();
state.update(p, Event::Name(name.into())).unwrap();
state
}
#[test]
fn mounted_creation_keeps_actions_visible_and_renders_only_six_owner_candidates() {
use iced::advanced::{Layout, layout, widget};
use iced::{Rectangle, Size, Vector};
struct Geometry {
candidates: Vec<widget::Id>,
rendered: Vec<widget::Id>,
actions: Option<Rectangle>,
fields: Option<Rectangle>,
}
impl widget::Operation for Geometry {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn widget::Operation)) {
visit(self);
}
fn container(&mut self, id: Option<&widget::Id>, bounds: Rectangle) {
if id == Some(&widget::Id::new("behavior-creation-actions")) {
self.actions = Some(bounds);
}
if let Some(id) = id.filter(|id| self.candidates.contains(id)) {
self.rendered.push(id.clone());
}
}
fn scrollable(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
_: Rectangle,
_: Vector,
_: &mut dyn widget::operation::Scrollable,
) {
if id == Some(&widget::Id::new("behavior-creation-fields")) {
self.fields = Some(bounds);
}
}
}
let mut p = Project::empty();
for index in 0..105 {
p.add_element(
Kind::Entity,
Layer::Oa,
&format!(
"{index:03} Long engineering participant name {}",
"雨 extended ".repeat(20)
),
None,
)
.unwrap();
}
let candidates: Vec<_> = p
.elements
.keys()
.map(|id| widget::Id::from(format!("behavior-creation-candidate-{id}")))
.collect();
for family in [Family::Sequence, Family::Scenario, Family::Machine] {
let state = start(&p, Layer::Oa, family, "Very long exact behavior name 雨");
for size in [
Size::new(500., 570.),
Size::new(1050., 570.),
Size::new(500., 320.),
] {
let mut view: UiElement<'_, Event, iced::Theme, ()> = state.view_with(&p).unwrap();
let mut tree = widget::Tree::new(view.as_widget());
let node =
view.as_widget_mut()
.layout(&mut tree, &(), &layout::Limits::new(Size::ZERO, size));
let mut geometry = Geometry {
candidates: candidates.clone(),
rendered: Vec::new(),
actions: None,
fields: None,
};
view.as_widget_mut()
.operate(&mut tree, Layout::new(&node), &(), &mut geometry);
let actions = geometry.actions.unwrap();
let fields = geometry.fields.unwrap();
assert!(actions.x >= 0. && actions.y >= 0.);
assert!(
actions.x + actions.width <= size.width
&& actions.y + actions.height <= size.height
);
assert!(fields.height >= 100. && fields.y + fields.height <= actions.y);
assert_eq!(
geometry.rendered.len(),
if family == Family::Machine { 6 } else { 0 }
);
}
}
}
fn roundtrip(p: Project, state: &mut State) -> Project {
let command = state.update(&p, Event::Submit).unwrap().unwrap();
assert_eq!(
command,
state.prepare_pending(&p).unwrap(),
"preparation must retain reserved IDs"
);
let api: Command = serde_json::from_value(serde_json::to_value(&command).unwrap()).unwrap();
assert_eq!(api, command);
let expected = execute_batch(&p, &[api]).unwrap();
let target = state.created().unwrap();
let mut document = Document::from_project(p.clone(), ProjectLimits::default()).unwrap();
let before_source = document.bundle().clone();
document.execute(command).unwrap();
assert_eq!(document.project(), &expected);
assert!(
state.has_pending(),
"only successful acknowledgement clears raw fields"
);
state.acknowledge_commit();
assert!(!state.has_pending());
assert!(document.project().elements.contains_key(&target.behavior));
let after_source = document.bundle().clone();
assert!(document.undo());
assert_eq!(document.project(), &p);
assert_eq!(document.bundle(), &before_source);
assert!(!document.can_undo(), "one creation must be one Undo entry");
assert!(document.redo());
assert_eq!(document.project(), &expected);
assert_eq!(document.bundle(), &after_source);
let reopened = Document::from_bundle(after_source, ProjectLimits::default()).unwrap();
assert_eq!(reopened.project(), &expected);
expected
}
#[test]
fn oa_process_and_sa_chain_keep_exact_names_root_ownership_and_one_history_entry() {
for layer in [Layer::Oa, Layer::Sa] {
let p = Project::empty();
let name = " Supply \"water\" — режим ";
let mut state = start(&p, layer, Family::Sequence, name);
let target = state.created().unwrap();
let result = roundtrip(p, &mut state);
let element = &result.elements[&target.behavior];
assert_eq!(element.name, name);
assert_eq!(element.layer(), layer);
assert_eq!(
element.kind(),
if layer == Layer::Oa {
Kind::Process
} else {
Kind::FunctionalChain
}
);
assert_eq!(element.parent, None);
assert!(element.steps().unwrap().is_empty());
assert!(result.diagrams.is_empty());
assert!(result.relations.is_empty());
}
}
#[test]
fn all_four_viewpoints_are_explicit_and_survive_source_history_reopen() {
for layer in [Layer::Oa, Layer::Sa] {
for viewpoint in viewpoints(layer) {
let mut p = Project::empty();
let context = p
.add_element(
if layer == Layer::Oa {
Kind::Capability
} else {
Kind::SystemCapability
},
layer,
"Water supply",
None,
)
.unwrap();
let mut state = start(&p, layer, Family::Scenario, "Nominal supply");
assert!(
state
.prepare_pending(&p)
.unwrap_err()
.contains("explicitly")
);
assert!(
state
.update(&p, Event::Viewpoint(ScenarioViewpoint::MixedLegacy))
.is_err()
);
let wrong = viewpoints(if layer == Layer::Oa {
Layer::Sa
} else {
Layer::Oa
})[0];
assert!(state.update(&p, Event::Viewpoint(wrong)).is_err());
state.update(&p, Event::Viewpoint(viewpoint)).unwrap();
state.update(&p, Event::Context(Some(context))).unwrap();
let id = state.created().unwrap().behavior;
let result = roundtrip(p, &mut state);
assert_eq!(
result.elements[&id].parent, None,
"context is not containment"
);
assert!(
matches!(result.elements[&id].shared(), Some(SharedBody::Scenario { viewpoint: actual, context: Some(actual_context), steps, .. }) if *actual == viewpoint && *actual_context == context && steps.is_empty())
);
}
}
}
#[test]
fn machine_requires_valid_owner_and_first_view_adds_no_region_or_state() {
for layer in [Layer::Oa, Layer::Sa] {
for first_view in [false, true] {
let mut p = Project::empty();
let owner = p
.add_element(
if layer == Layer::Oa {
Kind::Entity
} else {
Kind::System
},
layer,
"Pump",
None,
)
.unwrap();
let wrong_kind = p
.add_element(
if layer == Layer::Oa {
Kind::Activity
} else {
Kind::Function
},
layer,
"Pump water",
None,
)
.unwrap();
let opposite = if layer == Layer::Oa {
Layer::Sa
} else {
Layer::Oa
};
let wrong_layer = p
.add_element(
if opposite == Layer::Oa {
Kind::Entity
} else {
Kind::System
},
opposite,
"Other layer pump",
None,
)
.unwrap();
let mut state = start(&p, layer, Family::Machine, "Pump modes");
assert!(
state
.prepare_pending(&p)
.unwrap_err()
.contains("participant")
);
assert!(state.update(&p, Event::Owner(wrong_kind)).is_err());
assert!(state.update(&p, Event::Owner(wrong_layer)).is_err());
state.update(&p, Event::Owner(owner)).unwrap();
state.update(&p, Event::FirstView(first_view)).unwrap();
let target = state.created().unwrap();
let expected_count = p.elements.len() + 1;
let result = roundtrip(p, &mut state);
assert_eq!(result.elements.len(), expected_count);
assert_eq!(result.elements[&target.behavior].parent, Some(owner));
assert_eq!(result.elements[&target.behavior].kind(), Kind::StateMachine);
assert_eq!(result.diagrams.len(), usize::from(first_view));
if let Some(view) = target.diagram {
let diagram = &result.diagrams[&view];
assert_eq!(
diagram.projection,
ProjectionKind::StateMachine {
machine: target.behavior
}
);
assert_eq!(diagram.nodes.len(), 1);
assert_eq!(
diagram.nodes.values().next().unwrap().element,
target.behavior
);
}
}
}
}
#[test]
fn cancel_and_illegal_family_layer_switches_never_create_model_objects() {
let p = Project::empty();
let mut state = start(&p, Layer::Oa, Family::Scenario, "Raw name");
state
.update(
&p,
Event::Viewpoint(ScenarioViewpoint::ParticipantInteraction),
)
.unwrap();
let snapshot = state.recovery_snapshot().unwrap();
assert!(state.update(&p, Event::Open(Layer::Sa)).is_err());
assert!(state.update(&p, Event::Choose(Family::Sequence)).is_err());
assert_eq!(state.recovery_snapshot().unwrap(), snapshot);
assert!(state.update(&p, Event::Cancel).unwrap().is_none());
assert!(!state.has_pending());
assert!(state.created().is_none());
assert!(state.prepare_pending(&p).is_err());
assert!(p.elements.is_empty());
assert!(p.diagrams.is_empty());
}
#[test]
fn recovery_preserves_exact_raw_inputs_reserved_ids_and_revalidates_stale_owner() {
let mut p = Project::empty();
let owner = p
.add_element(Kind::Entity, Layer::Oa, "Plant", None)
.unwrap();
let mut state = start(&p, Layer::Oa, Family::Machine, " \nRaw rejected name\0 ");
state.update(&p, Event::Owner(owner)).unwrap();
state.update(&p, Event::FirstView(true)).unwrap();
state
.update(&p, Event::Search(Picker::Owner, " Plant ".into()))
.unwrap();
let raw = state.recovery_snapshot().unwrap().unwrap();
let mut restored = State::from_recovery(raw.clone()).unwrap();
assert_eq!(restored.recovery_snapshot().unwrap(), Some(raw.clone()));
assert_eq!(restored.created(), state.created());
assert_eq!(restored.pending_layer(), Some(Layer::Oa));
assert!(restored.prepare_pending(&p).is_err());
restored
.update(&p, Event::Name("Plant modes".into()))
.unwrap();
let command = restored.prepare_pending(&p).unwrap();
let again = State::from_recovery(restored.recovery_snapshot().unwrap().unwrap()).unwrap();
assert_eq!(again.prepare_pending(&p).unwrap(), command);
p.elements.remove(&owner);
let before = restored.recovery_snapshot().unwrap();
assert!(
restored
.prepare_pending(&p)
.unwrap_err()
.contains("participant")
);
assert_eq!(restored.recovery_snapshot().unwrap(), before);
let different = Project::empty();
assert!(
restored
.prepare_pending(&different)
.unwrap_err()
.contains("another document")
);
}
#[test]
fn rejected_source_transaction_keeps_draft_and_every_accepted_source_byte() {
let p = Project::empty();
let initial = Document::from_project(p.clone(), ProjectLimits::default()).unwrap();
let bytes: usize = initial.bundle().files.values().map(String::len).sum();
let limits = ProjectLimits {
model: language::ParseLimits {
max_source_bytes: bytes + 32,
..language::ParseLimits::UNLIMITED
},
..ProjectLimits::default()
};
let mut doc = Document::from_bundle(initial.bundle().clone(), limits).unwrap();
let mut state = start(
&p,
Layer::Oa,
Family::Sequence,
"A long exact name retained after the source budget refuses this new process",
);
let raw = state.recovery_snapshot().unwrap();
let command = state.prepare_pending(&p).unwrap();
assert!(doc.execute(command).is_err());
assert_eq!(doc.project(), &p);
assert_eq!(doc.bundle(), initial.bundle());
assert!(!doc.can_undo());
assert_eq!(state.recovery_snapshot().unwrap(), raw);
state.update(&p, Event::Cancel).unwrap();
}
#[test]
fn owner_search_is_name_ordered_filtered_and_page_sized_not_a_catalog() {
let mut p = Project::empty();
for index in (0..105).rev() {
p.add_element(Kind::Entity, Layer::Oa, &format!("Pump {index:03}"), None)
.unwrap();
}
p.add_element(Kind::System, Layer::Sa, "Pump 999", None)
.unwrap();
p.add_element(Kind::Activity, Layer::Oa, "Pump work", None)
.unwrap();
let mut state = start(&p, Layer::Oa, Family::Machine, "Pump modes");
let all = choices(&p, Layer::Oa, Picker::Owner, "");
assert_eq!(all.len(), 105);
assert_eq!(all[0].name, "Pump 000");
state
.update(&p, Event::Page(Picker::Owner, usize::MAX))
.unwrap();
assert!(
state.view(&p).is_some(),
"stale pages are clamped before slicing"
);
state
.update(&p, Event::Search(Picker::Owner, "Pump 104".into()))
.unwrap();
assert_eq!(state.draft.as_ref().unwrap().browsers[0].page, 0);
let found = choices(&p, Layer::Oa, Picker::Owner, "Pump 104");
assert_eq!(found.len(), 1);
state.update(&p, Event::Owner(found[0].id)).unwrap();
assert_eq!(state.draft.as_ref().unwrap().owner, Some(found[0].id));
}
#[test]
fn repeated_owner_names_remain_distinguishable_by_searchable_parent_context_and_alias() {
let mut p = Project::empty();
let north = p
.add_element(Kind::Entity, Layer::Oa, "North station", None)
.unwrap();
let south = p
.add_element(Kind::Entity, Layer::Oa, "South station", None)
.unwrap();
let first = p
.add_element(Kind::Entity, Layer::Oa, "Pump", Some(north))
.unwrap();
let second = p
.add_element(Kind::Entity, Layer::Oa, "Pump", Some(south))
.unwrap();
let label = reference_label(&p, second);
assert_ne!(reference_label(&p, first), label);
assert!(label.contains("South station") && label.contains("Pump"));
assert!(label.contains(&p.elements[&second].alias));
let found = choices(&p, Layer::Oa, Picker::Owner, "south station");
assert!(found.iter().any(|e| e.id == second));
assert!(!found.iter().any(|e| e.id == first));
let mut state = start(&p, Layer::Oa, Family::Machine, "Pump states");
state.update(&p, Event::Owner(second)).unwrap();
let result = execute_batch(&p, &[state.prepare_pending(&p).unwrap()]).unwrap();
assert_eq!(
result.elements[&state.created().unwrap().behavior].parent,
Some(second)
);
}
#[test]
fn corrupted_recovery_and_reserved_identity_collision_refuse_without_repairing_raw_values() {
let p = Project::empty();
let state = start(&p, Layer::Sa, Family::Sequence, "Supply");
let raw = state.recovery_snapshot().unwrap().unwrap();
for (field, value) in [
("version", serde_json::json!(99)),
("unexpected", serde_json::json!(true)),
] {
let mut bad = raw.clone();
bad[field] = value;
assert!(State::from_recovery(bad).is_err());
}
let mut bad = raw;
bad["element"] = serde_json::json!(p.id);
let restored = State::from_recovery(bad.clone()).unwrap();
assert!(
restored
.prepare_pending(&p)
.unwrap_err()
.contains("identity")
);
assert_eq!(restored.recovery_snapshot().unwrap(), Some(bad));
}
#[test]
fn post_commit_selection_is_correlated_with_exact_created_behavior_and_view() {
let mut p = Project::empty();
let owner = p
.add_element(Kind::Entity, Layer::Oa, "Pump", None)
.unwrap();
let mut state = start(&p, Layer::Oa, Family::Machine, "Pump modes");
state.update(&p, Event::Owner(owner)).unwrap();
state.update(&p, Event::FirstView(true)).unwrap();
let command = state.prepare_pending(&p).unwrap();
assert_eq!(state.created_by(&p, &command), state.created());
assert_eq!(
state.created_by(&p, &Command::Rename(owner, "Unrelated change".into())),
None
);
for edit in 0..4 {
let mut changed = command.clone();
let Command::Batch(ref mut commands) = changed else {
panic!("creation batch");
};
if edit < 3 {
let Command::CreateElement(element) = &mut commands[0] else {
panic!("new behavior");
};
match edit {
0 => element.id = Id::new_v4(),
1 => element.name = "A different authored draft".into(),
_ => element.parent = None,
}
} else {
let Command::CreateDiagram(diagram) = &mut commands[1] else {
panic!("new view");
};
diagram.projection = ProjectionKind::StateMachine { machine: owner };
}
assert_eq!(state.created_by(&p, &changed), None);
}
let Command::Batch(commands) = command else {
panic!("creation batch");
};
assert_eq!(
state.created_by(&p, &commands[0]),
None,
"an opt-in view must be part of the actual committed batch"
);
}
#[test]
fn optional_context_collapses_without_losing_authored_reference_or_raw_search() {
let mut p = Project::empty();
let context = p
.add_element(Kind::Capability, Layer::Oa, "Water supply", None)
.unwrap();
let mut state = start(&p, Layer::Oa, Family::Scenario, "Supply nominal");
assert!(!state.draft.as_ref().unwrap().context_open);
state
.update(&p, Event::Viewpoint(ScenarioViewpoint::OperationalActivity))
.unwrap();
state.update(&p, Event::ContextOptions(true)).unwrap();
state
.update(&p, Event::Search(Picker::Context, " Water ".into()))
.unwrap();
state.update(&p, Event::Context(Some(context))).unwrap();
let command = state.prepare_pending(&p).unwrap();
state.update(&p, Event::ContextOptions(false)).unwrap();
let restored = State::from_recovery(state.recovery_snapshot().unwrap().unwrap()).unwrap();
assert!(!restored.draft.as_ref().unwrap().context_open);
assert_eq!(
restored.draft.as_ref().unwrap().browsers[1].query,
" Water "
);
assert_eq!(restored.prepare_pending(&p).unwrap(), command);
assert_eq!(restored.created_by(&p, &command), restored.created());
}
#[test]
fn creation_selection_rejects_changed_scenario_body_and_post_creation_operations() {
let mut p = Project::empty();
let capability = p
.add_element(Kind::SystemCapability, Layer::Sa, "Supply", None)
.unwrap();
let mut state = start(&p, Layer::Sa, Family::Scenario, "Nominal functions");
state
.update(&p, Event::Viewpoint(ScenarioViewpoint::Functional))
.unwrap();
let command = state.prepare_pending(&p).unwrap();
assert_eq!(state.created_by(&p, &command), state.created());
for edit in 0..4 {
let mut altered = command.clone();
let Command::Batch(commands) = &mut altered else {
panic!("creation batch");
};
match edit {
0 => {
let Command::CreateElement(element) = &mut commands[0] else {
panic!("scenario");
};
let Some(SharedBody::Scenario { viewpoint, .. }) = element.shared_mut() else {
panic!("scenario body");
};
*viewpoint = ScenarioViewpoint::BoundaryInterface;
}
1 => {
let Command::CreateElement(element) = &mut commands[0] else {
panic!("scenario");
};
let Some(SharedBody::Scenario { context, .. }) = element.shared_mut() else {
panic!("scenario body");
};
*context = Some(capability);
}
2 => commands.push(Command::Rename(
state.created().unwrap().behavior,
"Changed afterward".into(),
)),
_ => commands.push(Command::Delete(state.created().unwrap().behavior)),
}
assert!(
execute_batch(&p, std::slice::from_ref(&altered)).is_ok(),
"the alternate command is valid, but is not this authored creation"
);
assert_eq!(state.created_by(&p, &altered), None);
}
}
@@ -0,0 +1,148 @@
//! Keep behavior field state within one editing session and reset it on replacement.
use iced::advanced::widget::{Operation, Tree, tree};
use iced::advanced::{Clipboard, Layout, Shell, Widget, layout, overlay, renderer};
use iced::{Element, Event, Length, Rectangle, Size, Theme, Vector, mouse};
use oa_core::Id;
struct Identity(Id);
struct Session<'a, Message, R: renderer::Renderer> {
identity: Id,
content: Element<'a, Message, Theme, R>,
}
pub(super) fn reset_on_change<'a, Message: 'a, R: renderer::Renderer + 'a>(
identity: Id,
content: impl Into<Element<'a, Message, Theme, R>>,
) -> Element<'a, Message, Theme, R> {
Element::new(Session {
identity,
content: content.into(),
})
}
impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Session<'_, Message, R> {
fn tag(&self) -> tree::Tag {
tree::Tag::of::<Identity>()
}
fn state(&self) -> tree::State {
tree::State::new(Identity(self.identity))
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(self.content.as_widget())]
}
fn diff(&self, tree: &mut Tree) {
let retained = tree.state.downcast_mut::<Identity>();
if retained.0 != self.identity {
retained.0 = self.identity;
// Iced's keyed column preserves same-length child replacements.
// An editing-session replacement must instead get fresh field state.
tree.children = self.children();
} else {
tree.diff_children(std::slice::from_ref(&self.content));
}
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(&mut self, tree: &mut Tree, renderer: &R, limits: &layout::Limits) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
operation: &mut dyn Operation,
) {
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
fn draw(
&self,
tree: &Tree,
renderer: &mut R,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &R,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'b>,
renderer: &R,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, R>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
+253 -496
View File
@@ -4,6 +4,9 @@ use super::topology::{occurrence, unique_batch};
use super::*;
use iced::widget::{Column, column, text_input};
use std::{cell::RefCell, collections::BTreeSet};
mod workspace;
pub(crate) use workspace::NAME_INPUT;
pub use workspace::{Shelf, view};
#[cfg(test)]
#[path = "scenario_operation_tests.rs"]
@@ -92,8 +95,15 @@ impl std::fmt::Display for CanvasTool {
}
#[derive(Debug, Clone)]
pub enum CanvasEvent {
First(Context, Tool),
Scrolled(Context, ScrollArea, iced::Vector),
Restored(Context, Id, ScrollArea, iced::Vector),
Viewport(Context, Size),
FormShown(Context, Id),
Zoom(Context, Option<f32>),
Camera(Context, u64, super::canvas_workspace::Event),
Focus(Context),
Shelf(Context, Shelf),
OpenUse(Context, Id),
Back(Context),
Choose(Context, CanvasTool),
@@ -120,13 +130,21 @@ pub enum CanvasEvent {
#[derive(Debug, Clone, Copy)]
pub enum ScrollArea {
Canvas,
// Retained navigation channel, now the independent Selection/outline shelf.
Page,
}
impl CanvasEvent {
pub fn context(&self) -> Context {
match self {
Self::Scrolled(context, _, _)
Self::First(context, _)
| Self::Scrolled(context, _, _)
| Self::Restored(context, ..)
| Self::Viewport(context, _)
| Self::FormShown(context, _)
| Self::Zoom(context, _)
| Self::Camera(context, ..)
| Self::Focus(context)
| Self::Shelf(context, _)
| Self::OpenUse(context, _)
| Self::Back(context)
| Self::Choose(context, _)
@@ -151,6 +169,7 @@ impl std::fmt::Display for Operator {
}
#[derive(Debug, Clone)]
pub enum Event {
Source(super::source_draft::Event),
Start(Id, Tool),
Cancel,
Submit,
@@ -186,11 +205,14 @@ const VALUE_PAGE_SIZE: usize = 24;
#[derive(Default)]
pub struct State {
draft: Option<Draft>,
form_session: Id,
form_focus_pending: bool,
canvas_tool: Option<(Id, CanvasTool)>,
call_choices: RefCell<Option<(CallChoiceContext, Vec<Choice>)>>,
scroll_offsets: [iced::Vector; 2],
return_to: Vec<Caller>,
restore: Option<ViewportRestore>,
presentation: workspace::Presentation,
}
const CALLER_LIMIT: usize = 32;
pub(crate) struct Caller {
@@ -200,6 +222,7 @@ pub(crate) struct Caller {
target: Id,
tool: CanvasTool,
offsets: [iced::Vector; 2],
presentation: workspace::Presentation,
}
struct ViewportRestore {
document: Id,
@@ -227,6 +250,13 @@ struct CallChoiceContext {
#[derive(Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Draft {
#[serde(default)]
source: super::source_draft::State,
#[serde(default = "Id::new_v4")]
invocation: Id,
#[serde(default)]
source_origin: Option<(Id, oa_core::Element)>,
owner: Id,
parent: Id,
before: Option<Id>,
@@ -259,6 +289,88 @@ struct Draft {
choice_page: usize,
}
impl State {
pub(crate) fn camera_boundary(&self) -> impl PartialEq + use<> {
(
self.canvas_tool,
self.presentation.focused,
self.presentation.shelf,
self.presentation.viewport,
self.presentation.pan,
self.presentation.zoom,
self.presentation.fit,
)
}
pub(super) fn pending_name(&self) -> Option<&str> {
self.draft.as_ref().map(|d| d.name.as_str())
}
pub(super) fn source_view<'a>(&'a self, p: &'a Project) -> Option<iced::Element<'a, Event>> {
self.draft
.as_ref()?
.source
.view(p)
.map(|v| v.map(Event::Source))
}
pub fn source_active(&self) -> bool {
self.draft.as_ref().is_some_and(|d| d.source.engaged())
}
pub fn source_open(&self) -> bool {
self.draft.as_ref().is_some_and(|d| d.source.is_open())
}
pub fn source_back(&mut self) -> bool {
self.draft.as_mut().is_some_and(|d| d.source.back())
}
pub(crate) fn enter(&mut self, document: Id, owner: Id) {
if self.presentation.identity != Some((document, owner)) {
self.presentation = workspace::Presentation {
identity: Some((document, owner)),
focused: self.presentation.focused,
..Default::default()
};
self.scroll_offsets = [iced::Vector::ZERO; 2];
self.restore = None;
}
}
pub(crate) fn viewport(&mut self, size: Size) -> bool {
self.presentation.viewport(size)
}
pub(crate) fn camera(&mut self, event: super::canvas_workspace::Event) -> bool {
let p = &mut self.presentation;
super::canvas_workspace::change(&mut p.pan, &mut p.zoom, &mut p.fit, event)
}
pub(crate) fn zoom(&mut self, scale: Option<f32>) -> bool {
self.presentation.zoom(scale)
}
pub(crate) fn camera_zoom(&mut self, p: &Project, owner: Id, zoom: Option<f32>) -> bool {
let size = Scene::sequence(p, owner, owner).size;
let old = self.presentation.scale(size);
if let Some(next) = zoom {
let viewport = self.presentation.viewport.unwrap_or(Size::new(500., 300.));
self.camera(super::canvas_workspace::Event::Zoom {
factor: next / old,
at: Point::new(viewport.width / 2., viewport.height / 2.),
base: old,
})
} else {
self.zoom(None);
let fitted = self.presentation.scale(size);
self.zoom(Some(fitted));
self.presentation.pan = iced::Vector::ZERO;
true
}
}
pub(crate) fn focused(&self) -> bool {
self.presentation.focused
}
pub(crate) fn toggle_focus(&mut self) {
self.presentation.focused = !self.presentation.focused;
}
pub(crate) fn toggle_shelf(&mut self, shelf: Shelf) {
self.presentation.shelf = (self.presentation.shelf != Some(shelf)).then_some(shelf);
}
pub(crate) fn open_use(
&mut self,
p: &Project,
@@ -279,6 +391,7 @@ impl State {
target,
tool: self.canvas_tool(context.scenario),
offsets: self.scroll_offsets,
presentation: self.presentation.clone(),
});
self.canvas_tool = Some((target, CanvasTool::Select));
self.scroll_offsets = [iced::Vector::ZERO; 2];
@@ -309,12 +422,14 @@ impl State {
}
self.canvas_tool = Some((frame.owner, frame.tool));
self.scroll_offsets = frame.offsets;
self.presentation = frame.presentation;
self.presentation.identity = Some((context.document, context.scenario));
self.restore = Some(ViewportRestore {
document: context.document,
owner: frame.owner,
token: Id::new_v4(),
offsets: frame.offsets,
pending: [true; 2],
pending: [false, true],
});
}
pub(super) fn scroll_restore(
@@ -373,11 +488,29 @@ impl State {
let draft = serde_json::from_value(value).map_err(|e| e.to_string())?;
Ok(Self {
draft: Some(draft),
form_session: Id::new_v4(),
form_focus_pending: true,
..Default::default()
})
}
pub(crate) fn form_session(&self) -> Option<Id> {
self.draft.as_ref().map(|_| self.form_session)
}
pub(crate) fn take_form_focus(&mut self, session: Id) -> bool {
if self.form_session() == Some(session) && self.form_focus_pending {
self.form_focus_pending = false;
true
} else {
false
}
}
pub(crate) fn scrolled(&mut self, area: ScrollArea, offset: iced::Vector) -> bool {
if !offset.x.is_finite() || !offset.y.is_finite() || offset.x < 0. || offset.y < 0. {
return false;
}
let index = match area {
ScrollArea::Canvas => 0,
ScrollArea::Page => 1,
@@ -386,8 +519,10 @@ impl State {
self.scroll_offsets[index] = offset;
changed
}
#[cfg(test)]
fn scroll_offset(&self) -> iced::Vector {
self.scroll_offsets[0] + self.scroll_offsets[1]
// The former page scroll now belongs to a sibling outline shelf.
self.scroll_offsets[0]
}
fn call_choices(&self, p: &Project, context: Context, draft: &Draft) -> Vec<Choice> {
let key = CallChoiceContext {
@@ -406,8 +541,16 @@ impl State {
}
cached.as_ref().unwrap().1.clone()
}
pub(crate) fn created_selection(&self, command: &Command) -> Option<Id> {
pub(crate) fn created_selection(&self, p: &Project, command: &Command) -> Option<Id> {
let draft = self.draft.as_ref()?;
if self
.draft
.as_ref()
.is_some_and(|d| d.source.label(d.target).is_some())
&& self.prepare_pending(p).ok().as_ref() != Some(command)
{
return None;
}
fn created(command: &Command, parent: Id) -> Option<Id> {
match command {
Command::CreateElement(element) if element.parent == Some(parent) => {
@@ -522,6 +665,61 @@ impl State {
}
pub fn update(&mut self, p: &Project, event: Event) -> Result<Option<Command>, String> {
if let Event::Source(event) = event {
if self
.draft
.as_mut()
.ok_or("Start the consumer form first.")?
.source
.dismiss(&event)?
{
return Ok(None);
}
let d = self
.draft
.as_ref()
.ok_or("Start the consumer form first.")?;
if d.tool != Tool::Lifeline {
return Err("This reference does not support staged source creation.".into());
}
if d.source_origin.as_ref().is_some_and(|(document, owner)| {
*document != p.id || p.elements.get(&d.owner) != Some(owner)
}) {
return Err("The original consumer changed. Cancel and reopen its form; the current draft is retained.".into());
}
if d.source_origin.is_none() && d.source.engaged() {
return Err("The recovered source draft has no original document binding. Go Back or cancel it.".into());
}
let mut next = d.clone();
if next.source_origin.is_none() && matches!(&event, super::source_draft::Event::Open(_))
{
next.source_origin = Some((
p.id,
p.elements
.get(&d.owner)
.ok_or("The consumer owner no longer exists.")?
.clone(),
));
}
if let Some(id) = next.source.update(
p,
super::source_draft::Scope::Lifeline {
owner: d.owner,
viewpoint: viewpoint(p, d.owner),
},
d.invocation,
event,
)? {
next.target = Some(id);
next.command(p)?;
}
self.draft = Some(next);
return Ok(None);
}
if self.source_open() && !matches!(&event, Event::Cancel) {
return Err("Use the new source or go Back before editing the parent form.".into());
}
if self.draft.is_some() && matches!(&event, Event::Start(..)) {
return Err(PENDING_DRAFT.into());
}
@@ -530,7 +728,12 @@ impl State {
if p.elements.get(&owner).map(oa_core::Element::kind) != Some(Kind::Scenario) {
return Err("Choose a scenario.".into());
}
self.form_session = Id::new_v4();
self.form_focus_pending = true;
self.draft = Some(Draft {
source: Default::default(),
invocation: Id::new_v4(),
source_origin: Some((p.id, p.elements[&owner].clone())),
owner,
parent: owner,
before: None,
@@ -894,7 +1097,14 @@ fn valid_body_choice(p: &Project, owner: Id, body: OccurrenceBody) -> bool {
execute_batch(p, &[Command::CreateElement(e)]).is_ok()
}
fn sources(p: &Project, d: &Draft) -> Vec<Choice> {
let layer = p.elements[&d.owner].layer();
let Some(owner) = p
.elements
.get(&d.owner)
.filter(|e| e.kind() == Kind::Scenario)
else {
return vec![];
};
let layer = owner.layer();
let mut values: Vec<_> = p
.elements
.values()
@@ -1210,6 +1420,28 @@ impl Draft {
e
}
fn command(&self, p: &Project) -> Result<Command, String> {
if self.source.engaged()
&& self.source_origin.as_ref().is_none_or(|(document, owner)| {
*document != p.id || p.elements.get(&self.owner) != Some(owner)
})
{
return Err("The original consumer document or owner changed. Cancel and reopen its form; your draft is retained.".into());
}
self.source.check_scope(
super::source_draft::Scope::Lifeline {
owner: self.owner,
viewpoint: viewpoint(p, self.owner),
},
self.target,
)?;
let preview = self.source.preview(p, self.target)?;
let command = self.consumer_command(preview.as_ref().unwrap_or(p))?;
self.source.combine(p, self.target, command)
}
fn consumer_command(&self, p: &Project) -> Result<Command, String> {
if p.elements.get(&self.owner).map(oa_core::Element::kind) != Some(Kind::Scenario) {
return Err("The scenario no longer exists. Cancel or restore its owner.".into());
}
if !parents(p, self.owner).iter().any(|c| c.id == self.parent) {
return Err("Choose this scenario or one of its operands as destination.".into());
}
@@ -1220,6 +1452,8 @@ impl Draft {
.unwrap_or(self.tool.label());
let name = if self.name.trim().is_empty() {
default
} else if self.source.label(self.target).is_some() {
self.name.as_str()
} else {
self.name.trim()
};
@@ -1634,493 +1868,6 @@ fn bounded_picker<'a>(
}
out.into()
}
pub fn view<'a>(app: &'a App, owner: Id, mut out: Column<'a, Message>) -> Element<'a, Message> {
let p = app.project();
out = out.push(label(match viewpoint(p, owner) {
ScenarioViewpoint::OperationalActivity => {
"Operational activity scenario · lifelines represent activities"
}
ScenarioViewpoint::Functional => {
"Functional scenario · lifelines represent system functions"
}
ScenarioViewpoint::ParticipantInteraction => {
"Participant scenario · lifelines represent entities, actors or roles"
}
ScenarioViewpoint::BoundaryInterface => {
"Interface scenario · lifelines represent the system and external actors"
}
ScenarioViewpoint::MixedLegacy => {
"Mixed scenario · lifelines may represent work or participants"
}
}));
let pending = app.behavior.has_pending();
let context = app.scenario_context().expect("visible scenario context");
let tool = app.behavior.scenario.canvas_tool(owner);
// Keep the canvas at a stable widget-tree position when a form replaces
// the palette, so Iced retains the user's current sequence viewport.
let mut controls = column![].spacing(6);
if !pending {
controls = controls.push(
row![
button("Select / reorder")
.on_press(Message::ScenarioCanvas(CanvasEvent::Choose(
context,
CanvasTool::Select
)))
.style(if tool == CanvasTool::Select {
style::selected
} else {
style::nav
}),
pick_list(
vec![
CanvasTool::Select,
CanvasTool::Message(MessageStyle::CallReply),
CanvasTool::Message(MessageStyle::Asynchronous),
CanvasTool::Message(MessageStyle::Call),
CanvasTool::Message(MessageStyle::Reply),
CanvasTool::Message(MessageStyle::Create),
CanvasTool::Message(MessageStyle::Delete),
CanvasTool::Message(MessageStyle::Timer),
CanvasTool::Add(Tool::Action),
CanvasTool::Add(Tool::Observation),
CanvasTool::Add(Tool::Reuse),
CanvasTool::Add(Tool::Fragment),
],
Some(tool),
move |tool| Message::ScenarioCanvas(CanvasEvent::Choose(context, tool))
)
.text_size(12)
.padding(8)
.width(240),
action("+ Lifeline", event(Event::Start(owner, Tool::Lifeline))),
action("Properties", Message::EditProperties(owner)),
]
.spacing(6)
.wrap(),
);
controls = controls.push(label(match tool {
CanvasTool::Message(_) => "Draw message · choose a sequence position on a lifeline, then click or drag to another lifeline · Escape cancels",
CanvasTool::Add(Tool::Action | Tool::Observation) => "Click a highlighted sequence position · click on a lifeline to preselect it · Escape cancels",
CanvasTool::Add(Tool::Reuse) => "Click a highlighted sequence position to reuse a scenario and bind its lifelines · Escape cancels",
CanvasTool::Add(Tool::Fragment) => "Click a highlighted sequence position to insert an empty fragment with operands · Escape cancels",
_ => "Select a lifeline or occurrence · drag its ↕ handle to reorder within its sequence",
}));
} else {
controls = controls.push(label(
"Pending form · the canvas remains visible · apply or cancel below",
));
}
let clean = !pending && !app.draft_dirty() && !app.source_dirty();
let mut navigation = row![].spacing(6);
if referenced_scenario(p, owner, app.selected).is_some() {
navigation = navigation.push(button("Open definition").on_press_maybe(clean.then_some(
Message::ScenarioCanvas(CanvasEvent::OpenUse(context, app.selected)),
)));
}
if app.behavior.scenario.can_back(p, context) {
navigation =
navigation.push(button("Back to caller").on_press_maybe(
clean.then_some(Message::ScenarioCanvas(CanvasEvent::Back(context))),
));
}
controls = controls.push(navigation.wrap());
out = out.push(controls);
let mut scene = Scene::sequence(p, owner, app.selected);
scene.interaction = Some((
context,
tool,
!app.behavior.has_pending() && !app.draft_dirty() && !app.source_dirty(),
));
scene.scroll_offset = app.behavior.scenario.scroll_offset();
scene.pending_placement = app.behavior.scenario.pending_placement(owner);
let size = scene.size;
out = out.push(
container(super::scenario_scroll::observe(
context,
ScrollArea::Canvas,
app.behavior
.scenario
.scroll_restore(context, ScrollArea::Canvas),
scrollable(
canvas::Canvas::new(scene)
.width(size.width)
.height(size.height),
)
.direction(scrollable::Direction::Both {
vertical: scrollable::Scrollbar::default(),
horizontal: scrollable::Scrollbar::default(),
})
.height(if pending {
(app.window_size.height - 660.).clamp(110., 190.)
} else {
(app.window_size.height - 410.).clamp(180., 340.)
}),
))
.padding(8)
.style(style::card),
);
if let Some(d) = app
.behavior
.scenario
.draft
.as_ref()
.filter(|d| d.owner == owner)
{
let mut form = column![
text(d.tool.label()).size(16),
text_input("Name (defaults to selected source)", &d.name)
.on_input(|s| event(Event::Name(s)))
.padding(9)
.size(12)
]
.spacing(9);
if d.tool != Tool::Lifeline {
form = form.push(label(format!(
"Insert: {}",
slot_label(
p,
Slot {
parent: d.parent,
before: d.before
}
)
)));
if d.before.is_some() {
form = form.push(
button("Append to this sequence instead").on_press(event(Event::AppendInstead)),
);
}
form = form.push(picker(
parents(p, owner),
Some(d.parent),
"Destination sequence / operand…",
Event::Parent,
));
}
if matches!(
d.tool,
Tool::Lifeline | Tool::Reuse | Tool::Action | Tool::Observation
) {
form = form.push(picker(
sources(p, d),
d.target,
"Choose a named source…",
Event::Target,
));
}
if d.tool == Tool::Message {
form = form.push(
pick_list(
vec![
MessageStyle::Asynchronous,
MessageStyle::Call,
MessageStyle::CallReply,
MessageStyle::Reply,
MessageStyle::Create,
MessageStyle::Delete,
MessageStyle::Timer,
],
Some(d.style),
|style| event(Event::Style(style)),
)
.width(Fill)
.padding(9)
.text_size(12),
);
if d.style == MessageStyle::Reply {
form = form.push(bounded_picker(
app.behavior.scenario.call_choices(p, context, d),
d,
d.call,
"Choose the earlier call…",
Event::Call,
));
if d.call.is_some() {
form = form.push(label(
"Reply reuses the call exchange in reverse and retains its correlation.",
));
}
} else if d.style != MessageStyle::Timer {
form = form.push(bounded_picker(
exchanges(p, d),
d,
d.exchange,
"Choose the exchange…",
Event::Exchange,
));
form = form.push(label(
"Apply checks that the message is valid at this insertion position.",
));
}
form = form.push(picker(
d.line_choices(p, true),
d.sender,
"Sending lifeline…",
Event::Sender,
));
if d.style != MessageStyle::Timer {
form = form.push(picker(
d.line_choices(p, false),
d.receiver,
"Receiving lifeline…",
Event::Receiver,
));
}
if d.style == MessageStyle::Timer {
form = form.push(
text_input("Duration / deadline, e.g. 30 s", &d.expression)
.on_input(|s| event(Event::Expression(s)))
.padding(9)
.size(12),
);
}
if p.layer_of(owner) == Some(Layer::Sa)
&& viewpoint(p, owner) == ScenarioViewpoint::BoundaryInterface
&& matches!(
d.style,
MessageStyle::Call | MessageStyle::CallReply | MessageStyle::Asynchronous
)
{
form = form.push(
iced::widget::checkbox(d.operation.is_some())
.label("Invoke a specific interface operation")
.on_toggle(|enabled| event(Event::OperationIntent(enabled))),
);
if let Some(operation) = &d.operation {
form = form
.push(bounded_picker(
crate::data_values::operation_choices(p, &d.proposed_message(p)),
d,
operation.allocation,
"Choose the exact interface operation allocation…",
Event::Operation,
))
.push(
button("Keep operation unresolved")
.on_press(event(Event::ClearOperation)),
);
if let Some(id) = operation.allocation {
form = form.push(label(crate::data_values::operation_identity(p, id)));
}
}
}
if let Some(description) =
crate::data_values::operation_label(p, &d.proposed_message(p))
{
form = form.push(label(description));
}
match d.signature(p) {
Ok(Some(exchange)) => form = form.push(value_panel(p, d, &exchange)),
Err(problem) => {
form = form.push(label(problem));
for (key, expression) in d.authored_values() {
form = form
.push(
text(format!(
"Retained value · {} / {}",
key.path
.iter()
.map(|id| p.named(*id))
.collect::<Vec<_>>()
.join(" → "),
p.named(key.field)
))
.size(11),
)
.push(
text_input("Value expression", expression)
.on_input({
let key = key.clone();
move |raw| event(Event::Value(key.clone(), raw))
})
.padding(8)
.size(12),
);
}
}
Ok(None) => {}
}
if d.style == MessageStyle::CallReply {
form=form.push(label("Creates the call and reversed, correlated reply together in one undoable operation."));
}
}
if matches!(d.tool, Tool::Action | Tool::Observation) {
form = form.push(picker(
lines(p, owner),
d.sender,
"Observed lifeline…",
Event::Sender,
));
}
if d.tool == Tool::Reuse
&& let Some(target) = d.target
{
for line in lines(p, target) {
let referenced = line.id;
let compatible: Vec<_> = lines(p, owner)
.into_iter()
.filter(|c| {
compatible_binding(p, referenced, c.id)
&& !d
.bindings
.iter()
.any(|(r, l)| *r != referenced && *l == c.id)
})
.collect();
if compatible.is_empty() {
form = form.push(label(format!(
"Add a compatible local lifeline before binding '{}'.",
p.named(referenced)
)));
}
form = form
.push(label(format!("Bind {}", p.named(referenced))))
.push(picker(
compatible,
d.bindings.get(&referenced).copied(),
"Compatible local lifeline…",
move |c| Event::Binding(referenced, c),
));
}
form = form.push(label(
"Bindings are explicit, one-to-one and refer to existing lifelines.",
));
}
if d.tool == Tool::Fragment {
form = form.push(
pick_list(
vec![
Operator(FragmentOperator::Alternative),
Operator(FragmentOperator::Parallel),
Operator(FragmentOperator::Loop),
Operator(FragmentOperator::Optional),
],
Some(Operator(d.operator)),
|o| event(Event::Operator(o)),
)
.padding(9)
.text_size(12)
.width(Fill),
);
if d.operator != FragmentOperator::Parallel {
form = form.push(
text_input("Condition / loop guard", &d.expression)
.on_input(|s| event(Event::Expression(s)))
.padding(9)
.size(12),
);
}
if d.operator == FragmentOperator::Alternative {
form = form.push(
text_input("Second alternative guard", &d.second_guard)
.on_input(|s| event(Event::SecondGuard(s)))
.padding(9)
.size(12),
);
}
form=form.push(label("Creates the fragment with its operands. Choose an operand as destination when adding messages or actions."));
}
let readiness = d.command(p);
if let Err(error) = &readiness {
form = form.push(label(error.clone()));
}
let footer = row![
button("Create")
.padding(9)
.on_press_maybe(readiness.is_ok().then_some(event(Event::Submit))),
action("Cancel", event(Event::Cancel))
]
.spacing(7);
out = out.push(
container(
column![
scrollable(form).height((app.window_size.height - 650.).clamp(110., 240.)),
footer
]
.spacing(9),
)
.padding(14)
.style(style::card),
);
}
if lines(p, owner).is_empty() && p.elements[&owner].steps().is_none_or(Vec::is_empty) {
out = out.push(container(label("Add lifelines for the participating work or actors, then create messages between them.")).padding(16).width(Fill).style(style::card));
} else if !pending {
out = sequence_rows(p, context, owner, out);
}
super::scenario_scroll::observe(
context,
ScrollArea::Page,
app.behavior
.scenario
.scroll_restore(context, ScrollArea::Page),
scrollable(out.padding(24)),
)
}
fn sequence_rows<'a>(
p: &'a Project,
context: Context,
owner: Id,
mut out: Column<'a, Message>,
) -> Column<'a, Message> {
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Fragment { branches, .. },
..
}) = p.elements.get(&owner).and_then(|e| e.shared())
{
for branch in branches {
out = out.push(action(
&format!("Operand: {}", p.named(*branch)),
Message::Select(*branch),
));
out = sequence_rows(p, context, *branch, out);
}
}
if let Some(steps) = p.elements.get(&owner).and_then(|e| e.steps()) {
for (i, id) in steps.iter().enumerate() {
out =
out.push(
row![
action(
&format!("{}. {}", i + 1, p.named(*id)),
Message::Select(*id)
)
.width(Fill),
button("↑")
.padding(8)
.on_press_maybe((i > 0).then_some(Message::Command(
Command::MoveStep(owner, i, i.saturating_sub(1))
))),
button("↓").padding(8).on_press_maybe(
(i + 1 < steps.len()).then_some(Message::Command(Command::MoveStep(
owner,
i,
i + 1
)))
)
]
.spacing(6),
);
if let Some(SharedBody::Occurrence {
body:
OccurrenceBody::ScenarioUse {
scenario: Some(target),
..
},
..
}) = p.elements[id].shared()
{
out = out.push(action(
&format!("Open {} →", p.named(*target)),
Message::ScenarioCanvas(CanvasEvent::OpenUse(context, *id)),
));
}
out = sequence_rows(p, context, *id, out);
}
}
out
}
#[cfg(test)]
pub(crate) mod direct_tests {
@@ -2180,7 +1927,7 @@ pub(crate) mod direct_tests {
epoch: 0,
}
}
fn placement_fixture() -> (Fixture, Id, Id, Id, Id, Id) {
pub(super) fn placement_fixture() -> (Fixture, Id, Id, Id, Id, Id) {
let mut f = fixture();
let p = &mut f.project;
let machine = p
@@ -2334,7 +2081,12 @@ pub(crate) mod direct_tests {
);
assert_eq!(
app.behavior.scenario.scroll_offset(),
iced::Vector::new(25., 250.)
iced::Vector::new(25., 170.)
);
assert_eq!(
app.behavior.scenario.scroll_offsets[1],
iced::Vector::new(0., 80.),
"The caller's independent outline scroll is restored separately"
);
assert!(
!app.behavior
@@ -2471,6 +2223,11 @@ pub(crate) mod direct_tests {
assert!(app.document.can_undo(), "{}", app.status);
navigation_event(&mut app, CanvasEvent::Back);
assert_eq!(app.selected, if edit == 0 { first } else { b });
assert_eq!(
app.scenario_context().unwrap().scenario,
if edit == 0 { a } else { b },
"Back must restore the caller workspace even if a rename already selected its UUID"
);
assert_eq!(app.project(), &project);
assert_eq!(app.document.bundle(), &source);
assert_eq!(app.document.revision(), revision);
@@ -2909,7 +2666,7 @@ pub(crate) mod direct_tests {
assert!(app.busy);
assert_eq!(
app.behavior.scenario.scroll_offset(),
iced::Vector::new(25., 140.)
iced::Vector::new(25., 100.)
);
assert_ne!(
app.scenario_context(),
@@ -2925,7 +2682,7 @@ pub(crate) mod direct_tests {
)));
assert_eq!(
app.behavior.scenario.scroll_offset(),
iced::Vector::new(25., 140.)
iced::Vector::new(25., 100.)
);
let root = std::path::PathBuf::from("scenario-scroll-save-fixture");
let receipt = crate::app::FileSnapshot {
@@ -0,0 +1,693 @@
//! Scenario presentation. Layout/camera controls never construct model commands.
use super::super::scenario_scroll;
use super::*;
use iced::widget::{Space, column, sensor};
pub(crate) const NAME_INPUT: &str = "scenario-form-name";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shelf {
Tools,
Selection,
}
#[derive(Clone, Default)]
pub(super) struct Presentation {
pub(super) identity: Option<(Id, Id)>,
pub(super) viewport: Option<Size>,
pub(super) focused: bool,
pub(super) shelf: Option<Shelf>,
pub(super) pan: iced::Vector,
pub(super) zoom: Option<f32>,
pub(super) fit: bool,
}
const MIN_SCALE: f32 = 0.05;
impl Presentation {
pub(super) fn viewport(&mut self, size: Size) -> bool {
if !size.width.is_finite()
|| !size.height.is_finite()
|| size.width <= 0.
|| size.height <= 0.
|| self.viewport == Some(size)
{
return false;
}
self.viewport = Some(size);
true
}
pub(super) fn zoom(&mut self, scale: Option<f32>) -> bool {
if scale.is_some_and(|value| !value.is_finite() || value <= 0.) {
return false;
}
let next = scale.map(|value| value.clamp(MIN_SCALE, 3.));
let changed = self.zoom != next || self.fit != scale.is_none();
self.zoom = next;
self.fit = scale.is_none();
changed
}
fn fit_scale(&self, scene: Size) -> Option<f32> {
let viewport = self.viewport?;
// Fit uses the actual mounted viewport with a small visual gutter.
Some(
((viewport.width - 16.).max(1.) / scene.width.max(1.))
.min((viewport.height - 16.).max(1.) / scene.height.max(1.)),
)
}
pub(super) fn scale(&self, scene: Size) -> f32 {
if self.fit {
self.fit_scale(scene).unwrap_or(1.).clamp(MIN_SCALE, 1.)
} else {
self.zoom.unwrap_or(1.)
}
}
}
pub fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Element<'a, Message> {
let p = app.project();
let state = &app.behavior.scenario;
let presentation = &state.presentation;
let pending = state
.draft
.as_ref()
.is_some_and(|draft| draft.owner == owner);
let context = app.scenario_context().expect("visible scenario context");
let tool = state.canvas_tool(owner);
let clean = !app.behavior.has_pending() && !app.draft_dirty() && !app.source_dirty();
let mut scene = Scene::sequence(p, owner, app.selected);
let scale = presentation.scale(scene.size);
scene.scale = scale;
scene.camera_pan = presentation.pan;
scene.interaction = Some((context, tool, clean));
scene.pending_placement = state.pending_placement(owner);
let scope = super::super::canvas_workspace::Scope {
document: context.document,
owner,
revision: context.revision,
epoch: app.camera_epoch,
};
let keyboard = clean && super::super::canvas_workspace::keyboard_enabled(app);
let camera = move |e| Message::ScenarioCanvas(CanvasEvent::Camera(context, scope.epoch, e));
let canvas = container(
sensor(
super::super::canvas_workspace::Viewport::new(
canvas::Canvas::new(scene).width(Fill).height(Fill),
scope,
scale,
keyboard,
camera,
)
.pan_background(tool == CanvasTool::Select),
)
.key((context.document, owner))
.on_show(move |size| Message::ScenarioCanvas(CanvasEvent::Viewport(context, size)))
.on_resize(move |size| Message::ScenarioCanvas(CanvasEvent::Viewport(context, size))),
)
.id("scenario-viewport")
.width(Fill)
.height(Fill)
.style(style::card)
.into();
let mut navigation = row![
out.width(Fill),
super::super::canvas_workspace::Control::new(
button(
text(if presentation.focused {
"Restore panels"
} else {
"Focus canvas"
})
.size(12)
)
.padding(6)
.on_press(super::super::canvas_workspace::intent(
scope,
"Panels",
Message::ScenarioCanvas(CanvasEvent::Focus(context))
)),
scope,
"Panels",
keyboard,
Some(super::super::canvas_workspace::intent(
scope,
"Panels",
Message::ScenarioCanvas(CanvasEvent::Focus(context))
)),
camera
)
]
.spacing(6);
if state.can_back(p, context) {
navigation =
navigation.push(button(text("Back").size(12)).padding(6).on_press_maybe(
clean.then_some(Message::ScenarioCanvas(CanvasEvent::Back(context))),
));
}
let header = column![
navigation,
super::super::canvas_workspace::controls(
scope,
keyboard,
scale,
Message::ScenarioCanvas(CanvasEvent::Shelf(context, Shelf::Selection)),
clean.then_some(Message::ScenarioCanvas(CanvasEvent::Camera(
context,
scope.epoch,
super::super::canvas_workspace::Event::Focus
))),
move |zoom| Message::ScenarioCanvas(CanvasEvent::Zoom(context, zoom)),
camera
)
]
.spacing(4);
let entries = [
("S", "Select / reorder occurrences", CanvasTool::Select),
(
"L",
"Lifeline: click to choose represented work or participant",
CanvasTool::Add(Tool::Lifeline),
),
(
"C/R",
"Call and correlated reply",
CanvasTool::Message(MessageStyle::CallReply),
),
(
"M",
"Asynchronous message",
CanvasTool::Message(MessageStyle::Asynchronous),
),
(
"C",
"Synchronous call",
CanvasTool::Message(MessageStyle::Call),
),
(
"R",
"Reply to existing call",
CanvasTool::Message(MessageStyle::Reply),
),
(
"+L",
"Create participant",
CanvasTool::Message(MessageStyle::Create),
),
(
"-L",
"Delete participant",
CanvasTool::Message(MessageStyle::Delete),
),
("T", "Local timer", CanvasTool::Message(MessageStyle::Timer)),
(
"A",
"Action: click a sequence position",
CanvasTool::Add(Tool::Action),
),
(
"St",
"State observation: click a sequence position",
CanvasTool::Add(Tool::Observation),
),
(
"ref",
"Reuse scenario: click a sequence position",
CanvasTool::Add(Tool::Reuse),
),
(
"alt",
"Fragment: click a sequence position",
CanvasTool::Add(Tool::Fragment),
),
];
let palette = super::super::canvas_workspace::palette(
scope,
keyboard,
camera,
entries.into_iter().map(|(glyph, label, choice)| {
(
glyph,
label,
choice == tool,
clean.then_some(Message::ScenarioCanvas(CanvasEvent::Choose(
context, choice,
))),
)
}),
);
let mut details = column![
text(format!("Selected: {}", p.named(app.selected))).size(12),
button(text("Properties").size(12))
.on_press_maybe(clean.then_some(Message::EditProperties(app.selected)))
]
.spacing(6);
if referenced_scenario(p, owner, app.selected).is_some() {
details = details.push(button(text("Open definition").size(12)).on_press_maybe(
clean.then_some(Message::ScenarioCanvas(CanvasEvent::OpenUse(
context,
app.selected,
))),
));
}
let details = details_pane(
context,
state.scroll_restore(context, ScrollArea::Page),
sequence_rows(p, context, owner, details, clean).into(),
);
let mut form_panel = editor_panel(
Id::nil(),
Space::new().height(0).into(),
Space::new().height(0).into(),
);
if let Some(d) = app
.behavior
.scenario
.draft
.as_ref()
.filter(|d| d.owner == owner)
{
if let Some(child) = d.source.view(p) {
form_panel = column![
text(format!(
"Consumer name: {}",
crate::views::short(&d.name, 60)
))
.size(12),
child.map(|e| event(Event::Source(e)))
]
.spacing(6)
.height(Fill)
.into();
} else {
let mut form = column![
text(d.tool.label()).size(16),
text_input("Name (defaults to selected source)", &d.name)
.id(NAME_INPUT)
.on_input(|s| event(Event::Name(s)))
.padding(9)
.size(12)
]
.spacing(9);
if d.tool != Tool::Lifeline {
form = form.push(label(format!(
"Insert: {}",
slot_label(
p,
Slot {
parent: d.parent,
before: d.before
}
)
)));
if d.before.is_some() {
form = form.push(
button("Append to this sequence instead")
.on_press(event(Event::AppendInstead)),
);
}
form = form.push(picker(
parents(p, owner),
Some(d.parent),
"Destination sequence / operand…",
Event::Parent,
));
}
if matches!(
d.tool,
Tool::Lifeline | Tool::Reuse | Tool::Action | Tool::Observation
) {
form = form.push(picker(
sources(p, d),
d.target,
"Choose a named source…",
Event::Target,
));
}
if d.tool == Tool::Lifeline {
if let Some(title) = d.source.label(d.target) {
form = form.push(label(title)).push(label(
"Create commits one new source and this lifeline together.",
));
}
if viewpoint(p, owner) != ScenarioViewpoint::MixedLegacy {
form = form.push(button("Create new source…").on_press(event(Event::Source(
super::super::source_draft::Event::Open(d.invocation),
))));
} else {
form=form.push(label("New source creation requires a strict viewpoint. Existing sources remain available."));
}
}
if d.tool == Tool::Message {
form = form.push(
pick_list(
vec![
MessageStyle::Asynchronous,
MessageStyle::Call,
MessageStyle::CallReply,
MessageStyle::Reply,
MessageStyle::Create,
MessageStyle::Delete,
MessageStyle::Timer,
],
Some(d.style),
|style| event(Event::Style(style)),
)
.width(Fill)
.padding(9)
.text_size(12),
);
if d.style == MessageStyle::Reply {
form = form.push(bounded_picker(
app.behavior.scenario.call_choices(p, context, d),
d,
d.call,
"Choose the earlier call…",
Event::Call,
));
if d.call.is_some() {
form = form.push(label(
"Reply reuses the call exchange in reverse and retains its correlation.",
));
}
} else if d.style != MessageStyle::Timer {
form = form.push(bounded_picker(
exchanges(p, d),
d,
d.exchange,
"Choose the exchange…",
Event::Exchange,
));
form = form.push(label(
"Apply checks that the message is valid at this insertion position.",
));
}
form = form.push(picker(
d.line_choices(p, true),
d.sender,
"Sending lifeline…",
Event::Sender,
));
if d.style != MessageStyle::Timer {
form = form.push(picker(
d.line_choices(p, false),
d.receiver,
"Receiving lifeline…",
Event::Receiver,
));
}
if d.style == MessageStyle::Timer {
form = form.push(
text_input("Duration / deadline, e.g. 30 s", &d.expression)
.on_input(|s| event(Event::Expression(s)))
.padding(9)
.size(12),
);
}
if p.layer_of(owner) == Some(Layer::Sa)
&& viewpoint(p, owner) == ScenarioViewpoint::BoundaryInterface
&& matches!(
d.style,
MessageStyle::Call | MessageStyle::CallReply | MessageStyle::Asynchronous
)
{
form = form.push(
iced::widget::checkbox(d.operation.is_some())
.label("Invoke a specific interface operation")
.on_toggle(|enabled| event(Event::OperationIntent(enabled))),
);
if let Some(operation) = &d.operation {
form = form
.push(bounded_picker(
crate::data_values::operation_choices(p, &d.proposed_message(p)),
d,
operation.allocation,
"Choose the exact interface operation allocation…",
Event::Operation,
))
.push(
button("Keep operation unresolved")
.on_press(event(Event::ClearOperation)),
);
if let Some(id) = operation.allocation {
form = form.push(label(crate::data_values::operation_identity(p, id)));
}
}
}
if let Some(description) =
crate::data_values::operation_label(p, &d.proposed_message(p))
{
form = form.push(label(description));
}
match d.signature(p) {
Ok(Some(exchange)) => form = form.push(value_panel(p, d, &exchange)),
Err(problem) => {
form = form.push(label(problem));
for (key, expression) in d.authored_values() {
form = form
.push(
text(format!(
"Retained value · {} / {}",
key.path
.iter()
.map(|id| p.named(*id))
.collect::<Vec<_>>()
.join(" → "),
p.named(key.field)
))
.size(11),
)
.push(
text_input("Value expression", expression)
.on_input({
let key = key.clone();
move |raw| event(Event::Value(key.clone(), raw))
})
.padding(8)
.size(12),
);
}
}
Ok(None) => {}
}
if d.style == MessageStyle::CallReply {
form=form.push(label("Creates the call and reversed, correlated reply together in one undoable operation."));
}
}
if matches!(d.tool, Tool::Action | Tool::Observation) {
form = form.push(picker(
lines(p, owner),
d.sender,
"Observed lifeline…",
Event::Sender,
));
}
if d.tool == Tool::Reuse
&& let Some(target) = d.target
{
for line in lines(p, target) {
let referenced = line.id;
let compatible: Vec<_> = lines(p, owner)
.into_iter()
.filter(|c| {
compatible_binding(p, referenced, c.id)
&& !d
.bindings
.iter()
.any(|(r, l)| *r != referenced && *l == c.id)
})
.collect();
if compatible.is_empty() {
form = form.push(label(format!(
"Add a compatible local lifeline before binding '{}'.",
p.named(referenced)
)));
}
form = form
.push(label(format!("Bind {}", p.named(referenced))))
.push(picker(
compatible,
d.bindings.get(&referenced).copied(),
"Compatible local lifeline…",
move |c| Event::Binding(referenced, c),
));
}
form = form.push(label(
"Bindings are explicit, one-to-one and refer to existing lifelines.",
));
}
if d.tool == Tool::Fragment {
form = form.push(
pick_list(
vec![
Operator(FragmentOperator::Alternative),
Operator(FragmentOperator::Parallel),
Operator(FragmentOperator::Loop),
Operator(FragmentOperator::Optional),
],
Some(Operator(d.operator)),
|o| event(Event::Operator(o)),
)
.padding(9)
.text_size(12)
.width(Fill),
);
if d.operator != FragmentOperator::Parallel {
form = form.push(
text_input("Condition / loop guard", &d.expression)
.on_input(|s| event(Event::Expression(s)))
.padding(9)
.size(12),
);
}
if d.operator == FragmentOperator::Alternative {
form = form.push(
text_input("Second alternative guard", &d.second_guard)
.on_input(|s| event(Event::SecondGuard(s)))
.padding(9)
.size(12),
);
}
form=form.push(label("Creates the fragment with its operands. Choose an operand as destination when adding messages or actions."));
}
let readiness = d.command(p);
if let Err(error) = &readiness {
form = form.push(label(error.clone()));
}
let footer = row![
button("Create")
.padding(9)
.on_press_maybe(readiness.is_ok().then_some(event(Event::Submit))),
action("Cancel", event(Event::Cancel))
]
.spacing(7);
let session = state.form_session().expect("visible scenario draft");
form_panel = sensor(editor_panel(session, footer.into(), form.into()))
.key(session)
.on_show(move |_| Message::ScenarioCanvas(CanvasEvent::FormShown(context, session)))
.into();
}
}
let editor = if pending {
Some(form_panel)
} else {
presentation.shelf.map(|_| details)
};
super::super::canvas_workspace::host(header.into(), palette, canvas, editor)
}
fn sequence_action<'a>(
title: &str,
message: Message,
enabled: bool,
) -> iced::widget::Button<'a, Message> {
button(text(title.to_owned()).size(12))
.padding(8)
.style(style::nav)
.on_press_maybe(enabled.then_some(message))
}
fn details_pane<'a, R: iced::advanced::text::Renderer + 'a>(
context: Context,
restore: Option<ScrollRestore>,
details: iced::Element<'a, Message, Theme, R>,
) -> iced::Element<'a, Message, Theme, R> {
scenario_scroll::observe(
context,
ScrollArea::Page,
restore,
scrollable(details)
.id("scenario-details")
.width(Fill)
.height(Fill),
)
}
fn editor_panel<'a, R: iced::advanced::text::Renderer + 'a>(
session: Id,
actions: iced::Element<'a, Message, Theme, R>,
fields: iced::Element<'a, Message, Theme, R>,
) -> iced::Element<'a, Message, Theme, R> {
container(
column![
container(actions).id("scenario-actions").width(Fill),
super::super::form_session::reset_on_change(
session,
scrollable(fields)
.id("scenario-form")
.width(Fill)
.height(Fill),
),
]
.spacing(6),
)
.padding(10)
.width(Fill)
.height(Fill)
.style(style::card)
.into()
}
#[cfg(all(test, debug_assertions))]
mod tests;
fn sequence_rows<'a>(
p: &'a Project,
context: Context,
owner: Id,
mut out: Column<'a, Message>,
enabled: bool,
) -> Column<'a, Message> {
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Fragment { branches, .. },
..
}) = p.elements.get(&owner).and_then(|e| e.shared())
{
for branch in branches {
out = out.push(sequence_action(
&format!("Operand: {}", p.named(*branch)),
Message::Select(*branch),
enabled,
));
out = sequence_rows(p, context, *branch, out, enabled);
}
}
if let Some(steps) = p.elements.get(&owner).and_then(|e| e.steps()) {
for (i, id) in steps.iter().enumerate() {
out = out.push(
row![
sequence_action(
&format!("{}. {}", i + 1, p.named(*id)),
Message::Select(*id),
enabled
)
.width(Fill),
button("↑")
.padding(8)
.on_press_maybe((enabled && i > 0).then_some(Message::Command(
Command::MoveStep(owner, i, i.saturating_sub(1))
))),
button("↓").padding(8).on_press_maybe(
(enabled && i + 1 < steps.len())
.then_some(Message::Command(Command::MoveStep(owner, i, i + 1)))
)
]
.spacing(6),
);
if let Some(SharedBody::Occurrence {
body:
OccurrenceBody::ScenarioUse {
scenario: Some(target),
..
},
..
}) = p.elements[id].shared()
{
out = out.push(sequence_action(
&format!("Open {} →", p.named(*target)),
Message::ScenarioCanvas(CanvasEvent::OpenUse(context, *id)),
enabled,
));
}
out = sequence_rows(p, context, *id, out, enabled);
}
}
out
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,283 @@
//! Read-only lifecycle geometry. Operand screen order is never execution order.
use oa_core::{FragmentOperator, Id, Kind, MessageKind, OccurrenceBody, Project, SharedBody};
use std::collections::{BTreeMap, BTreeSet};
/// Maps already recorded by the sequence renderer. Rows carry their owning sequence.
pub(crate) struct Geometry<'a> {
pub rows: &'a BTreeMap<Id, (Id, f32)>,
pub scopes: &'a BTreeMap<Id, (f32, f32)>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Span {
pub start: f32,
pub end: f32,
}
impl Span {
fn valid(self) -> bool {
self.start.is_finite() && self.end.is_finite() && self.start <= self.end
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Life {
Alive,
Absent,
Unresolved,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Interval {
pub scope: Id,
pub span: Span,
pub life: Life,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MarkerKind {
Birth,
Death,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Marker {
pub occurrence: Id,
pub scope: Id,
pub y: f32,
pub kind: MarkerKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UncertaintyReason {
Conditional,
Repeated,
Parallel,
MissingGeometry,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Uncertainty {
pub scope: Id,
pub reason: UncertaintyReason,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct LaneLifetime {
pub lifeline: Id,
pub intervals: Vec<Interval>,
pub markers: Vec<Marker>,
pub uncertainties: Vec<Uncertainty>,
}
/// Stable lane-ID order; source/model/history and caller-owned geometry are untouched.
/// An opaque ScenarioUse is a local use, not a caller birth/death contract.
pub(crate) fn project_lifetimes(
project: &Project,
scenario: Id,
geometry: &Geometry<'_>,
) -> Vec<LaneLifetime> {
if project
.elements
.get(&scenario)
.is_none_or(|e| e.kind() != Kind::Scenario)
{
return vec![];
}
project
.elements
.values()
.filter(|e| e.kind() == Kind::Lifeline && e.parent == Some(scenario))
.map(|e| {
let mut projection = Projection {
project,
geometry,
lane: e.id,
visiting: BTreeSet::new(),
result: LaneLifetime {
lifeline: e.id,
intervals: vec![],
markers: vec![],
uncertainties: vec![],
},
};
let initial = if projection.contains(scenario, Some(MarkerKind::Birth)) {
Life::Unresolved
} else {
Life::Alive
};
projection.sequence(scenario, initial);
projection.result
})
.collect()
}
struct Projection<'a, 'g> {
project: &'a Project,
geometry: &'a Geometry<'g>,
lane: Id,
visiting: BTreeSet<Id>,
result: LaneLifetime,
}
impl Projection<'_, '_> {
fn body(&self, id: Id) -> Option<&OccurrenceBody> {
match self.project.elements.get(&id)?.shared()? {
SharedBody::Occurrence { body, .. } => Some(body),
_ => None,
}
}
fn event(&self, id: Id) -> Option<MarkerKind> {
match self.body(id)? {
OccurrenceBody::Exchange {
receiver: Some(line),
message_kind,
..
} if *line == self.lane => match message_kind {
MessageKind::Create => Some(MarkerKind::Birth),
MessageKind::Delete => Some(MarkerKind::Death),
_ => None,
},
_ => None,
}
}
fn contains(&self, scope: Id, kind: Option<MarkerKind>) -> bool {
// Local structural walk only: no guards, iteration simulation or reuse expansion.
let mut pending = vec![scope];
let mut seen = BTreeSet::new();
while let Some(id) = pending.pop() {
if !seen.insert(id) {
continue;
}
if self
.event(id)
.is_some_and(|event| kind.is_none_or(|k| event == k))
{
return true;
}
if let Some(steps) = self.project.elements.get(&id).and_then(|e| e.steps()) {
pending.extend(steps);
}
if let Some(OccurrenceBody::Fragment { branches, .. }) = self.body(id) {
pending.extend(branches);
}
}
false
}
fn span(&self, scope: Id) -> Option<Span> {
let &(start, end) = self.geometry.scopes.get(&scope)?;
let span = Span { start, end };
span.valid().then_some(span)
}
fn uncertain(&mut self, scope: Id, reason: UncertaintyReason) {
let value = Uncertainty { scope, reason };
if !self.result.uncertainties.contains(&value) {
self.result.uncertainties.push(value);
}
}
fn interval(&mut self, scope: Id, start: f32, end: f32, life: Life) {
if start < end && start.is_finite() && end.is_finite() {
self.result.intervals.push(Interval {
scope,
span: Span { start, end },
life,
});
}
}
fn sequence(&mut self, scope: Id, entry: Life) -> Life {
let Some(span) = self.span(scope) else {
self.uncertain(scope, UncertaintyReason::MissingGeometry);
return Life::Unresolved;
};
if !self.visiting.insert(scope) {
self.uncertain(scope, UncertaintyReason::MissingGeometry);
return Life::Unresolved;
}
let steps = self
.project
.elements
.get(&scope)
.and_then(|e| e.steps())
.cloned()
.unwrap_or_default();
// A creation directly in this sequence fixes its local birth boundary.
// A creation only in a nested operand cannot fix its ancestor's entry.
let mut life = if steps
.iter()
.any(|&id| self.event(id) == Some(MarkerKind::Birth))
{
Life::Absent
} else {
entry
};
let mut cursor = span.start;
for id in steps {
let event = self.event(id);
let fragment = match self.body(id) {
Some(OccurrenceBody::Fragment { operator, branches }) => {
Some((*operator, branches.clone()))
}
_ => None,
};
if event.is_none() && fragment.is_none() {
continue;
}
let y = self
.geometry
.rows
.get(&id)
.filter(|(owner, y)| {
*owner == scope && y.is_finite() && *y >= cursor && *y <= span.end
})
.map(|(_, y)| *y);
let Some(y) = y else {
self.uncertain(id, UncertaintyReason::MissingGeometry);
life = Life::Unresolved;
continue;
};
self.interval(scope, cursor, y, life);
cursor = y;
if let Some(kind) = event {
self.result.markers.push(Marker {
occurrence: id,
scope,
y,
kind,
});
life = match kind {
MarkerKind::Birth => Life::Alive,
MarkerKind::Death => Life::Absent,
};
}
if let Some((operator, branches)) = fragment {
let entry = life;
let mut missing = false;
for branch in branches {
let bounds = self
.span(branch)
.filter(|s| s.start >= cursor && s.end <= span.end);
if let Some(bounds) = bounds {
// Every sibling inherits the same entry, never its displayed predecessor's exit.
self.sequence(branch, entry);
cursor = bounds.end;
} else {
self.uncertain(branch, UncertaintyReason::MissingGeometry);
missing = true;
}
}
if self.contains(id, None) {
let reason = match operator {
FragmentOperator::Alternative | FragmentOperator::Optional => {
UncertaintyReason::Conditional
}
FragmentOperator::Loop => UncertaintyReason::Repeated,
FragmentOperator::Parallel => UncertaintyReason::Parallel,
};
self.uncertain(id, reason);
life = Life::Unresolved;
} else if missing {
life = Life::Unresolved;
}
}
}
self.interval(scope, cursor, span.end, life);
self.visiting.remove(&scope);
life
}
}
#[cfg(test)]
#[path = "scenario_lifecycle/tests.rs"]
mod tests;
@@ -0,0 +1,470 @@
use super::*;
use oa_core::*;
struct Fixture {
p: Project,
owner: Id,
a: Id,
b: Id,
exchange: Id,
rows: BTreeMap<Id, (Id, f32)>,
scopes: BTreeMap<Id, (f32, f32)>,
}
impl Fixture {
fn new(layer: Layer) -> Self {
let mut p = Project::empty();
let kind = if layer == Layer::Oa {
Kind::Activity
} else {
Kind::Function
};
let a = p.add_element(kind, layer, "Request", None).unwrap();
let b = p.add_element(kind, layer, "Provide", None).unwrap();
let owner = p
.add_element(Kind::Scenario, layer, "Lifecycle", None)
.unwrap();
let exchange = p.relate(
if layer == Layer::Oa {
RelationKind::Interaction
} else {
RelationKind::FunctionalExchange
},
"Service",
a,
b,
);
let line = |p: &mut Project, represented| {
let id = p
.add_element(Kind::Lifeline, layer, "Participant", Some(owner))
.unwrap();
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::Lifeline {
represented: Some(represented),
};
id
};
let a = line(&mut p, a);
let b = line(&mut p, b);
Self {
p,
owner,
a,
b,
exchange,
rows: BTreeMap::new(),
scopes: [(owner, (0., 600.))].into(),
}
}
fn occurrence(&mut self, owner: Id, y: f32, body: OccurrenceBody) -> Id {
let mut e = self
.p
.make_element(
Kind::Occurrence,
self.p.elements[&owner].layer(),
"Occurrence",
Some(owner),
)
.unwrap();
let id = e.id;
*e.shared_mut().unwrap() = SharedBody::Occurrence {
body,
precondition: String::new(),
postcondition: String::new(),
};
self.p.elements.insert(id, e);
if let Some(steps) = self.p.elements.get_mut(&owner).unwrap().steps_mut() {
steps.push(id);
} else if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Fragment { branches, .. },
..
}) = self.p.elements.get_mut(&owner).unwrap().shared_mut()
{
branches.push(id);
}
self.rows.insert(id, (owner, y));
id
}
fn message(&mut self, owner: Id, y: f32, kind: MessageKind) -> Id {
self.occurrence(
owner,
y,
OccurrenceBody::Exchange {
exchange: Some(self.exchange),
sender: Some(self.a),
receiver: Some(self.b),
message_kind: kind,
operation: None,
reply_to: None,
values: vec![],
},
)
}
fn fragment(&mut self, owner: Id, y: f32, operator: FragmentOperator) -> Id {
self.occurrence(
owner,
y,
OccurrenceBody::Fragment {
operator,
branches: vec![],
},
)
}
fn branch(&mut self, fragment: Id, start: f32, end: f32) -> Id {
let id = self.occurrence(
fragment,
start,
OccurrenceBody::Branch {
guard: "condition".into(),
occurrences: vec![],
},
);
self.scopes.insert(id, (start, end));
id
}
fn project(&self) -> Vec<LaneLifetime> {
let errors: Vec<_> = validation::validate(&self.p)
.into_iter()
.filter(|i| i.severity == validation::Severity::Error)
.collect();
assert!(
errors.is_empty(),
"fixture must be ordinarily admitted: {errors:?}"
);
let before = self.p.clone();
let source = source_project::format_bundle(&self.p);
let geometry = Geometry {
rows: &self.rows,
scopes: &self.scopes,
};
let result = project_lifetimes(&self.p, self.owner, &geometry);
assert_eq!(result, project_lifetimes(&self.p, self.owner, &geometry));
assert_eq!(self.p, before);
assert_eq!(source_project::format_bundle(&self.p), source);
assert!(
result
.windows(2)
.all(|pair| pair[0].lifeline < pair[1].lifeline)
);
result
}
fn lane(&self) -> LaneLifetime {
self.project()
.into_iter()
.find(|lane| lane.lifeline == self.b)
.unwrap()
}
}
fn intervals(lane: &LaneLifetime, scope: Id) -> Vec<(f32, f32, Life)> {
lane.intervals
.iter()
.filter(|i| i.scope == scope)
.map(|i| (i.span.start, i.span.end, i.life))
.collect()
}
#[test]
fn root_lifetime_has_exact_birth_death_boundaries_without_source_mutation() {
for layer in [Layer::Oa, Layer::Sa] {
let mut f = Fixture::new(layer);
let create = f.message(f.owner, 100., MessageKind::Create);
f.message(f.owner, 200., MessageKind::Asynchronous);
let delete = f.message(f.owner, 300., MessageKind::Delete);
let lane = f.lane();
assert_eq!(
intervals(&lane, f.owner),
vec![
(0., 100., Life::Absent),
(100., 300., Life::Alive),
(300., 600., Life::Absent)
]
);
assert_eq!(
lane.markers,
vec![
Marker {
occurrence: create,
scope: f.owner,
y: 100.,
kind: MarkerKind::Birth
},
Marker {
occurrence: delete,
scope: f.owner,
y: 300.,
kind: MarkerKind::Death
},
]
);
let sender = f
.project()
.into_iter()
.find(|lane| lane.lifeline == f.a)
.unwrap();
assert_eq!(intervals(&sender, f.owner), vec![(0., 600., Life::Alive)]);
}
}
#[test]
fn alternative_death_does_not_kill_its_displayed_sibling() {
let mut f = Fixture::new(Layer::Sa);
let fragment = f.fragment(f.owner, 100., FragmentOperator::Alternative);
let left = f.branch(fragment, 120., 250.);
let right = f.branch(fragment, 300., 450.);
f.message(left, 200., MessageKind::Delete);
f.message(right, 350., MessageKind::Asynchronous);
let lane = f.lane();
assert_eq!(
intervals(&lane, left),
vec![(120., 200., Life::Alive), (200., 250., Life::Absent)]
);
assert_eq!(intervals(&lane, right), vec![(300., 450., Life::Alive)]);
assert_eq!(
intervals(&lane, f.owner),
vec![(0., 100., Life::Alive), (450., 600., Life::Unresolved)]
);
assert_eq!(
lane.uncertainties,
vec![Uncertainty {
scope: fragment,
reason: UncertaintyReason::Conditional
}]
);
}
#[test]
fn conditional_birth_does_not_infer_absence_in_siblings_or_ancestors() {
for operator in [FragmentOperator::Alternative, FragmentOperator::Optional] {
let mut f = Fixture::new(Layer::Oa);
let fragment = f.fragment(f.owner, 100., operator);
let left = f.branch(fragment, 120., 250.);
let right = f.branch(fragment, 300., 450.);
f.message(left, 200., MessageKind::Create);
let lane = f.lane();
assert_eq!(
intervals(&lane, left),
vec![(120., 200., Life::Absent), (200., 250., Life::Alive)]
);
assert_eq!(
intervals(&lane, right),
vec![(300., 450., Life::Unresolved)]
);
assert_eq!(
intervals(&lane, f.owner),
vec![(0., 100., Life::Unresolved), (450., 600., Life::Unresolved)]
);
}
}
#[test]
fn loop_lifetime_is_local_and_warning_bearing_loops_remain_drawable() {
for balanced in [true, false] {
let mut f = Fixture::new(Layer::Sa);
let fragment = f.fragment(f.owner, 100., FragmentOperator::Loop);
let iteration = f.branch(fragment, 120., 450.);
let create = f.message(iteration, 160., MessageKind::Create);
f.message(iteration, 250., MessageKind::Asynchronous);
if balanced {
f.message(iteration, 350., MessageKind::Delete);
}
let lane = f.lane();
assert_eq!(lane.markers.len(), if balanced { 2 } else { 1 });
assert_eq!(lane.markers[0].occurrence, create);
assert!(lane.uncertainties.contains(&Uncertainty {
scope: fragment,
reason: UncertaintyReason::Repeated
}));
assert_eq!(
intervals(&lane, f.owner).last().unwrap().2,
Life::Unresolved
);
assert_eq!(
validation::validate(&f.p)
.iter()
.any(|i| i.code == "lifeline_repetition"),
!balanced
);
}
}
#[test]
fn optional_cleanup_inside_loop_does_not_claim_balanced_or_definite_exit() {
let mut f = Fixture::new(Layer::Sa);
let repeated = f.fragment(f.owner, 100., FragmentOperator::Loop);
let iteration = f.branch(repeated, 120., 500.);
f.message(iteration, 160., MessageKind::Create);
let optional = f.fragment(iteration, 280., FragmentOperator::Optional);
let cleanup = f.branch(optional, 320., 400.);
f.message(cleanup, 350., MessageKind::Delete);
let lane = f.lane();
assert_eq!(
intervals(&lane, cleanup),
vec![(320., 350., Life::Alive), (350., 400., Life::Absent)]
);
assert_eq!(
intervals(&lane, iteration),
vec![
(120., 160., Life::Absent),
(160., 280., Life::Alive),
(400., 500., Life::Unresolved)
]
);
assert!(
validation::validate(&f.p)
.iter()
.any(|i| i.code == "lifeline_repetition")
);
assert!(lane.uncertainties.contains(&Uncertainty {
scope: optional,
reason: UncertaintyReason::Conditional
}));
assert!(lane.uncertainties.contains(&Uncertainty {
scope: repeated,
reason: UncertaintyReason::Repeated
}));
}
#[test]
fn lifecycle_free_fragments_do_not_poison_other_lanes() {
let mut f = Fixture::new(Layer::Oa);
let fragment = f.fragment(f.owner, 100., FragmentOperator::Parallel);
let left = f.branch(fragment, 120., 250.);
let right = f.branch(fragment, 300., 450.);
f.message(left, 200., MessageKind::Delete);
let result = f.project();
let sender = result.iter().find(|lane| lane.lifeline == f.a).unwrap();
assert!(sender.intervals.iter().all(|i| i.life == Life::Alive));
assert!(sender.uncertainties.is_empty());
let target = result.iter().find(|lane| lane.lifeline == f.b).unwrap();
assert!(target.uncertainties.contains(&Uncertainty {
scope: fragment,
reason: UncertaintyReason::Parallel
}));
assert_eq!(intervals(target, right), vec![(300., 450., Life::Alive)]);
}
#[test]
fn explicit_receiver_is_authoritative_even_with_missing_exchange() {
let mut f = Fixture::new(Layer::Oa);
let create = f.message(f.owner, 100., MessageKind::Create);
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { exchange, .. },
..
}) = f.p.elements.get_mut(&create).unwrap().shared_mut()
{
*exchange = None;
}
assert_eq!(f.lane().markers[0].occurrence, create);
if let Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
receiver, exchange, ..
},
..
}) = f.p.elements.get_mut(&create).unwrap().shared_mut()
{
*receiver = None;
*exchange = Some(f.exchange);
}
assert!(
f.lane().markers.is_empty(),
"exchange endpoints never invent a receiver"
);
}
#[test]
fn missing_geometry_is_reported_without_nonfinite_or_guessed_markers() {
let mut f = Fixture::new(Layer::Oa);
let create = f.message(f.owner, 100., MessageKind::Create);
f.rows.insert(create, (f.owner, f32::NAN));
let lane = f.lane();
assert!(lane.markers.is_empty());
assert_eq!(
lane.uncertainties,
vec![Uncertainty {
scope: create,
reason: UncertaintyReason::MissingGeometry
}]
);
assert_eq!(
intervals(&lane, f.owner),
vec![(0., 600., Life::Unresolved)]
);
f.scopes.remove(&f.owner);
let lane = f.lane();
assert!(lane.intervals.is_empty());
assert_eq!(lane.uncertainties[0].scope, f.owner);
}
#[test]
fn scenario_use_is_opaque_and_never_imports_callee_lifecycle_events() {
let mut f = Fixture::new(Layer::Oa);
let callee =
f.p.add_element(Kind::Scenario, Layer::Oa, "Callee", None)
.unwrap();
let remote_a =
f.p.add_element(Kind::Lifeline, Layer::Oa, "Remote A", Some(callee))
.unwrap();
let remote_b =
f.p.add_element(Kind::Lifeline, Layer::Oa, "Remote B", Some(callee))
.unwrap();
for (remote, local) in [(remote_a, f.a), (remote_b, f.b)] {
let body = f.p.elements[&local].shared().unwrap().clone();
*f.p.elements.get_mut(&remote).unwrap().shared_mut().unwrap() = body;
}
f.occurrence(
callee,
200.,
OccurrenceBody::Exchange {
exchange: Some(f.exchange),
sender: Some(remote_a),
receiver: Some(remote_b),
message_kind: MessageKind::Create,
operation: None,
reply_to: None,
values: vec![],
},
);
f.occurrence(
f.owner,
100.,
OccurrenceBody::ScenarioUse {
scenario: Some(callee),
bindings: vec![
LifelineBinding {
referenced: remote_a,
local: f.a,
},
LifelineBinding {
referenced: remote_b,
local: f.b,
},
],
},
);
let lane = f.lane();
assert_eq!(intervals(&lane, f.owner), vec![(0., 600., Life::Alive)]);
assert!(lane.markers.is_empty());
assert!(lane.uncertainties.is_empty());
}
#[test]
fn projection_retains_exact_authored_source_and_does_not_enter_history() {
use crate::document::Document;
let mut f = Fixture::new(Layer::Oa);
f.message(f.owner, 100., MessageKind::Create);
f.message(f.owner, 300., MessageKind::Delete);
let mut source = source_project::format_bundle(&f.p);
let text = source.files.get_mut(&source.entry).unwrap();
*text = format!("// Retained author note — 雨\r\n{text}\n");
let document =
Document::from_bundle(source.clone(), source_project::ProjectLimits::default()).unwrap();
let accepted = document.project().clone();
let geometry = Geometry {
rows: &f.rows,
scopes: &f.scopes,
};
let result = project_lifetimes(document.project(), f.owner, &geometry);
assert_eq!(result, f.project());
assert_eq!(document.bundle(), &source);
assert_eq!(document.project(), &accepted);
assert!(!document.can_undo());
assert!(!document.can_redo());
}
@@ -0,0 +1,488 @@
//! A prerequisite belongs to its pending consumer, never the accepted catalog.
use iced::{
Element as UiElement, Fill,
widget::{button, column, container, row, scrollable, text, text_input},
};
use oa_core::*;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
pub const NAME_INPUT: &str = "behavior-source-name";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Scope {
Lifeline {
owner: Id,
viewpoint: ScenarioViewpoint,
},
Work {
owner: Id,
},
Machine {
layer: Layer,
},
}
impl Scope {
fn owner(self) -> Option<Id> {
match self {
Self::Lifeline { owner, .. } | Self::Work { owner } => Some(owner),
Self::Machine { .. } => None,
}
}
fn layer(self, p: &Project) -> Result<Layer, String> {
match self {
Self::Machine { layer } => Ok(layer),
_ => p
.layer_of(self.owner().unwrap())
.ok_or("The consumer owner no longer exists.".into()),
}
}
fn kinds(self, layer: Layer) -> Vec<Kind> {
match self {
Self::Work { .. } => vec![if layer == Layer::Oa {
Kind::Activity
} else {
Kind::Function
}],
Self::Lifeline {
viewpoint: ScenarioViewpoint::OperationalActivity,
..
} => vec![Kind::Activity],
Self::Lifeline {
viewpoint: ScenarioViewpoint::Functional,
..
} => vec![Kind::Function],
Self::Lifeline {
viewpoint: ScenarioViewpoint::ParticipantInteraction,
..
} => vec![Kind::Entity, Kind::Actor, Kind::Role],
Self::Lifeline {
viewpoint: ScenarioViewpoint::BoundaryInterface,
..
} => vec![Kind::System, Kind::SystemActor],
Self::Machine { .. } if layer == Layer::Oa => vec![Kind::Entity, Kind::Actor],
Self::Machine { .. } => vec![Kind::System, Kind::SystemActor],
_ => vec![],
}
}
}
#[derive(Debug, Clone)]
pub enum Event {
Open(Id),
Edit(Id, Edit),
}
#[derive(Debug, Clone)]
pub enum Edit {
Name(String),
Kind(Kind),
Parent(Option<Id>),
Search(String),
Page(usize),
Back,
Use,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Draft {
token: Id,
document: Id,
scope: Scope,
layer: Layer,
owner: Option<Element>,
id: Id,
kind: Option<Kind>,
name: String,
parent: Option<Element>,
search: String,
page: usize,
identities: Vec<Id>,
}
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct State {
editing: Option<Draft>,
staged: Option<Draft>,
#[serde(default)]
engaged: bool,
}
impl State {
pub fn check_scope(&self, expected: Scope, selected: Option<Id>) -> Result<(), String> {
if self
.editing
.as_ref()
.or_else(|| self.staged.as_ref().filter(|d| Some(d.id) == selected))
.is_some_and(|d| d.scope != expected)
{
return Err("The recovered source request belongs to a different consumer context. Go Back or cancel this draft.".into());
}
Ok(())
}
pub fn dismiss(&mut self, event: &Event) -> Result<bool, String> {
if let Event::Edit(token, Edit::Back) = event {
if self.editing.as_ref().is_none_or(|d| d.token != *token) {
return Err("This Back action belongs to a previous source form.".into());
}
self.editing = None;
self.engaged = true;
return Ok(true);
}
Ok(false)
}
pub fn engaged(&self) -> bool {
self.engaged || self.editing.is_some() || self.staged.is_some()
}
pub fn is_open(&self) -> bool {
self.editing.is_some()
}
pub fn back(&mut self) -> bool {
self.editing.take().is_some()
}
pub fn label(&self, selected: Option<Id>) -> Option<String> {
self.staged
.as_ref()
.filter(|d| Some(d.id) == selected)
.map(|d| {
format!(
"New · {} · {}",
d.kind.map_or("Choose kind".into(), |k| k.to_string()),
d.name
)
})
}
pub fn update(
&mut self,
p: &Project,
scope: Scope,
invocation: Id,
event: Event,
) -> Result<Option<Id>, String> {
if self.dismiss(&event)? {
return Ok(None);
}
match event {
Event::Open(token) => {
if token != invocation || self.is_open() {
return Err("This source request is stale. Use the current form.".into());
}
let layer = scope.layer(p)?;
let kinds = scope.kinds(layer);
if kinds.is_empty() {
return Err("Create new sources requires a strict scenario viewpoint; use an existing source here.".into());
}
self.engaged = true;
self.editing = Some(Draft {
token: Id::new_v4(),
document: p.id,
scope,
layer,
owner: scope.owner().and_then(|id| p.elements.get(&id).cloned()),
id: Id::new_v4(),
kind: (kinds.len() == 1).then_some(kinds[0]),
name: String::new(),
parent: None,
search: String::new(),
page: 0,
identities: (0..match scope {
Scope::Work { owner } => p.children(owner).count() + 4,
Scope::Lifeline { .. } => 1,
Scope::Machine { .. } => 0,
})
.map(|_| Id::new_v4())
.collect(),
});
Ok(None)
}
Event::Edit(token, edit) => {
let d = self
.editing
.as_mut()
.filter(|d| d.token == token && d.scope == scope && d.document == p.id)
.ok_or("This source response is stale; return to the current form.")?;
match edit {
Edit::Back => {
self.editing = None;
Ok(None)
}
Edit::Use => {
d.command(p)?;
let id = d.id;
self.staged = self.editing.take();
Ok(Some(id))
}
Edit::Name(name) => {
d.name = name;
Ok(None)
}
Edit::Kind(kind) => {
if !scope.kinds(d.layer).contains(&kind) {
return Err("Choose an explicitly supported source kind.".into());
}
d.kind = Some(kind);
d.parent = None;
d.page = 0;
Ok(None)
}
Edit::Parent(parent) => {
let kind = d.kind.ok_or("Choose the source kind first.")?;
if !validation::can_parent(p, kind, d.layer, parent) {
return Err("Choose a valid semantic parent.".into());
}
d.parent = parent.map(|id| p.elements[&id].clone());
Ok(None)
}
Edit::Search(query) => {
d.search = query;
d.page = 0;
Ok(None)
}
Edit::Page(page) => {
d.page = page;
Ok(None)
}
}
}
}
}
pub fn preview(&self, p: &Project, selected: Option<Id>) -> Result<Option<Project>, String> {
if self.is_open() {
return Err("Use this new source or go Back before creating the consumer.".into());
}
self.staged
.as_ref()
.filter(|d| Some(d.id) == selected)
.map(|d| execute_batch(p, &[d.command(p)?]).map_err(|e| e.to_string()))
.transpose()
}
pub fn combine(
&self,
p: &Project,
selected: Option<Id>,
command: Command,
) -> Result<Command, String> {
let Some(d) = self.staged.as_ref().filter(|d| Some(d.id) == selected) else {
return Ok(command);
};
let preview = execute_batch(p, &[d.command(p)?]).map_err(|e| e.to_string())?;
let mut commands = match command {
Command::Batch(commands) => commands,
other => vec![other],
};
let fresh: Vec<_> = commands
.iter()
.filter(|_| !matches!(d.scope, Scope::Machine { .. }))
.filter_map(|c| match c {
Command::CreateElement(e) => Some(e.id),
Command::CreateRelation(r) => Some(r.id),
_ => None,
})
.collect();
if fresh.len() > d.identities.len() {
return Err(
"The path grew beyond this draft. Return and create the source again.".into(),
);
}
let replacements: BTreeMap<_, _> = fresh
.into_iter()
.zip(d.identities.iter().copied())
.collect();
if replacements.values().any(|id| preview.contains(*id)) {
return Err(
"A reserved consumer identity is already used. Start a fresh source draft.".into(),
);
}
let remap = |id: &mut Id| {
if let Some(new) = replacements.get(id) {
*id = *new;
}
};
for c in &mut commands {
match c {
Command::CreateElement(e) => {
remap(&mut e.id);
references::visit_element_refs(e, remap);
e.alias = preview.fresh_alias(&e.name, "contribution", e.id);
}
Command::CreateRelation(r) => {
remap(&mut r.id);
references::visit_relation_refs(r, remap);
r.alias = preview.fresh_alias(&r.name, "path", r.id);
}
Command::EditRelation(_, r) => references::visit_relation_refs(r, remap),
Command::SetSteps(_, steps) => steps.iter_mut().for_each(remap),
// Machine commands already carry their reserved identities.
Command::CreateDiagram(_) | Command::Layout(_) => {}
_ => return Err("Unsupported prerequisite consumer operation.".into()),
}
}
commands.insert(0, d.command(p)?);
let command = super::topology::unique_batch(p, commands);
execute_batch(p, std::slice::from_ref(&command)).map_err(|e| e.to_string())?;
Ok(command)
}
pub fn view<'a, R: iced::advanced::text::Renderer + 'a>(
&'a self,
p: &'a Project,
) -> Option<UiElement<'a, Event, iced::Theme, R>> {
let d = self.editing.as_ref()?;
let event = move |edit| Event::Edit(d.token, edit);
let mut fields = column![
text(format!("New source · {}", d.layer)).size(18),
text(match d.scope {
Scope::Lifeline { owner, viewpoint } =>
format!("For a lifeline in {} · {:?}", p.named(owner), viewpoint),
Scope::Work { owner } => format!("For a contribution in {}", p.named(owner)),
Scope::Machine { .. } => "Owner for the pending state machine".into(),
})
.size(12),
text("The parent form is retained. This source is created only with its consumer.")
.size(12)
]
.spacing(8);
for kind in d.scope.kinds(d.layer) {
fields = fields.push(
button(text(kind.to_string()))
.on_press(event(Edit::Kind(kind)))
.style(if d.kind == Some(kind) {
button::primary
} else {
button::secondary
}),
);
}
fields = fields.push(
text_input("Source name (independent of the consumer name)", &d.name)
.id(NAME_INPUT)
.on_input(move |v| event(Edit::Name(v)))
.padding(8),
);
fields = fields.push(
text(format!(
"Semantic parent: {}",
d.parent
.as_ref()
.map_or(format!("{} layer root", d.layer), |e| format!(
"{} · {} · @{}",
e.name,
e.kind(),
e.alias
))
))
.size(12),
);
if let Some(kind) = d.kind {
fields = fields.push(button("Use layer root").on_press_maybe(
validation::can_parent(p, kind, d.layer, None).then(|| event(Edit::Parent(None))),
));
fields = fields.push(
text_input("Find a semantic parent (optional)", &d.search)
.on_input(move |v| event(Edit::Search(v)))
.padding(6),
);
let query = d.search.to_lowercase();
let mut parents: Vec<_> = p
.elements
.values()
.filter(|e| validation::can_parent(p, kind, d.layer, Some(e.id)))
.map(|e| (e.id, super::creation::reference_label(p, e.id)))
.filter(|(_, label)| label.to_lowercase().contains(&query))
.collect();
parents.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
let page = d.page.min(parents.len().saturating_sub(1) / 6);
for (id, label) in parents.iter().skip(page * 6).take(6) {
fields = fields.push(
button(text(label.clone()).size(12))
.on_press(event(Edit::Parent(Some(*id))))
.width(Fill),
);
}
if parents.len() > 6 {
fields = fields.push(
row![
button("Previous").on_press_maybe(
(page > 0).then(|| event(Edit::Page(page.saturating_sub(1))))
),
text(format!("{} / {}", page + 1, parents.len().div_ceil(6))),
button("Next").on_press_maybe(
((page + 1) * 6 < parents.len()).then(|| event(Edit::Page(page + 1)))
)
]
.spacing(6),
);
}
}
let ready = d.command(p);
if let Err(error) = &ready {
fields = fields.push(text(error.clone()).size(12));
}
Some(
container(
column![
scrollable(fields).id("behavior-source-fields").height(Fill),
container(
row![
button("Back · Esc").on_press(event(Edit::Back)),
button("Use this new source")
.on_press_maybe(ready.is_ok().then(|| event(Edit::Use)))
]
.spacing(8)
)
.id("behavior-source-actions")
]
.spacing(10),
)
.padding(12)
.height(Fill)
.width(Fill)
.into(),
)
}
}
impl Draft {
fn command(&self, p: &Project) -> Result<Command, String> {
if self.document != p.id
|| self.scope.layer(p)? != self.layer
|| self
.owner
.as_ref()
.is_some_and(|e| p.elements.get(&e.id) != Some(e))
{
return Err(
"The source request's document or consumer changed. Go Back and reopen Create new."
.into(),
);
}
let kind = self
.kind
.filter(|kind| self.scope.kinds(self.layer).contains(kind))
.ok_or("Choose the source kind explicitly.")?;
if self.name.trim().is_empty() {
return Err("Enter the source name.".into());
}
if p.contains(self.id) {
return Err(
"The reserved source identity is already used. Go Back and start again.".into(),
);
}
let parent = self.parent.as_ref().map(|e| e.id);
if self
.parent
.as_ref()
.is_some_and(|e| p.elements.get(&e.id) != Some(e))
|| !validation::can_parent(p, kind, self.layer, parent)
{
return Err("The semantic parent changed. Choose its intended parent again.".into());
}
let e = Element {
id: self.id,
alias: p.fresh_alias(&self.name, "source", self.id),
name: self.name.clone(),
description: String::new(),
parent,
body: ElementBody::new(kind, self.layer)
.ok_or("This source kind is unavailable in this layer.")?,
};
let command = Command::CreateElement(e);
execute_batch(p, std::slice::from_ref(&command)).map_err(|e| e.to_string())?;
Ok(command)
}
}
+133 -4
View File
@@ -38,6 +38,7 @@ impl Tool {
}
#[derive(Debug, Clone)]
pub enum Event {
Source(super::source_draft::Event),
Start(Id, Tool, Option<Id>),
Cancel,
Submit,
@@ -80,9 +81,10 @@ pub struct State {
tool: CanvasTool,
expanded: BTreeSet<Id>,
scroll_offsets: [iced::Vector; 2],
return_to: Vec<(Id, Id, Option<oa_core::topology_context::ContextAddress>)>,
return_to: Vec<direct::ReturnFrame>,
draft: Option<Draft>,
viewport: Option<Size>,
pan: iced::Vector,
zoom: Option<f32>,
fit: bool,
pub(crate) focused: bool,
@@ -90,15 +92,22 @@ pub struct State {
selected_context: Option<oa_core::topology_context::ContextAddress>,
shelf: Option<Shelf>,
}
#[derive(Default, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Browser {
search: String,
page: usize,
}
#[derive(serde::Serialize, serde::Deserialize)]
#[derive(Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Draft {
#[serde(default)]
source: super::source_draft::State,
#[serde(default = "Id::new_v4")]
invocation: Id,
#[serde(default)]
source_origin: Option<(Id, oa_core::Element)>,
#[serde(with = "recovery_insertion")]
insertion: Insertion,
fixed: bool,
@@ -117,6 +126,40 @@ struct Draft {
contextual: Option<contextual::Draft>,
}
impl State {
pub(crate) fn camera_boundary(&self) -> impl PartialEq + use<> {
(
self.tool,
self.focused,
self.shelf,
self.viewport,
self.pan,
self.zoom,
self.fit,
)
}
pub(super) fn pending_name(&self) -> Option<&str> {
self.draft.as_ref().map(|d| d.name.as_str())
}
pub(super) fn source_view<'a>(&'a self, p: &'a Project) -> Option<iced::Element<'a, Event>> {
self.draft
.as_ref()?
.source
.view(p)
.map(|v| v.map(Event::Source))
}
pub fn source_active(&self) -> bool {
self.draft.as_ref().is_some_and(|d| d.source.engaged())
}
pub fn source_open(&self) -> bool {
self.draft.as_ref().is_some_and(|d| d.source.is_open())
}
pub fn source_back(&mut self) -> bool {
self.draft.as_mut().is_some_and(|d| d.source.back())
}
pub(super) fn recovery_snapshot(&self) -> Result<Option<serde_json::Value>, String> {
self.draft
.as_ref()
@@ -152,6 +195,58 @@ impl State {
}
pub fn update(&mut self, p: &Project, event: Event) -> Result<Option<Command>, String> {
if let Event::Source(event) = event {
if self
.draft
.as_mut()
.ok_or("Start the consumer form first.")?
.source
.dismiss(&event)?
{
return Ok(None);
}
let d = self
.draft
.as_ref()
.ok_or("Start the consumer form first.")?;
if d.tool != Tool::Work {
return Err("This reference does not support staged source creation.".into());
}
if d.source_origin.as_ref().is_some_and(|(document, owner)| {
*document != p.id || p.elements.get(&d.owner) != Some(owner)
}) {
return Err("The original consumer changed. Cancel and reopen its form; the current draft is retained.".into());
}
if d.source_origin.is_none() && d.source.engaged() {
return Err("The recovered source draft has no original document binding. Go Back or cancel it.".into());
}
let mut next = d.clone();
if next.source_origin.is_none() && matches!(&event, super::source_draft::Event::Open(_))
{
next.source_origin = Some((
p.id,
p.elements
.get(&d.owner)
.ok_or("The consumer owner no longer exists.")?
.clone(),
));
}
if let Some(id) = next.source.update(
p,
super::source_draft::Scope::Work { owner: d.owner },
d.invocation,
event,
)? {
next.target = Some(id);
next.command(p)?;
}
self.draft = Some(next);
return Ok(None);
}
if self.source_open() && !matches!(&event, Event::Cancel) {
return Err("Use the new source or go Back before editing the parent form.".into());
}
if self.draft.is_some() && matches!(&event, Event::Start(..)) {
return Err(PENDING_DRAFT.into());
}
@@ -184,6 +279,9 @@ impl State {
}
});
self.draft = Some(Draft {
source: Default::default(),
invocation: Id::new_v4(),
source_origin: Some((p.id, p.elements[&owner].clone())),
insertion: Insertion::default(),
fixed: false,
browsers: Default::default(),
@@ -263,10 +361,12 @@ impl State {
)
}
#[cfg(test)]
fn canvas_offset(&self) -> iced::Vector {
self.scroll_offsets[0]
}
#[cfg(test)]
fn fit_limited(&self, graph: Size, fallback_width: f32) -> bool {
let available = self.fit_area(fallback_width);
self.fit && (graph.width * 0.05 > available.width || graph.height * 0.05 > available.height)
@@ -508,6 +608,22 @@ fn link(p: &Project, source: Id, target: Id, guard: &str) -> Command {
}
impl Draft {
fn command(&self, p: &Project) -> Result<Command, String> {
if self.source.engaged()
&& self.source_origin.as_ref().is_none_or(|(document, owner)| {
*document != p.id || p.elements.get(&self.owner) != Some(owner)
})
{
return Err("The original consumer document or owner changed. Cancel and reopen its form; your draft is retained.".into());
}
self.source.check_scope(
super::source_draft::Scope::Work { owner: self.owner },
self.target,
)?;
let preview = self.source.preview(p, self.target)?;
let command = self.consumer_command(preview.as_ref().unwrap_or(p))?;
self.source.combine(p, self.target, command)
}
fn consumer_command(&self, p: &Project) -> Result<Command, String> {
let owner = p
.elements
.get(&self.owner)
@@ -615,6 +731,8 @@ impl Draft {
});
let name = if self.name.trim().is_empty() {
default_name
} else if self.source.label(self.target).is_some() {
self.name.as_str()
} else {
self.name.trim()
};
@@ -867,6 +985,8 @@ struct Graph<'a> {
project: &'a Project,
interaction: Option<(Context, CanvasTool, bool)>,
scroll_offset: iced::Vector,
camera_pan: iced::Vector,
pending_insertion: Option<Insertion>,
nodes: Vec<GraphNode>,
edges: Vec<GraphEdge>,
ordered_paths: Vec<OrderedPath>,
@@ -1199,6 +1319,8 @@ impl<'a> Graph<'a> {
project: p,
interaction: None,
scroll_offset: iced::Vector::ZERO,
camera_pan: iced::Vector::ZERO,
pending_insertion: None,
nodes,
edges,
ordered_paths,
@@ -1298,6 +1420,7 @@ impl canvas::Program<Message> for Graph<'_> {
) -> Vec<canvas::Geometry> {
let mut f = Frame::new(renderer, bounds.size());
f.fill_rectangle(Point::ORIGIN, bounds.size(), Color::WHITE);
f.translate(self.camera_pan);
f.scale(self.scale);
for pass in PAINT_PASSES {
match pass {
@@ -1513,7 +1636,10 @@ impl canvas::Program<Message> for Graph<'_> {
cursor: mouse::Cursor,
) -> mouse::Interaction {
if cursor.position_in(bounds).is_some_and(|p| {
let p = Point::new(p.x / self.scale, p.y / self.scale);
let p = Point::new(
(p.x - self.camera_pan.x) / self.scale,
(p.y - self.camera_pan.y) / self.scale,
);
self.nodes.iter().any(|n| n.rect.contains(p))
|| self.ordered_paths.iter().any(|path| {
path.points.windows(2).any(|pair| {
@@ -1587,6 +1713,9 @@ mod tests {
}
fn branch(owner: Id, a: Id, b: Id, before: Id, after: Id) -> Draft {
Draft {
source: Default::default(),
invocation: Id::new_v4(),
source_origin: None,
insertion: Insertion::default(),
fixed: false,
browsers: Default::default(),
@@ -33,7 +33,7 @@ pub enum Event {
Search(String),
Page(usize),
}
#[derive(Default, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Draft {
edit: Option<Id>,
@@ -608,7 +608,11 @@ mod tests {
"Authored endpoint is retained for explicit repair"
);
assert!(state.prepare_pending(&deleted).is_err());
state.remember(owner, reference);
state.remember(
owner,
reference,
super::super::direct::referenced(&p, owner, reference).unwrap(),
);
assert_eq!(state.back(&deleted), Some((owner, reference)));
assert!(state.selected_context.is_none());
state.draft = None;
+145 -28
View File
@@ -60,6 +60,7 @@ pub enum CanvasEvent {
Open(Context, Id),
Back(Context),
Zoom(Context, Option<f32>),
Camera(Context, u64, super::super::canvas_workspace::Event),
Focus(Context),
Viewport(Context, Size),
}
@@ -77,6 +78,7 @@ impl CanvasEvent {
| Self::Back(c)
| Self::AppendExchange(c)
| Self::Zoom(c, ..)
| Self::Camera(c, ..)
| Self::Focus(c)
| Self::Viewport(c, ..) => *c,
Self::Begin { context, .. }
@@ -86,6 +88,19 @@ impl CanvasEvent {
}
}
}
pub(super) struct ReturnFrame {
identity: Option<(Id, Id)>,
owner: Id,
occurrence: Id,
target: Id,
address: Option<oa_core::topology_context::ContextAddress>,
pan: iced::Vector,
zoom: Option<f32>,
fit: bool,
viewport: Option<Size>,
expanded: BTreeSet<Id>,
contextual_expanded: BTreeSet<OccurrenceEndpoint>,
}
impl State {
pub(crate) fn select_context(&mut self, address: oa_core::topology_context::ContextAddress) {
self.selected_context = Some(address);
@@ -138,6 +153,7 @@ impl State {
if self.identity != Some((document, owner)) {
self.identity = Some((document, owner));
self.tool = CanvasTool::Select;
self.pan = iced::Vector::ZERO;
self.zoom = Some(1.);
self.fit = false;
self.viewport = None;
@@ -162,11 +178,21 @@ impl State {
// Choosing how to edit must retain the user's current view.
self.tool = tool;
}
pub(crate) fn camera(&mut self, event: super::super::canvas_workspace::Event) -> bool {
super::super::canvas_workspace::change(&mut self.pan, &mut self.zoom, &mut self.fit, event)
}
pub(crate) fn zoom(&mut self, value: Option<f32>) {
self.fit = value.is_none();
self.zoom = value.map(|v| v.clamp(0.5, 2.));
self.zoom = value.map(|v| v.clamp(0.05, 3.));
}
pub(crate) fn viewport(&mut self, size: Size) -> bool {
if !size.width.is_finite()
|| !size.height.is_finite()
|| size.width <= 0.
|| size.height <= 0.
{
return false;
}
let changed = self.viewport != Some(size);
self.viewport = Some(size);
changed
@@ -188,26 +214,83 @@ impl State {
}
true
}
pub(crate) fn remember(&mut self, owner: Id, occurrence: Id) {
self.return_to
.push((owner, occurrence, self.selected_context.clone()));
pub(crate) fn remember(&mut self, owner: Id, occurrence: Id, target: Id) {
if self.return_to.len() == 32 {
self.return_to.remove(0);
}
self.return_to.push(ReturnFrame {
identity: self.identity,
owner,
occurrence,
target,
address: self.selected_context.clone(),
pan: self.pan,
zoom: self.zoom,
fit: self.fit,
viewport: self.viewport,
expanded: self.expanded.clone(),
contextual_expanded: self.contextual_expanded.clone(),
});
}
pub(crate) fn back(&mut self, p: &Project) -> Option<(Id, Id)> {
while let Some((owner, occurrence, address)) = self.return_to.pop() {
if is_contribution(p, owner, occurrence) {
self.selected_context = address.filter(|address| {
address.owner == owner
&& oa_core::topology_context::TopologyIndex::new(p)
.resolve(owner, &address.endpoint)
.is_ok()
while let Some(frame) = self.return_to.pop() {
if frame.identity.map(|i| i.0) != self.identity.map(|i| i.0) {
continue;
}
let valid = referenced(p, frame.owner, frame.occurrence) == Some(frame.target)
|| if let Some(address) = &frame.address {
oa_core::topology_context::TopologyIndex::new(p)
.resolve(frame.owner, &address.endpoint)
.is_ok_and(|r| r.defining_sequence == frame.target)
} else {
false
};
if valid && is_contribution(p, frame.owner, frame.occurrence) {
self.identity = frame.identity;
self.selected_context = frame.address.filter(|a| {
oa_core::topology_context::TopologyIndex::new(p)
.resolve(frame.owner, &a.endpoint)
.is_ok()
});
return Some((owner, occurrence));
self.pan = frame.pan;
self.zoom = frame.zoom;
self.fit = frame.fit;
self.viewport = frame.viewport;
self.expanded = frame.expanded;
self.contextual_expanded = frame.contextual_expanded;
return Some((frame.owner, frame.occurrence));
}
}
None
}
pub(crate) fn created_selection(&self, command: &Command) -> Option<Id> {
pub(crate) fn camera_zoom(&mut self, p: &Project, owner: Id, zoom: Option<f32>) {
let graph =
Graph::expanded_qualified(p, owner, owner, &self.expanded, &self.contextual_expanded);
let old = self.scale(graph.size, 500.);
if let Some(next) = zoom {
let size = self.viewport.unwrap_or(Size::new(500., 300.));
self.camera(super::super::canvas_workspace::Event::Zoom {
factor: next / old,
at: Point::new(size.width / 2., size.height / 2.),
base: old,
});
} else {
self.zoom(None);
let fitted = self.scale(graph.size, 500.);
self.zoom(Some(fitted));
self.pan = iced::Vector::ZERO;
}
}
pub(crate) fn created_selection(&self, p: &Project, command: &Command) -> Option<Id> {
let owner = self.pending_owner()?;
if self
.draft
.as_ref()
.is_some_and(|d| d.source.label(d.target).is_some())
&& self.prepare_pending(p).ok().as_ref() != Some(command)
{
return None;
}
if let Command::CreateRelation(r) | Command::EditRelation(_, r) = command
&& matches!(&r.body, RelationBody::ContextualLink { owner: caller, .. } if *caller == owner)
{
@@ -567,9 +650,12 @@ impl Graph<'_> {
}
_ => cursor,
};
let world = cursor
.position_in(bounds)
.map(|p| Point::new(p.x / self.scale, p.y / self.scale));
let world = cursor.position_in(bounds).map(|p| {
Point::new(
(p.x - self.camera_pan.x) / self.scale,
(p.y - self.camera_pan.y) / self.scale,
)
});
let publish = |event| Some(Action::publish(Message::TopologyCanvas(event)).and_capture());
match event {
canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) if visible => {
@@ -722,6 +808,22 @@ impl Graph<'_> {
let Some((context, tool, editable)) = self.interaction else {
return;
};
if let Some(insertion) = self.pending_insertion {
if let Some(edge) = insertion
.link
.and_then(|id| self.edges.iter().find(|e| e.id == id))
{
draw_arrow(f, &edge.points, style::TEAL, 3.);
} else if let Some(node) = insertion
.before
.and_then(|id| self.nodes.iter().find(|n| n.id == id))
{
f.stroke(
&Path::rounded_rectangle(node.rect.position(), node.rect.size(), 10.into()),
Stroke::default().with_color(style::TEAL).with_width(3.),
);
}
}
if !editable {
return;
}
@@ -730,7 +832,12 @@ impl Graph<'_> {
.map(|p| p + self.scroll_offset)
.or_else(|| cursor.position())
.filter(|p| bounds.contains(*p))
.map(|p| Point::new((p.x - bounds.x) / self.scale, (p.y - bounds.y) / self.scale));
.map(|p| {
Point::new(
(p.x - bounds.x - self.camera_pan.x) / self.scale,
(p.y - bounds.y - self.camera_pan.y) / self.scale,
)
});
let live =
state.context == Some(context) && state.tool == tool && state.bounds == Some(bounds);
if live && let Some(source) = state.source {
@@ -845,12 +952,7 @@ impl Graph<'_> {
}
impl State {
pub(crate) fn selection_offset(
&self,
p: &Project,
owner: Id,
id: Id,
) -> Option<scrollable::AbsoluteOffset> {
pub(crate) fn reveal_selection(&mut self, p: &Project, owner: Id, id: Id) -> bool {
let graph =
Graph::expanded_qualified(p, owner, id, &self.expanded, &self.contextual_expanded);
let scale = self.scale(graph.size, 500.);
@@ -862,10 +964,25 @@ impl State {
self.qualified_selection(p, owner)
.map_or(n.rect, |a| n.endpoint_rect(&a.endpoint))
})
.or_else(|| graph.edges.iter().find(|e| e.id == id).map(|e| e.label))?;
Some(scrollable::AbsoluteOffset {
x: (rect.x * scale - 12.).max(0.),
y: (rect.y * scale - 12.).max(0.),
})
.or_else(|| graph.edges.iter().find(|e| e.id == id).map(|e| e.label));
let Some(rect) = rect else {
return false;
};
let viewport = self.viewport.unwrap_or(Size::new(500., 300.));
let x = rect.x * scale + self.pan.x;
let y = rect.y * scale + self.pan.y;
let delta = iced::Vector::new(
if x < 12. || x + rect.width * scale > viewport.width - 12. {
12. - x
} else {
0.
},
if y < 12. || y + rect.height * scale > viewport.height - 12. {
12. - y
} else {
0.
},
);
self.camera(super::super::canvas_workspace::Event::Pan(delta))
}
}
@@ -732,7 +732,7 @@ fn direct_process_readable_default_fit_expansion_and_bounded_choices() {
state.zoom(None);
assert!(state.scale(Size::new(3262., 220.), 500.) < 0.2);
state.zoom(Some(0.1));
assert_eq!(state.scale(Size::new(3262., 220.), 500.), 0.5);
assert_eq!(state.scale(Size::new(3262., 220.), 500.), 0.1);
state.enter(Id::new_v4(), f.owner);
assert_eq!(state.scale(Size::new(3262., 220.), 500.), 1.);
let mut all = Vec::new();
@@ -1364,82 +1364,6 @@ fn direct_process_palette_preserves_fit_and_manual_camera() {
}
}
#[test]
fn direct_process_pending_form_diff_retains_the_canvas_scroll_state() {
use iced::advanced::widget::{Tree, tree};
use std::rc::Rc;
fn path_to(tree: &Tree, tag: tree::Tag) -> Option<Vec<usize>> {
if tree.tag == tag {
return Some(Vec::new());
}
tree.children.iter().enumerate().find_map(|(index, child)| {
let mut path = path_to(child, tag)?;
path.insert(0, index);
Some(path)
})
}
fn at<'a>(mut tree: &'a mut Tree, path: &[usize]) -> &'a mut Tree {
for &index in path {
tree = &mut tree.children[index];
}
tree
}
for layer in [Layer::Oa, Layer::Sa] {
for size in [Size::new(1440., 900.), Size::new(1100., 700.)] {
for tool in [Tool::Control, Tool::Branch, Tool::Connect] {
let f = fixture(layer);
let mut app = App::with_project(f.p.clone());
let _ = app.update(Message::Select(f.nodes[1]));
let _ = app.update(Message::Page(crate::app::Page::Behavior));
app.window_size = size;
let original = app.document.snapshot();
let graph: Element<'_, Message> =
canvas::Canvas::new(Graph::new(app.project(), f.owner, f.nodes[1])).into();
let canvas_tag = Tree::new(graph.as_widget()).tag;
drop(graph);
let scroll: Element<'_, Message> = scrollable(text("")).into();
let scroll_tag = Tree::new(scroll.as_widget()).tag;
let mut tree = Tree::new(view::view(&app, f.owner, Column::new()).as_widget());
let mut scroll_path = path_to(&tree, canvas_tag).unwrap();
scroll_path.pop();
assert_eq!(at(&mut tree, &scroll_path).tag, scroll_tag);
// Scrollable::diff treats its local state as opaque. A retained marker
// proves the real Iced diff preserves the state that owns the offsets.
// No layout or input operation runs on this test-only marker state.
let marker = Rc::new(());
at(&mut tree, &scroll_path).state = tree::State::new(Rc::clone(&marker));
let _ = app.update(Message::Behavior(super::super::Event::Topology(
Event::Start(f.owner, tool, Some(f.nodes[1])),
)));
assert!(app.behavior.has_pending());
tree.diff(view::view(&app, f.owner, Column::new()).as_widget());
assert_eq!(
Rc::strong_count(&marker),
2,
"form open: {layer:?} {size:?} {tool:?}"
);
let mut current_path = path_to(&tree, canvas_tag).unwrap();
current_path.pop();
assert_eq!(current_path, scroll_path);
assert!(Rc::ptr_eq(
at(&mut tree, &scroll_path).state.downcast_ref::<Rc<()>>(),
&marker,
));
let _ = app.update(Message::Behavior(super::super::Event::Topology(
Event::Cancel,
)));
tree.diff(view::view(&app, f.owner, Column::new()).as_widget());
assert_eq!(
Rc::strong_count(&marker),
2,
"form cancel: {layer:?} {size:?} {tool:?}"
);
assert!(std::sync::Arc::ptr_eq(&app.document.snapshot(), &original));
}
}
}
}
#[test]
fn direct_process_scaled_control_and_link_gestures_use_visible_positions() {
for layer in [Layer::Oa, Layer::Sa] {
File diff suppressed because it is too large Load Diff
+394 -463
View File
@@ -66,107 +66,7 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
let pending = state.draft.is_some();
let ordered = !legacy_order(p, owner).is_empty();
let selected = is_contribution(p, owner, app.selected).then_some(app.selected);
let choose = |tool| Message::TopologyCanvas(CanvasEvent::Choose(context, tool));
let mut controls = Column::new().spacing(6);
if !pending {
controls = controls
.push(
row![
button("Select / reorder")
.style(if state.tool == CanvasTool::Select {
button::primary
} else {
style::nav
})
.on_press(choose(CanvasTool::Select)),
button("Work")
.style(
if state.tool == CanvasTool::Add(Tool::Work, ControlKind::Choice) {
button::primary
} else {
style::nav
}
)
.on_press(choose(CanvasTool::Add(Tool::Work, ControlKind::Choice))),
button("Exchange")
.style(
if state.tool == CanvasTool::Add(Tool::Exchange, ControlKind::Choice) {
button::primary
} else {
style::nav
}
)
.on_press(choose(CanvasTool::Add(Tool::Exchange, ControlKind::Choice))),
button("Reuse")
.style(
if state.tool == CanvasTool::Add(Tool::Reuse, ControlKind::Choice) {
button::primary
} else {
style::nav
}
)
.on_press(choose(CanvasTool::Add(Tool::Reuse, ControlKind::Choice)))
]
.spacing(6),
)
.push(
row![
pick_list(
vec![
ControlKind::Choice,
ControlKind::Merge,
ControlKind::Fork,
ControlKind::Join,
ControlKind::Loop
]
.into_iter()
.map(ControlChoice)
.collect::<Vec<_>>(),
if let CanvasTool::Add(Tool::Control, kind) = state.tool {
Some(ControlChoice(kind))
} else {
None
},
move |c| Message::TopologyCanvas(CanvasEvent::Choose(
context,
CanvasTool::Add(Tool::Control, c.0)
))
)
.placeholder("Draw control…")
.text_size(12)
.padding(8),
button("Sequence link")
.style(if state.tool == CanvasTool::Connect {
button::primary
} else {
style::nav
})
.on_press(choose(CanvasTool::Connect)),
button("Two paths…").on_press(event(Event::Start(
owner,
Tool::Branch,
selected
)))
]
.spacing(6),
);
}
controls=controls.push(label(if pending{"Pending contribution · apply or cancel below"}else if ordered{"Ordered exchange path · click a path to insert or empty canvas to continue; the edit preserves its order"}else{match state.tool{
CanvasTool::Select=>"Select local contributions and paths · drag path endpoints to reconnect · ↕ reorders within a column",
CanvasTool::Connect=>"Sequence link · click or drag from preceding to following contribution · Escape cancels",
CanvasTool::Add(..)=>"Choose a highlighted path or contribution position · existing work stays shared · Escape cancels"}}));
if !pending && ordered {
controls = controls.push(button("Append exchange…").on_press(Message::TopologyCanvas(
CanvasEvent::AppendExchange(context),
)));
let commands = preserved_order(p, owner, None);
if !commands.is_empty() {
controls = controls.push(
button("Edit path links and guards")
.on_press(Message::Command(unique_batch(p, commands))),
);
}
}
let clean = !app.behavior.has_pending() && !app.draft_dirty() && !app.source_dirty();
// A fixed sibling keeps Iced's canvas scroll state through selection/form changes.
let mut navigation = column![].spacing(6);
if let Some(Relation {
@@ -211,11 +111,6 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
);
}
}
if !pending {
controls = controls.push(button("Qualified link / assembly…").on_press(event(
Event::Start(owner, Tool::Contextual, Some(app.selected)),
)));
}
if let Some(id) = selected {
let mut actions =
row![button("Contribution properties").on_press(Message::EditProperties(id))]
@@ -256,27 +151,79 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
button("Back to caller").on_press(Message::TopologyCanvas(CanvasEvent::Back(context))),
);
}
let diagram = {
let mut graph = Graph::expanded_qualified(
p,
owner,
app.selected,
&state.expanded,
&state.contextual_expanded,
navigation = navigation
.push(
button("Two paths...").on_press_maybe(clean.then_some(event(Event::Start(
owner,
Tool::Branch,
selected,
)))),
)
.push(
button("Qualified link / assembly...").on_press_maybe(clean.then_some(event(
Event::Start(owner, Tool::Contextual, Some(app.selected)),
))),
);
graph.scale = state.scale(graph.size, (app.window_size.width - 600.).max(200.));
graph.interaction = Some((
context,
state.tool,
!app.behavior.has_pending() && !app.draft_dirty() && !app.source_dirty(),
));
// Explicit graphs no longer have a scrolling page ancestor. A retained
// offset from an ordered view must not distort their pointer coordinates.
graph.scroll_offset = state.canvas_offset();
let scale = graph.scale;
let mut header = column![
row![
out.width(Fill),
if ordered {
navigation = navigation.push(button("Append exchange...").on_press_maybe(clean.then_some(
Message::TopologyCanvas(CanvasEvent::AppendExchange(context)),
)));
let commands = preserved_order(p, owner, None);
if !commands.is_empty() {
navigation = navigation.push(
button("Edit path links and guards")
.on_press_maybe(clean.then_some(Message::Command(unique_batch(p, commands)))),
);
}
}
let mut graph = Graph::expanded_qualified(
p,
owner,
app.selected,
&state.expanded,
&state.contextual_expanded,
);
graph.scale = state.scale(graph.size, (app.window_size.width - 600.).max(200.));
graph.camera_pan = state.pan;
graph.pending_insertion = state
.draft
.as_ref()
.filter(|d| d.owner == owner && d.fixed)
.map(|d| d.insertion);
graph.interaction = Some((context, state.tool, clean));
let scale = graph.scale;
let scope = super::super::canvas_workspace::Scope {
document: context.document,
owner,
revision: context.revision,
epoch: app.camera_epoch,
};
let keyboard = clean && super::super::canvas_workspace::keyboard_enabled(app);
let camera = move |e| Message::TopologyCanvas(CanvasEvent::Camera(context, scope.epoch, e));
let canvas = container(
iced::widget::sensor(
super::super::canvas_workspace::Viewport::new(
canvas::Canvas::new(graph).width(Fill).height(Fill),
scope,
scale,
keyboard,
camera,
)
.pan_background(state.tool == CanvasTool::Select),
)
.key((context.document, owner))
.on_show(move |size| Message::TopologyCanvas(CanvasEvent::Viewport(context, size)))
.on_resize(move |size| Message::TopologyCanvas(CanvasEvent::Viewport(context, size))),
)
.id("process-viewport")
.width(Fill)
.height(Fill)
.style(style::card)
.into();
let header = column![
row![
out.width(Fill),
super::super::canvas_workspace::Control::new(
button(
text(if state.focused {
"Restore panels"
@@ -285,368 +232,352 @@ pub(super) fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Ele
})
.size(12)
)
.on_press(Message::TopologyCanvas(CanvasEvent::Focus(context)))
.padding(6)
]
.spacing(6)
.align_y(iced::Center),
row![
button(text("Tools").size(12))
.padding(6)
.style(if state.shelf == Some(Shelf::Tools) {
button::primary
} else {
style::nav
})
.on_press(event(Event::Shelf(Shelf::Tools))),
button(text("Selection details").size(12))
.padding(6)
.style(if state.shelf == Some(Shelf::Selection) {
button::primary
} else {
style::nav
})
.on_press(event(Event::Shelf(Shelf::Selection))),
button(text("Fit overview").size(12))
.padding(6)
.on_press(Message::TopologyCanvas(CanvasEvent::Zoom(context, None))),
button(text("−").size(12))
.padding(6)
.on_press(Message::TopologyCanvas(CanvasEvent::Zoom(
context,
Some(scale / 1.25)
))),
label(format!("{:.0}%", scale * 100.)),
button(text("+").size(12))
.padding(6)
.on_press(Message::TopologyCanvas(CanvasEvent::Zoom(
context,
Some(scale * 1.25)
))),
button(text("100%").size(12))
.padding(6)
.on_press(Message::TopologyCanvas(CanvasEvent::Zoom(
context,
Some(1.)
)))
]
.spacing(6)
.wrap(),
.on_press(super::super::canvas_workspace::intent(
scope,
"Panels",
Message::TopologyCanvas(CanvasEvent::Focus(context))
)),
scope,
"Panels",
keyboard,
Some(super::super::canvas_workspace::intent(
scope,
"Panels",
Message::TopologyCanvas(CanvasEvent::Focus(context))
)),
camera
)
]
.spacing(6);
if state.fit_limited(graph.size, (app.window_size.width - 600.).max(200.)) {
header = header
.push(text("Minimum zoom reached · scroll to see the remaining graph.").size(11));
}
if graph.nodes.is_empty() {
controls = controls.push(label(
"Choose Work, Exchange, Reuse or a control, then click the canvas to start.",
));
}
let size = Size::new(graph.size.width * scale, graph.size.height * scale);
let canvas = scrollable(
canvas::Canvas::new(graph)
.width(size.width)
.height(size.height),
)
.id("process-canvas")
.direction(scrollable::Direction::Both {
vertical: scrollable::Scrollbar::default(),
horizontal: scrollable::Scrollbar::default(),
})
.width(Fill)
.height(Fill);
let canvas = container(
iced::widget::sensor(super::super::scenario_scroll::observe_topology(
.spacing(6),
super::super::canvas_workspace::controls(
scope,
keyboard,
scale,
event(Event::Shelf(Shelf::Selection)),
clean.then_some(Message::TopologyCanvas(CanvasEvent::Camera(
context,
scenario::ScrollArea::Canvas,
canvas,
))
.on_show(move |size| Message::TopologyCanvas(CanvasEvent::Viewport(context, size)))
.on_resize(move |size| Message::TopologyCanvas(CanvasEvent::Viewport(context, size))),
scope.epoch,
super::super::canvas_workspace::Event::Focus
))),
move |zoom| Message::TopologyCanvas(CanvasEvent::Zoom(context, zoom)),
camera
)
.padding(8)
.width(Fill)
.height(Fill)
.style(style::card);
let details: Element<'_, Message> = match state.shelf {
Some(Shelf::Tools) => controls.into(),
_ => navigation.push(text("Full qualified identities and definition actions appear here for the selected contribution or link.").size(11)).into(),
};
explicit_pane(
header.into(),
details,
canvas.into(),
state.shelf.is_some(),
pending,
)
};
]
.spacing(4);
let entries = [
("S", "Select contributions or paths", CanvasTool::Select),
(
"W",
"Work: click a path or empty space",
CanvasTool::Add(Tool::Work, ControlKind::Choice),
),
(
"E",
"Exchange: click a path or empty space",
CanvasTool::Add(Tool::Exchange, ControlKind::Choice),
),
(
"ref",
"Reuse process / chain",
CanvasTool::Add(Tool::Reuse, ControlKind::Choice),
),
(
"OR",
"Choice",
CanvasTool::Add(Tool::Control, ControlKind::Choice),
),
(
"M",
"Merge",
CanvasTool::Add(Tool::Control, ControlKind::Merge),
),
(
"AND",
"Fork",
CanvasTool::Add(Tool::Control, ControlKind::Fork),
),
(
"J",
"Join",
CanvasTool::Add(Tool::Control, ControlKind::Join),
),
(
"IT",
"Loop",
CanvasTool::Add(Tool::Control, ControlKind::Loop),
),
(
"->",
"Sequence link: click or drag between contributions",
CanvasTool::Connect,
),
];
let palette = super::super::canvas_workspace::palette(
scope,
keyboard,
camera,
entries.into_iter().map(|(glyph, label, choice)| {
(
glyph,
label,
choice == state.tool,
clean.then_some(Message::TopologyCanvas(CanvasEvent::Choose(
context, choice,
))),
)
}),
);
let details = scrollable(navigation.push(text("Layout is derived. The reorder handle changes display order within its column; it does not author a position.").size(11)))
.id("process-details").width(Fill).height(Fill).into();
let mut form_panel: Element<'_, Message> = iced::widget::Space::new().height(0).into();
if let Some(d) = state.draft.as_ref().filter(|d| d.owner == owner) {
let mut form = column![text(d.tool.title()).size(16)].spacing(8);
if let Some(contextual) = &d.contextual {
form = form
.push(
text_input("Link name (retain current when blank)", &d.name)
.on_input(|v| event(Event::Name(v)))
.padding(8)
.size(12),
)
.push(super::contextual::view(p, owner, contextual));
if let Some(child) = d.source.view(p) {
form_panel = column![
text(format!(
"Consumer name: {}",
crate::views::short(&d.name, 60)
))
.size(12),
child.map(|e| event(Event::Source(e)))
]
.spacing(6)
.height(Fill)
.into();
} else {
if let Some(link) = d.insertion.link.and_then(|id| p.relations.get(&id)) {
let guard = if let RelationBody::SequenceLink { guard, .. } = &link.body {
guard.as_str()
} else {
""
};
form = form.push(label(format!(
"Insert on {} → {} · preserve path identity and condition [{}]",
p.named(link.source()),
p.named(link.target()),
guard
)));
} else if d.fixed && ordered {
form = form.push(label(match (d.before, d.after) {
(Some(before), Some(after)) => format!(
"Insert between {} → {} · preserve the ordered path",
p.named(before),
p.named(after)
),
(Some(before), None) => format!("Continue after {}", p.named(before)),
(None, Some(after)) => format!("Insert before {}", p.named(after)),
_ => "Start the ordered path".into(),
}));
} else if d.fixed
&& d.tool == Tool::Exchange
&& let Some(before) = d.before
{
form = form.push(label(format!(
"Append after {} → new exchange · Create adds an explicit sequence link",
p.named(before)
)));
} else if d.fixed && d.tool != Tool::Connect {
form = form.push(label(
d.insertion
.before
.map_or("Append an unconnected contribution".into(), |id| {
format!("Unconnected contribution before {}", p.named(id))
}),
));
}
if !legacy_order(p, owner).is_empty() {
form = form.push(label(
let mut form = column![text(d.tool.title()).size(16)].spacing(8);
if let Some(contextual) = &d.contextual {
form = form
.push(
text_input("Link name (retain current when blank)", &d.name)
.on_input(|v| event(Event::Name(v)))
.padding(8)
.size(12),
)
.push(super::contextual::view(p, owner, contextual));
} else {
if let Some(link) = d.insertion.link.and_then(|id| p.relations.get(&id)) {
let guard = if let RelationBody::SequenceLink { guard, .. } = &link.body {
guard.as_str()
} else {
""
};
form = form.push(label(format!(
"Insert on {} → {} · preserve path identity and condition [{}]",
p.named(link.source()),
p.named(link.target()),
guard
)));
} else if d.fixed && ordered {
form = form.push(label(match (d.before, d.after) {
(Some(before), Some(after)) => format!(
"Insert between {} → {} · preserve the ordered path",
p.named(before),
p.named(after)
),
(Some(before), None) => format!("Continue after {}", p.named(before)),
(None, Some(after)) => format!("Insert before {}", p.named(after)),
_ => "Start the ordered path".into(),
}));
} else if d.fixed
&& d.tool == Tool::Exchange
&& let Some(before) = d.before
{
form = form.push(label(format!(
"Append after {} → new exchange · Create adds an explicit sequence link",
p.named(before)
)));
} else if d.fixed && d.tool != Tool::Connect {
form = form.push(label(
d.insertion
.before
.map_or("Append an unconnected contribution".into(), |id| {
format!("Unconnected contribution before {}", p.named(id))
}),
));
}
if d.tool == Tool::Work {
if let Some(title) = d.source.label(d.target) {
form = form.push(label(title)).push(label("Create commits the new work and contribution together at the chosen path position."));
}
form = form.push(button("Create new source…").on_press(event(Event::Source(
super::super::source_draft::Event::Open(d.invocation),
))));
}
if !legacy_order(p, owner).is_empty() {
form = form.push(label(
"This edit preserves the ordered path as explicit links in the same undo step.",
));
}
if matches!(
d.tool,
Tool::Work | Tool::Exchange | Tool::Reuse | Tool::Branch
) {
let choices = targets(p, owner, d.tool)
.into_iter()
.filter(|c| compatible_source(p, d, c.id))
.collect();
if d.tool == Tool::Branch {
form = form.push(label("First path work"));
}
form = form.push(picker(
choices,
d,
0,
d.target,
if matches!(
d.tool,
Tool::Work | Tool::Exchange | Tool::Reuse | Tool::Branch
) {
let choices = targets(p, owner, d.tool)
.into_iter()
.filter(|c| compatible_source(p, d, c.id))
.collect();
if d.tool == Tool::Branch {
"Choose first path work…"
form = form.push(label("First path work"));
}
form = form.push(picker(
choices,
d,
0,
d.target,
if d.tool == Tool::Branch {
"Choose first path work…"
} else {
"Choose existing source…"
},
Event::Target,
));
}
if d.tool != Tool::Connect {
form = form.push(
text_input("Contribution name (defaults to source)", &d.name)
.on_input(|v| event(Event::Name(v)))
.padding(8)
.size(12),
);
}
if matches!(d.tool, Tool::Control | Tool::Branch) {
let kinds = if d.tool == Tool::Branch {
vec![ControlKind::Choice, ControlKind::Fork]
} else {
"Choose existing source…"
},
Event::Target,
));
}
if d.tool != Tool::Connect {
form = form.push(
text_input("Contribution name (defaults to source)", &d.name)
.on_input(|v| event(Event::Name(v)))
vec![
ControlKind::Choice,
ControlKind::Merge,
ControlKind::Fork,
ControlKind::Join,
ControlKind::Loop,
]
};
form = form.push(
pick_list(
kinds.into_iter().map(ControlChoice).collect::<Vec<_>>(),
Some(ControlChoice(d.control)),
|v| event(Event::Control(v)),
)
.padding(8)
.text_size(12),
);
}
if d.tool == Tool::Branch {
form = form.push(label("Second path work")).push(picker(
targets(p, owner, Tool::Work),
d,
1,
d.alternate,
"Second path work…",
Event::Alternate,
));
if d.control != ControlKind::Fork {
form = form
.push(label("First path guard"))
.push(
text_input("First path guard", &d.guard)
.on_input(|v| event(Event::Guard(v)))
.padding(8),
)
.push(label("Second path guard"))
.push(
text_input("Second path guard (e.g. else)", &d.alternate_guard)
.on_input(|v| event(Event::AlternateGuard(v)))
.padding(8),
);
}
}
if d.fixed {
if let (Some(a), Some(b)) = (d.before, d.after) {
form = form.push(label(format!("{} → {}", p.named(a), p.named(b))));
}
} else {
form = form
.push(label("Preceding contribution"))
.push(picker(
contributions(p, owner),
d,
2,
d.before,
"After contribution…",
Event::Before,
))
.push(button("Clear preceding").on_press(event(Event::ClearBefore)))
.push(label("Following contribution"))
.push(picker(
contributions(p, owner),
d,
3,
d.after,
"Before contribution…",
Event::After,
))
.push(button("Clear following").on_press(event(Event::ClearAfter)));
}
if d.tool != Tool::Branch
&& d.insertion.link.is_none()
&& (d.before.is_some() || d.tool == Tool::Connect)
{
form = form.push(
text_input(
"Path condition (empty remains a Choice / Loop warning)",
&d.guard,
)
.on_input(|v| event(Event::Guard(v)))
.padding(8)
.size(12),
);
);
}
}
if matches!(d.tool, Tool::Control | Tool::Branch) {
let kinds = if d.tool == Tool::Branch {
vec![ControlKind::Choice, ControlKind::Fork]
let valid = match d.command(p) {
Ok(_) => true,
Err(problem) => {
form = form.push(label(problem));
false
}
};
let actions = row![
button(if d.contextual.is_some() {
"Apply link"
} else {
vec![
ControlKind::Choice,
ControlKind::Merge,
ControlKind::Fork,
ControlKind::Join,
ControlKind::Loop,
]
};
form = form.push(
pick_list(
kinds.into_iter().map(ControlChoice).collect::<Vec<_>>(),
Some(ControlChoice(d.control)),
|v| event(Event::Control(v)),
)
.padding(8)
.text_size(12),
);
}
if d.tool == Tool::Branch {
form = form.push(label("Second path work")).push(picker(
targets(p, owner, Tool::Work),
d,
1,
d.alternate,
"Second path work…",
Event::Alternate,
));
if d.control != ControlKind::Fork {
form = form
.push(label("First path guard"))
.push(
text_input("First path guard", &d.guard)
.on_input(|v| event(Event::Guard(v)))
.padding(8),
)
.push(label("Second path guard"))
.push(
text_input("Second path guard (e.g. else)", &d.alternate_guard)
.on_input(|v| event(Event::AlternateGuard(v)))
.padding(8),
);
}
}
if d.fixed {
if let (Some(a), Some(b)) = (d.before, d.after) {
form = form.push(label(format!("{} → {}", p.named(a), p.named(b))));
}
} else {
form = form
.push(label("Preceding contribution"))
.push(picker(
contributions(p, owner),
d,
2,
d.before,
"After contribution…",
Event::Before,
))
.push(button("Clear preceding").on_press(event(Event::ClearBefore)))
.push(label("Following contribution"))
.push(picker(
contributions(p, owner),
d,
3,
d.after,
"Before contribution…",
Event::After,
))
.push(button("Clear following").on_press(event(Event::ClearAfter)));
}
if d.tool != Tool::Branch
&& d.insertion.link.is_none()
&& (d.before.is_some() || d.tool == Tool::Connect)
{
form = form.push(
text_input(
"Path condition (empty remains a Choice / Loop warning)",
&d.guard,
)
.on_input(|v| event(Event::Guard(v)))
.padding(8)
.size(12),
);
}
"Create"
})
.on_press_maybe(valid.then(|| event(Event::Submit))),
button("Cancel").on_press(event(Event::Cancel))
]
.spacing(7);
form_panel = editor_panel(d.invocation, actions.into(), form.into());
}
let valid = match d.command(p) {
Ok(_) => true,
Err(problem) => {
form = form.push(label(problem));
false
}
};
let actions = row![
button(if d.contextual.is_some() {
"Apply link"
} else {
"Create"
})
.on_press_maybe(valid.then(|| event(Event::Submit))),
button("Cancel").on_press(event(Event::Cancel))
]
.spacing(7);
form_panel = editor_panel(actions.into(), form.into());
}
panes(diagram, form_panel, pending)
}
/// A permanent three-slot tree: variable controls never remount the canvas.
/// The shelf scrolls independently; the canvas receives actual remaining height.
fn explicit_pane<'a, R: iced::advanced::text::Renderer + 'a>(
header: iced::Element<'a, Message, iced::Theme, R>,
details: iced::Element<'a, Message, iced::Theme, R>,
canvas: iced::Element<'a, Message, iced::Theme, R>,
show_details: bool,
pending: bool,
) -> iced::Element<'a, Message, iced::Theme, R> {
// Column::push drops Fixed(0) children. from_vec retains the closed shelf
// slot so its disclosure cannot move/remount the following canvas tree.
Column::from_vec(vec![
container(header).width(Fill).into(),
scrollable(details)
.id("process-details")
.width(Fill)
.height(if show_details {
if pending { 64. } else { 112. }
} else {
0.
})
.into(),
container(canvas).width(Fill).height(Fill).into(),
])
.spacing(6)
.padding(8)
.width(Fill)
.height(Fill)
.into()
}
/// Keep the diagram mounted while an independent editor uses the remaining
/// workspace height. The editor must never be clipped by the page scrollable.
fn panes<'a, R: iced::advanced::Renderer + 'a>(
diagram: iced::Element<'a, Message, iced::Theme, R>,
form: iced::Element<'a, Message, iced::Theme, R>,
pending: bool,
) -> iced::Element<'a, Message, iced::Theme, R> {
column![
container(diagram).width(Fill).height(if pending {
iced::Length::FillPortion(1)
} else {
Fill
}),
container(form).width(Fill).height(if pending {
iced::Length::FillPortion(1)
} else {
iced::Length::Shrink
}),
]
.width(Fill)
.height(Fill)
.into()
let editor = if pending {
Some(form_panel)
} else {
state.shelf.map(|_| details)
};
super::super::canvas_workspace::host(header.into(), palette, canvas, editor)
}
fn editor_panel<'a, R: iced::advanced::text::Renderer + 'a>(
session: Id,
actions: iced::Element<'a, Message, iced::Theme, R>,
fields: iced::Element<'a, Message, iced::Theme, R>,
) -> iced::Element<'a, Message, iced::Theme, R> {
container(
container(column![actions, scrollable(fields).id("process-form").height(Fill)].spacing(8))
.width(Fill)
.height(Fill)
.padding(12)
.style(style::card),
container(
column![
container(actions).id("process-actions"),
super::super::form_session::reset_on_change(
session,
scrollable(fields).id("process-form").height(Fill)
)
]
.spacing(8),
)
.width(Fill)
.height(Fill)
.padding(12)
.style(style::card),
)
.width(Fill)
.height(Fill)
+22 -35
View File
@@ -18,6 +18,7 @@ mod context_fields;
mod data_fields;
mod history_fields;
mod port_fields;
pub(crate) mod reference_chooser;
mod view_fields;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -85,6 +86,8 @@ pub struct Draft {
pub value_browsers: BTreeMap<String, ValueBrowser>,
pub reference_browsers: BTreeMap<String, ReferenceBrowser>,
history: history_fields::State,
reference_session: Id,
reference_generation: Id,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -209,11 +212,14 @@ impl Draft {
value_browsers: BTreeMap::new(),
reference_browsers: BTreeMap::new(),
history: Default::default(),
reference_session: Id::new_v4(),
reference_generation: Id::new_v4(),
};
draft.rebuild();
Some(draft)
}
fn rebuild(&mut self) {
self.reference_generation = Id::new_v4();
// Array/variant edits can change the meaning of a row path.
self.value_browsers.clear();
self.inputs.clear();
@@ -274,6 +280,9 @@ impl Draft {
.unwrap_or_else(|| self.materialize().unwrap_or_else(|_| self.value.clone()))
}
pub fn set_context(&mut self, context: Option<Value>) {
if self.context != context {
self.reference_generation = Id::new_v4();
}
self.context = context;
}
/// Materialize selected scalar subtrees without parsing retained, unselected drafts.
@@ -359,6 +368,9 @@ impl Draft {
}
pub fn input(&mut self, path: &str, value: String) {
if let Some(input) = self.inputs.get_mut(path) {
if input.raw != value {
self.reference_generation = Id::new_v4();
}
input.editor = text_editor::Content::with_text(&value);
input.raw = value;
}
@@ -366,7 +378,11 @@ impl Draft {
pub fn edit_text(&mut self, path: &str, action: text_editor::Action) {
if let Some(input) = self.inputs.get_mut(path) {
input.editor.perform(action);
input.raw = input.editor.text();
let raw = input.editor.text();
if input.raw != raw {
self.reference_generation = Id::new_v4();
}
input.raw = raw;
}
}
pub fn shape(&mut self, path: &str, value: Value) -> Result<(), String> {
@@ -1795,7 +1811,7 @@ pub fn view<'a>(draft: &'a Draft, project: &'a Project) -> View<'a, Message> {
));
}
}
content.into()
reference_chooser::trigger::scope(content, draft.reference_session)
}
/// Render one closed property subtree for a workflow-owned typed draft.
@@ -1937,41 +1953,12 @@ fn property<'a>(
return out.into();
}
if reference(path) && (value.is_string() || value.is_null()) {
let raw = draft
.inputs
.get(path)
.map(|v| v.raw.as_str())
.or_else(|| value.as_str());
let current = raw.and_then(|s| s.parse::<Id>().ok()).unwrap_or(Id::nil());
let choices = reference_choices(draft, project, path, current);
let selected = choices.iter().find(|c| c.id == current).cloned();
let owned_path = path.to_string();
let optional = optional_reference(path);
let mut content = column![
return column![
label_view(),
pick_list(choices, selected, move |choice| Message::FieldShape(
owned_path.clone(),
if choice.id.is_nil() && optional {
Value::Null
} else {
json!(choice.id)
}
))
.text_size(12)
.padding(8)
.width(Fill)
reference_chooser::adapter::field(draft, project, path)
]
.spacing(5);
if let Some(raw) = raw
&& raw.parse::<Id>().is_err()
{
content = content.push(
text(format!("Invalid reference retained in the draft: {raw}"))
.size(11)
.color(style::MUTED),
);
}
return content.into();
.spacing(5)
.into();
}
match value {
Value::Object(map) => {
@@ -120,7 +120,9 @@ fn seed(schema: &'static Value, depth: usize) -> Result<Value, &'static str> {
if let Some(options) = alternatives(schema) {
if options
.iter()
.any(|s| matches_value(s, &json!("NotApplicable"), 0))
.filter_map(|s| resolve(s).ok())
.filter_map(|s| s.get("enum").and_then(Value::as_array))
.any(|values| values.contains(&json!("NotApplicable")))
{
return Ok(json!("NotApplicable"));
}
@@ -577,11 +579,11 @@ fn render<'a>(
for (index, item) in items.iter().enumerate().skip(page * PAGE_SIZE).take(PAGE_SIZE) {
let item_path = format!("{path}/{index}");
let mut card = column![render(draft, project, item_schema, Some(item), &item_path, &format!("{} {}", title, index + 1), depth + 1)].spacing(8);
if path == FACETS {
if let Some(current) = current_observation(draft, project, &item_path) {
card = card.push(button("Use current counterpart observations")
.on_press(Message::FieldShape(item_path.clone(), json!(current))).style(style::nav));
}
if path == FACETS
&& let Some(current) = current_observation(draft, project, &item_path)
{
card = card.push(button("Use current counterpart observations")
.on_press(Message::FieldShape(item_path.clone(), json!(current))).style(style::nav));
}
card = card.push(row![
button("↑").on_press_maybe((index > 0).then(|| Message::FieldArray(path.into(), Some(index), -1))),
@@ -752,6 +752,38 @@ fn choose_history_constructor(draft: &mut Draft, path: &str, label: &str) {
draft.shape(&path, value).unwrap();
}
#[test]
fn history_optional_uuid_and_text_seed_absence_without_inventing_observations() {
for fact in ["Header/Parent", "Artifact/review/Revision"] {
let side = format!("{FACETS}/0/{fact}/oa");
let schema = resolve(schema_at(&side).unwrap()).unwrap();
assert_eq!(seed(schema, 0).unwrap(), json!("NotApplicable"));
let observed_value = alternatives(schema)
.unwrap()
.iter()
.find(|branch| branch_label(branch) == "Observed value")
.unwrap();
let value = branch_seed(observed_value).unwrap();
assert_eq!(value, json!({"Value": null}));
assert_eq!(
seed(schema_at(&format!("{side}/Value")).unwrap(), 0).unwrap(),
Value::Null,
"a plain text/UUID shape is not the NotApplicable enum constructor"
);
if fact == "Header/Parent" {
assert_eq!(
serde_json::from_value::<Observed<Option<Id>>>(value).unwrap(),
Observed::Value(None)
);
} else {
assert_eq!(
serde_json::from_value::<Observed<Option<String>>>(value).unwrap(),
Observed::Value(None)
);
}
}
}
#[test]
fn history_nested_optional_number_events_switch_absent_present_and_recover_invalid_raw() {
let (project, id) = fixture(Some(baseline(vec![])));
@@ -0,0 +1,389 @@
//! Isolated live-reference chooser experiment, declared only under cfg(test).
//! The host supplies an eligible catalog and revalidates every
//! Write intent against the current document before changing a staged scalar.
//! No core command, draft serialization, or App message belongs in this module.
use oa_core::Id;
use std::collections::BTreeSet;
pub mod adapter;
#[cfg(test)]
mod tests;
pub mod trigger;
pub mod widget;
pub const MAX_ROWS: usize = 6;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Context {
pub document: Id,
pub revision: u64,
pub draft: Id,
pub record: Id,
pub path: String,
pub optional: bool,
}
impl Context {
/// This is an additional historical-path guard, not live schema discovery.
/// Call only after the parent form has identified a live reference field.
pub fn live(
document: Id,
revision: u64,
draft: Id,
record: Id,
path: impl Into<String>,
optional: bool,
) -> Result<Self, &'static str> {
let path = path.into();
if !path.starts_with('/') || path.split('/').any(|part| part == "baseline") {
return Err("The chooser requires a live reference property.");
}
Ok(Self {
document,
revision,
draft,
record,
path,
optional,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
/// For a diagram placement this is the placement ID, not its element ID.
pub id: Id,
pub name: String,
pub alias: String,
pub kind: String,
pub scope: String,
pub containment: String,
}
impl Candidate {
pub fn context_label(&self) -> String {
format!("{} · {} · {}", self.scope, self.kind, self.containment)
}
pub fn detail(&self) -> String {
format!(
"{} · @{} · {} · {}",
self.name,
self.alias,
self.context_label(),
self.id
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Current {
Unassigned,
Valid(Candidate),
Incompatible(Candidate),
Missing(Id),
InvalidRaw(String),
}
impl Current {
pub fn label(&self) -> String {
match self {
Self::Unassigned => "Not assigned".into(),
Self::Valid(c) => format!("Current: {} · @{}", c.name, c.alias),
Self::Incompatible(c) => {
format!("Current choice needs review: {} · @{}", c.name, c.alias)
}
Self::Missing(id) => format!("Missing reference: {id}"),
Self::InvalidRaw(raw) => format!("Invalid reference retained: {raw}"),
}
}
}
#[derive(Debug, Clone)]
struct Searchable {
candidate: Candidate,
all: String,
alias: String,
name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stamp {
pub context: Context,
pub invocation: Id,
pub results: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Close {
Escape,
Tab { backwards: bool },
Outside,
WindowChanged,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
/// The mounted text input numbers emitted edits. Multiple edits in one
/// runtime batch may share the old result stamp; none may be dropped.
Query {
text: String,
serial: u64,
},
Move {
delta: i32,
rows: usize,
},
Page {
delta: i32,
rows: usize,
},
Highlight(Id),
Choose(Id),
Clear,
Close(Close),
}
impl Action {
pub fn writes_staged_value(&self) -> bool {
matches!(self, Self::Choose(_) | Self::Clear)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Event {
pub stamp: Stamp,
pub action: Action,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Ignored,
Browsed,
Closed(Close),
/// The host must still check current eligibility and scoped draft guards.
Write {
context: Context,
value: Option<Id>,
},
}
#[derive(Debug, Clone)]
pub struct State {
context: Context,
invocation: Id,
results: u64,
serial: u64,
open: bool,
candidates: Vec<Searchable>,
filtered: Vec<usize>,
query: String,
start: usize,
highlight: Option<usize>,
pub current: Current,
pub scope_label: String,
}
impl State {
pub fn open(
context: Context,
candidates: Vec<Candidate>,
current: Current,
scope_label: impl Into<String>,
) -> Result<Self, &'static str> {
// Context fields are public for host comparisons; check again in case
// a caller constructed one without the live-path constructor.
if !context.path.starts_with('/') || context.path.split('/').any(|p| p == "baseline") {
return Err("Historical values are not live reference candidates.");
}
let mut seen = BTreeSet::new();
let mut indexed = Vec::with_capacity(candidates.len());
for candidate in candidates {
if candidate.id.is_nil() || !seen.insert(candidate.id) {
return Err("Eligible references must have distinct, non-nil identities.");
}
indexed.push(Searchable {
all: candidate.detail().to_lowercase(),
alias: candidate.alias.to_lowercase(),
name: candidate.name.to_lowercase(),
candidate,
});
}
indexed.sort_by(|a, b| {
(&a.name, &a.alias, a.candidate.id).cmp(&(&b.name, &b.alias, b.candidate.id))
});
let filtered: Vec<_> = (0..indexed.len()).collect();
let highlight = (!filtered.is_empty()).then_some(0);
Ok(Self {
context,
invocation: Id::new_v4(),
results: 0,
serial: 0,
open: true,
candidates: indexed,
filtered,
query: String::new(),
start: 0,
highlight,
current,
scope_label: scope_label.into(),
})
}
pub fn stamp(&self) -> Stamp {
Stamp {
context: self.context.clone(),
invocation: self.invocation,
results: self.results,
}
}
pub fn event(&self, action: Action) -> Event {
Event {
stamp: self.stamp(),
action,
}
}
pub fn is_open(&self) -> bool {
self.open
}
pub fn query(&self) -> &str {
&self.query
}
pub fn query_serial(&self) -> u64 {
self.serial
}
pub fn count(&self) -> usize {
self.filtered.len()
}
pub fn start(&self) -> usize {
self.start
}
pub fn optional(&self) -> bool {
self.context.optional
}
pub fn highlighted(&self) -> Option<&Candidate> {
self.highlight.and_then(|i| self.at(i))
}
fn at(&self, index: usize) -> Option<&Candidate> {
self.filtered
.get(index)
.map(|i| &self.candidates[*i].candidate)
}
pub fn visible(&self, rows: usize) -> impl Iterator<Item = &Candidate> {
self.filtered
.iter()
.skip(self.start)
.take(rows.min(MAX_ROWS))
.map(|index| &self.candidates[*index].candidate)
}
/// The host calls this before rendering on any path/document/facet/context
/// replacement. Existing events remain tied to the old invocation.
pub fn invalidate(&mut self) {
self.open = false;
}
pub fn update(&mut self, event: Event) -> Outcome {
if !self.open
|| event.stamp.context != self.context
|| event.stamp.invocation != self.invocation
{
return Outcome::Ignored;
}
// Absolute row actions require exactly the presented result set.
// Relative navigation and dismissal are processed in input order within
// this session: typing must not make a following Escape stale.
if matches!(event.action, Action::Choose(_) | Action::Highlight(_))
&& event.stamp.results != self.results
{
return Outcome::Ignored;
}
match event.action {
Action::Query { text, serial } => {
if serial <= self.serial {
return Outcome::Ignored;
}
self.serial = serial;
self.query = text;
let query = self.query.to_lowercase();
let terms: Vec<_> = query.split_whitespace().collect();
self.filtered = self
.candidates
.iter()
.enumerate()
.filter_map(|(i, c)| {
terms
.iter()
.all(|term| match term.strip_prefix('@') {
Some(alias) => c.alias.contains(alias),
None => c.all.contains(term),
})
.then_some(i)
})
.collect();
self.start = 0;
self.highlight = (!self.filtered.is_empty()).then_some(0);
}
Action::Page { delta, rows } => {
let rows = rows.clamp(1, MAX_ROWS);
if self.filtered.is_empty() {
return Outcome::Ignored;
}
let relative = self
.highlight
.unwrap_or(self.start)
.saturating_sub(self.start)
.min(rows - 1);
let last_page = (self.filtered.len() - 1) / rows * rows;
self.start = (self.start as i64 + i64::from(delta) * rows as i64)
.clamp(0, last_page as i64) as usize;
self.highlight = Some((self.start + relative).min(self.filtered.len() - 1));
}
Action::Move { delta, rows } => {
let rows = rows.clamp(1, MAX_ROWS);
if self.filtered.is_empty() {
return Outcome::Ignored;
}
let current = self.highlight.unwrap_or(self.start) as i64;
let next =
(current + i64::from(delta)).clamp(0, self.filtered.len() as i64 - 1) as usize;
self.highlight = Some(next);
if next < self.start {
self.start = next;
}
if next >= self.start + rows {
self.start = next + 1 - rows;
}
}
Action::Highlight(id) => {
let Some(index) = self
.filtered
.iter()
.position(|i| self.candidates[*i].candidate.id == id)
else {
return Outcome::Ignored;
};
if self.highlight == Some(index) {
return Outcome::Ignored;
}
self.highlight = Some(index);
}
Action::Choose(id) => {
if !self
.filtered
.iter()
.any(|i| self.candidates[*i].candidate.id == id)
{
return Outcome::Ignored;
}
self.open = false;
return Outcome::Write {
context: self.context.clone(),
value: Some(id),
};
}
Action::Clear if self.context.optional => {
self.open = false;
return Outcome::Write {
context: self.context.clone(),
value: None,
};
}
Action::Clear => return Outcome::Ignored,
Action::Close(reason) => {
self.open = false;
return Outcome::Closed(reason);
}
}
self.results = self.results.wrapping_add(1);
Outcome::Browsed
}
}
@@ -0,0 +1,307 @@
//! Live form adapter. Compatibility stays in the existing parent adapter;
//! browser metadata and scoped writes never reinterpret historical UUID text.
use super::super::{Draft, friendly, history_fields, optional_reference, reference, reference_ids};
use super::{Candidate, Context, Current, State, trigger};
use crate::{app::Message, style};
use iced::{
Element, Fill, Rectangle,
widget::{column, container, row, text, tooltip},
};
use oa_core::{Id, Project};
use serde_json::{Value, json};
use std::collections::BTreeSet;
#[derive(Debug, Clone)]
pub struct Open {
pub document: Id,
pub session: Id,
pub generation: Id,
pub record: Id,
pub path: String,
pub anchor: Rectangle,
}
#[derive(Debug, Clone)]
pub struct Set {
pub context: Context,
pub generation: Id,
pub value: Option<Id>,
}
impl Draft {
pub fn reference_session(&self) -> Id {
self.reference_session
}
pub fn reference_generation(&self) -> Id {
self.reference_generation
}
pub fn reference_open(&self, project: &Project, path: &str, anchor: Rectangle) -> Open {
Open {
document: project.id,
session: self.reference_session,
generation: self.reference_generation,
record: self.original,
path: path.into(),
anchor,
}
}
pub fn reference_matches(&self, request: &Open) -> bool {
self.reference_session == request.session
&& self.reference_generation == request.generation
&& self.original == request.record
&& self.live_reference(&request.path)
}
fn live_reference(&self, path: &str) -> bool {
!history_fields::is_path(path)
&& reference(path)
&& self
.value
.pointer(path)
.is_some_and(|v| v.is_string() || v.is_null())
}
pub fn reference_catalog(
&self,
project: &Project,
request: &Open,
revision: u64,
) -> Result<State, String> {
if request.document != project.id || !self.reference_matches(request) {
return Err("The reference field changed. Open its chooser again.".into());
}
let allowed: BTreeSet<_> = reference_ids(self, project, &request.path)
.into_iter()
.filter(|id| !id.is_nil())
.collect();
let candidates = allowed
.iter()
.filter_map(|id| candidate(project, *id))
.collect();
let raw = self
.inputs
.get(&request.path)
.map(|v| v.raw.as_str())
.or_else(|| self.value.pointer(&request.path).and_then(Value::as_str));
let current = match raw {
None => Current::Unassigned,
Some(raw) => match raw.parse::<Id>() {
Ok(id) if id.is_nil() => Current::Unassigned,
Ok(id) => match candidate(project, id) {
Some(c) if allowed.contains(&id) => Current::Valid(c),
Some(c) => Current::Incompatible(c),
None => Current::Missing(id),
},
Err(_) => Current::InvalidRaw(raw.into()),
},
};
let context = Context::live(
project.id,
revision,
self.reference_session,
self.original,
&request.path,
optional_reference(&request.path),
)
.map_err(str::to_owned)?;
State::open(
context,
candidates,
current,
format!(
"{} · compatible references",
friendly(request.path.rsplit('/').next().unwrap_or("Reference"))
),
)
.map_err(str::to_owned)
}
pub fn reference_set(&mut self, project: &Project, intent: &Set) -> Result<(), String> {
let value = self.reference_value(project, intent)?;
self.shape_scoped(&intent.context.path, value)
}
pub fn reference_value(&self, project: &Project, intent: &Set) -> Result<Value, String> {
let context = &intent.context;
if context.document != project.id
|| context.draft != self.reference_session
|| context.record != self.original
|| intent.generation != self.reference_generation
|| !self.live_reference(&context.path)
|| context.optional != optional_reference(&context.path)
{
return Err("The originating reference field is no longer current.".into());
}
let value = match intent.value {
Some(id)
if !id.is_nil() && reference_ids(self, project, &context.path).contains(&id) =>
{
json!(id)
}
None if context.optional => Value::Null,
_ => return Err("Choose a currently compatible reference.".into()),
};
Ok(value)
}
}
fn named(project: &Project, id: Id) -> String {
if let Some(e) = project.elements.get(&id) {
format!("{} · @{}", e.name, e.alias)
} else {
project.named(id).into()
}
}
fn ancestry(project: &Project, id: Id) -> String {
let mut parts = vec![];
let mut seen = BTreeSet::new();
let mut current = project.elements.get(&id).and_then(|e| e.parent);
while let Some(id) = current {
if !seen.insert(id) {
parts.push("[containment cycle]".into());
break;
}
parts.push(named(project, id));
current = project.elements.get(&id).and_then(|e| e.parent);
}
parts.reverse();
if parts.is_empty() {
project.name.clone()
} else {
parts.join(" / ")
}
}
pub(crate) fn candidate(project: &Project, id: Id) -> Option<Candidate> {
let layer = |layer| format!("{layer:?}").to_uppercase();
if id == project.id {
return Some(Candidate {
id,
name: project.name.clone(),
alias: project.alias.clone(),
kind: "Project".into(),
scope: "Model".into(),
containment: "Model root".into(),
});
}
if let Some(e) = project.elements.get(&id) {
return Some(Candidate {
id,
name: e.name.clone(),
alias: e.alias.clone(),
kind: e.kind().to_string(),
scope: layer(e.layer()),
containment: ancestry(project, id),
});
}
if let Some(r) = project.relations.get(&id) {
return Some(Candidate {
id,
name: r.name.clone(),
alias: r.alias.clone(),
kind: r.kind().to_string(),
scope: project.layer_of(id).map_or_else(|| "Model".into(), layer),
containment: format!(
"{} → {}",
named(project, r.source()),
named(project, r.target())
),
});
}
for diagram in project.diagrams.values() {
if id == diagram.id {
return Some(Candidate {
id,
name: diagram.name.clone(),
alias: diagram.alias.clone(),
kind: format!("{:?} diagram", diagram.projection),
scope: layer(diagram.layer),
containment: project.name.clone(),
});
}
if let Some(node) = diagram.nodes.get(&id) {
return Some(Candidate {
id,
name: project.named(node.element).into(),
alias: node.alias.clone(),
kind: "Placement".into(),
scope: layer(diagram.layer),
containment: format!(
"{} · @{} / {}",
diagram.name,
diagram.alias,
named(project, node.element)
),
});
}
}
if let Some(link) = project.artifact_links.get(&id) {
return Some(Candidate {
id,
name: link.name.clone(),
alias: link.alias.clone(),
kind: "Artifact link".into(),
scope: project
.layer_of(link.owner)
.map_or_else(|| "Model".into(), layer),
containment: named(project, link.owner),
});
}
project.traces.get(&id).map(|trace| Candidate {
id,
name: trace.name.clone(),
alias: trace.alias.clone(),
kind: "Trace".into(),
scope: "OA ↔ SA".into(),
containment: format!(
"{} ↔ {}",
named(project, trace.oa),
named(project, trace.sa)
),
})
}
pub fn field<'a, R: iced::advanced::text::Renderer<Font = iced::Font> + 'a>(
draft: &'a Draft,
project: &'a Project,
path: &str,
) -> Element<'a, Message, iced::Theme, R> {
let raw = draft
.inputs
.get(path)
.map(|v| v.raw.as_str())
.or_else(|| draft.value.pointer(path).and_then(Value::as_str));
let (label, detail) = match raw {
None => (
if optional_reference(path) {
"Not assigned"
} else {
"Choose a reference…"
}
.into(),
String::new(),
),
Some(raw) => match raw.parse::<Id>() {
Ok(id) if id.is_nil() => ("Choose a reference…".into(), String::new()),
Ok(id) => match candidate(project, id) {
Some(c) => (format!("{} · @{}", c.name, c.alias), c.detail()),
None => ("Missing reference".into(), raw.into()),
},
Err(_) => ("Invalid reference retained".into(), raw.into()),
},
};
let label = crate::views::short(&label, 35);
let body = container(row![text(label).size(12).width(Fill), text("⌄").size(12)].spacing(6))
.padding(8)
.width(Fill);
let path = path.to_owned();
let id = trigger::field_id(draft.reference_generation, &path);
let field = trigger::Field::new(body, id, move |anchor| {
Message::FieldReferenceOpen(draft.reference_open(project, &path, anchor))
});
if detail.is_empty() {
field.into()
} else {
tooltip(
field,
container(column![text(detail).size(11)])
.padding(8)
.style(style::card),
tooltip::Position::Left,
)
.into()
}
}
@@ -0,0 +1,803 @@
use super::*;
use iced::{
Element, Event as Input, Point, Rectangle, Size, Theme, Vector,
advanced::{Layout, Shell, layout, widget::Tree},
keyboard, mouse,
widget::{Space, mouse_area},
};
fn context(optional: bool) -> Context {
Context::live(
Id::from_u128(1),
7,
Id::from_u128(2),
Id::from_u128(3),
"/body/SequenceUse/sequence",
optional,
)
.unwrap()
}
fn candidate(index: u128) -> Candidate {
Candidate {
id: Id::from_u128(10_000 + index),
name: "Control".into(),
alias: format!("controller_{index:04}"),
kind: "Function".into(),
scope: "SA".into(),
containment: format!("System / Subsystem {} / Controller", index / 100),
}
}
fn thousand(current: Current, optional: bool) -> State {
// Reverse the fixture input to falsify accidental dependence on ingestion
// order. Expected IDs and aliases below are literal fixture identities.
State::open(
context(optional),
(0..1_000).rev().map(candidate).collect(),
current,
"SA · compatible functions",
)
.unwrap()
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Message {
Chooser(Event),
UnderPress,
UnderRelease,
}
#[derive(Default)]
struct Clipboard(Option<String>);
impl iced::advanced::Clipboard for Clipboard {
fn read(&self, _: iced::advanced::clipboard::Kind) -> Option<String> {
self.0.clone()
}
fn write(&mut self, _: iced::advanced::clipboard::Kind, text: String) {
self.0 = Some(text);
}
}
struct Mount {
tree: Option<Tree>,
size: Size,
anchor: Rectangle,
clipboard: Clipboard,
}
impl Default for Mount {
fn default() -> Self {
Self {
tree: None,
size: Size::new(1100., 700.),
anchor: Rectangle {
x: 790.,
y: 640.,
width: 278.,
height: 32.,
},
clipboard: Clipboard::default(),
}
}
}
impl Mount {
fn batch(
&mut self,
state: Option<&State>,
events: &[(Input, Option<Point>)],
) -> (Vec<Message>, Option<layout::Node>) {
let underneath: Element<'_, Message, Theme, ()> =
mouse_area(Space::new().width(iced::Fill).height(iced::Fill))
.on_press(Message::UnderPress)
.on_release(Message::UnderRelease)
.into();
let mut view: Element<'_, Message, Theme, ()> =
widget::Popup::new(underneath, state, self.anchor, Message::Chooser).into();
let tree = self.tree.get_or_insert_with(|| Tree::new(view.as_widget()));
view.as_widget().diff(tree);
let node =
view.as_widget_mut()
.layout(tree, &(), &layout::Limits::new(Size::ZERO, self.size));
let viewport = Rectangle::with_size(self.size);
let overlay_node = view
.as_widget_mut()
.overlay(tree, Layout::new(&node), &(), &viewport, Vector::ZERO)
.map(|mut overlay| overlay.as_overlay_mut().layout(&(), self.size));
let mut messages = Vec::new();
for (event, point) in events {
let cursor = point.map_or(mouse::Cursor::Unavailable, mouse::Cursor::Available);
let mut shell = Shell::new(&mut messages);
if let Some(overlay_node) = &overlay_node {
// Reconstruct the overlay between layout and every input, as
// Iced does. Geometry must live in the measured layout tree.
let mut overlay = view
.as_widget_mut()
.overlay(tree, Layout::new(&node), &(), &viewport, Vector::ZERO)
.unwrap();
overlay.as_overlay_mut().update(
event,
Layout::new(overlay_node),
cursor,
&(),
&mut self.clipboard,
&mut shell,
);
overlay.as_overlay().draw(
&mut (),
&crate::style::theme(),
&iced::advanced::renderer::Style {
text_color: iced::Color::BLACK,
},
Layout::new(overlay_node),
cursor,
);
if matches!(
event,
Input::Mouse(_) | Input::Keyboard(_) | Input::Touch(_) | Input::InputMethod(_)
) {
assert!(shell.is_event_captured(), "An open chooser owns input");
}
} else {
view.as_widget_mut().update(
tree,
event,
Layout::new(&node),
cursor,
&(),
&mut self.clipboard,
&mut shell,
&viewport,
);
}
}
(messages, overlay_node)
}
fn send(&mut self, state: &mut State, event: Input) -> Vec<Outcome> {
let (messages, _) = self.batch(Some(state), &[(event, None)]);
messages
.into_iter()
.map(|message| match message {
Message::Chooser(event) => state.update(event),
_ => panic!("Popup leaked input to its parent"),
})
.collect()
}
fn type_text(&mut self, state: &mut State, text: &str) -> Vec<Outcome> {
let (messages, _) = self.batch(Some(state), &typing(text));
messages
.into_iter()
.map(|message| match message {
Message::Chooser(event) => state.update(event),
_ => panic!("Typing leaked input to its parent"),
})
.collect()
}
fn geometry(&mut self, state: &State) -> widget::Geometry {
let (_, node) = self.batch(Some(state), &[]);
widget::Geometry::from_bounds(node.unwrap().children()[0].bounds())
}
fn click(&mut self, state: &State, point: Point) -> Vec<Message> {
self.batch(
Some(state),
&[
(
Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Some(point),
),
(
Input::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
Some(point),
),
],
)
.0
}
}
fn named(key: keyboard::key::Named) -> Input {
Input::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(key),
modified_key: keyboard::Key::Named(key),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::Space),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::empty(),
text: None,
repeat: false,
})
}
// Iced 0.14's physical-key path intentionally inserts one scalar from text.
// Whole-string typing is several key events; paste and IME commit are separate
// input paths and are exercised below rather than faked as one physical key.
fn typed(character: char) -> Input {
let text = character.to_string();
Input::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Character(text.clone().into()),
modified_key: keyboard::Key::Character(text.clone().into()),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::KeyA),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::empty(),
text: Some(text.into()),
repeat: false,
})
}
fn typing(text: &str) -> Vec<(Input, Option<Point>)> {
text.chars()
.map(|character| (typed(character), None))
.collect()
}
fn query(state: &mut State, value: &str) {
let event = state.event(Action::Query {
text: value.into(),
serial: state.query_serial() + 1,
});
assert_eq!(state.update(event), Outcome::Browsed);
}
#[test]
fn catalog_search_disambiguates_repeated_names_containment_alias_and_exact_placement_identity() {
let mut state = thousand(Current::Unassigned, false);
assert_eq!(
state.visible(6).map(|c| c.id).collect::<Vec<_>>(),
(10_000..10_006).map(Id::from_u128).collect::<Vec<_>>()
);
query(&mut state, "control subsystem 6 @controller_0617");
assert_eq!(state.count(), 1);
assert_eq!(state.highlighted().unwrap().id, Id::from_u128(10_617));
query(&mut state, "OA");
assert_eq!(state.count(), 0);
query(&mut state, &Id::from_u128(10_617).to_string());
assert_eq!(state.count(), 1);
assert_eq!(state.highlighted().unwrap().alias, "controller_0617");
let placement = Candidate {
id: Id::from_u128(20_001),
name: "Control".into(),
alias: "control_placement".into(),
kind: "Placement".into(),
scope: "SA".into(),
containment: "Architecture / Main diagram / Control".into(),
};
let mut state = State::open(
context(false),
vec![placement],
Current::Unassigned,
"SA · placements",
)
.unwrap();
query(&mut state, "placement main");
assert_eq!(state.highlighted().unwrap().id, Id::from_u128(20_001));
let event = state.event(Action::Choose(Id::from_u128(20_000)));
assert_eq!(
state.update(event),
Outcome::Ignored,
"Semantic ID is not the placement identity"
);
assert!(
State::open(
context(false),
vec![candidate(1), candidate(1)],
Current::Unassigned,
"SA"
)
.is_err()
);
}
#[test]
fn mounted_overlay_clamps_at_three_field_positions_and_keeps_results_and_query_bounded() {
let state = thousand(Current::InvalidRaw("not a uuid".into()), true);
for size in [
Size::new(1100., 700.),
Size::new(1600., 1000.),
Size::new(320., 320.),
] {
for y in [5., size.height / 2., size.height - 34.] {
let mut mount = Mount {
size,
anchor: Rectangle {
x: size.width - 300.,
y,
width: 278.,
height: 32.,
},
..Default::default()
};
let (_, node) = mount.batch(Some(&state), &[]);
let node = node.unwrap();
let bounds = node.children()[0].bounds();
let geometry = widget::Geometry::from_bounds(bounds);
assert!(bounds.x >= 8. && bounds.y >= 8.);
assert!(bounds.x + bounds.width <= size.width - 8.);
assert!(bounds.y + bounds.height <= size.height - 8.);
assert!(bounds.width <= 420. && bounds.height <= 360.);
assert!(geometry.rows > 0 && geometry.rows <= 6);
assert_eq!(geometry.rows, if size.height == 320. { 4 } else { 6 });
let search = node.children()[1].bounds();
assert!(
bounds.contains(search.position())
&& bounds.contains(Point::new(
search.x + search.width,
search.y + search.height
))
);
assert!(geometry.row(geometry.rows - 1).y + 34. <= geometry.detail.y);
assert_eq!(state.visible(geometry.rows).count(), geometry.rows);
}
}
}
#[test]
fn mounted_input_preserves_rapid_same_batch_typing_and_cursor_across_controlled_rebuilds() {
let mut state = thousand(Current::Unassigned, false);
let mut mount = Mount::default();
let (messages, _) = mount.batch(Some(&state), &[(typed('a'), None), (typed('b'), None)]);
assert_eq!(
messages.len(),
2,
"Actual focused input must publish each edit"
);
let mut queries = Vec::new();
for message in messages {
let Message::Chooser(event) = message else {
panic!("Unexpected parent event")
};
let Action::Query { text, .. } = &event.action else {
panic!("Typing must not choose a reference")
};
queries.push(text.clone());
assert_eq!(state.update(event), Outcome::Browsed);
}
assert_eq!(queries, ["a", "ab"]);
assert_eq!(state.query(), "ab");
assert!(
mount
.send(&mut state, named(keyboard::key::Named::Home))
.is_empty()
);
assert_eq!(mount.send(&mut state, typed('z')), [Outcome::Browsed]);
assert_eq!(
state.query(),
"zab",
"Rebuilding the controlled widget must not refocus at the end"
);
assert_eq!(state.current, Current::Unassigned);
}
#[test]
fn mounted_keyboard_pages_and_selects_only_the_highlighted_visible_candidate_once() {
let mut state = thousand(Current::Unassigned, false);
let mut mount = Mount::default();
assert_eq!(
mount.send(&mut state, named(keyboard::key::Named::PageDown)),
[Outcome::Browsed]
);
assert_eq!(state.start(), 6);
assert_eq!(state.highlighted().unwrap().id, Id::from_u128(10_006));
assert_eq!(
mount.send(&mut state, named(keyboard::key::Named::ArrowDown)),
[Outcome::Browsed]
);
assert_eq!(state.highlighted().unwrap().id, Id::from_u128(10_007));
let (messages, _) = mount.batch(
Some(&state),
&[
(named(keyboard::key::Named::Enter), None),
(named(keyboard::key::Named::Enter), None),
],
);
assert_eq!(messages.len(), 1);
let Message::Chooser(event) = messages.into_iter().next().unwrap() else {
panic!()
};
assert!(event.action.writes_staged_value());
assert_eq!(
state.update(event),
Outcome::Write {
context: context(false),
value: Some(Id::from_u128(10_007))
}
);
assert!(!state.is_open());
}
#[test]
fn mounted_filtered_row_click_uses_the_displayed_identity_and_scoped_write_intent() {
let mut state = thousand(Current::Missing(Id::from_u128(99)), false);
let mut mount = Mount::default();
let query = "@controller_0731";
assert_eq!(
mount.type_text(&mut state, query),
vec![Outcome::Browsed; query.chars().count()]
);
assert_eq!(state.query(), query);
assert_eq!(state.count(), 1);
let point = mount.geometry(&state).row(0).center();
let messages = mount.click(&state, point);
assert_eq!(messages.len(), 1);
let Message::Chooser(event) = messages[0].clone() else {
panic!()
};
assert_eq!(
state.update(event),
Outcome::Write {
context: context(false),
value: Some(Id::from_u128(10_731))
}
);
assert_eq!(state.current, Current::Missing(Id::from_u128(99)));
}
#[test]
fn mounted_query_change_rejects_old_release_and_old_result_events_without_locking_popup() {
let mut state = thousand(Current::Unassigned, false);
let mut mount = Mount::default();
let point = mount.geometry(&state).row(4).center();
let captured = mount.click(&state, point);
let Message::Chooser(old_choice) = captured[0].clone() else {
panic!()
};
query(&mut state, "@controller_0700");
assert_eq!(state.update(old_choice), Outcome::Ignored);
// The rejected old Choose had marked the widget closing; a changed result
// context must unlock it so an explicit current click can complete.
let point = mount.geometry(&state).row(0).center();
let messages = mount.click(&state, point);
assert_eq!(messages.len(), 1);
let Message::Chooser(event) = messages[0].clone() else {
panic!()
};
assert_eq!(
state.update(event),
Outcome::Write {
context: context(false),
value: Some(Id::from_u128(10_700))
}
);
let mut state = thousand(Current::Unassigned, false);
let point = mount.geometry(&state).row(0).center();
assert!(
mount
.batch(
Some(&state),
&[(
Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Some(point)
)]
)
.0
.is_empty()
);
query(&mut state, "@controller_0319");
assert!(
mount
.batch(
Some(&state),
&[(
Input::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
Some(point)
)]
)
.0
.is_empty()
);
assert!(state.is_open());
}
#[test]
fn captured_choice_cannot_cross_document_revision_draft_record_or_array_path() {
let source = thousand(Current::Unassigned, false);
let mut mount = Mount::default();
let point = mount.geometry(&source).row(0).center();
let Message::Chooser(event) = mount.click(&source, point).remove(0) else {
panic!()
};
for changed in 0..6 {
let mut destination = context(false);
match changed {
0 => destination.document = Id::from_u128(999),
1 => destination.revision += 1,
2 => destination.draft = Id::from_u128(999),
3 => destination.record = Id::from_u128(999),
4 => destination.path = "/body/SomeList/members/1/scenario".into(),
_ => {} // A new invocation even with every semantic ID unchanged.
}
let mut state = State::open(
destination,
vec![candidate(0)],
Current::InvalidRaw("unfinished".into()),
"SA",
)
.unwrap();
assert_eq!(state.update(event.clone()), Outcome::Ignored);
assert_eq!(state.current, Current::InvalidRaw("unfinished".into()));
assert!(state.is_open());
}
let mut invalidated = source.clone();
invalidated.invalidate();
assert_eq!(invalidated.update(event), Outcome::Ignored);
}
#[test]
fn empty_search_escape_tab_and_optional_clear_do_not_silently_choose_nil() {
for current in [
Current::Missing(Id::from_u128(999)),
Current::InvalidRaw("@incomplete/".into()),
Current::Incompatible(candidate(999)),
] {
let mut state = thousand(current.clone(), false);
let mut mount = Mount::default();
let query = "no match exists";
assert_eq!(
mount.type_text(&mut state, query),
vec![Outcome::Browsed; query.chars().count()]
);
assert_eq!(state.query(), query);
assert_eq!(
state.count(),
0,
"Verify actual input reached the empty-result state before Enter"
);
assert!(
mount
.send(&mut state, named(keyboard::key::Named::Enter))
.is_empty()
);
assert!(state.is_open());
assert_eq!(state.current, current);
assert_eq!(
mount.send(&mut state, named(keyboard::key::Named::Escape)),
[Outcome::Closed(Close::Escape)]
);
assert_eq!(state.current, current);
}
let mut state = thousand(Current::Unassigned, false);
let mut mount = Mount::default();
assert_eq!(
mount.send(&mut state, named(keyboard::key::Named::Tab)),
[Outcome::Closed(Close::Tab { backwards: false })]
);
let mut state = thousand(Current::InvalidRaw("?".into()), true);
let point = mount.geometry(&state).clear.center();
let Message::Chooser(event) = mount.click(&state, point).remove(0) else {
panic!()
};
assert_eq!(
state.update(event),
Outcome::Write {
context: context(true),
value: None
}
);
let mut required = thousand(Current::Unassigned, false);
let clear = required.event(Action::Clear);
assert_eq!(required.update(clear), Outcome::Ignored);
}
#[test]
fn dismissal_swallows_matching_release_across_closed_rebuild_but_next_click_reaches_parent() {
let mut state = thousand(Current::Unassigned, false);
let mut mount = Mount::default();
let outside = Point::new(20., 20.);
let (messages, _) = mount.batch(
Some(&state),
&[(
Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Some(outside),
)],
);
let [Message::Chooser(event)] = messages.as_slice() else {
panic!("Expected only popup dismissal")
};
assert_eq!(state.update(event.clone()), Outcome::Closed(Close::Outside));
let release = Input::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left));
assert!(
mount
.batch(None, &[(release.clone(), Some(outside))])
.0
.is_empty()
);
assert_eq!(
mount
.batch(
None,
&[
(
Input::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
Some(outside)
),
(release, Some(outside)),
]
)
.0,
[Message::UnderPress, Message::UnderRelease]
);
}
#[test]
fn historical_paths_never_open_and_only_explicit_choice_or_clear_is_a_write() {
for path in [
"/baseline",
"/baseline/oa/value",
"/baseline/sa/value/TypeRef/Named",
] {
assert!(
Context::live(
Id::from_u128(1),
0,
Id::from_u128(2),
Id::from_u128(3),
path,
true
)
.is_err()
);
let mut forged = context(true);
forged.path = path.into();
assert!(State::open(forged, vec![candidate(0)], Current::Unassigned, "History").is_err());
}
for action in [
Action::Query {
text: "Control".into(),
serial: 1,
},
Action::Highlight(Id::from_u128(10_000)),
Action::Move { delta: 1, rows: 6 },
Action::Page { delta: 1, rows: 6 },
Action::Close(Close::Escape),
] {
assert!(!action.writes_staged_value());
}
assert!(Action::Choose(Id::from_u128(10_000)).writes_staged_value());
assert!(Action::Clear.writes_staged_value());
}
#[test]
fn out_of_order_query_serials_cannot_restore_obsolete_results() {
let mut state = thousand(Current::Unassigned, false);
let old = state.event(Action::Query {
text: "@controller_0001".into(),
serial: 1,
});
let new = state.event(Action::Query {
text: "@controller_0999".into(),
serial: 2,
});
assert_eq!(state.update(new), Outcome::Browsed);
assert_eq!(state.update(old), Outcome::Ignored);
assert_eq!(state.highlighted().unwrap().id, Id::from_u128(10_999));
}
#[test]
fn mounted_query_then_escape_in_one_batch_closes_and_relative_keys_keep_input_order() {
let mut state = thousand(Current::InvalidRaw("unfinished".into()), false);
let mut mount = Mount::default();
let query = "@controller_0720";
let mut inputs = typing(query);
inputs.push((named(keyboard::key::Named::Escape), None));
let (messages, _) = mount.batch(Some(&state), &inputs);
let outcomes: Vec<_> = messages
.into_iter()
.map(|message| {
let Message::Chooser(event) = message else {
panic!("Input escaped the popup")
};
state.update(event)
})
.collect();
let mut expected = vec![Outcome::Browsed; query.chars().count()];
expected.push(Outcome::Closed(Close::Escape));
assert_eq!(outcomes, expected);
assert_eq!(state.query(), "@controller_0720");
assert_eq!(state.current, Current::InvalidRaw("unfinished".into()));
let mut state = thousand(Current::Unassigned, false);
let old_absolute_row = state.event(Action::Choose(Id::from_u128(10_000)));
let (messages, _) = mount.batch(
Some(&state),
&[
(named(keyboard::key::Named::PageDown), None),
(named(keyboard::key::Named::PageDown), None),
(named(keyboard::key::Named::ArrowUp), None),
],
);
assert_eq!(messages.len(), 3);
for message in messages {
let Message::Chooser(event) = message else {
panic!("Input escaped the popup")
};
assert_eq!(state.update(event), Outcome::Browsed);
}
assert_eq!(state.highlighted().unwrap().id, Id::from_u128(10_011));
assert_eq!(state.start(), 11);
assert_eq!(state.update(old_absolute_row), Outcome::Ignored);
assert!(state.is_open());
}
#[test]
fn mounted_clipboard_paste_and_ime_commit_preserve_whole_strings_without_selecting() {
let mut state = thousand(Current::Unassigned, false);
let mut mount = Mount::default();
mount.clipboard.0 = Some("@controller_0472".into());
let paste = Input::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Character("v".into()),
modified_key: keyboard::Key::Character("v".into()),
physical_key: keyboard::key::Physical::Code(keyboard::key::Code::KeyV),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::COMMAND,
text: None,
repeat: false,
});
let (messages, _) = mount.batch(
Some(&state),
&[
(
Input::Keyboard(keyboard::Event::ModifiersChanged(
keyboard::Modifiers::COMMAND,
)),
None,
),
(paste, None),
(
Input::Keyboard(keyboard::Event::ModifiersChanged(
keyboard::Modifiers::empty(),
)),
None,
),
],
);
let [Message::Chooser(event)] = messages.as_slice() else {
panic!("Paste should emit exactly one whole-string query")
};
assert_eq!(state.update(event.clone()), Outcome::Browsed);
assert_eq!(state.query(), "@controller_0472");
assert_eq!(state.count(), 1);
assert_eq!(state.highlighted().unwrap().id, Id::from_u128(10_472));
assert_eq!(state.current, Current::Unassigned);
assert!(state.is_open());
let unicode_name = "Режим Δ負荷";
let unicode = Candidate {
id: Id::from_u128(30_111),
name: unicode_name.into(),
alias: "mode_unicode".into(),
kind: "Function".into(),
scope: "SA".into(),
containment: "Система / 控制".into(),
};
let mut state = State::open(
context(false),
vec![unicode],
Current::InvalidRaw("retained".into()),
"SA",
)
.unwrap();
use iced::advanced::input_method::Event as Ime;
let preedit = [
(Input::InputMethod(Ime::Opened), None),
(
Input::InputMethod(Ime::Preedit(unicode_name.into(), None)),
None,
),
];
assert!(
mount.batch(Some(&state), &preedit).0.is_empty(),
"Composition is not a committed query"
);
assert_eq!(state.query(), "");
let (messages, _) = mount.batch(
Some(&state),
&[
(Input::InputMethod(Ime::Preedit(String::new(), None)), None),
(Input::InputMethod(Ime::Commit(unicode_name.into())), None),
(Input::InputMethod(Ime::Closed), None),
],
);
let [Message::Chooser(event)] = messages.as_slice() else {
panic!("IME commit should emit one complete query")
};
assert_eq!(state.update(event.clone()), Outcome::Browsed);
assert_eq!(state.query(), unicode_name);
assert_eq!(state.count(), 1);
assert_eq!(state.highlighted().unwrap().id, Id::from_u128(30_111));
assert_eq!(state.current, Current::InvalidRaw("retained".into()));
assert!(state.is_open());
}
@@ -0,0 +1,447 @@
//! Keyboard entry and focus operations scoped to one property form. Focus
//! targets include the draft generation so delayed operations cannot focus a
//! replacement array row or a recovered document with the same semantic IDs.
use crate::style;
use iced::{
Border, Color, Element, Event, Length, Rectangle, Size, Task, Theme, Vector,
advanced::{
Clipboard, Layout, Shell, Widget, layout, overlay, renderer,
widget::{Id, Operation, Tree, operation, tree},
},
keyboard, mouse,
widget::container,
};
use oa_core::Id as ModelId;
mod focus;
#[derive(Clone, Copy)]
pub struct FormScope {
pub session: ModelId,
pub modal: bool,
}
pub(super) struct FormOwner(pub Option<FormScope>);
const REVIEW_MODAL: &str = "reference-owning-review-modal";
/// Marks the entire Review dialog without changing its layout or event flow.
pub fn modal<'a, Message: 'a, R: renderer::Renderer + 'a>(
content: impl Into<Element<'a, Message, Theme, R>>,
) -> Element<'a, Message, Theme, R> {
Field {
content: content.into(),
id: Some(Id::new(REVIEW_MODAL)),
on_open: None,
}
.into()
}
pub fn field_id(generation: ModelId, path: &str) -> Id {
Id::new(format!("reference:{generation}:{path}"))
}
pub fn scope_id(session: ModelId) -> Id {
Id::new(format!("reference-form:{session}"))
}
#[derive(Default)]
struct Interaction {
focused: bool,
pressed: bool,
identity: Option<Id>,
anchor: Option<Rectangle>,
}
impl operation::Focusable for Interaction {
fn is_focused(&self) -> bool {
self.focused
}
fn focus(&mut self) {
self.focused = true;
}
fn unfocus(&mut self) {
self.focused = false;
self.pressed = false;
}
}
pub struct Field<'a, Message, R = iced::Renderer>
where
R: renderer::Renderer,
{
content: Element<'a, Message, Theme, R>,
id: Option<Id>,
on_open: Option<Box<dyn Fn(Rectangle) -> Message + 'a>>,
}
impl<'a, Message, R: renderer::Renderer> Field<'a, Message, R> {
pub fn new(
content: impl Into<Element<'a, Message, Theme, R>>,
id: Id,
on_open: impl Fn(Rectangle) -> Message + 'a,
) -> Self {
Self {
content: content.into(),
id: Some(id),
on_open: Some(Box::new(on_open)),
}
}
}
pub fn scope<'a, Message: 'a, R: renderer::Renderer + 'a>(
content: impl Into<Element<'a, Message, Theme, R>>,
session: ModelId,
) -> Element<'a, Message, Theme, R> {
container(Field {
content: content.into(),
id: None,
on_open: None,
})
.id(scope_id(session))
.width(Length::Fill)
.into()
}
fn run<Message, R: renderer::Renderer>(
content: &mut Element<'_, Message, Theme, R>,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
mut operation: Box<dyn Operation>,
) -> bool {
let mut changed = false;
loop {
content
.as_widget_mut()
.operate(tree, layout, renderer, &mut *operation);
match operation.finish() {
operation::Outcome::Chain(next) => {
operation = next;
changed = true;
}
_ => break,
}
}
changed
}
pub(super) fn tab<Message, R: renderer::Renderer>(
content: &mut Element<'_, Message, Theme, R>,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
scope: FormScope,
backwards: bool,
) -> bool {
run(
content,
tree,
layout,
renderer,
Box::new(focus::relative(scope.session, backwards, scope.modal)),
)
}
pub(super) fn own_input<Message, R: renderer::Renderer>(
content: &mut Element<'_, Message, Theme, R>,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
) {
content
.as_widget_mut()
.operate(tree, layout, renderer, &mut focus::exclusive());
}
impl<Message, R: renderer::Renderer> Widget<Message, Theme, R> for Field<'_, Message, R> {
fn tag(&self) -> tree::Tag {
tree::Tag::of::<Interaction>()
}
fn state(&self) -> tree::State {
tree::State::new(Interaction {
identity: self.id.clone(),
..Default::default()
})
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(self.content.as_widget())]
}
fn diff(&self, tree: &mut Tree) {
let state = tree.state.downcast_mut::<Interaction>();
if state.identity != self.id {
*state = Interaction {
identity: self.id.clone(),
..Default::default()
};
}
tree.diff_children(std::slice::from_ref(&self.content));
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(&mut self, tree: &mut Tree, renderer: &R, limits: &layout::Limits) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
operation: &mut dyn Operation,
) {
if let Some(id) = &self.id
&& self.on_open.is_some()
{
operation.focusable(
Some(id),
layout.bounds(),
tree.state.downcast_mut::<Interaction>(),
);
operation.custom(
Some(id),
layout.bounds(),
tree.state.downcast_mut::<Interaction>(),
);
}
if self.on_open.is_none() {
operation.container(self.id.as_ref(), layout.bounds());
operation.traverse(&mut |operation| {
self.content.as_widget_mut().operate(
&mut tree.children[0],
layout,
renderer,
operation,
)
});
} else {
self.content.as_widget_mut().operate(
&mut tree.children[0],
layout,
renderer,
operation,
);
}
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
if self.on_open.is_some() {
let state = tree.state.downcast_mut::<Interaction>();
let visible = layout.bounds().intersection(viewport);
let hovered = visible.is_some_and(|bounds| cursor.is_over(bounds));
let activate = match event {
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) if hovered => {
state.focused = true;
state.pressed = true;
shell.capture_event();
shell.request_redraw();
false
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
let activate = state.pressed && hovered;
if state.pressed {
shell.capture_event();
}
state.pressed = false;
activate
}
Event::Keyboard(keyboard::Event::KeyPressed {
key:
keyboard::Key::Named(keyboard::key::Named::Enter | keyboard::key::Named::Space),
repeat: false,
..
}) if state.focused => true,
Event::Mouse(mouse::Event::ButtonPressed(_)) => {
state.focused = false;
state.pressed = false;
false
}
_ => false,
};
if activate && let Some(bounds) = state.anchor {
shell.publish(self.on_open.as_ref().unwrap()(bounds));
shell.capture_event();
return;
}
}
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
fn draw(
&self,
tree: &Tree,
renderer: &mut R,
theme: &Theme,
renderer_style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
if self.on_open.is_some() {
let focus = tree.state.downcast_ref::<Interaction>().focused;
renderer.fill_quad(
renderer::Quad {
bounds: layout.bounds(),
border: Border {
color: if focus || cursor.is_over(layout.bounds()) {
style::TEAL
} else {
style::LINE
},
width: if focus { 2. } else { 1. },
radius: 5.into(),
},
..Default::default()
},
Color::WHITE,
);
}
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
renderer_style,
layout,
cursor,
viewport,
);
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &R,
) -> mouse::Interaction {
if self.on_open.is_some() && cursor.is_over(layout.bounds()) {
mouse::Interaction::Pointer
} else {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'b>,
renderer: &R,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, R>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
/// Scrollable child updates use content coordinates. The root visits the
/// retained tree before each input, so field anchors use current window
/// coordinates even when a wheel event and activation share one runtime batch.
pub(super) fn measure<Message, R: renderer::Renderer>(
content: &mut Element<'_, Message, Theme, R>,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
viewport: Rectangle,
) {
content.as_widget_mut().operate(
tree,
layout,
renderer,
&mut Measure {
translation: Vector::ZERO,
viewport: Some(viewport),
pending: None,
},
);
}
struct Measure {
translation: Vector,
viewport: Option<Rectangle>,
pending: Option<(Vector, Option<Rectangle>)>,
}
impl Operation for Measure {
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation)) {
let previous = (self.translation, self.viewport);
if let Some((translation, viewport)) = self.pending.take() {
self.translation = translation;
self.viewport = viewport;
}
visit(self);
(self.translation, self.viewport) = previous;
}
fn scrollable(
&mut self,
_: Option<&Id>,
bounds: Rectangle,
_: Rectangle,
translation: Vector,
_: &mut dyn operation::Scrollable,
) {
let bounds = Rectangle {
x: bounds.x - self.translation.x,
y: bounds.y - self.translation.y,
..bounds
};
self.pending = Some((
self.translation + translation,
self.viewport
.and_then(|viewport| viewport.intersection(&bounds)),
));
}
fn custom(&mut self, _: Option<&Id>, bounds: Rectangle, state: &mut dyn std::any::Any) {
if let Some(state) = state.downcast_mut::<Interaction>() {
let bounds = Rectangle {
x: bounds.x - self.translation.x,
y: bounds.y - self.translation.y,
..bounds
};
state.anchor = self
.viewport
.and_then(|viewport| viewport.intersection(&bounds));
}
}
}
impl<'a, Message: 'a, R: renderer::Renderer + 'a> From<Field<'a, Message, R>>
for Element<'a, Message, Theme, R>
{
fn from(field: Field<'a, Message, R>) -> Self {
Element::new(field)
}
}
pub fn focus_operation(
session: ModelId,
generation: ModelId,
path: &str,
step: i32,
) -> impl Operation + 'static {
focus::exact(session, generation, path, step)
}
pub fn focus<Message>(
session: ModelId,
generation: ModelId,
path: &str,
step: i32,
) -> Task<Message> {
iced::advanced::widget::operate(focus_operation(session, generation, path, step)).discard()
}
@@ -0,0 +1,303 @@
//! Focus movement and reveal share one root traversal. A form may be inside a
//! scrollable; restricting traversal to its container would hide that ancestor.
use super::{FormOwner, Id, ModelId, Operation, Rectangle, Vector, field_id, operation, scope_id};
use std::collections::BTreeMap;
enum Origin {
Current,
Exact(Id),
}
#[derive(Clone)]
struct Scroll {
index: usize,
bounds: Rectangle,
capacity: Vector,
offset: Vector,
}
struct Field {
id: Option<Id>,
bounds: Rectangle,
ancestors: Vec<Scroll>,
}
pub(super) struct Collect {
scope: Id,
origin: Origin,
step: i32,
inside: bool,
entering: Option<bool>,
translation: Vector,
scrolls: Vec<Scroll>,
pending_scroll: Option<Scroll>,
scroll_index: usize,
fields: Vec<Field>,
focused: Option<usize>,
outside_focused: bool,
modal: bool,
owner_valid: bool,
}
impl Collect {
fn new(scope: Id, origin: Origin, step: i32) -> Self {
let owner_valid = matches!(origin, Origin::Current);
Self {
scope,
origin,
step,
inside: false,
entering: None,
translation: Vector::ZERO,
scrolls: vec![],
pending_scroll: None,
scroll_index: 0,
fields: vec![],
focused: None,
outside_focused: false,
modal: false,
owner_valid,
}
}
}
pub(super) fn relative(session: ModelId, backwards: bool, modal: bool) -> Collect {
Collect {
modal,
..Collect::new(
scope_id(session),
Origin::Current,
if backwards { -1 } else { 1 },
)
}
}
pub(super) fn exact(session: ModelId, generation: ModelId, path: &str, step: i32) -> Collect {
Collect::new(
scope_id(session),
Origin::Exact(field_id(generation, path)),
step,
)
}
impl Operation for Collect {
fn custom(&mut self, _: Option<&Id>, _: Rectangle, state: &mut dyn std::any::Any) {
if let Some(owner) = state.downcast_ref::<FormOwner>() {
self.owner_valid = owner
.0
.is_some_and(|owner| scope_id(owner.session) == self.scope);
self.modal = owner.0.is_some_and(|owner| owner.modal);
}
}
fn container(&mut self, id: Option<&Id>, _: Rectangle) {
self.entering = Some(self.inside || id == Some(&self.scope));
}
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation)) {
let previous = (self.inside, self.translation, self.scrolls.len());
if let Some(inside) = self.entering.take() {
self.inside = inside;
}
if let Some(scroll) = self.pending_scroll.take() {
self.translation += scroll.offset;
self.scrolls.push(scroll);
}
visit(self);
self.inside = previous.0;
self.translation = previous.1;
self.scrolls.truncate(previous.2);
}
fn scrollable(
&mut self,
_: Option<&Id>,
bounds: Rectangle,
content: Rectangle,
offset: Vector,
_: &mut dyn operation::Scrollable,
) {
self.pending_scroll = Some(Scroll {
index: self.scroll_index,
bounds: translated(bounds, self.translation),
capacity: Vector::new(
(content.width - bounds.width).max(0.),
(content.height - bounds.height).max(0.),
),
offset,
});
self.scroll_index += 1;
}
fn focusable(
&mut self,
id: Option<&Id>,
bounds: Rectangle,
state: &mut dyn operation::Focusable,
) {
if !self.inside {
self.outside_focused |= state.is_focused();
return;
}
if state.is_focused() {
self.focused = Some(self.fields.len());
}
self.fields.push(Field {
id: id.cloned(),
bounds: translated(bounds, self.translation),
ancestors: self.scrolls.clone(),
});
}
fn finish(&self) -> operation::Outcome<()> {
if !self.owner_valid || self.fields.is_empty() {
return operation::Outcome::None;
}
let origin = match &self.origin {
Origin::Current if self.focused.is_none() && self.outside_focused && !self.modal => {
return operation::Outcome::None;
}
Origin::Current => self
.focused
.map(|index| index as i64)
.unwrap_or(if self.step < 0 {
self.fields.len() as i64
} else {
-1
}),
Origin::Exact(id) => {
let Some(index) = self
.fields
.iter()
.position(|field| field.id.as_ref() == Some(id))
else {
return operation::Outcome::None;
};
index as i64
}
};
// A form keeps a reachable focus at both boundaries. Initial Tab enters
// the first field; initial Shift+Tab enters the last field.
let target = (origin + i64::from(self.step)).rem_euclid(self.fields.len() as i64) as usize;
let field = &self.fields[target];
let mut bounds = field.bounds;
let mut shifts = BTreeMap::new();
for ancestor in field.ancestors.iter().rev() {
let dx = reveal_axis(
bounds.x,
bounds.width,
ancestor.bounds.x,
ancestor.bounds.width,
);
let dy = reveal_axis(
bounds.y,
bounds.height,
ancestor.bounds.y,
ancestor.bounds.height,
);
let delta = Vector::new(
(ancestor.offset.x + dx).clamp(0., ancestor.capacity.x) - ancestor.offset.x,
(ancestor.offset.y + dy).clamp(0., ancestor.capacity.y) - ancestor.offset.y,
);
if delta != Vector::ZERO {
shifts.insert(ancestor.index, delta);
}
bounds = translated(bounds, delta);
}
operation::Outcome::Chain(Box::new(Apply {
scope: self.scope.clone(),
inside: false,
entering: None,
target,
field_index: 0,
scroll_index: 0,
shifts,
owner_valid: matches!(self.origin, Origin::Current),
clear_outside: self.modal,
preserve_inside: false,
}))
}
}
fn translated(bounds: Rectangle, delta: Vector) -> Rectangle {
Rectangle {
x: bounds.x - delta.x,
y: bounds.y - delta.y,
..bounds
}
}
fn reveal_axis(start: f32, length: f32, viewport_start: f32, viewport_length: f32) -> f32 {
if start < viewport_start || length > viewport_length {
start - viewport_start
} else {
(start + length - viewport_start - viewport_length).max(0.)
}
}
pub(super) struct Apply {
scope: Id,
inside: bool,
entering: Option<bool>,
target: usize,
field_index: usize,
scroll_index: usize,
shifts: BTreeMap<usize, Vector>,
owner_valid: bool,
clear_outside: bool,
preserve_inside: bool,
}
pub(super) fn exclusive() -> Apply {
Apply {
scope: Id::new(super::REVIEW_MODAL),
inside: false,
entering: None,
target: 0,
field_index: 0,
scroll_index: 0,
shifts: BTreeMap::new(),
owner_valid: true,
clear_outside: true,
preserve_inside: true,
}
}
impl Operation for Apply {
fn custom(&mut self, _: Option<&Id>, _: Rectangle, state: &mut dyn std::any::Any) {
if let Some(owner) = state.downcast_ref::<FormOwner>() {
self.owner_valid = owner
.0
.is_some_and(|owner| scope_id(owner.session) == self.scope);
self.clear_outside = owner.0.is_some_and(|owner| owner.modal);
}
}
fn container(&mut self, id: Option<&Id>, _: Rectangle) {
self.entering = Some(self.inside || id == Some(&self.scope));
}
fn traverse(&mut self, visit: &mut dyn FnMut(&mut dyn Operation)) {
let previous = self.inside;
if let Some(inside) = self.entering.take() {
self.inside = inside;
}
visit(self);
self.inside = previous;
}
fn scrollable(
&mut self,
_: Option<&Id>,
bounds: Rectangle,
content: Rectangle,
_: Vector,
state: &mut dyn operation::Scrollable,
) {
if self.owner_valid
&& let Some(delta) = self.shifts.get(&self.scroll_index)
{
state.scroll_by(
operation::scrollable::AbsoluteOffset {
x: delta.x,
y: delta.y,
},
bounds,
content,
);
}
self.scroll_index += 1;
}
fn focusable(&mut self, _: Option<&Id>, _: Rectangle, state: &mut dyn operation::Focusable) {
if self.owner_valid && self.inside && !self.preserve_inside {
if self.field_index == self.target {
state.focus();
} else {
state.unfocus();
}
self.field_index += 1;
} else if self.owner_valid && !self.inside && self.clear_outside {
state.unfocus();
}
}
}
@@ -0,0 +1,994 @@
//! Root overlay adapter. Keep the wrapper mounted while closed so the release
//! from a dismissal gesture cannot reach the underlying content. Parent modal
//! ownership is supplied by the host (pass no chooser while a modal is active).
use super::{Action, Close, Event as ChoiceEvent, MAX_ROWS, Stamp, State as Chooser};
use crate::style;
use iced::{
Border, Color, Element, Event, Font, Length, Point, Rectangle, Size, Theme, Vector,
advanced::{
Clipboard, Layout, Shell, Widget, layout, overlay, renderer,
text::{self, Paragraph as _},
widget::{Operation, Tree, tree},
},
alignment, keyboard, mouse, touch,
widget::text_input,
window,
};
use std::{cell::Cell, rc::Rc};
const ROW: f32 = 34.;
const MARGIN: f32 = 8.;
#[derive(Debug, Clone, Copy)]
pub(super) struct Geometry {
pub popup: Rectangle,
pub search: Rectangle,
pub current: Rectangle,
pub detail: Rectangle,
pub close: Rectangle,
pub previous: Rectangle,
pub next: Rectangle,
pub clear: Rectangle,
pub rows: usize,
}
impl Geometry {
fn new(anchor: Rectangle, viewport: Size) -> Self {
let width = anchor
.width
.clamp(278., 420.)
.min((viewport.width - 2. * MARGIN).max(0.));
let height = 360f32.min((viewport.height - 2. * MARGIN).max(0.));
let x = anchor.x.clamp(
MARGIN.min(viewport.width / 2.),
(viewport.width - MARGIN - width).max(MARGIN.min(viewport.width / 2.)),
);
let below = anchor.y + anchor.height + 4.;
let preferred = if below + height + MARGIN <= viewport.height {
below
} else {
anchor.y - height - 4.
};
let y = preferred.clamp(
MARGIN.min(viewport.height / 2.),
(viewport.height - MARGIN - height).max(MARGIN.min(viewport.height / 2.)),
);
Self::from_bounds(Rectangle {
x,
y,
width,
height,
})
}
pub(super) fn from_bounds(popup: Rectangle) -> Self {
let inner = (popup.width - 16.).max(0.);
let rect = |left, top, width, height| Rectangle {
x: popup.x + left,
y: popup.y + top,
width,
height,
};
let footer = (popup.height - 32.).max(0.);
let detail_height = if popup.height >= 180. { 32. } else { 0. };
let detail_top = (footer - detail_height - 4.).max(84.);
let rows = (((detail_top - 88.).max(0.) / ROW) as usize).min(MAX_ROWS);
Self {
popup,
search: rect(8., 28., inner, 30.),
current: rect(8., 62., inner, 18.),
detail: rect(8., detail_top, inner, detail_height),
close: rect((popup.width - 58.).max(0.), 4., 50f32.min(popup.width), 22.),
previous: rect(8., footer, 28., 24.),
next: rect(40., footer, 28., 24.),
clear: rect((popup.width - 84.).max(0.), footer, 76., 24.),
rows,
}
}
pub fn row(&self, index: usize) -> Rectangle {
Rectangle {
x: self.popup.x + 8.,
y: self.popup.y + 84. + index as f32 * ROW,
width: (self.popup.width - 16.).max(0.),
height: ROW,
}
}
fn hit(&self, chooser: &Chooser, point: Point) -> Option<Action> {
if self.close.contains(point) {
return Some(Action::Close(Close::Escape));
}
if self.previous.contains(point) && chooser.start() > 0 {
return Some(Action::Page {
delta: -1,
rows: self.rows,
});
}
if self.next.contains(point) && chooser.start() + self.rows < chooser.count() {
return Some(Action::Page {
delta: 1,
rows: self.rows,
});
}
if self.clear.contains(point) && chooser.optional() {
return Some(Action::Clear);
}
chooser
.visible(self.rows)
.enumerate()
.find_map(|(i, c)| self.row(i).contains(point).then_some(Action::Choose(c.id)))
}
}
#[derive(Default)]
struct Interaction {
stamp: Option<Stamp>,
serial: u64,
pressed: Option<(ChoiceEvent, Pointer)>,
closing: bool,
swallow_mouse: Option<mouse::Button>,
swallow_touch: Option<touch::Finger>,
held_mouse: Option<mouse::Button>,
held_touch: Option<touch::Finger>,
detail_scroll: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Pointer {
Mouse,
Touch(touch::Finger),
}
impl Interaction {
fn swallow(&mut self, event: &Event) -> bool {
match event {
Event::Mouse(mouse::Event::ButtonReleased(button))
if self.swallow_mouse == Some(*button) =>
{
self.swallow_mouse = None;
true
}
Event::Touch(
touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. },
) if self.swallow_touch == Some(*id) => {
self.swallow_touch = None;
true
}
_ => false,
}
}
}
pub struct Popup<'a, Message, R = iced::Renderer>
where
R: text::Renderer<Font = Font>,
{
content: Element<'a, Message, Theme, R>,
input: Element<'a, String, Theme, R>,
chooser: Option<&'a Chooser>,
anchor: Rectangle,
on_event: Rc<dyn Fn(ChoiceEvent) -> Message + 'a>,
focus_scope: Option<super::trigger::FormScope>,
}
impl<'a, Message: Clone + 'a, R: text::Renderer<Font = Font> + 'a> Popup<'a, Message, R> {
pub fn new(
content: impl Into<Element<'a, Message, Theme, R>>,
chooser: Option<&'a Chooser>,
anchor: Rectangle,
on_event: impl Fn(ChoiceEvent) -> Message + 'a,
) -> Self {
let chooser = chooser.filter(|state| state.is_open());
let input = text_input(
"Name, @alias, kind or containment",
chooser.map_or("", Chooser::query),
)
.on_input(std::convert::identity)
.size(12)
.padding(6)
.width(Length::Fill)
.into();
Self {
content: content.into(),
input,
chooser,
anchor,
on_event: Rc::new(on_event),
focus_scope: None,
}
}
pub fn focus_scope(mut self, scope: Option<super::trigger::FormScope>) -> Self {
self.focus_scope = scope;
self
}
fn reconcile(&self, tree: &mut Tree) {
let state = tree.state.downcast_mut::<Interaction>();
let stamp = self.chooser.map(Chooser::stamp);
if state.stamp.as_ref().map(|s| s.invocation) != stamp.as_ref().map(|s| s.invocation) {
let input = tree.children[1]
.state
.downcast_mut::<text_input::State<R::Paragraph>>();
if stamp.is_some() {
input.focus();
} else {
input.unfocus();
}
state.closing = false;
state.serial = self.chooser.map_or(0, Chooser::query_serial);
}
if state.stamp != stamp {
state.pressed = None;
// A queued Choose can be rejected after a preceding query changed
// the result generation. Reconciliation must unlock this view.
state.closing = false;
state.detail_scroll = 0.;
}
state.stamp = stamp;
}
}
impl<Message: Clone, R: text::Renderer<Font = Font>> Widget<Message, Theme, R>
for Popup<'_, Message, R>
{
fn tag(&self) -> tree::Tag {
tree::Tag::of::<Interaction>()
}
fn state(&self) -> tree::State {
tree::State::new(Interaction::default())
}
fn children(&self) -> Vec<Tree> {
vec![
Tree::new(self.content.as_widget()),
Tree::new(self.input.as_widget()),
]
}
fn diff(&self, tree: &mut Tree) {
tree.children[0].diff(self.content.as_widget());
tree.children[1].diff(self.input.as_widget());
self.reconcile(tree);
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(&mut self, tree: &mut Tree, renderer: &R, limits: &layout::Limits) -> layout::Node {
self.reconcile(tree);
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &R,
operation: &mut dyn Operation,
) {
let mut owner =
super::trigger::FormOwner(self.focus_scope.filter(|_| self.chooser.is_none()));
operation.custom(None, layout.bounds(), &mut owner);
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
let state = tree.state.downcast_mut::<Interaction>();
if state.swallow(event) || self.chooser.is_some() && is_input(event) {
shell.capture_event();
return;
}
if is_input(event) && self.focus_scope.is_some_and(|scope| scope.modal) {
super::trigger::own_input(&mut self.content, &mut tree.children[0], layout, renderer);
}
if let Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(keyboard::key::Named::Tab),
modifiers,
..
}) = event
&& let Some(scope) = self.focus_scope
&& super::trigger::tab(
&mut self.content,
&mut tree.children[0],
layout,
renderer,
scope,
modifiers.shift(),
)
{
shell.capture_event();
shell.request_redraw();
return;
}
super::trigger::measure(
&mut self.content,
&mut tree.children[0],
layout,
renderer,
*viewport,
);
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
fn draw(
&self,
tree: &Tree,
renderer: &mut R,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
if self.chooser.is_some() {
mouse::Cursor::Unavailable
} else {
cursor
},
viewport,
);
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &R,
) -> mouse::Interaction {
if self.chooser.is_some() {
mouse::Interaction::None
} else {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'b>,
renderer: &R,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, R>> {
if let Some(chooser) = self.chooser {
Some(overlay::Element::new(Box::new(ChooserOverlay {
chooser,
anchor: self.anchor,
state: tree.state.downcast_mut(),
input: &mut self.input,
input_tree: &mut tree.children[1],
on_event: &*self.on_event,
})))
} else {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
}
impl<'a, Message: Clone + 'a, R: text::Renderer<Font = Font> + 'a> From<Popup<'a, Message, R>>
for Element<'a, Message, Theme, R>
{
fn from(popup: Popup<'a, Message, R>) -> Self {
Element::new(popup)
}
}
struct ChooserOverlay<'b, 'a, Message, R: text::Renderer<Font = Font>> {
chooser: &'a Chooser,
anchor: Rectangle,
state: &'b mut Interaction,
input: &'b mut Element<'a, String, Theme, R>,
input_tree: &'b mut Tree,
on_event: &'b dyn Fn(ChoiceEvent) -> Message,
}
impl<Message, R: text::Renderer<Font = Font>> ChooserOverlay<'_, '_, Message, R> {
fn geometry(&self, layout: Layout<'_>) -> Geometry {
Geometry::from_bounds(
layout
.children()
.next()
.expect("measured chooser bounds")
.bounds(),
)
}
fn publish(&mut self, action: Action, shell: &mut Shell<'_, Message>) {
if self.state.closing {
return;
}
if action.writes_staged_value() || matches!(action, Action::Close(_)) {
self.state.closing = true;
self.state.swallow_mouse = self.state.held_mouse.or(self.state.swallow_mouse);
self.state.swallow_touch = self.state.held_touch.or(self.state.swallow_touch);
}
shell.publish((self.on_event)(self.chooser.event(action)));
}
fn press(
&mut self,
point: Point,
pointer: Pointer,
geometry: Geometry,
shell: &mut Shell<'_, Message>,
) {
if !geometry.popup.contains(point) {
self.publish(Action::Close(Close::Outside), shell);
} else {
self.state.pressed = geometry
.hit(self.chooser, point)
.map(|action| (self.chooser.event(action), pointer));
}
}
fn release(
&mut self,
point: Point,
pointer: Pointer,
geometry: Geometry,
shell: &mut Shell<'_, Message>,
) {
if let Some((pressed, origin)) = self.state.pressed.take()
&& origin == pointer
&& pressed.stamp == self.chooser.stamp()
&& geometry.hit(self.chooser, point).as_ref() == Some(&pressed.action)
{
self.publish(pressed.action, shell);
}
}
}
impl<Message: Clone, R: text::Renderer<Font = Font>> overlay::Overlay<Message, Theme, R>
for ChooserOverlay<'_, '_, Message, R>
{
fn layout(&mut self, renderer: &R, bounds: Size) -> layout::Node {
let geometry = Geometry::new(self.anchor, bounds);
let input = self
.input
.as_widget_mut()
.layout(
self.input_tree,
renderer,
&layout::Limits::new(Size::ZERO, geometry.search.size()),
)
.move_to(geometry.search.position());
layout::Node::with_children(
bounds,
vec![
layout::Node::new(geometry.popup.size()).move_to(geometry.popup.position()),
input,
],
)
}
fn operate(&mut self, layout: Layout<'_>, renderer: &R, operation: &mut dyn Operation) {
self.input.as_widget_mut().operate(
self.input_tree,
layout.children().nth(1).unwrap(),
renderer,
operation,
);
}
fn update(
&mut self,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
) {
let geometry = self.geometry(layout);
match event {
Event::Mouse(mouse::Event::ButtonPressed(button)) => {
self.state.held_mouse = Some(*button)
}
Event::Mouse(mouse::Event::ButtonReleased(button))
if self.state.held_mouse == Some(*button) =>
{
self.state.held_mouse = None
}
Event::Touch(touch::Event::FingerPressed { id, .. }) => {
self.state.held_touch = Some(*id)
}
Event::Touch(
touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. },
) if self.state.held_touch == Some(*id) => self.state.held_touch = None,
_ => {}
}
if self.state.swallow(event) {
shell.capture_event();
return;
}
if self.state.closing {
if is_input(event) {
shell.capture_event();
}
return;
}
let mut handled = false;
match event {
Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) => {
use keyboard::key::Named;
let action = match key {
keyboard::Key::Named(Named::Escape) => Some(Action::Close(Close::Escape)),
keyboard::Key::Named(Named::Tab) => Some(Action::Close(Close::Tab {
backwards: modifiers.shift(),
})),
keyboard::Key::Named(Named::ArrowDown) => Some(Action::Move {
delta: 1,
rows: geometry.rows,
}),
keyboard::Key::Named(Named::ArrowUp) => Some(Action::Move {
delta: -1,
rows: geometry.rows,
}),
keyboard::Key::Named(Named::PageDown) => Some(Action::Page {
delta: 1,
rows: geometry.rows,
}),
keyboard::Key::Named(Named::PageUp) => Some(Action::Page {
delta: -1,
rows: geometry.rows,
}),
keyboard::Key::Named(Named::Enter) => {
handled = true;
self.chooser
.highlighted()
.filter(|c| self.chooser.visible(geometry.rows).any(|v| v.id == c.id))
.map(|c| Action::Choose(c.id))
}
keyboard::Key::Character(c)
if modifiers.control()
&& modifiers.shift()
&& c.eq_ignore_ascii_case("c") =>
{
clipboard.write(
iced::advanced::clipboard::Kind::Standard,
self.chooser
.highlighted()
.map_or_else(|| self.chooser.current.label(), |c| c.detail()),
);
handled = true;
None
}
_ => None,
};
if let Some(action) = action {
self.publish(action, shell);
handled = true;
}
}
Event::Window(window::Event::Resized(_) | window::Event::Unfocused) => {
self.publish(Action::Close(Close::WindowChanged), shell);
handled = true;
}
Event::Mouse(mouse::Event::ButtonPressed(button)) => {
if let Some(point) = cursor.position() {
if !geometry.popup.contains(point) {
self.state.swallow_mouse = Some(*button);
self.press(point, Pointer::Mouse, geometry, shell);
handled = true;
} else if *button == mouse::Button::Left && !geometry.search.contains(point) {
self.press(point, Pointer::Mouse, geometry, shell);
handled = true;
}
}
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
if self.state.pressed.is_some() =>
{
if let Some(point) = cursor.position() {
self.release(point, Pointer::Mouse, geometry, shell);
} else {
self.state.pressed = None;
}
handled = true;
}
Event::Mouse(mouse::Event::CursorMoved { position })
if self.state.pressed.is_none() =>
{
if let Some(Action::Choose(id)) = geometry.hit(self.chooser, *position)
&& self
.chooser
.highlighted()
.is_none_or(|candidate| candidate.id != id)
{
self.publish(Action::Highlight(id), shell);
}
}
Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
let (x, y) = match delta {
mouse::ScrollDelta::Lines { x, y } => (*x * 24., *y * 24.),
mouse::ScrollDelta::Pixels { x, y } => (*x, *y),
};
self.state.pressed = None;
if cursor
.position()
.is_some_and(|p| geometry.detail.contains(p))
{
let detail = self
.chooser
.highlighted()
.map_or_else(|| self.chooser.current.label(), |c| c.detail());
let max = (measure::<R>(&detail, 11., renderer.default_font())
- geometry.detail.width)
.max(0.);
self.state.detail_scroll =
(self.state.detail_scroll - if x != 0. { x } else { y }).clamp(0., max);
shell.request_redraw();
} else if y != 0. {
self.publish(
Action::Page {
delta: if y < 0. { 1 } else { -1 },
rows: geometry.rows,
},
shell,
);
}
handled = true;
}
Event::Touch(touch::Event::FingerPressed { id, position })
if !geometry.search.contains(*position) =>
{
if !geometry.popup.contains(*position) {
self.state.swallow_touch = Some(*id);
}
self.press(*position, Pointer::Touch(*id), geometry, shell);
handled = true;
}
Event::Touch(touch::Event::FingerLifted { id, position })
if self.state.pressed.is_some() =>
{
self.release(*position, Pointer::Touch(*id), geometry, shell);
handled = true;
}
Event::Touch(touch::Event::FingerLost { .. } | touch::Event::FingerMoved { .. }) => {
self.state.pressed = None;
}
_ => {}
}
if !handled {
let mut messages = Vec::new();
let mut input_shell = Shell::new(&mut messages);
self.input.as_widget_mut().update(
self.input_tree,
event,
layout.children().nth(1).unwrap(),
cursor,
renderer,
clipboard,
&mut input_shell,
&geometry.popup,
);
let serial = Cell::new(self.state.serial);
shell.merge(input_shell, |text| {
serial.set(serial.get().saturating_add(1));
(self.on_event)(self.chooser.event(Action::Query {
text,
serial: serial.get(),
}))
});
self.state.serial = serial.get();
}
if is_input(event) {
shell.capture_event();
}
}
fn draw(
&self,
renderer: &mut R,
theme: &Theme,
renderer_style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
) {
let geometry = self.geometry(layout);
renderer.fill_quad(
renderer::Quad {
bounds: geometry.popup,
border: Border {
color: style::LINE,
width: 1.,
radius: 8.into(),
},
..Default::default()
},
Color::WHITE,
);
renderer.with_layer(geometry.popup, |renderer| {
label(
renderer,
&self.chooser.scope_label,
11.,
style::MUTED,
Rectangle {
x: geometry.popup.x + 8.,
y: geometry.popup.y + 4.,
width: (geometry.popup.width - 78.).max(0.),
height: 22.,
},
);
label(renderer, "Close", 11., style::TEAL, geometry.close);
label(
renderer,
&self.chooser.current.label(),
11.,
style::MUTED,
geometry.current,
);
for (i, candidate) in self.chooser.visible(geometry.rows).enumerate() {
let row = geometry.row(i);
if self
.chooser
.highlighted()
.is_some_and(|c| c.id == candidate.id)
{
renderer.fill_quad(
renderer::Quad {
bounds: row,
..Default::default()
},
Color::from_rgb8(218, 238, 235),
);
}
let alias_width = (row.width * 0.42).min(
measure::<R>(
&format!("@{}", candidate.alias),
11.,
renderer.default_font(),
) + 4.,
);
label(
renderer,
&candidate.name,
12.,
style::INK,
Rectangle {
width: (row.width - alias_width - 6.).max(0.),
height: 17.,
..row
},
);
label(
renderer,
&format!("@{}", candidate.alias),
11.,
style::INK,
Rectangle {
x: row.x + row.width - alias_width,
width: alias_width,
height: 17.,
..row
},
);
label(
renderer,
&candidate.context_label(),
10.,
style::MUTED,
Rectangle {
y: row.y + 17.,
height: 17.,
..row
},
);
}
if self.chooser.count() == 0 {
label(
renderer,
"No compatible matches. Clear the query.",
11.,
style::MUTED,
geometry.row(0),
);
}
let detail = self
.chooser
.highlighted()
.map_or_else(|| self.chooser.current.label(), |c| c.detail());
renderer.with_layer(geometry.detail, |renderer| {
raw_label(
renderer,
detail,
11.,
style::MUTED,
Rectangle {
x: geometry.detail.x - self.state.detail_scroll,
width: geometry.detail.width + self.state.detail_scroll,
height: 16.,
..geometry.detail
},
);
label(
renderer,
"Scroll details · Ctrl+Shift+C copies",
10.,
style::MUTED,
Rectangle {
y: geometry.detail.y + 16.,
height: 16.,
..geometry.detail
},
);
});
label(
renderer,
"‹",
15.,
if self.chooser.start() > 0 {
style::TEAL
} else {
style::MUTED
},
geometry.previous,
);
label(
renderer,
"›",
15.,
if self.chooser.start() + geometry.rows < self.chooser.count() {
style::TEAL
} else {
style::MUTED
},
geometry.next,
);
let count = if self.chooser.count() == 0 {
"0 results".into()
} else {
format!(
"{}–{} / {}",
self.chooser.start() + 1,
(self.chooser.start() + geometry.rows).min(self.chooser.count()),
self.chooser.count()
)
};
label(
renderer,
&count,
11.,
style::MUTED,
Rectangle {
x: geometry.next.x + 30.,
width: (geometry.clear.x - geometry.next.x - 32.).max(0.),
..geometry.next
},
);
if self.chooser.optional() {
label(
renderer,
"Clear reference",
10.,
style::TEAL,
geometry.clear,
);
}
self.input.as_widget().draw(
self.input_tree,
renderer,
theme,
renderer_style,
layout.children().nth(1).unwrap(),
cursor,
&geometry.popup,
);
});
}
fn mouse_interaction(
&self,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &R,
) -> mouse::Interaction {
let geometry = self.geometry(layout);
if cursor
.position()
.is_some_and(|p| geometry.hit(self.chooser, p).is_some())
{
mouse::Interaction::Pointer
} else {
self.input.as_widget().mouse_interaction(
self.input_tree,
layout.children().nth(1).unwrap(),
cursor,
&geometry.popup,
renderer,
)
}
}
}
fn is_input(event: &Event) -> bool {
matches!(
event,
Event::Mouse(_) | Event::Touch(_) | Event::Keyboard(_) | Event::InputMethod(_)
)
}
fn measure<R: text::Renderer<Font = Font>>(content: &str, size: f32, font: Font) -> f32 {
R::Paragraph::with_text(text::Text {
content,
bounds: Size::INFINITE,
size: size.into(),
line_height: text::LineHeight::default(),
font,
align_x: text::Alignment::Left,
align_y: alignment::Vertical::Center,
shaping: text::Shaping::Advanced,
wrapping: text::Wrapping::None,
})
.min_width()
}
fn label<R: text::Renderer<Font = Font>>(
renderer: &mut R,
content: &str,
size: f32,
color: Color,
bounds: Rectangle,
) {
let font = renderer.default_font();
let mut display = content.to_owned();
if measure::<R>(content, size, font) > bounds.width {
let ends: Vec<_> = content
.char_indices()
.map(|(i, _)| i)
.chain(std::iter::once(content.len()))
.collect();
let (mut low, mut high) = (0, ends.len());
while low + 1 < high {
let middle = (low + high) / 2;
if measure::<R>(&format!("{}…", &content[..ends[middle]]), size, font) <= bounds.width
{
low = middle;
} else {
high = middle;
}
}
display = format!("{}…", &content[..ends[low]]);
}
raw_label(renderer, display, size, color, bounds);
}
fn raw_label<R: text::Renderer<Font = Font>>(
renderer: &mut R,
content: String,
size: f32,
color: Color,
bounds: Rectangle,
) {
renderer.fill_text(
text::Text {
content,
bounds: bounds.size(),
size: size.into(),
line_height: text::LineHeight::default(),
font: renderer.default_font(),
align_x: text::Alignment::Left,
align_y: alignment::Vertical::Center,
shaping: text::Shaping::Advanced,
wrapping: text::Wrapping::None,
},
Point::new(bounds.x, bounds.center_y()),
color,
bounds,
);
}
+26 -16
View File
@@ -187,8 +187,8 @@ fn article(topic: Topic) -> Article {
&[
"Choose New in the top bar. Use Project properties to name the model and describe its purpose. Apply changes commits the property draft.",
"On Architecture, choose Create architecture view. Architecture · allocated work shows work inside its performer.",
"Choose Entity in the diagram's Create toolbar. Enter Rescue coordinator, choose Choose position, then click the diagram. Use Actor for an external participant such as a Vessel in distress. You can also right-click a blank area, choose Create Entity here, enter its name and choose Create here.",
"Choose Activity in the same toolbar, name it Assess incident and place it. Select Rescue coordinator and use + Relationship with Allocation to assign Assess incident to it. The allocated-work view then shows the activity inside its performer.",
"Expand the diagram's side palette to see tool names. Choose Entity, click its position in the diagram, enter Rescue coordinator and press Enter. Escape cancels the draft. Use Actor for an external participant such as a Vessel in distress. Right-clicking a blank area also offers Create Entity here.",
"Right-click Rescue coordinator and choose Add activity. Enter Assess incident and press Enter to create the activity and its performer allocation together. Ordinary Activity creation in the palette leaves work unallocated; use + Relationship with Allocation to assign existing work. The allocated-work view shows work inside its performer.",
"Use Add existing to place an element that is already in the model. The initial choices match this view; no search is required. Include already shown offers Locate for elements already placed here.",
"Add a second activity for another participant. Select an activity, choose + Relationship, select Interaction and choose the compatible target. Name the exchange after what is conveyed.",
"Visit Model checks to review unfinished work. Save all writes the accepted model and applied drafts to your chosen file.",
@@ -262,8 +262,8 @@ fn article(topic: Topic) -> Article {
"Create and allocate work",
&[
"Choose the Operational or System perspective. Create participants using Entity/Actor in OA or System/System actor in SA.",
"In the diagram's Create toolbar, choose Activity in OA or Function in SA, enter a name and click to place it. For semantic decomposition, use Model explorer, select existing work and use + In selected to create smaller work units.",
"To assign work to a participant, use + Relationship with Allocation from the participant to the leaf work. Model explorer also offers + Allocated when a participant and the appropriate work kind are selected.",
"In the diagram's side palette, choose Activity in OA or Function in SA, click its position, enter a name and press Enter. Escape cancels without creating an element. Select a card and press F2 to rename it in place. For semantic decomposition, use Model explorer, select existing work and use + In selected to create smaller work units.",
"Right-click a participant and choose Add activity or Add function to create new work and its allocation together. To assign existing leaf work, use + Relationship with Allocation from the participant to the work. Model explorer also offers + Allocated when a participant and the appropriate work kind are selected.",
"Choose Architecture · allocated work to review responsibilities. Choose Functional dataflow to review the activity/function hierarchy and its exchanges independently.",
],
),
@@ -445,9 +445,9 @@ fn article(topic: Topic) -> Article {
walkthrough(
"Describe a path through exchanges",
&[
"First create the activities/functions and their exchanges. Check the source and target work for every exchange.",
"Open Behavior & scenarios. Create Process in OA or Functional chain in SA using Create element and + At root.",
"Select that behavior in the page's selector. Open Tools and choose Work or Exchange, then a highlighted path or contribution position to involve an existing source. Each contribution keeps its own identity while referring to the shared engineering definition.",
"A blank path offers Add first activity/function contribution. You can use existing work or stage a new source in that form; exchanges still need explicit compatible source and target work.",
"Open Behavior & scenarios → New. Choose Operational process in OA or Functional chain in SA, enter its exact name, then Create and open. The new behavior belongs at the layer root and opens immediately; Undo removes the creation as one edit.",
"Open Tools and choose Work or Exchange, then a highlighted position. In Work, Create new source keeps the contribution name and position while you name its Activity/Function and choose its semantic parent. Use this new source stages it; Create commits source and contribution in one Undo. An adjacent exchange may require a particular existing work identity.",
"In Tools, choose Sequence link and click or drag from the preceding contribution to the following contribution. Choose Tools → Select / reorder to drag a selected path endpoint and reconnect it; a contribution's ↕ handle changes its position within a column. These are local contributions and sequence links, not new architecture exchanges.",
"Select a contribution, then add another after it. Tools → Two paths… creates a split, two paths and their merge in one undoable edit. Enter explicit alternative conditions. Fit overview uses the visible canvas area; 100% keeps working scale with scrollbars. If the minimum zoom is reached, scroll to inspect the remainder.",
"Use Chain involvement from the Process/Functional chain to the capability it supports. Read Model checks for unfinished or disconnected paths.",
@@ -489,20 +489,20 @@ fn article(topic: Topic) -> Article {
walkthrough(
"Create a scenario",
&[
"Open Behavior & scenarios, choose Scenario under Create element and add it at a legal root/owner. Select the scenario in the behavior selector.",
"Use + Lifeline and choose the participant or work it represents. Choices follow the scenario's viewpoint: operational activities, operational participants, system functions or system boundary participants.",
"Choose + Message and its style. Call + correlated reply creates both occurrences in one edit. Select the exchange and compatible sending/receiving lifelines. Reply to existing call offers valid unanswered calls.",
"Use Action, Observe state or Fragment for other behavior. A local timer has an expression and a lifeline, with no global exchange. Create and delete messages describe participant lifetime; Model checks also flag risks inside repeated loops.",
"Choose a message style and Draw message. Start at a highlighted sequence position on a lifeline, then click or drag to the receiving lifeline. The form retains the chosen position while you select the exchange and details. Escape cancels the gesture.",
"Open Behavior & scenarios → New → Scenario and enter its name. Explicitly choose Activities or Participants in OA, or Functions or System boundary in SA. Add optional context only when needed: this is a reference, while the scenario itself belongs at the layer root. Create and open starts the empty scenario.",
"Use Add first lifeline on an empty scenario, or + Lifeline. Choose existing work/participant or Create new source. The explicit viewpoint limits its kinds; choose participant kinds deliberately. Source name and lifeline name are separate, and the source semantic parent is independent of the scenario. No allocation or capability involvement is inferred.",
"Choose a message style in the tool selector. Start at a highlighted sequence position on a lifeline, then click or drag to the receiving lifeline. Complete the exchange and details in the form, which retains that sequence position. Escape cancels the gesture.",
"Call + correlated reply creates both occurrences in one edit. Reply to existing call offers valid unanswered calls. A local timer has an expression and a lifeline, with no global exchange. Create and delete messages describe participant lifetime; Model checks also flag risks inside repeated loops.",
"Choose Add action, Observe state, Reuse scenario or Add fragment and click the intended sequence position. Clicking an action or observation on a lifeline also selects that lifeline. Complete any remaining choices before Create.",
"In Select / reorder, click an occurrence and drag its ↕ handle to another position within the same sequence. The ordered list's up/down controls provide another way to reorder. Select an occurrence to inspect its particular use of the exchange, including its message values.",
],
),
walkthrough(
"Describe alternatives",
&[
"Choose Fragment and select ALT, PAR, LOOP or OPT. Enter the branch conditions; the tool creates the fragment and its operands together.",
"Use the Destination selector in subsequent message or action forms to choose the intended operand. New occurrences append to that operand's ordered behavior.",
"Use Reuse scenario to refer to existing behavior. Bind every referenced lifeline to a compatible local lifeline explicitly. Open source follows the original scenario without copying its contents.",
"Choose Add fragment, click its sequence position and select ALT, PAR, LOOP or OPT. Enter the branch conditions; the tool creates the fragment and its operands together.",
"Click the highlighted position inside an operand to place the next message, action or reference there. The form shows its destination and insertion position. Append to this sequence instead explicitly moves the pending insertion to that sequence's end.",
"Choose Reuse scenario and click its position, then bind every referenced lifeline to a compatible local lifeline explicitly. Select the resulting use and choose Open definition. Back to caller returns to that exact use and its viewport after you apply or cancel pending edits.",
"Inspect the scenario projection and Model checks. State exactly what each guard means, including units and assumptions where relevant.",
],
),
@@ -543,7 +543,9 @@ fn article(topic: Topic) -> Article {
walkthrough(
"Build a state machine",
&[
"In Behavior & scenarios, create or select a State machine, then choose Create diagram. This places its existing regions and vertices in a saved view. + View creates another independent layout.",
"In Behavior & scenarios → New → State machine, enter its name and search for the existing same-layer participant that owns it. Candidate labels show parent context and alias to distinguish repeated names.",
"If the owner does not exist, Create new owner retains the machine name and first-view option. Choose its participant kind and semantic parent explicitly. Use this new source returns without changing the model; Create and open commits owner, machine and optional view together.",
"Optionally select Create the first state view, then Create and open. The new machine starts without regions or states. For an existing machine, Create diagram places its existing regions and vertices in a saved view; + View creates another independent layout.",
"Choose + Region and click the highlighted machine, or a State/Mode for a nested region. Choose Initial, State, Mode or another kind from + State / symbol, then click its highlighted owning region. Rename the new element in Properties.",
"Choose Transition and drag from a source vertex to a compatible target, or click the source and then the target. In Select / move, drag states or containers to arrange them; a container moves its descendant placements without changing ownership.",
"Select a drawn transition and drag its endpoint handle to reconnect it. Its right-click menu also offers Reconnect source and Reconnect target; choose one, then click a compatible vertex.",
@@ -696,6 +698,10 @@ fn article(topic: Topic) -> Article {
"Map references by meaning",
"Reference mapping connect exact OA and SA identities used by the proposed change. Similar names are not sufficient. Map the records that play the same engineering role, including enclosing fields in qualified message-value paths. Mapping a referenced record does not authorize creating, moving or editing that record. If it needs a counterpart, establish that correspondence first.",
),
explain(
"Edit stored observations deliberately",
"In a trace's Properties, Edit stored history (advanced)… edits the observations retained by that trace. Choose the fact and enter its Operational and System observations explicitly. Not applicable, an observed absent value, and no stored fact have different meanings. Historical references may retain the exact UUID of a deleted record. Apply changes validates the complete history; Undo restores it. These history edits leave both counterpart records unchanged. Use Review counterpart changes… for Keep/Take decisions about their current engineering content.",
),
walkthrough(
"Review one message value or lifeline binding",
&[
@@ -894,6 +900,10 @@ fn article(topic: Topic) -> Article {
"A property draft is not yet the model",
"Apply changes validates the candidate. When it is rejected, correct the retained draft or use Revert. The canvas continues to show accepted values. Navigation that needs to apply an invalid draft may remain on the current record so your work is not lost. You can read this guide without applying or discarding that draft.",
),
explain(
"A new behavior is still a draft",
"Inside a source subform, Back or the first Escape returns to the unchanged parent. Use this new source stages the prerequisite only. Canceling the parent discards it; choosing an existing reference excludes the staged source from creation. Recovery retains both forms and their reserved identities. An open dialog still receives Escape first. Behavior → New keeps the exact name, owner and viewpoint choices outside the model until Create and open succeeds. Cancel or Escape discards only this draft; if a dialog is open, the first Escape dismisses that dialog. New refuses other unfinished property, source or behavior drafts without applying them. Recovery restores the creation form in its original layer, including rejected raw text, for correction or cancellation.",
),
explain(
"Aliases and references",
"Stable source aliases must follow the language's identifier rules and avoid reserved words. Use a simple descriptive identifier such as assess_incident. Spaces belong in the displayed Name, not the alias. Reference pickers offer compatible model records; creating the required target first is often the missing step.",
+3
View File
@@ -87,6 +87,9 @@ pub enum RowEvent {
ValuePath(String, crate::data_values::FieldPathKey),
ValueBrowse(String, Option<crate::data_values::FieldPathKey>, usize),
ReferenceBrowse(String, String, usize),
ReferenceOpen(crate::forms::reference_chooser::adapter::Open),
ReferenceEvent(crate::forms::reference_chooser::Event),
ReferenceSet(crate::forms::reference_chooser::adapter::Set),
OperationOmission(bool),
OperationRationale(String),
Tab(Tab),
+75 -3
View File
@@ -296,6 +296,51 @@ impl State {
}
Ok(())
}
pub(crate) fn reference_form(&self, project: &Project) -> Option<&Draft> {
let facet = self.active.selected.as_ref()?;
if self.frozen(project).is_err()
|| self.active.tab != Tab::Facts
|| self.active.decisions.get(facet) != Some(&SemanticDecision::Candidate)
{
return None;
}
self.active.candidate_draft(facet)
}
pub(crate) fn reference_draft(
&self,
project: &Project,
address: Option<RowAddress>,
facet: &FacetSelector,
path: &str,
) -> Option<&Draft> {
if self.frozen(project).is_err()
|| self.active_address != address
|| self.active.tab != Tab::Facts
{
return None;
}
self.active.reference_draft(project, facet, path)
}
pub(crate) fn set_reference(
&mut self,
project: &Project,
address: Option<RowAddress>,
facet: &FacetSelector,
intent: crate::forms::reference_chooser::adapter::Set,
) -> Result<(), String> {
self.reference_draft(project, address, facet, &intent.context.path)
.ok_or("The originating review row or property is no longer active.")?
.reference_value(project, &intent)?;
self.update(
project,
Event::Row {
address,
facet: Some(facet.clone()),
event: RowEvent::ReferenceSet(intent),
},
);
Ok(())
}
pub fn update(&mut self, project: &Project, event: impl Into<Event>) {
let event = event.into();
#[cfg(test)]
@@ -303,6 +348,30 @@ impl State {
Event::Editor(event) => self.address_event(event),
other => other,
};
match &event {
Event::Row {
event: RowEvent::ReferenceOpen(_) | RowEvent::ReferenceEvent(_),
..
}
| Event::Editor(RowEvent::ReferenceOpen(_) | RowEvent::ReferenceEvent(_)) => return,
Event::Row {
address,
facet,
event: RowEvent::ReferenceSet(intent),
} => {
let valid = facet
.as_ref()
.and_then(|facet| {
self.reference_draft(project, *address, facet, &intent.context.path)
})
.is_some_and(|draft| draft.reference_value(project, intent).is_ok());
if !valid {
return;
}
}
Event::Editor(RowEvent::ReferenceSet(_)) => return,
_ => {}
}
if let Err(error) = self.frozen(project) {
// Withdrawing a pending reset is authored intent only. Retain it while
// keeping the original accepted base and disabling every stale plan.
@@ -464,7 +533,8 @@ impl State {
);
let scoped_edit = matches!(
event,
RowEvent::Input(_, _)
RowEvent::ReferenceSet(_)
| RowEvent::Input(_, _)
| RowEvent::Text(_, _)
| RowEvent::Shape(_, _)
| RowEvent::Variant(_, _)
@@ -747,13 +817,15 @@ impl State {
if let Some(notice) = &self.notice {
header = header.push(text(notice).size(11));
}
self.active
let view = self
.active
.view(&self.base, header.into(), self.can_apply())
.map(move |message| match message {
Message::Workflow(crate::workflow::Event::Semantic(Event::Editor(event))) => {
Message::Workflow(crate::workflow::Event::Semantic(self.address_event(event)))
}
other => other,
})
});
crate::forms::reference_chooser::trigger::modal(view)
}
}
@@ -166,6 +166,14 @@ impl ReviewRow {
pub fn update(&mut self, project: &Project, event: RowEvent) {
let mut replan = true;
let result = match event {
// Browser messages belong to the app overlay and must never replan.
RowEvent::ReferenceOpen(_) | RowEvent::ReferenceEvent(_) => return,
RowEvent::ReferenceSet(intent) => {
let path = intent.context.path.clone();
self.edit(project, &path, |draft| {
draft.reference_set(project, &intent)
})
}
RowEvent::OperationOmission(enabled) => {
self.operation_omission =
enabled.then(|| self.operation_omission.clone().unwrap_or_default());
@@ -518,6 +526,25 @@ impl ReviewRow {
}
}
pub(super) fn reference_draft(
&self,
project: &Project,
facet: &FacetSelector,
path: &str,
) -> Option<&Draft> {
if self.selected.as_ref() != Some(facet)
|| self.decisions.get(facet) != Some(&SemanticDecision::Candidate)
|| matches!(path, "/id" | "/alias" | "/body" | "/layer")
|| !self
.candidate_roots(project, facet)?
.iter()
.any(|root| path == root || path.starts_with(&format!("{root}/")))
{
return None;
}
self.candidate_draft(facet)
}
fn edit(
&mut self,
project: &Project,
@@ -895,6 +922,8 @@ pub fn form_event(message: Message) -> Message {
Message::FieldReferenceBrowse(path, query, page) => {
RowEvent::ReferenceBrowse(path, query, page)
}
Message::FieldReferenceOpen(request) => RowEvent::ReferenceOpen(request),
Message::FieldReferenceEvent(event) => RowEvent::ReferenceEvent(event),
_ => RowEvent::Preview,
};
Message::Workflow(crate::workflow::Event::Semantic(Event::Editor(event)))
@@ -867,7 +867,13 @@ impl ReviewRow {
) {
detail = detail.push(text("Attached facts are separate from referenced definitions. Removing membership never implies deleting a semantic object.").size(11).color(style::MUTED));
}
detail.into()
if self.decisions.get(&fact.selector) == Some(&SemanticDecision::Candidate)
&& let Some(draft) = self.candidate_draft(&fact.selector)
{
crate::forms::reference_chooser::trigger::scope(detail, draft.reference_session())
} else {
detail.into()
}
}
fn members_view<'a>(&'a self, project: &'a Project) -> Element<'a, Message> {
+7 -5
View File
@@ -228,13 +228,15 @@ pub fn view(app: &App) -> View<'_, Message> {
Page::Guide => crate::guide::view(&app.guide),
};
let process_layout = app.topology_context().is_some();
let focus_process = process_layout && app.behavior.topology.focused;
let scenario_layout = app.scenario_context().is_some();
let focus_behavior = (process_layout && app.behavior.topology.focused)
|| (scenario_layout && app.behavior.scenario.focused());
let mut body = if app.page == Page::Home {
row![container(main).width(Fill).height(Fill)].height(Fill)
} else if process_layout {
} else if process_layout || scenario_layout {
// Keep main at the same widget-tree path across Focus toggles. The
// collapsed slot has no controls, so it cannot paint over or hit the canvas.
let process_sidebar: View<'_, Message> = if focus_process {
let process_sidebar: View<'_, Message> = if focus_behavior {
Space::new().width(0).into()
} else {
sidebar.into()
@@ -242,7 +244,7 @@ pub fn view(app: &App) -> View<'_, Message> {
// Row::push would discard the zero-width slot and shift main again.
widget::Row::from_vec(vec![
container(process_sidebar)
.width(if focus_process { 0 } else { 260 })
.width(if focus_behavior { 0 } else { 260 })
.height(Fill)
.clip(true)
.into(),
@@ -253,7 +255,7 @@ pub fn view(app: &App) -> View<'_, Message> {
} else {
row![sidebar, container(main).width(Fill).height(Fill)].height(Fill)
};
if !focus_process && !matches!(app.page, Page::Home | Page::Text | Page::Guide) {
if !focus_behavior && !matches!(app.page, Page::Home | Page::Text | Page::Guide) {
body = body.push(inspector(app));
}
let footer = container(
+2 -1
View File
@@ -2,7 +2,8 @@
Run from any directory with Python 3: semantic_schema.py [--check] [--validate].
--validate additionally runs source-7 structural fixtures with jsonschema.
This generates documentation only, never runtime selectors or model mutations.
The desktop stored-history editor reads the checked-in descriptor for field
shapes. Core types and validation remain authoritative for model mutations.
"""
import copy
import json
+11
View File
@@ -1,9 +1,19 @@
# syntax=docker/dockerfile:1
# Requires --build-context server_notices=<prepared server-notices directory>.
# See docs/linux-packaging.md. Missing/stale notices fail before application build.
FROM rust:1.90-bookworm AS builder
RUN apt-get update && apt-get install -y --no-install-recommends python3 \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /src
COPY Cargo.toml Cargo.lock ./
COPY LICENSE ./LICENSE
COPY build ./build
COPY crates ./crates
COPY docs/openapi.json ./docs/openapi.json
COPY scripts/package-artifacts.py ./scripts/package-artifacts.py
COPY --from=server_notices / /tmp/server-notices/
RUN python3 scripts/package-artifacts.py verify-notices \
--directory /tmp/server-notices --repository /src --target x86_64-unknown-linux-gnu
RUN cargo build --release --locked -p oa-server
FROM debian:bookworm-slim
@@ -12,6 +22,7 @@ RUN groupadd --gid 10001 arcadia \
&& mkdir /data \
&& chown 10001:10001 /data
COPY --from=builder /src/target/release/arcadia-server /usr/local/bin/arcadia-server
COPY --from=builder /tmp/server-notices/ /usr/share/doc/arcadia-server/
USER 10001:10001
VOLUME ["/data"]
EXPOSE 8787
+22 -7
View File
@@ -1,9 +1,24 @@
.git
target
dist
harness
# Only inputs consumed by this Dockerfile enter the ordinary repository context.
# The server_notices named context is supplied separately and verified in builder.
**
!Cargo.toml
!Cargo.lock
!LICENSE
!build/
!build/**
!crates/
!crates/**
!docs/
!docs/openapi.json
!scripts/
!scripts/package-artifacts.py
!deployment/
!deployment/Dockerfile
!deployment/Dockerfile.dockerignore
# Do not admit generated/private files even inside an allowed source tree.
**/target
**/*.sqlite3
**/.git
**/.env
**/.env.*
**/*.log
.codex
.openai
**/*.sqlite3
+71 -20
View File
@@ -752,7 +752,7 @@ lists all additional fields. <span class="docutils literal">ref</span> means <sp
</tr>
<tr><td><p><span class="docutils literal">oa_scenario</span>, <span class="docutils literal">sa_scenario</span></p></td>
<td><p><span class="docutils literal">viewpoint</span>: ScenarioViewpoint; <span class="docutils literal">context</span>: ref?; <span class="docutils literal">precondition</span>, <span class="docutils literal">postcondition</span>: strings; <span class="docutils literal">steps</span>: occurrence refs</p></td>
<td><p>MixedLegacy for omitted schema-2 source; none; <span class="docutils literal">&quot;&quot;</span>; <span class="docutils literal">&quot;&quot;</span>; <span class="docutils literal">[]</span></p></td>
<td><p>MixedLegacy when viewpoint is omitted, including newly authored source 7 (see section 4.3); none; <span class="docutils literal">&quot;&quot;</span>; <span class="docutils literal">&quot;&quot;</span>; <span class="docutils literal">[]</span></p></td>
</tr>
<tr><td><p><span class="docutils literal">oa_lifeline</span>, <span class="docutils literal">sa_lifeline</span></p></td>
<td><p><span class="docutils literal">represented</span>: participant, work, or role ref?</p></td>
@@ -792,49 +792,71 @@ An Enumeration contains unique string literals. For example:</p>
<pre class="code text literal-block"><code>definition { Enumeration { literals [&quot;Clear&quot;, &quot;Fog&quot;]; }; };
type_ref { Named &#64;weather_classification; };</code></pre>
<p>These are typed constructors with named fields, not embedded JSON documents.
Constructor field names and enum spellings are case-sensitive. When replacing
a constructor, all of its fields MUST be supplied; the containing declaration
defaults do not silently fill a different constructor's missing fields.
During schema-2 compatibility, the new Exchange fields <span class="docutils literal">message_kind</span>,
<span class="docutils literal">reply_to</span> and <span class="docutils literal">values</span> are exceptions: omitted values hydrate as
Asynchronous, none and [] respectively. Canonical output writes them explicitly.
This preserves older schema-2 source/JSON without inventing call correlation or
value annotations. It is not a rule for an unspecified future schema.</p>
Constructor field names and enum spellings are case-sensitive. A selected
constructor uses its own field contract; it does not inherit the payload of a
different constructor from the declaration default. Required fields MUST be
supplied. Nullability and omission are separate properties: <span class="docutils literal">?</span> denotes a
value that can be <span class="docutils literal">none</span>; a constructor's omission contract determines whether
the field may be absent. There is no general all-constructor-fields-required
rule. Other typed constructors use their contracts in the corresponding
sections; the occurrence rules below do not establish defaults for them.</p>
<p>The following table records the source-7 OccurrenceBody contracts. Optional
references may be omitted and then mean <span class="docutils literal">none</span>. Exchange also admits omitted
<span class="docutils literal">message_kind</span> and <span class="docutils literal">values</span>, meaning Asynchronous and <span class="docutils literal">[]</span> respectively.
These omissions are accepted in newly authored source 7, not only in schema-2
compatibility input. Earlier schema admission of constructors and fields is
still governed by its version rules.</p>
<p>Canonical formatting writes the hydrated occurrence references and default
<span class="docutils literal">message_kind</span>, <span class="docutils literal">reply_to</span> and <span class="docutils literal">values</span> explicitly. An absent
<span class="docutils literal">operation</span> remains omitted in canonical output. Lossless no-op updates and
unrelated name edits retain authored omissions; canonical formatting is a
different operation. An admitted incomplete occurrence can still produce model
checks requesting its missing work, exchange, lifeline or referenced scenario.</p>
<table>
<caption>Occurrence body constructors</caption>
<colgroup>
<col style="width: 22.0%" />
<col style="width: 78.0%" />
<col style="width: 18.0%" />
<col style="width: 36.0%" />
<col style="width: 46.0%" />
</colgroup>
<thead>
<tr><th class="head"><p>Constructor</p></th>
<th class="head"><p>Required fields</p></th>
<th class="head"><p>Fields that may be omitted, with their resulting values</p></th>
</tr>
</thead>
<tbody>
<tr><td><p>Exchange</p></td>
<td><p><span class="docutils literal">exchange</span>: exchange relation ref?; <span class="docutils literal">sender</span>, <span class="docutils literal">receiver</span>: lifeline refs?; <span class="docutils literal">message_kind</span>: MessageKind; <span class="docutils literal">reply_to</span>: occurrence ref?; <span class="docutils literal">values</span>: MessageValue records</p></td>
<td><p>None</p></td>
<td><p><span class="docutils literal">exchange</span>: exchange relation ref?, <span class="docutils literal">sender</span>, <span class="docutils literal">receiver</span>: lifeline refs?, <span class="docutils literal">reply_to</span>: occurrence ref?, <span class="docutils literal">operation</span>: OperationUse? → <span class="docutils literal">none</span>; <span class="docutils literal">message_kind</span>: MessageKind → Asynchronous; <span class="docutils literal">values</span>: MessageValue records → <span class="docutils literal">[]</span></p></td>
</tr>
<tr><td><p>Action</p></td>
<td><p><span class="docutils literal">action</span>: activity/function ref?; <span class="docutils literal">lifeline</span>: ref?</p></td>
<td><p>None</p></td>
<td><p><span class="docutils literal">action</span>: activity/function ref?, <span class="docutils literal">lifeline</span>: ref? → <span class="docutils literal">none</span></p></td>
</tr>
<tr><td><p>Control</p></td>
<td><p><span class="docutils literal">kind</span>: Choice, Merge, Fork, Join, Loop</p></td>
<td><p>None</p></td>
</tr>
<tr><td><p>SequenceReference</p></td>
<td><p><span class="docutils literal">sequence</span>: process/functional-chain ref?</p></td>
<td><p>None</p></td>
<td><p><span class="docutils literal">sequence</span>: process/functional-chain ref? → <span class="docutils literal">none</span></p></td>
</tr>
<tr><td><p>ScenarioUse</p></td>
<td><p><span class="docutils literal">scenario</span>: scenario ref?; <span class="docutils literal">bindings</span>: LifelineBinding records</p></td>
<td><p><span class="docutils literal">bindings</span>: LifelineBinding records</p></td>
<td><p><span class="docutils literal">scenario</span>: scenario ref? → <span class="docutils literal">none</span></p></td>
</tr>
<tr><td><p>State</p></td>
<td><p><span class="docutils literal">state</span>: state/mode ref?; <span class="docutils literal">lifeline</span>: ref?</p></td>
<td><p>None</p></td>
<td><p><span class="docutils literal">state</span>: state/mode ref?, <span class="docutils literal">lifeline</span>: ref? → <span class="docutils literal">none</span></p></td>
</tr>
<tr><td><p>Fragment</p></td>
<td><p><span class="docutils literal">operator</span>: Alternative, Parallel, Loop, Optional; <span class="docutils literal">branches</span>: branch occurrence refs</p></td>
<td><p>None</p></td>
</tr>
<tr><td><p>Branch</p></td>
<td><p><span class="docutils literal">guard</span>: string; <span class="docutils literal">occurrences</span>: occurrence refs</p></td>
<td><p>None</p></td>
</tr>
</tbody>
</table>
@@ -1274,9 +1296,21 @@ reference checks.</p>
<p>Omitted schema-2 viewpoints hydrate as MixedLegacy in both source and JSON.
This preserves pre-extension mixed work/participant scenes without discarding
their lifelines or silently assigning a stricter meaning. MixedLegacy emits a
review warning. New graphical factories explicitly select OperationalActivity
or Functional by layer. Authors can select a strict viewpoint after reviewing
the legacy scene; canonical source then records that choice.</p>
review warning. Source parsing also uses MixedLegacy when <span class="docutils literal">viewpoint</span> is
omitted from a newly authored source-7 scenario; it does not infer a strict
viewpoint from the layer or lifelines. Write the intended viewpoint explicitly
when starting a scenario. For example, this new OA source project starts an
activity-based scenario whose lifelines and occurrences can be added later:</p>
<pre class="literal-block">arcadia 7;
project response &quot;Distress response&quot; {
oa_scenario assessment &quot;Assess the distress report&quot; {
viewpoint OperationalActivity;
}
}</pre>
<p>An empty scenario can produce completeness warnings while remaining editable.
The desktop's Behavior <strong>New</strong> flow asks authors to choose one of the layer's
two strict viewpoints explicitly. Authors can also select a strict viewpoint
after reviewing a legacy scene; canonical source then records that choice.</p>
<p>MessageKind is Asynchronous, Call, Reply, Create, Delete, or
<span class="docutils literal">{ Timer { expression &quot;after 5 s&quot;; }; }</span>. A process/chain exchange
contribution MUST remain Asynchronous with no reply correlation. Call/reply,
@@ -2217,6 +2251,23 @@ strings use JSON string escaping, including <span class="docutils literal">\n</s
and Unicode escapes. Literal unescaped newlines inside strings are invalid.
Numbers use JSON decimal/exponent syntax; NaN, infinity, hexadecimal numbers,
leading plus signs, and leading zeroes are invalid.</p>
<p>A small model may begin with engineering declarations alone. This complete
source describes two participants, their work, responsibility and an exchange:</p>
<pre class="literal-block">arcadia 7;
project distress &quot;Distress response&quot; {
oa_actor vessel &quot;Vessel in distress&quot; {}
oa_entity rescue &quot;Rescue coordination&quot; {}
oa_activity report &quot;Report distress&quot; {}
oa_activity assess &quot;Assess incident&quot; {}
allocation vessel_reports &quot;Crew reports&quot; { source &#64;vessel; target &#64;report; }
allocation rescue_assesses &quot;Team assesses&quot; { source &#64;rescue; target &#64;assess; }
interaction distress_report &quot;Distress report&quot; { source &#64;report; target &#64;assess; }
}</pre>
<p>No diagram, placement, empty description or explicit root parent is required.
The accepted source adds identities; keep those clauses during later edits.
Changing <span class="docutils literal">&quot;Assess incident&quot;</span> changes the display name while <span class="docutils literal">&#64;assess</span> still
resolves to the same activity. Behavior-coverage warnings permit this intermediate
model to be saved. Allocation remains explicit and distinct from decomposition.</p>
<p>Aliases match <span class="docutils literal"><span class="pre">[A-Za-z_][A-Za-z0-9_]*</span></span>. The following aliases are reserved:
arcadia, project, id, oa, sa, element, relation, diagram, node, artifact,
trace, body, alias, name, description, parent, from, to, entity, actor,
@@ -2227,7 +2278,7 @@ spellings can be used in alias positions because references begin with <span cla
<span class="docutils literal"><span class="pre">element-kind</span></span> and <span class="docutils literal"><span class="pre">relation-kind</span></span> are exactly the corresponding declaration
keywords listed above. Typed field
sets and enum constructors are closed by sections 3–5.</p>
<pre class="code text literal-block"><code>document = &quot;arcadia&quot; &quot;5&quot; &quot;;&quot; project
<pre class="code text literal-block"><code>document = &quot;arcadia&quot; &quot;7&quot; &quot;;&quot; project
project = &quot;project&quot; alias string identity? &quot;{&quot; project-entry* &quot;}&quot;
project-entry = &quot;description&quot; string &quot;;&quot; | declaration
declaration = element
+76 -19
View File
@@ -120,7 +120,7 @@ lists all additional fields. ``ref`` means ``@alias``; ``ref?`` also accepts
- No implicit contract; ``legacy`` defaults none. OA admits Legacy only.
* - ``oa_scenario``, ``sa_scenario``
- ``viewpoint``: ScenarioViewpoint; ``context``: ref?; ``precondition``, ``postcondition``: strings; ``steps``: occurrence refs
- MixedLegacy for omitted schema-2 source; none; ``""``; ``""``; ``[]``
- MixedLegacy when viewpoint is omitted, including newly authored source 7 (see section 4.3); none; ``""``; ``""``; ``[]``
* - ``oa_lifeline``, ``sa_lifeline``
- ``represented``: participant, work, or role ref?
- none
@@ -155,37 +155,60 @@ An Enumeration contains unique string literals. For example:
type_ref { Named @weather_classification; };
These are typed constructors with named fields, not embedded JSON documents.
Constructor field names and enum spellings are case-sensitive. When replacing
a constructor, all of its fields MUST be supplied; the containing declaration
defaults do not silently fill a different constructor's missing fields.
During schema-2 compatibility, the new Exchange fields ``message_kind``,
``reply_to`` and ``values`` are exceptions: omitted values hydrate as
Asynchronous, none and [] respectively. Canonical output writes them explicitly.
This preserves older schema-2 source/JSON without inventing call correlation or
value annotations. It is not a rule for an unspecified future schema.
Constructor field names and enum spellings are case-sensitive. A selected
constructor uses its own field contract; it does not inherit the payload of a
different constructor from the declaration default. Required fields MUST be
supplied. Nullability and omission are separate properties: ``?`` denotes a
value that can be ``none``; a constructor's omission contract determines whether
the field may be absent. There is no general all-constructor-fields-required
rule. Other typed constructors use their contracts in the corresponding
sections; the occurrence rules below do not establish defaults for them.
The following table records the source-7 OccurrenceBody contracts. Optional
references may be omitted and then mean ``none``. Exchange also admits omitted
``message_kind`` and ``values``, meaning Asynchronous and ``[]`` respectively.
These omissions are accepted in newly authored source 7, not only in schema-2
compatibility input. Earlier schema admission of constructors and fields is
still governed by its version rules.
Canonical formatting writes the hydrated occurrence references and default
``message_kind``, ``reply_to`` and ``values`` explicitly. An absent
``operation`` remains omitted in canonical output. Lossless no-op updates and
unrelated name edits retain authored omissions; canonical formatting is a
different operation. An admitted incomplete occurrence can still produce model
checks requesting its missing work, exchange, lifeline or referenced scenario.
.. list-table:: Occurrence body constructors
:header-rows: 1
:widths: 22 78
:widths: 18 36 46
* - Constructor
- Required fields
- Fields that may be omitted, with their resulting values
* - Exchange
- ``exchange``: exchange relation ref?; ``sender``, ``receiver``: lifeline refs?; ``message_kind``: MessageKind; ``reply_to``: occurrence ref?; ``values``: MessageValue records
- None
- ``exchange``: exchange relation ref?, ``sender``, ``receiver``: lifeline refs?, ``reply_to``: occurrence ref?, ``operation``: OperationUse? → ``none``; ``message_kind``: MessageKind → Asynchronous; ``values``: MessageValue records → ``[]``
* - Action
- ``action``: activity/function ref?; ``lifeline``: ref?
- None
- ``action``: activity/function ref?, ``lifeline``: ref? → ``none``
* - Control
- ``kind``: Choice, Merge, Fork, Join, Loop
- None
* - SequenceReference
- ``sequence``: process/functional-chain ref?
- None
- ``sequence``: process/functional-chain ref? → ``none``
* - ScenarioUse
- ``scenario``: scenario ref?; ``bindings``: LifelineBinding records
- ``bindings``: LifelineBinding records
- ``scenario``: scenario ref? → ``none``
* - State
- ``state``: state/mode ref?; ``lifeline``: ref?
- None
- ``state``: state/mode ref?, ``lifeline``: ref? → ``none``
* - Fragment
- ``operator``: Alternative, Parallel, Loop, Optional; ``branches``: branch occurrence refs
- None
* - Branch
- ``guard``: string; ``occurrences``: occurrence refs
- None
For example, ``body { Action { action @assess; lifeline @operator_line; }; };``
selects an Action occurrence. Processes and functional chains contain Exchange,
@@ -631,9 +654,23 @@ reference checks.
Omitted schema-2 viewpoints hydrate as MixedLegacy in both source and JSON.
This preserves pre-extension mixed work/participant scenes without discarding
their lifelines or silently assigning a stricter meaning. MixedLegacy emits a
review warning. New graphical factories explicitly select OperationalActivity
or Functional by layer. Authors can select a strict viewpoint after reviewing
the legacy scene; canonical source then records that choice.
review warning. Source parsing also uses MixedLegacy when ``viewpoint`` is
omitted from a newly authored source-7 scenario; it does not infer a strict
viewpoint from the layer or lifelines. Write the intended viewpoint explicitly
when starting a scenario. For example, this new OA source project starts an
activity-based scenario whose lifelines and occurrences can be added later::
arcadia 7;
project response "Distress response" {
oa_scenario assessment "Assess the distress report" {
viewpoint OperationalActivity;
}
}
An empty scenario can produce completeness warnings while remaining editable.
The desktop's Behavior **New** flow asks authors to choose one of the layer's
two strict viewpoints explicitly. Authors can also select a strict viewpoint
after reviewing a legacy scene; canonical source then records that choice.
MessageKind is Asynchronous, Call, Reply, Create, Delete, or
``{ Timer { expression "after 5 s"; }; }``. A process/chain exchange
@@ -1582,6 +1619,26 @@ and Unicode escapes. Literal unescaped newlines inside strings are invalid.
Numbers use JSON decimal/exponent syntax; NaN, infinity, hexadecimal numbers,
leading plus signs, and leading zeroes are invalid.
A small model may begin with engineering declarations alone. This complete
source describes two participants, their work, responsibility and an exchange::
arcadia 7;
project distress "Distress response" {
oa_actor vessel "Vessel in distress" {}
oa_entity rescue "Rescue coordination" {}
oa_activity report "Report distress" {}
oa_activity assess "Assess incident" {}
allocation vessel_reports "Crew reports" { source @vessel; target @report; }
allocation rescue_assesses "Team assesses" { source @rescue; target @assess; }
interaction distress_report "Distress report" { source @report; target @assess; }
}
No diagram, placement, empty description or explicit root parent is required.
The accepted source adds identities; keep those clauses during later edits.
Changing ``"Assess incident"`` changes the display name while ``@assess`` still
resolves to the same activity. Behavior-coverage warnings permit this intermediate
model to be saved. Allocation remains explicit and distinct from decomposition.
Aliases match ``[A-Za-z_][A-Za-z0-9_]*``. The following aliases are reserved:
arcadia, project, id, oa, sa, element, relation, diagram, node, artifact,
trace, body, alias, name, description, parent, from, to, entity, actor,
@@ -1596,7 +1653,7 @@ sets and enum constructors are closed by sections 3–5.
.. code-block:: text
document = "arcadia" "5" ";" project
document = "arcadia" "7" ";" project
project = "project" alias string identity? "{" project-entry* "}"
project-entry = "description" string ";" | declaration
declaration = element
+65
View File
@@ -0,0 +1,65 @@
# Linux packaging and deployment inputs
The packaging command stages **already-built** desktop/server executables for `x86_64-unknown-linux-gnu`. It runs on Windows PowerShell 5.1 or PowerShell 7 (including Linux) with Python 3.11+ standard library, Git, and the matching Rust/Cargo dependency cache. It does not build, download, install runtime libraries or launch the application. Python creates and reads back the tar archive; end users do not need Python, PowerShell or Rust.
Build and validate first in a source checkout. The current runtime validation baseline is Ubuntu 24.04 x86-64. A glibc symbol inventory is not a claim that every distribution with that glibc version supports the renderer and dialogs.
```powershell
./scripts/package-linux.ps1 -Target x86_64-unknown-linux-gnu `
-Version 0.2.0-rc1 -BinaryDirectory ./target/release -Python python3
```
For an explicit-target build, use `target/x86_64-unknown-linux-gnu/release`. A cross-build may supply another directory containing both `arcadia-studio` and `arcadia-server`. Select the Rust compiler used for the intended build before packaging; its Linux target libraries, copyright reports and locked source/archive cache must be installed. Read-only `cargo metadata --locked --offline --filter-platform x86_64-unknown-linux-gnu` and Rust version/sysroot queries are the only Rust commands run by packaging. When packaging from Windows, `-Python C:/path/to/python.exe` selects Python explicitly.
The script refuses existing output/claim names. It creates `dist/ArcadiaStudio-<version>-x86_64-unknown-linux-gnu/`, a `.tar.gz`, and an adjacent `.sha256`. A failed attempt leaves its claim and any partial outputs for diagnosis; choose a fresh version or output root rather than overwriting them. Archives use sorted paths, zero timestamps and uid/gid, 0755 for the two Linux executables and 0644 for other files. Every entry is read back and compared against staging, including permissions. The same unchanged inputs on the same Python/zlib implementation produce the same bytes; this does not promise reproducible compiler output.
## Contents and provenance
Both executables, the MIT license, a package-specific README, complete tracked examples (including all water-pressure teaching/evidence files), deployment references and the reachable documentation closure are included. Relative Markdown/reST/HTML file links are checked before archiving; upstream license texts are preserved verbatim and their internal source-tree hyperlinks are outside that documentation check. Untracked private files, caches and unrelated harness history are not included merely because they exist on disk.
`package.json` records input hashes and static ELF dependencies. `SHA256SUMS.txt` inventories every file except itself; the archive checksum covers that inventory too. `dependency-notices.json`, `THIRD-PARTY-NOTICES.txt` and `licenses/` use the same strict collector as Windows: exact target-filtered normal/build dependency graph, locked crate archives, actual source hashes, checksum-bound supplements and embedded fonts, Rust distribution notices and target-library hashes. Unknown sources, absent notices or changed supplements stop packaging. No Linux system libraries are bundled by this pipeline; their runtime distribution supplies them and its notices.
ELF preflight requires little-endian x86-64 executables/PIE, the glibc dynamic loader, no RPATH/RUNPATH and a reviewed set of direct libc/compiler-runtime imports. Unknown libraries require an explicit packaging design instead of being silently copied from a developer machine. Graphics/window/portal libraries loaded at runtime are outside that static import list.
Optionally pass `-BuildEvidence <json-file>`, containing nonempty `source_identity`, `profile`, `compiler`, exact `target`, and `binary_sha256` keyed by `arcadia-studio` and `arcadia-server`. Hash strings must be lowercase SHA256. Target and binary hashes are checked; other fields remain explicit caller assertions. Omission records build provenance as unknown. Never label a development binary an optimized release because of its directory or package version.
## Native extracted-bundle checks
Extract into a fresh user-writable Linux directory and run from an unrelated working directory. Verify SHA256SUMS, file permissions, `file`/`ldd` and actual desktop/runtime libraries. A typical Ubuntu runtime needs X11/XKB and Wayland clients, Vulkan loader/Mesa Vulkan drivers, and working session DBus plus an xdg-desktop-portal backend for file dialogs. A successful `ldd` alone is insufficient because these libraries can be loaded dynamically.
For a software Vulkan trial, first locate the installed lavapipe ICD; only if it exists, use:
```sh
WGPU_BACKEND=vulkan VK_DRIVER_FILES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json ./arcadia-studio
```
A compatible native GPU may run without these variables. WSLg uses real Linux user space with a particular display environment; record the actual X11/Wayland backend and do not infer support for all Linux sessions from one trial. Exercise Home walkthrough, Help/search, native Open/Save dialogs, a multi-file project, diagram/source edits, Undo/Redo and reopening at normal/minimum window sizes. Compare complete saved model/source and inspect stderr, not merely whether a window appeared.
Run the server against a separate local data directory and unused loopback port. Follow [server configuration](server.md) for health, authentication, ETags, restart and backup/restore. Test create/import, a changed conditional update, unchanged no-op, stale/invalid rejection, and persistence after a clean restart. Record exact binary/archive/source/compiler hashes and platform. Packaging verification is separate from current-tree release acceptance.
## Container server notices and context
The Dockerfile is x86-64 Linux only and requires BuildKit named build contexts. Before its application build it verifies a prepared server-only notice bundle against Cargo.lock, Rust compiler release/commit, exact Linux target-library hashes, notice-file checksums and workspace source hashes. This prevents using Windows dependency notices or a stale source/compiler inventory as the container's notice claim.
In the source checkout, select **Rust 1.90.0** and its `x86_64-unknown-linux-gnu` target libraries to match `rust:1.90-bookworm`. Populate the locked dependency cache through your ordinary documented build/setup first; notice collection itself remains offline. On a Windows host, a Rust 1.90 GNU-host toolchain with installed Linux target libraries can provide this read-only inventory. Prepare a fresh output root:
```powershell
./scripts/package-linux.ps1 -Target x86_64-unknown-linux-gnu `
-ServerNoticesOnly -OutputRoot ./.local/container-notices-rc1
```
This writes `.local/container-notices-rc1/server-notices` and a sibling claim file. Pass only the notice directory as the named context:
```sh
docker buildx build --platform linux/amd64 --load \
--build-context server_notices=./.local/container-notices-rc1/server-notices \
-f deployment/Dockerfile -t arcadia-server:0.2.0-rc1 .
```
The Dockerfile-specific ignore file allows only its ordinary source/build inputs; `.local`, model data, `.env` files and arbitrary caches are excluded from that root context. The separate named context includes only the explicitly prepared notices. The image retains them at `/usr/share/doc/arcadia-server/`, alongside Debian's own distribution notices. Do not pass a broad cache or home directory as the named context. Updating Cargo.lock, workspace sources or the compiler requires regenerating the bundle under a fresh output name.
The image runs as UID/GID 10001 and expects its data volume and token as described in [server configuration](server.md). Verify the actual image build, service health/authentication, writable volume and restart on a Docker-capable Linux runner. A Dockerfile review and successful local package checks do not establish container build/runtime acceptance.
## Runner-independent validation commands
Run `cargo fmt --all -- --check`, `cargo clippy --locked --workspace --all-targets -- -D warnings`, `cargo test --locked --workspace --all-targets`, and `cargo build --release --locked --workspace --bins` with the explicit supported compiler and native prerequisites. Run `python3 scripts/test-package-artifacts.py` and the PowerShell notice contract checks. Then package the resulting binaries and perform the native checks above. These commands are usable on a suitably provisioned runner; this document does not assert that GitLab, Gitea or GitHub has an active runner for this repository.
+5 -3
View File
@@ -1,6 +1,6 @@
# Arcadia Studio server
`arcadia-server` is a headless Rust REST service for the same schema-5 model, commands, source language, validation, artifacts and OA/SA traces used by the desktop. It stores each model and its authored source project together in an atomic JSON envelope. The service provides a deployment artifact and configuration examples; this repository does not assert that a remote instance has been deployed.
`arcadia-server` is a headless Rust REST service for the same schema-7 model, commands, source language, validation, artifacts and OA/SA traces used by the desktop. It stores each model and its authored source project together in an atomic JSON envelope. The service provides a deployment artifact and configuration examples; this repository does not assert that a remote instance has been deployed.
The complete HTTP contract is [api.rst](api.rst); machine-readable schemas are in [openapi.json](openapi.json), also served at `/api/v1/openapi.json`. The original [service research](research-v2-service.md) discusses broader alternatives; retained history, SQLite, idempotency receipts and stored transition plans from that research are **not** the implemented storage contract.
@@ -68,10 +68,12 @@ Errors use `application/problem+json` with stable `code`, HTTP `status`, human `
## Linux deployment
`deployment/Dockerfile` builds a headless image from the repository root:
Prepare the server-only dependency notices using the pinned Rust toolchain as described in [Linux packaging](linux-packaging.md), then build the headless image from the repository root. BuildKit supplies this checksum-bound notice bundle as a separate context; the ordinary build context excludes local caches and model data.
```sh
docker build -f deployment/Dockerfile -t arcadia-server:local .
docker buildx build --platform linux/amd64 --load \
--build-context server_notices=./.local/container-notices-rc1/server-notices \
-f deployment/Dockerfile -t arcadia-server:local .
docker run --rm --name arcadia-server \
-p 127.0.0.1:8787:8787 \
-v arcadia-data:/data \
+66
View File
@@ -0,0 +1,66 @@
# Source CLI
Use `arcadia` to check or update local `.arcadia` projects without opening Studio
or starting a server. Pass the entry file explicitly; its relative include paths
resolve from their containing source files.
Build with `cargo build --locked -p oa-cli --bin arcadia`. The resulting command
is `target/debug/arcadia.exe` on Windows or `target/debug/arcadia` on Linux unless
your Cargo configuration chooses another target directory. A workspace release
build also includes it. Use the platform's usual executable path prefix when
running these examples.
```sh
arcadia check project.arcadia
arcadia check project.arcadia --json
arcadia stabilize project.arcadia
arcadia stabilize project.arcadia --write
arcadia rename-alias project.arcadia old_alias new_alias
arcadia rename-alias project.arcadia old_alias new_alias --write --json
```
`lint` is an alias for `check`. Checks accept incomplete engineering models with
warnings; syntax errors and structural violations fail. Located diagnostics
refer to the named file and coordinate space. Line and column numbers are
one-based and columns count Unicode scalar values; byte ranges are half-open
UTF-8 offsets.
`stabilize` previews missing persistent identities and any supported source
migration. `rename-alias` changes one existing global alias and its typed
references while preserving comments, strings and unrelated source. Pass alias
names without `@`. The command does not rename an element's display name.
Both editing commands preview by default. Human output writes unified file
diffs to stdout and diagnostics to stderr. `--json` writes one versioned report
with diagnostics, migration information, exact before/after text for every
changed file, diffs and the write result. Unchanged files are not included in
that report. They are still checked for conflicts before a write.
Add `--write` to save the candidate prepared by that invocation. Even an empty
diff checks the captured files and pending-save state before returning. A failed
write reports `written: false` and retains its proposed diff. This does not
guarantee rollback; the reported conflict or recovery outcome determines the
next step. A pending save
requires explicit recovery through the existing project recovery workflow;
the CLI does not recover it automatically.
Missing IDs in a separate earlier preview remain provisional. A later command
may allocate different IDs until you save them. This CLI does not persist a
review plan for later application. It does not canonicalize the whole project
or delete detached files. Source versions 3–7 use the core's supported migration
rules; invalid source is not rewritten.
| Exit code | Meaning |
| --- | --- |
| 0 | Valid check or successful preview/write; warnings may remain |
| 1 | Invalid source or refused semantic alias change |
| 2 | Invalid command arguments |
| 3 | File/path, conflict, pending-save or output failure |
Admission bounds match the desktop: 256 files, include depth 32, 1024 include
edges, 64 MiB total UTF-8, 100,000 graph objects, 250,000 records and 500,000
ordered references. `arcadia --help` lists the commands and bounds. These limits
are not a claim of interactive performance at the maximum project size.
For the notation itself, start with [the text-first examples](../examples/text-first/README.md)
and the [language contract](language.rst).
+7 -5
View File
@@ -2,12 +2,12 @@
The standard build target is x86_64 MSVC. The optional gnullvm build uses LLVM-MinGW UCRT and currently needs `libunwind.dll` alongside both executables. Packaging is a separate operation on already-built inputs; it neither builds nor launches applications and does not confer release acceptance.
Run from a Git checkout with Windows PowerShell 5.1 or PowerShell 7. Build and test first using the [README](../README.md). Select the actual output directory explicitly; a native-host Cargo build normally uses `target/release`, while an explicit `--target` uses `target/<target>/release`.
Run from a Git checkout with Windows PowerShell 5.1 or PowerShell 7 and Python 3.11+ (standard library only). Build and test first using the [README](../README.md). Select the actual output directory explicitly; a native-host Cargo build normally uses `target/release`, while an explicit `--target` uses `target/<target>/release`. `-Python <executable>` selects Python when it is not named `python` on PATH; it collects/checks the package-local documentation closure without running binaries.
Packaging also needs the build's matching `cargo` and `rustc` on the packaging process PATH, the locked dependency sources/archive cache, and installed Rust target libraries and copyright reports. The script invokes only read-only `cargo metadata --locked --offline --filter-platform <target>` and Rust version/sysroot queries. It does not download dependencies or build. These tools are packaging prerequisites; the extracted application does not require them.
```powershell
# Standard MSVC outputs, already built:
# MSVC outputs, already built with a verified runtime strategy:
./scripts/package-windows.ps1 -Target x86_64-pc-windows-msvc `
-Version 0.2.0-rc1 -BinaryDirectory ./target/release
@@ -17,11 +17,13 @@ Packaging also needs the build's matching `cargo` and `rustc` on the packaging p
-LlvmMinGWRoot C:/Tools/llvm-mingw-20260826-ucrt-x86_64
```
The caller must supply the matching build target, version, and final binaries. PE headers establish x86_64 architecture, but do not prove a source revision or Cargo profile. `package.json` records input hashes and inspected imports; retain build/test evidence tied to those hashes separately. The version labels the package and does not change the embedded application version.
The caller must supply the matching build target, version, and final binaries. PE headers establish x86_64 architecture, but do not prove a source revision or Cargo profile. `package.json` records input hashes and inspected imports; retain build/test evidence tied to those hashes separately. The version labels the package and does not change the embedded application version. Optional `-BuildEvidence <json>` requires nonempty `source_identity`, `profile`, `compiler`, exact `target`, and `binary_sha256` keyed by both executable filenames. Target and lowercase SHA256 values are checked; source/compiler/profile remain explicitly supplied assertions, never inferred from a directory name.
Ordinary dynamic-CRT MSVC output can import VC redistributables and will be refused by the strict runtime check. One candidate recipe is an explicit-target build with `CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS=-C target-feature=+crt-static`; validate its actual imports and runtime on the intended platform before packaging. This guide does not assert that such a build has been performed. The existing GNU/LLVM recipe has its own exact libunwind staging below. Do not silence an unknown import or copy arbitrary DLLs to make packaging pass.
The script creates a fresh `dist/ArcadiaStudio-<version>-<target>/`, matching ZIP, and ZIP `.sha256` file. `-OutputRoot` selects another location. Existing output names are refused; no directories are deleted or overwritten. A `.packaging.lock` claim and partial outputs remain after failure for inspection; retry under a fresh version/output location. ZIP file order and timestamps are fixed so unchanged inputs can be compared across runs; this is not a reproducible compiler-build guarantee.
Each package includes desktop and server executables, README, MIT license, built-in Help in the application, tracked docs (including language/API specifications and OpenAPI), tracked examples and deployment recipes, current coverage/runtime notes, START-HERE, provenance, and SHA-256 inventory. It includes current working-tree contents of tracked files, so review uncommitted documentation edits before packaging. Untracked sample/user files are excluded. Repository sources are needed separately for the documented Cargo and Docker build recipes.
Each package includes both executables, a package-specific README, MIT license, built-in Help, language/API specifications and OpenAPI, server/platform guides and their reachable documentation closure, all tracked examples and deployment references, START-HERE, provenance, and SHA256 inventory. Relative Markdown/reST/HTML file links are checked before archiving; upstream license texts retain their own source-tree links unchanged. Current working-tree contents of tracked inputs are copied, so review uncommitted documentation edits before packaging. Untracked sample/user files are excluded. Repository sources and tools are needed separately for Cargo/Docker recipes; the archive README makes this distinction explicit.
For gnullvm, the exact selected toolchain's x86_64 `libunwind.dll` and full distribution `LICENSE.TXT` are included; both are hashed. Standard MSVC packaging has no LLVM-MinGW coupling. The script reads ordinary PE imports recursively for packaged runtime DLLs, accepts a bounded list of Windows system components/API sets, and fails on unknown imports. For example, a build importing a VC redistributable DLL must have its redistribution and dependency handling resolved before packaging; it is not silently treated as part of Windows. Do not copy arbitrary DLLs from System32. Dynamically loaded graphics libraries and delay-load imports require the runtime check below.
@@ -64,6 +66,6 @@ try {
}
```
This snippet only starts processes; it does not verify readiness. Check the server's health route documented in [server setup](server.md), import/read/update a model, restart with the same temporary store, and verify persistence. Close only the processes started for this smoke. Exercise the desktop's Home/example/open/save/reopen and Help, inspect real diagrams, and perform the [Save-as Undo/Redo recheck](../harness/release-save-as-runtime-packaging.md). Close normally and check stderr/exit state. A process that survives a few seconds alone is not adequate GUI evidence.
This snippet only starts processes; it does not verify readiness. Check the server's health route documented in [server setup](server.md), import/read/update a model, restart with the same temporary store, and verify persistence. Close only the processes started for this smoke. Exercise Home/example/open/save/reopen and Help, inspect real diagrams, and verify a graphical edit → Save as → Undo → Redo → Save → reopen against the complete intended model/source. Close normally and check stderr/exit state. A process that survives a few seconds alone is not adequate GUI evidence.
Acceptance is pending until these checks are actually performed against the packaged final binaries. Historical V2 bundles, this machine's Cargo checks, and a successful development launch with compiler PATH are separate evidence.
+2 -2
View File
@@ -65,12 +65,12 @@ The integration oracle executes this exact semantic review and source update. It
| `oa/`, `sa/` | Participants, work, data, capabilities and reusable behavior |
| `views/` | Five saved views; filters and placements are presentation state |
| `traceability.arcadia` | OA↔SA correspondence and review history |
| `model.json` | Current schema-6 interchange of the final accepted model |
| `model.json` | Current schema-7 interchange of the final accepted model |
| `transition-before.json`, `transition-request.json` | Explicit first-transition replay inputs |
| `evidence/repair-check.md` | Local teaching evidence linked from the SA conversation |
| `model.rs` | Deterministic lesson builder shared by generator and tests |
The REST routes are documented in [the API reference](../../docs/api.rst). Import `model.json` with `POST /api/v1/projects/import`; query the returned resource's `/model` and `/validation`. Expect schema 6 and the one warning above. JSON import provides canonical source; to retain the exact modular source layout, use `/api/v1/projects/import-source-project` with a SourceBundle containing entry `project.arcadia` and only the 30 reachable `.arcadia` file strings, keyed by slash-separated relative paths. Neither route reads the artifact target from your local filesystem.
The REST routes are documented in [the API reference](../../docs/api.rst). Import `model.json` with `POST /api/v1/projects/import`; query the returned resource's `/model` and `/validation`. Expect schema 7 and the one warning above. JSON import provides canonical source; to retain the exact modular source layout, use `/api/v1/projects/import-source-project` with a SourceBundle containing entry `project.arcadia` and only the 30 reachable `.arcadia` file strings, keyed by slash-separated relative paths. Neither route reads the artifact target from your local filesystem.
For transition replay, import `transition-before.json` instead. Submit `transition-request.json` to that baseline resource's `/transitions/preview` with its current ETag in `If-Match`. Review the returned plan, then follow the documented `/transitions/apply` protocol. Use the baseline resource for this exercise: the final model already contains the mapped records and subsequent refinements. This tutorial's automated evidence is core/source validation; it does not claim a separate native or HTTP acceptance run of this particular example.
+24
View File
@@ -0,0 +1,24 @@
# Start a model in text
Open `project.arcadia`, then choose **Textual model**. The model describes who
reports distress, who assesses it, and the information passing between those
activities. It needs no diagram or handwritten UUIDs.
1. Read each declaration as **kind, alias, display name**. References such as
`@assess` use the alias. The two allocations state responsibility; the
interaction states the direction of the exchange.
2. Change `"Assess incident"` to a name suited to your project. Use **Apply all**,
then **Save all**. Keep the identity clauses added to the accepted source:
they preserve the same model objects in later edits.
3. Add work and exchanges as your understanding grows. Behavior coverage checks
identify activities and exchanges that still need process or scenario context;
these advisory checks allow you to save the intermediate model.
Changing a display name keeps references intact. Changing an alias requires
updating every `@alias` use. Nesting expresses decomposition; an allocation
expresses who performs work. Neither implies the other.
For a larger example with behavior, ports, views and OA/SA correspondence, use
[the water-pressure walkthrough](../release1/README.md). The
[language reference](../../docs/language.rst) defines all declarations and the
rules for splitting a project into included files.
+10
View File
@@ -0,0 +1,10 @@
arcadia 7;
project distress "Distress response" {
oa_actor vessel "Vessel in distress" {}
oa_entity rescue "Rescue coordination" {}
oa_activity report "Report distress" {}
oa_activity assess "Assess incident" {}
allocation vessel_reports "Crew reports" { source @vessel; target @report; }
allocation rescue_assesses "Team assesses" { source @rescue; target @assess; }
interaction distress_report "Distress report" { source @report; target @assess; }
}
+136
View File
@@ -278,3 +278,139 @@ This is a selected design under implementation, not a native acceptance claim.
Native reverse scenario Apply selected a dependency and inserted five overlapping behavior placements into an unrelated architecture view. Core transition correctness did not make that presentation useful. Select the counterpart of the explicit request root and resolve its nearest scenario/process/chain/state owner. Without an explicit destination diagram, keep the exact core candidate and open Behavior; preserve unrelated architecture views. Retain ordinary architecture transition placement and honor explicit diagram choices.
Automatically creating another architecture view would retain the wrong editing workspace and introduce unrequested model state. Merely navigating to Behavior after adding placements would conceal the presentation damage. Both alternatives are rejected. The selected correction retains one source transaction and Undo operation and guards stale canvas events. Revisit if mixed-root requests or realistic explicit destination workflows require a separate user choice; do not infer such a choice from dependency ordering. Test/build/native acceptance is recorded separately in release-behavior-transition-context-20260906.md.
## Property baselines and explicit alternative cases — 2026-09-11
Problem: complete independent bindings repeat shared engineering assumptions in
every ordinary study case. The user requires practical text-only development and
reduced cognitive load for small and large models. Evaluator implementation
simplicity alone cannot justify that authoring cost.
Select property-owned base values/formulas and one-level case overrides as the next
active-study contract to formalize. Every evaluator caller explicitly requests
ModelBaseline or a particular Case identity; no active UI selection, unnamed
default case or case-to-case inheritance determines meaning. The baseline is the
model's explicit property values, not a mandatory extra record for entering the
first value. Inherited formulas read the requested effective case. An explicit
Unbound override shadows a known base; clearing an override uses the base.
The [executed comparison](release-analysis-context-experiment-20260911.md) passed
218 assertions. Twenty cases with20 fixed/two varying inputs used62 binding rows
under B versus480 under D, with identical results. Updating one shared assumption
required one B binding versus20 D bindings. Reusable predicates eliminated D's
threshold-edit disadvantage, so repeated formulas are not the reason for selection.
Retain an explicit complete independent freeze/export for intentionally separate
assumptions. It must capture effective values/formulas and the full exact definition
environment, including package pins; copying only case rows leaves hidden live
dependencies. Captured revisions and per-input origins must make propagation
visible. Effective dependency/cycle validation and stale result handling must cover
the whole requested context.
Reject compulsory complete cases for ordinary shared-assumption modeling; retain
their useful isolation as an explicit independent snapshot. Reject arbitrary
inheritance and UI-dependent evaluation. Do not import the tiny experiment
interpreter as production architecture. Exact check identity, type/operator
algebra, source syntax, library closure/compatibility, transitions and public
snapshot formats still require the coordinated precise contract. Current source7
does not implement this decision.
Revisit if complete text/native tasks expose unacceptable hidden propagation,
wrong-context edits or inability to preserve reproducible independent studies.
The comparison establishes semantic/text maintenance evidence, not human task
timings or full quantity/library integration acceptance.
## Analysis and library contract convergence — 2026-09-11
Root Codex-956atf read the complete [baseline refinement](release-analysis-baseline-contract-20260911.md),
[library refinement](release-library-compatibility-contract-20260911.md), their
complete fixtures and [independent review](release-refined-contracts-review-20260911.md).
Select the following architecture for production implementation:
- Required property-owned Binding values, explicit ModelBaseline/Case selection,
one level of complete-case override maps and shared root checks. Clear removes
an override; Unbound masks the base. Inherited formulas evaluate dependencies
in the requested context. Pure calculations see only explicit parameters.
- Same-layer property dependencies and case targets, with explicit analysis
selection for transitions and exports. Check/case subjects may be absent;
architectural containment must not infer their selection. Validate every
effective dependency graph, including statically referenced unused branches.
- The refined R6 closed algebra, exact rational R7 literal/AST preservation,
affine point/difference distinction and declared-output kind anchoring.
Strict expression operands gather actual missing/failure causes; Boolean
control flow evaluates only the selected branch. Supported domain failures
are distinct from violated predicates and missing values.
- Whole accepted PortableDocument freeze with exact SourceBundle, local
definitions, all imported package contents/pins and validated provenance.
Replay resolves only that immutable private capture. A result report, shallow
case copy or current cache is not a reproducible freeze.
- Exact archive/reference/history identity alongside verified same-origin
typed-contract equivalence. Different nominal origins remain distinct.
Compatibility supplies a scoped expected/actual field-path and operation
correspondence; it never advances a pin or rewrites outside record identities.
Keep qualified neutral definitions, immutable mapped layered definitions and
ordinary editable pattern instances for the first coherent implementation.
- Explicit source preparation/acceptance with complete version-controlled
package/base/map/lineage state, recomputed admission and stale-input rejection.
Exact three-way facets retain independent local edits. Mounted OA/SA transfer
requires a verified exact target-layer export or an explicitly independent
editable local derivative; no relabeling or silent mutation of a mount.
These are architecture decisions, not claims that the proposed schema8 examples
are admitted by current source7. Before real consumer integration, enumerate and
implement the class-specific canonical contract over all interpretation-bearing
fields and use sites, exact transitive archive closure and full source/history
boundaries. Retain the frozen120-assertion prototype with its documented C2
threshold-unit coverage gap; production typing must check every operand.
Close independent C1 before evaluator expansion: a request-local, profile-versioned
logical work meter must bound dynamic expression visits, calls, list traversal
and exact-number work. Static acyclicity/depth/node limits do not bound expanded
execution. Cache warmth must not change outcomes; terminal exhaustion stops
further traversal and marks collected causes as incomplete. Numeric ceilings and
the precise charging table require measured foundation implementation before
publishing the profile. The333-node/31-level counterexample and a nearby successful
case are mandatory tests across direct/API/frozen replay.
The exact numeric foundation is the next bounded core implementation. Ordinary
engineering approximations, a complete low-noise text workflow, two-project
library maintenance and native/API/source parity remain required release work.
An exact-only slice cannot complete the user's first release.
## Analysis production staging — 2026-09-11
Root accepts the concrete [production integration sequence](release-analysis-production-integration-plan-20260911.md).
Allocate schema8 to the next coherent production analysis integration. Start with
the actual Project's neutral definition catalog, three analysis element kinds,
typed expressions and a closed Local definition-reference environment. Imported
references will be admitted only with the real package environment; no placeholder
resolver, guessed pin, implicit type compatibility or competing package format.
This stages implementation and does not defer the required maintained libraries.
The first useful gate is the complete persisted/source-authored response budget,
shared two-parameter calculation and check: baseline7/4 seconds versus degraded9/4,
with explicit request context and the same core result through CLI and REST.
Required property fields cannot come from generic factory guesses. Existing
descriptive expressions/unit labels retain their exact old meaning and bytes.
Freeze older top-level wire DTOs before making definitions required in schema8;
reject new fields/constructors in older versions instead of silently dropping them.
Global, scoped parameter, imported and historical identities remain distinct.
Implement pure static numeric type helpers once and reuse them for admission and
runtime. Validate every effective case graph and unused branch before accepting a
candidate; deleting dependencies requires explicit same-batch repair. Numeric
domain failure is not a static type failure. Full evaluator traversal and actual
C1 input, provenance, terminal incomplete causes and immutable replay are required
before claiming evaluated engineering behavior. Until explicit analysis review/
transition facets exist, those entry points must reject unsupported analysis with
a clear capability error, including manual-trace paths that could otherwise appear
to reconcile headers alone.
Logical expression depth128 must be reconciled with bounded actual JSON/source
decoding; do not simply disable recursion limits. Raw byte, decoded string and
aggregate literal/graph/case-admission limits are separate from evaluation fuel.
Concrete decoder/admission ceilings remain subject to bounded boundary and timing
experiments; the implementer must surface those choices before locking the profile.
The current local numeric gate runs against frozen root source. New core contract
work proceeds in an isolated checkout, preserving root's Cargo/native leases and
the other hosts' CLI, staged-source and B4 ownership.
+71 -104
View File
@@ -1,117 +1,84 @@
# First release execution plan
## Active execution — 2026-09-10
Updated 2026-09-11. [PROJECT_GOAL.md](../PROJECT_GOAL.md) is the authoritative
current objective. [STATE.md](STATE.md) records exact execution/evidence and leases;
[TASK_LEDGER.md](TASK_LEDGER.md) separates facts, assumptions and decisions.
The complete previous plan is [preserved byte-for-byte](history/2026-09-10-ledgers-before-continuation-refresh/PLAN.md).
Its earlier goal paths, active-process claims and Escape pauses are historical.
1. Restore a reproducible local toolchain; repair the interrupted compact palette;
verify focused history/draft/placement regressions and the actual native workflow.
2. Independently reassess current behavior/scenario ergonomics and OA/SA semantic,
source/API and documentation completeness. Resolve verified high-impact gaps
with bounded changes and cross-representation acceptance criteria.
3. Complete realistic graphical OA/SA teaching, transition, behavior, recovery and
hosted workflows. Exercise minimum and wide layouts, rejected edits and history.
4. Run current Windows/Linux automated and native acceptance, fresh independent
end-state reviews, optimized builds and package verification. Publish accurate
build/run evidence and handoff only when the original release criteria hold.
## Outcome and working principles
This ordering supersedes historical stopped-session next actions below. Preserve
their scoped evidence; no test or runtime result transfers to a new binary without
verification. Root holds the serialized build/native lease; Gitea #1 tracks workers.
Deliver usable, complete OA/SA engineering workflows on Windows and Linux, with
one precise reST contract and equivalent graphical, textual and REST editing.
Constraints/calculations, quantities/units and reusable libraries are explicit
requirements alongside behavior/state modeling, traceability and navigable help.
Small and large models must be practical to author entirely in uncluttered text;
evaluate complete authored and stabilized models, not abbreviated grammar sketches.
Later Arcadia layers remain future scope. Compilation, metadata fields and polished
screens alone do not satisfy this outcome.
**Latest refinement:** consult actual installed Capella 7.1, replace the user-rejected horizontal creation/connection rows with a compact contextual palette and inline authoring, independently critique interaction risks, then build and verify the real workflow at wide/minimum sizes. [Benchmark and concrete acceptance](release-capella-basic-editing-20260907.md). Do not ship the rejected toolbar as the usability correction.
Retain the shared typed core, stable identity, semantic ownership/allocation distinct
from geometry, validated atomic commands and exact source/history. Persistent
extensions need coherent references/deletion, transition, source/migration,
API/schema and reachable graphical authoring. Define observable acceptance before
broad downstream changes. Do not silently promote a design proposal to a decision.
**Current priority (7 September):** the user's usability correction takes precedence over the advanced feature sequence below. Establish contextual named diagram creation, existing-element placement, basic editing and clear layer transitions, then verify them natively. Desktop checks were explicitly reauthorized. See [priority reset and acceptance](release-basic-editing-reset-20260907.md).
## Capability milestones
## Outcome and baseline
| Milestone | Work and acceptance | Dependency/current limit |
| --- | --- | --- |
| 1. Reliable direct authoring | Exercise actual minimum/wide native creation, allocation, editing, rejection, cancellation and history without implicit draft application or placement drift. Integrate compact named behavior creation after its coherent external gate. | Named creation4bb4aaf is imported; combined desktop676/676, format and strict Clippy pass at2cc4d11. Native80cf197 passes all four OA creations/history/reopen; new workspace fixes and production chooser await compilation. Workspace/B3/palette/recovery/packages are imported. Root owns this host's Cargo/native lease. |
| 2. Coherent process/scenario work | Interactive ordered/explicit process editing; clicked root/nested scenario insertion; exact reuse bindings and caller return; measured canvas/zoom/scroll; visible scoped Create/Delete lifetimes. Validate model/source/identity and no unintended edit during navigation, including stale/deleted/retargeted references and recovery. | B1/B2/B3 regressions pass in the full suite. Local B4 remains cfg(test); Codex-ytr83r owns production Scene integration and its independent native gate. Use the independently self-checked oracle for native checkpoints. |
| 3. Precise engineering analysis | Compare owned properties, analysis contexts and existing-data/external alternatives; settle quantity kind/unit/value, numerical policy, calculation/binding and Boolean/error/unknown semantics through falsifying examples. Implement mixed-unit budgets and reusable calculation/constraint definitions with full UI/source/REST parity and exact history/recovery. | B/shared-check/full-capture and R6/R7 architecture ratified after complete fixtures and criticism. Exact numeric/work-meter foundation is undeclared and under independent review. Approximate profile and full evaluator parity remain required. |
| 4. Maintained reusable libraries | Compare package/definition/instance alternatives. Establish pinned identity/version/dependency closure, local edits, import bindings, detach and explicit three-way updates. Demonstrate two projects, two independent instances, offline reopen, conflicting updates and stable unaffected identities. | Exact pins plus verified same-origin typed compatibility, explicit source preparation/acceptance and three-way editable updates are ratified. Finite120-assertion experiment is not production contract/archive/consumer implementation. |
| 5. Understandable complete engineering tasks | Close teaching, OA↔SA transition/reconciliation, typed state/data/interface, artifact, saved-view and hosted workflows. Establish complete text-only creation/refactoring/modular maintenance with stable identity. Replace concrete long homogeneous selectors with contextual/searchable bounded choices; verify large models, keyboard access, minimum sizes and failure/recovery. Keep offline guide/examples aligned. | A complete warning-free text-only model probe passes source/identity/rename/reparent/file-move checks; measure usability separately. Anchored chooser passes13 isolated mounted tests under cfg(test); production inspector/review integration is active; its compile/native gates remain open. Separate-host CLI is coherent at01b76a1 and awaits import here. Reassess current goal rather than copying historical scope exclusions. |
| 6. Release confidence and delivery | Fresh current Windows/Linux suites, strict Clippy/format, normative reST/OpenAPI/migration/examples; actual GUI/service transport, optimized builds, runtime/notices/archive/provenance/checksums and clean-environment launch. Fresh independent requirements/domain/parity/architecture/UX/runtime review; resolve material findings, then final handoff. | Integrates all preceding capabilities. Linux runtime remains open; use an approved supported environment, preserving historical failed/denied experiments. Historical previews are not final distributions. |
Deliver the first release of Arcadia Studio for system engineers: complete Operational Analysis and System Analysis/System Architecture workflows, equivalent graphical and textual models, clear artifact traceability and a deployable/programmatically accessible Rust service. Logical/Physical Architecture and later Arcadia layers are future releases, as the new objective explicitly states.
Milestones are capability gates, not a rigid serial schedule. Root can continue
build/native acceptance while independent foundational investigations compare
alternatives. Libraries and analysis share definition-resolution assumptions and
must converge coherently before broad model/schema edits. User workflows and
cross-representation evaluators guide implementation boundaries.
The authoritative objective is attachment `10b0f701-1743-4de7-9ee1-225920e19649/goal-objective.md`. It retains first-release scope and strengthens domain coherence, alternative evaluation and target-user task evidence. TASK_LEDGER.md separates given/verified facts, assumptions and open candidates; STATE.md records progress. The accepted 0.2.0 prototype is a historical baseline, not proof of release completeness. Its old D:/CodexBuilds archives are unavailable on this machine; existing dist archives must not be replaced until new acceptance passes.
## Immediate execution sequence
The user's cross-branch reminder led to an ancestry/patch/tree audit. Continue from integrated `c091f80` on `codex/release1-continuation`; direct state/scenario/process, data, hosted and semantic review work already exists here. `release-branch-integration-20260906.md` records the audit. `release-current-coverage-20260906.md` is the current measurable acceptance map and supersedes stale absence claims in older narratives below.
1. Complete the coherent workspace/production chooser build and focused gates,
then stage a new GUI for real engineering tasks. Full676/format/Clippy passed
for2cc4d11; working changes require their own verification.
2. Implement the user-required common canvas interactions for Process and Scenario
in issue2 after the bounded shared-viewport/domain-constraint design decision.
Treat this as direct-manipulation acceptance, not a tool-shelf restyle.
3. Exchange exact verified commits with the separate host, preserving its workspace
ownership. Direct authenticated publication works. CLI01b and exact evidence2ec
are imported; next contextual-source and B4 handoffs retain their owners.
4. Use the self-checked [scenario oracle](scenario-authoring-contract.rs), follow
its [native procedure](fixtures/scenario-authoring/README.md), and compare exact
whole snapshots for Undo/Redo/reopen at minimum/wide sizes.
5. Exact numeric/unit/work-meter foundation26/26 unit tests pass at7d14bd0; complete
its strict gate while actual schema8 core work proceeds in an isolated worktree.
Extend actual model/source/API/GUI under the ratified
B/R6/R7/full-capture and exact-pin/typed-compatibility contracts. Preserve explicit
approximate numeric, complete consumer/archive and two-project release gates.
6. Update current ledgers and durable decisions when evidence changes the plan.
Reassess unresolved assumptions before expanding downstream implementation.
## Existing architecture and retained decisions
## Coordination and evidence rules
Retain three Rust crates and one typed Project/validated atomic Command boundary. oa-core owns semantics, references, history, transitions, source and persistence; oa-desktop owns Iced interaction/drafts/projections; oa-server owns REST/ETag/current-model storage. Keep identity, semantic containment, allocation and per-diagram placement separate. No runtime plugin framework or later-layer skeleton.
Use Gitea issue #1 and Wiki for current ownership/handoffs; read before resuming.
Codex-956atf, Codex-9e8r6t and Codex-ytr83r are distinct hosts. Cargo/native leases
are host-local; shared source ownership is coordinated.9e8r6t owns the next runnable
Windows named-authoring prerelease and contextual-source/CLI; ytr83r owns B4 Scene
and its platform gates. Root owns local chooser/numeric/workspace integration.
Updated AGENTS requires runnable milestone prereleases. User#178 authorizes existing
MCP credential reuse for Git/REST; secrets must never be printed or committed.
Direct branch publication replaces bundle work when available; old exact bundles
remain valid evidence and transfer branches must not be merged.
The current forms are a closed typed-record adapter, not a second metamodel. Expand their real creation/reference/variant controls with every semantic addition. Core choices must drive graphical choices. New persistent fields participate in text round trips, identity/removal visitors, transitions, API schemas and graphical authoring tests.
## Milestones and measurable acceptance
Nested source ownership and persistent REST bundles are implemented and verified: Windows minimum-size source-to-graphics, nested reparent/source/Undo/Redo/Save/reopen, recovery, rebuilt Linux source/history/Save/reopen, independent review and both platform suites passed. Preserve the existing grammar/updater and separate allocation/order semantics.
Explorer/port discovery, custom routing, direct palette connections, four-side port
anchors, contextual menus and source folders have scoped Windows/Linux acceptance.
See release-explorer-usability.md, release-routing-verification.md,
release-routing-linux.md and release-port-drawing.md for exact evidence and limits.
Direct state-machine editing is accepted through316dc55: typed persisted views,
explicit-owner creation, movement, direct transitions/reconnection, typed detail
forms, folding, placement and correct camera/tool lifetime. Windows default/minimum
and Linux native acceptance plus independent reviews are recorded in
release-state-editing.md. Direct scenario/process gestures remain required.
R6 data contracts and direct scenario/process gestures are integrated; native
acceptance continues on both platforms. Typed R3 core/source5/REST and scalar review
milestones1–2 are integrated and pass full platform checks. Close independent scalar
fixes and native review, then finish constructor/keyed/order/reset/artifact and
multi-source graphical authoring using the existing shared core planner. Source5
migration retains lexical ownership/comments; no flat source rewrite is allowed.
See release-data-contract.md, release-semantic-integration.md and release-semantic-gui.md.
Continue source authoring improvements only through the production parser/updater.
The23-test experiment is evidence, not architecture: independent probes exposed
comment misattachment and unsupported edits. Additional shorthand must preserve
complete edit/delete behavior and exact source history, and justify itself in real
human authoring tasks. Shared state placements are now validated; scenario/chain
interaction must preserve its own occurrence and ordering semantics.
1. **Release coverage audit and interfaces.** Compare actual core/UI/API with official Capella OA/SA semantics and the new objective. Freeze a coverage table and concrete variant/reference/transition contracts before editing shared interfaces. Distinguish unsupported later layers from missing OA/SA workflows; V2 exclusions are reconsidered. Native audit exercises onboarding/help/authoring at supported sizes. Independent audits have separate file ownership.
2. **Complete engineering semantics.** Fill verified gaps in capability relationships and mission involvement; operational process/functional-chain function/control topology; scenario/state/data constructs needed by OA/SA engineers. Add typed semantic-content drift and reviewed existing-counterpart reconciliation, including reference mapping and explicit dependency/ownership decisions. Every addition has a usable graphical authoring workflow, equivalent source/API representation, meaningful reject/undo/delete/reidentify/transition tests and a worked example. Exact additions and invariants are recorded in the coverage/interface artifact from milestone1, avoiding speculative LA/PA concepts.
3. **Approachable authoring and help.** Replace static help with searchable topic navigation, concise concepts, numbered OA→SA tutorials, related topics and direct workspace actions. Add a focused starting workspace, recent models and practical creation guidance. Improve source authoring with asynchronous versioned lint, semantic warnings, diagnostic navigation and find/go-to tools. Make selection/navigation and hidden/placed model distinctions clear. Add recoverable local checkpoints for unsaved accepted models and drafts; preserve explicit file-save/conflict behavior.
4. **Connected automation workflow.** Keep headless deployment and shared core REST contract. Add direct optional desktop open/publish/save of hosted models using explicit connection details and conditional ETags, preserving drafts on failure/conflict and keeping credentials in memory. Verify actual desktop→API→desktop edits and artifact integration locally. Update OpenAPI, deployment and source contracts for the expanded release semantics.
5. **Release integration and polish.** Guided examples cover OA goals/roles/process alternatives, system missions/capabilities/boundary contracts, chains/scenarios/states and evidence. Review default/minimum/wide layouts, practical keyboard paths, empty/loading/error/recovery states and performance on representative models. Build/run the actual native app after each meaningful UI milestone, fix from evidence, then reverify.
6. **Independent final acceptance and packaging.** Fresh requirements, correctness, native UX and simplicity reviews in parallel; fix all material findings and rerun affected checks. Full Windows/Linux locked tests, formatting, strict Clippy and optimized builds. Operate primary GUI workflows and actual service transport. Verify current docs/reST rendering, examples/migration, reproducible source workflow, package binary equality/archive contents and checksums. Only then replace 0.2.0 bundles and mark this goal complete.
Dependencies: milestone1 freezes shared interfaces for2; guide/lifecycle work in3 can proceed independently once UI ownership is partitioned. Structural counterpart work depends on2. Hosted client4 depends on final core/API types but transport/lifecycle can be developed independently. Milestones5–6 integrate all preceding work.
## UI and state flow
Keep task navigation, engineering perspective and context-sensitive properties. A Home/start workspace offers projects, recovery and tutorials without obscuring active modeling. Help uses local Rust-owned content and search/category navigation; workspace links pass explicit events and respect draft/modal guards.
Text edits update a snapshot/version; parsing/semantic lint runs on a blocking worker and only the latest result is adopted. Syntax errors and semantic warnings have distinct severity/location and navigate to source. Applying text remains one atomic model transaction. Invalid text and property input are recoverable drafts.
Recovery writes separate per-session checkpoints in user-local application data, never silently overwrites a model file, and offers explicit restore. Recent paths are convenience metadata. Hosted models use a separate connection/resource/revision/ETag handle; ordinary core editing and Undo stay local until explicit conditional Save. Network/file failures retain the same draft. Tokens are not persisted or included in diagnostics.
## Failure and verification strategy
Cover wrong-layer/reference/kind input, ownership/reference cycles, duplicate or ambiguous counterpart matches, stale plans/ETags, typed semantic drift, sequence control topology and repeated occurrences, invalid source/property drafts, external file edits, failed storage/network operations, oversized models and unavailable graphics. Keep incomplete engineering work editable through warnings while rejecting structural corruption.
Tests must cover user-visible meaning and cross-representation invariants, not just serialize the same value twice. Use actual HTTP and native CUA for end-to-end behaviors. Independent review targets current artifacts and the original release objective, not only implementation summaries. Record unsupported/unavailable environments without turning missing required functionality into a limitation.
## Definition of done
Every concrete requirement in the new objective and release coverage table has authoritative current evidence. Primary OA/SA engineering workflows work graphically, textually and through the API; help is navigable and useful; native Windows/Linux UI is intentionally designed and exercised; no blocking/high-impact defect remains; strict checks pass; independent findings are closed; durable docs accurately reflect the release; another engineer can build/run/test and use the supplied packages. V2 completion alone does not satisfy this goal.
## Historical milestone progress — hosted integration
Milestone4 desktop adapter is implemented on the existing Document/REST boundary.
Windows native publish, graphical/text save, rejected invalid source, API artifact
reload and stale-revision recovery are demonstrated. Offline/retry and exact local-copy/catalog Open native acceptance passed on Windows.
Destination and catalog defects found afterward were fixed/reviewed/integrated; remaining platform/native cases retain their report scope. Constructor/keyed/order/Child/Incident/artifact and multi-source review, Home/recents and checkpoint recovery are now implemented. Their scoped native and automated results are in STATE.md; this older milestone is not a current absence list.
## Current execution refinement — 2026-09-07
First-release scope above is unchanged. The user-requested Windows development preview is packaged with565files, including all37 teaching-folder files, and is linked from `DEVELOPMENT_SUMMARY.md`. Latest Fit6 and two existing scroll/branch regressions pass; full desktop570/570, workspace bins, formatting and strict workspace/all-target Clippy pass. Corrected full server56/56 retains its unchanged-server scope. Exact build status and provenance are recorded in STATE.md. This is not an optimized final release.
Native6BAB operation/recovery/history passes and BCC1 corrected OA/SA nested routing passes retain their separate binary scopes. The latest DC50 preview launched with a clean PATH, and its four-card OA Fit overview was visible at1444×932 and1102×932. Minimum-height, pending-form and remaining process-purpose acceptance are still open. Computer Use was stopped by the user's Escape; leave both live GUI processes untouched and continue independent work.
Native Linux core436passed/2ignored is complete on its frozen455-file snapshot. The original server compile passed, unit2/2 and HTTP50/51 passed, and the single504-versus412 timing fixture failed twice. Its private preparation-gate replacement passes on Windows but still requires Linux execution. Preserve the original failures and exact final-state assertions; do not alter the production30-second deadline to make the fixture pass.
The fresh Linux GUI cross-build passed on immutable458-file snapshot `source7-20260907T102528493108Z`, including the Fit constructor fix. Run `20260907T1025486926611Z` completed in2m20s Cargo time with pre/post checks, ELF requirements and all37 lesson files verified; the compiler lease is released. The subsequent headless guest failed its early IO-APIC timer check on three bounded boots, before SSH/tests. Exact matching boot assets were extracted, but automatic approval review rejected the proposed transient boot workaround before launch. All task VMs are stopped; no application failure or current Linux server pass is inferred. Latest guide-label changes and the validated Exchange/CommonWork native oracles follow the frozen binary snapshot.
Next actions:
1. Retain all three guest boot records and exact-kernel proof; the proposed direct-boot action was denied by automatic approval review and must not be retried or split to bypass it. Resolve the runtime gate through an approved route or changed environment. Verify actual readiness and remaining monotonic budget before running the corrected Linux server gate. Do not restart on observation timeout alone.
2. Preserve the reviewed guide corrections and validated expected-model/source Exchange/CommonWork oracles; the updated guide now builds on Windows and belongs in the next packaged/native snapshot. Complete native purpose authoring/history once control is available.
3. Once native control is authorized again, complete current-layout minimum-height/Focus/pending-form checks, remaining engineering/hosted walkthroughs and actual Linux GUI acceptance using exact model/source/history evidence.
4. Execute the corrected Linux server suite; complete final Windows/Linux optimized builds, package provenance, documentation/contracts, and fresh independent cross-disciplinary end-state review. Successful slices do not complete the goal.
Record exact source/binary, command exit, test scope and native model/source oracle.
Do not add focused reruns to full-suite totals or transfer old binary acceptance.
Older denied Linux workaround instructions remain applicable to that action; do
not bypass them. Older stopped native sessions do not prevent currently authorized
native work. The [archived plan](history/2026-09-10-ledgers-before-continuation-refresh/PLAN.md)
and [archived progress](history/2026-09-10-ledgers-before-continuation-refresh/STATE.md)
preserve all previous strategy and scoped evidence; archive report links resolve
from their original `harness/` directory.
+180 -148
View File
@@ -1,170 +1,202 @@
# Progress Ledger — first release
## Active continuation — 2026-09-10
Updated 2026-09-11, coordination through Gitea #245 and issue2. This ledger describes the
Codex-956atf checkout; external-host evidence is labeled separately. The entire
previous ledger is preserved [byte-for-byte](history/2026-09-10-ledgers-before-continuation-refresh/STATE.md).
Historical dates, binaries, process IDs and stopped-session instructions in that
archive are evidence history, not current status or authorization.
The renewed user request is preserved in `PROJECT_GOAL.md`. Root is integrating
the first release, prioritizing direct diagram authoring and behavior/scenario
usability. The checkout began clean at `1797516` on `codex/release1-continuation`.
Gitea issue #1 and Wiki Home were read; ownership and progress are coordinated there.
## Current objective and source
- Root owns integration, serialized builds, native Computer Use and these ledgers.
`palette_repair` owns architecture authoring and `diagram.rs`; `behavior_audit`
and `release_audit` independently inspect ergonomics and release coverage.
- The recorded palette compilation errors have local corrections pending a fresh
build. Earlier 584-test evidence does not cover those corrections.
- This checkout began without the historical `.local` toolchain/cache/packages.
Project-local Rust/Cargo 1.98.1 GNU/LLVM and verified LLVM-MinGW 20260908
(clang 23.1.1) are installed. Locked dependencies are being fetched.
Host: four logical processors, 8 GiB RAM; builds remain serialized.
- Computer Use initialized successfully. The renewed request authorizes native
evaluation; old session Escape holds and process IDs are historical. No Arcadia
or Capella window is currently running.
- WSL lists no installed distribution. Linux runtime/build acceptance remains an
open gate; no historical denied guest workaround is being retried.
Deliver the complete, usable OA/SA first release in [PROJECT_GOAL.md](../PROJECT_GOAL.md),
including graphical/source/REST parity, constraints/calculations, quantities/units,
reusable model libraries, traceability, offline guidance and Windows/Linux release
acceptance. Direct behavior/scenario authoring and reduced cognitive load remain
immediate priorities. Complete small and large models must be practical to develop
through uncluttered text alone. The release is incomplete.
**Current branch is `codex/behavior-authoring-20260910`.** A distinct Gitea user
`Codex-9e8r6t` is running another root/team on a separate environment with the old
build cache. Our identity is **Codex-956atf**. Gitea #25 and #38 acknowledge the
scope split: their palette/platform/package and subsequent scenario layout work;
our process/scenario adapters and typed-history work. We will publish a clearly
untested coherent snapshot on this distinct branch for their warm-cache checks.
No shared branch-tip push or merge has occurred here.
Their reports/results must not be claimed as local validation or overwritten.
Local branch: `codex/behavior-authoring-20260910`. Last compiled source checkpoint
is `2cc4d115d0ff28423c7ed87fd5f4065efb011f2d`, including external named creation
`4bb4aaf` as `1516949`, the isolated chooser and final baseline/library contracts.
Full desktop676/676, formatting and strict Clippy pass at that source. The active
native GUI remains immutable80cf197. New workspace and production chooser changes
are outside those artifacts and await a coherent build. Current committed source
adds exact numeric foundation7d14bd0, imported CLIbc311bc and evidence/native
dc0f2e1. Numeric26/26 unit tests and strict core all-target Clippy pass. Shared
instruction ancestrycab01c3 is merged asc7ed894, retaining the exact uploaded goal.
The authoritative goal was copied byte-identically from attachment
`a49d1780-25d5-4778-ad68-6140c60e4207/goal-objective.md`; SHA256
`DD58F75C93D55FE16ED141A23D834898FB6EBC625AE7E7AE379DA552A8312435`.
See [Task Ledger](TASK_LEDGER.md) for knowledge/decisions and [Plan](PLAN.md)
for capability acceptance. Older goal paths are superseded.
Implemented locally, awaiting compilation:
## Completed work and evidence
- Palette compile repair, retained inline name after rejected stale Submit,
nonfinite click rejection and rename/allocation/history regressions.
- One interactive process renderer with presentation-only inferred ordered
paths; first editing batch preserves adjacency atomically. Independent source
review found no confirmed defect. Root added 3+ step/before-first insertion
and incompatible imported conversion tests after the reviewer hit model capacity.
- Scenario Action/State/Reuse/empty Fragment tools capture clicked operand/slot
and optional lifeline. Pointer-to-App, recovery, stale-event and history tests
are written. A bounded exact caller/use return path and scoped mounted-scroll
restoration are implemented with regressions, also untested.
- Advanced typed stored-history editor uses existing OpenAPI type descriptors;
twelve focused tests cover typed selectors, historical IDs, invalid raw input,
recovery and source/history. Core validation remains authoritative.
- Normative catalogs now include ExchangeCategory, ContextualLink and both
Exchange trace pairs. Manual trace help and scope source version corrected;
strict Docutils 0.22.2 HTML regeneration passed.
The creation bundle was fetched anonymously and verified at105022 bytes,
SHA256 `0DEFAE91A56430076C432758F923BC0675911DA9FA7588C9961FF15F47EAEBF6`.
Its coherent commit adds named Process/Chain/Scenario/Machine drafts, bounded
owner search, recovery/selection guards, offline guide and measured textual
examples. The duplicate Sensor correction was not reapplied. Both hosts' report
additions and exact experiment bytes are retained; this host's goal and ledgers
remain authoritative locally. External653-test/native evidence is attributed in
[its integrated report](release-integrated-gates-20260910.md), not claimed as a
local run. The separate isolated chooser at `c4e1580` passed13/13 mounted tests
under cfg(test); it is not a production selector yet.
Reference evidence: actual Capella 7.1 scenario/lifeline/LOOP creation and saved
XML are recorded in `release-capella-scenario-benchmark-20260910.md`; the isolated
Capella process closed normally and is absent. This is not Studio acceptance.
| Scope | Current evidence and limits |
| --- | --- |
| Reproducible local toolchain | Ignored `.local/toolchain/env.ps1` selects Rust/Cargo 1.98.1 GNU/LLVM and verified LLVM-MinGW 20260908 (clang 23.1.1), with one Cargo job. First cold desktop test build completed in 58m03s; one unused import warning was corrected separately. |
| B1 process authoring | `01bb52a` includes interactive empty/ordered/explicit topology and presentation-only inferred paths; first conversion preserves ordered adjacency atomically. All topology regressions pass within the current full desktop suite. Native acceptance is pending. |
| B2 scenario authoring | Clicked root/operand/slot and optional lifeline feed Action/State/Reuse/Fragment adapters. Pointer-to-App, cancellation, stale-event, recovery and history tests pass within the current full desktop suite. |
| B3 caller navigation and workspace | External `3978bbe` imported as `865cd55` fixes visible-owner restoration, pending-draft guards and remaining-height workspace. Root `80cf197` keys the viewport Sensor by document/scenario; a real mounted regression failed before the fix and now passes. The full suite is green; actual OA caller return and source-neutral navigation pass. Remaining native scope is explicit below. |
| Architecture palette | External palette commit `7d1df4f` was cherry-picked as `aed40d7`, retaining local invariant tests. Captured Escape, stale Submit/raw retention and bounded card fixes are source-integrated. External native results do not transfer to this checkout. |
| Typed stored-history F1 | `b6b76ef` fixes nullable constructor cache discrimination; `4ecad78` fixes NotApplicable seeding by checking actual enum alternatives. Thirteen focused tests passed and are included in the current full suite; core validation remains authoritative. |
| Lifeline lifecycle B4 | `eb5161b` adds pure local/scope-aware lifecycle projection with ten tests, declared under `cfg(test)` only. It is not production Scene wiring or native acceptance. [Design](release-scenario-lifecycle-design-20260910.md). |
| Native scenario oracle | [Independent checker](scenario-authoring-contract.rs) compiled/self-checked and verified the generated62-element/two-source baseline. Native OA Action/State/Reuse/ALT-fragment, each exact Save/Undo/Redo, and final native reopen pass at minimum size; caller identity/scroll return and source-neutral navigation pass. Remaining prescribed checkpoints are open. [Native scope](release-scenario-native-20260911.md), [oracle inputs](fixtures/scenario-authoring/README.md). |
| Normative documentation | Strict Docutils 0.22.2 language HTML regeneration passed. `semantic_schema.py --check --validate` passed 72 source7 fixtures, 204 schemas, 14 families/90 scalar leaves. These are documentation/schema gates, not a Rust build or runtime pass. |
| Comparable-product study | Actual isolated Capella 7.1 scenario/activity/lifeline/LOOP creation was saved and XML inspected, then closed normally. [Report](release-capella-scenario-benchmark-20260910.md). Current Studio native evidence is recorded separately. |
| New requirement audit | [Independent delta report](release-requirements-delta-20260910.md) establishes that current expressions/unit labels are descriptive and source includes are not maintained cross-project libraries. Refined B/R6/R7 and exact-pin/same-origin compatibility contracts are ratified; current source7 does not implement them. |
| Packaging integration | External `b98f135` imported as `6d2b961`; all 25 checked-in exact notices match the manifest. `scripts/test-package-artifacts.py` passes 11/11 and `scripts/test-windows-notices.ps1` passes synthetic package/runtime/source/font checks. Actual optimized distributions and clean-environment launches remain open. |
Toolchain bootstrap exec session **20812** completed successfully: verified
LLVM-MinGW 20260908 ZIP SHA256
`1bcf74d06b724aeecaa6412ca85f5b26fb1da770e7cdcefa9263c9c5c3ad34b6`, extracted
successfully; stable **1.98.1** GNU/LLVM, rustfmt and Clippy installed.
`.local/toolchain/env.ps1` configures task-local Cargo/Rustup/PATH and one build
job. Locked dependency fetch is local exec session **13108**. No build/test pass
is established; the target cache is still cold.
## Active work, ownership and unresolved findings
The coherent candidate `01bb52a` passed `cargo fmt --all` and `git diff --check`.
Direct push failed because this fresh host has no Git credentials. Authenticated
Gitea MCP transferred its exact verified Git bundle through
`codex/behavior-transfer-20260910` (`harness/transfers/behavior-01bb52a.bundle.b64`),
prerequisite `1797516`, decoded SHA256
`85A38B00207036DCB8DB24ED4A7E80B2BE670275EEB7B00413D36153322ADA5D`.
This **UNTESTED integration snapshot** lets the other host use its warm cache;
transfer is not acceptance. Their broader architecture
palette/Escape repair should be reconciled with our overlapping compile/stale
repairs while retaining the additional invariant tests. Their measured minimum
scenario canvas is too small; they own the subsequent layout implementation.
Their isolated palette commit is `7d1df4f`, fetched locally for reconciliation.
Root Codex-956atf owns this host's integration, serialized Cargo and native UI.
The source2cc4d11 gate completed with exit0: **676 passed, zero failed/ignored**,
tests611.24 seconds after warning-free compilation10m47s. Command:
`cargo test --locked -p oa-desktop --bin arcadia-studio -- --test-threads=1`.
Log `.local/logs/desktop-creation-chooser-20260911.log`. Immutable executable
`.local/creation-chooser-20260911/tests-2cc4d11/arcadia-studio-tests.exe`, SHA256
`8D7FB35071F155B3BD07CE1885A1136B2D2EF71C4FF8C704665202499C86A721`.
Its manifest pins256 tracked input hashes. Format passed; strict all-target desktop
Clippy passed7m18s after the isolated manual-clamp correction. Final logs are copied
beside the immutable binary. These gates supersede the historical642 total, not the
current uncompiled working changes. Focused counts are included, never additive.
Independent F1 review found a real optional-value cache collision in `01bb52a`.
The follow-up distinguishes null/scalar/list/tagged constructor identities and
adds actual inner selector-event tests. Independent source recheck found no
remaining collision; execution is still pending. The original full-platform
fetch was stopped after network timeouts; current Windows desktop test build
is exec session **51036**, compiling dependencies. Root owns this Cargo lease.
Actual native Studio remains `.local/native-qa/studio-80cf197/`, GUI SHA256
`A5ED6DF334B1BFB620425AFDF3E863F0B522990E6FB47C6C401A71CF4443954A`.
That GUI build passed3m28s. At1100x700, all four OA creation checkpoints and final
reopen now pass complete Project/two-source prediction and exact UUID restoration.
Preserved OA snapshots end in `oa-reopened/`; separate SA Action Save/Undo/Redo
also passes complete oracle/history comparisons, ending in `sa-action-redo/`,
63objects. The GUI is saved at SA A caller, no active form. SA State/Reuse/Fragment
and final reopen remain. No new-fix acceptance is inferred.
[Native report](release-scenario-native-20260911.md) records details and two real
workspace findings: new forms retain downward scroll, and opening a form can hide
its clicked marker below the reduced canvas. Root has written a fresh form-session
key, guarded Name focus, one-time marker reveal and three meaningful mounted/App
regressions. They are not yet compiled. The isolated chooser's corrected realistic
typing/paste/IME gate passes13/13; production inspector/review integration is now
source is now frozen, with exact row/facet/group/attachment guards. Independent
review exposed and closed three focus defects at source level, including the
legitimate Review rationale input. Fourteen new App/mounted tests await execution;
the earlier isolated13 is separately scoped. [Review](release-reference-chooser-production-review-20260911.md).
Next: focused `architecture_authoring_tests`,
`behavior::topology`, `direct_clicked`, caller-navigation and `history_fields::tests`,
then full relevant gates and a fresh native binary. Root owns all Cargo on this
host. Worker output or tests existing in source are not passes.
User [issue2](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/2)
requires Process and Scenario to behave as actual canvases like architecture/state
diagrams. Current scrollable diagrams/tool shelves do not close that requirement.
behavior_audit owns a bounded shared-canvas design; root re-observed the saved
native scenario and its restricted viewport, without new model input.
Gitea Actions run16 is queued for both ubuntu-latest and windows-latest with no
started steps, as are older listed runs. No usable current Linux runner result
is established and no duplicate dispatch was made. Progress is concrete;
release acceptance remains incomplete. Older checkpoint paragraphs below retain
their original revision scope.
The [baseline contract](release-analysis-baseline-contract-20260911.md) supplies a
complete17-UUID proposed model,11 exact fixtures, explicit ModelBaseline/Case,
property bases and shared checks. Its transport fixtures are not parser/evaluator
acceptance. The [library contract](release-library-compatibility-contract-20260911.md)
has120 executed finite-prototype assertions, separate-process reopen and11 complete
expected/reopened file comparisons. Final81-file manifest was independently
verified; preliminary output is retained and labeled superseded. All166 experiment
files retain exact Git bytes. Root ratified B/R6/R7/full private capture, nominal
typed compatibility alongside exact pins, explicit source normalization and OA/SA
dispositions in [DECISIONS](DECISIONS.md).
**Checkpoint publication — 2026-09-10:** the user requested committing all current changes and pushing `codex/release1-continuation` to both `origin` and `gitea`. This is a work-in-progress snapshot. The interrupted palette-focused compilation failed with E0659 (ambiguous `column!` in `app/architecture_authoring/palette.rs:168`) and E0507 (moving the view out of an Arc in `diagram.rs:624`); an unnecessary-pattern-parentheses warning also remains in `architecture_authoring.rs:346`. The prior 584-test pass does not cover this newer palette revision. No Cargo/rustc process or local subagent was active at the publication preflight. Fix these errors and complete automated/native acceptance before packaging the redesign. Gitea coordination starts at issue #1 and the project Wiki; older evidence below retains its original scope.
The [independent refined review](release-refined-contracts-review-20260911.md)
passes292 fixture/identity checks but finds C1:333 stored AST nodes can expand to
over2billion calls. Request-local dynamic/numeric work accounting is mandatory;
static depth/node limits alone fail. C2 is a finite-prototype threshold-unit gap,
not a passing production type-checker. Exact arithmetic, unit/dimension operations
and terminal work meter are declared/committed at7d14bd0; their26/26 unit gate has
[exact source/artifact evidence](release-analysis-numeric-gate-20260911.md).
requirements_delta now owns actual schema8 definitions, expressions, commands,
references, migration and static admission in the isolated
`.local/analysis-core-worktree-20260911/`, based at7d14bd0. It remains uncompiled.
semantics_critic reviews the bounded decoder strategy separately; existing default
recursion rejection stays until a full allocation/lifecycle gate is justified.
Root owns compilation. Numeric/runtime and static-admission ceilings remain
explicitly provisional pending measured gates. Approximate engineering calculations,
full evaluator/model/source/REST/GUI parity and actual library maintenance are open.
**Latest priority checkpoint — Capella consultation and redesign:** the user rejected the large creation buttons and explicitly requested consulting the installed Capella. Native control resumed for that consultation in a disposable Capella 7.1 workspace. Actual palette, F2 rename and activity allocation were exercised; saved XML confirms allocation distinct from ownership. The horizontal creation/connection rows are being replaced with a compact expandable palette and inline naming. This supersedes the Escape hold and toolbar-fix proposal below. New implementation, native acceptance and a fresh user build remain pending. [Observed benchmark, alternatives and acceptance criteria](release-capella-basic-editing-20260907.md). The first-release goal remains active.
Codex-9e8r6t and Codex-ytr83r are separate hosts/teams. The former owns contextual
prerequisite creation and source CLI. CLI01b76a1 is imported asbc311bc; exact
corrected evidence2ec72d4 is imported atdc0f2e1, preserving root's separate native
report. External675 staged-source and CLI12/183-assertion results remain externally
attributed. Its runnable Studio/server preview release1 and standalone CLI preview
release2 are published; see their release notes for exact source/runtime limits.
Strict language/API HTML regeneration and the72-fixture source7 schema gate pass
locally after that evidence import. Codex-ytr83r owns B4
production Scene wiring, independent native oracle and local Linux route. Its
rendering source has independent criticism but no passing build/native gate yet.
Do not duplicate these changes. Preserve root's distinct scenario-scroll/focus hook
when integrating other hosts' small App/behavior bridges.
**Latest checkpoint:** basic-editing v1 passed full desktop584/584, Windows binaries, format and strict all-target Clippy. Native v1 D8CFAA confirmed direct contextual named Entity creation at100%, and found a22px placement shift caused by the pending toolbar changing canvas height. The user pressed Escape at the attempted Undo; that action did not execute. **Desktop control is paused again.** Process9600 remains the isolated unsaved QA application; do not overwrite its binary or presume a clean close. Code-only placement fix is continuing. [Exact v1 evidence and remaining acceptance](release-basic-editing-reset-20260907.md). This supersedes the resumed-control state below; the first-release goal remains incomplete.
Updated AGENTS4b8465c8 adds concise shared maintenance to milestone releases. Gitea
user#178 explicitly authorizes programmatic reuse of existing MCP credentials for
Git/REST and relevant commits/tags/prereleases, without printing or committing them.
Direct authenticated push/readback passed on this host, most recently publishing
dc0f2e1. The subsequent owner's instruction commitcab01c3 has been fetched and
merged locally; no force push or additional credentials are required.
Historical verified bundle exchange remains reproducible: c6d296a bundle on
`codex/behavior-transfer-20260910`,334830 decoded bytes, SHA256
`526A80E2D32ED0E57A7B2372B5F02D4652E8751DFEBA81953C4F045225D6AACB`,
prerequisite1797516. Both other hosts received it. Never merge transfer branches.
Older bundles/logs retain historical scope in Git and the archived ledger.
**Superseding priority checkpoint:** the user explicitly said “Resume desktop checks” and rejected the focus on advanced review before basic diagram editing. Isolated native checks resumed and reproduced the global creation catalog, placeholder creation/camera jump and noisy review. Contextual named creation and compatible layer-transition destinations are now being implemented and tested. Their new executable has not yet been accepted. [Current priority and scoped evidence](release-basic-editing-reset-20260907.md). The older Escape hold and next-step priorities below are superseded; historical binary/test results retain their original scope.
## Remaining gates and highest-value next actions
Current checkpoint: 2026-09-07. The requested Windows development preview is built and packaged with its runtime, documentation, notices and complete examples. Latest Fit6, two existing scroll/branch regressions, full desktop570/570, workspace bins, formatting and strict workspace/all-target Clippy pass. Corrected server56/56 retains its earlier unchanged-server scope. Packaged DC50 GUI launched and the OA graph Fit overview was observed at1444×932 and1102×932; minimum-height and pending-form native acceptance remain open. The user stopped Computer Use with Escape; do not resume native control without renewed authorization. Native Linux core436passed/2ignored remains verified; corrected Linux server and full Linux GUI build/runtime remain open. The fresh Linux desktop cross-build passed on Rust1.90 in2m20s using the preserved cache; ELF and all37 teaching files are verified. Three later guest boots failed the early IO-APIC timer check before SSH/tests; the exact-kernel workaround was then rejected by automatic approval review before launch. All task VM processes are stopped. **Goal active; release incomplete.** The authoritative objective is `C:\Users\User\.codex\attachments\10b0f701-1743-4de7-9ee1-225920e19649\goal-objective.md`: a usable, feature-complete OA/SA engineering tool for Windows and Linux with graphical/source/REST parity, artifact traceability, offline guidance and independent end-state acceptance.
1. Freeze and compile the new workspace/chooser integration, resolve focused
failures, then build an immutable GUI and verify both native workspace fixes.
The676-test gate is complete for2cc4d11; new changes require their own evidence.
2. Publish coherent checkpoints directly; integrate9e8r6t's next staged-source
work, then ytr83r B4 only after its coherent handoff. CLI/evidence import is done.
Preserve ownership and distinguish every external versus local gate.
3. Use the self-checked independent oracle to exercise current Studio at
minimum/wide sizes: named creation, direct process/scenario edits, nested reuse,
caller return, lifeline lifecycle, invalid/cancel/recovery, Save/Undo/Redo/reopen.
Compare complete model/source and exact identities, not screenshots alone.
4. Compile/review/measure the numeric foundation, then implement the ratified
analysis/library contracts with shared-core/source/API/graphical parity. Use real
budgets, unit/kind failures, complete text-only and two-project update workflows.
Integrate the bounded chooser and run its actual keyboard/minimum-size gates.
5. Complete current teaching, transitions, semantic review, state/data, saved-view,
artifact, hosted transport and migration acceptance. Historical scoped passes
remain useful references, never blanket current acceptance.
6. Complete Windows/Linux build/test/native/runtime and optimized package gates,
notices, provenance and clean-environment launch. WSL has no installed distro
here; Linux acceptance remains open. Historical denied guest workarounds must
not be retried or split to bypass review. No host restart is authorized.
7. Run fresh independent cross-disciplinary end-state review, resolve material
findings and reconcile specification/help/coverage before final handoff.
## Workspace and ownership
## Reassessment
- Current branch `codex/release1-continuation`, checkpoint **4b6b5fc1977523e8cf52fdd5503a0a71c87a3f63** commits290files of source6 work and evidence. [Bounded checkpoint audit](release-checkpoint-integration-review-20260906.md) verified65pinned manifest entries and145exact staged/working fixture/archive files; `.gitattributes` protects their measured line endings. Integrated ancestry starts at `c091f80`; [branch audit](release-branch-integration-20260906.md) prevents reimplementing already integrated work. New source7 implementation is authorized but not yet accepted.
- Historical6BAB native scope (superseded in rendering by BCC1 and Fit by DC50): acceptance binary `.local/native-qa/bin-source7-acceptance/arcadia-studio.exe` SHA256 `6BAB6CDE7D31326F3C3CF7342D9B25FB6ADA032864BBE8104625E5EC9736283B` follows the Windows433/55/561 and strict/build gates below. Reset and ReadStatus each passed exact complete model/source Save/Undo/Redo and reopening with the correct derived Reply allocation30/31. OA caller→First.B passed exact persistence/history/reopen; routing remains open. Process11060 closed cleanly; isolated old6 recovery process11240 also closed after its complete source/JSON/raw-draft pass. Old5 process5244 subsequently passed exact30-source/full-JSON recovery and raw-workspace comparison. Current7 process8224→10420 passed invalid nested-link draft crash recovery; completing the recovered SA X→[R3,Inner]/B link passed exact model/two-source Save/Undo/Redo and saved reopening. Those historical native processes closed; the later BCC1 routing and DC50 Fit evidence is recorded separately below. [Native evidence](release-source7-native-acceptance-20260907.md).
- Completed bounded90minute Linux gate: one-job Rust1.90,455-file immutable snapshot SHA256 `7104946c89b2be7a1a030fdff47cb4405bacf05357d68cf35d181e860f55c279`, launched07:02:43UTC, deadline08:32:43UTC. Server compilation passed17m10s; unit2/2 and HTTP50/51 passed, with one504-vs-412 test assertion reproduced in an isolated rerun. Its two-second read/PATCH checks passed, but later persisted-state assertions were not reached. This establishes a timing-dependent fixture/deadline mismatch, not a production locking defect. Native core completed436passed/0failed/2ignored across40targets, Rust1.90, compile23m03 and1992seconds total; all455 source pre/post checks passed. The two ignored cases are optional inheritance scaling and explicit strace fault injection (earlier separately scoped injection passes remain historical). All artifacts were copied before sync/poweroff; QEMU6280, launcher5000 and seed816 were absent08:13:56UTC. [Current Linux report](release-source7-linux-gate-20260907.md). Earlier Linux evidence retains its older snapshot scope. WSL remains pending restart; no host restart is authorized.
- Windows session5735 completed all six gates with exit0: focused prepared-HTTP and cancellation, full server56/56 in68.78s, format10.44s, strict workspace/all-target Clippy99.60s, bins102.22s. Status/logs: `.local/source7-post-routing-gates-status.json`. Distinct GUI BCC1FC6DB68123C9D3A43CE53AA8EF59E33C54080632C104C99ED13270D5333F process8568 passed the scoped corrected routing checks and closed cleanly. [HTTP evaluator correction](release-http-preparation-phase-regression-20260907.md), [routing correction](release-contextual-route-native-fix-20260907.md), [native details](release-source7-native-acceptance-20260907.md). These passes precede the now-tested [Fit/layout correction](release-process-fit-layout-audit-20260907.md).
- The requested Windows preview is `dist/ArcadiaStudio-preview-source7-20260907-x86_64-pc-windows-gnullvm/arcadia-studio.exe`; its565-file ZIP includes all37 teaching-folder files and has SHA256 `1fac10b30daf2f8e1dac29e9469485e4bea142e77ff5a13e4c9d1e41ff03abb2`. The adjacent provenance records actual source/binary hashes. This is a development profile, not an optimized final release. Latest gates are in `.local/source7-latest-preview-status.json`; full desktop570/570 completed in198.82s test time,200.63s command time, exit0 in `.local/source7-latest-full-desktop-status.json`. Initial Fit4/2 failures exposed real zero-size-slot remounting; corrected constructors pass unchanged expectations. [Fit review](release-process-fit-independent-review-20260907.md), [development summary](../DEVELOPMENT_SUMMARY.md).
- Computer Use is stopped. Read-only inspection initially found preview9148 and second GUI8044 live; later9148 exited without agent intervention, while8044 remained untouched. No GUI control/closure is authorized for background verification. The cross-compiler lease ended after the successful142.766s monotonic run; no cross processes remain. The Linux worker completed a bounded headless guest experiment and released the lease. Three boots (same configuration twice, then Normal boot priority) reached terminal IO-APIC timer panic before SSH/Cargo; all task VM trees stopped and exact evidence was preserved. Exact matching kernel/microcode extraction passed without changing base/overlay hashes; automatic approval review rejected preparation/launch of the transient no_timer_check experiment as “blocked by policy.” No fourth boot or corrected tests ran. No task VM is live; see [the preserved boot evidence](release-source7-linux-server-corrected-gate-20260907.md). [Cross-build report](release-source7-linux-gui-cross-build-20260907.md).
Meaningful progress continues: concrete interaction defects have been found and
corrected,676 desktop tests pass and all four OA native creation/history/reopen
checks pass. Contracts have converged through independent falsification; numeric
implementation now addresses the exposed dynamic-work risk. The revised semantic
requirements are no longer hidden behind metadata.
Passing older suites or accumulating prose would not close the user problem.
Current highest information gain comes from actual build/native results and
independently criticized foundational examples, while preserving existing identity,
source and atomicity contracts. Replan when those results falsify a proposal.
## Current source build and stopped runtime gate
## Historical evidence access
The guide-only followup compiled successfully with locked Windows workspace bins in12.70s Cargo/12.82s command, exit0. Status `.local/source7-guide-current-build-status.json` records guide SHA256 `80A6797051FB28E767F2AB5DD2F335ABCD9F3E5F3A75C731CDE46D8B90D5C92E`; resulting GUI SHA256 `327FBDF734716A7F1AF2874183D46A531A8F429BA1A478E83A3E7F2EB1D6248B`. Formatting and independent actual-label review pass. This later debug artifact does not replace the user-facing packaged DC50 preview, its archive or earlier native evidence. No full570 rerun is claimed for the text-only followup.
Previous goal turn made progress by confirming full570 tests and handing off the package/summary. This continuation produced the successful Linux GUI build/ELF evidence, validated purpose oracles, corrected/built guide text, and concrete guest-boot evidence. Goal remains active/incomplete. The denied direct-boot action must not be split or retried to bypass automatic review; no new Linux job is running or scheduled.
## Latest Linux build and purpose-oracle evidence
Linux GUI snapshot458files `source7-20260907T102528493108Z` has archive SHA256 `9b10aa8457a5371367f7e24a0b2260b63c19fed69873d98a3972062a744503d7`. Run `20260907T1025486926611Z` passed locked/offline Rust1.90 zigbuild, both source checks and independent ELF/package readback. GUI72,953,296bytes SHA256 `330A3872D48EBF24AD21E6D4FA13CB6098BEBB3CB7FF82A2E082925CCF3DD346`; ELF64PIE, glibc requirements≤2.28, all37 lesson files exact. Actual Linux GUI runtime is still unverified. Subsequent guide-label text is excluded from both published Windows and this frozen Linux preview.
Extended native checker `source7-native-contract-incidence.exe` SHA256 `16994DC437F5CCC5E5F6FBB4212C03449F2389AE4615FA98B2930B3637468EE3` compiled with warnings denied in4.05s during a coordinated short lease. OA Exchange and SA CommonWork self-checks pass: exact contextual assembly, unchanged precedence, wrong direction/work rejection, caller-only exchange coverage and stable source update. Separate43-element/10-relation incidence fixture baseline passes; all original golden hashes and preserved OA-link/Reset accepted cases remain exact. Independent review found no material issue. [Cases and reproducible native steps](fixtures/source7-native/README.md). Native purpose authoring/history remains pending.
## Completed and verified at this checkpoint
| Scope | Evidence and limit |
|---|---|
| Historical source6 diagnostics and guide | Semantic filter **108 desktop + 2 core** passed; full desktop **527/527** passed; strict all-target Clippy and GUI/server build passed (`.local/semantic-diagnostics-final-tests.log`, `desktop-diagnostics-final-tests.log`, `diagnostics-final-clippy.log`, `diagnostics-final-build.log`). Subsequent guide **3/3** focused tests, strict Clippy and build passed (`.local/guide-navigation-{tests,clippy,build}.log`). The guide test increases compiled desktop inventory to528; no full528 run or final full-workspace total is claimed. |
| Current artifact implementation checkpoint | Full desktop **518/518**, corrected fresh artifact picker **6/6**, strict all-target Clippy passed. Logs `.local/source6-artifact-inspector-desktop-tests2.log`, `.local/source6-artifacts-final-tests2.log`, `.local/source6-artifacts-final-clippy3.log`. Four subsequent artifact recovery falsifiers and two core absence oracles passed separately. This predates latest display corrections. |
| Native artifact MOVE / CREATE / DELETE | All three complete source Apply/Save, one Undo/Save and one Redo/Save oracles passed; **nine saves succeeded first attempt**. MOVE invalid Owner and disabled optional text, and CREATE excluded row/all eight decisions/reserved UUID survived controlled-stop recovery exactly. DELETE removed destination from identified moved-source absence while retaining the source link. [Exact native report](release-artifacts-native-20260906.md), [fixture/generator instructions](fixtures/release1-native/artifacts/README.md). |
| Source-6 atomic batch review | Included valid and excluded invalid raw rows survived forced-stop recovery; repaired two-source Apply and complete Save/Undo/Redo source comparisons passed. [Native report](release-current-native-verification.md). |
| Scenario ordered-member variant | At1100×700, Take rejected ambiguous insertion; explicit final order retained the local self-test. Complete Apply/Save, Undo/Save and Redo/Save matched the independent source oracles with only the schema5→6 header token upgrade. All three saves succeeded first attempt. Branch steps/fragment branches and this variant's crash recovery remain separate cases. [Exact native report](release-current-native-verification.md). |
| Native guide navigation | On current guide binary at1100×700: related Scenarios-bottom→Exchanges opens the new heading; filtering `exchange` retains the current topic's bottom position; `Git` auto-selects Build first and opens its heading. No dirty model. Root's actual native observations close these bounded scroll cases; [implementation/tests](release-semantic-conflict-diagnostics-20260906.md) remain separately scoped. |
| Communication means | Drawing/create/reuse and legacy reverse full-model/source/history passes are retained. Corrected reverse Apply now opens the explicitly requested OA scenario in Behavior, preserving the original four-object Architecture. Distinct oracle predicts10UUIDs/zero placements; accepted model/all3sources, Undo baseline, Redo and reopen pass. Every Save succeeded first submission. Navigation5focused tests, strict Clippy and bins build pass; compiled desktop535 is not a full535 run. [Exact report](release-communication-native-20260906.md), [implementation](release-behavior-transition-context-20260906.md). |
| Teaching project and Home hook | Corrected94element/62relation/5view/68trace/30source example passes4expanded direct-rustc tests. Minimum-size Home/guide, raw-source guard, reviewed NameTake and exact source/history/reopen pass. Navigation fix is reverified. Additional data/interface/type drill-down, saved-view comparisons, invalid-view guard and typed Entry action selection pass. Fold/unfold and function rename/Undo/Redo each match complete model/all30source oracles, five first-submission saves; saved reopen retains the Entry target identity. Complete process/scenario/reuse/evidence lesson remains open. [Native report](release-teaching-native-20260906.md). |
| Child/Incident and source-5 recovery | Two-row attachment recovery and complete Apply/Save/Undo/Redo passed, every save first attempt. Exact old source-5 raw/base/include/path retention, manual repair and two-file Save passed. [Attachments](release-attachments-native-20260906.md), [source-5 native](release-source5-native-recovery-20260906.md), [independent review](release-source5-checkpoint-independent-review-20260906.md). |
| Dense saved views | Forty-label baseline and selected real relation identities inspected; filter, duplicate/hide, original10/copy9 persistence across restart and exact model oracle passed. Additional coverage/context intersections, empty selections and Names-and-items preview/Apply/Undo observed. Minimum-size overview requires working zoom/pan. Limits remain in [native evidence](release-current-native-verification.md). |
| Core/source/REST integration | Fresh `--all-targets` core run: **433 passed/1 ignored**,44 target summaries, exit0 in138.72s; fresh server run: **55/55**,4 summaries, exit0 in64.74s. Logs `.local/source7-core-all-targets.log`, `.local/source7-server-all-targets.log`; exits/timings in `.local/source7-current-gates-status.json`. These supersede the earlier combined core count and pre-budget-fix HTTP51 checkpoint. OpenAPI **72fixtures/204schemas/90leaves** and both strict reST renders pass. [Core checkpoint](release-source7-core-checkpoint-20260906.md), [API integration](release-source7-api-integration-20260906.md). |
| Source7 desktop authoring and recovery | Latest routing3/3 and full desktop **564/564 pass**; [routing checkpoint](release-contextual-route-native-fix-20260907.md) records exact logs. Earlier full desktop **561/561 passed**, zero failed/ignored,263.39s in `.local/source7-desktop-full-tests2.log`. The initial560/1 run exposed canvas scroll-state loss when a new conditional navigation control shifted its widget; a fixed navigation container corrected it, and the unchanged regression passed. Coverage includes qualified5, operation3 (selected Async request fields), semantic source7 facets/omission3, recovery8, legacy source5 13, artifact search2 and focus guard1. Exact old-version enum/cache-path intent rejection and raw text retention are covered. The complete-scope endpoint picker preserves access beyond512; canvas preview remains bounded. Guide now accurately describes attachment/artifact reconciliation and artifact filtering. [Desktop checkpoint](release-source7-desktop-authoring-20260906.md), [recovery](release-source7-recovery-20260906.md). |
| Windows strict/build checkpoint and native7 | Strict workspace/all-target Clippy passed2m50s; root observed final format exit0/empty log. Three affected semantic tests passed3.46s after equivalent lint edits; native build exit0 recorded in `.local/source7-current-gates-status.json`. These earlier results scope the6BAB binary, not the later routing test binary or pending new strict/build sequence. Reset/ReadStatus full model/all-source Save/Undo/Redo/reopen pass. OA First.B persistence passes but routing acceptance remains open. Old6 Recover preserved the complete30-file bundle/workspace/Ports DTO, exact spaces/Unicode/fingerprint/reserved identity; Cancel/Save as and JSON export passed full independent source/model equality. Original seed unchanged. Old5 complete accepted/raw recovery, exact repair/30-source Save and full-model export pass. Current7 invalid nested draft crash recovery plus completed link Save/Undo/Redo/reopen pass; rendering still uses the older binary. [Native report](release-source7-native-acceptance-20260907.md). |
| Current Linux source7 and cross-built probe | Frozen native server compilation passed17m10s; unit2/2 and HTTP50/51, with one timing-dependent504-vs-412 assertion reproduced twice. No complete server pass; later targets not claimed. Native core436passed/0failed/2ignored; VM cleanly off08:13:56UTC. Separately, the complete Windows macro/build-script cross-build probe's hash-verified ELF executed successfully on Linux; this is neither a full desktop build nor GUI acceptance. [Native Linux gate](release-source7-linux-gate-20260907.md), [cross-build probe](release-linux-cross-build-probe-20260906.md). |
| Historical Linux/MSRV core and server | Ubuntu24.04.4/x86_64/glibc2.39/ext4/Rust1.90: core38/38, patched journal4focused/42full and3explicit syscall fault cases pass on recorded snapshots. Actual server build passes34m42s including3m24s pause. Real HTTP modular import, invalid PUT unchanged source/ETag, clean SIGTERM and exact model/source/ETag restart pass on the older28-source lesson snapshot. Full server test command timed out while compiling; zero tests executed. That gate shut down cleanly21:53:56; the separate current gate has the scoped results above. Current desktop/Linux package unverified. [Linux report](release-linux-validation-options.md), [journal contract](release-linux-journal-publication.md). |
| Packaging foundation | Portable Windows QA staging, dependency/runtime/font/Rust notices, archive readback and clean-PATH smoke passed at earlier binaries. [Package report](release-windows-package-review.md). QA archives are not current final release artifacts. |
Historical full platform/native milestones retain their original revision scope; [complete prior ledger](history/2026-09-06-ledgers-before-consolidation/STATE.md) preserves all evidence links and previous environments. A test or native pass never transfers automatically to a changed executable.
## Active findings and checks
Native artifact review exposed same-row conflict wording and reserved identities shown as deleted. Corrections retain typed actual-slot equality, row-addressed reservations and accepted-identity precedence; independent re-review found no further material defect. The completed108-semantic/527-desktop checks supersede the earlier interrupted run and include reserved-label/partial-creation regressions. Revised artifact wording still needs its own native observation on the current binary. Guide-scroll implementation/tests/build and the bounded native cases above passed. [Diagnostic/guide report](release-semantic-conflict-diagnostics-20260906.md).
**F1** teaching onboarding/review/history has current-binary native evidence; remaining tutorial work is scoped in its report. **F2**, faithful behavior-canvas SVG export, is deferred by root's scope decision: export remains architecture-only and must be described that way; no faithful scenario/process/state SVG acceptance is claimed.
Reverse scenario's first-dependency focus/overlapping architecture placements and teaching NameTake's separate layer/view mismatch are fixed and natively reverified. Latest NameTake4focused tests, strict alltargetClippy28.26s and binsbuild50.50s pass; no full539desktop pass is claimed. [Navigation evidence](release-semantic-review-navigation-20260906.md). Minimum-size process working space is cramped; native lesson evidence records23% overview versus100% scrolling rather than claiming readability at Fit.
Independent scope reconciliation verified **S1** missing contextual assembly into repeated/nested process references and **S2** missing maintained interface-operation identity in parameterless messages. Isolated existing-core probes falsify the proposed workarounds. Root ratified the jointly critiqued [source7 integration decision](release-source7-integration-decision-20260906.md), including deterministic cache-independent admission, whole-link deletion, purpose-specific analysis, exact Call-derived operation/Reply identity and one frozen old5/6 checkpoint migration. These contracts now have implemented core/source/REST/desktop/recovery paths and the current automated gates above; remaining native7 and current Linux acceptance remain incomplete. [Scope reconciliation](release-scope-reconciliation-20260906.md).
Linux ordinary rename's empty-target replacement was independently reproduced and corrected using `renameat2(RENAME_NOREPLACE)` without fallback. Exact errno/no-write assertions now pass under actual syscall injection. This establishes the ext4 publication invariant, not power-loss durability, hostile ancestor protection or model-file compare-and-swap. Windows retains its no-replace API and bounded scanner retries.
## Remaining gates and next actions
1. Fit implementation/review and automated gates are complete, including full570 desktop tests. Finish its native minimum-height/Focus/pending-form checks when native control resumes. Preserve completed BCC1 routing and old5/old6/current7 recovery/source/history oracles. Complete remaining current-binary S1/S2 purpose workflows and teaching cases; operation allocation deletion remains subject to independent channel validation. Native-check revised reserved labels and same-row conflicts. The later guide-only control-label correction passed formatting, independent review and the fresh workspace-binary build; it awaits the next packaged/native release snapshot.
2. Close uncovered selective-view lifecycle cases; advanced ordered/process/scenario/fragment variants beyond the accepted Scenario case; typed state actions and pending Linux data/hosted/compact workflows. Implemented semantics must not be called missing merely because acceptance is outstanding; [coverage audit](release-current-coverage-20260906.md) is the baseline map, newer scoped reports supersede its old gap claims.
3. Verify complete current Linux integration suites and desktop/server build/runtime, then supported-size native workflows. The successful core/MSRV pilot is a reusable starting point, not application acceptance.
4. Preserve current strict Clippy/format/reST/example/source/OpenAPI results and rerun affected checks after changes. Complete optimized/MSRV/final platform gates, actual hosted transport variants and final migration/package checks. Rebuild portable distributions from the accepted exact tree, validate notices/runtime/content/checksums and clean-environment launch before replacing old bundles.
5. Conduct fresh independent requirements/domain/parity/architecture/runtime/UX/end-state reviews; resolve material findings. Commit/integrate authorized source with reviewable scope; remote publication is not requested. Only complete the goal when its applicable criteria are met.
Meaningful progress continues: native lifecycle and Linux no-replace uncertainty have been resolved with exact oracles. The highest-value work is current-binary validation and closing uncovered engineering workflows, not accumulating repeated historical headings or treating aggregate test counts as release completion.
The [complete prior STATE](history/2026-09-10-ledgers-before-continuation-refresh/STATE.md)
retains exact historical binary hashes, counts, logs, process closure, bundle hashes
and all report links. Links inside the byte-preserved archive retain their original
`harness/` context; resolve those relative report paths from `harness/`.
Useful direct entries: [source7 native](release-source7-native-acceptance-20260907.md),
[teaching](release-teaching-native-20260906.md),
[artifact native](release-artifacts-native-20260906.md),
[coverage baseline](release-current-coverage-20260906.md),
[Linux gate](release-source7-linux-gate-20260907.md),
[Linux cross-build](release-source7-linux-gui-cross-build-20260907.md),
[denied boot experiment](release-source7-linux-server-corrected-gate-20260907.md).
+198 -71
View File
@@ -1,96 +1,223 @@
# Task Ledger — first release
## Current knowledge — 2026-09-10
Updated 2026-09-11. [STATE.md](STATE.md) owns current execution/evidence;
[PLAN.md](PLAN.md) owns capability milestones. The entire former Task Ledger is
[preserved byte-for-byte](history/2026-09-10-ledgers-before-continuation-refresh/TASK_LEDGER.md).
Its old goal references, aggregate test claims and stopped-session directives retain
historical scope. New semantic decisions are recorded explicitly in DECISIONS.md;
prototype results retain their separate scope.
Given: the renewed objective in `PROJECT_GOAL.md` requires a feature-complete,
usable OA/SA first release and prioritizes direct behavior/scenario authoring.
Graphical/source/REST parity, explicit reST semantics, traceability, offline
guidance, Windows/Linux acceptance and independent review remain required.
Older scope deferrals must be checked against this request.
Verified: the checkout began clean at `1797516`; Gitea contains one active
continuation issue and no open PR. Current code includes direct behavior editors,
so old blanket descriptions of static diagrams need workflow-level reassessment.
The machine began without the ignored historical toolchain/cache/distributions.
Local Rust/Cargo 1.98.1 and verified LLVM-MinGW are now installed; dependency
fetch is pending and no current binary has been built. Native Computer Use is
available. Isolated Capella activity/lifeline/LOOP creation was saved and checked;
no Arcadia window is running. Candidate B1/B2/B3 and F1 edits are source-complete,
formatted and whitespace-clean, but have no fresh compile/test/runtime pass.
Assumption: the selected compact architecture palette remains a promising design,
pending real authoring evidence. Decision: repair and evaluate it before further
redesign. Parallel independent audits identify current behavior and semantic gaps
instead of reimplementing integrated work.
Open questions: which remaining menu-only behavior operations prevent a coherent
direct workflow; which first-release semantic/parity gaps remain; and how to
complete current Linux runtime acceptance. Root owns integration and native
control; worker ownership is disjoint. See `STATE.md` and Gitea #1.
**Superseding user direction:** large horizontal creation buttons were rejected as intrusive and unprofessional. The user explicitly authorized consulting the installed Capella; that consultation has resumed and established actual compact palette, inline rename and explicit activity-allocation behavior. See [Capella 7.1 evidence and selected redesign](release-capella-basic-editing-20260907.md). The current candidate replaces creation/connection rows with one compact expandable palette and an in-place name editor. Native acceptance of the redesigned executable is pending; compactness is not assumed to prove usability. The earlier Escape hold and proposed toolbar-only correction below are superseded.
**Latest evidence:** basic editing full desktop584/584, bins, formatting and strictClippy passed. Native named Entity creation works at100%, but changing pending-toolbar height moves the screen placement22px. User Escape stopped the attempted Undo; native checks are paused again. Code-only toolbar correction proceeds. [Current findings](release-basic-editing-reset-20260907.md). The previous goal turn made concrete progress through implementation, integration gates and a native-discovered defect; this is not a no-progress blocker turn.
**Current steering:** basic diagram authoring and understandable OA/SA transitions come first. The user explicitly reauthorized desktop checks; root resumed the isolated test build and reproduced the reported usability problems. Creation, transition and independent fixture work is underway. No new basic-editing native pass is claimed. See [priority reset](release-basic-editing-reset-20260907.md); older execution priorities and Escape hold are superseded.
Updated 2026-09-07 after source7 Reset/ReadStatus and old6 recovery native passes, OA contextual persistence with rendering open, and reproducible Linux server test deadline evidence. Native Linux core now passed436/0failed/2ignored and its guest shut down cleanly. Old5 full recovery and source7 pending nested-link crash recovery/history/reopen also passed; routing3/3 and full desktop564/564 now pass. Root's private-server/full-server/format/strict-Clippy/bins sequence is running with results pending. [STATE.md](STATE.md) owns current execution/evidence and leases. [PLAN.md](PLAN.md) owns the release plan; [DECISIONS.md](DECISIONS.md) preserves architectural rationale. Full pre-consolidation contents, including superseded requirements interpretations and evidence, remain [archived byte-for-byte](history/2026-09-06-ledgers-before-consolidation/TASK_LEDGER.md).
Current compiled checkpoint2cc4d11 includes external creation4bb4aaf as1516949,
isolated chooser13, and final baseline/library contracts. Local full676/format/
strict Clippy pass; native80cf197 now passes four OA creations, exact history and
reopen. Separate native SA Action/history also passes. Exact numeric foundation
is declared at7d14bd0 and passes26/26 unit tests plus strict core all-target Clippy.
Working workspace/production chooser changes remain outside compiled artifacts;
independent chooser source review closed three focus findings,14 new host tests
are prepared. Schema8 core implementation is isolated and uncompiled. External
results retain their host/source attribution.
## Goal and success criteria
The authoritative user objective is `C:\Users\User\.codex\attachments\10b0f701-1743-4de7-9ee1-225920e19649\goal-objective.md`. Deliver a usable, substantially complete OA/SA engineering tool in Rust/Iced on Windows and Linux; equivalent graphical, strict textual/reST and REST workflows; practical artifact traceability; navigable offline guidance; recoverable drafts; reproducible deployment. Completion requires native engineering task evidence and fresh independent end-state review, not implementation or passing tests alone. Later Arcadia layers remain future scope.
Deliver the usable, feature-complete OA/SA first release specified in
[PROJECT_GOAL.md](../PROJECT_GOAL.md). It is the exact copy of the user's revised
`a49d1780-25d5-4778-ad68-6140c60e4207/goal-objective.md`, SHA256
`DD58F75C93D55FE16ED141A23D834898FB6EBC625AE7E7AE379DA552A8312435`.
## Given facts and constraints
Success requires coherent explicit semantics, practical engineering workflows,
equivalent graphical/textual/REST behavior, real Windows/Linux runtime evidence,
recoverable authoring, relevant automated evaluators, precise documentation,
reproducible packages and fresh independent cross-disciplinary end-state review.
No known blocker or high-impact finding may remain unresolved. Later Arcadia
layers remain future scope. Code, a passing slice or an attractive screen alone
cannot establish completion.
- User prioritizes Capella domain fidelity, useful containment/nesting and explicit typed ports, while avoiding clutter, persistent action overload and awkward navigation. Study real domain workflows rather than mechanically copying Capella classes.
- Both-layer transitions and reviewed counterpart reconciliation must be intuitive and precise. Behavior/scenario diagrams must be directly editable and preserve selection/camera/task context.
- Human/AI/Git-friendly modular source, comments/includes, complete graphical/source/API parity and clear rejection are required. One validated model/history boundary must govern every representation.
- User permits autonomous reversible engineering, experiments, independent agents and authorized native work. Root is the sole native operator in this collaboration. Do not run concurrent shared Cargo writers. No remote push, usage reset, broad target deletion or host restart is implied by current task authorization.
- User permits isolated Linux work. WSL remains unavailable pending restart; earlier task-local QEMU core and server gates completed and shut down cleanly; the separate source7 core gate also completed and shut down cleanly, as recorded below. The server built and passed real HTTP/restart checks; its full test command timed out during compilation before any test executed. Historical external worktrees/toolchains are not present on this machine.
## Given facts
- Rust/Iced desktop and a deployable REST service serve system engineers. OA/SA
transitions in both directions must be understandable, explicit and useful.
- The revised goal explicitly requires constraints/calculations, quantities/units,
reusable model libraries, state/behavior modeling and strong standardized
specification/API, as well as textual/graphical notation and artifact traceability.
- Human/AI/Git-friendly source and a concrete unambiguous reST specification must
match graphical editing. The source editor needs highlighting/linting; help must
be offline, concise and navigable.
- The newest explicit goal requires uncluttered notation that reduces cognitive
load and supports development of complete small and large models using text alone.
- Direct behavior/scenario diagram authoring and reduced cognitive load are current
priorities. Long homogeneous selectors and bloated persistent creation controls
are rejected. Study actual Capella's useful domain workflows and nesting without
mechanically copying its interaction problems.
- The user authorizes autonomous bounded engineering, native Capella/Studio
evaluation and explicit independent delegation, exclusively with GPT-6 Astra
at effort appropriate to the question. Root owns synthesis/integration.
- Project instructions require Gitea coordination, ownership preservation and
durable handoffs. Current root reserves one Cargo/native operator per host.
Updated AGENTS4b8465c8 requires coordinated runnable milestone prereleases and
concise current shared maintenance with unique historical evidence preserved;
user Gitea#178 authorizes programmatic existing-MCP-credential reuse for relevant
Git/REST publication without printing/committing secrets. Restart and usage reset
remain unauthorized.
- Gitea issue2 explicitly requires actual Process/Scenario canvases with the same
interaction approach as architecture/state diagrams. Existing pointer edits
inside scrollable projections do not by themselves satisfy that requirement.
## Verified facts
- Latest superseding checkpoint: Fit6 and both existing scroll/branch regressions, full desktop570/570, workspace bins, format and strict workspace/all-target Clippy pass. Windows preview565-file ZIP and complete examples are verified; current server56/56 also passed. Native BCC1 OA/SA nested routing and unchanged-source oracles passed, followed by bounded DC50 packaged Fit overview. Earlier pending-build/routing claims below retain their historical scope and are superseded by these exact current results in STATE.md.
- The independent scenario checker compiled with warnings denied and passed its
self-check, deterministic fixture generation and complete baseline check on this
host. Its eight OA/SA checkpoints and exact UUID/source restoration comparisons
are evaluator evidence, not native Studio acceptance. Exact inputs/hashes are in
[the fixture instructions](fixtures/scenario-authoring/README.md).
- Branch/patch/tree audit established that direct state/scenario/process, data contracts, hosted editing and earlier semantic review are already integrated; no required production transplant was found. [Branch evidence](release-branch-integration-20260906.md).
- Capella's function input/output exchange endpoints and component Standard/Flow ports are distinct; explicit allocation connects them. Preserve that domain distinction. [Native benchmark](release-capella-workflow-benchmark.md).
- Source6 introduced participant CommunicationMean, typed explicit transition endpoint decisions, saved exchange categories/view selectors, completeness warnings and presentation duplication; current source7 retains them. Older audit absence claims are superseded; native acceptance remains scoped by reports.
- Semantic review includes independent scalar/constructor/keyed/order/Child/Incident/artifact facets and multiple source rows. One frozen accepted base, explicit mappings, unique merged candidate slots and one atomic command preserve raw excluded/rejected drafts. Recovery replans; it never restores an unchecked serialized command. [Batch design](release-semantic-batch-foundation-design.md), [artifact contract](release-semantic-artifacts.md).
- Native Windows artifact MOVE/CREATE/DELETE passed exact complete Save/Undo/Redo oracles, nine first-attempt saves. MOVE invalid raw optional state and CREATE exclusion/reserved identity survived controlled-stop recovery exactly. Destination-only retention is automated evidence, not separately native-applied in that run. [Native report](release-artifacts-native-20260906.md).
- Native batch, Child/Incident and source-5 checkpoint workflows have scoped exact source/recovery/history evidence. Dense views have persistence/duplicate/hide and bounded readability evidence. Current counts, binaries and remaining cases are in STATE.md; these are not universal usability claims.
- Native communication means drawing, explicit create/reuse ports and reverse Call/Reply pass independent complete model/source and exact Undo/Redo checks. The reverse navigation/overlapping-placement defect is fixed and reverified against a distinct oracle:10newUUIDs,zero implicit placements, correct Behavior owner and preserved Architecture. [Exact evidence](release-communication-native-20260906.md).
- Windows semantic108desktop+2core/full527desktop passes remain scoped. Subsequent guide/home and behavior navigation slices passed focused tests/strict Clippy/build; semantic navigation is also natively reverified. Fresh source7 core all-targets433passed/1ignored across44 summaries and server55/55 across4 summaries have recorded exit0. Full desktop561/561 passed263.39s after a real scroll-state regression was fixed with a stable navigation Column; the unchanged test passed. Strict workspace/all-target Clippy and root-observed final format exit0 pass;3 affected semantic tests passed after equivalent lint edits. Subsequent routing3/3 and full desktop564/564 pass; new standalone build and strict/server results remain pending. Logs and exact scope are in STATE.md; do not add affected reruns to full-suite totals.
- Native Scenario ordered review passed ambiguity rejection, explicit retained-local final order and complete Save/Undo/Redo source oracles at1100×700. Current guide binary passes related-topic heading reset, same-topic search scroll retention and Git auto-selected-topic reset without dirtying the model. Branch/fragment order variants and revised artifact diagnostic rendering remain separate gates. [Native ordered evidence](release-current-native-verification.md), [guide/diagnostic implementation](release-semantic-conflict-diagnostics-20260906.md).
- Windows user-local GNU/LLVM builds and isolated clean-PATH native launch work. Actual Ubuntu24.04.4/Rust1.90 core/journal tests pass on hashed snapshots. Actual Linux server build and real HTTP modular import/invalidPUT/cleanrestart exact source/model/ETag pass on the older28-source lesson snapshot. Its full server test command timed out during compilation with zero tests executed, then that gate shut down cleanly. The current frozen source7 gate compiled the server in17m10s and passed unit2/2 plus HTTP50/51; the sole504-vs-412 timing assertion failed again alone. Its final persisted-state checks were not reached. Native core436passed/0failed/2ignored and the VM shut down cleanly08:13:56UTC; full desktop/Linux package remain unverified. [Linux evidence](release-linux-validation-options.md).
- Corrected30-source/37-file teaching project passes minimum-size Home/guide/dirty-source guard, located initial warning, reviewed NameTake and complete exact source/Undo/Redo/reopen checks. The layer/canvas mismatch is corrected and natively reverified. Data/interface/type navigation, saved-view distinctions, invalid-view draft guard and typed state Entry fold/rename/history/reopen pass. The process workspace is cramped at minimum size and artifact navigation required excessive scrolling; targeted source7 UI improvements await native observation. [Native evidence](release-teaching-native-20260906.md).
- Scope reconciliation established caller-context links into repeated/nested reusable chains (**S1**) and maintained interface-operation selection for parameterless messages (**S2**) as real missing semantics. Their ratified source7 implementation now has fresh full core/server/desktop gates, OpenAPI72 fixtures and strict reST evidence. Old5/6 compatibility and current7 raw recovery tests pass. Root's native Reset and ReadStatus cases passed complete Save/Undo/Redo oracles and reopened with explicit derived allocation30/31. OA First.B persistence/history/reopen passed but rendering is open; old6 recovery passed full30-source/model JSON and exact raw workspace/Ports DTO comparison. Old5 complete raw/accepted recovery, exact repaired30-source save/full-model export pass. Current7 invalid nested draft crash recovery and completed link Save/Undo/Redo/reopen also pass; corrected rendering and remaining native7/Linux workflows remain open. [Native report](release-source7-native-acceptance-20260907.md). [Scope reconciliation](release-scope-reconciliation-20260906.md), [integration decision](release-source7-integration-decision-20260906.md).
- The historical native implementation is `80cf197` on `codex/behavior-authoring-20260910`, following
baseline `1797516`. Local commits cover B1/B2/B3 authoring, nullable history cache
(`b6b76ef`), external palette integration (`aed40d7`), cfg(test) lifecycle projection
(`eb5161b`), history seed correction (`4ecad78`) and exact-identity native oracle.
Later imports add focus recovery, exact packaging notices and scenario workspace/
owner restoration. Root80cf197 fixes document/scenario viewport Sensor identity
with a real mounted red-before/green-after regression.
- This fresh host has task-local Rust/Cargo 1.98.1 GNU/LLVM and verified LLVM-MinGW.
The integrated2cc4d11 desktop suite passes676/676, zero failed/ignored, with a
warning-free build; formatting and strict Clippy pass. History, pure lifecycle,
creation and isolated chooser are included. New working code still needs its
own gate. Native80cf197 evidence is separate. [Exact hashes/logs](STATE.md).
- Strict language HTML regeneration and the source7 OpenAPI checker passed locally:
72 fixtures, 204 schemas and 90 scalar leaves. Actual isolated Capella scenario,
activity/lifeline and LOOP creation was saved/inspected; this is reference study,
not Studio acceptance. [Native benchmark](release-capella-scenario-benchmark-20260910.md).
- Core/source7 already implements substantial direct behavior, typed data/ports,
contextual chain links, maintained message-operation identity, semantic reviews,
artifacts, hosted source envelopes and recovery. Historical absence claims must
be checked against code and newer scoped evidence, not copied forward.
- [Requirements audit](release-requirements-delta-20260910.md): Constraint and other
expression strings are descriptive, with no calculation/binding/result evaluator;
unit strings persist/inherit without dimensional compatibility or conversion;
named types/sequence/scenario reuse and includes exist, but there is no maintained
cross-project package/version/instance/update contract. These are explicit gaps.
- The same audit identifies concrete unbounded Constraint target choices and generic
expanded collection editors. Explorer already has hierarchy/search/paging; the
problem is targeted, not a claim that all selection is flat.
- Gitea #79's same-selected-ID/visible-owner defect is fixed in the imported
scenario checkpoint; owner restoration and pending-draft guards pass current
tests. B4 independent review #114 adds Scene integration requirements for actual
lifetime extents, branch-local activation clipping, incomplete lanes and self arrows.
- Codex-9e8r6t and Codex-ytr83r have independent host-local Cargo/native leases.
Named creation/workspace/palette/package integration is imported here.9e8r6t's
coherent CLI/evidence checkpoint01b76a1 awaits import; it owns staged-source and
the next runnable Windows prerelease. ytr83r owns production B4 and its native
oracle.9e8r6t successfully reused existing credentials for direct push; this
host is setting up the same authorized publication path.
- Current Linux acceptance is open; this host has no installed WSL distribution.
Historical Linux core/server/cross-build results have exact older snapshot scope.
The earlier denied guest workaround did not run and must not be bypassed.
## Decisions and candidate designs
## Assumptions
Retain three Rust crates, one typed Project and validated atomic Command. Keep semantic ownership, reference/allocation/order relationships and diagram placement separate. Forms remain a closed typed adapter, not a second metamodel. Persistent additions require model validation, references/deletion, transition, parser/updater, API/schema and reachable graphical editing parity.
- Compact contextual tools and an adequately sized scenario workspace can reduce
friction; only actual engineering tasks at minimum/wide sizes can validate this.
- The ratified bounded pure analysis and pinned-library architecture can satisfy
real engineering work without full language/runtime adoption. This remains a
product adequacy assumption until actual budgets, approximate calculations and
two-project/source/API/native workflows pass; metadata is insufficient.
- Existing shared core/source/history boundaries remain suitable for additions;
foundational examples and independent criticism must test that assumption.
Semantic reconciliation uses finite typed facets and separate member/presence/order decisions. Compare actual destination slots before constructing the core's complete candidate; two rows never become sequential Apply. Missing identities are not inferred by names. Raw constructor/numeric/keyed/optional drafts survive rejection, exclusion and checkpoint recovery. Artifact Presence means attachment to the reviewed owner; an identified source moved away can delete the destination, whereas a source key of None preserves destination-only membership. No invented tombstone or silent seed acknowledgment.
## Open questions
Source updates preserve lexical ownership/comments/includes and exact history. Checkpoint source5/6→7 upgrade admits only the established token/typed migration contract, validates old base fingerprints and resets transient approvals; it does not silently rebase authored drafts. Hosted saves remain explicit and conditional on the resource/ETag; credentials stay in memory.
- Do the ratified owned-value/shared-check/R6/R7 contracts meet real engineering
budgets once implemented, including approximate numeric requirements? What
measured ceilings keep work bounded without rejecting ordinary studies?
- Does actual package closure/canonical consumer typing/source preparation and
three-way update preserve every stable identity and local engineering edit?
- What migration and OA↔SA treatment follows from those contracts without guessing
executable meaning from old strings or silently changing old models?
- How can text-only creation establish library instance bases/maps, preserve
compatibility across cosmetic package revisions, export subjectless cases, and
transition mounted OA/SA data without hidden GUI normalization or silent forks?
- Will full evaluator and private-capture replay preserve effective-case and
deterministic work-limit behavior across direct, REST and cache-warm execution?
- Which source-preserving refactoring/navigation and grammar changes reduce actual
engineering effort while retaining stable identity and cross-file ownership?
- Do current real gestures, exact caller return, nested scopes and lifecycle markers
remain usable and correct under minimum sizing, scrolling, zoom and dirty drafts?
- Which uncovered teaching, traceability, transition, saved-view, state/data, hosted
and platform cases remain after current-binary acceptance? What supported Linux
environment can complete the remaining actual runtime gate?
- Does "standardized" require any external conformance beyond the project's precise
interoperable spec/API? Full OMG conformance is not inferred merely from comparison
to SysML v2; explicit claims require a mapped and verified contract.
For Linux journal publication, ordinary rename lost the empty-target ownership invariant in a real ext4 probe. Selected `renameat2(RENAME_NOREPLACE)` through existing locked libc with no fallback; syscall errors fail before model writes. Alternative overwrite fallback was rejected by that falsifier. Windows native no-replace/retry behavior is retained; other OS behavior is explicit. [Contract, alternatives and measured limits](release-linux-journal-publication.md).
## Candidate hypotheses / designs
Root selected **F1**, a complete source-6 teaching-project example. Corrected model/replay tests and bounded native onboarding/review/history pass; the full process/scenario/state/data/evidence lesson remains open. **F2**, faithful behavior-canvas SVG export, is deferred: current export scope is architecture-only, not a claim of faithful scenario/process/state export. Record this as an explicit scope decision rather than an accepted behavior-export result.
The [requirements delta](release-requirements-delta-20260910.md) compares metadata/
snippets, bounded pure engineering analysis with maintained pinned libraries,
external evaluators, and full standards adoption. Metadata alone fails the explicit
new semantics; external tools alone still need binding/result contracts. The report
recommends the bounded route for root synthesis, not as a ratified decision.
Behavior-root transition Apply should focus the explicitly requested counterpart and its nearest behavior owner. Without an explicit destination diagram it must preserve unrelated architecture presentation. Ordinary architecture transitions retain their existing path; explicit destination remains honored. This decision follows the independently reproduced reverse scenario placement/navigation failure, not a semantic change to the core transition.
Independent maximum-reasoning tracks now compare owned engineering properties
versus analysis contexts; calculation definitions/applications; numeric/unit rules;
and copy, linked-definition, live-instance or pinned-definition/editable-instance
library architectures. Require concrete falsifiers, source/API migration effects,
identity/history/recovery behavior and independent critique before convergence.
These alternatives converged after concrete experiments and independent review:
B property bases/shared checks/full capture, R6/R7, exact pins with same-origin
typed compatibility and explicit portable normalization are now ratified. Complete
11-file proposed baseline and120-assertion finite library prototype remain distinct
from production admission. Independent292-check review exposed C1 dynamic-work
expansion and a C2 prototype threshold-unit gap; implementation must close both.
The text-only40-identity fixture and13 mounted chooser tests pass. Production
numeric foundation and inspector/review chooser are active, with gates pending.
## Assumptions and open questions
The subsequent context experiment passed218 assertions: shared property baselines
and one-level overrides reduce repeated input maintenance while retaining explicit
independent freeze. Root selected that B direction for precise contract refinement;
quantity/library/source details remain open. [Decision](DECISIONS.md),
[experiment and limits](release-analysis-context-experiment-20260911.md).
- Nested source and contextual editors should reduce authoring effort; additional shorthand/grouping must justify grammar or interaction complexity through real tasks. Dense-view path overlap is not itself a failure when every actual identity remains accessible; arbitrary crossing-free layout is not promised.
- Remaining native variants must establish useful engineering workflows: CM transitions, advanced OA process/SA chain/scenario reuse/fragment/order, typed state actions, compact/Linux/hosted cases, and uncovered saved-view lifecycle combinations. Do not expand or shrink required OA/SA scope merely to fit implementation convenience.
- Latest diagnostic/reserved-label corrections have independent review and completed semantic/full-desktop/Clippy/build checks; their revised artifact rendering still needs native verification. The historical source6 process3012 closed cleanly. The6BAB source7 native build passed the scoped cases above;11060 and old6 recovery11240 closed cleanly. Old5 recovery/repair/save/model and current7 nested draft recovery/history/reopen pass on that binary. Later routing/hit-priority changes passed3focused/full564 desktop tests; root is running the server/format/strict/build sequence with results pending, and no corrected-render native acceptance is transferred. Exact binary scope is in STATE.md.
- Historical Linux evidence includes x86_64/glibc2.39/ext4 core/MSRV and server/HTTP runtime. Current455-file snapshot SHA256 `7104946c89b2be7a1a030fdff47cb4405bacf05357d68cf35d181e860f55c279` is frozen; core completed436passes/2ignored before clean VM shutdown08:13:56UTC; its original08:32:43UTC deadline was not reached. The hash-verified cross-built probe executed successfully on Linux, including its Windows macro/build-script build path, but no complete Linux GUI has been built. Syscall failure tests do not establish power-loss durability, network-filesystem behavior or cross-process model CAS. [Current Linux gate](release-source7-linux-gate-20260907.md).
- Earlier Windows QA packages include runtime/notices and verified archive contents; final accepted-tree optimized distributions and exact provenance/checksums remain a release gate. [Packaging evidence](release-windows-package-review.md).
## Decisions retained
- Keep explicit Rust crate responsibilities and one authoritative typed Project
with validated atomic Commands. A thin source CLI reuses the shared core. Separate semantic identity/ownership, allocation/reference/order and
diagram geometry. Forms are closed adapters, not a second metamodel. New persistent
semantics require core/source/UI/API/reference/transition parity. [Decisions](DECISIONS.md).
- Preserve authored source ownership/comments/includes, exact identity and accepted
model/source history. Source writeback must succeed before adoption. Raw invalid,
excluded or rejected drafts survive; navigation/tools must not implicitly accept
another editor. Recovery validates/replans rather than trusting serialized commands.
- Semantic reconciliation uses finite typed facets, frozen baselines, explicit
mappings, actual destination slots and a single atomic candidate. Do not infer
identity by name or apply reviewed rows as sequential independent edits.
[Foundation](release-semantic-batch-foundation-design.md),
[artifact contract](release-semantic-artifacts.md).
- Layer transitions are explicit engineering decisions, not automatic propagation.
Behavior-root navigation must establish the requested owner while preserving
unrelated architecture presentation. Ports/allocation and contextual occurrences
retain their distinct domain meaning. [Source7 contract](release-source7-integration-decision-20260906.md).
- Hosted revision/source envelopes and ETag checks remain atomic; credentials stay
out of persisted models and repository. Linux journal publication retains the
selected no-replace invariant, with measured limits, not an overwrite fallback.
[Journal decision](release-linux-journal-publication.md).
- Repair/evaluate the compact palette informed by native Capella evidence; do not
return to the rejected horizontal toolbar. Lifecycle projection remains isolated
under cfg(test) until coordinated Scene integration and actual acceptance.
- Preserve historical scope decisions as history. In particular, architecture-only
SVG is implemented and behavior SVG was deferred; that is not proof of satisfying
the revised release objective. Reassess older exclusions against current scope.
## Current strategy
The requested Windows preview and whole-run development summary are delivered; the summary is being refreshed with the confirmed package, full570/570 desktop result and final Fit/strict/build gates. Preview DC50 has bounded native launch/overview evidence, not complete minimum-height/pending-form acceptance. Computer Use stopped on user Escape, so leave live GUI processes untouched and advance independent verification.
Finish the new workspace/chooser compile and native loop; independently review
and measure the numeric foundation before expanding the ratified semantics.
Integrate coherent external CLI/staged-source/B4 checkpoints while preserving
ownership and source attribution. Use independent complete model/source oracles
and exact identity/history comparisons. Publish coordinated runnable milestone
prereleases; close actual analysis/library/source/API/native, cross-platform,
service/package and independent end-state gates before the final handoff.
Preserve the successful immutable458-file Linux GUI cross-build with the Fit fix, exact ELF/package evidence and released compiler lease. Three subsequent guest boots reached terminal IO-APIC timer panic before any tests; exact-kernel extraction succeeded but automatic approval review denied the proposed transient workaround. All task VMs are stopped. Preserve the denied action and evidence without bypassing review. Its snapshot/run/hashes and actual process status belong in STATE.md and the cross-build report. Preserve the original interrupted runs, cache, native core436/2ignored and failed Linux timed-server fixture. The replacement private HTTP preparation test and full server56 pass on Windows; Linux execution remains required.
Guide steps now name Tools/Selection details/Restore panels and the exact Reply label; formatting, independent label review and a fresh Windows workspace-binary build pass. The user-facing preview retains its original tested bytes. Independent full-model/source purpose oracles compiled and passed both self-checks and preserved baseline cases; complete their native authoring/history steps when control resumes. Complete current native OA/SA teaching, artifact, saved-view, process/scenario and hosted cases once control is available. Retain caller-specific budgets, actual port proof, independent channel validation and exact old5/6 recovery bytes. Final optimized packages, current platform gates and fresh independent end-state review remain open; architecture-only SVG and passing slices do not redefine completion.
The [archived Task Ledger](history/2026-09-10-ledgers-before-continuation-refresh/TASK_LEDGER.md)
and [archived STATE](history/2026-09-10-ledgers-before-continuation-refresh/STATE.md)
preserve all older claims, decisions and evidence links exactly. Relative report
links inside those byte-preserved files resolve from their original `harness/`
context. Their historical test totals and process holds are not live status.
+676
View File
@@ -0,0 +1,676 @@
//! Independent native creation oracle; no desktop producer is imported.
//! self-check BASE | check STAGE BASE ACTUAL ROLES | same EXPECTED ACTUAL [UNDO_FROM]
use oa_core::{source_project::*, *};
use std::{
collections::{BTreeMap, BTreeSet},
fs,
path::Path,
};
const PROCESS: &str = "Coordinate rescue";
const SCENARIO: &str = "Rescue coordination conversation";
const MACHINE: &str = "Rescue team operating modes";
const VIEW: &str = "Rescue team operating modes · states";
const CAPABILITY: u128 = 0xb451c00000004000800000000000001f;
const OWNER: u128 = 0xc062944912094b50afacf558a9a0fc7f;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Stage {
Baseline,
Process,
Scenario,
Machine,
}
impl Stage {
fn parse(value: &str) -> Self {
match value {
"baseline" => Self::Baseline,
"process" => Self::Process,
"scenario" => Self::Scenario,
"machine" => Self::Machine,
_ => panic!("Stage must be baseline, process, scenario or machine"),
}
}
fn additions(self) -> usize {
match self {
Self::Baseline => 0,
Self::Process => 1,
Self::Scenario => 2,
Self::Machine => 3,
}
}
}
type DiskSources = BTreeMap<String, Vec<u8>>;
fn source_paths(root: &Path, here: &Path, paths: &mut DiskSources) {
for entry in fs::read_dir(here).unwrap() {
let entry = entry.unwrap();
let kind = entry.file_type().unwrap();
assert!(
!kind.is_symlink(),
"Native checkpoint must contain ordinary files"
);
if kind.is_dir() {
source_paths(root, &entry.path(), paths);
} else if entry.path().extension().is_some_and(|ext| ext == "arcadia") {
assert!(kind.is_file());
paths.insert(
entry
.path()
.strip_prefix(root)
.unwrap()
.to_str()
.unwrap()
.replace('\\', "/"),
fs::read(entry.path()).unwrap(),
);
}
}
}
fn load_checkpoint(entry: &Path) -> (CompiledSourceProject, DiskSources) {
let files = source_files::load_project(entry, ProjectLimits::default()).unwrap();
let raw = files.reachable_bundle();
let compiled = compile_bundle(&raw, ProjectLimits::default()).unwrap();
assert_eq!(
compiled.bundle, raw,
"No migration, normalization or implicit identity insertion"
);
execute_batch(&compiled.decoded.project, &[]).unwrap();
let mut disk = BTreeMap::new();
let root = entry.parent().unwrap();
source_paths(root, root, &mut disk);
(compiled, disk)
}
fn predicted_disk(reachable: &SourceBundle, undo_from: Option<&DiskSources>) -> DiskSources {
// Saving Undo writes the restored reachable files and deliberately keeps
// detached files from the previously saved checkpoint. Never infer their
// bytes from the actual Undo directory: its explicit origin is the oracle.
let mut expected = undo_from.cloned().unwrap_or_default();
expected.extend(
reachable
.files
.iter()
.map(|(path, source)| (path.clone(), source.as_bytes().to_vec())),
);
expected
}
fn load(entry: &Path) -> CompiledSourceProject {
let (compiled, disk) = load_checkpoint(entry);
assert_eq!(
disk,
predicted_disk(&compiled.bundle, None),
"Ordinary checkpoints must contain exactly their reachable source files; retained Undo files require an explicit origin"
);
compiled
}
fn fnv1a(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf29ce484222325, |hash, byte| {
(hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3)
})
}
fn pinned_baseline(base: &CompiledSourceProject) -> bool {
// Fixed byte fingerprints of the root-preserved transition/reopen input,
// recorded before any creation. SHA-256 provenance is in the fixture README.
let pins = [
("project.arcadia", 4844, 0x450c6ffd8225af32),
("rationale.arcadia", 57, 0xf87e3c2e303f9b62),
("traceability.arcadia", 395, 0xb47992dbdacab344),
("oa/participants.arcadia", 403, 0x1e109eef81968b5f),
(
"oa/activities/activity_assess_incident.arcadia",
376,
0x0e67e533db3cff78,
),
("sa/participants.arcadia", 124, 0xcadb35025aea18cc),
];
base.bundle.entry == "project.arcadia"
&& base.bundle.files.len() == pins.len()
&& pins.iter().all(|(path, length, hash)| {
base.bundle
.files
.get(*path)
.is_some_and(|text| text.len() == *length && fnv1a(text.as_bytes()) == *hash)
})
}
fn baseline(entry: &Path) -> CompiledSourceProject {
let base = load(entry);
assert!(
pinned_baseline(&base),
"The six-file baseline differs from the frozen pre-creation input"
);
let p = &base.decoded.project;
assert_eq!(
(
p.elements.len(),
p.relations.len(),
p.diagrams.len(),
p.traces.len()
),
(10, 2, 4, 1)
);
let context = &p.elements[&Id::from_u128(CAPABILITY)];
assert_eq!(
(
context.name.as_str(),
context.kind(),
context.layer(),
context.parent
),
("Rescue capability", Kind::Capability, Layer::Oa, None)
);
let owner = &p.elements[&Id::from_u128(OWNER)];
assert_eq!(
(
owner.name.as_str(),
owner.kind(),
owner.layer(),
owner.parent
),
("Rescue team", Kind::SystemActor, Layer::Sa, None)
);
for name in [PROCESS, SCENARIO, MACHINE] {
assert!(
!p.elements.values().any(|e| e.name == name),
"Baseline already contains requested creation"
);
}
base
}
struct Roles<'a> {
actual: &'a Project,
baseline: &'a Project,
used: BTreeSet<Id>,
}
impl Roles<'_> {
fn fresh(&mut self, choices: Vec<Id>, role: &str) -> Id {
assert_eq!(
choices.len(),
1,
"Exactly one literal identity role required: {role}"
);
let id = choices[0];
assert_eq!(id.get_version_num(), 4, "{role} must be a fresh UUIDv4");
assert!(
!self.baseline.contains(id),
"{role} reuses a baseline identity"
);
assert!(self.used.insert(id), "{role} reuses another fresh role");
id
}
fn element(&mut self, kind: Kind, layer: Layer, name: &str) -> Id {
self.fresh(
self.actual
.elements
.values()
.filter(|e| e.kind() == kind && e.layer() == layer && e.name == name)
.map(|e| e.id)
.collect(),
name,
)
}
fn view(&mut self, machine: Id) -> Id {
self.fresh(
self.actual
.diagrams
.values()
.filter(|d| {
d.layer == Layer::Sa
&& d.name == VIEW
&& d.projection == ProjectionKind::StateMachine { machine }
})
.map(|d| d.id)
.collect(),
VIEW,
)
}
fn node(&mut self, diagram: Id, machine: Id) -> Id {
self.fresh(
self.actual.diagrams[&diagram]
.nodes
.values()
.filter(|node| node.element == machine)
.map(|node| node.id)
.collect(),
"new machine's exact view placement",
)
}
}
fn element(p: &Project, id: Id, name: &str, parent: Option<Id>, body: ElementBody) -> Element {
Element {
id,
alias: p.fresh_alias(name, "behavior", id),
name: name.into(),
description: String::new(),
parent,
body,
}
}
fn advance(base: &mut CompiledSourceProject, commands: Vec<Command>) {
let project = execute_batch(&base.decoded.project, &[Command::Batch(commands)]).unwrap();
*base = update_bundle(base, &project, ProjectLimits::default()).unwrap();
}
fn predict(base: &CompiledSourceProject, stage: Stage, carrier: &Project) -> CompiledSourceProject {
let mut result = base.clone();
let mut roles = Roles {
actual: carrier,
baseline: &base.decoded.project,
used: BTreeSet::new(),
};
if stage >= Stage::Process {
let id = roles.element(Kind::Process, Layer::Oa, PROCESS);
let record = element(
&result.decoded.project,
id,
PROCESS,
None,
ElementBody::Oa(OaBody::Process { steps: vec![] }),
);
advance(&mut result, vec![Command::CreateElement(record)]);
}
if stage >= Stage::Scenario {
let id = roles.element(Kind::Scenario, Layer::Oa, SCENARIO);
let record = element(
&result.decoded.project,
id,
SCENARIO,
None,
ElementBody::shared_in(
Layer::Oa,
SharedBody::Scenario {
viewpoint: ScenarioViewpoint::ParticipantInteraction,
context: Some(Id::from_u128(CAPABILITY)),
precondition: String::new(),
postcondition: String::new(),
steps: vec![],
},
),
);
advance(&mut result, vec![Command::CreateElement(record)]);
}
if stage == Stage::Machine {
let machine = roles.element(Kind::StateMachine, Layer::Sa, MACHINE);
let diagram = roles.view(machine);
let placement = roles.node(diagram, machine);
let record = element(
&result.decoded.project,
machine,
MACHINE,
Some(Id::from_u128(OWNER)),
ElementBody::shared_in(Layer::Sa, SharedBody::StateMachine),
);
let p = execute_batch(
&result.decoded.project,
&[Command::CreateElement(record.clone())],
)
.unwrap();
// Published first-view contract, independently constructed: one root,
// default options, no routes/regions/states. Shared core Layout owns the
// final geometry; no observed geometry or desktop planner is consulted.
let view = Diagram {
id: diagram,
alias: p.fresh_alias(VIEW, "state_view", diagram),
name: VIEW.into(),
description: String::new(),
layer: Layer::Sa,
projection: ProjectionKind::StateMachine { machine },
routes: vec![],
view_options: Default::default(),
nodes: BTreeMap::from([(
placement,
NodePlacement {
id: placement,
alias: p.fresh_alias(&format!("{MACHINE} placement"), "placement", placement),
element: machine,
position: Position { x: 60., y: 60. },
size: Size {
width: 336.,
height: 104.,
},
collapsed: false,
port_anchors: vec![],
},
)]),
};
advance(
&mut result,
vec![
Command::CreateElement(record),
Command::CreateDiagram(view),
Command::Layout(diagram),
],
);
}
let p = &result.decoded.project;
assert_eq!(
p.elements.len(),
base.decoded.project.elements.len() + stage.additions()
);
assert_eq!(
p.diagrams.len(),
base.decoded.project.diagrams.len() + usize::from(stage == Stage::Machine)
);
assert_eq!(p.relations, base.decoded.project.relations);
assert_eq!(p.traces, base.decoded.project.traces);
result
}
fn equal(left: &CompiledSourceProject, right: &CompiledSourceProject) -> bool {
left.decoded.project == right.decoded.project && left.bundle == right.bundle
}
fn assert_equal(expected: &CompiledSourceProject, actual: &CompiledSourceProject) {
assert_eq!(
actual.decoded.project, expected.decoded.project,
"Complete Project differs from independent prediction"
);
assert_eq!(
actual.bundle, expected.bundle,
"Complete SourceBundle differs, including comments and all included bytes"
);
}
fn test_id(n: u128) -> Id {
Id::from_u128(0xc4ea7100000040008000000000000000 + n)
}
fn false_carrier(base: &Project) -> Project {
let mut p = base.clone();
for (n, kind, layer, name) in [
(1, Kind::Process, Layer::Oa, PROCESS),
(2, Kind::Scenario, Layer::Oa, SCENARIO),
(3, Kind::StateMachine, Layer::Sa, MACHINE),
] {
p.elements.insert(
test_id(n),
Element {
id: test_id(n),
alias: format!("false_alias_{n}"),
name: name.into(),
description: "Must never be copied".into(),
parent: None,
body: ElementBody::new(kind, layer).unwrap(),
},
);
}
p.diagrams.insert(
test_id(4),
Diagram {
id: test_id(4),
alias: "false_view_alias".into(),
name: VIEW.into(),
description: "False view description".into(),
layer: Layer::Sa,
projection: ProjectionKind::StateMachine {
machine: test_id(3),
},
routes: vec![],
view_options: Default::default(),
nodes: BTreeMap::from([(
test_id(5),
NodePlacement {
id: test_id(5),
alias: "false_node_alias".into(),
element: test_id(3),
position: Position {
x: 9999.,
y: -9999.,
},
size: Size {
width: 1.,
height: 1.,
},
collapsed: true,
port_anchors: vec![],
},
)]),
},
);
p
}
fn self_check(base: &CompiledSourceProject) {
let original = base.clone();
let carrier = false_carrier(&base.decoded.project);
assert_equal(base, &predict(base, Stage::Baseline, &carrier));
for stage in [Stage::Process, Stage::Scenario, Stage::Machine] {
let expected = predict(base, stage, &carrier);
assert_equal(&expected, &predict(base, stage, &expected.decoded.project));
let parsed = compile_bundle(&expected.bundle, ProjectLimits::default()).unwrap();
assert_equal(&expected, &parsed);
let mut altered = expected.clone();
altered
.decoded
.project
.elements
.get_mut(&test_id(1))
.unwrap()
.description = "Unrequested metadata".into();
assert!(!equal(&expected, &altered));
let mut altered = expected.clone();
altered
.decoded
.project
.elements
.get_mut(&Id::from_u128(CAPABILITY))
.unwrap()
.name = "Changed unrelated baseline".into();
assert!(!equal(&expected, &altered));
let mut changed_source = expected.bundle.clone();
changed_source
.files
.get_mut("rationale.arcadia")
.unwrap()
.push_str("// Extra comment\n");
let altered = compile_bundle(&changed_source, ProjectLimits::default()).unwrap();
assert_eq!(altered.decoded.project, expected.decoded.project);
assert!(
!equal(&expected, &altered),
"Identical semantics do not excuse changed source bytes"
);
if stage >= Stage::Scenario {
let mut altered = expected.clone();
*altered
.decoded
.project
.elements
.get_mut(&test_id(2))
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Scenario {
viewpoint: ScenarioViewpoint::OperationalActivity,
context: None,
precondition: String::new(),
postcondition: String::new(),
steps: vec![],
};
assert!(!equal(&expected, &altered));
}
if stage == Stage::Machine {
assert_ne!(
expected.decoded.project, carrier,
"Never adopt role-carrier metadata/geometry"
);
assert_eq!(
expected.decoded.project.elements[&test_id(3)].parent,
Some(Id::from_u128(OWNER))
);
let view = &expected.decoded.project.diagrams[&test_id(4)];
assert_eq!(view.nodes.len(), 1);
let node = &view.nodes[&test_id(5)];
println!(
"PREDICT first view: {VIEW}; machine-root position {:?}, size {:?}; {} exact source files",
node.position,
node.size,
expected.bundle.files.len()
);
let mut altered = expected.clone();
altered
.decoded
.project
.diagrams
.get_mut(&test_id(4))
.unwrap()
.nodes
.get_mut(&test_id(5))
.unwrap()
.position
.x += 1.;
assert!(!equal(&expected, &altered));
let mut altered = expected.clone();
let extra = element(
&altered.decoded.project,
test_id(6),
"Unrequested region",
Some(test_id(3)),
ElementBody::shared_in(Layer::Sa, SharedBody::Region),
);
altered.decoded.project.elements.insert(extra.id, extra);
assert!(!equal(&expected, &altered), "Reject extra semantic objects");
let mut altered = expected.clone();
altered
.bundle
.files
.insert("unrequested.arcadia".into(), "// Extra file\n".into());
assert!(!equal(&expected, &altered));
}
println!(
"PASS self-check {stage:?}: full source fixed point; false metadata, unrelated edits and source-only drift rejected"
);
}
let mut altered_base = base.clone();
altered_base
.bundle
.files
.get_mut("rationale.arcadia")
.unwrap()
.push(' ');
assert!(
!pinned_baseline(&altered_base),
"Reject an altered baseline before use"
);
assert_equal(&original, base);
let before = predict(base, Stage::Scenario, &carrier);
let created = predict(base, Stage::Machine, &carrier);
let origin = predicted_disk(&created.bundle, None);
let detached: Vec<_> = created
.bundle
.files
.keys()
.filter(|path| !before.bundle.files.contains_key(*path))
.cloned()
.collect();
assert_eq!(
detached.len(),
1,
"A machine creation adds one source module"
);
// Independently simulate the saver's observable result: restored reachable
// bytes plus the one new module left on disk by the prior creation.
let mut retained = predicted_disk(&before.bundle, None);
retained.insert(
detached[0].clone(),
created.bundle.files[&detached[0]].as_bytes().to_vec(),
);
assert_eq!(
retained[&detached[0]], origin[&detached[0]],
"Retained bytes must come from the exact created checkpoint"
);
assert_ne!(
retained,
predicted_disk(&before.bundle, None),
"Ordinary comparison must not accept detached history files"
);
assert_eq!(
retained,
predicted_disk(&before.bundle, Some(&origin)),
"Explicit Undo origin permits only the expected retained bytes"
);
let mut unknown = retained.clone();
unknown.insert("unknown.arcadia".into(), b"// Unclaimed file\n".to_vec());
assert_ne!(
unknown,
predicted_disk(&before.bundle, Some(&origin)),
"Reject unknown detached files"
);
let mut changed = retained.clone();
changed.get_mut(&detached[0]).unwrap().push(b' ');
assert_ne!(
changed,
predicted_disk(&before.bundle, Some(&origin)),
"Reject changed detached bytes"
);
let mut missing = retained.clone();
missing.remove(&detached[0]);
assert_ne!(
missing,
predicted_disk(&before.bundle, Some(&origin)),
"The retained file set is exact, not optional"
);
let mut reachable_drift = retained.clone();
reachable_drift
.get_mut("rationale.arcadia")
.unwrap()
.push(b' ');
assert_ne!(
reachable_drift,
predicted_disk(&before.bundle, Some(&origin)),
"An Undo exemption cannot hide reachable-source changes"
);
println!(
"PASS explicit Undo disk contract: known detached retention accepted; unknown, changed, missing and reachable drift rejected"
);
println!("PASS baseline retained unchanged; no native acceptance claimed");
}
fn main() {
assert_eq!(SCHEMA_VERSION, 7);
let args: Vec<_> = std::env::args().collect();
match args.get(1).map(String::as_str) {
Some("self-check") => {
assert_eq!(args.len(), 3, "self-check BASELINE_ENTRY");
self_check(&baseline(Path::new(&args[2])));
}
Some("check") => {
assert_eq!(
args.len(),
6,
"check baseline|process|scenario|machine BASELINE_ENTRY ACTUAL_ENTRY ROLE_ENTRY"
);
let stage = Stage::parse(&args[2]);
let base = baseline(Path::new(&args[3]));
let actual = load(Path::new(&args[4]));
let carrier = load(Path::new(&args[5]));
let expected = predict(&base, stage, &carrier.decoded.project);
assert_equal(&expected, &actual);
println!(
"PASS {stage:?}: complete Project + {} exact source files; only fresh literal-role UUIDs borrowed",
actual.bundle.files.len()
);
}
Some("same") => {
assert!(
matches!(args.len(), 4 | 5),
"same EXPECTED_CHECKPOINT ACTUAL_CHECKPOINT [UNDO_FROM_CHECKPOINT]"
);
let expected = load(Path::new(&args[2]));
let (actual, disk) = load_checkpoint(Path::new(&args[3]));
assert_equal(&expected, &actual);
let origin = args.get(4).map(|entry| {
// The first committed checkpoint is itself exact. This keeps
// arbitrary pre-existing detached files out of the exception.
let committed = load(Path::new(entry));
predicted_disk(&committed.bundle, None)
});
assert_eq!(
disk,
predicted_disk(&expected.bundle, origin.as_ref()),
"Disk source files differ from the exact checkpoint plus explicitly proven retained Undo files"
);
println!(
"PASS exact checkpoint identity/model/{}-file SourceBundle equality; {} exact disk files ({} known retained)",
actual.bundle.files.len(),
disk.len(),
disk.len() - actual.bundle.files.len()
);
}
_ => panic!(
"self-check BASE | check STAGE BASE ACTUAL ROLES | same EXPECTED ACTUAL [UNDO_FROM]"
),
}
}
@@ -0,0 +1,15 @@
# Baseline contract fixtures
Companion to [the candidate contract](../../release-analysis-baseline-contract-20260911.md). This is proposed schema/source/JSON, not implemented Studio syntax.
- active.arcadia.proposed is a complete UUID-bearing local model with four base bindings, two cases and one shared check.
- evaluate-*.json are complete candidate REST request bodies.
- portable-document.json.proposed exposes the complete candidate Project, exact source, local definitions and explicitly empty library collections.
- freeze-degraded.json.proposed retains those exact document bytes, a SHA256 commitment, complete effective bindings/checks, and private definition inventory.
- expected-observations.json records hand-derived arithmetic/context expectations, not evaluator output.
- r7-literal-boundaries.json contains full exact JSON literal nodes and their expected canonical source, including 301-digit and 4096-bit boundaries.
- fixture-integrity.json records only transport/source/UUID checks and size counts.
Run build-fixtures.ps1 with PowerShell 7 to regenerate the JSON fixtures. It writes only within this directory. The script constructs the proposed typed data; it does not parse source, evaluate expressions, run Rust, or establish Project/source semantic equality. Changing the fixture file's exact line endings changes the captured document and digest; preserve these snapshot bytes when publishing.
The full local capture has no imports, so empty pins/package content are complete for this example. Nonempty pinned-package capture and offline replay remain a required paired library/evaluator acceptance test, not something this local transport fixture has proved.
@@ -0,0 +1,55 @@
arcadia 8;
project response_budget "Response budget" id "4210b9f2-7046-47f0-aa3b-153f626a579d" {
description "A complete proposed analysis model. Schema 8 and the new declarations are not implemented source7 syntax.";
quantity_kind duration "Duration" id "188b911c-5f8b-431c-9eea-2d41f3953767" {
dimension { time: 1; }
algebra Linear;
}
unit second "Second" id "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce" {
kind @duration; scale 1; offset 0; symbol "s";
}
unit millisecond "Millisecond" id "39053f37-fec9-4708-9f0a-3959d223f891" {
kind @duration; scale ratio(1, 1000); offset 0; symbol "ms";
}
calculation combine "Combine durations" id "fd7ce7ab-f789-40bc-b699-0c37f1b6902f" {
input a id "28ff40b0-1b8f-4735-8536-5a6ab21b56cb" : Quantity(@duration);
input b id "7a47cc1e-8ae5-4551-b2d8-8a68108e0976" : Quantity(@duration);
result Quantity(@duration);
body $a + $b;
}
oa_activity respond "Respond" id "cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59" {
oa_activity receive "Receive" id "4ab9a8a7-7552-488d-9862-e14b89e7b353" {}
oa_activity dispatch "Dispatch" id "6df991ba-4c5e-4535-99e2-524ae274ee8b" {}
}
oa_property receive_time "Receive time" id "63a931c2-675a-4fce-89e5-04361cb99450" {
subject @receive; type Quantity(@duration); display_unit @millisecond;
base 750 [@millisecond];
}
oa_property dispatch_time "Dispatch time" id "c33fc772-2a60-4044-9af9-73c61c563ace" {
subject @dispatch; type Quantity(@duration); display_unit @second;
base 1 [@second];
}
oa_property total_time "Total time" id "bd5b68e8-65fc-4e35-9071-a73061316a4b" {
subject @respond; type Quantity(@duration); display_unit @second;
// The formula is shared. Every read uses the requested evaluation context.
base @combine(a: @receive_time, b: @dispatch_time);
}
oa_property limit "Allowed duration" id "437bedbb-2cf4-44ee-a139-6563cc5086ec" {
subject @respond; type Quantity(@duration); display_unit @second;
base 2 [@second];
}
oa_check budget "Response budget" id "bac0de99-9d2f-4e53-9158-d424ecac61bf" {
subject none; documented_constraint none;
predicate @total_time <= @limit;
}
oa_analysis degraded "Degraded radio" id "38036c65-16d4-449c-837b-91eb141c1d93" {
subject none; base ModelBaseline;
overrides { @receive_time = 1250 [@millisecond]; }
}
oa_analysis unmeasured "Unmeasured radio" id "99d3e09a-0ec3-4194-9dd4-9f3de6625cde" {
subject none; base ModelBaseline;
overrides { @receive_time = unbound; }
}
}
@@ -0,0 +1,216 @@
# Fixture construction only. This does not parse/evaluate the proposed language.
$ErrorActionPreference = 'Stop'
$taskDir = $PSScriptRoot
$ids = @{
project = '4210b9f2-7046-47f0-aa3b-153f626a579d'
duration = '188b911c-5f8b-431c-9eea-2d41f3953767'
second = '534f4672-1ba5-4157-8b0a-b9cf41d0a3ce'
millisecond = '39053f37-fec9-4708-9f0a-3959d223f891'
combine = 'fd7ce7ab-f789-40bc-b699-0c37f1b6902f'
input_a = '28ff40b0-1b8f-4735-8536-5a6ab21b56cb'
input_b = '7a47cc1e-8ae5-4551-b2d8-8a68108e0976'
respond = 'cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59'
receive = '4ab9a8a7-7552-488d-9862-e14b89e7b353'
dispatch = '6df991ba-4c5e-4535-99e2-524ae274ee8b'
receive_time = '63a931c2-675a-4fce-89e5-04361cb99450'
dispatch_time = 'c33fc772-2a60-4044-9af9-73c61c563ace'
total_time = 'bd5b68e8-65fc-4e35-9071-a73061316a4b'
limit = '437bedbb-2cf4-44ee-a139-6563cc5086ec'
degraded = '38036c65-16d4-449c-837b-91eb141c1d93'
unmeasured = '99d3e09a-0ec3-4194-9dd4-9f3de6625cde'
budget = 'bac0de99-9d2f-4e53-9158-d424ecac61bf'
}
function Exact([string]$n, [string]$d = '1') {
return @{ numerator = $n; denominator = $d }
}
function Local([string]$name) { return @{ Local = $ids[$name] } }
function ReadProperty([string]$name) { return @{ Property = $ids[$name] } }
function Literal([string]$n, [string]$unit) {
return @{ Quantity = @{ magnitude = (Exact $n); unit = (Local $unit) } }
}
function Bound($expr) { return @{ Expression = $expr } }
function Record([string]$key, [string]$name, $body) {
return @{
id = $ids[$key]; alias = $key; name = $name; description = ''; body = $body
}
}
function Element([string]$key, [string]$name, $body, $parent = $null) {
$r = Record $key $name $body
$r.parent = $parent
return $r
}
function Property([string]$key, [string]$name, [string]$subject, [string]$unit, $binding) {
return Element $key $name @{ Oa = @{ Shared = @{ EngineeringProperty = @{
subject = @{ Element = $ids[$subject] }
value_type = $quantityType
display_unit = (Local $unit)
base = $binding
} } } }
}
function OrderedCopy($value) {
if ($null -eq $value) { return $null }
if ($value -is [Collections.IDictionary]) {
$copy = [ordered]@{}
[string[]]$keys = @($value.Keys)
[Array]::Sort($keys, [StringComparer]::Ordinal)
foreach ($key in $keys) { $copy[$key] = OrderedCopy $value[$key] }
return $copy
}
if ($value -is [Collections.IEnumerable] -and $value -isnot [string]) {
$copy = @()
foreach ($item in $value) { $copy += ,(OrderedCopy $item) }
return ,$copy
}
return $value
}
function JsonBytes($value) {
$json = (OrderedCopy $value) | ConvertTo-Json -Depth 100
$json = $json.Replace([string][char]13 + [string][char]10, [string][char]10)
return [Text.UTF8Encoding]::new($false).GetBytes($json + [string][char]10)
}
function SaveBytes([string]$name, [byte[]]$bytes) {
[IO.File]::WriteAllBytes((Join-Path $taskDir $name), $bytes)
}
$quantityType = @{ Scalar = @{ Quantity = (Local 'duration') } }
$definitions = @{}
$definitions[$ids.duration] = Record 'duration' 'Duration' @{ QuantityKind = @{
dimension = @(0, 0, 1, 0, 0, 0, 0); algebra = 'Linear'
} }
$definitions[$ids.second] = Record 'second' 'Second' @{ Unit = @{
kind = (Local 'duration'); scale = (Exact '1'); offset = (Exact '0'); symbol = 's'
} }
$definitions[$ids.millisecond] = Record 'millisecond' 'Millisecond' @{ Unit = @{
kind = (Local 'duration'); scale = (Exact '1' '1000'); offset = (Exact '0'); symbol = 'ms'
} }
$definitions[$ids.combine] = Record 'combine' 'Combine durations' @{ Calculation = @{
parameters = @(
@{ id = $ids.input_a; name = 'a'; value_type = $quantityType },
@{ id = $ids.input_b; name = 'b'; value_type = $quantityType }
)
result = $quantityType
body = (Bound @{ Binary = @{
op = 'Add'; left = @{ Parameter = $ids.input_a }; right = @{ Parameter = $ids.input_b }
} })
} }
$receiveBase = Bound (Literal '750' 'millisecond')
$dispatchBase = Bound (Literal '1' 'second')
$totalBase = Bound @{ Call = @{
definition = (Local 'combine')
arguments = @{
$ids.input_a = (ReadProperty 'receive_time')
$ids.input_b = (ReadProperty 'dispatch_time')
}
} }
$limitBase = Bound (Literal '2' 'second')
$degradedBinding = Bound (Literal '1250' 'millisecond')
$predicate = Bound @{ Binary = @{
op = 'LessOrEqual'; left = (ReadProperty 'total_time'); right = (ReadProperty 'limit')
} }
$elements = @{}
$elements[$ids.respond] = Element 'respond' 'Respond' @{ Oa = 'Activity' }
$elements[$ids.receive] = Element 'receive' 'Receive' @{ Oa = 'Activity' } $ids.respond
$elements[$ids.dispatch] = Element 'dispatch' 'Dispatch' @{ Oa = 'Activity' } $ids.respond
$elements[$ids.receive_time] = Property 'receive_time' 'Receive time' 'receive' 'millisecond' $receiveBase
$elements[$ids.dispatch_time] = Property 'dispatch_time' 'Dispatch time' 'dispatch' 'second' $dispatchBase
$elements[$ids.total_time] = Property 'total_time' 'Total time' 'respond' 'second' $totalBase
$elements[$ids.limit] = Property 'limit' 'Allowed duration' 'respond' 'second' $limitBase
$elements[$ids.budget] = Element 'budget' 'Response budget' @{ Oa = @{ Shared = @{ AnalysisCheck = @{
subject = $null; documented_constraint = $null; predicate = $predicate
} } } }
$elements[$ids.degraded] = Element 'degraded' 'Degraded radio' @{ Oa = @{ Shared = @{ AnalysisCase = @{
subject = $null; base = 'ModelBaseline'; overrides = @{ $ids.receive_time = $degradedBinding }
} } } }
$elements[$ids.unmeasured] = Element 'unmeasured' 'Unmeasured radio' @{ Oa = @{ Shared = @{ AnalysisCase = @{
subject = $null; base = 'ModelBaseline'; overrides = @{ $ids.receive_time = 'Unbound' }
} } } }
$sourceBytes = [IO.File]::ReadAllBytes((Join-Path $taskDir 'active.arcadia.proposed'))
$source = [Text.UTF8Encoding]::new($false, $true).GetString($sourceBytes)
$project = @{
schema_version = 8; id = $ids.project; alias = 'response_budget'; name = 'Response budget'
description = 'A complete proposed analysis model. Schema 8 and the new declarations are not implemented source7 syntax.'
elements = $elements; relations = @{}; diagrams = @{}; artifact_links = @{}; traces = @{}
definitions = $definitions; imports = @{}; definition_mounts = @{}; library_instances = @{}
}
$document = @{
model = $project
source = @{ entry = 'active.arcadia'; files = @{ 'active.arcadia' = $source } }
packages = @{}
}
[byte[]]$documentBytes = JsonBytes $document
SaveBytes 'portable-document.json.proposed' $documentBytes
$documentDigest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($documentBytes)).ToLowerInvariant()
$manifest = @(
@{ property = $ids.receive_time; binding = $degradedBinding; origin = @{ CaseOverride = $ids.degraded } },
@{ property = $ids.dispatch_time; binding = $dispatchBase; origin = 'ModelBaseline' },
@{ property = $ids.total_time; binding = $totalBase; origin = 'ModelBaseline' },
@{ property = $ids.limit; binding = $limitBase; origin = 'ModelBaseline' }
) | Sort-Object { $_.property }
$freeze = @{
format = 'arcadia-analysis-freeze-1-proposal'
captured_document = @{
media_type = 'application/vnd.arcadia.portable-document+json'
sha256 = $documentDigest
bytes_base64 = [Convert]::ToBase64String($documentBytes)
}
origin = @{ Local = @{
document_instance = 'd911a3c0-8adb-4203-850c-b16e9b4e4d0a'; accepted_revision = 1
} }
model_id = $ids.project
context = @{ Case = $ids.degraded }
targets = @{ properties = @($ids.total_time); checks = @($ids.budget) }
numeric_profile = 'Q1-exact-1'
effective_bindings = @($manifest)
check_predicates = @(@{ check = $ids.budget; predicate = $predicate })
definition_capture = @{
document_sha256 = $documentDigest
local_definitions = @($ids.duration, $ids.second, $ids.millisecond, $ids.combine | Sort-Object)
imports = @()
}
}
SaveBytes 'freeze-degraded.json.proposed' (JsonBytes $freeze)
$expected = @{
status = 'Hand-derived expectations, not evaluator output'
baseline = @{ total_canonical_seconds = (Exact '7' '4'); check = 'Satisfied' }
degraded = @{ total_canonical_seconds = (Exact '9' '4'); check = 'Violated' }
unmeasured = @{ total = 'Missing'; input = $ids.receive_time; check = 'Unresolved' }
after_clear_unmeasured_override = @{ total_canonical_seconds = (Exact '7' '4'); check = 'Satisfied' }
after_baseline_dispatch_changes_to_two_seconds = @{
active_degraded_total = (Exact '13' '4'); frozen_degraded_total = (Exact '9' '4')
}
}
SaveBytes 'expected-observations.json' (JsonBytes $expected)
$largeInteger = [Numerics.BigInteger]::Pow([Numerics.BigInteger]10, 300).ToString()
$smallDenominator = [Numerics.BigInteger]::Pow([Numerics.BigInteger]2, 4095).ToString()
$boundInteger = ([Numerics.BigInteger]::Pow([Numerics.BigInteger]2, 4096) - 1).ToString()
$literalFixtures = @(
@{ name = 'ten_to_300'; expression = @{ Number = (Exact $largeInteger) }; canonical_source = $largeInteger },
@{ name = 'one_over_two_to_4095'; expression = @{ Number = (Exact '1' $smallDenominator) }; canonical_source = ('ratio(1, ' + $smallDenominator + ')') },
@{ name = 'negative_4096_bit_bound'; expression = @{ Number = (Exact ('-' + $boundInteger)) }; canonical_source = ('ratio(-' + $boundInteger + ', 1)') }
)
SaveBytes 'r7-literal-boundaries.json' (JsonBytes $literalFixtures)
# Verify only JSON transport, UUID completeness, raw source retention and hashes.
$parsed = Get-Content -LiteralPath (Join-Path $taskDir 'freeze-degraded.json.proposed') -Raw | ConvertFrom-Json
$decoded = [Convert]::FromBase64String($parsed.captured_document.bytes_base64)
if ([Convert]::ToBase64String($decoded) -cne [Convert]::ToBase64String($documentBytes)) { throw 'Document capsule differs' }
$parsedDoc = [Text.Encoding]::UTF8.GetString($decoded) | ConvertFrom-Json
if ($parsedDoc.source.files.'active.arcadia' -cne $source) { throw 'Source changed' }
if ($ids.Count -ne (@($ids.Values | Sort-Object -Unique)).Count) { throw 'Duplicate fixture UUID' }
foreach ($value in $ids.Values) {
[void][guid]::ParseExact($value, 'D')
if (-not $source.Contains('id "' + $value + '"')) { throw "Missing source identity $value" }
}
$stats = @{
source_lines = ($source -split [string][char]10).Count - 1
source_utf8_bytes = $sourceBytes.Length
explicit_source_uuids = $ids.Count
project_elements = $elements.Count
local_definitions = $definitions.Count
scoped_parameters = 2
base_bindings = 4
override_bindings = 2
shared_checks = 1
portable_document_sha256 = $documentDigest
verified = 'JSON transport, 17 syntactically valid distinct UUIDs, exact source bytes, capsule equality. No proposed parser/evaluator execution.'
}
SaveBytes 'fixture-integrity.json' (JsonBytes $stats)
$stats | ConvertTo-Json
@@ -0,0 +1,8 @@
{
"context": "ModelBaseline",
"targets": {
"properties": ["bd5b68e8-65fc-4e35-9071-a73061316a4b"],
"checks": ["bac0de99-9d2f-4e53-9158-d424ecac61bf"]
},
"numeric_profile": "Q1-exact-1"
}
@@ -0,0 +1,8 @@
{
"context": {"Case": "38036c65-16d4-449c-837b-91eb141c1d93"},
"targets": {
"properties": ["bd5b68e8-65fc-4e35-9071-a73061316a4b"],
"checks": ["bac0de99-9d2f-4e53-9158-d424ecac61bf"]
},
"numeric_profile": "Q1-exact-1"
}
@@ -0,0 +1,8 @@
{
"context": {"Case": "99d3e09a-0ec3-4194-9dd4-9f3de6625cde"},
"targets": {
"properties": ["bd5b68e8-65fc-4e35-9071-a73061316a4b"],
"checks": ["bac0de99-9d2f-4e53-9158-d424ecac61bf"]
},
"numeric_profile": "Q1-exact-1"
}
@@ -0,0 +1,39 @@
{
"after_baseline_dispatch_changes_to_two_seconds": {
"active_degraded_total": {
"denominator": "4",
"numerator": "13"
},
"frozen_degraded_total": {
"denominator": "4",
"numerator": "9"
}
},
"after_clear_unmeasured_override": {
"check": "Satisfied",
"total_canonical_seconds": {
"denominator": "4",
"numerator": "7"
}
},
"baseline": {
"check": "Satisfied",
"total_canonical_seconds": {
"denominator": "4",
"numerator": "7"
}
},
"degraded": {
"check": "Violated",
"total_canonical_seconds": {
"denominator": "4",
"numerator": "9"
}
},
"status": "Hand-derived expectations, not evaluator output",
"unmeasured": {
"check": "Unresolved",
"input": "63a931c2-675a-4fce-89e5-04361cb99450",
"total": "Missing"
}
}
@@ -0,0 +1,13 @@
{
"base_bindings": 4,
"explicit_source_uuids": 17,
"local_definitions": 4,
"override_bindings": 2,
"portable_document_sha256": "6667773d90f83626f760b2faa2bf7d57638947d95574e3fa3e80b64416f01497",
"project_elements": 10,
"scoped_parameters": 2,
"shared_checks": 1,
"source_lines": 55,
"source_utf8_bytes": 2678,
"verified": "JSON transport, 17 syntactically valid distinct UUIDs, exact source bytes, capsule equality. No proposed parser/evaluator execution."
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,425 @@
{
"model": {
"alias": "response_budget",
"artifact_links": {},
"definition_mounts": {},
"definitions": {
"188b911c-5f8b-431c-9eea-2d41f3953767": {
"alias": "duration",
"body": {
"QuantityKind": {
"algebra": "Linear",
"dimension": [
0,
0,
1,
0,
0,
0,
0
]
}
},
"description": "",
"id": "188b911c-5f8b-431c-9eea-2d41f3953767",
"name": "Duration"
},
"39053f37-fec9-4708-9f0a-3959d223f891": {
"alias": "millisecond",
"body": {
"Unit": {
"kind": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
},
"offset": {
"denominator": "1",
"numerator": "0"
},
"scale": {
"denominator": "1000",
"numerator": "1"
},
"symbol": "ms"
}
},
"description": "",
"id": "39053f37-fec9-4708-9f0a-3959d223f891",
"name": "Millisecond"
},
"534f4672-1ba5-4157-8b0a-b9cf41d0a3ce": {
"alias": "second",
"body": {
"Unit": {
"kind": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
},
"offset": {
"denominator": "1",
"numerator": "0"
},
"scale": {
"denominator": "1",
"numerator": "1"
},
"symbol": "s"
}
},
"description": "",
"id": "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce",
"name": "Second"
},
"fd7ce7ab-f789-40bc-b699-0c37f1b6902f": {
"alias": "combine",
"body": {
"Calculation": {
"body": {
"Expression": {
"Binary": {
"left": {
"Parameter": "28ff40b0-1b8f-4735-8536-5a6ab21b56cb"
},
"op": "Add",
"right": {
"Parameter": "7a47cc1e-8ae5-4551-b2d8-8a68108e0976"
}
}
}
},
"parameters": [
{
"id": "28ff40b0-1b8f-4735-8536-5a6ab21b56cb",
"name": "a",
"value_type": {
"Scalar": {
"Quantity": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
}
}
}
},
{
"id": "7a47cc1e-8ae5-4551-b2d8-8a68108e0976",
"name": "b",
"value_type": {
"Scalar": {
"Quantity": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
}
}
}
}
],
"result": {
"Scalar": {
"Quantity": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
}
}
}
}
},
"description": "",
"id": "fd7ce7ab-f789-40bc-b699-0c37f1b6902f",
"name": "Combine durations"
}
},
"description": "A complete proposed analysis model. Schema 8 and the new declarations are not implemented source7 syntax.",
"diagrams": {},
"elements": {
"38036c65-16d4-449c-837b-91eb141c1d93": {
"alias": "degraded",
"body": {
"Oa": {
"Shared": {
"AnalysisCase": {
"base": "ModelBaseline",
"overrides": {
"63a931c2-675a-4fce-89e5-04361cb99450": {
"Expression": {
"Quantity": {
"magnitude": {
"denominator": "1",
"numerator": "1250"
},
"unit": {
"Local": "39053f37-fec9-4708-9f0a-3959d223f891"
}
}
}
}
},
"subject": null
}
}
}
},
"description": "",
"id": "38036c65-16d4-449c-837b-91eb141c1d93",
"name": "Degraded radio",
"parent": null
},
"437bedbb-2cf4-44ee-a139-6563cc5086ec": {
"alias": "limit",
"body": {
"Oa": {
"Shared": {
"EngineeringProperty": {
"base": {
"Expression": {
"Quantity": {
"magnitude": {
"denominator": "1",
"numerator": "2"
},
"unit": {
"Local": "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce"
}
}
}
},
"display_unit": {
"Local": "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce"
},
"subject": {
"Element": "cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59"
},
"value_type": {
"Scalar": {
"Quantity": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
}
}
}
}
}
}
},
"description": "",
"id": "437bedbb-2cf4-44ee-a139-6563cc5086ec",
"name": "Allowed duration",
"parent": null
},
"4ab9a8a7-7552-488d-9862-e14b89e7b353": {
"alias": "receive",
"body": {
"Oa": "Activity"
},
"description": "",
"id": "4ab9a8a7-7552-488d-9862-e14b89e7b353",
"name": "Receive",
"parent": "cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59"
},
"63a931c2-675a-4fce-89e5-04361cb99450": {
"alias": "receive_time",
"body": {
"Oa": {
"Shared": {
"EngineeringProperty": {
"base": {
"Expression": {
"Quantity": {
"magnitude": {
"denominator": "1",
"numerator": "750"
},
"unit": {
"Local": "39053f37-fec9-4708-9f0a-3959d223f891"
}
}
}
},
"display_unit": {
"Local": "39053f37-fec9-4708-9f0a-3959d223f891"
},
"subject": {
"Element": "4ab9a8a7-7552-488d-9862-e14b89e7b353"
},
"value_type": {
"Scalar": {
"Quantity": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
}
}
}
}
}
}
},
"description": "",
"id": "63a931c2-675a-4fce-89e5-04361cb99450",
"name": "Receive time",
"parent": null
},
"6df991ba-4c5e-4535-99e2-524ae274ee8b": {
"alias": "dispatch",
"body": {
"Oa": "Activity"
},
"description": "",
"id": "6df991ba-4c5e-4535-99e2-524ae274ee8b",
"name": "Dispatch",
"parent": "cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59"
},
"99d3e09a-0ec3-4194-9dd4-9f3de6625cde": {
"alias": "unmeasured",
"body": {
"Oa": {
"Shared": {
"AnalysisCase": {
"base": "ModelBaseline",
"overrides": {
"63a931c2-675a-4fce-89e5-04361cb99450": "Unbound"
},
"subject": null
}
}
}
},
"description": "",
"id": "99d3e09a-0ec3-4194-9dd4-9f3de6625cde",
"name": "Unmeasured radio",
"parent": null
},
"bac0de99-9d2f-4e53-9158-d424ecac61bf": {
"alias": "budget",
"body": {
"Oa": {
"Shared": {
"AnalysisCheck": {
"documented_constraint": null,
"predicate": {
"Expression": {
"Binary": {
"left": {
"Property": "bd5b68e8-65fc-4e35-9071-a73061316a4b"
},
"op": "LessOrEqual",
"right": {
"Property": "437bedbb-2cf4-44ee-a139-6563cc5086ec"
}
}
}
},
"subject": null
}
}
}
},
"description": "",
"id": "bac0de99-9d2f-4e53-9158-d424ecac61bf",
"name": "Response budget",
"parent": null
},
"bd5b68e8-65fc-4e35-9071-a73061316a4b": {
"alias": "total_time",
"body": {
"Oa": {
"Shared": {
"EngineeringProperty": {
"base": {
"Expression": {
"Call": {
"arguments": {
"28ff40b0-1b8f-4735-8536-5a6ab21b56cb": {
"Property": "63a931c2-675a-4fce-89e5-04361cb99450"
},
"7a47cc1e-8ae5-4551-b2d8-8a68108e0976": {
"Property": "c33fc772-2a60-4044-9af9-73c61c563ace"
}
},
"definition": {
"Local": "fd7ce7ab-f789-40bc-b699-0c37f1b6902f"
}
}
}
},
"display_unit": {
"Local": "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce"
},
"subject": {
"Element": "cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59"
},
"value_type": {
"Scalar": {
"Quantity": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
}
}
}
}
}
}
},
"description": "",
"id": "bd5b68e8-65fc-4e35-9071-a73061316a4b",
"name": "Total time",
"parent": null
},
"c33fc772-2a60-4044-9af9-73c61c563ace": {
"alias": "dispatch_time",
"body": {
"Oa": {
"Shared": {
"EngineeringProperty": {
"base": {
"Expression": {
"Quantity": {
"magnitude": {
"denominator": "1",
"numerator": "1"
},
"unit": {
"Local": "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce"
}
}
}
},
"display_unit": {
"Local": "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce"
},
"subject": {
"Element": "6df991ba-4c5e-4535-99e2-524ae274ee8b"
},
"value_type": {
"Scalar": {
"Quantity": {
"Local": "188b911c-5f8b-431c-9eea-2d41f3953767"
}
}
}
}
}
}
},
"description": "",
"id": "c33fc772-2a60-4044-9af9-73c61c563ace",
"name": "Dispatch time",
"parent": null
},
"cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59": {
"alias": "respond",
"body": {
"Oa": "Activity"
},
"description": "",
"id": "cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59",
"name": "Respond",
"parent": null
}
},
"id": "4210b9f2-7046-47f0-aa3b-153f626a579d",
"imports": {},
"library_instances": {},
"name": "Response budget",
"relations": {},
"schema_version": 8,
"traces": {}
},
"packages": {},
"source": {
"entry": "active.arcadia",
"files": {
"active.arcadia": "arcadia 8;\nproject response_budget \"Response budget\" id \"4210b9f2-7046-47f0-aa3b-153f626a579d\" {\n description \"A complete proposed analysis model. Schema 8 and the new declarations are not implemented source7 syntax.\";\n\n quantity_kind duration \"Duration\" id \"188b911c-5f8b-431c-9eea-2d41f3953767\" {\n dimension { time: 1; }\n algebra Linear;\n }\n unit second \"Second\" id \"534f4672-1ba5-4157-8b0a-b9cf41d0a3ce\" {\n kind @duration; scale 1; offset 0; symbol \"s\";\n }\n unit millisecond \"Millisecond\" id \"39053f37-fec9-4708-9f0a-3959d223f891\" {\n kind @duration; scale ratio(1, 1000); offset 0; symbol \"ms\";\n }\n calculation combine \"Combine durations\" id \"fd7ce7ab-f789-40bc-b699-0c37f1b6902f\" {\n input a id \"28ff40b0-1b8f-4735-8536-5a6ab21b56cb\" : Quantity(@duration);\n input b id \"7a47cc1e-8ae5-4551-b2d8-8a68108e0976\" : Quantity(@duration);\n result Quantity(@duration);\n body $a + $b;\n }\n\n oa_activity respond \"Respond\" id \"cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59\" {\n oa_activity receive \"Receive\" id \"4ab9a8a7-7552-488d-9862-e14b89e7b353\" {}\n oa_activity dispatch \"Dispatch\" id \"6df991ba-4c5e-4535-99e2-524ae274ee8b\" {}\n }\n oa_property receive_time \"Receive time\" id \"63a931c2-675a-4fce-89e5-04361cb99450\" {\n subject @receive; type Quantity(@duration); display_unit @millisecond;\n base 750 [@millisecond];\n }\n oa_property dispatch_time \"Dispatch time\" id \"c33fc772-2a60-4044-9af9-73c61c563ace\" {\n subject @dispatch; type Quantity(@duration); display_unit @second;\n base 1 [@second];\n }\n oa_property total_time \"Total time\" id \"bd5b68e8-65fc-4e35-9071-a73061316a4b\" {\n subject @respond; type Quantity(@duration); display_unit @second;\n // The formula is shared. Every read uses the requested evaluation context.\n base @combine(a: @receive_time, b: @dispatch_time);\n }\n oa_property limit \"Allowed duration\" id \"437bedbb-2cf4-44ee-a139-6563cc5086ec\" {\n subject @respond; type Quantity(@duration); display_unit @second;\n base 2 [@second];\n }\n oa_check budget \"Response budget\" id \"bac0de99-9d2f-4e53-9158-d424ecac61bf\" {\n subject none; documented_constraint none;\n predicate @total_time <= @limit;\n }\n oa_analysis degraded \"Degraded radio\" id \"38036c65-16d4-449c-837b-91eb141c1d93\" {\n subject none; base ModelBaseline;\n overrides { @receive_time = 1250 [@millisecond]; }\n }\n oa_analysis unmeasured \"Unmeasured radio\" id \"99d3e09a-0ec3-4194-9dd4-9f3de6625cde\" {\n subject none; base ModelBaseline;\n overrides { @receive_time = unbound; }\n }\n}\n"
}
}
}
@@ -0,0 +1,32 @@
[
{
"canonical_source": "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"expression": {
"Number": {
"denominator": "1",
"numerator": "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
},
"name": "ten_to_300"
},
{
"canonical_source": "ratio(1, 522194440706576253345876355358312191289982124523691890192116741641976953985778728424413405967498779170445053357219631418993786719092896803631618043925682638972978488271854999170180795067191859157214035005927973113188159419698856372836167342172293308748403954352901852035642024370059304557233988891799014503343469488440893892973452815095130470299789726716411734651513348221529512507986199933857107770846917779942645743159118957217248367043905936319748237550094520674504208530837546834166925275516486044134775384991808184705966507606898412918594045916828375610659246423184062775112999150206172392431297837246097308511903252956622805412865917690043804311051417135098849101156584508839003337597742539960818209685142687562392007453579567729991395256699805775897135553415567045292136442139895777424891477161767258532611634530697452993846501061481697843891439474220308003706472837459911525285821188577408160690315522951458068463354171428220365223949985950890732881736611925133626529949897998045399734600887312408859224933727829625089164535236559716582775403784110923285873186648442456409760158728501220463308455437074192539205964902261490928669488824051563042951500651206733594863336608245755565801460390869016718045121902354170201577095168)",
"expression": {
"Number": {
"denominator": "522194440706576253345876355358312191289982124523691890192116741641976953985778728424413405967498779170445053357219631418993786719092896803631618043925682638972978488271854999170180795067191859157214035005927973113188159419698856372836167342172293308748403954352901852035642024370059304557233988891799014503343469488440893892973452815095130470299789726716411734651513348221529512507986199933857107770846917779942645743159118957217248367043905936319748237550094520674504208530837546834166925275516486044134775384991808184705966507606898412918594045916828375610659246423184062775112999150206172392431297837246097308511903252956622805412865917690043804311051417135098849101156584508839003337597742539960818209685142687562392007453579567729991395256699805775897135553415567045292136442139895777424891477161767258532611634530697452993846501061481697843891439474220308003706472837459911525285821188577408160690315522951458068463354171428220365223949985950890732881736611925133626529949897998045399734600887312408859224933727829625089164535236559716582775403784110923285873186648442456409760158728501220463308455437074192539205964902261490928669488824051563042951500651206733594863336608245755565801460390869016718045121902354170201577095168",
"numerator": "1"
}
},
"name": "one_over_two_to_4095"
},
{
"canonical_source": "ratio(-1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335, 1)",
"expression": {
"Number": {
"denominator": "1",
"numerator": "-1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335"
}
},
"name": "negative_4096_bit_bound"
}
]
@@ -0,0 +1,29 @@
# Analysis context experiment
This standalone Rust program compares explicit baseline/override studies (B) with complete independent case bindings (D). It is an isolated experiment, **not Studio syntax or a production model implementation**. Its expression language is deliberately limited to integer magnitudes in milliseconds, addition/sum, comparison, missing inputs and pure reusable functions.
The source owns the fixture generator, parser, explicit context resolver, dependency-cycle check, evaluator, frozen-snapshot operation, provenance observations and line-diff counter. All comparisons use the same 20 fixed inputs, 2 varying inputs and 20 named cases. The formula/check variants are either inline or factored into reusable pure definitions.
From the repository root, using the installed local toolchain:
```powershell
. .local/toolchain/env.ps1
New-Item -ItemType Directory -Force .local/analysis-context-20260911 | Out-Null
rustc --edition=2024 -D warnings -C linker=clang.exe harness/experiments/analysis-context-20260911/main.rs -o .local/analysis-context-20260911/analysis-context.exe
if ($LASTEXITCODE -ne 0) { throw 'Experiment compilation failed' }
& .local/analysis-context-20260911/analysis-context.exe harness/experiments/analysis-context-20260911/generated
if ($LASTEXITCODE -ne 0) { throw 'Experiment assertions failed' }
```
The program overwrites its named generated fixtures/results in the output directory. It does not invoke Cargo, modify `target`, or import Studio modules. `EVIDENCE.json` was recorded separately after the verified run and contains exact compiler, program/executable/result hashes and every generated source fixture hash. Rerunning after editing the program requires refreshing that evidence rather than trusting the old manifest.
- [Results](generated/RESULTS.md): executed counts and assertions.
- [Evidence](generated/EVIDENCE.json): final run identity and 29 fixture hashes.
- [B with factored calculations](generated/B-factored.study) and [D equivalent](generated/D-factored.study).
- [B case provenance](generated/B-factored-provenance.md).
- [Frozen B case](generated/B-factored-frozen-case20.study): complete independent snapshot, copied definitions and explicit captured row origins.
- [Interpretation and limitations](../../release-analysis-context-experiment-20260911.md).
The small dialect has explicit `study B/D revision`, a shared property catalog, optional pure `function` declarations, an explicit named `baseline` for B, and named cases declaring either `base engineering` or `independent`. `missing` is an entire binding hole. Removing a B override resolves the baseline; removing a required D row rejects. Function parameters cannot capture project properties. No case-to-case inheritance or implicit selected/default case exists.
Generated studies do not have OA/SA subjects, UUID identity, quantity kinds, persistent source editing, JSON/REST, library import resolution or native UI integration. The experiment compares context semantics and the actual emitted text size/edit count, not human completion time or end-to-end product conformance.
@@ -0,0 +1,107 @@
study B revision 1
properties fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02, total, budget
function budget_formula(result) = le(result, 22000)
function total_formula(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02) = sum(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02)
baseline engineering revision 1
budget = budget_formula(total)
fixed01 = 1000
fixed02 = 1000
fixed03 = 1000
fixed04 = 1000
fixed05 = 1000
fixed06 = 1000
fixed07 = 1000
fixed08 = 1000
fixed09 = 1000
fixed10 = 1000
fixed11 = 1000
fixed12 = 1000
fixed13 = 1000
fixed14 = 1000
fixed15 = 1000
fixed16 = 1000
fixed17 = 1000
fixed18 = 1000
fixed19 = 1000
fixed20 = 1000
total = total_formula(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02)
varying01 = 750
varying02 = 1000
end
case case01 base engineering
end
case case02 base engineering
varying01 = 800
varying02 = 1025
end
case case03 base engineering
varying01 = 850
varying02 = 1050
end
case case04 base engineering
varying01 = 900
varying02 = 1075
end
case case05 base engineering
varying01 = 950
varying02 = 1100
end
case case06 base engineering
varying01 = 1000
varying02 = 1125
end
case case07 base engineering
varying01 = 1050
varying02 = 1150
end
case case08 base engineering
varying01 = 1100
varying02 = 1175
end
case case09 base engineering
varying01 = 1150
varying02 = 1200
end
case case10 base engineering
varying01 = 1200
varying02 = 1225
end
case case11 base engineering
varying01 = 1250
varying02 = 1250
end
case case12 base engineering
varying01 = 1300
varying02 = 1275
end
case case13 base engineering
varying01 = 1350
varying02 = 1300
end
case case14 base engineering
varying01 = 1400
varying02 = 1325
end
case case15 base engineering
varying01 = 1450
varying02 = 1350
end
case case16 base engineering
varying01 = 1500
varying02 = 1375
end
case case17 base engineering
varying01 = 1550
varying02 = 1400
end
case case18 base engineering
varying01 = 1600
varying02 = 1425
end
case case19 base engineering
varying01 = 1650
varying02 = 1450
end
case case20 base engineering
varying02 = 1475
end
@@ -0,0 +1,108 @@
study B revision 1
properties fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02, total, budget
function budget_formula(result) = le(result, 22000)
function total_formula(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02) = sum(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02)
baseline engineering revision 1
budget = budget_formula(total)
fixed01 = 1000
fixed02 = 1000
fixed03 = 1000
fixed04 = 1000
fixed05 = 1000
fixed06 = 1000
fixed07 = 1000
fixed08 = 1000
fixed09 = 1000
fixed10 = 1000
fixed11 = 1000
fixed12 = 1000
fixed13 = 1000
fixed14 = 1000
fixed15 = 1000
fixed16 = 1000
fixed17 = 1000
fixed18 = 1000
fixed19 = 1000
fixed20 = 1000
total = total_formula(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02)
varying01 = 750
varying02 = 1000
end
case case01 base engineering
end
case case02 base engineering
varying01 = 800
varying02 = 1025
end
case case03 base engineering
varying01 = 850
varying02 = 1050
end
case case04 base engineering
varying01 = 900
varying02 = 1075
end
case case05 base engineering
varying01 = 950
varying02 = 1100
end
case case06 base engineering
varying01 = 1000
varying02 = 1125
end
case case07 base engineering
varying01 = 1050
varying02 = 1150
end
case case08 base engineering
varying01 = 1100
varying02 = 1175
end
case case09 base engineering
varying01 = 1150
varying02 = 1200
end
case case10 base engineering
varying01 = 1200
varying02 = 1225
end
case case11 base engineering
varying01 = 1250
varying02 = 1250
end
case case12 base engineering
varying01 = 1300
varying02 = 1275
end
case case13 base engineering
varying01 = 1350
varying02 = 1300
end
case case14 base engineering
varying01 = 1400
varying02 = 1325
end
case case15 base engineering
varying01 = 1450
varying02 = 1350
end
case case16 base engineering
varying01 = 1500
varying02 = 1375
end
case case17 base engineering
varying01 = 1550
varying02 = 1400
end
case case18 base engineering
varying01 = 1600
varying02 = 1425
end
case case19 base engineering
varying01 = 1650
varying02 = 1450
end
case case20 base engineering
varying01 = total
varying02 = 1475
end
@@ -0,0 +1,108 @@
study B revision 2
properties fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02, total, budget
function budget_formula(result) = le(result, 22000)
function total_formula(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02) = sum(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02)
baseline engineering revision 2
budget = budget_formula(total)
fixed01 = 1200
fixed02 = 1000
fixed03 = 1000
fixed04 = 1000
fixed05 = 1000
fixed06 = 1000
fixed07 = 1000
fixed08 = 1000
fixed09 = 1000
fixed10 = 1000
fixed11 = 1000
fixed12 = 1000
fixed13 = 1000
fixed14 = 1000
fixed15 = 1000
fixed16 = 1000
fixed17 = 1000
fixed18 = 1000
fixed19 = 1000
fixed20 = 1000
total = total_formula(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02)
varying01 = 750
varying02 = 1000
end
case case01 base engineering
end
case case02 base engineering
varying01 = 800
varying02 = 1025
end
case case03 base engineering
varying01 = 850
varying02 = 1050
end
case case04 base engineering
varying01 = 900
varying02 = 1075
end
case case05 base engineering
varying01 = 950
varying02 = 1100
end
case case06 base engineering
varying01 = 1000
varying02 = 1125
end
case case07 base engineering
varying01 = 1050
varying02 = 1150
end
case case08 base engineering
varying01 = 1100
varying02 = 1175
end
case case09 base engineering
varying01 = 1150
varying02 = 1200
end
case case10 base engineering
varying01 = 1200
varying02 = 1225
end
case case11 base engineering
varying01 = 1250
varying02 = 1250
end
case case12 base engineering
varying01 = 1300
varying02 = 1275
end
case case13 base engineering
varying01 = 1350
varying02 = 1300
end
case case14 base engineering
varying01 = 1400
varying02 = 1325
end
case case15 base engineering
varying01 = 1450
varying02 = 1350
end
case case16 base engineering
varying01 = 1500
varying02 = 1375
end
case case17 base engineering
varying01 = 1550
varying02 = 1400
end
case case18 base engineering
varying01 = 1600
varying02 = 1425
end
case case19 base engineering
varying01 = 1650
varying02 = 1450
end
case case20 base engineering
varying01 = 1700
varying02 = 1475
end
@@ -0,0 +1,55 @@
study D revision 1
origin B:case20:document1:engineering@1
captured budget = baseline:engineering@1 via case20
captured fixed01 = baseline:engineering@1 via case20
captured fixed02 = baseline:engineering@1 via case20
captured fixed03 = baseline:engineering@1 via case20
captured fixed04 = baseline:engineering@1 via case20
captured fixed05 = baseline:engineering@1 via case20
captured fixed06 = baseline:engineering@1 via case20
captured fixed07 = baseline:engineering@1 via case20
captured fixed08 = baseline:engineering@1 via case20
captured fixed09 = baseline:engineering@1 via case20
captured fixed10 = baseline:engineering@1 via case20
captured fixed11 = baseline:engineering@1 via case20
captured fixed12 = baseline:engineering@1 via case20
captured fixed13 = baseline:engineering@1 via case20
captured fixed14 = baseline:engineering@1 via case20
captured fixed15 = baseline:engineering@1 via case20
captured fixed16 = baseline:engineering@1 via case20
captured fixed17 = baseline:engineering@1 via case20
captured fixed18 = baseline:engineering@1 via case20
captured fixed19 = baseline:engineering@1 via case20
captured fixed20 = baseline:engineering@1 via case20
captured total = baseline:engineering@1 via case20
captured varying01 = case:case20
captured varying02 = case:case20
properties fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02, total, budget
function budget_formula(result) = le(result, 22000)
function total_formula(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02) = sum(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02)
case case20 independent
budget = budget_formula(total)
fixed01 = 1000
fixed02 = 1000
fixed03 = 1000
fixed04 = 1000
fixed05 = 1000
fixed06 = 1000
fixed07 = 1000
fixed08 = 1000
fixed09 = 1000
fixed10 = 1000
fixed11 = 1000
fixed12 = 1000
fixed13 = 1000
fixed14 = 1000
fixed15 = 1000
fixed16 = 1000
fixed17 = 1000
fixed18 = 1000
fixed19 = 1000
fixed20 = 1000
total = total_formula(fixed01, fixed02, fixed03, fixed04, fixed05, fixed06, fixed07, fixed08, fixed09, fixed10, fixed11, fixed12, fixed13, fixed14, fixed15, fixed16, fixed17, fixed18, fixed19, fixed20, varying01, varying02)
varying01 = 1700
varying02 = 1475
end

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