77 lines
2.4 KiB
C++
77 lines
2.4 KiB
C++
#include "Core/ObjectsContext.h"
|
|
#include <algorithm>
|
|
|
|
namespace uLib {
|
|
|
|
ObjectsContext::ObjectsContext() : Object() {}
|
|
|
|
ObjectsContext::~ObjectsContext() {}
|
|
|
|
void ObjectsContext::AddObject(Object* obj) {
|
|
if (obj) {
|
|
auto it = std::find_if(m_objects.begin(), m_objects.end(), [obj](const SmartPointer<Object>& sp) {
|
|
return sp.get() == obj;
|
|
});
|
|
if (it == m_objects.end()) {
|
|
m_objects.push_back(SmartPointer<Object>(obj));
|
|
// Connect child's update to context's update to trigger re-renders
|
|
Object::connect(obj, &Object::Updated, this, &Object::Updated);
|
|
ULIB_SIGNAL_EMIT(ObjectsContext::ObjectAdded, obj);
|
|
this->Updated(); // Signal that the context has been updated
|
|
}
|
|
}
|
|
}
|
|
|
|
void ObjectsContext::RemoveObject(Object* obj) {
|
|
auto it = std::find_if(m_objects.begin(), m_objects.end(), [obj](const SmartPointer<Object>& sp) {
|
|
return sp.get() == obj;
|
|
});
|
|
if (it != m_objects.end()) {
|
|
Object* removedObj = it->get();
|
|
// Since we are about to erase it from the vector, if it was the last reference
|
|
// it would be deleted. We might want to emit the signal BEFORE erasing.
|
|
ULIB_SIGNAL_EMIT(ObjectsContext::ObjectRemoved, removedObj);
|
|
m_objects.erase(it);
|
|
this->Updated(); // Signal that the context has been updated
|
|
}
|
|
}
|
|
|
|
void ObjectsContext::Clear() {
|
|
if (!m_objects.empty()) {
|
|
// Create a copy of the pointers to emit signals since m_objects might be modified or cleared
|
|
std::vector<Object*> toRemove;
|
|
for (const auto& sp : m_objects) toRemove.push_back(sp.get());
|
|
|
|
for (auto obj : toRemove) {
|
|
ULIB_SIGNAL_EMIT(ObjectsContext::ObjectRemoved, obj);
|
|
}
|
|
m_objects.clear();
|
|
this->Updated();
|
|
}
|
|
}
|
|
|
|
const std::vector<SmartPointer<Object>>& ObjectsContext::GetObjects() const {
|
|
return m_objects;
|
|
}
|
|
|
|
size_t ObjectsContext::GetCount() const {
|
|
return m_objects.size();
|
|
}
|
|
|
|
Object* ObjectsContext::GetObject(size_t index) const {
|
|
if (index < m_objects.size()) {
|
|
return m_objects[index].get();
|
|
}
|
|
return nullptr;
|
|
}
|
|
|
|
void ObjectsContext::ObjectAdded(Object* obj) {
|
|
ULIB_SIGNAL_EMIT(ObjectsContext::ObjectAdded, obj);
|
|
}
|
|
|
|
void ObjectsContext::ObjectRemoved(Object* obj) {
|
|
ULIB_SIGNAL_EMIT(ObjectsContext::ObjectRemoved, obj);
|
|
}
|
|
|
|
} // namespace uLib
|