5#include <portals/detail/model_edit.hpp>
6#include <portals/ui_model.hpp>
8namespace portals::ui::detail {
12 static EditorCommandResult command(ManagedNavigation, std::expected<void, TreeError>, std::source_location);
14 static TreeError cause(
const ManagedError &error) {
15 const auto *tree = std::get_if<TreeError>(&error.
cause);
16 return tree ? *tree : TreeError::CALLBACK_FAILED;
19 template <
class Row>
static Model<Row> model(
const Navigation<Row> &navigation) {
20 return navigation.data_ ? navigation.data_->initial : Model<Row>{};
23 template <
class Row>
static Model<Row> model(
const std::shared_ptr<portals::detail::ManagedModelSource> &source) {
25 if (!std::dynamic_pointer_cast<portals::detail::ManagedModelSourceOf<Row>>(source)) {
28 if (
auto declaration = source->editDeclaration) {
29 result.data_ = std::static_pointer_cast<ModelDeclarationBase>(declaration);
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);
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());
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);
50 return SourceStamp{typed->model->state_->session, 1};
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
59 template <
class Row>
static NodeId scene(
const Model<Row> &model) {
60 return model.data_ ? model.data_->scene : NodeId{};
63 static std::expected<std::shared_ptr<portals::detail::ManagedNavigationRecord>,
TreeError>
64 context(
const ManagedNavigation &navigation) {
65 return navigation.lock();
69 static std::expected<std::uint64_t, TreeError> replace(
const Model<Row> &model, RowId
id, std::uint64_t version,
71 std::uint64_t acceptedVersion{};
72 const typename Model<Row>::Replacement replacement{
id, value,
version, &acceptedVersion};
73 auto result = model.mutate(
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);
81 return result ? std::expected<std::uint64_t, TreeError>(acceptedVersion) : std::unexpected(cause(result.error()));
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>) {
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);
101 if constexpr (std::same_as<Value, std::string>) {
102 return std::expected<Value, TreeError>(std::in_place, candidate);
108template <
class Row,
class Value>
class OwnedFieldEndpoint final :
public EditEndpoint<Value> {
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) {
116 EditCapabilities capabilities() const noexcept
override {
117 return {
static_cast<bool>(EditAccess::sequence(model_)),
true,
false,
false,
true};
120 std::expected<EditRecord<Value>,
TreeError> read(ModelResource resource, RowId row)
override {
121 auto managed = EditAccess::provisional(model_);
123 return std::unexpected(managed.error());
125 if (resource != resource_ || row != identity_.row || !member_) {
126 return std::unexpected(TreeError::INVALID_ARGUMENT);
128 auto sequence = EditAccess::sequence(model_);
129 if (!sequence || !sequence->current) {
130 return std::unexpected(TreeError::INVALID_ARGUMENT);
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);
137 if (sequence->editing) {
138 return std::unexpected(TreeError::WOULD_BLOCK);
140 if (!sequence->editVersions) {
141 sequence->editVersions = std::make_shared<std::vector<std::weak_ptr<OwnedEditVersion>>>(0);
143 std::erase_if(*sequence->editVersions, [](
const auto &weak) {
144 return weak.expired();
148 for (
const auto &weak : *sequence->editVersions) {
149 auto entry = weak.lock();
150 if (entry && entry->row == row) {
157 version = std::make_shared<OwnedEditVersion>(OwnedEditVersion{row, previous->revision()});
158 sequence->editVersions->push_back(version);
161 if (cachedRow_ == row && cachedVersion_ ==
version->version) {
162 if (
auto cached = cachedValue_.lock()) {
163 return EditRecord<Value>{std::move(cached), cachedVersion_};
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);
171 auto size = editValueBytes(previous->rows()[location.index].value.*member_);
173 return std::unexpected(size.error());
175 if (*size > maxBytes_) {
176 return std::unexpected(TreeError::NODE_LIMIT);
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);
183 auto live = EditAccess::provisional(model_);
185 return std::unexpected(
live.error());
187 cachedValue_ = value;
188 cachedVersion_ = expectedVersion;
190 return EditRecord<Value>{std::move(value), expectedVersion};
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);
199 auto current = read(resource_, request.target.row);
201 return EditReceipt{request.target,
202 current.error() == TreeError::STALE_NODE ? EditStatus::TARGET_MISSING : EditStatus::CLOSED, 0,
205 if (current->version != request.target.baseVersion) {
206 return EditReceipt{request.target, EditStatus::CONFLICT};
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);
215 return EditReceipt{request.target,
216 applied.error() == TreeError::WOULD_BLOCK ? EditStatus::CONFLICT : EditStatus::REJECTED, 0,
219 return EditReceipt{request.target, EditStatus::ACCEPTED, *applied};
222 std::expected<std::size_t, TreeError> ownedBytes(
const Value &value)
const override {
223 return editValueBytes(value);
229 ModelResource resource_;
230 EditTarget identity_;
231 std::size_t maxBytes_;
232 std::optional<std::size_t> maxTextBytes_;
233 std::shared_ptr<OwnedEditVersion> version_;
235 std::weak_ptr<const Value> cachedValue_;
236 std::uint64_t cachedVersion_{};
239template <
class Row,
class Value>
class ReadOnlyFieldEndpoint final :
public EditEndpoint<Value> {
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) {
247 EditCapabilities capabilities() const noexcept
override {
251 std::expected<EditRecord<Value>,
TreeError> read(ModelResource resource, RowId row)
override {
252 if (resource != resource_) {
253 return std::unexpected(TreeError::INVALID_ARGUMENT);
255 auto handle = EditAccess::provisional(model_);
257 return std::unexpected(handle.error());
259 auto snapshot = portals::detail::ManagedModelAccess::snapshot(*handle, EditAccess::scene(model_));
261 return std::unexpected(snapshot.error());
263 const auto found = (*snapshot)->locateRow(row);
264 if (found.state != RowLookupState::FOUND) {
265 return std::unexpected(TreeError::WOULD_BLOCK);
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);
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);
277 auto size = editValueBytes(value);
278 if (!size || *size > maxBytes_) {
279 return std::unexpected(size ? TreeError::NODE_LIMIT : size.error());
282 return EditRecord<Value>{std::make_shared<const Value>(value), (*snapshot)->revision()};
285 std::expected<EditReceipt, TreeError> submit(EditRequest<Value> request)
override {
286 return EditReceipt{request.target, EditStatus::READ_ONLY};
289 std::expected<std::size_t, TreeError> ownedBytes(
const Value &value)
const override {
290 return editValueBytes(value);
296 ModelResource resource_;
297 std::size_t maxBytes_;
298 std::optional<std::size_t> maxTextBytes_;
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) {
309 if (!chosen || (binding->validatedByEditor && !chosen->validatedByEditor)) {
310 chosen = std::move(binding);
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;
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) {
332 if (!chosen || (binding->validatedByEditor && !chosen->validatedByEditor)) {
333 chosen = std::move(binding);
340template <
class Row>
struct EditState;
342struct EditDefinitionBase {
343 virtual ~EditDefinitionBase() =
default;
345 std::function<std::expected<void, TreeError>(
const NavigationPosition &,
346 const std::shared_ptr<portals::detail::ManagedModelSource> &)>
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;
359struct EditEntryBase {
360 virtual ~EditEntryBase() =
default;
363 EditReceipt lastReceipt;
364 std::shared_ptr<const FieldValidation> validation;
365 std::size_t validationCharge{};
366 std::size_t charge{};
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;
379template <class Row, class Value> struct EditEntry final : EditEntryBase {
382 std::shared_ptr<const Value> value;
383 std::uint64_t generation;
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{};
399 std::uint64_t witnessedVersion{};
400 std::uint64_t validatedGeneration{std::numeric_limits<std::uint64_t>::max()};
401 bool requiresAsyncValidation{};
403 std::expected<std::string, TreeError> format(
const Value &value)
const {
404 if (definition->textCodec && definition->textCodec->format) {
405 return definition->textCodec->format(value);
407 if constexpr (std::same_as<Value, std::string>) {
408 return std::expected<std::string, TreeError>(std::in_place, value);
410 return std::unexpected(TreeError::INVALID_ARGUMENT);
414 std::expected<Value, TreeError> parse(std::string_view value)
const {
415 return parseEditText(definition->textCodec, value);
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();
425 return std::unexpected(TreeError::CLOSED);
427 const auto endpointOwner = endpoint;
428 if (discarded || !endpointOwner) {
429 return std::unexpected(TreeError::STALE_NODE);
431 if (state->accounting) {
432 return std::unexpected(TreeError::WOULD_BLOCK);
438 explicit Accounting(
bool &value) : active(value) {
445 } accounting(state->accounting);
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);
456 if (target != originalTarget || accepted != acceptedOwner || draft != draftOwner ||
457 (text ?
text->generation : generation) != originalGeneration || pending.size() != originalPendingCount) {
458 return std::unexpected(TreeError::WOULD_BLOCK);
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) {
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);
476 auto addValue = [&](
const Value *value) -> std::expected<void, TreeError> {
480 auto size = endpointOwner->ownedBytes(*value);
481 auto live = unchanged();
486 return std::unexpected(size.error());
488 return add(*size) ? std::expected<void, TreeError>{} : std::unexpected(TreeError::NODE_LIMIT);
490 const auto *acceptedValue = nextAccepted ? nextAccepted : acceptedOwner.get();
491 auto base = addValue(acceptedValue);
493 return std::unexpected(base.error());
495 if (candidate && (copiesCandidate || candidate != acceptedValue)) {
496 auto added = addValue(candidate);
498 return std::unexpected(added.error());
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)) {
507 bool counted =
false;
508 for (std::size_t previous = 0; previous < index; ++previous) {
509 counted = counted || pending[previous].value.get() == value;
512 auto added = addValue(value);
514 return std::unexpected(added.error());
521 std::expected<void, TreeError> refresh() {
522 admissionRefused =
false;
523 if (discarded || !endpoint) {
524 return std::unexpected(TreeError::STALE_NODE);
526 if (cancelReadPinned) {
529 const auto state = owner.lock();
531 return std::unexpected(TreeError::CLOSED);
533 if (state->accounting) {
534 return std::unexpected(TreeError::WOULD_BLOCK);
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);
543 if (value.error() == TreeError::STALE_NODE) {
544 status = EditStatus::TARGET_MISSING;
546 return std::unexpected(value.error());
548 if (!value->value || !value->version) {
549 return std::unexpected(TreeError::INVALID_ARGUMENT);
551 if (value->version < std::max(observedVersion, witnessedVersion)) {
552 return std::unexpected(TreeError::WOULD_BLOCK);
555 witnessedVersion = value->version;
556 auto localFailure = [&](
TreeError error) -> std::expected<void, TreeError> {
557 admissionRefused = error == TreeError::NODE_LIMIT;
558 return std::unexpected(error);
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);
568 nextSnapshotBytes =
sizeof(PropertyChange<std::string>) + value->value->capacity() + 1;
574 retainedCharge(retainedDraft.get(), textCharge,
false, {}, value->value.get(), nextSnapshotBytes);
576 return localFailure(estimated.error());
578 auto checked = state->checkCredit(*
this, *estimated,
false);
580 return localFailure(checked.error());
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;
590 if (definition->textCodec && (!nextSnapshot || nextSnapshot->revision != value->version)) {
591 auto formatted = format(*value->value);
593 return localFailure(formatted.error());
596 std::make_shared<const PropertyChange<std::string>>(PropertyChange<std::string>{*formatted, value->version});
597 nextSnapshotBytes =
sizeof(PropertyChange<std::string>) + nextSnapshot->value.capacity() + 1;
601 retainedCharge(retainedDraft.get(), textCharge,
false, {}, value->value.get(), nextSnapshotBytes);
603 return localFailure(nextCharge.error());
605 if (discarded || endpoint != endpointOwner || state->endpointClosed) {
606 return std::unexpected(TreeError::CLOSED);
608 if (value->version < witnessedVersion) {
609 return std::unexpected(TreeError::WOULD_BLOCK);
611 auto admitted = state->admit(*
this, *nextCharge,
false);
613 return localFailure(admitted.error());
616 const auto previousAccepted = std::exchange(accepted, value->value);
617 if (!draft && (!text || !
text->dirty) && pending.empty()) {
618 target.baseVersion = value->version;
620 observedVersion = value->version;
621 textSnapshot = std::move(nextSnapshot);
622 snapshotCharge = nextSnapshotBytes;
626 std::expected<void, TreeError> prepareCancel()
override {
627 if (cancelReadPinned) {
628 return std::unexpected(TreeError::WOULD_BLOCK);
633 bool hasDraft() const noexcept
override {
634 return draft || (
text &&
text->dirty);
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);
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);
647 if (
text->generation == std::numeric_limits<std::uint64_t>::max()) {
648 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
650 auto precharge = retainedCharge(&typedValue, textCharge,
true);
652 return std::unexpected(precharge.error());
654 auto checked = state->checkCredit(*
this, *precharge);
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);
662 return std::unexpected(prepared.error() == TextHistoryError::NO_MEMORY ? TreeError::NO_MEMORY
663 : TreeError::INVALID_ARGUMENT);
665 std::unique_ptr<GraphemeText> mask;
668 GraphemeText::from(std::string(prepared->text()->graphemes().size(),
'*'),
text->text.policy(),
text->limits);
670 return std::unexpected(TreeError::INVALID_ARGUMENT);
672 mask = std::make_unique<GraphemeText>(std::move(*masked));
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());
680 auto finalCharge = retainedCharge(candidate.get(), *nextTextCharge);
682 return std::unexpected(finalCharge.error());
684 auto ready =
text->history->checkPrepared(*prepared);
685 if (!ready || beforeGeneration !=
text->generation) {
686 return std::unexpected(TreeError::WOULD_BLOCK);
688 if (discarded || state->endpointClosed) {
689 return std::unexpected(TreeError::CLOSED);
691 auto admitted = state->admit(*
this, *finalCharge);
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));
700 return std::unexpected(TreeError::WOULD_BLOCK);
702 text->mask = std::move(mask);
703 text->cursor = cursor;
704 text->anchor = anchor;
707 textCharge = *nextTextCharge;
708 draft = std::move(candidate);
709 status = EditStatus::DIRTY;
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;
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) {
722 target.baseVersion = newVersion;
723 observedVersion = std::max(observedVersion, newVersion);
724 witnessedVersion = std::max(witnessedVersion, newVersion);
726 text->revision = newVersion;
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;
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) {
744 Navigation<Row> navigation;
746 std::unique_ptr<FixedEditContext<Row>> fixed;
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};
759 const std::thread::id ownerThread{std::this_thread::get_id()};
760 bool preparingTargets{};
763 bool endpointClosed{};
765 std::expected<void, TreeError> resolve(ManagedScene &scene, MountContext &context) {
767 return current().transform([](
const auto &) {
770 auto nav = ModelAccess::resolve(scene, navigation, context);
772 return std::unexpected(EditAccess::cause(nav.error()));
774 auto previous = EditAccess::context(managed);
775 auto next = EditAccess::context(*nav);
777 return std::unexpected(next.error());
779 if (!previous || previous->get() != next->get()) {
781 endpointClosed =
false;
784 const auto existingEntries = entries.size();
785 const auto wasRegistered = registered;
786 auto admitted = registerParticipant();
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;
805 std::expected<void, TreeError> registerParticipant() {
808 auto live = fixed->origin->check();
810 return std::unexpected(
live.error());
813 if (!writeSession.instance) {
814 auto stamp = portals::detail::windowSourceStamp();
816 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
818 writeSession = *stamp;
825 auto nav = navigation.managed();
829 auto record = EditAccess::context(managed);
831 return std::unexpected(record.error());
833 if (!writeSession.instance) {
834 auto stamp = portals::detail::windowSourceStamp();
836 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
838 writeSession = *stamp;
840 if ((*record)->admittingEdit) {
841 return std::unexpected(TreeError::WOULD_BLOCK);
843 if (!(*record)->editors) {
844 (*record)->editors = std::make_unique<std::vector<std::weak_ptr<portals::detail::EditNavigationParticipant>>>(0);
846 std::erase_if(*(*record)->editors, [](
const auto &weak) {
847 return weak.expired();
849 (*record)->editors->push_back(this->shared_from_this());
854 std::expected<NavigationPosition, TreeError> current() {
855 if (ownerThread != std::this_thread::get_id()) {
856 return std::unexpected(TreeError::WRONG_THREAD);
858 if (endpointClosed) {
859 return std::unexpected(TreeError::CLOSED);
861 auto admitted = registerParticipant();
863 return std::unexpected(admitted.error());
866 return fixed->position;
868 auto channel = managed.current();
870 return std::unexpected(channel.error());
872 auto snapshot = channel->snapshot();
875 return std::unexpected(snapshot.error());
878 auto position = (*snapshot)->value;
883 if (position.kind == PositionKind::ITEM && position.row && position.resolution == PositionResolution::NEAREST) {
884 position.resolution = PositionResolution::EXACT;
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)) {
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());
904 bytes -= entry->charge;
905 retired.push_back(std::move(entry));
908 std::erase(entries, std::shared_ptr<EditEntryBase>{});
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();
918 if (retain && entry.pristine()) {
919 const auto retained = std::ranges::count_if(entries, [](
const auto &value) {
920 return !value->discarded && !value->pristine();
922 if (
static_cast<std::size_t
>(retained) >= options.maxRetainedFields) {
923 return std::unexpected(TreeError::NODE_LIMIT);
926 if (entry.charge > bytes || charge > options.maxRetainedBytes ||
927 bytes - entry.charge > options.maxRetainedBytes - charge) {
928 return std::unexpected(TreeError::NODE_LIMIT);
933 std::expected<void, TreeError> admit(EditEntryBase &entry, std::size_t charge,
bool retain =
true) {
934 auto checked = checkCredit(entry, charge, retain);
938 bytes = bytes - entry.charge + charge;
939 entry.charge = charge;
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);
951 auto actualSource = nextSource ? nextSource : fixed ? fixed->source :
nullptr;
952 if (!actualSource && !fixed) {
953 auto record = EditAccess::context(managed);
955 return std::unexpected(record.error());
957 actualSource = (*record)->model.lock();
959 auto incarnation = fixed ? std::expected<SourceStamp, TreeError>(fixed->sourceSession)
960 : EditAccess::sourceSession<Row>(actualSource);
962 return std::unexpected(incarnation.error());
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))
973 return std::unexpected(TreeError::WOULD_BLOCK);
975 if (preparingTargets && !nextSource) {
976 return std::unexpected(TreeError::WOULD_BLOCK);
978 if (!preparingTargets) {
979 prunePristine(position, *incarnation);
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;
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);
994 value->endpoint = std::make_shared<ReadOnlyFieldEndpoint<Row, Value>>(
995 model, definition->member, position.resource, options.maxRetainedBytes, definition->maxTextBytes);
998 auto ready = value->refresh();
1000 return std::unexpected(ready.error());
1002 auto size = value->endpoint->ownedBytes(*value->accepted);
1004 return std::unexpected(size.error());
1006 if (options.maxRetainedBytes <
sizeof(*value) || *size > options.maxRetainedBytes -
sizeof(*value)) {
1007 return std::unexpected(TreeError::NODE_LIMIT);
1009 entries.reserve(entries.size() + 1);
1010 auto initialCharge = value->retainedCharge(
nullptr, 0);
1011 if (!initialCharge) {
1012 return std::unexpected(initialCharge.error());
1014 auto credit = admit(*value, *initialCharge,
false);
1016 return std::unexpected(credit.error());
1018 entries.push_back(value);
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);
1031 std::expected<void, TreeError>
1032 beforeTransition(
const NavigationPosition *next,
1033 const std::shared_ptr<portals::detail::ManagedModelSource> &source)
override {
1035 return std::unexpected(TreeError::WOULD_BLOCK);
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();
1048 if (next && next->row && next->resolution == PositionResolution::EXACT) {
1049 auto incarnation = EditAccess::sourceSession<Row>(source);
1051 return std::unexpected(incarnation.error());
1053 prunePristine(*next, *incarnation);
1054 const auto previousCount = entries.size();
1062 } guard{preparingTargets};
1064 preparingTargets =
true;
1065 auto prepareTargets = [&]() -> std::expected<void, TreeError> {
1066 for (
const auto &definition : retainedDefinitions) {
1067 auto admitted = definition->prepare(*next, source);
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);
1083 auto admitted = prepareTargets();
1085 while (entries.size() > previousCount) {
1086 auto retired = std::move(entries.back());
1088 bytes -= retired->charge;
1093 if (options.mode != EditMode::ON_COMPLETION) {
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)) {
1102 auto result = binding->complete(
false);
1104 return std::unexpected(result.error());
1106 if (result->status != LineEditStatus::COMMITTED && result->status != LineEditStatus::EDITED) {
1107 return std::unexpected(TreeError::WOULD_BLOCK);
1110 auto position = current();
1112 return std::unexpected(position.error());
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()) {
1119 auto result = entry->commit();
1121 return std::unexpected(result.error());
1123 if (result->status != EditStatus::CLEAN && result->status != EditStatus::ACCEPTED) {
1124 return std::unexpected(TreeError::WOULD_BLOCK);
1130 void closed() noexcept
override {
1131 endpointClosed =
true;
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);
1141 if (state->accounting) {
1142 return std::unexpected(TreeError::WOULD_BLOCK);
1144 if (discarded || !endpoint) {
1145 return EditReceipt{target, EditStatus::TARGET_MISSING};
1147 const auto endpointOwner = endpoint;
1148 const auto capabilities = endpointOwner->capabilities();
1149 if (!capabilities.writable) {
1150 return EditReceipt{target, EditStatus::READ_ONLY};
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());
1158 }
else if (text &&
text->dirty) {
1159 auto parsed = parse(
text->text.bytes());
1161 if (parsed.error() != TreeError::INVALID_ARGUMENT) {
1162 return std::unexpected(parsed.error());
1164 status = EditStatus::INVALID;
1166 return EditReceipt{target, status};
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());
1173 auto admitted = state->admit(*
this, *chargedBytes);
1175 return std::unexpected(admitted.error());
1177 draft = std::move(candidate);
1180 return status == EditStatus::ACCEPTED ? lastReceipt : EditReceipt{target, status};
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());
1189 requiresAsyncValidation = policy->asynchronous;
1193 if (requiresAsyncValidation && !editorValidated) {
1194 return EditReceipt{target, EditStatus::REJECTED, 0, TreeError::WOULD_BLOCK};
1196 bool policyValidated{};
1197 if (policy && !editorValidated) {
1198 std::optional<std::string> formatted;
1199 std::string_view bytes;
1203 formatted.emplace(
text->text.bytes());
1205 }
else if constexpr (std::same_as<Value, std::string>) {
1206 if (!definition->textCodec) {
1209 auto value = format(*candidate);
1211 return std::unexpected(value.error());
1213 formatted.emplace(*value);
1217 auto value = format(*candidate);
1219 return std::unexpected(value.error());
1221 formatted.emplace(*value);
1224 for (
const auto *validate : {&policy->validateBeforeParse, &policy->validateForCommit}) {
1228 auto checked = (*validate)(bytes);
1229 if (state->endpointClosed || discarded || endpoint != endpointOwner) {
1230 return std::unexpected(TreeError::CLOSED);
1234 if (policy->closed || draft != candidate ||
text.get() != previousText || target != previousTarget ||
1235 previousGeneration != (text ?
text->generation : generation)) {
1236 return EditReceipt{previousTarget, EditStatus::CONFLICT};
1239 return std::unexpected(checked.error());
1242 status = EditStatus::INVALID;
1243 return EditReceipt{target, status};
1246 policyValidated =
true;
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);
1254 if (draft != candidate ||
text.get() != previousText || target != previousTarget ||
1255 previousGeneration != (text ?
text->generation : generation)) {
1256 return EditReceipt{previousTarget, EditStatus::CONFLICT};
1259 status = EditStatus::INVALID;
1260 return EditReceipt{target, status};
1262 if (!pending.empty() && (!capabilities.conditional || !capabilities.ordered)) {
1263 status = EditStatus::PENDING;
1264 return EditReceipt{pending.back().target, status};
1266 if (state->sequence == std::numeric_limits<std::uint64_t>::max()) {
1267 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
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());
1276 if (discarded || endpoint != endpointOwner || state->endpointClosed) {
1277 return std::unexpected(TreeError::CLOSED);
1279 if (draft != candidate || previousGeneration != (text ?
text->generation : generation)) {
1280 return EditReceipt{target, EditStatus::CONFLICT};
1282 auto credited = state->admit(*
this, *pendingCharge);
1284 admissionRefused = credited.error() == TreeError::NODE_LIMIT;
1285 return std::unexpected(credited.error());
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;
1293 receipt = endpointOwner->submit(EditRequest<Value>{request, candidate});
1294 }
catch (
const std::bad_alloc &) {
1295 receipt = std::unexpected(TreeError::NO_MEMORY);
1297 receipt = std::unexpected(TreeError::CALLBACK_FAILED);
1300 std::erase_if(pending, [&](
const auto &value) {
1301 return value.target == request;
1303 return std::unexpected(receipt ? TreeError::INVALID_ARGUMENT : receipt.error());
1305 lastReceipt = *receipt;
1306 if (receipt->status == EditStatus::PENDING) {
1307 status = EditStatus::PENDING;
1308 lastReceipt = *receipt;
1311 auto applied = reply(*receipt);
1312 return applied ? receipt : std::unexpected(applied.error());
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) {
1320 if (found == pending.end() || receipt.status == EditStatus::PENDING) {
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);
1329 if (receipt.status == EditStatus::ACCEPTED &&
1330 (!receipt.acceptedVersion || receipt.acceptedVersion < receipt.target.baseVersion)) {
1331 return std::unexpected(TreeError::INVALID_ARGUMENT);
1333 const auto operation = *found;
1334 pending.erase(found);
1335 if (receipt.target.sequence < acceptedSequence) {
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;
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) {
1352 auto next = commit();
1354 status = EditStatus::REJECTED;
1355 lastReceipt = {target, status, 0, next.error()};
1357 }
catch (
const std::bad_alloc &) {
1358 status = EditStatus::REJECTED;
1359 lastReceipt = {target, status, 0, TreeError::NO_MEMORY};
1361 status = EditStatus::REJECTED;
1362 lastReceipt = {target, status, 0, TreeError::CALLBACK_FAILED};
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;
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;
1384 if (currentGeneration == operation.generation) {
1386 requiresAsyncValidation =
false;
1388 text->dirty =
false;
1391 status = hasDraft() ? EditStatus::DIRTY : EditStatus::ACCEPTED;
1393 if (
auto state = owner.lock()) {
1394 if (endpoint->capabilities().recordVersion) {
1395 state->accepted(receipt);
1402template <
class Row,
class Value> std::expected<void, TreeError> EditEntry<Row, Value>::cancel(
bool discard) {
1403 const auto state = owner.lock();
1405 return std::unexpected(TreeError::CLOSED);
1407 if (state->accounting) {
1408 return std::unexpected(TreeError::WOULD_BLOCK);
1410 if (discard && !pending.empty() && !state->endpointClosed) {
1411 return std::unexpected(TreeError::WOULD_BLOCK);
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);
1421 auto latest = refresh();
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;
1435 emptySnapshot = std::make_shared<const PropertyChange<std::string>>();
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()});
1441 return std::unexpected(TreeError::NO_MEMORY);
1443 prepared.emplace(std::move(*baseline));
1444 if (
text->mask && !discard) {
1446 GraphemeText::from(std::string(prepared->text()->graphemes().size(),
'*'),
text->text.policy(),
text->limits);
1448 return std::unexpected(TreeError::INVALID_ARGUMENT);
1450 mask = std::make_unique<GraphemeText>(std::move(*masked));
1453 portals::detail::EditStorageAccess::draftBytes(*prepared->text(), mask.get(), prepared->retainedBytes());
1455 return std::unexpected(measured.error());
1457 nextTextCharge = *measured;
1461 discard ? std::expected<std::size_t, TreeError>(
sizeof(*
this)) : retainedCharge(nullptr, nextTextCharge);
1463 return std::unexpected(finalCharge.error());
1465 if (draft != expectedDraft || accepted != expectedAccepted || endpoint != previousEndpoint ||
1466 beforeGeneration != (text ?
text->generation : generation)) {
1467 return std::unexpected(TreeError::WOULD_BLOCK);
1469 if (!discard && state->endpointClosed) {
1470 return std::unexpected(TreeError::CLOSED);
1473 auto ready =
text->history->checkPrepared(*prepared);
1475 return std::unexpected(TreeError::WOULD_BLOCK);
1478 auto admitted = state->admit(*
this, *finalCharge,
false);
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));
1488 return std::unexpected(TreeError::WOULD_BLOCK);
1490 text->mask = std::move(mask);
1491 text->cursor = cursor;
1492 text->anchor = anchor;
1493 text->dirty =
false;
1496 textCharge = nextTextCharge;
1498 requiresAsyncValidation =
false;
1501 pending.swap(retiredPending);
1506 validationCharge = 0;
1507 textSnapshot = std::move(emptySnapshot);
1510 target.baseVersion = observedVersion;
1512 text->revision = observedVersion;
1515 status = pending.empty() ? EditStatus::CLEAN : EditStatus::PENDING;
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