diff --git a/packages/dear-imgui/cpp/app/include/commit.h b/packages/dear-imgui/cpp/app/include/commit.h index 0d4ee61b..579f446d 100644 --- a/packages/dear-imgui/cpp/app/include/commit.h +++ b/packages/dear-imgui/cpp/app/include/commit.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -26,6 +27,9 @@ struct CommitBatch { std::vector rootChildren; // schema 2 complete virtual-root list std::optional correlationId; std::vector operations; + // "childLists": "changed": an omitted child list is the previous one, and a created + // node without an assignment has none. The default, "complete", needs every list. + bool changedChildLists = false; }; struct CommitError : std::runtime_error { @@ -62,6 +66,20 @@ struct PublicationPlan { std::vector destroyedIds; // previous tree postorder, excluding survivors }; +// What a changed-list publication does to the applied surface. Owned only by the request. +struct ChangedPublicationPlan { + std::vector>> assigned; // container 0 first, then assigned parents + std::vector created; // every created node; all are finally reachable + std::vector destroyedIds; // descendant-first in the previous tree +}; + +// The applied surface as changed-list validation reads it. Nothing is copied. +struct AppliedSurface { + const std::unordered_map>& children; + const std::unordered_map& parentOf; // publication-owned nodes; roots map to 0 + std::function(int)> node; +}; + CommitBatch ParseCommit(nlohmann::json wire); CommitResult UninitializedCommitResult(); nlohmann::json UninitializedCommitState(); @@ -69,6 +87,11 @@ int ParseNativeId(const nlohmann::json& value, bool allowContainer = false); int ParseBindingId(double value, bool allowContainer = false); PublicationPlan ValidatePublication(CommitBatch& batch, ValidationTree tree, const std::unordered_set& managedIds, uint64_t nativeRevision); +// Validates the final tree a changed-list batch describes over the applied surface, with +// the same rules as ValidatePublication except that omitted lists are kept. Its work +// follows the operations, the assigned lists and the nodes that leave. +ChangedPublicationPlan ValidateChangedPublication(CommitBatch& batch, const AppliedSurface& surface, + const std::unordered_set& managedIds, uint64_t nativeRevision); void ValidateCommitProps(const std::string& type, const nlohmann::json& props, bool create); bool IsCommitElementType(const std::string& type); bool IsMeasuredElementType(const std::string& type); diff --git a/packages/dear-imgui/cpp/app/include/xframes.h b/packages/dear-imgui/cpp/app/include/xframes.h index bfb754ff..81e3245b 100644 --- a/packages/dear-imgui/cpp/app/include/xframes.h +++ b/packages/dear-imgui/cpp/app/include/xframes.h @@ -69,12 +69,17 @@ class XFrames { json m_lastCommitDiagnostics; xframes::CommitResult DispatchCommit(xframes::CommitBatch batch); xframes::CommitResult ApplyCommitOperations(xframes::CommitBatch& batch); + void ApplyCompleteChildLists(xframes::PublicationPlan& plan, std::vector& destroyedIds); + void ApplyChangedChildLists(const xframes::ChangedPublicationPlan& plan, std::vector& destroyedIds); std::unordered_map(const json&, std::optional, XFrames*)>> m_element_init_fn; std::unordered_map> m_elements; std::mutex m_elements_mutex; std::unordered_map> m_hierarchy; + // The parent of every publication-owned node (0 for roots); kept with m_hierarchy + // by publication so a changed-list commit can validate without copying the tree. + std::unordered_map m_parentOf; std::mutex m_hierarchy_mutex; bool m_debug; diff --git a/packages/dear-imgui/cpp/app/src/commit.cpp b/packages/dear-imgui/cpp/app/src/commit.cpp index e3cf08a0..bb8f6f94 100644 --- a/packages/dear-imgui/cpp/app/src/commit.cpp +++ b/packages/dear-imgui/cpp/app/src/commit.cpp @@ -60,7 +60,7 @@ CommitBatch ParseCommit(json wire) { Require(wire.is_object() && wire.contains("schemaVersion"), "missing_field", "schemaVersion"); Require(wire["schemaVersion"].is_number_integer() && wire["schemaVersion"] == 2, "unsupported_version", "Only schemaVersion 2 is supported; the alpha v1 structural API was removed"); - Fields(wire, {"schemaVersion", "surfaceId", "baseRevision", "rootChildren", "operations"}, {"correlationId"}); + Fields(wire, {"schemaVersion", "surfaceId", "baseRevision", "rootChildren", "operations"}, {"correlationId", "childLists"}); Require(wire["surfaceId"].is_number_integer() && wire["surfaceId"] == 0, "unsupported_surface", "Only surfaceId 0 is supported"); Require(wire["operations"].is_array(), "invalid_field", "operations must be an array"); @@ -81,6 +81,12 @@ CommitBatch ParseCommit(json wire) { "invalid_field", "correlationId must be a string of at most 128 UTF-8 bytes"); batch.correlationId = wire["correlationId"].get(); } + if (wire.contains("childLists")) { + const auto& mode = wire["childLists"]; + Require(mode.is_string() && (mode == "complete" || mode == "changed"), + "invalid_field", "childLists must be \"complete\" or \"changed\""); + batch.changedChildLists = mode == "changed"; + } for (auto& def : wire["operations"]) { try { Require(def.is_object() && def.contains("op"), "missing_field", "Operation requires op"); @@ -238,4 +244,165 @@ PublicationPlan ValidatePublication(CommitBatch& batch, ValidationTree tree, return plan; } +ChangedPublicationPlan ValidateChangedPublication(CommitBatch& batch, const AppliedSurface& surface, + const std::unordered_set& managedIds, uint64_t nativeRevision) { + Require(batch.baseRevision == nativeRevision, "stale_revision", "baseRevision does not match the current structural revision"); + if (const auto roots = surface.children.find(0); roots != surface.children.end()) + for (int root : roots->second) + Require(managedIds.contains(root), "ownership_conflict", "Container has an unowned root"); + ChangedPublicationPlan plan; + std::unordered_map created; + const auto node = [&](int id) -> std::optional { + if (const auto it = created.find(id); it != created.end()) return it->second; + return surface.node(id); + }; + for (size_t index = 0; index < batch.operations.size(); ++index) { + const auto& op = batch.operations[index]; + if (op.op != CommitOp::Create) continue; + try { + Require(!node(op.id), "duplicate_id", "Create target already exists; a publication cannot recreate an old lifetime"); + Require(IsCommitElementType(op.elementType), "invalid_element_type", "Unsupported elementType"); + ValidateCommitProps(op.elementType, op.props, true); + created.emplace(op.id, ValidationNode{op.elementType, op.props.value("root", false), IsMeasuredElementType(op.elementType)}); + plan.created.push_back(op.id); + } catch (CommitError& error) { error.operationIndex = index; throw; } + } + // The final lists that differ from the applied surface's: container 0's always. + std::unordered_map*> assigned{{0, &batch.rootChildren}}; + std::unordered_map assignments; + std::vector parents{0}; + for (size_t index = 0; index < batch.operations.size(); ++index) { + auto& op = batch.operations[index]; + if (op.op == CommitOp::Create) continue; + try { + const auto target = node(op.id); + Require(target.has_value(), "missing_target", "Publication target does not exist"); + Require(managedIds.contains(op.id) || created.contains(op.id), "ownership_conflict", "Publication target is not owned by this surface"); + if (op.op == CommitOp::Patch) { + op.elementType = target->type; + ValidateCommitProps(op.elementType, op.props, false); + } else { + Require(op.op == CommitOp::SetChildren, "unsupported_operation", "Publication requires child lists"); + Require(assignments.emplace(op.id, index).second, "duplicate_assignment", "A publication assigns each parent's children exactly once"); + assigned.emplace(op.id, &op.children); + parents.push_back(op.id); + } + } catch (CommitError& error) { error.operationIndex = index; throw; } + } + std::unordered_map owners; + for (int parent : parents) { + const auto& children = *assigned.at(parent); + try { + Require(parent == 0 || children.empty() || !node(parent)->measured, + "invalid_relationship", "A measured Yoga leaf cannot own children"); + std::unordered_set unique; + for (int child : children) { + Require(unique.insert(child).second, "duplicate_child", "A child list cannot contain duplicate IDs"); + Require(child != parent, "cycle", "A node cannot contain itself"); + const auto childNode = node(child); + Require(childNode.has_value(), "missing_target", "Child does not exist in the complete candidate"); + Require(managedIds.contains(child) || created.contains(child), "ownership_conflict", "Child is not owned by this surface"); + Require(parent == 0 || !childNode->root, "invalid_relationship", "Root nodes can only attach to container 0"); + Require(owners.emplace(child, parent).second, "multiple_parents", "Final child has multiple owners"); + } + } catch (CommitError& error) { + if (parent != 0) error.operationIndex = assignments.at(parent); + throw; + } + } + // A node's final parent: the assigned list that names it; otherwise its applied parent, + // when that parent's list is kept; a created node otherwise has none. + const auto finalParent = [&](int id) -> std::optional { + if (const auto it = owners.find(id); it != owners.end()) return it->second; + if (created.contains(id)) return std::nullopt; + const auto it = surface.parentOf.find(id); + if (it == surface.parentOf.end() || assigned.contains(it->second)) return std::nullopt; + return it->second; + }; + // Final reachability by following final parents to container 0, memoised. Any cycle + // passes through an assigned list, so walking up from every assigned parent finds it. + std::unordered_map reachable{{0, true}}; + const auto reaches = [&](int id) { + std::vector path; + std::unordered_set onPath; + int current = id; + bool result = false; + while (true) { + if (const auto known = reachable.find(current); known != reachable.end()) { result = known->second; break; } + Require(onPath.insert(current).second, "cycle", "Final ownership contains a cycle"); + path.push_back(current); + const auto parent = finalParent(current); + if (!parent) break; + current = *parent; + } + for (int at : path) reachable[at] = result; + return result; + }; + for (int parent : parents) reaches(parent); + // A kept list still names its children: a child assigned elsewhere while its applied + // parent keeps its list and survives would have two parents. If that parent leaves, + // the child moves out of a removed ancestor, which is allowed. + for (int parent : parents) { + for (int child : *assigned.at(parent)) { + if (created.contains(child)) continue; + const auto previous = surface.parentOf.find(child); + if (previous == surface.parentOf.end() || previous->second == parent || assigned.contains(previous->second)) continue; + if (reaches(previous->second)) + throw CommitError("multiple_parents", "Final child has multiple owners", + parent == 0 ? std::nullopt : std::optional(assignments.at(parent))); + } + } + for (size_t index = 0; index < batch.operations.size(); ++index) + if (!reaches(batch.operations[index].id)) + throw CommitError("unreachable_operation", "Operations may target only final reachable nodes", index); + // Applied nodes that leave: the applied children of assigned parents that are no longer + // reachable, and everything finally below them. + std::unordered_set leaving; + std::vector leavingOrder, pending; + for (int parent : parents) { + if (created.contains(parent)) continue; + const auto previous = surface.children.find(parent); + if (previous == surface.children.end()) continue; + for (int child : previous->second) + if (managedIds.contains(child) && !reaches(child)) pending.push_back(child); + } + while (!pending.empty()) { + const int id = pending.back(); pending.pop_back(); + if (!leaving.insert(id).second) continue; + leavingOrder.push_back(id); + const auto kept = surface.children.find(id); + if (kept == surface.children.end()) continue; + for (int child : kept->second) + if (const auto parent = finalParent(child); parent && *parent == id) pending.push_back(child); + } + // Descendant-first in the previous tree: each leaving node whose applied parent stays is + // emitted in previous-tree postorder restricted to leaving nodes, deeper ones first. + std::vector> tops; + for (int id : leavingOrder) { + const auto parent = surface.parentOf.find(id); + const int above = parent == surface.parentOf.end() ? 0 : parent->second; + if (above != 0 && leaving.contains(above)) continue; + size_t depth = 0; + for (int at = above; at != 0; ++depth) { + const auto next = surface.parentOf.find(at); + at = next == surface.parentOf.end() ? 0 : next->second; + } + tops.emplace_back(depth, id); + } + std::stable_sort(tops.begin(), tops.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + for (const auto& [depth, top] : tops) { + std::vector> stack{{top, false}}; + while (!stack.empty()) { + const auto [id, visited] = stack.back(); stack.pop_back(); + if (visited) { plan.destroyedIds.push_back(id); continue; } + stack.emplace_back(id, true); + if (const auto children = surface.children.find(id); children != surface.children.end()) + for (auto it = children->second.rbegin(); it != children->second.rend(); ++it) + if (leaving.contains(*it)) stack.emplace_back(*it, false); + } + } + for (int parent : parents) plan.assigned.emplace_back(parent, *assigned.at(parent)); + return plan; +} + } diff --git a/packages/dear-imgui/cpp/app/src/xframes.cpp b/packages/dear-imgui/cpp/app/src/xframes.cpp index d1ad2ddb..7a7ad274 100644 --- a/packages/dear-imgui/cpp/app/src/xframes.cpp +++ b/packages/dear-imgui/cpp/app/src/xframes.cpp @@ -127,6 +127,7 @@ void XFrames::Dispose() { m_publicationOwnedIds.clear(); m_hierarchy.clear(); m_hierarchy.emplace(0, std::vector{}); + m_parentOf.clear(); m_diagnosticsLastInternalOpMs.clear(); m_floatFormatChars.clear(); m_pendingFrame.reset(); diff --git a/packages/dear-imgui/cpp/app/src/xframes_commit.cpp b/packages/dear-imgui/cpp/app/src/xframes_commit.cpp index 4006ee4d..27d03694 100644 --- a/packages/dear-imgui/cpp/app/src/xframes_commit.cpp +++ b/packages/dear-imgui/cpp/app/src/xframes_commit.cpp @@ -66,6 +66,7 @@ CommitResult XFrames::ApplyCommitOperations(CommitBatch& batch) { const std::lock_guard elementsLock(m_elements_mutex); lockedAt = diagnostics ? DiagnosticsNowMs() : 0; PublicationPlan plan; + ChangedPublicationPlan changed; try { if (m_surfaceQuarantined) throw CommitError("surface_quarantined", "Publication failed; recreate the native runtime"); @@ -73,14 +74,25 @@ CommitResult XFrames::ApplyCommitOperations(CommitBatch& batch) { throw CommitError("counter_overflow", "Native sequence/revision exhausted; create a new runtime"); if (!m_frameScheduler.CanInvalidate()) throw CommitError("counter_overflow", "Rendering ordering is unavailable; create a new runtime"); - ValidationTree tree; - tree.children = m_hierarchy; - for (const auto& [id, element] : m_elements) - tree.nodes.emplace(id, ValidationNode{element->m_type, element->m_isRoot, - YGNodeHasMeasureFunc(element->m_layoutNode->m_node)}); - plan = ValidatePublication(batch, std::move(tree), m_publicationOwnedIds, m_nativeRevision); - // Reserve acknowledgment storage before touching resources/live state. - result.destroyedIds.reserve(plan.destroyedIds.size()); + if (batch.changedChildLists) { + const AppliedSurface surface{m_hierarchy, m_parentOf, [this](int id) -> std::optional { + const auto it = m_elements.find(id); + if (it == m_elements.end()) return std::nullopt; + return ValidationNode{it->second->m_type, it->second->m_isRoot, + YGNodeHasMeasureFunc(it->second->m_layoutNode->m_node)}; + }}; + changed = ValidateChangedPublication(batch, surface, m_publicationOwnedIds, m_nativeRevision); + result.destroyedIds.reserve(changed.destroyedIds.size()); + } else { + ValidationTree tree; + tree.children = m_hierarchy; + for (const auto& [id, element] : m_elements) + tree.nodes.emplace(id, ValidationNode{element->m_type, element->m_isRoot, + YGNodeHasMeasureFunc(element->m_layoutNode->m_node)}); + plan = ValidatePublication(batch, std::move(tree), m_publicationOwnedIds, m_nativeRevision); + // Reserve acknowledgment storage before touching resources/live state. + result.destroyedIds.reserve(plan.destroyedIds.size()); + } } catch (const CommitError& error) { result.error = error; } @@ -105,35 +117,8 @@ CommitResult XFrames::ApplyCommitOperations(CommitBatch& batch) { } } operationIndex.reset(); - // Only parents whose child list changed are re-linked. Re-linking an - // unchanged parent marks its Yoga subtree dirty and makes the next - // frame lay it out again. A child that moves leaves a parent whose - // list changes too, or one that is destroyed; both are disconnected - // before any candidate child is attached. Moving out of a removed - // ancestor retains the exact Element, Yoga node, internal subject and - // populated data. - std::unordered_set relink; - for (const auto& [parent, children] : plan.children) { - if (parent == 0) continue; - const auto previous = m_hierarchy.find(parent); - if (!m_publicationOwnedIds.contains(parent) || previous == m_hierarchy.end() || previous->second != children) - relink.insert(parent); - } - for (int id : m_publicationOwnedIds) - if (relink.contains(id) || !plan.ownedIds.contains(id)) - YGNodeRemoveAllChildren(m_elements.at(id)->m_layoutNode->m_node); - for (const auto& [parent, children] : plan.children) { - m_hierarchy[parent] = children; - if (parent == 0 || !relink.contains(parent)) continue; - auto* element = m_elements.at(parent).get(); - for (size_t index = 0; index < children.size(); ++index) - element->m_layoutNode->InsertChild(m_elements.at(children[index])->m_layoutNode.get(), index); - element->m_maxBottomDirty = true; - } - // The plan is old-tree postorder filtered by final reachability; - // destruction never recursively follows the newly published tree. - for (int id : plan.destroyedIds) DestroyElementUnlocked(id, &result.destroyedIds); - m_publicationOwnedIds.swap(plan.ownedIds); + if (batch.changedChildLists) ApplyChangedChildLists(changed, result.destroyedIds); + else ApplyCompleteChildLists(plan, result.destroyedIds); // Revision and generation become visible with exactly this tree. // Capture never reads a later publication's generation after drawing. if (!m_frameScheduler.Invalidate(FrameReason::Publication)) @@ -167,11 +152,83 @@ CommitResult XFrames::ApplyCommitOperations(CommitBatch& batch) { return result; } +// Only parents whose child list changed are re-linked. Re-linking an unchanged +// parent marks its Yoga subtree dirty and makes the next frame lay it out again. +// A child that moves leaves a parent whose list changes too, or one that is +// destroyed; both are disconnected before any candidate child is attached. Moving +// out of a removed ancestor retains the exact Element, Yoga node, internal subject +// and populated data. +void XFrames::ApplyCompleteChildLists(PublicationPlan& plan, std::vector& destroyedIds) { + std::unordered_set relink; + for (const auto& [parent, children] : plan.children) { + if (parent == 0) continue; + const auto previous = m_hierarchy.find(parent); + if (!m_publicationOwnedIds.contains(parent) || previous == m_hierarchy.end() || previous->second != children) + relink.insert(parent); + } + for (int id : m_publicationOwnedIds) + if (relink.contains(id) || !plan.ownedIds.contains(id)) + YGNodeRemoveAllChildren(m_elements.at(id)->m_layoutNode->m_node); + for (const auto& [parent, children] : plan.children) { + m_hierarchy[parent] = children; + if (parent == 0 || !relink.contains(parent)) continue; + auto* element = m_elements.at(parent).get(); + for (size_t index = 0; index < children.size(); ++index) + element->m_layoutNode->InsertChild(m_elements.at(children[index])->m_layoutNode.get(), index); + element->m_maxBottomDirty = true; + } + // The plan is old-tree postorder filtered by final reachability; + // destruction never recursively follows the newly published tree. + for (int id : plan.destroyedIds) DestroyElementUnlocked(id, &destroyedIds); + m_publicationOwnedIds.swap(plan.ownedIds); + m_parentOf.clear(); + for (const auto& [parent, children] : plan.children) + for (int child : children) m_parentOf[child] = parent; +} + +// The same re-linking rule over the assigned lists only. Every other list, and its +// Yoga links, stays as it is: no work is done for unchanged parts of the tree. +void XFrames::ApplyChangedChildLists(const ChangedPublicationPlan& plan, std::vector& destroyedIds) { + std::unordered_set relink; + for (const auto& [parent, children] : plan.assigned) { + if (parent == 0) continue; + const auto previous = m_hierarchy.find(parent); + if (!m_publicationOwnedIds.contains(parent) || previous == m_hierarchy.end() || previous->second != children) + relink.insert(parent); + } + for (int id : relink) YGNodeRemoveAllChildren(m_elements.at(id)->m_layoutNode->m_node); + for (int id : plan.destroyedIds) YGNodeRemoveAllChildren(m_elements.at(id)->m_layoutNode->m_node); + // Parent links: drop the ones the assigned lists held, then record the new ones. + for (const auto& [parent, children] : plan.assigned) { + const auto previous = m_hierarchy.find(parent); + if (previous == m_hierarchy.end()) continue; + for (int child : previous->second) + if (const auto link = m_parentOf.find(child); link != m_parentOf.end() && link->second == parent) + m_parentOf.erase(link); + } + for (const auto& [parent, children] : plan.assigned) { + for (int child : children) m_parentOf[child] = parent; + m_hierarchy[parent] = children; + if (parent == 0 || !relink.contains(parent)) continue; + auto* element = m_elements.at(parent).get(); + for (size_t index = 0; index < children.size(); ++index) + element->m_layoutNode->InsertChild(m_elements.at(children[index])->m_layoutNode.get(), index); + element->m_maxBottomDirty = true; + } + for (int id : plan.created) m_publicationOwnedIds.insert(id); + for (int id : plan.destroyedIds) { + m_parentOf.erase(id); + m_publicationOwnedIds.erase(id); + DestroyElementUnlocked(id, &destroyedIds); + } +} + json XFrames::GetCommitState() { const std::lock_guard lock(m_commitMutex); json state = {{"schemaVersion", 2}, {"surfaceId", 0}, {"initialized", !m_runtimeDisposed}, {"nativeSequence", std::to_string(m_nativeSequence)}, {"nativeRevision", std::to_string(m_nativeRevision)}, - {"surfaceStatus", m_runtimeDisposed ? "disposed" : m_surfaceQuarantined ? "quarantined" : "healthy"}, {"managedCount", m_publicationOwnedIds.size()}}; + {"surfaceStatus", m_runtimeDisposed ? "disposed" : m_surfaceQuarantined ? "quarantined" : "healthy"}, {"managedCount", m_publicationOwnedIds.size()}, + {"commitFeatures", json::array({"changedChildLists"})}}; if (m_diagnosticsEnabled.load(std::memory_order_relaxed)) state["lastTransaction"] = m_lastCommitDiagnostics; return state; } diff --git a/packages/dear-imgui/cpp/tests/xframes_test.cpp b/packages/dear-imgui/cpp/tests/xframes_test.cpp index 122cff86..4fd97420 100644 --- a/packages/dear-imgui/cpp/tests/xframes_test.cpp +++ b/packages/dear-imgui/cpp/tests/xframes_test.cpp @@ -5,6 +5,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -314,6 +317,192 @@ TEST_F(XFramesTest, PublicationCompetingWritersCannotOverwriteAStaleTree) { EXPECT_EQ(xf->GetCommitState()["nativeRevision"], "2"); } +// "childLists": "changed" carries only the child lists that changed. An omitted +// list is the previous one; a created node without an assignment has none. +namespace { +json Changed(json wire) { wire["childLists"] = "changed"; return wire; } +} +TEST_F(XFramesTest, ChangedChildListsAreAdvertised) { + const auto features = xf->GetCommitState()["commitFeatures"]; + ASSERT_TRUE(features.is_array()); + EXPECT_NE(std::find(features.begin(), features.end(), "changedChildLists"), features.end()); +} +TEST_F(XFramesTest, ChangedChildListsKeepOmittedListsAndStartCreatedNodesEmpty) { + Publish({{0, {1}}, {1, {2, 3}}, {2, {}}, {3, {}}}, {Create(1), Create(2), Create(3)}); + // A patch alone: nothing re-assigned, nothing destroyed. + auto patched = xf->ApplyCommit(Changed(Wire({{0, {1}}}, {Patch(2, {{"style", {{"width", 5}}}})})).dump()); + ASSERT_EQ(patched.status, "applied") << patched.ToJson(); + EXPECT_TRUE(patched.destroyedIds.empty()); + EXPECT_EQ(xf->GetChildren(1), (std::vector{2, 3})); + // A created leaf needs no assignment of its own. + auto inserted = xf->ApplyCommit(Changed(Wire({{0, {1}}, {1, {2, 4, 3}}}, {Create(4)})).dump()); + ASSERT_EQ(inserted.status, "applied") << inserted.ToJson(); + EXPECT_EQ(xf->GetChildren(1), (std::vector{2, 4, 3})); + EXPECT_EQ(xf->GetChildren(4), std::vector{}); + EXPECT_EQ(xf->GetCommitState()["managedCount"], 4); + // Removing a subtree destroys it, descendants first. + Publish({{0, {1}}, {1, {2, 4, 3}}, {2, {5}}, {4, {}}, {3, {}}, {5, {}}}, {Create(5)}); + auto removed = xf->ApplyCommit(Changed(Wire({{0, {1}}, {1, {4, 3}}})).dump()); + ASSERT_EQ(removed.status, "applied") << removed.ToJson(); + EXPECT_EQ(removed.destroyedIds, (std::vector{5, 2})); + EXPECT_EQ(xf->GetCommitState()["managedCount"], 3); +} +TEST_F(XFramesTest, ChangedChildListsMoveOutOfARemovedAncestor) { + Publish({{0, {1, 4}}, {1, {2}}, {2, {3}}, {3, {}}, {4, {}}}, {Create(1), Create(2), Create(3), Create(4)}); + auto moved = ElementAt(3); + auto result = xf->ApplyCommit(Changed(Wire({{0, {4}}, {4, {3}}})).dump()); + ASSERT_EQ(result.status, "applied") << result.ToJson(); + EXPECT_EQ(result.destroyedIds, (std::vector{2, 1})); + EXPECT_EQ(ElementAt(3), moved); + EXPECT_EQ(xf->GetChildren(4), (std::vector{3})); + EXPECT_EQ(Node(xf->GetDiagnosticsState(), 3)["yogaParent"], 4); +} +TEST_F(XFramesTest, ChangedChildListsValidateTheFinalTree) { + InsertUnowned(99); + Publish({{0, {1, 4}}, {1, {2, 5}}, {2, {3}}, {3, {}}, {4, {}}, {5, {}}}, + {Create(1), Create(2), Create(3), Create(4), Create(5, "unformatted-text", {{"text", "leaf"}})}); + // A child still listed by an unchanged, surviving parent cannot be listed again. + Reject(Changed(Wire({{0, {1, 4}}, {4, {2}}})), "multiple_parents"); + // A cycle through unchanged links: 1 -> 2 -> 3 (unchanged) -> 1. + Reject(Changed(Wire({{0, {4}}, {3, {1}}})), "cycle"); + Reject(Changed(Wire({{0, {1, 4}}}, {Create(6)})), "unreachable_operation", 0); + Reject(Changed(Wire({{0, {4}}}, {Patch(2, json::object())})), "unreachable_operation", 0); + Reject(Changed(Wire({{0, {1, 4}}, {5, {6}}}, {Create(6)})), "invalid_relationship"); + Reject(Changed(Wire({{0, {1, 4}}, {4, {6}}}, {Create(6, "node", {{"root", true}})})), "invalid_relationship"); + Reject(Changed(Wire({{0, {1, 4}}, {4, {}}}, {Children(4, {})})), "duplicate_assignment"); + Reject(Changed(Wire({{0, {1, 4}}, {4, {99}}})), "ownership_conflict"); + Reject(Changed(Wire({{0, {1, 4}}, {4, {77}}})), "missing_target"); + Reject(Changed(Wire({{0, {1, 4}}, {4, {6, 6}}}, {Create(6)})), "duplicate_child"); + for (auto value : json::array({"partial", 1, nullptr, true})) { + auto wire = Wire({{0, {1, 4}}}); wire["childLists"] = value; Reject(wire, "invalid_field"); + } + auto explicitComplete = Wire({{0, {1, 4}}, {1, {2, 5}}, {2, {3}}, {3, {}}, {4, {}}, {5, {}}}); + explicitComplete["childLists"] = "complete"; + EXPECT_EQ(xf->ApplyCommit(explicitComplete.dump()).status, "applied"); + // "complete" still requires every list. + auto incomplete = Wire({{0, {1, 4}}}); incomplete["childLists"] = "complete"; + Reject(incomplete, "missing_children"); +} +TEST_F(XFramesTest, ChangedChildListsLeaveUnchangedLayoutClean) { + std::vector rows; + std::vector creates{Create(1)}; + for (int id = 2; id <= 2001; ++id) { rows.push_back(id); creates.push_back(Create(id)); } + auto wire = Wire({{0, {1}}}, {}); wire["childLists"] = "changed"; + for (const auto& create : creates) wire["operations"].push_back(create); + wire["operations"].push_back(Children(1, rows)); + ASSERT_EQ(xf->ApplyCommit(wire.dump()).status, "applied"); + const auto yoga = [&](int id) { return ElementAt(id)->m_layoutNode->m_node; }; + YGNodeCalculateLayout(yoga(1), 100, 100, YGDirectionLTR); + auto patch = xf->ApplyCommit(Changed(Wire({{0, {1}}}, {Patch(700, json::object())})).dump()); + ASSERT_EQ(patch.status, "applied") << patch.ToJson(); + EXPECT_FALSE(YGNodeIsDirty(yoga(1))); + EXPECT_FALSE(YGNodeIsDirty(yoga(700))); + EXPECT_EQ(xf->GetChildren(1).size(), 2000u); +} + +// Two surfaces, one fed complete commits and one fed changed commits for the same +// seeded edits, must stay identical: hierarchy, Yoga links, owned nodes, revisions +// and destroyed sets. Changed destruction is descendant-first in the previous tree. +TEST_F(XFramesTest, ChangedChildListsEqualCompleteCommitsOverSeededEdits) { + for (unsigned seed : {1u, 7u, 2026u}) { + auto complete = std::make_unique("publication-test", std::nullopt); + auto changed = std::make_unique("publication-test", std::nullopt); + std::mt19937 random(seed); + const auto pick = [&](size_t n) { return std::uniform_int_distribution(0, n - 1)(random); }; + std::map> tree{{0, {}}}; + int next = 1; + const auto subtree = [&](int id) { + std::vector result, pending{id}; + while (!pending.empty()) { + int at = pending.back(); pending.pop_back(); result.push_back(at); + for (int child : tree.at(at)) pending.push_back(child); + } + return result; + }; + const auto parentOf = [&](int id) { + for (const auto& [parent, children] : tree) + if (std::find(children.begin(), children.end(), id) != children.end()) return parent; + return -1; + }; + for (int step = 0; step < 200; ++step) { + const auto before = tree; + std::vector creates; + std::vector nodes; + for (const auto& [id, _] : tree) nodes.push_back(id); + const int at = nodes[pick(nodes.size())]; + switch (pick(5)) { + case 0: case 1: { // insert one or two new nodes + for (int k = 0; k <= static_cast(pick(2)); ++k) { + auto& children = tree.at(at); + children.insert(children.begin() + pick(children.size() + 1), next); + tree[next] = {}; + creates.push_back(Create(next++)); + } + break; + } + case 2: { // remove a subtree, first moving one grandchild out of it + if (at == 0) break; + const auto doomed = subtree(at); + for (int id : doomed) { + if (id != at && pick(2) == 0) { + auto& old = tree.at(parentOf(id)); + old.erase(std::find(old.begin(), old.end(), id)); + tree.at(0).push_back(id); + break; + } + } + auto& siblings = tree.at(parentOf(at)); + siblings.erase(std::find(siblings.begin(), siblings.end(), at)); + for (int id : subtree(at)) tree.erase(id); + break; + } + case 3: { // move a node under another parent outside its subtree + if (at == 0) break; + const auto inside = subtree(at); + std::vector targets; + for (int id : nodes) if (std::find(inside.begin(), inside.end(), id) == inside.end()) targets.push_back(id); + const int target = targets[pick(targets.size())]; + auto& old = tree.at(parentOf(at)); + old.erase(std::find(old.begin(), old.end(), at)); + auto& children = tree.at(target); + children.insert(children.begin() + pick(children.size() + 1), at); + break; + } + default: // reorder one child list + std::shuffle(tree.at(at).begin(), tree.at(at).end(), random); + } + json full = {{"schemaVersion", 2}, {"surfaceId", 0}, {"baseRevision", complete->GetCommitState()["nativeRevision"]}, + {"rootChildren", tree.at(0)}, {"operations", creates}}; + json delta = full; + delta["childLists"] = "changed"; + for (const auto& [id, children] : tree) { + if (id == 0) continue; + full["operations"].push_back(Children(id, children)); + const auto old = before.find(id); + if (old == before.end() ? !children.empty() : old->second != children) + delta["operations"].push_back(Children(id, children)); + } + const auto a = complete->ApplyCommit(full.dump()); + const auto b = changed->ApplyCommit(delta.dump()); + ASSERT_EQ(a.status, "applied") << seed << ":" << step << " " << a.ToJson(); + ASSERT_EQ(b.status, "applied") << seed << ":" << step << " " << b.ToJson() << delta; + EXPECT_EQ(a.nativeRevision, b.nativeRevision); + EXPECT_EQ(std::set(a.destroyedIds.begin(), a.destroyedIds.end()), + std::set(b.destroyedIds.begin(), b.destroyedIds.end())) << seed << ":" << step; + for (size_t i = 0; i < b.destroyedIds.size(); ++i) { + const auto prior = before.find(b.destroyedIds[i]); + ASSERT_NE(prior, before.end()); + for (int child : prior->second) + for (size_t j = i + 1; j < b.destroyedIds.size(); ++j) + EXPECT_NE(b.destroyedIds[j], child) << "descendant destroyed after its parent, " << seed << ":" << step; + } + ASSERT_EQ(complete->GetDiagnosticsState().dump(), changed->GetDiagnosticsState().dump()) << seed << ":" << step; + for (const auto& [id, children] : tree) ASSERT_EQ(changed->GetChildren(id), children) << seed << ":" << step; + ASSERT_EQ(changed->GetCommitState()["managedCount"], tree.size() - 1); + } + } +} + // The same subject path plus actual ImGui/ImPlot frame construction; no window // or graphics driver is involved. Real Node/Wasm suites establish GPU coverage. class XFramesQueueTest : public XFramesTest { diff --git a/packages/dear-imgui/npm/common/src/lib/nativeCommit.ts b/packages/dear-imgui/npm/common/src/lib/nativeCommit.ts index 44f55a60..6e834350 100644 --- a/packages/dear-imgui/npm/common/src/lib/nativeCommit.ts +++ b/packages/dear-imgui/npm/common/src/lib/nativeCommit.ts @@ -10,8 +10,15 @@ export interface NativeCommit { surfaceId: 0; /** Must match the current successful native revision. */ baseRevision: NativeCounter; - /** Complete virtual-root list; every reachable node also needs a child assignment. */ + /** Complete virtual-root list. */ rootChildren: number[]; + /** + * "complete" (the default): every reachable node needs a child assignment. + * "changed": an omitted assignment keeps the node's previous list, and a created + * node without one has no children. Advertised as "changedChildLists" in the + * commit state's commitFeatures. + */ + childLists?: "complete" | "changed"; /** Optional opaque correlation, at most 128 UTF-8 bytes; never controls ordering. */ correlationId?: string; operations: NativeCommitOperation[]; @@ -53,6 +60,8 @@ export interface NativeCommitState { managedCount: number; nativeSequence: NativeCounter; nativeRevision: NativeCounter; + /** Optional commit forms this surface accepts, such as "changedChildLists". */ + commitFeatures?: string[]; lastTransaction?: null | { nativeSequence?: NativeCounter | null; nativeRevision?: NativeCounter;