载入中...
搜索中...
未找到
ReflectedPropertyModel.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <cstdlib>
5#include <string_view>
6#include <utility>
7
8namespace eve::property_access {
9namespace {
10
11using eve::Value;
12
13PropertyKind propertyKind(const ReflectedMember &member) {
14 const std::string editor = member.attrString("editor");
15 if (editor == "combo" && !member.attrOptions("options").empty()) return PropertyKind::Enum;
16 if (editor == "color") return PropertyKind::Color;
17 if (editor == "vec2") return PropertyKind::Vec2;
18 if (editor == "vec3") return PropertyKind::Vec3;
19 if (editor == "vec4") return PropertyKind::Vec4;
20 switch (member.value.kind) {
21 case ReflectedValueKind::Bool: return PropertyKind::Bool;
22 case ReflectedValueKind::Integer: return PropertyKind::Integer;
23 case ReflectedValueKind::Float: return PropertyKind::Number;
24 case ReflectedValueKind::String: return PropertyKind::String;
25 case ReflectedValueKind::Array: return PropertyKind::Array;
26 case ReflectedValueKind::Table: return PropertyKind::Map;
27 case ReflectedValueKind::Instance: return PropertyKind::ObjectRef;
28 case ReflectedValueKind::None:
29 case ReflectedValueKind::Other: return PropertyKind::ReadOnlyText;
30 }
31 return PropertyKind::Auto;
32}
33
34bool editableKind(PropertyKind kind) {
35 switch (kind) {
50 return true;
54 return false;
55 }
56 return false;
57}
58
59bool scalar(ReflectedValueKind kind) {
60 return kind == ReflectedValueKind::Bool || kind == ReflectedValueKind::Integer ||
61 kind == ReflectedValueKind::Float || kind == ReflectedValueKind::String;
62}
63
64std::string ownerClass(const Runtime &runtime, const std::string &className,
65 const std::string &memberName) {
66 // Prefer the most-base class that still declares the member so inherited
67 // fields group under their defining class even when the leaf also lists them.
68 std::string owner;
69 std::string current = className;
70 while (!current.empty()) {
71 const ReflectedClass *reflected = runtime.reflectedClass(current);
72 if (!reflected) break;
73 const auto found = std::find_if(reflected->members.begin(), reflected->members.end(),
74 [&memberName](const ReflectedMember &member) {
75 return member.name == memberName;
76 });
77 if (found != reflected->members.end()) owner = current;
78 current = reflected->base;
79 }
80 return owner.empty() ? className : owner;
81}
82
83PropertyFlag propertyFlags(const ReflectedMember &member, PropertyKind kind) {
85 if (!editableKind(kind) || member.attrBool("read_only") || member.attrBool("readonly"))
87 if (member.attrBool("advanced")) flags = flags | PropertyFlag::Advanced;
88 if (member.attrBool("editor_only")) flags = flags | PropertyFlag::EditorOnly;
89 if (member.attrBool("transient")) flags = flags | PropertyFlag::Transient;
90 if (member.attrBool("dangerous")) flags = flags | PropertyFlag::Dangerous;
91 return flags;
92}
93
94ReflectedValue toReflectedValue(const Value &value) {
95 ReflectedValue result;
96 if (const auto *boolean = value.getIf<bool>()) {
97 result.kind = ReflectedValueKind::Bool;
98 result.boolean = *boolean;
99 } else if (const auto *integer = value.getIf<std::int64_t>()) {
100 result.kind = ReflectedValueKind::Integer;
101 result.integer = *integer;
102 } else if (const auto *number = value.getIf<double>()) {
103 result.kind = ReflectedValueKind::Float;
104 result.floating = *number;
105 } else if (const auto *text = value.getIf<std::string>()) {
106 result.kind = ReflectedValueKind::String;
107 result.text = *text;
108 }
109 return result;
110}
111
112Value scalarValue(const ReflectedValue &value) {
113 switch (value.kind) {
114 case ReflectedValueKind::Bool: return Value(value.boolean);
115 case ReflectedValueKind::Integer: return Value(value.integer);
116 case ReflectedValueKind::Float: return Value(value.floating);
117 case ReflectedValueKind::String: return Value(value.text);
118 default: return {};
119 }
120}
121
122const char *scriptValidationCode(std::string_view sharedCode) {
123 if (sharedCode == "property_access.property.read-only") return "property_access.script.read-only";
124 if (sharedCode == "property_access.property.type") return "property_access.script.type";
125 if (sharedCode == "property_access.property.choice") return "property_access.script.choice";
126 if (sharedCode == "property_access.property.finite") return "property_access.script.finite";
127 if (sharedCode == "property_access.property.minimum") return "property_access.script.minimum";
128 if (sharedCode == "property_access.property.maximum") return "property_access.script.maximum";
129 if (sharedCode == "property_access.property.arity") return "property_access.script.arity";
130 return "property_access.script.validation";
131}
132
133Result<void> validationFailure(Result<void> validation) {
134 std::string rule;
135 std::string message;
136 if (const Diagnostic *error = validation.error()) {
137 rule = std::string(diagnosticRule(*error));
138 message = error->message();
139 }
140 return rejected(scriptValidationCode(rule), std::move(message));
141}
142
143} // namespace
144
146 struct Entry {
147 std::uint64_t id = 0;
149 };
150 std::uint64_t nextId = 1;
151 std::vector<Entry> entries;
152};
153
155 : runtime_(&runtime), instance_(std::move(instance)), observers_(std::make_shared<ObserverState>()) {
157 refresh();
158}
159
161
163 schema_ = {};
164 cachedValues_.clear();
165 if (!runtime_ || instance_.getType() != ssq::Type::INSTANCE) return;
166 schema_.typeId = runtime_->classNameOf(instance_);
167 for (const ReflectedMember &member : runtime_->reflectInstance(instance_)) {
168 if (member.method) continue;
170 descriptor.path = member.name;
171 descriptor.displayName = member.attrString("label", member.name);
172 descriptor.description = member.attrString("tooltip", member.attrString("description"));
173 descriptor.category = member.attrString("category", ownerClass(*runtime_, schema_.typeId, member.name));
174 descriptor.kind = propertyKind(member);
175 descriptor.flags = propertyFlags(member, descriptor.kind);
176 descriptor.defaultValue = convertValue(member.name, member.value);
177 descriptor.numeric.minimum =
178 member.findAttribute("min") ? std::optional<double>(member.attrFloat("min")) : std::nullopt;
179 descriptor.numeric.maximum =
180 member.findAttribute("max") ? std::optional<double>(member.attrFloat("max")) : std::nullopt;
181 descriptor.numeric.step =
182 member.findAttribute("step") ? std::optional<double>(member.attrFloat("step")) : std::nullopt;
183 descriptor.numeric.units = member.attrString("units");
184 descriptor.numeric.precision = static_cast<int>(member.attrFloat("precision", 3.f));
185 descriptor.choices = member.attrOptions("options");
186 descriptor.presenterHint = member.attrString("editor");
187 schema_.properties.push_back(std::move(descriptor));
188 }
189 ++revision_;
190}
191
192Value ReflectedPropertyModel::convertValue(const std::string &path, const ReflectedValue &value) const {
193 switch (value.kind) {
194 case ReflectedValueKind::Bool: return Value(value.boolean);
195 case ReflectedValueKind::Integer: return Value(value.integer);
196 case ReflectedValueKind::Float: return Value(value.floating);
197 case ReflectedValueKind::String: return Value(value.text);
198 case ReflectedValueKind::Array: {
200 const std::size_t count = runtime_->arraySize(instance_, path);
201 result.reserve(count);
202 for (std::size_t index = 0; index < count; ++index) {
203 const ReflectedValue entry = runtime_->arrayGet(instance_, path, index);
204 if (scalar(entry.kind))
205 result.push_back(scalarValue(entry));
206 else
207 result.emplace_back();
208 }
209 return Value(std::move(result));
210 }
211 case ReflectedValueKind::Table: {
213 for (const std::string &key : runtime_->tableKeys(instance_, path)) {
214 const ReflectedValue entry = runtime_->tableGet(instance_, path, key);
215 if (scalar(entry.kind))
216 result.emplace(key, scalarValue(entry));
217 else
218 result.emplace(key, Value());
219 }
220 return Value(std::move(result));
221 }
222 case ReflectedValueKind::Instance: {
223 const ssq::Object nested = runtime_->readObjectProperty(instance_, path);
224 return Value(runtime_->classNameOf(nested));
225 }
226 case ReflectedValueKind::None:
227 case ReflectedValueKind::Other: return {};
228 }
229 return {};
230}
231
232std::optional<Value> ReflectedPropertyModel::read(const std::string &path) const {
233 if (!runtime_ || !schema_.find(path)) return std::nullopt;
234 return convertValue(path, runtime_->readProperty(instance_, path));
235}
236
238 auto descriptor = schema_.find(path);
239 if (!descriptor) return rejected("property_access.script.missing", "Property is not reflected");
240 Result<void> validation = validatePropertyValue(descriptor->get(), value);
241 if (!validation.ok()) return validationFailure(std::move(validation));
242
243 const PropertyKind kind = descriptor->get().kind;
246 const auto *items = value.getIf<Value::Array>();
247 if (!items) return rejected("property_access.script.type", "Unsupported property value type");
248 std::size_t current = runtime_->arraySize(instance_, path);
249 while (current > items->size()) {
250 if (!runtime_->arrayRemove(instance_, path, current - 1))
251 return rejected("property_access.script.write", "Runtime rejected the property write");
252 --current;
253 }
254 for (std::size_t index = 0; index < items->size(); ++index) {
255 const ReflectedValue reflected = toReflectedValue((*items)[index]);
256 if (reflected.empty()) return rejected("property_access.script.type", "Unsupported property value type");
257 if (index < current) {
258 if (!runtime_->arraySet(instance_, path, index, reflected))
259 return rejected("property_access.script.write", "Runtime rejected the property write");
260 } else if (!runtime_->arrayAppend(instance_, path, reflected)) {
261 return rejected("property_access.script.write", "Runtime rejected the property write");
262 }
263 }
264 } else if (kind == PropertyKind::Map || kind == PropertyKind::Struct) {
265 const auto *fields = value.getIf<Value::Object>();
266 if (!fields) return rejected("property_access.script.type", "Unsupported property value type");
267 const std::vector<std::string> existing = runtime_->tableKeys(instance_, path);
268 for (const std::string &key : existing) {
269 if (fields->find(key) != fields->end()) continue;
270 if (!runtime_->tableRemove(instance_, path, key))
271 return rejected("property_access.script.write", "Runtime rejected the property write");
272 }
273 for (const auto &[key, entry] : *fields) {
274 const ReflectedValue reflected = toReflectedValue(entry);
275 if (reflected.empty()) return rejected("property_access.script.type", "Unsupported property value type");
276 if (!runtime_->tableSet(instance_, path, key, reflected))
277 return rejected("property_access.script.write", "Runtime rejected the property write");
278 }
279 } else {
280 ReflectedValue reflected = toReflectedValue(value);
281 if (reflected.empty()) return rejected("property_access.script.type", "Unsupported property value type");
282 if (!runtime_->writeProperty(instance_, path, reflected))
283 return rejected("property_access.script.write", "Runtime rejected the property write");
284 }
285
286 const Value applied = convertValue(path, runtime_->readProperty(instance_, path));
287 const auto found = cachedValues_.find(path);
288 if (found == cachedValues_.end() || found->second != applied) emit(path, applied);
289 return accepted();
290}
291
293 const std::uint64_t id = observers_->nextId++;
294 observers_->entries.push_back({id, std::move(callback)});
295 std::weak_ptr<ObserverState> weak = observers_;
296 return Subscription([weak, id]() {
297 if (const auto state = weak.lock())
298 std::erase_if(state->entries, [id](const ObserverState::Entry &entry) { return entry.id == id; });
299 });
300}
301
303 for (const PropertyDescriptor &descriptor : schema_.properties) {
304 const std::optional<Value> current = read(descriptor.path);
305 if (!current) continue;
306 const auto found = cachedValues_.find(descriptor.path);
307 if (found == cachedValues_.end() || found->second != *current) emit(descriptor.path, *current);
308 }
309}
310
311void ReflectedPropertyModel::emit(const std::string &path, const Value &value) {
312 cachedValues_[path] = value;
313 const PropertyChange change{path, value, ++revision_};
314 const auto snapshot = observers_->entries;
315 for (const ObserverState::Entry &entry : snapshot)
316 if (entry.callback) entry.callback(change);
317}
318
319} // namespace eve::property_access
std::string descriptor
bool applied
SQObjectPtr key
Definition ECS.cpp:155
std::vector< std::string > fields
Definition ECS.cpp:42
std::string message
std::function< Numbers(b3JointId)> read
std::string id
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::shared_ptr< OceanGpuSpectrum > owner
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
double number
bool found
std::string text
std::string kind
double current
bool boolean
int count
float(ui::Theme::* member)[4]
uint32_t index
ViewPreparation callback
uint32_t flags
Move-only operation result carrying either a value or Status.
Definition Result.h:176
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:286
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:189
bool arrayRemove(const ssq::Object &instance, const std::string &name, size_t index) const
Removes one element of an array member (shifts the rest).
Definition Runtime.cpp:928
std::vector< ReflectedMember > reflectInstance(const ssq::Object &instance) const
Inspects a live instance: own + inherited members with current values.
Definition Runtime.cpp:710
ReflectedValue tableGet(const ssq::Object &instance, const std::string &name, const std::string &key) const
Value of a table member key; empty when missing.
Definition Runtime.cpp:977
bool writeProperty(const ssq::Object &instance, const std::string &name, const ReflectedValue &value) const
Writes one property of a live instance.
Definition Runtime.cpp:773
ssq::Object readObjectProperty(const ssq::Object &instance, const std::string &name) const
Reads a live object-valued property (nested instance).
Definition Runtime.cpp:832
bool tableRemove(const ssq::Object &instance, const std::string &name, const std::string &key) const
Removes a key from a table member.
Definition Runtime.cpp:1036
bool tableSet(const ssq::Object &instance, const std::string &name, const std::string &key, const ReflectedValue &value) const
Sets a key of a table member (creates the key when missing).
Definition Runtime.cpp:998
bool arrayAppend(const ssq::Object &instance, const std::string &name, const ReflectedValue &value) const
Appends an element to an array member.
Definition Runtime.cpp:911
std::string classNameOf(const ssq::Object &instance) const
Name of the script class of a live instance ("" when unknown).
Definition Runtime.cpp:1204
ReflectedValue readProperty(const ssq::Object &instance, const std::string &name) const
Reads one property of a live instance.
Definition Runtime.cpp:757
size_t arraySize(const ssq::Object &instance, const std::string &name) const
Element count of an array member (0 when missing/not an array).
Definition Runtime.cpp:851
bool arraySet(const ssq::Object &instance, const std::string &name, size_t index, const ReflectedValue &value) const
Replaces one element of an array member.
Definition Runtime.cpp:887
ReflectedValue arrayGet(const ssq::Object &instance, const std::string &name, size_t index) const
Element value of an array member; empty when out of range.
Definition Runtime.cpp:867
std::vector< std::string > tableKeys(const ssq::Object &instance, const std::string &name) const
String keys of a table member.
Definition Runtime.cpp:951
Move-only RAII token that owns one observer registration.
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::vector< Value > Array
Definition Value.h:33
std::function< void(const PropertyChange &)> ChangeCallback
~ReflectedPropertyModel() override
Reflected property model.
ReflectedPropertyModel(Runtime &runtime, ssq::Object instance)
Bind one live script instance to the shared property-access contract.
Result< void > write(const std::string &path, const eve::Value &value) override
Writes .
void rebuildSchema()
Rebuild reflection metadata after a script reload.
void refresh()
Pull live values and notify observers for changed properties.
Subscription subscribe(ChangeCallback callback) override
Subscribe.
std::optional< eve::Value > read(const std::string &path) const override
Reads .
Result< void > rejected(std::string rule, std::string message, DiagnosticCode code=DiagnosticCode::PreconditionViolation)
Build a rejected write/validation result with a stable rule string.
std::string_view diagnosticRule(const Diagnostic &diagnostic)
Return the projected property-access rule id, or empty when absent.
eve::Subscription Subscription
Compatibility alias for the common observer lifetime token.
Result< void > accepted()
Build a successful write/validation result.
PropertyFlag
Cross-host property visibility and editing flags.
PropertyKind
Semantic property kind used by renderer-independent presenters.
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
enum EVENGINE_API_FOUNDATION ReflectedValueKind
Runtime value kind read from a live script instance slot.
Definition Runtime.h:114
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:152
Typed snapshot of one live instance property.
Definition Runtime.h:132
bool empty() const noexcept
True when the slot exists and is non-null.
Definition Runtime.h:140
ReflectedValueKind kind
Definition Runtime.h:133
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