1 /*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "c/drawing_typeface.h"
17 #include <mutex>
18 #include <unordered_map>
19
20 #include "text/typeface.h"
21
22 using namespace OHOS;
23 using namespace Rosen;
24 using namespace Drawing;
25
26 static std::mutex g_typefaceLockMutex;
27 static std::unordered_map<void*, std::shared_ptr<Typeface>> g_typefaceMap;
28
CastToMemoryStream(OH_Drawing_MemoryStream * cCanvas)29 static MemoryStream* CastToMemoryStream(OH_Drawing_MemoryStream* cCanvas)
30 {
31 return reinterpret_cast<MemoryStream*>(cCanvas);
32 }
33
OH_Drawing_TypefaceCreateDefault()34 OH_Drawing_Typeface* OH_Drawing_TypefaceCreateDefault()
35 {
36 std::shared_ptr<Typeface> typeface = Typeface::MakeDefault();
37 std::lock_guard<std::mutex> lock(g_typefaceLockMutex);
38 g_typefaceMap.insert({typeface.get(), typeface});
39 return (OH_Drawing_Typeface*)typeface.get();
40 }
41
OH_Drawing_TypefaceCreateFromFile(const char * path,int index)42 OH_Drawing_Typeface* OH_Drawing_TypefaceCreateFromFile(const char* path, int index)
43 {
44 std::shared_ptr<Typeface> typeface = Typeface::MakeFromFile(path, index);
45 if (typeface == nullptr) {
46 return nullptr;
47 }
48 std::lock_guard<std::mutex> lock(g_typefaceLockMutex);
49 g_typefaceMap.insert({typeface.get(), typeface});
50 return (OH_Drawing_Typeface*)typeface.get();
51 }
52
OH_Drawing_TypefaceCreateFromStream(OH_Drawing_MemoryStream * cMemoryStream,int32_t index)53 OH_Drawing_Typeface* OH_Drawing_TypefaceCreateFromStream(OH_Drawing_MemoryStream* cMemoryStream, int32_t index)
54 {
55 if (cMemoryStream == nullptr) {
56 return nullptr;
57 }
58 std::unique_ptr<MemoryStream> memoryStream(CastToMemoryStream(cMemoryStream));
59 std::shared_ptr<Typeface> typeface = Typeface::MakeFromStream(std::move(memoryStream), index);
60 if (typeface == nullptr) {
61 return nullptr;
62 }
63 std::lock_guard<std::mutex> lock(g_typefaceLockMutex);
64 g_typefaceMap.insert({typeface.get(), typeface});
65 return (OH_Drawing_Typeface*)typeface.get();
66 }
67
OH_Drawing_TypefaceDestroy(OH_Drawing_Typeface * cTypeface)68 void OH_Drawing_TypefaceDestroy(OH_Drawing_Typeface* cTypeface)
69 {
70 std::lock_guard<std::mutex> lock(g_typefaceLockMutex);
71 auto it = g_typefaceMap.find(cTypeface);
72 if (it == g_typefaceMap.end()) {
73 return;
74 }
75 g_typefaceMap.erase(it);
76 }
77