OSDN Git Service

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