Merge branch 'heads/android-14.0.0_r18' into 14-dev

This commit is contained in:
MrSluffy committed 2023-12-16 17:18:13 +08:00
1 parent 32700b0100
commit cc8f9828ab
756 files changed
+23785 -12235

No files matched your search

@@ -0,0 +1,127 @@
package com.android.launcher3.model
import android.app.prediction.AppPredictor
import android.app.prediction.AppTarget
import android.app.prediction.AppTargetEvent
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.launcher3.LauncherAppState
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_PREDICTION
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_WALLPAPERS
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_WIDGETS_PREDICTION
import com.android.launcher3.util.LauncherModelHelper
import org.junit.After
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
import org.mockito.MockitoAnnotations
/** Unit tests for [QuickstepModelDelegate]. */
@RunWith(AndroidJUnit4::class)
class QuickstepModelDelegateTest {
private lateinit var underTest: QuickstepModelDelegate
private lateinit var modelHelper: LauncherModelHelper
@Mock private lateinit var target: AppTarget
@Mock private lateinit var mockedAppTargetEvent: AppTargetEvent
@Mock private lateinit var allAppsPredictor: AppPredictor
@Mock private lateinit var hotseatPredictor: AppPredictor
@Mock private lateinit var widgetRecommendationPredictor: AppPredictor
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
modelHelper = LauncherModelHelper()
underTest = QuickstepModelDelegate(modelHelper.sandboxContext)
underTest.mAllAppsState.predictor = allAppsPredictor
underTest.mHotseatState.predictor = hotseatPredictor
underTest.mWidgetsRecommendationState.predictor = widgetRecommendationPredictor
underTest.mApp = LauncherAppState.getInstance(modelHelper.sandboxContext)
underTest.mDataModel = BgDataModel()
}
@After
fun tearDown() {
modelHelper.destroy()
}
@Test
fun onAppTargetEvent_notifyTarget() {
underTest.onAppTargetEvent(mockedAppTargetEvent, CONTAINER_PREDICTION)
verify(allAppsPredictor).notifyAppTargetEvent(mockedAppTargetEvent)
verifyZeroInteractions(hotseatPredictor)
verifyZeroInteractions(widgetRecommendationPredictor)
}
@Test
fun onWidgetPrediction_notifyWidgetRecommendationPredictor() {
underTest.onAppTargetEvent(mockedAppTargetEvent, CONTAINER_WIDGETS_PREDICTION)
verifyZeroInteractions(allAppsPredictor)
verify(widgetRecommendationPredictor).notifyAppTargetEvent(mockedAppTargetEvent)
verifyZeroInteractions(hotseatPredictor)
}
@Test
fun onHotseatPrediction_notifyHotseatPredictor() {
underTest.onAppTargetEvent(mockedAppTargetEvent, CONTAINER_HOTSEAT_PREDICTION)
verifyZeroInteractions(allAppsPredictor)
verifyZeroInteractions(widgetRecommendationPredictor)
verify(hotseatPredictor).notifyAppTargetEvent(mockedAppTargetEvent)
}
@Test
fun onOtherClient_notifyHotseatPredictor() {
underTest.onAppTargetEvent(mockedAppTargetEvent, CONTAINER_WALLPAPERS)
verifyZeroInteractions(allAppsPredictor)
verifyZeroInteractions(widgetRecommendationPredictor)
verify(hotseatPredictor).notifyAppTargetEvent(mockedAppTargetEvent)
}
@Test
fun hotseatActionPin_recreateHotSeat() {
assertSame(underTest.mHotseatState.predictor, hotseatPredictor)
val appTargetEvent = AppTargetEvent.Builder(target, AppTargetEvent.ACTION_PIN).build()
underTest.markActive()
underTest.onAppTargetEvent(appTargetEvent, CONTAINER_HOTSEAT_PREDICTION)
verify(hotseatPredictor).destroy()
assertNotSame(underTest.mHotseatState.predictor, hotseatPredictor)
}
@Test
fun hotseatActionUnpin_recreateHotSeat() {
assertSame(underTest.mHotseatState.predictor, hotseatPredictor)
underTest.markActive()
val appTargetEvent = AppTargetEvent.Builder(target, AppTargetEvent.ACTION_UNPIN).build()
underTest.onAppTargetEvent(appTargetEvent, CONTAINER_HOTSEAT_PREDICTION)
verify(hotseatPredictor).destroy()
assertNotSame(underTest.mHotseatState.predictor, hotseatPredictor)
}
@Test
fun container_actionPin_notRecreateHotSeat() {
assertSame(underTest.mHotseatState.predictor, hotseatPredictor)
val appTargetEvent = AppTargetEvent.Builder(target, AppTargetEvent.ACTION_UNPIN).build()
underTest.markActive()
underTest.onAppTargetEvent(appTargetEvent, CONTAINER_PREDICTION)
verify(allAppsPredictor, never()).destroy()
verify(hotseatPredictor, never()).destroy()
assertSame(underTest.mHotseatState.predictor, hotseatPredictor)
}
}
@@ -20,6 +20,7 @@ import static android.os.Process.myUserHandle;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_WIDGETS_PREDICTION;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import static com.android.launcher3.util.TestUtil.runOnExecutorSync;
import static com.android.launcher3.util.WidgetUtils.createAppWidgetProviderInfo;
import static com.google.common.truth.Truth.assertThat;
@@ -40,11 +41,9 @@ import android.text.TextUtils;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.icons.ComponentWithLabel;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.QuickstepModelDelegate.PredictorState;
import com.android.launcher3.util.LauncherLayoutBuilder;
import com.android.launcher3.util.LauncherModelHelper;
import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
import com.android.launcher3.widget.PendingAddWidgetInfo;
@@ -53,8 +52,6 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Arrays;
import java.util.List;
@@ -76,17 +73,9 @@ public final class WidgetsPredicationUpdateTaskTest {
private LauncherModelHelper mModelHelper;
private UserHandle mUserHandle;
@Mock
private IconCache mIconCache;
@Before
public void setup() throws Exception {
mModelHelper = new LauncherModelHelper();
MockitoAnnotations.initMocks(this);
doAnswer(invocation -> {
ComponentWithLabel componentWithLabel = invocation.getArgument(0);
return componentWithLabel.getComponent().getShortClassName();
}).when(mIconCache).getTitleNoCache(any());
mUserHandle = myUserHandle();
mApp1Provider1 = createAppWidgetProviderInfo(
@@ -114,16 +103,12 @@ public final class WidgetsPredicationUpdateTaskTest {
.collect(Collectors.toList());
}).when(manager).getInstalledProvidersForPackage(any(), eq(myUserHandle()));
// 2 widgets, app4/provider1 & app5/provider1, have already been added to the workspace.
mModelHelper.initializeData("widgets_predication_update_task_data");
LauncherLayoutBuilder builder = new LauncherLayoutBuilder()
.atWorkspace(0, 1, 2).putWidget("app4", "provider1", 1, 1)
.atWorkspace(0, 1, 3).putWidget("app5", "provider1", 1, 1);
mModelHelper.setupDefaultLayoutProvider(builder);
MAIN_EXECUTOR.submit(() -> mModelHelper.getModel().addCallbacks(mCallback)).get();
MODEL_EXECUTOR.post(() -> mModelHelper.getBgDataModel().widgetsModel.update(
LauncherAppState.getInstance(mModelHelper.sandboxContext),
/* packageUser= */ null));
MODEL_EXECUTOR.submit(() -> { }).get();
MAIN_EXECUTOR.submit(() -> { }).get();
mModelHelper.loadModelSync();
}
@After
@@ -132,65 +117,72 @@ public final class WidgetsPredicationUpdateTaskTest {
}
@Test
public void widgetsRecommendationRan_shouldOnlyReturnNotAddedWidgetsInAppPredictionOrder()
throws Exception {
// WHEN newPredicationTask is executed with app predication of 5 apps.
AppTarget app1 = new AppTarget(new AppTargetId("app1"), "app1", "provider1",
mUserHandle);
AppTarget app2 = new AppTarget(new AppTargetId("app2"), "app2", "provider1",
mUserHandle);
AppTarget app3 = new AppTarget(new AppTargetId("app3"), "app3", "className",
mUserHandle);
AppTarget app4 = new AppTarget(new AppTargetId("app4"), "app4", "provider1",
mUserHandle);
AppTarget app5 = new AppTarget(new AppTargetId("app5"), "app5", "provider1",
mUserHandle);
mModelHelper.executeTaskForTest(
newWidgetsPredicationTask(List.of(app5, app3, app2, app4, app1)))
.forEach(Runnable::run);
public void widgetsRecommendationRan_shouldOnlyReturnNotAddedWidgetsInAppPredictionOrder() {
// Run on model executor so that no other task runs in the middle.
runOnExecutorSync(MODEL_EXECUTOR, () -> {
// WHEN newPredicationTask is executed with app predication of 5 apps.
AppTarget app1 = new AppTarget(new AppTargetId("app1"), "app1", "provider1",
mUserHandle);
AppTarget app2 = new AppTarget(new AppTargetId("app2"), "app2", "provider1",
mUserHandle);
AppTarget app3 = new AppTarget(new AppTargetId("app3"), "app3", "className",
mUserHandle);
AppTarget app4 = new AppTarget(new AppTargetId("app4"), "app4", "provider1",
mUserHandle);
AppTarget app5 = new AppTarget(new AppTargetId("app5"), "app5", "provider1",
mUserHandle);
mCallback.mRecommendedWidgets = null;
mModelHelper.getModel().enqueueModelUpdateTask(
newWidgetsPredicationTask(List.of(app5, app3, app2, app4, app1)));
runOnExecutorSync(MAIN_EXECUTOR, () -> { });
// THEN only 2 widgets are returned because
// 1. app5/provider1 & app4/provider1 have already been added to workspace. They are
// excluded from the result.
// 2. app3 doesn't have a widget.
// 3. only 1 widget is picked from app1 because we only want to promote one widget per app.
List<PendingAddWidgetInfo> recommendedWidgets = mCallback.mRecommendedWidgets.items
.stream()
.map(itemInfo -> (PendingAddWidgetInfo) itemInfo)
.collect(Collectors.toList());
assertThat(recommendedWidgets).hasSize(2);
assertWidgetInfo(recommendedWidgets.get(0).info, mApp2Provider1);
assertWidgetInfo(recommendedWidgets.get(1).info, mApp1Provider1);
// THEN only 2 widgets are returned because
// 1. app5/provider1 & app4/provider1 have already been added to workspace. They are
// excluded from the result.
// 2. app3 doesn't have a widget.
// 3. only 1 widget is picked from app1 because we only want to promote one widget per app.
List<PendingAddWidgetInfo> recommendedWidgets = mCallback.mRecommendedWidgets.items
.stream()
.map(itemInfo -> (PendingAddWidgetInfo) itemInfo)
.collect(Collectors.toList());
assertThat(recommendedWidgets).hasSize(2);
assertWidgetInfo(recommendedWidgets.get(0).info, mApp2Provider1);
assertWidgetInfo(recommendedWidgets.get(1).info, mApp1Provider1);
});
}
@Test
public void widgetsRecommendationRan_shouldReturnPackageWidgetsWhenEmpty()
throws Exception {
public void widgetsRecommendationRan_shouldReturnPackageWidgetsWhenEmpty() {
runOnExecutorSync(MODEL_EXECUTOR, () -> {
// Not installed widget
AppTarget widget1 = new AppTarget(new AppTargetId("app1"), "app1", "provider3",
mUserHandle);
// Not installed app
AppTarget widget3 = new AppTarget(new AppTargetId("app2"), "app3", "provider1",
mUserHandle);
// Workspace added widgets
AppTarget widget4 = new AppTarget(new AppTargetId("app4"), "app4", "provider1",
mUserHandle);
AppTarget widget5 = new AppTarget(new AppTargetId("app5"), "app5", "provider1",
mUserHandle);
mModelHelper.executeTaskForTest(
newWidgetsPredicationTask(List.of(widget5, widget3, widget4, widget1)))
.forEach(Runnable::run);
// Not installed widget
AppTarget widget1 = new AppTarget(new AppTargetId("app1"), "app1", "provider3",
mUserHandle);
// Not installed app
AppTarget widget3 = new AppTarget(new AppTargetId("app2"), "app3", "provider1",
mUserHandle);
// Workspace added widgets
AppTarget widget4 = new AppTarget(new AppTargetId("app4"), "app4", "provider1",
mUserHandle);
AppTarget widget5 = new AppTarget(new AppTargetId("app5"), "app5", "provider1",
mUserHandle);
// THEN only 2 widgets are returned because the launcher only filters out non-exist widgets.
List<PendingAddWidgetInfo> recommendedWidgets = mCallback.mRecommendedWidgets.items
.stream()
.map(itemInfo -> (PendingAddWidgetInfo) itemInfo)
.collect(Collectors.toList());
assertThat(recommendedWidgets).hasSize(2);
// Another widget from the same package
assertWidgetInfo(recommendedWidgets.get(0).info, mApp4Provider2);
assertWidgetInfo(recommendedWidgets.get(1).info, mApp1Provider1);
mCallback.mRecommendedWidgets = null;
mModelHelper.getModel().enqueueModelUpdateTask(
newWidgetsPredicationTask(List.of(widget5, widget3, widget4, widget1)));
runOnExecutorSync(MAIN_EXECUTOR, () -> { });
// THEN only 2 widgets are returned because the launcher only filters out
// non-exist widgets.
List<PendingAddWidgetInfo> recommendedWidgets = mCallback.mRecommendedWidgets.items
.stream()
.map(itemInfo -> (PendingAddWidgetInfo) itemInfo)
.collect(Collectors.toList());
assertThat(recommendedWidgets).hasSize(2);
// Another widget from the same package
assertWidgetInfo(recommendedWidgets.get(0).info, mApp4Provider2);
assertWidgetInfo(recommendedWidgets.get(1).info, mApp1Provider1);
});
}
private void assertWidgetInfo(
@@ -0,0 +1,228 @@
/*
* 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.launcher3.taskbar;
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import static com.android.launcher3.taskbar.TaskbarAutohideSuspendController.FLAG_AUTOHIDE_SUSPEND_HOVERING_ICONS;
import static com.android.launcher3.taskbar.TaskbarHoverToolTipController.HOVER_TOOL_TIP_REVEAL_START_DELAY;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
import android.view.Display;
import android.view.MotionEvent;
import androidx.test.filters.SmallTest;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.util.ActivityContextWrapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.stubbing.Answer;
/**
* Tests for TaskbarHoverToolTipController.
*/
@SmallTest
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper(setAsMainLooper = true)
public class TaskbarHoverToolTipControllerTest extends TaskbarBaseTestCase {
private TaskbarHoverToolTipController mTaskbarHoverToolTipController;
private TestableLooper mTestableLooper;
@Mock private TaskbarView mTaskbarView;
@Mock private MotionEvent mMotionEvent;
@Mock private BubbleTextView mHoverBubbleTextView;
@Mock private FolderIcon mHoverFolderIcon;
@Mock private Display mDisplay;
@Mock private TaskbarDragLayer mTaskbarDragLayer;
private Folder mSpyFolderView;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
Context context = getApplicationContext();
doAnswer((Answer<Object>) invocation -> context.getSystemService(
(String) invocation.getArgument(0)))
.when(taskbarActivityContext).getSystemService(anyString());
when(taskbarActivityContext.getResources()).thenReturn(context.getResources());
when(taskbarActivityContext.getApplicationInfo()).thenReturn(
context.getApplicationInfo());
when(taskbarActivityContext.getDragLayer()).thenReturn(mTaskbarDragLayer);
when(taskbarActivityContext.getMainLooper()).thenReturn(context.getMainLooper());
when(taskbarActivityContext.getDisplay()).thenReturn(mDisplay);
when(mTaskbarDragLayer.getChildCount()).thenReturn(1);
mSpyFolderView = spy(new Folder(new ActivityContextWrapper(context), null));
when(mTaskbarDragLayer.getChildAt(anyInt())).thenReturn(mSpyFolderView);
doReturn(false).when(mSpyFolderView).isOpen();
when(mHoverBubbleTextView.getText()).thenReturn("tooltip");
doAnswer((Answer<Void>) invocation -> {
Object[] args = invocation.getArguments();
((int[]) args[0])[0] = 0;
((int[]) args[0])[1] = 0;
return null;
}).when(mHoverBubbleTextView).getLocationOnScreen(any(int[].class));
when(mHoverBubbleTextView.getWidth()).thenReturn(100);
when(mHoverBubbleTextView.getHeight()).thenReturn(100);
mHoverFolderIcon.mInfo = new FolderInfo();
mHoverFolderIcon.mInfo.title = "tooltip";
doAnswer((Answer<Void>) invocation -> {
Object[] args = invocation.getArguments();
((int[]) args[0])[0] = 0;
((int[]) args[0])[1] = 0;
return null;
}).when(mHoverFolderIcon).getLocationOnScreen(any(int[].class));
when(mHoverFolderIcon.getWidth()).thenReturn(100);
when(mHoverFolderIcon.getHeight()).thenReturn(100);
when(mTaskbarView.getTop()).thenReturn(200);
mTaskbarHoverToolTipController = new TaskbarHoverToolTipController(
taskbarActivityContext, mTaskbarView, mHoverBubbleTextView);
mTestableLooper = TestableLooper.get(this);
}
@Test
public void onHover_hoverEnterIcon_revealToolTip() {
when(mMotionEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_ENTER);
when(mMotionEvent.getActionMasked()).thenReturn(MotionEvent.ACTION_HOVER_ENTER);
boolean hoverHandled =
mTaskbarHoverToolTipController.onHover(mHoverBubbleTextView, mMotionEvent);
// Verify fullscreen is not set until the delayed runnable to reveal the tooltip has run
verify(taskbarActivityContext, never()).setTaskbarWindowFullscreen(true);
waitForIdleSync();
assertThat(hoverHandled).isTrue();
verify(taskbarActivityContext).setAutohideSuspendFlag(FLAG_AUTOHIDE_SUSPEND_HOVERING_ICONS,
true);
verify(taskbarActivityContext).setTaskbarWindowFullscreen(true);
}
@Test
public void onHover_hoverExitIcon_closeToolTip() {
when(mMotionEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_EXIT);
when(mMotionEvent.getActionMasked()).thenReturn(MotionEvent.ACTION_HOVER_EXIT);
boolean hoverHandled =
mTaskbarHoverToolTipController.onHover(mHoverBubbleTextView, mMotionEvent);
waitForIdleSync();
assertThat(hoverHandled).isTrue();
verify(taskbarActivityContext).setAutohideSuspendFlag(FLAG_AUTOHIDE_SUSPEND_HOVERING_ICONS,
false);
}
@Test
public void onHover_hoverEnterFolderIcon_revealToolTip() {
when(mMotionEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_ENTER);
when(mMotionEvent.getActionMasked()).thenReturn(MotionEvent.ACTION_HOVER_ENTER);
boolean hoverHandled =
mTaskbarHoverToolTipController.onHover(mHoverFolderIcon, mMotionEvent);
// Verify fullscreen is not set until the delayed runnable to reveal the tooltip has run
verify(taskbarActivityContext, never()).setTaskbarWindowFullscreen(true);
waitForIdleSync();
assertThat(hoverHandled).isTrue();
verify(taskbarActivityContext).setAutohideSuspendFlag(FLAG_AUTOHIDE_SUSPEND_HOVERING_ICONS,
true);
verify(taskbarActivityContext).setTaskbarWindowFullscreen(true);
}
@Test
public void onHover_hoverExitFolderIcon_closeToolTip() {
when(mMotionEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_EXIT);
when(mMotionEvent.getActionMasked()).thenReturn(MotionEvent.ACTION_HOVER_EXIT);
boolean hoverHandled =
mTaskbarHoverToolTipController.onHover(mHoverFolderIcon, mMotionEvent);
waitForIdleSync();
assertThat(hoverHandled).isTrue();
verify(taskbarActivityContext).setAutohideSuspendFlag(FLAG_AUTOHIDE_SUSPEND_HOVERING_ICONS,
false);
}
@Test
public void onHover_hoverExitFolderOpen_closeToolTip() {
when(mMotionEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_EXIT);
when(mMotionEvent.getActionMasked()).thenReturn(MotionEvent.ACTION_HOVER_EXIT);
doReturn(true).when(mSpyFolderView).isOpen();
boolean hoverHandled =
mTaskbarHoverToolTipController.onHover(mHoverFolderIcon, mMotionEvent);
waitForIdleSync();
assertThat(hoverHandled).isTrue();
verify(taskbarActivityContext).setAutohideSuspendFlag(FLAG_AUTOHIDE_SUSPEND_HOVERING_ICONS,
false);
}
@Test
public void onHover_hoverEnterFolderOpen_noToolTip() {
when(mMotionEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_ENTER);
when(mMotionEvent.getActionMasked()).thenReturn(MotionEvent.ACTION_HOVER_ENTER);
doReturn(true).when(mSpyFolderView).isOpen();
boolean hoverHandled =
mTaskbarHoverToolTipController.onHover(mHoverFolderIcon, mMotionEvent);
assertThat(hoverHandled).isFalse();
}
@Test
public void onHover_hoverMove_noUpdate() {
when(mMotionEvent.getAction()).thenReturn(MotionEvent.ACTION_HOVER_MOVE);
when(mMotionEvent.getActionMasked()).thenReturn(MotionEvent.ACTION_HOVER_MOVE);
boolean hoverHandled =
mTaskbarHoverToolTipController.onHover(mHoverFolderIcon, mMotionEvent);
assertThat(hoverHandled).isFalse();
}
private void waitForIdleSync() {
mTestableLooper.moveTimeForward(HOVER_TOOL_TIP_REVEAL_START_DELAY + 1);
mTestableLooper.processAllMessages();
}
}
@@ -17,6 +17,7 @@ import static com.android.quickstep.OverviewCommandHelper.TYPE_TOGGLE;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_SCREEN_PINNING;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -26,12 +27,14 @@ import static org.mockito.Mockito.when;
import android.os.Handler;
import android.view.View;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import com.android.launcher3.logging.StatsLogManager;
import com.android.quickstep.OverviewCommandHelper;
import com.android.quickstep.SystemUiProxy;
import com.android.quickstep.TouchInteractionService;
import com.android.quickstep.util.AssistUtils;
import org.junit.Before;
import org.junit.Test;
@@ -53,6 +56,8 @@ public class TaskbarNavButtonControllerTest {
@Mock
Handler mockHandler;
@Mock
AssistUtils mockAssistUtils;
@Mock
StatsLogManager mockStatsLogManager;
@Mock
StatsLogManager.StatsLogger mockStatsLogger;
@@ -70,12 +75,15 @@ public class TaskbarNavButtonControllerTest {
MockitoAnnotations.initMocks(this);
when(mockService.getDisplayId()).thenReturn(DISPLAY_ID);
when(mockService.getOverviewCommandHelper()).thenReturn(mockCommandHelper);
when(mockService.getApplicationContext())
.thenReturn(InstrumentationRegistry.getInstrumentation().getTargetContext()
.getApplicationContext());
when(mockStatsLogManager.logger()).thenReturn(mockStatsLogger);
when(mockTaskbarControllers.getTaskbarActivityContext())
.thenReturn(mockTaskbarActivityContext);
doReturn(mockStatsLogManager).when(mockTaskbarActivityContext).getStatsLogManager();
mNavButtonController = new TaskbarNavButtonController(mockService,
mockSystemUiProxy, mockHandler);
mockSystemUiProxy, mockHandler, mockAssistUtils);
}
@Test
@@ -104,16 +112,42 @@ public class TaskbarNavButtonControllerTest {
}
@Test
public void testLongPressHome_enabled() {
public void testLongPressHome_enabled_withoutOverride() {
mNavButtonController.setAssistantLongPressEnabled(true /*assistantLongPressEnabled*/);
when(mockAssistUtils.tryStartAssistOverride(anyInt())).thenReturn(false);
mNavButtonController.onButtonLongClick(BUTTON_HOME, mockView);
verify(mockAssistUtils, times(1)).tryStartAssistOverride(anyInt());
verify(mockSystemUiProxy, times(1)).startAssistant(any());
}
@Test
public void testLongPressHome_disabled() {
mNavButtonController.setAssistantLongPressEnabled(false /*assistantLongPressEnabled*/);
public void testLongPressHome_enabled_withOverride() {
mNavButtonController.setAssistantLongPressEnabled(true /*assistantLongPressEnabled*/);
when(mockAssistUtils.tryStartAssistOverride(anyInt())).thenReturn(true);
mNavButtonController.onButtonLongClick(BUTTON_HOME, mockView);
verify(mockAssistUtils, times(1)).tryStartAssistOverride(anyInt());
verify(mockSystemUiProxy, never()).startAssistant(any());
}
@Test
public void testLongPressHome_disabled_withoutOverride() {
mNavButtonController.setAssistantLongPressEnabled(false /*assistantLongPressEnabled*/);
when(mockAssistUtils.tryStartAssistOverride(anyInt())).thenReturn(false);
mNavButtonController.onButtonLongClick(BUTTON_HOME, mockView);
verify(mockAssistUtils, never()).tryStartAssistOverride(anyInt());
verify(mockSystemUiProxy, never()).startAssistant(any());
}
@Test
public void testLongPressHome_disabled_withOverride() {
mNavButtonController.setAssistantLongPressEnabled(false /*assistantLongPressEnabled*/);
when(mockAssistUtils.tryStartAssistOverride(anyInt())).thenReturn(true);
mNavButtonController.onButtonLongClick(BUTTON_HOME, mockView);
verify(mockAssistUtils, never()).tryStartAssistOverride(anyInt());
verify(mockSystemUiProxy, never()).startAssistant(any());
}
@@ -1,6 +1,9 @@
package com.android.launcher3.taskbar.navbutton
import android.content.res.Resources
import android.view.Surface
import android.view.Surface.ROTATION_270
import android.view.Surface.Rotation
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
@@ -32,6 +35,8 @@ class NavButtonLayoutFactoryTest {
@Mock lateinit var mockRecentsButton: ImageView
@Mock lateinit var mockHomeButton: ImageView
private var surfaceRotation = Surface.ROTATION_0
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
@@ -60,7 +65,8 @@ class NavButtonLayoutFactoryTest {
isKidsMode = true,
isInSetup = false,
isThreeButtonNav = false,
phoneMode = false
phoneMode = false,
surfaceRotation = surfaceRotation
)
assert(layoutter is KidsNavLayoutter)
}
@@ -74,7 +80,8 @@ class NavButtonLayoutFactoryTest {
isKidsMode = false,
isInSetup = true,
isThreeButtonNav = false,
phoneMode = false
phoneMode = false,
surfaceRotation = surfaceRotation
)
assert(layoutter is SetupNavLayoutter)
}
@@ -88,7 +95,8 @@ class NavButtonLayoutFactoryTest {
isKidsMode = false,
isInSetup = false,
isThreeButtonNav = false,
phoneMode = false
phoneMode = false,
surfaceRotation = surfaceRotation
)
assert(layoutter is TaskbarNavLayoutter)
}
@@ -101,7 +109,8 @@ class NavButtonLayoutFactoryTest {
isKidsMode = false,
isInSetup = false,
isThreeButtonNav = false,
phoneMode = false
phoneMode = false,
surfaceRotation = surfaceRotation
)
}
@@ -114,7 +123,8 @@ class NavButtonLayoutFactoryTest {
isKidsMode = false,
isInSetup = false,
isThreeButtonNav = true,
phoneMode = true
phoneMode = true,
surfaceRotation = surfaceRotation
)
assert(layoutter is PhonePortraitNavLayoutter)
}
@@ -129,11 +139,28 @@ class NavButtonLayoutFactoryTest {
isKidsMode = false,
isInSetup = false,
isThreeButtonNav = true,
phoneMode = true
phoneMode = true,
surfaceRotation = surfaceRotation
)
assert(layoutter is PhoneLandscapeNavLayoutter)
}
@Test
fun getTaskbarSeascapeLayoutter() {
assumeTrue(TaskbarManager.FLAG_HIDE_NAVBAR_WINDOW)
mockDeviceProfile.isTaskbarPresent = false
setDeviceProfileLandscape()
val layoutter: NavButtonLayoutFactory.NavButtonLayoutter =
getLayoutter(
isKidsMode = false,
isInSetup = false,
isThreeButtonNav = true,
phoneMode = true,
surfaceRotation = ROTATION_270
)
assert(layoutter is PhoneSeascapeNavLayoutter)
}
@Test(expected = IllegalStateException::class)
fun noValidLayoutForPhoneGestureNav() {
assumeTrue(TaskbarManager.FLAG_HIDE_NAVBAR_WINDOW)
@@ -142,7 +169,8 @@ class NavButtonLayoutFactoryTest {
isKidsMode = false,
isInSetup = false,
isThreeButtonNav = false,
phoneMode = true
phoneMode = true,
surfaceRotation = surfaceRotation
)
}
@@ -157,7 +185,8 @@ class NavButtonLayoutFactoryTest {
isKidsMode: Boolean,
isInSetup: Boolean,
isThreeButtonNav: Boolean,
phoneMode: Boolean
phoneMode: Boolean,
@Rotation surfaceRotation: Int
): NavButtonLayoutFactory.NavButtonLayoutter {
return NavButtonLayoutFactory.getUiLayoutter(
deviceProfile = mockDeviceProfile,
@@ -166,7 +195,8 @@ class NavButtonLayoutFactoryTest {
isKidsMode = isKidsMode,
isInSetup = isInSetup,
isThreeButtonNav = isThreeButtonNav,
phoneMode = phoneMode
phoneMode = phoneMode,
surfaceRotation = surfaceRotation
)
}
}
@@ -16,11 +16,17 @@
package com.android.quickstep;
import static com.android.launcher3.ui.TaplTestsLauncher3.getAppPackageName;
import static org.junit.Assert.assertTrue;
import android.os.SystemProperties;
import androidx.test.uiautomator.By;
import androidx.test.uiautomator.Until;
import com.android.launcher3.Launcher;
import com.android.launcher3.tapl.LaunchedAppState;
import com.android.launcher3.tapl.LauncherInstrumentation;
import com.android.launcher3.tapl.LauncherInstrumentation.ContainerType;
import com.android.launcher3.ui.AbstractLauncherUiTest;
@@ -76,6 +82,21 @@ public abstract class AbstractQuickStepTest extends AbstractLauncherUiTest {
}
}
protected void assertTestActivityIsRunning(int activityNumber, String message) {
assertTrue(message, mDevice.wait(
Until.hasObject(By.pkg(getAppPackageName()).text("TestActivity" + activityNumber)),
DEFAULT_UI_TIMEOUT));
}
protected LaunchedAppState getAndAssertLaunchedApp() {
final LaunchedAppState launchedAppState = mLauncher.getLaunchedAppState();
executeOnLauncher(launcher -> assertTrue(
"Launcher activity is the top activity; expecting another activity to be the top "
+ "one",
isInLaunchedApp(launcher)));
return launchedAppState;
}
private boolean isInLiveTileMode(Launcher launcher,
LauncherInstrumentation.ContainerType expectedContainerType) {
if (expectedContainerType != LauncherInstrumentation.ContainerType.OVERVIEW) {
@@ -116,12 +116,13 @@ public class FallbackRecentsTest {
Utilities.enableRunningInTestHarnessForTests();
}
final ViewCaptureRule viewCaptureRule = new ViewCaptureRule();
final ViewCaptureRule viewCaptureRule = new ViewCaptureRule(
RecentsActivity.ACTIVITY_TRACKER::getCreatedActivity);
mOrderSensitiveRules = RuleChain
.outerRule(new SamplerRule())
.around(new NavigationModeSwitchRule(mLauncher))
.around(viewCaptureRule)
.around(new FailureWatcher(mDevice, mLauncher, viewCaptureRule.getViewCapture()));
.around(new FailureWatcher(mLauncher, viewCaptureRule::getViewCaptureData))
.around(viewCaptureRule);
mOtherLauncherActivity = context.getPackageManager().queryIntentActivities(
getHomeIntentInPackage(context),
@@ -15,6 +15,7 @@
*/
package com.android.quickstep
import android.content.Context
import android.graphics.Rect
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
@@ -29,7 +30,9 @@ import kotlin.math.roundToInt
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.mock
import org.mockito.Mockito.spy
/** Test for FullscreenDrawParams class. */
@SmallTest
@@ -186,4 +189,76 @@ class FullscreenDrawParamsTest : FakeInvariantDeviceProfileTest() {
val expectedRadius = QuickStepContract.getWindowCornerRadius(context)
assertThat(params.mCurrentDrawnCornerRadius).isEqualTo(expectedRadius)
}
@Test
fun setStartProgress_correctCornerRadiusForMultiDisplay() {
val display1Context = context
val display2Context = mock(Context::class.java)
val spyParams = spy(params)
val display1TaskRadius = TaskCornerRadius.get(display1Context)
val display1WindowRadius = QuickStepContract.getWindowCornerRadius(display1Context)
val display2TaskRadius = display1TaskRadius * 2 + 1 // Arbitrarily different.
val display2WindowRadius = display1WindowRadius * 2 + 1 // Arbitrarily different.
doReturn(display2TaskRadius).`when`(spyParams).computeTaskCornerRadius(display2Context)
doReturn(display2WindowRadius).`when`(spyParams).computeWindowCornerRadius(display2Context)
spyParams.updateCornerRadius(display1Context)
spyParams.setProgress(
/* fullscreenProgress= */ 0f,
/* parentScale= */ 1.0f,
/* taskViewScale= */ 1.0f,
/* unused previewWidth= */ -1,
/* unusedDp= */ null,
/* unused previewPositionHelper= */ null
)
assertThat(spyParams.mCurrentDrawnCornerRadius).isEqualTo(display1TaskRadius)
spyParams.updateCornerRadius(display2Context)
spyParams.setProgress(
/* fullscreenProgress= */ 0f,
/* parentScale= */ 1.0f,
/* taskViewScale= */ 1.0f,
/* unused previewWidth= */ -1,
/* unusedDp= */ null,
/* unused previewPositionHelper= */ null
)
assertThat(spyParams.mCurrentDrawnCornerRadius).isEqualTo(display2TaskRadius)
}
@Test
fun setFullProgress_correctCornerRadiusForMultiDisplay() {
val display1Context = context
val display2Context = mock(Context::class.java)
val spyParams = spy(params)
val display1TaskRadius = TaskCornerRadius.get(display1Context)
val display1WindowRadius = QuickStepContract.getWindowCornerRadius(display1Context)
val display2TaskRadius = display1TaskRadius * 2 + 1 // Arbitrarily different.
val display2WindowRadius = display1WindowRadius * 2 + 1 // Arbitrarily different.
doReturn(display2TaskRadius).`when`(spyParams).computeTaskCornerRadius(display2Context)
doReturn(display2WindowRadius).`when`(spyParams).computeWindowCornerRadius(display2Context)
spyParams.updateCornerRadius(display1Context)
spyParams.setProgress(
/* fullscreenProgress= */ 1.0f,
/* parentScale= */ 1.0f,
/* taskViewScale= */ 1.0f,
/* unused previewWidth= */ -1,
/* unusedDp= */ null,
/* unused previewPositionHelper= */ null
)
assertThat(spyParams.mCurrentDrawnCornerRadius).isEqualTo(display1WindowRadius)
spyParams.updateCornerRadius(display2Context)
spyParams.setProgress(
/* fullscreenProgress= */ 1.0f,
/* parentScale= */ 1.0f,
/* taskViewScale= */ 1.0f,
/* unused previewWidth= */ -1,
/* unusedDp= */ null,
/* unused previewPositionHelper= */ null
)
assertThat(spyParams.mCurrentDrawnCornerRadius).isEqualTo(display2WindowRadius)
}
}
@@ -52,6 +52,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import java.util.List;
@SmallTest
@RunWith(AndroidJUnit4.class)
public class OrientationTouchTransformerTest {
@@ -295,7 +297,7 @@ public class OrientationTouchTransformerTest {
WindowManagerProxy wmProxy = mock(WindowManagerProxy.class);
doReturn(cachedDisplayInfo).when(wmProxy).getDisplayInfo(any());
doReturn(windowBounds).when(wmProxy).getRealBounds(any(), any());
ArrayMap<CachedDisplayInfo, WindowBounds[]> internalDisplayBounds = new ArrayMap<>();
ArrayMap<CachedDisplayInfo, List<WindowBounds>> internalDisplayBounds = new ArrayMap<>();
doReturn(internalDisplayBounds).when(wmProxy).estimateInternalDisplayBounds(any());
return new DisplayController.Info(
getApplicationContext(), wmProxy, new ArrayMap<>());
@@ -16,15 +16,17 @@
package com.android.quickstep;
import static com.android.launcher3.util.rule.TestStabilityRule.LOCAL;
import static com.android.launcher3.util.rule.TestStabilityRule.PLATFORM_POSTSUBMIT;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import com.android.launcher3.ui.TaplTestsLauncher3;
import com.android.launcher3.util.RaceConditionReproducer;
import com.android.launcher3.util.rule.TestStabilityRule.Stability;
import com.android.quickstep.NavigationModeSwitchRule.NavigationModeSwitch;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -45,21 +47,9 @@ public class StartLauncherViaGestureTests extends AbstractQuickStepTest {
startTestActivity(2);
}
private void runTest(String... eventSequence) {
final RaceConditionReproducer eventProcessor = new RaceConditionReproducer(eventSequence);
// Destroy Launcher activity.
closeLauncherActivity();
// The test action.
eventProcessor.startIteration();
mLauncher.goHome();
eventProcessor.finishIteration();
}
@Ignore
@Test
@NavigationModeSwitch
@Stability(flavors = LOCAL | PLATFORM_POSTSUBMIT) // b/187761685
public void testStressPressHome() {
for (int i = 0; i < STRESS_REPEAT_COUNT; ++i) {
// Destroy Launcher activity.
@@ -70,9 +60,9 @@ public class StartLauncherViaGestureTests extends AbstractQuickStepTest {
}
}
@Ignore
@Test
@NavigationModeSwitch
@Stability(flavors = LOCAL | PLATFORM_POSTSUBMIT) // b/187761685
public void testStressSwipeToOverview() {
for (int i = 0; i < STRESS_REPEAT_COUNT; ++i) {
// Destroy Launcher activity.
@@ -16,7 +16,10 @@
package com.android.quickstep;
import static com.android.launcher3.testing.shared.TestProtocol.FLAKY_QUICK_SWITCH_TO_PREVIOUS_APP;
import static com.android.launcher3.ui.TaplTestsLauncher3.getAppPackageName;
import static com.android.launcher3.util.rule.TestStabilityRule.LOCAL;
import static com.android.launcher3.util.rule.TestStabilityRule.PLATFORM_POSTSUBMIT;
import static com.android.quickstep.TaskbarModeSwitchRule.Mode.PERSISTENT;
import static org.junit.Assert.assertEquals;
@@ -27,6 +30,7 @@ import static org.junit.Assume.assumeTrue;
import android.content.Intent;
import android.platform.test.annotations.PlatinumTest;
import android.util.Log;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
@@ -42,9 +46,13 @@ import com.android.launcher3.tapl.LauncherInstrumentation.NavigationModel;
import com.android.launcher3.tapl.Overview;
import com.android.launcher3.tapl.OverviewActions;
import com.android.launcher3.tapl.OverviewTask;
import com.android.launcher3.tapl.OverviewTaskMenu;
import com.android.launcher3.ui.PortraitLandscapeRunner.PortraitLandscape;
import com.android.launcher3.ui.TaplTestsLauncher3;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.Wait;
import com.android.launcher3.util.rule.ScreenRecordRule.ScreenRecord;
import com.android.launcher3.util.rule.TestStabilityRule;
import com.android.quickstep.NavigationModeSwitchRule.NavigationModeSwitch;
import com.android.quickstep.TaskbarModeSwitchRule.TaskbarModeSwitch;
import com.android.quickstep.views.RecentsView;
@@ -143,7 +151,7 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
assertNotNull("overview.getCurrentTask() returned null (1)", task);
assertNotNull("OverviewTask.open returned null", task.open());
assertTrue("Test activity didn't open from Overview", mDevice.wait(Until.hasObject(
By.pkg(getAppPackageName()).text("TestActivity2")),
By.pkg(getAppPackageName()).text("TestActivity2")),
DEFAULT_UI_TIMEOUT));
executeOnLauncher(launcher -> assertTrue(
"Launcher activity is the top activity; expecting another activity to be the top "
@@ -177,7 +185,6 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
@Test
@NavigationModeSwitch
@PortraitLandscape
@ScreenRecord // b/195673272
@PlatinumTest(focusArea = "launcher")
public void testOverviewActions() throws Exception {
// Experimenting for b/165029151:
@@ -192,6 +199,19 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
actionsView.clickAndDismissScreenshot();
}
@Test
public void testOverviewActionsMenu() throws Exception {
startTestAppsWithCheck();
OverviewTaskMenu menu = mLauncher.goHome().switchToOverview().getCurrentTask().tapMenu();
assertNotNull("Tapping App info menu item returned null", menu.tapAppInfoMenuItem());
executeOnLauncher(launcher -> assertTrue(
"Launcher activity is the top activity; expecting another activity to be the top",
isInLaunchedApp(launcher)));
}
private int getCurrentOverviewPage(Launcher launcher) {
return launcher.<RecentsView>getOverviewPanel().getCurrentPage();
}
@@ -237,16 +257,6 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
isInState(() -> LauncherState.OVERVIEW));
}
private LaunchedAppState getAndAssertLaunchedApp() {
final LaunchedAppState launchedAppState = mLauncher.getLaunchedAppState();
assertNotNull("Launcher.getLaunchedApp() returned null", launchedAppState);
executeOnLauncher(launcher -> assertTrue(
"Launcher activity is the top activity; expecting another activity to be the top "
+ "one",
isInLaunchedApp(launcher)));
return launchedAppState;
}
private void quickSwitchToPreviousAppAndAssert(boolean toRight) {
final LaunchedAppState launchedAppState = getAndAssertLaunchedApp();
if (toRight) {
@@ -288,22 +298,22 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
startTestActivity(4);
quickSwitchToPreviousAppAndAssert(true /* toRight */);
assertTrue("The first app we should have quick switched to is not running",
isTestActivityRunning(3));
assertTestActivityIsRunning(3,
"The first app we should have quick switched to is not running");
quickSwitchToPreviousAppAndAssert(true /* toRight */);
if (mLauncher.getNavigationModel() == NavigationModel.THREE_BUTTON) {
// 3-button mode toggles between 2 apps, rather than going back further.
assertTrue("Second quick switch should have returned to the first app.",
isTestActivityRunning(4));
assertTestActivityIsRunning(4,
"Second quick switch should have returned to the first app.");
} else {
assertTrue("The second app we should have quick switched to is not running",
isTestActivityRunning(2));
assertTestActivityIsRunning(2,
"The second app we should have quick switched to is not running");
}
quickSwitchToPreviousAppAndAssert(false /* toRight */);
assertTrue("The 2nd app we should have quick switched to is not running",
isTestActivityRunning(3));
assertTestActivityIsRunning(3,
"The 2nd app we should have quick switched to is not running");
final LaunchedAppState launchedAppState = getAndAssertLaunchedApp();
launchedAppState.switchToOverview();
@@ -312,7 +322,7 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
@Test
@ScreenRecord // b/242163205
@PlatinumTest(focusArea = "launcher")
@TaskbarModeSwitch(mode = PERSISTENT)
@TestStabilityRule.Stability(flavors = LOCAL | PLATFORM_POSTSUBMIT) // b/286084688
public void testQuickSwitchToPreviousAppForTablet() throws Exception {
assumeTrue(mLauncher.isTablet());
startTestActivity(2);
@@ -328,17 +338,20 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
// Quick-switch to the test app with swiping to right.
quickSwitchToPreviousAppAndAssert(true /* toRight */);
assertTrue("The first app we should have quick switched to is not running",
isTestActivityRunning(2));
assertTestActivityIsRunning(2,
"The first app we should have quick switched to is not running");
// Expect task bar visible when the launched app was the test activity.
launchedAppState = getAndAssertLaunchedApp();
launchedAppState.assertTaskbarVisible();
}
private boolean isTestActivityRunning(int activityNumber) {
return mDevice.wait(Until.hasObject(By.pkg(getAppPackageName())
.text("TestActivity" + activityNumber)),
DEFAULT_UI_TIMEOUT);
Log.e(FLAKY_QUICK_SWITCH_TO_PREVIOUS_APP,
"is Taskbar Transient : " + DisplayController.isTransientTaskbar(mTargetContext));
// TODO(b/286084688): Remove this branching check after test corruption is resolved.
// Branching this check because of test corruption.
if (DisplayController.isTransientTaskbar(mTargetContext)) {
launchedAppState.assertTaskbarHidden();
} else {
launchedAppState.assertTaskbarVisible();
}
}
@Test
@@ -348,8 +361,8 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
public void testQuickSwitchFromHome() throws Exception {
startTestActivity(2);
mLauncher.goHome().quickSwitchToPreviousApp();
assertTrue("The most recent task is not running after quick switching from home",
isTestActivityRunning(2));
assertTestActivityIsRunning(2,
"The most recent task is not running after quick switching from home");
getAndAssertLaunchedApp();
}
@@ -15,25 +15,41 @@
*/
package com.android.quickstep;
import static com.android.launcher3.util.rule.TestStabilityRule.LOCAL;
import static com.android.launcher3.util.rule.TestStabilityRule.PLATFORM_POSTSUBMIT;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import android.content.Intent;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.ui.PortraitLandscapeRunner.PortraitLandscape;
import com.android.launcher3.ui.TaplTestsLauncher3;
import com.android.launcher3.util.rule.TestStabilityRule;
import com.android.quickstep.TaskbarModeSwitchRule.TaskbarModeSwitch;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class TaplTestsSplitscreen extends AbstractQuickStepTest {
private static final String CALCULATOR_APP_NAME = "Calculator";
private static final String CALCULATOR_APP_PACKAGE =
resolveSystemApp(Intent.CATEGORY_APP_CALCULATOR);
private static final String READ_DEVICE_CONFIG_PERMISSION =
"android.permission.READ_DEVICE_CONFIG";
@Override
@Before
public void setUp() throws Exception {
@@ -44,6 +60,8 @@ public class TaplTestsSplitscreen extends AbstractQuickStepTest {
mLauncher.enableBlockTimeout(true);
mLauncher.showTaskbarIfHidden();
}
InstrumentationRegistry.getInstrumentation().getUiAutomation().adoptShellPermissionIdentity(
READ_DEVICE_CONFIG_PERMISSION);
}
@After
@@ -62,6 +80,7 @@ public class TaplTestsSplitscreen extends AbstractQuickStepTest {
@Test
@PortraitLandscape
@TaskbarModeSwitch
@TestStabilityRule.Stability(flavors = PLATFORM_POSTSUBMIT | LOCAL) // b/295225524
public void testSplitAppFromHomeWithItself() throws Exception {
// Currently only tablets have Taskbar in Overview, so test is only active on tablets
assumeTrue(mLauncher.isTablet());
@@ -20,6 +20,7 @@ import static com.android.quickstep.TaplTestsTaskbar.TaskbarMode.TRANSIENT;
import androidx.test.filters.LargeTest;
import com.android.launcher3.ui.PortraitLandscapeRunner.PortraitLandscape;
import com.android.launcher3.util.rule.ScreenRecordRule.ScreenRecord;
import org.junit.Test;
@@ -0,0 +1,132 @@
/*
* 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.quickstep;
import static com.android.quickstep.NavigationModeSwitchRule.Mode.ZERO_BUTTON;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
import android.app.Instrumentation;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.tapl.LauncherInstrumentation.TrackpadGestureType;
import com.android.launcher3.tapl.Workspace;
import com.android.launcher3.ui.PortraitLandscapeRunner.PortraitLandscape;
import com.android.launcher3.ui.TaplTestsLauncher3;
import com.android.quickstep.NavigationModeSwitchRule.NavigationModeSwitch;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class TaplTestsTrackpad extends AbstractQuickStepTest {
private static final String READ_DEVICE_CONFIG_PERMISSION =
"android.permission.READ_DEVICE_CONFIG";
@Before
public void setUp() throws Exception {
super.setUp();
TaplTestsLauncher3.initialize(this);
}
@After
public void tearDown() {
mLauncher.setTrackpadGestureType(TrackpadGestureType.NONE);
}
@Test
@PortraitLandscape
@NavigationModeSwitch
public void goHome() throws Exception {
assumeTrue(mLauncher.isTablet());
mLauncher.setTrackpadGestureType(TrackpadGestureType.THREE_FINGER);
startTestActivity(2);
mLauncher.goHome();
}
@Test
@PortraitLandscape
// TODO(b/291944684): Support back in 3-button mode. It requires triggering the logic to enable
// trackpad gesture back in SysUI. Normally it's triggered by the attachment of a trackpad. We
// need to figure out a way to emulate that in the test, or bypass the logic altogether.
@NavigationModeSwitch(mode = ZERO_BUTTON)
public void pressBack() throws Exception {
assumeTrue(mLauncher.isTablet());
assumeFalse(FeatureFlags.ENABLE_BACK_SWIPE_LAUNCHER_ANIMATION.get());
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
try {
instrumentation.getUiAutomation().adoptShellPermissionIdentity(
READ_DEVICE_CONFIG_PERMISSION);
mLauncher.setTrackpadGestureType(TrackpadGestureType.THREE_FINGER);
startTestActivity(2);
mLauncher.pressBack();
} finally {
instrumentation.getUiAutomation().dropShellPermissionIdentity();
}
}
@Test
@PortraitLandscape
@NavigationModeSwitch
public void switchToOverview() throws Exception {
assumeTrue(mLauncher.isTablet());
mLauncher.setTrackpadGestureType(TrackpadGestureType.THREE_FINGER);
startTestActivity(2);
mLauncher.goHome().switchToOverview();
}
@Test
@PortraitLandscape
@NavigationModeSwitch
public void testAllAppsFromHome() throws Exception {
assumeTrue(mLauncher.isTablet());
mLauncher.setTrackpadGestureType(TrackpadGestureType.TWO_FINGER);
assertNotNull("switchToAllApps() returned null",
mLauncher.getWorkspace().switchToAllApps());
}
@Test
@NavigationModeSwitch
@PortraitLandscape
public void testQuickSwitchFromHome() throws Exception {
assumeTrue(mLauncher.isTablet());
startTestActivity(2);
Workspace workspace = mLauncher.goHome();
mLauncher.setTrackpadGestureType(TrackpadGestureType.FOUR_FINGER);
workspace.quickSwitchToPreviousApp();
assertTestActivityIsRunning(2,
"The most recent task is not running after quick switching from home");
getAndAssertLaunchedApp();
}
}
@@ -18,7 +18,6 @@ package com.android.quickstep;
import static com.android.launcher3.config.FeatureFlags.ENABLE_CURSOR_HOVER_STATES;
import static com.android.quickstep.TaskbarModeSwitchRule.Mode.TRANSIENT;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
@@ -64,4 +63,15 @@ public class TaplTestsTransientTaskbar extends AbstractTaplTestsTaskbar {
throw new RuntimeException(e);
}
}
@Test
@TaskbarModeSwitch(mode = TRANSIENT)
public void testClickHoveredTaskbarToGoHome() {
try (AutoCloseable flag = TestUtil.overrideFlag(ENABLE_CURSOR_HOVER_STATES, true)) {
getTaskbar().getAppIcon(TEST_APP_NAME).launch(TEST_APP_PACKAGE);
mLauncher.getLaunchedAppState().clickStashedTaskbarToGoHome();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -17,8 +17,8 @@ package com.android.quickstep;
import static androidx.test.InstrumentationRegistry.getContext;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
import static androidx.test.InstrumentationRegistry.getTargetContext;
import static com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID;
import static com.android.launcher3.testcomponent.TestCommandReceiver.EXTRA_VALUE;
import static com.android.launcher3.testcomponent.TestCommandReceiver.SET_LIST_VIEW_SERVICE_BINDER;
import static com.android.launcher3.util.WidgetUtils.createWidgetInfo;
@@ -32,7 +32,6 @@ import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
@@ -42,14 +41,16 @@ import android.view.View;
import android.view.ViewConfiguration;
import android.widget.RemoteViews;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.filters.Suppress;
import androidx.test.runner.AndroidJUnit4;
import androidx.test.uiautomator.By;
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.Until;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.celllayout.FavoriteItemsTransaction;
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.tapl.LaunchedAppState;
import com.android.launcher3.testcomponent.ListViewService;
@@ -57,6 +58,7 @@ import com.android.launcher3.testcomponent.ListViewService.SimpleViewsFactory;
import com.android.launcher3.testcomponent.TestCommandReceiver;
import com.android.launcher3.ui.TaplTestsLauncher3;
import com.android.launcher3.ui.TestViewHelpers;
import com.android.launcher3.util.Executors;
import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
import com.android.quickstep.NavigationModeSwitchRule.NavigationModeSwitch;
@@ -67,6 +69,7 @@ import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntConsumer;
/**
@@ -84,9 +87,9 @@ import java.util.function.IntConsumer;
@RunWith(AndroidJUnit4.class)
public class ViewInflationDuringSwipeUp extends AbstractQuickStepTest {
private ContentResolver mResolver;
private SparseArray<ViewConfiguration> mConfigMap;
private InitTracker mInitTracker;
private LauncherModel mModel;
@Before
public void setUp() throws Exception {
@@ -101,8 +104,8 @@ public class ViewInflationDuringSwipeUp extends AbstractQuickStepTest {
TaplTestsLauncher3.initialize(this);
mResolver = mTargetContext.getContentResolver();
LauncherSettings.Settings.call(mResolver, LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
mModel = LauncherAppState.getInstance(mTargetContext).getModel();
Executors.MODEL_EXECUTOR.submit(mModel.getModelDbController()::createEmptyDB).get();
// Get static configuration map
Field field = ViewConfiguration.class.getDeclaredField("sConfigurations");
@@ -182,26 +185,30 @@ public class ViewInflationDuringSwipeUp extends AbstractQuickStepTest {
private void executeSwipeUpTestWithWidget(IntConsumer widgetIdCreationCallback,
IntConsumer updateBeforeSwipeUp, String finalWidgetText) {
try {
// Clear all existing data
LauncherSettings.Settings.call(mResolver,
LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
LauncherSettings.Settings.call(mResolver,
LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
LauncherAppWidgetProviderInfo info = TestViewHelpers.findWidgetProvider(this, false);
LauncherAppWidgetProviderInfo info = TestViewHelpers.findWidgetProvider(false);
// Make sure the widget is big enough to show a list of items
info.minSpanX = 2;
info.minSpanY = 2;
info.spanX = 2;
info.spanY = 2;
LauncherAppWidgetInfo item = createWidgetInfo(info, getTargetContext(), true);
AtomicInteger widgetId = new AtomicInteger();
new FavoriteItemsTransaction(mTargetContext)
.addItem(() -> {
LauncherAppWidgetInfo item = createWidgetInfo(info, mTargetContext, true);
item.screenId = FIRST_SCREEN_ID;
widgetId.set(item.appWidgetId);
return item;
})
.commitAndLoadHome(mLauncher);
addItemToScreen(item);
assertTrue("Widget is not present",
mLauncher.goHome().tryGetWidget(info.label, DEFAULT_UI_TIMEOUT) != null);
int widgetId = item.appWidgetId;
// Verify widget id
widgetIdCreationCallback.accept(widgetId);
widgetIdCreationCallback.accept(widgetId.get());
// Go to overview once so that all views are initialized and cached
startAppFast(resolveSystemApp(Intent.CATEGORY_APP_CALCULATOR));
@@ -214,7 +221,7 @@ public class ViewInflationDuringSwipeUp extends AbstractQuickStepTest {
LaunchedAppState launchedAppState = mLauncher.getLaunchedAppState();
// Update widget
updateBeforeSwipeUp.accept(widgetId);
updateBeforeSwipeUp.accept(widgetId.get());
launchedAppState.switchToOverview();
assertEquals("Views inflated during swipe up", 0, mInitTracker.viewInitCount);
@@ -0,0 +1,395 @@
/*
* 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.quickstep.util
import android.app.ActivityManager.RunningTaskInfo
import android.app.ActivityTaskManager.INVALID_TASK_ID
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.os.UserHandle
import androidx.test.platform.app.InstrumentationRegistry
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.shortcuts.ShortcutKey
import com.android.launcher3.ui.AbstractLauncherUiTest
import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_PENDINGINTENT_PENDINGINTENT
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_PENDINGINTENT_TASK
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_SHORTCUT_TASK
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_SINGLE_INTENT_FULLSCREEN
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_SINGLE_SHORTCUT_FULLSCREEN
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_SINGLE_TASK_FULLSCREEN
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_TASK_PENDINGINTENT
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_TASK_SHORTCUT
import com.android.quickstep.util.SplitSelectDataHolder.Companion.SPLIT_TASK_TASK
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class SplitSelectDataHolderTest {
private lateinit var splitSelectDataHolder: SplitSelectDataHolder
private val context: Context =
ContextWrapper(InstrumentationRegistry.getInstrumentation().targetContext)
private val sampleTaskInfo = RunningTaskInfo()
private val sampleTaskId = 10
private val sampleTaskId2 = 11
private val sampleUser = UserHandle(0)
private val sampleIntent = Intent()
private val sampleIntent2 = Intent()
private val sampleShortcut = Intent()
private val sampleShortcut2 = Intent()
private val sampleItemInfo = ItemInfo()
private val samplePackage =
AbstractLauncherUiTest.resolveSystemApp(Intent.CATEGORY_APP_CALCULATOR)
@Before
fun setup() {
splitSelectDataHolder = SplitSelectDataHolder(context)
sampleTaskInfo.taskId = sampleTaskId
sampleItemInfo.user = sampleUser
sampleIntent.setPackage(samplePackage)
sampleIntent2.setPackage(samplePackage)
sampleShortcut.setPackage(samplePackage)
sampleShortcut2.setPackage(samplePackage)
sampleShortcut.putExtra(ShortcutKey.EXTRA_SHORTCUT_ID, "sampleShortcut")
sampleShortcut2.putExtra(ShortcutKey.EXTRA_SHORTCUT_ID, "sampleShortcut2")
}
@Test
fun setInitialAsTask() {
splitSelectDataHolder.setInitialTaskSelect(
sampleTaskInfo,
STAGE_POSITION_TOP_OR_LEFT,
null,
null
)
assertTrue(splitSelectDataHolder.isSplitSelectActive())
}
@Test
fun setInitialAsIntent() {
splitSelectDataHolder.setInitialTaskSelect(
sampleIntent,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
assertTrue(splitSelectDataHolder.isSplitSelectActive())
}
@Test
fun setInitialAsIntentWithAlreadyRunningTask() {
splitSelectDataHolder.setInitialTaskSelect(
sampleIntent,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
sampleTaskId
)
assertTrue(splitSelectDataHolder.isSplitSelectActive())
}
@Test
fun setInitialAsShortcut() {
splitSelectDataHolder.setInitialTaskSelect(
sampleShortcut,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
assertTrue(splitSelectDataHolder.isSplitSelectActive())
}
@Test
fun setSecondAsTask() {
splitSelectDataHolder.setInitialTaskSelect(
sampleShortcut,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
splitSelectDataHolder.setSecondTask(sampleTaskId)
assertTrue(splitSelectDataHolder.isBothSplitAppsConfirmed())
}
@Test
fun setSecondAsIntent() {
splitSelectDataHolder.setInitialTaskSelect(
sampleTaskInfo,
STAGE_POSITION_TOP_OR_LEFT,
null,
null
)
splitSelectDataHolder.setSecondTask(sampleIntent, sampleUser)
assertTrue(splitSelectDataHolder.isBothSplitAppsConfirmed())
}
@Test
fun setSecondAsShortcut() {
splitSelectDataHolder.setInitialTaskSelect(
sampleIntent,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
splitSelectDataHolder.setSecondTask(sampleShortcut, sampleUser)
assertTrue(splitSelectDataHolder.isBothSplitAppsConfirmed())
}
@Test
fun generateLaunchData_Task_Task() {
splitSelectDataHolder.setInitialTaskSelect(
sampleTaskInfo,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null
)
splitSelectDataHolder.setSecondTask(sampleTaskId2)
val launchData = splitSelectDataHolder.getSplitLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_TASK_TASK)
// should contain a valid task ID for first app, and no intent or shortcut
assertNotEquals(launchData.initialTaskId, INVALID_TASK_ID)
assertNull(launchData.initialPendingIntent)
assertNull(launchData.initialShortcut)
// should contain a valid task ID for second app, and no intent or shortcut
assertNotEquals(launchData.secondTaskId, INVALID_TASK_ID)
assertNull(launchData.secondPendingIntent)
assertNull(launchData.secondShortcut)
}
@Test
fun generateLaunchData_Task_Intent() {
splitSelectDataHolder.setInitialTaskSelect(
sampleTaskInfo,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null
)
splitSelectDataHolder.setSecondTask(sampleIntent, sampleUser)
val launchData = splitSelectDataHolder.getSplitLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_TASK_PENDINGINTENT)
// should contain a valid task ID for first app, and no intent or shortcut
assertNotEquals(launchData.initialTaskId, INVALID_TASK_ID)
assertNull(launchData.initialPendingIntent)
assertNull(launchData.initialShortcut)
// should contain a valid intent for second app, and no task ID or shortcut
assertNotNull(launchData.secondPendingIntent)
assertEquals(launchData.secondTaskId, INVALID_TASK_ID)
assertNull(launchData.secondShortcut)
}
@Test
fun generateLaunchData_Task_Shortcut() {
splitSelectDataHolder.setInitialTaskSelect(
sampleTaskInfo,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null
)
splitSelectDataHolder.setSecondTask(sampleShortcut, sampleUser)
val launchData = splitSelectDataHolder.getSplitLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_TASK_SHORTCUT)
// should contain a valid task ID for first app, and no intent or shortcut
assertNotEquals(launchData.initialTaskId, INVALID_TASK_ID)
assertNull(launchData.initialPendingIntent)
assertNull(launchData.initialShortcut)
// should contain a valid shortcut and intent for second app, and no task ID
assertNotNull(launchData.secondShortcut)
assertNotNull(launchData.secondPendingIntent)
assertEquals(launchData.secondTaskId, INVALID_TASK_ID)
}
@Test
fun generateLaunchData_Intent_Task() {
splitSelectDataHolder.setInitialTaskSelect(
sampleIntent,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
splitSelectDataHolder.setSecondTask(sampleTaskId)
val launchData = splitSelectDataHolder.getSplitLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_PENDINGINTENT_TASK)
// should contain a valid intent for first app, and no task ID or shortcut
assertNotNull(launchData.initialPendingIntent)
assertEquals(launchData.initialTaskId, INVALID_TASK_ID)
assertNull(launchData.initialShortcut)
// should contain a valid task ID for second app, and no intent or shortcut
assertNotEquals(launchData.secondTaskId, INVALID_TASK_ID)
assertNull(launchData.secondPendingIntent)
assertNull(launchData.secondShortcut)
}
@Test
fun generateLaunchData_Shortcut_Task() {
splitSelectDataHolder.setInitialTaskSelect(
sampleShortcut,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
splitSelectDataHolder.setSecondTask(sampleTaskId)
val launchData = splitSelectDataHolder.getSplitLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_SHORTCUT_TASK)
// should contain a valid shortcut and intent for first app, and no task ID
assertNotNull(launchData.initialShortcut)
assertNotNull(launchData.initialPendingIntent)
assertEquals(launchData.initialTaskId, INVALID_TASK_ID)
// should contain a valid task ID for second app, and no intent or shortcut
assertNotEquals(launchData.secondTaskId, INVALID_TASK_ID)
assertNull(launchData.secondPendingIntent)
assertNull(launchData.secondShortcut)
}
@Test
fun generateLaunchData_Intent_Intent() {
splitSelectDataHolder.setInitialTaskSelect(
sampleIntent,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
splitSelectDataHolder.setSecondTask(sampleIntent2, sampleUser)
val launchData = splitSelectDataHolder.getSplitLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_PENDINGINTENT_PENDINGINTENT)
// should contain a valid intent for first app, and no task ID or shortcut
assertNotNull(launchData.initialPendingIntent)
assertEquals(launchData.initialTaskId, INVALID_TASK_ID)
assertNull(launchData.initialShortcut)
// should contain a valid intent for second app, and no task ID or shortcut
assertNotNull(launchData.secondPendingIntent)
assertEquals(launchData.secondTaskId, INVALID_TASK_ID)
assertNull(launchData.secondShortcut)
}
@Test
fun generateLaunchData_Single_Task() {
splitSelectDataHolder.setInitialTaskSelect(
sampleTaskInfo,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null
)
val launchData = splitSelectDataHolder.getFullscreenLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_SINGLE_TASK_FULLSCREEN)
// should contain a valid task ID for first app, and no intent or shortcut
assertNotEquals(launchData.initialTaskId, INVALID_TASK_ID)
assertNull(launchData.initialPendingIntent)
assertNull(launchData.initialShortcut)
// should contain no task ID, intent, or shortcut for second app
assertEquals(launchData.secondTaskId, INVALID_TASK_ID)
assertNull(launchData.secondPendingIntent)
assertNull(launchData.secondShortcut)
}
@Test
fun generateLaunchData_Single_Intent() {
splitSelectDataHolder.setInitialTaskSelect(
sampleIntent,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
val launchData = splitSelectDataHolder.getFullscreenLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_SINGLE_INTENT_FULLSCREEN)
// should contain a valid intent for first app, and no task ID or shortcut
assertNotNull(launchData.initialPendingIntent)
assertEquals(launchData.initialTaskId, INVALID_TASK_ID)
assertNull(launchData.initialShortcut)
// should contain no task ID, intent, or shortcut for second app
assertEquals(launchData.secondTaskId, INVALID_TASK_ID)
assertNull(launchData.secondPendingIntent)
assertNull(launchData.secondShortcut)
}
@Test
fun generateLaunchData_Single_Shortcut() {
splitSelectDataHolder.setInitialTaskSelect(
sampleShortcut,
STAGE_POSITION_TOP_OR_LEFT,
sampleItemInfo,
null,
INVALID_TASK_ID
)
val launchData = splitSelectDataHolder.getFullscreenLaunchData()
assertEquals(launchData.splitLaunchType, SPLIT_SINGLE_SHORTCUT_FULLSCREEN)
// should contain a valid shortcut and intent for first app, and no task ID
assertNotNull(launchData.initialShortcut)
assertNotNull(launchData.initialPendingIntent)
assertEquals(launchData.initialTaskId, INVALID_TASK_ID)
// should contain no task ID, intent, or shortcut for second app
assertEquals(launchData.secondTaskId, INVALID_TASK_ID)
assertNull(launchData.secondPendingIntent)
assertNull(launchData.secondShortcut)
}
@Test
fun clearState() {
splitSelectDataHolder.setInitialTaskSelect(
sampleTaskInfo,
STAGE_POSITION_TOP_OR_LEFT,
null,
null
)
splitSelectDataHolder.setSecondTask(sampleIntent, sampleUser)
splitSelectDataHolder.resetState()
assertFalse(splitSelectDataHolder.isSplitSelectActive())
}
}
@@ -37,6 +37,7 @@ import com.android.launcher3.util.withArgCaptor
import com.android.quickstep.RecentsModel
import com.android.quickstep.SystemUiProxy
import com.android.systemui.shared.recents.model.Task
import java.util.function.Consumer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
@@ -48,7 +49,6 @@ import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import java.util.function.Consumer
@RunWith(AndroidJUnit4::class)
class SplitSelectStateControllerTest {
@@ -67,6 +67,9 @@ class SplitSelectStateControllerTest {
private val primaryUserHandle = UserHandle(ActivityManager.RunningTaskInfo().userId)
private val nonPrimaryUserHandle = UserHandle(ActivityManager.RunningTaskInfo().userId + 10)
private var taskIdCounter = 0
private fun getUniqueId(): Int { return ++taskIdCounter }
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
@@ -100,15 +103,15 @@ class SplitSelectStateControllerTest {
tasks.add(groupTask2)
// Assertions happen in the callback we get from what we pass into
// #findLastActiveTaskAndRunCallback
// #findLastActiveTasksAndRunCallback
val taskConsumer =
Consumer<Task> { assertNull("No tasks should have matched", it /*task*/) }
Consumer<List<Task>> { assertNull("No tasks should have matched", it[0] /*task*/) }
// Capture callback from recentsModel#getTasks()
val consumer =
withArgCaptor<Consumer<ArrayList<GroupTask>>> {
splitSelectStateController.findLastActiveTaskAndRunCallback(
nonMatchingComponent,
splitSelectStateController.findLastActiveTasksAndRunCallback(
listOf(nonMatchingComponent),
taskConsumer
)
verify(recentsModel).getTasks(capture())
@@ -139,27 +142,27 @@ class SplitSelectStateControllerTest {
tasks.add(groupTask2)
// Assertions happen in the callback we get from what we pass into
// #findLastActiveTaskAndRunCallback
// #findLastActiveTasksAndRunCallback
val taskConsumer =
Consumer<Task> {
Consumer<List<Task>> {
assertEquals(
"ComponentName package mismatched",
it.key.baseIntent.component.packageName,
it[0].key.baseIntent.component?.packageName,
matchingPackage
)
assertEquals(
"ComponentName class mismatched",
it.key.baseIntent.component.className,
it[0].key.baseIntent.component?.className,
matchingClass
)
assertEquals(it, groupTask1.task1)
assertEquals(it[0], groupTask1.task1)
}
// Capture callback from recentsModel#getTasks()
val consumer =
withArgCaptor<Consumer<ArrayList<GroupTask>>> {
splitSelectStateController.findLastActiveTaskAndRunCallback(
matchingComponent,
splitSelectStateController.findLastActiveTasksAndRunCallback(
listOf(matchingComponent),
taskConsumer
)
verify(recentsModel).getTasks(capture())
@@ -190,15 +193,15 @@ class SplitSelectStateControllerTest {
tasks.add(groupTask2)
// Assertions happen in the callback we get from what we pass into
// #findLastActiveTaskAndRunCallback
// #findLastActiveTasksAndRunCallback
val taskConsumer =
Consumer<Task> { assertNull("No tasks should have matched", it /*task*/) }
Consumer<List<Task>> { assertNull("No tasks should have matched", it[0] /*task*/) }
// Capture callback from recentsModel#getTasks()
val consumer =
withArgCaptor<Consumer<ArrayList<GroupTask>>> {
splitSelectStateController.findLastActiveTaskAndRunCallback(
nonPrimaryUserComponent,
splitSelectStateController.findLastActiveTasksAndRunCallback(
listOf(nonPrimaryUserComponent),
taskConsumer
)
verify(recentsModel).getTasks(capture())
@@ -231,28 +234,28 @@ class SplitSelectStateControllerTest {
tasks.add(groupTask2)
// Assertions happen in the callback we get from what we pass into
// #findLastActiveTaskAndRunCallback
// #findLastActiveTasksAndRunCallback
val taskConsumer =
Consumer<Task> {
Consumer<List<Task>> {
assertEquals(
"ComponentName package mismatched",
it.key.baseIntent.component.packageName,
it[0].key.baseIntent.component?.packageName,
matchingPackage
)
assertEquals(
"ComponentName class mismatched",
it.key.baseIntent.component.className,
it[0].key.baseIntent.component?.className,
matchingClass
)
assertEquals("userId mismatched", it.key.userId, nonPrimaryUserHandle.identifier)
assertEquals(it, groupTask1.task1)
assertEquals("userId mismatched", it[0].key.userId, nonPrimaryUserHandle.identifier)
assertEquals(it[0], groupTask1.task1)
}
// Capture callback from recentsModel#getTasks()
val consumer =
withArgCaptor<Consumer<ArrayList<GroupTask>>> {
splitSelectStateController.findLastActiveTaskAndRunCallback(
nonPrimaryUserComponent,
splitSelectStateController.findLastActiveTasksAndRunCallback(
listOf(nonPrimaryUserComponent),
taskConsumer
)
verify(recentsModel).getTasks(capture())
@@ -283,27 +286,200 @@ class SplitSelectStateControllerTest {
tasks.add(groupTask1)
// Assertions happen in the callback we get from what we pass into
// #findLastActiveTaskAndRunCallback
// #findLastActiveTasksAndRunCallback
val taskConsumer =
Consumer<Task> {
Consumer<List<Task>> {
assertEquals(
"ComponentName package mismatched",
it.key.baseIntent.component.packageName,
it[0].key.baseIntent.component?.packageName,
matchingPackage
)
assertEquals(
"ComponentName class mismatched",
it.key.baseIntent.component.className,
it[0].key.baseIntent.component?.className,
matchingClass
)
assertEquals(it, groupTask2.task2)
assertEquals(it[0], groupTask1.task1)
}
// Capture callback from recentsModel#getTasks()
val consumer =
withArgCaptor<Consumer<ArrayList<GroupTask>>> {
splitSelectStateController.findLastActiveTaskAndRunCallback(
matchingComponent,
splitSelectStateController.findLastActiveTasksAndRunCallback(
listOf(matchingComponent),
taskConsumer
)
verify(recentsModel).getTasks(capture())
}
// Send our mocked tasks
consumer.accept(tasks)
}
@Test
fun activeTasks_multipleSearchShouldFindTask() {
val nonMatchingComponent = ComponentKey(ComponentName("no", "match"), primaryUserHandle)
val matchingPackage = "hotdog"
val matchingClass = "juice"
val matchingComponent =
ComponentKey(ComponentName(matchingPackage, matchingClass), primaryUserHandle)
val groupTask1 =
generateGroupTask(
ComponentName("hotdog", "pie"),
ComponentName("pumpkin", "pie")
)
val groupTask2 =
generateGroupTask(
ComponentName("pomegranate", "juice"),
ComponentName(matchingPackage, matchingClass)
)
val tasks: ArrayList<GroupTask> = ArrayList()
tasks.add(groupTask2)
tasks.add(groupTask1)
// Assertions happen in the callback we get from what we pass into
// #findLastActiveTasksAndRunCallback
val taskConsumer =
Consumer<List<Task>> {
assertEquals("Expected array length 2", 2, it.size)
assertNull("No tasks should have matched", it[0] /*task*/)
assertEquals(
"ComponentName package mismatched",
it[1].key.baseIntent.component?.packageName,
matchingPackage
)
assertEquals(
"ComponentName class mismatched",
it[1].key.baseIntent.component?.className,
matchingClass
)
assertEquals(it[1], groupTask2.task2)
}
// Capture callback from recentsModel#getTasks()
val consumer =
withArgCaptor<Consumer<ArrayList<GroupTask>>> {
splitSelectStateController.findLastActiveTasksAndRunCallback(
listOf(nonMatchingComponent, matchingComponent),
taskConsumer
)
verify(recentsModel).getTasks(capture())
}
// Send our mocked tasks
consumer.accept(tasks)
}
@Test
fun activeTasks_multipleSearchShouldNotFindSameTaskTwice() {
val matchingPackage = "hotdog"
val matchingClass = "juice"
val matchingComponent =
ComponentKey(ComponentName(matchingPackage, matchingClass), primaryUserHandle)
val groupTask1 =
generateGroupTask(
ComponentName("hotdog", "pie"),
ComponentName("pumpkin", "pie")
)
val groupTask2 =
generateGroupTask(
ComponentName("pomegranate", "juice"),
ComponentName(matchingPackage, matchingClass)
)
val tasks: ArrayList<GroupTask> = ArrayList()
tasks.add(groupTask2)
tasks.add(groupTask1)
// Assertions happen in the callback we get from what we pass into
// #findLastActiveTasksAndRunCallback
val taskConsumer =
Consumer<List<Task>> {
assertEquals("Expected array length 2", 2, it.size)
assertEquals(
"ComponentName package mismatched",
it[0].key.baseIntent.component?.packageName,
matchingPackage
)
assertEquals(
"ComponentName class mismatched",
it[0].key.baseIntent.component?.className,
matchingClass
)
assertEquals(it[0], groupTask2.task2)
assertNull("No tasks should have matched", it[1] /*task*/)
}
// Capture callback from recentsModel#getTasks()
val consumer =
withArgCaptor<Consumer<ArrayList<GroupTask>>> {
splitSelectStateController.findLastActiveTasksAndRunCallback(
listOf(matchingComponent, matchingComponent),
taskConsumer
)
verify(recentsModel).getTasks(capture())
}
// Send our mocked tasks
consumer.accept(tasks)
}
@Test
fun activeTasks_multipleSearchShouldFindDifferentInstancesOfSameTask() {
val matchingPackage = "hotdog"
val matchingClass = "juice"
val matchingComponent =
ComponentKey(ComponentName(matchingPackage, matchingClass), primaryUserHandle)
val groupTask1 =
generateGroupTask(
ComponentName(matchingPackage, matchingClass),
ComponentName("pumpkin", "pie")
)
val groupTask2 =
generateGroupTask(
ComponentName("pomegranate", "juice"),
ComponentName(matchingPackage, matchingClass)
)
val tasks: ArrayList<GroupTask> = ArrayList()
tasks.add(groupTask2)
tasks.add(groupTask1)
// Assertions happen in the callback we get from what we pass into
// #findLastActiveTasksAndRunCallback
val taskConsumer =
Consumer<List<Task>> {
assertEquals("Expected array length 2", 2, it.size)
assertEquals(
"ComponentName package mismatched",
it[0].key.baseIntent.component?.packageName,
matchingPackage
)
assertEquals(
"ComponentName class mismatched",
it[0].key.baseIntent.component?.className,
matchingClass
)
assertEquals(it[0], groupTask1.task1)
assertEquals(
"ComponentName package mismatched",
it[1].key.baseIntent.component?.packageName,
matchingPackage
)
assertEquals(
"ComponentName class mismatched",
it[1].key.baseIntent.component?.className,
matchingClass
)
assertEquals(it[1], groupTask2.task2)
}
// Capture callback from recentsModel#getTasks()
val consumer =
withArgCaptor<Consumer<ArrayList<GroupTask>>> {
splitSelectStateController.findLastActiveTasksAndRunCallback(
listOf(matchingComponent, matchingComponent),
taskConsumer
)
verify(recentsModel).getTasks(capture())
@@ -366,6 +542,7 @@ class SplitSelectStateControllerTest {
): GroupTask {
val task1 = Task()
var taskInfo = ActivityManager.RunningTaskInfo()
taskInfo.taskId = getUniqueId()
var intent = Intent()
intent.component = task1ComponentName
taskInfo.baseIntent = intent
@@ -373,6 +550,7 @@ class SplitSelectStateControllerTest {
val task2 = Task()
taskInfo = ActivityManager.RunningTaskInfo()
taskInfo.taskId = getUniqueId()
intent = Intent()
intent.component = task2ComponentName
taskInfo.baseIntent = intent
@@ -393,6 +571,7 @@ class SplitSelectStateControllerTest {
): GroupTask {
val task1 = Task()
var taskInfo = ActivityManager.RunningTaskInfo()
taskInfo.taskId = getUniqueId()
// Apply custom userHandle1
taskInfo.userId = userHandle1.identifier
var intent = Intent()
@@ -401,6 +580,7 @@ class SplitSelectStateControllerTest {
task1.key = Task.TaskKey(taskInfo)
val task2 = Task()
taskInfo = ActivityManager.RunningTaskInfo()
taskInfo.taskId = getUniqueId()
// Apply custom userHandle2
taskInfo.userId = userHandle2.identifier
intent = Intent()
@@ -50,6 +50,9 @@ import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.List;
@SmallTest
@RunWith(AndroidJUnit4.class)
public class TaskViewSimulatorTest {
@@ -150,7 +153,7 @@ public class TaskViewSimulatorTest {
WindowBounds wm = new WindowBounds(
new Rect(0, 0, mDisplaySize.x, mDisplaySize.y),
mDisplayInsets);
WindowBounds[] allBounds = new WindowBounds[4];
List<WindowBounds> allBounds = new ArrayList<>(4);
for (int i = 0; i < 4; i++) {
Rect boundsR = new Rect(wm.bounds);
Rect insetsR = new Rect(wm.insets);
@@ -158,7 +161,7 @@ public class TaskViewSimulatorTest {
RotationUtils.rotateRect(insetsR, RotationUtils.deltaRotation(rotation, i));
RotationUtils.rotateRect(boundsR, RotationUtils.deltaRotation(rotation, i));
boundsR.set(0, 0, Math.abs(boundsR.width()), Math.abs(boundsR.height()));
allBounds[i] = new WindowBounds(boundsR, insetsR);
allBounds.add(new WindowBounds(boundsR, insetsR));
}
WindowManagerProxy wmProxy = mock(WindowManagerProxy.class);
@@ -166,7 +169,7 @@ public class TaskViewSimulatorTest {
doReturn(wm).when(wmProxy).getRealBounds(any(), any());
doReturn(NavigationMode.NO_BUTTON).when(wmProxy).getNavigationMode(any());
ArrayMap<CachedDisplayInfo, WindowBounds[]> perDisplayBoundsCache =
ArrayMap<CachedDisplayInfo, List<WindowBounds>> perDisplayBoundsCache =
new ArrayMap<>();
perDisplayBoundsCache.put(cdi.normalize(), allBounds);