Merge Android R (rvc-dev-plus-aosp-without-vendor@6692709)
Bug: 166295507 Merged-In: I88f54d5cf388aeacbf1da48e3e5f1e89f37ba836 Change-Id: I2e4012ae6bf1cf4e5e5cb76790cd2451e313febc
This commit is contained in:
commit
05bfabfc02
953 files changed
+54481
-34826
No files matched your search
@@ -22,7 +22,6 @@ import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CH
|
||||
import static com.android.launcher3.compat.AccessibilityManagerCompat.isAccessibilityEnabled;
|
||||
import static com.android.launcher3.compat.AccessibilityManagerCompat.sendCustomAccessibilityEvent;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
@@ -30,11 +29,12 @@ import android.util.Pair;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.accessibility.AccessibilityNodeInfo;
|
||||
import android.view.animation.Interpolator;
|
||||
import android.widget.LinearLayout;
|
||||
|
||||
import androidx.annotation.IntDef;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.anim.PendingAnimation;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
|
||||
import com.android.launcher3.util.TouchController;
|
||||
@@ -59,6 +59,7 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
|
||||
TYPE_DISCOVERY_BOUNCE,
|
||||
TYPE_SNACKBAR,
|
||||
TYPE_LISTENER,
|
||||
TYPE_ALL_APPS_EDU,
|
||||
|
||||
TYPE_TASK_MENU,
|
||||
TYPE_OPTIONS_POPUP
|
||||
@@ -74,25 +75,28 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
|
||||
public static final int TYPE_DISCOVERY_BOUNCE = 1 << 6;
|
||||
public static final int TYPE_SNACKBAR = 1 << 7;
|
||||
public static final int TYPE_LISTENER = 1 << 8;
|
||||
public static final int TYPE_ALL_APPS_EDU = 1 << 9;
|
||||
|
||||
// Popups related to quickstep UI
|
||||
public static final int TYPE_TASK_MENU = 1 << 9;
|
||||
public static final int TYPE_OPTIONS_POPUP = 1 << 10;
|
||||
public static final int TYPE_TASK_MENU = 1 << 10;
|
||||
public static final int TYPE_OPTIONS_POPUP = 1 << 11;
|
||||
|
||||
public static final int TYPE_ALL = TYPE_FOLDER | TYPE_ACTION_POPUP
|
||||
| TYPE_WIDGETS_BOTTOM_SHEET | TYPE_WIDGET_RESIZE_FRAME | TYPE_WIDGETS_FULL_SHEET
|
||||
| TYPE_ON_BOARD_POPUP | TYPE_DISCOVERY_BOUNCE | TYPE_TASK_MENU
|
||||
| TYPE_OPTIONS_POPUP | TYPE_SNACKBAR | TYPE_LISTENER;
|
||||
| TYPE_OPTIONS_POPUP | TYPE_SNACKBAR | TYPE_LISTENER | TYPE_ALL_APPS_EDU;
|
||||
|
||||
// Type of popups which should be kept open during launcher rebind
|
||||
public static final int TYPE_REBIND_SAFE = TYPE_WIDGETS_FULL_SHEET
|
||||
| TYPE_WIDGETS_BOTTOM_SHEET | TYPE_ON_BOARD_POPUP | TYPE_DISCOVERY_BOUNCE;
|
||||
| TYPE_WIDGETS_BOTTOM_SHEET | TYPE_ON_BOARD_POPUP | TYPE_DISCOVERY_BOUNCE
|
||||
| TYPE_ALL_APPS_EDU;
|
||||
|
||||
// Usually we show the back button when a floating view is open. Instead, hide for these types.
|
||||
public static final int TYPE_HIDE_BACK_BUTTON = TYPE_ON_BOARD_POPUP | TYPE_DISCOVERY_BOUNCE
|
||||
| TYPE_SNACKBAR | TYPE_WIDGET_RESIZE_FRAME | TYPE_LISTENER;
|
||||
|
||||
public static final int TYPE_ACCESSIBLE = TYPE_ALL & ~TYPE_DISCOVERY_BOUNCE & ~TYPE_LISTENER;
|
||||
public static final int TYPE_ACCESSIBLE = TYPE_ALL & ~TYPE_DISCOVERY_BOUNCE & ~TYPE_LISTENER
|
||||
& ~TYPE_ALL_APPS_EDU;
|
||||
|
||||
// These view all have particular operation associated with swipe down interaction.
|
||||
public static final int TYPE_STATUS_BAR_SWIPE_DOWN_DISALLOW = TYPE_WIDGETS_BOTTOM_SHEET |
|
||||
@@ -134,9 +138,8 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
|
||||
* Creates a user-controlled animation to hint that the view will be closed if completed.
|
||||
* @param distanceToMove The max distance that elements should move from their starting point.
|
||||
*/
|
||||
public @Nullable Animator createHintCloseAnim(float distanceToMove) {
|
||||
return null;
|
||||
}
|
||||
public void addHintCloseAnim(
|
||||
float distanceToMove, Interpolator interpolator, PendingAnimation target) { }
|
||||
|
||||
public abstract void logActionCommand(int command);
|
||||
|
||||
@@ -171,7 +174,8 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
|
||||
targetInfo.first, TYPE_WINDOW_STATE_CHANGED, targetInfo.second);
|
||||
|
||||
if (mIsOpen) {
|
||||
performAccessibilityAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null);
|
||||
getAccessibilityInitialFocusView().performAccessibilityAction(
|
||||
AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null);
|
||||
}
|
||||
ActivityContext.lookupContext(getContext()).getDragLayer()
|
||||
.sendAccessibilityEvent(TYPE_WINDOW_CONTENT_CHANGED);
|
||||
@@ -181,7 +185,15 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
|
||||
return null;
|
||||
}
|
||||
|
||||
protected static <T extends AbstractFloatingView> T getOpenView(
|
||||
/** Returns the View that Accessibility services should focus on first. */
|
||||
protected View getAccessibilityInitialFocusView() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a view matching FloatingViewType
|
||||
*/
|
||||
public static <T extends AbstractFloatingView> T getOpenView(
|
||||
ActivityContext activity, @FloatingViewType int type) {
|
||||
BaseDragLayer dragLayer = activity.getDragLayer();
|
||||
if (dragLayer == null) return null;
|
||||
@@ -251,4 +263,8 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
|
||||
@FloatingViewType int type) {
|
||||
return getOpenView(activity, type);
|
||||
}
|
||||
|
||||
public boolean canInterceptEventsInSystemGestureRegion() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import android.view.ViewGroup;
|
||||
import com.android.launcher3.accessibility.DragViewStateAnnouncer;
|
||||
import com.android.launcher3.dragndrop.DragLayer;
|
||||
import com.android.launcher3.util.FocusLogic;
|
||||
import com.android.launcher3.util.MainThreadInitializedObject;
|
||||
import com.android.launcher3.widget.LauncherAppWidgetHostView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -35,7 +36,12 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
|
||||
private static final Rect sTmpRect = new Rect();
|
||||
|
||||
// Represents the cell size on the grid in the two orientations.
|
||||
private static Point[] sCellSize;
|
||||
private static final MainThreadInitializedObject<Point[]> CELL_SIZE =
|
||||
new MainThreadInitializedObject<>(c -> {
|
||||
InvariantDeviceProfile inv = LauncherAppState.getIDP(c);
|
||||
return new Point[] {inv.landscapeProfile.getCellSize(),
|
||||
inv.portraitProfile.getCellSize()};
|
||||
});
|
||||
|
||||
private static final int HANDLE_COUNT = 4;
|
||||
private static final int INDEX_LEFT = 0;
|
||||
@@ -344,7 +350,7 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
|
||||
mWidgetView.requestLayout();
|
||||
}
|
||||
|
||||
static void updateWidgetSizeRanges(AppWidgetHostView widgetView, Launcher launcher,
|
||||
public static void updateWidgetSizeRanges(AppWidgetHostView widgetView, Launcher launcher,
|
||||
int spanX, int spanY) {
|
||||
getWidgetSizeRanges(launcher, spanX, spanY, sTmpRect);
|
||||
widgetView.updateAppWidgetSize(null, sTmpRect.left, sTmpRect.top,
|
||||
@@ -352,27 +358,19 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
|
||||
}
|
||||
|
||||
public static Rect getWidgetSizeRanges(Context context, int spanX, int spanY, Rect rect) {
|
||||
if (sCellSize == null) {
|
||||
InvariantDeviceProfile inv = LauncherAppState.getIDP(context);
|
||||
|
||||
// Initiate cell sizes.
|
||||
sCellSize = new Point[2];
|
||||
sCellSize[0] = inv.landscapeProfile.getCellSize();
|
||||
sCellSize[1] = inv.portraitProfile.getCellSize();
|
||||
}
|
||||
|
||||
if (rect == null) {
|
||||
rect = new Rect();
|
||||
}
|
||||
final float density = context.getResources().getDisplayMetrics().density;
|
||||
final Point[] cellSize = CELL_SIZE.get(context);
|
||||
|
||||
// Compute landscape size
|
||||
int landWidth = (int) ((spanX * sCellSize[0].x) / density);
|
||||
int landHeight = (int) ((spanY * sCellSize[0].y) / density);
|
||||
int landWidth = (int) ((spanX * cellSize[0].x) / density);
|
||||
int landHeight = (int) ((spanY * cellSize[0].y) / density);
|
||||
|
||||
// Compute portrait size
|
||||
int portWidth = (int) ((spanX * sCellSize[1].x) / density);
|
||||
int portHeight = (int) ((spanY * sCellSize[1].y) / density);
|
||||
int portWidth = (int) ((spanX * cellSize[1].x) / density);
|
||||
int portHeight = (int) ((spanY * cellSize[1].y) / density);
|
||||
rect.set(portWidth, landHeight, landWidth, portHeight);
|
||||
return rect;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
import static android.os.Process.myUserHandle;
|
||||
|
||||
import android.appwidget.AppWidgetHost;
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.appwidget.AppWidgetProviderInfo;
|
||||
@@ -10,16 +12,15 @@ import android.content.Intent;
|
||||
import android.database.Cursor;
|
||||
import android.util.Log;
|
||||
|
||||
import com.android.launcher3.LauncherSettings.Favorites;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.model.LoaderTask;
|
||||
import com.android.launcher3.provider.RestoreDbTask;
|
||||
import com.android.launcher3.util.ContentWriter;
|
||||
|
||||
import androidx.annotation.WorkerThread;
|
||||
|
||||
import static android.os.Process.myUserHandle;
|
||||
import com.android.launcher3.LauncherSettings.Favorites;
|
||||
import com.android.launcher3.model.LoaderTask;
|
||||
import com.android.launcher3.model.WidgetsModel;
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.pm.UserCache;
|
||||
import com.android.launcher3.provider.RestoreDbTask;
|
||||
import com.android.launcher3.util.ContentWriter;
|
||||
|
||||
public class AppWidgetsRestoredReceiver extends BroadcastReceiver {
|
||||
|
||||
@@ -50,7 +51,7 @@ public class AppWidgetsRestoredReceiver extends BroadcastReceiver {
|
||||
@WorkerThread
|
||||
public static void restoreAppWidgetIds(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
|
||||
AppWidgetHost appWidgetHost = new LauncherAppWidgetHost(context);
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
if (WidgetsModel.GO_DISABLE_WIDGETS) {
|
||||
Log.e(TAG, "Skipping widget ID remap as widgets not supported");
|
||||
appWidgetHost.deleteHost();
|
||||
return;
|
||||
@@ -82,7 +83,7 @@ public class AppWidgetsRestoredReceiver extends BroadcastReceiver {
|
||||
|
||||
// b/135926478: Work profile widget restore is broken in platform. This forces us to
|
||||
// recreate the widget during loading with the correct host provider.
|
||||
long mainProfileId = UserManagerCompat.getInstance(context)
|
||||
long mainProfileId = UserCache.INSTANCE.get(context)
|
||||
.getSerialNumberForUser(myUserHandle());
|
||||
String oldWidgetId = Integer.toString(oldWidgetIds[i]);
|
||||
int result = new ContentWriter(context, new ContentWriter.CommitParams(
|
||||
|
||||
@@ -44,6 +44,8 @@ import com.android.launcher3.LauncherProvider.SqlArguments;
|
||||
import com.android.launcher3.LauncherSettings.Favorites;
|
||||
import com.android.launcher3.icons.GraphicsUtils;
|
||||
import com.android.launcher3.icons.LauncherIcons;
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
import com.android.launcher3.qsb.QsbContainerView;
|
||||
import com.android.launcher3.util.IntArray;
|
||||
import com.android.launcher3.util.PackageManagerHelper;
|
||||
@@ -130,6 +132,7 @@ public class AutoInstallsLayout {
|
||||
private static final String ATTR_PACKAGE_NAME = "packageName";
|
||||
private static final String ATTR_CLASS_NAME = "className";
|
||||
private static final String ATTR_TITLE = "title";
|
||||
private static final String ATTR_TITLE_TEXT = "titleText";
|
||||
private static final String ATTR_SCREEN = "screen";
|
||||
|
||||
// x and y can be specified as negative integers, in which case -1 represents the
|
||||
@@ -583,7 +586,8 @@ public class AutoInstallsLayout {
|
||||
if (titleResId != 0) {
|
||||
title = mSourceRes.getString(titleResId);
|
||||
} else {
|
||||
title = "";
|
||||
String titleText = getAttributeValue(parser, ATTR_TITLE_TEXT);
|
||||
title = TextUtils.isEmpty(titleText) ? "" : titleText;
|
||||
}
|
||||
|
||||
mValues.put(Favorites.TITLE, title);
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.model.WidgetsModel.GO_DISABLE_WIDGETS;
|
||||
import static com.android.launcher3.util.SystemUiController.UI_STATE_OVERVIEW;
|
||||
|
||||
import static java.lang.annotation.RetentionPolicy.SOURCE;
|
||||
@@ -24,30 +25,34 @@ import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.ContextWrapper;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.res.Configuration;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Bundle;
|
||||
import android.os.UserHandle;
|
||||
import android.util.Log;
|
||||
import android.view.ContextThemeWrapper;
|
||||
|
||||
import androidx.annotation.IntDef;
|
||||
|
||||
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
|
||||
import com.android.launcher3.logging.StatsLogManager;
|
||||
import com.android.launcher3.logging.StatsLogUtils;
|
||||
import com.android.launcher3.logging.StatsLogUtils.LogStateProvider;
|
||||
import com.android.launcher3.logging.UserEventDispatcher;
|
||||
import com.android.launcher3.logging.UserEventDispatcher.UserEventDelegate;
|
||||
import com.android.launcher3.uioverrides.UiFactory;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto;
|
||||
import com.android.launcher3.util.SystemUiController;
|
||||
import com.android.launcher3.util.ViewCache;
|
||||
import com.android.launcher3.views.ActivityContext;
|
||||
|
||||
import java.io.FileDescriptor;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public abstract class BaseActivity extends Activity
|
||||
implements UserEventDelegate, LogStateProvider, ActivityContext {
|
||||
/**
|
||||
* Launcher BaseActivity
|
||||
*/
|
||||
public abstract class BaseActivity extends Activity implements ActivityContext {
|
||||
|
||||
private static final String TAG = "BaseActivity";
|
||||
|
||||
public static final int INVISIBLE_BY_STATE_HANDLER = 1 << 0;
|
||||
public static final int INVISIBLE_BY_APP_TRANSITIONS = 1 << 1;
|
||||
@@ -81,19 +86,44 @@ public abstract class BaseActivity extends Activity
|
||||
protected StatsLogManager mStatsLogManager;
|
||||
protected SystemUiController mSystemUiController;
|
||||
|
||||
private static final int ACTIVITY_STATE_STARTED = 1 << 0;
|
||||
private static final int ACTIVITY_STATE_RESUMED = 1 << 1;
|
||||
|
||||
public static final int ACTIVITY_STATE_STARTED = 1 << 0;
|
||||
public static final int ACTIVITY_STATE_RESUMED = 1 << 1;
|
||||
|
||||
/**
|
||||
* State flag indicating if the user is active or the actitvity when to background as a result
|
||||
* State flags indicating that the activity has received one frame after resume, and was
|
||||
* not immediately paused.
|
||||
*/
|
||||
public static final int ACTIVITY_STATE_DEFERRED_RESUMED = 1 << 2;
|
||||
|
||||
public static final int ACTIVITY_STATE_WINDOW_FOCUSED = 1 << 3;
|
||||
|
||||
/**
|
||||
* State flag indicating if the user is active or the activity when to background as a result
|
||||
* of user action.
|
||||
* @see #isUserActive()
|
||||
*/
|
||||
private static final int ACTIVITY_STATE_USER_ACTIVE = 1 << 2;
|
||||
public static final int ACTIVITY_STATE_USER_ACTIVE = 1 << 4;
|
||||
|
||||
/**
|
||||
* State flag indicating if the user will be active shortly.
|
||||
*/
|
||||
public static final int ACTIVITY_STATE_USER_WILL_BE_ACTIVE = 1 << 5;
|
||||
|
||||
/**
|
||||
* State flag indicating that a state transition is in progress
|
||||
*/
|
||||
public static final int ACTIVITY_STATE_TRANSITION_ACTIVE = 1 << 6;
|
||||
|
||||
@Retention(SOURCE)
|
||||
@IntDef(
|
||||
flag = true,
|
||||
value = {ACTIVITY_STATE_STARTED, ACTIVITY_STATE_RESUMED, ACTIVITY_STATE_USER_ACTIVE})
|
||||
value = {ACTIVITY_STATE_STARTED,
|
||||
ACTIVITY_STATE_RESUMED,
|
||||
ACTIVITY_STATE_DEFERRED_RESUMED,
|
||||
ACTIVITY_STATE_WINDOW_FOCUSED,
|
||||
ACTIVITY_STATE_USER_ACTIVE,
|
||||
ACTIVITY_STATE_TRANSITION_ACTIVE})
|
||||
public @interface ActivityFlags{}
|
||||
|
||||
@ActivityFlags
|
||||
@@ -114,20 +144,18 @@ public abstract class BaseActivity extends Activity
|
||||
return mDeviceProfile;
|
||||
}
|
||||
|
||||
public int getCurrentState() { return StatsLogUtils.LAUNCHER_STATE_BACKGROUND; }
|
||||
|
||||
public void modifyUserEvent(LauncherLogProto.LauncherEvent event) {}
|
||||
|
||||
public final StatsLogManager getStatsLogManager() {
|
||||
if (mStatsLogManager == null) {
|
||||
mStatsLogManager = StatsLogManager.newInstance(this, this);
|
||||
mStatsLogManager = StatsLogManager.newInstance(this);
|
||||
}
|
||||
return mStatsLogManager;
|
||||
}
|
||||
|
||||
public final UserEventDispatcher getUserEventDispatcher() {
|
||||
if (mUserEventDispatcher == null) {
|
||||
mUserEventDispatcher = UserEventDispatcher.newInstance(this, this);
|
||||
mUserEventDispatcher = UserEventDispatcher.newInstance(this);
|
||||
}
|
||||
return mUserEventDispatcher;
|
||||
}
|
||||
@@ -146,19 +174,20 @@ public abstract class BaseActivity extends Activity
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
mActivityFlags |= ACTIVITY_STATE_STARTED;
|
||||
addActivityFlags(ACTIVITY_STATE_STARTED);
|
||||
super.onStart();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
mActivityFlags |= ACTIVITY_STATE_RESUMED | ACTIVITY_STATE_USER_ACTIVE;
|
||||
addActivityFlags(ACTIVITY_STATE_RESUMED | ACTIVITY_STATE_USER_ACTIVE);
|
||||
removeActivityFlags(ACTIVITY_STATE_USER_WILL_BE_ACTIVE);
|
||||
super.onResume();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onUserLeaveHint() {
|
||||
mActivityFlags &= ~ACTIVITY_STATE_USER_ACTIVE;
|
||||
removeActivityFlags(ACTIVITY_STATE_USER_ACTIVE);
|
||||
super.onUserLeaveHint();
|
||||
}
|
||||
|
||||
@@ -172,7 +201,7 @@ public abstract class BaseActivity extends Activity
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
mActivityFlags &= ~ACTIVITY_STATE_STARTED & ~ACTIVITY_STATE_USER_ACTIVE;
|
||||
removeActivityFlags(ACTIVITY_STATE_STARTED | ACTIVITY_STATE_USER_ACTIVE);
|
||||
mForceInvisible = 0;
|
||||
super.onStop();
|
||||
|
||||
@@ -183,7 +212,7 @@ public abstract class BaseActivity extends Activity
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
mActivityFlags &= ~ACTIVITY_STATE_RESUMED;
|
||||
removeActivityFlags(ACTIVITY_STATE_RESUMED | ACTIVITY_STATE_DEFERRED_RESUMED);
|
||||
super.onPause();
|
||||
|
||||
// Reset the overridden sysui flags used for the task-swipe launch animation, we do this
|
||||
@@ -193,6 +222,17 @@ public abstract class BaseActivity extends Activity
|
||||
getSystemUiController().updateUiState(UI_STATE_OVERVIEW, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWindowFocusChanged(boolean hasFocus) {
|
||||
super.onWindowFocusChanged(hasFocus);
|
||||
if (hasFocus) {
|
||||
addActivityFlags(ACTIVITY_STATE_WINDOW_FOCUSED);
|
||||
} else {
|
||||
removeActivityFlags(ACTIVITY_STATE_WINDOW_FOCUSED);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean isStarted() {
|
||||
return (mActivityFlags & ACTIVITY_STATE_STARTED) != 0;
|
||||
}
|
||||
@@ -208,6 +248,22 @@ public abstract class BaseActivity extends Activity
|
||||
return (mActivityFlags & ACTIVITY_STATE_USER_ACTIVE) != 0;
|
||||
}
|
||||
|
||||
public int getActivityFlags() {
|
||||
return mActivityFlags;
|
||||
}
|
||||
|
||||
protected void addActivityFlags(int flags) {
|
||||
mActivityFlags |= flags;
|
||||
onActivityFlagsChanged(flags);
|
||||
}
|
||||
|
||||
protected void removeActivityFlags(int flags) {
|
||||
mActivityFlags &= ~flags;
|
||||
onActivityFlagsChanged(flags);
|
||||
}
|
||||
|
||||
protected void onActivityFlagsChanged(int changeBits) { }
|
||||
|
||||
public void addOnDeviceProfileChangeListener(OnDeviceProfileChangeListener listener) {
|
||||
mDPChangeListeners.add(listener);
|
||||
}
|
||||
@@ -233,7 +289,7 @@ public abstract class BaseActivity extends Activity
|
||||
/**
|
||||
* 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;
|
||||
@@ -258,13 +314,6 @@ public abstract class BaseActivity extends Activity
|
||||
void onMultiWindowModeChanged(boolean isInMultiWindowMode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
|
||||
if (!UiFactory.dumpActivity(this, writer)) {
|
||||
super.dump(prefix, fd, writer, args);
|
||||
}
|
||||
}
|
||||
|
||||
protected void dumpMisc(String prefix, PrintWriter writer) {
|
||||
writer.println(prefix + "deviceProfile isTransposed="
|
||||
+ getDeviceProfile().isVerticalBarLayout());
|
||||
@@ -274,6 +323,22 @@ public abstract class BaseActivity extends Activity
|
||||
writer.println(prefix + "mForceInvisible: " + mForceInvisible);
|
||||
}
|
||||
|
||||
/**
|
||||
* A wrapper around the platform method with Launcher specific checks
|
||||
*/
|
||||
public void startShortcut(String packageName, String id, Rect sourceBounds,
|
||||
Bundle startActivityOptions, UserHandle user) {
|
||||
if (GO_DISABLE_WIDGETS) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
getSystemService(LauncherApps.class).startShortcut(packageName, id, sourceBounds,
|
||||
startActivityOptions, user);
|
||||
} catch (SecurityException | IllegalStateException e) {
|
||||
Log.e(TAG, "Failed to start shortcut", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T extends BaseActivity> T fromContext(Context context) {
|
||||
if (context instanceof BaseActivity) {
|
||||
return (T) context;
|
||||
|
||||
@@ -16,10 +16,16 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_APP_LAUNCH_TAP;
|
||||
import static com.android.launcher3.util.DefaultDisplay.CHANGE_ROTATION;
|
||||
|
||||
import android.app.ActivityOptions;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.res.Configuration;
|
||||
import android.graphics.Insets;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Bundle;
|
||||
import android.os.Process;
|
||||
@@ -27,25 +33,36 @@ import android.os.StrictMode;
|
||||
import android.os.UserHandle;
|
||||
import android.util.Log;
|
||||
import android.view.ActionMode;
|
||||
import android.view.Display;
|
||||
import android.view.View;
|
||||
import android.view.View.OnClickListener;
|
||||
import android.view.WindowInsets.Type;
|
||||
import android.view.WindowMetrics;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.LauncherSettings.Favorites;
|
||||
import com.android.launcher3.compat.LauncherAppsCompat;
|
||||
import com.android.launcher3.logging.InstanceId;
|
||||
import com.android.launcher3.logging.InstanceIdSequence;
|
||||
import com.android.launcher3.model.AppLaunchTracker;
|
||||
import com.android.launcher3.shortcuts.DeepShortcutManager;
|
||||
import com.android.launcher3.uioverrides.DisplayRotationListener;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
import com.android.launcher3.touch.ItemClickHandler;
|
||||
import com.android.launcher3.uioverrides.WallpaperColorInfo;
|
||||
import com.android.launcher3.util.DefaultDisplay;
|
||||
import com.android.launcher3.util.DefaultDisplay.DisplayInfoChangeListener;
|
||||
import com.android.launcher3.util.DefaultDisplay.Info;
|
||||
import com.android.launcher3.util.PackageManagerHelper;
|
||||
import com.android.launcher3.util.Themes;
|
||||
import com.android.launcher3.util.TraceHelper;
|
||||
import com.android.launcher3.util.WindowBounds;
|
||||
|
||||
/**
|
||||
* Extension of BaseActivity allowing support for drag-n-drop
|
||||
*/
|
||||
public abstract class BaseDraggingActivity extends BaseActivity
|
||||
implements WallpaperColorInfo.OnChangeListener {
|
||||
implements WallpaperColorInfo.OnChangeListener, DisplayInfoChangeListener {
|
||||
|
||||
private static final String TAG = "BaseDraggingActivity";
|
||||
|
||||
@@ -56,21 +73,21 @@ public abstract class BaseDraggingActivity extends BaseActivity
|
||||
private ActionMode mCurrentActionMode;
|
||||
protected boolean mIsSafeModeEnabled;
|
||||
|
||||
private OnStartCallback mOnStartCallback;
|
||||
private Runnable mOnStartCallback;
|
||||
|
||||
private int mThemeRes = R.style.AppTheme;
|
||||
|
||||
private DisplayRotationListener mRotationListener;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
mIsSafeModeEnabled = getPackageManager().isSafeMode();
|
||||
mRotationListener = new DisplayRotationListener(this, this::onDeviceRotationChanged);
|
||||
|
||||
|
||||
mIsSafeModeEnabled = TraceHelper.whitelistIpcs("isSafeMode",
|
||||
() -> getPackageManager().isSafeMode());
|
||||
DefaultDisplay.INSTANCE.get(this).addChangeListener(this);
|
||||
|
||||
// Update theme
|
||||
WallpaperColorInfo wallpaperColorInfo = WallpaperColorInfo.getInstance(this);
|
||||
wallpaperColorInfo.addOnChangeListener(this);
|
||||
WallpaperColorInfo.INSTANCE.get(this).addOnChangeListener(this);
|
||||
int themeRes = Themes.getActivityThemeRes(this);
|
||||
if (themeRes != mThemeRes) {
|
||||
mThemeRes = themeRes;
|
||||
@@ -166,13 +183,16 @@ public abstract class BaseDraggingActivity extends BaseActivity
|
||||
AppLaunchTracker.INSTANCE.get(this).onStartApp(intent.getComponent(),
|
||||
Process.myUserHandle(), sourceContainer);
|
||||
} else {
|
||||
LauncherAppsCompat.getInstance(this).startActivityForProfile(
|
||||
getSystemService(LauncherApps.class).startMainActivity(
|
||||
intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
|
||||
AppLaunchTracker.INSTANCE.get(this).onStartApp(intent.getComponent(), user,
|
||||
sourceContainer);
|
||||
}
|
||||
getUserEventDispatcher().logAppLaunch(v, intent);
|
||||
getStatsLogManager().logAppLaunch(v, intent);
|
||||
getUserEventDispatcher().logAppLaunch(v, intent, user);
|
||||
if (item != null) {
|
||||
InstanceId instanceId = new InstanceIdSequence().newInstanceId();
|
||||
logAppLaunch(item, instanceId);
|
||||
}
|
||||
return true;
|
||||
} catch (NullPointerException|ActivityNotFoundException|SecurityException e) {
|
||||
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
|
||||
@@ -181,6 +201,11 @@ public abstract class BaseDraggingActivity extends BaseActivity
|
||||
return false;
|
||||
}
|
||||
|
||||
protected void logAppLaunch(ItemInfo info, InstanceId instanceId) {
|
||||
getStatsLogManager().logger().withItemInfo(info).withInstanceId(instanceId)
|
||||
.log(LAUNCHER_APP_LAUNCH_TAP);
|
||||
}
|
||||
|
||||
private void startShortcutIntentSafely(Intent intent, Bundle optsBundle, ItemInfo info,
|
||||
@Nullable String sourceContainer) {
|
||||
try {
|
||||
@@ -195,8 +220,7 @@ public abstract class BaseDraggingActivity extends BaseActivity
|
||||
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
|
||||
String id = ((WorkspaceItemInfo) info).getDeepShortcutId();
|
||||
String packageName = intent.getPackage();
|
||||
DeepShortcutManager.getInstance(this).startShortcut(
|
||||
packageName, id, intent.getSourceBounds(), optsBundle, info.user);
|
||||
startShortcut(packageName, id, intent.getSourceBounds(), optsBundle, info.user);
|
||||
AppLaunchTracker.INSTANCE.get(this).onStartShortcut(packageName, id, info.user,
|
||||
sourceContainer);
|
||||
} else {
|
||||
@@ -222,7 +246,7 @@ public abstract class BaseDraggingActivity extends BaseActivity
|
||||
super.onStart();
|
||||
|
||||
if (mOnStartCallback != null) {
|
||||
mOnStartCallback.onActivityStart(this);
|
||||
mOnStartCallback.run();
|
||||
mOnStartCallback = null;
|
||||
}
|
||||
}
|
||||
@@ -230,36 +254,50 @@ public abstract class BaseDraggingActivity extends BaseActivity
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
WallpaperColorInfo.getInstance(this).removeOnChangeListener(this);
|
||||
mRotationListener.disable();
|
||||
WallpaperColorInfo.INSTANCE.get(this).removeOnChangeListener(this);
|
||||
DefaultDisplay.INSTANCE.get(this).removeChangeListener(this);
|
||||
}
|
||||
|
||||
public <T extends BaseDraggingActivity> void setOnStartCallback(OnStartCallback<T> callback) {
|
||||
mOnStartCallback = callback;
|
||||
public void runOnceOnStart(Runnable action) {
|
||||
mOnStartCallback = action;
|
||||
}
|
||||
|
||||
public void clearRunOnceOnStartCallback() {
|
||||
mOnStartCallback = null;
|
||||
}
|
||||
|
||||
protected void onDeviceProfileInitiated() {
|
||||
if (mDeviceProfile.isVerticalBarLayout()) {
|
||||
mRotationListener.enable();
|
||||
mDeviceProfile.updateIsSeascape(this);
|
||||
} else {
|
||||
mRotationListener.disable();
|
||||
}
|
||||
}
|
||||
|
||||
private void onDeviceRotationChanged() {
|
||||
if (mDeviceProfile.updateIsSeascape(this)) {
|
||||
@Override
|
||||
public void onDisplayInfoChanged(Info info, int flags) {
|
||||
if ((flags & CHANGE_ROTATION) != 0 && mDeviceProfile.updateIsSeascape(this)) {
|
||||
reapplyUi();
|
||||
}
|
||||
}
|
||||
|
||||
public OnClickListener getItemOnClickListener() {
|
||||
return ItemClickHandler.INSTANCE;
|
||||
}
|
||||
|
||||
protected abstract void reapplyUi();
|
||||
|
||||
/**
|
||||
* Callback for listening for onStart
|
||||
*/
|
||||
public interface OnStartCallback<T extends BaseDraggingActivity> {
|
||||
protected WindowBounds getMultiWindowDisplaySize() {
|
||||
if (Utilities.ATLEAST_R) {
|
||||
WindowMetrics wm = getWindowManager().getCurrentWindowMetrics();
|
||||
|
||||
void onActivityStart(T activity);
|
||||
Insets insets = wm.getWindowInsets().getInsets(Type.systemBars());
|
||||
return new WindowBounds(wm.getBounds(),
|
||||
new Rect(insets.left, insets.top, insets.right, insets.bottom));
|
||||
}
|
||||
// Note: Calls to getSize() can't rely on our cached DefaultDisplay since it can return
|
||||
// the app window size
|
||||
Display display = getWindowManager().getDefaultDisplay();
|
||||
Point mwSize = new Point();
|
||||
display.getSize(mwSize);
|
||||
return new WindowBounds(new Rect(0, 0, mwSize.x, mwSize.y), new Rect());
|
||||
}
|
||||
}
|
||||
@@ -16,17 +16,23 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.Log;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import com.android.launcher3.compat.AccessibilityManagerCompat;
|
||||
import com.android.launcher3.views.RecyclerViewFastScroller;
|
||||
import android.view.accessibility.AccessibilityNodeInfo;
|
||||
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.android.launcher3.compat.AccessibilityManagerCompat;
|
||||
import com.android.launcher3.testing.TestProtocol;
|
||||
import com.android.launcher3.views.ActivityContext;
|
||||
import com.android.launcher3.views.RecyclerViewFastScroller;
|
||||
|
||||
|
||||
/**
|
||||
* A base {@link RecyclerView}, which does the following:
|
||||
@@ -138,7 +144,7 @@ public abstract class BaseRecyclerView extends RecyclerView {
|
||||
if (getCurrentScrollY() == 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return getAdapter() == null || getAdapter().getItemCount() == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,4 +187,20 @@ public abstract class BaseRecyclerView extends RecyclerView {
|
||||
AccessibilityManagerCompat.sendScrollFinishedEventToTest(getContext());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
|
||||
super.onInitializeAccessibilityNodeInfo(info);
|
||||
if (isLayoutSuppressed()) info.setScrollable(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLayoutFrozen(boolean frozen) {
|
||||
final boolean changing = frozen != isLayoutSuppressed();
|
||||
super.setLayoutFrozen(frozen);
|
||||
if (changing) {
|
||||
ActivityContext.lookupContext(getContext()).getDragLayer()
|
||||
.sendAccessibilityEvent(TYPE_WINDOW_CONTENT_CHANGED);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.FastBitmapDrawable.newIcon;
|
||||
import static com.android.launcher3.graphics.PreloadIconDrawable.newPendingIcon;
|
||||
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
|
||||
|
||||
import android.animation.Animator;
|
||||
@@ -27,6 +29,7 @@ import android.content.res.TypedArray;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PointF;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
@@ -37,22 +40,27 @@ import android.util.TypedValue;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
import android.view.ViewDebug;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.android.launcher3.Launcher.OnResumeCallback;
|
||||
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
|
||||
import com.android.launcher3.dot.DotInfo;
|
||||
import com.android.launcher3.dragndrop.DraggableView;
|
||||
import com.android.launcher3.folder.FolderIcon;
|
||||
import com.android.launcher3.graphics.DrawableFactory;
|
||||
import com.android.launcher3.graphics.IconPalette;
|
||||
import com.android.launcher3.graphics.IconShape;
|
||||
import com.android.launcher3.graphics.PreloadIconDrawable;
|
||||
import com.android.launcher3.icons.DotRenderer;
|
||||
import com.android.launcher3.icons.IconCache.IconLoadRequest;
|
||||
import com.android.launcher3.icons.IconCache.ItemInfoUpdateReceiver;
|
||||
import com.android.launcher3.model.PackageItemInfo;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.ItemInfoWithIcon;
|
||||
import com.android.launcher3.model.data.PackageItemInfo;
|
||||
import com.android.launcher3.model.data.PromiseAppInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
import com.android.launcher3.util.SafeCloseable;
|
||||
import com.android.launcher3.views.ActivityContext;
|
||||
import com.android.launcher3.views.IconLabelDotView;
|
||||
|
||||
@@ -64,7 +72,7 @@ import java.text.NumberFormat;
|
||||
* too aggressive.
|
||||
*/
|
||||
public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, OnResumeCallback,
|
||||
IconLabelDotView {
|
||||
IconLabelDotView, DraggableView, Reorderable {
|
||||
|
||||
private static final int DISPLAY_WORKSPACE = 0;
|
||||
private static final int DISPLAY_ALL_APPS = 1;
|
||||
@@ -72,6 +80,10 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
|
||||
private static final int[] STATE_PRESSED = new int[] {android.R.attr.state_pressed};
|
||||
|
||||
private final PointF mTranslationForReorderBounce = new PointF(0, 0);
|
||||
private final PointF mTranslationForReorderPreview = new PointF(0, 0);
|
||||
|
||||
private float mScaleForReorderBounce = 1f;
|
||||
|
||||
private static final Property<BubbleTextView, Float> DOT_SCALE_PROPERTY
|
||||
= new Property<BubbleTextView, Float>(Float.TYPE, "dotScale") {
|
||||
@@ -102,13 +114,11 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
|
||||
private final ActivityContext mActivity;
|
||||
private Drawable mIcon;
|
||||
private final boolean mCenterVertically;
|
||||
private boolean mCenterVertically;
|
||||
|
||||
private final int mDisplay;
|
||||
|
||||
private final CheckLongPressHelper mLongPressHelper;
|
||||
private final StylusEventHelper mStylusEventHelper;
|
||||
private final float mSlop;
|
||||
|
||||
private final boolean mLayoutHorizontal;
|
||||
private final int mIconSize;
|
||||
@@ -135,9 +145,6 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
@ViewDebug.ExportedProperty(category = "launcher")
|
||||
private boolean mDisableRelayout = false;
|
||||
|
||||
@ViewDebug.ExportedProperty(category = "launcher")
|
||||
private final boolean mIgnorePaddingTouch;
|
||||
|
||||
private IconLoadRequest mIconLoadRequest;
|
||||
|
||||
public BubbleTextView(Context context) {
|
||||
@@ -151,36 +158,29 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
public BubbleTextView(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
mActivity = ActivityContext.lookupContext(context);
|
||||
mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
|
||||
|
||||
TypedArray a = context.obtainStyledAttributes(attrs,
|
||||
R.styleable.BubbleTextView, defStyle, 0);
|
||||
mLayoutHorizontal = a.getBoolean(R.styleable.BubbleTextView_layoutHorizontal, false);
|
||||
DeviceProfile grid = mActivity.getDeviceProfile();
|
||||
|
||||
mDisplay = a.getInteger(R.styleable.BubbleTextView_iconDisplay, DISPLAY_WORKSPACE);
|
||||
final int defaultIconSize;
|
||||
if (mDisplay == DISPLAY_WORKSPACE) {
|
||||
DeviceProfile grid = mActivity.getWallpaperDeviceProfile();
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx);
|
||||
setCompoundDrawablePadding(grid.iconDrawablePaddingPx);
|
||||
defaultIconSize = grid.iconSizePx;
|
||||
mIgnorePaddingTouch = true;
|
||||
} else if (mDisplay == DISPLAY_ALL_APPS) {
|
||||
DeviceProfile grid = mActivity.getDeviceProfile();
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.allAppsIconTextSizePx);
|
||||
setCompoundDrawablePadding(grid.allAppsIconDrawablePaddingPx);
|
||||
defaultIconSize = grid.allAppsIconSizePx;
|
||||
mIgnorePaddingTouch = true;
|
||||
} else if (mDisplay == DISPLAY_FOLDER) {
|
||||
DeviceProfile grid = mActivity.getDeviceProfile();
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.folderChildTextSizePx);
|
||||
setCompoundDrawablePadding(grid.folderChildDrawablePaddingPx);
|
||||
defaultIconSize = grid.folderChildIconSizePx;
|
||||
mIgnorePaddingTouch = true;
|
||||
} else {
|
||||
// widget_selection or shortcut_popup
|
||||
defaultIconSize = mActivity.getDeviceProfile().iconSizePx;
|
||||
mIgnorePaddingTouch = false;
|
||||
defaultIconSize = grid.iconSizePx;
|
||||
}
|
||||
|
||||
mCenterVertically = a.getBoolean(R.styleable.BubbleTextView_centerVertically, false);
|
||||
@@ -190,7 +190,6 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
a.recycle();
|
||||
|
||||
mLongPressHelper = new CheckLongPressHelper(this);
|
||||
mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
|
||||
|
||||
mDotParams = new DotRenderer.DrawParams();
|
||||
|
||||
@@ -215,6 +214,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
cancelDotScaleAnim();
|
||||
mDotParams.scale = 0f;
|
||||
mForceHideDot = false;
|
||||
setBackground(null);
|
||||
}
|
||||
|
||||
private void cancelDotScaleAnim() {
|
||||
@@ -287,9 +287,8 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
}
|
||||
|
||||
private void applyIconAndLabel(ItemInfoWithIcon info) {
|
||||
FastBitmapDrawable iconDrawable = DrawableFactory.INSTANCE.get(getContext())
|
||||
.newIcon(getContext(), info);
|
||||
mDotParams.color = IconPalette.getMutedColor(info.iconColor, 0.54f);
|
||||
FastBitmapDrawable iconDrawable = newIcon(getContext(), info);
|
||||
mDotParams.color = IconPalette.getMutedColor(info.bitmap.color, 0.54f);
|
||||
|
||||
setIcon(iconDrawable);
|
||||
setText(info.title);
|
||||
@@ -331,42 +330,21 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
// ignore events if they happen in padding area
|
||||
if (event.getAction() == MotionEvent.ACTION_DOWN && mIgnorePaddingTouch
|
||||
if (event.getAction() == MotionEvent.ACTION_DOWN
|
||||
&& (event.getY() < getPaddingTop()
|
||||
|| event.getX() < getPaddingLeft()
|
||||
|| event.getY() > getHeight() - getPaddingBottom()
|
||||
|| event.getX() > getWidth() - getPaddingRight())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Call the superclass onTouchEvent first, because sometimes it changes the state to
|
||||
// isPressed() on an ACTION_UP
|
||||
boolean result = super.onTouchEvent(event);
|
||||
|
||||
// Check for a stylus button press, if it occurs cancel any long press checks.
|
||||
if (mStylusEventHelper.onMotionEvent(event)) {
|
||||
mLongPressHelper.cancelLongPress();
|
||||
result = true;
|
||||
if (isLongClickable()) {
|
||||
super.onTouchEvent(event);
|
||||
mLongPressHelper.onTouchEvent(event);
|
||||
// Keep receiving the rest of the events
|
||||
return true;
|
||||
} else {
|
||||
return super.onTouchEvent(event);
|
||||
}
|
||||
|
||||
switch (event.getAction()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
// If we're in a stylus button press, don't check for long press.
|
||||
if (!mStylusEventHelper.inStylusButtonPressed()) {
|
||||
mLongPressHelper.postCheckForLongPress();
|
||||
}
|
||||
break;
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
case MotionEvent.ACTION_UP:
|
||||
mLongPressHelper.cancelLongPress();
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
if (!Utilities.pointInView(this, event.getX(), event.getY(), mSlop)) {
|
||||
mLongPressHelper.cancelLongPress();
|
||||
}
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void setStayPressed(boolean stayPressed) {
|
||||
@@ -496,7 +474,8 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
// Text should be visible everywhere but the hotseat.
|
||||
Object tag = getParent() instanceof FolderIcon ? ((View) getParent()).getTag() : getTag();
|
||||
ItemInfo info = tag instanceof ItemInfo ? (ItemInfo) tag : null;
|
||||
return info == null || info.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT;
|
||||
return info == null || (info.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT
|
||||
&& info.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION);
|
||||
}
|
||||
|
||||
public void setTextVisibility(boolean visible) {
|
||||
@@ -528,7 +507,6 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
@Override
|
||||
public void cancelLongPress() {
|
||||
super.cancelLongPress();
|
||||
|
||||
mLongPressHelper.cancelLongPress();
|
||||
}
|
||||
|
||||
@@ -567,8 +545,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
preloadDrawable = (PreloadIconDrawable) mIcon;
|
||||
preloadDrawable.setLevel(progressLevel);
|
||||
} else {
|
||||
preloadDrawable = DrawableFactory.INSTANCE.get(getContext())
|
||||
.newPendingIcon(getContext(), info);
|
||||
preloadDrawable = newPendingIcon(getContext(), info);
|
||||
preloadDrawable.setLevel(progressLevel);
|
||||
setIcon(preloadDrawable);
|
||||
}
|
||||
@@ -665,7 +642,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
mDisableRelayout = true;
|
||||
|
||||
// Optimization: Starting in N, pre-uploads the bitmap to RenderThread.
|
||||
info.iconBitmap.prepareToDraw();
|
||||
info.bitmap.icon.prepareToDraw();
|
||||
|
||||
if (info instanceof AppInfo) {
|
||||
applyFromApplicationInfo((AppInfo) info);
|
||||
@@ -700,4 +677,80 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
|
||||
public int getIconSize() {
|
||||
return mIconSize;
|
||||
}
|
||||
|
||||
private void updateTranslation() {
|
||||
super.setTranslationX(mTranslationForReorderBounce.x + mTranslationForReorderPreview.x);
|
||||
super.setTranslationY(mTranslationForReorderBounce.y + mTranslationForReorderPreview.y);
|
||||
}
|
||||
|
||||
public void setReorderBounceOffset(float x, float y) {
|
||||
mTranslationForReorderBounce.set(x, y);
|
||||
updateTranslation();
|
||||
}
|
||||
|
||||
public void getReorderBounceOffset(PointF offset) {
|
||||
offset.set(mTranslationForReorderBounce);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReorderPreviewOffset(float x, float y) {
|
||||
mTranslationForReorderPreview.set(x, y);
|
||||
updateTranslation();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getReorderPreviewOffset(PointF offset) {
|
||||
offset.set(mTranslationForReorderPreview);
|
||||
}
|
||||
|
||||
public void setReorderBounceScale(float scale) {
|
||||
mScaleForReorderBounce = scale;
|
||||
super.setScaleX(scale);
|
||||
super.setScaleY(scale);
|
||||
}
|
||||
|
||||
public float getReorderBounceScale() {
|
||||
return mScaleForReorderBounce;
|
||||
}
|
||||
|
||||
public View getView() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getViewType() {
|
||||
return DRAGGABLE_ICON;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void getWorkspaceVisualDragBounds(Rect bounds) {
|
||||
DeviceProfile grid = mActivity.getDeviceProfile();
|
||||
BubbleTextView.getIconBounds(this, bounds, grid.iconSizePx);
|
||||
}
|
||||
|
||||
private int getIconSizeForDisplay(int display) {
|
||||
DeviceProfile grid = mActivity.getDeviceProfile();
|
||||
switch (display) {
|
||||
case DISPLAY_ALL_APPS:
|
||||
return grid.allAppsIconSizePx;
|
||||
case DISPLAY_WORKSPACE:
|
||||
case DISPLAY_FOLDER:
|
||||
default:
|
||||
return grid.iconSizePx;
|
||||
}
|
||||
}
|
||||
|
||||
public void getSourceVisualDragBounds(Rect bounds) {
|
||||
BubbleTextView.getIconBounds(this, bounds, getIconSizeForDisplay(mDisplay));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SafeCloseable prepareDrawDragView() {
|
||||
if (getIcon() instanceof FastBitmapDrawable) {
|
||||
FastBitmapDrawable icon = (FastBitmapDrawable) getIcon();
|
||||
icon.setScale(1f);
|
||||
}
|
||||
setForceHideDot(true);
|
||||
return () -> { };
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,7 @@ import com.android.launcher3.dragndrop.DragController;
|
||||
import com.android.launcher3.dragndrop.DragLayer;
|
||||
import com.android.launcher3.dragndrop.DragOptions;
|
||||
import com.android.launcher3.dragndrop.DragView;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
|
||||
import com.android.launcher3.util.Themes;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
@@ -155,7 +156,7 @@ public abstract class ButtonDropTarget extends TextView
|
||||
|
||||
@Override
|
||||
public final void onDragEnter(DragObject d) {
|
||||
if (!d.accessibleDrag && !mTextVisible) {
|
||||
if (!mAccessibleDrag && !mTextVisible) {
|
||||
// Show tooltip
|
||||
hideTooltip();
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.PointF;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
@@ -53,22 +54,18 @@ import androidx.core.view.ViewCompat;
|
||||
|
||||
import com.android.launcher3.LauncherSettings.Favorites;
|
||||
import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
|
||||
import com.android.launcher3.accessibility.FolderAccessibilityHelper;
|
||||
import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
|
||||
import com.android.launcher3.anim.Interpolators;
|
||||
import com.android.launcher3.anim.PropertyListBuilder;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.dragndrop.DraggableView;
|
||||
import com.android.launcher3.folder.PreviewBackground;
|
||||
import com.android.launcher3.graphics.DragPreviewProvider;
|
||||
import com.android.launcher3.graphics.RotationMode;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.util.CellAndSpan;
|
||||
import com.android.launcher3.util.GridOccupancy;
|
||||
import com.android.launcher3.util.ParcelableSparseArray;
|
||||
import com.android.launcher3.util.Themes;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
import com.android.launcher3.views.ActivityContext;
|
||||
import com.android.launcher3.views.Transposable;
|
||||
import com.android.launcher3.widget.LauncherAppWidgetHostView;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
@@ -78,10 +75,7 @@ import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Stack;
|
||||
|
||||
public class CellLayout extends ViewGroup implements Transposable {
|
||||
public static final int WORKSPACE_ACCESSIBILITY_DRAG = 2;
|
||||
public static final int FOLDER_ACCESSIBILITY_DRAG = 1;
|
||||
|
||||
public class CellLayout extends ViewGroup {
|
||||
private static final String TAG = "CellLayout";
|
||||
private static final boolean LOGD = false;
|
||||
|
||||
@@ -104,13 +98,19 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
// return an (x, y) value from helper functions. Do NOT use them to maintain other state.
|
||||
@Thunk final int[] mTmpPoint = new int[2];
|
||||
@Thunk final int[] mTempLocation = new int[2];
|
||||
final PointF mTmpPointF = new PointF();
|
||||
|
||||
// Used to visualize / debug the Grid of the CellLayout
|
||||
private static final boolean VISUALIZE_GRID = false;
|
||||
private Rect mVisualizeGridRect = new Rect();
|
||||
private Paint mVisualizeGridPaint = new Paint();
|
||||
|
||||
private GridOccupancy mOccupied;
|
||||
private GridOccupancy mTmpOccupied;
|
||||
|
||||
private OnTouchListener mInterceptTouchListener;
|
||||
|
||||
private final ArrayList<PreviewBackground> mFolderBackgrounds = new ArrayList<>();
|
||||
private final ArrayList<DelegatedCellDrawing> mDelegatedCellDrawings = new ArrayList<>();
|
||||
final PreviewBackground mFolderLeaveBehind = new PreviewBackground();
|
||||
|
||||
private static final int[] BACKGROUND_STATE_ACTIVE = new int[] { android.R.attr.state_active };
|
||||
@@ -136,7 +136,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
private final Paint mDragOutlinePaint = new Paint();
|
||||
|
||||
@Thunk final ArrayMap<LayoutParams, Animator> mReorderAnimators = new ArrayMap<>();
|
||||
@Thunk final ArrayMap<View, ReorderPreviewAnimation> mShakeAnimators = new ArrayMap<>();
|
||||
@Thunk final ArrayMap<Reorderable, ReorderPreviewAnimation> mShakeAnimators = new ArrayMap<>();
|
||||
|
||||
private boolean mItemPlacementDirty = false;
|
||||
|
||||
@@ -179,12 +179,10 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
|
||||
private final Rect mTempRect = new Rect();
|
||||
|
||||
private final static Paint sPaint = new Paint();
|
||||
private static final Paint sPaint = new Paint();
|
||||
|
||||
// Related to accessible drag and drop
|
||||
private DragAndDropAccessibilityDelegate mTouchHelper;
|
||||
private boolean mUseTouchHelper = false;
|
||||
private RotationMode mRotationMode = RotationMode.NORMAL;
|
||||
DragAndDropAccessibilityDelegate mTouchHelper;
|
||||
|
||||
public CellLayout(Context context) {
|
||||
this(context, null);
|
||||
@@ -206,7 +204,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
setClipToPadding(false);
|
||||
mActivity = ActivityContext.lookupContext(context);
|
||||
|
||||
DeviceProfile grid = mActivity.getWallpaperDeviceProfile();
|
||||
DeviceProfile grid = mActivity.getDeviceProfile();
|
||||
|
||||
mCellWidth = mCellHeight = -1;
|
||||
mFixedCellWidth = mFixedCellHeight = -1;
|
||||
@@ -219,8 +217,8 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
mPreviousReorderDirection[0] = INVALID_DIRECTION;
|
||||
mPreviousReorderDirection[1] = INVALID_DIRECTION;
|
||||
|
||||
mFolderLeaveBehind.delegateCellX = -1;
|
||||
mFolderLeaveBehind.delegateCellY = -1;
|
||||
mFolderLeaveBehind.mDelegateCellX = -1;
|
||||
mFolderLeaveBehind.mDelegateCellY = -1;
|
||||
|
||||
setAlwaysDrawnWithCacheEnabled(false);
|
||||
final Resources res = getResources();
|
||||
@@ -292,26 +290,18 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
addView(mShortcutsAndWidgets);
|
||||
}
|
||||
|
||||
public void enableAccessibleDrag(boolean enable, int dragType) {
|
||||
mUseTouchHelper = enable;
|
||||
if (!enable) {
|
||||
ViewCompat.setAccessibilityDelegate(this, null);
|
||||
setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
|
||||
getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
|
||||
setOnClickListener(null);
|
||||
} else {
|
||||
if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
|
||||
!(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
|
||||
mTouchHelper = new WorkspaceAccessibilityHelper(this);
|
||||
} else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
|
||||
!(mTouchHelper instanceof FolderAccessibilityHelper)) {
|
||||
mTouchHelper = new FolderAccessibilityHelper(this);
|
||||
}
|
||||
ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
|
||||
setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
|
||||
getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
|
||||
setOnClickListener(mTouchHelper);
|
||||
}
|
||||
/**
|
||||
* Sets or clears a delegate used for accessible drag and drop
|
||||
*/
|
||||
public void setDragAndDropAccessibilityDelegate(DragAndDropAccessibilityDelegate delegate) {
|
||||
setOnClickListener(delegate);
|
||||
ViewCompat.setAccessibilityDelegate(this, delegate);
|
||||
|
||||
mTouchHelper = delegate;
|
||||
int accessibilityFlag = mTouchHelper != null
|
||||
? IMPORTANT_FOR_ACCESSIBILITY_YES : IMPORTANT_FOR_ACCESSIBILITY_NO;
|
||||
setImportantForAccessibility(accessibilityFlag);
|
||||
getShortcutsAndWidgets().setImportantForAccessibility(accessibilityFlag);
|
||||
|
||||
// Invalidate the accessibility hierarchy
|
||||
if (getParent() != null) {
|
||||
@@ -320,28 +310,10 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
}
|
||||
}
|
||||
|
||||
public void setRotationMode(RotationMode mode) {
|
||||
if (mRotationMode != mode) {
|
||||
mRotationMode = mode;
|
||||
requestLayout();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RotationMode getRotationMode() {
|
||||
return mRotationMode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPadding(int left, int top, int right, int bottom) {
|
||||
mRotationMode.mapRect(left, top, right, bottom, mTempRect);
|
||||
super.setPadding(mTempRect.left, mTempRect.top, mTempRect.right, mTempRect.bottom);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean dispatchHoverEvent(MotionEvent event) {
|
||||
// Always attempt to dispatch hover events to accessibility first.
|
||||
if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
|
||||
if (mTouchHelper != null && mTouchHelper.dispatchHoverEvent(event)) {
|
||||
return true;
|
||||
}
|
||||
return super.dispatchHoverEvent(event);
|
||||
@@ -349,8 +321,8 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
|
||||
@Override
|
||||
public boolean onInterceptTouchEvent(MotionEvent ev) {
|
||||
if (mUseTouchHelper ||
|
||||
(mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
|
||||
if (mTouchHelper != null
|
||||
|| (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -466,49 +438,82 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < mFolderBackgrounds.size(); i++) {
|
||||
PreviewBackground bg = mFolderBackgrounds.get(i);
|
||||
cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
|
||||
for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
|
||||
DelegatedCellDrawing cellDrawing = mDelegatedCellDrawings.get(i);
|
||||
cellToPoint(cellDrawing.mDelegateCellX, cellDrawing.mDelegateCellY, mTempLocation);
|
||||
canvas.save();
|
||||
canvas.translate(mTempLocation[0], mTempLocation[1]);
|
||||
bg.drawBackground(canvas);
|
||||
if (!bg.isClipping) {
|
||||
bg.drawBackgroundStroke(canvas);
|
||||
}
|
||||
cellDrawing.drawUnderItem(canvas);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
if (mFolderLeaveBehind.delegateCellX >= 0 && mFolderLeaveBehind.delegateCellY >= 0) {
|
||||
cellToPoint(mFolderLeaveBehind.delegateCellX,
|
||||
mFolderLeaveBehind.delegateCellY, mTempLocation);
|
||||
if (mFolderLeaveBehind.mDelegateCellX >= 0 && mFolderLeaveBehind.mDelegateCellY >= 0) {
|
||||
cellToPoint(mFolderLeaveBehind.mDelegateCellX,
|
||||
mFolderLeaveBehind.mDelegateCellY, mTempLocation);
|
||||
canvas.save();
|
||||
canvas.translate(mTempLocation[0], mTempLocation[1]);
|
||||
mFolderLeaveBehind.drawLeaveBehind(canvas);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
if (VISUALIZE_GRID) {
|
||||
visualizeGrid(canvas);
|
||||
}
|
||||
}
|
||||
|
||||
protected void visualizeGrid(Canvas canvas) {
|
||||
mVisualizeGridRect.set(0, 0, mCellWidth, mCellHeight);
|
||||
mVisualizeGridPaint.setStrokeWidth(4);
|
||||
|
||||
for (int i = 0; i < mCountX; i++) {
|
||||
for (int j = 0; j < mCountY; j++) {
|
||||
canvas.save();
|
||||
|
||||
int transX = i * mCellWidth;
|
||||
int transY = j * mCellHeight;
|
||||
|
||||
canvas.translate(getPaddingLeft() + transX, getPaddingTop() + transY);
|
||||
|
||||
mVisualizeGridPaint.setStyle(Paint.Style.FILL);
|
||||
mVisualizeGridPaint.setColor(Color.argb(80, 255, 100, 100));
|
||||
|
||||
canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
|
||||
|
||||
mVisualizeGridPaint.setStyle(Paint.Style.STROKE);
|
||||
mVisualizeGridPaint.setColor(Color.argb(255, 255, 100, 100));
|
||||
|
||||
canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
|
||||
canvas.restore();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void dispatchDraw(Canvas canvas) {
|
||||
super.dispatchDraw(canvas);
|
||||
|
||||
for (int i = 0; i < mFolderBackgrounds.size(); i++) {
|
||||
PreviewBackground bg = mFolderBackgrounds.get(i);
|
||||
if (bg.isClipping) {
|
||||
cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
|
||||
canvas.save();
|
||||
canvas.translate(mTempLocation[0], mTempLocation[1]);
|
||||
bg.drawBackgroundStroke(canvas);
|
||||
canvas.restore();
|
||||
}
|
||||
for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
|
||||
DelegatedCellDrawing bg = mDelegatedCellDrawings.get(i);
|
||||
cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
|
||||
canvas.save();
|
||||
canvas.translate(mTempLocation[0], mTempLocation[1]);
|
||||
bg.drawOverItem(canvas);
|
||||
canvas.restore();
|
||||
}
|
||||
}
|
||||
|
||||
public void addFolderBackground(PreviewBackground bg) {
|
||||
mFolderBackgrounds.add(bg);
|
||||
/**
|
||||
* Add Delegated cell drawing
|
||||
*/
|
||||
public void addDelegatedCellDrawing(DelegatedCellDrawing bg) {
|
||||
mDelegatedCellDrawings.add(bg);
|
||||
}
|
||||
public void removeFolderBackground(PreviewBackground bg) {
|
||||
mFolderBackgrounds.remove(bg);
|
||||
|
||||
/**
|
||||
* Remove item from DelegatedCellDrawings
|
||||
*/
|
||||
public void removeDelegatedCellDrawing(DelegatedCellDrawing bg) {
|
||||
mDelegatedCellDrawings.remove(bg);
|
||||
}
|
||||
|
||||
public void setFolderLeaveBehindCell(int x, int y) {
|
||||
@@ -516,14 +521,14 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
mFolderLeaveBehind.setup(getContext(), mActivity, null,
|
||||
child.getMeasuredWidth(), child.getPaddingTop());
|
||||
|
||||
mFolderLeaveBehind.delegateCellX = x;
|
||||
mFolderLeaveBehind.delegateCellY = y;
|
||||
mFolderLeaveBehind.mDelegateCellX = x;
|
||||
mFolderLeaveBehind.mDelegateCellY = y;
|
||||
invalidate();
|
||||
}
|
||||
|
||||
public void clearFolderLeaveBehind() {
|
||||
mFolderLeaveBehind.delegateCellX = -1;
|
||||
mFolderLeaveBehind.delegateCellY = -1;
|
||||
mFolderLeaveBehind.mDelegateCellX = -1;
|
||||
mFolderLeaveBehind.mDelegateCellY = -1;
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@@ -536,7 +541,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
try {
|
||||
dispatchRestoreInstanceState(states);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
if (FeatureFlags.IS_DOGFOOD_BUILD) {
|
||||
if (FeatureFlags.IS_STUDIO_BUILD) {
|
||||
throw ex;
|
||||
}
|
||||
// Mismatched viewId / viewType preventing restore. Skip restore on production builds.
|
||||
@@ -771,13 +776,6 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
|
||||
int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
|
||||
|
||||
mShortcutsAndWidgets.setRotation(mRotationMode.surfaceRotation);
|
||||
if (mRotationMode.isTransposed) {
|
||||
int tmp = childWidthSize;
|
||||
childWidthSize = childHeightSize;
|
||||
childHeightSize = tmp;
|
||||
}
|
||||
|
||||
if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
|
||||
int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
|
||||
int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
|
||||
@@ -828,15 +826,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
right + mTempRect.right + getPaddingRight(),
|
||||
bottom + mTempRect.bottom + getPaddingBottom());
|
||||
|
||||
if (mRotationMode.isTransposed) {
|
||||
int halfW = mShortcutsAndWidgets.getMeasuredWidth() / 2;
|
||||
int halfH = mShortcutsAndWidgets.getMeasuredHeight() / 2;
|
||||
int cX = (left + right) / 2;
|
||||
int cY = (top + bottom) / 2;
|
||||
mShortcutsAndWidgets.layout(cX - halfW, cY - halfH, cX + halfW, cY + halfH);
|
||||
} else {
|
||||
mShortcutsAndWidgets.layout(left, top, right, bottom);
|
||||
}
|
||||
mShortcutsAndWidgets.layout(left, top, right, bottom);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -845,8 +835,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
* width in {@link DeviceProfile#calculateCellWidth(int, int)}.
|
||||
*/
|
||||
public int getUnusedHorizontalSpace() {
|
||||
return (mRotationMode.isTransposed ? getMeasuredHeight() : getMeasuredWidth())
|
||||
- getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
|
||||
return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
|
||||
}
|
||||
|
||||
public Drawable getScrimBackground() {
|
||||
@@ -870,9 +859,10 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
int delay, boolean permanent, boolean adjustOccupied) {
|
||||
ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
|
||||
|
||||
if (clc.indexOfChild(child) != -1) {
|
||||
if (clc.indexOfChild(child) != -1 && (child instanceof Reorderable)) {
|
||||
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
|
||||
final ItemInfo info = (ItemInfo) child.getTag();
|
||||
final Reorderable item = (Reorderable) child;
|
||||
|
||||
// We cancel any existing animations
|
||||
if (mReorderAnimators.containsKey(lp)) {
|
||||
@@ -880,13 +870,18 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
mReorderAnimators.remove(lp);
|
||||
}
|
||||
|
||||
final int oldX = lp.x;
|
||||
final int oldY = lp.y;
|
||||
|
||||
if (adjustOccupied) {
|
||||
GridOccupancy occupied = permanent ? mOccupied : mTmpOccupied;
|
||||
occupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, false);
|
||||
occupied.markCells(cellX, cellY, lp.cellHSpan, lp.cellVSpan, true);
|
||||
}
|
||||
|
||||
// Compute the new x and y position based on the new cellX and cellY
|
||||
// We leverage the actual layout logic in the layout params and hence need to modify
|
||||
// state and revert that state.
|
||||
final int oldX = lp.x;
|
||||
final int oldY = lp.y;
|
||||
lp.isLockedToGrid = true;
|
||||
if (permanent) {
|
||||
lp.cellX = info.cellX = cellX;
|
||||
@@ -896,15 +891,23 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
lp.tmpCellY = cellY;
|
||||
}
|
||||
clc.setupLp(child);
|
||||
lp.isLockedToGrid = false;
|
||||
final int newX = lp.x;
|
||||
final int newY = lp.y;
|
||||
|
||||
lp.x = oldX;
|
||||
lp.y = oldY;
|
||||
lp.isLockedToGrid = false;
|
||||
// End compute new x and y
|
||||
|
||||
item.getReorderPreviewOffset(mTmpPointF);
|
||||
final float initPreviewOffsetX = mTmpPointF.x;
|
||||
final float initPreviewOffsetY = mTmpPointF.y;
|
||||
final float finalPreviewOffsetX = newX - oldX;
|
||||
final float finalPreviewOffsetY = newY - oldY;
|
||||
|
||||
|
||||
// Exit early if we're not actually moving the view
|
||||
if (oldX == newX && oldY == newY) {
|
||||
if (finalPreviewOffsetX == 0 && finalPreviewOffsetY == 0
|
||||
&& initPreviewOffsetX == 0 && initPreviewOffsetY == 0) {
|
||||
lp.isLockedToGrid = true;
|
||||
return true;
|
||||
}
|
||||
@@ -917,9 +920,9 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
@Override
|
||||
public void onAnimationUpdate(ValueAnimator animation) {
|
||||
float r = (Float) animation.getAnimatedValue();
|
||||
lp.x = (int) ((1 - r) * oldX + r * newX);
|
||||
lp.y = (int) ((1 - r) * oldY + r * newY);
|
||||
child.requestLayout();
|
||||
float x = (1 - r) * initPreviewOffsetX + r * finalPreviewOffsetX;
|
||||
float y = (1 - r) * initPreviewOffsetY + r * finalPreviewOffsetY;
|
||||
item.setReorderPreviewOffset(x, y);
|
||||
}
|
||||
});
|
||||
va.addListener(new AnimatorListenerAdapter() {
|
||||
@@ -930,6 +933,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
// place just yet.
|
||||
if (!cancelled) {
|
||||
lp.isLockedToGrid = true;
|
||||
item.setReorderPreviewOffset(0, 0);
|
||||
child.requestLayout();
|
||||
}
|
||||
if (mReorderAnimators.containsKey(lp)) {
|
||||
@@ -947,8 +951,8 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
return false;
|
||||
}
|
||||
|
||||
void visualizeDropLocation(View v, DragPreviewProvider outlineProvider, int cellX, int cellY,
|
||||
int spanX, int spanY, boolean resize, DropTarget.DragObject dragObject) {
|
||||
void visualizeDropLocation(DraggableView v, DragPreviewProvider outlineProvider, int cellX, int
|
||||
cellY, int spanX, int spanY, boolean resize, DropTarget.DragObject dragObject) {
|
||||
final int oldDragCellX = mDragCell[0];
|
||||
final int oldDragCellY = mDragCell[1];
|
||||
|
||||
@@ -958,9 +962,6 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
|
||||
Bitmap dragOutline = outlineProvider.generatedDragOutline;
|
||||
if (cellX != oldDragCellX || cellY != oldDragCellY) {
|
||||
Point dragOffset = dragObject.dragView.getDragVisualizeOffset();
|
||||
Rect dragRegion = dragObject.dragView.getDragRegion();
|
||||
|
||||
mDragCell[0] = cellX;
|
||||
mDragCell[1] = cellY;
|
||||
|
||||
@@ -969,50 +970,32 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
|
||||
Rect r = mDragOutlines[mDragOutlineCurrent];
|
||||
|
||||
cellToRect(cellX, cellY, spanX, spanY, r);
|
||||
int left = r.left;
|
||||
int top = r.top;
|
||||
|
||||
int width = dragOutline.getWidth();
|
||||
int height = dragOutline.getHeight();
|
||||
|
||||
if (resize) {
|
||||
cellToRect(cellX, cellY, spanX, spanY, r);
|
||||
if (v instanceof LauncherAppWidgetHostView) {
|
||||
DeviceProfile profile = mActivity.getWallpaperDeviceProfile();
|
||||
Utilities.shrinkRect(r, profile.appWidgetScale.x, profile.appWidgetScale.y);
|
||||
}
|
||||
} else {
|
||||
// Find the top left corner of the rect the object will occupy
|
||||
final int[] topLeft = mTmpPoint;
|
||||
cellToPoint(cellX, cellY, topLeft);
|
||||
|
||||
int left = topLeft[0];
|
||||
int top = topLeft[1];
|
||||
|
||||
if (v != null && dragOffset == null) {
|
||||
// When drawing the drag outline, it did not account for margin offsets
|
||||
// added by the view's parent.
|
||||
MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
|
||||
left += lp.leftMargin;
|
||||
top += lp.topMargin;
|
||||
|
||||
// Offsets due to the size difference between the View and the dragOutline.
|
||||
// There is a size difference to account for the outer blur, which may lie
|
||||
// outside the bounds of the view.
|
||||
top += ((mCellHeight * spanY) - dragOutline.getHeight()) / 2;
|
||||
// We center about the x axis
|
||||
left += ((mCellWidth * spanX) - dragOutline.getWidth()) / 2;
|
||||
} else {
|
||||
if (dragOffset != null && dragRegion != null) {
|
||||
// Center the drag region *horizontally* in the cell and apply a drag
|
||||
// outline offset
|
||||
left += dragOffset.x + ((mCellWidth * spanX) - dragRegion.width()) / 2;
|
||||
int cHeight = getShortcutsAndWidgets().getCellContentHeight();
|
||||
int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
|
||||
top += dragOffset.y + cellPaddingY;
|
||||
} else {
|
||||
// Center the drag outline in the cell
|
||||
left += ((mCellWidth * spanX) - dragOutline.getWidth()) / 2;
|
||||
top += ((mCellHeight * spanY) - dragOutline.getHeight()) / 2;
|
||||
}
|
||||
}
|
||||
r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
|
||||
width = r.width();
|
||||
height = r.height();
|
||||
}
|
||||
|
||||
// Center horizontaly
|
||||
left += ((mCellWidth * spanX) - dragOutline.getWidth()) / 2;
|
||||
|
||||
if (v != null && v.getViewType() == DraggableView.DRAGGABLE_WIDGET) {
|
||||
// Center vertically
|
||||
top += ((mCellHeight * spanY) - dragOutline.getHeight()) / 2;
|
||||
} else if (v != null && v.getViewType() == DraggableView.DRAGGABLE_ICON) {
|
||||
int cHeight = getShortcutsAndWidgets().getCellContentHeight();
|
||||
int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
|
||||
top += cellPaddingY;
|
||||
}
|
||||
|
||||
r.set(left, top, left + width, top + height);
|
||||
|
||||
Utilities.scaleRectAboutCenter(r, mChildScale);
|
||||
mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
|
||||
mDragOutlineAnims[mDragOutlineCurrent].animateIn();
|
||||
@@ -1898,7 +1881,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
|
||||
// This method starts or changes the reorder preview animations
|
||||
private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
|
||||
View dragView, int delay, int mode) {
|
||||
View dragView, int mode) {
|
||||
int childCount = mShortcutsAndWidgets.getChildCount();
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
View child = mShortcutsAndWidgets.getChildAt(i);
|
||||
@@ -1907,10 +1890,11 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
|
||||
!= null && !solution.intersectingViews.contains(child);
|
||||
|
||||
|
||||
LayoutParams lp = (LayoutParams) child.getLayoutParams();
|
||||
if (c != null && !skip) {
|
||||
ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
|
||||
lp.cellY, c.cellX, c.cellY, c.spanX, c.spanY);
|
||||
if (c != null && !skip && (child instanceof Reorderable)) {
|
||||
ReorderPreviewAnimation rha = new ReorderPreviewAnimation((Reorderable) child,
|
||||
mode, lp.cellX, lp.cellY, c.cellX, c.cellY, c.spanX, c.spanY);
|
||||
rha.animate();
|
||||
}
|
||||
}
|
||||
@@ -1932,7 +1916,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
// Class which represents the reorder preview animations. These animations show that an item is
|
||||
// in a temporary state, and hint at where the item will return to.
|
||||
class ReorderPreviewAnimation {
|
||||
final View child;
|
||||
final Reorderable child;
|
||||
float finalDeltaX;
|
||||
float finalDeltaY;
|
||||
float initDeltaX;
|
||||
@@ -1952,8 +1936,8 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
float animationProgress = 0;
|
||||
ValueAnimator a;
|
||||
|
||||
public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
|
||||
int cellY1, int spanX, int spanY) {
|
||||
public ReorderPreviewAnimation(Reorderable child, int mode, int cellX0, int cellY0,
|
||||
int cellX1, int cellY1, int spanX, int spanY) {
|
||||
regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
|
||||
final int x0 = mTmpPoint[0];
|
||||
final int y0 = mTmpPoint[1];
|
||||
@@ -1965,61 +1949,60 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
|
||||
this.child = child;
|
||||
this.mode = mode;
|
||||
setInitialAnimationValues(false);
|
||||
finalScale = (mChildScale - (CHILD_DIVIDEND / child.getWidth())) * initScale;
|
||||
finalDeltaX = initDeltaX;
|
||||
finalDeltaY = initDeltaY;
|
||||
finalDeltaX = 0;
|
||||
finalDeltaY = 0;
|
||||
|
||||
child.getReorderBounceOffset(mTmpPointF);
|
||||
initDeltaX = mTmpPointF.x;
|
||||
initDeltaY = mTmpPointF.y;
|
||||
initScale = child.getReorderBounceScale();
|
||||
finalScale = mChildScale - (CHILD_DIVIDEND / child.getView().getWidth()) * initScale;
|
||||
|
||||
int dir = mode == MODE_HINT ? -1 : 1;
|
||||
if (dX == dY && dX == 0) {
|
||||
} else {
|
||||
if (dY == 0) {
|
||||
finalDeltaX += - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
|
||||
finalDeltaX = -dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
|
||||
} else if (dX == 0) {
|
||||
finalDeltaY += - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
|
||||
finalDeltaY = -dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
|
||||
} else {
|
||||
double angle = Math.atan( (float) (dY) / dX);
|
||||
finalDeltaX += (int) (- dir * Math.signum(dX) *
|
||||
Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
|
||||
finalDeltaY += (int) (- dir * Math.signum(dY) *
|
||||
Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
|
||||
finalDeltaX = (int) (-dir * Math.signum(dX)
|
||||
* Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
|
||||
finalDeltaY = (int) (-dir * Math.signum(dY)
|
||||
* Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setInitialAnimationValues(boolean restoreOriginalValues) {
|
||||
if (restoreOriginalValues) {
|
||||
if (child instanceof LauncherAppWidgetHostView) {
|
||||
LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) child;
|
||||
initScale = lahv.getScaleToFit();
|
||||
initDeltaX = lahv.getTranslationForCentering().x;
|
||||
initDeltaY = lahv.getTranslationForCentering().y;
|
||||
} else {
|
||||
initScale = mChildScale;
|
||||
initDeltaX = 0;
|
||||
initDeltaY = 0;
|
||||
}
|
||||
} else {
|
||||
initScale = child.getScaleX();
|
||||
initDeltaX = child.getTranslationX();
|
||||
initDeltaY = child.getTranslationY();
|
||||
}
|
||||
void setInitialAnimationValuesToBaseline() {
|
||||
initScale = mChildScale;
|
||||
initDeltaX = 0;
|
||||
initDeltaY = 0;
|
||||
}
|
||||
|
||||
void animate() {
|
||||
boolean noMovement = (finalDeltaX == initDeltaX) && (finalDeltaY == initDeltaY);
|
||||
boolean noMovement = (finalDeltaX == 0) && (finalDeltaY == 0);
|
||||
|
||||
if (mShakeAnimators.containsKey(child)) {
|
||||
ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
|
||||
oldAnimation.cancel();
|
||||
mShakeAnimators.remove(child);
|
||||
|
||||
if (noMovement) {
|
||||
completeAnimationImmediately();
|
||||
// A previous animation for this item exists, and no new animation will exist.
|
||||
// Finish the old animation smoothly.
|
||||
oldAnimation.finishAnimation();
|
||||
return;
|
||||
} else {
|
||||
// A previous animation for this item exists, and a new one will exist. Stop
|
||||
// the old animation in its tracks, and proceed with the new one.
|
||||
oldAnimation.cancel();
|
||||
}
|
||||
}
|
||||
if (noMovement) {
|
||||
return;
|
||||
}
|
||||
|
||||
ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS, 0, 1);
|
||||
a = va;
|
||||
|
||||
@@ -2036,7 +2019,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
va.addListener(new AnimatorListenerAdapter() {
|
||||
public void onAnimationRepeat(Animator animation) {
|
||||
// We make sure to end only after a full period
|
||||
setInitialAnimationValues(true);
|
||||
setInitialAnimationValuesToBaseline();
|
||||
repeating = true;
|
||||
}
|
||||
});
|
||||
@@ -2049,11 +2032,9 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
float r1 = (mode == MODE_HINT && repeating) ? 1.0f : animationProgress;
|
||||
float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
|
||||
float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
|
||||
child.setTranslationX(x);
|
||||
child.setTranslationY(y);
|
||||
child.setReorderBounceOffset(x, y);
|
||||
float s = animationProgress * finalScale + (1 - animationProgress) * initScale;
|
||||
child.setScaleX(s);
|
||||
child.setScaleY(s);
|
||||
child.setReorderBounceScale(s);
|
||||
}
|
||||
|
||||
private void cancel() {
|
||||
@@ -2062,27 +2043,27 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
}
|
||||
}
|
||||
|
||||
@Thunk void completeAnimationImmediately() {
|
||||
/**
|
||||
* Smoothly returns the item to its baseline position / scale
|
||||
*/
|
||||
@Thunk void finishAnimation() {
|
||||
if (a != null) {
|
||||
a.cancel();
|
||||
}
|
||||
|
||||
setInitialAnimationValues(true);
|
||||
a = new PropertyListBuilder()
|
||||
.scale(initScale)
|
||||
.translationX(initDeltaX)
|
||||
.translationY(initDeltaY)
|
||||
.build(child)
|
||||
.setDuration(REORDER_ANIMATION_DURATION);
|
||||
Launcher.cast(mActivity).getDragController().addFirstFrameAnimationHelper(a);
|
||||
setInitialAnimationValuesToBaseline();
|
||||
ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS,
|
||||
animationProgress, 0);
|
||||
a = va;
|
||||
a.setInterpolator(DEACCEL_1_5);
|
||||
a.setDuration(REORDER_ANIMATION_DURATION);
|
||||
a.start();
|
||||
}
|
||||
}
|
||||
|
||||
private void completeAndClearReorderPreviewAnimations() {
|
||||
for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
|
||||
a.completeAnimationImmediately();
|
||||
a.finishAnimation();
|
||||
}
|
||||
mShakeAnimators.clear();
|
||||
}
|
||||
@@ -2160,6 +2141,8 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
*/
|
||||
private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
|
||||
int spanY, View dragView, int[] resultDirection) {
|
||||
|
||||
//TODO(adamcohen) b/151776141 use the items visual center for the direction vector
|
||||
int[] targetDestination = new int[2];
|
||||
|
||||
findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
|
||||
@@ -2270,7 +2253,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
setItemPlacementDirty(false);
|
||||
} else {
|
||||
beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
|
||||
REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
|
||||
ReorderPreviewAnimation.MODE_PREVIEW);
|
||||
}
|
||||
mShortcutsAndWidgets.requestLayout();
|
||||
}
|
||||
@@ -2324,7 +2307,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
|
||||
if (mode == MODE_SHOW_REORDER_HINT) {
|
||||
if (finalSolution != null) {
|
||||
beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
|
||||
beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
|
||||
ReorderPreviewAnimation.MODE_HINT);
|
||||
result[0] = finalSolution.cellX;
|
||||
result[1] = finalSolution.cellY;
|
||||
@@ -2364,7 +2347,7 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
setItemPlacementDirty(false);
|
||||
} else {
|
||||
beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
|
||||
REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
|
||||
ReorderPreviewAnimation.MODE_PREVIEW);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -2743,6 +2726,24 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A Delegated cell Drawing for drawing on CellLayout
|
||||
*/
|
||||
public abstract static class DelegatedCellDrawing {
|
||||
public int mDelegateCellX;
|
||||
public int mDelegateCellY;
|
||||
|
||||
/**
|
||||
* Draw under CellLayout
|
||||
*/
|
||||
public abstract void drawUnderItem(Canvas canvas);
|
||||
|
||||
/**
|
||||
* Draw over CellLayout
|
||||
*/
|
||||
public abstract void drawOverItem(Canvas canvas);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
|
||||
* if necessary).
|
||||
@@ -2763,6 +2764,36 @@ public class CellLayout extends ViewGroup implements Transposable {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds solution to accept hotseat migration to cell layout. commits solution if commitConfig
|
||||
*/
|
||||
public boolean makeSpaceForHotseatMigration(boolean commitConfig) {
|
||||
int[] cellPoint = new int[2];
|
||||
int[] directionVector = new int[]{0, -1};
|
||||
cellToPoint(0, mCountY, cellPoint);
|
||||
ItemConfiguration configuration = new ItemConfiguration();
|
||||
if (findReorderSolution(cellPoint[0], cellPoint[1], mCountX, 1, mCountX, 1,
|
||||
directionVector, null, false, configuration).isSolution) {
|
||||
if (commitConfig) {
|
||||
copySolutionToTempState(configuration, null);
|
||||
commitTempPlacement();
|
||||
// undo marking cells occupied since there is actually nothing being placed yet.
|
||||
mOccupied.markCells(0, mCountY - 1, mCountX, 1, false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns a copy of cell layout's grid occupancy
|
||||
*/
|
||||
public GridOccupancy cloneGridOccupancy() {
|
||||
GridOccupancy occupancy = new GridOccupancy(mCountX, mCountY);
|
||||
mOccupied.copyTo(occupancy);
|
||||
return occupancy;
|
||||
}
|
||||
|
||||
public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
|
||||
return mOccupied.isRegionVacant(x, y, spanX, spanY);
|
||||
}
|
||||
|
||||
@@ -16,46 +16,68 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
|
||||
import com.android.launcher3.util.Thunk;
|
||||
|
||||
/**
|
||||
* Utility class to handle tripper long press on a view with custom timeout and stylus event
|
||||
*/
|
||||
public class CheckLongPressHelper {
|
||||
|
||||
public static final float DEFAULT_LONG_PRESS_TIMEOUT_FACTOR = 0.75f;
|
||||
|
||||
@Thunk View mView;
|
||||
@Thunk View.OnLongClickListener mListener;
|
||||
@Thunk boolean mHasPerformedLongPress;
|
||||
private float mLongPressTimeoutFactor = DEFAULT_LONG_PRESS_TIMEOUT_FACTOR;
|
||||
private CheckForLongPress mPendingCheckForLongPress;
|
||||
private final View mView;
|
||||
private final View.OnLongClickListener mListener;
|
||||
private final float mSlop;
|
||||
|
||||
class CheckForLongPress implements Runnable {
|
||||
public void run() {
|
||||
if ((mView.getParent() != null) && mView.hasWindowFocus()
|
||||
&& !mHasPerformedLongPress) {
|
||||
boolean handled;
|
||||
if (mListener != null) {
|
||||
handled = mListener.onLongClick(mView);
|
||||
} else {
|
||||
handled = mView.performLongClick();
|
||||
}
|
||||
if (handled) {
|
||||
mView.setPressed(false);
|
||||
mHasPerformedLongPress = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private float mLongPressTimeoutFactor = DEFAULT_LONG_PRESS_TIMEOUT_FACTOR;
|
||||
|
||||
private boolean mHasPerformedLongPress;
|
||||
|
||||
private Runnable mPendingCheckForLongPress;
|
||||
|
||||
public CheckLongPressHelper(View v) {
|
||||
mView = v;
|
||||
this(v, null);
|
||||
}
|
||||
|
||||
public CheckLongPressHelper(View v, View.OnLongClickListener listener) {
|
||||
mView = v;
|
||||
mListener = listener;
|
||||
mSlop = ViewConfiguration.get(mView.getContext()).getScaledTouchSlop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the touch event on a view
|
||||
*
|
||||
* @see View#onTouchEvent(MotionEvent)
|
||||
*/
|
||||
public void onTouchEvent(MotionEvent ev) {
|
||||
switch (ev.getAction()) {
|
||||
case MotionEvent.ACTION_DOWN: {
|
||||
// Just in case the previous long press hasn't been cleared, we make sure to
|
||||
// start fresh on touch down.
|
||||
cancelLongPress();
|
||||
|
||||
postCheckForLongPress();
|
||||
if (isStylusButtonPressed(ev)) {
|
||||
triggerLongPress();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
case MotionEvent.ACTION_UP:
|
||||
cancelLongPress();
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
if (!Utilities.pointInView(mView, ev.getX(), ev.getY(), mSlop)) {
|
||||
cancelLongPress();
|
||||
} else if (mPendingCheckForLongPress != null && isStylusButtonPressed(ev)) {
|
||||
// Only trigger long press if it has not been cancelled before
|
||||
triggerLongPress();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,25 +87,67 @@ public class CheckLongPressHelper {
|
||||
mLongPressTimeoutFactor = longPressTimeoutFactor;
|
||||
}
|
||||
|
||||
public void postCheckForLongPress() {
|
||||
private void postCheckForLongPress() {
|
||||
mHasPerformedLongPress = false;
|
||||
|
||||
if (mPendingCheckForLongPress == null) {
|
||||
mPendingCheckForLongPress = new CheckForLongPress();
|
||||
mPendingCheckForLongPress = this::triggerLongPress;
|
||||
}
|
||||
mView.postDelayed(mPendingCheckForLongPress,
|
||||
(long) (ViewConfiguration.getLongPressTimeout() * mLongPressTimeoutFactor));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels any pending long press
|
||||
*/
|
||||
public void cancelLongPress() {
|
||||
mHasPerformedLongPress = false;
|
||||
clearCallbacks();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if long press has been performed in the current touch gesture
|
||||
*/
|
||||
public boolean hasPerformedLongPress() {
|
||||
return mHasPerformedLongPress;
|
||||
}
|
||||
|
||||
private void triggerLongPress() {
|
||||
if ((mView.getParent() != null)
|
||||
&& mView.hasWindowFocus()
|
||||
&& (!mView.isPressed() || mListener == null)
|
||||
&& !mHasPerformedLongPress) {
|
||||
boolean handled;
|
||||
if (mListener != null) {
|
||||
handled = mListener.onLongClick(mView);
|
||||
} else {
|
||||
handled = mView.performLongClick();
|
||||
}
|
||||
if (handled) {
|
||||
mView.setPressed(false);
|
||||
mHasPerformedLongPress = true;
|
||||
}
|
||||
clearCallbacks();
|
||||
}
|
||||
}
|
||||
|
||||
private void clearCallbacks() {
|
||||
if (mPendingCheckForLongPress != null) {
|
||||
mView.removeCallbacks(mPendingCheckForLongPress);
|
||||
mPendingCheckForLongPress = null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasPerformedLongPress() {
|
||||
return mHasPerformedLongPress;
|
||||
|
||||
/**
|
||||
* Identifies if the provided {@link MotionEvent} is a stylus with the primary stylus button
|
||||
* pressed.
|
||||
*
|
||||
* @param event The event to check.
|
||||
* @return Whether a stylus button press occurred.
|
||||
*/
|
||||
private static boolean isStylusButtonPressed(MotionEvent event) {
|
||||
return event.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS
|
||||
&& event.isButtonPressed(MotionEvent.BUTTON_SECONDARY);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROPPED_ON_CANCEL;
|
||||
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROPPED_ON_REMOVE;
|
||||
import static com.android.launcher3.userevent.nano.LauncherLogProto.Action.Touch.TAP;
|
||||
import static com.android.launcher3.userevent.nano.LauncherLogProto.ControlType.UNDO;
|
||||
|
||||
@@ -27,13 +29,20 @@ import android.view.View;
|
||||
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
|
||||
import com.android.launcher3.dragndrop.DragOptions;
|
||||
import com.android.launcher3.logging.LoggerUtils;
|
||||
import com.android.launcher3.logging.StatsLogManager;
|
||||
import com.android.launcher3.model.ModelWriter;
|
||||
import com.android.launcher3.model.data.FolderInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
|
||||
import com.android.launcher3.views.Snackbar;
|
||||
|
||||
public class DeleteDropTarget extends ButtonDropTarget {
|
||||
|
||||
private final StatsLogManager mStatsLogManager;
|
||||
|
||||
private int mControlType = ControlType.DEFAULT_CONTROLTYPE;
|
||||
|
||||
public DeleteDropTarget(Context context, AttributeSet attrs) {
|
||||
@@ -42,6 +51,7 @@ public class DeleteDropTarget extends ButtonDropTarget {
|
||||
|
||||
public DeleteDropTarget(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
this.mStatsLogManager = StatsLogManager.newInstance(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -67,7 +77,7 @@ public class DeleteDropTarget extends ButtonDropTarget {
|
||||
public boolean supportsAccessibilityDrop(ItemInfo info, View view) {
|
||||
if (info instanceof WorkspaceItemInfo) {
|
||||
// Support the action unless the item is in a context menu.
|
||||
return info.screenId >= 0;
|
||||
return canRemove(info);
|
||||
}
|
||||
|
||||
return (info instanceof LauncherAppWidgetInfo)
|
||||
@@ -113,8 +123,12 @@ public class DeleteDropTarget extends ButtonDropTarget {
|
||||
public void onDrop(DragObject d, DragOptions options) {
|
||||
if (canRemove(d.dragInfo)) {
|
||||
mLauncher.getModelWriter().prepareToUndoDelete();
|
||||
d.dragInfo.container = NO_ID;
|
||||
}
|
||||
super.onDrop(d, options);
|
||||
mStatsLogManager.logger().withInstanceId(d.logInstanceId)
|
||||
.log(mControlType == ControlType.REMOVE_TARGET ? LAUNCHER_ITEM_DROPPED_ON_REMOVE
|
||||
: LAUNCHER_ITEM_DROPPED_ON_CANCEL);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -125,7 +139,8 @@ public class DeleteDropTarget extends ButtonDropTarget {
|
||||
onAccessibilityDrop(null, item);
|
||||
ModelWriter modelWriter = mLauncher.getModelWriter();
|
||||
Runnable onUndoClicked = () -> {
|
||||
modelWriter.abortDelete(itemPage);
|
||||
mLauncher.setPageToBindSynchronously(itemPage);
|
||||
modelWriter.abortDelete();
|
||||
mLauncher.getUserEventDispatcher().logActionOnControl(TAP, UNDO);
|
||||
};
|
||||
Snackbar.show(mLauncher, R.string.item_removed, R.string.undo,
|
||||
|
||||
@@ -22,22 +22,23 @@ import android.content.res.Resources;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.PointF;
|
||||
import android.graphics.Rect;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.Surface;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.CellLayout.ContainerType;
|
||||
import com.android.launcher3.graphics.IconShape;
|
||||
import com.android.launcher3.icons.DotRenderer;
|
||||
import com.android.launcher3.icons.IconNormalizer;
|
||||
import com.android.launcher3.util.DefaultDisplay;
|
||||
import com.android.launcher3.util.WindowBounds;
|
||||
|
||||
public class DeviceProfile {
|
||||
|
||||
private static final float TABLET_MIN_DPS = 600;
|
||||
private static final float LARGE_TABLET_MIN_DPS = 720;
|
||||
|
||||
|
||||
public final InvariantDeviceProfile inv;
|
||||
// IDP with no grid override values.
|
||||
@Nullable private final InvariantDeviceProfile originalIdp;
|
||||
private final DefaultDisplay.Info mInfo;
|
||||
|
||||
// Device properties
|
||||
public final boolean isTablet;
|
||||
@@ -49,6 +50,8 @@ public class DeviceProfile {
|
||||
public final boolean isLandscape;
|
||||
public final boolean isMultiWindowMode;
|
||||
|
||||
public final int windowX;
|
||||
public final int windowY;
|
||||
public final int widthPx;
|
||||
public final int heightPx;
|
||||
public final int availableWidthPx;
|
||||
@@ -76,9 +79,9 @@ public class DeviceProfile {
|
||||
public float workspaceSpringLoadShrinkFactor;
|
||||
public final int workspaceSpringLoadedBottomSpace;
|
||||
|
||||
// Drag handle
|
||||
public final int verticalDragHandleSizePx;
|
||||
private final int verticalDragHandleOverlapWorkspace;
|
||||
// Workspace page indicator
|
||||
public final int workspacePageIndicatorHeight;
|
||||
private final int mWorkspacePageIndicatorOverlapWorkspace;
|
||||
|
||||
// Workspace icons
|
||||
public int iconSizePx;
|
||||
@@ -137,14 +140,16 @@ public class DeviceProfile {
|
||||
public DotRenderer mDotRendererWorkSpace;
|
||||
public DotRenderer mDotRendererAllApps;
|
||||
|
||||
public DeviceProfile(Context context, InvariantDeviceProfile inv,
|
||||
InvariantDeviceProfile originalIDP, Point minSize, Point maxSize,
|
||||
int width, int height, boolean isLandscape, boolean isMultiWindowMode) {
|
||||
DeviceProfile(Context context, InvariantDeviceProfile inv, DefaultDisplay.Info info,
|
||||
Point minSize, Point maxSize, int width, int height, boolean isLandscape,
|
||||
boolean isMultiWindowMode, boolean transposeLayoutWithOrientation,
|
||||
Point windowPosition) {
|
||||
|
||||
this.inv = inv;
|
||||
this.originalIdp = inv;
|
||||
this.isLandscape = isLandscape;
|
||||
this.isMultiWindowMode = isMultiWindowMode;
|
||||
windowX = windowPosition.x;
|
||||
windowY = windowPosition.y;
|
||||
|
||||
// Determine sizes.
|
||||
widthPx = width;
|
||||
@@ -157,24 +162,24 @@ public class DeviceProfile {
|
||||
availableHeightPx = maxSize.y;
|
||||
}
|
||||
|
||||
Resources res = context.getResources();
|
||||
DisplayMetrics dm = res.getDisplayMetrics();
|
||||
mInfo = info;
|
||||
|
||||
// Constants from resources
|
||||
isTablet = res.getBoolean(R.bool.is_tablet);
|
||||
isLargeTablet = res.getBoolean(R.bool.is_large_tablet);
|
||||
float swDPs = Utilities.dpiFromPx(
|
||||
Math.min(info.smallestSize.x, info.smallestSize.y), info.metrics);
|
||||
isTablet = swDPs >= TABLET_MIN_DPS;
|
||||
isLargeTablet = swDPs >= LARGE_TABLET_MIN_DPS;
|
||||
isPhone = !isTablet && !isLargeTablet;
|
||||
aspectRatio = ((float) Math.max(widthPx, heightPx)) / Math.min(widthPx, heightPx);
|
||||
boolean isTallDevice = Float.compare(aspectRatio, TALL_DEVICE_ASPECT_RATIO_THRESHOLD) >= 0;
|
||||
|
||||
// Some more constants
|
||||
transposeLayoutWithOrientation =
|
||||
res.getBoolean(R.bool.hotseat_transpose_layout_with_orientation);
|
||||
this.transposeLayoutWithOrientation = transposeLayoutWithOrientation;
|
||||
|
||||
context = getContext(context, isVerticalBarLayout()
|
||||
context = getContext(context, info, isVerticalBarLayout()
|
||||
? Configuration.ORIENTATION_LANDSCAPE
|
||||
: Configuration.ORIENTATION_PORTRAIT);
|
||||
res = context.getResources();
|
||||
final Resources res = context.getResources();
|
||||
|
||||
edgeMarginPx = res.getDimensionPixelSize(R.dimen.dynamic_grid_edge_margin);
|
||||
desiredWorkspaceLeftRightMarginPx = isVerticalBarLayout() ? 0 : edgeMarginPx;
|
||||
@@ -190,10 +195,10 @@ public class DeviceProfile {
|
||||
cellLayoutBottomPaddingPx = 0;
|
||||
}
|
||||
|
||||
verticalDragHandleSizePx = res.getDimensionPixelSize(
|
||||
R.dimen.vertical_drag_handle_size);
|
||||
verticalDragHandleOverlapWorkspace =
|
||||
res.getDimensionPixelSize(R.dimen.vertical_drag_handle_overlap_workspace);
|
||||
workspacePageIndicatorHeight = res.getDimensionPixelSize(
|
||||
R.dimen.workspace_page_indicator_height);
|
||||
mWorkspacePageIndicatorOverlapWorkspace =
|
||||
res.getDimensionPixelSize(R.dimen.workspace_page_indicator_overlap_workspace);
|
||||
|
||||
iconDrawablePaddingOriginalPx =
|
||||
res.getDimensionPixelSize(R.dimen.dynamic_grid_icon_drawable_padding);
|
||||
@@ -211,14 +216,15 @@ public class DeviceProfile {
|
||||
hotseatBarSidePaddingEndPx =
|
||||
res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_side_padding);
|
||||
// Add a bit of space between nav bar and hotseat in vertical bar layout.
|
||||
hotseatBarSidePaddingStartPx = isVerticalBarLayout() ? verticalDragHandleSizePx : 0;
|
||||
hotseatBarSizePx = ResourceUtils.pxFromDp(inv.iconSize, dm) + (isVerticalBarLayout()
|
||||
hotseatBarSidePaddingStartPx = isVerticalBarLayout() ? workspacePageIndicatorHeight : 0;
|
||||
hotseatBarSizePx = ResourceUtils.pxFromDp(inv.iconSize, mInfo.metrics)
|
||||
+ (isVerticalBarLayout()
|
||||
? (hotseatBarSidePaddingStartPx + hotseatBarSidePaddingEndPx)
|
||||
: (res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_extra_vertical_size)
|
||||
+ hotseatBarTopPaddingPx + hotseatBarBottomPaddingPx));
|
||||
|
||||
// Calculate all of the remaining variables.
|
||||
updateAvailableDimensions(dm, res);
|
||||
updateAvailableDimensions(res);
|
||||
|
||||
// Now that we have all of the variables calculated, we can tune certain sizes.
|
||||
if (!isVerticalBarLayout() && isPhone && isTallDevice) {
|
||||
@@ -227,25 +233,12 @@ public class DeviceProfile {
|
||||
// in portrait mode closer together by adding more height to the hotseat.
|
||||
// Note: This calculation was created after noticing a pattern in the design spec.
|
||||
int extraSpace = getCellSize().y - iconSizePx - iconDrawablePaddingPx * 2
|
||||
- verticalDragHandleSizePx;
|
||||
- workspacePageIndicatorHeight;
|
||||
hotseatBarSizePx += extraSpace;
|
||||
hotseatBarBottomPaddingPx += extraSpace;
|
||||
|
||||
// Recalculate the available dimensions using the new hotseat size.
|
||||
updateAvailableDimensions(dm, res);
|
||||
}
|
||||
|
||||
if (originalIDP != null) {
|
||||
// Grid size change should not affect All Apps UI, so we use the original profile
|
||||
// measurements here.
|
||||
DeviceProfile originalProfile = isLandscape
|
||||
? originalIDP.landscapeProfile
|
||||
: originalIDP.portraitProfile;
|
||||
allAppsIconSizePx = originalProfile.iconSizePx;
|
||||
allAppsIconTextSizePx = originalProfile.iconTextSizePx;
|
||||
allAppsCellHeightPx = originalProfile.allAppsCellHeightPx;
|
||||
allAppsIconDrawablePaddingPx = originalProfile.iconDrawablePaddingOriginalPx;
|
||||
allAppsCellWidthPx = allAppsIconSizePx + allAppsIconDrawablePaddingPx;
|
||||
updateAvailableDimensions(res);
|
||||
}
|
||||
updateWorkspacePadding();
|
||||
|
||||
@@ -257,22 +250,34 @@ public class DeviceProfile {
|
||||
IconShape.DEFAULT_PATH_SIZE);
|
||||
}
|
||||
|
||||
public DeviceProfile copy(Context context) {
|
||||
public Builder toBuilder(Context context) {
|
||||
Point size = new Point(availableWidthPx, availableHeightPx);
|
||||
return new DeviceProfile(context, inv, originalIdp, size, size, widthPx, heightPx,
|
||||
isLandscape, isMultiWindowMode);
|
||||
return new Builder(context, inv, mInfo)
|
||||
.setSizeRange(size, size)
|
||||
.setSize(widthPx, heightPx)
|
||||
.setWindowPosition(windowX, windowY)
|
||||
.setMultiWindowMode(isMultiWindowMode);
|
||||
}
|
||||
|
||||
public DeviceProfile getMultiWindowProfile(Context context, Point mwSize) {
|
||||
public DeviceProfile copy(Context context) {
|
||||
return toBuilder(context).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO: Move this to the builder as part of setMultiWindowMode
|
||||
*/
|
||||
public DeviceProfile getMultiWindowProfile(Context context, WindowBounds windowBounds) {
|
||||
// We take the minimum sizes of this profile and it's multi-window variant to ensure that
|
||||
// the system decor is always excluded.
|
||||
mwSize.set(Math.min(availableWidthPx, mwSize.x), Math.min(availableHeightPx, mwSize.y));
|
||||
Point mwSize = new Point(Math.min(availableWidthPx, windowBounds.availableSize.x),
|
||||
Math.min(availableHeightPx, windowBounds.availableSize.y));
|
||||
|
||||
// In multi-window mode, we can have widthPx = availableWidthPx
|
||||
// and heightPx = availableHeightPx because Launcher uses the InvariantDeviceProfiles'
|
||||
// widthPx and heightPx values where it's needed.
|
||||
DeviceProfile profile = new DeviceProfile(context, inv, originalIdp, mwSize, mwSize,
|
||||
mwSize.x, mwSize.y, isLandscape, true);
|
||||
DeviceProfile profile = toBuilder(context)
|
||||
.setSizeRange(mwSize, mwSize)
|
||||
.setSize(windowBounds.bounds.width(), windowBounds.bounds.height())
|
||||
.setWindowPosition(windowBounds.bounds.left, windowBounds.bounds.top)
|
||||
.setMultiWindowMode(true)
|
||||
.build();
|
||||
|
||||
// If there isn't enough vertical cell padding with the labels displayed, hide the labels.
|
||||
float workspaceCellPaddingY = profile.getCellSize().y - profile.iconSizePx
|
||||
@@ -292,7 +297,7 @@ public class DeviceProfile {
|
||||
}
|
||||
|
||||
/**
|
||||
* Inverse of {@link #getMultiWindowProfile(Context, Point)}
|
||||
* Inverse of {@link #getMultiWindowProfile(Context, WindowBounds)}
|
||||
* @return device profile corresponding to the current orientation in non multi-window mode.
|
||||
*/
|
||||
public DeviceProfile getFullScreenProfile() {
|
||||
@@ -307,27 +312,30 @@ public class DeviceProfile {
|
||||
iconTextSizePx = 0;
|
||||
iconDrawablePaddingPx = 0;
|
||||
cellHeightPx = iconSizePx;
|
||||
autoResizeAllAppsCells();
|
||||
}
|
||||
|
||||
// In normal cases, All Apps cell height should equal the Workspace cell height.
|
||||
// Since we are removing labels from the Workspace, we need to manually compute the
|
||||
// All Apps cell height.
|
||||
/**
|
||||
* Re-computes the all-apps cell size to be independent of workspace
|
||||
*/
|
||||
public void autoResizeAllAppsCells() {
|
||||
int topBottomPadding = allAppsIconDrawablePaddingPx * (isVerticalBarLayout() ? 2 : 1);
|
||||
allAppsCellHeightPx = allAppsIconSizePx + allAppsIconDrawablePaddingPx
|
||||
+ Utilities.calculateTextHeight(allAppsIconTextSizePx)
|
||||
+ topBottomPadding * 2;
|
||||
}
|
||||
|
||||
private void updateAvailableDimensions(DisplayMetrics dm, Resources res) {
|
||||
updateIconSize(1f, res, dm);
|
||||
private void updateAvailableDimensions(Resources res) {
|
||||
updateIconSize(1f, res);
|
||||
|
||||
// Check to see if the icons fit within the available height. If not, then scale down.
|
||||
float usedHeight = (cellHeightPx * inv.numRows);
|
||||
int maxHeight = (availableHeightPx - getTotalWorkspacePadding().y);
|
||||
if (usedHeight > maxHeight) {
|
||||
float scale = maxHeight / usedHeight;
|
||||
updateIconSize(scale, res, dm);
|
||||
updateIconSize(scale, res);
|
||||
}
|
||||
updateAvailableFolderCellDimensions(dm, res);
|
||||
updateAvailableFolderCellDimensions(res);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -335,12 +343,13 @@ public class DeviceProfile {
|
||||
* iconTextSizePx, iconDrawablePaddingPx, cellWidth/Height, allApps* variants,
|
||||
* hotseat sizes, workspaceSpringLoadedShrinkFactor, folderIconSizePx, and folderIconOffsetYPx.
|
||||
*/
|
||||
private void updateIconSize(float scale, Resources res, DisplayMetrics dm) {
|
||||
private void updateIconSize(float scale, Resources res) {
|
||||
// Workspace
|
||||
final boolean isVerticalLayout = isVerticalBarLayout();
|
||||
float invIconSizeDp = isVerticalLayout ? inv.landscapeIconSize : inv.iconSize;
|
||||
iconSizePx = Math.max(1, (int) (ResourceUtils.pxFromDp(invIconSizeDp, dm) * scale));
|
||||
iconTextSizePx = (int) (Utilities.pxFromSp(inv.iconTextSize, dm) * scale);
|
||||
iconSizePx = Math.max(1, (int) (ResourceUtils.pxFromDp(invIconSizeDp, mInfo.metrics)
|
||||
* scale));
|
||||
iconTextSizePx = (int) (Utilities.pxFromSp(inv.iconTextSize, mInfo.metrics) * scale);
|
||||
iconDrawablePaddingPx = (int) (iconDrawablePaddingOriginalPx * scale);
|
||||
|
||||
cellHeightPx = iconSizePx + iconDrawablePaddingPx
|
||||
@@ -356,10 +365,20 @@ public class DeviceProfile {
|
||||
}
|
||||
cellWidthPx = iconSizePx + iconDrawablePaddingPx;
|
||||
|
||||
allAppsIconSizePx = iconSizePx;
|
||||
allAppsIconTextSizePx = iconTextSizePx;
|
||||
allAppsIconDrawablePaddingPx = iconDrawablePaddingPx;
|
||||
allAppsCellHeightPx = getCellSize().y;
|
||||
// All apps
|
||||
if (allAppsHasDifferentNumColumns()) {
|
||||
allAppsIconSizePx = ResourceUtils.pxFromDp(inv.allAppsIconSize, mInfo.metrics);
|
||||
allAppsIconTextSizePx = Utilities.pxFromSp(inv.allAppsIconTextSize, mInfo.metrics);
|
||||
allAppsIconDrawablePaddingPx = iconDrawablePaddingOriginalPx;
|
||||
// We use 4 below to ensure labels are closer to their corresponding icon.
|
||||
allAppsCellHeightPx = Math.round(allAppsIconSizePx + allAppsIconTextSizePx
|
||||
+ (4 * allAppsIconDrawablePaddingPx));
|
||||
} else {
|
||||
allAppsIconSizePx = iconSizePx;
|
||||
allAppsIconTextSizePx = iconTextSizePx;
|
||||
allAppsIconDrawablePaddingPx = iconDrawablePaddingPx;
|
||||
allAppsCellHeightPx = getCellSize().y;
|
||||
}
|
||||
allAppsCellWidthPx = allAppsIconSizePx + allAppsIconDrawablePaddingPx;
|
||||
|
||||
if (isVerticalBarLayout()) {
|
||||
@@ -376,7 +395,7 @@ public class DeviceProfile {
|
||||
|
||||
if (!isVerticalLayout) {
|
||||
int expectedWorkspaceHeight = availableHeightPx - hotseatBarSizePx
|
||||
- verticalDragHandleSizePx - edgeMarginPx;
|
||||
- workspacePageIndicatorHeight - edgeMarginPx;
|
||||
float minRequiredHeight = dropTargetBarSizePx + workspaceSpringLoadedBottomSpace;
|
||||
workspaceSpringLoadShrinkFactor = Math.min(
|
||||
res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f,
|
||||
@@ -391,12 +410,12 @@ public class DeviceProfile {
|
||||
folderIconOffsetYPx = (iconSizePx - folderIconSizePx) / 2;
|
||||
}
|
||||
|
||||
private void updateAvailableFolderCellDimensions(DisplayMetrics dm, Resources res) {
|
||||
private void updateAvailableFolderCellDimensions(Resources res) {
|
||||
int folderBottomPanelSize = res.getDimensionPixelSize(R.dimen.folder_label_padding_top)
|
||||
+ res.getDimensionPixelSize(R.dimen.folder_label_padding_bottom)
|
||||
+ Utilities.calculateTextHeight(res.getDimension(R.dimen.folder_label_text_size));
|
||||
|
||||
updateFolderCellSize(1f, dm, res);
|
||||
updateFolderCellSize(1f, res);
|
||||
|
||||
// Don't let the folder get too close to the edges of the screen.
|
||||
int folderMargin = edgeMarginPx * 2;
|
||||
@@ -415,12 +434,12 @@ public class DeviceProfile {
|
||||
|
||||
float scale = Math.min(scaleX, scaleY);
|
||||
if (scale < 1f) {
|
||||
updateFolderCellSize(scale, dm, res);
|
||||
updateFolderCellSize(scale, res);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateFolderCellSize(float scale, DisplayMetrics dm, Resources res) {
|
||||
folderChildIconSizePx = (int) (ResourceUtils.pxFromDp(inv.iconSize, dm) * scale);
|
||||
private void updateFolderCellSize(float scale, Resources res) {
|
||||
folderChildIconSizePx = (int) (ResourceUtils.pxFromDp(inv.iconSize, mInfo.metrics) * scale);
|
||||
folderChildTextSizePx =
|
||||
(int) (res.getDimensionPixelSize(R.dimen.folder_child_text_size) * scale);
|
||||
|
||||
@@ -480,14 +499,14 @@ public class DeviceProfile {
|
||||
padding.bottom = edgeMarginPx;
|
||||
if (isSeascape()) {
|
||||
padding.left = hotseatBarSizePx;
|
||||
padding.right = verticalDragHandleSizePx;
|
||||
padding.right = hotseatBarSidePaddingStartPx;
|
||||
} else {
|
||||
padding.left = verticalDragHandleSizePx;
|
||||
padding.left = hotseatBarSidePaddingStartPx;
|
||||
padding.right = hotseatBarSizePx;
|
||||
}
|
||||
} else {
|
||||
int paddingBottom = hotseatBarSizePx + verticalDragHandleSizePx
|
||||
- verticalDragHandleOverlapWorkspace;
|
||||
int paddingBottom = hotseatBarSizePx + workspacePageIndicatorHeight
|
||||
- mWorkspacePageIndicatorOverlapWorkspace;
|
||||
if (isTablet) {
|
||||
// Pad the left and right of the workspace to ensure consistent spacing
|
||||
// between all icons
|
||||
@@ -521,7 +540,6 @@ public class DeviceProfile {
|
||||
mInsets.right + hotseatBarSidePaddingStartPx, mInsets.bottom);
|
||||
}
|
||||
} else {
|
||||
|
||||
// We want the edges of the hotseat to line up with the edges of the workspace, but the
|
||||
// icons in the hotseat are a different size, and so don't line up perfectly. To account
|
||||
// for this, we pad the left and right of the hotseat with half of the difference of a
|
||||
@@ -530,9 +548,11 @@ public class DeviceProfile {
|
||||
float hotseatCellWidth = (float) widthPx / inv.numHotseatIcons;
|
||||
int hotseatAdjustment = Math.round((workspaceCellWidth - hotseatCellWidth) / 2);
|
||||
mHotseatPadding.set(
|
||||
hotseatAdjustment + workspacePadding.left + cellLayoutPaddingLeftRightPx,
|
||||
hotseatAdjustment + workspacePadding.left + cellLayoutPaddingLeftRightPx
|
||||
+ mInsets.left,
|
||||
hotseatBarTopPaddingPx,
|
||||
hotseatAdjustment + workspacePadding.right + cellLayoutPaddingLeftRightPx,
|
||||
hotseatAdjustment + workspacePadding.right + cellLayoutPaddingLeftRightPx
|
||||
+ mInsets.right,
|
||||
hotseatBarBottomPaddingPx + mInsets.bottom + cellLayoutBottomPaddingPx);
|
||||
}
|
||||
return mHotseatPadding;
|
||||
@@ -554,7 +574,7 @@ public class DeviceProfile {
|
||||
mInsets.top + dropTargetBarSizePx + edgeMarginPx,
|
||||
mInsets.left + availableWidthPx - edgeMarginPx,
|
||||
mInsets.top + availableHeightPx - hotseatBarSizePx
|
||||
- verticalDragHandleSizePx - edgeMarginPx);
|
||||
- workspacePageIndicatorHeight - edgeMarginPx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -618,10 +638,11 @@ public class DeviceProfile {
|
||||
}
|
||||
}
|
||||
|
||||
private static Context getContext(Context c, int orientation) {
|
||||
Configuration context = new Configuration(c.getResources().getConfiguration());
|
||||
context.orientation = orientation;
|
||||
return c.createConfigurationContext(context);
|
||||
private static Context getContext(Context c, DefaultDisplay.Info info, int orientation) {
|
||||
Configuration config = new Configuration(c.getResources().getConfiguration());
|
||||
config.orientation = orientation;
|
||||
config.densityDpi = info.metrics.densityDpi;
|
||||
return c.createConfigurationContext(config);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -637,4 +658,64 @@ public class DeviceProfile {
|
||||
*/
|
||||
void onDeviceProfileChanged(DeviceProfile dp);
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
private Context mContext;
|
||||
private InvariantDeviceProfile mInv;
|
||||
private DefaultDisplay.Info mInfo;
|
||||
|
||||
private final Point mWindowPosition = new Point();
|
||||
private Point mMinSize, mMaxSize;
|
||||
private int mWidth, mHeight;
|
||||
|
||||
private boolean mIsLandscape;
|
||||
private boolean mIsMultiWindowMode = false;
|
||||
private boolean mTransposeLayoutWithOrientation;
|
||||
|
||||
public Builder(Context context, InvariantDeviceProfile inv, DefaultDisplay.Info info) {
|
||||
mContext = context;
|
||||
mInv = inv;
|
||||
mInfo = info;
|
||||
mTransposeLayoutWithOrientation = context.getResources()
|
||||
.getBoolean(R.bool.hotseat_transpose_layout_with_orientation);
|
||||
}
|
||||
|
||||
public Builder setSizeRange(Point minSize, Point maxSize) {
|
||||
mMinSize = minSize;
|
||||
mMaxSize = maxSize;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setSize(int width, int height) {
|
||||
mWidth = width;
|
||||
mHeight = height;
|
||||
mIsLandscape = mWidth > mHeight;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setMultiWindowMode(boolean isMultiWindowMode) {
|
||||
mIsMultiWindowMode = isMultiWindowMode;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the window position if not full-screen
|
||||
*/
|
||||
public Builder setWindowPosition(int x, int y) {
|
||||
mWindowPosition.set(x, y);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setTransposeLayoutWithOrientation(boolean transposeLayoutWithOrientation) {
|
||||
mTransposeLayoutWithOrientation = transposeLayoutWithOrientation;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DeviceProfile build() {
|
||||
return new DeviceProfile(mContext, mInv, mInfo, mMinSize, mMaxSize,
|
||||
mWidth, mHeight, mIsLandscape, mIsMultiWindowMode,
|
||||
mTransposeLayoutWithOrientation, mWindowPosition);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,11 +16,19 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Rect;
|
||||
|
||||
import com.android.launcher3.accessibility.DragViewStateAnnouncer;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.dragndrop.DragOptions;
|
||||
import com.android.launcher3.dragndrop.DragView;
|
||||
import com.android.launcher3.dragndrop.DraggableView;
|
||||
import com.android.launcher3.folder.FolderNameProvider;
|
||||
import com.android.launcher3.logging.InstanceId;
|
||||
import com.android.launcher3.logging.InstanceIdSequence;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.util.Executors;
|
||||
|
||||
/**
|
||||
* Interface defining an object that can receive a drag.
|
||||
@@ -56,9 +64,6 @@ public interface DropTarget {
|
||||
/** Where the drag originated */
|
||||
public DragSource dragSource = null;
|
||||
|
||||
/** The object is part of an accessible drag operation */
|
||||
public boolean accessibleDrag;
|
||||
|
||||
/** Indicates that the drag operation was cancelled */
|
||||
public boolean cancelled = false;
|
||||
|
||||
@@ -67,7 +72,23 @@ public interface DropTarget {
|
||||
|
||||
public DragViewStateAnnouncer stateAnnouncer;
|
||||
|
||||
public DragObject() {
|
||||
public FolderNameProvider folderNameProvider;
|
||||
|
||||
/** The source view (ie. icon, widget etc.) that is being dragged and which the
|
||||
* DragView represents. May be an actual View class or a virtual stand-in */
|
||||
public DraggableView originalView = null;
|
||||
|
||||
/** Used for matching DROP event with its corresponding DRAG event on the server side. */
|
||||
public final InstanceId logInstanceId =
|
||||
new InstanceIdSequence(1 << 20 /*InstanceId.INSTANCE_ID_MAX*/)
|
||||
.newInstanceId();
|
||||
|
||||
public DragObject(Context context) {
|
||||
if (FeatureFlags.FOLDER_NAME_SUGGEST.get()) {
|
||||
Executors.MODEL_EXECUTOR.post(() -> {
|
||||
folderNameProvider = FolderNameProvider.newInstance(context);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,6 +113,18 @@ public interface DropTarget {
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This is used to determine if an object is dropped at a different location than it was
|
||||
* dragged from
|
||||
*/
|
||||
public boolean isMoved() {
|
||||
return dragInfo.cellX != originalDragInfo.cellX
|
||||
|| dragInfo.cellY != originalDragInfo.cellY
|
||||
|| dragInfo.screenId != originalDragInfo.screenId
|
||||
|| dragInfo.container != originalDragInfo.container;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,6 +29,7 @@ import com.android.launcher3.util.UiThreadHelper;
|
||||
|
||||
/**
|
||||
* The edit text that reports back when the back key has been pressed.
|
||||
* Note: AppCompatEditText doesn't fully support #displayCompletions and #onCommitCompletion
|
||||
*/
|
||||
public class ExtendedEditText extends EditText {
|
||||
|
||||
@@ -39,7 +40,7 @@ public class ExtendedEditText extends EditText {
|
||||
* Implemented by listeners of the back key.
|
||||
*/
|
||||
public interface OnBackKeyListener {
|
||||
public boolean onBackKey();
|
||||
boolean onBackKey();
|
||||
}
|
||||
|
||||
private OnBackKeyListener mBackKeyListener;
|
||||
@@ -85,12 +86,9 @@ public class ExtendedEditText extends EditText {
|
||||
super.onLayout(changed, left, top, right, bottom);
|
||||
if (mShowImeAfterFirstLayout) {
|
||||
// soft input only shows one frame after the layout of the EditText happens,
|
||||
post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
showSoftInput();
|
||||
mShowImeAfterFirstLayout = false;
|
||||
}
|
||||
post(() -> {
|
||||
showSoftInput();
|
||||
mShowImeAfterFirstLayout = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -105,7 +103,7 @@ public class ExtendedEditText extends EditText {
|
||||
|
||||
private boolean showSoftInput() {
|
||||
return requestFocus() &&
|
||||
((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
|
||||
getContext().getSystemService(InputMethodManager.class)
|
||||
.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import static com.android.launcher3.anim.Interpolators.ACCEL;
|
||||
import static com.android.launcher3.anim.Interpolators.DEACCEL;
|
||||
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
@@ -28,14 +29,15 @@ import android.graphics.ColorMatrix;
|
||||
import android.graphics.ColorMatrixColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.PorterDuff;
|
||||
import android.graphics.PorterDuffColorFilter;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.util.Property;
|
||||
import android.util.SparseArray;
|
||||
|
||||
import com.android.launcher3.graphics.PlaceHolderIconDrawable;
|
||||
import com.android.launcher3.icons.BitmapInfo;
|
||||
import com.android.launcher3.model.data.ItemInfoWithIcon;
|
||||
import com.android.launcher3.util.Themes;
|
||||
|
||||
|
||||
public class FastBitmapDrawable extends Drawable {
|
||||
|
||||
@@ -46,17 +48,7 @@ public class FastBitmapDrawable extends Drawable {
|
||||
|
||||
public static final int CLICK_FEEDBACK_DURATION = 200;
|
||||
|
||||
// Since we don't need 256^2 values for combinations of both the brightness and saturation, we
|
||||
// reduce the value space to a smaller value V, which reduces the number of cached
|
||||
// ColorMatrixColorFilters that we need to keep to V^2
|
||||
private static final int REDUCED_FILTER_VALUE_SPACE = 48;
|
||||
|
||||
// A cache of ColorFilters for optimizing brightness and saturation animations
|
||||
private static final SparseArray<ColorFilter> sCachedFilter = new SparseArray<>();
|
||||
|
||||
// Temporary matrices used for calculation
|
||||
private static final ColorMatrix sTempBrightnessMatrix = new ColorMatrix();
|
||||
private static final ColorMatrix sTempFilterMatrix = new ColorMatrix();
|
||||
private static ColorFilter sDisabledFColorFilter;
|
||||
|
||||
protected final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
|
||||
protected Bitmap mBitmap;
|
||||
@@ -64,6 +56,7 @@ public class FastBitmapDrawable extends Drawable {
|
||||
|
||||
private boolean mIsPressed;
|
||||
private boolean mIsDisabled;
|
||||
private float mDisabledAlpha = 1f;
|
||||
|
||||
// Animator and properties for the fast bitmap drawable's scale
|
||||
private static final Property<FastBitmapDrawable, Float> SCALE
|
||||
@@ -82,13 +75,7 @@ public class FastBitmapDrawable extends Drawable {
|
||||
private ObjectAnimator mScaleAnimation;
|
||||
private float mScale = 1;
|
||||
|
||||
|
||||
// The saturation and brightness are values that are mapped to REDUCED_FILTER_VALUE_SPACE and
|
||||
// as a result, can be used to compose the key for the cached ColorMatrixColorFilters
|
||||
private int mDesaturation = 0;
|
||||
private int mBrightness = 0;
|
||||
private int mAlpha = 255;
|
||||
private int mPrevUpdateKey = Integer.MAX_VALUE;
|
||||
|
||||
public FastBitmapDrawable(Bitmap b) {
|
||||
this(b, Color.TRANSPARENT);
|
||||
@@ -98,10 +85,6 @@ public class FastBitmapDrawable extends Drawable {
|
||||
this(info.icon, info.color);
|
||||
}
|
||||
|
||||
public FastBitmapDrawable(ItemInfoWithIcon info) {
|
||||
this(info.iconBitmap, info.iconColor);
|
||||
}
|
||||
|
||||
protected FastBitmapDrawable(Bitmap b, int iconColor) {
|
||||
this(b, iconColor, false);
|
||||
}
|
||||
@@ -245,15 +228,10 @@ public class FastBitmapDrawable extends Drawable {
|
||||
return false;
|
||||
}
|
||||
|
||||
private void invalidateDesaturationAndBrightness() {
|
||||
setDesaturation(mIsDisabled ? DISABLED_DESATURATION : 0);
|
||||
setBrightness(mIsDisabled ? DISABLED_BRIGHTNESS : 0);
|
||||
}
|
||||
|
||||
public void setIsDisabled(boolean isDisabled) {
|
||||
if (mIsDisabled != isDisabled) {
|
||||
mIsDisabled = isDisabled;
|
||||
invalidateDesaturationAndBrightness();
|
||||
updateFilter();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,90 +239,33 @@ public class FastBitmapDrawable extends Drawable {
|
||||
return mIsDisabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the saturation of this icon, 0 [full color] -> 1 [desaturated]
|
||||
*/
|
||||
private void setDesaturation(float desaturation) {
|
||||
int newDesaturation = (int) Math.floor(desaturation * REDUCED_FILTER_VALUE_SPACE);
|
||||
if (mDesaturation != newDesaturation) {
|
||||
mDesaturation = newDesaturation;
|
||||
updateFilter();
|
||||
private ColorFilter getDisabledColorFilter() {
|
||||
if (sDisabledFColorFilter == null) {
|
||||
ColorMatrix tempBrightnessMatrix = new ColorMatrix();
|
||||
ColorMatrix tempFilterMatrix = new ColorMatrix();
|
||||
|
||||
tempFilterMatrix.setSaturation(1f - DISABLED_DESATURATION);
|
||||
float scale = 1 - DISABLED_BRIGHTNESS;
|
||||
int brightnessI = (int) (255 * DISABLED_BRIGHTNESS);
|
||||
float[] mat = tempBrightnessMatrix.getArray();
|
||||
mat[0] = scale;
|
||||
mat[6] = scale;
|
||||
mat[12] = scale;
|
||||
mat[4] = brightnessI;
|
||||
mat[9] = brightnessI;
|
||||
mat[14] = brightnessI;
|
||||
mat[18] = mDisabledAlpha;
|
||||
tempFilterMatrix.preConcat(tempBrightnessMatrix);
|
||||
sDisabledFColorFilter = new ColorMatrixColorFilter(tempFilterMatrix);
|
||||
}
|
||||
}
|
||||
|
||||
public float getDesaturation() {
|
||||
return (float) mDesaturation / REDUCED_FILTER_VALUE_SPACE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the brightness of this icon, 0 [no add. brightness] -> 1 [2bright2furious]
|
||||
*/
|
||||
private void setBrightness(float brightness) {
|
||||
int newBrightness = (int) Math.floor(brightness * REDUCED_FILTER_VALUE_SPACE);
|
||||
if (mBrightness != newBrightness) {
|
||||
mBrightness = newBrightness;
|
||||
updateFilter();
|
||||
}
|
||||
}
|
||||
|
||||
private float getBrightness() {
|
||||
return (float) mBrightness / REDUCED_FILTER_VALUE_SPACE;
|
||||
return sDisabledFColorFilter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the paint to reflect the current brightness and saturation.
|
||||
*/
|
||||
protected void updateFilter() {
|
||||
boolean usePorterDuffFilter = false;
|
||||
int key = -1;
|
||||
if (mDesaturation > 0) {
|
||||
key = (mDesaturation << 16) | mBrightness;
|
||||
} else if (mBrightness > 0) {
|
||||
// Compose a key with a fully saturated icon if we are just animating brightness
|
||||
key = (1 << 16) | mBrightness;
|
||||
|
||||
// We found that in L, ColorFilters cause drawing artifacts with shadows baked into
|
||||
// icons, so just use a PorterDuff filter when we aren't animating saturation
|
||||
usePorterDuffFilter = true;
|
||||
}
|
||||
|
||||
// Debounce multiple updates on the same frame
|
||||
if (key == mPrevUpdateKey) {
|
||||
return;
|
||||
}
|
||||
mPrevUpdateKey = key;
|
||||
|
||||
if (key != -1) {
|
||||
ColorFilter filter = sCachedFilter.get(key);
|
||||
if (filter == null) {
|
||||
float brightnessF = getBrightness();
|
||||
int brightnessI = (int) (255 * brightnessF);
|
||||
if (usePorterDuffFilter) {
|
||||
filter = new PorterDuffColorFilter(Color.argb(brightnessI, 255, 255, 255),
|
||||
PorterDuff.Mode.SRC_ATOP);
|
||||
} else {
|
||||
float saturationF = 1f - getDesaturation();
|
||||
sTempFilterMatrix.setSaturation(saturationF);
|
||||
if (mBrightness > 0) {
|
||||
// Brightness: C-new = C-old*(1-amount) + amount
|
||||
float scale = 1f - brightnessF;
|
||||
float[] mat = sTempBrightnessMatrix.getArray();
|
||||
mat[0] = scale;
|
||||
mat[6] = scale;
|
||||
mat[12] = scale;
|
||||
mat[4] = brightnessI;
|
||||
mat[9] = brightnessI;
|
||||
mat[14] = brightnessI;
|
||||
sTempFilterMatrix.preConcat(sTempBrightnessMatrix);
|
||||
}
|
||||
filter = new ColorMatrixColorFilter(sTempFilterMatrix);
|
||||
}
|
||||
sCachedFilter.append(key, filter);
|
||||
}
|
||||
mPaint.setColorFilter(filter);
|
||||
} else {
|
||||
mPaint.setColorFilter(null);
|
||||
}
|
||||
mPaint.setColorFilter(mIsDisabled ? getDisabledColorFilter() : null);
|
||||
invalidateSelf();
|
||||
}
|
||||
|
||||
@@ -365,7 +286,7 @@ public class FastBitmapDrawable extends Drawable {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Drawable newDrawable() {
|
||||
public FastBitmapDrawable newDrawable() {
|
||||
return new FastBitmapDrawable(mBitmap, mIconColor, mIsDisabled);
|
||||
}
|
||||
|
||||
@@ -374,4 +295,40 @@ public class FastBitmapDrawable extends Drawable {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface to be implemented by custom {@link BitmapInfo} to handle drawable construction
|
||||
*/
|
||||
public interface Factory {
|
||||
|
||||
/**
|
||||
* Called to create a new drawable
|
||||
*/
|
||||
FastBitmapDrawable newDrawable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a FastBitmapDrawable with the icon.
|
||||
*/
|
||||
public static FastBitmapDrawable newIcon(Context context, ItemInfoWithIcon info) {
|
||||
FastBitmapDrawable drawable = newIcon(context, info.bitmap);
|
||||
drawable.setIsDisabled(info.isDisabled());
|
||||
return drawable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a drawable for the provided BitmapInfo
|
||||
*/
|
||||
public static FastBitmapDrawable newIcon(Context context, BitmapInfo info) {
|
||||
final FastBitmapDrawable drawable;
|
||||
if (info instanceof Factory) {
|
||||
drawable = ((Factory) info).newDrawable();
|
||||
} else if (info.isLowRes()) {
|
||||
drawable = new PlaceHolderIconDrawable(info, context);
|
||||
} else {
|
||||
drawable = new FastBitmapDrawable(info);
|
||||
}
|
||||
drawable.mDisabledAlpha = Themes.getFloat(context, R.attr.disabledIconAlpha, 1f);
|
||||
return drawable;
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import android.view.ViewGroup;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.folder.Folder;
|
||||
import com.android.launcher3.folder.FolderPagedView;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.util.FocusLogic;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
|
||||
@@ -96,7 +97,7 @@ public class FocusHelper {
|
||||
}
|
||||
|
||||
if (!(v.getParent() instanceof ShortcutAndWidgetContainer)) {
|
||||
if (FeatureFlags.IS_DOGFOOD_BUILD) {
|
||||
if (FeatureFlags.IS_STUDIO_BUILD) {
|
||||
throw new IllegalStateException("Parent of the focused item is not supported.");
|
||||
} else {
|
||||
return false;
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2008 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;
|
||||
|
||||
import android.os.Process;
|
||||
|
||||
import com.android.launcher3.model.ModelWriter;
|
||||
import com.android.launcher3.util.ContentWriter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* Represents a folder containing shortcuts or apps.
|
||||
*/
|
||||
public class FolderInfo extends ItemInfo {
|
||||
|
||||
public static final int NO_FLAGS = 0x00000000;
|
||||
|
||||
/**
|
||||
* The folder is locked in sorted mode
|
||||
*/
|
||||
public static final int FLAG_ITEMS_SORTED = 0x00000001;
|
||||
|
||||
/**
|
||||
* It is a work folder
|
||||
*/
|
||||
public static final int FLAG_WORK_FOLDER = 0x00000002;
|
||||
|
||||
/**
|
||||
* The multi-page animation has run for this folder
|
||||
*/
|
||||
public static final int FLAG_MULTI_PAGE_ANIMATION = 0x00000004;
|
||||
|
||||
public int options;
|
||||
|
||||
/**
|
||||
* The apps and shortcuts
|
||||
*/
|
||||
public ArrayList<WorkspaceItemInfo> contents = new ArrayList<>();
|
||||
|
||||
private ArrayList<FolderListener> mListeners = new ArrayList<>();
|
||||
|
||||
public FolderInfo() {
|
||||
itemType = LauncherSettings.Favorites.ITEM_TYPE_FOLDER;
|
||||
user = Process.myUserHandle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an app or shortcut
|
||||
*
|
||||
* @param item
|
||||
*/
|
||||
public void add(WorkspaceItemInfo item, boolean animate) {
|
||||
add(item, contents.size(), animate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an app or shortcut for a specified rank.
|
||||
*/
|
||||
public void add(WorkspaceItemInfo item, int rank, boolean animate) {
|
||||
rank = Utilities.boundToRange(rank, 0, contents.size() + 1);
|
||||
contents.add(rank, item);
|
||||
for (int i = 0; i < mListeners.size(); i++) {
|
||||
mListeners.get(i).onAdd(item, rank);
|
||||
}
|
||||
itemsChanged(animate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an app or shortcut. Does not change the DB.
|
||||
*
|
||||
* @param item
|
||||
*/
|
||||
public void remove(WorkspaceItemInfo item, boolean animate) {
|
||||
contents.remove(item);
|
||||
for (int i = 0; i < mListeners.size(); i++) {
|
||||
mListeners.get(i).onRemove(item);
|
||||
}
|
||||
itemsChanged(animate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAddToDatabase(ContentWriter writer) {
|
||||
super.onAddToDatabase(writer);
|
||||
writer.put(LauncherSettings.Favorites.TITLE, title)
|
||||
.put(LauncherSettings.Favorites.OPTIONS, options);
|
||||
}
|
||||
|
||||
public void addListener(FolderListener listener) {
|
||||
mListeners.add(listener);
|
||||
}
|
||||
|
||||
public void removeListener(FolderListener listener) {
|
||||
mListeners.remove(listener);
|
||||
}
|
||||
|
||||
public void itemsChanged(boolean animate) {
|
||||
for (int i = 0; i < mListeners.size(); i++) {
|
||||
mListeners.get(i).onItemsChanged(animate);
|
||||
}
|
||||
}
|
||||
|
||||
public interface FolderListener {
|
||||
public void onAdd(WorkspaceItemInfo item, int rank);
|
||||
public void onRemove(WorkspaceItemInfo item);
|
||||
public void onItemsChanged(boolean animate);
|
||||
}
|
||||
|
||||
public boolean hasOption(int optionFlag) {
|
||||
return (options & optionFlag) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param option flag to set or clear
|
||||
* @param isEnabled whether to set or clear the flag
|
||||
* @param writer if not null, save changes to the db.
|
||||
*/
|
||||
public void setOption(int option, boolean isEnabled, ModelWriter writer) {
|
||||
int oldOptions = options;
|
||||
if (isEnabled) {
|
||||
options |= option;
|
||||
} else {
|
||||
options &= ~option;
|
||||
}
|
||||
if (writer != null && oldOptions != options) {
|
||||
writer.updateItemInDatabase(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,26 +16,30 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Rect;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.Gravity;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewDebug;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
import com.android.launcher3.graphics.RotationMode;
|
||||
import com.android.launcher3.logging.StatsLogUtils.LogContainerProvider;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
|
||||
import com.android.launcher3.views.Transposable;
|
||||
|
||||
public class Hotseat extends CellLayout implements LogContainerProvider, Insettable, Transposable {
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class Hotseat extends CellLayout implements LogContainerProvider, Insettable {
|
||||
|
||||
@ViewDebug.ExportedProperty(category = "launcher")
|
||||
private boolean mHasVerticalHotseat;
|
||||
private Workspace mWorkspace;
|
||||
private boolean mSendTouchToWorkspace;
|
||||
|
||||
public Hotseat(Context context) {
|
||||
this(context, null);
|
||||
@@ -49,12 +53,17 @@ public class Hotseat extends CellLayout implements LogContainerProvider, Insetta
|
||||
super(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
/* Get the orientation specific coordinates given an invariant order in the hotseat. */
|
||||
int getCellXFromOrder(int rank) {
|
||||
/**
|
||||
* Returns orientation specific cell X given invariant order in the hotseat
|
||||
*/
|
||||
public int getCellXFromOrder(int rank) {
|
||||
return mHasVerticalHotseat ? 0 : rank;
|
||||
}
|
||||
|
||||
int getCellYFromOrder(int rank) {
|
||||
/**
|
||||
* Returns orientation specific cell Y given invariant order in the hotseat
|
||||
*/
|
||||
public int getCellYFromOrder(int rank) {
|
||||
return mHasVerticalHotseat ? (getCountY() - (rank + 1)) : 0;
|
||||
}
|
||||
|
||||
@@ -70,17 +79,18 @@ public class Hotseat extends CellLayout implements LogContainerProvider, Insetta
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
|
||||
target.gridX = info.cellX;
|
||||
target.gridY = info.cellY;
|
||||
targetParent.containerType = LauncherLogProto.ContainerType.HOTSEAT;
|
||||
public void fillInLogContainerData(ItemInfo childInfo, Target child,
|
||||
ArrayList<Target> parents) {
|
||||
child.rank = childInfo.rank;
|
||||
child.gridX = childInfo.cellX;
|
||||
child.gridY = childInfo.cellY;
|
||||
parents.add(newContainerTarget(LauncherLogProto.ContainerType.HOTSEAT));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInsets(Rect insets) {
|
||||
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) getLayoutParams();
|
||||
DeviceProfile grid = mActivity.getWallpaperDeviceProfile();
|
||||
insets = grid.getInsets();
|
||||
DeviceProfile grid = mActivity.getDeviceProfile();
|
||||
|
||||
if (grid.isVerticalBarLayout()) {
|
||||
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
|
||||
@@ -103,13 +113,35 @@ public class Hotseat extends CellLayout implements LogContainerProvider, Insetta
|
||||
InsettableFrameLayout.dispatchInsets(this, insets);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
return event.getY() > getCellHeight();
|
||||
public void setWorkspace(Workspace w) {
|
||||
mWorkspace = w;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RotationMode getRotationMode() {
|
||||
return Launcher.getLauncher(getContext()).getRotationMode();
|
||||
public boolean onInterceptTouchEvent(MotionEvent ev) {
|
||||
// We allow horizontal workspace scrolling from within the Hotseat. We do this by delegating
|
||||
// touch intercept the Workspace, and if it intercepts, delegating touch to the Workspace
|
||||
// for the remainder of the this input stream.
|
||||
int yThreshold = getMeasuredHeight() - getPaddingBottom();
|
||||
if (mWorkspace != null && ev.getY() <= yThreshold) {
|
||||
mSendTouchToWorkspace = mWorkspace.onInterceptTouchEvent(ev);
|
||||
return mSendTouchToWorkspace;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
// See comment in #onInterceptTouchEvent
|
||||
if (mSendTouchToWorkspace) {
|
||||
final int action = event.getAction();
|
||||
switch (action & MotionEvent.ACTION_MASK) {
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
mSendTouchToWorkspace = false;
|
||||
}
|
||||
return mWorkspace.onTouchEvent(event);
|
||||
}
|
||||
return event.getY() > getCellHeight();
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.util.MainThreadInitializedObject.forOverride;
|
||||
|
||||
import android.content.pm.LauncherActivityInfo;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
import com.android.launcher3.util.MainThreadInitializedObject;
|
||||
import com.android.launcher3.util.ResourceBasedOverride;
|
||||
|
||||
public class IconProvider implements ResourceBasedOverride {
|
||||
|
||||
public static MainThreadInitializedObject<IconProvider> INSTANCE =
|
||||
forOverride(IconProvider.class, R.string.icon_provider_class);
|
||||
|
||||
public IconProvider() { }
|
||||
|
||||
public String getSystemStateForPackage(String systemState, String packageName) {
|
||||
return systemState;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param flattenDrawable true if the caller does not care about the specification of the
|
||||
* original icon as long as the flattened version looks the same.
|
||||
*/
|
||||
public Drawable getIcon(LauncherActivityInfo info, int iconDpi, boolean flattenDrawable) {
|
||||
return info.getIcon(iconDpi);
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,9 @@ public class InsettableFrameLayout extends FrameLayout implements Insettable {
|
||||
@Override
|
||||
public void onViewAdded(View child) {
|
||||
super.onViewAdded(child);
|
||||
if (!isAttachedToWindow()) {
|
||||
return;
|
||||
}
|
||||
setFrameLayoutChildInsets(child, mInsets, new Rect());
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.content.pm.LauncherActivityInfo;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ShortcutInfo;
|
||||
import android.graphics.Bitmap;
|
||||
@@ -42,13 +43,16 @@ import android.util.Pair;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.WorkerThread;
|
||||
|
||||
import com.android.launcher3.compat.LauncherAppsCompat;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.icons.BitmapInfo;
|
||||
import com.android.launcher3.icons.GraphicsUtils;
|
||||
import com.android.launcher3.icons.LauncherIcons;
|
||||
import com.android.launcher3.shortcuts.DeepShortcutManager;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
import com.android.launcher3.pm.UserCache;
|
||||
import com.android.launcher3.shortcuts.ShortcutKey;
|
||||
import com.android.launcher3.shortcuts.ShortcutRequest;
|
||||
import com.android.launcher3.util.PackageManagerHelper;
|
||||
import com.android.launcher3.util.Preconditions;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
@@ -59,7 +63,6 @@ import org.json.JSONStringer;
|
||||
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
@@ -71,7 +74,6 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
public static final int FLAG_ACTIVITY_PAUSED = 1;
|
||||
public static final int FLAG_LOADER_RUNNING = 2;
|
||||
public static final int FLAG_DRAG_AND_DROP = 4;
|
||||
public static final int FLAG_BULK_ADD = 4;
|
||||
|
||||
// Determines whether to defer installing shortcuts immediately until
|
||||
// processAllPendingInstalls() is called.
|
||||
@@ -112,8 +114,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
|
||||
@WorkerThread
|
||||
private static void flushQueueInBackground(Context context) {
|
||||
LauncherModel model = LauncherAppState.getInstance(context).getModel();
|
||||
if (model.getCallback() == null) {
|
||||
if (Launcher.ACTIVITY_TRACKER.getCreatedActivity() == null) {
|
||||
// Launcher not loaded
|
||||
return;
|
||||
}
|
||||
@@ -126,7 +127,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
return;
|
||||
}
|
||||
|
||||
LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
|
||||
LauncherApps launcherApps = context.getSystemService(LauncherApps.class);
|
||||
for (String encoded : strings) {
|
||||
PendingInstallShortcutInfo info = decode(encoded, context);
|
||||
if (info == null) {
|
||||
@@ -135,7 +136,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
|
||||
String pkg = getIntentPackage(info.launchIntent);
|
||||
if (!TextUtils.isEmpty(pkg)
|
||||
&& !launcherApps.isPackageEnabledForProfile(pkg, info.user)
|
||||
&& !launcherApps.isPackageEnabled(pkg, info.user)
|
||||
&& !info.isActivity) {
|
||||
if (DBG) {
|
||||
Log.d(TAG, "Ignoring shortcut for absent package: " + info.launchIntent);
|
||||
@@ -148,7 +149,8 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
}
|
||||
prefs.edit().remove(APPS_PENDING_INSTALL).apply();
|
||||
if (!installQueue.isEmpty()) {
|
||||
model.addAndBindAddedWorkspaceItems(installQueue);
|
||||
LauncherAppState.getInstance(context).getModel()
|
||||
.addAndBindAddedWorkspaceItems(installQueue);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,7 +423,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
.object()
|
||||
.key(LAUNCH_INTENT_KEY).value(launchIntent.toUri(0))
|
||||
.key(DEEPSHORTCUT_TYPE_KEY).value(true)
|
||||
.key(USER_HANDLE_KEY).value(UserManagerCompat.getInstance(mContext)
|
||||
.key(USER_HANDLE_KEY).value(UserCache.INSTANCE.get(mContext)
|
||||
.getSerialNumberForUser(user))
|
||||
.endObject().toString();
|
||||
} else if (providerInfo != null) {
|
||||
@@ -431,7 +433,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
.object()
|
||||
.key(LAUNCH_INTENT_KEY).value(launchIntent.toUri(0))
|
||||
.key(APP_WIDGET_TYPE_KEY).value(true)
|
||||
.key(USER_HANDLE_KEY).value(UserManagerCompat.getInstance(mContext)
|
||||
.key(USER_HANDLE_KEY).value(UserCache.INSTANCE.get(mContext)
|
||||
.getSerialNumberForUser(user))
|
||||
.endObject().toString();
|
||||
}
|
||||
@@ -459,7 +461,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
.key(LAUNCH_INTENT_KEY).value(launchIntent.toUri(0))
|
||||
.key(NAME_KEY).value(name)
|
||||
.key(USER_HANDLE_KEY).value(
|
||||
UserManagerCompat.getInstance(mContext).getSerialNumberForUser(user))
|
||||
UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user))
|
||||
.key(APP_SHORTCUT_TYPE_KEY).value(isActivity);
|
||||
if (icon != null) {
|
||||
byte[] iconByteArray = GraphicsUtils.flattenBitmap(icon);
|
||||
@@ -490,9 +492,8 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
return Pair.create(si, null);
|
||||
} else if (shortcutInfo != null) {
|
||||
WorkspaceItemInfo itemInfo = new WorkspaceItemInfo(shortcutInfo, mContext);
|
||||
LauncherIcons li = LauncherIcons.obtain(mContext);
|
||||
itemInfo.applyFrom(li.createShortcutIcon(shortcutInfo));
|
||||
li.recycle();
|
||||
LauncherAppState.getInstance(mContext).getIconCache().getShortcutIcon(
|
||||
itemInfo, shortcutInfo);
|
||||
return Pair.create(itemInfo, shortcutInfo);
|
||||
} else if (providerInfo != null) {
|
||||
LauncherAppWidgetProviderInfo info = LauncherAppWidgetProviderInfo
|
||||
@@ -527,18 +528,15 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
try {
|
||||
Decoder decoder = new Decoder(encoded, context);
|
||||
if (decoder.optBoolean(APP_SHORTCUT_TYPE_KEY)) {
|
||||
LauncherActivityInfo info = LauncherAppsCompat.getInstance(context)
|
||||
LauncherActivityInfo info = context.getSystemService(LauncherApps.class)
|
||||
.resolveActivity(decoder.launcherIntent, decoder.user);
|
||||
if (info != null) {
|
||||
return new PendingInstallShortcutInfo(info, context);
|
||||
}
|
||||
} else if (decoder.optBoolean(DEEPSHORTCUT_TYPE_KEY)) {
|
||||
DeepShortcutManager sm = DeepShortcutManager.getInstance(context);
|
||||
List<ShortcutInfo> si = sm.queryForFullDetails(
|
||||
decoder.launcherIntent.getPackage(),
|
||||
Arrays.asList(decoder.launcherIntent.getStringExtra(
|
||||
ShortcutKey.EXTRA_SHORTCUT_ID)),
|
||||
decoder.user);
|
||||
List<ShortcutInfo> si = ShortcutKey.fromIntent(decoder.launcherIntent, decoder.user)
|
||||
.buildRequest(context)
|
||||
.query(ShortcutRequest.ALL);
|
||||
if (si.isEmpty()) {
|
||||
return null;
|
||||
} else {
|
||||
@@ -593,7 +591,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
private Decoder(String encoded, Context context) throws JSONException, URISyntaxException {
|
||||
super(encoded);
|
||||
launcherIntent = Intent.parseUri(getString(LAUNCH_INTENT_KEY), 0);
|
||||
user = has(USER_HANDLE_KEY) ? UserManagerCompat.getInstance(context)
|
||||
user = has(USER_HANDLE_KEY) ? UserCache.INSTANCE.get(context)
|
||||
.getUserForSerialNumber(getLong(USER_HANDLE_KEY))
|
||||
: Process.myUserHandle();
|
||||
if (user == null) {
|
||||
@@ -617,7 +615,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
return original;
|
||||
}
|
||||
|
||||
LauncherActivityInfo info = LauncherAppsCompat.getInstance(original.mContext)
|
||||
LauncherActivityInfo info = original.mContext.getSystemService(LauncherApps.class)
|
||||
.resolveActivity(original.launchIntent, original.user);
|
||||
if (info == null) {
|
||||
return original;
|
||||
@@ -662,7 +660,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
|
||||
if (iconInfo == null) {
|
||||
iconInfo = app.getIconCache().getDefaultIcon(info.user);
|
||||
}
|
||||
info.applyFrom(iconInfo);
|
||||
info.bitmap = iconInfo;
|
||||
|
||||
info.title = Utilities.trim(name);
|
||||
info.contentDescription = app.getContext().getPackageManager()
|
||||
|
||||
@@ -17,9 +17,9 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.Utilities.getDevicePrefs;
|
||||
import static com.android.launcher3.Utilities.getPointString;
|
||||
import static com.android.launcher3.config.FeatureFlags.APPLY_CONFIG_AT_RUNTIME;
|
||||
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
|
||||
import static com.android.launcher3.settings.SettingsActivity.GRID_OPTIONS_PREFERENCE_KEY;
|
||||
import static com.android.launcher3.util.PackageManagerHelper.getPackageFilter;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
@@ -41,6 +41,7 @@ import android.util.Log;
|
||||
import android.util.SparseArray;
|
||||
import android.util.TypedValue;
|
||||
import android.util.Xml;
|
||||
import android.view.Display;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.VisibleForTesting;
|
||||
@@ -48,6 +49,7 @@ import androidx.annotation.VisibleForTesting;
|
||||
import com.android.launcher3.graphics.IconShape;
|
||||
import com.android.launcher3.util.ConfigMonitor;
|
||||
import com.android.launcher3.util.DefaultDisplay;
|
||||
import com.android.launcher3.util.DefaultDisplay.Info;
|
||||
import com.android.launcher3.util.IntArray;
|
||||
import com.android.launcher3.util.MainThreadInitializedObject;
|
||||
import com.android.launcher3.util.Themes;
|
||||
@@ -58,7 +60,6 @@ import org.xmlpull.v1.XmlPullParserException;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
|
||||
public class InvariantDeviceProfile {
|
||||
|
||||
@@ -67,6 +68,9 @@ public class InvariantDeviceProfile {
|
||||
public static final MainThreadInitializedObject<InvariantDeviceProfile> INSTANCE =
|
||||
new MainThreadInitializedObject<>(InvariantDeviceProfile::new);
|
||||
|
||||
public static final String KEY_MIGRATION_SRC_WORKSPACE_SIZE = "migration_src_workspace_size";
|
||||
public static final String KEY_MIGRATION_SRC_HOTSEAT_COUNT = "migration_src_hotseat_count";
|
||||
|
||||
private static final String KEY_IDP_GRID_NAME = "idp_grid_name";
|
||||
|
||||
private static final float ICON_SIZE_DEFINED_IN_APP_DP = 48;
|
||||
@@ -119,6 +123,7 @@ public class InvariantDeviceProfile {
|
||||
*/
|
||||
public int numAllAppsColumns;
|
||||
|
||||
public String dbFile;
|
||||
public int defaultLayoutId;
|
||||
int demoModeLayoutId;
|
||||
|
||||
@@ -143,9 +148,11 @@ public class InvariantDeviceProfile {
|
||||
iconSize = p.iconSize;
|
||||
iconShapePath = p.iconShapePath;
|
||||
landscapeIconSize = p.landscapeIconSize;
|
||||
iconBitmapSize = p.iconBitmapSize;
|
||||
iconTextSize = p.iconTextSize;
|
||||
numHotseatIcons = p.numHotseatIcons;
|
||||
numAllAppsColumns = p.numAllAppsColumns;
|
||||
dbFile = p.dbFile;
|
||||
allAppsIconSize = p.allAppsIconSize;
|
||||
allAppsIconTextSize = p.allAppsIconTextSize;
|
||||
defaultLayoutId = p.defaultLayoutId;
|
||||
@@ -156,10 +163,16 @@ public class InvariantDeviceProfile {
|
||||
|
||||
@TargetApi(23)
|
||||
private InvariantDeviceProfile(Context context) {
|
||||
String gridName = Utilities.getPrefs(context).getBoolean(GRID_OPTIONS_PREFERENCE_KEY, false)
|
||||
? Utilities.getPrefs(context).getString(KEY_IDP_GRID_NAME, null)
|
||||
: null;
|
||||
initGrid(context, gridName);
|
||||
String gridName = getCurrentGridName(context);
|
||||
String newGridName = initGrid(context, gridName);
|
||||
if (!newGridName.equals(gridName)) {
|
||||
Utilities.getPrefs(context).edit().putString(KEY_IDP_GRID_NAME, newGridName).apply();
|
||||
}
|
||||
Utilities.getPrefs(context).edit()
|
||||
.putInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT, numHotseatIcons)
|
||||
.putString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, getPointString(numColumns, numRows))
|
||||
.apply();
|
||||
|
||||
mConfigMonitor = new ConfigMonitor(context,
|
||||
APPLY_CONFIG_AT_RUNTIME.get() ? this::onConfigChanged : this::killProcess);
|
||||
mOverlayMonitor = new OverlayMonitor(context);
|
||||
@@ -175,6 +188,37 @@ public class InvariantDeviceProfile {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This constructor should NOT have any monitors by design.
|
||||
*/
|
||||
public InvariantDeviceProfile(Context context, Display display) {
|
||||
// Ensure that the main device profile is initialized
|
||||
InvariantDeviceProfile originalProfile = INSTANCE.get(context);
|
||||
String gridName = getCurrentGridName(context);
|
||||
|
||||
// Get the display info based on default display and interpolate it to existing display
|
||||
DisplayOption defaultDisplayOption = invDistWeightedInterpolate(
|
||||
DefaultDisplay.INSTANCE.get(context).getInfo(),
|
||||
getPredefinedDeviceProfiles(context, gridName));
|
||||
|
||||
Info myInfo = new Info(context, display);
|
||||
DisplayOption myDisplayOption = invDistWeightedInterpolate(
|
||||
myInfo, getPredefinedDeviceProfiles(context, gridName));
|
||||
|
||||
DisplayOption result = new DisplayOption(defaultDisplayOption.grid)
|
||||
.add(myDisplayOption);
|
||||
result.iconSize = defaultDisplayOption.iconSize;
|
||||
result.landscapeIconSize = defaultDisplayOption.landscapeIconSize;
|
||||
result.allAppsIconSize = Math.min(
|
||||
defaultDisplayOption.allAppsIconSize, myDisplayOption.allAppsIconSize);
|
||||
initGrid(context, myInfo, result);
|
||||
}
|
||||
|
||||
public static String getCurrentGridName(Context context) {
|
||||
return Utilities.isGridOptionsEnabled(context)
|
||||
? Utilities.getPrefs(context).getString(KEY_IDP_GRID_NAME, null) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve system defined or RRO overriden icon shape.
|
||||
*/
|
||||
@@ -188,15 +232,46 @@ public class InvariantDeviceProfile {
|
||||
|
||||
private String initGrid(Context context, String gridName) {
|
||||
DefaultDisplay.Info displayInfo = DefaultDisplay.INSTANCE.get(context).getInfo();
|
||||
ArrayList<DisplayOption> allOptions = getPredefinedDeviceProfiles(context, gridName);
|
||||
|
||||
Point smallestSize = new Point(displayInfo.smallestSize);
|
||||
Point largestSize = new Point(displayInfo.largestSize);
|
||||
DisplayOption displayOption = invDistWeightedInterpolate(displayInfo, allOptions);
|
||||
initGrid(context, displayInfo, displayOption);
|
||||
return displayOption.grid.name;
|
||||
}
|
||||
|
||||
// This guarantees that width < height
|
||||
float minWidthDps = Utilities.dpiFromPx(Math.min(smallestSize.x, smallestSize.y),
|
||||
displayInfo.metrics);
|
||||
float minHeightDps = Utilities.dpiFromPx(Math.min(largestSize.x, largestSize.y),
|
||||
displayInfo.metrics);
|
||||
private void initGrid(
|
||||
Context context, DefaultDisplay.Info displayInfo, DisplayOption displayOption) {
|
||||
GridOption closestProfile = displayOption.grid;
|
||||
numRows = closestProfile.numRows;
|
||||
numColumns = closestProfile.numColumns;
|
||||
numHotseatIcons = closestProfile.numHotseatIcons;
|
||||
dbFile = closestProfile.dbFile;
|
||||
defaultLayoutId = closestProfile.defaultLayoutId;
|
||||
demoModeLayoutId = closestProfile.demoModeLayoutId;
|
||||
numFolderRows = closestProfile.numFolderRows;
|
||||
numFolderColumns = closestProfile.numFolderColumns;
|
||||
numAllAppsColumns = closestProfile.numAllAppsColumns;
|
||||
|
||||
mExtraAttrs = closestProfile.extraAttrs;
|
||||
|
||||
iconSize = displayOption.iconSize;
|
||||
iconShapePath = getIconShapePath(context);
|
||||
landscapeIconSize = displayOption.landscapeIconSize;
|
||||
iconBitmapSize = ResourceUtils.pxFromDp(iconSize, displayInfo.metrics);
|
||||
iconTextSize = displayOption.iconTextSize;
|
||||
fillResIconDpi = getLauncherIconDensity(iconBitmapSize);
|
||||
|
||||
if (Utilities.isGridOptionsEnabled(context)) {
|
||||
allAppsIconSize = displayOption.allAppsIconSize;
|
||||
allAppsIconTextSize = displayOption.allAppsIconTextSize;
|
||||
} else {
|
||||
allAppsIconSize = iconSize;
|
||||
allAppsIconTextSize = iconTextSize;
|
||||
}
|
||||
|
||||
// If the partner customization apk contains any grid overrides, apply them
|
||||
// Supported overrides: numRows, numColumns, iconSize
|
||||
applyPartnerDeviceProfileOverrides(context, displayInfo.metrics);
|
||||
|
||||
Point realSize = new Point(displayInfo.realSize);
|
||||
// The real size never changes. smallSide and largeSide will remain the
|
||||
@@ -204,64 +279,12 @@ public class InvariantDeviceProfile {
|
||||
int smallSide = Math.min(realSize.x, realSize.y);
|
||||
int largeSide = Math.max(realSize.x, realSize.y);
|
||||
|
||||
// We want a list of all options as well as the list of filtered options. This allows us
|
||||
// to have a consistent UI for areas that the grid size change should not affect
|
||||
// ie. All Apps should be consistent between grid sizes.
|
||||
ArrayList<DisplayOption> allOptions = new ArrayList<>();
|
||||
ArrayList<DisplayOption> filteredOptions = new ArrayList<>();
|
||||
getPredefinedDeviceProfiles(context, gridName, filteredOptions, allOptions);
|
||||
DeviceProfile.Builder builder = new DeviceProfile.Builder(context, this, displayInfo)
|
||||
.setSizeRange(new Point(displayInfo.smallestSize),
|
||||
new Point(displayInfo.largestSize));
|
||||
|
||||
if (allOptions.isEmpty() && filteredOptions.isEmpty()) {
|
||||
throw new RuntimeException("No display option with canBeDefault=true");
|
||||
}
|
||||
|
||||
// Sort the profiles based on the closeness to the device size
|
||||
Comparator<DisplayOption> comparator = (a, b) -> Float.compare(dist(minWidthDps,
|
||||
minHeightDps, a.minWidthDps, a.minHeightDps),
|
||||
dist(minWidthDps, minHeightDps, b.minWidthDps, b.minHeightDps));
|
||||
|
||||
// Calculate the device profiles as if there is no grid override.
|
||||
Collections.sort(allOptions, comparator);
|
||||
DisplayOption interpolatedDisplayOption =
|
||||
invDistWeightedInterpolate(minWidthDps, minHeightDps, allOptions);
|
||||
initGridOption(context, allOptions, interpolatedDisplayOption, displayInfo.metrics);
|
||||
|
||||
// Create IDP with no grid override values.
|
||||
InvariantDeviceProfile originalIDP = new InvariantDeviceProfile(this);
|
||||
originalIDP.landscapeProfile = new DeviceProfile(context, this, null, smallestSize,
|
||||
largestSize, largeSide, smallSide, true /* isLandscape */,
|
||||
false /* isMultiWindowMode */);
|
||||
originalIDP.portraitProfile = new DeviceProfile(context, this, null, smallestSize,
|
||||
largestSize, smallSide, largeSide, false /* isLandscape */,
|
||||
false /* isMultiWindowMode */);
|
||||
|
||||
if (filteredOptions.isEmpty()) {
|
||||
filteredOptions = allOptions;
|
||||
|
||||
landscapeProfile = originalIDP.landscapeProfile;
|
||||
portraitProfile = originalIDP.portraitProfile;
|
||||
} else {
|
||||
Collections.sort(filteredOptions, comparator);
|
||||
interpolatedDisplayOption =
|
||||
invDistWeightedInterpolate(minWidthDps, minHeightDps, filteredOptions);
|
||||
|
||||
initGridOption(context, filteredOptions, interpolatedDisplayOption,
|
||||
displayInfo.metrics);
|
||||
numAllAppsColumns = originalIDP.numAllAppsColumns;
|
||||
|
||||
landscapeProfile = new DeviceProfile(context, this, originalIDP, smallestSize,
|
||||
largestSize, largeSide, smallSide, true /* isLandscape */,
|
||||
false /* isMultiWindowMode */);
|
||||
portraitProfile = new DeviceProfile(context, this, originalIDP, smallestSize,
|
||||
largestSize, smallSide, largeSide, false /* isLandscape */,
|
||||
false /* isMultiWindowMode */);
|
||||
}
|
||||
|
||||
GridOption closestProfile = filteredOptions.get(0).grid;
|
||||
if (!closestProfile.name.equals(gridName)) {
|
||||
Utilities.getPrefs(context).edit()
|
||||
.putString(KEY_IDP_GRID_NAME, closestProfile.name).apply();
|
||||
}
|
||||
landscapeProfile = builder.setSize(largeSide, smallSide).build();
|
||||
portraitProfile = builder.setSize(smallSide, largeSide).build();
|
||||
|
||||
// We need to ensure that there is enough extra space in the wallpaper
|
||||
// for the intended parallax effects
|
||||
@@ -275,37 +298,8 @@ public class InvariantDeviceProfile {
|
||||
|
||||
ComponentName cn = new ComponentName(context.getPackageName(), getClass().getName());
|
||||
defaultWidgetPadding = AppWidgetHostView.getDefaultPaddingForWidget(context, cn, null);
|
||||
|
||||
return closestProfile.name;
|
||||
}
|
||||
|
||||
private void initGridOption(Context context, ArrayList<DisplayOption> options,
|
||||
DisplayOption displayOption, DisplayMetrics metrics) {
|
||||
GridOption closestProfile = options.get(0).grid;
|
||||
numRows = closestProfile.numRows;
|
||||
numColumns = closestProfile.numColumns;
|
||||
numHotseatIcons = closestProfile.numHotseatIcons;
|
||||
defaultLayoutId = closestProfile.defaultLayoutId;
|
||||
demoModeLayoutId = closestProfile.demoModeLayoutId;
|
||||
numFolderRows = closestProfile.numFolderRows;
|
||||
numFolderColumns = closestProfile.numFolderColumns;
|
||||
numAllAppsColumns = numColumns;
|
||||
|
||||
mExtraAttrs = closestProfile.extraAttrs;
|
||||
|
||||
iconSize = displayOption.iconSize;
|
||||
iconShapePath = getIconShapePath(context);
|
||||
landscapeIconSize = displayOption.landscapeIconSize;
|
||||
iconBitmapSize = ResourceUtils.pxFromDp(iconSize, metrics);
|
||||
iconTextSize = displayOption.iconTextSize;
|
||||
fillResIconDpi = getLauncherIconDensity(iconBitmapSize);
|
||||
|
||||
// If the partner customization apk contains any grid overrides, apply them
|
||||
// Supported overrides: numRows, numColumns, iconSize
|
||||
applyPartnerDeviceProfileOverrides(context, metrics);
|
||||
}
|
||||
|
||||
|
||||
@Nullable
|
||||
public TypedValue getAttrValue(int attr) {
|
||||
return mExtraAttrs == null ? null : mExtraAttrs.get(attr);
|
||||
@@ -348,9 +342,7 @@ public class InvariantDeviceProfile {
|
||||
InvariantDeviceProfile oldProfile = new InvariantDeviceProfile(this);
|
||||
|
||||
// Re-init grid
|
||||
String gridName = Utilities.getPrefs(context).getBoolean(GRID_OPTIONS_PREFERENCE_KEY, false)
|
||||
? Utilities.getPrefs(context).getString(KEY_IDP_GRID_NAME, null)
|
||||
: null;
|
||||
String gridName = getCurrentGridName(context);
|
||||
initGrid(context, gridName);
|
||||
|
||||
int changeFlags = 0;
|
||||
@@ -383,13 +375,7 @@ public class InvariantDeviceProfile {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param gridName The current grid name.
|
||||
* @param filteredOptionsOut List filled with all the filtered options based on gridName.
|
||||
* @param allOptionsOut List filled with all the options that can be the default option.
|
||||
*/
|
||||
static void getPredefinedDeviceProfiles(Context context, String gridName,
|
||||
ArrayList<DisplayOption> filteredOptionsOut, ArrayList<DisplayOption> allOptionsOut) {
|
||||
static ArrayList<DisplayOption> getPredefinedDeviceProfiles(Context context, String gridName) {
|
||||
ArrayList<DisplayOption> profiles = new ArrayList<>();
|
||||
try (XmlResourceParser parser = context.getResources().getXml(R.xml.device_profiles)) {
|
||||
final int depth = parser.getDepth();
|
||||
@@ -416,19 +402,26 @@ public class InvariantDeviceProfile {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
ArrayList<DisplayOption> filteredProfiles = new ArrayList<>();
|
||||
if (!TextUtils.isEmpty(gridName)) {
|
||||
for (DisplayOption option : profiles) {
|
||||
if (gridName.equals(option.grid.name)) {
|
||||
filteredOptionsOut.add(option);
|
||||
filteredProfiles.add(option);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (DisplayOption option : profiles) {
|
||||
if (option.canBeDefault) {
|
||||
allOptionsOut.add(option);
|
||||
if (filteredProfiles.isEmpty()) {
|
||||
// No grid found, use the default options
|
||||
for (DisplayOption option : profiles) {
|
||||
if (option.canBeDefault) {
|
||||
filteredProfiles.add(option);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (filteredProfiles.isEmpty()) {
|
||||
throw new RuntimeException("No display option with canBeDefault=true");
|
||||
}
|
||||
return filteredProfiles;
|
||||
}
|
||||
|
||||
private int getLauncherIconDensity(int requiredSize) {
|
||||
@@ -471,9 +464,44 @@ public class InvariantDeviceProfile {
|
||||
return (float) Math.hypot(x1 - x0, y1 - y0);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static DisplayOption invDistWeightedInterpolate(
|
||||
DefaultDisplay.Info displayInfo, ArrayList<DisplayOption> points) {
|
||||
Point smallestSize = new Point(displayInfo.smallestSize);
|
||||
Point largestSize = new Point(displayInfo.largestSize);
|
||||
|
||||
// This guarantees that width < height
|
||||
float width = Utilities.dpiFromPx(Math.min(smallestSize.x, smallestSize.y),
|
||||
displayInfo.metrics);
|
||||
float height = Utilities.dpiFromPx(Math.min(largestSize.x, largestSize.y),
|
||||
displayInfo.metrics);
|
||||
|
||||
// Sort the profiles based on the closeness to the device size
|
||||
Collections.sort(points, (a, b) ->
|
||||
Float.compare(dist(width, height, a.minWidthDps, a.minHeightDps),
|
||||
dist(width, height, b.minWidthDps, b.minHeightDps)));
|
||||
|
||||
GridOption closestOption = points.get(0).grid;
|
||||
float weights = 0;
|
||||
|
||||
DisplayOption p = points.get(0);
|
||||
if (dist(width, height, p.minWidthDps, p.minHeightDps) == 0) {
|
||||
return p;
|
||||
}
|
||||
|
||||
DisplayOption out = new DisplayOption(closestOption);
|
||||
for (int i = 0; i < points.size() && i < KNEARESTNEIGHBOR; ++i) {
|
||||
p = points.get(i);
|
||||
float w = weight(width, height, p.minWidthDps, p.minHeightDps, WEIGHT_POWER);
|
||||
weights += w;
|
||||
out.add(new DisplayOption().add(p).multiply(w));
|
||||
}
|
||||
return out.multiply(1.0f / weights);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static DisplayOption invDistWeightedInterpolate(float width, float height,
|
||||
ArrayList<DisplayOption> points) {
|
||||
ArrayList<DisplayOption> points) {
|
||||
float weights = 0;
|
||||
|
||||
DisplayOption p = points.get(0);
|
||||
@@ -552,6 +580,9 @@ public class InvariantDeviceProfile {
|
||||
|
||||
private final int numHotseatIcons;
|
||||
|
||||
private final String dbFile;
|
||||
private final int numAllAppsColumns;
|
||||
|
||||
private final int defaultLayoutId;
|
||||
private final int demoModeLayoutId;
|
||||
|
||||
@@ -564,6 +595,7 @@ public class InvariantDeviceProfile {
|
||||
numRows = a.getInt(R.styleable.GridDisplayOption_numRows, 0);
|
||||
numColumns = a.getInt(R.styleable.GridDisplayOption_numColumns, 0);
|
||||
|
||||
dbFile = a.getString(R.styleable.GridDisplayOption_dbFile);
|
||||
defaultLayoutId = a.getResourceId(
|
||||
R.styleable.GridDisplayOption_defaultLayoutId, 0);
|
||||
demoModeLayoutId = a.getResourceId(
|
||||
@@ -574,6 +606,8 @@ public class InvariantDeviceProfile {
|
||||
R.styleable.GridDisplayOption_numFolderRows, numRows);
|
||||
numFolderColumns = a.getInt(
|
||||
R.styleable.GridDisplayOption_numFolderColumns, numColumns);
|
||||
numAllAppsColumns = a.getInt(
|
||||
R.styleable.GridDisplayOption_numAllAppsColumns, numColumns);
|
||||
|
||||
a.recycle();
|
||||
|
||||
@@ -585,7 +619,6 @@ public class InvariantDeviceProfile {
|
||||
private static final class DisplayOption {
|
||||
private final GridOption grid;
|
||||
|
||||
private final String name;
|
||||
private final float minWidthDps;
|
||||
private final float minHeightDps;
|
||||
private final boolean canBeDefault;
|
||||
@@ -593,6 +626,8 @@ public class InvariantDeviceProfile {
|
||||
private float iconSize;
|
||||
private float iconTextSize;
|
||||
private float landscapeIconSize;
|
||||
private float allAppsIconSize;
|
||||
private float allAppsIconTextSize;
|
||||
|
||||
DisplayOption(GridOption grid, Context context, AttributeSet attrs) {
|
||||
this.grid = grid;
|
||||
@@ -600,7 +635,6 @@ public class InvariantDeviceProfile {
|
||||
TypedArray a = context.obtainStyledAttributes(
|
||||
attrs, R.styleable.ProfileDisplayOption);
|
||||
|
||||
name = a.getString(R.styleable.ProfileDisplayOption_name);
|
||||
minWidthDps = a.getFloat(R.styleable.ProfileDisplayOption_minWidthDps, 0);
|
||||
minHeightDps = a.getFloat(R.styleable.ProfileDisplayOption_minHeightDps, 0);
|
||||
canBeDefault = a.getBoolean(
|
||||
@@ -611,12 +645,19 @@ public class InvariantDeviceProfile {
|
||||
iconSize);
|
||||
iconTextSize = a.getFloat(R.styleable.ProfileDisplayOption_iconTextSize, 0);
|
||||
|
||||
allAppsIconSize = a.getFloat(R.styleable.ProfileDisplayOption_allAppsIconSize,
|
||||
iconSize);
|
||||
allAppsIconTextSize = a.getFloat(R.styleable.ProfileDisplayOption_allAppsIconTextSize,
|
||||
iconTextSize);
|
||||
a.recycle();
|
||||
}
|
||||
|
||||
DisplayOption() {
|
||||
grid = null;
|
||||
name = null;
|
||||
this(null);
|
||||
}
|
||||
|
||||
DisplayOption(GridOption grid) {
|
||||
this.grid = grid;
|
||||
minWidthDps = 0;
|
||||
minHeightDps = 0;
|
||||
canBeDefault = false;
|
||||
@@ -625,14 +666,18 @@ public class InvariantDeviceProfile {
|
||||
private DisplayOption multiply(float w) {
|
||||
iconSize *= w;
|
||||
landscapeIconSize *= w;
|
||||
allAppsIconSize *= w;
|
||||
iconTextSize *= w;
|
||||
allAppsIconTextSize *= w;
|
||||
return this;
|
||||
}
|
||||
|
||||
private DisplayOption add(DisplayOption p) {
|
||||
iconSize += p.iconSize;
|
||||
landscapeIconSize += p.landscapeIconSize;
|
||||
allAppsIconSize += p.allAppsIconSize;
|
||||
iconTextSize += p.iconTextSize;
|
||||
allAppsIconTextSize += p.allAppsIconTextSize;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -650,4 +695,4 @@ public class InvariantDeviceProfile {
|
||||
onConfigChanged(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2008 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;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Intent;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.util.ContentWriter;
|
||||
|
||||
/**
|
||||
* Represents an item in the launcher.
|
||||
*/
|
||||
public class ItemInfo {
|
||||
|
||||
public static final int NO_ID = -1;
|
||||
|
||||
/**
|
||||
* The id in the settings database for this item
|
||||
*/
|
||||
public int id = NO_ID;
|
||||
|
||||
/**
|
||||
* One of {@link LauncherSettings.Favorites#ITEM_TYPE_APPLICATION},
|
||||
* {@link LauncherSettings.Favorites#ITEM_TYPE_SHORTCUT},
|
||||
* {@link LauncherSettings.Favorites#ITEM_TYPE_DEEP_SHORTCUT}
|
||||
* {@link LauncherSettings.Favorites#ITEM_TYPE_FOLDER},
|
||||
* {@link LauncherSettings.Favorites#ITEM_TYPE_APPWIDGET} or
|
||||
* {@link LauncherSettings.Favorites#ITEM_TYPE_CUSTOM_APPWIDGET}.
|
||||
*/
|
||||
public int itemType;
|
||||
|
||||
/**
|
||||
* The id of the container that holds this item. For the desktop, this will be
|
||||
* {@link LauncherSettings.Favorites#CONTAINER_DESKTOP}. For the all applications folder it
|
||||
* will be {@link #NO_ID} (since it is not stored in the settings DB). For user folders
|
||||
* it will be the id of the folder.
|
||||
*/
|
||||
public int container = NO_ID;
|
||||
|
||||
/**
|
||||
* Indicates the screen in which the shortcut appears if the container types is
|
||||
* {@link LauncherSettings.Favorites#CONTAINER_DESKTOP}. (i.e., ignore if the container type is
|
||||
* {@link LauncherSettings.Favorites#CONTAINER_HOTSEAT})
|
||||
*/
|
||||
public int screenId = -1;
|
||||
|
||||
/**
|
||||
* Indicates the X position of the associated cell.
|
||||
*/
|
||||
public int cellX = -1;
|
||||
|
||||
/**
|
||||
* Indicates the Y position of the associated cell.
|
||||
*/
|
||||
public int cellY = -1;
|
||||
|
||||
/**
|
||||
* Indicates the X cell span.
|
||||
*/
|
||||
public int spanX = 1;
|
||||
|
||||
/**
|
||||
* Indicates the Y cell span.
|
||||
*/
|
||||
public int spanY = 1;
|
||||
|
||||
/**
|
||||
* Indicates the minimum X cell span.
|
||||
*/
|
||||
public int minSpanX = 1;
|
||||
|
||||
/**
|
||||
* Indicates the minimum Y cell span.
|
||||
*/
|
||||
public int minSpanY = 1;
|
||||
|
||||
/**
|
||||
* Indicates the position in an ordered list.
|
||||
*/
|
||||
public int rank = 0;
|
||||
|
||||
/**
|
||||
* Title of the item
|
||||
*/
|
||||
public CharSequence title;
|
||||
|
||||
/**
|
||||
* Content description of the item.
|
||||
*/
|
||||
public CharSequence contentDescription;
|
||||
|
||||
public UserHandle user;
|
||||
|
||||
public ItemInfo() {
|
||||
user = Process.myUserHandle();
|
||||
}
|
||||
|
||||
ItemInfo(ItemInfo info) {
|
||||
copyFrom(info);
|
||||
}
|
||||
|
||||
public void copyFrom(ItemInfo info) {
|
||||
id = info.id;
|
||||
cellX = info.cellX;
|
||||
cellY = info.cellY;
|
||||
spanX = info.spanX;
|
||||
spanY = info.spanY;
|
||||
rank = info.rank;
|
||||
screenId = info.screenId;
|
||||
itemType = info.itemType;
|
||||
container = info.container;
|
||||
user = info.user;
|
||||
contentDescription = info.contentDescription;
|
||||
}
|
||||
|
||||
public Intent getIntent() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ComponentName getTargetComponent() {
|
||||
Intent intent = getIntent();
|
||||
if (intent != null) {
|
||||
return intent.getComponent();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void writeToValues(ContentWriter writer) {
|
||||
writer.put(LauncherSettings.Favorites.ITEM_TYPE, itemType)
|
||||
.put(LauncherSettings.Favorites.CONTAINER, container)
|
||||
.put(LauncherSettings.Favorites.SCREEN, screenId)
|
||||
.put(LauncherSettings.Favorites.CELLX, cellX)
|
||||
.put(LauncherSettings.Favorites.CELLY, cellY)
|
||||
.put(LauncherSettings.Favorites.SPANX, spanX)
|
||||
.put(LauncherSettings.Favorites.SPANY, spanY)
|
||||
.put(LauncherSettings.Favorites.RANK, rank);
|
||||
}
|
||||
|
||||
public void readFromValues(ContentValues values) {
|
||||
itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
|
||||
container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
|
||||
screenId = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
|
||||
cellX = values.getAsInteger(LauncherSettings.Favorites.CELLX);
|
||||
cellY = values.getAsInteger(LauncherSettings.Favorites.CELLY);
|
||||
spanX = values.getAsInteger(LauncherSettings.Favorites.SPANX);
|
||||
spanY = values.getAsInteger(LauncherSettings.Favorites.SPANY);
|
||||
rank = values.getAsInteger(LauncherSettings.Favorites.RANK);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the fields of this item to the DB
|
||||
*/
|
||||
public void onAddToDatabase(ContentWriter writer) {
|
||||
if (screenId == Workspace.EXTRA_EMPTY_SCREEN_ID) {
|
||||
// We should never persist an item on the extra empty screen.
|
||||
throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
|
||||
}
|
||||
|
||||
writeToValues(writer);
|
||||
writer.put(LauncherSettings.Favorites.PROFILE_ID, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final String toString() {
|
||||
return getClass().getSimpleName() + "(" + dumpProperties() + ")";
|
||||
}
|
||||
|
||||
protected String dumpProperties() {
|
||||
return "id=" + id
|
||||
+ " type=" + LauncherSettings.Favorites.itemTypeToString(itemType)
|
||||
+ " container=" + LauncherSettings.Favorites.containerToString((int)container)
|
||||
+ " screen=" + screenId
|
||||
+ " cell(" + cellX + "," + cellY + ")"
|
||||
+ " span(" + spanX + "," + spanY + ")"
|
||||
+ " minSpan(" + minSpanX + "," + minSpanY + ")"
|
||||
+ " rank=" + rank
|
||||
+ " user=" + user
|
||||
+ " title=" + title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this item is disabled.
|
||||
*/
|
||||
public boolean isDisabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getViewId() {
|
||||
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
|
||||
// This cast is safe as long as the id < 0x00FFFFFF
|
||||
// Since we jail all the dynamically generated views, there should be no clashes
|
||||
// with any other views.
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -18,7 +18,7 @@ package com.android.launcher3;
|
||||
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.util.FloatProperty;
|
||||
import android.util.Property;
|
||||
import android.util.IntProperty;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup.LayoutParams;
|
||||
|
||||
@@ -27,23 +27,20 @@ public class LauncherAnimUtils {
|
||||
* Durations for various state animations. These are not defined in resources to allow
|
||||
* easier access from static classes and enums
|
||||
*/
|
||||
public static final int ALL_APPS_TRANSITION_MS = 320;
|
||||
public static final int OVERVIEW_TRANSITION_MS = 250;
|
||||
public static final int SPRING_LOADED_TRANSITION_MS = 150;
|
||||
public static final int SPRING_LOADED_EXIT_DELAY = 500;
|
||||
|
||||
// The progress of an animation to all apps must be at least this far along to snap to all apps.
|
||||
public static final float MIN_PROGRESS_TO_ALL_APPS = 0.5f;
|
||||
|
||||
public static final Property<Drawable, Integer> DRAWABLE_ALPHA =
|
||||
new Property<Drawable, Integer>(Integer.TYPE, "drawableAlpha") {
|
||||
public static final IntProperty<Drawable> DRAWABLE_ALPHA =
|
||||
new IntProperty<Drawable>("drawableAlpha") {
|
||||
@Override
|
||||
public Integer get(Drawable drawable) {
|
||||
return drawable.getAlpha();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(Drawable drawable, Integer alpha) {
|
||||
public void setValue(Drawable drawable, int alpha) {
|
||||
drawable.setAlpha(alpha);
|
||||
}
|
||||
};
|
||||
@@ -67,28 +64,28 @@ public class LauncherAnimUtils {
|
||||
return (int) Utilities.boundToRange(Math.abs(velocity) / 2, 2f, 6f);
|
||||
}
|
||||
|
||||
public static final Property<LayoutParams, Integer> LAYOUT_WIDTH =
|
||||
new Property<LayoutParams, Integer>(Integer.TYPE, "width") {
|
||||
public static final IntProperty<LayoutParams> LAYOUT_WIDTH =
|
||||
new IntProperty<LayoutParams>("width") {
|
||||
@Override
|
||||
public Integer get(LayoutParams lp) {
|
||||
return lp.width;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(LayoutParams lp, Integer width) {
|
||||
public void setValue(LayoutParams lp, int width) {
|
||||
lp.width = width;
|
||||
}
|
||||
};
|
||||
|
||||
public static final Property<LayoutParams, Integer> LAYOUT_HEIGHT =
|
||||
new Property<LayoutParams, Integer>(Integer.TYPE, "height") {
|
||||
public static final IntProperty<LayoutParams> LAYOUT_HEIGHT =
|
||||
new IntProperty<LayoutParams>("height") {
|
||||
@Override
|
||||
public Integer get(LayoutParams lp) {
|
||||
return lp.height;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(LayoutParams lp, Integer height) {
|
||||
public void setValue(LayoutParams lp, int height) {
|
||||
lp.height = height;
|
||||
}
|
||||
};
|
||||
@@ -120,4 +117,18 @@ public class LauncherAnimUtils {
|
||||
return view.getTranslationY();
|
||||
}
|
||||
};
|
||||
|
||||
public static final FloatProperty<View> VIEW_ALPHA =
|
||||
View.ALPHA instanceof FloatProperty ? (FloatProperty) View.ALPHA
|
||||
: new FloatProperty<View>("alpha") {
|
||||
@Override
|
||||
public void setValue(View view, float v) {
|
||||
view.setAlpha(v);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Float get(View view) {
|
||||
return view.getAlpha();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -17,26 +17,32 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.InvariantDeviceProfile.CHANGE_FLAG_ICON_PARAMS;
|
||||
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
|
||||
import static com.android.launcher3.util.SecureSettingsObserver.newNotificationSettingsObserver;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.ContentProviderClient;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.os.Handler;
|
||||
import android.util.Log;
|
||||
|
||||
import com.android.launcher3.compat.LauncherAppsCompat;
|
||||
import com.android.launcher3.compat.PackageInstallerCompat;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.icons.IconCache;
|
||||
import com.android.launcher3.icons.IconProvider;
|
||||
import com.android.launcher3.icons.LauncherIcons;
|
||||
import com.android.launcher3.model.PredictionModel;
|
||||
import com.android.launcher3.notification.NotificationListener;
|
||||
import com.android.launcher3.pm.InstallSessionHelper;
|
||||
import com.android.launcher3.pm.InstallSessionTracker;
|
||||
import com.android.launcher3.pm.UserCache;
|
||||
import com.android.launcher3.util.MainThreadInitializedObject;
|
||||
import com.android.launcher3.util.Preconditions;
|
||||
import com.android.launcher3.util.SafeCloseable;
|
||||
import com.android.launcher3.util.SecureSettingsObserver;
|
||||
import com.android.launcher3.util.SimpleBroadcastReceiver;
|
||||
import com.android.launcher3.widget.custom.CustomWidgetManager;
|
||||
|
||||
public class LauncherAppState {
|
||||
@@ -44,7 +50,7 @@ public class LauncherAppState {
|
||||
public static final String ACTION_FORCE_ROLOAD = "force-reload-launcher";
|
||||
|
||||
// We do not need any synchronization for this variable as its only written on UI thread.
|
||||
private static final MainThreadInitializedObject<LauncherAppState> INSTANCE =
|
||||
public static final MainThreadInitializedObject<LauncherAppState> INSTANCE =
|
||||
new MainThreadInitializedObject<>(LauncherAppState::new);
|
||||
|
||||
private final Context mContext;
|
||||
@@ -52,7 +58,13 @@ public class LauncherAppState {
|
||||
private final IconCache mIconCache;
|
||||
private final WidgetPreviewLoader mWidgetCache;
|
||||
private final InvariantDeviceProfile mInvariantDeviceProfile;
|
||||
private final SecureSettingsObserver mNotificationDotsObserver;
|
||||
private final PredictionModel mPredictionModel;
|
||||
|
||||
private SecureSettingsObserver mNotificationDotsObserver;
|
||||
private InstallSessionTracker mInstallSessionTracker;
|
||||
private SimpleBroadcastReceiver mModelChangeReceiver;
|
||||
private SafeCloseable mCalendarChangeTracker;
|
||||
private SafeCloseable mUserChangeListener;
|
||||
|
||||
public static LauncherAppState getInstance(final Context context) {
|
||||
return INSTANCE.get(context);
|
||||
@@ -66,42 +78,37 @@ public class LauncherAppState {
|
||||
return mContext;
|
||||
}
|
||||
|
||||
private LauncherAppState(Context context) {
|
||||
if (getLocalProvider(context) == null) {
|
||||
throw new RuntimeException(
|
||||
"Initializing LauncherAppState in the absence of LauncherProvider");
|
||||
public LauncherAppState(Context context) {
|
||||
this(context, LauncherFiles.APP_ICONS_DB);
|
||||
|
||||
mModelChangeReceiver = new SimpleBroadcastReceiver(mModel::onBroadcastIntent);
|
||||
|
||||
mContext.getSystemService(LauncherApps.class).registerCallback(mModel);
|
||||
mModelChangeReceiver.register(mContext, Intent.ACTION_LOCALE_CHANGED,
|
||||
Intent.ACTION_MANAGED_PROFILE_AVAILABLE,
|
||||
Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE,
|
||||
Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
|
||||
if (FeatureFlags.IS_STUDIO_BUILD) {
|
||||
mModelChangeReceiver.register(mContext, ACTION_FORCE_ROLOAD);
|
||||
}
|
||||
Log.v(Launcher.TAG, "LauncherAppState initiated");
|
||||
Preconditions.assertUIThread();
|
||||
mContext = context;
|
||||
|
||||
mInvariantDeviceProfile = InvariantDeviceProfile.INSTANCE.get(mContext);
|
||||
mIconCache = new IconCache(mContext, mInvariantDeviceProfile);
|
||||
mWidgetCache = new WidgetPreviewLoader(mContext, mIconCache);
|
||||
mModel = new LauncherModel(this, mIconCache, AppFilter.newInstance(mContext));
|
||||
mCalendarChangeTracker = IconProvider.registerIconChangeListener(mContext,
|
||||
mModel::onAppIconChanged, MODEL_EXECUTOR.getHandler());
|
||||
|
||||
LauncherAppsCompat.getInstance(mContext).addOnAppsChangedCallback(mModel);
|
||||
|
||||
// Register intent receivers
|
||||
IntentFilter filter = new IntentFilter();
|
||||
filter.addAction(Intent.ACTION_LOCALE_CHANGED);
|
||||
// For handling managed profiles
|
||||
filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
|
||||
filter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
|
||||
filter.addAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
|
||||
filter.addAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
|
||||
filter.addAction(Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
|
||||
|
||||
if (FeatureFlags.IS_DOGFOOD_BUILD) {
|
||||
filter.addAction(ACTION_FORCE_ROLOAD);
|
||||
}
|
||||
// TODO: remove listener on terminate
|
||||
FeatureFlags.APP_SEARCH_IMPROVEMENTS.addChangeListener(context, mModel::forceReload);
|
||||
CustomWidgetManager.INSTANCE.get(mContext)
|
||||
.setWidgetRefreshCallback(mModel::refreshAndBindWidgetsAndShortcuts);
|
||||
|
||||
mUserChangeListener = UserCache.INSTANCE.get(mContext)
|
||||
.addUserChangeListener(mModel::forceReload);
|
||||
|
||||
mContext.registerReceiver(mModel, filter);
|
||||
UserManagerCompat.getInstance(mContext).enableAndResetCache();
|
||||
mInvariantDeviceProfile.addOnChangeListener(this::onIdpChanged);
|
||||
new Handler().post( () -> mInvariantDeviceProfile.verifyConfigChangedInBackground(context));
|
||||
|
||||
mInstallSessionTracker = InstallSessionHelper.INSTANCE.get(context)
|
||||
.registerInstallTracker(mModel, MODEL_EXECUTOR);
|
||||
|
||||
if (!mContext.getResources().getBoolean(R.bool.notification_dots_enabled)) {
|
||||
mNotificationDotsObserver = null;
|
||||
} else {
|
||||
@@ -113,6 +120,18 @@ public class LauncherAppState {
|
||||
}
|
||||
}
|
||||
|
||||
public LauncherAppState(Context context, @Nullable String iconCacheFileName) {
|
||||
Log.v(Launcher.TAG, "LauncherAppState initiated");
|
||||
Preconditions.assertUIThread();
|
||||
mContext = context;
|
||||
|
||||
mInvariantDeviceProfile = InvariantDeviceProfile.INSTANCE.get(context);
|
||||
mIconCache = new IconCache(mContext, mInvariantDeviceProfile, iconCacheFileName);
|
||||
mWidgetCache = new WidgetPreviewLoader(mContext, mIconCache);
|
||||
mModel = new LauncherModel(this, mIconCache, AppFilter.newInstance(mContext));
|
||||
mPredictionModel = PredictionModel.newInstance(mContext);
|
||||
}
|
||||
|
||||
protected void onNotificationSettingsChanged(boolean areNotificationDotsEnabled) {
|
||||
if (areNotificationDotsEnabled) {
|
||||
NotificationListener.requestRebind(new ComponentName(
|
||||
@@ -138,23 +157,26 @@ public class LauncherAppState {
|
||||
* Call from Application.onTerminate(), which is not guaranteed to ever be called.
|
||||
*/
|
||||
public void onTerminate() {
|
||||
mContext.unregisterReceiver(mModel);
|
||||
final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(mContext);
|
||||
launcherApps.removeOnAppsChangedCallback(mModel);
|
||||
PackageInstallerCompat.getInstance(mContext).onStop();
|
||||
if (mModelChangeReceiver != null) {
|
||||
mContext.unregisterReceiver(mModelChangeReceiver);
|
||||
}
|
||||
mContext.getSystemService(LauncherApps.class).unregisterCallback(mModel);
|
||||
if (mInstallSessionTracker != null) {
|
||||
mInstallSessionTracker.unregister();
|
||||
}
|
||||
if (mCalendarChangeTracker != null) {
|
||||
mCalendarChangeTracker.close();
|
||||
}
|
||||
if (mUserChangeListener != null) {
|
||||
mUserChangeListener.close();
|
||||
}
|
||||
CustomWidgetManager.INSTANCE.get(mContext).setWidgetRefreshCallback(null);
|
||||
|
||||
if (mNotificationDotsObserver != null) {
|
||||
mNotificationDotsObserver.unregister();
|
||||
}
|
||||
}
|
||||
|
||||
LauncherModel setLauncher(Launcher launcher) {
|
||||
getLocalProvider(mContext).setLauncherProviderChangeListener(launcher);
|
||||
mModel.initialize(launcher);
|
||||
CustomWidgetManager.INSTANCE.get(launcher)
|
||||
.setWidgetRefreshCallback(mModel::refreshAndBindWidgetsAndShortcuts);
|
||||
return mModel;
|
||||
}
|
||||
|
||||
public IconCache getIconCache() {
|
||||
return mIconCache;
|
||||
}
|
||||
@@ -163,6 +185,10 @@ public class LauncherAppState {
|
||||
return mModel;
|
||||
}
|
||||
|
||||
public PredictionModel getPredictionModel() {
|
||||
return mPredictionModel;
|
||||
}
|
||||
|
||||
public WidgetPreviewLoader getWidgetCache() {
|
||||
return mWidgetCache;
|
||||
}
|
||||
@@ -177,11 +203,4 @@ public class LauncherAppState {
|
||||
public static InvariantDeviceProfile getIDP(Context context) {
|
||||
return InvariantDeviceProfile.INSTANCE.get(context);
|
||||
}
|
||||
|
||||
private static LauncherProvider getLocalProvider(Context context) {
|
||||
try (ContentProviderClient cl = context.getContentResolver()
|
||||
.acquireContentProviderClient(LauncherProvider.AUTHORITY)) {
|
||||
return (LauncherProvider) cl.getLocalContentProvider();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,8 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.app.ActivityOptions;
|
||||
import android.content.Context;
|
||||
import android.graphics.Rect;
|
||||
@@ -58,13 +55,16 @@ public class LauncherAppTransitionManager implements ResourceBasedOverride {
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of animations which run on state properties.
|
||||
* Registers remote animations for certain system transitions.
|
||||
*/
|
||||
public int getStateElementAnimationsCount() {
|
||||
return 0;
|
||||
public void registerRemoteAnimations() {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
public Animator createStateElementAnimation(int index, float... values) {
|
||||
throw new RuntimeException("Unknown gesture animation " + index);
|
||||
/**
|
||||
* Unregisters all remote animations.
|
||||
*/
|
||||
public void unregisterRemoteAnimations() {
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
@@ -29,9 +29,12 @@ import android.os.Handler;
|
||||
import android.util.SparseArray;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.model.WidgetsModel;
|
||||
import com.android.launcher3.testing.TestLogging;
|
||||
import com.android.launcher3.testing.TestProtocol;
|
||||
import com.android.launcher3.widget.DeferredAppWidgetHostView;
|
||||
import com.android.launcher3.widget.LauncherAppWidgetHostView;
|
||||
import com.android.launcher3.widget.PendingAppWidgetHostView;
|
||||
import com.android.launcher3.widget.custom.CustomWidgetManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -53,12 +56,14 @@ public class LauncherAppWidgetHost extends AppWidgetHost {
|
||||
|
||||
private final ArrayList<ProviderChangedListener> mProviderChangeListeners = new ArrayList<>();
|
||||
private final SparseArray<LauncherAppWidgetHostView> mViews = new SparseArray<>();
|
||||
private final SparseArray<PendingAppWidgetHostView> mPendingViews = new SparseArray<>();
|
||||
|
||||
private final Context mContext;
|
||||
private int mFlags = FLAG_RESUMED;
|
||||
|
||||
private IntConsumer mAppWidgetRemovedCallback = null;
|
||||
|
||||
|
||||
public LauncherAppWidgetHost(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
@@ -73,14 +78,20 @@ public class LauncherAppWidgetHost extends AppWidgetHost {
|
||||
@Override
|
||||
protected LauncherAppWidgetHostView onCreateView(Context context, int appWidgetId,
|
||||
AppWidgetProviderInfo appWidget) {
|
||||
LauncherAppWidgetHostView view = new LauncherAppWidgetHostView(context);
|
||||
final LauncherAppWidgetHostView view;
|
||||
if (mPendingViews.get(appWidgetId) != null) {
|
||||
view = mPendingViews.get(appWidgetId);
|
||||
mPendingViews.remove(appWidgetId);
|
||||
} else {
|
||||
view = new LauncherAppWidgetHostView(context);
|
||||
}
|
||||
mViews.put(appWidgetId, view);
|
||||
return view;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startListening() {
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
if (WidgetsModel.GO_DISABLE_WIDGETS) {
|
||||
return;
|
||||
}
|
||||
mFlags |= FLAG_LISTENING;
|
||||
@@ -107,7 +118,7 @@ public class LauncherAppWidgetHost extends AppWidgetHost {
|
||||
|
||||
@Override
|
||||
public void stopListening() {
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
if (WidgetsModel.GO_DISABLE_WIDGETS) {
|
||||
return;
|
||||
}
|
||||
mFlags &= ~FLAG_LISTENING;
|
||||
@@ -166,7 +177,7 @@ public class LauncherAppWidgetHost extends AppWidgetHost {
|
||||
|
||||
@Override
|
||||
public int allocateAppWidgetId() {
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
if (WidgetsModel.GO_DISABLE_WIDGETS) {
|
||||
return AppWidgetManager.INVALID_APPWIDGET_ID;
|
||||
}
|
||||
|
||||
@@ -189,6 +200,10 @@ public class LauncherAppWidgetHost extends AppWidgetHost {
|
||||
}
|
||||
}
|
||||
|
||||
void addPendingView(int appWidgetId, PendingAppWidgetHostView view) {
|
||||
mPendingViews.put(appWidgetId, view);
|
||||
}
|
||||
|
||||
public AppWidgetHostView createView(Context context, int appWidgetId,
|
||||
LauncherAppWidgetProviderInfo appWidget) {
|
||||
if (appWidget.isCustomWidget()) {
|
||||
@@ -238,8 +253,8 @@ public class LauncherAppWidgetHost extends AppWidgetHost {
|
||||
|
||||
/**
|
||||
* Called on an appWidget is removed for a widgetId
|
||||
* @param appWidgetId
|
||||
* TODO: make this override when SDK is updated
|
||||
*
|
||||
* @param appWidgetId TODO: make this override when SDK is updated
|
||||
*/
|
||||
public void onAppWidgetRemoved(int appWidgetId) {
|
||||
if (mAppWidgetRemovedCallback == null) {
|
||||
@@ -263,7 +278,7 @@ public class LauncherAppWidgetHost extends AppWidgetHost {
|
||||
public void startBindFlow(BaseActivity activity,
|
||||
int appWidgetId, AppWidgetProviderInfo info, int requestCode) {
|
||||
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
if (WidgetsModel.GO_DISABLE_WIDGETS) {
|
||||
sendActionCancelled(activity, requestCode);
|
||||
return;
|
||||
}
|
||||
@@ -279,12 +294,13 @@ public class LauncherAppWidgetHost extends AppWidgetHost {
|
||||
|
||||
|
||||
public void startConfigActivity(BaseActivity activity, int widgetId, int requestCode) {
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
if (WidgetsModel.GO_DISABLE_WIDGETS) {
|
||||
sendActionCancelled(activity, requestCode);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "start: startConfigActivity");
|
||||
startAppWidgetConfigureActivityForResult(activity, widgetId, 0, requestCode, null);
|
||||
} catch (ActivityNotFoundException | SecurityException e) {
|
||||
Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
|
||||
|
||||
@@ -7,10 +7,13 @@ import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Parcel;
|
||||
import android.os.UserHandle;
|
||||
|
||||
import com.android.launcher3.icons.ComponentWithLabel;
|
||||
import com.android.launcher3.icons.ComponentWithLabelAndIcon;
|
||||
import com.android.launcher3.icons.IconCache;
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
|
||||
|
||||
/**
|
||||
* This class is a thin wrapper around the framework AppWidgetProviderInfo class. This class affords
|
||||
@@ -19,7 +22,7 @@ import com.android.launcher3.icons.ComponentWithLabel;
|
||||
* as opposed to a widget instance, and so should not be confused with {@link LauncherAppWidgetInfo}
|
||||
*/
|
||||
public class LauncherAppWidgetProviderInfo extends AppWidgetProviderInfo
|
||||
implements ComponentWithLabel {
|
||||
implements ComponentWithLabelAndIcon {
|
||||
|
||||
public static final String CLS_CUSTOM_WIDGET_PREFIX = "#custom-widget-";
|
||||
|
||||
@@ -111,4 +114,9 @@ public class LauncherAppWidgetProviderInfo extends AppWidgetProviderInfo
|
||||
public final UserHandle getUser() {
|
||||
return getProfile();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Drawable getFullResIcon(IconCache cache) {
|
||||
return cache.getFullResIcon(provider.getPackageName(), icon);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
|
||||
import java.io.FileDescriptor;
|
||||
@@ -36,31 +35,8 @@ public interface LauncherCallbacks {
|
||||
* the code in the corresponding Launcher method is executed.
|
||||
*/
|
||||
void onCreate(Bundle savedInstanceState);
|
||||
void onResume();
|
||||
void onStart();
|
||||
void onStop();
|
||||
void onPause();
|
||||
void onDestroy();
|
||||
void onSaveInstanceState(Bundle outState);
|
||||
void onActivityResult(int requestCode, int resultCode, Intent data);
|
||||
void onRequestPermissionsResult(int requestCode, String[] permissions,
|
||||
int[] grantResults);
|
||||
void onAttachedToWindow();
|
||||
void onDetachedFromWindow();
|
||||
void dump(String prefix, FileDescriptor fd, PrintWriter w, String[] args);
|
||||
void onHomeIntent(boolean internalStateHandled);
|
||||
boolean handleBackPressed();
|
||||
void onTrimMemory(int level);
|
||||
|
||||
/**
|
||||
* Called when the launcher state changed
|
||||
*/
|
||||
default void onStateChanged() { }
|
||||
|
||||
/*
|
||||
* Extension points for providing custom behavior on certain user interactions.
|
||||
*/
|
||||
void onLauncherProviderChange();
|
||||
|
||||
/**
|
||||
* Starts a search with {@param initialQuery}. Return false if search was not started.
|
||||
|
||||
@@ -15,8 +15,13 @@ public class LauncherFiles {
|
||||
private static final String XML = ".xml";
|
||||
|
||||
public static final String LAUNCHER_DB = "launcher.db";
|
||||
public static final String LAUNCHER_4_BY_4_DB = "launcher_4_by_4.db";
|
||||
public static final String LAUNCHER_3_BY_3_DB = "launcher_3_by_3.db";
|
||||
public static final String LAUNCHER_2_BY_2_DB = "launcher_2_by_2.db";
|
||||
public static final String BACKUP_DB = "backup.db";
|
||||
public static final String SHARED_PREFERENCES_KEY = "com.android.launcher3.prefs";
|
||||
public static final String MANAGED_USER_PREFERENCES_KEY = "com.android.launcher3.managedusers.prefs";
|
||||
public static final String MANAGED_USER_PREFERENCES_KEY =
|
||||
"com.android.launcher3.managedusers.prefs";
|
||||
// This preference file is not backed up to cloud.
|
||||
public static final String DEVICE_PREFERENCES_KEY = "com.android.launcher3.device.prefs";
|
||||
|
||||
@@ -25,6 +30,10 @@ public class LauncherFiles {
|
||||
|
||||
public static final List<String> ALL_FILES = Collections.unmodifiableList(Arrays.asList(
|
||||
LAUNCHER_DB,
|
||||
LAUNCHER_4_BY_4_DB,
|
||||
LAUNCHER_3_BY_3_DB,
|
||||
LAUNCHER_2_BY_2_DB,
|
||||
BACKUP_DB,
|
||||
SHARED_PREFERENCES_KEY + XML,
|
||||
WIDGET_PREVIEWS_DB,
|
||||
MANAGED_USER_PREFERENCES_KEY + XML,
|
||||
|
||||
@@ -17,27 +17,26 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.LauncherAppState.ACTION_FORCE_ROLOAD;
|
||||
import static com.android.launcher3.config.FeatureFlags.IS_DOGFOOD_BUILD;
|
||||
import static com.android.launcher3.config.FeatureFlags.IS_STUDIO_BUILD;
|
||||
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
|
||||
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
|
||||
import static com.android.launcher3.util.PackageManagerHelper.hasShortcutsPermission;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.pm.PackageInstaller;
|
||||
import android.content.pm.ShortcutInfo;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
import android.util.Pair;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.WorkerThread;
|
||||
|
||||
import com.android.launcher3.compat.LauncherAppsCompat;
|
||||
import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.icons.IconCache;
|
||||
import com.android.launcher3.icons.LauncherIcons;
|
||||
import com.android.launcher3.logging.FileLog;
|
||||
import com.android.launcher3.model.AddWorkspaceItemsTask;
|
||||
import com.android.launcher3.model.AllAppsList;
|
||||
@@ -52,16 +51,21 @@ import com.android.launcher3.model.PackageInstallStateChangedTask;
|
||||
import com.android.launcher3.model.PackageUpdatedTask;
|
||||
import com.android.launcher3.model.ShortcutsChangedTask;
|
||||
import com.android.launcher3.model.UserLockStateChangedTask;
|
||||
import com.android.launcher3.shortcuts.DeepShortcutManager;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
import com.android.launcher3.pm.InstallSessionTracker;
|
||||
import com.android.launcher3.pm.PackageInstallInfo;
|
||||
import com.android.launcher3.pm.UserCache;
|
||||
import com.android.launcher3.shortcuts.ShortcutRequest;
|
||||
import com.android.launcher3.util.IntSparseArrayMap;
|
||||
import com.android.launcher3.util.ItemInfoMatcher;
|
||||
import com.android.launcher3.util.LooperExecutor;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
import com.android.launcher3.util.Preconditions;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
|
||||
import java.io.FileDescriptor;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -74,17 +78,17 @@ import java.util.function.Supplier;
|
||||
* LauncherModel object held in a static. Also provide APIs for updating the database state
|
||||
* for the Launcher.
|
||||
*/
|
||||
public class LauncherModel extends BroadcastReceiver
|
||||
implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
|
||||
public class LauncherModel extends LauncherApps.Callback implements InstallSessionTracker.Callback {
|
||||
private static final boolean DEBUG_RECEIVER = false;
|
||||
|
||||
static final String TAG = "Launcher.Model";
|
||||
|
||||
@Thunk final LauncherAppState mApp;
|
||||
@Thunk final Object mLock = new Object();
|
||||
@Thunk
|
||||
LoaderTask mLoaderTask;
|
||||
@Thunk boolean mIsLoaderTaskRunning;
|
||||
private final LauncherAppState mApp;
|
||||
private final Object mLock = new Object();
|
||||
private final LooperExecutor mMainExecutor = MAIN_EXECUTOR;
|
||||
|
||||
private LoaderTask mLoaderTask;
|
||||
private boolean mIsLoaderTaskRunning;
|
||||
|
||||
// Indicates whether the current model data is valid or not.
|
||||
// We start off with everything not loaded. After that, we assume that
|
||||
@@ -97,7 +101,7 @@ public class LauncherModel extends BroadcastReceiver
|
||||
}
|
||||
}
|
||||
|
||||
@Thunk WeakReference<Callbacks> mCallbacks;
|
||||
private final ArrayList<Callbacks> mCallbacksList = new ArrayList<>(1);
|
||||
|
||||
// < only access in worker thread >
|
||||
private final AllAppsList mBgAllAppsList;
|
||||
@@ -106,18 +110,15 @@ public class LauncherModel extends BroadcastReceiver
|
||||
* All the static data should be accessed on the background thread, A lock should be acquired
|
||||
* on this object when accessing any data from this model.
|
||||
*/
|
||||
static final BgDataModel sBgDataModel = new BgDataModel();
|
||||
private final BgDataModel mBgDataModel = new BgDataModel();
|
||||
|
||||
// Runnable to check if the shortcuts permission has changed.
|
||||
private final Runnable mShortcutPermissionCheckRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mModelLoaded) {
|
||||
boolean hasShortcutHostPermission =
|
||||
DeepShortcutManager.getInstance(mApp.getContext()).hasHostPermission();
|
||||
if (hasShortcutHostPermission != sBgDataModel.hasShortcutHostPermission) {
|
||||
forceReload();
|
||||
}
|
||||
if (mModelLoaded && hasShortcutsPermission(mApp.getContext())
|
||||
!= mBgAllAppsList.hasShortcutHostPermission()) {
|
||||
forceReload();
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -127,76 +128,27 @@ public class LauncherModel extends BroadcastReceiver
|
||||
mBgAllAppsList = new AllAppsList(iconCache, appFilter);
|
||||
}
|
||||
|
||||
public void setPackageState(PackageInstallInfo installInfo) {
|
||||
enqueueModelUpdateTask(new PackageInstallStateChangedTask(installInfo));
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the icons and label of all pending icons for the provided package name.
|
||||
*/
|
||||
public void updateSessionDisplayInfo(final String packageName, final UserHandle user) {
|
||||
HashSet<String> packages = new HashSet<>();
|
||||
packages.add(packageName);
|
||||
enqueueModelUpdateTask(new CacheDataUpdatedTask(
|
||||
CacheDataUpdatedTask.OP_SESSION_UPDATE, user, packages));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the provided items to the workspace.
|
||||
*/
|
||||
public void addAndBindAddedWorkspaceItems(List<Pair<ItemInfo, Object>> itemList) {
|
||||
Callbacks callbacks = getCallback();
|
||||
if (callbacks != null) {
|
||||
callbacks.preAddApps();
|
||||
for (Callbacks cb : getCallbacks()) {
|
||||
cb.preAddApps();
|
||||
}
|
||||
enqueueModelUpdateTask(new AddWorkspaceItemsTask(itemList));
|
||||
}
|
||||
|
||||
public ModelWriter getWriter(boolean hasVerticalHotseat, boolean verifyChanges) {
|
||||
return new ModelWriter(mApp.getContext(), this, sBgDataModel,
|
||||
return new ModelWriter(mApp.getContext(), this, mBgDataModel,
|
||||
hasVerticalHotseat, verifyChanges);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set this as the current Launcher activity object for the loader.
|
||||
*/
|
||||
public void initialize(Callbacks callbacks) {
|
||||
synchronized (mLock) {
|
||||
Preconditions.assertUIThread();
|
||||
mCallbacks = new WeakReference<>(callbacks);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackageChanged(String packageName, UserHandle user) {
|
||||
int op = PackageUpdatedTask.OP_UPDATE;
|
||||
enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packageName));
|
||||
}
|
||||
|
||||
public void onSessionFailure(String packageName, UserHandle user) {
|
||||
enqueueModelUpdateTask(new BaseModelUpdateTask() {
|
||||
@Override
|
||||
public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
|
||||
final IntSparseArrayMap<Boolean> removedIds = new IntSparseArrayMap<>();
|
||||
synchronized (dataModel) {
|
||||
for (ItemInfo info : dataModel.itemsIdMap) {
|
||||
if (info instanceof WorkspaceItemInfo
|
||||
&& ((WorkspaceItemInfo) info).hasPromiseIconUi()
|
||||
&& user.equals(info.user)
|
||||
&& info.getIntent() != null
|
||||
&& TextUtils.equals(packageName, info.getIntent().getPackage())) {
|
||||
removedIds.put(info.id, true /* remove */);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!removedIds.isEmpty()) {
|
||||
deleteAndBindComponentsRemoved(ItemInfoMatcher.ofItemIds(removedIds, false));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackageRemoved(String packageName, UserHandle user) {
|
||||
onPackagesRemoved(user, packageName);
|
||||
@@ -204,7 +156,7 @@ public class LauncherModel extends BroadcastReceiver
|
||||
|
||||
public void onPackagesRemoved(UserHandle user, String... packages) {
|
||||
int op = PackageUpdatedTask.OP_REMOVE;
|
||||
FileLog.d(TAG, "package removed received " + String.join("," + packages));
|
||||
FileLog.d(TAG, "package removed received " + TextUtils.join(",", packages));
|
||||
enqueueModelUpdateTask(new PackageUpdatedTask(op, user, packages));
|
||||
}
|
||||
|
||||
@@ -248,26 +200,29 @@ public class LauncherModel extends BroadcastReceiver
|
||||
enqueueModelUpdateTask(new ShortcutsChangedTask(packageName, shortcuts, user, true));
|
||||
}
|
||||
|
||||
public void updatePinnedShortcuts(String packageName, List<ShortcutInfo> shortcuts,
|
||||
UserHandle user) {
|
||||
enqueueModelUpdateTask(new ShortcutsChangedTask(packageName, shortcuts, user, false));
|
||||
/**
|
||||
* Called when the icon for an app changes, outside of package event
|
||||
*/
|
||||
@WorkerThread
|
||||
public void onAppIconChanged(String packageName, UserHandle user) {
|
||||
// Update the icon for the calendar package
|
||||
Context context = mApp.getContext();
|
||||
onPackageChanged(packageName, user);
|
||||
|
||||
List<ShortcutInfo> pinnedShortcuts = new ShortcutRequest(context, user)
|
||||
.forPackage(packageName).query(ShortcutRequest.PINNED);
|
||||
if (!pinnedShortcuts.isEmpty()) {
|
||||
enqueueModelUpdateTask(new ShortcutsChangedTask(packageName, pinnedShortcuts, user,
|
||||
false));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
|
||||
* ACTION_PACKAGE_CHANGED.
|
||||
*/
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
public void onBroadcastIntent(Intent intent) {
|
||||
if (DEBUG_RECEIVER) Log.d(TAG, "onReceive intent=" + intent);
|
||||
final String action = intent.getAction();
|
||||
if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
|
||||
// If we have changed locale we need to clear out the labels in all apps/workspace.
|
||||
forceReload();
|
||||
} else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
|
||||
|| Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
|
||||
UserManagerCompat.getInstance(context).enableAndResetCache();
|
||||
forceReload();
|
||||
} else if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) ||
|
||||
Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) ||
|
||||
Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) {
|
||||
@@ -283,25 +238,24 @@ public class LauncherModel extends BroadcastReceiver
|
||||
// we need to run the state change task again.
|
||||
if (Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) ||
|
||||
Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) {
|
||||
enqueueModelUpdateTask(new UserLockStateChangedTask(user));
|
||||
enqueueModelUpdateTask(new UserLockStateChangedTask(
|
||||
user, Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)));
|
||||
}
|
||||
}
|
||||
} else if (IS_STUDIO_BUILD && ACTION_FORCE_ROLOAD.equals(action)) {
|
||||
for (Callbacks cb : getCallbacks()) {
|
||||
if (cb instanceof Launcher) {
|
||||
((Launcher) cb).recreate();
|
||||
}
|
||||
}
|
||||
} else if (IS_DOGFOOD_BUILD && ACTION_FORCE_ROLOAD.equals(action)) {
|
||||
Launcher l = (Launcher) getCallback();
|
||||
l.reload();
|
||||
}
|
||||
}
|
||||
|
||||
public void forceReload() {
|
||||
forceReload(-1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the workspace items from the DB and re-binds the workspace. This should generally
|
||||
* not be called as DB updates are automatically followed by UI update
|
||||
* @param synchronousBindPage The page to bind first. Can pass -1 to use the current page.
|
||||
*/
|
||||
public void forceReload(int synchronousBindPage) {
|
||||
public void forceReload() {
|
||||
synchronized (mLock) {
|
||||
// Stop any existing loaders first, so they don't set mModelLoaded to true later
|
||||
stopLoader();
|
||||
@@ -310,37 +264,77 @@ public class LauncherModel extends BroadcastReceiver
|
||||
|
||||
// Start the loader if launcher is already running, otherwise the loader will run,
|
||||
// the next time launcher starts
|
||||
Callbacks callbacks = getCallback();
|
||||
if (callbacks != null) {
|
||||
if (synchronousBindPage < 0) {
|
||||
synchronousBindPage = callbacks.getCurrentWorkspaceScreen();
|
||||
}
|
||||
startLoader(synchronousBindPage);
|
||||
if (hasCallbacks()) {
|
||||
startLoader();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isCurrentCallbacks(Callbacks callbacks) {
|
||||
return (mCallbacks != null && mCallbacks.get() == callbacks);
|
||||
/**
|
||||
* Rebinds all existing callbacks with already loaded model
|
||||
*/
|
||||
public void rebindCallbacks() {
|
||||
if (hasCallbacks()) {
|
||||
startLoader();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an existing callback
|
||||
*/
|
||||
public void removeCallbacks(Callbacks callbacks) {
|
||||
synchronized (mCallbacksList) {
|
||||
Preconditions.assertUIThread();
|
||||
if (mCallbacksList.remove(callbacks)) {
|
||||
if (stopLoader()) {
|
||||
// Rebind existing callbacks
|
||||
startLoader();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a callbacks to receive model updates
|
||||
* @return true if workspace load was performed synchronously
|
||||
*/
|
||||
public boolean addCallbacksAndLoad(Callbacks callbacks) {
|
||||
synchronized (mLock) {
|
||||
addCallbacks(callbacks);
|
||||
return startLoader();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a callbacks to receive model updates
|
||||
*/
|
||||
public void addCallbacks(Callbacks callbacks) {
|
||||
Preconditions.assertUIThread();
|
||||
synchronized (mCallbacksList) {
|
||||
mCallbacksList.add(callbacks);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the loader. Tries to bind {@params synchronousBindPage} synchronously if possible.
|
||||
* @return true if the page could be bound synchronously.
|
||||
*/
|
||||
public boolean startLoader(int synchronousBindPage) {
|
||||
public boolean startLoader() {
|
||||
// Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems
|
||||
InstallShortcutReceiver.enableInstallQueue(InstallShortcutReceiver.FLAG_LOADER_RUNNING);
|
||||
synchronized (mLock) {
|
||||
// Don't bother to start the thread if we know it's not going to do anything
|
||||
if (mCallbacks != null && mCallbacks.get() != null) {
|
||||
final Callbacks oldCallbacks = mCallbacks.get();
|
||||
final Callbacks[] callbacksList = getCallbacks();
|
||||
if (callbacksList.length > 0) {
|
||||
// Clear any pending bind-runnables from the synchronized load process.
|
||||
MAIN_EXECUTOR.execute(oldCallbacks::clearPendingBinds);
|
||||
for (Callbacks cb : callbacksList) {
|
||||
mMainExecutor.execute(cb::clearPendingBinds);
|
||||
}
|
||||
|
||||
// If there is already one running, tell it to stop.
|
||||
stopLoader();
|
||||
LoaderResults loaderResults = new LoaderResults(mApp, sBgDataModel,
|
||||
mBgAllAppsList, synchronousBindPage, mCallbacks);
|
||||
LoaderResults loaderResults = new LoaderResults(
|
||||
mApp, mBgDataModel, mBgAllAppsList, callbacksList, mMainExecutor);
|
||||
if (mModelLoaded && !mIsLoaderTaskRunning) {
|
||||
// Divide the set of loaded items into those that we are binding synchronously,
|
||||
// and everything else that is to be bound normally (asynchronously).
|
||||
@@ -361,21 +355,24 @@ public class LauncherModel extends BroadcastReceiver
|
||||
|
||||
/**
|
||||
* If there is already a loader task running, tell it to stop.
|
||||
* @return true if an existing loader was stopped.
|
||||
*/
|
||||
public void stopLoader() {
|
||||
public boolean stopLoader() {
|
||||
synchronized (mLock) {
|
||||
LoaderTask oldTask = mLoaderTask;
|
||||
mLoaderTask = null;
|
||||
if (oldTask != null) {
|
||||
oldTask.stopLocked();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void startLoaderForResults(LoaderResults results) {
|
||||
synchronized (mLock) {
|
||||
stopLoader();
|
||||
mLoaderTask = new LoaderTask(mApp, mBgAllAppsList, sBgDataModel, results);
|
||||
mLoaderTask = new LoaderTask(mApp, mBgAllAppsList, mBgDataModel, results);
|
||||
|
||||
// Always post the loader task, instead of running directly (even on same thread) so
|
||||
// that we exit any nested synchronized blocks
|
||||
@@ -392,16 +389,65 @@ public class LauncherModel extends BroadcastReceiver
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onInstallSessionCreated(final PackageInstallInfo sessionInfo) {
|
||||
if (FeatureFlags.PROMISE_APPS_IN_ALL_APPS.get()) {
|
||||
enqueueModelUpdateTask(new BaseModelUpdateTask() {
|
||||
@Override
|
||||
public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
|
||||
apps.addPromiseApp(app.getContext(), sessionInfo);
|
||||
bindApplicationsIfNeeded();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSessionFailure(String packageName, UserHandle user) {
|
||||
if (!FeatureFlags.PROMISE_APPS_NEW_INSTALLS.get()) {
|
||||
return;
|
||||
}
|
||||
enqueueModelUpdateTask(new BaseModelUpdateTask() {
|
||||
@Override
|
||||
public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
|
||||
apps.addPromiseApp(app.getContext(), sessionInfo);
|
||||
bindApplicationsIfNeeded();
|
||||
final IntSparseArrayMap<Boolean> removedIds = new IntSparseArrayMap<>();
|
||||
synchronized (dataModel) {
|
||||
for (ItemInfo info : dataModel.itemsIdMap) {
|
||||
if (info instanceof WorkspaceItemInfo
|
||||
&& ((WorkspaceItemInfo) info).hasPromiseIconUi()
|
||||
&& user.equals(info.user)
|
||||
&& info.getIntent() != null
|
||||
&& TextUtils.equals(packageName, info.getIntent().getPackage())) {
|
||||
removedIds.put(info.id, true /* remove */);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!removedIds.isEmpty()) {
|
||||
deleteAndBindComponentsRemoved(ItemInfoMatcher.ofItemIds(removedIds, false));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackageStateChanged(PackageInstallInfo installInfo) {
|
||||
enqueueModelUpdateTask(new PackageInstallStateChangedTask(installInfo));
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the icons and label of all pending icons for the provided package name.
|
||||
*/
|
||||
@Override
|
||||
public void onUpdateSessionDisplay(PackageUserKey key, PackageInstaller.SessionInfo info) {
|
||||
mApp.getIconCache().updateSessionCache(key, info);
|
||||
|
||||
HashSet<String> packages = new HashSet<>();
|
||||
packages.add(key.mPackageName);
|
||||
enqueueModelUpdateTask(new CacheDataUpdatedTask(
|
||||
CacheDataUpdatedTask.OP_SESSION_UPDATE, key.mUser, packages));
|
||||
}
|
||||
|
||||
public class LoaderTransaction implements AutoCloseable {
|
||||
|
||||
private final LoaderTask mTask;
|
||||
@@ -443,7 +489,7 @@ public class LauncherModel extends BroadcastReceiver
|
||||
/**
|
||||
* Refreshes the cached shortcuts if the shortcut permission has changed.
|
||||
* Current implementation simply reloads the workspace, but it can be optimized to
|
||||
* use partial updates similar to {@link UserManagerCompat}
|
||||
* use partial updates similar to {@link UserCache}
|
||||
*/
|
||||
public void refreshShortcutsIfRequired() {
|
||||
MODEL_EXECUTOR.getHandler().removeCallbacks(mShortcutPermissionCheckRunnable);
|
||||
@@ -474,7 +520,7 @@ public class LauncherModel extends BroadcastReceiver
|
||||
}
|
||||
|
||||
public void enqueueModelUpdateTask(ModelUpdateTask task) {
|
||||
task.init(mApp, this, sBgDataModel, mBgAllAppsList, MAIN_EXECUTOR);
|
||||
task.init(mApp, this, mBgDataModel, mBgAllAppsList, mMainExecutor);
|
||||
MODEL_EXECUTOR.execute(task);
|
||||
}
|
||||
|
||||
@@ -503,9 +549,7 @@ public class LauncherModel extends BroadcastReceiver
|
||||
public void updateAndBindWorkspaceItem(WorkspaceItemInfo si, ShortcutInfo info) {
|
||||
updateAndBindWorkspaceItem(() -> {
|
||||
si.updateFromDeepShortcutInfo(info, mApp.getContext());
|
||||
LauncherIcons li = LauncherIcons.obtain(mApp.getContext());
|
||||
si.applyFrom(li.createShortcutIcon(info));
|
||||
li.recycle();
|
||||
mApp.getIconCache().getShortcutIcon(si, info);
|
||||
return si;
|
||||
});
|
||||
}
|
||||
@@ -540,14 +584,29 @@ public class LauncherModel extends BroadcastReceiver
|
||||
if (args.length > 0 && TextUtils.equals(args[0], "--all")) {
|
||||
writer.println(prefix + "All apps list: size=" + mBgAllAppsList.data.size());
|
||||
for (AppInfo info : mBgAllAppsList.data) {
|
||||
writer.println(prefix + " title=\"" + info.title + "\" iconBitmap=" + info.iconBitmap
|
||||
writer.println(prefix + " title=\"" + info.title
|
||||
+ "\" bitmapIcon=" + info.bitmap.icon
|
||||
+ " componentName=" + info.componentName.getPackageName());
|
||||
}
|
||||
}
|
||||
sBgDataModel.dump(prefix, fd, writer, args);
|
||||
mBgDataModel.dump(prefix, fd, writer, args);
|
||||
}
|
||||
|
||||
public Callbacks getCallback() {
|
||||
return mCallbacks != null ? mCallbacks.get() : null;
|
||||
/**
|
||||
* Returns true if there are any callbacks attached to the model
|
||||
*/
|
||||
public boolean hasCallbacks() {
|
||||
synchronized (mCallbacksList) {
|
||||
return !mCallbacksList.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of currently attached callbacks
|
||||
*/
|
||||
public Callbacks[] getCallbacks() {
|
||||
synchronized (mCallbacksList) {
|
||||
return mCallbacksList.toArray(new Callbacks[mCallbacksList.size()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
|
||||
import static com.android.launcher3.provider.LauncherDbUtils.copyTable;
|
||||
import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
|
||||
import static com.android.launcher3.provider.LauncherDbUtils.tableExists;
|
||||
|
||||
@@ -45,10 +47,9 @@ import android.net.Uri;
|
||||
import android.os.Binder;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Message;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
import android.os.UserManager;
|
||||
import android.provider.BaseColumns;
|
||||
import android.provider.Settings;
|
||||
import android.text.TextUtils;
|
||||
@@ -57,10 +58,10 @@ import android.util.Xml;
|
||||
|
||||
import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
|
||||
import com.android.launcher3.LauncherSettings.Favorites;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.logging.FileLog;
|
||||
import com.android.launcher3.model.DbDowngradeHelper;
|
||||
import com.android.launcher3.pm.UserCache;
|
||||
import com.android.launcher3.provider.LauncherDbUtils;
|
||||
import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
|
||||
import com.android.launcher3.provider.RestoreDbTask;
|
||||
@@ -69,7 +70,6 @@ import com.android.launcher3.util.IntArray;
|
||||
import com.android.launcher3.util.IntSet;
|
||||
import com.android.launcher3.util.NoLocaleSQLiteHelper;
|
||||
import com.android.launcher3.util.PackageManagerHelper;
|
||||
import com.android.launcher3.util.Preconditions;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
|
||||
import org.xmlpull.v1.XmlPullParser;
|
||||
@@ -83,12 +83,15 @@ import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LauncherProvider extends ContentProvider {
|
||||
private static final String TAG = "LauncherProvider";
|
||||
private static final boolean LOGD = false;
|
||||
|
||||
private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
|
||||
private static final long RESTORE_BACKUP_TABLE_DELAY = TimeUnit.SECONDS.toMillis(30);
|
||||
|
||||
/**
|
||||
* Represents the schema of the database. Changes in scheme need not be backwards compatible.
|
||||
@@ -100,11 +103,10 @@ public class LauncherProvider extends ContentProvider {
|
||||
|
||||
static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
|
||||
|
||||
private final ChangeListenerWrapper mListenerWrapper = new ChangeListenerWrapper();
|
||||
private Handler mListenerHandler;
|
||||
|
||||
protected DatabaseHelper mOpenHelper;
|
||||
|
||||
private long mLastRestoreTimestamp = 0L;
|
||||
|
||||
/**
|
||||
* $ adb shell dumpsys activity provider com.android.launcher3
|
||||
*/
|
||||
@@ -119,10 +121,9 @@ public class LauncherProvider extends ContentProvider {
|
||||
|
||||
@Override
|
||||
public boolean onCreate() {
|
||||
if (FeatureFlags.IS_DOGFOOD_BUILD) {
|
||||
if (FeatureFlags.IS_STUDIO_BUILD) {
|
||||
Log.d(TAG, "Launcher process started");
|
||||
}
|
||||
mListenerHandler = new Handler(mListenerWrapper);
|
||||
|
||||
// The content provider exists for the entire duration of the launcher main process and
|
||||
// is the first component to get created.
|
||||
@@ -130,14 +131,6 @@ public class LauncherProvider extends ContentProvider {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a provider listener.
|
||||
*/
|
||||
public void setLauncherProviderChangeListener(LauncherProviderChangeListener listener) {
|
||||
Preconditions.assertUIThread();
|
||||
mListenerWrapper.mListener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getType(Uri uri) {
|
||||
SqlArguments args = new SqlArguments(uri, null, null);
|
||||
@@ -153,7 +146,8 @@ public class LauncherProvider extends ContentProvider {
|
||||
*/
|
||||
protected synchronized void createDbIfNotExists() {
|
||||
if (mOpenHelper == null) {
|
||||
mOpenHelper = new DatabaseHelper(getContext(), mListenerHandler);
|
||||
mOpenHelper = DatabaseHelper.createDatabaseHelper(
|
||||
getContext(), false /* forMigration */);
|
||||
|
||||
if (RestoreDbTask.isPending(getContext())) {
|
||||
if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
|
||||
@@ -167,6 +161,20 @@ public class LauncherProvider extends ContentProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized boolean prepForMigration(String dbFile, String targetTableName,
|
||||
Supplier<DatabaseHelper> src, Supplier<DatabaseHelper> dst) {
|
||||
if (TextUtils.equals(dbFile, mOpenHelper.getDatabaseName())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final DatabaseHelper helper = src.get();
|
||||
mOpenHelper = dst.get();
|
||||
copyTable(helper.getReadableDatabase(), Favorites.TABLE_NAME,
|
||||
mOpenHelper.getWritableDatabase(), targetTableName, getContext());
|
||||
helper.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cursor query(Uri uri, String[] projection, String selection,
|
||||
String[] selectionArgs, String sortOrder) {
|
||||
@@ -220,10 +228,9 @@ public class LauncherProvider extends ContentProvider {
|
||||
addModifiedTime(initialValues);
|
||||
final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
|
||||
if (rowId < 0) return null;
|
||||
mOpenHelper.onAddOrDeleteOp(db);
|
||||
onAddOrDeleteOp(db);
|
||||
|
||||
uri = ContentUris.withAppendedId(uri, rowId);
|
||||
notifyListeners();
|
||||
reloadLauncherIfExternal();
|
||||
return uri;
|
||||
}
|
||||
@@ -279,11 +286,10 @@ public class LauncherProvider extends ContentProvider {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
mOpenHelper.onAddOrDeleteOp(db);
|
||||
onAddOrDeleteOp(db);
|
||||
t.commit();
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
reloadLauncherIfExternal();
|
||||
return values.length;
|
||||
}
|
||||
@@ -306,7 +312,7 @@ public class LauncherProvider extends ContentProvider {
|
||||
results[i].count != null && results[i].count > 0;
|
||||
}
|
||||
if (isAddOrDelete) {
|
||||
mOpenHelper.onAddOrDeleteOp(t.getDb());
|
||||
onAddOrDeleteOp(t.getDb());
|
||||
}
|
||||
|
||||
t.commit();
|
||||
@@ -328,8 +334,7 @@ public class LauncherProvider extends ContentProvider {
|
||||
}
|
||||
int count = db.delete(args.table, args.where, args.args);
|
||||
if (count > 0) {
|
||||
mOpenHelper.onAddOrDeleteOp(db);
|
||||
notifyListeners();
|
||||
onAddOrDeleteOp(db);
|
||||
reloadLauncherIfExternal();
|
||||
}
|
||||
return count;
|
||||
@@ -343,8 +348,6 @@ public class LauncherProvider extends ContentProvider {
|
||||
addModifiedTime(values);
|
||||
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
|
||||
int count = db.update(args.table, values, args.where, args.args);
|
||||
if (count > 0) notifyListeners();
|
||||
|
||||
reloadLauncherIfExternal();
|
||||
return count;
|
||||
}
|
||||
@@ -375,12 +378,14 @@ public class LauncherProvider extends ContentProvider {
|
||||
}
|
||||
case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
|
||||
Bundle result = new Bundle();
|
||||
result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
|
||||
result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
|
||||
mOpenHelper.generateNewItemId());
|
||||
return result;
|
||||
}
|
||||
case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
|
||||
Bundle result = new Bundle();
|
||||
result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
|
||||
result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
|
||||
mOpenHelper.generateNewScreenId());
|
||||
return result;
|
||||
}
|
||||
case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
|
||||
@@ -402,14 +407,58 @@ public class LauncherProvider extends ContentProvider {
|
||||
return result;
|
||||
}
|
||||
case LauncherSettings.Settings.METHOD_REFRESH_BACKUP_TABLE: {
|
||||
mOpenHelper.mBackupTableExists =
|
||||
tableExists(mOpenHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
|
||||
mOpenHelper.mBackupTableExists = tableExists(mOpenHelper.getReadableDatabase(),
|
||||
Favorites.BACKUP_TABLE_NAME);
|
||||
return null;
|
||||
}
|
||||
case LauncherSettings.Settings.METHOD_REFRESH_HOTSEAT_RESTORE_TABLE: {
|
||||
mOpenHelper.mHotseatRestoreTableExists = tableExists(
|
||||
mOpenHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
|
||||
return null;
|
||||
}
|
||||
case LauncherSettings.Settings.METHOD_RESTORE_BACKUP_TABLE: {
|
||||
final long ts = System.currentTimeMillis();
|
||||
if (ts - mLastRestoreTimestamp > RESTORE_BACKUP_TABLE_DELAY) {
|
||||
mLastRestoreTimestamp = ts;
|
||||
RestoreDbTask.restoreIfPossible(
|
||||
getContext(), mOpenHelper, new BackupManager(getContext()));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
|
||||
if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
|
||||
Bundle result = new Bundle();
|
||||
result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
|
||||
prepForMigration(
|
||||
InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
|
||||
Favorites.TMP_TABLE,
|
||||
() -> mOpenHelper,
|
||||
() -> DatabaseHelper.createDatabaseHelper(
|
||||
getContext(), true /* forMigration */)));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
|
||||
if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
|
||||
Bundle result = new Bundle();
|
||||
result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
|
||||
prepForMigration(
|
||||
arg /* dbFile */,
|
||||
Favorites.PREVIEW_TABLE_NAME,
|
||||
() -> DatabaseHelper.createDatabaseHelper(
|
||||
getContext(), arg, true /* forMigration */),
|
||||
() -> mOpenHelper));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void onAddOrDeleteOp(SQLiteDatabase db) {
|
||||
mOpenHelper.onAddOrDeleteOp(db);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes any empty folder from the DB.
|
||||
* @return Ids of deleted folders.
|
||||
@@ -438,13 +487,6 @@ public class LauncherProvider extends ContentProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden in tests
|
||||
*/
|
||||
protected void notifyListeners() {
|
||||
mListenerHandler.sendEmptyMessage(ChangeListenerWrapper.MSG_LAUNCHER_PROVIDER_CHANGED);
|
||||
}
|
||||
|
||||
@Thunk static void addModifiedTime(ContentValues values) {
|
||||
values.put(LauncherSettings.Favorites.MODIFIED, System.currentTimeMillis());
|
||||
}
|
||||
@@ -511,8 +553,6 @@ public class LauncherProvider extends ContentProvider {
|
||||
*/
|
||||
private AutoInstallsLayout createWorkspaceLoaderFromAppRestriction(AppWidgetHost widgetHost) {
|
||||
Context ctx = getContext();
|
||||
InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
|
||||
|
||||
String authority = Settings.Secure.getString(ctx.getContentResolver(),
|
||||
"launcher3.layout.provider");
|
||||
if (TextUtils.isEmpty(authority)) {
|
||||
@@ -524,13 +564,7 @@ public class LauncherProvider extends ContentProvider {
|
||||
Log.e(TAG, "No provider found for authority " + authority);
|
||||
return null;
|
||||
}
|
||||
Uri uri = new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
|
||||
.appendQueryParameter("version", "1")
|
||||
.appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
|
||||
.appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
|
||||
.appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
|
||||
.build();
|
||||
|
||||
Uri uri = getLayoutUri(authority, ctx);
|
||||
try (InputStream in = ctx.getContentResolver().openInputStream(uri)) {
|
||||
// Read the full xml so that we fail early in case of any IO error.
|
||||
String layout = new String(IOUtils.toByteArray(in));
|
||||
@@ -547,12 +581,22 @@ public class LauncherProvider extends ContentProvider {
|
||||
}
|
||||
}
|
||||
|
||||
public static Uri getLayoutUri(String authority, Context ctx) {
|
||||
InvariantDeviceProfile grid = LauncherAppState.getIDP(ctx);
|
||||
return new Uri.Builder().scheme("content").authority(authority).path("launcher_layout")
|
||||
.appendQueryParameter("version", "1")
|
||||
.appendQueryParameter("gridWidth", Integer.toString(grid.numColumns))
|
||||
.appendQueryParameter("gridHeight", Integer.toString(grid.numRows))
|
||||
.appendQueryParameter("hotseatSize", Integer.toString(grid.numHotseatIcons))
|
||||
.build();
|
||||
}
|
||||
|
||||
private DefaultLayoutParser getDefaultLayoutParser(AppWidgetHost widgetHost) {
|
||||
InvariantDeviceProfile idp = LauncherAppState.getIDP(getContext());
|
||||
int defaultLayout = idp.defaultLayoutId;
|
||||
|
||||
UserManagerCompat um = UserManagerCompat.getInstance(getContext());
|
||||
if (um.isDemoUser() && idp.demoModeLayoutId != 0) {
|
||||
if (getContext().getSystemService(UserManager.class).isDemoUser()
|
||||
&& idp.demoModeLayoutId != 0) {
|
||||
defaultLayout = idp.demoModeLayoutId;
|
||||
}
|
||||
|
||||
@@ -563,38 +607,52 @@ public class LauncherProvider extends ContentProvider {
|
||||
/**
|
||||
* The class is subclassed in tests to create an in-memory db.
|
||||
*/
|
||||
public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
|
||||
private final BackupManager mBackupManager;
|
||||
private final Handler mWidgetHostResetHandler;
|
||||
public static class DatabaseHelper extends NoLocaleSQLiteHelper implements
|
||||
LayoutParserCallback {
|
||||
private final Context mContext;
|
||||
private final boolean mForMigration;
|
||||
private int mMaxItemId = -1;
|
||||
private int mMaxScreenId = -1;
|
||||
private boolean mBackupTableExists;
|
||||
private boolean mHotseatRestoreTableExists;
|
||||
|
||||
DatabaseHelper(Context context, Handler widgetHostResetHandler) {
|
||||
this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
|
||||
static DatabaseHelper createDatabaseHelper(Context context, boolean forMigration) {
|
||||
return createDatabaseHelper(context, null, forMigration);
|
||||
}
|
||||
|
||||
static DatabaseHelper createDatabaseHelper(Context context, String dbName,
|
||||
boolean forMigration) {
|
||||
if (dbName == null) {
|
||||
dbName = MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
|
||||
context).dbFile : LauncherFiles.LAUNCHER_DB;
|
||||
}
|
||||
DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
|
||||
// Table creation sometimes fails silently, which leads to a crash loop.
|
||||
// This way, we will try to create a table every time after crash, so the device
|
||||
// would eventually be able to recover.
|
||||
if (!tableExists(getReadableDatabase(), Favorites.TABLE_NAME)) {
|
||||
if (!tableExists(databaseHelper.getReadableDatabase(), Favorites.TABLE_NAME)) {
|
||||
Log.e(TAG, "Tables are missing after onCreate has been called. Trying to recreate");
|
||||
// This operation is a no-op if the table already exists.
|
||||
addFavoritesTable(getWritableDatabase(), true);
|
||||
databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
|
||||
}
|
||||
mBackupTableExists = tableExists(getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
|
||||
if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
|
||||
databaseHelper.mBackupTableExists = tableExists(
|
||||
databaseHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
|
||||
}
|
||||
databaseHelper.mHotseatRestoreTableExists = tableExists(
|
||||
databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
|
||||
|
||||
initIds();
|
||||
databaseHelper.initIds();
|
||||
return databaseHelper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor used in tests and for restore.
|
||||
*/
|
||||
public DatabaseHelper(
|
||||
Context context, Handler widgetHostResetHandler, String tableName) {
|
||||
super(context, tableName, SCHEMA_VERSION);
|
||||
public DatabaseHelper(Context context, String dbName, boolean forMigration) {
|
||||
super(context, dbName, SCHEMA_VERSION);
|
||||
mContext = context;
|
||||
mWidgetHostResetHandler = widgetHostResetHandler;
|
||||
mBackupManager = new BackupManager(mContext);
|
||||
mForMigration = forMigration;
|
||||
}
|
||||
|
||||
protected void initIds() {
|
||||
@@ -619,7 +677,9 @@ public class LauncherProvider extends ContentProvider {
|
||||
|
||||
// Fresh and clean launcher DB.
|
||||
mMaxItemId = initializeMaxItemId(db);
|
||||
onEmptyDbCreated();
|
||||
if (!mForMigration) {
|
||||
onEmptyDbCreated();
|
||||
}
|
||||
}
|
||||
|
||||
protected void onAddOrDeleteOp(SQLiteDatabase db) {
|
||||
@@ -627,25 +687,22 @@ public class LauncherProvider extends ContentProvider {
|
||||
dropTable(db, Favorites.BACKUP_TABLE_NAME);
|
||||
mBackupTableExists = false;
|
||||
}
|
||||
if (mHotseatRestoreTableExists) {
|
||||
dropTable(db, Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
|
||||
mHotseatRestoreTableExists = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Overriden in tests.
|
||||
*/
|
||||
protected void onEmptyDbCreated() {
|
||||
// Database was just created, so wipe any previous widgets
|
||||
if (mWidgetHostResetHandler != null) {
|
||||
newLauncherWidgetHost().deleteHost();
|
||||
mWidgetHostResetHandler.sendEmptyMessage(
|
||||
ChangeListenerWrapper.MSG_APP_WIDGET_HOST_RESET);
|
||||
}
|
||||
|
||||
// Set the flag for empty DB
|
||||
Utilities.getPrefs(mContext).edit().putBoolean(EMPTY_DATABASE_CREATED, true).commit();
|
||||
}
|
||||
|
||||
public long getSerialNumberForUser(UserHandle user) {
|
||||
return UserManagerCompat.getInstance(mContext).getSerialNumberForUser(user);
|
||||
return UserCache.INSTANCE.get(mContext).getSerialNumberForUser(user);
|
||||
}
|
||||
|
||||
public long getDefaultUserSerial() {
|
||||
@@ -676,7 +733,7 @@ public class LauncherProvider extends ContentProvider {
|
||||
*/
|
||||
protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
|
||||
// Remove "profile extra"
|
||||
UserManagerCompat um = UserManagerCompat.getInstance(mContext);
|
||||
UserCache um = UserCache.INSTANCE.get(mContext);
|
||||
for (UserHandle user : um.getUserProfiles()) {
|
||||
long serial = um.getSerialNumberForUser(user);
|
||||
String sql = "update favorites set intent = replace(intent, "
|
||||
@@ -1039,27 +1096,4 @@ public class LauncherProvider extends ContentProvider {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class ChangeListenerWrapper implements Handler.Callback {
|
||||
|
||||
private static final int MSG_LAUNCHER_PROVIDER_CHANGED = 1;
|
||||
private static final int MSG_APP_WIDGET_HOST_RESET = 2;
|
||||
|
||||
private LauncherProviderChangeListener mListener;
|
||||
|
||||
@Override
|
||||
public boolean handleMessage(Message msg) {
|
||||
if (mListener != null) {
|
||||
switch (msg.what) {
|
||||
case MSG_LAUNCHER_PROVIDER_CHANGED:
|
||||
mListener.onLauncherProviderChanged();
|
||||
break;
|
||||
case MSG_APP_WIDGET_HOST_RESET:
|
||||
mListener.onAppWidgetHostReset();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
/**
|
||||
* This class is a listener for {@link LauncherProvider} changes. It gets notified in the
|
||||
* sendNotify method. This listener is needed because by default the Launcher suppresses
|
||||
* standard data change callbacks.
|
||||
*/
|
||||
public interface LauncherProviderChangeListener {
|
||||
|
||||
void onLauncherProviderChanged();
|
||||
|
||||
void onAppWidgetHostReset();
|
||||
}
|
||||
@@ -1,22 +1,17 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.util.SystemUiController.FLAG_DARK_NAV;
|
||||
import static com.android.launcher3.util.SystemUiController.UI_STATE_ROOT_VIEW;
|
||||
import static com.android.launcher3.config.FeatureFlags.SEPARATE_RECENTS_ACTIVITY;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.ActivityManager;
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Insets;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Build;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.view.ViewDebug;
|
||||
import android.view.WindowInsets;
|
||||
|
||||
import com.android.launcher3.statemanager.StatefulActivity;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@@ -24,82 +19,31 @@ public class LauncherRootView extends InsettableFrameLayout {
|
||||
|
||||
private final Rect mTempRect = new Rect();
|
||||
|
||||
private final Launcher mLauncher;
|
||||
|
||||
private final Paint mOpaquePaint;
|
||||
|
||||
@ViewDebug.ExportedProperty(category = "launcher")
|
||||
private final Rect mConsumedInsets = new Rect();
|
||||
private final StatefulActivity mActivity;
|
||||
|
||||
@ViewDebug.ExportedProperty(category = "launcher")
|
||||
private static final List<Rect> SYSTEM_GESTURE_EXCLUSION_RECT =
|
||||
Collections.singletonList(new Rect());
|
||||
|
||||
private View mAlignedView;
|
||||
private WindowStateListener mWindowStateListener;
|
||||
@ViewDebug.ExportedProperty(category = "launcher")
|
||||
private boolean mDisallowBackGesture;
|
||||
@ViewDebug.ExportedProperty(category = "launcher")
|
||||
private boolean mForceHideBackArrow;
|
||||
|
||||
public LauncherRootView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
|
||||
mOpaquePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
mOpaquePaint.setColor(Color.BLACK);
|
||||
mOpaquePaint.setStyle(Paint.Style.FILL);
|
||||
|
||||
mLauncher = Launcher.getLauncher(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onFinishInflate() {
|
||||
if (getChildCount() > 0) {
|
||||
// LauncherRootView contains only one child, which should be aligned
|
||||
// based on the horizontal insets.
|
||||
mAlignedView = getChildAt(0);
|
||||
}
|
||||
super.onFinishInflate();
|
||||
mActivity = StatefulActivity.fromContext(context);
|
||||
}
|
||||
|
||||
private void handleSystemWindowInsets(Rect insets) {
|
||||
mConsumedInsets.setEmpty();
|
||||
boolean drawInsetBar = false;
|
||||
if (mLauncher.isInMultiWindowMode()
|
||||
&& (insets.left > 0 || insets.right > 0 || insets.bottom > 0)) {
|
||||
mConsumedInsets.left = insets.left;
|
||||
mConsumedInsets.right = insets.right;
|
||||
mConsumedInsets.bottom = insets.bottom;
|
||||
insets.set(0, insets.top, 0, 0);
|
||||
drawInsetBar = true;
|
||||
} else if ((insets.right > 0 || insets.left > 0) &&
|
||||
getContext().getSystemService(ActivityManager.class).isLowRamDevice()) {
|
||||
mConsumedInsets.left = insets.left;
|
||||
mConsumedInsets.right = insets.right;
|
||||
insets.set(0, insets.top, 0, insets.bottom);
|
||||
drawInsetBar = true;
|
||||
}
|
||||
|
||||
mLauncher.getSystemUiController().updateUiState(
|
||||
UI_STATE_ROOT_VIEW, drawInsetBar ? FLAG_DARK_NAV : 0);
|
||||
|
||||
// Update device profile before notifying th children.
|
||||
mLauncher.updateInsets(insets);
|
||||
mActivity.getDeviceProfile().updateInsets(insets);
|
||||
boolean resetState = !insets.equals(mInsets);
|
||||
setInsets(insets);
|
||||
|
||||
if (mAlignedView != null) {
|
||||
// Apply margins on aligned view to handle consumed insets.
|
||||
MarginLayoutParams lp = (MarginLayoutParams) mAlignedView.getLayoutParams();
|
||||
if (lp.leftMargin != mConsumedInsets.left || lp.rightMargin != mConsumedInsets.right ||
|
||||
lp.bottomMargin != mConsumedInsets.bottom) {
|
||||
lp.leftMargin = mConsumedInsets.left;
|
||||
lp.rightMargin = mConsumedInsets.right;
|
||||
lp.topMargin = mConsumedInsets.top;
|
||||
lp.bottomMargin = mConsumedInsets.bottom;
|
||||
mAlignedView.setLayoutParams(lp);
|
||||
}
|
||||
}
|
||||
if (resetState) {
|
||||
mLauncher.getStateManager().reapplyState(true /* cancelCurrentAnimation */);
|
||||
mActivity.getStateManager().reapplyState(true /* cancelCurrentAnimation */);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,12 +52,7 @@ public class LauncherRootView extends InsettableFrameLayout {
|
||||
mTempRect.set(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(),
|
||||
insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
|
||||
handleSystemWindowInsets(mTempRect);
|
||||
if (Utilities.ATLEAST_Q) {
|
||||
return insets.inset(mConsumedInsets.left, mConsumedInsets.top,
|
||||
mConsumedInsets.right, mConsumedInsets.bottom);
|
||||
} else {
|
||||
return insets.replaceSystemWindowInsets(mTempRect);
|
||||
}
|
||||
return insets;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -126,28 +65,10 @@ public class LauncherRootView extends InsettableFrameLayout {
|
||||
}
|
||||
|
||||
public void dispatchInsets() {
|
||||
mLauncher.updateInsets(mInsets);
|
||||
mActivity.getDeviceProfile().updateInsets(mInsets);
|
||||
super.setInsets(mInsets);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void dispatchDraw(Canvas canvas) {
|
||||
super.dispatchDraw(canvas);
|
||||
|
||||
// If the right inset is opaque, draw a black rectangle to ensure that is stays opaque.
|
||||
if (mConsumedInsets.right > 0) {
|
||||
int width = getWidth();
|
||||
canvas.drawRect(width - mConsumedInsets.right, 0, width, getHeight(), mOpaquePaint);
|
||||
}
|
||||
if (mConsumedInsets.left > 0) {
|
||||
canvas.drawRect(0, 0, mConsumedInsets.left, getHeight(), mOpaquePaint);
|
||||
}
|
||||
if (mConsumedInsets.bottom > 0) {
|
||||
int height = getHeight();
|
||||
canvas.drawRect(0, height - mConsumedInsets.bottom, getWidth(), height, mOpaquePaint);
|
||||
}
|
||||
}
|
||||
|
||||
public void setWindowStateListener(WindowStateListener listener) {
|
||||
mWindowStateListener = listener;
|
||||
}
|
||||
@@ -175,13 +96,19 @@ public class LauncherRootView extends InsettableFrameLayout {
|
||||
setDisallowBackGesture(mDisallowBackGesture);
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.Q)
|
||||
public void setForceHideBackArrow(boolean forceHideBackArrow) {
|
||||
this.mForceHideBackArrow = forceHideBackArrow;
|
||||
setDisallowBackGesture(mDisallowBackGesture);
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.Q)
|
||||
public void setDisallowBackGesture(boolean disallowBackGesture) {
|
||||
if (!Utilities.ATLEAST_Q) {
|
||||
if (!Utilities.ATLEAST_Q || SEPARATE_RECENTS_ACTIVITY.get()) {
|
||||
return;
|
||||
}
|
||||
mDisallowBackGesture = disallowBackGesture;
|
||||
setSystemGestureExclusionRects(mDisallowBackGesture
|
||||
setSystemGestureExclusionRects((mForceHideBackArrow || mDisallowBackGesture)
|
||||
? SYSTEM_GESTURE_EXCLUSION_RECT
|
||||
: Collections.emptyList());
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.provider.BaseColumns;
|
||||
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
|
||||
/**
|
||||
* Settings related utilities.
|
||||
*/
|
||||
@@ -93,15 +95,42 @@ public class LauncherSettings {
|
||||
public static final String TABLE_NAME = "favorites";
|
||||
|
||||
/**
|
||||
* Backup table created when when the favorites table is modified during grid migration
|
||||
* Backup table created when the favorites table is modified during grid migration
|
||||
*/
|
||||
public static final String BACKUP_TABLE_NAME = "favorites_bakup";
|
||||
|
||||
/**
|
||||
* The content:// style URL for this table
|
||||
* Backup table created when user hotseat is moved to workspace for hybrid hotseat
|
||||
*/
|
||||
public static final Uri CONTENT_URI = Uri.parse("content://" +
|
||||
LauncherProvider.AUTHORITY + "/" + TABLE_NAME);
|
||||
public static final String HYBRID_HOTSEAT_BACKUP_TABLE = "hotseat_restore_backup";
|
||||
|
||||
/**
|
||||
* Temporary table used specifically for grid migrations during wallpaper preview
|
||||
*/
|
||||
public static final String PREVIEW_TABLE_NAME = "favorites_preview";
|
||||
|
||||
/**
|
||||
* Temporary table used specifically for multi-db grid migrations
|
||||
*/
|
||||
public static final String TMP_TABLE = "favorites_tmp";
|
||||
|
||||
/**
|
||||
* The content:// style URL for "favorites" table
|
||||
*/
|
||||
public static final Uri CONTENT_URI = Uri.parse("content://"
|
||||
+ LauncherProvider.AUTHORITY + "/" + TABLE_NAME);
|
||||
|
||||
/**
|
||||
* The content:// style URL for "favorites_preview" table
|
||||
*/
|
||||
public static final Uri PREVIEW_CONTENT_URI = Uri.parse("content://"
|
||||
+ LauncherProvider.AUTHORITY + "/" + PREVIEW_TABLE_NAME);
|
||||
|
||||
/**
|
||||
* The content:// style URL for "favorites_tmp" table
|
||||
*/
|
||||
public static final Uri TMP_CONTENT_URI = Uri.parse("content://"
|
||||
+ LauncherProvider.AUTHORITY + "/" + TMP_TABLE);
|
||||
|
||||
/**
|
||||
* The content:// style URL for a given row, identified by its id.
|
||||
@@ -111,8 +140,8 @@ public class LauncherSettings {
|
||||
* @return The unique content URL for the specified row.
|
||||
*/
|
||||
public static Uri getContentUri(int id) {
|
||||
return Uri.parse("content://" + LauncherProvider.AUTHORITY +
|
||||
"/" + TABLE_NAME + "/" + id);
|
||||
return Uri.parse("content://" + LauncherProvider.AUTHORITY
|
||||
+ "/" + TABLE_NAME + "/" + id);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,17 +156,29 @@ public class LauncherSettings {
|
||||
public static final int CONTAINER_DESKTOP = -100;
|
||||
public static final int CONTAINER_HOTSEAT = -101;
|
||||
public static final int CONTAINER_PREDICTION = -102;
|
||||
public static final int CONTAINER_HOTSEAT_PREDICTION = -103;
|
||||
public static final int CONTAINER_ALL_APPS = -104;
|
||||
public static final int CONTAINER_WIDGETS_TRAY = -105;
|
||||
// Represents search results view.
|
||||
public static final int CONTAINER_SEARCH_RESULTS = -106;
|
||||
public static final int CONTAINER_SHORTCUTS = -107;
|
||||
public static final int CONTAINER_SETTINGS = -108;
|
||||
public static final int CONTAINER_TASKSWITCHER = -109;
|
||||
|
||||
static final String containerToString(int container) {
|
||||
public static final String containerToString(int container) {
|
||||
switch (container) {
|
||||
case CONTAINER_DESKTOP: return "desktop";
|
||||
case CONTAINER_HOTSEAT: return "hotseat";
|
||||
case CONTAINER_PREDICTION: return "prediction";
|
||||
case CONTAINER_ALL_APPS: return "all_apps";
|
||||
case CONTAINER_WIDGETS_TRAY: return "widgets_tray";
|
||||
case CONTAINER_SEARCH_RESULTS: return "search_result";
|
||||
case CONTAINER_SHORTCUTS: return "shortcuts";
|
||||
default: return String.valueOf(container);
|
||||
}
|
||||
}
|
||||
|
||||
static final String itemTypeToString(int type) {
|
||||
public static final String itemTypeToString(int type) {
|
||||
switch(type) {
|
||||
case ITEM_TYPE_APPLICATION: return "APP";
|
||||
case ITEM_TYPE_SHORTCUT: return "SHORTCUT";
|
||||
@@ -209,6 +250,12 @@ public class LauncherSettings {
|
||||
*/
|
||||
public static final int ITEM_TYPE_DEEP_SHORTCUT = 6;
|
||||
|
||||
/**
|
||||
* Type of the item is recents task.
|
||||
* TODO(hyunyoungs): move constants not related to Favorites DB to a better location.
|
||||
*/
|
||||
public static final int ITEM_TYPE_TASK = 7;
|
||||
|
||||
/**
|
||||
* The appWidgetId of the widget
|
||||
*
|
||||
@@ -299,10 +346,22 @@ public class LauncherSettings {
|
||||
|
||||
public static final String METHOD_REFRESH_BACKUP_TABLE = "refresh_backup_table";
|
||||
|
||||
public static final String METHOD_REFRESH_HOTSEAT_RESTORE_TABLE = "restore_hotseat_table";
|
||||
|
||||
public static final String METHOD_RESTORE_BACKUP_TABLE = "restore_backup_table";
|
||||
|
||||
public static final String METHOD_UPDATE_CURRENT_OPEN_HELPER = "update_current_open_helper";
|
||||
|
||||
public static final String METHOD_PREP_FOR_PREVIEW = "prep_for_preview";
|
||||
|
||||
public static final String EXTRA_VALUE = "value";
|
||||
|
||||
public static Bundle call(ContentResolver cr, String method) {
|
||||
return cr.call(CONTENT_URI, method, null, null);
|
||||
return call(cr, method, null);
|
||||
}
|
||||
|
||||
public static Bundle call(ContentResolver cr, String method, String arg) {
|
||||
return cr.call(CONTENT_URI, method, arg, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,47 +15,35 @@
|
||||
*/
|
||||
package com.android.launcher3;
|
||||
|
||||
import static android.view.View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
|
||||
import static android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS;
|
||||
import static android.view.View.VISIBLE;
|
||||
import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
|
||||
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_FADE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCALE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_TRANSLATE_X;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_FADE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_SCALE;
|
||||
import static com.android.launcher3.anim.Interpolators.ACCEL;
|
||||
import static com.android.launcher3.anim.Interpolators.DEACCEL;
|
||||
import static com.android.launcher3.anim.Interpolators.DEACCEL_1_7;
|
||||
import static com.android.launcher3.anim.Interpolators.clampToProgress;
|
||||
import static com.android.launcher3.anim.Interpolators.ACCEL_2;
|
||||
import static com.android.launcher3.testing.TestProtocol.ALL_APPS_STATE_ORDINAL;
|
||||
import static com.android.launcher3.testing.TestProtocol.BACKGROUND_APP_STATE_ORDINAL;
|
||||
import static com.android.launcher3.testing.TestProtocol.HINT_STATE_ORDINAL;
|
||||
import static com.android.launcher3.testing.TestProtocol.NORMAL_STATE_ORDINAL;
|
||||
import static com.android.launcher3.testing.TestProtocol.OVERVIEW_MODAL_TASK_STATE_ORDINAL;
|
||||
import static com.android.launcher3.testing.TestProtocol.OVERVIEW_PEEK_STATE_ORDINAL;
|
||||
import static com.android.launcher3.testing.TestProtocol.OVERVIEW_STATE_ORDINAL;
|
||||
import static com.android.launcher3.testing.TestProtocol.QUICK_SWITCH_STATE_ORDINAL;
|
||||
import static com.android.launcher3.testing.TestProtocol.SPRING_LOADED_STATE_ORDINAL;
|
||||
import static com.android.launcher3.anim.Interpolators.ACCEL_2;
|
||||
import static com.android.launcher3.states.RotationHelper.REQUEST_NONE;
|
||||
|
||||
import android.content.Context;
|
||||
import android.view.animation.Interpolator;
|
||||
|
||||
import com.android.launcher3.anim.AnimatorSetBuilder;
|
||||
import com.android.launcher3.statemanager.BaseState;
|
||||
import com.android.launcher3.statemanager.StateManager;
|
||||
import com.android.launcher3.states.HintState;
|
||||
import com.android.launcher3.states.SpringLoadedState;
|
||||
import com.android.launcher3.uioverrides.UiFactory;
|
||||
import com.android.launcher3.testing.TestProtocol;
|
||||
import com.android.launcher3.uioverrides.states.AllAppsState;
|
||||
import com.android.launcher3.uioverrides.states.OverviewState;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
|
||||
/**
|
||||
* Base state for various states used for the Launcher
|
||||
*/
|
||||
public class LauncherState {
|
||||
|
||||
public abstract class LauncherState implements BaseState<LauncherState> {
|
||||
|
||||
/**
|
||||
* Set of elements indicating various workspace elements which change visibility across states
|
||||
@@ -68,18 +56,33 @@ public class LauncherState {
|
||||
public static final int ALL_APPS_HEADER_EXTRA = 1 << 3; // e.g. app predictions
|
||||
public static final int ALL_APPS_CONTENT = 1 << 4;
|
||||
public static final int VERTICAL_SWIPE_INDICATOR = 1 << 5;
|
||||
public static final int RECENTS_CLEAR_ALL_BUTTON = 1 << 6;
|
||||
public static final int OVERVIEW_BUTTONS = 1 << 6;
|
||||
|
||||
protected static final int FLAG_MULTI_PAGE = 1 << 0;
|
||||
protected static final int FLAG_DISABLE_ACCESSIBILITY = 1 << 1;
|
||||
protected static final int FLAG_DISABLE_RESTORE = 1 << 2;
|
||||
protected static final int FLAG_WORKSPACE_ICONS_CAN_BE_DRAGGED = 1 << 3;
|
||||
protected static final int FLAG_DISABLE_PAGE_CLIPPING = 1 << 4;
|
||||
protected static final int FLAG_PAGE_BACKGROUNDS = 1 << 5;
|
||||
protected static final int FLAG_DISABLE_INTERACTION = 1 << 6;
|
||||
protected static final int FLAG_OVERVIEW_UI = 1 << 7;
|
||||
protected static final int FLAG_HIDE_BACK_BUTTON = 1 << 8;
|
||||
protected static final int FLAG_HAS_SYS_UI_SCRIM = 1 << 9;
|
||||
/** Mask of all the items that are contained in the apps view. */
|
||||
public static final int APPS_VIEW_ITEM_MASK =
|
||||
HOTSEAT_SEARCH_BOX | ALL_APPS_HEADER | ALL_APPS_HEADER_EXTRA | ALL_APPS_CONTENT;
|
||||
|
||||
// Flag indicating workspace has multiple pages visible.
|
||||
public static final int FLAG_MULTI_PAGE = BaseState.getFlag(0);
|
||||
// Flag indicating that workspace and its contents are not accessible
|
||||
public static final int FLAG_WORKSPACE_INACCESSIBLE = BaseState.getFlag(1);
|
||||
|
||||
// Flag indicating the state allows workspace icons to be dragged.
|
||||
public static final int FLAG_WORKSPACE_ICONS_CAN_BE_DRAGGED = BaseState.getFlag(2);
|
||||
// Flag to indicate that workspace should draw page background
|
||||
public static final int FLAG_WORKSPACE_HAS_BACKGROUNDS = BaseState.getFlag(3);
|
||||
// True if the back button should be hidden when in this state (assuming no floating views are
|
||||
// open, launcher has window focus, etc).
|
||||
public static final int FLAG_HIDE_BACK_BUTTON = BaseState.getFlag(4);
|
||||
// Flag to indicate if the state would have scrim over sysui region: statu sbar and nav bar
|
||||
public static final int FLAG_HAS_SYS_UI_SCRIM = BaseState.getFlag(5);
|
||||
// Flag to inticate that all popups should be closed when this state is enabled.
|
||||
public static final int FLAG_CLOSE_POPUPS = BaseState.getFlag(6);
|
||||
public static final int FLAG_OVERVIEW_UI = BaseState.getFlag(7);
|
||||
|
||||
|
||||
public static final float NO_OFFSET = 0;
|
||||
public static final float NO_SCALE = 1;
|
||||
|
||||
protected static final PageAlphaProvider DEFAULT_ALPHA_PROVIDER =
|
||||
new PageAlphaProvider(ACCEL_2) {
|
||||
@@ -89,15 +92,21 @@ public class LauncherState {
|
||||
}
|
||||
};
|
||||
|
||||
private static final LauncherState[] sAllStates = new LauncherState[7];
|
||||
private static final LauncherState[] sAllStates = new LauncherState[9];
|
||||
|
||||
/**
|
||||
* TODO: Create a separate class for NORMAL state.
|
||||
*/
|
||||
public static final LauncherState NORMAL = new LauncherState(NORMAL_STATE_ORDINAL,
|
||||
ContainerType.WORKSPACE, 0,
|
||||
ContainerType.WORKSPACE,
|
||||
FLAG_DISABLE_RESTORE | FLAG_WORKSPACE_ICONS_CAN_BE_DRAGGED | FLAG_HIDE_BACK_BUTTON |
|
||||
FLAG_HAS_SYS_UI_SCRIM);
|
||||
FLAG_HAS_SYS_UI_SCRIM) {
|
||||
@Override
|
||||
public int getTransitionDuration(Context context) {
|
||||
// Arbitrary duration, when going to NORMAL we use the state we're coming from instead.
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Various Launcher states arranged in the increasing order of UI layers
|
||||
@@ -105,10 +114,13 @@ public class LauncherState {
|
||||
public static final LauncherState SPRING_LOADED = new SpringLoadedState(
|
||||
SPRING_LOADED_STATE_ORDINAL);
|
||||
public static final LauncherState ALL_APPS = new AllAppsState(ALL_APPS_STATE_ORDINAL);
|
||||
public static final LauncherState HINT_STATE = new HintState(HINT_STATE_ORDINAL);
|
||||
|
||||
public static final LauncherState OVERVIEW = new OverviewState(OVERVIEW_STATE_ORDINAL);
|
||||
public static final LauncherState OVERVIEW_PEEK =
|
||||
OverviewState.newPeekState(OVERVIEW_PEEK_STATE_ORDINAL);
|
||||
public static final LauncherState OVERVIEW_MODAL_TASK = OverviewState.newModalTaskState(
|
||||
OVERVIEW_MODAL_TASK_STATE_ORDINAL);
|
||||
public static final LauncherState QUICK_SWITCH =
|
||||
OverviewState.newSwitchState(QUICK_SWITCH_STATE_ORDINAL);
|
||||
public static final LauncherState BACKGROUND_APP =
|
||||
@@ -121,87 +133,35 @@ public class LauncherState {
|
||||
*/
|
||||
public final int containerType;
|
||||
|
||||
/**
|
||||
* True if the state can be persisted across activity restarts.
|
||||
*/
|
||||
public final boolean disableRestore;
|
||||
|
||||
/**
|
||||
* True if workspace has multiple pages visible.
|
||||
*/
|
||||
public final boolean hasMultipleVisiblePages;
|
||||
|
||||
/**
|
||||
* Accessibility flag for workspace and its pages.
|
||||
* @see android.view.View#setImportantForAccessibility(int)
|
||||
*/
|
||||
public final int workspaceAccessibilityFlag;
|
||||
|
||||
/**
|
||||
* Properties related to state transition animation
|
||||
*
|
||||
* @see WorkspaceStateTransitionAnimation
|
||||
*/
|
||||
public final boolean hasWorkspacePageBackground;
|
||||
|
||||
public final int transitionDuration;
|
||||
|
||||
/**
|
||||
* True if the state allows workspace icons to be dragged.
|
||||
*/
|
||||
public final boolean workspaceIconsCanBeDragged;
|
||||
|
||||
/**
|
||||
* True if the workspace pages should not be clipped relative to the workspace bounds
|
||||
* for this state.
|
||||
*/
|
||||
public final boolean disablePageClipping;
|
||||
|
||||
/**
|
||||
* True if launcher can not be directly interacted in this state;
|
||||
*/
|
||||
public final boolean disableInteraction;
|
||||
|
||||
/**
|
||||
* True if the state has overview panel visible.
|
||||
*/
|
||||
public final boolean overviewUi;
|
||||
|
||||
/**
|
||||
* True if the back button should be hidden when in this state (assuming no floating views are
|
||||
* open, launcher has window focus, etc).
|
||||
*/
|
||||
public final boolean hideBackButton;
|
||||
private final int mFlags;
|
||||
|
||||
public final boolean hasSysUiScrim;
|
||||
|
||||
public LauncherState(int id, int containerType, int transitionDuration, int flags) {
|
||||
public LauncherState(int id, int containerType, int flags) {
|
||||
this.containerType = containerType;
|
||||
this.transitionDuration = transitionDuration;
|
||||
|
||||
this.hasWorkspacePageBackground = (flags & FLAG_PAGE_BACKGROUNDS) != 0;
|
||||
this.hasMultipleVisiblePages = (flags & FLAG_MULTI_PAGE) != 0;
|
||||
this.workspaceAccessibilityFlag = (flags & FLAG_DISABLE_ACCESSIBILITY) != 0
|
||||
? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
|
||||
: IMPORTANT_FOR_ACCESSIBILITY_AUTO;
|
||||
this.disableRestore = (flags & FLAG_DISABLE_RESTORE) != 0;
|
||||
this.workspaceIconsCanBeDragged = (flags & FLAG_WORKSPACE_ICONS_CAN_BE_DRAGGED) != 0;
|
||||
this.disablePageClipping = (flags & FLAG_DISABLE_PAGE_CLIPPING) != 0;
|
||||
this.disableInteraction = (flags & FLAG_DISABLE_INTERACTION) != 0;
|
||||
this.mFlags = flags;
|
||||
this.overviewUi = (flags & FLAG_OVERVIEW_UI) != 0;
|
||||
this.hideBackButton = (flags & FLAG_HIDE_BACK_BUTTON) != 0;
|
||||
this.hasSysUiScrim = (flags & FLAG_HAS_SYS_UI_SCRIM) != 0;
|
||||
|
||||
this.ordinal = id;
|
||||
sAllStates[id] = this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns if the state has the provided flag
|
||||
*/
|
||||
@Override
|
||||
public final boolean hasFlag(int mask) {
|
||||
return (mFlags & mask) != 0;
|
||||
}
|
||||
|
||||
public static LauncherState[] values() {
|
||||
return Arrays.copyOf(sAllStates, sAllStates.length);
|
||||
}
|
||||
|
||||
public ScaleAndTranslation getWorkspaceScaleAndTranslation(Launcher launcher) {
|
||||
return new ScaleAndTranslation(1, 0, 0);
|
||||
return new ScaleAndTranslation(NO_SCALE, NO_OFFSET, NO_OFFSET);
|
||||
}
|
||||
|
||||
public ScaleAndTranslation getHotseatScaleAndTranslation(Launcher launcher) {
|
||||
@@ -209,20 +169,24 @@ public class LauncherState {
|
||||
return getWorkspaceScaleAndTranslation(launcher);
|
||||
}
|
||||
|
||||
public ScaleAndTranslation getOverviewScaleAndTranslation(Launcher launcher) {
|
||||
return UiFactory.getOverviewScaleAndTranslationForNormalState(launcher);
|
||||
/**
|
||||
* Returns an array of two elements.
|
||||
* The first specifies the scale for the overview
|
||||
* The second is the factor ([0, 1], 0 => center-screen; 1 => offscreen) by which overview
|
||||
* should be shifted horizontally.
|
||||
*/
|
||||
public float[] getOverviewScaleAndOffset(Launcher launcher) {
|
||||
return launcher.getNormalOverviewScaleAndOffset();
|
||||
}
|
||||
|
||||
public ScaleAndTranslation getQsbScaleAndTranslation(Launcher launcher) {
|
||||
return new ScaleAndTranslation(NO_SCALE, NO_OFFSET, NO_OFFSET);
|
||||
}
|
||||
|
||||
public float getOverviewFullscreenProgress() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
public void onStateEnabled(Launcher launcher) {
|
||||
dispatchWindowStateChanged(launcher);
|
||||
}
|
||||
|
||||
public void onStateDisabled(Launcher launcher) { }
|
||||
|
||||
public int getVisibleElements(Launcher launcher) {
|
||||
if (launcher.getDeviceProfile().isVerticalBarLayout()) {
|
||||
return HOTSEAT_ICONS | VERTICAL_SWIPE_INDICATOR;
|
||||
@@ -247,6 +211,40 @@ public class LauncherState {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* For this state, how modal should over view been shown. 0 modalness means all tasks drawn,
|
||||
* 1 modalness means the current task is show on its own.
|
||||
*/
|
||||
public float getOverviewModalness() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The amount of blur and wallpaper zoom to apply to the background of either the app
|
||||
* or Launcher surface in this state. Should be a number between 0 and 1, inclusive.
|
||||
*
|
||||
* 0 means completely zoomed in, without blurs. 1 is zoomed out, with blurs.
|
||||
*/
|
||||
public final float getDepth(Context context) {
|
||||
return getDepth(context,
|
||||
BaseDraggingActivity.fromContext(context).getDeviceProfile().isMultiWindowMode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the amount of blur and wallpaper zoom for this state with {@param isMultiWindowMode}.
|
||||
* @see #getDepth(Context).
|
||||
*/
|
||||
public final float getDepth(Context context, boolean isMultiWindowMode) {
|
||||
if (isMultiWindowMode) {
|
||||
return 0;
|
||||
}
|
||||
return getDepthUnchecked(context);
|
||||
}
|
||||
|
||||
protected float getDepthUnchecked(Context context) {
|
||||
return 0f;
|
||||
}
|
||||
|
||||
public String getDescription(Launcher launcher) {
|
||||
return launcher.getWorkspace().getCurrentPageDescription();
|
||||
}
|
||||
@@ -264,73 +262,25 @@ public class LauncherState {
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public LauncherState getHistoryForState(LauncherState previousState) {
|
||||
// No history is supported
|
||||
return NORMAL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the start transition ends and the user settles on this particular state.
|
||||
*/
|
||||
public void onStateTransitionEnd(Launcher launcher) {
|
||||
if (this == NORMAL) {
|
||||
// Clear any rotation locks when going to normal state
|
||||
launcher.getRotationHelper().setCurrentStateRequest(REQUEST_NONE);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return TestProtocol.stateOrdinalToString(ordinal);
|
||||
}
|
||||
|
||||
public void onBackPressed(Launcher launcher) {
|
||||
if (this != NORMAL) {
|
||||
LauncherStateManager lsm = launcher.getStateManager();
|
||||
StateManager<LauncherState> lsm = launcher.getStateManager();
|
||||
LauncherState lastState = lsm.getLastState();
|
||||
lsm.goToState(lastState);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares for a non-user controlled animation from fromState to this state. Preparations
|
||||
* include:
|
||||
* - Setting interpolators for various animations included in the state transition.
|
||||
* - Setting some start values (e.g. scale) for views that are hidden but about to be shown.
|
||||
*/
|
||||
public void prepareForAtomicAnimation(Launcher launcher, LauncherState fromState,
|
||||
AnimatorSetBuilder builder) {
|
||||
if (this == NORMAL && fromState == OVERVIEW) {
|
||||
builder.setInterpolator(ANIM_WORKSPACE_SCALE, DEACCEL);
|
||||
builder.setInterpolator(ANIM_WORKSPACE_FADE, ACCEL);
|
||||
builder.setInterpolator(ANIM_OVERVIEW_SCALE, clampToProgress(ACCEL, 0, 0.9f));
|
||||
builder.setInterpolator(ANIM_OVERVIEW_TRANSLATE_X, ACCEL);
|
||||
builder.setInterpolator(ANIM_OVERVIEW_FADE, DEACCEL_1_7);
|
||||
Workspace workspace = launcher.getWorkspace();
|
||||
|
||||
// Start from a higher workspace scale, but only if we're invisible so we don't jump.
|
||||
boolean isWorkspaceVisible = workspace.getVisibility() == VISIBLE;
|
||||
if (isWorkspaceVisible) {
|
||||
CellLayout currentChild = (CellLayout) workspace.getChildAt(
|
||||
workspace.getCurrentPage());
|
||||
isWorkspaceVisible = currentChild.getVisibility() == VISIBLE
|
||||
&& currentChild.getShortcutsAndWidgets().getAlpha() > 0;
|
||||
}
|
||||
if (!isWorkspaceVisible) {
|
||||
workspace.setScaleX(0.92f);
|
||||
workspace.setScaleY(0.92f);
|
||||
}
|
||||
Hotseat hotseat = launcher.getHotseat();
|
||||
boolean isHotseatVisible = hotseat.getVisibility() == VISIBLE && hotseat.getAlpha() > 0;
|
||||
if (!isHotseatVisible) {
|
||||
hotseat.setScaleX(0.92f);
|
||||
hotseat.setScaleY(0.92f);
|
||||
}
|
||||
} else if (this == NORMAL && fromState == OVERVIEW_PEEK) {
|
||||
// Keep fully visible until the very end (when overview is offscreen) to make invisible.
|
||||
builder.setInterpolator(ANIM_OVERVIEW_FADE, t -> t < 1 ? 0 : 1);
|
||||
}
|
||||
}
|
||||
|
||||
protected static void dispatchWindowStateChanged(Launcher launcher) {
|
||||
launcher.getWindow().getDecorView().sendAccessibilityEvent(TYPE_WINDOW_STATE_CHANGED);
|
||||
}
|
||||
|
||||
public static abstract class PageAlphaProvider {
|
||||
|
||||
public final Interpolator interpolator;
|
||||
|
||||
@@ -1,674 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2015 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;
|
||||
|
||||
import static com.android.launcher3.LauncherState.NORMAL;
|
||||
import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.AnimatorSet;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.IntDef;
|
||||
|
||||
import com.android.launcher3.anim.AnimationSuccessListener;
|
||||
import com.android.launcher3.anim.AnimatorPlaybackController;
|
||||
import com.android.launcher3.anim.AnimatorSetBuilder;
|
||||
import com.android.launcher3.anim.PropertySetter;
|
||||
import com.android.launcher3.anim.PropertySetter.AnimatedPropertySetter;
|
||||
import com.android.launcher3.compat.AccessibilityManagerCompat;
|
||||
import com.android.launcher3.uioverrides.UiFactory;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* TODO: figure out what kind of tests we can write for this
|
||||
*
|
||||
* Things to test when changing the following class.
|
||||
* - Home from workspace
|
||||
* - from center screen
|
||||
* - from other screens
|
||||
* - Home from all apps
|
||||
* - from center screen
|
||||
* - from other screens
|
||||
* - Back from all apps
|
||||
* - from center screen
|
||||
* - from other screens
|
||||
* - Launch app from workspace and quit
|
||||
* - with back
|
||||
* - with home
|
||||
* - Launch app from all apps and quit
|
||||
* - with back
|
||||
* - with home
|
||||
* - Go to a screen that's not the default, then all
|
||||
* apps, and launch and app, and go back
|
||||
* - with back
|
||||
* -with home
|
||||
* - On workspace, long press power and go back
|
||||
* - with back
|
||||
* - with home
|
||||
* - On all apps, long press power and go back
|
||||
* - with back
|
||||
* - with home
|
||||
* - On workspace, power off
|
||||
* - On all apps, power off
|
||||
* - Launch an app and turn off the screen while in that app
|
||||
* - Go back with home key
|
||||
* - Go back with back key TODO: make this not go to workspace
|
||||
* - From all apps
|
||||
* - From workspace
|
||||
* - Enter and exit car mode (becase it causes an extra configuration changed)
|
||||
* - From all apps
|
||||
* - From the center workspace
|
||||
* - From another workspace
|
||||
*/
|
||||
public class LauncherStateManager {
|
||||
|
||||
public static final String TAG = "StateManager";
|
||||
|
||||
// We separate the state animations into "atomic" and "non-atomic" components. The atomic
|
||||
// components may be run atomically - that is, all at once, instead of user-controlled. However,
|
||||
// atomic components are not restricted to this purpose; they can be user-controlled alongside
|
||||
// non atomic components as well. Note that each gesture model has exactly one atomic component,
|
||||
// ATOMIC_OVERVIEW_SCALE_COMPONENT *or* ATOMIC_OVERVIEW_PEEK_COMPONENT.
|
||||
@IntDef(flag = true, value = {
|
||||
NON_ATOMIC_COMPONENT,
|
||||
ATOMIC_OVERVIEW_SCALE_COMPONENT,
|
||||
ATOMIC_OVERVIEW_PEEK_COMPONENT,
|
||||
})
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
public @interface AnimationComponents {}
|
||||
public static final int NON_ATOMIC_COMPONENT = 1 << 0;
|
||||
public static final int ATOMIC_OVERVIEW_SCALE_COMPONENT = 1 << 1;
|
||||
public static final int ATOMIC_OVERVIEW_PEEK_COMPONENT = 1 << 2;
|
||||
|
||||
public static final int ANIM_ALL = NON_ATOMIC_COMPONENT | ATOMIC_OVERVIEW_SCALE_COMPONENT
|
||||
| ATOMIC_OVERVIEW_PEEK_COMPONENT;
|
||||
|
||||
private final AnimationConfig mConfig = new AnimationConfig();
|
||||
private final Handler mUiHandler;
|
||||
private final Launcher mLauncher;
|
||||
private final ArrayList<StateListener> mListeners = new ArrayList<>();
|
||||
|
||||
// Animators which are run on properties also controlled by state animations.
|
||||
private Animator[] mStateElementAnimators;
|
||||
|
||||
private StateHandler[] mStateHandlers;
|
||||
private LauncherState mState = NORMAL;
|
||||
|
||||
private LauncherState mLastStableState = NORMAL;
|
||||
private LauncherState mCurrentStableState = NORMAL;
|
||||
|
||||
private LauncherState mRestState;
|
||||
|
||||
public LauncherStateManager(Launcher l) {
|
||||
mUiHandler = new Handler(Looper.getMainLooper());
|
||||
mLauncher = l;
|
||||
}
|
||||
|
||||
public LauncherState getState() {
|
||||
return mState;
|
||||
}
|
||||
|
||||
public LauncherState getCurrentStableState() {
|
||||
return mCurrentStableState;
|
||||
}
|
||||
|
||||
public void dump(String prefix, PrintWriter writer) {
|
||||
writer.println(prefix + "LauncherState:");
|
||||
writer.println(prefix + "\tmLastStableState:" + mLastStableState);
|
||||
writer.println(prefix + "\tmCurrentStableState:" + mCurrentStableState);
|
||||
writer.println(prefix + "\tmState:" + mState);
|
||||
writer.println(prefix + "\tmRestState:" + mRestState);
|
||||
writer.println(prefix + "\tisInTransition:" + (mConfig.mCurrentAnimation != null));
|
||||
}
|
||||
|
||||
public StateHandler[] getStateHandlers() {
|
||||
if (mStateHandlers == null) {
|
||||
mStateHandlers = UiFactory.getStateHandler(mLauncher);
|
||||
}
|
||||
return mStateHandlers;
|
||||
}
|
||||
|
||||
public void addStateListener(StateListener listener) {
|
||||
mListeners.add(listener);
|
||||
}
|
||||
|
||||
public void removeStateListener(StateListener listener) {
|
||||
mListeners.remove(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the state changes should be animated.
|
||||
*/
|
||||
public boolean shouldAnimateStateChange() {
|
||||
return !mLauncher.isForceInvisible() && mLauncher.isStarted();
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #goToState(LauncherState, boolean, Runnable)
|
||||
*/
|
||||
public void goToState(LauncherState state) {
|
||||
goToState(state, shouldAnimateStateChange());
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #goToState(LauncherState, boolean, Runnable)
|
||||
*/
|
||||
public void goToState(LauncherState state, boolean animated) {
|
||||
goToState(state, animated, 0, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the Launcher state to the provided state.
|
||||
*
|
||||
* @param animated false if the state should change immediately without any animation,
|
||||
* true otherwise
|
||||
* @paras onCompleteRunnable any action to perform at the end of the transition, of null.
|
||||
*/
|
||||
public void goToState(LauncherState state, boolean animated, Runnable onCompleteRunnable) {
|
||||
goToState(state, animated, 0, onCompleteRunnable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the Launcher state to the provided state after the given delay.
|
||||
*/
|
||||
public void goToState(LauncherState state, long delay, Runnable onCompleteRunnable) {
|
||||
goToState(state, true, delay, onCompleteRunnable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the Launcher state to the provided state after the given delay.
|
||||
*/
|
||||
public void goToState(LauncherState state, long delay) {
|
||||
goToState(state, true, delay, null);
|
||||
}
|
||||
|
||||
public void reapplyState() {
|
||||
reapplyState(false);
|
||||
}
|
||||
|
||||
public void reapplyState(boolean cancelCurrentAnimation) {
|
||||
boolean wasInAnimation = mConfig.mCurrentAnimation != null;
|
||||
if (cancelCurrentAnimation) {
|
||||
cancelAllStateElementAnimation();
|
||||
cancelAnimation();
|
||||
}
|
||||
if (mConfig.mCurrentAnimation == null) {
|
||||
for (StateHandler handler : getStateHandlers()) {
|
||||
handler.setState(mState);
|
||||
}
|
||||
if (wasInAnimation) {
|
||||
onStateTransitionEnd(mState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void goToState(LauncherState state, boolean animated, long delay,
|
||||
final Runnable onCompleteRunnable) {
|
||||
animated &= Utilities.areAnimationsEnabled(mLauncher);
|
||||
if (mLauncher.isInState(state)) {
|
||||
if (mConfig.mCurrentAnimation == null) {
|
||||
// Run any queued runnable
|
||||
if (onCompleteRunnable != null) {
|
||||
onCompleteRunnable.run();
|
||||
}
|
||||
return;
|
||||
} else if (!mConfig.userControlled && animated && mConfig.mTargetState == state) {
|
||||
// We are running the same animation as requested
|
||||
if (onCompleteRunnable != null) {
|
||||
mConfig.mCurrentAnimation.addListener(new AnimationSuccessListener() {
|
||||
@Override
|
||||
public void onAnimationSuccess(Animator animator) {
|
||||
onCompleteRunnable.run();
|
||||
}
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel the current animation. This will reset mState to mCurrentStableState, so store it.
|
||||
LauncherState fromState = mState;
|
||||
mConfig.reset();
|
||||
|
||||
if (!animated) {
|
||||
cancelAllStateElementAnimation();
|
||||
onStateTransitionStart(state);
|
||||
for (StateHandler handler : getStateHandlers()) {
|
||||
handler.setState(state);
|
||||
}
|
||||
|
||||
onStateTransitionEnd(state);
|
||||
|
||||
// Run any queued runnable
|
||||
if (onCompleteRunnable != null) {
|
||||
onCompleteRunnable.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (delay > 0) {
|
||||
// Create the animation after the delay as some properties can change between preparing
|
||||
// the animation and running the animation.
|
||||
int startChangeId = mConfig.mChangeId;
|
||||
mUiHandler.postDelayed(() -> {
|
||||
if (mConfig.mChangeId == startChangeId) {
|
||||
goToStateAnimated(state, fromState, onCompleteRunnable);
|
||||
}
|
||||
}, delay);
|
||||
} else {
|
||||
goToStateAnimated(state, fromState, onCompleteRunnable);
|
||||
}
|
||||
}
|
||||
|
||||
private void goToStateAnimated(LauncherState state, LauncherState fromState,
|
||||
Runnable onCompleteRunnable) {
|
||||
// Since state NORMAL can be reached from multiple states, just assume that the
|
||||
// transition plays in reverse and use the same duration as previous state.
|
||||
mConfig.duration = state == NORMAL ? fromState.transitionDuration : state.transitionDuration;
|
||||
|
||||
AnimatorSetBuilder builder = new AnimatorSetBuilder();
|
||||
prepareForAtomicAnimation(fromState, state, builder);
|
||||
AnimatorSet animation = createAnimationToNewWorkspaceInternal(
|
||||
state, builder, onCompleteRunnable);
|
||||
mUiHandler.post(new StartAnimRunnable(animation));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares for a non-user controlled animation from fromState to toState. Preparations include:
|
||||
* - Setting interpolators for various animations included in the state transition.
|
||||
* - Setting some start values (e.g. scale) for views that are hidden but about to be shown.
|
||||
*/
|
||||
public void prepareForAtomicAnimation(LauncherState fromState, LauncherState toState,
|
||||
AnimatorSetBuilder builder) {
|
||||
toState.prepareForAtomicAnimation(mLauncher, fromState, builder);
|
||||
}
|
||||
|
||||
public AnimatorSet createAtomicAnimation(LauncherState fromState, LauncherState toState,
|
||||
AnimatorSetBuilder builder, @AnimationComponents int atomicComponent, long duration) {
|
||||
prepareForAtomicAnimation(fromState, toState, builder);
|
||||
AnimationConfig config = new AnimationConfig();
|
||||
config.animComponents = atomicComponent;
|
||||
config.duration = duration;
|
||||
for (StateHandler handler : mLauncher.getStateManager().getStateHandlers()) {
|
||||
handler.setStateWithAnimation(toState, builder, config);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link AnimatorPlaybackController} that can be used for a controlled
|
||||
* state transition. The UI is force-set to fromState before creating the controller.
|
||||
* @param fromState the initial state for the transition.
|
||||
* @param state the final state for the transition.
|
||||
* @param duration intended duration for normal playback. Use higher duration for better
|
||||
* accuracy.
|
||||
*/
|
||||
public AnimatorPlaybackController createAnimationToNewWorkspace(
|
||||
LauncherState fromState, LauncherState state, long duration) {
|
||||
// Since we are creating a state animation to a different state, temporarily prevent state
|
||||
// change as part of config reset.
|
||||
LauncherState originalRestState = mRestState;
|
||||
mRestState = state;
|
||||
mConfig.reset();
|
||||
mRestState = originalRestState;
|
||||
|
||||
for (StateHandler handler : getStateHandlers()) {
|
||||
handler.setState(fromState);
|
||||
}
|
||||
|
||||
return createAnimationToNewWorkspace(state, duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link AnimatorPlaybackController} that can be used for a controlled
|
||||
* state transition.
|
||||
* @param state the final state for the transition.
|
||||
* @param duration intended duration for normal playback. Use higher duration for better
|
||||
* accuracy.
|
||||
*/
|
||||
public AnimatorPlaybackController createAnimationToNewWorkspace(
|
||||
LauncherState state, long duration) {
|
||||
return createAnimationToNewWorkspace(state, duration, LauncherStateManager.ANIM_ALL);
|
||||
}
|
||||
|
||||
public AnimatorPlaybackController createAnimationToNewWorkspace(
|
||||
LauncherState state, long duration, @AnimationComponents int animComponents) {
|
||||
return createAnimationToNewWorkspace(state, new AnimatorSetBuilder(), duration, null,
|
||||
animComponents);
|
||||
}
|
||||
|
||||
public AnimatorPlaybackController createAnimationToNewWorkspace(LauncherState state,
|
||||
AnimatorSetBuilder builder, long duration, Runnable onCancelRunnable,
|
||||
@AnimationComponents int animComponents) {
|
||||
mConfig.reset();
|
||||
mConfig.userControlled = true;
|
||||
mConfig.animComponents = animComponents;
|
||||
mConfig.duration = duration;
|
||||
mConfig.playbackController = AnimatorPlaybackController.wrap(
|
||||
createAnimationToNewWorkspaceInternal(state, builder, null), duration,
|
||||
onCancelRunnable);
|
||||
return mConfig.playbackController;
|
||||
}
|
||||
|
||||
protected AnimatorSet createAnimationToNewWorkspaceInternal(final LauncherState state,
|
||||
AnimatorSetBuilder builder, final Runnable onCompleteRunnable) {
|
||||
|
||||
for (StateHandler handler : getStateHandlers()) {
|
||||
handler.setStateWithAnimation(state, builder, mConfig);
|
||||
}
|
||||
|
||||
final AnimatorSet animation = builder.build();
|
||||
animation.addListener(new AnimationSuccessListener() {
|
||||
|
||||
@Override
|
||||
public void onAnimationStart(Animator animation) {
|
||||
// Change the internal state only when the transition actually starts
|
||||
onStateTransitionStart(state);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationSuccess(Animator animator) {
|
||||
// Run any queued runnables
|
||||
if (onCompleteRunnable != null) {
|
||||
onCompleteRunnable.run();
|
||||
}
|
||||
onStateTransitionEnd(state);
|
||||
}
|
||||
});
|
||||
mConfig.setAnimation(animation, state);
|
||||
return mConfig.mCurrentAnimation;
|
||||
}
|
||||
|
||||
private void onStateTransitionStart(LauncherState state) {
|
||||
if (mState != state) {
|
||||
mState.onStateDisabled(mLauncher);
|
||||
}
|
||||
mState = state;
|
||||
mState.onStateEnabled(mLauncher);
|
||||
mLauncher.onStateSetStart(mState);
|
||||
|
||||
if (state.disablePageClipping) {
|
||||
// Only disable clipping if needed, otherwise leave it as previous value.
|
||||
mLauncher.getWorkspace().setClipChildren(false);
|
||||
}
|
||||
UiFactory.onLauncherStateOrResumeChanged(mLauncher);
|
||||
|
||||
for (int i = mListeners.size() - 1; i >= 0; i--) {
|
||||
mListeners.get(i).onStateTransitionStart(state);
|
||||
}
|
||||
}
|
||||
|
||||
private void onStateTransitionEnd(LauncherState state) {
|
||||
// Only change the stable states after the transitions have finished
|
||||
if (state != mCurrentStableState) {
|
||||
mLastStableState = state.getHistoryForState(mCurrentStableState);
|
||||
mCurrentStableState = state;
|
||||
}
|
||||
|
||||
state.onStateTransitionEnd(mLauncher);
|
||||
mLauncher.onStateSetEnd(state);
|
||||
|
||||
if (state == NORMAL) {
|
||||
setRestState(null);
|
||||
}
|
||||
|
||||
UiFactory.onLauncherStateOrResumeChanged(mLauncher);
|
||||
|
||||
for (int i = mListeners.size() - 1; i >= 0; i--) {
|
||||
mListeners.get(i).onStateTransitionComplete(state);
|
||||
}
|
||||
|
||||
AccessibilityManagerCompat.sendStateEventToTest(mLauncher, state.ordinal);
|
||||
}
|
||||
|
||||
public void onWindowFocusChanged() {
|
||||
UiFactory.onLauncherStateOrFocusChanged(mLauncher);
|
||||
}
|
||||
|
||||
public LauncherState getLastState() {
|
||||
return mLastStableState;
|
||||
}
|
||||
|
||||
public void moveToRestState() {
|
||||
if (mConfig.mCurrentAnimation != null && mConfig.userControlled) {
|
||||
// The user is doing something. Lets not mess it up
|
||||
return;
|
||||
}
|
||||
if (mState.disableRestore) {
|
||||
goToState(getRestState());
|
||||
// Reset history
|
||||
mLastStableState = NORMAL;
|
||||
}
|
||||
}
|
||||
|
||||
public LauncherState getRestState() {
|
||||
return mRestState == null ? NORMAL : mRestState;
|
||||
}
|
||||
|
||||
public void setRestState(LauncherState restState) {
|
||||
mRestState = restState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels the current animation.
|
||||
*/
|
||||
public void cancelAnimation() {
|
||||
mConfig.reset();
|
||||
}
|
||||
|
||||
public void setCurrentUserControlledAnimation(AnimatorPlaybackController controller) {
|
||||
clearCurrentAnimation();
|
||||
setCurrentAnimation(controller.getTarget());
|
||||
mConfig.userControlled = true;
|
||||
mConfig.playbackController = controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the animation as the current state animation, i.e., canceled when
|
||||
* starting another animation and may block some launcher interactions while running.
|
||||
*
|
||||
* @param childAnimations Set of animations with the new target is controlling.
|
||||
*/
|
||||
public void setCurrentAnimation(AnimatorSet anim, Animator... childAnimations) {
|
||||
for (Animator childAnim : childAnimations) {
|
||||
if (childAnim == null) {
|
||||
continue;
|
||||
}
|
||||
if (mConfig.playbackController != null
|
||||
&& mConfig.playbackController.getTarget() == childAnim) {
|
||||
clearCurrentAnimation();
|
||||
break;
|
||||
} else if (mConfig.mCurrentAnimation == childAnim) {
|
||||
clearCurrentAnimation();
|
||||
break;
|
||||
}
|
||||
}
|
||||
boolean reapplyNeeded = mConfig.mCurrentAnimation != null;
|
||||
cancelAnimation();
|
||||
if (reapplyNeeded) {
|
||||
reapplyState();
|
||||
// Dispatch on transition end, so that any transient property is cleared.
|
||||
onStateTransitionEnd(mState);
|
||||
}
|
||||
mConfig.setAnimation(anim, null);
|
||||
}
|
||||
|
||||
private void cancelAllStateElementAnimation() {
|
||||
if (mStateElementAnimators == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Animator animator : mStateElementAnimators) {
|
||||
if (animator != null) {
|
||||
animator.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels a currently running gesture animation
|
||||
*/
|
||||
public void cancelStateElementAnimation(int index) {
|
||||
if (mStateElementAnimators == null) {
|
||||
return;
|
||||
}
|
||||
if (mStateElementAnimators[index] != null) {
|
||||
mStateElementAnimators[index].cancel();
|
||||
}
|
||||
}
|
||||
|
||||
public Animator createStateElementAnimation(int index, float... values) {
|
||||
cancelStateElementAnimation(index);
|
||||
LauncherAppTransitionManager latm = mLauncher.getAppTransitionManager();
|
||||
if (mStateElementAnimators == null) {
|
||||
mStateElementAnimators = new Animator[latm.getStateElementAnimationsCount()];
|
||||
}
|
||||
Animator anim = latm.createStateElementAnimation(index, values);
|
||||
mStateElementAnimators[index] = anim;
|
||||
anim.addListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mStateElementAnimators[index] = null;
|
||||
}
|
||||
});
|
||||
return anim;
|
||||
}
|
||||
|
||||
private void clearCurrentAnimation() {
|
||||
if (mConfig.mCurrentAnimation != null) {
|
||||
mConfig.mCurrentAnimation.removeListener(mConfig);
|
||||
mConfig.mCurrentAnimation = null;
|
||||
}
|
||||
mConfig.playbackController = null;
|
||||
}
|
||||
|
||||
private class StartAnimRunnable implements Runnable {
|
||||
|
||||
private final AnimatorSet mAnim;
|
||||
|
||||
public StartAnimRunnable(AnimatorSet anim) {
|
||||
mAnim = anim;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (mConfig.mCurrentAnimation != mAnim) {
|
||||
return;
|
||||
}
|
||||
mAnim.start();
|
||||
}
|
||||
}
|
||||
|
||||
public static class AnimationConfig extends AnimatorListenerAdapter {
|
||||
public long duration;
|
||||
public boolean userControlled;
|
||||
public AnimatorPlaybackController playbackController;
|
||||
public @AnimationComponents int animComponents = ANIM_ALL;
|
||||
private PropertySetter mPropertySetter;
|
||||
|
||||
private AnimatorSet mCurrentAnimation;
|
||||
private LauncherState mTargetState;
|
||||
// Id to keep track of config changes, to tie an animation with the corresponding request
|
||||
private int mChangeId = 0;
|
||||
|
||||
/**
|
||||
* Cancels the current animation and resets config variables.
|
||||
*/
|
||||
public void reset() {
|
||||
duration = 0;
|
||||
userControlled = false;
|
||||
animComponents = ANIM_ALL;
|
||||
mPropertySetter = null;
|
||||
mTargetState = null;
|
||||
|
||||
if (playbackController != null) {
|
||||
playbackController.getAnimationPlayer().cancel();
|
||||
playbackController.dispatchOnCancel();
|
||||
} else if (mCurrentAnimation != null) {
|
||||
mCurrentAnimation.setDuration(0);
|
||||
mCurrentAnimation.cancel();
|
||||
}
|
||||
|
||||
mCurrentAnimation = null;
|
||||
playbackController = null;
|
||||
mChangeId ++;
|
||||
}
|
||||
|
||||
public PropertySetter getPropertySetter(AnimatorSetBuilder builder) {
|
||||
if (mPropertySetter == null) {
|
||||
mPropertySetter = duration == 0 ? NO_ANIM_PROPERTY_SETTER
|
||||
: new AnimatedPropertySetter(duration, builder);
|
||||
}
|
||||
return mPropertySetter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
if (playbackController != null && playbackController.getTarget() == animation) {
|
||||
playbackController = null;
|
||||
}
|
||||
if (mCurrentAnimation == animation) {
|
||||
mCurrentAnimation = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void setAnimation(AnimatorSet animation, LauncherState targetState) {
|
||||
mCurrentAnimation = animation;
|
||||
mTargetState = targetState;
|
||||
mCurrentAnimation.addListener(this);
|
||||
}
|
||||
|
||||
public boolean playAtomicOverviewScaleComponent() {
|
||||
return (animComponents & ATOMIC_OVERVIEW_SCALE_COMPONENT) != 0;
|
||||
}
|
||||
|
||||
public boolean playAtomicOverviewPeekComponent() {
|
||||
return (animComponents & ATOMIC_OVERVIEW_PEEK_COMPONENT) != 0;
|
||||
}
|
||||
|
||||
public boolean playNonAtomicComponent() {
|
||||
return (animComponents & NON_ATOMIC_COMPONENT) != 0;
|
||||
}
|
||||
}
|
||||
|
||||
public interface StateHandler {
|
||||
|
||||
/**
|
||||
* Updates the UI to {@param state} without any animations
|
||||
*/
|
||||
void setState(LauncherState state);
|
||||
|
||||
/**
|
||||
* Sets the UI to {@param state} by animating any changes.
|
||||
*/
|
||||
void setStateWithAnimation(LauncherState toState,
|
||||
AnimatorSetBuilder builder, AnimationConfig config);
|
||||
}
|
||||
|
||||
public interface StateListener {
|
||||
|
||||
void onStateTransitionStart(LauncherState toState);
|
||||
void onStateTransitionComplete(LauncherState finalState);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ package com.android.launcher3;
|
||||
import android.content.Context;
|
||||
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.graphics.BitmapCreationCheck;
|
||||
import com.android.launcher3.graphics.IconShape;
|
||||
import com.android.launcher3.logging.FileLog;
|
||||
import com.android.launcher3.util.ResourceBasedOverride;
|
||||
@@ -39,5 +40,9 @@ public class MainProcessInitializer implements ResourceBasedOverride {
|
||||
FeatureFlags.initialize(context);
|
||||
SessionCommitReceiver.applyDefaultUserPrefs(context);
|
||||
IconShape.init(context);
|
||||
|
||||
if (BitmapCreationCheck.ENABLED) {
|
||||
BitmapCreationCheck.startTracking(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,9 @@ import static com.android.launcher3.compat.AccessibilityManagerCompat.isAccessib
|
||||
import static com.android.launcher3.compat.AccessibilityManagerCompat.isObservedEventType;
|
||||
import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
|
||||
import static com.android.launcher3.touch.OverScroll.OVERSCROLL_DAMP_FACTOR;
|
||||
import static com.android.launcher3.touch.PagedOrientationHandler.CANVAS_TRANSLATE;
|
||||
import static com.android.launcher3.touch.PagedOrientationHandler.VIEW_SCROLL_BY;
|
||||
import static com.android.launcher3.touch.PagedOrientationHandler.VIEW_SCROLL_TO;
|
||||
|
||||
import android.animation.LayoutTransition;
|
||||
import android.animation.TimeInterpolator;
|
||||
@@ -46,13 +49,18 @@ import android.view.accessibility.AccessibilityNodeInfo;
|
||||
import android.view.animation.Interpolator;
|
||||
import android.widget.ScrollView;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.anim.Interpolators;
|
||||
import com.android.launcher3.compat.AccessibilityManagerCompat;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.pageindicators.PageIndicator;
|
||||
import com.android.launcher3.touch.OverScroll;
|
||||
import com.android.launcher3.touch.PagedOrientationHandler;
|
||||
import com.android.launcher3.touch.PagedOrientationHandler.ChildBounds;
|
||||
import com.android.launcher3.util.OverScroller;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
import com.android.launcher3.views.ActivityContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
@@ -63,8 +71,10 @@ import java.util.ArrayList;
|
||||
public abstract class PagedView<T extends View & PageIndicator> extends ViewGroup {
|
||||
private static final String TAG = "PagedView";
|
||||
private static final boolean DEBUG = false;
|
||||
public static final boolean DEBUG_FAILED_QUICKSWITCH = false;
|
||||
|
||||
protected static final int INVALID_PAGE = -1;
|
||||
public static final int ACTION_MOVE_ALLOW_EASY_FLING = MotionEvent.ACTION_MASK - 1;
|
||||
public static final int INVALID_PAGE = -1;
|
||||
protected static final ComputePageScrollsLogic SIMPLE_SCROLL_LOGIC = (v) -> v.getVisibility() != GONE;
|
||||
|
||||
public static final int PAGE_SNAP_ANIMATION_DURATION = 750;
|
||||
@@ -81,16 +91,16 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
// The following constants need to be scaled based on density. The scaled versions will be
|
||||
// assigned to the corresponding member variables below.
|
||||
private static final int FLING_THRESHOLD_VELOCITY = 500;
|
||||
private static final int EASY_FLING_THRESHOLD_VELOCITY = 400;
|
||||
private static final int MIN_SNAP_VELOCITY = 1500;
|
||||
private static final int MIN_FLING_VELOCITY = 250;
|
||||
|
||||
public static final int INVALID_RESTORE_PAGE = -1001;
|
||||
|
||||
private boolean mFreeScroll = false;
|
||||
|
||||
protected int mFlingThresholdVelocity;
|
||||
protected int mMinFlingVelocity;
|
||||
protected int mMinSnapVelocity;
|
||||
protected final int mFlingThresholdVelocity;
|
||||
protected final int mEasyFlingThresholdVelocity;
|
||||
protected final int mMinFlingVelocity;
|
||||
protected final int mMinSnapVelocity;
|
||||
|
||||
protected boolean mFirstLayout = true;
|
||||
|
||||
@@ -99,8 +109,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
|
||||
@ViewDebug.ExportedProperty(category = "launcher")
|
||||
protected int mNextPage = INVALID_PAGE;
|
||||
protected int mMinScrollX;
|
||||
protected int mMaxScrollX;
|
||||
protected int mMaxScroll;
|
||||
protected int mMinScroll;
|
||||
protected OverScroller mScroller;
|
||||
private Interpolator mDefaultInterpolator;
|
||||
private VelocityTracker mVelocityTracker;
|
||||
@@ -108,14 +118,21 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
|
||||
private float mDownMotionX;
|
||||
private float mDownMotionY;
|
||||
private float mLastMotionX;
|
||||
private float mLastMotionXRemainder;
|
||||
private float mTotalMotionX;
|
||||
private float mDownMotionPrimary;
|
||||
private float mLastMotion;
|
||||
private float mLastMotionRemainder;
|
||||
private float mTotalMotion;
|
||||
// Used in special cases where the fling checks can be relaxed for an intentional gesture
|
||||
private boolean mAllowEasyFling;
|
||||
protected PagedOrientationHandler mOrientationHandler = PagedOrientationHandler.PORTRAIT;
|
||||
|
||||
protected int[] mPageScrolls;
|
||||
private boolean mIsBeingDragged;
|
||||
|
||||
// The amount of movement to begin scrolling
|
||||
protected int mTouchSlop;
|
||||
// The amount of movement to begin paging
|
||||
protected int mPageSlop;
|
||||
private int mMaximumVelocity;
|
||||
protected boolean mAllowOverScroll = true;
|
||||
|
||||
@@ -124,12 +141,13 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
protected int mActivePointerId = INVALID_POINTER;
|
||||
|
||||
protected boolean mIsPageInTransition = false;
|
||||
private Runnable mOnPageTransitionEndCallback;
|
||||
|
||||
protected float mSpringOverScrollX;
|
||||
protected float mSpringOverScroll;
|
||||
|
||||
protected boolean mWasInOverscroll = false;
|
||||
|
||||
protected int mUnboundedScrollX;
|
||||
protected int mUnboundedScroll;
|
||||
|
||||
// Page Indicator
|
||||
@Thunk int mPageIndicatorViewId;
|
||||
@@ -161,23 +179,19 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
|
||||
setHapticFeedbackEnabled(false);
|
||||
mIsRtl = Utilities.isRtl(getResources());
|
||||
init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes various states for this workspace.
|
||||
*/
|
||||
protected void init() {
|
||||
mScroller = new OverScroller(getContext());
|
||||
mScroller = new OverScroller(context);
|
||||
setDefaultInterpolator(Interpolators.SCROLL);
|
||||
mCurrentPage = 0;
|
||||
|
||||
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
|
||||
mTouchSlop = configuration.getScaledPagingTouchSlop();
|
||||
final ViewConfiguration configuration = ViewConfiguration.get(context);
|
||||
mTouchSlop = configuration.getScaledTouchSlop();
|
||||
mPageSlop = configuration.getScaledPagingTouchSlop();
|
||||
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
|
||||
|
||||
float density = getResources().getDisplayMetrics().density;
|
||||
mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * density);
|
||||
mEasyFlingThresholdVelocity = (int) (EASY_FLING_THRESHOLD_VELOCITY * density);
|
||||
mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * density);
|
||||
mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * density);
|
||||
|
||||
@@ -238,12 +252,12 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
*/
|
||||
protected void updateCurrentPageScroll() {
|
||||
// If the current page is invalid, just reset the scroll position to zero
|
||||
int newX = 0;
|
||||
int newPosition = 0;
|
||||
if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
|
||||
newX = getScrollForPage(mCurrentPage);
|
||||
newPosition = getScrollForPage(mCurrentPage);
|
||||
}
|
||||
scrollTo(newX, 0);
|
||||
mScroller.startScroll(mScroller.getCurrPos(), newX - mScroller.getCurrPos());
|
||||
mOrientationHandler.set(this, VIEW_SCROLL_TO, newPosition);
|
||||
mOrientationHandler.scrollerStartScroll(mScroller, newPosition);
|
||||
forceFinishScroller(true);
|
||||
}
|
||||
|
||||
@@ -280,7 +294,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
int dir = !mIsRtl ? 1 : - 1;
|
||||
int currScroll = getScrollForPage(page);
|
||||
int prevScroll;
|
||||
while (currScroll < mMinScrollX) {
|
||||
while (currScroll < mMinScroll) {
|
||||
page += dir;
|
||||
prevScroll = currScroll;
|
||||
currScroll = getScrollForPage(page);
|
||||
@@ -289,7 +303,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
break;
|
||||
}
|
||||
}
|
||||
while (currScroll > mMaxScrollX) {
|
||||
while (currScroll > mMaxScroll) {
|
||||
page -= dir;
|
||||
prevScroll = currScroll;
|
||||
currScroll = getScrollForPage(page);
|
||||
@@ -369,47 +383,62 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
protected void onPageEndTransition() {
|
||||
mWasInOverscroll = false;
|
||||
AccessibilityManagerCompat.sendScrollFinishedEventToTest(getContext());
|
||||
AccessibilityManagerCompat.sendCustomAccessibilityEvent(getPageAt(mCurrentPage),
|
||||
AccessibilityEvent.TYPE_VIEW_FOCUSED, null);
|
||||
if (mOnPageTransitionEndCallback != null) {
|
||||
mOnPageTransitionEndCallback.run();
|
||||
mOnPageTransitionEndCallback = null;
|
||||
}
|
||||
}
|
||||
|
||||
protected int getUnboundedScrollX() {
|
||||
return mUnboundedScrollX;
|
||||
/**
|
||||
* Sets a callback to run once when the scrolling finishes. If there is currently
|
||||
* no page in transition, then the callback is called immediately.
|
||||
*/
|
||||
public void setOnPageTransitionEndCallback(@Nullable Runnable callback) {
|
||||
if (mIsPageInTransition || callback == null) {
|
||||
mOnPageTransitionEndCallback = callback;
|
||||
} else {
|
||||
callback.run();
|
||||
}
|
||||
}
|
||||
|
||||
protected int getUnboundedScroll() {
|
||||
return mUnboundedScroll;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scrollBy(int x, int y) {
|
||||
scrollTo(getUnboundedScrollX() + x, getScrollY() + y);
|
||||
mOrientationHandler.delegateScrollBy(this, getUnboundedScroll(), x, y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scrollTo(int x, int y) {
|
||||
mUnboundedScrollX = x;
|
||||
int primaryScroll = mOrientationHandler.getPrimaryValue(x, y);
|
||||
int secondaryScroll = mOrientationHandler.getSecondaryValue(x, y);
|
||||
mUnboundedScroll = primaryScroll;
|
||||
|
||||
boolean isXBeforeFirstPage = mIsRtl ? (x > mMaxScrollX) : (x < mMinScrollX);
|
||||
boolean isXAfterLastPage = mIsRtl ? (x < mMinScrollX) : (x > mMaxScrollX);
|
||||
|
||||
if (!isXBeforeFirstPage && !isXAfterLastPage) {
|
||||
mSpringOverScrollX = 0;
|
||||
boolean isBeforeFirstPage = mIsRtl ?
|
||||
(primaryScroll > mMaxScroll) : (primaryScroll < mMinScroll);
|
||||
boolean isAfterLastPage = mIsRtl ?
|
||||
(primaryScroll < mMinScroll) : (primaryScroll > mMaxScroll);
|
||||
if (!isBeforeFirstPage && !isAfterLastPage) {
|
||||
mSpringOverScroll = 0;
|
||||
}
|
||||
|
||||
if (isXBeforeFirstPage) {
|
||||
super.scrollTo(mIsRtl ? mMaxScrollX : mMinScrollX, y);
|
||||
if (isBeforeFirstPage) {
|
||||
mOrientationHandler.delegateScrollTo(this,
|
||||
secondaryScroll, mIsRtl ? mMaxScroll : mMinScroll);
|
||||
if (mAllowOverScroll) {
|
||||
mWasInOverscroll = true;
|
||||
if (mIsRtl) {
|
||||
overScroll(x - mMaxScrollX);
|
||||
} else {
|
||||
overScroll(x - mMinScrollX);
|
||||
}
|
||||
overScroll(primaryScroll - (mIsRtl ? mMaxScroll : mMinScroll));
|
||||
}
|
||||
} else if (isXAfterLastPage) {
|
||||
super.scrollTo(mIsRtl ? mMinScrollX : mMaxScrollX, y);
|
||||
} else if (isAfterLastPage) {
|
||||
mOrientationHandler.delegateScrollTo(this,
|
||||
secondaryScroll, mIsRtl ? mMinScroll : mMaxScroll);
|
||||
if (mAllowOverScroll) {
|
||||
mWasInOverscroll = true;
|
||||
if (mIsRtl) {
|
||||
overScroll(x - mMinScrollX);
|
||||
} else {
|
||||
overScroll(x - mMaxScrollX);
|
||||
}
|
||||
overScroll(primaryScroll - (mIsRtl ? mMinScroll : mMaxScroll));
|
||||
}
|
||||
} else {
|
||||
if (mWasInOverscroll) {
|
||||
@@ -418,7 +447,13 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
}
|
||||
super.scrollTo(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for {@link PagedOrientationHandler} to be able to call parent's scrollTo method
|
||||
*/
|
||||
public void superScrollTo(int x, int y) {
|
||||
super.scrollTo(x, y);
|
||||
}
|
||||
|
||||
private void sendScrollAccessibilityEvent() {
|
||||
@@ -429,9 +464,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
ev.setScrollable(true);
|
||||
ev.setScrollX(getScrollX());
|
||||
ev.setScrollY(getScrollY());
|
||||
ev.setMaxScrollX(mMaxScrollX);
|
||||
ev.setMaxScrollY(0);
|
||||
|
||||
mOrientationHandler.setMaxScroll(ev, mMaxScroll);
|
||||
sendAccessibilityEventUnchecked(ev);
|
||||
}
|
||||
}
|
||||
@@ -452,9 +485,10 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
protected boolean computeScrollHelper(boolean shouldInvalidate) {
|
||||
if (mScroller.computeScrollOffset()) {
|
||||
// Don't bother scrolling if the page does not need to be moved
|
||||
if (getUnboundedScrollX() != mScroller.getCurrPos()
|
||||
|| getScrollX() != mScroller.getCurrPos()) {
|
||||
scrollTo(mScroller.getCurrPos(), 0);
|
||||
int currentScroll = mOrientationHandler.getPrimaryScroll(this);
|
||||
if (mUnboundedScroll != mScroller.getCurrPos()
|
||||
|| currentScroll != mScroller.getCurrPos()) {
|
||||
mOrientationHandler.set(this, VIEW_SCROLL_TO, mScroller.getCurrPos());
|
||||
}
|
||||
if (shouldInvalidate) {
|
||||
invalidate();
|
||||
@@ -573,7 +607,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
|
||||
if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
|
||||
|
||||
if (getPageScrolls(mPageScrolls, true, SIMPLE_SCROLL_LOGIC)) {
|
||||
boolean isScrollChanged = getPageScrolls(mPageScrolls, true, SIMPLE_SCROLL_LOGIC);
|
||||
if (isScrollChanged) {
|
||||
pageScrollChanged = true;
|
||||
}
|
||||
|
||||
@@ -614,7 +649,6 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
/**
|
||||
* Initializes {@code outPageScrolls} with scroll positions for view at that index. The length
|
||||
* of {@code outPageScrolls} should be same as the the childCount
|
||||
*
|
||||
*/
|
||||
protected boolean getPageScrolls(int[] outPageScrolls, boolean layoutChildren,
|
||||
ComputePageScrollsLogic scrollLogic) {
|
||||
@@ -624,36 +658,30 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
final int endIndex = mIsRtl ? -1 : childCount;
|
||||
final int delta = mIsRtl ? -1 : 1;
|
||||
|
||||
final int verticalCenter = (getPaddingTop() + getMeasuredHeight() + mInsets.top
|
||||
- mInsets.bottom - getPaddingBottom()) / 2;
|
||||
final int pageCenter = mOrientationHandler.getCenterForPage(this, mInsets);
|
||||
|
||||
final int scrollOffsetLeft = mInsets.left + getPaddingLeft();
|
||||
final int scrollOffsetRight = getWidth() - getPaddingRight() - mInsets.right;
|
||||
final int scrollOffsetStart = mOrientationHandler.getScrollOffsetStart(this, mInsets);
|
||||
final int scrollOffsetEnd = mOrientationHandler.getScrollOffsetEnd(this, mInsets);
|
||||
boolean pageScrollChanged = false;
|
||||
|
||||
for (int i = startIndex, childLeft = scrollOffsetLeft; i != endIndex; i += delta) {
|
||||
for (int i = startIndex, childStart = scrollOffsetStart; i != endIndex; i += delta) {
|
||||
final View child = getPageAt(i);
|
||||
if (scrollLogic.shouldIncludeView(child)) {
|
||||
final int childWidth = child.getMeasuredWidth();
|
||||
final int childRight = childLeft + childWidth;
|
||||
|
||||
if (layoutChildren) {
|
||||
final int childHeight = child.getMeasuredHeight();
|
||||
final int childTop = verticalCenter - childHeight / 2;
|
||||
child.layout(childLeft, childTop, childRight, childTop + childHeight);
|
||||
}
|
||||
ChildBounds bounds = mOrientationHandler.getChildBounds(child, childStart,
|
||||
pageCenter, layoutChildren);
|
||||
final int primaryDimension = bounds.primaryDimension;
|
||||
final int childPrimaryEnd = bounds.childPrimaryEnd;
|
||||
|
||||
// In case the pages are of different width, align the page to left or right edge
|
||||
// based on the orientation.
|
||||
final int pageScroll = mIsRtl
|
||||
? (childLeft - scrollOffsetLeft)
|
||||
: Math.max(0, childRight - scrollOffsetRight);
|
||||
? (childStart - scrollOffsetStart)
|
||||
: Math.max(0, childPrimaryEnd - scrollOffsetEnd);
|
||||
if (outPageScrolls[i] != pageScroll) {
|
||||
pageScrollChanged = true;
|
||||
outPageScrolls[i] = pageScroll;
|
||||
}
|
||||
|
||||
childLeft += childWidth + mPageSpacing + getChildGap();
|
||||
childStart += primaryDimension + mPageSpacing + getChildGap();
|
||||
}
|
||||
}
|
||||
return pageScrollChanged;
|
||||
@@ -664,15 +692,15 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
}
|
||||
|
||||
protected void updateMinAndMaxScrollX() {
|
||||
mMinScrollX = computeMinScrollX();
|
||||
mMaxScrollX = computeMaxScrollX();
|
||||
mMinScroll = computeMinScroll();
|
||||
mMaxScroll = computeMaxScroll();
|
||||
}
|
||||
|
||||
protected int computeMinScrollX() {
|
||||
protected int computeMinScroll() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected int computeMaxScrollX() {
|
||||
protected int computeMaxScroll() {
|
||||
int childCount = getChildCount();
|
||||
if (childCount > 0) {
|
||||
final int index = mIsRtl ? 0 : childCount - 1;
|
||||
@@ -715,7 +743,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
|
||||
protected int getChildOffset(int index) {
|
||||
if (index < 0 || index > getChildCount() - 1) return 0;
|
||||
return getPageAt(index).getLeft();
|
||||
View pageAtIndex = getPageAt(index);
|
||||
return mOrientationHandler.getChildStart(pageAtIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -866,13 +895,13 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
case MotionEvent.ACTION_MOVE: {
|
||||
/*
|
||||
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
|
||||
* whether the user has moved far enough from his original down touch.
|
||||
* whether the user has moved far enough from their original down touch.
|
||||
*/
|
||||
if (mActivePointerId != INVALID_POINTER) {
|
||||
determineScrollingStart(ev);
|
||||
}
|
||||
// if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
|
||||
// event. in that case, treat the first occurence of a move event as a ACTION_DOWN
|
||||
// event. in that case, treat the first occurrence of a move event as a ACTION_DOWN
|
||||
// i.e. fall through to the next case (don't break)
|
||||
// (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
|
||||
// while it's small- this was causing a crash before we checked for INVALID_POINTER)
|
||||
@@ -885,9 +914,10 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
// Remember location of down touch
|
||||
mDownMotionX = x;
|
||||
mDownMotionY = y;
|
||||
mLastMotionX = x;
|
||||
mLastMotionXRemainder = 0;
|
||||
mTotalMotionX = 0;
|
||||
mDownMotionPrimary = mLastMotion = mOrientationHandler.getPrimaryDirection(ev, 0);
|
||||
mLastMotionRemainder = 0;
|
||||
mTotalMotion = 0;
|
||||
mAllowEasyFling = false;
|
||||
mActivePointerId = ev.getPointerId(0);
|
||||
|
||||
updateIsBeingDraggedOnTouchDown();
|
||||
@@ -919,7 +949,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
private void updateIsBeingDraggedOnTouchDown() {
|
||||
// mScroller.isFinished should be false when being flinged.
|
||||
final int xDist = Math.abs(mScroller.getFinalPos() - mScroller.getCurrPos());
|
||||
final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop / 3);
|
||||
final boolean finishedScrolling = (mScroller.isFinished() || xDist < mPageSlop / 3);
|
||||
|
||||
if (finishedScrolling) {
|
||||
mIsBeingDragged = false;
|
||||
@@ -949,17 +979,17 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
|
||||
if (pointerIndex == -1) return;
|
||||
|
||||
final float x = ev.getX(pointerIndex);
|
||||
final int xDiff = (int) Math.abs(x - mLastMotionX);
|
||||
final float primaryDirection = mOrientationHandler.getPrimaryDirection(ev, pointerIndex);
|
||||
final int diff = (int) Math.abs(primaryDirection - mLastMotion);
|
||||
final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
|
||||
boolean xMoved = xDiff > touchSlop;
|
||||
boolean moved = diff > touchSlop || ev.getAction() == ACTION_MOVE_ALLOW_EASY_FLING;
|
||||
|
||||
if (xMoved) {
|
||||
if (moved) {
|
||||
// Scroll if the user moved far enough along the X axis
|
||||
mIsBeingDragged = true;
|
||||
mTotalMotionX += Math.abs(mLastMotionX - x);
|
||||
mLastMotionX = x;
|
||||
mLastMotionXRemainder = 0;
|
||||
mTotalMotion += Math.abs(mLastMotion - primaryDirection);
|
||||
mLastMotion = primaryDirection;
|
||||
mLastMotionRemainder = 0;
|
||||
onScrollInteractionBegin();
|
||||
pageBeginTransition();
|
||||
// Stop listening for things like pinches.
|
||||
@@ -1026,10 +1056,9 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
|
||||
@Override
|
||||
protected void dispatchDraw(Canvas canvas) {
|
||||
if (mScroller.isSpringing() && mSpringOverScrollX != 0) {
|
||||
if (mScroller.isSpringing() && mSpringOverScroll != 0) {
|
||||
int saveCount = canvas.save();
|
||||
|
||||
canvas.translate(-mSpringOverScrollX, 0);
|
||||
mOrientationHandler.set(canvas, CANVAS_TRANSLATE, -mSpringOverScroll);
|
||||
super.dispatchDraw(canvas);
|
||||
|
||||
canvas.restoreToCount(saveCount);
|
||||
@@ -1038,27 +1067,41 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the amount of overscroll caused by the spring in {@link OverScroller}.
|
||||
*/
|
||||
private int getSpringOverScroll(int amount) {
|
||||
if (mScroller.isSpringing()) {
|
||||
return amount < 0
|
||||
? mScroller.getCurrPos() - mMinScroll
|
||||
: Math.max(0, mScroller.getCurrPos() - mMaxScroll);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
protected void dampedOverScroll(int amount) {
|
||||
mSpringOverScrollX = amount;
|
||||
if (amount == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
int overScrollAmount = OverScroll.dampedScroll(amount, getMeasuredWidth());
|
||||
mSpringOverScrollX = overScrollAmount;
|
||||
int size = mOrientationHandler.getMeasuredSize(this);
|
||||
int overScrollAmount = OverScroll.dampedScroll(amount, size);
|
||||
if (mScroller.isSpringing()) {
|
||||
mSpringOverScroll = getSpringOverScroll(amount);
|
||||
invalidate();
|
||||
return;
|
||||
}
|
||||
|
||||
int x = Utilities.boundToRange(getScrollX(), mMinScrollX, mMaxScrollX);
|
||||
super.scrollTo(x + overScrollAmount, getScrollY());
|
||||
int primaryScroll = mOrientationHandler.getPrimaryScroll(this);
|
||||
int boundedScroll = Utilities.boundToRange(primaryScroll, mMinScroll, mMaxScroll);
|
||||
mOrientationHandler.delegateScrollTo(this, boundedScroll + overScrollAmount);
|
||||
invalidate();
|
||||
}
|
||||
|
||||
protected void overScroll(int amount) {
|
||||
mSpringOverScrollX = amount;
|
||||
if (mScroller.isSpringing()) {
|
||||
mSpringOverScroll = getSpringOverScroll(amount);
|
||||
invalidate();
|
||||
return;
|
||||
}
|
||||
@@ -1066,11 +1109,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
if (amount == 0) return;
|
||||
|
||||
if (mFreeScroll && !mScroller.isFinished()) {
|
||||
if (amount < 0) {
|
||||
super.scrollTo(mMinScrollX + amount, getScrollY());
|
||||
} else {
|
||||
super.scrollTo(mMaxScrollX + amount, getScrollY());
|
||||
}
|
||||
int scrollAmount = amount < 0 ? mMinScroll + amount : mMaxScroll + amount;
|
||||
mOrientationHandler.delegateScrollTo(this, scrollAmount);
|
||||
} else {
|
||||
dampedOverScroll(amount);
|
||||
}
|
||||
@@ -1120,18 +1160,25 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
}
|
||||
|
||||
// Remember where the motion event started
|
||||
mDownMotionX = mLastMotionX = ev.getX();
|
||||
mDownMotionX = ev.getX();
|
||||
mDownMotionY = ev.getY();
|
||||
mLastMotionXRemainder = 0;
|
||||
mTotalMotionX = 0;
|
||||
mDownMotionPrimary = mLastMotion = mOrientationHandler.getPrimaryDirection(ev, 0);
|
||||
mLastMotionRemainder = 0;
|
||||
mTotalMotion = 0;
|
||||
mAllowEasyFling = false;
|
||||
mActivePointerId = ev.getPointerId(0);
|
||||
|
||||
if (mIsBeingDragged) {
|
||||
onScrollInteractionBegin();
|
||||
pageBeginTransition();
|
||||
}
|
||||
break;
|
||||
|
||||
case ACTION_MOVE_ALLOW_EASY_FLING:
|
||||
// Start scrolling immediately
|
||||
determineScrollingStart(ev);
|
||||
mAllowEasyFling = true;
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
if (mIsBeingDragged) {
|
||||
// Scroll to follow the motion event
|
||||
@@ -1139,18 +1186,18 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
|
||||
if (pointerIndex == -1) return true;
|
||||
|
||||
final float x = ev.getX(pointerIndex);
|
||||
final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
|
||||
|
||||
mTotalMotionX += Math.abs(deltaX);
|
||||
float direction = mOrientationHandler.getPrimaryDirection(ev, pointerIndex);
|
||||
float delta = mLastMotion + mLastMotionRemainder - direction;
|
||||
mTotalMotion += Math.abs(delta);
|
||||
|
||||
// Only scroll and update mLastMotionX if we have moved some discrete amount. We
|
||||
// keep the remainder because we are actually testing if we've moved from the last
|
||||
// scrolled position (which is discrete).
|
||||
if (Math.abs(deltaX) >= 1.0f) {
|
||||
scrollBy((int) deltaX, 0);
|
||||
mLastMotionX = x;
|
||||
mLastMotionXRemainder = deltaX - (int) deltaX;
|
||||
if (Math.abs(delta) >= 1.0f) {
|
||||
mLastMotion = direction;
|
||||
mLastMotionRemainder = delta - (int) delta;
|
||||
|
||||
mOrientationHandler.set(this, VIEW_SCROLL_BY, (int) delta);
|
||||
} else {
|
||||
awakenScrollBars();
|
||||
}
|
||||
@@ -1163,27 +1210,38 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
if (mIsBeingDragged) {
|
||||
final int activePointerId = mActivePointerId;
|
||||
final int pointerIndex = ev.findPointerIndex(activePointerId);
|
||||
final float x = ev.getX(pointerIndex);
|
||||
if (pointerIndex == -1) return true;
|
||||
|
||||
final float primaryDirection = mOrientationHandler.getPrimaryDirection(ev,
|
||||
pointerIndex);
|
||||
final VelocityTracker velocityTracker = mVelocityTracker;
|
||||
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
|
||||
int velocityX = (int) velocityTracker.getXVelocity(mActivePointerId);
|
||||
final int deltaX = (int) (x - mDownMotionX);
|
||||
final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
|
||||
boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
|
||||
SIGNIFICANT_MOVE_THRESHOLD;
|
||||
|
||||
mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
|
||||
boolean isFling = mTotalMotionX > mTouchSlop && shouldFlingForVelocity(velocityX);
|
||||
boolean isDeltaXLeft = mIsRtl ? deltaX > 0 : deltaX < 0;
|
||||
boolean isVelocityXLeft = mIsRtl ? velocityX > 0 : velocityX < 0;
|
||||
int velocity = (int) mOrientationHandler.getPrimaryVelocity(velocityTracker,
|
||||
mActivePointerId);
|
||||
int delta = (int) (primaryDirection - mDownMotionPrimary);
|
||||
int pageOrientedSize = mOrientationHandler.getMeasuredSize(getPageAt(mCurrentPage));
|
||||
|
||||
boolean isSignificantMove = Math.abs(delta) > pageOrientedSize *
|
||||
SIGNIFICANT_MOVE_THRESHOLD;
|
||||
|
||||
mTotalMotion += Math.abs(mLastMotion + mLastMotionRemainder - primaryDirection);
|
||||
boolean passedSlop = mAllowEasyFling || mTotalMotion > mPageSlop;
|
||||
boolean isFling = passedSlop && shouldFlingForVelocity(velocity);
|
||||
boolean isDeltaLeft = mIsRtl ? delta > 0 : delta < 0;
|
||||
boolean isVelocityLeft = mIsRtl ? velocity > 0 : velocity < 0;
|
||||
if (DEBUG_FAILED_QUICKSWITCH && !isFling && mAllowEasyFling) {
|
||||
Log.d("Quickswitch", "isFling=false vel=" + velocity
|
||||
+ " threshold=" + mEasyFlingThresholdVelocity);
|
||||
}
|
||||
|
||||
if (!mFreeScroll) {
|
||||
// In the case that the page is moved far to one direction and then is flung
|
||||
// in the opposite direction, we use a threshold to determine whether we should
|
||||
// just return to the starting page, or if we should skip one further.
|
||||
boolean returnToOriginalPage = false;
|
||||
if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
|
||||
Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
|
||||
if (Math.abs(delta) > pageOrientedSize * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
|
||||
Math.signum(velocity) != Math.signum(delta) && isFling) {
|
||||
returnToOriginalPage = true;
|
||||
}
|
||||
|
||||
@@ -1192,15 +1250,15 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
// test for a large move if a fling has been registered. That is, a large
|
||||
// move to the left and fling to the right will register as a fling to the right.
|
||||
|
||||
if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
|
||||
(isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
|
||||
if (((isSignificantMove && !isDeltaLeft && !isFling) ||
|
||||
(isFling && !isVelocityLeft)) && mCurrentPage > 0) {
|
||||
finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
|
||||
snapToPageWithVelocity(finalPage, velocityX);
|
||||
} else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
|
||||
(isFling && isVelocityXLeft)) &&
|
||||
snapToPageWithVelocity(finalPage, velocity);
|
||||
} else if (((isSignificantMove && isDeltaLeft && !isFling) ||
|
||||
(isFling && isVelocityLeft)) &&
|
||||
mCurrentPage < getChildCount() - 1) {
|
||||
finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
|
||||
snapToPageWithVelocity(finalPage, velocityX);
|
||||
snapToPageWithVelocity(finalPage, velocity);
|
||||
} else {
|
||||
snapToDestination();
|
||||
}
|
||||
@@ -1209,38 +1267,40 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
abortScrollerAnimation(true);
|
||||
}
|
||||
|
||||
int initialScrollX = getScrollX();
|
||||
int initialScroll = mOrientationHandler.getPrimaryScroll(this);
|
||||
int maxScroll = mMaxScroll;
|
||||
int minScroll = mMinScroll;
|
||||
|
||||
if (((initialScrollX >= mMaxScrollX) && (isVelocityXLeft || !isFling)) ||
|
||||
((initialScrollX <= mMinScrollX) && (!isVelocityXLeft || !isFling))) {
|
||||
mScroller.springBack(getScrollX(), mMinScrollX, mMaxScrollX);
|
||||
if (((initialScroll >= maxScroll) && (isVelocityLeft || !isFling)) ||
|
||||
((initialScroll <= minScroll) && (!isVelocityLeft || !isFling))) {
|
||||
mScroller.springBack(initialScroll, minScroll, maxScroll);
|
||||
mNextPage = getPageNearestToCenterOfScreen();
|
||||
} else {
|
||||
mScroller.setInterpolator(mDefaultInterpolator);
|
||||
mScroller.fling(initialScrollX, -velocityX,
|
||||
mMinScrollX, mMaxScrollX,
|
||||
Math.round(getWidth() * 0.5f * OVERSCROLL_DAMP_FACTOR));
|
||||
mScroller.fling(initialScroll, -velocity,
|
||||
minScroll, maxScroll,
|
||||
Math.round(getWidth() * 0.5f * OVERSCROLL_DAMP_FACTOR));
|
||||
|
||||
int finalX = mScroller.getFinalPos();
|
||||
mNextPage = getPageNearestToCenterOfScreen(finalX);
|
||||
int finalPos = mScroller.getFinalPos();
|
||||
mNextPage = getPageNearestToCenterOfScreen(finalPos);
|
||||
|
||||
int firstPageScroll = getScrollForPage(!mIsRtl ? 0 : getPageCount() - 1);
|
||||
int lastPageScroll = getScrollForPage(!mIsRtl ? getPageCount() - 1 : 0);
|
||||
if (finalX > mMinScrollX && finalX < mMaxScrollX) {
|
||||
if (finalPos > minScroll && finalPos < maxScroll) {
|
||||
// If scrolling ends in the half of the added space that is closer to
|
||||
// the end, settle to the end. Otherwise snap to the nearest page.
|
||||
// If flinging past one of the ends, don't change the velocity as it
|
||||
// will get stopped at the end anyway.
|
||||
int pageSnappedX = finalX < (firstPageScroll + mMinScrollX) / 2
|
||||
? mMinScrollX
|
||||
: finalX > (lastPageScroll + mMaxScrollX) / 2
|
||||
? mMaxScrollX
|
||||
: getScrollForPage(mNextPage);
|
||||
int pageSnapped = finalPos < (firstPageScroll + minScroll) / 2
|
||||
? minScroll
|
||||
: finalPos > (lastPageScroll + maxScroll) / 2
|
||||
? maxScroll
|
||||
: getScrollForPage(mNextPage);
|
||||
|
||||
mScroller.setFinalPos(pageSnappedX);
|
||||
mScroller.setFinalPos(pageSnapped);
|
||||
// Ensure the scroll/snap doesn't happen too fast;
|
||||
int extraScrollDuration = OVERSCROLL_PAGE_SNAP_ANIMATION_DURATION
|
||||
- mScroller.getDuration();
|
||||
- mScroller.getDuration();
|
||||
if (extraScrollDuration > 0) {
|
||||
mScroller.extendDuration(extraScrollDuration);
|
||||
}
|
||||
@@ -1272,8 +1332,9 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
return true;
|
||||
}
|
||||
|
||||
protected boolean shouldFlingForVelocity(int velocityX) {
|
||||
return Math.abs(velocityX) > mFlingThresholdVelocity;
|
||||
protected boolean shouldFlingForVelocity(int velocity) {
|
||||
float threshold = mAllowEasyFling ? mEasyFlingThresholdVelocity : mFlingThresholdVelocity;
|
||||
return Math.abs(velocity) > threshold;
|
||||
}
|
||||
|
||||
private void resetTouchState() {
|
||||
@@ -1296,10 +1357,6 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
|
||||
switch (event.getAction()) {
|
||||
case MotionEvent.ACTION_SCROLL: {
|
||||
Launcher launcher = Launcher.getLauncher(getContext());
|
||||
if (launcher != null) {
|
||||
AbstractFloatingView.closeAllOpenViews(launcher);
|
||||
}
|
||||
// Handle mouse (or ext. device) by shifting the page depending on the scroll
|
||||
final float vscroll;
|
||||
final float hscroll;
|
||||
@@ -1310,8 +1367,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
|
||||
hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
|
||||
}
|
||||
if (Math.abs(vscroll) > Math.abs(hscroll) && !isVerticalScrollable()) {
|
||||
return true;
|
||||
if (!canScroll(Math.abs(vscroll), Math.abs(hscroll))) {
|
||||
return false;
|
||||
}
|
||||
if (hscroll != 0 || vscroll != 0) {
|
||||
boolean isForwardScroll = mIsRtl ? (hscroll < 0 || vscroll < 0)
|
||||
@@ -1329,8 +1386,13 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
return super.onGenericMotionEvent(event);
|
||||
}
|
||||
|
||||
protected boolean isVerticalScrollable() {
|
||||
return true;
|
||||
/**
|
||||
* Returns true if the paged view can scroll for the provided vertical and horizontal
|
||||
* scroll values
|
||||
*/
|
||||
protected boolean canScroll(float absVScroll, float absHScroll) {
|
||||
ActivityContext ac = ActivityContext.lookupContext(getContext());
|
||||
return (ac == null || AbstractFloatingView.getTopOpenView(ac) == null);
|
||||
}
|
||||
|
||||
private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
|
||||
@@ -1349,16 +1411,16 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
}
|
||||
|
||||
private void onSecondaryPointerUp(MotionEvent ev) {
|
||||
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
|
||||
MotionEvent.ACTION_POINTER_INDEX_SHIFT;
|
||||
final int pointerIndex = ev.getActionIndex();
|
||||
final int pointerId = ev.getPointerId(pointerIndex);
|
||||
if (pointerId == mActivePointerId) {
|
||||
// This was our active pointer going up. Choose a new
|
||||
// active pointer and adjust accordingly.
|
||||
// TODO: Make this decision more intelligent.
|
||||
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
|
||||
mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
|
||||
mLastMotionXRemainder = 0;
|
||||
mLastMotion = mDownMotionPrimary = mOrientationHandler.getPrimaryDirection(ev,
|
||||
newPointerIndex);
|
||||
mLastMotionRemainder = 0;
|
||||
mActivePointerId = ev.getPointerId(newPointerIndex);
|
||||
if (mVelocityTracker != null) {
|
||||
mVelocityTracker.clear();
|
||||
@@ -1376,19 +1438,20 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
}
|
||||
|
||||
public int getPageNearestToCenterOfScreen() {
|
||||
return getPageNearestToCenterOfScreen(getScrollX());
|
||||
return getPageNearestToCenterOfScreen(mOrientationHandler.getPrimaryScroll(this));
|
||||
}
|
||||
|
||||
private int getPageNearestToCenterOfScreen(int scaledScrollX) {
|
||||
int screenCenter = scaledScrollX + (getMeasuredWidth() / 2);
|
||||
private int getPageNearestToCenterOfScreen(int scaledScroll) {
|
||||
int pageOrientationSize = mOrientationHandler.getMeasuredSize(this);
|
||||
int screenCenter = scaledScroll + (pageOrientationSize / 2);
|
||||
int minDistanceFromScreenCenter = Integer.MAX_VALUE;
|
||||
int minDistanceFromScreenCenterIndex = -1;
|
||||
final int childCount = getChildCount();
|
||||
for (int i = 0; i < childCount; ++i) {
|
||||
View layout = getPageAt(i);
|
||||
int childWidth = layout.getMeasuredWidth();
|
||||
int halfChildWidth = (childWidth / 2);
|
||||
int childCenter = getChildOffset(i) + halfChildWidth;
|
||||
int childSize = mOrientationHandler.getMeasuredSize(layout);
|
||||
int halfChildSize = (childSize / 2);
|
||||
int childCenter = getChildOffset(i) + halfChildSize;
|
||||
int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
|
||||
if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
|
||||
minDistanceFromScreenCenter = distanceFromScreenCenter;
|
||||
@@ -1403,7 +1466,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
}
|
||||
|
||||
protected boolean isInOverScroll() {
|
||||
return (getScrollX() > mMaxScrollX || getScrollX() < mMinScrollX);
|
||||
int scroll = mOrientationHandler.getPrimaryScroll(this);
|
||||
return scroll > mMaxScroll || scroll < mMinScroll;
|
||||
}
|
||||
|
||||
protected int getPageSnapDuration() {
|
||||
@@ -1425,10 +1489,10 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
|
||||
protected boolean snapToPageWithVelocity(int whichPage, int velocity) {
|
||||
whichPage = validateNewPage(whichPage);
|
||||
int halfScreenSize = getMeasuredWidth() / 2;
|
||||
int halfScreenSize = mOrientationHandler.getMeasuredSize(this) / 2;
|
||||
|
||||
final int newX = getScrollForPage(whichPage);
|
||||
int delta = newX - getUnboundedScrollX();
|
||||
final int newLoc = getScrollForPage(whichPage);
|
||||
int delta = newLoc - getUnboundedScroll();
|
||||
int duration = 0;
|
||||
|
||||
if (Math.abs(velocity) < mMinFlingVelocity) {
|
||||
@@ -1453,9 +1517,9 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
// interpolator at zero, ie. 5. We use 4 to make it a little slower.
|
||||
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
|
||||
|
||||
if (QUICKSTEP_SPRINGS.get()) {
|
||||
if (QUICKSTEP_SPRINGS.get() && mCurrentPage != whichPage) {
|
||||
return snapToPage(whichPage, delta, duration, false, null,
|
||||
velocity * Math.signum(newX - getUnboundedScrollX()), true);
|
||||
velocity * Math.signum(delta), true);
|
||||
} else {
|
||||
return snapToPage(whichPage, delta, duration);
|
||||
}
|
||||
@@ -1481,8 +1545,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
TimeInterpolator interpolator) {
|
||||
whichPage = validateNewPage(whichPage);
|
||||
|
||||
int newX = getScrollForPage(whichPage);
|
||||
final int delta = newX - getUnboundedScrollX();
|
||||
int newLoc = getScrollForPage(whichPage);
|
||||
final int delta = newLoc - getUnboundedScroll();
|
||||
return snapToPage(whichPage, delta, duration, immediate, interpolator, 0, false);
|
||||
}
|
||||
|
||||
@@ -1497,7 +1561,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
return false;
|
||||
}
|
||||
|
||||
if (FeatureFlags.IS_DOGFOOD_BUILD) {
|
||||
if (FeatureFlags.IS_STUDIO_BUILD) {
|
||||
duration *= Settings.Global.getFloat(getContext().getContentResolver(),
|
||||
Settings.Global.WINDOW_ANIMATION_SCALE, 1);
|
||||
}
|
||||
@@ -1528,9 +1592,9 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
|
||||
}
|
||||
|
||||
if (spring && QUICKSTEP_SPRINGS.get()) {
|
||||
mScroller.startScrollSpring(getUnboundedScrollX(), delta, duration, velocity);
|
||||
mScroller.startScrollSpring(getUnboundedScroll(), delta, duration, velocity);
|
||||
} else {
|
||||
mScroller.startScroll(getUnboundedScrollX(), delta, duration);
|
||||
mScroller.startScroll(getUnboundedScroll(), delta, duration);
|
||||
}
|
||||
|
||||
updatePageIndicator();
|
||||
|
||||
@@ -53,21 +53,12 @@ public class Partner {
|
||||
public static final String RES_GRID_NUM_COLUMNS = "grid_num_columns";
|
||||
public static final String RES_GRID_ICON_SIZE_DP = "grid_icon_size_dp";
|
||||
|
||||
private static boolean sSearched = false;
|
||||
private static Partner sPartner;
|
||||
|
||||
/**
|
||||
* Find and return partner details, or {@code null} if none exists.
|
||||
*/
|
||||
public static synchronized Partner get(PackageManager pm) {
|
||||
if (!sSearched) {
|
||||
Pair<String, Resources> apkInfo = findSystemApk(ACTION_PARTNER_CUSTOMIZATION, pm);
|
||||
if (apkInfo != null) {
|
||||
sPartner = new Partner(apkInfo.first, apkInfo.second);
|
||||
}
|
||||
sSearched = true;
|
||||
}
|
||||
return sPartner;
|
||||
Pair<String, Resources> apkInfo = findSystemApk(ACTION_PARTNER_CUSTOMIZATION, pm);
|
||||
return apkInfo != null ? new Partner(apkInfo.first, apkInfo.second) : null;
|
||||
}
|
||||
|
||||
private final String mPackageName;
|
||||
|
||||
@@ -18,10 +18,15 @@ package com.android.launcher3;
|
||||
|
||||
import android.content.ComponentName;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Meta data that is used for deferred binding.
|
||||
* e.g., this object is used to pass information on draggable targets when they are dropped onto
|
||||
* the workspace from another container.
|
||||
* Meta data that is used for deferred binding. e.g., this object is used to pass information on
|
||||
* draggable targets when they are dropped onto the workspace from another container.
|
||||
*/
|
||||
public class PendingAddItemInfo extends ItemInfo {
|
||||
|
||||
@@ -34,4 +39,22 @@ public class PendingAddItemInfo extends ItemInfo {
|
||||
protected String dumpProperties() {
|
||||
return super.dumpProperties() + " componentName=" + componentName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns shallow copy of the object.
|
||||
*/
|
||||
@Override
|
||||
public ItemInfo makeShallowCopy() {
|
||||
PendingAddItemInfo itemInfo = new PendingAddItemInfo();
|
||||
itemInfo.copyFrom(this);
|
||||
itemInfo.componentName = this.componentName;
|
||||
return itemInfo;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public ComponentName getTargetComponent() {
|
||||
return Optional.ofNullable(super.getTargetComponent()).orElse(componentName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import android.graphics.PointF;
|
||||
import android.view.View;
|
||||
|
||||
public interface Reorderable {
|
||||
|
||||
/**
|
||||
* Set the offset related to reorder hint and bounce animations
|
||||
*/
|
||||
void setReorderBounceOffset(float x, float y);
|
||||
|
||||
void getReorderBounceOffset(PointF offset);
|
||||
|
||||
/**
|
||||
* Set the offset related to previewing the new reordered position
|
||||
*/
|
||||
void setReorderPreviewOffset(float x, float y);
|
||||
|
||||
void getReorderPreviewOffset(PointF offset);
|
||||
|
||||
/**
|
||||
* Set the scale related to reorder hint and "bounce" animations
|
||||
*/
|
||||
void setReorderBounceScale(float scale);
|
||||
float getReorderBounceScale();
|
||||
|
||||
/**
|
||||
* Get the com.android.view related to this object
|
||||
*/
|
||||
View getView();
|
||||
}
|
||||
@@ -21,15 +21,15 @@ import android.util.DisplayMetrics;
|
||||
import android.util.TypedValue;
|
||||
|
||||
public class ResourceUtils {
|
||||
public static final int DEFAULT_NAVBAR_VALUE = 48;
|
||||
public static final String NAVBAR_LANDSCAPE_LEFT_RIGHT_SIZE = "navigation_bar_width";
|
||||
public static final String NAVBAR_BOTTOM_GESTURE_SIZE = "navigation_bar_gesture_height";
|
||||
|
||||
|
||||
public static int getNavbarSize(String resName, Resources res) {
|
||||
return getDimenByName(resName, res, 48);
|
||||
return getDimenByName(resName, res, DEFAULT_NAVBAR_VALUE);
|
||||
}
|
||||
|
||||
private static int getDimenByName(String resName, Resources res, int defaultValue) {
|
||||
public static int getDimenByName(String resName, Resources res, int defaultValue) {
|
||||
final int frameSize;
|
||||
final int frameSizeResID = res.getIdentifier(resName, "dimen", "android");
|
||||
if (frameSizeResID != 0) {
|
||||
@@ -40,6 +40,17 @@ public class ResourceUtils {
|
||||
return frameSize;
|
||||
}
|
||||
|
||||
public static boolean getBoolByName(String resName, Resources res, boolean defaultValue) {
|
||||
final boolean val;
|
||||
final int resId = res.getIdentifier(resName, "bool", "android");
|
||||
if (resId != 0) {
|
||||
val = res.getBoolean(resId);
|
||||
} else {
|
||||
val = defaultValue;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
public static int pxFromDp(float size, DisplayMetrics metrics) {
|
||||
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, size, metrics));
|
||||
}
|
||||
|
||||
@@ -3,11 +3,16 @@ package com.android.launcher3;
|
||||
import static android.appwidget.AppWidgetManager.INVALID_APPWIDGET_ID;
|
||||
import static android.appwidget.AppWidgetProviderInfo.WIDGET_FEATURE_RECONFIGURABLE;
|
||||
|
||||
import static com.android.launcher3.ItemInfoWithIcon.FLAG_SYSTEM_MASK;
|
||||
import static com.android.launcher3.ItemInfoWithIcon.FLAG_SYSTEM_NO;
|
||||
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
|
||||
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.DISMISS_PREDICTION;
|
||||
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.RECONFIGURE;
|
||||
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.UNINSTALL;
|
||||
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROPPED_ON_DONT_SUGGEST;
|
||||
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROPPED_ON_UNINSTALL;
|
||||
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_UNINSTALL_CANCELLED;
|
||||
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_UNINSTALL_COMPLETED;
|
||||
import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_SYSTEM_MASK;
|
||||
import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_SYSTEM_NO;
|
||||
|
||||
import android.appwidget.AppWidgetHostView;
|
||||
import android.appwidget.AppWidgetProviderInfo;
|
||||
@@ -16,6 +21,7 @@ import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.LauncherActivityInfo;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
@@ -28,20 +34,28 @@ import android.view.View;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.android.launcher3.Launcher.OnResumeCallback;
|
||||
import com.android.launcher3.compat.LauncherAppsCompat;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.dragndrop.DragOptions;
|
||||
import com.android.launcher3.logging.FileLog;
|
||||
import com.android.launcher3.logging.LoggerUtils;
|
||||
import com.android.launcher3.logging.StatsLogManager;
|
||||
import com.android.launcher3.model.AppLaunchTracker;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.ItemInfoWithIcon;
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.ControlType;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
|
||||
import com.android.launcher3.util.PackageManagerHelper;
|
||||
import com.android.launcher3.util.Themes;
|
||||
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* Drop target which provides a secondary option for an item.
|
||||
* For app targets: shows as uninstall
|
||||
* For configurable widgets: shows as setup
|
||||
* For predicted app icons: don't suggest app
|
||||
*/
|
||||
public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmListener {
|
||||
|
||||
@@ -49,8 +63,9 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
|
||||
private static final long CACHE_EXPIRE_TIMEOUT = 5000;
|
||||
private final ArrayMap<UserHandle, Boolean> mUninstallDisabledCache = new ArrayMap<>(1);
|
||||
|
||||
private final StatsLogManager mStatsLogManager;
|
||||
private final Alarm mCacheExpireAlarm;
|
||||
private boolean mHadPendingAlarm;
|
||||
|
||||
protected int mCurrentAccessibilityAction = -1;
|
||||
public SecondaryDropTarget(Context context, AttributeSet attrs) {
|
||||
@@ -59,9 +74,28 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
|
||||
public SecondaryDropTarget(Context context, AttributeSet attrs, int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
|
||||
mCacheExpireAlarm = new Alarm();
|
||||
mCacheExpireAlarm.setOnAlarmListener(this);
|
||||
mStatsLogManager = StatsLogManager.newInstance(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onAttachedToWindow() {
|
||||
super.onAttachedToWindow();
|
||||
if (mHadPendingAlarm) {
|
||||
mCacheExpireAlarm.setAlarm(CACHE_EXPIRE_TIMEOUT);
|
||||
mCacheExpireAlarm.setOnAlarmListener(this);
|
||||
mHadPendingAlarm = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDetachedFromWindow() {
|
||||
super.onDetachedFromWindow();
|
||||
if (mCacheExpireAlarm.alarmPending()) {
|
||||
mCacheExpireAlarm.cancelAlarm();
|
||||
mCacheExpireAlarm.setOnAlarmListener(null);
|
||||
mHadPendingAlarm = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -80,7 +114,11 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
mHoverColor = getResources().getColor(R.color.uninstall_target_hover_tint);
|
||||
setDrawable(R.drawable.ic_uninstall_shadow);
|
||||
updateText(R.string.uninstall_drop_target_label);
|
||||
} else {
|
||||
} else if (action == DISMISS_PREDICTION) {
|
||||
mHoverColor = Themes.getColorAccent(getContext());
|
||||
setDrawable(R.drawable.ic_block_shadow);
|
||||
updateText(R.string.dismiss_prediction_label);
|
||||
} else if (action == RECONFIGURE) {
|
||||
mHoverColor = Themes.getColorAccent(getContext());
|
||||
setDrawable(R.drawable.ic_setup_shadow);
|
||||
updateText(R.string.gadget_setup_text);
|
||||
@@ -100,8 +138,13 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
@Override
|
||||
public Target getDropTargetForLogging() {
|
||||
Target t = LoggerUtils.newTarget(Target.Type.CONTROL);
|
||||
t.controlType = mCurrentAccessibilityAction == UNINSTALL ? ControlType.UNINSTALL_TARGET
|
||||
: ControlType.SETTINGS_BUTTON;
|
||||
if (mCurrentAccessibilityAction == UNINSTALL) {
|
||||
t.controlType = ControlType.UNINSTALL_TARGET;
|
||||
} else if (mCurrentAccessibilityAction == DISMISS_PREDICTION) {
|
||||
t.controlType = ControlType.DISMISS_PREDICTION;
|
||||
} else {
|
||||
t.controlType = ControlType.SETTINGS_BUTTON;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
@@ -118,6 +161,9 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} else if (FeatureFlags.ENABLE_PREDICTION_DISMISS.get() && info.isPredictedItem()) {
|
||||
setupUi(DISMISS_PREDICTION);
|
||||
return true;
|
||||
}
|
||||
|
||||
setupUi(UNINSTALL);
|
||||
@@ -132,6 +178,7 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
}
|
||||
// Cancel any pending alarm and set cache expiry after some time
|
||||
mCacheExpireAlarm.setAlarm(CACHE_EXPIRE_TIMEOUT);
|
||||
mCacheExpireAlarm.setOnAlarmListener(this);
|
||||
if (uninstallDisabled) {
|
||||
return false;
|
||||
}
|
||||
@@ -157,7 +204,7 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
user = item.user;
|
||||
}
|
||||
if (intent != null) {
|
||||
LauncherActivityInfo info = LauncherAppsCompat.getInstance(mLauncher)
|
||||
LauncherActivityInfo info = mLauncher.getSystemService(LauncherApps.class)
|
||||
.resolveActivity(intent, user);
|
||||
if (info != null
|
||||
&& (info.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
|
||||
@@ -172,6 +219,13 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
// Defer onComplete
|
||||
d.dragSource = new DeferredOnComplete(d.dragSource, getContext());
|
||||
super.onDrop(d, options);
|
||||
if (mCurrentAccessibilityAction == UNINSTALL) {
|
||||
mStatsLogManager.logger().withInstanceId(d.logInstanceId)
|
||||
.log(LAUNCHER_ITEM_DROPPED_ON_UNINSTALL);
|
||||
} else if (mCurrentAccessibilityAction == DISMISS_PREDICTION) {
|
||||
mStatsLogManager.logger().withInstanceId(d.logInstanceId)
|
||||
.log(LAUNCHER_ITEM_DROPPED_ON_DONT_SUGGEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -228,6 +282,11 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (mCurrentAccessibilityAction == DISMISS_PREDICTION) {
|
||||
AppLaunchTracker.INSTANCE.get(getContext()).onDismissApp(info.getTargetComponent(),
|
||||
info.user, AppLaunchTracker.CONTAINER_PREDICTIONS);
|
||||
return null;
|
||||
}
|
||||
// else: mCurrentAccessibilityAction == UNINSTALL
|
||||
|
||||
ComponentName cn = getUninstallTarget(info);
|
||||
@@ -279,21 +338,24 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fillInLogContainerData(View v, ItemInfo info, Target target,
|
||||
Target targetParent) {
|
||||
mOriginal.fillInLogContainerData(v, info, target, targetParent);
|
||||
public void fillInLogContainerData(ItemInfo childInfo, Target child,
|
||||
ArrayList<Target> parents) {
|
||||
mOriginal.fillInLogContainerData(childInfo, child, parents);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLauncherResume() {
|
||||
// We use MATCH_UNINSTALLED_PACKAGES as the app can be on SD card as well.
|
||||
if (LauncherAppsCompat.getInstance(mContext)
|
||||
.getApplicationInfo(mPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
|
||||
mDragObject.dragInfo.user) == null) {
|
||||
if (new PackageManagerHelper(mContext).getApplicationInfo(mPackageName,
|
||||
mDragObject.dragInfo.user, PackageManager.MATCH_UNINSTALLED_PACKAGES) == null) {
|
||||
mDragObject.dragSource = mOriginal;
|
||||
mOriginal.onDropCompleted(SecondaryDropTarget.this, mDragObject, true);
|
||||
mStatsLogManager.logger().withInstanceId(mDragObject.logInstanceId)
|
||||
.log(LAUNCHER_ITEM_UNINSTALL_COMPLETED);
|
||||
} else {
|
||||
sendFailure();
|
||||
mStatsLogManager.logger().withInstanceId(mDragObject.logInstanceId)
|
||||
.log(LAUNCHER_ITEM_UNINSTALL_CANCELLED);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.pm.InstallSessionHelper.getUserHandle;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.ComponentName;
|
||||
@@ -23,6 +25,7 @@ import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.LauncherActivityInfo;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.pm.PackageInstaller;
|
||||
import android.content.pm.PackageInstaller.SessionInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
@@ -37,14 +40,11 @@ import android.provider.Settings;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import com.android.launcher3.compat.LauncherAppsCompat;
|
||||
import com.android.launcher3.pm.InstallSessionHelper;
|
||||
import com.android.launcher3.util.Executors;
|
||||
import com.android.launcher3.compat.PackageInstallerCompat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static com.android.launcher3.compat.PackageInstallerCompat.getUserHandle;
|
||||
|
||||
/**
|
||||
* BroadcastReceiver to handle session commit intent.
|
||||
*/
|
||||
@@ -77,7 +77,8 @@ public class SessionCommitReceiver extends BroadcastReceiver {
|
||||
return;
|
||||
}
|
||||
|
||||
PackageInstallerCompat packageInstallerCompat = PackageInstallerCompat.getInstance(context);
|
||||
InstallSessionHelper packageInstallerCompat = InstallSessionHelper.INSTANCE.get(context);
|
||||
packageInstallerCompat.restoreDbIfApplicable(info);
|
||||
if (TextUtils.isEmpty(info.getAppPackageName())
|
||||
|| info.getInstallReason() != PackageManager.INSTALL_REASON_USER
|
||||
|| packageInstallerCompat.promiseIconAddedForId(info.getSessionId())) {
|
||||
@@ -90,9 +91,8 @@ public class SessionCommitReceiver extends BroadcastReceiver {
|
||||
|
||||
public static void queuePromiseAppIconAddition(Context context, SessionInfo sessionInfo) {
|
||||
String packageName = sessionInfo.getAppPackageName();
|
||||
List<LauncherActivityInfo> activities = LauncherAppsCompat.getInstance(context)
|
||||
.getActivityList(packageName, getUserHandle(sessionInfo));
|
||||
if (activities == null || activities.isEmpty()) {
|
||||
if (context.getSystemService(LauncherApps.class)
|
||||
.getActivityList(packageName, getUserHandle(sessionInfo)).isEmpty()) {
|
||||
// Ensure application isn't already installed.
|
||||
queueAppIconAddition(context, packageName, sessionInfo.getAppLabel(),
|
||||
sessionInfo.getAppIcon(), getUserHandle(sessionInfo));
|
||||
@@ -100,9 +100,9 @@ public class SessionCommitReceiver extends BroadcastReceiver {
|
||||
}
|
||||
|
||||
public static void queueAppIconAddition(Context context, String packageName, UserHandle user) {
|
||||
List<LauncherActivityInfo> activities = LauncherAppsCompat.getInstance(context)
|
||||
List<LauncherActivityInfo> activities = context.getSystemService(LauncherApps.class)
|
||||
.getActivityList(packageName, user);
|
||||
if (activities == null || activities.isEmpty()) {
|
||||
if (activities.isEmpty()) {
|
||||
// no activity found
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ public class ShortcutAndWidgetContainer extends ViewGroup {
|
||||
public void setupLp(View child) {
|
||||
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
|
||||
if (child instanceof LauncherAppWidgetHostView) {
|
||||
DeviceProfile profile = mActivity.getWallpaperDeviceProfile();
|
||||
DeviceProfile profile = mActivity.getDeviceProfile();
|
||||
lp.setup(mCellWidth, mCellHeight, invertLayoutHorizontally(), mCountX,
|
||||
profile.appWidgetScale.x, profile.appWidgetScale.y);
|
||||
} else {
|
||||
@@ -108,12 +108,12 @@ public class ShortcutAndWidgetContainer extends ViewGroup {
|
||||
|
||||
public int getCellContentHeight() {
|
||||
return Math.min(getMeasuredHeight(),
|
||||
mActivity.getWallpaperDeviceProfile().getCellHeight(mContainerType));
|
||||
mActivity.getDeviceProfile().getCellHeight(mContainerType));
|
||||
}
|
||||
|
||||
public void measureChild(View child) {
|
||||
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
|
||||
final DeviceProfile profile = mActivity.getWallpaperDeviceProfile();
|
||||
final DeviceProfile profile = mActivity.getDeviceProfile();
|
||||
|
||||
if (child instanceof LauncherAppWidgetHostView) {
|
||||
lp.setup(mCellWidth, mCellHeight, invertLayoutHorizontally(), mCountX,
|
||||
@@ -145,38 +145,46 @@ public class ShortcutAndWidgetContainer extends ViewGroup {
|
||||
final View child = getChildAt(i);
|
||||
if (child.getVisibility() != GONE) {
|
||||
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
|
||||
|
||||
if (child instanceof LauncherAppWidgetHostView) {
|
||||
LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) child;
|
||||
|
||||
// Scale and center the widget to fit within its cells.
|
||||
DeviceProfile profile = mActivity.getDeviceProfile();
|
||||
float scaleX = profile.appWidgetScale.x;
|
||||
float scaleY = profile.appWidgetScale.y;
|
||||
|
||||
lahv.setScaleToFit(Math.min(scaleX, scaleY));
|
||||
lahv.setTranslationForCentering(-(lp.width - (lp.width * scaleX)) / 2.0f,
|
||||
-(lp.height - (lp.height * scaleY)) / 2.0f);
|
||||
}
|
||||
|
||||
int childLeft = lp.x;
|
||||
int childTop = lp.y;
|
||||
child.layout(childLeft, childTop, childLeft + lp.width, childTop + lp.height);
|
||||
|
||||
if (lp.dropped) {
|
||||
lp.dropped = false;
|
||||
|
||||
final int[] cellXY = mTmpCellXY;
|
||||
getLocationOnScreen(cellXY);
|
||||
mWallpaperManager.sendWallpaperCommand(getWindowToken(),
|
||||
WallpaperManager.COMMAND_DROP,
|
||||
cellXY[0] + childLeft + lp.width / 2,
|
||||
cellXY[1] + childTop + lp.height / 2, 0, null);
|
||||
}
|
||||
layoutChild(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Core logic to layout a child for this ViewGroup.
|
||||
*/
|
||||
public void layoutChild(View child) {
|
||||
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
|
||||
if (child instanceof LauncherAppWidgetHostView) {
|
||||
LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) child;
|
||||
|
||||
// Scale and center the widget to fit within its cells.
|
||||
DeviceProfile profile = mActivity.getDeviceProfile();
|
||||
float scaleX = profile.appWidgetScale.x;
|
||||
float scaleY = profile.appWidgetScale.y;
|
||||
|
||||
lahv.setScaleToFit(Math.min(scaleX, scaleY));
|
||||
lahv.setTranslationForCentering(-(lp.width - (lp.width * scaleX)) / 2.0f,
|
||||
-(lp.height - (lp.height * scaleY)) / 2.0f);
|
||||
}
|
||||
|
||||
int childLeft = lp.x;
|
||||
int childTop = lp.y;
|
||||
child.layout(childLeft, childTop, childLeft + lp.width, childTop + lp.height);
|
||||
|
||||
if (lp.dropped) {
|
||||
lp.dropped = false;
|
||||
|
||||
final int[] cellXY = mTmpCellXY;
|
||||
getLocationOnScreen(cellXY);
|
||||
mWallpaperManager.sendWallpaperCommand(getWindowToken(),
|
||||
WallpaperManager.COMMAND_DROP,
|
||||
cellXY[0] + childLeft + lp.width / 2,
|
||||
cellXY[1] + childTop + lp.height / 2, 0, null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean onInterceptTouchEvent(MotionEvent ev) {
|
||||
if (ev.getAction() == ACTION_DOWN && getAlpha() == 0) {
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
|
||||
import com.android.launcher3.StylusEventHelper.StylusButtonListener;
|
||||
|
||||
/**
|
||||
* Simple listener that performs a long click on the view after a stylus button press.
|
||||
*/
|
||||
public class SimpleOnStylusPressListener implements StylusButtonListener {
|
||||
private View mView;
|
||||
|
||||
public SimpleOnStylusPressListener(View view) {
|
||||
mView = view;
|
||||
}
|
||||
|
||||
public boolean onPressed(MotionEvent event) {
|
||||
return mView.isLongClickable() && mView.performLongClick();
|
||||
}
|
||||
|
||||
public boolean onReleased(MotionEvent event) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package com.android.launcher3;
|
||||
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
|
||||
/**
|
||||
* Helper for identifying when a stylus touches a view while the primary stylus button is pressed.
|
||||
* This can occur in {@value MotionEvent#ACTION_DOWN} or {@value MotionEvent#ACTION_MOVE}.
|
||||
*/
|
||||
public class StylusEventHelper {
|
||||
|
||||
/**
|
||||
* Implement this interface to receive callbacks for a stylus button press and release.
|
||||
*/
|
||||
public interface StylusButtonListener {
|
||||
/**
|
||||
* Called when the stylus button is pressed.
|
||||
*
|
||||
* @param event The MotionEvent that the button press occurred for.
|
||||
* @return Whether the event was handled.
|
||||
*/
|
||||
public boolean onPressed(MotionEvent event);
|
||||
|
||||
/**
|
||||
* Called when the stylus button is released after a button press. This is also called if
|
||||
* the event is canceled or the stylus is lifted off the screen.
|
||||
*
|
||||
* @param event The MotionEvent the button release occurred for.
|
||||
* @return Whether the event was handled.
|
||||
*/
|
||||
public boolean onReleased(MotionEvent event);
|
||||
}
|
||||
|
||||
private boolean mIsButtonPressed;
|
||||
private View mView;
|
||||
private StylusButtonListener mListener;
|
||||
private final float mSlop;
|
||||
|
||||
/**
|
||||
* Constructs a helper for listening to stylus button presses and releases. Ensure that {
|
||||
* {@link #onMotionEvent(MotionEvent)} and {@link #onGenericMotionEvent(MotionEvent)} are called on
|
||||
* the helper to correctly identify stylus events.
|
||||
*
|
||||
* @param listener The listener to call for stylus events.
|
||||
* @param view Optional view associated with the touch events.
|
||||
*/
|
||||
public StylusEventHelper(StylusButtonListener listener, View view) {
|
||||
mListener = listener;
|
||||
mView = view;
|
||||
if (mView != null) {
|
||||
mSlop = ViewConfiguration.get(mView.getContext()).getScaledTouchSlop();
|
||||
} else {
|
||||
mSlop = ViewConfiguration.getTouchSlop();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean onMotionEvent(MotionEvent event) {
|
||||
final boolean stylusButtonPressed = isStylusButtonPressed(event);
|
||||
switch (event.getAction()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
mIsButtonPressed = stylusButtonPressed;
|
||||
if (mIsButtonPressed) {
|
||||
return mListener.onPressed(event);
|
||||
}
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
if (!Utilities.pointInView(mView, event.getX(), event.getY(), mSlop)) {
|
||||
return false;
|
||||
}
|
||||
if (!mIsButtonPressed && stylusButtonPressed) {
|
||||
mIsButtonPressed = true;
|
||||
return mListener.onPressed(event);
|
||||
} else if (mIsButtonPressed && !stylusButtonPressed) {
|
||||
mIsButtonPressed = false;
|
||||
return mListener.onReleased(event);
|
||||
}
|
||||
break;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
if (mIsButtonPressed) {
|
||||
mIsButtonPressed = false;
|
||||
return mListener.onReleased(event);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a stylus button press is occurring.
|
||||
*/
|
||||
public boolean inStylusButtonPressed() {
|
||||
return mIsButtonPressed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies if the provided {@link MotionEvent} is a stylus with the primary stylus button
|
||||
* pressed.
|
||||
*
|
||||
* @param event The event to check.
|
||||
* @return Whether a stylus button press occurred.
|
||||
*/
|
||||
private static boolean isStylusButtonPressed(MotionEvent event) {
|
||||
return event.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS
|
||||
&& ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY)
|
||||
== MotionEvent.BUTTON_SECONDARY);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static com.android.launcher3.ItemInfoWithIcon.FLAG_ICON_BADGED;
|
||||
import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_ICON_BADGED;
|
||||
|
||||
import android.animation.ValueAnimator;
|
||||
import android.annotation.TargetApi;
|
||||
@@ -24,9 +24,13 @@ import android.app.ActivityManager;
|
||||
import android.app.Person;
|
||||
import android.app.WallpaperManager;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.LauncherActivityInfo;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.content.pm.ShortcutInfo;
|
||||
import android.content.res.Resources;
|
||||
@@ -59,17 +63,22 @@ import android.view.View;
|
||||
import android.view.ViewConfiguration;
|
||||
import android.view.animation.Interpolator;
|
||||
|
||||
import com.android.launcher3.compat.LauncherAppsCompat;
|
||||
import com.android.launcher3.compat.ShortcutConfigActivityInfo;
|
||||
import androidx.core.os.BuildCompat;
|
||||
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.dragndrop.FolderAdaptiveIcon;
|
||||
import com.android.launcher3.graphics.RotationMode;
|
||||
import com.android.launcher3.graphics.GridOptionsProvider;
|
||||
import com.android.launcher3.graphics.TintedDrawableSpan;
|
||||
import com.android.launcher3.icons.IconProvider;
|
||||
import com.android.launcher3.icons.LauncherIcons;
|
||||
import com.android.launcher3.shortcuts.DeepShortcutManager;
|
||||
import com.android.launcher3.icons.ShortcutCachingLogic;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.ItemInfoWithIcon;
|
||||
import com.android.launcher3.pm.ShortcutConfigActivityInfo;
|
||||
import com.android.launcher3.shortcuts.ShortcutKey;
|
||||
import com.android.launcher3.shortcuts.ShortcutRequest;
|
||||
import com.android.launcher3.util.IntArray;
|
||||
import com.android.launcher3.util.PackageManagerHelper;
|
||||
import com.android.launcher3.views.Transposable;
|
||||
import com.android.launcher3.widget.PendingAddShortcutInfo;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
@@ -97,6 +106,8 @@ public final class Utilities {
|
||||
public static final String[] EMPTY_STRING_ARRAY = new String[0];
|
||||
public static final Person[] EMPTY_PERSON_ARRAY = new Person[0];
|
||||
|
||||
public static final boolean ATLEAST_R = BuildCompat.isAtLeastR();
|
||||
|
||||
public static final boolean ATLEAST_Q = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
|
||||
|
||||
public static final boolean ATLEAST_P =
|
||||
@@ -163,7 +174,7 @@ public final class Utilities {
|
||||
public static float getDescendantCoordRelativeToAncestor(
|
||||
View descendant, View ancestor, float[] coord, boolean includeRootScroll) {
|
||||
return getDescendantCoordRelativeToAncestor(descendant, ancestor, coord, includeRootScroll,
|
||||
false, null);
|
||||
false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -176,15 +187,12 @@ public final class Utilities {
|
||||
* @param includeRootScroll Whether or not to account for the scroll of the descendant:
|
||||
* sometimes this is relevant as in a child's coordinates within the descendant.
|
||||
* @param ignoreTransform If true, view transform is ignored
|
||||
* @param outRotation If not null, and {@param ignoreTransform} is true, this is set to the
|
||||
* overall rotation of the view in degrees.
|
||||
* @return The factor by which this descendant is scaled relative to this DragLayer. Caution
|
||||
* this scale factor is assumed to be equal in X and Y, and so if at any point this
|
||||
* assumption fails, we will need to return a pair of scale factors.
|
||||
*/
|
||||
public static float getDescendantCoordRelativeToAncestor(View descendant, View ancestor,
|
||||
float[] coord, boolean includeRootScroll, boolean ignoreTransform,
|
||||
float[] outRotation) {
|
||||
float[] coord, boolean includeRootScroll, boolean ignoreTransform) {
|
||||
float scale = 1.0f;
|
||||
View v = descendant;
|
||||
while(v != ancestor && v != null) {
|
||||
@@ -194,19 +202,7 @@ public final class Utilities {
|
||||
offsetPoints(coord, -v.getScrollX(), -v.getScrollY());
|
||||
}
|
||||
|
||||
if (ignoreTransform) {
|
||||
if (v instanceof Transposable) {
|
||||
RotationMode m = ((Transposable) v).getRotationMode();
|
||||
if (m.isTransposed) {
|
||||
sMatrix.setRotate(m.surfaceRotation, v.getPivotX(), v.getPivotY());
|
||||
sMatrix.mapPoints(coord);
|
||||
|
||||
if (outRotation != null) {
|
||||
outRotation[0] += m.surfaceRotation;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!ignoreTransform) {
|
||||
v.getMatrix().mapPoints(coord);
|
||||
}
|
||||
offsetPoints(coord, v.getLeft(), v.getTop());
|
||||
@@ -352,6 +348,30 @@ public final class Utilities {
|
||||
return min + (value * (max - min));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounds parameter to the range [0, 1]
|
||||
*/
|
||||
public static float saturate(float a) {
|
||||
return boundToRange(a, 0, 1.0f);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the compliment (1 - a) of the parameter.
|
||||
*/
|
||||
public static float comp(float a) {
|
||||
return 1 - a;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the "probabilistic or" of a and b. (a + b - ab).
|
||||
* Useful beyond probability, can be used to combine two unit progresses for example.
|
||||
*/
|
||||
public static float or(float a, float b) {
|
||||
float satA = saturate(a);
|
||||
float satB = saturate(b);
|
||||
return satA + satB - (satA * satB);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trims the string, removing all whitespace at the beginning and end of the string.
|
||||
* Non-breaking whitespaces are also removed.
|
||||
@@ -380,7 +400,7 @@ public final class Utilities {
|
||||
return res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
|
||||
}
|
||||
|
||||
public static float dpiFromPx(int size, DisplayMetrics metrics){
|
||||
public static float dpiFromPx(float size, DisplayMetrics metrics) {
|
||||
float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
|
||||
return (size / densityRatio);
|
||||
}
|
||||
@@ -463,15 +483,26 @@ public final class Utilities {
|
||||
}
|
||||
|
||||
public static SharedPreferences getPrefs(Context context) {
|
||||
return context.getSharedPreferences(
|
||||
// Use application context for shared preferences, so that we use a single cached instance
|
||||
return context.getApplicationContext().getSharedPreferences(
|
||||
LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
public static SharedPreferences getDevicePrefs(Context context) {
|
||||
return context.getSharedPreferences(
|
||||
// Use application context for shared preferences, so that we use a single cached instance
|
||||
return context.getApplicationContext().getSharedPreferences(
|
||||
LauncherFiles.DEVICE_PREFERENCES_KEY, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {@link SharedPreferences} that backs {@link FeatureFlags}
|
||||
*/
|
||||
public static SharedPreferences getFeatureFlagsPrefs(Context context) {
|
||||
// Use application context for shared preferences, so that we use a single cached instance
|
||||
return context.getApplicationContext().getSharedPreferences(
|
||||
FeatureFlags.FLAGS_PREF_NAME, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
public static boolean areAnimationsEnabled(Context context) {
|
||||
return ATLEAST_OREO
|
||||
? ValueAnimator.areAnimatorsEnabled()
|
||||
@@ -487,6 +518,42 @@ public final class Utilities {
|
||||
|| e.getCause() instanceof DeadObjectException;
|
||||
}
|
||||
|
||||
public static boolean isGridOptionsEnabled(Context context) {
|
||||
return isComponentEnabled(context.getPackageManager(),
|
||||
context.getPackageName(),
|
||||
GridOptionsProvider.class.getName());
|
||||
}
|
||||
|
||||
private static boolean isComponentEnabled(PackageManager pm, String pkgName, String clsName) {
|
||||
ComponentName componentName = new ComponentName(pkgName, clsName);
|
||||
int componentEnabledSetting = pm.getComponentEnabledSetting(componentName);
|
||||
|
||||
switch (componentEnabledSetting) {
|
||||
case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
|
||||
return false;
|
||||
case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
|
||||
return true;
|
||||
case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
|
||||
default:
|
||||
// We need to get the application info to get the component's default state
|
||||
try {
|
||||
PackageInfo packageInfo = pm.getPackageInfo(pkgName,
|
||||
PackageManager.GET_PROVIDERS | PackageManager.GET_DISABLED_COMPONENTS);
|
||||
|
||||
if (packageInfo.providers != null) {
|
||||
return Arrays.stream(packageInfo.providers).anyMatch(
|
||||
pi -> pi.name.equals(clsName) && pi.isEnabled());
|
||||
}
|
||||
|
||||
// the component is not declared in the AndroidManifest
|
||||
return false;
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
// the package isn't installed on the device
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method to post a runnable on the handler, skipping the synchronization barriers.
|
||||
*/
|
||||
@@ -518,19 +585,20 @@ public final class Utilities {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the full drawable for {@param info}.
|
||||
* Returns the full drawable for info without any flattening or pre-processing.
|
||||
*
|
||||
* @param outObj this is set to the internal data associated with {@param info},
|
||||
* eg {@link LauncherActivityInfo} or {@link ShortcutInfo}.
|
||||
*/
|
||||
public static Drawable getFullDrawable(Launcher launcher, ItemInfo info, int width, int height,
|
||||
boolean flattenDrawable, Object[] outObj) {
|
||||
Object[] outObj) {
|
||||
LauncherAppState appState = LauncherAppState.getInstance(launcher);
|
||||
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
|
||||
LauncherActivityInfo activityInfo = LauncherAppsCompat.getInstance(launcher)
|
||||
LauncherActivityInfo activityInfo = launcher.getSystemService(LauncherApps.class)
|
||||
.resolveActivity(info.getIntent(), info.user);
|
||||
outObj[0] = activityInfo;
|
||||
return (activityInfo != null) ? appState.getIconCache()
|
||||
.getFullResIcon(activityInfo, flattenDrawable) : null;
|
||||
return activityInfo == null ? null : new IconProvider(launcher).getIconForUI(
|
||||
activityInfo, launcher.getDeviceProfile().inv.fillResIconDpi);
|
||||
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
|
||||
if (info instanceof PendingAddShortcutInfo) {
|
||||
ShortcutConfigActivityInfo activityInfo =
|
||||
@@ -538,15 +606,15 @@ public final class Utilities {
|
||||
outObj[0] = activityInfo;
|
||||
return activityInfo.getFullResIcon(appState.getIconCache());
|
||||
}
|
||||
ShortcutKey key = ShortcutKey.fromItemInfo(info);
|
||||
DeepShortcutManager sm = DeepShortcutManager.getInstance(launcher);
|
||||
List<ShortcutInfo> si = sm.queryForFullDetails(
|
||||
key.componentName.getPackageName(), Arrays.asList(key.getId()), key.user);
|
||||
if (info.getIntent() == null || info.getIntent().getPackage() == null) return null;
|
||||
List<ShortcutInfo> si = ShortcutKey.fromItemInfo(info)
|
||||
.buildRequest(launcher)
|
||||
.query(ShortcutRequest.ALL);
|
||||
if (si.isEmpty()) {
|
||||
return null;
|
||||
} else {
|
||||
outObj[0] = si.get(0);
|
||||
return sm.getShortcutIconDrawable(si.get(0),
|
||||
return ShortcutCachingLogic.getIcon(launcher, si.get(0),
|
||||
appState.getInvariantDeviceProfile().fillResIconDpi);
|
||||
}
|
||||
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
|
||||
@@ -581,9 +649,8 @@ public final class Utilities {
|
||||
return new FixedSizeEmptyDrawable(iconSize);
|
||||
}
|
||||
ShortcutInfo si = (ShortcutInfo) obj;
|
||||
LauncherIcons li = LauncherIcons.obtain(appState.getContext());
|
||||
Bitmap badge = li.getShortcutInfoBadge(si, appState.getIconCache()).iconBitmap;
|
||||
li.recycle();
|
||||
Bitmap badge = LauncherAppState.getInstance(appState.getContext())
|
||||
.getIconCache().getShortcutInfoBadge(si).icon;
|
||||
float badgeSize = LauncherIcons.getBadgeSizeForIconSize(iconSize);
|
||||
float insetFraction = (iconSize - badgeSize) / iconSize;
|
||||
return new InsetDrawable(new FastBitmapDrawable(badge),
|
||||
|
||||
@@ -23,24 +23,27 @@ import android.graphics.PorterDuff;
|
||||
import android.graphics.PorterDuffXfermode;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.CancellationSignal;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
import android.util.ArrayMap;
|
||||
import android.util.Log;
|
||||
import android.util.LongSparseArray;
|
||||
import android.util.Pair;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
import com.android.launcher3.compat.AppWidgetManagerCompat;
|
||||
import com.android.launcher3.compat.ShortcutConfigActivityInfo;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.icons.GraphicsUtils;
|
||||
import com.android.launcher3.icons.IconCache;
|
||||
import com.android.launcher3.icons.LauncherIcons;
|
||||
import com.android.launcher3.icons.ShadowGenerator;
|
||||
import com.android.launcher3.model.WidgetItem;
|
||||
import com.android.launcher3.pm.ShortcutConfigActivityInfo;
|
||||
import com.android.launcher3.pm.UserCache;
|
||||
import com.android.launcher3.util.ComponentKey;
|
||||
import com.android.launcher3.util.Executors;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
@@ -48,6 +51,7 @@ import com.android.launcher3.util.Preconditions;
|
||||
import com.android.launcher3.util.SQLiteCacheHelper;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
import com.android.launcher3.widget.WidgetCell;
|
||||
import com.android.launcher3.widget.WidgetManagerHelper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
@@ -74,16 +78,64 @@ public class WidgetPreviewLoader {
|
||||
|
||||
private final Context mContext;
|
||||
private final IconCache mIconCache;
|
||||
private final UserManagerCompat mUserManager;
|
||||
private final UserCache mUserCache;
|
||||
private final CacheDb mDb;
|
||||
|
||||
private final UserHandle mMyUser = Process.myUserHandle();
|
||||
private final ArrayMap<UserHandle, Bitmap> mUserBadges = new ArrayMap<>();
|
||||
|
||||
public WidgetPreviewLoader(Context context, IconCache iconCache) {
|
||||
mContext = context;
|
||||
mIconCache = iconCache;
|
||||
mUserManager = UserManagerCompat.getInstance(context);
|
||||
mUserCache = UserCache.INSTANCE.get(context);
|
||||
mDb = new CacheDb(context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a drawable that can be used as a badge for the user or null.
|
||||
*/
|
||||
@UiThread
|
||||
public Drawable getBadgeForUser(UserHandle user, int badgeSize) {
|
||||
if (mMyUser.equals(user)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Bitmap badgeBitmap = getUserBadge(user, badgeSize);
|
||||
FastBitmapDrawable d = new FastBitmapDrawable(badgeBitmap);
|
||||
d.setFilterBitmap(true);
|
||||
d.setBounds(0, 0, badgeBitmap.getWidth(), badgeBitmap.getHeight());
|
||||
return d;
|
||||
}
|
||||
|
||||
private Bitmap getUserBadge(UserHandle user, int badgeSize) {
|
||||
synchronized (mUserBadges) {
|
||||
Bitmap badgeBitmap = mUserBadges.get(user);
|
||||
if (badgeBitmap != null) {
|
||||
return badgeBitmap;
|
||||
}
|
||||
|
||||
final Resources res = mContext.getResources();
|
||||
badgeBitmap = Bitmap.createBitmap(badgeSize, badgeSize, Bitmap.Config.ARGB_8888);
|
||||
|
||||
Drawable drawable = mContext.getPackageManager().getUserBadgedDrawableForDensity(
|
||||
new BitmapDrawable(res, badgeBitmap), user,
|
||||
new Rect(0, 0, badgeSize, badgeSize),
|
||||
0);
|
||||
if (drawable instanceof BitmapDrawable) {
|
||||
badgeBitmap = ((BitmapDrawable) drawable).getBitmap();
|
||||
} else {
|
||||
badgeBitmap.eraseColor(Color.TRANSPARENT);
|
||||
Canvas c = new Canvas(badgeBitmap);
|
||||
drawable.setBounds(0, 0, badgeSize, badgeSize);
|
||||
drawable.draw(c);
|
||||
c.setBitmap(null);
|
||||
}
|
||||
|
||||
mUserBadges.put(user, badgeBitmap);
|
||||
return badgeBitmap;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the widget preview on {@link AsyncTask#THREAD_POOL_EXECUTOR}. Must be
|
||||
* called on UI thread
|
||||
@@ -105,8 +157,8 @@ public class WidgetPreviewLoader {
|
||||
|
||||
public void refresh() {
|
||||
mDb.clear();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The DB holds the generated previews for various components. Previews can also have different
|
||||
* sizes (landscape vs portrait).
|
||||
@@ -145,7 +197,7 @@ public class WidgetPreviewLoader {
|
||||
@Thunk void writeToDb(WidgetCacheKey key, long[] versions, Bitmap preview) {
|
||||
ContentValues values = new ContentValues();
|
||||
values.put(CacheDb.COLUMN_COMPONENT, key.componentName.flattenToShortString());
|
||||
values.put(CacheDb.COLUMN_USER, mUserManager.getSerialNumberForUser(key.user));
|
||||
values.put(CacheDb.COLUMN_USER, mUserCache.getSerialNumberForUser(key.user));
|
||||
values.put(CacheDb.COLUMN_SIZE, key.size);
|
||||
values.put(CacheDb.COLUMN_PACKAGE, key.componentName.getPackageName());
|
||||
values.put(CacheDb.COLUMN_VERSION, versions[0]);
|
||||
@@ -155,7 +207,7 @@ public class WidgetPreviewLoader {
|
||||
}
|
||||
|
||||
public void removePackage(String packageName, UserHandle user) {
|
||||
removePackage(packageName, user, mUserManager.getSerialNumberForUser(user));
|
||||
removePackage(packageName, user, mUserCache.getSerialNumberForUser(user));
|
||||
}
|
||||
|
||||
private void removePackage(String packageName, UserHandle user, long userSerial) {
|
||||
@@ -184,7 +236,7 @@ public class WidgetPreviewLoader {
|
||||
LongSparseArray<HashSet<String>> validPackages = new LongSparseArray<>();
|
||||
|
||||
for (ComponentKey key : list) {
|
||||
final long userId = mUserManager.getSerialNumberForUser(key.user);
|
||||
final long userId = mUserCache.getSerialNumberForUser(key.user);
|
||||
HashSet<String> packages = validPackages.get(userId);
|
||||
if (packages == null) {
|
||||
packages = new HashSet<>();
|
||||
@@ -195,7 +247,7 @@ public class WidgetPreviewLoader {
|
||||
|
||||
LongSparseArray<HashSet<String>> packagesToDelete = new LongSparseArray<>();
|
||||
long passedUserId = packageUser == null ? 0
|
||||
: mUserManager.getSerialNumberForUser(packageUser.mUser);
|
||||
: mUserCache.getSerialNumberForUser(packageUser.mUser);
|
||||
Cursor c = null;
|
||||
try {
|
||||
c = mDb.query(
|
||||
@@ -234,7 +286,7 @@ public class WidgetPreviewLoader {
|
||||
|
||||
for (int i = 0; i < packagesToDelete.size(); i++) {
|
||||
long userId = packagesToDelete.keyAt(i);
|
||||
UserHandle user = mUserManager.getUserForSerialNumber(userId);
|
||||
UserHandle user = mUserCache.getUserForSerialNumber(userId);
|
||||
for (String pkg : packagesToDelete.valueAt(i)) {
|
||||
removePackage(pkg, user, userId);
|
||||
}
|
||||
@@ -260,7 +312,7 @@ public class WidgetPreviewLoader {
|
||||
+ CacheDb.COLUMN_SIZE + " = ?",
|
||||
new String[]{
|
||||
key.componentName.flattenToShortString(),
|
||||
Long.toString(mUserManager.getSerialNumberForUser(key.user)),
|
||||
Long.toString(mUserCache.getSerialNumberForUser(key.user)),
|
||||
key.size
|
||||
});
|
||||
// If cancelled, skip getting the blob and decoding it into a bitmap
|
||||
@@ -289,19 +341,30 @@ public class WidgetPreviewLoader {
|
||||
return null;
|
||||
}
|
||||
|
||||
private Bitmap generatePreview(BaseActivity launcher, WidgetItem item, Bitmap recycle,
|
||||
/**
|
||||
* Returns generatedPreview for a widget and if the preview should be saved in persistent
|
||||
* storage.
|
||||
* @param launcher
|
||||
* @param item
|
||||
* @param recycle
|
||||
* @param previewWidth
|
||||
* @param previewHeight
|
||||
* @return Pair<Bitmap, Boolean>
|
||||
*/
|
||||
private Pair<Bitmap, Boolean> generatePreview(BaseActivity launcher, WidgetItem item,
|
||||
Bitmap recycle,
|
||||
int previewWidth, int previewHeight) {
|
||||
if (item.widgetInfo != null) {
|
||||
return generateWidgetPreview(launcher, item.widgetInfo,
|
||||
previewWidth, recycle, null);
|
||||
} else {
|
||||
return generateShortcutPreview(launcher, item.activityInfo,
|
||||
previewWidth, previewHeight, recycle);
|
||||
return new Pair<>(generateShortcutPreview(launcher, item.activityInfo,
|
||||
previewWidth, previewHeight, recycle), false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the widget preview from either the {@link AppWidgetManagerCompat} or cache
|
||||
* Generates the widget preview from either the {@link WidgetManagerHelper} or cache
|
||||
* and add badge at the bottom right corner.
|
||||
*
|
||||
* @param launcher
|
||||
@@ -309,9 +372,10 @@ public class WidgetPreviewLoader {
|
||||
* @param maxPreviewWidth width of the preview on either workspace or tray
|
||||
* @param preview bitmap that can be recycled
|
||||
* @param preScaledWidthOut return the width of the returned bitmap
|
||||
* @return
|
||||
* @return Pair<Bitmap (the preview) , Boolean (should be stored in db)>
|
||||
*/
|
||||
public Bitmap generateWidgetPreview(BaseActivity launcher, LauncherAppWidgetProviderInfo info,
|
||||
public Pair<Bitmap, Boolean> generateWidgetPreview(BaseActivity launcher,
|
||||
LauncherAppWidgetProviderInfo info,
|
||||
int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
|
||||
// Load the preview image if possible
|
||||
if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
|
||||
@@ -341,6 +405,8 @@ public class WidgetPreviewLoader {
|
||||
int previewWidth;
|
||||
int previewHeight;
|
||||
|
||||
boolean savePreviewImage = widgetPreviewExists || info.previewImage == 0;
|
||||
|
||||
if (widgetPreviewExists && drawable.getIntrinsicWidth() > 0
|
||||
&& drawable.getIntrinsicHeight() > 0) {
|
||||
previewWidth = drawable.getIntrinsicWidth();
|
||||
@@ -427,10 +493,12 @@ public class WidgetPreviewLoader {
|
||||
icon.setBounds(hoffset, yoffset, hoffset + iconSize, yoffset + iconSize);
|
||||
icon.draw(c);
|
||||
}
|
||||
} catch (Resources.NotFoundException e) { }
|
||||
} catch (Resources.NotFoundException e) {
|
||||
savePreviewImage = false;
|
||||
}
|
||||
c.setBitmap(null);
|
||||
}
|
||||
return preview;
|
||||
return new Pair<>(preview, savePreviewImage);
|
||||
}
|
||||
|
||||
private RectF drawBoxWithShadow(Canvas c, int width, int height) {
|
||||
@@ -533,6 +601,8 @@ public class WidgetPreviewLoader {
|
||||
@Thunk long[] mVersions;
|
||||
@Thunk Bitmap mBitmapToRecycle;
|
||||
|
||||
private boolean mSaveToDB = false;
|
||||
|
||||
PreviewLoadTask(WidgetCacheKey key, WidgetItem info, int previewWidth,
|
||||
int previewHeight, WidgetCell caller) {
|
||||
mKey = key;
|
||||
@@ -588,7 +658,10 @@ public class WidgetPreviewLoader {
|
||||
: null;
|
||||
|
||||
// it's not in the db... we need to generate it
|
||||
preview = generatePreview(mActivity, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
|
||||
Pair<Bitmap, Boolean> pair = generatePreview(mActivity, mInfo, unusedBitmap,
|
||||
mPreviewWidth, mPreviewHeight);
|
||||
preview = pair.first;
|
||||
this.mSaveToDB = pair.second;
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
@@ -602,7 +675,7 @@ public class WidgetPreviewLoader {
|
||||
MODEL_EXECUTOR.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!isCancelled()) {
|
||||
if (!isCancelled() && mSaveToDB) {
|
||||
// If we are still using this preview, then write it to the DB and then
|
||||
// let the normal clear mechanism recycle the bitmap
|
||||
writeToDb(mKey, mVersions, preview);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,6 +21,7 @@ import android.view.ViewGroup;
|
||||
|
||||
import com.android.launcher3.folder.Folder;
|
||||
import com.android.launcher3.folder.FolderIcon;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.touch.ItemLongClickListener;
|
||||
|
||||
public interface WorkspaceLayoutManager {
|
||||
@@ -39,7 +40,8 @@ public interface WorkspaceLayoutManager {
|
||||
default void addInScreenFromBind(View child, ItemInfo info) {
|
||||
int x = info.cellX;
|
||||
int y = info.cellY;
|
||||
if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
|
||||
if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT
|
||||
|| info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION) {
|
||||
int screenId = info.screenId;
|
||||
x = getHotseat().getCellXFromOrder(screenId);
|
||||
y = getHotseat().getCellYFromOrder(screenId);
|
||||
@@ -83,7 +85,8 @@ public interface WorkspaceLayoutManager {
|
||||
}
|
||||
|
||||
final CellLayout layout;
|
||||
if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
|
||||
if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT
|
||||
|| container == LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION) {
|
||||
layout = getHotseat();
|
||||
|
||||
// Hide folder title in the hotseat
|
||||
|
||||
@@ -16,29 +16,43 @@
|
||||
|
||||
package com.android.launcher3;
|
||||
|
||||
import static androidx.dynamicanimation.animation.DynamicAnimation.MIN_VISIBLE_CHANGE_SCALE;
|
||||
|
||||
import static com.android.launcher3.LauncherAnimUtils.DRAWABLE_ALPHA;
|
||||
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
|
||||
import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
|
||||
import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
|
||||
import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
|
||||
import static com.android.launcher3.LauncherState.FLAG_HAS_SYS_UI_SCRIM;
|
||||
import static com.android.launcher3.LauncherState.FLAG_WORKSPACE_HAS_BACKGROUNDS;
|
||||
import static com.android.launcher3.LauncherState.HINT_STATE;
|
||||
import static com.android.launcher3.LauncherState.HOTSEAT_ICONS;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_HOTSEAT_SCALE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_HOTSEAT_TRANSLATE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_FADE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_SCALE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_WORKSPACE_TRANSLATE;
|
||||
import static com.android.launcher3.LauncherState.NORMAL;
|
||||
import static com.android.launcher3.anim.Interpolators.LINEAR;
|
||||
import static com.android.launcher3.anim.Interpolators.ZOOM_OUT;
|
||||
import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
|
||||
import static com.android.launcher3.graphics.WorkspaceAndHotseatScrim.SCRIM_PROGRESS;
|
||||
import static com.android.launcher3.graphics.Scrim.SCRIM_PROGRESS;
|
||||
import static com.android.launcher3.graphics.WorkspaceAndHotseatScrim.SYSUI_PROGRESS;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_HOTSEAT_SCALE;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_HOTSEAT_TRANSLATE;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_FADE;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_SCALE;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_WORKSPACE_TRANSLATE;
|
||||
|
||||
import android.animation.ValueAnimator;
|
||||
import android.view.View;
|
||||
import android.view.animation.Interpolator;
|
||||
|
||||
import com.android.launcher3.LauncherState.PageAlphaProvider;
|
||||
import com.android.launcher3.LauncherState.ScaleAndTranslation;
|
||||
import com.android.launcher3.LauncherStateManager.AnimationConfig;
|
||||
import com.android.launcher3.anim.AnimatorSetBuilder;
|
||||
import com.android.launcher3.allapps.AllAppsContainerView;
|
||||
import com.android.launcher3.anim.PendingAnimation;
|
||||
import com.android.launcher3.anim.PropertySetter;
|
||||
import com.android.launcher3.anim.SpringAnimationBuilder;
|
||||
import com.android.launcher3.graphics.WorkspaceAndHotseatScrim;
|
||||
import com.android.launcher3.states.StateAnimationConfig;
|
||||
import com.android.launcher3.util.DynamicResource;
|
||||
import com.android.systemui.plugins.ResourceProvider;
|
||||
|
||||
/**
|
||||
* Manages the animations between each of the workspace states.
|
||||
@@ -56,13 +70,15 @@ public class WorkspaceStateTransitionAnimation {
|
||||
}
|
||||
|
||||
public void setState(LauncherState toState) {
|
||||
setWorkspaceProperty(toState, NO_ANIM_PROPERTY_SETTER, new AnimatorSetBuilder(),
|
||||
new AnimationConfig());
|
||||
setWorkspaceProperty(toState, NO_ANIM_PROPERTY_SETTER, new StateAnimationConfig());
|
||||
}
|
||||
|
||||
public void setStateWithAnimation(LauncherState toState, AnimatorSetBuilder builder,
|
||||
AnimationConfig config) {
|
||||
setWorkspaceProperty(toState, config.getPropertySetter(builder), builder, config);
|
||||
/**
|
||||
* @see com.android.launcher3.statemanager.StateManager.StateHandler#setStateWithAnimation
|
||||
*/
|
||||
public void setStateWithAnimation(
|
||||
LauncherState toState, StateAnimationConfig config, PendingAnimation animation) {
|
||||
setWorkspaceProperty(toState, animation, config);
|
||||
}
|
||||
|
||||
public float getFinalScale() {
|
||||
@@ -73,41 +89,55 @@ public class WorkspaceStateTransitionAnimation {
|
||||
* Starts a transition animation for the workspace.
|
||||
*/
|
||||
private void setWorkspaceProperty(LauncherState state, PropertySetter propertySetter,
|
||||
AnimatorSetBuilder builder, AnimationConfig config) {
|
||||
StateAnimationConfig config) {
|
||||
ScaleAndTranslation scaleAndTranslation = state.getWorkspaceScaleAndTranslation(mLauncher);
|
||||
ScaleAndTranslation hotseatScaleAndTranslation = state.getHotseatScaleAndTranslation(
|
||||
mLauncher);
|
||||
ScaleAndTranslation qsbScaleAndTranslation = state.getQsbScaleAndTranslation(mLauncher);
|
||||
mNewScale = scaleAndTranslation.scale;
|
||||
PageAlphaProvider pageAlphaProvider = state.getWorkspacePageAlphaProvider(mLauncher);
|
||||
final int childCount = mWorkspace.getChildCount();
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
applyChildState(state, (CellLayout) mWorkspace.getChildAt(i), i, pageAlphaProvider,
|
||||
propertySetter, builder, config);
|
||||
propertySetter, config);
|
||||
}
|
||||
|
||||
int elements = state.getVisibleElements(mLauncher);
|
||||
Interpolator fadeInterpolator = builder.getInterpolator(ANIM_WORKSPACE_FADE,
|
||||
Interpolator fadeInterpolator = config.getInterpolator(ANIM_WORKSPACE_FADE,
|
||||
pageAlphaProvider.interpolator);
|
||||
boolean playAtomicComponent = config.playAtomicOverviewScaleComponent();
|
||||
Hotseat hotseat = mWorkspace.getHotseat();
|
||||
// Since we set the pivot relative to mWorkspace, we need to scale a sibling of Workspace.
|
||||
AllAppsContainerView qsbScaleView = mLauncher.getAppsView();
|
||||
View qsbView = qsbScaleView.getSearchView();
|
||||
if (playAtomicComponent) {
|
||||
Interpolator scaleInterpolator = builder.getInterpolator(ANIM_WORKSPACE_SCALE, ZOOM_OUT);
|
||||
propertySetter.setFloat(mWorkspace, SCALE_PROPERTY, mNewScale, scaleInterpolator);
|
||||
|
||||
if (!hotseat.getRotationMode().isTransposed) {
|
||||
// Set the hotseat's pivot point to match the workspace's, so that it scales
|
||||
// together. Since both hotseat and workspace can move, transform the point
|
||||
// manually instead of using dragLayer.getDescendantCoordRelativeToSelf and
|
||||
// related methods.
|
||||
hotseat.setPivotY(mWorkspace.getPivotY() + mWorkspace.getTop() - hotseat.getTop());
|
||||
hotseat.setPivotX(mWorkspace.getPivotX()
|
||||
+ mWorkspace.getLeft() - hotseat.getLeft());
|
||||
Interpolator scaleInterpolator = config.getInterpolator(ANIM_WORKSPACE_SCALE, ZOOM_OUT);
|
||||
LauncherState fromState = mLauncher.getStateManager().getState();
|
||||
boolean shouldSpring = propertySetter instanceof PendingAnimation
|
||||
&& fromState == HINT_STATE && state == NORMAL;
|
||||
if (shouldSpring) {
|
||||
((PendingAnimation) propertySetter).add(getSpringScaleAnimator(mLauncher,
|
||||
mWorkspace, mNewScale));
|
||||
} else {
|
||||
propertySetter.setFloat(mWorkspace, SCALE_PROPERTY, mNewScale, scaleInterpolator);
|
||||
}
|
||||
|
||||
setPivotToScaleWithWorkspace(hotseat);
|
||||
setPivotToScaleWithWorkspace(qsbScaleView);
|
||||
float hotseatScale = hotseatScaleAndTranslation.scale;
|
||||
Interpolator hotseatScaleInterpolator = builder.getInterpolator(ANIM_HOTSEAT_SCALE,
|
||||
scaleInterpolator);
|
||||
propertySetter.setFloat(hotseat, SCALE_PROPERTY, hotseatScale,
|
||||
hotseatScaleInterpolator);
|
||||
if (shouldSpring) {
|
||||
PendingAnimation pa = (PendingAnimation) propertySetter;
|
||||
pa.add(getSpringScaleAnimator(mLauncher, hotseat, hotseatScale));
|
||||
pa.add(getSpringScaleAnimator(mLauncher, qsbScaleView,
|
||||
qsbScaleAndTranslation.scale));
|
||||
} else {
|
||||
Interpolator hotseatScaleInterpolator = config.getInterpolator(ANIM_HOTSEAT_SCALE,
|
||||
scaleInterpolator);
|
||||
propertySetter.setFloat(hotseat, SCALE_PROPERTY, hotseatScale,
|
||||
hotseatScaleInterpolator);
|
||||
propertySetter.setFloat(qsbScaleView, SCALE_PROPERTY, qsbScaleAndTranslation.scale,
|
||||
hotseatScaleInterpolator);
|
||||
}
|
||||
|
||||
float hotseatIconsAlpha = (elements & HOTSEAT_ICONS) != 0 ? 1 : 0;
|
||||
propertySetter.setViewAlpha(hotseat, hotseatIconsAlpha, fadeInterpolator);
|
||||
@@ -115,56 +145,93 @@ public class WorkspaceStateTransitionAnimation {
|
||||
hotseatIconsAlpha, fadeInterpolator);
|
||||
}
|
||||
|
||||
if (!config.playNonAtomicComponent()) {
|
||||
if (config.onlyPlayAtomicComponent()) {
|
||||
// Only the alpha and scale, handled above, are included in the atomic animation.
|
||||
return;
|
||||
}
|
||||
|
||||
Interpolator translationInterpolator = !playAtomicComponent
|
||||
? LINEAR
|
||||
: builder.getInterpolator(ANIM_WORKSPACE_TRANSLATE, ZOOM_OUT);
|
||||
propertySetter.setFloat(mWorkspace, View.TRANSLATION_X,
|
||||
: config.getInterpolator(ANIM_WORKSPACE_TRANSLATE, ZOOM_OUT);
|
||||
propertySetter.setFloat(mWorkspace, VIEW_TRANSLATE_X,
|
||||
scaleAndTranslation.translationX, translationInterpolator);
|
||||
propertySetter.setFloat(mWorkspace, View.TRANSLATION_Y,
|
||||
propertySetter.setFloat(mWorkspace, VIEW_TRANSLATE_Y,
|
||||
scaleAndTranslation.translationY, translationInterpolator);
|
||||
|
||||
Interpolator hotseatTranslationInterpolator = builder.getInterpolator(
|
||||
Interpolator hotseatTranslationInterpolator = config.getInterpolator(
|
||||
ANIM_HOTSEAT_TRANSLATE, translationInterpolator);
|
||||
propertySetter.setFloat(hotseat, View.TRANSLATION_Y,
|
||||
propertySetter.setFloat(hotseat, VIEW_TRANSLATE_Y,
|
||||
hotseatScaleAndTranslation.translationY, hotseatTranslationInterpolator);
|
||||
propertySetter.setFloat(mWorkspace.getPageIndicator(), View.TRANSLATION_Y,
|
||||
propertySetter.setFloat(mWorkspace.getPageIndicator(), VIEW_TRANSLATE_Y,
|
||||
hotseatScaleAndTranslation.translationY, hotseatTranslationInterpolator);
|
||||
propertySetter.setFloat(qsbView, VIEW_TRANSLATE_Y,
|
||||
qsbScaleAndTranslation.translationY, hotseatTranslationInterpolator);
|
||||
|
||||
setScrim(propertySetter, state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the given view's pivot point to match the workspace's, so that it scales together. Since
|
||||
* both this view and workspace can move, transform the point manually instead of using
|
||||
* dragLayer.getDescendantCoordRelativeToSelf and related methods.
|
||||
*/
|
||||
private void setPivotToScaleWithWorkspace(View sibling) {
|
||||
sibling.setPivotY(mWorkspace.getPivotY() + mWorkspace.getTop()
|
||||
- sibling.getTop() - sibling.getTranslationY());
|
||||
sibling.setPivotX(mWorkspace.getPivotX() + mWorkspace.getLeft()
|
||||
- sibling.getLeft() - sibling.getTranslationX());
|
||||
}
|
||||
|
||||
public void setScrim(PropertySetter propertySetter, LauncherState state) {
|
||||
WorkspaceAndHotseatScrim scrim = mLauncher.getDragLayer().getScrim();
|
||||
propertySetter.setFloat(scrim, SCRIM_PROGRESS, state.getWorkspaceScrimAlpha(mLauncher),
|
||||
LINEAR);
|
||||
propertySetter.setFloat(scrim, SYSUI_PROGRESS, state.hasSysUiScrim ? 1 : 0, LINEAR);
|
||||
propertySetter.setFloat(scrim, SYSUI_PROGRESS,
|
||||
state.hasFlag(FLAG_HAS_SYS_UI_SCRIM) ? 1 : 0, LINEAR);
|
||||
}
|
||||
|
||||
public void applyChildState(LauncherState state, CellLayout cl, int childIndex) {
|
||||
applyChildState(state, cl, childIndex, state.getWorkspacePageAlphaProvider(mLauncher),
|
||||
NO_ANIM_PROPERTY_SETTER, new AnimatorSetBuilder(), new AnimationConfig());
|
||||
NO_ANIM_PROPERTY_SETTER, new StateAnimationConfig());
|
||||
}
|
||||
|
||||
private void applyChildState(LauncherState state, CellLayout cl, int childIndex,
|
||||
PageAlphaProvider pageAlphaProvider, PropertySetter propertySetter,
|
||||
AnimatorSetBuilder builder, AnimationConfig config) {
|
||||
StateAnimationConfig config) {
|
||||
float pageAlpha = pageAlphaProvider.getPageAlpha(childIndex);
|
||||
int drawableAlpha = Math.round(pageAlpha * (state.hasWorkspacePageBackground ? 255 : 0));
|
||||
int drawableAlpha = state.hasFlag(FLAG_WORKSPACE_HAS_BACKGROUNDS)
|
||||
? Math.round(pageAlpha * 255) : 0;
|
||||
|
||||
if (config.playNonAtomicComponent()) {
|
||||
if (!config.onlyPlayAtomicComponent()) {
|
||||
// Don't update the scrim during the atomic animation.
|
||||
propertySetter.setInt(cl.getScrimBackground(),
|
||||
DRAWABLE_ALPHA, drawableAlpha, ZOOM_OUT);
|
||||
}
|
||||
if (config.playAtomicOverviewScaleComponent()) {
|
||||
Interpolator fadeInterpolator = builder.getInterpolator(ANIM_WORKSPACE_FADE,
|
||||
Interpolator fadeInterpolator = config.getInterpolator(ANIM_WORKSPACE_FADE,
|
||||
pageAlphaProvider.interpolator);
|
||||
propertySetter.setFloat(cl.getShortcutsAndWidgets(), View.ALPHA,
|
||||
propertySetter.setFloat(cl.getShortcutsAndWidgets(), VIEW_ALPHA,
|
||||
pageAlpha, fadeInterpolator);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a spring based animator for the scale property of {@param v}.
|
||||
*/
|
||||
public static ValueAnimator getSpringScaleAnimator(Launcher launcher, View v, float scale) {
|
||||
ResourceProvider rp = DynamicResource.provider(launcher);
|
||||
float damping = rp.getFloat(R.dimen.hint_scale_damping_ratio);
|
||||
float stiffness = rp.getFloat(R.dimen.hint_scale_stiffness);
|
||||
float velocityPxPerS = rp.getDimension(R.dimen.hint_scale_velocity_dp_per_s);
|
||||
|
||||
return new SpringAnimationBuilder(v.getContext())
|
||||
.setStiffness(stiffness)
|
||||
.setDampingRatio(damping)
|
||||
.setMinimumVisibleChange(MIN_VISIBLE_CHANGE_SCALE)
|
||||
.setEndValue(scale)
|
||||
.setStartValue(SCALE_PROPERTY.get(v))
|
||||
.setStartVelocity(velocityPxPerS)
|
||||
.build(v, SCALE_PROPERTY);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,9 @@
|
||||
|
||||
package com.android.launcher3.accessibility;
|
||||
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewGroup.OnHierarchyChangeListener;
|
||||
|
||||
import com.android.launcher3.CellLayout;
|
||||
import com.android.launcher3.DropTarget.DragObject;
|
||||
@@ -24,36 +26,55 @@ import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.dragndrop.DragController.DragListener;
|
||||
import com.android.launcher3.dragndrop.DragOptions;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Utility listener to enable/disable accessibility drag flags for a ViewGroup
|
||||
* containing CellLayouts
|
||||
*/
|
||||
public class AccessibleDragListenerAdapter implements DragListener {
|
||||
public class AccessibleDragListenerAdapter implements DragListener, OnHierarchyChangeListener {
|
||||
|
||||
private final ViewGroup mViewGroup;
|
||||
private final int mDragType;
|
||||
private final Function<CellLayout, DragAndDropAccessibilityDelegate> mDelegateFactory;
|
||||
|
||||
/**
|
||||
* @param parent
|
||||
* @param dragType either {@link CellLayout#WORKSPACE_ACCESSIBILITY_DRAG} or
|
||||
* {@link CellLayout#FOLDER_ACCESSIBILITY_DRAG}
|
||||
* @param parent the viewgroup containing all the children
|
||||
* @param delegateFactory function to create no delegates
|
||||
*/
|
||||
public AccessibleDragListenerAdapter(ViewGroup parent, int dragType) {
|
||||
public AccessibleDragListenerAdapter(ViewGroup parent,
|
||||
Function<CellLayout, DragAndDropAccessibilityDelegate> delegateFactory) {
|
||||
mViewGroup = parent;
|
||||
mDragType = dragType;
|
||||
mDelegateFactory = delegateFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDragStart(DragObject dragObject, DragOptions options) {
|
||||
mViewGroup.setOnHierarchyChangeListener(this);
|
||||
enableAccessibleDrag(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDragEnd() {
|
||||
mViewGroup.setOnHierarchyChangeListener(null);
|
||||
enableAccessibleDrag(false);
|
||||
Launcher.getLauncher(mViewGroup.getContext()).getDragController().removeDragListener(this);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onChildViewAdded(View parent, View child) {
|
||||
if (parent == mViewGroup) {
|
||||
setEnableForLayout((CellLayout) child, true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onChildViewRemoved(View parent, View child) {
|
||||
if (parent == mViewGroup) {
|
||||
setEnableForLayout((CellLayout) child, false);
|
||||
}
|
||||
}
|
||||
|
||||
protected void enableAccessibleDrag(boolean enable) {
|
||||
for (int i = 0; i < mViewGroup.getChildCount(); i++) {
|
||||
setEnableForLayout((CellLayout) mViewGroup.getChildAt(i), enable);
|
||||
@@ -61,6 +82,6 @@ public class AccessibleDragListenerAdapter implements DragListener {
|
||||
}
|
||||
|
||||
protected final void setEnableForLayout(CellLayout layout, boolean enable) {
|
||||
layout.enableAccessibleDrag(enable, mDragType);
|
||||
layout.setDragAndDropAccessibilityDelegate(enable ? mDelegateFactory.apply(layout) : null);
|
||||
}
|
||||
}
|
||||
@@ -19,24 +19,26 @@ package com.android.launcher3.accessibility;
|
||||
import android.content.Context;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Bundle;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.View.OnClickListener;
|
||||
import android.view.View.OnHoverListener;
|
||||
import android.view.accessibility.AccessibilityEvent;
|
||||
|
||||
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
|
||||
import androidx.customview.widget.ExploreByTouchHelper;
|
||||
|
||||
import com.android.launcher3.CellLayout;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.R;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
|
||||
import androidx.customview.widget.ExploreByTouchHelper;
|
||||
|
||||
/**
|
||||
* Helper class to make drag-and-drop in a {@link CellLayout} accessible.
|
||||
*/
|
||||
public abstract class DragAndDropAccessibilityDelegate extends ExploreByTouchHelper
|
||||
implements OnClickListener {
|
||||
implements OnClickListener, OnHoverListener {
|
||||
protected static final int INVALID_POSITION = -1;
|
||||
|
||||
private static final int[] sTempArray = new int[2];
|
||||
@@ -123,6 +125,11 @@ public abstract class DragAndDropAccessibilityDelegate extends ExploreByTouchHel
|
||||
node.setFocusable(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onHover(View view, MotionEvent motionEvent) {
|
||||
return dispatchHoverEvent(motionEvent);
|
||||
}
|
||||
|
||||
protected abstract String getLocationDescriptionForIconDrop(int id);
|
||||
|
||||
protected abstract String getConfirmationForIconDrop(int id);
|
||||
|
||||
@@ -7,6 +7,7 @@ import static com.android.launcher3.LauncherState.NORMAL;
|
||||
import android.app.AlertDialog;
|
||||
import android.appwidget.AppWidgetProviderInfo;
|
||||
import android.content.DialogInterface;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
@@ -18,26 +19,26 @@ import android.view.View.AccessibilityDelegate;
|
||||
import android.view.accessibility.AccessibilityNodeInfo;
|
||||
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
|
||||
|
||||
import com.android.launcher3.AppInfo;
|
||||
import com.android.launcher3.AppWidgetResizeFrame;
|
||||
import com.android.launcher3.BubbleTextView;
|
||||
import com.android.launcher3.ButtonDropTarget;
|
||||
import com.android.launcher3.CellLayout;
|
||||
import com.android.launcher3.DropTarget.DragObject;
|
||||
import com.android.launcher3.FolderInfo;
|
||||
import com.android.launcher3.ItemInfo;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.LauncherSettings;
|
||||
import com.android.launcher3.LauncherSettings.Favorites;
|
||||
import com.android.launcher3.PendingAddItemInfo;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.Workspace;
|
||||
import com.android.launcher3.WorkspaceItemInfo;
|
||||
import com.android.launcher3.dragndrop.DragController.DragListener;
|
||||
import com.android.launcher3.dragndrop.DragOptions;
|
||||
import com.android.launcher3.folder.Folder;
|
||||
import com.android.launcher3.keyboard.CustomActionsPopup;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.model.data.FolderInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
import com.android.launcher3.notification.NotificationListener;
|
||||
import com.android.launcher3.popup.PopupContainerWithArrow;
|
||||
import com.android.launcher3.touch.ItemLongClickListener;
|
||||
@@ -54,6 +55,8 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
|
||||
public static final int REMOVE = R.id.action_remove;
|
||||
public static final int UNINSTALL = R.id.action_uninstall;
|
||||
public static final int DISMISS_PREDICTION = R.id.action_dismiss_prediction;
|
||||
public static final int PIN_PREDICTION = R.id.action_pin_prediction;
|
||||
public static final int RECONFIGURE = R.id.action_reconfigure;
|
||||
protected static final int ADD_TO_WORKSPACE = R.id.action_add_to_workspace;
|
||||
protected static final int MOVE = R.id.action_move;
|
||||
@@ -86,6 +89,8 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
launcher.getText(R.string.remove_drop_target_label)));
|
||||
mActions.put(UNINSTALL, new AccessibilityAction(UNINSTALL,
|
||||
launcher.getText(R.string.uninstall_drop_target_label)));
|
||||
mActions.put(DISMISS_PREDICTION, new AccessibilityAction(DISMISS_PREDICTION,
|
||||
launcher.getText(R.string.dismiss_prediction_label)));
|
||||
mActions.put(RECONFIGURE, new AccessibilityAction(RECONFIGURE,
|
||||
launcher.getText(R.string.gadget_setup_text)));
|
||||
mActions.put(ADD_TO_WORKSPACE, new AccessibilityAction(ADD_TO_WORKSPACE,
|
||||
@@ -116,6 +121,10 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
if (!(host.getTag() instanceof ItemInfo)) return;
|
||||
ItemInfo item = (ItemInfo) host.getTag();
|
||||
|
||||
if (host instanceof AccessibilityActionHandler) {
|
||||
((AccessibilityActionHandler) host).addSupportedAccessibilityActions(info);
|
||||
}
|
||||
|
||||
// If the request came from keyboard, do not add custom shortcuts as that is already
|
||||
// exposed as a direct shortcut
|
||||
if (!fromKeyboard && ShortcutUtil.supportsShortcuts(item)) {
|
||||
@@ -142,15 +151,25 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
}
|
||||
}
|
||||
|
||||
if (!fromKeyboard && !itemSupportsLongClick(host, item)) {
|
||||
info.setLongClickable(false);
|
||||
info.removeAction(AccessibilityAction.ACTION_LONG_CLICK);
|
||||
}
|
||||
|
||||
if ((item instanceof AppInfo) || (item instanceof PendingAddItemInfo)) {
|
||||
info.addAction(mActions.get(ADD_TO_WORKSPACE));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean itemSupportsLongClick(View host, ItemInfo info) {
|
||||
return PopupContainerWithArrow.canShow(host, info)
|
||||
|| new CustomActionsPopup(mLauncher, host).canShow();
|
||||
}
|
||||
|
||||
private boolean itemSupportsAccessibleDrag(ItemInfo item) {
|
||||
if (item instanceof WorkspaceItemInfo) {
|
||||
// Support the action unless the item is in a context menu.
|
||||
return item.screenId >= 0;
|
||||
return item.screenId >= 0 && item.container != Favorites.CONTAINER_HOTSEAT_PREDICTION;
|
||||
}
|
||||
return (item instanceof LauncherAppWidgetInfo)
|
||||
|| (item instanceof FolderInfo);
|
||||
@@ -166,13 +185,25 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
}
|
||||
|
||||
public boolean performAction(final View host, final ItemInfo item, int action) {
|
||||
if (action == ACTION_LONG_CLICK && ShortcutUtil.isDeepShortcut(item)) {
|
||||
CustomActionsPopup popup = new CustomActionsPopup(mLauncher, host);
|
||||
if (popup.canShow()) {
|
||||
popup.show();
|
||||
if (action == ACTION_LONG_CLICK) {
|
||||
if (PopupContainerWithArrow.canShow(host, item)) {
|
||||
// Long press should be consumed for workspace items, and it should invoke the
|
||||
// Shortcuts / Notifications / Actions pop-up menu, and not start a drag as the
|
||||
// standard long press path does.
|
||||
PopupContainerWithArrow.showForIcon((BubbleTextView) host);
|
||||
return true;
|
||||
} else {
|
||||
CustomActionsPopup popup = new CustomActionsPopup(mLauncher, host);
|
||||
if (popup.canShow()) {
|
||||
popup.show();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (host instanceof AccessibilityActionHandler
|
||||
&& ((AccessibilityActionHandler) host).performAccessibilityAction(action, item)) {
|
||||
return true;
|
||||
}
|
||||
if (action == MOVE) {
|
||||
beginAccessibleDrag(host, item);
|
||||
} else if (action == ADD_TO_WORKSPACE) {
|
||||
@@ -191,6 +222,7 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
ArrayList<ItemInfo> itemList = new ArrayList<>();
|
||||
itemList.add(info);
|
||||
mLauncher.bindItems(itemList, true);
|
||||
announceConfirmation(R.string.item_added_to_workspace);
|
||||
} else if (item instanceof PendingAddItemInfo) {
|
||||
PendingAddItemInfo info = (PendingAddItemInfo) item;
|
||||
Workspace workspace = mLauncher.getWorkspace();
|
||||
@@ -198,7 +230,6 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
mLauncher.addPendingItem(info, Favorites.CONTAINER_DESKTOP,
|
||||
screenId, coordinates, info.spanX, info.spanY);
|
||||
}
|
||||
announceConfirmation(R.string.item_added_to_workspace);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
@@ -388,11 +419,11 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
|
||||
Rect pos = new Rect();
|
||||
mLauncher.getDragLayer().getDescendantRectRelativeToSelf(item, pos);
|
||||
mLauncher.getDragController().prepareAccessibleDrag(pos.centerX(), pos.centerY());
|
||||
mLauncher.getDragController().addDragListener(this);
|
||||
|
||||
DragOptions options = new DragOptions();
|
||||
options.isAccessibleDrag = true;
|
||||
options.simulatedDndStartPoint = new Point(pos.centerX(), pos.centerY());
|
||||
ItemLongClickListener.beginDrag(item, mLauncher, info, options);
|
||||
}
|
||||
|
||||
@@ -443,4 +474,20 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
|
||||
}
|
||||
return screenId;
|
||||
}
|
||||
|
||||
/**
|
||||
* An interface allowing views to handle their own action.
|
||||
*/
|
||||
public interface AccessibilityActionHandler {
|
||||
|
||||
/**
|
||||
* performs accessibility action and returns true on success
|
||||
*/
|
||||
boolean performAccessibilityAction(int action, ItemInfo itemInfo);
|
||||
|
||||
/**
|
||||
* adds all the accessibility actions that can be handled.
|
||||
*/
|
||||
void addSupportedAccessibilityActions(AccessibilityNodeInfo accessibilityNodeInfo);
|
||||
}
|
||||
}
|
||||
@@ -23,11 +23,11 @@ import android.view.accessibility.AccessibilityNodeInfo;
|
||||
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
|
||||
|
||||
import com.android.launcher3.AbstractFloatingView;
|
||||
import com.android.launcher3.ItemInfo;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.LauncherSettings;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.WorkspaceItemInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
import com.android.launcher3.notification.NotificationMainView;
|
||||
import com.android.launcher3.shortcuts.DeepShortcutView;
|
||||
|
||||
|
||||
@@ -21,17 +21,17 @@ import android.graphics.Rect;
|
||||
import android.text.TextUtils;
|
||||
import android.view.View;
|
||||
|
||||
import com.android.launcher3.AppInfo;
|
||||
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
|
||||
|
||||
import com.android.launcher3.CellLayout;
|
||||
import com.android.launcher3.FolderInfo;
|
||||
import com.android.launcher3.ItemInfo;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.WorkspaceItemInfo;
|
||||
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate.DragType;
|
||||
import com.android.launcher3.dragndrop.DragLayer;
|
||||
|
||||
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.model.data.FolderInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.WorkspaceItemInfo;
|
||||
|
||||
/**
|
||||
* Implementation of {@link DragAndDropAccessibilityDelegate} to support DnD on workspace.
|
||||
|
||||
@@ -15,13 +15,19 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
|
||||
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_HAS_SHORTCUT_PERMISSION;
|
||||
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_QUIET_MODE_CHANGE_PERMISSION;
|
||||
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_QUIET_MODE_ENABLED;
|
||||
|
||||
import android.animation.ValueAnimator;
|
||||
import android.content.Context;
|
||||
import android.content.res.Configuration;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Point;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Bundle;
|
||||
import android.os.Process;
|
||||
import android.text.Selection;
|
||||
import android.text.SpannableStringBuilder;
|
||||
@@ -32,38 +38,37 @@ import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.WindowInsets;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.StringRes;
|
||||
import androidx.dynamicanimation.animation.DynamicAnimation;
|
||||
import androidx.recyclerview.widget.DefaultItemAnimator;
|
||||
import androidx.recyclerview.widget.LinearLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import com.android.launcher3.AppInfo;
|
||||
|
||||
import com.android.launcher3.BaseDraggingActivity;
|
||||
import com.android.launcher3.DeviceProfile;
|
||||
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
|
||||
import com.android.launcher3.DragSource;
|
||||
import com.android.launcher3.DropTarget.DragObject;
|
||||
import com.android.launcher3.Insettable;
|
||||
import com.android.launcher3.InsettableFrameLayout;
|
||||
import com.android.launcher3.ItemInfo;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.LauncherState;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.compat.AccessibilityManagerCompat;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.keyboard.FocusedItemDecorator;
|
||||
import com.android.launcher3.testing.TestProtocol;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
|
||||
import com.android.launcher3.util.ItemInfoMatcher;
|
||||
import com.android.launcher3.util.MultiValueAlpha;
|
||||
import com.android.launcher3.util.MultiValueAlpha.AlphaProperty;
|
||||
import com.android.launcher3.util.Themes;
|
||||
import com.android.launcher3.views.BottomUserEducationView;
|
||||
import com.android.launcher3.views.RecyclerViewFastScroller;
|
||||
import com.android.launcher3.views.SpringRelativeLayout;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* The all apps view container.
|
||||
*/
|
||||
@@ -75,8 +80,8 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
private static final float FLING_ANIMATION_THRESHOLD = 0.55f;
|
||||
private static final int ALPHA_CHANNEL_COUNT = 2;
|
||||
|
||||
private final Launcher mLauncher;
|
||||
private final AdapterHolder[] mAH;
|
||||
protected final BaseDraggingActivity mLauncher;
|
||||
protected final AdapterHolder[] mAH;
|
||||
private final ItemInfoMatcher mPersonalMatcher = ItemInfoMatcher.ofUser(Process.myUserHandle());
|
||||
private final ItemInfoMatcher mWorkMatcher = ItemInfoMatcher.not(mPersonalMatcher);
|
||||
private final AllAppsStore mAllAppsStore = new AllAppsStore();
|
||||
@@ -84,21 +89,26 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
private final Paint mNavBarScrimPaint;
|
||||
private int mNavBarScrimHeight = 0;
|
||||
|
||||
private SearchUiManager mSearchUiManager;
|
||||
protected SearchUiManager mSearchUiManager;
|
||||
private View mSearchContainer;
|
||||
private AllAppsPagedView mViewPager;
|
||||
|
||||
private FloatingHeaderView mHeader;
|
||||
private WorkModeSwitch mWorkModeSwitch;
|
||||
|
||||
|
||||
private SpannableStringBuilder mSearchQueryBuilder = null;
|
||||
|
||||
private boolean mUsingTabs;
|
||||
protected boolean mUsingTabs;
|
||||
private boolean mSearchModeWhileUsingTabs = false;
|
||||
|
||||
private RecyclerViewFastScroller mTouchHandler;
|
||||
private final Point mFastScrollerOffset = new Point();
|
||||
protected RecyclerViewFastScroller mTouchHandler;
|
||||
protected final Point mFastScrollerOffset = new Point();
|
||||
|
||||
private final MultiValueAlpha mMultiValueAlpha;
|
||||
|
||||
Rect mInsets = new Rect();
|
||||
|
||||
public AllAppsContainerView(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
@@ -110,7 +120,7 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
public AllAppsContainerView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
|
||||
mLauncher = Launcher.getLauncher(context);
|
||||
mLauncher = BaseDraggingActivity.fromContext(context);
|
||||
mLauncher.addOnDeviceProfileChangeListener(this);
|
||||
|
||||
mSearchQueryBuilder = new SpannableStringBuilder();
|
||||
@@ -132,6 +142,15 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
mMultiValueAlpha = new MultiValueAlpha(this, ALPHA_CHANNEL_COUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the long click listener for icons
|
||||
*/
|
||||
public void setOnIconLongClickListener(OnLongClickListener listener) {
|
||||
for (AdapterHolder holder : mAH) {
|
||||
holder.adapter.setOnIconLongClickListener(listener);
|
||||
}
|
||||
}
|
||||
|
||||
public AllAppsStore getAppsStore() {
|
||||
return mAllAppsStore;
|
||||
}
|
||||
@@ -140,6 +159,11 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
return mMultiValueAlpha.getProperty(index);
|
||||
}
|
||||
|
||||
public WorkModeSwitch getWorkModeSwitch() {
|
||||
return mWorkModeSwitch;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected void setDampedScrollShift(float shift) {
|
||||
// Bound the shift amount to avoid content from drawing on top (Y-val) of the QSB.
|
||||
@@ -160,16 +184,23 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
}
|
||||
|
||||
private void onAppsUpdated() {
|
||||
if (FeatureFlags.ALL_APPS_TABS_ENABLED) {
|
||||
boolean hasWorkApps = false;
|
||||
for (AppInfo app : mAllAppsStore.getApps()) {
|
||||
if (mWorkMatcher.matches(app, null)) {
|
||||
hasWorkApps = true;
|
||||
break;
|
||||
}
|
||||
boolean hasWorkApps = false;
|
||||
for (AppInfo app : mAllAppsStore.getApps()) {
|
||||
if (mWorkMatcher.matches(app, null)) {
|
||||
hasWorkApps = true;
|
||||
break;
|
||||
}
|
||||
rebindAdapters(hasWorkApps);
|
||||
}
|
||||
rebindAdapters(hasWorkApps);
|
||||
if (hasWorkApps) {
|
||||
resetWorkProfile();
|
||||
}
|
||||
}
|
||||
|
||||
private void resetWorkProfile() {
|
||||
mWorkModeSwitch.update(!mAllAppsStore.hasModelFlag(FLAG_QUIET_MODE_ENABLED));
|
||||
mAH[AdapterHolder.WORK].setupOverlay();
|
||||
mAH[AdapterHolder.WORK].applyPadding();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -194,14 +225,6 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
|
||||
@Override
|
||||
public boolean onInterceptTouchEvent(MotionEvent ev) {
|
||||
|
||||
// The AllAppsContainerView houses the QSB and is hence visible from the Workspace
|
||||
// Overview states. We shouldn't intercept for the scrubber in these cases.
|
||||
if (!mLauncher.isInState(LauncherState.ALL_APPS)) {
|
||||
mTouchHandler = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
|
||||
AllAppsRecyclerView rv = getActiveRecyclerView();
|
||||
if (rv != null &&
|
||||
@@ -221,14 +244,14 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
public boolean onTouchEvent(MotionEvent ev) {
|
||||
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
|
||||
AllAppsRecyclerView rv = getActiveRecyclerView();
|
||||
if (rv != null && rv.getScrollbar()
|
||||
.isHitInParent(ev.getX(), ev.getY(), mFastScrollerOffset)) {
|
||||
if (rv != null && rv.getScrollbar().isHitInParent(ev.getX(), ev.getY(),
|
||||
mFastScrollerOffset)) {
|
||||
mTouchHandler = rv.getScrollbar();
|
||||
} else {
|
||||
mTouchHandler = null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (mTouchHandler != null) {
|
||||
mTouchHandler.handleTouchEvent(ev, mFastScrollerOffset);
|
||||
return true;
|
||||
@@ -257,6 +280,10 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
}
|
||||
}
|
||||
|
||||
public LayoutInflater getLayoutInflater() {
|
||||
return LayoutInflater.from(getContext());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the state of AllApps.
|
||||
*/
|
||||
@@ -304,44 +331,42 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDropCompleted(View target, DragObject d, boolean success) { }
|
||||
public void onDropCompleted(View target, DragObject d, boolean success) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
|
||||
if (getApps().hasFilter()) {
|
||||
targetParent.containerType = ContainerType.SEARCHRESULT;
|
||||
} else {
|
||||
targetParent.containerType = ContainerType.ALLAPPS;
|
||||
}
|
||||
public void fillInLogContainerData(ItemInfo childInfo, Target child,
|
||||
ArrayList<Target> parents) {
|
||||
parents.add(newContainerTarget(
|
||||
getApps().hasFilter() ? ContainerType.SEARCHRESULT : ContainerType.ALLAPPS));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInsets(Rect insets) {
|
||||
mInsets.set(insets);
|
||||
DeviceProfile grid = mLauncher.getDeviceProfile();
|
||||
int leftRightPadding = grid.desiredWorkspaceLeftRightMarginPx
|
||||
+ grid.cellLayoutPaddingLeftRightPx;
|
||||
|
||||
for (int i = 0; i < mAH.length; i++) {
|
||||
mAH[i].adapter.setAppsPerRow(grid.inv.numAllAppsColumns);
|
||||
mAH[i].padding.bottom = insets.bottom;
|
||||
mAH[i].padding.left = mAH[i].padding.right = leftRightPadding;
|
||||
mAH[i].applyPadding();
|
||||
mAH[i].setupOverlay();
|
||||
}
|
||||
|
||||
ViewGroup.MarginLayoutParams mlp = (MarginLayoutParams) getLayoutParams();
|
||||
if (grid.isVerticalBarLayout()) {
|
||||
mlp.leftMargin = insets.left;
|
||||
mlp.rightMargin = insets.right;
|
||||
setPadding(grid.workspacePadding.left, 0, grid.workspacePadding.right, 0);
|
||||
} else {
|
||||
mlp.leftMargin = mlp.rightMargin = 0;
|
||||
setPadding(0, 0, 0, 0);
|
||||
}
|
||||
mlp.leftMargin = insets.left;
|
||||
mlp.rightMargin = insets.right;
|
||||
setLayoutParams(mlp);
|
||||
|
||||
if (grid.isVerticalBarLayout()) {
|
||||
setPadding(grid.workspacePadding.left, 0, grid.workspacePadding.right, 0);
|
||||
} else {
|
||||
setPadding(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
InsettableFrameLayout.dispatchInsets(this, insets);
|
||||
mLauncher.getAllAppsController()
|
||||
.setScrollRangeDelta(mSearchUiManager.getScrollRangeDelta(insets));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -374,7 +399,7 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
rebindAdapters(showTabs, false /* force */);
|
||||
}
|
||||
|
||||
private void rebindAdapters(boolean showTabs, boolean force) {
|
||||
protected void rebindAdapters(boolean showTabs, boolean force) {
|
||||
if (showTabs == mUsingTabs && !force) {
|
||||
return;
|
||||
}
|
||||
@@ -385,12 +410,22 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
mAllAppsStore.unregisterIconContainer(mAH[AdapterHolder.WORK].recyclerView);
|
||||
|
||||
if (mUsingTabs) {
|
||||
setupWorkToggle();
|
||||
mAH[AdapterHolder.MAIN].setup(mViewPager.getChildAt(0), mPersonalMatcher);
|
||||
mAH[AdapterHolder.WORK].setup(mViewPager.getChildAt(1), mWorkMatcher);
|
||||
mViewPager.getPageIndicator().setActiveMarker(AdapterHolder.MAIN);
|
||||
findViewById(R.id.tab_personal)
|
||||
.setOnClickListener((View view) -> mViewPager.snapToPage(AdapterHolder.MAIN));
|
||||
findViewById(R.id.tab_work)
|
||||
.setOnClickListener((View view) -> mViewPager.snapToPage(AdapterHolder.WORK));
|
||||
onTabChanged(mViewPager.getNextPage());
|
||||
} else {
|
||||
mAH[AdapterHolder.MAIN].setup(findViewById(R.id.apps_list_view), null);
|
||||
mAH[AdapterHolder.WORK].recyclerView = null;
|
||||
if (mWorkModeSwitch != null) {
|
||||
((ViewGroup) mWorkModeSwitch.getParent()).removeView(mWorkModeSwitch);
|
||||
mWorkModeSwitch = null;
|
||||
}
|
||||
}
|
||||
setupHeader();
|
||||
|
||||
@@ -398,6 +433,25 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
mAllAppsStore.registerIconContainer(mAH[AdapterHolder.WORK].recyclerView);
|
||||
}
|
||||
|
||||
private void setupWorkToggle() {
|
||||
if (Utilities.ATLEAST_P) {
|
||||
mWorkModeSwitch = (WorkModeSwitch) mLauncher.getLayoutInflater().inflate(
|
||||
R.layout.work_mode_switch, this, false);
|
||||
this.addView(mWorkModeSwitch);
|
||||
mWorkModeSwitch.setInsets(mInsets);
|
||||
mWorkModeSwitch.post(() -> mAH[AdapterHolder.WORK].applyPadding());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onConfigurationChanged(Configuration newConfig) {
|
||||
super.onConfigurationChanged(newConfig);
|
||||
View overlay = mAH[AdapterHolder.WORK].getOverlayView();
|
||||
int v = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? GONE : VISIBLE;
|
||||
overlay.findViewById(R.id.work_apps_paused_title).setVisibility(v);
|
||||
overlay.findViewById(R.id.work_apps_paused_content).setVisibility(v);
|
||||
}
|
||||
|
||||
private void replaceRVContainer(boolean showTabs) {
|
||||
for (int i = 0; i < mAH.length; i++) {
|
||||
if (mAH[i].recyclerView != null) {
|
||||
@@ -408,7 +462,7 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
int index = indexOfChild(oldView);
|
||||
removeView(oldView);
|
||||
int layout = showTabs ? R.layout.all_apps_tabs : R.layout.all_apps_rv_layout;
|
||||
View newView = LayoutInflater.from(getContext()).inflate(layout, this, false);
|
||||
View newView = getLayoutInflater().inflate(layout, this, false);
|
||||
addView(newView, index);
|
||||
if (showTabs) {
|
||||
mViewPager = (AllAppsPagedView) newView;
|
||||
@@ -425,18 +479,14 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
|
||||
public void onTabChanged(int pos) {
|
||||
mHeader.setMainActive(pos == 0);
|
||||
reset(true /* animate */);
|
||||
if (mAH[pos].recyclerView != null) {
|
||||
mAH[pos].recyclerView.bindFastScrollbar();
|
||||
|
||||
findViewById(R.id.tab_personal)
|
||||
.setOnClickListener((View view) -> mViewPager.snapToPage(AdapterHolder.MAIN));
|
||||
findViewById(R.id.tab_work)
|
||||
.setOnClickListener((View view) -> mViewPager.snapToPage(AdapterHolder.WORK));
|
||||
|
||||
}
|
||||
if (pos == AdapterHolder.WORK) {
|
||||
BottomUserEducationView.showIfNeeded(mLauncher);
|
||||
reset(true /* animate */);
|
||||
if (mWorkModeSwitch != null) {
|
||||
mWorkModeSwitch.setWorkTabVisible(pos == AdapterHolder.WORK
|
||||
&& mAllAppsStore.hasModelFlag(
|
||||
FLAG_HAS_SHORTCUT_PERMISSION | FLAG_QUIET_MODE_CHANGE_PERMISSION));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,17 +583,6 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
return mHeader != null && mHeader.getVisibility() == View.VISIBLE;
|
||||
}
|
||||
|
||||
public void onScrollUpEnd() {
|
||||
highlightWorkTabIfNecessary();
|
||||
}
|
||||
|
||||
void highlightWorkTabIfNecessary() {
|
||||
if (mUsingTabs) {
|
||||
((PersonalWorkSlidingTabStrip) findViewById(R.id.tabs))
|
||||
.highlightWorkTabIfNecessary();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an update listener to {@param animator} that adds springs to the animation.
|
||||
*/
|
||||
@@ -557,15 +596,8 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
&& valueAnimator.getAnimatedFraction() >= FLING_ANIMATION_THRESHOLD) {
|
||||
int searchViewId = getSearchView().getId();
|
||||
addSpringView(searchViewId);
|
||||
|
||||
finishWithShiftAndVelocity(1, velocity * FLING_VELOCITY_MULTIPLIER,
|
||||
new DynamicAnimation.OnAnimationEndListener() {
|
||||
@Override
|
||||
public void onAnimationEnd(DynamicAnimation animation,
|
||||
boolean canceled, float value, float velocity) {
|
||||
removeSpringView(searchViewId);
|
||||
}
|
||||
});
|
||||
(anim, canceled, value, velocity) -> removeSpringView(searchViewId));
|
||||
|
||||
shouldSpring = false;
|
||||
}
|
||||
@@ -583,25 +615,32 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
public static final int MAIN = 0;
|
||||
public static final int WORK = 1;
|
||||
|
||||
private ItemInfoMatcher mInfoMatcher;
|
||||
private final boolean mIsWork;
|
||||
public final AllAppsGridAdapter adapter;
|
||||
final LinearLayoutManager layoutManager;
|
||||
final AlphabeticalAppsList appsList;
|
||||
final Rect padding = new Rect();
|
||||
AllAppsRecyclerView recyclerView;
|
||||
boolean verticalFadingEdge;
|
||||
private View mOverlay;
|
||||
|
||||
boolean mWorkDisabled;
|
||||
|
||||
AdapterHolder(boolean isWork) {
|
||||
mIsWork = isWork;
|
||||
appsList = new AlphabeticalAppsList(mLauncher, mAllAppsStore, isWork);
|
||||
adapter = new AllAppsGridAdapter(mLauncher, appsList);
|
||||
adapter = new AllAppsGridAdapter(mLauncher, getLayoutInflater(), appsList);
|
||||
appsList.setAdapter(adapter);
|
||||
layoutManager = adapter.getLayoutManager();
|
||||
}
|
||||
|
||||
void setup(@NonNull View rv, @Nullable ItemInfoMatcher matcher) {
|
||||
mInfoMatcher = matcher;
|
||||
appsList.updateItemFilter(matcher);
|
||||
recyclerView = (AllAppsRecyclerView) rv;
|
||||
recyclerView.setEdgeEffectFactory(createEdgeEffectFactory());
|
||||
recyclerView.setApps(appsList, mUsingTabs);
|
||||
recyclerView.setApps(appsList);
|
||||
recyclerView.setLayoutManager(layoutManager);
|
||||
recyclerView.setAdapter(adapter);
|
||||
recyclerView.setHasFixedSize(true);
|
||||
@@ -612,11 +651,45 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
adapter.setIconFocusListener(focusedItemDecorator.getFocusListener());
|
||||
applyVerticalFadingEdgeEnabled(verticalFadingEdge);
|
||||
applyPadding();
|
||||
setupOverlay();
|
||||
}
|
||||
|
||||
void setupOverlay() {
|
||||
if (!mIsWork || recyclerView == null) return;
|
||||
boolean workDisabled = mAllAppsStore.hasModelFlag(FLAG_QUIET_MODE_ENABLED);
|
||||
if (mWorkDisabled == workDisabled) return;
|
||||
recyclerView.setContentDescription(workDisabled ? mLauncher.getString(
|
||||
R.string.work_apps_paused_content_description) : null);
|
||||
View overlayView = getOverlayView();
|
||||
recyclerView.setItemAnimator(new DefaultItemAnimator());
|
||||
if (workDisabled) {
|
||||
overlayView.setAlpha(0);
|
||||
recyclerView.addAutoSizedOverlay(overlayView);
|
||||
overlayView.animate().alpha(1).withEndAction(
|
||||
() -> {
|
||||
appsList.updateItemFilter((info, cn) -> false);
|
||||
recyclerView.setItemAnimator(null);
|
||||
}).start();
|
||||
} else if (mInfoMatcher != null) {
|
||||
appsList.updateItemFilter(mInfoMatcher);
|
||||
overlayView.animate().alpha(0).withEndAction(() -> {
|
||||
recyclerView.setItemAnimator(null);
|
||||
recyclerView.clearAutoSizedOverlays();
|
||||
}).start();
|
||||
}
|
||||
mWorkDisabled = workDisabled;
|
||||
}
|
||||
|
||||
void applyPadding() {
|
||||
if (recyclerView != null) {
|
||||
recyclerView.setPadding(padding.left, padding.top, padding.right, padding.bottom);
|
||||
Resources res = getResources();
|
||||
int switchH = res.getDimensionPixelSize(R.dimen.work_profile_footer_padding) * 2
|
||||
+ mInsets.bottom + Utilities.calculateTextHeight(
|
||||
res.getDimension(R.dimen.work_profile_footer_text_size));
|
||||
|
||||
int bottomOffset = mWorkModeSwitch != null && mIsWork ? switchH : 0;
|
||||
recyclerView.setPadding(padding.left, padding.top, padding.right,
|
||||
padding.bottom + bottomOffset);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -625,18 +698,12 @@ public class AllAppsContainerView extends SpringRelativeLayout implements DragSo
|
||||
mAH[AdapterHolder.MAIN].recyclerView.setVerticalFadingEdgeEnabled(!mUsingTabs
|
||||
&& verticalFadingEdge);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean performAccessibilityAction(int action, Bundle arguments) {
|
||||
if (AccessibilityManagerCompat.processTestRequest(
|
||||
mLauncher, TestProtocol.GET_SCROLL_MESSAGE, action, arguments,
|
||||
response ->
|
||||
response.putInt(TestProtocol.SCROLL_Y_FIELD,
|
||||
getActiveRecyclerView().getCurrentScrollY()))) {
|
||||
return true;
|
||||
private View getOverlayView() {
|
||||
if (mOverlay == null) {
|
||||
mOverlay = mLauncher.getLayoutInflater().inflate(R.layout.work_apps_paused, null);
|
||||
}
|
||||
return mOverlay;
|
||||
}
|
||||
|
||||
return super.performAccessibilityAction(action, arguments);
|
||||
}
|
||||
}
|
||||
@@ -15,206 +15,90 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import com.android.launcher3.util.Thunk;
|
||||
import androidx.recyclerview.widget.LinearSmoothScroller;
|
||||
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import com.android.launcher3.allapps.AlphabeticalAppsList.FastScrollSectionInfo;
|
||||
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
public class AllAppsFastScrollHelper {
|
||||
|
||||
public class AllAppsFastScrollHelper implements AllAppsGridAdapter.BindViewCallback {
|
||||
private static final int NO_POSITION = -1;
|
||||
|
||||
private static final int INITIAL_TOUCH_SETTLING_DURATION = 100;
|
||||
private static final int REPEAT_TOUCH_SETTLING_DURATION = 200;
|
||||
private int mTargetFastScrollPosition = NO_POSITION;
|
||||
|
||||
private AllAppsRecyclerView mRv;
|
||||
private AlphabeticalAppsList mApps;
|
||||
private ViewHolder mLastSelectedViewHolder;
|
||||
|
||||
// Keeps track of the current and targeted fast scroll section (the section to scroll to after
|
||||
// the initial delay)
|
||||
int mTargetFastScrollPosition = -1;
|
||||
@Thunk String mCurrentFastScrollSection;
|
||||
@Thunk String mTargetFastScrollSection;
|
||||
|
||||
// The settled states affect the delay before the fast scroll animation is applied
|
||||
private boolean mHasFastScrollTouchSettled;
|
||||
private boolean mHasFastScrollTouchSettledAtLeastOnce;
|
||||
|
||||
// Set of all views animated during fast scroll. We keep track of these ourselves since there
|
||||
// is no way to reset a view once it gets scrapped or recycled without other hacks
|
||||
private HashSet<RecyclerView.ViewHolder> mTrackedFastScrollViews = new HashSet<>();
|
||||
|
||||
// Smooth fast-scroll animation frames
|
||||
@Thunk int mFastScrollFrameIndex;
|
||||
@Thunk final int[] mFastScrollFrames = new int[10];
|
||||
|
||||
/**
|
||||
* This runnable runs a single frame of the smooth scroll animation and posts the next frame
|
||||
* if necessary.
|
||||
*/
|
||||
@Thunk Runnable mSmoothSnapNextFrameRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (mFastScrollFrameIndex < mFastScrollFrames.length) {
|
||||
mRv.scrollBy(0, mFastScrollFrames[mFastScrollFrameIndex]);
|
||||
mFastScrollFrameIndex++;
|
||||
mRv.postOnAnimation(mSmoothSnapNextFrameRunnable);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* This runnable updates the current fast scroll section to the target fastscroll section.
|
||||
*/
|
||||
Runnable mFastScrollToTargetSectionRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// Update to the target section
|
||||
mCurrentFastScrollSection = mTargetFastScrollSection;
|
||||
mHasFastScrollTouchSettled = true;
|
||||
mHasFastScrollTouchSettledAtLeastOnce = true;
|
||||
updateTrackedViewsFastScrollFocusState();
|
||||
}
|
||||
};
|
||||
|
||||
public AllAppsFastScrollHelper(AllAppsRecyclerView rv, AlphabeticalAppsList apps) {
|
||||
public AllAppsFastScrollHelper(AllAppsRecyclerView rv) {
|
||||
mRv = rv;
|
||||
mApps = apps;
|
||||
}
|
||||
|
||||
public void onSetAdapter(AllAppsGridAdapter adapter) {
|
||||
adapter.setBindViewCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Smooth scrolls the recycler view to the given section.
|
||||
*
|
||||
* @return whether the fastscroller can scroll to the new section.
|
||||
*/
|
||||
public boolean smoothScrollToSection(int scrollY, int availableScrollHeight,
|
||||
AlphabeticalAppsList.FastScrollSectionInfo info) {
|
||||
if (mTargetFastScrollPosition != info.fastScrollToItem.position) {
|
||||
mTargetFastScrollPosition = info.fastScrollToItem.position;
|
||||
smoothSnapToPosition(scrollY, availableScrollHeight, info);
|
||||
return true;
|
||||
public void smoothScrollToSection(FastScrollSectionInfo info) {
|
||||
if (mTargetFastScrollPosition == info.fastScrollToItem.position) {
|
||||
return;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Smoothly snaps to a given position. We do this manually by calculating the keyframes
|
||||
* ourselves and animating the scroll on the recycler view.
|
||||
*/
|
||||
private void smoothSnapToPosition(int scrollY, int availableScrollHeight,
|
||||
AlphabeticalAppsList.FastScrollSectionInfo info) {
|
||||
mRv.removeCallbacks(mSmoothSnapNextFrameRunnable);
|
||||
mRv.removeCallbacks(mFastScrollToTargetSectionRunnable);
|
||||
|
||||
trackAllChildViews();
|
||||
if (mHasFastScrollTouchSettled) {
|
||||
// In this case, the user has already settled once (and the fast scroll state has
|
||||
// animated) and they are just fine-tuning their section from the last section, so
|
||||
// we should make it feel fast and update immediately.
|
||||
mCurrentFastScrollSection = info.sectionName;
|
||||
mTargetFastScrollSection = null;
|
||||
updateTrackedViewsFastScrollFocusState();
|
||||
} else {
|
||||
// Otherwise, the user has scrubbed really far, and we don't want to distract the user
|
||||
// with the flashing fast scroll state change animation in addition to the fast scroll
|
||||
// section popup, so reset the views to normal, and wait for the touch to settle again
|
||||
// before animating the fast scroll state.
|
||||
mCurrentFastScrollSection = null;
|
||||
mTargetFastScrollSection = info.sectionName;
|
||||
mHasFastScrollTouchSettled = false;
|
||||
updateTrackedViewsFastScrollFocusState();
|
||||
|
||||
// Delay scrolling to a new section until after some duration. If the user has been
|
||||
// scrubbing a while and makes multiple big jumps, then reduce the time needed for the
|
||||
// fast scroll to settle so it doesn't feel so long.
|
||||
mRv.postDelayed(mFastScrollToTargetSectionRunnable,
|
||||
mHasFastScrollTouchSettledAtLeastOnce ?
|
||||
REPEAT_TOUCH_SETTLING_DURATION :
|
||||
INITIAL_TOUCH_SETTLING_DURATION);
|
||||
}
|
||||
|
||||
// Calculate the full animation from the current scroll position to the final scroll
|
||||
// position, and then run the animation for the duration. If we are scrolling to the
|
||||
// first fast scroll section, then just scroll to the top of the list itself.
|
||||
List<AlphabeticalAppsList.FastScrollSectionInfo> fastScrollSections =
|
||||
mApps.getFastScrollerSections();
|
||||
int newPosition = info.fastScrollToItem.position;
|
||||
int newScrollY = fastScrollSections.size() > 0 && fastScrollSections.get(0) == info
|
||||
? 0
|
||||
: Math.min(availableScrollHeight, mRv.getCurrentScrollY(newPosition, 0));
|
||||
int numFrames = mFastScrollFrames.length;
|
||||
int deltaY = newScrollY - scrollY;
|
||||
float ySign = Math.signum(deltaY);
|
||||
int step = (int) (ySign * Math.ceil((float) Math.abs(deltaY) / numFrames));
|
||||
for (int i = 0; i < numFrames; i++) {
|
||||
// TODO(winsonc): We can interpolate this as well.
|
||||
mFastScrollFrames[i] = (int) (ySign * Math.min(Math.abs(step), Math.abs(deltaY)));
|
||||
deltaY -= step;
|
||||
}
|
||||
mFastScrollFrameIndex = 0;
|
||||
mRv.postOnAnimation(mSmoothSnapNextFrameRunnable);
|
||||
mTargetFastScrollPosition = info.fastScrollToItem.position;
|
||||
mRv.getLayoutManager().startSmoothScroll(new MyScroller(mTargetFastScrollPosition));
|
||||
}
|
||||
|
||||
public void onFastScrollCompleted() {
|
||||
// TODO(winsonc): Handle the case when the user scrolls and releases before the animation
|
||||
// runs
|
||||
|
||||
// Stop animating the fast scroll position and state
|
||||
mRv.removeCallbacks(mSmoothSnapNextFrameRunnable);
|
||||
mRv.removeCallbacks(mFastScrollToTargetSectionRunnable);
|
||||
|
||||
// Reset the tracking variables
|
||||
mHasFastScrollTouchSettled = false;
|
||||
mHasFastScrollTouchSettledAtLeastOnce = false;
|
||||
mCurrentFastScrollSection = null;
|
||||
mTargetFastScrollSection = null;
|
||||
mTargetFastScrollPosition = -1;
|
||||
|
||||
updateTrackedViewsFastScrollFocusState();
|
||||
mTrackedFastScrollViews.clear();
|
||||
mTargetFastScrollPosition = NO_POSITION;
|
||||
setLastHolderSelected(false);
|
||||
mLastSelectedViewHolder = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindView(AllAppsGridAdapter.ViewHolder holder) {
|
||||
// Update newly bound views to the current fast scroll state if we are fast scrolling
|
||||
if (mCurrentFastScrollSection != null || mTargetFastScrollSection != null) {
|
||||
mTrackedFastScrollViews.add(holder);
|
||||
|
||||
private void setLastHolderSelected(boolean isSelected) {
|
||||
if (mLastSelectedViewHolder != null) {
|
||||
mLastSelectedViewHolder.itemView.setActivated(isSelected);
|
||||
mLastSelectedViewHolder.setIsRecyclable(!isSelected);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts tracking all the recycler view's children which are FastScrollFocusableViews.
|
||||
*/
|
||||
private void trackAllChildViews() {
|
||||
int childCount = mRv.getChildCount();
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
RecyclerView.ViewHolder viewHolder = mRv.getChildViewHolder(mRv.getChildAt(i));
|
||||
if (viewHolder != null) {
|
||||
mTrackedFastScrollViews.add(viewHolder);
|
||||
}
|
||||
}
|
||||
}
|
||||
private class MyScroller extends LinearSmoothScroller {
|
||||
|
||||
/**
|
||||
* Updates the fast scroll focus on all the children.
|
||||
*/
|
||||
private void updateTrackedViewsFastScrollFocusState() {
|
||||
for (RecyclerView.ViewHolder viewHolder : mTrackedFastScrollViews) {
|
||||
int pos = viewHolder.getAdapterPosition();
|
||||
boolean isActive = false;
|
||||
if (mCurrentFastScrollSection != null
|
||||
&& pos > RecyclerView.NO_POSITION
|
||||
&& pos < mApps.getAdapterItems().size()) {
|
||||
AlphabeticalAppsList.AdapterItem item = mApps.getAdapterItems().get(pos);
|
||||
isActive = item != null &&
|
||||
mCurrentFastScrollSection.equals(item.sectionName) &&
|
||||
item.position == mTargetFastScrollPosition;
|
||||
private final int mTargetPosition;
|
||||
|
||||
public MyScroller(int targetPosition) {
|
||||
super(mRv.getContext());
|
||||
|
||||
mTargetPosition = targetPosition;
|
||||
setTargetPosition(targetPosition);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getVerticalSnapPreference() {
|
||||
return SNAP_TO_START;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
if (mTargetPosition != mTargetFastScrollPosition) {
|
||||
// Target changed, before the last scroll can finish
|
||||
return;
|
||||
}
|
||||
|
||||
ViewHolder currentHolder = mRv.findViewHolderForAdapterPosition(mTargetPosition);
|
||||
if (currentHolder == mLastSelectedViewHolder) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLastHolderSelected(false);
|
||||
mLastSelectedViewHolder = currentHolder;
|
||||
setLastHolderSelected(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
if (mTargetPosition != mTargetFastScrollPosition) {
|
||||
setLastHolderSelected(false);
|
||||
mLastSelectedViewHolder = null;
|
||||
}
|
||||
viewHolder.itemView.setActivated(isActive);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,36 +15,38 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import static com.android.launcher3.touch.ItemLongClickListener.INSTANCE_ALL_APPS;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.view.Gravity;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.View.OnClickListener;
|
||||
import android.view.View.OnFocusChangeListener;
|
||||
import android.view.View.OnLongClickListener;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.accessibility.AccessibilityEvent;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.android.launcher3.AppInfo;
|
||||
import com.android.launcher3.BubbleTextView;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.allapps.AlphabeticalAppsList.AdapterItem;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.model.AppLaunchTracker;
|
||||
import com.android.launcher3.touch.ItemClickHandler;
|
||||
import com.android.launcher3.touch.ItemLongClickListener;
|
||||
import com.android.launcher3.util.PackageManagerHelper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.view.accessibility.AccessibilityEventCompat;
|
||||
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
|
||||
import androidx.core.view.accessibility.AccessibilityRecordCompat;
|
||||
import androidx.recyclerview.widget.GridLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.android.launcher3.BaseDraggingActivity;
|
||||
import com.android.launcher3.BubbleTextView;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.allapps.AlphabeticalAppsList.AdapterItem;
|
||||
import com.android.launcher3.model.AppLaunchTracker;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.util.PackageManagerHelper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The grid view adapter of all the apps.
|
||||
*/
|
||||
@@ -64,17 +66,11 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter<AllAppsGridAdapter.
|
||||
|
||||
// A divider that separates the apps list and the search market button
|
||||
public static final int VIEW_TYPE_ALL_APPS_DIVIDER = 1 << 4;
|
||||
public static final int VIEW_TYPE_WORK_TAB_FOOTER = 1 << 5;
|
||||
|
||||
// Common view type masks
|
||||
public static final int VIEW_TYPE_MASK_DIVIDER = VIEW_TYPE_ALL_APPS_DIVIDER;
|
||||
public static final int VIEW_TYPE_MASK_ICON = VIEW_TYPE_ICON;
|
||||
|
||||
|
||||
public interface BindViewCallback {
|
||||
void onBindView(ViewHolder holder);
|
||||
}
|
||||
|
||||
/**
|
||||
* ViewHolder for each icon.
|
||||
*/
|
||||
@@ -174,23 +170,26 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter<AllAppsGridAdapter.
|
||||
}
|
||||
}
|
||||
|
||||
private final Launcher mLauncher;
|
||||
private final BaseDraggingActivity mLauncher;
|
||||
private final LayoutInflater mLayoutInflater;
|
||||
private final AlphabeticalAppsList mApps;
|
||||
private final GridLayoutManager mGridLayoutMgr;
|
||||
private final GridSpanSizer mGridSizer;
|
||||
|
||||
private final OnClickListener mOnIconClickListener;
|
||||
private OnLongClickListener mOnIconLongClickListener = INSTANCE_ALL_APPS;
|
||||
|
||||
private int mAppsPerRow;
|
||||
|
||||
private BindViewCallback mBindViewCallback;
|
||||
private OnFocusChangeListener mIconFocusListener;
|
||||
|
||||
// The text to show when there are no search results and no market search handler.
|
||||
private String mEmptySearchMessage;
|
||||
protected String mEmptySearchMessage;
|
||||
// The intent to send off to the market app, updated each time the search query changes.
|
||||
private Intent mMarketSearchIntent;
|
||||
|
||||
public AllAppsGridAdapter(Launcher launcher, AlphabeticalAppsList apps) {
|
||||
public AllAppsGridAdapter(BaseDraggingActivity launcher, LayoutInflater inflater,
|
||||
AlphabeticalAppsList apps) {
|
||||
Resources res = launcher.getResources();
|
||||
mLauncher = launcher;
|
||||
mApps = apps;
|
||||
@@ -198,7 +197,9 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter<AllAppsGridAdapter.
|
||||
mGridSizer = new GridSpanSizer();
|
||||
mGridLayoutMgr = new AppsGridLayoutManager(launcher);
|
||||
mGridLayoutMgr.setSpanSizeLookup(mGridSizer);
|
||||
mLayoutInflater = LayoutInflater.from(launcher);
|
||||
mLayoutInflater = inflater;
|
||||
|
||||
mOnIconClickListener = launcher.getItemOnClickListener();
|
||||
|
||||
setAppsPerRow(mLauncher.getDeviceProfile().inv.numAllAppsColumns);
|
||||
}
|
||||
@@ -208,6 +209,13 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter<AllAppsGridAdapter.
|
||||
mGridLayoutMgr.setSpanCount(mAppsPerRow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the long click listener for icons
|
||||
*/
|
||||
public void setOnIconLongClickListener(@Nullable OnLongClickListener listener) {
|
||||
mOnIconLongClickListener = listener;
|
||||
}
|
||||
|
||||
public static boolean isDividerViewType(int viewType) {
|
||||
return isViewType(viewType, VIEW_TYPE_MASK_DIVIDER);
|
||||
}
|
||||
@@ -234,13 +242,6 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter<AllAppsGridAdapter.
|
||||
mMarketSearchIntent = PackageManagerHelper.getMarketSearchIntent(mLauncher, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the callback for when views are bound.
|
||||
*/
|
||||
public void setBindViewCallback(BindViewCallback cb) {
|
||||
mBindViewCallback = cb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the grid layout manager.
|
||||
*/
|
||||
@@ -254,8 +255,8 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter<AllAppsGridAdapter.
|
||||
case VIEW_TYPE_ICON:
|
||||
BubbleTextView icon = (BubbleTextView) mLayoutInflater.inflate(
|
||||
R.layout.all_apps_icon, parent, false);
|
||||
icon.setOnClickListener(ItemClickHandler.INSTANCE);
|
||||
icon.setOnLongClickListener(ItemLongClickListener.INSTANCE_ALL_APPS);
|
||||
icon.setOnClickListener(mOnIconClickListener);
|
||||
icon.setOnLongClickListener(mOnIconLongClickListener);
|
||||
icon.setLongPressTimeoutFactor(1f);
|
||||
icon.setOnFocusChangeListener(mIconFocusListener);
|
||||
|
||||
@@ -274,9 +275,6 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter<AllAppsGridAdapter.
|
||||
case VIEW_TYPE_ALL_APPS_DIVIDER:
|
||||
return new ViewHolder(mLayoutInflater.inflate(
|
||||
R.layout.all_apps_divider, parent, false));
|
||||
case VIEW_TYPE_WORK_TAB_FOOTER:
|
||||
View footer = mLayoutInflater.inflate(R.layout.work_tab_footer, parent, false);
|
||||
return new ViewHolder(footer);
|
||||
default:
|
||||
throw new RuntimeException("Unexpected view type");
|
||||
}
|
||||
@@ -308,18 +306,6 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter<AllAppsGridAdapter.
|
||||
case VIEW_TYPE_ALL_APPS_DIVIDER:
|
||||
// nothing to do
|
||||
break;
|
||||
case VIEW_TYPE_WORK_TAB_FOOTER:
|
||||
WorkModeSwitch workModeToggle = holder.itemView.findViewById(R.id.work_mode_toggle);
|
||||
workModeToggle.refresh();
|
||||
TextView managedByLabel = holder.itemView.findViewById(R.id.managed_by_label);
|
||||
boolean anyProfileQuietModeEnabled = UserManagerCompat.getInstance(
|
||||
managedByLabel.getContext()).isAnyProfileQuietModeEnabled();
|
||||
managedByLabel.setText(anyProfileQuietModeEnabled
|
||||
? R.string.work_mode_off_label : R.string.work_mode_on_label);
|
||||
break;
|
||||
}
|
||||
if (mBindViewCallback != null) {
|
||||
mBindViewCallback.onBindView(holder);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ public class AllAppsPagedView extends PagedView<PersonalWorkSlidingTabStrip> {
|
||||
@Override
|
||||
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
|
||||
super.onScrollChanged(l, t, oldl, oldt);
|
||||
mPageIndicator.setScroll(l, mMaxScrollX);
|
||||
mPageIndicator.setScroll(l, mMaxScroll);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -83,7 +83,7 @@ public class AllAppsPagedView extends PagedView<PersonalWorkSlidingTabStrip> {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isVerticalScrollable() {
|
||||
return false;
|
||||
protected boolean canScroll(float absVScroll, float absHScroll) {
|
||||
return (absHScroll > absVScroll) && super.canScroll(absVScroll, absHScroll);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,11 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import static android.view.View.MeasureSpec.EXACTLY;
|
||||
import static android.view.View.MeasureSpec.UNSPECIFIED;
|
||||
import static android.view.View.MeasureSpec.makeMeasureSpec;
|
||||
|
||||
import static com.android.launcher3.logging.LoggerUtils.newContainerTarget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
@@ -28,19 +32,19 @@ import android.view.View;
|
||||
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.android.launcher3.BaseDraggingActivity;
|
||||
import com.android.launcher3.BaseRecyclerView;
|
||||
import com.android.launcher3.DeviceProfile;
|
||||
import com.android.launcher3.ItemInfo;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.LauncherAppState;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.allapps.AllAppsGridAdapter.AppsGridLayoutManager;
|
||||
import com.android.launcher3.compat.AccessibilityManagerCompat;
|
||||
import com.android.launcher3.logging.StatsLogUtils.LogContainerProvider;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
|
||||
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
|
||||
import com.android.launcher3.views.RecyclerViewFastScroller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -49,17 +53,19 @@ import java.util.List;
|
||||
public class AllAppsRecyclerView extends BaseRecyclerView implements LogContainerProvider {
|
||||
|
||||
private AlphabeticalAppsList mApps;
|
||||
private AllAppsFastScrollHelper mFastScrollHelper;
|
||||
private final int mNumAppsPerRow;
|
||||
|
||||
// The specific view heights that we use to calculate scroll
|
||||
private SparseIntArray mViewHeights = new SparseIntArray();
|
||||
private SparseIntArray mCachedScrollPositions = new SparseIntArray();
|
||||
private final SparseIntArray mViewHeights = new SparseIntArray();
|
||||
private final SparseIntArray mCachedScrollPositions = new SparseIntArray();
|
||||
private final AllAppsFastScrollHelper mFastScrollHelper;
|
||||
|
||||
// The empty-search result background
|
||||
private AllAppsBackgroundDrawable mEmptySearchBackground;
|
||||
private int mEmptySearchBackgroundTopOffset;
|
||||
|
||||
private ArrayList<View> mAutoSizedOverlays = new ArrayList<>();
|
||||
|
||||
public AllAppsRecyclerView(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
@@ -79,14 +85,14 @@ public class AllAppsRecyclerView extends BaseRecyclerView implements LogContaine
|
||||
mEmptySearchBackgroundTopOffset = res.getDimensionPixelSize(
|
||||
R.dimen.all_apps_empty_search_bg_top_offset);
|
||||
mNumAppsPerRow = LauncherAppState.getIDP(context).numColumns;
|
||||
mFastScrollHelper = new AllAppsFastScrollHelper(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the list of apps in this view, used to determine the fastscroll position.
|
||||
*/
|
||||
public void setApps(AlphabeticalAppsList apps, boolean usingTabs) {
|
||||
public void setApps(AlphabeticalAppsList apps) {
|
||||
mApps = apps;
|
||||
mFastScrollHelper = new AllAppsFastScrollHelper(this, apps);
|
||||
}
|
||||
|
||||
public AlphabeticalAppsList getApps() {
|
||||
@@ -94,7 +100,7 @@ public class AllAppsRecyclerView extends BaseRecyclerView implements LogContaine
|
||||
}
|
||||
|
||||
private void updatePoolSize() {
|
||||
DeviceProfile grid = Launcher.getLauncher(getContext()).getDeviceProfile();
|
||||
DeviceProfile grid = BaseDraggingActivity.fromContext(getContext()).getDeviceProfile();
|
||||
RecyclerView.RecycledViewPool pool = getRecycledViewPool();
|
||||
int approxRows = (int) Math.ceil(grid.availableHeightPx / grid.allAppsIconSizePx);
|
||||
pool.setMaxRecycledViews(AllAppsGridAdapter.VIEW_TYPE_EMPTY_SEARCH, 1);
|
||||
@@ -143,15 +149,37 @@ public class AllAppsRecyclerView extends BaseRecyclerView implements LogContaine
|
||||
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
|
||||
updateEmptySearchBackgroundBounds();
|
||||
updatePoolSize();
|
||||
for (int i = 0; i < mAutoSizedOverlays.size(); i++) {
|
||||
View overlay = mAutoSizedOverlays.get(i);
|
||||
overlay.measure(makeMeasureSpec(w, EXACTLY), makeMeasureSpec(w, EXACTLY));
|
||||
overlay.layout(0, 0, w, h);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an overlay that automatically rescales with the recyclerview.
|
||||
*/
|
||||
public void addAutoSizedOverlay(View overlay) {
|
||||
mAutoSizedOverlays.add(overlay);
|
||||
getOverlay().add(overlay);
|
||||
onSizeChanged(getWidth(), getHeight(), getWidth(), getHeight());
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears auto scaling overlay views added by #addAutoSizedOverlay
|
||||
*/
|
||||
public void clearAutoSizedOverlays() {
|
||||
for (View v : mAutoSizedOverlays) {
|
||||
getOverlay().remove(v);
|
||||
}
|
||||
mAutoSizedOverlays.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
|
||||
if (mApps.hasFilter()) {
|
||||
targetParent.containerType = ContainerType.SEARCHRESULT;
|
||||
} else {
|
||||
targetParent.containerType = ContainerType.ALLAPPS;
|
||||
}
|
||||
public void fillInLogContainerData(ItemInfo childInfo, Target child,
|
||||
ArrayList<Target> parents) {
|
||||
parents.add(newContainerTarget(
|
||||
getApps().hasFilter() ? ContainerType.SEARCHRESULT : ContainerType.ALLAPPS));
|
||||
}
|
||||
|
||||
public void onSearchResultsChanged() {
|
||||
@@ -193,9 +221,6 @@ public class AllAppsRecyclerView extends BaseRecyclerView implements LogContaine
|
||||
return "";
|
||||
}
|
||||
|
||||
// Stop the scroller if it is scrolling
|
||||
stopScroll();
|
||||
|
||||
// Find the fastscroll section that maps to this touch fraction
|
||||
List<AlphabeticalAppsList.FastScrollSectionInfo> fastScrollSections =
|
||||
mApps.getFastScrollerSections();
|
||||
@@ -208,10 +233,7 @@ public class AllAppsRecyclerView extends BaseRecyclerView implements LogContaine
|
||||
lastInfo = info;
|
||||
}
|
||||
|
||||
// Update the fast scroll
|
||||
int scrollY = getCurrentScrollY();
|
||||
int availableScrollHeight = getAvailableScrollHeight();
|
||||
mFastScrollHelper.smoothScrollToSection(scrollY, availableScrollHeight, lastInfo);
|
||||
mFastScrollHelper.smoothScrollToSection(lastInfo);
|
||||
return lastInfo.sectionName;
|
||||
}
|
||||
|
||||
@@ -229,7 +251,6 @@ public class AllAppsRecyclerView extends BaseRecyclerView implements LogContaine
|
||||
mCachedScrollPositions.clear();
|
||||
}
|
||||
});
|
||||
mFastScrollHelper.onSetAdapter((AllAppsGridAdapter) adapter);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -15,22 +15,23 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import static com.android.launcher3.AppInfo.COMPONENT_KEY_COMPARATOR;
|
||||
import static com.android.launcher3.AppInfo.EMPTY_ARRAY;
|
||||
import static com.android.launcher3.model.data.AppInfo.COMPONENT_KEY_COMPARATOR;
|
||||
import static com.android.launcher3.model.data.AppInfo.EMPTY_ARRAY;
|
||||
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import com.android.launcher3.AppInfo;
|
||||
import com.android.launcher3.BubbleTextView;
|
||||
import com.android.launcher3.ItemInfo;
|
||||
import com.android.launcher3.PromiseAppInfo;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.model.data.ItemInfo;
|
||||
import com.android.launcher3.model.data.PromiseAppInfo;
|
||||
import com.android.launcher3.util.ComponentKey;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@@ -49,8 +50,9 @@ public class AllAppsStore {
|
||||
|
||||
private AppInfo[] mApps = EMPTY_ARRAY;
|
||||
|
||||
private final List<OnUpdateListener> mUpdateListeners = new ArrayList<>();
|
||||
private final List<OnUpdateListener> mUpdateListeners = new CopyOnWriteArrayList<>();
|
||||
private final ArrayList<ViewGroup> mIconContainers = new ArrayList<>();
|
||||
private int mModelFlags;
|
||||
|
||||
private int mDeferUpdatesFlags = 0;
|
||||
private boolean mUpdatePending = false;
|
||||
@@ -62,11 +64,21 @@ public class AllAppsStore {
|
||||
/**
|
||||
* Sets the current set of apps.
|
||||
*/
|
||||
public void setApps(AppInfo[] apps) {
|
||||
public void setApps(AppInfo[] apps, int flags) {
|
||||
mApps = apps;
|
||||
mModelFlags = flags;
|
||||
notifyUpdate();
|
||||
}
|
||||
|
||||
/**
|
||||
* @see com.android.launcher3.model.BgDataModel.Callbacks#FLAG_QUIET_MODE_ENABLED
|
||||
* @see com.android.launcher3.model.BgDataModel.Callbacks#FLAG_HAS_SHORTCUT_PERMISSION
|
||||
* @see com.android.launcher3.model.BgDataModel.Callbacks#FLAG_QUIET_MODE_CHANGE_PERMISSION
|
||||
*/
|
||||
public boolean hasModelFlag(int mask) {
|
||||
return (mModelFlags & mask) != 0;
|
||||
}
|
||||
|
||||
public AppInfo getApp(ComponentKey key) {
|
||||
mTempInfo.componentName = key.componentName;
|
||||
mTempInfo.user = key.user;
|
||||
@@ -99,9 +111,8 @@ public class AllAppsStore {
|
||||
mUpdatePending = true;
|
||||
return;
|
||||
}
|
||||
int count = mUpdateListeners.size();
|
||||
for (int i = 0; i < count; i++) {
|
||||
mUpdateListeners.get(i).onAppsUpdated();
|
||||
for (OnUpdateListener listener : mUpdateListeners) {
|
||||
listener.onAppsUpdated();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,35 +2,43 @@ package com.android.launcher3.allapps;
|
||||
|
||||
import static com.android.launcher3.LauncherState.ALL_APPS_CONTENT;
|
||||
import static com.android.launcher3.LauncherState.ALL_APPS_HEADER_EXTRA;
|
||||
import static com.android.launcher3.LauncherState.APPS_VIEW_ITEM_MASK;
|
||||
import static com.android.launcher3.LauncherState.OVERVIEW;
|
||||
import static com.android.launcher3.LauncherState.VERTICAL_SWIPE_INDICATOR;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_FADE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_ALL_APPS_HEADER_FADE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_OVERVIEW_SCALE;
|
||||
import static com.android.launcher3.anim.AnimatorSetBuilder.ANIM_VERTICAL_PROGRESS;
|
||||
import static com.android.launcher3.anim.Interpolators.FAST_OUT_SLOW_IN;
|
||||
import static com.android.launcher3.anim.Interpolators.FINAL_FRAME;
|
||||
import static com.android.launcher3.anim.Interpolators.INSTANT;
|
||||
import static com.android.launcher3.anim.Interpolators.LINEAR;
|
||||
import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
|
||||
import static com.android.launcher3.util.SystemUiController.UI_STATE_ALL_APPS;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_FADE;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_HEADER_FADE;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE;
|
||||
import static com.android.launcher3.states.StateAnimationConfig.ANIM_VERTICAL_PROGRESS;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.content.Context;
|
||||
import android.util.FloatProperty;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.animation.Interpolator;
|
||||
import android.widget.EditText;
|
||||
|
||||
import com.android.launcher3.DeviceProfile;
|
||||
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.LauncherState;
|
||||
import com.android.launcher3.LauncherStateManager.AnimationConfig;
|
||||
import com.android.launcher3.LauncherStateManager.StateHandler;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.anim.AnimationSuccessListener;
|
||||
import com.android.launcher3.anim.AnimatorSetBuilder;
|
||||
import com.android.launcher3.anim.PendingAnimation;
|
||||
import com.android.launcher3.anim.PropertySetter;
|
||||
import com.android.launcher3.anim.SpringObjectAnimator;
|
||||
import com.android.launcher3.util.Themes;
|
||||
import com.android.launcher3.statemanager.StateManager.StateHandler;
|
||||
import com.android.launcher3.states.StateAnimationConfig;
|
||||
import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
|
||||
import com.android.launcher3.views.ScrimView;
|
||||
import com.android.systemui.plugins.AllAppsSearchPlugin;
|
||||
import com.android.systemui.plugins.PluginListener;
|
||||
|
||||
/**
|
||||
* Handles AllApps view transition.
|
||||
@@ -42,10 +50,8 @@ import com.android.launcher3.views.ScrimView;
|
||||
* If release velocity < THRES1, snap according to either top or bottom depending on whether it's
|
||||
* closer to top or closer to the page indicator.
|
||||
*/
|
||||
public class AllAppsTransitionController implements StateHandler, OnDeviceProfileChangeListener {
|
||||
|
||||
private static final float SPRING_DAMPING_RATIO = 0.9f;
|
||||
private static final float SPRING_STIFFNESS = 600f;
|
||||
public class AllAppsTransitionController implements StateHandler<LauncherState>,
|
||||
OnDeviceProfileChangeListener, PluginListener<AllAppsSearchPlugin> {
|
||||
|
||||
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PROGRESS =
|
||||
new FloatProperty<AllAppsTransitionController>("allAppsProgress") {
|
||||
@@ -67,7 +73,6 @@ public class AllAppsTransitionController implements StateHandler, OnDeviceProfil
|
||||
private ScrimView mScrimView;
|
||||
|
||||
private final Launcher mLauncher;
|
||||
private final boolean mIsDarkTheme;
|
||||
private boolean mIsVerticalLayout;
|
||||
|
||||
// Animation in this class is controlled by a single variable {@link mProgress}.
|
||||
@@ -81,12 +86,15 @@ public class AllAppsTransitionController implements StateHandler, OnDeviceProfil
|
||||
|
||||
private float mScrollRangeDelta = 0;
|
||||
|
||||
// plugin related variables
|
||||
private AllAppsSearchPlugin mPlugin;
|
||||
private View mPluginContent;
|
||||
|
||||
public AllAppsTransitionController(Launcher l) {
|
||||
mLauncher = l;
|
||||
mShiftRange = mLauncher.getDeviceProfile().heightPx;
|
||||
mProgress = 1f;
|
||||
|
||||
mIsDarkTheme = Themes.getAttrBoolean(mLauncher, R.attr.isMainColorDark);
|
||||
mIsVerticalLayout = mLauncher.getDeviceProfile().isVerticalBarLayout();
|
||||
mLauncher.addOnDeviceProfileChangeListener(this);
|
||||
}
|
||||
@@ -114,7 +122,7 @@ public class AllAppsTransitionController implements StateHandler, OnDeviceProfil
|
||||
* @param progress value between 0 and 1, 0 shows all apps and 1 shows workspace
|
||||
*
|
||||
* @see #setState(LauncherState)
|
||||
* @see #setStateWithAnimation(LauncherState, AnimatorSetBuilder, AnimationConfig)
|
||||
* @see #setStateWithAnimation(LauncherState, StateAnimationConfig, PendingAnimation)
|
||||
*/
|
||||
public void setProgress(float progress) {
|
||||
mProgress = progress;
|
||||
@@ -122,15 +130,8 @@ public class AllAppsTransitionController implements StateHandler, OnDeviceProfil
|
||||
float shiftCurrent = progress * mShiftRange;
|
||||
|
||||
mAppsView.setTranslationY(shiftCurrent);
|
||||
|
||||
// Use a light system UI (dark icons) if all apps is behind at least half of the
|
||||
// status bar.
|
||||
boolean forceChange = shiftCurrent - mScrimView.getDragHandleSize()
|
||||
<= mLauncher.getDeviceProfile().getInsets().top / 2;
|
||||
if (forceChange) {
|
||||
mLauncher.getSystemUiController().updateUiState(UI_STATE_ALL_APPS, !mIsDarkTheme);
|
||||
} else {
|
||||
mLauncher.getSystemUiController().updateUiState(UI_STATE_ALL_APPS, 0);
|
||||
if (mPlugin != null) {
|
||||
mPlugin.setProgress(progress);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +146,7 @@ public class AllAppsTransitionController implements StateHandler, OnDeviceProfil
|
||||
@Override
|
||||
public void setState(LauncherState state) {
|
||||
setProgress(state.getVerticalProgress(mLauncher));
|
||||
setAlphas(state, null, new AnimatorSetBuilder());
|
||||
setAlphas(state, new StateAnimationConfig(), NO_ANIM_PROPERTY_SETTER);
|
||||
onProgressAnimationEnd();
|
||||
}
|
||||
|
||||
@@ -155,73 +156,80 @@ public class AllAppsTransitionController implements StateHandler, OnDeviceProfil
|
||||
*/
|
||||
@Override
|
||||
public void setStateWithAnimation(LauncherState toState,
|
||||
AnimatorSetBuilder builder, AnimationConfig config) {
|
||||
StateAnimationConfig config, PendingAnimation builder) {
|
||||
float targetProgress = toState.getVerticalProgress(mLauncher);
|
||||
if (Float.compare(mProgress, targetProgress) == 0) {
|
||||
setAlphas(toState, config, builder);
|
||||
if (!config.onlyPlayAtomicComponent()) {
|
||||
setAlphas(toState, config, builder);
|
||||
}
|
||||
// Fail fast
|
||||
onProgressAnimationEnd();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!config.playNonAtomicComponent()) {
|
||||
if (config.onlyPlayAtomicComponent()) {
|
||||
// There is no atomic component for the all apps transition, so just return early.
|
||||
return;
|
||||
}
|
||||
|
||||
Interpolator interpolator = config.userControlled ? LINEAR : toState == OVERVIEW
|
||||
? builder.getInterpolator(ANIM_OVERVIEW_SCALE, FAST_OUT_SLOW_IN)
|
||||
? config.getInterpolator(ANIM_OVERVIEW_SCALE, FAST_OUT_SLOW_IN)
|
||||
: FAST_OUT_SLOW_IN;
|
||||
Animator anim = createSpringAnimation(mProgress, targetProgress);
|
||||
anim.setDuration(config.duration);
|
||||
anim.setInterpolator(builder.getInterpolator(ANIM_VERTICAL_PROGRESS, interpolator));
|
||||
anim.addListener(getProgressAnimatorListener());
|
||||
|
||||
builder.play(anim);
|
||||
Animator anim = createSpringAnimation(mProgress, targetProgress);
|
||||
anim.setInterpolator(config.getInterpolator(ANIM_VERTICAL_PROGRESS, interpolator));
|
||||
anim.addListener(getProgressAnimatorListener());
|
||||
builder.add(anim);
|
||||
|
||||
setAlphas(toState, config, builder);
|
||||
}
|
||||
|
||||
public Animator createSpringAnimation(float... progressValues) {
|
||||
return new SpringObjectAnimator<>(this, ALL_APPS_PROGRESS, 1f / mShiftRange,
|
||||
SPRING_DAMPING_RATIO, SPRING_STIFFNESS, progressValues);
|
||||
return ObjectAnimator.ofFloat(this, ALL_APPS_PROGRESS, progressValues);
|
||||
}
|
||||
|
||||
private void setAlphas(LauncherState toState, AnimationConfig config,
|
||||
AnimatorSetBuilder builder) {
|
||||
setAlphas(toState.getVisibleElements(mLauncher), config, builder);
|
||||
}
|
||||
|
||||
public void setAlphas(int visibleElements, AnimationConfig config, AnimatorSetBuilder builder) {
|
||||
PropertySetter setter = config == null ? NO_ANIM_PROPERTY_SETTER
|
||||
: config.getPropertySetter(builder);
|
||||
/**
|
||||
* Updates the property for the provided state
|
||||
*/
|
||||
public void setAlphas(LauncherState state, StateAnimationConfig config, PropertySetter setter) {
|
||||
int visibleElements = state.getVisibleElements(mLauncher);
|
||||
boolean hasHeaderExtra = (visibleElements & ALL_APPS_HEADER_EXTRA) != 0;
|
||||
boolean hasAllAppsContent = (visibleElements & ALL_APPS_CONTENT) != 0;
|
||||
|
||||
Interpolator allAppsFade = builder.getInterpolator(ANIM_ALL_APPS_FADE, LINEAR);
|
||||
Interpolator headerFade = builder.getInterpolator(ANIM_ALL_APPS_HEADER_FADE, allAppsFade);
|
||||
setter.setViewAlpha(mAppsView.getContentView(), hasAllAppsContent ? 1 : 0, allAppsFade);
|
||||
setter.setViewAlpha(mAppsView.getScrollBar(), hasAllAppsContent ? 1 : 0, allAppsFade);
|
||||
mAppsView.getFloatingHeaderView().setContentVisibility(hasHeaderExtra, hasAllAppsContent,
|
||||
setter, headerFade, allAppsFade);
|
||||
boolean hasAnyVisibleItem = (visibleElements & APPS_VIEW_ITEM_MASK) != 0;
|
||||
|
||||
Interpolator allAppsFade = config.getInterpolator(ANIM_ALL_APPS_FADE, LINEAR);
|
||||
Interpolator headerFade = config.getInterpolator(ANIM_ALL_APPS_HEADER_FADE, allAppsFade);
|
||||
|
||||
if (mPlugin == null) {
|
||||
setter.setViewAlpha(mAppsView.getContentView(), hasAllAppsContent ? 1 : 0, allAppsFade);
|
||||
setter.setViewAlpha(mAppsView.getScrollBar(), hasAllAppsContent ? 1 : 0, allAppsFade);
|
||||
mAppsView.getFloatingHeaderView().setContentVisibility(hasHeaderExtra,
|
||||
hasAllAppsContent, setter, headerFade, allAppsFade);
|
||||
} else {
|
||||
setter.setViewAlpha(mPluginContent, hasAllAppsContent ? 1 : 0, allAppsFade);
|
||||
setter.setViewAlpha(mAppsView.getContentView(), 0, allAppsFade);
|
||||
setter.setViewAlpha(mAppsView.getScrollBar(), 0, allAppsFade);
|
||||
}
|
||||
mAppsView.getSearchUiManager().setContentVisibility(visibleElements, setter, allAppsFade);
|
||||
|
||||
setter.setInt(mScrimView, ScrimView.DRAG_HANDLE_ALPHA,
|
||||
(visibleElements & VERTICAL_SWIPE_INDICATOR) != 0 ? 255 : 0, allAppsFade);
|
||||
|
||||
// Set visibility of the container at the very beginning or end of the transition.
|
||||
setter.setViewAlpha(mAppsView, hasAnyVisibleItem ? 1 : 0,
|
||||
hasAnyVisibleItem ? INSTANT : FINAL_FRAME);
|
||||
}
|
||||
|
||||
public AnimatorListenerAdapter getProgressAnimatorListener() {
|
||||
return new AnimationSuccessListener() {
|
||||
@Override
|
||||
public void onAnimationSuccess(Animator animator) {
|
||||
onProgressAnimationEnd();
|
||||
}
|
||||
};
|
||||
return AnimationSuccessListener.forRunnable(this::onProgressAnimationEnd);
|
||||
}
|
||||
|
||||
public void setupViews(AllAppsContainerView appsView) {
|
||||
public void setupViews(AllAppsContainerView appsView, ScrimView scrimView) {
|
||||
mAppsView = appsView;
|
||||
mScrimView = mLauncher.findViewById(R.id.scrim_view);
|
||||
mScrimView = scrimView;
|
||||
PluginManagerWrapper.INSTANCE.get(mLauncher)
|
||||
.addPluginListener(this, AllAppsSearchPlugin.class, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -243,18 +251,48 @@ public class AllAppsTransitionController implements StateHandler, OnDeviceProfil
|
||||
private void onProgressAnimationEnd() {
|
||||
if (Float.compare(mProgress, 1f) == 0) {
|
||||
mAppsView.reset(false /* animate */);
|
||||
} else if (isAllAppsExpanded()) {
|
||||
mAppsView.onScrollUpEnd();
|
||||
}
|
||||
updatePluginAnimationEnd();
|
||||
}
|
||||
|
||||
private boolean isAllAppsExpanded() {
|
||||
return Float.compare(mProgress, 0f) == 0;
|
||||
@Override
|
||||
public void onPluginConnected(AllAppsSearchPlugin plugin, Context context) {
|
||||
mPlugin = plugin;
|
||||
mPluginContent = mLauncher.getLayoutInflater().inflate(
|
||||
R.layout.all_apps_content_layout, mAppsView, false);
|
||||
mAppsView.addView(mPluginContent);
|
||||
mPluginContent.setAlpha(0f);
|
||||
mPlugin.setup((ViewGroup) mPluginContent, mLauncher, mShiftRange);
|
||||
}
|
||||
|
||||
public void highlightWorkTabIfNecessary() {
|
||||
if (isAllAppsExpanded()) {
|
||||
mAppsView.highlightWorkTabIfNecessary();
|
||||
@Override
|
||||
public void onPluginDisconnected(AllAppsSearchPlugin plugin) {
|
||||
mPlugin = null;
|
||||
mAppsView.removeView(mPluginContent);
|
||||
}
|
||||
|
||||
public void onActivityDestroyed() {
|
||||
PluginManagerWrapper.INSTANCE.get(mLauncher).removePluginListener(this);
|
||||
}
|
||||
|
||||
/** Used for the plugin to signal when drag starts happens
|
||||
* @param toAllApps*/
|
||||
public void onDragStart(boolean toAllApps) {
|
||||
if (mPlugin == null) return;
|
||||
|
||||
if (toAllApps) {
|
||||
EditText editText = mAppsView.getSearchUiManager().setTextSearchEnabled(true);
|
||||
mPlugin.setEditText(editText);
|
||||
}
|
||||
mPlugin.onDragStart(toAllApps ? 1f : 0f);
|
||||
}
|
||||
|
||||
private void updatePluginAnimationEnd() {
|
||||
if (mPlugin == null) return;
|
||||
mPlugin.onAnimationEnd(mProgress);
|
||||
if (Float.compare(mProgress, 1f) == 0) {
|
||||
mAppsView.getSearchUiManager().setTextSearchEnabled(false);
|
||||
mPlugin.setEditText(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,13 +15,11 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
|
||||
import com.android.launcher3.AppInfo;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.shortcuts.DeepShortcutManager;
|
||||
import android.content.Context;
|
||||
|
||||
import com.android.launcher3.BaseDraggingActivity;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.util.ComponentKey;
|
||||
import com.android.launcher3.util.ItemInfoMatcher;
|
||||
import com.android.launcher3.util.LabelComparator;
|
||||
@@ -116,16 +114,9 @@ public class AlphabeticalAppsList implements AllAppsStore.OnUpdateListener {
|
||||
item.position = pos;
|
||||
return item;
|
||||
}
|
||||
|
||||
public static AdapterItem asWorkTabFooter(int pos) {
|
||||
AdapterItem item = new AdapterItem();
|
||||
item.viewType = AllAppsGridAdapter.VIEW_TYPE_WORK_TAB_FOOTER;
|
||||
item.position = pos;
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
private final Launcher mLauncher;
|
||||
private final BaseDraggingActivity mLauncher;
|
||||
|
||||
// The set of apps from the system
|
||||
private final List<AppInfo> mApps = new ArrayList<>();
|
||||
@@ -150,7 +141,7 @@ public class AlphabeticalAppsList implements AllAppsStore.OnUpdateListener {
|
||||
|
||||
public AlphabeticalAppsList(Context context, AllAppsStore appsStore, boolean isWork) {
|
||||
mAllAppsStore = appsStore;
|
||||
mLauncher = Launcher.getLauncher(context);
|
||||
mLauncher = BaseDraggingActivity.fromContext(context);
|
||||
mAppNameComparator = new AppInfoComparator(context);
|
||||
mIsWork = isWork;
|
||||
mNumAppsPerRow = mLauncher.getDeviceProfile().inv.numColumns;
|
||||
@@ -389,18 +380,6 @@ public class AlphabeticalAppsList implements AllAppsStore.OnUpdateListener {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Add the work profile footer if required.
|
||||
if (shouldShowWorkFooter()) {
|
||||
mAdapterItems.add(AdapterItem.asWorkTabFooter(position++));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldShowWorkFooter() {
|
||||
return mIsWork && Utilities.ATLEAST_P &&
|
||||
(DeepShortcutManager.getInstance(mLauncher).hasHostPermission()
|
||||
|| mLauncher.checkSelfPermission("android.permission.MODIFY_QUIET_MODE")
|
||||
== PackageManager.PERMISSION_GRANTED);
|
||||
}
|
||||
|
||||
private List<AppInfo> getFiltersAppInfos() {
|
||||
|
||||
@@ -19,8 +19,8 @@ import android.content.Context;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
|
||||
import com.android.launcher3.AppInfo;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.pm.UserCache;
|
||||
import com.android.launcher3.util.LabelComparator;
|
||||
|
||||
import java.util.Comparator;
|
||||
@@ -30,12 +30,12 @@ import java.util.Comparator;
|
||||
*/
|
||||
public class AppInfoComparator implements Comparator<AppInfo> {
|
||||
|
||||
private final UserManagerCompat mUserManager;
|
||||
private final UserCache mUserManager;
|
||||
private final UserHandle mMyUser;
|
||||
private final LabelComparator mLabelComparator;
|
||||
|
||||
public AppInfoComparator(Context context) {
|
||||
mUserManager = UserManagerCompat.getInstance(context);
|
||||
mUserManager = UserCache.INSTANCE.get(context);
|
||||
mMyUser = Process.myUserHandle();
|
||||
mLabelComparator = new LabelComparator();
|
||||
}
|
||||
|
||||
@@ -24,19 +24,18 @@ import static com.android.launcher3.userevent.nano.LauncherLogProto.ContainerTyp
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorInflater;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.Handler;
|
||||
import android.os.UserManager;
|
||||
import android.view.MotionEvent;
|
||||
|
||||
import com.android.launcher3.AbstractFloatingView;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.LauncherState;
|
||||
import com.android.launcher3.LauncherStateManager;
|
||||
import com.android.launcher3.LauncherStateManager.StateListener;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.states.InternalStateHandler;
|
||||
import com.android.launcher3.statemanager.StateManager.StateListener;
|
||||
import com.android.launcher3.touch.PagedOrientationHandler;
|
||||
import com.android.launcher3.util.OnboardingPrefs;
|
||||
|
||||
/**
|
||||
* Abstract base class of floating view responsible for showing discovery bounce animation
|
||||
@@ -45,17 +44,10 @@ public class DiscoveryBounce extends AbstractFloatingView {
|
||||
|
||||
private static final long DELAY_MS = 450;
|
||||
|
||||
public static final String HOME_BOUNCE_SEEN = "launcher.apps_view_shown";
|
||||
public static final String SHELF_BOUNCE_SEEN = "launcher.shelf_bounce_seen";
|
||||
public static final String HOME_BOUNCE_COUNT = "launcher.home_bounce_count";
|
||||
public static final String SHELF_BOUNCE_COUNT = "launcher.shelf_bounce_count";
|
||||
|
||||
public static final int BOUNCE_MAX_COUNT = 3;
|
||||
|
||||
private final Launcher mLauncher;
|
||||
private final Animator mDiscoBounceAnimation;
|
||||
|
||||
private final StateListener mStateListener = new StateListener() {
|
||||
private final StateListener<LauncherState> mStateListener = new StateListener<LauncherState>() {
|
||||
@Override
|
||||
public void onStateTransitionStart(LauncherState toState) {
|
||||
handleClose(false);
|
||||
@@ -144,11 +136,11 @@ public class DiscoveryBounce extends AbstractFloatingView {
|
||||
}
|
||||
|
||||
private static void showForHomeIfNeeded(Launcher launcher, boolean withDelay) {
|
||||
OnboardingPrefs onboardingPrefs = launcher.getOnboardingPrefs();
|
||||
if (!launcher.isInState(NORMAL)
|
||||
|| (launcher.getSharedPrefs().getBoolean(HOME_BOUNCE_SEEN, false)
|
||||
&& !shouldShowForWorkProfile(launcher))
|
||||
|| onboardingPrefs.getBoolean(OnboardingPrefs.HOME_BOUNCE_SEEN)
|
||||
|| AbstractFloatingView.getTopOpenView(launcher) != null
|
||||
|| UserManagerCompat.getInstance(launcher).isDemoUser()
|
||||
|| launcher.getSystemService(UserManager.class).isDemoUser()
|
||||
|| Utilities.IS_RUNNING_IN_TEST_HARNESS) {
|
||||
return;
|
||||
}
|
||||
@@ -157,36 +149,39 @@ public class DiscoveryBounce extends AbstractFloatingView {
|
||||
new Handler().postDelayed(() -> showForHomeIfNeeded(launcher, false), DELAY_MS);
|
||||
return;
|
||||
}
|
||||
incrementHomeBounceCount(launcher);
|
||||
onboardingPrefs.incrementEventCount(OnboardingPrefs.HOME_BOUNCE_COUNT);
|
||||
|
||||
new DiscoveryBounce(launcher, 0).show(HOTSEAT);
|
||||
}
|
||||
|
||||
public static void showForOverviewIfNeeded(Launcher launcher) {
|
||||
showForOverviewIfNeeded(launcher, true);
|
||||
public static void showForOverviewIfNeeded(Launcher launcher,
|
||||
PagedOrientationHandler orientationHandler) {
|
||||
showForOverviewIfNeeded(launcher, true, orientationHandler);
|
||||
}
|
||||
|
||||
private static void showForOverviewIfNeeded(Launcher launcher, boolean withDelay) {
|
||||
private static void showForOverviewIfNeeded(Launcher launcher, boolean withDelay,
|
||||
PagedOrientationHandler orientationHandler) {
|
||||
OnboardingPrefs onboardingPrefs = launcher.getOnboardingPrefs();
|
||||
if (!launcher.isInState(OVERVIEW)
|
||||
|| !launcher.hasBeenResumed()
|
||||
|| launcher.isForceInvisible()
|
||||
|| launcher.getDeviceProfile().isVerticalBarLayout()
|
||||
|| (launcher.getSharedPrefs().getBoolean(SHELF_BOUNCE_SEEN, false)
|
||||
&& !shouldShowForWorkProfile(launcher))
|
||||
|| UserManagerCompat.getInstance(launcher).isDemoUser()
|
||||
|| !orientationHandler.isLayoutNaturalToLauncher()
|
||||
|| onboardingPrefs.getBoolean(OnboardingPrefs.SHELF_BOUNCE_SEEN)
|
||||
|| launcher.getSystemService(UserManager.class).isDemoUser()
|
||||
|| Utilities.IS_RUNNING_IN_TEST_HARNESS) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (withDelay) {
|
||||
new Handler().postDelayed(() -> showForOverviewIfNeeded(launcher, false), DELAY_MS);
|
||||
new Handler().postDelayed(() -> showForOverviewIfNeeded(launcher, false,
|
||||
orientationHandler), DELAY_MS);
|
||||
return;
|
||||
} else if (InternalStateHandler.hasPending()
|
||||
|| AbstractFloatingView.getTopOpenView(launcher) != null) {
|
||||
} else if (AbstractFloatingView.getTopOpenView(launcher) != null) {
|
||||
// TODO: Move these checks to the top and call this method after invalidate handler.
|
||||
return;
|
||||
}
|
||||
incrementShelfBounceCount(launcher);
|
||||
onboardingPrefs.incrementEventCount(OnboardingPrefs.SHELF_BOUNCE_COUNT);
|
||||
|
||||
new DiscoveryBounce(launcher, (1 - OVERVIEW.getVerticalProgress(launcher)))
|
||||
.show(PREDICTION);
|
||||
@@ -213,28 +208,4 @@ public class DiscoveryBounce extends AbstractFloatingView {
|
||||
mController.setProgress(progress - mDelta);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean shouldShowForWorkProfile(Launcher launcher) {
|
||||
return !launcher.getSharedPrefs().getBoolean(
|
||||
PersonalWorkSlidingTabStrip.KEY_SHOWED_PEEK_WORK_TAB, false)
|
||||
&& UserManagerCompat.getInstance(launcher).hasWorkProfile();
|
||||
}
|
||||
|
||||
private static void incrementShelfBounceCount(Launcher launcher) {
|
||||
SharedPreferences sharedPrefs = launcher.getSharedPrefs();
|
||||
int count = sharedPrefs.getInt(SHELF_BOUNCE_COUNT, 0);
|
||||
if (count > BOUNCE_MAX_COUNT) {
|
||||
return;
|
||||
}
|
||||
sharedPrefs.edit().putInt(SHELF_BOUNCE_COUNT, count + 1).apply();
|
||||
}
|
||||
|
||||
private static void incrementHomeBounceCount(Launcher launcher) {
|
||||
SharedPreferences sharedPrefs = launcher.getSharedPrefs();
|
||||
int count = sharedPrefs.getInt(HOME_BOUNCE_COUNT, 0);
|
||||
if (count > BOUNCE_MAX_COUNT) {
|
||||
return;
|
||||
}
|
||||
sharedPrefs.edit().putInt(HOME_BOUNCE_COUNT, count + 1).apply();
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
|
||||
|
||||
import android.animation.ValueAnimator;
|
||||
import android.content.Context;
|
||||
import android.graphics.Point;
|
||||
@@ -31,9 +33,9 @@ import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import com.android.launcher3.BaseDraggingActivity;
|
||||
import com.android.launcher3.DeviceProfile;
|
||||
import com.android.launcher3.Insettable;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.anim.PropertySetter;
|
||||
import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
|
||||
@@ -370,7 +372,7 @@ public class FloatingHeaderView extends LinearLayout implements
|
||||
}
|
||||
|
||||
allowTouchForwarding(hasAllAppsContent);
|
||||
setter.setFloat(mTabLayout, ALPHA, hasAllAppsContent ? 1 : 0, headerFade);
|
||||
setter.setFloat(mTabLayout, VIEW_ALPHA, hasAllAppsContent ? 1 : 0, headerFade);
|
||||
}
|
||||
|
||||
protected void allowTouchForwarding(boolean allow) {
|
||||
@@ -393,7 +395,7 @@ public class FloatingHeaderView extends LinearLayout implements
|
||||
|
||||
@Override
|
||||
public void setInsets(Rect insets) {
|
||||
DeviceProfile grid = Launcher.getLauncher(getContext()).getDeviceProfile();
|
||||
DeviceProfile grid = BaseDraggingActivity.fromContext(getContext()).getDeviceProfile();
|
||||
for (FloatingHeaderRow row : mAllRows) {
|
||||
row.setInsets(insets, grid);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright (C) 2017 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.allapps;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Rect;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.MotionEvent;
|
||||
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.LauncherState;
|
||||
import com.android.launcher3.statemanager.StateManager.StateListener;
|
||||
import com.android.launcher3.views.WorkEduView;
|
||||
|
||||
/**
|
||||
* AllAppsContainerView with launcher specific callbacks
|
||||
*/
|
||||
public class LauncherAllAppsContainerView extends AllAppsContainerView {
|
||||
|
||||
private final Launcher mLauncher;
|
||||
|
||||
private StateListener<LauncherState> mWorkTabListener;
|
||||
|
||||
public LauncherAllAppsContainerView(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
public LauncherAllAppsContainerView(Context context, AttributeSet attrs) {
|
||||
this(context, attrs, 0);
|
||||
}
|
||||
|
||||
public LauncherAllAppsContainerView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
mLauncher = Launcher.getLauncher(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onInterceptTouchEvent(MotionEvent ev) {
|
||||
// The AllAppsContainerView houses the QSB and is hence visible from the Workspace
|
||||
// Overview states. We shouldn't intercept for the scrubber in these cases.
|
||||
if (!mLauncher.isInState(LauncherState.ALL_APPS)) {
|
||||
mTouchHandler = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
return super.onInterceptTouchEvent(ev);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent ev) {
|
||||
if (!mLauncher.isInState(LauncherState.ALL_APPS)) {
|
||||
return false;
|
||||
}
|
||||
return super.onTouchEvent(ev);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInsets(Rect insets) {
|
||||
super.setInsets(insets);
|
||||
mLauncher.getAllAppsController()
|
||||
.setScrollRangeDelta(mSearchUiManager.getScrollRangeDelta(insets));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setupHeader() {
|
||||
super.setupHeader();
|
||||
if (mWorkTabListener != null && !mUsingTabs) {
|
||||
mLauncher.getStateManager().removeStateListener(mWorkTabListener);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTabChanged(int pos) {
|
||||
super.onTabChanged(pos);
|
||||
if (mUsingTabs) {
|
||||
if (pos == AdapterHolder.WORK) {
|
||||
WorkEduView.showWorkEduIfNeeded(mLauncher);
|
||||
} else {
|
||||
mWorkTabListener = WorkEduView.showEduFlowIfNeeded(mLauncher, mWorkTabListener);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.util.AttributeSet;
|
||||
@@ -24,15 +23,14 @@ import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.LinearLayout;
|
||||
|
||||
import com.android.launcher3.Launcher;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.pageindicators.PageIndicator;
|
||||
import com.android.launcher3.util.Themes;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* Supports two indicator colors, dedicated for personal and work tabs.
|
||||
*/
|
||||
@@ -40,11 +38,8 @@ public class PersonalWorkSlidingTabStrip extends LinearLayout implements PageInd
|
||||
private static final int POSITION_PERSONAL = 0;
|
||||
private static final int POSITION_WORK = 1;
|
||||
|
||||
public static final String KEY_SHOWED_PEEK_WORK_TAB = "showed_peek_work_tab";
|
||||
|
||||
private final Paint mSelectedIndicatorPaint;
|
||||
private final Paint mDividerPaint;
|
||||
private final SharedPreferences mSharedPreferences;
|
||||
|
||||
private int mSelectedIndicatorHeight;
|
||||
private int mIndicatorLeft = -1;
|
||||
@@ -73,16 +68,13 @@ public class PersonalWorkSlidingTabStrip extends LinearLayout implements PageInd
|
||||
mDividerPaint.setStrokeWidth(
|
||||
getResources().getDimensionPixelSize(R.dimen.all_apps_divider_height));
|
||||
|
||||
mSharedPreferences = Launcher.getLauncher(getContext()).getSharedPrefs();
|
||||
mIsRtl = Utilities.isRtl(getResources());
|
||||
}
|
||||
|
||||
private void updateIndicatorPosition(float scrollOffset) {
|
||||
mScrollOffset = scrollOffset;
|
||||
updateIndicatorPosition();
|
||||
}
|
||||
|
||||
private void updateTabTextColor(int pos) {
|
||||
/**
|
||||
* Highlights tab with index pos
|
||||
*/
|
||||
public void updateTabTextColor(int pos) {
|
||||
mSelectedPosition = pos;
|
||||
for (int i = 0; i < getChildCount(); i++) {
|
||||
Button tab = (Button) getChildAt(i);
|
||||
@@ -90,6 +82,11 @@ public class PersonalWorkSlidingTabStrip extends LinearLayout implements PageInd
|
||||
}
|
||||
}
|
||||
|
||||
private void updateIndicatorPosition(float scrollOffset) {
|
||||
mScrollOffset = scrollOffset;
|
||||
updateIndicatorPosition();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onLayout(boolean changed, int l, int t, int r, int b) {
|
||||
super.onLayout(changed, l, t, r, b);
|
||||
@@ -129,25 +126,6 @@ public class PersonalWorkSlidingTabStrip extends LinearLayout implements PageInd
|
||||
mIndicatorRight, getHeight(), mSelectedIndicatorPaint);
|
||||
}
|
||||
|
||||
public void highlightWorkTabIfNecessary() {
|
||||
if (mSharedPreferences.getBoolean(KEY_SHOWED_PEEK_WORK_TAB, false)) {
|
||||
return;
|
||||
}
|
||||
if (mLastActivePage != POSITION_PERSONAL) {
|
||||
return;
|
||||
}
|
||||
highlightWorkTab();
|
||||
mSharedPreferences.edit().putBoolean(KEY_SHOWED_PEEK_WORK_TAB, true).apply();
|
||||
}
|
||||
|
||||
private void highlightWorkTab() {
|
||||
View v = getChildAt(POSITION_WORK);
|
||||
v.post(() -> {
|
||||
v.setPressed(true);
|
||||
v.setPressed(false);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setScroll(int currentScroll, int totalScroll) {
|
||||
float scrollOffset = ((float) currentScroll) / totalScroll;
|
||||
@@ -158,6 +136,7 @@ public class PersonalWorkSlidingTabStrip extends LinearLayout implements PageInd
|
||||
public void setActiveMarker(int activePage) {
|
||||
updateTabTextColor(activePage);
|
||||
if (mContainerView != null && mLastActivePage != activePage) {
|
||||
updateIndicatorPosition(activePage);
|
||||
mContainerView.onTabChanged(activePage);
|
||||
}
|
||||
mLastActivePage = activePage;
|
||||
|
||||
@@ -15,10 +15,11 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import static android.view.View.ALPHA;
|
||||
import static android.view.View.INVISIBLE;
|
||||
import static android.view.View.VISIBLE;
|
||||
|
||||
import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
|
||||
|
||||
import android.graphics.Rect;
|
||||
import android.view.View;
|
||||
import android.view.animation.Interpolator;
|
||||
@@ -67,7 +68,7 @@ public class PluginHeaderRow implements FloatingHeaderRow {
|
||||
public void setContentVisibility(boolean hasHeaderExtra, boolean hasAllAppsContent,
|
||||
PropertySetter setter, Interpolator headerFade, Interpolator allAppsFade) {
|
||||
// Don't use setViewAlpha as we want to control the visibility ourselves.
|
||||
setter.setFloat(mView, ALPHA, hasAllAppsContent ? 1 : 0, headerFade);
|
||||
setter.setFloat(mView, VIEW_ALPHA, hasAllAppsContent ? 1 : 0, headerFade);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -15,9 +15,14 @@
|
||||
*/
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import static com.android.launcher3.LauncherState.ALL_APPS_HEADER;
|
||||
|
||||
import android.graphics.Rect;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.animation.Interpolator;
|
||||
import android.widget.EditText;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.anim.PropertySetter;
|
||||
|
||||
@@ -52,4 +57,21 @@ public interface SearchUiManager {
|
||||
*/
|
||||
void setContentVisibility(int visibleElements, PropertySetter setter,
|
||||
Interpolator interpolator);
|
||||
|
||||
/**
|
||||
* Returns true if the QSB should be visible for the given set of visible elements
|
||||
*/
|
||||
default boolean isQsbVisible(int visibleElements) {
|
||||
return (visibleElements & ALL_APPS_HEADER) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to control how the search UI result should be handled.
|
||||
*
|
||||
* @param isEnabled when {@code true}, the search is all handled inside AOSP
|
||||
* and is not overlayable.
|
||||
* @return the searchbox edit text object
|
||||
*/
|
||||
@Nullable
|
||||
EditText setTextSearchEnabled(boolean isEnabled);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2018 The Android Open Source Project
|
||||
* 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.
|
||||
@@ -16,61 +16,124 @@
|
||||
package com.android.launcher3.allapps;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Rect;
|
||||
import android.os.AsyncTask;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
import android.os.UserManager;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.ViewConfiguration;
|
||||
import android.widget.Switch;
|
||||
|
||||
import com.android.launcher3.compat.UserManagerCompat;
|
||||
import com.android.launcher3.Insettable;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.pm.UserCache;
|
||||
import com.android.launcher3.views.ArrowTipView;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.List;
|
||||
|
||||
public class WorkModeSwitch extends Switch {
|
||||
/**
|
||||
* Work profile toggle switch shown at the bottom of AllApps work tab
|
||||
*/
|
||||
public class WorkModeSwitch extends Switch implements Insettable {
|
||||
|
||||
private static final int WORK_TIP_THRESHOLD = 2;
|
||||
public static final String KEY_WORK_TIP_COUNTER = "worked_tip_counter";
|
||||
|
||||
private Rect mInsets = new Rect();
|
||||
|
||||
private final float[] mTouch = new float[2];
|
||||
private int mTouchSlop;
|
||||
|
||||
public WorkModeSwitch(Context context) {
|
||||
super(context);
|
||||
init();
|
||||
}
|
||||
|
||||
public WorkModeSwitch(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init();
|
||||
}
|
||||
|
||||
public WorkModeSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() {
|
||||
ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());
|
||||
mTouchSlop = viewConfiguration.getScaledTouchSlop();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setChecked(boolean checked) {
|
||||
// No-op, do not change the checked state until broadcast is received.
|
||||
}
|
||||
public void setChecked(boolean checked) { }
|
||||
|
||||
@Override
|
||||
public void toggle() {
|
||||
// don't show tip if user uses toggle
|
||||
Utilities.getPrefs(getContext()).edit().putInt(KEY_WORK_TIP_COUNTER, -1).apply();
|
||||
trySetQuietModeEnabledToAllProfilesAsync(isChecked());
|
||||
}
|
||||
|
||||
private void setCheckedInternal(boolean checked) {
|
||||
super.setChecked(checked);
|
||||
}
|
||||
|
||||
public void refresh() {
|
||||
UserManagerCompat userManager = UserManagerCompat.getInstance(getContext());
|
||||
setCheckedInternal(!userManager.isAnyProfileQuietModeEnabled());
|
||||
/**
|
||||
* Sets the enabled or disabled state of the button
|
||||
* @param isChecked
|
||||
*/
|
||||
public void update(boolean isChecked) {
|
||||
super.setChecked(isChecked);
|
||||
setCompoundDrawablesRelativeWithIntrinsicBounds(
|
||||
isChecked ? R.drawable.ic_corp : R.drawable.ic_corp_off, 0, 0, 0);
|
||||
setEnabled(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent ev) {
|
||||
return ev.getActionMasked() == MotionEvent.ACTION_MOVE || super.onTouchEvent(ev);
|
||||
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
|
||||
mTouch[0] = ev.getX();
|
||||
mTouch[1] = ev.getY();
|
||||
} else if (ev.getActionMasked() == MotionEvent.ACTION_MOVE) {
|
||||
if (Math.abs(mTouch[0] - ev.getX()) > mTouchSlop
|
||||
|| Math.abs(mTouch[1] - ev.getY()) > mTouchSlop) {
|
||||
int action = ev.getAction();
|
||||
ev.setAction(MotionEvent.ACTION_CANCEL);
|
||||
super.onTouchEvent(ev);
|
||||
ev.setAction(action);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return super.onTouchEvent(ev);
|
||||
}
|
||||
|
||||
private void trySetQuietModeEnabledToAllProfilesAsync(boolean enabled) {
|
||||
new SetQuietModeEnabledAsyncTask(enabled, new WeakReference<>(this)).execute();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInsets(Rect insets) {
|
||||
int bottomInset = insets.bottom - mInsets.bottom;
|
||||
mInsets.set(insets);
|
||||
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
|
||||
getPaddingBottom() + bottomInset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Animates in/out work profile toggle panel based on the tab user is on
|
||||
*/
|
||||
public void setWorkTabVisible(boolean workTabVisible) {
|
||||
clearAnimation();
|
||||
if (workTabVisible) {
|
||||
setVisibility(VISIBLE);
|
||||
setAlpha(0);
|
||||
animate().alpha(1).start();
|
||||
showTipIfNeeded();
|
||||
} else {
|
||||
animate().alpha(0).withEndAction(() -> this.setVisibility(GONE)).start();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class SetQuietModeEnabledAsyncTask
|
||||
extends AsyncTask<Void, Void, Boolean> {
|
||||
|
||||
@@ -95,14 +158,14 @@ public class WorkModeSwitch extends Switch {
|
||||
@Override
|
||||
protected Boolean doInBackground(Void... voids) {
|
||||
WorkModeSwitch workModeSwitch = switchWeakReference.get();
|
||||
if (workModeSwitch == null) {
|
||||
if (workModeSwitch == null || !Utilities.ATLEAST_P) {
|
||||
return false;
|
||||
}
|
||||
UserManagerCompat userManager =
|
||||
UserManagerCompat.getInstance(workModeSwitch.getContext());
|
||||
List<UserHandle> userProfiles = userManager.getUserProfiles();
|
||||
|
||||
Context context = workModeSwitch.getContext();
|
||||
UserManager userManager = context.getSystemService(UserManager.class);
|
||||
boolean showConfirm = false;
|
||||
for (UserHandle userProfile : userProfiles) {
|
||||
for (UserHandle userProfile : UserCache.INSTANCE.get(context).getUserProfiles()) {
|
||||
if (Process.myUserHandle().equals(userProfile)) {
|
||||
continue;
|
||||
}
|
||||
@@ -121,4 +184,19 @@ public class WorkModeSwitch extends Switch {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a work tip on the Nth work tab open
|
||||
*/
|
||||
public void showTipIfNeeded() {
|
||||
Context context = getContext();
|
||||
SharedPreferences prefs = Utilities.getPrefs(context);
|
||||
int tipCounter = prefs.getInt(KEY_WORK_TIP_COUNTER, WORK_TIP_THRESHOLD);
|
||||
if (tipCounter < 0) return;
|
||||
if (tipCounter == 0) {
|
||||
new ArrowTipView(context)
|
||||
.show(context.getString(R.string.work_switch_tip), getTop());
|
||||
}
|
||||
prefs.edit().putInt(KEY_WORK_TIP_COUNTER, tipCounter - 1).apply();
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,8 @@ import android.view.inputmethod.EditorInfo;
|
||||
import android.widget.TextView;
|
||||
import android.widget.TextView.OnEditorActionListener;
|
||||
|
||||
import com.android.launcher3.BaseDraggingActivity;
|
||||
import com.android.launcher3.ExtendedEditText;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.model.AppLaunchTracker;
|
||||
import com.android.launcher3.util.ComponentKey;
|
||||
@@ -41,7 +41,7 @@ public class AllAppsSearchBarController
|
||||
implements TextWatcher, OnEditorActionListener, ExtendedEditText.OnBackKeyListener,
|
||||
OnFocusChangeListener {
|
||||
|
||||
protected Launcher mLauncher;
|
||||
protected BaseDraggingActivity mLauncher;
|
||||
protected Callbacks mCb;
|
||||
protected ExtendedEditText mInput;
|
||||
protected String mQuery;
|
||||
@@ -56,7 +56,7 @@ public class AllAppsSearchBarController
|
||||
*/
|
||||
public final void initialize(
|
||||
SearchAlgorithm searchAlgorithm, ExtendedEditText input,
|
||||
Launcher launcher, Callbacks cb) {
|
||||
BaseDraggingActivity launcher, Callbacks cb) {
|
||||
mCb = cb;
|
||||
mLauncher = launcher;
|
||||
|
||||
|
||||
@@ -19,15 +19,12 @@ import static android.view.View.MeasureSpec.EXACTLY;
|
||||
import static android.view.View.MeasureSpec.getSize;
|
||||
import static android.view.View.MeasureSpec.makeMeasureSpec;
|
||||
|
||||
import static com.android.launcher3.LauncherState.ALL_APPS_HEADER;
|
||||
import static com.android.launcher3.Utilities.prefixTextWithIcon;
|
||||
import static com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Rect;
|
||||
import android.text.Selection;
|
||||
import android.text.Spannable;
|
||||
import android.text.SpannableString;
|
||||
import android.text.SpannableStringBuilder;
|
||||
import android.text.method.TextKeyListener;
|
||||
import android.util.AttributeSet;
|
||||
@@ -35,19 +32,18 @@ import android.view.KeyEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup.MarginLayoutParams;
|
||||
import android.view.animation.Interpolator;
|
||||
import android.widget.EditText;
|
||||
|
||||
import com.android.launcher3.BaseDraggingActivity;
|
||||
import com.android.launcher3.DeviceProfile;
|
||||
import com.android.launcher3.ExtendedEditText;
|
||||
import com.android.launcher3.Insettable;
|
||||
import com.android.launcher3.Launcher;
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.allapps.AllAppsContainerView;
|
||||
import com.android.launcher3.allapps.AllAppsStore;
|
||||
import com.android.launcher3.allapps.AlphabeticalAppsList;
|
||||
import com.android.launcher3.allapps.SearchUiManager;
|
||||
import com.android.launcher3.anim.PropertySetter;
|
||||
import com.android.launcher3.graphics.TintedDrawableSpan;
|
||||
import com.android.launcher3.util.ComponentKey;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -59,17 +55,15 @@ public class AppsSearchContainerLayout extends ExtendedEditText
|
||||
implements SearchUiManager, AllAppsSearchBarController.Callbacks,
|
||||
AllAppsStore.OnUpdateListener, Insettable {
|
||||
|
||||
|
||||
private final Launcher mLauncher;
|
||||
private final BaseDraggingActivity mLauncher;
|
||||
private final AllAppsSearchBarController mSearchBarController;
|
||||
private final SpannableStringBuilder mSearchQueryBuilder;
|
||||
|
||||
private AlphabeticalAppsList mApps;
|
||||
private AllAppsContainerView mAppsView;
|
||||
|
||||
// This value was used to position the QSB. We store it here for translationY animations.
|
||||
private final float mFixedTranslationY;
|
||||
private final float mMarginTopAdjusting;
|
||||
// The amount of pixels to shift down and overlap with the rest of the content.
|
||||
private final int mContentOverlap;
|
||||
|
||||
public AppsSearchContainerLayout(Context context) {
|
||||
this(context, null);
|
||||
@@ -82,28 +76,27 @@ public class AppsSearchContainerLayout extends ExtendedEditText
|
||||
public AppsSearchContainerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
|
||||
mLauncher = Launcher.getLauncher(context);
|
||||
mLauncher = BaseDraggingActivity.fromContext(context);
|
||||
mSearchBarController = new AllAppsSearchBarController();
|
||||
|
||||
mSearchQueryBuilder = new SpannableStringBuilder();
|
||||
Selection.setSelection(mSearchQueryBuilder, 0);
|
||||
|
||||
mFixedTranslationY = getTranslationY();
|
||||
mMarginTopAdjusting = mFixedTranslationY - getPaddingTop();
|
||||
|
||||
setHint(prefixTextWithIcon(getContext(), R.drawable.ic_allapps_search, getHint()));
|
||||
|
||||
mContentOverlap =
|
||||
getResources().getDimensionPixelSize(R.dimen.all_apps_search_bar_field_height) / 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onAttachedToWindow() {
|
||||
super.onAttachedToWindow();
|
||||
mLauncher.getAppsView().getAppsStore().addUpdateListener(this);
|
||||
mAppsView.getAppsStore().addUpdateListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDetachedFromWindow() {
|
||||
super.onDetachedFromWindow();
|
||||
mLauncher.getAppsView().getAppsStore().removeUpdateListener(this);
|
||||
mAppsView.getAppsStore().removeUpdateListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -133,6 +126,8 @@ public class AppsSearchContainerLayout extends ExtendedEditText
|
||||
int expectedLeft = parent.getPaddingLeft() + (availableWidth - myWidth) / 2;
|
||||
int shift = expectedLeft - left;
|
||||
setTranslationX(shift);
|
||||
|
||||
offsetTopAndBottom(mContentOverlap);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -201,7 +196,7 @@ public class AppsSearchContainerLayout extends ExtendedEditText
|
||||
@Override
|
||||
public void setInsets(Rect insets) {
|
||||
MarginLayoutParams mlp = (MarginLayoutParams) getLayoutParams();
|
||||
mlp.topMargin = Math.round(Math.max(-mFixedTranslationY, insets.top - mMarginTopAdjusting));
|
||||
mlp.topMargin = insets.top;
|
||||
requestLayout();
|
||||
}
|
||||
|
||||
@@ -210,15 +205,18 @@ public class AppsSearchContainerLayout extends ExtendedEditText
|
||||
if (mLauncher.getDeviceProfile().isVerticalBarLayout()) {
|
||||
return 0;
|
||||
} else {
|
||||
int topMargin = Math.round(Math.max(
|
||||
-mFixedTranslationY, insets.top - mMarginTopAdjusting));
|
||||
return insets.bottom + topMargin + mFixedTranslationY;
|
||||
return insets.bottom + insets.top;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setContentVisibility(int visibleElements, PropertySetter setter,
|
||||
Interpolator interpolator) {
|
||||
setter.setViewAlpha(this, (visibleElements & ALL_APPS_HEADER) != 0 ? 1 : 0, interpolator);
|
||||
setter.setViewAlpha(this, isQsbVisible(visibleElements) ? 1 : 0, interpolator);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EditText setTextSearchEnabled(boolean isEnabled) {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ package com.android.launcher3.allapps.search;
|
||||
|
||||
import android.os.Handler;
|
||||
|
||||
import com.android.launcher3.AppInfo;
|
||||
import com.android.launcher3.model.data.AppInfo;
|
||||
import com.android.launcher3.util.ComponentKey;
|
||||
|
||||
import java.text.Collator;
|
||||
|
||||
@@ -39,4 +39,25 @@ public abstract class AnimationSuccessListener extends AnimatorListenerAdapter {
|
||||
}
|
||||
|
||||
public abstract void onAnimationSuccess(Animator animator);
|
||||
|
||||
/**
|
||||
* Returns an AnimationSuccessListener which runs the provided action on success
|
||||
*/
|
||||
public static AnimationSuccessListener forRunnable(Runnable r) {
|
||||
return new RunnableSuccessListener(r);
|
||||
}
|
||||
|
||||
private static class RunnableSuccessListener extends AnimationSuccessListener {
|
||||
|
||||
private final Runnable mRunnable;
|
||||
|
||||
private RunnableSuccessListener(Runnable r) {
|
||||
mRunnable = r;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationSuccess(Animator animator) {
|
||||
mRunnable.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,11 @@
|
||||
*/
|
||||
package com.android.launcher3.anim;
|
||||
|
||||
import static com.android.launcher3.Utilities.boundToRange;
|
||||
import static com.android.launcher3.anim.Interpolators.LINEAR;
|
||||
import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
|
||||
import static com.android.launcher3.anim.Interpolators.clampToProgress;
|
||||
import static com.android.launcher3.anim.Interpolators.scrollInterpolatorForVelocity;
|
||||
import static com.android.launcher3.util.DefaultDisplay.getSingleFrameMs;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.Animator.AnimatorListener;
|
||||
@@ -24,16 +27,15 @@ import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.AnimatorSet;
|
||||
import android.animation.TimeInterpolator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.util.Log;
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.dynamicanimation.animation.DynamicAnimation;
|
||||
import androidx.dynamicanimation.animation.SpringAnimation;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Helper class to control the playback of an {@link AnimatorSet}, with custom interpolators
|
||||
@@ -42,14 +44,7 @@ import java.util.Set;
|
||||
* Note: The implementation does not support start delays on child animations or
|
||||
* sequential playbacks.
|
||||
*/
|
||||
public abstract class AnimatorPlaybackController implements ValueAnimator.AnimatorUpdateListener {
|
||||
|
||||
private static final String TAG = "AnimatorPlaybackCtrler";
|
||||
private static boolean DEBUG = false;
|
||||
|
||||
public static AnimatorPlaybackController wrap(AnimatorSet anim, long duration) {
|
||||
return wrap(anim, duration, null);
|
||||
}
|
||||
public class AnimatorPlaybackController implements ValueAnimator.AnimatorUpdateListener {
|
||||
|
||||
/**
|
||||
* Creates an animation controller for the provided animation.
|
||||
@@ -57,20 +52,21 @@ public abstract class AnimatorPlaybackController implements ValueAnimator.Animat
|
||||
* needs to be larger than the total number of pixels so that we don't have jittering due
|
||||
* to float (animation-fraction * total duration) to int conversion.
|
||||
*/
|
||||
public static AnimatorPlaybackController wrap(AnimatorSet anim, long duration,
|
||||
Runnable onCancelRunnable) {
|
||||
public static AnimatorPlaybackController wrap(AnimatorSet anim, long duration) {
|
||||
ArrayList<Holder> childAnims = new ArrayList<>();
|
||||
addAnimationHoldersRecur(anim, duration, SpringProperty.DEFAULT, childAnims);
|
||||
|
||||
/**
|
||||
* TODO: use {@link AnimatorSet#setCurrentPlayTime(long)} once b/68382377 is fixed.
|
||||
*/
|
||||
return new AnimatorPlaybackControllerVL(anim, duration, onCancelRunnable);
|
||||
return new AnimatorPlaybackController(anim, duration, childAnims);
|
||||
}
|
||||
|
||||
// Progress factor after which an animation is considered almost completed.
|
||||
private static final float ANIMATION_COMPLETE_THRESHOLD = 0.95f;
|
||||
|
||||
private final ValueAnimator mAnimationPlayer;
|
||||
private final long mDuration;
|
||||
|
||||
protected final AnimatorSet mAnim;
|
||||
private Set<SpringAnimation> mSprings;
|
||||
private final AnimatorSet mAnim;
|
||||
private final Holder[] mChildAnimations;
|
||||
|
||||
protected float mCurrentFraction;
|
||||
private Runnable mEndAction;
|
||||
@@ -78,22 +74,14 @@ public abstract class AnimatorPlaybackController implements ValueAnimator.Animat
|
||||
protected boolean mTargetCancelled = false;
|
||||
protected Runnable mOnCancelRunnable;
|
||||
|
||||
private OnAnimationEndDispatcher mEndListener;
|
||||
private DynamicAnimation.OnAnimationEndListener mSpringEndListener;
|
||||
// We need this variable to ensure the end listener is called immediately, otherwise we run into
|
||||
// issues where the callback interferes with the states of the swipe detector.
|
||||
private boolean mSkipToEnd = false;
|
||||
|
||||
protected AnimatorPlaybackController(AnimatorSet anim, long duration,
|
||||
Runnable onCancelRunnable) {
|
||||
/** package private */
|
||||
AnimatorPlaybackController(AnimatorSet anim, long duration, ArrayList<Holder> childAnims) {
|
||||
mAnim = anim;
|
||||
mDuration = duration;
|
||||
mOnCancelRunnable = onCancelRunnable;
|
||||
|
||||
mAnimationPlayer = ValueAnimator.ofFloat(0, 1);
|
||||
mAnimationPlayer.setInterpolator(LINEAR);
|
||||
mEndListener = new OnAnimationEndDispatcher();
|
||||
mAnimationPlayer.addListener(mEndListener);
|
||||
mAnimationPlayer.addListener(new OnAnimationEndDispatcher());
|
||||
mAnimationPlayer.addUpdateListener(this);
|
||||
|
||||
mAnim.addListener(new AnimatorListenerAdapter() {
|
||||
@@ -118,14 +106,7 @@ public abstract class AnimatorPlaybackController implements ValueAnimator.Animat
|
||||
}
|
||||
});
|
||||
|
||||
mSprings = new HashSet<>();
|
||||
mSpringEndListener = (animation, canceled, value, velocity1) -> {
|
||||
if (canceled) {
|
||||
mEndListener.onAnimationCancel(mAnimationPlayer);
|
||||
} else {
|
||||
mEndListener.onAnimationEnd(mAnimationPlayer);
|
||||
}
|
||||
};
|
||||
mChildAnimations = childAnims.toArray(new Holder[childAnims.size()]);
|
||||
}
|
||||
|
||||
public AnimatorSet getTarget() {
|
||||
@@ -158,10 +139,80 @@ public abstract class AnimatorPlaybackController implements ValueAnimator.Animat
|
||||
mAnimationPlayer.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts playing the animation with the provided velocity optionally playing any
|
||||
* physics based animations
|
||||
*/
|
||||
public void startWithVelocity(Context context, boolean goingToEnd,
|
||||
float velocity, float scale, long animationDuration) {
|
||||
float scaleInverse = 1 / Math.abs(scale);
|
||||
float scaledVelocity = velocity * scaleInverse;
|
||||
|
||||
float nextFrameProgress = boundToRange(getProgressFraction()
|
||||
+ scaledVelocity * getSingleFrameMs(context), 0f, 1f);
|
||||
|
||||
// Update setters for spring
|
||||
int springFlag = goingToEnd
|
||||
? SpringProperty.FLAG_CAN_SPRING_ON_END
|
||||
: SpringProperty.FLAG_CAN_SPRING_ON_START;
|
||||
|
||||
long springDuration = animationDuration;
|
||||
for (Holder h : mChildAnimations) {
|
||||
if ((h.springProperty.flags & springFlag) != 0) {
|
||||
SpringAnimationBuilder s = new SpringAnimationBuilder(context)
|
||||
.setStartValue(mCurrentFraction)
|
||||
.setEndValue(goingToEnd ? 1 : 0)
|
||||
.setStartVelocity(scaledVelocity)
|
||||
.setMinimumVisibleChange(scaleInverse)
|
||||
.setDampingRatio(h.springProperty.mDampingRatio)
|
||||
.setStiffness(h.springProperty.mStiffness)
|
||||
.computeParams();
|
||||
|
||||
long expectedDurationL = s.getDuration();
|
||||
springDuration = Math.max(expectedDurationL, springDuration);
|
||||
|
||||
float expectedDuration = expectedDurationL;
|
||||
h.mapper = (progress, globalEndProgress) ->
|
||||
mAnimationPlayer.getCurrentPlayTime() / expectedDuration;
|
||||
h.anim.setInterpolator(s::getInterpolatedValue);
|
||||
}
|
||||
}
|
||||
|
||||
mAnimationPlayer.setFloatValues(nextFrameProgress, goingToEnd ? 1f : 0f);
|
||||
|
||||
if (springDuration <= animationDuration) {
|
||||
mAnimationPlayer.setDuration(animationDuration);
|
||||
mAnimationPlayer.setInterpolator(scrollInterpolatorForVelocity(velocity));
|
||||
} else {
|
||||
// Since spring requires more time to run, we let the other animations play with
|
||||
// current time and interpolation and by clamping the duration.
|
||||
mAnimationPlayer.setDuration(springDuration);
|
||||
|
||||
float cutOff = animationDuration / (float) springDuration;
|
||||
mAnimationPlayer.setInterpolator(
|
||||
clampToProgress(scrollInterpolatorForVelocity(velocity), 0, cutOff));
|
||||
}
|
||||
mAnimationPlayer.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to finish the running animation if it is close to completion.
|
||||
*/
|
||||
public void forceFinishIfCloseToEnd() {
|
||||
if (mAnimationPlayer.isRunning()
|
||||
&& mAnimationPlayer.getAnimatedFraction() > ANIMATION_COMPLETE_THRESHOLD) {
|
||||
mAnimationPlayer.end();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pauses the currently playing animation.
|
||||
*/
|
||||
public void pause() {
|
||||
// Reset property setters
|
||||
for (Holder h : mChildAnimations) {
|
||||
h.reset();
|
||||
}
|
||||
mAnimationPlayer.cancel();
|
||||
}
|
||||
|
||||
@@ -175,7 +226,18 @@ public abstract class AnimatorPlaybackController implements ValueAnimator.Animat
|
||||
/**
|
||||
* Sets the current animation position and updates all the child animators accordingly.
|
||||
*/
|
||||
public abstract void setPlayFraction(float fraction);
|
||||
public void setPlayFraction(float fraction) {
|
||||
mCurrentFraction = fraction;
|
||||
// Let the animator report the progress but don't apply the progress to child
|
||||
// animations if it has been cancelled.
|
||||
if (mTargetCancelled) {
|
||||
return;
|
||||
}
|
||||
float progress = boundToRange(fraction, 0, 1);
|
||||
for (Holder holder : mChildAnimations) {
|
||||
holder.setProgress(progress);
|
||||
}
|
||||
}
|
||||
|
||||
public float getProgressFraction() {
|
||||
return mCurrentFraction;
|
||||
@@ -207,169 +269,68 @@ public abstract class AnimatorPlaybackController implements ValueAnimator.Animat
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts playback and sets the spring.
|
||||
*/
|
||||
public void dispatchOnStartWithVelocity(float end, float velocity) {
|
||||
if (!QUICKSTEP_SPRINGS.get()) {
|
||||
dispatchOnStart();
|
||||
return;
|
||||
}
|
||||
|
||||
if (DEBUG) Log.d(TAG, "dispatchOnStartWithVelocity#end=" + end + ", velocity=" + velocity);
|
||||
|
||||
for (Animator a : mAnim.getChildAnimations()) {
|
||||
if (a instanceof SpringObjectAnimator) {
|
||||
if (DEBUG) Log.d(TAG, "Found springAnimator=" + a);
|
||||
SpringObjectAnimator springAnimator = (SpringObjectAnimator) a;
|
||||
mSprings.add(springAnimator.getSpring());
|
||||
springAnimator.startSpring(end, velocity, mSpringEndListener);
|
||||
}
|
||||
}
|
||||
|
||||
dispatchOnStart();
|
||||
}
|
||||
|
||||
public void dispatchOnStart() {
|
||||
dispatchOnStartRecursively(mAnim);
|
||||
}
|
||||
|
||||
private void dispatchOnStartRecursively(Animator animator) {
|
||||
List<AnimatorListener> listeners = animator instanceof SpringObjectAnimator
|
||||
? nonNullList(((SpringObjectAnimator) animator).getObjectAnimatorListeners())
|
||||
: nonNullList(animator.getListeners());
|
||||
|
||||
for (AnimatorListener l : listeners) {
|
||||
l.onAnimationStart(animator);
|
||||
}
|
||||
|
||||
if (animator instanceof AnimatorSet) {
|
||||
for (Animator anim : nonNullList(((AnimatorSet) animator).getChildAnimations())) {
|
||||
dispatchOnStartRecursively(anim);
|
||||
}
|
||||
}
|
||||
/** @see #dispatchOnCancelWithoutCancelRunnable(Runnable) */
|
||||
public void dispatchOnCancelWithoutCancelRunnable() {
|
||||
dispatchOnCancelWithoutCancelRunnable(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets mOnCancelRunnable = null before dispatching the cancel and restoring the runnable. This
|
||||
* is intended to be used only if you need to cancel but want to defer cleaning up yourself.
|
||||
* @param callback An optional callback to run after dispatching the cancel but before resetting
|
||||
* the onCancelRunnable.
|
||||
*/
|
||||
public void dispatchOnCancelWithoutCancelRunnable() {
|
||||
public void dispatchOnCancelWithoutCancelRunnable(@Nullable Runnable callback) {
|
||||
Runnable onCancel = mOnCancelRunnable;
|
||||
setOnCancelRunnable(null);
|
||||
dispatchOnCancel();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
setOnCancelRunnable(onCancel);
|
||||
}
|
||||
|
||||
public void dispatchOnCancel() {
|
||||
dispatchOnCancelRecursively(mAnim);
|
||||
|
||||
public AnimatorPlaybackController setOnCancelRunnable(Runnable runnable) {
|
||||
mOnCancelRunnable = runnable;
|
||||
return this;
|
||||
}
|
||||
|
||||
private void dispatchOnCancelRecursively(Animator animator) {
|
||||
for (AnimatorListener l : nonNullList(animator.getListeners())) {
|
||||
l.onAnimationCancel(animator);
|
||||
}
|
||||
public void dispatchOnStart() {
|
||||
callListenerCommandRecursively(mAnim, AnimatorListener::onAnimationStart);
|
||||
}
|
||||
|
||||
if (animator instanceof AnimatorSet) {
|
||||
for (Animator anim : nonNullList(((AnimatorSet) animator).getChildAnimations())) {
|
||||
dispatchOnCancelRecursively(anim);
|
||||
}
|
||||
}
|
||||
public void dispatchOnCancel() {
|
||||
callListenerCommandRecursively(mAnim, AnimatorListener::onAnimationCancel);
|
||||
}
|
||||
|
||||
public void dispatchSetInterpolator(TimeInterpolator interpolator) {
|
||||
dispatchSetInterpolatorRecursively(mAnim, interpolator);
|
||||
callAnimatorCommandRecursively(mAnim, a -> a.setInterpolator(interpolator));
|
||||
}
|
||||
|
||||
private void dispatchSetInterpolatorRecursively(Animator anim, TimeInterpolator interpolator) {
|
||||
anim.setInterpolator(interpolator);
|
||||
private static void callListenerCommandRecursively(
|
||||
Animator anim, BiConsumer<AnimatorListener, Animator> command) {
|
||||
callAnimatorCommandRecursively(anim, a-> {
|
||||
for (AnimatorListener l : nonNullList(a.getListeners())) {
|
||||
command.accept(l, a);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void callAnimatorCommandRecursively(Animator anim, Consumer<Animator> command) {
|
||||
command.accept(anim);
|
||||
if (anim instanceof AnimatorSet) {
|
||||
for (Animator child : nonNullList(((AnimatorSet) anim).getChildAnimations())) {
|
||||
dispatchSetInterpolatorRecursively(child, interpolator);
|
||||
callAnimatorCommandRecursively(child, command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setOnCancelRunnable(Runnable runnable) {
|
||||
mOnCancelRunnable = runnable;
|
||||
}
|
||||
|
||||
public void skipToEnd() {
|
||||
mSkipToEnd = true;
|
||||
for (SpringAnimation spring : mSprings) {
|
||||
if (spring.canSkipToEnd()) {
|
||||
spring.skipToEnd();
|
||||
}
|
||||
}
|
||||
mAnimationPlayer.end();
|
||||
mSkipToEnd = false;
|
||||
}
|
||||
|
||||
public static class AnimatorPlaybackControllerVL extends AnimatorPlaybackController {
|
||||
|
||||
private final ValueAnimator[] mChildAnimations;
|
||||
|
||||
private AnimatorPlaybackControllerVL(AnimatorSet anim, long duration,
|
||||
Runnable onCancelRunnable) {
|
||||
super(anim, duration, onCancelRunnable);
|
||||
|
||||
// Build animation list
|
||||
ArrayList<ValueAnimator> childAnims = new ArrayList<>();
|
||||
getAnimationsRecur(mAnim, childAnims);
|
||||
mChildAnimations = childAnims.toArray(new ValueAnimator[childAnims.size()]);
|
||||
}
|
||||
|
||||
private void getAnimationsRecur(AnimatorSet anim, ArrayList<ValueAnimator> out) {
|
||||
long forceDuration = anim.getDuration();
|
||||
TimeInterpolator forceInterpolator = anim.getInterpolator();
|
||||
for (Animator child : anim.getChildAnimations()) {
|
||||
if (forceDuration > 0) {
|
||||
child.setDuration(forceDuration);
|
||||
}
|
||||
if (forceInterpolator != null) {
|
||||
child.setInterpolator(forceInterpolator);
|
||||
}
|
||||
if (child instanceof ValueAnimator) {
|
||||
out.add((ValueAnimator) child);
|
||||
} else if (child instanceof AnimatorSet) {
|
||||
getAnimationsRecur((AnimatorSet) child, out);
|
||||
} else {
|
||||
throw new RuntimeException("Unknown animation type " + child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPlayFraction(float fraction) {
|
||||
mCurrentFraction = fraction;
|
||||
// Let the animator report the progress but don't apply the progress to child
|
||||
// animations if it has been cancelled.
|
||||
if (mTargetCancelled) {
|
||||
return;
|
||||
}
|
||||
long playPos = clampDuration(fraction);
|
||||
for (ValueAnimator anim : mChildAnimations) {
|
||||
anim.setCurrentPlayTime(Math.min(playPos, anim.getDuration()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isAnySpringRunning() {
|
||||
for (SpringAnimation spring : mSprings) {
|
||||
if (spring.isRunning()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only dispatches the on end actions once the animator and all springs have completed running.
|
||||
*/
|
||||
private class OnAnimationEndDispatcher extends AnimationSuccessListener {
|
||||
|
||||
boolean mAnimatorDone = false;
|
||||
boolean mSpringsDone = false;
|
||||
boolean mDispatched = false;
|
||||
|
||||
@Override
|
||||
@@ -380,39 +341,83 @@ public abstract class AnimatorPlaybackController implements ValueAnimator.Animat
|
||||
|
||||
@Override
|
||||
public void onAnimationSuccess(Animator animator) {
|
||||
if (mSprings.isEmpty()) {
|
||||
mSpringsDone = mAnimatorDone = true;
|
||||
}
|
||||
if (isAnySpringRunning()) {
|
||||
mAnimatorDone = true;
|
||||
} else {
|
||||
mSpringsDone = true;
|
||||
}
|
||||
|
||||
// We wait for the spring (if any) to finish running before completing the end callback.
|
||||
if (!mDispatched && (mSkipToEnd || (mAnimatorDone && mSpringsDone))) {
|
||||
dispatchOnEndRecursively(mAnim);
|
||||
if (!mDispatched) {
|
||||
callListenerCommandRecursively(mAnim, AnimatorListener::onAnimationEnd);
|
||||
if (mEndAction != null) {
|
||||
mEndAction.run();
|
||||
}
|
||||
mDispatched = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void dispatchOnEndRecursively(Animator animator) {
|
||||
for (AnimatorListener l : nonNullList(animator.getListeners())) {
|
||||
l.onAnimationEnd(animator);
|
||||
}
|
||||
|
||||
if (animator instanceof AnimatorSet) {
|
||||
for (Animator anim : nonNullList(((AnimatorSet) animator).getChildAnimations())) {
|
||||
dispatchOnEndRecursively(anim);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> List<T> nonNullList(ArrayList<T> list) {
|
||||
return list == null ? Collections.emptyList() : list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for mapping progress to animation progress
|
||||
*/
|
||||
private interface ProgressMapper {
|
||||
|
||||
ProgressMapper DEFAULT = (progress, globalEndProgress) ->
|
||||
progress > globalEndProgress ? 1 : (progress / globalEndProgress);
|
||||
|
||||
float getProgress(float progress, float globalProgress);
|
||||
}
|
||||
|
||||
/**
|
||||
* Holder class for various child animations
|
||||
*/
|
||||
static class Holder {
|
||||
|
||||
public final ValueAnimator anim;
|
||||
|
||||
public final SpringProperty springProperty;
|
||||
|
||||
public final TimeInterpolator interpolator;
|
||||
|
||||
public final float globalEndProgress;
|
||||
|
||||
public ProgressMapper mapper;
|
||||
|
||||
Holder(Animator anim, float globalDuration, SpringProperty springProperty) {
|
||||
this.anim = (ValueAnimator) anim;
|
||||
this.springProperty = springProperty;
|
||||
this.interpolator = this.anim.getInterpolator();
|
||||
this.globalEndProgress = anim.getDuration() / globalDuration;
|
||||
this.mapper = ProgressMapper.DEFAULT;
|
||||
}
|
||||
|
||||
public void setProgress(float progress) {
|
||||
anim.setCurrentFraction(mapper.getProgress(progress, globalEndProgress));
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
anim.setInterpolator(interpolator);
|
||||
mapper = ProgressMapper.DEFAULT;
|
||||
}
|
||||
}
|
||||
|
||||
static void addAnimationHoldersRecur(Animator anim, long globalDuration,
|
||||
SpringProperty springProperty, ArrayList<Holder> out) {
|
||||
long forceDuration = anim.getDuration();
|
||||
TimeInterpolator forceInterpolator = anim.getInterpolator();
|
||||
if (anim instanceof ValueAnimator) {
|
||||
out.add(new Holder(anim, globalDuration, springProperty));
|
||||
} else if (anim instanceof AnimatorSet) {
|
||||
for (Animator child : ((AnimatorSet) anim).getChildAnimations()) {
|
||||
if (forceDuration > 0) {
|
||||
child.setDuration(forceDuration);
|
||||
}
|
||||
if (forceInterpolator != null) {
|
||||
child.setInterpolator(forceInterpolator);
|
||||
}
|
||||
addAnimationHoldersRecur(child, globalDuration, springProperty, out);
|
||||
}
|
||||
} else {
|
||||
throw new RuntimeException("Unknown animation type " + anim);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2017 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.anim;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorSet;
|
||||
import android.util.SparseArray;
|
||||
import android.view.animation.Interpolator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Utility class for building animator set
|
||||
*/
|
||||
public class AnimatorSetBuilder {
|
||||
|
||||
public static final int ANIM_VERTICAL_PROGRESS = 0;
|
||||
public static final int ANIM_WORKSPACE_SCALE = 1;
|
||||
public static final int ANIM_WORKSPACE_TRANSLATE = 2;
|
||||
public static final int ANIM_WORKSPACE_FADE = 3;
|
||||
public static final int ANIM_HOTSEAT_SCALE = 4;
|
||||
public static final int ANIM_HOTSEAT_TRANSLATE = 5;
|
||||
public static final int ANIM_OVERVIEW_SCALE = 6;
|
||||
public static final int ANIM_OVERVIEW_TRANSLATE_X = 7;
|
||||
public static final int ANIM_OVERVIEW_TRANSLATE_Y = 8;
|
||||
public static final int ANIM_OVERVIEW_FADE = 9;
|
||||
public static final int ANIM_ALL_APPS_FADE = 10;
|
||||
public static final int ANIM_OVERVIEW_SCRIM_FADE = 11;
|
||||
public static final int ANIM_ALL_APPS_HEADER_FADE = 12; // e.g. predictions
|
||||
|
||||
public static final int FLAG_DONT_ANIMATE_OVERVIEW = 1 << 0;
|
||||
|
||||
protected final ArrayList<Animator> mAnims = new ArrayList<>();
|
||||
|
||||
private final SparseArray<Interpolator> mInterpolators = new SparseArray<>();
|
||||
private List<Runnable> mOnFinishRunnables = new ArrayList<>();
|
||||
private int mFlags = 0;
|
||||
|
||||
public void play(Animator anim) {
|
||||
mAnims.add(anim);
|
||||
}
|
||||
|
||||
public void addOnFinishRunnable(Runnable onFinishRunnable) {
|
||||
mOnFinishRunnables.add(onFinishRunnable);
|
||||
}
|
||||
|
||||
public AnimatorSet build() {
|
||||
AnimatorSet anim = new AnimatorSet();
|
||||
anim.playTogether(mAnims);
|
||||
if (!mOnFinishRunnables.isEmpty()) {
|
||||
anim.addListener(new AnimationSuccessListener() {
|
||||
@Override
|
||||
public void onAnimationSuccess(Animator animation) {
|
||||
for (Runnable onFinishRunnable : mOnFinishRunnables) {
|
||||
onFinishRunnable.run();
|
||||
}
|
||||
mOnFinishRunnables.clear();
|
||||
}
|
||||
});
|
||||
}
|
||||
return anim;
|
||||
}
|
||||
|
||||
public Interpolator getInterpolator(int animId, Interpolator fallback) {
|
||||
return mInterpolators.get(animId, fallback);
|
||||
}
|
||||
|
||||
public void setInterpolator(int animId, Interpolator interpolator) {
|
||||
mInterpolators.put(animId, interpolator);
|
||||
}
|
||||
|
||||
public void addFlag(int flag) {
|
||||
mFlags |= flag;
|
||||
}
|
||||
|
||||
public boolean hasFlag(int flag) {
|
||||
return (mFlags & flag) != 0;
|
||||
}
|
||||
}
|
||||
@@ -15,32 +15,41 @@
|
||||
*/
|
||||
package com.android.launcher3.anim;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.dynamicanimation.animation.DynamicAnimation.OnAnimationEndListener;
|
||||
import androidx.dynamicanimation.animation.FlingAnimation;
|
||||
import androidx.dynamicanimation.animation.FloatPropertyCompat;
|
||||
import androidx.dynamicanimation.animation.SpringAnimation;
|
||||
import androidx.dynamicanimation.animation.SpringForce;
|
||||
|
||||
import com.android.launcher3.R;
|
||||
import com.android.launcher3.util.DynamicResource;
|
||||
import com.android.systemui.plugins.ResourceProvider;
|
||||
|
||||
/**
|
||||
* Given a property to animate and a target value and starting velocity, first apply friction to
|
||||
* the fling until we pass the target, then apply a spring force to pull towards the target.
|
||||
*/
|
||||
public class FlingSpringAnim {
|
||||
|
||||
private static final float FLING_FRICTION = 1.5f;
|
||||
private static final float SPRING_STIFFNESS = 200;
|
||||
private static final float SPRING_DAMPING = 0.8f;
|
||||
|
||||
private final FlingAnimation mFlingAnim;
|
||||
private SpringAnimation mSpringAnim;
|
||||
private final boolean mSkipFlingAnim;
|
||||
|
||||
private float mTargetPosition;
|
||||
|
||||
public <K> FlingSpringAnim(K object, FloatPropertyCompat<K> property, float startPosition,
|
||||
float targetPosition, float startVelocity, float minVisChange, float minValue,
|
||||
float maxValue, float springVelocityFactor, OnAnimationEndListener onEndListener) {
|
||||
public <K> FlingSpringAnim(K object, Context context, FloatPropertyCompat<K> property,
|
||||
float startPosition, float targetPosition, float startVelocity, float minVisChange,
|
||||
float minValue, float maxValue, float springVelocityFactor,
|
||||
OnAnimationEndListener onEndListener) {
|
||||
ResourceProvider rp = DynamicResource.provider(context);
|
||||
float damping = rp.getFloat(R.dimen.swipe_up_rect_xy_damping_ratio);
|
||||
float stiffness = rp.getFloat(R.dimen.swipe_up_rect_xy_stiffness);
|
||||
float friction = rp.getFloat(R.dimen.swipe_up_rect_xy_fling_friction);
|
||||
|
||||
mFlingAnim = new FlingAnimation(object, property)
|
||||
.setFriction(FLING_FRICTION)
|
||||
.setFriction(friction)
|
||||
// Have the spring pull towards the target if we've slowed down too much before
|
||||
// reaching it.
|
||||
.setMinimumVisibleChange(minVisChange)
|
||||
@@ -49,13 +58,17 @@ public class FlingSpringAnim {
|
||||
.setMaxValue(maxValue);
|
||||
mTargetPosition = targetPosition;
|
||||
|
||||
// We are already past the fling target, so skip it to avoid losing a frame of the spring.
|
||||
mSkipFlingAnim = startPosition <= minValue && startVelocity < 0
|
||||
|| startPosition >= maxValue && startVelocity > 0;
|
||||
|
||||
mFlingAnim.addEndListener(((animation, canceled, value, velocity) -> {
|
||||
mSpringAnim = new SpringAnimation(object, property)
|
||||
.setStartValue(value)
|
||||
.setStartVelocity(velocity * springVelocityFactor)
|
||||
.setSpring(new SpringForce(mTargetPosition)
|
||||
.setStiffness(SPRING_STIFFNESS)
|
||||
.setDampingRatio(SPRING_DAMPING));
|
||||
.setStiffness(stiffness)
|
||||
.setDampingRatio(damping));
|
||||
mSpringAnim.addEndListener(onEndListener);
|
||||
mSpringAnim.animateToFinalPosition(mTargetPosition);
|
||||
}));
|
||||
@@ -76,6 +89,9 @@ public class FlingSpringAnim {
|
||||
|
||||
public void start() {
|
||||
mFlingAnim.start();
|
||||
if (mSkipFlingAnim) {
|
||||
mFlingAnim.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
public void end() {
|
||||
|
||||
@@ -61,6 +61,11 @@ public class Interpolators {
|
||||
public static final Interpolator EXAGGERATED_EASE;
|
||||
|
||||
public static final Interpolator INSTANT = t -> 1;
|
||||
/**
|
||||
* All values of t map to 0 until t == 1. This is primarily useful for setting view visibility,
|
||||
* which should only happen at the very end of the animation (when it's already hidden).
|
||||
*/
|
||||
public static final Interpolator FINAL_FRAME = t -> t < 1 ? 0 : 1;
|
||||
|
||||
private static final int MIN_SETTLE_DURATION = 200;
|
||||
private static final float OVERSHOOT_FACTOR = 0.9f;
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright (C) 2018 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.anim;
|
||||
|
||||
import static com.android.launcher3.anim.AnimatorPlaybackController.addAnimationHoldersRecur;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.Animator.AnimatorListener;
|
||||
import android.animation.AnimatorSet;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.TimeInterpolator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.util.FloatProperty;
|
||||
import android.util.IntProperty;
|
||||
import android.view.View;
|
||||
|
||||
import com.android.launcher3.anim.AnimatorPlaybackController.Holder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Utility class to keep track of a running animation.
|
||||
*
|
||||
* This class allows attaching end callbacks to an animation is intended to be used with
|
||||
* {@link com.android.launcher3.anim.AnimatorPlaybackController}, since in that case
|
||||
* AnimationListeners are not properly dispatched.
|
||||
*
|
||||
* TODO: Find a better name
|
||||
*/
|
||||
public class PendingAnimation implements PropertySetter {
|
||||
|
||||
private final ArrayList<Consumer<EndState>> mEndListeners = new ArrayList<>();
|
||||
|
||||
private final ArrayList<Holder> mAnimHolders = new ArrayList<>();
|
||||
private final AnimatorSet mAnim;
|
||||
private final long mDuration;
|
||||
|
||||
private ValueAnimator mProgressAnimator;
|
||||
|
||||
public PendingAnimation(long duration) {
|
||||
mDuration = duration;
|
||||
mAnim = new AnimatorSet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method to sent an interpolator on an animation and add it to the list
|
||||
*/
|
||||
public void add(Animator anim, TimeInterpolator interpolator, SpringProperty springProperty) {
|
||||
anim.setInterpolator(interpolator);
|
||||
add(anim, springProperty);
|
||||
}
|
||||
|
||||
public void add(Animator anim) {
|
||||
add(anim, SpringProperty.DEFAULT);
|
||||
}
|
||||
|
||||
public void add(Animator a, SpringProperty springProperty) {
|
||||
mAnim.play(a.setDuration(mDuration));
|
||||
addAnimationHoldersRecur(a, mDuration, springProperty, mAnimHolders);
|
||||
}
|
||||
|
||||
public void finish(boolean isSuccess, int logAction) {
|
||||
for (Consumer<EndState> listeners : mEndListeners) {
|
||||
listeners.accept(new EndState(isSuccess, logAction));
|
||||
}
|
||||
mEndListeners.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setViewAlpha(View view, float alpha, TimeInterpolator interpolator) {
|
||||
if (view == null || view.getAlpha() == alpha) {
|
||||
return;
|
||||
}
|
||||
ObjectAnimator anim = ObjectAnimator.ofFloat(view, View.ALPHA, alpha);
|
||||
anim.addListener(new AlphaUpdateListener(view));
|
||||
anim.setInterpolator(interpolator);
|
||||
add(anim);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setFloat(T target, FloatProperty<T> property, float value,
|
||||
TimeInterpolator interpolator) {
|
||||
if (property.get(target) == value) {
|
||||
return;
|
||||
}
|
||||
Animator anim = ObjectAnimator.ofFloat(target, property, value);
|
||||
anim.setDuration(mDuration).setInterpolator(interpolator);
|
||||
add(anim);
|
||||
}
|
||||
|
||||
public <T> void addFloat(T target, FloatProperty<T> property, float from, float to,
|
||||
TimeInterpolator interpolator) {
|
||||
Animator anim = ObjectAnimator.ofFloat(target, property, from, to);
|
||||
anim.setInterpolator(interpolator);
|
||||
add(anim);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setInt(T target, IntProperty<T> property, int value,
|
||||
TimeInterpolator interpolator) {
|
||||
if (property.get(target) == value) {
|
||||
return;
|
||||
}
|
||||
Animator anim = ObjectAnimator.ofInt(target, property, value);
|
||||
anim.setInterpolator(interpolator);
|
||||
add(anim);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a callback to be run on every frame of the animation
|
||||
*/
|
||||
public void addOnFrameCallback(Runnable runnable) {
|
||||
if (mProgressAnimator == null) {
|
||||
mProgressAnimator = ValueAnimator.ofFloat(0, 1);
|
||||
}
|
||||
|
||||
mProgressAnimator.addUpdateListener(anim -> runnable.run());
|
||||
}
|
||||
|
||||
/**
|
||||
* @see AnimatorSet#addListener(AnimatorListener)
|
||||
*/
|
||||
public void addListener(Animator.AnimatorListener listener) {
|
||||
mAnim.addListener(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns the underlying AnimatorSet
|
||||
*/
|
||||
public AnimatorSet buildAnim() {
|
||||
// Add progress animation to the end, so that frame callback is called after all the other
|
||||
// animation update.
|
||||
if (mProgressAnimator != null) {
|
||||
add(mProgressAnimator);
|
||||
mProgressAnimator = null;
|
||||
}
|
||||
if (mAnimHolders.isEmpty()) {
|
||||
// Add a dummy animation to that the duration is respected
|
||||
add(ValueAnimator.ofFloat(0, 1).setDuration(mDuration));
|
||||
}
|
||||
return mAnim;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a controller for this animation
|
||||
*/
|
||||
public AnimatorPlaybackController createPlaybackController() {
|
||||
return new AnimatorPlaybackController(buildAnim(), mDuration, mAnimHolders);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a listener of receiving the end state.
|
||||
* Note that the listeners are called as a result of calling {@link #finish(boolean, int)}
|
||||
* and not automatically
|
||||
*/
|
||||
public void addEndListener(Consumer<EndState> listener) {
|
||||
mEndListeners.add(listener);
|
||||
}
|
||||
|
||||
public static class EndState {
|
||||
public boolean isSuccess;
|
||||
public int logAction;
|
||||
|
||||
public EndState(boolean isSuccess, int logAction) {
|
||||
this.isSuccess = isSuccess;
|
||||
this.logAction = logAction;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,77 +16,43 @@
|
||||
|
||||
package com.android.launcher3.anim;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.TimeInterpolator;
|
||||
import android.util.Property;
|
||||
import android.util.FloatProperty;
|
||||
import android.util.IntProperty;
|
||||
import android.view.View;
|
||||
|
||||
/**
|
||||
* Utility class for setting a property with or without animation
|
||||
*/
|
||||
public class PropertySetter {
|
||||
public interface PropertySetter {
|
||||
|
||||
public static final PropertySetter NO_ANIM_PROPERTY_SETTER = new PropertySetter();
|
||||
PropertySetter NO_ANIM_PROPERTY_SETTER = new PropertySetter() { };
|
||||
|
||||
public void setViewAlpha(View view, float alpha, TimeInterpolator interpolator) {
|
||||
/**
|
||||
* Sets the view alpha using the provided interpolator.
|
||||
* Unlike {@link #setFloat}, this also updates the visibility of the view as alpha changes
|
||||
* between zero and non-zero.
|
||||
*/
|
||||
default void setViewAlpha(View view, float alpha, TimeInterpolator interpolator) {
|
||||
if (view != null) {
|
||||
view.setAlpha(alpha);
|
||||
AlphaUpdateListener.updateVisibility(view);
|
||||
}
|
||||
}
|
||||
|
||||
public <T> void setFloat(T target, Property<T, Float> property, float value,
|
||||
/**
|
||||
* Updates the float property of the target using the provided interpolator
|
||||
*/
|
||||
default <T> void setFloat(T target, FloatProperty<T> property, float value,
|
||||
TimeInterpolator interpolator) {
|
||||
property.set(target, value);
|
||||
property.setValue(target, value);
|
||||
}
|
||||
|
||||
public <T> void setInt(T target, Property<T, Integer> property, int value,
|
||||
/**
|
||||
* Updates the int property of the target using the provided interpolator
|
||||
*/
|
||||
default <T> void setInt(T target, IntProperty<T> property, int value,
|
||||
TimeInterpolator interpolator) {
|
||||
property.set(target, value);
|
||||
}
|
||||
|
||||
public static class AnimatedPropertySetter extends PropertySetter {
|
||||
|
||||
private final long mDuration;
|
||||
private final AnimatorSetBuilder mStateAnimator;
|
||||
|
||||
public AnimatedPropertySetter(long duration, AnimatorSetBuilder builder) {
|
||||
mDuration = duration;
|
||||
mStateAnimator = builder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setViewAlpha(View view, float alpha, TimeInterpolator interpolator) {
|
||||
if (view == null || view.getAlpha() == alpha) {
|
||||
return;
|
||||
}
|
||||
ObjectAnimator anim = ObjectAnimator.ofFloat(view, View.ALPHA, alpha);
|
||||
anim.addListener(new AlphaUpdateListener(view));
|
||||
anim.setDuration(mDuration).setInterpolator(interpolator);
|
||||
mStateAnimator.play(anim);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setFloat(T target, Property<T, Float> property, float value,
|
||||
TimeInterpolator interpolator) {
|
||||
if (property.get(target) == value) {
|
||||
return;
|
||||
}
|
||||
Animator anim = ObjectAnimator.ofFloat(target, property, value);
|
||||
anim.setDuration(mDuration).setInterpolator(interpolator);
|
||||
mStateAnimator.play(anim);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void setInt(T target, Property<T, Integer> property, int value,
|
||||
TimeInterpolator interpolator) {
|
||||
if (property.get(target) == value) {
|
||||
return;
|
||||
}
|
||||
Animator anim = ObjectAnimator.ofInt(target, property, value);
|
||||
anim.setDuration(mDuration).setInterpolator(interpolator);
|
||||
mStateAnimator.play(anim);
|
||||
}
|
||||
property.setValue(target, value);
|
||||
}
|
||||
}
|
||||
@@ -15,24 +15,25 @@
|
||||
*/
|
||||
package com.android.launcher3.anim;
|
||||
|
||||
import static com.android.launcher3.anim.Interpolators.LINEAR;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.content.Context;
|
||||
import android.util.FloatProperty;
|
||||
|
||||
import com.android.launcher3.util.DefaultDisplay;
|
||||
|
||||
import androidx.annotation.FloatRange;
|
||||
import androidx.dynamicanimation.animation.SpringForce;
|
||||
|
||||
import com.android.launcher3.util.DefaultDisplay;
|
||||
|
||||
/**
|
||||
* Utility class to build an object animator which follows the same path as a spring animation for
|
||||
* an underdamped spring.
|
||||
*/
|
||||
public class SpringAnimationBuilder<T> extends FloatProperty<T> {
|
||||
public class SpringAnimationBuilder {
|
||||
|
||||
private final T mTarget;
|
||||
private final FloatProperty<T> mProperty;
|
||||
private final Context mContext;
|
||||
|
||||
private float mStartValue;
|
||||
private float mEndValue;
|
||||
@@ -65,27 +66,23 @@ public class SpringAnimationBuilder<T> extends FloatProperty<T> {
|
||||
private double mValueThreshold;
|
||||
private double mVelocityThreshold;
|
||||
|
||||
private float mCurrentTime = 0;
|
||||
private float mDuration = 0;
|
||||
|
||||
public SpringAnimationBuilder(T target, FloatProperty<T> property) {
|
||||
super("dynamic-spring-property");
|
||||
mTarget = target;
|
||||
mProperty = property;
|
||||
|
||||
mStartValue = mProperty.get(target);
|
||||
public SpringAnimationBuilder(Context context) {
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
public SpringAnimationBuilder<T> setEndValue(float value) {
|
||||
public SpringAnimationBuilder setEndValue(float value) {
|
||||
mEndValue = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SpringAnimationBuilder<T> setStartValue(float value) {
|
||||
public SpringAnimationBuilder setStartValue(float value) {
|
||||
mStartValue = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SpringAnimationBuilder<T> setValues(float... values) {
|
||||
public SpringAnimationBuilder setValues(float... values) {
|
||||
if (values.length > 1) {
|
||||
mStartValue = values[0];
|
||||
mEndValue = values[values.length - 1];
|
||||
@@ -95,7 +92,7 @@ public class SpringAnimationBuilder<T> extends FloatProperty<T> {
|
||||
return this;
|
||||
}
|
||||
|
||||
public SpringAnimationBuilder<T> setStiffness(
|
||||
public SpringAnimationBuilder setStiffness(
|
||||
@FloatRange(from = 0.0, fromInclusive = false) float stiffness) {
|
||||
if (stiffness <= 0) {
|
||||
throw new IllegalArgumentException("Spring stiffness constant must be positive.");
|
||||
@@ -104,7 +101,7 @@ public class SpringAnimationBuilder<T> extends FloatProperty<T> {
|
||||
return this;
|
||||
}
|
||||
|
||||
public SpringAnimationBuilder<T> setDampingRatio(
|
||||
public SpringAnimationBuilder setDampingRatio(
|
||||
@FloatRange(from = 0.0, to = 1.0, fromInclusive = false, toInclusive = false)
|
||||
float dampingRatio) {
|
||||
if (dampingRatio <= 0 || dampingRatio >= 1) {
|
||||
@@ -114,7 +111,7 @@ public class SpringAnimationBuilder<T> extends FloatProperty<T> {
|
||||
return this;
|
||||
}
|
||||
|
||||
public SpringAnimationBuilder<T> setMinimumVisibleChange(
|
||||
public SpringAnimationBuilder setMinimumVisibleChange(
|
||||
@FloatRange(from = 0.0, fromInclusive = false) float minimumVisibleChange) {
|
||||
if (minimumVisibleChange <= 0) {
|
||||
throw new IllegalArgumentException("Minimum visible change must be positive.");
|
||||
@@ -123,25 +120,21 @@ public class SpringAnimationBuilder<T> extends FloatProperty<T> {
|
||||
return this;
|
||||
}
|
||||
|
||||
public SpringAnimationBuilder<T> setStartVelocity(float startVelocity) {
|
||||
public SpringAnimationBuilder setStartVelocity(float startVelocity) {
|
||||
mVelocity = startVelocity;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValue(T object, float time) {
|
||||
mCurrentTime = time;
|
||||
mProperty.setValue(
|
||||
object, (float) (exponentialComponent(time) * cosSinX(time)) + mEndValue);
|
||||
public float getInterpolatedValue(float fraction) {
|
||||
return getValue(mDuration * fraction);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Float get(T t) {
|
||||
return mCurrentTime;
|
||||
private float getValue(float time) {
|
||||
return (float) (exponentialComponent(time) * cosSinX(time)) + mEndValue;
|
||||
}
|
||||
|
||||
public ObjectAnimator build(Context context) {
|
||||
int singleFrameMs = DefaultDisplay.getSingleFrameMs(context);
|
||||
public SpringAnimationBuilder computeParams() {
|
||||
int singleFrameMs = DefaultDisplay.getSingleFrameMs(mContext);
|
||||
double naturalFreq = Math.sqrt(mStiffness);
|
||||
double dampedFreq = naturalFreq * Math.sqrt(1 - mDampingRatio * mDampingRatio);
|
||||
|
||||
@@ -188,14 +181,25 @@ public class SpringAnimationBuilder<T> extends FloatProperty<T> {
|
||||
}
|
||||
} while (true);
|
||||
|
||||
mDuration = (float) duration;
|
||||
return this;
|
||||
}
|
||||
|
||||
long durationMs = (long) (1000.0 * duration);
|
||||
ObjectAnimator animator = ObjectAnimator.ofFloat(mTarget, this, 0, (float) duration);
|
||||
animator.setDuration(durationMs).setInterpolator(Interpolators.LINEAR);
|
||||
public long getDuration() {
|
||||
return (long) (1000.0 * mDuration);
|
||||
}
|
||||
|
||||
public <T> ValueAnimator build(T target, FloatProperty<T> property) {
|
||||
computeParams();
|
||||
|
||||
ValueAnimator animator = ValueAnimator.ofFloat(0, mDuration);
|
||||
animator.setDuration(getDuration()).setInterpolator(LINEAR);
|
||||
animator.addUpdateListener(anim ->
|
||||
property.set(target, getInterpolatedValue(anim.getAnimatedFraction())));
|
||||
animator.addListener(new AnimationSuccessListener() {
|
||||
@Override
|
||||
public void onAnimationSuccess(Animator animator) {
|
||||
mProperty.setValue(mTarget, mEndValue);
|
||||
public void onAnimationSuccess(Animator animation) {
|
||||
property.set(target, mEndValue);
|
||||
}
|
||||
});
|
||||
return animator;
|
||||
|
||||
@@ -1,305 +0,0 @@
|
||||
/*
|
||||
* 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.launcher3.anim;
|
||||
|
||||
import static androidx.dynamicanimation.animation.FloatPropertyCompat.createFloatPropertyCompat;
|
||||
|
||||
import static com.android.launcher3.config.FeatureFlags.QUICKSTEP_SPRINGS;
|
||||
|
||||
import android.animation.Animator;
|
||||
import android.animation.AnimatorListenerAdapter;
|
||||
import android.animation.ObjectAnimator;
|
||||
import android.animation.TimeInterpolator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.FloatProperty;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import androidx.dynamicanimation.animation.DynamicAnimation.OnAnimationEndListener;
|
||||
import androidx.dynamicanimation.animation.SpringAnimation;
|
||||
import androidx.dynamicanimation.animation.SpringForce;
|
||||
|
||||
/**
|
||||
* This animator allows for an object's property to be be controlled by an {@link ObjectAnimator} or
|
||||
* a {@link SpringAnimation}. It extends ValueAnimator so it can be used in an AnimatorSet.
|
||||
*/
|
||||
public class SpringObjectAnimator<T> extends ValueAnimator {
|
||||
|
||||
private static final String TAG = "SpringObjectAnimator";
|
||||
private static boolean DEBUG = false;
|
||||
|
||||
private ObjectAnimator mObjectAnimator;
|
||||
private float[] mValues;
|
||||
|
||||
private SpringAnimation mSpring;
|
||||
private SpringProperty<T> mProperty;
|
||||
|
||||
private ArrayList<AnimatorListener> mListeners;
|
||||
private boolean mSpringEnded = true;
|
||||
private boolean mAnimatorEnded = true;
|
||||
private boolean mEnded = true;
|
||||
|
||||
public SpringObjectAnimator(T object, FloatProperty<T> property, float minimumVisibleChange,
|
||||
float damping, float stiffness, float... values) {
|
||||
mSpring = new SpringAnimation(object, createFloatPropertyCompat(property));
|
||||
mSpring.setMinimumVisibleChange(minimumVisibleChange);
|
||||
mSpring.setSpring(new SpringForce(0)
|
||||
.setDampingRatio(damping)
|
||||
.setStiffness(stiffness));
|
||||
mSpring.setStartVelocity(0.01f);
|
||||
mProperty = new SpringProperty<>(property, mSpring);
|
||||
mObjectAnimator = ObjectAnimator.ofFloat(object, mProperty, values);
|
||||
mValues = values;
|
||||
mListeners = new ArrayList<>();
|
||||
setFloatValues(values);
|
||||
|
||||
// We use this listener and track mListeners so that we can sync the animator and spring
|
||||
// listeners.
|
||||
mObjectAnimator.addListener(new AnimatorListenerAdapter() {
|
||||
@Override
|
||||
public void onAnimationStart(Animator animation) {
|
||||
mAnimatorEnded = false;
|
||||
mEnded = false;
|
||||
for (AnimatorListener l : mListeners) {
|
||||
l.onAnimationStart(animation);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationEnd(Animator animation) {
|
||||
mAnimatorEnded = true;
|
||||
tryEnding();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAnimationCancel(Animator animation) {
|
||||
for (AnimatorListener l : mListeners) {
|
||||
l.onAnimationCancel(animation);
|
||||
}
|
||||
mSpring.cancel();
|
||||
}
|
||||
});
|
||||
|
||||
mSpring.addUpdateListener((animation, value, velocity) -> {
|
||||
mSpringEnded = false;
|
||||
mEnded = false;
|
||||
});
|
||||
mSpring.addEndListener((animation, canceled, value, velocity) -> {
|
||||
mSpringEnded = true;
|
||||
tryEnding();
|
||||
});
|
||||
}
|
||||
|
||||
private void tryEnding() {
|
||||
if (DEBUG) {
|
||||
Log.d(TAG, "tryEnding#mAnimatorEnded=" + mAnimatorEnded + ", mSpringEnded="
|
||||
+ mSpringEnded + ", mEnded=" + mEnded);
|
||||
}
|
||||
|
||||
// If springs are disabled, ignore value of mSpringEnded
|
||||
if (mAnimatorEnded && (mSpringEnded || !QUICKSTEP_SPRINGS.get()) && !mEnded) {
|
||||
for (AnimatorListener l : mListeners) {
|
||||
l.onAnimationEnd(this);
|
||||
}
|
||||
mEnded = true;
|
||||
}
|
||||
}
|
||||
|
||||
public SpringAnimation getSpring() {
|
||||
return mSpring;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes and sets up the spring to take over controlling the object.
|
||||
*/
|
||||
public void startSpring(float end, float velocity, OnAnimationEndListener endListener) {
|
||||
// Cancel the spring so we can set new start velocity and final position. We need to remove
|
||||
// the listener since the spring is not actually ending.
|
||||
mSpring.removeEndListener(endListener);
|
||||
mSpring.cancel();
|
||||
mSpring.addEndListener(endListener);
|
||||
|
||||
mProperty.switchToSpring();
|
||||
|
||||
mSpring.setStartVelocity(velocity);
|
||||
|
||||
float startValue = end == 0 ? mValues[1] : mValues[0];
|
||||
float endValue = end == 0 ? mValues[0] : mValues[1];
|
||||
mSpring.setStartValue(startValue);
|
||||
new Handler(Looper.getMainLooper()).postDelayed(() -> {
|
||||
mSpring.animateToFinalPosition(endValue);
|
||||
}, getStartDelay());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addListener(AnimatorListener listener) {
|
||||
mListeners.add(listener);
|
||||
}
|
||||
|
||||
public ArrayList<AnimatorListener> getObjectAnimatorListeners() {
|
||||
return mObjectAnimator.getListeners();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArrayList<AnimatorListener> getListeners() {
|
||||
return mListeners;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAllListeners() {
|
||||
mListeners.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeListener(AnimatorListener listener) {
|
||||
mListeners.remove(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addPauseListener(AnimatorPauseListener listener) {
|
||||
mObjectAnimator.addPauseListener(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
mObjectAnimator.cancel();
|
||||
mSpring.cancel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void end() {
|
||||
mObjectAnimator.end();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getDuration() {
|
||||
return mObjectAnimator.getDuration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TimeInterpolator getInterpolator() {
|
||||
return mObjectAnimator.getInterpolator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getStartDelay() {
|
||||
return mObjectAnimator.getStartDelay();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getTotalDuration() {
|
||||
return mObjectAnimator.getTotalDuration();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPaused() {
|
||||
return mObjectAnimator.isPaused();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
return mObjectAnimator.isRunning();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isStarted() {
|
||||
return mObjectAnimator.isStarted();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pause() {
|
||||
mObjectAnimator.pause();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removePauseListener(AnimatorPauseListener listener) {
|
||||
mObjectAnimator.removePauseListener(listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resume() {
|
||||
mObjectAnimator.resume();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ValueAnimator setDuration(long duration) {
|
||||
return mObjectAnimator.setDuration(duration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setInterpolator(TimeInterpolator value) {
|
||||
mObjectAnimator.setInterpolator(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStartDelay(long startDelay) {
|
||||
mObjectAnimator.setStartDelay(startDelay);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTarget(Object target) {
|
||||
mObjectAnimator.setTarget(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
mObjectAnimator.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCurrentFraction(float fraction) {
|
||||
mObjectAnimator.setCurrentFraction(fraction);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCurrentPlayTime(long playTime) {
|
||||
mObjectAnimator.setCurrentPlayTime(playTime);
|
||||
}
|
||||
|
||||
public static class SpringProperty<T> extends FloatProperty<T> {
|
||||
|
||||
boolean useSpring = false;
|
||||
final FloatProperty<T> mProperty;
|
||||
final SpringAnimation mSpring;
|
||||
|
||||
public SpringProperty(FloatProperty<T> property, SpringAnimation spring) {
|
||||
super(property.getName());
|
||||
mProperty = property;
|
||||
mSpring = spring;
|
||||
}
|
||||
|
||||
public void switchToSpring() {
|
||||
useSpring = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Float get(T object) {
|
||||
return mProperty.get(object);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValue(T object, float progress) {
|
||||
if (useSpring) {
|
||||
mSpring.animateToFinalPosition(progress);
|
||||
} else {
|
||||
mProperty.setValue(object, progress);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* 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.anim;
|
||||
|
||||
import androidx.dynamicanimation.animation.SpringForce;
|
||||
|
||||
/**
|
||||
* Utility class to store configurations for spring animation
|
||||
*/
|
||||
public class SpringProperty {
|
||||
|
||||
public static final SpringProperty DEFAULT = new SpringProperty();
|
||||
|
||||
// Play spring when the animation is going towards the end
|
||||
public static final int FLAG_CAN_SPRING_ON_END = 1 << 0;
|
||||
// Play spring when animation is going towards the start (in reverse direction)
|
||||
public static final int FLAG_CAN_SPRING_ON_START = 1 << 1;
|
||||
|
||||
public final int flags;
|
||||
|
||||
float mDampingRatio = SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY;
|
||||
float mStiffness = SpringForce.STIFFNESS_MEDIUM;
|
||||
|
||||
public SpringProperty() {
|
||||
this(0);
|
||||
}
|
||||
|
||||
public SpringProperty(int flags) {
|
||||
this.flags = flags;
|
||||
}
|
||||
|
||||
public SpringProperty setDampingRatio(float dampingRatio) {
|
||||
mDampingRatio = dampingRatio;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SpringProperty setStiffness(float stiffness) {
|
||||
mStiffness = stiffness;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -18,15 +18,16 @@ package com.android.launcher3.compat;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Bundle;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.view.accessibility.AccessibilityEvent;
|
||||
import android.view.accessibility.AccessibilityManager;
|
||||
import android.view.accessibility.AccessibilityNodeInfo;
|
||||
|
||||
import com.android.launcher3.testing.TestProtocol;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.Utilities;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import com.android.launcher3.testing.TestProtocol;
|
||||
|
||||
public class AccessibilityManagerCompat {
|
||||
|
||||
@@ -39,11 +40,21 @@ public class AccessibilityManagerCompat {
|
||||
return isAccessibilityEnabled(context);
|
||||
}
|
||||
|
||||
public static void sendCustomAccessibilityEvent(View target, int type, String text) {
|
||||
if (isObservedEventType(target.getContext(), type)) {
|
||||
/**
|
||||
*
|
||||
* @param target The view the accessibility event is initialized on.
|
||||
* If null, this method has no effect.
|
||||
* @param type See TYPE_ constants defined in {@link AccessibilityEvent}.
|
||||
* @param text Optional text to add to the event, which will be announced to the user.
|
||||
*/
|
||||
public static void sendCustomAccessibilityEvent(@Nullable View target, int type,
|
||||
@Nullable String text) {
|
||||
if (target != null && isObservedEventType(target.getContext(), type)) {
|
||||
AccessibilityEvent event = AccessibilityEvent.obtain(type);
|
||||
target.onInitializeAccessibilityEvent(event);
|
||||
event.getText().add(text);
|
||||
if (!TextUtils.isEmpty(text)) {
|
||||
event.getText().add(text);
|
||||
}
|
||||
getManager(target.getContext()).sendAccessibilityEvent(event);
|
||||
}
|
||||
}
|
||||
@@ -60,6 +71,7 @@ public class AccessibilityManagerCompat {
|
||||
parcel.putInt(TestProtocol.STATE_FIELD, stateOrdinal);
|
||||
|
||||
sendEventToTest(accessibilityManager, TestProtocol.SWITCHED_TO_STATE_MESSAGE, parcel);
|
||||
Log.d(TestProtocol.PERMANENT_DIAG_TAG, "sendStateEventToTest: " + stateOrdinal);
|
||||
}
|
||||
|
||||
public static void sendScrollFinishedEventToTest(Context context) {
|
||||
@@ -103,24 +115,6 @@ public class AccessibilityManagerCompat {
|
||||
return accessibilityManager;
|
||||
}
|
||||
|
||||
public static boolean processTestRequest(Context context, String eventTag, int action,
|
||||
Bundle request, Consumer<Bundle> responseFiller) {
|
||||
final AccessibilityManager accessibilityManager = getAccessibilityManagerForTest(context);
|
||||
if (accessibilityManager == null) return false;
|
||||
|
||||
// The test sends a request via a ACTION_SET_TEXT.
|
||||
if (action == AccessibilityNodeInfo.ACTION_SET_TEXT &&
|
||||
eventTag.equals(request.getCharSequence(
|
||||
AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE))) {
|
||||
final Bundle response = new Bundle();
|
||||
responseFiller.accept(response);
|
||||
AccessibilityManagerCompat.sendEventToTest(
|
||||
accessibilityManager, eventTag + TestProtocol.RESPONSE_MESSAGE_POSTFIX, response);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static int getRecommendedTimeoutMillis(Context context, int originalTimeout, int flags) {
|
||||
if (Utilities.ATLEAST_Q) {
|
||||
return getManager(context).getRecommendedTimeoutMillis(originalTimeout, flags);
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.compat;
|
||||
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.appwidget.AppWidgetProviderInfo;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.os.Bundle;
|
||||
import android.os.UserHandle;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.LauncherAppWidgetProviderInfo;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.util.ComponentKey;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
import com.android.launcher3.widget.custom.CustomWidgetManager;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class AppWidgetManagerCompat {
|
||||
|
||||
private static final Object sInstanceLock = new Object();
|
||||
private static AppWidgetManagerCompat sInstance;
|
||||
|
||||
public static AppWidgetManagerCompat getInstance(Context context) {
|
||||
synchronized (sInstanceLock) {
|
||||
if (sInstance == null) {
|
||||
if (Utilities.ATLEAST_OREO) {
|
||||
sInstance = new AppWidgetManagerCompatVO(context.getApplicationContext());
|
||||
} else {
|
||||
sInstance = new AppWidgetManagerCompatVL(context.getApplicationContext());
|
||||
}
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
}
|
||||
|
||||
final AppWidgetManager mAppWidgetManager;
|
||||
final Context mContext;
|
||||
|
||||
AppWidgetManagerCompat(Context context) {
|
||||
mContext = context;
|
||||
mAppWidgetManager = AppWidgetManager.getInstance(context);
|
||||
}
|
||||
|
||||
public LauncherAppWidgetProviderInfo getLauncherAppWidgetInfo(int appWidgetId) {
|
||||
if (appWidgetId <= LauncherAppWidgetInfo.CUSTOM_WIDGET_ID) {
|
||||
return CustomWidgetManager.INSTANCE.get(mContext).getWidgetProvider(appWidgetId);
|
||||
}
|
||||
AppWidgetProviderInfo info = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
|
||||
return info == null ? null : LauncherAppWidgetProviderInfo.fromProviderInfo(mContext, info);
|
||||
}
|
||||
|
||||
public abstract List<AppWidgetProviderInfo> getAllProviders(
|
||||
@Nullable PackageUserKey packageUser);
|
||||
|
||||
public abstract boolean bindAppWidgetIdIfAllowed(
|
||||
int appWidgetId, AppWidgetProviderInfo info, Bundle options);
|
||||
|
||||
public abstract LauncherAppWidgetProviderInfo findProvider(
|
||||
ComponentName provider, UserHandle user);
|
||||
|
||||
public abstract HashMap<ComponentKey, AppWidgetProviderInfo> getAllProvidersMap();
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.compat;
|
||||
|
||||
import android.appwidget.AppWidgetProviderInfo;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.os.Bundle;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
import android.os.UserManager;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.LauncherAppWidgetInfo;
|
||||
import com.android.launcher3.LauncherAppWidgetProviderInfo;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.util.ComponentKey;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
import com.android.launcher3.widget.custom.CustomAppWidgetProviderInfo;
|
||||
import com.android.launcher3.widget.custom.CustomWidgetManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
class AppWidgetManagerCompatVL extends AppWidgetManagerCompat {
|
||||
|
||||
private final UserManager mUserManager;
|
||||
|
||||
AppWidgetManagerCompatVL(Context context) {
|
||||
super(context);
|
||||
mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AppWidgetProviderInfo> getAllProviders(@Nullable PackageUserKey packageUser) {
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
if (packageUser == null) {
|
||||
ArrayList<AppWidgetProviderInfo> providers = new ArrayList<>();
|
||||
for (UserHandle user : mUserManager.getUserProfiles()) {
|
||||
providers.addAll(mAppWidgetManager.getInstalledProvidersForProfile(user));
|
||||
}
|
||||
providers.addAll(getCustomWidgets());
|
||||
return providers;
|
||||
}
|
||||
// Only get providers for the given package/user.
|
||||
List<AppWidgetProviderInfo> providers = new ArrayList<>(mAppWidgetManager
|
||||
.getInstalledProvidersForProfile(packageUser.mUser));
|
||||
Iterator<AppWidgetProviderInfo> iterator = providers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (!iterator.next().provider.getPackageName().equals(packageUser.mPackageName)) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
if (Process.myUserHandle().equals(packageUser.mUser)
|
||||
&& mContext.getPackageName().equals(packageUser.mPackageName)) {
|
||||
providers.addAll(getCustomWidgets());
|
||||
}
|
||||
return providers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean bindAppWidgetIdIfAllowed(int appWidgetId, AppWidgetProviderInfo info,
|
||||
Bundle options) {
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
return false;
|
||||
}
|
||||
if (appWidgetId <= LauncherAppWidgetInfo.CUSTOM_WIDGET_ID) {
|
||||
return true;
|
||||
}
|
||||
return mAppWidgetManager.bindAppWidgetIdIfAllowed(
|
||||
appWidgetId, info.getProfile(), info.provider, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LauncherAppWidgetProviderInfo findProvider(ComponentName provider, UserHandle user) {
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
return null;
|
||||
}
|
||||
for (AppWidgetProviderInfo info :
|
||||
getAllProviders(new PackageUserKey(provider.getPackageName(), user))) {
|
||||
if (info.provider.equals(provider)) {
|
||||
return LauncherAppWidgetProviderInfo.fromProviderInfo(mContext, info);
|
||||
}
|
||||
}
|
||||
|
||||
if (Process.myUserHandle().equals(user)) {
|
||||
for (LauncherAppWidgetProviderInfo info : getCustomWidgets()) {
|
||||
if (info.provider.equals(provider)) {
|
||||
return info;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<ComponentKey, AppWidgetProviderInfo> getAllProvidersMap() {
|
||||
HashMap<ComponentKey, AppWidgetProviderInfo> result = new HashMap<>();
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
return result;
|
||||
}
|
||||
for (UserHandle user : mUserManager.getUserProfiles()) {
|
||||
for (AppWidgetProviderInfo info :
|
||||
mAppWidgetManager.getInstalledProvidersForProfile(user)) {
|
||||
result.put(new ComponentKey(info.provider, user), info);
|
||||
}
|
||||
}
|
||||
for (LauncherAppWidgetProviderInfo info : getCustomWidgets()) {
|
||||
result.put(new ComponentKey(info.provider, info.getProfile()), info);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
List<CustomAppWidgetProviderInfo> getCustomWidgets() {
|
||||
return CustomWidgetManager.INSTANCE.get(mContext).getCustomWidgets();
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2017 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.compat;
|
||||
|
||||
import android.appwidget.AppWidgetProviderInfo;
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
class AppWidgetManagerCompatVO extends AppWidgetManagerCompatVL {
|
||||
|
||||
AppWidgetManagerCompatVO(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AppWidgetProviderInfo> getAllProviders(@Nullable PackageUserKey packageUser) {
|
||||
if (FeatureFlags.GO_DISABLE_WIDGETS) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
if (packageUser == null) {
|
||||
return super.getAllProviders(null);
|
||||
}
|
||||
return mAppWidgetManager.getInstalledProvidersForPackage(packageUser.mPackageName,
|
||||
packageUser.mUser);
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.compat;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.LauncherActivityInfo;
|
||||
import android.content.pm.PackageInstaller;
|
||||
import android.content.pm.PackageInstaller.SessionCallback;
|
||||
import android.content.pm.ShortcutInfo;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Bundle;
|
||||
import android.os.UserHandle;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.util.LooperExecutor;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class LauncherAppsCompat {
|
||||
|
||||
public interface OnAppsChangedCallbackCompat {
|
||||
default void onPackageRemoved(String packageName, UserHandle user) { }
|
||||
default void onPackageAdded(String packageName, UserHandle user) { }
|
||||
default void onPackageChanged(String packageName, UserHandle user) { }
|
||||
default void onPackagesAvailable(String[] packageNames, UserHandle user,
|
||||
boolean replacing) { }
|
||||
default void onPackagesUnavailable(String[] packageNames, UserHandle user,
|
||||
boolean replacing) { }
|
||||
default void onPackagesSuspended(String[] packageNames, UserHandle user) { }
|
||||
default void onPackagesUnsuspended(String[] packageNames, UserHandle user) { }
|
||||
default void onShortcutsChanged(String packageName, List<ShortcutInfo> shortcuts,
|
||||
UserHandle user) { }
|
||||
}
|
||||
|
||||
protected LauncherAppsCompat() {
|
||||
}
|
||||
|
||||
private static LauncherAppsCompat sInstance;
|
||||
private static final Object sInstanceLock = new Object();
|
||||
|
||||
public static LauncherAppsCompat getInstance(Context context) {
|
||||
synchronized (sInstanceLock) {
|
||||
if (sInstance == null) {
|
||||
if (Utilities.ATLEAST_Q) {
|
||||
sInstance = new LauncherAppsCompatVQ(context.getApplicationContext());
|
||||
} else if (Utilities.ATLEAST_OREO) {
|
||||
sInstance = new LauncherAppsCompatVO(context.getApplicationContext());
|
||||
} else {
|
||||
sInstance = new LauncherAppsCompatVL(context.getApplicationContext());
|
||||
}
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract List<LauncherActivityInfo> getActivityList(String packageName,
|
||||
UserHandle user);
|
||||
public abstract LauncherActivityInfo resolveActivity(Intent intent,
|
||||
UserHandle user);
|
||||
public abstract void startActivityForProfile(ComponentName component, UserHandle user,
|
||||
Rect sourceBounds, Bundle opts);
|
||||
public abstract ApplicationInfo getApplicationInfo(
|
||||
String packageName, int flags, UserHandle user);
|
||||
public abstract void showAppDetailsForProfile(ComponentName component, UserHandle user,
|
||||
Rect sourceBounds, Bundle opts);
|
||||
public abstract void addOnAppsChangedCallback(OnAppsChangedCallbackCompat listener);
|
||||
public abstract void removeOnAppsChangedCallback(OnAppsChangedCallbackCompat listener);
|
||||
public abstract boolean isPackageEnabledForProfile(String packageName, UserHandle user);
|
||||
public abstract boolean isActivityEnabledForProfile(ComponentName component,
|
||||
UserHandle user);
|
||||
public abstract List<ShortcutConfigActivityInfo> getCustomShortcutActivityList(
|
||||
@Nullable PackageUserKey packageUser);
|
||||
|
||||
public abstract List<PackageInstaller.SessionInfo> getAllPackageInstallerSessions();
|
||||
|
||||
public abstract void registerSessionCallback(LooperExecutor executor,
|
||||
SessionCallback sessionCallback);
|
||||
public abstract void unregisterSessionCallback(SessionCallback sessionCallback);
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.compat;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.LauncherActivityInfo;
|
||||
import android.content.pm.LauncherApps;
|
||||
import android.content.pm.PackageInstaller;
|
||||
import android.content.pm.PackageInstaller.SessionCallback;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.content.pm.ShortcutInfo;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Bundle;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
import android.util.ArrayMap;
|
||||
import android.util.Log;
|
||||
|
||||
import com.android.launcher3.compat.ShortcutConfigActivityInfo.ShortcutConfigActivityInfoVL;
|
||||
import com.android.launcher3.testing.TestProtocol;
|
||||
import com.android.launcher3.util.LooperExecutor;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
public class LauncherAppsCompatVL extends LauncherAppsCompat {
|
||||
|
||||
protected final LauncherApps mLauncherApps;
|
||||
protected final Context mContext;
|
||||
|
||||
private final ArrayMap<OnAppsChangedCallbackCompat, WrappedCallback> mCallbacks =
|
||||
new ArrayMap<>();
|
||||
|
||||
LauncherAppsCompatVL(Context context) {
|
||||
mContext = context;
|
||||
mLauncherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<LauncherActivityInfo> getActivityList(String packageName, UserHandle user) {
|
||||
return mLauncherApps.getActivityList(packageName, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LauncherActivityInfo resolveActivity(Intent intent, UserHandle user) {
|
||||
return mLauncherApps.resolveActivity(intent, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startActivityForProfile(ComponentName component, UserHandle user,
|
||||
Rect sourceBounds, Bundle opts) {
|
||||
mLauncherApps.startMainActivity(component, user, sourceBounds, opts);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationInfo getApplicationInfo(String packageName, int flags, UserHandle user) {
|
||||
final boolean isPrimaryUser = Process.myUserHandle().equals(user);
|
||||
if (!isPrimaryUser && (flags == 0)) {
|
||||
// We are looking for an installed app on a secondary profile. Prior to O, the only
|
||||
// entry point for work profiles is through the LauncherActivity.
|
||||
List<LauncherActivityInfo> activityList =
|
||||
mLauncherApps.getActivityList(packageName, user);
|
||||
return activityList.size() > 0 ? activityList.get(0).getApplicationInfo() : null;
|
||||
}
|
||||
try {
|
||||
ApplicationInfo info =
|
||||
mContext.getPackageManager().getApplicationInfo(packageName, flags);
|
||||
// There is no way to check if the app is installed for managed profile. But for
|
||||
// primary profile, we can still have this check.
|
||||
if (isPrimaryUser && ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0)
|
||||
|| !info.enabled) {
|
||||
return null;
|
||||
}
|
||||
return info;
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
// Package not found
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showAppDetailsForProfile(ComponentName component, UserHandle user,
|
||||
Rect sourceBounds, Bundle opts) {
|
||||
mLauncherApps.startAppDetailsActivity(component, user, sourceBounds, opts);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addOnAppsChangedCallback(LauncherAppsCompat.OnAppsChangedCallbackCompat callback) {
|
||||
WrappedCallback wrappedCallback = new WrappedCallback(callback);
|
||||
synchronized (mCallbacks) {
|
||||
mCallbacks.put(callback, wrappedCallback);
|
||||
}
|
||||
mLauncherApps.registerCallback(wrappedCallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeOnAppsChangedCallback(OnAppsChangedCallbackCompat callback) {
|
||||
final WrappedCallback wrappedCallback;
|
||||
synchronized (mCallbacks) {
|
||||
wrappedCallback = mCallbacks.remove(callback);
|
||||
}
|
||||
if (wrappedCallback != null) {
|
||||
mLauncherApps.unregisterCallback(wrappedCallback);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPackageEnabledForProfile(String packageName, UserHandle user) {
|
||||
return mLauncherApps.isPackageEnabled(packageName, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isActivityEnabledForProfile(ComponentName component, UserHandle user) {
|
||||
return mLauncherApps.isActivityEnabled(component, user);
|
||||
}
|
||||
|
||||
private static class WrappedCallback extends LauncherApps.Callback {
|
||||
private final LauncherAppsCompat.OnAppsChangedCallbackCompat mCallback;
|
||||
|
||||
public WrappedCallback(LauncherAppsCompat.OnAppsChangedCallbackCompat callback) {
|
||||
mCallback = callback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackageRemoved(String packageName, UserHandle user) {
|
||||
mCallback.onPackageRemoved(packageName, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackageAdded(String packageName, UserHandle user) {
|
||||
mCallback.onPackageAdded(packageName, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackageChanged(String packageName, UserHandle user) {
|
||||
mCallback.onPackageChanged(packageName, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackagesAvailable(String[] packageNames, UserHandle user, boolean replacing) {
|
||||
mCallback.onPackagesAvailable(packageNames, user, replacing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackagesUnavailable(String[] packageNames, UserHandle user,
|
||||
boolean replacing) {
|
||||
mCallback.onPackagesUnavailable(packageNames, user, replacing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackagesSuspended(String[] packageNames, UserHandle user) {
|
||||
if (TestProtocol.sDebugTracing) {
|
||||
Log.d(TestProtocol.APP_NOT_DISABLED, "onPackagesSuspended: " +
|
||||
Arrays.toString(packageNames));
|
||||
}
|
||||
mCallback.onPackagesSuspended(packageNames, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPackagesUnsuspended(String[] packageNames, UserHandle user) {
|
||||
mCallback.onPackagesUnsuspended(packageNames, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onShortcutsChanged(@NonNull String packageName,
|
||||
@NonNull List<ShortcutInfo> shortcuts,
|
||||
@NonNull UserHandle user) {
|
||||
mCallback.onShortcutsChanged(packageName, shortcuts, user);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ShortcutConfigActivityInfo> getCustomShortcutActivityList(
|
||||
@Nullable PackageUserKey packageUser) {
|
||||
List<ShortcutConfigActivityInfo> result = new ArrayList<>();
|
||||
if (packageUser != null && !packageUser.mUser.equals(Process.myUserHandle())) {
|
||||
return result;
|
||||
}
|
||||
PackageManager pm = mContext.getPackageManager();
|
||||
for (ResolveInfo info :
|
||||
pm.queryIntentActivities(new Intent(Intent.ACTION_CREATE_SHORTCUT), 0)) {
|
||||
if (packageUser == null || packageUser.mPackageName
|
||||
.equals(info.activityInfo.packageName)) {
|
||||
result.add(new ShortcutConfigActivityInfoVL(info.activityInfo));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<PackageInstaller.SessionInfo> getAllPackageInstallerSessions() {
|
||||
return mContext.getPackageManager().getPackageInstaller().getAllSessions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerSessionCallback(LooperExecutor executor, SessionCallback sessionCallback) {
|
||||
mContext.getPackageManager().getPackageInstaller().registerSessionCallback(sessionCallback,
|
||||
executor.getHandler());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterSessionCallback(SessionCallback sessionCallback) {
|
||||
mContext.getPackageManager().getPackageInstaller()
|
||||
.unregisterSessionCallback(sessionCallback);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
* 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.launcher3.compat;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageInstaller;
|
||||
import android.content.pm.PackageInstaller.SessionCallback;
|
||||
|
||||
import com.android.launcher3.util.LooperExecutor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@TargetApi(29)
|
||||
public class LauncherAppsCompatVQ extends LauncherAppsCompatVO {
|
||||
|
||||
LauncherAppsCompatVQ(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public List<PackageInstaller.SessionInfo> getAllPackageInstallerSessions() {
|
||||
return mLauncherApps.getAllPackageInstallerSessions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerSessionCallback(LooperExecutor executor, SessionCallback sessionCallback) {
|
||||
mLauncherApps.registerPackageInstallerSessionCallback(executor, sessionCallback);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterSessionCallback(SessionCallback sessionCallback) {
|
||||
mLauncherApps.unregisterPackageInstallerSessionCallback(sessionCallback);
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.compat;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageInstaller;
|
||||
import android.content.pm.PackageInstaller.SessionInfo;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
|
||||
public abstract class PackageInstallerCompat {
|
||||
|
||||
// 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 int STATUS_INSTALLED = 0;
|
||||
public static final int STATUS_INSTALLING = 1;
|
||||
public static final int STATUS_FAILED = 2;
|
||||
|
||||
private static final Object sInstanceLock = new Object();
|
||||
private static PackageInstallerCompat sInstance;
|
||||
|
||||
public static PackageInstallerCompat getInstance(Context context) {
|
||||
synchronized (sInstanceLock) {
|
||||
if (sInstance == null) {
|
||||
sInstance = new PackageInstallerCompatVL(context);
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
}
|
||||
|
||||
public static UserHandle getUserHandle(SessionInfo info) {
|
||||
return Utilities.ATLEAST_Q ? info.getUser() : Process.myUserHandle();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a map of active installs to their progress
|
||||
*/
|
||||
public abstract HashMap<PackageUserKey, SessionInfo> updateAndGetActiveSessionCache();
|
||||
|
||||
/**
|
||||
* @return an active SessionInfo for {@param pkg} or null if none exists.
|
||||
*/
|
||||
public abstract SessionInfo getActiveSessionInfo(UserHandle user, String pkg);
|
||||
|
||||
public abstract void onStop();
|
||||
|
||||
public static final class PackageInstallInfo {
|
||||
public final ComponentName componentName;
|
||||
public final String packageName;
|
||||
public final int state;
|
||||
public final int progress;
|
||||
public final UserHandle user;
|
||||
|
||||
private PackageInstallInfo(@NonNull SessionInfo info) {
|
||||
this.state = STATUS_INSTALLING;
|
||||
this.packageName = info.getAppPackageName();
|
||||
this.componentName = new ComponentName(packageName, "");
|
||||
this.progress = (int) (info.getProgress() * 100f);
|
||||
this.user = getUserHandle(info);
|
||||
}
|
||||
|
||||
public PackageInstallInfo(String packageName, int state, int progress, UserHandle user) {
|
||||
this.state = state;
|
||||
this.packageName = packageName;
|
||||
this.componentName = new ComponentName(packageName, "");
|
||||
this.progress = progress;
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public static PackageInstallInfo fromInstallingState(SessionInfo info) {
|
||||
return new PackageInstallInfo(info);
|
||||
}
|
||||
|
||||
public static PackageInstallInfo fromState(int state, String packageName, UserHandle user) {
|
||||
return new PackageInstallInfo(packageName, state, 0 /* progress */, user);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public abstract List<SessionInfo> getAllVerifiedSessions();
|
||||
|
||||
/**
|
||||
* Returns true if a promise icon was already added to the home screen for {@param sessionId}.
|
||||
* Applicable only for icons with flag FLAG_PROMISE_NEW_INSTALLS.
|
||||
*/
|
||||
public abstract boolean promiseIconAddedForId(int sessionId);
|
||||
|
||||
/**
|
||||
* Applicable only for icons with flag FLAG_PROMISE_NEW_INSTALLS.
|
||||
*/
|
||||
public abstract void removePromiseIconId(int sessionId);
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.compat;
|
||||
|
||||
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.PackageInstaller;
|
||||
import android.content.pm.PackageInstaller.SessionCallback;
|
||||
import android.content.pm.PackageInstaller.SessionInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.UserHandle;
|
||||
import android.text.TextUtils;
|
||||
import android.util.SparseArray;
|
||||
|
||||
import com.android.launcher3.SessionCommitReceiver;
|
||||
import com.android.launcher3.Utilities;
|
||||
import com.android.launcher3.icons.IconCache;
|
||||
import com.android.launcher3.LauncherAppState;
|
||||
import com.android.launcher3.config.FeatureFlags;
|
||||
import com.android.launcher3.util.IntArray;
|
||||
import com.android.launcher3.util.IntSet;
|
||||
import com.android.launcher3.util.PackageUserKey;
|
||||
import com.android.launcher3.util.Thunk;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static com.android.launcher3.Utilities.getPrefs;
|
||||
|
||||
public class PackageInstallerCompatVL extends PackageInstallerCompat {
|
||||
|
||||
private static final boolean DEBUG = false;
|
||||
|
||||
@Thunk final SparseArray<PackageUserKey> mActiveSessions = new SparseArray<>();
|
||||
|
||||
@Thunk final PackageInstaller mInstaller;
|
||||
private final IconCache mCache;
|
||||
private final Context mAppContext;
|
||||
private final HashMap<String,Boolean> mSessionVerifiedMap = new HashMap<>();
|
||||
private final LauncherAppsCompat mLauncherApps;
|
||||
private final IntSet mPromiseIconIds;
|
||||
|
||||
PackageInstallerCompatVL(Context context) {
|
||||
mAppContext = context.getApplicationContext();
|
||||
mInstaller = context.getPackageManager().getPackageInstaller();
|
||||
mCache = LauncherAppState.getInstance(context).getIconCache();
|
||||
mLauncherApps = LauncherAppsCompat.getInstance(context);
|
||||
mLauncherApps.registerSessionCallback(MODEL_EXECUTOR, mCallback);
|
||||
mPromiseIconIds = IntSet.wrap(IntArray.fromConcatString(
|
||||
getPrefs(context).getString(PROMISE_ICON_IDS, "")));
|
||||
|
||||
cleanUpPromiseIconIds();
|
||||
}
|
||||
|
||||
private void cleanUpPromiseIconIds() {
|
||||
IntArray existingIds = new IntArray();
|
||||
for (SessionInfo info : updateAndGetActiveSessionCache().values()) {
|
||||
existingIds.add(info.getSessionId());
|
||||
}
|
||||
IntArray idsToRemove = new IntArray();
|
||||
|
||||
for (int i = mPromiseIconIds.size() - 1; i >= 0; --i) {
|
||||
if (!existingIds.contains(mPromiseIconIds.getArray().get(i))) {
|
||||
idsToRemove.add(mPromiseIconIds.getArray().get(i));
|
||||
}
|
||||
}
|
||||
for (int i = idsToRemove.size() - 1; i >= 0; --i) {
|
||||
mPromiseIconIds.getArray().removeValue(idsToRemove.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public HashMap<PackageUserKey, SessionInfo> updateAndGetActiveSessionCache() {
|
||||
HashMap<PackageUserKey, SessionInfo> activePackages = new HashMap<>();
|
||||
for (SessionInfo info : getAllVerifiedSessions()) {
|
||||
addSessionInfoToCache(info, getUserHandle(info));
|
||||
if (info.getAppPackageName() != null) {
|
||||
activePackages.put(new PackageUserKey(info.getAppPackageName(),
|
||||
getUserHandle(info)), info);
|
||||
mActiveSessions.put(info.getSessionId(),
|
||||
new PackageUserKey(info.getAppPackageName(), getUserHandle(info)));
|
||||
}
|
||||
}
|
||||
return activePackages;
|
||||
}
|
||||
|
||||
public SessionInfo getActiveSessionInfo(UserHandle user, String pkg) {
|
||||
for (SessionInfo info : getAllVerifiedSessions()) {
|
||||
boolean match = pkg.equals(info.getAppPackageName());
|
||||
if (Utilities.ATLEAST_Q && !user.equals(getUserHandle(info))) {
|
||||
match = false;
|
||||
}
|
||||
if (match) {
|
||||
return info;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Thunk void addSessionInfoToCache(SessionInfo info, UserHandle user) {
|
||||
String packageName = info.getAppPackageName();
|
||||
if (packageName != null) {
|
||||
mCache.cachePackageInstallInfo(packageName, user, info.getAppIcon(),
|
||||
info.getAppLabel());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop() {
|
||||
mLauncherApps.unregisterSessionCallback(mCallback);
|
||||
}
|
||||
|
||||
@Thunk void sendUpdate(PackageInstallInfo info) {
|
||||
LauncherAppState app = LauncherAppState.getInstanceNoCreate();
|
||||
if (app != null) {
|
||||
app.getModel().setPackageState(info);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a promise app icon to the workspace iff:
|
||||
* - The settings for it are enabled
|
||||
* - The user installed the app
|
||||
* - There is an app icon and label (For apps with no launching activity, no icon is provided).
|
||||
* - The app is not already installed
|
||||
* - A promise icon for the session has not already been created
|
||||
*/
|
||||
private void tryQueuePromiseAppIcon(SessionInfo sessionInfo) {
|
||||
if (Utilities.ATLEAST_OREO && FeatureFlags.PROMISE_APPS_NEW_INSTALLS.get()
|
||||
&& SessionCommitReceiver.isEnabled(mAppContext)
|
||||
&& verify(sessionInfo) != null
|
||||
&& sessionInfo.getInstallReason() == PackageManager.INSTALL_REASON_USER
|
||||
&& sessionInfo.getAppIcon() != null
|
||||
&& !TextUtils.isEmpty(sessionInfo.getAppLabel())
|
||||
&& !mPromiseIconIds.contains(sessionInfo.getSessionId())
|
||||
&& mLauncherApps.getApplicationInfo(sessionInfo.getAppPackageName(), 0,
|
||||
getUserHandle(sessionInfo)) == null) {
|
||||
SessionCommitReceiver.queuePromiseAppIconAddition(mAppContext, sessionInfo);
|
||||
mPromiseIconIds.add(sessionInfo.getSessionId());
|
||||
updatePromiseIconPrefs();
|
||||
}
|
||||
}
|
||||
|
||||
private final SessionCallback mCallback = new SessionCallback() {
|
||||
|
||||
@Override
|
||||
public void onCreated(int sessionId) {
|
||||
SessionInfo sessionInfo = pushSessionDisplayToLauncher(sessionId);
|
||||
if (FeatureFlags.LAUNCHER3_PROMISE_APPS_IN_ALL_APPS && sessionInfo != null) {
|
||||
LauncherAppState app = LauncherAppState.getInstanceNoCreate();
|
||||
if (app != null) {
|
||||
app.getModel().onInstallSessionCreated(
|
||||
PackageInstallInfo.fromInstallingState(sessionInfo));
|
||||
}
|
||||
}
|
||||
|
||||
tryQueuePromiseAppIcon(sessionInfo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFinished(int sessionId, boolean success) {
|
||||
// For a finished session, we can't get the session info. So use the
|
||||
// packageName from our local cache.
|
||||
PackageUserKey key = mActiveSessions.get(sessionId);
|
||||
mActiveSessions.remove(sessionId);
|
||||
|
||||
if (key != null && key.mPackageName != null) {
|
||||
String packageName = key.mPackageName;
|
||||
sendUpdate(PackageInstallInfo.fromState(success ? STATUS_INSTALLED : STATUS_FAILED,
|
||||
packageName, key.mUser));
|
||||
|
||||
if (!success && FeatureFlags.PROMISE_APPS_NEW_INSTALLS.get()
|
||||
&& mPromiseIconIds.contains(sessionId)) {
|
||||
LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
|
||||
if (appState != null) {
|
||||
appState.getModel().onSessionFailure(packageName, key.mUser);
|
||||
}
|
||||
// If it is successful, the id is removed in the the package added flow.
|
||||
removePromiseIconId(sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onProgressChanged(int sessionId, float progress) {
|
||||
SessionInfo session = verify(mInstaller.getSessionInfo(sessionId));
|
||||
if (session != null && session.getAppPackageName() != null) {
|
||||
sendUpdate(PackageInstallInfo.fromInstallingState(session));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActiveChanged(int sessionId, boolean active) { }
|
||||
|
||||
@Override
|
||||
public void onBadgingChanged(int sessionId) {
|
||||
SessionInfo sessionInfo = pushSessionDisplayToLauncher(sessionId);
|
||||
if (sessionInfo != null) {
|
||||
tryQueuePromiseAppIcon(sessionInfo);
|
||||
}
|
||||
}
|
||||
|
||||
private SessionInfo pushSessionDisplayToLauncher(int sessionId) {
|
||||
SessionInfo session = verify(mInstaller.getSessionInfo(sessionId));
|
||||
if (session != null && session.getAppPackageName() != null) {
|
||||
UserHandle user = getUserHandle(session);
|
||||
mActiveSessions.put(session.getSessionId(),
|
||||
new PackageUserKey(session.getAppPackageName(), user));
|
||||
addSessionInfoToCache(session, user);
|
||||
LauncherAppState app = LauncherAppState.getInstanceNoCreate();
|
||||
if (app != null) {
|
||||
app.getModel().updateSessionDisplayInfo(session.getAppPackageName(),
|
||||
user);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
private PackageInstaller.SessionInfo verify(PackageInstaller.SessionInfo sessionInfo) {
|
||||
if (sessionInfo == null
|
||||
|| sessionInfo.getInstallerPackageName() == null
|
||||
|| TextUtils.isEmpty(sessionInfo.getAppPackageName())) {
|
||||
return null;
|
||||
}
|
||||
String pkg = sessionInfo.getInstallerPackageName();
|
||||
synchronized (mSessionVerifiedMap) {
|
||||
if (!mSessionVerifiedMap.containsKey(pkg)) {
|
||||
LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(mAppContext);
|
||||
boolean hasSystemFlag = launcherApps.getApplicationInfo(pkg,
|
||||
ApplicationInfo.FLAG_SYSTEM, getUserHandle(sessionInfo)) != null;
|
||||
mSessionVerifiedMap.put(pkg, DEBUG || hasSystemFlag);
|
||||
}
|
||||
}
|
||||
return mSessionVerifiedMap.get(pkg) ? sessionInfo : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SessionInfo> getAllVerifiedSessions() {
|
||||
List<SessionInfo> list = new ArrayList<>(Utilities.ATLEAST_Q
|
||||
? mLauncherApps.getAllPackageInstallerSessions()
|
||||
: mInstaller.getAllSessions());
|
||||
Iterator<SessionInfo> it = list.iterator();
|
||||
while (it.hasNext()) {
|
||||
if (verify(it.next()) == null) {
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean promiseIconAddedForId(int sessionId) {
|
||||
return mPromiseIconIds.contains(sessionId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removePromiseIconId(int sessionId) {
|
||||
if (mPromiseIconIds.contains(sessionId)) {
|
||||
mPromiseIconIds.getArray().removeValue(sessionId);
|
||||
updatePromiseIconPrefs();
|
||||
}
|
||||
}
|
||||
|
||||
private void updatePromiseIconPrefs() {
|
||||
getPrefs(mAppContext).edit()
|
||||
.putString(PROMISE_ICON_IDS, mPromiseIconIds.getArray().toConcatString())
|
||||
.apply();
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014 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.compat;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.UserHandle;
|
||||
|
||||
import com.android.launcher3.Utilities;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class UserManagerCompat {
|
||||
protected UserManagerCompat() {
|
||||
}
|
||||
|
||||
private static final Object sInstanceLock = new Object();
|
||||
private static UserManagerCompat sInstance;
|
||||
|
||||
public static UserManagerCompat getInstance(Context context) {
|
||||
synchronized (sInstanceLock) {
|
||||
if (sInstance == null) {
|
||||
if (Utilities.ATLEAST_P) {
|
||||
sInstance = new UserManagerCompatVP(context.getApplicationContext());
|
||||
} else {
|
||||
sInstance = new UserManagerCompatVNMr1(context.getApplicationContext());
|
||||
}
|
||||
}
|
||||
return sInstance;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a cache for users.
|
||||
*/
|
||||
public abstract void enableAndResetCache();
|
||||
|
||||
public abstract List<UserHandle> getUserProfiles();
|
||||
public abstract long getSerialNumberForUser(UserHandle user);
|
||||
public abstract UserHandle getUserForSerialNumber(long serialNumber);
|
||||
public abstract boolean isQuietModeEnabled(UserHandle user);
|
||||
public abstract boolean isUserUnlocked(UserHandle user);
|
||||
|
||||
public abstract boolean isDemoUser();
|
||||
public abstract boolean requestQuietModeEnabled(boolean enableQuietMode, UserHandle user);
|
||||
public abstract boolean isAnyProfileQuietModeEnabled();
|
||||
|
||||
public abstract boolean hasWorkProfile();
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2016 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.compat;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.os.Process;
|
||||
import android.os.UserHandle;
|
||||
import android.os.UserManager;
|
||||
import android.util.ArrayMap;
|
||||
import android.util.LongSparseArray;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.N_MR1)
|
||||
public class UserManagerCompatVNMr1 extends UserManagerCompat {
|
||||
|
||||
protected final UserManager mUserManager;
|
||||
|
||||
protected LongSparseArray<UserHandle> mUsers;
|
||||
// Create a separate reverse map as LongSparseArray.indexOfValue checks if objects are same
|
||||
// and not {@link Object#equals}
|
||||
protected ArrayMap<UserHandle, Long> mUserToSerialMap;
|
||||
|
||||
UserManagerCompatVNMr1(Context context) {
|
||||
mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isQuietModeEnabled(UserHandle user) {
|
||||
return mUserManager.isQuietModeEnabled(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserUnlocked(UserHandle user) {
|
||||
return mUserManager.isUserUnlocked(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnyProfileQuietModeEnabled() {
|
||||
List<UserHandle> userProfiles = getUserProfiles();
|
||||
for (UserHandle userProfile : userProfiles) {
|
||||
if (Process.myUserHandle().equals(userProfile)) {
|
||||
continue;
|
||||
}
|
||||
if (isQuietModeEnabled(userProfile)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSerialNumberForUser(UserHandle user) {
|
||||
synchronized (this) {
|
||||
if (mUserToSerialMap != null) {
|
||||
Long serial = mUserToSerialMap.get(user);
|
||||
return serial == null ? 0 : serial;
|
||||
}
|
||||
}
|
||||
return mUserManager.getSerialNumberForUser(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserHandle getUserForSerialNumber(long serialNumber) {
|
||||
synchronized (this) {
|
||||
if (mUsers != null) {
|
||||
return mUsers.get(serialNumber);
|
||||
}
|
||||
}
|
||||
return mUserManager.getUserForSerialNumber(serialNumber);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDemoUser() {
|
||||
return mUserManager.isDemoUser();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean requestQuietModeEnabled(boolean enableQuietMode, UserHandle user) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enableAndResetCache() {
|
||||
synchronized (this) {
|
||||
mUsers = new LongSparseArray<>();
|
||||
mUserToSerialMap = new ArrayMap<>();
|
||||
List<UserHandle> users = mUserManager.getUserProfiles();
|
||||
if (users != null) {
|
||||
for (UserHandle user : users) {
|
||||
long serial = mUserManager.getSerialNumberForUser(user);
|
||||
mUsers.put(serial, user);
|
||||
mUserToSerialMap.put(user, serial);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UserHandle> getUserProfiles() {
|
||||
synchronized (this) {
|
||||
if (mUsers != null) {
|
||||
return new ArrayList<>(mUserToSerialMap.keySet());
|
||||
}
|
||||
}
|
||||
|
||||
List<UserHandle> users = mUserManager.getUserProfiles();
|
||||
return users == null ? Collections.<UserHandle>emptyList() : users;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasWorkProfile() {
|
||||
synchronized (this) {
|
||||
if (mUsers != null) {
|
||||
return mUsers.size() > 1;
|
||||
}
|
||||
}
|
||||
return getUserProfiles().size() > 1;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 953 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user