OSDN Git Service

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