forked from androidx/androidx
-
Notifications
You must be signed in to change notification settings - Fork 93
Non-linear font scaling #1867
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
alexzhirkevich
wants to merge
9
commits into
JetBrains:jb-main
Choose a base branch
from
alexzhirkevich:non-linear-font-scaling
base: jb-main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Non-linear font scaling #1867
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
10e829b
non linear font scaling
alexzhirkevich 5bbed37
add test
alexzhirkevich f902655
write lock
alexzhirkevich 60dc3f7
cleanup
alexzhirkevich d1c90ae
copy-on-write lookup tables
alexzhirkevich fe8976e
copy-on-write lookup tables
alexzhirkevich 3cd3c04
api dump
alexzhirkevich a8babf4
review fix
alexzhirkevich b180a3e
more tests
alexzhirkevich File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
compose/ui/ui-unit/src/desktopMain/kotlin/androidx/compose/ui/unit/FontScaling.desktop.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
/* | ||
* Copyright 2025 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package androidx.compose.ui.unit | ||
|
||
import androidx.compose.ui.unit.fontscaling.FontScaleConverter | ||
|
||
internal actual fun isNonLinearFontScalingActive(fontScale: Float): Boolean = false | ||
|
||
internal actual fun defaultFontScaleConverters() : Map<Float, FontScaleConverter> = emptyMap() | ||
|
||
internal actual val NonLinearFontSizeAnchors : List<Float> get() = emptyList() |
41 changes: 41 additions & 0 deletions
41
compose/ui/ui-unit/src/jbMain/kotlin/androidx/compose/ui/unit/Density.jb.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
/* | ||
* Copyright 2025 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package androidx.compose.ui.unit | ||
|
||
import androidx.compose.ui.unit.fontscaling.FontScaleConverter | ||
|
||
internal data class DensityWithConverter( | ||
override val density: Float, | ||
override val fontScale: Float, | ||
private val converter: FontScaleConverter | ||
) : Density { | ||
|
||
override fun Dp.toSp(): TextUnit { | ||
return converter.convertDpToSp(value).sp | ||
} | ||
|
||
override fun TextUnit.toDp(): Dp { | ||
check(type == TextUnitType.Sp) { "Only Sp can convert to Px" } | ||
return Dp(converter.convertSpToDp(value)) | ||
} | ||
} | ||
|
||
internal data class LinearFontScaleConverter(private val fontScale: Float) : FontScaleConverter { | ||
override fun convertSpToDp(sp: Float) = sp * fontScale | ||
|
||
override fun convertDpToSp(dp: Float) = dp / fontScale | ||
} |
77 changes: 77 additions & 0 deletions
77
compose/ui/ui-unit/src/jbMain/kotlin/androidx/compose/ui/unit/FontScaling.jb.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
/* | ||
* Copyright 2025 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package androidx.compose.ui.unit | ||
|
||
import androidx.compose.runtime.Immutable | ||
import androidx.compose.runtime.Stable | ||
import androidx.compose.ui.unit.fontscaling.FontScaleConverter | ||
import androidx.compose.ui.unit.fontscaling.FontScaleConverterFactory | ||
import androidx.compose.ui.unit.internal.JvmDefaultWithCompatibility | ||
|
||
/** | ||
* Converts [TextUnit] to [Dp] and vice-versa. | ||
* | ||
* Note that the converter can't be cached in the interface itself. FontScaleConverterFactory | ||
* already caches the tables, but it still does a a map lookup for each conversion. If you are | ||
* implementing this interface, you should cache your own converter for additional speed. | ||
*/ | ||
@Immutable | ||
@JvmDefaultWithCompatibility | ||
actual interface FontScaling { | ||
alexzhirkevich marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** Current user preference for the scaling factor for fonts. */ | ||
@Stable actual val fontScale: Float | ||
|
||
/** Convert [Dp] to Sp. Sp is used for font size, etc. */ | ||
@Stable | ||
actual fun Dp.toSp(): TextUnit { | ||
if (!isNonLinearFontScalingActive(fontScale)) { | ||
return (value / fontScale).sp | ||
} | ||
|
||
val converter = FontScaleConverterFactory.forScale(fontScale) | ||
return (converter?.convertDpToSp(value) ?: (value / fontScale)).sp | ||
} | ||
|
||
/** | ||
* Convert Sp to [Dp]. | ||
* | ||
* @throws IllegalStateException if TextUnit other than SP unit is specified. | ||
*/ | ||
@Stable | ||
actual fun TextUnit.toDp(): Dp { | ||
checkPrecondition(type == TextUnitType.Sp) { "Only Sp can convert to Px" } | ||
if (!isNonLinearFontScalingActive(fontScale)) { | ||
return Dp(value * fontScale) | ||
} | ||
|
||
val converter = FontScaleConverterFactory.forScale(fontScale) | ||
?: return Dp(value * fontScale) | ||
|
||
return Dp(converter.convertSpToDp(value)) | ||
} | ||
} | ||
|
||
/** | ||
* Returns true if non-linear font scaling curves would be in effect for the given scale, false | ||
* if the scaling would follow a linear curve or for no scaling. | ||
*/ | ||
internal expect fun isNonLinearFontScalingActive(fontScale: Float): Boolean | ||
|
||
internal expect val NonLinearFontSizeAnchors : List<Float> | ||
|
||
internal expect fun defaultFontScaleConverters() : Map<Float, FontScaleConverter> |
35 changes: 35 additions & 0 deletions
35
...i/ui-unit/src/jbMain/kotlin/androidx/compose/ui/unit/fontscaling/FontScaleConverter.jb.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/* | ||
* Copyright 2025 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package androidx.compose.ui.unit.fontscaling | ||
|
||
|
||
/** | ||
* A converter for non-linear font scaling. Converts font sizes given in "sp" dimensions to a "dp" | ||
* dimension according to a non-linear curve. | ||
* | ||
* This is meant to improve readability at larger font scales: larger fonts will scale up more | ||
* slowly than smaller fonts, so we don't get ridiculously huge fonts that don't fit on the screen. | ||
* | ||
* The thinking here is that large fonts are already big enough to read, but we still want to scale | ||
* them slightly to preserve the visual hierarchy when compared to smaller fonts. | ||
*/ | ||
internal interface FontScaleConverter { | ||
/** Converts a dimension in "sp" to "dp". */ | ||
fun convertSpToDp(sp: Float): Float | ||
|
||
/** Converts a dimension in "dp" back to "sp". */ | ||
fun convertDpToSp(dp: Float): Float | ||
} |
117 changes: 117 additions & 0 deletions
117
...it/src/jbMain/kotlin/androidx/compose/ui/unit/fontscaling/FontScaleConverterFactory.jb.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
/* | ||
* Copyright 2025 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package androidx.compose.ui.unit.fontscaling | ||
|
||
import androidx.collection.SparseArrayCompat | ||
import androidx.collection.forEach | ||
import androidx.collection.size | ||
import androidx.compose.ui.unit.NonLinearFontSizeAnchors | ||
import androidx.compose.ui.unit.defaultFontScaleConverters | ||
import androidx.compose.ui.unit.isNonLinearFontScalingActive | ||
import androidx.compose.ui.util.lerp | ||
import kotlinx.atomicfu.locks.reentrantLock | ||
import kotlinx.atomicfu.locks.withLock | ||
|
||
internal object FontScaleConverterFactory { | ||
|
||
private const val ScaleKeyMultiplier = 100f | ||
|
||
private val lookupTablesWriteLock = reentrantLock() | ||
|
||
private var lookupTables = SparseArrayCompat<FontScaleConverter>().apply { | ||
lookupTablesWriteLock.withLock { | ||
defaultFontScaleConverters().forEach { (scale, converter) -> | ||
put(getKey(scale), converter) | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Finds a matching FontScaleConverter for the given fontScale factor. | ||
*/ | ||
fun forScale(fontScale: Float): FontScaleConverter? { | ||
if (!isNonLinearFontScalingActive(fontScale)) { | ||
return null | ||
} | ||
|
||
val index = lookupTables.indexOfKey(getKey(fontScale)) | ||
if (index >= 0) { | ||
return lookupTables.valueAt(index) | ||
} | ||
// Didn't find an exact match: interpolate between two existing tables | ||
val lowerIndex = -(index + 1) - 1 | ||
val higherIndex = lowerIndex + 1 | ||
val converter = if (higherIndex >= lookupTables.size()) { | ||
// We have gone beyond our bounds and have nothing to interpolate between. | ||
// Just give them a straight linear table instead. | ||
// This works because when FontScaleConverter encounters a size beyond its bounds, it | ||
// calculates a linear fontScale factor using the ratio of the last element pair. | ||
FontScaleConverterTable(listOf(1f), listOf(fontScale)) | ||
} else { | ||
val (startScale, startTable) = if (lowerIndex < 0) { | ||
// if we're in between 1x and the first table, interpolate between them. | ||
// (See b/336720383) | ||
1f to FontScaleConverterTable(NonLinearFontSizeAnchors, NonLinearFontSizeAnchors) | ||
} else { | ||
getScaleFromKey(lookupTables.keyAt(lowerIndex)) to lookupTables.valueAt(lowerIndex) | ||
} | ||
|
||
val endScale = getScaleFromKey(lookupTables.keyAt(higherIndex)) | ||
|
||
createInterpolatedTableBetween( | ||
startTable, | ||
lookupTables.valueAt(higherIndex), | ||
constrainedMap(0f, 1f, startScale, endScale, fontScale) | ||
) | ||
} | ||
|
||
put(fontScale, converter) | ||
|
||
return converter | ||
} | ||
|
||
private fun createInterpolatedTableBetween( | ||
start: FontScaleConverter, | ||
end: FontScaleConverter, | ||
interpolationPoint: Float | ||
): FontScaleConverter = FontScaleConverterTable( | ||
fromSp = NonLinearFontSizeAnchors, | ||
toDp = NonLinearFontSizeAnchors.map { sp -> | ||
lerp(start.convertSpToDp(sp), end.convertSpToDp(sp), interpolationPoint) | ||
} | ||
) | ||
|
||
|
||
private fun getKey(fontScale: Float): Int { | ||
return (fontScale * ScaleKeyMultiplier).toInt() | ||
} | ||
|
||
private fun getScaleFromKey(key: Int): Float { | ||
return key.toFloat() / ScaleKeyMultiplier | ||
} | ||
|
||
private fun put(scaleKey: Float, fontScaleConverter: FontScaleConverter) { | ||
lookupTablesWriteLock.withLock { | ||
// copy-on-write to safely omit reading synchronization | ||
val copy = SparseArrayCompat<FontScaleConverter>(lookupTables.size + 1) | ||
lookupTables.forEach { key, value -> | ||
copy.put(key, value) | ||
} | ||
copy.put(getKey(scaleKey), fontScaleConverter) | ||
lookupTables = copy | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Isn't it a breaking change (for binary compatibility)?
cc @igordmn