From cf8675a94981a6d9241a1638de6021ccc088f39e Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 10 Nov 2022 09:47:28 +0800 Subject: [PATCH] fixed #13232: [feature] Support to pass commandline arguments to JS (#13268) * [feature] Support to pass arguments to execution file and export them to JS ( native.process.argv ) . --- cocos/native-binding/impl.ts | 1 + cocos/native-binding/index.ts | 12 +++ native/CMakeLists.txt | 6 ++ native/cocos/application/ApplicationManager.h | 17 ++-- native/cocos/application/BaseApplication.h | 14 ++++ native/cocos/application/CocosApplication.cpp | 12 +++ native/cocos/application/CocosApplication.h | 15 +++- native/cocos/bindings/manual/jsb_global.cpp | 15 +++- .../platform/empty/modules/SystemWindow.cpp | 18 +++-- .../platform/empty/modules/SystemWindow.h | 6 +- .../empty/modules/SystemWindowManager.cpp | 69 ++++++++++++++++ .../empty/modules/SystemWindowManager.h | 52 +++++++++++++ native/cocos/platform/linux/LinuxPlatform.cpp | 1 + native/cocos/platform/mac/MacPlatform.mm | 11 ++- native/external-config.json | 2 +- templates/windows/main.cpp | 78 ++++++++++++++----- 16 files changed, 292 insertions(+), 37 deletions(-) create mode 100644 native/cocos/platform/empty/modules/SystemWindowManager.cpp create mode 100644 native/cocos/platform/empty/modules/SystemWindowManager.h diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 5a8b5bd4ed..644f4344bc 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -153,4 +153,5 @@ export const native = { EventAssetsManager: globalJsb.EventAssetsManager, Manifest: globalJsb.Manifest, saveImageData: globalJsb.saveImageData, + process: globalJsb.process, }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index fae1953c3e..dd14463b7c 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -1366,4 +1366,16 @@ export declare namespace native { }); */ export function saveImageData(data: Uint8Array, width: number, height: number, filePath: string): Promise; + + /** + * @en Current process information + * @zh 当前进程信息 + */ + export namespace process { + /** + * @en Get argument list passed to execution file + * @zh 获取当前传递给执行文件的参数列表 + */ + export const argv: Readonly; + } } diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index e4392a33a5..c1a1f5d328 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -620,6 +620,8 @@ if(WINDOWS) cocos/platform/empty/modules/Screen.h cocos/platform/empty/modules/SystemWindow.cpp cocos/platform/empty/modules/SystemWindow.h + cocos/platform/empty/modules/SystemWindowManager.cpp + cocos/platform/empty/modules/SystemWindowManager.h ) else() cocos_source_files( @@ -687,6 +689,8 @@ elseif(MACOSX) cocos/platform/empty/modules/Screen.h cocos/platform/empty/modules/SystemWindow.cpp cocos/platform/empty/modules/SystemWindow.h + cocos/platform/empty/modules/SystemWindowManager.cpp + cocos/platform/empty/modules/SystemWindowManager.h ) else() cocos_source_files( @@ -736,6 +740,8 @@ elseif(LINUX) cocos/platform/empty/modules/Screen.h cocos/platform/empty/modules/SystemWindow.cpp cocos/platform/empty/modules/SystemWindow.h + cocos/platform/empty/modules/SystemWindowManager.cpp + cocos/platform/empty/modules/SystemWindowManager.h ) else() cocos_source_files( diff --git a/native/cocos/application/ApplicationManager.h b/native/cocos/application/ApplicationManager.h index b74d92c87f..96d147c471 100644 --- a/native/cocos/application/ApplicationManager.h +++ b/native/cocos/application/ApplicationManager.h @@ -41,8 +41,9 @@ public: */ template std::enable_if_t::value, ApplicationPtr> - createApplication() { + createApplication(int argc, const char* argv[]) { ApplicationPtr app = std::make_shared(); + app->setArgumentsInternal(argc, argv); _apps.push_back(app); _currentApp = app; return app; @@ -81,13 +82,13 @@ private: /** * @brief Called at the user-defined main entry */ -#define CC_START_APPLICATION(className) \ - do { \ - auto app = CC_APPLICATION_MANAGER()->createApplication(); \ - if (app->init()) { \ - return -1; \ - } \ - return app->run(argc, argv); \ +#define CC_START_APPLICATION(className) \ + do { \ + auto app = CC_APPLICATION_MANAGER()->createApplication(argc, argv); \ + if (app->init()) { \ + return -1; \ + } \ + return app->run(argc, argv); \ } while (0) #define CC_REGISTER_APPLICATION(className) \ diff --git a/native/cocos/application/BaseApplication.h b/native/cocos/application/BaseApplication.h index 3b35b13013..9ed5eb32f7 100644 --- a/native/cocos/application/BaseApplication.h +++ b/native/cocos/application/BaseApplication.h @@ -62,6 +62,20 @@ public: * @brief Get engine. */ virtual BaseEngine::Ptr getEngine() const = 0; + + /** + * @brief Get arguments passed to execution file + */ + virtual const std::vector &getArguments() const = 0; + +protected: + /** + * @brief Set arguments passed to execution file + * @note setArgumentsInternal needs to be protected since it should only be used internally. + */ + virtual void setArgumentsInternal(int argc, const char *argv[]) = 0; + + friend class ApplicationManager; }; } // namespace cc diff --git a/native/cocos/application/CocosApplication.cpp b/native/cocos/application/CocosApplication.cpp index dbe3ff2f11..b542ca9b3e 100644 --- a/native/cocos/application/CocosApplication.cpp +++ b/native/cocos/application/CocosApplication.cpp @@ -128,6 +128,18 @@ BaseEngine::Ptr CocosApplication::getEngine() const { return _engine; } +const std::vector &CocosApplication::getArguments() const { + return _argv; +} + +void CocosApplication::setArgumentsInternal(int argc, const char *argv[]) { + _argv.clear(); + _argv.reserve(argc); + for (int i = 0; i < argc; ++i) { + _argv.emplace_back(argv[i]); + } +} + void CocosApplication::onStart() { // TODO(cc): Handling engine start events } diff --git a/native/cocos/application/CocosApplication.h b/native/cocos/application/CocosApplication.h index e69f1c6bc0..28dedd85d3 100644 --- a/native/cocos/application/CocosApplication.h +++ b/native/cocos/application/CocosApplication.h @@ -66,6 +66,19 @@ public: */ BaseEngine::Ptr getEngine() const override; + /** + * @brief Get arguments passed to execution file + */ + const std::vector &getArguments() const override; + +protected: + /** + * @brief Set arguments passed to execution file + * @note setArgumentsInternal needs to be protected since it should only be used internally. + */ + void setArgumentsInternal(int argc, const char *argv[]) override; + +public: /** * @brief Processing engine start events. */ @@ -134,6 +147,6 @@ private: BaseEngine::EngineStatusChange::EventID _engineEvents; - + std::vector _argv; }; } // namespace cc diff --git a/native/cocos/bindings/manual/jsb_global.cpp b/native/cocos/bindings/manual/jsb_global.cpp index 69be4ead7f..1cea444e58 100644 --- a/native/cocos/bindings/manual/jsb_global.cpp +++ b/native/cocos/bindings/manual/jsb_global.cpp @@ -660,7 +660,7 @@ static bool js_loadImage(se::State &s) { // NOLINT return false; } SE_BIND_FUNC(js_loadImage) -//pixels(RGBA), width, height, fullFilePath(*.png/*.jpg) +// pixels(RGBA), width, height, fullFilePath(*.png/*.jpg) static bool js_saveImageData(se::State &s) { // NOLINT const auto &args = s.args(); size_t argc = args.size(); @@ -1362,6 +1362,14 @@ static bool jsb_register_TextDecoder(se::Object *globalObj) { return true; } +static bool JSB_process_get_argv(se::State &s) // NOLINT(readability-identifier-naming) +{ + const auto &args = CC_CURRENT_APPLICATION()->getArguments(); + nativevalue_to_se(args, s.rval()); + return true; +} +SE_BIND_PROP_GET(JSB_process_get_argv) + bool jsb_register_global_variables(se::Object *global) { // NOLINT gThreadPool = LegacyThreadPool::newFixedThreadPool(3); @@ -1387,6 +1395,11 @@ bool jsb_register_global_variables(se::Object *global) { // NOLINT __jsbObj->defineFunction("saveByteCode", _SE(JSB_saveByteCode)); __jsbObj->defineFunction("createExternalArrayBuffer", _SE(jsb_createExternalArrayBuffer)); + // Create process object + se::HandleObject processObj{se::Object::createPlainObject()}; + processObj->defineProperty("argv", _SE(JSB_process_get_argv), nullptr); + __jsbObj->setProperty("process", se::Value(processObj)); + se::HandleObject zipUtils(se::Object::createPlainObject()); zipUtils->defineFunction("inflateMemory", _SE(JSB_zipUtils_inflateMemory)); zipUtils->defineFunction("inflateGZipFile", _SE(JSB_zipUtils_inflateGZipFile)); diff --git a/native/cocos/platform/empty/modules/SystemWindow.cpp b/native/cocos/platform/empty/modules/SystemWindow.cpp index 0fa9d9fda5..cd562d3c3a 100644 --- a/native/cocos/platform/empty/modules/SystemWindow.cpp +++ b/native/cocos/platform/empty/modules/SystemWindow.cpp @@ -28,7 +28,6 @@ #include "base/Log.h" #include "base/Macros.h" #include "engine/EngineEvents.h" -#include "platform/IEventDispatch.h" #include "platform/empty/EmptyPlatform.h" namespace { @@ -36,21 +35,28 @@ namespace { } // namespace namespace cc { -SystemWindow::SystemWindow(IEventDispatch* delegate) { +SystemWindow::SystemWindow(uint32_t windowId, void* externalHandle) +: _windowId(windowId) { + if (externalHandle) { + _windowHandle = reinterpret_cast(externalHandle); + } } -SystemWindow::~SystemWindow() { -} +SystemWindow::~SystemWindow() = default; uintptr_t SystemWindow::getWindowHandle() const { - return 0; + return _windowHandle; +} + +uint32_t SystemWindow::getWindowId() const { + return _windowId; } void SystemWindow::setCursorEnabled(bool value) { } void SystemWindow::copyTextToClipboard(const ccstd::string& text) { - //TODO + // TODO } int SystemWindow::init() { diff --git a/native/cocos/platform/empty/modules/SystemWindow.h b/native/cocos/platform/empty/modules/SystemWindow.h index 3f4bca3e42..ff387ac012 100644 --- a/native/cocos/platform/empty/modules/SystemWindow.h +++ b/native/cocos/platform/empty/modules/SystemWindow.h @@ -33,10 +33,11 @@ namespace cc { class CC_DLL SystemWindow : public ISystemWindow { public: - explicit SystemWindow(IEventDispatch* delegate); + explicit SystemWindow(uint32_t windowId, void* externalHandle); ~SystemWindow() override; uintptr_t getWindowHandle() const override; + uint32_t getWindowId() const override; Size getViewSize() const override; /* @@ -52,6 +53,9 @@ public: private: int _width{0}; int _height{0}; + + uint32_t _windowId{0}; + uintptr_t _windowHandle{0}; }; } // namespace cc diff --git a/native/cocos/platform/empty/modules/SystemWindowManager.cpp b/native/cocos/platform/empty/modules/SystemWindowManager.cpp new file mode 100644 index 0000000000..420ed8547f --- /dev/null +++ b/native/cocos/platform/empty/modules/SystemWindowManager.cpp @@ -0,0 +1,69 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "SystemWindowManager.h" +#include "platform/BasePlatform.h" +#include "platform/interfaces/modules/ISystemWindowManager.h" +#include "platform/empty/modules/SystemWindow.h" + +namespace cc { + +int SystemWindowManager::init() { + return 0; +} + +void SystemWindowManager::processEvent(bool* quit) { + +} + +void SystemWindowManager::swapWindows() { + +} + +ISystemWindow *SystemWindowManager::getWindow(uint32_t windowId) const { + if (windowId == 0) { + return nullptr; + } + + auto iter = _windows.find(windowId); + if (iter != _windows.end()) { + return iter->second.get(); + } + return nullptr; +} + +ISystemWindow *SystemWindowManager::createWindow(const cc::ISystemWindowInfo &info) { + ISystemWindow *window = BasePlatform::getPlatform()->createNativeWindow(_nextWindowId, info.externalHandle); + if (window) { + if (!info.externalHandle) { + window->createWindow(info.title.c_str(), info.x, info.y, info.width, info.height, info.flags); + } + _windows[_nextWindowId] = std::shared_ptr(window); + _nextWindowId++; + } + return window; +} + +} // namespace cc diff --git a/native/cocos/platform/empty/modules/SystemWindowManager.h b/native/cocos/platform/empty/modules/SystemWindowManager.h new file mode 100644 index 0000000000..02cac6ed74 --- /dev/null +++ b/native/cocos/platform/empty/modules/SystemWindowManager.h @@ -0,0 +1,52 @@ +/**************************************************************************** + Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "base/std/container/unordered_map.h" +#include "platform/interfaces/modules/ISystemWindowManager.h" + + +namespace cc { + +class ISystemWindow; + +class SystemWindowManager : public ISystemWindowManager { +public: + explicit SystemWindowManager() = default; + + int init() override; + void processEvent(bool* quit) override; + void swapWindows() override; + + ISystemWindow *createWindow(const ISystemWindowInfo &info) override; + ISystemWindow *getWindow(uint32_t windowId) const override; + const SystemWindowMap &getWindows() const override { return _windows; } + +private: + uint32_t _nextWindowId{1}; // start from 1, 0 means an invalid ID + SystemWindowMap _windows; +}; +} // namespace cc diff --git a/native/cocos/platform/linux/LinuxPlatform.cpp b/native/cocos/platform/linux/LinuxPlatform.cpp index a9984176ce..4781fb44ba 100644 --- a/native/cocos/platform/linux/LinuxPlatform.cpp +++ b/native/cocos/platform/linux/LinuxPlatform.cpp @@ -39,6 +39,7 @@ #if defined(CC_SERVER_MODE) #include "platform/empty/modules/Screen.h" #include "platform/empty/modules/SystemWindow.h" + #include "platform/empty/modules/SystemWindowManager.h" #else #include "modules/Screen.h" #include "modules/SystemWindow.h" diff --git a/native/cocos/platform/mac/MacPlatform.mm b/native/cocos/platform/mac/MacPlatform.mm index 0509d60e96..d4eec5177a 100644 --- a/native/cocos/platform/mac/MacPlatform.mm +++ b/native/cocos/platform/mac/MacPlatform.mm @@ -36,6 +36,7 @@ #if defined(CC_SERVER_MODE) #include "platform/empty/modules/Screen.h" #include "platform/empty/modules/SystemWindow.h" + #include "platform/empty/modules/SystemWindowManager.h" #else #include "modules/Screen.h" #include "modules/SystemWindow.h" @@ -119,7 +120,15 @@ int32_t MacPlatform::init() { int32_t MacPlatform::loop(void) { [_timer start]; - return cocos_main(0, nullptr); + NSArray *arguments = [[NSProcessInfo processInfo] arguments]; + int argc = static_cast(arguments.count); + std::vector argv; + argv.reserve(argc); + for (id arg in arguments) { + argv.emplace_back([arg UTF8String]); + } + + return cocos_main(argc, argv.data()); } int32_t MacPlatform::run(int argc, const char **argv) { diff --git a/native/external-config.json b/native/external-config.json index d08209b352..47421cc422 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "develop-3" + "checkout": "develop-7" } } \ No newline at end of file diff --git a/templates/windows/main.cpp b/templates/windows/main.cpp index 157fe7e625..08d1ea28d5 100644 --- a/templates/windows/main.cpp +++ b/templates/windows/main.cpp @@ -25,34 +25,76 @@ you. ****************************************************************************/ #include +#include #include "platform/BasePlatform.h" #if defined(CC_SERVER_MODE) -#include -int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) { - if (!AllocConsole()) { - // GetLastError() to get more info about the error. - MessageBox(NULL, L"The console window was not created", NULL, - MB_ICONEXCLAMATION); - return 0; - } - FILE *fConsole; - freopen_s(&fConsole, "CONOUT$", "w", stdout); - freopen_s(&fConsole, "CONOUT$", "w", stderr); - freopen_s(&fConsole, "CONIN$", "r", stdin); +static bool UTF16ToUTF8(LPCWSTR wideStr, const char** const outUtf8) { + if (outUtf8 == nullptr) { + return false; + } + int utf8BufferBytes = ::WideCharToMultiByte(CP_UTF8, 0, wideStr, -1, NULL, 0, NULL, NULL); + if (utf8BufferBytes < 0) { + *outUtf8 = nullptr; + return false; + } - START_PLATFORM(0, nullptr); + char* utf8Str = static_cast(malloc(utf8BufferBytes)); + int convResult = ::WideCharToMultiByte(CP_UTF8, 0, wideStr, -1, (LPSTR)utf8Str, utf8BufferBytes, NULL, NULL); + if (convResult != utf8BufferBytes) { + free(utf8Str); + *outUtf8 = nullptr; + return false; + } - fclose(fConsole); - if (!FreeConsole()) - MessageBox(NULL, L"Failed to free the console!", NULL, MB_ICONEXCLAMATION); + *outUtf8 = utf8Str; + return true; +} + +int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int sw) { + if (!AllocConsole()) { + // GetLastError() to get more info about the error. + MessageBox(NULL, L"The console window was not created", NULL, + MB_ICONEXCLAMATION); + return 0; + } + + FILE* fConsole; + freopen_s(&fConsole, "CONOUT$", "w", stdout); + freopen_s(&fConsole, "CONOUT$", "w", stderr); + freopen_s(&fConsole, "CONIN$", "r", stdin); + + int argc = 0; + + LPCWSTR szCmdLine = ::GetCommandLineW(); + LPWSTR* lpszArgv = ::CommandLineToArgvW(szCmdLine, &argc); + + std::vector argv; + argv.reserve(argc); + for (int i = 0; i < argc; ++i) { + const char* utf8Arg = nullptr; + if (UTF16ToUTF8(lpszArgv[i], &utf8Arg)) { + argv.emplace_back(utf8Arg); + } + } + + START_PLATFORM(static_cast(argv.size()), argv.data()); + + for (const char* arg : argv) { + free(const_cast(arg)); + } + + fclose(fConsole); + if (!FreeConsole()) { + MessageBox(NULL, L"Failed to free the console!", NULL, MB_ICONEXCLAMATION); + } } #else #include "sdl2/SDL_main.h" -int SDL_main(int argc, char **argv) { - START_PLATFORM(argc, (const char **)argv); +int SDL_main(int argc, char** argv) { + START_PLATFORM(argc, (const char**)argv); } #endif \ No newline at end of file