Workspace.java revision 7372c59277a23a31eeb1513a554b29d7bf05aedb
1f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp/* 2f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * Copyright (C) 2008 The Android Open Source Project 3f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * 4f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * Licensed under the Apache License, Version 2.0 (the "License"); 5f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * you may not use this file except in compliance with the License. 6f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * You may obtain a copy of the License at 7f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * 8f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * http://www.apache.org/licenses/LICENSE-2.0 9f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * 10f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * Unless required by applicable law or agreed to in writing, software 11f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * distributed under the License is distributed on an "AS IS" BASIS, 12f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * See the License for the specific language governing permissions and 14f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * limitations under the License. 15f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp */ 16f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 17f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyppackage com.android.launcher2; 18351ad4e87e0b0b98df9ca88266a8a63541dc5a81Andy Huang 19f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.animation.Animator; 20f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.animation.Animator.AnimatorListener; 21f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.animation.AnimatorListenerAdapter; 22f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.animation.AnimatorSet; 23f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.animation.ObjectAnimator; 240e8a95148f7fdc9c6a33971924b0d29a202d73ecmindypimport android.animation.TimeInterpolator; 250e8a95148f7fdc9c6a33971924b0d29a202d73ecmindypimport android.animation.ValueAnimator; 26f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.animation.ValueAnimator.AnimatorUpdateListener; 27f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.app.AlertDialog; 28f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.app.WallpaperManager; 29f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.appwidget.AppWidgetHostView; 30f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.appwidget.AppWidgetManager; 31f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.appwidget.AppWidgetProviderInfo; 32f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.content.ClipData; 33ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindypimport android.content.ClipDescription; 3426d4d2d9c43c499f458808f050ec73ea3c28dec4mindypimport android.content.ComponentName; 35f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.content.Context; 36f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.content.Intent; 37351ad4e87e0b0b98df9ca88266a8a63541dc5a81Andy Huangimport android.content.res.Resources; 38351ad4e87e0b0b98df9ca88266a8a63541dc5a81Andy Huangimport android.content.res.TypedArray; 39351ad4e87e0b0b98df9ca88266a8a63541dc5a81Andy Huangimport android.graphics.Bitmap; 40351ad4e87e0b0b98df9ca88266a8a63541dc5a81Andy Huangimport android.graphics.Camera; 41351ad4e87e0b0b98df9ca88266a8a63541dc5a81Andy Huangimport android.graphics.Canvas; 42f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.graphics.Matrix; 43f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.graphics.Paint; 44f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.graphics.Point; 45adbf3e8cadb66666f307352b72537fbac57b916fAndy Huangimport android.graphics.PorterDuff; 46f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.graphics.Rect; 47f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.graphics.RectF; 48f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.graphics.Region.Op; 49f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.graphics.drawable.Drawable; 50f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.os.IBinder; 51f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.os.Parcelable; 52f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.util.AttributeSet; 53f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.util.DisplayMetrics; 54f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.util.Log; 55f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.util.Pair; 56f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.view.Display; 5726d4d2d9c43c499f458808f050ec73ea3c28dec4mindypimport android.view.DragEvent; 58f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.view.MotionEvent; 59f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.view.View; 6026d4d2d9c43c499f458808f050ec73ea3c28dec4mindypimport android.view.ViewGroup; 61f4fce1227d8b49f45e6569f1590565f2df9e8d6emindypimport android.view.animation.DecelerateInterpolator; 6226d4d2d9c43c499f458808f050ec73ea3c28dec4mindypimport android.widget.ImageView; 630a1aa1bb89221eda2f67af52ef274612f28ecf5cPaul Westbrookimport android.widget.TextView; 64542fec98d011c78782b63b33d29cf81044e96f75Paul Westbrookimport android.widget.Toast; 65ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindyp 66ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindypimport com.android.launcher.R; 679d3fd92ed6091dbd0d38799222a1cf841f1c3f29Andy Huangimport com.android.launcher2.FolderIcon.FolderRingAnimator; 684d8cad5e37ade03903a23cca8ea3e782af21170fPaul Westbrookimport com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData; 694d8cad5e37ade03903a23cca8ea3e782af21170fPaul Westbrook 704d8cad5e37ade03903a23cca8ea3e782af21170fPaul Westbrookimport java.util.ArrayList; 71ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindypimport java.util.HashSet; 72ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindypimport java.util.List; 73ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindyp 74f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp/** 75f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * The workspace is a wide area with a wallpaper and a finite number of pages. 76f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * Each page contains a number of icons, folders or widgets the user can 77f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * interact with. A workspace is meant to be used with a fixed width only. 78f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp */ 79f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyppublic class Workspace extends SmoothPagedView 80f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp implements DropTarget, DragSource, DragScroller, View.OnTouchListener, 81f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp DragController.DragListener { 82f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp @SuppressWarnings({"UnusedDeclaration"}) 83f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final String TAG = "Launcher.Workspace"; 84f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 85f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // Y rotation to apply to the workspace screens 86f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final float WORKSPACE_ROTATION = 12.5f; 87f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final float WORKSPACE_OVERSCROLL_ROTATION = 24f; 88f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static float CAMERA_DISTANCE = 6500; 89f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 90f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final int CHILDREN_OUTLINE_FADE_OUT_DELAY = 0; 91f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final int CHILDREN_OUTLINE_FADE_OUT_DURATION = 375; 92f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final int CHILDREN_OUTLINE_FADE_IN_DURATION = 100; 93f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 94f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final int BACKGROUND_FADE_OUT_DURATION = 350; 95f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final int ADJACENT_SCREEN_DROP_DURATION = 300; 96f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final int FLING_THRESHOLD_VELOCITY = 500; 97f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 98f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // These animators are used to fade the children's outlines 99f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private ObjectAnimator mChildrenOutlineFadeInAnimation; 100f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private ObjectAnimator mChildrenOutlineFadeOutAnimation; 101604f7716eaac3bc0989cdb2ff129c383b6dfe4d6mindyp private float mChildrenOutlineAlpha = 0; 102f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 103f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // These properties refer to the background protection gradient used for AllApps and Customize 104f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private ValueAnimator mBackgroundFadeInAnimation; 105f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private ValueAnimator mBackgroundFadeOutAnimation; 1067388dba58aecafacd91ded0f787cf01bfc7af232Andy Huang private Drawable mBackground; 107f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp boolean mDrawBackground = true; 108f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mBackgroundAlpha = 0; 109f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mOverScrollMaxBackgroundAlpha = 0.0f; 11069a6cdff8afde77ec9bcd75a5651ee212344019eVikram Aggarwal private int mOverScrollPageIndex = -1; 11169a6cdff8afde77ec9bcd75a5651ee212344019eVikram Aggarwal 11269a6cdff8afde77ec9bcd75a5651ee212344019eVikram Aggarwal private float mWallpaperScrollRatio = 1.0f; 113f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 114ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindyp private final WallpaperManager mWallpaperManager; 115f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private IBinder mWindowToken; 116f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final float WALLPAPER_SCREENS_SPAN = 2f; 117f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 118f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private int mDefaultPage; 119f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 120f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp /** 12126d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp * CellInfo for the cell that is currently being dragged 122f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp */ 123f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private CellLayout.CellInfo mDragInfo; 12426d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp 125ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindyp /** 12626d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp * Target drop area calculated during last acceptDrop call. 127ff282d0ef252dbdaf6e9f4e2a7fd640287c01e6bmindyp */ 12805e522165c415f0a16a23117cd7d91a033780890mindyp private int[] mTargetCell = new int[2]; 129f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 130f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp /** 131f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * The CellLayout that is currently being dragged over 132f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp */ 133f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private CellLayout mDragTargetLayout = null; 134f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private boolean mDragHasEnteredWorkspace = false; 135f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 136f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private Launcher mLauncher; 1374d8cad5e37ade03903a23cca8ea3e782af21170fPaul Westbrook private IconCache mIconCache; 138f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private DragController mDragController; 139f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 140f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // These are temporary variables to prevent having to allocate a new object just to 141f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // return an (x, y) value from helper functions. Do NOT use them to maintain other state. 142fafcd17adae9b7ba5c270611d0f53608ced92e2eScott Kennedy private int[] mTempCell = new int[2]; 143fafcd17adae9b7ba5c270611d0f53608ced92e2eScott Kennedy private int[] mTempEstimate = new int[2]; 144fafcd17adae9b7ba5c270611d0f53608ced92e2eScott Kennedy private float[] mDragViewVisualCenter = new float[2]; 145fafcd17adae9b7ba5c270611d0f53608ced92e2eScott Kennedy private float[] mTempDragCoordinates = new float[2]; 146fafcd17adae9b7ba5c270611d0f53608ced92e2eScott Kennedy private float[] mTempCellLayoutCenterCoordinates = new float[2]; 147f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mTempDragBottomRightCoordinates = new float[2]; 148f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private Matrix mTempInverseMatrix = new Matrix(); 149f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 150f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private SpringLoadedDragController mSpringLoadedDragController; 151fb05201c2c5c53f58846112240a05849319317a9mindyp private float mSpringLoadedShrinkFactor; 152fb05201c2c5c53f58846112240a05849319317a9mindyp 153fb05201c2c5c53f58846112240a05849319317a9mindyp private static final int DEFAULT_CELL_COUNT_X = 4; 154f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private static final int DEFAULT_CELL_COUNT_Y = 4; 155f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 156f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // State variable that indicates whether the pages are small (ie when you're 157f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // in all apps or customize mode) 158f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 159351ad4e87e0b0b98df9ca88266a8a63541dc5a81Andy Huang enum State { NORMAL, SPRING_LOADED, SMALL }; 160f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private State mState = State.NORMAL; 161f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private boolean mIsSwitchingState = false; 162f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 163adbf3e8cadb66666f307352b72537fbac57b916fAndy Huang private AnimatorListener mChangeStateAnimationListener; 164f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 165f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp boolean mAnimatingViewIntoPlace = false; 166f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp boolean mIsDragOccuring = false; 167f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp boolean mChildrenLayersEnabled = true; 168f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 169f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp /** Is the user is dragging an item near the edge of a page? */ 170f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private boolean mInScrollArea = false; 171f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 172f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper(); 173f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private Bitmap mDragOutline = null; 174f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private final Rect mTempRect = new Rect(); 175f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private final int[] mTempXY = new int[2]; 176f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private int mDragViewMultiplyColor; 177f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mOverscrollFade = 0; 178f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 179f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // Paint used to draw external drop outline 180f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private final Paint mExternalDragOutlinePaint = new Paint(); 181f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 182f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp // Camera and Matrix used to determine the final position of a neighboring CellLayout 183f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private final Matrix mMatrix = new Matrix(); 184604f7716eaac3bc0989cdb2ff129c383b6dfe4d6mindyp private final Camera mCamera = new Camera(); 185604f7716eaac3bc0989cdb2ff129c383b6dfe4d6mindyp private final float mTempFloat2[] = new float[2]; 186604f7716eaac3bc0989cdb2ff129c383b6dfe4d6mindyp 18751ad9041014920d78d9b7b3ab84ec04a7c41beaeVikram Aggarwal enum WallpaperVerticalOffset { TOP, MIDDLE, BOTTOM }; 18851ad9041014920d78d9b7b3ab84ec04a7c41beaeVikram Aggarwal int mWallpaperWidth; 18951ad9041014920d78d9b7b3ab84ec04a7c41beaeVikram Aggarwal int mWallpaperHeight; 190604f7716eaac3bc0989cdb2ff129c383b6dfe4d6mindyp WallpaperOffsetInterpolator mWallpaperOffset; 191f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp boolean mUpdateWallpaperOffsetImmediately = false; 192f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private Runnable mDelayedResizeRunnable; 193f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private int mDisplayWidth; 194eb9a4bdc53269ee05fe11870b9ebf03f18196585Scott Kennedy private int mDisplayHeight; 195eb9a4bdc53269ee05fe11870b9ebf03f18196585Scott Kennedy private int mWallpaperTravelWidth; 196eb9a4bdc53269ee05fe11870b9ebf03f18196585Scott Kennedy 197eb9a4bdc53269ee05fe11870b9ebf03f18196585Scott Kennedy // Variables relating to the creation of user folders by hovering shortcuts over shortcuts 198eb9a4bdc53269ee05fe11870b9ebf03f18196585Scott Kennedy private static final int FOLDER_CREATION_TIMEOUT = 250; 199eb9a4bdc53269ee05fe11870b9ebf03f18196585Scott Kennedy private final Alarm mFolderCreationAlarm = new Alarm(); 200f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private FolderRingAnimator mDragFolderRingAnimator = null; 201f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private View mLastDragOverView = null; 202f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private boolean mCreateUserFolderOnDrop = false; 203f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 204014ea4c15d147794789b9c5bf4e243fa08781ad9Andy Huang // Variables relating to touch disambiguation (scrolling workspace vs. scrolling a widget) 205014ea4c15d147794789b9c5bf4e243fa08781ad9Andy Huang private float mXDown; 206f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mYDown; 207014ea4c15d147794789b9c5bf4e243fa08781ad9Andy Huang final static float START_DAMPING_TOUCH_SLOP_ANGLE = (float) Math.PI / 6; 208f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp final static float MAX_SWIPE_ANGLE = (float) Math.PI / 3; 209f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp final static float TOUCH_SLOP_DAMPING_FACTOR = 4; 210f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 2111abfcaf0ee345acee28f0b4892314119082b28a2Mark Wei // These variables are used for storing the initial and final values during workspace animations 2121abfcaf0ee345acee28f0b4892314119082b28a2Mark Wei private int mSavedScrollX; 2131abfcaf0ee345acee28f0b4892314119082b28a2Mark Wei private float mSavedRotationY; 2141abfcaf0ee345acee28f0b4892314119082b28a2Mark Wei private float mSavedTranslationX; 215014ea4c15d147794789b9c5bf4e243fa08781ad9Andy Huang private float mCurrentScaleX; 216f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mCurrentScaleY; 217f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mCurrentRotationY; 218f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mCurrentTranslationX; 219f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mCurrentTranslationY; 220f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mOldTranslationXs; 221f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mOldTranslationYs; 222f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mOldScaleXs; 223f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mOldScaleYs; 224f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mOldBackgroundAlphas; 22551ad9041014920d78d9b7b3ab84ec04a7c41beaeVikram Aggarwal private float[] mOldBackgroundAlphaMultipliers; 226f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mOldAlphas; 227f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mOldRotationYs; 228f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mNewTranslationXs; 229f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mNewTranslationYs; 230f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mNewScaleXs; 2310e8a95148f7fdc9c6a33971924b0d29a202d73ecmindyp private float[] mNewScaleYs; 2320e8a95148f7fdc9c6a33971924b0d29a202d73ecmindyp private float[] mNewBackgroundAlphas; 2330e8a95148f7fdc9c6a33971924b0d29a202d73ecmindyp private float[] mNewBackgroundAlphaMultipliers; 234f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mNewAlphas; 235f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float[] mNewRotationYs; 236f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp private float mTransitionProgress; 2370a1aa1bb89221eda2f67af52ef274612f28ecf5cPaul Westbrook 2380a1aa1bb89221eda2f67af52ef274612f28ecf5cPaul Westbrook /** 239f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * Used to inflate the Workspace from XML. 240f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp * 241202738427ede23dd5863583aa3df17e4abfbf5e2Scott Kennedy * @param context The application's context. 242202738427ede23dd5863583aa3df17e4abfbf5e2Scott Kennedy * @param attrs The attributes set containing the Workspace's customization values. 243f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp */ 24477a4605e6fbc368b2b87b4888f2ffd6329620807mindyp public Workspace(Context context, AttributeSet attrs) { 245f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp this(context, attrs, 0); 246f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp } 24726d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp 24826d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp /** 24926d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp * Used to inflate the Workspace from XML. 25026d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp * 25126d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp * @param context The application's context. 25226d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp * @param attrs The attributes set containing the Workspace's customization values. 25326d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp * @param defStyle Unused. 25426d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp */ 25526d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp public Workspace(Context context, AttributeSet attrs, int defStyle) { 25626d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp super(context, attrs, defStyle); 25726d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp mContentIsRefreshable = false; 25826d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp 25926d4d2d9c43c499f458808f050ec73ea3c28dec4mindyp // With workspace, data is available straight from the get-go 26051ad9041014920d78d9b7b3ab84ec04a7c41beaeVikram Aggarwal setDataIsReady(); 261f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 262f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp mFadeInAdjacentScreens = 2631b3cc47f54072105c161d6ed557550e0e149b8bbmindyp getResources().getBoolean(R.bool.config_workspaceFadeAdjacentScreens); 2641b3cc47f54072105c161d6ed557550e0e149b8bbmindyp mWallpaperManager = WallpaperManager.getInstance(context); 2651b3cc47f54072105c161d6ed557550e0e149b8bbmindyp 2661b3cc47f54072105c161d6ed557550e0e149b8bbmindyp int cellCountX = DEFAULT_CELL_COUNT_X; 2671b3cc47f54072105c161d6ed557550e0e149b8bbmindyp int cellCountY = DEFAULT_CELL_COUNT_Y; 268f4fce1227d8b49f45e6569f1590565f2df9e8d6emindyp 269 TypedArray a = context.obtainStyledAttributes(attrs, 270 R.styleable.Workspace, defStyle, 0); 271 272 final Resources res = context.getResources(); 273 if (LauncherApplication.isScreenLarge()) { 274 // Determine number of rows/columns dynamically 275 // TODO: This code currently fails on tablets with an aspect ratio < 1.3. 276 // Around that ratio we should make cells the same size in portrait and 277 // landscape 278 TypedArray actionBarSizeTypedArray = 279 context.obtainStyledAttributes(new int[] { android.R.attr.actionBarSize }); 280 final float actionBarHeight = actionBarSizeTypedArray.getDimension(0, 0f); 281 final float systemBarHeight = res.getDimension(R.dimen.status_bar_height); 282 final float smallestScreenDim = res.getConfiguration().smallestScreenWidthDp; 283 284 cellCountX = 1; 285 while (CellLayout.widthInPortrait(res, cellCountX + 1) <= smallestScreenDim) { 286 cellCountX++; 287 } 288 289 cellCountY = 1; 290 while (actionBarHeight + CellLayout.heightInLandscape(res, cellCountY + 1) 291 <= smallestScreenDim - systemBarHeight) { 292 cellCountY++; 293 } 294 } 295 296 mSpringLoadedShrinkFactor = 297 res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f; 298 mDragViewMultiplyColor = res.getColor(R.color.drag_view_multiply_color); 299 300 // if the value is manually specified, use that instead 301 cellCountX = a.getInt(R.styleable.Workspace_cellCountX, cellCountX); 302 cellCountY = a.getInt(R.styleable.Workspace_cellCountY, cellCountY); 303 mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1); 304 a.recycle(); 305 306 LauncherModel.updateWorkspaceLayoutCells(cellCountX, cellCountY); 307 setHapticFeedbackEnabled(false); 308 309 mLauncher = (Launcher) context; 310 initWorkspace(); 311 312 // Disable multitouch across the workspace/all apps/customize tray 313 setMotionEventSplittingEnabled(true); 314 } 315 316 // estimate the size of a widget with spans hSpan, vSpan. return MAX_VALUE for each 317 // dimension if unsuccessful 318 public int[] estimateItemSize(int hSpan, int vSpan, 319 PendingAddItemInfo pendingItemInfo, boolean springLoaded) { 320 int[] size = new int[2]; 321 if (getChildCount() > 0) { 322 CellLayout cl = (CellLayout) mLauncher.getWorkspace().getChildAt(0); 323 RectF r = estimateItemPosition(cl, pendingItemInfo, 0, 0, hSpan, vSpan); 324 size[0] = (int) r.width(); 325 size[1] = (int) r.height(); 326 if (springLoaded) { 327 size[0] *= mSpringLoadedShrinkFactor; 328 size[1] *= mSpringLoadedShrinkFactor; 329 } 330 return size; 331 } else { 332 size[0] = Integer.MAX_VALUE; 333 size[1] = Integer.MAX_VALUE; 334 return size; 335 } 336 } 337 public RectF estimateItemPosition(CellLayout cl, ItemInfo pendingInfo, 338 int hCell, int vCell, int hSpan, int vSpan) { 339 RectF r = new RectF(); 340 cl.cellToRect(hCell, vCell, hSpan, vSpan, r); 341 if (pendingInfo instanceof PendingAddWidgetInfo) { 342 PendingAddWidgetInfo widgetInfo = (PendingAddWidgetInfo) pendingInfo; 343 Rect p = AppWidgetHostView.getDefaultPaddingForWidget(mContext, 344 widgetInfo.componentName, null); 345 r.top += p.top; 346 r.left += p.left; 347 r.right -= p.right; 348 r.bottom -= p.bottom; 349 } 350 return r; 351 } 352 353 public void buildPageHardwareLayers() { 354 if (getWindowToken() != null) { 355 final int childCount = getChildCount(); 356 for (int i = 0; i < childCount; i++) { 357 CellLayout cl = (CellLayout) getChildAt(i); 358 cl.buildChildrenLayer(); 359 } 360 } 361 } 362 363 public void onDragStart(DragSource source, Object info, int dragAction) { 364 mIsDragOccuring = true; 365 updateChildrenLayersEnabled(); 366 mLauncher.lockScreenOrientationOnLargeUI(); 367 } 368 369 public void onDragEnd() { 370 mIsDragOccuring = false; 371 updateChildrenLayersEnabled(); 372 mLauncher.unlockScreenOrientationOnLargeUI(); 373 } 374 375 /** 376 * Initializes various states for this workspace. 377 */ 378 protected void initWorkspace() { 379 Context context = getContext(); 380 mCurrentPage = mDefaultPage; 381 Launcher.setScreen(mCurrentPage); 382 LauncherApplication app = (LauncherApplication)context.getApplicationContext(); 383 mIconCache = app.getIconCache(); 384 mExternalDragOutlinePaint.setAntiAlias(true); 385 setWillNotDraw(false); 386 setChildrenDrawnWithCacheEnabled(true); 387 388 try { 389 final Resources res = getResources(); 390 mBackground = res.getDrawable(R.drawable.apps_customize_bg); 391 } catch (Resources.NotFoundException e) { 392 // In this case, we will skip drawing background protection 393 } 394 395 mChangeStateAnimationListener = new AnimatorListenerAdapter() { 396 @Override 397 public void onAnimationStart(Animator animation) { 398 mIsSwitchingState = true; 399 } 400 401 @Override 402 public void onAnimationEnd(Animator animation) { 403 mIsSwitchingState = false; 404 mWallpaperOffset.setOverrideHorizontalCatchupConstant(false); 405 updateChildrenLayersEnabled(); 406 } 407 }; 408 409 mWallpaperOffset = new WallpaperOffsetInterpolator(); 410 Display display = mLauncher.getWindowManager().getDefaultDisplay(); 411 mDisplayWidth = display.getWidth(); 412 mDisplayHeight = display.getHeight(); 413 mWallpaperTravelWidth = (int) (mDisplayWidth * 414 wallpaperTravelToScreenWidthRatio(mDisplayWidth, mDisplayHeight)); 415 416 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity); 417 418 } 419 420 @Override 421 protected int getScrollMode() { 422 return SmoothPagedView.X_LARGE_MODE; 423 } 424 425 @Override 426 protected void onViewAdded(View child) { 427 super.onViewAdded(child); 428 if (!(child instanceof CellLayout)) { 429 throw new IllegalArgumentException("A Workspace can only have CellLayout children."); 430 } 431 CellLayout cl = ((CellLayout) child); 432 cl.setOnInterceptTouchListener(this); 433 cl.setClickable(true); 434 cl.enableHardwareLayers(); 435 } 436 437 /** 438 * @return The open folder on the current screen, or null if there is none 439 */ 440 Folder getOpenFolder() { 441 DragLayer dragLayer = mLauncher.getDragLayer(); 442 int count = dragLayer.getChildCount(); 443 for (int i = 0; i < count; i++) { 444 View child = dragLayer.getChildAt(i); 445 if (child instanceof Folder) { 446 Folder folder = (Folder) child; 447 if (folder.getInfo().opened) 448 return folder; 449 } 450 } 451 return null; 452 } 453 454 boolean isTouchActive() { 455 return mTouchState != TOUCH_STATE_REST; 456 } 457 458 /** 459 * Adds the specified child in the specified screen. The position and dimension of 460 * the child are defined by x, y, spanX and spanY. 461 * 462 * @param child The child to add in one of the workspace's screens. 463 * @param screen The screen in which to add the child. 464 * @param x The X position of the child in the screen's grid. 465 * @param y The Y position of the child in the screen's grid. 466 * @param spanX The number of cells spanned horizontally by the child. 467 * @param spanY The number of cells spanned vertically by the child. 468 */ 469 void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY) { 470 addInScreen(child, container, screen, x, y, spanX, spanY, false); 471 } 472 473 /** 474 * Adds the specified child in the specified screen. The position and dimension of 475 * the child are defined by x, y, spanX and spanY. 476 * 477 * @param child The child to add in one of the workspace's screens. 478 * @param screen The screen in which to add the child. 479 * @param x The X position of the child in the screen's grid. 480 * @param y The Y position of the child in the screen's grid. 481 * @param spanX The number of cells spanned horizontally by the child. 482 * @param spanY The number of cells spanned vertically by the child. 483 * @param insert When true, the child is inserted at the beginning of the children list. 484 */ 485 void addInScreen(View child, long container, int screen, int x, int y, int spanX, int spanY, 486 boolean insert) { 487 if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { 488 if (screen < 0 || screen >= getChildCount()) { 489 Log.e(TAG, "The screen must be >= 0 and < " + getChildCount() 490 + " (was " + screen + "); skipping child"); 491 return; 492 } 493 } 494 495 final CellLayout layout; 496 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 497 layout = mLauncher.getHotseat().getLayout(); 498 child.setOnKeyListener(null); 499 500 // Hide folder title in the hotseat 501 if (child instanceof FolderIcon) { 502 ((FolderIcon) child).setTextVisible(false); 503 } 504 505 if (screen < 0) { 506 screen = mLauncher.getHotseat().getOrderInHotseat(x, y); 507 } else { 508 // Note: We do this to ensure that the hotseat is always laid out in the orientation 509 // of the hotseat in order regardless of which orientation they were added 510 x = mLauncher.getHotseat().getCellXFromOrder(screen); 511 y = mLauncher.getHotseat().getCellYFromOrder(screen); 512 } 513 } else { 514 // Show folder title if not in the hotseat 515 if (child instanceof FolderIcon) { 516 ((FolderIcon) child).setTextVisible(true); 517 } 518 519 layout = (CellLayout) getChildAt(screen); 520 child.setOnKeyListener(new IconKeyEventListener()); 521 } 522 523 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); 524 if (lp == null) { 525 lp = new CellLayout.LayoutParams(x, y, spanX, spanY); 526 } else { 527 lp.cellX = x; 528 lp.cellY = y; 529 lp.cellHSpan = spanX; 530 lp.cellVSpan = spanY; 531 } 532 533 if (spanX < 0 && spanY < 0) { 534 lp.isLockedToGrid = false; 535 } 536 537 // Get the canonical child id to uniquely represent this view in this screen 538 int childId = LauncherModel.getCellLayoutChildId(container, screen, x, y, spanX, spanY); 539 boolean markCellsAsOccupied = !(child instanceof Folder); 540 if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) { 541 // TODO: This branch occurs when the workspace is adding views 542 // outside of the defined grid 543 // maybe we should be deleting these items from the LauncherModel? 544 Log.w(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout"); 545 } 546 547 if (!(child instanceof Folder)) { 548 child.setHapticFeedbackEnabled(false); 549 child.setOnLongClickListener(mLongClickListener); 550 } 551 if (child instanceof DropTarget) { 552 mDragController.addDropTarget((DropTarget) child); 553 } 554 } 555 556 /** 557 * Check if the point (x, y) hits a given page. 558 */ 559 private boolean hitsPage(int index, float x, float y) { 560 final View page = getChildAt(index); 561 if (page != null) { 562 float[] localXY = { x, y }; 563 mapPointFromSelfToChild(page, localXY); 564 return (localXY[0] >= 0 && localXY[0] < page.getWidth() 565 && localXY[1] >= 0 && localXY[1] < page.getHeight()); 566 } 567 return false; 568 } 569 570 @Override 571 protected boolean hitsPreviousPage(float x, float y) { 572 // mNextPage is set to INVALID_PAGE whenever we are stationary. 573 // Calculating "next page" this way ensures that you scroll to whatever page you tap on 574 final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage; 575 576 // Only allow tap to next page on large devices, where there's significant margin outside 577 // the active workspace 578 return LauncherApplication.isScreenLarge() && hitsPage(current - 1, x, y); 579 } 580 581 @Override 582 protected boolean hitsNextPage(float x, float y) { 583 // mNextPage is set to INVALID_PAGE whenever we are stationary. 584 // Calculating "next page" this way ensures that you scroll to whatever page you tap on 585 final int current = (mNextPage == INVALID_PAGE) ? mCurrentPage : mNextPage; 586 587 // Only allow tap to next page on large devices, where there's significant margin outside 588 // the active workspace 589 return LauncherApplication.isScreenLarge() && hitsPage(current + 1, x, y); 590 } 591 592 /** 593 * Called directly from a CellLayout (not by the framework), after we've been added as a 594 * listener via setOnInterceptTouchEventListener(). This allows us to tell the CellLayout 595 * that it should intercept touch events, which is not something that is normally supported. 596 */ 597 @Override 598 public boolean onTouch(View v, MotionEvent event) { 599 return (isSmall() || mIsSwitchingState); 600 } 601 602 public boolean isSwitchingState() { 603 return mIsSwitchingState; 604 } 605 606 protected void onWindowVisibilityChanged (int visibility) { 607 mLauncher.onWindowVisibilityChanged(visibility); 608 } 609 610 @Override 611 public boolean dispatchUnhandledMove(View focused, int direction) { 612 if (isSmall() || mIsSwitchingState) { 613 // when the home screens are shrunken, shouldn't allow side-scrolling 614 return false; 615 } 616 return super.dispatchUnhandledMove(focused, direction); 617 } 618 619 @Override 620 public boolean onInterceptTouchEvent(MotionEvent ev) { 621 switch (ev.getAction() & MotionEvent.ACTION_MASK) { 622 case MotionEvent.ACTION_DOWN: 623 mXDown = ev.getX(); 624 mYDown = ev.getY(); 625 break; 626 case MotionEvent.ACTION_POINTER_UP: 627 case MotionEvent.ACTION_UP: 628 if (mTouchState == TOUCH_STATE_REST) { 629 final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage); 630 if (!currentPage.lastDownOnOccupiedCell()) { 631 onWallpaperTap(ev); 632 } 633 } 634 } 635 return super.onInterceptTouchEvent(ev); 636 } 637 638 @Override 639 protected void determineScrollingStart(MotionEvent ev) { 640 if (!isSmall() && !mIsSwitchingState) { 641 float deltaX = Math.abs(ev.getX() - mXDown); 642 float deltaY = Math.abs(ev.getY() - mYDown); 643 644 if (Float.compare(deltaX, 0f) == 0) return; 645 646 float slope = deltaY / deltaX; 647 float theta = (float) Math.atan(slope); 648 649 if (deltaX > mTouchSlop || deltaY > mTouchSlop) { 650 cancelCurrentPageLongPress(); 651 } 652 653 if (theta > MAX_SWIPE_ANGLE) { 654 // Above MAX_SWIPE_ANGLE, we don't want to ever start scrolling the workspace 655 return; 656 } else if (theta > START_DAMPING_TOUCH_SLOP_ANGLE) { 657 // Above START_DAMPING_TOUCH_SLOP_ANGLE and below MAX_SWIPE_ANGLE, we want to 658 // increase the touch slop to make it harder to begin scrolling the workspace. This 659 // results in vertically scrolling widgets to more easily. The higher the angle, the 660 // more we increase touch slop. 661 theta -= START_DAMPING_TOUCH_SLOP_ANGLE; 662 float extraRatio = (float) 663 Math.sqrt((theta / (MAX_SWIPE_ANGLE - START_DAMPING_TOUCH_SLOP_ANGLE))); 664 super.determineScrollingStart(ev, 1 + TOUCH_SLOP_DAMPING_FACTOR * extraRatio); 665 } else { 666 // Below START_DAMPING_TOUCH_SLOP_ANGLE, we don't do anything special 667 super.determineScrollingStart(ev); 668 } 669 } 670 } 671 672 @Override 673 protected boolean isScrollingIndicatorEnabled() { 674 return mState != State.SPRING_LOADED; 675 } 676 677 protected void onPageBeginMoving() { 678 super.onPageBeginMoving(); 679 680 if (isHardwareAccelerated()) { 681 updateChildrenLayersEnabled(); 682 } else { 683 if (mNextPage != INVALID_PAGE) { 684 // we're snapping to a particular screen 685 enableChildrenCache(mCurrentPage, mNextPage); 686 } else { 687 // this is when user is actively dragging a particular screen, they might 688 // swipe it either left or right (but we won't advance by more than one screen) 689 enableChildrenCache(mCurrentPage - 1, mCurrentPage + 1); 690 } 691 } 692 693 // Only show page outlines as we pan if we are on large screen 694 if (LauncherApplication.isScreenLarge()) { 695 showOutlines(); 696 } 697 } 698 699 protected void onPageEndMoving() { 700 super.onPageEndMoving(); 701 702 if (isHardwareAccelerated()) { 703 updateChildrenLayersEnabled(); 704 } else { 705 clearChildrenCache(); 706 } 707 708 // Hide the outlines, as long as we're not dragging 709 if (!mDragController.dragging()) { 710 // Only hide page outlines as we pan if we are on large screen 711 if (LauncherApplication.isScreenLarge()) { 712 hideOutlines(); 713 } 714 } 715 mOverScrollMaxBackgroundAlpha = 0.0f; 716 mOverScrollPageIndex = -1; 717 718 if (mDelayedResizeRunnable != null) { 719 mDelayedResizeRunnable.run(); 720 mDelayedResizeRunnable = null; 721 } 722 } 723 724 @Override 725 protected void notifyPageSwitchListener() { 726 super.notifyPageSwitchListener(); 727 Launcher.setScreen(mCurrentPage); 728 }; 729 730 // As a ratio of screen height, the total distance we want the parallax effect to span 731 // horizontally 732 private float wallpaperTravelToScreenWidthRatio(int width, int height) { 733 float aspectRatio = width / (float) height; 734 735 // At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width 736 // At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width 737 // We will use these two data points to extrapolate how much the wallpaper parallax effect 738 // to span (ie travel) at any aspect ratio: 739 740 final float ASPECT_RATIO_LANDSCAPE = 16/10f; 741 final float ASPECT_RATIO_PORTRAIT = 10/16f; 742 final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f; 743 final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f; 744 745 // To find out the desired width at different aspect ratios, we use the following two 746 // formulas, where the coefficient on x is the aspect ratio (width/height): 747 // (16/10)x + y = 1.5 748 // (10/16)x + y = 1.2 749 // We solve for x and y and end up with a final formula: 750 final float x = 751 (WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) / 752 (ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT); 753 final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT; 754 return x * aspectRatio + y; 755 } 756 757 // The range of scroll values for Workspace 758 private int getScrollRange() { 759 return getChildOffset(getChildCount() - 1) - getChildOffset(0); 760 } 761 762 protected void setWallpaperDimension() { 763 DisplayMetrics displayMetrics = new DisplayMetrics(); 764 mLauncher.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics); 765 final int maxDim = Math.max(displayMetrics.widthPixels, displayMetrics.heightPixels); 766 final int minDim = Math.min(displayMetrics.widthPixels, displayMetrics.heightPixels); 767 768 // We need to ensure that there is enough extra space in the wallpaper for the intended 769 // parallax effects 770 if (LauncherApplication.isScreenLarge()) { 771 mWallpaperWidth = (int) (maxDim * wallpaperTravelToScreenWidthRatio(maxDim, minDim)); 772 mWallpaperHeight = maxDim; 773 } else { 774 mWallpaperWidth = Math.max((int) (minDim * WALLPAPER_SCREENS_SPAN), maxDim); 775 mWallpaperHeight = maxDim; 776 } 777 new Thread("setWallpaperDimension") { 778 public void run() { 779 mWallpaperManager.suggestDesiredDimensions(mWallpaperWidth, mWallpaperHeight); 780 } 781 }.start(); 782 } 783 784 public void setVerticalWallpaperOffset(float offset) { 785 mWallpaperOffset.setFinalY(offset); 786 } 787 public float getVerticalWallpaperOffset() { 788 return mWallpaperOffset.getCurrY(); 789 } 790 public void setHorizontalWallpaperOffset(float offset) { 791 mWallpaperOffset.setFinalX(offset); 792 } 793 public float getHorizontalWallpaperOffset() { 794 return mWallpaperOffset.getCurrX(); 795 } 796 797 private float wallpaperOffsetForCurrentScroll() { 798 // The wallpaper travel width is how far, from left to right, the wallpaper will move 799 // at this orientation. On tablets in portrait mode we don't move all the way to the 800 // edges of the wallpaper, or otherwise the parallax effect would be too strong. 801 int wallpaperTravelWidth = mWallpaperWidth; 802 if (LauncherApplication.isScreenLarge()) { 803 wallpaperTravelWidth = mWallpaperTravelWidth; 804 } 805 806 // Set wallpaper offset steps (1 / (number of screens - 1)) 807 mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 1.0f); 808 809 // For the purposes of computing the scrollRange and overScrollOffset, we assume 810 // that mLayoutScale is 1. This means that when we're in spring-loaded mode, 811 // there's no discrepancy between the wallpaper offset for a given page. 812 float layoutScale = mLayoutScale; 813 mLayoutScale = 1f; 814 int scrollRange = getScrollRange(); 815 816 // Again, we adjust the wallpaper offset to be consistent between values of mLayoutScale 817 float adjustedScrollX = Math.max(0, Math.min(mScrollX, mMaxScrollX)); 818 adjustedScrollX *= mWallpaperScrollRatio; 819 mLayoutScale = layoutScale; 820 821 float scrollProgress = 822 adjustedScrollX / (float) scrollRange; 823 float offsetInDips = wallpaperTravelWidth * scrollProgress + 824 (mWallpaperWidth - wallpaperTravelWidth) / 2; // center it 825 float offset = offsetInDips / (float) mWallpaperWidth; 826 return offset; 827 } 828 private void syncWallpaperOffsetWithScroll() { 829 final boolean enableWallpaperEffects = isHardwareAccelerated(); 830 if (enableWallpaperEffects) { 831 mWallpaperOffset.setFinalX(wallpaperOffsetForCurrentScroll()); 832 } 833 } 834 835 public void updateWallpaperOffsetImmediately() { 836 mUpdateWallpaperOffsetImmediately = true; 837 } 838 839 private void updateWallpaperOffsets() { 840 boolean updateNow = false; 841 boolean keepUpdating = true; 842 if (mUpdateWallpaperOffsetImmediately) { 843 updateNow = true; 844 keepUpdating = false; 845 mWallpaperOffset.jumpToFinal(); 846 mUpdateWallpaperOffsetImmediately = false; 847 } else { 848 updateNow = keepUpdating = mWallpaperOffset.computeScrollOffset(); 849 } 850 if (updateNow) { 851 if (mWindowToken != null) { 852 mWallpaperManager.setWallpaperOffsets(mWindowToken, 853 mWallpaperOffset.getCurrX(), mWallpaperOffset.getCurrY()); 854 } 855 } 856 if (keepUpdating) { 857 invalidate(); 858 } 859 } 860 861 @Override 862 protected void updateCurrentPageScroll() { 863 super.updateCurrentPageScroll(); 864 computeWallpaperScrollRatio(mCurrentPage); 865 } 866 867 @Override 868 protected void snapToPage(int whichPage) { 869 super.snapToPage(whichPage); 870 computeWallpaperScrollRatio(whichPage); 871 } 872 873 private void computeWallpaperScrollRatio(int page) { 874 // Here, we determine what the desired scroll would be with and without a layout scale, 875 // and compute a ratio between the two. This allows us to adjust the wallpaper offset 876 // as though there is no layout scale. 877 float layoutScale = mLayoutScale; 878 int scaled = getChildOffset(page) - getRelativeChildOffset(page); 879 mLayoutScale = 1.0f; 880 float unscaled = getChildOffset(page) - getRelativeChildOffset(page); 881 mLayoutScale = layoutScale; 882 if (scaled > 0) { 883 mWallpaperScrollRatio = (1.0f * unscaled) / scaled; 884 } else { 885 mWallpaperScrollRatio = 1f; 886 } 887 } 888 889 class WallpaperOffsetInterpolator { 890 float mFinalHorizontalWallpaperOffset = 0.0f; 891 float mFinalVerticalWallpaperOffset = 0.5f; 892 float mHorizontalWallpaperOffset = 0.0f; 893 float mVerticalWallpaperOffset = 0.5f; 894 long mLastWallpaperOffsetUpdateTime; 895 boolean mIsMovingFast; 896 boolean mOverrideHorizontalCatchupConstant; 897 float mHorizontalCatchupConstant = 0.35f; 898 float mVerticalCatchupConstant = 0.35f; 899 900 public WallpaperOffsetInterpolator() { 901 } 902 903 public void setOverrideHorizontalCatchupConstant(boolean override) { 904 mOverrideHorizontalCatchupConstant = override; 905 } 906 907 public void setHorizontalCatchupConstant(float f) { 908 mHorizontalCatchupConstant = f; 909 } 910 911 public void setVerticalCatchupConstant(float f) { 912 mVerticalCatchupConstant = f; 913 } 914 915 public boolean computeScrollOffset() { 916 if (Float.compare(mHorizontalWallpaperOffset, mFinalHorizontalWallpaperOffset) == 0 && 917 Float.compare(mVerticalWallpaperOffset, mFinalVerticalWallpaperOffset) == 0) { 918 mIsMovingFast = false; 919 return false; 920 } 921 boolean isLandscape = mDisplayWidth > mDisplayHeight; 922 923 long currentTime = System.currentTimeMillis(); 924 long timeSinceLastUpdate = currentTime - mLastWallpaperOffsetUpdateTime; 925 timeSinceLastUpdate = Math.min((long) (1000/30f), timeSinceLastUpdate); 926 timeSinceLastUpdate = Math.max(1L, timeSinceLastUpdate); 927 928 float xdiff = Math.abs(mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset); 929 if (!mIsMovingFast && xdiff > 0.07) { 930 mIsMovingFast = true; 931 } 932 933 float fractionToCatchUpIn1MsHorizontal; 934 if (mOverrideHorizontalCatchupConstant) { 935 fractionToCatchUpIn1MsHorizontal = mHorizontalCatchupConstant; 936 } else if (mIsMovingFast) { 937 fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.5f : 0.75f; 938 } else { 939 // slow 940 fractionToCatchUpIn1MsHorizontal = isLandscape ? 0.27f : 0.5f; 941 } 942 float fractionToCatchUpIn1MsVertical = mVerticalCatchupConstant; 943 944 fractionToCatchUpIn1MsHorizontal /= 33f; 945 fractionToCatchUpIn1MsVertical /= 33f; 946 947 final float UPDATE_THRESHOLD = 0.00001f; 948 float hOffsetDelta = mFinalHorizontalWallpaperOffset - mHorizontalWallpaperOffset; 949 float vOffsetDelta = mFinalVerticalWallpaperOffset - mVerticalWallpaperOffset; 950 boolean jumpToFinalValue = Math.abs(hOffsetDelta) < UPDATE_THRESHOLD && 951 Math.abs(vOffsetDelta) < UPDATE_THRESHOLD; 952 953 // Don't have any lag between workspace and wallpaper on non-large devices 954 if (!LauncherApplication.isScreenLarge() || jumpToFinalValue) { 955 mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset; 956 mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset; 957 } else { 958 float percentToCatchUpVertical = 959 Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsVertical); 960 float percentToCatchUpHorizontal = 961 Math.min(1.0f, timeSinceLastUpdate * fractionToCatchUpIn1MsHorizontal); 962 mHorizontalWallpaperOffset += percentToCatchUpHorizontal * hOffsetDelta; 963 mVerticalWallpaperOffset += percentToCatchUpVertical * vOffsetDelta; 964 } 965 966 mLastWallpaperOffsetUpdateTime = System.currentTimeMillis(); 967 return true; 968 } 969 970 public float getCurrX() { 971 return mHorizontalWallpaperOffset; 972 } 973 974 public float getFinalX() { 975 return mFinalHorizontalWallpaperOffset; 976 } 977 978 public float getCurrY() { 979 return mVerticalWallpaperOffset; 980 } 981 982 public float getFinalY() { 983 return mFinalVerticalWallpaperOffset; 984 } 985 986 public void setFinalX(float x) { 987 mFinalHorizontalWallpaperOffset = Math.max(0f, Math.min(x, 1.0f)); 988 } 989 990 public void setFinalY(float y) { 991 mFinalVerticalWallpaperOffset = Math.max(0f, Math.min(y, 1.0f)); 992 } 993 994 public void jumpToFinal() { 995 mHorizontalWallpaperOffset = mFinalHorizontalWallpaperOffset; 996 mVerticalWallpaperOffset = mFinalVerticalWallpaperOffset; 997 } 998 } 999 1000 @Override 1001 public void computeScroll() { 1002 super.computeScroll(); 1003 syncWallpaperOffsetWithScroll(); 1004 } 1005 1006 void showOutlines() { 1007 if (!isSmall() && !mIsSwitchingState) { 1008 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 1009 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 1010 mChildrenOutlineFadeInAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 1.0f); 1011 mChildrenOutlineFadeInAnimation.setDuration(CHILDREN_OUTLINE_FADE_IN_DURATION); 1012 mChildrenOutlineFadeInAnimation.start(); 1013 } 1014 } 1015 1016 void hideOutlines() { 1017 if (!isSmall() && !mIsSwitchingState) { 1018 if (mChildrenOutlineFadeInAnimation != null) mChildrenOutlineFadeInAnimation.cancel(); 1019 if (mChildrenOutlineFadeOutAnimation != null) mChildrenOutlineFadeOutAnimation.cancel(); 1020 mChildrenOutlineFadeOutAnimation = ObjectAnimator.ofFloat(this, "childrenOutlineAlpha", 0.0f); 1021 mChildrenOutlineFadeOutAnimation.setDuration(CHILDREN_OUTLINE_FADE_OUT_DURATION); 1022 mChildrenOutlineFadeOutAnimation.setStartDelay(CHILDREN_OUTLINE_FADE_OUT_DELAY); 1023 mChildrenOutlineFadeOutAnimation.start(); 1024 } 1025 } 1026 1027 public void showOutlinesTemporarily() { 1028 if (!mIsPageMoving && !isTouchActive()) { 1029 snapToPage(mCurrentPage); 1030 } 1031 } 1032 1033 public void setChildrenOutlineAlpha(float alpha) { 1034 mChildrenOutlineAlpha = alpha; 1035 for (int i = 0; i < getChildCount(); i++) { 1036 CellLayout cl = (CellLayout) getChildAt(i); 1037 cl.setBackgroundAlpha(alpha); 1038 } 1039 } 1040 1041 public float getChildrenOutlineAlpha() { 1042 return mChildrenOutlineAlpha; 1043 } 1044 1045 void disableBackground() { 1046 mDrawBackground = false; 1047 } 1048 void enableBackground() { 1049 mDrawBackground = true; 1050 } 1051 1052 private void animateBackgroundGradient(float finalAlpha, boolean animated) { 1053 if (mBackground == null) return; 1054 if (mBackgroundFadeInAnimation != null) { 1055 mBackgroundFadeInAnimation.cancel(); 1056 mBackgroundFadeInAnimation = null; 1057 } 1058 if (mBackgroundFadeOutAnimation != null) { 1059 mBackgroundFadeOutAnimation.cancel(); 1060 mBackgroundFadeOutAnimation = null; 1061 } 1062 float startAlpha = getBackgroundAlpha(); 1063 if (finalAlpha != startAlpha) { 1064 if (animated) { 1065 mBackgroundFadeOutAnimation = ValueAnimator.ofFloat(startAlpha, finalAlpha); 1066 mBackgroundFadeOutAnimation.addUpdateListener(new AnimatorUpdateListener() { 1067 public void onAnimationUpdate(ValueAnimator animation) { 1068 setBackgroundAlpha(((Float) animation.getAnimatedValue()).floatValue()); 1069 } 1070 }); 1071 mBackgroundFadeOutAnimation.setInterpolator(new DecelerateInterpolator(1.5f)); 1072 mBackgroundFadeOutAnimation.setDuration(BACKGROUND_FADE_OUT_DURATION); 1073 mBackgroundFadeOutAnimation.start(); 1074 } else { 1075 setBackgroundAlpha(finalAlpha); 1076 } 1077 } 1078 } 1079 1080 public void setBackgroundAlpha(float alpha) { 1081 if (alpha != mBackgroundAlpha) { 1082 mBackgroundAlpha = alpha; 1083 invalidate(); 1084 } 1085 } 1086 1087 public float getBackgroundAlpha() { 1088 return mBackgroundAlpha; 1089 } 1090 1091 /** 1092 * Due to 3D transformations, if two CellLayouts are theoretically touching each other, 1093 * on the xy plane, when one is rotated along the y-axis, the gap between them is perceived 1094 * as being larger. This method computes what offset the rotated view should be translated 1095 * in order to minimize this perceived gap. 1096 * @param degrees Angle of the view 1097 * @param width Width of the view 1098 * @param height Height of the view 1099 * @return Offset to be used in a View.setTranslationX() call 1100 */ 1101 private float getOffsetXForRotation(float degrees, int width, int height) { 1102 mMatrix.reset(); 1103 mCamera.save(); 1104 mCamera.rotateY(Math.abs(degrees)); 1105 mCamera.getMatrix(mMatrix); 1106 mCamera.restore(); 1107 1108 mMatrix.preTranslate(-width * 0.5f, -height * 0.5f); 1109 mMatrix.postTranslate(width * 0.5f, height * 0.5f); 1110 mTempFloat2[0] = width; 1111 mTempFloat2[1] = height; 1112 mMatrix.mapPoints(mTempFloat2); 1113 return (width - mTempFloat2[0]) * (degrees > 0.0f ? 1.0f : -1.0f); 1114 } 1115 1116 float backgroundAlphaInterpolator(float r) { 1117 float pivotA = 0.1f; 1118 float pivotB = 0.4f; 1119 if (r < pivotA) { 1120 return 0; 1121 } else if (r > pivotB) { 1122 return 1.0f; 1123 } else { 1124 return (r - pivotA)/(pivotB - pivotA); 1125 } 1126 } 1127 1128 float overScrollBackgroundAlphaInterpolator(float r) { 1129 float threshold = 0.08f; 1130 1131 if (r > mOverScrollMaxBackgroundAlpha) { 1132 mOverScrollMaxBackgroundAlpha = r; 1133 } else if (r < mOverScrollMaxBackgroundAlpha) { 1134 r = mOverScrollMaxBackgroundAlpha; 1135 } 1136 1137 return Math.min(r / threshold, 1.0f); 1138 } 1139 1140 private void screenScrolledLargeUI(int screenCenter) { 1141 if (isSwitchingState()) return; 1142 boolean isInOverscroll = false; 1143 for (int i = 0; i < getChildCount(); i++) { 1144 CellLayout cl = (CellLayout) getChildAt(i); 1145 if (cl != null) { 1146 float scrollProgress = getScrollProgress(screenCenter, cl, i); 1147 float rotation = WORKSPACE_ROTATION * scrollProgress; 1148 float translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1149 1150 // If the current page (i) is being over scrolled, we use a different 1151 // set of rules for setting the background alpha multiplier. 1152 if (!isSmall()) { 1153 if ((mOverScrollX < 0 && i == 0) || (mOverScrollX > mMaxScrollX && 1154 i == getChildCount() -1)) { 1155 isInOverscroll = true; 1156 rotation *= -1; 1157 cl.setBackgroundAlphaMultiplier( 1158 overScrollBackgroundAlphaInterpolator(Math.abs(scrollProgress))); 1159 mOverScrollPageIndex = i; 1160 cl.setOverScrollAmount(Math.abs(scrollProgress), i == 0); 1161 cl.setPivotX(cl.getMeasuredWidth() * (i == 0 ? 0.75f : 0.25f)); 1162 cl.setPivotY(cl.getMeasuredHeight() * 0.5f); 1163 cl.setOverscrollTransformsDirty(true); 1164 } else if (mOverScrollPageIndex != i) { 1165 cl.setBackgroundAlphaMultiplier( 1166 backgroundAlphaInterpolator(Math.abs(scrollProgress))); 1167 } 1168 } 1169 cl.setTranslationX(translationX); 1170 cl.setRotationY(rotation); 1171 if (mFadeInAdjacentScreens && !isSmall()) { 1172 float alpha = 1 - Math.abs(scrollProgress); 1173 cl.setAlpha(alpha); 1174 } 1175 } 1176 } 1177 if (!isSwitchingState() && !isInOverscroll) { 1178 ((CellLayout) getChildAt(0)).resetOverscrollTransforms(); 1179 ((CellLayout) getChildAt(getChildCount() - 1)).resetOverscrollTransforms(); 1180 } 1181 invalidate(); 1182 } 1183 1184 private void screenScrolledStandardUI(int screenCenter) { 1185 if (mOverScrollX < 0 || mOverScrollX > mMaxScrollX) { 1186 int index = mOverScrollX < 0 ? 0 : getChildCount() - 1; 1187 CellLayout cl = (CellLayout) getChildAt(index); 1188 float scrollProgress = getScrollProgress(screenCenter, cl, index); 1189 cl.setOverScrollAmount(Math.abs(scrollProgress), index == 0); 1190 float rotation = - WORKSPACE_OVERSCROLL_ROTATION * scrollProgress; 1191 cl.setCameraDistance(mDensity * CAMERA_DISTANCE); 1192 cl.setPivotX(cl.getMeasuredWidth() * (index == 0 ? 0.75f : 0.25f)); 1193 cl.setPivotY(cl.getMeasuredHeight() * 0.5f); 1194 cl.setRotationY(rotation); 1195 cl.setOverscrollTransformsDirty(true); 1196 setFadeForOverScroll(Math.abs(scrollProgress)); 1197 } else { 1198 if (mOverscrollFade != 0) { 1199 setFadeForOverScroll(0); 1200 } 1201 // We don't want to mess with the translations during transitions 1202 if (!isSwitchingState()) { 1203 ((CellLayout) getChildAt(0)).resetOverscrollTransforms(); 1204 ((CellLayout) getChildAt(getChildCount() - 1)).resetOverscrollTransforms(); 1205 } 1206 } 1207 } 1208 1209 @Override 1210 protected void screenScrolled(int screenCenter) { 1211 if (LauncherApplication.isScreenLarge()) { 1212 // We don't call super.screenScrolled() here because we handle the adjacent pages alpha 1213 // ourselves (for efficiency), and there are no scrolling indicators to update. 1214 screenScrolledLargeUI(screenCenter); 1215 } else { 1216 super.screenScrolled(screenCenter); 1217 screenScrolledStandardUI(screenCenter); 1218 } 1219 } 1220 1221 @Override 1222 protected void overScroll(float amount) { 1223 if (LauncherApplication.isScreenLarge()) { 1224 dampedOverScroll(amount); 1225 } else { 1226 acceleratedOverScroll(amount); 1227 } 1228 } 1229 1230 protected void onAttachedToWindow() { 1231 super.onAttachedToWindow(); 1232 mWindowToken = getWindowToken(); 1233 computeScroll(); 1234 mDragController.setWindowToken(mWindowToken); 1235 } 1236 1237 protected void onDetachedFromWindow() { 1238 mWindowToken = null; 1239 } 1240 1241 @Override 1242 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 1243 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) { 1244 mUpdateWallpaperOffsetImmediately = true; 1245 } 1246 super.onLayout(changed, left, top, right, bottom); 1247 } 1248 1249 @Override 1250 protected void onDraw(Canvas canvas) { 1251 updateWallpaperOffsets(); 1252 1253 // Draw the background gradient if necessary 1254 if (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground) { 1255 int alpha = (int) (mBackgroundAlpha * 255); 1256 mBackground.setAlpha(alpha); 1257 mBackground.setBounds(mScrollX, 0, mScrollX + getMeasuredWidth(), 1258 getMeasuredHeight()); 1259 mBackground.draw(canvas); 1260 } 1261 1262 super.onDraw(canvas); 1263 } 1264 1265 boolean isDrawingBackgroundGradient() { 1266 return (mBackground != null && mBackgroundAlpha > 0.0f && mDrawBackground); 1267 } 1268 1269 @Override 1270 protected void dispatchDraw(Canvas canvas) { 1271 super.dispatchDraw(canvas); 1272 1273 if (mInScrollArea && !LauncherApplication.isScreenLarge()) { 1274 final int width = getWidth(); 1275 final int height = getHeight(); 1276 final int pageHeight = getChildAt(0).getHeight(); 1277 1278 // Set the height of the outline to be the height of the page 1279 final int offset = (height - pageHeight - mPaddingTop - mPaddingBottom) / 2; 1280 final int paddingTop = mPaddingTop + offset; 1281 final int paddingBottom = mPaddingBottom + offset; 1282 1283 final CellLayout leftPage = (CellLayout) getChildAt(mCurrentPage - 1); 1284 final CellLayout rightPage = (CellLayout) getChildAt(mCurrentPage + 1); 1285 1286 if (leftPage != null && leftPage.getIsDragOverlapping()) { 1287 final Drawable d = getResources().getDrawable(R.drawable.page_hover_left_holo); 1288 d.setBounds(mScrollX, paddingTop, mScrollX + d.getIntrinsicWidth(), 1289 height - paddingBottom); 1290 d.draw(canvas); 1291 } else if (rightPage != null && rightPage.getIsDragOverlapping()) { 1292 final Drawable d = getResources().getDrawable(R.drawable.page_hover_right_holo); 1293 d.setBounds(mScrollX + width - d.getIntrinsicWidth(), paddingTop, mScrollX + width, 1294 height - paddingBottom); 1295 d.draw(canvas); 1296 } 1297 } 1298 } 1299 1300 @Override 1301 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 1302 if (!mLauncher.isAllAppsVisible()) { 1303 final Folder openFolder = getOpenFolder(); 1304 if (openFolder != null) { 1305 return openFolder.requestFocus(direction, previouslyFocusedRect); 1306 } else { 1307 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 1308 } 1309 } 1310 return false; 1311 } 1312 1313 @Override 1314 public int getDescendantFocusability() { 1315 if (isSmall()) { 1316 return ViewGroup.FOCUS_BLOCK_DESCENDANTS; 1317 } 1318 return super.getDescendantFocusability(); 1319 } 1320 1321 @Override 1322 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1323 if (!mLauncher.isAllAppsVisible()) { 1324 final Folder openFolder = getOpenFolder(); 1325 if (openFolder != null) { 1326 openFolder.addFocusables(views, direction); 1327 } else { 1328 super.addFocusables(views, direction, focusableMode); 1329 } 1330 } 1331 } 1332 1333 public boolean isSmall() { 1334 return mState == State.SMALL || mState == State.SPRING_LOADED; 1335 } 1336 1337 void enableChildrenCache(int fromPage, int toPage) { 1338 if (fromPage > toPage) { 1339 final int temp = fromPage; 1340 fromPage = toPage; 1341 toPage = temp; 1342 } 1343 1344 final int screenCount = getChildCount(); 1345 1346 fromPage = Math.max(fromPage, 0); 1347 toPage = Math.min(toPage, screenCount - 1); 1348 1349 for (int i = fromPage; i <= toPage; i++) { 1350 final CellLayout layout = (CellLayout) getChildAt(i); 1351 layout.setChildrenDrawnWithCacheEnabled(true); 1352 layout.setChildrenDrawingCacheEnabled(true); 1353 } 1354 } 1355 1356 void clearChildrenCache() { 1357 final int screenCount = getChildCount(); 1358 for (int i = 0; i < screenCount; i++) { 1359 final CellLayout layout = (CellLayout) getChildAt(i); 1360 layout.setChildrenDrawnWithCacheEnabled(false); 1361 // In software mode, we don't want the items to continue to be drawn into bitmaps 1362 if (!isHardwareAccelerated()) { 1363 layout.setChildrenDrawingCacheEnabled(false); 1364 } 1365 } 1366 } 1367 1368 private void updateChildrenLayersEnabled() { 1369 boolean small = isSmall() || mIsSwitchingState; 1370 boolean dragging = mAnimatingViewIntoPlace || mIsDragOccuring; 1371 boolean enableChildrenLayers = small || dragging || isPageMoving(); 1372 1373 if (enableChildrenLayers != mChildrenLayersEnabled) { 1374 mChildrenLayersEnabled = enableChildrenLayers; 1375 for (int i = 0; i < getPageCount(); i++) { 1376 ((ViewGroup)getChildAt(i)).setChildrenLayersEnabled(mChildrenLayersEnabled); 1377 } 1378 } 1379 } 1380 1381 protected void onWallpaperTap(MotionEvent ev) { 1382 final int[] position = mTempCell; 1383 getLocationOnScreen(position); 1384 1385 int pointerIndex = ev.getActionIndex(); 1386 position[0] += (int) ev.getX(pointerIndex); 1387 position[1] += (int) ev.getY(pointerIndex); 1388 1389 mWallpaperManager.sendWallpaperCommand(getWindowToken(), 1390 ev.getAction() == MotionEvent.ACTION_UP 1391 ? WallpaperManager.COMMAND_TAP : WallpaperManager.COMMAND_SECONDARY_TAP, 1392 position[0], position[1], 0, null); 1393 } 1394 1395 /* 1396 * This interpolator emulates the rate at which the perceived scale of an object changes 1397 * as its distance from a camera increases. When this interpolator is applied to a scale 1398 * animation on a view, it evokes the sense that the object is shrinking due to moving away 1399 * from the camera. 1400 */ 1401 static class ZInterpolator implements TimeInterpolator { 1402 private float focalLength; 1403 1404 public ZInterpolator(float foc) { 1405 focalLength = foc; 1406 } 1407 1408 public float getInterpolation(float input) { 1409 return (1.0f - focalLength / (focalLength + input)) / 1410 (1.0f - focalLength / (focalLength + 1.0f)); 1411 } 1412 } 1413 1414 /* 1415 * The exact reverse of ZInterpolator. 1416 */ 1417 static class InverseZInterpolator implements TimeInterpolator { 1418 private ZInterpolator zInterpolator; 1419 public InverseZInterpolator(float foc) { 1420 zInterpolator = new ZInterpolator(foc); 1421 } 1422 public float getInterpolation(float input) { 1423 return 1 - zInterpolator.getInterpolation(1 - input); 1424 } 1425 } 1426 1427 /* 1428 * ZInterpolator compounded with an ease-out. 1429 */ 1430 static class ZoomOutInterpolator implements TimeInterpolator { 1431 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(0.75f); 1432 private final ZInterpolator zInterpolator = new ZInterpolator(0.13f); 1433 1434 public float getInterpolation(float input) { 1435 return decelerate.getInterpolation(zInterpolator.getInterpolation(input)); 1436 } 1437 } 1438 1439 /* 1440 * InvereZInterpolator compounded with an ease-out. 1441 */ 1442 static class ZoomInInterpolator implements TimeInterpolator { 1443 private final InverseZInterpolator inverseZInterpolator = new InverseZInterpolator(0.35f); 1444 private final DecelerateInterpolator decelerate = new DecelerateInterpolator(3.0f); 1445 1446 public float getInterpolation(float input) { 1447 return decelerate.getInterpolation(inverseZInterpolator.getInterpolation(input)); 1448 } 1449 } 1450 1451 private final ZoomInInterpolator mZoomInInterpolator = new ZoomInInterpolator(); 1452 1453 /* 1454 * 1455 * We call these methods (onDragStartedWithItemSpans/onDragStartedWithSize) whenever we 1456 * start a drag in Launcher, regardless of whether the drag has ever entered the Workspace 1457 * 1458 * These methods mark the appropriate pages as accepting drops (which alters their visual 1459 * appearance). 1460 * 1461 */ 1462 public void onDragStartedWithItem(View v) { 1463 final Canvas canvas = new Canvas(); 1464 1465 // We need to add extra padding to the bitmap to make room for the glow effect 1466 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1467 1468 // The outline is used to visualize where the item will land if dropped 1469 mDragOutline = createDragOutline(v, canvas, bitmapPadding); 1470 } 1471 1472 public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, Paint alphaClipPaint) { 1473 final Canvas canvas = new Canvas(); 1474 1475 // We need to add extra padding to the bitmap to make room for the glow effect 1476 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1477 1478 int[] size = estimateItemSize(info.spanX, info.spanY, info, false); 1479 1480 // The outline is used to visualize where the item will land if dropped 1481 mDragOutline = createDragOutline(b, canvas, bitmapPadding, size[0], size[1], alphaClipPaint); 1482 } 1483 1484 // we call this method whenever a drag and drop in Launcher finishes, even if Workspace was 1485 // never dragged over 1486 public void onDragStopped(boolean success) { 1487 // In the success case, DragController has already called onDragExit() 1488 if (!success) { 1489 doDragExit(null); 1490 } 1491 } 1492 1493 public void exitWidgetResizeMode() { 1494 DragLayer dragLayer = mLauncher.getDragLayer(); 1495 dragLayer.clearAllResizeFrames(); 1496 } 1497 1498 private void initAnimationArrays() { 1499 final int childCount = getChildCount(); 1500 if (mOldTranslationXs != null) return; 1501 mOldTranslationXs = new float[childCount]; 1502 mOldTranslationYs = new float[childCount]; 1503 mOldScaleXs = new float[childCount]; 1504 mOldScaleYs = new float[childCount]; 1505 mOldBackgroundAlphas = new float[childCount]; 1506 mOldBackgroundAlphaMultipliers = new float[childCount]; 1507 mOldAlphas = new float[childCount]; 1508 mOldRotationYs = new float[childCount]; 1509 mNewTranslationXs = new float[childCount]; 1510 mNewTranslationYs = new float[childCount]; 1511 mNewScaleXs = new float[childCount]; 1512 mNewScaleYs = new float[childCount]; 1513 mNewBackgroundAlphas = new float[childCount]; 1514 mNewBackgroundAlphaMultipliers = new float[childCount]; 1515 mNewAlphas = new float[childCount]; 1516 mNewRotationYs = new float[childCount]; 1517 } 1518 1519 Animator getChangeStateAnimation(final State state, boolean animated) { 1520 return getChangeStateAnimation(state, animated, 0); 1521 } 1522 1523 Animator getChangeStateAnimation(final State state, boolean animated, int delay) { 1524 if (mState == state) { 1525 return null; 1526 } 1527 1528 // Initialize animation arrays for the first time if necessary 1529 initAnimationArrays(); 1530 1531 AnimatorSet anim = animated ? new AnimatorSet() : null; 1532 1533 // Stop any scrolling, move to the current page right away 1534 setCurrentPage((mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage); 1535 1536 final State oldState = mState; 1537 final boolean oldStateIsNormal = (oldState == State.NORMAL); 1538 final boolean oldStateIsSmall = (oldState == State.SMALL); 1539 mState = state; 1540 final boolean stateIsNormal = (state == State.NORMAL); 1541 final boolean stateIsSpringLoaded = (state == State.SPRING_LOADED); 1542 final boolean stateIsSmall = (state == State.SMALL); 1543 float finalScaleFactor = 1.0f; 1544 float finalBackgroundAlpha = stateIsSpringLoaded ? 1.0f : 0f; 1545 float translationX = 0; 1546 float translationY = 0; 1547 boolean zoomIn = true; 1548 1549 if (state != State.NORMAL) { 1550 finalScaleFactor = mSpringLoadedShrinkFactor - (stateIsSmall ? 0.1f : 0); 1551 if (oldStateIsNormal && stateIsSmall) { 1552 zoomIn = false; 1553 setLayoutScale(finalScaleFactor); 1554 updateChildrenLayersEnabled(); 1555 } else { 1556 finalBackgroundAlpha = 1.0f; 1557 setLayoutScale(finalScaleFactor); 1558 } 1559 } else { 1560 setLayoutScale(1.0f); 1561 } 1562 1563 final int duration = zoomIn ? 1564 getResources().getInteger(R.integer.config_workspaceUnshrinkTime) : 1565 getResources().getInteger(R.integer.config_appsCustomizeWorkspaceShrinkTime); 1566 for (int i = 0; i < getChildCount(); i++) { 1567 final CellLayout cl = (CellLayout) getChildAt(i); 1568 float rotation = 0f; 1569 float initialAlpha = cl.getAlpha(); 1570 float finalAlphaMultiplierValue = 1f; 1571 float finalAlpha = (!mFadeInAdjacentScreens || stateIsSpringLoaded || 1572 (i == mCurrentPage)) ? 1f : 0f; 1573 1574 // Determine the pages alpha during the state transition 1575 if ((oldStateIsSmall && stateIsNormal) || 1576 (oldStateIsNormal && stateIsSmall)) { 1577 // To/from workspace - only show the current page unless the transition is not 1578 // animated and the animation end callback below doesn't run 1579 if (i == mCurrentPage || !animated) { 1580 finalAlpha = 1f; 1581 finalAlphaMultiplierValue = 0f; 1582 } else { 1583 initialAlpha = 0f; 1584 finalAlpha = 0f; 1585 } 1586 } 1587 1588 // Update the rotation of the screen (don't apply rotation on Phone UI) 1589 if (LauncherApplication.isScreenLarge()) { 1590 if (i < mCurrentPage) { 1591 rotation = WORKSPACE_ROTATION; 1592 } else if (i > mCurrentPage) { 1593 rotation = -WORKSPACE_ROTATION; 1594 } 1595 } 1596 1597 // If the screen is not xlarge, then don't rotate the CellLayouts 1598 // NOTE: If we don't update the side pages alpha, then we should not hide the side 1599 // pages. see unshrink(). 1600 if (LauncherApplication.isScreenLarge()) { 1601 translationX = getOffsetXForRotation(rotation, cl.getWidth(), cl.getHeight()); 1602 } 1603 1604 mOldAlphas[i] = initialAlpha; 1605 mNewAlphas[i] = finalAlpha; 1606 if (animated) { 1607 mOldTranslationXs[i] = cl.getTranslationX(); 1608 mOldTranslationYs[i] = cl.getTranslationY(); 1609 mOldScaleXs[i] = cl.getScaleX(); 1610 mOldScaleYs[i] = cl.getScaleY(); 1611 mOldBackgroundAlphas[i] = cl.getBackgroundAlpha(); 1612 mOldBackgroundAlphaMultipliers[i] = cl.getBackgroundAlphaMultiplier(); 1613 mOldRotationYs[i] = cl.getRotationY(); 1614 1615 mNewTranslationXs[i] = translationX; 1616 mNewTranslationYs[i] = translationY; 1617 mNewScaleXs[i] = finalScaleFactor; 1618 mNewScaleYs[i] = finalScaleFactor; 1619 mNewBackgroundAlphas[i] = finalBackgroundAlpha; 1620 mNewBackgroundAlphaMultipliers[i] = finalAlphaMultiplierValue; 1621 mNewRotationYs[i] = rotation; 1622 } else { 1623 cl.setTranslationX(translationX); 1624 cl.setTranslationY(translationY); 1625 cl.setScaleX(finalScaleFactor); 1626 cl.setScaleY(finalScaleFactor); 1627 cl.setBackgroundAlpha(finalBackgroundAlpha); 1628 cl.setBackgroundAlphaMultiplier(finalAlphaMultiplierValue); 1629 cl.setAlpha(finalAlpha); 1630 cl.setRotationY(rotation); 1631 mChangeStateAnimationListener.onAnimationEnd(null); 1632 } 1633 } 1634 1635 if (animated) { 1636 anim.addListener(new AnimatorListenerAdapter() { 1637 @Override 1638 public void onAnimationEnd(android.animation.Animator animation) { 1639 // The above code to determine initialAlpha and finalAlpha will ensure that only 1640 // the current page is visible during (and subsequently, after) the transition 1641 // animation. If fade adjacent pages is disabled, then re-enable the page 1642 // visibility after the transition animation. 1643 if (!mFadeInAdjacentScreens && stateIsNormal && oldStateIsSmall) { 1644 for (int i = 0; i < getChildCount(); i++) { 1645 final CellLayout cl = (CellLayout) getChildAt(i); 1646 cl.setAlpha(1f); 1647 } 1648 } 1649 } 1650 }); 1651 for (int index = 0; index < getChildCount(); index++) { 1652 final int i = index; 1653 final CellLayout cl = (CellLayout) getChildAt(i); 1654 if (mOldAlphas[i] == 0 && mNewAlphas[i] == 0) { 1655 cl.setTranslationX(mNewTranslationXs[i]); 1656 cl.setTranslationY(mNewTranslationYs[i]); 1657 cl.setScaleX(mNewScaleXs[i]); 1658 cl.setScaleY(mNewScaleYs[i]); 1659 cl.setBackgroundAlpha(mNewBackgroundAlphas[i]); 1660 cl.setBackgroundAlphaMultiplier(mNewBackgroundAlphaMultipliers[i]); 1661 cl.setAlpha(mNewAlphas[i]); 1662 cl.setRotationY(mNewRotationYs[i]); 1663 } else { 1664 LauncherViewPropertyAnimator a = new LauncherViewPropertyAnimator(cl); 1665 a.translationX(mNewTranslationXs[i]) 1666 .translationY(mNewTranslationYs[i]) 1667 .scaleX(mNewScaleXs[i]) 1668 .scaleY(mNewScaleYs[i]) 1669 .setDuration(duration) 1670 .setInterpolator(mZoomInInterpolator); 1671 if (mOldAlphas[i] != mNewAlphas[i]) { 1672 a.alpha(mNewAlphas[i]); 1673 } 1674 anim.play(a); 1675 if (mOldRotationYs[i] != 0 || mNewRotationYs[i] != 0) { 1676 ValueAnimator rotate = ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1677 rotate.setInterpolator(new DecelerateInterpolator(2.0f)); 1678 rotate.addUpdateListener(new LauncherAnimatorUpdateListener() { 1679 public void onAnimationUpdate(float a, float b) { 1680 cl.setRotationY(a * 0f + b * 1f); 1681 } 1682 }); 1683 anim.play(rotate); 1684 } 1685 if (mOldBackgroundAlphas[i] != 0 || 1686 mNewBackgroundAlphas[i] != 0 || 1687 mOldBackgroundAlphaMultipliers[i] != 0 || 1688 mNewBackgroundAlphaMultipliers[i] != 0) { 1689 ValueAnimator bgAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1690 bgAnim.setInterpolator(mZoomInInterpolator); 1691 bgAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 1692 public void onAnimationUpdate(float a, float b) { 1693 cl.setBackgroundAlpha( 1694 a * mOldBackgroundAlphas[i] + 1695 b * mNewBackgroundAlphas[i]); 1696 cl.setBackgroundAlphaMultiplier( 1697 a * mOldBackgroundAlphaMultipliers[i] + 1698 b * mNewBackgroundAlphaMultipliers[i]); 1699 } 1700 }); 1701 anim.play(bgAnim); 1702 } 1703 } 1704 } 1705 anim.setStartDelay(delay); 1706 // If we call this when we're not animated, onAnimationEnd is never called on 1707 // the listener; make sure we only use the listener when we're actually animating 1708 anim.addListener(mChangeStateAnimationListener); 1709 } 1710 1711 if (stateIsSpringLoaded) { 1712 // Right now we're covered by Apps Customize 1713 // Show the background gradient immediately, so the gradient will 1714 // be showing once AppsCustomize disappears 1715 animateBackgroundGradient(getResources().getInteger( 1716 R.integer.config_appsCustomizeSpringLoadedBgAlpha) / 100f, false); 1717 } else { 1718 // Fade the background gradient away 1719 animateBackgroundGradient(0f, true); 1720 } 1721 return anim; 1722 } 1723 1724 /** 1725 * Draw the View v into the given Canvas. 1726 * 1727 * @param v the view to draw 1728 * @param destCanvas the canvas to draw on 1729 * @param padding the horizontal and vertical padding to use when drawing 1730 */ 1731 private void drawDragView(View v, Canvas destCanvas, int padding, boolean pruneToDrawable) { 1732 final Rect clipRect = mTempRect; 1733 v.getDrawingRect(clipRect); 1734 1735 boolean textVisible = false; 1736 1737 destCanvas.save(); 1738 if (v instanceof TextView && pruneToDrawable) { 1739 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1740 clipRect.set(0, 0, d.getIntrinsicWidth() + padding, d.getIntrinsicHeight() + padding); 1741 destCanvas.translate(padding / 2, padding / 2); 1742 d.draw(destCanvas); 1743 } else { 1744 if (v instanceof FolderIcon) { 1745 // For FolderIcons the text can bleed into the icon area, and so we need to 1746 // hide the text completely (which can't be achieved by clipping). 1747 if (((FolderIcon) v).getTextVisible()) { 1748 ((FolderIcon) v).setTextVisible(false); 1749 textVisible = true; 1750 } 1751 } else if (v instanceof BubbleTextView) { 1752 final BubbleTextView tv = (BubbleTextView) v; 1753 clipRect.bottom = tv.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + 1754 tv.getLayout().getLineTop(0); 1755 } else if (v instanceof TextView) { 1756 final TextView tv = (TextView) v; 1757 clipRect.bottom = tv.getExtendedPaddingTop() - tv.getCompoundDrawablePadding() + 1758 tv.getLayout().getLineTop(0); 1759 } 1760 destCanvas.translate(-v.getScrollX() + padding / 2, -v.getScrollY() + padding / 2); 1761 destCanvas.clipRect(clipRect, Op.REPLACE); 1762 v.draw(destCanvas); 1763 1764 // Restore text visibility of FolderIcon if necessary 1765 if (textVisible) { 1766 ((FolderIcon) v).setTextVisible(true); 1767 } 1768 } 1769 destCanvas.restore(); 1770 } 1771 1772 /** 1773 * Returns a new bitmap to show when the given View is being dragged around. 1774 * Responsibility for the bitmap is transferred to the caller. 1775 */ 1776 public Bitmap createDragBitmap(View v, Canvas canvas, int padding) { 1777 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1778 Bitmap b; 1779 1780 if (v instanceof TextView) { 1781 Drawable d = ((TextView) v).getCompoundDrawables()[1]; 1782 b = Bitmap.createBitmap(d.getIntrinsicWidth() + padding, 1783 d.getIntrinsicHeight() + padding, Bitmap.Config.ARGB_8888); 1784 } else { 1785 b = Bitmap.createBitmap( 1786 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1787 } 1788 1789 canvas.setBitmap(b); 1790 drawDragView(v, canvas, padding, true); 1791 mOutlineHelper.applyOuterBlur(b, canvas, outlineColor); 1792 canvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); 1793 canvas.setBitmap(null); 1794 1795 return b; 1796 } 1797 1798 /** 1799 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1800 * Responsibility for the bitmap is transferred to the caller. 1801 */ 1802 private Bitmap createDragOutline(View v, Canvas canvas, int padding) { 1803 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1804 final Bitmap b = Bitmap.createBitmap( 1805 v.getWidth() + padding, v.getHeight() + padding, Bitmap.Config.ARGB_8888); 1806 1807 canvas.setBitmap(b); 1808 drawDragView(v, canvas, padding, true); 1809 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1810 canvas.setBitmap(null); 1811 return b; 1812 } 1813 1814 /** 1815 * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. 1816 * Responsibility for the bitmap is transferred to the caller. 1817 */ 1818 private Bitmap createDragOutline(Bitmap orig, Canvas canvas, int padding, int w, int h, 1819 Paint alphaClipPaint) { 1820 final int outlineColor = getResources().getColor(android.R.color.holo_blue_light); 1821 final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 1822 canvas.setBitmap(b); 1823 1824 Rect src = new Rect(0, 0, orig.getWidth(), orig.getHeight()); 1825 float scaleFactor = Math.min((w - padding) / (float) orig.getWidth(), 1826 (h - padding) / (float) orig.getHeight()); 1827 int scaledWidth = (int) (scaleFactor * orig.getWidth()); 1828 int scaledHeight = (int) (scaleFactor * orig.getHeight()); 1829 Rect dst = new Rect(0, 0, scaledWidth, scaledHeight); 1830 1831 // center the image 1832 dst.offset((w - scaledWidth) / 2, (h - scaledHeight) / 2); 1833 1834 canvas.drawBitmap(orig, src, dst, null); 1835 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor, 1836 alphaClipPaint); 1837 canvas.setBitmap(null); 1838 1839 return b; 1840 } 1841 1842 /** 1843 * Creates a drag outline to represent a drop (that we don't have the actual information for 1844 * yet). May be changed in the future to alter the drop outline slightly depending on the 1845 * clip description mime data. 1846 */ 1847 private Bitmap createExternalDragOutline(Canvas canvas, int padding) { 1848 Resources r = getResources(); 1849 final int outlineColor = r.getColor(android.R.color.holo_blue_light); 1850 final int iconWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width); 1851 final int iconHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height); 1852 final int rectRadius = r.getDimensionPixelSize(R.dimen.external_drop_icon_rect_radius); 1853 final int inset = (int) (Math.min(iconWidth, iconHeight) * 0.2f); 1854 final Bitmap b = Bitmap.createBitmap( 1855 iconWidth + padding, iconHeight + padding, Bitmap.Config.ARGB_8888); 1856 1857 canvas.setBitmap(b); 1858 canvas.drawRoundRect(new RectF(inset, inset, iconWidth - inset, iconHeight - inset), 1859 rectRadius, rectRadius, mExternalDragOutlinePaint); 1860 mOutlineHelper.applyMediumExpensiveOutlineWithBlur(b, canvas, outlineColor, outlineColor); 1861 canvas.setBitmap(null); 1862 return b; 1863 } 1864 1865 void startDrag(CellLayout.CellInfo cellInfo) { 1866 View child = cellInfo.cell; 1867 1868 // Make sure the drag was started by a long press as opposed to a long click. 1869 if (!child.isInTouchMode()) { 1870 return; 1871 } 1872 1873 mDragInfo = cellInfo; 1874 child.setVisibility(GONE); 1875 1876 child.clearFocus(); 1877 child.setPressed(false); 1878 1879 final Canvas canvas = new Canvas(); 1880 1881 // We need to add extra padding to the bitmap to make room for the glow effect 1882 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1883 1884 // The outline is used to visualize where the item will land if dropped 1885 mDragOutline = createDragOutline(child, canvas, bitmapPadding); 1886 beginDragShared(child, this); 1887 } 1888 1889 public void beginDragShared(View child, DragSource source) { 1890 Resources r = getResources(); 1891 1892 // We need to add extra padding to the bitmap to make room for the glow effect 1893 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 1894 1895 // The drag bitmap follows the touch point around on the screen 1896 final Bitmap b = createDragBitmap(child, new Canvas(), bitmapPadding); 1897 1898 final int bmpWidth = b.getWidth(); 1899 1900 mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY); 1901 final int dragLayerX = (int) mTempXY[0] + (child.getWidth() - bmpWidth) / 2; 1902 int dragLayerY = mTempXY[1] - bitmapPadding / 2; 1903 1904 Point dragVisualizeOffset = null; 1905 Rect dragRect = null; 1906 if (child instanceof BubbleTextView || child instanceof PagedViewIcon) { 1907 int iconSize = r.getDimensionPixelSize(R.dimen.app_icon_size); 1908 int iconPaddingTop = r.getDimensionPixelSize(R.dimen.app_icon_padding_top); 1909 int top = child.getPaddingTop(); 1910 int left = (bmpWidth - iconSize) / 2; 1911 int right = left + iconSize; 1912 int bottom = top + iconSize; 1913 dragLayerY += top; 1914 // Note: The drag region is used to calculate drag layer offsets, but the 1915 // dragVisualizeOffset in addition to the dragRect (the size) to position the outline. 1916 dragVisualizeOffset = new Point(-bitmapPadding / 2, iconPaddingTop - bitmapPadding / 2); 1917 dragRect = new Rect(left, top, right, bottom); 1918 } else if (child instanceof FolderIcon) { 1919 int previewSize = r.getDimensionPixelSize(R.dimen.folder_preview_size); 1920 dragRect = new Rect(0, 0, child.getWidth(), previewSize); 1921 } 1922 1923 // Clear the pressed state if necessary 1924 if (child instanceof BubbleTextView) { 1925 BubbleTextView icon = (BubbleTextView) child; 1926 icon.clearPressedOrFocusedBackground(); 1927 } 1928 1929 mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(), 1930 DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect); 1931 b.recycle(); 1932 } 1933 1934 void addApplicationShortcut(ShortcutInfo info, CellLayout target, long container, int screen, 1935 int cellX, int cellY, boolean insertAtFirst, int intersectX, int intersectY) { 1936 View view = mLauncher.createShortcut(R.layout.application, target, (ShortcutInfo) info); 1937 1938 final int[] cellXY = new int[2]; 1939 target.findCellForSpanThatIntersects(cellXY, 1, 1, intersectX, intersectY); 1940 addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, insertAtFirst); 1941 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, cellXY[0], 1942 cellXY[1]); 1943 } 1944 1945 public boolean transitionStateShouldAllowDrop() { 1946 return (!isSwitchingState() || mTransitionProgress > 0.5f); 1947 } 1948 1949 /** 1950 * {@inheritDoc} 1951 */ 1952 public boolean acceptDrop(DragObject d) { 1953 // If it's an external drop (e.g. from All Apps), check if it should be accepted 1954 if (d.dragSource != this) { 1955 // Don't accept the drop if we're not over a screen at time of drop 1956 if (mDragTargetLayout == null) { 1957 return false; 1958 } 1959 if (!transitionStateShouldAllowDrop()) return false; 1960 1961 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 1962 d.dragView, mDragViewVisualCenter); 1963 1964 // We want the point to be mapped to the dragTarget. 1965 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 1966 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 1967 } else { 1968 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 1969 } 1970 1971 int spanX = 1; 1972 int spanY = 1; 1973 View ignoreView = null; 1974 if (mDragInfo != null) { 1975 final CellLayout.CellInfo dragCellInfo = mDragInfo; 1976 spanX = dragCellInfo.spanX; 1977 spanY = dragCellInfo.spanY; 1978 ignoreView = dragCellInfo.cell; 1979 } else { 1980 final ItemInfo dragInfo = (ItemInfo) d.dragInfo; 1981 spanX = dragInfo.spanX; 1982 spanY = dragInfo.spanY; 1983 } 1984 1985 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 1986 (int) mDragViewVisualCenter[1], spanX, spanY, mDragTargetLayout, mTargetCell); 1987 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, true)) { 1988 return true; 1989 } 1990 if (willAddToExistingUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, 1991 mTargetCell)) { 1992 return true; 1993 } 1994 1995 // Don't accept the drop if there's no room for the item 1996 if (!mDragTargetLayout.findCellForSpanIgnoring(null, spanX, spanY, ignoreView)) { 1997 // Don't show the message if we are dropping on the AllApps button and the hotseat 1998 // is full 1999 if (mTargetCell != null && mLauncher.isHotseatLayout(mDragTargetLayout)) { 2000 Hotseat hotseat = mLauncher.getHotseat(); 2001 if (Hotseat.isAllAppsButtonRank( 2002 hotseat.getOrderInHotseat(mTargetCell[0], mTargetCell[1]))) { 2003 return false; 2004 } 2005 } 2006 2007 mLauncher.showOutOfSpaceMessage(); 2008 return false; 2009 } 2010 } 2011 return true; 2012 } 2013 2014 boolean willCreateUserFolder(ItemInfo info, CellLayout target, int[] targetCell, 2015 boolean considerTimeout) { 2016 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2017 2018 boolean hasntMoved = false; 2019 if (mDragInfo != null) { 2020 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2021 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2022 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2023 } 2024 2025 if (dropOverView == null || hasntMoved || (considerTimeout && !mCreateUserFolderOnDrop)) { 2026 return false; 2027 } 2028 2029 boolean aboveShortcut = (dropOverView.getTag() instanceof ShortcutInfo); 2030 boolean willBecomeShortcut = 2031 (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION || 2032 info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT); 2033 2034 return (aboveShortcut && willBecomeShortcut); 2035 } 2036 2037 boolean willAddToExistingUserFolder(Object dragInfo, CellLayout target, int[] targetCell) { 2038 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2039 if (dropOverView instanceof FolderIcon) { 2040 FolderIcon fi = (FolderIcon) dropOverView; 2041 if (fi.acceptDrop(dragInfo)) { 2042 return true; 2043 } 2044 } 2045 return false; 2046 } 2047 2048 boolean createUserFolderIfNecessary(View newView, long container, CellLayout target, 2049 int[] targetCell, boolean external, DragView dragView, Runnable postAnimationRunnable) { 2050 View v = target.getChildAt(targetCell[0], targetCell[1]); 2051 boolean hasntMoved = false; 2052 if (mDragInfo != null) { 2053 CellLayout cellParent = getParentCellLayoutForView(mDragInfo.cell); 2054 hasntMoved = (mDragInfo.cellX == targetCell[0] && 2055 mDragInfo.cellY == targetCell[1]) && (cellParent == target); 2056 } 2057 2058 if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false; 2059 mCreateUserFolderOnDrop = false; 2060 final int screen = (targetCell == null) ? mDragInfo.screen : indexOfChild(target); 2061 2062 boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo); 2063 boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo); 2064 2065 if (aboveShortcut && willBecomeShortcut) { 2066 ShortcutInfo sourceInfo = (ShortcutInfo) newView.getTag(); 2067 ShortcutInfo destInfo = (ShortcutInfo) v.getTag(); 2068 // if the drag started here, we need to remove it from the workspace 2069 if (!external) { 2070 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2071 } 2072 2073 Rect folderLocation = new Rect(); 2074 float scale = mLauncher.getDragLayer().getDescendantRectRelativeToSelf(v, folderLocation); 2075 target.removeView(v); 2076 2077 FolderIcon fi = 2078 mLauncher.addFolder(target, container, screen, targetCell[0], targetCell[1]); 2079 destInfo.cellX = -1; 2080 destInfo.cellY = -1; 2081 sourceInfo.cellX = -1; 2082 sourceInfo.cellY = -1; 2083 2084 // If the dragView is null, we can't animate 2085 boolean animate = dragView != null; 2086 if (animate) { 2087 fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale, 2088 postAnimationRunnable); 2089 } else { 2090 fi.addItem(destInfo); 2091 fi.addItem(sourceInfo); 2092 } 2093 return true; 2094 } 2095 return false; 2096 } 2097 2098 boolean addToExistingFolderIfNecessary(View newView, CellLayout target, int[] targetCell, 2099 DragObject d, boolean external) { 2100 View dropOverView = target.getChildAt(targetCell[0], targetCell[1]); 2101 if (dropOverView instanceof FolderIcon) { 2102 FolderIcon fi = (FolderIcon) dropOverView; 2103 if (fi.acceptDrop(d.dragInfo)) { 2104 fi.onDrop(d); 2105 2106 // if the drag started here, we need to remove it from the workspace 2107 if (!external) { 2108 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 2109 } 2110 return true; 2111 } 2112 } 2113 return false; 2114 } 2115 2116 public void onDrop(DragObject d) { 2117 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, 2118 mDragViewVisualCenter); 2119 2120 // We want the point to be mapped to the dragTarget. 2121 if (mDragTargetLayout != null) { 2122 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2123 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2124 } else { 2125 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2126 } 2127 } 2128 2129 CellLayout dropTargetLayout = mDragTargetLayout; 2130 2131 int snapScreen = -1; 2132 if (d.dragSource != this) { 2133 final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], 2134 (int) mDragViewVisualCenter[1] }; 2135 onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d); 2136 } else if (mDragInfo != null) { 2137 final View cell = mDragInfo.cell; 2138 2139 if (dropTargetLayout != null) { 2140 // Move internally 2141 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout); 2142 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout); 2143 long container = hasMovedIntoHotseat ? 2144 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2145 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2146 int screen = (mTargetCell[0] < 0) ? 2147 mDragInfo.screen : indexOfChild(dropTargetLayout); 2148 int spanX = mDragInfo != null ? mDragInfo.spanX : 1; 2149 int spanY = mDragInfo != null ? mDragInfo.spanY : 1; 2150 // First we find the cell nearest to point at which the item is 2151 // dropped, without any consideration to whether there is an item there. 2152 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) 2153 mDragViewVisualCenter[1], spanX, spanY, dropTargetLayout, mTargetCell); 2154 // If the item being dropped is a shortcut and the nearest drop 2155 // cell also contains a shortcut, then create a folder with the two shortcuts. 2156 if (!mInScrollArea && createUserFolderIfNecessary(cell, container, 2157 dropTargetLayout, mTargetCell, false, d.dragView, null)) { 2158 return; 2159 } 2160 2161 if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, d, false)) { 2162 return; 2163 } 2164 2165 // Aside from the special case where we're dropping a shortcut onto a shortcut, 2166 // we need to find the nearest cell location that is vacant 2167 mTargetCell = findNearestVacantArea((int) mDragViewVisualCenter[0], 2168 (int) mDragViewVisualCenter[1], mDragInfo.spanX, mDragInfo.spanY, cell, 2169 dropTargetLayout, mTargetCell); 2170 2171 if (mCurrentPage != screen && !hasMovedIntoHotseat) { 2172 snapScreen = screen; 2173 snapToPage(screen); 2174 } 2175 2176 if (mTargetCell[0] >= 0 && mTargetCell[1] >= 0) { 2177 if (hasMovedLayouts) { 2178 // Reparent the view 2179 getParentCellLayoutForView(cell).removeView(cell); 2180 addInScreen(cell, container, screen, mTargetCell[0], mTargetCell[1], 2181 mDragInfo.spanX, mDragInfo.spanY); 2182 } 2183 2184 // update the item's position after drop 2185 final ItemInfo info = (ItemInfo) cell.getTag(); 2186 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams(); 2187 dropTargetLayout.onMove(cell, mTargetCell[0], mTargetCell[1]); 2188 lp.cellX = mTargetCell[0]; 2189 lp.cellY = mTargetCell[1]; 2190 cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screen, 2191 mTargetCell[0], mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY)); 2192 2193 if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2194 cell instanceof LauncherAppWidgetHostView) { 2195 final CellLayout cellLayout = dropTargetLayout; 2196 // We post this call so that the widget has a chance to be placed 2197 // in its final location 2198 2199 final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell; 2200 AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo(); 2201 if (pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) { 2202 final Runnable resizeRunnable = new Runnable() { 2203 public void run() { 2204 DragLayer dragLayer = mLauncher.getDragLayer(); 2205 dragLayer.addResizeFrame(info, hostView, cellLayout); 2206 } 2207 }; 2208 post(new Runnable() { 2209 public void run() { 2210 if (!isPageMoving()) { 2211 resizeRunnable.run(); 2212 } else { 2213 mDelayedResizeRunnable = resizeRunnable; 2214 } 2215 } 2216 }); 2217 } 2218 } 2219 2220 LauncherModel.moveItemInDatabase(mLauncher, info, container, screen, lp.cellX, 2221 lp.cellY); 2222 } 2223 } 2224 2225 final CellLayout parent = (CellLayout) cell.getParent().getParent(); 2226 2227 // Prepare it to be animated into its new position 2228 // This must be called after the view has been re-parented 2229 final Runnable disableHardwareLayersRunnable = new Runnable() { 2230 @Override 2231 public void run() { 2232 mAnimatingViewIntoPlace = false; 2233 updateChildrenLayersEnabled(); 2234 } 2235 }; 2236 mAnimatingViewIntoPlace = true; 2237 if (d.dragView.hasDrawn()) { 2238 int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION; 2239 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, 2240 disableHardwareLayersRunnable, this); 2241 } else { 2242 cell.setVisibility(VISIBLE); 2243 } 2244 parent.onDropChild(cell); 2245 } 2246 } 2247 2248 public void setFinalScrollForPageChange(int screen) { 2249 if (screen >= 0) { 2250 mSavedScrollX = getScrollX(); 2251 CellLayout cl = (CellLayout) getChildAt(screen); 2252 mSavedTranslationX = cl.getTranslationX(); 2253 mSavedRotationY = cl.getRotationY(); 2254 final int newX = getChildOffset(screen) - getRelativeChildOffset(screen); 2255 setScrollX(newX); 2256 cl.setTranslationX(0f); 2257 cl.setRotationY(0f); 2258 } 2259 } 2260 2261 public void resetFinalScrollForPageChange(int screen) { 2262 if (screen >= 0) { 2263 CellLayout cl = (CellLayout) getChildAt(screen); 2264 setScrollX(mSavedScrollX); 2265 cl.setTranslationX(mSavedTranslationX); 2266 cl.setRotationY(mSavedRotationY); 2267 } 2268 } 2269 2270 public void getViewLocationRelativeToSelf(View v, int[] location) { 2271 getLocationInWindow(location); 2272 int x = location[0]; 2273 int y = location[1]; 2274 2275 v.getLocationInWindow(location); 2276 int vX = location[0]; 2277 int vY = location[1]; 2278 2279 location[0] = vX - x; 2280 location[1] = vY - y; 2281 } 2282 2283 public void onDragEnter(DragObject d) { 2284 mDragHasEnteredWorkspace = true; 2285 if (mDragTargetLayout != null) { 2286 mDragTargetLayout.setIsDragOverlapping(false); 2287 mDragTargetLayout.onDragExit(); 2288 } 2289 mDragTargetLayout = getCurrentDropLayout(); 2290 mDragTargetLayout.setIsDragOverlapping(true); 2291 mDragTargetLayout.onDragEnter(); 2292 2293 // Because we don't have space in the Phone UI (the CellLayouts run to the edge) we 2294 // don't need to show the outlines 2295 if (LauncherApplication.isScreenLarge()) { 2296 showOutlines(); 2297 } 2298 } 2299 2300 private void doDragExit(DragObject d) { 2301 // Clean up folders 2302 cleanupFolderCreation(d); 2303 2304 // Reset the scroll area and previous drag target 2305 onResetScrollArea(); 2306 2307 if (mDragTargetLayout != null) { 2308 mDragTargetLayout.setIsDragOverlapping(false); 2309 mDragTargetLayout.onDragExit(); 2310 } 2311 mLastDragOverView = null; 2312 mSpringLoadedDragController.cancel(); 2313 2314 if (!mIsPageMoving) { 2315 hideOutlines(); 2316 } 2317 } 2318 2319 public void onDragExit(DragObject d) { 2320 mDragHasEnteredWorkspace = false; 2321 doDragExit(d); 2322 } 2323 2324 public DropTarget getDropTargetDelegate(DragObject d) { 2325 return null; 2326 } 2327 2328 /** 2329 * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data 2330 * in the returned structure related to the widgets that match the drop (or a null list if it is 2331 * a shortcut drop). If the drop is not accepted then a null structure is returned. 2332 */ 2333 private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) { 2334 final LauncherModel model = mLauncher.getModel(); 2335 final ClipDescription desc = event.getClipDescription(); 2336 final int mimeTypeCount = desc.getMimeTypeCount(); 2337 for (int i = 0; i < mimeTypeCount; ++i) { 2338 final String mimeType = desc.getMimeType(i); 2339 if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) { 2340 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null); 2341 } else { 2342 final List<WidgetMimeTypeHandlerData> widgets = 2343 model.resolveWidgetsForMimeType(mContext, mimeType); 2344 if (widgets.size() > 0) { 2345 return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets); 2346 } 2347 } 2348 } 2349 return null; 2350 } 2351 2352 /** 2353 * Global drag and drop handler 2354 */ 2355 @Override 2356 public boolean onDragEvent(DragEvent event) { 2357 final ClipDescription desc = event.getClipDescription(); 2358 final CellLayout layout = (CellLayout) getChildAt(mCurrentPage); 2359 final int[] pos = new int[2]; 2360 layout.getLocationOnScreen(pos); 2361 // We need to offset the drag coordinates to layout coordinate space 2362 final int x = (int) event.getX() - pos[0]; 2363 final int y = (int) event.getY() - pos[1]; 2364 2365 switch (event.getAction()) { 2366 case DragEvent.ACTION_DRAG_STARTED: { 2367 // Validate this drag 2368 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2369 if (test != null) { 2370 boolean isShortcut = (test.second == null); 2371 if (isShortcut) { 2372 // Check if we have enough space on this screen to add a new shortcut 2373 if (!layout.findCellForSpan(pos, 1, 1)) { 2374 mLauncher.showOutOfSpaceMessage(); 2375 return false; 2376 } 2377 } 2378 } else { 2379 // Show error message if we couldn't accept any of the items 2380 Toast.makeText(mContext, mContext.getString(R.string.external_drop_widget_error), 2381 Toast.LENGTH_SHORT).show(); 2382 return false; 2383 } 2384 2385 // Create the drag outline 2386 // We need to add extra padding to the bitmap to make room for the glow effect 2387 final Canvas canvas = new Canvas(); 2388 final int bitmapPadding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS; 2389 mDragOutline = createExternalDragOutline(canvas, bitmapPadding); 2390 2391 // Show the current page outlines to indicate that we can accept this drop 2392 showOutlines(); 2393 layout.onDragEnter(); 2394 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1, null, null); 2395 2396 return true; 2397 } 2398 case DragEvent.ACTION_DRAG_LOCATION: 2399 // Visualize the drop location 2400 layout.visualizeDropLocation(null, mDragOutline, x, y, 1, 1, null, null); 2401 return true; 2402 case DragEvent.ACTION_DROP: { 2403 // Try and add any shortcuts 2404 final LauncherModel model = mLauncher.getModel(); 2405 final ClipData data = event.getClipData(); 2406 2407 // We assume that the mime types are ordered in descending importance of 2408 // representation. So we enumerate the list of mime types and alert the 2409 // user if any widgets can handle the drop. Only the most preferred 2410 // representation will be handled. 2411 pos[0] = x; 2412 pos[1] = y; 2413 Pair<Integer, List<WidgetMimeTypeHandlerData>> test = validateDrag(event); 2414 if (test != null) { 2415 final int index = test.first; 2416 final List<WidgetMimeTypeHandlerData> widgets = test.second; 2417 final boolean isShortcut = (widgets == null); 2418 final String mimeType = desc.getMimeType(index); 2419 if (isShortcut) { 2420 final Intent intent = data.getItemAt(index).getIntent(); 2421 Object info = model.infoFromShortcutIntent(mContext, intent, data.getIcon()); 2422 if (info != null) { 2423 onDropExternal(new int[] { x, y }, info, layout, false); 2424 } 2425 } else { 2426 if (widgets.size() == 1) { 2427 // If there is only one item, then go ahead and add and configure 2428 // that widget 2429 final AppWidgetProviderInfo widgetInfo = widgets.get(0).widgetInfo; 2430 final PendingAddWidgetInfo createInfo = 2431 new PendingAddWidgetInfo(widgetInfo, mimeType, data); 2432 mLauncher.addAppWidgetFromDrop(createInfo, 2433 LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentPage, null, pos); 2434 } else { 2435 // Show the widget picker dialog if there is more than one widget 2436 // that can handle this data type 2437 final InstallWidgetReceiver.WidgetListAdapter adapter = 2438 new InstallWidgetReceiver.WidgetListAdapter(mLauncher, mimeType, 2439 data, widgets, layout, mCurrentPage, pos); 2440 final AlertDialog.Builder builder = 2441 new AlertDialog.Builder(mContext); 2442 builder.setAdapter(adapter, adapter); 2443 builder.setCancelable(true); 2444 builder.setTitle(mContext.getString( 2445 R.string.external_drop_widget_pick_title)); 2446 builder.setIcon(R.drawable.ic_no_applications); 2447 builder.show(); 2448 } 2449 } 2450 } 2451 return true; 2452 } 2453 case DragEvent.ACTION_DRAG_ENDED: 2454 // Hide the page outlines after the drop 2455 layout.onDragExit(); 2456 hideOutlines(); 2457 return true; 2458 } 2459 return super.onDragEvent(event); 2460 } 2461 2462 /* 2463 * 2464 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2465 * coordinate space. The argument xy is modified with the return result. 2466 * 2467 */ 2468 void mapPointFromSelfToChild(View v, float[] xy) { 2469 mapPointFromSelfToChild(v, xy, null); 2470 } 2471 2472 /* 2473 * 2474 * Convert the 2D coordinate xy from the parent View's coordinate space to this CellLayout's 2475 * coordinate space. The argument xy is modified with the return result. 2476 * 2477 * if cachedInverseMatrix is not null, this method will just use that matrix instead of 2478 * computing it itself; we use this to avoid redundant matrix inversions in 2479 * findMatchingPageForDragOver 2480 * 2481 */ 2482 void mapPointFromSelfToChild(View v, float[] xy, Matrix cachedInverseMatrix) { 2483 if (cachedInverseMatrix == null) { 2484 v.getMatrix().invert(mTempInverseMatrix); 2485 cachedInverseMatrix = mTempInverseMatrix; 2486 } 2487 xy[0] = xy[0] + mScrollX - v.getLeft(); 2488 xy[1] = xy[1] + mScrollY - v.getTop(); 2489 cachedInverseMatrix.mapPoints(xy); 2490 } 2491 2492 /* 2493 * Maps a point from the Workspace's coordinate system to another sibling view's. (Workspace 2494 * covers the full screen) 2495 */ 2496 void mapPointFromSelfToSibling(View v, float[] xy) { 2497 xy[0] = xy[0] - v.getLeft(); 2498 xy[1] = xy[1] - v.getTop(); 2499 } 2500 2501 /* 2502 * 2503 * Convert the 2D coordinate xy from this CellLayout's coordinate space to 2504 * the parent View's coordinate space. The argument xy is modified with the return result. 2505 * 2506 */ 2507 void mapPointFromChildToSelf(View v, float[] xy) { 2508 v.getMatrix().mapPoints(xy); 2509 xy[0] -= (mScrollX - v.getLeft()); 2510 xy[1] -= (mScrollY - v.getTop()); 2511 } 2512 2513 static private float squaredDistance(float[] point1, float[] point2) { 2514 float distanceX = point1[0] - point2[0]; 2515 float distanceY = point2[1] - point2[1]; 2516 return distanceX * distanceX + distanceY * distanceY; 2517 } 2518 2519 /* 2520 * 2521 * Returns true if the passed CellLayout cl overlaps with dragView 2522 * 2523 */ 2524 boolean overlaps(CellLayout cl, DragView dragView, 2525 int dragViewX, int dragViewY, Matrix cachedInverseMatrix) { 2526 // Transform the coordinates of the item being dragged to the CellLayout's coordinates 2527 final float[] draggedItemTopLeft = mTempDragCoordinates; 2528 draggedItemTopLeft[0] = dragViewX; 2529 draggedItemTopLeft[1] = dragViewY; 2530 final float[] draggedItemBottomRight = mTempDragBottomRightCoordinates; 2531 draggedItemBottomRight[0] = draggedItemTopLeft[0] + dragView.getDragRegionWidth(); 2532 draggedItemBottomRight[1] = draggedItemTopLeft[1] + dragView.getDragRegionHeight(); 2533 2534 // Transform the dragged item's top left coordinates 2535 // to the CellLayout's local coordinates 2536 mapPointFromSelfToChild(cl, draggedItemTopLeft, cachedInverseMatrix); 2537 float overlapRegionLeft = Math.max(0f, draggedItemTopLeft[0]); 2538 float overlapRegionTop = Math.max(0f, draggedItemTopLeft[1]); 2539 2540 if (overlapRegionLeft <= cl.getWidth() && overlapRegionTop >= 0) { 2541 // Transform the dragged item's bottom right coordinates 2542 // to the CellLayout's local coordinates 2543 mapPointFromSelfToChild(cl, draggedItemBottomRight, cachedInverseMatrix); 2544 float overlapRegionRight = Math.min(cl.getWidth(), draggedItemBottomRight[0]); 2545 float overlapRegionBottom = Math.min(cl.getHeight(), draggedItemBottomRight[1]); 2546 2547 if (overlapRegionRight >= 0 && overlapRegionBottom <= cl.getHeight()) { 2548 float overlap = (overlapRegionRight - overlapRegionLeft) * 2549 (overlapRegionBottom - overlapRegionTop); 2550 if (overlap > 0) { 2551 return true; 2552 } 2553 } 2554 } 2555 return false; 2556 } 2557 2558 /* 2559 * 2560 * This method returns the CellLayout that is currently being dragged to. In order to drag 2561 * to a CellLayout, either the touch point must be directly over the CellLayout, or as a second 2562 * strategy, we see if the dragView is overlapping any CellLayout and choose the closest one 2563 * 2564 * Return null if no CellLayout is currently being dragged over 2565 * 2566 */ 2567 private CellLayout findMatchingPageForDragOver( 2568 DragView dragView, float originX, float originY, boolean exact) { 2569 // We loop through all the screens (ie CellLayouts) and see which ones overlap 2570 // with the item being dragged and then choose the one that's closest to the touch point 2571 final int screenCount = getChildCount(); 2572 CellLayout bestMatchingScreen = null; 2573 float smallestDistSoFar = Float.MAX_VALUE; 2574 2575 for (int i = 0; i < screenCount; i++) { 2576 CellLayout cl = (CellLayout) getChildAt(i); 2577 2578 final float[] touchXy = {originX, originY}; 2579 // Transform the touch coordinates to the CellLayout's local coordinates 2580 // If the touch point is within the bounds of the cell layout, we can return immediately 2581 cl.getMatrix().invert(mTempInverseMatrix); 2582 mapPointFromSelfToChild(cl, touchXy, mTempInverseMatrix); 2583 2584 if (touchXy[0] >= 0 && touchXy[0] <= cl.getWidth() && 2585 touchXy[1] >= 0 && touchXy[1] <= cl.getHeight()) { 2586 return cl; 2587 } 2588 2589 if (!exact) { 2590 // Get the center of the cell layout in screen coordinates 2591 final float[] cellLayoutCenter = mTempCellLayoutCenterCoordinates; 2592 cellLayoutCenter[0] = cl.getWidth()/2; 2593 cellLayoutCenter[1] = cl.getHeight()/2; 2594 mapPointFromChildToSelf(cl, cellLayoutCenter); 2595 2596 touchXy[0] = originX; 2597 touchXy[1] = originY; 2598 2599 // Calculate the distance between the center of the CellLayout 2600 // and the touch point 2601 float dist = squaredDistance(touchXy, cellLayoutCenter); 2602 2603 if (dist < smallestDistSoFar) { 2604 smallestDistSoFar = dist; 2605 bestMatchingScreen = cl; 2606 } 2607 } 2608 } 2609 return bestMatchingScreen; 2610 } 2611 2612 // This is used to compute the visual center of the dragView. This point is then 2613 // used to visualize drop locations and determine where to drop an item. The idea is that 2614 // the visual center represents the user's interpretation of where the item is, and hence 2615 // is the appropriate point to use when determining drop location. 2616 private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, 2617 DragView dragView, float[] recycle) { 2618 float res[]; 2619 if (recycle == null) { 2620 res = new float[2]; 2621 } else { 2622 res = recycle; 2623 } 2624 2625 // First off, the drag view has been shifted in a way that is not represented in the 2626 // x and y values or the x/yOffsets. Here we account for that shift. 2627 x += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetX); 2628 y += getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 2629 2630 // These represent the visual top and left of drag view if a dragRect was provided. 2631 // If a dragRect was not provided, then they correspond to the actual view left and 2632 // top, as the dragRect is in that case taken to be the entire dragView. 2633 // R.dimen.dragViewOffsetY. 2634 int left = x - xOffset; 2635 int top = y - yOffset; 2636 2637 // In order to find the visual center, we shift by half the dragRect 2638 res[0] = left + dragView.getDragRegion().width() / 2; 2639 res[1] = top + dragView.getDragRegion().height() / 2; 2640 2641 return res; 2642 } 2643 2644 private boolean isDragWidget(DragObject d) { 2645 return (d.dragInfo instanceof LauncherAppWidgetInfo || 2646 d.dragInfo instanceof PendingAddWidgetInfo); 2647 } 2648 private boolean isExternalDragWidget(DragObject d) { 2649 return d.dragSource != this && isDragWidget(d); 2650 } 2651 2652 public void onDragOver(DragObject d) { 2653 // Skip drag over events while we are dragging over side pages 2654 if (mInScrollArea) return; 2655 if (mIsSwitchingState) return; 2656 2657 Rect r = new Rect(); 2658 CellLayout layout = null; 2659 ItemInfo item = (ItemInfo) d.dragInfo; 2660 2661 // Ensure that we have proper spans for the item that we are dropping 2662 if (item.spanX < 0 || item.spanY < 0) throw new RuntimeException("Improper spans found"); 2663 mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, 2664 d.dragView, mDragViewVisualCenter); 2665 2666 // Identify whether we have dragged over a side page 2667 if (isSmall()) { 2668 if (mLauncher.getHotseat() != null && !isExternalDragWidget(d)) { 2669 mLauncher.getHotseat().getHitRect(r); 2670 if (r.contains(d.x, d.y)) { 2671 layout = mLauncher.getHotseat().getLayout(); 2672 } 2673 } 2674 if (layout == null) { 2675 layout = findMatchingPageForDragOver(d.dragView, d.x, d.y, false); 2676 } 2677 if (layout != mDragTargetLayout) { 2678 // Cancel all intermediate folder states 2679 cleanupFolderCreation(d); 2680 2681 if (mDragTargetLayout != null) { 2682 mDragTargetLayout.setIsDragOverlapping(false); 2683 mDragTargetLayout.onDragExit(); 2684 } 2685 mDragTargetLayout = layout; 2686 if (mDragTargetLayout != null) { 2687 mDragTargetLayout.setIsDragOverlapping(true); 2688 mDragTargetLayout.onDragEnter(); 2689 } else { 2690 mLastDragOverView = null; 2691 } 2692 2693 boolean isInSpringLoadedMode = (mState == State.SPRING_LOADED); 2694 if (isInSpringLoadedMode) { 2695 if (mLauncher.isHotseatLayout(layout)) { 2696 mSpringLoadedDragController.cancel(); 2697 } else { 2698 mSpringLoadedDragController.setAlarm(mDragTargetLayout); 2699 } 2700 } 2701 } 2702 } else { 2703 // Test to see if we are over the hotseat otherwise just use the current page 2704 if (mLauncher.getHotseat() != null && !isDragWidget(d)) { 2705 mLauncher.getHotseat().getHitRect(r); 2706 if (r.contains(d.x, d.y)) { 2707 layout = mLauncher.getHotseat().getLayout(); 2708 } 2709 } 2710 if (layout == null) { 2711 layout = getCurrentDropLayout(); 2712 } 2713 if (layout != mDragTargetLayout) { 2714 if (mDragTargetLayout != null) { 2715 mDragTargetLayout.setIsDragOverlapping(false); 2716 mDragTargetLayout.onDragExit(); 2717 } 2718 mDragTargetLayout = layout; 2719 mDragTargetLayout.setIsDragOverlapping(true); 2720 mDragTargetLayout.onDragEnter(); 2721 } 2722 } 2723 2724 // Handle the drag over 2725 if (mDragTargetLayout != null) { 2726 final View child = (mDragInfo == null) ? null : mDragInfo.cell; 2727 2728 // We want the point to be mapped to the dragTarget. 2729 if (mLauncher.isHotseatLayout(mDragTargetLayout)) { 2730 mapPointFromSelfToSibling(mLauncher.getHotseat(), mDragViewVisualCenter); 2731 } else { 2732 mapPointFromSelfToChild(mDragTargetLayout, mDragViewVisualCenter, null); 2733 } 2734 ItemInfo info = (ItemInfo) d.dragInfo; 2735 2736 mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], 2737 (int) mDragViewVisualCenter[1], 1, 1, mDragTargetLayout, mTargetCell); 2738 final View dragOverView = mDragTargetLayout.getChildAt(mTargetCell[0], 2739 mTargetCell[1]); 2740 2741 boolean userFolderPending = willCreateUserFolder(info, mDragTargetLayout, 2742 mTargetCell, false); 2743 boolean isOverFolder = dragOverView instanceof FolderIcon; 2744 if (dragOverView != mLastDragOverView) { 2745 cancelFolderCreation(); 2746 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2747 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2748 } 2749 } 2750 2751 if (userFolderPending && dragOverView != mLastDragOverView) { 2752 mFolderCreationAlarm.setOnAlarmListener(new 2753 FolderCreationAlarmListener(mDragTargetLayout, mTargetCell[0], mTargetCell[1])); 2754 mFolderCreationAlarm.setAlarm(FOLDER_CREATION_TIMEOUT); 2755 } 2756 2757 if (dragOverView != mLastDragOverView && isOverFolder) { 2758 ((FolderIcon) dragOverView).onDragEnter(d.dragInfo); 2759 if (mDragTargetLayout != null) { 2760 mDragTargetLayout.clearDragOutlines(); 2761 } 2762 } 2763 mLastDragOverView = dragOverView; 2764 2765 if (!mCreateUserFolderOnDrop && !isOverFolder) { 2766 mDragTargetLayout.visualizeDropLocation(child, mDragOutline, 2767 (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], 2768 item.spanX, item.spanY, d.dragView.getDragVisualizeOffset(), 2769 d.dragView.getDragRegion()); 2770 } 2771 } 2772 } 2773 2774 private void cleanupFolderCreation(DragObject d) { 2775 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2776 mDragFolderRingAnimator.animateToNaturalState(); 2777 } 2778 if (mLastDragOverView != null && mLastDragOverView instanceof FolderIcon) { 2779 if (d != null) { 2780 ((FolderIcon) mLastDragOverView).onDragExit(d.dragInfo); 2781 } 2782 } 2783 mFolderCreationAlarm.cancelAlarm(); 2784 } 2785 2786 private void cancelFolderCreation() { 2787 if (mDragFolderRingAnimator != null && mCreateUserFolderOnDrop) { 2788 mDragFolderRingAnimator.animateToNaturalState(); 2789 } 2790 mCreateUserFolderOnDrop = false; 2791 mFolderCreationAlarm.cancelAlarm(); 2792 } 2793 2794 class FolderCreationAlarmListener implements OnAlarmListener { 2795 CellLayout layout; 2796 int cellX; 2797 int cellY; 2798 2799 public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) { 2800 this.layout = layout; 2801 this.cellX = cellX; 2802 this.cellY = cellY; 2803 } 2804 2805 public void onAlarm(Alarm alarm) { 2806 if (mDragFolderRingAnimator == null) { 2807 mDragFolderRingAnimator = new FolderRingAnimator(mLauncher, null); 2808 } 2809 mDragFolderRingAnimator.setCell(cellX, cellY); 2810 mDragFolderRingAnimator.setCellLayout(layout); 2811 mDragFolderRingAnimator.animateToAcceptState(); 2812 layout.showFolderAccept(mDragFolderRingAnimator); 2813 layout.clearDragOutlines(); 2814 mCreateUserFolderOnDrop = true; 2815 } 2816 } 2817 2818 @Override 2819 public void getHitRect(Rect outRect) { 2820 // We want the workspace to have the whole area of the display (it will find the correct 2821 // cell layout to drop to in the existing drag/drop logic. 2822 outRect.set(0, 0, mDisplayWidth, mDisplayHeight); 2823 } 2824 2825 /** 2826 * Add the item specified by dragInfo to the given layout. 2827 * @return true if successful 2828 */ 2829 public boolean addExternalItemToScreen(ItemInfo dragInfo, CellLayout layout) { 2830 if (layout.findCellForSpan(mTempEstimate, dragInfo.spanX, dragInfo.spanY)) { 2831 onDropExternal(dragInfo.dropPos, (ItemInfo) dragInfo, (CellLayout) layout, false); 2832 return true; 2833 } 2834 mLauncher.showOutOfSpaceMessage(); 2835 return false; 2836 } 2837 2838 private void onDropExternal(int[] touchXY, Object dragInfo, 2839 CellLayout cellLayout, boolean insertAtFirst) { 2840 onDropExternal(touchXY, dragInfo, cellLayout, insertAtFirst, null); 2841 } 2842 2843 /** 2844 * Drop an item that didn't originate on one of the workspace screens. 2845 * It may have come from Launcher (e.g. from all apps or customize), or it may have 2846 * come from another app altogether. 2847 * 2848 * NOTE: This can also be called when we are outside of a drag event, when we want 2849 * to add an item to one of the workspace screens. 2850 */ 2851 private void onDropExternal(final int[] touchXY, final Object dragInfo, 2852 final CellLayout cellLayout, boolean insertAtFirst, DragObject d) { 2853 final Runnable exitSpringLoadedRunnable = new Runnable() { 2854 @Override 2855 public void run() { 2856 mLauncher.exitSpringLoadedDragModeDelayed(true, false); 2857 } 2858 }; 2859 2860 ItemInfo info = (ItemInfo) dragInfo; 2861 int spanX = info.spanX; 2862 int spanY = info.spanY; 2863 if (mDragInfo != null) { 2864 spanX = mDragInfo.spanX; 2865 spanY = mDragInfo.spanY; 2866 } 2867 2868 final long container = mLauncher.isHotseatLayout(cellLayout) ? 2869 LauncherSettings.Favorites.CONTAINER_HOTSEAT : 2870 LauncherSettings.Favorites.CONTAINER_DESKTOP; 2871 final int screen = indexOfChild(cellLayout); 2872 if (!mLauncher.isHotseatLayout(cellLayout) && screen != mCurrentPage 2873 && mState != State.SPRING_LOADED) { 2874 snapToPage(screen); 2875 } 2876 2877 if (info instanceof PendingAddItemInfo) { 2878 final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo; 2879 2880 boolean findNearestVacantCell = true; 2881 if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 2882 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 2883 cellLayout, mTargetCell); 2884 if (willCreateUserFolder((ItemInfo) d.dragInfo, mDragTargetLayout, mTargetCell, 2885 true) || willAddToExistingUserFolder((ItemInfo) d.dragInfo, 2886 mDragTargetLayout, mTargetCell)) { 2887 findNearestVacantCell = false; 2888 } 2889 } 2890 if (findNearestVacantCell) { 2891 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], spanX, spanY, null, 2892 cellLayout, mTargetCell); 2893 } 2894 2895 Runnable onAnimationCompleteRunnable = new Runnable() { 2896 @Override 2897 public void run() { 2898 // When dragging and dropping from customization tray, we deal with creating 2899 // widgets/shortcuts/folders in a slightly different way 2900 switch (pendingInfo.itemType) { 2901 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 2902 mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, 2903 container, screen, mTargetCell, null); 2904 break; 2905 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2906 mLauncher.processShortcutFromDrop(pendingInfo.componentName, 2907 container, screen, mTargetCell, null); 2908 break; 2909 default: 2910 throw new IllegalStateException("Unknown item type: " + 2911 pendingInfo.itemType); 2912 } 2913 cellLayout.onDragExit(); 2914 } 2915 }; 2916 2917 // Now we animate the dragView, (ie. the widget or shortcut preview) into its final 2918 // location and size on the home screen. 2919 RectF r = estimateItemPosition(cellLayout, pendingInfo, 2920 mTargetCell[0], mTargetCell[1], spanX, spanY); 2921 int loc[] = new int[2]; 2922 loc[0] = (int) r.left; 2923 loc[1] = (int) r.top; 2924 setFinalTransitionTransform(cellLayout); 2925 float cellLayoutScale = 2926 mLauncher.getDragLayer().getDescendantCoordRelativeToSelf(cellLayout, loc); 2927 resetTransitionTransform(cellLayout); 2928 2929 float dragViewScale = Math.min(r.width() / d.dragView.getMeasuredWidth(), 2930 r.height() / d.dragView.getMeasuredHeight()); 2931 // The animation will scale the dragView about its center, so we need to center about 2932 // the final location. 2933 loc[0] -= (d.dragView.getMeasuredWidth() - cellLayoutScale * r.width()) / 2; 2934 loc[1] -= (d.dragView.getMeasuredHeight() - cellLayoutScale * r.height()) / 2; 2935 2936 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, loc, 2937 dragViewScale * cellLayoutScale, onAnimationCompleteRunnable); 2938 } else { 2939 // This is for other drag/drop cases, like dragging from All Apps 2940 View view = null; 2941 2942 switch (info.itemType) { 2943 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 2944 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2945 if (info.container == NO_ID && info instanceof ApplicationInfo) { 2946 // Came from all apps -- make a copy 2947 info = new ShortcutInfo((ApplicationInfo) info); 2948 } 2949 view = mLauncher.createShortcut(R.layout.application, cellLayout, 2950 (ShortcutInfo) info); 2951 break; 2952 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 2953 view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, 2954 (FolderInfo) info, mIconCache); 2955 break; 2956 default: 2957 throw new IllegalStateException("Unknown item type: " + info.itemType); 2958 } 2959 2960 // First we find the cell nearest to point at which the item is 2961 // dropped, without any consideration to whether there is an item there. 2962 if (touchXY != null) { 2963 mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, 2964 cellLayout, mTargetCell); 2965 d.postAnimationRunnable = exitSpringLoadedRunnable; 2966 if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, true, 2967 d.dragView, d.postAnimationRunnable)) { 2968 return; 2969 } 2970 if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, d, true)) { 2971 return; 2972 } 2973 } 2974 2975 if (touchXY != null) { 2976 // when dragging and dropping, just find the closest free spot 2977 mTargetCell = findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, null, 2978 cellLayout, mTargetCell); 2979 } else { 2980 cellLayout.findCellForSpan(mTargetCell, 1, 1); 2981 } 2982 addInScreen(view, container, screen, mTargetCell[0], mTargetCell[1], info.spanX, 2983 info.spanY, insertAtFirst); 2984 cellLayout.onDropChild(view); 2985 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams(); 2986 cellLayout.getChildrenLayout().measureChild(view); 2987 2988 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screen, 2989 lp.cellX, lp.cellY); 2990 2991 if (d.dragView != null) { 2992 // We wrap the animation call in the temporary set and reset of the current 2993 // cellLayout to its final transform -- this means we animate the drag view to 2994 // the correct final location. 2995 setFinalTransitionTransform(cellLayout); 2996 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, 2997 exitSpringLoadedRunnable); 2998 resetTransitionTransform(cellLayout); 2999 } 3000 } 3001 } 3002 3003 public void setFinalTransitionTransform(CellLayout layout) { 3004 if (isSwitchingState()) { 3005 int index = indexOfChild(layout); 3006 mCurrentScaleX = layout.getScaleX(); 3007 mCurrentScaleY = layout.getScaleY(); 3008 mCurrentTranslationX = layout.getTranslationX(); 3009 mCurrentTranslationY = layout.getTranslationY(); 3010 mCurrentRotationY = layout.getRotationY(); 3011 layout.setScaleX(mNewScaleXs[index]); 3012 layout.setScaleY(mNewScaleYs[index]); 3013 layout.setTranslationX(mNewTranslationXs[index]); 3014 layout.setTranslationY(mNewTranslationYs[index]); 3015 layout.setRotationY(mNewRotationYs[index]); 3016 } 3017 } 3018 public void resetTransitionTransform(CellLayout layout) { 3019 if (isSwitchingState()) { 3020 mCurrentScaleX = layout.getScaleX(); 3021 mCurrentScaleY = layout.getScaleY(); 3022 mCurrentTranslationX = layout.getTranslationX(); 3023 mCurrentTranslationY = layout.getTranslationY(); 3024 mCurrentRotationY = layout.getRotationY(); 3025 layout.setScaleX(mCurrentScaleX); 3026 layout.setScaleY(mCurrentScaleY); 3027 layout.setTranslationX(mCurrentTranslationX); 3028 layout.setTranslationY(mCurrentTranslationY); 3029 layout.setRotationY(mCurrentRotationY); 3030 } 3031 } 3032 3033 /** 3034 * Return the current {@link CellLayout}, correctly picking the destination 3035 * screen while a scroll is in progress. 3036 */ 3037 public CellLayout getCurrentDropLayout() { 3038 return (CellLayout) getChildAt(mNextPage == INVALID_PAGE ? mCurrentPage : mNextPage); 3039 } 3040 3041 /** 3042 * Return the current CellInfo describing our current drag; this method exists 3043 * so that Launcher can sync this object with the correct info when the activity is created/ 3044 * destroyed 3045 * 3046 */ 3047 public CellLayout.CellInfo getDragInfo() { 3048 return mDragInfo; 3049 } 3050 3051 /** 3052 * Calculate the nearest cell where the given object would be dropped. 3053 * 3054 * pixelX and pixelY should be in the coordinate system of layout 3055 */ 3056 private int[] findNearestVacantArea(int pixelX, int pixelY, 3057 int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) { 3058 return layout.findNearestVacantArea( 3059 pixelX, pixelY, spanX, spanY, ignoreView, recycle); 3060 } 3061 3062 /** 3063 * Calculate the nearest cell where the given object would be dropped. 3064 * 3065 * pixelX and pixelY should be in the coordinate system of layout 3066 */ 3067 private int[] findNearestArea(int pixelX, int pixelY, 3068 int spanX, int spanY, CellLayout layout, int[] recycle) { 3069 return layout.findNearestArea( 3070 pixelX, pixelY, spanX, spanY, recycle); 3071 } 3072 3073 void setup(DragController dragController) { 3074 mSpringLoadedDragController = new SpringLoadedDragController(mLauncher); 3075 mDragController = dragController; 3076 3077 // hardware layers on children are enabled on startup, but should be disabled until 3078 // needed 3079 updateChildrenLayersEnabled(); 3080 setWallpaperDimension(); 3081 } 3082 3083 /** 3084 * Called at the end of a drag which originated on the workspace. 3085 */ 3086 public void onDropCompleted(View target, DragObject d, boolean success) { 3087 if (success) { 3088 if (target != this) { 3089 if (mDragInfo != null) { 3090 getParentCellLayoutForView(mDragInfo.cell).removeView(mDragInfo.cell); 3091 if (mDragInfo.cell instanceof DropTarget) { 3092 mDragController.removeDropTarget((DropTarget) mDragInfo.cell); 3093 } 3094 } 3095 } 3096 } else if (mDragInfo != null) { 3097 // NOTE: When 'success' is true, onDragExit is called by the DragController before 3098 // calling onDropCompleted(). We call it ourselves here, but maybe this should be 3099 // moved into DragController.cancelDrag(). 3100 doDragExit(null); 3101 CellLayout cellLayout; 3102 if (mLauncher.isHotseatLayout(target)) { 3103 cellLayout = mLauncher.getHotseat().getLayout(); 3104 } else { 3105 cellLayout = (CellLayout) getChildAt(mDragInfo.screen); 3106 } 3107 cellLayout.onDropChild(mDragInfo.cell); 3108 } 3109 if (d.cancelled && mDragInfo.cell != null) { 3110 mDragInfo.cell.setVisibility(VISIBLE); 3111 } 3112 mDragOutline = null; 3113 mDragInfo = null; 3114 } 3115 3116 public boolean isDropEnabled() { 3117 return true; 3118 } 3119 3120 @Override 3121 protected void onRestoreInstanceState(Parcelable state) { 3122 super.onRestoreInstanceState(state); 3123 Launcher.setScreen(mCurrentPage); 3124 } 3125 3126 @Override 3127 public void scrollLeft() { 3128 if (!isSmall() && !mIsSwitchingState) { 3129 super.scrollLeft(); 3130 } 3131 Folder openFolder = getOpenFolder(); 3132 if (openFolder != null) { 3133 openFolder.completeDragExit(); 3134 } 3135 } 3136 3137 @Override 3138 public void scrollRight() { 3139 if (!isSmall() && !mIsSwitchingState) { 3140 super.scrollRight(); 3141 } 3142 Folder openFolder = getOpenFolder(); 3143 if (openFolder != null) { 3144 openFolder.completeDragExit(); 3145 } 3146 } 3147 3148 @Override 3149 public boolean onEnterScrollArea(int x, int y, int direction) { 3150 // Ignore the scroll area if we are dragging over the hot seat 3151 if (mLauncher.getHotseat() != null) { 3152 Rect r = new Rect(); 3153 mLauncher.getHotseat().getHitRect(r); 3154 if (r.contains(x, y)) { 3155 return false; 3156 } 3157 } 3158 3159 boolean result = false; 3160 if (!isSmall() && !mIsSwitchingState) { 3161 mInScrollArea = true; 3162 3163 final int page = mCurrentPage + (direction == DragController.SCROLL_LEFT ? -1 : 1); 3164 final CellLayout layout = (CellLayout) getChildAt(page); 3165 cancelFolderCreation(); 3166 3167 if (layout != null) { 3168 // Exit the current layout and mark the overlapping layout 3169 if (mDragTargetLayout != null) { 3170 mDragTargetLayout.setIsDragOverlapping(false); 3171 mDragTargetLayout.onDragExit(); 3172 } 3173 mDragTargetLayout = layout; 3174 mDragTargetLayout.setIsDragOverlapping(true); 3175 3176 // Workspace is responsible for drawing the edge glow on adjacent pages, 3177 // so we need to redraw the workspace when this may have changed. 3178 invalidate(); 3179 result = true; 3180 } 3181 } 3182 return result; 3183 } 3184 3185 @Override 3186 public boolean onExitScrollArea() { 3187 boolean result = false; 3188 if (mInScrollArea) { 3189 if (mDragTargetLayout != null) { 3190 mDragTargetLayout.setIsDragOverlapping(false); 3191 // Workspace is responsible for drawing the edge glow on adjacent pages, 3192 // so we need to redraw the workspace when this may have changed. 3193 invalidate(); 3194 } 3195 if (mDragTargetLayout != null && mDragHasEnteredWorkspace) { 3196 // Unmark the overlapping layout and re-enter the current layout 3197 mDragTargetLayout = getCurrentDropLayout(); 3198 mDragTargetLayout.onDragEnter(); 3199 } 3200 result = true; 3201 mInScrollArea = false; 3202 } 3203 return result; 3204 } 3205 3206 private void onResetScrollArea() { 3207 if (mDragTargetLayout != null) { 3208 // Unmark the overlapping layout 3209 mDragTargetLayout.setIsDragOverlapping(false); 3210 3211 // Workspace is responsible for drawing the edge glow on adjacent pages, 3212 // so we need to redraw the workspace when this may have changed. 3213 invalidate(); 3214 } 3215 mInScrollArea = false; 3216 } 3217 3218 /** 3219 * Returns a specific CellLayout 3220 */ 3221 CellLayout getParentCellLayoutForView(View v) { 3222 ArrayList<CellLayout> layouts = getWorkspaceAndHotseatCellLayouts(); 3223 for (CellLayout layout : layouts) { 3224 if (layout.getChildrenLayout().indexOfChild(v) > -1) { 3225 return layout; 3226 } 3227 } 3228 return null; 3229 } 3230 3231 /** 3232 * Returns a list of all the CellLayouts in the workspace. 3233 */ 3234 ArrayList<CellLayout> getWorkspaceAndHotseatCellLayouts() { 3235 ArrayList<CellLayout> layouts = new ArrayList<CellLayout>(); 3236 int screenCount = getChildCount(); 3237 for (int screen = 0; screen < screenCount; screen++) { 3238 layouts.add(((CellLayout) getChildAt(screen))); 3239 } 3240 if (mLauncher.getHotseat() != null) { 3241 layouts.add(mLauncher.getHotseat().getLayout()); 3242 } 3243 return layouts; 3244 } 3245 3246 /** 3247 * We should only use this to search for specific children. Do not use this method to modify 3248 * CellLayoutChildren directly. 3249 */ 3250 ArrayList<CellLayoutChildren> getWorkspaceAndHotseatCellLayoutChildren() { 3251 ArrayList<CellLayoutChildren> childrenLayouts = new ArrayList<CellLayoutChildren>(); 3252 int screenCount = getChildCount(); 3253 for (int screen = 0; screen < screenCount; screen++) { 3254 childrenLayouts.add(((CellLayout) getChildAt(screen)).getChildrenLayout()); 3255 } 3256 if (mLauncher.getHotseat() != null) { 3257 childrenLayouts.add(mLauncher.getHotseat().getLayout().getChildrenLayout()); 3258 } 3259 return childrenLayouts; 3260 } 3261 3262 public Folder getFolderForTag(Object tag) { 3263 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3264 for (CellLayoutChildren layout: childrenLayouts) { 3265 int count = layout.getChildCount(); 3266 for (int i = 0; i < count; i++) { 3267 View child = layout.getChildAt(i); 3268 if (child instanceof Folder) { 3269 Folder f = (Folder) child; 3270 if (f.getInfo() == tag && f.getInfo().opened) { 3271 return f; 3272 } 3273 } 3274 } 3275 } 3276 return null; 3277 } 3278 3279 public View getViewForTag(Object tag) { 3280 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3281 for (CellLayoutChildren layout: childrenLayouts) { 3282 int count = layout.getChildCount(); 3283 for (int i = 0; i < count; i++) { 3284 View child = layout.getChildAt(i); 3285 if (child.getTag() == tag) { 3286 return child; 3287 } 3288 } 3289 } 3290 return null; 3291 } 3292 3293 void clearDropTargets() { 3294 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3295 for (CellLayoutChildren layout: childrenLayouts) { 3296 int childCount = layout.getChildCount(); 3297 for (int j = 0; j < childCount; j++) { 3298 View v = layout.getChildAt(j); 3299 if (v instanceof DropTarget) { 3300 mDragController.removeDropTarget((DropTarget) v); 3301 } 3302 } 3303 } 3304 } 3305 3306 void removeItems(final ArrayList<ApplicationInfo> apps) { 3307 final AppWidgetManager widgets = AppWidgetManager.getInstance(getContext()); 3308 3309 final HashSet<String> packageNames = new HashSet<String>(); 3310 final int appCount = apps.size(); 3311 for (int i = 0; i < appCount; i++) { 3312 packageNames.add(apps.get(i).componentName.getPackageName()); 3313 } 3314 3315 ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts(); 3316 for (final CellLayout layoutParent: cellLayouts) { 3317 final ViewGroup layout = layoutParent.getChildrenLayout(); 3318 3319 // Avoid ANRs by treating each screen separately 3320 post(new Runnable() { 3321 public void run() { 3322 final ArrayList<View> childrenToRemove = new ArrayList<View>(); 3323 childrenToRemove.clear(); 3324 3325 int childCount = layout.getChildCount(); 3326 for (int j = 0; j < childCount; j++) { 3327 final View view = layout.getChildAt(j); 3328 Object tag = view.getTag(); 3329 3330 if (tag instanceof ShortcutInfo) { 3331 final ShortcutInfo info = (ShortcutInfo) tag; 3332 final Intent intent = info.intent; 3333 final ComponentName name = intent.getComponent(); 3334 3335 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3336 for (String packageName: packageNames) { 3337 if (packageName.equals(name.getPackageName())) { 3338 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3339 childrenToRemove.add(view); 3340 } 3341 } 3342 } 3343 } else if (tag instanceof FolderInfo) { 3344 final FolderInfo info = (FolderInfo) tag; 3345 final ArrayList<ShortcutInfo> contents = info.contents; 3346 final int contentsCount = contents.size(); 3347 final ArrayList<ShortcutInfo> appsToRemoveFromFolder = 3348 new ArrayList<ShortcutInfo>(); 3349 3350 for (int k = 0; k < contentsCount; k++) { 3351 final ShortcutInfo appInfo = contents.get(k); 3352 final Intent intent = appInfo.intent; 3353 final ComponentName name = intent.getComponent(); 3354 3355 if (Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3356 for (String packageName: packageNames) { 3357 if (packageName.equals(name.getPackageName())) { 3358 appsToRemoveFromFolder.add(appInfo); 3359 } 3360 } 3361 } 3362 } 3363 for (ShortcutInfo item: appsToRemoveFromFolder) { 3364 info.remove(item); 3365 LauncherModel.deleteItemFromDatabase(mLauncher, item); 3366 } 3367 } else if (tag instanceof LauncherAppWidgetInfo) { 3368 final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag; 3369 final AppWidgetProviderInfo provider = 3370 widgets.getAppWidgetInfo(info.appWidgetId); 3371 if (provider != null) { 3372 for (String packageName: packageNames) { 3373 if (packageName.equals(provider.provider.getPackageName())) { 3374 LauncherModel.deleteItemFromDatabase(mLauncher, info); 3375 childrenToRemove.add(view); 3376 } 3377 } 3378 } 3379 } 3380 } 3381 3382 childCount = childrenToRemove.size(); 3383 for (int j = 0; j < childCount; j++) { 3384 View child = childrenToRemove.get(j); 3385 // Note: We can not remove the view directly from CellLayoutChildren as this 3386 // does not re-mark the spaces as unoccupied. 3387 layoutParent.removeViewInLayout(child); 3388 if (child instanceof DropTarget) { 3389 mDragController.removeDropTarget((DropTarget)child); 3390 } 3391 } 3392 3393 if (childCount > 0) { 3394 layout.requestLayout(); 3395 layout.invalidate(); 3396 } 3397 } 3398 }); 3399 } 3400 } 3401 3402 void updateShortcuts(ArrayList<ApplicationInfo> apps) { 3403 ArrayList<CellLayoutChildren> childrenLayouts = getWorkspaceAndHotseatCellLayoutChildren(); 3404 for (CellLayoutChildren layout: childrenLayouts) { 3405 int childCount = layout.getChildCount(); 3406 for (int j = 0; j < childCount; j++) { 3407 final View view = layout.getChildAt(j); 3408 Object tag = view.getTag(); 3409 if (tag instanceof ShortcutInfo) { 3410 ShortcutInfo info = (ShortcutInfo)tag; 3411 // We need to check for ACTION_MAIN otherwise getComponent() might 3412 // return null for some shortcuts (for instance, for shortcuts to 3413 // web pages.) 3414 final Intent intent = info.intent; 3415 final ComponentName name = intent.getComponent(); 3416 if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 3417 Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { 3418 final int appCount = apps.size(); 3419 for (int k = 0; k < appCount; k++) { 3420 ApplicationInfo app = apps.get(k); 3421 if (app.componentName.equals(name)) { 3422 info.setIcon(mIconCache.getIcon(info.intent)); 3423 ((TextView)view).setCompoundDrawablesWithIntrinsicBounds(null, 3424 new FastBitmapDrawable(info.getIcon(mIconCache)), 3425 null, null); 3426 } 3427 } 3428 } 3429 } 3430 } 3431 } 3432 } 3433 3434 void moveToDefaultScreen(boolean animate) { 3435 if (!isSmall()) { 3436 if (animate) { 3437 snapToPage(mDefaultPage); 3438 } else { 3439 setCurrentPage(mDefaultPage); 3440 } 3441 } 3442 getChildAt(mDefaultPage).requestFocus(); 3443 } 3444 3445 @Override 3446 public void syncPages() { 3447 } 3448 3449 @Override 3450 public void syncPageItems(int page, boolean immediate) { 3451 } 3452 3453 @Override 3454 protected String getCurrentPageDescription() { 3455 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 3456 return String.format(mContext.getString(R.string.workspace_scroll_format), 3457 page + 1, getChildCount()); 3458 } 3459 3460 public void getLocationInDragLayer(int[] loc) { 3461 mLauncher.getDragLayer().getLocationInDragLayer(this, loc); 3462 } 3463 3464 void setFadeForOverScroll(float fade) { 3465 if (!isScrollingIndicatorEnabled()) return; 3466 3467 mOverscrollFade = fade; 3468 float reducedFade = 0.5f + 0.5f * (1 - fade); 3469 final ViewGroup parent = (ViewGroup) getParent(); 3470 final ImageView qsbDivider = (ImageView) (parent.findViewById(R.id.qsb_divider)); 3471 final ImageView dockDivider = (ImageView) (parent.findViewById(R.id.dock_divider)); 3472 final View scrollIndicator = getScrollingIndicator(); 3473 3474 cancelScrollingIndicatorAnimations(); 3475 if (qsbDivider != null) qsbDivider.setAlpha(reducedFade); 3476 if (dockDivider != null) dockDivider.setAlpha(reducedFade); 3477 scrollIndicator.setAlpha(1 - fade); 3478 } 3479} 3480