1 /*
2 * Copyright (c) 2024 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 "font_buffer.h"
17
18 #include <algorithm>
19
20 #include "face_data.h"
21 #include "font_manager.h"
22
23 #include <core/log.h>
24
FONT_BEGIN_NAMESPACE()25 FONT_BEGIN_NAMESPACE()
26 FontBuffer::FontBuffer(FontManager* fontMgr, const uint64_t hash, BASE_NS::array_view<const uint8_t> bytes)
27 : hash_(hash), bytes_(bytes.data(), bytes.data() + bytes.size()),
28 fontManager(BASE_NS::refcnt_ptr<FontManager>(fontMgr))
29 {}
30
~FontBuffer()31 FontBuffer::~FontBuffer()
32 {
33 fontManager->Gc(hash_, this);
34 }
35
CreateFace(long index)36 std::shared_ptr<FaceData> FontBuffer::CreateFace(long index)
37 {
38 {
39 std::shared_lock readerLock(mutex_);
40
41 for (const auto& faceData : faces_) {
42 if (auto fromWeak = faceData.lock(); fromWeak && fromWeak->face_->face_index == index) {
43 return fromWeak;
44 }
45 }
46 }
47 std::lock_guard writerLock(mutex_);
48
49 for (const auto& faceData : faces_) {
50 if (auto fromWeak = faceData.lock(); fromWeak && fromWeak->face_->face_index == index) {
51 return fromWeak;
52 }
53 }
54
55 auto ftFace = fontManager->OpenFtFace(bytes_, index);
56 if (!ftFace) {
57 return nullptr;
58 }
59
60 auto face = std::make_shared<FaceData>(shared_from_this(), ftFace);
61
62 faces_.push_back(face);
63 CORE_LOG_N("create FaceData");
64 return face;
65 }
66
Gc()67 void FontBuffer::Gc()
68 {
69 std::lock_guard writerLock(mutex_);
70 faces_.erase(
71 std::remove_if(faces_.begin(), faces_.end(), [](const std::weak_ptr<FaceData>& ptr) { return ptr.expired(); }),
72 faces_.cend());
73 }
74 FONT_END_NAMESPACE()
75