diff --git a/native/.github/workflows/clangtidy-android.yml b/native/.github/workflows/clangtidy-android.yml index e79b877892..562f3db098 100644 --- a/native/.github/workflows/clangtidy-android.yml +++ b/native/.github/workflows/clangtidy-android.yml @@ -31,6 +31,7 @@ jobs: - exclude: 'cocos/editor-support/dragonbones/**' - exclude: 'cocos/base/etc1.*' - exclude: 'cocos/base/etc2.*' + - exclude: 'cocos/bindings/manual/jsb_global.cpp' allChanges: - added|modified|deleted: '**' skipedDebug: diff --git a/native/cocos/bindings/event/CustomEventTypes.h b/native/cocos/bindings/event/CustomEventTypes.h index f832679050..582157d90e 100644 --- a/native/cocos/bindings/event/CustomEventTypes.h +++ b/native/cocos/bindings/event/CustomEventTypes.h @@ -32,6 +32,7 @@ #define EVENT_RECREATE_WINDOW "event_recreate_window" #define EVENT_MEMORY_WARNING "event_memory_warning" #define EVENT_RESIZE "event_resize" +#define EVENT_CLOSE "event_close" #define EVENT_MOUSE_DOWN "event_mouse_down" #define EVENT_MOUSE_UP "event_mouse_up" diff --git a/native/cocos/bindings/event/EventDispatcher.cpp b/native/cocos/bindings/event/EventDispatcher.cpp index 2d7300d2ab..9863703ecd 100644 --- a/native/cocos/bindings/event/EventDispatcher.cpp +++ b/native/cocos/bindings/event/EventDispatcher.cpp @@ -30,26 +30,26 @@ #include "cocos/bindings/manual/jsb_global_init.h" namespace { -se::Value _tickVal; -std::vector _jsTouchObjPool; -se::Object * _jsTouchObjArray = nullptr; -se::Object * _jsMouseEventObj = nullptr; -se::Object * _jsKeyboardEventObj = nullptr; -se::Object * _jsResizeEventObj = nullptr; -se::Object * _jsOrientationEventObj = nullptr; -bool _inited = false; +se::Value tickVal; +std::vector jsTouchObjPool; +se::Object * jsTouchObjArray = nullptr; +se::Object * jsMouseEventObj = nullptr; +se::Object * jsKeyboardEventObj = nullptr; +se::Object * jsResizeEventObj = nullptr; +se::Object * jsOrientationEventObj = nullptr; +bool inited = false; } // namespace namespace cc { -std::unordered_map EventDispatcher::_listeners; -uint32_t EventDispatcher::_hashListenerID = 1; +std::unordered_map EventDispatcher::listeners; +uint32_t EventDispatcher::hashListenerId = 1; bool EventDispatcher::initialized() { - return _inited; + return inited; }; void EventDispatcher::init() { - _inited = true; + inited = true; se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() { EventDispatcher::destroy(); }); @@ -58,65 +58,65 @@ void EventDispatcher::init() { void EventDispatcher::destroy() { removeAllEventListeners(); - for (auto touchObj : _jsTouchObjPool) { + for (auto *touchObj : jsTouchObjPool) { touchObj->unroot(); touchObj->decRef(); } - _jsTouchObjPool.clear(); + jsTouchObjPool.clear(); - if (_jsTouchObjArray != nullptr) { - _jsTouchObjArray->unroot(); - _jsTouchObjArray->decRef(); - _jsTouchObjArray = nullptr; + if (jsTouchObjArray != nullptr) { + jsTouchObjArray->unroot(); + jsTouchObjArray->decRef(); + jsTouchObjArray = nullptr; } - if (_jsMouseEventObj != nullptr) { - _jsMouseEventObj->unroot(); - _jsMouseEventObj->decRef(); - _jsMouseEventObj = nullptr; + if (jsMouseEventObj != nullptr) { + jsMouseEventObj->unroot(); + jsMouseEventObj->decRef(); + jsMouseEventObj = nullptr; } - if (_jsKeyboardEventObj != nullptr) { - _jsKeyboardEventObj->unroot(); - _jsKeyboardEventObj->decRef(); - _jsKeyboardEventObj = nullptr; + if (jsKeyboardEventObj != nullptr) { + jsKeyboardEventObj->unroot(); + jsKeyboardEventObj->decRef(); + jsKeyboardEventObj = nullptr; } - if (_jsResizeEventObj != nullptr) { - _jsResizeEventObj->unroot(); - _jsResizeEventObj->decRef(); - _jsResizeEventObj = nullptr; + if (jsResizeEventObj != nullptr) { + jsResizeEventObj->unroot(); + jsResizeEventObj->decRef(); + jsResizeEventObj = nullptr; } - _inited = false; - _tickVal.setUndefined(); + inited = false; + tickVal.setUndefined(); } void EventDispatcher::dispatchTouchEvent(const struct TouchEvent &touchEvent) { se::AutoHandleScope scope; - if (!_jsTouchObjArray) { - _jsTouchObjArray = se::Object::createArrayObject(0); - _jsTouchObjArray->root(); + if (!jsTouchObjArray) { + jsTouchObjArray = se::Object::createArrayObject(0); + jsTouchObjArray->root(); } - _jsTouchObjArray->setProperty("length", se::Value((uint32_t)touchEvent.touches.size())); + jsTouchObjArray->setProperty("length", se::Value(static_cast(touchEvent.touches.size()))); - while (_jsTouchObjPool.size() < touchEvent.touches.size()) { + while (jsTouchObjPool.size() < touchEvent.touches.size()) { se::Object *touchObj = se::Object::createPlainObject(); touchObj->root(); - _jsTouchObjPool.push_back(touchObj); + jsTouchObjPool.push_back(touchObj); } uint32_t touchIndex = 0; int poolIndex = 0; for (const auto &touch : touchEvent.touches) { - se::Object *jsTouch = _jsTouchObjPool.at(poolIndex++); + se::Object *jsTouch = jsTouchObjPool.at(poolIndex++); jsTouch->setProperty("identifier", se::Value(touch.index)); jsTouch->setProperty("clientX", se::Value(touch.x)); jsTouch->setProperty("clientY", se::Value(touch.y)); jsTouch->setProperty("pageX", se::Value(touch.x)); jsTouch->setProperty("pageY", se::Value(touch.y)); - _jsTouchObjArray->setArrayElement(touchIndex, se::Value(jsTouch)); + jsTouchObjArray->setArrayElement(touchIndex, se::Value(jsTouch)); ++touchIndex; } @@ -140,15 +140,15 @@ void EventDispatcher::dispatchTouchEvent(const struct TouchEvent &touchEvent) { } se::ValueArray args; - args.push_back(se::Value(_jsTouchObjArray)); + args.push_back(se::Value(jsTouchObjArray)); EventDispatcher::doDispatchEvent(nullptr, eventName, args); } void EventDispatcher::dispatchMouseEvent(const struct MouseEvent &mouseEvent) { se::AutoHandleScope scope; - if (!_jsMouseEventObj) { - _jsMouseEventObj = se::Object::createPlainObject(); - _jsMouseEventObj->root(); + if (!jsMouseEventObj) { + jsMouseEventObj = se::Object::createPlainObject(); + jsMouseEventObj->root(); } const auto & xVal = se::Value(mouseEvent.x); @@ -156,14 +156,14 @@ void EventDispatcher::dispatchMouseEvent(const struct MouseEvent &mouseEvent) { const MouseEvent::Type type = mouseEvent.type; if (type == MouseEvent::Type::WHEEL) { - _jsMouseEventObj->setProperty("wheelDeltaX", xVal); - _jsMouseEventObj->setProperty("wheelDeltaY", yVal); + jsMouseEventObj->setProperty("wheelDeltaX", xVal); + jsMouseEventObj->setProperty("wheelDeltaY", yVal); } else { if (type == MouseEvent::Type::DOWN || type == MouseEvent::Type::UP) { - _jsMouseEventObj->setProperty("button", se::Value(mouseEvent.button)); + jsMouseEventObj->setProperty("button", se::Value(mouseEvent.button)); } - _jsMouseEventObj->setProperty("x", xVal); - _jsMouseEventObj->setProperty("y", yVal); + jsMouseEventObj->setProperty("x", xVal); + jsMouseEventObj->setProperty("y", yVal); } const char *eventName = nullptr; @@ -191,15 +191,15 @@ void EventDispatcher::dispatchMouseEvent(const struct MouseEvent &mouseEvent) { } se::ValueArray args; - args.push_back(se::Value(_jsMouseEventObj)); + args.push_back(se::Value(jsMouseEventObj)); EventDispatcher::doDispatchEvent(eventName, jsFunctionName, args); } void EventDispatcher::dispatchKeyboardEvent(const struct KeyboardEvent &keyboardEvent) { se::AutoHandleScope scope; - if (!_jsKeyboardEventObj) { - _jsKeyboardEventObj = se::Object::createPlainObject(); - _jsKeyboardEventObj->root(); + if (!jsKeyboardEventObj) { + jsKeyboardEventObj = se::Object::createPlainObject(); + jsKeyboardEventObj->root(); } const char *eventName = nullptr; @@ -216,69 +216,71 @@ void EventDispatcher::dispatchKeyboardEvent(const struct KeyboardEvent &keyboard break; } - _jsKeyboardEventObj->setProperty("altKey", se::Value(keyboardEvent.altKeyActive)); - _jsKeyboardEventObj->setProperty("ctrlKey", se::Value(keyboardEvent.ctrlKeyActive)); - _jsKeyboardEventObj->setProperty("metaKey", se::Value(keyboardEvent.metaKeyActive)); - _jsKeyboardEventObj->setProperty("shiftKey", se::Value(keyboardEvent.shiftKeyActive)); - _jsKeyboardEventObj->setProperty("repeat", se::Value(keyboardEvent.action == KeyboardEvent::Action::REPEAT)); - _jsKeyboardEventObj->setProperty("keyCode", se::Value(keyboardEvent.key)); + jsKeyboardEventObj->setProperty("altKey", se::Value(keyboardEvent.altKeyActive)); + jsKeyboardEventObj->setProperty("ctrlKey", se::Value(keyboardEvent.ctrlKeyActive)); + jsKeyboardEventObj->setProperty("metaKey", se::Value(keyboardEvent.metaKeyActive)); + jsKeyboardEventObj->setProperty("shiftKey", se::Value(keyboardEvent.shiftKeyActive)); + jsKeyboardEventObj->setProperty("repeat", se::Value(keyboardEvent.action == KeyboardEvent::Action::REPEAT)); + jsKeyboardEventObj->setProperty("keyCode", se::Value(keyboardEvent.key)); se::ValueArray args; - args.push_back(se::Value(_jsKeyboardEventObj)); + args.push_back(se::Value(jsKeyboardEventObj)); EventDispatcher::doDispatchEvent(nullptr, eventName, args); } -void EventDispatcher::dispatchTickEvent(float dt) { - if (!se::ScriptEngine::getInstance()->isValid()) +void EventDispatcher::dispatchTickEvent(float /*dt*/) { + if (!se::ScriptEngine::getInstance()->isValid()) { return; + } se::AutoHandleScope scope; - if (_tickVal.isUndefined()) { - se::ScriptEngine::getInstance()->getGlobalObject()->getProperty("gameTick", &_tickVal); + if (tickVal.isUndefined()) { + se::ScriptEngine::getInstance()->getGlobalObject()->getProperty("gameTick", &tickVal); } static std::chrono::steady_clock::time_point prevTime; prevTime = std::chrono::steady_clock::now(); se::ValueArray args; - long long milliSeconds = std::chrono::duration_cast(prevTime - se::ScriptEngine::getInstance()->getStartTime()).count(); - args.push_back(se::Value((double)milliSeconds)); + int64_t milliSeconds = std::chrono::duration_cast(prevTime - se::ScriptEngine::getInstance()->getStartTime()).count(); + args.push_back(se::Value(static_cast(milliSeconds))); - _tickVal.toObject()->call(args, nullptr); + tickVal.toObject()->call(args, nullptr); } void EventDispatcher::dispatchResizeEvent(int width, int height) { se::AutoHandleScope scope; - if (!_jsResizeEventObj) { - _jsResizeEventObj = se::Object::createPlainObject(); - _jsResizeEventObj->root(); + if (!jsResizeEventObj) { + jsResizeEventObj = se::Object::createPlainObject(); + jsResizeEventObj->root(); } - _jsResizeEventObj->setProperty("width", se::Value(width)); - _jsResizeEventObj->setProperty("height", se::Value(height)); + jsResizeEventObj->setProperty("width", se::Value(width)); + jsResizeEventObj->setProperty("height", se::Value(height)); se::ValueArray args; - args.push_back(se::Value(_jsResizeEventObj)); + args.push_back(se::Value(jsResizeEventObj)); EventDispatcher::doDispatchEvent(EVENT_RESIZE, "onResize", args); } void EventDispatcher::dispatchOrientationChangeEvent(int orientation) { - if (!se::ScriptEngine::getInstance()->isValid()) + if (!se::ScriptEngine::getInstance()->isValid()) { return; + } se::AutoHandleScope scope; - assert(_inited); + assert(inited); - if (_jsOrientationEventObj == nullptr) { - _jsOrientationEventObj = se::Object::createPlainObject(); - _jsOrientationEventObj->root(); + if (jsOrientationEventObj == nullptr) { + jsOrientationEventObj = se::Object::createPlainObject(); + jsOrientationEventObj->root(); } se::Value func; __jsbObj->getProperty("onOrientationChanged", &func); if (func.isObject() && func.toObject()->isFunction()) { - _jsOrientationEventObj->setProperty("orientation", se::Value(orientation)); + jsOrientationEventObj->setProperty("orientation", se::Value(orientation)); se::ValueArray args; - args.push_back(se::Value(_jsOrientationEventObj)); + args.push_back(se::Value(jsOrientationEventObj)); func.toObject()->call(args, nullptr); } } @@ -299,9 +301,14 @@ void EventDispatcher::dispatchRestartVM() { EventDispatcher::doDispatchEvent(EVENT_RESTART_VM, "onRestartVM", se::EmptyValueArray); } +void EventDispatcher::dispatchCloseEvent() { + EventDispatcher::doDispatchEvent(EVENT_CLOSE, "onClose", se::EmptyValueArray); +} + void EventDispatcher::doDispatchEvent(const char *eventName, const char *jsFunctionName, const std::vector &args) { - if (!se::ScriptEngine::getInstance()->isValid()) + if (!se::ScriptEngine::getInstance()->isValid()) { return; + } if (eventName) { CustomEvent event; @@ -310,11 +317,12 @@ void EventDispatcher::doDispatchEvent(const char *eventName, const char *jsFunct } // dispatch to Javascript - if (!se::ScriptEngine::getInstance()->isValid()) + if (!se::ScriptEngine::getInstance()->isValid()) { return; + } se::AutoHandleScope scope; - assert(_inited); + assert(inited); se::Value func; __jsbObj->getProperty(jsFunctionName, &func); @@ -326,12 +334,12 @@ void EventDispatcher::doDispatchEvent(const char *eventName, const char *jsFunct uint32_t EventDispatcher::addCustomEventListener(const std::string &eventName, const CustomEventListener &listener) { Node *newNode = new Node(); newNode->listener = listener; - newNode->listenerID = _hashListenerID; + newNode->listenerID = hashListenerId; newNode->next = nullptr; - auto iter = _listeners.find(eventName); - if (iter == _listeners.end()) { - _listeners.emplace(eventName, newNode); + auto iter = listeners.find(eventName); + if (iter == listeners.end()) { + listeners.emplace(eventName, newNode); } else { Node *node = iter->second; assert(node != nullptr); @@ -342,18 +350,20 @@ uint32_t EventDispatcher::addCustomEventListener(const std::string &eventName, c } prev->next = newNode; } - return _hashListenerID++; + return hashListenerId++; } void EventDispatcher::removeCustomEventListener(const std::string &eventName, uint32_t listenerID) { - if (eventName.empty()) + if (eventName.empty()) { return; + } - if (listenerID == 0) + if (listenerID == 0) { return; + } - auto iter = _listeners.find(eventName); - if (iter != _listeners.end()) { + auto iter = listeners.find(eventName); + if (iter != listeners.end()) { Node *prev = nullptr; Node *node = iter->second; while (node != nullptr) { @@ -361,9 +371,9 @@ void EventDispatcher::removeCustomEventListener(const std::string &eventName, ui if (prev != nullptr) { prev->next = node->next; } else if (node->next) { - _listeners[eventName] = node->next; + listeners[eventName] = node->next; } else { - _listeners.erase(iter); + listeners.erase(iter); } delete node; @@ -377,30 +387,30 @@ void EventDispatcher::removeCustomEventListener(const std::string &eventName, ui } void EventDispatcher::removeAllCustomEventListeners(const std::string &eventName) { - auto iter = _listeners.find(eventName); - if (iter != _listeners.end()) { + auto iter = listeners.find(eventName); + if (iter != listeners.end()) { Node *node = iter->second; while (node != nullptr) { Node *next = node->next; delete node; node = next; } - _listeners.erase(iter); + listeners.erase(iter); } } void EventDispatcher::removeAllEventListeners() { - for (auto &&node : _listeners) { + for (auto &&node : listeners) { delete node.second; } - _listeners.clear(); + listeners.clear(); //start from 1 cuz 0 represents pause and resume - _hashListenerID = 1; + hashListenerId = 1; } void EventDispatcher::dispatchCustomEvent(const CustomEvent &event) { - auto iter = _listeners.find(event.name); - if (iter != _listeners.end()) { + auto iter = listeners.find(event.name); + if (iter != listeners.end()) { Node *next = nullptr; Node *node = iter->second; while (node != nullptr) { diff --git a/native/cocos/bindings/event/EventDispatcher.h b/native/cocos/bindings/event/EventDispatcher.h index 037dff9551..894cc8fff9 100644 --- a/native/cocos/bindings/event/EventDispatcher.h +++ b/native/cocos/bindings/event/EventDispatcher.h @@ -43,10 +43,10 @@ struct TouchInfo { float y = 0; int index = 0; - TouchInfo(float _x, float _y, int _index) - : x(_x), - y(_y), - index(_index) {} + TouchInfo(float x, float y, int index) + : x(x), + y(y), + index(index) {} }; struct TouchEvent { @@ -71,67 +71,67 @@ struct MouseEvent { UNKNOWN }; - float x = 0.0f; - float y = 0.0f; + float x = 0.0F; + float y = 0.0F; // The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. // For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left. - unsigned short button = 0; - Type type = Type::UNKNOWN; + uint16_t button = 0; + Type type = Type::UNKNOWN; }; enum class KeyCode { - Backspace = 8, - Tab = 9, - NumLock = 12, - NumpadEnter = 20013, - Enter = 13, - ShiftRight = 20016, - ShiftLeft = 16, - ControlLeft = 17, - ControlRight = 20017, - AltRight = 20018, - AltLeft = 18, - CapsLock = 20, - Escape = 27, - Space = 32, - PageUp = 33, - PageDown = 34, - End = 35, - Home = 36, - ArrowLeft = 37, - ArrowUp = 38, - ArrowRight = 39, - ArrowDown = 40, - Delete = 46, - MetaLeft = 91, - ContextMenu = 20093, - MetaRight = 93, - NumpadMultiply = 106, - NumpadPlus = 107, - NumpadMinus = 109, - NumpadDecimal = 110, - NumpadDivide = 111, - Semicolon = 186, - Equal = 187, - Comma = 188, - Minus = 189, - Period = 190, - Slash = 191, - Backquote = 192, - BracketLeft = 219, - Backslash = 220, - BracketRight = 221, - Quote = 222, - NUMPAD_0 = 10048, - NUMPAD_1 = 10049, - NUMPAD_2 = 10050, - NUMPAD_3 = 10051, - NUMPAD_4 = 10052, - NUMPAD_5 = 10053, - NUMPAD_6 = 10054, - NUMPAD_7 = 10055, - NUMPAD_8 = 10056, - NUMPAD_9 = 10057 + BACKSPACE = 8, + TAB = 9, + NUM_LOCK = 12, + NUMPAD_ENTER = 20013, + ENTER = 13, + SHIFT_RIGHT = 20016, + SHIFT_LEFT = 16, + CONTROL_LEFT = 17, + CONTROL_RIGHT = 20017, + ALT_RIGHT = 20018, + ALT_LEFT = 18, + CAPS_LOCK = 20, + ESCAPE = 27, + SPACE = 32, + PAGE_UP = 33, + PAGE_DOWN = 34, + END = 35, + HOME = 36, + ARROW_LEFT = 37, + ARROW_UP = 38, + ARROW_RIGHT = 39, + ARROW_DOWN = 40, + DELETE_KEY = 46, //DELETE has conflict + META_LEFT = 91, + CONTEXT_MENU = 20093, + META_RIGHT = 93, + NUMPAD_MULTIPLY = 106, + NUMPAD_PLUS = 107, + NUMPAD_MINUS = 109, + NUMPAD_DECIMAL = 110, + NUMPAD_DIVIDE = 111, + SEMICOLON = 186, + EQUAL = 187, + COMMA = 188, + MINUS = 189, + PERIOD = 190, + SLASH = 191, + BACKQUOTE = 192, + BRACKET_LEFT = 219, + BACKSLASH = 220, + BRACKET_RIGHT = 221, + QUOTE = 222, + NUMPAD_0 = 10048, + NUMPAD_1 = 10049, + NUMPAD_2 = 10050, + NUMPAD_3 = 10051, + NUMPAD_4 = 10052, + NUMPAD_5 = 10053, + NUMPAD_6 = 10054, + NUMPAD_7 = 10055, + NUMPAD_8 = 10056, + NUMPAD_9 = 10057 }; struct KeyboardEvent { @@ -148,23 +148,23 @@ struct KeyboardEvent { bool ctrlKeyActive = false; bool metaKeyActive = false; bool shiftKeyActive = false; - // TODO: support caps lock? + // TODO(mingo): support caps lock? }; class CustomEvent { public: std::string name; union { - void *ptrVal; - long longVal; - int intVal; - short shortVal; - char charVal; - bool boolVal; + void * ptrVal; + int32_t longVal; + int intVal; + int16_t shortVal; + char charVal; + bool boolVal; } args[10]; - CustomEvent(){}; - virtual ~CustomEvent(){}; + CustomEvent() = default; + virtual ~CustomEvent() = default; }; class EventDispatcher { @@ -183,6 +183,7 @@ public: static void dispatchEnterForegroundEvent(); static void dispatchMemoryWarningEvent(); static void dispatchRestartVM(); + static void dispatchCloseEvent(); using CustomEventListener = std::function; static uint32_t addCustomEventListener(const std::string &eventName, const CustomEventListener &listener); @@ -199,8 +200,8 @@ private: uint32_t listenerID; struct Node * next = nullptr; }; - static std::unordered_map _listeners; - static uint32_t _hashListenerID; //simple increment hash + static std::unordered_map listeners; + static uint32_t hashListenerId; //simple increment hash }; } // end of namespace cc diff --git a/native/cocos/bindings/manual/jsb_global.cpp b/native/cocos/bindings/manual/jsb_global.cpp index 5902dd9ae6..f0aedfb589 100644 --- a/native/cocos/bindings/manual/jsb_global.cpp +++ b/native/cocos/bindings/manual/jsb_global.cpp @@ -45,54 +45,56 @@ #include #include -using namespace cc; +using cc::Application; +using cc::FileUtils; +using cc::LegacyThreadPool; -static LegacyThreadPool *__threadPool = nullptr; +static LegacyThreadPool *threadPool = nullptr; -static std::shared_ptr _localDownloader = nullptr; -static std::map> _localDownloaderHandlers; -static uint64_t _localDownloaderTaskId = 1000000; +static std::shared_ptr localDownloader = nullptr; +static std::map> localDownloaderHandlers; +static uint64_t localDownloaderTaskId = 1000000; -static cc::network::Downloader *localDownloader() { - if (!_localDownloader) { - _localDownloader = std::make_shared(); - _localDownloader->onDataTaskSuccess = [=](const cc::network::DownloadTask & task, - const std::vector &data) { +static cc::network::Downloader *localDownloaderInstance() { + if (!localDownloader) { + localDownloader = std::make_shared(); + localDownloader->onDataTaskSuccess = [=](const cc::network::DownloadTask & task, + const std::vector &data) { if (data.empty()) { SE_REPORT_ERROR("Getting image from (%s) failed!", task.requestURL.c_str()); return; } - auto callback = _localDownloaderHandlers.find(task.identifier); - if (callback == _localDownloaderHandlers.end()) { + auto callback = localDownloaderHandlers.find(task.identifier); + if (callback == localDownloaderHandlers.end()) { SE_REPORT_ERROR("Getting image from (%s), callback not found!!", task.requestURL.c_str()); return; } - size_t imageBytes = data.size(); - unsigned char *imageData = (unsigned char *)malloc(imageBytes); + size_t imageBytes = data.size(); + auto * imageData = static_cast(malloc(imageBytes)); memcpy(imageData, data.data(), imageBytes); (callback->second)("", imageData, static_cast(imageBytes)); //initImageFunc("", imageData, imageBytes); - _localDownloaderHandlers.erase(callback); + localDownloaderHandlers.erase(callback); }; - _localDownloader->onTaskError = [=](const cc::network::DownloadTask &task, - int errorCode, - int errorCodeInternal, - const std::string & errorStr) { + localDownloader->onTaskError = [=](const cc::network::DownloadTask &task, + int /*errorCode*/, + int /*errorCodeInternal*/, + const std::string & /*errorStr*/) { SE_REPORT_ERROR("Getting image from (%s) failed!", task.requestURL.c_str()); - _localDownloaderHandlers.erase(task.identifier); + localDownloaderHandlers.erase(task.identifier); }; } - return _localDownloader.get(); + return localDownloader.get(); } -static void localDownloaderCreateTask(const std::string &url, std::function callback) { +static void localDownloaderCreateTask(const std::string &url, const std::function &callback) { std::stringstream ss; - ss << "jsb_loadimage_" << (_localDownloaderTaskId++); + ss << "jsb_loadimage_" << (localDownloaderTaskId++); std::string key = ss.str(); - auto task = localDownloader()->createDownloadDataTask(url, key); - _localDownloaderHandlers.emplace(std::make_pair(task->identifier, callback)); + auto task = localDownloaderInstance()->createDownloadDataTask(url, key); + localDownloaderHandlers.emplace(std::make_pair(task->identifier, callback)); } bool jsb_set_extend_property(const char *ns, const char *clsName) { @@ -116,13 +118,11 @@ bool jsb_set_extend_property(const char *ns, const char *clsName) { return false; } -namespace { +std::unordered_map moduleCache; -std::unordered_map __moduleCache; - -static bool require(se::State &s) { +bool require(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); assert(argc >= 1); assert(args[0].isString()); @@ -130,7 +130,7 @@ static bool require(se::State &s) { } SE_BIND_FUNC(require) -static bool doModuleRequire(const std::string &path, se::Value *ret, const std::string &prevScriptFileDir) { +bool doModuleRequire(const std::string &path, se::Value *ret, const std::string &prevScriptFileDir) { se::AutoHandleScope hs; assert(!path.empty()); @@ -140,24 +140,28 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: std::string fullPath; std::string pathWithSuffix = path; - if (pathWithSuffix.rfind(".js") != (pathWithSuffix.length() - 3)) + if (pathWithSuffix.rfind(".js") != (pathWithSuffix.length() - 3)) { pathWithSuffix += ".js"; + } std::string scriptBuffer = fileOperationDelegate.onGetStringFromFile(pathWithSuffix); if (scriptBuffer.empty() && !prevScriptFileDir.empty()) { std::string secondPath = prevScriptFileDir; - if (secondPath[secondPath.length() - 1] != '/') + if (secondPath[secondPath.length() - 1] != '/') { secondPath += "/"; + } secondPath += path; if (FileUtils::getInstance()->isDirectoryExist(secondPath)) { - if (secondPath[secondPath.length() - 1] != '/') + if (secondPath[secondPath.length() - 1] != '/') { secondPath += "/"; + } secondPath += "index.js"; } else { - if (path.rfind(".js") != (path.length() - 3)) + if (path.rfind(".js") != (path.length() - 3)) { secondPath += ".js"; + } } fullPath = fileOperationDelegate.onGetFullPath(secondPath); @@ -167,10 +171,10 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: } if (!scriptBuffer.empty()) { - const auto &iter = __moduleCache.find(fullPath); - if (iter != __moduleCache.end()) { + const auto &iter = moduleCache.find(fullPath); + if (iter != moduleCache.end()) { *ret = iter->second; - // printf("Found cache: %s, value: %d\n", fullPath.c_str(), (int)ret->getType()); + // printf("Found cache: %s, value: %d\n", fullPath.c_str(), static_cast(ret->getType())); return true; } std::string currentScriptFileDir = FileUtils::getInstance()->getFileDir(fullPath); @@ -187,39 +191,46 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: // fwrite(scriptBuffer.c_str(), scriptBuffer.length(), 1, fp); // fclose(fp); - std::string reletivePath = fullPath; + std::string relativePath; + #if CC_PLATFORM == CC_PLATFORM_MAC_OSX || CC_PLATFORM == CC_PLATFORM_MAC_IOS + + std::string relativePathKey; + #if CC_PLATFORM == CC_PLATFORM_MAC_OSX - const std::string reletivePathKey = "/Contents/Resources"; + relativePathKey = "/Contents/Resources"; #else - const std::string reletivePathKey = ".app"; + relativePathKey = ".app"; #endif - size_t pos = reletivePath.find(reletivePathKey); + size_t pos = fullPath.find(relativePathKey); if (pos != std::string::npos) { - reletivePath = reletivePath.substr(pos + reletivePathKey.length() + 1); + relativePath = fullPath.substr(pos + relativePathKey.length() + 1); } +#else + relativePath = fullPath; #endif // RENDERER_LOGD("Evaluate: %s", fullPath.c_str()); - auto se = se::ScriptEngine::getInstance(); - bool succeed = se->evalString(scriptBuffer.c_str(), scriptBuffer.length(), nullptr, reletivePath.c_str()); + auto * se = se::ScriptEngine::getInstance(); + bool succeed = se->evalString(scriptBuffer.c_str(), static_cast(scriptBuffer.length()), nullptr, relativePath.c_str()); se::Value moduleVal; if (succeed && se->getGlobalObject()->getProperty("module", &moduleVal) && moduleVal.isObject()) { se::Value exportsVal; if (moduleVal.toObject()->getProperty("exports", &exportsVal)) { - if (ret != nullptr) + if (ret != nullptr) { *ret = exportsVal; + } - __moduleCache[fullPath] = std::move(exportsVal); + moduleCache[fullPath] = std::move(exportsVal); } else { - __moduleCache[fullPath] = se::Value::Undefined; + moduleCache[fullPath] = se::Value::Undefined; } // clear module.exports moduleVal.toObject()->setProperty("exports", se::Value::Undefined); } else { - __moduleCache[fullPath] = se::Value::Undefined; + moduleCache[fullPath] = se::Value::Undefined; } assert(succeed); return succeed; @@ -230,9 +241,9 @@ static bool doModuleRequire(const std::string &path, se::Value *ret, const std:: return false; } -static bool moduleRequire(se::State &s) { +bool moduleRequire(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); assert(argc >= 2); assert(args[0].isString()); assert(args[1].isString()); @@ -240,7 +251,6 @@ static bool moduleRequire(se::State &s) { return doModuleRequire(args[0].toString(), &s.rval(), args[1].toString()); } SE_BIND_FUNC(moduleRequire) -} // namespace bool jsb_run_script(const std::string &filePath, se::Value *rval /* = nullptr */) { se::AutoHandleScope hs; @@ -251,14 +261,14 @@ bool jsb_run_script_module(const std::string &filePath, se::Value *rval /* = nul return doModuleRequire(filePath, rval, ""); } -static bool jsc_garbageCollect(se::State &s) { +static bool jscGarbageCollect(se::State &s) { se::ScriptEngine::getInstance()->garbageCollect(); return true; } -SE_BIND_FUNC(jsc_garbageCollect) +SE_BIND_FUNC(jscGarbageCollect) -static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { - CC_LOG_DEBUG(">>> total: %d, Dump (native -> jsobj) map begin", (int)se::NativePtrToObjectMap::size()); +static bool jscDumpNativePtrToSeObjectMap(se::State &s) { + CC_LOG_DEBUG(">>> total: %d, Dump (native -> jsobj) map begin", static_cast(se::NativePtrToObjectMap::size())); struct NamePtrStruct { const char *name; @@ -279,38 +289,39 @@ static bool jsc_dumpNativePtrToSeObjectMap(se::State &s) { std::sort(namePtrArray.begin(), namePtrArray.end(), [](const NamePtrStruct &a, const NamePtrStruct &b) -> bool { std::string left = a.name; std::string right = b.name; - for (std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit) - if (::tolower(*lit) < ::tolower(*rit)) + for (std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit) { + if (::tolower(*lit) < ::tolower(*rit)) { return true; - else if (::tolower(*lit) > ::tolower(*rit)) + } + if (::tolower(*lit) > ::tolower(*rit)) { return false; - if (left.size() < right.size()) - return true; - return false; + } + } + return left.size() < right.size(); }); for (const auto &e : namePtrArray) { CC_LOG_DEBUG("%s: %p", e.name, e.ptr); } - CC_LOG_DEBUG(">>> total: %d, nonRefMap: %d, Dump (native -> jsobj) map end", (int)se::NativePtrToObjectMap::size(), (int)se::NonRefNativePtrCreatedByCtorMap::size()); + CC_LOG_DEBUG(">>> total: %d, nonRefMap: %d, Dump (native -> jsobj) map end", static_cast(se::NativePtrToObjectMap::size()), static_cast(se::NonRefNativePtrCreatedByCtorMap::size())); return true; } -SE_BIND_FUNC(jsc_dumpNativePtrToSeObjectMap) +SE_BIND_FUNC(jscDumpNativePtrToSeObjectMap) -static bool jsc_dumpRoot(se::State &s) { +static bool jscDumpRoot(se::State &s) { assert(false); return true; } -SE_BIND_FUNC(jsc_dumpRoot) +SE_BIND_FUNC(jscDumpRoot) -static bool JSBCore_platform(se::State &s) { +static bool jsbCorePlatform(se::State &s) { Application::Platform platform = Application::getInstance()->getPlatform(); - s.rval().setInt32((int32_t)platform); + s.rval().setInt32(static_cast(platform)); return true; } -SE_BIND_FUNC(JSBCore_platform) +SE_BIND_FUNC(jsbCorePlatform) -static bool JSBCore_os(se::State &s) { +static bool jsbCoreOs(se::State &s) { se::Value os; // osx, ios, android, windows, linux, etc.. @@ -329,9 +340,9 @@ static bool JSBCore_os(se::State &s) { s.rval() = os; return true; } -SE_BIND_FUNC(JSBCore_os) +SE_BIND_FUNC(jsbCoreOs) -static bool JSBCore_getCurrentLanguage(se::State &s) { +static bool jsbCoreGetCurrentLanguage(se::State &s) { std::string languageStr; Application::LanguageType language = Application::getInstance()->getCurrentLanguage(); switch (language) { @@ -399,32 +410,38 @@ static bool JSBCore_getCurrentLanguage(se::State &s) { s.rval().setString(languageStr); return true; } -SE_BIND_FUNC(JSBCore_getCurrentLanguage) +SE_BIND_FUNC(jsbCoreGetCurrentLanguage) -static bool JSBCore_getCurrentLanguageCode(se::State &s) { +static bool jsbCoreGetCurrentLanguageCode(se::State &s) { std::string language = Application::getInstance()->getCurrentLanguageCode(); s.rval().setString(language); return true; } -SE_BIND_FUNC(JSBCore_getCurrentLanguageCode) +SE_BIND_FUNC(jsbCoreGetCurrentLanguageCode) -static bool JSB_getOSVersion(se::State &s) { +static bool jsbGetOsVersion(se::State &s) { std::string systemVersion = Application::getInstance()->getSystemVersion(); s.rval().setString(systemVersion); return true; } -SE_BIND_FUNC(JSB_getOSVersion) +SE_BIND_FUNC(jsbGetOsVersion) -static bool JSB_core_restartVM(se::State &s) { +static bool jsbCoreRestartVm(se::State &s) { //REFINE: release AudioEngine, waiting HttpClient & WebSocket threads to exit. Application::getInstance()->restart(); return true; } -SE_BIND_FUNC(JSB_core_restartVM) +SE_BIND_FUNC(jsbCoreRestartVm) -static bool JSB_isObjectValid(se::State &s) { +static bool jsbCloseWindow(se::State &s) { + Application::getInstance()->close(); + return true; +} +SE_BIND_FUNC(jsbCloseWindow) + +static bool jsbIsObjectValid(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); if (argc == 1) { void *nativePtr = nullptr; seval_to_native_ptr(args[0], &nativePtr); @@ -435,24 +452,25 @@ static bool JSB_isObjectValid(se::State &s) { SE_REPORT_ERROR("Invalid number of arguments: %d. Expecting: 1", argc); return false; } -SE_BIND_FUNC(JSB_isObjectValid) +SE_BIND_FUNC(jsbIsObjectValid) -static bool JSB_setCursorEnabled(se::State &s) { +static bool jsbSetCursorEnabled(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); SE_PRECONDITION2(argc == 1, false, "Invalid number of arguments"); - bool ok = true, value = true; + bool ok = true; + bool value = true; ok &= seval_to_boolean(args[0], &value); SE_PRECONDITION2(ok, false, "Error processing arguments"); Application::getInstance()->setCursorEnabled(value); return true; } -SE_BIND_FUNC(JSB_setCursorEnabled) +SE_BIND_FUNC(jsbSetCursorEnabled) -static bool JSB_saveByteCode(se::State &s) { +static bool jsbSaveByteCode(se::State &s) { const auto &args = s.args(); - int argc = (int)args.size(); + int argc = static_cast(args.size()); SE_PRECONDITION2(argc == 2, false, "Invalid number of arguments"); bool ok = true; std::string srcfile; @@ -464,9 +482,9 @@ static bool JSB_saveByteCode(se::State &s) { s.rval().setBoolean(ok); return true; } -SE_BIND_FUNC(JSB_saveByteCode) +SE_BIND_FUNC(jsbSaveByteCode) -static bool getOrCreatePlainObject_r(const char *name, se::Object *parent, se::Object **outObj) { +static bool getOrCreatePlainObjectR(const char *name, se::Object *parent, se::Object **outObj) { assert(parent != nullptr); assert(outObj != nullptr); se::Value tmp; @@ -482,15 +500,14 @@ static bool getOrCreatePlainObject_r(const char *name, se::Object *parent, se::O return true; } -static bool js_performance_now(se::State &s) { +static bool jsPerformanceNow(se::State &s) { auto now = std::chrono::steady_clock::now(); auto micro = std::chrono::duration_cast(now - se::ScriptEngine::getInstance()->getStartTime()).count(); - s.rval().setNumber((double)micro * 0.001); + s.rval().setNumber(static_cast(micro) * 0.001); return true; } -SE_BIND_FUNC(js_performance_now) +SE_BIND_FUNC(jsPerformanceNow) -namespace { struct ImageInfo { uint32_t length = 0; uint32_t width = 0; @@ -502,7 +519,7 @@ struct ImageInfo { }; uint8_t *convertRGB2RGBA(uint32_t length, uint8_t *src) { - uint8_t *dst = reinterpret_cast(malloc(length)); + auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { dst[i] = *src++; dst[i + 1] = *src++; @@ -513,7 +530,7 @@ uint8_t *convertRGB2RGBA(uint32_t length, uint8_t *src) { } uint8_t *convertIA2RGBA(uint32_t length, uint8_t *src) { - uint8_t *dst = reinterpret_cast(malloc(length)); + auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { dst[i] = *src; dst[i + 1] = *src; @@ -524,7 +541,7 @@ uint8_t *convertIA2RGBA(uint32_t length, uint8_t *src) { } uint8_t *convertI2RGBA(uint32_t length, uint8_t *src) { - uint8_t *dst = reinterpret_cast(malloc(length)); + auto *dst = reinterpret_cast(malloc(length)); for (uint32_t i = 0; i < length; i += 4) { dst[i] = *src; dst[i + 1] = *src; @@ -534,11 +551,11 @@ uint8_t *convertI2RGBA(uint32_t length, uint8_t *src) { return dst; } -struct ImageInfo *createImageInfo(Image *img) { - struct ImageInfo *imgInfo = new struct ImageInfo(); - imgInfo->length = (uint32_t)img->getDataLen(); - imgInfo->width = img->getWidth(); - imgInfo->height = img->getHeight(); +struct ImageInfo *createImageInfo(cc::Image *img) { + auto *imgInfo = new struct ImageInfo(); + imgInfo->length = static_cast(img->getDataLen()); + imgInfo->width = img->getWidth(); + imgInfo->height = img->getHeight(); img->takeData(&imgInfo->data); imgInfo->format = img->getRenderFormat(); imgInfo->compressed = img->isCompressed(); @@ -578,7 +595,6 @@ struct ImageInfo *createImageInfo(Image *img) { return imgInfo; } -} // namespace bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal) { if (path.empty()) { @@ -590,9 +606,9 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal std::shared_ptr callbackPtr = std::make_shared(callbackVal); auto initImageFunc = [path, callbackPtr](const std::string &fullPath, unsigned char *imageData, int imageBytes) { - Image *img = new (std::nothrow) Image(); + auto *img = new (std::nothrow) cc::Image(); - __threadPool->pushTask([=](int tid) { + threadPool->pushTask([=](int /*tid*/) { // NOTE: FileUtils::getInstance()->fullPathForFilename isn't a threadsafe method, // Image::initWithImageFile will call fullPathForFilename internally which may // cause thread race issues. Therefore, we get the full path of file before @@ -618,7 +634,7 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal if (loadSucceed) { se::HandleObject retObj(se::Object::createPlainObject()); - ulong_to_seval((unsigned long)imgInfo->data, &dataVal); + ulong_to_seval((unsigned long)imgInfo->data, &dataVal); //NOLINT retObj->setProperty("data", dataVal); retObj->setProperty("width", se::Value(imgInfo->width)); retObj->setProperty("height", se::Value(imgInfo->height)); @@ -644,7 +660,7 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal size_t dataStartPos = pos + strlen("base64,"); const char * base64Data = path.data() + dataStartPos; size_t dataLen = path.length() - dataStartPos; - imageBytes = base64Decode((const unsigned char *)base64Data, (unsigned int)dataLen, &imageData); + imageBytes = cc::base64Decode(reinterpret_cast(base64Data), static_cast(dataLen), &imageData); if (imageBytes <= 0 || imageData == nullptr) { SE_REPORT_ERROR("Decode base64 image data failed!"); return false; @@ -652,8 +668,9 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal initImageFunc("", imageData, imageBytes); } else { std::string fullPath(FileUtils::getInstance()->fullPathForFilename(path)); - if (0 == path.find("file://")) + if (0 == path.find("file://")) { fullPath = FileUtils::getInstance()->fullPathForFilename(path.substr(strlen("file://"))); + } if (fullPath.empty()) { SE_REPORT_ERROR("File (%s) doesn't exist!", path.c_str()); @@ -664,7 +681,7 @@ bool jsb_global_load_image(const std::string &path, const se::Value &callbackVal return true; } -static bool js_loadImage(se::State &s) { +static bool jsLoadImage(se::State &s) { const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; @@ -679,29 +696,29 @@ static bool js_loadImage(se::State &s) { return jsb_global_load_image(path, callbackVal); } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast(argc), 2); return false; } -SE_BIND_FUNC(js_loadImage) +SE_BIND_FUNC(jsLoadImage) -static bool js_destroyImage(se::State &s) { +static bool jsDestroyImage(se::State &s) { const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc == 1) { - unsigned long data = 0; - ok &= seval_to_ulong(args[0], &data); + char *data = nullptr; + ok &= seval_to_ulong(args[0], reinterpret_cast(&data)); //NOLINT google-runtime-int SE_PRECONDITION2(ok, false, "js_destroyImage : Error processing arguments"); - free(reinterpret_cast(data)); + free(data); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast(argc), 1); return false; } -SE_BIND_FUNC(js_destroyImage) +SE_BIND_FUNC(jsDestroyImage) -static bool JSB_openURL(se::State &s) { +static bool jsbOpenUrl(se::State &s) { const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; @@ -713,12 +730,12 @@ static bool JSB_openURL(se::State &s) { return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast(argc), 1); return false; } -SE_BIND_FUNC(JSB_openURL) +SE_BIND_FUNC(jsbOpenUrl) -static bool JSB_copyTextToClipboard(se::State &s) { +static bool jsbCopyTextToClipboard(se::State &s) { const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; @@ -730,12 +747,12 @@ static bool JSB_copyTextToClipboard(se::State &s) { return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast(argc), 1); return false; } -SE_BIND_FUNC(JSB_copyTextToClipboard) +SE_BIND_FUNC(jsbCopyTextToClipboard) -static bool JSB_setPreferredFramesPerSecond(se::State &s) { +static bool jsbSetPreferredFramesPerSecond(se::State &s) { const auto & args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; @@ -748,13 +765,13 @@ static bool JSB_setPreferredFramesPerSecond(se::State &s) { return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast(argc), 1); return false; } -SE_BIND_FUNC(JSB_setPreferredFramesPerSecond) +SE_BIND_FUNC(jsbSetPreferredFramesPerSecond) #if CC_USE_EDITBOX -static bool JSB_showInputBox(se::State &s) { +static bool jsbShowInputBox(se::State &s) { const auto &args = s.args(); size_t argc = args.size(); if (argc == 1) { @@ -778,114 +795,122 @@ static bool JSB_showInputBox(se::State &s) { if (obj->getProperty("confirmHold", &tmp)) { SE_PRECONDITION2(tmp.isBoolean(), false, "confirmHold is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.confirmHold = tmp.toBoolean(); + } } if (obj->getProperty("confirmType", &tmp)) { SE_PRECONDITION2(tmp.isString(), false, "confirmType is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.confirmType = tmp.toString(); + } } if (obj->getProperty("inputType", &tmp)) { SE_PRECONDITION2(tmp.isString(), false, "inputType is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.inputType = tmp.toString(); + } } if (obj->getProperty("originX", &tmp)) { SE_PRECONDITION2(tmp.isNumber(), false, "originX is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.x = tmp.toInt32(); + } } if (obj->getProperty("originY", &tmp)) { SE_PRECONDITION2(tmp.isNumber(), false, "originY is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.y = tmp.toInt32(); + } } if (obj->getProperty("width", &tmp)) { SE_PRECONDITION2(tmp.isNumber(), false, "width is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.width = tmp.toInt32(); + } } if (obj->getProperty("height", &tmp)) { SE_PRECONDITION2(tmp.isNumber(), false, "height is invalid!"); - if (!tmp.isUndefined()) + if (!tmp.isUndefined()) { showInfo.height = tmp.toInt32(); + } } - EditBox::show(showInfo); + cc::EditBox::show(showInfo); return true; } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", static_cast(argc), 1); return false; } -SE_BIND_FUNC(JSB_showInputBox); +SE_BIND_FUNC(jsbShowInputBox); -static bool JSB_hideInputBox(se::State &s) { - EditBox::hide(); +static bool jsbHideInputBox(se::State &s) { + cc::EditBox::hide(); return true; } -SE_BIND_FUNC(JSB_hideInputBox) +SE_BIND_FUNC(jsbHideInputBox) #endif bool jsb_register_global_variables(se::Object *global) { - __threadPool = LegacyThreadPool::newFixedThreadPool(3); + threadPool = LegacyThreadPool::newFixedThreadPool(3); global->defineFunction("require", _SE(require)); global->defineFunction("requireModule", _SE(moduleRequire)); - getOrCreatePlainObject_r("jsb", global, &__jsbObj); + getOrCreatePlainObjectR("jsb", global, &__jsbObj); - auto glContextCls = se::Class::create("WebGLRenderingContext", global, nullptr, nullptr); + auto *glContextCls = se::Class::create("WebGLRenderingContext", global, nullptr, nullptr); glContextCls->install(); - __jsbObj->defineFunction("garbageCollect", _SE(jsc_garbageCollect)); - __jsbObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jsc_dumpNativePtrToSeObjectMap)); + __jsbObj->defineFunction("garbageCollect", _SE(jscGarbageCollect)); + __jsbObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jscDumpNativePtrToSeObjectMap)); - __jsbObj->defineFunction("loadImage", _SE(js_loadImage)); - __jsbObj->defineFunction("openURL", _SE(JSB_openURL)); - __jsbObj->defineFunction("copyTextToClipboard", _SE(JSB_copyTextToClipboard)); - __jsbObj->defineFunction("setPreferredFramesPerSecond", _SE(JSB_setPreferredFramesPerSecond)); - __jsbObj->defineFunction("destroyImage", _SE(js_destroyImage)); + __jsbObj->defineFunction("loadImage", _SE(jsLoadImage)); + __jsbObj->defineFunction("openURL", _SE(jsbOpenUrl)); + __jsbObj->defineFunction("copyTextToClipboard", _SE(jsbCopyTextToClipboard)); + __jsbObj->defineFunction("setPreferredFramesPerSecond", _SE(jsbSetPreferredFramesPerSecond)); + __jsbObj->defineFunction("destroyImage", _SE(jsDestroyImage)); #if CC_USE_EDITBOX - __jsbObj->defineFunction("showInputBox", _SE(JSB_showInputBox)); - __jsbObj->defineFunction("hideInputBox", _SE(JSB_hideInputBox)); + __jsbObj->defineFunction("showInputBox", _SE(jsbShowInputBox)); + __jsbObj->defineFunction("hideInputBox", _SE(jsbHideInputBox)); #endif - __jsbObj->defineFunction("setCursorEnabled", _SE(JSB_setCursorEnabled)); - __jsbObj->defineFunction("saveByteCode", _SE(JSB_saveByteCode)); - global->defineFunction("__getPlatform", _SE(JSBCore_platform)); - global->defineFunction("__getOS", _SE(JSBCore_os)); - global->defineFunction("__getOSVersion", _SE(JSB_getOSVersion)); - global->defineFunction("__getCurrentLanguage", _SE(JSBCore_getCurrentLanguage)); - global->defineFunction("__getCurrentLanguageCode", _SE(JSBCore_getCurrentLanguageCode)); - global->defineFunction("__restartVM", _SE(JSB_core_restartVM)); - global->defineFunction("__isObjectValid", _SE(JSB_isObjectValid)); + __jsbObj->defineFunction("setCursorEnabled", _SE(jsbSetCursorEnabled)); + __jsbObj->defineFunction("saveByteCode", _SE(jsbSaveByteCode)); + global->defineFunction("__getPlatform", _SE(jsbCorePlatform)); + global->defineFunction("__getOS", _SE(jsbCoreOs)); + global->defineFunction("__getOSVersion", _SE(jsbGetOsVersion)); + global->defineFunction("__getCurrentLanguage", _SE(jsbCoreGetCurrentLanguage)); + global->defineFunction("__getCurrentLanguageCode", _SE(jsbCoreGetCurrentLanguageCode)); + global->defineFunction("__restartVM", _SE(jsbCoreRestartVm)); + global->defineFunction("__isObjectValid", _SE(jsbIsObjectValid)); + global->defineFunction("__close", _SE(jsbCloseWindow)); se::HandleObject performanceObj(se::Object::createPlainObject()); - performanceObj->defineFunction("now", _SE(js_performance_now)); + performanceObj->defineFunction("now", _SE(jsPerformanceNow)); global->setProperty("performance", se::Value(performanceObj)); se::ScriptEngine::getInstance()->clearException(); se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() { - delete __threadPool; - __threadPool = nullptr; + delete threadPool; + threadPool = nullptr; - PoolManager::getInstance()->getCurrentPool()->clear(); + cc::PoolManager::getInstance()->getCurrentPool()->clear(); }); se::ScriptEngine::getInstance()->addAfterCleanupHook([]() { - PoolManager::getInstance()->getCurrentPool()->clear(); + cc::PoolManager::getInstance()->getCurrentPool()->clear(); - __moduleCache.clear(); + moduleCache.clear(); SAFE_DEC_REF(__jsbObj); SAFE_DEC_REF(__glObj); diff --git a/native/cocos/platform/Application.cpp b/native/cocos/platform/Application.cpp index 058ae7312b..c03c42eaf7 100644 --- a/native/cocos/platform/Application.cpp +++ b/native/cocos/platform/Application.cpp @@ -38,7 +38,6 @@ namespace cc { void Application::restartVM() { - cc::EventDispatcher::dispatchRestartVM(); auto *scriptEngine = se::ScriptEngine::getInstance(); @@ -52,8 +51,8 @@ void Application::restartVM() { #endif cc::network::HttpClient::destroyInstance(); - _scheduler->removeAllFunctionsToBePerformedInCocosThread(); - _scheduler->unscheduleAll(); + scheduler->removeAllFunctionsToBePerformedInCocosThread(); + scheduler->unscheduleAll(); scriptEngine->cleanup(); cc::EventDispatcher::destroy(); @@ -64,8 +63,34 @@ void Application::restartVM() { init(); } -void Application::tick() { +void Application::close() { // NOLINT + if (cc::EventDispatcher::initialized()) { + cc::EventDispatcher::dispatchCloseEvent(); + } + auto *scriptEngine = se::ScriptEngine::getInstance(); + + cc::PoolManager::getInstance()->getCurrentPool()->clear(); +#if USE_AUDIO + cc::AudioEngine::stopAll(); +#endif +#if USE_SOCKET + cc::network::WebSocket::closeAllConnections(); +#endif + cc::network::HttpClient::destroyInstance(); + + scheduler->removeAllFunctionsToBePerformedInCocosThread(); + scheduler->unscheduleAll(); + + scriptEngine->cleanup(); + cc::EventDispatcher::destroy(); + + // exit + + exit(0); +} + +void Application::tick() { if (_needRestart) { restartVM(); _needRestart = false; @@ -73,23 +98,23 @@ void Application::tick() { static std::chrono::steady_clock::time_point prevTime; static std::chrono::steady_clock::time_point now; - static float dt = 0.f; - static double dtNS = NANOSECONDS_60FPS; + static float dt = 0.F; + static double dtNS = NANOSECONDS_60FPS; ++_totalFrames; // iOS/macOS use its own fps limitation algorithm. #if (CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_WINDOWS) - if (dtNS < _prefererredNanosecondsPerFrame) { + if (dtNS < static_cast(_prefererredNanosecondsPerFrame)) { std::this_thread::sleep_for( - std::chrono::nanoseconds(_prefererredNanosecondsPerFrame - static_cast(dtNS))); - dtNS = _prefererredNanosecondsPerFrame; + std::chrono::nanoseconds(_prefererredNanosecondsPerFrame - static_cast(dtNS))); + dtNS = static_cast(_prefererredNanosecondsPerFrame); } #endif prevTime = std::chrono::steady_clock::now(); - _scheduler->update(dt); + scheduler->update(dt); cc::EventDispatcher::dispatchTickEvent(dt); AutoreleasePool *currentPool = PoolManager::getInstance()->getCurrentPool(); @@ -97,9 +122,9 @@ void Application::tick() { currentPool->clear(); } - now = std::chrono::steady_clock::now(); - dtNS = dtNS * 0.1 + 0.9 * std::chrono::duration_cast(now - prevTime).count(); - dt = (float)dtNS / NANOSECONDS_PER_SECOND; + now = std::chrono::steady_clock::now(); + dtNS = dtNS * 0.1 + 0.9 * static_cast(std::chrono::duration_cast(now - prevTime).count()); + dt = static_cast(dtNS) / NANOSECONDS_PER_SECOND; } } // namespace cc diff --git a/native/cocos/platform/Application.h b/native/cocos/platform/Application.h index 7e26ea7321..bc537c7861 100644 --- a/native/cocos/platform/Application.h +++ b/native/cocos/platform/Application.h @@ -26,15 +26,15 @@ #pragma once -#include #include +#include #include // // std::this_thread::sleep_for #include "base/Macros.h" -#include "bindings/event/EventDispatcher.h" -#include "base/Scheduler.h" #include "base/AutoreleasePool.h" +#include "base/Scheduler.h" #include "base/TypeDef.h" +#include "bindings/event/EventDispatcher.h" #include "math/Vec2.h" #define NANOSECONDS_PER_SECOND 1000000000 @@ -83,7 +83,7 @@ public: }; // This class is useful for internal usage. - static Application *getInstance() { return _instance; } + static Application *getInstance() { return instance; } Application(int width, int height); virtual ~Application(); @@ -91,14 +91,15 @@ public: virtual bool init(); virtual void onPause(); virtual void onResume(); + virtual void onClose(); void restart() { _needRestart = true; } - void tick(); - void restartVM(); - inline std::shared_ptr getScheduler() const { return _scheduler; } + void close(); + + inline std::shared_ptr getScheduler() const { return scheduler; } // NOLINT /** * @brief Sets the preferred frame rate for main loop callback. @@ -161,13 +162,13 @@ public: inline const cc::Vec2 &getViewLogicalSize() const { return _viewLogicalSize; } private: - static Application *_instance; - static std::shared_ptr _scheduler; - int _fps = 60; - long _prefererredNanosecondsPerFrame = NANOSECONDS_60FPS; - uint _totalFrames = 0; - cc::Vec2 _viewLogicalSize; - bool _needRestart = false; + static Application * instance; + static std::shared_ptr scheduler; + int _fps = 60; + int64_t _prefererredNanosecondsPerFrame = NANOSECONDS_60FPS; + uint _totalFrames = 0; + cc::Vec2 _viewLogicalSize; + bool _needRestart = false; }; // end of platform group diff --git a/native/cocos/platform/android/Application-android.cpp b/native/cocos/platform/android/Application-android.cpp index 6e2da1ee88..e3de02b035 100644 --- a/native/cocos/platform/android/Application-android.cpp +++ b/native/cocos/platform/android/Application-android.cpp @@ -25,16 +25,16 @@ THE SOFTWARE. ****************************************************************************/ -#include "platform/Application.h" -#include #include -#include "platform/android/jni/JniImp.h" -#include "base/Scheduler.h" +#include #include "audio/include/AudioEngine.h" -#include "cocos/bindings/jswrapper/SeApi.h" +#include "base/Scheduler.h" #include "cocos/bindings/event/EventDispatcher.h" -#include "platform/android/jni/JniHelper.h" +#include "cocos/bindings/jswrapper/SeApi.h" +#include "platform/Application.h" #include "platform/android/jni/JniCocosActivity.h" +#include "platform/android/jni/JniHelper.h" +#include "platform/android/jni/JniImp.h" #include "pipeline/Define.h" #include "pipeline/RenderPipeline.h" @@ -55,23 +55,23 @@ namespace cc { namespace { -bool setCanvasCallback(se::Object *global) { - auto viewLogicalSize = cc::Application::getInstance()->getViewLogicalSize(); +bool setCanvasCallback(se::Object * /*global*/) { + auto viewLogicalSize = cc::Application::getInstance()->getViewLogicalSize(); se::AutoHandleScope scope; - se::ScriptEngine *se = se::ScriptEngine::getInstance(); - char commandBuf[200] = {0}; + se::ScriptEngine * se = se::ScriptEngine::getInstance(); + char commandBuf[200] = {0}; sprintf(commandBuf, "window.innerWidth = %d; window.innerHeight = %d; window.windowHandler = 0x%" PRIxPTR ";", - (int)(viewLogicalSize.x), - (int)(viewLogicalSize.y), - (uintptr_t)cc::cocosApp.window); + static_cast(viewLogicalSize.x), + static_cast(viewLogicalSize.y), + reinterpret_cast(cc::cocosApp.window)); se->evalString(commandBuf); gfx::DeviceInfo deviceInfo; - deviceInfo.windowHandle = (uintptr_t)cc::cocosApp.window; - deviceInfo.width = viewLogicalSize.x; - deviceInfo.height = viewLogicalSize.y; - deviceInfo.nativeWidth = viewLogicalSize.x; - deviceInfo.nativeHeight = viewLogicalSize.y; + deviceInfo.windowHandle = reinterpret_cast(cc::cocosApp.window); + deviceInfo.width = static_cast(viewLogicalSize.x); + deviceInfo.height = static_cast(viewLogicalSize.y); + deviceInfo.nativeWidth = static_cast(viewLogicalSize.x); + deviceInfo.nativeHeight = static_cast(viewLogicalSize.y); deviceInfo.bindingMappingInfo = pipeline::bindingMappingInfo; gfx::DeviceManager::create(deviceInfo); @@ -81,14 +81,14 @@ bool setCanvasCallback(se::Object *global) { } // namespace -Application *Application::_instance = nullptr; -std::shared_ptr Application::_scheduler = nullptr; +Application * Application::instance = nullptr; +std::shared_ptr Application::scheduler = nullptr; Application::Application(int width, int height) { - Application::_instance = this; - _scheduler = std::make_shared(); - _viewLogicalSize.x = width; - _viewLogicalSize.y = height; + Application::instance = this; + scheduler = std::make_shared(); + _viewLogicalSize.x = static_cast(width); + _viewLogicalSize.y = static_cast(height); } Application::~Application() { @@ -96,6 +96,11 @@ Application::~Application() { AudioEngine::end(); #endif + Application::getInstance()->onClose(); + if (EventDispatcher::initialized()) { + EventDispatcher::dispatchCloseEvent(); + } + pipeline::RenderPipeline::getInstance()->destroy(); EventDispatcher::destroy(); @@ -103,7 +108,7 @@ Application::~Application() { gfx::DeviceManager::destroy(); - Application::_instance = nullptr; + Application::instance = nullptr; } bool Application::init() { @@ -121,29 +126,33 @@ void Application::onPause() { void Application::onResume() { } -void Application::setPreferredFramesPerSecond(int fps) { - if (fps == 0) - return; - - _fps = fps; - _prefererredNanosecondsPerFrame = (long)(1.0 / _fps * NANOSECONDS_PER_SECOND); +void Application::onClose() { } -std::string Application::getCurrentLanguageCode() const { +void Application::setPreferredFramesPerSecond(int fps) { + if (fps == 0) { + return; + } + + _fps = fps; + _prefererredNanosecondsPerFrame = static_cast(1.0 / _fps * NANOSECONDS_PER_SECOND); +} + +std::string Application::getCurrentLanguageCode() const { // NOLINT return getCurrentLanguageCodeJNI(); } -bool Application::isDisplayStats() { +bool Application::isDisplayStats() { //NOLINT se::AutoHandleScope hs; - se::Value ret; - char commandBuf[100] = "cc.debug.isDisplayStats();"; + se::Value ret; + char commandBuf[100] = "cc.debug.isDisplayStats();"; se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret); return ret.toBoolean(); } -void Application::setDisplayStats(bool isShow) { +void Application::setDisplayStats(bool isShow) { // NOLINT se::AutoHandleScope hs; - char commandBuf[100] = {0}; + char commandBuf[100] = {0}; sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false"); se::ScriptEngine::getInstance()->evalString(commandBuf); } @@ -151,10 +160,10 @@ void Application::setDisplayStats(bool isShow) { void Application::setCursorEnabled(bool value) { } -Application::LanguageType Application::getCurrentLanguage() const { - std::string languageName = getCurrentLanguageJNI(); - const char *pLanguageName = languageName.c_str(); - LanguageType ret = LanguageType::ENGLISH; +Application::LanguageType Application::getCurrentLanguage() const { // NOLINT + std::string languageName = getCurrentLanguageJNI(); + const char * pLanguageName = languageName.c_str(); + LanguageType ret = LanguageType::ENGLISH; if (0 == strcmp("zh", pLanguageName)) { ret = LanguageType::CHINESE; @@ -198,19 +207,19 @@ Application::LanguageType Application::getCurrentLanguage() const { return ret; } -Application::Platform Application::getPlatform() const { +Application::Platform Application::getPlatform() const { // NOLINT return Platform::ANDROIDOS; } -bool Application::openURL(const std::string &url) { +bool Application::openURL(const std::string &url) { // NOLINT return openURLJNI(url); } -void Application::copyTextToClipboard(const std::string &text) { +void Application::copyTextToClipboard(const std::string &text) { // NOLINT copyTextToClipboardJNI(text); } -std::string Application::getSystemVersion() { +std::string Application::getSystemVersion() { // NOLINT return getSystemVersionJNI(); } diff --git a/native/cocos/platform/android/View.cpp b/native/cocos/platform/android/View.cpp index 797dccab1e..1815ffd4f8 100644 --- a/native/cocos/platform/android/View.cpp +++ b/native/cocos/platform/android/View.cpp @@ -27,13 +27,13 @@ #include "View.h" #include -#include "cocos/bindings/event/EventDispatcher.h" #include "cocos/bindings/event/CustomEventTypes.h" +#include "cocos/bindings/event/EventDispatcher.h" #include "platform/Application.h" #include "platform/android/jni/JniCocosActivity.h" namespace { -struct cc::TouchEvent touchEvent; +struct cc::TouchEvent touchEvent; struct cc::KeyboardEvent keyboardEvent; // key values in web, refer to http://docs.cocos.com/creator/api/en/enums/KEY.html @@ -50,8 +50,8 @@ std::unordered_map keyCodeMap = { void dispatchTouchEvent(int index, AInputEvent *event, cc::TouchEvent *touchEvent) { int pointerID = AMotionEvent_getPointerId(event, index); touchEvent->touches.emplace_back(AMotionEvent_getX(event, index), // x - AMotionEvent_getY(event, index), // y - pointerID); + AMotionEvent_getY(event, index), // y + pointerID); cc::EventDispatcher::dispatchTouchEvent(*touchEvent); touchEvent->touches.clear(); @@ -61,8 +61,8 @@ void dispatchTouchEvents(AInputEvent *event, cc::TouchEvent *touchEvent) { size_t pointerCount = AMotionEvent_getPointerCount(event); for (size_t i = 0; i < pointerCount; ++i) { touchEvent->touches.emplace_back(AMotionEvent_getX(event, i), - AMotionEvent_getY(event, i), - AMotionEvent_getPointerId(event, i)); + AMotionEvent_getY(event, i), + AMotionEvent_getPointerId(event, i)); } cc::EventDispatcher::dispatchTouchEvent(*touchEvent); @@ -76,20 +76,19 @@ void View::engineHandleCmd(int cmd) { static bool isWindowInitialized = false; // Handle CMD here if needed. switch (cmd) { - case APP_CMD_INIT_WINDOW: + case APP_CMD_INIT_WINDOW: { if (!isWindowInitialized) { isWindowInitialized = true; return; - } else { - cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; - event.args->ptrVal = cocosApp.window; - cc::EventDispatcher::dispatchCustomEvent(event); } - break; + cc::CustomEvent event; + event.name = EVENT_RECREATE_WINDOW; + event.args->ptrVal = cocosApp.window; + cc::EventDispatcher::dispatchCustomEvent(event); + } break; case APP_CMD_TERM_WINDOW: { cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; + event.name = EVENT_DESTROY_WINDOW; event.args->ptrVal = cocosApp.window; cc::EventDispatcher::dispatchCustomEvent(event); } break; @@ -130,7 +129,7 @@ int32_t View::engineHandleInput(struct android_app * /*app*/, AInputEvent *event keyCode = 0; } - keyboardEvent.key = keyCode; + keyboardEvent.key = keyCode; keyboardEvent.action = action == AKEY_EVENT_ACTION_DOWN ? cc::KeyboardEvent::Action::RELEASE : cc::KeyboardEvent::Action::PRESS; diff --git a/native/cocos/platform/ios/Application-ios.mm b/native/cocos/platform/ios/Application-ios.mm index 6b021bcb03..b1bbdd4815 100644 --- a/native/cocos/platform/ios/Application-ios.mm +++ b/native/cocos/platform/ios/Application-ios.mm @@ -90,35 +90,35 @@ namespace cc { namespace { - bool setCanvasCallback(se::Object* global) { + bool setCanvasCallback(se::Object *global) { auto viewLogicalSize = cc::Application::getInstance()->getViewLogicalSize(); - int nativeWidth = static_cast(viewLogicalSize.y * Device::getDevicePixelRatio()); - int nativeHeight = static_cast(viewLogicalSize.x * Device::getDevicePixelRatio()); - auto orientation = cc::Device::getDeviceOrientation(); - bool isLandscape = (orientation == cc::Device::Orientation::LANDSCAPE_RIGHT || orientation == cc::Device::Orientation::LANDSCAPE_LEFT); + int nativeWidth = static_cast(viewLogicalSize.y * Device::getDevicePixelRatio()); + int nativeHeight = static_cast(viewLogicalSize.x * Device::getDevicePixelRatio()); + auto orientation = cc::Device::getDeviceOrientation(); + bool isLandscape = (orientation == cc::Device::Orientation::LANDSCAPE_RIGHT || orientation == cc::Device::Orientation::LANDSCAPE_LEFT); if (isLandscape) std::swap(nativeWidth, nativeHeight); // https://stackoverflow.com/questions/5795978/string-format-for-intptr-t-and-uintptr-t/41897226#41897226 // format intptr_t //set window.innerWidth/innerHeight in css pixel units - uintptr_t windowHandle = reinterpret_cast(UIApplication.sharedApplication.delegate.window.rootViewController.view); + uintptr_t windowHandle = reinterpret_cast(UIApplication.sharedApplication.delegate.window.rootViewController.view); std::stringstream commandBuf; commandBuf << "window.innerWidth = " << viewLogicalSize.x - << "; window.innerHeight = " << viewLogicalSize.y - << "; window.nativeWidth= " << nativeWidth - << "; window.nativeHeight = " << nativeHeight - << "; window.windowHandler = " << windowHandle << ";"; + << "; window.innerHeight = " << viewLogicalSize.y + << "; window.nativeWidth= " << nativeWidth + << "; window.nativeHeight = " << nativeHeight + << "; window.windowHandler = " << windowHandle << ";"; - se::ScriptEngine* se = se::ScriptEngine::getInstance(); + se::ScriptEngine *se = se::ScriptEngine::getInstance(); se->evalString(commandBuf.str().c_str()); gfx::DeviceInfo deviceInfo; - deviceInfo.windowHandle = windowHandle; - deviceInfo.width = viewLogicalSize.x; - deviceInfo.height = viewLogicalSize.y; - deviceInfo.nativeWidth = nativeWidth; - deviceInfo.nativeHeight = nativeHeight; + deviceInfo.windowHandle = windowHandle; + deviceInfo.width = viewLogicalSize.x; + deviceInfo.height = viewLogicalSize.y; + deviceInfo.nativeWidth = nativeWidth; + deviceInfo.nativeHeight = nativeHeight; deviceInfo.bindingMappingInfo = pipeline::bindingMappingInfo; gfx::DeviceManager::create(deviceInfo); @@ -126,15 +126,15 @@ namespace { return true; } - MyTimer* _timer; + MyTimer *_timer; } -Application *Application::_instance = nullptr; -std::shared_ptr Application::_scheduler = nullptr; +Application * Application::instance = nullptr; +std::shared_ptr Application::scheduler = nullptr; Application::Application(int width, int height) { - Application::_instance = this; - _scheduler = std::make_shared(); + Application::instance = this; + scheduler = std::make_shared(); EventDispatcher::init(); _viewLogicalSize.x = width; _viewLogicalSize.y = height; @@ -154,7 +154,7 @@ Application::~Application() { gfx::DeviceManager::destroy(); - Application::_instance = nullptr; + Application::instance = nullptr; [_timer release]; } @@ -256,6 +256,9 @@ void Application::onResume() { [_timer resume]; } +void Application::onClose() { +} + std::string Application::getSystemVersion() { NSString *systemVersion = [UIDevice currentDevice].systemVersion; return [systemVersion UTF8String]; diff --git a/native/cocos/platform/mac/Application-mac.mm b/native/cocos/platform/mac/Application-mac.mm index 818e7ff2b9..578b711490 100644 --- a/native/cocos/platform/mac/Application-mac.mm +++ b/native/cocos/platform/mac/Application-mac.mm @@ -123,23 +123,22 @@ bool setCanvasCallback(se::Object *global) { MyTimer *_timer; } // namespace -Application * Application::_instance = nullptr; -std::shared_ptr Application::_scheduler = nullptr; +Application * Application::instance = nullptr; +std::shared_ptr Application::scheduler = nullptr; Application::Application(int width, int height) { - Application::_instance = this; + Application::instance = this; _viewLogicalSize.x = width; _viewLogicalSize.y = height; - _scheduler = std::make_shared(); + scheduler = std::make_shared(); EventDispatcher::init(); _timer = [[MyTimer alloc] initWithApp:this fps:_fps]; } Application::~Application() { - #if USE_AUDIO AudioEngine::end(); #endif @@ -154,7 +153,7 @@ Application::~Application() { gfx::DeviceManager::destroy(); - Application::_instance = nullptr; + Application::instance = nullptr; [_timer release]; } @@ -256,6 +255,9 @@ void Application::onResume() { [_timer resume]; } +void Application::onClose() { +} + std::string Application::getSystemVersion() { NSOperatingSystemVersion v = NSProcessInfo.processInfo.operatingSystemVersion; char version[50] = {0}; diff --git a/native/cocos/platform/win32/Application-win32.cpp b/native/cocos/platform/win32/Application-win32.cpp index 34458b202b..86740ae012 100644 --- a/native/cocos/platform/win32/Application-win32.cpp +++ b/native/cocos/platform/win32/Application-win32.cpp @@ -50,12 +50,12 @@ extern std::shared_ptr cc_get_application_view(); namespace cc { -Application * Application::_instance = nullptr; -std::shared_ptr Application::_scheduler = nullptr; +Application * Application::instance = nullptr; +std::shared_ptr Application::scheduler = nullptr; Application::Application(int width, int height) { - Application::_instance = this; - _scheduler = std::make_shared(); + Application::instance = this; + scheduler = std::make_shared(); FileUtils::getInstance()->addSearchPath("Resources", true); @@ -64,7 +64,6 @@ Application::Application(int width, int height) { } Application::~Application() { - #if USE_AUDIO AudioEngine::end(); #endif @@ -76,7 +75,7 @@ Application::~Application() { gfx::DeviceManager::destroy(); - Application::_instance = nullptr; + Application::instance = nullptr; } bool Application::init() { @@ -90,7 +89,7 @@ bool Application::init() { auto viewSize = view->getViewSize(); gfx::DeviceInfo deviceInfo; - deviceInfo.windowHandle = (uintptr_t)view->getWindowHandler(); + deviceInfo.windowHandle = reinterpret_cast(view->getWindowHandler()); deviceInfo.width = viewSize[0]; deviceInfo.height = viewSize[1]; deviceInfo.nativeWidth = viewSize[0]; @@ -107,7 +106,7 @@ void Application::setPreferredFramesPerSecond(int fps) { return; _fps = fps; - _prefererredNanosecondsPerFrame = (long)(1.0 / _fps * NANOSECONDS_PER_SECOND); + _prefererredNanosecondsPerFrame = static_cast(1.0 / _fps * NANOSECONDS_PER_SECOND); } Application::LanguageType Application::getCurrentLanguage() const { @@ -233,6 +232,9 @@ void Application::onPause() { void Application::onResume() { } +void Application::onClose() { +} + std::string Application::getSystemVersion() { OSVERSIONINFO osvi; memset(&osvi, 0, sizeof(osvi)); diff --git a/native/cocos/platform/win32/View-win32.cpp b/native/cocos/platform/win32/View-win32.cpp index c834d4fe89..fa6afdf0fe 100644 --- a/native/cocos/platform/win32/View-win32.cpp +++ b/native/cocos/platform/win32/View-win32.cpp @@ -24,18 +24,17 @@ ****************************************************************************/ #include "View-win32.h" -#include "base/Log.h" #include +#include "base/Log.h" using namespace cc; namespace { std::unordered_map gKeyMap = { - {SDLK_ESCAPE, KeyCode::Escape}, {SDLK_MINUS, KeyCode::Minus}, {SDLK_LSHIFT, KeyCode::ShiftLeft}, {SDLK_RSHIFT, KeyCode::ShiftRight}, {SDLK_EQUALS, KeyCode::Equal}, {SDLK_BACKSLASH, KeyCode::Backslash}, {SDLK_BACKQUOTE, KeyCode::Backquote}, {SDLK_BACKSPACE, KeyCode::Backspace}, {SDLK_RETURN, KeyCode::Enter}, {SDLK_RETURN2, KeyCode::Enter}, {SDLK_LEFTBRACKET, KeyCode::BracketLeft}, {SDLK_RIGHTBRACKET, KeyCode::BracketRight}, {SDLK_SEMICOLON, KeyCode::Semicolon}, {SDLK_QUOTE, KeyCode::Quote}, {SDLK_TAB, KeyCode::Tab}, {SDLK_LCTRL, KeyCode::ControlLeft}, {SDLK_RCTRL, KeyCode::ControlRight}, {SDLK_LALT, KeyCode::AltLeft}, {SDLK_RALT, KeyCode::AltRight}, {SDLK_LEFT, KeyCode::ArrowLeft}, {SDLK_RIGHT, KeyCode::ArrowRight}, {SDLK_UP, KeyCode::ArrowUp}, {SDLK_DOWN, KeyCode::ArrowDown}, {SDLK_KP_ENTER, KeyCode::NumpadEnter}, {SDLK_KP_PLUS, KeyCode::NumpadPlus}, {SDLK_KP_MULTIPLY, KeyCode::NumpadMultiply}, {SDLK_KP_DIVIDE, KeyCode::NumpadDivide}, {SDLK_KP_MINUS, KeyCode::NumpadMinus}, {SDLK_KP_PERIOD, KeyCode::NumpadDecimal}, {SDLK_KP_BACKSPACE, KeyCode::Backspace}, {SDLK_NUMLOCKCLEAR, KeyCode::NumLock}, {SDLK_HOME, KeyCode::Home}, {SDLK_PAGEUP, KeyCode::PageUp}, {SDLK_PAGEDOWN, KeyCode::PageDown}, {SDLK_END, KeyCode::End}, {SDLK_COMMA, KeyCode::Comma}, {SDLK_PERIOD, KeyCode::Period}, {SDLK_SLASH, KeyCode::Slash}, {SDLK_SPACE, KeyCode::Space}, {SDLK_DELETE, KeyCode::Delete}, {SDLK_CAPSLOCK, KeyCode::CapsLock}, {SDLK_KP_0, KeyCode::NUMPAD_0}, {SDLK_KP_1, KeyCode::NUMPAD_1}, {SDLK_KP_2, KeyCode::NUMPAD_2}, {SDLK_KP_3, KeyCode::NUMPAD_3}, {SDLK_KP_4, KeyCode::NUMPAD_4}, {SDLK_KP_5, KeyCode::NUMPAD_5}, {SDLK_KP_6, KeyCode::NUMPAD_6}, {SDLK_KP_7, KeyCode::NUMPAD_7}, {SDLK_KP_8, KeyCode::NUMPAD_8}, {SDLK_KP_9, KeyCode::NUMPAD_9}}; - -int sdl_keycode_to_cocos_code(int code_, int mode) { + {SDLK_ESCAPE, KeyCode::ESCAPE}, {SDLK_MINUS, KeyCode::MINUS}, {SDLK_LSHIFT, KeyCode::SHIFT_LEFT}, {SDLK_RSHIFT, KeyCode::SHIFT_RIGHT}, {SDLK_EQUALS, KeyCode::EQUAL}, {SDLK_BACKSLASH, KeyCode::BACKSLASH}, {SDLK_BACKQUOTE, KeyCode::BACKQUOTE}, {SDLK_BACKSPACE, KeyCode::BACKSPACE}, {SDLK_RETURN, KeyCode::ENTER}, {SDLK_RETURN2, KeyCode::ENTER}, {SDLK_LEFTBRACKET, KeyCode::BRACKET_LEFT}, {SDLK_RIGHTBRACKET, KeyCode::BRACKET_RIGHT}, {SDLK_SEMICOLON, KeyCode::SEMICOLON}, {SDLK_QUOTE, KeyCode::QUOTE}, {SDLK_TAB, KeyCode::TAB}, {SDLK_LCTRL, KeyCode::CONTROL_LEFT}, {SDLK_RCTRL, KeyCode::CONTROL_RIGHT}, {SDLK_LALT, KeyCode::ALT_LEFT}, {SDLK_RALT, KeyCode::ALT_RIGHT}, {SDLK_LEFT, KeyCode::ARROW_LEFT}, {SDLK_RIGHT, KeyCode::ARROW_RIGHT}, {SDLK_UP, KeyCode::ARROW_UP}, {SDLK_DOWN, KeyCode::ARROW_DOWN}, {SDLK_KP_ENTER, KeyCode::NUMPAD_ENTER}, {SDLK_KP_PLUS, KeyCode::NUMPAD_PLUS}, {SDLK_KP_MULTIPLY, KeyCode::NUMPAD_MULTIPLY}, {SDLK_KP_DIVIDE, KeyCode::NUMPAD_DIVIDE}, {SDLK_KP_MINUS, KeyCode::NUMPAD_MINUS}, {SDLK_KP_PERIOD, KeyCode::NUMPAD_DECIMAL}, {SDLK_KP_BACKSPACE, KeyCode::BACKSPACE}, {SDLK_NUMLOCKCLEAR, KeyCode::NUM_LOCK}, {SDLK_HOME, KeyCode::HOME}, {SDLK_PAGEUP, KeyCode::PAGE_UP}, {SDLK_PAGEDOWN, KeyCode::PAGE_DOWN}, {SDLK_END, KeyCode::END}, {SDLK_COMMA, KeyCode::COMMA}, {SDLK_PERIOD, KeyCode::PERIOD}, {SDLK_SLASH, KeyCode::SLASH}, {SDLK_SPACE, KeyCode::SPACE}, {SDLK_DELETE, KeyCode::DELETE_KEY}, {SDLK_CAPSLOCK, KeyCode::CAPS_LOCK}, {SDLK_KP_0, KeyCode::NUMPAD_0}, {SDLK_KP_1, KeyCode::NUMPAD_1}, {SDLK_KP_2, KeyCode::NUMPAD_2}, {SDLK_KP_3, KeyCode::NUMPAD_3}, {SDLK_KP_4, KeyCode::NUMPAD_4}, {SDLK_KP_5, KeyCode::NUMPAD_5}, {SDLK_KP_6, KeyCode::NUMPAD_6}, {SDLK_KP_7, KeyCode::NUMPAD_7}, {SDLK_KP_8, KeyCode::NUMPAD_8}, {SDLK_KP_9, KeyCode::NUMPAD_9}}; +int sdlKeycodeToCocosCode(int code_, int mode) { auto it = gKeyMap.find(code_); if (it != gKeyMap.end()) { return static_cast(it->second); @@ -90,7 +89,7 @@ bool View::init() { return true; } -bool View::pollEvent(bool *quit, bool *resume, bool *pause) { +bool View::pollEvent(bool *quit, bool *resume, bool *pause, bool *close) { int cnt = SDL_PollEvent(&sdlEvent); if (cnt == 0) return false; cc::TouchEvent touch; @@ -119,6 +118,9 @@ bool View::pollEvent(bool *quit, bool *resume, bool *pause) { case SDL_WINDOWEVENT_ENTER: SDL_CaptureMouse(SDL_TRUE); break; + case SDL_WINDOWEVENT_CLOSE: + *close = true; + break; } break; } @@ -183,7 +185,7 @@ bool View::pollEvent(bool *quit, bool *resume, bool *pause) { SDL_KeyboardEvent &event = sdlEvent.key; auto mode = event.keysym.mod; keyboard.action = KeyboardEvent::Action::PRESS; - keyboard.key = sdl_keycode_to_cocos_code(event.keysym.sym, mode); + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); keyboard.altKeyActive = mode & KMOD_ALT; keyboard.ctrlKeyActive = mode & KMOD_CTRL; keyboard.shiftKeyActive = mode & KMOD_SHIFT; @@ -195,7 +197,7 @@ bool View::pollEvent(bool *quit, bool *resume, bool *pause) { SDL_KeyboardEvent &event = sdlEvent.key; auto mode = event.keysym.mod; keyboard.action = KeyboardEvent::Action::RELEASE; - keyboard.key = sdl_keycode_to_cocos_code(event.keysym.sym, mode); + keyboard.key = sdlKeycodeToCocosCode(event.keysym.sym, mode); keyboard.altKeyActive = mode & KMOD_ALT; keyboard.ctrlKeyActive = mode & KMOD_CTRL; keyboard.shiftKeyActive = mode & KMOD_SHIFT; diff --git a/native/cocos/platform/win32/View-win32.h b/native/cocos/platform/win32/View-win32.h index 72b5aae639..b227a82e35 100644 --- a/native/cocos/platform/win32/View-win32.h +++ b/native/cocos/platform/win32/View-win32.h @@ -25,16 +25,16 @@ #pragma once +#include +#include +#include +#include #include "base/Macros.h" #include "platform/StdC.h" -#include -#include -#include -#include // SDL headers -#include "sdl2/SDL_main.h" #include "sdl2/SDL.h" +#include "sdl2/SDL_main.h" #include "sdl2/SDL_syswm.h" #include "cocos/bindings/event/EventDispatcher.h" @@ -48,7 +48,7 @@ public: bool init(); - bool pollEvent(bool *quit, bool *resume, bool *pause); + bool pollEvent(bool *quit, bool *resume, bool *pause, bool *close); std::array getViewSize() const { return std::array{_width, _height}; } @@ -60,12 +60,12 @@ public: private: std::string _title; - int _width = 0; - int _height = 0; - bool _inited = false; + int _width = 0; + int _height = 0; + bool _inited = false; SDL_Window *_window = nullptr; - SDL_Event sdlEvent; + SDL_Event sdlEvent; }; } // namespace cc diff --git a/native/templates/common/Classes/Game.cpp b/native/templates/common/Classes/Game.cpp index e22f743dd4..fd6cb06a6b 100644 --- a/native/templates/common/Classes/Game.cpp +++ b/native/templates/common/Classes/Game.cpp @@ -76,18 +76,15 @@ bool Game::init() { void Game::onPause() { cc::Application::onPause(); - - cc::CustomEvent event; - event.name = EVENT_COME_TO_BACKGROUND; - cc::EventDispatcher::dispatchCustomEvent(event); cc::EventDispatcher::dispatchEnterBackgroundEvent(); } void Game::onResume() { cc::Application::onResume(); - - cc::CustomEvent event; - event.name = EVENT_COME_TO_FOREGROUND; - cc::EventDispatcher::dispatchCustomEvent(event); cc::EventDispatcher::dispatchEnterForegroundEvent(); } + +void Game::onClose() { + cc::Application::onClose(); + cc::EventDispatcher::dispatchCloseEvent(); +} diff --git a/native/templates/common/Classes/Game.h b/native/templates/common/Classes/Game.h index 1caa08b145..e5114d0bd3 100644 --- a/native/templates/common/Classes/Game.h +++ b/native/templates/common/Classes/Game.h @@ -30,14 +30,14 @@ The reason for implement as private inheritance is to hide some interface call by Director. */ -class Game : public cc::Application -{ +class Game : public cc::Application { public: /** * width and height in logical pixel unit */ Game(int width, int height); - virtual bool init() override; - virtual void onPause() override; - virtual void onResume() override; + bool init() override; + void onPause() override; + void onResume() override; + void onClose() override; }; diff --git a/native/templates/ios/AppDelegate.mm b/native/templates/ios/AppDelegate.mm index c292532941..bbb50c011e 100644 --- a/native/templates/ios/AppDelegate.mm +++ b/native/templates/ios/AppDelegate.mm @@ -27,12 +27,12 @@ #import "ViewController.h" #include "platform/ios/View.h" -#include "SDKWrapper.h" #include "Game.h" +#include "SDKWrapper.h" @implementation AppDelegate -Game* game = nullptr; +Game * game = nullptr; @synthesize window; #pragma mark - @@ -42,19 +42,19 @@ Game* game = nullptr; [[SDKWrapper shared] application:application didFinishLaunchingWithOptions:launchOptions]; // Add the view controller's view to the window and display. CGRect bounds = [[UIScreen mainScreen] bounds]; - self.window = [[UIWindow alloc] initWithFrame: bounds]; + self.window = [[UIWindow alloc] initWithFrame:bounds]; // Should create view controller first, cc::Application will use it. - _viewController = [[ViewController alloc]init]; - _viewController.view = [[View alloc] initWithFrame:bounds]; - _viewController.view.contentScaleFactor = UIScreen.mainScreen.scale; + _viewController = [[ViewController alloc] init]; + _viewController.view = [[View alloc] initWithFrame:bounds]; + _viewController.view.contentScaleFactor = UIScreen.mainScreen.scale; _viewController.view.multipleTouchEnabled = true; [self.window setRootViewController:_viewController]; // cocos2d application instance game = new Game(bounds.size.width, bounds.size.height); game->init(); - + [self.window makeKeyAndVisible]; return YES; @@ -73,7 +73,7 @@ Game* game = nullptr; /* Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. */ - [[SDKWrapper shared] applicationDidBecomeActive:application]; + [[SDKWrapper shared] applicationDidBecomeActive:application]; game->onResume(); } @@ -93,6 +93,7 @@ Game* game = nullptr; } - (void)applicationWillTerminate:(UIApplication *)application { + game->onClose(); [[SDKWrapper shared] applicationWillTerminate:application]; delete game; game = nullptr; diff --git a/native/templates/mac/AppDelegate.mm b/native/templates/mac/AppDelegate.mm index 8f7ca24068..b3184cfa26 100644 --- a/native/templates/mac/AppDelegate.mm +++ b/native/templates/mac/AppDelegate.mm @@ -41,6 +41,10 @@ selector:@selector(windowDidDeminiaturizeNotification) name:NSWindowDidDeminiaturizeNotification object:_window]; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(windowWillCloseNotification) + name:NSWindowWillCloseNotification + object:_window]; } - (void)windowWillMiniaturizeNotification { @@ -51,6 +55,10 @@ _game->onResume(); } +- (void)windowWillCloseNotification { + _game->onClose(); +} + - (NSWindow*)getWindow { return _window; } diff --git a/native/templates/win32/AppDelegate.cpp b/native/templates/win32/AppDelegate.cpp index 2e0d27d6a5..84029ef03b 100644 --- a/native/templates/win32/AppDelegate.cpp +++ b/native/templates/win32/AppDelegate.cpp @@ -9,87 +9,80 @@ #include "platform/win32/View-win32.h" #include "cocos/bindings/jswrapper/SeApi.h" -namespace -{ +namespace { std::weak_ptr gView; /** - @brief This function changes the PVRFrame show/hide setting in register. - @param bEnable If true show the PVRFrame window, otherwise hide. - */ - void PVRFrameEnableControlWindow(bool bEnable) - { + @brief This function changes the PVRFrame show/hide setting in register. + @param bEnable If true show the PVRFrame window, otherwise hide. + */ + void PVRFrameEnableControlWindow(bool bEnable) { HKEY hKey = 0; // Open PVRFrame control key, if not exist create it. - if(ERROR_SUCCESS != RegCreateKeyExW(HKEY_CURRENT_USER, - L"Software\\Imagination Technologies\\PVRVFRame\\STARTUP\\", - 0, - 0, - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, - 0, - &hKey, - nullptr)) - { + if (ERROR_SUCCESS != RegCreateKeyExW(HKEY_CURRENT_USER, + L"Software\\Imagination Technologies\\PVRVFRame\\STARTUP\\", + 0, + 0, + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + 0, + &hKey, + nullptr)) { return; } - const WCHAR* wszValue = L"hide_gui"; - const WCHAR* wszNewData = (bEnable) ? L"NO" : L"YES"; - WCHAR wszOldData[256] = {0}; - DWORD dwSize = sizeof(wszOldData); - LSTATUS status = RegQueryValueExW(hKey, wszValue, 0, nullptr, (LPBYTE)wszOldData, &dwSize); - if (ERROR_FILE_NOT_FOUND == status // the key not exist - || (ERROR_SUCCESS == status // or the hide_gui value is exist - && 0 != wcscmp(wszNewData, wszOldData))) // but new data and old data not equal + const WCHAR* wszValue = L"hide_gui"; + const WCHAR* wszNewData = (bEnable) ? L"NO" : L"YES"; + WCHAR wszOldData[256] = {0}; + DWORD dwSize = sizeof(wszOldData); + LSTATUS status = RegQueryValueExW(hKey, wszValue, 0, nullptr, (LPBYTE)wszOldData, &dwSize); + if (ERROR_FILE_NOT_FOUND == status // the key not exist + || (ERROR_SUCCESS == status // or the hide_gui value is exist + && 0 != wcscmp(wszNewData, wszOldData))) // but new data and old data not equal { dwSize = sizeof(WCHAR) * (wcslen(wszNewData) + 1); - RegSetValueEx(hKey, wszValue, 0, REG_SZ, (const BYTE *)wszNewData, dwSize); + RegSetValueEx(hKey, wszValue, 0, REG_SZ, (const BYTE*)wszNewData, dwSize); } RegCloseKey(hKey); } - bool setCanvasCallback(se::Object* global) - { + bool setCanvasCallback(se::Object* global) { std::stringstream ss; - se::ScriptEngine* se = se::ScriptEngine::getInstance(); - auto view = gView.lock(); - auto handler = view->getWindowHandler(); - auto viewSize = view->getViewSize(); - char commandBuf[200] = { 0 }; + se::ScriptEngine* se = se::ScriptEngine::getInstance(); + auto view = gView.lock(); + auto handler = view->getWindowHandler(); + auto viewSize = view->getViewSize(); + char commandBuf[200] = {0}; ss << "window.innerWidth = " << viewSize[0] << "; " - << "window.innerHeight = " << viewSize[1] << "; " - << "window.windowHandler = " - << reinterpret_cast(handler) - << ";"; + << "window.innerHeight = " << viewSize[1] << "; " + << "window.windowHandler = " + << reinterpret_cast(handler) + << ";"; se->evalString(ss.str().c_str()); return true; } -} +} // namespace //exported function std::shared_ptr cc_get_application_view() { return gView.lock(); } -AppDelegage::AppDelegage(const std::string &name, int width, int height) -{ +AppDelegate::AppDelegate(const std::string& name, int width, int height) { _view = std::make_shared(name, width, height); _game = std::make_shared(width, height); gView = _view; } -void AppDelegage::start() -{ - - bool resume, pause; +void AppDelegate::start() { + bool resume, pause, close; se::ScriptEngine::getInstance()->addPermanentRegisterCallback(setCanvasCallback); - if(!_view->init()) return; - if(!_game->init()) return; + if (!_view->init()) return; + if (!_game->init()) return; if (!_view) return; @@ -101,16 +94,15 @@ void AppDelegage::start() /////////////////////////////////////////////////////////////////////////// /////////////// changing timer resolution /////////////////////////////////////////////////////////////////////////// - UINT TARGET_RESOLUTION = 1; // 1 millisecond target resolution + UINT TARGET_RESOLUTION = 1; // 1 millisecond target resolution TIMECAPS tc; - UINT wTimerRes = 0; - if (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(TIMECAPS))) - { + UINT wTimerRes = 0; + if (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(TIMECAPS))) { wTimerRes = std::min(std::max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax); timeBeginPeriod(wTimerRes); } - float dt = 0.f; + float dt = 0.f; const DWORD _16ms = 16; // Main message loop: @@ -118,38 +110,36 @@ void AppDelegage::start() LARGE_INTEGER nLast; LARGE_INTEGER nNow; - LONGLONG actualInterval = 0LL; // actual frame internal + LONGLONG actualInterval = 0LL; // actual frame internal LONGLONG desiredInterval = 0LL; // desired frame internal, 1 / fps - LONG waitMS = 0L; + LONG waitMS = 0L; QueryPerformanceCounter(&nLast); QueryPerformanceFrequency(&nFreq); se::ScriptEngine* se = se::ScriptEngine::getInstance(); - _game->onResume(); - while (!_quit) - { + while (!_quit) { desiredInterval = (LONGLONG)(1.0 / _game->getPreferredFramesPerSecond() * nFreq.QuadPart); - - resume = false; - pause = false; - while (_view->pollEvent(&_quit, &resume, &pause)) {} - if(pause) _game->onPause(); - if(resume) _game->onResume(); + resume = false; + pause = false; + close = false; + while (_view->pollEvent(&_quit, &resume, &pause, &close)) { + } + + if (pause) _game->onPause(); + if (resume) _game->onResume(); + if (close) _game->onClose(); QueryPerformanceCounter(&nNow); actualInterval = nNow.QuadPart - nLast.QuadPart; - if (actualInterval >= desiredInterval) - { + if (actualInterval >= desiredInterval) { nLast.QuadPart = nNow.QuadPart; _game->tick(); _view->swapbuffer(); - } - else - { + } else { // The precision of timer on Windows is set to highest (1ms) by 'timeBeginPeriod' from above code, // but it's still not precise enough. For example, if the precision of timer is 1ms, // Sleep(3) may make a sleep of 2ms or 4ms. Therefore, we subtract 1ms here to make Sleep time shorter. @@ -161,8 +151,6 @@ void AppDelegage::start() } } - if (wTimerRes != 0) timeEndPeriod(wTimerRes); - } diff --git a/native/templates/win32/AppDelegate.h b/native/templates/win32/AppDelegate.h index d4e4218964..48034238ea 100644 --- a/native/templates/win32/AppDelegate.h +++ b/native/templates/win32/AppDelegate.h @@ -8,9 +8,9 @@ namespace cc { class View; }; -class AppDelegage { +class AppDelegate { public: - AppDelegage(const std::string &name, int width, int height); + AppDelegate(const std::string &name, int width, int height); void start(); diff --git a/native/templates/win32/main.cpp b/native/templates/win32/main.cpp index 631c37fb66..150246e7c3 100644 --- a/native/templates/win32/main.cpp +++ b/native/templates/win32/main.cpp @@ -43,7 +43,7 @@ int SDL_main(int argc, char *argv[]) #endif // create the application instance - AppDelegage app("Cocos3D Game", 960, 640); + AppDelegate app("Cocos3D Game", 960, 640); app.start(); #ifdef USE_WIN32_CONSOLE diff --git a/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp b/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp index b475a5990c..5f60205732 100755 --- a/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp +++ b/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp @@ -85,22 +85,17 @@ bool Game::init() } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void Game::onPause() -{ +void Game::onPause() { cc::Application::onPause(); - - cc::CustomEvent event; - event.name = EVENT_COME_TO_BACKGROUND; - cc::EventDispatcher::dispatchCustomEvent(event); - cc::EventDispatcher::dispatchEnterBackgroundEvent();} - -// this function will be called when the app is active again -void Game::onResume() -{ - cc::Application::onResume(); - cc::CustomEvent event; - event.name = EVENT_COME_TO_FOREGROUND; - cc::EventDispatcher::dispatchCustomEvent(event); - cc::EventDispatcher::dispatchEnterForegroundEvent(); - + cc::EventDispatcher::dispatchEnterBackgroundEvent(); +} + +void Game::onResume() { + cc::Application::onResume(); + cc::EventDispatcher::dispatchEnterForegroundEvent(); +} + +void Game::onClose() { + cc::Application::onClose(); + cc::EventDispatcher::dispatchCloseEvent(); } diff --git a/native/tools/simulator/frameworks/runtime-src/Classes/Game.h b/native/tools/simulator/frameworks/runtime-src/Classes/Game.h index 4dae59a24c..2b3ae739bc 100755 --- a/native/tools/simulator/frameworks/runtime-src/Classes/Game.h +++ b/native/tools/simulator/frameworks/runtime-src/Classes/Game.h @@ -43,4 +43,5 @@ public: virtual bool init() override; virtual void onPause() override; virtual void onResume() override; + virtual void onClose() override; }; diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp index b959a1f098..363f48fb51 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp +++ b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorWin.cpp @@ -519,7 +519,7 @@ int SimulatorWin::run() // update window title updateWindowTitle(); - bool resume, pause; + bool resume, pause, close; se::ScriptEngine::getInstance()->addRegisterCallback(setCanvasCallback); if (!_app->init()) return 1; @@ -564,10 +564,12 @@ int SimulatorWin::run() resume = false; pause = false; - while (_view->pollEvent(&_quit, &resume, &pause)) {} + close = false; + while (_view->pollEvent(&_quit, &resume, &pause, &close)) {} if (pause) _app->onPause(); if (resume) _app->onResume(); + if (close) _app->onClose(); QueryPerformanceCounter(&nNow); actualInterval = nNow.QuadPart - nLast.QuadPart;