Settings: add a new developer menu entry to show hdr/sdr ratio overlay.

- The hdr/sdr ratio overlay will be shown on screen if the option is
  selected from the developer option.
- This option is hidden on non-HDR-supported devices.
- Add flags: com.android.settings.flags.development_hdr_sdr_ratio

Test: enable show hdr/sdr ratio from developer menu; com.android.settings.development.ShowHdrSdrRatioPreferenceControllerTest
Bug: 291863102
Change-Id: Idd72f95c67c95cd8127f9b94e031b3d87b18e307
diff --git a/aconfig/Android.bp b/aconfig/Android.bp
index 78fba34..5c6c8c3 100644
--- a/aconfig/Android.bp
+++ b/aconfig/Android.bp
@@ -8,6 +8,7 @@
     srcs: [
         "settings_accessibility_flag_declarations.aconfig",
         "settings_connecteddevice_flag_declarations.aconfig",
+        "settings_development_flag_declarations.aconfig",
         "settings_globalintl_flag_declarations.aconfig",
         "settings_experience_flag_declarations.aconfig",
         "settings_onboarding_experience_flag_declarations.aconfig",
diff --git a/aconfig/settings_development_flag_declarations.aconfig b/aconfig/settings_development_flag_declarations.aconfig
new file mode 100644
index 0000000..c23a38f
--- /dev/null
+++ b/aconfig/settings_development_flag_declarations.aconfig
@@ -0,0 +1,13 @@
+package: "com.android.settings.flags"
+
+# NOTE: Keep alphabetized to help limit merge conflicts from multiple simultaneous editors.
+
+# NOTE: All Settings flags share the same Flags class, so prefix our
+# flags with 'development' to prevent naming collision.
+
+flag {
+  name: "development_hdr_sdr_ratio"
+  namespace: "core_graphics"
+  description: "Shows hdr/sdr dev opton on the development options page from aconfig"
+  bug: "291863102"
+}
diff --git a/res/values/strings.xml b/res/values/strings.xml
index a3760c5..a503710 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1853,6 +1853,11 @@
     <!-- Debugging developer settings: show refresh rate summary [CHAR LIMIT=58] -->
     <string name="show_refresh_rate_summary">Show the current display refresh rate</string>
 
+    <!-- Debugging developer settings: show HDR/SDR ratio? [CHAR LIMIT=36] -->
+    <string name="show_hdr_sdr_ratio">Show HDR/SDR ratio</string>
+    <!-- Debugging developer settings: show HDR/SDR ratio summary [CHAR LIMIT=58] -->
+    <string name="show_hdr_sdr_ratio_summary">Show the current HDR/SDR ratio</string>
+
     <!-- NFC settings -->
     <!-- Used in the 1st-level settings screen to turn on NFC -->
     <string name="nfc_quick_toggle_title">NFC</string>
diff --git a/res/xml/development_settings.xml b/res/xml/development_settings.xml
index b053424..f890984 100644
--- a/res/xml/development_settings.xml
+++ b/res/xml/development_settings.xml
@@ -274,6 +274,11 @@
             android:summary="@string/show_refresh_rate_summary" />
 
         <SwitchPreferenceCompat
+            android:key="show_hdr_sdr_ratio"
+            android:title="@string/show_hdr_sdr_ratio"
+            android:summary="@string/show_hdr_sdr_ratio_summary" />
+
+        <SwitchPreferenceCompat
             android:key="overlay_settings"
             android:title="@string/overlay_settings_title"
             android:summary="@string/overlay_settings_summary" />
diff --git a/src/com/android/settings/development/DevelopmentSettingsDashboardFragment.java b/src/com/android/settings/development/DevelopmentSettingsDashboardFragment.java
index b88c345..a995ac3 100644
--- a/src/com/android/settings/development/DevelopmentSettingsDashboardFragment.java
+++ b/src/com/android/settings/development/DevelopmentSettingsDashboardFragment.java
@@ -666,6 +666,7 @@
         controllers.add(new ShowKeyPressesPreferenceController(context));
         controllers.add(new ShowSurfaceUpdatesPreferenceController(context));
         controllers.add(new ShowLayoutBoundsPreferenceController(context));
+        controllers.add(new ShowHdrSdrRatioPreferenceController(context));
         controllers.add(new ShowRefreshRatePreferenceController(context));
         controllers.add(new RtlLayoutPreferenceController(context));
         controllers.add(new WindowAnimationScalePreferenceController(context));
diff --git a/src/com/android/settings/development/OWNERS b/src/com/android/settings/development/OWNERS
new file mode 100644
index 0000000..6443afe
--- /dev/null
+++ b/src/com/android/settings/development/OWNERS
@@ -0,0 +1,5 @@
+# ShowHdrSdrRatioPreferenceController
+per-file ShowHdrSdrRatioPreferenceController.java=file:platform/frameworks/native:/services/surfaceflinger/OWNERS
+
+# ShowRefreshRatePreferenceController
+per-file ShowRefreshRatePreferenceController.java=file:platform/frameworks/native:/services/surfaceflinger/OWNERS
diff --git a/src/com/android/settings/development/ShowHdrSdrRatioPreferenceController.java b/src/com/android/settings/development/ShowHdrSdrRatioPreferenceController.java
new file mode 100644
index 0000000..2e7807e
--- /dev/null
+++ b/src/com/android/settings/development/ShowHdrSdrRatioPreferenceController.java
@@ -0,0 +1,144 @@
+/**
+ * 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.
+ * 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.development;
+
+import android.content.Context;
+import android.hardware.display.DisplayManager;
+import android.os.IBinder;
+import android.os.Parcel;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.view.Display;
+
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.Preference;
+import androidx.preference.TwoStatePreference;
+
+import com.android.settings.core.PreferenceControllerMixin;
+import com.android.settings.flags.Flags;
+import com.android.settingslib.development.DeveloperOptionsPreferenceController;
+
+/**
+ * Controller class for controlling the hdr/sdr ratio on SurfaceFlinger
+ */
+public class ShowHdrSdrRatioPreferenceController extends DeveloperOptionsPreferenceController
+        implements Preference.OnPreferenceChangeListener, PreferenceControllerMixin {
+
+    private static final String SHOW_REFRESH_RATE_KEY = "show_hdr_sdr_ratio";
+
+    private static final int SETTING_VALUE_QUERY = 2;
+    private static final int SETTING_VALUE_ON = 1;
+    private static final int SETTING_VALUE_OFF = 0;
+
+    private static final String SURFACE_FLINGER_SERVICE_KEY = "SurfaceFlinger";
+
+    private static final int SURFACE_FLINGER_CODE = 1043;
+
+    private static final String SURFACE_COMPOSER_INTERFACE_KEY = "android.ui.ISurfaceComposer";
+
+    private final IBinder mSurfaceFlinger;
+
+    private final boolean mIsHdrSdrRatioAvailable;
+
+    public ShowHdrSdrRatioPreferenceController(Context context) {
+        super(context);
+        mSurfaceFlinger = ServiceManager.getService(SURFACE_FLINGER_SERVICE_KEY);
+        DisplayManager displayManager = context.getSystemService(DisplayManager.class);
+        Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
+        mIsHdrSdrRatioAvailable = display != null && display.isHdrSdrRatioAvailable();
+    }
+
+    @VisibleForTesting
+    ShowHdrSdrRatioPreferenceController(Context context, IBinder surfaceFlinger,
+                                        boolean isHdrSdrRatioAvailable) {
+        super(context);
+        mSurfaceFlinger = surfaceFlinger;
+        mIsHdrSdrRatioAvailable = isHdrSdrRatioAvailable;
+    }
+
+    @Override
+    public String getPreferenceKey() {
+        return SHOW_REFRESH_RATE_KEY;
+    }
+
+    @Override
+    public boolean onPreferenceChange(Preference preference, Object newValue) {
+        final boolean isEnabled = (Boolean) newValue;
+        writeShowHdrSdrRatioSetting(isEnabled);
+        return true;
+    }
+
+    @Override
+    public void updateState(Preference preference) {
+        super.updateState(preference);
+        updateShowHdrSdrRatioSetting();
+    }
+
+    @Override
+    public boolean isAvailable() {
+        return Flags.developmentHdrSdrRatio() && mIsHdrSdrRatioAvailable;
+    }
+
+    @Override
+    protected void onDeveloperOptionsSwitchDisabled() {
+        super.onDeveloperOptionsSwitchDisabled();
+        final TwoStatePreference preference = (TwoStatePreference) mPreference;
+        if (preference.isChecked()) {
+            // Writing false to the preference when the setting is already off will have a
+            // side effect of turning on the preference that we wish to avoid
+            writeShowHdrSdrRatioSetting(false);
+            preference.setChecked(false);
+        }
+    }
+
+    private void updateShowHdrSdrRatioSetting() {
+        // magic communication with surface flinger.
+        try {
+            if (mSurfaceFlinger != null) {
+                final Parcel data = Parcel.obtain();
+                final Parcel reply = Parcel.obtain();
+                data.writeInterfaceToken(SURFACE_COMPOSER_INTERFACE_KEY);
+                data.writeInt(SETTING_VALUE_QUERY);
+                mSurfaceFlinger.transact(SURFACE_FLINGER_CODE, data, reply, 0 /* flags */);
+                final boolean enabled = reply.readBoolean();
+                ((TwoStatePreference) mPreference).setChecked(enabled);
+                reply.recycle();
+                data.recycle();
+            }
+        } catch (RemoteException ex) {
+            // intentional no-op
+        }
+    }
+
+    @VisibleForTesting
+    void writeShowHdrSdrRatioSetting(boolean isEnabled) {
+        try {
+            if (mSurfaceFlinger != null) {
+                final Parcel data = Parcel.obtain();
+                data.writeInterfaceToken(SURFACE_COMPOSER_INTERFACE_KEY);
+                final int showHdrSdrRatio = isEnabled ? SETTING_VALUE_ON : SETTING_VALUE_OFF;
+                data.writeInt(showHdrSdrRatio);
+                mSurfaceFlinger.transact(SURFACE_FLINGER_CODE, data,
+                        null /* reply */, 0 /* flags */);
+                data.recycle();
+            }
+        } catch (RemoteException ex) {
+            // intentional no-op
+        }
+        updateShowHdrSdrRatioSetting();
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/development/ShowHdrSdrRatioPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/development/ShowHdrSdrRatioPreferenceControllerTest.java
new file mode 100644
index 0000000..2234754
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/development/ShowHdrSdrRatioPreferenceControllerTest.java
@@ -0,0 +1,171 @@
+/**
+ * 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.
+ * 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.development;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.platform.test.flag.junit.SetFlagsRule;
+
+import androidx.preference.PreferenceScreen;
+import androidx.preference.TwoStatePreference;
+
+import com.android.settings.flags.Flags;
+import com.android.settings.testutils.shadow.ShadowParcel;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(RobolectricTestRunner.class)
+public class ShowHdrSdrRatioPreferenceControllerTest {
+
+    @Mock
+    private Context mContext;
+    @Mock
+    private PreferenceScreen mScreen;
+    @Mock
+    private TwoStatePreference mPreference;
+    @Mock
+    private IBinder mSurfaceFlinger;
+
+    private ShowHdrSdrRatioPreferenceController mController;
+
+    @Rule
+    public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mContext = RuntimeEnvironment.application;
+        mController = new ShowHdrSdrRatioPreferenceController(mContext, mSurfaceFlinger, true);
+        when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mPreference);
+        mController.displayPreference(mScreen);
+    }
+
+    @Test
+    @Config(shadows = ShadowParcel.class)
+    public void onPreferenceChange_settingEnabled_shouldChecked() throws RemoteException {
+        mSetFlagsRule.enableFlags(Flags.FLAG_DEVELOPMENT_HDR_SDR_RATIO);
+        assertTrue(mController.isAvailable());
+        ShadowParcel.sReadBoolResult = true;
+        doReturn(true).when(mSurfaceFlinger)
+            .transact(anyInt(), any(), any(), eq(0 /* flags */));
+        mController.onPreferenceChange(mPreference, true /* new value */);
+        verify(mPreference).setChecked(true);
+    }
+
+    @Test
+    @Config(shadows = ShadowParcel.class)
+    public void onPreferenceChange_settingDisabled_shouldUnchecked() throws RemoteException {
+        mSetFlagsRule.enableFlags(Flags.FLAG_DEVELOPMENT_HDR_SDR_RATIO);
+        assertTrue(mController.isAvailable());
+        ShadowParcel.sReadBoolResult = false;
+        doReturn(true).when(mSurfaceFlinger)
+            .transact(anyInt(), any(), any(), eq(0 /* flags */));
+        mController.onPreferenceChange(mPreference, false /* new value */);
+        verify(mPreference).setChecked(false);
+    }
+
+    @Test
+    @Config(shadows = ShadowParcel.class)
+    public void updateState_settingEnabled_shouldChecked() throws RemoteException {
+        mSetFlagsRule.enableFlags(Flags.FLAG_DEVELOPMENT_HDR_SDR_RATIO);
+        assertTrue(mController.isAvailable());
+        ShadowParcel.sReadBoolResult = true;
+        doReturn(true).when(mSurfaceFlinger)
+            .transact(anyInt(), any(), any(), eq(0 /* flags */));
+        mController.updateState(mPreference);
+        verify(mPreference).setChecked(true);
+    }
+
+    @Test
+    @Config(shadows = ShadowParcel.class)
+    public void updateState_settingDisabled_shouldUnchecked() throws RemoteException {
+        mSetFlagsRule.enableFlags(Flags.FLAG_DEVELOPMENT_HDR_SDR_RATIO);
+        assertTrue(mController.isAvailable());
+        ShadowParcel.sReadBoolResult = false;
+        doReturn(true).when(mSurfaceFlinger)
+            .transact(anyInt(), any(), any(), eq(0 /* flags */));
+        mController.updateState(mPreference);
+        verify(mPreference).setChecked(false);
+    }
+
+    @Test
+    public void settingNotAvailable_isHdrSdrRatioAvailableFalse_flagsOff() {
+        mSetFlagsRule.disableFlags(Flags.FLAG_DEVELOPMENT_HDR_SDR_RATIO);
+        mController = new ShowHdrSdrRatioPreferenceController(mContext, mSurfaceFlinger, true);
+        assertFalse(mController.isAvailable());
+    }
+
+    @Test
+    public void settingNotAvailable_isHdrSdrRatioAvailableTrue_flagsOn() {
+        mSetFlagsRule.enableFlags(Flags.FLAG_DEVELOPMENT_HDR_SDR_RATIO);
+        mController = new ShowHdrSdrRatioPreferenceController(mContext, mSurfaceFlinger, false);
+        assertFalse(mController.isAvailable());
+    }
+
+    @Test
+    @Config(shadows = ShadowParcel.class)
+    public void onDeveloperOptionsSwitchDisabled_preferenceUnchecked_shouldNotTurnOffPreference()
+            throws RemoteException {
+        mSetFlagsRule.enableFlags(Flags.FLAG_DEVELOPMENT_HDR_SDR_RATIO);
+        assertTrue(mController.isAvailable());
+        ShadowParcel.sReadBoolResult = false;
+        doReturn(true).when(mSurfaceFlinger)
+            .transact(anyInt(), any(), any(), eq(0 /* flags */));
+        when(mPreference.isChecked()).thenReturn(false);
+        mController.onDeveloperOptionsSwitchDisabled();
+
+        mController.writeShowHdrSdrRatioSetting(true);
+        verify(mPreference).setChecked(false);
+        verify(mPreference).setEnabled(false);
+    }
+
+    @Test
+    @Config(shadows = ShadowParcel.class)
+    public void onDeveloperOptionsSwitchDisabled_preferenceChecked_shouldTurnOffPreference()
+            throws RemoteException {
+        mSetFlagsRule.enableFlags(Flags.FLAG_DEVELOPMENT_HDR_SDR_RATIO);
+        assertTrue(mController.isAvailable());
+        ShadowParcel.sReadBoolResult = true;
+        doReturn(true).when(mSurfaceFlinger)
+            .transact(anyInt(), any(), any(), eq(0 /* flags */));
+        when(mPreference.isChecked()).thenReturn(true);
+        mController.onDeveloperOptionsSwitchDisabled();
+
+        mController.writeShowHdrSdrRatioSetting(false);
+        verify(mPreference).setChecked(false);
+        verify(mPreference).setEnabled(false);
+    }
+}
+