Merge "Remove colors.xml file from core/res/res/values-watch/" into main
diff --git a/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/DesktopModeFlickerScenarios.kt b/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/DesktopModeFlickerScenarios.kt
index 32217d8..c725b08 100644
--- a/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/DesktopModeFlickerScenarios.kt
+++ b/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/DesktopModeFlickerScenarios.kt
@@ -21,11 +21,10 @@
 import android.tools.flicker.assertors.assertions.AppLayerIsVisibleAlways
 import android.tools.flicker.assertors.assertions.AppLayerIsVisibleAtStart
 import android.tools.flicker.assertors.assertions.AppWindowHasDesktopModeInitialBoundsAtTheEnd
+import android.tools.flicker.assertors.assertions.AppWindowHasSizeOfAtLeast
 import android.tools.flicker.assertors.assertions.AppWindowIsInvisibleAtEnd
-import android.tools.flicker.assertors.assertions.AppWindowIsVisibleAlways
 import android.tools.flicker.assertors.assertions.AppWindowOnTopAtEnd
 import android.tools.flicker.assertors.assertions.AppWindowOnTopAtStart
-import android.tools.flicker.assertors.assertions.AppWindowRemainInsideDisplayBounds
 import android.tools.flicker.assertors.assertions.LauncherWindowReplacesAppAsTopWindow
 import android.tools.flicker.config.AssertionTemplates
 import android.tools.flicker.config.FlickerConfigEntry
@@ -46,28 +45,27 @@
             FlickerConfigEntry(
                 scenarioId = ScenarioId("END_DRAG_TO_DESKTOP"),
                 extractor =
-                    ShellTransitionScenarioExtractor(
-                        transitionMatcher =
-                            object : ITransitionMatcher {
-                                override fun findAll(
-                                    transitions: Collection<Transition>
-                                ): Collection<Transition> {
-                                    return transitions.filter {
-                                        it.type == TransitionType.DESKTOP_MODE_END_DRAG_TO_DESKTOP
-                                    }
-                                }
+                ShellTransitionScenarioExtractor(
+                    transitionMatcher =
+                    object : ITransitionMatcher {
+                        override fun findAll(
+                            transitions: Collection<Transition>
+                        ): Collection<Transition> {
+                            return transitions.filter {
+                                it.type == TransitionType.DESKTOP_MODE_END_DRAG_TO_DESKTOP
                             }
-                    ),
+                        }
+                    }
+                ),
                 assertions =
-                    AssertionTemplates.COMMON_ASSERTIONS +
+                AssertionTemplates.COMMON_ASSERTIONS +
                         listOf(
-                                AppLayerIsVisibleAlways(Components.DESKTOP_MODE_APP),
-                                AppWindowOnTopAtEnd(Components.DESKTOP_MODE_APP),
-                                AppWindowHasDesktopModeInitialBoundsAtTheEnd(
-                                    Components.DESKTOP_MODE_APP
-                                )
+                            AppLayerIsVisibleAlways(Components.DESKTOP_MODE_APP),
+                            AppWindowOnTopAtEnd(Components.DESKTOP_MODE_APP),
+                            AppWindowHasDesktopModeInitialBoundsAtTheEnd(
+                                Components.DESKTOP_MODE_APP
                             )
-                            .associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
+                        ).associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
             )
 
         // Use this scenario for closing an app in desktop windowing, except the last app. For the
@@ -76,77 +74,85 @@
             FlickerConfigEntry(
                 scenarioId = ScenarioId("CLOSE_APP"),
                 extractor =
-                    ShellTransitionScenarioExtractor(
-                        transitionMatcher =
-                            object : ITransitionMatcher {
-                                override fun findAll(
-                                    transitions: Collection<Transition>
-                                ): Collection<Transition> {
-                                    // In case there are multiple windows closing, filter out the
-                                    // last window closing. It should use the CLOSE_LAST_APP
-                                    // scenario below.
-                                    return transitions
-                                            .filter { it.type == TransitionType.CLOSE }
-                                            .sortedByDescending { it.id }
-                                            .drop(1)
-                                }
-                            }
-                    ),
+                ShellTransitionScenarioExtractor(
+                    transitionMatcher =
+                    object : ITransitionMatcher {
+                        override fun findAll(
+                            transitions: Collection<Transition>
+                        ): Collection<Transition> {
+                            // In case there are multiple windows closing, filter out the
+                            // last window closing. It should use the CLOSE_LAST_APP
+                            // scenario below.
+                            return transitions
+                                    .filter { it.type == TransitionType.CLOSE }
+                                    .sortedByDescending { it.id }
+                                    .drop(1)
+                        }
+                    }
+                ),
                 assertions =
-                    AssertionTemplates.COMMON_ASSERTIONS +
+                AssertionTemplates.COMMON_ASSERTIONS +
                         listOf(
-                                AppWindowOnTopAtStart(Components.DESKTOP_MODE_APP),
-                                AppLayerIsVisibleAtStart(Components.DESKTOP_MODE_APP),
-                                AppLayerIsInvisibleAtEnd(Components.DESKTOP_MODE_APP),
-                            )
-                            .associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
+                            AppWindowOnTopAtStart(Components.DESKTOP_MODE_APP),
+                            AppLayerIsVisibleAtStart(Components.DESKTOP_MODE_APP),
+                            AppLayerIsInvisibleAtEnd(Components.DESKTOP_MODE_APP),
+                        ).associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
             )
 
         val CLOSE_LAST_APP =
             FlickerConfigEntry(
                 scenarioId = ScenarioId("CLOSE_LAST_APP"),
                 extractor =
-                    ShellTransitionScenarioExtractor(
-                        transitionMatcher =
-                            object : ITransitionMatcher {
-                                override fun findAll(
-                                    transitions: Collection<Transition>
-                                ): Collection<Transition> {
-                                    val lastTransition =
-                                        transitions
-                                                .filter { it.type == TransitionType.CLOSE }
-                                                .maxByOrNull { it.id }!!
-                                    return listOf(lastTransition)
-                                }
-                            }
-                    ),
+                ShellTransitionScenarioExtractor(
+                    transitionMatcher =
+                    object : ITransitionMatcher {
+                        override fun findAll(
+                            transitions: Collection<Transition>
+                        ): Collection<Transition> {
+                            val lastTransition =
+                                transitions
+                                        .filter { it.type == TransitionType.CLOSE }
+                                        .maxByOrNull { it.id }!!
+                            return listOf(lastTransition)
+                        }
+                    }
+                ),
                 assertions =
-                    AssertionTemplates.COMMON_ASSERTIONS +
+                AssertionTemplates.COMMON_ASSERTIONS +
                         listOf(
-                                AppWindowIsInvisibleAtEnd(Components.DESKTOP_MODE_APP),
-                                LauncherWindowReplacesAppAsTopWindow(Components.DESKTOP_MODE_APP),
-                                AppWindowIsInvisibleAtEnd(DESKTOP_WALLPAPER)
-                            )
-                            .associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
+                            AppWindowIsInvisibleAtEnd(Components.DESKTOP_MODE_APP),
+                            LauncherWindowReplacesAppAsTopWindow(Components.DESKTOP_MODE_APP),
+                            AppWindowIsInvisibleAtEnd(DESKTOP_WALLPAPER)
+                        ).associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
             )
 
         val CORNER_RESIZE =
             FlickerConfigEntry(
                 scenarioId = ScenarioId("CORNER_RESIZE"),
                 extractor =
-                    TaggedScenarioExtractorBuilder()
+                TaggedScenarioExtractorBuilder()
                         .setTargetTag(CujType.CUJ_DESKTOP_MODE_RESIZE_WINDOW)
                         .setTransitionMatcher(
                             TaggedCujTransitionMatcher(associatedTransitionRequired = false)
                         )
                         .build(),
+                assertions = AssertionTemplates.DESKTOP_MODE_APP_VISIBILITY_ASSERTIONS
+            )
+
+        val CORNER_RESIZE_TO_MINIMUM_SIZE =
+            FlickerConfigEntry(
+                scenarioId = ScenarioId("CORNER_RESIZE_TO_MINIMUM_SIZE"),
+                extractor =
+                TaggedScenarioExtractorBuilder()
+                        .setTargetTag(CujType.CUJ_DESKTOP_MODE_RESIZE_WINDOW)
+                        .setTransitionMatcher(
+                            TaggedCujTransitionMatcher(associatedTransitionRequired = false)
+                        ).build(),
                 assertions =
-                    listOf(
-                            AppWindowIsVisibleAlways(Components.DESKTOP_MODE_APP),
-                            AppWindowOnTopAtEnd(Components.DESKTOP_MODE_APP),
-                            AppWindowRemainInsideDisplayBounds(Components.DESKTOP_MODE_APP),
-                        )
-                        .associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
+                AssertionTemplates.DESKTOP_MODE_APP_VISIBILITY_ASSERTIONS +
+                        listOf(
+                            AppWindowHasSizeOfAtLeast(Components.DESKTOP_MODE_APP, 770, 700)
+                        ).associateBy({ it }, { AssertionInvocationGroup.BLOCKING }),
             )
     }
-}
+}
\ No newline at end of file
diff --git a/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/ResizeAppToMinimumWindowSizeLandscape.kt b/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/ResizeAppToMinimumWindowSizeLandscape.kt
new file mode 100644
index 0000000..6319cf7
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/ResizeAppToMinimumWindowSizeLandscape.kt
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2024 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.wm.shell.flicker.service.desktopmode.flicker
+
+import android.tools.Rotation
+import android.tools.flicker.FlickerConfig
+import android.tools.flicker.annotation.ExpectedScenarios
+import android.tools.flicker.annotation.FlickerConfigProvider
+import android.tools.flicker.config.FlickerConfig
+import android.tools.flicker.config.FlickerServiceConfig
+import android.tools.flicker.junit.FlickerServiceJUnit4ClassRunner
+import com.android.wm.shell.flicker.service.desktopmode.flicker.DesktopModeFlickerScenarios.Companion.CORNER_RESIZE_TO_MINIMUM_SIZE
+import com.android.wm.shell.flicker.service.desktopmode.scenarios.ResizeAppWithCornerResize
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Resize app window using corner resize to the smallest possible height and width in
+ * landscape mode.
+ *
+ * Assert that the minimum window size constraint is maintained.
+ */
+@RunWith(FlickerServiceJUnit4ClassRunner::class)
+class ResizeAppToMinimumWindowSizeLandscape : ResizeAppWithCornerResize(
+    rotation = Rotation.ROTATION_90,
+    horizontalChange = -1500,
+    verticalChange = 1500) {
+    @ExpectedScenarios(["CORNER_RESIZE_TO_MINIMUM_SIZE"])
+    @Test
+    override fun resizeAppWithCornerResize() = super.resizeAppWithCornerResize()
+
+    companion object {
+        @JvmStatic
+        @FlickerConfigProvider
+        fun flickerConfigProvider(): FlickerConfig =
+            FlickerConfig().use(FlickerServiceConfig.DEFAULT).use(CORNER_RESIZE_TO_MINIMUM_SIZE)
+    }
+}
diff --git a/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/ResizeAppToMinimumWindowSizePortrait.kt b/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/ResizeAppToMinimumWindowSizePortrait.kt
new file mode 100644
index 0000000..431f6e3
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/flicker/ResizeAppToMinimumWindowSizePortrait.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2024 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.wm.shell.flicker.service.desktopmode.flicker
+
+import android.tools.flicker.FlickerConfig
+import android.tools.flicker.annotation.ExpectedScenarios
+import android.tools.flicker.annotation.FlickerConfigProvider
+import android.tools.flicker.config.FlickerConfig
+import android.tools.flicker.config.FlickerServiceConfig
+import android.tools.flicker.junit.FlickerServiceJUnit4ClassRunner
+import com.android.wm.shell.flicker.service.desktopmode.flicker.DesktopModeFlickerScenarios.Companion.CORNER_RESIZE_TO_MINIMUM_SIZE
+import com.android.wm.shell.flicker.service.desktopmode.scenarios.ResizeAppWithCornerResize
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Resize app window using corner resize to the smallest possible height and width in portrait mode.
+ *
+ * Assert that the minimum window size constraint is maintained.
+ */
+@RunWith(FlickerServiceJUnit4ClassRunner::class)
+class ResizeAppToMinimumWindowSizePortrait : ResizeAppWithCornerResize(horizontalChange = -1500,
+    verticalChange = 1500) {
+    @ExpectedScenarios(["CORNER_RESIZE_TO_MINIMUM_SIZE"])
+    @Test
+    override fun resizeAppWithCornerResize() = super.resizeAppWithCornerResize()
+
+    companion object {
+        @JvmStatic
+        @FlickerConfigProvider
+        fun flickerConfigProvider(): FlickerConfig =
+            FlickerConfig().use(FlickerServiceConfig.DEFAULT).use(CORNER_RESIZE_TO_MINIMUM_SIZE)
+    }
+}
diff --git a/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/scenarios/ResizeAppWithCornerResize.kt b/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/scenarios/ResizeAppWithCornerResize.kt
index ac9089a..136cf37 100644
--- a/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/scenarios/ResizeAppWithCornerResize.kt
+++ b/libs/WindowManager/Shell/tests/flicker/service/src/com/android/wm/shell/flicker/service/desktopmode/scenarios/ResizeAppWithCornerResize.kt
@@ -38,7 +38,9 @@
 @Ignore("Base Test Class")
 abstract class ResizeAppWithCornerResize
 @JvmOverloads
-constructor(val rotation: Rotation = Rotation.ROTATION_0) {
+constructor(val rotation: Rotation = Rotation.ROTATION_0,
+    val horizontalChange: Int = 50,
+    val verticalChange: Int = -50) {
 
     private val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation()
     private val tapl = LauncherInstrumentation()
@@ -46,7 +48,9 @@
     private val device = UiDevice.getInstance(instrumentation)
     private val testApp = DesktopModeAppHelper(SimpleAppHelper(instrumentation))
 
-    @Rule @JvmField val testSetupRule = Utils.testSetupRule(NavBar.MODE_GESTURAL, rotation)
+    @Rule
+    @JvmField
+    val testSetupRule = Utils.testSetupRule(NavBar.MODE_GESTURAL, rotation)
 
     @Before
     fun setup() {
@@ -58,7 +62,11 @@
 
     @Test
     open fun resizeAppWithCornerResize() {
-        testApp.cornerResize(wmHelper, device, DesktopModeAppHelper.Corners.RIGHT_TOP, 50, -50)
+        testApp.cornerResize(wmHelper,
+            device,
+            DesktopModeAppHelper.Corners.RIGHT_TOP,
+            horizontalChange,
+            verticalChange)
     }
 
     @After
diff --git a/libs/androidfw/StringPool.cpp b/libs/androidfw/StringPool.cpp
index ad445c0..629f146 100644
--- a/libs/androidfw/StringPool.cpp
+++ b/libs/androidfw/StringPool.cpp
@@ -297,24 +297,22 @@
 template <typename E>
 static void SortEntries(
     std::vector<std::unique_ptr<E>>& entries,
-    const std::function<int(const StringPool::Context&, const StringPool::Context&)>& cmp) {
+    base::function_ref<int(const StringPool::Context&, const StringPool::Context&)> cmp) {
   using UEntry = std::unique_ptr<E>;
-
-  if (cmp != nullptr) {
-    std::sort(entries.begin(), entries.end(), [&cmp](const UEntry& a, const UEntry& b) -> bool {
-      int r = cmp(a->context, b->context);
-      if (r == 0) {
-        r = a->value.compare(b->value);
-      }
-      return r < 0;
-    });
-  } else {
-    std::sort(entries.begin(), entries.end(),
-              [](const UEntry& a, const UEntry& b) -> bool { return a->value < b->value; });
-  }
+  std::sort(entries.begin(), entries.end(), [cmp](const UEntry& a, const UEntry& b) -> bool {
+    int r = cmp(a->context, b->context);
+    if (r == 0) {
+      r = a->value.compare(b->value);
+    }
+    return r < 0;
+  });
 }
 
-void StringPool::Sort(const std::function<int(const Context&, const Context&)>& cmp) {
+void StringPool::Sort() {
+  Sort([](auto&&, auto&&) { return 0; });
+}
+
+void StringPool::Sort(base::function_ref<int(const Context&, const Context&)> cmp) {
   SortEntries(styles_, cmp);
   SortEntries(strings_, cmp);
   ReAssignIndices();
diff --git a/libs/androidfw/include/androidfw/StringPool.h b/libs/androidfw/include/androidfw/StringPool.h
index 0190ab5..9b2c72a 100644
--- a/libs/androidfw/include/androidfw/StringPool.h
+++ b/libs/androidfw/include/androidfw/StringPool.h
@@ -17,7 +17,6 @@
 #ifndef _ANDROID_STRING_POOL_H
 #define _ANDROID_STRING_POOL_H
 
-#include <functional>
 #include <memory>
 #include <string>
 #include <unordered_map>
@@ -25,6 +24,7 @@
 
 #include "BigBuffer.h"
 #include "IDiagnostics.h"
+#include "android-base/function_ref.h"
 #include "android-base/macros.h"
 #include "androidfw/ConfigDescription.h"
 #include "androidfw/StringPiece.h"
@@ -205,7 +205,8 @@
   // Sorts the strings according to their Context using some comparison function.
   // Equal Contexts are further sorted by string value, lexicographically.
   // If no comparison function is provided, values are only sorted lexicographically.
-  void Sort(const std::function<int(const Context&, const Context&)>& cmp = nullptr);
+  void Sort();
+  void Sort(base::function_ref<int(const Context&, const Context&)> cmp);
 
   // Removes any strings that have no references.
   void Prune();
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InfoMediaManagerTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InfoMediaManagerTest.java
index c9b35a0a..e1447dc 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InfoMediaManagerTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/InfoMediaManagerTest.java
@@ -861,6 +861,23 @@
     }
 
     @Test
+    public void addMediaDevice_withAddresslessBluetoothDevice_shouldIgnoreDeviceAndNotCrash() {
+        MediaRoute2Info bluetoothRoute =
+                new MediaRoute2Info.Builder(TEST_BLUETOOTH_ROUTE).setAddress(null).build();
+
+        final CachedBluetoothDeviceManager cachedBluetoothDeviceManager =
+                mock(CachedBluetoothDeviceManager.class);
+        when(mLocalBluetoothManager.getCachedDeviceManager())
+                .thenReturn(cachedBluetoothDeviceManager);
+        when(cachedBluetoothDeviceManager.findDevice(any(BluetoothDevice.class))).thenReturn(null);
+
+        mInfoMediaManager.mMediaDevices.clear();
+        mInfoMediaManager.addMediaDevice(bluetoothRoute, TEST_SYSTEM_ROUTING_SESSION);
+
+        assertThat(mInfoMediaManager.mMediaDevices.size()).isEqualTo(0);
+    }
+
+    @Test
     public void onRoutesUpdated_setsFirstSelectedRouteAsCurrentConnectedDevice() {
         final CachedBluetoothDeviceManager cachedBluetoothDeviceManager =
                 mock(CachedBluetoothDeviceManager.class);
diff --git a/packages/SystemUI/aconfig/systemui.aconfig b/packages/SystemUI/aconfig/systemui.aconfig
index 07f7436..3f165a3 100644
--- a/packages/SystemUI/aconfig/systemui.aconfig
+++ b/packages/SystemUI/aconfig/systemui.aconfig
@@ -1052,6 +1052,16 @@
 }
 
 flag {
+  name: "glanceable_hub_back_gesture"
+  namespace: "systemui"
+  description: "Enables back gesture on the glanceable hub"
+  bug: "346331399"
+  metadata {
+    purpose: PURPOSE_BUGFIX
+  }
+}
+
+flag {
   name: "glanceable_hub_allow_keyguard_when_dreaming"
   namespace: "systemui"
   description: "Allows users to exit dream to keyguard with glanceable hub enabled"
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
index cc4e775..d046631 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
@@ -27,6 +27,7 @@
 import androidx.compose.ui.platform.LocalDensity
 import androidx.compose.ui.unit.dp
 import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.android.compose.animation.scene.Back
 import com.android.compose.animation.scene.CommunalSwipeDetector
 import com.android.compose.animation.scene.Edge
 import com.android.compose.animation.scene.ElementKey
@@ -41,6 +42,7 @@
 import com.android.compose.animation.scene.observableTransitionState
 import com.android.compose.animation.scene.transitions
 import com.android.compose.theme.LocalAndroidColorScheme
+import com.android.systemui.Flags.glanceableHubBackGesture
 import com.android.systemui.communal.shared.model.CommunalBackgroundType
 import com.android.systemui.communal.shared.model.CommunalScenes
 import com.android.systemui.communal.shared.model.CommunalTransitionKeys
@@ -193,10 +195,17 @@
             Box(modifier = Modifier.fillMaxSize())
         }
 
-        scene(
-            CommunalScenes.Communal,
-            userActions = mapOf(Swipe(SwipeDirection.Right) to CommunalScenes.Blank)
-        ) {
+        val userActions =
+            if (glanceableHubBackGesture()) {
+                mapOf(
+                    Swipe(SwipeDirection.Right) to CommunalScenes.Blank,
+                    Back to CommunalScenes.Blank,
+                )
+            } else {
+                mapOf(Swipe(SwipeDirection.Right) to CommunalScenes.Blank)
+            }
+
+        scene(CommunalScenes.Communal, userActions = userActions) {
             CommunalScene(
                 backgroundType = backgroundType,
                 colors = colors,
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
index a614fc1..4ef1f93 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/QuickStepContract.java
@@ -126,6 +126,8 @@
     public static final long SYSUI_STATE_TOUCHPAD_GESTURES_DISABLED = 1L << 33;
     // PiP animation is running
     public static final long SYSUI_STATE_DISABLE_GESTURE_PIP_ANIMATING = 1L << 34;
+    // Communal hub is showing
+    public static final long SYSUI_STATE_COMMUNAL_HUB_SHOWING = 1L << 35;
 
     // Mask for SystemUiStateFlags to isolate SYSUI_STATE_AWAKE and
     // SYSUI_STATE_WAKEFULNESS_TRANSITION, to match WAKEFULNESS_* constants
@@ -176,6 +178,7 @@
             SYSUI_STATE_SHORTCUT_HELPER_SHOWING,
             SYSUI_STATE_TOUCHPAD_GESTURES_DISABLED,
             SYSUI_STATE_DISABLE_GESTURE_PIP_ANIMATING,
+            SYSUI_STATE_COMMUNAL_HUB_SHOWING,
     })
     public @interface SystemUiStateFlags {}
 
@@ -283,6 +286,9 @@
         if ((flags & SYSUI_STATE_DISABLE_GESTURE_PIP_ANIMATING) != 0) {
             str.add("disable_gesture_pip_animating");
         }
+        if ((flags & SYSUI_STATE_COMMUNAL_HUB_SHOWING) != 0) {
+            str.add("communal_hub_showing");
+        }
 
         return str.toString();
     }
@@ -336,7 +342,8 @@
         // the keyguard)
         if ((sysuiStateFlags & SYSUI_STATE_BOUNCER_SHOWING) != 0
                 || (sysuiStateFlags & SYSUI_STATE_DIALOG_SHOWING) != 0
-                || (sysuiStateFlags & SYSUI_STATE_VOICE_INTERACTION_WINDOW_SHOWING) != 0) {
+                || (sysuiStateFlags & SYSUI_STATE_VOICE_INTERACTION_WINDOW_SHOWING) != 0
+                || (sysuiStateFlags & SYSUI_STATE_COMMUNAL_HUB_SHOWING) != 0) {
             return false;
         }
         if ((sysuiStateFlags & SYSUI_STATE_ALLOW_GESTURE_IGNORING_BAR_VISIBILITY) != 0) {
diff --git a/packages/SystemUI/src-debug/com/android/systemui/log/DebugLogger.kt b/packages/SystemUI/src-debug/com/android/systemui/log/DebugLogger.kt
index af29b05..8d1de0e 100644
--- a/packages/SystemUI/src-debug/com/android/systemui/log/DebugLogger.kt
+++ b/packages/SystemUI/src-debug/com/android/systemui/log/DebugLogger.kt
@@ -62,6 +62,8 @@
      * @param error: a [Throwable] to log.
      * @param message: a lazily evaluated message you wish to log.
      */
+    @JvmOverloads
+    @JvmName("logcatMessage")
     inline fun Any.debugLog(
         enabled: Boolean = Build.IS_DEBUGGABLE,
         priority: Int = Log.DEBUG,
diff --git a/packages/SystemUI/src-release/com/android/systemui/log/DebugLogger.kt b/packages/SystemUI/src-release/com/android/systemui/log/DebugLogger.kt
index 2764a1f..e29ce2d 100644
--- a/packages/SystemUI/src-release/com/android/systemui/log/DebugLogger.kt
+++ b/packages/SystemUI/src-release/com/android/systemui/log/DebugLogger.kt
@@ -22,6 +22,7 @@
 /** An empty logger for release builds. */
 object DebugLogger {
 
+    @JvmOverloads
     @JvmName("logcatMessage")
     inline fun Any.debugLog(
         enabled: Boolean = Build.IS_DEBUGGABLE,
diff --git a/packages/SystemUI/src/com/android/systemui/accessibility/SystemActions.java b/packages/SystemUI/src/com/android/systemui/accessibility/SystemActions.java
index 37e9dc1a..7750f6b 100644
--- a/packages/SystemUI/src/com/android/systemui/accessibility/SystemActions.java
+++ b/packages/SystemUI/src/com/android/systemui/accessibility/SystemActions.java
@@ -233,7 +233,7 @@
         // NotificationShadeWindowController.registerCallback() only keeps weak references.
         mNotificationShadeCallback =
                 (keyguardShowing, keyguardOccluded, keyguardGoingAway, bouncerShowing, mDozing,
-                        panelExpanded, isDreaming) ->
+                        panelExpanded, isDreaming, communalShowing) ->
                         registerOrUnregisterDismissNotificationShadeAction();
         mScreenshotHelper = new ScreenshotHelper(mContext);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/model/SceneContainerPlugin.kt b/packages/SystemUI/src/com/android/systemui/model/SceneContainerPlugin.kt
index 5084944..42f66cc 100644
--- a/packages/SystemUI/src/com/android/systemui/model/SceneContainerPlugin.kt
+++ b/packages/SystemUI/src/com/android/systemui/model/SceneContainerPlugin.kt
@@ -18,12 +18,14 @@
 
 import com.android.compose.animation.scene.ObservableTransitionState
 import com.android.compose.animation.scene.SceneKey
+import com.android.systemui.Flags.glanceableHubBackGesture
 import com.android.systemui.dagger.SysUISingleton
 import com.android.systemui.scene.domain.interactor.SceneContainerOcclusionInteractor
 import com.android.systemui.scene.domain.interactor.SceneInteractor
 import com.android.systemui.scene.shared.flag.SceneContainerFlag
 import com.android.systemui.scene.shared.model.Scenes
 import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_BOUNCER_SHOWING
+import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_COMMUNAL_HUB_SHOWING
 import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED
 import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_NOTIFICATION_PANEL_VISIBLE
 import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_QUICK_SETTINGS_EXPANDED
@@ -105,6 +107,10 @@
                     {
                         it.scene == Scenes.Lockscreen && it.invisibleDueToOcclusion
                     },
+                SYSUI_STATE_COMMUNAL_HUB_SHOWING to
+                    {
+                        glanceableHubBackGesture() && it.scene == Scenes.Communal
+                    }
             )
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
index e07b057..4e2e227 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
@@ -26,11 +26,13 @@
 import static android.view.WindowManagerPolicyConstants.NAV_BAR_MODE_3BUTTON;
 
 import static com.android.internal.accessibility.common.ShortcutConstants.CHOOSER_PACKAGE_NAME;
+import static com.android.systemui.Flags.glanceableHubBackGesture;
 import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_SYSUI_PROXY;
 import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_UNFOLD_ANIMATION_FORWARDER;
 import static com.android.systemui.shared.system.QuickStepContract.KEY_EXTRA_UNLOCK_ANIMATION_CONTROLLER;
 import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_AWAKE;
 import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_BOUNCER_SHOWING;
+import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_COMMUNAL_HUB_SHOWING;
 import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_DEVICE_DOZING;
 import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_DEVICE_DREAMING;
 import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_FREEFORM_ACTIVE_IN_DESKTOP_MODE;
@@ -792,7 +794,7 @@
 
     private void onStatusBarStateChanged(boolean keyguardShowing, boolean keyguardOccluded,
             boolean keyguardGoingAway, boolean bouncerShowing, boolean isDozing,
-            boolean panelExpanded, boolean isDreaming) {
+            boolean panelExpanded, boolean isDreaming, boolean communalShowing) {
         mSysUiState.setFlag(SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING,
                         keyguardShowing && !keyguardOccluded)
                 .setFlag(SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED,
@@ -802,6 +804,8 @@
                 .setFlag(SYSUI_STATE_BOUNCER_SHOWING, bouncerShowing)
                 .setFlag(SYSUI_STATE_DEVICE_DOZING, isDozing)
                 .setFlag(SYSUI_STATE_DEVICE_DREAMING, isDreaming)
+                .setFlag(SYSUI_STATE_COMMUNAL_HUB_SHOWING,
+                        glanceableHubBackGesture() && communalShowing)
                 .commitUpdate(mContext.getDisplayId());
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsActivity.java b/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsActivity.java
index c4f6cd9..8feefa4 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsActivity.java
@@ -62,6 +62,7 @@
 import com.android.internal.logging.UiEventLogger.UiEventEnum;
 import com.android.settingslib.Utils;
 import com.android.systemui.Flags;
+import com.android.systemui.log.DebugLogger;
 import com.android.systemui.res.R;
 import com.android.systemui.screenshot.scroll.CropView;
 import com.android.systemui.settings.UserTracker;
@@ -307,13 +308,16 @@
                 && mViewModel.getBacklinksLiveData().getValue() != null) {
             ClipData backlinksData = mViewModel.getBacklinksLiveData().getValue().getClipData();
             data.putParcelable(EXTRA_CLIP_DATA, backlinksData);
+
+            DebugLogger.INSTANCE.logcatMessage(this,
+                    () -> "setResultThenFinish: sending notes app ClipData");
         }
 
         try {
             mResultReceiver.send(Activity.RESULT_OK, data);
             logUiEvent(SCREENSHOT_FOR_NOTE_ACCEPTED);
         } catch (Exception e) {
-            Log.e(TAG, "Error while returning data to trampoline activity", e);
+            Log.e(TAG, "Error while sending data to trampoline activity", e);
         }
 
         // Nullify the ResultReceiver before finishing to avoid resending the result.
@@ -354,6 +358,7 @@
             }
         } catch (Exception e) {
             // Do nothing.
+            Log.e(TAG, "Error while sending trampoline activity error code: " + errorCode, e);
         }
 
         // Nullify the ResultReceiver to avoid resending the result.
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsTrampolineActivity.java b/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsTrampolineActivity.java
index 0161f78..ef18fbe 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsTrampolineActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsTrampolineActivity.java
@@ -53,6 +53,7 @@
 import com.android.systemui.dagger.qualifiers.Application;
 import com.android.systemui.dagger.qualifiers.Background;
 import com.android.systemui.dagger.qualifiers.Main;
+import com.android.systemui.log.DebugLogger;
 import com.android.systemui.notetask.NoteTaskController;
 import com.android.systemui.notetask.NoteTaskEntryPoint;
 import com.android.systemui.res.R;
@@ -265,11 +266,15 @@
             if (statusCode == CAPTURE_CONTENT_FOR_NOTE_SUCCESS) {
                 Uri uri = resultData.getParcelable(EXTRA_SCREENSHOT_URI, Uri.class);
                 convertedData.setData(uri);
-            }
 
-            if (resultData.containsKey(EXTRA_CLIP_DATA)) {
-                ClipData backlinksData = resultData.getParcelable(EXTRA_CLIP_DATA, ClipData.class);
-                convertedData.setClipData(backlinksData);
+                if (resultData.containsKey(EXTRA_CLIP_DATA)) {
+                    ClipData backlinksData = resultData.getParcelable(EXTRA_CLIP_DATA,
+                            ClipData.class);
+                    convertedData.setClipData(backlinksData);
+
+                    DebugLogger.INSTANCE.logcatMessage(this,
+                            () -> "onReceiveResult: sending notes app ClipData");
+                }
             }
 
             // Broadcast no longer required, setting it to null.
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsViewModel.java b/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsViewModel.java
index d30d518..8c833ec 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsViewModel.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/appclips/AppClipsViewModel.java
@@ -54,6 +54,7 @@
 
 import com.android.systemui.dagger.qualifiers.Background;
 import com.android.systemui.dagger.qualifiers.Main;
+import com.android.systemui.log.DebugLogger;
 import com.android.systemui.screenshot.AssistContentRequester;
 import com.android.systemui.screenshot.ImageExporter;
 
@@ -143,6 +144,7 @@
      * @param displayId       id of the display to query tasks for Backlinks data
      */
     void triggerBacklinks(Set<Integer> taskIdsToIgnore, int displayId) {
+        DebugLogger.INSTANCE.logcatMessage(this, () -> "Backlinks triggered");
         mBgExecutor.execute(() -> {
             ListenableFuture<InternalBacklinksData> backlinksData = getBacklinksData(
                     taskIdsToIgnore, displayId);
@@ -247,6 +249,10 @@
     }
 
     private boolean shouldIncludeTask(RootTaskInfo taskInfo, Set<Integer> taskIdsToIgnore) {
+        DebugLogger.INSTANCE.logcatMessage(this,
+                () -> String.format("shouldIncludeTask taskId %d; topActivity %s", taskInfo.taskId,
+                        taskInfo.topActivity));
+
         // Only consider tasks that shouldn't be ignored, are visible, running, and have a launcher
         // icon. Furthermore, types such as launcher/home/dock/assistant are ignored.
         return !taskIdsToIgnore.contains(taskInfo.taskId)
@@ -267,6 +273,10 @@
 
     private ListenableFuture<InternalBacklinksData> getBacklinksDataForTaskId(
             RootTaskInfo taskInfo) {
+        DebugLogger.INSTANCE.logcatMessage(this,
+                () -> String.format("getBacklinksDataForTaskId for taskId %d; topActivity %s",
+                        taskInfo.taskId, taskInfo.topActivity));
+
         SettableFuture<InternalBacklinksData> backlinksData = SettableFuture.create();
         int taskId = taskInfo.taskId;
         mAssistContentRequester.requestAssistContent(taskId, assistContent ->
@@ -295,6 +305,10 @@
      */
     private InternalBacklinksData getBacklinksDataFromAssistContent(RootTaskInfo taskInfo,
             @Nullable AssistContent content) {
+        DebugLogger.INSTANCE.logcatMessage(this,
+                () -> String.format("getBacklinksDataFromAssistContent taskId %d; topActivity %s",
+                        taskInfo.taskId, taskInfo.topActivity));
+
         String appName = getAppNameOfTask(taskInfo);
         String packageName = taskInfo.topActivity.getPackageName();
         Drawable appIcon = taskInfo.topActivityInfo.loadIcon(mPackageManager);
@@ -307,22 +321,34 @@
 
         // First preference is given to app provided uri.
         if (content.isAppProvidedWebUri()) {
+            DebugLogger.INSTANCE.logcatMessage(this,
+                    () -> "getBacklinksDataFromAssistContent: app has provided a uri");
+
             Uri uri = content.getWebUri();
             Intent backlinksIntent = new Intent(ACTION_VIEW).setData(uri);
             if (doesIntentResolveToSamePackage(backlinksIntent, packageName)) {
+                DebugLogger.INSTANCE.logcatMessage(this,
+                        () -> "getBacklinksDataFromAssistContent: using app provided uri");
                 return new InternalBacklinksData(ClipData.newRawUri(appName, uri), appIcon);
             }
         }
 
         // Second preference is given to app provided, hopefully deep-linking, intent.
         if (content.isAppProvidedIntent()) {
+            DebugLogger.INSTANCE.logcatMessage(this,
+                    () -> "getBacklinksDataFromAssistContent: app has provided an intent");
+
             Intent backlinksIntent = content.getIntent();
             if (doesIntentResolveToSamePackage(backlinksIntent, packageName)) {
+                DebugLogger.INSTANCE.logcatMessage(this,
+                        () -> "getBacklinksDataFromAssistContent: using app provided intent");
                 return new InternalBacklinksData(ClipData.newIntent(appName, backlinksIntent),
                         appIcon);
             }
         }
 
+        DebugLogger.INSTANCE.logcatMessage(this,
+                () -> "getBacklinksDataFromAssistContent: using fallback");
         return fallback;
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/shade/GlanceableHubContainerController.kt b/packages/SystemUI/src/com/android/systemui/shade/GlanceableHubContainerController.kt
index ba4c29a..d870fe6 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/GlanceableHubContainerController.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/GlanceableHubContainerController.kt
@@ -17,6 +17,7 @@
 package com.android.systemui.shade
 
 import android.content.Context
+import android.graphics.Insets
 import android.graphics.Rect
 import android.os.PowerManager
 import android.os.SystemClock
@@ -25,6 +26,7 @@
 import android.view.MotionEvent
 import android.view.View
 import android.view.ViewGroup
+import android.view.WindowInsets
 import android.widget.FrameLayout
 import androidx.activity.OnBackPressedDispatcher
 import androidx.activity.OnBackPressedDispatcherOwner
@@ -37,6 +39,7 @@
 import androidx.lifecycle.repeatOnLifecycle
 import com.android.compose.theme.PlatformTheme
 import com.android.internal.annotations.VisibleForTesting
+import com.android.systemui.Flags.glanceableHubBackGesture
 import com.android.systemui.ambient.touch.TouchMonitor
 import com.android.systemui.ambient.touch.dagger.AmbientTouchComponent
 import com.android.systemui.communal.dagger.Communal
@@ -259,15 +262,33 @@
             // Run when the touch handling lifecycle is RESUMED, meaning the hub is visible and not
             // occluded.
             lifecycleRegistry.repeatOnLifecycle(Lifecycle.State.RESUMED) {
-                val exclusionRect =
-                    Rect(
-                        0,
-                        topEdgeSwipeRegionWidth,
-                        containerView.right,
-                        containerView.bottom - bottomEdgeSwipeRegionWidth
-                    )
+                // Avoid adding exclusion to right/left edges to allow back gestures.
+                val insets =
+                    if (glanceableHubBackGesture()) {
+                        containerView.rootWindowInsets.getInsets(WindowInsets.Type.systemGestures())
+                    } else {
+                        Insets.NONE
+                    }
 
-                containerView.systemGestureExclusionRects = listOf(exclusionRect)
+                containerView.systemGestureExclusionRects =
+                    listOf(
+                        // Only allow swipe up to bouncer and swipe down to shade in the very
+                        // top/bottom to avoid conflicting with widgets in the hub grid.
+                        Rect(
+                            insets.left,
+                            topEdgeSwipeRegionWidth,
+                            containerView.right - insets.right,
+                            containerView.bottom - bottomEdgeSwipeRegionWidth
+                        ),
+                        // Disable back gestures on the left side of the screen, to avoid
+                        // conflicting with scene transitions.
+                        Rect(
+                            0,
+                            0,
+                            insets.right,
+                            containerView.bottom,
+                        )
+                    )
             }
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowControllerImpl.java b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowControllerImpl.java
index f67d0c1..bc5cf2a 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/shade/NotificationShadeWindowControllerImpl.java
@@ -644,7 +644,8 @@
                     mCurrentState.bouncerShowing,
                     mCurrentState.dozing,
                     mCurrentState.shadeOrQsExpanded,
-                    mCurrentState.dreaming);
+                    mCurrentState.dreaming,
+                    mCurrentState.communalVisible);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowCallback.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowCallback.java
index da91d6a..6ac7f11 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowCallback.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowCallback.java
@@ -26,5 +26,5 @@
      */
     void onStateChanged(boolean keyguardShowing, boolean keyguardOccluded,
             boolean keyguardGoingAway, boolean bouncerShowing, boolean isDozing,
-            boolean panelExpanded, boolean isDreaming);
+            boolean panelExpanded, boolean isDreaming, boolean communalShowing);
 }
diff --git a/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java b/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java
index 8457bdb..45799b2 100644
--- a/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java
+++ b/packages/SystemUI/src/com/android/systemui/wmshell/BubblesManager.java
@@ -261,7 +261,7 @@
         // Store callback in a field so it won't get GC'd
         mStatusBarWindowCallback =
                 (keyguardShowing, keyguardOccluded, keyguardGoingAway, bouncerShowing, isDozing,
-                        panelExpanded, isDreaming) -> {
+                        panelExpanded, isDreaming, communalShowing) -> {
                     if (panelExpanded != mPanelExpanded) {
                         mPanelExpanded = panelExpanded;
                         mBubbles.onNotificationPanelExpandedChanged(panelExpanded);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shade/GlanceableHubContainerControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/shade/GlanceableHubContainerControllerTest.kt
index b0213a4..169511f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shade/GlanceableHubContainerControllerTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/shade/GlanceableHubContainerControllerTest.kt
@@ -16,19 +16,24 @@
 
 package com.android.systemui.shade
 
+import android.graphics.Insets
 import android.graphics.Rect
 import android.os.PowerManager
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
 import android.testing.AndroidTestingRunner
 import android.testing.TestableLooper
 import android.testing.ViewUtils
 import android.view.MotionEvent
 import android.view.View
+import android.view.WindowInsets
 import android.widget.FrameLayout
 import androidx.lifecycle.Lifecycle
 import androidx.lifecycle.LifecycleOwner
 import androidx.test.filters.SmallTest
 import com.android.compose.animation.scene.SceneKey
 import com.android.systemui.Flags
+import com.android.systemui.Flags.FLAG_GLANCEABLE_HUB_BACK_GESTURE
 import com.android.systemui.SysuiTestCase
 import com.android.systemui.ambient.touch.TouchHandler
 import com.android.systemui.ambient.touch.TouchMonitor
@@ -66,6 +71,9 @@
 import org.mockito.Mock
 import org.mockito.Mockito.`when`
 import org.mockito.MockitoAnnotations
+import org.mockito.kotlin.doReturn
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.spy
 
 @ExperimentalCoroutinesApi
 @RunWith(AndroidTestingRunner::class)
@@ -317,6 +325,7 @@
         }
 
     @Test
+    @DisableFlags(FLAG_GLANCEABLE_HUB_BACK_GESTURE)
     fun gestureExclusionZone_setAfterInit() =
         with(kosmos) {
             testScope.runTest {
@@ -325,10 +334,41 @@
                 assertThat(containerView.systemGestureExclusionRects)
                     .containsExactly(
                         Rect(
-                            /* left */ 0,
-                            /* top */ TOP_SWIPE_REGION_WIDTH,
-                            /* right */ CONTAINER_WIDTH,
-                            /* bottom */ CONTAINER_HEIGHT - BOTTOM_SWIPE_REGION_WIDTH
+                            /* left= */ 0,
+                            /* top= */ TOP_SWIPE_REGION_WIDTH,
+                            /* right= */ CONTAINER_WIDTH,
+                            /* bottom= */ CONTAINER_HEIGHT - BOTTOM_SWIPE_REGION_WIDTH
+                        ),
+                        Rect(
+                            /* left= */ 0,
+                            /* top= */ 0,
+                            /* right= */ 0,
+                            /* bottom= */ CONTAINER_HEIGHT
+                        )
+                    )
+            }
+        }
+
+    @Test
+    @EnableFlags(FLAG_GLANCEABLE_HUB_BACK_GESTURE)
+    fun gestureExclusionZone_setAfterInit_backGestureEnabled() =
+        with(kosmos) {
+            testScope.runTest {
+                goToScene(CommunalScenes.Communal)
+
+                assertThat(containerView.systemGestureExclusionRects)
+                    .containsExactly(
+                        Rect(
+                            /* left= */ FAKE_INSETS.left,
+                            /* top= */ TOP_SWIPE_REGION_WIDTH,
+                            /* right= */ CONTAINER_WIDTH - FAKE_INSETS.right,
+                            /* bottom= */ CONTAINER_HEIGHT - BOTTOM_SWIPE_REGION_WIDTH
+                        ),
+                        Rect(
+                            /* left= */ 0,
+                            /* top= */ 0,
+                            /* right= */ FAKE_INSETS.right,
+                            /* bottom= */ CONTAINER_HEIGHT
                         )
                     )
             }
@@ -340,6 +380,9 @@
             testScope.runTest {
                 goToScene(CommunalScenes.Communal)
 
+                // Exclusion rect is set.
+                assertThat(containerView.systemGestureExclusionRects).isNotEmpty()
+
                 // Shade shows up.
                 shadeTestUtil.setQsExpansion(1.0f)
                 testableLooper.processAllMessages()
@@ -355,6 +398,9 @@
             testScope.runTest {
                 goToScene(CommunalScenes.Communal)
 
+                // Exclusion rect is set.
+                assertThat(containerView.systemGestureExclusionRects).isNotEmpty()
+
                 // Bouncer is visible.
                 fakeKeyguardBouncerRepository.setPrimaryShow(true)
                 testableLooper.processAllMessages()
@@ -371,7 +417,7 @@
                 goToScene(CommunalScenes.Communal)
 
                 // Exclusion rect is set.
-                assertThat(containerView.systemGestureExclusionRects).hasSize(1)
+                assertThat(containerView.systemGestureExclusionRects).isNotEmpty()
 
                 // Leave the hub.
                 goToScene(CommunalScenes.Blank)
@@ -399,7 +445,12 @@
         }
 
     private fun initAndAttachContainerView() {
-        containerView = View(context)
+        val mockInsets =
+            mock<WindowInsets> {
+                on { getInsets(WindowInsets.Type.systemGestures()) } doReturn FAKE_INSETS
+            }
+
+        containerView = spy(View(context)) { on { rootWindowInsets } doReturn mockInsets }
 
         parentView = FrameLayout(context)
 
@@ -422,6 +473,7 @@
         private const val RIGHT_SWIPE_REGION_WIDTH = 20
         private const val TOP_SWIPE_REGION_WIDTH = 12
         private const val BOTTOM_SWIPE_REGION_WIDTH = 14
+        private val FAKE_INSETS = Insets.of(10, 20, 30, 50)
 
         /**
          * A touch down event right in the middle of the screen, to avoid being in any of the swipe
diff --git a/services/profcollect/src/com/android/server/profcollect/ProfcollectForwardingService.java b/services/profcollect/src/com/android/server/profcollect/ProfcollectForwardingService.java
index 64dbc50..c76bcf8 100644
--- a/services/profcollect/src/com/android/server/profcollect/ProfcollectForwardingService.java
+++ b/services/profcollect/src/com/android/server/profcollect/ProfcollectForwardingService.java
@@ -287,7 +287,7 @@
         if (randomNum < traceFrequency) {
             BackgroundThread.get().getThreadHandler().post(() -> {
                 try {
-                    mIProfcollect.trace_once("applaunch");
+                    mIProfcollect.trace_system("applaunch");
                 } catch (RemoteException e) {
                     Log.e(LOG_TAG, "Failed to initiate trace: " + e.getMessage());
                 }
@@ -327,7 +327,7 @@
             // Dex2oat could take a while before it starts. Add a short delay before start tracing.
             BackgroundThread.get().getThreadHandler().postDelayed(() -> {
                 try {
-                    mIProfcollect.trace_once("dex2oat");
+                    mIProfcollect.trace_system("dex2oat");
                 } catch (RemoteException e) {
                     Log.e(LOG_TAG, "Failed to initiate trace: " + e.getMessage());
                 }
@@ -404,7 +404,7 @@
                 String traceTag = traceInitialization ? "camera_init" : "camera";
                 BackgroundThread.get().getThreadHandler().postDelayed(() -> {
                     try {
-                        mIProfcollect.trace_once(traceTag);
+                        mIProfcollect.trace_system(traceTag);
                     } catch (RemoteException e) {
                         Log.e(LOG_TAG, "Failed to initiate trace: " + e.getMessage());
                     }
diff --git a/tools/aapt2/xml/XmlPullParser.cpp b/tools/aapt2/xml/XmlPullParser.cpp
index 203832d..8abc26d 100644
--- a/tools/aapt2/xml/XmlPullParser.cpp
+++ b/tools/aapt2/xml/XmlPullParser.cpp
@@ -14,11 +14,13 @@
  * limitations under the License.
  */
 
-#include <iostream>
+#include "xml/XmlPullParser.h"
+
+#include <algorithm>
 #include <string>
+#include <tuple>
 
 #include "util/Util.h"
-#include "xml/XmlPullParser.h"
 #include "xml/XmlUtil.h"
 
 using ::android::InputStream;
@@ -325,5 +327,18 @@
   return {};
 }
 
+XmlPullParser::const_iterator XmlPullParser::FindAttribute(android::StringPiece namespace_uri,
+                                                           android::StringPiece name) const {
+  const auto end_iter = end_attributes();
+  const auto iter = std::lower_bound(begin_attributes(), end_iter, std::tuple(namespace_uri, name),
+                                     [](const Attribute& attr, const auto& rhs) {
+                                       return std::tie(attr.namespace_uri, attr.name) < rhs;
+                                     });
+  if (iter != end_iter && namespace_uri == iter->namespace_uri && name == iter->name) {
+    return iter;
+  }
+  return end_iter;
+}
+
 }  // namespace xml
 }  // namespace aapt
diff --git a/tools/aapt2/xml/XmlPullParser.h b/tools/aapt2/xml/XmlPullParser.h
index 655e6dc..64274d0 100644
--- a/tools/aapt2/xml/XmlPullParser.h
+++ b/tools/aapt2/xml/XmlPullParser.h
@@ -19,8 +19,7 @@
 
 #include <expat.h>
 
-#include <algorithm>
-#include <istream>
+#include <optional>
 #include <ostream>
 #include <queue>
 #include <stack>
@@ -302,31 +301,6 @@
   return compare(rhs) != 0;
 }
 
-inline XmlPullParser::const_iterator XmlPullParser::FindAttribute(
-    android::StringPiece namespace_uri, android::StringPiece name) const {
-  const auto end_iter = end_attributes();
-  const auto iter = std::lower_bound(
-      begin_attributes(), end_iter,
-      std::pair<android::StringPiece, android::StringPiece>(namespace_uri, name),
-      [](const Attribute& attr,
-         const std::pair<android::StringPiece, android::StringPiece>& rhs) -> bool {
-        int cmp = attr.namespace_uri.compare(
-            0, attr.namespace_uri.size(), rhs.first.data(), rhs.first.size());
-        if (cmp < 0) return true;
-        if (cmp > 0) return false;
-        cmp = attr.name.compare(0, attr.name.size(), rhs.second.data(),
-                                rhs.second.size());
-        if (cmp < 0) return true;
-        return false;
-      });
-
-  if (iter != end_iter && namespace_uri == iter->namespace_uri &&
-      name == iter->name) {
-    return iter;
-  }
-  return end_iter;
-}
-
 }  // namespace xml
 }  // namespace aapt