Exit focus search when the next candidate is the same with the current
candidate

Fixes: 160924453
Test: maual test and atest CarRotaryControllerRoboTests
Change-Id: I628feec78416906480ae611a299bb2880906780a
diff --git a/src/com/android/car/rotary/Navigator.java b/src/com/android/car/rotary/Navigator.java
index 81a53d0..708d2aa 100644
--- a/src/com/android/car/rotary/Navigator.java
+++ b/src/com/android/car/rotary/Navigator.java
@@ -325,11 +325,16 @@
             AccessibilityNodeInfo candidateFocusArea =
                     nextCandidate == null ? null : getAncestorFocusArea(nextCandidate);
 
-            // Only advance to nextCandidate if it's in the same focus area and it isn't a
-            // FocusParkingView. The second condition prevents wrap-around when there is only one
-            // focus area in the window, including when the root node is treated as a focus area.
+            // Only advance to nextCandidate if:
+            // 1. it's in the same focus area,
+            // 2. and it isn't a FocusParkingView (this is to prevent wrap-around when there is only
+            //    one focus area in the window, including when the root node is treated as a focus
+            //    area),
+            // 3. and nextCandidate is different from candidate (if sourceNode is the first
+            //    focusable node in the window, searching backward will return sourceNode itself).
             if (nextCandidate != null && currentFocusArea.equals(candidateFocusArea)
-                    && !Utils.isFocusParkingView(nextCandidate)) {
+                    && !Utils.isFocusParkingView(nextCandidate)
+                    && !nextCandidate.equals(candidate)) {
                 // We need to skip nextTargetNode if:
                 // 1. it can't perform focus action (focusSearch() may return a node with zero
                 //    width and height),
diff --git a/tests/robotests/src/com/android/car/rotary/NavigatorTest.java b/tests/robotests/src/com/android/car/rotary/NavigatorTest.java
index c89482f..8e58b95 100644
--- a/tests/robotests/src/com/android/car/rotary/NavigatorTest.java
+++ b/tests/robotests/src/com/android/car/rotary/NavigatorTest.java
@@ -303,6 +303,22 @@
     }
 
     /**
+     * Tests {@link Navigator#findRotateTarget} in the following node tree:
+     * <pre>
+     *             node
+     * </pre>
+     */
+    @Test
+    public void testFindRotateTargetWithOneNode() {
+        AccessibilityNodeInfo node = mNodeBuilder.build();
+        int direction = View.FOCUS_BACKWARD;
+        when(node.focusSearch(direction)).thenReturn(node);
+
+        FindRotateTargetResult target = mNavigator.findRotateTarget(node, direction, 1);
+        assertThat(target).isNull();
+    }
+
+    /**
      * Tests {@link Navigator#findRotateTarget} in the following layout:
      * <pre>
      *     ============ focus area ============