From e9d4a5aaf8f31c6eff24b4a7be70168c25240abf Mon Sep 17 00:00:00 2001 From: Andrea Mancuso Date: Tue, 24 Nov 2026 12:28:45 +0100 Subject: [PATCH] Show controlled values unless the user has an unacknowledged edit An embedder numbers widget events with NoteWidgetEvent, and a commit may carry "eventsApplied": the last event applied to the state its tree was built from. Elements declare controlled properties (input-text: value). With eventsApplied, a commit stores them as the element's committed values. An element edited after eventsApplied keeps what the user typed; any other patched, created or acknowledged element shows its committed values, even when the commit does not carry them, so a rejected or transformed edit converges. Without eventsApplied nothing changes. InputText reloads ImGui's edit buffer when a controlled value replaces the text while it is being edited, and its value is reported in the diagnostics state. The commit state advertises controlledValues. Five new unit tests; all 414 pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0186WhMU3KjnmjR7Y4r49GrT --- packages/dear-imgui/cpp/app/include/commit.h | 4 ++ .../cpp/app/include/element/element.h | 12 ++++ .../cpp/app/include/widget/input_text.h | 17 +++++ packages/dear-imgui/cpp/app/include/xframes.h | 13 ++++ packages/dear-imgui/cpp/app/src/commit.cpp | 26 +++++--- .../cpp/app/src/widget/input_text.cpp | 7 +++ packages/dear-imgui/cpp/app/src/xframes.cpp | 6 ++ .../dear-imgui/cpp/app/src/xframes_commit.cpp | 53 +++++++++++++++- .../dear-imgui/cpp/tests/xframes_test.cpp | 63 +++++++++++++++++++ 9 files changed, 191 insertions(+), 10 deletions(-) diff --git a/packages/dear-imgui/cpp/app/include/commit.h b/packages/dear-imgui/cpp/app/include/commit.h index 579f446d..53c18793 100644 --- a/packages/dear-imgui/cpp/app/include/commit.h +++ b/packages/dear-imgui/cpp/app/include/commit.h @@ -30,6 +30,10 @@ struct CommitBatch { // "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; + // "eventsApplied": the last widget event (XFrames::NoteWidgetEvent) applied to the + // state this tree was built from. With it, controlled properties are shown only on + // elements that were not edited after that event; absent, they are ignored as before. + std::optional eventsApplied; }; struct CommitError : std::runtime_error { diff --git a/packages/dear-imgui/cpp/app/include/element/element.h b/packages/dear-imgui/cpp/app/include/element/element.h index 96949158..e3f70456 100644 --- a/packages/dear-imgui/cpp/app/include/element/element.h +++ b/packages/dear-imgui/cpp/app/include/element/element.h @@ -123,6 +123,18 @@ class Element { virtual void HandleInternalOp(const json& opDef); + // Controlled properties: values the application owns while the user may edit them, + // such as an input's text. A commit carrying eventsApplied stores them here and + // XFrames shows them with ApplyControlled only while the element has no edit the + // application has not seen. Most elements have none. + virtual const std::vector& ControlledProps() const { + static const std::vector none; + return none; + } + // Shows committed controlled values; a value equal to the one shown changes nothing. + virtual void ApplyControlled(const json& values) {} + json m_committedControlled = json::object(); + virtual float GetLayoutLeftFromParentNode(YGNodeRef node, float left); virtual float GetLayoutTopFromParentNode(YGNodeRef node, float top); diff --git a/packages/dear-imgui/cpp/app/include/widget/input_text.h b/packages/dear-imgui/cpp/app/include/widget/input_text.h index 6bcc5061..56bc582a 100644 --- a/packages/dear-imgui/cpp/app/include/widget/input_text.h +++ b/packages/dear-imgui/cpp/app/include/widget/input_text.h @@ -81,6 +81,23 @@ class InputText final : public StyledWidget { m_value = value; } + // Set when a controlled value replaced the text: if the user is editing, ImGui's own + // edit buffer is reloaded on the next frame so it does not write the old text back. + bool m_reloadEditBuffer = false; + + const std::vector& ControlledProps() const override { + static const std::vector props = {"value"}; + return props; + } + + void ApplyControlled(const json& values) override { + if (!values.contains("value") || !values["value"].is_string()) return; + const auto& value = values["value"].get_ref(); + if (value == m_value) return; + m_value = value; + m_reloadEditBuffer = true; + } + void Init(const json& elementDef) override { Element::Init(elementDef); diff --git a/packages/dear-imgui/cpp/app/include/xframes.h b/packages/dear-imgui/cpp/app/include/xframes.h index bb0563f6..58bc8df9 100644 --- a/packages/dear-imgui/cpp/app/include/xframes.h +++ b/packages/dear-imgui/cpp/app/include/xframes.h @@ -72,6 +72,14 @@ class XFrames { xframes::CommitResult ApplyCommitOperations(xframes::CommitBatch& batch); void ApplyCompleteChildLists(xframes::PublicationPlan& plan, std::vector& destroyedIds); void ApplyChangedChildLists(const xframes::ChangedPublicationPlan& plan, std::vector& destroyedIds); + // Widget events numbered by NoteWidgetEvent. m_unsyncedEdits holds, per element, the + // last event no commit has acknowledged yet. Taken last: after the tree locks, and + // after an embedder's own event lock. + std::mutex m_eventMutex; + uint64_t m_eventSequence = 0; + std::unordered_map m_unsyncedEdits; + // Shows committed controlled values where the element has no unacknowledged edit. + void SyncControlledUnlocked(uint64_t eventsApplied, const std::unordered_set& touched); std::unordered_map(const json&, std::optional, XFrames*)>> m_element_init_fn; @@ -202,6 +210,11 @@ class XFrames { // advances, under the visibility locks. An event raised while a frame is built // belongs to this tree. Safe to read from any thread. uint64_t VisibleRevision() const { return m_visibleRevision.load(std::memory_order_acquire); } + // Numbers a widget event raised on element `id` (0 for none) and returns its sequence. + // An embedder that publishes with eventsApplied calls it for every widget event, in + // the order it queues them. Safe from any thread, including inside event callbacks. + uint64_t NoteWidgetEvent(int id); + uint64_t LastEventSequence(); diff --git a/packages/dear-imgui/cpp/app/src/commit.cpp b/packages/dear-imgui/cpp/app/src/commit.cpp index bb8f6f94..0aa92c1b 100644 --- a/packages/dear-imgui/cpp/app/src/commit.cpp +++ b/packages/dear-imgui/cpp/app/src/commit.cpp @@ -21,6 +21,17 @@ void Fields(const json& value, std::initializer_list required, std::any_of(optional.begin(), optional.end(), matches), "unknown_field", "Unknown envelope or operation field"); } } +// A uint64 counter on the wire: a canonical decimal string. +uint64_t ParseCounter(const json& field, const char* invalid, const char* overflow) { + Require(field.is_string(), "invalid_field", invalid); + const auto& value = field.get_ref(); + Require(!value.empty() && (value == "0" || value.front() != '0') && + value.find_first_not_of("0123456789") == std::string::npos, "invalid_field", invalid); + uint64_t result = 0; + const auto parsed = std::from_chars(value.data(), value.data() + value.size(), result); + Require(parsed.ec == std::errc{} && parsed.ptr == value.data() + value.size(), "invalid_field", overflow); + return result; +} } json CommitResult::ToJson() const { @@ -60,19 +71,15 @@ 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", "childLists"}); + Fields(wire, {"schemaVersion", "surfaceId", "baseRevision", "rootChildren", "operations"}, + {"correlationId", "childLists", "eventsApplied"}); 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"); CommitBatch batch; { - Require(wire["baseRevision"].is_string(), "invalid_field", "baseRevision must be a canonical uint64 decimal string"); - const auto& value = wire["baseRevision"].get_ref(); - Require(!value.empty() && (value == "0" || value.front() != '0') && - value.find_first_not_of("0123456789") == std::string::npos, - "invalid_field", "baseRevision must be a canonical uint64 decimal string"); - const auto parsed = std::from_chars(value.data(), value.data() + value.size(), batch.baseRevision); - Require(parsed.ec == std::errc{} && parsed.ptr == value.data() + value.size(), "invalid_field", "baseRevision exceeds uint64"); + batch.baseRevision = ParseCounter(wire["baseRevision"], "baseRevision must be a canonical uint64 decimal string", + "baseRevision exceeds uint64"); Require(wire["rootChildren"].is_array(), "invalid_field", "rootChildren must be an array"); for (const auto& id : wire["rootChildren"]) batch.rootChildren.push_back(ParseNativeId(id)); } @@ -87,6 +94,9 @@ CommitBatch ParseCommit(json wire) { "invalid_field", "childLists must be \"complete\" or \"changed\""); batch.changedChildLists = mode == "changed"; } + if (wire.contains("eventsApplied")) + batch.eventsApplied = ParseCounter(wire["eventsApplied"], "eventsApplied must be a canonical uint64 decimal string", + "eventsApplied exceeds uint64"); for (auto& def : wire["operations"]) { try { Require(def.is_object() && def.contains("op"), "missing_field", "Operation requires op"); diff --git a/packages/dear-imgui/cpp/app/src/widget/input_text.cpp b/packages/dear-imgui/cpp/app/src/widget/input_text.cpp index dd73dc30..e7fb682a 100644 --- a/packages/dear-imgui/cpp/app/src/widget/input_text.cpp +++ b/packages/dear-imgui/cpp/app/src/widget/input_text.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -7,6 +8,12 @@ void InputText::Render(XFrames* view, const std::optional& viewport) { ImGui::PushID(m_id); + if (m_reloadEditBuffer) { + // The input's ImGui ID is that of its empty label inside this ID scope. The state + // exists only while the input is being edited. + if (auto* state = ImGui::GetInputTextState(ImGui::GetID(""))) state->ReloadUserBufAndMoveToEnd(); + m_reloadEditBuffer = false; + } if (m_multiline) { ImVec2 size(YGNodeLayoutGetWidth(m_layoutNode->m_node), YGNodeLayoutGetHeight(m_layoutNode->m_node)); ImGui::InputTextMultiline("", &m_value, size, m_inputTextFlags, InputTextCb, (void*)this); diff --git a/packages/dear-imgui/cpp/app/src/xframes.cpp b/packages/dear-imgui/cpp/app/src/xframes.cpp index 7a7ad274..95d05595 100644 --- a/packages/dear-imgui/cpp/app/src/xframes.cpp +++ b/packages/dear-imgui/cpp/app/src/xframes.cpp @@ -245,6 +245,7 @@ json XFrames::BuildDiagnosticsStateUnlocked() { if (auto* text = dynamic_cast(element.get())) record["state"] = {{"byteCount", text->m_textBuffer.size()}, {"lineCount", text->m_lineOffsets.Size}}; if (auto* table = dynamic_cast(element.get())) record["state"] = table->GetDiagnosticsState(); + if (auto* input = dynamic_cast(element.get())) record["state"] = {{"value", input->m_value}}; if (auto* table = dynamic_cast(element.get())) { record["state"] = {{"rowCount", table->m_data.size()}, {"columnCount", table->m_columns.size()}, {"filterDirty", table->m_filterDirty}, {"filteredCount", table->m_filteredIndices.size()}, @@ -859,6 +860,11 @@ void XFrames::DestroyElementUnlocked(const int id, std::vector* destroyedId // Clean up per-widget reactive subject m_elementInternalOpsSubject.erase(id); m_diagnosticsLastInternalOpMs.erase(id); + { + // An edit of a destroyed element cannot hold back an element that reuses its ID. + const std::lock_guard lock(m_eventMutex); + m_unsyncedEdits.erase(id); + } // Erase from element registry — triggers unique_ptr destructor chain: // LayoutNode::~LayoutNode frees YGNode, diff --git a/packages/dear-imgui/cpp/app/src/xframes_commit.cpp b/packages/dear-imgui/cpp/app/src/xframes_commit.cpp index d3751cd6..bf497070 100644 --- a/packages/dear-imgui/cpp/app/src/xframes_commit.cpp +++ b/packages/dear-imgui/cpp/app/src/xframes_commit.cpp @@ -101,6 +101,19 @@ CommitResult XFrames::ApplyCommitOperations(CommitBatch& batch) { result.nativeSequence = ++m_nativeSequence; std::optional operationIndex; try { + // With eventsApplied, controlled props are stored, not patched; the sync below + // decides whether each element shows them. + std::unordered_set controlled; + const auto takeControlled = [&](int id, json& props) { + if (!batch.eventsApplied) return; + auto& element = *m_elements.at(id); + for (const auto& name : element.ControlledProps()) { + if (!props.contains(name)) continue; + element.m_committedControlled[name] = props[name]; + props.erase(name); + controlled.insert(id); + } + }; // All creates precede patches, so forward references in the // complete candidate have one unambiguous meaning. for (auto kind : {CommitOp::Create, CommitOp::Patch}) { @@ -113,12 +126,17 @@ CommitResult XFrames::ApplyCommitOperations(CommitBatch& batch) { if (kind == CommitOp::Create) { def["type"] = op.elementType; CreateElementUnlocked(def); - } else PatchElementUnlocked(def); + takeControlled(op.id, def); + } else { + takeControlled(op.id, def); + PatchElementUnlocked(def); + } } } operationIndex.reset(); if (batch.changedChildLists) ApplyChangedChildLists(changed, result.destroyedIds); else ApplyCompleteChildLists(plan, result.destroyedIds); + if (batch.eventsApplied) SyncControlledUnlocked(*batch.eventsApplied, controlled); // 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)) @@ -224,12 +242,43 @@ void XFrames::ApplyChangedChildLists(const ChangedPublicationPlan& plan, std::ve } } +// The controlled-values rule. An element edited after eventsApplied keeps what the user +// typed: the application has not seen that edit, and its event will reach it. Any other +// element that was patched, created or edited shows its committed controlled values, even +// when this commit does not carry them, so a rejected or transformed edit is undone. +void XFrames::SyncControlledUnlocked(uint64_t eventsApplied, const std::unordered_set& touched) { + const std::lock_guard lock(m_eventMutex); + std::unordered_set candidates(touched); + for (const auto& [id, sequence] : m_unsyncedEdits) candidates.insert(id); + for (int id : candidates) { + if (const auto edit = m_unsyncedEdits.find(id); edit != m_unsyncedEdits.end()) { + if (edit->second > eventsApplied) continue; + m_unsyncedEdits.erase(edit); + } + const auto element = m_elements.find(id); + if (element == m_elements.end() || element->second->ControlledProps().empty()) continue; + element->second->ApplyControlled(element->second->m_committedControlled); + } +} + +uint64_t XFrames::NoteWidgetEvent(int id) { + const std::lock_guard lock(m_eventMutex); + const auto sequence = ++m_eventSequence; + if (id != 0) m_unsyncedEdits[id] = sequence; + return sequence; +} + +uint64_t XFrames::LastEventSequence() { + const std::lock_guard lock(m_eventMutex); + return m_eventSequence; +} + 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()}, - {"commitFeatures", json::array({"changedChildLists"})}}; + {"commitFeatures", json::array({"changedChildLists", "controlledValues"})}}; 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 1ca02a88..ef0055df 100644 --- a/packages/dear-imgui/cpp/tests/xframes_test.cpp +++ b/packages/dear-imgui/cpp/tests/xframes_test.cpp @@ -20,6 +20,7 @@ #include "widget/lua_canvas.h" #include "widget/janet_canvas.h" #include "widget/map_view.h" +#include "widget/input_text.h" using json = nlohmann::json; namespace { @@ -332,6 +333,68 @@ TEST_F(XFramesTest, VisibleRevisionFollowsAppliedPublicationsOnly) { EXPECT_EQ(std::to_string(xf->VisibleRevision()), xf->GetCommitState()["nativeRevision"].get()); } +// Controlled values: a commit's eventsApplied names the last widget event the +// application had applied. An element edited after it keeps what the user typed; +// any other shows the committed value, even when the commit does not patch it. +namespace { +json Applied(json wire, uint64_t events) { wire["eventsApplied"] = std::to_string(events); return wire; } +} +TEST_F(XFramesTest, ControlledValuesAreAdvertisedAndEventsAreNumbered) { + const auto features = xf->GetCommitState()["commitFeatures"]; + EXPECT_NE(std::find(features.begin(), features.end(), "controlledValues"), features.end()); + EXPECT_EQ(xf->LastEventSequence(), 0u); + EXPECT_EQ(xf->NoteWidgetEvent(0), 1u); + EXPECT_EQ(xf->NoteWidgetEvent(7), 2u); + EXPECT_EQ(xf->LastEventSequence(), 2u); + auto leadingZero = Wire(); leadingZero["eventsApplied"] = "01"; + Reject(leadingZero, "invalid_field"); + auto number = Wire(); number["eventsApplied"] = 3; + Reject(number, "invalid_field"); +} +TEST_F(XFramesTest, ControlledValueIsShownWithoutUnacknowledgedEdits) { + const auto text = [&] { return static_cast(ElementAt(1))->m_value; }; + auto created = xf->ApplyCommit(Applied(Wire({{0, {1}}, {1, {}}}, {Create(1, "input-text", {{"value", "a"}})}), 0).dump()); + ASSERT_EQ(created.status, "applied") << created.ToJson(); + EXPECT_EQ(text(), "a"); + // Nobody edited it: a patch is shown at once. + ASSERT_EQ(xf->ApplyCommit(Applied(Wire({{0, {1}}, {1, {}}}, {Patch(1, {{"value", "x"}})}), 0).dump()).status, "applied"); + EXPECT_EQ(text(), "x"); + EXPECT_EQ(ElementAt(1)->m_committedControlled, (json{{"value", "x"}})); +} +TEST_F(XFramesTest, EditAfterEventsAppliedKeepsTheUsersValueUntilAcknowledged) { + const auto input = [&] { return static_cast(ElementAt(1)); }; + ASSERT_EQ(xf->ApplyCommit(Applied(Wire({{0, {1}}, {1, {}}}, {Create(1, "input-text", {{"value", ""}})}), 0).dump()).status, "applied"); + // The user types "a" (event 1), then "ab" (event 2). A commit built after event 1 crosses event 2. + input()->SetValue("a"); const auto first = xf->NoteWidgetEvent(1); + input()->SetValue("ab"); const auto second = xf->NoteWidgetEvent(1); + ASSERT_EQ(xf->ApplyCommit(Applied(Wire({{0, {1}}, {1, {}}}, {Patch(1, {{"value", "a"}})}), first).dump()).status, "applied"); + EXPECT_EQ(input()->m_value, "ab"); + EXPECT_EQ(input()->m_committedControlled["value"], "a"); + // The model rejected "ab" and kept "a": a commit acknowledging event 2, with no patch, restores it. + ASSERT_EQ(xf->ApplyCommit(Applied(Wire({{0, {1}}, {1, {}}}), second).dump()).status, "applied"); + EXPECT_EQ(input()->m_value, "a"); + EXPECT_TRUE(input()->m_reloadEditBuffer); + // Settled: with no new edit, a commit that does not touch it leaves it alone. + input()->m_value = "untouched"; + ASSERT_EQ(xf->ApplyCommit(Applied(Wire({{0, {1}}, {1, {}}}), second).dump()).status, "applied"); + EXPECT_EQ(input()->m_value, "untouched"); +} +TEST_F(XFramesTest, ControlledValuesWithoutEventsAppliedAreIgnoredAsBefore) { + Publish({{0, {1}}, {1, {}}}, {Create(1, "input-text", {{"value", "a"}})}); + EXPECT_EQ(static_cast(ElementAt(1))->m_value, ""); + Publish({{0, {1}}, {1, {}}}, {Patch(1, {{"value", "b"}})}); + EXPECT_EQ(static_cast(ElementAt(1))->m_value, ""); + EXPECT_TRUE(ElementAt(1)->m_committedControlled.empty()); +} +TEST_F(XFramesTest, DestroyingAnElementForgetsItsUnacknowledgedEdit) { + ASSERT_EQ(xf->ApplyCommit(Applied(Wire({{0, {1}}, {1, {}}}, {Create(1, "input-text", {{"value", "a"}})}), 0).dump()).status, "applied"); + xf->NoteWidgetEvent(1); + ASSERT_EQ(xf->ApplyCommit(Applied(Wire(), 0).dump()).status, "applied"); + // The ID comes back for a new input: the old edit does not hold its value back. + ASSERT_EQ(xf->ApplyCommit(Applied(Wire({{0, {1}}, {1, {}}}, {Create(1, "input-text", {{"value", "new"}})}), 0).dump()).status, "applied"); + EXPECT_EQ(static_cast(ElementAt(1))->m_value, "new"); +} + // "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 {