Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/dear-imgui/cpp/app/include/commit.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint64_t> eventsApplied;
};

struct CommitError : std::runtime_error {
Expand Down
12 changes: 12 additions & 0 deletions packages/dear-imgui/cpp/app/include/element/element.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string>& ControlledProps() const {
static const std::vector<std::string> 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);
Expand Down
17 changes: 17 additions & 0 deletions packages/dear-imgui/cpp/app/include/widget/input_text.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string>& ControlledProps() const override {
static const std::vector<std::string> 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<const std::string&>();
if (value == m_value) return;
m_value = value;
m_reloadEditBuffer = true;
}

void Init(const json& elementDef) override {
Element::Init(elementDef);

Expand Down
13 changes: 13 additions & 0 deletions packages/dear-imgui/cpp/app/include/xframes.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ class XFrames {
xframes::CommitResult ApplyCommitOperations(xframes::CommitBatch& batch);
void ApplyCompleteChildLists(xframes::PublicationPlan& plan, std::vector<int>& destroyedIds);
void ApplyChangedChildLists(const xframes::ChangedPublicationPlan& plan, std::vector<int>& 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<int, uint64_t> m_unsyncedEdits;
// Shows committed controlled values where the element has no unacknowledged edit.
void SyncControlledUnlocked(uint64_t eventsApplied, const std::unordered_set<int>& touched);

std::unordered_map<std::string, std::function<std::unique_ptr<Element>(const json&, std::optional<WidgetStyle>, XFrames*)>> m_element_init_fn;

Expand Down Expand Up @@ -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();



Expand Down
26 changes: 18 additions & 8 deletions packages/dear-imgui/cpp/app/src/commit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ void Fields(const json& value, std::initializer_list<const char*> 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<const std::string&>();
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 {
Expand Down Expand Up @@ -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<const std::string&>();
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));
}
Expand All @@ -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");
Expand Down
7 changes: 7 additions & 0 deletions packages/dear-imgui/cpp/app/src/widget/input_text.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <imgui.h>
#include <imgui_internal.h>
#include <string>
#include <nlohmann/json.hpp>

Expand All @@ -7,6 +8,12 @@

void InputText::Render(XFrames* view, const std::optional<ImRect>& 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);
Expand Down
6 changes: 6 additions & 0 deletions packages/dear-imgui/cpp/app/src/xframes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ json XFrames::BuildDiagnosticsStateUnlocked() {
if (auto* text = dynamic_cast<ClippedMultiLineTextRenderer*>(element.get()))
record["state"] = {{"byteCount", text->m_textBuffer.size()}, {"lineCount", text->m_lineOffsets.Size}};
if (auto* table = dynamic_cast<VirtualTable*>(element.get())) record["state"] = table->GetDiagnosticsState();
if (auto* input = dynamic_cast<InputText*>(element.get())) record["state"] = {{"value", input->m_value}};
if (auto* table = dynamic_cast<Table*>(element.get())) {
record["state"] = {{"rowCount", table->m_data.size()}, {"columnCount", table->m_columns.size()},
{"filterDirty", table->m_filterDirty}, {"filteredCount", table->m_filteredIndices.size()},
Expand Down Expand Up @@ -859,6 +860,11 @@ void XFrames::DestroyElementUnlocked(const int id, std::vector<int>* 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<std::mutex> lock(m_eventMutex);
m_unsyncedEdits.erase(id);
}

// Erase from element registry — triggers unique_ptr destructor chain:
// LayoutNode::~LayoutNode frees YGNode,
Expand Down
53 changes: 51 additions & 2 deletions packages/dear-imgui/cpp/app/src/xframes_commit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,19 @@ CommitResult XFrames::ApplyCommitOperations(CommitBatch& batch) {
result.nativeSequence = ++m_nativeSequence;
std::optional<size_t> operationIndex;
try {
// With eventsApplied, controlled props are stored, not patched; the sync below
// decides whether each element shows them.
std::unordered_set<int> 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}) {
Expand All @@ -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))
Expand Down Expand Up @@ -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<int>& touched) {
const std::lock_guard<std::mutex> lock(m_eventMutex);
std::unordered_set<int> 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<std::mutex> 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<std::mutex> lock(m_eventMutex);
return m_eventSequence;
}

json XFrames::GetCommitState() {
const std::lock_guard<std::mutex> 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;
}
63 changes: 63 additions & 0 deletions packages/dear-imgui/cpp/tests/xframes_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -332,6 +333,68 @@ TEST_F(XFramesTest, VisibleRevisionFollowsAppliedPublicationsOnly) {
EXPECT_EQ(std::to_string(xf->VisibleRevision()), xf->GetCommitState()["nativeRevision"].get<std::string>());
}

// 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<InputText*>(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<InputText*>(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<InputText*>(ElementAt(1))->m_value, "");
Publish({{0, {1}}, {1, {}}}, {Patch(1, {{"value", "b"}})});
EXPECT_EQ(static_cast<InputText*>(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<InputText*>(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 {
Expand Down
Loading