mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-21 08:02:39 +08:00
Replacing the Observer Pattern with the Event Pattern (#10551)
* Replacing the Observer Pattern with the Event Pattern * Fix callbacksinvoker interface * fix callbacksInvokder compilation error * Add remove event listener
This commit is contained in:
@@ -1520,6 +1520,12 @@ if(USE_PHYSICS_PHYSX)
|
||||
)
|
||||
endif()
|
||||
|
||||
##### core
|
||||
cocos_source_files(
|
||||
cocos/core/event/CallbacksInvoker.cpp
|
||||
cocos/core/event/CallbacksInvoker.h
|
||||
)
|
||||
|
||||
##### script bindings
|
||||
######## dop
|
||||
cocos_source_files(
|
||||
|
||||
@@ -46,14 +46,26 @@ CocosApplication::CocosApplication() {
|
||||
CCASSERT(_systemWidow != nullptr, "Invalid interface pointer");
|
||||
}
|
||||
|
||||
CocosApplication::~CocosApplication() = default;
|
||||
CocosApplication::~CocosApplication() {
|
||||
_engine->off(BaseEngine::ON_RESUME);
|
||||
_engine->off(BaseEngine::ON_PAUSE);
|
||||
_engine->off(BaseEngine::ON_CLOSE);
|
||||
}
|
||||
|
||||
int CocosApplication::init() {
|
||||
if (_engine->init()) {
|
||||
return -1;
|
||||
}
|
||||
auto callback = std::bind(&CocosApplication::handleAppEvent, this, std::placeholders::_1); // NOLINT(modernize-avoid-bind)
|
||||
_engine->addEventCallback(OSEventType::APP_OSEVENT, callback);
|
||||
|
||||
_engine->on(BaseEngine::ON_RESUME, [this]() {
|
||||
this->onResume();
|
||||
});
|
||||
_engine->on(BaseEngine::ON_PAUSE, [this]() {
|
||||
this->onPause();
|
||||
});
|
||||
_engine->on(BaseEngine::ON_CLOSE, [this]() {
|
||||
this->onClose();
|
||||
});
|
||||
|
||||
se::ScriptEngine *se = se::ScriptEngine::getInstance();
|
||||
|
||||
@@ -146,21 +158,4 @@ void CocosApplication::createWindow(const char *title,
|
||||
}
|
||||
#endif
|
||||
|
||||
void CocosApplication::handleAppEvent(const OSEvent &ev) {
|
||||
const AppEvent &appEv = OSEvent::castEvent<AppEvent>(ev);
|
||||
switch (appEv.type) {
|
||||
case AppEvent::Type::RESUME:
|
||||
onResume();
|
||||
break;
|
||||
case AppEvent::Type::PAUSE:
|
||||
onPause();
|
||||
break;
|
||||
case AppEvent::Type::CLOSE:
|
||||
onClose();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -123,8 +123,6 @@ public:
|
||||
virtual void setXXTeaKey(const std::string& key);
|
||||
|
||||
private:
|
||||
void handleAppEvent(const OSEvent& ev);
|
||||
|
||||
ISystemWindow* _systemWidow{nullptr};
|
||||
BaseEngine::Ptr _engine{nullptr};
|
||||
};
|
||||
|
||||
@@ -35,6 +35,7 @@ using ulong = std::uint32_t;
|
||||
#endif
|
||||
using FlagBits = std::uint32_t;
|
||||
|
||||
using index_t = int32_t;
|
||||
#define CC_ENUM_CONVERSION_OPERATOR(T) \
|
||||
inline std::underlying_type<T>::type toNumber(const T v) { return static_cast<std::underlying_type<T>::type>(v); }
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <bitset>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
@@ -125,5 +126,95 @@ inline uint toUint(T value) {
|
||||
return static_cast<uint>(value);
|
||||
}
|
||||
|
||||
template <typename Map>
|
||||
Map &mergeToMap(Map &outMap, const Map &inMap) {
|
||||
for (const auto &e : inMap) {
|
||||
outMap.emplace(e.first, e.second);
|
||||
}
|
||||
return outMap;
|
||||
}
|
||||
|
||||
namespace array {
|
||||
|
||||
/**
|
||||
* @zh
|
||||
* 移除首个指定的数组元素。判定元素相等时相当于于使用了 `Array.prototype.indexOf`。
|
||||
* @en
|
||||
* Removes the first occurrence of a specific object from the array.
|
||||
* Decision of the equality of elements is similar to `Array.prototype.indexOf`.
|
||||
* @param array 数组。
|
||||
* @param value 待移除元素。
|
||||
*/
|
||||
template <typename T>
|
||||
bool remove(std::vector<T> &array, T value) {
|
||||
auto iter = std::find(array.begin(), array.end(), value);
|
||||
if (iter != array.end()) {
|
||||
array.erase(iter);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh
|
||||
* 移除指定索引的数组元素。
|
||||
* @en
|
||||
* Removes the array item at the specified index.
|
||||
* @param array 数组。
|
||||
* @param index 待移除元素的索引。
|
||||
*/
|
||||
template <typename T>
|
||||
bool removeAt(std::vector<T> &array, int32_t index) {
|
||||
if (index >= 0 && index < static_cast<int32_t>(array.size())) {
|
||||
array.erase(array.begin() + index);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh
|
||||
* 移除指定索引的数组元素。
|
||||
* 此函数十分高效,但会改变数组的元素次序。
|
||||
* @en
|
||||
* Removes the array item at the specified index.
|
||||
* It's faster but the order of the array will be changed.
|
||||
* @param array 数组。
|
||||
* @param index 待移除元素的索引。
|
||||
*/
|
||||
template <typename T>
|
||||
bool fastRemoveAt(std::vector<T> &array, int32_t index) {
|
||||
const auto length = static_cast<int32_t>(array.size());
|
||||
if (index < 0 || index >= length) {
|
||||
return false;
|
||||
}
|
||||
array[index] = array[length - 1];
|
||||
array.resize(length - 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh
|
||||
* 移除首个指定的数组元素。判定元素相等时相当于于使用了 `Array.prototype.indexOf`。
|
||||
* 此函数十分高效,但会改变数组的元素次序。
|
||||
* @en
|
||||
* Removes the first occurrence of a specific object from the array.
|
||||
* Decision of the equality of elements is similar to `Array.prototype.indexOf`.
|
||||
* It's faster but the order of the array will be changed.
|
||||
* @param array 数组。
|
||||
* @param value 待移除元素。
|
||||
*/
|
||||
template <typename T>
|
||||
bool fastRemove(std::vector<T> &array, T value) {
|
||||
auto iter = std::find(array.begin(), array.end(), value);
|
||||
if (iter != array.end()) {
|
||||
*iter = array[array.size() - 1];
|
||||
array.resize(array.size() - 1);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace array
|
||||
} // namespace utils
|
||||
} // namespace cc
|
||||
|
||||
@@ -68,18 +68,6 @@ private:
|
||||
#define CONSTRUCT_EVENT(name, type) \
|
||||
name() : OSEvent(type) {}
|
||||
|
||||
class AppEvent : public OSEvent {
|
||||
public:
|
||||
CONSTRUCT_EVENT(AppEvent, OSEventType::APP_OSEVENT)
|
||||
enum class Type {
|
||||
RUN = 0,
|
||||
PAUSE,
|
||||
RESUME,
|
||||
CLOSE,
|
||||
UNKNOWN,
|
||||
};
|
||||
Type type = Type::UNKNOWN;
|
||||
};
|
||||
|
||||
class WindowEvent : public OSEvent {
|
||||
public:
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "core/event/CallbacksInvoker.h"
|
||||
#include "base/Log.h"
|
||||
|
||||
namespace cc {
|
||||
|
||||
// NOTE: CCObject is not defined in engine 3.5, so make a fake one.
|
||||
bool isObjectValid(CCObject *value, bool strictMode/* = false*/) {
|
||||
CC_UNUSED_PARAM(value);
|
||||
CC_UNUSED_PARAM(strictMode);
|
||||
return true;
|
||||
}
|
||||
//
|
||||
|
||||
CallbackInfoBase::ID CallbacksInvoker::cbIDCounter{0};
|
||||
|
||||
void CallbackList::removeByCallbackID(CallbackInfoBase::ID cbID) {
|
||||
for (size_t i = 0; i < _callbackInfos.size(); ++i) {
|
||||
auto &info = _callbackInfos[i];
|
||||
if (info->_id == cbID) {
|
||||
utils::array::fastRemoveAt(_callbackInfos, static_cast<int32_t>(i));
|
||||
--i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CallbackList::removeByTarget(void *target) {
|
||||
for (size_t i = 0; i < _callbackInfos.size(); ++i) {
|
||||
auto &info = _callbackInfos[i];
|
||||
if (info->_target == target) {
|
||||
utils::array::fastRemoveAt(_callbackInfos, static_cast<int32_t>(i));
|
||||
--i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CallbackList::cancel(index_t index) {
|
||||
std::shared_ptr<CallbackInfoBase> *info = nullptr;
|
||||
if (index >= 0 && static_cast<size_t>(index) < _callbackInfos.size()) {
|
||||
info = &_callbackInfos[index];
|
||||
}
|
||||
|
||||
if (info) {
|
||||
if (_isInvoking) {
|
||||
_callbackInfos[index] = nullptr;
|
||||
} else {
|
||||
utils::array::fastRemoveAt(_callbackInfos, index);
|
||||
}
|
||||
}
|
||||
_containCanceled = true;
|
||||
}
|
||||
|
||||
void CallbackList::cancelAll() {
|
||||
for (auto &callbackInfo : _callbackInfos) {
|
||||
callbackInfo = nullptr;
|
||||
}
|
||||
_containCanceled = true;
|
||||
}
|
||||
|
||||
void CallbackList::purgeCanceled() {
|
||||
for (index_t i = static_cast<index_t>(_callbackInfos.size()) - 1; i >= 0; --i) {
|
||||
const auto &info = _callbackInfos[i];
|
||||
if (!info) {
|
||||
utils::array::fastRemoveAt(_callbackInfos, i);
|
||||
}
|
||||
}
|
||||
_containCanceled = false;
|
||||
}
|
||||
|
||||
void CallbackList::clear() {
|
||||
cancelAll();
|
||||
_callbackInfos.clear();
|
||||
_isInvoking = false;
|
||||
_containCanceled = false;
|
||||
}
|
||||
|
||||
bool CallbacksInvoker::hasEventListener(const KeyType &key) const {
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter == _callbackTable.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto &list = iter->second;
|
||||
// check any valid callback
|
||||
const auto &infos = list._callbackInfos;
|
||||
// Make sure no cancelled callbacks
|
||||
if (list._isInvoking) {
|
||||
for (const auto &info : infos) { // NOLINT(readability-use-anyofallof)
|
||||
if (info != nullptr) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return !infos.empty();
|
||||
}
|
||||
|
||||
bool CallbacksInvoker::hasEventListener(const KeyType &key, CallbackInfoBase::ID cbID) const {
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter == _callbackTable.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto &list = iter->second;
|
||||
// check any valid callback
|
||||
const auto &infos = list._callbackInfos;
|
||||
|
||||
for (const auto &info : infos) { // NOLINT(readability-use-anyofallof)
|
||||
if (info != nullptr && info->check() && info->_id == cbID) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CallbacksInvoker::hasEventListener(const KeyType &key, void *target) {
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter == _callbackTable.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto &list = iter->second;
|
||||
// check any valid callback
|
||||
const auto &infos = list._callbackInfos;
|
||||
|
||||
for (const auto &info : infos) { // NOLINT(readability-use-anyofallof)
|
||||
if (info != nullptr && info->check() && info->_target == target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CallbacksInvoker::hasEventListener(const KeyType &key, void *target, CallbackInfoBase::ID cbID) const {
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter == _callbackTable.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto &list = iter->second;
|
||||
// check any valid callback
|
||||
const auto &infos = list._callbackInfos;
|
||||
|
||||
for (const auto &info : infos) { // NOLINT(readability-use-anyofallof)
|
||||
if (info != nullptr && info->check() && info->_target == target && info->_id == cbID) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void CallbacksInvoker::offAll(const KeyType &key) {
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter != _callbackTable.end()) {
|
||||
auto &list = iter->second;
|
||||
if (list._isInvoking) {
|
||||
list.cancelAll();
|
||||
} else {
|
||||
list.clear();
|
||||
_callbackTable.erase(iter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CallbacksInvoker::offAll(void *target) {
|
||||
for (auto &e : _callbackTable) {
|
||||
auto & list = e.second;
|
||||
const auto &infos = list._callbackInfos;
|
||||
if (list._isInvoking) {
|
||||
index_t i = 0;
|
||||
for (const auto &info : infos) {
|
||||
if (info != nullptr && info->_target == target) {
|
||||
list.cancel(i);
|
||||
}
|
||||
++i;
|
||||
}
|
||||
} else {
|
||||
list.removeByTarget(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CallbacksInvoker::offAll() {
|
||||
for (auto iter = _callbackTable.begin(); iter != _callbackTable.end();) {
|
||||
auto &list = iter->second;
|
||||
if (list._isInvoking) {
|
||||
list.cancelAll();
|
||||
++iter;
|
||||
} else {
|
||||
list.clear();
|
||||
iter = _callbackTable.erase(iter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CallbacksInvoker::off(const KeyType &key, CallbackInfoBase::ID cbID) {
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter != _callbackTable.end()) {
|
||||
auto & list = iter->second;
|
||||
const auto &infos = list._callbackInfos;
|
||||
index_t i = 0;
|
||||
for (const auto &info : infos) {
|
||||
if (info != nullptr && info->_id == cbID) {
|
||||
list.cancel(i);
|
||||
break;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CallbacksInvoker::offAll(const KeyType &key, void *target) {
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter != _callbackTable.end()) {
|
||||
auto & list = iter->second;
|
||||
const auto &infos = list._callbackInfos;
|
||||
index_t i = 0;
|
||||
if (list._isInvoking) {
|
||||
for (const auto &info : infos) {
|
||||
if (info != nullptr && info->_target == target) {
|
||||
list.cancel(i);
|
||||
}
|
||||
++i;
|
||||
}
|
||||
} else {
|
||||
list.removeByTarget(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CallbacksInvoker::off(CallbackInfoBase::ID cbID) {
|
||||
for (auto &cbInfo : _callbackTable) {
|
||||
auto & list = cbInfo.second;
|
||||
const auto &infos = list._callbackInfos;
|
||||
index_t i = 0;
|
||||
for (const auto &info : infos) {
|
||||
if (info != nullptr && info->_id == cbID) {
|
||||
list.cancel(i);
|
||||
break;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace cc
|
||||
@@ -0,0 +1,483 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2021 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <typeinfo>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "base/Log.h"
|
||||
#include "base/Macros.h"
|
||||
#include "base/Utils.h"
|
||||
//#include "core/data/Object.h"
|
||||
//#include "core/memop/Pool.h"
|
||||
|
||||
namespace cc {
|
||||
|
||||
#define CC_CALLBACK_INVOKE_0(__selector__, __target__, ...) std::function<void()>(std::bind(&__selector__, __target__, ##__VA_ARGS__)), __target__
|
||||
#define CC_CALLBACK_INVOKE_1(__selector__, __target__, Arg0, ...) std::function<void(Arg0)>(std::bind(&__selector__, __target__, std::placeholders::_1, ##__VA_ARGS__)), __target__
|
||||
#define CC_CALLBACK_INVOKE_2(__selector__, __target__, Arg0, Arg1, ...) std::function<void(Arg0, Arg1)>(std::bind(&__selector__, __target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__)), __target__
|
||||
#define CC_CALLBACK_INVOKE_3(__selector__, __target__, Arg0, Arg1, Arg2, ...) std::function<void(Arg0, Arg1, Arg2)>(std::bind(&__selector__, __target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)), __target__
|
||||
|
||||
// NOTE: CCObject is not defined in engine 3.5, so make a fake one.
|
||||
class CCObject {
|
||||
public:
|
||||
inline bool isObjectValid() const { return true; }// NOLINT(readability-convert-member-functions-to-static)
|
||||
};
|
||||
|
||||
bool isObjectValid(CCObject *value, bool strictMode = false);
|
||||
//
|
||||
|
||||
struct CallbackInfoBase {
|
||||
using ID = uint32_t;
|
||||
using FakeCallbackMemberFn = void (CCObject::*)();
|
||||
|
||||
CallbackInfoBase() = default;
|
||||
virtual ~CallbackInfoBase() = default;
|
||||
|
||||
virtual bool check() const = 0;
|
||||
virtual void reset() = 0;
|
||||
virtual FakeCallbackMemberFn getMemberFn() const = 0;
|
||||
|
||||
void *_target{nullptr};
|
||||
ID _id{0};
|
||||
bool _once{false};
|
||||
bool _isCCObject{false};
|
||||
#if CC_DEBUG
|
||||
std::vector<std::string> _argTypes;
|
||||
#endif
|
||||
};
|
||||
|
||||
template <typename... Args>
|
||||
struct CallbackInfo final : public CallbackInfoBase {
|
||||
using CallbackFn = std::function<void(Args...)>;
|
||||
using CallbackMemberFn = void (CCObject::*)(Args...);
|
||||
|
||||
CallbackFn _callback{nullptr};
|
||||
CallbackMemberFn _memberFn{nullptr};
|
||||
|
||||
template <typename Target>
|
||||
void set(CallbackFn &&callback, Target *target, bool once) {
|
||||
_callback = std::forward<CallbackFn>(callback);
|
||||
_target = target;
|
||||
_once = once;
|
||||
_isCCObject = std::is_base_of<CCObject, Target>::value;
|
||||
#if CC_DEBUG
|
||||
_argTypes = {(typeid(Args).name())...};
|
||||
#endif
|
||||
}
|
||||
|
||||
template <typename Target, typename = std::enable_if_t<std::is_base_of<CCObject, Target>::value>>
|
||||
void set(CallbackMemberFn memberFn, Target *target, bool once) {
|
||||
_memberFn = memberFn;
|
||||
_target = target;
|
||||
_once = once;
|
||||
_isCCObject = true;
|
||||
#if CC_DEBUG
|
||||
_argTypes = {(typeid(Args).name())...};
|
||||
#endif
|
||||
}
|
||||
|
||||
void reset() override {
|
||||
_callback = nullptr;
|
||||
_memberFn = nullptr;
|
||||
_target = nullptr;
|
||||
_once = false;
|
||||
_isCCObject = false;
|
||||
#if CC_DEBUG
|
||||
_argTypes.clear();
|
||||
#endif
|
||||
}
|
||||
|
||||
bool check() const override {
|
||||
// Validation
|
||||
if (_isCCObject) {
|
||||
if (!isObjectValid(reinterpret_cast<CCObject *>(_target), true)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
FakeCallbackMemberFn getMemberFn() const override {
|
||||
return reinterpret_cast<FakeCallbackMemberFn>(_memberFn);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @zh 事件监听器列表的简单封装。
|
||||
* @en A simple list of event callbacks
|
||||
*/
|
||||
class CallbackList final {
|
||||
public:
|
||||
std::vector<std::shared_ptr<CallbackInfoBase>> _callbackInfos;
|
||||
bool _isInvoking{false};
|
||||
bool _containCanceled{false};
|
||||
|
||||
/**
|
||||
* @zh 从列表中移除与指定目标相同回调函数的事件。
|
||||
* @en Remove the event listeners with the given callback from the list
|
||||
*
|
||||
* @param cbID - The callback id to be removed
|
||||
*/
|
||||
void removeByCallbackID(CallbackInfoBase::ID cbID);
|
||||
|
||||
/**
|
||||
* @zh 从列表中移除与指定目标相同调用者的事件。
|
||||
* @en Remove the event listeners with the given target from the list
|
||||
* @param target
|
||||
*/
|
||||
void removeByTarget(void *target);
|
||||
|
||||
/**
|
||||
* @zh 移除指定编号事件。
|
||||
* @en Remove the event listener at the given index
|
||||
* @param index
|
||||
*/
|
||||
void cancel(index_t index);
|
||||
|
||||
/**
|
||||
* @zh 注销所有事件。
|
||||
* @en Cancel all event listeners
|
||||
*/
|
||||
void cancelAll();
|
||||
|
||||
/**
|
||||
* @zh 立即删除所有取消的回调。(在移除过程中会更加紧凑的排列数组)
|
||||
* @en Delete all canceled callbacks and compact array
|
||||
*/
|
||||
void purgeCanceled();
|
||||
|
||||
/**
|
||||
* @zh 清除并重置所有数据。
|
||||
* @en Clear all data
|
||||
*/
|
||||
void clear();
|
||||
};
|
||||
|
||||
/**
|
||||
* @zh CallbacksInvoker 用来根据事件名(Key)管理事件监听器列表并调用回调方法。
|
||||
* @en CallbacksInvoker is used to manager and invoke event listeners with different event keys,
|
||||
* each key is mapped to a CallbackList.
|
||||
*/
|
||||
class CallbacksInvoker {
|
||||
public:
|
||||
using KeyType = uint32_t;
|
||||
CallbacksInvoker() = default;
|
||||
virtual ~CallbacksInvoker() = default;
|
||||
/**
|
||||
* @zh 向一个事件名注册一个新的事件监听器,包含回调函数和调用者
|
||||
* @en Register an event listener to a given event key with callback and target.
|
||||
*
|
||||
* @param key - Event type
|
||||
* @param callback - Callback function when event triggered
|
||||
* @param target - Callback callee
|
||||
* @param once - Whether invoke the callback only once (and remove it)
|
||||
*/
|
||||
template <typename Target, typename... Args>
|
||||
void on(const KeyType &key, void (Target::*memberFn)(Args...), Target *target, bool once = false);
|
||||
|
||||
template <typename Target, typename... Args>
|
||||
void on(const KeyType &key, std::function<void(Args...)> &&callback, Target *target, bool once = false);
|
||||
|
||||
template <typename... Args>
|
||||
void on(const KeyType &key, std::function<void(Args...)> &&callback, bool once = false);
|
||||
|
||||
template <typename Target, typename LambdaType>
|
||||
std::enable_if_t<!std::is_member_function_pointer<LambdaType>::value, void>
|
||||
on(const KeyType &key, LambdaType &&callback, Target *target, bool once = false);
|
||||
|
||||
template <typename LambdaType>
|
||||
std::enable_if_t<!std::is_member_function_pointer<LambdaType>::value, void>
|
||||
on(const KeyType &key, LambdaType &&callback, bool once = false);
|
||||
|
||||
//
|
||||
template <typename Target, typename... Args>
|
||||
void on(const KeyType &key, std::function<void(Args...)> &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once = false);
|
||||
|
||||
template <typename... Args>
|
||||
void on(const KeyType &key, std::function<void(Args...)> &&callback, CallbackInfoBase::ID &outCallbackID, bool once = false);
|
||||
|
||||
template <typename Target, typename LambdaType>
|
||||
std::enable_if_t<!std::is_member_function_pointer<LambdaType>::value, void>
|
||||
on(const KeyType &key, LambdaType &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once = false);
|
||||
|
||||
template <typename LambdaType>
|
||||
std::enable_if_t<!std::is_member_function_pointer<LambdaType>::value, void>
|
||||
on(const KeyType &key, LambdaType &&callback, CallbackInfoBase::ID &outCallbackID, bool once = false);
|
||||
|
||||
/**
|
||||
* @zh 检查指定事件是否已注册回调。
|
||||
* @en Checks whether there is correspond event listener registered on the given event
|
||||
* @param key - Event type
|
||||
* @param cbID - Callback ID
|
||||
*/
|
||||
bool hasEventListener(const KeyType &key) const;
|
||||
bool hasEventListener(const KeyType &key, CallbackInfoBase::ID cbID) const;
|
||||
bool hasEventListener(const KeyType &key, void *target);
|
||||
bool hasEventListener(const KeyType &key, void *target, CallbackInfoBase::ID cbID) const;
|
||||
template <typename Target, typename... Args>
|
||||
bool hasEventListener(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) const;
|
||||
/**
|
||||
* @zh 移除在特定事件类型中注册的所有回调或在某个目标中注册的所有回调。
|
||||
* @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target
|
||||
* @param key - The event type or target with which the listeners will be removed
|
||||
*/
|
||||
void offAll(const KeyType &key, void *target);
|
||||
void offAll(const KeyType &key);
|
||||
void offAll(void *target);
|
||||
void offAll();
|
||||
|
||||
/**
|
||||
* @zh 删除以指定事件,回调函数,目标注册的回调。
|
||||
* @en Remove event listeners registered with the given event key, callback and target
|
||||
* @param key - Event type
|
||||
* @param target callback Target
|
||||
* @param cbID - The callback ID of the event listener, if absent all event listeners for the given type will be removed
|
||||
*/
|
||||
void off(const KeyType &key, CallbackInfoBase::ID cbID);
|
||||
void off(CallbackInfoBase::ID cbID);
|
||||
template <typename Target, typename... Args>
|
||||
void off(const KeyType &key, void (Target::*memberFn)(Args...), Target *target);
|
||||
|
||||
/**
|
||||
* @zh 派发一个指定事件,并传递需要的参数
|
||||
* @en Trigger an event directly with the event name and necessary arguments.
|
||||
* @param key - event type
|
||||
* @param args - The arguments to be passed to the callback
|
||||
*/
|
||||
template <typename... Args>
|
||||
void emit(const KeyType &key, Args &&...args);
|
||||
|
||||
template <typename T>
|
||||
struct FunctionTraits
|
||||
: public FunctionTraits<decltype(&T::operator())> {
|
||||
};
|
||||
|
||||
template <typename ClassType, typename ReturnType, typename... Args>
|
||||
struct FunctionTraits<ReturnType (ClassType::*)(Args...) const> {
|
||||
using type = std::function<ReturnType(Args...)>;
|
||||
};
|
||||
|
||||
template <typename ClassType, typename ReturnType, typename... Args>
|
||||
struct FunctionTraits<ReturnType (ClassType::*)(Args...)> {
|
||||
using type = std::function<ReturnType(Args...)>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
static typename FunctionTraits<std::remove_reference_t<T>>::type toFunction(T &&l) {
|
||||
return typename FunctionTraits<std::remove_reference_t<T>>::type{std::forward<T>(l)};
|
||||
}
|
||||
|
||||
private:
|
||||
std::unordered_map<KeyType, CallbackList> _callbackTable;
|
||||
static CallbackInfoBase::ID cbIDCounter;
|
||||
};
|
||||
|
||||
template <typename Target, typename... Args>
|
||||
void CallbacksInvoker::on(const KeyType &key, void (Target::*memberFn)(Args...), Target *target, bool once) {
|
||||
static_assert(std::is_base_of<CCObject, Target>::value, "Target must be the subclass of CCObject");
|
||||
using CallbackInfoType = CallbackInfo<Args...>;
|
||||
auto &list = _callbackTable[key];
|
||||
auto info = std::make_shared<CallbackInfoType>();
|
||||
info->_id = ++cbIDCounter;
|
||||
CallbackInfoBase::ID cbID = info->_id;
|
||||
info->set(static_cast<typename CallbackInfoType::CallbackMemberFn>(memberFn), target, once);
|
||||
list._callbackInfos.emplace_back(std::move(info));
|
||||
}
|
||||
|
||||
template <typename Target, typename... Args>
|
||||
void CallbacksInvoker::on(const KeyType &key, std::function<void(Args...)> &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once) {
|
||||
auto &list = _callbackTable[key];
|
||||
auto info = std::make_shared<CallbackInfo<Args...>>();
|
||||
info->_id = ++cbIDCounter;
|
||||
CallbackInfoBase::ID cbID = info->_id;
|
||||
info->set(std::forward<std::function<void(Args...)>>(callback), target, once);
|
||||
list._callbackInfos.emplace_back(std::move(info));
|
||||
outCallbackID = cbID;
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void CallbacksInvoker::on(const KeyType &key, std::function<void(Args...)> &&callback, CallbackInfoBase::ID &outCallbackID, bool once) {
|
||||
on<std::nullptr_t>(key, std::forward<std::function<void(Args...)>>(callback), nullptr, outCallbackID, once);
|
||||
}
|
||||
|
||||
template <typename Target, typename LambdaType>
|
||||
std::enable_if_t<!std::is_member_function_pointer<LambdaType>::value, void>
|
||||
CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once) {
|
||||
on(key, toFunction(std::forward<LambdaType>(callback)), target, outCallbackID, once);
|
||||
}
|
||||
|
||||
template <typename LambdaType>
|
||||
std::enable_if_t<!std::is_member_function_pointer<LambdaType>::value, void>
|
||||
CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, CallbackInfoBase::ID &outCallbackID, bool once) {
|
||||
on(key, toFunction(std::forward<LambdaType>(callback)), outCallbackID, once);
|
||||
}
|
||||
|
||||
template <typename Target, typename... Args>
|
||||
void CallbacksInvoker::on(const KeyType &key, std::function<void(Args...)> &&callback, Target *target, bool once) {
|
||||
CallbackInfoBase::ID unusedID{0};
|
||||
on(key, callback, target, unusedID, once);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void CallbacksInvoker::on(const KeyType &key, std::function<void(Args...)> &&callback, bool once) {
|
||||
CallbackInfoBase::ID unusedID{0};
|
||||
on<std::nullptr_t>(key, std::forward<std::function<void(Args...)>>(callback), nullptr, unusedID, once);
|
||||
}
|
||||
|
||||
template <typename Target, typename LambdaType>
|
||||
std::enable_if_t<!std::is_member_function_pointer<LambdaType>::value, void>
|
||||
CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, bool once) {
|
||||
CallbackInfoBase::ID unusedID{0};
|
||||
on(key, toFunction(std::forward<LambdaType>(callback)), target, unusedID, once);
|
||||
}
|
||||
|
||||
template <typename LambdaType>
|
||||
std::enable_if_t<!std::is_member_function_pointer<LambdaType>::value, void>
|
||||
CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, bool once) {
|
||||
CallbackInfoBase::ID unusedID{0};
|
||||
on(key, toFunction(std::forward<LambdaType>(callback)), unusedID, once);
|
||||
}
|
||||
|
||||
template <typename Target, typename... Args>
|
||||
void CallbacksInvoker::off(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) {
|
||||
static_assert(std::is_base_of<CCObject, Target>::value, "Target must be the subclass of CCObject");
|
||||
using CallbackFn = void (CCObject::*)(Args...);
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter != _callbackTable.end()) {
|
||||
auto & list = iter->second;
|
||||
const auto &infos = list._callbackInfos;
|
||||
size_t i = 0;
|
||||
for (const auto &info : infos) { // NOLINT(readability-use-anyofallof)
|
||||
if (info != nullptr && reinterpret_cast<CallbackFn>(info->getMemberFn()) == memberFn && info->_target == target) {
|
||||
list.cancel(static_cast<int32_t>(i));
|
||||
break;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void CallbacksInvoker::emit(const KeyType &key, Args &&...args) {
|
||||
#if CC_DEBUG
|
||||
std::vector<std::string> argTypes{(typeid(Args).name())...};
|
||||
#endif
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter != _callbackTable.end()) {
|
||||
auto &list = iter->second;
|
||||
bool rootInvoker = !list._isInvoking;
|
||||
list._isInvoking = true;
|
||||
|
||||
auto &infos = list._callbackInfos;
|
||||
for (auto &i : infos) { // NOLINT(readability-use-anyofallof)
|
||||
auto &baseInfo = i;
|
||||
if (baseInfo == nullptr) {
|
||||
continue;
|
||||
}
|
||||
|
||||
#if CC_DEBUG
|
||||
CC_ASSERT(baseInfo->_argTypes.size() == argTypes.size());
|
||||
for (size_t i = 0, len = argTypes.size(); i < len; ++i) { // NOLINT(readability-use-anyofallof)
|
||||
if (baseInfo->_argTypes[i] != argTypes[i]) {
|
||||
CC_LOG_ERROR("Wrong argument type! baseInfo->_argTypes[%d]=%s, argTypes[%d]=%s", i, baseInfo->_argTypes[i].c_str(), i, argTypes[i].c_str());
|
||||
CC_ASSERT(false);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
using CallbackInfoType = CallbackInfo<Args...>;
|
||||
auto info = std::static_pointer_cast<CallbackInfoType>(i);
|
||||
if (info != nullptr) {
|
||||
if (info->_memberFn != nullptr && info->_target != nullptr) {
|
||||
auto memberFn = info->_memberFn;
|
||||
auto *target = reinterpret_cast<CCObject *>(info->_target);
|
||||
|
||||
// Pre off once callbacks to avoid influence on logic in callback
|
||||
if (info->_once) {
|
||||
off(key, memberFn, target);
|
||||
}
|
||||
// Lazy check validity of callback target,
|
||||
// if target is CCObject and is no longer valid, then remove the callback info directly
|
||||
if (!info->check()) {
|
||||
off(key, memberFn, target);
|
||||
} else {
|
||||
(target->*memberFn)(std::forward<Args>(args)...);
|
||||
}
|
||||
} else {
|
||||
const auto & callback = info->_callback;
|
||||
CallbackInfoBase::ID cbID = info->_id;
|
||||
// Pre off once callbacks to avoid influence on logic in callback
|
||||
if (info->_once) {
|
||||
off(key, cbID);
|
||||
}
|
||||
// Lazy check validity of callback target,
|
||||
// if target is CCObject and is no longer valid, then remove the callback info directly
|
||||
if (!info->check()) {
|
||||
off(key, cbID);
|
||||
} else {
|
||||
callback(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
CC_ASSERT(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (rootInvoker) {
|
||||
list._isInvoking = false;
|
||||
if (list._containCanceled) {
|
||||
list.purgeCanceled();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Target, typename... Args>
|
||||
bool CallbacksInvoker::hasEventListener(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) const {
|
||||
using CallbackFn = void (CCObject::*)(Args...);
|
||||
auto iter = _callbackTable.find(key);
|
||||
if (iter == _callbackTable.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto &list = iter->second;
|
||||
// check any valid callback
|
||||
const auto &infos = list._callbackInfos;
|
||||
|
||||
for (const auto &info : infos) { // NOLINT(readability-use-anyofallof)
|
||||
if (info != nullptr && info->check() && reinterpret_cast<CallbackFn>(info->getMemberFn()) == memberFn && info->_target == target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
using EventTarget = CallbacksInvoker;
|
||||
|
||||
} // namespace cc
|
||||
@@ -30,12 +30,21 @@
|
||||
#include "base/Scheduler.h"
|
||||
#include "base/TypeDef.h"
|
||||
#include "platform/BasePlatform.h"
|
||||
#include "core/event/CallbacksInvoker.h"
|
||||
|
||||
namespace cc {
|
||||
|
||||
class CC_DLL BaseEngine : public std::enable_shared_from_this<BaseEngine> {
|
||||
class CC_DLL BaseEngine : public CallbacksInvoker,
|
||||
public std::enable_shared_from_this<BaseEngine> {
|
||||
public:
|
||||
virtual ~BaseEngine();
|
||||
enum EngineStatus {
|
||||
ON_START,
|
||||
ON_PAUSE,
|
||||
ON_RESUME,
|
||||
ON_CLOSE,
|
||||
UNKNOWN,
|
||||
};
|
||||
~BaseEngine() override;
|
||||
using Ptr = std::shared_ptr<BaseEngine>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -250,7 +250,8 @@ int32_t Engine::restartVM() {
|
||||
|
||||
scriptEngine->cleanup();
|
||||
cc::EventDispatcher::destroy();
|
||||
|
||||
// remove all listening events
|
||||
offAll();
|
||||
// start
|
||||
cc::EventDispatcher::init();
|
||||
CC_CURRENT_APPLICATION()->init();
|
||||
@@ -299,7 +300,11 @@ bool Engine::dispatchWindowEvent(const WindowEvent& ev) {
|
||||
bool isHandled = false;
|
||||
if (ev.type == WindowEvent::Type::SHOW ||
|
||||
ev.type == WindowEvent::Type::RESTORED) {
|
||||
onResume();
|
||||
emit(static_cast<int>(ON_RESUME));
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
cc::EventDispatcher::dispatchRecreateWindowEvent();
|
||||
#endif
|
||||
cc::EventDispatcher::dispatchEnterForegroundEvent();
|
||||
isHandled = true;
|
||||
} else if (ev.type == WindowEvent::Type::SIZE_CHANGED ||
|
||||
ev.type == WindowEvent::Type::RESIZED) {
|
||||
@@ -307,13 +312,19 @@ bool Engine::dispatchWindowEvent(const WindowEvent& ev) {
|
||||
isHandled = true;
|
||||
} else if (ev.type == WindowEvent::Type::HIDDEN ||
|
||||
ev.type == WindowEvent::Type::MINIMIZED) {
|
||||
onPause();
|
||||
emit(static_cast<int>(ON_PAUSE));
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
cc::EventDispatcher::dispatchDestroyWindowEvent();
|
||||
#endif
|
||||
cc::EventDispatcher::dispatchEnterBackgroundEvent();
|
||||
isHandled = true;
|
||||
} else if (ev.type == WindowEvent::Type::CLOSE) {
|
||||
onClose();
|
||||
emit(static_cast<int>(ON_CLOSE));
|
||||
cc::EventDispatcher::dispatchCloseEvent();
|
||||
isHandled = true;
|
||||
} else if (ev.type == WindowEvent::Type::QUIT) {
|
||||
onClose();
|
||||
// There is no need to process the quit message,
|
||||
// the quit message is a custom message for the application
|
||||
isHandled = true;
|
||||
}
|
||||
return isHandled;
|
||||
@@ -328,32 +339,4 @@ bool Engine::dispatchEventToApp(OSEventType type, const OSEvent& ev) {
|
||||
return false;
|
||||
}
|
||||
|
||||
void Engine::onPause() {
|
||||
AppEvent appEv;
|
||||
appEv.type = AppEvent::Type::PAUSE;
|
||||
dispatchEventToApp(OSEventType::APP_OSEVENT, appEv);
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
cc::EventDispatcher::dispatchDestroyWindowEvent();
|
||||
#endif
|
||||
cc::EventDispatcher::dispatchEnterBackgroundEvent();
|
||||
}
|
||||
|
||||
void Engine::onResume() {
|
||||
AppEvent appEv;
|
||||
appEv.type = AppEvent::Type::RESUME;
|
||||
dispatchEventToApp(OSEventType::APP_OSEVENT, appEv);
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS
|
||||
cc::EventDispatcher::dispatchRecreateWindowEvent();
|
||||
#endif
|
||||
cc::EventDispatcher::dispatchEnterForegroundEvent();
|
||||
}
|
||||
|
||||
void Engine::onClose() {
|
||||
AppEvent appEv;
|
||||
appEv.type = AppEvent::Type::CLOSE;
|
||||
dispatchEventToApp(OSEventType::APP_OSEVENT, appEv);
|
||||
|
||||
cc::EventDispatcher::dispatchCloseEvent();
|
||||
}
|
||||
|
||||
} // namespace cc
|
||||
|
||||
@@ -110,9 +110,6 @@ private:
|
||||
bool dispatchWindowEvent(const WindowEvent& ev);
|
||||
bool dispatchDeviceEvent(const DeviceEvent& ev);
|
||||
bool dispatchEventToApp(OSEventType type, const OSEvent& ev);
|
||||
void onPause();
|
||||
void onResume();
|
||||
void onClose();
|
||||
int32_t restartVM();
|
||||
|
||||
bool _close{false};
|
||||
|
||||
Reference in New Issue
Block a user