OSDN Git Service

Merge "Refactoring search bar animations." into ub-launcher3-burnaby
[android-x86/packages-apps-Launcher3.git] / src / com / android / launcher3 / Launcher.java
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.launcher3;
18
19 import android.animation.Animator;
20 import android.animation.AnimatorListenerAdapter;
21 import android.animation.AnimatorSet;
22 import android.animation.ObjectAnimator;
23 import android.animation.PropertyValuesHolder;
24 import android.animation.ValueAnimator;
25 import android.annotation.SuppressLint;
26 import android.annotation.TargetApi;
27 import android.app.Activity;
28 import android.app.ActivityManager;
29 import android.app.ActivityOptions;
30 import android.app.AlertDialog;
31 import android.app.SearchManager;
32 import android.appwidget.AppWidgetHostView;
33 import android.appwidget.AppWidgetManager;
34 import android.appwidget.AppWidgetProviderInfo;
35 import android.content.ActivityNotFoundException;
36 import android.content.BroadcastReceiver;
37 import android.content.ComponentCallbacks2;
38 import android.content.ComponentName;
39 import android.content.Context;
40 import android.content.DialogInterface;
41 import android.content.Intent;
42 import android.content.IntentFilter;
43 import android.content.IntentSender;
44 import android.content.SharedPreferences;
45 import android.content.pm.ActivityInfo;
46 import android.content.pm.ApplicationInfo;
47 import android.content.pm.PackageManager;
48 import android.content.pm.PackageManager.NameNotFoundException;
49 import android.content.res.Configuration;
50 import android.database.sqlite.SQLiteDatabase;
51 import android.graphics.Bitmap;
52 import android.graphics.Canvas;
53 import android.graphics.Color;
54 import android.graphics.PorterDuff;
55 import android.graphics.Rect;
56 import android.graphics.drawable.ColorDrawable;
57 import android.graphics.drawable.Drawable;
58 import android.net.Uri;
59 import android.os.AsyncTask;
60 import android.os.Build;
61 import android.os.Bundle;
62 import android.os.Environment;
63 import android.os.Handler;
64 import android.os.Message;
65 import android.os.StrictMode;
66 import android.os.SystemClock;
67 import android.os.UserHandle;
68 import android.text.Selection;
69 import android.text.SpannableStringBuilder;
70 import android.text.TextUtils;
71 import android.text.method.TextKeyListener;
72 import android.util.Log;
73 import android.view.Display;
74 import android.view.Gravity;
75 import android.view.HapticFeedbackConstants;
76 import android.view.KeyEvent;
77 import android.view.LayoutInflater;
78 import android.view.Menu;
79 import android.view.MotionEvent;
80 import android.view.Surface;
81 import android.view.View;
82 import android.view.View.OnClickListener;
83 import android.view.View.OnLongClickListener;
84 import android.view.ViewGroup;
85 import android.view.ViewStub;
86 import android.view.ViewTreeObserver;
87 import android.view.Window;
88 import android.view.WindowManager;
89 import android.view.accessibility.AccessibilityEvent;
90 import android.view.animation.OvershootInterpolator;
91 import android.view.inputmethod.InputMethodManager;
92 import android.widget.Advanceable;
93 import android.widget.FrameLayout;
94 import android.widget.ImageView;
95 import android.widget.TextView;
96 import android.widget.Toast;
97
98 import com.android.launcher3.DropTarget.DragObject;
99 import com.android.launcher3.PagedView.PageSwitchListener;
100 import com.android.launcher3.allapps.AllAppsContainerView;
101 import com.android.launcher3.compat.AppWidgetManagerCompat;
102 import com.android.launcher3.compat.LauncherActivityInfoCompat;
103 import com.android.launcher3.compat.LauncherAppsCompat;
104 import com.android.launcher3.compat.UserHandleCompat;
105 import com.android.launcher3.compat.UserManagerCompat;
106 import com.android.launcher3.model.WidgetsModel;
107 import com.android.launcher3.util.ComponentKey;
108 import com.android.launcher3.util.LongArrayMap;
109 import com.android.launcher3.util.Thunk;
110 import com.android.launcher3.widget.PendingAddWidgetInfo;
111 import com.android.launcher3.widget.WidgetHostViewLoader;
112 import com.android.launcher3.widget.WidgetsContainerView;
113
114 import java.io.File;
115 import java.io.FileDescriptor;
116 import java.io.FileOutputStream;
117 import java.io.IOException;
118 import java.io.PrintWriter;
119 import java.lang.reflect.InvocationTargetException;
120 import java.lang.reflect.Method;
121 import java.text.DateFormat;
122 import java.util.ArrayList;
123 import java.util.Collection;
124 import java.util.Date;
125 import java.util.HashMap;
126 import java.util.HashSet;
127 import java.util.List;
128 import java.util.concurrent.atomic.AtomicInteger;
129
130 /**
131  * Default launcher application.
132  */
133 public class Launcher extends Activity
134         implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
135                    View.OnTouchListener, PageSwitchListener, LauncherProviderChangeListener {
136     static final String TAG = "Launcher";
137     static final boolean LOGD = false;
138
139     static final boolean PROFILE_STARTUP = false;
140     static final boolean DEBUG_WIDGETS = true;
141     static final boolean DEBUG_STRICT_MODE = false;
142     static final boolean DEBUG_RESUME_TIME = false;
143     static final boolean DEBUG_DUMP_LOG = false;
144
145     static final boolean ENABLE_DEBUG_INTENTS = false; // allow DebugIntents to run
146
147     private static final int REQUEST_CREATE_SHORTCUT = 1;
148     private static final int REQUEST_CREATE_APPWIDGET = 5;
149     private static final int REQUEST_PICK_APPWIDGET = 9;
150     private static final int REQUEST_PICK_WALLPAPER = 10;
151
152     private static final int REQUEST_BIND_APPWIDGET = 11;
153     private static final int REQUEST_RECONFIGURE_APPWIDGET = 12;
154
155     private static final int WORKSPACE_BACKGROUND_GRADIENT = 0;
156     private static final int WORKSPACE_BACKGROUND_TRANSPARENT = 1;
157     private static final int WORKSPACE_BACKGROUND_BLACK = 2;
158
159     private static final float BOUNCE_ANIMATION_TENSION = 1.3f;
160
161     /**
162      * IntentStarter uses request codes starting with this. This must be greater than all activity
163      * request codes used internally.
164      */
165     protected static final int REQUEST_LAST = 100;
166
167     static final int SCREEN_COUNT = 5;
168
169     // To turn on these properties, type
170     // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
171     static final String DUMP_STATE_PROPERTY = "launcher_dump_state";
172
173     // The Intent extra that defines whether to ignore the launch animation
174     static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
175             "com.android.launcher3.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
176
177     // Type: int
178     private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
179     // Type: int
180     private static final String RUNTIME_STATE = "launcher.state";
181     // Type: int
182     private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
183     // Type: int
184     private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
185     // Type: int
186     private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
187     // Type: int
188     private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
189     // Type: int
190     private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
191     // Type: int
192     private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
193     // Type: parcelable
194     private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
195     // Type: parcelable
196     private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_ID = "launcher.add_widget_id";
197     // Type: int[]
198     private static final String RUNTIME_STATE_VIEW_IDS = "launcher.view_ids";
199
200     static final String INTRO_SCREEN_DISMISSED = "launcher.intro_screen_dismissed";
201     static final String FIRST_RUN_ACTIVITY_DISPLAYED = "launcher.first_run_activity_displayed";
202
203     static final String FIRST_LOAD_COMPLETE = "launcher.first_load_complete";
204     static final String ACTION_FIRST_LOAD_COMPLETE =
205             "com.android.launcher3.action.FIRST_LOAD_COMPLETE";
206
207     public static final String SHOW_WEIGHT_WATCHER = "debug.show_mem";
208     public static final boolean SHOW_WEIGHT_WATCHER_DEFAULT = false;
209
210     private static final String QSB_WIDGET_ID = "qsb_widget_id";
211     private static final String QSB_WIDGET_PROVIDER = "qsb_widget_provider";
212
213     public static final String USER_HAS_MIGRATED = "launcher.user_migrated_from_old_data";
214
215     /** The different states that Launcher can be in. */
216     enum State { NONE, WORKSPACE, APPS, APPS_SPRING_LOADED, WIDGETS, WIDGETS_SPRING_LOADED }
217
218     @Thunk State mState = State.WORKSPACE;
219     @Thunk LauncherStateTransitionAnimation mStateTransitionAnimation;
220
221     private boolean mIsSafeModeEnabled;
222
223     LauncherOverlayCallbacks mLauncherOverlayCallbacks = new LauncherOverlayCallbacksImpl();
224     LauncherOverlay mLauncherOverlay;
225     InsettableFrameLayout mLauncherOverlayContainer;
226
227     static final int APPWIDGET_HOST_ID = 1024;
228     public static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
229     private static final int ON_ACTIVITY_RESULT_ANIMATION_DELAY = 500;
230     private static final int ACTIVITY_START_DELAY = 1000;
231
232     private HashMap<Integer, Integer> mItemIdToViewId = new HashMap<Integer, Integer>();
233     private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
234
235     // How long to wait before the new-shortcut animation automatically pans the workspace
236     private static int NEW_APPS_PAGE_MOVE_DELAY = 500;
237     private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 5;
238     @Thunk static int NEW_APPS_ANIMATION_DELAY = 500;
239
240     private final BroadcastReceiver mCloseSystemDialogsReceiver
241             = new CloseSystemDialogsIntentReceiver();
242
243     private LayoutInflater mInflater;
244
245     @Thunk Workspace mWorkspace;
246     private View mLauncherView;
247     private View mPageIndicators;
248     @Thunk DragLayer mDragLayer;
249     private DragController mDragController;
250     private View mWeightWatcher;
251
252     private AppWidgetManagerCompat mAppWidgetManager;
253     private LauncherAppWidgetHost mAppWidgetHost;
254
255     @Thunk ItemInfo mPendingAddInfo = new ItemInfo();
256     private LauncherAppWidgetProviderInfo mPendingAddWidgetInfo;
257     private int mPendingAddWidgetId = -1;
258
259     private int[] mTmpAddItemCellCoordinates = new int[2];
260
261     @Thunk Hotseat mHotseat;
262     private ViewGroup mOverviewPanel;
263
264     private View mAllAppsButton;
265     private View mWidgetsButton;
266
267     private SearchDropTargetBar mSearchDropTargetBar;
268
269     // Main container view for the all apps screen.
270     @Thunk AllAppsContainerView mAppsView;
271
272     // Main container view and the model for the widget tray screen.
273     @Thunk WidgetsContainerView mWidgetsView;
274     @Thunk WidgetsModel mWidgetsModel;
275
276     private boolean mAutoAdvanceRunning = false;
277     private AppWidgetHostView mQsb;
278
279     private Bundle mSavedState;
280     // We set the state in both onCreate and then onNewIntent in some cases, which causes both
281     // scroll issues (because the workspace may not have been measured yet) and extra work.
282     // Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
283     private State mOnResumeState = State.NONE;
284
285     private SpannableStringBuilder mDefaultKeySsb = null;
286
287     @Thunk boolean mWorkspaceLoading = true;
288
289     private boolean mPaused = true;
290     private boolean mRestoring;
291     private boolean mWaitingForResult;
292     private boolean mOnResumeNeedsLoad;
293
294     private ArrayList<Runnable> mBindOnResumeCallbacks = new ArrayList<Runnable>();
295     private ArrayList<Runnable> mOnResumeCallbacks = new ArrayList<Runnable>();
296
297     private Bundle mSavedInstanceState;
298
299     private LauncherModel mModel;
300     private IconCache mIconCache;
301     @Thunk boolean mUserPresent = true;
302     private boolean mVisible = false;
303     private boolean mHasFocus = false;
304     private boolean mAttached = false;
305
306     private static LongArrayMap<FolderInfo> sFolders = new LongArrayMap<>();
307
308     private View.OnTouchListener mHapticFeedbackTouchListener;
309
310     // Related to the auto-advancing of widgets
311     private final int ADVANCE_MSG = 1;
312     private final int mAdvanceInterval = 20000;
313     private final int mAdvanceStagger = 250;
314     private long mAutoAdvanceSentTime;
315     private long mAutoAdvanceTimeLeft = -1;
316     @Thunk HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
317         new HashMap<View, AppWidgetProviderInfo>();
318
319     // Determines how long to wait after a rotation before restoring the screen orientation to
320     // match the sensor state.
321     private final int mRestoreScreenOrientationDelay = 500;
322
323     @Thunk Drawable mWorkspaceBackgroundDrawable;
324
325     private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
326     private static final boolean DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE = false;
327
328     static final ArrayList<String> sDumpLogs = new ArrayList<String>();
329     static Date sDateStamp = new Date();
330     static DateFormat sDateFormat =
331             DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
332     static long sRunStart = System.currentTimeMillis();
333     static final String CORRUPTION_EMAIL_SENT_KEY = "corruptionEmailSent";
334
335     // We only want to get the SharedPreferences once since it does an FS stat each time we get
336     // it from the context.
337     private SharedPreferences mSharedPrefs;
338
339     // Holds the page that we need to animate to, and the icon views that we need to animate up
340     // when we scroll to that page on resume.
341     @Thunk ImageView mFolderIconImageView;
342     private Bitmap mFolderIconBitmap;
343     private Canvas mFolderIconCanvas;
344     private Rect mRectForFolderAnimation = new Rect();
345
346     private DeviceProfile mDeviceProfile;
347
348     // This is set to the view that launched the activity that navigated the user away from
349     // launcher. Since there is no callback for when the activity has finished launching, enable
350     // the press state and keep this reference to reset the press state when we return to launcher.
351     private BubbleTextView mWaitingForResume;
352
353     protected static HashMap<String, CustomAppWidget> sCustomAppWidgets =
354             new HashMap<String, CustomAppWidget>();
355
356     private static final boolean ENABLE_CUSTOM_WIDGET_TEST = false;
357     static {
358         if (ENABLE_CUSTOM_WIDGET_TEST) {
359             sCustomAppWidgets.put(DummyWidget.class.getName(), new DummyWidget());
360         }
361     }
362
363     // TODO: remove this field and call method directly when Launcher3 can depend on M APIs
364     private static Method sClipRevealMethod = null;
365     static {
366         Class<?> activityOptionsClass = ActivityOptions.class;
367         try {
368             sClipRevealMethod = activityOptionsClass.getDeclaredMethod("makeClipRevealAnimation",
369                     View.class, int.class, int.class, int.class, int.class);
370         } catch (Exception e) {
371             // Earlier version
372         }
373     }
374
375     @Thunk Runnable mBuildLayersRunnable = new Runnable() {
376         public void run() {
377             if (mWorkspace != null) {
378                 mWorkspace.buildPageHardwareLayers();
379             }
380         }
381     };
382
383     private static PendingAddArguments sPendingAddItem;
384
385     @Thunk static class PendingAddArguments {
386         int requestCode;
387         Intent intent;
388         long container;
389         long screenId;
390         int cellX;
391         int cellY;
392         int appWidgetId;
393     }
394
395     private Stats mStats;
396     FocusIndicatorView mFocusHandler;
397     private boolean mRotationEnabled = false;
398
399     @Thunk void setOrientation() {
400         if (mRotationEnabled) {
401             unlockScreenOrientation(true);
402         } else {
403             setRequestedOrientation(
404                     ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
405         }
406     }
407
408     private Runnable mUpdateOrientationRunnable = new Runnable() {
409         public void run() {
410             setOrientation();
411         }
412     };
413
414     @Override
415     protected void onCreate(Bundle savedInstanceState) {
416         if (DEBUG_STRICT_MODE) {
417             StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
418                     .detectDiskReads()
419                     .detectDiskWrites()
420                     .detectNetwork()   // or .detectAll() for all detectable problems
421                     .penaltyLog()
422                     .build());
423             StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
424                     .detectLeakedSqlLiteObjects()
425                     .detectLeakedClosableObjects()
426                     .penaltyLog()
427                     .penaltyDeath()
428                     .build());
429         }
430
431         if (mLauncherCallbacks != null) {
432             mLauncherCallbacks.preOnCreate();
433         }
434
435         super.onCreate(savedInstanceState);
436
437         LauncherAppState.setApplicationContext(getApplicationContext());
438         LauncherAppState app = LauncherAppState.getInstance();
439
440         // Load configuration-specific DeviceProfile
441         mDeviceProfile = getResources().getConfiguration().orientation
442                 == Configuration.ORIENTATION_LANDSCAPE ?
443                         app.getInvariantDeviceProfile().landscapeProfile
444                             : app.getInvariantDeviceProfile().portraitProfile;
445
446         mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
447                 Context.MODE_PRIVATE);
448         mIsSafeModeEnabled = getPackageManager().isSafeMode();
449         mModel = app.setLauncher(this);
450         mIconCache = app.getIconCache();
451
452         mDragController = new DragController(this);
453         mInflater = getLayoutInflater();
454         mStateTransitionAnimation = new LauncherStateTransitionAnimation(this);
455
456         mStats = new Stats(this);
457
458         mAppWidgetManager = AppWidgetManagerCompat.getInstance(this);
459
460         mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
461         mAppWidgetHost.startListening();
462
463         // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
464         // this also ensures that any synchronous binding below doesn't re-trigger another
465         // LauncherModel load.
466         mPaused = false;
467
468         if (PROFILE_STARTUP) {
469             android.os.Debug.startMethodTracing(
470                     Environment.getExternalStorageDirectory() + "/launcher");
471         }
472
473         setContentView(R.layout.launcher);
474
475         setupViews();
476         mDeviceProfile.layout(this);
477
478         lockAllApps();
479
480         mSavedState = savedInstanceState;
481         restoreState(mSavedState);
482
483         if (PROFILE_STARTUP) {
484             android.os.Debug.stopMethodTracing();
485         }
486
487         if (!mRestoring) {
488             if (DISABLE_SYNCHRONOUS_BINDING_CURRENT_PAGE) {
489                 // If the user leaves launcher, then we should just load items asynchronously when
490                 // they return.
491                 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE);
492             } else {
493                 // We only load the page synchronously if the user rotates (or triggers a
494                 // configuration change) while launcher is in the foreground
495                 mModel.startLoader(mWorkspace.getRestorePage());
496             }
497         }
498
499         // For handling default keys
500         mDefaultKeySsb = new SpannableStringBuilder();
501         Selection.setSelection(mDefaultKeySsb, 0);
502
503         IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
504         registerReceiver(mCloseSystemDialogsReceiver, filter);
505
506         mRotationEnabled = Utilities.isRotationAllowedForDevice(getApplicationContext());
507         // In case we are on a device with locked rotation, we should look at preferences to check
508         // if the user has specifically allowed rotation.
509         if (!mRotationEnabled) {
510             mRotationEnabled = Utilities.isAllowRotationPrefEnabled(getApplicationContext(), false);
511         }
512
513         // On large interfaces, or on devices that a user has specifically enabled screen rotation,
514         // we want the screen to auto-rotate based on the current orientation
515         setOrientation();
516
517         if (mLauncherCallbacks != null) {
518             mLauncherCallbacks.onCreate(savedInstanceState);
519             if (mLauncherCallbacks.hasLauncherOverlay()) {
520                 ViewStub stub = (ViewStub) findViewById(R.id.launcher_overlay_stub);
521                 mLauncherOverlayContainer = (InsettableFrameLayout) stub.inflate();
522                 mLauncherOverlay = mLauncherCallbacks.setLauncherOverlayView(
523                         mLauncherOverlayContainer, mLauncherOverlayCallbacks);
524                 mWorkspace.setLauncherOverlay(mLauncherOverlay);
525             }
526         }
527
528         if (shouldShowIntroScreen()) {
529             showIntroScreen();
530         } else {
531             showFirstRunActivity();
532             showFirstRunClings();
533         }
534     }
535
536     @Override
537     public void onSettingsChanged(String settings, boolean value) {
538         if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(settings)) {
539             mRotationEnabled = value;
540             if (!waitUntilResume(mUpdateOrientationRunnable, true)) {
541                 mUpdateOrientationRunnable.run();
542             }
543         }
544     }
545
546     private LauncherCallbacks mLauncherCallbacks;
547
548     public void onPostCreate(Bundle savedInstanceState) {
549         super.onPostCreate(savedInstanceState);
550         if (mLauncherCallbacks != null) {
551             mLauncherCallbacks.onPostCreate(savedInstanceState);
552         }
553     }
554
555     public boolean setLauncherCallbacks(LauncherCallbacks callbacks) {
556         mLauncherCallbacks = callbacks;
557         mLauncherCallbacks.setLauncherSearchCallback(new Launcher.LauncherSearchCallbacks() {
558             private boolean mWorkspaceImportanceStored = false;
559             private boolean mHotseatImportanceStored = false;
560             private int mWorkspaceImportanceForAccessibility =
561                 View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
562             private int mHotseatImportanceForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
563
564             @Override
565             public void onSearchOverlayOpened() {
566                 if (mWorkspaceImportanceStored || mHotseatImportanceStored) {
567                     return;
568                 }
569                 // The underlying workspace and hotseat are temporarily suppressed by the search
570                 // overlay. So they sholudn't be accessible.
571                 if (mWorkspace != null) {
572                     mWorkspaceImportanceForAccessibility =
573                             mWorkspace.getImportantForAccessibility();
574                     mWorkspace.setImportantForAccessibility(
575                             View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
576                     mWorkspaceImportanceStored = true;
577                 }
578                 if (mHotseat != null) {
579                     mHotseatImportanceForAccessibility = mHotseat.getImportantForAccessibility();
580                     mHotseat.setImportantForAccessibility(
581                             View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
582                     mHotseatImportanceStored = true;
583                 }
584             }
585
586             @Override
587             public void onSearchOverlayClosed() {
588                 if (mWorkspaceImportanceStored && mWorkspace != null) {
589                     mWorkspace.setImportantForAccessibility(mWorkspaceImportanceForAccessibility);
590                 }
591                 if (mHotseatImportanceStored && mHotseat != null) {
592                     mHotseat.setImportantForAccessibility(mHotseatImportanceForAccessibility);
593                 }
594                 mWorkspaceImportanceStored = false;
595                 mHotseatImportanceStored = false;
596             }
597         });
598         return true;
599     }
600
601     @Override
602     public void onLauncherProviderChange() {
603         if (mLauncherCallbacks != null) {
604             mLauncherCallbacks.onLauncherProviderChange();
605         }
606     }
607
608     /**
609      * Updates the bounds of all the overlays to match the new fixed bounds.
610      */
611     public void updateOverlayBounds(Rect newBounds) {
612         mAppsView.setSearchBarBounds(newBounds);
613         mWidgetsView.setSearchBarBounds(newBounds);
614     }
615
616     /** To be overridden by subclasses to hint to Launcher that we have custom content */
617     protected boolean hasCustomContentToLeft() {
618         if (mLauncherCallbacks != null) {
619             return mLauncherCallbacks.hasCustomContentToLeft();
620         }
621         return false;
622     }
623
624     /**
625      * To be overridden by subclasses to populate the custom content container and call
626      * {@link #addToCustomContentPage}. This will only be invoked if
627      * {@link #hasCustomContentToLeft()} is {@code true}.
628      */
629     protected void populateCustomContentContainer() {
630         if (mLauncherCallbacks != null) {
631             mLauncherCallbacks.populateCustomContentContainer();
632         }
633     }
634
635     /**
636      * Invoked by subclasses to signal a change to the {@link #addCustomContentToLeft} value to
637      * ensure the custom content page is added or removed if necessary.
638      */
639     protected void invalidateHasCustomContentToLeft() {
640         if (mWorkspace == null || mWorkspace.getScreenOrder().isEmpty()) {
641             // Not bound yet, wait for bindScreens to be called.
642             return;
643         }
644
645         if (!mWorkspace.hasCustomContent() && hasCustomContentToLeft()) {
646             // Create the custom content page and call the subclass to populate it.
647             mWorkspace.createCustomContentContainer();
648             populateCustomContentContainer();
649         } else if (mWorkspace.hasCustomContent() && !hasCustomContentToLeft()) {
650             mWorkspace.removeCustomContentPage();
651         }
652     }
653
654     public Stats getStats() {
655         return mStats;
656     }
657
658     public LayoutInflater getInflater() {
659         return mInflater;
660     }
661
662     public boolean isDraggingEnabled() {
663         // We prevent dragging when we are loading the workspace as it is possible to pick up a view
664         // that is subsequently removed from the workspace in startBinding().
665         return !mModel.isLoadingWorkspace();
666     }
667
668     @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
669     public static int generateViewId() {
670         if (Build.VERSION.SDK_INT >= 17) {
671             return View.generateViewId();
672         } else {
673             // View.generateViewId() is not available. The following fallback logic is a copy
674             // of its implementation.
675             for (;;) {
676                 final int result = sNextGeneratedId.get();
677                 // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
678                 int newValue = result + 1;
679                 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
680                 if (sNextGeneratedId.compareAndSet(result, newValue)) {
681                     return result;
682                 }
683             }
684         }
685     }
686
687     public int getViewIdForItem(ItemInfo info) {
688         // This cast is safe given the > 2B range for int.
689         int itemId = (int) info.id;
690         if (mItemIdToViewId.containsKey(itemId)) {
691             return mItemIdToViewId.get(itemId);
692         }
693         int viewId = generateViewId();
694         mItemIdToViewId.put(itemId, viewId);
695         return viewId;
696     }
697
698     /**
699      * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
700      * a configuration step, this allows the proper animations to run after other transitions.
701      */
702     private long completeAdd(PendingAddArguments args) {
703         long screenId = args.screenId;
704         if (args.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
705             // When the screen id represents an actual screen (as opposed to a rank) we make sure
706             // that the drop page actually exists.
707             screenId = ensurePendingDropLayoutExists(args.screenId);
708         }
709
710         switch (args.requestCode) {
711             case REQUEST_CREATE_SHORTCUT:
712                 completeAddShortcut(args.intent, args.container, screenId, args.cellX,
713                         args.cellY);
714                 break;
715             case REQUEST_CREATE_APPWIDGET:
716                 completeAddAppWidget(args.appWidgetId, args.container, screenId, null, null);
717                 break;
718             case REQUEST_RECONFIGURE_APPWIDGET:
719                 completeRestoreAppWidget(args.appWidgetId);
720                 break;
721         }
722         // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
723         // if you turned the screen off and then back while in All Apps, Launcher would not
724         // return to the workspace. Clearing mAddInfo.container here fixes this issue
725         resetAddInfo();
726         return screenId;
727     }
728
729     private void handleActivityResult(
730             final int requestCode, final int resultCode, final Intent data) {
731         // Reset the startActivity waiting flag
732         setWaitingForResult(false);
733         final int pendingAddWidgetId = mPendingAddWidgetId;
734         mPendingAddWidgetId = -1;
735
736         Runnable exitSpringLoaded = new Runnable() {
737             @Override
738             public void run() {
739                 exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED),
740                         EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
741             }
742         };
743
744         if (requestCode == REQUEST_BIND_APPWIDGET) {
745             final int appWidgetId = data != null ?
746                     data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
747             if (resultCode == RESULT_CANCELED) {
748                 completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
749                 mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
750                         ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
751             } else if (resultCode == RESULT_OK) {
752                 addAppWidgetImpl(appWidgetId, mPendingAddInfo, null,
753                         mPendingAddWidgetInfo, ON_ACTIVITY_RESULT_ANIMATION_DELAY);
754             }
755             return;
756         } else if (requestCode == REQUEST_PICK_WALLPAPER) {
757             if (resultCode == RESULT_OK && mWorkspace.isInOverviewMode()) {
758                 showWorkspace(false);
759             }
760             return;
761         }
762
763         boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
764                 requestCode == REQUEST_CREATE_APPWIDGET);
765
766         final boolean workspaceLocked = isWorkspaceLocked();
767         // We have special handling for widgets
768         if (isWidgetDrop) {
769             final int appWidgetId;
770             int widgetId = data != null ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)
771                     : -1;
772             if (widgetId < 0) {
773                 appWidgetId = pendingAddWidgetId;
774             } else {
775                 appWidgetId = widgetId;
776             }
777
778             final int result;
779             if (appWidgetId < 0 || resultCode == RESULT_CANCELED) {
780                 Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not " +
781                         "returned from the widget configuration activity.");
782                 result = RESULT_CANCELED;
783                 completeTwoStageWidgetDrop(result, appWidgetId);
784                 final Runnable onComplete = new Runnable() {
785                     @Override
786                     public void run() {
787                         exitSpringLoadedDragModeDelayed(false, 0, null);
788                     }
789                 };
790                 if (workspaceLocked) {
791                     // No need to remove the empty screen if we're mid-binding, as the
792                     // the bind will not add the empty screen.
793                     mWorkspace.postDelayed(onComplete, ON_ACTIVITY_RESULT_ANIMATION_DELAY);
794                 } else {
795                     mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete,
796                             ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
797                 }
798             } else {
799                 if (!workspaceLocked) {
800                     if (mPendingAddInfo.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
801                         // When the screen id represents an actual screen (as opposed to a rank)
802                         // we make sure that the drop page actually exists.
803                         mPendingAddInfo.screenId =
804                                 ensurePendingDropLayoutExists(mPendingAddInfo.screenId);
805                     }
806                     final CellLayout dropLayout = mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
807
808                     dropLayout.setDropPending(true);
809                     final Runnable onComplete = new Runnable() {
810                         @Override
811                         public void run() {
812                             completeTwoStageWidgetDrop(resultCode, appWidgetId);
813                             dropLayout.setDropPending(false);
814                         }
815                     };
816                     mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete,
817                             ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
818                 } else {
819                     PendingAddArguments args = preparePendingAddArgs(requestCode, data, appWidgetId,
820                             mPendingAddInfo);
821                     sPendingAddItem = args;
822                 }
823             }
824             return;
825         }
826
827         if (requestCode == REQUEST_RECONFIGURE_APPWIDGET) {
828             if (resultCode == RESULT_OK) {
829                 // Update the widget view.
830                 PendingAddArguments args = preparePendingAddArgs(requestCode, data,
831                         pendingAddWidgetId, mPendingAddInfo);
832                 if (workspaceLocked) {
833                     sPendingAddItem = args;
834                 } else {
835                     completeAdd(args);
836                 }
837             }
838             // Leave the widget in the pending state if the user canceled the configure.
839             return;
840         }
841
842         // The pattern used here is that a user PICKs a specific application,
843         // which, depending on the target, might need to CREATE the actual target.
844
845         // For example, the user would PICK_SHORTCUT for "Music playlist", and we
846         // launch over to the Music app to actually CREATE_SHORTCUT.
847         if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
848             final PendingAddArguments args = preparePendingAddArgs(requestCode, data, -1,
849                     mPendingAddInfo);
850             if (isWorkspaceLocked()) {
851                 sPendingAddItem = args;
852             } else {
853                 completeAdd(args);
854                 mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
855                         ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
856             }
857         } else if (resultCode == RESULT_CANCELED) {
858             mWorkspace.removeExtraEmptyScreenDelayed(true, exitSpringLoaded,
859                     ON_ACTIVITY_RESULT_ANIMATION_DELAY, false);
860         }
861         mDragLayer.clearAnimatedView();
862
863     }
864
865     @Override
866     protected void onActivityResult(
867             final int requestCode, final int resultCode, final Intent data) {
868         handleActivityResult(requestCode, resultCode, data);
869         if (mLauncherCallbacks != null) {
870             mLauncherCallbacks.onActivityResult(requestCode, resultCode, data);
871         }
872     }
873
874     /** @Override for MNC */
875     public void onRequestPermissionsResult(int requestCode, String[] permissions,
876             int[] grantResults) {
877         if (mLauncherCallbacks != null) {
878             mLauncherCallbacks.onRequestPermissionsResult(requestCode, permissions,
879                     grantResults);
880         }
881     }
882
883     private PendingAddArguments preparePendingAddArgs(int requestCode, Intent data, int
884             appWidgetId, ItemInfo info) {
885         PendingAddArguments args = new PendingAddArguments();
886         args.requestCode = requestCode;
887         args.intent = data;
888         args.container = info.container;
889         args.screenId = info.screenId;
890         args.cellX = info.cellX;
891         args.cellY = info.cellY;
892         args.appWidgetId = appWidgetId;
893         return args;
894     }
895
896     /**
897      * Check to see if a given screen id exists. If not, create it at the end, return the new id.
898      *
899      * @param screenId the screen id to check
900      * @return the new screen, or screenId if it exists
901      */
902     private long ensurePendingDropLayoutExists(long screenId) {
903         CellLayout dropLayout =
904                 (CellLayout) mWorkspace.getScreenWithId(screenId);
905         if (dropLayout == null) {
906             // it's possible that the add screen was removed because it was
907             // empty and a re-bind occurred
908             mWorkspace.addExtraEmptyScreen();
909             return mWorkspace.commitExtraEmptyScreen();
910         } else {
911             return screenId;
912         }
913     }
914
915     @Thunk void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
916         CellLayout cellLayout =
917                 (CellLayout) mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
918         Runnable onCompleteRunnable = null;
919         int animationType = 0;
920
921         AppWidgetHostView boundWidget = null;
922         if (resultCode == RESULT_OK) {
923             animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
924             final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
925                     mPendingAddWidgetInfo);
926             boundWidget = layout;
927             onCompleteRunnable = new Runnable() {
928                 @Override
929                 public void run() {
930                     completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
931                             mPendingAddInfo.screenId, layout, null);
932                     exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED),
933                             EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
934                 }
935             };
936         } else if (resultCode == RESULT_CANCELED) {
937             mAppWidgetHost.deleteAppWidgetId(appWidgetId);
938             animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
939         }
940         if (mDragLayer.getAnimatedView() != null) {
941             mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
942                     (DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
943                     animationType, boundWidget, true);
944         } else if (onCompleteRunnable != null) {
945             // The animated view may be null in the case of a rotation during widget configuration
946             onCompleteRunnable.run();
947         }
948     }
949
950     @Override
951     protected void onStop() {
952         super.onStop();
953         FirstFrameAnimatorHelper.setIsVisible(false);
954
955         if (mLauncherCallbacks != null) {
956             mLauncherCallbacks.onStop();
957         }
958     }
959
960     @Override
961     protected void onStart() {
962         super.onStart();
963         FirstFrameAnimatorHelper.setIsVisible(true);
964
965         if (mLauncherCallbacks != null) {
966             mLauncherCallbacks.onStart();
967         }
968     }
969
970     @Override
971     protected void onResume() {
972         long startTime = 0;
973         if (DEBUG_RESUME_TIME) {
974             startTime = System.currentTimeMillis();
975             Log.v(TAG, "Launcher.onResume()");
976         }
977
978         if (mLauncherCallbacks != null) {
979             mLauncherCallbacks.preOnResume();
980         }
981
982         super.onResume();
983
984         // Restore the previous launcher state
985         if (mOnResumeState == State.WORKSPACE) {
986             showWorkspace(false);
987         } else if (mOnResumeState == State.APPS) {
988             boolean launchedFromApp = (mWaitingForResume != null);
989             // Don't update the predicted apps if the user is returning to launcher in the apps
990             // view after launching an app, as they may be depending on the UI to be static to
991             // switch to another app, otherwise, if it was
992             showAppsView(false /* animated */, false /* resetListToTop */,
993                     !launchedFromApp /* updatePredictedApps */, false /* focusSearchBar */);
994         } else if (mOnResumeState == State.WIDGETS) {
995             showWidgetsView(false, false);
996         }
997         mOnResumeState = State.NONE;
998
999         // Background was set to gradient in onPause(), restore to transparent if in all apps.
1000         setWorkspaceBackground(mState == State.WORKSPACE ? WORKSPACE_BACKGROUND_GRADIENT
1001                 : WORKSPACE_BACKGROUND_TRANSPARENT);
1002
1003         mPaused = false;
1004         if (mRestoring || mOnResumeNeedsLoad) {
1005             setWorkspaceLoading(true);
1006             mModel.startLoader(PagedView.INVALID_RESTORE_PAGE);
1007             mRestoring = false;
1008             mOnResumeNeedsLoad = false;
1009         }
1010         if (mBindOnResumeCallbacks.size() > 0) {
1011             // We might have postponed some bind calls until onResume (see waitUntilResume) --
1012             // execute them here
1013             long startTimeCallbacks = 0;
1014             if (DEBUG_RESUME_TIME) {
1015                 startTimeCallbacks = System.currentTimeMillis();
1016             }
1017
1018             for (int i = 0; i < mBindOnResumeCallbacks.size(); i++) {
1019                 mBindOnResumeCallbacks.get(i).run();
1020             }
1021             mBindOnResumeCallbacks.clear();
1022             if (DEBUG_RESUME_TIME) {
1023                 Log.d(TAG, "Time spent processing callbacks in onResume: " +
1024                     (System.currentTimeMillis() - startTimeCallbacks));
1025             }
1026         }
1027         if (mOnResumeCallbacks.size() > 0) {
1028             for (int i = 0; i < mOnResumeCallbacks.size(); i++) {
1029                 mOnResumeCallbacks.get(i).run();
1030             }
1031             mOnResumeCallbacks.clear();
1032         }
1033
1034         // Reset the pressed state of icons that were locked in the press state while activities
1035         // were launching
1036         if (mWaitingForResume != null) {
1037             // Resets the previous workspace icon press state
1038             mWaitingForResume.setStayPressed(false);
1039         }
1040
1041         // It is possible that widgets can receive updates while launcher is not in the foreground.
1042         // Consequently, the widgets will be inflated in the orientation of the foreground activity
1043         // (framework issue). On resuming, we ensure that any widgets are inflated for the current
1044         // orientation.
1045         getWorkspace().reinflateWidgetsIfNecessary();
1046         reinflateQSBIfNecessary();
1047
1048         if (DEBUG_RESUME_TIME) {
1049             Log.d(TAG, "Time spent in onResume: " + (System.currentTimeMillis() - startTime));
1050         }
1051
1052         if (mWorkspace.getCustomContentCallbacks() != null) {
1053             // If we are resuming and the custom content is the current page, we call onShow().
1054             // It is also poassible that onShow will instead be called slightly after first layout
1055             // if PagedView#setRestorePage was set to the custom content page in onCreate().
1056             if (mWorkspace.isOnOrMovingToCustomContent()) {
1057                 mWorkspace.getCustomContentCallbacks().onShow(true);
1058             }
1059         }
1060         updateInteraction(Workspace.State.NORMAL, mWorkspace.getState());
1061         mWorkspace.onResume();
1062
1063         if (!isWorkspaceLoading()) {
1064             // Process any items that were added while Launcher was away.
1065             InstallShortcutReceiver.disableAndFlushInstallQueue(this);
1066         }
1067
1068         if (mLauncherCallbacks != null) {
1069             mLauncherCallbacks.onResume();
1070         }
1071     }
1072
1073     @Override
1074     protected void onPause() {
1075         // Ensure that items added to Launcher are queued until Launcher returns
1076         InstallShortcutReceiver.enableInstallQueue();
1077
1078         super.onPause();
1079         mPaused = true;
1080         mDragController.cancelDrag();
1081         mDragController.resetLastGestureUpTime();
1082
1083         // We call onHide() aggressively. The custom content callbacks should be able to
1084         // debounce excess onHide calls.
1085         if (mWorkspace.getCustomContentCallbacks() != null) {
1086             mWorkspace.getCustomContentCallbacks().onHide();
1087         }
1088
1089         if (mLauncherCallbacks != null) {
1090             mLauncherCallbacks.onPause();
1091         }
1092     }
1093
1094     public interface CustomContentCallbacks {
1095         // Custom content is completely shown. {@code fromResume} indicates whether this was caused
1096         // by a onResume or by scrolling otherwise.
1097         public void onShow(boolean fromResume);
1098
1099         // Custom content is completely hidden
1100         public void onHide();
1101
1102         // Custom content scroll progress changed. From 0 (not showing) to 1 (fully showing).
1103         public void onScrollProgressChanged(float progress);
1104
1105         // Indicates whether the user is allowed to scroll away from the custom content.
1106         boolean isScrollingAllowed();
1107     }
1108
1109     public interface LauncherOverlay {
1110
1111         /**
1112          * Touch interaction leading to overscroll has begun
1113          */
1114         public void onScrollInteractionBegin();
1115
1116         /**
1117          * Touch interaction related to overscroll has ended
1118          */
1119         public void onScrollInteractionEnd();
1120
1121         /**
1122          * Scroll progress, between 0 and 100, when the user scrolls beyond the leftmost
1123          * screen (or in the case of RTL, the rightmost screen).
1124          */
1125         public void onScrollChange(int progress, boolean rtl);
1126
1127         /**
1128          * Screen has stopped scrolling
1129          */
1130         public void onScrollSettled();
1131
1132         /**
1133          * This method can be called by the Launcher in order to force the LauncherOverlay
1134          * to exit fully immersive mode.
1135          */
1136         public void forceExitFullImmersion();
1137     }
1138
1139     public interface LauncherSearchCallbacks {
1140         /**
1141          * Called when the search overlay is shown.
1142          */
1143         public void onSearchOverlayOpened();
1144
1145         /**
1146          * Called when the search overlay is dismissed.
1147          */
1148         public void onSearchOverlayClosed();
1149     }
1150
1151     public interface LauncherOverlayCallbacks {
1152         /**
1153          * This method indicates whether a call to {@link #enterFullImmersion()} will succeed,
1154          * however it doesn't modify any state within the launcher.
1155          */
1156         public boolean canEnterFullImmersion();
1157
1158         /**
1159          * Should be called to tell Launcher that the LauncherOverlay will take over interaction,
1160          * eg. by occupying the full screen and handling all touch events.
1161          *
1162          * @return true if Launcher allows the LauncherOverlay to become fully immersive. In this
1163          *          case, Launcher will modify any necessary state and assumes the overlay is
1164          *          handling all interaction. If false, the LauncherOverlay should cancel any
1165          *
1166          */
1167         public boolean enterFullImmersion();
1168
1169         /**
1170          * Must be called when exiting fully immersive mode. Indicates to Launcher that it has
1171          * full control over UI and state.
1172          */
1173         public void exitFullImmersion();
1174     }
1175
1176     class LauncherOverlayCallbacksImpl implements LauncherOverlayCallbacks {
1177
1178         @Override
1179         public boolean canEnterFullImmersion() {
1180             return mState == State.WORKSPACE;
1181         }
1182
1183         @Override
1184         public boolean enterFullImmersion() {
1185             if (mState == State.WORKSPACE) {
1186                 // When fully immersed, disregard any touches which fall through.
1187                 mDragLayer.setBlockTouch(true);
1188                 return true;
1189             }
1190             return false;
1191         }
1192
1193         @Override
1194         public void exitFullImmersion() {
1195             mDragLayer.setBlockTouch(false);
1196         }
1197     }
1198
1199     protected boolean hasSettings() {
1200         if (mLauncherCallbacks != null) {
1201             return mLauncherCallbacks.hasSettings();
1202         } else {
1203             // On devices with a locked orientation, we will at least have the allow rotation
1204             // setting.
1205             return !Utilities.isRotationAllowedForDevice(this);
1206         }
1207     }
1208
1209     public void addToCustomContentPage(View customContent,
1210             CustomContentCallbacks callbacks, String description) {
1211         mWorkspace.addToCustomContentPage(customContent, callbacks, description);
1212     }
1213
1214     // The custom content needs to offset its content to account for the QSB
1215     public int getTopOffsetForCustomContent() {
1216         return mWorkspace.getPaddingTop();
1217     }
1218
1219     @Override
1220     public Object onRetainNonConfigurationInstance() {
1221         // Flag the loader to stop early before switching
1222         if (mModel.isCurrentCallbacks(this)) {
1223             mModel.stopLoader();
1224         }
1225         //TODO(hyunyoungs): stop the widgets loader when there is a rotation.
1226
1227         return Boolean.TRUE;
1228     }
1229
1230     // We can't hide the IME if it was forced open.  So don't bother
1231     @Override
1232     public void onWindowFocusChanged(boolean hasFocus) {
1233         super.onWindowFocusChanged(hasFocus);
1234         mHasFocus = hasFocus;
1235
1236         if (mLauncherCallbacks != null) {
1237             mLauncherCallbacks.onWindowFocusChanged(hasFocus);
1238         }
1239     }
1240
1241     private boolean acceptFilter() {
1242         final InputMethodManager inputManager = (InputMethodManager)
1243                 getSystemService(Context.INPUT_METHOD_SERVICE);
1244         return !inputManager.isFullscreenMode();
1245     }
1246
1247     @Override
1248     public boolean onKeyDown(int keyCode, KeyEvent event) {
1249         final int uniChar = event.getUnicodeChar();
1250         final boolean handled = super.onKeyDown(keyCode, event);
1251         final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
1252         if (!handled && acceptFilter() && isKeyNotWhitespace) {
1253             boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
1254                     keyCode, event);
1255             if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
1256                 // something usable has been typed - start a search
1257                 // the typed text will be retrieved and cleared by
1258                 // showSearchDialog()
1259                 // If there are multiple keystrokes before the search dialog takes focus,
1260                 // onSearchRequested() will be called for every keystroke,
1261                 // but it is idempotent, so it's fine.
1262                 return onSearchRequested();
1263             }
1264         }
1265
1266         // Eat the long press event so the keyboard doesn't come up.
1267         if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
1268             return true;
1269         }
1270
1271         return handled;
1272     }
1273
1274     private String getTypedText() {
1275         return mDefaultKeySsb.toString();
1276     }
1277
1278     private void clearTypedText() {
1279         mDefaultKeySsb.clear();
1280         mDefaultKeySsb.clearSpans();
1281         Selection.setSelection(mDefaultKeySsb, 0);
1282     }
1283
1284     /**
1285      * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
1286      * State
1287      */
1288     private static State intToState(int stateOrdinal) {
1289         State state = State.WORKSPACE;
1290         final State[] stateValues = State.values();
1291         for (int i = 0; i < stateValues.length; i++) {
1292             if (stateValues[i].ordinal() == stateOrdinal) {
1293                 state = stateValues[i];
1294                 break;
1295             }
1296         }
1297         return state;
1298     }
1299
1300     /**
1301      * Restores the previous state, if it exists.
1302      *
1303      * @param savedState The previous state.
1304      */
1305     @SuppressWarnings("unchecked")
1306     private void restoreState(Bundle savedState) {
1307         if (savedState == null) {
1308             return;
1309         }
1310
1311         State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
1312         if (state == State.APPS || state == State.WIDGETS) {
1313             mOnResumeState = state;
1314         }
1315
1316         int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN,
1317                 PagedView.INVALID_RESTORE_PAGE);
1318         if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
1319             mWorkspace.setRestorePage(currentScreen);
1320         }
1321
1322         final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
1323         final long pendingAddScreen = savedState.getLong(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
1324
1325         if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
1326             mPendingAddInfo.container = pendingAddContainer;
1327             mPendingAddInfo.screenId = pendingAddScreen;
1328             mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
1329             mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
1330             mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
1331             mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
1332             AppWidgetProviderInfo info = savedState.getParcelable(
1333                     RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
1334             mPendingAddWidgetInfo = info == null ?
1335                     null : LauncherAppWidgetProviderInfo.fromProviderInfo(this, info);
1336
1337             mPendingAddWidgetId = savedState.getInt(RUNTIME_STATE_PENDING_ADD_WIDGET_ID);
1338             setWaitingForResult(true);
1339             mRestoring = true;
1340         }
1341
1342         mItemIdToViewId = (HashMap<Integer, Integer>)
1343                 savedState.getSerializable(RUNTIME_STATE_VIEW_IDS);
1344     }
1345
1346     /**
1347      * Finds all the views we need and configure them properly.
1348      */
1349     private void setupViews() {
1350         final DragController dragController = mDragController;
1351
1352         mLauncherView = findViewById(R.id.launcher);
1353         mFocusHandler = (FocusIndicatorView) findViewById(R.id.focus_indicator);
1354         mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
1355         mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
1356         mWorkspace.setPageSwitchListener(this);
1357         mPageIndicators = mDragLayer.findViewById(R.id.page_indicator);
1358
1359         mLauncherView.setSystemUiVisibility(
1360                 View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
1361         mWorkspaceBackgroundDrawable = getResources().getDrawable(R.drawable.workspace_bg);
1362
1363         // Setup the drag layer
1364         mDragLayer.setup(this, dragController);
1365
1366         // Setup the hotseat
1367         mHotseat = (Hotseat) findViewById(R.id.hotseat);
1368         if (mHotseat != null) {
1369             mHotseat.setOnLongClickListener(this);
1370         }
1371
1372         mOverviewPanel = (ViewGroup) findViewById(R.id.overview_panel);
1373         mWidgetsButton = findViewById(R.id.widget_button);
1374         mWidgetsButton.setOnClickListener(new OnClickListener() {
1375             @Override
1376             public void onClick(View arg0) {
1377                 if (!mWorkspace.isSwitchingState()) {
1378                     onClickAddWidgetButton(arg0);
1379                 }
1380             }
1381         });
1382         mWidgetsButton.setOnTouchListener(getHapticFeedbackTouchListener());
1383
1384         View wallpaperButton = findViewById(R.id.wallpaper_button);
1385         wallpaperButton.setOnClickListener(new OnClickListener() {
1386             @Override
1387             public void onClick(View arg0) {
1388                 if (!mWorkspace.isSwitchingState()) {
1389                     onClickWallpaperPicker(arg0);
1390                 }
1391             }
1392         });
1393         wallpaperButton.setOnTouchListener(getHapticFeedbackTouchListener());
1394
1395         View settingsButton = findViewById(R.id.settings_button);
1396         if (hasSettings()) {
1397             settingsButton.setOnClickListener(new OnClickListener() {
1398                 @Override
1399                 public void onClick(View arg0) {
1400                     if (!mWorkspace.isSwitchingState()) {
1401                         onClickSettingsButton(arg0);
1402                     }
1403                 }
1404             });
1405             settingsButton.setOnTouchListener(getHapticFeedbackTouchListener());
1406         } else {
1407             settingsButton.setVisibility(View.GONE);
1408         }
1409
1410         mOverviewPanel.setAlpha(0f);
1411
1412         // Setup the workspace
1413         mWorkspace.setHapticFeedbackEnabled(false);
1414         mWorkspace.setOnLongClickListener(this);
1415         mWorkspace.setup(dragController);
1416         dragController.addDragListener(mWorkspace);
1417
1418         // Get the search/delete bar
1419         mSearchDropTargetBar = (SearchDropTargetBar)
1420                 mDragLayer.findViewById(R.id.search_drop_target_bar);
1421
1422         // Setup Apps and Widgets
1423         mAppsView = (AllAppsContainerView) findViewById(R.id.apps_view);
1424         mWidgetsView = (WidgetsContainerView) findViewById(R.id.widgets_view);
1425         if (mLauncherCallbacks != null && mLauncherCallbacks.getAllAppsSearchBarController() != null) {
1426             mAppsView.setSearchBarController(mLauncherCallbacks.getAllAppsSearchBarController());
1427         } else {
1428             mAppsView.setSearchBarController(mAppsView.newDefaultAppSearchController());
1429         }
1430
1431         // Setup the drag controller (drop targets have to be added in reverse order in priority)
1432         dragController.setDragScoller(mWorkspace);
1433         dragController.setScrollView(mDragLayer);
1434         dragController.setMoveTarget(mWorkspace);
1435         dragController.addDropTarget(mWorkspace);
1436         if (mSearchDropTargetBar != null) {
1437             mSearchDropTargetBar.setup(this, dragController);
1438             mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
1439         }
1440
1441         if (getResources().getBoolean(R.bool.debug_memory_enabled)) {
1442             Log.v(TAG, "adding WeightWatcher");
1443             mWeightWatcher = new WeightWatcher(this);
1444             mWeightWatcher.setAlpha(0.5f);
1445             ((FrameLayout) mLauncherView).addView(mWeightWatcher,
1446                     new FrameLayout.LayoutParams(
1447                             FrameLayout.LayoutParams.MATCH_PARENT,
1448                             FrameLayout.LayoutParams.WRAP_CONTENT,
1449                             Gravity.BOTTOM)
1450             );
1451
1452             boolean show = shouldShowWeightWatcher();
1453             mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
1454         }
1455     }
1456
1457     /**
1458      * Sets the all apps button. This method is called from {@link Hotseat}.
1459      */
1460     public void setAllAppsButton(View allAppsButton) {
1461         mAllAppsButton = allAppsButton;
1462     }
1463
1464     public View getAllAppsButton() {
1465         return mAllAppsButton;
1466     }
1467
1468     public View getWidgetsButton() {
1469         return mWidgetsButton;
1470     }
1471
1472     /**
1473      * Creates a view representing a shortcut.
1474      *
1475      * @param info The data structure describing the shortcut.
1476      */
1477     View createShortcut(ShortcutInfo info) {
1478         return createShortcut((ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
1479     }
1480
1481     /**
1482      * Creates a view representing a shortcut inflated from the specified resource.
1483      *
1484      * @param parent The group the shortcut belongs to.
1485      * @param info The data structure describing the shortcut.
1486      *
1487      * @return A View inflated from layoutResId.
1488      */
1489     public View createShortcut(ViewGroup parent, ShortcutInfo info) {
1490         BubbleTextView favorite = (BubbleTextView) mInflater.inflate(R.layout.app_icon,
1491                 parent, false);
1492         favorite.applyFromShortcutInfo(info, mIconCache);
1493         favorite.setCompoundDrawablePadding(mDeviceProfile.iconDrawablePaddingPx);
1494         favorite.setOnClickListener(this);
1495         favorite.setOnFocusChangeListener(mFocusHandler);
1496         return favorite;
1497     }
1498
1499     /**
1500      * Add a shortcut to the workspace.
1501      *
1502      * @param data The intent describing the shortcut.
1503      */
1504     private void completeAddShortcut(Intent data, long container, long screenId, int cellX,
1505             int cellY) {
1506         int[] cellXY = mTmpAddItemCellCoordinates;
1507         int[] touchXY = mPendingAddInfo.dropPos;
1508         CellLayout layout = getCellLayout(container, screenId);
1509
1510         ShortcutInfo info = InstallShortcutReceiver.fromShortcutIntent(this, data);
1511         if (info == null) {
1512             return;
1513         }
1514         final View view = createShortcut(info);
1515
1516         boolean foundCellSpan = false;
1517         // First we check if we already know the exact location where we want to add this item.
1518         if (cellX >= 0 && cellY >= 0) {
1519             cellXY[0] = cellX;
1520             cellXY[1] = cellY;
1521             foundCellSpan = true;
1522
1523             // If appropriate, either create a folder or add to an existing folder
1524             if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
1525                     true, null,null)) {
1526                 return;
1527             }
1528             DragObject dragObject = new DragObject();
1529             dragObject.dragInfo = info;
1530             if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
1531                     true)) {
1532                 return;
1533             }
1534         } else if (touchXY != null) {
1535             // when dragging and dropping, just find the closest free spot
1536             int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
1537             foundCellSpan = (result != null);
1538         } else {
1539             foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
1540         }
1541
1542         if (!foundCellSpan) {
1543             showOutOfSpaceMessage(isHotseatLayout(layout));
1544             return;
1545         }
1546
1547         LauncherModel.addItemToDatabase(this, info, container, screenId, cellXY[0], cellXY[1]);
1548
1549         if (!mRestoring) {
1550             mWorkspace.addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1,
1551                     isWorkspaceLocked());
1552         }
1553     }
1554
1555     /**
1556      * Add a widget to the workspace.
1557      *
1558      * @param appWidgetId The app widget id
1559      */
1560     @Thunk void completeAddAppWidget(int appWidgetId, long container, long screenId,
1561             AppWidgetHostView hostView, LauncherAppWidgetProviderInfo appWidgetInfo) {
1562
1563         ItemInfo info = mPendingAddInfo;
1564         if (appWidgetInfo == null) {
1565             appWidgetInfo = LauncherAppWidgetProviderInfo.fromProviderInfo(this,
1566                     mAppWidgetManager.getAppWidgetInfo(appWidgetId));
1567         }
1568
1569         if (appWidgetInfo.isCustomWidget) {
1570             appWidgetId = LauncherAppWidgetInfo.CUSTOM_WIDGET_ID;
1571         }
1572
1573         LauncherAppWidgetInfo launcherInfo;
1574         launcherInfo = new LauncherAppWidgetInfo(appWidgetId, appWidgetInfo.provider);
1575         launcherInfo.spanX = info.spanX;
1576         launcherInfo.spanY = info.spanY;
1577         launcherInfo.minSpanX = info.minSpanX;
1578         launcherInfo.minSpanY = info.minSpanY;
1579         launcherInfo.user = mAppWidgetManager.getUser(appWidgetInfo);
1580
1581         LauncherModel.addItemToDatabase(this, launcherInfo,
1582                 container, screenId, info.cellX, info.cellY);
1583
1584         if (!mRestoring) {
1585             if (hostView == null) {
1586                 // Perform actual inflation because we're live
1587                 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId,
1588                         appWidgetInfo);
1589             } else {
1590                 // The AppWidgetHostView has already been inflated and instantiated
1591                 launcherInfo.hostView = hostView;
1592             }
1593             launcherInfo.hostView.setTag(launcherInfo);
1594             launcherInfo.hostView.setVisibility(View.VISIBLE);
1595             launcherInfo.notifyWidgetSizeChanged(this);
1596
1597             mWorkspace.addInScreen(launcherInfo.hostView, container, screenId, info.cellX,
1598                     info.cellY, launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1599
1600             addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1601         }
1602         resetAddInfo();
1603     }
1604
1605     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1606         @Override
1607         public void onReceive(Context context, Intent intent) {
1608             final String action = intent.getAction();
1609             if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1610                 mUserPresent = false;
1611                 mDragLayer.clearAllResizeFrames();
1612                 updateAutoAdvanceState();
1613
1614                 // Reset AllApps to its initial state only if we are not in the middle of
1615                 // processing a multi-step drop
1616                 if (mAppsView != null && mWidgetsView != null &&
1617                         mPendingAddInfo.container == ItemInfo.NO_ID) {
1618                     showWorkspace(false);
1619                 }
1620             } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1621                 mUserPresent = true;
1622                 updateAutoAdvanceState();
1623             } else if (ENABLE_DEBUG_INTENTS && DebugIntents.DELETE_DATABASE.equals(action)) {
1624                 mModel.resetLoadedState(false, true);
1625                 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE,
1626                         LauncherModel.LOADER_FLAG_CLEAR_WORKSPACE);
1627             } else if (ENABLE_DEBUG_INTENTS && DebugIntents.MIGRATE_DATABASE.equals(action)) {
1628                 mModel.resetLoadedState(false, true);
1629                 mModel.startLoader(PagedView.INVALID_RESTORE_PAGE,
1630                         LauncherModel.LOADER_FLAG_CLEAR_WORKSPACE
1631                                 | LauncherModel.LOADER_FLAG_MIGRATE_SHORTCUTS);
1632             }
1633         }
1634     };
1635
1636     @Override
1637     public void onAttachedToWindow() {
1638         super.onAttachedToWindow();
1639
1640         // Listen for broadcasts related to user-presence
1641         final IntentFilter filter = new IntentFilter();
1642         filter.addAction(Intent.ACTION_SCREEN_OFF);
1643         filter.addAction(Intent.ACTION_USER_PRESENT);
1644         // For handling managed profiles
1645         if (ENABLE_DEBUG_INTENTS) {
1646             filter.addAction(DebugIntents.DELETE_DATABASE);
1647             filter.addAction(DebugIntents.MIGRATE_DATABASE);
1648         }
1649         registerReceiver(mReceiver, filter);
1650         FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView());
1651         setupTransparentSystemBarsForLmp();
1652         mAttached = true;
1653         mVisible = true;
1654     }
1655
1656     /**
1657      * Sets up transparent navigation and status bars in LMP.
1658      * This method is a no-op for other platform versions.
1659      */
1660     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
1661     private void setupTransparentSystemBarsForLmp() {
1662         if (Utilities.isLmpOrAbove()) {
1663             Window window = getWindow();
1664             window.getAttributes().systemUiVisibility |=
1665                     (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
1666                             | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
1667                             | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
1668             window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
1669                     | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1670             window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
1671             window.setStatusBarColor(Color.TRANSPARENT);
1672             window.setNavigationBarColor(Color.TRANSPARENT);
1673         }
1674     }
1675
1676     @Override
1677     public void onDetachedFromWindow() {
1678         super.onDetachedFromWindow();
1679         mVisible = false;
1680
1681         if (mAttached) {
1682             unregisterReceiver(mReceiver);
1683             mAttached = false;
1684         }
1685         updateAutoAdvanceState();
1686     }
1687
1688     public void onWindowVisibilityChanged(int visibility) {
1689         mVisible = visibility == View.VISIBLE;
1690         updateAutoAdvanceState();
1691         // The following code used to be in onResume, but it turns out onResume is called when
1692         // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
1693         // is a more appropriate event to handle
1694         if (mVisible) {
1695             if (!mWorkspaceLoading) {
1696                 final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
1697                 // We want to let Launcher draw itself at least once before we force it to build
1698                 // layers on all the workspace pages, so that transitioning to Launcher from other
1699                 // apps is nice and speedy.
1700                 observer.addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
1701                     private boolean mStarted = false;
1702                     public void onDraw() {
1703                         if (mStarted) return;
1704                         mStarted = true;
1705                         // We delay the layer building a bit in order to give
1706                         // other message processing a time to run.  In particular
1707                         // this avoids a delay in hiding the IME if it was
1708                         // currently shown, because doing that may involve
1709                         // some communication back with the app.
1710                         mWorkspace.postDelayed(mBuildLayersRunnable, 500);
1711                         final ViewTreeObserver.OnDrawListener listener = this;
1712                         mWorkspace.post(new Runnable() {
1713                                 public void run() {
1714                                     if (mWorkspace != null &&
1715                                             mWorkspace.getViewTreeObserver() != null) {
1716                                         mWorkspace.getViewTreeObserver().
1717                                                 removeOnDrawListener(listener);
1718                                     }
1719                                 }
1720                             });
1721                         return;
1722                     }
1723                 });
1724             }
1725             clearTypedText();
1726         }
1727     }
1728
1729     @Thunk void sendAdvanceMessage(long delay) {
1730         mHandler.removeMessages(ADVANCE_MSG);
1731         Message msg = mHandler.obtainMessage(ADVANCE_MSG);
1732         mHandler.sendMessageDelayed(msg, delay);
1733         mAutoAdvanceSentTime = System.currentTimeMillis();
1734     }
1735
1736     @Thunk void updateAutoAdvanceState() {
1737         boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
1738         if (autoAdvanceRunning != mAutoAdvanceRunning) {
1739             mAutoAdvanceRunning = autoAdvanceRunning;
1740             if (autoAdvanceRunning) {
1741                 long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
1742                 sendAdvanceMessage(delay);
1743             } else {
1744                 if (!mWidgetsToAdvance.isEmpty()) {
1745                     mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
1746                             (System.currentTimeMillis() - mAutoAdvanceSentTime));
1747                 }
1748                 mHandler.removeMessages(ADVANCE_MSG);
1749                 mHandler.removeMessages(0); // Remove messages sent using postDelayed()
1750             }
1751         }
1752     }
1753
1754     @Thunk final Handler mHandler = new Handler(new Handler.Callback() {
1755
1756         @Override
1757         public boolean handleMessage(Message msg) {
1758             if (msg.what == ADVANCE_MSG) {
1759                 int i = 0;
1760                 for (View key: mWidgetsToAdvance.keySet()) {
1761                     final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
1762                     final int delay = mAdvanceStagger * i;
1763                     if (v instanceof Advanceable) {
1764                         mHandler.postDelayed(new Runnable() {
1765                            public void run() {
1766                                ((Advanceable) v).advance();
1767                            }
1768                        }, delay);
1769                     }
1770                     i++;
1771                 }
1772                 sendAdvanceMessage(mAdvanceInterval);
1773             }
1774             return true;
1775         }
1776     });
1777
1778     void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1779         if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
1780         View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1781         if (v instanceof Advanceable) {
1782             mWidgetsToAdvance.put(hostView, appWidgetInfo);
1783             ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1784             updateAutoAdvanceState();
1785         }
1786     }
1787
1788     void removeWidgetToAutoAdvance(View hostView) {
1789         if (mWidgetsToAdvance.containsKey(hostView)) {
1790             mWidgetsToAdvance.remove(hostView);
1791             updateAutoAdvanceState();
1792         }
1793     }
1794
1795     public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1796         removeWidgetToAutoAdvance(launcherInfo.hostView);
1797         launcherInfo.hostView = null;
1798     }
1799
1800     public void showOutOfSpaceMessage(boolean isHotseatLayout) {
1801         int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
1802         Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
1803     }
1804
1805     public DragLayer getDragLayer() {
1806         return mDragLayer;
1807     }
1808
1809     public AllAppsContainerView getAppsView() {
1810         return mAppsView;
1811     }
1812
1813     public WidgetsContainerView getWidgetsView() {
1814         return mWidgetsView;
1815     }
1816
1817     public Workspace getWorkspace() {
1818         return mWorkspace;
1819     }
1820
1821     public Hotseat getHotseat() {
1822         return mHotseat;
1823     }
1824
1825     public ViewGroup getOverviewPanel() {
1826         return mOverviewPanel;
1827     }
1828
1829     public SearchDropTargetBar getSearchDropTargetBar() {
1830         return mSearchDropTargetBar;
1831     }
1832
1833     public LauncherAppWidgetHost getAppWidgetHost() {
1834         return mAppWidgetHost;
1835     }
1836
1837     public LauncherModel getModel() {
1838         return mModel;
1839     }
1840
1841     protected SharedPreferences getSharedPrefs() {
1842         return mSharedPrefs;
1843     }
1844
1845     public DeviceProfile getDeviceProfile() {
1846         return mDeviceProfile;
1847     }
1848
1849     public void closeSystemDialogs() {
1850         getWindow().closeAllPanels();
1851
1852         // Whatever we were doing is hereby canceled.
1853         setWaitingForResult(false);
1854     }
1855
1856     @Override
1857     protected void onNewIntent(Intent intent) {
1858         long startTime = 0;
1859         if (DEBUG_RESUME_TIME) {
1860             startTime = System.currentTimeMillis();
1861         }
1862         super.onNewIntent(intent);
1863
1864         // Close the menu
1865         if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1866             // also will cancel mWaitingForResult.
1867             closeSystemDialogs();
1868
1869             final boolean alreadyOnHome = mHasFocus && ((intent.getFlags() &
1870                     Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1871                     != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1872
1873             if (mWorkspace == null) {
1874                 // Can be cases where mWorkspace is null, this prevents a NPE
1875                 return;
1876             }
1877             Folder openFolder = mWorkspace.getOpenFolder();
1878             // In all these cases, only animate if we're already on home
1879             mWorkspace.exitWidgetResizeMode();
1880
1881             boolean moveToDefaultScreen = mLauncherCallbacks != null ?
1882                     mLauncherCallbacks.shouldMoveToDefaultScreenOnHomeIntent() : true;
1883             if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
1884                     openFolder == null && moveToDefaultScreen) {
1885                 mWorkspace.moveToDefaultScreen(true);
1886             }
1887
1888             closeFolder();
1889             exitSpringLoadedDragMode();
1890
1891             // If we are already on home, then just animate back to the workspace,
1892             // otherwise, just wait until onResume to set the state back to Workspace
1893             if (alreadyOnHome) {
1894                 showWorkspace(true);
1895             } else {
1896                 mOnResumeState = State.WORKSPACE;
1897             }
1898
1899             final View v = getWindow().peekDecorView();
1900             if (v != null && v.getWindowToken() != null) {
1901                 InputMethodManager imm = (InputMethodManager)getSystemService(
1902                         INPUT_METHOD_SERVICE);
1903                 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1904             }
1905
1906             // Reset the apps view
1907             if (!alreadyOnHome && mAppsView != null) {
1908                 mAppsView.scrollToTop();
1909             }
1910
1911             // Reset the widgets view
1912             if (!alreadyOnHome && mWidgetsView != null) {
1913                 mWidgetsView.scrollToTop();
1914             }
1915
1916             if (mLauncherCallbacks != null) {
1917                 mLauncherCallbacks.onHomeIntent();
1918             }
1919         }
1920
1921         if (DEBUG_RESUME_TIME) {
1922             Log.d(TAG, "Time spent in onNewIntent: " + (System.currentTimeMillis() - startTime));
1923         }
1924
1925         if (mLauncherCallbacks != null) {
1926             mLauncherCallbacks.onNewIntent(intent);
1927         }
1928     }
1929
1930     @Override
1931     public void onRestoreInstanceState(Bundle state) {
1932         super.onRestoreInstanceState(state);
1933         for (int page: mSynchronouslyBoundPages) {
1934             mWorkspace.restoreInstanceStateForChild(page);
1935         }
1936     }
1937
1938     @Override
1939     protected void onSaveInstanceState(Bundle outState) {
1940         if (mWorkspace.getChildCount() > 0) {
1941             outState.putInt(RUNTIME_STATE_CURRENT_SCREEN,
1942                     mWorkspace.getCurrentPageOffsetFromCustomContent());
1943         }
1944         super.onSaveInstanceState(outState);
1945
1946         outState.putInt(RUNTIME_STATE, mState.ordinal());
1947         // We close any open folder since it will not be re-opened, and we need to make sure
1948         // this state is reflected.
1949         closeFolder();
1950
1951         if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screenId > -1 &&
1952                 mWaitingForResult) {
1953             outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
1954             outState.putLong(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screenId);
1955             outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
1956             outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
1957             outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
1958             outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
1959             outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
1960             outState.putInt(RUNTIME_STATE_PENDING_ADD_WIDGET_ID, mPendingAddWidgetId);
1961         }
1962
1963         // Save the current widgets tray?
1964         // TODO(hyunyoungs)
1965         outState.putSerializable(RUNTIME_STATE_VIEW_IDS, mItemIdToViewId);
1966
1967         if (mLauncherCallbacks != null) {
1968             mLauncherCallbacks.onSaveInstanceState(outState);
1969         }
1970     }
1971
1972     @Override
1973     public void onDestroy() {
1974         super.onDestroy();
1975
1976         // Remove all pending runnables
1977         mHandler.removeMessages(ADVANCE_MSG);
1978         mHandler.removeMessages(0);
1979         mWorkspace.removeCallbacks(mBuildLayersRunnable);
1980
1981         // Stop callbacks from LauncherModel
1982         LauncherAppState app = (LauncherAppState.getInstance());
1983
1984         // It's possible to receive onDestroy after a new Launcher activity has
1985         // been created. In this case, don't interfere with the new Launcher.
1986         if (mModel.isCurrentCallbacks(this)) {
1987             mModel.stopLoader();
1988             app.setLauncher(null);
1989         }
1990
1991         try {
1992             mAppWidgetHost.stopListening();
1993         } catch (NullPointerException ex) {
1994             Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1995         }
1996         mAppWidgetHost = null;
1997
1998         mWidgetsToAdvance.clear();
1999
2000         TextKeyListener.getInstance().release();
2001
2002         unregisterReceiver(mCloseSystemDialogsReceiver);
2003
2004         mDragLayer.clearAllResizeFrames();
2005         ((ViewGroup) mWorkspace.getParent()).removeAllViews();
2006         mWorkspace.removeAllWorkspaceScreens();
2007         mWorkspace = null;
2008         mDragController = null;
2009
2010         LauncherAnimUtils.onDestroyActivity();
2011
2012         if (mLauncherCallbacks != null) {
2013             mLauncherCallbacks.onDestroy();
2014         }
2015     }
2016
2017     public DragController getDragController() {
2018         return mDragController;
2019     }
2020
2021     @Override
2022     public void startActivityForResult(Intent intent, int requestCode) {
2023         onStartForResult(requestCode);
2024         super.startActivityForResult(intent, requestCode);
2025     }
2026
2027     @Override
2028     public void startIntentSenderForResult (IntentSender intent, int requestCode,
2029             Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) {
2030         onStartForResult(requestCode);
2031         try {
2032             super.startIntentSenderForResult(intent, requestCode,
2033                 fillInIntent, flagsMask, flagsValues, extraFlags, options);
2034         } catch (IntentSender.SendIntentException e) {
2035             throw new ActivityNotFoundException();
2036         }
2037     }
2038
2039     private void onStartForResult(int requestCode) {
2040         if (requestCode >= 0) {
2041             setWaitingForResult(true);
2042         }
2043     }
2044
2045     /**
2046      * Indicates that we want global search for this activity by setting the globalSearch
2047      * argument for {@link #startSearch} to true.
2048      */
2049     @Override
2050     public void startSearch(String initialQuery, boolean selectInitialQuery,
2051             Bundle appSearchData, boolean globalSearch) {
2052
2053         if (initialQuery == null) {
2054             // Use any text typed in the launcher as the initial query
2055             initialQuery = getTypedText();
2056         }
2057         if (appSearchData == null) {
2058             appSearchData = new Bundle();
2059             appSearchData.putString("source", "launcher-search");
2060         }
2061         Rect sourceBounds = new Rect();
2062         if (mSearchDropTargetBar != null) {
2063             sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
2064         }
2065
2066         boolean clearTextImmediately = startSearch(initialQuery, selectInitialQuery,
2067                 appSearchData, sourceBounds);
2068         if (clearTextImmediately) {
2069             clearTypedText();
2070         }
2071
2072         // We need to show the workspace after starting the search
2073         showWorkspace(true);
2074     }
2075
2076     /**
2077      * Start a text search.
2078      *
2079      * @return {@code true} if the search will start immediately, so any further keypresses
2080      * will be handled directly by the search UI. {@code false} if {@link Launcher} should continue
2081      * to buffer keypresses.
2082      */
2083     public boolean startSearch(String initialQuery,
2084             boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
2085         if (mLauncherCallbacks != null && mLauncherCallbacks.providesSearch()) {
2086             return mLauncherCallbacks.startSearch(initialQuery, selectInitialQuery, appSearchData,
2087                     sourceBounds);
2088         }
2089
2090         startGlobalSearch(initialQuery, selectInitialQuery,
2091                 appSearchData, sourceBounds);
2092         return false;
2093     }
2094
2095     /**
2096      * Starts the global search activity. This code is a copied from SearchManager
2097      */
2098     private void startGlobalSearch(String initialQuery,
2099             boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
2100         final SearchManager searchManager =
2101             (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2102         ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
2103         if (globalSearchActivity == null) {
2104             Log.w(TAG, "No global search activity found.");
2105             return;
2106         }
2107         Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
2108         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2109         intent.setComponent(globalSearchActivity);
2110         // Make sure that we have a Bundle to put source in
2111         if (appSearchData == null) {
2112             appSearchData = new Bundle();
2113         } else {
2114             appSearchData = new Bundle(appSearchData);
2115         }
2116         // Set source to package name of app that starts global search if not set already.
2117         if (!appSearchData.containsKey("source")) {
2118             appSearchData.putString("source", getPackageName());
2119         }
2120         intent.putExtra(SearchManager.APP_DATA, appSearchData);
2121         if (!TextUtils.isEmpty(initialQuery)) {
2122             intent.putExtra(SearchManager.QUERY, initialQuery);
2123         }
2124         if (selectInitialQuery) {
2125             intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
2126         }
2127         intent.setSourceBounds(sourceBounds);
2128         try {
2129             startActivity(intent);
2130         } catch (ActivityNotFoundException ex) {
2131             Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
2132         }
2133     }
2134
2135     public boolean isOnCustomContent() {
2136         return mWorkspace.isOnOrMovingToCustomContent();
2137     }
2138
2139     @Override
2140     public boolean onPrepareOptionsMenu(Menu menu) {
2141         super.onPrepareOptionsMenu(menu);
2142         if (!isOnCustomContent()) {
2143             // Close any open folders
2144             closeFolder();
2145             // Stop resizing any widgets
2146             mWorkspace.exitWidgetResizeMode();
2147             if (!mWorkspace.isInOverviewMode()) {
2148                 // Show the overview mode
2149                 showOverviewMode(true);
2150             } else {
2151                 showWorkspace(true);
2152             }
2153         }
2154         if (mLauncherCallbacks != null) {
2155             return mLauncherCallbacks.onPrepareOptionsMenu(menu);
2156         }
2157
2158         return false;
2159     }
2160
2161     @Override
2162     public boolean onSearchRequested() {
2163         startSearch(null, false, null, true);
2164         // Use a custom animation for launching search
2165         return true;
2166     }
2167
2168     public boolean isWorkspaceLocked() {
2169         return mWorkspaceLoading || mWaitingForResult;
2170     }
2171
2172     public boolean isWorkspaceLoading() {
2173         return mWorkspaceLoading;
2174     }
2175
2176     private void setWorkspaceLoading(boolean value) {
2177         boolean isLocked = isWorkspaceLocked();
2178         mWorkspaceLoading = value;
2179         if (isLocked != isWorkspaceLocked()) {
2180             onWorkspaceLockedChanged();
2181         }
2182     }
2183
2184     private void setWaitingForResult(boolean value) {
2185         boolean isLocked = isWorkspaceLocked();
2186         mWaitingForResult = value;
2187         if (isLocked != isWorkspaceLocked()) {
2188             onWorkspaceLockedChanged();
2189         }
2190     }
2191
2192     protected void onWorkspaceLockedChanged() {
2193         if (mLauncherCallbacks != null) {
2194             mLauncherCallbacks.onWorkspaceLockedChanged();
2195         }
2196     }
2197
2198     private void resetAddInfo() {
2199         mPendingAddInfo.container = ItemInfo.NO_ID;
2200         mPendingAddInfo.screenId = -1;
2201         mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
2202         mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
2203         mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = 1;
2204         mPendingAddInfo.dropPos = null;
2205     }
2206
2207     void addAppWidgetImpl(final int appWidgetId, final ItemInfo info, final
2208             AppWidgetHostView boundWidget, final LauncherAppWidgetProviderInfo appWidgetInfo) {
2209         addAppWidgetImpl(appWidgetId, info, boundWidget, appWidgetInfo, 0);
2210     }
2211
2212     void addAppWidgetImpl(final int appWidgetId, final ItemInfo info,
2213             final AppWidgetHostView boundWidget, final LauncherAppWidgetProviderInfo appWidgetInfo,
2214             int delay) {
2215         if (appWidgetInfo.configure != null) {
2216             mPendingAddWidgetInfo = appWidgetInfo;
2217             mPendingAddWidgetId = appWidgetId;
2218
2219             // Launch over to configure widget, if needed
2220             mAppWidgetManager.startConfigActivity(appWidgetInfo, appWidgetId, this,
2221                     mAppWidgetHost, REQUEST_CREATE_APPWIDGET);
2222
2223         } else {
2224             // Otherwise just add it
2225             Runnable onComplete = new Runnable() {
2226                 @Override
2227                 public void run() {
2228                     // Exit spring loaded mode if necessary after adding the widget
2229                     exitSpringLoadedDragModeDelayed(true, EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT,
2230                             null);
2231                 }
2232             };
2233             completeAddAppWidget(appWidgetId, info.container, info.screenId, boundWidget,
2234                     appWidgetInfo);
2235             mWorkspace.removeExtraEmptyScreenDelayed(true, onComplete, delay, false);
2236         }
2237     }
2238
2239     protected void moveToCustomContentScreen(boolean animate) {
2240         // Close any folders that may be open.
2241         closeFolder();
2242         mWorkspace.moveToCustomContentScreen(animate);
2243     }
2244
2245     public void addPendingItem(PendingAddItemInfo info, long container, long screenId,
2246             int[] cell, int spanX, int spanY) {
2247         switch (info.itemType) {
2248             case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
2249             case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
2250                 int span[] = new int[2];
2251                 span[0] = spanX;
2252                 span[1] = spanY;
2253                 addAppWidgetFromDrop((PendingAddWidgetInfo) info,
2254                         container, screenId, cell, span);
2255                 break;
2256             case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2257                 processShortcutFromDrop(info.componentName, container, screenId, cell);
2258                 break;
2259             default:
2260                 throw new IllegalStateException("Unknown item type: " + info.itemType);
2261             }
2262     }
2263
2264     /**
2265      * Process a shortcut drop.
2266      *
2267      * @param componentName The name of the component
2268      * @param screenId The ID of the screen where it should be added
2269      * @param cell The cell it should be added to, optional
2270      */
2271     private void processShortcutFromDrop(ComponentName componentName, long container, long screenId,
2272             int[] cell) {
2273         resetAddInfo();
2274         mPendingAddInfo.container = container;
2275         mPendingAddInfo.screenId = screenId;
2276         mPendingAddInfo.dropPos = null;
2277
2278         if (cell != null) {
2279             mPendingAddInfo.cellX = cell[0];
2280             mPendingAddInfo.cellY = cell[1];
2281         }
2282
2283         Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
2284         createShortcutIntent.setComponent(componentName);
2285         Utilities.startActivityForResultSafely(this, createShortcutIntent, REQUEST_CREATE_SHORTCUT);
2286     }
2287
2288     /**
2289      * Process a widget drop.
2290      *
2291      * @param info The PendingAppWidgetInfo of the widget being added.
2292      * @param screenId The ID of the screen where it should be added
2293      * @param cell The cell it should be added to, optional
2294      */
2295     private void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, long screenId,
2296             int[] cell, int[] span) {
2297         resetAddInfo();
2298         mPendingAddInfo.container = info.container = container;
2299         mPendingAddInfo.screenId = info.screenId = screenId;
2300         mPendingAddInfo.dropPos = null;
2301         mPendingAddInfo.minSpanX = info.minSpanX;
2302         mPendingAddInfo.minSpanY = info.minSpanY;
2303
2304         if (cell != null) {
2305             mPendingAddInfo.cellX = cell[0];
2306             mPendingAddInfo.cellY = cell[1];
2307         }
2308         if (span != null) {
2309             mPendingAddInfo.spanX = span[0];
2310             mPendingAddInfo.spanY = span[1];
2311         }
2312
2313         AppWidgetHostView hostView = info.boundWidget;
2314         int appWidgetId;
2315         if (hostView != null) {
2316             appWidgetId = hostView.getAppWidgetId();
2317             addAppWidgetImpl(appWidgetId, info, hostView, info.info);
2318
2319             // Clear the boundWidget so that it doesn't get destroyed.
2320             info.boundWidget = null;
2321         } else {
2322             // In this case, we either need to start an activity to get permission to bind
2323             // the widget, or we need to start an activity to configure the widget, or both.
2324             appWidgetId = getAppWidgetHost().allocateAppWidgetId();
2325             Bundle options = info.bindOptions;
2326
2327             boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed(
2328                     appWidgetId, info.info, options);
2329             if (success) {
2330                 addAppWidgetImpl(appWidgetId, info, null, info.info);
2331             } else {
2332                 mPendingAddWidgetInfo = info.info;
2333                 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
2334                 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
2335                 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
2336                 mAppWidgetManager.getUser(mPendingAddWidgetInfo)
2337                     .addToIntent(intent, AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE);
2338                 // TODO: we need to make sure that this accounts for the options bundle.
2339                 // intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
2340                 startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
2341             }
2342         }
2343     }
2344
2345     FolderIcon addFolder(CellLayout layout, long container, final long screenId, int cellX,
2346             int cellY) {
2347         final FolderInfo folderInfo = new FolderInfo();
2348         folderInfo.title = getText(R.string.folder_name);
2349
2350         // Update the model
2351         LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screenId,
2352                 cellX, cellY);
2353         sFolders.put(folderInfo.id, folderInfo);
2354
2355         // Create the view
2356         FolderIcon newFolder =
2357             FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
2358         mWorkspace.addInScreen(newFolder, container, screenId, cellX, cellY, 1, 1,
2359                 isWorkspaceLocked());
2360         // Force measure the new folder icon
2361         CellLayout parent = mWorkspace.getParentCellLayoutForView(newFolder);
2362         parent.getShortcutsAndWidgets().measureChild(newFolder);
2363         return newFolder;
2364     }
2365
2366     void removeFolder(FolderInfo folder) {
2367         sFolders.remove(folder.id);
2368     }
2369
2370     @Override
2371     public boolean dispatchKeyEvent(KeyEvent event) {
2372         if (event.getAction() == KeyEvent.ACTION_DOWN) {
2373             switch (event.getKeyCode()) {
2374                 case KeyEvent.KEYCODE_HOME:
2375                     return true;
2376                 case KeyEvent.KEYCODE_VOLUME_DOWN:
2377                     if (Utilities.isPropertyEnabled(DUMP_STATE_PROPERTY)) {
2378                         dumpState();
2379                         return true;
2380                     }
2381                     break;
2382             }
2383         } else if (event.getAction() == KeyEvent.ACTION_UP) {
2384             switch (event.getKeyCode()) {
2385                 case KeyEvent.KEYCODE_HOME:
2386                     return true;
2387             }
2388         }
2389
2390         return super.dispatchKeyEvent(event);
2391     }
2392
2393     @Override
2394     public void onBackPressed() {
2395         if (mLauncherCallbacks != null && mLauncherCallbacks.handleBackPressed()) {
2396             return;
2397         }
2398
2399         if (mDragController.isDragging()) {
2400             mDragController.cancelDrag();
2401             return;
2402         }
2403
2404         if (isAppsViewVisible()) {
2405             showWorkspace(true);
2406         } else if (isWidgetsViewVisible())  {
2407             showOverviewMode(true);
2408         } else if (mWorkspace.isInOverviewMode()) {
2409             showWorkspace(true);
2410         } else if (mWorkspace.getOpenFolder() != null) {
2411             Folder openFolder = mWorkspace.getOpenFolder();
2412             if (openFolder.isEditingName()) {
2413                 openFolder.dismissEditingName();
2414             } else {
2415                 closeFolder();
2416             }
2417         } else {
2418             mWorkspace.exitWidgetResizeMode();
2419
2420             // Back button is a no-op here, but give at least some feedback for the button press
2421             mWorkspace.showOutlinesTemporarily();
2422         }
2423     }
2424
2425     /**
2426      * Re-listen when widget host is reset.
2427      */
2428     @Override
2429     public void onAppWidgetHostReset() {
2430         if (mAppWidgetHost != null) {
2431             mAppWidgetHost.startListening();
2432         }
2433     }
2434
2435     /**
2436      * Launches the intent referred by the clicked shortcut.
2437      *
2438      * @param v The view representing the clicked shortcut.
2439      */
2440     public void onClick(View v) {
2441         // Make sure that rogue clicks don't get through while allapps is launching, or after the
2442         // view has detached (it's possible for this to happen if the view is removed mid touch).
2443         if (v.getWindowToken() == null) {
2444             return;
2445         }
2446
2447         if (!mWorkspace.isFinishedSwitchingState()) {
2448             return;
2449         }
2450
2451         if (v instanceof Workspace) {
2452             if (mWorkspace.isInOverviewMode()) {
2453                 showWorkspace(true);
2454             }
2455             return;
2456         }
2457
2458         if (v instanceof CellLayout) {
2459             if (mWorkspace.isInOverviewMode()) {
2460                 showWorkspace(mWorkspace.indexOfChild(v), true);
2461             }
2462         }
2463
2464         Object tag = v.getTag();
2465         if (tag instanceof ShortcutInfo) {
2466             onClickAppShortcut(v);
2467         } else if (tag instanceof FolderInfo) {
2468             if (v instanceof FolderIcon) {
2469                 onClickFolderIcon(v);
2470             }
2471         } else if (v == mAllAppsButton) {
2472             onClickAllAppsButton(v);
2473         } else if (tag instanceof AppInfo) {
2474             startAppShortcutOrInfoActivity(v);
2475         } else if (tag instanceof LauncherAppWidgetInfo) {
2476             if (v instanceof PendingAppWidgetHostView) {
2477                 onClickPendingWidget((PendingAppWidgetHostView) v);
2478             }
2479         }
2480     }
2481
2482     @SuppressLint("ClickableViewAccessibility")
2483     public boolean onTouch(View v, MotionEvent event) {
2484         return false;
2485     }
2486
2487     /**
2488      * Event handler for the app widget view which has not fully restored.
2489      */
2490     public void onClickPendingWidget(final PendingAppWidgetHostView v) {
2491         if (mIsSafeModeEnabled) {
2492             Toast.makeText(this, R.string.safemode_widget_error, Toast.LENGTH_SHORT).show();
2493             return;
2494         }
2495
2496         final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) v.getTag();
2497         if (v.isReadyForClickSetup()) {
2498             int widgetId = info.appWidgetId;
2499             AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(widgetId);
2500             if (appWidgetInfo != null) {
2501                 mPendingAddWidgetInfo = LauncherAppWidgetProviderInfo.fromProviderInfo(
2502                         this, appWidgetInfo);
2503                 mPendingAddInfo.copyFrom(info);
2504                 mPendingAddWidgetId = widgetId;
2505
2506                 AppWidgetManagerCompat.getInstance(this).startConfigActivity(appWidgetInfo,
2507                         info.appWidgetId, this, mAppWidgetHost, REQUEST_RECONFIGURE_APPWIDGET);
2508             }
2509         } else if (info.installProgress < 0) {
2510             // The install has not been queued
2511             final String packageName = info.providerName.getPackageName();
2512             showBrokenAppInstallDialog(packageName,
2513                 new DialogInterface.OnClickListener() {
2514                     public void onClick(DialogInterface dialog, int id) {
2515                         startActivitySafely(v, LauncherModel.getMarketIntent(packageName), info);
2516                     }
2517                 });
2518         } else {
2519             // Download has started.
2520             final String packageName = info.providerName.getPackageName();
2521             startActivitySafely(v, LauncherModel.getMarketIntent(packageName), info);
2522         }
2523     }
2524
2525     /**
2526      * Event handler for the "grid" button that appears on the home screen, which
2527      * enters all apps mode.
2528      *
2529      * @param v The view that was clicked.
2530      */
2531     protected void onClickAllAppsButton(View v) {
2532         if (LOGD) Log.d(TAG, "onClickAllAppsButton");
2533         if (!isAppsViewVisible()) {
2534             showAppsView(true /* animated */, false /* resetListToTop */,
2535                     true /* updatePredictedApps */, false /* focusSearchBar */);
2536         }
2537     }
2538
2539     protected void onLongClickAllAppsButton(View v) {
2540         if (LOGD) Log.d(TAG, "onLongClickAllAppsButton");
2541         if (!isAppsViewVisible()) {
2542             showAppsView(true /* animated */, false /* resetListToTop */,
2543                     true /* updatePredictedApps */, true /* focusSearchBar */);
2544         }
2545     }
2546
2547     private void showBrokenAppInstallDialog(final String packageName,
2548             DialogInterface.OnClickListener onSearchClickListener) {
2549         new AlertDialog.Builder(this)
2550             .setTitle(R.string.abandoned_promises_title)
2551             .setMessage(R.string.abandoned_promise_explanation)
2552             .setPositiveButton(R.string.abandoned_search, onSearchClickListener)
2553             .setNeutralButton(R.string.abandoned_clean_this,
2554                 new DialogInterface.OnClickListener() {
2555                     public void onClick(DialogInterface dialog, int id) {
2556                         final UserHandleCompat user = UserHandleCompat.myUserHandle();
2557                         mWorkspace.removeAbandonedPromise(packageName, user);
2558                     }
2559                 })
2560             .create().show();
2561         return;
2562     }
2563
2564     /**
2565      * Event handler for an app shortcut click.
2566      *
2567      * @param v The view that was clicked. Must be a tagged with a {@link ShortcutInfo}.
2568      */
2569     protected void onClickAppShortcut(final View v) {
2570         if (LOGD) Log.d(TAG, "onClickAppShortcut");
2571         Object tag = v.getTag();
2572         if (!(tag instanceof ShortcutInfo)) {
2573             throw new IllegalArgumentException("Input must be a Shortcut");
2574         }
2575
2576         // Open shortcut
2577         final ShortcutInfo shortcut = (ShortcutInfo) tag;
2578
2579         if (shortcut.isDisabled != 0) {
2580             int error = R.string.activity_not_available;
2581             if ((shortcut.isDisabled & ShortcutInfo.FLAG_DISABLED_SAFEMODE) != 0) {
2582                 error = R.string.safemode_shortcut_error;
2583             }
2584             Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
2585             return;
2586         }
2587
2588         final Intent intent = shortcut.intent;
2589
2590         // Check for special shortcuts
2591         if (intent.getComponent() != null) {
2592             final String shortcutClass = intent.getComponent().getClassName();
2593
2594             if (shortcutClass.equals(MemoryDumpActivity.class.getName())) {
2595                 MemoryDumpActivity.startDump(this);
2596                 return;
2597             } else if (shortcutClass.equals(ToggleWeightWatcher.class.getName())) {
2598                 toggleShowWeightWatcher();
2599                 return;
2600             }
2601         }
2602
2603         // Check for abandoned promise
2604         if ((v instanceof BubbleTextView)
2605                 && shortcut.isPromise()
2606                 && !shortcut.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE)) {
2607             showBrokenAppInstallDialog(
2608                     shortcut.getTargetComponent().getPackageName(),
2609                     new DialogInterface.OnClickListener() {
2610                         public void onClick(DialogInterface dialog, int id) {
2611                             startAppShortcutOrInfoActivity(v);
2612                         }
2613                     });
2614             return;
2615         }
2616
2617         // Start activities
2618         startAppShortcutOrInfoActivity(v);
2619
2620         if (mLauncherCallbacks != null) {
2621             mLauncherCallbacks.onClickAppShortcut(v);
2622         }
2623     }
2624
2625     @Thunk void startAppShortcutOrInfoActivity(View v) {
2626         Object tag = v.getTag();
2627         final ShortcutInfo shortcut;
2628         final Intent intent;
2629         if (tag instanceof ShortcutInfo) {
2630             shortcut = (ShortcutInfo) tag;
2631             intent = shortcut.intent;
2632             int[] pos = new int[2];
2633             v.getLocationOnScreen(pos);
2634             intent.setSourceBounds(new Rect(pos[0], pos[1],
2635                     pos[0] + v.getWidth(), pos[1] + v.getHeight()));
2636
2637         } else if (tag instanceof AppInfo) {
2638             shortcut = null;
2639             intent = ((AppInfo) tag).intent;
2640         } else {
2641             throw new IllegalArgumentException("Input must be a Shortcut or AppInfo");
2642         }
2643
2644         boolean success = startActivitySafely(v, intent, tag);
2645         mStats.recordLaunch(v, intent, shortcut);
2646
2647         if (success && v instanceof BubbleTextView) {
2648             mWaitingForResume = (BubbleTextView) v;
2649             mWaitingForResume.setStayPressed(true);
2650         }
2651     }
2652
2653     /**
2654      * Event handler for a folder icon click.
2655      *
2656      * @param v The view that was clicked. Must be an instance of {@link FolderIcon}.
2657      */
2658     protected void onClickFolderIcon(View v) {
2659         if (LOGD) Log.d(TAG, "onClickFolder");
2660         if (!(v instanceof FolderIcon)){
2661             throw new IllegalArgumentException("Input must be a FolderIcon");
2662         }
2663
2664         // TODO(sunnygoyal): Re-evaluate this code.
2665         FolderIcon folderIcon = (FolderIcon) v;
2666         final FolderInfo info = folderIcon.getFolderInfo();
2667         Folder openFolder = mWorkspace.getFolderForTag(info);
2668
2669         // If the folder info reports that the associated folder is open, then verify that
2670         // it is actually opened. There have been a few instances where this gets out of sync.
2671         if (info.opened && openFolder == null) {
2672             Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
2673                     + info.screenId + " (" + info.cellX + ", " + info.cellY + ")");
2674             info.opened = false;
2675         }
2676
2677         if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
2678             // Close any open folder
2679             closeFolder();
2680             // Open the requested folder
2681             openFolder(folderIcon);
2682         } else {
2683             // Find the open folder...
2684             int folderScreen;
2685             if (openFolder != null) {
2686                 folderScreen = mWorkspace.getPageForView(openFolder);
2687                 // .. and close it
2688                 closeFolder(openFolder);
2689                 if (folderScreen != mWorkspace.getCurrentPage()) {
2690                     // Close any folder open on the current screen
2691                     closeFolder();
2692                     // Pull the folder onto this screen
2693                     openFolder(folderIcon);
2694                 }
2695             }
2696         }
2697
2698         if (mLauncherCallbacks != null) {
2699             mLauncherCallbacks.onClickFolderIcon(v);
2700         }
2701     }
2702
2703     /**
2704      * Event handler for the (Add) Widgets button that appears after a long press
2705      * on the home screen.
2706      */
2707     protected void onClickAddWidgetButton(View view) {
2708         if (LOGD) Log.d(TAG, "onClickAddWidgetButton");
2709         if (mIsSafeModeEnabled) {
2710             Toast.makeText(this, R.string.safemode_widget_error, Toast.LENGTH_SHORT).show();
2711         } else {
2712             showWidgetsView(true /* animated */, true /* resetPageToZero */);
2713             if (mLauncherCallbacks != null) {
2714                 mLauncherCallbacks.onClickAddWidgetButton(view);
2715             }
2716         }
2717     }
2718
2719     /**
2720      * Event handler for the wallpaper picker button that appears after a long press
2721      * on the home screen.
2722      */
2723     protected void onClickWallpaperPicker(View v) {
2724         if (LOGD) Log.d(TAG, "onClickWallpaperPicker");
2725         startActivityForResult(new Intent(Intent.ACTION_SET_WALLPAPER).setPackage(getPackageName()),
2726                 REQUEST_PICK_WALLPAPER);
2727
2728         if (mLauncherCallbacks != null) {
2729             mLauncherCallbacks.onClickWallpaperPicker(v);
2730         }
2731     }
2732
2733     /**
2734      * Event handler for a click on the settings button that appears after a long press
2735      * on the home screen.
2736      */
2737     protected void onClickSettingsButton(View v) {
2738         if (LOGD) Log.d(TAG, "onClickSettingsButton");
2739         if (mLauncherCallbacks != null) {
2740             mLauncherCallbacks.onClickSettingsButton(v);
2741         } else {
2742             startActivity(new Intent(this, SettingsActivity.class));
2743         }
2744     }
2745
2746     public View.OnTouchListener getHapticFeedbackTouchListener() {
2747         if (mHapticFeedbackTouchListener == null) {
2748             mHapticFeedbackTouchListener = new View.OnTouchListener() {
2749                 @SuppressLint("ClickableViewAccessibility")
2750                 @Override
2751                 public boolean onTouch(View v, MotionEvent event) {
2752                     if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
2753                         v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2754                     }
2755                     return false;
2756                 }
2757             };
2758         }
2759         return mHapticFeedbackTouchListener;
2760     }
2761
2762     public void onDragStarted(View view) {
2763         if (isOnCustomContent()) {
2764             // Custom content screen doesn't participate in drag and drop. If on custom
2765             // content screen, move to default.
2766             moveWorkspaceToDefaultScreen();
2767         }
2768
2769         if (mLauncherCallbacks != null) {
2770             mLauncherCallbacks.onDragStarted(view);
2771         }
2772     }
2773
2774     /**
2775      * Called when the user stops interacting with the launcher.
2776      * This implies that the user is now on the homescreen and is not doing housekeeping.
2777      */
2778     protected void onInteractionEnd() {
2779         if (mLauncherCallbacks != null) {
2780             mLauncherCallbacks.onInteractionEnd();
2781         }
2782     }
2783
2784     /**
2785      * Called when the user starts interacting with the launcher.
2786      * The possible interactions are:
2787      *  - open all apps
2788      *  - reorder an app shortcut, or a widget
2789      *  - open the overview mode.
2790      * This is a good time to stop doing things that only make sense
2791      * when the user is on the homescreen and not doing housekeeping.
2792      */
2793     protected void onInteractionBegin() {
2794         if (mLauncherCallbacks != null) {
2795             mLauncherCallbacks.onInteractionBegin();
2796         }
2797     }
2798
2799     /** Updates the interaction state. */
2800     public void updateInteraction(Workspace.State fromState, Workspace.State toState) {
2801         // Only update the interacting state if we are transitioning to/from a view with an
2802         // overlay
2803         boolean fromStateWithOverlay = fromState != Workspace.State.NORMAL;
2804         boolean toStateWithOverlay = toState != Workspace.State.NORMAL;
2805         if (toStateWithOverlay) {
2806             onInteractionBegin();
2807         } else if (fromStateWithOverlay) {
2808             onInteractionEnd();
2809         }
2810     }
2811
2812     void startApplicationDetailsActivity(ComponentName componentName, UserHandleCompat user) {
2813         try {
2814             LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
2815             launcherApps.showAppDetailsForProfile(componentName, user);
2816         } catch (SecurityException e) {
2817             Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2818             Log.e(TAG, "Launcher does not have permission to launch settings");
2819         } catch (ActivityNotFoundException e) {
2820             Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2821             Log.e(TAG, "Unable to launch settings");
2822         }
2823     }
2824
2825     // returns true if the activity was started
2826     boolean startApplicationUninstallActivity(ComponentName componentName, int flags,
2827             UserHandleCompat user) {
2828         if ((flags & AppInfo.DOWNLOADED_FLAG) == 0) {
2829             // System applications cannot be installed. For now, show a toast explaining that.
2830             // We may give them the option of disabling apps this way.
2831             int messageId = R.string.uninstall_system_app_text;
2832             Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
2833             return false;
2834         } else {
2835             String packageName = componentName.getPackageName();
2836             String className = componentName.getClassName();
2837             Intent intent = new Intent(
2838                     Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
2839             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
2840                     Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2841             if (user != null) {
2842                 user.addToIntent(intent, Intent.EXTRA_USER);
2843             }
2844             startActivity(intent);
2845             return true;
2846         }
2847     }
2848
2849     private boolean startActivity(View v, Intent intent, Object tag) {
2850         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2851         try {
2852             // Only launch using the new animation if the shortcut has not opted out (this is a
2853             // private contract between launcher and may be ignored in the future).
2854             boolean useLaunchAnimation = (v != null) &&
2855                     !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
2856             LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
2857             UserManagerCompat userManager = UserManagerCompat.getInstance(this);
2858
2859             UserHandleCompat user = null;
2860             if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) {
2861                 long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1);
2862                 user = userManager.getUserForSerialNumber(serialNumber);
2863             }
2864
2865             Bundle optsBundle = null;
2866             if (useLaunchAnimation) {
2867                 ActivityOptions opts = null;
2868                 if (sClipRevealMethod != null) {
2869                     // TODO: call method directly when Launcher3 can depend on M APIs
2870                     int left = 0, top = 0;
2871                     int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
2872                     if (v instanceof TextView) {
2873                         // Launch from center of icon, not entire view
2874                         Drawable icon = Workspace.getTextViewIcon((TextView) v);
2875                         if (icon != null) {
2876                             Rect bounds = icon.getBounds();
2877                             left = (width - bounds.width()) / 2;
2878                             top = v.getPaddingTop();
2879                             width = bounds.width();
2880                             height = bounds.height();
2881                         }
2882                     }
2883                     try {
2884                         opts = (ActivityOptions) sClipRevealMethod.invoke(null, v,
2885                                 left, top, width, height);
2886                     } catch (IllegalAccessException e) {
2887                         Log.d(TAG, "Could not call makeClipRevealAnimation: " + e);
2888                         sClipRevealMethod = null;
2889                     } catch (InvocationTargetException e) {
2890                         Log.d(TAG, "Could not call makeClipRevealAnimation: " + e);
2891                         sClipRevealMethod = null;
2892                     }
2893                 }
2894                 if (opts == null && !Utilities.isLmpOrAbove()) {
2895                     // Below L, we use a scale up animation
2896                     opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
2897                                     v.getMeasuredWidth(), v.getMeasuredHeight());
2898                 } else if (opts == null && Utilities.isLmpMR1()) {
2899                     // On L devices, we use the device default slide-up transition.
2900                     // On L MR1 devices, we a custom version of the slide-up transition which
2901                     // doesn't have the delay present in the device default.
2902                     opts = ActivityOptions.makeCustomAnimation(this,
2903                             R.anim.task_open_enter, R.anim.no_anim);
2904                 }
2905                 optsBundle = opts != null ? opts.toBundle() : null;
2906             }
2907
2908             if (user == null || user.equals(UserHandleCompat.myUserHandle())) {
2909                 // Could be launching some bookkeeping activity
2910                 startActivity(intent, optsBundle);
2911             } else {
2912                 // TODO Component can be null when shortcuts are supported for secondary user
2913                 launcherApps.startActivityForProfile(intent.getComponent(), user,
2914                         intent.getSourceBounds(), optsBundle);
2915             }
2916             return true;
2917         } catch (SecurityException e) {
2918             Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2919             Log.e(TAG, "Launcher does not have the permission to launch " + intent +
2920                     ". Make sure to create a MAIN intent-filter for the corresponding activity " +
2921                     "or use the exported attribute for this activity. "
2922                     + "tag="+ tag + " intent=" + intent, e);
2923         }
2924         return false;
2925     }
2926
2927     @Thunk boolean startActivitySafely(View v, Intent intent, Object tag) {
2928         boolean success = false;
2929         if (mIsSafeModeEnabled && !Utilities.isSystemApp(this, intent)) {
2930             Toast.makeText(this, R.string.safemode_shortcut_error, Toast.LENGTH_SHORT).show();
2931             return false;
2932         }
2933         try {
2934             success = startActivity(v, intent, tag);
2935         } catch (ActivityNotFoundException e) {
2936             Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2937             Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
2938         }
2939         return success;
2940     }
2941
2942     /**
2943      * This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
2944      * in the DragLayer in the exact absolute location of the original FolderIcon.
2945      */
2946     private void copyFolderIconToImage(FolderIcon fi) {
2947         final int width = fi.getMeasuredWidth();
2948         final int height = fi.getMeasuredHeight();
2949
2950         // Lazy load ImageView, Bitmap and Canvas
2951         if (mFolderIconImageView == null) {
2952             mFolderIconImageView = new ImageView(this);
2953         }
2954         if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
2955                 mFolderIconBitmap.getHeight() != height) {
2956             mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2957             mFolderIconCanvas = new Canvas(mFolderIconBitmap);
2958         }
2959
2960         DragLayer.LayoutParams lp;
2961         if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
2962             lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
2963         } else {
2964             lp = new DragLayer.LayoutParams(width, height);
2965         }
2966
2967         // The layout from which the folder is being opened may be scaled, adjust the starting
2968         // view size by this scale factor.
2969         float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
2970         lp.customPosition = true;
2971         lp.x = mRectForFolderAnimation.left;
2972         lp.y = mRectForFolderAnimation.top;
2973         lp.width = (int) (scale * width);
2974         lp.height = (int) (scale * height);
2975
2976         mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
2977         fi.draw(mFolderIconCanvas);
2978         mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
2979         if (fi.getFolder() != null) {
2980             mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
2981             mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
2982         }
2983         // Just in case this image view is still in the drag layer from a previous animation,
2984         // we remove it and re-add it.
2985         if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
2986             mDragLayer.removeView(mFolderIconImageView);
2987         }
2988         mDragLayer.addView(mFolderIconImageView, lp);
2989         if (fi.getFolder() != null) {
2990             fi.getFolder().bringToFront();
2991         }
2992     }
2993
2994     private void growAndFadeOutFolderIcon(FolderIcon fi) {
2995         if (fi == null) return;
2996         PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
2997         PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
2998         PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
2999
3000         FolderInfo info = (FolderInfo) fi.getTag();
3001         if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
3002             CellLayout cl = (CellLayout) fi.getParent().getParent();
3003             CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
3004             cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
3005         }
3006
3007         // Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
3008         copyFolderIconToImage(fi);
3009         fi.setVisibility(View.INVISIBLE);
3010
3011         ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
3012                 scaleX, scaleY);
3013         if (Utilities.isLmpOrAbove()) {
3014             oa.setInterpolator(new LogDecelerateInterpolator(100, 0));
3015         }
3016         oa.setDuration(getResources().getInteger(R.integer.config_folderExpandDuration));
3017         oa.start();
3018     }
3019
3020     private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
3021         if (fi == null) return;
3022         PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
3023         PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
3024         PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
3025
3026         final CellLayout cl = (CellLayout) fi.getParent().getParent();
3027
3028         // We remove and re-draw the FolderIcon in-case it has changed
3029         mDragLayer.removeView(mFolderIconImageView);
3030         copyFolderIconToImage(fi);
3031         ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
3032                 scaleX, scaleY);
3033         oa.setDuration(getResources().getInteger(R.integer.config_folderExpandDuration));
3034         oa.addListener(new AnimatorListenerAdapter() {
3035             @Override
3036             public void onAnimationEnd(Animator animation) {
3037                 if (cl != null) {
3038                     cl.clearFolderLeaveBehind();
3039                     // Remove the ImageView copy of the FolderIcon and make the original visible.
3040                     mDragLayer.removeView(mFolderIconImageView);
3041                     fi.setVisibility(View.VISIBLE);
3042                 }
3043             }
3044         });
3045         oa.start();
3046     }
3047
3048     /**
3049      * Opens the user folder described by the specified tag. The opening of the folder
3050      * is animated relative to the specified View. If the View is null, no animation
3051      * is played.
3052      *
3053      * @param folderInfo The FolderInfo describing the folder to open.
3054      */
3055     public void openFolder(FolderIcon folderIcon) {
3056         Folder folder = folderIcon.getFolder();
3057         Folder openFolder = mWorkspace != null ? mWorkspace.getOpenFolder() : null;
3058         if (openFolder != null && openFolder != folder) {
3059             // Close any open folder before opening a folder.
3060             closeFolder();
3061         }
3062
3063         FolderInfo info = folder.mInfo;
3064
3065         info.opened = true;
3066
3067         // While the folder is open, the position of the icon cannot change.
3068         ((CellLayout.LayoutParams) folderIcon.getLayoutParams()).canReorder = false;
3069
3070         // Just verify that the folder hasn't already been added to the DragLayer.
3071         // There was a one-off crash where the folder had a parent already.
3072         if (folder.getParent() == null) {
3073             mDragLayer.addView(folder);
3074             mDragController.addDropTarget((DropTarget) folder);
3075         } else {
3076             Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
3077                     folder.getParent() + ").");
3078         }
3079         folder.animateOpen();
3080         growAndFadeOutFolderIcon(folderIcon);
3081
3082         // Notify the accessibility manager that this folder "window" has appeared and occluded
3083         // the workspace items
3084         folder.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3085         getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
3086     }
3087
3088     public void closeFolder() {
3089         Folder folder = mWorkspace != null ? mWorkspace.getOpenFolder() : null;
3090         if (folder != null) {
3091             if (folder.isEditingName()) {
3092                 folder.dismissEditingName();
3093             }
3094             closeFolder(folder);
3095         }
3096     }
3097
3098     public void closeFolder(Folder folder) {
3099         folder.getInfo().opened = false;
3100
3101         ViewGroup parent = (ViewGroup) folder.getParent().getParent();
3102         if (parent != null) {
3103             FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
3104             shrinkAndFadeInFolderIcon(fi);
3105             if (fi != null) {
3106                 ((CellLayout.LayoutParams) fi.getLayoutParams()).canReorder = true;
3107             }
3108         }
3109         folder.animateClosed();
3110
3111         // Notify the accessibility manager that this folder "window" has disappeard and no
3112         // longer occludeds the workspace items
3113         getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3114     }
3115
3116     public boolean onLongClick(View v) {
3117         if (!isDraggingEnabled()) return false;
3118         if (isWorkspaceLocked()) return false;
3119         if (mState != State.WORKSPACE) return false;
3120
3121         if (v == mAllAppsButton) {
3122             onLongClickAllAppsButton(v);
3123             return true;
3124         }
3125
3126         if (v instanceof Workspace) {
3127             if (!mWorkspace.isInOverviewMode()) {
3128                 if (!mWorkspace.isTouchActive()) {
3129                     showOverviewMode(true);
3130                     mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
3131                             HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
3132                     return true;
3133                 } else {
3134                     return false;
3135                 }
3136             } else {
3137                 return false;
3138             }
3139         }
3140
3141         CellLayout.CellInfo longClickCellInfo = null;
3142         View itemUnderLongClick = null;
3143         if (v.getTag() instanceof ItemInfo) {
3144             ItemInfo info = (ItemInfo) v.getTag();
3145             longClickCellInfo = new CellLayout.CellInfo(v, info);
3146             itemUnderLongClick = longClickCellInfo.cell;
3147             resetAddInfo();
3148         }
3149
3150         // The hotseat touch handling does not go through Workspace, and we always allow long press
3151         // on hotseat items.
3152         final boolean inHotseat = isHotseatLayout(v);
3153         if (!mDragController.isDragging()) {
3154             if (itemUnderLongClick == null) {
3155                 // User long pressed on empty space
3156                 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
3157                         HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
3158                 if (mWorkspace.isInOverviewMode()) {
3159                     mWorkspace.startReordering(v);
3160                 } else {
3161                     showOverviewMode(true);
3162                 }
3163             } else {
3164                 final boolean isAllAppsButton = inHotseat && isAllAppsButtonRank(
3165                         mHotseat.getOrderInHotseat(
3166                                 longClickCellInfo.cellX,
3167                                 longClickCellInfo.cellY));
3168                 if (!(itemUnderLongClick instanceof Folder || isAllAppsButton)) {
3169                     // User long pressed on an item
3170                     mWorkspace.startDrag(longClickCellInfo);
3171                 }
3172             }
3173         }
3174         return true;
3175     }
3176
3177     boolean isHotseatLayout(View layout) {
3178         return mHotseat != null && layout != null &&
3179                 (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
3180     }
3181
3182     /**
3183      * Returns the CellLayout of the specified container at the specified screen.
3184      */
3185     public CellLayout getCellLayout(long container, long screenId) {
3186         if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
3187             if (mHotseat != null) {
3188                 return mHotseat.getLayout();
3189             } else {
3190                 return null;
3191             }
3192         } else {
3193             return mWorkspace.getScreenWithId(screenId);
3194         }
3195     }
3196
3197     /**
3198      * For overridden classes.
3199      */
3200     public boolean isAllAppsVisible() {
3201         return isAppsViewVisible();
3202     }
3203
3204     public boolean isAppsViewVisible() {
3205         return (mState == State.APPS) || (mOnResumeState == State.APPS);
3206     }
3207
3208     public boolean isWidgetsViewVisible() {
3209         return (mState == State.WIDGETS) || (mOnResumeState == State.WIDGETS);
3210     }
3211
3212     private void setWorkspaceBackground(int background) {
3213         switch (background) {
3214             case WORKSPACE_BACKGROUND_TRANSPARENT:
3215                 getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
3216                 break;
3217             case WORKSPACE_BACKGROUND_BLACK:
3218                 getWindow().setBackgroundDrawable(null);
3219                 break;
3220             default:
3221                 getWindow().setBackgroundDrawable(mWorkspaceBackgroundDrawable);
3222         }
3223     }
3224
3225     protected void changeWallpaperVisiblity(boolean visible) {
3226         int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
3227         int curflags = getWindow().getAttributes().flags
3228                 & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
3229         if (wpflags != curflags) {
3230             getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
3231         }
3232         setWorkspaceBackground(visible ? WORKSPACE_BACKGROUND_GRADIENT : WORKSPACE_BACKGROUND_BLACK);
3233     }
3234
3235     @Override
3236     public void onTrimMemory(int level) {
3237         super.onTrimMemory(level);
3238         if (level >= ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
3239             // The widget preview db can result in holding onto over
3240             // 3MB of memory for caching which isn't necessary.
3241             SQLiteDatabase.releaseMemory();
3242
3243             // This clears all widget bitmaps from the widget tray
3244             // TODO(hyunyoungs)
3245         }
3246         if (mLauncherCallbacks != null) {
3247             mLauncherCallbacks.onTrimMemory(level);
3248         }
3249     }
3250
3251     public void showWorkspace(boolean animated) {
3252         showWorkspace(WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated, null);
3253     }
3254
3255     public void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
3256         showWorkspace(WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated,
3257                 onCompleteRunnable);
3258     }
3259
3260     protected void showWorkspace(int snapToPage, boolean animated) {
3261         showWorkspace(snapToPage, animated, null);
3262     }
3263
3264     void showWorkspace(int snapToPage, boolean animated, Runnable onCompleteRunnable) {
3265         boolean changed = mState != State.WORKSPACE ||
3266                 mWorkspace.getState() != Workspace.State.NORMAL;
3267         if (changed) {
3268             mWorkspace.setVisibility(View.VISIBLE);
3269             mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
3270                     Workspace.State.NORMAL, snapToPage, animated, onCompleteRunnable);
3271
3272             // Set focus to the AppsCustomize button
3273             if (mAllAppsButton != null) {
3274                 mAllAppsButton.requestFocus();
3275             }
3276         }
3277
3278         // Change the state *after* we've called all the transition code
3279         mState = State.WORKSPACE;
3280
3281         // Resume the auto-advance of widgets
3282         mUserPresent = true;
3283         updateAutoAdvanceState();
3284
3285         if (changed) {
3286             // Send an accessibility event to announce the context change
3287             getWindow().getDecorView()
3288                     .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3289         }
3290     }
3291
3292     void showOverviewMode(boolean animated) {
3293         mWorkspace.setVisibility(View.VISIBLE);
3294         mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
3295                 Workspace.State.OVERVIEW,
3296                 WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, animated,
3297                 null /* onCompleteRunnable */);
3298         mState = State.WORKSPACE;
3299     }
3300
3301     /**
3302      * Shows the apps view.
3303      */
3304     void showAppsView(boolean animated, boolean resetListToTop, boolean updatePredictedApps,
3305             boolean focusSearchBar) {
3306         if (resetListToTop) {
3307             mAppsView.scrollToTop();
3308         }
3309         if (updatePredictedApps) {
3310             tryAndUpdatePredictedApps();
3311         }
3312         showAppsOrWidgets(State.APPS, animated, focusSearchBar);
3313     }
3314
3315     /**
3316      * Shows the widgets view.
3317      */
3318     void showWidgetsView(boolean animated, boolean resetPageToZero) {
3319         if (LOGD) Log.d(TAG, "showWidgetsView:" + animated + " resetPageToZero:" + resetPageToZero);
3320         if (resetPageToZero) {
3321             mWidgetsView.scrollToTop();
3322         }
3323         showAppsOrWidgets(State.WIDGETS, animated, false);
3324
3325         mWidgetsView.post(new Runnable() {
3326             @Override
3327             public void run() {
3328                 mWidgetsView.requestFocus();
3329             }
3330         });
3331     }
3332
3333     /**
3334      * Sets up the transition to show the apps/widgets view.
3335      *
3336      * @return whether the current from and to state allowed this operation
3337      */
3338     // TODO: calling method should use the return value so that when {@code false} is returned
3339     // the workspace transition doesn't fall into invalid state.
3340     private boolean showAppsOrWidgets(State toState, boolean animated, boolean focusSearchBar) {
3341         if (mState != State.WORKSPACE &&  mState != State.APPS_SPRING_LOADED &&
3342                 mState != State.WIDGETS_SPRING_LOADED) {
3343             return false;
3344         }
3345         if (toState != State.APPS && toState != State.WIDGETS) {
3346             return false;
3347         }
3348
3349         if (toState == State.APPS) {
3350             mStateTransitionAnimation.startAnimationToAllApps(mWorkspace.getState(), animated,
3351                     focusSearchBar);
3352         } else {
3353             mStateTransitionAnimation.startAnimationToWidgets(mWorkspace.getState(), animated);
3354         }
3355
3356         // Change the state *after* we've called all the transition code
3357         mState = toState;
3358
3359         // Pause the auto-advance of widgets until we are out of AllApps
3360         mUserPresent = false;
3361         updateAutoAdvanceState();
3362         closeFolder();
3363
3364         // Send an accessibility event to announce the context change
3365         getWindow().getDecorView()
3366                 .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3367         return true;
3368     }
3369
3370     /**
3371      * Updates the workspace and interaction state on state change, and return the animation to this
3372      * new state.
3373      */
3374     public Animator startWorkspaceStateChangeAnimation(Workspace.State toState, int toPage,
3375             boolean animated, HashMap<View, Integer> layerViews) {
3376         Workspace.State fromState = mWorkspace.getState();
3377         Animator anim = mWorkspace.setStateWithAnimation(toState, toPage, animated, layerViews);
3378         updateInteraction(fromState, toState);
3379         return anim;
3380     }
3381
3382     public void enterSpringLoadedDragMode() {
3383         if (LOGD) Log.d(TAG, String.format("enterSpringLoadedDragMode [mState=%s", mState.name()));
3384         if (mState == State.WORKSPACE || mState == State.APPS_SPRING_LOADED ||
3385                 mState == State.WIDGETS_SPRING_LOADED) {
3386             return;
3387         }
3388
3389         mStateTransitionAnimation.startAnimationToWorkspace(mState, mWorkspace.getState(),
3390                 Workspace.State.SPRING_LOADED,
3391                 WorkspaceStateTransitionAnimation.SCROLL_TO_CURRENT_PAGE, true /* animated */,
3392                 null /* onCompleteRunnable */);
3393         mState = isAppsViewVisible() ? State.APPS_SPRING_LOADED : State.WIDGETS_SPRING_LOADED;
3394     }
3395
3396     public void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, int delay,
3397             final Runnable onCompleteRunnable) {
3398         if (mState != State.APPS_SPRING_LOADED && mState != State.WIDGETS_SPRING_LOADED) return;
3399
3400         mHandler.postDelayed(new Runnable() {
3401             @Override
3402             public void run() {
3403                 if (successfulDrop) {
3404                     // TODO(hyunyoungs): verify if this hack is still needed, if not, delete.
3405                     //
3406                     // Before we show workspace, hide all apps again because
3407                     // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
3408                     // clean up our state transition functions
3409                     mWidgetsView.setVisibility(View.GONE);
3410                     showWorkspace(true, onCompleteRunnable);
3411                 } else {
3412                     exitSpringLoadedDragMode();
3413                 }
3414             }
3415         }, delay);
3416     }
3417
3418     void exitSpringLoadedDragMode() {
3419         if (mState == State.APPS_SPRING_LOADED) {
3420             showAppsView(true /* animated */, false /* resetListToTop */,
3421                     false /* updatePredictedApps */, false /* focusSearchBar */);
3422         } else if (mState == State.WIDGETS_SPRING_LOADED) {
3423             showWidgetsView(true, false);
3424         }
3425     }
3426
3427     /**
3428      * Updates the set of predicted apps if it hasn't been updated since the last time Launcher was
3429      * resumed.
3430      */
3431     private void tryAndUpdatePredictedApps() {
3432         if (mLauncherCallbacks != null) {
3433             List<ComponentKey> apps = mLauncherCallbacks.getPredictedApps();
3434             if (apps != null) {
3435                 mAppsView.setPredictedApps(apps);
3436             }
3437         }
3438     }
3439
3440     void lockAllApps() {
3441         // TODO
3442     }
3443
3444     void unlockAllApps() {
3445         // TODO
3446     }
3447
3448     protected void disableVoiceButtonProxy(boolean disable) {
3449         // NO-OP
3450     }
3451
3452     public View getOrCreateQsbBar() {
3453         if (mLauncherCallbacks != null && mLauncherCallbacks.providesSearch()) {
3454             return mLauncherCallbacks.getQsbBar();
3455         }
3456
3457         if (mQsb == null) {
3458             AppWidgetProviderInfo searchProvider = Utilities.getSearchWidgetProvider(this);
3459             if (searchProvider == null) {
3460                 return null;
3461             }
3462
3463             Bundle opts = new Bundle();
3464             opts.putInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY,
3465                     AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX);
3466
3467             SharedPreferences sp = getSharedPreferences(
3468                     LauncherAppState.getSharedPreferencesKey(), MODE_PRIVATE);
3469             int widgetId = sp.getInt(QSB_WIDGET_ID, -1);
3470             AppWidgetProviderInfo widgetInfo = mAppWidgetManager.getAppWidgetInfo(widgetId);
3471             if (!searchProvider.provider.flattenToString().equals(
3472                     sp.getString(QSB_WIDGET_PROVIDER, null))
3473                     || (widgetInfo == null)
3474                     || !widgetInfo.provider.equals(searchProvider.provider)) {
3475                 // A valid widget is not already bound.
3476                 if (widgetId > -1) {
3477                     mAppWidgetHost.deleteAppWidgetId(widgetId);
3478                     widgetId = -1;
3479                 }
3480
3481                 // Try to bind a new widget
3482                 widgetId = mAppWidgetHost.allocateAppWidgetId();
3483
3484                 if (!AppWidgetManagerCompat.getInstance(this)
3485                         .bindAppWidgetIdIfAllowed(widgetId, searchProvider, opts)) {
3486                     mAppWidgetHost.deleteAppWidgetId(widgetId);
3487                     widgetId = -1;
3488                 }
3489
3490                 sp.edit()
3491                     .putInt(QSB_WIDGET_ID, widgetId)
3492                     .putString(QSB_WIDGET_PROVIDER, searchProvider.provider.flattenToString())
3493                     .commit();
3494             }
3495
3496             mAppWidgetHost.setQsbWidgetId(widgetId);
3497             if (widgetId != -1) {
3498                 mQsb = mAppWidgetHost.createView(this, widgetId, searchProvider);
3499                 mQsb.updateAppWidgetOptions(opts);
3500                 mQsb.setPadding(0, 0, 0, 0);
3501                 mSearchDropTargetBar.addView(mQsb);
3502                 mSearchDropTargetBar.setQsbSearchBar(mQsb);
3503             }
3504         }
3505         return mQsb;
3506     }
3507
3508     private void reinflateQSBIfNecessary() {
3509         if (mQsb instanceof LauncherAppWidgetHostView &&
3510                 ((LauncherAppWidgetHostView) mQsb).isReinflateRequired()) {
3511             mSearchDropTargetBar.removeView(mQsb);
3512             mQsb = null;
3513             mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
3514         }
3515     }
3516
3517     @Override
3518     public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3519         final boolean result = super.dispatchPopulateAccessibilityEvent(event);
3520         final List<CharSequence> text = event.getText();
3521         text.clear();
3522         // Populate event with a fake title based on the current state.
3523         if (mState == State.APPS) {
3524             text.add(getString(R.string.all_apps_button_label));
3525         } else if (mState == State.WIDGETS) {
3526             text.add(getString(R.string.widget_button_text));
3527         } else if (mWorkspace != null) {
3528             text.add(mWorkspace.getCurrentPageDescription());
3529         } else {
3530             text.add(getString(R.string.all_apps_home_button_label));
3531         }
3532         return result;
3533     }
3534
3535     /**
3536      * Receives notifications when system dialogs are to be closed.
3537      */
3538     @Thunk class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
3539         @Override
3540         public void onReceive(Context context, Intent intent) {
3541             closeSystemDialogs();
3542         }
3543     }
3544
3545     /**
3546      * If the activity is currently paused, signal that we need to run the passed Runnable
3547      * in onResume.
3548      *
3549      * This needs to be called from incoming places where resources might have been loaded
3550      * while the activity is paused. That is because the Configuration (e.g., rotation)  might be
3551      * wrong when we're not running, and if the activity comes back to what the configuration was
3552      * when we were paused, activity is not restarted.
3553      *
3554      * Implementation of the method from LauncherModel.Callbacks.
3555      *
3556      * @return {@code true} if we are currently paused. The caller might be able to skip some work
3557      */
3558     @Thunk boolean waitUntilResume(Runnable run, boolean deletePreviousRunnables) {
3559         if (mPaused) {
3560             if (LOGD) Log.d(TAG, "Deferring update until onResume");
3561             if (deletePreviousRunnables) {
3562                 while (mBindOnResumeCallbacks.remove(run)) {
3563                 }
3564             }
3565             mBindOnResumeCallbacks.add(run);
3566             return true;
3567         } else {
3568             return false;
3569         }
3570     }
3571
3572     private boolean waitUntilResume(Runnable run) {
3573         return waitUntilResume(run, false);
3574     }
3575
3576     public void addOnResumeCallback(Runnable run) {
3577         mOnResumeCallbacks.add(run);
3578     }
3579
3580     /**
3581      * If the activity is currently paused, signal that we need to re-run the loader
3582      * in onResume.
3583      *
3584      * This needs to be called from incoming places where resources might have been loaded
3585      * while we are paused.  That is becaues the Configuration might be wrong
3586      * when we're not running, and if it comes back to what it was when we
3587      * were paused, we are not restarted.
3588      *
3589      * Implementation of the method from LauncherModel.Callbacks.
3590      *
3591      * @return true if we are currently paused.  The caller might be able to
3592      * skip some work in that case since we will come back again.
3593      */
3594     public boolean setLoadOnResume() {
3595         if (mPaused) {
3596             if (LOGD) Log.d(TAG, "setLoadOnResume");
3597             mOnResumeNeedsLoad = true;
3598             return true;
3599         } else {
3600             return false;
3601         }
3602     }
3603
3604     /**
3605      * Implementation of the method from LauncherModel.Callbacks.
3606      */
3607     public int getCurrentWorkspaceScreen() {
3608         if (mWorkspace != null) {
3609             return mWorkspace.getCurrentPage();
3610         } else {
3611             return SCREEN_COUNT / 2;
3612         }
3613     }
3614
3615     /**
3616      * Refreshes the shortcuts shown on the workspace.
3617      *
3618      * Implementation of the method from LauncherModel.Callbacks.
3619      */
3620     public void startBinding() {
3621         setWorkspaceLoading(true);
3622
3623         // If we're starting binding all over again, clear any bind calls we'd postponed in
3624         // the past (see waitUntilResume) -- we don't need them since we're starting binding
3625         // from scratch again
3626         mBindOnResumeCallbacks.clear();
3627
3628         // Clear the workspace because it's going to be rebound
3629         mWorkspace.clearDropTargets();
3630         mWorkspace.removeAllWorkspaceScreens();
3631
3632         mWidgetsToAdvance.clear();
3633         if (mHotseat != null) {
3634             mHotseat.resetLayout();
3635         }
3636     }
3637
3638     @Override
3639     public void bindScreens(ArrayList<Long> orderedScreenIds) {
3640         bindAddScreens(orderedScreenIds);
3641
3642         // If there are no screens, we need to have an empty screen
3643         if (orderedScreenIds.size() == 0) {
3644             mWorkspace.addExtraEmptyScreen();
3645         }
3646
3647         // Create the custom content page (this call updates mDefaultScreen which calls
3648         // setCurrentPage() so ensure that all pages are added before calling this).
3649         if (hasCustomContentToLeft()) {
3650             mWorkspace.createCustomContentContainer();
3651             populateCustomContentContainer();
3652         }
3653     }
3654
3655     @Override
3656     public void bindAddScreens(ArrayList<Long> orderedScreenIds) {
3657         int count = orderedScreenIds.size();
3658         for (int i = 0; i < count; i++) {
3659             mWorkspace.insertNewWorkspaceScreenBeforeEmptyScreen(orderedScreenIds.get(i));
3660         }
3661     }
3662
3663     private boolean shouldShowWeightWatcher() {
3664         String spKey = LauncherAppState.getSharedPreferencesKey();
3665         SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
3666         boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, SHOW_WEIGHT_WATCHER_DEFAULT);
3667
3668         return show;
3669     }
3670
3671     private void toggleShowWeightWatcher() {
3672         String spKey = LauncherAppState.getSharedPreferencesKey();
3673         SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
3674         boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, true);
3675
3676         show = !show;
3677
3678         SharedPreferences.Editor editor = sp.edit();
3679         editor.putBoolean(SHOW_WEIGHT_WATCHER, show);
3680         editor.commit();
3681
3682         if (mWeightWatcher != null) {
3683             mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
3684         }
3685     }
3686
3687     public void bindAppsAdded(final ArrayList<Long> newScreens,
3688                               final ArrayList<ItemInfo> addNotAnimated,
3689                               final ArrayList<ItemInfo> addAnimated,
3690                               final ArrayList<AppInfo> addedApps) {
3691         Runnable r = new Runnable() {
3692             public void run() {
3693                 bindAppsAdded(newScreens, addNotAnimated, addAnimated, addedApps);
3694             }
3695         };
3696         if (waitUntilResume(r)) {
3697             return;
3698         }
3699
3700         // Add the new screens
3701         if (newScreens != null) {
3702             bindAddScreens(newScreens);
3703         }
3704
3705         // We add the items without animation on non-visible pages, and with
3706         // animations on the new page (which we will try and snap to).
3707         if (addNotAnimated != null && !addNotAnimated.isEmpty()) {
3708             bindItems(addNotAnimated, 0,
3709                     addNotAnimated.size(), false);
3710         }
3711         if (addAnimated != null && !addAnimated.isEmpty()) {
3712             bindItems(addAnimated, 0,
3713                     addAnimated.size(), true);
3714         }
3715
3716         // Remove the extra empty screen
3717         mWorkspace.removeExtraEmptyScreen(false, false);
3718
3719         if (addedApps != null && mAppsView != null) {
3720             mAppsView.addApps(addedApps);
3721         }
3722     }
3723
3724     /**
3725      * Bind the items start-end from the list.
3726      *
3727      * Implementation of the method from LauncherModel.Callbacks.
3728      */
3729     public void bindItems(final ArrayList<ItemInfo> shortcuts, final int start, final int end,
3730                           final boolean forceAnimateIcons) {
3731         Runnable r = new Runnable() {
3732             public void run() {
3733                 bindItems(shortcuts, start, end, forceAnimateIcons);
3734             }
3735         };
3736         if (waitUntilResume(r)) {
3737             return;
3738         }
3739
3740         // Get the list of added shortcuts and intersect them with the set of shortcuts here
3741         final AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
3742         final Collection<Animator> bounceAnims = new ArrayList<Animator>();
3743         final boolean animateIcons = forceAnimateIcons && canRunNewAppsAnimation();
3744         Workspace workspace = mWorkspace;
3745         long newShortcutsScreenId = -1;
3746         for (int i = start; i < end; i++) {
3747             final ItemInfo item = shortcuts.get(i);
3748
3749             // Short circuit if we are loading dock items for a configuration which has no dock
3750             if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3751                     mHotseat == null) {
3752                 continue;
3753             }
3754
3755             switch (item.itemType) {
3756                 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3757                 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3758                     ShortcutInfo info = (ShortcutInfo) item;
3759                     View shortcut = createShortcut(info);
3760
3761                     /*
3762                      * TODO: FIX collision case
3763                      */
3764                     if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
3765                         CellLayout cl = mWorkspace.getScreenWithId(item.screenId);
3766                         if (cl != null && cl.isOccupied(item.cellX, item.cellY)) {
3767                             View v = cl.getChildAt(item.cellX, item.cellY);
3768                             Object tag = v.getTag();
3769                             String desc = "Collision while binding workspace item: " + item
3770                                     + ". Collides with " + tag;
3771                             if (LauncherAppState.isDogfoodBuild()) {
3772                                 throw (new RuntimeException(desc));
3773                             } else {
3774                                 Log.d(TAG, desc);
3775                             }
3776                         }
3777                     }
3778
3779                     workspace.addInScreenFromBind(shortcut, item.container, item.screenId, item.cellX,
3780                             item.cellY, 1, 1);
3781                     if (animateIcons) {
3782                         // Animate all the applications up now
3783                         shortcut.setAlpha(0f);
3784                         shortcut.setScaleX(0f);
3785                         shortcut.setScaleY(0f);
3786                         bounceAnims.add(createNewAppBounceAnimation(shortcut, i));
3787                         newShortcutsScreenId = item.screenId;
3788                     }
3789                     break;
3790                 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3791                     FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
3792                             (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3793                             (FolderInfo) item, mIconCache);
3794                     workspace.addInScreenFromBind(newFolder, item.container, item.screenId, item.cellX,
3795                             item.cellY, 1, 1);
3796                     break;
3797                 default:
3798                     throw new RuntimeException("Invalid Item Type");
3799             }
3800         }
3801
3802         if (animateIcons) {
3803             // Animate to the correct page
3804             if (newShortcutsScreenId > -1) {
3805                 long currentScreenId = mWorkspace.getScreenIdForPageIndex(mWorkspace.getNextPage());
3806                 final int newScreenIndex = mWorkspace.getPageIndexForScreenId(newShortcutsScreenId);
3807                 final Runnable startBounceAnimRunnable = new Runnable() {
3808                     public void run() {
3809                         anim.playTogether(bounceAnims);
3810                         anim.start();
3811                     }
3812                 };
3813                 if (newShortcutsScreenId != currentScreenId) {
3814                     // We post the animation slightly delayed to prevent slowdowns
3815                     // when we are loading right after we return to launcher.
3816                     mWorkspace.postDelayed(new Runnable() {
3817                         public void run() {
3818                             if (mWorkspace != null) {
3819                                 mWorkspace.snapToPage(newScreenIndex);
3820                                 mWorkspace.postDelayed(startBounceAnimRunnable,
3821                                         NEW_APPS_ANIMATION_DELAY);
3822                             }
3823                         }
3824                     }, NEW_APPS_PAGE_MOVE_DELAY);
3825                 } else {
3826                     mWorkspace.postDelayed(startBounceAnimRunnable, NEW_APPS_ANIMATION_DELAY);
3827                 }
3828             }
3829         }
3830         workspace.requestLayout();
3831     }
3832
3833     /**
3834      * Implementation of the method from LauncherModel.Callbacks.
3835      */
3836     public void bindFolders(final LongArrayMap<FolderInfo> folders) {
3837         Runnable r = new Runnable() {
3838             public void run() {
3839                 bindFolders(folders);
3840             }
3841         };
3842         if (waitUntilResume(r)) {
3843             return;
3844         }
3845         sFolders = folders.clone();
3846     }
3847
3848     /**
3849      * Add the views for a widget to the workspace.
3850      *
3851      * Implementation of the method from LauncherModel.Callbacks.
3852      */
3853     public void bindAppWidget(final LauncherAppWidgetInfo item) {
3854         Runnable r = new Runnable() {
3855             public void run() {
3856                 bindAppWidget(item);
3857             }
3858         };
3859         if (waitUntilResume(r)) {
3860             return;
3861         }
3862
3863         final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3864         if (DEBUG_WIDGETS) {
3865             Log.d(TAG, "bindAppWidget: " + item);
3866         }
3867         final Workspace workspace = mWorkspace;
3868
3869         LauncherAppWidgetProviderInfo appWidgetInfo =
3870                 LauncherModel.getProviderInfo(this, item.providerName, item.user);
3871
3872         if (!mIsSafeModeEnabled
3873                 && ((item.restoreStatus & LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY) == 0)
3874                 && ((item.restoreStatus & LauncherAppWidgetInfo.FLAG_ID_NOT_VALID) != 0)) {
3875             if (appWidgetInfo == null) {
3876                 if (DEBUG_WIDGETS) {
3877                     Log.d(TAG, "Removing restored widget: id=" + item.appWidgetId
3878                             + " belongs to component " + item.providerName
3879                             + ", as the povider is null");
3880                 }
3881                 LauncherModel.deleteItemFromDatabase(this, item);
3882                 return;
3883             }
3884             // Note: This assumes that the id remap broadcast is received before this step.
3885             // If that is not the case, the id remap will be ignored and user may see the
3886             // click to setup view.
3887             PendingAddWidgetInfo pendingInfo = new PendingAddWidgetInfo(this, appWidgetInfo, null);
3888             pendingInfo.spanX = item.spanX;
3889             pendingInfo.spanY = item.spanY;
3890             pendingInfo.minSpanX = item.minSpanX;
3891             pendingInfo.minSpanY = item.minSpanY;
3892             Bundle options = null;
3893                     WidgetHostViewLoader.getDefaultOptionsForWidget(this, pendingInfo);
3894
3895             int newWidgetId = mAppWidgetHost.allocateAppWidgetId();
3896             boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed(
3897                     newWidgetId, appWidgetInfo, options);
3898
3899             // TODO consider showing a permission dialog when the widget is clicked.
3900             if (!success) {
3901                 mAppWidgetHost.deleteAppWidgetId(newWidgetId);
3902                 if (DEBUG_WIDGETS) {
3903                     Log.d(TAG, "Removing restored widget: id=" + item.appWidgetId
3904                             + " belongs to component " + item.providerName
3905                             + ", as the launcher is unable to bing a new widget id");
3906                 }
3907                 LauncherModel.deleteItemFromDatabase(this, item);
3908                 return;
3909             }
3910
3911             item.appWidgetId = newWidgetId;
3912
3913             // If the widget has a configure activity, it is still needs to set it up, otherwise
3914             // the widget is ready to go.
3915             item.restoreStatus = (appWidgetInfo.configure == null)
3916                     ? LauncherAppWidgetInfo.RESTORE_COMPLETED
3917                     : LauncherAppWidgetInfo.FLAG_UI_NOT_READY;
3918
3919             LauncherModel.updateItemInDatabase(this, item);
3920         }
3921
3922         if (!mIsSafeModeEnabled && item.restoreStatus == LauncherAppWidgetInfo.RESTORE_COMPLETED) {
3923             final int appWidgetId = item.appWidgetId;
3924             if (DEBUG_WIDGETS) {
3925                 Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component "
3926                         + appWidgetInfo.provider);
3927             }
3928
3929             item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3930             item.minSpanX = appWidgetInfo.minSpanX;
3931             item.minSpanY = appWidgetInfo.minSpanY;
3932         } else {
3933             appWidgetInfo = null;
3934             PendingAppWidgetHostView view = new PendingAppWidgetHostView(this, item,
3935                     mIsSafeModeEnabled);
3936             view.updateIcon(mIconCache);
3937             item.hostView = view;
3938             item.hostView.updateAppWidget(null);
3939             item.hostView.setOnClickListener(this);
3940         }
3941
3942         item.hostView.setTag(item);
3943         item.onBindAppWidget(this);
3944
3945         workspace.addInScreen(item.hostView, item.container, item.screenId, item.cellX,
3946                 item.cellY, item.spanX, item.spanY, false);
3947         if (!item.isCustomWidget()) {
3948             addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3949         }
3950
3951         workspace.requestLayout();
3952
3953         if (DEBUG_WIDGETS) {
3954             Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3955                     + (SystemClock.uptimeMillis()-start) + "ms");
3956         }
3957     }
3958
3959     /**
3960      * Restores a pending widget.
3961      *
3962      * @param appWidgetId The app widget id
3963      * @param cellInfo The position on screen where to create the widget.
3964      */
3965     private void completeRestoreAppWidget(final int appWidgetId) {
3966         LauncherAppWidgetHostView view = mWorkspace.getWidgetForAppWidgetId(appWidgetId);
3967         if ((view == null) || !(view instanceof PendingAppWidgetHostView)) {
3968             Log.e(TAG, "Widget update called, when the widget no longer exists.");
3969             return;
3970         }
3971
3972         LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
3973         info.restoreStatus = LauncherAppWidgetInfo.RESTORE_COMPLETED;
3974
3975         mWorkspace.reinflateWidgetsIfNecessary();
3976         LauncherModel.updateItemInDatabase(this, info);
3977     }
3978
3979     public void onPageBoundSynchronously(int page) {
3980         mSynchronouslyBoundPages.add(page);
3981     }
3982
3983     /**
3984      * Callback saying that there aren't any more items to bind.
3985      *
3986      * Implementation of the method from LauncherModel.Callbacks.
3987      */
3988     public void finishBindingItems() {
3989         Runnable r = new Runnable() {
3990             public void run() {
3991                 finishBindingItems();
3992             }
3993         };
3994         if (waitUntilResume(r)) {
3995             return;
3996         }
3997         if (mSavedState != null) {
3998             if (!mWorkspace.hasFocus()) {
3999                 mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
4000             }
4001             mSavedState = null;
4002         }
4003
4004         mWorkspace.restoreInstanceStateForRemainingPages();
4005
4006         setWorkspaceLoading(false);
4007         sendLoadingCompleteBroadcastIfNecessary();
4008
4009         // If we received the result of any pending adds while the loader was running (e.g. the
4010         // widget configuration forced an orientation change), process them now.
4011         if (sPendingAddItem != null) {
4012             final long screenId = completeAdd(sPendingAddItem);
4013
4014             // TODO: this moves the user to the page where the pending item was added. Ideally,
4015             // the screen would be guaranteed to exist after bind, and the page would be set through
4016             // the workspace restore process.
4017             mWorkspace.post(new Runnable() {
4018                 @Override
4019                 public void run() {
4020                     mWorkspace.snapToScreenId(screenId);
4021                 }
4022             });
4023             sPendingAddItem = null;
4024         }
4025
4026         InstallShortcutReceiver.disableAndFlushInstallQueue(this);
4027
4028         if (mLauncherCallbacks != null) {
4029             mLauncherCallbacks.finishBindingItems(false);
4030         }
4031     }
4032
4033     private void sendLoadingCompleteBroadcastIfNecessary() {
4034         if (!mSharedPrefs.getBoolean(FIRST_LOAD_COMPLETE, false)) {
4035             String permission =
4036                     getResources().getString(R.string.receive_first_load_broadcast_permission);
4037             Intent intent = new Intent(ACTION_FIRST_LOAD_COMPLETE);
4038             sendBroadcast(intent, permission);
4039             SharedPreferences.Editor editor = mSharedPrefs.edit();
4040             editor.putBoolean(FIRST_LOAD_COMPLETE, true);
4041             editor.apply();
4042         }
4043     }
4044
4045     public boolean isAllAppsButtonRank(int rank) {
4046         if (mHotseat != null) {
4047             return mHotseat.isAllAppsButtonRank(rank);
4048         }
4049         return false;
4050     }
4051
4052     private boolean canRunNewAppsAnimation() {
4053         long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
4054         return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
4055     }
4056
4057     private ValueAnimator createNewAppBounceAnimation(View v, int i) {
4058         ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
4059                 PropertyValuesHolder.ofFloat("alpha", 1f),
4060                 PropertyValuesHolder.ofFloat("scaleX", 1f),
4061                 PropertyValuesHolder.ofFloat("scaleY", 1f));
4062         bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
4063         bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
4064         bounceAnim.setInterpolator(new OvershootInterpolator(BOUNCE_ANIMATION_TENSION));
4065         return bounceAnim;
4066     }
4067
4068     public boolean useVerticalBarLayout() {
4069         return mDeviceProfile.isVerticalBarLayout();
4070     }
4071
4072     protected Rect getSearchBarBounds() {
4073         return mDeviceProfile.getSearchBarBounds(Utilities.isRtl(getResources()));
4074     }
4075
4076     public void bindSearchProviderChanged() {
4077         if (mSearchDropTargetBar == null) {
4078             return;
4079         }
4080         if (mQsb != null) {
4081             mSearchDropTargetBar.removeView(mQsb);
4082             mQsb = null;
4083         }
4084         mSearchDropTargetBar.setQsbSearchBar(getOrCreateQsbBar());
4085     }
4086
4087     /**
4088      * A runnable that we can dequeue and re-enqueue when all applications are bound (to prevent
4089      * multiple calls to bind the same list.)
4090      */
4091     @Thunk ArrayList<AppInfo> mTmpAppsList;
4092     private Runnable mBindAllApplicationsRunnable = new Runnable() {
4093         public void run() {
4094             bindAllApplications(mTmpAppsList);
4095             mTmpAppsList = null;
4096         }
4097     };
4098
4099     /**
4100      * Add the icons for all apps.
4101      *
4102      * Implementation of the method from LauncherModel.Callbacks.
4103      */
4104     public void bindAllApplications(final ArrayList<AppInfo> apps) {
4105         if (waitUntilResume(mBindAllApplicationsRunnable, true)) {
4106             mTmpAppsList = apps;
4107             return;
4108         }
4109
4110         if (mAppsView != null) {
4111             mAppsView.setApps(apps);
4112         }
4113         if (mLauncherCallbacks != null) {
4114             mLauncherCallbacks.bindAllApplications(apps);
4115         }
4116     }
4117
4118     /**
4119      * A package was updated.
4120      *
4121      * Implementation of the method from LauncherModel.Callbacks.
4122      */
4123     public void bindAppsUpdated(final ArrayList<AppInfo> apps) {
4124         Runnable r = new Runnable() {
4125             public void run() {
4126                 bindAppsUpdated(apps);
4127             }
4128         };
4129         if (waitUntilResume(r)) {
4130             return;
4131         }
4132
4133         if (mAppsView != null) {
4134             mAppsView.updateApps(apps);
4135         }
4136     }
4137
4138     @Override
4139     public void bindWidgetsRestored(final ArrayList<LauncherAppWidgetInfo> widgets) {
4140         Runnable r = new Runnable() {
4141             public void run() {
4142                 bindWidgetsRestored(widgets);
4143             }
4144         };
4145         if (waitUntilResume(r)) {
4146             return;
4147         }
4148         mWorkspace.widgetsRestored(widgets);
4149     }
4150
4151     /**
4152      * Some shortcuts were updated in the background.
4153      *
4154      * Implementation of the method from LauncherModel.Callbacks.
4155      */
4156     @Override
4157     public void bindShortcutsChanged(final ArrayList<ShortcutInfo> updated,
4158             final ArrayList<ShortcutInfo> removed, final UserHandleCompat user) {
4159         Runnable r = new Runnable() {
4160             public void run() {
4161                 bindShortcutsChanged(updated, removed, user);
4162             }
4163         };
4164         if (waitUntilResume(r)) {
4165             return;
4166         }
4167
4168         if (!updated.isEmpty()) {
4169             mWorkspace.updateShortcuts(updated);
4170         }
4171
4172         if (!removed.isEmpty()) {
4173             HashSet<ComponentName> removedComponents = new HashSet<ComponentName>();
4174             for (ShortcutInfo si : removed) {
4175                 removedComponents.add(si.getTargetComponent());
4176             }
4177             mWorkspace.removeItemsByComponentName(removedComponents, user);
4178             // Notify the drag controller
4179             mDragController.onAppsRemoved(new ArrayList<String>(), removedComponents);
4180         }
4181     }
4182
4183     /**
4184      * Update the state of a package, typically related to install state.
4185      *
4186      * Implementation of the method from LauncherModel.Callbacks.
4187      */
4188     @Override
4189     public void bindRestoreItemsChange(final HashSet<ItemInfo> updates) {
4190         Runnable r = new Runnable() {
4191             public void run() {
4192                 bindRestoreItemsChange(updates);
4193             }
4194         };
4195         if (waitUntilResume(r)) {
4196             return;
4197         }
4198
4199         mWorkspace.updateRestoreItems(updates);
4200     }
4201
4202     /**
4203      * A package was uninstalled.  We take both the super set of packageNames
4204      * in addition to specific applications to remove, the reason being that
4205      * this can be called when a package is updated as well.  In that scenario,
4206      * we only remove specific components from the workspace, where as
4207      * package-removal should clear all items by package name.
4208      *
4209      * @param reason if non-zero, the icons are not permanently removed, rather marked as disabled.
4210      * Implementation of the method from LauncherModel.Callbacks.
4211      */
4212     @Override
4213     public void bindComponentsRemoved(final ArrayList<String> packageNames,
4214             final ArrayList<AppInfo> appInfos, final UserHandleCompat user, final int reason) {
4215         Runnable r = new Runnable() {
4216             public void run() {
4217                 bindComponentsRemoved(packageNames, appInfos, user, reason);
4218             }
4219         };
4220         if (waitUntilResume(r)) {
4221             return;
4222         }
4223
4224         if (reason == 0) {
4225             HashSet<ComponentName> removedComponents = new HashSet<ComponentName>();
4226             for (AppInfo info : appInfos) {
4227                 removedComponents.add(info.componentName);
4228             }
4229             if (!packageNames.isEmpty()) {
4230                 mWorkspace.removeItemsByPackageName(packageNames, user);
4231             }
4232             if (!removedComponents.isEmpty()) {
4233                 mWorkspace.removeItemsByComponentName(removedComponents, user);
4234             }
4235             // Notify the drag controller
4236             mDragController.onAppsRemoved(packageNames, removedComponents);
4237
4238         } else {
4239             mWorkspace.disableShortcutsByPackageName(packageNames, user, reason);
4240         }
4241
4242         // Update AllApps
4243         if (mAppsView != null) {
4244             mAppsView.removeApps(appInfos);
4245         }
4246     }
4247
4248     private Runnable mBindPackagesUpdatedRunnable = new Runnable() {
4249             public void run() {
4250                 bindAllPackages(mWidgetsModel);
4251             }
4252         };
4253
4254     @Override
4255     public void bindAllPackages(final WidgetsModel model) {
4256         if (waitUntilResume(mBindPackagesUpdatedRunnable, true)) {
4257             mWidgetsModel = model;
4258             return;
4259         }
4260
4261         if (mWidgetsView != null && model != null) {
4262             mWidgetsView.addWidgets(model);
4263             mWidgetsModel = null;
4264         }
4265     }
4266
4267     private int mapConfigurationOriActivityInfoOri(int configOri) {
4268         final Display d = getWindowManager().getDefaultDisplay();
4269         int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
4270         switch (d.getRotation()) {
4271         case Surface.ROTATION_0:
4272         case Surface.ROTATION_180:
4273             // We are currently in the same basic orientation as the natural orientation
4274             naturalOri = configOri;
4275             break;
4276         case Surface.ROTATION_90:
4277         case Surface.ROTATION_270:
4278             // We are currently in the other basic orientation to the natural orientation
4279             naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
4280                     Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
4281             break;
4282         }
4283
4284         int[] oriMap = {
4285                 ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
4286                 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
4287                 ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
4288                 ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
4289         };
4290         // Since the map starts at portrait, we need to offset if this device's natural orientation
4291         // is landscape.
4292         int indexOffset = 0;
4293         if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
4294             indexOffset = 1;
4295         }
4296         return oriMap[(d.getRotation() + indexOffset) % 4];
4297     }
4298
4299     public void lockScreenOrientation() {
4300         if (mRotationEnabled) {
4301             if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
4302                 setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
4303                         .getConfiguration().orientation));
4304             } else {
4305                 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
4306             }
4307         }
4308     }
4309
4310     public void unlockScreenOrientation(boolean immediate) {
4311         if (mRotationEnabled) {
4312             if (immediate) {
4313                 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
4314             } else {
4315                 mHandler.postDelayed(new Runnable() {
4316                     public void run() {
4317                         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
4318                     }
4319                 }, mRestoreScreenOrientationDelay);
4320             }
4321         }
4322     }
4323
4324     protected boolean isLauncherPreinstalled() {
4325         if (mLauncherCallbacks != null) {
4326             return mLauncherCallbacks.isLauncherPreinstalled();
4327         }
4328         PackageManager pm = getPackageManager();
4329         try {
4330             ApplicationInfo ai = pm.getApplicationInfo(getComponentName().getPackageName(), 0);
4331             if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4332                 return true;
4333             } else {
4334                 return false;
4335             }
4336         } catch (NameNotFoundException e) {
4337             e.printStackTrace();
4338             return false;
4339         }
4340     }
4341
4342     /**
4343      * This method indicates whether or not we should suggest default wallpaper dimensions
4344      * when our wallpaper cropper was not yet used to set a wallpaper.
4345      */
4346     protected boolean overrideWallpaperDimensions() {
4347         if (mLauncherCallbacks != null) {
4348             return mLauncherCallbacks.overrideWallpaperDimensions();
4349         }
4350         return true;
4351     }
4352
4353     /**
4354      * To be overridden by subclasses to indicate that there is an activity to launch
4355      * before showing the standard launcher experience.
4356      */
4357     protected boolean hasFirstRunActivity() {
4358         if (mLauncherCallbacks != null) {
4359             return mLauncherCallbacks.hasFirstRunActivity();
4360         }
4361         return false;
4362     }
4363
4364     /**
4365      * To be overridden by subclasses to launch any first run activity
4366      */
4367     protected Intent getFirstRunActivity() {
4368         if (mLauncherCallbacks != null) {
4369             return mLauncherCallbacks.getFirstRunActivity();
4370         }
4371         return null;
4372     }
4373
4374     private boolean shouldRunFirstRunActivity() {
4375         return !ActivityManager.isRunningInTestHarness() &&
4376                 !mSharedPrefs.getBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, false);
4377     }
4378
4379     protected boolean hasRunFirstRunActivity() {
4380         return mSharedPrefs.getBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, false);
4381     }
4382
4383     public boolean showFirstRunActivity() {
4384         if (shouldRunFirstRunActivity() &&
4385                 hasFirstRunActivity()) {
4386             Intent firstRunIntent = getFirstRunActivity();
4387             if (firstRunIntent != null) {
4388                 startActivity(firstRunIntent);
4389                 markFirstRunActivityShown();
4390                 return true;
4391             }
4392         }
4393         return false;
4394     }
4395
4396     private void markFirstRunActivityShown() {
4397         SharedPreferences.Editor editor = mSharedPrefs.edit();
4398         editor.putBoolean(FIRST_RUN_ACTIVITY_DISPLAYED, true);
4399         editor.apply();
4400     }
4401
4402     /**
4403      * To be overridden by subclasses to indicate that there is an in-activity full-screen intro
4404      * screen that must be displayed and dismissed.
4405      */
4406     protected boolean hasDismissableIntroScreen() {
4407         if (mLauncherCallbacks != null) {
4408             return mLauncherCallbacks.hasDismissableIntroScreen();
4409         }
4410         return false;
4411     }
4412
4413     /**
4414      * Full screen intro screen to be shown and dismissed before the launcher can be used.
4415      */
4416     protected View getIntroScreen() {
4417         if (mLauncherCallbacks != null) {
4418             return mLauncherCallbacks.getIntroScreen();
4419         }
4420         return null;
4421     }
4422
4423     /**
4424      * To be overriden by subclasses to indicate whether the in-activity intro screen has been
4425      * dismissed. This method is ignored if #hasDismissableIntroScreen returns false.
4426      */
4427     private boolean shouldShowIntroScreen() {
4428         return hasDismissableIntroScreen() &&
4429                 !mSharedPrefs.getBoolean(INTRO_SCREEN_DISMISSED, false);
4430     }
4431
4432     protected void showIntroScreen() {
4433         View introScreen = getIntroScreen();
4434         changeWallpaperVisiblity(false);
4435         if (introScreen != null) {
4436             mDragLayer.showOverlayView(introScreen);
4437         }
4438         if (mLauncherOverlayContainer != null) {
4439             mLauncherOverlayContainer.setVisibility(View.INVISIBLE);
4440         }
4441     }
4442
4443     public void dismissIntroScreen() {
4444         markIntroScreenDismissed();
4445         if (showFirstRunActivity()) {
4446             // We delay hiding the intro view until the first run activity is showing. This
4447             // avoids a blip.
4448             mWorkspace.postDelayed(new Runnable() {
4449                 @Override
4450                 public void run() {
4451                     mDragLayer.dismissOverlayView();
4452                     if (mLauncherOverlayContainer != null) {
4453                         mLauncherOverlayContainer.setVisibility(View.VISIBLE);
4454                     }
4455                     showFirstRunClings();
4456                 }
4457             }, ACTIVITY_START_DELAY);
4458         } else {
4459             mDragLayer.dismissOverlayView();
4460             if (mLauncherOverlayContainer != null) {
4461                 mLauncherOverlayContainer.setVisibility(View.VISIBLE);
4462             }
4463             showFirstRunClings();
4464         }
4465         changeWallpaperVisiblity(true);
4466     }
4467
4468     private void markIntroScreenDismissed() {
4469         SharedPreferences.Editor editor = mSharedPrefs.edit();
4470         editor.putBoolean(INTRO_SCREEN_DISMISSED, true);
4471         editor.apply();
4472     }
4473
4474     @Thunk void showFirstRunClings() {
4475         // The two first run cling paths are mutually exclusive, if the launcher is preinstalled
4476         // on the device, then we always show the first run cling experience (or if there is no
4477         // launcher2). Otherwise, we prompt the user upon started for migration
4478         LauncherClings launcherClings = new LauncherClings(this);
4479         if (launcherClings.shouldShowFirstRunOrMigrationClings()) {
4480             if (mModel.canMigrateFromOldLauncherDb(this)) {
4481                 launcherClings.showMigrationCling();
4482             } else {
4483                 launcherClings.showLongPressCling(true);
4484             }
4485         }
4486     }
4487
4488     void showWorkspaceSearchAndHotseat() {
4489         if (mWorkspace != null) mWorkspace.setAlpha(1f);
4490         if (mHotseat != null) mHotseat.setAlpha(1f);
4491         if (mPageIndicators != null) mPageIndicators.setAlpha(1f);
4492         if (mSearchDropTargetBar != null) mSearchDropTargetBar.animateToState(
4493                 SearchDropTargetBar.State.SEARCH_BAR, 0);
4494     }
4495
4496     void hideWorkspaceSearchAndHotseat() {
4497         if (mWorkspace != null) mWorkspace.setAlpha(0f);
4498         if (mHotseat != null) mHotseat.setAlpha(0f);
4499         if (mPageIndicators != null) mPageIndicators.setAlpha(0f);
4500         if (mSearchDropTargetBar != null) mSearchDropTargetBar.animateToState(
4501                 SearchDropTargetBar.State.INVISIBLE, 0);
4502     }
4503
4504     // TODO: These method should be a part of LauncherSearchCallback
4505     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
4506     public ItemInfo createAppDragInfo(Intent appLaunchIntent) {
4507         // Called from search suggestion
4508         UserHandleCompat user = null;
4509         if (Utilities.isLmpOrAbove()) {
4510             UserHandle userHandle = appLaunchIntent.getParcelableExtra(Intent.EXTRA_USER);
4511             if (userHandle != null) {
4512                 user = UserHandleCompat.fromUser(userHandle);
4513             }
4514         }
4515         return createAppDragInfo(appLaunchIntent, user);
4516     }
4517
4518     // TODO: This method should be a part of LauncherSearchCallback
4519     public ItemInfo createAppDragInfo(Intent intent, UserHandleCompat user) {
4520         if (user == null) {
4521             user = UserHandleCompat.myUserHandle();
4522         }
4523
4524         // Called from search suggestion, add the profile extra to the intent to ensure that we
4525         // can launch it correctly
4526         LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
4527         LauncherActivityInfoCompat activityInfo = launcherApps.resolveActivity(intent, user);
4528         if (activityInfo == null) {
4529             return null;
4530         }
4531         return new AppInfo(this, activityInfo, user, mIconCache);
4532     }
4533
4534     // TODO: This method should be a part of LauncherSearchCallback
4535     public ItemInfo createShortcutDragInfo(Intent shortcutIntent, CharSequence caption,
4536             Bitmap icon) {
4537         return new ShortcutInfo(shortcutIntent, caption, caption, icon,
4538                 UserHandleCompat.myUserHandle());
4539     }
4540
4541     // TODO: This method should be a part of LauncherSearchCallback
4542     public void startDrag(View dragView, ItemInfo dragInfo, DragSource source) {
4543         dragView.setTag(dragInfo);
4544         mWorkspace.onExternalDragStartedWithItem(dragView);
4545         mWorkspace.beginExternalDragShared(dragView, source);
4546     }
4547
4548     protected void moveWorkspaceToDefaultScreen() {
4549         mWorkspace.moveToDefaultScreen(false);
4550     }
4551
4552     @Override
4553     public void onPageSwitch(View newPage, int newPageIndex) {
4554         if (mLauncherCallbacks != null) {
4555             mLauncherCallbacks.onPageSwitch(newPage, newPageIndex);
4556         }
4557     }
4558
4559     /**
4560      * Returns a FastBitmapDrawable with the icon, accurately sized.
4561      */
4562     public FastBitmapDrawable createIconDrawable(Bitmap icon) {
4563         FastBitmapDrawable d = new FastBitmapDrawable(icon);
4564         d.setFilterBitmap(true);
4565         resizeIconDrawable(d);
4566         return d;
4567     }
4568
4569     /**
4570      * Resizes an icon drawable to the correct icon size.
4571      */
4572     public void resizeIconDrawable(Drawable icon) {
4573         icon.setBounds(0, 0, mDeviceProfile.iconSizePx, mDeviceProfile.iconSizePx);
4574     }
4575
4576     /**
4577      * Prints out out state for debugging.
4578      */
4579     public void dumpState() {
4580         Log.d(TAG, "BEGIN launcher3 dump state for launcher " + this);
4581         Log.d(TAG, "mSavedState=" + mSavedState);
4582         Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
4583         Log.d(TAG, "mRestoring=" + mRestoring);
4584         Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
4585         Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
4586         Log.d(TAG, "sFolders.size=" + sFolders.size());
4587         mModel.dumpState();
4588         // TODO(hyunyoungs): add mWidgetsView.dumpState(); or mWidgetsModel.dumpState();
4589
4590         Log.d(TAG, "END launcher3 dump state");
4591     }
4592
4593     @Override
4594     public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4595         super.dump(prefix, fd, writer, args);
4596         synchronized (sDumpLogs) {
4597             writer.println(" ");
4598             writer.println("Debug logs: ");
4599             for (int i = 0; i < sDumpLogs.size(); i++) {
4600                 writer.println("  " + sDumpLogs.get(i));
4601             }
4602         }
4603         if (mLauncherCallbacks != null) {
4604             mLauncherCallbacks.dump(prefix, fd, writer, args);
4605         }
4606     }
4607
4608     public static void dumpDebugLogsToConsole() {
4609         if (DEBUG_DUMP_LOG) {
4610             synchronized (sDumpLogs) {
4611                 Log.d(TAG, "");
4612                 Log.d(TAG, "*********************");
4613                 Log.d(TAG, "Launcher debug logs: ");
4614                 for (int i = 0; i < sDumpLogs.size(); i++) {
4615                     Log.d(TAG, "  " + sDumpLogs.get(i));
4616                 }
4617                 Log.d(TAG, "*********************");
4618                 Log.d(TAG, "");
4619             }
4620         }
4621     }
4622
4623     public static void addDumpLog(String tag, String log, boolean debugLog) {
4624         addDumpLog(tag, log, null, debugLog);
4625     }
4626
4627     public static void addDumpLog(String tag, String log, Exception e, boolean debugLog) {
4628         if (debugLog) {
4629             if (e != null) {
4630                 Log.d(tag, log, e);
4631             } else {
4632                 Log.d(tag, log);
4633             }
4634         }
4635         if (DEBUG_DUMP_LOG) {
4636             sDateStamp.setTime(System.currentTimeMillis());
4637             synchronized (sDumpLogs) {
4638                 sDumpLogs.add(sDateFormat.format(sDateStamp) + ": " + tag + ", " + log
4639                     + (e == null ? "" : (", Exception: " + e)));
4640             }
4641         }
4642     }
4643
4644     public static CustomAppWidget getCustomAppWidget(String name) {
4645         return sCustomAppWidgets.get(name);
4646     }
4647
4648     public static HashMap<String, CustomAppWidget> getCustomAppWidgets() {
4649         return sCustomAppWidgets;
4650     }
4651
4652     public void dumpLogsToLocalData() {
4653         if (DEBUG_DUMP_LOG) {
4654             new AsyncTask<Void, Void, Void>() {
4655                 public Void doInBackground(Void ... args) {
4656                     boolean success = false;
4657                     sDateStamp.setTime(sRunStart);
4658                     String FILENAME = sDateStamp.getMonth() + "-"
4659                             + sDateStamp.getDay() + "_"
4660                             + sDateStamp.getHours() + "-"
4661                             + sDateStamp.getMinutes() + "_"
4662                             + sDateStamp.getSeconds() + ".txt";
4663
4664                     FileOutputStream fos = null;
4665                     File outFile = null;
4666                     try {
4667                         outFile = new File(getFilesDir(), FILENAME);
4668                         outFile.createNewFile();
4669                         fos = new FileOutputStream(outFile);
4670                     } catch (Exception e) {
4671                         e.printStackTrace();
4672                     }
4673                     if (fos != null) {
4674                         PrintWriter writer = new PrintWriter(fos);
4675
4676                         writer.println(" ");
4677                         writer.println("Debug logs: ");
4678                         synchronized (sDumpLogs) {
4679                             for (int i = 0; i < sDumpLogs.size(); i++) {
4680                                 writer.println("  " + sDumpLogs.get(i));
4681                             }
4682                         }
4683                         writer.close();
4684                     }
4685                     try {
4686                         if (fos != null) {
4687                             fos.close();
4688                             success = true;
4689                         }
4690                     } catch (IOException e) {
4691                         e.printStackTrace();
4692                     }
4693                     return null;
4694                 }
4695             }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
4696         }
4697     }
4698 }
4699
4700 interface DebugIntents {
4701     static final String DELETE_DATABASE = "com.android.launcher3.action.DELETE_DATABASE";
4702     static final String MIGRATE_DATABASE = "com.android.launcher3.action.MIGRATE_DATABASE";
4703 }