Move PeakRefreshRateController to Settings app

1. 60/90 Hz switch
2. Allow DeviceConfig to change default refresh rate

bug: 139869828
bug: 137064289
bug: 132750102

Test: Check refresh rate is expected.
Change-Id: Ia6a3e3717fd8845c7177e55b70bc6d2d952d58f3
diff --git a/res/values/config.xml b/res/values/config.xml
index 876af37..746d3e7 100755
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -459,4 +459,7 @@
 
     <!-- Whether to show Enhanced Connectivity switch in Developer Options -->
     <bool name="config_show_enhanced_connectivity">false</bool>
+
+    <!-- Whether to show Smooth Display feature in Settings Options -->
+    <bool name="config_show_smooth_display">false</bool>
 </resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 369115c..0d1f3d7 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -2746,6 +2746,10 @@
     <string name="display_white_balance_title">Display white balance</string>
     <!-- Display settings screen, display white balance settings summary [CHAR LIMIT=NONE] -->
     <string name="display_white_balance_summary"></string>
+    <!-- Display settings screen, peak refresh rate settings title [CHAR LIMIT=30] -->
+    <string name="peak_refresh_rate_title">Smooth Display</string>
+    <!-- Display settings screen, peak refresh rate settings summary [CHAR LIMIT=NONE] -->
+    <string name="peak_refresh_rate_summary">Automatically raises the refresh rate from 60 to 90 Hz for some content. Increases battery usage.</string>
     <!-- Display settings screen, setting option name to enable adaptive sleep [CHAR LIMIT=30] -->
     <string name="adaptive_sleep_title">Screen attention</string>
     <!-- Setting option summary when adaptive sleep is on [CHAR LIMIT=NONE] -->
diff --git a/res/xml/display_settings.xml b/res/xml/display_settings.xml
index d463a84..30dad01 100644
--- a/res/xml/display_settings.xml
+++ b/res/xml/display_settings.xml
@@ -97,6 +97,12 @@
         android:summary="@string/display_white_balance_summary"
         settings:controller="com.android.settings.display.DisplayWhiteBalancePreferenceController" />
 
+    <SwitchPreference
+        android:key="peak_refresh_rate"
+        android:title="@string/peak_refresh_rate_title"
+        android:summary="@string/peak_refresh_rate_summary"
+        settings:controller="com.android.settings.display.PeakRefreshRatePreferenceController" />
+
     <Preference
         android:key="font_size"
         android:title="@string/title_font_size"
diff --git a/src/com/android/settings/display/PeakRefreshRatePreferenceController.java b/src/com/android/settings/display/PeakRefreshRatePreferenceController.java
new file mode 100644
index 0000000..091ae32
--- /dev/null
+++ b/src/com/android/settings/display/PeakRefreshRatePreferenceController.java
@@ -0,0 +1,196 @@
+/*
+ * Copyright (C) 2020 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 com.android.settings.display;
+
+import android.content.Context;
+import android.hardware.display.DisplayManager;
+import android.os.Handler;
+import android.provider.DeviceConfig;
+import android.provider.Settings;
+import android.util.Log;
+import android.view.Display;
+
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.Preference;
+import androidx.preference.PreferenceScreen;
+import androidx.preference.SwitchPreference;
+
+import com.android.settings.R;
+import com.android.settings.core.TogglePreferenceController;
+import com.android.settingslib.core.lifecycle.LifecycleObserver;
+import com.android.settingslib.core.lifecycle.events.OnStart;
+import com.android.settingslib.core.lifecycle.events.OnStop;
+
+import java.util.concurrent.Executor;
+
+public class PeakRefreshRatePreferenceController extends TogglePreferenceController
+        implements LifecycleObserver, OnStart, OnStop {
+
+    @VisibleForTesting static float DEFAULT_REFRESH_RATE = 60f;
+
+    @VisibleForTesting float mPeakRefreshRate;
+
+    private static final String TAG = "RefreshRatePrefCtr";
+    private static final String KEY_PEAK_REFRESH_RATE_DEFAULT = "peak_refresh_rate_default";
+    private static final float INVALIDATE_REFRESH_RATE = -1f;
+
+    private final Handler mHandler;
+    private final IDeviceConfigChange mOnDeviceConfigChange;
+    private final DeviceConfigDisplaySettings mDeviceConfigDisplaySettings;
+    private Preference mPreference;
+
+    private interface IDeviceConfigChange {
+        void onDefaultRefreshRateChanged();
+    }
+
+    public PeakRefreshRatePreferenceController(Context context, String key) {
+        super(context, key);
+        mHandler = new Handler();
+        mDeviceConfigDisplaySettings = new DeviceConfigDisplaySettings();
+        mOnDeviceConfigChange =
+                new IDeviceConfigChange() {
+                    public void onDefaultRefreshRateChanged() {
+                        updateState(mPreference);
+                    }
+                };
+
+        final DisplayManager dm = mContext.getSystemService(DisplayManager.class);
+        final Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
+
+        if (display == null) {
+            Log.w(TAG, "No valid default display device");
+            mPeakRefreshRate = DEFAULT_REFRESH_RATE;
+        } else {
+            mPeakRefreshRate = findPeakRefreshRate(display.getSupportedModes());
+        }
+
+        Log.d(
+                TAG,
+                "DEFAULT_REFRESH_RATE : "
+                        + DEFAULT_REFRESH_RATE
+                        + " mPeakRefreshRate : "
+                        + mPeakRefreshRate);
+    }
+
+    @Override
+    public void displayPreference(PreferenceScreen screen) {
+        super.displayPreference(screen);
+
+        mPreference = screen.findPreference(getPreferenceKey());
+    }
+
+    @Override
+    public int getAvailabilityStatus() {
+        if (mContext.getResources().getBoolean(R.bool.config_show_smooth_display)) {
+            return mPeakRefreshRate > DEFAULT_REFRESH_RATE ? AVAILABLE : UNSUPPORTED_ON_DEVICE;
+        } else {
+            return UNSUPPORTED_ON_DEVICE;
+        }
+    }
+
+    @Override
+    public boolean isChecked() {
+        final float peakRefreshRate =
+                Settings.System.getFloat(
+                        mContext.getContentResolver(),
+                        Settings.System.PEAK_REFRESH_RATE,
+                        getDefaultPeakRefreshRate());
+        return peakRefreshRate == mPeakRefreshRate;
+    }
+
+    @Override
+    public boolean setChecked(boolean isChecked) {
+        final float peakRefreshRate = isChecked ? mPeakRefreshRate : DEFAULT_REFRESH_RATE;
+        Log.d(TAG, "setChecked to : " + peakRefreshRate);
+
+        return Settings.System.putFloat(
+                mContext.getContentResolver(), Settings.System.PEAK_REFRESH_RATE, peakRefreshRate);
+    }
+
+    @Override
+    public void onStart() {
+        mDeviceConfigDisplaySettings.startListening();
+    }
+
+    @Override
+    public void onStop() {
+        mDeviceConfigDisplaySettings.stopListening();
+    }
+
+    private float findPeakRefreshRate(Display.Mode[] modes) {
+        float peakRefreshRate = DEFAULT_REFRESH_RATE;
+        for (Display.Mode mode : modes) {
+            if (Math.round(mode.getRefreshRate()) > DEFAULT_REFRESH_RATE) {
+                peakRefreshRate = mode.getRefreshRate();
+            }
+        }
+        return peakRefreshRate;
+    }
+
+    private class DeviceConfigDisplaySettings
+            implements DeviceConfig.OnPropertiesChangedListener, Executor {
+        public void startListening() {
+            DeviceConfig.addOnPropertiesChangedListener(
+                    DeviceConfig.NAMESPACE_DISPLAY_MANAGER,
+                    this /* Executor */,
+                    this /* Listener */);
+        }
+
+        public void stopListening() {
+            DeviceConfig.removeOnPropertiesChangedListener(this);
+        }
+
+        public float getDefaultPeakRefreshRate() {
+            float defaultPeakRefreshRate =
+                    DeviceConfig.getFloat(
+                            DeviceConfig.NAMESPACE_DISPLAY_MANAGER,
+                            DisplayManager.DeviceConfig.KEY_PEAK_REFRESH_RATE_DEFAULT,
+                            INVALIDATE_REFRESH_RATE);
+            Log.d(TAG, "DeviceConfig getDefaultPeakRefreshRate : " + defaultPeakRefreshRate);
+
+            return defaultPeakRefreshRate;
+        }
+
+        @Override
+        public void onPropertiesChanged(DeviceConfig.Properties properties) {
+            // Got notified if any property has been changed in NAMESPACE_DISPLAY_MANAGER. The
+            // KEY_PEAK_REFRESH_RATE_DEFAULT value could be added, changed, removed or unchanged.
+            // Just force a UI update for any case.
+            if (mOnDeviceConfigChange != null) {
+                mOnDeviceConfigChange.onDefaultRefreshRateChanged();
+                updateState(mPreference);
+            }
+        }
+
+        @Override
+        public void execute(Runnable runnable) {
+            if (mHandler != null) {
+                mHandler.post(runnable);
+            }
+        }
+    }
+
+    private float getDefaultPeakRefreshRate() {
+        float defaultPeakRefreshRate = mDeviceConfigDisplaySettings.getDefaultPeakRefreshRate();
+        if (defaultPeakRefreshRate == INVALIDATE_REFRESH_RATE) {
+            defaultPeakRefreshRate = (float) mContext.getResources().getInteger(
+                    com.android.internal.R.integer.config_defaultPeakRefreshRate);
+        }
+
+        return defaultPeakRefreshRate;
+    }
+}
diff --git a/tests/robotests/res/values-mcc999/config.xml b/tests/robotests/res/values-mcc999/config.xml
index c7173bc..ff17891 100644
--- a/tests/robotests/res/values-mcc999/config.xml
+++ b/tests/robotests/res/values-mcc999/config.xml
@@ -68,6 +68,7 @@
     <bool name="config_show_avatar_in_homepage">true</bool>
     <bool name="config_show_branded_account_in_device_info">false</bool>
     <bool name="config_show_emergency_info_in_device_info">false</bool>
+    <bool name="config_show_smooth_display">false</bool>
 
     <!-- Whether or not extra preview panels should be used for screen zoom setting. -->
     <bool name="config_enable_extra_screen_zoom_preview">false</bool>
diff --git a/tests/robotests/res/values/config.xml b/tests/robotests/res/values/config.xml
index 3f1c9f1..d315a66 100644
--- a/tests/robotests/res/values/config.xml
+++ b/tests/robotests/res/values/config.xml
@@ -20,6 +20,7 @@
     <bool name="config_show_camera_laser_sensor">true</bool>
     <bool name="config_show_connectivity_monitor">true</bool>
     <bool name="config_display_recent_apps">true</bool>
+    <bool name="config_show_smooth_display">true</bool>
 
     <!-- Fake dimen value for restricted icon size - needed to get around Robolectric
          issue loading framework hidden resources -->
diff --git a/tests/robotests/src/com/android/settings/display/PeakRefreshRatePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/display/PeakRefreshRatePreferenceControllerTest.java
new file mode 100644
index 0000000..cae7d89
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/display/PeakRefreshRatePreferenceControllerTest.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2020 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 com.android.settings.display;
+
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+import static com.android.settings.core.BasePreferenceController.UNSUPPORTED_ON_DEVICE;
+import static com.android.settings.display.PeakRefreshRatePreferenceController.DEFAULT_REFRESH_RATE;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.Context;
+import android.provider.Settings;
+
+import androidx.preference.SwitchPreference;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(RobolectricTestRunner.class)
+public class PeakRefreshRatePreferenceControllerTest {
+
+    private Context mContext;
+    private PeakRefreshRatePreferenceController mController;
+    private SwitchPreference mPreference;
+
+    @Before
+    public void setUp() {
+        mContext = RuntimeEnvironment.application;
+        mController = new PeakRefreshRatePreferenceController(mContext, "key");
+        mPreference = new SwitchPreference(RuntimeEnvironment.application);
+    }
+
+    @Test
+    @Config(qualifiers = "mcc999")
+    public void getAvailabilityStatus_withConfigNoShow_returnUnsupported() {
+        assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
+    }
+
+    @Test
+    public void getAvailabilityStatus_refreshRateLargerThanDefault_returnAvailable() {
+        mController.mPeakRefreshRate = DEFAULT_REFRESH_RATE + 1;
+
+        assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+    }
+
+    @Test
+    public void getAvailabilityStatus_refreshRateEqualToDefault_returnUnsupported() {
+        mController.mPeakRefreshRate = DEFAULT_REFRESH_RATE;
+
+        assertThat(mController.getAvailabilityStatus()).isEqualTo(UNSUPPORTED_ON_DEVICE);
+    }
+
+    @Test
+    public void setChecked_enableSmoothDisplay_setCurrentRefreshRate() {
+        mController.mPeakRefreshRate = 88f;
+        mController.setChecked(true);
+
+        assertThat(Settings.System.getFloat(mContext.getContentResolver(),
+                Settings.System.PEAK_REFRESH_RATE, DEFAULT_REFRESH_RATE))
+                .isEqualTo(88.0f);
+    }
+
+    @Test
+    public void setChecked_disableSmoothDisplay_setDefaultRefreshRate() {
+        mController.mPeakRefreshRate = 88f;
+        mController.setChecked(false);
+
+        assertThat(Settings.System.getFloat(mContext.getContentResolver(),
+                Settings.System.PEAK_REFRESH_RATE, DEFAULT_REFRESH_RATE))
+                .isEqualTo(DEFAULT_REFRESH_RATE);
+    }
+
+    @Test
+    public void isChecked_enableSmoothDisplay_returnTrue() {
+        enableSmoothDisplayPreference();
+
+        assertThat(mController.isChecked()).isTrue();
+    }
+
+    @Test
+    public void isChecked_disableSmoothDisplay_returnFalse() {
+        disableSmoothDisplayPreference();
+
+        assertThat(mController.isChecked()).isFalse();
+    }
+
+    private void enableSmoothDisplayPreference() {
+        mController.mPeakRefreshRate = 88f;
+
+        Settings.System.putFloat(
+                mContext.getContentResolver(),
+                Settings.System.PEAK_REFRESH_RATE,
+                mController.mPeakRefreshRate);
+    }
+
+    private void disableSmoothDisplayPreference() {
+        mController.mPeakRefreshRate = 88f;
+
+        Settings.System.putFloat(
+                mContext.getContentResolver(),
+                Settings.System.PEAK_REFRESH_RATE,
+                DEFAULT_REFRESH_RATE);
+    }
+}