1 /*
2  * Copyright (C) 2022 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 @file:OptIn(ExperimentalTextApi::class)
18 
19 package com.android.settingslib.spa.framework.theme
20 
21 import android.annotation.SuppressLint
22 import android.content.Context
23 import androidx.compose.runtime.Composable
24 import androidx.compose.ui.text.ExperimentalTextApi
25 import androidx.compose.ui.text.font.DeviceFontFamilyName
26 import androidx.compose.ui.text.font.Font
27 import androidx.compose.ui.text.font.FontFamily
28 import androidx.compose.ui.text.font.FontWeight
29 import com.android.settingslib.spa.framework.compose.rememberContext
30 
31 internal data class SettingsFontFamily(
32     val brand: FontFamily,
33     val plain: FontFamily,
34 )
35 
Contextnull36 private fun Context.getSettingsFontFamily(): SettingsFontFamily {
37     return SettingsFontFamily(
38         brand = getFontFamily(
39             configFontFamilyNormal = "config_headlineFontFamily",
40             configFontFamilyMedium = "config_headlineFontFamilyMedium",
41         ),
42         plain = getFontFamily(
43             configFontFamilyNormal = "config_bodyFontFamily",
44             configFontFamilyMedium = "config_bodyFontFamilyMedium",
45         ),
46     )
47 }
48 
Contextnull49 private fun Context.getFontFamily(
50     configFontFamilyNormal: String,
51     configFontFamilyMedium: String,
52 ): FontFamily {
53     val fontFamilyNormal = getAndroidConfig(configFontFamilyNormal)
54     val fontFamilyMedium = getAndroidConfig(configFontFamilyMedium)
55     if (fontFamilyNormal.isEmpty() || fontFamilyMedium.isEmpty()) return FontFamily.Default
56     return FontFamily(
57         Font(DeviceFontFamilyName(fontFamilyNormal), FontWeight.Normal),
58         Font(DeviceFontFamilyName(fontFamilyMedium), FontWeight.Medium),
59     )
60 }
61 
Contextnull62 private fun Context.getAndroidConfig(configName: String): String {
63     @SuppressLint("DiscouragedApi")
64     val configId = resources.getIdentifier(configName, "string", "android")
65     return resources.getString(configId)
66 }
67 
68 @Composable
rememberSettingsFontFamilynull69 internal fun rememberSettingsFontFamily(): SettingsFontFamily {
70     return rememberContext(Context::getSettingsFontFamily)
71 }
72