no message

This commit is contained in:
gem
2025-02-18 15:21:31 +08:00
commit 2d133e56d7
1980 changed files with 465595 additions and 0 deletions

View File

@@ -0,0 +1,281 @@
/****************************************************************************
Copyright (c) 2021-2023 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 "platform/openharmony/FileUtils-OpenHarmony.h"
#include <hilog/log.h>
#include <sys/stat.h>
#include <cstdio>
#include <regex>
#include <string>
#include <sys/syscall.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include "base/memory/Memory.h"
#include "base/Log.h"
namespace cc {
NativeResourceManager* FileUtilsOpenHarmony::_nativeResourceManager = nullptr;
FileUtils *createFileUtils() {
return ccnew FileUtilsOpenHarmony();
}
FileUtilsOpenHarmony::FileUtilsOpenHarmony() {
init();
}
std::string FileUtilsOpenHarmony::_ohWritablePath;
bool FileUtilsOpenHarmony::initResourceManager(napi_env env, napi_value param) {
_nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, param);
return true;
}
FileUtils::Status FileUtilsOpenHarmony::getRawFileDescriptor(const std::string &filename,RawFileDescriptor& descriptor) {
if (filename.empty()) {
return FileUtils::Status::NOT_EXISTS;
}
std::string fullPath = fullPathForFilename(filename);
if (fullPath.empty()) {
return FileUtils::Status::NOT_EXISTS;
}
if (nullptr == _nativeResourceManager) {
CC_LOG_ERROR("nativeResourceManager is nullptr");
return FileUtils::Status::NOT_INITIALIZED;
}
RawFile *rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str());
if (nullptr == rawFile) {
return FileUtils::Status::OPEN_FAILED;
}
bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
if (!result) {
OH_ResourceManager_CloseRawFile(rawFile);
return FileUtils::Status::OPEN_FAILED;
}
OH_ResourceManager_CloseRawFile(rawFile);
return FileUtils::Status::OK;
}
FileUtils::Status FileUtilsOpenHarmony::getContents(const std::string &filename, ResizableBuffer *buffer) {
if (filename.empty()) {
return FileUtils::Status::NOT_EXISTS;
}
std::string fullPath = fullPathForFilename(filename);
if (fullPath.empty()) {
return FileUtils::Status::NOT_EXISTS;
}
if (fullPath[0] == '/') {
return FileUtils::getContents(fullPath, buffer);
}
if (nullptr == _nativeResourceManager) {
CC_LOG_ERROR("nativeResourceManager is nullptr");
return FileUtils::Status::NOT_INITIALIZED;
}
RawFile *rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str());
if (nullptr == rawFile) {
return FileUtils::Status::OPEN_FAILED;
}
auto size = OH_ResourceManager_GetRawFileSize(rawFile);
buffer->resize(size);
assert(buffer->buffer());
int readsize = OH_ResourceManager_ReadRawFile(rawFile, buffer->buffer(), size);
// TODO(unknown): read error
if (readsize < size) {
if (readsize >= 0) {
buffer->resize(readsize);
}
OH_ResourceManager_CloseRawFile(rawFile);
return FileUtils::Status::READ_FAILED;
}
OH_ResourceManager_CloseRawFile(rawFile);
return FileUtils::Status::OK;
}
FileUtilsOpenHarmony::~FileUtilsOpenHarmony() {
if(_nativeResourceManager)
OH_ResourceManager_ReleaseNativeResourceManager(_nativeResourceManager);
}
bool FileUtilsOpenHarmony::init() {
_defaultResRootPath = "";
return FileUtils::init();
}
bool FileUtilsOpenHarmony::isAbsolutePath(const std::string &strPath) const {
return !strPath.empty() && (strPath[0] == '/');
}
std::string FileUtilsOpenHarmony::getSuitableFOpen(const std::string &filenameUtf8) const {
return filenameUtf8;
}
long FileUtilsOpenHarmony::getFileSize(const std::string &filepath) {
if (filepath.empty()) {
return 0;
}
auto *fs = FileUtils::getInstance();
std::string fullPath = fs->fullPathForFilename(filepath);
if (fullPath.empty()) {
return 0;
}
if (nullptr == _nativeResourceManager) {
CC_LOG_ERROR("nativeResourceManager is nullptr");
return 0;
}
long filesize = 0;
RawFile* rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, fullPath.c_str());
if(rawFile) {
filesize = OH_ResourceManager_GetRawFileSize(rawFile);
OH_ResourceManager_CloseRawFile(rawFile);
}
return filesize;
}
std::string FileUtilsOpenHarmony::getWritablePath() const {
return _ohWritablePath;
}
bool FileUtilsOpenHarmony::isFileExistInternal(const std::string &strFilePath) const {
if (strFilePath.empty()) {
return false;
}
std::string strPath = strFilePath;
if (!isAbsolutePath(strPath)) { // Not absolute path, add the default root path at the beginning.
strPath.insert(0, _defaultResRootPath);
}
if (nullptr == _nativeResourceManager) {
CC_LOG_ERROR("nativeResourceManager is nullptr");
return false;
}
RawFile* rawFile = OH_ResourceManager_OpenRawFile(_nativeResourceManager, strPath.c_str());
if(rawFile) {
OH_ResourceManager_CloseRawFile(rawFile);
return true;
}
return false;
}
bool FileUtilsOpenHarmony::isDirectoryExistInternal(const std::string &dirPath) const {
if (dirPath.empty()) return false;
std::string dirPathMf = dirPath[dirPath.length() - 1] == '/' ? dirPath.substr(0, dirPath.length() - 1) : dirPath;
if (dirPathMf[0] == '/') {
struct stat st;
return stat(dirPathMf.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
if (dirPathMf.find(_defaultResRootPath) == 0) {
dirPathMf = dirPathMf.substr(_defaultResRootPath.length(), dirPathMf.length());
}
if (nullptr == _nativeResourceManager) {
CC_LOG_ERROR("nativeResourceManager is nullptr");
return false;
}
RawDir* rawDir = OH_ResourceManager_OpenRawDir(_nativeResourceManager, dirPathMf.c_str());
if(rawDir) {
OH_ResourceManager_CloseRawDir(rawDir);
return true;
}
return false;
}
bool FileUtilsOpenHarmony::renameFile(const std::string &oldfullpath, const std::string &newfullpath) {
if (access(oldfullpath.c_str(), F_OK) != 0) {
return false;
}
if (rename(oldfullpath.c_str(), newfullpath.c_str()) != 0) {
if (access(newfullpath.c_str(), F_OK) == 0) {
remove(newfullpath.c_str());
}
return false;
}
return true;
}
bool FileUtilsOpenHarmony::removeFile(const std::string &filepath) {
return remove(filepath.c_str()) == 0;
}
bool FileUtilsOpenHarmony::removeDirectory(const std::string &dirPath) {
DIR *directory = opendir(dirPath.c_str());
if (!directory) {
return false;
}
struct dirent *dir{nullptr};
struct stat st;
while ((dir = readdir(directory)) != NULL) {
if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) {
continue;
}
std::string subPath = dirPath + '/' + dir->d_name;
if (lstat(subPath.c_str(), &st) == -1) {
continue;
}
if (S_ISDIR(st.st_mode)) {
if (!removeDirectory(subPath)) {
closedir(directory);
return false;
}
rmdir(subPath.c_str());
} else if (S_ISREG(st.st_mode)) {
unlink(subPath.c_str());
} else {
continue;
}
}
if (rmdir(dirPath.c_str()) == -1) {
closedir(directory);
return false;
}
closedir(directory);
return true;
}
} // namespace cc

View File

@@ -0,0 +1,71 @@
/****************************************************************************
Copyright (c) 2021-2023 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
//clang-format off
#include <cstdint>
//clang-format on
#include <rawfile/raw_dir.h>
#include <rawfile/raw_file.h>
#include <rawfile/raw_file_manager.h>
#include <napi/native_api.h>
#include "base/Macros.h"
#include "platform/FileUtils.h"
namespace cc {
class CC_DLL FileUtilsOpenHarmony : public FileUtils {
public:
FileUtilsOpenHarmony();
~FileUtilsOpenHarmony() override;
static bool initResourceManager(napi_env env, napi_value info);
bool init() override;
bool isAbsolutePath(const std::string &strPath) const override;
std::string getWritablePath() const override;
long getFileSize(const std::string &filepath) override;
std::string getSuitableFOpen(const std::string &filenameUtf8) const override;
FileUtils::Status getContents(const std::string &filename, ResizableBuffer *buffer) override;
FileUtils::Status getRawFileDescriptor(const std::string &filename,RawFileDescriptor& descriptor);
bool renameFile(const std::string &oldfullpath, const std::string &newfullpath) override;
bool removeFile(const std::string &filepath) override;
bool removeDirectory(const std::string &dirPath) override;
static std::string _ohWritablePath;
private:
bool isFileExistInternal(const std::string &strFilePath) const override;
bool isDirectoryExistInternal(const std::string &dirPath) const override;
static NativeResourceManager* _nativeResourceManager;
};
} // namespace cc

View File

@@ -0,0 +1,310 @@
/****************************************************************************
Copyright (c) 2021-2023 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 "platform/openharmony/OpenHarmonyPlatform.h"
#include "base/Macros.h"
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <napi/native_api.h>
#include "application/ApplicationManager.h"
#include "application/CocosApplication.h"
#include "platform/UniversalPlatform.h"
#include "platform/openharmony/modules/SystemWindow.h"
#include "platform/openharmony/modules/SystemWindowManager.h"
#include "platform/empty/modules/Accelerometer.h"
#include "platform/empty/modules/Battery.h"
#include "platform/empty/modules/Network.h"
#include "platform/empty/modules/Screen.h"
#include "platform/empty/modules/Vibrator.h"
#include "platform/openharmony/modules/System.h"
#include <chrono>
#include <sstream>
namespace {
void sendMsgToWorker(const cc::MessageType& type, void* data, void* window) {
cc::OpenHarmonyPlatform* platform = dynamic_cast<cc::OpenHarmonyPlatform*>(cc::BasePlatform::getPlatform());
CC_ASSERT(platform != nullptr);
cc::WorkerMessageData msg{type, static_cast<void*>(data), window};
platform->enqueue(msg);
}
void onSurfaceCreatedCB(OH_NativeXComponent* component, void* window) {
// It is possible that when the message is sent, the worker thread has not yet started.
//sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_CREATED, component, window);
cc::ISystemWindowInfo info;
info.title = "";
info.x = 0;
info.y = 0;
info.width = 0;
info.height = 0;
info.flags = 0;
info.externalHandle = window;
cc::ISystemWindowManager* windowMgr =
cc::OpenHarmonyPlatform::getInstance()->getInterface<cc::ISystemWindowManager>();
windowMgr->createWindow(info);
}
void dispatchTouchEventCB(OH_NativeXComponent* component, void* window) {
OH_NativeXComponent_TouchEvent touchEvent;
int32_t ret = OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
// TODO(qgh):Is it possible to find an efficient way to do this, I thought about using a cache queue but it requires locking.
cc::TouchEvent* ev = new cc::TouchEvent;
cc::SystemWindowManager* windowMgr =
cc::OpenHarmonyPlatform::getInstance()->getInterface<cc::SystemWindowManager>();
CC_ASSERT_NOT_NULL(windowMgr);
cc::ISystemWindow* systemWindow = windowMgr->getWindowFromHandle(window);
CC_ASSERT_NOT_NULL(systemWindow);
ev->windowId = systemWindow->getWindowId();
if (touchEvent.type == OH_NATIVEXCOMPONENT_DOWN) {
ev->type = cc::TouchEvent::Type::BEGAN;
} else if (touchEvent.type == OH_NATIVEXCOMPONENT_MOVE) {
ev->type = cc::TouchEvent::Type::MOVED;
} else if (touchEvent.type == OH_NATIVEXCOMPONENT_UP) {
ev->type = cc::TouchEvent::Type::ENDED;
} else if (touchEvent.type == OH_NATIVEXCOMPONENT_CANCEL) {
ev->type = cc::TouchEvent::Type::CANCELLED;
}
for (int i = 0; i < touchEvent.numPoints; ++i) {
int32_t id = touchEvent.touchPoints[i].id;
if (touchEvent.id == id) {
ev->touches.emplace_back(touchEvent.touchPoints[i].x, touchEvent.touchPoints[i].y, id);
}
}
sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_TOUCH_EVENT, reinterpret_cast<void*>(ev), window);
}
void onSurfaceChangedCB(OH_NativeXComponent* component, void* window) {
sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_CHANGED, reinterpret_cast<void*>(component), window);
}
void onSurfaceDestroyedCB(OH_NativeXComponent* component, void* window) {
sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_DESTROY, reinterpret_cast<void*>(component), window);
}
} // namespace
namespace cc {
OpenHarmonyPlatform::OpenHarmonyPlatform() {
registerInterface(std::make_shared<System>());
registerInterface(std::make_shared<Screen>());
registerInterface(std::make_shared<Vibrator>());
registerInterface(std::make_shared<Network>());
registerInterface(std::make_shared<Battery>());
registerInterface(std::make_shared<Accelerometer>());
registerInterface(std::make_shared<SystemWindowManager>());
_callback.OnSurfaceCreated = onSurfaceCreatedCB;
_callback.OnSurfaceChanged = onSurfaceChangedCB;
_callback.OnSurfaceDestroyed = onSurfaceDestroyedCB;
_callback.DispatchTouchEvent = dispatchTouchEventCB;
}
int32_t OpenHarmonyPlatform::init() {
return 0;
}
OpenHarmonyPlatform* OpenHarmonyPlatform::getInstance() {
return dynamic_cast<OpenHarmonyPlatform*>(BasePlatform::getPlatform());
}
int32_t OpenHarmonyPlatform::run(int argc, const char** argv) {
UniversalPlatform::run(argc, argv);
/*
if (_workerLoop) {
// Todo: Starting the timer in this way is inaccurate and will be fixed later.
uv_timer_init(_workerLoop, &_timerHandle);
// 1s = 1000ms = 60fps;
// 1000ms / 60fps = 16 ms/fps
uv_timer_start(&_timerHandle, &OpenHarmonyPlatform::timerCb, 16, true);
}
*/
return 0;
}
void OpenHarmonyPlatform::setNativeXComponent(OH_NativeXComponent* component) {
_component = component;
OH_NativeXComponent_RegisterCallback(_component, &_callback);
}
void OpenHarmonyPlatform::enqueue(const WorkerMessageData& msg) {
_messageQueue.enqueue(msg);
triggerMessageSignal();
}
void OpenHarmonyPlatform::triggerMessageSignal() {
if (_workerLoop != nullptr) {
// It is possible that when the message is sent, the worker thread has not yet started.
uv_async_send(&_messageSignal);
}
}
bool OpenHarmonyPlatform::dequeue(WorkerMessageData* msg) {
return _messageQueue.dequeue(msg);
}
// static
void OpenHarmonyPlatform::onMessageCallback(const uv_async_t* /* req */) {
void* window = nullptr;
WorkerMessageData msgData;
OpenHarmonyPlatform* platform = OpenHarmonyPlatform::getInstance();
while (true) {
//loop until all msg dispatch
if (!platform->dequeue(reinterpret_cast<WorkerMessageData*>(&msgData))) {
// Queue has no data
break;
}
if ((msgData.type >= MessageType::WM_XCOMPONENT_SURFACE_CREATED) && (msgData.type <= MessageType::WM_XCOMPONENT_SURFACE_DESTROY)) {
if (msgData.type == MessageType::WM_XCOMPONENT_TOUCH_EVENT) {
TouchEvent* ev = reinterpret_cast<TouchEvent*>(msgData.data);
CC_ASSERT(ev != nullptr);
events::Touch::broadcast(*ev);
delete ev;
ev = nullptr;
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CREATED) {
CC_LOG_INFO("onMessageCallback WM_XCOMPONENT_SURFACE_CREATED ...");
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
CC_ASSERT(nativexcomponet != nullptr);
platform->onSurfaceCreated(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CHANGED) {
CC_LOG_INFO("onMessageCallback WM_XCOMPONENT_SURFACE_CHANGED ...");
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
CC_ASSERT(nativexcomponet != nullptr);
platform->onSurfaceChanged(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_DESTROY) {
CC_LOG_INFO("onMessageCallback WM_XCOMPONENT_SURFACE_DESTROY ...");
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
CC_ASSERT(nativexcomponet != nullptr);
platform->onSurfaceDestroyed(nativexcomponet, msgData.window);
} else {
CC_ASSERT(false);
}
continue;
}
if (msgData.type == MessageType::WM_APP_SHOW) {
platform->onShowNative();
} else if (msgData.type == MessageType::WM_APP_HIDE) {
platform->onHideNative();
} else if (msgData.type == MessageType::WM_APP_DESTROY) {
platform->onDestroyNative();
}
if (msgData.type == MessageType::WM_VSYNC) {
platform->runTask();
}
// CC_ASSERT(false);
//}
}
}
void OpenHarmonyPlatform::onCreateNative(napi_env env, uv_loop_t* loop) {
}
void OpenHarmonyPlatform::onShowNative() {
WindowEvent ev;
ev.type = WindowEvent::Type::SHOW;
ev.windowId = cc::ISystemWindow::mainWindowId;
events::WindowEvent::broadcast(ev);
}
void OpenHarmonyPlatform::onHideNative() {
WindowEvent ev;
ev.type = WindowEvent::Type::HIDDEN;
ev.windowId = cc::ISystemWindow::mainWindowId;
events::WindowEvent::broadcast(ev);
}
void OpenHarmonyPlatform::onDestroyNative() {
onDestroy();
}
void OpenHarmonyPlatform::timerCb(uv_timer_t* handle) {
OpenHarmonyPlatform::getInstance()->runTask();
}
void OpenHarmonyPlatform::workerInit(uv_loop_t* loop) {
_workerLoop = loop;
if (_workerLoop) {
uv_async_init(_workerLoop, &_messageSignal, reinterpret_cast<uv_async_cb>(OpenHarmonyPlatform::onMessageCallback));
}
}
void OpenHarmonyPlatform::requestVSync() {
//CC_LOG_ERROR("OpenHarmonyPlatform::requestVSync1");
//OH_NativeVSync_RequestFrame(OpenHarmonyPlatform::getInstance()->_nativeVSync, OnVSync, nullptr);
if (_workerLoop) {
// // Todo: Starting the timer in this way is inaccurate and will be fixed later.
uv_timer_init(_workerLoop, &_timerHandle);
// The tick function needs to be called as quickly as possible because it is controlling the frame rate inside the engine.
uv_timer_start(&_timerHandle, &OpenHarmonyPlatform::timerCb, 0, 1);
}
//CC_LOG_ERROR("OpenHarmonyPlatform::requestVSync2");
}
int32_t OpenHarmonyPlatform::loop() {
return 0;
}
void OpenHarmonyPlatform::onSurfaceCreated(OH_NativeXComponent* component, void* window) {
}
void OpenHarmonyPlatform::onSurfaceChanged(OH_NativeXComponent* component, void* window) {
uint64_t width = 0;
uint64_t height = 0;
int32_t ret = OH_NativeXComponent_GetXComponentSize(_component, window, &width, &height);
CC_ASSERT(ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS);
WindowEvent ev;
ev.windowId = cc::ISystemWindow::mainWindowId;
ev.type = WindowEvent::Type::SIZE_CHANGED;
ev.width = width;
ev.height = height;
events::WindowEvent::broadcast(ev);
}
void OpenHarmonyPlatform::onSurfaceDestroyed(OH_NativeXComponent* component, void* window) {
cc::SystemWindowManager* windowMgr = this->getInterface<cc::SystemWindowManager>();
CC_ASSERT_NOT_NULL(windowMgr);
windowMgr->removeWindow(window);
}
ISystemWindow* OpenHarmonyPlatform::createNativeWindow(uint32_t windowId, void* externalHandle) {
SystemWindow* window = ccnew SystemWindow(windowId, externalHandle);
uint64_t width = 0;
uint64_t height = 0;
CC_ASSERT_NOT_NULL(_component);
int32_t ret = OH_NativeXComponent_GetXComponentSize(_component, externalHandle, &width, &height);
CC_ASSERT(ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS);
window->setViewSize(width, height);
return window;
}
}; // namespace cc

View File

@@ -0,0 +1,81 @@
/****************************************************************************
Copyright (c) 2021-2023 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 "platform/UniversalPlatform.h"
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <uv.h>
#include <string>
#include <unordered_map>
#include <napi/native_api.h>
#include "platform/openharmony/WorkerMessageQueue.h"
namespace cc {
class OpenHarmonyPlatform : public UniversalPlatform {
public:
OpenHarmonyPlatform();
int32_t init() override;
static OpenHarmonyPlatform* getInstance();
void onCreateNative(napi_env env, uv_loop_t* loop);
void onShowNative();
void onHideNative();
void onDestroyNative();
void workerInit(uv_loop_t* loop);
void setNativeXComponent(OH_NativeXComponent* component);
int32_t run(int argc, const char** argv) override;
int32_t loop() override;
void requestVSync();
void enqueue(const WorkerMessageData& data);
bool dequeue(WorkerMessageData* data);
void triggerMessageSignal();
ISystemWindow *createNativeWindow(uint32_t windowId, void *externalHandle) override;
public:
// Callback, called by ACE XComponent
void onSurfaceCreated(OH_NativeXComponent* component, void* window);
void onSurfaceChanged(OH_NativeXComponent* component, void* window);
void onSurfaceDestroyed(OH_NativeXComponent* component, void* window);
static void onMessageCallback(const uv_async_t* req);
static void timerCb(uv_timer_t* handle);
OH_NativeXComponent* _component{nullptr};
OH_NativeXComponent_Callback _callback;
uv_timer_t _timerHandle;
uv_loop_t* _workerLoop{nullptr};
uv_async_t _messageSignal{};
WorkerMessageQueue _messageQueue;
};
} // namespace cc

View File

@@ -0,0 +1,49 @@
/****************************************************************************
Copyright (c) 2021-2023 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 "platform/openharmony/WorkerMessageQueue.h"
namespace cc {
void WorkerMessageQueue::enqueue(const WorkerMessageData& data) {
std::lock_guard<std::mutex> lck(_mutex);
_queue.push(data);
}
bool WorkerMessageQueue::dequeue(WorkerMessageData *data) {
std::lock_guard<std::mutex> lck(_mutex);
if (empty()) {
return false;
}
*data = _queue.front();
_queue.pop();
return true;
}
bool WorkerMessageQueue::empty() const {
return _queue.empty();
}
} // namespace cc

View File

@@ -0,0 +1,67 @@
/****************************************************************************
Copyright (c) 2021-2023 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 <queue>
#include <thread>
#include <mutex>
namespace cc {
enum class MessageType {
WM_XCOMPONENT_SURFACE_CREATED = 0,
WM_XCOMPONENT_TOUCH_EVENT,
WM_XCOMPONENT_SURFACE_CHANGED,
WM_XCOMPONENT_SURFACE_DESTROY,
WM_APP_SHOW,
WM_APP_HIDE,
WM_APP_DESTROY,
WM_VSYNC,
};
struct WorkerMessageData {
MessageType type;
void* data;
void* window;
};
class WorkerMessageQueue final {
public:
void enqueue(const WorkerMessageData& data);
bool dequeue(WorkerMessageData *data);
bool empty() const;
size_t size() const {
return _queue.size();
}
private:
std::mutex _mutex;
std::queue<WorkerMessageData> _queue;
};
} // namespace cc

View File

@@ -0,0 +1,65 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/openharmony/modules/Accelerometer.h"
#include "platform/openharmony/napi/NapiHelper.h"
namespace cc {
void Accelerometer::setAccelerometerEnabled(bool isEnabled) {
//setAccelerometerEnabledJNI(isEnabled);
}
void Accelerometer::setAccelerometerInterval(float interval) {
//setAccelerometerIntervalJNI(interval);
}
const Accelerometer::MotionValue &Accelerometer::getDeviceMotionValue() {
static MotionValue motionValue;
Napi::Value ret = NapiHelper::napiCallFunction("getDeviceMotionValue");
if (!ret.IsArray()) {
return motionValue;
}
auto v = ret.As<Napi::Array>();
if (v.Length() == 9) {
motionValue.accelerationIncludingGravityX = static_cast<Napi::Value>(v[(uint32_t)0]).As<Napi::Number>().FloatValue();
motionValue.accelerationIncludingGravityY = static_cast<Napi::Value>(v[(uint32_t)1]).As<Napi::Number>().FloatValue();
motionValue.accelerationIncludingGravityZ = static_cast<Napi::Value>(v[(uint32_t)2]).As<Napi::Number>().FloatValue();
motionValue.accelerationX = static_cast<Napi::Value>(v[(uint32_t)3]).As<Napi::Number>().FloatValue();
motionValue.accelerationY = static_cast<Napi::Value>(v[(uint32_t)4]).As<Napi::Number>().FloatValue();
motionValue.accelerationZ = static_cast<Napi::Value>(v[(uint32_t)5]).As<Napi::Number>().FloatValue();
motionValue.rotationRateAlpha = static_cast<Napi::Value>(v[(uint32_t)6]).As<Napi::Number>().FloatValue();
motionValue.rotationRateBeta = static_cast<Napi::Value>(v[(uint32_t)7]).As<Napi::Number>().FloatValue();
motionValue.rotationRateGamma = static_cast<Napi::Value>(v[(uint32_t)8]).As<Napi::Number>().FloatValue();
} else {
memset(&motionValue, 0, sizeof(motionValue));
}
return motionValue;
}
} // namespace cc

View File

@@ -0,0 +1,50 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/interfaces/modules/IAccelerometer.h"
namespace cc {
class Accelerometer : public IAccelerometer {
public:
/**
* To enable or disable accelerometer.
*/
void setAccelerometerEnabled(bool isEnabled) override;
/**
* Sets the interval of accelerometer.
*/
void setAccelerometerInterval(float interval) override;
/**
* Gets the motion value of current device.
*/
const MotionValue &getDeviceMotionValue() override;
};
} // namespace cc

View File

@@ -0,0 +1,39 @@
/****************************************************************************
Copyright (c) 2021-2023 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 "platform/openharmony/modules/Battery.h"
#include "platform/openharmony/napi/NapiHelper.h"
namespace cc {
float Battery::getBatteryLevel() const {
auto value = NapiHelper::napiCallFunction("getBatteryLevel");
if (value.IsNumber()) {
return value.As<Napi::Number>().FloatValue();
}
return 0.F;
}
} // namespace cc

View File

@@ -0,0 +1,37 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/interfaces/modules/IBattery.h"
namespace cc {
class Battery : public IBattery {
public:
float getBatteryLevel() const override;
};
} // namespace cc

View File

@@ -0,0 +1,338 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/openharmony/modules/CanvasRenderingContext2DDelegate.h"
#include "platform/openharmony/OpenHarmonyPlatform.h"
#include <native_drawing/drawing_text_typography.h>
#include <native_drawing/drawing_canvas.h>
#include <native_drawing/drawing_font_collection.h>
#include <native_drawing/drawing_types.h>
#include <native_drawing/drawing_path.h>
#include <native_drawing/drawing_brush.h>
namespace cc {
class CanvasRenderingContext2DDelegate::ScopedTypography {
public:
ScopedTypography(OH_Drawing_Typography* typography) :_typegraphy(typography) {}
~ScopedTypography() {
if(_typegraphy) {
OH_Drawing_DestroyTypography(_typegraphy);
}
}
OH_Drawing_Typography* get() {
return _typegraphy;
}
private:
OH_Drawing_Typography* _typegraphy{nullptr};
};
CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() {
_typographyStyle = OH_Drawing_CreateTypographyStyle();
OH_Drawing_SetTypographyTextDirection(_typographyStyle, TEXT_DIRECTION_LTR);
OH_Drawing_SetTypographyTextAlign(_typographyStyle, TEXT_ALIGN_LEFT);
_fontCollection = OH_Drawing_CreateFontCollection();
_typographyCreate = OH_Drawing_CreateTypographyHandler(_typographyStyle, _fontCollection);
_textStyle = OH_Drawing_CreateTextStyle();
}
CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() {
if(_typographyStyle) {
OH_Drawing_DestroyTypographyStyle(_typographyStyle);
_typographyStyle = nullptr;
}
if(_fontCollection) {
OH_Drawing_DestroyFontCollection(_fontCollection);
}
if(_typographyCreate) {
OH_Drawing_DestroyTypographyHandler(_typographyCreate);
_typographyCreate = nullptr;
}
if(_textStyle) {
OH_Drawing_DestroyTextStyle(_textStyle);
_textStyle = nullptr;
}
if(_canvas) {
OH_Drawing_CanvasDestroy(_canvas);
_canvas = nullptr;
}
if(_bitmap) {
OH_Drawing_BitmapDestroy(_bitmap);
_bitmap = nullptr;
}
}
void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) {
_bufferWidth = w;
_bufferHeight = h;
if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) {
return;
}
if(_canvas) {
OH_Drawing_CanvasDestroy(_canvas);
_canvas = nullptr;
}
if(_bitmap) {
OH_Drawing_BitmapDestroy(_bitmap);
_bitmap = nullptr;
}
_bufferSize = static_cast<int>(_bufferWidth * _bufferHeight * 4);
auto *data = static_cast<uint8_t *>(malloc(sizeof(uint8_t) * _bufferSize));
memset(data, 0x00, _bufferSize);
_imageData.fastSet(data, _bufferSize);
_bitmap = OH_Drawing_BitmapCreate();
OH_Drawing_BitmapBuild(_bitmap, _bufferWidth, _bufferHeight, &_format);
_canvas = OH_Drawing_CanvasCreate();
OH_Drawing_CanvasBind(_canvas, _bitmap);
}
void CanvasRenderingContext2DDelegate::beginPath() {
}
void CanvasRenderingContext2DDelegate::closePath() {
}
void CanvasRenderingContext2DDelegate::moveTo(float x, float y) {
//MoveToEx(_DC, static_cast<int>(x), static_cast<int>(-(y - _bufferHeight - _fontSize)), nullptr);
_x = x;
_y = y;
}
void CanvasRenderingContext2DDelegate::lineTo(float x, float y) {
}
void CanvasRenderingContext2DDelegate::stroke() {
}
void CanvasRenderingContext2DDelegate::saveContext() {
}
void CanvasRenderingContext2DDelegate::restoreContext() {
}
void CanvasRenderingContext2DDelegate::clearRect(float x, float y, float w, float h) {
if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) {
return;
}
if (_imageData.isNull()) {
return;
}
recreateBuffer(w, h);
}
void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float h) {
if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) {
return;
}
uint8_t r = static_cast<uint8_t>(_fillStyle[0]);
uint8_t g = static_cast<uint8_t>(_fillStyle[1]);
uint8_t b = static_cast<uint8_t>(_fillStyle[2]);
uint8_t a = static_cast<uint8_t>(_fillStyle[3]);
OH_Drawing_Path* path = OH_Drawing_PathCreate();
OH_Drawing_PathMoveTo(path, x, y);
OH_Drawing_PathLineTo(path, x + w, y);
OH_Drawing_PathLineTo(path, x + w, y + h);
OH_Drawing_PathLineTo(path, x, y + h);
OH_Drawing_PathLineTo(path, x, y);
OH_Drawing_PathClose(path);
OH_Drawing_Brush* brush = OH_Drawing_BrushCreate();
OH_Drawing_BrushSetColor(brush, OH_Drawing_ColorSetArgb(a, r, g, b));
OH_Drawing_CanvasAttachBrush(_canvas, brush);
OH_Drawing_CanvasDrawPath(_canvas, path);
}
void CanvasRenderingContext2DDelegate::fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) {
if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) {
return;
}
Size textSize = {0, 0};
Point offsetPoint = convertDrawPoint(Point{x, y}, text);
drawText(text, (int)offsetPoint[0], (int)offsetPoint[1]);
}
void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const {
}
CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const ccstd::string &text) {
auto typography = createTypography(text);
return ccstd::array<float, 2>{static_cast<float>(OH_Drawing_TypographyGetMaxIntrinsicWidth(typography->get())),
static_cast<float>(OH_Drawing_TypographyGetHeight(typography->get()))};
}
void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName,
float fontSize,
bool bold,
bool italic,
bool oblique,
bool /* smallCaps */) {
_fontName = fontName;
_fontSize = static_cast<int>(fontSize);
ccstd::string fontPath;
if (!_fontName.empty()) {
const char* fontFamilies[1];
fontFamilies[0] = fontName.c_str();
OH_Drawing_SetTextStyleFontFamilies(_textStyle, 1, fontFamilies);
OH_Drawing_SetTextStyleLocale(_textStyle, "en");
}
if (_fontSize)
OH_Drawing_SetTextStyleFontSize(_textStyle, _fontSize);
if (bold)
OH_Drawing_SetTextStyleFontWeight(_textStyle, FONT_WEIGHT_700);
else
OH_Drawing_SetTextStyleFontWeight(_textStyle, FONT_WEIGHT_400);
if(italic)
OH_Drawing_SetTextStyleFontStyle(_textStyle, FONT_STYLE_ITALIC);
else
OH_Drawing_SetTextStyleFontStyle(_textStyle, FONT_STYLE_NORMAL);
}
void CanvasRenderingContext2DDelegate::setTextAlign(TextAlign align) {
_textAlign = align;
}
void CanvasRenderingContext2DDelegate::setTextBaseline(TextBaseline baseline) {
_textBaseLine = baseline;
}
void CanvasRenderingContext2DDelegate::setFillStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
_fillStyle = {static_cast<float>(r), static_cast<float>(g), static_cast<float>(b), static_cast<float>(a)};
OH_Drawing_SetTextStyleColor(_textStyle, OH_Drawing_ColorSetArgb(a, r, g, b));
}
void CanvasRenderingContext2DDelegate::setStrokeStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
_strokeStyle = {static_cast<float>(r), static_cast<float>(g), static_cast<float>(b), static_cast<float>(a)};
}
void CanvasRenderingContext2DDelegate::setLineWidth(float lineWidth) {
_lineWidth = lineWidth;
}
const cc::Data &CanvasRenderingContext2DDelegate::getDataRef() const {
void* bitmapAddr = OH_Drawing_BitmapGetPixels(_bitmap);
memcpy(_imageData.getBytes(), bitmapAddr, _bufferSize);
return _imageData;
}
void CanvasRenderingContext2DDelegate::removeCustomFont() {
}
// x, y offset value
int CanvasRenderingContext2DDelegate::drawText(const ccstd::string &text, int x, int y) {
auto typography = createTypography(text);
OH_Drawing_TypographyPaint(typography->get(), _canvas, x, y);
return 0;
}
CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::sizeWithText(const wchar_t *pszText, int nLen) {
return ccstd::array<float, 2>{0.0F, 0.0F};
}
void CanvasRenderingContext2DDelegate::prepareBitmap(int nWidth, int nHeight) {
}
void CanvasRenderingContext2DDelegate::deleteBitmap() {
}
void CanvasRenderingContext2DDelegate::fillTextureData() {
}
ccstd::array<float, 2> CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const ccstd::string &text) {
auto typography = createTypography(text);
Size textSize {static_cast<float>(OH_Drawing_TypographyGetMaxIntrinsicWidth(typography->get())),
static_cast<float>(OH_Drawing_TypographyGetHeight(typography->get()))};
if (_textAlign == TextAlign::CENTER) {
point[0] -= textSize[0] / 2.0f;
} else if (_textAlign == TextAlign::RIGHT) {
point[0] -= textSize[0];
}
double alphabeticBaseLine = OH_Drawing_TypographyGetAlphabeticBaseline(typography->get());
if (_textBaseLine == TextBaseline::TOP) {
//point[1] += -alphabeticBaseLine;
} else if (_textBaseLine == TextBaseline::MIDDLE) {
point[1] += -textSize[1] / 2.0f;
} else if (_textBaseLine == TextBaseline::BOTTOM) {
point[1] += -textSize[1];
} else if (_textBaseLine == TextBaseline::ALPHABETIC) {
//GetTextMetrics(_DC, &_tm);
//point[1] -= _tm.tmAscent;
point[1] -= alphabeticBaseLine;
}
return point;
}
std::unique_ptr<CanvasRenderingContext2DDelegate::ScopedTypography> CanvasRenderingContext2DDelegate::createTypography(const ccstd::string &text) {
OH_Drawing_TypographyHandlerPushTextStyle(_typographyCreate, _textStyle);
OH_Drawing_TypographyHandlerAddText(_typographyCreate, text.c_str());
OH_Drawing_TypographyHandlerPopTextStyle(_typographyCreate);
OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(_typographyCreate);
OH_Drawing_TypographyLayout(typography, _bufferWidth);
return std::make_unique<ScopedTypography>(typography);
}
void CanvasRenderingContext2DDelegate::fill() {
}
void CanvasRenderingContext2DDelegate::setLineCap(const ccstd::string &lineCap) {
}
void CanvasRenderingContext2DDelegate::setLineJoin(const ccstd::string &lineJoin) {
}
void CanvasRenderingContext2DDelegate::fillImageData(const Data & /* imageData */,
float /* imageWidth */,
float /* imageHeight */,
float /* offsetX */,
float /* offsetY */) {
}
void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string & /* text */,
float /* x */,
float /* y */,
float /* maxWidth */) {
}
void CanvasRenderingContext2DDelegate::rect(float /* x */,
float /* y */,
float /* w */,
float /* h */) {
}
void CanvasRenderingContext2DDelegate::updateData() {
}
} // namespace cc

View File

@@ -0,0 +1,136 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/interfaces/modules/canvas/ICanvasRenderingContext2D.h"
#include <array>
#include <cstdint>
#include <regex>
#include <memory>
#include <native_drawing/drawing_types.h>
#include <native_drawing/drawing_bitmap.h>
#include <native_drawing/drawing_text_declaration.h>
#include "base/csscolorparser.h"
#include "cocos/bindings/manual/jsb_platform.h"
#include "math/Math.h"
#include "platform/FileUtils.h"
namespace cc {
class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate {
public:
using Point = ccstd::array<float, 2>;
using Vec2 = ccstd::array<float, 2>;
using Size = ccstd::array<float, 2>;
using Color4F = ccstd::array<float, 4>;
using TextAlign = ICanvasRenderingContext2D::TextAlign;
using TextBaseline = ICanvasRenderingContext2D::TextBaseline;
CanvasRenderingContext2DDelegate();
~CanvasRenderingContext2DDelegate() override;
void recreateBuffer(float w, float h) override;
void beginPath() override;
void closePath() override;
void moveTo(float x, float y) override;
void lineTo(float x, float y) override;
void stroke() override;
void saveContext() override;
void restoreContext() override;
void clearRect(float /*x*/, float /*y*/, float w, float h) override;
void fillRect(float x, float y, float w, float h) override;
void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override;
void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) const;
Size measureText(const ccstd::string &text) override;
void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override;
void setTextAlign(TextAlign align) override;
void setTextBaseline(TextBaseline baseline) override;
void setFillStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override;
void setStrokeStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override;
void setLineWidth(float lineWidth) override;
const cc::Data &getDataRef() const override;
void fill() override;
void setLineCap(const ccstd::string &lineCap) override;
void setLineJoin(const ccstd::string &lineCap) override;
void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override;
void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override;
void rect(float x, float y, float w, float h) override;
void setShadowBlur(float blur)override{}
void setShadowColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override{}
void setShadowOffsetX(float offsetX) override{}
void setShadowOffsetY(float offsetY) override{}
void updateData() override;
private:
static wchar_t * utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr);
void removeCustomFont();
int drawText(const ccstd::string &text, int x, int y);
Size sizeWithText(const wchar_t *pszText, int nLen);
void prepareBitmap(int nWidth, int nHeight);
void deleteBitmap();
void fillTextureData();
ccstd::array<float, 2> convertDrawPoint(Point point, const ccstd::string &text);
class ScopedTypography;
std::unique_ptr<ScopedTypography> createTypography(const ccstd::string &text);
public:
int _screen{0};
private:
int32_t _x{0};
int32_t _y{0};
int32_t _lineCap{0};
int32_t _lineJoin{0};
private:
OH_Drawing_Bitmap* _bitmap{nullptr};
OH_Drawing_BitmapFormat _format {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE};
OH_Drawing_Canvas* _canvas{nullptr};
OH_Drawing_TypographyStyle* _typographyStyle{nullptr};
OH_Drawing_TypographyCreate* _typographyCreate{nullptr};
OH_Drawing_FontCollection* _fontCollection{nullptr};
OH_Drawing_TextStyle* _textStyle{nullptr};
cc::Data _imageData;
ccstd::string _curFontPath;
int _savedDC{0};
float _lineWidth{0.0F};
float _bufferWidth{0.0F};
float _bufferHeight{0.0F};
int32_t _bufferSize{0};
ccstd::string _fontName;
int _fontSize{0};
Size _textSize;
TextAlign _textAlign{TextAlign::CENTER};
TextBaseline _textBaseLine{TextBaseline::TOP};
Color4F _fillStyle{0};
Color4F _strokeStyle{0};
};
} // namespace cc

View File

@@ -0,0 +1,93 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/openharmony/modules/Screen.h"
#include "platform/openharmony/napi/NapiHelper.h"
#include "bindings/jswrapper/SeApi.h"
namespace cc {
int Screen::getDPI() const {
auto dpi = NapiHelper::napiCallFunction("getDPI");
if (dpi.IsNumber()) {
return dpi.As<Napi::Number>().Int32Value();
}
return 0;
}
float Screen::getDevicePixelRatio() const {
// float value;
// NapiHelper::napiCallFunction("getPixelRation", &value);
// return value;
// TODO(qgh):openharmony does support this interface, but returning a value of 1.5 will cause the entire page to zoom in.
return 1;
}
Screen::Orientation Screen::getDeviceOrientation() const {
auto dpi = NapiHelper::napiCallFunction("getDeviceOrientation");
int32_t value = 0;
if (dpi.IsNumber()) {
value = dpi.As<Napi::Number>().Int32Value();
}
if(value == 0) {
return Orientation::PORTRAIT;
} else if(value == 1) {
return Orientation::LANDSCAPE_LEFT;
} else if(value == 2) {
return Orientation::PORTRAIT_UPSIDE_DOWN;
} else if(value == 3) {
return Orientation::LANDSCAPE_RIGHT;
}
CC_ASSERT(false);
return Orientation::PORTRAIT;
}
void Screen::setKeepScreenOn(bool value) {
CC_UNUSED_PARAM(value);
}
Vec4 Screen::getSafeAreaEdge() const {
return cc::Vec4();
}
bool Screen::isDisplayStats() {
se::AutoHandleScope hs;
se::Value ret;
const char commandBuf[100] = "cc.profiler.isShowingStats();";
se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret);
return ret.toBoolean();
}
void Screen::setDisplayStats(bool isShow) {
se::AutoHandleScope hs;
char commandBuf[100] = {0};
sprintf(commandBuf, isShow ? "cc.profiler.showStats();" : "cc.profiler.hideStats();");
se::ScriptEngine::getInstance()->evalString(commandBuf);
}
} // namespace cc

View File

@@ -0,0 +1,51 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/interfaces/modules/IScreen.h"
namespace cc {
class Screen : public IScreen {
public:
int getDPI() const override;
float getDevicePixelRatio() const override;
void setKeepScreenOn(bool value) override;
Orientation getDeviceOrientation() const override;
Vec4 getSafeAreaEdge() const override;
/**
@brief Get current display stats.
@return bool, is displaying stats or not.
*/
bool isDisplayStats() override;
/**
@brief set display stats information.
*/
void setDisplayStats(bool isShow) override;
};
} // namespace cc

View File

@@ -0,0 +1,115 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/openharmony/modules/System.h"
#include <string>
#include "platform/openharmony/napi/NapiHelper.h"
namespace cc {
System::System() = default;
System::~System() = default;
System::OSType System::getOSType() const {
return OSType::OPENHARMONY;
}
std::string System::getDeviceModel() const {
return "";
}
System::LanguageType System::getCurrentLanguage() const {
ccstd::string languageStr = getCurrentLanguageCode(); // NOLINT
if (languageStr == "en") {
return ISystem::LanguageType::ENGLISH;
} else if (languageStr == "zh") {
return ISystem::LanguageType::CHINESE;
} else if (languageStr == "fr") {
return ISystem::LanguageType::FRENCH;
} else if (languageStr == "it") {
return ISystem::LanguageType::ITALIAN;
} else if (languageStr == "de") {
return ISystem::LanguageType::GERMAN;
} else if (languageStr == "es") {
return ISystem::LanguageType::SPANISH;
} else if (languageStr == "du") {
return ISystem::LanguageType::DUTCH;
} else if (languageStr == "ru") {
return ISystem::LanguageType::RUSSIAN;
} else if (languageStr == "ko") {
return ISystem::LanguageType::KOREAN;
} else if (languageStr == "ja") {
return ISystem::LanguageType::JAPANESE;
} else if (languageStr == "hu") {
return ISystem::LanguageType::HUNGARIAN;
} else if (languageStr == "pt") {
return ISystem::LanguageType::PORTUGUESE;
} else if (languageStr == "ar") {
return ISystem::LanguageType::ARABIC;
} else if (languageStr == "no") {
return ISystem::LanguageType::NORWEGIAN;
} else if (languageStr == "pl") {
return ISystem::LanguageType::POLISH;
} else if (languageStr == "tr") {
return ISystem::LanguageType::TURKISH;
} else if (languageStr == "uk") {
return ISystem::LanguageType::UKRAINIAN;
} else if (languageStr == "ro") {
return ISystem::LanguageType::ROMANIAN;
} else if (languageStr == "bg") {
return ISystem::LanguageType::BULGARIAN;
}
return ISystem::LanguageType::ENGLISH;
}
std::string System::getCurrentLanguageCode() const {
auto ret = NapiHelper::napiCallFunction("getSystemLanguage");
if (!ret.IsString()) {
return {};
}
auto str = ret.As<Napi::String>().Utf8Value();
std::string::size_type pos = str.find('-');
if(pos != std::string::npos) {
str = str.substr(0, pos);
}
return str;
}
std::string System::getSystemVersion() const {
auto ret = NapiHelper::napiCallFunction("getOSFullName");
if (!ret.IsString()) {
return {};
}
return ret.As<Napi::String>().Utf8Value();
}
bool System::openURL(const std::string& url) {
return false;
}
void System::copyTextToClipboard(const std::string& text) {
//copyTextToClipboardJNI(text);
}
} // namespace cc

View File

@@ -0,0 +1,68 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/interfaces/modules/ISystem.h"
class ANativeWindow;
namespace cc {
class System : public ISystem {
public:
System();
~System() override;
OSType getOSType() const override;
/**
@brief Get target device model.
*/
std::string getDeviceModel() const override;
/**
@brief Get current language config.
@return Current language config.
*/
LanguageType getCurrentLanguage() const override;
/**
@brief Get current language iso 639-1 code.
@return Current language iso 639-1 code.
*/
std::string getCurrentLanguageCode() const override;
/**
@brief Get system version.
@return system version.
*/
std::string getSystemVersion() const override;
/**
@brief Open url in default browser.
@param String with url to open.
@return True if the resource located by the URL was successfully opened; otherwise false.
*/
bool openURL(const std::string& url) override;
void copyTextToClipboard(const std::string& text) override;
};
} // namespace cc

View File

@@ -0,0 +1,85 @@
/****************************************************************************
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.
****************************************************************************/
#include "platform/openharmony/modules/SystemWindow.h"
#include "base/Log.h"
#include "base/Macros.h"
#include "platform/openharmony/OpenHarmonyPlatform.h"
namespace cc {
SystemWindow::SystemWindow(uint32_t windowId, void *externalHandle)
: _windowId(windowId) {
if (externalHandle) {
_windowHandle = reinterpret_cast<void*>(externalHandle);
}
}
SystemWindow::~SystemWindow() {
_windowHandle = 0;
_windowId = 0;
}
bool SystemWindow::createWindow(const char* title,
int x, int y, int w,
int h, int flags) {
CC_UNUSED_PARAM(title);
CC_UNUSED_PARAM(x);
CC_UNUSED_PARAM(y);
CC_UNUSED_PARAM(flags);
_width = w;
_height = h;
return true;
}
void SystemWindow::setCursorEnabled(bool value) {
}
uint32_t SystemWindow::getWindowId() const {
return _windowId;
}
uintptr_t SystemWindow::getWindowHandle() const {
return reinterpret_cast<uintptr_t>(_windowHandle);
}
void SystemWindow::setWindowHandle(void* window) {
_windowHandle = window;
}
void SystemWindow::setViewSize(uint32_t width, uint32_t height) {
_width = width;
_height = height;
}
SystemWindow::Size SystemWindow::getViewSize() const {
return Size{static_cast<float>(_width),
static_cast<float>(_height)};
}
} // namespace cc

View File

@@ -0,0 +1,63 @@
/****************************************************************************
Copyright (c) 2021-2023 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 <iostream>
#include "platform/interfaces/modules/ISystemWindow.h"
#include <ace/xcomponent/native_interface_xcomponent.h>
namespace cc {
class SystemWindow : public ISystemWindow {
public:
explicit SystemWindow(uint32_t windowId, void* externalHandle);
~SystemWindow() override;
bool createWindow(const char* title,
int x, int y, int w,
int h, int flags) override;
uint32_t getWindowId() const override;
uintptr_t getWindowHandle() const override;
void setWindowHandle(void* window);
Size getViewSize() const override;
void setViewSize(uint32_t width, uint32_t height) override;
/**
@brief enable/disable(lock) the cursor, default is enabled
*/
void setCursorEnabled(bool value) override;
private:
void* _windowHandle{nullptr};
uint32_t _windowId{0};
std::string _id{""};
uint64_t _width{0};
uint64_t _height{0};
};
} // namespace cc

View File

@@ -0,0 +1,93 @@
/****************************************************************************
Copyright (c) 2023 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 documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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/SDLHelper.h"
#include "platform/interfaces/modules/ISystemWindowManager.h"
#include "platform/openharmony/modules/SystemWindow.h"
namespace cc {
int SystemWindowManager::init() {
return 0;
}
void SystemWindowManager::processEvent() {
}
ISystemWindow *SystemWindowManager::createWindow(const 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<ISystemWindow>(window);
_nextWindowId++;
}
return window;
}
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::getWindowFromHandle(void *window) const {
if (!window) {
return nullptr;
}
for (const auto &pair : _windows) {
ISystemWindow *sysWindow = pair.second.get();
auto *nativeWindow = reinterpret_cast<void *>(sysWindow->getWindowHandle());
if (nativeWindow == window) {
return sysWindow;
}
}
return nullptr;
}
void SystemWindowManager::removeWindow(void* window) {
if (!window) {
return;
}
for (auto it = _windows.begin(); it != _windows.end(); ++it) {
ISystemWindow *sysWindow = it->second.get();
auto *nativeWindow = reinterpret_cast<void *>(sysWindow->getWindowHandle());
if (nativeWindow == window) {
_windows.erase(it);
break;
}
}
return;
}
} // namespace cc

View File

@@ -0,0 +1,51 @@
/****************************************************************************
Copyright (c) 2023 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 documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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:
SystemWindowManager() = default;
int init() override;
void processEvent() override;
ISystemWindow *createWindow(const ISystemWindowInfo &info) override;
ISystemWindow *getWindow(uint32_t windowId) const override;
const SystemWindowMap &getWindows() const override { return _windows; }
ISystemWindow *getWindowFromHandle(void* handle) const;
void removeWindow(void* window);
private:
uint32_t _nextWindowId{1}; // start from 1, 0 means an invalid ID
SystemWindowMap _windows;
};
} // namespace cc

View File

@@ -0,0 +1,356 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/openharmony/napi/NapiHelper.h"
#include <ace/xcomponent/native_interface_xcomponent.h>
#include "platform/openharmony/OpenHarmonyPlatform.h"
#include "platform/openharmony/modules/SystemWindow.h"
#include "platform/openharmony/FileUtils-OpenHarmony.h"
#include "bindings/jswrapper/SeApi.h"
#if CC_USE_EDITBOX
#include "ui/edit-box/EditBox-openharmony.h"
#endif
#if CC_USE_WEBVIEW
#include "ui/webview/WebViewImpl-openharmony.h"
#endif
namespace cc {
// Must be the same as the value called by js
enum ContextType {
APP_LIFECYCLE = 0,
JS_PAGE_LIFECYCLE,
XCOMPONENT_CONTEXT,
XCOMPONENT_REGISTER_LIFECYCLE_CALLBACK,
NATIVE_RENDER_API,
WORKER_INIT,
ENGINE_UTILS,
EDITBOX_UTILS,
WEBVIEW_UTILS,
UV_ASYNC_SEND,
VIDEO_UTILS,
};
static Napi::Env gWorkerEnv(nullptr);
static Napi::FunctionReference* gPostMessageToUIThreadFunc = nullptr;
static Napi::FunctionReference* gPostSyncMessageToUIThreadFunc = nullptr;
#define DEFINE_FUNCTION_CALLBACK(functionName, cachedFunctionRefPtr) \
static void functionName(const Napi::CallbackInfo &info) { \
Napi::Env env = info.Env(); \
if (info.Length() != 1) { \
Napi::Error::New(env, "setPostMessageFunction, 1 argument expected").ThrowAsJavaScriptException(); \
return; \
} \
\
if (!info[0].IsFunction()) { \
Napi::TypeError::New(env, "setPostMessageFunction, function expected").ThrowAsJavaScriptException(); \
return; \
} \
\
delete cachedFunctionRefPtr; \
cachedFunctionRefPtr = new Napi::FunctionReference(Napi::Persistent(info[0].As<Napi::Function>())); \
}
DEFINE_FUNCTION_CALLBACK(js_set_PostMessage2UIThreadCallback, gPostMessageToUIThreadFunc)
DEFINE_FUNCTION_CALLBACK(js_set_PostSyncMessage2UIThreadCallback, gPostSyncMessageToUIThreadFunc)
/* static */
void NapiHelper::postMessageToUIThread(const std::string& type, Napi::Value param) {
if (gPostMessageToUIThreadFunc == nullptr) {
CC_LOG_ERROR("callback was not set %s, type: %s", __FUNCTION__, type.c_str());
return;
}
gPostMessageToUIThreadFunc->Call({Napi::String::New(getWorkerEnv(), type), param});
}
/* static */
Napi::Value NapiHelper::postSyncMessageToUIThread(const std::string& type, Napi::Value param) {
if (gPostSyncMessageToUIThreadFunc == nullptr) {
CC_LOG_ERROR("callback was not set %s, type: %s", __FUNCTION__, type.c_str());
return getWorkerEnv().Undefined();
}
// it return a promise object
return gPostSyncMessageToUIThreadFunc->Call({Napi::String::New(getWorkerEnv(), type), param}).As<Napi::Promise>();
}
/* static */
Napi::Value NapiHelper::napiCallFunction(const char* functionName) {
auto env = getWorkerEnv();
auto funcVal = env.Global().Get(functionName);
if (!funcVal.IsFunction()) {
return {};
}
return funcVal.As<Napi::Function>().Call(env.Global(), {});
}
// NAPI Interface
static bool exportFunctions(Napi::Object exports) {
Napi::MaybeOrValue<Napi::Value> xcomponentObject = exports.Get(OH_NATIVE_XCOMPONENT_OBJ);
if (!xcomponentObject.IsObject()) {
CC_LOG_ERROR("Could not get property: %s", OH_NATIVE_XCOMPONENT_OBJ);
return false;
}
auto* nativeXComponent = Napi::ObjectWrap<OH_NativeXComponent>::Unwrap(xcomponentObject.As<Napi::Object>());
if (nativeXComponent == nullptr) {
CC_LOG_ERROR("nativeXComponent is nullptr");
return false;
}
OpenHarmonyPlatform::getInstance()->setNativeXComponent(nativeXComponent);
return true;
}
// APP Lifecycle
static void napiOnCreate(const Napi::CallbackInfo &info) {
// uv_loop_t* loop = nullptr;
// NAPI_CALL(env, napi_get_uv_event_loop(env, &loop));
// OpenHarmonyPlatform::getInstance()->onCreateNative(env, loop);
CC_LOG_INFO("napiOnCreate");
}
static void napiOnShow(const Napi::CallbackInfo &info) {
CC_LOG_INFO("napiOnShow");
cc::WorkerMessageData data{cc::MessageType::WM_APP_SHOW, nullptr, nullptr};
OpenHarmonyPlatform::getInstance()->enqueue(data);
}
static void napiOnHide(const Napi::CallbackInfo &info) {
CC_LOG_INFO("napiOnHide");
cc::WorkerMessageData data{cc::MessageType::WM_APP_HIDE, nullptr, nullptr};
OpenHarmonyPlatform::getInstance()->enqueue(data);
}
static void napiOnDestroy(const Napi::CallbackInfo &info) {
CC_LOG_INFO("napiOnDestroy");
cc::WorkerMessageData data{cc::MessageType::WM_APP_DESTROY, nullptr, nullptr};
OpenHarmonyPlatform::getInstance()->enqueue(data);
}
// JS Page : Lifecycle
static void napiOnPageShow(const Napi::CallbackInfo &info) {
CC_LOG_INFO("napiOnPageShow");
}
static void napiOnPageHide(const Napi::CallbackInfo &info) {
CC_LOG_INFO("napiOnPageHide");
}
static void napiNativeEngineInit(const Napi::CallbackInfo &info) {
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI
se::ScriptEngine::setEnv(info.Env());
#endif
CC_LOG_INFO("napiNativeEngineInit before run");
OpenHarmonyPlatform::getInstance()->run(0, nullptr);
CC_LOG_INFO("napiNativeEngineInit after run");
}
static void napiNativeEngineStart(const Napi::CallbackInfo &info) {
OpenHarmonyPlatform::getInstance()->requestVSync();
}
static void napiWorkerInit(const Napi::CallbackInfo &info) {
CC_LOG_INFO("napiWorkerInit ...");
Napi::Env env = info.Env();
uv_loop_t* loop = nullptr;
napi_status status = napi_get_uv_event_loop(napi_env(env), &loop);
if (status != napi_ok) {
CC_LOG_ERROR("napi_get_uv_event_loop failed!");
return;
}
OpenHarmonyPlatform::getInstance()->workerInit(loop);
}
static void napiResourceManagerInit(const Napi::CallbackInfo &info) {
if (info.Length() != 1) {
Napi::Error::New(info.Env(), "1 argument expected").ThrowAsJavaScriptException();
return;
}
FileUtilsOpenHarmony::initResourceManager(napi_env(info.Env()), napi_value(info[0]));
}
static void napiWritablePathInit(const Napi::CallbackInfo &info) {
if (info.Length() != 1) {
Napi::Error::New(info.Env(), "1 argument expected").ThrowAsJavaScriptException();
return;
}
if (!info[0].IsString()) {
Napi::Error::New(info.Env(), "string expected").ThrowAsJavaScriptException();
return;
}
FileUtilsOpenHarmony::_ohWritablePath = info[0].As<Napi::String>().Utf8Value();
}
static void napiASend(const Napi::CallbackInfo &info) {
OpenHarmonyPlatform::getInstance()->triggerMessageSignal();
}
static void napiOnVideoEvent(const Napi::CallbackInfo &info) {
if (info.Length() != 3) {
Napi::Error::New(info.Env(), "napiOnVideoEvent, 3 argument expected").ThrowAsJavaScriptException();
return;
}
int32_t videoTag = info[0].As<Napi::Number>().Int32Value();
int32_t videoEvent = info[1].As<Napi::Number>().Int32Value();
bool hasArg = false;
double arg = 0.0;
if (info[2].IsNumber()) {
arg = info[2].As<Napi::Number>().DoubleValue();
hasArg = true;
}
se::AutoHandleScope hs;
auto *global = se::ScriptEngine::getInstance()->getGlobalObject();
se::Value ohVal;
bool ok = global->getProperty("oh", &ohVal);
if (!ok || !ohVal.isObject()) {
CC_LOG_ERROR("oh var not found");
return;
}
se::Value onVideoEventVal;
ok = ohVal.toObject()->getProperty("onVideoEvent", &onVideoEventVal);
if (!ok || !onVideoEventVal.isObject() || !onVideoEventVal.toObject()->isFunction()) {
CC_LOG_ERROR("onVideoEvent not found");
return;
}
// Convert args to se::ValueArray
se::ValueArray seArgs;
seArgs.reserve(3);
seArgs.emplace_back(se::Value(videoTag));
seArgs.emplace_back(se::Value(videoEvent));
if (hasArg) {
seArgs.emplace_back(se::Value(arg));
}
ok = onVideoEventVal.toObject()->call(seArgs, ohVal.toObject());
if (!ok) {
CC_LOG_ERROR("Call oh.onEventEvent failed!");
}
}
// NAPI Interface
static Napi::Value getContext(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
size_t argc = info.Length();
if (argc != 1) {
Napi::Error::New(env, "Wrong argument count, 1 expected!").ThrowAsJavaScriptException();
return env.Undefined();
}
if (!info[0].IsNumber()) {
Napi::TypeError::New(env, "number expected!").ThrowAsJavaScriptException();
return env.Undefined();
}
auto exports = Napi::Object::New(env);
int64_t value = info[0].As<Napi::Number>().Int64Value();
switch (value) {
case APP_LIFECYCLE: {
exports["onCreate"] = Napi::Function::New(env, napiOnCreate);
exports["onDestroy"] = Napi::Function::New(env, napiOnDestroy);
exports["onShow"] = Napi::Function::New(env, napiOnShow);
exports["onHide"] = Napi::Function::New(env, napiOnHide);
} break;
case JS_PAGE_LIFECYCLE: {
exports["onPageShow"] = Napi::Function::New(env, napiOnPageShow);
exports["onPageHide"] = Napi::Function::New(env, napiOnPageHide);
} break;
case XCOMPONENT_REGISTER_LIFECYCLE_CALLBACK: {
} break;
case NATIVE_RENDER_API: {
exports["nativeEngineInit"] = Napi::Function::New(env, napiNativeEngineInit);
exports["nativeEngineStart"] = Napi::Function::New(env, napiNativeEngineStart);
} break;
case WORKER_INIT: {
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI
se::ScriptEngine::setEnv(env);
#endif
gWorkerEnv = env;
exports["workerInit"] = Napi::Function::New(env, napiWorkerInit);
exports["setPostMessageFunction"] = Napi::Function::New(env, js_set_PostMessage2UIThreadCallback);
exports["setPostSyncMessageFunction"] = Napi::Function::New(env, js_set_PostSyncMessage2UIThreadCallback);
} break;
case ENGINE_UTILS: {
exports["resourceManagerInit"] = Napi::Function::New(env, napiResourceManagerInit);
exports["writablePathInit"] = Napi::Function::New(env, napiWritablePathInit);
} break;
case EDITBOX_UTILS: {
#if CC_USE_EDITBOX
exports["onTextChange"] = Napi::Function::New(env, OpenHarmonyEditBox::napiOnTextChange);
exports["onComplete"] = Napi::Function::New(env, OpenHarmonyEditBox::napiOnComplete);
#endif
} break;
case WEBVIEW_UTILS: {
#if CC_USE_WEBVIEW
exports["shouldStartLoading"] = Napi::Function::New(env, OpenHarmonyWebView::napiShouldStartLoading);
exports["finishLoading"] = Napi::Function::New(env, OpenHarmonyWebView::napiFinishLoading);
exports["failLoading"] = Napi::Function::New(env, OpenHarmonyWebView::napiFailLoading);
exports["jsCallback"] = Napi::Function::New(env, OpenHarmonyWebView::napiJsCallback);
#endif
} break;
case UV_ASYNC_SEND: {
exports["send"] = Napi::Function::New(env, napiASend);
} break;
case VIDEO_UTILS: {
exports["onVideoEvent"] = Napi::Function::New(env, napiOnVideoEvent);
} break;
default:
CC_LOG_ERROR("unknown type");
}
return exports;
}
/* static */
Napi::Env NapiHelper::getWorkerEnv() {
return gWorkerEnv;
}
/* static */
Napi::Object NapiHelper::init(Napi::Env env, Napi::Object exports) {
exports["getContext"] = Napi::Function::New(env, getContext);
bool ret = exportFunctions(exports);
if (!ret) {
CC_LOG_ERROR("NapiHelper init failed");
}
return exports;
}
} // namespace cc

View File

@@ -0,0 +1,44 @@
/****************************************************************************
Copyright (c) 2022-2023 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
#define NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS 1
#define NAPI_DISABLE_CPP_EXCEPTIONS 1
#define NODE_ADDON_API_DISABLE_DEPRECATED 1
#include "napi.h"
namespace cc {
class NapiHelper {
public:
static Napi::Env getWorkerEnv();
static Napi::Object init(Napi::Env env, Napi::Object exports);
static Napi::Value napiCallFunction(const char* functionName);
static void postMessageToUIThread(const std::string& type, Napi::Value param);
static Napi::Value postSyncMessageToUIThread(const std::string& type, Napi::Value param);
};
} // namespace cc

View File

@@ -0,0 +1,54 @@
/****************************************************************************
Copyright (c) 2022-2023 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 "platform/openharmony/napi/NapiHelper.h"
static const char kLibname[] = "cocos";
/*
* function for module exports
*/
static napi_value init(napi_env env, napi_value exports) {
cc::NapiHelper::init(Napi::Env(env), Napi::Object(env, exports));
return exports;
}
/*
* Napi Module define
*/
static napi_module cocos2dModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = init, // called by ACE XComponent
.nm_modname = kLibname,
.nm_priv = ((void*)0),
.reserved = {0},
};
/*
* Module register function
*/
extern "C" __attribute__((visibility ("default"))) __attribute__((constructor)) void RegisterModule(void) {
napi_module_register(&cocos2dModule);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff