1 /*
2  * Copyright 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 package androidx.compose.ui.text
18 
19 import androidx.compose.runtime.Composable
20 import androidx.compose.runtime.remember
21 import androidx.compose.ui.platform.LocalDensity
22 import androidx.compose.ui.platform.LocalFontFamilyResolver
23 import androidx.compose.ui.platform.LocalLayoutDirection
24 
25 /** This value should reflect the default cache size for TextMeasurer. */
26 private val DefaultCacheSize: Int = 8
27 
28 /**
29  * Creates and remembers a [TextMeasurer]. All parameters that are required for [TextMeasurer]
30  * except [cacheSize] are read from CompositionLocals. Created [TextMeasurer] carries an internal
31  * [TextLayoutCache] with [cacheSize] capacity. Provide 0 for [cacheSize] to opt-out from internal
32  * caching behavior.
33  *
34  * @param cacheSize Capacity of internal cache inside [TextMeasurer]. Size unit is the number of
35  *   unique text layout inputs that are measured. Value of this parameter highly depends on the
36  *   consumer use case. Provide a cache size that is in line with how many distinct text layouts are
37  *   going to be calculated by this measurer repeatedly. If you are animating font attributes, or
38  *   any other layout affecting input, cache can be skipped because most repeated measure calls
39  *   would miss the cache.
40  */
41 @Composable
rememberTextMeasurernull42 fun rememberTextMeasurer(cacheSize: Int = DefaultCacheSize): TextMeasurer {
43     val fontFamilyResolver = LocalFontFamilyResolver.current
44     val density = LocalDensity.current
45     val layoutDirection = LocalLayoutDirection.current
46 
47     return remember(fontFamilyResolver, density, layoutDirection, cacheSize) {
48         TextMeasurer(fontFamilyResolver, density, layoutDirection, cacheSize)
49     }
50 }
51