Skip to content

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
wants to merge 9 commits into
base: jb-main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion compose/ui/ui-unit/api/desktop/ui-unit.api
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public final class androidx/compose/ui/unit/ConstraintsKt {
public static synthetic fun offset-NN6Ew-U$default (JIIILjava/lang/Object;)J
}

public abstract interface class androidx/compose/ui/unit/Density : androidx/compose/ui/unit/FontScalingLinear {
public abstract interface class androidx/compose/ui/unit/Density : androidx/compose/ui/unit/FontScaling {
Copy link
Member

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

public abstract fun getDensity ()F
public fun roundToPx--R2X_6o (J)I
public fun roundToPx-0680j_4 (F)I
Expand Down Expand Up @@ -233,6 +233,17 @@ public final class androidx/compose/ui/unit/DpSize$Companion {
public abstract interface annotation class androidx/compose/ui/unit/ExperimentalUnitApi : java/lang/annotation/Annotation {
}

public abstract interface class androidx/compose/ui/unit/FontScaling {
public abstract fun getFontScale ()F
public fun toDp-GaN1DYA (J)F
public fun toSp-0xMU5do (F)J
}

public final class androidx/compose/ui/unit/FontScaling$DefaultImpls {
public static fun toDp-GaN1DYA (Landroidx/compose/ui/unit/FontScaling;J)F
public static fun toSp-0xMU5do (Landroidx/compose/ui/unit/FontScaling;F)J
}

public abstract interface class androidx/compose/ui/unit/FontScalingLinear {
public abstract fun getFontScale ()F
public fun toDp-GaN1DYA (J)F
Expand Down
11 changes: 10 additions & 1 deletion compose/ui/ui-unit/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ if(AndroidXComposePlugin.isMultiplatformEnabled(project)) {
api(project(":compose:ui:ui-geometry"))

implementation(project(":annotation:annotation"))
implementation(project(":collection:collection"))
implementation(project(":compose:runtime:runtime"))
implementation(project(":compose:ui:ui-util"))
}
Expand All @@ -88,18 +89,26 @@ if(AndroidXComposePlugin.isMultiplatformEnabled(project)) {
api("androidx.annotation:annotation:1.1.0")
}

jbMain.dependsOn(commonMain)
jbMain {
dependsOn(commonMain)
dependencies {
implementation(libs.atomicFu)
}
}
desktopMain.dependsOn(jbMain)
jsNativeMain.dependsOn(jbMain)
jsMain.dependsOn(jsNativeMain)
nativeMain.dependsOn(jsNativeMain)
jsWasmMain.dependsOn(jbMain)

jsMain {
dependsOn(jsNativeMain)
dependsOn(jsWasmMain)
}

wasmJsMain {
dependsOn(jsNativeMain)
dependsOn(jsWasmMain)
dependencies {
implementation(libs.kotlinStdlib)
}
Expand Down
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()
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
}
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 {

/** 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>
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
}
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
}
}
}
Loading