1 /*
2  * Copyright 2019 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 package androidx.compose.ui.platform
18 
19 import android.content.Context
20 import android.graphics.Typeface
21 import android.os.Build
22 import androidx.annotation.RequiresApi
23 import androidx.compose.ui.text.font.Font
24 import androidx.compose.ui.text.font.ResourceFont
25 import androidx.core.content.res.ResourcesCompat
26 
27 /** Android implementation for [Font.ResourceLoader]. It is designed to load only [ResourceFont]. */
28 @Suppress("DEPRECATION", "OverridingDeprecatedMember")
29 @Deprecated(
30     "Replaced with PlatformFontLoader during the introduction of async fonts, all" +
31         " usages should be replaced",
32     ReplaceWith("PlatformFontLoader"),
33 )
34 internal class AndroidFontResourceLoader(private val context: Context) : Font.ResourceLoader {
35 
36     @Deprecated(
37         "Replaced by FontFamily.Resolver, this method should not be called",
38         replaceWith = ReplaceWith("FontFamily.Resolver.resolve(font, )")
39     )
loadnull40     override fun load(font: Font): Typeface {
41         return when (font) {
42             is ResourceFont ->
43                 if (Build.VERSION.SDK_INT >= 26) {
44                     AndroidFontResourceLoaderHelper.create(context, font.resId)
45                 } else {
46                     ResourcesCompat.getFont(context, font.resId)!!
47                 }
48             else -> throw IllegalArgumentException("Unknown font type: $font")
49         }
50     }
51 }
52 
53 /**
54  * This class is here to ensure that the classes that use this API will get verified and can be AOT
55  * compiled. It is expected that this class will soft-fail verification, but the classes which use
56  * this method will pass.
57  */
58 @RequiresApi(26)
59 private object AndroidFontResourceLoaderHelper {
60     @RequiresApi(26)
createnull61     fun create(context: Context, resourceId: Int): Typeface {
62         return context.resources.getFont(resourceId)
63     }
64 }
65