载入中...
搜索中...
未找到
EditorHostProfile.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <atomic>
4#include <chrono>
5#include <cstdint>
6#include <span>
7#include <utility>
8#include "common/Exception.h"
13
14// EditorHostProfile.cpp
15namespace eve::editor {
16
18 HostProfile profile(HostKind::Developer);
22 profile.allowAllCommands_ = true;
23 profile.maxPayloadBytes_ = 4 * 1024 * 1024;
24 return profile;
25}
26
28 HostProfile profile(HostKind::RuntimeBuilder);
30 return profile;
31}
32
34 HostProfile profile(HostKind::Automation);
36 profile.maxPayloadBytes_ = 1024 * 1024;
37 return profile;
38}
39
40bool HostProfile::hasFeatures(HostFeature required) const { return (features_ & required) == required; }
41
43 if (!id) return;
44 deniedCommands_.erase(id);
45 allowedCommands_.insert(std::move(id));
46}
47
48void HostProfile::allowCommands(std::initializer_list<CommandId> ids) {
49 for (const auto &id : ids) allowCommand(id);
50}
51
53 if (!id) return;
54 allowedCommands_.erase(id);
55 deniedCommands_.insert(id);
56}
57
59 if (!id || deniedCommands_.contains(id)) return false;
60 return allowAllCommands_ || allowedCommands_.contains(id);
61}
62
63} // namespace eve::editor
64
65// EditorInspector.cpp
66namespace eve::editor {
67
69 fields_.clear();
70 pollCursor_ = 0;
71}
72
73int EditorInspector::findIndex(const std::string &id) const {
74 for (int i = 0; i < static_cast<int>(fields_.size()); ++i) {
75 if (fields_[i].id == id) return i;
76 }
77 return -1;
78}
79
80EditorInspector::Field *EditorInspector::find(const std::string &id) {
81 int i = findIndex(id);
82 return i < 0 ? nullptr : &fields_[i];
83}
84
85const EditorInspector::Field *EditorInspector::find(const std::string &id) const {
86 int i = findIndex(id);
87 return i < 0 ? nullptr : &fields_[i];
88}
89
90void EditorInspector::addFloat(const std::string &id, const std::string &label, float value, float minV, float maxV,
91 float step) {
92 if (id.empty() || findIndex(id) >= 0) throw Exception("EditorInspector::addFloat: bad id");
93 Field f;
94 f.kind = "float";
95 f.id = id;
96 f.label = label;
97 f.f0 = value;
98 f.minV = minV;
99 f.maxV = maxV;
100 f.step = step;
101 fields_.push_back(std::move(f));
102}
103
104void EditorInspector::addFloat3(const std::string &id, const std::string &label, float x, float y, float z) {
105 if (id.empty() || findIndex(id) >= 0) throw Exception("EditorInspector::addFloat3: bad id");
106 Field f;
107 f.kind = "float3";
108 f.id = id;
109 f.label = label;
110 f.f0 = x;
111 f.f1 = y;
112 f.f2 = z;
113 fields_.push_back(std::move(f));
114}
115
116void EditorInspector::addBool(const std::string &id, const std::string &label, bool value) {
117 if (id.empty() || findIndex(id) >= 0) throw Exception("EditorInspector::addBool: bad id");
118 Field f;
119 f.kind = "bool";
120 f.id = id;
121 f.label = label;
122 f.b = value;
123 fields_.push_back(std::move(f));
124}
125
126void EditorInspector::addString(const std::string &id, const std::string &label, const std::string &value) {
127 if (id.empty() || findIndex(id) >= 0) throw Exception("EditorInspector::addString: bad id");
128 Field f;
129 f.kind = "string";
130 f.id = id;
131 f.label = label;
132 f.s = value;
133 fields_.push_back(std::move(f));
134}
135
136void EditorInspector::addChoice(const std::string &id, const std::string &label, const std::string &choicesCsv,
137 const std::string &selected) {
138 if (id.empty() || findIndex(id) >= 0) throw Exception("EditorInspector::addChoice: bad id");
139 Field f;
140 f.kind = "choice";
141 f.id = id;
142 f.label = label;
143 f.choices = choicesCsv;
144 f.s = selected;
145 fields_.push_back(std::move(f));
146}
147
148std::string EditorInspector::getFieldKind(int index) const {
149 if (index < 0 || index >= static_cast<int>(fields_.size()))
150 throw Exception("EditorInspector::getFieldKind: bad index");
151 return fields_[index].kind;
152}
153std::string EditorInspector::getFieldId(int index) const {
154 if (index < 0 || index >= static_cast<int>(fields_.size()))
155 throw Exception("EditorInspector::getFieldId: bad index");
156 return fields_[index].id;
157}
158std::string EditorInspector::getFieldLabel(int index) const {
159 if (index < 0 || index >= static_cast<int>(fields_.size()))
160 throw Exception("EditorInspector::getFieldLabel: bad index");
161 return fields_[index].label;
162}
163
164float EditorInspector::getFloat(const std::string &id) const {
165 const Field *f = find(id);
166 if (!f || f->kind != "float") throw Exception("EditorInspector::getFloat: missing float field");
167 return f->f0;
168}
169
170void EditorInspector::setFloat(const std::string &id, float value) {
171 Field *f = find(id);
172 if (!f || f->kind != "float") throw Exception("EditorInspector::setFloat: missing float field");
173 if (f->f0 != value) {
174 f->f0 = value;
175 f->dirty = true;
176 }
177}
178
179float EditorInspector::getFloatMin(const std::string &id) const {
180 const Field *f = find(id);
181 if (!f || f->kind != "float") throw Exception("EditorInspector::getFloatMin: missing");
182 return f->minV;
183}
184float EditorInspector::getFloatMax(const std::string &id) const {
185 const Field *f = find(id);
186 if (!f || f->kind != "float") throw Exception("EditorInspector::getFloatMax: missing");
187 return f->maxV;
188}
189float EditorInspector::getFloatStep(const std::string &id) const {
190 const Field *f = find(id);
191 if (!f || f->kind != "float") throw Exception("EditorInspector::getFloatStep: missing");
192 return f->step;
193}
194
195float EditorInspector::getFloat3X(const std::string &id) const {
196 const Field *f = find(id);
197 if (!f || f->kind != "float3") throw Exception("EditorInspector::getFloat3X: missing");
198 return f->f0;
199}
200float EditorInspector::getFloat3Y(const std::string &id) const {
201 const Field *f = find(id);
202 if (!f || f->kind != "float3") throw Exception("EditorInspector::getFloat3Y: missing");
203 return f->f1;
204}
205float EditorInspector::getFloat3Z(const std::string &id) const {
206 const Field *f = find(id);
207 if (!f || f->kind != "float3") throw Exception("EditorInspector::getFloat3Z: missing");
208 return f->f2;
209}
210
211void EditorInspector::setFloat3(const std::string &id, float x, float y, float z) {
212 Field *f = find(id);
213 if (!f || f->kind != "float3") throw Exception("EditorInspector::setFloat3: missing");
214 if (f->f0 != x || f->f1 != y || f->f2 != z) {
215 f->f0 = x;
216 f->f1 = y;
217 f->f2 = z;
218 f->dirty = true;
219 }
220}
221
222bool EditorInspector::getBool(const std::string &id) const {
223 const Field *f = find(id);
224 if (!f || f->kind != "bool") throw Exception("EditorInspector::getBool: missing");
225 return f->b;
226}
227
228void EditorInspector::setBool(const std::string &id, bool value) {
229 Field *f = find(id);
230 if (!f || f->kind != "bool") throw Exception("EditorInspector::setBool: missing");
231 if (f->b != value) {
232 f->b = value;
233 f->dirty = true;
234 }
235}
236
237std::string EditorInspector::getString(const std::string &id) const {
238 const Field *f = find(id);
239 if (!f || f->kind != "string") throw Exception("EditorInspector::getString: missing");
240 return f->s;
241}
242
243void EditorInspector::setString(const std::string &id, const std::string &value) {
244 Field *f = find(id);
245 if (!f || f->kind != "string") throw Exception("EditorInspector::setString: missing");
246 if (f->s != value) {
247 f->s = value;
248 f->dirty = true;
249 }
250}
251
252std::string EditorInspector::getChoice(const std::string &id) const {
253 const Field *f = find(id);
254 if (!f || f->kind != "choice") throw Exception("EditorInspector::getChoice: missing");
255 return f->s;
256}
257
258void EditorInspector::setChoice(const std::string &id, const std::string &value) {
259 Field *f = find(id);
260 if (!f || f->kind != "choice") throw Exception("EditorInspector::setChoice: missing");
261 if (f->s != value) {
262 f->s = value;
263 f->dirty = true;
264 }
265}
266
267std::string EditorInspector::getChoicesCsv(const std::string &id) const {
268 const Field *f = find(id);
269 if (!f || f->kind != "choice") throw Exception("EditorInspector::getChoicesCsv: missing");
270 return f->choices;
271}
272
273bool EditorInspector::isDirty(const std::string &id) const {
274 const Field *f = find(id);
275 return f && f->dirty;
276}
277
278void EditorInspector::clearDirty(const std::string &id) {
279 Field *f = find(id);
280 if (f) f->dirty = false;
281}
282
284 for (auto &f : fields_) f.dirty = false;
285 pollCursor_ = 0;
286}
287
289 const int n = static_cast<int>(fields_.size());
290 if (n == 0) return "";
291 for (int k = 0; k < n; ++k) {
292 int i = (pollCursor_ + k) % n;
293 if (fields_[i].dirty) {
294 fields_[i].dirty = false;
295 pollCursor_ = (i + 1) % n;
296 return fields_[i].id;
297 }
298 }
299 return "";
300}
301
302} // namespace eve::editor
303
304// EditorPersistence.cpp
305namespace eve::editor {
306namespace {
307
308EditorValue operationValue(const DomainOperation &operation) {
310 value["type"] = EditorValue(operation.type);
311 value["inverseType"] = EditorValue(operation.inverseType);
312 value["target"] = EditorValue(operation.target.value());
313 value["payload"] = operation.payload;
314 value["inverse"] = operation.inverse;
315 value["hasInverse"] = EditorValue(operation.hasInverse);
316 value["mergeKey"] = EditorValue(operation.mergeKey);
317 return EditorValue(std::move(value));
318}
319
320DomainOperation decodeOperation(const EditorValue &value) {
322 const auto *object = value.getIf<EditorValue::Object>();
323 if (!object) return operation;
324 const auto text = [&](const char *key) {
325 auto found = object->find(key);
326 const auto *result = found == object->end() ? nullptr : found->second.getIf<std::string>();
327 return result ? *result : std::string{};
328 };
329 operation.type = text("type");
330 operation.inverseType = text("inverseType");
331 operation.target = TargetId(text("target"));
332 operation.mergeKey = text("mergeKey");
333 auto payload = object->find("payload");
334 if (payload != object->end()) operation.payload = payload->second;
335 auto inverse = object->find("inverse");
336 if (inverse != object->end()) operation.inverse = inverse->second;
337 auto hasInverse = object->find("hasInverse");
338 const auto *flag = hasInverse == object->end() ? nullptr : hasInverse->second.getIf<bool>();
339 operation.hasInverse = flag && *flag;
340 return operation;
341}
342
343Result<EditorPersistenceSnapshot> persistenceError(EditorStatus status, const char *rule, std::string message) {
344 return eve::editing::failed<EditorPersistenceSnapshot>(status, RuleId(rule), std::move(message));
345}
346
347} // namespace
348
350 if (!store_ || resourceUri_.empty())
351 return persistenceError(EditorStatus::Rejected, "editor.persistence.invalid",
352 "Persistence store and URI are required");
353 auto stored = store_->read(resourceUri_);
354 if (!stored.ok()) {
355 if (stored.code() == EditorStatus::NotFound) {
357 empty.kind = kind_;
358 return eve::editing::applied<EditorPersistenceSnapshot>(std::move(empty));
359 }
361 }
362 return decode(kind_, stored.value());
363}
364
366 EditorValue content,
367 std::vector<DomainOperation> journal) {
368 if (!store_ || base.kind != kind_)
369 return persistenceError(EditorStatus::Rejected, "editor.persistence.kind-mismatch",
370 "Persistence checkpoint belongs to another backend kind");
371 EditorValue::Array serializedJournal;
372 serializedJournal.reserve(journal.size());
373 for (const DomainOperation &operation : journal) serializedJournal.push_back(operationValue(operation));
374 EditorValue::Object envelope;
375 envelope["schemaVersion"] = EditorValue(1);
376 envelope["content"] = std::move(content);
377 envelope["journal"] = EditorValue(std::move(serializedJournal));
378 auto stored =
379 store_->compareAndSwap(resourceUri_, base.revision, base.contentHash, EditorValue(std::move(envelope)));
380 if (!stored.ok()) return Result<EditorPersistenceSnapshot>::failure(stored.status());
381 return decode(kind_, stored.value());
382}
383
384Result<EditorPersistenceSnapshot> EditorPersistenceAdapter::decode(EditorPersistenceKind kind,
385 const StoredDocument &stored) {
386 const auto *envelope = stored.content.getIf<EditorValue::Object>();
387 if (!envelope)
388 return persistenceError(EditorStatus::Failed, "editor.persistence.invalid-envelope",
389 "Persistence checkpoint must be an object");
390 const auto content = envelope->find("content");
391 const auto journal = envelope->find("journal");
392 const auto *journalValues = journal == envelope->end() ? nullptr : journal->second.getIf<EditorValue::Array>();
393 if (content == envelope->end() || !journalValues)
394 return persistenceError(EditorStatus::Failed, "editor.persistence.invalid-envelope",
395 "Persistence checkpoint content or journal is missing");
397 result.kind = kind;
398 result.revision = stored.revision;
399 result.contentHash = stored.contentHash;
400 result.content = content->second;
401 for (const EditorValue &value : *journalValues) result.journal.push_back(decodeOperation(value));
402 return eve::editing::applied<EditorPersistenceSnapshot>(std::move(result));
403}
404
405} // namespace eve::editor
406
407// EditorPropertyModel.cpp
410
411#include <algorithm>
412#include <atomic>
413#include <chrono>
414#include <cstdint>
415#include <span>
416#include <utility>
417
418namespace eve::editor {
419namespace {
420
421template <class T>
422eve::Result<void> writeFailure(const Result<T> &result, std::string fallbackCode, std::string fallbackMessage) {
423 if (!result.diagnostics().empty()) {
424 const EditorDiagnostic &diagnostic = result.diagnostics().front();
425 const RuleId rule = eve::editing::diagnosticRule(diagnostic);
426 if (!rule.empty() && !diagnostic.message().empty())
427 return property_access::rejected(rule.value(), diagnostic.message());
428 if (!diagnostic.message().empty())
429 return property_access::rejected(std::move(fallbackCode), diagnostic.message());
430 }
431 return property_access::rejected(std::move(fallbackCode), std::move(fallbackMessage));
432}
433
434TransactionId newPropertyTransactionId() {
435 static std::atomic<std::uint64_t> entropySequence{1};
436 const eve::UuidV7Generator generator([](std::span<std::uint8_t> bytes) {
437 const std::uint64_t seed = entropySequence.fetch_add(1, std::memory_order_relaxed);
438 for (std::size_t index = 0; index < bytes.size(); ++index)
439 bytes[index] = static_cast<std::uint8_t>(seed >> ((index % sizeof(seed)) * 8u));
440 return true;
441 });
442 const auto generated = generator.generate(std::chrono::system_clock::now());
443 if (!generated) {
444 // A clock before the UUID epoch is not expected for a live editor, but
445 // retain a valid canonical UUID path if a platform clock is malformed.
446 const auto epoch = generator.generate(std::chrono::system_clock::time_point{});
447 if (!epoch) return TransactionId{};
448 using CanonicalUuid = typename TransactionId::Uuid;
449 return TransactionId::fromUuid(CanonicalUuid(epoch->bytes()));
450 }
451 using CanonicalUuid = typename TransactionId::Uuid;
452 return TransactionId::fromUuid(CanonicalUuid(generated->bytes()));
453}
454
455TargetId selectionTarget(const SelectionSnapshot &selection) {
456 if (selection.primary && !selection.primary->target.empty()) return selection.primary->target;
457 for (const SelectionItem &item : selection.items)
458 if (!item.target.empty()) return item.target;
459 return {};
460}
461
462EditorStatus editorStatusFor(eve::StatusCode code) {
463 switch (code) {
464 case eve::StatusCode::Conflict: return EditorStatus::Conflict;
465 case eve::StatusCode::NotFound: return EditorStatus::NotFound;
466 case eve::StatusCode::Unsupported: return EditorStatus::Unsupported;
467 case eve::StatusCode::Cancelled: return EditorStatus::Cancelled;
468 case eve::StatusCode::Rejected: return EditorStatus::Rejected;
473 case eve::StatusCode::Failed: return EditorStatus::Failed;
474 }
475 return EditorStatus::Failed;
476}
477
478Result<eve::Revision> providerRevisionFailure(const eve::Result<eve::Revision> &result) {
479 const eve::Status &status = result.status();
480 const char *rule = "editor.property.current-revision";
481 switch (status.code()) {
482 case eve::StatusCode::Conflict: rule = "editor.property.revision-conflict"; break;
483 case eve::StatusCode::Unsupported: rule = "editor.property.revision-unsupported"; break;
484 case eve::StatusCode::NotFound: rule = "editor.property.target"; break;
485 default: break;
486 }
487 return eve::editing::failed<eve::Revision>(editorStatusFor(status.code()), RuleId(rule), status.describe());
488}
489
490Result<void> externalRevisionConflict(eve::Revision expected, eve::Revision actual) {
491 return eve::editing::failed<void>(EditorStatus::Conflict, RuleId("editor.property.revision-conflict"),
492 "Property target revision changed from " + std::to_string(expected.value()) +
493 " to " + std::to_string(actual.value()) + "; refresh/rebase before writing");
494}
495
496} // namespace
497
499 struct Entry {
500 std::uint64_t id = 0;
502 };
503 std::uint64_t nextId = 1;
504 std::vector<Entry> entries;
505};
506
509 HostProfile profile, IEditorTransactionBackend *transactionBackend)
510 : editorSchema_(std::move(schema)),
511 selection_(std::move(selection)),
512 provider_(provider),
513 surface_(surface),
514 profile_(std::move(profile)),
515 transactionBackend_(transactionBackend),
516 observers_(std::make_shared<ObserverState>()) {
517 rebuildSchema();
518 const Result<void> initialBinding = bind();
519 if (!initialBinding.ok()) {
520 // A constructor cannot return a Result. Keep the model unbound so
521 // every write fails closed until the caller explicitly refreshes.
522 }
523}
524
526
527void EditorPropertyModel::rebuildSchema() {
528 presentationSchema_.typeId = editorSchema_.typeId;
529 presentationSchema_.version = editorSchema_.version;
530 presentationSchema_.properties.clear();
531 if (surface_ == PropertyModelSurface::Runtime && !profile_.hasFeatures(HostFeature::RuntimeWorld)) return;
532 for (const PropertyDescriptor &property : editorSchema_.properties) {
533 if (surface_ == PropertyModelSurface::Runtime && (!hasPropertyFlag(property.flags, PropertyFlag::Runtime) ||
534 hasPropertyFlag(property.flags, PropertyFlag::EditorOnly)))
535 continue;
536 presentationSchema_.properties.push_back(toPresentationDescriptor(property));
537 }
538}
539
540std::optional<eve::Value> EditorPropertyModel::read(const std::string &path) const {
541 if (!presentationSchema_.find(path)) return std::nullopt;
542 const auto found = cachedProperties_.find(path);
543 if (found == cachedProperties_.end() || found->second.state != property_access::PropertyChangeState::Value)
544 return std::nullopt;
545 return found->second.value;
546}
547
549 if (!provider_) return property_access::rejected("editor.property.provider", "No property provider");
550 const Result<void> revisionCheck = ensureCurrentRevision();
551 if (!revisionCheck.ok())
552 return writeFailure(revisionCheck, "editor.property.revision", "Property revision is unavailable");
553 if (transactionBackend_ && transactionBackend_->active() && pendingPaths_.contains(path))
554 return property_access::rejected("editor.property.duplicate-path",
555 "A property may be written only once per transaction");
556
557 const EditorValue editorValue = toEditorValue(value);
558 Result<PropertyEditIntent> intent = [&]() {
559 if (surface_ == PropertyModelSurface::Runtime) {
560 RuntimePropertyPresenter presenter;
561 return presenter.editIntent(editorSchema_, selection_, PropertyPath(path), editorValue, profile_);
562 }
564 return presenter.editIntent(editorSchema_, selection_, PropertyPath(path), editorValue);
565 }();
566 if (!intent.ok()) {
567 return writeFailure(intent, "editor.property.intent", "Property edit was rejected");
568 }
569
570 if (transactionBackend_) {
572 provider_->makeSet(selection_, PropertyPath(path), editorValue, PropertySetMode::Absolute);
573 if (!operation.ok())
574 return writeFailure(operation, "editor.property.operation", "Property operation was rejected");
575 if (operation.value().target.empty())
576 return property_access::rejected("editor.property.target", "Property operation has no target");
577 if (operation.value().mergeKey.empty())
578 operation.value().mergeKey = intent.value().command.value() + ":" + path;
579
580 bool started = false;
581 if (!transactionBackend_->active()) {
582 TransactionSpec specification;
583 specification.id = newPropertyTransactionId();
584 specification.label = intent.value().command.value();
585 specification.target = operation.value().target;
586 specification.mergeKey = operation.value().mergeKey;
587 specification.baseRevision = targetRevision_.value();
588 if (specification.id.empty())
589 return property_access::rejected("editor.property.transaction-id",
590 "Could not allocate a property transaction identity");
591 Result<TransactionId> begun = transactionBackend_->begin(std::move(specification));
592 if (!begun.ok() || !begun.ok())
593 return writeFailure(begun, "editor.property.transaction.begin", "Could not begin property transaction");
594 started = true;
595 }
596
597 Result<void> appended = transactionBackend_->append(std::move(operation.value()));
598 if (!appended.ok()) {
599 if (started) {
600 Result<void> discarded = transactionBackend_->discard();
601 if (!discarded.ok())
602 return writeFailure(discarded, "editor.property.transaction.discard",
603 "Could not discard rejected property transaction");
604 }
605 return writeFailure(appended, "editor.property.transaction.append", "Could not stage property operation");
606 }
607 pendingPaths_.insert(path);
608
609 // An already-open transaction is intentionally left staged for the
610 // caller's explicit preview/commit boundary.
611 if (!started) return property_access::accepted();
612
613 Result<EditorDryRunReport> previewed = transactionBackend_->preview();
614 if (!previewed.ok() || !previewed.ok()) {
615 Result<void> discarded = transactionBackend_->discard();
616 pendingPaths_.clear();
617 if (!discarded.ok())
618 return writeFailure(discarded, "editor.property.transaction.discard",
619 "Could not discard failed property preview");
620 return writeFailure(previewed, "editor.property.transaction.preview",
621 "Property transaction preview was rejected");
622 }
623
624 Result<TransactionReceipt> committed = transactionBackend_->commit();
625 if (!committed.ok() || !committed.ok())
626 // Commit failure is deliberately retained by the backend so the
627 // caller can inspect diagnostics, retry, or explicitly discard.
628 return writeFailure(committed, "editor.property.transaction.commit", "Property transaction commit failed");
629 targetRevision_ = eve::Revision(committed.value().afterRevision);
630 pendingPaths_.clear();
631 // The mutation already committed. Do not report a successful commit
632 // as a rejected write; force an explicit refresh if observation fails.
633 if (!refresh().ok()) bound_ = false;
635 }
636
637 if (!sink_) return property_access::rejected("editor.property.sink", "No command sink is connected");
638 // The sink is a compatibility path and may not have an authority that can
639 // perform a commit-time CAS. Recheck immediately before handing it the
640 // intent; stale compatibility writes must fail closed as well.
641 const Result<void> sinkRevisionCheck = ensureCurrentRevision();
642 if (!sinkRevisionCheck.ok())
643 return writeFailure(sinkRevisionCheck, "editor.property.revision", "Property revision is unavailable");
644 const Result<void> applied = sink_(intent.value());
645 if (!applied.ok()) return writeFailure(applied, "editor.property.command", "Property command failed");
646 // A legacy sink may mutate the provider without returning a receipt. Read
647 // the authoritative post-command revision so the next write does not use
648 // the pre-command baseline. If observation fails, retain command success
649 // and require an explicit refresh before another write.
650 if (!refresh().ok()) bound_ = false;
652}
653
655 if (transactionBackend_ && transactionBackend_->active())
656 return eve::editing::failed<void>(
657 EditorStatus::Conflict, RuleId("editor.property.active-transaction"),
658 "Cannot replace a property transaction backend while a transaction is active");
659 if (backend && backend->active())
660 return eve::editing::failed<void>(EditorStatus::Conflict, RuleId("editor.property.backend-active"),
661 "Cannot attach a backend that already has an active transaction");
662 transactionBackend_ = backend;
663 pendingPaths_.clear();
664 return eve::editing::applied<void>();
665}
666
668 if (!transactionBackend_)
669 return eve::editing::failed<TransactionId>(EditorStatus::Unsupported,
670 RuleId("editor.property.transaction-backend"),
671 "A transaction backend is not configured");
672 if (transactionBackend_->active())
673 return eve::editing::failed<TransactionId>(EditorStatus::Conflict, RuleId("editor.property.transaction-active"),
674 "A transaction is already active");
675 const TargetId target = selectionTarget(selection_);
676 if (target.empty())
677 return eve::editing::failed<TransactionId>(EditorStatus::Rejected, RuleId("editor.property.target"),
678 "An explicit property transaction requires a selected target");
679 const Result<void> revisionCheck = ensureCurrentRevision();
680 if (!revisionCheck.ok()) {
681 return Result<TransactionId>::failure(revisionCheck.status());
682 }
683 TransactionSpec specification;
684 specification.id = newPropertyTransactionId();
685 specification.label = std::move(label);
686 specification.target = target;
687 specification.baseRevision = targetRevision_.value();
688 specification.mergeKey = "editor.property";
689 if (specification.id.empty())
690 return eve::editing::failed<TransactionId>(EditorStatus::Failed, RuleId("editor.property.transaction-id"),
691 "Could not allocate a property transaction identity");
692 Result<TransactionId> result = transactionBackend_->begin(std::move(specification));
693 if (result.ok()) pendingPaths_.clear();
694 return result;
695}
696
698 if (!transactionBackend_)
699 return eve::editing::failed<EditorDryRunReport>(EditorStatus::Unsupported,
700 RuleId("editor.property.transaction-backend"),
701 "A transaction backend is not configured");
702 Result<EditorDryRunReport> result = transactionBackend_->preview();
703 if (!result.ok()) return result;
704 return result;
705}
706
708 if (!transactionBackend_)
709 return eve::editing::failed<TransactionReceipt>(EditorStatus::Unsupported,
710 RuleId("editor.property.transaction-backend"),
711 "A transaction backend is not configured");
712 Result<TransactionReceipt> result = transactionBackend_->commit();
713 if (!result.ok()) return result;
714 targetRevision_ = eve::Revision(result.value().afterRevision);
715 pendingPaths_.clear();
716 const Result<void> refreshed = refresh();
717 if (!refreshed.ok())
719 eve::Status(EditorStatus::Applied, refreshed.diagnostics()));
720 return result;
721}
722
724 if (!transactionBackend_)
725 return eve::editing::failed<void>(EditorStatus::Unsupported, RuleId("editor.property.transaction-backend"),
726 "A transaction backend is not configured");
727 Result<void> result = transactionBackend_->discard();
728 if (result.ok()) pendingPaths_.clear();
729 return result;
730}
731
733 if (!transactionBackend_)
734 return eve::editing::failed<TransactionReceipt>(EditorStatus::Unsupported,
735 RuleId("editor.property.transaction-backend"),
736 "A transaction backend is not configured");
737 Result<TransactionReceipt> result = transactionBackend_->retry();
738 if (!result.ok()) return result;
739 targetRevision_ = eve::Revision(result.value().afterRevision);
740 pendingPaths_.clear();
741 const Result<void> refreshed = refresh();
742 if (!refreshed.ok())
744 eve::Status(EditorStatus::Applied, refreshed.diagnostics()));
745 return result;
746}
747
749 if (!transactionBackend_)
750 return eve::editing::failed<TransactionReceipt>(EditorStatus::Unsupported,
751 RuleId("editor.property.transaction-backend"),
752 "A transaction backend is not configured");
753 Result<TransactionReceipt> result = transactionBackend_->undo();
754 if (!result.ok()) return result;
755 targetRevision_ = eve::Revision(result.value().afterRevision);
756 const Result<void> refreshed = refresh();
757 if (!refreshed.ok())
759 eve::Status(EditorStatus::Applied, refreshed.diagnostics()));
760 return result;
761}
762
764 if (!transactionBackend_)
765 return eve::editing::failed<TransactionReceipt>(EditorStatus::Unsupported,
766 RuleId("editor.property.transaction-backend"),
767 "A transaction backend is not configured");
768 Result<TransactionReceipt> result = transactionBackend_->redo();
769 if (!result.ok()) return result;
770 targetRevision_ = eve::Revision(result.value().afterRevision);
771 const Result<void> refreshed = refresh();
772 if (!refreshed.ok())
774 eve::Status(EditorStatus::Applied, refreshed.diagnostics()));
775 return result;
776}
777
779 const std::uint64_t id = observers_->nextId++;
780 observers_->entries.push_back({id, std::move(callback)});
781 std::weak_ptr<ObserverState> weak = observers_;
782 return property_access::Subscription([weak, id]() {
783 if (const auto state = weak.lock())
784 std::erase_if(state->entries, [id](const ObserverState::Entry &entry) { return entry.id == id; });
785 });
786}
787
788Result<eve::Revision> EditorPropertyModel::readProviderRevision() const {
789 if (!provider_)
790 return eve::editing::failed<eve::Revision>(EditorStatus::Unsupported, RuleId("editor.property.provider"),
791 "No property provider is connected");
792 eve::Result<eve::Revision> result = provider_->currentRevision(selection_);
793 if (!result.ok()) return providerRevisionFailure(result);
794 return eve::editing::applied<eve::Revision>(eve::Revision(result.value().value()));
795}
796
797Result<void> EditorPropertyModel::ensureCurrentRevision() const {
798 const Result<eve::Revision> current = readProviderRevision();
799 if (!current.ok()) return Result<void>::failure(current.status());
800 if (!bound_)
801 return eve::editing::failed<void>(EditorStatus::Conflict, RuleId("editor.property.unbound"),
802 "Property model is not bound to a provider revision; call refresh/rebase");
803 if (current.value() != targetRevision_) return externalRevisionConflict(targetRevision_, current.value());
804 return eve::editing::applied<void>();
805}
806
808
810
812 if (!provider_)
813 return eve::editing::failed<void>(EditorStatus::Unsupported, RuleId("editor.property.provider"),
814 "No property provider is connected");
815 if (transactionBackend_ && transactionBackend_->active())
816 return eve::editing::failed<void>(EditorStatus::Conflict, RuleId("editor.property.active-transaction"),
817 "Cannot refresh or rebase while a property transaction is active");
818
819 const Result<eve::Revision> first = readProviderRevision();
820 if (!first.ok()) return Result<void>::failure(first.status());
821
822 std::map<std::string, CachedProperty> nextProperties;
823 for (const property_access::PropertyDescriptor &property : presentationSchema_.properties) {
824 const PropertyReadResult current = provider_->read(selection_, PropertyPath(property.path));
825 if (current.state == PropertyReadState::Error) {
826 if (!current.diagnostics.empty())
827 return Result<void>::failure(eve::Status(EditorStatus::Failed, current.diagnostics));
828 return eve::editing::failed<void>(EditorStatus::Failed, RuleId("editor.property.read"),
829 "Property provider returned a read error");
830 }
831 CachedProperty cached;
832 switch (current.state) {
833 case PropertyReadState::Value:
835 cached.value = toPresentationValue(current.value);
836 break;
837 case PropertyReadState::Mixed: cached.state = property_access::PropertyChangeState::Mixed; break;
838 case PropertyReadState::Missing: cached.state = property_access::PropertyChangeState::Missing; break;
839 case PropertyReadState::Error: break;
840 }
841 nextProperties.emplace(property.path, std::move(cached));
842 }
843
844 const Result<eve::Revision> last = readProviderRevision();
845 if (!last.ok()) return Result<void>::failure(last.status());
846 if (first.value() != last.value()) return externalRevisionConflict(first.value(), last.value());
847
848 std::vector<property_access::PropertyChange> changes;
849 for (const auto &[path, property] : nextProperties) {
850 const auto found = cachedProperties_.find(path);
851 if (found == cachedProperties_.end() || found->second != property)
852 changes.push_back({path, property.value.value_or(eve::Value{}), 0, property.state});
853 }
854
855 if (!changes.empty()) {
856 const std::uint64_t snapshotRevision = ++revision_;
857 for (property_access::PropertyChange &change : changes) change.revision = snapshotRevision;
858 }
859 cachedProperties_ = std::move(nextProperties);
860 targetRevision_ = last.value();
861 bound_ = true;
862 dispatch(std::move(changes));
863 return eve::editing::applied<void>();
864}
865
866void EditorPropertyModel::dispatch(std::vector<property_access::PropertyChange> changes) {
867 if (changes.empty()) return;
868 notificationQueue_.push_back(std::move(changes));
869 if (dispatchingNotifications_) return;
870
871 dispatchingNotifications_ = true;
872 try {
873 while (!notificationQueue_.empty()) {
874 std::vector<property_access::PropertyChange> batch = std::move(notificationQueue_.front());
875 notificationQueue_.erase(notificationQueue_.begin());
876 for (const property_access::PropertyChange &change : batch) {
877 const auto observers = observers_->entries;
878 for (const ObserverState::Entry &entry : observers)
879 if (entry.callback) entry.callback(change);
880 }
881 }
882 dispatchingNotifications_ = false;
883 } catch (...) {
884 notificationQueue_.clear();
885 dispatchingNotifications_ = false;
886 throw;
887 }
888}
889
890} // namespace eve::editor
double z
double y
double x
LogicalId target
ActionParameterOperation operation
Value::Object payload
std::string selected
std::uint64_t revision
bool committed
bool applied
SQObjectPtr key
Definition ECS.cpp:155
std::vector< std::uint8_t > stored
Definition Evpack.cpp:171
std::string message
DiagnosticCode code
wgpu::PopErrorScopeStatus status
glm::vec3 n
Definition Grass.cpp:63
std::int32_t first
std::map< std::string, PropertyRule > properties
bool required
std::string label
std::string id
Poco::JSON::Object::Ptr result
std::uint64_t bytes
OceanRenderBackend backend
uint64_t epoch
Definition OnnxGpgpu.cpp:28
bool dirty
float f
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
bool found
std::string text
std::string kind
double current
Json object
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
uint32_t index
ViewPreparation callback
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
const T & value() const &
Borrow the value from a const lvalue after checking success.
Definition Result.h:339
const std::vector< Diagnostic > & diagnostics() const noexcept
Inspect all diagnostics; this counts as checking the Result.
Definition Result.h:314
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:286
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:300
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
Move-only RAII token that owns one observer registration.
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
static UuidIdAdapter fromUuid(Uuid value)
Builds an adapter from an explicit canonical UUID.
Definition Identity.h:346
const std::string & value() const noexcept
Returns the exact legacy or canonical compatibility spelling.
Definition Identity.h:365
StrongUuid< Tag > Uuid
Definition Identity.h:315
bool empty() const noexcept
True when no compatibility spelling has been assigned.
Definition Identity.h:377
Injectable UUIDv7 generator.
Definition UuidV7.h:38
std::optional< PersistentId > generate() const
Generates a UUIDv7 using the injected clock.
Definition Identity.cpp:81
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
UI-independent property access for an immutable selection snapshot.
virtual Result< DomainOperation > makeSet(const SelectionSnapshot &selection, const PropertyPath &path, const Value &value, PropertySetMode mode) const =0
Make set.
virtual PropertyReadResult read(const SelectionSnapshot &selection, const PropertyPath &path) const =0
Reads read.
virtual eve::Result< eve::Revision > currentRevision(const SelectionSnapshot &selection) const
Current revision.
Deterministic owning value tree shared by authoring hosts.
std::vector< Value > Array
std::map< std::string, Value > Object
Shared presenter logic that exposes developer-oriented property rows.
Result< PropertyEditIntent > editIntent(const PropertySchema &schema, const SelectionSnapshot &selection, const PropertyPath &path, const EditorValue &value, PropertySetMode mode=PropertySetMode::Absolute) const
Validate a candidate and emit a command payload without mutating the provider.
void addFloat(const std::string &id, const std::string &label, float value, float minV, float maxV, float step)
Adds float.
std::string getFieldKind(int index) const
Returns the field kind.
bool isDirty(const std::string &id) const
True when dirty.
void setFloat3(const std::string &id, float x, float y, float z)
Sets the float 3.
float getFloatStep(const std::string &id) const
Returns the float step.
std::string getFieldLabel(int index) const
Returns the field label.
float getFloat3X(const std::string &id) const
Returns the float 3 x.
void setChoice(const std::string &id, const std::string &value)
Sets the choice.
std::string getString(const std::string &id) const
Returns the string.
void clearDirty(const std::string &id)
Clears dirty.
std::string pollChangedId()
Returns next dirty field id, or "" if none.
void setFloat(const std::string &id, float value)
Sets the float.
std::string getChoice(const std::string &id) const
Returns the choice.
std::string getChoicesCsv(const std::string &id) const
Returns the choices csv.
void addString(const std::string &id, const std::string &label, const std::string &value)
Adds string.
float getFloat(const std::string &id) const
Returns the float.
float getFloat3Z(const std::string &id) const
Returns the float 3 z.
std::string getFieldId(int index) const
Returns the field id.
void setString(const std::string &id, const std::string &value)
Sets the string.
void setBool(const std::string &id, bool value)
Sets the bool.
void addBool(const std::string &id, const std::string &label, bool value)
Adds bool.
float getFloatMax(const std::string &id) const
Returns the float max.
float getFloatMin(const std::string &id) const
Returns the float min.
void addFloat3(const std::string &id, const std::string &label, float x, float y, float z)
Adds float 3.
bool getBool(const std::string &id) const
Returns the bool.
void addChoice(const std::string &id, const std::string &label, const std::string &choicesCsv, const std::string &selected)
Adds choice.
void clearAllDirty()
Clears all dirty.
float getFloat3Y(const std::string &id) const
Returns the float 3 y.
Result< EditorPersistenceSnapshot > commit(const EditorPersistenceSnapshot &base, EditorValue content, std::vector< DomainOperation > journal)
Atomically commit a checkpoint against its loaded revision/hash.
Result< EditorPersistenceSnapshot > load() const
Load the last committed checkpoint and journal.
Result< TransactionReceipt > undo()
Undo the latest committed property transaction.
Result< void > setTransactionBackend(IEditorTransactionBackend *backend)
Set the borrowed canonical transaction boundary.
property_access::Subscription subscribe(ChangeCallback callback) override
Subscribe.
Result< void > rollbackTransaction()
Discard pending property writes without publishing them.
~EditorPropertyModel() override
Editor property model.
Result< EditorDryRunReport > previewTransaction()
Validate pending property writes without changing the target.
Result< TransactionReceipt > redo()
Redo the latest undone property transaction.
EditorPropertyModel(PropertySchema schema, SelectionSnapshot selection, const IPropertyProvider *provider, PropertyModelSurface surface=PropertyModelSurface::Developer, HostProfile profile=HostProfile::developer(), IEditorTransactionBackend *transactionBackend=nullptr)
Editor property model.
Result< TransactionReceipt > commitTransaction()
Commit pending property writes and refresh observers after success.
Result< TransactionId > beginTransaction(std::string label="Edit property")
Begin an explicit property transaction.
Result< TransactionReceipt > retryTransaction()
Retry a retained failed commit.
Result< void > refresh()
Re-read values and adopt the provider's current revision.
Result< void > bind()
Bind to the provider's current revision and values.
Result< void > rebase()
Explicit spelling for refreshing and rebasing this model.
std::optional< eve::Value > read(const std::string &path) const override
Reads .
eve::Result< void > write(const std::string &path, const eve::Value &value) override
Writes .
Upper capability boundary for one editor host.
static HostProfile runtimeBuilder()
Safe runtime profile that denies commands unless allow-listed.
static HostProfile developer()
Unrestricted developer profile used by legacy sessions.
void allowCommands(std::initializer_list< CommandId > ids)
Allow commands.
void denyCommand(const CommandId &id)
Deny command.
bool hasFeatures(HostFeature required) const
True when features.
bool allowsCommand(const CommandId &id) const
Allows command.
void allowCommand(CommandId id)
Allow command.
static HostProfile automation()
Headless profile that denies commands unless allow-listed.
virtual Result< StoredDocument > read(const std::string &resourceUri) const =0
Read the latest value for a resource URI.
virtual Result< StoredDocument > compareAndSwap(const std::string &resourceUri, Revision expectedRevision, const std::string &expectedContentHash, const EditorValue &content)=0
Replace a value only when the expected disk revision still matches.
Transaction boundary consumed by editor property and other UI models.
virtual Result< TransactionReceipt > redo()=0
Reapply the latest compensated transaction.
virtual Result< void > discard()=0
Discard pending work after reverting any provisional preview.
virtual Result< TransactionReceipt > undo()=0
Compensate the latest committed transaction.
virtual Result< TransactionReceipt > commit()=0
Publish the pending transaction and retain it for undo.
virtual Result< TransactionReceipt > retry()=0
Retry a failed commit while retaining its original operation list.
virtual Result< void > append(DomainOperation operation)=0
Append a serializable operation to the pending transaction.
virtual bool active() const noexcept=0
Whether a transaction is currently pending.
virtual Result< EditorDryRunReport > preview()=0
Validate the pending transaction without publishing target state.
virtual Result< TransactionId > begin(TransactionSpec specification)=0
Begin an explicit transaction without mutating its target.
Shared presenter logic that exposes only runtime-safe property rows.
Result< PropertyEditIntent > editIntent(const PropertySchema &schema, const SelectionSnapshot &selection, const PropertyPath &path, const EditorValue &value, const HostProfile &profile, PropertySetMode mode=PropertySetMode::Absolute) const
Validate a runtime-visible candidate and emit the same command payload as developer UI.
std::function< void(const PropertyChange &)> ChangeCallback
std::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
RuleId diagnosticRule(const Diagnostic &diagnostic)
Return the projected editing rule, or an empty RuleId when absent.
eve::editing::Value EditorValue
Compatibility alias for the UI-independent authoring value tree.
Definition EditorValue.h:8
EditorValue toEditorValue(const eve::Value &value)
Compatibility spelling for conversion into the authoring value tree.
eve::editing::PropertyPath PropertyPath
Definition EditorIds.h:37
eve::editing::SelectionItem SelectionItem
Stable item stored in a selection snapshot.
eve::editing::TargetId TargetId
Definition EditorIds.h:29
eve::Diagnostic EditorDiagnostic
eve::editing::RuleId RuleId
Definition EditorIds.h:32
eve::editing::SelectionSnapshot SelectionSnapshot
Immutable multi-selection captured for property and command work.
EditorPersistenceKind
Persistence target selected by a game/editor host.
HostFeature
Coarse host features used to discover and gate editor extensions.
PropertyModelSurface
Property visibility/permission surface exposed by an editor model.
eve::editing::DomainOperation DomainOperation
eve::editing::TransactionId TransactionId
Definition EditorIds.h:34
eve::StatusCode EditorStatus
Definition EditorResult.h:8
Result< void > rejected(std::string rule, std::string message, DiagnosticCode code=DiagnosticCode::PreconditionViolation)
Build a rejected write/validation result with a stable rule string.
eve::Subscription Subscription
Compatibility alias for the common observer lifetime token.
Result< void > accepted()
Build a successful write/validation result.
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
detail::StrongUint64< detail::RevisionTag > Revision
Monotonic content/state revision used for optimistic-concurrency checks.
Definition Revision.h:13
DomainOperation public API.
PropertyDescriptor public API.
PropertyReadResult public API.
EVENGINE_API_PLATFORM public API.
SelectionSnapshot public API.
TransactionSpec public API.
Loaded checkpoint plus the domain operations recorded with it.
Value snapshot returned by an atomic document store.
Immutable notification emitted after a model property changes.
One stable property description consumed by any UI shell.
eve::OptionalRef< const PropertyDescriptor > find(const std::string &path) const
Find a property by stable path, or an empty immediate borrow.
std::vector< PropertyDescriptor > properties
bool started
Definition Graphics.cpp:200