Merge "Fix regression where ShortcutRequest returns no results" into ub-launcher3-master
diff --git a/SharedLibWrapper/build.gradle b/SharedLibWrapper/build.gradle
new file mode 100644
index 0000000..674e38a
--- /dev/null
+++ b/SharedLibWrapper/build.gradle
@@ -0,0 +1,17 @@
+apply plugin: 'java'
+
+final String ANDROID_TOP = "${rootDir}/../../.."
+final String FRAMEWORK_PREBUILTS_DIR = "${ANDROID_TOP}/prebuilts/framework_intermediates/"
+
+sourceSets {
+ main {
+ java.srcDirs = ["${ANDROID_TOP}/frameworks/lib/systemui/SharedLibWrapper/src"]
+ }
+}
+
+sourceCompatibility = 1.8
+
+dependencies {
+ implementation fileTree(dir: "${FRAMEWORK_PREBUILTS_DIR}/quickstep/libs", include: 'sysui_shared.jar')
+ compileOnly fileTree(dir: "$ANDROID_TOP/prebuilts/fullsdk-${org.gradle.internal.os.OperatingSystem.current().isMacOsX() ? "darwin" : "linux"}/platforms/${COMPILE_SDK}", include: 'android.jar')
+}
diff --git a/build.gradle b/build.gradle
index e296455..534ca65 100644
--- a/build.gradle
+++ b/build.gradle
@@ -2,6 +2,7 @@
repositories {
mavenCentral()
google()
+ jcenter()
}
dependencies {
classpath GRADLE_CLASS_PATH
@@ -62,12 +63,6 @@
minSdkVersion 28
}
- withQuickstepIconRecents {
- dimension "recents"
-
- minSdkVersion 28
- }
-
withoutQuickstep {
dimension "recents"
}
@@ -78,11 +73,6 @@
if (variant.buildType.name.endsWith('release')) {
variant.setIgnore(true)
}
-
- // Icon recents is Go only
- if (name.contains("WithQuickstepIconRecents") && !name.contains("l3go")) {
- variant.setIgnore(true)
- }
}
sourceSets {
@@ -96,10 +86,6 @@
}
}
- debug {
- manifest.srcFile "AndroidManifest.xml"
- }
-
androidTest {
res.srcDirs = ['tests/res']
java.srcDirs = ['tests/src', 'tests/tapl']
@@ -112,15 +98,30 @@
aosp {
java.srcDirs = ['src_flags', 'src_shortcuts_overrides']
+ }
+
+ aospWithoutQuickstep {
manifest.srcFile "AndroidManifest.xml"
}
+ aospWithQuickstep {
+ manifest.srcFile "quickstep/AndroidManifest-launcher.xml"
+ }
+
l3go {
res.srcDirs = ['go/res']
java.srcDirs = ['go/src']
manifest.srcFile "go/AndroidManifest.xml"
}
+ l3goWithoutQuickstepDebug {
+ manifest.srcFile "AndroidManifest.xml"
+ }
+
+ l3goWithQuickstepDebug {
+ manifest.srcFile "quickstep/AndroidManifest-launcher.xml"
+ }
+
withoutQuickstep {
java.srcDirs = ['src_ui_overrides']
}
@@ -130,20 +131,17 @@
java.srcDirs = ['quickstep/src', 'quickstep/recents_ui_overrides/src']
manifest.srcFile "quickstep/AndroidManifest.xml"
}
-
- withQuickstepIconRecents {
- res.srcDirs = ['quickstep/res', 'go/quickstep/res']
- java.srcDirs = ['quickstep/src', 'go/quickstep/src']
- manifest.srcFile "quickstep/AndroidManifest.xml"
- }
}
}
-repositories {
- maven { url "../../../prebuilts/fullsdk-darwin/extras/android/m2repository" }
- maven { url "../../../prebuilts/fullsdk-linux/extras/android/m2repository" }
- mavenCentral()
- google()
+allprojects {
+ repositories {
+ maven { url "../../../prebuilts/sdk/current/androidx/m2repository" }
+ maven { url "../../../prebuilts/fullsdk-darwin/extras/android/m2repository" }
+ maven { url "../../../prebuilts/fullsdk-linux/extras/android/m2repository" }
+ mavenCentral()
+ google()
+ }
}
dependencies {
@@ -151,14 +149,12 @@
implementation "androidx.recyclerview:recyclerview:${ANDROID_X_VERSION}"
implementation "androidx.preference:preference:${ANDROID_X_VERSION}"
implementation project(':IconLoader')
+ withQuickstepImplementation project(':SharedLibWrapper')
implementation fileTree(dir: "${FRAMEWORK_PREBUILTS_DIR}/libs", include: 'launcher_protos.jar')
// Recents lib dependency
withQuickstepImplementation fileTree(dir: "${FRAMEWORK_PREBUILTS_DIR}/quickstep/libs", include: 'sysui_shared.jar')
- // Recents lib dependency for Go
- withQuickstepIconRecentsImplementation fileTree(dir: "${FRAMEWORK_PREBUILTS_DIR}/quickstep/libs", include: 'sysui_shared.jar')
-
// Required for AOSP to compile. This is already included in the sysui_shared.jar
withoutQuickstepImplementation fileTree(dir: "${FRAMEWORK_PREBUILTS_DIR}/libs", include: 'plugin_core.jar')
@@ -175,7 +171,7 @@
protobuf {
// Configure the protoc executable
protoc {
- artifact = 'com.google.protobuf:protoc:3.0.0-alpha-3'
+ artifact = 'com.google.protobuf:protoc:3.0.0'
generateProtoTasks {
all().each { task ->
diff --git a/gradle.properties b/gradle.properties
index a77f52a..7a51375 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -2,11 +2,11 @@
android.useAndroidX = true
android.enableJetifier = true
-ANDROID_X_VERSION=1.0.0-beta01
+ANDROID_X_VERSION=1+
-GRADLE_CLASS_PATH=com.android.tools.build:gradle:3.3.0
+GRADLE_CLASS_PATH=com.android.tools.build:gradle:3.5.1
-PROTOBUF_CLASS_PATH=com.google.protobuf:protobuf-gradle-plugin:0.8.6
+PROTOBUF_CLASS_PATH=com.google.protobuf:protobuf-gradle-plugin:0.8.8
PROTOBUF_DEPENDENCY=com.google.protobuf.nano:protobuf-javanano:3.0.0-alpha-7
BUILD_TOOLS_VERSION=28.0.3
diff --git a/iconloaderlib/build.gradle b/iconloaderlib/build.gradle
index 8a4d2b7..d7a62e1 100644
--- a/iconloaderlib/build.gradle
+++ b/iconloaderlib/build.gradle
@@ -3,7 +3,6 @@
android {
compileSdkVersion COMPILE_SDK
buildToolsVersion BUILD_TOOLS_VERSION
- publishNonDefault true
defaultConfig {
minSdkVersion 25
diff --git a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java
index 613386e..4e08df9 100644
--- a/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java
+++ b/quickstep/recents_ui_overrides/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java
@@ -98,6 +98,7 @@
private final float mYRange;
private final MotionPauseDetector mMotionPauseDetector;
private final float mMotionPauseMinDisplacement;
+ private final LauncherRecentsView mRecentsView;
private boolean mNoIntercept;
private LauncherState mStartState;
@@ -119,6 +120,7 @@
mMotionPauseDetector = new MotionPauseDetector(mLauncher);
mMotionPauseMinDisplacement = mLauncher.getResources().getDimension(
R.dimen.motion_pause_detector_min_displacement_from_app);
+ mRecentsView = mLauncher.getOverviewPanel();
}
@Override
@@ -208,6 +210,15 @@
updateNonOverviewAnim(QUICK_SWITCH, nonOverviewBuilder, ANIM_ALL);
mNonOverviewAnim.dispatchOnStart();
+ if (mRecentsView.getTaskViewCount() == 0) {
+ mRecentsView.setOnEmptyMessageUpdatedListener(isEmpty -> {
+ if (!isEmpty && mSwipeDetector.isDraggingState()) {
+ // We have loaded tasks, update the animators to start at the correct scale etc.
+ setupOverviewAnimators();
+ }
+ });
+ }
+
setupOverviewAnimators();
}
@@ -228,25 +239,25 @@
LauncherState.ScaleAndTranslation toScaleAndTranslation = toState
.getOverviewScaleAndTranslation(mLauncher);
// Update RecentView's translationX to have it start offscreen.
- LauncherRecentsView recentsView = mLauncher.getOverviewPanel();
float startScale = Utilities.mapRange(
SCALE_DOWN_INTERPOLATOR.getInterpolation(Y_ANIM_MIN_PROGRESS),
fromScaleAndTranslation.scale,
toScaleAndTranslation.scale);
- fromScaleAndTranslation.translationX = recentsView.getOffscreenTranslationX(startScale);
+ fromScaleAndTranslation.translationX = mRecentsView.getOffscreenTranslationX(startScale);
// Set RecentView's initial properties.
- recentsView.setScaleX(fromScaleAndTranslation.scale);
- recentsView.setScaleY(fromScaleAndTranslation.scale);
- recentsView.setTranslationX(fromScaleAndTranslation.translationX);
- recentsView.setTranslationY(fromScaleAndTranslation.translationY);
- recentsView.setContentAlpha(1);
+ mRecentsView.setScaleX(fromScaleAndTranslation.scale);
+ mRecentsView.setScaleY(fromScaleAndTranslation.scale);
+ mRecentsView.setTranslationX(fromScaleAndTranslation.translationX);
+ mRecentsView.setTranslationY(fromScaleAndTranslation.translationY);
+ mRecentsView.setContentAlpha(1);
+ mRecentsView.setFullscreenProgress(fromState.getOverviewFullscreenProgress());
// As we drag right, animate the following properties:
// - RecentsView translationX
// - OverviewScrim
AnimatorSet xOverviewAnim = new AnimatorSet();
- xOverviewAnim.play(ObjectAnimator.ofFloat(recentsView, View.TRANSLATION_X,
+ xOverviewAnim.play(ObjectAnimator.ofFloat(mRecentsView, View.TRANSLATION_X,
toScaleAndTranslation.translationX));
xOverviewAnim.play(ObjectAnimator.ofFloat(
mLauncher.getDragLayer().getOverviewScrim(), OverviewScrim.SCRIM_PROGRESS,
@@ -261,11 +272,11 @@
// - RecentsView scale
// - RecentsView fullscreenProgress
AnimatorSet yAnimation = new AnimatorSet();
- Animator translateYAnim = ObjectAnimator.ofFloat(recentsView, View.TRANSLATION_Y,
+ Animator translateYAnim = ObjectAnimator.ofFloat(mRecentsView, View.TRANSLATION_Y,
toScaleAndTranslation.translationY);
- Animator scaleAnim = ObjectAnimator.ofFloat(recentsView, SCALE_PROPERTY,
+ Animator scaleAnim = ObjectAnimator.ofFloat(mRecentsView, SCALE_PROPERTY,
toScaleAndTranslation.scale);
- Animator fullscreenProgressAnim = ObjectAnimator.ofFloat(recentsView, FULLSCREEN_PROGRESS,
+ Animator fullscreenProgressAnim = ObjectAnimator.ofFloat(mRecentsView, FULLSCREEN_PROGRESS,
fromState.getOverviewFullscreenProgress(), toState.getOverviewFullscreenProgress());
scaleAnim.setInterpolator(SCALE_DOWN_INTERPOLATOR);
fullscreenProgressAnim.setInterpolator(SCALE_DOWN_INTERPOLATOR);
@@ -466,5 +477,6 @@
mYOverviewAnim = null;
mIsHomeScreenVisible = true;
mSwipeDetector.finishedScrolling();
+ mRecentsView.setOnEmptyMessageUpdatedListener(null);
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/FallbackNavBarTouchController.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/FallbackNavBarTouchController.java
new file mode 100644
index 0000000..6f919c1
--- /dev/null
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/FallbackNavBarTouchController.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2019 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.fallback;
+
+import android.view.MotionEvent;
+
+import androidx.annotation.Nullable;
+
+import com.android.launcher3.Utilities;
+import com.android.launcher3.util.DefaultDisplay;
+import com.android.launcher3.util.TouchController;
+import com.android.quickstep.RecentsActivity;
+import com.android.quickstep.SysUINavigationMode;
+import com.android.quickstep.util.NavBarPosition;
+import com.android.quickstep.util.TriggerSwipeUpTouchTracker;
+
+/**
+ * In 0-button mode, intercepts swipe up from the nav bar on FallbackRecentsView to go home.
+ */
+public class FallbackNavBarTouchController implements TouchController {
+
+ private final RecentsActivity mActivity;
+ @Nullable
+ private final TriggerSwipeUpTouchTracker mTriggerSwipeUpTracker;
+
+ public FallbackNavBarTouchController(RecentsActivity activity) {
+ mActivity = activity;
+ SysUINavigationMode.Mode sysUINavigationMode = SysUINavigationMode.getMode(mActivity);
+ if (sysUINavigationMode == SysUINavigationMode.Mode.NO_BUTTON) {
+ NavBarPosition navBarPosition = new NavBarPosition(sysUINavigationMode,
+ DefaultDisplay.INSTANCE.get(mActivity).getInfo());
+ mTriggerSwipeUpTracker = new TriggerSwipeUpTouchTracker(mActivity,
+ true /* disableHorizontalSwipe */, navBarPosition,
+ null /* onInterceptTouch */, this::onSwipeUp);
+ } else {
+ mTriggerSwipeUpTracker = null;
+ }
+ }
+
+ @Override
+ public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
+ boolean cameFromNavBar = (ev.getEdgeFlags() & Utilities.EDGE_NAV_BAR) != 0;
+ if (cameFromNavBar && mTriggerSwipeUpTracker != null) {
+ if (ev.getAction() == MotionEvent.ACTION_DOWN) {
+ mTriggerSwipeUpTracker.init();
+ }
+ onControllerTouchEvent(ev);
+ return mTriggerSwipeUpTracker.interceptedTouch();
+ }
+ return false;
+ }
+
+ @Override
+ public boolean onControllerTouchEvent(MotionEvent ev) {
+ if (mTriggerSwipeUpTracker != null) {
+ mTriggerSwipeUpTracker.onMotionEvent(ev);
+ return true;
+ }
+ return false;
+ }
+
+ private void onSwipeUp(boolean wasFling) {
+ mActivity.<FallbackRecentsView>getOverviewPanel().startHome();
+ }
+}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsRootView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsRootView.java
index 1820729..de5fd7c 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsRootView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsRootView.java
@@ -48,7 +48,10 @@
}
public void setup() {
- mControllers = new TouchController[] { new RecentsTaskController(mActivity) };
+ mControllers = new TouchController[] {
+ new RecentsTaskController(mActivity),
+ new FallbackNavBarTouchController(mActivity),
+ };
}
@Override
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewWithoutFocusInputConsumer.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewWithoutFocusInputConsumer.java
index 875ec29..ca15ca1 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewWithoutFocusInputConsumer.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/inputconsumers/OverviewWithoutFocusInputConsumer.java
@@ -15,23 +15,12 @@
*/
package com.android.quickstep.inputconsumers;
-import static android.view.MotionEvent.ACTION_CANCEL;
-import static android.view.MotionEvent.ACTION_DOWN;
-import static android.view.MotionEvent.ACTION_MOVE;
-import static android.view.MotionEvent.ACTION_UP;
-
-import static com.android.launcher3.Utilities.squaredHypot;
-
import android.content.Context;
import android.content.Intent;
-import android.graphics.PointF;
import android.view.MotionEvent;
-import android.view.VelocityTracker;
-import android.view.ViewConfiguration;
import com.android.launcher3.BaseActivity;
import com.android.launcher3.BaseDraggingActivity;
-import com.android.launcher3.Utilities;
import com.android.launcher3.logging.StatsLogUtils;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Direction;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch;
@@ -39,31 +28,22 @@
import com.android.quickstep.InputConsumer;
import com.android.quickstep.RecentsAnimationDeviceState;
import com.android.quickstep.util.ActiveGestureLog;
+import com.android.quickstep.util.TriggerSwipeUpTouchTracker;
import com.android.systemui.shared.system.InputMonitorCompat;
public class OverviewWithoutFocusInputConsumer implements InputConsumer {
private final Context mContext;
- private final RecentsAnimationDeviceState mDeviceState;
- private final GestureState mGestureState;
private final InputMonitorCompat mInputMonitor;
- private final boolean mDisableHorizontalSwipe;
- private final PointF mDownPos = new PointF();
- private final float mSquaredTouchSlop;
-
- private boolean mInterceptedTouch;
- private VelocityTracker mVelocityTracker;
+ private final TriggerSwipeUpTouchTracker mTriggerSwipeUpTracker;
public OverviewWithoutFocusInputConsumer(Context context,
RecentsAnimationDeviceState deviceState, GestureState gestureState,
InputMonitorCompat inputMonitor, boolean disableHorizontalSwipe) {
mContext = context;
- mDeviceState = deviceState;
- mGestureState = gestureState;
mInputMonitor = inputMonitor;
- mDisableHorizontalSwipe = disableHorizontalSwipe;
- mSquaredTouchSlop = Utilities.squaredTouchSlop(context);
- mVelocityTracker = VelocityTracker.obtain();
+ mTriggerSwipeUpTracker = new TriggerSwipeUpTouchTracker(context, disableHorizontalSwipe,
+ deviceState.getNavBarPosition(), this::onInterceptTouch, this::onSwipeUp);
}
@Override
@@ -73,97 +53,31 @@
@Override
public boolean allowInterceptByParent() {
- return !mInterceptedTouch;
- }
-
- private void endTouchTracking() {
- if (mVelocityTracker != null) {
- mVelocityTracker.recycle();
- mVelocityTracker = null;
- }
+ return !mTriggerSwipeUpTracker.interceptedTouch();
}
@Override
public void onMotionEvent(MotionEvent ev) {
- if (mVelocityTracker == null) {
- return;
- }
+ mTriggerSwipeUpTracker.onMotionEvent(ev);
+ }
- mVelocityTracker.addMovement(ev);
- switch (ev.getActionMasked()) {
- case ACTION_DOWN: {
- mDownPos.set(ev.getX(), ev.getY());
- break;
- }
- case ACTION_MOVE: {
- if (!mInterceptedTouch) {
- float displacementX = ev.getX() - mDownPos.x;
- float displacementY = ev.getY() - mDownPos.y;
- if (squaredHypot(displacementX, displacementY) >= mSquaredTouchSlop) {
- if (mDisableHorizontalSwipe
- && Math.abs(displacementX) > Math.abs(displacementY)) {
- // Horizontal gesture is not allowed in this region
- endTouchTracking();
- break;
- }
-
- mInterceptedTouch = true;
-
- if (mInputMonitor != null) {
- mInputMonitor.pilferPointers();
- }
- }
- }
- break;
- }
-
- case ACTION_CANCEL:
- endTouchTracking();
- break;
-
- case ACTION_UP: {
- finishTouchTracking(ev);
- endTouchTracking();
- break;
- }
+ private void onInterceptTouch() {
+ if (mInputMonitor != null) {
+ mInputMonitor.pilferPointers();
}
}
- private void finishTouchTracking(MotionEvent ev) {
- mVelocityTracker.computeCurrentVelocity(100);
- float velocityX = mVelocityTracker.getXVelocity();
- float velocityY = mVelocityTracker.getYVelocity();
- float velocity = mDeviceState.getNavBarPosition().isRightEdge()
- ? -velocityX
- : mDeviceState.getNavBarPosition().isLeftEdge()
- ? velocityX
- : -velocityY;
-
- final boolean triggerQuickstep;
- int touch = Touch.FLING;
- if (Math.abs(velocity) >= ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) {
- triggerQuickstep = velocity > 0;
- } else {
- float displacementX = mDisableHorizontalSwipe ? 0 : (ev.getX() - mDownPos.x);
- float displacementY = ev.getY() - mDownPos.y;
- triggerQuickstep = squaredHypot(displacementX, displacementY) >= mSquaredTouchSlop;
- touch = Touch.SWIPE;
- }
-
- if (triggerQuickstep) {
- mContext.startActivity(new Intent(Intent.ACTION_MAIN)
- .addCategory(Intent.CATEGORY_HOME)
- .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
- ActiveGestureLog.INSTANCE.addLog("startQuickstep");
- BaseActivity activity = BaseDraggingActivity.fromContext(mContext);
- int pageIndex = -1; // This number doesn't reflect workspace page index.
- // It only indicates that launcher client screen was shown.
- int containerType = StatsLogUtils.getContainerTypeFromState(activity.getCurrentState());
- activity.getUserEventDispatcher().logActionOnContainer(
- touch, Direction.UP, containerType, pageIndex);
- activity.getUserEventDispatcher().setPreviousHomeGesture(true);
- } else {
- // ignore
- }
+ private void onSwipeUp(boolean wasFling) {
+ mContext.startActivity(new Intent(Intent.ACTION_MAIN)
+ .addCategory(Intent.CATEGORY_HOME)
+ .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+ ActiveGestureLog.INSTANCE.addLog("startQuickstep");
+ BaseActivity activity = BaseDraggingActivity.fromContext(mContext);
+ int pageIndex = -1; // This number doesn't reflect workspace page index.
+ // It only indicates that launcher client screen was shown.
+ int containerType = StatsLogUtils.getContainerTypeFromState(activity.getCurrentState());
+ activity.getUserEventDispatcher().logActionOnContainer(
+ wasFling ? Touch.FLING : Touch.SWIPE, Direction.UP, containerType, pageIndex);
+ activity.getUserEventDispatcher().setPreviousHomeGesture(true);
}
}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/util/TriggerSwipeUpTouchTracker.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/TriggerSwipeUpTouchTracker.java
new file mode 100644
index 0000000..c71258b
--- /dev/null
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/util/TriggerSwipeUpTouchTracker.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2019 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 static android.view.MotionEvent.ACTION_CANCEL;
+import static android.view.MotionEvent.ACTION_DOWN;
+import static android.view.MotionEvent.ACTION_MOVE;
+import static android.view.MotionEvent.ACTION_UP;
+
+import static com.android.launcher3.Utilities.squaredHypot;
+
+import android.content.Context;
+import android.graphics.PointF;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+import android.view.ViewConfiguration;
+
+import com.android.launcher3.Utilities;
+
+/**
+ * Tracks motion events to determine whether a gesture on the nav bar is a swipe up.
+ */
+public class TriggerSwipeUpTouchTracker {
+
+ private final PointF mDownPos = new PointF();
+ private final float mSquaredTouchSlop;
+ private final float mMinFlingVelocity;
+ private final boolean mDisableHorizontalSwipe;
+ private final NavBarPosition mNavBarPosition;
+ private final Runnable mOnInterceptTouch;
+ private final OnSwipeUpListener mOnSwipeUp;
+
+ private boolean mInterceptedTouch;
+ private VelocityTracker mVelocityTracker;
+
+ public TriggerSwipeUpTouchTracker(Context context, boolean disableHorizontalSwipe,
+ NavBarPosition navBarPosition, Runnable onInterceptTouch,
+ OnSwipeUpListener onSwipeUp) {
+ mSquaredTouchSlop = Utilities.squaredTouchSlop(context);
+ mMinFlingVelocity = ViewConfiguration.get(context).getScaledMinimumFlingVelocity();
+ mNavBarPosition = navBarPosition;
+ mDisableHorizontalSwipe = disableHorizontalSwipe;
+ mOnInterceptTouch = onInterceptTouch;
+ mOnSwipeUp = onSwipeUp;
+
+ init();
+ }
+
+ /**
+ * Reset some initial values to prepare for the next gesture.
+ */
+ public void init() {
+ mInterceptedTouch = false;
+ mVelocityTracker = VelocityTracker.obtain();
+ }
+
+ /**
+ * @return Whether we have passed the touch slop and are still tracking the gesture.
+ */
+ public boolean interceptedTouch() {
+ return mInterceptedTouch;
+ }
+
+ /**
+ * Track motion events to determine whether an atomic swipe up has occurred.
+ */
+ public void onMotionEvent(MotionEvent ev) {
+ if (mVelocityTracker == null) {
+ return;
+ }
+
+ mVelocityTracker.addMovement(ev);
+ switch (ev.getActionMasked()) {
+ case ACTION_DOWN: {
+ mDownPos.set(ev.getX(), ev.getY());
+ break;
+ }
+ case ACTION_MOVE: {
+ if (!mInterceptedTouch) {
+ float displacementX = ev.getX() - mDownPos.x;
+ float displacementY = ev.getY() - mDownPos.y;
+ if (squaredHypot(displacementX, displacementY) >= mSquaredTouchSlop) {
+ if (mDisableHorizontalSwipe
+ && Math.abs(displacementX) > Math.abs(displacementY)) {
+ // Horizontal gesture is not allowed in this region
+ endTouchTracking();
+ break;
+ }
+
+ mInterceptedTouch = true;
+
+ if (mOnInterceptTouch != null) {
+ mOnInterceptTouch.run();
+ }
+ }
+ }
+ break;
+ }
+
+ case ACTION_CANCEL:
+ endTouchTracking();
+ break;
+
+ case ACTION_UP: {
+ onGestureEnd(ev);
+ endTouchTracking();
+ break;
+ }
+ }
+ }
+
+ private void endTouchTracking() {
+ if (mVelocityTracker != null) {
+ mVelocityTracker.recycle();
+ mVelocityTracker = null;
+ }
+ }
+
+ private void onGestureEnd(MotionEvent ev) {
+ mVelocityTracker.computeCurrentVelocity(1000);
+ float velocityX = mVelocityTracker.getXVelocity();
+ float velocityY = mVelocityTracker.getYVelocity();
+ float velocity = mNavBarPosition.isRightEdge()
+ ? -velocityX
+ : mNavBarPosition.isLeftEdge()
+ ? velocityX
+ : -velocityY;
+
+ final boolean wasFling = Math.abs(velocity) >= mMinFlingVelocity;
+ final boolean isSwipeUp;
+ if (wasFling) {
+ isSwipeUp = velocity > 0;
+ } else {
+ float displacementX = mDisableHorizontalSwipe ? 0 : (ev.getX() - mDownPos.x);
+ float displacementY = ev.getY() - mDownPos.y;
+ isSwipeUp = squaredHypot(displacementX, displacementY) >= mSquaredTouchSlop;
+ }
+
+ if (isSwipeUp && mOnSwipeUp != null) {
+ mOnSwipeUp.onSwipeUp(wasFling);
+ }
+ }
+
+ /**
+ * Callback when the gesture ends and was determined to be a swipe from the nav bar.
+ */
+ public interface OnSwipeUpListener {
+ /**
+ * Called on touch up if a swipe up was detected.
+ * @param wasFling Whether the swipe was a fling, or just passed touch slop at low velocity.
+ */
+ void onSwipeUp(boolean wasFling);
+ }
+}
diff --git a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/RecentsView.java b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/RecentsView.java
index c836791..cb20ed0 100644
--- a/quickstep/recents_ui_overrides/src/com/android/quickstep/views/RecentsView.java
+++ b/quickstep/recents_ui_overrides/src/com/android/quickstep/views/RecentsView.java
@@ -309,6 +309,7 @@
private final Point mLastMeasureSize = new Point();
private final int mEmptyMessagePadding;
private boolean mShowEmptyMessage;
+ private OnEmptyMessageUpdatedListener mOnEmptyMessageUpdatedListener;
private Layout mEmptyTextLayout;
private boolean mLiveTileOverlayAttached;
@@ -1456,6 +1457,10 @@
return null;
}
+ public void setOnEmptyMessageUpdatedListener(OnEmptyMessageUpdatedListener listener) {
+ mOnEmptyMessageUpdatedListener = listener;
+ }
+
public void updateEmptyMessage() {
boolean isEmpty = getTaskViewCount() == 0;
boolean hasSizeChanged = mLastMeasureSize.x != getWidth()
@@ -1467,6 +1472,10 @@
mShowEmptyMessage = isEmpty;
updateEmptyStateUi(hasSizeChanged);
invalidate();
+
+ if (mOnEmptyMessageUpdatedListener != null) {
+ mOnEmptyMessageUpdatedListener.onEmptyMessageUpdated(mShowEmptyMessage);
+ }
}
@Override
@@ -1927,4 +1936,15 @@
return !(view instanceof TaskView) && !(view instanceof ClearAllButton)
&& index <= mTaskViewStartIndex;
}
+
+ /**
+ * Used to register callbacks for when our empty message state changes.
+ *
+ * @see #setOnEmptyMessageUpdatedListener(OnEmptyMessageUpdatedListener)
+ * @see #updateEmptyMessage()
+ */
+ public interface OnEmptyMessageUpdatedListener {
+ /** @param isEmpty Whether RecentsView is empty (i.e. has no children) */
+ void onEmptyMessageUpdated(boolean isEmpty);
+ }
}
diff --git a/quickstep/src/com/android/launcher3/QuickstepAppTransitionManagerImpl.java b/quickstep/src/com/android/launcher3/QuickstepAppTransitionManagerImpl.java
index d4db05a..1e01709 100644
--- a/quickstep/src/com/android/launcher3/QuickstepAppTransitionManagerImpl.java
+++ b/quickstep/src/com/android/launcher3/QuickstepAppTransitionManagerImpl.java
@@ -69,9 +69,9 @@
import com.android.launcher3.util.MultiValueAlpha;
import com.android.launcher3.util.MultiValueAlpha.AlphaProperty;
import com.android.launcher3.views.FloatingIconView;
+import com.android.quickstep.RemoteAnimationTargets;
import com.android.quickstep.util.MultiValueUpdateListener;
import com.android.quickstep.util.RemoteAnimationProvider;
-import com.android.quickstep.RemoteAnimationTargets;
import com.android.systemui.shared.system.ActivityCompat;
import com.android.systemui.shared.system.ActivityOptionsCompat;
import com.android.systemui.shared.system.QuickStepContract;
@@ -83,6 +83,8 @@
import com.android.systemui.shared.system.SyncRtSurfaceTransactionApplierCompat.SurfaceParams;
import com.android.systemui.shared.system.WindowManagerWrapper;
+import java.lang.ref.WeakReference;
+
/**
* {@link LauncherAppTransitionManager} with Quickstep-specific app transitions for launching from
* home and/or all-apps.
@@ -149,6 +151,7 @@
private DeviceProfile mDeviceProfile;
private RemoteAnimationProvider mRemoteAnimationProvider;
+ private WrappedAnimationRunnerImpl mWallpaperOpenRunner;
private final AnimatorListenerAdapter mForceInvisibleListener = new AnimatorListenerAdapter() {
@Override
@@ -176,7 +179,6 @@
mClosingWindowTransY = res.getDimensionPixelSize(R.dimen.closing_window_trans_y);
mLauncher.addOnDeviceProfileChangeListener(this);
- registerRemoteAnimations();
}
@Override
@@ -598,18 +600,36 @@
/**
* Registers remote animations used when closing apps to home screen.
*/
- private void registerRemoteAnimations() {
- // Unregister this
+ @Override
+ public void registerRemoteAnimations() {
if (hasControlRemoteAppTransitionPermission()) {
+ mWallpaperOpenRunner = createWallpaperOpenRunner(false /* fromUnlock */);
+
RemoteAnimationDefinitionCompat definition = new RemoteAnimationDefinitionCompat();
definition.addRemoteAnimation(WindowManagerWrapper.TRANSIT_WALLPAPER_OPEN,
WindowManagerWrapper.ACTIVITY_TYPE_STANDARD,
- new RemoteAnimationAdapterCompat(getWallpaperOpenRunner(false /* fromUnlock */),
+ new RemoteAnimationAdapterCompat(
+ new WrappedLauncherAnimationRunner<>(mWallpaperOpenRunner,
+ false /* startAtFrontOfQueue */),
CLOSING_TRANSITION_DURATION_MS, 0 /* statusBarTransitionDelay */));
new ActivityCompat(mLauncher).registerRemoteAnimations(definition);
}
}
+ /**
+ * Unregisters all remote animations.
+ */
+ @Override
+ public void unregisterRemoteAnimations() {
+ if (hasControlRemoteAppTransitionPermission()) {
+ new ActivityCompat(mLauncher).unregisterRemoteAnimations();
+
+ // Also clear strong references to the runners registered with the remote animation
+ // definition so we don't have to wait for the system gc
+ mWallpaperOpenRunner = null;
+ }
+ }
+
private boolean launcherIsATargetWithMode(RemoteAnimationTargetCompat[] targets, int mode) {
return taskIsATargetWithMode(targets, mLauncher.getTaskId(), mode);
}
@@ -618,9 +638,8 @@
* @return Runner that plays when user goes to Launcher
* ie. pressing home, swiping up from nav bar.
*/
- RemoteAnimationRunnerCompat getWallpaperOpenRunner(boolean fromUnlock) {
- return new WallpaperOpenLauncherAnimationRunner(mHandler, false /* startAtFrontOfQueue */,
- fromUnlock);
+ WrappedAnimationRunnerImpl createWallpaperOpenRunner(boolean fromUnlock) {
+ return new WallpaperOpenLauncherAnimationRunner(mHandler, fromUnlock);
}
/**
@@ -701,7 +720,8 @@
}
/**
- * Creates an animator that modifies Launcher as a result from {@link #getWallpaperOpenRunner}.
+ * Creates an animator that modifies Launcher as a result from
+ * {@link #createWallpaperOpenRunner}.
*/
private void createLauncherResumeAnimation(AnimatorSet anim) {
if (mLauncher.isInState(LauncherState.ALL_APPS)) {
@@ -761,18 +781,70 @@
}
/**
+ * Used with WrappedLauncherAnimationRunner as an interface for the runner to call back to the
+ * implementation.
+ */
+ protected interface WrappedAnimationRunnerImpl {
+ Handler getHandler();
+ void onCreateAnimation(RemoteAnimationTargetCompat[] appTargets,
+ RemoteAnimationTargetCompat[] wallpaperTargets,
+ LauncherAnimationRunner.AnimationResult result);
+ }
+
+ /**
+ * This class is needed to wrap any animation runner that is a part of the
+ * RemoteAnimationDefinition:
+ * - Launcher creates a new instance of the LauncherAppTransitionManagerImpl whenever it is
+ * created, which in turn registers a new definition
+ * - When the definition is registered, window manager retains a strong binder reference to the
+ * runner passed in
+ * - If the Launcher activity is recreated, the new definition registered will replace the old
+ * reference in the system's activity record, but until the system server is GC'd, the binder
+ * reference will still exist, which references the runner in the Launcher process, which
+ * references the (old) Launcher activity through this class
+ *
+ * Instead we make the runner provided to the definition static only holding a weak reference to
+ * the runner implementation. When this animation manager is destroyed, we remove the Launcher
+ * reference to the runner, leaving only the weak ref from the runner.
+ */
+ protected static class WrappedLauncherAnimationRunner<R extends WrappedAnimationRunnerImpl>
+ extends LauncherAnimationRunner {
+ private WeakReference<R> mImpl;
+
+ public WrappedLauncherAnimationRunner(R animationRunnerImpl, boolean startAtFrontOfQueue) {
+ super(animationRunnerImpl.getHandler(), startAtFrontOfQueue);
+ mImpl = new WeakReference<>(animationRunnerImpl);
+ }
+
+ @Override
+ public void onCreateAnimation(RemoteAnimationTargetCompat[] appTargets,
+ RemoteAnimationTargetCompat[] wallpaperTargets, AnimationResult result) {
+ R animationRunnerImpl = mImpl.get();
+ if (animationRunnerImpl != null) {
+ animationRunnerImpl.onCreateAnimation(appTargets, wallpaperTargets, result);
+ }
+ }
+ }
+
+ /**
* Remote animation runner for animation from the app to Launcher, including recents.
*/
- class WallpaperOpenLauncherAnimationRunner extends LauncherAnimationRunner {
+ protected class WallpaperOpenLauncherAnimationRunner implements WrappedAnimationRunnerImpl {
+
+ private final Handler mHandler;
private final boolean mFromUnlock;
- public WallpaperOpenLauncherAnimationRunner(Handler handler, boolean startAtFrontOfQueue,
- boolean fromUnlock) {
- super(handler, startAtFrontOfQueue);
+ public WallpaperOpenLauncherAnimationRunner(Handler handler, boolean fromUnlock) {
+ mHandler = handler;
mFromUnlock = fromUnlock;
}
@Override
+ public Handler getHandler() {
+ return mHandler;
+ }
+
+ @Override
public void onCreateAnimation(RemoteAnimationTargetCompat[] appTargets,
RemoteAnimationTargetCompat[] wallpaperTargets,
LauncherAnimationRunner.AnimationResult result) {
diff --git a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java
index 428e647..71d77fc 100644
--- a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java
+++ b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java
@@ -43,6 +43,7 @@
import com.android.quickstep.NavigationModeSwitchRule.NavigationModeSwitch;
import com.android.quickstep.views.RecentsView;
+import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -51,10 +52,18 @@
@LargeTest
@RunWith(AndroidJUnit4.class)
public class TaplTestsQuickstep extends AbstractQuickStepTest {
+ private int mLauncherPid;
+
@Before
public void setUp() throws Exception {
super.setUp();
TaplTestsLauncher3.initialize(this);
+ mLauncherPid = mLauncher.getPid();
+ }
+
+ @After
+ public void teardown() {
+ assertEquals("Launcher crashed, pid mismatch:", mLauncherPid, mLauncher.getPid());
}
private void startTestApps() throws Exception {
@@ -100,6 +109,7 @@
@PortraitLandscape
public void testOverview() throws Exception {
startTestApps();
+ // mLauncher.pressHome() also tests an important case of pressing home while in background.
Overview overview = mLauncher.pressHome().switchToOverview();
assertTrue("Launcher internal state didn't switch to Overview",
isInState(LauncherState.OVERVIEW));
diff --git a/robolectric_tests/src/com/android/launcher3/model/BackupRestoreTest.java b/robolectric_tests/src/com/android/launcher3/model/BackupRestoreTest.java
new file mode 100644
index 0000000..6223760
--- /dev/null
+++ b/robolectric_tests/src/com/android/launcher3/model/BackupRestoreTest.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.launcher3.model;
+
+import static com.android.launcher3.LauncherSettings.Favorites.BACKUP_TABLE_NAME;
+import static com.android.launcher3.provider.LauncherDbUtils.tableExists;
+
+import static org.junit.Assert.assertTrue;
+
+import android.database.sqlite.SQLiteDatabase;
+
+import com.android.launcher3.provider.RestoreDbTask;
+import com.android.launcher3.util.LauncherModelHelper;
+import com.android.launcher3.util.LauncherRoboTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.LooperMode;
+
+/**
+ * Tests to verify backup and restore flow.
+ */
+@RunWith(LauncherRoboTestRunner.class)
+@LooperMode(LooperMode.Mode.PAUSED)
+public class BackupRestoreTest {
+
+ private LauncherModelHelper mModelHelper;
+ private SQLiteDatabase mDb;
+
+ @Before
+ public void setUp() {
+ mModelHelper = new LauncherModelHelper();
+ RestoreDbTask.setPending(RuntimeEnvironment.application, true);
+ mDb = mModelHelper.provider.getDb();
+ }
+
+ @Test
+ public void testOnCreateDbIfNotExists_CreatesBackup() {
+ assertTrue(tableExists(mDb, BACKUP_TABLE_NAME));
+ }
+}
diff --git a/robolectric_tests/src/com/android/launcher3/util/LauncherModelHelper.java b/robolectric_tests/src/com/android/launcher3/util/LauncherModelHelper.java
index 655055c..e8b7157 100644
--- a/robolectric_tests/src/com/android/launcher3/util/LauncherModelHelper.java
+++ b/robolectric_tests/src/com/android/launcher3/util/LauncherModelHelper.java
@@ -28,6 +28,7 @@
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager.NameNotFoundException;
+import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.Settings;
@@ -276,6 +277,8 @@
Context context = RuntimeEnvironment.application;
LauncherSettings.Settings.call(context.getContentResolver(),
LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
+ LauncherSettings.Settings.call(context.getContentResolver(),
+ LauncherSettings.Settings.METHOD_CLEAR_EMPTY_DB_FLAG);
int[][][] ids = new int[typeArray.length][][];
for (int i = 0; i < typeArray.length; i++) {
@@ -312,7 +315,6 @@
idp.numRows = idp.numColumns = idp.numHotseatIcons = DEFAULT_GRID_SIZE;
idp.iconBitmapSize = DEFAULT_BITMAP_SIZE;
- provider.setAllowLoadDefaultFavorites(true);
Settings.Secure.putString(context.getContentResolver(),
"launcher3.layout.provider", TEST_PROVIDER_AUTHORITY);
@@ -340,4 +342,20 @@
filter.addCategory(Intent.CATEGORY_DEFAULT);
spm.addIntentFilterForActivity(cn, filter);
}
+
+ /**
+ * An extension of LauncherProvider backed up by in-memory database.
+ */
+ public static class TestLauncherProvider extends LauncherProvider {
+
+ @Override
+ public boolean onCreate() {
+ return true;
+ }
+
+ public SQLiteDatabase getDb() {
+ createDbIfNotExists();
+ return mOpenHelper.getWritableDatabase();
+ }
+ }
}
diff --git a/robolectric_tests/src/com/android/launcher3/util/TestLauncherProvider.java b/robolectric_tests/src/com/android/launcher3/util/TestLauncherProvider.java
deleted file mode 100644
index 7e873e8..0000000
--- a/robolectric_tests/src/com/android/launcher3/util/TestLauncherProvider.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package com.android.launcher3.util;
-
-import android.content.Context;
-import android.database.sqlite.SQLiteDatabase;
-
-import com.android.launcher3.LauncherProvider;
-
-/**
- * An extension of LauncherProvider backed up by in-memory database.
- */
-public class TestLauncherProvider extends LauncherProvider {
-
- private boolean mAllowLoadDefaultFavorites;
-
- @Override
- public boolean onCreate() {
- return true;
- }
-
- @Override
- protected synchronized void createDbIfNotExists() {
- if (mOpenHelper == null) {
- mOpenHelper = new MyDatabaseHelper(getContext(), mAllowLoadDefaultFavorites);
- }
- }
-
- public void setAllowLoadDefaultFavorites(boolean allowLoadDefaultFavorites) {
- mAllowLoadDefaultFavorites = allowLoadDefaultFavorites;
- }
-
- public SQLiteDatabase getDb() {
- createDbIfNotExists();
- return mOpenHelper.getWritableDatabase();
- }
-
- private static class MyDatabaseHelper extends DatabaseHelper {
-
- private final boolean mAllowLoadDefaultFavorites;
-
- MyDatabaseHelper(Context context, boolean allowLoadDefaultFavorites) {
- super(context, null);
- mAllowLoadDefaultFavorites = allowLoadDefaultFavorites;
- initIds();
- }
-
- @Override
- public long getDefaultUserSerial() {
- return 0;
- }
-
- @Override
- protected void onEmptyDbCreated() {
- if (mAllowLoadDefaultFavorites) {
- super.onEmptyDbCreated();
- }
- }
-
- @Override
- protected void handleOneTimeDataUpgrade(SQLiteDatabase db) { }
- }
-}
diff --git a/settings.gradle b/settings.gradle
index b52bd4f..ce13bfb 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -1,2 +1,5 @@
include ':IconLoader'
project(':IconLoader').projectDir = new File(rootDir, 'iconloaderlib')
+
+include ':SharedLibWrapper'
+project(':SharedLibWrapper').projectDir = new File(rootDir, 'SharedLibWrapper')
diff --git a/src/com/android/launcher3/BaseActivity.java b/src/com/android/launcher3/BaseActivity.java
index ea63fa7..3ca4f59 100644
--- a/src/com/android/launcher3/BaseActivity.java
+++ b/src/com/android/launcher3/BaseActivity.java
@@ -286,7 +286,7 @@
/**
* Used to set the override visibility state, used only to handle the transition home with the
* recents animation.
- * @see QuickstepAppTransitionManagerImpl#getWallpaperOpenRunner
+ * @see QuickstepAppTransitionManagerImpl#createWallpaperOpenRunner
*/
public void addForceInvisibleFlag(@InvisibilityFlags int flag) {
mForceInvisible |= flag;
diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java
index f5fafbf..8066d38 100644
--- a/src/com/android/launcher3/Launcher.java
+++ b/src/com/android/launcher3/Launcher.java
@@ -373,6 +373,7 @@
mPopupDataProvider = new PopupDataProvider(this);
mAppTransitionManager = LauncherAppTransitionManager.newInstance(this);
+ mAppTransitionManager.registerRemoteAnimations();
boolean internalStateHandled = ACTIVITY_TRACKER.handleCreate(this);
if (internalStateHandled) {
@@ -1545,6 +1546,7 @@
LauncherAppState.getIDP(this).removeOnChangeListener(this);
mOverlayManager.onActivityDestroyed(this);
+ mAppTransitionManager.unregisterRemoteAnimations();
}
public LauncherAccessibilityDelegate getAccessibilityDelegate() {
diff --git a/src/com/android/launcher3/LauncherAppTransitionManager.java b/src/com/android/launcher3/LauncherAppTransitionManager.java
index c55c120..9148c2f 100644
--- a/src/com/android/launcher3/LauncherAppTransitionManager.java
+++ b/src/com/android/launcher3/LauncherAppTransitionManager.java
@@ -67,4 +67,18 @@
public Animator createStateElementAnimation(int index, float... values) {
throw new RuntimeException("Unknown gesture animation " + index);
}
+
+ /**
+ * Registers remote animations for certain system transitions.
+ */
+ public void registerRemoteAnimations() {
+ // Do nothing
+ }
+
+ /**
+ * Unregisters all remote animations.
+ */
+ public void unregisterRemoteAnimations() {
+ // Do nothing
+ }
}
diff --git a/src/com/android/launcher3/LauncherProvider.java b/src/com/android/launcher3/LauncherProvider.java
index 900c966..b0ab35c 100644
--- a/src/com/android/launcher3/LauncherProvider.java
+++ b/src/com/android/launcher3/LauncherProvider.java
@@ -18,6 +18,7 @@
import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
import static com.android.launcher3.provider.LauncherDbUtils.tableExists;
+import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import android.annotation.TargetApi;
import android.app.backup.BackupManager;
@@ -45,6 +46,7 @@
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
+import android.os.Handler;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
@@ -87,6 +89,8 @@
private static final boolean LOGD = false;
private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
+ private static final String TOKEN_RESTORE_BACKUP_TABLE = "restore_backup_table";
+ private static final long RESTORE_BACKUP_TABLE_DELAY = 60000;
/**
* Represents the schema of the database. Changes in scheme need not be backwards compatible.
@@ -387,6 +391,14 @@
tableExists(mOpenHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
return null;
}
+ case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
+ final Handler handler = MODEL_EXECUTOR.getHandler();
+ handler.removeCallbacksAndMessages(TOKEN_RESTORE_BACKUP_TABLE);
+ handler.postDelayed(() -> RestoreDbTask.restoreIfPossible(
+ getContext(), mOpenHelper, new BackupManager(getContext())),
+ TOKEN_RESTORE_BACKUP_TABLE, RESTORE_BACKUP_TABLE_DELAY);
+ return null;
+ }
}
return null;
}
diff --git a/src/com/android/launcher3/LauncherSettings.java b/src/com/android/launcher3/LauncherSettings.java
index ec307db..4c5c61c 100644
--- a/src/com/android/launcher3/LauncherSettings.java
+++ b/src/com/android/launcher3/LauncherSettings.java
@@ -300,6 +300,8 @@
public static final String METHOD_REFRESH_BACKUP_TABLE = "refresh_backup_table";
+ public static final String METHOD_RESTORE_BACKUP_TABLE = "restore_backup_table";
+
public static final String EXTRA_VALUE = "value";
public static Bundle call(ContentResolver cr, String method) {
diff --git a/src/com/android/launcher3/SessionCommitReceiver.java b/src/com/android/launcher3/SessionCommitReceiver.java
index f0bae02..89f0a3d 100644
--- a/src/com/android/launcher3/SessionCommitReceiver.java
+++ b/src/com/android/launcher3/SessionCommitReceiver.java
@@ -78,6 +78,7 @@
}
InstallSessionHelper packageInstallerCompat = InstallSessionHelper.INSTANCE.get(context);
+ packageInstallerCompat.restoreDbIfApplicable(info);
if (TextUtils.isEmpty(info.getAppPackageName())
|| info.getInstallReason() != PackageManager.INSTALL_REASON_USER
|| packageInstallerCompat.promiseIconAddedForId(info.getSessionId())) {
diff --git a/src/com/android/launcher3/config/FeatureFlags.java b/src/com/android/launcher3/config/FeatureFlags.java
index 81dcba3..75609fe 100644
--- a/src/com/android/launcher3/config/FeatureFlags.java
+++ b/src/com/android/launcher3/config/FeatureFlags.java
@@ -136,6 +136,10 @@
public static final TogglableFlag ENABLE_OVERVIEW_ACTIONS = new TogglableFlag(
"ENABLE_OVERVIEW_ACTIONS", false, "Show app actions in Overview");
+ public static final TogglableFlag ENABLE_DATABASE_RESTORE = new TogglableFlag(
+ "ENABLE_DATABASE_RESTORE", true,
+ "Enable database restore when new restore session is created");
+
public static void initialize(Context context) {
// Avoid the disk read for user builds
if (Utilities.IS_DEBUG_DEVICE) {
diff --git a/src/com/android/launcher3/model/GridBackupTable.java b/src/com/android/launcher3/model/GridBackupTable.java
index 11d4edd..fc9948e 100644
--- a/src/com/android/launcher3/model/GridBackupTable.java
+++ b/src/com/android/launcher3/model/GridBackupTable.java
@@ -27,6 +27,8 @@
import android.os.Process;
import android.util.Log;
+import androidx.annotation.IntDef;
+
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.LauncherSettings.Settings;
import com.android.launcher3.pm.UserCache;
@@ -45,6 +47,19 @@
private static final String KEY_GRID_Y_SIZE = Favorites.SPANY;
private static final String KEY_DB_VERSION = Favorites.RANK;
+ public static final int OPTION_REQUIRES_SANITIZATION = 1;
+
+ /** STATE_NOT_FOUND indicates backup doesn't exist in the db. */
+ private static final int STATE_NOT_FOUND = 0;
+ /**
+ * STATE_RAW indicates the backup has not yet been sanitized. This implies it might still
+ * posses app info that doesn't exist in the workspace and needed to be sanitized before
+ * put into use.
+ */
+ private static final int STATE_RAW = 1;
+ /** STATE_SANITIZED indicates the backup has already been sanitized, thus can be used as-is. */
+ private static final int STATE_SANITIZED = 2;
+
private final Context mContext;
private final SQLiteDatabase mDb;
@@ -56,6 +71,9 @@
private int mRestoredGridX;
private int mRestoredGridY;
+ @IntDef({STATE_NOT_FOUND, STATE_RAW, STATE_SANITIZED})
+ private @interface BackupState { }
+
public GridBackupTable(Context context, SQLiteDatabase db,
int hotseatSize, int gridX, int gridY) {
mContext = context;
@@ -66,6 +84,10 @@
mOldGridY = gridY;
}
+ /**
+ * Create a backup from current workspace layout if one isn't created already (Note backup
+ * created this way is always sanitized). Otherwise restore from the backup instead.
+ */
public boolean backupOrRestoreAsNeeded() {
// Check if backup table exists
if (!tableExists(mDb, BACKUP_TABLE_NAME)) {
@@ -74,16 +96,16 @@
// No need to copy if empty DB was created.
return false;
}
-
- copyTable(Favorites.TABLE_NAME, BACKUP_TABLE_NAME);
- encodeDBProperties();
+ doBackup(UserCache.INSTANCE.get(mContext).getSerialNumberForUser(
+ Process.myUserHandle()), 0);
return false;
}
-
- if (!loadDbProperties()) {
+ if (loadDBProperties() != STATE_SANITIZED) {
return false;
}
- copyTable(BACKUP_TABLE_NAME, Favorites.TABLE_NAME);
+ long userSerial = UserCache.INSTANCE.get(mContext).getSerialNumberForUser(
+ Process.myUserHandle());
+ copyTable(BACKUP_TABLE_NAME, Favorites.TABLE_NAME, userSerial);
Log.d(TAG, "Backup table found");
return true;
}
@@ -93,43 +115,84 @@
return mRestoredHotseatSize;
}
- private void copyTable(String from, String to) {
- long userSerial = UserCache.INSTANCE.get(mContext).getSerialNumberForUser(
- Process.myUserHandle());
+ /**
+ * Copy valid grid entries from one table to another.
+ */
+ private void copyTable(String from, String to, long userSerial) {
dropTable(mDb, to);
Favorites.addTableToDb(mDb, userSerial, false, to);
mDb.execSQL("INSERT INTO " + to + " SELECT * FROM " + from + " where _id > " + ID_PROPERTY);
}
- private void encodeDBProperties() {
+ private void encodeDBProperties(int options) {
ContentValues values = new ContentValues();
values.put(Favorites._ID, ID_PROPERTY);
values.put(KEY_DB_VERSION, mDb.getVersion());
values.put(KEY_GRID_X_SIZE, mOldGridX);
values.put(KEY_GRID_Y_SIZE, mOldGridY);
values.put(KEY_HOTSEAT_SIZE, mOldHotseatSize);
+ values.put(Favorites.OPTIONS, options);
mDb.insert(BACKUP_TABLE_NAME, null, values);
}
- private boolean loadDbProperties() {
+ /**
+ * Load DB properties from grid backup table.
+ */
+ public @BackupState int loadDBProperties() {
try (Cursor c = mDb.query(BACKUP_TABLE_NAME, new String[] {
- KEY_DB_VERSION, // 0
- KEY_GRID_X_SIZE, // 1
- KEY_GRID_Y_SIZE, // 2
- KEY_HOTSEAT_SIZE}, // 3
+ KEY_DB_VERSION, // 0
+ KEY_GRID_X_SIZE, // 1
+ KEY_GRID_Y_SIZE, // 2
+ KEY_HOTSEAT_SIZE, // 3
+ Favorites.OPTIONS}, // 4
"_id=" + ID_PROPERTY, null, null, null, null)) {
if (!c.moveToNext()) {
Log.e(TAG, "Meta data not found in backup table");
- return false;
+ return STATE_NOT_FOUND;
}
- if (mDb.getVersion() != c.getInt(0)) {
- return false;
+ if (!validateDBVersion(mDb.getVersion(), c.getInt(0))) {
+ return STATE_NOT_FOUND;
}
mRestoredGridX = c.getInt(1);
mRestoredGridY = c.getInt(2);
mRestoredHotseatSize = c.getInt(3);
- return true;
+ boolean isSanitized = (c.getInt(4) & OPTION_REQUIRES_SANITIZATION) == 0;
+ return isSanitized ? STATE_SANITIZED : STATE_RAW;
}
}
+
+ /**
+ * Restore workspace from raw backup if available.
+ */
+ public boolean restoreFromRawBackupIfAvailable(long oldProfileId) {
+ if (!tableExists(mDb, Favorites.BACKUP_TABLE_NAME)
+ || loadDBProperties() != STATE_RAW
+ || mOldHotseatSize != mRestoredHotseatSize
+ || mOldGridX != mRestoredGridX
+ || mOldGridY != mRestoredGridY) {
+ // skip restore if dimensions in backup table differs from current setup.
+ return false;
+ }
+ copyTable(Favorites.BACKUP_TABLE_NAME, Favorites.TABLE_NAME, oldProfileId);
+ Log.d(TAG, "Backup restored");
+ return true;
+ }
+
+ /**
+ * Performs a backup on the workspace layout.
+ */
+ public void doBackup(long profileId, int options) {
+ copyTable(Favorites.TABLE_NAME, Favorites.BACKUP_TABLE_NAME, profileId);
+ encodeDBProperties(options);
+ }
+
+ private static boolean validateDBVersion(int expected, int actual) {
+ if (expected != actual) {
+ Log.e(TAG, String.format("Launcher.db version mismatch, expecting %d but %d was found",
+ expected, actual));
+ return false;
+ }
+ return true;
+ }
}
diff --git a/src/com/android/launcher3/pm/InstallSessionHelper.java b/src/com/android/launcher3/pm/InstallSessionHelper.java
index 186293f..976d7ba 100644
--- a/src/com/android/launcher3/pm/InstallSessionHelper.java
+++ b/src/com/android/launcher3/pm/InstallSessionHelper.java
@@ -29,6 +29,10 @@
import android.os.UserHandle;
import android.text.TextUtils;
+import androidx.annotation.NonNull;
+import androidx.annotation.RequiresApi;
+
+import com.android.launcher3.LauncherSettings;
import com.android.launcher3.SessionCommitReceiver;
import com.android.launcher3.Utilities;
import com.android.launcher3.config.FeatureFlags;
@@ -52,6 +56,8 @@
// Set<String> of session ids of promise icons that have been added to the home screen
// as FLAG_PROMISE_NEW_INSTALLS.
protected static final String PROMISE_ICON_IDS = "promise_icon_ids";
+ public static final String KEY_INSTALL_SESSION_CREATED_TIMESTAMP =
+ "key_install_session_created_timestamp";
private static final boolean DEBUG = false;
@@ -159,6 +165,34 @@
return list;
}
+ /**
+ * Attempt to restore workspace layout if the session is triggered due to device restore and it
+ * has a newer timestamp.
+ */
+ public boolean restoreDbIfApplicable(@NonNull final SessionInfo info) {
+ if (!Utilities.ATLEAST_OREO || !FeatureFlags.ENABLE_DATABASE_RESTORE.get()) {
+ return false;
+ }
+ if (isRestore(info) && hasNewerTimestamp(mAppContext, info)) {
+ LauncherSettings.Settings.call(mAppContext.getContentResolver(),
+ LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE);
+ return true;
+ }
+ return false;
+ }
+
+ @RequiresApi(26)
+ private static boolean isRestore(@NonNull final SessionInfo info) {
+ return info.getInstallReason() == PackageManager.INSTALL_REASON_DEVICE_RESTORE;
+ }
+
+ private static boolean hasNewerTimestamp(
+ @NonNull final Context context, @NonNull final SessionInfo info) {
+ return PackageManagerHelper.getSessionCreatedTimeInMillis(info)
+ > Utilities.getDevicePrefs(context).getLong(
+ KEY_INSTALL_SESSION_CREATED_TIMESTAMP, 0);
+ }
+
public boolean promiseIconAddedForId(int sessionId) {
return mPromiseIconIds.contains(sessionId);
}
diff --git a/src/com/android/launcher3/popup/PopupContainerWithArrow.java b/src/com/android/launcher3/popup/PopupContainerWithArrow.java
index 72c95c4..b764a07 100644
--- a/src/com/android/launcher3/popup/PopupContainerWithArrow.java
+++ b/src/com/android/launcher3/popup/PopupContainerWithArrow.java
@@ -351,7 +351,9 @@
}
public void applyNotificationInfos(List<NotificationInfo> notificationInfos) {
- mNotificationItemView.applyNotificationInfos(notificationInfos);
+ if (mNotificationItemView != null) {
+ mNotificationItemView.applyNotificationInfos(notificationInfos);
+ }
}
private void updateHiddenShortcuts() {
diff --git a/src/com/android/launcher3/provider/RestoreDbTask.java b/src/com/android/launcher3/provider/RestoreDbTask.java
index 9987994..407ff31 100644
--- a/src/com/android/launcher3/provider/RestoreDbTask.java
+++ b/src/com/android/launcher3/provider/RestoreDbTask.java
@@ -16,6 +16,7 @@
package com.android.launcher3.provider;
+import static com.android.launcher3.pm.InstallSessionHelper.KEY_INSTALL_SESSION_CREATED_TIMESTAMP;
import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
import android.app.backup.BackupManager;
@@ -25,23 +26,28 @@
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.UserHandle;
+import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseLongArray;
import androidx.annotation.NonNull;
import com.android.launcher3.AppWidgetsRestoredReceiver;
+import com.android.launcher3.InvariantDeviceProfile;
+import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherAppWidgetInfo;
import com.android.launcher3.LauncherProvider.DatabaseHelper;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.Utilities;
import com.android.launcher3.WorkspaceItemInfo;
import com.android.launcher3.logging.FileLog;
+import com.android.launcher3.model.GridBackupTable;
import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.LogConfig;
import java.io.InvalidObjectException;
+import java.util.Arrays;
/**
* Utility class to update DB schema after it has been restored.
@@ -65,6 +71,7 @@
SQLiteDatabase db = helper.getWritableDatabase();
try (SQLiteTransaction t = new SQLiteTransaction(db)) {
RestoreDbTask task = new RestoreDbTask();
+ task.backupWorkspace(context, db);
task.sanitizeDB(helper, db, backupManager);
task.restoreAppWidgetIdsIfExists(context);
t.commit();
@@ -76,6 +83,47 @@
}
/**
+ * Restore the workspace if backup is available.
+ */
+ public static boolean restoreIfPossible(@NonNull Context context,
+ @NonNull DatabaseHelper helper, @NonNull BackupManager backupManager) {
+ Utilities.getDevicePrefs(context).edit().putLong(
+ KEY_INSTALL_SESSION_CREATED_TIMESTAMP, System.currentTimeMillis()).apply();
+ final SQLiteDatabase db = helper.getWritableDatabase();
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
+ RestoreDbTask task = new RestoreDbTask();
+ task.restoreWorkspace(context, db, helper, backupManager);
+ task.restoreAppWidgetIdsIfExists(context);
+ t.commit();
+ return true;
+ } catch (Exception e) {
+ FileLog.e(TAG, "Failed to restore db", e);
+ return false;
+ }
+ }
+
+ /**
+ * Backup the workspace so that if things go south in restore, we can recover these entries.
+ */
+ private void backupWorkspace(Context context, SQLiteDatabase db) throws Exception {
+ InvariantDeviceProfile idp = LauncherAppState.getIDP(context);
+ new GridBackupTable(context, db, idp.numHotseatIcons, idp.numColumns, idp.numRows)
+ .doBackup(getDefaultProfileId(db), GridBackupTable.OPTION_REQUIRES_SANITIZATION);
+ }
+
+ private void restoreWorkspace(@NonNull Context context, @NonNull SQLiteDatabase db,
+ @NonNull DatabaseHelper helper, @NonNull BackupManager backupManager)
+ throws Exception {
+ final InvariantDeviceProfile idp = LauncherAppState.getIDP(context);
+ GridBackupTable backupTable = new GridBackupTable(context, db,
+ idp.numHotseatIcons, idp.numColumns, idp.numRows);
+ if (backupTable.restoreFromRawBackupIfAvailable(getDefaultProfileId(db))) {
+ sanitizeDB(helper, db, backupManager);
+ LauncherAppState.getInstance(context).getModel().forceReload();
+ }
+ }
+
+ /**
* Makes the following changes in the provider DB.
* 1. Removes all entries belonging to any profiles that were not restored.
* 2. Marks all entries as restored. The flags are updated during first load or as
@@ -107,22 +155,14 @@
int numProfiles = profileMapping.size();
String[] profileIds = new String[numProfiles];
profileIds[0] = Long.toString(oldProfileId);
- StringBuilder whereClause = new StringBuilder("profileId != ?");
- for (int i = profileMapping.size() - 1; i >= 1; --i) {
- whereClause.append(" AND profileId != ?");
+ for (int i = numProfiles - 1; i >= 1; --i) {
profileIds[i] = Long.toString(profileMapping.keyAt(i));
}
- try {
- int itemsDeleted = db.delete(Favorites.TABLE_NAME, whereClause.toString(), profileIds);
- FileLog.d(TAG, itemsDeleted + " items from unrestored user(s) were deleted");
- } catch (IllegalArgumentException exception) {
- // b/147114476
- FileLog.e(TAG, new StringBuilder("Failed to execute delete, where clause: '")
- .append(whereClause).append("', profile Id size:").append(profileIds.length)
- .append("profileIds: ").append(String.join(", ", profileIds)).toString()
- );
- throw exception;
- }
+ final String[] args = new String[profileIds.length];
+ Arrays.fill(args, "?");
+ final String where = "profileId NOT IN (" + TextUtils.join(", ", Arrays.asList(args)) + ")";
+ int itemsDeleted = db.delete(Favorites.TABLE_NAME, where, profileIds);
+ FileLog.d(TAG, itemsDeleted + " items from unrestored user(s) were deleted");
// Mark all items as restored.
boolean keepAllIcons = Utilities.isPropertyEnabled(LogConfig.KEEP_ALL_ICONS);
@@ -132,15 +172,16 @@
db.update(Favorites.TABLE_NAME, values, null, null);
// Mark widgets with appropriate restore flag.
- values.put(Favorites.RESTORED, LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
- LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
- LauncherAppWidgetInfo.FLAG_UI_NOT_READY |
- (keepAllIcons ? LauncherAppWidgetInfo.FLAG_RESTORE_STARTED : 0));
+ values.put(Favorites.RESTORED, LauncherAppWidgetInfo.FLAG_ID_NOT_VALID
+ | LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY
+ | LauncherAppWidgetInfo.FLAG_UI_NOT_READY
+ | (keepAllIcons ? LauncherAppWidgetInfo.FLAG_RESTORE_STARTED : 0));
db.update(Favorites.TABLE_NAME, values, "itemType = ?",
new String[]{Integer.toString(Favorites.ITEM_TYPE_APPWIDGET)});
- // Migrate ids. To avoid any overlap, we initially move conflicting ids to a temp location.
- // Using Long.MIN_VALUE since profile ids can not be negative, so there will be no overlap.
+ // Migrate ids. To avoid any overlap, we initially move conflicting ids to a temp
+ // location. Using Long.MIN_VALUE since profile ids can not be negative, so there will
+ // be no overlap.
final long tempLocationOffset = Long.MIN_VALUE;
SparseLongArray tempMigratedIds = new SparseLongArray(profileMapping.size());
int numTempMigrations = 0;
@@ -198,10 +239,10 @@
private LongSparseArray<Long> getManagedProfileIds(SQLiteDatabase db, long defaultProfileId) {
LongSparseArray<Long> ids = new LongSparseArray<>();
try (Cursor c = db.rawQuery("SELECT profileId from favorites WHERE profileId != ? "
- + "GROUP BY profileId", new String[] {Long.toString(defaultProfileId)})){
- while (c.moveToNext()) {
- ids.put(c.getLong(c.getColumnIndex(Favorites.PROFILE_ID)), null);
- }
+ + "GROUP BY profileId", new String[] {Long.toString(defaultProfileId)})) {
+ while (c.moveToNext()) {
+ ids.put(c.getLong(c.getColumnIndex(Favorites.PROFILE_ID)), null);
+ }
}
return ids;
}
@@ -222,7 +263,7 @@
* Returns the profile id used in the favorites table of the provided db.
*/
protected long getDefaultProfileId(SQLiteDatabase db) throws Exception {
- try (Cursor c = db.rawQuery("PRAGMA table_info (favorites)", null)){
+ try (Cursor c = db.rawQuery("PRAGMA table_info (favorites)", null)) {
int nameIndex = c.getColumnIndex(INFO_COLUMN_NAME);
while (c.moveToNext()) {
if (Favorites.PROFILE_ID.equals(c.getString(nameIndex))) {
diff --git a/src/com/android/launcher3/testing/TestInformationHandler.java b/src/com/android/launcher3/testing/TestInformationHandler.java
index ecfc77c..506830d 100644
--- a/src/com/android/launcher3/testing/TestInformationHandler.java
+++ b/src/com/android/launcher3/testing/TestInformationHandler.java
@@ -126,11 +126,11 @@
case TestProtocol.REQUEST_APPS_LIST_SCROLL_Y: {
try {
- final int deferUpdatesFlags = MAIN_EXECUTOR.submit(() ->
+ final int scroll = MAIN_EXECUTOR.submit(() ->
mLauncher.getAppsView().getActiveRecyclerView().getCurrentScrollY())
.get();
response.putInt(TestProtocol.TEST_INFO_RESPONSE_FIELD,
- deferUpdatesFlags);
+ scroll);
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
diff --git a/src/com/android/launcher3/testing/TestLogging.java b/src/com/android/launcher3/testing/TestLogging.java
new file mode 100644
index 0000000..fd066c1
--- /dev/null
+++ b/src/com/android/launcher3/testing/TestLogging.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.launcher3.testing;
+
+import android.util.Log;
+
+import com.android.launcher3.Utilities;
+
+public final class TestLogging {
+ public static void recordEvent(String event) {
+ if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
+ Log.d(TestProtocol.TAPL_EVENTS_TAG, event);
+ }
+ }
+}
diff --git a/src/com/android/launcher3/testing/TestProtocol.java b/src/com/android/launcher3/testing/TestProtocol.java
index 929315a..01c207f 100644
--- a/src/com/android/launcher3/testing/TestProtocol.java
+++ b/src/com/android/launcher3/testing/TestProtocol.java
@@ -31,6 +31,7 @@
public static final int QUICK_SWITCH_STATE_ORDINAL = 4;
public static final int ALL_APPS_STATE_ORDINAL = 5;
public static final int BACKGROUND_APP_STATE_ORDINAL = 6;
+ public static final String TAPL_EVENTS_TAG = "TaplEvents";
public static String stateOrdinalToString(int ordinal) {
switch (ordinal) {
diff --git a/src/com/android/launcher3/touch/AbstractStateChangeTouchController.java b/src/com/android/launcher3/touch/AbstractStateChangeTouchController.java
index f470edb..d193bef 100644
--- a/src/com/android/launcher3/touch/AbstractStateChangeTouchController.java
+++ b/src/com/android/launcher3/touch/AbstractStateChangeTouchController.java
@@ -508,7 +508,7 @@
mAtomicComponentsController.getAnimationPlayer().end();
mAtomicComponentsController = null;
}
- cancelAnimationControllers();
+ clearState();
boolean shouldGoToTargetState = true;
if (mPendingAnimation != null) {
boolean reachedTarget = mToState == targetState;
@@ -546,13 +546,13 @@
mAtomicAnim = null;
}
mScheduleResumeAtomicComponent = false;
+ mDetector.finishedScrolling();
+ mDetector.setDetectableScrollConditions(0, false);
}
private void cancelAnimationControllers() {
mCurrentAnimation = null;
cancelAtomicComponentsController();
- mDetector.finishedScrolling();
- mDetector.setDetectableScrollConditions(0, false);
}
private void cancelAtomicComponentsController() {
diff --git a/src/com/android/launcher3/touch/BaseSwipeDetector.java b/src/com/android/launcher3/touch/BaseSwipeDetector.java
index 12ca5ee..30283da 100644
--- a/src/com/android/launcher3/touch/BaseSwipeDetector.java
+++ b/src/com/android/launcher3/touch/BaseSwipeDetector.java
@@ -24,6 +24,10 @@
import android.view.ViewConfiguration;
import androidx.annotation.NonNull;
+import androidx.annotation.VisibleForTesting;
+
+import java.util.LinkedList;
+import java.util.Queue;
/**
* Scroll/drag/swipe gesture detector.
@@ -49,13 +53,15 @@
protected final boolean mIsRtl;
protected final float mTouchSlop;
protected final float mMaxVelocity;
+ private final Queue<Runnable> mSetStateQueue = new LinkedList<>();
private int mActivePointerId = INVALID_POINTER_ID;
private VelocityTracker mVelocityTracker;
private PointF mLastDisplacement = new PointF();
private PointF mDisplacement = new PointF();
protected PointF mSubtractDisplacement = new PointF();
- private ScrollState mState = ScrollState.IDLE;
+ @VisibleForTesting ScrollState mState = ScrollState.IDLE;
+ private boolean mIsSettingState;
protected boolean mIgnoreSlopWhenSettling;
@@ -195,6 +201,12 @@
// SETTLING -> (View settled) -> IDLE
private void setState(ScrollState newState) {
+ if (mIsSettingState) {
+ mSetStateQueue.add(() -> setState(newState));
+ return;
+ }
+ mIsSettingState = true;
+
if (DBG) {
Log.d(TAG, "setState:" + mState + "->" + newState);
}
@@ -212,6 +224,10 @@
}
mState = newState;
+ mIsSettingState = false;
+ if (!mSetStateQueue.isEmpty()) {
+ mSetStateQueue.remove().run();
+ }
}
private void initializeDragging() {
diff --git a/src/com/android/launcher3/touch/WorkspaceTouchListener.java b/src/com/android/launcher3/touch/WorkspaceTouchListener.java
index 66fdc94..310d598 100644
--- a/src/com/android/launcher3/touch/WorkspaceTouchListener.java
+++ b/src/com/android/launcher3/touch/WorkspaceTouchListener.java
@@ -25,7 +25,6 @@
import android.graphics.PointF;
import android.graphics.Rect;
-import android.util.Log;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
@@ -37,10 +36,8 @@
import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Launcher;
-import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.dragndrop.DragLayer;
-import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.views.OptionsPopupView;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
@@ -178,9 +175,6 @@
mLauncher.getUserEventDispatcher().logActionOnContainer(Action.Touch.LONGPRESS,
Action.Direction.NONE, ContainerType.WORKSPACE,
mWorkspace.getCurrentPage());
- if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
- Log.d(TestProtocol.PERMANENT_DIAG_TAG, "Opening options popup on long press");
- }
OptionsPopupView.showDefaultOptions(mLauncher, mTouchDownPoint.x, mTouchDownPoint.y);
} else {
cancelLongPress();
diff --git a/src/com/android/launcher3/util/PackageManagerHelper.java b/src/com/android/launcher3/util/PackageManagerHelper.java
index 8b2ee36..6c18747 100644
--- a/src/com/android/launcher3/util/PackageManagerHelper.java
+++ b/src/com/android/launcher3/util/PackageManagerHelper.java
@@ -16,6 +16,7 @@
package com.android.launcher3.util;
+import static android.content.pm.PackageInstaller.SessionInfo;
import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
import android.app.AppOpsManager;
@@ -44,6 +45,8 @@
import android.util.Pair;
import android.widget.Toast;
+import androidx.annotation.NonNull;
+
import com.android.launcher3.AppInfo;
import com.android.launcher3.ItemInfo;
import com.android.launcher3.LauncherAppWidgetInfo;
@@ -345,4 +348,15 @@
}
return false;
}
+
+ /**
+ * Returns the created time in millis of given session info. Returns 0 if not available.
+ */
+ public static long getSessionCreatedTimeInMillis(@NonNull final SessionInfo info) {
+ try {
+ return (long) SessionInfo.class.getDeclaredMethod("getCreatedMillis").invoke(info);
+ } catch (Exception e) {
+ return 0;
+ }
+ }
}
diff --git a/tests/src/com/android/launcher3/touch/SingleAxisSwipeDetectorTest.java b/tests/src/com/android/launcher3/touch/SingleAxisSwipeDetectorTest.java
index 5174e4d..6d463b5 100644
--- a/tests/src/com/android/launcher3/touch/SingleAxisSwipeDetectorTest.java
+++ b/tests/src/com/android/launcher3/touch/SingleAxisSwipeDetectorTest.java
@@ -21,9 +21,11 @@
import static com.android.launcher3.touch.SingleAxisSwipeDetector.HORIZONTAL;
import static com.android.launcher3.touch.SingleAxisSwipeDetector.VERTICAL;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyFloat;
import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -168,4 +170,21 @@
// TODO: actually calculate the following parameters and do exact value checks.
verify(mMockListener).onDragEnd(anyFloat());
}
+
+ @Test
+ public void testInterleavedSetState() {
+ doAnswer(invocationOnMock -> {
+ // Sets state to IDLE. (Normally onDragEnd() will have state SETTLING.)
+ mDetector.finishedScrolling();
+ return null;
+ }).when(mMockListener).onDragEnd(anyFloat());
+
+ mGenerator.put(0, 100, 100);
+ mGenerator.move(0, 100, 100 + mTouchSlop);
+ mGenerator.move(0, 100, 100 + mTouchSlop * 2);
+ mGenerator.lift(0);
+ verify(mMockListener).onDragEnd(anyFloat());
+ assertTrue("SwipeDetector should be IDLE but was " + mDetector.mState,
+ mDetector.isIdleState());
+ }
}
diff --git a/tests/tapl/com/android/launcher3/tapl/AddToHomeScreenPrompt.java b/tests/tapl/com/android/launcher3/tapl/AddToHomeScreenPrompt.java
index 03d1600..afb50e0 100644
--- a/tests/tapl/com/android/launcher3/tapl/AddToHomeScreenPrompt.java
+++ b/tests/tapl/com/android/launcher3/tapl/AddToHomeScreenPrompt.java
@@ -37,8 +37,10 @@
}
public void addAutomatically() {
- mLauncher.waitForObjectInContainer(
- mWidgetCell.getParent().getParent().getParent().getParent(),
- By.text(ADD_AUTOMATICALLY)).click();
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ mLauncher.waitForObjectInContainer(
+ mWidgetCell.getParent().getParent().getParent().getParent(),
+ By.text(ADD_AUTOMATICALLY)).click();
+ }
}
}
diff --git a/tests/tapl/com/android/launcher3/tapl/AllApps.java b/tests/tapl/com/android/launcher3/tapl/AllApps.java
index 3bdeb14..4a2d699 100644
--- a/tests/tapl/com/android/launcher3/tapl/AllApps.java
+++ b/tests/tapl/com/android/launcher3/tapl/AllApps.java
@@ -99,8 +99,9 @@
*/
@NonNull
public AppIcon getAppIcon(String appName) {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "getting app icon " + appName + " on all apps")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "getting app icon " + appName + " on all apps")) {
final UiObject2 allAppsContainer = verifyActiveContainer();
final UiObject2 appListRecycler = mLauncher.waitForObjectInContainer(allAppsContainer,
"apps_list_view");
@@ -130,6 +131,9 @@
searchBox.getVisibleBounds().bottom
- allAppsContainer.getVisibleBounds().top);
final int newScroll = getAllAppsScroll();
+ mLauncher.assertTrue(
+ "Scrolled in a wrong direction in AllApps: from " + scroll + " to "
+ + newScroll, newScroll >= scroll);
if (newScroll == scroll) break;
mLauncher.assertTrue(
@@ -197,7 +201,8 @@
* Flings forward (down) and waits the fling's end.
*/
public void flingForward() {
- try (LauncherInstrumentation.Closable c =
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c =
mLauncher.addContextLayer("want to fling forward in all apps")) {
final UiObject2 allAppsContainer = verifyActiveContainer();
// Start the gesture in the center to avoid starting at elements near the top.
@@ -211,7 +216,8 @@
* Flings backward (up) and waits the fling's end.
*/
public void flingBackward() {
- try (LauncherInstrumentation.Closable c =
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c =
mLauncher.addContextLayer("want to fling backward in all apps")) {
final UiObject2 allAppsContainer = verifyActiveContainer();
// Start the gesture in the center, for symmetry with forward.
diff --git a/tests/tapl/com/android/launcher3/tapl/AllAppsFromOverview.java b/tests/tapl/com/android/launcher3/tapl/AllAppsFromOverview.java
index f48d4dd..8f9fec9 100644
--- a/tests/tapl/com/android/launcher3/tapl/AllAppsFromOverview.java
+++ b/tests/tapl/com/android/launcher3/tapl/AllAppsFromOverview.java
@@ -42,8 +42,9 @@
*/
@NonNull
public Overview switchBackToOverview() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "want to switch back from all apps to overview")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "want to switch back from all apps to overview")) {
final UiObject2 allAppsContainer = verifyActiveContainer();
// Swipe from the search box to the bottom.
final UiObject2 qsb = mLauncher.waitForObjectInContainer(
diff --git a/tests/tapl/com/android/launcher3/tapl/AppIcon.java b/tests/tapl/com/android/launcher3/tapl/AppIcon.java
index 2da6344..0a6ed7f 100644
--- a/tests/tapl/com/android/launcher3/tapl/AppIcon.java
+++ b/tests/tapl/com/android/launcher3/tapl/AppIcon.java
@@ -26,6 +26,7 @@
* App icon, whether in all apps or in workspace/
*/
public final class AppIcon extends Launchable {
+
AppIcon(LauncherInstrumentation launcher, UiObject2 icon) {
super(launcher, icon);
}
@@ -38,8 +39,10 @@
* Long-clicks the icon to open its menu.
*/
public AppIconMenu openMenu() {
- return new AppIconMenu(mLauncher, mLauncher.clickAndGet(
- mObject, "deep_shortcuts_container"));
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ return new AppIconMenu(mLauncher, mLauncher.clickAndGet(
+ mObject, "deep_shortcuts_container"));
+ }
}
@Override
diff --git a/tests/tapl/com/android/launcher3/tapl/Background.java b/tests/tapl/com/android/launcher3/tapl/Background.java
index d9ae778..50bdf5c 100644
--- a/tests/tapl/com/android/launcher3/tapl/Background.java
+++ b/tests/tapl/com/android/launcher3/tapl/Background.java
@@ -52,8 +52,9 @@
*/
@NonNull
public BaseOverview switchToOverview() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "want to switch from background to overview")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "want to switch from background to overview")) {
verifyActiveContainer();
goToOverviewUnchecked();
return mLauncher.isFallbackOverview() ?
@@ -124,8 +125,9 @@
* Swipes right or double presses the square button to switch to the previous app.
*/
public Background quickSwitchToPreviousApp() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "want to quick switch to the previous app")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "want to quick switch to the previous app")) {
verifyActiveContainer();
quickSwitchToPreviousApp(getExpectedStateForQuickSwitch());
return new Background(mLauncher);
diff --git a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
index 339e14f..e13ea52 100644
--- a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
+++ b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
@@ -48,6 +48,12 @@
* Flings forward (left) and waits the fling's end.
*/
public void flingForward() {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ flingForwardImpl();
+ }
+ }
+
+ private void flingForwardImpl() {
try (LauncherInstrumentation.Closable c =
mLauncher.addContextLayer("want to fling forward in overview")) {
LauncherInstrumentation.log("Overview.flingForward before fling");
@@ -65,14 +71,15 @@
* Dismissed all tasks by scrolling to Clear-all button and pressing it.
*/
public void dismissAllTasks() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "dismissing all tasks")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "dismissing all tasks")) {
final BySelector clearAllSelector = mLauncher.getOverviewObjectSelector("clear_all");
for (int i = 0;
i < FLINGS_FOR_DISMISS_LIMIT
&& !verifyActiveContainer().hasObject(clearAllSelector);
++i) {
- flingForward();
+ flingForwardImpl();
}
mLauncher.waitForObjectInContainer(verifyActiveContainer(), clearAllSelector).click();
@@ -83,7 +90,8 @@
* Flings backward (right) and waits the fling's end.
*/
public void flingBackward() {
- try (LauncherInstrumentation.Closable c =
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c =
mLauncher.addContextLayer("want to fling backward in overview")) {
LauncherInstrumentation.log("Overview.flingBackward before fling");
final UiObject2 overview = verifyActiveContainer();
diff --git a/tests/tapl/com/android/launcher3/tapl/Home.java b/tests/tapl/com/android/launcher3/tapl/Home.java
index 1e4d937..1a0fe3d 100644
--- a/tests/tapl/com/android/launcher3/tapl/Home.java
+++ b/tests/tapl/com/android/launcher3/tapl/Home.java
@@ -48,8 +48,9 @@
@NonNull
@Override
public Overview switchToOverview() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "want to switch from home to overview")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "want to switch from home to overview")) {
verifyActiveContainer();
goToOverviewUnchecked();
try (LauncherInstrumentation.Closable c1 = mLauncher.addContextLayer(
diff --git a/tests/tapl/com/android/launcher3/tapl/Launchable.java b/tests/tapl/com/android/launcher3/tapl/Launchable.java
index 6881197..f88a616 100644
--- a/tests/tapl/com/android/launcher3/tapl/Launchable.java
+++ b/tests/tapl/com/android/launcher3/tapl/Launchable.java
@@ -46,7 +46,9 @@
* Clicks the object to launch its app.
*/
public Background launch(String expectedPackageName) {
- return launch(By.pkg(expectedPackageName));
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ return launch(By.pkg(expectedPackageName));
+ }
}
private Background launch(BySelector selector) {
@@ -69,17 +71,20 @@
* Drags an object to the center of homescreen.
*/
public void dragToWorkspace() {
- final Point launchableCenter = getObject().getVisibleCenter();
- final Point displaySize = mLauncher.getRealDisplaySize();
- final int width = displaySize.x / 2;
- Workspace.dragIconToWorkspace(
- mLauncher,
- this,
- new Point(
- launchableCenter.x >= width ?
- launchableCenter.x - width / 2 : launchableCenter.x + width / 2,
- displaySize.y / 2),
- getLongPressIndicator());
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ final Point launchableCenter = getObject().getVisibleCenter();
+ final Point displaySize = mLauncher.getRealDisplaySize();
+ final int width = displaySize.x / 2;
+ Workspace.dragIconToWorkspace(
+ mLauncher,
+ this,
+ new Point(
+ launchableCenter.x >= width
+ ? launchableCenter.x - width / 2
+ : launchableCenter.x + width / 2,
+ displaySize.y / 2),
+ getLongPressIndicator());
+ }
}
protected abstract String getLongPressIndicator();
diff --git a/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java b/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
index 95c4997..6df8790 100644
--- a/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
+++ b/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
@@ -79,6 +79,8 @@
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
@@ -92,6 +94,13 @@
private static final int GESTURE_STEP_MS = 16;
private static long START_TIME = System.currentTimeMillis();
+ static final Pattern LOG_TIME = Pattern.compile(
+ "[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\.[0-9][0-9][0-9]");
+
+ static final Pattern EVENT_LOG_ENTRY = Pattern.compile(
+ "(?<time>[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\.[0-9][0-9][0-9])"
+ + ".*" + TestProtocol.TAPL_EVENTS_TAG + ": (?<event>.*)");
+
// Types for launcher containers that the user is interacting with. "Background" is a
// pseudo-container corresponding to inactive launcher covered by another app.
public enum ContainerType {
@@ -146,6 +155,11 @@
private Consumer<ContainerType> mOnSettledStateAction;
+ // Not null when we are collecting expected events to compare with actual ones.
+ private List<Pattern> mExpectedEvents;
+
+ private String mTimeBeforeFirstLogEvent;
+
/**
* Constructs the root of TAPL hierarchy. You get all other objects from it.
*/
@@ -299,8 +313,11 @@
public void checkForAnomaly() {
final String anomalyMessage = getAnomalyMessage();
if (anomalyMessage != null) {
- failWithSystemHealth(
- "Tests are broken by a non-Launcher system error: " + anomalyMessage);
+ String message = "Tests are broken by a non-Launcher system error: " + anomalyMessage;
+ log("Hierarchy dump for: " + message);
+ dumpViewHierarchy();
+
+ Assert.fail(formatSystemHealthMessage(message));
}
}
@@ -339,7 +356,7 @@
mOnSettledStateAction = onSettledStateAction;
}
- private String getSystemHealthMessage() {
+ private String formatSystemHealthMessage(String message) {
final String testPackage = getContext().getPackageName();
mInstrumentation.getUiAutomation().grantRuntimePermission(
@@ -347,30 +364,34 @@
mInstrumentation.getUiAutomation().grantRuntimePermission(
testPackage, "android.permission.PACKAGE_USAGE_STATS");
- return mSystemHealthSupplier != null
+ final String systemHealth = mSystemHealthSupplier != null
? mSystemHealthSupplier.apply(START_TIME)
: TestHelpers.getSystemHealthMessage(getContext(), START_TIME);
+
+ if (systemHealth != null) {
+ return message
+ + ",\nperhaps linked to system health problems:\n<<<<<<<<<<<<<<<<<<\n"
+ + systemHealth + "\n>>>>>>>>>>>>>>>>>>";
+ }
+
+ return message;
}
private void fail(String message) {
checkForAnomaly();
- failWithSystemHealth("http://go/tapl : " + getContextDescription() + message +
- " (visible state: " + getVisibleStateMessage() + ")");
- }
-
- private void failWithSystemHealth(String message) {
- final String systemHealth = getSystemHealthMessage();
- if (systemHealth != null) {
- message = message
- + ", perhaps because of system health problems:\n<<<<<<<<<<<<<<<<<<\n"
- + systemHealth + "\n>>>>>>>>>>>>>>>>>>";
- }
-
+ message = "http://go/tapl : " + getContextDescription() + message
+ + " (visible state: " + getVisibleStateMessage() + ")";
log("Hierarchy dump for: " + message);
dumpViewHierarchy();
- Assert.fail(message);
+ final String eventMismatch = getEventMismatchMessage();
+
+ if (eventMismatch != null) {
+ message = message + ",\nhaving produced wrong events:\n " + eventMismatch;
+ }
+
+ Assert.fail(formatSystemHealthMessage(message));
}
private String getContextDescription() {
@@ -539,61 +560,63 @@
* @return the Workspace object.
*/
public Workspace pressHome() {
- // Click home, then wait for any accessibility event, then wait until accessibility events
- // stop.
- // We need waiting for any accessibility event generated after pressing Home because
- // otherwise waitForIdle may return immediately in case when there was a big enough pause in
- // accessibility events prior to pressing Home.
- final String action;
- if (getNavigationModel() == NavigationModel.ZERO_BUTTON) {
- checkForAnomaly();
+ try (LauncherInstrumentation.Closable e = eventsCheck()) {
+ // Click home, then wait for any accessibility event, then wait until accessibility
+ // events stop.
+ // We need waiting for any accessibility event generated after pressing Home because
+ // otherwise waitForIdle may return immediately in case when there was a big enough
+ // pause in accessibility events prior to pressing Home.
+ final String action;
+ if (getNavigationModel() == NavigationModel.ZERO_BUTTON) {
+ checkForAnomaly();
- final Point displaySize = getRealDisplaySize();
+ final Point displaySize = getRealDisplaySize();
- if (hasLauncherObject(CONTEXT_MENU_RES_ID)) {
- linearGesture(
- displaySize.x / 2, displaySize.y - 1,
- displaySize.x / 2, 0,
- ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME,
- false);
- try (LauncherInstrumentation.Closable c = addContextLayer(
- "Swiped up from context menu to home")) {
- waitUntilGone(CONTEXT_MENU_RES_ID);
- }
- }
- if (hasLauncherObject(WORKSPACE_RES_ID)) {
- log(action = "already at home");
- } else {
- log("Hierarchy before swiping up to home:");
- dumpViewHierarchy();
- log(action = "swiping up to home from " + getVisibleStateMessage());
-
- try (LauncherInstrumentation.Closable c = addContextLayer(action)) {
- swipeToState(
+ if (hasLauncherObject(CONTEXT_MENU_RES_ID)) {
+ linearGesture(
displaySize.x / 2, displaySize.y - 1,
displaySize.x / 2, 0,
- ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME, NORMAL_STATE_ORDINAL);
+ ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME,
+ false);
+ try (LauncherInstrumentation.Closable c = addContextLayer(
+ "Swiped up from context menu to home")) {
+ waitUntilGone(CONTEXT_MENU_RES_ID);
+ }
+ }
+ if (hasLauncherObject(WORKSPACE_RES_ID)) {
+ log(action = "already at home");
+ } else {
+ log("Hierarchy before swiping up to home:");
+ dumpViewHierarchy();
+ log(action = "swiping up to home from " + getVisibleStateMessage());
+
+ try (LauncherInstrumentation.Closable c = addContextLayer(action)) {
+ swipeToState(
+ displaySize.x / 2, displaySize.y - 1,
+ displaySize.x / 2, 0,
+ ZERO_BUTTON_STEPS_FROM_BACKGROUND_TO_HOME, NORMAL_STATE_ORDINAL);
+ }
+ }
+ } else {
+ log("Hierarchy before clicking home:");
+ dumpViewHierarchy();
+ log(action = "clicking home button from " + getVisibleStateMessage());
+ try (LauncherInstrumentation.Closable c = addContextLayer(action)) {
+ mDevice.waitForIdle();
+ runToState(
+ waitForSystemUiObject("home")::click,
+ NORMAL_STATE_ORDINAL,
+ !hasLauncherObject(WORKSPACE_RES_ID)
+ && (hasLauncherObject(APPS_RES_ID)
+ || hasLauncherObject(OVERVIEW_RES_ID)));
+ mDevice.waitForIdle();
}
}
- } else {
- log("Hierarchy before clicking home:");
- dumpViewHierarchy();
- log(action = "clicking home button from " + getVisibleStateMessage());
- try (LauncherInstrumentation.Closable c = addContextLayer(action)) {
- mDevice.waitForIdle();
- runToState(
- () -> waitForSystemUiObject("home").click(),
- NORMAL_STATE_ORDINAL,
- !hasLauncherObject(WORKSPACE_RES_ID)
- && (hasLauncherObject(APPS_RES_ID)
- || hasLauncherObject(OVERVIEW_RES_ID)));
- mDevice.waitForIdle();
+ try (LauncherInstrumentation.Closable c = addContextLayer(
+ "performed action to switch to Home - " + action)) {
+ return getWorkspace();
}
}
- try (LauncherInstrumentation.Closable c = addContextLayer(
- "performed action to switch to Home - " + action)) {
- return getWorkspace();
- }
}
/**
@@ -1099,4 +1122,104 @@
}
return tasks;
}
+
+ private List<String> getEvents() {
+ final ArrayList<String> events = new ArrayList<>();
+ try {
+ final String logcatTimeParameter =
+ mTimeBeforeFirstLogEvent != null ? " -t " + mTimeBeforeFirstLogEvent : "";
+ final String logcatEvents = mDevice.executeShellCommand(
+ "logcat -d --pid=" + getPid() + logcatTimeParameter
+ + " -s " + TestProtocol.TAPL_EVENTS_TAG);
+ final Matcher matcher = EVENT_LOG_ENTRY.matcher(logcatEvents);
+ while (matcher.find()) {
+ final String eventTime = matcher.group("time");
+ if (eventTime.equals(mTimeBeforeFirstLogEvent)) continue;
+
+ events.add(matcher.group("event"));
+ }
+ return events;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void startRecordingEvents() {
+ Assert.assertTrue("Already recording events", mExpectedEvents == null);
+ mExpectedEvents = new ArrayList<>();
+
+ try {
+ final String lastLogLine =
+ mDevice.executeShellCommand("logcat -d --pid=" + getPid() + " -t 1");
+ final Matcher matcher = LOG_TIME.matcher(lastLogLine);
+ mTimeBeforeFirstLogEvent = matcher.find() ? matcher.group().replaceAll(" ", "") : null;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void stopRecordingEvents() {
+ mExpectedEvents = null;
+ }
+
+ Closable eventsCheck() {
+ // Entering events check block.
+ startRecordingEvents();
+
+ return () -> {
+ // Leaving events check block.
+ if (mExpectedEvents == null) {
+ return; // There was a failure. Noo need to report another one.
+ }
+
+ // Wait until Launcher generates expected number of events.
+ final long endTime = SystemClock.uptimeMillis() + WAIT_TIME_MS;
+ while (SystemClock.uptimeMillis() < endTime
+ && getEvents().size() < mExpectedEvents.size()) {
+ SystemClock.sleep(100);
+ }
+
+ final String message = getEventMismatchMessage();
+ if (message != null) {
+ Assert.fail(formatSystemHealthMessage(
+ "http://go/tapl : unexpected event sequence: " + message));
+ }
+ };
+ }
+
+ void expectEvent(Pattern expected) {
+ if (mExpectedEvents != null) mExpectedEvents.add(expected);
+ }
+
+ private String getEventMismatchMessage() {
+ if (mExpectedEvents == null) return null;
+
+ try {
+ final List<String> actual = getEvents();
+
+ for (int i = 0; i < mExpectedEvents.size(); ++i) {
+ if (i >= actual.size()) {
+ return formatEventMismatchMessage("too few actual events", actual, i);
+ }
+ if (!mExpectedEvents.get(i).matcher(actual.get(i)).find()) {
+ return formatEventMismatchMessage("mismatched event", actual, i);
+ }
+ }
+
+ if (actual.size() > mExpectedEvents.size()) {
+ return formatEventMismatchMessage(
+ "too many actual events", actual, mExpectedEvents.size());
+ }
+ } finally {
+ stopRecordingEvents();
+ }
+
+ return null;
+ }
+
+ private String formatEventMismatchMessage(String message, List<String> actual, int position) {
+ return message + ", pos=" + position
+ + ", expected=" + mExpectedEvents
+ + ", actual=" + actual;
+ }
}
\ No newline at end of file
diff --git a/tests/tapl/com/android/launcher3/tapl/OptionsPopupMenuItem.java b/tests/tapl/com/android/launcher3/tapl/OptionsPopupMenuItem.java
index 8527d05..461610d 100644
--- a/tests/tapl/com/android/launcher3/tapl/OptionsPopupMenuItem.java
+++ b/tests/tapl/com/android/launcher3/tapl/OptionsPopupMenuItem.java
@@ -35,12 +35,14 @@
*/
@NonNull
public void launch(@NonNull String expectedPackageName) {
- LauncherInstrumentation.log("OptionsPopupMenuItem before click "
- + mObject.getVisibleCenter() + " in " + mObject.getVisibleBounds());
- mObject.click();
- mLauncher.assertTrue(
- "App didn't start: " + By.pkg(expectedPackageName),
- mLauncher.getDevice().wait(Until.hasObject(By.pkg(expectedPackageName)),
- LauncherInstrumentation.WAIT_TIME_MS));
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ LauncherInstrumentation.log("OptionsPopupMenuItem before click "
+ + mObject.getVisibleCenter() + " in " + mObject.getVisibleBounds());
+ mObject.click();
+ mLauncher.assertTrue(
+ "App didn't start: " + By.pkg(expectedPackageName),
+ mLauncher.getDevice().wait(Until.hasObject(By.pkg(expectedPackageName)),
+ LauncherInstrumentation.WAIT_TIME_MS));
+ }
}
}
diff --git a/tests/tapl/com/android/launcher3/tapl/Overview.java b/tests/tapl/com/android/launcher3/tapl/Overview.java
index 16a64a7..6622c6e 100644
--- a/tests/tapl/com/android/launcher3/tapl/Overview.java
+++ b/tests/tapl/com/android/launcher3/tapl/Overview.java
@@ -45,8 +45,9 @@
*/
@NonNull
public AllAppsFromOverview switchToAllApps() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "want to switch from overview to all apps")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "want to switch from overview to all apps")) {
verifyActiveContainer();
// Swipe from an app icon to the top.
diff --git a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
index 46f8ba5..0d93cbc 100644
--- a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
+++ b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
@@ -45,8 +45,9 @@
* Swipes the task up.
*/
public void dismiss() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "want to dismiss a task")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "want to dismiss a task")) {
verifyActiveContainer();
// Dismiss the task via flinging it up.
final Rect taskBounds = mTask.getVisibleBounds();
@@ -61,15 +62,17 @@
* Clicks at the task.
*/
public Background open() {
- verifyActiveContainer();
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "clicking an overview task")) {
- mLauncher.executeAndWaitForEvent(
- () -> mTask.click(),
- event -> event.getEventType() == TYPE_WINDOW_STATE_CHANGED,
- () -> "Launching task didn't open a new window: "
- + mTask.getParent().getContentDescription());
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ verifyActiveContainer();
+ try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "clicking an overview task")) {
+ mLauncher.executeAndWaitForEvent(
+ () -> mTask.click(),
+ event -> event.getEventType() == TYPE_WINDOW_STATE_CHANGED,
+ () -> "Launching task didn't open a new window: "
+ + mTask.getParent().getContentDescription());
+ }
+ return new Background(mLauncher);
}
- return new Background(mLauncher);
}
}
diff --git a/tests/tapl/com/android/launcher3/tapl/Widget.java b/tests/tapl/com/android/launcher3/tapl/Widget.java
index 1b6d8c4..dfd74ed 100644
--- a/tests/tapl/com/android/launcher3/tapl/Widget.java
+++ b/tests/tapl/com/android/launcher3/tapl/Widget.java
@@ -22,6 +22,7 @@
* Widget in workspace or a widget list.
*/
public final class Widget extends Launchable {
+
Widget(LauncherInstrumentation launcher, UiObject2 icon) {
super(launcher, icon);
}
diff --git a/tests/tapl/com/android/launcher3/tapl/Widgets.java b/tests/tapl/com/android/launcher3/tapl/Widgets.java
index d208c66..ede5bd9 100644
--- a/tests/tapl/com/android/launcher3/tapl/Widgets.java
+++ b/tests/tapl/com/android/launcher3/tapl/Widgets.java
@@ -41,8 +41,9 @@
* Flings forward (down) and waits the fling's end.
*/
public void flingForward() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "want to fling forward in widgets")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "want to fling forward in widgets")) {
LauncherInstrumentation.log("Widgets.flingForward enter");
final UiObject2 widgetsContainer = verifyActiveContainer();
mLauncher.scroll(
@@ -62,8 +63,9 @@
* Flings backward (up) and waits the fling's end.
*/
public void flingBackward() {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "want to fling backwards in widgets")) {
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "want to fling backwards in widgets")) {
LauncherInstrumentation.log("Widgets.flingBackward enter");
final UiObject2 widgetsContainer = verifyActiveContainer();
mLauncher.scroll(
diff --git a/tests/tapl/com/android/launcher3/tapl/Workspace.java b/tests/tapl/com/android/launcher3/tapl/Workspace.java
index af7e552..1d2c821 100644
--- a/tests/tapl/com/android/launcher3/tapl/Workspace.java
+++ b/tests/tapl/com/android/launcher3/tapl/Workspace.java
@@ -85,7 +85,8 @@
*/
@NonNull
public AllApps switchToAllApps() {
- try (LauncherInstrumentation.Closable c =
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
+ LauncherInstrumentation.Closable c =
mLauncher.addContextLayer("want to switch from workspace to all apps")) {
verifyActiveContainer();
final int deviceHeight = mLauncher.getDevice().getDisplayHeight();
@@ -156,21 +157,23 @@
* second screen.
*/
public void ensureWorkspaceIsScrollable() {
- final UiObject2 workspace = verifyActiveContainer();
- if (!isWorkspaceScrollable(workspace)) {
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
- "dragging icon to a second page of workspace to make it scrollable")) {
- dragIconToWorkspace(
- mLauncher,
- getHotseatAppIcon("Chrome"),
- new Point(mLauncher.getDevice().getDisplayWidth(),
- workspace.getVisibleBounds().centerY()),
- "deep_shortcuts_container");
- verifyActiveContainer();
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ final UiObject2 workspace = verifyActiveContainer();
+ if (!isWorkspaceScrollable(workspace)) {
+ try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
+ "dragging icon to a second page of workspace to make it scrollable")) {
+ dragIconToWorkspace(
+ mLauncher,
+ getHotseatAppIcon("Chrome"),
+ new Point(mLauncher.getDevice().getDisplayWidth(),
+ workspace.getVisibleBounds().centerY()),
+ "deep_shortcuts_container");
+ verifyActiveContainer();
+ }
}
+ assertTrue("Home screen workspace didn't become scrollable",
+ isWorkspaceScrollable(workspace));
}
- assertTrue("Home screen workspace didn't become scrollable",
- isWorkspaceScrollable(workspace));
}
private boolean isWorkspaceScrollable(UiObject2 workspace) {
@@ -213,11 +216,13 @@
* recoil to complete.
*/
public void flingForward() {
- final UiObject2 workspace = verifyActiveContainer();
- mLauncher.scroll(workspace, Direction.RIGHT,
- new Rect(0, 0, mLauncher.getEdgeSensitivityWidth() + 1, 0),
- FLING_STEPS, false);
- verifyActiveContainer();
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ final UiObject2 workspace = verifyActiveContainer();
+ mLauncher.scroll(workspace, Direction.RIGHT,
+ new Rect(0, 0, mLauncher.getEdgeSensitivityWidth() + 1, 0),
+ FLING_STEPS, false);
+ verifyActiveContainer();
+ }
}
/**
@@ -225,11 +230,13 @@
* recoil to complete.
*/
public void flingBackward() {
- final UiObject2 workspace = verifyActiveContainer();
- mLauncher.scroll(workspace, Direction.LEFT,
- new Rect(mLauncher.getEdgeSensitivityWidth() + 1, 0, 0, 0),
- FLING_STEPS, false);
- verifyActiveContainer();
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ final UiObject2 workspace = verifyActiveContainer();
+ mLauncher.scroll(workspace, Direction.LEFT,
+ new Rect(mLauncher.getEdgeSensitivityWidth() + 1, 0, 0, 0),
+ FLING_STEPS, false);
+ verifyActiveContainer();
+ }
}
/**
@@ -239,10 +246,12 @@
*/
@NonNull
public Widgets openAllWidgets() {
- verifyActiveContainer();
- mLauncher.getDevice().pressKeyCode(KeyEvent.KEYCODE_W, KeyEvent.META_CTRL_ON);
- try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer("pressed Ctrl+W")) {
- return new Widgets(mLauncher);
+ try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
+ verifyActiveContainer();
+ mLauncher.getDevice().pressKeyCode(KeyEvent.KEYCODE_W, KeyEvent.META_CTRL_ON);
+ try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer("pressed Ctrl+W")) {
+ return new Widgets(mLauncher);
+ }
}
}