diff --git a/ROADMAP.md b/ROADMAP.md index ef0a8574..045f3201 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -86,6 +86,12 @@ recursion. **Scope:** `InterconnectionViewLayoutStrategy`'s `LayOutInterior`/`CollectParts` recursion; possibly a new `LayeredPlacement` entry point that builds a genuinely nested `LayoutGraph`. + +**Engine support:** `DemaConsulting.Rendering` 0.3.0-beta.2 now routes an edge declared on a graph +scope between nodes that sit at any depth beneath it (a cross-hierarchy edge, anchored to the actual +nested nodes rather than their containers), which removes the engine-side blocker for this item. +`GeneralViewLayoutStrategy` already uses it for edges across packages. The Interconnection +strategy's restructuring described above is still required, so this item remains open. **Visual gate:** `connect psu to board.cpu;` renders a connector line that visually terminates on the inner `cpu` box, not the `board` container's boundary. diff --git a/docs/design/sysml2-tools-core/layout/internal/general-view-layout-strategy.md b/docs/design/sysml2-tools-core/layout/internal/general-view-layout-strategy.md index 41a4fdca..f5f0241a 100644 --- a/docs/design/sysml2-tools-core/layout/internal/general-view-layout-strategy.md +++ b/docs/design/sysml2-tools-core/layout/internal/general-view-layout-strategy.md @@ -7,11 +7,13 @@ renders every user-defined definition (part, port, interface, requirement, actio — since Phase 2d (see `ROADMAP.md`'s "View `filter [];` expression evaluation" section) — every named usage-level declaration too, as a keyword-labeled box, groups the boxes that belong to a bare package (one with no admitted definition as its own owner) inside a folder-shaped -container when the view is unscoped, nests a definition that owns nested definitions recursively +container when the view is unscoped — drawing a package nested in another package inside its +owner's folder — nests a definition that owns nested definitions recursively inside that definition's own box rather than as a duplicate sibling container, lists each definition's owned usages in compartments, and draws specialization, membership, attribute-typing, redefinition, subsetting, connect, allocate, dependency, and -binding edges orthogonally between the boxes. The whole diagram — package +binding edges orthogonally between the boxes, including edges whose endpoints lie in different +packages or at different nesting depths. The whole diagram — package folders, definition-as-container boxes, and plain definitions alike — is expressed as a single `DemaConsulting.Rendering` `LayoutGraph` and placed with one `LayoutEngine.Layout` call via the `"auto"` meta-algorithm @@ -20,7 +22,11 @@ connectivity, routing connected groups through the bundled layered algorithm (`LayeredLayoutAlgorithm`) and packing disconnected/singleton nodes by reading order (`ContainmentLayoutAlgorithm`), while each container's own contents (a folder's or a nested-owning-definition's) are always ordered by their intra-container edges with the layered -algorithm. All box sizing (title bands, compartment rows) remains this strategy's +algorithm. Because the engine places a folder's contents without knowing where the folder's +relationships to the outside lead, the strategy orders each folder's definitions by the vertical +position of those relationships' far ends in a first layout and lays out once more (see +`ComputeItemOrder`), so relationships leaving a folder are not forced to cross by declaration order. +All box sizing (title bands, compartment rows) remains this strategy's responsibility, since the layout stage in `DemaConsulting.Rendering.Layout` is theme-agnostic; box title and folder-tab geometry come from `BoxMetrics` in `DemaConsulting.Rendering.Abstractions`. @@ -35,7 +41,16 @@ own `comment` annotations from `SysmlNode.Annotations`, threaded through by `Col specialization/membership/attribute-typing/redefinition/subsetting/connect/allocate/dependency/ binding relationship expressed by qualified name, together with its target end marker, edge kind, and an optional midpoint label), `Location` (a located definition's -graph node and owning package, used to resolve and scope edges), and `TruncatedContainer` (a +graph node and the `ScopeInfo` that directly holds it, used to resolve and scope edges), `ScopeInfo` +(one container scope of the layout graph — the root graph, a package folder's `Children` graph, or +a definition-as-container's `Children` graph — with a `Parent` link to its enclosing scope and the +`Owner` container node whose `Children` graph it is (null for the root), so the +scopes form a tree whose lowest common ancestor `LowestCommonScope` can find), `GraphBuild` (the +result of one `BuildGraph` pass: the root graph, the truncated containers, the `located` map, and the +folder plans, which the order-refinement pass reads), `FolderPlan` (the +pre-materialization plan for one package folder: its key, nearest enclosing folder, directly owned +definitions, ordered child-folder keys, nesting level, and the hidden-element count reported if it is +truncated; see `BuildGraph`), and `TruncatedContainer` (a depth-truncated package folder's or nested-definition-containing definition's leaf placeholder graph node, hidden-item count, and vertical title-band offset, used to stamp its ellipsis label onto the placed box after layout — see `DecorateTruncated` below). `DroppedRelationshipEdge` (a private record) @@ -99,15 +114,26 @@ specialization/membership/attribute-typing/redefinition/subsetting/ connect/allocate/dependency/binding relationships are resolved into qualified-name edges (plus any dropped-edge diagnostics) with `BuildModelEdges`, the single input `LayoutGraph` is built -with `BuildGraph` (passed `childrenByParent` and whether the view has a resolved scope), and the -whole graph is placed with one `LayoutEngine.Layout(graph)` call after setting -`graph.Set(CoreOptions.Algorithm, AutoLayoutAlgorithm.AlgorithmId)` — delegating root-scope +with `BuildGraph` (passed `childrenByParent`, whether the view has a resolved scope, the set of +every non-stdlib package in the workspace from `CollectPackageNames`, and no item order on the first +pass), and the +whole graph is placed with one `LayoutEngine.Layout(graph)` call (the `LayOut` helper, which first sets +`graph.Set(CoreOptions.Algorithm, AutoLayoutAlgorithm.AlgorithmId)`) — delegating root-scope algorithm selection to `"auto"`, which classifies the root's own folders/top-level definitions by connectivity (routing connected groups through the layered algorithm and packing disconnected/singleton nodes via containment) rather than pinning every root-scope node to a single -fixed algorithm regardless of its own connectivity. When any package folder or -nested-definition-containing definition was depth-truncated, `DecorateTruncated` stamps each -truncated container's "+N more…" ellipsis label onto its placed box. Finally, the returned tree's `Warnings` concatenates +fixed algorithm regardless of its own connectivity. The engine places a package folder's contents +without knowing where the folder's relationships to the outside lead, and stacks the unconnected +groups of those contents by the order they were added, so `BuildLayout` then calls +`ComputeItemOrder` on the first layout: when it reports a different item order for any folder, the +graph is built a second time with that order (`BuildGraph`'s `itemOrder`) and laid out again; when +it reports none (no folder has two or more items with external relationships whose order would +change) the first layout is kept unchanged. The refinement is a single pass — there is no iteration +to a fixed point, so termination is guaranteed — and it is documented as a compensation for the +engine's placement model that can be retired once the engine orders a container's interior by its +cross-hierarchy edges. When any package folder or nested-definition-containing definition was +depth-truncated, `DecorateTruncated` stamps each truncated container's "+N more…" ellipsis label onto +its placed box of the final layout. Finally, the returned tree's `Warnings` concatenates `LayoutWarnings.ForUnevaluatedFilter` (only when standalone filter parsing/evaluation failed), `LayoutWarnings.ForUnevaluatedExposeBracketFilter(context.ViewName, scope?.Failures ?? [])` (Phase 2a: one warning per bracket-filter expression that failed to parse or evaluate — a @@ -216,7 +242,9 @@ method is unchanged by the nested-definition-containment fix: `BuildLayout` now with the subset of definitions whose immediate parent is *not* itself an admitted definition (see `BuildLayout` above), so an admitted definition's own qualified name can never again become one of its bucket keys — which is precisely what removes the duplicate-folder symptom, without any change -to this method's own flat, first-seen-order bucketing logic. +to this method's own flat, first-seen-order bucketing logic. The buckets stay flat: package nesting +is not decided here but in `BuildGraph`, which also receives the exposed-package and workspace-package +sets that nesting needs. ###### `CollectExposedPackages(workspace, scope)` @@ -225,6 +253,12 @@ admits (an empty set for an unscoped view). `BuildLayout` applies the view's `fi these packages exactly as to definitions (a package is a candidate element), keeps the view non-empty when only packages are exposed, and passes the set to `BuildGraph`. +###### `CollectPackageNames(workspace)` + +Returns the qualified names of every non-stdlib `SysmlPackageNode` in the workspace, exposed or not. +`BuildGraph` uses it to tell which qualified-name prefixes are packages, so an unscoped view draws an +enclosing package's folder even when that package owns no definitions directly. + ###### `BuildModelEdges(defs, workspace, isScoped)` Resolves every specialization (subtype → supertype), structural membership (member-type → owner), @@ -404,10 +438,19 @@ longest-prefix-wins) would resolve *both* sides of the dominant real-world corpu — to the same box (`Drone`), producing a false self-loop where a real diagram must show two distinct boxes (`Controller` and `Battery`) connected. -###### `BuildGraph(groups, childrenByParent, modelEdges, theme, depthLimit, exposedPackages)` - -Builds the single input `LayoutGraph`, setting `CoreOptions.MergeParallelEdges` to `false` on the -root graph so multiple distinct model relationship edges that happen to share the same source and +###### `BuildGraph(groups, childrenByParent, modelEdges, theme, depthLimit, exposedPackages, packageNames, itemOrder)` + +Builds the single input `LayoutGraph` and returns it as a `GraphBuild` (graph, truncated containers, +`located` map, folder plans). The optional `itemOrder` (folder key to item qualified names, produced by +`ComputeItemOrder`) sets the order in which a folder's own definitions are placed (`OrderedItems`); +without it, or for a folder it does not name, declaration order is used, names the folder does not own +are ignored, and any item the order omits follows the named ones in declaration order, so a stale or +partial order can never drop a definition. Sets `CoreOptions.MergeParallelEdges` to `false` on the +root graph (every `CoreOptions` property cascades to the nested package-folder and definition-container +`Children` scopes unless a scope overrides it, so the setting holds in every scope where an edge is +declared; the `ParallelEdgesInNestedPackage_AreNotMerged` and +`ParallelEdgesInDefinitionContainer_AreNotMerged` tests pin it) so multiple distinct model +relationship edges that happen to share the same source and target (for example two attributes of the same type, or a redefinition edge that coincides with another edge between the same two definitions) are never collapsed by the bundled layered algorithm's default parallel-edge merging — every distinct model relationship this strategy adds @@ -418,64 +461,100 @@ top-level item, a bare package's item, or a definition nested inside another def through the recursive `PlaceDef` helper (below), which is what actually creates each definition's node and recurses into its own `childrenByParent` entry, if any. -For each `(package, items)` group: an empty `package` key means top-level (unpackaged) items, -placed via `PlaceDef` directly on the root graph. When `exposedPackages` is non-null (the view -has a resolved `expose` scope), a non-empty `package` key becomes a folder only when the package is -itself exposed: per SysML 2.1 Beta 2 8.3.26.3/8.3.26.4 (and KerML 8.3.2.4.4) a MembershipExpose -(`expose P;`, `expose P::**;`) exposes the Package P itself, while a NamespaceExpose -(`expose P::*;`, `expose P::*::**;`) exposes only P's members. A package that is merely an ancestor -of admitted content is not exposed, so its items are placed via `PlaceDef` directly on the root -graph, exactly like top-level items. An exposed package with no exposed members gets its own group -with no items (added in `BuildLayout` from `CollectExposedPackages`) and is drawn as a leaf package -node (`Shape = Folder`, name inside, sized to its label) — the SysML 8.2.3.5 `package-node` -with no compartments — instead of an empty canvas. This case is handled before depth -truncation, so a depth limit never decorates an empty package node with a `+0 more…` indicator. -Exposed packages are grouped flat by qualified name, as for unscoped views: a nested exposed -package (`P::Sub` under `expose P::**;`) is drawn as its own package node beside `P`, not inside -it. When `exposedPackages` is null, every non-empty -`package` key becomes a folder container node (`Shape = Folder`, `Keyword = "package"`, `Label` the simple -package name, `TitleHeight` set from -`BoxMetrics.TitleAreaHeight` so the hierarchical engine reserves the exact title band the renderer -will draw), and its items are placed via `PlaceDef` under `folder.Children`; the folder's own -`CoreOptions.Algorithm` is set to `LayeredLayoutAlgorithm.AlgorithmId` per the established -per-container-algorithm convention (the algorithm override lives on the container node itself, while -every other `CoreOptions` property would live on its `Children` graph). When the depth limit -forbids a folder's nested level (and the view is unscoped — depth-truncation and scope-suppression -never both apply to the same folder, since the scope-suppression branch already diverted a scoped -folder's items before the depth check runs), its definitions are never added as individual boxes at -all — the folder becomes a single leaf node (its `Children` graph is never touched, so the -hierarchical engine keeps this caller-computed ellipsis size rather than auto-sizing it as a -container) sized like the previous ellipsis-indicator formula, and recorded as a `TruncatedContainer` -for later decoration. - -Package-folder contents (and the top-level/scoped-promoted items placed directly on the root graph) -sit at depth 1 — the pre-existing convention `truncateFolderContents` (`depthLimit > 0 && depthLimit -<= 1`) already relies on. Every `PlaceDef` call `BuildGraph` makes passes this same `rootDepth == 1` -as `def`'s own starting depth, so `PlaceDef`'s own nested-definition-containment recursion (see -below) goes one depth deeper per level from this same baseline — a definition's immediate nested -child sits at depth 2, its grandchild at depth 3, and so on — regardless of whether that definition -sits directly on the root, inside a folder, or is itself already nested inside another definition. -This is what fixes the reviewer-confirmed defect where `RenderOptions.DepthLimit` only capped -package-folder-contents nesting and had no effect at all on nested-definition containment. - -Every located definition's node and owning container scope key ("package", or an admitted -definition's own qualified name — see `PlaceDef`) is recorded in a `located` map so model edges can -be resolved and scoped: an edge whose endpoints share the same non-empty scope key is added to that -container's own `Children` scope (an intra-container edge the layered algorithm can use to order -the container's contents); every other edge — including any crossing containers — is added at the -root, referencing the (possibly nested) endpoint nodes directly, per the graph's -lowest-common-ancestor edge convention. An edge touching a depth-truncated (unrendered) definition -has no node in the `located` map to reference and is silently dropped, exactly as before. - -###### `PlaceDef(def, targetScope, packageKeyForEdgeScoping, childrenByParent, located, containerScopes, ...)` - -Places a single definition's node into `targetScope` via `MakeDefNode`, records its `Location` in -`located` (keyed by the container scope it was placed in, for edge scoping), and emits its +Folders are planned before any graph node exists (`PlanFolders`), then materialized parent-first. + +*Planning.* A group becomes a folder seed when its `package` key is non-empty and, in a scoped view +(`exposedPackages` non-null), the package is itself exposed: per SysML 2.1 Beta 2 8.3.26.3/8.3.26.4 +(and KerML 8.3.2.4.4) a MembershipExpose (`expose P;`, `expose P::**;`) exposes the Package P itself, +while a NamespaceExpose (`expose P::*;`, `expose P::*::**;`) exposes only P's members. Groups with an +empty key (top-level, unpackaged items) and, in a scoped view, groups of non-exposed packages are not +folders; their items are placed via `PlaceDef` directly on the root scope, exactly like top-level items +(a package that is merely an ancestor of admitted content is not drawn). Every enclosing package of a +seed that is eligible — an exposed package in a scoped view, otherwise any package from +`packageNames` — also becomes a folder, planned before the first folder nested in it, even when it +owns no definitions directly; a prefix that is not a package (for example a definition) is skipped. +Each folder is nested in its nearest enclosing planned folder, or sits on the root when there is none +(so in a scoped view a nested exposed package attaches to its nearest *exposed* ancestor, else the +root). The plan records each folder's nesting level (the number of enclosing folders) and its +subtree count — its own definitions plus, for each nested folder, one for the folder and its own +subtree count — which is the number a truncated folder reports as hidden. + +*Materialization.* Folders are materialized in plan order, so a folder's parent scope always exists +first; a folder whose parent was collapsed by the depth limit is skipped (the parent's subtree count +already includes it). A folder with no definitions and no nested folders is drawn as a leaf package +node (`Shape = Folder`, name inside, sized to its label) — the SysML 8.2.3.5 `package-node` with no +compartments — instead of an empty canvas; this case is handled before depth truncation, so a depth +limit never decorates an empty package node with a `+0 more…` indicator. Any other folder becomes a +container node (`Shape = Folder`, `Keyword = "package"`, `Label` the simple package name, +`TitleHeight` set from `BoxMetrics.TitleAreaHeight` so the hierarchical engine reserves the exact +title band the renderer will draw) added to its parent scope — the root graph, or the enclosing +folder's own `Children` graph, which is how a nested package is drawn inside its owner — with its own +definitions placed via `PlaceDef` under `folder.Children` and a new `ScopeInfo` whose parent is the +enclosing scope. The folder's own `CoreOptions.Algorithm` is set to `LayeredLayoutAlgorithm.AlgorithmId` +per the established per-container-algorithm convention (the algorithm override lives on the container +node itself, while every other `CoreOptions` property would live on its `Children` graph). When the +depth limit forbids a folder's contents, its definitions and nested folders are never added as +individual boxes at all — the folder becomes a single leaf node (its `Children` graph is never +touched, so the hierarchical engine keeps this caller-computed ellipsis size rather than auto-sizing +it as a container) sized like the previous ellipsis-indicator formula from its subtree count, and +recorded as a `TruncatedContainer` for later decoration. + +Package-folder contents sit at depth `1 + nesting level`: the contents of a top-level folder, and the +top-level/scoped-promoted items placed directly on the root graph, are at depth 1 — the pre-existing +convention (`depthLimit > 0 && depthLimit <= 1` collapses a top-level folder) — and each enclosing +folder adds one level, the same as a definition nested in a definition. A folder is therefore +collapsed when `depthLimit > 0 && depthLimit <= 1 + nesting level`: with a limit of 1 only the +top-level folders are shown, collapsed; with 2 each top-level folder's own definitions are shown and +its nested folders are collapsed; and so on. Every `PlaceDef` call `BuildGraph` makes for a folder's +items passes that folder's content depth as `def`'s own starting depth (and the root depth, 1, for +root-scope items), so `PlaceDef`'s own nested-definition-containment recursion (see below) goes one +depth deeper per level from this same baseline — a definition's immediate nested child sits one +level deeper than the definition, its grandchild two, and so on — regardless of whether that +definition sits directly on the root, inside a (possibly nested) folder, or is itself already nested +inside another definition. This is what fixes the reviewer-confirmed defect where +`RenderOptions.DepthLimit` only capped package-folder-contents nesting and had no effect at all on +nested-definition containment. + +Every located definition's node and the `ScopeInfo` that directly holds it is recorded in a `located` +map so model edges can be scoped by lowest common ancestor. Each edge is added to the scope returned +by `LowestCommonScope(source.Scope, target.Scope)` — the innermost scope on both endpoints' parent +chains — and references the (possibly deeply nested) endpoint nodes directly. Because the scope +chain contains both package folders and definition-as-container scopes, one lookup handles sibling +definitions in one scope, two siblings of a common parent (their parent package or definition), a +nested package versus its owner (the owner's scope), definitions several packages deep in different +top-level packages (the root), and mixtures of package and definition nesting. The layout engine +(`DemaConsulting.Rendering.Layout` 0.3.0-beta.2 or later) routes an edge declared on an ancestor +scope between the endpoint nodes themselves, not between the containers holding them, so +relationships across packages are drawn between the actual definition boxes; earlier engine versions +dropped such edges or anchored them to package borders. An edge between a container and one of its +own descendants has the container's own enclosing scope as its lowest common ancestor; the engine +does not draw it (the containment is already visible) and does not throw. An edge touching a +depth-truncated (unrendered) definition has no node in the `located` map to reference and is silently +dropped, exactly as before. + +###### `PlanFolders(groups, exposedPackages, packageNames)` + +Pure planning step used by `BuildGraph` (see above): decides which packages become folders, their +nesting and order (an enclosing folder always precedes everything nested in it), the nesting level, +and the subtree count, and returns the ordered materialization steps — each either a folder key or the +index of a group whose items are placed directly on the root scope — so root-level items keep their +original relative order. + +###### `LowestCommonScope(a, b)` + +Returns the innermost `ScopeInfo` that encloses both arguments (a scope encloses itself) by collecting +the ancestors of `a` (by reference identity) and walking `b` upward until one of them is found; the +root scope is on both chains, so a result always exists. + +###### `PlaceDef(def, scope, childrenByParent, located, theme, depth, depthLimit, truncated)` + +Places a single definition's node into `scope.Graph` via `MakeDefNode`, records its `Location` in +`located` (the node and the `scope` that directly holds it, for edge scoping), and emits its annotation note via `AddAnnotationNote` — exactly the three steps `BuildGraph` used to perform inline for every leaf definition, now factored into one recursive helper. `depth` is `def`'s own -nesting depth, using the same numbering `BuildGraph` already uses for package-folder contents (a -top-level or folder-scoped definition is depth 1, per `BuildGraph`'s `rootDepth` convention above); -`def`'s own immediate nested children (if any) sit one depth deeper, at `depth + 1`. +nesting depth, using the same numbering `BuildGraph` uses for package-folder contents (a +top-level definition is depth 1; a folder's definition is its folder's content depth, per `BuildGraph` +above); `def`'s own immediate nested children (if any) sit one depth deeper, at `depth + 1`. When `def` owns nested definitions (a `childrenByParent` entry keyed by `def.QualifiedName`), the definition's own node's `TitleHeight` is set to `def.Height` (which already includes the title band @@ -491,15 +570,15 @@ of two things happens to that nested content: recorded in `truncated` with a `TitleOffset` of `0` (unlike a truncated package folder's placeholder, this ellipsis node is an ordinary child placed inside `def`'s own already-title reserved `Children` scope, not a standalone box carrying its own title/keyword band, so no further - offset is needed once its absolute position is known). No `containerScopes` entry is registered - for `def.QualifiedName` in this branch (nothing beyond the single ellipsis leaf is ever placed in - its scope, so no intra-container edge could resolve there), and none of the hidden children + offset is needed once its absolute position is known). No child `ScopeInfo` is created for `def` in + this branch (nothing beyond the single ellipsis leaf is ever placed in its scope, so no + intra-container edge could resolve there), and none of the hidden children receive a `located` entry, so every edge touching one is dropped exactly like a depth-truncated package folder's contents. -- Otherwise, `node.Children` is registered in `containerScopes` under `def.QualifiedName` so - intra-container edges between `def`'s own nested children resolve to `def`'s scope rather than - the root, and each child is placed by a recursive call to `PlaceDef` with `node.Children` as the - new target scope, `def.QualifiedName` as the new edge-scoping key, and `depth + 1` as the child's +- Otherwise, a new `ScopeInfo` (enclosed by `scope`, graph `node.Children`) is created for `def`, so + edges between `def`'s own nested children — or between one of them and a node elsewhere — resolve to + their lowest common scope rather than always the root, and each child is placed by a recursive call + to `PlaceDef` with that new scope and `depth + 1` as the child's own depth — resolving arbitrarily deep nesting (a definition owning a definition owning a definition, and so on) through repeated single-level recursion, one call per level, rather than a multi-hop ancestor walk, with the depth-limit check re-applied at every level. @@ -586,21 +665,70 @@ placeholders, is built in one `BuildGraph` pass before layout ever runs — so a ordinary graph node/edge pair up front is the natural fit, and lets the layout engine route and position it like any other element rather than requiring bespoke placement math. +###### `ComputeItemOrder(tree, build, edges)` + +Decides, from the first-pass layout, how each package folder's definitions should be ordered so that +relationships leaving the folder do not have to cross one another. The layered engine lays out a +container's contents independently of the container's external edges (the engine's +`SeparateChildren` placement model) and orders the unconnected groups of those contents by their +lowest insertion index, so declaration order alone can force a crossing: in the gallery's +`VehiclePackagesGeneralView`, `Hybrid` is declared after `Chassis` and was therefore stacked below +it, although `Hybrid`'s relationship leads to the nearer `Powertrain` folder and `Chassis`'s leads +past that folder to `Car`. This unit applies the standard barycenter heuristic across the container +boundary, which the engine leaves to the caller: + +1. `CollectCenters` records the absolute vertical center of every placed box against the graph node it + was placed from (tree coordinates are absolute, so centers in different scopes compare directly). +2. For every folder plan with at least two items, `ExternalPartnerKey` computes each item's key: the + mean center of the boxes its *external* relationships lead to. For each model edge touching the + item (`PartnerOf`), `ExternalAnchor` takes the lowest common scope of the item's scope and the + partner's scope; when that is the item's own (holding) scope the relationship stays inside the + folder and contributes nothing, whether the partner is a sibling definition or sits inside a nested + package or definition of the same folder: such an edge is declared in the folder's scope, so the + engine sees it when it orders that scope's contents (a nested-package partner does not force a + crossing, which the `ExternalEdges_DefinitionToSiblingNestedPackages_OrdersByPartnerFolder` test + pins). Otherwise the partner is walked up through `ScopeInfo.Owner`/`Parent` until the scope + reached is the common scope, and the node reached is the *anchor* — the direct member of the common + scope that contains the partner (the partner itself when it is a direct member). Anchors are + container boxes at the common scope, so the key does not depend on the partner folder's interior + order, which changes between passes. A partner without a node (hidden by the depth limit) adds + nothing. +3. `OrderByPartnerPosition` sorts the items that have a key by the rounded key (ties keep declaration + order) into the slots those items occupied; items without a key stay where they are. It returns + null when fewer than two items have a key or the order is unchanged. + +The result maps each folder whose order changes to its wanted item order; an empty result means the +first layout stands. Scope limits, deliberately not addressed: only package-folder items are +reordered (promoted root-level items and the children of a definition-as-container keep declaration +order); the key is vertical only, matching the default left-to-right flow every folder uses; and a +single refinement pass is made. The heuristic is a crossing-reduction mitigation, not a guarantee. It +also relies on the engine's insertion-order behavior, which is pinned by the OTS requirement +`SysML2Tools-OTS-DemaRendering-ComponentOrderFollowsInsertion`. + ###### `DecorateTruncated(tree, graph, truncated, theme)` Replaces each truncated container's placed box with one carrying its "+N more…" ellipsis label, positioned within the box's now-known absolute placement, using each `TruncatedContainer`'s own `TitleOffset` to position the label below any title/keyword band the placeholder box itself carries. Delegates to a recursive worker overload that walks the tree scope-by-scope: at every -compound-graph scope (the root graph, or any container node's own `Children` graph), the leaf -algorithm emits one box per node in that scope's own `Nodes` order, so a scope's placed boxes align -with that same scope's graph nodes by index (`LayoutBox` carries no `Id` to match by instead). The -worker decorates any box whose matching graph node is a recorded truncation, and otherwise — when -that graph node itself owns children and the placed box has its own nested children — recurses one -level deeper into that box's own `Children` against the graph node's own `Children.Nodes`. This is -what lets a truncated nested-definition-containment placeholder (potentially several levels deep — -inside a folder, inside another definition, or both) be found and decorated exactly like a -root-level truncated package folder, not just the ones directly on the root graph. +compound-graph scope (the root graph, or any container node's own `Children` graph) the engine emits +one box per node of that scope, possibly interleaved with the lines of the scope's own routed +edges, and not necessarily in node order. `LayoutBox` carries no `Id`, so each placed box is paired +with the graph node of that same scope it came from — by the shared `PairBoxesWithNodes` enumerator, +which `ComputeItemOrder`'s `CollectCenters` also uses so both agree on which node a box is — through +the identity signature the strategy itself set +on the node and the engine copies verbatim onto the box — `Label`, `Keyword`, and `Shape`: each box +takes the first not-yet-paired node with an equal signature, so the pairing does not depend on box +order. Nodes with an equal signature (only duplicated, never-truncated nodes can have one; a +truncated folder's simple name is unique among its siblings, and a truncated definition's ellipsis +placeholder is the only child of its scope) pair in order, and a box with no signature match falls +back to the first unpaired node. The worker decorates any box whose paired graph node is a recorded +truncation, and otherwise — when that graph node itself owns children and the placed box has its own +nested children — recurses one level deeper into that box's own `Children` against the graph node's +own `Children.Nodes`. This is what lets a truncated nested-definition-containment placeholder or a +truncated nested package folder (potentially several levels deep — inside a folder, inside another +definition, or both) be found and decorated exactly like a root-level truncated package folder, not +just the ones directly on the root graph. ##### Error Handling diff --git a/docs/gallery/README.md b/docs/gallery/README.md index 0470a283..9712af19 100644 --- a/docs/gallery/README.md +++ b/docs/gallery/README.md @@ -269,10 +269,11 @@ Model: [`models/10-mission-control-expose-recursion.sysml`](models/10-mission-co ![Operator Console Deep View](png/OperatorConsoleDeepView.png) `GroundSegmentDirectChildrenView` (`expose GroundSegment::*;`, NamespaceDirectChildren) -exposes only `GroundSegment`'s direct members, one level deep: `OperatorConsole` and -`ThermalRegulator` appear, but neither `OperatorConsole`'s own nested definitions nor -`RadioNetwork`'s nested `Uplink`/`Downlink` (both two levels below `GroundSegment`) do — -and `GroundSegment` itself is not included either. +exposes only `GroundSegment`'s direct members, one level deep: `OperatorConsole`, `ThermalRegulator`, +and the `RadioNetwork` package itself (drawn as an empty package node, since its own members +`Uplink`/`Downlink` are two levels below `GroundSegment` and so are not exposed) appear, but neither +`OperatorConsole`'s own nested definitions nor `RadioNetwork`'s contents do — and `GroundSegment` +itself is not included either. Model: [`models/10-mission-control-expose-recursion.sysml`](models/10-mission-control-expose-recursion.sysml) (`GroundSegmentDirectChildrenView`) · @@ -282,11 +283,10 @@ SVG: [`svg/GroundSegmentDirectChildrenView.svg`](svg/GroundSegmentDirectChildren `GroundSegmentRecursiveView` (`expose GroundSegment::*::**;`, NamespaceRecursive) exposes every descendant of `GroundSegment`, recursively — `OperatorConsole`, `DisplayPanel`, -`CommsHandset`, `ThermalRegulator`, `Uplink`, and `Downlink` all appear. `RadioNetwork` -is a bare `package`, not a definition, so it is never itself rendered as a box; its members -`Uplink`/`Downlink` are in scope and render as flat top-level boxes with no `RadioNetwork` -wrapper. `GroundSegment` (also a bare package) is excluded from scope and, like -`RadioNetwork`, shows no folder either. +`CommsHandset`, `ThermalRegulator`, `Uplink`, and `Downlink` all appear. `RadioNetwork` is +itself a descendant of `GroundSegment`, so it is drawn as a package folder around its members +`Uplink`/`Downlink`. `GroundSegment` (also a bare package) is excluded from scope and shows no +folder. Model: [`models/10-mission-control-expose-recursion.sysml`](models/10-mission-control-expose-recursion.sysml) (`GroundSegmentRecursiveView`) · SVG: [`svg/GroundSegmentRecursiveView.svg`](svg/GroundSegmentRecursiveView.svg) @@ -303,6 +303,44 @@ Model: [`models/10-mission-control-expose-recursion.sysml`](models/10-mission-co > around `Battery` in `BatterySubsystemView`, since `QuadcopterDrone` itself was never exposed — > only `Battery` was. +The unscoped `MissionControlGeneralView` in the same model draws the whole hierarchy: the +`MissionControl` folder holds the `GroundSegment` and `SpaceSegment` folders, and +`GroundSegment` in turn holds the `RadioNetwork` folder beside the `OperatorConsole` and +`ThermalRegulator` boxes, because a nested package is drawn inside its owner's folder. + +Model: [`models/10-mission-control-expose-recursion.sysml`](models/10-mission-control-expose-recursion.sysml) +(`MissionControlGeneralView`) · SVG: [`svg/MissionControlGeneralView.svg`](svg/MissionControlGeneralView.svg) + +![Mission Control General View: SpaceSegment and GroundSegment folders, with RadioNetwork nested inside GroundSegment, all inside the MissionControl folder](png/MissionControlGeneralView.png) + +--- + +## 11. General View — Nested Packages and Cross-Package Edges + +Shows how a General View draws a package hierarchy. The `Vehicle` package owns two nested +packages, `Powertrain` and `Body`, which are drawn as folders **inside** the `Vehicle` folder +rather than beside it, together with `Car`, a definition owned by `Vehicle` itself. + +Every relationship between two drawn definitions is drawn as a connector between the two +definition boxes themselves, whichever packages they are in. `Hybrid :> Powertrain::Engine` +is a specialization that crosses from the `Body` package into the `Powertrain` package, and +`Car`'s `engine : Powertrain::Engine` and `chassis : Body::Chassis` parts draw filled-diamond +composition edges from the nested packages' definitions to the owner-level `Car` box. Each +connector is declared in the innermost container that encloses both of its ends (here the +`Vehicle` folder), so it leaves the nested folders and ends on the definition boxes, not on the +folder borders. Specializations inside one package (`ElectricMotor :> Engine`, +`SportsChassis :> Chassis`) stay inside that package's folder. + +The order of the definitions inside a folder follows where their relationships lead rather than the +order they were declared in: `Hybrid` is declared after `Chassis`, but its specialization leads into +the nearer `Powertrain` folder while `Chassis`'s composition leads past it to `Car`, so `Hybrid` is +drawn above `Chassis` and the connectors do not cross. + +Model: [`models/11-nested-packages-general.sysml`](models/11-nested-packages-general.sysml) · +SVG: [`svg/VehiclePackagesGeneralView.svg`](svg/VehiclePackagesGeneralView.svg) + +![Vehicle Packages General View: Powertrain and Body folders nested inside the Vehicle folder, with the Hybrid specialization and the Engine and Chassis compositions into Car drawn between the definition boxes](png/VehiclePackagesGeneralView.png) + --- ## View coverage @@ -319,3 +357,4 @@ Model: [`models/10-mission-control-expose-recursion.sysml`](models/10-mission-co | 8 | Nested Interconnection View | Computer System | ✅ | | 9 | Multi-Port Interconnection View | Motor/Controller Rig | ✅ | | 10 | Geometry View | — | Deferred (requires spatial coordinate data) | +| 11 | General View — Nested Packages | Vehicle Packages | ✅ | diff --git a/docs/gallery/models/11-nested-packages-general.sysml b/docs/gallery/models/11-nested-packages-general.sysml new file mode 100644 index 00000000..498a8c4d --- /dev/null +++ b/docs/gallery/models/11-nested-packages-general.sysml @@ -0,0 +1,30 @@ +package Vehicle { + + // Two packages nested inside the Vehicle package. A General View draws each nested + // package as a folder inside its owner's folder, instead of beside it. + package Powertrain { + part def Engine; + + // A specialization inside one nested package: both definitions share a folder. + part def ElectricMotor :> Engine; + } + + package Body { + part def Chassis; + part def SportsChassis :> Chassis; + + // A specialization across two sibling packages: Hybrid specializes Powertrain's + // Engine from Body's folder, so the edge crosses between the two nested folders. + part def Hybrid :> Powertrain::Engine; + } + + // Car is owned by the outer Vehicle package and typed by definitions from both nested + // packages. Its parts draw composition edges from the nested definitions out to the + // owner-level Car box, crossing the nested folders' borders. + part def Car { + part engine : Powertrain::Engine; + part chassis : Body::Chassis; + } + + view def VehiclePackagesGeneralView {} +} diff --git a/docs/gallery/png/GroundSegmentDirectChildrenView.png b/docs/gallery/png/GroundSegmentDirectChildrenView.png index cdff7a5c..f7873ebd 100644 Binary files a/docs/gallery/png/GroundSegmentDirectChildrenView.png and b/docs/gallery/png/GroundSegmentDirectChildrenView.png differ diff --git a/docs/gallery/png/GroundSegmentRecursiveView.png b/docs/gallery/png/GroundSegmentRecursiveView.png index 1b907605..0d13c225 100644 Binary files a/docs/gallery/png/GroundSegmentRecursiveView.png and b/docs/gallery/png/GroundSegmentRecursiveView.png differ diff --git a/docs/gallery/png/MissionControlGeneralView.png b/docs/gallery/png/MissionControlGeneralView.png index 4856f080..f3bf42c1 100644 Binary files a/docs/gallery/png/MissionControlGeneralView.png and b/docs/gallery/png/MissionControlGeneralView.png differ diff --git a/docs/gallery/png/VehiclePackagesGeneralView.png b/docs/gallery/png/VehiclePackagesGeneralView.png new file mode 100644 index 00000000..674d9a02 Binary files /dev/null and b/docs/gallery/png/VehiclePackagesGeneralView.png differ diff --git a/docs/gallery/svg/GroundSegmentDirectChildrenView.svg b/docs/gallery/svg/GroundSegmentDirectChildrenView.svg index 1afe19ff..9bc4ea13 100644 --- a/docs/gallery/svg/GroundSegmentDirectChildrenView.svg +++ b/docs/gallery/svg/GroundSegmentDirectChildrenView.svg @@ -1,4 +1,4 @@ - + @@ -36,4 +36,7 @@ «part def» ThermalRegulator + + «package» + RadioNetwork diff --git a/docs/gallery/svg/GroundSegmentRecursiveView.svg b/docs/gallery/svg/GroundSegmentRecursiveView.svg index 914f0110..08ae5dc7 100644 --- a/docs/gallery/svg/GroundSegmentRecursiveView.svg +++ b/docs/gallery/svg/GroundSegmentRecursiveView.svg @@ -1,4 +1,4 @@ - + @@ -30,22 +30,25 @@ - - «part def» - OperatorConsole - - «part def» - DisplayPanel - - «part def» - CommsHandset - - «part def» - Uplink - - «part def» - Downlink - - «part def» - ThermalRegulator + + «package» + RadioNetwork + + «part def» + Uplink + + «part def» + Downlink + + «part def» + OperatorConsole + + «part def» + DisplayPanel + + «part def» + CommsHandset + + «part def» + ThermalRegulator diff --git a/docs/gallery/svg/MissionControlGeneralView.svg b/docs/gallery/svg/MissionControlGeneralView.svg index 57bf26fd..33e8f363 100644 --- a/docs/gallery/svg/MissionControlGeneralView.svg +++ b/docs/gallery/svg/MissionControlGeneralView.svg @@ -1,4 +1,4 @@ - + @@ -30,34 +30,37 @@ - - «package» - RadioNetwork - - «part def» - Uplink - - «part def» - Downlink - - «package» - GroundSegment - - «part def» - OperatorConsole - - «part def» - DisplayPanel - - «part def» - CommsHandset - - «part def» - ThermalRegulator - - «package» - SpaceSegment - - «part def» - Payload + + «package» + MissionControl + + «package» + GroundSegment + + «part def» + OperatorConsole + + «part def» + DisplayPanel + + «part def» + CommsHandset + + «part def» + ThermalRegulator + + «package» + RadioNetwork + + «part def» + Uplink + + «part def» + Downlink + + «package» + SpaceSegment + + «part def» + Payload diff --git a/docs/gallery/svg/VehiclePackagesGeneralView.svg b/docs/gallery/svg/VehiclePackagesGeneralView.svg new file mode 100644 index 00000000..62d9d340 --- /dev/null +++ b/docs/gallery/svg/VehiclePackagesGeneralView.svg @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + «package» + Vehicle + + «part def» + Car + + parts + engine : Powertrain::Engine + chassis : Body::Chassis + + «package» + Powertrain + + «part def» + Engine + + «part def» + ElectricMotor + + + «package» + Body + + «part def» + Hybrid + + «part def» + SportsChassis + + «part def» + Chassis + + + + + diff --git a/docs/reqstream/ots/dema-rendering.yaml b/docs/reqstream/ots/dema-rendering.yaml index 287b5334..337b4739 100644 --- a/docs/reqstream/ots/dema-rendering.yaml +++ b/docs/reqstream/ots/dema-rendering.yaml @@ -99,3 +99,35 @@ sections: - PngRenderer_Render_EmptyTree_WritesPngBytes - DiagramRenderer_RenderWorkspace_SoftwareStructureModel_PngRenderer_ReturnsPngOutput - DiagramRenderer_RenderWorkspace_GeneralViewModel_PngProducesValidOutput + + - id: SysML2Tools-OTS-DemaRendering-CrossHierarchyEdges + title: >- + DemaConsulting.Rendering shall route an edge declared on a graph scope between two + nodes that sit at any depth beneath that scope, connecting the endpoint nodes + themselves rather than the containers that hold them. + justification: | + The General View declares each relationship in the lowest common ancestor scope of + its two endpoints, which may be several packages above them. The relationship is + only readable if the package connects the endpoint boxes themselves: connecting the + enclosing package borders, or dropping the edge when its endpoints are in different + containers, would hide relationships between definitions of different packages. + Version 0.3.0-beta.2 of the package family introduced this behavior. + tags: [ots] + tests: + - GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_SiblingPackages_DeclaredAtRootAndRoutedToNestedBoxes + - GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_NestedVersusOuter_DeclaredInOuterScope + + - id: SysML2Tools-OTS-DemaRendering-ComponentOrderFollowsInsertion + title: >- + DemaConsulting.Rendering shall stack the unconnected groups of nodes inside a layered + container in the order the nodes were added to it. + justification: | + The General View cannot make the engine place a package folder's contents with + knowledge of where the folder's outgoing relationships lead, so it controls the + stacking by the order in which it adds the folder's definitions. That is only a sound + mechanism while the package keeps ordering such groups by insertion order; this + requirement pins the behavior so that an upgrade that changes it fails here instead of + silently reintroducing relationship crossings. + tags: [ots] + tests: + - LayeredLayoutAlgorithm_Layout_ContainerContents_StackUnconnectedGroupsByInsertionOrder diff --git a/docs/reqstream/quality.yaml b/docs/reqstream/quality.yaml index 4b03d1f8..8cd41765 100644 --- a/docs/reqstream/quality.yaml +++ b/docs/reqstream/quality.yaml @@ -123,3 +123,5 @@ sections: - SysML2Tools-OTS-DemaRendering-Routing - SysML2Tools-OTS-DemaRendering-RenderSvg - SysML2Tools-OTS-DemaRendering-RenderPng + - SysML2Tools-OTS-DemaRendering-CrossHierarchyEdges + - SysML2Tools-OTS-DemaRendering-ComponentOrderFollowsInsertion diff --git a/docs/reqstream/sysml2-tools-core/layout/internal.yaml b/docs/reqstream/sysml2-tools-core/layout/internal.yaml index 0f6eaa8a..33e1fd5c 100644 --- a/docs/reqstream/sysml2-tools-core/layout/internal.yaml +++ b/docs/reqstream/sysml2-tools-core/layout/internal.yaml @@ -40,6 +40,10 @@ sections: - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-Redefinition-NoEdgeOnFailure - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-AnnotationNote - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-ExposedPackageNodes + - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-NestedPackageFolders + - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-CrossContainerEdges + - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-ExternalEdgeOrdering + - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-TruncatedContainerDecoration - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-SameNamedDefinitions - SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-RequirementConstraintCompartments - SysML2Tools-Core-Layout-Internal-InterconnectionViewLayoutStrategy-Internals diff --git a/docs/reqstream/sysml2-tools-core/layout/internal/general-view-layout-strategy.yaml b/docs/reqstream/sysml2-tools-core/layout/internal/general-view-layout-strategy.yaml index 1fbc396b..89189d70 100644 --- a/docs/reqstream/sysml2-tools-core/layout/internal/general-view-layout-strategy.yaml +++ b/docs/reqstream/sysml2-tools-core/layout/internal/general-view-layout-strategy.yaml @@ -592,7 +592,9 @@ sections: In an `expose`-scoped view, GeneralViewLayoutStrategy shall draw each package that is itself exposed (`expose P;` or `expose P::**;`) and satisfies the view conditions as a package node containing whichever - of its members are also exposed — an empty package node when none are — and shall not draw + of its members are also exposed — an empty package node when none are — drawing an + exposed package that is nested inside another exposed package inside that package's node, + and shall not draw a package that is only an ancestor of exposed elements (`expose P::*;` exposes P's members but not P). justification: | @@ -606,3 +608,86 @@ sections: - GeneralViewLayoutStrategy_BuildLayout_ViewConditionOnExposedPackage_KeepsOrRemovesPackageNode - GeneralViewLayoutStrategy_BuildLayout_NamespaceExpose_DrawsMembersWithoutPackageNode - GeneralViewLayoutStrategy_BuildLayout_RecursivePackageExpose_DrawsPackageNodeWithMembers + - GeneralViewLayoutStrategy_BuildLayout_ScopedExpose_NestedExposedPackageInsideOwner + + - id: SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-NestedPackageFolders + title: >- + GeneralViewLayoutStrategy shall draw a package that is nested inside another drawn + package as a folder inside the owning package's folder, shall draw an enclosing + package's folder even when that package owns no definitions directly, and shall count + each enclosing package folder as one nesting level when applying the depth limit. + justification: | + A nested package is part of its owner. Drawing it as a separate folder beside the owner + hides that ownership and, because the layout can then only relate the two folders as + peers, prevents relationships between their members from being drawn in the owner's + context. Counting every enclosing folder as a nesting level keeps the depth limit + consistent with how definitions nested inside definitions are already counted, and a + collapsed folder must still account for everything it hides. + tests: + - GeneralViewLayoutStrategy_BuildLayout_NestedPackage_RendersInsideOwnerFolder + - GeneralViewLayoutStrategy_BuildLayout_NestedPackage_ParentWithoutDirectItems_CreatesEnclosingFolder + - GeneralViewLayoutStrategy_BuildLayout_NestedPackages_DepthLimit_CountsPackageNesting + - GeneralViewLayoutStrategy_BuildLayout_NestedPackagesGalleryModel_RendersFoldersNestedAndCrossPackageEdges + + - id: SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-CrossContainerEdges + title: >- + GeneralViewLayoutStrategy shall draw every model relationship whose two endpoints are both + drawn, including one whose endpoints lie in different packages or at different nesting + depths, as a connector between the two endpoint boxes themselves, declared in the + innermost container that encloses both endpoints, shall keep two distinct relationships + between the same two definitions as two separate connectors in every container, and + shall draw none for a relationship that touches a depth-truncated definition. + justification: | + Relationships between definitions of different packages (a specialization across + sibling packages, a part typed by a definition of a nested package) are core model + structure. Declaring each in the lowest common ancestor scope lets the layout engine + route it to the actual endpoint boxes instead of dropping it or stopping at a package + border; a relationship to a hidden definition has no box to connect to. The connector + order is then refined so that the connectors do not cross (see ExternalEdgeOrdering). + tests: + - GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_SiblingPackages_DeclaredAtRootAndRoutedToNestedBoxes + - GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_NestedVersusOuter_DeclaredInOuterScope + - GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_SiblingNestedPackages_DeclaredInCommonParent + - GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_DeepNestingAcrossTopLevelPackages_DrawsEdge + - GeneralViewLayoutStrategy_BuildLayout_EdgeBetweenContainerAndOwnDescendant_DoesNotThrow + - GeneralViewLayoutStrategy_BuildLayout_NestedPackages_DepthLimit_EdgeToTruncatedPackageIsDropped + - GeneralViewLayoutStrategy_BuildLayout_ParallelEdgesInNestedPackage_AreNotMerged + - GeneralViewLayoutStrategy_BuildLayout_ParallelEdgesInDefinitionContainer_AreNotMerged + - GeneralViewLayoutStrategy_BuildLayout_NestedPackagesGalleryModel_RendersFoldersNestedAndCrossPackageEdges + + - id: SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-ExternalEdgeOrdering + title: >- + GeneralViewLayoutStrategy shall order the definitions inside a package folder by the + vertical position of the boxes their relationships lead to outside that folder, so that + relationships leaving the folder do not need to cross one another and the picture does + not depend on the order the definitions were declared in. + justification: | + The layout engine places a container's contents without knowing where that container's + outgoing relationships lead, and stacks unconnected groups of those contents in the order + they were added. Adding definitions in declaration order therefore lets an arbitrary + declaration order force relationship crossings. Ordering them by their relationships' + targets is the standard crossing-reduction (barycenter) heuristic. A definition without + external relationships, a folder without any, and a relationship to a hidden definition + leave the order untouched. + tests: + - GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_OrderFolderItemsByPartnerPosition + - GeneralViewLayoutStrategy_BuildLayout_NoExternalEdges_KeepsDeclarationOrder + - GeneralViewLayoutStrategy_BuildLayout_ExternalEdgeToTruncatedPartner_DoesNotThrowAndKeepsOrder + - GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_DeepNesting_FollowsPartnerContainerOrder + - GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_DefinitionToSiblingNestedPackages_OrdersByPartnerFolder + - GeneralViewLayoutStrategy_BuildLayout_NestedPackagesGalleryModel_RendersFoldersNestedAndCrossPackageEdges + + - id: SysML2Tools-Core-Layout-Internal-GeneralViewLayoutStrategy-TruncatedContainerDecoration + title: >- + GeneralViewLayoutStrategy shall label each depth-truncated package folder or definition + with the number of elements it hides on that container's own placed box, independent of + the order in which the layout engine emits a scope's boxes. + justification: | + The "+N more…" label tells the reader that content was collapsed by the depth limit. A + label attached to the wrong box (because the engine emitted boxes in a different order + than the nodes were added) would misreport which container is collapsed and how much it + hides. + tests: + - GeneralViewLayoutStrategy_DecorateTruncated_LineBeforeBoxes_DoesNotBreakBoxToNodePairing + - GeneralViewLayoutStrategy_DecorateTruncated_BoxOrderDiffersFromNodeOrder_DecoratesMatchingNode + - GeneralViewLayoutStrategy_BuildLayout_NestedPackages_DepthLimit_CountsPackageNesting diff --git a/docs/user_guide/introduction.md b/docs/user_guide/introduction.md index a7e6c537..ccc52f05 100644 --- a/docs/user_guide/introduction.md +++ b/docs/user_guide/introduction.md @@ -246,6 +246,12 @@ An Interconnection View that exposes several independent systems (for example `expose SystemA::**; expose SystemB::**;`) draws every system's frame side by side, in declaration order. +A General View draws a package nested inside another package as a folder inside its owner's +folder, and it draws every relationship between two drawn definitions — including a +specialization or typing that crosses from one package into another — as a connector between the +two definition boxes themselves. The repository's diagram gallery shows both in the example +`11-nested-packages-general.sysml`. + ## View Body Statements A `view def`/`view` declaration's body may contain `render ;` and `filter [];` @@ -527,7 +533,11 @@ a single line). The `lint` command does not lay views out, so it does not report Use `--walk-depth ` to limit the nesting depth rendered. Parts beyond the limit are replaced with an ellipsis footer (`+N more…`). Silent omission is never used — truncation is always -visible in the output. +visible in the output. In a General View every enclosing package counts as one nesting level, the +same as a definition nested inside another definition: with `--walk-depth 1` each top-level package +is drawn collapsed, and with `--walk-depth 2` its own definitions are drawn while its nested +packages are collapsed. A collapsed package reports everything it hides, including nested packages, +in its `+N more…` label, and relationships to hidden definitions are not drawn. ```bash sysml2tools render model.sysml --output out --walk-depth 3 diff --git a/docs/verification/ots/dema-rendering.md b/docs/verification/ots/dema-rendering.md index b4423e33..c74e8418 100644 --- a/docs/verification/ots/dema-rendering.md +++ b/docs/verification/ots/dema-rendering.md @@ -21,7 +21,10 @@ SysML2Tools: SysML2Tools relies on the family to lay a graph of sized nodes and directed edges out into placed boxes and routed orthogonal connectors, honor the requested layout direction (including a top-to-bottom flow), pack container regions, route connectors around the boxes it places, and -render a layout tree to both SVG and PNG. +render a layout tree to both SVG and PNG, and route an edge declared on an ancestor graph scope +between the nested endpoint nodes themselves (cross-hierarchy edges, available since version +0.3.0-beta.2), and stack the unconnected groups of a layered container's contents in the order the +nodes were added. ### Verification Approach @@ -163,3 +166,37 @@ package's `PngRenderer`. **Expected**: A valid PNG image is produced. **Requirement coverage**: `SysML2Tools-OTS-DemaRendering-RenderPng`. + +#### GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_SiblingPackages_DeclaredAtRootAndRoutedToNestedBoxes + +**Scenario**: Two sibling top-level packages each own a definition, and one definition specializes +the other. The General View strategy declares the specialization edge on the root graph scope with +the two nested definition nodes as its endpoints. + +**Expected**: The package returns the edge as a routed connector at the root scope whose first and +last waypoints lie on the borders of the two definition boxes, not on the package folder borders. + +**Requirement coverage**: `SysML2Tools-OTS-DemaRendering-CrossHierarchyEdges`. + +#### GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_NestedVersusOuter_DeclaredInOuterScope + +**Scenario**: A package owns a definition and a nested package whose definition specializes the +owner's definition. The strategy declares the edge on the owner folder's own child scope with a node +inside the nested folder as one endpoint. + +**Expected**: The package returns the connector inside the owner folder's children, running from +the nested definition's box to the owner's definition box. + +**Requirement coverage**: `SysML2Tools-OTS-DemaRendering-CrossHierarchyEdges`. + +#### LayeredLayoutAlgorithm_Layout_ContainerContents_StackUnconnectedGroupsByInsertionOrder + +**Scenario**: A layered package-folder container holds a specialization pair (`S` specializing `C`) +and an otherwise unconnected node `H`, and has relationships leaving it at the root scope. The nodes are +added to the container in the order `C`, `S`, `H` in one run and `H`, `C`, `S` in another. + +**Expected**: The package stacks the unconnected group in insertion order: `H` is placed below `C` in the +first run and above `C` in the second. This is the behavior the General View's ordering refinement +relies on; an upgrade that changes it fails this scenario. + +**Requirement coverage**: `SysML2Tools-OTS-DemaRendering-ComponentOrderFollowsInsertion`. diff --git a/docs/verification/sysml2-tools-core/layout/internal/general-view-layout-strategy.md b/docs/verification/sysml2-tools-core/layout/internal/general-view-layout-strategy.md index 8732b71c..de30d8c9 100644 --- a/docs/verification/sysml2-tools-core/layout/internal/general-view-layout-strategy.md +++ b/docs/verification/sysml2-tools-core/layout/internal/general-view-layout-strategy.md @@ -162,6 +162,33 @@ configuration are required beyond a standard .NET SDK installation. quality re-validation (Retry 2): exactly 2 boxes render (`A` and `c`), `b` never appears as its own box, and `c` is never silently dropped merely because its immediate parent was itself excluded in the same pass. +- A package nested in another drawn package appears as a folder inside the owning package's + folder (as the owner box's own `Children`), never as a separate folder beside it; an enclosing + package that owns no definitions directly still gets its folder when a nested package is drawn; + in a scoped view a nested exposed package sits inside its exposed owner, and only the nearest + exposed enclosing package (or the root, when none is exposed) holds it. +- A model relationship between two drawn definitions is drawn as a single connector between the two + endpoint boxes themselves — across sibling packages, between a nested package and its owner, + and across any depth of nesting — declared in the innermost container scope that encloses both + endpoints (the root for sibling top-level packages, the owner folder for a nested-versus-outer or + sibling-subpackage pair); a relationship between a definition and a definition it contains lays + out without error. +- The depth limit counts each enclosing package folder as one nesting level: a limit of 1 collapses + the top-level folder (its label reports every hidden definition and nested package), a limit of 2 + keeps the top-level folder's own definitions and collapses the nested folder, and a relationship to + a definition hidden by the limit draws no connector. +- A "+N more…" truncation label is attached to the box of the truncated node regardless of the order + in which the layout engine emitted a scope's boxes, at the root and inside nested containers. +- The gallery model `docs/gallery/models/11-nested-packages-general.sysml` renders `Powertrain` and + `Body` folders inside the `Vehicle` folder with the cross-package specialization and the + compositions into `Car` drawn in the `Vehicle` scope between the actual endpoint boxes, with no two + connectors of the drawing crossing and `Hybrid` stacked above `Chassis`. +- The definitions inside a package folder are stacked in the order of the boxes their relationships + lead to outside the folder (a definition leading to a nearer box above one leading to a farther + box), independent of declaration order, with no crossing between the connectors of the + nested-package example; a folder with no relationship leaving it keeps declaration order; a + relationship to a partner hidden by the depth limit does not disturb the layout; and the partner + position is measured at the level where the two meet however deeply the partner is nested. ##### Test Scenarios @@ -401,3 +428,59 @@ configuration are required beyond a standard .NET SDK installation. bare package `QuadcopterDrone`, exposed via `expose Battery;` (exact match) — no folder-shaped box exists and the `Battery` box is present directly at the root level, the primary Defect B correctness guard +- `GeneralViewLayoutStrategy_BuildLayout_NestedPackage_RendersInsideOwnerFolder`: + `package P { part def A; package Sub { part def B; } }` renders one root folder `P` holding the `A` + box and a `Sub` folder (which holds `B`), and no `Sub` folder at the root +- `GeneralViewLayoutStrategy_BuildLayout_NestedPackage_ParentWithoutDirectItems_CreatesEnclosingFolder`: + `Outer { Inner { Deep { X } } }` renders three nested folders around `X` and nothing else at the root, + although `Outer` and `Inner` own no definitions +- `GeneralViewLayoutStrategy_BuildLayout_ScopedExpose_NestedExposedPackageInsideOwner`: + `expose P::**;` draws `Sub` inside `P`; `expose P::Sub::**;` draws `Sub` at the root with no `P` folder +- `GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_SiblingPackages_DeclaredAtRootAndRoutedToNestedBoxes`: + A specialization between definitions of two sibling top-level packages is exactly one line at the root + scope, starting on the specializing box and ending on the supertype box +- `GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_NestedVersusOuter_DeclaredInOuterScope`: + A nested-package definition specializing an owner-package definition yields one line among the owner + folder's children (none at the root or in the nested folder), ending on both boxes +- `GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_SiblingNestedPackages_DeclaredInCommonParent`: + A specialization between two sibling nested packages is declared in their common parent folder +- `GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_DeepNestingAcrossTopLevelPackages_DrawsEdge`: + A definition three packages deep specializing a definition of another top-level package is drawn at + the root between the two boxes, beside an unpackaged definition +- `GeneralViewLayoutStrategy_BuildLayout_EdgeBetweenContainerAndOwnDescendant_DoesNotThrow`: + A definition related to a definition it contains lays out without error with both boxes present +- `GeneralViewLayoutStrategy_BuildLayout_NestedPackages_DepthLimit_CountsPackageNesting`: + Depth limit 1 collapses `P` to `+4 more…`; limit 2 keeps `A` and collapses `Sub` to `+2 more…`; limit 3 + and no limit show everything with no truncation label +- `GeneralViewLayoutStrategy_BuildLayout_NestedPackages_DepthLimit_EdgeToTruncatedPackageIsDropped`: + A relationship into a nested package collapsed by the depth limit draws no line and does not throw +- `GeneralViewLayoutStrategy_DecorateTruncated_BoxOrderDiffersFromNodeOrder_DecoratesMatchingNode`: + With the placed boxes (and a line) in a different order than the graph nodes, at the root and inside a + nested container, only the box of the truncated node carries the "+N more…" label +- `GeneralViewLayoutStrategy_BuildLayout_NestedPackagesGalleryModel_RendersFoldersNestedAndCrossPackageEdges`: + The gallery model `11-nested-packages-general.sysml` draws `Powertrain` and `Body` inside `Vehicle`, the + `Hybrid` to `Engine` specialization and both compositions into `Car` in the `Vehicle` scope between the + endpoint boxes, with `Hybrid` above `Chassis` and zero crossings between the lines of the whole drawing +- `GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_OrderFolderItemsByPartnerPosition`: + The nested-package model with `Hybrid` declared last and again first in `Body` places `Hybrid` above + `Chassis` in both and draws no crossing connectors, so the picture does not depend on declaration order +- `GeneralViewLayoutStrategy_BuildLayout_NoExternalEdges_KeepsDeclarationOrder`: + A package with unconnected definitions and a specialization pair and no relationship leaving it + keeps its declaration order (`Zeta` before `Alpha` before `Beta`) +- `GeneralViewLayoutStrategy_BuildLayout_ExternalEdgeToTruncatedPartner_DoesNotThrowAndKeepsOrder`: + A relationship into a nested package collapsed by the depth limit gives the definition no ordering + key; the layout completes, both definitions of the folder are drawn in declaration order, and the + hidden partner's box is absent +- `GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_DeepNesting_FollowsPartnerContainerOrder`: + Two definitions of `A::B` leading into `Lo::In` and `Hi::In` are stacked in the same vertical order + as the `Lo` and `Hi` folders, for both declaration orders +- `GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_DefinitionToSiblingNestedPackages_OrdersByPartnerFolder`: + Two definitions of package `P` specializing definitions of sibling nested packages `A` and `B` are + stacked in the same vertical order as those folders, for both declaration orders, with zero crossings + (the relationships stay inside `P`'s scope, which the engine orders itself) +- `GeneralViewLayoutStrategy_BuildLayout_ParallelEdgesInNestedPackage_AreNotMerged`: + Two attributes of the same type inside a nested package give two separate typing connectors, so + parallel-edge merging stays off in nested folder scopes +- `GeneralViewLayoutStrategy_BuildLayout_ParallelEdgesInDefinitionContainer_AreNotMerged`: + Two attributes of the same nested type inside a definition container give two separate typing + connectors, so parallel-edge merging stays off in definition-container scopes diff --git a/src/DemaConsulting.SysML2Tools.Core/DemaConsulting.SysML2Tools.Core.csproj b/src/DemaConsulting.SysML2Tools.Core/DemaConsulting.SysML2Tools.Core.csproj index 7714a027..c041aad2 100644 --- a/src/DemaConsulting.SysML2Tools.Core/DemaConsulting.SysML2Tools.Core.csproj +++ b/src/DemaConsulting.SysML2Tools.Core/DemaConsulting.SysML2Tools.Core.csproj @@ -53,7 +53,7 @@ - + diff --git a/src/DemaConsulting.SysML2Tools.Core/Layout/Internal/GeneralViewLayoutStrategy.cs b/src/DemaConsulting.SysML2Tools.Core/Layout/Internal/GeneralViewLayoutStrategy.cs index 7d5cdd6e..30bf44b4 100644 --- a/src/DemaConsulting.SysML2Tools.Core/Layout/Internal/GeneralViewLayoutStrategy.cs +++ b/src/DemaConsulting.SysML2Tools.Core/Layout/Internal/GeneralViewLayoutStrategy.cs @@ -17,8 +17,9 @@ namespace DemaConsulting.SysML2Tools.Layout.Internal; /// /// Layout strategy for GeneralView diagrams. Renders every user-defined def element /// (part, port, interface, requirement, action, …) as a keyword-labeled box, groups boxes by -/// their owning package inside folder-shaped containers, and routes specialization, membership, and -/// attribute-typing edges orthogonally between the boxes. +/// their owning package inside folder-shaped containers (a nested package inside its owner's +/// folder), and routes specialization, membership, and +/// attribute-typing edges orthogonally between the boxes, whichever packages their endpoints sit in. /// /// /// Every definition and package folder is expressed as a single — packages @@ -38,7 +39,10 @@ namespace DemaConsulting.SysML2Tools.Layout.Internal; /// ): depth-limited (truncated) content is never added to the graph as /// individual boxes — the truncated folder or definition body becomes (or gains) a single leaf /// node sized like a plain ellipsis indicator, and the "+N more…" label is stamped onto its placed -/// box once the layout is known. +/// box once the layout is known. Because the engine places a folder's contents without knowing where +/// the folder's external relationships lead, the items of each package folder are ordered by the +/// vertical position of those relationships' far ends (see ), so +/// relationships leaving a folder do not need to cross one another. /// internal sealed class GeneralViewLayoutStrategy : ILayoutStrategy { @@ -201,8 +205,80 @@ private sealed record DefBox( IReadOnlyList Annotations, bool IsUsage); - /// Where a located definition's node lives: the node itself and its owning package. - private readonly record struct Location(LayoutGraphNode Node, string Package); + /// + /// One container scope of the layout graph: the root graph, a package folder's own + /// graph, or a definition-as-container's own + /// graph. The scopes form a tree through + /// (the root scope's parent is ), which is what + /// walks to find the scope an edge belongs to. Scopes are compared + /// by reference identity. + /// + /// The enclosing scope, or for the root scope. + /// The layout graph holding this scope's own nodes (and the edges declared in it). + /// + /// The container node whose graph this scope is, or + /// for the root scope. The external-edge anchor lookup uses it to find + /// which direct member of a common scope contains a given box. + /// + private sealed class ScopeInfo(ScopeInfo? parent, LayoutGraph graph, LayoutGraphNode? owner = null) + { + /// Gets the enclosing scope, or for the root scope. + public ScopeInfo? Parent { get; } = parent; + + /// Gets the layout graph holding this scope's own nodes. + public LayoutGraph Graph { get; } = graph; + + /// Gets the container node that owns this scope's graph, or for the root scope. + public LayoutGraphNode? Owner { get; } = owner; + } + + /// Where a located definition's node lives: the node itself and the scope that directly holds it. + private readonly record struct Location(LayoutGraphNode Node, ScopeInfo Scope); + + /// + /// The result of one pass: the input graph together with the + /// bookkeeping the second, order-refining pass needs (). + /// + /// The root layout graph, ready to be handed to the layout engine. + /// The depth-truncated containers to decorate once the layout is known. + /// Every definition's node and directly holding scope, keyed by qualified name. + /// The planned package folders, keyed by package qualified name. + private sealed record GraphBuild( + LayoutGraph Graph, + List Truncated, + IReadOnlyDictionary Located, + IReadOnlyDictionary Plans); + + /// + /// The planned shape of one package folder, computed before any graph node is created so the + /// folders can then be materialized parent-first. + /// + /// The folder's package qualified name. + /// + /// The qualified name of the nearest enclosing folder, or when the folder + /// sits directly on the root scope. + /// + /// The definitions owned directly by the package (empty for a pure enclosing folder). + private sealed class FolderPlan(string key, string? parentKey, IReadOnlyList items) + { + /// Gets the folder's package qualified name. + public string Key { get; } = key; + + /// Gets the nearest enclosing folder's key, or for a root-level folder. + public string? ParentKey { get; } = parentKey; + + /// Gets the definitions owned directly by the package. + public IReadOnlyList Items { get; } = items; + + /// Gets the keys of the folders nested directly inside this one, in drawing order. + public List ChildKeys { get; } = []; + + /// Gets or sets the number of enclosing folders (0 for a root-level folder). + public int NestingLevel { get; set; } + + /// Gets or sets the number of hidden elements reported when this folder is truncated. + public int SubtreeCount { get; set; } + } /// /// A package folder or nested-definition container whose contents were depth-truncated: @@ -382,8 +458,11 @@ bool AnnotationVisible(string ownerQualifiedName, string metaclass) => // node (because its folder was depth-truncated). var (modelEdges, droppedEdges) = BuildModelEdges(defs, context.Workspace, scope is not null); - // Build the single input graph: package folders as containers, definitions as leaves. - var (graph, truncated) = BuildGraph(groups, childrenByParent, modelEdges, theme, options.DepthLimit, scope is not null ? exposedPackages : null); + // Build the single input graph: package folders as containers (nested packages inside their + // owner's folder), definitions as leaves. + var packageNames = CollectPackageNames(context.Workspace); + var exposed = scope is not null ? exposedPackages : null; + var build = BuildGraph(groups, childrenByParent, modelEdges, theme, options.DepthLimit, exposed, packageNames, itemOrder: null); // Lay out the whole graph in one call, delegating root-scope algorithm selection to "auto": // it classifies the root's own folders/top-level definitions by connectivity, routing @@ -391,15 +470,29 @@ bool AnnotationVisible(string ownerQualifiedName, string metaclass) => // reading order (containment) — the same per-container-algorithm convention this strategy // already applies per folder, just resolved automatically at the root instead of being pinned // to a single fixed algorithm for every root-scope node regardless of its own connectivity. - graph.Set(CoreOptions.Algorithm, AutoLayoutAlgorithm.AlgorithmId); - var tree = LayoutEngine.Layout(graph); + var tree = LayOut(build.Graph); + + // The engine lays out each package folder's contents without knowing where the folder's + // relationships to the outside lead, and stacks unconnected groups of those contents in the + // order they were added - so declaration order alone can force relationships that leave a + // folder to cross one another. Refine once: reorder each folder's items by the vertical + // position (in the first layout) of the boxes their external relationships lead to, and lay + // out again with that order. When no folder's order changes the first layout is kept as is. + // NOTE: this compensates for the engine's SeparateChildren placement model and can be retired + // when the engine orders a container's interior by its cross-hierarchy edges. + var itemOrder = ComputeItemOrder(tree, build, modelEdges); + if (itemOrder.Count > 0) + { + build = BuildGraph(groups, childrenByParent, modelEdges, theme, options.DepthLimit, exposed, packageNames, itemOrder); + tree = LayOut(build.Graph); + } // Stamp the "+N more…" ellipsis label onto each truncated folder's or truncated - // definition's placed box. The leaf algorithm emits one box per node in Nodes order at - // every scope (root graph and every container's own Children graph alike), so the boxes - // portion of the placed tree aligns with the corresponding graph's Nodes by index at every - // nesting depth, not just the root. - var placed = truncated.Count == 0 ? tree : DecorateTruncated(tree, graph, truncated, theme); + // definition's placed box. Every placed box is paired with its graph node by identity + // (label, keyword, shape) within its own scope rather than by position, so the pairing + // does not depend on the order in which the engine emits a scope's boxes; this recurses + // through every nesting depth, not just the root. + var placed = build.Truncated.Count == 0 ? tree : DecorateTruncated(tree, build.Graph, build.Truncated, theme); // Surface any standalone `filter [];` evaluation failure, plus a distinct warning // for each `expose ::**[]` bracket filter that failed to parse or evaluate @@ -443,6 +536,27 @@ private static HashSet CollectExposedPackages(SysmlWorkspace workspace, return result; } + /// + /// Returns the qualified names of every non-stdlib package declared in the workspace, whether or + /// not the view exposes it. uses it to recognize which qualified-name + /// prefixes are packages, so an unscoped view can draw an enclosing package's folder even when + /// the package owns no definitions directly. + /// + private static HashSet CollectPackageNames(SysmlWorkspace workspace) + { + var result = new HashSet(StringComparer.Ordinal); + foreach (var (qualifiedName, declaration) in workspace.Declarations) + { + if (declaration is SysmlPackageNode && + !StdlibFilter.IsStdlibElement(qualifiedName, workspace.StdlibNames)) + { + result.Add(qualifiedName); + } + } + + return result; + } + /// /// Collects every user-defined (and every named /// usage, at any nesting depth) from the workspace and computes @@ -1400,7 +1514,11 @@ public bool TryResolveSupertype( /// Builds the single input : each package becomes a folder container /// node holding its definitions as leaves (or, when depth-truncated, a single leaf ellipsis /// placeholder); top-level (unpackaged) definitions become leaves directly on the root graph. - /// A definition that owns nested definitions () becomes a + /// A package nested inside another package is drawn inside its owner's folder: folders are + /// materialized parent-first, a nested package's folder node is added to its nearest enclosing + /// folder's own scope, and an enclosing package that + /// owns no definitions directly still gets its folder whenever one of its nested packages is + /// drawn. A definition that owns nested definitions () becomes a /// genuine container in its own right — its nested definitions are placed inside its own node's /// scope (recursively, to any depth) via /// , instead of being handed to a second time @@ -1409,36 +1527,53 @@ public bool TryResolveSupertype( /// holding its children). When is non-null (the view is /// narrowed by a resolved expose scope), only a package that is itself exposed (SysML /// 8.3.26.3: expose P; or expose P::**;) becomes a package node — an empty leaf - /// package node when none of its members are exposed — while a package that is only an ancestor - /// of admitted content is never rendered as a wrapping folder: its items are promoted directly - /// onto the root graph instead, exactly like top-level (unpackaged) definitions. When - /// is null, every bare package still becomes a - /// folder, unchanged from the pre-fix behavior. Model edges are added once every definition's - /// node placement is known: an edge whose endpoints share the same non-empty container scope - /// (a package folder or a definition-as-container) is added to that scope (an intra-container - /// edge the layered algorithm can use to order the container's contents); every other edge — - /// including one whose endpoints sit in different containers, even when one container is nested - /// inside the other — is added at the root, referencing the descendant nodes directly (this is - /// an exact container-scope-key match, not a genuine lowest-common-ancestor search). An edge - /// touching a depth-truncated (unrendered) definition has no node to reference and is dropped, - /// exactly as before. caps nesting depth uniformly whether the - /// extra nesting comes from a package folder or from a definition containing another - /// definition: package-folder contents and top-level/scoped-promoted items placed directly by - /// this method sit at depth 1 (the pre-existing convention — see truncateFolderContents - /// below), and every level of nested-definition containment recurses into - /// is one depth deeper again (a definition's immediate nested children sit at depth 2, its - /// grandchildren at depth 3, and so on) — see 's own remarks for how that - /// deeper truncation is applied. + /// package node when it has neither exposed members nor exposed nested packages — while a + /// package that is only an ancestor of admitted content is never rendered as a wrapping + /// folder: its items are promoted directly onto the root graph instead, exactly like top-level + /// (unpackaged) definitions, and a nested exposed package attaches to its nearest exposed + /// enclosing package (or to the root when none is exposed). When + /// is null, every package that owns definitions, together with every enclosing package + /// recognized through , becomes a folder. Model edges are added + /// once every definition's node placement is known: each edge is declared in the scope at the + /// lowest common ancestor of its two endpoints' scopes (see ), + /// referencing the endpoint nodes directly even when they sit several containers deep, so the + /// layout engine routes it between the actual endpoint boxes — across sibling packages, + /// between a nested package and its owner, and across any depth of nesting. An edge touching a + /// depth-truncated (unrendered) definition has no node to reference and is dropped. + /// caps nesting depth uniformly whether the extra nesting comes + /// from a package folder or from a definition containing another definition: a top-level + /// folder's contents and top-level/scoped-promoted items placed directly on the root sit at depth + /// 1, each enclosing folder adds one further level (a nested folder's contents sit at depth 2, + /// and so on), and every level of nested-definition containment + /// recurses into is one depth deeper again — see 's own remarks for how that + /// deeper truncation is applied. A truncated folder is a single ellipsis leaf that reports the + /// number of hidden definitions and nested packages. /// - private static (LayoutGraph Graph, List Truncated) BuildGraph( + /// The package groups (package qualified name and its directly owned definitions). + /// Definitions nested inside a definition, keyed by the owning definition's qualified name. + /// The model relationships to draw as graph edges. + /// The theme used to size title bands and ellipsis placeholders. + /// The nesting depth limit, or a non-positive value for none. + /// The exposed packages of a scoped view, or null for an unscoped view. + /// Every package the workspace declares, used to recognize enclosing packages. + /// + /// Optional per-folder item order (package qualified name to the folder's definition qualified + /// names in the wanted order) produced by ; null keeps declaration + /// order. A folder or name it does not know is ignored. + /// + /// The graph and the bookkeeping for decoration and order refinement. + private static GraphBuild BuildGraph( IReadOnlyList<(string Package, List Items)> groups, IReadOnlyDictionary> childrenByParent, IReadOnlyList modelEdges, Theme theme, int depthLimit, - IReadOnlySet? exposedPackages) + IReadOnlySet? exposedPackages, + IReadOnlySet packageNames, + IReadOnlyDictionary>? itemOrder) { var graph = new LayoutGraph(); + var rootScope = new ScopeInfo(null, graph); // The General View intentionally draws one edge per source model relationship even when // several distinct edges share the same source and target node (for example two attributes @@ -1446,7 +1581,8 @@ private static (LayoutGraph Graph, List Truncated) BuildGrap // between the same two definitions) — unlike InterconnectionViewLayoutStrategy, this graph // has never relied on the bundled algorithm's parallel-edge merging, so it opts out // explicitly to keep every distinct model relationship visible regardless of the layered - // algorithm's own default. + // algorithm's own default. The option cascades from this root to every nested folder and + // definition-container scope (edges are declared in those scopes too), so it is set once here. graph.Set(CoreOptions.MergeParallelEdges, false); var truncated = new List(); @@ -1454,101 +1590,103 @@ private static (LayoutGraph Graph, List Truncated) BuildGrap // label never overlaps the first child box; the renderer draws the smaller tab notch within. var folderTitleHeight = BoxMetrics.TitleAreaHeight(theme, hasLabel: true, hasKeyword: true); - // Folder contents (and top-level or scoped-promoted items placed directly here) sit at - // depth 1 - the baseline every PlaceDef call below starts from. Nested-definition - // containment recursion goes one depth deeper per level from there. + // Folder contents (and top-level or scoped-promoted items placed directly on the root) sit at + // depth 1 - the baseline every PlaceDef call below starts from; each enclosing folder adds + // one level, and nested-definition containment recursion goes one depth deeper per level. const int rootDepth = 1; - var truncateFolderContents = depthLimit > 0 && depthLimit <= rootDepth; - // Every located definition's node and owning container scope key, so edges can be resolved - // and scoped. + // Every located definition's node and the scope directly holding it, so edges can be scoped + // to their lowest common ancestor. var located = new Dictionary(StringComparer.Ordinal); - // Each non-truncated container's own child scope, keyed by its scope key (a package name, or - // an admitted definition's own qualified name when it owns nested definitions), so - // same-container edges can be added there instead of at the root. - var containerScopes = new Dictionary(StringComparer.Ordinal); + var (plans, steps) = PlanFolders(groups, exposedPackages, packageNames); - for (var g = 0; g < groups.Count; g++) - { - var (package, items) = groups[g]; - var isFolder = !string.IsNullOrEmpty(package); + // Each materialized (non-truncated, non-leaf) folder's own child scope, keyed by package + // name. A folder absent from this map is a truncated placeholder (or hidden beneath one). + var folderScopes = new Dictionary(StringComparer.Ordinal); - if (!isFolder) + foreach (var (folderKey, groupIndex) in steps) + { + if (folderKey is null) { - // Top-level (unpackaged) items: plain leaves directly on the root graph, recursing - // through PlaceDef so any of these items' own nested-definition children are still - // handled. - foreach (var def in items) + // A top-level (unpackaged) item, or an item of a package the scoped view does not + // expose: promoted directly onto the root graph through PlaceDef so any of its own + // nested-definition children are still handled. + foreach (var def in groups[groupIndex].Items) { - PlaceDef(def, graph, package, childrenByParent, located, containerScopes, theme, rootDepth, depthLimit, truncated); + PlaceDef(def, rootScope, childrenByParent, located, theme, rootDepth, depthLimit, truncated); } continue; } - if (exposedPackages is not null && !exposedPackages.Contains(package)) + var plan = plans[folderKey]; + ScopeInfo parentScope; + if (plan.ParentKey is null) { - // The view is narrowed by a resolved expose scope and this package is not itself - // exposed: it is never rendered as a wrapping folder purely because it is an - // ancestor of admitted content — promote its items directly to the root graph. - foreach (var def in items) - { - PlaceDef(def, graph, package, childrenByParent, located, containerScopes, theme, rootDepth, depthLimit, truncated); - } - + parentScope = rootScope; + } + else if (!folderScopes.TryGetValue(plan.ParentKey, out parentScope!)) + { + // The enclosing folder is a truncated placeholder: this folder was already counted + // in its hidden-element total and is not drawn. continue; } - if (items.Count == 0) + var label = SimplePackageName(folderKey); + if (plan.Items.Count == 0 && plan.ChildKeys.Count == 0) { - // An exposed package with no exposed members (checked before - // depth truncation, which has nothing to hide here): a leaf package node (name inside) - // sized to its label, since an empty container has no contents to size it. - var label = SimplePackageName(package); + // An exposed package with no exposed members (checked before depth truncation, + // which has nothing to hide here): a leaf package node (name inside) sized to its + // label, since an empty container has no contents to size it. var width = Math.Max(MinBoxWidth, (label.Length * theme.FontSizeTitle * CharWidthFactor) + (4.0 * theme.LabelPadding)); - var packageNode = graph.AddNode($"folder:{package}", width, folderTitleHeight + theme.FontSizeTitle + (2.0 * theme.LabelPadding)); + var packageNode = parentScope.Graph.AddNode($"folder:{folderKey}", width, folderTitleHeight + theme.FontSizeTitle + (2.0 * theme.LabelPadding)); packageNode.Label = label; packageNode.Shape = BoxShape.Folder; packageNode.Keyword = "package"; continue; } - if (truncateFolderContents) + // The depth of this folder's own contents: one level per enclosing folder, plus one. + var contentDepth = rootDepth + plan.NestingLevel; + if (depthLimit > 0 && depthLimit <= contentDepth) { - // Replace the folder's definition boxes with a single leaf ellipsis indicator. It - // stays a leaf (its Children graph is never touched) so the hierarchical engine keeps - // this caller-computed size rather than auto-sizing it as a container. - var (ellipsisWidth, ellipsisHeight) = ComputeEllipsisSize(items.Count, theme); - var placeholder = graph.AddNode($"folder:{package}", ellipsisWidth, folderTitleHeight + ellipsisHeight); - placeholder.Label = SimplePackageName(package); + // Replace the folder's contents (definitions and nested packages) with a single leaf + // ellipsis indicator. It stays a leaf (its Children graph is never touched) so the + // hierarchical engine keeps this caller-computed size rather than auto-sizing it as + // a container. + var (ellipsisWidth, ellipsisHeight) = ComputeEllipsisSize(plan.SubtreeCount, theme); + var placeholder = parentScope.Graph.AddNode($"folder:{folderKey}", ellipsisWidth, folderTitleHeight + ellipsisHeight); + placeholder.Label = label; placeholder.Shape = BoxShape.Folder; placeholder.Keyword = "package"; - truncated.Add(new TruncatedContainer(placeholder, items.Count, folderTitleHeight)); + truncated.Add(new TruncatedContainer(placeholder, plan.SubtreeCount, folderTitleHeight)); - // None of the folder's definitions receive a node: every edge touching one is dropped. + // None of the folder's contents receive a node: every edge touching one is dropped. continue; } - var folder = graph.AddNode($"folder:{package}", 0, 0); - folder.Label = SimplePackageName(package); + var folder = parentScope.Graph.AddNode($"folder:{folderKey}", 0, 0); + folder.Label = label; folder.Shape = BoxShape.Folder; folder.Keyword = "package"; folder.TitleHeight = folderTitleHeight; folder.Set(CoreOptions.Algorithm, LayeredLayoutAlgorithm.AlgorithmId); - containerScopes[package] = folder.Children; + var folderScope = new ScopeInfo(parentScope, folder.Children, folder); + folderScopes[folderKey] = folderScope; - foreach (var def in items) + foreach (var def in OrderedItems(plan, itemOrder)) { - PlaceDef(def, folder.Children, package, childrenByParent, located, containerScopes, theme, rootDepth, depthLimit, truncated); + PlaceDef(def, folderScope, childrenByParent, located, theme, contentDepth, depthLimit, truncated); } } - // Add every model edge whose endpoints both received a node: an edge whose endpoints share - // the same non-empty container scope key is scoped to that container's own scope; every - // other edge — including one whose endpoints sit in different containers, even when one - // container is nested inside the other — is added at the root graph instead (an exact - // scope-key match, not a genuine lowest-common-ancestor search). + // Add every model edge whose endpoints both received a node, declared in the scope at the + // lowest common ancestor of the two endpoints' scopes. Both endpoints may be nested several + // containers below that scope; the layout engine routes the edge between the endpoint nodes + // themselves. An edge between a container and one of its own descendants has the + // container's own enclosing scope as its lowest common ancestor and is not drawn by the + // engine (the containment is already visible). var edgeId = 0; foreach (var edge in modelEdges) { @@ -1558,23 +1696,159 @@ private static (LayoutGraph Graph, List Truncated) BuildGrap continue; } - var scope = source.Package.Length > 0 && - source.Package == target.Package && - containerScopes.TryGetValue(source.Package, out var containerScope) - ? containerScope - : graph; - - var added = scope.AddEdge($"e{edgeId++}", source.Node, target.Node); + var added = LowestCommonScope(source.Scope, target.Scope).Graph.AddEdge($"e{edgeId++}", source.Node, target.Node); added.TargetEnd = edge.Arrowhead; added.LineStyle = LineStyleForKind(edge.Kind); added.Label = edge.Label; } - return (graph, truncated); + return new GraphBuild(graph, truncated, located, plans); } /// - /// Places a single definition's node into , then recursively + /// Returns a folder's items in the order the layout engine should receive them: the order named + /// by for the folder when one exists, otherwise declaration order. + /// Names the folder does not own are ignored and items the order omits keep their relative + /// declaration order after the named ones, so a stale or partial order can never drop a + /// definition from the drawing. + /// + private static IReadOnlyList OrderedItems(FolderPlan plan, IReadOnlyDictionary>? itemOrder) + { + if (itemOrder is null || !itemOrder.TryGetValue(plan.Key, out var wanted)) + { + return plan.Items; + } + + var byName = plan.Items.ToDictionary(d => d.QualifiedName, StringComparer.Ordinal); + var names = wanted.Where(byName.ContainsKey).Distinct(StringComparer.Ordinal).ToList(); + var ordered = names.Select(name => byName[name]).ToList(); + var named = names.ToHashSet(StringComparer.Ordinal); + ordered.AddRange(plan.Items.Where(d => !named.Contains(d.QualifiedName))); + return ordered; + } + + /// + /// Returns the innermost scope that encloses both and + /// (a scope encloses itself). Both scopes must belong to the same scope tree, so the root scope + /// is always a common ancestor. + /// + private static ScopeInfo LowestCommonScope(ScopeInfo a, ScopeInfo b) + { + var ancestorsOfA = new HashSet(ReferenceEqualityComparer.Instance); + for (var scope = a; scope is not null; scope = scope.Parent) + { + ancestorsOfA.Add(scope); + } + + var common = b; + while (!ancestorsOfA.Contains(common)) + { + common = common.Parent ?? throw new InvalidOperationException("Scopes belong to different scope trees."); + } + + return common; + } + + /// Returns the qualified name before the last :: of , or null when it has no separator. + private static string? EnclosingPackage(string qualifiedName) + { + var separator = qualifiedName.LastIndexOf("::", StringComparison.Ordinal); + return separator > 0 ? qualifiedName[..separator] : null; + } + + /// + /// Plans the package folders before any graph node exists: which packages become folders (every + /// package that owns drawn definitions, plus every enclosing package recognized through + /// or, in a scoped view, ), how + /// they nest, and the order in which they and the promoted (non-folder) groups are materialized + /// — an enclosing folder always precedes everything nested in it. + /// + /// + /// The plans keyed by package name, and the ordered materialization steps: a non-null folder key, + /// or a null folder key plus the index of a entry whose items are placed + /// directly on the root scope. + /// + private static (Dictionary Plans, List<(string? FolderKey, int GroupIndex)> Steps) PlanFolders( + IReadOnlyList<(string Package, List Items)> groups, + IReadOnlySet? exposedPackages, + IReadOnlySet packageNames) + { + // Packages that may serve as an enclosing folder: the exposed ones in a scoped view, + // otherwise every package the workspace declares. + var eligibleAncestors = exposedPackages ?? packageNames; + + // Pass 1: decide the folder set and its order (ancestors first). + var itemsByFolder = new Dictionary>(StringComparer.Ordinal); + var folderOrder = new List(); + var steps = new List<(string? FolderKey, int GroupIndex)>(); + + for (var g = 0; g < groups.Count; g++) + { + var (package, items) = groups[g]; + if (string.IsNullOrEmpty(package) || (exposedPackages is not null && !exposedPackages.Contains(package))) + { + steps.Add((null, g)); + continue; + } + + // Each enclosing package that is eligible gets its folder (outermost first) before the + // first thing nested in it, even when it owns no definitions directly. + var separator = package.IndexOf("::", StringComparison.Ordinal); + while (separator > 0) + { + var ancestor = package[..separator]; + if (eligibleAncestors.Contains(ancestor) && !itemsByFolder.ContainsKey(ancestor)) + { + itemsByFolder[ancestor] = []; + folderOrder.Add(ancestor); + steps.Add((ancestor, g)); + } + + separator = package.IndexOf("::", separator + 2, StringComparison.Ordinal); + } + + // A folder first added as a pure ancestor takes its own items here, keeping its position. + var firstAdded = !itemsByFolder.ContainsKey(package); + itemsByFolder[package] = items; + if (firstAdded) + { + folderOrder.Add(package); + steps.Add((package, g)); + } + } + + // Pass 2: nest each folder in its nearest enclosing folder. + var plans = new Dictionary(StringComparer.Ordinal); + foreach (var key in folderOrder) + { + var parentKey = EnclosingPackage(key); + while (parentKey is not null && !plans.ContainsKey(parentKey)) + { + parentKey = EnclosingPackage(parentKey); + } + + var plan = new FolderPlan(key, parentKey, itemsByFolder[key]); + if (parentKey is not null) + { + plans[parentKey].ChildKeys.Add(key); + plan.NestingLevel = plans[parentKey].NestingLevel + 1; + } + + plans[key] = plan; + } + + // Pass 3: hidden-element counts, children before parents (reverse materialization order). + for (var i = folderOrder.Count - 1; i >= 0; i--) + { + var plan = plans[folderOrder[i]]; + plan.SubtreeCount = plan.Items.Count + plan.ChildKeys.Sum(child => 1 + plans[child].SubtreeCount); + } + + return (plans, steps); + } + + /// + /// Places a single definition's node into , then recursively /// places every nested definition that owns as its immediate parent (see /// ) inside 's own node's /// scope — to any nesting depth, one level per recursive @@ -1594,28 +1868,27 @@ private static (LayoutGraph Graph, List Truncated) BuildGrap /// ) is placed inside 's own /// scope instead, so /// caps nested-definition containment depth exactly as it already caps package-folder nesting. - /// A truncated definition still registers no entry (nothing + /// A truncated definition creates no child scope (nothing /// is ever placed inside its scope beyond the ellipsis leaf, so no intra-container edge could /// ever resolve there); an edge touching one of the hidden children has no /// entry to reference and is dropped, exactly like a depth-truncated package folder's contents. - /// Otherwise, its scope key is registered in so intra-container - /// edges between its own nested children resolve to its scope rather than the root. + /// Otherwise, a child (enclosed by ) is created for + /// its nested children, so an edge between them — or between one of them and any node elsewhere — + /// resolves to the lowest common scope rather than always the root. /// private static void PlaceDef( DefBox def, - LayoutGraph targetScope, - string packageKeyForEdgeScoping, + ScopeInfo scope, IReadOnlyDictionary> childrenByParent, Dictionary located, - Dictionary containerScopes, Theme theme, int depth, int depthLimit, List truncated) { - var node = MakeDefNode(targetScope, def); - located[def.QualifiedName] = new Location(node, packageKeyForEdgeScoping); - AddAnnotationNote(targetScope, def, node, theme); + var node = MakeDefNode(scope.Graph, def); + located[def.QualifiedName] = new Location(node, scope); + AddAnnotationNote(scope.Graph, def, node, theme); if (!childrenByParent.TryGetValue(def.QualifiedName, out var children)) { @@ -1638,11 +1911,11 @@ private static void PlaceDef( return; } - containerScopes[def.QualifiedName] = node.Children; + var childScope = new ScopeInfo(scope, node.Children, node); foreach (var child in children) { - PlaceDef(child, node.Children, def.QualifiedName, childrenByParent, located, containerScopes, theme, childDepth, depthLimit, truncated); + PlaceDef(child, childScope, childrenByParent, located, theme, childDepth, depthLimit, truncated); } } @@ -1771,19 +2044,17 @@ private static LayoutTree DecorateTruncated( /// /// Recursive worker for : - /// walks one graph scope's placed nodes, matching each encountered (in - /// order) against that same scope's (in order) — the leaf - /// algorithm at any compound-graph scope, root or nested, emits exactly one box per node in - /// that scope's own Nodes order, but may also intersperse - /// entries for that scope's own routed edges among those boxes at arbitrary positions (see - /// e.g. LayeredPlacement's tree.Nodes.OfType<LayoutBox>()/ - /// OfType<LayoutLine>() filtering elsewhere in this codebase) — so the two lists - /// are matched by tracking a separate box-only cursor into - /// (advanced only when a is actually encountered), rather than by a - /// single shared index, which would fall out of sync permanently after the first interspersed line. - /// carries no Id to match by directly, so this relative-order - /// pairing is the only mechanism available. Decorates any box whose matching graph node is a - /// recorded truncation and recurses into every other container box's own children. + /// walks one graph scope's placed nodes and pairs each with the graph + /// node of that same scope it was placed from. carries no Id, so + /// the pairing is by the identity signature the strategy itself set on the graph node and the + /// engine copies verbatim onto the box: , + /// and . Each box takes the + /// first not-yet-paired graph node with an equal signature, so the pairing does not depend on the + /// order in which the engine emits a scope's boxes, nor on where it intersperses + /// entries for the scope's own routed edges. Nodes that share a + /// signature (which only duplicated, never-truncated nodes can) pair in order, and a box with no + /// signature match falls back to the first unpaired node. Decorates any box whose paired graph + /// node is a recorded truncation and recurses into every other container box's own children. /// private static List DecorateTruncated( IReadOnlyList nodes, @@ -1792,16 +2063,8 @@ private static List DecorateTruncated( Theme theme) { var result = new List(nodes); - var graphIndex = 0; - for (var i = 0; i < result.Count && graphIndex < graphNodes.Count; i++) + foreach (var (i, box, graphNode) in PairBoxesWithNodes(nodes, graphNodes)) { - if (result[i] is not LayoutBox box) - { - continue; - } - - var graphNode = graphNodes[graphIndex++]; - if (hiddenByNode.TryGetValue(graphNode, out var hidden)) { var indicator = new LayoutLabel( @@ -1828,6 +2091,244 @@ private static List DecorateTruncated( return result; } + /// + /// Pairs every of one placed scope with the graph node of that same + /// scope it was placed from, yielding the box's index in , the box, and + /// its node. carries no Id, so the pairing is by the identity + /// signature the strategy itself set on the graph node and the engine copies verbatim onto the + /// box (see ); it is shared by the truncation decoration and + /// the item-order refinement so both agree on which node a box is. Non-box entries (routed lines) + /// and boxes with no node left to pair are skipped. + /// + private static IEnumerable<(int Index, LayoutBox Box, LayoutGraphNode Node)> PairBoxesWithNodes( + IReadOnlyList nodes, + IReadOnlyList graphNodes) + { + var paired = new bool[graphNodes.Count]; + for (var i = 0; i < nodes.Count; i++) + { + if (nodes[i] is not LayoutBox box) + { + continue; + } + + var graphIndex = FindUnpairedGraphNode(box, graphNodes, paired); + if (graphIndex < 0) + { + continue; + } + + paired[graphIndex] = true; + yield return (i, box, graphNodes[graphIndex]); + } + } + + /// + /// Returns the index of the first graph node not yet whose + /// , and + /// equal 's; when none matches, the + /// index of the first unpaired node; or -1 when every node is already paired. + /// + private static int FindUnpairedGraphNode(LayoutBox box, IReadOnlyList graphNodes, bool[] paired) + { + var firstUnpaired = -1; + for (var j = 0; j < graphNodes.Count; j++) + { + if (paired[j]) + { + continue; + } + + firstUnpaired = firstUnpaired < 0 ? j : firstUnpaired; + var candidate = graphNodes[j]; + if (candidate.Label == box.Label && candidate.Keyword == box.Keyword && candidate.Shape == box.Shape) + { + return j; + } + } + + return firstUnpaired; + } + + /// + /// Runs the layout engine over with the root scope delegated to the + /// "auto" algorithm, so both layout passes of are configured identically. + /// + private static LayoutTree LayOut(LayoutGraph graph) + { + graph.Set(CoreOptions.Algorithm, AutoLayoutAlgorithm.AlgorithmId); + return LayoutEngine.Layout(graph); + } + + /// + /// Computes, for every package folder whose items should be stacked differently, the item order + /// that keeps relationships leaving the folder from crossing one another: the folder's items + /// that have external relationships are ordered by the mean vertical center, in the first + /// layout (), of the boxes those relationships lead to. + /// + /// + /// The layered engine places a container's contents blind to the container's external edges and + /// stacks unconnected groups of those contents by insertion index, so it is the caller that must + /// supply the crossing-reducing (barycenter) order. Items without external relationships keep + /// their positions; the keyed items are sorted into the slots the keyed items occupied. Only + /// package-folder items are considered, the key is vertical only (every folder flows left to + /// right) and one refinement pass is made with no iteration, so the computation always + /// terminates and is a no-op, returning an empty result, whenever no folder's order changes. + /// + /// The first-pass layout. + /// The first-pass graph with its located nodes and folder plans. + /// The model edges the graph was built from. + /// Folder key to wanted item qualified-name order, only for folders whose order changes. + private static Dictionary> ComputeItemOrder( + LayoutTree tree, + GraphBuild build, + IReadOnlyList edges) + { + var order = new Dictionary>(StringComparer.Ordinal); + var centers = new Dictionary(); + CollectCenters(tree.Nodes, build.Graph.Nodes, centers); + + foreach (var plan in build.Plans.Values) + { + if (plan.Items.Count < 2) + { + continue; + } + + var keys = plan.Items.Select(item => ExternalPartnerKey(item.QualifiedName, build.Located, edges, centers)).ToList(); + var wanted = OrderByPartnerPosition(plan.Items, keys); + if (wanted is not null) + { + order[plan.Key] = wanted; + } + } + + return order; + } + + /// + /// Records the absolute vertical center of every placed box against the graph node it was placed + /// from, recursing through container boxes. Coordinates in the layout tree are absolute, so + /// centers of boxes in different scopes are directly comparable. + /// + private static void CollectCenters( + IReadOnlyList nodes, + IReadOnlyList graphNodes, + Dictionary centers) + { + foreach (var (_, box, graphNode) in PairBoxesWithNodes(nodes, graphNodes)) + { + centers[graphNode] = box.Y + (box.Height / 2.0); + if (graphNode.HasChildren && box.Children.Count > 0) + { + CollectCenters(box.Children, graphNode.Children.Nodes, centers); + } + } + } + + /// + /// Returns the mean vertical center of the boxes the external relationships of the definition + /// lead to, or when it has none that can be + /// placed (no relationship leaving its folder, or every partner is hidden by the depth limit). + /// + private static double? ExternalPartnerKey( + string name, + IReadOnlyDictionary located, + IReadOnlyList edges, + IReadOnlyDictionary centers) + { + if (!located.TryGetValue(name, out var self)) + { + return null; + } + + var sum = 0.0; + var count = 0; + foreach (var edge in edges) + { + var partnerName = PartnerOf(edge, name); + if (partnerName is null || !located.TryGetValue(partnerName, out var partner)) + { + continue; + } + + var anchor = ExternalAnchor(self.Scope, partner); + if (anchor is not null && centers.TryGetValue(anchor, out var center)) + { + sum += center; + count++; + } + } + + return count > 0 ? sum / count : null; + } + + /// Returns the other end of as seen from , or null when it does not touch it (or is a self-loop). + private static string? PartnerOf(ModelEdge edge, string name) + { + if (edge.SourceQualified == name && edge.TargetQualified != name) + { + return edge.TargetQualified; + } + + return edge.TargetQualified == name && edge.SourceQualified != name ? edge.SourceQualified : null; + } + + /// + /// Returns the node a relationship from a definition held by to + /// actually targets at the level where the two meet: the partner itself + /// when it is a direct member of the lowest common scope, otherwise the container (folder or + /// definition) that holds the partner and is a direct member of that scope. Returns null when the + /// relationship stays inside (the scope that holds the definition): + /// that scope's own layout sees the edge, so it needs no ordering key. + /// + private static LayoutGraphNode? ExternalAnchor(ScopeInfo selfScope, Location partner) + { + var common = LowestCommonScope(selfScope, partner.Scope); + if (ReferenceEquals(common, selfScope)) + { + return null; + } + + var anchor = partner.Node; + for (var scope = partner.Scope; !ReferenceEquals(scope, common); scope = scope.Parent!) + { + anchor = scope.Owner ?? anchor; + } + + return anchor; + } + + /// + /// Orders the items that have a key by that key (ties keep declaration order) into the slots the + /// keyed items occupied, leaving the items without a key where they are. Returns null when fewer than two + /// items have a key or the order does not change. + /// + private static List? OrderByPartnerPosition(IReadOnlyList items, IReadOnlyList keys) + { + var slots = Enumerable.Range(0, items.Count).Where(i => keys[i].HasValue).ToList(); + if (slots.Count < 2) + { + return null; + } + + // Round before comparing so sub-pixel differences between boxes that are effectively level + // do not reorder them (and thereby make the result depend on layout noise). + var sorted = slots.OrderBy(i => Math.Round(keys[i]!.Value)).ThenBy(i => i).ToList(); + if (sorted.SequenceEqual(slots)) + { + return null; + } + + var wanted = items.Select(item => item.QualifiedName).ToList(); + for (var k = 0; k < slots.Count; k++) + { + wanted[slots[k]] = items[sorted[k]].QualifiedName; + } + + return wanted; + } + /// Returns the last segment of a qualified package name for use as a folder label. private static string SimplePackageName(string package) { diff --git a/src/DemaConsulting.SysML2Tools.Tool/DemaConsulting.SysML2Tools.Tool.csproj b/src/DemaConsulting.SysML2Tools.Tool/DemaConsulting.SysML2Tools.Tool.csproj index 97a8b792..e03c89a1 100644 --- a/src/DemaConsulting.SysML2Tools.Tool/DemaConsulting.SysML2Tools.Tool.csproj +++ b/src/DemaConsulting.SysML2Tools.Tool/DemaConsulting.SysML2Tools.Tool.csproj @@ -87,8 +87,8 @@ - - + + diff --git a/test/DemaConsulting.SysML2Tools.Tests/DemaConsulting.SysML2Tools.Tests.csproj b/test/DemaConsulting.SysML2Tools.Tests/DemaConsulting.SysML2Tools.Tests.csproj index b9398d2b..827d4ead 100644 --- a/test/DemaConsulting.SysML2Tools.Tests/DemaConsulting.SysML2Tools.Tests.csproj +++ b/test/DemaConsulting.SysML2Tools.Tests/DemaConsulting.SysML2Tools.Tests.csproj @@ -63,8 +63,8 @@ - - + + diff --git a/test/DemaConsulting.SysML2Tools.Tests/Layout/GeneralViewLayoutStrategyTests.cs b/test/DemaConsulting.SysML2Tools.Tests/Layout/GeneralViewLayoutStrategyTests.cs index e889d258..fb76c151 100644 --- a/test/DemaConsulting.SysML2Tools.Tests/Layout/GeneralViewLayoutStrategyTests.cs +++ b/test/DemaConsulting.SysML2Tools.Tests/Layout/GeneralViewLayoutStrategyTests.cs @@ -5,6 +5,7 @@ using System.Reflection; using DemaConsulting.Rendering; using DemaConsulting.Rendering.Abstractions; +using DemaConsulting.Rendering.Layout; using DemaConsulting.SysML2Tools.Layout.Internal; using DemaConsulting.SysML2Tools.Rendering; using DemaConsulting.SysML2Tools.Semantic; @@ -2059,6 +2060,61 @@ public async Task GeneralViewLayoutStrategy_BuildLayout_DroneGalleryModel_Render Assert.Equal(21, boxes.Count); } + /// + /// The gallery's nested-package example (11-nested-packages-general.sysml) draws its + /// Powertrain and Body packages as folders inside the Vehicle folder, + /// declares the cross-package relationships in the Vehicle scope (the lowest common + /// ancestor of the nested packages and the owner-level Car), and routes each to its + /// actual endpoint boxes: the Hybrid to Engine specialization across the two + /// sibling packages and the composition edges from both nested packages into Car. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_NestedPackagesGalleryModel_RendersFoldersNestedAndCrossPackageEdges() + { + var galleryModelsRoot = FindGalleryModelsRoot(); + if (galleryModelsRoot is null) + { + return; + } + + var modelPath = Path.Combine(galleryModelsRoot, "11-nested-packages-general.sysml"); + if (!File.Exists(modelPath)) + { + return; + } + + var (stdlibTable, _) = StdlibProvider.GetSymbolTable(); + var result = await WorkspaceLoader.LoadAsync([modelPath], stdlibTable); + Assert.NotNull(result.Workspace); + + // Act + var layout = new GeneralViewLayoutStrategy().BuildLayout( + new ViewContext("v", result.Workspace), new RenderOptions(Themes.Light)); + + // Assert: one root folder holding both nested package folders and the owner-level Car box + var vehicle = Assert.Single(layout.Nodes.OfType()); + Assert.Equal("Vehicle", vehicle.Label); + var nestedFolders = vehicle.Children.OfType().Where(b => b.Shape == BoxShape.Folder).ToList(); + Assert.Equal(["Body", "Powertrain"], nestedFolders.Select(f => f.Label).Order().ToArray()); + Assert.Contains(vehicle.Children.OfType(), b => b.Label == "Car"); + + // Assert: the cross-package edges live in the Vehicle scope and end on the nested boxes + var hybrid = FindBox(layout.Nodes, "Hybrid"); + var engine = FindBox(layout.Nodes, "Engine"); + var car = FindBox(layout.Nodes, "Car"); + var crossSpecialization = Assert.Single(DirectSpecializationLines(vehicle.Children)); + Assert.True(RunsBetween(crossSpecialization, hybrid, engine)); + var compositions = vehicle.Children.OfType().Where(l => l.TargetEnd == EndMarkerStyle.FilledDiamond).ToList(); + Assert.Equal(2, compositions.Count); + Assert.Contains(compositions, l => RunsBetween(l, engine, car)); + Assert.Contains(compositions, l => RunsBetween(l, FindBox(layout.Nodes, "Chassis"), car)); + + // Assert: no two connectors cross - Hybrid is stacked above Chassis because its relationship + // leads to the nearer Powertrain folder while Chassis's leads past it to Car + Assert.Equal(0, CountLineCrossings(layout.Nodes)); + Assert.True(hybrid.Y < FindBox(layout.Nodes, "Chassis").Y); + } + /// /// Finds the repository's docs/gallery/models directory relative to the test /// assembly, mirroring 's upward path-walk convention. @@ -3381,7 +3437,9 @@ public void GeneralViewLayoutStrategy_DecorateTruncated_LineBeforeBoxes_DoesNotB // Arrange: two graph nodes at this scope — nodeA (kept) and nodeB (truncated, hiding 3 items) var graph = new LayoutGraph(); var nodeA = graph.AddNode("A", 100, 60); + nodeA.Label = "A"; var nodeB = graph.AddNode("B", 100, 60); + nodeB.Label = "B"; // A placed line (an intra-scope routed edge) appears before either box in the placed-node list var line = new LayoutLine( @@ -3428,5 +3486,653 @@ public void GeneralViewLayoutStrategy_DecorateTruncated_LineBeforeBoxes_DoesNotB var indicatorB = Assert.IsType(Assert.Single(resultBoxB.Children)); Assert.Equal("+3 more\u2026", indicatorB.Text); } + + /// + /// Loads and lays out an unscoped view (no expose: every + /// non-stdlib definition and package is drawn) with the general view strategy. + /// + private static async Task LayOutUnscopedAsync(string sysml, int depthLimit = 0) + { + var tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".sysml"); + try + { + await File.WriteAllTextAsync(tempFile, sysml, TestContext.Current.CancellationToken); + var (stdlibTable, _) = StdlibProvider.GetSymbolTable(); + var result = await WorkspaceLoader.LoadAsync([tempFile], stdlibTable); + Assert.NotNull(result.Workspace); + return new GeneralViewLayoutStrategy().BuildLayout( + new ViewContext("v", result.Workspace), new RenderOptions(Themes.Light, DepthLimit: depthLimit)); + } + finally + { + File.Delete(tempFile); + } + } + + /// Returns the single box labeled (optionally of ) anywhere in . + private static LayoutBox FindBox(IReadOnlyList nodes, string label, BoxShape? shape = null) => + Assert.Single(CollectBoxes(nodes), b => b.Label == label && (shape is null || b.Shape == shape)); + + /// Returns the hollow-triangle (specialization) lines among the direct nodes of a scope. + private static IReadOnlyList DirectSpecializationLines(IReadOnlyList scopeNodes) => + [.. scopeNodes.OfType().Where(l => l.TargetEnd == EndMarkerStyle.HollowTriangle)]; + + /// + /// True when the point lies on the border of (within a 2-pixel tolerance + /// for stroke and marker geometry): inside the box's outline and next to one of its four edges. + /// + private static bool OnBorder(double x, double y, LayoutBox box) + { + const double tolerance = 2.0; + var inside = x >= box.X - tolerance && x <= box.X + box.Width + tolerance && + y >= box.Y - tolerance && y <= box.Y + box.Height + tolerance; + var nearEdge = Math.Abs(x - box.X) <= tolerance || Math.Abs(x - (box.X + box.Width)) <= tolerance || + Math.Abs(y - box.Y) <= tolerance || Math.Abs(y - (box.Y + box.Height)) <= tolerance; + return inside && nearEdge; + } + + /// True when the line starts on 's border and ends on 's. + private static bool RunsBetween(LayoutLine line, LayoutBox source, LayoutBox target) => + OnBorder(line.Waypoints[0].X, line.Waypoints[0].Y, source) && + OnBorder(line.Waypoints[^1].X, line.Waypoints[^1].Y, target); + + /// + /// A package nested in another package is drawn inside its owner's folder (issue #87), not as a + /// separate folder beside it. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_NestedPackage_RendersInsideOwnerFolder() + { + // Act + var layout = await LayOutUnscopedAsync("package P { part def A; package Sub { part def B; } }"); + + // Assert: one root folder P, holding the A box and the Sub folder (which holds B) + var root = Assert.Single(layout.Nodes.OfType()); + Assert.Equal("P", root.Label); + Assert.Equal(BoxShape.Folder, root.Shape); + Assert.Contains(root.Children.OfType(), b => b.Label == "A"); + var sub = Assert.Single(root.Children.OfType(), b => b.Shape == BoxShape.Folder); + Assert.Equal("Sub", sub.Label); + Assert.Contains(sub.Children.OfType(), b => b.Label == "B"); + Assert.Single(CollectBoxes(layout.Nodes), b => b.Label == "Sub"); + } + + /// + /// An enclosing package that owns no definitions directly still gets its folder when a nested + /// package is drawn, at every nesting level. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_NestedPackage_ParentWithoutDirectItems_CreatesEnclosingFolder() + { + // Act + var layout = await LayOutUnscopedAsync("package Outer { package Inner { package Deep { part def X; } } }"); + + // Assert: Outer > Inner > Deep > X, three folders and nothing else at the root + var outer = Assert.Single(layout.Nodes.OfType()); + Assert.Equal("Outer", outer.Label); + var inner = Assert.Single(outer.Children.OfType()); + Assert.Equal("Inner", inner.Label); + Assert.Equal(BoxShape.Folder, inner.Shape); + var deep = Assert.Single(inner.Children.OfType()); + Assert.Equal("Deep", deep.Label); + Assert.Equal(BoxShape.Folder, deep.Shape); + Assert.Equal("X", Assert.Single(deep.Children.OfType()).Label); + Assert.Equal(3, CollectBoxes(layout.Nodes).Count(b => b.Shape == BoxShape.Folder)); + } + + /// + /// With expose P::**; the nested exposed package sits inside P's folder; with + /// expose P::Sub::**; only Sub is exposed, so it is drawn at the root with no P folder. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_ScopedExpose_NestedExposedPackageInsideOwner() + { + // Arrange + const string sysml = """ + package P { part def A; package Sub { part def B; } } + package Diagrams { + view Outer { expose P::**; } + view InnerOnly { expose P::Sub::**; } + } + """; + + // Act + var outer = await LayOutDeclaredViewAsync(sysml, "Outer"); + var innerOnly = await LayOutDeclaredViewAsync(sysml, "InnerOnly"); + + // Assert: nested inside P in the first view + var p = Assert.Single(outer.Nodes.OfType()); + Assert.Equal("P", p.Label); + Assert.Contains(p.Children.OfType(), b => b.Label == "Sub" && b.Shape == BoxShape.Folder); + + // Assert: Sub at the root, P not drawn, in the second + var sub = Assert.Single(innerOnly.Nodes.OfType()); + Assert.Equal("Sub", sub.Label); + Assert.DoesNotContain(CollectBoxes(innerOnly.Nodes), b => b.Label == "P"); + } + + /// + /// A specialization between definitions of two sibling top-level packages is drawn at the root + /// scope (their lowest common ancestor) and runs between the two definition boxes themselves, + /// not between the package folder borders. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_SiblingPackages_DeclaredAtRootAndRoutedToNestedBoxes() + { + // Act + var layout = await LayOutUnscopedAsync("package P1 { part def A; } package P2 { part def B :> P1::A; }"); + + // Assert + var line = Assert.Single(DirectSpecializationLines(layout.Nodes)); + Assert.True(RunsBetween(line, FindBox(layout.Nodes, "B"), FindBox(layout.Nodes, "A"))); + } + + /// + /// An edge between a definition in a nested package and one in the owner package is declared in + /// the owner's folder scope (the nested package is below it), and runs between the two boxes. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_NestedVersusOuter_DeclaredInOuterScope() + { + // Act + var layout = await LayOutUnscopedAsync("package P { part def A; package Sub { part def B :> A; } }"); + + // Assert: the line belongs to P's scope - not the root, not Sub's + var p = FindBox(layout.Nodes, "P"); + var sub = FindBox(layout.Nodes, "Sub"); + Assert.Empty(DirectSpecializationLines(layout.Nodes)); + Assert.Empty(DirectSpecializationLines(sub.Children)); + var line = Assert.Single(DirectSpecializationLines(p.Children)); + Assert.True(RunsBetween(line, FindBox(layout.Nodes, "B"), FindBox(layout.Nodes, "A"))); + } + + /// An edge between two sibling nested packages is declared in their common parent's scope. + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_SiblingNestedPackages_DeclaredInCommonParent() + { + // Act + var layout = await LayOutUnscopedAsync( + "package P { package S1 { part def A; } package S2 { part def B :> S1::A; } }"); + + // Assert + var p = FindBox(layout.Nodes, "P"); + Assert.Empty(DirectSpecializationLines(layout.Nodes)); + Assert.Empty(DirectSpecializationLines(FindBox(layout.Nodes, "S1").Children)); + Assert.Empty(DirectSpecializationLines(FindBox(layout.Nodes, "S2").Children)); + var line = Assert.Single(DirectSpecializationLines(p.Children)); + Assert.True(RunsBetween(line, FindBox(layout.Nodes, "B"), FindBox(layout.Nodes, "A"))); + } + + /// + /// An edge from a definition three packages deep to a definition in another top-level package + /// is declared at the root (their lowest common ancestor) and drawn between the two boxes, + /// even beside an unpackaged definition. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_CrossPackageEdge_DeepNestingAcrossTopLevelPackages_DrawsEdge() + { + // Act + var layout = await LayOutUnscopedAsync( + "package O { package M { package D { part def X :> Q::Y; } } } package Q { part def Y; } part def Loose;"); + + // Assert + var line = Assert.Single(DirectSpecializationLines(layout.Nodes)); + Assert.True(RunsBetween(line, FindBox(layout.Nodes, "X"), FindBox(layout.Nodes, "Y"))); + Assert.Contains(layout.Nodes.OfType(), b => b.Label == "Loose"); + } + + /// + /// A definition that contains a nested definition and is related to it (here through the typed + /// feature) has the container's own enclosing scope as its lowest common ancestor; the layout + /// completes without error and draws both boxes. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_EdgeBetweenContainerAndOwnDescendant_DoesNotThrow() + { + // Act + var layout = await LayOutUnscopedAsync("part def Car { part def Eng; part e : Eng; }"); + + // Assert + var car = FindBox(layout.Nodes, "Car"); + Assert.Contains(car.Children.OfType(), b => b.Label == "Eng"); + } + + /// The model for the nested-package depth-limit tests: P owns A and a Sub package of B and C. + private const string DepthLimitedNestedSysml = "package P { part def A; package Sub { part def B; part def C; } }"; + + /// + /// Each enclosing package counts as one nesting level, so a depth limit of 1 collapses the top + /// folder (counting the nested package's contents too), a limit of 2 keeps the owner's own + /// definitions but collapses the nested package, and a limit of 3 (or none) shows everything. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_NestedPackages_DepthLimit_CountsPackageNesting() + { + // Act + var limitOne = await LayOutUnscopedAsync(DepthLimitedNestedSysml, depthLimit: 1); + var limitTwo = await LayOutUnscopedAsync(DepthLimitedNestedSysml, depthLimit: 2); + var limitThree = await LayOutUnscopedAsync(DepthLimitedNestedSysml, depthLimit: 3); + var unlimited = await LayOutUnscopedAsync(DepthLimitedNestedSysml); + + // Assert: limit 1 - P collapses, hiding A, Sub, B and C + var folderOne = FindBox(limitOne.Nodes, "P"); + Assert.Equal("+4 more\u2026", Assert.IsType(Assert.Single(folderOne.Children)).Text); + Assert.DoesNotContain(CollectBoxes(limitOne.Nodes), b => b.Label is "A" or "Sub" or "B" or "C"); + + // Assert: limit 2 - A is drawn, Sub collapses to "+2 more…" + var folderTwo = FindBox(limitTwo.Nodes, "P"); + Assert.Contains(folderTwo.Children.OfType(), b => b.Label == "A"); + var subTwo = FindBox(limitTwo.Nodes, "Sub"); + Assert.Equal("+2 more\u2026", Assert.IsType(Assert.Single(subTwo.Children)).Text); + Assert.DoesNotContain(CollectBoxes(limitTwo.Nodes), b => b.Label is "B" or "C"); + + // Assert: limit 3 and no limit - everything is drawn with no truncation label + foreach (var layout in new[] { limitThree, unlimited }) + { + var sub = FindBox(layout.Nodes, "Sub"); + Assert.Equal(["B", "C"], sub.Children.OfType().Select(b => b.Label).Order().ToArray()); + Assert.DoesNotContain(CollectNodes(layout.Nodes), n => n is LayoutLabel { Text: var t } && t.Contains("more")); + } + } + + /// An edge to a definition hidden inside a depth-truncated nested package is dropped without error. + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_NestedPackages_DepthLimit_EdgeToTruncatedPackageIsDropped() + { + // Act + var layout = await LayOutUnscopedAsync( + "package P { part def A; package Sub { part def B :> P::A; } }", depthLimit: 2); + + // Assert: A is drawn, Sub is collapsed, and no specialization line exists + FindBox(layout.Nodes, "A"); + Assert.DoesNotContain(CollectBoxes(layout.Nodes), b => b.Label == "B"); + Assert.Empty(CollectLines(layout.Nodes)); + } + + /// Recursively collects every node (boxes, lines, labels) from a node list. + private static IReadOnlyList CollectNodes(IReadOnlyList nodes) + { + var result = new List(); + void Walk(IReadOnlyList ns) + { + foreach (var n in ns) + { + result.Add(n); + if (n is LayoutBox box) + { + Walk(box.Children); + } + } + } + + Walk(nodes); + return result; + } + + /// Builds a minimal placed box for the DecorateTruncated fixtures. + private static LayoutBox MakeFixtureBox(string label, BoxShape shape, string? keyword, params LayoutNode[] children) => + new( + X: 0, Y: 0, Width: 100, Height: 60, Label: label, Depth: 1, Shape: shape, + Compartments: [], Children: children, Keyword: keyword, RoundedCornerRadius: null, + FolderTabWidth: null, FolderTabHeight: null, ContentInsetLeft: 0, ContentInsetRight: 0, + ContentInsetTop: 0, ContentInsetBottom: 0, CenterTitle: false); + + /// Invokes the private recursive DecorateTruncated worker. + private static List InvokeDecorateTruncated( + List placed, + List graphNodes, + Dictionary hiddenByNode) + { + var method = typeof(GeneralViewLayoutStrategy) + .GetMethods(BindingFlags.NonPublic | BindingFlags.Static) + .Single(m => m.Name == "DecorateTruncated" && m.GetParameters().Length == 4 + && m.GetParameters()[0].ParameterType == typeof(IReadOnlyList)); + return (List)method.Invoke(null, [placed, graphNodes, hiddenByNode, Themes.Light])!; + } + + /// + /// The "+N more…" decoration is paired with its box by the node's identity (label, keyword, + /// shape), not by position: with the boxes placed in a different order than the graph nodes + /// (and a line among them), and with a nested container whose children are permuted too, only + /// the box standing for the truncated node is decorated. + /// + [Fact] + public void GeneralViewLayoutStrategy_DecorateTruncated_BoxOrderDiffersFromNodeOrder_DecoratesMatchingNode() + { + // Arrange: root scope nodes A, P (a folder container holding X and truncated Y), B (truncated) + var graph = new LayoutGraph(); + var nodeA = graph.AddNode("A", 100, 60); + nodeA.Label = "A"; + nodeA.Keyword = "part def"; + nodeA.Shape = BoxShape.Rectangle; + var nodeP = graph.AddNode("folder:P", 0, 0); + nodeP.Label = "P"; + nodeP.Keyword = "package"; + nodeP.Shape = BoxShape.Folder; + var nodeX = nodeP.Children.AddNode("P::X", 100, 60); + nodeX.Label = "X"; + nodeX.Keyword = "part def"; + nodeX.Shape = BoxShape.Rectangle; + var nodeY = nodeP.Children.AddNode("folder:P::Y", 100, 60); + nodeY.Label = "Y"; + nodeY.Keyword = "package"; + nodeY.Shape = BoxShape.Folder; + var nodeB = graph.AddNode("folder:B", 100, 60); + nodeB.Label = "B"; + nodeB.Keyword = "package"; + nodeB.Shape = BoxShape.Folder; + + var line = new LayoutLine( + Waypoints: [], SourceEnd: EndMarkerStyle.None, TargetEnd: EndMarkerStyle.None, + LineStyle: LineStyle.Solid, MidpointLabel: null); + + // The engine order is reversed relative to the graph order, at both scopes + var placedP = MakeFixtureBox( + "P", BoxShape.Folder, "package", + MakeFixtureBox("Y", BoxShape.Folder, "package"), + line, + MakeFixtureBox("X", BoxShape.Rectangle, "part def")); + var placed = new List + { + MakeFixtureBox("B", BoxShape.Folder, "package"), + line, + placedP, + MakeFixtureBox("A", BoxShape.Rectangle, "part def"), + }; + var hiddenByNode = new Dictionary + { + [nodeB] = (5, 0.0), + [nodeY] = (2, 0.0), + }; + + // Act + var result = InvokeDecorateTruncated(placed, [nodeA, nodeP, nodeB], hiddenByNode); + + // Assert: root scope - only B carries a label + Assert.Equal("+5 more\u2026", Assert.IsType(Assert.Single(Assert.IsType(result[0]).Children)).Text); + Assert.Empty(Assert.IsType(result[3]).Children); + + // Assert: nested scope - only Y carries a label + var resultP = Assert.IsType(result[2]); + var resultY = Assert.IsType(resultP.Children[0]); + Assert.Equal("+2 more\u2026", Assert.IsType(Assert.Single(resultY.Children)).Text); + Assert.Empty(Assert.IsType(resultP.Children[2]).Children); + } + + /// + /// Counts the places where two different lines cross each other properly (an interior point of + /// a segment of one line lies strictly inside a segment of the other). Lines that merely touch, + /// share an endpoint or run along the same line are not counted; every line's waypoints are absolute. + /// + private static int CountLineCrossings(IReadOnlyList nodes) + { + var lines = CollectNodes(nodes).OfType().ToList(); + var crossings = 0; + for (var i = 0; i < lines.Count; i++) + { + for (var j = i + 1; j < lines.Count; j++) + { + crossings += CountSegmentCrossings(lines[i], lines[j]); + } + } + + return crossings; + } + + /// Counts the proper crossings between the segments of two lines. + private static int CountSegmentCrossings(LayoutLine first, LayoutLine second) + { + var count = 0; + for (var a = 0; a + 1 < first.Waypoints.Count; a++) + { + for (var b = 0; b + 1 < second.Waypoints.Count; b++) + { + var (a1, a2) = (first.Waypoints[a], first.Waypoints[a + 1]); + var (b1, b2) = (second.Waypoints[b], second.Waypoints[b + 1]); + var onOppositeSidesOfB = Orientation(b1.X, b1.Y, b2.X, b2.Y, a1.X, a1.Y) * Orientation(b1.X, b1.Y, b2.X, b2.Y, a2.X, a2.Y) < 0; + var onOppositeSidesOfA = Orientation(a1.X, a1.Y, a2.X, a2.Y, b1.X, b1.Y) * Orientation(a1.X, a1.Y, a2.X, a2.Y, b2.X, b2.Y) < 0; + if (onOppositeSidesOfA && onOppositeSidesOfB) + { + count++; + } + } + } + + return count; + } + + /// The signed area of the triangle (p, q, r): positive when r is left of p-q, negative when right, zero when collinear. + private static double Orientation(double px, double py, double qx, double qy, double rx, double ry) => + ((qx - px) * (ry - py)) - ((qy - py) * (rx - px)); + + /// + /// The vehicle model of the nested-package gallery example with the Body package's + /// definitions supplied by the caller, so tests can vary their declaration order. + /// + private static string VehicleModel(string bodyDefinitions) => $$""" + package Vehicle { + package Powertrain { part def Engine; part def ElectricMotor :> Engine; } + package Body { {{bodyDefinitions}} } + part def Car { part engine : Powertrain::Engine; part chassis : Body::Chassis; } + } + """; + + /// + /// Relationships leaving a package folder are not forced to cross by the declaration order of + /// the folder's definitions: Hybrid (leading into the Powertrain folder) is placed + /// above Chassis (leading past it to Car) whether it is declared last or first, and + /// no two lines of the whole drawing cross. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_OrderFolderItemsByPartnerPosition() + { + // Act: the declaration order that used to force the crossing, and its reverse + var hybridLast = await LayOutUnscopedAsync(VehicleModel("part def Chassis; part def SportsChassis :> Chassis; part def Hybrid :> Powertrain::Engine;")); + var hybridFirst = await LayOutUnscopedAsync(VehicleModel("part def Hybrid :> Powertrain::Engine; part def Chassis; part def SportsChassis :> Chassis;")); + + // Assert: Hybrid sits above Chassis in both and nothing crosses + foreach (var layout in new[] { hybridLast, hybridFirst }) + { + Assert.True(FindBox(layout.Nodes, "Hybrid").Y < FindBox(layout.Nodes, "Chassis").Y); + Assert.Equal(0, CountLineCrossings(layout.Nodes)); + } + } + + /// + /// A folder none of whose definitions has a relationship leaving it is laid out in declaration + /// order: the refinement leaves it alone (the engine stacks its unconnected definitions by the + /// order they were added). + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_NoExternalEdges_KeepsDeclarationOrder() + { + // Act: three unconnected definitions and a specialization pair, all inside one package + var layout = await LayOutUnscopedAsync("package P { part def Zeta; part def Alpha; part def Mid :> Alpha; part def Beta; }"); + + // Assert: reading order (top to bottom, then left to right) equals declaration order of the + // groups, and nothing is reordered alphabetically or by connectivity + var p = FindBox(layout.Nodes, "P"); + var readingOrder = p.Children.OfType() + .OrderBy(b => b.Y).ThenBy(b => b.X) + .Select(b => b.Label) + .ToList(); + Assert.True(readingOrder.IndexOf("Zeta") < readingOrder.IndexOf("Alpha")); + Assert.True(readingOrder.IndexOf("Alpha") < readingOrder.IndexOf("Beta")); + } + + /// + /// A partner hidden inside a depth-truncated folder has no box to measure, so the definition has + /// no ordering key: the layout completes, both of the folder's definitions are drawn and they keep + /// their declaration order. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_ExternalEdgeToTruncatedPartner_DoesNotThrowAndKeepsOrder() + { + // Act: Z lives in Far::Sub, whose contents sit beyond the depth limit of 2 + var layout = await LayOutUnscopedAsync( + "package Body { part def A; part def B :> Far::Sub::Z; } package Far { part def W; package Sub { part def Z; } }", + depthLimit: 2); + + // Assert + var a = FindBox(layout.Nodes, "A"); + var b = FindBox(layout.Nodes, "B"); + Assert.True(a.Y < b.Y || a.X < b.X); + Assert.DoesNotContain(CollectBoxes(layout.Nodes), box => box.Label == "Z"); + Assert.Equal("+1 more\u2026", Assert.IsType(Assert.Single(FindBox(layout.Nodes, "Sub").Children)).Text); + } + + /// + /// The partner's position is measured at the level where the two meet, however deep the partner + /// is nested: definitions of A::B that lead into Lo::In and Hi::In are + /// stacked in the same vertical order as the Lo and Hi folders they lead to, + /// whichever way they were declared. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_DeepNesting_FollowsPartnerContainerOrder() + { + // Arrange: the same four packages, with the definitions of A::B declared in both orders + const string packages = "package Lo { package In { part def L; } } package Hi { package In { part def H; } }"; + var viaLowFirst = packages + " package A { package B { part def ToLo :> Lo::In::L; part def ToHi :> Hi::In::H; } }"; + var viaHighFirst = packages + " package A { package B { part def ToHi :> Hi::In::H; part def ToLo :> Lo::In::L; } }"; + + // Act / Assert: the stacking of the two definitions matches the stacking of their partners + foreach (var sysml in new[] { viaLowFirst, viaHighFirst }) + { + var layout = await LayOutUnscopedAsync(sysml); + var lo = FindBox(layout.Nodes, "Lo"); + var hi = FindBox(layout.Nodes, "Hi"); + var toLo = FindBox(layout.Nodes, "ToLo"); + var toHi = FindBox(layout.Nodes, "ToHi"); + Assert.NotEqual(lo.Y + (lo.Height / 2.0), hi.Y + (hi.Height / 2.0)); + Assert.Equal( + (lo.Y + (lo.Height / 2.0)).CompareTo(hi.Y + (hi.Height / 2.0)), + (toLo.Y + (toLo.Height / 2.0)).CompareTo(toHi.Y + (toHi.Height / 2.0))); + } + } + + /// + /// A definition that is a direct member of a package and whose partners live in different nested + /// packages of that same package is ordered by where those nested packages sit, even though the + /// lowest common scope of each relationship is the package's own scope: ToA and + /// ToB are stacked like the A and B folders they lead to, whichever way + /// they were declared, and no lines cross. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_ExternalEdges_DefinitionToSiblingNestedPackages_OrdersByPartnerFolder() + { + // Arrange: the same packages, with the owner's definitions declared in both orders + const string packages = "package A { part def X; } package B { part def Y; }"; + var toAFirst = "package P { part def ToA :> A::X; part def ToB :> B::Y; " + packages + " }"; + var toBFirst = "package P { part def ToB :> B::Y; part def ToA :> A::X; " + packages + " }"; + + // Act / Assert + foreach (var sysml in new[] { toAFirst, toBFirst }) + { + var layout = await LayOutUnscopedAsync(sysml); + var a = FindBox(layout.Nodes, "A"); + var b = FindBox(layout.Nodes, "B"); + var toA = FindBox(layout.Nodes, "ToA"); + var toB = FindBox(layout.Nodes, "ToB"); + Assert.NotEqual(a.Y + (a.Height / 2.0), b.Y + (b.Height / 2.0)); + Assert.Equal( + (a.Y + (a.Height / 2.0)).CompareTo(b.Y + (b.Height / 2.0)), + (toA.Y + (toA.Height / 2.0)).CompareTo(toB.Y + (toB.Height / 2.0))); + Assert.Equal(0, CountLineCrossings(layout.Nodes)); + } + } + + /// + /// Two distinct relationships between the same two definitions inside a nested package (two + /// attributes of the same type) are drawn as two separate connectors: parallel-edge merging is + /// off in every scope, not only at the root. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_ParallelEdgesInNestedPackage_AreNotMerged() + { + // Act + var layout = await LayOutUnscopedAsync( + "package P { package Sub { attribute def Mass; part def Vehicle { attribute mass : Mass; attribute weight : Mass; } } }"); + + // Assert: one dashed typing dependency per attribute + var typing = CollectLines(layout.Nodes).Where(l => l.TargetEnd == EndMarkerStyle.OpenChevron).ToList(); + Assert.Equal(2, typing.Count); + } + + /// + /// Two distinct relationships between the same two definitions inside a definition container + /// are likewise drawn as two separate connectors. + /// + [Fact] + public async Task GeneralViewLayoutStrategy_BuildLayout_ParallelEdgesInDefinitionContainer_AreNotMerged() + { + // Act + var layout = await LayOutUnscopedAsync( + "part def Outer { attribute def Mass; part def Vehicle { attribute mass : Mass; attribute weight : Mass; } }"); + + // Assert: Vehicle and Mass are nested in Outer, and each attribute has its own typing dependency + var outer = FindBox(layout.Nodes, "Outer"); + Assert.Contains(outer.Children.OfType(), b => b.Label == "Mass"); + var typing = CollectLines(layout.Nodes).Where(l => l.TargetEnd == EndMarkerStyle.OpenChevron).ToList(); + Assert.Equal(2, typing.Count); + } + + /// + /// Builds the layered-layout graph the General view relies on for its ordering refinement: a + /// B folder holding C, S (specializing C) and H, added in the + /// given order, beside a P folder holding E and a leaf K, with relationships + /// H to E, E to K and C to K declared at the root. + /// + private static LayoutTree LayOutOrderProbe(string bodyOrder) + { + static LayoutGraphNode Add(LayoutGraph scope, string name) + { + var node = scope.AddNode(name, 130, 50); + node.Label = name; + node.Keyword = "part def"; + node.Shape = BoxShape.Rectangle; + return node; + } + + static LayoutGraphNode AddFolder(LayoutGraph scope, string name) + { + var folder = scope.AddNode("folder:" + name, 0, 0); + folder.Label = name; + folder.Shape = BoxShape.Folder; + folder.Keyword = "package"; + folder.TitleHeight = 56; + folder.Set(CoreOptions.Algorithm, LayeredLayoutAlgorithm.AlgorithmId); + return folder; + } + + var graph = new LayoutGraph(); + var k = Add(graph, "K"); + var p = AddFolder(graph, "P"); + var e = Add(p.Children, "E"); + var b = AddFolder(graph, "B"); + var nodes = bodyOrder.ToDictionary(name => name, name => Add(b.Children, name.ToString())); + b.Children.AddEdge("s-c", nodes['S'], nodes['C']).TargetEnd = EndMarkerStyle.HollowTriangle; + graph.AddEdge("h-e", nodes['H'], e).TargetEnd = EndMarkerStyle.HollowTriangle; + graph.AddEdge("e-k", e, k).TargetEnd = EndMarkerStyle.FilledDiamond; + graph.AddEdge("c-k", nodes['C'], k).TargetEnd = EndMarkerStyle.FilledDiamond; + graph.Set(CoreOptions.Algorithm, AutoLayoutAlgorithm.AlgorithmId); + return LayoutEngine.Layout(graph); + } + + /// + /// OTS evidence for the contract the General view's ordering refinement builds on: the layered + /// algorithm stacks the unconnected groups of a container's contents in the order the nodes were + /// added, so adding H first places it above C and adding it last places it below. + /// + [Fact] + public void LayeredLayoutAlgorithm_Layout_ContainerContents_StackUnconnectedGroupsByInsertionOrder() + { + // Act + var hybridLast = LayOutOrderProbe("CSH"); + var hybridFirst = LayOutOrderProbe("HCS"); + + // Assert + Assert.True(FindBox(hybridLast.Nodes, "H").Y > FindBox(hybridLast.Nodes, "C").Y); + Assert.True(FindBox(hybridFirst.Nodes, "H").Y < FindBox(hybridFirst.Nodes, "C").Y); + } }