Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
ui_model_edit_core.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/detail/model_edit.hpp>
6#include <portals/ui_model.hpp>
7
8namespace portals::ui::detail {
10
11struct EditAccess {
12 static EditorCommandResult command(ManagedNavigation, std::expected<void, TreeError>, std::source_location);
13
14 static TreeError cause(const ManagedError &error) {
15 const auto *tree = std::get_if<TreeError>(&error.cause);
16 return tree ? *tree : TreeError::CALLBACK_FAILED;
17 }
18
19 template <class Row> static Model<Row> model(const Navigation<Row> &navigation) {
20 return navigation.data_ ? navigation.data_->initial : Model<Row>{};
21 }
22
23 template <class Row> static Model<Row> model(const std::shared_ptr<portals::detail::ManagedModelSource> &source) {
24 Model<Row> result;
25 if (!std::dynamic_pointer_cast<portals::detail::ManagedModelSourceOf<Row>>(source)) {
26 return result;
27 }
28 if (auto declaration = source->editDeclaration) {
29 result.data_ = std::static_pointer_cast<ModelDeclarationBase>(declaration);
30 }
31 return result;
32 }
33
34 template <class Row> static std::expected<ManagedModel<Row>, TreeError> provisional(const Model<Row> &model) {
35 if (!model.data_ || model.data_->kind != ModelDeclarationBase::Kind::COLLECTION) {
36 return std::unexpected(TreeError::INVALID_ARGUMENT);
37 }
38 auto data = std::static_pointer_cast<ModelDeclaration<Row>>(model.data_);
39 auto valid = portals::detail::ManagedModelAccess::validate(data->handle, data->scene);
40 return valid ? std::expected<ManagedModel<Row>, TreeError>(data->handle) : std::unexpected(valid.error());
41 }
42
43 template <class Row>
44 static std::expected<SourceStamp, TreeError>
45 sourceSession(const std::shared_ptr<portals::detail::ManagedModelSource> &source) {
46 const auto typed = std::dynamic_pointer_cast<portals::detail::ManagedModelSourceOf<Row>>(source);
47 if (!typed || typed->retired || !typed->model) {
48 return std::unexpected(TreeError::CLOSED);
49 }
50 return SourceStamp{typed->model->state_->session, 1};
51 }
52
53 template <class Row> static std::shared_ptr<OwnedSequence<Row>> sequence(const Model<Row> &model) {
54 return model.data_ && model.data_->kind == ModelDeclarationBase::Kind::COLLECTION
55 ? std::static_pointer_cast<ModelDeclaration<Row>>(model.data_)->sequence
56 : nullptr;
57 }
58
59 template <class Row> static NodeId scene(const Model<Row> &model) {
60 return model.data_ ? model.data_->scene : NodeId{};
61 }
62
63 static std::expected<std::shared_ptr<portals::detail::ManagedNavigationRecord>, TreeError>
64 context(const ManagedNavigation &navigation) {
65 return navigation.lock();
66 }
67
68 template <class Row>
69 static std::expected<std::uint64_t, TreeError> replace(const Model<Row> &model, RowId id, std::uint64_t version,
70 const Row &value) {
71 std::uint64_t acceptedVersion{};
72 const typename Model<Row>::Replacement replacement{id, value, version, &acceptedVersion};
73 auto result = model.mutate(
74 {}, false,
75 [&](auto &rows, auto old, std::uint64_t) {
76 for (const auto &row : old) {
77 rows.emplace_back(row.id, row.id == id ? value : row.value);
78 }
79 },
80 &replacement);
81 return result ? std::expected<std::uint64_t, TreeError>(acceptedVersion) : std::unexpected(cause(result.error()));
82 }
83};
84
85template <class Value> std::expected<std::size_t, TreeError> editValueBytes(const Value &value) {
86 if constexpr (std::same_as<Value, std::string>) {
87 return sizeof(Value) + value.capacity() + 1;
88 } else if constexpr (std::is_trivially_copyable_v<Value>) {
89 return sizeof(Value);
90 } else {
91 return std::unexpected(TreeError::INVALID_ARGUMENT);
92 }
93}
94
95template <class Value>
96std::expected<Value, TreeError> parseEditText(const std::shared_ptr<const EditTextCodec<Value>> &codec,
97 std::string_view candidate) {
98 if (codec && codec->parse) {
99 return codec->parse(candidate);
100 }
101 if constexpr (std::same_as<Value, std::string>) {
102 return std::expected<Value, TreeError>(std::in_place, candidate);
103 } else {
104 return std::unexpected(TreeError::INVALID_ARGUMENT);
105 }
106}
107
108template <class Row, class Value> class OwnedFieldEndpoint final : public EditEndpoint<Value> {
109public:
110 OwnedFieldEndpoint(Model<Row> model, Value Row::*member, EditTarget identity, std::size_t maxBytes,
111 std::optional<std::size_t> maxTextBytes)
112 : model_(std::move(model)), member_(member), resource_(identity.resource), identity_(std::move(identity)),
113 maxBytes_(maxBytes), maxTextBytes_(maxTextBytes) {
114 }
115
116 EditCapabilities capabilities() const noexcept override {
117 return {static_cast<bool>(EditAccess::sequence(model_)), true, false, false, true};
118 }
119
120 std::expected<EditRecord<Value>, TreeError> read(ModelResource resource, RowId row) override {
121 auto managed = EditAccess::provisional(model_);
122 if (!managed) {
123 return std::unexpected(managed.error());
124 }
125 if (resource != resource_ || row != identity_.row || !member_) {
126 return std::unexpected(TreeError::INVALID_ARGUMENT);
127 }
128 auto sequence = EditAccess::sequence(model_);
129 if (!sequence || !sequence->current) {
130 return std::unexpected(TreeError::INVALID_ARGUMENT);
131 }
132 const auto previous = sequence->current;
133 const auto location = previous->locateRow(row);
134 if (location.state != RowLookupState::FOUND) {
135 return std::unexpected(TreeError::STALE_NODE);
136 }
137 if (sequence->editing) {
138 return std::unexpected(TreeError::WOULD_BLOCK);
139 }
140 if (!sequence->editVersions) {
141 sequence->editVersions = std::make_shared<std::vector<std::weak_ptr<OwnedEditVersion>>>(0);
142 }
143 std::erase_if(*sequence->editVersions, [](const auto &weak) {
144 return weak.expired();
145 });
146 auto version = version_;
147 if (!version) {
148 for (const auto &weak : *sequence->editVersions) {
149 auto entry = weak.lock();
150 if (entry && entry->row == row) {
151 version = std::move(entry);
152 break;
153 }
154 }
155 }
156 if (!version) {
157 version = std::make_shared<OwnedEditVersion>(OwnedEditVersion{row, previous->revision()});
158 sequence->editVersions->push_back(version);
159 }
160 version_ = version;
161 if (cachedRow_ == row && cachedVersion_ == version->version) {
162 if (auto cached = cachedValue_.lock()) {
163 return EditRecord<Value>{std::move(cached), cachedVersion_};
164 }
165 }
166 if constexpr (std::same_as<Value, std::string>) {
167 if (maxTextBytes_ && (previous->rows()[location.index].value.*member_).size() > *maxTextBytes_) {
168 return std::unexpected(TreeError::INVALID_ARGUMENT);
169 }
170 }
171 auto size = editValueBytes(previous->rows()[location.index].value.*member_);
172 if (!size) {
173 return std::unexpected(size.error());
174 }
175 if (*size > maxBytes_) {
176 return std::unexpected(TreeError::NODE_LIMIT);
177 }
178 const auto expectedVersion = version->version;
179 auto value = std::make_shared<const Value>(previous->rows()[location.index].value.*member_);
180 if (sequence->current != previous || version->version != expectedVersion) {
181 return std::unexpected(TreeError::WOULD_BLOCK);
182 }
183 auto live = EditAccess::provisional(model_);
184 if (!live) {
185 return std::unexpected(live.error());
186 }
187 cachedValue_ = value;
188 cachedVersion_ = expectedVersion;
189 cachedRow_ = row;
190 return EditRecord<Value>{std::move(value), expectedVersion};
191 }
192
193 std::expected<EditReceipt, TreeError> submit(EditRequest<Value> request) override {
194 if (!request.value || request.target.resource != resource_ || request.target.session != identity_.session ||
195 request.target.sourceSession != identity_.sourceSession || request.target.row != identity_.row ||
196 request.target.field != identity_.field || !request.target.baseVersion || !request.target.sequence) {
197 return std::unexpected(TreeError::INVALID_ARGUMENT);
198 }
199 auto current = read(resource_, request.target.row);
200 if (!current) {
201 return EditReceipt{request.target,
202 current.error() == TreeError::STALE_NODE ? EditStatus::TARGET_MISSING : EditStatus::CLOSED, 0,
203 current.error()};
204 }
205 if (current->version != request.target.baseVersion) {
206 return EditReceipt{request.target, EditStatus::CONFLICT};
207 }
208 auto sequence = EditAccess::sequence(model_);
209 const auto previous = sequence->current;
210 const auto location = previous->locateRow(request.target.row);
211 Row candidate(previous->rows()[location.index].value);
212 candidate.*member_ = *request.value;
213 auto applied = EditAccess::replace(model_, request.target.row, request.target.baseVersion, candidate);
214 if (!applied) {
215 return EditReceipt{request.target,
216 applied.error() == TreeError::WOULD_BLOCK ? EditStatus::CONFLICT : EditStatus::REJECTED, 0,
217 applied.error()};
218 }
219 return EditReceipt{request.target, EditStatus::ACCEPTED, *applied};
220 }
221
222 std::expected<std::size_t, TreeError> ownedBytes(const Value &value) const override {
223 return editValueBytes(value);
224 }
225
226private:
227 Model<Row> model_;
228 Value Row::*member_;
229 ModelResource resource_;
230 EditTarget identity_;
231 std::size_t maxBytes_;
232 std::optional<std::size_t> maxTextBytes_;
233 std::shared_ptr<OwnedEditVersion> version_;
234 RowId cachedRow_;
235 std::weak_ptr<const Value> cachedValue_;
236 std::uint64_t cachedVersion_{};
237};
238
239template <class Row, class Value> class ReadOnlyFieldEndpoint final : public EditEndpoint<Value> {
240public:
241 ReadOnlyFieldEndpoint(Model<Row> model, Value Row::*member, ModelResource resource, std::size_t maxBytes,
242 std::optional<std::size_t> maxTextBytes)
243 : model_(std::move(model)), member_(member), resource_(resource), maxBytes_(maxBytes),
244 maxTextBytes_(maxTextBytes) {
245 }
246
247 EditCapabilities capabilities() const noexcept override {
248 return {};
249 }
250
251 std::expected<EditRecord<Value>, TreeError> read(ModelResource resource, RowId row) override {
252 if (resource != resource_) {
253 return std::unexpected(TreeError::INVALID_ARGUMENT);
254 }
255 auto handle = EditAccess::provisional(model_);
256 if (!handle) {
257 return std::unexpected(handle.error());
258 }
259 auto snapshot = portals::detail::ManagedModelAccess::snapshot(*handle, EditAccess::scene(model_));
260 if (!snapshot) {
261 return std::unexpected(snapshot.error());
262 }
263 const auto found = (*snapshot)->locateRow(row);
264 if (found.state != RowLookupState::FOUND) {
265 return std::unexpected(TreeError::WOULD_BLOCK);
266 }
267 auto rows = (*snapshot)->read({found.index, 1});
268 if (rows.state != RangeState::READY || rows.rows.size() != 1 || rows.rows.front().id != row) {
269 return std::unexpected(TreeError::WOULD_BLOCK);
270 }
271 const auto &value = rows.rows.front().value.*member_;
272 if constexpr (std::same_as<Value, std::string>) {
273 if (maxTextBytes_ && value.size() > *maxTextBytes_) {
274 return std::unexpected(TreeError::INVALID_ARGUMENT);
275 }
276 }
277 auto size = editValueBytes(value);
278 if (!size || *size > maxBytes_) {
279 return std::unexpected(size ? TreeError::NODE_LIMIT : size.error());
280 }
281
282 return EditRecord<Value>{std::make_shared<const Value>(value), (*snapshot)->revision()};
283 }
284
285 std::expected<EditReceipt, TreeError> submit(EditRequest<Value> request) override {
286 return EditReceipt{request.target, EditStatus::READ_ONLY};
287 }
288
289 std::expected<std::size_t, TreeError> ownedBytes(const Value &value) const override {
290 return editValueBytes(value);
291 }
292
293private:
294 Model<Row> model_;
295 Value Row::*member_;
296 ModelResource resource_;
297 std::size_t maxBytes_;
298 std::optional<std::size_t> maxTextBytes_;
299};
300
301inline std::shared_ptr<portals::detail::EditTextBinding>
302selectEditBinding(const std::vector<std::weak_ptr<portals::detail::EditTextBinding>> &bindings, const void *entry) {
303 std::shared_ptr<portals::detail::EditTextBinding> chosen;
304 for (const auto &weak : bindings) {
305 auto binding = weak.lock();
306 if (!binding || binding->closed || binding->displayedEntry != entry) {
307 continue;
308 }
309 if (!chosen || (binding->validatedByEditor && !chosen->validatedByEditor)) {
310 chosen = std::move(binding);
311 }
312 }
313 return chosen;
314}
315
316inline bool preferredEditBinding(const std::vector<std::weak_ptr<portals::detail::EditTextBinding>> &bindings,
317 const std::shared_ptr<portals::detail::EditTextBinding> &candidate) {
318 return selectEditBinding(bindings, candidate->displayedEntry) == candidate;
319}
320
321// Preserve registration order: the first eligible live FormField wins over plain editors.
322// A cold recipe has no displayed draft, and a removed editor closes its binding.
323inline std::shared_ptr<portals::detail::EditTextBinding>
324selectEditPolicy(const std::vector<std::weak_ptr<portals::detail::EditTextBinding>> &bindings, const void *definition) {
325 std::shared_ptr<portals::detail::EditTextBinding> chosen;
326 for (const auto &weak : bindings) {
327 auto binding = weak.lock();
328 if (!binding || binding->closed || !binding->displayed || binding->definition != definition ||
329 !binding->validateForCommit) {
330 continue;
331 }
332 if (!chosen || (binding->validatedByEditor && !chosen->validatedByEditor)) {
333 chosen = std::move(binding);
334 }
335 }
336
337 return chosen;
338}
339
340template <class Row> struct EditState;
341
342struct EditDefinitionBase {
343 virtual ~EditDefinitionBase() = default;
344 EditFieldKey key;
345 std::function<std::expected<void, TreeError>(const NavigationPosition &,
346 const std::shared_ptr<portals::detail::ManagedModelSource> &)>
347 prepare;
348};
349
350template <class Row, class Value> struct EditDefinition final : EditDefinitionBase {
351 Value Row::*member{};
352 std::shared_ptr<EditEndpoint<Value>> endpoint;
353 std::function<bool(const Value &)> validate;
354 std::shared_ptr<const EditTextCodec<Value>> textCodec;
355 std::optional<std::size_t> maxTextBytes;
356 bool active{};
357};
358
359struct EditEntryBase {
360 virtual ~EditEntryBase() = default;
361 EditTarget target;
362 EditStatus status{EditStatus::CLEAN};
363 EditReceipt lastReceipt;
364 std::shared_ptr<const FieldValidation> validation;
365 std::size_t validationCharge{};
366 std::size_t charge{};
367 bool discarded{};
368 bool admissionRefused{};
369 bool cancelReadPinned{};
370 virtual bool hasDraft() const noexcept = 0;
371 virtual bool pristine() const noexcept = 0;
372 virtual std::expected<EditReceipt, TreeError> commit() = 0;
373 virtual std::expected<void, TreeError> prepareCancel() = 0;
374 virtual std::expected<void, TreeError> cancel(bool discard) = 0;
375 virtual std::expected<bool, TreeError> reply(const EditReceipt &) = 0;
376 virtual void rebase(std::uint64_t oldVersion, std::uint64_t newVersion) = 0;
377};
378
379template <class Row, class Value> struct EditEntry final : EditEntryBase {
380 struct Pending {
381 EditTarget target;
382 std::shared_ptr<const Value> value;
383 std::uint64_t generation;
384 };
385
386 std::weak_ptr<EditState<Row>> owner;
387 std::shared_ptr<EditDefinition<Row, Value>> definition;
388 std::shared_ptr<EditEndpoint<Value>> endpoint;
389 std::shared_ptr<const Value> accepted;
390 std::shared_ptr<const Value> draft;
391 std::unique_ptr<portals::detail::EditTextDraft> text;
392 std::shared_ptr<const PropertyChange<std::string>> textSnapshot;
393 std::vector<Pending> pending = std::vector<Pending>(0);
394 std::uint64_t generation{};
395 std::size_t textCharge{};
396 std::size_t snapshotCharge{};
397 std::uint64_t acceptedSequence{};
398 std::uint64_t observedVersion{}; // Version paired with the admitted accepted value.
399 std::uint64_t witnessedVersion{}; // Read/receipt watermark, including values refused by the budget.
400 std::uint64_t validatedGeneration{std::numeric_limits<std::uint64_t>::max()};
401 bool requiresAsyncValidation{};
402
403 std::expected<std::string, TreeError> format(const Value &value) const {
404 if (definition->textCodec && definition->textCodec->format) {
405 return definition->textCodec->format(value);
406 }
407 if constexpr (std::same_as<Value, std::string>) {
408 return std::expected<std::string, TreeError>(std::in_place, value);
409 } else {
410 return std::unexpected(TreeError::INVALID_ARGUMENT);
411 }
412 }
413
414 std::expected<Value, TreeError> parse(std::string_view value) const {
415 return parseEditText(definition->textCodec, value);
416 }
417
418 std::expected<std::size_t, TreeError> retainedCharge(const Value *candidate, std::size_t nextTextCharge,
419 bool copiesCandidate = false,
420 std::optional<std::size_t> pendingCapacity = {},
421 const Value *nextAccepted = nullptr,
422 std::optional<std::size_t> nextSnapshotCharge = {}) const {
423 auto state = owner.lock();
424 if (!state) {
425 return std::unexpected(TreeError::CLOSED);
426 }
427 const auto endpointOwner = endpoint;
428 if (discarded || !endpointOwner) {
429 return std::unexpected(TreeError::STALE_NODE);
430 }
431 if (state->accounting) {
432 return std::unexpected(TreeError::WOULD_BLOCK);
433 }
434
435 struct Accounting {
436 bool &active;
437
438 explicit Accounting(bool &value) : active(value) {
439 active = true;
440 }
441
442 ~Accounting() {
443 active = false;
444 }
445 } accounting(state->accounting);
446
447 const auto acceptedOwner = accepted;
448 const auto draftOwner = draft;
449 const auto originalTarget = target;
450 const auto originalGeneration = text ? text->generation : generation;
451 const auto originalPendingCount = pending.size();
452 auto unchanged = [&]() -> std::expected<void, TreeError> {
453 if (discarded || endpoint != endpointOwner || state->endpointClosed) {
454 return std::unexpected(TreeError::CLOSED);
455 }
456 if (target != originalTarget || accepted != acceptedOwner || draft != draftOwner ||
457 (text ? text->generation : generation) != originalGeneration || pending.size() != originalPendingCount) {
458 return std::unexpected(TreeError::WOULD_BLOCK);
459 }
460 return {};
461 };
462 const auto limit = state->options.maxRetainedBytes;
463 const auto capacity = pendingCapacity.value_or(pending.capacity());
464 std::size_t total = sizeof(*this);
465 auto add = [&](std::size_t count) -> bool {
466 if (total > limit || count > limit - total) {
467 return false;
468 }
469 total += count;
470 return true;
471 };
472 if (!add(nextTextCharge) || !add(validationCharge) || !add(nextSnapshotCharge.value_or(snapshotCharge)) ||
473 capacity > limit / sizeof(Pending) || !add(capacity * sizeof(Pending))) {
474 return std::unexpected(TreeError::NODE_LIMIT);
475 }
476 auto addValue = [&](const Value *value) -> std::expected<void, TreeError> {
477 if (!value) {
478 return {};
479 }
480 auto size = endpointOwner->ownedBytes(*value);
481 auto live = unchanged();
482 if (!live) {
483 return live;
484 }
485 if (!size) {
486 return std::unexpected(size.error());
487 }
488 return add(*size) ? std::expected<void, TreeError>{} : std::unexpected(TreeError::NODE_LIMIT);
489 };
490 const auto *acceptedValue = nextAccepted ? nextAccepted : acceptedOwner.get();
491 auto base = addValue(acceptedValue);
492 if (!base) {
493 return std::unexpected(base.error());
494 }
495 if (candidate && (copiesCandidate || candidate != acceptedValue)) {
496 auto added = addValue(candidate);
497 if (!added) {
498 return std::unexpected(added.error());
499 }
500 }
501 for (std::size_t index = 0; index < pending.size(); ++index) {
502 const auto pendingOwner = pending[index].value;
503 const auto *value = pendingOwner.get();
504 if (value == acceptedValue || (!copiesCandidate && value == candidate)) {
505 continue;
506 }
507 bool counted = false;
508 for (std::size_t previous = 0; previous < index; ++previous) {
509 counted = counted || pending[previous].value.get() == value;
510 }
511 if (!counted) {
512 auto added = addValue(value);
513 if (!added) {
514 return std::unexpected(added.error());
515 }
516 }
517 }
518 return total;
519 }
520
521 std::expected<void, TreeError> refresh() {
522 admissionRefused = false;
523 if (discarded || !endpoint) {
524 return std::unexpected(TreeError::STALE_NODE);
525 }
526 if (cancelReadPinned) {
527 return {};
528 }
529 const auto state = owner.lock();
530 if (!state) {
531 return std::unexpected(TreeError::CLOSED);
532 }
533 if (state->accounting) {
534 return std::unexpected(TreeError::WOULD_BLOCK);
535 }
536 const auto endpointOwner = endpoint;
537 const auto retainedDraft = draft;
538 auto value = endpointOwner->read(target.resource, target.row);
539 if (discarded || endpoint != endpointOwner) {
540 return std::unexpected(TreeError::STALE_NODE);
541 }
542 if (!value) {
543 if (value.error() == TreeError::STALE_NODE) {
544 status = EditStatus::TARGET_MISSING;
545 }
546 return std::unexpected(value.error());
547 }
548 if (!value->value || !value->version) {
549 return std::unexpected(TreeError::INVALID_ARGUMENT);
550 }
551 if (value->version < std::max(observedVersion, witnessedVersion)) {
552 return std::unexpected(TreeError::WOULD_BLOCK);
553 }
554 // A valid read witnesses the version even when retaining its payload is refused.
555 witnessedVersion = value->version;
556 auto localFailure = [&](TreeError error) -> std::expected<void, TreeError> {
557 admissionRefused = error == TreeError::NODE_LIMIT;
558 return std::unexpected(error);
559 };
560 auto nextSnapshot = textSnapshot;
561 auto nextSnapshotBytes = snapshotCharge;
562 if constexpr (std::same_as<Value, std::string>) {
563 if (!definition->textCodec && (!nextSnapshot || nextSnapshot->revision != value->version)) {
564 if (value->value->capacity() >
565 std::numeric_limits<std::size_t>::max() - sizeof(PropertyChange<std::string>) - 1) {
566 return localFailure(TreeError::NODE_LIMIT);
567 }
568 nextSnapshotBytes = sizeof(PropertyChange<std::string>) + value->value->capacity() + 1;
569 }
570 }
571 // Refuse known oversized input before copying the UI's owning string snapshot.
572 if (charge) {
573 auto estimated =
574 retainedCharge(retainedDraft.get(), textCharge, false, {}, value->value.get(), nextSnapshotBytes);
575 if (!estimated) {
576 return localFailure(estimated.error());
577 }
578 auto checked = state->checkCredit(*this, *estimated, false);
579 if (!checked) {
580 return localFailure(checked.error());
581 }
582 }
583 if constexpr (std::same_as<Value, std::string>) {
584 if (!definition->textCodec && (!nextSnapshot || nextSnapshot->revision != value->version)) {
585 nextSnapshot = std::make_shared<const PropertyChange<std::string>>(
586 PropertyChange<std::string>{*value->value, value->version});
587 nextSnapshotBytes = sizeof(PropertyChange<std::string>) + nextSnapshot->value.capacity() + 1;
588 }
589 }
590 if (definition->textCodec && (!nextSnapshot || nextSnapshot->revision != value->version)) {
591 auto formatted = format(*value->value);
592 if (!formatted) {
593 return localFailure(formatted.error());
594 }
595 nextSnapshot =
596 std::make_shared<const PropertyChange<std::string>>(PropertyChange<std::string>{*formatted, value->version});
597 nextSnapshotBytes = sizeof(PropertyChange<std::string>) + nextSnapshot->value.capacity() + 1;
598 }
599 if (charge) {
600 auto nextCharge =
601 retainedCharge(retainedDraft.get(), textCharge, false, {}, value->value.get(), nextSnapshotBytes);
602 if (!nextCharge) {
603 return localFailure(nextCharge.error());
604 }
605 if (discarded || endpoint != endpointOwner || state->endpointClosed) {
606 return std::unexpected(TreeError::CLOSED);
607 }
608 if (value->version < witnessedVersion) {
609 return std::unexpected(TreeError::WOULD_BLOCK);
610 }
611 auto admitted = state->admit(*this, *nextCharge, false);
612 if (!admitted) {
613 return localFailure(admitted.error());
614 }
615 }
616 const auto previousAccepted = std::exchange(accepted, value->value);
617 if (!draft && (!text || !text->dirty) && pending.empty()) {
618 target.baseVersion = value->version;
619 }
620 observedVersion = value->version;
621 textSnapshot = std::move(nextSnapshot);
622 snapshotCharge = nextSnapshotBytes;
623 return {};
624 }
625
626 std::expected<void, TreeError> prepareCancel() override {
627 if (cancelReadPinned) {
628 return std::unexpected(TreeError::WOULD_BLOCK);
629 }
630 return refresh();
631 }
632
633 bool hasDraft() const noexcept override {
634 return draft || (text && text->dirty);
635 }
636
637 bool pristine() const noexcept override {
638 return !discarded && !hasDraft() && pending.empty() && status != EditStatus::DIRTY &&
639 (!text || !text->history->operationCount()) && (!validation || validation->status == FieldStatus::UNCHECKED);
640 }
641
642 std::expected<void, TreeError> setRetainedText(const Value &typedValue, const std::string &value) {
643 const auto state = owner.lock();
644 if (!state || state->endpointClosed || discarded || !text) {
645 return std::unexpected(TreeError::CLOSED);
646 }
647 if (text->generation == std::numeric_limits<std::uint64_t>::max()) {
648 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
649 }
650 auto precharge = retainedCharge(&typedValue, textCharge, true);
651 if (!precharge) {
652 return std::unexpected(precharge.error());
653 }
654 auto checked = state->checkCredit(*this, *precharge);
655 if (!checked) {
656 return checked;
657 }
658 const auto beforeGeneration = text->generation;
659 auto prepared = text->history->prepareEdit({std::string(text->text.bytes()), text->cursor, text->anchor},
660 {value, value.size(), value.size()}, TextHistoryKind::PROGRAMMATIC);
661 if (!prepared) {
662 return std::unexpected(prepared.error() == TextHistoryError::NO_MEMORY ? TreeError::NO_MEMORY
663 : TreeError::INVALID_ARGUMENT);
664 }
665 std::unique_ptr<GraphemeText> mask;
666 if (text->mask) {
667 auto masked =
668 GraphemeText::from(std::string(prepared->text()->graphemes().size(), '*'), text->text.policy(), text->limits);
669 if (!masked) {
670 return std::unexpected(TreeError::INVALID_ARGUMENT);
671 }
672 mask = std::make_unique<GraphemeText>(std::move(*masked));
673 }
674 auto candidate = std::make_shared<const Value>(typedValue);
675 auto nextTextCharge =
676 portals::detail::EditStorageAccess::draftBytes(*prepared->text(), mask.get(), prepared->retainedBytes());
677 if (!nextTextCharge) {
678 return std::unexpected(nextTextCharge.error());
679 }
680 auto finalCharge = retainedCharge(candidate.get(), *nextTextCharge);
681 if (!finalCharge) {
682 return std::unexpected(finalCharge.error());
683 }
684 auto ready = text->history->checkPrepared(*prepared);
685 if (!ready || beforeGeneration != text->generation) {
686 return std::unexpected(TreeError::WOULD_BLOCK);
687 }
688 if (discarded || state->endpointClosed) {
689 return std::unexpected(TreeError::CLOSED);
690 }
691 auto admitted = state->admit(*this, *finalCharge);
692 if (!admitted) {
693 return admitted;
694 }
695 const auto cursor = prepared->cursor();
696 const auto anchor = prepared->anchor();
697 prepared->takeText(text->text);
698 auto committed = text->history->commit(std::move(*prepared));
699 if (!committed) {
700 return std::unexpected(TreeError::WOULD_BLOCK);
701 }
702 text->mask = std::move(mask);
703 text->cursor = cursor;
704 text->anchor = anchor;
705 text->dirty = true;
706 ++text->generation;
707 textCharge = *nextTextCharge;
708 draft = std::move(candidate);
709 status = EditStatus::DIRTY;
710 return {};
711 }
712
713 std::expected<EditReceipt, TreeError> commit() override;
714 std::expected<void, TreeError> cancel(bool discard) override;
715 std::expected<bool, TreeError> reply(const EditReceipt &receipt) override;
716
717 void rebase(std::uint64_t oldVersion, std::uint64_t newVersion) override {
718 if (discarded || !endpoint || !endpoint->capabilities().recordVersion || target.baseVersion != oldVersion ||
719 status == EditStatus::CONFLICT || !pending.empty() || newVersion < witnessedVersion) {
720 return;
721 }
722 target.baseVersion = newVersion;
723 observedVersion = std::max(observedVersion, newVersion);
724 witnessedVersion = std::max(witnessedVersion, newVersion);
725 if (text) {
726 text->revision = newVersion;
727 }
728 }
729};
730
731template <class Row> struct FixedEditContext {
732 NavigationPosition position;
733 std::shared_ptr<portals::detail::ManagedModelSource> source;
734 SourceStamp sourceSession;
735 std::shared_ptr<portals::detail::ManagedOrigin> origin;
736 std::function<std::expected<void, TreeError>()> admitDraft;
737};
738
739template <class Row>
740struct EditState final : portals::detail::EditNavigationParticipant, std::enable_shared_from_this<EditState<Row>> {
741 explicit EditState(Navigation<Row> value, EditOptions config) : navigation(std::move(value)), options(config) {
742 }
743
744 Navigation<Row> navigation;
745 // Only fixed-record delegates allocate this extension; ordinary sessions retain one optional pointer.
746 std::unique_ptr<FixedEditContext<Row>> fixed;
747 EditOptions options;
748 ManagedNavigation managed;
749 std::vector<std::shared_ptr<EditDefinitionBase>> definitions = std::vector<std::shared_ptr<EditDefinitionBase>>(0);
750 std::vector<std::shared_ptr<EditEntryBase>> entries = std::vector<std::shared_ptr<EditEntryBase>>(0);
751 std::vector<std::weak_ptr<portals::detail::EditTextBinding>> bindings =
752 std::vector<std::weak_ptr<portals::detail::EditTextBinding>>(0);
753 std::shared_ptr<EditCommitResult> last;
754 std::uint64_t sequence{};
755 SourceStamp writeSession;
756 std::uint64_t nextLocal{1};
757 std::uint64_t nextGeneration{1};
758 std::size_t bytes{};
759 const std::thread::id ownerThread{std::this_thread::get_id()};
760 bool preparingTargets{};
761 bool accounting{};
762 bool registered{};
763 bool endpointClosed{};
764
765 std::expected<void, TreeError> resolve(ManagedScene &scene, MountContext &context) {
766 if (fixed) {
767 return current().transform([](const auto &) {
768 });
769 }
770 auto nav = ModelAccess::resolve(scene, navigation, context);
771 if (!nav) {
772 return std::unexpected(EditAccess::cause(nav.error()));
773 }
774 auto previous = EditAccess::context(managed);
775 auto next = EditAccess::context(*nav);
776 if (!next) {
777 return std::unexpected(next.error());
778 }
779 if (!previous || previous->get() != next->get()) {
780 registered = false;
781 endpointClosed = false;
782 }
783 managed = *nav;
784 const auto existingEntries = entries.size();
785 const auto wasRegistered = registered;
786 auto admitted = registerParticipant();
787 if (!admitted) {
788 return admitted;
789 }
790 if (!wasRegistered) {
791 context.rollback.push_back([weak = std::weak_ptr(this->shared_from_this()), existingEntries] {
792 if (auto state = weak.lock()) {
793 state->registered = false;
794 while (state->entries.size() > existingEntries) {
795 auto retired = std::move(state->entries.back());
796 state->entries.pop_back();
797 state->bytes -= retired->charge;
798 }
799 }
800 });
801 }
802 return {};
803 }
804
805 std::expected<void, TreeError> registerParticipant() {
806 if (fixed) {
807 if (fixed->origin) {
808 auto live = fixed->origin->check();
809 if (!live) {
810 return std::unexpected(live.error());
811 }
812 }
813 if (!writeSession.instance) {
814 auto stamp = portals::detail::windowSourceStamp();
815 if (!stamp) {
816 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
817 }
818 writeSession = *stamp;
819 }
820 return {};
821 }
822 if (registered) {
823 return {};
824 }
825 auto nav = navigation.managed();
826 if (nav) {
827 managed = *nav;
828 }
829 auto record = EditAccess::context(managed);
830 if (!record) {
831 return std::unexpected(record.error());
832 }
833 if (!writeSession.instance) {
834 auto stamp = portals::detail::windowSourceStamp();
835 if (!stamp) {
836 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
837 }
838 writeSession = *stamp;
839 }
840 if ((*record)->admittingEdit) {
841 return std::unexpected(TreeError::WOULD_BLOCK);
842 }
843 if (!(*record)->editors) {
844 (*record)->editors = std::make_unique<std::vector<std::weak_ptr<portals::detail::EditNavigationParticipant>>>(0);
845 }
846 std::erase_if(*(*record)->editors, [](const auto &weak) {
847 return weak.expired();
848 });
849 (*record)->editors->push_back(this->shared_from_this());
850 registered = true;
851 return {};
852 }
853
854 std::expected<NavigationPosition, TreeError> current() {
855 if (ownerThread != std::this_thread::get_id()) {
856 return std::unexpected(TreeError::WRONG_THREAD);
857 }
858 if (endpointClosed) {
859 return std::unexpected(TreeError::CLOSED);
860 }
861 auto admitted = registerParticipant();
862 if (!admitted) {
863 return std::unexpected(admitted.error());
864 }
865 if (fixed) {
866 return fixed->position;
867 }
868 auto channel = managed.current();
869 if (!channel) {
870 return std::unexpected(channel.error());
871 }
872 auto snapshot = channel->snapshot();
873
874 if (!snapshot) {
875 return std::unexpected(snapshot.error());
876 }
877
878 auto position = (*snapshot)->value;
879
880 // NEAREST describes how navigation selected this already-resolved current row. A new editor
881 // addresses that concrete RowId exactly; it never resolves or rewrites an older retained target.
882 // Keep the navigation channel/bookmark diagnostic unchanged and retain exact entry/endpoint checks.
883 if (position.kind == PositionKind::ITEM && position.row && position.resolution == PositionResolution::NEAREST) {
884 position.resolution = PositionResolution::EXACT;
885 }
886
887 return position;
888 }
889
890 void prunePristine(const NavigationPosition &target, SourceStamp sourceIdentity) {
891 std::vector<std::shared_ptr<EditEntryBase>> retired(0);
892 retired.reserve(entries.size());
893 for (auto &entry : entries) {
894 if ((!entry->pristine() && !entry->discarded) ||
895 (entry->target.resource == target.resource && target.row == entry->target.row &&
896 entry->target.sourceSession == sourceIdentity && !entry->discarded)) {
897 continue;
898 }
899 const auto visible = std::ranges::any_of(bindings, [&](const auto &weak) {
900 auto binding = weak.lock();
901 return binding && (binding->displayedEntry == entry.get() || binding->preparedEntry == entry.get());
902 });
903 if (!visible) {
904 bytes -= entry->charge;
905 retired.push_back(std::move(entry));
906 }
907 }
908 std::erase(entries, std::shared_ptr<EditEntryBase>{});
909 }
910
911 std::expected<void, TreeError> checkCredit(const EditEntryBase &entry, std::size_t charge, bool retain = true) const {
912 if (retain && fixed && fixed->admitDraft) {
913 auto admitted = fixed->admitDraft();
914 if (!admitted) {
915 return admitted;
916 }
917 }
918 if (retain && entry.pristine()) {
919 const auto retained = std::ranges::count_if(entries, [](const auto &value) {
920 return !value->discarded && !value->pristine();
921 });
922 if (static_cast<std::size_t>(retained) >= options.maxRetainedFields) {
923 return std::unexpected(TreeError::NODE_LIMIT);
924 }
925 }
926 if (entry.charge > bytes || charge > options.maxRetainedBytes ||
927 bytes - entry.charge > options.maxRetainedBytes - charge) {
928 return std::unexpected(TreeError::NODE_LIMIT);
929 }
930 return {};
931 }
932
933 std::expected<void, TreeError> admit(EditEntryBase &entry, std::size_t charge, bool retain = true) {
934 auto checked = checkCredit(entry, charge, retain);
935 if (!checked) {
936 return checked;
937 }
938 bytes = bytes - entry.charge + charge;
939 entry.charge = charge;
940 return {};
941 }
942
943 template <class Value>
944 std::expected<std::shared_ptr<EditEntry<Row, Value>>, TreeError>
945 entry(const std::shared_ptr<EditDefinition<Row, Value>> &definition, const NavigationPosition &position,
946 const std::shared_ptr<portals::detail::ManagedModelSource> &nextSource = {}) {
947 definition->active = true;
948 if (!position.row || position.kind != PositionKind::ITEM || position.resolution != PositionResolution::EXACT) {
949 return std::unexpected(TreeError::WOULD_BLOCK);
950 }
951 auto actualSource = nextSource ? nextSource : fixed ? fixed->source : nullptr;
952 if (!actualSource && !fixed) {
953 auto record = EditAccess::context(managed);
954 if (!record) {
955 return std::unexpected(record.error());
956 }
957 actualSource = (*record)->model.lock();
958 }
959 auto incarnation = fixed ? std::expected<SourceStamp, TreeError>(fixed->sourceSession)
960 : EditAccess::sourceSession<Row>(actualSource);
961 if (!incarnation) {
962 return std::unexpected(incarnation.error());
963 }
964 for (const auto &base : entries) {
965 if (base->target.resource == position.resource && base->target.row == *position.row &&
966 base->target.field == definition->key && base->target.sourceSession == *incarnation && !base->discarded) {
967 auto value = std::dynamic_pointer_cast<EditEntry<Row, Value>>(base);
968 return value ? std::expected<std::shared_ptr<EditEntry<Row, Value>>, TreeError>(std::move(value))
969 : std::unexpected(TreeError::INVALID_ARGUMENT);
970 }
971 }
972 if (accounting) {
973 return std::unexpected(TreeError::WOULD_BLOCK);
974 }
975 if (preparingTargets && !nextSource) {
976 return std::unexpected(TreeError::WOULD_BLOCK);
977 }
978 if (!preparingTargets) {
979 prunePristine(position, *incarnation);
980 }
981 auto value = std::make_shared<EditEntry<Row, Value>>();
982 value->owner = this->shared_from_this();
983 value->definition = definition;
984 value->target = {position.resource, writeSession, *position.row, definition->key};
985 value->target.sourceSession = *incarnation;
986 if (definition->endpoint) {
987 value->endpoint = definition->endpoint;
988 } else {
989 auto model = EditAccess::model<Row>(actualSource);
990 if (EditAccess::sequence(model)) {
991 value->endpoint = std::make_shared<OwnedFieldEndpoint<Row, Value>>(
992 model, definition->member, value->target, options.maxRetainedBytes, definition->maxTextBytes);
993 } else {
994 value->endpoint = std::make_shared<ReadOnlyFieldEndpoint<Row, Value>>(
995 model, definition->member, position.resource, options.maxRetainedBytes, definition->maxTextBytes);
996 }
997 }
998 auto ready = value->refresh();
999 if (!ready) {
1000 return std::unexpected(ready.error());
1001 }
1002 auto size = value->endpoint->ownedBytes(*value->accepted);
1003 if (!size) {
1004 return std::unexpected(size.error());
1005 }
1006 if (options.maxRetainedBytes < sizeof(*value) || *size > options.maxRetainedBytes - sizeof(*value)) {
1007 return std::unexpected(TreeError::NODE_LIMIT);
1008 }
1009 entries.reserve(entries.size() + 1);
1010 auto initialCharge = value->retainedCharge(nullptr, 0);
1011 if (!initialCharge) {
1012 return std::unexpected(initialCharge.error());
1013 }
1014 auto credit = admit(*value, *initialCharge, false);
1015 if (!credit) {
1016 return std::unexpected(credit.error());
1017 }
1018 entries.push_back(value);
1019 return value;
1020 }
1021
1022 void accepted(const EditReceipt &receipt) {
1023 for (const auto &entry : entries) {
1024 if (entry->target.resource == receipt.target.resource && entry->target.session == receipt.target.session &&
1025 entry->target.row == receipt.target.row && entry->target.sourceSession == receipt.target.sourceSession) {
1026 entry->rebase(receipt.target.baseVersion, receipt.acceptedVersion);
1027 }
1028 }
1029 }
1030
1031 std::expected<void, TreeError>
1032 beforeTransition(const NavigationPosition *next,
1033 const std::shared_ptr<portals::detail::ManagedModelSource> &source) override {
1034 if (accounting) {
1035 return std::unexpected(TreeError::WOULD_BLOCK);
1036 }
1037 const auto retainedBindings = bindings;
1038 const auto retainedDefinitions = definitions;
1039 for (const auto &weak : retainedBindings) {
1040 auto binding = weak.lock();
1041 if (binding && !binding->closed && binding->preserveValidation) {
1042 auto preserved = binding->preserveValidation();
1043 if (!preserved) {
1044 return preserved;
1045 }
1046 }
1047 }
1048 if (next && next->row && next->resolution == PositionResolution::EXACT) {
1049 auto incarnation = EditAccess::sourceSession<Row>(source);
1050 if (!incarnation) {
1051 return std::unexpected(incarnation.error());
1052 }
1053 prunePristine(*next, *incarnation);
1054 const auto previousCount = entries.size();
1055
1056 struct Preparing {
1057 bool &active;
1058
1059 ~Preparing() {
1060 active = false;
1061 }
1062 } guard{preparingTargets};
1063
1064 preparingTargets = true;
1065 auto prepareTargets = [&]() -> std::expected<void, TreeError> {
1066 for (const auto &definition : retainedDefinitions) {
1067 auto admitted = definition->prepare(*next, source);
1068 if (!admitted) {
1069 return admitted;
1070 }
1071 }
1072 for (const auto &weak : retainedBindings) {
1073 auto binding = weak.lock();
1074 if (binding && !binding->closed && binding->preflight) {
1075 auto admitted = binding->preflight(*next, source);
1076 if (!admitted) {
1077 return admitted;
1078 }
1079 }
1080 }
1081 return {};
1082 };
1083 auto admitted = prepareTargets();
1084 if (!admitted) {
1085 while (entries.size() > previousCount) {
1086 auto retired = std::move(entries.back());
1087 entries.pop_back();
1088 bytes -= retired->charge;
1089 }
1090 return admitted;
1091 }
1092 }
1093 if (options.mode != EditMode::ON_COMPLETION) {
1094 return {};
1095 }
1096 for (const auto &weak : retainedBindings) {
1097 auto binding = weak.lock();
1098 if (!binding || binding->closed || !binding->displayedEntry || !binding->displayed->dirty ||
1099 !preferredEditBinding(retainedBindings, binding)) {
1100 continue;
1101 }
1102 auto result = binding->complete(false);
1103 if (!result) {
1104 return std::unexpected(result.error());
1105 }
1106 if (result->status != LineEditStatus::COMMITTED && result->status != LineEditStatus::EDITED) {
1107 return std::unexpected(TreeError::WOULD_BLOCK);
1108 }
1109 }
1110 auto position = current();
1111 if (!position) {
1112 return std::unexpected(position.error());
1113 }
1114 const auto retainedEntries = entries;
1115 for (const auto &entry : retainedEntries) {
1116 if (entry->target.resource != position->resource || position->row != entry->target.row || !entry->hasDraft()) {
1117 continue;
1118 }
1119 auto result = entry->commit();
1120 if (!result) {
1121 return std::unexpected(result.error());
1122 }
1123 if (result->status != EditStatus::CLEAN && result->status != EditStatus::ACCEPTED) {
1124 return std::unexpected(TreeError::WOULD_BLOCK);
1125 }
1126 }
1127 return {};
1128 }
1129
1130 void closed() noexcept override {
1131 endpointClosed = true;
1132 }
1133};
1134
1135template <class Row, class Value> std::expected<EditReceipt, TreeError> EditEntry<Row, Value>::commit() {
1136 admissionRefused = false;
1137 auto state = owner.lock();
1138 if (!state || state->endpointClosed) {
1139 return std::unexpected(TreeError::CLOSED);
1140 }
1141 if (state->accounting) {
1142 return std::unexpected(TreeError::WOULD_BLOCK);
1143 }
1144 if (discarded || !endpoint) {
1145 return EditReceipt{target, EditStatus::TARGET_MISSING};
1146 }
1147 const auto endpointOwner = endpoint;
1148 const auto capabilities = endpointOwner->capabilities();
1149 if (!capabilities.writable) {
1150 return EditReceipt{target, EditStatus::READ_ONLY};
1151 }
1152 if (text && text->dirty && !definition->textCodec) {
1153 if constexpr (std::same_as<Value, std::string>) {
1154 if (!draft || *draft != text->text.bytes()) {
1155 draft = std::make_shared<const Value>(text->text.bytes());
1156 }
1157 }
1158 } else if (text && text->dirty) {
1159 auto parsed = parse(text->text.bytes());
1160 if (!parsed) {
1161 if (parsed.error() != TreeError::INVALID_ARGUMENT) {
1162 return std::unexpected(parsed.error());
1163 }
1164 status = EditStatus::INVALID;
1165
1166 return EditReceipt{target, status};
1167 }
1168 auto candidate = std::make_shared<const Value>(*parsed);
1169 auto chargedBytes = retainedCharge(candidate.get(), textCharge);
1170 if (!chargedBytes) {
1171 return std::unexpected(chargedBytes.error());
1172 }
1173 auto admitted = state->admit(*this, *chargedBytes);
1174 if (!admitted) {
1175 return std::unexpected(admitted.error());
1176 }
1177 draft = std::move(candidate);
1178 }
1179 if (!draft) {
1180 return status == EditStatus::ACCEPTED ? lastReceipt : EditReceipt{target, status};
1181 }
1182 const auto candidate = draft;
1183 const auto previousGeneration = text ? text->generation : generation;
1184 const auto previousText = text.get();
1185 const auto previousTarget = target;
1186 const bool editorValidated = text && validatedGeneration == text->generation;
1187 const auto policy = selectEditPolicy(state->bindings, definition.get());
1188 if (policy) {
1189 requiresAsyncValidation = policy->asynchronous;
1190 }
1191 // An admitted async draft keeps its approval barrier after widget removal. A replacement
1192 // mounted editor may supply a new policy, but a cold recipe cannot authorize publication.
1193 if (requiresAsyncValidation && !editorValidated) {
1194 return EditReceipt{target, EditStatus::REJECTED, 0, TreeError::WOULD_BLOCK};
1195 }
1196 bool policyValidated{};
1197 if (policy && !editorValidated) {
1198 std::optional<std::string> formatted;
1199 std::string_view bytes;
1200 if (text) {
1201 // Semantic validators may reenter the typed setter and replace this retained draft.
1202 // Keep the entire candidate alive independently of the entry until validation returns.
1203 formatted.emplace(text->text.bytes());
1204 bytes = *formatted;
1205 } else if constexpr (std::same_as<Value, std::string>) {
1206 if (!definition->textCodec) {
1207 bytes = *candidate;
1208 } else {
1209 auto value = format(*candidate);
1210 if (!value) {
1211 return std::unexpected(value.error());
1212 }
1213 formatted.emplace(*value);
1214 bytes = *formatted;
1215 }
1216 } else {
1217 auto value = format(*candidate);
1218 if (!value) {
1219 return std::unexpected(value.error());
1220 }
1221 formatted.emplace(*value);
1222 bytes = *formatted;
1223 }
1224 for (const auto *validate : {&policy->validateBeforeParse, &policy->validateForCommit}) {
1225 if (!*validate) {
1226 continue;
1227 }
1228 auto checked = (*validate)(bytes);
1229 if (state->endpointClosed || discarded || endpoint != endpointOwner) {
1230 return std::unexpected(TreeError::CLOSED);
1231 }
1232 // Check supersession before interpreting a result or entering the next parsing phase.
1233 // A reentrant inner publication owns its status and must not be overwritten by this call.
1234 if (policy->closed || draft != candidate || text.get() != previousText || target != previousTarget ||
1235 previousGeneration != (text ? text->generation : generation)) {
1236 return EditReceipt{previousTarget, EditStatus::CONFLICT};
1237 }
1238 if (!checked) {
1239 return std::unexpected(checked.error());
1240 }
1241 if (!*checked) {
1242 status = EditStatus::INVALID;
1243 return EditReceipt{target, status};
1244 }
1245 }
1246 policyValidated = true;
1247 }
1248 const bool modelValidated = editorValidated || (policyValidated && policy->validatedByEditor);
1249 const auto rule = definition->validate;
1250 const bool modelValid = !rule || modelValidated || rule(*candidate);
1251 if (state->endpointClosed || discarded || endpoint != endpointOwner) {
1252 return std::unexpected(TreeError::CLOSED);
1253 }
1254 if (draft != candidate || text.get() != previousText || target != previousTarget ||
1255 previousGeneration != (text ? text->generation : generation)) {
1256 return EditReceipt{previousTarget, EditStatus::CONFLICT};
1257 }
1258 if (!modelValid) {
1259 status = EditStatus::INVALID;
1260 return EditReceipt{target, status};
1261 }
1262 if (!pending.empty() && (!capabilities.conditional || !capabilities.ordered)) {
1263 status = EditStatus::PENDING;
1264 return EditReceipt{pending.back().target, status};
1265 }
1266 if (state->sequence == std::numeric_limits<std::uint64_t>::max()) {
1267 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
1268 }
1269 auto staged = pending;
1270 staged.reserve(staged.size() + 1);
1271 auto pendingCharge = retainedCharge(draft.get(), textCharge, false, staged.capacity());
1272 if (!pendingCharge) {
1273 admissionRefused = pendingCharge.error() == TreeError::NODE_LIMIT;
1274 return std::unexpected(pendingCharge.error());
1275 }
1276 if (discarded || endpoint != endpointOwner || state->endpointClosed) {
1277 return std::unexpected(TreeError::CLOSED);
1278 }
1279 if (draft != candidate || previousGeneration != (text ? text->generation : generation)) {
1280 return EditReceipt{target, EditStatus::CONFLICT};
1281 }
1282 auto credited = state->admit(*this, *pendingCharge);
1283 if (!credited) {
1284 admissionRefused = credited.error() == TreeError::NODE_LIMIT;
1285 return std::unexpected(credited.error());
1286 }
1287 EditTarget request = target;
1288 request.sequence = ++state->sequence;
1289 staged.push_back(Pending{request, candidate, previousGeneration});
1290 pending.swap(staged);
1291 std::expected<EditReceipt, TreeError> receipt;
1292 try {
1293 receipt = endpointOwner->submit(EditRequest<Value>{request, candidate});
1294 } catch (const std::bad_alloc &) {
1295 receipt = std::unexpected(TreeError::NO_MEMORY);
1296 } catch (...) {
1297 receipt = std::unexpected(TreeError::CALLBACK_FAILED);
1298 }
1299 if (!receipt || !editReceiptMatches(request, *receipt)) {
1300 std::erase_if(pending, [&](const auto &value) {
1301 return value.target == request;
1302 });
1303 return std::unexpected(receipt ? TreeError::INVALID_ARGUMENT : receipt.error());
1304 }
1305 lastReceipt = *receipt;
1306 if (receipt->status == EditStatus::PENDING) {
1307 status = EditStatus::PENDING;
1308 lastReceipt = *receipt;
1309 return *receipt;
1310 }
1311 auto applied = reply(*receipt);
1312 return applied ? receipt : std::unexpected(applied.error());
1313}
1314
1315template <class Row, class Value>
1316std::expected<bool, TreeError> EditEntry<Row, Value>::reply(const EditReceipt &receipt) {
1317 const auto found = std::ranges::find_if(pending, [&](const Pending &value) {
1318 return editReceiptMatches(value.target, receipt);
1319 });
1320 if (found == pending.end() || receipt.status == EditStatus::PENDING) {
1321 return false;
1322 }
1323 if (receipt.status != EditStatus::ACCEPTED && receipt.status != EditStatus::INVALID &&
1324 receipt.status != EditStatus::CONFLICT && receipt.status != EditStatus::TARGET_MISSING &&
1325 receipt.status != EditStatus::READ_ONLY && receipt.status != EditStatus::CLOSED &&
1326 receipt.status != EditStatus::REJECTED) {
1327 return std::unexpected(TreeError::INVALID_ARGUMENT);
1328 }
1329 if (receipt.status == EditStatus::ACCEPTED &&
1330 (!receipt.acceptedVersion || receipt.acceptedVersion < receipt.target.baseVersion)) {
1331 return std::unexpected(TreeError::INVALID_ARGUMENT);
1332 }
1333 const auto operation = *found;
1334 pending.erase(found);
1335 if (receipt.target.sequence < acceptedSequence) {
1336 return false;
1337 }
1338 if (receipt.status == EditStatus::ACCEPTED && receipt.acceptedVersion < std::max(observedVersion, witnessedVersion)) {
1339 acceptedSequence = std::max(acceptedSequence, receipt.target.sequence);
1340 lastReceipt = receipt;
1341 status = hasDraft() ? EditStatus::CONFLICT : EditStatus::CLEAN;
1342 return false;
1343 }
1344 const auto currentGeneration = text ? text->generation : generation;
1345 auto publishNewer = [&] {
1346 auto state = owner.lock();
1347 if (!state || !hasDraft() || currentGeneration == operation.generation || !pending.empty() ||
1348 state->options.mode != EditMode::IMMEDIATE) {
1349 return;
1350 }
1351 try {
1352 auto next = commit();
1353 if (!next) {
1354 status = EditStatus::REJECTED;
1355 lastReceipt = {target, status, 0, next.error()};
1356 }
1357 } catch (const std::bad_alloc &) {
1358 status = EditStatus::REJECTED;
1359 lastReceipt = {target, status, 0, TreeError::NO_MEMORY};
1360 } catch (...) {
1361 status = EditStatus::REJECTED;
1362 lastReceipt = {target, status, 0, TreeError::CALLBACK_FAILED};
1363 }
1364 };
1365 status = receipt.status;
1366 lastReceipt = receipt;
1367 if (receipt.status != EditStatus::ACCEPTED) {
1368 if (currentGeneration != operation.generation && hasDraft() &&
1369 (receipt.status == EditStatus::REJECTED || receipt.status == EditStatus::INVALID)) {
1370 status = EditStatus::DIRTY;
1371 publishNewer();
1372 }
1373 return true;
1374 }
1375 acceptedSequence = receipt.target.sequence;
1376 observedVersion = receipt.acceptedVersion;
1377 witnessedVersion = std::max(witnessedVersion, receipt.acceptedVersion);
1378 const auto previousAccepted = std::exchange(accepted, operation.value);
1379 target.baseVersion = receipt.acceptedVersion;
1380 if (text && text->revision == receipt.target.baseVersion &&
1381 (currentGeneration == operation.generation || hasDraft())) {
1382 text->revision = receipt.acceptedVersion;
1383 }
1384 if (currentGeneration == operation.generation) {
1385 draft.reset();
1386 requiresAsyncValidation = false;
1387 if (text) {
1388 text->dirty = false;
1389 }
1390 } else {
1391 status = hasDraft() ? EditStatus::DIRTY : EditStatus::ACCEPTED;
1392 }
1393 if (auto state = owner.lock()) {
1394 if (endpoint->capabilities().recordVersion) {
1395 state->accepted(receipt);
1396 }
1397 }
1398 publishNewer();
1399 return true;
1400}
1401
1402template <class Row, class Value> std::expected<void, TreeError> EditEntry<Row, Value>::cancel(bool discard) {
1403 const auto state = owner.lock();
1404 if (!state) {
1405 return std::unexpected(TreeError::CLOSED);
1406 }
1407 if (state->accounting) {
1408 return std::unexpected(TreeError::WOULD_BLOCK);
1409 }
1410 if (discard && !pending.empty() && !state->endpointClosed) {
1411 return std::unexpected(TreeError::WOULD_BLOCK);
1412 }
1413
1414 // Retire owning values only after the whole target state and its charge agree.
1415 const auto previousDraft = draft;
1416 const auto previousAccepted = accepted;
1417 const auto previousEndpoint = endpoint;
1418 const auto previousValidation = validation;
1419 std::vector<Pending> retiredPending(0);
1420 if (!discard) {
1421 auto latest = refresh();
1422 if (!latest) {
1423 return latest;
1424 }
1425 }
1426 const auto expectedDraft = draft;
1427 const auto expectedAccepted = accepted;
1428 const auto beforeGeneration = text ? text->generation : generation;
1429 std::optional<PreparedTextHistory> prepared;
1430 std::unique_ptr<GraphemeText> mask;
1431 std::shared_ptr<const PropertyChange<std::string>> emptySnapshot;
1432 auto nextTextCharge = textCharge;
1433 if (text) {
1434 if (discard) {
1435 emptySnapshot = std::make_shared<const PropertyChange<std::string>>();
1436 }
1437 if (discard || text->dirty || text->history->operationCount() || text->text.bytes() != textSnapshot->value) {
1438 const auto bytes = discard ? std::string_view{} : std::string_view(textSnapshot->value);
1439 auto baseline = text->history->prepareResetBaseline({std::string(bytes), bytes.size(), bytes.size()});
1440 if (!baseline) {
1441 return std::unexpected(TreeError::NO_MEMORY);
1442 }
1443 prepared.emplace(std::move(*baseline));
1444 if (text->mask && !discard) {
1445 auto masked =
1446 GraphemeText::from(std::string(prepared->text()->graphemes().size(), '*'), text->text.policy(), text->limits);
1447 if (!masked) {
1448 return std::unexpected(TreeError::INVALID_ARGUMENT);
1449 }
1450 mask = std::make_unique<GraphemeText>(std::move(*masked));
1451 }
1452 auto measured =
1453 portals::detail::EditStorageAccess::draftBytes(*prepared->text(), mask.get(), prepared->retainedBytes());
1454 if (!measured) {
1455 return std::unexpected(measured.error());
1456 }
1457 nextTextCharge = *measured;
1458 }
1459 }
1460 auto finalCharge =
1461 discard ? std::expected<std::size_t, TreeError>(sizeof(*this)) : retainedCharge(nullptr, nextTextCharge);
1462 if (!finalCharge) {
1463 return std::unexpected(finalCharge.error());
1464 }
1465 if (draft != expectedDraft || accepted != expectedAccepted || endpoint != previousEndpoint ||
1466 beforeGeneration != (text ? text->generation : generation)) {
1467 return std::unexpected(TreeError::WOULD_BLOCK);
1468 }
1469 if (!discard && state->endpointClosed) {
1470 return std::unexpected(TreeError::CLOSED);
1471 }
1472 if (prepared) {
1473 auto ready = text->history->checkPrepared(*prepared);
1474 if (!ready) {
1475 return std::unexpected(TreeError::WOULD_BLOCK);
1476 }
1477 }
1478 auto admitted = state->admit(*this, *finalCharge, false);
1479 if (!admitted) {
1480 return admitted;
1481 }
1482 if (prepared) {
1483 const auto cursor = prepared->cursor();
1484 const auto anchor = prepared->anchor();
1485 prepared->takeText(text->text);
1486 auto committed = text->history->commit(std::move(*prepared));
1487 if (!committed) {
1488 return std::unexpected(TreeError::WOULD_BLOCK);
1489 }
1490 text->mask = std::move(mask);
1491 text->cursor = cursor;
1492 text->anchor = anchor;
1493 text->dirty = false;
1494 ++text->generation;
1495 }
1496 textCharge = nextTextCharge;
1497 draft.reset();
1498 requiresAsyncValidation = false;
1499 ++generation;
1500 if (discard) {
1501 pending.swap(retiredPending);
1502 accepted.reset();
1503 discarded = true;
1504 endpoint.reset();
1505 validation.reset();
1506 validationCharge = 0;
1507 textSnapshot = std::move(emptySnapshot);
1508 snapshotCharge = 0;
1509 } else {
1510 target.baseVersion = observedVersion;
1511 if (text) {
1512 text->revision = observedVersion;
1513 }
1514 }
1515 status = pending.empty() ? EditStatus::CLEAN : EditStatus::PENDING;
1516 return {};
1517}
1518
1520} // namespace portals::ui::detail
consteval auto id(StyleState state=StyleState::ANY, bool readOnly=false)
Definition style_static.hpp:865
consteval auto rule(S target, D... declarations)
Definition style_static.hpp:1366
auto live(ManagedScene &scene, const S &description)
Definition style_static.hpp:1703
ui::ValueText text(std::format_string< const ui::detail::TextArgumentValue< Args > &... > pattern, Args &&...args)
Declare live formatted text over explicit scalar roots, fields or value properties.
Definition ui_value_text.hpp:567
@ INVALID_ARGUMENT
Empty task, callback or immutable data owner, or invalid policy.
Definition async.hpp:26
bool editReceiptMatches(const EditTarget &target, const EditReceipt &receipt) noexcept
Exact qualification; this does not prove a backend applied its precondition.
EditStatus
Submission and acceptance are separate protocol states.
Definition model_edit.hpp:56
Version version() noexcept
Return the version of the linked library by value.
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
std::variant< TreeError, StyleError, ApplicationError > cause
Unformatted original error; StyleError messages follow their static-storage contract.
Definition managed_diagnostics.hpp:66