diff --git a/native/cocos/base/CCEventDispatcher.cpp b/native/cocos/base/CCEventDispatcher.cpp index d458928f20..fdc9522b6a 100644 --- a/native/cocos/base/CCEventDispatcher.cpp +++ b/native/cocos/base/CCEventDispatcher.cpp @@ -191,12 +191,15 @@ void EventDispatcher::EventListenerVector::clear() EventDispatcher::EventDispatcher() : _inDispatch(0) -, _isEnabled(false) , _nodePriorityIndex(0) +, _isEnabled(false) { _toAddedListeners.reserve(50); _toRemovedListeners.reserve(50); + memset(_beforeDispatchEventHooks, 0, sizeof(_beforeDispatchEventHooks)); + memset(_afterDispatchEventHooks, 0, sizeof(_afterDispatchEventHooks)); + // fixed #4129: Mark the following listener IDs for internal use. // Therefore, internal listeners would not be cleaned when removeAllEventListeners is invoked. _internalCustomListenerIDs.insert(EVENT_COME_TO_FOREGROUND); @@ -803,6 +806,13 @@ void EventDispatcher::dispatchEvent(Event* event) if (!_isEnabled) return; + DispatchEventHook beforeDispatchHook = _beforeDispatchEventHooks[(int)event->getType()]; + DispatchEventHook afterDispatchHook = _afterDispatchEventHooks[(int)event->getType()]; + if (beforeDispatchHook != nullptr) + { + beforeDispatchHook(event); + } + updateDirtyFlagForSceneGraph(); DispatchGuard guard(_inDispatch); @@ -810,6 +820,11 @@ void EventDispatcher::dispatchEvent(Event* event) if (event->getType() == Event::Type::TOUCH) { dispatchTouchEvent(static_cast(event)); + updateListeners(event); + if (afterDispatchHook != nullptr) + { + afterDispatchHook(event); + } return; } @@ -832,6 +847,11 @@ void EventDispatcher::dispatchEvent(Event* event) updateListeners(event); } + + if (afterDispatchHook != nullptr) + { + afterDispatchHook(event); + } } void EventDispatcher::dispatchCustomEvent(const std::string &eventName, void *optionalUserData) @@ -873,6 +893,16 @@ bool EventDispatcher::hasEventListener(const EventListener::ListenerID& listener return true; } +void EventDispatcher::setBeforeDispatchEventHook(Event::Type type, const DispatchEventHook& hook) +{ + _beforeDispatchEventHooks[(int)type] = hook; +} + +void EventDispatcher::setAfterDispatchEventHook(Event::Type type, const DispatchEventHook& hook) +{ + _afterDispatchEventHooks[(int)type] = hook; +} + void EventDispatcher::dispatchTouchEvent(EventTouch* event) { sortEventListeners(EventListenerTouchOneByOne::LISTENER_ID); @@ -967,13 +997,6 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) } } - // If the event was stopped, return directly. - if (event->isStopped()) - { - updateListeners(event); - return true; - } - CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(), "touchesIter ID should be equal to mutableTouchesIter's ID."); @@ -987,15 +1010,20 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) return true; } + if (event->isStopped()) + { + // TouchOneByOne event is special, touchEvent->stopPropagation() should only affect current touch. + // Therefore, reset it to non-stopped state for next touch event handling and return true to stop + // current touch event propagation. + event->_isStopped = false; + return true; + } + return false; }; // dispatchEventToListeners(oneByOneListeners, onTouchEvent); - if (event->isStopped()) - { - return; - } if (!isSwallowed) ++mutableTouchesIter; @@ -1050,7 +1078,6 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) // If the event was stopped, return directly. if (event->isStopped()) { - updateListeners(event); return true; } @@ -1063,8 +1090,6 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) return; } } - - updateListeners(event); } void EventDispatcher::updateListeners(Event* event) diff --git a/native/cocos/base/CCEventDispatcher.h b/native/cocos/base/CCEventDispatcher.h index 0925c54abd..a40d54f9cd 100644 --- a/native/cocos/base/CCEventDispatcher.h +++ b/native/cocos/base/CCEventDispatcher.h @@ -185,6 +185,10 @@ public: */ bool hasEventListener(const EventListener::ListenerID& listenerID) const; + using DispatchEventHook = void (*)(Event*); + void setBeforeDispatchEventHook(Event::Type type, const DispatchEventHook& hook); + void setAfterDispatchEventHook(Event::Type type, const DispatchEventHook& hook); + ///////////////////////////////////////////// /** Constructor of EventDispatcher. @@ -328,15 +332,17 @@ protected: /** The nodes were associated with scene graph based priority listeners */ std::set _dirtyNodes; + std::set _internalCustomListenerIDs; + + static const int MAX_EVENT_TYPE = (int)Event::Type::CUSTOM + 1; + DispatchEventHook _beforeDispatchEventHooks[MAX_EVENT_TYPE]; + DispatchEventHook _afterDispatchEventHooks[MAX_EVENT_TYPE]; + /** Whether the dispatcher is dispatching event */ int _inDispatch; - + int _nodePriorityIndex; /** Whether to enable dispatching event */ bool _isEnabled; - - int _nodePriorityIndex; - - std::set _internalCustomListenerIDs; }; diff --git a/native/cocos/renderer/CCTextureCache.cpp b/native/cocos/renderer/CCTextureCache.cpp index bf915006d1..a9e1a745f2 100644 --- a/native/cocos/renderer/CCTextureCache.cpp +++ b/native/cocos/renderer/CCTextureCache.cpp @@ -56,8 +56,10 @@ TextureCache* TextureCache::getInstance() TextureCache::TextureCache() : _loadingThread(nullptr) -, _needQuit(false) +, _textureCreateHook(nullptr) +, _textureDestroyHook(nullptr) , _asyncRefCount(0) +, _needQuit(false) { } @@ -298,6 +300,9 @@ void TextureCache::addImageAsyncCallBack(float dt) texture->retain(); texture->autorelease(); + + if (_textureCreateHook != nullptr) + _textureCreateHook(this, texture); } else { texture = nullptr; CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str()); @@ -360,6 +365,9 @@ Texture2D * TextureCache::addImage(const std::string &path) // texture already retained, no need to re-retain it _textures.insert( std::make_pair(fullpath, texture) ); + if (_textureCreateHook != nullptr) + _textureCreateHook(this, texture); + //parse 9-patch info this->parseNinePatchImage(image, texture, path); } @@ -410,6 +418,9 @@ Texture2D* TextureCache::addImage(Image *image, const std::string &key) texture->retain(); texture->autorelease(); + + if (_textureCreateHook != nullptr) + _textureCreateHook(this, texture); } else { @@ -483,6 +494,9 @@ cocos2d::Vector TextureCache::getAllTextures() const void TextureCache::removeAllTextures() { for( auto it=_textures.begin(); it!=_textures.end(); ++it ) { + if (_textureDestroyHook != nullptr) + _textureDestroyHook(this, it->second); + (it->second)->release(); } _textures.clear(); @@ -494,6 +508,8 @@ void TextureCache::removeUnusedTextures() Texture2D *tex = it->second; if( tex->getReferenceCount() == 1 ) { CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str()); + if (_textureDestroyHook != nullptr) + _textureDestroyHook(this, tex); tex->release(); it = _textures.erase(it); @@ -514,6 +530,9 @@ void TextureCache::removeTexture(Texture2D* texture) for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */ ) { if( it->second == texture ) { + if (_textureDestroyHook != nullptr) + _textureDestroyHook(this, texture); + it->second->release(); it = _textures.erase(it); break; @@ -534,6 +553,9 @@ void TextureCache::removeTextureForKey(const std::string &textureKeyName) } if( it != _textures.end() ) { + if (_textureDestroyHook != nullptr) + _textureDestroyHook(this, it->second); + (it->second)->release(); _textures.erase(it); } @@ -657,6 +679,16 @@ void TextureCache::renameTextureWithKey(const std::string& srcName, const std::s } } +void TextureCache::setTextureCreateHook(TextureLifeCycleHook hook) +{ + _textureCreateHook = hook; +} + +void TextureCache::setTextureDestroyHook(TextureLifeCycleHook hook) +{ + _textureDestroyHook = hook; +} + #if CC_ENABLE_CACHE_TEXTURE_DATA std::list VolatileTextureMgr::_textures; diff --git a/native/cocos/renderer/CCTextureCache.h b/native/cocos/renderer/CCTextureCache.h index 52fdebd64b..73885d3050 100644 --- a/native/cocos/renderer/CCTextureCache.h +++ b/native/cocos/renderer/CCTextureCache.h @@ -212,6 +212,9 @@ public: */ void renameTextureWithKey(const std::string& srcName, const std::string& dstName); + using TextureLifeCycleHook = void (*)(TextureCache*, Texture2D*); + void setTextureCreateHook(TextureLifeCycleHook hook); + void setTextureDestroyHook(TextureLifeCycleHook hook); private: void addImageAsyncCallBack(float dt); @@ -221,8 +224,6 @@ public: protected: struct AsyncStruct; - std::thread* _loadingThread; - std::deque _asyncStructQueue; std::deque _requestQueue; std::deque _responseQueue; @@ -231,12 +232,15 @@ protected: std::mutex _responseMutex; std::condition_variable _sleepCondition; + std::unordered_map _textures; - bool _needQuit; + std::thread* _loadingThread; + + TextureLifeCycleHook _textureCreateHook; + TextureLifeCycleHook _textureDestroyHook; int _asyncRefCount; - - std::unordered_map _textures; + bool _needQuit; }; #if CC_ENABLE_CACHE_TEXTURE_DATA diff --git a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp index ce8095b74b..167c91c4f3 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_cocos2dx_manual.cpp @@ -11,6 +11,7 @@ #include "cocos/scripting/js-bindings/jswrapper/SeApi.h" #include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp" #include "cocos/scripting/js-bindings/manual/jsb_global.h" +#include "cocos/scripting/js-bindings/manual/ScriptingCore.h" #include "cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp" #include "cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.hpp" @@ -341,7 +342,7 @@ static bool invokeJSMouseCallback(EventListenerMouse* listener, const char* func SE_PRECONDITION2(ok, false, "invokeJSMouseCallback convert arg1 failed!"); if (!fromCache) - { + { // EventMouse is holded by CCGLView-desktop forever. So just root it once to make it never be garbage collected. arg1Val.toObject()->root(); } argArr.push_back(std::move(arg1Val)); @@ -433,28 +434,20 @@ static bool invokeJSTouchOneByOneCallback(EventListenerTouchOneByOne* listener, se::ValueArray argArr; argArr.reserve(2); se::Value arg1Val; - se::Object* arg1Obj = nullptr; do { ok = native_ptr_to_seval(touch, &arg1Val); SE_PRECONDITION_ERROR_BREAK(ok, "invokeJSTouchOneByOneCallback convert arg1 failed!"); - - arg1Obj = arg1Val.toObject(); - - if (type == TOUCH_ONE_BY_ONE_ON_TOUCH_BEGAN) - { - arg1Obj->root(); - } - argArr.push_back(std::move(arg1Val)); + bool fromCache = true; se::Value arg2Val; - bool eventFromCache = true; - ok = native_ptr_to_seval(event, &arg2Val, &eventFromCache); + ok = native_ptr_to_seval(event, &arg2Val, &fromCache); SE_PRECONDITION_ERROR_BREAK(ok, "invokeJSTouchOneByOneCallback convert arg2 failed!"); - if (!eventFromCache) + if (!fromCache) { + // EventTouch is holded by CCGLView forever. So just root it once to make it never be garbage collected. arg2Val.toObject()->root(); } @@ -468,18 +461,6 @@ static bool invokeJSTouchOneByOneCallback(EventListenerTouchOneByOne* listener, } while(false); - if (type == TOUCH_ONE_BY_ONE_ON_TOUCH_BEGAN) - { - if (!(retVal->isBoolean() && retVal->toBoolean())) - { - arg1Obj->unroot(); - } - } - else if (type == TOUCH_ONE_BY_ONE_ON_TOUCH_ENDED || type == TOUCH_ONE_BY_ONE_ON_TOUCH_CANCELLED) - { - arg1Obj->unroot(); - } - return ok; } @@ -553,14 +534,16 @@ static bool invokeJSTouchAllAtOnceCallback(EventListenerTouchAllAtOnce* listener SE_PRECONDITION2(ok, false, "invokeJSTouchAllAtOnceCallback convert arg1 failed!"); argArr.push_back(std::move(arg1Val)); + bool fromCache = true; se::Value arg2Val; - bool eventFromCache = true; - ok = native_ptr_to_seval(event, &arg2Val, &eventFromCache); + ok = native_ptr_to_seval(event, &arg2Val, &fromCache); SE_PRECONDITION2(ok, false, "invokeJSTouchAllAtOnceCallback convert arg2 failed!"); - if (!eventFromCache) + if (!fromCache) { + // EventTouch is holded by CCGLView forever. So just root it once to make it never be garbage collected. arg2Val.toObject()->root(); } + argArr.push_back(std::move(arg2Val)); ok = funcVal.toObject()->call(argArr, listenerObj, retVal); @@ -787,7 +770,7 @@ static bool js_EventListenerCustom_create(se::State& s) se::Value funcVal = args[1]; assert(funcVal.isObject() && funcVal.toObject()->isFunction()); - auto ret = new EventListenerCustom(); + auto ret = new (std::nothrow) EventListenerCustom(); ret->init(eventName, [ret, funcVal](EventCustom* event){ @@ -836,6 +819,93 @@ static bool js_EventListenerCustom_create(se::State& s) } SE_BIND_FUNC(js_EventListenerCustom_create) +static void onBeforeDispatchTouchEvent(Event* event) +{ + se::AutoHandleScope hs; + if (event->getType() == Event::Type::TOUCH) + { + EventTouch* touchEvent = static_cast(event); + if (touchEvent->getEventCode() == EventTouch::EventCode::BEGAN) + { + bool fromCache = true; + const auto& touches = touchEvent->getTouches(); + for (auto&& touch : touches) + { + se::Value touchVal; + native_ptr_to_seval(touch, __jsb_cocos2d_Touch_class, &touchVal, &fromCache); + assert(!fromCache); + touchVal.toObject()->root(); + } + } + } +} + +static void onAfterDispatchTouchEvent(Event* event) +{ + se::AutoHandleScope hs; + if (event->getType() == Event::Type::TOUCH) + { + EventTouch* touchEvent = static_cast(event); + EventTouch::EventCode code = touchEvent->getEventCode(); + if (code == EventTouch::EventCode::ENDED || code == EventTouch::EventCode::CANCELLED) + { + const auto& touches = touchEvent->getTouches(); + for (auto&& touch : touches) + { + auto iter = se::NativePtrToObjectMap::find(touch); + assert(iter != se::NativePtrToObjectMap::end()); + iter->second->unroot(); + } + } + } +} + +static void onTextureCreate(TextureCache* cache, Texture2D* texture) +{ + se::AutoHandleScope hs; + auto iterOwner = se::NativePtrToObjectMap::find(cache); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + assert(false); + return; + } + + se::Value textureVal; + bool fromCache = false; + native_ptr_to_seval(texture, __jsb_cocos2d_Texture2D_class, &textureVal, &fromCache); + if (!fromCache && textureVal.isObject()) + { + iterOwner->second->attachObject(textureVal.toObject()); + } + else + { + assert(false); + } +} + +static void onTextureDestroy(TextureCache* cache, Texture2D* texture) +{ + se::AutoHandleScope hs; + auto iterOwner = se::NativePtrToObjectMap::find(cache); + if (iterOwner == se::NativePtrToObjectMap::end()) + { + assert(false); + return; + } + + se::Value textureVal; + bool fromCache = false; + native_ptr_to_seval(texture, __jsb_cocos2d_Texture2D_class, &textureVal, &fromCache); + if (fromCache && textureVal.isObject()) + { + iterOwner->second->detachObject(textureVal.toObject()); + } + else + { + assert(false); + } +} + static bool register_eventlistener(se::Object* obj) { se::Value v; @@ -867,6 +937,12 @@ static bool register_eventlistener(se::Object* obj) assert(v.isObject()); v.toObject()->defineFunction("create", _SE(js_EventListenerCustom_create)); + Director::getInstance()->getEventDispatcher()->setBeforeDispatchEventHook(Event::Type::TOUCH, onBeforeDispatchTouchEvent); + Director::getInstance()->getEventDispatcher()->setAfterDispatchEventHook(Event::Type::TOUCH, onAfterDispatchTouchEvent); + + Director::getInstance()->getTextureCache()->setTextureCreateHook(onTextureCreate); + Director::getInstance()->getTextureCache()->setTextureDestroyHook(onTextureDestroy); + se::ScriptEngine::getInstance()->clearException(); return true; diff --git a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js index 572ae53c66..833973a05f 100644 --- a/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js +++ b/native/cocos/scripting/js-bindings/script/jsb_cocos2d.js @@ -1089,3 +1089,57 @@ cc.GLProgram.prototype.setUniformLocationWithMatrix4fv = function(){ tempArray.push(4); this.setUniformLocationWithMatrixfvUnion.apply(this, tempArray); }; + +// Hack for the lifecycle of JS objects +cc.Director.prototype._jsb_getScheduler = cc.Director.prototype.getScheduler; +cc.Director.prototype.getScheduler = function() { + var scheduler = this._jsb_getScheduler(); + if (this._jsb_scheduler != scheduler) + { + this._jsb_scheduler = scheduler; + } + return scheduler; +} + +cc.Director.prototype._jsb_getActionManager = cc.Director.prototype.getActionManager; +cc.Director.prototype.getActionManager = function() { + var actionManager = this._jsb_getActionManager(); + if (this._jsb_actionManager != actionManager) + { + this._jsb_actionManager = actionManager; + } + return actionManager; +} + +cc.Director.prototype._jsb_getEventDispatcher = cc.Director.prototype.getEventDispatcher; +cc.Director.prototype.getEventDispatcher = function() { + var eventDispatcher = this._jsb_getEventDispatcher(); + if (this._jsb_eventDispatcher != eventDispatcher) + { + this._jsb_eventDispatcher = eventDispatcher; + } + return eventDispatcher; +} + +cc.SpriteFrame.prototype._jsb_getTexture = cc.SpriteFrame.prototype.getTexture; +cc.SpriteFrame.prototype.getTexture = function() { + var texture = this._jsb_getTexture(); + if (this._jsb_texture != texture) + { + this._jsb_texture = texture; + } + return texture; +} + +cc.Sprite.prototype._jsb_getTexture = cc.Sprite.prototype.getTexture; +cc.Sprite.prototype.getTexture = function() { + var texture = this._jsb_getTexture(); + if (this._jsb_texture != texture) + { + this._jsb_texture = texture; + } + return texture; +} + +// +