载入中...
搜索中...
未找到
UiEditorModule.cpp
浏览该文件的文档.
2#include <cstdint>
3#include <simplesquirrel/simplesquirrel.hpp>
4#include <string>
5#include <utility>
7#include "common/Value.h"
10#include "ui/UIHost.h"
11#include "ui/UISystem.h"
15
16// UiEditorModule.cpp
17namespace eve::ui_editor {
18
20
22
23void UiEditorModule::expose(ssq::Table& table) {
24 auto module = table.addClass(name, UiEditorModule::create, false);
27}
28void UiEditorModule::expose(ssq::Class&) {}
29
30} // namespace eve::ui_editor
31
32// UiThemeEditor.cpp
33namespace eve::ui_editor {
34namespace {
35
36template <class T = void>
37ui_editing::Result<T> editorError(ui_editing::EditorStatus status, std::string rule, std::string message) {
38 return eve::editing::failed<T>(status, ui_editing::RuleId(std::move(rule)), std::move(message));
39}
40
41ui_editing::UiThemeBasePreset presetFromName(const std::string& name) {
42 if (name == "light") return ui_editing::UiThemeBasePreset::Light;
44}
45
46} // namespace
47
49 : target_(std::move(targetId)), authority_(&target_), transactions_(&authority_) {
50 auto previewed = refreshPreview();
51 if (!previewed.ok()) previewed.ignore("ui theme editor keeps an empty preview when the seeded catalog is rejected");
52}
53
55 editor::EditorWorkspace candidate = workspace;
56 struct Panel {
57 const char* id;
58 const char* title;
59 const char* region;
60 const char* context;
61 int order;
62 };
63 constexpr Panel panels[] = {
64 {"ui.themes", "Themes", "left", "list", 100},
65 {"ui.preview", "Theme Preview", "center", "preview", 100},
66 {"ui.inspector", "Theme Inspector", "right", "inspector", 100},
67 };
68 for (const auto& panel : panels) {
69 if (!candidate.registerPanel(panel.id, panel.title, panel.region, panel.order) ||
70 !candidate.setPanelCapability(panel.id, "ui.theme") || !candidate.setPanelContext(panel.id, panel.context))
71 return editorError(ui_editing::EditorStatus::Rejected, "editor.ui-theme.workspace-conflict",
72 "Could not install the UI theme workspace composition");
73 }
74 if (!candidate.activatePanel("ui.preview"))
75 return editorError(ui_editing::EditorStatus::Rejected, "editor.ui-theme.workspace-activate",
76 "Could not activate the UI theme preview panel");
77 workspace = std::move(candidate);
78 return eve::editing::applied<void>();
79}
80
81editor::SelectionSnapshot UiThemeEditor::selection() const {
83 snapshot.channel = "ui-theme";
85 item.domain = editor::SelectionDomain::Asset;
86 item.target = editor::TargetId(target_.targetId());
87 item.item = editor::StableId(selectedId_);
88 item.type = "ui.theme";
89 snapshot.items.push_back(item);
90 snapshot.primary = item;
91 return snapshot;
92}
93
95 std::string label) {
96 if (!operation.ok()) return ui_editing::Result<void>::failure(operation.status());
98 spec.id = editor::TransactionId("ui.theme.tx." + std::to_string(++txSequence_));
99 spec.label = std::move(label);
100 spec.target = editor::TargetId(target_.targetId());
101 spec.baseRevision = target_.revision();
102 auto begun = transactions_.begin(std::move(spec));
103 if (!begun.ok()) return editorError(begun.code(), "editor.ui-theme.begin", "Could not begin the theme transaction");
104 auto appended = transactions_.append(std::move(operation).takeValue());
105 if (!appended.ok()) {
106 auto discarded = transactions_.discard();
107 if (!discarded.ok()) discarded.ignore("pending theme transaction already inactive");
108 return ui_editing::Result<void>::failure(appended.status());
109 }
110 auto committed = transactions_.commit();
111 if (!committed.ok()) return ui_editing::Result<void>::failure(committed.status());
112 return refreshPreview();
113}
114
115ui_editing::Result<void> UiThemeEditor::refreshPreview() {
116 preview_ = previews_.build(target_, ui_editing::ObjectId(selectedId_), target_.revision());
117 if (preview_.status != ui_editing::EditorStatus::Applied)
118 return editorError(preview_.status, "editor.ui-theme.preview", "Could not rebuild the theme preview");
119 return eve::editing::applied<void>();
120}
121
123 auto asset = target_.theme(ui_editing::ObjectId(id));
124 if (!asset.ok()) return ui_editing::Result<void>::failure(asset.status());
125 selectedId_ = std::move(id);
126 return refreshPreview();
127}
128
129ui_editing::Result<void> UiThemeEditor::createFromPreset(std::string id, std::string name, std::string preset) {
130 if (preset != "dark" && preset != "light")
131 return editorError(ui_editing::EditorStatus::Rejected, "editor.ui-theme.preset-source",
132 "New themes must be created from dark or light");
133 auto created =
134 commit(target_.makeCreateFromPreset(ui_editing::ObjectId(id), std::move(name), presetFromName(preset)),
135 "Create theme");
136 if (!created.ok()) return created;
137 selectedId_ = std::move(id);
138 return refreshPreview();
139}
140
142 auto duplicated =
143 commit(target_.makeDuplicate(ui_editing::ObjectId(selectedId_), ui_editing::ObjectId(id), std::move(name)),
144 "Duplicate theme");
145 if (!duplicated.ok()) return duplicated;
146 selectedId_ = std::move(id);
147 return refreshPreview();
148}
149
151 auto deleted = commit(target_.makeDelete(ui_editing::ObjectId(selectedId_)), "Delete theme");
152 if (!deleted.ok()) return deleted;
153 selectedId_ = target_.activeId().value();
154 if (selectedId_.empty() && !target_.themes().empty()) selectedId_ = target_.themes().front().id.value();
155 return refreshPreview();
156}
157
159 auto activated = commit(target_.makeSetActive(ui_editing::ObjectId(selectedId_)), "Activate theme");
160 if (!activated.ok()) return activated;
161 auto published = publisher_.publish(target_);
162 if (!published.ok()) return published;
163 return refreshPreview();
164}
165
167 return commit(target_.makeResetToBase(ui_editing::ObjectId(selectedId_)), "Reset theme");
168}
169
171 return commit(
172 target_.makeSet(selection(), ui_editing::PropertyPath(path), value, ui_editing::PropertySetMode::Absolute),
173 "Set theme token");
174}
175
177 auto undone = transactions_.undo();
178 if (!undone.ok()) return undone;
179 if (!target_.theme(ui_editing::ObjectId(selectedId_)).ok() && !target_.themes().empty())
180 selectedId_ = target_.themes().front().id.value();
181 auto previewed = refreshPreview();
182 if (!previewed.ok()) return ui_editing::Result<editor::TransactionReceipt>::failure(previewed.status());
183 return undone;
184}
185
187 auto redone = transactions_.redo();
188 if (!redone.ok()) return redone;
189 auto previewed = refreshPreview();
190 if (!previewed.ok()) return ui_editing::Result<editor::TransactionReceipt>::failure(previewed.status());
191 return redone;
192}
193
195 if (hostName.empty())
196 return editorError(ui_editing::EditorStatus::Rejected, "editor.ui-theme.host",
197 "Preview host name must not be empty");
198 if (preview_.status != ui_editing::EditorStatus::Applied || preview_.documentRevision != target_.revision()) {
199 auto previewed = refreshPreview();
200 if (!previewed.ok()) return previewed;
201 }
203 if (!host)
204 return editorError(ui_editing::EditorStatus::NotFound, "editor.ui-theme.host-missing",
205 "Preview UI host was not found: " + hostName);
206 host->get().setThemeOverride(preview_.theme);
207 return eve::editing::applied<void>();
208}
209
210const ui_editing::UiThemeAsset* UiThemeEditor::themeAt(int index) const {
211 if (index < 0 || static_cast<std::size_t>(index) >= target_.themes().size()) return nullptr;
212 return &target_.themes()[static_cast<std::size_t>(index)];
213}
214
215std::string UiThemeEditor::themeId(int index) const {
216 const auto* asset = themeAt(index);
217 return asset ? asset->id.value() : std::string{};
218}
219std::string UiThemeEditor::themeName(int index) const {
220 const auto* asset = themeAt(index);
221 return asset ? asset->name : std::string{};
222}
224 const auto* asset = themeAt(index);
225 return asset && asset->id.value() == selectedId_;
226}
228 const auto* asset = themeAt(index);
229 return asset && asset->id == target_.activeId();
230}
231
232float UiThemeEditor::getColorChannel(const std::string& path, int channel) const {
233 auto value = target_.read(selection(), ui_editing::PropertyPath(path));
234 if (value.state != ui_editing::PropertyReadState::Value) return 0.0f;
235 const auto* array = value.value.getIf<ui_editing::EditorValue::Array>();
236 if (!array || channel < 0 || static_cast<std::size_t>(channel) >= array->size()) return 0.0f;
237 const auto* number = (*array)[static_cast<std::size_t>(channel)].getIf<double>();
238 return number ? static_cast<float>(*number) : 0.0f;
239}
240
241float UiThemeEditor::getFloat(const std::string& path) const {
242 auto value = target_.read(selection(), ui_editing::PropertyPath(path));
243 if (value.state != ui_editing::PropertyReadState::Value) return 0.0f;
244 const auto* number = value.value.getIf<double>();
245 return number ? static_cast<float>(*number) : 0.0f;
246}
247
248} // namespace eve::ui_editor
249
250// UiThemeEditorScriptBindings.cpp
251namespace eve::ui_editor {
252namespace {
253
254constexpr const char* kBindingSource = "editor.ui.theme.squirrel";
255
256class ScriptUiThemeEditor {
257public:
258 explicit ScriptUiThemeEditor(std::string targetId) : editor_(std::move(targetId)) {}
259
260 UiThemeEditor& editor() noexcept { return editor_; }
261 const UiThemeEditor& editor() const noexcept { return editor_; }
262
263private:
264 UiThemeEditor editor_;
265};
266
267} // namespace
268
269void exposeUiThemeEditorScriptBindings(ssq::Table& table, ssq::Class& moduleClass) {
270 const editor::ScriptBind bind{table.getHandle(), kBindingSource};
271 auto themeEditor = editor::addScriptClass<ScriptUiThemeEditor>(table, "UiThemeEditor");
272
273 editor::registerEditorWorkspace<ScriptUiThemeEditor>(themeEditor, bind,
274 "theme editor and workspace must not be null");
275 themeEditor.addFunc("selectTheme", [bind](ScriptUiThemeEditor* self, const std::string& id) {
276 return bind.checked(self, "theme editor must not be null", [&] { return self->editor().selectTheme(id); });
277 });
278 themeEditor.addFunc("createFromPreset", [bind](ScriptUiThemeEditor* self, const std::string& id,
279 const std::string& name, const std::string& preset) {
280 return bind.checked(self, "theme editor must not be null",
281 [&] { return self->editor().createFromPreset(id, name, preset); });
282 });
283 themeEditor.addFunc("duplicateSelected",
284 [bind](ScriptUiThemeEditor* self, const std::string& id, const std::string& name) {
285 return bind.checked(self, "theme editor must not be null",
286 [&] { return self->editor().duplicateSelected(id, name); });
287 });
288 themeEditor.addFunc("deleteSelected", [bind](ScriptUiThemeEditor* self) {
289 return bind.checked(self, "theme editor must not be null", [&] { return self->editor().deleteSelected(); });
290 });
291 themeEditor.addFunc("setActiveSelected", [bind](ScriptUiThemeEditor* self) {
292 return bind.checked(self, "theme editor must not be null", [&] { return self->editor().setActiveSelected(); });
293 });
294 themeEditor.addFunc("resetSelectedToBase", [bind](ScriptUiThemeEditor* self) {
295 return bind.checked(self, "theme editor must not be null",
296 [&] { return self->editor().resetSelectedToBase(); });
297 });
298 themeEditor.addFunc(
299 "setColor", [bind](ScriptUiThemeEditor* self, const std::string& path, float r, float g, float b, float a) {
300 return bind.checked(self, "theme editor must not be null", [&] {
301 return self->editor().setToken(
302 path, ui_editing::EditorValue::Array{static_cast<double>(r), static_cast<double>(g),
303 static_cast<double>(b), static_cast<double>(a)});
304 });
305 });
306 themeEditor.addFunc("setFloat", [bind](ScriptUiThemeEditor* self, const std::string& path, float value) {
307 return bind.checked(self, "theme editor must not be null",
308 [&] { return self->editor().setToken(path, static_cast<double>(value)); });
309 });
310 themeEditor.addFunc("applyPreviewHost", [bind](ScriptUiThemeEditor* self, const std::string& hostName) {
311 return bind.checked(self, "theme editor must not be null",
312 [&] { return self->editor().applyPreviewHost(hostName); });
313 });
314 editor::registerEditorHistory<ScriptUiThemeEditor>(themeEditor, bind, "theme editor must not be null");
315 script::bindNullSafe<ScriptUiThemeEditor>(
316 themeEditor, "getPreviewRevision",
317 [](ScriptUiThemeEditor& self) { return static_cast<int>(self.editor().previewRevision()); }, 0);
318 script::bindNullSafe<ScriptUiThemeEditor>(
319 themeEditor, "getSelectedId", [](ScriptUiThemeEditor& self) { return self.editor().selectedId(); },
320 std::string{});
321 script::bindNullSafe<ScriptUiThemeEditor>(
322 themeEditor, "getActiveId", [](ScriptUiThemeEditor& self) { return self.editor().activeId(); }, std::string{});
323 script::bindNullSafe<ScriptUiThemeEditor>(
324 themeEditor, "getPreviewRuntimeName",
325 [](ScriptUiThemeEditor& self) { return self.editor().previewRuntimeName(); }, std::string{});
326 script::bindNullSafe<ScriptUiThemeEditor>(
327 themeEditor, "getThemeCount", [](ScriptUiThemeEditor& self) { return self.editor().themeCount(); }, 0);
328 themeEditor.addFunc("getThemeId", [](ScriptUiThemeEditor* self, int index) {
329 return self ? self->editor().themeId(index) : std::string{};
330 });
331 themeEditor.addFunc("getThemeName", [](ScriptUiThemeEditor* self, int index) {
332 return self ? self->editor().themeName(index) : std::string{};
333 });
334 themeEditor.addFunc("getThemeSelected", [](ScriptUiThemeEditor* self, int index) {
335 return self && self->editor().isThemeSelected(index);
336 });
337 themeEditor.addFunc("getThemeActive", [](ScriptUiThemeEditor* self, int index) {
338 return self && self->editor().isThemeActive(index);
339 });
340 themeEditor.addFunc("getColorR", [](ScriptUiThemeEditor* self, const std::string& path) {
341 return self ? self->editor().getColorChannel(path, 0) : 0.0f;
342 });
343 themeEditor.addFunc("getColorG", [](ScriptUiThemeEditor* self, const std::string& path) {
344 return self ? self->editor().getColorChannel(path, 1) : 0.0f;
345 });
346 themeEditor.addFunc("getColorB", [](ScriptUiThemeEditor* self, const std::string& path) {
347 return self ? self->editor().getColorChannel(path, 2) : 0.0f;
348 });
349 themeEditor.addFunc("getColorA", [](ScriptUiThemeEditor* self, const std::string& path) {
350 return self ? self->editor().getColorChannel(path, 3) : 1.0f;
351 });
352 themeEditor.addFunc("getFloat", [](ScriptUiThemeEditor* self, const std::string& path) {
353 return self ? self->editor().getFloat(path) : 0.0f;
354 });
355 // Additive structured snapshot; atomic getters above remain the compatibility surface.
356 themeEditor.addFunc("getState", [vm = table.getHandle()](ScriptUiThemeEditor* self) {
357 if (!self) {
360 {}, {}, kBindingSource)));
361 }
362 const auto& editor = self->editor();
366 {"selectedId", Value(editor.selectedId())},
367 {"activeId", Value(editor.activeId())},
368 {"previewRuntimeName", Value(editor.previewRuntimeName())},
369 {"revision", Value(static_cast<std::int64_t>(editor.revision()))},
370 {"previewRevision", Value(static_cast<std::int64_t>(editor.previewRevision()))},
371 {"themeCount", Value(editor.themeCount())},
372 }));
373 });
374
375 editor::registerEditorOwnedCreate<ScriptUiThemeEditor, UiEditorModule>(moduleClass, bind,
376 "theme catalog id must not be empty");
377}
378
379} // namespace eve::ui_editor
ActionParameterOperation operation
std::string title
bool committed
HSQUIRRELVM vm
Definition ECS.cpp:38
std::string name
Definition ECS.cpp:154
ScriptFieldRegion region
std::string message
tensor::Graph g
Definition GpuGraph.cpp:7
wgpu::PopErrorScopeStatus status
double r
std::string label
std::string id
Snapshot snapshot
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< std::int32_t > order
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::string path
Definition PlayHost.cpp:111
std::uint32_t targetId
Object::Ptr value
double number
int created
Per-translation-unit VM + diagnostic-source helper for Squirrel bindings.
UIHostHandle host
Squirrel adapter for the UI theme editor.
UI-neutral named Theme catalog editor: workspace, gallery preview, undo.
uint32_t index
Owning, renderer-independent dynamic values.
const VegetationPresetContext & context
Squirrel adapters for WorkspaceLayoutShell.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::uint64_t revision() const override
Return the current revision.
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
const T * getIf() const
Return an immediately borrowed typed value.
Composition model shared by project-specific developer and runtime editors.
bool setPanelContext(const std::string &id, const std::string &context)
Attach a semantic input context such as scene, graph, or timeline.
Result< WorkspacePanelDescriptor > registerPanel(WorkspacePanelDescriptor descriptor)
Register a checked owning panel descriptor.
Result< WorkspacePanelDescriptor > activatePanel(const StableId &id)
Activate a visible panel with structured not-found/rejected results.
bool setPanelCapability(const std::string &id, const std::string &capability)
Attach a capability requirement used by the host when filtering panels.
Result< TransactionReceipt > commit() override
Preflight and commit all active operations through the authority.
Result< TransactionId > begin(TransactionSpec specification) override
Begin a transaction with a stable id and base revision.
Result< TransactionReceipt > undo() override
Compensate the most recent committed transaction.
Result< void > discard() override
Discard the active, not-yet-committed operation list.
Result< TransactionReceipt > redo() override
Reapply the most recently compensated transaction.
Result< void > append(DomainOperation operation) override
Append an operation to the active transaction without applying it.
Editor facade binder: common script::BindContext plus history/owned-create helpers.
static eve::OptionalRef< UIHost > resolve(UIHostHandle handle) noexcept
Resolves a UI host handle with ECS generation checking.
Definition UIHost.cpp:62
static UIHostHandle findHost(const std::string &name)
Lookup by Meta.name across the UIHost View.
Result< DomainOperation > makeDelete(const ObjectId &id) const
Make delete.
Definition UiTheme.cpp:276
Result< DomainOperation > makeSetActive(const ObjectId &id) const
Make set active.
Definition UiTheme.cpp:292
Result< DomainOperation > makeResetToBase(const ObjectId &id) const
Make reset to base.
Definition UiTheme.cpp:301
const ObjectId & activeId() const noexcept
Active publication id; empty only if the catalog failed to seed.
Definition UiTheme.h:93
TargetId targetId() const override
Target id.
Definition UiTheme.h:72
Result< UiThemeAsset > theme(const ObjectId &id) const
Copy one named theme, or NotFound.
Definition UiTheme.cpp:143
PropertyReadResult read(const SelectionSnapshot &selection, const PropertyPath &path) const override
Reads .
Result< DomainOperation > makeCreateFromPreset(const ObjectId &id, std::string name, UiThemeBasePreset preset) const
Make create from preset.
Definition UiTheme.cpp:212
Result< DomainOperation > makeSet(const SelectionSnapshot &selection, const PropertyPath &path, const EditorValue &value, PropertySetMode mode) const override
Make set.
const std::vector< UiThemeAsset > & themes() const noexcept
Borrow authored themes in catalog order.
Definition UiTheme.h:91
Result< DomainOperation > makeDuplicate(const ObjectId &source, const ObjectId &id, std::string name) const
Make duplicate.
Definition UiTheme.cpp:237
UiThemePreviewSnapshot build(const UiThemeCatalogTarget &catalog, const ObjectId &themeId, Revision expectedRevision) const
Copy tokens for themeId when expectedRevision matches the catalog.
Result< void > publish(const UiThemeCatalogTarget &catalog) const
Replace the process global theme with the catalog's active asset.
Composition adapter that exposes the script-owned UiThemeEditor factory.
UiEditorModule()
Constructs a UiEditorModule.
ui_editing::Result< void > duplicateSelected(std::string id, std::string name)
ui_editing::Result< void > deleteSelected()
std::string themeId(int index) const
Theme id.
ui_editing::Result< void > configureWorkspace(editor::EditorWorkspace &workspace) const
Install Themes / Preview / Inspector panels.
ui_editing::Result< void > setToken(const std::string &path, const ui_editing::EditorValue &value)
ui_editing::Result< void > setActiveSelected()
float getFloat(const std::string &path) const
Returns the float.
bool isThemeActive(int index) const
True when theme active.
ui_editing::Result< editor::TransactionReceipt > redo()
ui_editing::Result< void > applyPreviewHost(const std::string &hostName)
Copy the selected theme onto a live UIHost without changing globalTheme.
ui_editing::Result< void > createFromPreset(std::string id, std::string name, std::string preset)
UiThemeEditor(std::string targetId)
Construct a catalog seeded with built-in Dark and Light assets.
ui_editing::Result< void > resetSelectedToBase()
std::string themeName(int index) const
Theme name.
ui_editing::Result< editor::TransactionReceipt > undo()
float getColorChannel(const std::string &path, int channel) const
Returns the color channel.
bool isThemeSelected(int index) const
True when theme selected.
ui_editing::Result< void > selectTheme(std::string id)
eve::editing::StableId StableId
Definition EditorIds.h:36
eve::editing::TargetId TargetId
Definition EditorIds.h:29
eve::editing::TransactionId TransactionId
Definition EditorIds.h:34
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
UiThemeBasePreset
Base preset used when resetting a named theme asset.
Definition UiTheme.h:44
editing::Status EditorStatus
Definition UiDocument.h:45
void exposeUiThemeEditorScriptBindings(ssq::Table &table, ssq::Class &moduleClass)
Expose the script-owned UiThemeEditor factory on UiEditorModule.
void exposeWorkspaceLayoutShellBindings(ssq::Table &table, ssq::Class &moduleClass)
Expose WorkspaceLayoutShell helpers on UiEditorModule.
SelectionItem public API.
SelectionSnapshot public API.
TransactionSpec public API.
One named, fully snapshotted Theme asset.
Definition UiTheme.h:47