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

Commit 6efdab9f authored by Joanne Chung's avatar Joanne Chung Committed by Android (Google) Code Review
Browse files

Merge "Remove ConfigParser from TextClassificationConstants."

parents baccb2d0 c44f529a
Loading
Loading
Loading
Loading
+6 −19
Original line number Diff line number Diff line
@@ -37,7 +37,6 @@ import android.os.IBinder;
import android.os.Looper;
import android.os.Parcelable;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Slog;
import android.view.textclassifier.ConversationActions;
@@ -437,28 +436,16 @@ public abstract class TextClassifierService extends Service {
    /**
     * Returns the component name of the system default textclassifier service if it can be found
     * on the system. Otherwise, returns null.
     * @hide
     */
    public static ComponentName getServiceComponentName(@NonNull Context context) {
        return getServiceComponentName(context, new TextClassificationConstants(
                () -> Settings.Global.getString(
                        context.getContentResolver(),
                        Settings.Global.TEXT_CLASSIFIER_CONSTANTS)));
    }

    /**
     * Returns the component name of the system default textclassifier service if it can be found
     * on the system. Otherwise, returns null.
     * @param context the text classification context
     * @param settings TextClassifier specific settings.
     *
     * @param context the text classification context
     * @hide
     */
    @Nullable
    public static ComponentName getServiceComponentName(@NonNull Context context,
            @NonNull TextClassificationConstants settings) {
    public static ComponentName getServiceComponentName(@NonNull Context context) {
        final TextClassificationConstants settings = TextClassificationManager.getSettings(context);
        // get override TextClassifierService package name
        String packageName = settings.getTextClassifierServiceName();
        String packageName = settings.getTextClassifierServicePackageOverride();

        ComponentName serviceComponent = null;
        final boolean isOverrideService = !TextUtils.isEmpty(packageName);
        if (isOverrideService) {
@@ -468,7 +455,7 @@ public abstract class TextClassifierService extends Service {
        if (serviceComponent != null) {
            return serviceComponent;
        }
        // If no TextClassifierService overrode or invalid override package name, read the first
        // If no TextClassifierService override or invalid override package name, read the first
        // package defined in the config
        final String[] packages = context.getPackageManager().getSystemTextClassifierPackages();
        if (packages.length == 0 || TextUtils.isEmpty(packages[0])) {
+0 −264
Original line number Diff line number Diff line
/*
 * Copyright (C) 2019 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.view.textclassifier;

import android.annotation.Nullable;
import android.provider.DeviceConfig;
import android.util.ArrayMap;
import android.util.KeyValueListParser;

import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.annotations.VisibleForTesting.Visibility;
import com.android.internal.util.Preconditions;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * Retrieves settings from {@link DeviceConfig} and {@link android.provider.Settings}.
 * It will try DeviceConfig first and then Settings.
 *
 * @hide
 */
@VisibleForTesting(visibility = Visibility.PACKAGE)
public final class ConfigParser {
    private static final String TAG = "ConfigParser";

    public static final boolean ENABLE_DEVICE_CONFIG = true;

    private static final String STRING_LIST_DELIMITER = ":";

    private final Supplier<String> mLegacySettingsSupplier;
    private final Object mLock = new Object();
    @GuardedBy("mLock")
    private final Map<String, Object> mCache = new ArrayMap<>();
    @GuardedBy("mLock")
    private @Nullable KeyValueListParser mSettingsParser;  // Call getLegacySettings() instead.

    public ConfigParser(Supplier<String> legacySettingsSupplier) {
        mLegacySettingsSupplier = Preconditions.checkNotNull(legacySettingsSupplier);
    }

    private KeyValueListParser getLegacySettings() {
        synchronized (mLock) {
            if (mSettingsParser == null) {
                final String legacySettings = mLegacySettingsSupplier.get();
                try {
                    mSettingsParser = new KeyValueListParser(',');
                    mSettingsParser.setString(legacySettings);
                } catch (IllegalArgumentException e) {
                    // Failed to parse the settings string, log this and move on with defaults.
                    Log.w(TAG, "Bad text_classifier_constants: " + legacySettings);
                }
            }
            return mSettingsParser;
        }
    }

    /**
     * Reads a boolean setting through the cache.
     */
    public boolean getBoolean(String key, boolean defaultValue) {
        synchronized (mLock) {
            final Object cached = mCache.get(key);
            if (cached instanceof Boolean) {
                return (boolean) cached;
            }
            final boolean value;
            if (ENABLE_DEVICE_CONFIG) {
                value = DeviceConfig.getBoolean(
                        DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                        key,
                        getLegacySettings().getBoolean(key, defaultValue));
            } else {
                value = getLegacySettings().getBoolean(key, defaultValue);
            }
            mCache.put(key, value);
            return value;
        }
    }

    /**
     * Reads an integer setting through the cache.
     */
    public int getInt(String key, int defaultValue) {
        synchronized (mLock) {
            final Object cached = mCache.get(key);
            if (cached instanceof Integer) {
                return (int) cached;
            }
            final int value;
            if (ENABLE_DEVICE_CONFIG) {
                value = DeviceConfig.getInt(
                        DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                        key,
                        getLegacySettings().getInt(key, defaultValue));
            } else {
                value = getLegacySettings().getInt(key, defaultValue);
            }
            mCache.put(key, value);
            return value;
        }
    }

    /**
     * Reads a float setting through the cache.
     */
    public float getFloat(String key, float defaultValue) {
        synchronized (mLock) {
            final Object cached = mCache.get(key);
            if (cached instanceof Float) {
                return (float) cached;
            }
            final float value;
            if (ENABLE_DEVICE_CONFIG) {
                value = DeviceConfig.getFloat(
                        DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                        key,
                        getLegacySettings().getFloat(key, defaultValue));
            } else {
                value = getLegacySettings().getFloat(key, defaultValue);
            }
            mCache.put(key, value);
            return value;
        }
    }

    /**
     * Reads a string setting through the cache.
     */
    public String getString(String key, String defaultValue) {
        synchronized (mLock) {
            final Object cached = mCache.get(key);
            if (cached instanceof String) {
                return (String) cached;
            }
            final String value;
            if (ENABLE_DEVICE_CONFIG) {
                value = DeviceConfig.getString(
                        DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                        key,
                        getLegacySettings().getString(key, defaultValue));
            } else {
                value = getLegacySettings().getString(key, defaultValue);
            }
            mCache.put(key, value);
            return value;
        }
    }

    /**
     * Reads a string list setting through the cache.
     */
    public List<String> getStringList(String key, List<String> defaultValue) {
        synchronized (mLock) {
            final Object cached = mCache.get(key);
            if (cached instanceof List) {
                final List asList = (List) cached;
                if (asList.isEmpty()) {
                    return Collections.emptyList();
                } else if (asList.get(0) instanceof String) {
                    return (List<String>) cached;
                }
            }
            final List<String> value;
            if (ENABLE_DEVICE_CONFIG) {
                value = getDeviceConfigStringList(
                        key,
                        getSettingsStringList(key, defaultValue));
            } else {
                value = getSettingsStringList(key, defaultValue);
            }
            mCache.put(key, value);
            return value;
        }
    }

    /**
     * Reads a float array through the cache. The returned array should be expected to be of the
     * same length as that of the defaultValue.
     */
    public float[] getFloatArray(String key, float[] defaultValue) {
        synchronized (mLock) {
            final Object cached = mCache.get(key);
            if (cached instanceof float[]) {
                return (float[]) cached;
            }
            final float[] value;
            if (ENABLE_DEVICE_CONFIG) {
                value = getDeviceConfigFloatArray(
                        key,
                        getSettingsFloatArray(key, defaultValue));
            } else {
                value = getSettingsFloatArray(key, defaultValue);
            }
            mCache.put(key, value);
            return value;
        }
    }

    private List<String> getSettingsStringList(String key, List<String> defaultValue) {
        return parse(mSettingsParser.getString(key, null), defaultValue);
    }

    private static List<String> getDeviceConfigStringList(String key, List<String> defaultValue) {
        return parse(
                DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key, null),
                defaultValue);
    }

    private static float[] getDeviceConfigFloatArray(String key, float[] defaultValue) {
        return parse(
                DeviceConfig.getString(DeviceConfig.NAMESPACE_TEXTCLASSIFIER, key, null),
                defaultValue);
    }

    private float[] getSettingsFloatArray(String key, float[] defaultValue) {
        return parse(mSettingsParser.getString(key, null), defaultValue);
    }

    private static List<String> parse(@Nullable String listStr, List<String> defaultValue) {
        if (listStr != null) {
            return Collections.unmodifiableList(
                    Arrays.asList(listStr.split(STRING_LIST_DELIMITER)));
        }
        return defaultValue;
    }

    private static float[] parse(@Nullable String arrayStr, float[] defaultValue) {
        if (arrayStr != null) {
            final String[] split = arrayStr.split(STRING_LIST_DELIMITER);
            if (split.length != defaultValue.length) {
                return defaultValue;
            }
            final float[] result = new float[split.length];
            for (int i = 0; i < split.length; i++) {
                try {
                    result[i] = Float.parseFloat(split[i]);
                } catch (NumberFormatException e) {
                    return defaultValue;
                }
            }
            return result;
        } else {
            return defaultValue;
        }
    }
}
+103 −84

File changed.

Preview size limit exceeded, changes collapsed.

+22 −35
Original line number Diff line number Diff line
@@ -22,11 +22,9 @@ import android.annotation.SystemService;
import android.annotation.UnsupportedAppUsage;
import android.app.ActivityThread;
import android.content.Context;
import android.database.ContentObserver;
import android.os.ServiceManager;
import android.provider.DeviceConfig;
import android.provider.DeviceConfig.Properties;
import android.provider.Settings;
import android.service.textclassifier.TextClassifierService;
import android.view.textclassifier.TextClassifier.TextClassifierType;

@@ -36,6 +34,7 @@ import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.Preconditions;

import java.lang.ref.WeakReference;
import java.util.Set;

/**
 * Interface to the text classification service.
@@ -46,7 +45,7 @@ public final class TextClassificationManager {
    private static final String LOG_TAG = "TextClassificationManager";

    private static final TextClassificationConstants sDefaultSettings =
            new TextClassificationConstants(() ->  null);
            new TextClassificationConstants();

    private final Object mLock = new Object();
    private final TextClassificationSessionFactory mDefaultSessionFactory =
@@ -132,10 +131,7 @@ public final class TextClassificationManager {
    private TextClassificationConstants getSettings() {
        synchronized (mLock) {
            if (mSettings == null) {
                mSettings = new TextClassificationConstants(
                        () ->  Settings.Global.getString(
                                getApplicationContext().getContentResolver(),
                                Settings.Global.TEXT_CLASSIFIER_CONSTANTS));
                mSettings = new TextClassificationConstants();
            }
            return mSettings;
        }
@@ -201,12 +197,8 @@ public final class TextClassificationManager {
        try {
            // Note that fields could be null if the constructor threw.
            if (mSettingsObserver != null) {
                getApplicationContext().getContentResolver()
                        .unregisterContentObserver(mSettingsObserver);
                if (ConfigParser.ENABLE_DEVICE_CONFIG) {
                DeviceConfig.removeOnPropertiesChangedListener(mSettingsObserver);
            }
            }
        } finally {
            super.finalize();
        }
@@ -250,7 +242,7 @@ public final class TextClassificationManager {

    private boolean isSystemTextClassifierEnabled() {
        return getSettings().isSystemTextClassifierEnabled()
                && TextClassifierService.getServiceComponentName(mContext, getSettings()) != null;
                && TextClassifierService.getServiceComponentName(mContext) != null;
    }

    /** @hide */
@@ -262,6 +254,12 @@ public final class TextClassificationManager {
    private void invalidate() {
        synchronized (mLock) {
            mSettings = null;
            invalidateTextClassifiers();
        }
    }

    private void invalidateTextClassifiers() {
        synchronized (mLock) {
            mLocalTextClassifier = null;
            mSystemTextClassifier = null;
        }
@@ -293,40 +291,29 @@ public final class TextClassificationManager {
        }
    }

    private static final class SettingsObserver extends ContentObserver
            implements DeviceConfig.OnPropertiesChangedListener {
    private static final class SettingsObserver implements
            DeviceConfig.OnPropertiesChangedListener {

        private final WeakReference<TextClassificationManager> mTcm;

        SettingsObserver(TextClassificationManager tcm) {
            super(null);
            mTcm = new WeakReference<>(tcm);
            tcm.getApplicationContext().getContentResolver().registerContentObserver(
                    Settings.Global.getUriFor(Settings.Global.TEXT_CLASSIFIER_CONSTANTS),
                    false /* notifyForDescendants */,
                    this);
            if (ConfigParser.ENABLE_DEVICE_CONFIG) {
            DeviceConfig.addOnPropertiesChangedListener(
                    DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                    ActivityThread.currentApplication().getMainExecutor(),
                    this);
        }
        }

        @Override
        public void onChange(boolean selfChange) {
            invalidateSettings();
        }

        @Override
        public void onPropertiesChanged(Properties properties) {
            invalidateSettings();
        }

        private void invalidateSettings() {
            final TextClassificationManager tcm = mTcm.get();
            if (tcm != null) {
                tcm.invalidate();
                final Set<String> keys = properties.getKeyset();
                if (keys.contains(TextClassificationConstants.SYSTEM_TEXT_CLASSIFIER_ENABLED)
                        || keys.contains(
                        TextClassificationConstants.LOCAL_TEXT_CLASSIFIER_ENABLED)) {
                    tcm.invalidateTextClassifiers();
                }
            }
        }
    }
+0 −138
Original line number Diff line number Diff line
/*
 * Copyright (C) 2019 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.view.textclassifier;

import static com.google.common.truth.Truth.assertThat;

import android.provider.DeviceConfig;
import android.support.test.uiautomator.UiDevice;

import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.IOException;
import java.util.function.Supplier;

@SmallTest
@RunWith(AndroidJUnit4.class)
public class ConfigParserTest {
    private static final Supplier<String> SETTINGS =
            () -> "int=42,float=12.3,boolean=true,string=abc";
    private static final String CLEAR_DEVICE_CONFIG_KEY_CMD =
            "device_config delete " + DeviceConfig.NAMESPACE_TEXTCLASSIFIER;
    private static final String[] DEVICE_CONFIG_KEYS = new String[]{
            "boolean",
            "string",
            "int",
            "float"
    };

    private ConfigParser mConfigParser;

    @Before
    public void setup() throws IOException {
        mConfigParser = new ConfigParser(SETTINGS);
        clearDeviceConfig();
    }

    @After
    public void tearDown() throws IOException {
        clearDeviceConfig();
    }

    @Test
    public void getBoolean_deviceConfig() {
        DeviceConfig.setProperty(
                DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                "boolean",
                "false",
                false);
        boolean value = mConfigParser.getBoolean("boolean", true);
        assertThat(value).isFalse();
    }

    @Test
    public void getBoolean_settings() {
        boolean value = mConfigParser.getBoolean(
                "boolean",
                false);
        assertThat(value).isTrue();
    }

    @Test
    public void getInt_deviceConfig() {
        DeviceConfig.setProperty(
                DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                "int",
                "1",
                false);
        int value = mConfigParser.getInt("int", 0);
        assertThat(value).isEqualTo(1);
    }

    @Test
    public void getInt_settings() {
        int value = mConfigParser.getInt("int", 0);
        assertThat(value).isEqualTo(42);
    }

    @Test
    public void getFloat_deviceConfig() {
        DeviceConfig.setProperty(
                DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                "float",
                "3.14",
                false);
        float value = mConfigParser.getFloat("float", 0);
        assertThat(value).isWithin(0.0001f).of(3.14f);
    }

    @Test
    public void getFloat_settings() {
        float value = mConfigParser.getFloat("float", 0);
        assertThat(value).isWithin(0.0001f).of(12.3f);
    }

    @Test
    public void getString_deviceConfig() {
        DeviceConfig.setProperty(
                DeviceConfig.NAMESPACE_TEXTCLASSIFIER,
                "string",
                "hello",
                false);
        String value = mConfigParser.getString("string", "");
        assertThat(value).isEqualTo("hello");
    }

    @Test
    public void getString_settings() {
        String value = mConfigParser.getString("string", "");
        assertThat(value).isEqualTo("abc");
    }

    private static void clearDeviceConfig() throws IOException {
        UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        for (String key : DEVICE_CONFIG_KEYS) {
            uiDevice.executeShellCommand(CLEAR_DEVICE_CONFIG_KEY_CMD + " " + key);
        }
    }
}
Loading