* Copyright (c) 2025 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 <bits/alltypes.h>
#include <native_drawing/drawing_font_collection.h>
#include <native_drawing/drawing_text_typography.h>
#include <native_drawing/drawing_text_declaration.h>
#include <native_drawing/drawing_register_font.h>
#include <native_buffer/native_buffer.h>
#include "common/log_common.h"
#include "sample_bitmap.h"
#include "plugin/plugin_manager.h"
static void OnSurfaceCreatedCB(OH_NativeXComponent *component, void *window)
{
DRAWING_LOGI("OnSurfaceCreatedCB");
if ((component == nullptr) || (window == nullptr)) {
DRAWING_LOGE("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) {
DRAWING_LOGE("OnSurfaceCreatedCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
auto render = SampleBitMap::GetInstance(id);
OHNativeWindow *nativeWindow = static_cast<OHNativeWindow *>(window);
render->SetNativeWindow(nativeWindow);
uint64_t width;
uint64_t height;
int32_t xSize = OH_NativeXComponent_GetXComponentSize(component, window, &width, &height);
if ((xSize == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) && (render != nullptr)) {
render->SetHeight(height);
render->SetWidth(width);
DRAWING_LOGI("xComponent width = %{public}llu, height = %{public}llu", width, height);
}
}
static void OnSurfaceDestroyedCB(OH_NativeXComponent *component, void *window)
{
DRAWING_LOGI("OnSurfaceDestroyedCB");
if ((component == nullptr) || (window == nullptr)) {
DRAWING_LOGE("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) {
DRAWING_LOGE("OnSurfaceDestroyedCB: Unable to get XComponent id");
return;
}
std::string id(idStr);
SampleBitMap::Release(id);
}
static std::unordered_map<std::string, SampleBitMap *> g_instance;
void SampleBitMap::SetWidth(uint64_t width)
{
width_ = width;
}
void SampleBitMap::SetHeight(uint64_t height)
{
height_ = height;
}
void SampleBitMap::SetNativeWindow(OHNativeWindow *nativeWindow)
{
nativeWindow_ = nativeWindow;
}
void SampleBitMap::Prepare()
{
if (nativeWindow_ == nullptr) {
DRAWING_LOGE("nativeWindow_ is nullptr");
return;
}
int32_t usage = NATIVEBUFFER_USAGE_CPU_READ | NATIVEBUFFER_USAGE_CPU_WRITE | NATIVEBUFFER_USAGE_MEM_DMA;
int ret = OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_USAGE, usage);
if (ret != 0) {
DRAWING_LOGE("failed to OH_NativeWindow_NativeWindowHandleOpt");
return;
}
ret = OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer_, &fenceFd_);
DRAWING_LOGI("request buffer ret = %{public}d", ret);
bufferHandle_ = OH_NativeWindow_GetBufferHandleFromNative(buffer_);
mappedAddr_ = static_cast<uint32_t *>(
mmap(bufferHandle_->virAddr, bufferHandle_->size, PROT_READ | PROT_WRITE, MAP_SHARED, bufferHandle_->fd, 0));
if (mappedAddr_ == MAP_FAILED) {
DRAWING_LOGE("mmap failed");
}
}
void SampleBitMap::DisPlay()
{
void *bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap_);
uint32_t *value = static_cast<uint32_t *>(bitmapAddr);
uint32_t *pixel = static_cast<uint32_t *>(mappedAddr_);
if (pixel == nullptr) {
DRAWING_LOGE("pixel is null");
return;
}
if (value == nullptr) {
DRAWING_LOGE("value is null");
return;
}
uint32_t width = static_cast<uint32_t>(bufferHandle_->stride / 4);
for (uint32_t x = 0; x < width; x++) {
for (uint32_t y = 0; y < height_; y++) {
*pixel++ = *value++;
}
}
Region region {nullptr, 0};
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer_, fenceFd_, region);
int result = munmap(mappedAddr_, bufferHandle_->size);
if (result == -1) {
DRAWING_LOGE("munmap failed!");
}
}
void SampleBitMap::Create()
{
uint32_t width = static_cast<uint32_t>(bufferHandle_->stride / 4);
cBitmap_ = OH_Drawing_BitmapCreate();
OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE};
OH_Drawing_BitmapBuild(cBitmap_, width, height_, &cFormat);
cCanvas_ = OH_Drawing_CanvasCreate();
OH_Drawing_CanvasBind(cCanvas_, cBitmap_);
OH_Drawing_CanvasClear(cCanvas_, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
}
void SampleBitMap::DrawText()
{
OH_Drawing_FontCollection *fontCollection = OH_Drawing_GetFontCollectionGlobalInstance();
OH_Drawing_TextStyle *myTextStyle = OH_Drawing_CreateTextStyle();
OH_Drawing_SetTextStyleColor(myTextStyle, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0x00, 0x00));
OH_Drawing_SetTextStyleFontSize(myTextStyle, 50.0);
OH_Drawing_TypographyStyle *typographyStyle = OH_Drawing_CreateTypographyStyle();
OH_Drawing_SetTypographyTextAlign(typographyStyle, TEXT_ALIGN_LEFT);
OH_Drawing_TypographyCreate *handler = OH_Drawing_CreateTypographyHandler(typographyStyle, fontCollection);
OH_Drawing_TypographyHandlerPushTextStyle(handler, myTextStyle);
const char *text = "排版测量的文字度量信息";
OH_Drawing_TypographyHandlerAddText(handler, text);
OH_Drawing_Typography *typography = OH_Drawing_CreateTypography(handler);
double maxWidth = width_;
OH_Drawing_TypographyLayout(typography, maxWidth);
OH_Drawing_TypographyPaint(typography, cCanvas_, 0, 100);
PrintMetricsAndLayout(typography, myTextStyle);
}
void SampleBitMap::PrintMetricsAndLayout(OH_Drawing_Typography *typography, OH_Drawing_TextStyle *myTextStyle)
{
double longestLine = OH_Drawing_TypographyGetLongestLine(typography);
DRAWING_LOGI("第%{public}d行 longestLine: %{public}f", longestLine);
size_t lineCnt = OH_Drawing_TypographyGetLineCount(typography);
DRAWING_LOGI("lineCnt: %{public}zu", lineCnt);
OH_Drawing_LineMetrics *lineMetrics = OH_Drawing_TypographyGetLineMetrics(typography);
int lineMetricsSize = OH_Drawing_LineMetricsGetSize(lineMetrics);
for (int i = 0; i < lineMetricsSize; ++i) {
double curLineAscender = -lineMetrics[i].ascender;
double curLineWidth = lineMetrics[i].width;
DRAWING_LOGI("第%{public}d行 lineMetrics ascender: %{public}f", i + 1, curLineAscender);
DRAWING_LOGI("第%{public}d行 lineMetrics width: %{public}f", i + 1, curLineWidth);
}
double longestLineWithIndent = OH_Drawing_TypographyGetLongestLineWithIndent(typography);
DRAWING_LOGI("longestLineWithIndent: %{public}f", longestLineWithIndent);
OH_Drawing_Font_Metrics fontMetrics;
bool result = OH_Drawing_TextStyleGetFontMetrics(typography, myTextStyle, &fontMetrics);
DRAWING_LOGI("result: %{public}zu, fontMetrics ascent: %{public}f", result, fontMetrics.ascent);
OH_Drawing_LineMetrics lineMetric;
OH_Drawing_TypographyGetLineMetricsAt(typography, 0, &lineMetric);
DRAWING_LOGI("第1行 lineMetrics ascender: %{public}f", -lineMetric.ascender);
PrintConstraintsAndPositions(typography);
}
void SampleBitMap::PrintConstraintsAndPositions(OH_Drawing_Typography *typography)
{
OH_Drawing_RectSize constraintsRect;
constraintsRect.width = 500.0;
constraintsRect.height = 200.0;
OH_Drawing_Array *fitStrRangeArr = nullptr;
size_t fitStrRangeArrayLen = 0;
OH_Drawing_RectSize actualSize = OH_Drawing_TypographyLayoutWithConstraintsWithBuffer(typography,
constraintsRect, &fitStrRangeArr, &fitStrRangeArrayLen);
DRAWING_LOGI("actualSize width: %{public}f, height: %{public}f", actualSize.width, actualSize.height);
DRAWING_LOGI("fitStrRangeArrayLen: %{public}zu", fitStrRangeArrayLen);
for (size_t i = 0; i < fitStrRangeArrayLen; ++i) {
OH_Drawing_Range *range = OH_Drawing_GetRangeByArrayIndex(fitStrRangeArr, i);
if (range != nullptr) {
DRAWING_LOGI("fitStrRange[%{public}zu] start: %{public}zu, end: %{public}zu",
i, OH_Drawing_GetStartFromRange(range), OH_Drawing_GetEndFromRange(range));
}
}
OH_Drawing_ReleaseArrayBuffer(fitStrRangeArr);
PrintCharAndGlyphInfo(typography);
}
void SampleBitMap::PrintCharAndGlyphInfo(OH_Drawing_Typography *typography)
{
OH_Drawing_PositionAndAffinity *charPos =
OH_Drawing_TypographyGetCharacterPositionAtCoordinateWithBuffer(
typography, 100.0, 30.0, OH_Drawing_TextEncoding::TEXT_ENCODING_UTF8);
if (charPos != nullptr) {
size_t charPosition = OH_Drawing_GetPositionFromPositionAndAffinity(charPos);
int affinity = OH_Drawing_GetAffinityFromPositionAndAffinity(charPos);
DRAWING_LOGI("charPosition (UTF-8 byte offset): %{public}zu, affinity: %{public}d",
charPosition, affinity);
OH_Drawing_DestroyPositionAndAffinity(charPos);
}
OH_Drawing_Range *actualGlyphRange = nullptr;
OH_Drawing_Range *charRange =
OH_Drawing_TypographyGetCharacterRangeForGlyphRangeWithBuffer(
typography, 0, 5, &actualGlyphRange, OH_Drawing_TextEncoding::TEXT_ENCODING_UTF8);
if (charRange != nullptr) {
DRAWING_LOGI("charRange start: %{public}zu, end: %{public}zu",
OH_Drawing_GetStartFromRange(charRange), OH_Drawing_GetEndFromRange(charRange));
OH_Drawing_ReleaseRangeBuffer(charRange);
}
if (actualGlyphRange != nullptr) {
DRAWING_LOGI("actualGlyphRange start: %{public}zu, end: %{public}zu",
OH_Drawing_GetStartFromRange(actualGlyphRange), OH_Drawing_GetEndFromRange(actualGlyphRange));
OH_Drawing_ReleaseRangeBuffer(actualGlyphRange);
}
OH_Drawing_Range *actualCharRange = nullptr;
OH_Drawing_Range *glyphRange =
OH_Drawing_TypographyGetGlyphRangeForCharacterRangeWithBuffer(
typography, 0, 10, &actualCharRange, OH_Drawing_TextEncoding::TEXT_ENCODING_UTF8);
if (glyphRange != nullptr) {
DRAWING_LOGI("glyphRange start: %{public}zu, end: %{public}zu",
OH_Drawing_GetStartFromRange(glyphRange), OH_Drawing_GetEndFromRange(glyphRange));
OH_Drawing_ReleaseRangeBuffer(glyphRange);
}
if (actualCharRange != nullptr) {
DRAWING_LOGI("actualCharRange start: %{public}zu, end: %{public}zu",
OH_Drawing_GetStartFromRange(actualCharRange), OH_Drawing_GetEndFromRange(actualCharRange));
OH_Drawing_ReleaseRangeBuffer(actualCharRange);
}
}
napi_value SampleBitMap::NapiDrawText(napi_env env, napi_callback_info info)
{
DRAWING_LOGI("NapiDrawText");
if ((env == nullptr) || (info == nullptr)) {
DRAWING_LOGE("NapiDrawPattern: env or info is null");
return nullptr;
}
napi_value thisArg;
if (napi_get_cb_info(env, info, nullptr, nullptr, &thisArg, nullptr) != napi_ok) {
DRAWING_LOGE("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) {
DRAWING_LOGE("NapiDrawPattern: napi_get_named_property fail");
return nullptr;
}
OH_NativeXComponent *nativeXComponent = nullptr;
if (napi_unwrap(env, exportInstance, reinterpret_cast<void **>(&nativeXComponent)) != napi_ok) {
DRAWING_LOGE("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) {
DRAWING_LOGE("NapiDrawPattern: Unable to get XComponent id");
return nullptr;
}
DRAWING_LOGI("ID = %{public}s", idStr);
std::string id(idStr);
SampleBitMap *render = SampleBitMap().GetInstance(id);
if (render != nullptr) {
render->Prepare();
render->Create();
render->DrawText();
render->DisPlay();
render->Destroy();
DRAWING_LOGI("DrawText executed");
} else {
DRAWING_LOGE("render is nullptr");
}
return nullptr;
}
SampleBitMap::~SampleBitMap()
{
OH_Drawing_BrushDestroy(cBrush_);
cBrush_ = nullptr;
OH_Drawing_PenDestroy(cPen_);
cPen_ = nullptr;
OH_Drawing_PathDestroy(cPath_);
cPath_ = nullptr;
OH_Drawing_CanvasDestroy(cCanvas_);
cCanvas_ = nullptr;
OH_Drawing_BitmapDestroy(cBitmap_);
cBitmap_ = nullptr;
buffer_ = nullptr;
bufferHandle_ = nullptr;
nativeWindow_ = nullptr;
mappedAddr_ = nullptr;
}
void SampleBitMap::Destroy()
{
OH_Drawing_BrushDestroy(cBrush_);
cBrush_ = nullptr;
OH_Drawing_PenDestroy(cPen_);
cPen_ = nullptr;
OH_Drawing_PathDestroy(cPath_);
cPath_ = nullptr;
OH_Drawing_CanvasDestroy(cCanvas_);
cCanvas_ = nullptr;
OH_Drawing_BitmapDestroy(cBitmap_);
}
void SampleBitMap::Release(std::string &id)
{
PluginManager::GetInstance()->ReleaseRender(id);
SampleBitMap *render = SampleBitMap::GetInstance(id);
if (render != nullptr) {
delete render;
render = nullptr;
g_instance.erase(g_instance.find(id));
}
}
void SampleBitMap::Export(napi_env env, napi_value exports)
{
if ((env == nullptr) || (exports == nullptr)) {
DRAWING_LOGE("Export: env or exports is null");
return;
}
napi_property_descriptor desc[] = {
{"drawText", nullptr, SampleBitMap::NapiDrawText, nullptr, nullptr, nullptr, napi_default, nullptr}};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
if (napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc) != napi_ok) {
DRAWING_LOGE("Export: napi_define_properties failed");
}
}
void SampleBitMap::RegisterCallback(OH_NativeXComponent *nativeXComponent)
{
DRAWING_LOGI("register callback");
renderCallback_.OnSurfaceCreated = OnSurfaceCreatedCB;
renderCallback_.OnSurfaceDestroyed = OnSurfaceDestroyedCB;
renderCallback_.DispatchTouchEvent = nullptr;
renderCallback_.OnSurfaceChanged = nullptr;
OH_NativeXComponent_RegisterCallback(nativeXComponent, &renderCallback_);
}
SampleBitMap *SampleBitMap::GetInstance(std::string &id)
{
if (g_instance.find(id) == g_instance.end()) {
SampleBitMap *render = new SampleBitMap(id);
g_instance[id] = render;
return render;
} else {
return g_instance[id];
}
}