demo submit and 修改了另外两个demo的名字

Signed-off-by: Zjsxstar <yuguanbin@huawei.com>
This commit is contained in:
Zjsxstar 2024-08-26 17:26:56 +08:00
parent 66320f7d81
commit 418eec9571
112 changed files with 3591 additions and 1422 deletions

14
OAT.xml
View File

@ -103,12 +103,24 @@ Note:If the text contains special characters, please escape them according to th
<filteritem type="filepath" name="network/Bluetooth/entry/src/main/java/ohos/samples/bluetooth/adapter/" desc="Not contains 3rd codelicense file is not required in this subdirectory."/>
</filefilter>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binary file policies" >
<filteritem type="filepath" name="code/BasicFeature/Native/XComponent/entry/src/ohosTest/resources/base/media/icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/ArkTSXComponent/entry/src/ohosTest/resources/base/media/icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/ArkTSXComponent/screenshots/device/changeColor.png" desc="Provided by code/BasicFeature/Native/ArkTSXComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/ArkTSXComponent/screenshots/device/drawStar.png" desc="Provided by code/BasicFeature/Native/ArkTSXComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/ArkTSXComponent/screenshots/device/main.png" desc="Provided by code/BasicFeature/Native/ArkTSXComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/ArkTSXComponent/AppScope/resources/base/media/app_icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/ArkTSXComponent/entry/src/main/resources/base/media/icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/XComponent/entry/src/ohosTest/resources/base/media/icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/XComponent/screenshots/device/changeColor.png" desc="Provided by code/BasicFeature/Native/XComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/XComponent/screenshots/device/drawStar.png" desc="Provided by code/BasicFeature/Native/XComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/XComponent/screenshots/device/main.png" desc="Provided by code/BasicFeature/Native/XComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/XComponent/AppScope/resources/base/media/app_icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/XComponent/entry/src/main/resources/base/media/icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/NdkXComponent/entry/src/ohosTest/resources/base/media/icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/NdkXComponent/screenshots/device/changeColor.png" desc="Provided by code/BasicFeature/Native/NdkXComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/NdkXComponent/screenshots/device/drawStar.png" desc="Provided by code/BasicFeature/Native/NdkXComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/NdkXComponent/screenshots/device/main.png" desc="Provided by code/BasicFeature/Native/NdkXComponent."/>
<filteritem type="filepath" name="code/BasicFeature/Native/NdkXComponent/AppScope/resources/base/media/app_icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Native/NdkXComponent/entry/src/main/resources/base/media/icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Security/Asset/AppScope/resources/base/media/app_icon.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Security/Asset/AppScope/resources/base/media/forward.png" desc="Provided by the UX team."/>
<filteritem type="filepath" name="code/BasicFeature/Security/Asset/AppScope/resources/base/media/back.png" desc="Provided by the UX team."/>

View File

@ -0,0 +1,11 @@
/node_modules
/oh_modules
/local.properties
/.idea
**/build
/.hvigor
.cxx
/.clangd
/.clang-format
/.clang-tidy
**/.test

View File

@ -0,0 +1,25 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
"app": {
"bundleName": "com.samples.arktsxcomponent",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",
"label": "$string:app_name"
}
}

View File

@ -0,0 +1,8 @@
{
"string": [
{
"name": "app_name",
"value": "ArkTSXComponent"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

View File

@ -0,0 +1,102 @@
# XComponent
### 介绍
本示例主要介绍开发者如何使用ArkTS XComponent组件进行自绘制主要包括XComponent组件使用
SurfaceId获取方法Surface生命周期回调使用NativeWindow创建等知识点。开发者基于ArkTS侧获取的SurfaceId
在Native侧调用OH_NativeWindow_CreateNativeWindowFromSurfaceId接口创建出NativeWindow实例后使用OpenGL ES/EGL接口在XComponent组件上进行图形绘制。功能主要包括点击按钮绘制一个五角星并可以通过点击XComponent区域改变五角星的颜色。
### 效果预览
| 主页 | 绘制五角星 | 改变颜色 |
|--------------------------------------|-----------------------------------------------|-----------------------------------------------------|
| ![main](screenshots/device/main.png) | ![draw star](screenshots/device/drawStar.png) | ![change color](screenshots/device/changeColor.png) |
使用说明
1. 安装编译生成的hap包并打开应用。
2. 点击页面底部“Draw Star”按钮页面将绘制一个五角星。
3. 点击XComponent组件区域页面中灰色区域改变五角星颜色。
### 工程目录
```
├──entry/src/main
│ ├──cpp // C++代码区
│ │ ├──CMakeLists.txt // CMake配置文件
│ │ ├──napi_init.cpp // Napi模块注册
│ │ ├──common
│ │ │ └──common.h // 常量定义文件
│ │ ├──manager // 生命周期管理模块
│ │ │ ├──plugin_manager.cpp
│ │ │ └──plugin_manager.h
│ │ ├──render // 渲染模块
│ │ │ ├──egl_core.cpp
│ │ │ ├──egl_core.h
│ │ │ ├──plugin_render.cpp
│ │ │ └──plugin_render.h
│ ├──ets // ets代码区
│ │ ├──entryability
│ │ │ └──EntryAbility.ts // 程序入口类
│ │ └──pages // 页面文件
│ │ └──Index.ets // 主界面
| ├──resources // 资源文件目录
```
### 具体实现
通过在IDE中创建Native c++ 工程在c++代码中定义对外接口为DrawPattern在ArkTS侧调用该接口可在页面上绘制出一个五角星。在
c++代码中定义对外接口为ChangeColor点击XComponent组件时在ArkTs侧调用该接口可在页面绘制一个大小相同、颜色不同的五角星达到改变颜色的目的。
在XComponentController的OnSurfaceCreated回调中传入XComponent的surfaceId在Native侧调用OH_NativeWindow_CreateNativeWindowFromSurfaceId创建NativeWindow实例并初始化
EGL环境。在XComponentController的OnsurfaceChanged回调中传入surfaceId、宽和高并以此为输入调用EGL相关的接口改变对应NativeWindow的尺寸和内容。
源码参考:[main目录](entry/src/main/)下的文件。涉及到的相关接口:
#### ArkTS组件
XComponentController
| 接口名 | 描述 |
|-------------------------------------------|--------------------------|
| getXComponentSurfaceId(): string | 获取XComponent对应Surface的ID |
| onSurfaceCreated(surfaceId: string): void |当XComponent持有的Surface创建后进行该回调|
|onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void|当XComponent持有的Surface尺寸更新时进行该回调包括初始尺寸设定|
|onSurfaceDestroyed(surfaceId: string): void|当XComponent持有的Surface销毁后进行该回调|
#### C API
| 接口名 | 描述 |
|-------------------------------------------|--------------------------|
| int32_t OH_NativeWindow_CreateNativeWindowFromSurfaceId (uint64_t surfaceId, OHNativeWindow **window ) | 通过surfaceId创建对应的OHNativeWindow |
| void OH_NativeWindow_DestroyNativeWindow (OHNativeWindow* window)|将OHNativeWindow对象的引用计数减1当引用计数为0的时候该OHNativeWindow对象会被析构掉|
### 相关权限
不涉及。
### 依赖
不涉及。
### 约束与限制
1. 本示例仅支持标准系统上运行支持设备rk3568
2. 本示例为Stage模型支持API12版本SDKSDK版本号(API Version 12 Release),镜像版本号(5.0 Release)
3. 本示例需要使用DevEco Studio 版本号(4.0 Release)及以上版本才可编译运行
### 下载
如需单独下载本工程,执行如下命令:
```
git init
git config core.sparsecheckout true
echo code/BasicFeature/Native/ArkTSXComponent/ > .git/info/sparse-checkout
git remote add origin https://gitee.com/openharmony/applications_app_samples.git
git pull origin master
```

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
"app": {
"signingConfigs": [],
"products": [
{
"name": "default",
"signingConfig": "default",
"compileSdkVersion": 12,
"compatibleSdkVersion": 12,
"runtimeOS": "OpenHarmony",
}
],
"buildModeSet": [
{
"name": "debug",
},
{
"name": "release"
}
]
},
"modules": [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
}
]
}

View File

@ -0,0 +1,6 @@
/node_modules
/oh_modules
/.preview
/build
/.cxx
/.test

View File

@ -0,0 +1,56 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
"apiType": "stageMode",
"buildOption": {
"externalNativeOptions": {
"path": "./src/main/cpp/CMakeLists.txt",
"arguments": "",
"cppFlags": "",
"abiFilters": ["arm64-v8a", "armeabi-v7a", "x86_64"]
}
},
"buildOptionSet": [
{
"name": "release",
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": true,
"files": [
"./obfuscation-rules.txt"
]
}
}
},
"nativeLib": {
"debugSymbol": {
"strip": true,
"exclude": []
}
}
},
],
"targets": [
{
"name": "default"
},
{
"name": "ohosTest",
}
]
}

View File

@ -0,0 +1,6 @@
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}

View File

@ -0,0 +1,11 @@
{
"name": "entry",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "",
"author": "",
"license": "",
"dependencies": {
"libnativerender.so": "file:./src/main/cpp/types/libnativerender"
}
}

View File

@ -0,0 +1,69 @@
# the minimum version of CMake.
cmake_minimum_required(VERSION 3.4.1)
project(XComponent)
set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
add_definitions(-DOHOS_PLATFORM)
include_directories(
${NATIVERENDER_ROOT_PATH}
${NATIVERENDER_ROOT_PATH}/include
)
add_library(nativerender SHARED
render/egl_core.cpp
render/plugin_render.cpp
manager/plugin_manager.cpp
napi_init.cpp
)
find_library(
# Sets the name of the path variable.
EGL-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
EGL
)
find_library(
# Sets the name of the path variable.
GLES-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
GLESv3
)
find_library(
# Sets the name of the path variable.
hilog-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
hilog_ndk.z
)
find_library(
# Sets the name of the path variable.
libace-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
ace_ndk.z
)
find_library(
# Sets the name of the path variable.
libnapi-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
ace_napi.z
)
find_library(
# Sets the name of the path variable.
libuv-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
uv
)
target_link_libraries(nativerender PUBLIC
${EGL-lib} ${GLES-lib} ${hilog-lib} ${libace-lib} ${libnapi-lib} ${libuv-lib} libnative_window.so)

View File

@ -0,0 +1,31 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVE_XCOMPONENT_COMMON_H
#define NATIVE_XCOMPONENT_COMMON_H
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <EGL/eglplatform.h>
#include <GLES3/gl3.h>
#include <napi/native_api.h>
namespace NativeXComponentSample {
/**
* Log print domain.
*/
const unsigned int LOG_PRINT_DOMAIN = 0xFF00;
} // namespace NativeXComponentSample
#endif // NATIVE_XCOMPONENT_COMMON_H

View File

@ -0,0 +1,218 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "plugin_manager.h"
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <cstdint>
#include <hilog/log.h>
#include <native_drawing/drawing_text_typography.h>
#include <string>
#include "../common/common.h"
#include <native_window/external_window.h>
namespace NativeXComponentSample {
namespace {
int64_t ParseId(napi_env env, napi_callback_info info)
{
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "ParseId", "env or info is null");
return -1;
}
size_t argc = 1;
napi_value args[1] = {nullptr};
if (napi_ok != napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "ParseId", "GetContext napi_get_cb_info failed");
return -1;
}
int64_t value = 0;
bool lossless = true;
if (napi_ok != napi_get_value_bigint_int64(env, args[0], &value, &lossless)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "ParseId", "Get value failed");
return -1;
}
return value;
}
}
std::unordered_map<int64_t, PluginRender*> PluginManager::pluginRenderMap_;
std::unordered_map<int64_t, OHNativeWindow*> PluginManager::windowMap_;
PluginManager::~PluginManager()
{
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "~PluginManager");
for (auto iter = pluginRenderMap_.begin(); iter != pluginRenderMap_.end(); ++iter) {
if (iter->second != nullptr) {
delete iter->second;
iter->second = nullptr;
}
}
pluginRenderMap_.clear();
for (auto iter = windowMap_.begin(); iter != windowMap_.end(); ++iter) {
if (iter->second != nullptr) {
delete iter->second;
iter->second = nullptr;
}
}
windowMap_.clear();
}
PluginRender* PluginManager::GetPluginRender(int64_t& id)
{
if (pluginRenderMap_.find(id) != pluginRenderMap_.end()) {
return pluginRenderMap_[id];
}
return nullptr;
}
napi_value PluginManager::SetSurfaceId(napi_env env, napi_callback_info info)
{
int64_t surfaceId = ParseId(env, info);
OHNativeWindow *nativeWindow;
PluginRender *pluginRender;
if (windowMap_.find(surfaceId) == windowMap_.end()) {
OH_NativeWindow_CreateNativeWindowFromSurfaceId(surfaceId, &nativeWindow);
windowMap_[surfaceId] = nativeWindow;
}
if (pluginRenderMap_.find(surfaceId) == pluginRenderMap_.end()) {
pluginRender = new PluginRender(surfaceId);
pluginRenderMap_[surfaceId] = pluginRender;
}
pluginRender->InitNativeWindow(nativeWindow);
return nullptr;
}
napi_value PluginManager::DestroySurface(napi_env env, napi_callback_info info)
{
int64_t surfaceId = ParseId(env, info);
auto pluginRenderMapIter = pluginRenderMap_.find(surfaceId);
if (pluginRenderMapIter != pluginRenderMap_.end()) {
delete pluginRenderMapIter->second;
pluginRenderMap_.erase(pluginRenderMapIter);
}
auto windowMapIter = windowMap_.find(surfaceId);
if (windowMapIter != windowMap_.end()) {
OH_NativeWindow_DestroyNativeWindow(windowMapIter->second);
windowMap_.erase(windowMapIter);
}
return nullptr;
}
napi_value PluginManager::ChangeSurface(napi_env env, napi_callback_info info)
{
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"ChangeSurface: OnLoad env or info is null");
return nullptr;
}
int64_t surfaceId = 0;
size_t argc = 3;
napi_value args[3] = {nullptr};
if (napi_ok != napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"ChangeSurface: GetContext napi_get_cb_info failed");
}
bool lossless = true;
int index = 0;
if (napi_ok != napi_get_value_bigint_int64(env, args[index++], &surfaceId, &lossless)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeSurface: Get value failed");
}
double width;
if (napi_ok != napi_get_value_double(env, args[index++], &width)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeSurface: Get width failed");
}
double height;
if (napi_ok != napi_get_value_double(env, args[index++], &height)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeSurface: Get height failed");
}
auto pluginRender = GetPluginRender(surfaceId);
if (pluginRender == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeSurface: Get pluginRender failed");
return nullptr;
}
pluginRender->UpdateNativeWindowSize(width, height);
return nullptr;
}
napi_value PluginManager::ChangeColor(napi_env env, napi_callback_info info)
{
int64_t surfaceId = ParseId(env, info);
auto pluginRender = GetPluginRender(surfaceId);
if (pluginRender == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeColor: Get pluginRender failed");
return nullptr;
}
pluginRender->ChangeColor();
return nullptr;
}
napi_value PluginManager::DrawPattern(napi_env env, napi_callback_info info)
{
int64_t surfaceId = ParseId(env, info);
auto pluginRender = GetPluginRender(surfaceId);
if (pluginRender == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "DrawPattern: Get pluginRender failed");
return nullptr;
}
pluginRender->DrawPattern();
return nullptr;
}
napi_value PluginManager::GetXComponentStatus(napi_env env, napi_callback_info info)
{
int64_t surfaceId = ParseId(env, info);
auto pluginRender = GetPluginRender(surfaceId);
if (pluginRender == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: Get pluginRender failed");
return nullptr;
}
napi_value hasDraw;
napi_value hasChangeColor;
napi_status ret = napi_create_int32(env, pluginRender->HasDraw(), &(hasDraw));
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: napi_create_int32 hasDraw_ error");
return nullptr;
}
ret = napi_create_int32(env, pluginRender->HasChangedColor(), &(hasChangeColor));
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: napi_create_int32 hasChangeColor_ error");
return nullptr;
}
napi_value obj;
ret = napi_create_object(env, &obj);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN,
"PluginManager", "GetXComponentStatus: napi_create_object error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasDraw", hasDraw);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: napi_set_named_property hasDraw error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasChangeColor", hasChangeColor);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: napi_set_named_property hasChangeColor error");
return nullptr;
}
return obj;
}
} // namespace NativeXComponentSample

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVE_XCOMPONENT_PLUGIN_MANAGER_H
#define NATIVE_XCOMPONENT_PLUGIN_MANAGER_H
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <unordered_map>
#include <native_window/external_window.h>
#include "../render/plugin_render.h"
namespace NativeXComponentSample {
class PluginManager {
public:
~PluginManager();
static PluginRender* GetPluginRender(int64_t& id);
static napi_value ChangeColor(napi_env env, napi_callback_info info);
static napi_value DrawPattern(napi_env env, napi_callback_info info);
static napi_value SetSurfaceId(napi_env env, napi_callback_info info);
static napi_value ChangeSurface(napi_env env, napi_callback_info info);
static napi_value DestroySurface(napi_env env, napi_callback_info info);
static napi_value GetXComponentStatus(napi_env env, napi_callback_info info);
public:
static std::unordered_map<int64_t, PluginRender*> pluginRenderMap_;
static std::unordered_map<int64_t, OHNativeWindow*> windowMap_;
};
} // namespace NativeXComponentSample
#endif // NATIVE_XCOMPONENT_PLUGIN_MANAGER_H

View File

@ -0,0 +1,65 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <hilog/log.h>
#include "common/common.h"
#include "manager/plugin_manager.h"
namespace NativeXComponentSample {
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Init", "Init begins");
if ((env == nullptr) || (exports == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Init", "env or exports is null");
return nullptr;
}
napi_property_descriptor desc[] = {
{"ChangeColor", nullptr, PluginManager::ChangeColor,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"SetSurfaceId", nullptr, PluginManager::SetSurfaceId,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"ChangeSurface", nullptr, PluginManager::ChangeSurface,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"GetXComponentStatus", nullptr, PluginManager::GetXComponentStatus,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"DrawPattern", nullptr, PluginManager::DrawPattern,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"DestroySurface", nullptr, PluginManager::DestroySurface,
nullptr, nullptr, nullptr, napi_default, nullptr}
};
if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Init", "napi_define_properties failed");
return nullptr;
}
return exports;
}
EXTERN_C_END
static napi_module nativerenderModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "nativerender",
.nm_priv = ((void*)0),
.reserved = { 0 } };
} // namespace NativeXComponentSample
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&NativeXComponentSample::nativerenderModule);
}

View File

@ -0,0 +1,607 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "egl_core.h"
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <EGL/eglplatform.h>
#include <GLES3/gl3.h>
#include <cmath>
#include <cstdio>
#include <hilog/log.h>
#include "../common/common.h"
#include "plugin_render.h"
namespace NativeXComponentSample {
namespace {
constexpr int32_t NUM_4 = 4;
/**
* Vertex shader.
*/
const char VERTEX_SHADER[] = "#version 300 es\n"
"layout(location = 0) in vec4 a_position;\n"
"layout(location = 1) in vec4 a_color; \n"
"out vec4 v_color; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_color = a_color; \n"
"} \n";
/**
* Fragment shader.
*/
const char FRAGMENT_SHADER[] = "#version 300 es\n"
"precision mediump float; \n"
"in vec4 v_color; \n"
"out vec4 fragColor; \n"
"void main() \n"
"{ \n"
" fragColor = v_color; \n"
"} \n";
/**
* Background color #f4f4f4.
*/
const GLfloat BACKGROUND_COLOR[] = {244.0f / 255, 244.0f / 255, 244.0f / 255, 1.0f};
/**
* Draw color #7E8FFB.
*/
const GLfloat DRAW_COLOR[] = {126.0f / 255, 143.0f / 255, 251.0f / 255, 1.0f};
/**
* Change color #92D6CC.
*/
const GLfloat CHANGE_COLOR[] = {146.0f / 255, 214.0f / 255, 204.0f / 255, 1.0f};
/**
* Background area.
*/
const GLfloat BACKGROUND_RECTANGLE_VERTICES[] = {
-1.0f, 1.0f,
1.0f, 1.0f,
1.0f, -1.0f,
-1.0f, -1.0f};
/**
* Get context parameter count.
*/
const size_t GET_CONTEXT_PARAM_CNT = 1;
/**
* Fifty percent.
*/
const float FIFTY_PERCENT = 0.5;
/**
* Pointer size.
*/
const GLint POINTER_SIZE = 2;
/**
* Triangle fan size.
*/
const GLsizei TRIANGLE_FAN_SIZE = 4;
/**
* Egl red size default.
*/
const int EGL_RED_SIZE_DEFAULT = 8;
/**
* Egl green size default.
*/
const int EGL_GREEN_SIZE_DEFAULT = 8;
/**
* Egl blue size default.
*/
const int EGL_BLUE_SIZE_DEFAULT = 8;
/**
* Egl alpha size default.
*/
const int EGL_ALPHA_SIZE_DEFAULT = 8;
/**
* Default x position.
*/
const int DEFAULT_X_POSITION = 0;
/**
* Default y position.
*/
const int DEFAULT_Y_POSITION = 0;
/**
* Gl red default.
*/
const GLfloat GL_RED_DEFAULT = 0.0;
/**
* Gl green default.
*/
const GLfloat GL_GREEN_DEFAULT = 0.0;
/**
* Gl blue default.
*/
const GLfloat GL_BLUE_DEFAULT = 0.0;
/**
* Gl alpha default.
*/
const GLfloat GL_ALPHA_DEFAULT = 1.0;
/**
* Program error.
*/
const GLuint PROGRAM_ERROR = 0;
/**
* Shape vertices size.
*/
const int SHAPE_VERTICES_SIZE = 8;
/**
* Position handle name.
*/
const char POSITION_NAME[] = "a_position";
/**
* Position error.
*/
const GLint POSITION_ERROR = -1;
/**
* Config attribute list.
*/
const EGLint ATTRIB_LIST[] = {
// Key,value.
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, EGL_RED_SIZE_DEFAULT,
EGL_GREEN_SIZE, EGL_GREEN_SIZE_DEFAULT,
EGL_BLUE_SIZE, EGL_BLUE_SIZE_DEFAULT,
EGL_ALPHA_SIZE, EGL_ALPHA_SIZE_DEFAULT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
// End.
EGL_NONE};
/**
* Context attributes.
*/
const EGLint CONTEXT_ATTRIBS[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE};
} // namespace
bool EGLCore::EglContextInit(void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "EGLCore", "EglContextInit execute");
eglWindow_ = static_cast<EGLNativeWindowType>(window);
// Init display.
eglDisplay_ = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (eglDisplay_ == EGL_NO_DISPLAY) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglGetDisplay: unable to get EGL display");
return false;
}
EGLint majorVersion;
EGLint minorVersion;
if (!eglInitialize(eglDisplay_, &majorVersion, &minorVersion)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglInitialize: unable to get initialize EGL display");
return false;
}
// Select configuration.
const EGLint maxConfigSize = 1;
EGLint numConfigs;
if (!eglChooseConfig(eglDisplay_, ATTRIB_LIST, &eglConfig_, maxConfigSize, &numConfigs)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglChooseConfig: unable to choose configs");
return false;
}
return CreateEnvironment();
}
bool EGLCore::CreateEnvironment()
{
// Create surface.
if (eglWindow_ == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglWindow_ is null");
return false;
}
eglSurface_ = eglCreateWindowSurface(eglDisplay_, eglConfig_, eglWindow_, NULL);
if (eglSurface_ == nullptr) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglCreateWindowSurface: unable to create surface");
return false;
}
// Create context.
eglContext_ = eglCreateContext(eglDisplay_, eglConfig_, EGL_NO_CONTEXT, CONTEXT_ATTRIBS);
if (!eglMakeCurrent(eglDisplay_, eglSurface_, eglSurface_, eglContext_)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglMakeCurrent failed");
return false;
}
// Create program.
program_ = CreateProgram(VERTEX_SHADER, FRAGMENT_SHADER);
if (program_ == PROGRAM_ERROR) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "CreateProgram: unable to create program");
return false;
}
return true;
}
void EGLCore::Background()
{
GLint position = PrepareDraw();
if (position == POSITION_ERROR) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Background get position failed");
return;
}
if (!ExecuteDraw(position, BACKGROUND_COLOR,
BACKGROUND_RECTANGLE_VERTICES, sizeof(BACKGROUND_RECTANGLE_VERTICES))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Background execute draw failed");
return;
}
if (!FinishDraw()) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Background FinishDraw failed");
return;
}
}
void EGLCore::Draw(int& hasDraw)
{
flag_ = false;
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "EGLCore", "Draw");
GLint position = PrepareDraw();
if (position == POSITION_ERROR) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw get position failed");
return;
}
if (!ExecuteDraw(position, BACKGROUND_COLOR,
BACKGROUND_RECTANGLE_VERTICES, sizeof(BACKGROUND_RECTANGLE_VERTICES))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw background failed");
return;
}
// Divided into five quadrilaterals and calculate one of the quadrilateral's Vertices
GLfloat rotateX = 0;
GLfloat rotateY = FIFTY_PERCENT * height_;
GLfloat centerX = 0;
// Convert DEG(54° & 18°) to RAD
GLfloat centerY = -rotateY * (M_PI / 180 * 54) * (M_PI / 180 * 18);
// Convert DEG(18°) to RAD
GLfloat leftX = -rotateY * (M_PI / 180 * 18);
GLfloat leftY = 0;
// Convert DEG(18°) to RAD
GLfloat rightX = rotateY * (M_PI / 180 * 18);
GLfloat rightY = 0;
const GLfloat shapeVertices[] = { centerX / width_, centerY / height_, leftX / width_, leftY / height_,
rotateX / width_, rotateY / height_, rightX / width_, rightY / height_ };
if (!ExecuteDrawStar(position, DRAW_COLOR, shapeVertices, sizeof(shapeVertices))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw shape failed");
return;
}
// Convert DEG(72°) to RAD
GLfloat rad = M_PI / 180 * 72;
// Rotate four times
for (int i = 0; i < NUM_4; ++i) {
Rotate2d(centerX, centerY, &rotateX, &rotateY, rad);
Rotate2d(centerX, centerY, &leftX, &leftY, rad);
Rotate2d(centerX, centerY, &rightX, &rightY, rad);
const GLfloat shapeVertices[] = { centerX / width_, centerY / height_, leftX / width_, leftY / height_,
rotateX / width_, rotateY / height_, rightX / width_, rightY / height_ };
if (!ExecuteDrawStar(position, DRAW_COLOR, shapeVertices, sizeof(shapeVertices))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw shape failed");
return;
}
}
if (!FinishDraw()) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw FinishDraw failed");
return;
}
hasDraw = 1;
flag_ = true;
}
void EGLCore::ChangeColor(int& hasChangeColor)
{
if (!flag_) {
return;
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "EGLCore", "ChangeColor");
GLint position = PrepareDraw();
if (position == POSITION_ERROR) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ChangeColor get position failed");
return;
}
if (!ExecuteDraw(position, BACKGROUND_COLOR,
BACKGROUND_RECTANGLE_VERTICES, sizeof(BACKGROUND_RECTANGLE_VERTICES))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ChangeColor execute draw background failed");
return;
}
// Divided into five quadrilaterals and calculate one of the quadrilateral's Vertices
GLfloat rotateX = 0;
GLfloat rotateY = FIFTY_PERCENT * height_;
GLfloat centerX = 0;
// Convert DEG(54° & 18°) to RAD
GLfloat centerY = -rotateY * (M_PI / 180 * 54) * (M_PI / 180 * 18);
// Convert DEG(18°) to RAD
GLfloat leftX = -rotateY * (M_PI / 180 * 18);
GLfloat leftY = 0;
// Convert DEG(18°) to RAD
GLfloat rightX = rotateY * (M_PI / 180 * 18);
GLfloat rightY = 0;
const GLfloat shapeVertices[] = { centerX / width_, centerY / height_, leftX / width_, leftY / height_,
rotateX / width_, rotateY / height_, rightX / width_, rightY / height_ };
if (!ExecuteDrawNewStar(0, CHANGE_COLOR, shapeVertices, sizeof(shapeVertices))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw shape failed");
return;
}
// Convert DEG(72°) to RAD
GLfloat rad = M_PI / 180 * 72;
// Rotate four times
for (int i = 0; i < NUM_4; ++i) {
Rotate2d(centerX, centerY, &rotateX, &rotateY, rad);
Rotate2d(centerX, centerY, &leftX, &leftY, rad);
Rotate2d(centerX, centerY, &rightX, &rightY, rad);
const GLfloat shapeVertices[] = { centerX / width_, centerY / height_, leftX / width_, leftY / height_,
rotateX / width_, rotateY / height_, rightX / width_, rightY / height_ };
if (!ExecuteDrawNewStar(position, CHANGE_COLOR, shapeVertices, sizeof(shapeVertices))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Draw execute draw shape failed");
return;
}
}
if (!FinishDraw()) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ChangeColor FinishDraw failed");
}
hasChangeColor = 1;
}
GLint EGLCore::PrepareDraw()
{
if ((eglDisplay_ == nullptr) || (eglSurface_ == nullptr) || (eglContext_ == nullptr) ||
(!eglMakeCurrent(eglDisplay_, eglSurface_, eglSurface_, eglContext_))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "PrepareDraw: param error");
return POSITION_ERROR;
}
// The gl function has no return value.
glViewport(DEFAULT_X_POSITION, DEFAULT_Y_POSITION, width_, height_);
glClearColor(GL_RED_DEFAULT, GL_GREEN_DEFAULT, GL_BLUE_DEFAULT, GL_ALPHA_DEFAULT);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program_);
return glGetAttribLocation(program_, POSITION_NAME);
}
bool EGLCore::ExecuteDraw(GLint position, const GLfloat* color, const GLfloat shapeVertices[], unsigned long vertSize)
{
if ((position > 0) || (color == nullptr) || (vertSize / sizeof(shapeVertices[0])) != SHAPE_VERTICES_SIZE) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ExecuteDraw: param error");
return false;
}
// The gl function has no return value.
glVertexAttribPointer(position, POINTER_SIZE, GL_FLOAT, GL_FALSE, 0, shapeVertices);
glEnableVertexAttribArray(position);
glVertexAttrib4fv(1, color);
glDrawArrays(GL_TRIANGLE_FAN, 0, TRIANGLE_FAN_SIZE);
glDisableVertexAttribArray(position);
return true;
}
bool EGLCore::ExecuteDrawStar(
GLint position, const GLfloat* color, const GLfloat shapeVertices[], unsigned long vertSize)
{
if ((position > 0) || (color == nullptr) || (vertSize / sizeof(shapeVertices[0])) != SHAPE_VERTICES_SIZE) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ExecuteDraw: param error");
return false;
}
// The gl function has no return value.
glVertexAttribPointer(position, POINTER_SIZE, GL_FLOAT, GL_FALSE, 0, shapeVertices);
glVertexAttribPointer(1, POINTER_SIZE, GL_FLOAT, GL_FALSE, 0, color);
glEnableVertexAttribArray(position);
glEnableVertexAttribArray(1);
glVertexAttrib4fv(1, color);
glDrawArrays(GL_TRIANGLE_FAN, 0, TRIANGLE_FAN_SIZE);
glDisableVertexAttribArray(position);
glDisableVertexAttribArray(1);
return true;
}
bool EGLCore::ExecuteDrawNewStar(
GLint position, const GLfloat* color, const GLfloat shapeVertices[], unsigned long vertSize)
{
if ((position > 0) || (color == nullptr) || (vertSize / sizeof(shapeVertices[0])) != SHAPE_VERTICES_SIZE) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "ExecuteDraw: param error");
return false;
}
// The gl function has no return value.
glVertexAttribPointer(position, POINTER_SIZE, GL_FLOAT, GL_FALSE, 0, shapeVertices);
glEnableVertexAttribArray(position);
glVertexAttrib4fv(1, color);
glDrawArrays(GL_TRIANGLE_FAN, 0, TRIANGLE_FAN_SIZE);
glDisableVertexAttribArray(position);
return true;
}
void EGLCore::Rotate2d(GLfloat centerX, GLfloat centerY, GLfloat* rotateX, GLfloat* rotateY, GLfloat theta)
{
GLfloat tempX = cos(theta) * (*rotateX - centerX) - sin(theta) * (*rotateY - centerY);
GLfloat tempY = sin(theta) * (*rotateX - centerX) + cos(theta) * (*rotateY - centerY);
*rotateX = tempX + centerX;
*rotateY = tempY + centerY;
}
bool EGLCore::FinishDraw()
{
// The gl function has no return value.
glFlush();
glFinish();
return eglSwapBuffers(eglDisplay_, eglSurface_);
}
GLuint EGLCore::LoadShader(GLenum type, const char* shaderSrc)
{
if ((type <= 0) || (shaderSrc == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "glCreateShader type or shaderSrc error");
return PROGRAM_ERROR;
}
GLuint shader = glCreateShader(type);
if (shader == 0) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "glCreateShader unable to load shader");
return PROGRAM_ERROR;
}
// The gl function has no return value.
glShaderSource(shader, 1, &shaderSrc, nullptr);
glCompileShader(shader);
GLint compiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (compiled != 0) {
return shader;
}
GLint infoLen = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen <= 1) {
glDeleteShader(shader);
return PROGRAM_ERROR;
}
char* infoLog = (char*)malloc(sizeof(char) * (infoLen + 1));
if (infoLog != nullptr) {
memset(infoLog, 0, infoLen + 1);
glGetShaderInfoLog(shader, infoLen, nullptr, infoLog);
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "glCompileShader error = %s", infoLog);
free(infoLog);
infoLog = nullptr;
}
glDeleteShader(shader);
return PROGRAM_ERROR;
}
GLuint EGLCore::CreateProgram(const char* vertexShader, const char* fragShader)
{
if ((vertexShader == nullptr) || (fragShader == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "createProgram: vertexShader or fragShader is null");
return PROGRAM_ERROR;
}
GLuint vertex = LoadShader(GL_VERTEX_SHADER, vertexShader);
if (vertex == PROGRAM_ERROR) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "createProgram vertex error");
return PROGRAM_ERROR;
}
GLuint fragment = LoadShader(GL_FRAGMENT_SHADER, fragShader);
if (fragment == PROGRAM_ERROR) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "createProgram fragment error");
return PROGRAM_ERROR;
}
GLuint program = glCreateProgram();
if (program == PROGRAM_ERROR) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "createProgram program error");
glDeleteShader(vertex);
glDeleteShader(fragment);
return PROGRAM_ERROR;
}
// The gl function has no return value.
glAttachShader(program, vertex);
glAttachShader(program, fragment);
glLinkProgram(program);
GLint linked;
glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (linked != 0) {
glDeleteShader(vertex);
glDeleteShader(fragment);
return program;
}
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "createProgram linked error");
GLint infoLen = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen > 1) {
char* infoLog = (char*)malloc(sizeof(char) * (infoLen + 1));
memset(infoLog, 0, infoLen + 1);
glGetProgramInfoLog(program, infoLen, nullptr, infoLog);
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "glLinkProgram error = %s", infoLog);
free(infoLog);
infoLog = nullptr;
}
glDeleteShader(vertex);
glDeleteShader(fragment);
glDeleteProgram(program);
return PROGRAM_ERROR;
}
void EGLCore::UpdateSize(int width, int height)
{
width_ = width;
height_ = height;
if (width_ > 0) {
widthPercent_ = FIFTY_PERCENT * height_ / width_;
}
}
void EGLCore::Release()
{
if ((eglDisplay_ == nullptr) || (eglSurface_ == nullptr) || (!eglDestroySurface(eglDisplay_, eglSurface_))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Release eglDestroySurface failed");
}
if ((eglDisplay_ == nullptr) || (eglContext_ == nullptr) || (!eglDestroyContext(eglDisplay_, eglContext_))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Release eglDestroyContext failed");
}
if ((eglDisplay_ == nullptr) || (!eglTerminate(eglDisplay_))) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "Release eglTerminate failed");
}
}
} // namespace NativeXComponentSample

View File

@ -0,0 +1,59 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVE_XCOMPONENT_EGL_CORE_H
#define NATIVE_XCOMPONENT_EGL_CORE_H
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
namespace NativeXComponentSample {
class EGLCore {
public:
explicit EGLCore() {};
~EGLCore() {}
bool EglContextInit(void* window);
bool CreateEnvironment();
void Draw(int& hasDraw);
void Background();
void ChangeColor(int& hasChangeColor);
void Release();
void UpdateSize(int width, int height);
private:
GLuint LoadShader(GLenum type, const char* shaderSrc);
GLuint CreateProgram(const char* vertexShader, const char* fragShader);
GLint PrepareDraw();
bool ExecuteDraw(GLint position, const GLfloat* color, const GLfloat shapeVertices[], unsigned long vertSize);
bool ExecuteDrawStar(GLint position, const GLfloat* color, const GLfloat shapeVertices[], unsigned long vertSize);
bool ExecuteDrawNewStar(GLint position, const GLfloat* color,
const GLfloat shapeVertices[], unsigned long vertSize);
void Rotate2d(GLfloat centerX, GLfloat centerY, GLfloat* rotateX, GLfloat* rotateY, GLfloat theta);
bool FinishDraw();
private:
EGLNativeWindowType eglWindow_;
EGLDisplay eglDisplay_ = EGL_NO_DISPLAY;
EGLConfig eglConfig_ = EGL_NO_CONFIG_KHR;
EGLSurface eglSurface_ = EGL_NO_SURFACE;
EGLContext eglContext_ = EGL_NO_CONTEXT;
GLuint program_;
bool flag_ = false;
int width_;
int height_;
GLfloat widthPercent_;
};
} // namespace NativeXComponentSample
#endif // NATIVE_XCOMPONENT_EGL_CORE_H

View File

@ -0,0 +1,62 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdint>
#include <js_native_api_types.h>
#include "plugin_render.h"
namespace NativeXComponentSample {
PluginRender::PluginRender(int64_t& id)
{
this->id_ = id;
this->eglCore_ = new EGLCore();
hasDraw_ = 0;
hasChangeColor_ = 0;
}
void PluginRender::ChangeColor()
{
eglCore_->ChangeColor(hasChangeColor_);
}
void PluginRender::DrawPattern()
{
eglCore_->Draw(hasDraw_);
}
void PluginRender::InitNativeWindow(OHNativeWindow *window)
{
eglCore_->EglContextInit(window);
}
void PluginRender::UpdateNativeWindowSize(int width, int height)
{
eglCore_->UpdateSize(width, height);
if (!hasChangeColor_ && !hasDraw_) {
eglCore_->Background();
}
}
int32_t PluginRender::HasDraw()
{
return hasDraw_;
}
int32_t PluginRender::HasChangedColor()
{
return hasChangeColor_;
}
} // namespace NativeXComponentSample

View File

@ -0,0 +1,47 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVE_XCOMPONENT_PLUGIN_RENDER_H
#define NATIVE_XCOMPONENT_PLUGIN_RENDER_H
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <native_window/external_window.h>
#include "egl_core.h"
namespace NativeXComponentSample {
class PluginRender {
public:
explicit PluginRender(int64_t& id);
~PluginRender()
{
if (eglCore_ != nullptr) {
eglCore_->Release();
delete eglCore_;
eglCore_ = nullptr;
}
}
void ChangeColor();
void DrawPattern();
int32_t HasDraw();
int32_t HasChangedColor();
void InitNativeWindow(OHNativeWindow* window);
void UpdateNativeWindowSize(int width, int height);
private:
EGLCore* eglCore_;
int64_t id_;
int32_t hasDraw_;
int32_t hasChangeColor_;
};
} // namespace NativeXComponentSample
#endif // NATIVE_XCOMPONENT_PLUGIN_RENDER_H

View File

@ -1,24 +1,24 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
type XComponentContextStatus = {
hasDraw: boolean,
hasChangeColor: boolean,
};
export const SetSurfaceId: (id: BigInt) => any;
export const ChangeSurface: (id: BigInt, w: number, h: number) =>any;
export const DrawPattern: (id: BigInt) => any;
export const GetXComponentStatus: (id: BigInt) => XComponentContextStatus
export const ChangeColor: (id: BigInt) => any;
export const DestroySurface: (id: BigInt) => any;
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
type XComponentContextStatus = {
hasDraw: boolean,
hasChangeColor: boolean,
};
export const SetSurfaceId: (id: BigInt) => any;
export const ChangeSurface: (id: BigInt, w: number, h: number) =>any;
export const DrawPattern: (id: BigInt) => any;
export const GetXComponentStatus: (id: BigInt) => XComponentContextStatus
export const ChangeColor: (id: BigInt) => any;
export const DestroySurface: (id: BigInt) => any;

View File

@ -1,6 +1,6 @@
{
"name": "libnativerender.so",
"types": "./Index.d.ts",
"version": "",
"description": "Please describe the basic information."
{
"name": "libnativerender.so",
"types": "./Index.d.ts",
"version": "",
"description": "Please describe the basic information."
}

View File

@ -1,56 +1,56 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
}
onDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
}
};
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
}
onDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
}
};

View File

@ -0,0 +1,106 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import nativeRender from 'libnativerender.so';
class MyXComponentController extends XComponentController{
onSurfaceCreated(surfaceId: string): void {
console.log(`onSurfaceCreated surfaceId: ${surfaceId}`);
nativeRender.SetSurfaceId(BigInt(surfaceId));
}
onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void {
console.log(`onSurfaceChanged surfaceId: ${surfaceId}, rect: ${JSON.stringify(rect)}}`);
nativeRender.ChangeSurface(BigInt(surfaceId), rect.surfaceWidth, rect.surfaceHeight);
}
onSurfaceDestroyed(surfaceId: string): void {
console.log(`onSurfaceDestroyed surfaceId: ${surfaceId}`);
nativeRender.DestroySurface(BigInt(surfaceId));
}
}
@Entry
@Component
struct Index {
@State currentStatus: string = "index";
xComponentController: XComponentController = new MyXComponentController();
build() {
Column() {
Row() {
Text('Native XComponent Sample')
.fontSize('24fp')
.fontWeight(500)
.margin({
left: 24,
top: 12
})
}
.margin({ top: 24 })
.width('100%')
.height(56)
Column({ space: 10 }) {
XComponent({
type: XComponentType.SURFACE,
controller: this.xComponentController
})
Text(this.currentStatus)
.fontSize('24fp')
.fontWeight(500)
}
.onClick(() => {
let surfaceId = this.xComponentController.getXComponentSurfaceId();
nativeRender.ChangeColor(BigInt(surfaceId));
let hasChangeColor: boolean = false;
if (nativeRender.GetXComponentStatus(BigInt(surfaceId))) {
hasChangeColor = nativeRender.GetXComponentStatus(BigInt(surfaceId)).hasChangeColor;
}
if (hasChangeColor) {
this.currentStatus = "change color";
}
})
.margin({
top: 27,
left: 12,
right: 12
})
.height('40%')
.width('90%')
Row() {
Button('Draw Star')
.fontSize('16fp')
.fontWeight(500)
.margin({ bottom: 24 })
.onClick(() => {
let surfaceId = this.xComponentController.getXComponentSurfaceId();
nativeRender.DrawPattern(BigInt(surfaceId));
let hasDraw: boolean = false;
if (nativeRender.GetXComponentStatus(BigInt(surfaceId))) {
hasDraw = nativeRender.GetXComponentStatus(BigInt(surfaceId)).hasDraw;
}
if (hasDraw) {
this.currentStatus = "draw star";
}
})
.width('53.6%')
.height(40)
}
.width('100%')
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Bottom)
.layoutWeight(1)
}
.width('100%')
.height('100%')
}
}

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"default",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
]
}
}

View File

@ -0,0 +1,8 @@
{
"color": [
{
"name": "start_window_background",
"value": "#FFFFFF"
}
]
}

View File

@ -0,0 +1,16 @@
{
"string": [
{
"name": "module_desc",
"value": "module description"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "label"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

View File

@ -0,0 +1,5 @@
{
"src": [
"pages/Index"
]
}

View File

@ -0,0 +1,16 @@
{
"string": [
{
"name": "module_desc",
"value": "module description"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "label"
}
]
}

View File

@ -0,0 +1,16 @@
{
"string": [
{
"name": "module_desc",
"value": "模块描述"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "label"
}
]
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import hilog from '@ohos.hilog';
import TestRunner from '@ohos.application.testRunner';
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let abilityDelegator = undefined;
let abilityDelegatorArguments = undefined;
async function onAbilityCreateCallback() {
hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback');
}
async function addAbilityMonitorCallback(err: any) {
hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? '');
}
export default class OpenHarmonyTestRunner implements TestRunner {
constructor() {
}
onPrepare() {
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare ');
}
async onRun() {
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run');
abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments();
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility';
let lMonitor = {
abilityName: testAbilityName,
onAbilityCreate: onAbilityCreateCallback,
};
abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback);
let cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName;
let debug = abilityDelegatorArguments.parameters['-D'];
if (debug == 'true') {
cmd += ' -D';
}
hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd);
abilityDelegator.executeShellCommand(cmd,
(err: any, d: any) => {
hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? '');
hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? '');
hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? '');
});
hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end');
}
}

View File

@ -0,0 +1,20 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import abilityTest from './XComponentAbility.test'
export default function testsuite() {
abilityTest()
}

View File

@ -0,0 +1,74 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
import { describe, it, expect } from '@ohos/hypium';
import { Driver, ON } from '@ohos.UiTest';
const TAG = '[Sample_NDK_XComponent]';
export default function abilityTest() {
describe('ActsAbilityTest', () => {
/**
* 打开应用
*/
it('StartAbility_001', 0, async (done: Function) => {
console.info(TAG, 'StartAbility_001 begin');
let driver = Driver.create();
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
try {
await abilityDelegator.startAbility({
bundleName: 'com.sample.xcomponent',
abilityName: 'EntryAbility'
});
} catch (exception) {
console.info(TAG, `StartAbility_001 exception = ${JSON.stringify(exception)}`);
expect().assertFail();
}
await driver.delayMs(1000);
await driver.assertComponentExist(ON.text('Draw Star'));
done();
console.info(TAG, 'StartAbility_001 end');
})
/**
* 点击按钮绘制图形之后点击XComponent改变颜色
*/
it('DrawShape_001', 2, async () => {
console.info(TAG, 'CreateFiles_001 begin');
let driver = Driver.create();
// 判断XComponent onLoad回调执行成功
await driver.assertComponentExist(ON.text('index'));
// 判断是否有按键
await driver.assertComponentExist(ON.text('Draw Star'));
let drawStarBtn = await driver.findComponent(ON.text('Draw Star'));
// 点击'Draw Star'按钮
await drawStarBtn.click();
await driver.delayMs(1000);
// 判断drawPattern方法已执行
await driver.assertComponentExist(ON.text('draw star'));
// 判断是否有XComponent组件
let xcomponent = await driver.findComponent(ON.id('xcomponent'));
// 点击XComponent组件
await xcomponent.click();
await driver.delayMs(1000);
// 判断touch回调已执行
await driver.assertComponentExist(ON.text('change color'));
console.info(TAG, 'DrawShape_001 end');
})
})
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
import hilog from '@ohos.hilog';
import { Hypium } from '@ohos/hypium';
import testsuite from '../test/List.test';
import window from '@ohos.window';
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
export default class TestAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate');
hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');
hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? '');
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let abilityDelegatorArguments: AbilityDelegatorRegistry.AbilityDelegatorArgs = AbilityDelegatorRegistry.getArguments();
hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!');
Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite)
}
onDestroy() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage) {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageCreate');
windowStage.loadContent('testability/pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s',
JSON.stringify(data) ?? '');
});
}
onWindowStageDestroy() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageDestroy');
}
onForeground() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onForeground');
}
onBackground() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onBackground');
}
}

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import hilog from '@ohos.hilog';
@Entry
@Component
struct Index {
aboutToAppear() {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility index aboutToAppear');
}
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('next page')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('35%')
.height('5%')
.onClick(() => {
})
}
.width('100%')
}
.height('100%')
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
"module": {
"name": "entry_test",
"type": "feature",
"description": "$string:module_test_desc",
"mainElement": "TestAbility",
"deviceTypes": [
"default"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:test_pages",
"abilities": [
{
"name": "TestAbility",
"srcEntry": "./ets/testability/TestAbility.ets",
"description": "$string:TestAbility_desc",
"icon": "$media:icon",
"label": "$string:TestAbility_label",
"exported": true,
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"skills": [
{
"actions": [
"action.system.home"
],
"entities": [
"entity.system.home"
]
}
]
}
]
}
}

View File

@ -0,0 +1,8 @@
{
"color": [
{
"name": "start_window_background",
"value": "#FFFFFF"
}
]
}

View File

@ -0,0 +1,16 @@
{
"string": [
{
"name": "module_test_desc",
"value": "test ability description"
},
{
"name": "TestAbility_desc",
"value": "the test ability"
},
{
"name": "TestAbility_label",
"value": "test label"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

View File

@ -0,0 +1,5 @@
{
"src": [
"testability/pages/Index"
]
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
{
"hvigorVersion": "4.1.2",
"dependencies": {
"@ohos/hvigor-ohos-plugin": "4.1.2"
},
"execution": {
// "analyze": "default", /* Define the build analyze mode. Value: [ "default" | "verbose" | false ]. Default: "default" */
// "daemon": true, /* Enable daemon compilation. Value: [ true | false ]. Default: true */
// "incremental": true, /* Enable incremental compilation. Value: [ true | false ]. Default: true */
// "parallel": true, /* Enable parallel compilation. Value: [ true | false ]. Default: true */
// "typeCheck": false, /* Enable typeCheck. Value: [ true | false ]. Default: false */
},
"logging": {
// "level": "info" /* Define the log level. Value: [ "debug" | "info" | "warn" | "error" ]. Default: "info" */
},
"debugging": {
// "stacktrace": false /* Disable stacktrace compilation. Value: [ true | false ]. Default: false */
},
"nodeOptions": {
// "maxOldSpaceSize": 4096 /* Enable nodeOptions maxOldSpaceSize compilation. Unit M. Used for the daemon process */
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,6 @@
import { appTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}

View File

@ -0,0 +1,54 @@
#!/bin/bash
# ----------------------------------------------------------------------------
# Hvigor startup script, version 1.0.0
#
# Required ENV vars:
# ------------------
# NODE_HOME - location of a Node home dir
# or
# Add /usr/local/nodejs/bin to the PATH environment variable
# ----------------------------------------------------------------------------
HVIGOR_APP_HOME="`pwd -P`"
HVIGOR_WRAPPER_SCRIPT=${HVIGOR_APP_HOME}/hvigor/hvigor-wrapper.js
#NODE_OPTS="--max-old-space-size=4096"
fail() {
echo "$*"
exit 1
}
set_executable_node() {
EXECUTABLE_NODE="${NODE_HOME}/bin/node"
if [ -x "$EXECUTABLE_NODE" ]; then
return
fi
EXECUTABLE_NODE="${NODE_HOME}/node"
if [ -x "$EXECUTABLE_NODE" ]; then
return
fi
fail "ERROR: NODE_HOME is set to an invalid directory,check $NODE_HOME\n\nPlease set NODE_HOME in your environment to the location where your nodejs installed"
}
# Determine node to start hvigor wrapper script
if [ -n "${NODE_HOME}" ]; then
set_executable_node
else
EXECUTABLE_NODE="node"
command -v ${EXECUTABLE_NODE} &> /dev/null || fail "ERROR: NODE_HOME not set and 'node' command not found"
fi
# Check hvigor wrapper script
if [ ! -r "$HVIGOR_WRAPPER_SCRIPT" ]; then
fail "ERROR: Couldn't find hvigor/hvigor-wrapper.js in ${HVIGOR_APP_HOME}"
fi
if [ -z "${NODE_OPTS}" ]; then
NODE_OPTS="--"
fi
# start hvigor-wrapper script
exec "${EXECUTABLE_NODE}" "${NODE_OPTS}" \
"${HVIGOR_WRAPPER_SCRIPT}" "$@"

View File

@ -0,0 +1,54 @@
@rem
@rem ----------------------------------------------------------------------------
@rem Hvigor startup script for Windows, version 1.0.0
@rem
@rem Required ENV vars:
@rem ------------------
@rem NODE_HOME - location of a Node home dir
@rem or
@rem Add %NODE_HOME%/bin to the PATH environment variable
@rem ----------------------------------------------------------------------------
@rem
@echo off
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
set WRAPPER_MODULE_PATH=%APP_HOME%\hvigor\hvigor-wrapper.js
set NODE_EXE=node.exe
@rem set NODE_OPTS="--max-old-space-size=4096"
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
if not defined NODE_OPTS set NODE_OPTS="--"
@rem Find node.exe
if defined NODE_HOME (
set NODE_HOME=%NODE_HOME:"=%
set NODE_EXE_PATH=%NODE_HOME%/%NODE_EXE%
)
%NODE_EXE% --version >NUL 2>&1
if "%ERRORLEVEL%" == "0" (
"%NODE_EXE%" "%NODE_OPTS%" "%WRAPPER_MODULE_PATH%" %*
) else if exist "%NODE_EXE_PATH%" (
"%NODE_EXE%" "%NODE_OPTS%" "%WRAPPER_MODULE_PATH%" %*
) else (
echo.
echo ERROR: NODE_HOME is not set and no 'node' command could be found in your PATH.
echo.
echo Please set the NODE_HOME variable in your environment to match the
echo location of your NodeJs installation.
)
if "%ERRORLEVEL%" == "0" (
if "%OS%" == "Windows_NT" endlocal
) else (
exit /b %ERRORLEVEL%
)

View File

@ -0,0 +1,14 @@
{
"name": "ndkxcomponentv2",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "",
"author": "",
"license": "",
"dependencies": {
},
"devDependencies": {
"@ohos/hypium": "1.0.16",
"@ohos/hamock": "1.0.0"
}
}

View File

@ -0,0 +1,9 @@
# NdkXComponent 测试用例归档
## 用例表
|测试功能|预置条件|输入|预期输出|是否自动|测试结果|
|--------------------------------|--------------------------------|--------------------------------|--------------------------------|--------------------------------|--------------------------------|
| 拉起应用 | 设备正常运行 | |成功拉起应用|是| Pass |
| 绘制图形 | 位于首页 | 1、点击**Draw Star** | 1、页面显示出一个五角星 | 是 | Pass |
| 响应触摸事件 | 位于首页,且已经显示了五角星 | 1、点击XComponent区域灰色背景部分 | 1、页面中的五角星改变颜色 | 是 | Pass |

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View File

@ -13,7 +13,7 @@
3. 点击页面底部“Draw Text”按钮页面将绘制“Hello World Drawing”。
> **说明**
> 本示例XComponent接口使用方法已停止演进推荐使用方法请参考[XComponent示例](../XComponent/README_zh.md)。
> 本示例XComponent接口使用方法已停止演进推荐使用方法请参考[ArkTSXComponent示例](../ArkTSXComponent/README_zh.md)。
### 效果预览
| 主页 | 绘制五角星 | 绘制文字 |

View File

@ -5,7 +5,7 @@
本示例中主要介绍开发者在利用[Native XComponent](https://docs.openharmony.cn/pages/v4.1/zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md)来获取[NativeWindow](https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/reference/native-apis/_native_window.md)实例,通过数据填充改变矩形框颜色。并提供从[NativeImage](https://docs.openharmony.cn/pages/v4.1/zh-cn/application-dev/reference/apis-arkgraphics2d/_o_h___native_image.md)中获取NativeWindow进行buffer轮转的案例通过NativeWindow生产buffer来触发NativeImage的可用帧回调。
> **说明**
> 本示例XComponent接口使用方法已停止演进推荐使用方法请参考[XComponent示例](../XComponent/README_zh.md)。
> 本示例XComponent接口使用方法已停止演进推荐使用方法请参考[ArkTSXComponent示例](../ArkTSXComponent/README_zh.md)。
### 效果预览
| 主页 | 改变矩形框颜色 | 生产buffer | 获取可用帧回调次数 |

View File

@ -5,7 +5,7 @@
XComponent控件常用于相机预览流的显示和游戏画面的绘制,在OpenHarmony上可以配合Native Window创建OpenGL开发环境并最终将OpenGL绘制的图形显示到XComponent控件。本示例基于"Native C++"模板调用OpenGL(OpenGL ES)图形库相关API绘制3D图形三棱锥并将结果渲染到页面的XComponent控件中进行展示。同时还可以在屏幕上通过触摸滑动手势对三棱锥进行旋转最终得到不同角度的图形并显示到页面。
> **说明**
> 本示例XComponent接口使用方法已停止演进推荐使用方法请参考[XComponent示例](../XComponent/README_zh.md)。
> 本示例XComponent接口使用方法已停止演进推荐使用方法请参考[ArkTSXComponent示例](../ArkTSXComponent/README_zh.md)。
### 效果预览
| 首页 | 滑动屏幕旋转变换 |

View File

@ -11,7 +11,7 @@ XComponent组件作为绘制组件, 可用于满足开发者较为复杂的自
[Vulkan](https://gitee.com/openharmony/docs/tree/master/zh-cn/application-dev/reference/native-lib)接口。
> **说明**
> 本示例XComponent接口使用方法已停止演进推荐使用方法请参考[XComponent示例](../XComponent/README_zh.md)。
> 本示例XComponent接口使用方法已停止演进推荐使用方法请参考[ArkTSXComponent示例](../ArkTSXComponent/README_zh.md)。
### 效果预览
如下图所示, 打开应用, 屏幕中心会绘制一个旋转中的三角形, 可以点击'stop/start'按钮控制三角形的旋转状态。
![image](screenshots/device/sample.png)

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,11 +1,9 @@
# Native XComponent
### 介
###
本示例中主要介绍开发者如何使用Native XComponent接口来获取NativeWindow实例、获取布局/事件信息、注册事件回调并通过OpenGL/EGL实现在页面上绘制形状。功能主要包括点击按钮绘制一个五角星并可以通过点击XComponent区域改变五角星的颜色。
本示例展示了如何在native侧使用ArkUI NDK API创建XComponent组件进行自定义绘制。具体步骤包括创建组件获取NativeXComponent实例注册XComponent生命周期和事件回调通过回调获取NativeWindow后使用OpenGL ES/EGL接口在XComponent组件上进行图形绘制最后在ArkTS层使用ContentSlot站位组件进行挂载显示。功能主要包括点击按钮绘制一个五角星并可以通过点击XComponent区域改变五角星的颜色。
> **说明**
> 本示例已停止演进XComponent使用方法推荐参考[XComponent示例](../XComponent/README_zh.md)。
### 效果预览
| 主页 | 绘制五角星 | 改变颜色 |
@ -36,8 +34,10 @@
│ │ ├──render // 渲染模块
│ │ │ ├──egl_core.cpp
│ │ │ ├──egl_core.h
│ │ │ ├──plugin_render.cpp
│ │ │ └──plugin_render.h
| | ├──types //定义接口文件
│ │ │ ├──libnativenode
│ │ │ │ ├──Index.d.ts
│ │ │ │ ├──oh-package.json5
│ ├──ets // ets代码区
│ │ ├──entryability
│ │ │ └──EntryAbility.ts // 程序入口类
@ -56,27 +56,36 @@
涉及到的相关接口:
| 接口名 | 描述 |
| ------------------------------------------------------------ | ------------------------------------------------------- |
| OH_NativeXComponent_GetXComponentId(OH_NativeXComponent* component, char* id, uint64_t* size) | 获取XComponent的id。 |
| OH_NativeXComponent_GetXComponentSize(OH_NativeXComponent* component, const void* window, uint64_t* width, uint64_t* height) | 获取XComponent持有的surface的大小。 |
| OH_NativeXComponent_GetXComponentOffset(OH_NativeXComponent* component, const void* window, double* x, double* y) | 获取XComponent持有的surface相对窗口左上角的偏移量。 |
| OH_NativeXComponent_GetTouchEvent(OH_NativeXComponent* component, const void* window, OH_NativeXComponent_TouchEvent* touchEvent) | 获取由XComponent触发的触摸事件。 |
| OH_NativeXComponent_GetTouchPointToolType(OH_NativeXComponent* component, uint32_t pointIndex, OH_NativeXComponent_TouchPointToolType* toolType) | 获取XComponent触摸点的工具类型。 |
| OH_NativeXComponent_GetTouchPointTiltX(OH_NativeXComponent* component, uint32_t pointIndex, float* tiltX) | 获取XComponent触摸点处相对X轴的倾斜角度。 |
| OH_NativeXComponent_GetTouchPointTiltY(OH_NativeXComponent* component, uint32_t pointIndex, float* tiltY) | 获取XComponent触摸点处相对Y轴的倾斜角度。 |
| OH_NativeXComponent_GetMouseEvent(OH_NativeXComponent* component, const void* window, OH_NativeXComponent_MouseEvent* mouseEvent) | 获取由XComponent触发的鼠标事件。 |
| OH_NativeXComponent_RegisterCallback(OH_NativeXComponent* component, OH_NativeXComponent_Callback* callback) | 为此OH_NativeXComponent实例注册生命周期和触摸事件回调。 |
| OH_NativeXComponent_RegisterMouseEventCallback(OH_NativeXComponent* component, OH_NativeXComponent_MouseEvent_Callback* callback) | 为此OH_NativeXComponent实例注册鼠标事件回调。 |
| OH_NativeXComponent_RegisterFocusEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册获得焦点事件回调。 |
| OH_NativeXComponent_RegisterKeyEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册按键事件回调。 |
| OH_NativeXComponent_RegisterBlurEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册失去焦点事件回调。 |
| OH_NativeXComponent_GetKeyEvent(OH_NativeXComponent* component, OH_NativeXComponent_KeyEvent** keyEvent) | 获取由XComponent触发的按键事件。 |
| OH_NativeXComponent_GetKeyEventAction(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_KeyAction* action) | 获取按键事件的动作。 |
| OH_NativeXComponent_GetKeyEventCode(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_KeyCode* code) | 获取按键事件的键码值。 |
| OH_NativeXComponent_GetKeyEventSourceType(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_EventSourceType* sourceType) | 获取按键事件的输入源类型。 |
| OH_NativeXComponent_GetKeyEventDeviceId(OH_NativeXComponent_KeyEvent* keyEvent, int64_t* deviceId) | 获取按键事件的设备ID。 |
| OH_NativeXComponent_GetKeyEventTimestamp(OH_NativeXComponent_KeyEvent* keyEvent, int64_t* timestamp) | 获取按键事件的时间戳。 |
| 接口名 | 描述 |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| OH_NativeXComponent_GetXComponentId(OH_NativeXComponent* component, char* id, uint64_t* size) | 获取XComponent的id。 |
| OH_NativeXComponent_GetXComponentSize(OH_NativeXComponent* component, const void* window, uint64_t* width, uint64_t* height) | 获取XComponent持有的surface的大小。 |
| OH_NativeXComponent_GetXComponentOffset(OH_NativeXComponent* component, const void* window, double* x, double* y) | 获取XComponent持有的surface相对窗口左上角的偏移量。 |
| OH_NativeXComponent_GetTouchEvent(OH_NativeXComponent* component, const void* window, OH_NativeXComponent_TouchEvent* touchEvent) | 获取由XComponent触发的触摸事件。 |
| OH_NativeXComponent_GetTouchPointToolType(OH_NativeXComponent* component, uint32_t pointIndex, OH_NativeXComponent_TouchPointToolType* toolType) | 获取XComponent触摸点的工具类型。 |
| OH_NativeXComponent_GetTouchPointTiltX(OH_NativeXComponent* component, uint32_t pointIndex, float* tiltX) | 获取XComponent触摸点处相对X轴的倾斜角度。 |
| OH_NativeXComponent_GetTouchPointTiltY(OH_NativeXComponent* component, uint32_t pointIndex, float* tiltY) | 获取XComponent触摸点处相对Y轴的倾斜角度。 |
| OH_NativeXComponent_GetMouseEvent(OH_NativeXComponent* component, const void* window, OH_NativeXComponent_MouseEvent* mouseEvent) | 获取由XComponent触发的鼠标事件。 |
| OH_NativeXComponent_RegisterCallback(OH_NativeXComponent* component, OH_NativeXComponent_Callback* callback) | 为此OH_NativeXComponent实例注册生命周期和触摸事件回调。 |
| OH_NativeXComponent_RegisterMouseEventCallback(OH_NativeXComponent* component, OH_NativeXComponent_MouseEvent_Callback* callback) | 为此OH_NativeXComponent实例注册鼠标事件回调。 |
| OH_NativeXComponent_RegisterFocusEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册获得焦点事件回调。 |
| OH_NativeXComponent_RegisterKeyEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册按键事件回调。 |
| OH_NativeXComponent_RegisterBlurEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册失去焦点事件回调。 |
| OH_NativeXComponent_GetKeyEvent(OH_NativeXComponent* component, OH_NativeXComponent_KeyEvent** keyEvent) | 获取由XComponent触发的按键事件。 |
| OH_NativeXComponent_GetKeyEventAction(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_KeyAction* action) | 获取按键事件的动作。 |
| OH_NativeXComponent_GetKeyEventCode(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_KeyCode* code) | 获取按键事件的键码值。 |
| OH_NativeXComponent_GetKeyEventSourceType(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_EventSourceType* sourceType) | 获取按键事件的输入源类型。 |
| OH_NativeXComponent_GetKeyEventDeviceId(OH_NativeXComponent_KeyEvent* keyEvent, int64_t* deviceId) | 获取按键事件的设备ID。 |
| OH_NativeXComponent_GetKeyEventTimestamp(OH_NativeXComponent_KeyEvent* keyEvent, int64_t* timestamp) | 获取按键事件的时间戳。 |
| OH_ArkUI_QueryModuleInterfaceByName(ArkUI_NativeAPIVariantKind type, const char* structName) | 获取指定类型的Native模块接口集合。 |
| OH_ArkUI_GetNodeContentFromNapiValue(napi_env env, napi_value value, ArkUI_NodeContentHandle* content) | 获取ArkTS侧创建的NodeContent对象映射到native侧的ArkUI_NodeContentHandle。 |
| OH_ArkUI_NodeContent_SetUserData(ArkUI_NodeContentHandle content, void* userData) | 在NodeContent对象上保存自定义数据。 |
| OH_ArkUI_NodeContentEvent_GetNodeContentHandle(ArkUI_NodeContentEvent* event) | 获取触发事件的NodeContent对象。 |
| OH_ArkUI_NodeContent_GetUserData(ArkUI_NodeContentHandle content) | 获取在NodeContent对象上保存的自定义数据。 |
| OH_ArkUI_NodeContentEvent_GetEventType(ArkUI_NodeContentEvent* event) | 获取触发NodeContent事件的事件类型。 |
| OH_ArkUI_NodeContent_AddNode(ArkUI_NodeContentHandle content, ArkUI_NodeHandle node) | 将一个ArkUI组件节点添加到对应的NodeContent对象下。 |
| OH_ArkUI_NodeContent_RegisterCallback(ArkUI_NodeContentHandle content, ArkUI_NodeContentCallback callback) | 注册NodeContent事件函数。 |
| OH_NativeXComponent_GetNativeXComponent(ArkUI_NodeHandle node) | 基于Native接口创建的组件实例获取OH_NativeXComponent类型的指针。 |
### 相关权限
@ -90,9 +99,9 @@
1. 本示例仅支持标准系统上运行支持设备RK3568
2. 本示例为Stage模型支持API10版本SDKSDK版本号(API Version 10 Release),镜像版本号(4.0 Release)
2. 本示例为Stage模型支持API12版本SDKSDK版本号(API Version 12Release),镜像版本号(5.0 Release)
3. 本示例需要使用DevEco Studio 版本号(4.0 Release)及以上版本才可编译运行
3. 本示例需要使用DevEco Studio 版本号(5.0 Release)及以上版本才可编译运行
### 下载
@ -105,3 +114,4 @@ echo code/BasicFeature/Native/NdkXComponent/ > .git/info/sparse-checkout
git remote add origin https://gitee.com/openharmony/applications_app_samples.git
git pull origin master
```

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -20,8 +20,9 @@
{
"name": "default",
"signingConfig": "default",
"compileSdkVersion": 10,
"compatibleSdkVersion": 10,
"compileSdkVersion": 12,
"compatibleSdkVersion": 12,
"targetSdkVersion": 12,
"runtimeOS": "OpenHarmony"
}
]

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -20,6 +20,7 @@
"path": "./src/main/cpp/CMakeLists.txt",
"arguments": "",
"cppFlags": "",
"abiFilters": ["arm64-v8a", "x86_64", "armeabi-v7a"]
}
},
"targets": [

View File

@ -6,5 +6,7 @@
"description": "Please describe the basic information.",
"main": "",
"version": "1.0.0",
"dependencies": {}
"dependencies": {
"libnativenode.so": "file:./src/main/cpp/types/libnativenode"
}
}

View File

@ -10,9 +10,8 @@ include_directories(
${NATIVERENDER_ROOT_PATH}/include
)
add_library(nativerender SHARED
add_library(nativenode SHARED
render/egl_core.cpp
render/plugin_render.cpp
manager/plugin_manager.cpp
napi_init.cpp
)
@ -65,5 +64,5 @@ find_library(
uv
)
target_link_libraries(nativerender PUBLIC
target_link_libraries(nativenode PUBLIC
${EGL-lib} ${GLES-lib} ${hilog-lib} ${libace-lib} ${libnapi-lib} ${libuv-lib})

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -20,125 +20,318 @@
#include <cstdio>
#include <hilog/log.h>
#include <string>
#include "arkui/native_node.h"
#include "arkui/native_node_napi.h"
#include "arkui/native_interface.h"
#include "../common/common.h"
#define COLUMN_MARGIN 10
#define XC_WIDTH 300
#define XC_HEIGHT 300
#define ARG_CNT 2
namespace NativeXComponentSample {
PluginManager PluginManager::pluginManager_;
OH_NativeXComponent_Callback PluginManager::callback_;
static ArkUI_NativeNodeAPI_1* nodeAPI;
ArkUI_NodeHandle xc;
int32_t PluginManager::hasDraw_ = 0;
int32_t PluginManager::hasChangeColor_ = 0;
static std::string value2String(napi_env env, napi_value value)
{
size_t stringSize = 0;
napi_get_value_string_utf8(env, value, nullptr, 0, &stringSize);
std::string valueString;
valueString.resize(stringSize);
napi_get_value_string_utf8(env, value, &valueString[0], stringSize+1, &stringSize);
return valueString;
}
napi_value PluginManager::GetXComponentStatus(napi_env env, napi_callback_info info)
{
napi_value hasDraw;
napi_value hasChangeColor;
napi_status ret = napi_create_int32(env, hasDraw_, &(hasDraw));
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "GetXComponentStatus", "napi_create_int32 hasDraw_ error");
return nullptr;
}
ret = napi_create_int32(env, hasChangeColor_, &(hasChangeColor));
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "GetXComponentStatus", "napi_create_int32 hasChangeColor_ error");
return nullptr;
}
napi_value obj;
ret = napi_create_object(env, &obj);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "GetXComponentStatus", "napi_create_object error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasDraw", hasDraw);
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "GetXComponentStatus", "napi_set_named_property hasDraw error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasChangeColor", hasChangeColor);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "GetXComponentStatus",
"napi_set_named_property hasChangeColor error");
return nullptr;
}
return obj;
}
napi_value PluginManager::NapiDrawPattern(napi_env env, napi_callback_info info)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginManager", "NapiDrawPattern");
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "NapiDrawPattern: env or info is null");
return nullptr;
}
napi_value thisArg;
if (napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "NapiDrawPattern: napi_get_cb_info fail");
return nullptr;
}
auto *pluginManger = PluginManager::GetInstance();
pluginManger->eglcore_->Draw(hasDraw_);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginManager", "render->eglCore_->Draw() executed");
return nullptr;
}
void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "XComponent_Native", "OnSurfaceCreatedCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "XComponent_Native", "OnSurfaceCreatedCB id=%{public}s",
id.c_str());
auto *pluginManger = PluginManager::GetInstance();
pluginManger->OnSurfaceCreated(component, window);
}
void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "XComponent_Native", "OnSurfaceChangedCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto *pluginManger = PluginManager::GetInstance();
pluginManger->OnSurfaceChanged(component, window);
}
void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceDestroyedCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto *pluginManger = PluginManager::GetInstance();
pluginManger->OnSurfaceDestroyed(component, window);
}
void DispatchTouchEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto *pluginManger = PluginManager::GetInstance();
pluginManger->DispatchTouchEvent(component, window);
}
PluginManager::PluginManager()
{
eglcore_ = new EGLCore();
callback_.OnSurfaceCreated = OnSurfaceCreatedCB;
callback_.OnSurfaceChanged = OnSurfaceChangedCB;
callback_.OnSurfaceDestroyed = OnSurfaceDestroyedCB;
callback_.DispatchTouchEvent = DispatchTouchEventCB;
}
PluginManager::~PluginManager()
{
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "~PluginManager");
nativeXComponentMap_.clear();
if (eglcore_ != nullptr) {
delete eglcore_;
eglcore_ = nullptr;
}
for (auto iter = pluginRenderMap_.begin(); iter != pluginRenderMap_.end(); ++iter) {
for (auto iter = pluginManagerMap_.begin(); iter != pluginManagerMap_.end(); ++iter) {
if (iter->second != nullptr) {
delete iter->second;
iter->second = nullptr;
}
}
pluginRenderMap_.clear();
pluginManagerMap_.clear();
}
napi_value PluginManager::GetContext(napi_env env, napi_callback_info info)
ArkUI_NodeHandle CreateNodeHandle(const std::string &tag)
{
ArkUI_NodeHandle column = nodeAPI->createNode(ARKUI_NODE_COLUMN);
ArkUI_NumberValue value[] = {480};
ArkUI_NumberValue value1[] = {{.u32 = 15}, {.f32 = 15}};
ArkUI_AttributeItem item = {value, 1, "changeSize"};
ArkUI_AttributeItem item1 = {value1, 2};
nodeAPI->setAttribute(column, NODE_WIDTH, &item);
value[0].f32 = COLUMN_MARGIN;
nodeAPI->setAttribute(column, NODE_MARGIN, &item);
xc = nodeAPI->createNode(ARKUI_NODE_XCOMPONENT);
value[0].u32 = ARKUI_XCOMPONENT_TYPE_SURFACE;
nodeAPI->setAttribute(xc, NODE_XCOMPONENT_TYPE, &item);
nodeAPI->setAttribute(xc, NODE_XCOMPONENT_ID, &item);
nodeAPI->setAttribute(xc, NODE_XCOMPONENT_SURFACE_SIZE, &item1);
ArkUI_NumberValue focusable[] = {1};
focusable[0].i32 = 1;
ArkUI_AttributeItem focusableItem = {focusable, 1};
nodeAPI->setAttribute(xc, NODE_FOCUSABLE, &focusableItem);
ArkUI_NumberValue valueSize[] = {480};
ArkUI_AttributeItem itemSize = {valueSize, 1};
valueSize[0].f32 = XC_WIDTH;
nodeAPI->setAttribute(xc, NODE_WIDTH, &itemSize);
valueSize[0].f32 = XC_HEIGHT;
nodeAPI->setAttribute(xc, NODE_HEIGHT, &itemSize);
ArkUI_AttributeItem item2 = {value, 1, "ndkxcomponent"};
nodeAPI->setAttribute(xc, NODE_ID, &item2);
auto *nativeXComponent = OH_NativeXComponent_GetNativeXComponent(xc);
if (!nativeXComponent) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "GetNativeXComponent error");
return column;
}
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "GetNativeXComponent success");
OH_NativeXComponent_RegisterCallback(nativeXComponent, &PluginManager::callback_);
auto typeRet = nodeAPI->getAttribute(xc, NODE_XCOMPONENT_TYPE);
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "xcomponent type: %{public}d",
typeRet->value[0].i32);
auto idRet = nodeAPI->getAttribute(xc, NODE_XCOMPONENT_ID);
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "xcomponent id: %{public}s",
idRet->string);
nodeAPI->addChild(column, xc);
return column;
}
napi_value PluginManager::createNativeNode(napi_env env, napi_callback_info info)
{
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "GetContext env or info is null");
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "CreateNativeNode env or info is null");
return nullptr;
}
size_t argCnt = 1;
napi_value args[1] = { nullptr };
size_t argCnt = 2;
napi_value args[2] = { nullptr, nullptr };
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "GetContext napi_get_cb_info failed");
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "CreateNativeNode napi_get_cb_info failed");
}
if (argCnt != 1) {
if (argCnt != ARG_CNT) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
napi_valuetype valuetype;
if (napi_typeof(env, args[0], &valuetype) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_typeof failed");
return nullptr;
ArkUI_NodeContentHandle nodeContentHandle_ = nullptr;
OH_ArkUI_GetNodeContentFromNapiValue(env, args[0], &nodeContentHandle_);
nodeAPI = reinterpret_cast<ArkUI_NativeNodeAPI_1*>(
OH_ArkUI_QueryModuleInterfaceByName(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1")
);
std::string tag = value2String(env, args[1]);
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "tag=%{public}s", tag.c_str());
int32_t ret = OH_ArkUI_NodeContent_SetUserData(nodeContentHandle_, new std::string(tag));
if (ret != ARKUI_ERROR_CODE_NO_ERROR) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "setUserData failed error=%{public}d", ret);
}
if (valuetype != napi_number) {
napi_throw_type_error(env, NULL, "Wrong type of arguments");
return nullptr;
if (nodeAPI != nullptr && nodeAPI->createNode != nullptr && nodeAPI->addChild != nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"CreateNativeNode tag=%{public}s", tag.c_str());
auto nodeContentEvent = [](ArkUI_NodeContentEvent *event) {
ArkUI_NodeContentHandle handle = OH_ArkUI_NodeContentEvent_GetNodeContentHandle(event);
std::string *userDate = reinterpret_cast<std::string*>(OH_ArkUI_NodeContent_GetUserData(handle));
if (OH_ArkUI_NodeContentEvent_GetEventType(event) == NODE_CONTENT_EVENT_ON_ATTACH_TO_WINDOW) {
ArkUI_NodeHandle testNode;
if (userDate) {
testNode = CreateNodeHandle(*userDate);
delete userDate;
userDate = nullptr;
} else {
testNode = CreateNodeHandle("noUserData");
}
OH_ArkUI_NodeContent_AddNode(handle, testNode);
}
};
OH_ArkUI_NodeContent_RegisterCallback(nodeContentHandle_, nodeContentEvent);
}
int64_t value;
if (napi_get_value_int64(env, args[0], &value) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_get_value_int64 failed");
return nullptr;
}
napi_value exports;
if (napi_create_object(env, &exports) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_create_object failed");
return nullptr;
}
return exports;
return nullptr;
}
void PluginManager::Export(napi_env env, napi_value exports)
void PluginManager::OnSurfaceCreated(OH_NativeXComponent* component, void* window)
{
if ((env == nullptr) || (exports == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "Export: env or exports is null");
return;
}
napi_value exportInstance = nullptr;
if (napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "Export: napi_get_named_property fail");
return;
}
OH_NativeXComponent* nativeXComponent = nullptr;
if (napi_unwrap(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent)) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "Export: napi_unwrap fail");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "XComponent_Native", "PluginManager::OnSurfaceCreated");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "Export: OH_NativeXComponent_GetXComponentId fail");
return;
}
std::string id(idStr);
auto context = PluginManager::GetInstance();
if ((context != nullptr) && (nativeXComponent != nullptr)) {
context->SetNativeXComponent(id, nativeXComponent);
auto render = context->GetRender(id);
if (render != nullptr) {
render->RegisterCallback(nativeXComponent);
render->Export(env, exports);
}
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
ret = OH_NativeXComponent_GetXComponentSize(component, window, &width_, &height_);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
eglcore_->EglContextInit(window, width_, height_);
eglcore_->Background();
}
}
void PluginManager::SetNativeXComponent(std::string& id, OH_NativeXComponent* nativeXComponent)
void PluginManager::OnSurfaceDestroyed(OH_NativeXComponent* component, void* window)
{
if (nativeXComponent == nullptr) {
return;
}
nativeXComponentMap_[id] = nativeXComponent;
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "XComponent_Native", "PluginManager::OnSurfaceDestroyed");
}
PluginRender* PluginManager::GetRender(std::string& id)
void PluginManager::DispatchTouchEvent(OH_NativeXComponent* component, void* window)
{
if (pluginRenderMap_.find(id) == pluginRenderMap_.end()) {
PluginRender* instance = PluginRender::GetInstance(id);
pluginRenderMap_[id] = instance;
return instance;
int32_t ret = OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent_);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
float tiltX = 2.2;
float tiltY = 2.2;
OH_NativeXComponent_TouchPointToolType toolType =
OH_NativeXComponent_TouchPointToolType::OH_NATIVEXCOMPONENT_TOOL_TYPE_LENS;
OH_NativeXComponent_GetTouchPointToolType(component, 0, &toolType);
OH_NativeXComponent_GetTouchPointTiltX(component, 0, &tiltX);
OH_NativeXComponent_GetTouchPointTiltY(component, 0, &tiltY);
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "XComponent_Native",
"Touch Info : x=%{public}f, y=%{public}f screenx=%{public}f, screeny=%{public}f,"
"type=%{public}d, force=%{public}f, tiltX=%{public}f, tiltY=%{public}f, toolType=%{public}d",
touchEvent_.x, touchEvent_.y, touchEvent_.screenX,
touchEvent_.screenY, touchEvent_.type, touchEvent_.force, tiltX, tiltY, toolType);
if (touchEvent_.type == OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UP)
eglcore_->ChangeColor(hasChangeColor_);
} else {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "XComponent_Native", "touch fail");
}
return pluginRenderMap_[id];
}
void PluginManager::OnSurfaceChanged(OH_NativeXComponent* component, void* window)
{
int32_t ret = OH_NativeXComponent_GetXComponentSize(component, window, &width_, &height_);
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "XComponent_Native",
"OnSurfaceChanged ret=%{public}d width=%{public}lu, height=%{public}lu", ret, width_, height_);
}
} // namespace NativeXComponentSample

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -16,35 +16,48 @@
#define NATIVE_XCOMPONENT_PLUGIN_MANAGER_H
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <cstdint>
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <napi/native_api.h>
#include <string>
#include <unordered_map>
#include "../render/plugin_render.h"
#include "render/egl_core.h"
namespace NativeXComponentSample {
class PluginManager {
public:
static OH_NativeXComponent_Callback callback_;
PluginManager();
~PluginManager();
static PluginManager* GetInstance()
{
return &PluginManager::pluginManager_;
}
static napi_value GetContext(napi_env env, napi_callback_info info);
void SetNativeXComponent(std::string& id, OH_NativeXComponent* nativeXComponent);
PluginRender* GetRender(std::string& id);
void Export(napi_env env, napi_value exports);
static napi_value createNativeNode(napi_env env, napi_callback_info info);
static napi_value GetXComponentStatus(napi_env env, napi_callback_info info);
static napi_value NapiDrawPattern(napi_env env, napi_callback_info info);
// CApi XComponent
void OnSurfaceChanged(OH_NativeXComponent* component, void* window);
void OnSurfaceDestroyed(OH_NativeXComponent* component, void* window);
void DispatchTouchEvent(OH_NativeXComponent* component, void* window);
void OnSurfaceCreated(OH_NativeXComponent* component, void* window);
private:
static PluginManager pluginManager_;
std::unordered_map<std::string, OH_NativeXComponent*> nativeXComponentMap_;
std::unordered_map<std::string, PluginRender*> pluginRenderMap_;
std::unordered_map<std::string, PluginManager*> pluginManagerMap_;
public:
EGLCore *eglcore_;
uint64_t width_;
uint64_t height_;
OH_NativeXComponent_TouchEvent touchEvent_;
static int32_t hasDraw_;
static int32_t hasChangeColor_;
};
} // namespace NativeXComponentSample
#endif // NATIVE_XCOMPONENT_PLUGIN_MANAGER_H

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -28,28 +28,33 @@ static napi_value Init(napi_env env, napi_value exports)
return nullptr;
}
napi_property_descriptor desc[] = { { "getContext", nullptr, PluginManager::GetContext, nullptr, nullptr, nullptr,
napi_default, nullptr } };
napi_property_descriptor desc[] = {
{"createNativeNode", nullptr, PluginManager::createNativeNode, nullptr, nullptr, nullptr,
napi_default, nullptr },
{"getStatus", nullptr, PluginManager::GetXComponentStatus, nullptr, nullptr,
nullptr, napi_default, nullptr},
{"drawPattern", nullptr, PluginManager::NapiDrawPattern, nullptr, nullptr,
nullptr, napi_default, nullptr}
};
if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Init", "napi_define_properties failed");
return nullptr;
}
PluginManager::GetInstance()->Export(env, exports);
return exports;
}
EXTERN_C_END
static napi_module nativerenderModule = { .nm_version = 1,
static napi_module nativenodeModule = { .nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "nativerender",
.nm_modname = "nativenode",
.nm_priv = ((void*)0),
.reserved = { 0 } };
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&nativerenderModule);
napi_module_register(&nativenodeModule);
}
} // namespace NativeXComponentSample

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -24,7 +24,6 @@
#include <hilog/log.h>
#include "../common/common.h"
#include "plugin_render.h"
namespace NativeXComponentSample {
namespace {
@ -222,7 +221,6 @@ bool EGLCore::EglContextInit(void* window, int width, int height)
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "eglChooseConfig: unable to choose configs");
return false;
}
return CreateEnvironment();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -18,11 +18,12 @@
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include "string"
namespace NativeXComponentSample {
class EGLCore {
public:
explicit EGLCore() {};
explicit EGLCore() {}
~EGLCore() {}
bool EglContextInit(void* window, int width, int height);
bool CreateEnvironment();

View File

@ -1,471 +0,0 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdint>
#include <hilog/log.h>
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <string>
#include "../common/common.h"
#include "../manager/plugin_manager.h"
#include "plugin_render.h"
namespace NativeXComponentSample {
namespace {
void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceCreatedCB");
if ((component == nullptr) || (window == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceCreatedCB: component or window is null");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceCreatedCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
uint64_t width;
uint64_t height;
int32_t xSize = OH_NativeXComponent_GetXComponentSize(component, window, &width, &height);
if ((xSize == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) && (render != nullptr)) {
if (render->eglCore_->EglContextInit(window, width, height)) {
render->eglCore_->Background();
}
}
}
void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceChangedCB");
if ((component == nullptr) || (window == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceChangedCB: component or window is null");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceChangedCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnSurfaceChanged(component, window);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "surface changed");
}
}
void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceDestroyedCB");
if ((component == nullptr) || (window == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceDestroyedCB: component or window is null");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceDestroyedCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
PluginRender::Release(id);
}
void DispatchTouchEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB");
if ((component == nullptr) || (window == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB: component or window is null");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnTouchEvent(component, window);
}
}
void DispatchMouseEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "DispatchMouseEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnMouseEvent(component, window);
}
}
void DispatchHoverEventCB(OH_NativeXComponent* component, bool isHover)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "DispatchHoverEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnHoverEvent(component, isHover);
}
}
void OnFocusEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnFocusEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnFocusEvent(component, window);
}
}
void OnBlurEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnBlurEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnBlurEvent(component, window);
}
}
void OnKeyEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnKeyEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnKeyEvent(component, window);
}
}
} // namespace
std::unordered_map<std::string, PluginRender*> PluginRender::instance_;
int32_t PluginRender::hasDraw_ = 0;
int32_t PluginRender::hasChangeColor_ = 0;
PluginRender::PluginRender(std::string& id)
{
this->id_ = id;
this->eglCore_ = new EGLCore();
}
PluginRender* PluginRender::GetInstance(std::string& id)
{
if (instance_.find(id) == instance_.end()) {
PluginRender* instance = new PluginRender(id);
instance_[id] = instance;
return instance;
} else {
return instance_[id];
}
}
void PluginRender::Export(napi_env env, napi_value exports)
{
if ((env == nullptr) || (exports == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "Export: env or exports is null");
return;
}
napi_property_descriptor desc[] = {
{"drawPattern", nullptr, PluginRender::NapiDrawPattern, nullptr, nullptr,
nullptr, napi_default, nullptr},
{"getStatus", nullptr, PluginRender::TestGetXComponentStatus, nullptr, nullptr,
nullptr, napi_default, nullptr}};
if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "Export: napi_define_properties failed");
}
}
// NAPI registration method type napi_callback. If no value is returned, nullptr is returned.
napi_value PluginRender::NapiDrawPattern(napi_env env, napi_callback_info info)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern");
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: env or info is null");
return nullptr;
}
napi_value thisArg;
if (napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: napi_get_cb_info fail");
return nullptr;
}
napi_value exportInstance;
if (napi_get_named_property(env, thisArg, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance) != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: napi_get_named_property fail");
return nullptr;
}
OH_NativeXComponent* nativeXComponent = nullptr;
if (napi_unwrap(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent)) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: napi_unwrap fail");
return nullptr;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: Unable to get XComponent id");
return nullptr;
}
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->eglCore_->Draw(hasDraw_);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "render->eglCore_->Draw() executed");
}
return nullptr;
}
void PluginRender::Release(std::string& id)
{
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->eglCore_->Release();
delete render->eglCore_;
render->eglCore_ = nullptr;
instance_.erase(instance_.find(id));
}
}
void PluginRender::OnSurfaceChanged(OH_NativeXComponent* component, void* window)
{
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceChanged: Unable to get XComponent id");
return;
}
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
double offsetX;
double offsetY;
OH_NativeXComponent_GetXComponentOffset(component, window, &offsetX, &offsetY);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "OH_NativeXComponent_GetXComponentOffset",
"offsetX = %{public}lf, offsetY = %{public}lf", offsetX, offsetY);
uint64_t width;
uint64_t height;
OH_NativeXComponent_GetXComponentSize(component, window, &width, &height);
if (render != nullptr) {
render->eglCore_->UpdateSize(width, height);
}
}
void PluginRender::OnTouchEvent(OH_NativeXComponent* component, void* window)
{
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB: Unable to get XComponent id");
return;
}
OH_NativeXComponent_TouchEvent touchEvent;
OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent);
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr && touchEvent.type == OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UP) {
render->eglCore_->ChangeColor(hasChangeColor_);
}
float tiltX = 0.0f;
float tiltY = 0.0f;
OH_NativeXComponent_TouchPointToolType toolType =
OH_NativeXComponent_TouchPointToolType::OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN;
OH_NativeXComponent_GetTouchPointToolType(component, 0, &toolType);
OH_NativeXComponent_GetTouchPointTiltX(component, 0, &tiltX);
OH_NativeXComponent_GetTouchPointTiltY(component, 0, &tiltY);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "OnTouchEvent",
"touch info: toolType = %{public}d, tiltX = %{public}lf, tiltY = %{public}lf", toolType, tiltX, tiltY);
}
void PluginRender::RegisterCallback(OH_NativeXComponent* nativeXComponent)
{
renderCallback_.OnSurfaceCreated = OnSurfaceCreatedCB;
renderCallback_.OnSurfaceChanged = OnSurfaceChangedCB;
renderCallback_.OnSurfaceDestroyed = OnSurfaceDestroyedCB;
renderCallback_.DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, &renderCallback_);
mouseCallback_.DispatchMouseEvent = DispatchMouseEventCB;
mouseCallback_.DispatchHoverEvent = DispatchHoverEventCB;
OH_NativeXComponent_RegisterMouseEventCallback(nativeXComponent, &mouseCallback_);
OH_NativeXComponent_RegisterFocusEventCallback(nativeXComponent, OnFocusEventCB);
OH_NativeXComponent_RegisterKeyEventCallback(nativeXComponent, OnKeyEventCB);
OH_NativeXComponent_RegisterBlurEventCallback(nativeXComponent, OnBlurEventCB);
}
void PluginRender::OnMouseEvent(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnMouseEvent");
OH_NativeXComponent_MouseEvent mouseEvent;
int32_t ret = OH_NativeXComponent_GetMouseEvent(component, window, &mouseEvent);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender",
"MouseEvent Info: x = %{public}f, y = %{public}f, action = %{public}d, button = %{public}d", mouseEvent.x,
mouseEvent.y, mouseEvent.action, mouseEvent.button);
} else {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "GetMouseEvent error");
}
}
void PluginRender::OnHoverEvent(OH_NativeXComponent* component, bool isHover)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnHoverEvent isHover_ = %{public}d", isHover);
}
void PluginRender::OnFocusEvent(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnFocusEvent");
}
void PluginRender::OnBlurEvent(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnBlurEvent");
}
void PluginRender::OnKeyEvent(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnKeyEvent");
OH_NativeXComponent_KeyEvent* keyEvent = nullptr;
if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) >= 0) {
OH_NativeXComponent_KeyAction action;
OH_NativeXComponent_GetKeyEventAction(keyEvent, &action);
OH_NativeXComponent_KeyCode code;
OH_NativeXComponent_GetKeyEventCode(keyEvent, &code);
OH_NativeXComponent_EventSourceType sourceType;
OH_NativeXComponent_GetKeyEventSourceType(keyEvent, &sourceType);
int64_t deviceId;
OH_NativeXComponent_GetKeyEventDeviceId(keyEvent, &deviceId);
int64_t timeStamp;
OH_NativeXComponent_GetKeyEventTimestamp(keyEvent, &timeStamp);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender",
"KeyEvent Info: action=%{public}d, code=%{public}d, sourceType=%{public}d, deviceId=%{public}ld, "
"timeStamp=%{public}ld",
action, code, sourceType, deviceId, timeStamp);
} else {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "GetKeyEvent error");
}
}
napi_value PluginRender::TestGetXComponentStatus(napi_env env, napi_callback_info info)
{
napi_value hasDraw;
napi_value hasChangeColor;
napi_status ret = napi_create_int32(env, hasDraw_, &(hasDraw));
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus", "napi_create_int32 hasDraw_ error");
return nullptr;
}
ret = napi_create_int32(env, hasChangeColor_, &(hasChangeColor));
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus", "napi_create_int32 hasChangeColor_ error");
return nullptr;
}
napi_value obj;
ret = napi_create_object(env, &obj);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus", "napi_create_object error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasDraw", hasDraw);
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus", "napi_set_named_property hasDraw error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasChangeColor", hasChangeColor);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus",
"napi_set_named_property hasChangeColor error");
return nullptr;
}
return obj;
}
} // namespace NativeXComponentSample

View File

@ -1,63 +0,0 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef NATIVE_XCOMPONENT_PLUGIN_RENDER_H
#define NATIVE_XCOMPONENT_PLUGIN_RENDER_H
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <napi/native_api.h>
#include <string>
#include <unordered_map>
#include "egl_core.h"
namespace NativeXComponentSample {
class PluginRender {
public:
explicit PluginRender(std::string& id);
~PluginRender()
{
if (eglCore_ != nullptr) {
eglCore_->Release();
delete eglCore_;
eglCore_ = nullptr;
}
}
static PluginRender* GetInstance(std::string& id);
static void Release(std::string& id);
static napi_value NapiDrawPattern(napi_env env, napi_callback_info info);
static napi_value TestGetXComponentStatus(napi_env env, napi_callback_info info);
void Export(napi_env env, napi_value exports);
void OnSurfaceChanged(OH_NativeXComponent* component, void* window);
void OnTouchEvent(OH_NativeXComponent* component, void* window);
void OnMouseEvent(OH_NativeXComponent* component, void* window);
void OnHoverEvent(OH_NativeXComponent* component, bool isHover);
void OnFocusEvent(OH_NativeXComponent* component, void* window);
void OnBlurEvent(OH_NativeXComponent* component, void* window);
void OnKeyEvent(OH_NativeXComponent* component, void* window);
void RegisterCallback(OH_NativeXComponent* nativeXComponent);
public:
static std::unordered_map<std::string, PluginRender*> instance_;
EGLCore* eglCore_;
std::string id_;
static int32_t hasDraw_;
static int32_t hasChangeColor_;
private:
OH_NativeXComponent_Callback renderCallback_;
OH_NativeXComponent_MouseEvent_Callback mouseCallback_;
};
} // namespace NativeXComponentSample
#endif // NATIVE_XCOMPONENT_PLUGIN_RENDER_H

View File

@ -0,0 +1,23 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { NodeContent } from '@ohos.arkui.node';
type XComponentContextStatus = {
hasDraw: boolean,
hasChangeColor: boolean
};
export const createNativeNode: (content: NodeContent, tag: string) => void;
export const getStatus: () => XComponentContextStatus;
export const drawPattern: () => void;

View File

@ -0,0 +1,6 @@
{
"name": "libnativenode.so",
"types": "./Index.d.ts",
"version": " ",
"description": "Please describe the basic infomation"
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,13 +13,17 @@
* limitations under the License.
*/
import XComponentContext from "../interface/XComponentContext"
import nativeNode from 'libnativenode.so';
import {NodeContent} from '@kit.ArkUI';
@Entry
@Component
struct Index {
@State currentStatus: string = "init";
private xComponentContext: XComponentContext | undefined = undefined;
private nodeContent: NodeContent = new NodeContent();
aboutToAppear():void{
nativeNode.createNativeNode(this.nodeContent,"ygb");
}
build() {
Column() {
@ -37,19 +41,7 @@ struct Index {
.height(56)
Column({ space: 10 }) {
XComponent({
id: 'xcomponentId',
type: XComponentType.SURFACE,
libraryname: 'nativerender'
})
.onLoad((xComponentContext) => {
this.xComponentContext = xComponentContext as XComponentContext;
this.currentStatus = "index";
})
.onDestroy(() => {
console.log('onDestroy');
})
.id("xcomponent")
ContentSlot(this.nodeContent);
Text(this.currentStatus)
.fontSize('24fp')
@ -57,8 +49,8 @@ struct Index {
}
.onClick(() => {
let hasChangeColor: boolean = false;
if (this.xComponentContext && this.xComponentContext.getStatus()) {
hasChangeColor = this.xComponentContext.getStatus().hasChangeColor;
if (nativeNode.getStatus()) {
hasChangeColor = nativeNode.getStatus().hasChangeColor;
}
if (hasChangeColor) {
this.currentStatus = "change color";
@ -78,16 +70,14 @@ struct Index {
.fontWeight(500)
.margin({ bottom: 24 })
.onClick(() => {
if (this.xComponentContext) {
this.xComponentContext.drawPattern();
nativeNode.drawPattern();
let hasDraw: boolean = false;
if (this.xComponentContext.getStatus()) {
hasDraw = this.xComponentContext.getStatus().hasDraw;
if (nativeNode.getStatus()) {
hasDraw = nativeNode.getStatus().hasDraw;
}
if (hasDraw) {
this.currentStatus = "draw star";
}
}
})
.width('53.6%')
.height(40)

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -50,8 +50,6 @@ export default function abilityTest() {
it('DrawShape_001', 2, async () => {
console.info(TAG, 'CreateFiles_001 begin');
let driver = Driver.create();
// 判断XComponent onLoad回调执行成功
await driver.assertComponentExist(ON.text('index'));
// 判断是否有按键
await driver.assertComponentExist(ON.text('Draw Star'));
let drawStarBtn = await driver.findComponent(ON.text('Draw Star'));
@ -62,7 +60,7 @@ export default function abilityTest() {
await driver.assertComponentExist(ON.text('draw star'));
// 判断是否有XComponent组件
let xcomponent = await driver.findComponent(ON.id('xcomponent'));
let xcomponent = await driver.findComponent(ON.id('ndkxcomponent'));
// 点击XComponent组件
await xcomponent.click();
await driver.delayMs(1000);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -23,7 +23,7 @@ import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
export default class TestAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam){
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate');
hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');
hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? '');
@ -37,7 +37,7 @@ export default class TestAbility extends UIAbility {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage) {
onWindowStageCreate(windowStage : window.WindowStage) {
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageCreate');
windowStage.loadContent('testability/pages/Index', (err, data) => {
if (err.code) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -18,13 +18,11 @@ import hilog from '@ohos.hilog';
@Entry
@Component
struct Index {
aboutToAppear() {
aboutToAppear(){
hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility index aboutToAppear');
}
@State message: string = 'Hello World';
build() {
build(){
Row() {
Column() {
Text(this.message)

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at

View File

@ -1,6 +1,5 @@
{
"hvigorVersion": "3.0.2",
"modelVersion": "5.0.0",
"dependencies": {
"@ohos/hvigor-ohos-plugin": "3.0.2"
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,48 +0,0 @@
#!/bin/bash
# ----------------------------------------------------------------------------
# Hvigor startup script, version 1.0.0
#
# Required ENV vars:
# ------------------
# NODE_HOME - location of a Node home dir
# or
# Add /usr/local/nodejs/bin to the PATH environment variable
# ----------------------------------------------------------------------------
HVIGOR_APP_HOME=$(dirname $(readlink -f $0))
HVIGOR_WRAPPER_SCRIPT=${HVIGOR_APP_HOME}/hvigor/hvigor-wrapper.js
warn() {
echo ""
echo -e "\033[1;33m`date '+[%Y-%m-%d %H:%M:%S]'`$@\033[0m"
}
error() {
echo ""
echo -e "\033[1;31m`date '+[%Y-%m-%d %H:%M:%S]'`$@\033[0m"
}
fail() {
error "$@"
exit 1
}
# Determine node to start hvigor wrapper script
if [ -n "${NODE_HOME}" ];then
EXECUTABLE_NODE="${NODE_HOME}/bin/node"
if [ ! -x "$EXECUTABLE_NODE" ];then
fail "ERROR: NODE_HOME is set to an invalid directory,check $NODE_HOME\n\nPlease set NODE_HOME in your environment to the location where your nodejs installed"
fi
else
EXECUTABLE_NODE="node"
which ${EXECUTABLE_NODE} > /dev/null 2>&1 || fail "ERROR: NODE_HOME is not set and not 'node' command found in your path"
fi
# Check hvigor wrapper script
if [ ! -r "$HVIGOR_WRAPPER_SCRIPT" ];then
fail "ERROR: Couldn't find hvigor/hvigor-wrapper.js in ${HVIGOR_APP_HOME}"
fi
# start hvigor-wrapper script
exec "${EXECUTABLE_NODE}" \
"${HVIGOR_WRAPPER_SCRIPT}" "$@"

View File

@ -1,79 +0,0 @@
:: Copyright (c) 2023 Huawei Device Co., Ltd.
:: Licensed under the Apache License, Version 2.0 (the "License");
:: you may not use this file except in compliance with the License.
:: You may obtain a copy of the License at
::
:: http://www.apache.org/licenses/LICENSE-2.0
::
:: Unless required by applicable law or agreed to in writing, software
:: distributed under the License is distributed on an "AS IS" BASIS,
:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
:: See the License for the specific language governing permissions and
:: limitations under the License.
@echo off
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Hvigor startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
set WRAPPER_MODULE_PATH=%APP_HOME%\hvigor\hvigor-wrapper.js
set NODE_EXE=node.exe
goto start
:start
@rem Find node.exe
if defined NODE_HOME goto findNodeFromNodeHome
%NODE_EXE% --version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: NODE_HOME is not set and no 'node' command could be found in your PATH.
echo.
echo Please set the NODE_HOME variable in your environment to match the
echo location of your NodeJs installation.
goto fail
:findNodeFromNodeHome
set NODE_HOME=%NODE_HOME:"=%
set NODE_EXE_PATH=%NODE_HOME%/%NODE_EXE%
if exist "%NODE_EXE_PATH%" goto execute
echo.
echo ERROR: NODE_HOME is not set and no 'node' command could be found in your PATH.
echo.
echo Please set the NODE_HOME variable in your environment to match the
echo location of your NodeJs installation.
goto fail
:execute
@rem Execute hvigor
"%NODE_EXE%" %WRAPPER_MODULE_PATH% %*
if "%ERRORLEVEL%" == "0" goto hvigorwEnd
:fail
exit /b 1
:hvigorwEnd
if "%OS%" == "Windows_NT" endlocal
:end

View File

@ -1,4 +1,5 @@
{
"modelVersion": "5.0.0",
"license": "",
"devDependencies": {
"@ohos/hypium": "1.0.6"
@ -9,4 +10,4 @@
"main": "",
"version": "1.0.0",
"dependencies": {}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -15,8 +15,8 @@
{
"app": {
"bundleName": "com.sample.xcomponent",
"vendor": "example",
"bundleName": "com.samples.xcomponent",
"vendor": "samples",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",

View File

@ -2,7 +2,7 @@
"string": [
{
"name": "app_name",
"value": "xcomponent"
"value": "XComponent"
}
]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

View File

@ -1,15 +1,15 @@
# XComponent
# Native XComponent
### 介绍
本示例主要介绍开发者如何使用ArkTS XComponent组件进行自绘制主要包括XComponent组件使用
SurfaceId获取方法Surface生命周期回调使用NativeWindow创建等知识点。开发者基于ArkTS侧获取的SurfaceId
在Native侧调用OH_NativeWindow_CreateNativeWindowFromSurfaceId接口创建出NativeWindow实例后使用OpenGL ES/EGL接口在XComponent组件上进行图形绘制。功能主要包括点击按钮绘制一个五角星并可以通过点击XComponent区域改变五角星的颜色。
本示例中主要介绍开发者如何使用Native XComponent接口来获取NativeWindow实例、获取布局/事件信息、注册事件回调并通过OpenGL/EGL实现在页面上绘制形状。功能主要包括点击按钮绘制一个五角星并可以通过点击XComponent区域改变五角星的颜色。
> **说明**
> 本示例已停止演进XComponent使用方法推荐参考[ArkTSXComponent示例](../ArkTSXComponent/README_zh.md)。
### 效果预览
| 主页 | 绘制五角星 | 改变颜色 |
|--------------------------------------|-----------------------------------------------|-----------------------------------------------------|
| 主页 | 绘制五角星 | 改变颜色 |
| ------------------------------------ | --------------------------------------------- | --------------------------------------------------- |
| ![main](screenshots/device/main.png) | ![draw star](screenshots/device/drawStar.png) | ![change color](screenshots/device/changeColor.png) |
使用说明
@ -48,30 +48,35 @@ SurfaceId获取方法Surface生命周期回调使用NativeWindow创建等
### 具体实现
通过在IDE中创建Native c++ 工程在c++代码中定义对外接口为DrawPattern在ArkTS侧调用该接口可在页面上绘制出一个五角星。在
c++代码中定义对外接口为ChangeColor点击XComponent组件时在ArkTs侧调用该接口可在页面绘制一个大小相同、颜色不同的五角星达到改变颜色的目的。
通过在IDE中创建Native c++ 工程在c++代码中定义对外接口为drawPattern在js侧调用该接口可在页面上绘制出一个三角形。
在XComponentController的OnSurfaceCreated回调中传入XComponent的surfaceId在Native侧调用OH_NativeWindow_CreateNativeWindowFromSurfaceId创建NativeWindow实例并初始化
EGL环境。在XComponentController的OnsurfaceChanged回调中传入surfaceId、宽和高并以此为输入调用EGL相关的接口改变对应NativeWindow的尺寸和内容。
在XComponent的OnSurfaceCreated回调中获取NativeWindow实例并初始化EGL环境。调用OH_NativeXComponent_GetXComponentSize接口获取XComponent的宽高并以此为输入调用EGL相关的绘制接口在NativeWindow上绘制出一个五角星。在DispatchTouchEvent回调中再次调用EGL相关的绘制接口在NativeWindow上绘制出一个大小相同、颜色不同的五角星以达到点击后改变颜色的目的。
源码参考:[main目录](entry/src/main/)下的文件。涉及到的相关接口:
源码参考:[render目录](entry/src/main/cpp/render)下的文件。
#### ArkTS组件
XComponentController
| 接口名 | 描述 |
|-------------------------------------------|--------------------------|
| getXComponentSurfaceId(): string | 获取XComponent对应Surface的ID |
| onSurfaceCreated(surfaceId: string): void |当XComponent持有的Surface创建后进行该回调|
|onSurfaceChanged(surfaceId: string, rect: SurfaceRect): void|当XComponent持有的Surface大小改变后包括首次创建时的大小改变进行该回调|
|onSurfaceDestroyed(surfaceId: string): void|当XComponent持有的Surface销毁后进行该回调|
#### C API
| 接口名 | 描述 |
|-------------------------------------------|--------------------------|
| int32_t OH_NativeWindow_CreateNativeWindowFromSurfaceId (uint64_t surfaceId, OHNativeWindow **window ) | 通过surfaceId创建对应的OHNativeWindow |
| void OH_NativeWindow_DestroyNativeWindow (OHNativeWindow* window)|将OHNativeWindow对象的引用计数减1当引用计数为0的时候该OHNativeWindow对象会被析构掉|
涉及到的相关接口:
| 接口名 | 描述 |
| ------------------------------------------------------------ | ------------------------------------------------------- |
| OH_NativeXComponent_GetXComponentId(OH_NativeXComponent* component, char* id, uint64_t* size) | 获取XComponent的id。 |
| OH_NativeXComponent_GetXComponentSize(OH_NativeXComponent* component, const void* window, uint64_t* width, uint64_t* height) | 获取XComponent持有的surface的大小。 |
| OH_NativeXComponent_GetXComponentOffset(OH_NativeXComponent* component, const void* window, double* x, double* y) | 获取XComponent持有的surface相对窗口左上角的偏移量。 |
| OH_NativeXComponent_GetTouchEvent(OH_NativeXComponent* component, const void* window, OH_NativeXComponent_TouchEvent* touchEvent) | 获取由XComponent触发的触摸事件。 |
| OH_NativeXComponent_GetTouchPointToolType(OH_NativeXComponent* component, uint32_t pointIndex, OH_NativeXComponent_TouchPointToolType* toolType) | 获取XComponent触摸点的工具类型。 |
| OH_NativeXComponent_GetTouchPointTiltX(OH_NativeXComponent* component, uint32_t pointIndex, float* tiltX) | 获取XComponent触摸点处相对X轴的倾斜角度。 |
| OH_NativeXComponent_GetTouchPointTiltY(OH_NativeXComponent* component, uint32_t pointIndex, float* tiltY) | 获取XComponent触摸点处相对Y轴的倾斜角度。 |
| OH_NativeXComponent_GetMouseEvent(OH_NativeXComponent* component, const void* window, OH_NativeXComponent_MouseEvent* mouseEvent) | 获取由XComponent触发的鼠标事件。 |
| OH_NativeXComponent_RegisterCallback(OH_NativeXComponent* component, OH_NativeXComponent_Callback* callback) | 为此OH_NativeXComponent实例注册生命周期和触摸事件回调。 |
| OH_NativeXComponent_RegisterMouseEventCallback(OH_NativeXComponent* component, OH_NativeXComponent_MouseEvent_Callback* callback) | 为此OH_NativeXComponent实例注册鼠标事件回调。 |
| OH_NativeXComponent_RegisterFocusEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册获得焦点事件回调。 |
| OH_NativeXComponent_RegisterKeyEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册按键事件回调。 |
| OH_NativeXComponent_RegisterBlurEventCallback(OH_NativeXComponent* component, void (*callback)(OH_NativeXComponent* component, void* window)) | 为此OH_NativeXComponent实例注册失去焦点事件回调。 |
| OH_NativeXComponent_GetKeyEvent(OH_NativeXComponent* component, OH_NativeXComponent_KeyEvent** keyEvent) | 获取由XComponent触发的按键事件。 |
| OH_NativeXComponent_GetKeyEventAction(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_KeyAction* action) | 获取按键事件的动作。 |
| OH_NativeXComponent_GetKeyEventCode(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_KeyCode* code) | 获取按键事件的键码值。 |
| OH_NativeXComponent_GetKeyEventSourceType(OH_NativeXComponent_KeyEvent* keyEvent, OH_NativeXComponent_EventSourceType* sourceType) | 获取按键事件的输入源类型。 |
| OH_NativeXComponent_GetKeyEventDeviceId(OH_NativeXComponent_KeyEvent* keyEvent, int64_t* deviceId) | 获取按键事件的设备ID。 |
| OH_NativeXComponent_GetKeyEventTimestamp(OH_NativeXComponent_KeyEvent* keyEvent, int64_t* timestamp) | 获取按键事件的时间戳。 |
### 相关权限
@ -83,9 +88,9 @@ XComponentController
### 约束与限制
1. 本示例仅支持标准系统上运行,支持设备:rk3568
1. 本示例仅支持标准系统上运行,支持设备:RK3568
2. 本示例为Stage模型支持API12版本SDKSDK版本号(API Version 12 Release),镜像版本号(5.0 Release)
2. 本示例为Stage模型支持API10版本SDKSDK版本号(API Version 10 Release),镜像版本号(4.0 Release)
3. 本示例需要使用DevEco Studio 版本号(4.0 Release)及以上版本才可编译运行

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -20,17 +20,9 @@
{
"name": "default",
"signingConfig": "default",
"compileSdkVersion": 12,
"compatibleSdkVersion": 12,
"runtimeOS": "OpenHarmony",
}
],
"buildModeSet": [
{
"name": "debug",
},
{
"name": "release"
"compileSdkVersion": 10,
"compatibleSdkVersion": 10,
"runtimeOS": "OpenHarmony"
}
]
},

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -14,40 +14,18 @@
*/
{
"apiType": "stageMode",
"apiType": '',
"buildOption": {
"externalNativeOptions": {
"path": "./src/main/cpp/CMakeLists.txt",
"arguments": "",
"cppFlags": "",
"abiFilters": ["arm64-v8a", "armeabi-v7a", "x86_64"]
}
},
"buildOptionSet": [
{
"name": "release",
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": true,
"files": [
"./obfuscation-rules.txt"
]
}
}
},
"nativeLib": {
"debugSymbol": {
"strip": true,
"exclude": []
}
}
},
],
"targets": [
{
"name": "default"
"name": "default",
"runtimeOS": "OpenHarmony"
},
{
"name": "ohosTest",

View File

@ -1,6 +1,2 @@
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
export { hapTasks } from '@ohos/hvigor-ohos-plugin';

View File

@ -1,11 +1,10 @@
{
"license": "",
"devDependencies": {},
"author": "",
"name": "entry",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "",
"author": "",
"license": "",
"dependencies": {
"libnativerender.so": "file:./src/main/cpp/types/libnativerender"
}
}
"version": "1.0.0",
"dependencies": {}
}

View File

@ -66,4 +66,4 @@ find_library(
)
target_link_libraries(nativerender PUBLIC
${EGL-lib} ${GLES-lib} ${hilog-lib} ${libace-lib} ${libnapi-lib} ${libuv-lib} libnative_window.so)
${EGL-lib} ${GLES-lib} ${hilog-lib} ${libace-lib} ${libnapi-lib} ${libuv-lib})

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -14,45 +14,23 @@
*/
#include "plugin_manager.h"
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <cstdint>
#include <cstdio>
#include <hilog/log.h>
#include <native_drawing/drawing_text_typography.h>
#include <string>
#include "../common/common.h"
#include <native_window/external_window.h>
namespace NativeXComponentSample {
namespace {
int64_t ParseId(napi_env env, napi_callback_info info)
{
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "ParseId", "env or info is null");
return -1;
}
size_t argc = 1;
napi_value args[1] = {nullptr};
if (napi_ok != napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "ParseId", "GetContext napi_get_cb_info failed");
return -1;
}
int64_t value = 0;
bool lossless = true;
if (napi_ok != napi_get_value_bigint_int64(env, args[0], &value, &lossless)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "ParseId", "Get value failed");
return -1;
}
return value;
}
}
std::unordered_map<int64_t, PluginRender*> PluginManager::pluginRenderMap_;
std::unordered_map<int64_t, OHNativeWindow*> PluginManager::windowMap_;
PluginManager PluginManager::pluginManager_;
PluginManager::~PluginManager()
{
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "~PluginManager");
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "~PluginManager");
nativeXComponentMap_.clear();
for (auto iter = pluginRenderMap_.begin(); iter != pluginRenderMap_.end(); ++iter) {
if (iter->second != nullptr) {
delete iter->second;
@ -60,159 +38,107 @@ PluginManager::~PluginManager()
}
}
pluginRenderMap_.clear();
for (auto iter = windowMap_.begin(); iter != windowMap_.end(); ++iter) {
if (iter->second != nullptr) {
delete iter->second;
iter->second = nullptr;
}
}
windowMap_.clear();
}
PluginRender* PluginManager::GetPluginRender(int64_t& id)
{
if (pluginRenderMap_.find(id) != pluginRenderMap_.end()) {
return pluginRenderMap_[id];
}
return nullptr;
}
napi_value PluginManager::SetSurfaceId(napi_env env, napi_callback_info info)
{
int64_t surfaceId = ParseId(env, info);
OHNativeWindow *nativeWindow;
PluginRender *pluginRender;
if (windowMap_.find(surfaceId) == windowMap_.end()) {
OH_NativeWindow_CreateNativeWindowFromSurfaceId(surfaceId, &nativeWindow);
windowMap_[surfaceId] = nativeWindow;
}
if (pluginRenderMap_.find(surfaceId) == pluginRenderMap_.end()) {
pluginRender = new PluginRender(surfaceId);
pluginRenderMap_[surfaceId] = pluginRender;
}
pluginRender->InitNativeWindow(nativeWindow);
return nullptr;
}
napi_value PluginManager::DestroySurface(napi_env env, napi_callback_info info)
{
int64_t surfaceId = ParseId(env, info);
auto pluginRenderMapIter = pluginRenderMap_.find(surfaceId);
if (pluginRenderMapIter != pluginRenderMap_.end()) {
delete pluginRenderMapIter->second;
pluginRenderMap_.erase(pluginRenderMapIter);
}
auto windowMapIter = windowMap_.find(surfaceId);
if (windowMapIter != windowMap_.end()) {
OH_NativeWindow_DestroyNativeWindow(windowMapIter->second);
windowMap_.erase(windowMapIter);
}
return nullptr;
}
napi_value PluginManager::ChangeSurface(napi_env env, napi_callback_info info)
napi_value PluginManager::GetContext(napi_env env, napi_callback_info info)
{
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"ChangeSurface: OnLoad env or info is null");
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "GetContext env or info is null");
return nullptr;
}
int64_t surfaceId = 0;
size_t argc = 3;
napi_value args[3] = {nullptr};
if (napi_ok != napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"ChangeSurface: GetContext napi_get_cb_info failed");
size_t argCnt = 1;
napi_value args[1] = { nullptr };
if (napi_get_cb_info(env, info, &argCnt, args, nullptr, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "GetContext napi_get_cb_info failed");
}
bool lossless = true;
int index = 0;
if (napi_ok != napi_get_value_bigint_int64(env, args[index++], &surfaceId, &lossless)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeSurface: Get value failed");
}
double width;
if (napi_ok != napi_get_value_double(env, args[index++], &width)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeSurface: Get width failed");
}
double height;
if (napi_ok != napi_get_value_double(env, args[index++], &height)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeSurface: Get height failed");
}
auto pluginRender = GetPluginRender(surfaceId);
if (pluginRender == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeSurface: Get pluginRender failed");
if (argCnt != 1) {
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
pluginRender->UpdateNativeWindowSize(width, height);
return nullptr;
napi_valuetype valuetype;
if (napi_typeof(env, args[0], &valuetype) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_typeof failed");
return nullptr;
}
if (valuetype != napi_number) {
napi_throw_type_error(env, NULL, "Wrong type of arguments");
return nullptr;
}
int64_t value;
if (napi_get_value_int64(env, args[0], &value) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_get_value_int64 failed");
return nullptr;
}
napi_value exports;
if (napi_create_object(env, &exports) != napi_ok) {
napi_throw_type_error(env, NULL, "napi_create_object failed");
return nullptr;
}
return exports;
}
napi_value PluginManager::ChangeColor(napi_env env, napi_callback_info info)
void PluginManager::Export(napi_env env, napi_value exports)
{
int64_t surfaceId = ParseId(env, info);
auto pluginRender = GetPluginRender(surfaceId);
if (pluginRender == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "ChangeColor: Get pluginRender failed");
return nullptr;
if ((env == nullptr) || (exports == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "Export: env or exports is null");
return;
}
napi_value exportInstance = nullptr;
if (napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "Export: napi_get_named_property fail");
return;
}
OH_NativeXComponent* nativeXComponent = nullptr;
if (napi_unwrap(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent)) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "Export: napi_unwrap fail");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "Export: OH_NativeXComponent_GetXComponentId fail");
return;
}
std::string id(idStr);
auto context = PluginManager::GetInstance();
if ((context != nullptr) && (nativeXComponent != nullptr)) {
context->SetNativeXComponent(id, nativeXComponent);
auto render = context->GetRender(id);
if (render != nullptr) {
render->RegisterCallback(nativeXComponent);
render->Export(env, exports);
}
}
pluginRender->ChangeColor();
return nullptr;
}
napi_value PluginManager::DrawPattern(napi_env env, napi_callback_info info)
void PluginManager::SetNativeXComponent(std::string& id, OH_NativeXComponent* nativeXComponent)
{
int64_t surfaceId = ParseId(env, info);
auto pluginRender = GetPluginRender(surfaceId);
if (pluginRender == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager", "DrawPattern: Get pluginRender failed");
return nullptr;
if (nativeXComponent == nullptr) {
return;
}
pluginRender->DrawPattern();
return nullptr;
nativeXComponentMap_[id] = nativeXComponent;
}
napi_value PluginManager::GetXComponentStatus(napi_env env, napi_callback_info info)
PluginRender* PluginManager::GetRender(std::string& id)
{
int64_t surfaceId = ParseId(env, info);
auto pluginRender = GetPluginRender(surfaceId);
if (pluginRender == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: Get pluginRender failed");
return nullptr;
if (pluginRenderMap_.find(id) == pluginRenderMap_.end()) {
PluginRender* instance = PluginRender::GetInstance(id);
pluginRenderMap_[id] = instance;
return instance;
}
napi_value hasDraw;
napi_value hasChangeColor;
napi_status ret = napi_create_int32(env, pluginRender->HasDraw(), &(hasDraw));
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: napi_create_int32 hasDraw_ error");
return nullptr;
}
ret = napi_create_int32(env, pluginRender->HasChangedColor(), &(hasChangeColor));
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: napi_create_int32 hasChangeColor_ error");
return nullptr;
}
napi_value obj;
ret = napi_create_object(env, &obj);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN,
"PluginManager", "GetXComponentStatus: napi_create_object error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasDraw", hasDraw);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: napi_set_named_property hasDraw error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasChangeColor", hasChangeColor);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginManager",
"GetXComponentStatus: napi_set_named_property hasChangeColor error");
return nullptr;
}
return obj;
return pluginRenderMap_[id];
}
} // namespace NativeXComponentSample

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -18,24 +18,33 @@
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <napi/native_api.h>
#include <string>
#include <unordered_map>
#include <native_window/external_window.h>
#include "../render/plugin_render.h"
namespace NativeXComponentSample {
class PluginManager {
public:
~PluginManager();
static PluginRender* GetPluginRender(int64_t& id);
static napi_value ChangeColor(napi_env env, napi_callback_info info);
static napi_value DrawPattern(napi_env env, napi_callback_info info);
static napi_value SetSurfaceId(napi_env env, napi_callback_info info);
static napi_value ChangeSurface(napi_env env, napi_callback_info info);
static napi_value DestroySurface(napi_env env, napi_callback_info info);
static napi_value GetXComponentStatus(napi_env env, napi_callback_info info);
public:
static std::unordered_map<int64_t, PluginRender*> pluginRenderMap_;
static std::unordered_map<int64_t, OHNativeWindow*> windowMap_;
static PluginManager* GetInstance()
{
return &PluginManager::pluginManager_;
}
static napi_value GetContext(napi_env env, napi_callback_info info);
void SetNativeXComponent(std::string& id, OH_NativeXComponent* nativeXComponent);
PluginRender* GetRender(std::string& id);
void Export(napi_env env, napi_value exports);
private:
static PluginManager pluginManager_;
std::unordered_map<std::string, OH_NativeXComponent*> nativeXComponentMap_;
std::unordered_map<std::string, PluginRender*> pluginRenderMap_;
};
} // namespace NativeXComponentSample
#endif // NATIVE_XCOMPONENT_PLUGIN_MANAGER_H

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -19,7 +19,6 @@
#include "manager/plugin_manager.h"
namespace NativeXComponentSample {
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
@ -28,38 +27,29 @@ static napi_value Init(napi_env env, napi_value exports)
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Init", "env or exports is null");
return nullptr;
}
napi_property_descriptor desc[] = {
{"ChangeColor", nullptr, PluginManager::ChangeColor,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"SetSurfaceId", nullptr, PluginManager::SetSurfaceId,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"ChangeSurface", nullptr, PluginManager::ChangeSurface,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"GetXComponentStatus", nullptr, PluginManager::GetXComponentStatus,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"DrawPattern", nullptr, PluginManager::DrawPattern,
nullptr, nullptr, nullptr, napi_default, nullptr},
{"DestroySurface", nullptr, PluginManager::DestroySurface,
nullptr, nullptr, nullptr, napi_default, nullptr}
};
napi_property_descriptor desc[] = { { "getContext", nullptr, PluginManager::GetContext, nullptr, nullptr, nullptr,
napi_default, nullptr } };
if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Init", "napi_define_properties failed");
return nullptr;
}
PluginManager::GetInstance()->Export(env, exports);
return exports;
}
EXTERN_C_END
static napi_module nativerenderModule = {
.nm_version = 1,
static napi_module nativerenderModule = { .nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "nativerender",
.nm_priv = ((void*)0),
.reserved = { 0 } };
} // namespace NativeXComponentSample
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&NativeXComponentSample::nativerenderModule);
}
napi_module_register(&nativerenderModule);
}
} // namespace NativeXComponentSample

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -189,9 +189,15 @@ const EGLint CONTEXT_ATTRIBS[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE};
} // namespace
bool EGLCore::EglContextInit(void* window)
bool EGLCore::EglContextInit(void* window, int width, int height)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "EGLCore", "EglContextInit execute");
if ((window == nullptr) || (width <= 0) || (height <= 0)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "EGLCore", "EglContextInit: param error");
return false;
}
UpdateSize(width, height);
eglWindow_ = static_cast<EGLNativeWindowType>(window);
// Init display.

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -24,7 +24,7 @@ class EGLCore {
public:
explicit EGLCore() {};
~EGLCore() {}
bool EglContextInit(void* window);
bool EglContextInit(void* window, int width, int height);
bool CreateEnvironment();
void Draw(int& hasDraw);
void Background();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -14,49 +14,458 @@
*/
#include <cstdint>
#include <hilog/log.h>
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <string>
#include "../common/common.h"
#include "../manager/plugin_manager.h"
#include "plugin_render.h"
namespace NativeXComponentSample {
PluginRender::PluginRender(int64_t& id)
namespace {
void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window)
{
this->id_ = id;
this->eglCore_ = new EGLCore();
hasDraw_ = 0;
hasChangeColor_ = 0;
}
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceCreatedCB");
if ((component == nullptr) || (window == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceCreatedCB: component or window is null");
return;
}
void PluginRender::ChangeColor()
{
eglCore_->ChangeColor(hasChangeColor_);
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceCreatedCB: Unable to get XComponent id");
return;
}
void PluginRender::DrawPattern()
{
eglCore_->Draw(hasDraw_);
}
void PluginRender::InitNativeWindow(OHNativeWindow *window)
{
eglCore_->EglContextInit(window);
}
void PluginRender::UpdateNativeWindowSize(int width, int height)
{
eglCore_->UpdateSize(width, height);
if (!hasChangeColor_ && !hasDraw_) {
eglCore_->Background();
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
uint64_t width;
uint64_t height;
int32_t xSize = OH_NativeXComponent_GetXComponentSize(component, window, &width, &height);
if ((xSize == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) && (render != nullptr)) {
if (render->eglCore_->EglContextInit(window, width, height)) {
render->eglCore_->Background();
}
}
}
int32_t PluginRender::HasDraw()
void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window)
{
return hasDraw_;
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceChangedCB");
if ((component == nullptr) || (window == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceChangedCB: component or window is null");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceChangedCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnSurfaceChanged(component, window);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "surface changed");
}
}
int32_t PluginRender::HasChangedColor()
void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window)
{
return hasChangeColor_;
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceDestroyedCB");
if ((component == nullptr) || (window == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceDestroyedCB: component or window is null");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceDestroyedCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
PluginRender::Release(id);
}
void DispatchTouchEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB");
if ((component == nullptr) || (window == nullptr)) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB: component or window is null");
return;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnTouchEvent(component, window);
}
}
void DispatchMouseEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "DispatchMouseEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnMouseEvent(component, window);
}
}
void DispatchHoverEventCB(OH_NativeXComponent* component, bool isHover)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "DispatchHoverEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnHoverEvent(component, isHover);
}
}
void OnFocusEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnFocusEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnFocusEvent(component, window);
}
}
void OnBlurEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnBlurEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnBlurEvent(component, window);
}
}
void OnKeyEventCB(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "Callback", "OnKeyEventCB");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
std::string id(idStr);
auto render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->OnKeyEvent(component, window);
}
}
} // namespace
std::unordered_map<std::string, PluginRender*> PluginRender::instance_;
int32_t PluginRender::hasDraw_ = 0;
int32_t PluginRender::hasChangeColor_ = 0;
PluginRender::PluginRender(std::string& id)
{
this->id_ = id;
this->eglCore_ = new EGLCore();
}
PluginRender* PluginRender::GetInstance(std::string& id)
{
if (instance_.find(id) == instance_.end()) {
PluginRender* instance = new PluginRender(id);
instance_[id] = instance;
return instance;
} else {
return instance_[id];
}
}
void PluginRender::Export(napi_env env, napi_value exports)
{
if ((env == nullptr) || (exports == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "Export: env or exports is null");
return;
}
napi_property_descriptor desc[] = {
{"drawPattern", nullptr, PluginRender::NapiDrawPattern, nullptr, nullptr,
nullptr, napi_default, nullptr},
{"getStatus", nullptr, PluginRender::TestGetXComponentStatus, nullptr, nullptr,
nullptr, napi_default, nullptr}};
if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "Export: napi_define_properties failed");
}
}
// NAPI registration method type napi_callback. If no value is returned, nullptr is returned.
napi_value PluginRender::NapiDrawPattern(napi_env env, napi_callback_info info)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern");
if ((env == nullptr) || (info == nullptr)) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: env or info is null");
return nullptr;
}
napi_value thisArg;
if (napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, nullptr) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: napi_get_cb_info fail");
return nullptr;
}
napi_value exportInstance;
if (napi_get_named_property(env, thisArg, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance) != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: napi_get_named_property fail");
return nullptr;
}
OH_NativeXComponent* nativeXComponent = nullptr;
if (napi_unwrap(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent)) != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: napi_unwrap fail");
return nullptr;
}
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "NapiDrawPattern: Unable to get XComponent id");
return nullptr;
}
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->eglCore_->Draw(hasDraw_);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "render->eglCore_->Draw() executed");
}
return nullptr;
}
void PluginRender::Release(std::string& id)
{
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr) {
render->eglCore_->Release();
delete render->eglCore_;
render->eglCore_ = nullptr;
instance_.erase(instance_.find(id));
}
}
void PluginRender::OnSurfaceChanged(OH_NativeXComponent* component, void* window)
{
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "OnSurfaceChanged: Unable to get XComponent id");
return;
}
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
double offsetX;
double offsetY;
OH_NativeXComponent_GetXComponentOffset(component, window, &offsetX, &offsetY);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "OH_NativeXComponent_GetXComponentOffset",
"offsetX = %{public}lf, offsetY = %{public}lf", offsetX, offsetY);
uint64_t width;
uint64_t height;
OH_NativeXComponent_GetXComponentSize(component, window, &width, &height);
if (render != nullptr) {
render->eglCore_->UpdateSize(width, height);
}
}
void PluginRender::OnTouchEvent(OH_NativeXComponent* component, void* window)
{
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { '\0' };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
if (OH_NativeXComponent_GetXComponentId(component, idStr, &idSize) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "Callback", "DispatchTouchEventCB: Unable to get XComponent id");
return;
}
OH_NativeXComponent_TouchEvent touchEvent;
OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent);
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr && touchEvent.type == OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UP) {
render->eglCore_->ChangeColor(hasChangeColor_);
}
float tiltX = 0.0f;
float tiltY = 0.0f;
OH_NativeXComponent_TouchPointToolType toolType =
OH_NativeXComponent_TouchPointToolType::OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN;
OH_NativeXComponent_GetTouchPointToolType(component, 0, &toolType);
OH_NativeXComponent_GetTouchPointTiltX(component, 0, &tiltX);
OH_NativeXComponent_GetTouchPointTiltY(component, 0, &tiltY);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "OnTouchEvent",
"touch info: toolType = %{public}d, tiltX = %{public}lf, tiltY = %{public}lf", toolType, tiltX, tiltY);
}
void PluginRender::RegisterCallback(OH_NativeXComponent* nativeXComponent)
{
renderCallback_.OnSurfaceCreated = OnSurfaceCreatedCB;
renderCallback_.OnSurfaceChanged = OnSurfaceChangedCB;
renderCallback_.OnSurfaceDestroyed = OnSurfaceDestroyedCB;
renderCallback_.DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, &renderCallback_);
mouseCallback_.DispatchMouseEvent = DispatchMouseEventCB;
mouseCallback_.DispatchHoverEvent = DispatchHoverEventCB;
OH_NativeXComponent_RegisterMouseEventCallback(nativeXComponent, &mouseCallback_);
OH_NativeXComponent_RegisterFocusEventCallback(nativeXComponent, OnFocusEventCB);
OH_NativeXComponent_RegisterKeyEventCallback(nativeXComponent, OnKeyEventCB);
OH_NativeXComponent_RegisterBlurEventCallback(nativeXComponent, OnBlurEventCB);
}
void PluginRender::OnMouseEvent(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnMouseEvent");
OH_NativeXComponent_MouseEvent mouseEvent;
int32_t ret = OH_NativeXComponent_GetMouseEvent(component, window, &mouseEvent);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender",
"MouseEvent Info: x = %{public}f, y = %{public}f, action = %{public}d, button = %{public}d", mouseEvent.x,
mouseEvent.y, mouseEvent.action, mouseEvent.button);
} else {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "GetMouseEvent error");
}
}
void PluginRender::OnHoverEvent(OH_NativeXComponent* component, bool isHover)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnHoverEvent isHover_ = %{public}d", isHover);
}
void PluginRender::OnFocusEvent(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnFocusEvent");
}
void PluginRender::OnBlurEvent(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnBlurEvent");
}
void PluginRender::OnKeyEvent(OH_NativeXComponent* component, void* window)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnKeyEvent");
OH_NativeXComponent_KeyEvent* keyEvent = nullptr;
if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) >= 0) {
OH_NativeXComponent_KeyAction action;
OH_NativeXComponent_GetKeyEventAction(keyEvent, &action);
OH_NativeXComponent_KeyCode code;
OH_NativeXComponent_GetKeyEventCode(keyEvent, &code);
OH_NativeXComponent_EventSourceType sourceType;
OH_NativeXComponent_GetKeyEventSourceType(keyEvent, &sourceType);
int64_t deviceId;
OH_NativeXComponent_GetKeyEventDeviceId(keyEvent, &deviceId);
int64_t timeStamp;
OH_NativeXComponent_GetKeyEventTimestamp(keyEvent, &timeStamp);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender",
"KeyEvent Info: action=%{public}d, code=%{public}d, sourceType=%{public}d, deviceId=%{public}ld, "
"timeStamp=%{public}ld",
action, code, sourceType, deviceId, timeStamp);
} else {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "GetKeyEvent error");
}
}
napi_value PluginRender::TestGetXComponentStatus(napi_env env, napi_callback_info info)
{
napi_value hasDraw;
napi_value hasChangeColor;
napi_status ret = napi_create_int32(env, hasDraw_, &(hasDraw));
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus", "napi_create_int32 hasDraw_ error");
return nullptr;
}
ret = napi_create_int32(env, hasChangeColor_, &(hasChangeColor));
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus", "napi_create_int32 hasChangeColor_ error");
return nullptr;
}
napi_value obj;
ret = napi_create_object(env, &obj);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus", "napi_create_object error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasDraw", hasDraw);
if (ret != napi_ok) {
OH_LOG_Print(
LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus", "napi_set_named_property hasDraw error");
return nullptr;
}
ret = napi_set_named_property(env, obj, "hasChangeColor", hasChangeColor);
if (ret != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "TestGetXComponentStatus",
"napi_set_named_property hasChangeColor error");
return nullptr;
}
return obj;
}
} // namespace NativeXComponentSample

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -16,13 +16,16 @@
#define NATIVE_XCOMPONENT_PLUGIN_RENDER_H
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <native_window/external_window.h>
#include <napi/native_api.h>
#include <string>
#include <unordered_map>
#include "egl_core.h"
namespace NativeXComponentSample {
class PluginRender {
public:
explicit PluginRender(int64_t& id);
explicit PluginRender(std::string& id);
~PluginRender()
{
if (eglCore_ != nullptr) {
@ -31,17 +34,30 @@ public:
eglCore_ = nullptr;
}
}
void ChangeColor();
void DrawPattern();
int32_t HasDraw();
int32_t HasChangedColor();
void InitNativeWindow(OHNativeWindow* window);
void UpdateNativeWindowSize(int width, int height);
private:
static PluginRender* GetInstance(std::string& id);
static void Release(std::string& id);
static napi_value NapiDrawPattern(napi_env env, napi_callback_info info);
static napi_value TestGetXComponentStatus(napi_env env, napi_callback_info info);
void Export(napi_env env, napi_value exports);
void OnSurfaceChanged(OH_NativeXComponent* component, void* window);
void OnTouchEvent(OH_NativeXComponent* component, void* window);
void OnMouseEvent(OH_NativeXComponent* component, void* window);
void OnHoverEvent(OH_NativeXComponent* component, bool isHover);
void OnFocusEvent(OH_NativeXComponent* component, void* window);
void OnBlurEvent(OH_NativeXComponent* component, void* window);
void OnKeyEvent(OH_NativeXComponent* component, void* window);
void RegisterCallback(OH_NativeXComponent* nativeXComponent);
public:
static std::unordered_map<std::string, PluginRender*> instance_;
EGLCore* eglCore_;
int64_t id_;
int32_t hasDraw_;
int32_t hasChangeColor_;
std::string id_;
static int32_t hasDraw_;
static int32_t hasChangeColor_;
private:
OH_NativeXComponent_Callback renderCallback_;
OH_NativeXComponent_MouseEvent_Callback mouseCallback_;
};
} // namespace NativeXComponentSample
#endif // NATIVE_XCOMPONENT_PLUGIN_RENDER_H

Some files were not shown because too many files have changed in this diff Show More