xref: /aosp_15_r20/frameworks/base/libs/hwui/jni/FontFamily.cpp (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <nativehelper/ScopedPrimitiveArray.h>
18 #include <nativehelper/ScopedUtfChars.h>
19 #include "FontUtils.h"
20 #include "GraphicsJNI.h"
21 #include "SkData.h"
22 #include "SkFontMgr.h"
23 #include "SkRefCnt.h"
24 #include "SkStream.h"
25 #include "SkTypeface.h"
26 #include "Utils.h"
27 #include "fonts/Font.h"
28 
29 #include <hwui/MinikinSkia.h>
30 #include <hwui/Typeface.h>
31 #include <minikin/FontFamily.h>
32 #include <minikin/LocaleList.h>
33 #include <ui/FatVector.h>
34 #include <utils/TypefaceUtils.h>
35 
36 #include <memory>
37 
38 ///////////////////////////////////////////////////////////////////////////////////////////////////
39 //
40 // The following JNI methods are kept only for compatibility reasons due to hidden API accesses.
41 //
42 ///////////////////////////////////////////////////////////////////////////////////////////////////
43 
44 namespace android {
45 
46 namespace {
47 struct NativeFamilyBuilder {
NativeFamilyBuilderandroid::__anon0e71180e0111::NativeFamilyBuilder48     NativeFamilyBuilder(uint32_t langId, int variant)
49         : langId(langId), variant(static_cast<minikin::FamilyVariant>(variant)) {}
50     uint32_t langId;
51     minikin::FamilyVariant variant;
52     std::vector<std::shared_ptr<minikin::Font>> fonts;
53     std::vector<minikin::FontVariation> axes;
54 };
55 }  // namespace
56 
toNativeBuilder(jlong ptr)57 static inline NativeFamilyBuilder* toNativeBuilder(jlong ptr) {
58     return reinterpret_cast<NativeFamilyBuilder*>(ptr);
59 }
60 
toFamily(jlong ptr)61 static inline FontFamilyWrapper* toFamily(jlong ptr) {
62     return reinterpret_cast<FontFamilyWrapper*>(ptr);
63 }
64 
toJLong(Ptr ptr)65 template<typename Ptr> static inline jlong toJLong(Ptr ptr) {
66     return reinterpret_cast<jlong>(ptr);
67 }
68 
FontFamily_initBuilder(JNIEnv * env,jobject clazz,jstring langs,jint variant)69 static jlong FontFamily_initBuilder(JNIEnv* env, jobject clazz, jstring langs, jint variant) {
70     NativeFamilyBuilder* builder;
71     if (langs != nullptr) {
72         ScopedUtfChars str(env, langs);
73         builder = new NativeFamilyBuilder(minikin::registerLocaleList(str.c_str()), variant);
74     } else {
75         builder = new NativeFamilyBuilder(minikin::registerLocaleList(""), variant);
76     }
77     return toJLong(builder);
78 }
79 
FontFamily_create(CRITICAL_JNI_PARAMS_COMMA jlong builderPtr)80 static jlong FontFamily_create(CRITICAL_JNI_PARAMS_COMMA jlong builderPtr) {
81     if (builderPtr == 0) {
82         return 0;
83     }
84     NativeFamilyBuilder* builder = toNativeBuilder(builderPtr);
85     if (builder->fonts.empty()) {
86         return 0;
87     }
88     std::shared_ptr<minikin::FontFamily> family = minikin::FontFamily::create(
89             builder->langId, builder->variant, std::move(builder->fonts),
90             true /* isCustomFallback */, false /* isDefaultFallback */,
91             minikin::VariationFamilyType::None);
92     if (family->getCoverage().length() == 0) {
93         return 0;
94     }
95     return toJLong(new FontFamilyWrapper(std::move(family)));
96 }
97 
releaseBuilder(jlong builderPtr)98 static void releaseBuilder(jlong builderPtr) {
99     delete toNativeBuilder(builderPtr);
100 }
101 
FontFamily_getBuilderReleaseFunc(CRITICAL_JNI_PARAMS)102 static jlong FontFamily_getBuilderReleaseFunc(CRITICAL_JNI_PARAMS) {
103     return toJLong(&releaseBuilder);
104 }
105 
releaseFamily(jlong familyPtr)106 static void releaseFamily(jlong familyPtr) {
107     delete toFamily(familyPtr);
108 }
109 
FontFamily_getFamilyReleaseFunc(CRITICAL_JNI_PARAMS)110 static jlong FontFamily_getFamilyReleaseFunc(CRITICAL_JNI_PARAMS) {
111     return toJLong(&releaseFamily);
112 }
113 
addSkTypeface(NativeFamilyBuilder * builder,sk_sp<SkData> && data,int ttcIndex,jint weight,jint italic)114 static bool addSkTypeface(NativeFamilyBuilder* builder, sk_sp<SkData>&& data, int ttcIndex,
115         jint weight, jint italic) {
116     FatVector<SkFontArguments::VariationPosition::Coordinate, 2> skVariation;
117     for (const auto& axis : builder->axes) {
118         skVariation.push_back({axis.axisTag, axis.value});
119     }
120 
121     const size_t fontSize = data->size();
122     const void* fontPtr = data->data();
123     std::unique_ptr<SkStreamAsset> fontData(new SkMemoryStream(std::move(data)));
124 
125     SkFontArguments args;
126     args.setCollectionIndex(ttcIndex);
127     args.setVariationDesignPosition({skVariation.data(), static_cast<int>(skVariation.size())});
128 
129     sk_sp<SkFontMgr> fm = android::FreeTypeFontMgr();
130     sk_sp<SkTypeface> face(fm->makeFromStream(std::move(fontData), args));
131     if (face == NULL) {
132         ALOGE("addFont failed to create font, invalid request");
133         builder->axes.clear();
134         return false;
135     }
136     std::shared_ptr<minikin::MinikinFont> minikinFont = std::make_shared<MinikinFontSkia>(
137             std::move(face), fonts::getNewSourceId(), fontPtr, fontSize, "", ttcIndex,
138             minikin::VariationSettings(builder->axes, false));
139     minikin::Font::Builder fontBuilder(minikinFont);
140 
141     if (weight != RESOLVE_BY_FONT_TABLE) {
142         fontBuilder.setWeight(weight);
143     }
144     if (italic != RESOLVE_BY_FONT_TABLE) {
145         fontBuilder.setSlant(static_cast<minikin::FontStyle::Slant>(italic != 0));
146     }
147     builder->fonts.push_back(fontBuilder.build());
148     builder->axes.clear();
149     return true;
150 }
151 
release_global_ref(const void *,void * context)152 static void release_global_ref(const void* /*data*/, void* context) {
153     JNIEnv* env = GraphicsJNI::getJNIEnv();
154     bool needToAttach = (env == NULL);
155     if (needToAttach) {
156         env = GraphicsJNI::attachJNIEnv("release_font_data");
157         if (env == nullptr) {
158             ALOGE("failed to attach to thread to release global ref.");
159             return;
160         }
161     }
162 
163     jobject obj = reinterpret_cast<jobject>(context);
164     env->DeleteGlobalRef(obj);
165 
166     if (needToAttach) {
167        GraphicsJNI::detachJNIEnv();
168     }
169 }
170 
FontFamily_addFont(JNIEnv * env,jobject clazz,jlong builderPtr,jobject bytebuf,jint ttcIndex,jint weight,jint isItalic)171 static jboolean FontFamily_addFont(JNIEnv* env, jobject clazz, jlong builderPtr, jobject bytebuf,
172         jint ttcIndex, jint weight, jint isItalic) {
173     NPE_CHECK_RETURN_ZERO(env, bytebuf);
174     NativeFamilyBuilder* builder = reinterpret_cast<NativeFamilyBuilder*>(builderPtr);
175     const void* fontPtr = env->GetDirectBufferAddress(bytebuf);
176     if (fontPtr == NULL) {
177         ALOGE("addFont failed to create font, buffer invalid");
178         builder->axes.clear();
179         return false;
180     }
181     jlong fontSize = env->GetDirectBufferCapacity(bytebuf);
182     if (fontSize < 0) {
183         ALOGE("addFont failed to create font, buffer size invalid");
184         builder->axes.clear();
185         return false;
186     }
187     jobject fontRef = MakeGlobalRefOrDie(env, bytebuf);
188     sk_sp<SkData> data(SkData::MakeWithProc(fontPtr, fontSize,
189             release_global_ref, reinterpret_cast<void*>(fontRef)));
190     return addSkTypeface(builder, std::move(data), ttcIndex, weight, isItalic);
191 }
192 
FontFamily_addFontWeightStyle(JNIEnv * env,jobject clazz,jlong builderPtr,jobject font,jint ttcIndex,jint weight,jint isItalic)193 static jboolean FontFamily_addFontWeightStyle(JNIEnv* env, jobject clazz, jlong builderPtr,
194         jobject font, jint ttcIndex, jint weight, jint isItalic) {
195     NPE_CHECK_RETURN_ZERO(env, font);
196     NativeFamilyBuilder* builder = toNativeBuilder(builderPtr);
197     const void* fontPtr = env->GetDirectBufferAddress(font);
198     if (fontPtr == NULL) {
199         ALOGE("addFont failed to create font, buffer invalid");
200         builder->axes.clear();
201         return false;
202     }
203     jlong fontSize = env->GetDirectBufferCapacity(font);
204     if (fontSize < 0) {
205         ALOGE("addFont failed to create font, buffer size invalid");
206         builder->axes.clear();
207         return false;
208     }
209     jobject fontRef = MakeGlobalRefOrDie(env, font);
210     sk_sp<SkData> data(SkData::MakeWithProc(fontPtr, fontSize,
211             release_global_ref, reinterpret_cast<void*>(fontRef)));
212     return addSkTypeface(builder, std::move(data), ttcIndex, weight, isItalic);
213 }
214 
FontFamily_addAxisValue(CRITICAL_JNI_PARAMS_COMMA jlong builderPtr,jint tag,jfloat value)215 static void FontFamily_addAxisValue(CRITICAL_JNI_PARAMS_COMMA jlong builderPtr, jint tag, jfloat value) {
216     NativeFamilyBuilder* builder = toNativeBuilder(builderPtr);
217     builder->axes.push_back({static_cast<minikin::AxisTag>(tag), value});
218 }
219 
220 ///////////////////////////////////////////////////////////////////////////////
221 
222 static const JNINativeMethod gFontFamilyMethods[] = {
223     { "nInitBuilder",           "(Ljava/lang/String;I)J", (void*)FontFamily_initBuilder },
224     { "nCreateFamily",          "(J)J", (void*)FontFamily_create },
225     { "nGetBuilderReleaseFunc", "()J", (void*)FontFamily_getBuilderReleaseFunc },
226     { "nGetFamilyReleaseFunc",  "()J", (void*)FontFamily_getFamilyReleaseFunc },
227     { "nAddFont",               "(JLjava/nio/ByteBuffer;III)Z", (void*)FontFamily_addFont },
228     { "nAddFontWeightStyle",    "(JLjava/nio/ByteBuffer;III)Z",
229             (void*)FontFamily_addFontWeightStyle },
230     { "nAddAxisValue",         "(JIF)V", (void*)FontFamily_addAxisValue },
231 };
232 
register_android_graphics_FontFamily(JNIEnv * env)233 int register_android_graphics_FontFamily(JNIEnv* env)
234 {
235     int err = RegisterMethodsOrDie(env, "android/graphics/FontFamily", gFontFamilyMethods,
236             NELEM(gFontFamilyMethods));
237 
238     init_FontUtils(env);
239     return err;
240 }
241 
242 }
243