Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 38fc4f35 authored by Tyler Freeman's avatar Tyler Freeman Committed by Android (Google) Code Review
Browse files

Merge changes from topic "fontscaling-publicapi" into main

* changes:
  fix(non linear font scaling): make FontScaleConverterFactory thread-safe
  feat(non linear font scaling): optimization: cache any generated tables to reduce duplicate calculations
  feat(non linear font scaling): make FontScaleConverter APIs public
  fix(non linear font scaling): add missing @Test annotations
parents 40221e0d 6dbd9626
Loading
Loading
Loading
Loading
+10 −0
Original line number Diff line number Diff line
@@ -13657,6 +13657,16 @@ package android.content.res {
    field public int uiMode;
  }
  @FlaggedApi("android.content.res.font_scale_converter_public") public interface FontScaleConverter {
    method public float convertDpToSp(float);
    method public float convertSpToDp(float);
  }
  @FlaggedApi("android.content.res.font_scale_converter_public") public class FontScaleConverterFactory {
    method @FlaggedApi("android.content.res.font_scale_converter_public") @AnyThread @Nullable public static android.content.res.FontScaleConverter forScale(float);
    method @FlaggedApi("android.content.res.font_scale_converter_public") @AnyThread public static boolean isNonLinearFontScalingActive(float);
  }
  public class ObbInfo implements android.os.Parcelable {
    method public int describeContents();
    method public void writeToParcel(android.os.Parcel, int);
+9 −128
Original line number Diff line number Diff line
/*
 * Copyright (C) 2022 The Android Open Source Project
 * Copyright (C) 2023 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.
@@ -16,15 +16,11 @@

package android.content.res;

import android.annotation.NonNull;
import android.util.MathUtils;

import com.android.internal.annotations.VisibleForTesting;

import java.util.Arrays;
import android.annotation.FlaggedApi;

/**
 * A lookup table for non-linear font scaling. Converts font sizes given in "sp" dimensions to a
 * A converter for non-linear font scaling. Converts font sizes given in "sp" dimensions to a
 * "dp" dimension according to a non-linear curve.
 *
 * <p>This is meant to improve readability at larger font scales: larger fonts will scale up more
@@ -32,131 +28,16 @@ import java.util.Arrays;
 *
 * <p>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.
 *
 * @hide
 */
public class FontScaleConverter {

    @VisibleForTesting
    final float[] mFromSpValues;
    @VisibleForTesting
    final float[] mToDpValues;

@FlaggedApi(Flags.FLAG_FONT_SCALE_CONVERTER_PUBLIC)
public interface FontScaleConverter {
    /**
     * Creates a lookup table for the given conversions.
     *
     * <p>Any "sp" value not in the lookup table will be derived via linear interpolation.
     *
     * <p>The arrays must be sorted ascending and monotonically increasing.
     *
     * @param fromSp array of dimensions in SP
     * @param toDp array of dimensions in DP that correspond to an SP value in fromSp
     *
     * @throws IllegalArgumentException if the array lengths don't match or are empty
     * @hide
     * Converts a dimension in "sp" to "dp".
     */
    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
    public FontScaleConverter(@NonNull float[] fromSp, @NonNull float[] toDp) {
        if (fromSp.length != toDp.length || fromSp.length == 0) {
            throw new IllegalArgumentException("Array lengths must match and be nonzero");
        }

        mFromSpValues = fromSp;
        mToDpValues = toDp;
    }

    /**
     * Convert a dimension in "dp" back to "sp" using the lookup table.
     *
     * @hide
     */
    public float convertDpToSp(float dp) {
        return lookupAndInterpolate(dp, mToDpValues, mFromSpValues);
    }
    float convertSpToDp(float sp);

    /**
     * Convert a dimension in "sp" to "dp" using the lookup table.
     *
     * @hide
     * Converts a dimension in "dp" back to "sp".
     */
    public float convertSpToDp(float sp) {
        return lookupAndInterpolate(sp, mFromSpValues, mToDpValues);
    }

    private static float lookupAndInterpolate(
            float sourceValue,
            float[] sourceValues,
            float[] targetValues
    ) {
        final float sourceValuePositive = Math.abs(sourceValue);
        // TODO(b/247861374): find a match at a higher index?
        final float sign = Math.signum(sourceValue);
        // We search for exact matches only, even if it's just a little off. The interpolation will
        // handle any non-exact matches.
        final int index = Arrays.binarySearch(sourceValues, sourceValuePositive);
        if (index >= 0) {
            // exact match, return the matching dp
            return sign * targetValues[index];
        } else {
            // must be a value in between index and index + 1: interpolate.
            final int lowerIndex = -(index + 1) - 1;

            final float startSp;
            final float endSp;
            final float startDp;
            final float endDp;

            if (lowerIndex >= sourceValues.length - 1) {
                // It's past our lookup table. Determine the last elements' scaling factor and use.
                startSp = sourceValues[sourceValues.length - 1];
                startDp = targetValues[sourceValues.length - 1];

                if (startSp == 0) return 0;

                final float scalingFactor = startDp / startSp;
                return sourceValue * scalingFactor;
            } else if (lowerIndex == -1) {
                // It's smaller than the smallest value in our table. Interpolate from 0.
                startSp = 0;
                startDp = 0;
                endSp = sourceValues[0];
                endDp = targetValues[0];
            } else {
                startSp = sourceValues[lowerIndex];
                endSp = sourceValues[lowerIndex + 1];
                startDp = targetValues[lowerIndex];
                endDp = targetValues[lowerIndex + 1];
            }

            return sign
                    * MathUtils.constrainedMap(startDp, endDp, startSp, endSp, sourceValuePositive);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null) return false;
        if (!(o instanceof FontScaleConverter)) return false;
        FontScaleConverter that = (FontScaleConverter) o;
        return Arrays.equals(mFromSpValues, that.mFromSpValues)
                && Arrays.equals(mToDpValues, that.mToDpValues);
    }

    @Override
    public int hashCode() {
        int result = Arrays.hashCode(mFromSpValues);
        result = 31 * result + Arrays.hashCode(mToDpValues);
        return result;
    }

    @Override
    public String toString() {
        return "FontScaleConverter{"
                + "fromSpValues="
                + Arrays.toString(mFromSpValues)
                + ", toDpValues="
                + Arrays.toString(mToDpValues)
                + '}';
    }
    float convertDpToSp(float dp);
}
+120 −66
Original line number Diff line number Diff line
@@ -16,6 +16,8 @@

package android.content.res;

import android.annotation.AnyThread;
import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.util.MathUtils;
@@ -24,67 +26,88 @@ import android.util.SparseArray;
import com.android.internal.annotations.VisibleForTesting;

/**
 * Stores lookup tables for creating {@link FontScaleConverter}s at various scales.
 * Creates {@link FontScaleConverter}s at various scales.
 *
 * @hide
 * Generally you shouldn't need this; you can use {@link
 * android.util.TypedValue#applyDimension(int, float, DisplayMetrics)} directly and it will do the
 * scaling conversion for you. But for UI frameworks or other situations where you need to do the
 * conversion without an Android Context, you can use this class.
 */
@FlaggedApi(Flags.FLAG_FONT_SCALE_CONVERTER_PUBLIC)
public class FontScaleConverterFactory {
    private static final float SCALE_KEY_MULTIPLIER = 100f;

    /** @hide */
    // GuardedBy("LOOKUP_TABLES_WRITE_LOCK") but only for writes!
    @VisibleForTesting
    static final SparseArray<FontScaleConverter> LOOKUP_TABLES = new SparseArray<>();
    @NonNull
    public static volatile SparseArray<FontScaleConverter> sLookupTables = new SparseArray<>();

    /**
     * This is a write lock only! We don't care about synchronization on reads; they can be a bit
     * out of date. But all writes have to be atomic, so we use this similar to a
     * CopyOnWriteArrayList.
     */
    private static final Object LOOKUP_TABLES_WRITE_LOCK = new Object();

    private static float sMinScaleBeforeCurvesApplied = 1.05f;

    static {
        // These were generated by frameworks/base/tools/fonts/font-scaling-array-generator.js and
        // manually tweaked for optimum readability.
        put(
        synchronized (LOOKUP_TABLES_WRITE_LOCK) {
            putInto(
                    sLookupTables,
                    /* scaleKey= */ 1.15f,
                new FontScaleConverter(
                    new FontScaleConverterImpl(
                            /* fromSp= */
                            new float[] {   8f,   10f,   12f,   14f,   18f,   20f,   24f,   30f,  100},
                            /* toDp=   */
                            new float[] { 9.2f, 11.5f, 13.8f, 16.4f, 19.8f, 21.8f, 25.2f,   30f,  100})
            );

        put(
            putInto(
                    sLookupTables,
                    /* scaleKey= */ 1.3f,
                new FontScaleConverter(
                    new FontScaleConverterImpl(
                            /* fromSp= */
                            new float[] {   8f,   10f,   12f,   14f,   18f,   20f,   24f,   30f,  100},
                            /* toDp=   */
                            new float[] {10.4f,   13f, 15.6f, 18.8f, 21.6f, 23.6f, 26.4f,   30f,  100})
            );

        put(
            putInto(
                    sLookupTables,
                    /* scaleKey= */ 1.5f,
                new FontScaleConverter(
                    new FontScaleConverterImpl(
                            /* fromSp= */
                            new float[] {   8f,   10f,   12f,   14f,   18f,   20f,   24f,   30f,  100},
                            /* toDp=   */
                            new float[] {  12f,   15f,   18f,   22f,   24f,   26f,   28f,   30f,  100})
            );

        put(
            putInto(
                    sLookupTables,
                    /* scaleKey= */ 1.8f,
                new FontScaleConverter(
                    new FontScaleConverterImpl(
                            /* fromSp= */
                            new float[] {   8f,   10f,   12f,   14f,   18f,   20f,   24f,   30f,  100},
                            /* toDp=   */
                            new float[] {14.4f,   18f, 21.6f, 24.4f, 27.6f, 30.8f, 32.8f, 34.8f,  100})
            );

        put(
            putInto(
                    sLookupTables,
                    /* scaleKey= */ 2f,
                new FontScaleConverter(
                    new FontScaleConverterImpl(
                            /* fromSp= */
                            new float[] {   8f,   10f,   12f,   14f,   18f,   20f,   24f,   30f,  100},
                            /* toDp=   */
                            new float[] {  16f,   20f,   24f,   26f,   30f,   34f,   36f,   38f,  100})
            );
        }

        sMinScaleBeforeCurvesApplied = getScaleFromKey(LOOKUP_TABLES.keyAt(0)) - 0.02f;
        sMinScaleBeforeCurvesApplied = getScaleFromKey(sLookupTables.keyAt(0)) - 0.02f;
        if (sMinScaleBeforeCurvesApplied <= 1.0f) {
            throw new IllegalStateException(
                    "You should only apply non-linear scaling to font scales > 1"
@@ -100,9 +123,9 @@ public class FontScaleConverterFactory {
     *
     * <p>Example usage:
     * <code>isNonLinearFontScalingActive(getResources().getConfiguration().fontScale)</code>
     *
     * @hide
     */
    @FlaggedApi(Flags.FLAG_FONT_SCALE_CONVERTER_PUBLIC)
    @AnyThread
    public static boolean isNonLinearFontScalingActive(float fontScale) {
        return fontScale >= sMinScaleBeforeCurvesApplied;
    }
@@ -113,10 +136,10 @@ public class FontScaleConverterFactory {
     * @param fontScale the scale factor, usually from {@link Configuration#fontScale}.
     *
     * @return a converter for the given scale, or null if non-linear scaling should not be used.
     *
     * @hide
     */
    @FlaggedApi(Flags.FLAG_FONT_SCALE_CONVERTER_PUBLIC)
    @Nullable
    @AnyThread
    public static FontScaleConverter forScale(float fontScale) {
        if (!isNonLinearFontScalingActive(fontScale)) {
            return null;
@@ -128,23 +151,33 @@ public class FontScaleConverterFactory {
        }

        // Didn't find an exact match: interpolate between two existing tables
        final int index = LOOKUP_TABLES.indexOfKey(getKey(fontScale));
        final int index = sLookupTables.indexOfKey(getKey(fontScale));
        if (index >= 0) {
            // This should never happen, should have been covered by get() above.
            return LOOKUP_TABLES.valueAt(index);
            return sLookupTables.valueAt(index);
        }
        // Didn't find an exact match: interpolate between two existing tables
        final int lowerIndex = -(index + 1) - 1;
        final int higherIndex = lowerIndex + 1;
        if (lowerIndex < 0 || higherIndex >= LOOKUP_TABLES.size()) {
        if (lowerIndex < 0 || higherIndex >= sLookupTables.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.
            return new FontScaleConverter(new float[] {1f}, new float[] {fontScale});
            FontScaleConverterImpl converter = new FontScaleConverterImpl(
                    new float[]{1f},
                    new float[]{fontScale}
            );

            if (Flags.fontScaleConverterPublic()) {
                // Cache for next time.
                put(fontScale, converter);
            }

            return converter;
        } else {
            float startScale = getScaleFromKey(LOOKUP_TABLES.keyAt(lowerIndex));
            float endScale = getScaleFromKey(LOOKUP_TABLES.keyAt(higherIndex));
            float startScale = getScaleFromKey(sLookupTables.keyAt(lowerIndex));
            float endScale = getScaleFromKey(sLookupTables.keyAt(higherIndex));
            float interpolationPoint = MathUtils.constrainedMap(
                    /* rangeMin= */ 0f,
                    /* rangeMax= */ 1f,
@@ -152,10 +185,18 @@ public class FontScaleConverterFactory {
                    endScale,
                    fontScale
            );
            return createInterpolatedTableBetween(
                    LOOKUP_TABLES.valueAt(lowerIndex),
                    LOOKUP_TABLES.valueAt(higherIndex),
                    interpolationPoint);
            FontScaleConverter converter = createInterpolatedTableBetween(
                    sLookupTables.valueAt(lowerIndex),
                    sLookupTables.valueAt(higherIndex),
                    interpolationPoint
            );

            if (Flags.fontScaleConverterPublic()) {
                // Cache for next time.
                put(fontScale, converter);
            }

            return converter;
        }
    }

@@ -175,7 +216,7 @@ public class FontScaleConverterFactory {
            dpInterpolated[i] = MathUtils.lerp(startDp, endDp, interpolationPoint);
        }

        return new FontScaleConverter(commonSpSizes, dpInterpolated);
        return new FontScaleConverterImpl(commonSpSizes, dpInterpolated);
    }

    private static int getKey(float fontScale) {
@@ -187,11 +228,24 @@ public class FontScaleConverterFactory {
    }

    private static void put(float scaleKey, @NonNull FontScaleConverter fontScaleConverter) {
        LOOKUP_TABLES.put(getKey(scaleKey), fontScaleConverter);
        // Dollar-store CopyOnWriteSparseArray, since this is the only write op we need.
        synchronized (LOOKUP_TABLES_WRITE_LOCK) {
            var newTable = sLookupTables.clone();
            putInto(newTable, scaleKey, fontScaleConverter);
            sLookupTables = newTable;
        }
    }

    private static void putInto(
            SparseArray<FontScaleConverter> table,
            float scaleKey,
            @NonNull FontScaleConverter fontScaleConverter
    ) {
        table.put(getKey(scaleKey), fontScaleConverter);
    }

    @Nullable
    private static FontScaleConverter get(float scaleKey) {
        return LOOKUP_TABLES.get(getKey(scaleKey));
        return sLookupTables.get(getKey(scaleKey));
    }
}
+164 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2022 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 android.content.res;

import android.annotation.NonNull;
import android.util.MathUtils;

import com.android.internal.annotations.VisibleForTesting;

import java.util.Arrays;

/**
 * A lookup table for non-linear font scaling. Converts font sizes given in "sp" dimensions to a
 * "dp" dimension according to a non-linear curve by interpolating values in a lookup table.
 *
 * {@see FontScaleConverter}
 *
 * @hide
 */
// Needs to be public so the Kotlin test can see it
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public class FontScaleConverterImpl implements FontScaleConverter {

    /** @hide */
    @VisibleForTesting
    public final float[] mFromSpValues;
    /** @hide */
    @VisibleForTesting
    public final float[] mToDpValues;

    /**
     * Creates a lookup table for the given conversions.
     *
     * <p>Any "sp" value not in the lookup table will be derived via linear interpolation.
     *
     * <p>The arrays must be sorted ascending and monotonically increasing.
     *
     * @param fromSp array of dimensions in SP
     * @param toDp array of dimensions in DP that correspond to an SP value in fromSp
     *
     * @throws IllegalArgumentException if the array lengths don't match or are empty
     * @hide
     */
    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
    public FontScaleConverterImpl(@NonNull float[] fromSp, @NonNull float[] toDp) {
        if (fromSp.length != toDp.length || fromSp.length == 0) {
            throw new IllegalArgumentException("Array lengths must match and be nonzero");
        }

        mFromSpValues = fromSp;
        mToDpValues = toDp;
    }

    /**
     * Convert a dimension in "dp" back to "sp" using the lookup table.
     *
     * @hide
     */
    @Override
    public float convertDpToSp(float dp) {
        return lookupAndInterpolate(dp, mToDpValues, mFromSpValues);
    }

    /**
     * Convert a dimension in "sp" to "dp" using the lookup table.
     *
     * @hide
     */
    @Override
    public float convertSpToDp(float sp) {
        return lookupAndInterpolate(sp, mFromSpValues, mToDpValues);
    }

    private static float lookupAndInterpolate(
            float sourceValue,
            float[] sourceValues,
            float[] targetValues
    ) {
        final float sourceValuePositive = Math.abs(sourceValue);
        // TODO(b/247861374): find a match at a higher index?
        final float sign = Math.signum(sourceValue);
        // We search for exact matches only, even if it's just a little off. The interpolation will
        // handle any non-exact matches.
        final int index = Arrays.binarySearch(sourceValues, sourceValuePositive);
        if (index >= 0) {
            // exact match, return the matching dp
            return sign * targetValues[index];
        } else {
            // must be a value in between index and index + 1: interpolate.
            final int lowerIndex = -(index + 1) - 1;

            final float startSp;
            final float endSp;
            final float startDp;
            final float endDp;

            if (lowerIndex >= sourceValues.length - 1) {
                // It's past our lookup table. Determine the last elements' scaling factor and use.
                startSp = sourceValues[sourceValues.length - 1];
                startDp = targetValues[sourceValues.length - 1];

                if (startSp == 0) return 0;

                final float scalingFactor = startDp / startSp;
                return sourceValue * scalingFactor;
            } else if (lowerIndex == -1) {
                // It's smaller than the smallest value in our table. Interpolate from 0.
                startSp = 0;
                startDp = 0;
                endSp = sourceValues[0];
                endDp = targetValues[0];
            } else {
                startSp = sourceValues[lowerIndex];
                endSp = sourceValues[lowerIndex + 1];
                startDp = targetValues[lowerIndex];
                endDp = targetValues[lowerIndex + 1];
            }

            return sign
                    * MathUtils.constrainedMap(startDp, endDp, startSp, endSp, sourceValuePositive);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null) return false;
        if (!(o instanceof FontScaleConverterImpl)) return false;
        FontScaleConverterImpl that = (FontScaleConverterImpl) o;
        return Arrays.equals(mFromSpValues, that.mFromSpValues)
                && Arrays.equals(mToDpValues, that.mToDpValues);
    }

    @Override
    public int hashCode() {
        int result = Arrays.hashCode(mFromSpValues);
        result = 31 * result + Arrays.hashCode(mToDpValues);
        return result;
    }

    @Override
    public String toString() {
        return "FontScaleConverter{"
                + "fromSpValues="
                + Arrays.toString(mFromSpValues)
                + ", toDpValues="
                + Arrays.toString(mToDpValues)
                + '}';
    }
}
+9 −0
Original line number Diff line number Diff line
@@ -9,6 +9,15 @@ flag {
    is_fixed_read_only: true
}

flag {
    name: "font_scale_converter_public"
    namespace: "accessibility"
    description: "Enables the public API for FontScaleConverter, including enabling thread-safe caching."
    bug: "239736383"
    # fixed_read_only or device wont boot because of permission issues accessing flags during boot
    is_fixed_read_only: true
}

flag {
    name: "asset_file_descriptor_frro"
    namespace: "resource_manager"
Loading