feat(UAT): Global View Models (#12888) f564fe7c61 * feat: Global View Models Co-authored-by: Phil Chung <philterdesign@gmail.com> Co-authored-by: hernan <hernan@rive.app>
diff --git a/.rive_head b/.rive_head index 3dcf24a..a5f7371 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -bb61acd90005795dc12c6c7a40d8f0302f158d4a +f564fe7c6101755e6147c1abb672dad51425b304
diff --git a/dev/defs/viewmodel/viewmodel.json b/dev/defs/viewmodel/viewmodel.json index 85c8724..4c290ad 100644 --- a/dev/defs/viewmodel/viewmodel.json +++ b/dev/defs/viewmodel/viewmodel.json
@@ -51,8 +51,7 @@ "int": 981, "string": "viewmodeltype" }, - "description": "Indentifies view models that have special uses, like text input view models", - "runtime": false + "description": "Identifies view models that have special uses, like text input view models" } } } \ No newline at end of file
diff --git a/dev/defs/viewmodel/viewmodel_instance.json b/dev/defs/viewmodel/viewmodel_instance.json index 8f68170..1a14346 100644 --- a/dev/defs/viewmodel/viewmodel_instance.json +++ b/dev/defs/viewmodel/viewmodel_instance.json
@@ -65,6 +65,16 @@ }, "description": "Whether the instance should be exported for runtime.", "runtime": false + }, + "isOverride": { + "type": "bool", + "initialValue": "false", + "key": { + "int": 1034, + "string": "isoverride" + }, + "description": "Whether this instance is an override of a global ViewModel instance.", + "runtime": false } } } \ No newline at end of file
diff --git a/include/rive/animation/state_machine_instance.hpp b/include/rive/animation/state_machine_instance.hpp index 24774a8..8e4a6d6 100644 --- a/include/rive/animation/state_machine_instance.hpp +++ b/include/rive/animation/state_machine_instance.hpp
@@ -90,6 +90,10 @@ StateMachineLayerInstance* layerInstance); rcp<DataContext> m_DataContext = nullptr; + // Ensures the current data context holds an instance for the artboard's + // main view model and for every global view model in the file, creating + // (completing) any that are missing before the context is applied. + void completeViewModelInstances(); void addToHitLookup(Component* target, bool isLayoutComponent, std::unordered_map<Component*, HitDrawable*>& hitLookup, @@ -124,7 +128,24 @@ SMITrigger* getTrigger(const std::string& name) const override; void bindViewModelInstance( rcp<ViewModelInstance> viewModelInstance) override; + // Sets the main (non-global) view model instance in the data context + // without rebinding. Call bind() to apply. A global instance is routed to + // setGlobalViewModelInstance. + void setViewModelInstance(rcp<ViewModelInstance> viewModelInstance); + // Sets/replaces the global view model instance bound under the given global + // view model name without rebinding, preserving the main instance and the + // other globals' order. Returns false if the name does not match the + // instance's global view model. Call bind() to apply. + bool setGlobalViewModelInstance(const std::string& name, + rcp<ViewModelInstance> viewModelInstance); + // Applies the current data context: rebinds artboard + state machine data + // binds in a single pass. No-op if nothing has been set. + void bind(); + // @returns the global view model instance currently bound under the given + // name, or nullptr if none has been set. Never creates. + rcp<ViewModelInstance> globalViewModelInstance(const std::string& name); void bindDataContext(rcp<DataContext> dataContext); + void inheritDataContext(rcp<DataContext> dataContext); void dataContext(rcp<DataContext> dataContext); rcp<DataContext> dataContext() const { return m_DataContext; } void rebind() override;
diff --git a/include/rive/animation/transition_viewmodel_condition.hpp b/include/rive/animation/transition_viewmodel_condition.hpp index 7d030fd..abc0fd8 100644 --- a/include/rive/animation/transition_viewmodel_condition.hpp +++ b/include/rive/animation/transition_viewmodel_condition.hpp
@@ -531,9 +531,9 @@ { auto dataContext = stateMachineInstance->dataContext(); if (dataContext != nullptr && - dataContext->viewModelInstance() != nullptr) + dataContext->mainViewModelInstance() != nullptr) { - return dataContext->viewModelInstance().get(); + return dataContext->mainViewModelInstance().get(); } return nullptr; }
diff --git a/include/rive/artboard.hpp b/include/rive/artboard.hpp index d2f3818..18bc9b2 100644 --- a/include/rive/artboard.hpp +++ b/include/rive/artboard.hpp
@@ -420,6 +420,25 @@ void bindViewModelInstance(rcp<ViewModelInstance> viewModelInstance, rcp<DataContext> parent); void bindViewModelInstance(rcp<ViewModelInstance> viewModelInstance); + void bindViewModelInstances( + std::vector<rcp<ViewModelInstance>> viewModelInstances, + rcp<DataContext> parent); + // Sets the main (non-global) view model instance in the data context + // without rebinding. Call bind() to apply. A global instance is routed to + // setGlobalViewModelInstance. + void setViewModelInstance(rcp<ViewModelInstance> viewModelInstance); + // Sets/replaces the global view model instance bound under the given global + // view model name without rebinding, preserving the main instance and the + // other globals' order. Returns false if the name does not match the + // instance's global view model. Call bind() to apply. + bool setGlobalViewModelInstance(const std::string& name, + rcp<ViewModelInstance> viewModelInstance); + // Applies the current data context: rebinds the artboard's data binds. + // No-op if nothing has been set. + void bind(); + // @returns the global view model instance currently bound under the given + // name, or nullptr if none has been set. Never creates. + rcp<ViewModelInstance> globalViewModelInstance(const std::string& name); void rebuildDataBind(DataBind*) override; bool hasAudio() const; @@ -662,6 +681,12 @@ m_rootTransformCallback = callback; } #endif + +protected: + // The File backing this artboard, when it is an instance. Used to lazily + // create default global view model instances. The base Artboard (e.g. an + // editor-time artboard) has no backing file. + virtual rcp<const File> artboardFile() const; }; class ArtboardInstance : public Artboard @@ -673,6 +698,9 @@ /// Holds a reference to the File that vended this instance so the File /// outlives the instance. void file(rcp<const File> file); + /// @returns the File that vended this instance, if any. Used to lazily + /// create default global view model instances on demand. + rcp<const File> file() const; std::unique_ptr<LinearAnimationInstance> animationAt(size_t index); std::unique_ptr<LinearAnimationInstance> animationNamed( @@ -702,6 +730,9 @@ SMITrigger* getTrigger(const std::string& name, const std::string& path); TextValueRun* getTextRun(const std::string& name, const std::string& path); +protected: + rcp<const File> artboardFile() const override; + private: rcp<const File> m_file; };
diff --git a/include/rive/command_queue.hpp b/include/rive/command_queue.hpp index 8b7544f..ebd3d09 100644 --- a/include/rive/command_queue.hpp +++ b/include/rive/command_queue.hpp
@@ -145,6 +145,12 @@ std::vector<std::string> viewModelNames) {} + virtual void onGlobalViewModelNamesListed( + const FileHandle, + uint64_t requestId, + std::vector<std::string> globalViewModelNames) + {} + virtual void onViewModelInstanceNamesListed( const FileHandle, uint64_t requestId, @@ -594,6 +600,33 @@ ViewModelInstanceHandle, uint64_t requestId = 0); + // Sets the main (non-global) view model instance without rebinding. Call + // bind() to apply. + void setViewModelInstance(StateMachineHandle, + ViewModelInstanceHandle, + uint64_t requestId = 0); + + // Sets/replaces the global view model instance bound under the given global + // view model name without rebinding. Call bind() to apply. Reports a state + // machine error if the name does not match a global view model. + void setGlobalViewModelInstance(StateMachineHandle, + std::string name, + ViewModelInstanceHandle, + uint64_t requestId = 0); + + // Returns a handle to the global view model instance currently bound under + // the given name. Never creates: if none is bound, reports a view model + // error and the returned handle maps to nothing. + ViewModelInstanceHandle globalViewModelInstance( + StateMachineHandle, + std::string name, + ViewModelInstanceListener* listener = nullptr, + uint64_t requestId = 0); + + // Applies the current data context: rebinds artboard + state machine data + // binds in a single pass. No-op if nothing has been set. + void bind(StateMachineHandle, uint64_t requestId = 0); + void advanceStateMachine(StateMachineHandle, float timeToAdvance, uint64_t requestId = 0); @@ -715,6 +748,7 @@ void disconnect(); void requestViewModelNames(FileHandle, uint64_t requestId = 0); + void requestGlobalViewModelNames(FileHandle, uint64_t requestId = 0); void requestArtboardNames(FileHandle, uint64_t requestId = 0); void requestFileAssets(FileHandle, uint64_t requestId = 0); void requestViewModelInstanceViewModelName(ViewModelInstanceHandle, @@ -942,6 +976,10 @@ requestSemanticFocus, clearSemanticFocus, bindViewModelInstance, + setViewModelInstance, + setGlobalViewModelInstance, + getGlobalViewModelInstance, + bind, runOnce, draw, cancelDraw, @@ -960,6 +998,7 @@ listStateMachines, getDefaultViewModel, listViewModels, + listGlobalViewModelNames, listViewModelInstanceNames, listViewModelProperties, listViewModelPropertyValue, @@ -982,6 +1021,7 @@ defaultViewModelReceived, viewModelInstanceViewModelNameReceived, viewModelsListend, + globalViewModelNamesListed, viewModelInstanceNamesListed, viewModelPropertiesListed, viewModelPropertyValueReceived,
diff --git a/include/rive/data_bind/data_context.hpp b/include/rive/data_bind/data_context.hpp index cb523b1..9bf1360 100644 --- a/include/rive/data_bind/data_context.hpp +++ b/include/rive/data_bind/data_context.hpp
@@ -4,6 +4,10 @@ #include "rive/viewmodel/viewmodel_instance.hpp" #include "rive/data_resolver.hpp" #include "rive/refcnt.hpp" +#include <cstdint> +#include <limits> +#include <memory> +#include <vector> namespace rive { @@ -11,11 +15,77 @@ class DataContext : public RefCnt<DataContext> { private: + // Sentinel slot key for an entry that is not on the slot keys, i.e. a main + // view model instance. A real slot key is a viewModelId (an index into the + // file's view models), so this value can never be a valid slot. + static constexpr uint32_t kNoSlot = std::numeric_limits<uint32_t>::max(); + rcp<DataContext> m_Parent = nullptr; - rcp<ViewModelInstance> m_ViewModelInstance; + std::vector<rcp<ViewModelInstance>> m_ViewModelInstances; + + // Containers (artboard + its state machines) that share this context and + // must be kept registered as dependents of every instance it holds. The + // context owns this bookkeeping so that mutating a shared context re-points + // ALL attached containers, not just the caller. Raw pointers: a container + // deregisters via removeDependentContainer before it dies (and the + // destructor detaches defensively). + std::vector<DataBindContainer*> m_dependentContainers; + // Add/remove every attached container as a dependent of one instance. + void attachContainers(ViewModelInstance* instance); + void detachContainers(ViewModelInstance* instance); + + // Slot bookkeeping for contexts that carry global view model instances. + // A "slot key" is the declared view model id a slot represents; it lets us + // place an instance in the right slot (and find/replace it) even when the + // instance's own view model differs from the slot's (the "override" case). + // Kept index-aligned with m_ViewModelInstances and allocated lazily, so the + // many global-free contexts pay only a single null pointer. Resolution + // never consults it. + struct GlobalSlots + { + std::vector<uint32_t> slotKeys; + }; + std::unique_ptr<GlobalSlots> m_globalSlots; + + // Ensures m_globalSlots exists and its slotKeys are index-aligned with + // m_ViewModelInstances, backfilling any missing entries with kNoSlot (they + // were mains before the first global was slotted). + void ensureGlobalSlots(); + // The slot key for the instance at index i (its stored key when tracked, + // otherwise kNoSlot, meaning the entry is a main / not on the slot keys). + uint32_t slotKeyAt(size_t index) const; + // Insert/remove an instance while keeping slot keys aligned. + void insertInstanceAt(size_t index, + rcp<ViewModelInstance> value, + uint32_t slotKey); + void removeInstanceAt(size_t index); + + ViewModelInstanceValue* tryGetViewModelProperty( + rcp<ViewModelInstance> instance, + const std::vector<uint32_t>& path) const; + ViewModelInstanceValue* tryGetRelativeViewModelProperty( + rcp<ViewModelInstance> instance, + const std::vector<uint32_t>& path, + DataResolver* resolver) const; + rcp<ViewModelInstance> tryGetViewModelInstance( + rcp<ViewModelInstance> instance, + const std::vector<uint32_t>& path) const; + rcp<ViewModelInstance> tryGetRelativeViewModelInstance( + rcp<ViewModelInstance> instance, + const std::vector<uint32_t>& path, + DataResolver* resolver) const; public: DataContext(rcp<ViewModelInstance> viewModelInstance); + DataContext(std::vector<rcp<ViewModelInstance>> viewModelInstances); + ~DataContext(); + + // Registers a container as a dependent of this context. Idempotent; also + // registers it against every instance currently held. + void addDependentContainer(DataBindContainer* container); + // Unregisters a container from this context and from every instance it + // holds. Call before the container is destroyed. + void removeDependentContainer(DataBindContainer* container); rcp<DataContext> parent() { return m_Parent; } void parent(rcp<DataContext> value) { m_Parent = value; } @@ -32,15 +102,36 @@ const std::vector<uint32_t> path, DataResolver* resolver) const; void viewModelInstance(rcp<ViewModelInstance> value); + // Insert-or-replace the instance occupying `slotKey`. Positions by + // canonical order (non-global/main first, then ascending slotKey). The + // instance's own viewModelId is irrelevant to placement, so any instance + // can fill any slot. + void setViewModelInstanceForSlot(uint32_t slotKey, + rcp<ViewModelInstance> value); + // The instance currently occupying `slotKey`, or nullptr. + rcp<ViewModelInstance> instanceForSlot(uint32_t slotKey) const; + // Removes the main view model instance(s): every entry not on the slot + // keys. + void removeMainViewModelInstance(); + // Replaces the single "main" view model instance (the entry not on the slot + // keys), preserving any global instances and their slot order. The result + // is always ordered as [main, globals...]. + void setMainViewModelInstance(rcp<ViewModelInstance> value); void advanced(); - rcp<ViewModelInstance> viewModelInstance() { return m_ViewModelInstance; }; + // The main view model instance: the first entry not on the slot keys, or + // nullptr if the context holds only globals. + rcp<ViewModelInstance> mainViewModelInstance() const; + const std::vector<rcp<ViewModelInstance>>& viewModelInstances() const + { + return m_ViewModelInstances; + } rcp<ViewModelInstance> rootViewModelInstance() { if (m_Parent) { return m_Parent->rootViewModelInstance(); } - return m_ViewModelInstance; + return mainViewModelInstance(); }; ViewModelInstanceValue* viewModelValue()
diff --git a/include/rive/file.hpp b/include/rive/file.hpp index 8af6aae..6c05622 100644 --- a/include/rive/file.hpp +++ b/include/rive/file.hpp
@@ -179,7 +179,17 @@ size_t viewModelCount() const { return m_ViewModels.size(); } ViewModel* viewModel(std::string name); - ViewModel* viewModel(size_t index); + ViewModel* viewModel(size_t index) const; + /// @returns the file index (definition order) of the view model with the + /// given name — the slot key used for data-context slots — or the view + /// model count if no such view model exists. + uint32_t viewModelId(const std::string& name) const; + /// @returns the global view models (viewModelType == global), in file + /// reference order. + std::vector<ViewModel*> globalViewModels() const; + /// @returns the names of the global view models (viewModelType == global), + /// in file reference order. + std::vector<std::string> globalViewModelNames() const; ViewModelRuntime* defaultArtboardViewModel(Artboard* artboard) const; ViewModelRuntime* viewModelByIndex(size_t index) const; ViewModelRuntime* viewModelByName(std::string name) const;
diff --git a/include/rive/generated/core_registry.hpp b/include/rive/generated/core_registry.hpp index 6bd499f..bd577f7 100644 --- a/include/rive/generated/core_registry.hpp +++ b/include/rive/generated/core_registry.hpp
@@ -950,6 +950,9 @@ case ViewModelPropertyEnumSystemBase::enumTypePropertyKey: object->as<ViewModelPropertyEnumSystemBase>()->enumType(value); break; + case ViewModelBase::viewModelTypePropertyKey: + object->as<ViewModelBase>()->viewModelType(value); + break; case DataEnumSystemBase::enumTypePropertyKey: object->as<DataEnumSystemBase>()->enumType(value); break; @@ -3164,6 +3167,8 @@ case ViewModelPropertyEnumSystemBase::enumTypePropertyKey: return object->as<ViewModelPropertyEnumSystemBase>() ->enumType(); + case ViewModelBase::viewModelTypePropertyKey: + return object->as<ViewModelBase>()->viewModelType(); case DataEnumSystemBase::enumTypePropertyKey: return object->as<DataEnumSystemBase>()->enumType(); case ViewModelPropertyViewModelBase:: @@ -4403,6 +4408,7 @@ case ViewModelInstanceEnumBase::propertyValuePropertyKey: case ViewModelInstanceArtboardBase::propertyValuePropertyKey: case ViewModelPropertyEnumSystemBase::enumTypePropertyKey: + case ViewModelBase::viewModelTypePropertyKey: case DataEnumSystemBase::enumTypePropertyKey: case ViewModelPropertyViewModelBase:: viewModelReferenceIdPropertyKey: @@ -5010,6 +5016,8 @@ return object->is<ViewModelInstanceArtboardBase>(); case ViewModelPropertyEnumSystemBase::enumTypePropertyKey: return object->is<ViewModelPropertyEnumSystemBase>(); + case ViewModelBase::viewModelTypePropertyKey: + return object->is<ViewModelBase>(); case DataEnumSystemBase::enumTypePropertyKey: return object->is<DataEnumSystemBase>(); case ViewModelPropertyViewModelBase::
diff --git a/include/rive/generated/viewmodel/viewmodel_base.hpp b/include/rive/generated/viewmodel/viewmodel_base.hpp index 4f05cdc..7c17205 100644 --- a/include/rive/generated/viewmodel/viewmodel_base.hpp +++ b/include/rive/generated/viewmodel/viewmodel_base.hpp
@@ -1,5 +1,6 @@ #ifndef _RIVE_VIEW_MODEL_BASE_HPP_ #define _RIVE_VIEW_MODEL_BASE_HPP_ +#include "rive/core/field_types/core_uint_type.hpp" #include "rive/viewmodel/viewmodel_component.hpp" namespace rive { @@ -27,9 +28,44 @@ uint16_t coreType() const override { return typeKey; } - Core* clone() const override; + static const uint16_t viewModelTypePropertyKey = 981; protected: + uint32_t m_ViewModelType = 0; + +public: + inline uint32_t viewModelType() const { return m_ViewModelType; } + void viewModelType(uint32_t value) + { + if (m_ViewModelType == value) + { + return; + } + m_ViewModelType = value; + viewModelTypeChanged(); + notifyPropertyChanged(viewModelTypePropertyKey); + } + + Core* clone() const override; + void copy(const ViewModelBase& object) + { + m_ViewModelType = object.m_ViewModelType; + ViewModelComponent::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case viewModelTypePropertyKey: + m_ViewModelType = CoreUintType::deserialize(reader); + return true; + } + return ViewModelComponent::deserialize(propertyKey, reader); + } + +protected: + virtual void viewModelTypeChanged() {} }; } // namespace rive
diff --git a/include/rive/nested_artboard.hpp b/include/rive/nested_artboard.hpp index 79f6b58..81f2fd2 100644 --- a/include/rive/nested_artboard.hpp +++ b/include/rive/nested_artboard.hpp
@@ -47,6 +47,11 @@ // dynamically-created bound VMI for a different ViewModel (owned here, see // m_ownsActiveVmi). ViewModelInstance* m_activeViewModelInstance = nullptr; + // Global ViewModelInstance children — appended to the data context passed + // down to the wrapped artboard. The artboard's m_Objects owns the + // construction ref; this list holds an extra ref (see ref_rcp in + // onAddedClean) so it stays valid regardless of teardown ordering. + std::vector<rcp<ViewModelInstance>> m_globalViewModelInstances; protected: private: @@ -59,8 +64,6 @@ void nest(Artboard* artboard); bool tryScheduleBindStateful(); void bindStateful(); - void bindArtboardInstance(ViewModelInstance* instance, - rcp<DataContext> parent); // Walks children() for the first ViewModelInstance child (the stateful // component VMI authored in the editor). Returns nullptr if none. ViewModelInstance* findStatefulChildVmi() const;
diff --git a/include/rive/view_model_type.hpp b/include/rive/view_model_type.hpp new file mode 100644 index 0000000..2007e8e --- /dev/null +++ b/include/rive/view_model_type.hpp
@@ -0,0 +1,12 @@ +#ifndef _RIVE_VIEW_MODEL_TYPE_HPP_ +#define _RIVE_VIEW_MODEL_TYPE_HPP_ +namespace rive +{ +enum class ViewModelType : int +{ + standard = 0, + textInput = 1, + global = 2, +}; +} +#endif \ No newline at end of file
diff --git a/include/rive/viewmodel/viewmodel_instance.hpp b/include/rive/viewmodel/viewmodel_instance.hpp index 323af89..5506b7e 100644 --- a/include/rive/viewmodel/viewmodel_instance.hpp +++ b/include/rive/viewmodel/viewmodel_instance.hpp
@@ -39,6 +39,10 @@ ~ViewModelInstance(); void addValue(ViewModelInstanceValue* value); + // Removes the property value with the given property id, if present. + // Returns whether a value was removed. Used to prune editor-time override + // instances down to only their explicitly-overridden properties. + bool removeValue(uint32_t propertyId); ViewModelInstanceValue* propertyValue(const uint32_t id); ViewModelInstanceValue* propertyValue(const std::string& name); ViewModelInstanceValue* propertyValue(const SymbolType symbolType);
diff --git a/src/animation/listener_viewmodel_change.cpp b/src/animation/listener_viewmodel_change.cpp index 703c4e2..630ed01 100644 --- a/src/animation/listener_viewmodel_change.cpp +++ b/src/animation/listener_viewmodel_change.cpp
@@ -64,7 +64,7 @@ auto context = stateMachineInstance->dataContext(); if (context != nullptr) { - auto value = context->viewModelInstance().get(); + auto value = context->mainViewModelInstance().get(); targetValue->viewModelInstanceValue(value); CoreRegistry::setUint( targetValue,
diff --git a/src/animation/state_machine_instance.cpp b/src/animation/state_machine_instance.cpp index 786d710..48b5f9f 100644 --- a/src/animation/state_machine_instance.cpp +++ b/src/animation/state_machine_instance.cpp
@@ -63,6 +63,10 @@ #include "rive/focus_data.hpp" #include "rive/node.hpp" #include "rive/semantic/semantic_data.hpp" +#include "rive/view_model_type.hpp" +#include "rive/viewmodel/viewmodel.hpp" +#include "rive/file.hpp" +#include "rive/data_bind/data_context.hpp" #include <array> #include <memory> #include <unordered_map> @@ -2686,29 +2690,170 @@ return getNamedInput<StateMachineTrigger, SMITrigger>(name); } +void StateMachineInstance::setViewModelInstance( + rcp<ViewModelInstance> viewModelInstance) +{ + if (viewModelInstance == nullptr) + { + return; + } + if (m_DataContext == nullptr) + { + m_DataContext = make_rcp<DataContext>(viewModelInstance); + m_DataContext->addDependentContainer(this); + return; + } + // The data context re-points every attached container (this state machine, + // the artboard, and any sibling state machines sharing the context) off the + // old main and onto the new one. + m_DataContext->setMainViewModelInstance(viewModelInstance); +} + +bool StateMachineInstance::setGlobalViewModelInstance( + const std::string& name, + rcp<ViewModelInstance> viewModelInstance) +{ + if (viewModelInstance == nullptr) + { + return false; + } + auto file = m_artboardInstance->file(); + if (file == nullptr) + { + return false; + } + // The slot is addressed by the named view model (its file index), not by + // the instance's own view model — so an override instance of a different + // view model can be placed on the slot. + uint32_t slotKey = file->viewModelId(name); + if (slotKey >= file->viewModelCount()) + { + return false; + } + // Only global view models get a slot; a non-global name is not a valid + // global slot and must not be slotted. + auto slotViewModel = file->viewModel(slotKey); + if (slotViewModel == nullptr || + static_cast<ViewModelType>(slotViewModel->viewModelType()) != + ViewModelType::global) + { + return false; + } + if (m_DataContext == nullptr) + { + m_DataContext = make_rcp<DataContext>(rcp<ViewModelInstance>(nullptr)); + m_DataContext->addDependentContainer(this); + } + // The data context re-points every attached container off any previous + // instance occupying this slot and onto the new one. + m_DataContext->setViewModelInstanceForSlot(slotKey, viewModelInstance); + return true; +} + +void StateMachineInstance::bind() +{ + if (m_DataContext == nullptr) + { + return; + } + // Make sure every view model instance the data context needs exists before + // it is applied: the main instance plus one for each global view model. + // Any that are missing are created (completed) on the fly. + completeViewModelInstances(); + // Apply the current data context: rebind the artboard and state machine + // data binds in a single pass. + m_artboardInstance->internalDataContext(m_DataContext); + internalDataContext(m_DataContext); +} + +void StateMachineInstance::completeViewModelInstances() +{ + auto file = m_artboardInstance->file(); + if (file == nullptr) + { + return; + } + // Ensure a main instance is present. The main is the entry not on the slot + // keys; if there is none, create the artboard's default and place it first. + if (m_DataContext->mainViewModelInstance() == nullptr) + { + auto main = file->createDefaultViewModelInstance(m_artboardInstance); + if (main != nullptr) + { + // setMainViewModelInstance re-points every attached container onto + // the new instance. + m_DataContext->setMainViewModelInstance(main); + } + } + // Ensure an instance exists for each global view model slot, creating any + // missing ones. Occupancy is checked by slot key, so a cross-view-model + // override already sitting in a slot is not treated as empty. + for (auto* viewModel : file->globalViewModels()) + { + uint32_t slotKey = file->viewModelId(viewModel->name()); + if (m_DataContext->instanceForSlot(slotKey) != nullptr) + { + continue; + } + auto instance = file->createDefaultViewModelInstance(viewModel); + if (instance != nullptr) + { + // setViewModelInstanceForSlot re-points every attached container + // onto the new instance. + m_DataContext->setViewModelInstanceForSlot(slotKey, instance); + } + } +} + void StateMachineInstance::bindViewModelInstance( rcp<ViewModelInstance> viewModelInstance) { - clearDataContext(); - auto dataContext = make_rcp<DataContext>(viewModelInstance); - viewModelInstance->addDependent(this); - m_artboardInstance->clearDataContext(); - m_artboardInstance->internalDataContext(dataContext); - internalDataContext(dataContext); + if (viewModelInstance == nullptr) + { + clearDataContext(); + m_artboardInstance->unbind(); + return; + } + setViewModelInstance(std::move(viewModelInstance)); + bind(); +} + +rcp<ViewModelInstance> StateMachineInstance::globalViewModelInstance( + const std::string& name) +{ + // Pure read: returns the instance in the named slot only if one has been + // set/bound; never creates. + if (m_DataContext == nullptr) + { + return nullptr; + } + auto file = m_artboardInstance->file(); + if (file == nullptr) + { + return nullptr; + } + return m_DataContext->instanceForSlot(file->viewModelId(name)); } void StateMachineInstance::bindDataContext(rcp<DataContext> dataContext) { clearDataContext(); - if (dataContext->viewModelInstance()) - { - dataContext->viewModelInstance()->addDependent(this); - } + dataContext->addDependentContainer(this); m_artboardInstance->clearDataContext(); m_artboardInstance->internalDataContext(dataContext); internalDataContext(dataContext); } +void StateMachineInstance::inheritDataContext(rcp<DataContext> dataContext) +{ + if (dataContext == nullptr) + { + return; + } + dataContext->addDependentContainer(this); + internalDataContext(dataContext); +} + void StateMachineInstance::dataContext(rcp<DataContext> dataContext) { clearDataContext(); @@ -2756,10 +2901,7 @@ { if (m_DataContext) { - if (m_DataContext->viewModelInstance()) - { - m_DataContext->viewModelInstance()->removeDependent(this); - } + m_DataContext->removeDependentContainer(this); m_DataContext = nullptr; } for (auto& listenerViewModel : m_listenerViewModels)
diff --git a/src/artboard.cpp b/src/artboard.cpp index dff0fc9..4a561e1 100644 --- a/src/artboard.cpp +++ b/src/artboard.cpp
@@ -42,6 +42,9 @@ #include "rive/animation/nested_trigger.hpp" #include "rive/viewmodel/viewmodel_instance.hpp" #include "rive/viewmodel/viewmodel_instance_value.hpp" +#include "rive/viewmodel/viewmodel.hpp" +#include "rive/view_model_type.hpp" +#include "rive/data_bind/data_context.hpp" #include "rive/animation/state_machine_input_instance.hpp" #include "rive/animation/state_machine_instance.hpp" #include "rive/shapes/shape.hpp" @@ -2566,7 +2569,7 @@ m_DataContext->getViewModelInstance(artboardHost->dataBindPath()); if (value == nullptr) { - value = m_DataContext->viewModelInstance(); + value = m_DataContext->mainViewModelInstance(); } artboardHost->relinkDataContext(value); } @@ -2594,10 +2597,7 @@ { if (m_DataContext) { - if (m_DataContext->viewModelInstance()) - { - m_DataContext->viewModelInstance()->removeDependent(this); - } + m_DataContext->removeDependentContainer(this); m_DataContext = nullptr; } for (auto artboardHost : m_ArtboardHosts) @@ -2632,6 +2632,8 @@ internalDataContext(value); } +rcp<const File> Artboard::artboardFile() const { return nullptr; } + void Artboard::bindViewModelInstance(rcp<ViewModelInstance> viewModelInstance) { bindViewModelInstance(viewModelInstance, nullptr); @@ -2645,16 +2647,114 @@ unbind(); return; } - clearDataContext(); - auto dataContext = make_rcp<DataContext>(viewModelInstance); - if (dataContext->viewModelInstance()) + setViewModelInstance(std::move(viewModelInstance)); + if (parent != nullptr && m_DataContext != nullptr) { - dataContext->viewModelInstance()->addDependent(this); + m_DataContext->parent(parent); } + bind(); +} + +void Artboard::setViewModelInstance(rcp<ViewModelInstance> viewModelInstance) +{ + if (viewModelInstance == nullptr) + { + return; + } + if (m_DataContext == nullptr) + { + m_DataContext = make_rcp<DataContext>(viewModelInstance); + m_DataContext->addDependentContainer(this); + return; + } + // The data context re-points every attached container (this artboard and + // any state machines sharing the context) off the old main and onto the new + // one. + m_DataContext->setMainViewModelInstance(viewModelInstance); +} + +void Artboard::bindViewModelInstances( + std::vector<rcp<ViewModelInstance>> viewModelInstances, + rcp<DataContext> parent) +{ + if (viewModelInstances.empty()) + { + unbind(); + return; + } + clearDataContext(); + auto dataContext = make_rcp<DataContext>(std::move(viewModelInstances)); + dataContext->addDependentContainer(this); dataContext->parent(parent); internalDataContext(dataContext); } +void Artboard::bind() +{ + if (m_DataContext != nullptr) + { + internalDataContext(m_DataContext); + } +} + +rcp<ViewModelInstance> Artboard::globalViewModelInstance( + const std::string& name) +{ + // Pure read: returns the instance in the named slot only if one has been + // set/bound; never creates. + if (m_DataContext == nullptr) + { + return nullptr; + } + auto f = artboardFile(); + if (f == nullptr) + { + return nullptr; + } + return m_DataContext->instanceForSlot(f->viewModelId(name)); +} + +bool Artboard::setGlobalViewModelInstance( + const std::string& name, + rcp<ViewModelInstance> viewModelInstance) +{ + if (viewModelInstance == nullptr) + { + return false; + } + auto f = artboardFile(); + if (f == nullptr) + { + return false; + } + // The slot is addressed by the named view model (its file index), not by + // the instance's own view model — so an override instance of a different + // view model can be placed on the slot. + uint32_t slotKey = f->viewModelId(name); + if (slotKey >= f->viewModelCount()) + { + return false; + } + // Only global view models get a slot; a non-global name is not a valid + // global slot and must not be slotted. + auto slotViewModel = f->viewModel(slotKey); + if (slotViewModel == nullptr || + static_cast<ViewModelType>(slotViewModel->viewModelType()) != + ViewModelType::global) + { + return false; + } + if (m_DataContext == nullptr) + { + m_DataContext = make_rcp<DataContext>(rcp<ViewModelInstance>(nullptr)); + m_DataContext->addDependentContainer(this); + } + // The data context re-points every attached container off any previous + // instance occupying this slot and onto the new one. + m_DataContext->setViewModelInstanceForSlot(slotKey, viewModelInstance); + return true; +} + bool Artboard::isAncestor(const Artboard* artboard) { if (artboard != nullptr && m_artboardSource == artboard->artboardSource()) @@ -2705,6 +2805,10 @@ void ArtboardInstance::file(rcp<const File> file) { m_file = std::move(file); } +rcp<const File> ArtboardInstance::file() const { return m_file; } + +rcp<const File> ArtboardInstance::artboardFile() const { return m_file; } + std::unique_ptr<LinearAnimationInstance> ArtboardInstance::animationAt( size_t index) { @@ -2723,14 +2827,32 @@ size_t index) { auto sm = this->stateMachine(index); - return sm ? std::make_unique<StateMachineInstance>(sm, this) : nullptr; + if (sm == nullptr) + { + return nullptr; + } + auto smInstance = std::make_unique<StateMachineInstance>(sm, this); + if (auto dc = dataContext()) + { + smInstance->inheritDataContext(dc); + } + return smInstance; } std::unique_ptr<StateMachineInstance> ArtboardInstance::stateMachineNamed( const std::string& name) { auto sm = this->stateMachine(name); - return sm ? std::make_unique<StateMachineInstance>(sm, this) : nullptr; + if (sm == nullptr) + { + return nullptr; + } + auto smInstance = std::make_unique<StateMachineInstance>(sm, this); + if (auto dc = dataContext()) + { + smInstance->inheritDataContext(dc); + } + return smInstance; } std::unique_ptr<StateMachineInstance> ArtboardInstance::defaultStateMachine()
diff --git a/src/artboard_component_list.cpp b/src/artboard_component_list.cpp index 5f8120b..7e52579 100644 --- a/src/artboard_component_list.cpp +++ b/src/artboard_component_list.cpp
@@ -852,7 +852,7 @@ auto dataContext = itr->second->dataContext(); if (dataContext != nullptr) { - auto boundInstance = dataContext->viewModelInstance(); + auto boundInstance = dataContext->mainViewModelInstance(); if (boundInstance != nullptr && boundInstance != viewModelInstance) {
diff --git a/src/command_queue.cpp b/src/command_queue.cpp index 0c06d3d..9560e62 100644 --- a/src/command_queue.cpp +++ b/src/command_queue.cpp
@@ -658,6 +658,63 @@ m_commandStream << requestId; } +void CommandQueue::setViewModelInstance(StateMachineHandle handle, + ViewModelInstanceHandle viewModel, + uint64_t requestId) +{ + AutoLockAndNotify lock(m_commandMutex, m_commandConditionVariable); + m_commandStream << Command::setViewModelInstance; + m_commandStream << handle; + m_commandStream << viewModel; + m_commandStream << requestId; +} + +void CommandQueue::setGlobalViewModelInstance(StateMachineHandle handle, + std::string name, + ViewModelInstanceHandle viewModel, + uint64_t requestId) +{ + AutoLockAndNotify lock(m_commandMutex, m_commandConditionVariable); + m_commandStream << Command::setGlobalViewModelInstance; + m_commandStream << handle; + m_commandStream << viewModel; + m_commandStream << requestId; + m_names << name; +} + +ViewModelInstanceHandle CommandQueue::globalViewModelInstance( + StateMachineHandle handle, + std::string name, + ViewModelInstanceListener* listener, + uint64_t requestId) +{ + auto viewHandle = reinterpret_cast<ViewModelInstanceHandle>( + ++m_currentViewModelHandleIdx); + if (listener) + { + assert(listener->m_handle == RIVE_NULL_HANDLE); + listener->m_handle = viewHandle; + listener->m_owningQueue = ref_rcp(this); + registerListener(viewHandle, listener); + } + AutoLockAndNotify lock(m_commandMutex, m_commandConditionVariable); + m_commandStream << Command::getGlobalViewModelInstance; + m_commandStream << handle; + m_commandStream << viewHandle; + m_commandStream << requestId; + m_names << name; + + return viewHandle; +} + +void CommandQueue::bind(StateMachineHandle handle, uint64_t requestId) +{ + AutoLockAndNotify lock(m_commandMutex, m_commandConditionVariable); + m_commandStream << Command::bind; + m_commandStream << handle; + m_commandStream << requestId; +} + void CommandQueue::advanceStateMachine(StateMachineHandle stateMachineHandle, float timeToAdvance, uint64_t requestId) @@ -980,6 +1037,15 @@ m_commandStream << requestId; } +void CommandQueue::requestGlobalViewModelNames(FileHandle fileHandle, + uint64_t requestId) +{ + AutoLockAndNotify lock(m_commandMutex, m_commandConditionVariable); + m_commandStream << Command::listGlobalViewModelNames; + m_commandStream << fileHandle; + m_commandStream << requestId; +} + void CommandQueue::requestArtboardNames(FileHandle fileHandle, uint64_t requestId) { @@ -1435,6 +1501,40 @@ break; } + case Message::globalViewModelNamesListed: + { + size_t numViewModels; + FileHandle handle; + uint64_t requestId; + m_messageStream >> handle; + m_messageStream >> requestId; + m_messageStream >> numViewModels; + std::vector<std::string> globalViewModelNames(numViewModels); + for (auto& name : globalViewModelNames) + { + m_messageNames >> name; + } + lock.unlock(); + + if (m_globalFileListener) + { + m_globalFileListener->onGlobalViewModelNamesListed( + handle, + requestId, + globalViewModelNames); + } + + auto itr = m_fileListeners.find(handle); + if (itr != m_fileListeners.end()) + { + itr->second->onGlobalViewModelNamesListed( + itr->first, + requestId, + std::move(globalViewModelNames)); + } + + break; + } case Message::viewModelInstanceNamesListed: {
diff --git a/src/command_server.cpp b/src/command_server.cpp index a06a304..bd1ba3c 100644 --- a/src/command_server.cpp +++ b/src/command_server.cpp
@@ -1853,6 +1853,188 @@ break; } + case CommandQueue::Command::setViewModelInstance: + { + StateMachineHandle handle; + ViewModelInstanceHandle viewModel; + uint64_t requestId; + commandStream >> handle; + commandStream >> viewModel; + commandStream >> requestId; + lock.unlock(); + + if (auto stateMachineWrapper = getStateMachineWrapper(handle)) + { + if (auto viewModelInstance = + getViewModelInstance(viewModel)) + { + std::unique_lock<std::mutex> accesLock( + stateMachineWrapper->m_mutex); + stateMachineWrapper->instance->setViewModelInstance( + viewModelInstance->instance()); + } + else + { + ErrorReporter<StateMachineHandle>( + this, + handle, + requestId, + CommandQueue::Message::stateMachineError) + << "View model instance " << viewModel + << " not found when trying to set the main view " + "model instance on a state machine"; + } + } + else + { + ErrorReporter<StateMachineHandle>( + this, + handle, + requestId, + CommandQueue::Message::stateMachineError) + << "State machine " << handle + << " not found for setting view model instance."; + } + break; + } + + case CommandQueue::Command::setGlobalViewModelInstance: + { + StateMachineHandle handle; + ViewModelInstanceHandle viewModel; + uint64_t requestId; + std::string name; + commandStream >> handle; + commandStream >> viewModel; + commandStream >> requestId; + m_commandQueue->m_names >> name; + lock.unlock(); + + if (auto stateMachineWrapper = getStateMachineWrapper(handle)) + { + if (auto viewModelInstance = + getViewModelInstance(viewModel)) + { + std::unique_lock<std::mutex> accesLock( + stateMachineWrapper->m_mutex); + if (!stateMachineWrapper->instance + ->setGlobalViewModelInstance( + name, + viewModelInstance->instance())) + { + ErrorReporter<StateMachineHandle>( + this, + handle, + requestId, + CommandQueue::Message::stateMachineError) + << "Could not set global view model instance " + << viewModel << " under name " << name + << " on a state machine"; + } + } + else + { + ErrorReporter<StateMachineHandle>( + this, + handle, + requestId, + CommandQueue::Message::stateMachineError) + << "View model instance " << viewModel + << " not found when trying to set a global view " + "model instance on a state machine"; + } + } + else + { + ErrorReporter<StateMachineHandle>( + this, + handle, + requestId, + CommandQueue::Message::stateMachineError) + << "State machine " << handle + << " not found for setting global view model instance."; + } + break; + } + + case CommandQueue::Command::getGlobalViewModelInstance: + { + StateMachineHandle handle; + ViewModelInstanceHandle viewHandle; + uint64_t requestId; + std::string name; + commandStream >> handle; + commandStream >> viewHandle; + commandStream >> requestId; + m_commandQueue->m_names >> name; + lock.unlock(); + + if (auto stateMachineWrapper = getStateMachineWrapper(handle)) + { + rcp<ViewModelInstance> viewModelInstance; + { + std::unique_lock<std::mutex> accesLock( + stateMachineWrapper->m_mutex); + viewModelInstance = stateMachineWrapper->instance + ->globalViewModelInstance(name); + } + if (viewModelInstance != nullptr) + { + m_viewModels[viewHandle] = + make_rcp<ViewModelInstanceRuntime>( + viewModelInstance); + } + else + { + ErrorReporter<ViewModelInstanceHandle>( + this, + viewHandle, + requestId, + CommandQueue::Message::viewModelError) + << "No global view model instance bound under name " + << name << " on a state machine"; + } + } + else + { + ErrorReporter<ViewModelInstanceHandle>( + this, + viewHandle, + requestId, + CommandQueue::Message::viewModelError) + << "State machine " << handle + << " not found for getting global view model instance."; + } + break; + } + + case CommandQueue::Command::bind: + { + StateMachineHandle handle; + uint64_t requestId; + commandStream >> handle; + commandStream >> requestId; + lock.unlock(); + + if (auto stateMachineWrapper = getStateMachineWrapper(handle)) + { + std::unique_lock<std::mutex> accesLock( + stateMachineWrapper->m_mutex); + stateMachineWrapper->instance->bind(); + } + else + { + ErrorReporter<StateMachineHandle>( + this, + handle, + requestId, + CommandQueue::Message::stateMachineError) + << "State machine " << handle + << " not found for binding data context."; + } + break; + } + case CommandQueue::Command::advanceStateMachine: { StateMachineHandle handle; @@ -2543,6 +2725,42 @@ break; } + case CommandQueue::Command::listGlobalViewModelNames: + { + FileHandle handle; + uint64_t requestId; + commandStream >> handle; + commandStream >> requestId; + lock.unlock(); + auto file = getFile(handle); + if (file) + { + auto names = file->globalViewModelNames(); + + std::unique_lock<std::mutex> messageLock( + m_commandQueue->m_messageMutex); + messageStream + << CommandQueue::Message::globalViewModelNamesListed; + messageStream << handle; + messageStream << requestId; + messageStream << names.size(); + for (auto& name : names) + { + m_commandQueue->m_messageNames << name; + } + } + else + { + ErrorReporter<FileHandle>(this, + handle, + requestId, + CommandQueue::Message::fileError) + << "Invalid file handle " << handle + << " when getting list of global view models"; + } + break; + } + case CommandQueue::Command::listViewModelInstanceNames: { FileHandle handle;
diff --git a/src/data_bind/data_bind_container.cpp b/src/data_bind/data_bind_container.cpp index 5a8a1da..593d6db 100644 --- a/src/data_bind/data_bind_container.cpp +++ b/src/data_bind/data_bind_container.cpp
@@ -24,7 +24,6 @@ void DataBindContainer::bindDataBindsFromContext(DataContext* dataContext) { - for (auto& dataBind : m_dataBinds) { if (dataBind->is<DataBindContext>())
diff --git a/src/data_bind/data_context.cpp b/src/data_bind/data_context.cpp index fcfcfb6..57971bf 100644 --- a/src/data_bind/data_context.cpp +++ b/src/data_bind/data_context.cpp
@@ -4,59 +4,413 @@ #include "rive/viewmodel/viewmodel_instance.hpp" #include "rive/viewmodel/viewmodel.hpp" #include "rive/viewmodel/viewmodel_instance_viewmodel.hpp" +#include <algorithm> using namespace rive; -DataContext::DataContext(rcp<ViewModelInstance> viewModelInstance) : - m_ViewModelInstance(viewModelInstance) +DataContext::DataContext(rcp<ViewModelInstance> viewModelInstance) +{ + if (viewModelInstance != nullptr) + { + m_ViewModelInstances.push_back(std::move(viewModelInstance)); + } +} + +DataContext::DataContext( + std::vector<rcp<ViewModelInstance>> viewModelInstances) : + m_ViewModelInstances(std::move(viewModelInstances)) {} +DataContext::~DataContext() +{ + // Defensive: detach any still-registered containers so a surviving instance + // (e.g. one a user still holds) can't keep a stale pointer to a container + // that is going away with this context. + for (auto& instance : m_ViewModelInstances) + { + detachContainers(instance.get()); + } +} + +void DataContext::attachContainers(ViewModelInstance* instance) +{ + if (instance == nullptr) + { + return; + } + for (auto* container : m_dependentContainers) + { + instance->addDependent(container); + } +} + +void DataContext::detachContainers(ViewModelInstance* instance) +{ + if (instance == nullptr) + { + return; + } + for (auto* container : m_dependentContainers) + { + instance->removeDependent(container); + } +} + +void DataContext::addDependentContainer(DataBindContainer* container) +{ + if (container == nullptr) + { + return; + } + if (std::find(m_dependentContainers.begin(), + m_dependentContainers.end(), + container) != m_dependentContainers.end()) + { + return; + } + m_dependentContainers.push_back(container); + for (auto& instance : m_ViewModelInstances) + { + if (instance != nullptr) + { + instance->addDependent(container); + } + } +} + +void DataContext::removeDependentContainer(DataBindContainer* container) +{ + for (auto& instance : m_ViewModelInstances) + { + if (instance != nullptr) + { + instance->removeDependent(container); + } + } + m_dependentContainers.erase(std::remove(m_dependentContainers.begin(), + m_dependentContainers.end(), + container), + m_dependentContainers.end()); +} + +void DataContext::ensureGlobalSlots() +{ + if (m_globalSlots != nullptr) + { + // Already tracking; kept index-aligned by the insert/remove primitives. + return; + } + m_globalSlots = std::make_unique<GlobalSlots>(); + // Everything already in the context was a main before the first global was + // slotted, so backfill each entry as unslotted. + m_globalSlots->slotKeys.assign(m_ViewModelInstances.size(), kNoSlot); +} + +uint32_t DataContext::slotKeyAt(size_t index) const +{ + if (m_globalSlots != nullptr && index < m_globalSlots->slotKeys.size()) + { + return m_globalSlots->slotKeys[index]; + } + // Untracked entries are mains (not on the slot keys). + return kNoSlot; +} + +void DataContext::insertInstanceAt(size_t index, + rcp<ViewModelInstance> value, + uint32_t slotKey) +{ + auto it = m_ViewModelInstances.insert(m_ViewModelInstances.begin() + index, + std::move(value)); + if (m_globalSlots != nullptr) + { + m_globalSlots->slotKeys.insert(m_globalSlots->slotKeys.begin() + index, + slotKey); + } + // Keep all attached containers registered as dependents of the new entry. + attachContainers(it->get()); +} + +void DataContext::removeInstanceAt(size_t index) +{ + // Detach before erasing so no container stays registered on the removed + // instance (which may outlive the context via a user-held reference). + detachContainers(m_ViewModelInstances[index].get()); + m_ViewModelInstances.erase(m_ViewModelInstances.begin() + index); + if (m_globalSlots != nullptr) + { + m_globalSlots->slotKeys.erase(m_globalSlots->slotKeys.begin() + index); + } +} + void DataContext::viewModelInstance(rcp<ViewModelInstance> value) { - m_ViewModelInstance = value; + if (m_globalSlots != nullptr) + { + setMainViewModelInstance(std::move(value)); + return; + } + if (m_ViewModelInstances.empty()) + { + m_ViewModelInstances.push_back(std::move(value)); + attachContainers(m_ViewModelInstances.back().get()); + } + else + { + detachContainers(m_ViewModelInstances[0].get()); + m_ViewModelInstances[0] = std::move(value); + attachContainers(m_ViewModelInstances[0].get()); + } } -void DataContext::advanced() { m_ViewModelInstance->advanced(); } +void DataContext::setViewModelInstanceForSlot(uint32_t slotKey, + rcp<ViewModelInstance> value) +{ + if (value == nullptr) + { + return; + } + // Holding a slot-addressed instance makes this a global-bearing context. + ensureGlobalSlots(); + // Replace in place if the slot is already occupied (keeps its position). + for (size_t i = 0; i < m_ViewModelInstances.size(); i++) + { + if (slotKeyAt(i) == slotKey) + { + detachContainers(m_ViewModelInstances[i].get()); + m_ViewModelInstances[i] = std::move(value); + m_globalSlots->slotKeys[i] = slotKey; + attachContainers(m_ViewModelInstances[i].get()); + return; + } + } + // Insert at canonical position: keep any leading main (unslotted) instance + // ahead of the globals, then order among globals by ascending slot key. The + // instance's own viewModelId is irrelevant here — placement follows + // slotKey. + size_t index = 0; + while (index < m_ViewModelInstances.size() && slotKeyAt(index) == kNoSlot) + { + index++; + } + while (index < m_ViewModelInstances.size() && slotKeyAt(index) != kNoSlot && + slotKeyAt(index) < slotKey) + { + index++; + } + insertInstanceAt(index, std::move(value), slotKey); +} + +rcp<ViewModelInstance> DataContext::instanceForSlot(uint32_t slotKey) const +{ + for (size_t i = 0; i < m_ViewModelInstances.size(); i++) + { + if (slotKeyAt(i) == slotKey) + { + return m_ViewModelInstances[i]; + } + } + return nullptr; +} + +void DataContext::removeMainViewModelInstance() +{ + for (size_t i = 0; i < m_ViewModelInstances.size();) + { + if (slotKeyAt(i) == kNoSlot) + { + removeInstanceAt(i); + } + else + { + i++; + } + } +} + +void DataContext::setMainViewModelInstance(rcp<ViewModelInstance> value) +{ + // Drop any existing main (unslotted) entries, then place the new main at + // the front so resolution order is [main, globals...]. + removeMainViewModelInstance(); + if (value != nullptr) + { + // Main is not on the slot keys. + insertInstanceAt(0, std::move(value), kNoSlot); + } +} + +rcp<ViewModelInstance> DataContext::mainViewModelInstance() const +{ + for (size_t i = 0; i < m_ViewModelInstances.size(); i++) + { + if (slotKeyAt(i) == kNoSlot) + { + return m_ViewModelInstances[i]; + } + } + return nullptr; +} + +void DataContext::advanced() +{ + for (auto& vmi : m_ViewModelInstances) + { + vmi->advanced(); + } +} + +// --- Private helpers: try resolution against a single instance --- + +ViewModelInstanceValue* DataContext::tryGetViewModelProperty( + rcp<ViewModelInstance> instance, + const std::vector<uint32_t>& path) const +{ + if (instance == nullptr || instance->viewModelId() != path[0]) + { + return nullptr; + } + if (path.size() == 1) + { + return nullptr; + } + rcp<ViewModelInstance> current = instance; + for (auto it = path.begin() + 1; it != path.end() - 1; it++) + { + auto viewModelInstanceValue = current->propertyValue(*it); + if (viewModelInstanceValue != nullptr && + viewModelInstanceValue->is<ViewModelInstanceViewModel>()) + { + current = viewModelInstanceValue->as<ViewModelInstanceViewModel>() + ->referenceViewModelInstance(); + if (current == nullptr) + { + return nullptr; + } + } + else + { + return nullptr; + } + } + return current->propertyValue(path.back()); +} + +ViewModelInstanceValue* DataContext::tryGetRelativeViewModelProperty( + rcp<ViewModelInstance> instance, + const std::vector<uint32_t>& path, + DataResolver* resolver) const +{ + if (instance == nullptr) + { + return nullptr; + } + rcp<ViewModelInstance> current = instance; + if (path.size() == 1) + { + return current->propertyValue(resolver->resolveName(path[0])); + } + for (auto it = path.begin(); it != path.end() - 1; it++) + { + auto viewModelInstanceValue = + current->propertyValue(resolver->resolveName(*it)); + if (viewModelInstanceValue != nullptr && + viewModelInstanceValue->is<ViewModelInstanceViewModel>()) + { + current = viewModelInstanceValue->as<ViewModelInstanceViewModel>() + ->referenceViewModelInstance(); + if (current == nullptr) + { + return nullptr; + } + } + else + { + return nullptr; + } + } + return current->propertyValue(resolver->resolveName(path.back())); +} + +rcp<ViewModelInstance> DataContext::tryGetViewModelInstance( + rcp<ViewModelInstance> instance, + const std::vector<uint32_t>& path) const +{ + if (instance == nullptr || instance->viewModelId() != path[0]) + { + return nullptr; + } + rcp<ViewModelInstance> current = instance; + for (auto it = path.begin() + 1; it != path.end(); it++) + { + auto viewModelInstanceValue = current->propertyValue(*it); + if (viewModelInstanceValue != nullptr && + viewModelInstanceValue->is<ViewModelInstanceViewModel>()) + { + current = viewModelInstanceValue->as<ViewModelInstanceViewModel>() + ->referenceViewModelInstance(); + if (current == nullptr) + { + return nullptr; + } + } + else + { + return nullptr; + } + } + return current; +} + +rcp<ViewModelInstance> DataContext::tryGetRelativeViewModelInstance( + rcp<ViewModelInstance> instance, + const std::vector<uint32_t>& path, + DataResolver* resolver) const +{ + if (instance == nullptr) + { + return nullptr; + } + rcp<ViewModelInstance> current = instance; + for (auto it = path.begin(); it != path.end(); it++) + { + auto viewModelInstanceValue = + current->propertyValue(resolver->resolveName(*it)); + if (viewModelInstanceValue != nullptr && + viewModelInstanceValue->is<ViewModelInstanceViewModel>()) + { + current = viewModelInstanceValue->as<ViewModelInstanceViewModel>() + ->referenceViewModelInstance(); + if (current == nullptr) + { + return nullptr; + } + } + else + { + return nullptr; + } + } + return current; +} + +// --- Public resolution methods: iterate instances, then fall to parent --- ViewModelInstanceValue* DataContext::getViewModelProperty( const std::vector<uint32_t> path) const { - std::vector<uint32_t>::const_iterator it; if (path.size() == 0) { return nullptr; } - if (m_ViewModelInstance != nullptr && - m_ViewModelInstance->viewModelId() == path[0]) + for (auto& instance : m_ViewModelInstances) { - if (path.size() == 1) + auto result = tryGetViewModelProperty(instance, path); + if (result != nullptr) { - return nullptr; + return result; } - rcp<ViewModelInstance> instance = m_ViewModelInstance; - for (it = path.begin() + 1; it != path.end() - 1; it++) - { - auto viewModelInstanceValue = instance->propertyValue(*it); - if (viewModelInstanceValue != nullptr && - viewModelInstanceValue->is<ViewModelInstanceViewModel>()) - { - instance = - viewModelInstanceValue->as<ViewModelInstanceViewModel>() - ->referenceViewModelInstance(); - if (instance == nullptr) - { - goto skip_path; - } - } - else - { - goto skip_path; - } - } - ViewModelInstanceValue* value = instance->propertyValue(*it++); - return value; } -skip_path: if (m_Parent != nullptr) { return m_Parent->getViewModelProperty(path); @@ -68,51 +422,18 @@ const std::vector<uint32_t> path, DataResolver* resolver) const { - std::vector<uint32_t>::const_iterator it; if (path.size() == 0 || !resolver) { return nullptr; } + for (auto& instance : m_ViewModelInstances) { - rcp<ViewModelInstance> instance = m_ViewModelInstance; - if (path.size() == 1) + auto result = tryGetRelativeViewModelProperty(instance, path, resolver); + if (result != nullptr) { - ViewModelInstanceValue* propertyValue = - instance->propertyValue(resolver->resolveName(path[0])); - if (propertyValue) - { - return propertyValue; - } - goto skip_relative_path; - } - for (it = path.begin(); it != path.end() - 1; it++) - { - auto viewModelInstanceValue = - instance->propertyValue(resolver->resolveName(*it)); - if (viewModelInstanceValue != nullptr && - viewModelInstanceValue->is<ViewModelInstanceViewModel>()) - { - instance = - viewModelInstanceValue->as<ViewModelInstanceViewModel>() - ->referenceViewModelInstance(); - if (instance == nullptr) - { - goto skip_relative_path; - } - } - else - { - goto skip_relative_path; - } - } - ViewModelInstanceValue* propertyValue = - instance->propertyValue(resolver->resolveName(*it++)); - if (propertyValue) - { - return propertyValue; + return result; } } -skip_relative_path: if (m_Parent != nullptr) { return m_Parent->getRelativeViewModelProperty(path, resolver); @@ -147,33 +468,14 @@ { return nullptr; } - std::vector<uint32_t>::const_iterator it; - if (m_ViewModelInstance != nullptr && - m_ViewModelInstance->viewModelId() == path[0]) + for (auto& instance : m_ViewModelInstances) { - rcp<ViewModelInstance> instance = m_ViewModelInstance; - for (it = path.begin() + 1; it != path.end(); it++) + auto result = tryGetViewModelInstance(instance, path); + if (result != nullptr) { - auto viewModelInstanceValue = instance->propertyValue(*it); - if (viewModelInstanceValue != nullptr && - viewModelInstanceValue->is<ViewModelInstanceViewModel>()) - { - instance = - viewModelInstanceValue->as<ViewModelInstanceViewModel>() - ->referenceViewModelInstance(); - } - else - { - instance = nullptr; - } - if (instance == nullptr) - { - goto skip_path; - } + return result; } - return instance; } -skip_path: if (m_Parent != nullptr) { return m_Parent->getViewModelInstance(path); @@ -189,33 +491,14 @@ { return nullptr; } - std::vector<uint32_t>::const_iterator it; - if (m_ViewModelInstance != nullptr) + for (auto& instance : m_ViewModelInstances) { - rcp<ViewModelInstance> instance = m_ViewModelInstance; - for (it = path.begin(); it != path.end(); it++) + auto result = tryGetRelativeViewModelInstance(instance, path, resolver); + if (result != nullptr) { - auto viewModelInstanceValue = - instance->propertyValue(resolver->resolveName(*it)); - if (viewModelInstanceValue != nullptr && - viewModelInstanceValue->is<ViewModelInstanceViewModel>()) - { - instance = - viewModelInstanceValue->as<ViewModelInstanceViewModel>() - ->referenceViewModelInstance(); - } - else - { - instance = nullptr; - } - if (instance == nullptr) - { - goto skip_path_relative; - } + return result; } - return instance; } -skip_path_relative: if (m_Parent != nullptr) { return m_Parent->getRelativeViewModelInstance(path, resolver); @@ -249,4 +532,4 @@ { return getViewModelInstance(dataBindPath->resolvedPath()); } -} \ No newline at end of file +}
diff --git a/src/file.cpp b/src/file.cpp index 9bb1150..9966c32 100644 --- a/src/file.cpp +++ b/src/file.cpp
@@ -95,6 +95,7 @@ #include "rive/viewmodel/viewmodel_property_trigger.hpp" #include "rive/viewmodel/viewmodel_property_symbol_list_index.hpp" #include "rive/viewmodel/runtime/viewmodel_runtime.hpp" +#include "rive/view_model_type.hpp" // Default namespace for Rive Cpp code using namespace rive; @@ -826,6 +827,11 @@ artboardInstance->scriptingVM(m_scriptingVM.get()); #endif artboardInstance->file(ref_rcp(this)); + + // Global view model instances are no longer auto-created here. Callers + // (e.g. the high-level runtime's autoBind, or explicit + // setGlobalViewModelInstance) create and bind them on demand. + return artboardInstance; } return nullptr; @@ -1299,7 +1305,7 @@ return nullptr; } -ViewModel* File::viewModel(size_t index) +ViewModel* File::viewModel(size_t index) const { if (index < m_ViewModels.size()) { @@ -1308,6 +1314,43 @@ return nullptr; } +uint32_t File::viewModelId(const std::string& name) const +{ + for (uint32_t i = 0; i < m_ViewModels.size(); i++) + { + auto vm = m_ViewModels[i]; + if (vm != nullptr && vm->name() == name) + { + return i; + } + } + return static_cast<uint32_t>(m_ViewModels.size()); +} + +std::vector<ViewModel*> File::globalViewModels() const +{ + std::vector<ViewModel*> viewModels; + for (ViewModel* vm : m_ViewModels) + { + if (vm != nullptr && static_cast<ViewModelType>(vm->viewModelType()) == + ViewModelType::global) + { + viewModels.push_back(vm); + } + } + return viewModels; +} + +std::vector<std::string> File::globalViewModelNames() const +{ + std::vector<std::string> names; + for (ViewModel* vm : globalViewModels()) + { + names.push_back(vm->name()); + } + return names; +} + ViewModelRuntime* File::viewModelByIndex(size_t index) const { if (index < m_ViewModels.size())
diff --git a/src/lua/lua_data_context.cpp b/src/lua/lua_data_context.cpp index a5298dc..c03f705 100644 --- a/src/lua/lua_data_context.cpp +++ b/src/lua/lua_data_context.cpp
@@ -29,7 +29,7 @@ int ScriptedDataContext::pushViewModel() { - auto vmi = m_dataContext->viewModelInstance(); + auto vmi = m_dataContext->mainViewModelInstance(); if (vmi) { lua_newrive<ScriptedViewModel>(m_state,
diff --git a/src/lua/lua_scripted_context.cpp b/src/lua/lua_scripted_context.cpp index fb15f14..aa87582 100644 --- a/src/lua/lua_scripted_context.cpp +++ b/src/lua/lua_scripted_context.cpp
@@ -131,9 +131,9 @@ if (m_scriptedObject) { auto dataContext = m_scriptedObject->dataContext(); - if (dataContext && dataContext->viewModelInstance()) + if (dataContext && dataContext->mainViewModelInstance()) { - auto viewModelInstance = dataContext->viewModelInstance(); + auto viewModelInstance = dataContext->mainViewModelInstance(); lua_newrive<ScriptedViewModel>( state, state,
diff --git a/src/nested_artboard.cpp b/src/nested_artboard.cpp index 9a5848b..01a8ec5 100644 --- a/src/nested_artboard.cpp +++ b/src/nested_artboard.cpp
@@ -11,11 +11,36 @@ #include "rive/data_bind/data_bind_path.hpp" #include "rive/clip_result.hpp" #include "rive/text/text_input.hpp" +#include "rive/view_model_type.hpp" +#include "rive/viewmodel/viewmodel.hpp" #include <limits> #include <cassert> using namespace rive; +namespace +{ +std::vector<rcp<ViewModelInstance>> buildVMIList( + const rcp<ViewModelInstance>& primary, + const std::vector<rcp<ViewModelInstance>>& globals) +{ + std::vector<rcp<ViewModelInstance>> list; + list.reserve((primary != nullptr ? 1 : 0) + globals.size()); + if (primary != nullptr) + { + list.push_back(primary); + } + for (auto& g : globals) + { + if (g != nullptr) + { + list.push_back(g); + } + } + return list; +} +} // namespace + NestedArtboard::NestedArtboard() {} NestedArtboard::~NestedArtboard() { @@ -44,6 +69,9 @@ m_activeViewModelInstance = nullptr; m_ownsActiveVmi = false; m_hasPendingStatefulBinding = false; + // Release our extra refs on the global VMI children (the artboard's + // m_Objects still holds its own ref for each). + m_globalViewModelInstances.clear(); } Core* NestedArtboard::clone() const @@ -120,13 +148,14 @@ void NestedArtboard::bindStateful() { m_hasPendingStatefulBinding = false; - bindArtboardInstance(m_activeViewModelInstance, m_dataContext); -} - -void NestedArtboard::bindArtboardInstance(ViewModelInstance* instance, - rcp<DataContext> parent) -{ - artboardInstance()->bindViewModelInstance(ref_rcp(instance), parent); + if (artboardInstance() == nullptr) + { + return; + } + // Active VMI is the local-root binding; append the global VMI children. + auto list = buildVMIList(ref_rcp(m_activeViewModelInstance), + m_globalViewModelInstances); + artboardInstance()->bindViewModelInstances(std::move(list), m_dataContext); for (auto& animation : m_NestedAnimations) { if (animation->is<NestedStateMachine>()) @@ -383,15 +412,35 @@ applyOriginOverride(); } - // ViewModelInstance children are only added to NestedArtboards - // that wrap a stateful component Artboard. We borrow the child VMI as the - // initial active binding; the parent Artboard's m_Objects teardown owns - // its lifetime. - if (auto vmi = findStatefulChildVmi()) + // ViewModelInstance children belong to NestedArtboards that wrap a + // stateful component Artboard. A single "standard" VMI becomes the active + // local-root binding (borrowed; the parent Artboard's m_Objects teardown + // owns its lifetime), and any number of "global" VMIs are appended to the + // data context passed down to the wrapped artboard. + for (auto child : children()) { - m_activeViewModelInstance = vmi; - m_ownsActiveVmi = false; + if (!child->is<ViewModelInstance>()) + { + continue; + } + auto vmi = child->as<ViewModelInstance>(); + auto vm = vmi->viewModel(); + auto type = vm != nullptr + ? static_cast<ViewModelType>(vm->viewModelType()) + : ViewModelType::standard; m_file->completeViewModelProperties(vmi); + if (type == ViewModelType::global) + { + // The artboard's m_Objects owns the construction ref; take an + // extra ref so the list outlives any teardown ordering. + m_globalViewModelInstances.push_back(ref_rcp(vmi)); + } + else if (m_activeViewModelInstance == nullptr) + { + // Borrow the first standard child VMI as the active binding. + m_activeViewModelInstance = vmi; + m_ownsActiveVmi = false; + } } tryScheduleBindStateful(); @@ -570,24 +619,41 @@ m_dataContext = value; m_viewModelInstance = nullptr; - if (artboardInstance() != nullptr) + if (artboardInstance() == nullptr) { - // If we have a stateful ViewModelInstance, bind it to the artboard - // instance. - if (tryScheduleBindStateful()) - { - return; - } + return; + } - // Non-stateful path: just propagate the data context. - artboardInstance()->internalDataContext(value); + // If we have a stateful ViewModelInstance, bind it (with globals) via + // the scheduled stateful path. + if (tryScheduleBindStateful()) + { + return; + } + + if (!m_globalViewModelInstances.empty()) + { + auto list = buildVMIList(nullptr, m_globalViewModelInstances); + artboardInstance()->bindViewModelInstances(std::move(list), value); for (auto& animation : m_NestedAnimations) { if (animation->is<NestedStateMachine>()) { - animation->as<NestedStateMachine>()->dataContext(value); + animation->as<NestedStateMachine>()->dataContext( + artboardInstance()->dataContext()); } } + return; + } + + // Non-stateful path with no globals: just propagate the data context. + artboardInstance()->internalDataContext(value); + for (auto& animation : m_NestedAnimations) + { + if (animation->is<NestedStateMachine>()) + { + animation->as<NestedStateMachine>()->dataContext(value); + } } } @@ -600,7 +666,7 @@ auto dataContext = instance->dataContext(); if (dataContext != nullptr) { - if (dataContext->viewModelInstance() != viewModelInstance) + if (dataContext->mainViewModelInstance() != viewModelInstance) { dataContext->viewModelInstance(viewModelInstance); } @@ -646,14 +712,55 @@ { m_dataContext = parent; m_viewModelInstance = viewModelInstance; - if (artboardInstance() != nullptr) + if (artboardInstance() == nullptr) { - // Stateful nested artboards must keep their own instance as the local - // root context, while the incoming instance remains the parent context. - ViewModelInstance* instanceToBind = m_activeViewModelInstance != nullptr - ? m_activeViewModelInstance - : viewModelInstance.get(); - bindArtboardInstance(instanceToBind, parent); + return; + } + + // Stateful: local root is the active VMI; append nested globals. + if (m_activeViewModelInstance != nullptr) + { + auto list = buildVMIList(ref_rcp(m_activeViewModelInstance), + m_globalViewModelInstances); + artboardInstance()->bindViewModelInstances(std::move(list), parent); + for (auto& animation : m_NestedAnimations) + { + if (animation->is<NestedStateMachine>()) + { + animation->as<NestedStateMachine>()->dataContext( + artboardInstance()->dataContext()); + } + } + return; + } + + // Non-stateful with a passed VMI or nested globals: build composite DC. + if (viewModelInstance != nullptr || !m_globalViewModelInstances.empty()) + { + auto list = buildVMIList(viewModelInstance, m_globalViewModelInstances); + artboardInstance()->bindViewModelInstances(std::move(list), parent); + for (auto& animation : m_NestedAnimations) + { + if (animation->is<NestedStateMachine>()) + { + animation->as<NestedStateMachine>()->dataContext( + artboardInstance()->dataContext()); + } + } + return; + } + + // Nothing to merge in — propagate parent context unchanged (legacy + // passthrough). Binding a null instance would call + // Artboard::bindViewModelInstance(nullptr, ...), which now triggers + // unbind(); use internalDataContext to keep the parent context wired. + artboardInstance()->internalDataContext(parent); + for (auto& animation : m_NestedAnimations) + { + if (animation->is<NestedStateMachine>()) + { + animation->as<NestedStateMachine>()->dataContext(parent); + } } }
diff --git a/src/viewmodel/viewmodel_instance.cpp b/src/viewmodel/viewmodel_instance.cpp index 3e6c0f4..a3578f5 100644 --- a/src/viewmodel/viewmodel_instance.cpp +++ b/src/viewmodel/viewmodel_instance.cpp
@@ -65,6 +65,44 @@ m_PropertyValues.push_back(rcp<ViewModelInstanceValue>(value)); } +bool ViewModelInstance::removeValue(uint32_t propertyId) +{ + for (auto it = m_PropertyValues.begin(); it != m_PropertyValues.end(); ++it) + { + auto value = *it; + if (value->viewModelPropertyId() != propertyId) + { + continue; + } + // Mirror the destructor cleanup for nested view model references. + if (value->is<ViewModelInstanceViewModel>()) + { + auto vmInstanceViewModel = value->as<ViewModelInstanceViewModel>(); + if (vmInstanceViewModel->referenceViewModelInstance()) + { + vmInstanceViewModel->referenceViewModelInstance()->removeParent( + this); + } + } + // Drop any symbol-table entry pointing at this value. + for (auto sit = m_propertySymbols.begin(); + sit != m_propertySymbols.end();) + { + if (sit->second == value.get()) + { + sit = m_propertySymbols.erase(sit); + } + else + { + ++sit; + } + } + m_PropertyValues.erase(it); // rcp releases the value + return true; + } + return false; +} + ViewModelInstanceValue* ViewModelInstance::propertyValue(const uint32_t id) { for (auto value : m_PropertyValues)
diff --git a/tests/unit_tests/assets/global_variables_test.riv b/tests/unit_tests/assets/global_variables_test.riv new file mode 100644 index 0000000..4124ef2 --- /dev/null +++ b/tests/unit_tests/assets/global_variables_test.riv Binary files differ
diff --git a/tests/unit_tests/assets/global_viewmodels_test.riv b/tests/unit_tests/assets/global_viewmodels_test.riv new file mode 100644 index 0000000..a56a7fd --- /dev/null +++ b/tests/unit_tests/assets/global_viewmodels_test.riv Binary files differ
diff --git a/tests/unit_tests/runtime/command_queue_test.cpp b/tests/unit_tests/runtime/command_queue_test.cpp index 28936bd..9599df8 100644 --- a/tests/unit_tests/runtime/command_queue_test.cpp +++ b/tests/unit_tests/runtime/command_queue_test.cpp
@@ -3848,8 +3848,9 @@ auto viewModel = server->getViewModelInstance(viewModelHandle); CHECK(viewModel != nullptr); - CHECK(stateMachine->artboard()->dataContext()->viewModelInstance() == - viewModel->instance()); + CHECK( + stateMachine->artboard()->dataContext()->mainViewModelInstance() == + viewModel->instance()); }); auto badInstanceHandle = @@ -6247,3 +6248,157 @@ } REQUIRE(comparedAny); } + +class GlobalNamesListener : public CommandQueue::FileListener +{ +public: + virtual void onGlobalViewModelNamesListed( + const FileHandle handle, + uint64_t requestId, + std::vector<std::string> names) override + { + m_handle = handle; + m_requestId = requestId; + m_names = std::move(names); + m_hasCallback = true; + } + + bool m_hasCallback = false; + FileHandle m_handle = RIVE_NULL_HANDLE; + uint64_t m_requestId = 0; + std::vector<std::string> m_names; +}; + +TEST_CASE("Global View Model Names Listed", "[CommandQueue]") +{ + auto commandQueue = make_rcp<CommandQueue>(); + std::thread serverThread(server_thread, commandQueue); + { + GlobalNamesListener listener; + std::ifstream stream("assets/global_variables_test.riv", + std::ios::binary); + FileHandle fileHandle = commandQueue->loadFile( + std::vector<uint8_t>(std::istreambuf_iterator<char>(stream), {}), + &listener); + + commandQueue->requestGlobalViewModelNames(fileHandle, 7); + + wait_for_server(commandQueue.get()); + commandQueue->processMessages(); + + CHECK(listener.m_hasCallback); + CHECK(listener.m_handle == fileHandle); + CHECK(listener.m_requestId == 7); + CHECK_FALSE(listener.m_names.empty()); + for (auto& name : listener.m_names) + { + CHECK_FALSE(name.empty()); + } + } + + // An invalid file yields no callback (file error instead). + { + GlobalNamesListener listener; + FileHandle fileHandle = + commandQueue->loadFile(std::vector<uint8_t>(1024 * 1024, {}), + &listener); + + commandQueue->requestGlobalViewModelNames(fileHandle, 8); + + wait_for_server(commandQueue.get()); + commandQueue->processMessages(); + + CHECK(!listener.m_hasCallback); + } + + commandQueue->disconnect(); + serverThread.join(); +} + +class GlobalInstanceListener : public CommandQueue::ViewModelInstanceListener +{ +public: + virtual void onViewModelInstanceViewModelNameReceived( + const ViewModelInstanceHandle handle, + uint64_t requestId, + std::string viewModelName) override + { + m_handle = handle; + m_viewModelName = viewModelName; + m_hasNameCallback = true; + } + + virtual void onViewModelInstanceError(const ViewModelInstanceHandle handle, + uint64_t requestId, + std::string error) override + { + m_handle = handle; + m_error = error; + m_hasErrorCallback = true; + } + + bool m_hasNameCallback = false; + bool m_hasErrorCallback = false; + ViewModelInstanceHandle m_handle = RIVE_NULL_HANDLE; + std::string m_viewModelName; + std::string m_error; +}; + +TEST_CASE("Set/Bind/Get Global View Model Instance", "[CommandQueue]") +{ + auto commandQueue = make_rcp<CommandQueue>(); + std::thread serverThread(server_thread, commandQueue); + + GlobalNamesListener fileListener; + std::ifstream stream("assets/global_variables_test.riv", std::ios::binary); + FileHandle fileHandle = commandQueue->loadFile( + std::vector<uint8_t>(std::istreambuf_iterator<char>(stream), {}), + &fileListener); + + // Discover a global view model name. + commandQueue->requestGlobalViewModelNames(fileHandle, 1); + wait_for_server(commandQueue.get()); + commandQueue->processMessages(); + REQUIRE(fileListener.m_hasCallback); + REQUIRE_FALSE(fileListener.m_names.empty()); + const std::string globalName = fileListener.m_names.front(); + + // Default artboard + state machine. + auto artboard = commandQueue->instantiateDefaultArtboard(fileHandle); + auto stateMachine = commandQueue->instantiateDefaultStateMachine(artboard); + + // Instantiate a default instance of the global view model, set it on the + // global slot, and apply with bind(). + auto globalVmi = + commandQueue->instantiateDefaultViewModelInstance(fileHandle, + globalName); + commandQueue->setGlobalViewModelInstance(stateMachine, + globalName, + globalVmi); + commandQueue->bind(stateMachine); + + // Reading the global back yields a handle to the bound instance; confirm it + // maps to the same global view model. + GlobalInstanceListener okListener; + auto fetched = commandQueue->globalViewModelInstance(stateMachine, + globalName, + &okListener); + commandQueue->requestViewModelInstanceViewModelName(fetched, 2); + + // Reading an unknown global name reports an error and maps nothing. + GlobalInstanceListener errListener; + commandQueue->globalViewModelInstance(stateMachine, + "not-a-global", + &errListener, + 3); + + wait_for_server(commandQueue.get()); + commandQueue->processMessages(); + + CHECK(okListener.m_hasNameCallback); + CHECK(okListener.m_viewModelName == globalName); + CHECK(errListener.m_hasErrorCallback); + + commandQueue->disconnect(); + serverThread.join(); +}
diff --git a/tests/unit_tests/runtime/component_list_test.cpp b/tests/unit_tests/runtime/component_list_test.cpp index 6724ba8..85eab36 100644 --- a/tests/unit_tests/runtime/component_list_test.cpp +++ b/tests/unit_tests/runtime/component_list_test.cpp
@@ -139,7 +139,8 @@ auto artboard = list->artboardInstance(i); REQUIRE(artboard != nullptr); auto context = artboard->dataContext(); - auto vmString = context->viewModelInstance()->propertyValue("Label"); + auto vmString = + context->mainViewModelInstance()->propertyValue("Label"); REQUIRE(vmString->is<rive::ViewModelInstanceString>()); REQUIRE( vmString->as<rive::ViewModelInstanceString>()->propertyValue() ==
diff --git a/tests/unit_tests/runtime/component_test.cpp b/tests/unit_tests/runtime/component_test.cpp index f8338dd..5a7c3c7 100644 --- a/tests/unit_tests/runtime/component_test.cpp +++ b/tests/unit_tests/runtime/component_test.cpp
@@ -573,7 +573,7 @@ REQUIRE(strokedAbInst != nullptr); auto strokedCtx = strokedAbInst->dataContext(); REQUIRE(strokedCtx != nullptr); - auto strokedVmi = strokedCtx->viewModelInstance(); + auto strokedVmi = strokedCtx->mainViewModelInstance(); REQUIRE(strokedVmi != nullptr); auto strokeWidthProp = strokedVmi->propertyValue("strokeWidth"); REQUIRE(strokeWidthProp != nullptr); @@ -598,7 +598,7 @@ REQUIRE(buttonAbInst != nullptr); auto buttonCtx = buttonAbInst->dataContext(); REQUIRE(buttonCtx != nullptr); - auto buttonVmi = buttonCtx->viewModelInstance(); + auto buttonVmi = buttonCtx->mainViewModelInstance(); REQUIRE(buttonVmi != nullptr); // Button's VM has count/tint/label/clipped/clicked/click but // does NOT have strokeWidth. @@ -629,7 +629,7 @@ REQUIRE(buttonAbInst3 != nullptr); auto buttonCtx3 = buttonAbInst3->dataContext(); REQUIRE(buttonCtx3 != nullptr); - auto buttonVmi3 = buttonCtx3->viewModelInstance(); + auto buttonVmi3 = buttonCtx3->mainViewModelInstance(); REQUIRE(buttonVmi3 != nullptr); CHECK(buttonVmi3->propertyValue("count") != nullptr); CHECK(buttonVmi3->propertyValue("strokeWidth") == nullptr); @@ -738,7 +738,7 @@ { return nullptr; } - return ctx->viewModelInstance().get(); + return ctx->mainViewModelInstance().get(); }; auto runFrames = [&](int n) {
diff --git a/tests/unit_tests/runtime/global_view_model_binding_test.cpp b/tests/unit_tests/runtime/global_view_model_binding_test.cpp new file mode 100644 index 0000000..1ec04d9 --- /dev/null +++ b/tests/unit_tests/runtime/global_view_model_binding_test.cpp
@@ -0,0 +1,299 @@ +#include "rive/file.hpp" +#include "rive/artboard.hpp" +#include "rive/animation/state_machine_instance.hpp" +#include "rive/data_bind/data_context.hpp" +#include "rive/viewmodel/viewmodel.hpp" +#include "rive/viewmodel/viewmodel_instance.hpp" +#include "rive/view_model_type.hpp" +#include "rive_file_reader.hpp" +#include <catch.hpp> +#include <vector> +#include <string> + +using namespace rive; + +namespace +{ +std::vector<std::string> boundNames(const DataContext* dc) +{ + std::vector<std::string> names; + if (dc == nullptr) + { + return names; + } + for (auto& vmi : dc->viewModelInstances()) + { + auto vm = vmi != nullptr ? vmi->viewModel() : nullptr; + names.push_back(vm != nullptr ? vm->name() : ""); + } + return names; +} +} // namespace + +// The file's global view model names are enumerable, in file order. +TEST_CASE("File::globalViewModelNames lists globals in file order", + "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto names = file->globalViewModelNames(); + REQUIRE_FALSE(names.empty()); + // Every listed name resolves to a global view model. + for (auto& name : names) + { + auto vm = file->viewModel(name); + REQUIRE(vm != nullptr); + REQUIRE(static_cast<ViewModelType>(vm->viewModelType()) == + ViewModelType::global); + } +} + +// Instancing no longer auto-creates globals — the data context starts empty. +TEST_CASE("artboard instancing does not auto-create globals", "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + REQUIRE(artboard->dataContext() == nullptr); +} + +// Getter is null-until-created; a global becomes readable only after it is set. +TEST_CASE("global getter is null until set", "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + auto names = file->globalViewModelNames(); + REQUIRE_FALSE(names.empty()); + const std::string target = names[0]; + + REQUIRE(artboard->globalViewModelInstance(target) == nullptr); + + auto instance = + file->createDefaultViewModelInstance(file->viewModel(target)); + REQUIRE(instance != nullptr); + REQUIRE(artboard->setGlobalViewModelInstance(target, instance)); + REQUIRE(artboard->globalViewModelInstance(target) == instance); + + // A non-global name is rejected and stays null. + REQUIRE_FALSE( + artboard->setGlobalViewModelInstance("not-a-global", instance)); + REQUIRE(artboard->globalViewModelInstance("not-a-global") == nullptr); +} + +// set* mutates the data context without applying; order is [main, globals...]. +TEST_CASE("set without bind mutates order; bind applies", "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + auto globalNames = file->globalViewModelNames(); + REQUIRE_FALSE(globalNames.empty()); + + auto mainVmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(mainVmi != nullptr); + auto mainVm = mainVmi->viewModel(); + REQUIRE(mainVm != nullptr); + REQUIRE(static_cast<ViewModelType>(mainVm->viewModelType()) != + ViewModelType::global); + + // Batch: set main + each global, then a single bind(). + artboard->setViewModelInstance(mainVmi); + for (auto& name : globalNames) + { + auto g = file->createDefaultViewModelInstance(file->viewModel(name)); + REQUIRE(artboard->setGlobalViewModelInstance(name, g)); + } + + // The data context already reflects the sets (getter reads pre-bind). + std::vector<std::string> expected; + expected.push_back(mainVm->name()); + for (auto& n : globalNames) + { + expected.push_back(n); + } + REQUIRE(boundNames(artboard->dataContext().get()) == expected); + + artboard->bind(); + // Order is unchanged after applying. + REQUIRE(boundNames(artboard->dataContext().get()) == expected); +} + +// Globals set out of order still land in file-definition order. +TEST_CASE("globals are ordered by file definition regardless of set order", + "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + auto globalNames = file->globalViewModelNames(); + // Need at least two globals to observe ordering. + REQUIRE(globalNames.size() >= 2); + + // Set them in reverse file order. + for (auto it = globalNames.rbegin(); it != globalNames.rend(); ++it) + { + auto g = file->createDefaultViewModelInstance(file->viewModel(*it)); + REQUIRE(artboard->setGlobalViewModelInstance(*it, g)); + } + + // The data context still lists them in file order. + REQUIRE(boundNames(artboard->dataContext().get()) == globalNames); + + // Setting a main afterwards keeps globals ordered, main first. + auto mainVmi = file->createDefaultViewModelInstance(artboard.get()); + if (mainVmi != nullptr && + static_cast<ViewModelType>(mainVmi->viewModel()->viewModelType()) != + ViewModelType::global) + { + artboard->setViewModelInstance(mainVmi); + std::vector<std::string> expected; + expected.push_back(mainVmi->viewModel()->name()); + for (auto& n : globalNames) + { + expected.push_back(n); + } + REQUIRE(boundNames(artboard->dataContext().get()) == expected); + } +} + +// bind() self-completes: binding only a main fills every global slot on the +// fly. +TEST_CASE("bind completes missing global slots on the fly", "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + + auto globalNames = file->globalViewModelNames(); + REQUIRE_FALSE(globalNames.empty()); + + // Bind only a main — no globals set explicitly. + auto mainVmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(mainVmi != nullptr); + stateMachine->bindViewModelInstance(mainVmi); + + // Every global slot has been completed by bind(). + for (auto& name : globalNames) + { + REQUIRE(stateMachine->globalViewModelInstance(name) != nullptr); + } + auto dc = stateMachine->dataContext(); + REQUIRE(dc != nullptr); + // [main, globals...] — main plus one instance per global slot. + REQUIRE(boundNames(dc.get()).size() == globalNames.size() + 1); +} + +// A slot is addressed by its name (file index), not by the instance's own view +// model, so an instance of a different view model can be placed on a slot. +TEST_CASE("slot accepts a different view model instance (override)", + "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + auto globalNames = file->globalViewModelNames(); + REQUIRE(globalNames.size() >= 2); + + const std::string slotA = globalNames[0]; + const std::string vmB = globalNames[1]; + + // An instance of view model B, placed onto slot A. + auto override = file->createDefaultViewModelInstance(file->viewModel(vmB)); + REQUIRE(override != nullptr); + REQUIRE(override->viewModel()->name() == vmB); + + // Previously rejected (name != instance's VM); now accepted. + REQUIRE(artboard->setGlobalViewModelInstance(slotA, override)); + + // Slot A resolves to the B-typed instance (addressed by slot, not by VM). + REQUIRE(artboard->globalViewModelInstance(slotA) == override); + // Occupancy is keyed by slot: B's own slot stays empty — the instance's own + // viewModelId does not place it into B's slot. + REQUIRE(artboard->globalViewModelInstance(vmB) == nullptr); +} + +// The state machine path exposes the same set/bind + get-by-name behavior. +TEST_CASE("state machine set/bind and get by name", "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + auto globalNames = file->globalViewModelNames(); + REQUIRE_FALSE(globalNames.empty()); + + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + + // Null until set. + REQUIRE(stateMachine->globalViewModelInstance(globalNames[0]) == nullptr); + + auto mainVmi = file->createDefaultViewModelInstance(artboard.get()); + stateMachine->setViewModelInstance(mainVmi); + for (auto& name : globalNames) + { + auto g = file->createDefaultViewModelInstance(file->viewModel(name)); + REQUIRE(stateMachine->setGlobalViewModelInstance(name, g)); + } + stateMachine->bind(); + + auto dc = stateMachine->dataContext(); + REQUIRE(dc != nullptr); + auto names = boundNames(dc.get()); + REQUIRE(names.size() == globalNames.size() + 1); + REQUIRE(names[0] == mainVmi->viewModel()->name()); + + auto fetched = stateMachine->globalViewModelInstance(globalNames[0]); + REQUIRE(fetched != nullptr); + REQUIRE(fetched->viewModel()->name() == globalNames[0]); + + // Replacing by name preserves position. + auto custom = + file->createDefaultViewModelInstance(file->viewModel(globalNames[0])); + REQUIRE(stateMachine->setGlobalViewModelInstance(globalNames[0], custom)); + REQUIRE(stateMachine->globalViewModelInstance(globalNames[0]) == custom); + REQUIRE(boundNames(stateMachine->dataContext().get()) == names); +} + +// A slot only exists for global view models: naming a real but non-global view +// model is rejected and nothing is slotted. +TEST_CASE("setGlobalViewModelInstance rejects a non-global name", "[viewmodel]") +{ + auto file = ReadRiveFile("assets/global_variables_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + + // Find a real view model that is not a global. + std::string nonGlobal; + for (size_t i = 0; i < file->viewModelCount(); i++) + { + auto vm = file->viewModel(i); + if (vm != nullptr && static_cast<ViewModelType>(vm->viewModelType()) != + ViewModelType::global) + { + nonGlobal = vm->name(); + break; + } + } + REQUIRE_FALSE(nonGlobal.empty()); + + auto instance = + file->createDefaultViewModelInstance(file->viewModel(nonGlobal)); + REQUIRE(instance != nullptr); + + // Rejected on both the artboard and the state machine paths; no slot + // filled. + REQUIRE_FALSE(artboard->setGlobalViewModelInstance(nonGlobal, instance)); + REQUIRE(artboard->globalViewModelInstance(nonGlobal) == nullptr); + REQUIRE_FALSE( + stateMachine->setGlobalViewModelInstance(nonGlobal, instance)); + REQUIRE(stateMachine->globalViewModelInstance(nonGlobal) == nullptr); +}
diff --git a/tests/unit_tests/runtime/global_viewmodels_test.cpp b/tests/unit_tests/runtime/global_viewmodels_test.cpp new file mode 100644 index 0000000..093b147 --- /dev/null +++ b/tests/unit_tests/runtime/global_viewmodels_test.cpp
@@ -0,0 +1,142 @@ +#include "rive/file.hpp" +#include "rive/animation/linear_animation.hpp" +#include "rive/animation/linear_animation_instance.hpp" +#include "rive/animation/state_machine_instance.hpp" +#include "rive/viewmodel/viewmodel.hpp" +#include "rive/viewmodel/runtime/viewmodel_runtime.hpp" +#include "rive/math/random.hpp" +#include "utils/serializing_factory.hpp" +#include "rive_file_reader.hpp" +#include <catch.hpp> +#include <cstdio> +#include <cstring> +#include "rive/profiler/profiler_macros.h" +#include <filesystem> +#include <fstream> +#include <iostream> + +using namespace rive; + +TEST_CASE("Global view models and overrides", "[silver]") +{ + SerializingFactory silver; + auto file = ReadRiveFile("assets/global_variables_test.riv", &silver); + + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + silver.frameSize(artboard->width(), artboard->height()); + + auto stateMachine = artboard->stateMachineAt(0); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + + // Globals are no longer auto-created at instance time; create + set a + // default for each (as the high-level runtime's autoBind does), then apply + // everything with a single bind. + stateMachine->setViewModelInstance(vmi); + for (auto& name : file->globalViewModelNames()) + { + auto global = + file->createDefaultViewModelInstance(file->viewModel(name)); + REQUIRE(global != nullptr); + REQUIRE(stateMachine->setGlobalViewModelInstance(name, global)); + } + stateMachine->bind(); + stateMachine->advanceAndApply(0.1f); + auto renderer = silver.makeRenderer(); + artboard->draw(renderer.get()); + int frames = (int)(1.0f / 0.016f); + for (int i = 0; i < frames; i++) + { + silver.addFrame(); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + CHECK(silver.matches("global_variables_test")); +} + +TEST_CASE("Test global view models with automatic instancing", "[silver]") +{ + SerializingFactory silver; + auto file = ReadRiveFile("assets/global_viewmodels_test.riv", &silver); + + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + silver.frameSize(artboard->width(), artboard->height()); + + auto stateMachine = artboard->stateMachineAt(0); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + + auto renderer = silver.makeRenderer(); + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.0f); + artboard->draw(renderer.get()); + silver.addFrame(); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + + CHECK(silver.matches("global_viewmodels_test-auto_instance")); +} + +TEST_CASE("Test global view models with instance explicitly specified", + "[silver]") +{ + SerializingFactory silver; + auto file = ReadRiveFile("assets/global_viewmodels_test.riv", &silver); + + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + silver.frameSize(artboard->width(), artboard->height()); + + auto stateMachine = artboard->stateMachineAt(0); + auto renderer = silver.makeRenderer(); + + { + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + auto globalColorsVM = file->viewModel("GlobalColors"); + auto vmiColors = file->createDefaultViewModelInstance(globalColorsVM); + auto c1Prop = + vmiColors->propertyValue("c1")->as<ViewModelInstanceColor>(); + + auto yellowColor = (255 << 24) | (255 << 16) | (255 << 8); + c1Prop->propertyValue(yellowColor); + + stateMachine->setViewModelInstance(vmi); + stateMachine->setGlobalViewModelInstance("GlobalColors", vmiColors); + stateMachine->bind(); + } + + stateMachine->advanceAndApply(0.0f); + artboard->draw(renderer.get()); + + silver.addFrame(); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + + { + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + auto labelProp = + vmi->propertyValue("label")->as<ViewModelInstanceString>(); + labelProp->propertyValue("label updated"); + auto globalColorsVM = file->viewModel("GlobalColors"); + auto vmiColors = file->createDefaultViewModelInstance(globalColorsVM); + auto c1Prop = + vmiColors->propertyValue("c1")->as<ViewModelInstanceColor>(); + + auto cyanColor = (255 << 24) | (255 << 8) | 255; + c1Prop->propertyValue(cyanColor); + + stateMachine->setGlobalViewModelInstance("GlobalColors", vmiColors); + stateMachine->setViewModelInstance(vmi); + stateMachine->bind(); + } + silver.addFrame(); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + + CHECK(silver.matches("global_viewmodels_test-set_instance")); +} \ No newline at end of file
diff --git a/tests/unit_tests/runtime/viewmodel_instance_prune_test.cpp b/tests/unit_tests/runtime/viewmodel_instance_prune_test.cpp new file mode 100644 index 0000000..af020b7 --- /dev/null +++ b/tests/unit_tests/runtime/viewmodel_instance_prune_test.cpp
@@ -0,0 +1,88 @@ +#include "rive/viewmodel/viewmodel_instance.hpp" +#include "rive/viewmodel/viewmodel_instance_number.hpp" +#include "rive/data_bind/data_context.hpp" +#include "rive/refcnt.hpp" +#include <catch.hpp> + +using namespace rive; + +namespace +{ +// Builds a number value with the given runtime property id and value. +ViewModelInstanceNumber* makeNumber(uint32_t propertyId, float value) +{ + auto* number = new ViewModelInstanceNumber(); + number->viewModelPropertyId(propertyId); + number->propertyValue(value); + return number; +} + +// Builds an instance for view model `viewModelId` holding the given numbers. +rcp<ViewModelInstance> makeInstance( + uint32_t viewModelId, + std::vector<ViewModelInstanceNumber*> numbers) +{ + auto instance = make_rcp<ViewModelInstance>(); + instance->viewModelId(viewModelId); + for (auto* number : numbers) + { + instance->addValue(number); + } + return instance; +} +} // namespace + +TEST_CASE("removeValue removes only the matching property", + "[viewmodel_instance]") +{ + auto instance = + makeInstance(7, {makeNumber(100, 1.0f), makeNumber(200, 2.0f)}); + + REQUIRE(instance->propertyValue(100u) != nullptr); + REQUIRE(instance->propertyValue(200u) != nullptr); + + // Removing an absent id reports nothing removed and leaves both values. + CHECK(instance->removeValue(999u) == false); + CHECK(instance->propertyValue(100u) != nullptr); + CHECK(instance->propertyValue(200u) != nullptr); + + // Removing a present id reports success and drops only that value. + CHECK(instance->removeValue(200u) == true); + CHECK(instance->propertyValue(200u) == nullptr); + CHECK(instance->propertyValue(100u) != nullptr); +} + +TEST_CASE("Sparse override instance falls through to parent for non-overridden " + "properties", + "[viewmodel_instance]") +{ + // Parent context: both properties resolve to their parent values. + auto parentInstance = + makeInstance(7, {makeNumber(100, 10.0f), makeNumber(200, 20.0f)}); + auto parentContext = make_rcp<DataContext>(parentInstance); + + // Child (override) context: a full copy that is then pruned down to only + // property 100 (the explicitly-overridden property), matching what the + // editor does for a sparse nested-artboard override instance. + auto childInstance = + makeInstance(7, {makeNumber(100, 99.0f), makeNumber(200, 88.0f)}); + childInstance->removeValue(200u); // prune the non-overridden property + + auto childContext = make_rcp<DataContext>(childInstance); + childContext->parent(parentContext); + + // Property 100 is present on the override → resolves to the override value. + auto* resolvedA = childContext->getViewModelProperty({7u, 100u}); + REQUIRE(resolvedA != nullptr); + CHECK(resolvedA->as<ViewModelInstanceNumber>()->propertyValue() == + Approx(99.0f)); + + // Property 200 was pruned → resolution must fall through to the parent + // value instead of returning the override's (default) copy. This is the + // regression guard: before the fix the override carried every property and + // this returned 88.0f, leaking the override onto a non-overridden property. + auto* resolvedB = childContext->getViewModelProperty({7u, 200u}); + REQUIRE(resolvedB != nullptr); + CHECK(resolvedB->as<ViewModelInstanceNumber>()->propertyValue() == + Approx(20.0f)); +}
diff --git a/tests/unit_tests/silvers/global_variables_test.sriv b/tests/unit_tests/silvers/global_variables_test.sriv new file mode 100644 index 0000000..c243fe0 --- /dev/null +++ b/tests/unit_tests/silvers/global_variables_test.sriv Binary files differ
diff --git a/tests/unit_tests/silvers/global_viewmodels_test-auto_instance.sriv b/tests/unit_tests/silvers/global_viewmodels_test-auto_instance.sriv new file mode 100644 index 0000000..684a946 --- /dev/null +++ b/tests/unit_tests/silvers/global_viewmodels_test-auto_instance.sriv Binary files differ
diff --git a/tests/unit_tests/silvers/global_viewmodels_test-set_instance.sriv b/tests/unit_tests/silvers/global_viewmodels_test-set_instance.sriv new file mode 100644 index 0000000..2d5e1e8 --- /dev/null +++ b/tests/unit_tests/silvers/global_viewmodels_test-set_instance.sriv Binary files differ
diff --git a/tests/unit_tests/silvers/script_affects_has_changed.sriv b/tests/unit_tests/silvers/script_affects_has_changed.sriv index 6eb2df4..8506d98 100644 --- a/tests/unit_tests/silvers/script_affects_has_changed.sriv +++ b/tests/unit_tests/silvers/script_affects_has_changed.sriv Binary files differ
diff --git a/tests/unit_tests/silvers/scripted_as_path.sriv b/tests/unit_tests/silvers/scripted_as_path.sriv index 690ccad..99b5020 100644 --- a/tests/unit_tests/silvers/scripted_as_path.sriv +++ b/tests/unit_tests/silvers/scripted_as_path.sriv Binary files differ
diff --git a/tests/unit_tests/silvers/scripting_linear_animation.sriv b/tests/unit_tests/silvers/scripting_linear_animation.sriv index 8c36765..d9aa0f8 100644 --- a/tests/unit_tests/silvers/scripting_linear_animation.sriv +++ b/tests/unit_tests/silvers/scripting_linear_animation.sriv Binary files differ