diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index f78fe3e13e..6f3757bb31 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -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( diff --git a/native/cocos/application/CocosApplication.cpp b/native/cocos/application/CocosApplication.cpp index beddda60cb..bf69353b13 100644 --- a/native/cocos/application/CocosApplication.cpp +++ b/native/cocos/application/CocosApplication.cpp @@ -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(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 diff --git a/native/cocos/application/CocosApplication.h b/native/cocos/application/CocosApplication.h index df0951bfb5..1287aa5f0c 100644 --- a/native/cocos/application/CocosApplication.h +++ b/native/cocos/application/CocosApplication.h @@ -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}; }; diff --git a/native/cocos/base/TypeDef.h b/native/cocos/base/TypeDef.h index 33627fcf4a..abd9113f8c 100644 --- a/native/cocos/base/TypeDef.h +++ b/native/cocos/base/TypeDef.h @@ -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::type toNumber(const T v) { return static_cast::type>(v); } diff --git a/native/cocos/base/Utils.h b/native/cocos/base/Utils.h index 6688dbca9d..208303d3be 100644 --- a/native/cocos/base/Utils.h +++ b/native/cocos/base/Utils.h @@ -27,6 +27,7 @@ #pragma once +#include #include #include #include @@ -125,5 +126,95 @@ inline uint toUint(T value) { return static_cast(value); } +template +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 +bool remove(std::vector &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 +bool removeAt(std::vector &array, int32_t index) { + if (index >= 0 && index < static_cast(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 +bool fastRemoveAt(std::vector &array, int32_t index) { + const auto length = static_cast(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 +bool fastRemove(std::vector &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 diff --git a/native/cocos/bindings/event/EventDispatcher.h b/native/cocos/bindings/event/EventDispatcher.h index 9a279167dc..ab0fe9b610 100644 --- a/native/cocos/bindings/event/EventDispatcher.h +++ b/native/cocos/bindings/event/EventDispatcher.h @@ -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: diff --git a/native/cocos/core/event/CallbacksInvoker.cpp b/native/cocos/core/event/CallbacksInvoker.cpp new file mode 100644 index 0000000000..06de14e273 --- /dev/null +++ b/native/cocos/core/event/CallbacksInvoker.cpp @@ -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(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(i)); + --i; + } + } +} + +void CallbackList::cancel(index_t index) { + std::shared_ptr *info = nullptr; + if (index >= 0 && static_cast(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(_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 diff --git a/native/cocos/core/event/CallbacksInvoker.h b/native/cocos/core/event/CallbacksInvoker.h new file mode 100644 index 0000000000..164171c344 --- /dev/null +++ b/native/cocos/core/event/CallbacksInvoker.h @@ -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 +#include +#include +#include +#include + +#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(std::bind(&__selector__, __target__, ##__VA_ARGS__)), __target__ +#define CC_CALLBACK_INVOKE_1(__selector__, __target__, Arg0, ...) std::function(std::bind(&__selector__, __target__, std::placeholders::_1, ##__VA_ARGS__)), __target__ +#define CC_CALLBACK_INVOKE_2(__selector__, __target__, Arg0, Arg1, ...) std::function(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(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 _argTypes; +#endif +}; + +template +struct CallbackInfo final : public CallbackInfoBase { + using CallbackFn = std::function; + using CallbackMemberFn = void (CCObject::*)(Args...); + + CallbackFn _callback{nullptr}; + CallbackMemberFn _memberFn{nullptr}; + + template + void set(CallbackFn &&callback, Target *target, bool once) { + _callback = std::forward(callback); + _target = target; + _once = once; + _isCCObject = std::is_base_of::value; +#if CC_DEBUG + _argTypes = {(typeid(Args).name())...}; +#endif + } + + template ::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(_target), true)) { + return false; + } + } + return true; + } + + FakeCallbackMemberFn getMemberFn() const override { + return reinterpret_cast(_memberFn); + } +}; + +/** + * @zh 浜嬩欢鐩戝惉鍣ㄥ垪琛ㄧ殑绠�鍗曞皝瑁呫�� + * @en A simple list of event callbacks + */ +class CallbackList final { +public: + std::vector> _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 + void on(const KeyType &key, void (Target::*memberFn)(Args...), Target *target, bool once = false); + + template + void on(const KeyType &key, std::function &&callback, Target *target, bool once = false); + + template + void on(const KeyType &key, std::function &&callback, bool once = false); + + template + std::enable_if_t::value, void> + on(const KeyType &key, LambdaType &&callback, Target *target, bool once = false); + + template + std::enable_if_t::value, void> + on(const KeyType &key, LambdaType &&callback, bool once = false); + + // + template + void on(const KeyType &key, std::function &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once = false); + + template + void on(const KeyType &key, std::function &&callback, CallbackInfoBase::ID &outCallbackID, bool once = false); + + template + std::enable_if_t::value, void> + on(const KeyType &key, LambdaType &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once = false); + + template + std::enable_if_t::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 + 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 + 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 + void emit(const KeyType &key, Args &&...args); + + template + struct FunctionTraits + : public FunctionTraits { + }; + + template + struct FunctionTraits { + using type = std::function; + }; + + template + struct FunctionTraits { + using type = std::function; + }; + + template + static typename FunctionTraits>::type toFunction(T &&l) { + return typename FunctionTraits>::type{std::forward(l)}; + } + +private: + std::unordered_map _callbackTable; + static CallbackInfoBase::ID cbIDCounter; +}; + +template +void CallbacksInvoker::on(const KeyType &key, void (Target::*memberFn)(Args...), Target *target, bool once) { + static_assert(std::is_base_of::value, "Target must be the subclass of CCObject"); + using CallbackInfoType = CallbackInfo; + auto &list = _callbackTable[key]; + auto info = std::make_shared(); + info->_id = ++cbIDCounter; + CallbackInfoBase::ID cbID = info->_id; + info->set(static_cast(memberFn), target, once); + list._callbackInfos.emplace_back(std::move(info)); +} + +template +void CallbacksInvoker::on(const KeyType &key, std::function &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once) { + auto &list = _callbackTable[key]; + auto info = std::make_shared>(); + info->_id = ++cbIDCounter; + CallbackInfoBase::ID cbID = info->_id; + info->set(std::forward>(callback), target, once); + list._callbackInfos.emplace_back(std::move(info)); + outCallbackID = cbID; +} + +template +void CallbacksInvoker::on(const KeyType &key, std::function &&callback, CallbackInfoBase::ID &outCallbackID, bool once) { + on(key, std::forward>(callback), nullptr, outCallbackID, once); +} + +template +std::enable_if_t::value, void> +CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, CallbackInfoBase::ID &outCallbackID, bool once) { + on(key, toFunction(std::forward(callback)), target, outCallbackID, once); +} + +template +std::enable_if_t::value, void> +CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, CallbackInfoBase::ID &outCallbackID, bool once) { + on(key, toFunction(std::forward(callback)), outCallbackID, once); +} + +template +void CallbacksInvoker::on(const KeyType &key, std::function &&callback, Target *target, bool once) { + CallbackInfoBase::ID unusedID{0}; + on(key, callback, target, unusedID, once); +} + +template +void CallbacksInvoker::on(const KeyType &key, std::function &&callback, bool once) { + CallbackInfoBase::ID unusedID{0}; + on(key, std::forward>(callback), nullptr, unusedID, once); +} + +template +std::enable_if_t::value, void> +CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, bool once) { + CallbackInfoBase::ID unusedID{0}; + on(key, toFunction(std::forward(callback)), target, unusedID, once); +} + +template +std::enable_if_t::value, void> +CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, bool once) { + CallbackInfoBase::ID unusedID{0}; + on(key, toFunction(std::forward(callback)), unusedID, once); +} + +template +void CallbacksInvoker::off(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) { + static_assert(std::is_base_of::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(info->getMemberFn()) == memberFn && info->_target == target) { + list.cancel(static_cast(i)); + break; + } + ++i; + } + } +} + +template +void CallbacksInvoker::emit(const KeyType &key, Args &&...args) { +#if CC_DEBUG + std::vector 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; + auto info = std::static_pointer_cast(i); + if (info != nullptr) { + if (info->_memberFn != nullptr && info->_target != nullptr) { + auto memberFn = info->_memberFn; + auto *target = reinterpret_cast(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)...); + } + } 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)...); + } + } + } else { + CC_ASSERT(false); + } + } + + if (rootInvoker) { + list._isInvoking = false; + if (list._containCanceled) { + list.purgeCanceled(); + } + } + } +} + +template +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(info->getMemberFn()) == memberFn && info->_target == target) { + return true; + } + } + + return false; +} + +using EventTarget = CallbacksInvoker; + +} // namespace cc diff --git a/native/cocos/engine/BaseEngine.h b/native/cocos/engine/BaseEngine.h index 623b3ae5ba..9fc1fb15f1 100644 --- a/native/cocos/engine/BaseEngine.h +++ b/native/cocos/engine/BaseEngine.h @@ -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 { +class CC_DLL BaseEngine : public CallbacksInvoker, + public std::enable_shared_from_this { public: - virtual ~BaseEngine(); + enum EngineStatus { + ON_START, + ON_PAUSE, + ON_RESUME, + ON_CLOSE, + UNKNOWN, + }; + ~BaseEngine() override; using Ptr = std::shared_ptr; /** diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index fde25eac02..d6898d15e4 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -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(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(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(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 diff --git a/native/cocos/engine/Engine.h b/native/cocos/engine/Engine.h index 78de74c1ef..38f7739248 100644 --- a/native/cocos/engine/Engine.h +++ b/native/cocos/engine/Engine.h @@ -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};