载入中...
搜索中...
未找到
EditorPropertyPresenter.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <deque>
4#include <exception>
5#include <unordered_set>
13
14// EditorPropertyPresenter.cpp
15namespace eve::editor {
16namespace {
17
18EditorValue selectionValue(const SelectionSnapshot& selection) {
20 items.reserve(selection.items.size());
21 for (const SelectionItem& item : selection.items) items.emplace_back(item.item.value());
22 return EditorValue(std::move(items));
23}
24
25Result<PropertyEditIntent> makeIntent(const PropertySchema& schema, const SelectionSnapshot& selection,
27 bool runtime) {
28 auto descriptor = schema.find(path);
29 if (!descriptor)
30 return eve::editing::failed<PropertyEditIntent>(EditorStatus::NotFound, RuleId("editor.property.not-found"),
31 "Property is not present in the schema: " + path.value());
32 if (runtime && (!hasPropertyFlag(descriptor->flags, PropertyFlag::Runtime) ||
33 hasPropertyFlag(descriptor->flags, PropertyFlag::EditorOnly)))
34 return eve::editing::failed<PropertyEditIntent>(EditorStatus::Rejected,
35 RuleId("editor.property.runtime-hidden"),
36 "Property is unavailable in runtime editing");
37 Result<void> validation = validatePropertyValue(*descriptor, value);
38 if (!validation.ok()) return Result<PropertyEditIntent>::failure(validation.status());
39
41 payload["path"] = path.value();
42 payload["value"] = value;
43 payload["selection"] = selectionValue(selection);
44 switch (mode) {
45 case PropertySetMode::Absolute: payload["mode"] = "absolute"; break;
46 case PropertySetMode::Relative: payload["mode"] = "relative"; break;
47 case PropertySetMode::Reset: payload["mode"] = "reset"; break;
48 }
49 return eve::editing::applied<PropertyEditIntent>(
50 PropertyEditIntent{CommandId("editor.property.set"), EditorValue(std::move(payload))});
51}
52
53} // namespace
54
56 const SelectionSnapshot& selection,
57 const IPropertyProvider& provider) const {
59 presentation.typeId = schema.typeId;
60 presentation.schemaVersion = schema.version;
61 presentation.rows.reserve(schema.properties.size());
62 for (const PropertyDescriptor& descriptor : schema.properties)
63 presentation.rows.push_back({descriptor, provider.read(selection, descriptor.path)});
64 return presentation;
65}
66
67Result<PropertyEditIntent> DeveloperPropertyPresenter::editIntent(const PropertySchema& schema,
68 const SelectionSnapshot& selection,
69 const PropertyPath& path, const EditorValue& value,
70 PropertySetMode mode) const {
71 return makeIntent(schema, selection, path, value, mode, false);
72}
73
74PropertyPresentation RuntimePropertyPresenter::present(const PropertySchema& schema, const SelectionSnapshot& selection,
76 const HostProfile& profile) const {
78 presentation.typeId = schema.typeId;
79 presentation.schemaVersion = schema.version;
80 if (!profile.hasFeatures(HostFeature::RuntimeWorld)) return presentation;
81 for (const PropertyDescriptor& descriptor : schema.properties) {
82 if (!hasPropertyFlag(descriptor.flags, PropertyFlag::Runtime) ||
83 hasPropertyFlag(descriptor.flags, PropertyFlag::EditorOnly))
84 continue;
85 presentation.rows.push_back({descriptor, provider.read(selection, descriptor.path)});
86 }
87 return presentation;
88}
89
90Result<PropertyEditIntent> RuntimePropertyPresenter::editIntent(const PropertySchema& schema,
91 const SelectionSnapshot& selection,
92 const PropertyPath& path, const EditorValue& value,
93 const HostProfile& profile,
94 PropertySetMode mode) const {
95 if (!profile.hasFeatures(HostFeature::RuntimeWorld))
96 return eve::editing::failed<PropertyEditIntent>(EditorStatus::Rejected,
97 RuleId("editor.property.runtime-feature-denied"),
98 "Host profile does not expose runtime world editing");
99 return makeIntent(schema, selection, path, value, mode, true);
100}
101
102} // namespace eve::editor
103
104// EditorRuntimeManifest.cpp
105namespace eve::editor {
106namespace {
107
108template <class Id>
109bool selected(const std::vector<Id>& values, const Id& id) {
110 return std::find(values.begin(), values.end(), id) != values.end();
111}
112
113Result<RuntimeEditorPackage> manifestError(const char* rule, std::string message) {
114 return eve::editing::failed<RuntimeEditorPackage>(EditorStatus::Rejected, RuleId(rule), std::move(message));
115}
116
117} // namespace
118
121 const EditorExtensionRegistry& extensions,
122 const MemoryAssetDatabase& assets) const {
125 if ((manifest.features & forbidden) != HostFeature::None)
126 return manifestError("editor.runtime.forbidden-feature",
127 "Runtime editor manifest requests a developer-only feature");
128
129 RuntimeEditorPackage package;
131 package.profile.setFeatures(manifest.features);
133 for (const CommandId& id : manifest.commands) {
134 const CommandDescriptor* descriptor = commands.find(id);
135 if (!descriptor)
136 return manifestError("editor.runtime.command-not-found",
137 "Manifest command is not registered: " + id.value());
138 if (!descriptor->automationAllowed)
139 return manifestError("editor.runtime.command-not-publishable",
140 "Manifest command is not publishable: " + id.value());
141 if (!package.profile.hasFeatures(descriptor->requiredFeatures))
142 return manifestError("editor.runtime.command-feature-missing",
143 "Manifest omits a feature required by command: " + id.value());
144 package.profile.allowCommand(id);
145 package.commands.push_back(*descriptor);
146 }
147
148 HostProfile audienceProfile = HostProfile::runtimeBuilder();
149 audienceProfile.setAllowAllCommands(true);
150 for (const auto& descriptor : extensions.tools(audienceProfile))
151 if (selected(manifest.tools, descriptor.id)) package.tools.push_back(descriptor);
152 for (const ToolId& id : manifest.tools)
153 if (std::none_of(package.tools.begin(), package.tools.end(), [&](const auto& value) { return value.id == id; }))
154 return manifestError("editor.runtime.tool-not-found", "Manifest tool is unavailable: " + id.value());
155 for (const auto& descriptor : extensions.palettes(audienceProfile))
156 if (selected(manifest.palettes, descriptor.id)) package.palettes.push_back(descriptor);
157 for (const StableId& id : manifest.palettes)
158 if (std::none_of(package.palettes.begin(), package.palettes.end(),
159 [&](const auto& value) { return value.id == id; }))
160 return manifestError("editor.runtime.palette-not-found", "Manifest palette is unavailable: " + id.value());
161 for (const auto& descriptor : extensions.rules(audienceProfile))
162 if (selected(manifest.rules, descriptor.id)) package.rules.push_back(descriptor);
163 for (const RuleId& id : manifest.rules)
164 if (std::none_of(package.rules.begin(), package.rules.end(), [&](const auto& value) { return value.id == id; }))
165 return manifestError("editor.runtime.rule-not-found", "Manifest rule is unavailable: " + id.value());
166
167 std::deque<AssetGuid> pending(manifest.rootAssets.begin(), manifest.rootAssets.end());
168 std::unordered_set<AssetGuid, StrongEditorIdHash<AssetGuid>> visited;
169 while (!pending.empty()) {
170 AssetGuid current = pending.front();
171 pending.pop_front();
172 if (!visited.emplace(current).second) continue;
173 if (!assets.find(current).ok())
174 return manifestError("editor.runtime.asset-not-found", "Manifest asset is unavailable: " + current.value());
175 package.assetClosure.push_back(current);
176 for (const AssetDependency& dependency : assets.dependencies(current))
177 if (dependency.kind != DependencyKind::EditorOnly && dependency.kind != DependencyKind::Source)
178 pending.push_back(dependency.to);
179 }
180 std::sort(package.assetClosure.begin(), package.assetClosure.end());
181 return eve::editing::applied<RuntimeEditorPackage>(std::move(package));
182}
183
184} // namespace eve::editor
185
186// EditorSelection.cpp
187namespace eve::editor {
188
189Result<SelectionSnapshot> EditorSelectionService::set(std::string channel, std::vector<SelectionItem> items,
190 std::optional<SelectionItem> primary) {
191 if (channel.empty())
192 return eve::editing::failed<SelectionSnapshot>(
193 EditorStatus::Rejected, RuleId("editor.selection.channel-required"), "Selection channel is required");
194 if (primary && std::find(items.begin(), items.end(), *primary) == items.end())
195 return eve::editing::failed<SelectionSnapshot>(EditorStatus::Rejected,
196 RuleId("editor.selection.primary-missing"),
197 "Primary selection must be included in items");
199 value.channel = std::move(channel);
200 value.items = std::move(items);
201 value.primary = std::move(primary);
202 value.sequence = ++sequence_;
203 selections_.insert_or_assign(value.channel, value);
204 for (const auto& [owner, listener] : listeners_) {
205 (void)owner;
206 listener(value);
207 }
208 return eve::editing::applied<SelectionSnapshot>(std::move(value));
209}
210
211Result<SelectionSnapshot> EditorSelectionService::clear(const std::string& channel) { return set(channel, {}); }
212
213SelectionSnapshot EditorSelectionService::snapshot(const std::string& channel) const {
214 const auto found = selections_.find(channel);
215 if (found != selections_.end()) return found->second;
216 SelectionSnapshot empty;
217 empty.channel = channel;
218 return empty;
219}
220
222 if (owner.empty() || !listener)
223 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.selection.invalid-listener"),
224 "Selection listener owner and callback are required");
225 listeners_.insert_or_assign(std::move(owner), std::move(listener));
226 return eve::editing::applied<void>();
227}
228
229bool EditorSelectionService::unsubscribe(const std::string& owner) { return listeners_.erase(owner) != 0; }
230
232 if (channel.empty() || surface.empty())
233 return eve::editing::failed<EditorFocusSnapshot>(EditorStatus::Rejected, RuleId("editor.focus.invalid"),
234 "Focus channel and surface are required");
236 value.channel = std::move(channel);
237 value.surface = std::move(surface);
238 value.item = std::move(item);
239 value.sequence = ++sequence_;
240 focus_.insert_or_assign(value.channel, value);
241 return eve::editing::applied<EditorFocusSnapshot>(std::move(value));
242}
243
244EditorFocusSnapshot EditorFocusService::snapshot(const std::string& channel) const {
245 const auto found = focus_.find(channel);
246 if (found != focus_.end()) return found->second;
248 empty.channel = channel;
249 return empty;
250}
251
252} // namespace eve::editor
253
254// EditorSession.cpp
255namespace eve::editor {
256
257EditorSession::EditorSession() : context_(this) {}
258
259IEditableTarget* EditorContext::target() const { return session_ ? session_->target() : nullptr; }
260
262
263bool EditorContext::execute(std::unique_ptr<IEditCommand> command) const {
264 return session_ && session_->execute(std::move(command));
265}
266
267Result<void> EditorContext::executeChecked(std::unique_ptr<IEditCommand> command) const {
268 if (!session_)
269 return eve::editing::failed<void>(EditorStatus::Failed, RuleId("editor.context.missing-session"),
270 "Editor context has no dispatching session");
271 return session_->executeChecked(std::move(command));
272}
273
274bool EditorSession::execute(std::unique_ptr<IEditCommand> command) { return executeChecked(std::move(command)).ok(); }
275
276Result<void> EditorSession::executeChecked(std::unique_ptr<IEditCommand> command) {
277 if (!command)
278 return eve::editing::failed<void>(EditorStatus::Rejected, RuleId("editor.command.null"),
279 "Editor command must not be null");
280 Result<void> constrained = constraints_.evaluateChecked(context_, *command);
281 if (!constrained.ok()) return constrained;
282 auto appended = transactions_.append(std::move(command));
283 if (!appended.ok()) return appended;
284 return Result<void>::success(eve::Status(EditorStatus::Applied, constrained.diagnostics()));
285}
286
288 releaseTargetBinding();
289 target_ = &target;
290 boundTargetId_ = TargetId(target.targetId());
291 targetGeneration_ = nextDirectTargetGeneration_++;
292 targetLifetime_ = {};
293 targetLifetimeTracked_ = false;
294}
295
302
303void EditorSession::bindTrackedTarget(IEditableTarget& target, std::weak_ptr<void> lifetime,
304 EditorTargetCoordinator& coordinator, std::uint64_t generation) {
305 releaseTargetBinding();
306 target_ = &target;
307 boundTargetId_ = TargetId(target.targetId());
308 targetLifetime_ = std::move(lifetime);
309 targetLifetimeTracked_ = true;
310 targetGeneration_ = generation;
311 targetCoordinator_ = &coordinator;
312}
313
314void EditorSession::releaseTargetBinding() {
315 transactions_.clear();
317 if (targetCoordinator_) targetCoordinator_->detach(*this);
318 target_ = nullptr;
319 boundTargetId_ = {};
320 targetLifetime_ = {};
321 targetLifetimeTracked_ = false;
322 targetGeneration_ = 0;
323 targetCoordinator_ = nullptr;
324}
325
326void EditorSession::clearTarget() { releaseTargetBinding(); }
327
328void EditorSession::invalidateTrackedTarget(EditorTargetCoordinator& coordinator, const TargetId& target,
329 std::uint64_t generation) {
330 if (targetCoordinator_ != &coordinator || boundTargetId_ != target || targetGeneration_ != generation) return;
331 releaseTargetBinding();
332}
333
334void EditorSession::coordinatorDestroyed(EditorTargetCoordinator& coordinator) noexcept {
335 if (targetCoordinator_ != &coordinator) return;
336 try {
337 transactions_.clear();
338 } catch (...) {
339 }
340 clearRetainedPlans();
341 target_ = nullptr;
342 boundTargetId_ = {};
343 targetLifetime_ = {};
344 targetLifetimeTracked_ = false;
345 targetGeneration_ = 0;
346 targetCoordinator_ = nullptr;
347}
348
350 if (!target_) return nullptr;
351 if (targetLifetimeTracked_ && targetLifetime_.expired()) return nullptr;
352 return target_;
353}
354
357 if (!commandService_)
358 return eve::editing::failed<EditorValue>(EditorStatus::Failed, RuleId("editor.command.missing-service"),
359 "Editor session has no command service");
360
361 const CommandDescriptor* descriptor = commandService_->find(id);
362 const bool ownsTransaction = descriptor && descriptor->createsTransaction && !transactions_.isActive();
363 if (ownsTransaction) {
364 auto begun =
365 transactions_.beginTransaction(descriptor->displayName.empty() ? id.value() : descriptor->displayName);
366 if (!begun.ok()) return Result<EditorValue>::failure(begun.status());
367 }
368
369 CommandContext commandContext;
370 commandContext.session = this;
371 commandContext.profile = &hostProfile_;
372 commandContext.source = source;
373 if (IEditableTarget* currentTarget = target()) {
374 commandContext.target = TargetId(currentTarget->targetId());
375 commandContext.targetRevision = currentTarget->revision();
376 }
377
378 Result<EditorValue> result = commandService_->execute(id, commandContext, payload);
379 if (ownsTransaction) {
380 if (result.ok()) {
381 auto committed = transactions_.commitTransaction();
382 if (!committed.ok()) {
383 auto discarded = transactions_.rollbackTransaction();
384 if (!discarded.ok()) {
385 std::vector<EditorDiagnostic> diagnostics = committed.diagnostics();
386 appendProjectedDiagnostics(diagnostics, discarded.status());
387 return Result<EditorValue>::failure(eve::Status(EditorStatus::Failed, std::move(diagnostics)));
388 }
390 }
391 } else {
392 auto discarded = transactions_.rollbackTransaction();
393 if (!discarded.ok()) {
394 std::vector<EditorDiagnostic> diagnostics = result.diagnostics();
395 appendProjectedDiagnostics(diagnostics, discarded.status());
396 return Result<EditorValue>::failure(eve::Status(EditorStatus::Failed, std::move(diagnostics)));
397 }
398 }
399 }
400 return result;
401}
402
405 snapshot.session = sessionId_;
406 snapshot.host = hostProfile_.kind();
407 if (IEditableTarget* currentTarget = target()) {
408 snapshot.target = TargetId(currentTarget->targetId());
409 snapshot.targetRevision = currentTarget->revision();
410 snapshot.targetGeneration = targetGeneration_;
411 }
412 return snapshot;
413}
414
416 std::optional<Revision> expectedRevision) const {
417 if (!commandService_)
418 return eve::editing::failed<CommandPlan>(EditorStatus::Failed, RuleId("editor.command.missing-service"),
419 "Editor session has no command service");
421 request.id = id;
422 request.payload = payload;
423 request.source = source;
424 request.context = contextSnapshot();
425 request.expectedRevision = expectedRevision;
426 request.dryRun = true;
427 return commandService_->plan(request, hostProfile_);
428}
429
432 if (!commandService_)
433 return eve::editing::failed<TransactionReceipt>(EditorStatus::Failed, RuleId("editor.command.missing-service"),
434 "Editor session has no command service");
436 request.id = plan.command;
437 request.payload = payload;
438 request.source = source;
439 request.context = contextSnapshot();
440 if (request.context.target != plan.target || request.context.targetRevision != plan.baseRevision ||
441 request.context.targetGeneration != plan.targetGeneration)
442 return eve::editing::failed<TransactionReceipt>(EditorStatus::Conflict, RuleId("editor.command.stale-plan"),
443 "The live target binding no longer matches this plan");
444 request.expectedRevision = plan.baseRevision;
445 return commandService_->executePlan(request, plan, hostProfile_);
446}
447
450 TransactionReceipt receipt;
451 receipt.id = TransactionId((sessionId_.empty() ? std::string("editor.session") : sessionId_.value()) +
452 ".transaction." + std::to_string(++receiptSequence_));
453 IEditableTarget* currentTarget = target();
454 receipt.beforeRevision = currentTarget ? currentTarget->revision() : 0;
456 currentTarget = target();
457 receipt.afterRevision = currentTarget ? currentTarget->revision() : receipt.beforeRevision;
458 receipt.diagnostics = command.diagnostics();
459 receipt.state = command.ok() ? TransactionState::Committed
460 : (command.code() == EditorStatus::Conflict ? TransactionState::Conflicted
461 : TransactionState::Rejected);
462 if (!command.ok()) return Result<TransactionReceipt>::failure(command.status());
463 return Result<TransactionReceipt>::success(std::move(receipt), eve::Status(command.code(), command.diagnostics()));
464}
465
466std::vector<CommandDescriptor> EditorSession::availableCommands() const {
467 return commandService_ ? commandService_->commands(hostProfile_) : std::vector<CommandDescriptor>{};
468}
469
471 std::optional<Revision> expectedRevision) {
472 Result<CommandPlan> planned = planCommand(id, payload, source, expectedRevision);
473 if (!planned.ok()) return Result<PlanId>::failure(planned.status());
474 const PlanId planId = planned.value().id;
475 retainedPlans_.erase(std::remove_if(retainedPlans_.begin(), retainedPlans_.end(),
476 [&](const RetainedPlan& retained) { return retained.plan.id == planId; }),
477 retainedPlans_.end());
478 retainedPlans_.push_back({std::move(planned.value()), payload});
479 return eve::editing::applied<PlanId>(planId);
480}
481
483 const auto found = std::find_if(retainedPlans_.begin(), retainedPlans_.end(),
484 [&](const RetainedPlan& retained) { return retained.plan.id == id; });
485 if (found == retainedPlans_.end())
486 return eve::editing::failed<TransactionReceipt>(EditorStatus::NotFound, RuleId("editor.command.plan-not-found"),
487 "Retained command plan was not found");
489 if (result.ok()) retainedPlans_.erase(found);
490 return result;
491}
492
494 const auto found = std::find_if(retainedPlans_.begin(), retainedPlans_.end(),
495 [&](const RetainedPlan& retained) { return retained.plan.id == id; });
496 if (found == retainedPlans_.end())
497 return eve::editing::failed<void>(EditorStatus::NotFound, RuleId("editor.command.plan-not-found"),
498 "Retained command plan was not found");
499 retainedPlans_.erase(found);
500 return eve::editing::applied<void>();
501}
502
503void EditorSession::clearRetainedPlans() { retainedPlans_.clear(); }
504
506 if (documents)
507 bindDocumentServices(*documents, autosave);
508 else
510}
511
513 documentService_ = &documents;
514 autosaveService_ = autosave;
516}
517
520 documentService_ = nullptr;
521 autosaveService_ = nullptr;
522}
523
525 if (!documentService_)
526 return eve::editing::failed<DocumentSnapshot>(EditorStatus::Failed,
527 RuleId("editor.session.missing-document-service"),
528 "Editor session has no document service");
529 Result<DocumentSnapshot> snapshot = documentService_->snapshot(document);
530 if (!snapshot.ok() || !snapshot.ok()) return snapshot;
531 activeDocument_ = document;
532 autosaveElapsed_ = 0.f;
533 externalPollElapsed_ = 0.f;
534 lastAutosavedRevision_ = snapshot.value().revision.saved;
535 return snapshot;
536}
537
539 activeDocument_ = DocumentId();
540 autosaveElapsed_ = 0.f;
541 externalPollElapsed_ = 0.f;
542 lastAutosavedRevision_ = 0;
543}
544
545Result<DocumentSnapshot> EditorSession::editDocument(EditorValue content, std::optional<Revision> expectedRevision) {
546 if (!documentService_ || activeDocument_.empty())
547 return eve::editing::failed<DocumentSnapshot>(EditorStatus::Failed, RuleId("editor.session.no-active-document"),
548 "Editor session has no active document");
549 return documentService_->edit(activeDocument_, std::move(content), expectedRevision);
550}
551
553 if (!documentService_ || activeDocument_.empty())
554 return eve::editing::failed<DocumentSnapshot>(EditorStatus::Failed, RuleId("editor.session.no-active-document"),
555 "Editor session has no active document");
556 Result<SaveTicket> ticket = documentService_->requestSave(activeDocument_);
557 if (!ticket.ok()) return Result<DocumentSnapshot>::failure(ticket.status());
558 Result<DocumentSnapshot> result = documentService_->executeSave(ticket.value());
559 if (result.ok()) {
560 autosaveElapsed_ = 0.f;
561 if (!result.value().dirty()) lastAutosavedRevision_ = result.value().revision.edit;
562 }
563 return result;
564}
565
567 if (!documentService_ || !autosaveService_ || activeDocument_.empty())
568 return eve::editing::failed<StoredDocument>(EditorStatus::Failed,
569 RuleId("editor.session.missing-autosave-service"),
570 "Editor session has no active autosave service");
571 Result<DocumentSnapshot> snapshot = documentService_->snapshot(activeDocument_);
572 Result<EditorValue> content = documentService_->content(activeDocument_);
573 if (!snapshot.ok() || !snapshot.ok() || !content.ok() || !content.ok())
574 return eve::editing::failed<StoredDocument>(EditorStatus::Failed,
575 RuleId("editor.session.autosave-snapshot-failed"),
576 "Active document could not be captured for autosave");
577 Result<StoredDocument> result = autosaveService_->writeDraft(snapshot.value(), content.value());
578 if (result.ok()) {
579 lastAutosavedRevision_ = snapshot.value().revision.edit;
580 autosaveElapsed_ = 0.f;
581 }
582 return result;
583}
584
586 if (!documentService_ || activeDocument_.empty())
587 return eve::editing::failed<DocumentSnapshot>(EditorStatus::Failed, RuleId("editor.session.no-active-document"),
588 "Editor session has no active document");
589 externalPollElapsed_ = 0.f;
590 return documentService_->reconcileExternal(activeDocument_);
591}
592
593void EditorSession::setAutosaveInterval(float seconds) { autosaveInterval_ = std::max(0.f, seconds); }
594
595void EditorSession::setExternalPollInterval(float seconds) { externalPollInterval_ = std::max(0.f, seconds); }
596
598 try {
599 deactivateCurrent();
600 } catch (...) {
601 }
602 try {
603 releaseTargetBinding();
604 } catch (...) {
605 }
606}
607
609 if (!tool || tool->descriptor().id.empty()) return false;
610 for (auto* registered : tools_) {
611 if (registered == tool || registered->descriptor().id == tool->descriptor().id) return false;
612 }
613 tools_.push_back(tool);
614 return true;
615}
616
617bool EditorSession::removeTool(const std::string& id) {
618 auto it = std::find_if(tools_.begin(), tools_.end(),
619 [&](const IEditorTool* tool) { return tool && tool->descriptor().id == id; });
620 if (it == tools_.end()) return false;
621 const bool wasActive = *it == activeTool_;
622 tools_.erase(it);
623 if (wasActive) deactivateCurrent();
624 return true;
625}
626
628 tools_.clear();
629 deactivateCurrent();
630}
631
632int EditorSession::getToolCount() const { return static_cast<int>(tools_.size()); }
633
635 if (index < 0 || index >= static_cast<int>(tools_.size())) return nullptr;
636 return tools_[static_cast<size_t>(index)];
637}
638
639IEditorTool* EditorSession::findTool(const std::string& id) const {
640 for (auto* tool : tools_) {
641 if (tool && tool->descriptor().id == id) return tool;
642 }
643 return nullptr;
644}
645
646bool EditorSession::activateTool(const std::string& id) {
647 if (id.empty()) {
648 deactivateCurrent();
649 return true;
650 }
651 IEditorTool* next = findTool(id);
652 if (!next) return false;
653 if (next == activeTool_) return true;
654 deactivateCurrent();
655 next = findTool(id);
656 if (!next) return false;
657 activeTool_ = next;
658 ++toolGeneration_;
659 try {
660 activeTool_->activate(context_);
661 } catch (...) {
662 if (activeTool_ == next) {
663 activeTool_ = nullptr;
664 capturedPointerId_ = -1;
665 ++toolGeneration_;
666 }
667 throw;
668 }
669 return true;
670}
671
672std::string EditorSession::activeToolId() const { return activeTool_ ? activeTool_->descriptor().id : std::string{}; }
673
675 if (!activeTool_) return ToolResponse::ignored();
676 if (capturedPointerId_ >= 0 && event.pointerId != capturedPointerId_) {
677 return ToolResponse::ignored();
678 }
679 IEditorTool* const dispatchedTool = activeTool_;
680 const std::uint64_t generation = toolGeneration_;
681 ToolResponse response = dispatchedTool->pointerEvent(context_, event);
682 if (activeTool_ != dispatchedTool || toolGeneration_ != generation) return {response.handled, false, false};
683 if (response.capturePointer && capturedPointerId_ < 0) capturedPointerId_ = event.pointerId;
684 if (response.releasePointer && capturedPointerId_ == event.pointerId) capturedPointerId_ = -1;
685 if (event.phase == EditorPointerEvent::Phase::Cancel && capturedPointerId_ == event.pointerId) {
686 capturedPointerId_ = -1;
687 }
688 return response;
689}
690
692 return activeTool_ ? activeTool_->keyEvent(context_, event) : ToolResponse::ignored();
693}
694
696 if (activeTool_) activeTool_->update(context_, dt);
697 if (!documentService_ || activeDocument_.empty() || dt <= 0.f) return;
698
699 if (externalPollInterval_ > 0.f) {
700 externalPollElapsed_ += dt;
701 if (externalPollElapsed_ >= externalPollInterval_) (void)pollDocumentChanges();
702 }
703
704 Result<DocumentSnapshot> snapshot = documentService_->snapshot(activeDocument_);
705 if (!snapshot.ok() || !snapshot.value().dirty()) {
706 autosaveElapsed_ = 0.f;
707 return;
708 }
709 if (!autosaveService_ || autosaveInterval_ <= 0.f || snapshot.value().revision.edit == lastAutosavedRevision_)
710 return;
711 autosaveElapsed_ += dt;
712 if (autosaveElapsed_ >= autosaveInterval_) (void)autosaveDocument();
713}
714
716 if (activeTool_) activeTool_->drawOverlay(context_, overlay);
717}
718
720 if (activeTool_) activeTool_->inspect(context_, inspector);
721}
722
724 capturedPointerId_ = -1;
725 if (activeTool_) activeTool_->cancel(context_);
726}
727
728void EditorSession::deactivateCurrent() {
729 IEditorTool* current = activeTool_;
730 activeTool_ = nullptr;
731 capturedPointerId_ = -1;
732 if (!current) return;
733 ++toolGeneration_;
734
735 std::exception_ptr failure;
736 try {
737 current->cancel(context_);
738 } catch (...) {
739 failure = std::current_exception();
740 }
741 try {
742 current->deactivate(context_);
743 } catch (...) {
744 if (!failure) failure = std::current_exception();
745 }
746 if (failure) std::rethrow_exception(failure);
747}
748
749} // namespace eve::editor
LogicalId target
Value::Object payload
std::string selected
std::string descriptor
std::vector< QuestEvent > pending
bool committed
Generation generation
Definition ECS.cpp:40
std::string message
const GltfImportRequest & request
std::weak_ptr< const void > lifetime
std::string id
std::string response
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::shared_ptr< OceanGpuSpectrum > owner
double dt
std::unique_ptr< DeformMeshPresentation > presentation
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
Object::Ptr value
bool found
std::string_view source
double current
uint32_t index
std::vector< VegetationPresetCommand > commands
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:514
const std::vector< Diagnostic > & diagnostics() const noexcept
Inspect all diagnostics; this counts as checking the Result.
Definition Result.h:535
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
StatusCode code() const noexcept
Inspect the stable operation code.
Definition Result.h:307
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
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
const std::string & value() const noexcept
Returns the exact legacy or canonical compatibility spelling.
Definition Identity.h:365
bool empty() const noexcept
True when no compatibility spelling has been assigned.
Definition Identity.h:377
IEditableTarget public API.
virtual TargetId targetId() const =0
Target id.
UI-independent property access for an immutable selection snapshot.
Dotted property path (layout.size) compared and persisted as text.
Definition EditingIds.h:78
Deterministic owning value tree shared by authoring hosts.
std::vector< Value > Array
std::map< std::string, Value > Object
Autosave coordinator that never overwrites the formal document URI.
Result< StoredDocument > writeDraft(const DocumentSnapshot &snapshot, const EditorValue &content)
Write one revisioned draft under autosave://project/document.draft.
PropertyPresentation present(const PropertySchema &schema, const SelectionSnapshot &selection, const IPropertyProvider &provider) const
Read every schema property, including advanced/editor-only rows.
Document coordinator with revision-safe requestSave/executeSave sequencing.
Result< DocumentSnapshot > reconcileExternal(const DocumentId &document)
Reconcile one open document with the latest store value. Clean documents adopt external content; dirt...
Result< DocumentSnapshot > edit(const DocumentId &document, EditorValue content, std::optional< Revision > expectedRevision=std::nullopt)
Replace the working content using an optional expected edit revision.
Result< DocumentSnapshot > snapshot(const DocumentId &document) const
Return one metadata snapshot.
Result< DocumentSnapshot > executeSave(const SaveTicket &ticket)
Execute a captured save ticket without reading newer working content.
Result< EditorValue > content(const DocumentId &document) const
Return the current working content snapshot.
Result< SaveTicket > requestSave(const DocumentId &document)
Capture an exact content/revision pair for a later CAS save.
Result< void > evaluateChecked(EditorContext &context, IEditCommand &command)
Evaluate the chain and return structured allow/warning/reject diagnostics.
Registry and execution gate for UI-, script- and automation-neutral commands.
Result< EditorValue > execute(const CommandId &id, const CommandContext &context, const EditorValue &payload) const
Execute a command after payload and profile checks.
const CommandDescriptor * find(const CommandId &id) const
Return command metadata or nullptr when it is not registered.
std::vector< CommandDescriptor > commands(const HostProfile &profile) const
Return descriptors visible to a host profile.
Result< TransactionReceipt > executePlan(const CommandRequest &request, const CommandPlan &plan, const HostProfile &profile) const
Execute a plan only when its lifetime, registration, policy and input bindings remain valid.
Result< CommandPlan > plan(const CommandRequest &request, const HostProfile &profile) const
Produce a side-effect-free plan bound to the target, command generation, payload and source.
bool execute(std::unique_ptr< IEditCommand > command) const
Send a command through constraints into the active transaction.
Result< void > executeChecked(std::unique_ptr< IEditCommand > command) const
Send a command without discarding validation or transaction diagnostics.
EditorTransactions & transactions() const
Transactions.
IEditableTarget * target() const
Target currently bound to the session.
Loads game extensions and filters their descriptors for each host.
std::vector< ExtensionToolDescriptor > tools(const HostProfile &profile) const
Return tool descriptors visible to a host.
std::vector< ExtensionRuleDescriptor > rules(const HostProfile &profile) const
Return validation descriptors visible to a host.
std::vector< ExtensionPaletteDescriptor > palettes(const HostProfile &profile) const
Return palette descriptors visible to a host.
EditorFocusSnapshot snapshot(const std::string &channel) const
Read the current focus of one channel.
Result< EditorFocusSnapshot > focus(std::string channel, StableId surface, StableId item={})
Set the focused surface/item for one channel.
Result< SelectionSnapshot > clear(const std::string &channel)
Clear a channel while retaining a monotonic sequence.
std::function< void(const SelectionSnapshot &)> Listener
SelectionSnapshot snapshot(const std::string &channel) const
Read one channel, returning an empty sequence-zero snapshot when absent.
bool unsubscribe(const std::string &owner)
Remove one listener owner.
Result< void > subscribe(std::string owner, Listener listener)
Subscribe an owner callback; owner replacement and unload are deterministic.
Result< SelectionSnapshot > set(std::string channel, std::vector< SelectionItem > items, std::optional< SelectionItem > primary=std::nullopt)
Atomically replace a channel selection and optional primary item.
IEditableTarget * target() const
Return the live borrowed target, or null after an explicit or tracked unbind.
Result< StoredDocument > autosaveDocument()
Write the active dirty revision to its separate autosave draft.
void clearTarget()
Clear the active target and invalidate retained plans derived from it.
IEditorTool * findTool(const std::string &id) const
Finds tool.
void unbindDocument()
Stop coordinating the active document without closing it.
bool addTool(IEditorTool *tool)
Register a tool. Returns false for null or duplicate id/pointer.
bool execute(std::unique_ptr< IEditCommand > command)
Validate then execute a command in the active transaction.
bool removeTool(const std::string &id)
Remove a registered tool by id, deactivating it when necessary.
IEditorTool * getTool(int index) const
Returns the tool.
EditorContextSnapshot contextSnapshot() const
Capture target revision and host identity for delayed command work.
ToolResponse dispatchPointer(const EditorPointerEvent &event)
Route input to the active tool and apply pointer-capture response.
ToolResponse dispatchKey(const EditorKeyEvent &event)
Route keyboard input to the active tool.
void clearDocumentServices()
Clear document service bindings and unbind the active document.
EditorTransactions & transactions()
Transactions.
Result< void > cancelRetainedPlan(const PlanId &id)
Discard one retained plan without executing it.
void drawOverlay(IEditorOverlay &overlay)
Ask the active tool to emit viewport feedback.
Result< TransactionReceipt > executeCommandReceipt(const CommandId &id, const EditorValue &payload={}, CommandSource source=CommandSource::Api)
Execute a legacy-compatible command and return a V2 transaction receipt.
bool activateTool(const std::string &id)
Activate a registered tool by id. Empty id deactivates all tools.
void clearRetainedPlans()
Discard all retained plans, for example after replacing a document or target.
void update(float dt)
Update the active tool.
Result< void > executeChecked(std::unique_ptr< IEditCommand > command)
Validate and execute a command while preserving constraint and transaction diagnostics.
Result< CommandPlan > planCommand(const CommandId &id, const EditorValue &payload={}, CommandSource source=CommandSource::Api, std::optional< Revision > expectedRevision=std::nullopt) const
Plan a registered command without applying target mutations.
Result< DocumentSnapshot > pollDocumentChanges()
Detect external disk changes, adopting only when the document is clean.
Result< DocumentSnapshot > bindDocument(const DocumentId &document)
Select an already-open document for save, autosave and conflict polling.
Result< TransactionReceipt > executeRetainedPlan(const PlanId &id, CommandSource source=CommandSource::Api)
Execute a retained plan. Successful plans are consumed exactly once.
void inspect(IEditorInspector &inspector)
Ask the active tool to expose its configurable properties.
Result< DocumentSnapshot > editDocument(EditorValue content, std::optional< Revision > expectedRevision=std::nullopt)
Replace active working content using optional optimistic edit revision.
void cancelActiveTool()
Cancel its gesture and clear pointer capture.
void clearTools()
Remove all tools and release any pointer capture.
Result< TransactionReceipt > executePlan(const CommandPlan &plan, const EditorValue &payload={}, CommandSource source=CommandSource::Api)
Execute a previously returned plan through its registered executor.
void setAutosaveInterval(float seconds)
Configure draft cadence.
void setExternalPollInterval(float seconds)
Configure external-store polling cadence.
~EditorSession() noexcept
Editor session.
void bindTarget(IEditableTarget &target)
Bind a caller-managed editable target available to every tool callback.
Result< EditorValue > executeCommand(const CommandId &id, const EditorValue &payload={}, CommandSource source=CommandSource::Api)
Execute a registered V2 command in this session.
std::string activeToolId() const
Active tool id.
int getToolCount() const
Returns the tool count.
std::vector< CommandDescriptor > availableCommands() const
Return commands visible through this session's host profile.
Result< DocumentSnapshot > saveDocument()
Persist the current active revision through the document CAS store.
void setDocumentServices(DocumentService *documents, AutosaveService *autosave=nullptr)
Bind non-owning persistence services used by the active document.
Result< PlanId > retainPlan(const CommandId &id, const EditorValue &payload={}, CommandSource source=CommandSource::Api, std::optional< Revision > expectedRevision=std::nullopt)
Plan a command and retain its immutable payload under the returned plan id.
void bindDocumentServices(DocumentService &documents, AutosaveService *autosave=nullptr)
Bind document services; documents must outlive this binding.
Coordinates editable targets, per-target histories and domain commands.
Executes, groups, rolls back and replays arbitrary edit commands.
eve::Result< TransactionId > beginTransaction(TransactionSpec specification)
Begin a canonical checked transaction.
eve::Result< void > rollbackTransaction()
Discard the active transaction and restore its preview state.
eve::Result< void > append(std::unique_ptr< IEditCommand > command)
Stage and preview one command without discarding diagnostics.
bool isActive() const
True when active.
eve::Result< EditorTransactionRecord > commitTransaction()
Commit the active transaction and return its complete record.
Upper capability boundary for one editor host.
static HostProfile runtimeBuilder()
Safe runtime profile that denies commands unless allow-listed.
void setMaxPayloadBytes(size_t bytes)
Sets the max payload bytes.
void setAllowAllCommands(bool allow)
Sets the allow all commands.
bool hasFeatures(HostFeature required) const
True when features.
void setFeatures(HostFeature features)
Sets the features.
void allowCommand(CommandId id)
Allow command.
HostKind kind() const
Kind.
UI-independent property editor used by tools to expose settings.
Sink implemented by a 2D or 3D viewport to render tool feedback.
Protocol implemented by every editor tool.
Definition EditorTool.h:110
virtual void update(EditorContext &context, float dt)
Per-frame hook for an active tool.
Definition EditorTool.h:140
virtual void inspect(EditorContext &context, IEditorInspector &inspector)
Expose configurable settings through a host-provided inspector.
Definition EditorTool.h:152
virtual void drawOverlay(EditorContext &context, IEditorOverlay &overlay)
Emit renderer-independent feedback for the active viewport.
Definition EditorTool.h:146
virtual ToolResponse pointerEvent(EditorContext &context, const EditorPointerEvent &event)
Handle normalized pointer input.
Definition EditorTool.h:124
virtual ToolResponse keyEvent(EditorContext &context, const EditorKeyEvent &event)
Handle normalized keyboard input.
Definition EditorTool.h:132
virtual void activate(EditorContext &context)
Called exactly once when this tool becomes active.
Definition EditorTool.h:119
virtual void cancel(EditorContext &context)
Cancel the active gesture while keeping the tool selected.
Definition EditorTool.h:158
virtual const ToolDescriptor & descriptor() const =0
Stable tool identity and presentation metadata.
Thread-neutral in-memory asset index used by editor hosts and tests.
Result< AssetRecord > find(const AssetGuid &guid) const
Find one asset by stable GUID.
std::vector< AssetDependency > dependencies(const AssetGuid &guid, bool incoming=false) const
Query outgoing or incoming dependencies for one asset.
Result< RuntimeEditorPackage > publish(const RuntimeEditorManifest &manifest, const EditorCommandService &commands, const EditorExtensionRegistry &extensions, const MemoryAssetDatabase &assets) const
Build a deny-by-default runtime package.
PropertySetMode
PropertySetMode public API.
CommandSource
Source that initiated an authoring command.
Result< void > validatePropertyValue(const PropertyDescriptor &descriptor, const Value &value)
Validate property value.
constexpr bool hasPropertyFlag(PropertyFlag value, PropertyFlag flag)
True when property flag.
eve::editing::Value EditorValue
Compatibility alias for the UI-independent authoring value tree.
Definition EditorValue.h:8
eve::editing::PropertyPath PropertyPath
Definition EditorIds.h:37
eve::editing::SelectionItem SelectionItem
Stable item stored in a selection snapshot.
void appendProjectedDiagnostics(std::vector< eve::Diagnostic > &destination, const eve::Status &status)
Append diagnostics while assembling a new immutable Result status.
eve::editing::CommandId CommandId
Definition EditorIds.h:30
eve::editing::TargetId TargetId
Definition EditorIds.h:29
eve::editing::RuleId RuleId
Definition EditorIds.h:32
eve::editing::SelectionSnapshot SelectionSnapshot
Immutable multi-selection captured for property and command work.
HostFeature
Coarse host features used to discover and gate editor extensions.
eve::editing::TransactionId TransactionId
Definition EditorIds.h:34
eve::editing::PropertySetMode PropertySetMode
eve::editing::DocumentId DocumentId
Definition EditorIds.h:40
eve::editing::PropertySchema PropertySchema
CommandPlan public API.
CommandRequest public API.
ContextSnapshot public API.
FocusSnapshot public API.
PropertyDescriptor public API.
EVENGINE_API_PLATFORM public API.
std::vector< PropertyDescriptor > properties
SelectionSnapshot public API.
TransactionReceipt public API.
std::vector< Diagnostic > diagnostics
Directed dependency between two stable asset identities.
Immutable execution context captured for a synchronous command.
Presentation and execution metadata for a registered command.
Keyboard input normalized by the editor host.
Definition EditorTool.h:40
Pointer input normalized by an editor viewport adapter.
Definition EditorTool.h:20
Immutable presentation model consumed by developer or game UI.
Explicit publish allow-list for a player-facing editor build.
Resolved editor package embedded into a game build.
std::vector< CommandDescriptor > commands
std::vector< ExtensionToolDescriptor > tools
std::vector< ExtensionRuleDescriptor > rules
std::vector< ExtensionPaletteDescriptor > palettes
Result returned by a tool after processing input.
Definition EditorTool.h:50
static ToolResponse ignored()
Ignored.
Definition EditorTool.h:56