Launcher.java revision a805e1a297c0d1fa84d9fed51e0167aa32bd42bb
1
2/*
3 * Copyright (C) 2008 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.launcher3;
19
20import android.accounts.Account;
21import android.accounts.AccountManager;
22import android.animation.Animator;
23import android.animation.AnimatorListenerAdapter;
24import android.animation.AnimatorSet;
25import android.animation.ObjectAnimator;
26import android.animation.PropertyValuesHolder;
27import android.animation.ValueAnimator;
28import android.animation.ValueAnimator.AnimatorUpdateListener;
29import android.app.Activity;
30import android.app.ActivityManager;
31import android.app.ActivityOptions;
32import android.app.SearchManager;
33import android.appwidget.AppWidgetHostView;
34import android.appwidget.AppWidgetManager;
35import android.appwidget.AppWidgetProviderInfo;
36import android.content.ActivityNotFoundException;
37import android.content.BroadcastReceiver;
38import android.content.ComponentCallbacks2;
39import android.content.ComponentName;
40import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
44import android.content.SharedPreferences;
45import android.content.pm.ActivityInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.PackageManager.NameNotFoundException;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.database.ContentObserver;
51import android.graphics.Bitmap;
52import android.graphics.Canvas;
53import android.graphics.Point;
54import android.graphics.PorterDuff;
55import android.graphics.Rect;
56import android.graphics.drawable.Drawable;
57import android.net.Uri;
58import android.os.AsyncTask;
59import android.os.Bundle;
60import android.os.Environment;
61import android.os.Handler;
62import android.os.Message;
63import android.os.StrictMode;
64import android.os.SystemClock;
65import android.provider.Settings;
66import android.speech.RecognizerIntent;
67import android.text.Selection;
68import android.text.SpannableStringBuilder;
69import android.text.TextUtils;
70import android.text.method.TextKeyListener;
71import android.util.Log;
72import android.view.Display;
73import android.view.Gravity;
74import android.view.HapticFeedbackConstants;
75import android.view.KeyEvent;
76import android.view.LayoutInflater;
77import android.view.Menu;
78import android.view.MenuItem;
79import android.view.MotionEvent;
80import android.view.Surface;
81import android.view.View;
82import android.view.View.OnClickListener;
83import android.view.View.OnLongClickListener;
84import android.view.ViewGroup;
85import android.view.ViewTreeObserver;
86import android.view.ViewTreeObserver.OnGlobalLayoutListener;
87import android.view.WindowManager;
88import android.view.accessibility.AccessibilityEvent;
89import android.view.animation.AccelerateDecelerateInterpolator;
90import android.view.animation.AccelerateInterpolator;
91import android.view.animation.DecelerateInterpolator;
92import android.view.inputmethod.InputMethodManager;
93import android.widget.Advanceable;
94import android.widget.FrameLayout;
95import android.widget.ImageView;
96import android.widget.TextView;
97import android.widget.Toast;
98
99import com.android.launcher3.DropTarget.DragObject;
100
101import java.io.DataInputStream;
102import java.io.DataOutputStream;
103import java.io.FileDescriptor;
104import java.io.FileNotFoundException;
105import java.io.IOException;
106import java.io.PrintWriter;
107import java.util.ArrayList;
108import java.util.Collection;
109import java.util.HashMap;
110import java.util.List;
111
112/**
113 * Default launcher application.
114 */
115public class Launcher extends Activity
116        implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
117                   View.OnTouchListener {
118    static final String TAG = "Launcher";
119    static final boolean LOGD = false;
120
121    static final boolean PROFILE_STARTUP = false;
122    static final boolean DEBUG_WIDGETS = false;
123    static final boolean DEBUG_STRICT_MODE = false;
124    static final boolean DEBUG_RESUME_TIME = false;
125
126    private static final int MENU_GROUP_WALLPAPER = 1;
127    private static final int MENU_WALLPAPER_SETTINGS = Menu.FIRST + 1;
128    private static final int MENU_MANAGE_APPS = MENU_WALLPAPER_SETTINGS + 1;
129    private static final int MENU_SYSTEM_SETTINGS = MENU_MANAGE_APPS + 1;
130    private static final int MENU_HELP = MENU_SYSTEM_SETTINGS + 1;
131
132    private static final int REQUEST_CREATE_SHORTCUT = 1;
133    private static final int REQUEST_CREATE_APPWIDGET = 5;
134    private static final int REQUEST_PICK_APPLICATION = 6;
135    private static final int REQUEST_PICK_SHORTCUT = 7;
136    private static final int REQUEST_PICK_APPWIDGET = 9;
137    private static final int REQUEST_PICK_WALLPAPER = 10;
138
139    private static final int REQUEST_BIND_APPWIDGET = 11;
140
141    /**
142     * IntentStarter uses request codes starting with this. This must be greater than all activity
143     * request codes used internally.
144     */
145    protected static final int REQUEST_LAST = 100;
146
147    static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
148
149    static final int SCREEN_COUNT = 5;
150    static final int DEFAULT_SCREEN = 2;
151
152    private static final String PREFERENCES = "launcher.preferences";
153    // To turn on these properties, type
154    // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
155    static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
156    static final String DUMP_STATE_PROPERTY = "launcher_dump_state";
157
158    // The Intent extra that defines whether to ignore the launch animation
159    static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
160            "com.android.launcher3.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
161
162    // Type: int
163    private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
164    // Type: int
165    private static final String RUNTIME_STATE = "launcher.state";
166    // Type: int
167    private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
168    // Type: int
169    private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
170    // Type: int
171    private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
172    // Type: int
173    private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
174    // Type: boolean
175    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
176    // Type: long
177    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
178    // Type: int
179    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
180    // Type: int
181    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
182    // Type: parcelable
183    private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
184
185    private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
186    private static final String TOOLBAR_SEARCH_ICON_METADATA_NAME =
187            "com.android.launcher.toolbar_search_icon";
188    private static final String TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME =
189            "com.android.launcher.toolbar_voice_search_icon";
190
191    public static final String SHOW_WEIGHT_WATCHER = "debug.show_mem";
192    public static final boolean SHOW_WEIGHT_WATCHER_DEFAULT = false;
193
194    /** The different states that Launcher can be in. */
195    private enum State { NONE, WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
196    private State mState = State.WORKSPACE;
197    private AnimatorSet mStateAnimation;
198
199    static final int APPWIDGET_HOST_ID = 1024;
200    private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
201    private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
202    private static final int SHOW_CLING_DURATION = 550;
203    private static final int DISMISS_CLING_DURATION = 250;
204
205    private static final Object sLock = new Object();
206    private static int sScreen = DEFAULT_SCREEN;
207
208    // How long to wait before the new-shortcut animation automatically pans the workspace
209    private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 10;
210    private static int NEW_APPS_ANIMATION_DELAY = 500;
211
212    private final BroadcastReceiver mCloseSystemDialogsReceiver
213            = new CloseSystemDialogsIntentReceiver();
214    private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
215
216    private LayoutInflater mInflater;
217
218    private Workspace mWorkspace;
219    private View mLauncherView;
220    private DragLayer mDragLayer;
221    private DragController mDragController;
222    private View mWeightWatcher;
223
224    private AppWidgetManager mAppWidgetManager;
225    private LauncherAppWidgetHost mAppWidgetHost;
226
227    private ItemInfo mPendingAddInfo = new ItemInfo();
228    private AppWidgetProviderInfo mPendingAddWidgetInfo;
229
230    private int[] mTmpAddItemCellCoordinates = new int[2];
231
232    private FolderInfo mFolderInfo;
233
234    private Hotseat mHotseat;
235    private View mOverviewPanel;
236
237    private View mAllAppsButton;
238
239    private SearchDropTargetBar mSearchDropTargetBar;
240    private AppsCustomizeTabHost mAppsCustomizeTabHost;
241    private AppsCustomizePagedView mAppsCustomizeContent;
242    private boolean mAutoAdvanceRunning = false;
243
244    private Bundle mSavedState;
245    // We set the state in both onCreate and then onNewIntent in some cases, which causes both
246    // scroll issues (because the workspace may not have been measured yet) and extra work.
247    // Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
248    private State mOnResumeState = State.NONE;
249
250    private SpannableStringBuilder mDefaultKeySsb = null;
251
252    private boolean mWorkspaceLoading = true;
253
254    private boolean mPaused = true;
255    private boolean mRestoring;
256    private boolean mWaitingForResult;
257    private boolean mOnResumeNeedsLoad;
258
259    private ArrayList<Runnable> mBindOnResumeCallbacks = new ArrayList<Runnable>();
260    private ArrayList<Runnable> mOnResumeCallbacks = new ArrayList<Runnable>();
261
262    // Keep track of whether the user has left launcher
263    private static boolean sPausedFromUserAction = false;
264
265    private Bundle mSavedInstanceState;
266
267    private LauncherModel mModel;
268    private IconCache mIconCache;
269    private boolean mUserPresent = true;
270    private boolean mVisible = false;
271    private boolean mAttached = false;
272    private static final boolean DISABLE_CLINGS = true;
273
274    private static LocaleConfiguration sLocaleConfiguration = null;
275
276    private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
277
278    private Intent mAppMarketIntent = null;
279
280    // Related to the auto-advancing of widgets
281    private final int ADVANCE_MSG = 1;
282    private final int mAdvanceInterval = 20000;
283    private final int mAdvanceStagger = 250;
284    private long mAutoAdvanceSentTime;
285    private long mAutoAdvanceTimeLeft = -1;
286    private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
287        new HashMap<View, AppWidgetProviderInfo>();
288
289    // Determines how long to wait after a rotation before restoring the screen orientation to
290    // match the sensor state.
291    private final int mRestoreScreenOrientationDelay = 500;
292
293    // External icons saved in case of resource changes, orientation, etc.
294    private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2];
295    private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2];
296    private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2];
297
298    private Drawable mWorkspaceBackgroundDrawable;
299
300    private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
301
302    static final ArrayList<String> sDumpLogs = new ArrayList<String>();
303
304    // We only want to get the SharedPreferences once since it does an FS stat each time we get
305    // it from the context.
306    private SharedPreferences mSharedPrefs;
307
308    private static ArrayList<ComponentName> mIntentsOnWorkspaceFromUpgradePath = null;
309
310    // Holds the page that we need to animate to, and the icon views that we need to animate up
311    // when we scroll to that page on resume.
312    private ImageView mFolderIconImageView;
313    private Bitmap mFolderIconBitmap;
314    private Canvas mFolderIconCanvas;
315    private Rect mRectForFolderAnimation = new Rect();
316
317    private BubbleTextView mWaitingForResume;
318
319    private HideFromAccessibilityHelper mHideFromAccessibilityHelper
320        = new HideFromAccessibilityHelper();
321
322    private Runnable mBuildLayersRunnable = new Runnable() {
323        public void run() {
324            if (mWorkspace != null) {
325                mWorkspace.buildPageHardwareLayers();
326            }
327        }
328    };
329
330    private static ArrayList<PendingAddArguments> sPendingAddList
331            = new ArrayList<PendingAddArguments>();
332
333    private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
334
335    private static class PendingAddArguments {
336        int requestCode;
337        Intent intent;
338        long container;
339        long screenId;
340        int cellX;
341        int cellY;
342    }
343
344    private Stats mStats;
345
346    private static boolean isPropertyEnabled(String propertyName) {
347        return Log.isLoggable(propertyName, Log.VERBOSE);
348    }
349
350    @Override
351    protected void onCreate(Bundle savedInstanceState) {
352        if (DEBUG_STRICT_MODE) {
353            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
354                    .detectDiskReads()
355                    .detectDiskWrites()
356                    .detectNetwork()   // or .detectAll() for all detectable problems
357                    .penaltyLog()
358                    .build());
359            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
360                    .detectLeakedSqlLiteObjects()
361                    .detectLeakedClosableObjects()
362                    .penaltyLog()
363                    .penaltyDeath()
364                    .build());
365        }
366
367        super.onCreate(savedInstanceState);
368
369        LauncherAppState.setApplicationContext(getApplicationContext());
370        LauncherAppState app = LauncherAppState.getInstance();
371
372        // Determine the dynamic grid properties
373        Point smallestSize = new Point();
374        Point largestSize = new Point();
375        Point realSize = new Point();
376        Display display = getWindowManager().getDefaultDisplay();
377        display.getCurrentSizeRange(smallestSize, largestSize);
378        display.getRealSize(realSize);
379        // Lazy-initialize the dynamic grid
380        DeviceProfile grid = app.initDynamicGrid(this,
381                Math.min(smallestSize.x, smallestSize.y),
382                Math.min(largestSize.x, largestSize.y),
383                realSize.x, realSize.y);
384
385        // the LauncherApplication should call this, but in case of Instrumentation it might not be present yet
386        mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
387                Context.MODE_PRIVATE);
388        mModel = app.setLauncher(this);
389        mIconCache = app.getIconCache();
390        mDragController = new DragController(this);
391        mInflater = getLayoutInflater();
392
393        mStats = new Stats(this);
394
395        mAppWidgetManager = AppWidgetManager.getInstance(this);
396        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
397        mAppWidgetHost.startListening();
398
399        // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
400        // this also ensures that any synchronous binding below doesn't re-trigger another
401        // LauncherModel load.
402        mPaused = false;
403
404        if (PROFILE_STARTUP) {
405            android.os.Debug.startMethodTracing(
406                    Environment.getExternalStorageDirectory() + "/launcher");
407        }
408
409        checkForLocaleChange();
410        setContentView(R.layout.launcher);
411        grid.layout(this);
412        setupViews();
413        showFirstRunWorkspaceCling();
414
415        registerContentObservers();
416
417        lockAllApps();
418
419        mSavedState = savedInstanceState;
420        restoreState(mSavedState);
421
422        // Update customization drawer _after_ restoring the states
423        if (mAppsCustomizeContent != null) {
424            mAppsCustomizeContent.onPackagesUpdated(
425                LauncherModel.getSortedWidgetsAndShortcuts(this));
426        }
427
428        if (PROFILE_STARTUP) {
429            android.os.Debug.stopMethodTracing();
430        }
431
432        if (!mRestoring) {
433            if (sPausedFromUserAction) {
434                // If the user leaves launcher, then we should just load items asynchronously when
435                // they return.
436                mModel.startLoader(true, -1);
437            } else {
438                // We only load the page synchronously if the user rotates (or triggers a
439                // configuration change) while launcher is in the foreground
440                mModel.startLoader(true, mWorkspace.getCurrentPage());
441            }
442        }
443
444        // For handling default keys
445        mDefaultKeySsb = new SpannableStringBuilder();
446        Selection.setSelection(mDefaultKeySsb, 0);
447
448        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
449        registerReceiver(mCloseSystemDialogsReceiver, filter);
450
451        updateGlobalIcons();
452
453        // On large interfaces, we want the screen to auto-rotate based on the current orientation
454        unlockScreenOrientation(true);
455    }
456
457    protected void onUserLeaveHint() {
458        super.onUserLeaveHint();
459        sPausedFromUserAction = true;
460    }
461
462    /** To be overriden by subclasses to hint to Launcher that we have custom content */
463    protected boolean hasCustomContentToLeft() {
464        return false;
465    }
466
467    private void updateGlobalIcons() {
468        boolean searchVisible = false;
469        boolean voiceVisible = false;
470        // If we have a saved version of these external icons, we load them up immediately
471        int coi = getCurrentOrientationIndexForGlobalIcons();
472        if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null ||
473                sAppMarketIcon[coi] == null) {
474            updateAppMarketIcon();
475            searchVisible = updateGlobalSearchIcon();
476            voiceVisible = updateVoiceSearchIcon(searchVisible);
477        }
478        if (sGlobalSearchIcon[coi] != null) {
479             updateGlobalSearchIcon(sGlobalSearchIcon[coi]);
480             searchVisible = true;
481        }
482        if (sVoiceSearchIcon[coi] != null) {
483            updateVoiceSearchIcon(sVoiceSearchIcon[coi]);
484            voiceVisible = true;
485        }
486        if (sAppMarketIcon[coi] != null) {
487            updateAppMarketIcon(sAppMarketIcon[coi]);
488        }
489        if (mSearchDropTargetBar != null) {
490            mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
491        }
492    }
493
494    private void checkForLocaleChange() {
495        if (sLocaleConfiguration == null) {
496            new AsyncTask<Void, Void, LocaleConfiguration>() {
497                @Override
498                protected LocaleConfiguration doInBackground(Void... unused) {
499                    LocaleConfiguration localeConfiguration = new LocaleConfiguration();
500                    readConfiguration(Launcher.this, localeConfiguration);
501                    return localeConfiguration;
502                }
503
504                @Override
505                protected void onPostExecute(LocaleConfiguration result) {
506                    sLocaleConfiguration = result;
507                    checkForLocaleChange();  // recursive, but now with a locale configuration
508                }
509            }.execute();
510            return;
511        }
512
513        final Configuration configuration = getResources().getConfiguration();
514
515        final String previousLocale = sLocaleConfiguration.locale;
516        final String locale = configuration.locale.toString();
517
518        final int previousMcc = sLocaleConfiguration.mcc;
519        final int mcc = configuration.mcc;
520
521        final int previousMnc = sLocaleConfiguration.mnc;
522        final int mnc = configuration.mnc;
523
524        boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
525
526        if (localeChanged) {
527            sLocaleConfiguration.locale = locale;
528            sLocaleConfiguration.mcc = mcc;
529            sLocaleConfiguration.mnc = mnc;
530
531            mIconCache.flush();
532
533            final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
534            new Thread("WriteLocaleConfiguration") {
535                @Override
536                public void run() {
537                    writeConfiguration(Launcher.this, localeConfiguration);
538                }
539            }.start();
540        }
541    }
542
543    private static class LocaleConfiguration {
544        public String locale;
545        public int mcc = -1;
546        public int mnc = -1;
547    }
548
549    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
550        DataInputStream in = null;
551        try {
552            in = new DataInputStream(context.openFileInput(PREFERENCES));
553            configuration.locale = in.readUTF();
554            configuration.mcc = in.readInt();
555            configuration.mnc = in.readInt();
556        } catch (FileNotFoundException e) {
557            // Ignore
558        } catch (IOException e) {
559            // Ignore
560        } finally {
561            if (in != null) {
562                try {
563                    in.close();
564                } catch (IOException e) {
565                    // Ignore
566                }
567            }
568        }
569    }
570
571    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
572        DataOutputStream out = null;
573        try {
574            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
575            out.writeUTF(configuration.locale);
576            out.writeInt(configuration.mcc);
577            out.writeInt(configuration.mnc);
578            out.flush();
579        } catch (FileNotFoundException e) {
580            // Ignore
581        } catch (IOException e) {
582            //noinspection ResultOfMethodCallIgnored
583            context.getFileStreamPath(PREFERENCES).delete();
584        } finally {
585            if (out != null) {
586                try {
587                    out.close();
588                } catch (IOException e) {
589                    // Ignore
590                }
591            }
592        }
593    }
594
595    public LayoutInflater getInflater() {
596        return mInflater;
597    }
598
599    public DragLayer getDragLayer() {
600        return mDragLayer;
601    }
602
603    boolean isDraggingEnabled() {
604        // We prevent dragging when we are loading the workspace as it is possible to pick up a view
605        // that is subsequently removed from the workspace in startBinding().
606        return !mModel.isLoadingWorkspace();
607    }
608
609    static int getScreen() {
610        synchronized (sLock) {
611            return sScreen;
612        }
613    }
614
615    static void setScreen(int screen) {
616        synchronized (sLock) {
617            sScreen = screen;
618        }
619    }
620
621    /**
622     * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
623     * a configuration step, this allows the proper animations to run after other transitions.
624     */
625    private boolean completeAdd(PendingAddArguments args) {
626        boolean result = false;
627        switch (args.requestCode) {
628            case REQUEST_PICK_APPLICATION:
629                completeAddApplication(args.intent, args.container, args.screenId, args.cellX,
630                        args.cellY);
631                break;
632            case REQUEST_PICK_SHORTCUT:
633                processShortcut(args.intent);
634                break;
635            case REQUEST_CREATE_SHORTCUT:
636                completeAddShortcut(args.intent, args.container, args.screenId, args.cellX,
637                        args.cellY);
638                result = true;
639                break;
640            case REQUEST_CREATE_APPWIDGET:
641                int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
642                completeAddAppWidget(appWidgetId, args.container, args.screenId, null, null);
643                result = true;
644                break;
645            case REQUEST_PICK_WALLPAPER:
646                // We just wanted the activity result here so we can clear mWaitingForResult
647                break;
648        }
649        // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
650        // if you turned the screen off and then back while in All Apps, Launcher would not
651        // return to the workspace. Clearing mAddInfo.container here fixes this issue
652        resetAddInfo();
653        return result;
654    }
655
656    @Override
657    protected void onActivityResult(
658            final int requestCode, final int resultCode, final Intent data) {
659        // Reset the startActivity waiting flag
660        mWaitingForResult = false;
661
662        if (requestCode == REQUEST_BIND_APPWIDGET) {
663            int appWidgetId = data != null ?
664                    data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
665            if (resultCode == RESULT_CANCELED) {
666                completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
667            } else if (resultCode == RESULT_OK) {
668                addAppWidgetImpl(appWidgetId, mPendingAddInfo, null, mPendingAddWidgetInfo);
669            }
670            return;
671        }
672        boolean delayExitSpringLoadedMode = false;
673        boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
674                requestCode == REQUEST_CREATE_APPWIDGET);
675
676        // We have special handling for widgets
677        if (isWidgetDrop) {
678            int appWidgetId = data != null ?
679                    data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
680            if (appWidgetId < 0) {
681                Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not returned from the \\" +
682                        "widget configuration activity.");
683                completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
684            } else {
685                completeTwoStageWidgetDrop(resultCode, appWidgetId);
686            }
687            return;
688        }
689
690        // The pattern used here is that a user PICKs a specific application,
691        // which, depending on the target, might need to CREATE the actual target.
692
693        // For example, the user would PICK_SHORTCUT for "Music playlist", and we
694        // launch over to the Music app to actually CREATE_SHORTCUT.
695        if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
696            final PendingAddArguments args = new PendingAddArguments();
697            args.requestCode = requestCode;
698            args.intent = data;
699            args.container = mPendingAddInfo.container;
700            args.screenId = mPendingAddInfo.screenId;
701            args.cellX = mPendingAddInfo.cellX;
702            args.cellY = mPendingAddInfo.cellY;
703            if (isWorkspaceLocked()) {
704                sPendingAddList.add(args);
705            } else {
706                delayExitSpringLoadedMode = completeAdd(args);
707            }
708        }
709        mDragLayer.clearAnimatedView();
710        // Exit spring loaded mode if necessary after cancelling the configuration of a widget
711        exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode,
712                null);
713    }
714
715    private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
716        CellLayout cellLayout =
717                (CellLayout) mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
718        Runnable onCompleteRunnable = null;
719        int animationType = 0;
720
721        AppWidgetHostView boundWidget = null;
722        if (resultCode == RESULT_OK) {
723            animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
724            final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
725                    mPendingAddWidgetInfo);
726            boundWidget = layout;
727            onCompleteRunnable = new Runnable() {
728                @Override
729                public void run() {
730                    completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
731                            mPendingAddInfo.screenId, layout, null);
732                    exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
733                            null);
734                }
735            };
736        } else if (resultCode == RESULT_CANCELED) {
737            animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
738            onCompleteRunnable = new Runnable() {
739                @Override
740                public void run() {
741                    exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
742                            null);
743                }
744            };
745        }
746        if (mDragLayer.getAnimatedView() != null) {
747            mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
748                    (DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
749                    animationType, boundWidget, true);
750        } else {
751            // The animated view may be null in the case of a rotation during widget configuration
752            onCompleteRunnable.run();
753        }
754    }
755
756    @Override
757    protected void onStop() {
758        super.onStop();
759        FirstFrameAnimatorHelper.setIsVisible(false);
760    }
761
762    @Override
763    protected void onStart() {
764        super.onStart();
765        FirstFrameAnimatorHelper.setIsVisible(true);
766    }
767
768    @Override
769    protected void onResume() {
770        long startTime = 0;
771        if (DEBUG_RESUME_TIME) {
772            startTime = System.currentTimeMillis();
773            Log.v(TAG, "Launcher.onResume()");
774        }
775        super.onResume();
776
777        // Restore the previous launcher state
778        if (mOnResumeState == State.WORKSPACE) {
779            showWorkspace(false);
780        } else if (mOnResumeState == State.APPS_CUSTOMIZE) {
781            showAllApps(false);
782        }
783        mOnResumeState = State.NONE;
784
785        // Background was set to gradient in onPause(), restore to black if in all apps.
786        setWorkspaceBackground(mState == State.WORKSPACE);
787
788        // Process any items that were added while Launcher was away
789        InstallShortcutReceiver.disableAndFlushInstallQueue(this);
790
791        mPaused = false;
792        sPausedFromUserAction = false;
793        if (mRestoring || mOnResumeNeedsLoad) {
794            mWorkspaceLoading = true;
795            mModel.startLoader(true, -1);
796            mRestoring = false;
797            mOnResumeNeedsLoad = false;
798        }
799        if (mBindOnResumeCallbacks.size() > 0) {
800            // We might have postponed some bind calls until onResume (see waitUntilResume) --
801            // execute them here
802            long startTimeCallbacks = 0;
803            if (DEBUG_RESUME_TIME) {
804                startTimeCallbacks = System.currentTimeMillis();
805            }
806
807            if (mAppsCustomizeContent != null) {
808                mAppsCustomizeContent.setBulkBind(true);
809            }
810            for (int i = 0; i < mBindOnResumeCallbacks.size(); i++) {
811                mBindOnResumeCallbacks.get(i).run();
812            }
813            if (mAppsCustomizeContent != null) {
814                mAppsCustomizeContent.setBulkBind(false);
815            }
816            mBindOnResumeCallbacks.clear();
817            if (DEBUG_RESUME_TIME) {
818                Log.d(TAG, "Time spent processing callbacks in onResume: " +
819                    (System.currentTimeMillis() - startTimeCallbacks));
820            }
821        }
822        if (mOnResumeCallbacks.size() > 0) {
823            for (int i = 0; i < mOnResumeCallbacks.size(); i++) {
824                mOnResumeCallbacks.get(i).run();
825            }
826            mOnResumeCallbacks.clear();
827        }
828
829        // Reset the pressed state of icons that were locked in the press state while activities
830        // were launching
831        if (mWaitingForResume != null) {
832            // Resets the previous workspace icon press state
833            mWaitingForResume.setStayPressed(false);
834        }
835        if (mAppsCustomizeContent != null) {
836            // Resets the previous all apps icon press state
837            mAppsCustomizeContent.resetDrawableState();
838        }
839        // It is possible that widgets can receive updates while launcher is not in the foreground.
840        // Consequently, the widgets will be inflated in the orientation of the foreground activity
841        // (framework issue). On resuming, we ensure that any widgets are inflated for the current
842        // orientation.
843        getWorkspace().reinflateWidgetsIfNecessary();
844
845        // Again, as with the above scenario, it's possible that one or more of the global icons
846        // were updated in the wrong orientation.
847        updateGlobalIcons();
848        if (DEBUG_RESUME_TIME) {
849            Log.d(TAG, "Time spent in onResume: " + (System.currentTimeMillis() - startTime));
850        }
851    }
852
853    @Override
854    protected void onPause() {
855        // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
856        // to be consistent.  So re-enable the flag here, and we will re-disable it as necessary
857        // when Launcher resumes and we are still in AllApps.
858        updateWallpaperVisibility(true);
859
860        // Ensure that items added to Launcher are queued until Launcher returns
861        InstallShortcutReceiver.enableInstallQueue();
862
863        super.onPause();
864        mPaused = true;
865        mDragController.cancelDrag();
866        mDragController.resetLastGestureUpTime();
867    }
868
869    protected void onFinishBindingItems() {
870    }
871
872    QSBScroller mQsbScroller = new QSBScroller() {
873        int scrollY = 0;
874
875        @Override
876        public void setScrollY(int scroll) {
877            scrollY = scroll;
878
879            if (mWorkspace.isOnOrMovingToCustomContent()) {
880                mSearchDropTargetBar.setTranslationY(- scrollY);
881            }
882        }
883    };
884
885    public void resetQSBScroll() {
886        mSearchDropTargetBar.animate().translationY(0).start();
887    }
888
889    public interface CustomContentCallbacks {
890        // Custom content is completely shown
891        public void onShow();
892
893        // Custom content is completely hidden
894        public void onHide();
895    }
896
897    public interface QSBScroller {
898        public void setScrollY(int scrollY);
899    }
900
901    // Add a fullscreen unpadded view to the workspace to the left all other screens.
902    public QSBScroller addToCustomContentPage(View customContent) {
903        return addToCustomContentPage(customContent, null);
904    }
905
906    public QSBScroller addToCustomContentPage(View customContent,
907            CustomContentCallbacks callbacks) {
908        mWorkspace.addToCustomContentPage(customContent, callbacks);
909        return mQsbScroller;
910    }
911
912    // The custom content needs to offset its content to account for the QSB
913    public int getTopOffsetForCustomContent() {
914        return mWorkspace.getPaddingTop();
915    }
916
917    @Override
918    public Object onRetainNonConfigurationInstance() {
919        // Flag the loader to stop early before switching
920        mModel.stopLoader();
921        if (mAppsCustomizeContent != null) {
922            mAppsCustomizeContent.surrender();
923        }
924        return Boolean.TRUE;
925    }
926
927    // We can't hide the IME if it was forced open.  So don't bother
928    /*
929    @Override
930    public void onWindowFocusChanged(boolean hasFocus) {
931        super.onWindowFocusChanged(hasFocus);
932
933        if (hasFocus) {
934            final InputMethodManager inputManager = (InputMethodManager)
935                    getSystemService(Context.INPUT_METHOD_SERVICE);
936            WindowManager.LayoutParams lp = getWindow().getAttributes();
937            inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
938                        android.os.Handler()) {
939                        protected void onReceiveResult(int resultCode, Bundle resultData) {
940                            Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
941                        }
942                    });
943            Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
944        }
945    }
946    */
947
948    private boolean acceptFilter() {
949        final InputMethodManager inputManager = (InputMethodManager)
950                getSystemService(Context.INPUT_METHOD_SERVICE);
951        return !inputManager.isFullscreenMode();
952    }
953
954    @Override
955    public boolean onKeyDown(int keyCode, KeyEvent event) {
956        final int uniChar = event.getUnicodeChar();
957        final boolean handled = super.onKeyDown(keyCode, event);
958        final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
959        if (!handled && acceptFilter() && isKeyNotWhitespace) {
960            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
961                    keyCode, event);
962            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
963                // something usable has been typed - start a search
964                // the typed text will be retrieved and cleared by
965                // showSearchDialog()
966                // If there are multiple keystrokes before the search dialog takes focus,
967                // onSearchRequested() will be called for every keystroke,
968                // but it is idempotent, so it's fine.
969                return onSearchRequested();
970            }
971        }
972
973        // Eat the long press event so the keyboard doesn't come up.
974        if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
975            return true;
976        }
977
978        return handled;
979    }
980
981    private String getTypedText() {
982        return mDefaultKeySsb.toString();
983    }
984
985    private void clearTypedText() {
986        mDefaultKeySsb.clear();
987        mDefaultKeySsb.clearSpans();
988        Selection.setSelection(mDefaultKeySsb, 0);
989    }
990
991    /**
992     * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
993     * State
994     */
995    private static State intToState(int stateOrdinal) {
996        State state = State.WORKSPACE;
997        final State[] stateValues = State.values();
998        for (int i = 0; i < stateValues.length; i++) {
999            if (stateValues[i].ordinal() == stateOrdinal) {
1000                state = stateValues[i];
1001                break;
1002            }
1003        }
1004        return state;
1005    }
1006
1007    /**
1008     * Restores the previous state, if it exists.
1009     *
1010     * @param savedState The previous state.
1011     */
1012    private void restoreState(Bundle savedState) {
1013        if (savedState == null) {
1014            return;
1015        }
1016
1017        State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
1018        if (state == State.APPS_CUSTOMIZE) {
1019            mOnResumeState = State.APPS_CUSTOMIZE;
1020        }
1021
1022        int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
1023        if (currentScreen > -1) {
1024            mWorkspace.setRestorePage(currentScreen);
1025        }
1026
1027        final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
1028        final long pendingAddScreen = savedState.getLong(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
1029
1030        if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
1031            mPendingAddInfo.container = pendingAddContainer;
1032            mPendingAddInfo.screenId = pendingAddScreen;
1033            mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
1034            mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
1035            mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
1036            mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
1037            mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
1038            mWaitingForResult = true;
1039            mRestoring = true;
1040        }
1041
1042        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
1043        if (renameFolder) {
1044            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
1045            mFolderInfo = mModel.getFolderById(this, sFolders, id);
1046            mRestoring = true;
1047        }
1048
1049        // Restore the AppsCustomize tab
1050        if (mAppsCustomizeTabHost != null) {
1051            String curTab = savedState.getString("apps_customize_currentTab");
1052            if (curTab != null) {
1053                mAppsCustomizeTabHost.setContentTypeImmediate(
1054                        mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
1055                mAppsCustomizeContent.loadAssociatedPages(
1056                        mAppsCustomizeContent.getCurrentPage());
1057            }
1058
1059            int currentIndex = savedState.getInt("apps_customize_currentIndex");
1060            mAppsCustomizeContent.restorePageForIndex(currentIndex);
1061        }
1062    }
1063
1064    /**
1065     * Finds all the views we need and configure them properly.
1066     */
1067    private void setupViews() {
1068        final DragController dragController = mDragController;
1069
1070        mLauncherView = findViewById(R.id.launcher);
1071        mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
1072        mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
1073
1074        mLauncherView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1075        mWorkspaceBackgroundDrawable = getResources().getDrawable(R.drawable.workspace_bg);
1076
1077        // Setup the drag layer
1078        mDragLayer.setup(this, dragController);
1079
1080        // Setup the hotseat
1081        mHotseat = (Hotseat) findViewById(R.id.hotseat);
1082        if (mHotseat != null) {
1083            mHotseat.setup(this);
1084        }
1085
1086        mOverviewPanel = findViewById(R.id.overview_panel);
1087        findViewById(R.id.widget_button).setOnClickListener(new OnClickListener() {
1088            @Override
1089            public void onClick(View arg0) {
1090                showAllApps(true);
1091            }
1092        });
1093        findViewById(R.id.wallpaper_button).setOnClickListener(new OnClickListener() {
1094            @Override
1095            public void onClick(View arg0) {
1096                startWallpaper();
1097            }
1098        });
1099
1100        // Setup the workspace
1101        mWorkspace.setHapticFeedbackEnabled(false);
1102        mWorkspace.setOnLongClickListener(this);
1103        mWorkspace.setup(dragController);
1104        dragController.addDragListener(mWorkspace);
1105
1106        // Get the search/delete bar
1107        mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
1108
1109        // Setup AppsCustomize
1110        mAppsCustomizeTabHost = (AppsCustomizeTabHost) findViewById(R.id.apps_customize_pane);
1111        mAppsCustomizeContent = (AppsCustomizePagedView)
1112                mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
1113        mAppsCustomizeContent.setup(this, dragController);
1114
1115        // Setup the drag controller (drop targets have to be added in reverse order in priority)
1116        dragController.setDragScoller(mWorkspace);
1117        dragController.setScrollView(mDragLayer);
1118        dragController.setMoveTarget(mWorkspace);
1119        dragController.addDropTarget(mWorkspace);
1120        if (mSearchDropTargetBar != null) {
1121            mSearchDropTargetBar.setup(this, dragController);
1122        }
1123
1124        if (getResources().getBoolean(R.bool.debug_memory_enabled)) {
1125            Log.v(TAG, "adding WeightWatcher");
1126            mWeightWatcher = new WeightWatcher(this);
1127            mWeightWatcher.setAlpha(0.5f);
1128            ((FrameLayout) mLauncherView).addView(mWeightWatcher,
1129                    new FrameLayout.LayoutParams(
1130                            FrameLayout.LayoutParams.MATCH_PARENT,
1131                            FrameLayout.LayoutParams.WRAP_CONTENT,
1132                            Gravity.BOTTOM)
1133            );
1134
1135            boolean show = shouldShowWeightWatcher();
1136            mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
1137        }
1138    }
1139
1140    /**
1141     * Creates a view representing a shortcut.
1142     *
1143     * @param info The data structure describing the shortcut.
1144     *
1145     * @return A View inflated from R.layout.application.
1146     */
1147    View createShortcut(ShortcutInfo info) {
1148        return createShortcut(R.layout.application,
1149                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
1150    }
1151
1152    /**
1153     * Creates a view representing a shortcut inflated from the specified resource.
1154     *
1155     * @param layoutResId The id of the XML layout used to create the shortcut.
1156     * @param parent The group the shortcut belongs to.
1157     * @param info The data structure describing the shortcut.
1158     *
1159     * @return A View inflated from layoutResId.
1160     */
1161    View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
1162        BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
1163        favorite.applyFromShortcutInfo(info, mIconCache);
1164        favorite.setOnClickListener(this);
1165        return favorite;
1166    }
1167
1168    /**
1169     * Add an application shortcut to the workspace.
1170     *
1171     * @param data The intent describing the application.
1172     * @param cellInfo The position on screen where to create the shortcut.
1173     */
1174    void completeAddApplication(Intent data, long container, long screenId, int cellX, int cellY) {
1175        final int[] cellXY = mTmpAddItemCellCoordinates;
1176        final CellLayout layout = getCellLayout(container, screenId);
1177
1178        // First we check if we already know the exact location where we want to add this item.
1179        if (cellX >= 0 && cellY >= 0) {
1180            cellXY[0] = cellX;
1181            cellXY[1] = cellY;
1182        } else if (!layout.findCellForSpan(cellXY, 1, 1)) {
1183            showOutOfSpaceMessage(isHotseatLayout(layout));
1184            return;
1185        }
1186
1187        final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
1188
1189        if (info != null) {
1190            info.setActivity(this, data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
1191                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1192            info.container = ItemInfo.NO_ID;
1193            mWorkspace.addApplicationShortcut(info, layout, container, screenId, cellXY[0], cellXY[1],
1194                    isWorkspaceLocked(), cellX, cellY);
1195        } else {
1196            Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
1197        }
1198    }
1199
1200    /**
1201     * Add a shortcut to the workspace.
1202     *
1203     * @param data The intent describing the shortcut.
1204     * @param cellInfo The position on screen where to create the shortcut.
1205     */
1206    private void completeAddShortcut(Intent data, long container, long screenId, int cellX,
1207            int cellY) {
1208        int[] cellXY = mTmpAddItemCellCoordinates;
1209        int[] touchXY = mPendingAddInfo.dropPos;
1210        CellLayout layout = getCellLayout(container, screenId);
1211
1212        boolean foundCellSpan = false;
1213
1214        ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null);
1215        if (info == null) {
1216            return;
1217        }
1218        final View view = createShortcut(info);
1219
1220        // First we check if we already know the exact location where we want to add this item.
1221        if (cellX >= 0 && cellY >= 0) {
1222            cellXY[0] = cellX;
1223            cellXY[1] = cellY;
1224            foundCellSpan = true;
1225
1226            // If appropriate, either create a folder or add to an existing folder
1227            if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
1228                    true, null,null)) {
1229                return;
1230            }
1231            DragObject dragObject = new DragObject();
1232            dragObject.dragInfo = info;
1233            if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
1234                    true)) {
1235                return;
1236            }
1237        } else if (touchXY != null) {
1238            // when dragging and dropping, just find the closest free spot
1239            int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
1240            foundCellSpan = (result != null);
1241        } else {
1242            foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
1243        }
1244
1245        if (!foundCellSpan) {
1246            showOutOfSpaceMessage(isHotseatLayout(layout));
1247            return;
1248        }
1249
1250        LauncherModel.addItemToDatabase(this, info, container, screenId, cellXY[0], cellXY[1], false);
1251
1252        if (!mRestoring) {
1253            mWorkspace.addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1,
1254                    isWorkspaceLocked());
1255        }
1256    }
1257
1258    static int[] getSpanForWidget(Context context, ComponentName component, int minWidth,
1259            int minHeight) {
1260        Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, component, null);
1261        // We want to account for the extra amount of padding that we are adding to the widget
1262        // to ensure that it gets the full amount of space that it has requested
1263        int requiredWidth = minWidth + padding.left + padding.right;
1264        int requiredHeight = minHeight + padding.top + padding.bottom;
1265        return CellLayout.rectToCell(requiredWidth, requiredHeight, null);
1266    }
1267
1268    static int[] getSpanForWidget(Context context, AppWidgetProviderInfo info) {
1269        return getSpanForWidget(context, info.provider, info.minWidth, info.minHeight);
1270    }
1271
1272    static int[] getMinSpanForWidget(Context context, AppWidgetProviderInfo info) {
1273        return getSpanForWidget(context, info.provider, info.minResizeWidth, info.minResizeHeight);
1274    }
1275
1276    static int[] getSpanForWidget(Context context, PendingAddWidgetInfo info) {
1277        return getSpanForWidget(context, info.componentName, info.minWidth, info.minHeight);
1278    }
1279
1280    static int[] getMinSpanForWidget(Context context, PendingAddWidgetInfo info) {
1281        return getSpanForWidget(context, info.componentName, info.minResizeWidth,
1282                info.minResizeHeight);
1283    }
1284
1285    /**
1286     * Add a widget to the workspace.
1287     *
1288     * @param appWidgetId The app widget id
1289     * @param cellInfo The position on screen where to create the widget.
1290     */
1291    private void completeAddAppWidget(final int appWidgetId, long container, long screenId,
1292            AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) {
1293        if (appWidgetInfo == null) {
1294            appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1295        }
1296
1297        // Calculate the grid spans needed to fit this widget
1298        CellLayout layout = getCellLayout(container, screenId);
1299
1300        int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo);
1301        int[] spanXY = getSpanForWidget(this, appWidgetInfo);
1302
1303        // Try finding open space on Launcher screen
1304        // We have saved the position to which the widget was dragged-- this really only matters
1305        // if we are placing widgets on a "spring-loaded" screen
1306        int[] cellXY = mTmpAddItemCellCoordinates;
1307        int[] touchXY = mPendingAddInfo.dropPos;
1308        int[] finalSpan = new int[2];
1309        boolean foundCellSpan = false;
1310        if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
1311            cellXY[0] = mPendingAddInfo.cellX;
1312            cellXY[1] = mPendingAddInfo.cellY;
1313            spanXY[0] = mPendingAddInfo.spanX;
1314            spanXY[1] = mPendingAddInfo.spanY;
1315            foundCellSpan = true;
1316        } else if (touchXY != null) {
1317            // when dragging and dropping, just find the closest free spot
1318            int[] result = layout.findNearestVacantArea(
1319                    touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0],
1320                    spanXY[1], cellXY, finalSpan);
1321            spanXY[0] = finalSpan[0];
1322            spanXY[1] = finalSpan[1];
1323            foundCellSpan = (result != null);
1324        } else {
1325            foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]);
1326        }
1327
1328        if (!foundCellSpan) {
1329            if (appWidgetId != -1) {
1330                // Deleting an app widget ID is a void call but writes to disk before returning
1331                // to the caller...
1332                new Thread("deleteAppWidgetId") {
1333                    public void run() {
1334                        mAppWidgetHost.deleteAppWidgetId(appWidgetId);
1335                    }
1336                }.start();
1337            }
1338            showOutOfSpaceMessage(isHotseatLayout(layout));
1339            return;
1340        }
1341
1342        // Build Launcher-specific widget info and save to database
1343        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId,
1344                appWidgetInfo.provider);
1345        launcherInfo.spanX = spanXY[0];
1346        launcherInfo.spanY = spanXY[1];
1347        launcherInfo.minSpanX = mPendingAddInfo.minSpanX;
1348        launcherInfo.minSpanY = mPendingAddInfo.minSpanY;
1349
1350        LauncherModel.addItemToDatabase(this, launcherInfo,
1351                container, screenId, cellXY[0], cellXY[1], false);
1352
1353        if (!mRestoring) {
1354            if (hostView == null) {
1355                // Perform actual inflation because we're live
1356                launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1357                launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1358            } else {
1359                // The AppWidgetHostView has already been inflated and instantiated
1360                launcherInfo.hostView = hostView;
1361            }
1362
1363            launcherInfo.hostView.setTag(launcherInfo);
1364            launcherInfo.hostView.setVisibility(View.VISIBLE);
1365            launcherInfo.notifyWidgetSizeChanged(this);
1366
1367            mWorkspace.addInScreen(launcherInfo.hostView, container, screenId, cellXY[0], cellXY[1],
1368                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1369
1370            addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1371        }
1372        resetAddInfo();
1373    }
1374
1375    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1376        @Override
1377        public void onReceive(Context context, Intent intent) {
1378            final String action = intent.getAction();
1379            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1380                mUserPresent = false;
1381                mDragLayer.clearAllResizeFrames();
1382                updateRunning();
1383
1384                // Reset AllApps to its initial state only if we are not in the middle of
1385                // processing a multi-step drop
1386                if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
1387                    mAppsCustomizeTabHost.reset();
1388                    showWorkspace(false);
1389                }
1390            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1391                mUserPresent = true;
1392                updateRunning();
1393            }
1394        }
1395    };
1396
1397    @Override
1398    public void onAttachedToWindow() {
1399        super.onAttachedToWindow();
1400
1401        // Listen for broadcasts related to user-presence
1402        final IntentFilter filter = new IntentFilter();
1403        filter.addAction(Intent.ACTION_SCREEN_OFF);
1404        filter.addAction(Intent.ACTION_USER_PRESENT);
1405        registerReceiver(mReceiver, filter);
1406        FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView());
1407        mAttached = true;
1408        mVisible = true;
1409    }
1410
1411    @Override
1412    public void onDetachedFromWindow() {
1413        super.onDetachedFromWindow();
1414        mVisible = false;
1415
1416        if (mAttached) {
1417            unregisterReceiver(mReceiver);
1418            mAttached = false;
1419        }
1420        updateRunning();
1421    }
1422
1423    public void onWindowVisibilityChanged(int visibility) {
1424        mVisible = visibility == View.VISIBLE;
1425        updateRunning();
1426        // The following code used to be in onResume, but it turns out onResume is called when
1427        // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
1428        // is a more appropriate event to handle
1429        if (mVisible) {
1430            mAppsCustomizeTabHost.onWindowVisible();
1431            if (!mWorkspaceLoading) {
1432                final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
1433                // We want to let Launcher draw itself at least once before we force it to build
1434                // layers on all the workspace pages, so that transitioning to Launcher from other
1435                // apps is nice and speedy.
1436                observer.addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
1437                    private boolean mStarted = false;
1438                    public void onDraw() {
1439                        if (mStarted) return;
1440                        mStarted = true;
1441                        // We delay the layer building a bit in order to give
1442                        // other message processing a time to run.  In particular
1443                        // this avoids a delay in hiding the IME if it was
1444                        // currently shown, because doing that may involve
1445                        // some communication back with the app.
1446                        mWorkspace.postDelayed(mBuildLayersRunnable, 500);
1447                        final ViewTreeObserver.OnDrawListener listener = this;
1448                        mWorkspace.post(new Runnable() {
1449                                public void run() {
1450                                    if (mWorkspace != null &&
1451                                            mWorkspace.getViewTreeObserver() != null) {
1452                                        mWorkspace.getViewTreeObserver().
1453                                                removeOnDrawListener(listener);
1454                                    }
1455                                }
1456                            });
1457                        return;
1458                    }
1459                });
1460            }
1461            // When Launcher comes back to foreground, a different Activity might be responsible for
1462            // the app market intent, so refresh the icon
1463            updateAppMarketIcon();
1464            clearTypedText();
1465        }
1466    }
1467
1468    private void sendAdvanceMessage(long delay) {
1469        mHandler.removeMessages(ADVANCE_MSG);
1470        Message msg = mHandler.obtainMessage(ADVANCE_MSG);
1471        mHandler.sendMessageDelayed(msg, delay);
1472        mAutoAdvanceSentTime = System.currentTimeMillis();
1473    }
1474
1475    private void updateRunning() {
1476        boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
1477        if (autoAdvanceRunning != mAutoAdvanceRunning) {
1478            mAutoAdvanceRunning = autoAdvanceRunning;
1479            if (autoAdvanceRunning) {
1480                long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
1481                sendAdvanceMessage(delay);
1482            } else {
1483                if (!mWidgetsToAdvance.isEmpty()) {
1484                    mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
1485                            (System.currentTimeMillis() - mAutoAdvanceSentTime));
1486                }
1487                mHandler.removeMessages(ADVANCE_MSG);
1488                mHandler.removeMessages(0); // Remove messages sent using postDelayed()
1489            }
1490        }
1491    }
1492
1493    private final Handler mHandler = new Handler() {
1494        @Override
1495        public void handleMessage(Message msg) {
1496            if (msg.what == ADVANCE_MSG) {
1497                int i = 0;
1498                for (View key: mWidgetsToAdvance.keySet()) {
1499                    final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
1500                    final int delay = mAdvanceStagger * i;
1501                    if (v instanceof Advanceable) {
1502                       postDelayed(new Runnable() {
1503                           public void run() {
1504                               ((Advanceable) v).advance();
1505                           }
1506                       }, delay);
1507                    }
1508                    i++;
1509                }
1510                sendAdvanceMessage(mAdvanceInterval);
1511            }
1512        }
1513    };
1514
1515    void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1516        if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
1517        View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1518        if (v instanceof Advanceable) {
1519            mWidgetsToAdvance.put(hostView, appWidgetInfo);
1520            ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1521            updateRunning();
1522        }
1523    }
1524
1525    void removeWidgetToAutoAdvance(View hostView) {
1526        if (mWidgetsToAdvance.containsKey(hostView)) {
1527            mWidgetsToAdvance.remove(hostView);
1528            updateRunning();
1529        }
1530    }
1531
1532    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1533        removeWidgetToAutoAdvance(launcherInfo.hostView);
1534        launcherInfo.hostView = null;
1535    }
1536
1537    void showOutOfSpaceMessage(boolean isHotseatLayout) {
1538        int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
1539        Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
1540    }
1541
1542    public LauncherAppWidgetHost getAppWidgetHost() {
1543        return mAppWidgetHost;
1544    }
1545
1546    public LauncherModel getModel() {
1547        return mModel;
1548    }
1549
1550    public void closeSystemDialogs() {
1551        getWindow().closeAllPanels();
1552
1553        // Whatever we were doing is hereby canceled.
1554        mWaitingForResult = false;
1555    }
1556
1557    @Override
1558    protected void onNewIntent(Intent intent) {
1559        long startTime = 0;
1560        if (DEBUG_RESUME_TIME) {
1561            startTime = System.currentTimeMillis();
1562        }
1563        super.onNewIntent(intent);
1564
1565        // Close the menu
1566        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1567            // also will cancel mWaitingForResult.
1568            closeSystemDialogs();
1569
1570            final boolean alreadyOnHome =
1571                    ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1572                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1573
1574            Runnable processIntent = new Runnable() {
1575                public void run() {
1576                    if (mWorkspace == null) {
1577                        // Can be cases where mWorkspace is null, this prevents a NPE
1578                        return;
1579                    }
1580                    Folder openFolder = mWorkspace.getOpenFolder();
1581                    // In all these cases, only animate if we're already on home
1582                    mWorkspace.exitWidgetResizeMode();
1583                    if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
1584                            openFolder == null) {
1585                        mWorkspace.moveToDefaultScreen(true);
1586                    }
1587
1588                    closeFolder();
1589                    exitSpringLoadedDragMode();
1590
1591                    // If we are already on home, then just animate back to the workspace,
1592                    // otherwise, just wait until onResume to set the state back to Workspace
1593                    if (alreadyOnHome) {
1594                        showWorkspace(true);
1595                        if (mWorkspace.isInOverviewMode()) {
1596                            mWorkspace.exitOverviewMode();
1597                        }
1598                    } else {
1599                        mOnResumeState = State.WORKSPACE;
1600                    }
1601
1602                    final View v = getWindow().peekDecorView();
1603                    if (v != null && v.getWindowToken() != null) {
1604                        InputMethodManager imm = (InputMethodManager)getSystemService(
1605                                INPUT_METHOD_SERVICE);
1606                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1607                    }
1608
1609                    // Reset AllApps to its initial state
1610                    if (!alreadyOnHome && mAppsCustomizeTabHost != null) {
1611                        mAppsCustomizeTabHost.reset();
1612                    }
1613                }
1614            };
1615
1616            if (alreadyOnHome && !mWorkspace.hasWindowFocus()) {
1617                // Delay processing of the intent to allow the status bar animation to finish
1618                // first in order to avoid janky animations.
1619                mWorkspace.postDelayed(processIntent, 350);
1620            } else {
1621                // Process the intent immediately.
1622                processIntent.run();
1623            }
1624
1625        }
1626        if (DEBUG_RESUME_TIME) {
1627            Log.d(TAG, "Time spent in onNewIntent: " + (System.currentTimeMillis() - startTime));
1628        }
1629    }
1630
1631    @Override
1632    public void onRestoreInstanceState(Bundle state) {
1633        super.onRestoreInstanceState(state);
1634        for (int page: mSynchronouslyBoundPages) {
1635            mWorkspace.restoreInstanceStateForChild(page);
1636        }
1637    }
1638
1639    @Override
1640    protected void onSaveInstanceState(Bundle outState) {
1641        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getNextPage());
1642        super.onSaveInstanceState(outState);
1643
1644        outState.putInt(RUNTIME_STATE, mState.ordinal());
1645        // We close any open folder since it will not be re-opened, and we need to make sure
1646        // this state is reflected.
1647        closeFolder();
1648
1649        if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screenId > -1 &&
1650                mWaitingForResult) {
1651            outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
1652            outState.putLong(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screenId);
1653            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
1654            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
1655            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
1656            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
1657            outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
1658        }
1659
1660        if (mFolderInfo != null && mWaitingForResult) {
1661            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1662            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1663        }
1664
1665        // Save the current AppsCustomize tab
1666        if (mAppsCustomizeTabHost != null) {
1667            String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
1668            if (currentTabTag != null) {
1669                outState.putString("apps_customize_currentTab", currentTabTag);
1670            }
1671            int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
1672            outState.putInt("apps_customize_currentIndex", currentIndex);
1673        }
1674    }
1675
1676    @Override
1677    public void onDestroy() {
1678        super.onDestroy();
1679
1680        // Remove all pending runnables
1681        mHandler.removeMessages(ADVANCE_MSG);
1682        mHandler.removeMessages(0);
1683        mWorkspace.removeCallbacks(mBuildLayersRunnable);
1684
1685        // Stop callbacks from LauncherModel
1686        LauncherAppState app = (LauncherAppState.getInstance());
1687        mModel.stopLoader();
1688        app.setLauncher(null);
1689
1690        try {
1691            mAppWidgetHost.stopListening();
1692        } catch (NullPointerException ex) {
1693            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1694        }
1695        mAppWidgetHost = null;
1696
1697        mWidgetsToAdvance.clear();
1698
1699        TextKeyListener.getInstance().release();
1700
1701        // Disconnect any of the callbacks and drawables associated with ItemInfos on the workspace
1702        // to prevent leaking Launcher activities on orientation change.
1703        if (mModel != null) {
1704            mModel.unbindItemInfosAndClearQueuedBindRunnables();
1705        }
1706
1707        getContentResolver().unregisterContentObserver(mWidgetObserver);
1708        unregisterReceiver(mCloseSystemDialogsReceiver);
1709
1710        mDragLayer.clearAllResizeFrames();
1711        ((ViewGroup) mWorkspace.getParent()).removeAllViews();
1712        mWorkspace.removeAllViews();
1713        mWorkspace = null;
1714        mDragController = null;
1715
1716        LauncherAnimUtils.onDestroyActivity();
1717    }
1718
1719    public DragController getDragController() {
1720        return mDragController;
1721    }
1722
1723    @Override
1724    public void startActivityForResult(Intent intent, int requestCode) {
1725        if (requestCode >= 0) mWaitingForResult = true;
1726        super.startActivityForResult(intent, requestCode);
1727    }
1728
1729    /**
1730     * Indicates that we want global search for this activity by setting the globalSearch
1731     * argument for {@link #startSearch} to true.
1732     */
1733    @Override
1734    public void startSearch(String initialQuery, boolean selectInitialQuery,
1735            Bundle appSearchData, boolean globalSearch) {
1736
1737        showWorkspace(true);
1738
1739        if (initialQuery == null) {
1740            // Use any text typed in the launcher as the initial query
1741            initialQuery = getTypedText();
1742        }
1743        if (appSearchData == null) {
1744            appSearchData = new Bundle();
1745            appSearchData.putString("source", "launcher-search");
1746        }
1747        Rect sourceBounds = new Rect();
1748        if (mSearchDropTargetBar != null) {
1749            sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
1750        }
1751
1752        startSearch(initialQuery, selectInitialQuery,
1753                appSearchData, sourceBounds);
1754    }
1755
1756    public void startSearch(String initialQuery,
1757            boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
1758        startGlobalSearch(initialQuery, selectInitialQuery,
1759                appSearchData, sourceBounds);
1760    }
1761
1762    /**
1763     * Starts the global search activity. This code is a copied from SearchManager
1764     */
1765    private void startGlobalSearch(String initialQuery,
1766            boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
1767        final SearchManager searchManager =
1768            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1769        ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
1770        if (globalSearchActivity == null) {
1771            Log.w(TAG, "No global search activity found.");
1772            return;
1773        }
1774        Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
1775        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1776        intent.setComponent(globalSearchActivity);
1777        // Make sure that we have a Bundle to put source in
1778        if (appSearchData == null) {
1779            appSearchData = new Bundle();
1780        } else {
1781            appSearchData = new Bundle(appSearchData);
1782        }
1783        // Set source to package name of app that starts global search, if not set already.
1784        if (!appSearchData.containsKey("source")) {
1785            appSearchData.putString("source", getPackageName());
1786        }
1787        intent.putExtra(SearchManager.APP_DATA, appSearchData);
1788        if (!TextUtils.isEmpty(initialQuery)) {
1789            intent.putExtra(SearchManager.QUERY, initialQuery);
1790        }
1791        if (selectInitialQuery) {
1792            intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
1793        }
1794        intent.setSourceBounds(sourceBounds);
1795        try {
1796            startActivity(intent);
1797        } catch (ActivityNotFoundException ex) {
1798            Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
1799        }
1800    }
1801
1802    @Override
1803    public boolean onCreateOptionsMenu(Menu menu) {
1804        if (isWorkspaceLocked()) {
1805            return false;
1806        }
1807
1808        super.onCreateOptionsMenu(menu);
1809
1810        Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
1811        manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1812                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1813        Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1814        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1815                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1816        String helpUrl = getString(R.string.help_url);
1817        Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
1818        help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1819                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1820
1821        menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1822            .setIcon(android.R.drawable.ic_menu_gallery)
1823            .setAlphabeticShortcut('W');
1824        menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
1825            .setIcon(android.R.drawable.ic_menu_manage)
1826            .setIntent(manageApps)
1827            .setAlphabeticShortcut('M');
1828        menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings)
1829            .setIcon(android.R.drawable.ic_menu_preferences)
1830            .setIntent(settings)
1831            .setAlphabeticShortcut('P');
1832        if (!helpUrl.isEmpty()) {
1833            menu.add(0, MENU_HELP, 0, R.string.menu_help)
1834                .setIcon(android.R.drawable.ic_menu_help)
1835                .setIntent(help)
1836                .setAlphabeticShortcut('H');
1837        }
1838        return true;
1839    }
1840
1841    @Override
1842    public boolean onPrepareOptionsMenu(Menu menu) {
1843        super.onPrepareOptionsMenu(menu);
1844
1845        if (mAppsCustomizeTabHost.isTransitioning()) {
1846            return false;
1847        }
1848        boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE);
1849        menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible);
1850
1851        return true;
1852    }
1853
1854    @Override
1855    public boolean onOptionsItemSelected(MenuItem item) {
1856        switch (item.getItemId()) {
1857        case MENU_WALLPAPER_SETTINGS:
1858            startWallpaper();
1859            return true;
1860        }
1861
1862        return super.onOptionsItemSelected(item);
1863    }
1864
1865    @Override
1866    public boolean onSearchRequested() {
1867        startSearch(null, false, null, true);
1868        // Use a custom animation for launching search
1869        return true;
1870    }
1871
1872    public boolean isWorkspaceLocked() {
1873        return mWorkspaceLoading || mWaitingForResult;
1874    }
1875
1876    private void resetAddInfo() {
1877        mPendingAddInfo.container = ItemInfo.NO_ID;
1878        mPendingAddInfo.screenId = -1;
1879        mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
1880        mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
1881        mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1;
1882        mPendingAddInfo.dropPos = null;
1883    }
1884
1885    void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget,
1886            AppWidgetProviderInfo appWidgetInfo) {
1887        if (appWidgetInfo.configure != null) {
1888            mPendingAddWidgetInfo = appWidgetInfo;
1889
1890            // Launch over to configure widget, if needed
1891            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1892            intent.setComponent(appWidgetInfo.configure);
1893            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1894            Utilities.startActivityForResultSafely(this, intent, REQUEST_CREATE_APPWIDGET);
1895        } else {
1896            // Otherwise just add it
1897            completeAddAppWidget(appWidgetId, info.container, info.screenId, boundWidget,
1898                    appWidgetInfo);
1899            // Exit spring loaded mode if necessary after adding the widget
1900            exitSpringLoadedDragModeDelayed(true, false, null);
1901        }
1902    }
1903
1904    /**
1905     * Process a shortcut drop.
1906     *
1907     * @param componentName The name of the component
1908     * @param screenId The ID of the screen where it should be added
1909     * @param cell The cell it should be added to, optional
1910     * @param position The location on the screen where it was dropped, optional
1911     */
1912    void processShortcutFromDrop(ComponentName componentName, long container, long screenId,
1913            int[] cell, int[] loc) {
1914        resetAddInfo();
1915        mPendingAddInfo.container = container;
1916        mPendingAddInfo.screenId = screenId;
1917        mPendingAddInfo.dropPos = loc;
1918
1919        if (cell != null) {
1920            mPendingAddInfo.cellX = cell[0];
1921            mPendingAddInfo.cellY = cell[1];
1922        }
1923
1924        Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1925        createShortcutIntent.setComponent(componentName);
1926        processShortcut(createShortcutIntent);
1927    }
1928
1929    /**
1930     * Process a widget drop.
1931     *
1932     * @param info The PendingAppWidgetInfo of the widget being added.
1933     * @param screenId The ID of the screen where it should be added
1934     * @param cell The cell it should be added to, optional
1935     * @param position The location on the screen where it was dropped, optional
1936     */
1937    void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, long screenId,
1938            int[] cell, int[] span, int[] loc) {
1939        resetAddInfo();
1940        mPendingAddInfo.container = info.container = container;
1941        mPendingAddInfo.screenId = info.screenId = screenId;
1942        mPendingAddInfo.dropPos = loc;
1943        mPendingAddInfo.minSpanX = info.minSpanX;
1944        mPendingAddInfo.minSpanY = info.minSpanY;
1945
1946        if (cell != null) {
1947            mPendingAddInfo.cellX = cell[0];
1948            mPendingAddInfo.cellY = cell[1];
1949        }
1950        if (span != null) {
1951            mPendingAddInfo.spanX = span[0];
1952            mPendingAddInfo.spanY = span[1];
1953        }
1954
1955        AppWidgetHostView hostView = info.boundWidget;
1956        int appWidgetId;
1957        if (hostView != null) {
1958            appWidgetId = hostView.getAppWidgetId();
1959            addAppWidgetImpl(appWidgetId, info, hostView, info.info);
1960        } else {
1961            // In this case, we either need to start an activity to get permission to bind
1962            // the widget, or we need to start an activity to configure the widget, or both.
1963            appWidgetId = getAppWidgetHost().allocateAppWidgetId();
1964            Bundle options = info.bindOptions;
1965
1966            boolean success = false;
1967            if (options != null) {
1968                success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
1969                        info.componentName, options);
1970            } else {
1971                success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
1972                        info.componentName);
1973            }
1974            if (success) {
1975                addAppWidgetImpl(appWidgetId, info, null, info.info);
1976            } else {
1977                mPendingAddWidgetInfo = info.info;
1978                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
1979                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1980                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
1981                // TODO: we need to make sure that this accounts for the options bundle.
1982                // intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
1983                startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
1984            }
1985        }
1986    }
1987
1988    void processShortcut(Intent intent) {
1989        // Handle case where user selected "Applications"
1990        String applicationName = getResources().getString(R.string.group_applications);
1991        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1992
1993        if (applicationName != null && applicationName.equals(shortcutName)) {
1994            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1995            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1996
1997            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1998            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1999            pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
2000            Utilities.startActivityForResultSafely(this, pickIntent, REQUEST_PICK_APPLICATION);
2001        } else {
2002            Utilities.startActivityForResultSafely(this, intent, REQUEST_CREATE_SHORTCUT);
2003        }
2004    }
2005
2006    void processWallpaper(Intent intent) {
2007        startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
2008    }
2009
2010    FolderIcon addFolder(CellLayout layout, long container, final long screenId, int cellX,
2011            int cellY) {
2012        final FolderInfo folderInfo = new FolderInfo();
2013        folderInfo.title = getText(R.string.folder_name);
2014
2015        // Update the model
2016        LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screenId, cellX, cellY,
2017                false);
2018        sFolders.put(folderInfo.id, folderInfo);
2019
2020        // Create the view
2021        FolderIcon newFolder =
2022            FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
2023        mWorkspace.addInScreen(newFolder, container, screenId, cellX, cellY, 1, 1,
2024                isWorkspaceLocked());
2025        // Force measure the new folder icon
2026        CellLayout parent = mWorkspace.getParentCellLayoutForView(newFolder);
2027        parent.getShortcutsAndWidgets().measureChild(newFolder);
2028        return newFolder;
2029    }
2030
2031    void removeFolder(FolderInfo folder) {
2032        sFolders.remove(folder.id);
2033    }
2034
2035    private void startWallpaper() {
2036        showWorkspace(true);
2037        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
2038        pickWallpaper.setComponent(
2039                new ComponentName(getPackageName(), WallpaperPickerActivity.class.getName()));
2040        startActivityForResult(pickWallpaper, REQUEST_PICK_WALLPAPER);
2041    }
2042
2043    /**
2044     * Registers various content observers. The current implementation registers
2045     * only a favorites observer to keep track of the favorites applications.
2046     */
2047    private void registerContentObservers() {
2048        ContentResolver resolver = getContentResolver();
2049        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
2050                true, mWidgetObserver);
2051    }
2052
2053    @Override
2054    public boolean dispatchKeyEvent(KeyEvent event) {
2055        if (event.getAction() == KeyEvent.ACTION_DOWN) {
2056            switch (event.getKeyCode()) {
2057                case KeyEvent.KEYCODE_HOME:
2058                    return true;
2059                case KeyEvent.KEYCODE_VOLUME_DOWN:
2060                    if (isPropertyEnabled(DUMP_STATE_PROPERTY)) {
2061                        dumpState();
2062                        return true;
2063                    }
2064                    break;
2065            }
2066        } else if (event.getAction() == KeyEvent.ACTION_UP) {
2067            switch (event.getKeyCode()) {
2068                case KeyEvent.KEYCODE_HOME:
2069                    return true;
2070            }
2071        }
2072
2073        return super.dispatchKeyEvent(event);
2074    }
2075
2076    @Override
2077    public void onBackPressed() {
2078        if (isAllAppsVisible()) {
2079            showWorkspace(true);
2080        } else if (mWorkspace.isInOverviewMode()) {
2081            mWorkspace.exitOverviewMode();
2082        } else if (mWorkspace.getOpenFolder() != null) {
2083            Folder openFolder = mWorkspace.getOpenFolder();
2084            if (openFolder.isEditingName()) {
2085                openFolder.dismissEditingName();
2086            } else {
2087                closeFolder();
2088            }
2089        } else {
2090            mWorkspace.exitWidgetResizeMode();
2091
2092            // Back button is a no-op here, but give at least some feedback for the button press
2093            mWorkspace.showOutlinesTemporarily();
2094        }
2095    }
2096
2097    /**
2098     * Re-listen when widgets are reset.
2099     */
2100    private void onAppWidgetReset() {
2101        if (mAppWidgetHost != null) {
2102            mAppWidgetHost.startListening();
2103        }
2104    }
2105
2106    /**
2107     * Launches the intent referred by the clicked shortcut.
2108     *
2109     * @param v The view representing the clicked shortcut.
2110     */
2111    public void onClick(View v) {
2112        // Make sure that rogue clicks don't get through while allapps is launching, or after the
2113        // view has detached (it's possible for this to happen if the view is removed mid touch).
2114        if (v.getWindowToken() == null) {
2115            return;
2116        }
2117
2118        if (!mWorkspace.isFinishedSwitchingState()) {
2119            return;
2120        }
2121
2122        if (v instanceof PageIndicator) {
2123            if (!mWorkspace.isInOverviewMode()) {
2124                mWorkspace.enterOverviewMode();
2125            }
2126            return;
2127        }
2128
2129        if (v instanceof CellLayout) {
2130            if (mWorkspace.isInOverviewMode()) {
2131                mWorkspace.exitOverviewMode(mWorkspace.indexOfChild(v));
2132            }
2133        }
2134
2135        Object tag = v.getTag();
2136        if (tag instanceof ShortcutInfo) {
2137            // Open shortcut
2138            final ShortcutInfo shortcut = (ShortcutInfo) tag;
2139            final Intent intent = shortcut.intent;
2140
2141            // Check for special shortcuts
2142            if (intent.getComponent() != null) {
2143                final String shortcutClass = intent.getComponent().getClassName();
2144
2145                if (shortcutClass.equals(WidgetAdder.class.getName())) {
2146                    showAllApps(true);
2147                    return;
2148                } else if (shortcutClass.equals(MemoryDumpActivity.class.getName())) {
2149                    MemoryDumpActivity.startDump(this);
2150                    return;
2151                } else if (shortcutClass.equals(ToggleWeightWatcher.class.getName())) {
2152                    toggleShowWeightWatcher();
2153                    return;
2154                }
2155            }
2156
2157            // Start activities
2158            int[] pos = new int[2];
2159            v.getLocationOnScreen(pos);
2160            intent.setSourceBounds(new Rect(pos[0], pos[1],
2161                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
2162
2163            boolean success = startActivitySafely(v, intent, tag);
2164
2165            mStats.recordLaunch(intent, shortcut);
2166
2167            if (success && v instanceof BubbleTextView) {
2168                mWaitingForResume = (BubbleTextView) v;
2169                mWaitingForResume.setStayPressed(true);
2170            }
2171        } else if (tag instanceof FolderInfo) {
2172            if (v instanceof FolderIcon) {
2173                FolderIcon fi = (FolderIcon) v;
2174                handleFolderClick(fi);
2175            }
2176        } else if (v == mAllAppsButton) {
2177            if (isAllAppsVisible()) {
2178                showWorkspace(true);
2179            } else {
2180                onClickAllAppsButton(v);
2181            }
2182        }
2183    }
2184
2185    public boolean onTouch(View v, MotionEvent event) {
2186        return false;
2187    }
2188
2189    /**
2190     * Event handler for the search button
2191     *
2192     * @param v The view that was clicked.
2193     */
2194    public void onClickSearchButton(View v) {
2195        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2196
2197        onSearchRequested();
2198    }
2199
2200    /**
2201     * Event handler for the voice button
2202     *
2203     * @param v The view that was clicked.
2204     */
2205    public void onClickVoiceButton(View v) {
2206        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2207
2208        startVoice();
2209    }
2210
2211    public void startVoice() {
2212        try {
2213            final SearchManager searchManager =
2214                    (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2215            ComponentName activityName = searchManager.getGlobalSearchActivity();
2216            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2217            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2218            if (activityName != null) {
2219                intent.setPackage(activityName.getPackageName());
2220            }
2221            startActivity(null, intent, "onClickVoiceButton");
2222        } catch (ActivityNotFoundException e) {
2223            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2224            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2225            startActivitySafely(null, intent, "onClickVoiceButton");
2226        }
2227    }
2228
2229    /**
2230     * Event handler for the "grid" button that appears on the home screen, which
2231     * enters all apps mode.
2232     *
2233     * @param v The view that was clicked.
2234     */
2235    public void onClickAllAppsButton(View v) {
2236        showAllApps(true);
2237    }
2238
2239    public void onTouchDownAllAppsButton(View v) {
2240        // Provide the same haptic feedback that the system offers for virtual keys.
2241        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2242    }
2243
2244    public void onClickAppMarketButton(View v) {
2245        if (mAppMarketIntent != null) {
2246            startActivitySafely(v, mAppMarketIntent, "app market");
2247        } else {
2248            Log.e(TAG, "Invalid app market intent.");
2249        }
2250    }
2251
2252    void startApplicationDetailsActivity(ComponentName componentName) {
2253        String packageName = componentName.getPackageName();
2254        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
2255                Uri.fromParts("package", packageName, null));
2256        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2257        startActivitySafely(null, intent, "startApplicationDetailsActivity");
2258    }
2259
2260    // returns true if the activity was started
2261    boolean startApplicationUninstallActivity(ComponentName componentName, int flags) {
2262        if ((flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
2263            // System applications cannot be installed. For now, show a toast explaining that.
2264            // We may give them the option of disabling apps this way.
2265            int messageId = R.string.uninstall_system_app_text;
2266            Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
2267            return false;
2268        } else {
2269            String packageName = componentName.getPackageName();
2270            String className = componentName.getClassName();
2271            Intent intent = new Intent(
2272                    Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
2273            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
2274                    Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2275            startActivity(intent);
2276            return true;
2277        }
2278    }
2279
2280    boolean startActivity(View v, Intent intent, Object tag) {
2281        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2282
2283        try {
2284            // Only launch using the new animation if the shortcut has not opted out (this is a
2285            // private contract between launcher and may be ignored in the future).
2286            boolean useLaunchAnimation = (v != null) &&
2287                    !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
2288            if (useLaunchAnimation) {
2289                ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
2290                        v.getMeasuredWidth(), v.getMeasuredHeight());
2291
2292                startActivity(intent, opts.toBundle());
2293            } else {
2294                startActivity(intent);
2295            }
2296            return true;
2297        } catch (SecurityException e) {
2298            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2299            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
2300                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
2301                    "or use the exported attribute for this activity. "
2302                    + "tag="+ tag + " intent=" + intent, e);
2303        }
2304        return false;
2305    }
2306
2307    boolean startActivitySafely(View v, Intent intent, Object tag) {
2308        boolean success = false;
2309        try {
2310            success = startActivity(v, intent, tag);
2311        } catch (ActivityNotFoundException e) {
2312            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2313            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
2314        }
2315        return success;
2316    }
2317
2318    private void handleFolderClick(FolderIcon folderIcon) {
2319        final FolderInfo info = folderIcon.getFolderInfo();
2320        Folder openFolder = mWorkspace.getFolderForTag(info);
2321
2322        // If the folder info reports that the associated folder is open, then verify that
2323        // it is actually opened. There have been a few instances where this gets out of sync.
2324        if (info.opened && openFolder == null) {
2325            Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
2326                    + info.screenId + " (" + info.cellX + ", " + info.cellY + ")");
2327            info.opened = false;
2328        }
2329
2330        if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
2331            // Close any open folder
2332            closeFolder();
2333            // Open the requested folder
2334            openFolder(folderIcon);
2335        } else {
2336            // Find the open folder...
2337            int folderScreen;
2338            if (openFolder != null) {
2339                folderScreen = mWorkspace.getPageForView(openFolder);
2340                // .. and close it
2341                closeFolder(openFolder);
2342                if (folderScreen != mWorkspace.getCurrentPage()) {
2343                    // Close any folder open on the current screen
2344                    closeFolder();
2345                    // Pull the folder onto this screen
2346                    openFolder(folderIcon);
2347                }
2348            }
2349        }
2350    }
2351
2352    /**
2353     * This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
2354     * in the DragLayer in the exact absolute location of the original FolderIcon.
2355     */
2356    private void copyFolderIconToImage(FolderIcon fi) {
2357        final int width = fi.getMeasuredWidth();
2358        final int height = fi.getMeasuredHeight();
2359
2360        // Lazy load ImageView, Bitmap and Canvas
2361        if (mFolderIconImageView == null) {
2362            mFolderIconImageView = new ImageView(this);
2363        }
2364        if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
2365                mFolderIconBitmap.getHeight() != height) {
2366            mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2367            mFolderIconCanvas = new Canvas(mFolderIconBitmap);
2368        }
2369
2370        DragLayer.LayoutParams lp;
2371        if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
2372            lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
2373        } else {
2374            lp = new DragLayer.LayoutParams(width, height);
2375        }
2376
2377        // The layout from which the folder is being opened may be scaled, adjust the starting
2378        // view size by this scale factor.
2379        float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
2380        lp.customPosition = true;
2381        lp.x = mRectForFolderAnimation.left;
2382        lp.y = mRectForFolderAnimation.top;
2383        lp.width = (int) (scale * width);
2384        lp.height = (int) (scale * height);
2385
2386        mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
2387        fi.draw(mFolderIconCanvas);
2388        mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
2389        if (fi.getFolder() != null) {
2390            mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
2391            mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
2392        }
2393        // Just in case this image view is still in the drag layer from a previous animation,
2394        // we remove it and re-add it.
2395        if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
2396            mDragLayer.removeView(mFolderIconImageView);
2397        }
2398        mDragLayer.addView(mFolderIconImageView, lp);
2399        if (fi.getFolder() != null) {
2400            fi.getFolder().bringToFront();
2401        }
2402    }
2403
2404    private void growAndFadeOutFolderIcon(FolderIcon fi) {
2405        if (fi == null) return;
2406        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
2407        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
2408        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
2409
2410        FolderInfo info = (FolderInfo) fi.getTag();
2411        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2412            CellLayout cl = (CellLayout) fi.getParent().getParent();
2413            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
2414            cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
2415        }
2416
2417        // Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
2418        copyFolderIconToImage(fi);
2419        fi.setVisibility(View.INVISIBLE);
2420
2421        ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
2422                scaleX, scaleY);
2423        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
2424        oa.start();
2425    }
2426
2427    private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
2428        if (fi == null) return;
2429        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
2430        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
2431        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
2432
2433        final CellLayout cl = (CellLayout) fi.getParent().getParent();
2434
2435        // We remove and re-draw the FolderIcon in-case it has changed
2436        mDragLayer.removeView(mFolderIconImageView);
2437        copyFolderIconToImage(fi);
2438        ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
2439                scaleX, scaleY);
2440        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
2441        oa.addListener(new AnimatorListenerAdapter() {
2442            @Override
2443            public void onAnimationEnd(Animator animation) {
2444                if (cl != null) {
2445                    cl.clearFolderLeaveBehind();
2446                    // Remove the ImageView copy of the FolderIcon and make the original visible.
2447                    mDragLayer.removeView(mFolderIconImageView);
2448                    fi.setVisibility(View.VISIBLE);
2449                }
2450            }
2451        });
2452        oa.start();
2453    }
2454
2455    /**
2456     * Opens the user folder described by the specified tag. The opening of the folder
2457     * is animated relative to the specified View. If the View is null, no animation
2458     * is played.
2459     *
2460     * @param folderInfo The FolderInfo describing the folder to open.
2461     */
2462    public void openFolder(FolderIcon folderIcon) {
2463        Folder folder = folderIcon.getFolder();
2464        FolderInfo info = folder.mInfo;
2465
2466        info.opened = true;
2467
2468        // Just verify that the folder hasn't already been added to the DragLayer.
2469        // There was a one-off crash where the folder had a parent already.
2470        if (folder.getParent() == null) {
2471            mDragLayer.addView(folder);
2472            mDragController.addDropTarget((DropTarget) folder);
2473        } else {
2474            Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
2475                    folder.getParent() + ").");
2476        }
2477        folder.animateOpen();
2478        growAndFadeOutFolderIcon(folderIcon);
2479
2480        // Notify the accessibility manager that this folder "window" has appeared and occluded
2481        // the workspace items
2482        folder.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2483        getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
2484    }
2485
2486    public void closeFolder() {
2487        Folder folder = mWorkspace.getOpenFolder();
2488        if (folder != null) {
2489            if (folder.isEditingName()) {
2490                folder.dismissEditingName();
2491            }
2492            closeFolder(folder);
2493
2494            // Dismiss the folder cling
2495            dismissFolderCling(null);
2496        }
2497    }
2498
2499    void closeFolder(Folder folder) {
2500        folder.getInfo().opened = false;
2501
2502        ViewGroup parent = (ViewGroup) folder.getParent().getParent();
2503        if (parent != null) {
2504            FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
2505            shrinkAndFadeInFolderIcon(fi);
2506        }
2507        folder.animateClosed();
2508
2509        // Notify the accessibility manager that this folder "window" has disappeard and no
2510        // longer occludeds the workspace items
2511        getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2512    }
2513
2514    public boolean onLongClick(View v) {
2515        if (!isDraggingEnabled()) return false;
2516        if (isWorkspaceLocked()) return false;
2517        if (mState != State.WORKSPACE) return false;
2518
2519        if (!(v instanceof CellLayout)) {
2520            v = (View) v.getParent().getParent();
2521        }
2522
2523        resetAddInfo();
2524        CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
2525        // This happens when long clicking an item with the dpad/trackball
2526        if (longClickCellInfo == null) {
2527            return true;
2528        }
2529
2530        // The hotseat touch handling does not go through Workspace, and we always allow long press
2531        // on hotseat items.
2532        final View itemUnderLongClick = longClickCellInfo.cell;
2533        boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
2534        if (allowLongPress && !mDragController.isDragging()) {
2535            if (itemUnderLongClick == null) {
2536                // User long pressed on empty space
2537                mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
2538                        HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
2539                // Disabling reordering until we sort out some issues.
2540                if (mWorkspace.isInOverviewMode()) {
2541                    mWorkspace.startReordering(v);
2542                } else {
2543                    mWorkspace.enterOverviewMode();
2544                }
2545            } else {
2546                if (!(itemUnderLongClick instanceof Folder)) {
2547                    // User long pressed on an item
2548                    mWorkspace.startDrag(longClickCellInfo);
2549                }
2550            }
2551        }
2552        return true;
2553    }
2554
2555    boolean isHotseatLayout(View layout) {
2556        return mHotseat != null && layout != null &&
2557                (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
2558    }
2559    Hotseat getHotseat() {
2560        return mHotseat;
2561    }
2562    View getOverviewPanel() {
2563        return mOverviewPanel;
2564    }
2565    SearchDropTargetBar getSearchBar() {
2566        return mSearchDropTargetBar;
2567    }
2568
2569    /**
2570     * Returns the CellLayout of the specified container at the specified screen.
2571     */
2572    CellLayout getCellLayout(long container, long screenId) {
2573        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2574            if (mHotseat != null) {
2575                return mHotseat.getLayout();
2576            } else {
2577                return null;
2578            }
2579        } else {
2580            return (CellLayout) mWorkspace.getScreenWithId(screenId);
2581        }
2582    }
2583
2584    Workspace getWorkspace() {
2585        return mWorkspace;
2586    }
2587
2588    public boolean isAllAppsVisible() {
2589        return (mState == State.APPS_CUSTOMIZE) || (mOnResumeState == State.APPS_CUSTOMIZE);
2590    }
2591
2592    /**
2593     * Helper method for the cameraZoomIn/cameraZoomOut animations
2594     * @param view The view being animated
2595     * @param scaleFactor The scale factor used for the zoom
2596     */
2597    private void setPivotsForZoom(View view, float scaleFactor) {
2598        view.setPivotX(view.getWidth() / 2.0f);
2599        view.setPivotY(view.getHeight() / 2.0f);
2600    }
2601
2602    void disableWallpaperIfInAllApps() {
2603        // Only disable it if we are in all apps
2604        if (isAllAppsVisible()) {
2605            if (mAppsCustomizeTabHost != null &&
2606                    !mAppsCustomizeTabHost.isTransitioning()) {
2607                updateWallpaperVisibility(false);
2608            }
2609        }
2610    }
2611
2612    private void setWorkspaceBackground(boolean workspace) {
2613        mLauncherView.setBackground(workspace ?
2614                mWorkspaceBackgroundDrawable : null);
2615    }
2616
2617    void updateWallpaperVisibility(boolean visible) {
2618        int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
2619        int curflags = getWindow().getAttributes().flags
2620                & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
2621        if (wpflags != curflags) {
2622            getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
2623        }
2624        setWorkspaceBackground(visible);
2625    }
2626
2627    private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) {
2628        if (v instanceof LauncherTransitionable) {
2629            ((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace);
2630        }
2631    }
2632
2633    private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) {
2634        if (v instanceof LauncherTransitionable) {
2635            ((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace);
2636        }
2637
2638        // Update the workspace transition step as well
2639        dispatchOnLauncherTransitionStep(v, 0f);
2640    }
2641
2642    private void dispatchOnLauncherTransitionStep(View v, float t) {
2643        if (v instanceof LauncherTransitionable) {
2644            ((LauncherTransitionable) v).onLauncherTransitionStep(this, t);
2645        }
2646    }
2647
2648    private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) {
2649        if (v instanceof LauncherTransitionable) {
2650            ((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace);
2651        }
2652
2653        // Update the workspace transition step as well
2654        dispatchOnLauncherTransitionStep(v, 1f);
2655    }
2656
2657    /**
2658     * Things to test when changing the following seven functions.
2659     *   - Home from workspace
2660     *          - from center screen
2661     *          - from other screens
2662     *   - Home from all apps
2663     *          - from center screen
2664     *          - from other screens
2665     *   - Back from all apps
2666     *          - from center screen
2667     *          - from other screens
2668     *   - Launch app from workspace and quit
2669     *          - with back
2670     *          - with home
2671     *   - Launch app from all apps and quit
2672     *          - with back
2673     *          - with home
2674     *   - Go to a screen that's not the default, then all
2675     *     apps, and launch and app, and go back
2676     *          - with back
2677     *          -with home
2678     *   - On workspace, long press power and go back
2679     *          - with back
2680     *          - with home
2681     *   - On all apps, long press power and go back
2682     *          - with back
2683     *          - with home
2684     *   - On workspace, power off
2685     *   - On all apps, power off
2686     *   - Launch an app and turn off the screen while in that app
2687     *          - Go back with home key
2688     *          - Go back with back key  TODO: make this not go to workspace
2689     *          - From all apps
2690     *          - From workspace
2691     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2692     *          - From all apps
2693     *          - From the center workspace
2694     *          - From another workspace
2695     */
2696
2697    /**
2698     * Zoom the camera out from the workspace to reveal 'toView'.
2699     * Assumes that the view to show is anchored at either the very top or very bottom
2700     * of the screen.
2701     */
2702    private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
2703        if (mStateAnimation != null) {
2704            mStateAnimation.setDuration(0);
2705            mStateAnimation.cancel();
2706            mStateAnimation = null;
2707        }
2708        final Resources res = getResources();
2709
2710        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
2711        final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
2712        final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2713        final View fromView = mWorkspace;
2714        final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
2715        final int startDelay =
2716                res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
2717
2718        setPivotsForZoom(toView, scale);
2719
2720        // Shrink workspaces away if going to AppsCustomize from workspace
2721        Animator workspaceAnim =
2722                mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
2723
2724        if (animated) {
2725            toView.setScaleX(scale);
2726            toView.setScaleY(scale);
2727            final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
2728            scaleAnim.
2729                scaleX(1f).scaleY(1f).
2730                setDuration(duration).
2731                setInterpolator(new Workspace.ZoomOutInterpolator());
2732
2733            toView.setVisibility(View.VISIBLE);
2734            toView.setAlpha(0f);
2735            final ObjectAnimator alphaAnim = LauncherAnimUtils
2736                .ofFloat(toView, "alpha", 0f, 1f)
2737                .setDuration(fadeDuration);
2738            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2739            alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
2740                @Override
2741                public void onAnimationUpdate(ValueAnimator animation) {
2742                    if (animation == null) {
2743                        throw new RuntimeException("animation is null");
2744                    }
2745                    float t = (Float) animation.getAnimatedValue();
2746                    dispatchOnLauncherTransitionStep(fromView, t);
2747                    dispatchOnLauncherTransitionStep(toView, t);
2748                }
2749            });
2750
2751            // toView should appear right at the end of the workspace shrink
2752            // animation
2753            mStateAnimation = LauncherAnimUtils.createAnimatorSet();
2754            mStateAnimation.play(scaleAnim).after(startDelay);
2755            mStateAnimation.play(alphaAnim).after(startDelay);
2756
2757            mStateAnimation.addListener(new AnimatorListenerAdapter() {
2758                boolean animationCancelled = false;
2759
2760                @Override
2761                public void onAnimationStart(Animator animation) {
2762                    updateWallpaperVisibility(true);
2763                    // Prepare the position
2764                    toView.setTranslationX(0.0f);
2765                    toView.setTranslationY(0.0f);
2766                    toView.setVisibility(View.VISIBLE);
2767                    toView.bringToFront();
2768                }
2769                @Override
2770                public void onAnimationEnd(Animator animation) {
2771                    dispatchOnLauncherTransitionEnd(fromView, animated, false);
2772                    dispatchOnLauncherTransitionEnd(toView, animated, false);
2773
2774                    if (!animationCancelled) {
2775                        updateWallpaperVisibility(false);
2776                    }
2777
2778                    // Hide the search bar
2779                    if (mSearchDropTargetBar != null) {
2780                        mSearchDropTargetBar.hideSearchBar(false);
2781                    }
2782                }
2783
2784                @Override
2785                public void onAnimationCancel(Animator animation) {
2786                    animationCancelled = true;
2787                }
2788            });
2789
2790            if (workspaceAnim != null) {
2791                mStateAnimation.play(workspaceAnim);
2792            }
2793
2794            boolean delayAnim = false;
2795
2796            dispatchOnLauncherTransitionPrepare(fromView, animated, false);
2797            dispatchOnLauncherTransitionPrepare(toView, animated, false);
2798
2799            // If any of the objects being animated haven't been measured/laid out
2800            // yet, delay the animation until we get a layout pass
2801            if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
2802                    (mWorkspace.getMeasuredWidth() == 0) ||
2803                    (toView.getMeasuredWidth() == 0)) {
2804                delayAnim = true;
2805            }
2806
2807            final AnimatorSet stateAnimation = mStateAnimation;
2808            final Runnable startAnimRunnable = new Runnable() {
2809                public void run() {
2810                    // Check that mStateAnimation hasn't changed while
2811                    // we waited for a layout/draw pass
2812                    if (mStateAnimation != stateAnimation)
2813                        return;
2814                    setPivotsForZoom(toView, scale);
2815                    dispatchOnLauncherTransitionStart(fromView, animated, false);
2816                    dispatchOnLauncherTransitionStart(toView, animated, false);
2817                    LauncherAnimUtils.startAnimationAfterNextDraw(mStateAnimation, toView);
2818                }
2819            };
2820            if (delayAnim) {
2821                final ViewTreeObserver observer = toView.getViewTreeObserver();
2822                observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
2823                        public void onGlobalLayout() {
2824                            startAnimRunnable.run();
2825                            toView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
2826                        }
2827                    });
2828            } else {
2829                startAnimRunnable.run();
2830            }
2831        } else {
2832            toView.setTranslationX(0.0f);
2833            toView.setTranslationY(0.0f);
2834            toView.setScaleX(1.0f);
2835            toView.setScaleY(1.0f);
2836            toView.setVisibility(View.VISIBLE);
2837            toView.bringToFront();
2838
2839            if (!springLoaded && !LauncherAppState.getInstance().isScreenLarge()) {
2840                // Hide the search bar
2841                if (mSearchDropTargetBar != null) {
2842                    mSearchDropTargetBar.hideSearchBar(false);
2843                }
2844            }
2845            dispatchOnLauncherTransitionPrepare(fromView, animated, false);
2846            dispatchOnLauncherTransitionStart(fromView, animated, false);
2847            dispatchOnLauncherTransitionEnd(fromView, animated, false);
2848            dispatchOnLauncherTransitionPrepare(toView, animated, false);
2849            dispatchOnLauncherTransitionStart(toView, animated, false);
2850            dispatchOnLauncherTransitionEnd(toView, animated, false);
2851            updateWallpaperVisibility(false);
2852        }
2853    }
2854
2855    /**
2856     * Zoom the camera back into the workspace, hiding 'fromView'.
2857     * This is the opposite of showAppsCustomizeHelper.
2858     * @param animated If true, the transition will be animated.
2859     */
2860    private void hideAppsCustomizeHelper(State toState, final boolean animated,
2861            final boolean springLoaded, final Runnable onCompleteRunnable) {
2862
2863        if (mStateAnimation != null) {
2864            mStateAnimation.setDuration(0);
2865            mStateAnimation.cancel();
2866            mStateAnimation = null;
2867        }
2868        Resources res = getResources();
2869
2870        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
2871        final int fadeOutDuration =
2872                res.getInteger(R.integer.config_appsCustomizeFadeOutTime);
2873        final float scaleFactor = (float)
2874                res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2875        final View fromView = mAppsCustomizeTabHost;
2876        final View toView = mWorkspace;
2877        Animator workspaceAnim = null;
2878        if (toState == State.WORKSPACE) {
2879            int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger);
2880            workspaceAnim = mWorkspace.getChangeStateAnimation(
2881                    Workspace.State.NORMAL, animated, stagger, -1);
2882        } else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2883            workspaceAnim = mWorkspace.getChangeStateAnimation(
2884                    Workspace.State.SPRING_LOADED, animated);
2885        }
2886
2887        setPivotsForZoom(fromView, scaleFactor);
2888        updateWallpaperVisibility(true);
2889        showHotseat(animated);
2890        if (animated) {
2891            final LauncherViewPropertyAnimator scaleAnim =
2892                    new LauncherViewPropertyAnimator(fromView);
2893            scaleAnim.
2894                scaleX(scaleFactor).scaleY(scaleFactor).
2895                setDuration(duration).
2896                setInterpolator(new Workspace.ZoomInInterpolator());
2897
2898            final ObjectAnimator alphaAnim = LauncherAnimUtils
2899                .ofFloat(fromView, "alpha", 1f, 0f)
2900                .setDuration(fadeOutDuration);
2901            alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator());
2902            alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
2903                @Override
2904                public void onAnimationUpdate(ValueAnimator animation) {
2905                    float t = 1f - (Float) animation.getAnimatedValue();
2906                    dispatchOnLauncherTransitionStep(fromView, t);
2907                    dispatchOnLauncherTransitionStep(toView, t);
2908                }
2909            });
2910
2911            mStateAnimation = LauncherAnimUtils.createAnimatorSet();
2912
2913            dispatchOnLauncherTransitionPrepare(fromView, animated, true);
2914            dispatchOnLauncherTransitionPrepare(toView, animated, true);
2915            mAppsCustomizeContent.pauseScrolling();
2916
2917            mStateAnimation.addListener(new AnimatorListenerAdapter() {
2918                @Override
2919                public void onAnimationEnd(Animator animation) {
2920                    updateWallpaperVisibility(true);
2921                    fromView.setVisibility(View.GONE);
2922                    dispatchOnLauncherTransitionEnd(fromView, animated, true);
2923                    dispatchOnLauncherTransitionEnd(toView, animated, true);
2924                    if (onCompleteRunnable != null) {
2925                        onCompleteRunnable.run();
2926                    }
2927                    mAppsCustomizeContent.updateCurrentPageScroll();
2928                    mAppsCustomizeContent.resumeScrolling();
2929                }
2930            });
2931
2932            mStateAnimation.playTogether(scaleAnim, alphaAnim);
2933            if (workspaceAnim != null) {
2934                mStateAnimation.play(workspaceAnim);
2935            }
2936            dispatchOnLauncherTransitionStart(fromView, animated, true);
2937            dispatchOnLauncherTransitionStart(toView, animated, true);
2938            LauncherAnimUtils.startAnimationAfterNextDraw(mStateAnimation, toView);
2939        } else {
2940            fromView.setVisibility(View.GONE);
2941            dispatchOnLauncherTransitionPrepare(fromView, animated, true);
2942            dispatchOnLauncherTransitionStart(fromView, animated, true);
2943            dispatchOnLauncherTransitionEnd(fromView, animated, true);
2944            dispatchOnLauncherTransitionPrepare(toView, animated, true);
2945            dispatchOnLauncherTransitionStart(toView, animated, true);
2946            dispatchOnLauncherTransitionEnd(toView, animated, true);
2947        }
2948    }
2949
2950    @Override
2951    public void onTrimMemory(int level) {
2952        super.onTrimMemory(level);
2953        if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
2954            mAppsCustomizeTabHost.onTrimMemory();
2955        }
2956    }
2957
2958    @Override
2959    public void onWindowFocusChanged(boolean hasFocus) {
2960        if (!hasFocus) {
2961            // When another window occludes launcher (like the notification shade, or recents),
2962            // ensure that we enable the wallpaper flag so that transitions are done correctly.
2963            updateWallpaperVisibility(true);
2964        } else {
2965            // When launcher has focus again, disable the wallpaper if we are in AllApps
2966            mWorkspace.postDelayed(new Runnable() {
2967                @Override
2968                public void run() {
2969                    disableWallpaperIfInAllApps();
2970                }
2971            }, 500);
2972        }
2973    }
2974
2975    void showWorkspace(boolean animated) {
2976        showWorkspace(animated, null);
2977    }
2978
2979    void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
2980        if (mState != State.WORKSPACE) {
2981            boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED);
2982            mWorkspace.setVisibility(View.VISIBLE);
2983            hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable);
2984
2985            // Show the search bar (only animate if we were showing the drop target bar in spring
2986            // loaded mode)
2987            if (mSearchDropTargetBar != null) {
2988                mSearchDropTargetBar.showSearchBar(wasInSpringLoadedMode);
2989            }
2990
2991            // Set focus to the AppsCustomize button
2992            if (mAllAppsButton != null) {
2993                mAllAppsButton.requestFocus();
2994            }
2995        }
2996
2997        // Change the state *after* we've called all the transition code
2998        mState = State.WORKSPACE;
2999
3000        // Resume the auto-advance of widgets
3001        mUserPresent = true;
3002        updateRunning();
3003
3004        // Send an accessibility event to announce the context change
3005        getWindow().getDecorView()
3006                .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3007
3008        onWorkspaceShown(animated);
3009    }
3010
3011    public void onWorkspaceShown(boolean animated) {
3012    }
3013
3014    void showAllApps(boolean animated) {
3015        if (mState != State.WORKSPACE) return;
3016
3017        showAppsCustomizeHelper(animated, false);
3018        mAppsCustomizeTabHost.requestFocus();
3019
3020        // Change the state *after* we've called all the transition code
3021        mState = State.APPS_CUSTOMIZE;
3022
3023        // Pause the auto-advance of widgets until we are out of AllApps
3024        mUserPresent = false;
3025        updateRunning();
3026        closeFolder();
3027
3028        // Send an accessibility event to announce the context change
3029        getWindow().getDecorView()
3030                .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3031    }
3032
3033    void enterSpringLoadedDragMode() {
3034        if (isAllAppsVisible()) {
3035            hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null);
3036            mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
3037        }
3038    }
3039
3040    void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay,
3041            final Runnable onCompleteRunnable) {
3042        if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return;
3043
3044        mHandler.postDelayed(new Runnable() {
3045            @Override
3046            public void run() {
3047                if (successfulDrop) {
3048                    // Before we show workspace, hide all apps again because
3049                    // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
3050                    // clean up our state transition functions
3051                    mAppsCustomizeTabHost.setVisibility(View.GONE);
3052                    showWorkspace(true, onCompleteRunnable);
3053                } else {
3054                    exitSpringLoadedDragMode();
3055                }
3056            }
3057        }, (extendedDelay ?
3058                EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
3059                EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
3060    }
3061
3062    void exitSpringLoadedDragMode() {
3063        if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
3064            final boolean animated = true;
3065            final boolean springLoaded = true;
3066            showAppsCustomizeHelper(animated, springLoaded);
3067            mState = State.APPS_CUSTOMIZE;
3068        }
3069        // Otherwise, we are not in spring loaded mode, so don't do anything.
3070    }
3071
3072    void lockAllApps() {
3073        // TODO
3074    }
3075
3076    void unlockAllApps() {
3077        // TODO
3078    }
3079
3080    /**
3081     * Shows the hotseat area.
3082     */
3083    void showHotseat(boolean animated) {
3084        if (!LauncherAppState.getInstance().isScreenLarge()) {
3085            if (animated) {
3086                if (mHotseat.getAlpha() != 1f) {
3087                    int duration = 0;
3088                    if (mSearchDropTargetBar != null) {
3089                        duration = mSearchDropTargetBar.getTransitionInDuration();
3090                    }
3091                    mHotseat.animate().alpha(1f).setDuration(duration);
3092                }
3093            } else {
3094                mHotseat.setAlpha(1f);
3095            }
3096        }
3097    }
3098
3099    /**
3100     * Hides the hotseat area.
3101     */
3102    void hideHotseat(boolean animated) {
3103        if (!LauncherAppState.getInstance().isScreenLarge()) {
3104            if (animated) {
3105                if (mHotseat.getAlpha() != 0f) {
3106                    int duration = 0;
3107                    if (mSearchDropTargetBar != null) {
3108                        duration = mSearchDropTargetBar.getTransitionOutDuration();
3109                    }
3110                    mHotseat.animate().alpha(0f).setDuration(duration);
3111                }
3112            } else {
3113                mHotseat.setAlpha(0f);
3114            }
3115        }
3116    }
3117
3118    /**
3119     * Add an item from all apps or customize onto the given workspace screen.
3120     * If layout is null, add to the current screen.
3121     */
3122    void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
3123        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
3124            showOutOfSpaceMessage(isHotseatLayout(layout));
3125        }
3126    }
3127
3128    /** Maps the current orientation to an index for referencing orientation correct global icons */
3129    private int getCurrentOrientationIndexForGlobalIcons() {
3130        // default - 0, landscape - 1
3131        switch (getResources().getConfiguration().orientation) {
3132        case Configuration.ORIENTATION_LANDSCAPE:
3133            return 1;
3134        default:
3135            return 0;
3136        }
3137    }
3138
3139    private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) {
3140        try {
3141            PackageManager packageManager = getPackageManager();
3142            // Look for the toolbar icon specified in the activity meta-data
3143            Bundle metaData = packageManager.getActivityInfo(
3144                    activityName, PackageManager.GET_META_DATA).metaData;
3145            if (metaData != null) {
3146                int iconResId = metaData.getInt(resourceName);
3147                if (iconResId != 0) {
3148                    Resources res = packageManager.getResourcesForActivity(activityName);
3149                    return res.getDrawable(iconResId);
3150                }
3151            }
3152        } catch (NameNotFoundException e) {
3153            // This can happen if the activity defines an invalid drawable
3154            Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
3155                    " not found", e);
3156        } catch (Resources.NotFoundException nfe) {
3157            // This can happen if the activity defines an invalid drawable
3158            Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
3159                    nfe);
3160        }
3161        return null;
3162    }
3163
3164    // if successful in getting icon, return it; otherwise, set button to use default drawable
3165    private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
3166            int buttonId, ComponentName activityName, int fallbackDrawableId,
3167            String toolbarResourceName) {
3168        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
3169        Resources r = getResources();
3170        int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
3171        int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
3172
3173        TextView button = (TextView) findViewById(buttonId);
3174        // If we were unable to find the icon via the meta-data, use a generic one
3175        if (toolbarIcon == null) {
3176            toolbarIcon = r.getDrawable(fallbackDrawableId);
3177            toolbarIcon.setBounds(0, 0, w, h);
3178            if (button != null) {
3179                button.setCompoundDrawables(toolbarIcon, null, null, null);
3180            }
3181            return null;
3182        } else {
3183            toolbarIcon.setBounds(0, 0, w, h);
3184            if (button != null) {
3185                button.setCompoundDrawables(toolbarIcon, null, null, null);
3186            }
3187            return toolbarIcon.getConstantState();
3188        }
3189    }
3190
3191    // if successful in getting icon, return it; otherwise, set button to use default drawable
3192    private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
3193            int buttonId, ComponentName activityName, int fallbackDrawableId,
3194            String toolbarResourceName) {
3195        ImageView button = (ImageView) findViewById(buttonId);
3196        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
3197
3198        if (button != null) {
3199            // If we were unable to find the icon via the meta-data, use a
3200            // generic one
3201            if (toolbarIcon == null) {
3202                button.setImageResource(fallbackDrawableId);
3203            } else {
3204                button.setImageDrawable(toolbarIcon);
3205            }
3206        }
3207
3208        return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
3209
3210    }
3211
3212    private void updateTextButtonWithDrawable(int buttonId, Drawable d) {
3213        TextView button = (TextView) findViewById(buttonId);
3214        button.setCompoundDrawables(d, null, null, null);
3215    }
3216
3217    private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
3218        ImageView button = (ImageView) findViewById(buttonId);
3219        button.setImageDrawable(d.newDrawable(getResources()));
3220    }
3221
3222    private void invalidatePressedFocusedStates(View container, View button) {
3223        if (container instanceof HolographicLinearLayout) {
3224            HolographicLinearLayout layout = (HolographicLinearLayout) container;
3225            layout.invalidatePressedFocusedStates();
3226        } else if (button instanceof HolographicImageView) {
3227            HolographicImageView view = (HolographicImageView) button;
3228            view.invalidatePressedFocusedStates();
3229        }
3230    }
3231
3232    private boolean updateGlobalSearchIcon() {
3233        final View searchButtonContainer = findViewById(R.id.search_button_container);
3234        final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
3235        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3236        final View voiceButton = findViewById(R.id.voice_button);
3237
3238        final SearchManager searchManager =
3239                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
3240        ComponentName activityName = searchManager.getGlobalSearchActivity();
3241        if (activityName != null) {
3242            int coi = getCurrentOrientationIndexForGlobalIcons();
3243            sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3244                    R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
3245                    TOOLBAR_SEARCH_ICON_METADATA_NAME);
3246            if (sGlobalSearchIcon[coi] == null) {
3247                sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3248                        R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
3249                        TOOLBAR_ICON_METADATA_NAME);
3250            }
3251
3252            if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE);
3253            searchButton.setVisibility(View.VISIBLE);
3254            invalidatePressedFocusedStates(searchButtonContainer, searchButton);
3255            return true;
3256        } else {
3257            // We disable both search and voice search when there is no global search provider
3258            if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE);
3259            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
3260            searchButton.setVisibility(View.GONE);
3261            voiceButton.setVisibility(View.GONE);
3262            setVoiceButtonProxyVisible(false);
3263            return false;
3264        }
3265    }
3266
3267    private void updateGlobalSearchIcon(Drawable.ConstantState d) {
3268        final View searchButtonContainer = findViewById(R.id.search_button_container);
3269        final View searchButton = (ImageView) findViewById(R.id.search_button);
3270        updateButtonWithDrawable(R.id.search_button, d);
3271        invalidatePressedFocusedStates(searchButtonContainer, searchButton);
3272    }
3273
3274    private boolean updateVoiceSearchIcon(boolean searchVisible) {
3275        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3276        final View voiceButton = findViewById(R.id.voice_button);
3277
3278        // We only show/update the voice search icon if the search icon is enabled as well
3279        final SearchManager searchManager =
3280                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
3281        ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
3282
3283        ComponentName activityName = null;
3284        if (globalSearchActivity != null) {
3285            // Check if the global search activity handles voice search
3286            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3287            intent.setPackage(globalSearchActivity.getPackageName());
3288            activityName = intent.resolveActivity(getPackageManager());
3289        }
3290
3291        if (activityName == null) {
3292            // Fallback: check if an activity other than the global search activity
3293            // resolves this
3294            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3295            activityName = intent.resolveActivity(getPackageManager());
3296        }
3297        if (searchVisible && activityName != null) {
3298            int coi = getCurrentOrientationIndexForGlobalIcons();
3299            sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3300                    R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
3301                    TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME);
3302            if (sVoiceSearchIcon[coi] == null) {
3303                sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3304                        R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
3305                        TOOLBAR_ICON_METADATA_NAME);
3306            }
3307            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE);
3308            voiceButton.setVisibility(View.VISIBLE);
3309            setVoiceButtonProxyVisible(true);
3310            invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
3311            return true;
3312        } else {
3313            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
3314            voiceButton.setVisibility(View.GONE);
3315            setVoiceButtonProxyVisible(false);
3316            return false;
3317        }
3318    }
3319
3320    private void updateVoiceSearchIcon(Drawable.ConstantState d) {
3321        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3322        final View voiceButton = findViewById(R.id.voice_button);
3323        updateButtonWithDrawable(R.id.voice_button, d);
3324        invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
3325    }
3326
3327    public void setVoiceButtonProxyVisible(boolean visible) {
3328        final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
3329        if (voiceButtonProxy != null) {
3330            voiceButtonProxy.setVisibility(visible ? View.VISIBLE : View.GONE);
3331        }
3332    }
3333    /**
3334     * Sets the app market icon
3335     */
3336    private void updateAppMarketIcon() {
3337        final View marketButton = findViewById(R.id.market_button);
3338        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
3339        // Find the app market activity by resolving an intent.
3340        // (If multiple app markets are installed, it will return the ResolverActivity.)
3341        ComponentName activityName = intent.resolveActivity(getPackageManager());
3342        if (activityName != null) {
3343            int coi = getCurrentOrientationIndexForGlobalIcons();
3344            mAppMarketIntent = intent;
3345            sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(
3346                    R.id.market_button, activityName, R.drawable.ic_launcher_market_holo,
3347                    TOOLBAR_ICON_METADATA_NAME);
3348            marketButton.setVisibility(View.VISIBLE);
3349        } else {
3350            // We should hide and disable the view so that we don't try and restore the visibility
3351            // of it when we swap between drag & normal states from IconDropTarget subclasses.
3352            marketButton.setVisibility(View.GONE);
3353            marketButton.setEnabled(false);
3354        }
3355    }
3356
3357    private void updateAppMarketIcon(Drawable.ConstantState d) {
3358        // Ensure that the new drawable we are creating has the approprate toolbar icon bounds
3359        Resources r = getResources();
3360        Drawable marketIconDrawable = d.newDrawable(r);
3361        int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
3362        int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
3363        marketIconDrawable.setBounds(0, 0, w, h);
3364
3365        updateTextButtonWithDrawable(R.id.market_button, marketIconDrawable);
3366    }
3367
3368    @Override
3369    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3370        final boolean result = super.dispatchPopulateAccessibilityEvent(event);
3371        final List<CharSequence> text = event.getText();
3372        text.clear();
3373        // Populate event with a fake title based on the current state.
3374        if (mState == State.APPS_CUSTOMIZE) {
3375            text.add(getString(R.string.all_apps_button_label));
3376        } else {
3377            text.add(getString(R.string.all_apps_home_button_label));
3378        }
3379        return result;
3380    }
3381
3382    /**
3383     * Receives notifications when system dialogs are to be closed.
3384     */
3385    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
3386        @Override
3387        public void onReceive(Context context, Intent intent) {
3388            closeSystemDialogs();
3389        }
3390    }
3391
3392    /**
3393     * Receives notifications whenever the appwidgets are reset.
3394     */
3395    private class AppWidgetResetObserver extends ContentObserver {
3396        public AppWidgetResetObserver() {
3397            super(new Handler());
3398        }
3399
3400        @Override
3401        public void onChange(boolean selfChange) {
3402            onAppWidgetReset();
3403        }
3404    }
3405
3406    /**
3407     * If the activity is currently paused, signal that we need to run the passed Runnable
3408     * in onResume.
3409     *
3410     * This needs to be called from incoming places where resources might have been loaded
3411     * while we are paused.  That is becaues the Configuration might be wrong
3412     * when we're not running, and if it comes back to what it was when we
3413     * were paused, we are not restarted.
3414     *
3415     * Implementation of the method from LauncherModel.Callbacks.
3416     *
3417     * @return true if we are currently paused.  The caller might be able to
3418     * skip some work in that case since we will come back again.
3419     */
3420    private boolean waitUntilResume(Runnable run, boolean deletePreviousRunnables) {
3421        if (mPaused) {
3422            Log.i(TAG, "Deferring update until onResume");
3423            if (deletePreviousRunnables) {
3424                while (mBindOnResumeCallbacks.remove(run)) {
3425                }
3426            }
3427            mBindOnResumeCallbacks.add(run);
3428            return true;
3429        } else {
3430            return false;
3431        }
3432    }
3433
3434    private boolean waitUntilResume(Runnable run) {
3435        return waitUntilResume(run, false);
3436    }
3437
3438    public void addOnResumeCallback(Runnable run) {
3439        mOnResumeCallbacks.add(run);
3440    }
3441
3442    /**
3443     * If the activity is currently paused, signal that we need to re-run the loader
3444     * in onResume.
3445     *
3446     * This needs to be called from incoming places where resources might have been loaded
3447     * while we are paused.  That is becaues the Configuration might be wrong
3448     * when we're not running, and if it comes back to what it was when we
3449     * were paused, we are not restarted.
3450     *
3451     * Implementation of the method from LauncherModel.Callbacks.
3452     *
3453     * @return true if we are currently paused.  The caller might be able to
3454     * skip some work in that case since we will come back again.
3455     */
3456    public boolean setLoadOnResume() {
3457        if (mPaused) {
3458            Log.i(TAG, "setLoadOnResume");
3459            mOnResumeNeedsLoad = true;
3460            return true;
3461        } else {
3462            return false;
3463        }
3464    }
3465
3466    /**
3467     * Implementation of the method from LauncherModel.Callbacks.
3468     */
3469    public int getCurrentWorkspaceScreen() {
3470        if (mWorkspace != null) {
3471            return mWorkspace.getCurrentPage();
3472        } else {
3473            return SCREEN_COUNT / 2;
3474        }
3475    }
3476
3477    /**
3478     * Refreshes the shortcuts shown on the workspace.
3479     *
3480     * Implementation of the method from LauncherModel.Callbacks.
3481     */
3482    public void startBinding() {
3483        // If we're starting binding all over again, clear any bind calls we'd postponed in
3484        // the past (see waitUntilResume) -- we don't need them since we're starting binding
3485        // from scratch again
3486        mBindOnResumeCallbacks.clear();
3487
3488        // Clear the workspace because it's going to be rebound
3489        mWorkspace.clearDropTargets();
3490        mWorkspace.removeAllViews();
3491
3492        mWidgetsToAdvance.clear();
3493        if (mHotseat != null) {
3494            mHotseat.resetLayout();
3495        }
3496    }
3497
3498    @Override
3499    public void bindScreens(ArrayList<Long> orderedScreenIds) {
3500        bindAddScreens(orderedScreenIds);
3501        mWorkspace.addExtraEmptyScreen();
3502    }
3503
3504    @Override
3505    public void bindAddScreens(ArrayList<Long> orderedScreenIds) {
3506        int count = orderedScreenIds.size();
3507        for (int i = 0; i < count; i++) {
3508            Log.w(TAG, "10249126 - bindAddScreens(" + orderedScreenIds.get(i) + ")");
3509            mWorkspace.insertNewWorkspaceScreenBeforeEmptyScreen(orderedScreenIds.get(i));
3510        }
3511    }
3512
3513    private boolean shouldShowWeightWatcher() {
3514        String spKey = LauncherAppState.getSharedPreferencesKey();
3515        SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
3516        boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, SHOW_WEIGHT_WATCHER_DEFAULT);
3517
3518        return show;
3519    }
3520
3521    private void toggleShowWeightWatcher() {
3522        String spKey = LauncherAppState.getSharedPreferencesKey();
3523        SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
3524        boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, true);
3525
3526        show = !show;
3527
3528        SharedPreferences.Editor editor = sp.edit();
3529        editor.putBoolean(SHOW_WEIGHT_WATCHER, show);
3530        editor.commit();
3531
3532        if (mWeightWatcher != null) {
3533            mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
3534        }
3535    }
3536
3537    public void bindAppsAdded(final ArrayList<Long> newScreens,
3538                              final ArrayList<ItemInfo> addNotAnimated,
3539                              final ArrayList<ItemInfo> addAnimated) {
3540        Runnable r = new Runnable() {
3541            public void run() {
3542                bindAppsAdded(newScreens, addNotAnimated, addAnimated);
3543            }
3544        };
3545        if (waitUntilResume(r)) {
3546            return;
3547        }
3548
3549        Log.w(TAG, "10249126 - bindAppsAdded(" + newScreens.size() + ")");
3550
3551        // Add the new screens
3552        bindAddScreens(newScreens);
3553
3554        // We add the items without animation on non-visible pages, and with
3555        // animations on the new page (which we will try and snap to).
3556        if (!addNotAnimated.isEmpty()) {
3557            bindItems(addNotAnimated, 0,
3558                    addNotAnimated.size(), false);
3559        }
3560        if (!addAnimated.isEmpty()) {
3561            bindItems(addAnimated, 0,
3562                    addAnimated.size(), true);
3563        }
3564    }
3565
3566    /**
3567     * Bind the items start-end from the list.
3568     *
3569     * Implementation of the method from LauncherModel.Callbacks.
3570     */
3571    public void bindItems(final ArrayList<ItemInfo> shortcuts, final int start, final int end,
3572                          final boolean forceAnimateIcons) {
3573        Runnable r = new Runnable() {
3574            public void run() {
3575                bindItems(shortcuts, start, end, forceAnimateIcons);
3576            }
3577        };
3578        if (waitUntilResume(r)) {
3579            return;
3580        }
3581
3582        // Get the list of added shortcuts and intersect them with the set of shortcuts here
3583        final AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
3584        final Collection<Animator> bounceAnims = new ArrayList<Animator>();
3585        final boolean animateIcons = forceAnimateIcons && canRunNewAppsAnimation();
3586        Workspace workspace = mWorkspace;
3587        long newShortcutsScreenId = -1;
3588        for (int i = start; i < end; i++) {
3589            final ItemInfo item = shortcuts.get(i);
3590
3591            // Short circuit if we are loading dock items for a configuration which has no dock
3592            if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3593                    mHotseat == null) {
3594                continue;
3595            }
3596
3597            switch (item.itemType) {
3598                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3599                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3600                    ShortcutInfo info = (ShortcutInfo) item;
3601                    View shortcut = createShortcut(info);
3602
3603                    /*
3604                     * TODO: FIX collision case
3605                     */
3606                    if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
3607                        CellLayout cl = mWorkspace.getScreenWithId(item.screenId);
3608                        if (cl != null && cl.isOccupied(item.cellX, item.cellY)) {
3609                            throw new RuntimeException("OCCUPIED");
3610                        }
3611                    }
3612
3613                    workspace.addInScreenFromBind(shortcut, item.container, item.screenId, item.cellX,
3614                            item.cellY, 1, 1);
3615                    if (animateIcons) {
3616                        // Animate all the applications up now
3617                        shortcut.setAlpha(0f);
3618                        shortcut.setScaleX(0f);
3619                        shortcut.setScaleY(0f);
3620                        bounceAnims.add(createNewAppBounceAnimation(shortcut, i));
3621                        newShortcutsScreenId = item.screenId;
3622                    }
3623                    break;
3624                case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3625                    FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
3626                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3627                            (FolderInfo) item, mIconCache);
3628                    workspace.addInScreenFromBind(newFolder, item.container, item.screenId, item.cellX,
3629                            item.cellY, 1, 1);
3630                    break;
3631                default:
3632                    throw new RuntimeException("Invalid Item Type");
3633            }
3634        }
3635
3636        if (animateIcons) {
3637            // Animate to the correct page
3638            if (newShortcutsScreenId > -1) {
3639                long currentScreenId = mWorkspace.getScreenIdForPageIndex(mWorkspace.getNextPage());
3640                int newScreenIndex = mWorkspace.getPageIndexForScreenId(newShortcutsScreenId);
3641                if (newShortcutsScreenId != currentScreenId) {
3642                    mWorkspace.snapToPage(newScreenIndex);
3643                }
3644            }
3645
3646            // We post the animation slightly delayed to prevent slowdowns when we are loading
3647            // right after we return to launcher.
3648            mWorkspace.postDelayed(new Runnable() {
3649                public void run() {
3650                    anim.playTogether(bounceAnims);
3651                    anim.start();
3652                }
3653            }, NEW_APPS_ANIMATION_DELAY);
3654        }
3655        workspace.requestLayout();
3656    }
3657
3658    /**
3659     * Implementation of the method from LauncherModel.Callbacks.
3660     */
3661    public void bindFolders(final HashMap<Long, FolderInfo> folders) {
3662        Runnable r = new Runnable() {
3663            public void run() {
3664                bindFolders(folders);
3665            }
3666        };
3667        if (waitUntilResume(r)) {
3668            return;
3669        }
3670        sFolders.clear();
3671        sFolders.putAll(folders);
3672    }
3673
3674    /**
3675     * Add the views for a widget to the workspace.
3676     *
3677     * Implementation of the method from LauncherModel.Callbacks.
3678     */
3679    public void bindAppWidget(final LauncherAppWidgetInfo item) {
3680        Runnable r = new Runnable() {
3681            public void run() {
3682                bindAppWidget(item);
3683            }
3684        };
3685        if (waitUntilResume(r)) {
3686            return;
3687        }
3688
3689        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3690        if (DEBUG_WIDGETS) {
3691            Log.d(TAG, "bindAppWidget: " + item);
3692        }
3693        final Workspace workspace = mWorkspace;
3694
3695        final int appWidgetId = item.appWidgetId;
3696        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
3697        if (DEBUG_WIDGETS) {
3698            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
3699        }
3700
3701        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3702
3703        item.hostView.setTag(item);
3704        item.onBindAppWidget(this);
3705
3706        workspace.addInScreen(item.hostView, item.container, item.screenId, item.cellX,
3707                item.cellY, item.spanX, item.spanY, false);
3708        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3709
3710        workspace.requestLayout();
3711
3712        if (DEBUG_WIDGETS) {
3713            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3714                    + (SystemClock.uptimeMillis()-start) + "ms");
3715        }
3716    }
3717
3718    public void onPageBoundSynchronously(int page) {
3719        mSynchronouslyBoundPages.add(page);
3720    }
3721
3722    /**
3723     * Callback saying that there aren't any more items to bind.
3724     *
3725     * Implementation of the method from LauncherModel.Callbacks.
3726     */
3727    public void finishBindingItems(final boolean upgradePath) {
3728        Runnable r = new Runnable() {
3729            public void run() {
3730                finishBindingItems(upgradePath);
3731            }
3732        };
3733        if (waitUntilResume(r)) {
3734            return;
3735        }
3736        if (mSavedState != null) {
3737            if (!mWorkspace.hasFocus()) {
3738                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
3739            }
3740            mSavedState = null;
3741        }
3742
3743        // Create the custom content page here before onLayout to prevent flashing
3744        if (!mWorkspace.hasCustomContent() && hasCustomContentToLeft()) {
3745            mWorkspace.createCustomContentPage();
3746        }
3747
3748        mWorkspace.restoreInstanceStateForRemainingPages();
3749
3750        // If we received the result of any pending adds while the loader was running (e.g. the
3751        // widget configuration forced an orientation change), process them now.
3752        for (int i = 0; i < sPendingAddList.size(); i++) {
3753            completeAdd(sPendingAddList.get(i));
3754        }
3755        sPendingAddList.clear();
3756
3757        // Update the market app icon as necessary (the other icons will be managed in response to
3758        // package changes in bindSearchablesChanged()
3759        updateAppMarketIcon();
3760
3761        mWorkspaceLoading = false;
3762        if (upgradePath) {
3763            mWorkspace.stripDuplicateApps();
3764            mIntentsOnWorkspaceFromUpgradePath = mWorkspace.stripDuplicateApps();
3765        }
3766
3767        mWorkspace.post(new Runnable() {
3768            @Override
3769            public void run() {
3770                onFinishBindingItems();
3771            }
3772        });
3773    }
3774
3775    private boolean canRunNewAppsAnimation() {
3776        long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
3777        return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
3778    }
3779
3780    private ValueAnimator createNewAppBounceAnimation(View v, int i) {
3781        ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
3782                PropertyValuesHolder.ofFloat("alpha", 1f),
3783                PropertyValuesHolder.ofFloat("scaleX", 1f),
3784                PropertyValuesHolder.ofFloat("scaleY", 1f));
3785        bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
3786        bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
3787        bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator());
3788        return bounceAnim;
3789    }
3790
3791    @Override
3792    public void bindSearchablesChanged() {
3793        boolean searchVisible = updateGlobalSearchIcon();
3794        boolean voiceVisible = updateVoiceSearchIcon(searchVisible);
3795        if (mSearchDropTargetBar != null) {
3796            mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
3797        }
3798    }
3799
3800    /**
3801     * Add the icons for all apps.
3802     *
3803     * Implementation of the method from LauncherModel.Callbacks.
3804     */
3805    public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
3806        if (mIntentsOnWorkspaceFromUpgradePath != null) {
3807            if (LauncherModel.UPGRADE_USE_MORE_APPS_FOLDER) {
3808                getHotseat().addAllAppsFolder(mIconCache, apps,
3809                        mIntentsOnWorkspaceFromUpgradePath, Launcher.this, mWorkspace);
3810            }
3811            mIntentsOnWorkspaceFromUpgradePath = null;
3812        }
3813    }
3814
3815    /**
3816     * A package was updated.
3817     *
3818     * Implementation of the method from LauncherModel.Callbacks.
3819     */
3820    public void bindAppsUpdated(final ArrayList<ApplicationInfo> apps) {
3821        Runnable r = new Runnable() {
3822            public void run() {
3823                bindAppsUpdated(apps);
3824            }
3825        };
3826        if (waitUntilResume(r)) {
3827            return;
3828        }
3829
3830        if (mWorkspace != null) {
3831            mWorkspace.updateShortcuts(apps);
3832        }
3833    }
3834
3835    /**
3836     * A package was uninstalled.  We take both the super set of packageNames
3837     * in addition to specific applications to remove, the reason being that
3838     * this can be called when a package is updated as well.  In that scenario,
3839     * we only remove specific components from the workspace, where as
3840     * package-removal should clear all items by package name.
3841     *
3842     * Implementation of the method from LauncherModel.Callbacks.
3843     */
3844    public void bindComponentsRemoved(final ArrayList<String> packageNames,
3845                                      final ArrayList<ApplicationInfo> appInfos,
3846                                      final boolean packageRemoved) {
3847        Runnable r = new Runnable() {
3848            public void run() {
3849                bindComponentsRemoved(packageNames, appInfos, packageRemoved);
3850            }
3851        };
3852        if (waitUntilResume(r)) {
3853            return;
3854        }
3855
3856        if (packageRemoved) {
3857            mWorkspace.removeItemsByPackageName(packageNames);
3858        } else {
3859            mWorkspace.removeItemsByApplicationInfo(appInfos);
3860        }
3861
3862        // Notify the drag controller
3863        mDragController.onAppsRemoved(appInfos, this);
3864    }
3865
3866    /**
3867     * A number of packages were updated.
3868     */
3869    private ArrayList<Object> mWidgetsAndShortcuts;
3870    private Runnable mBindPackagesUpdatedRunnable = new Runnable() {
3871            public void run() {
3872                bindPackagesUpdated(mWidgetsAndShortcuts);
3873                mWidgetsAndShortcuts = null;
3874            }
3875        };
3876
3877    public void bindPackagesUpdated(final ArrayList<Object> widgetsAndShortcuts) {
3878        if (waitUntilResume(mBindPackagesUpdatedRunnable, true)) {
3879            mWidgetsAndShortcuts = widgetsAndShortcuts;
3880            return;
3881        }
3882
3883        // Update the widgets pane
3884        if (mAppsCustomizeContent != null) {
3885            mAppsCustomizeContent.onPackagesUpdated(widgetsAndShortcuts);
3886        }
3887    }
3888
3889    private int mapConfigurationOriActivityInfoOri(int configOri) {
3890        final Display d = getWindowManager().getDefaultDisplay();
3891        int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
3892        switch (d.getRotation()) {
3893        case Surface.ROTATION_0:
3894        case Surface.ROTATION_180:
3895            // We are currently in the same basic orientation as the natural orientation
3896            naturalOri = configOri;
3897            break;
3898        case Surface.ROTATION_90:
3899        case Surface.ROTATION_270:
3900            // We are currently in the other basic orientation to the natural orientation
3901            naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
3902                    Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
3903            break;
3904        }
3905
3906        int[] oriMap = {
3907                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
3908                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
3909                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
3910                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
3911        };
3912        // Since the map starts at portrait, we need to offset if this device's natural orientation
3913        // is landscape.
3914        int indexOffset = 0;
3915        if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
3916            indexOffset = 1;
3917        }
3918        return oriMap[(d.getRotation() + indexOffset) % 4];
3919    }
3920
3921    public boolean isRotationEnabled() {
3922        boolean enableRotation = sForceEnableRotation ||
3923                getResources().getBoolean(R.bool.allow_rotation);
3924        return enableRotation;
3925    }
3926    public void lockScreenOrientation() {
3927        if (isRotationEnabled()) {
3928            setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
3929                    .getConfiguration().orientation));
3930        }
3931    }
3932    public void unlockScreenOrientation(boolean immediate) {
3933        if (isRotationEnabled()) {
3934            if (immediate) {
3935                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3936            } else {
3937                mHandler.postDelayed(new Runnable() {
3938                    public void run() {
3939                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3940                    }
3941                }, mRestoreScreenOrientationDelay);
3942            }
3943        }
3944    }
3945
3946    /* Cling related */
3947    private boolean isClingsEnabled() {
3948        if (DISABLE_CLINGS) {
3949            return false;
3950        }
3951
3952        // disable clings when running in a test harness
3953        if(ActivityManager.isRunningInTestHarness()) return false;
3954
3955        // Restricted secondary users (child mode) will potentially have very few apps
3956        // seeded when they start up for the first time. Clings won't work well with that
3957//        boolean supportsLimitedUsers =
3958//                android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
3959//        Account[] accounts = AccountManager.get(this).getAccounts();
3960//        if (supportsLimitedUsers && accounts.length == 0) {
3961//            UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
3962//            Bundle restrictions = um.getUserRestrictions();
3963//            if (restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, false)) {
3964//               return false;
3965//            }
3966//        }
3967        return true;
3968    }
3969
3970    private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) {
3971        final Cling cling = (Cling) findViewById(clingId);
3972        if (cling != null) {
3973            cling.init(this, positionData);
3974            cling.setVisibility(View.VISIBLE);
3975            cling.setLayerType(View.LAYER_TYPE_HARDWARE, null);
3976            if (animate) {
3977                cling.buildLayer();
3978                cling.setAlpha(0f);
3979                cling.animate()
3980                    .alpha(1f)
3981                    .setInterpolator(new AccelerateInterpolator())
3982                    .setDuration(SHOW_CLING_DURATION)
3983                    .setStartDelay(delay)
3984                    .start();
3985            } else {
3986                cling.setAlpha(1f);
3987            }
3988            cling.setFocusableInTouchMode(true);
3989            cling.post(new Runnable() {
3990                public void run() {
3991                    cling.setFocusable(true);
3992                    cling.requestFocus();
3993                }
3994            });
3995            mHideFromAccessibilityHelper.setImportantForAccessibilityToNo(
3996                    mDragLayer, clingId == R.id.all_apps_cling);
3997        }
3998        return cling;
3999    }
4000
4001    private void dismissCling(final Cling cling, final String flag, int duration) {
4002        // To catch cases where siblings of top-level views are made invisible, just check whether
4003        // the cling is directly set to GONE before dismissing it.
4004        if (cling != null && cling.getVisibility() != View.GONE) {
4005            ObjectAnimator anim = LauncherAnimUtils.ofFloat(cling, "alpha", 0f);
4006            anim.setDuration(duration);
4007            anim.addListener(new AnimatorListenerAdapter() {
4008                public void onAnimationEnd(Animator animation) {
4009                    cling.setVisibility(View.GONE);
4010                    cling.cleanup();
4011                    // We should update the shared preferences on a background thread
4012                    new Thread("dismissClingThread") {
4013                        public void run() {
4014                            SharedPreferences.Editor editor = mSharedPrefs.edit();
4015                            editor.putBoolean(flag, true);
4016                            editor.commit();
4017                        }
4018                    }.start();
4019                };
4020            });
4021            anim.start();
4022            mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer);
4023        }
4024    }
4025
4026    private void removeCling(int id) {
4027        final View cling = findViewById(id);
4028        if (cling != null) {
4029            final ViewGroup parent = (ViewGroup) cling.getParent();
4030            parent.post(new Runnable() {
4031                @Override
4032                public void run() {
4033                    parent.removeView(cling);
4034                }
4035            });
4036            mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer);
4037        }
4038    }
4039
4040    private boolean skipCustomClingIfNoAccounts() {
4041        Cling cling = (Cling) findViewById(R.id.workspace_cling);
4042        boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
4043        if (customCling) {
4044            AccountManager am = AccountManager.get(this);
4045            if (am == null) return false;
4046            Account[] accounts = am.getAccountsByType("com.google");
4047            return accounts.length == 0;
4048        }
4049        return false;
4050    }
4051
4052    public void showFirstRunWorkspaceCling() {
4053        // Enable the clings only if they have not been dismissed before
4054        if (isClingsEnabled() &&
4055                !mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false) &&
4056                !skipCustomClingIfNoAccounts() ) {
4057            // If we're not using the default workspace layout, replace workspace cling
4058            // with a custom workspace cling (usually specified in an overlay)
4059            // For now, only do this on tablets
4060            if (mSharedPrefs.getInt(LauncherProvider.DEFAULT_WORKSPACE_RESOURCE_ID, 0) != 0 &&
4061                    getResources().getBoolean(R.bool.config_useCustomClings)) {
4062                // Use a custom cling
4063                View cling = findViewById(R.id.workspace_cling);
4064                ViewGroup clingParent = (ViewGroup) cling.getParent();
4065                int clingIndex = clingParent.indexOfChild(cling);
4066                clingParent.removeViewAt(clingIndex);
4067                View customCling = mInflater.inflate(R.layout.custom_workspace_cling, clingParent, false);
4068                clingParent.addView(customCling, clingIndex);
4069                customCling.setId(R.id.workspace_cling);
4070            }
4071            initCling(R.id.workspace_cling, null, false, 0);
4072        } else {
4073            removeCling(R.id.workspace_cling);
4074        }
4075    }
4076    public void showFirstRunAllAppsCling(int[] position) {
4077        // Enable the clings only if they have not been dismissed before
4078        if (isClingsEnabled() &&
4079                !mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) {
4080            initCling(R.id.all_apps_cling, position, true, 0);
4081        } else {
4082            removeCling(R.id.all_apps_cling);
4083        }
4084    }
4085    public Cling showFirstRunFoldersCling() {
4086        // Enable the clings only if they have not been dismissed before
4087        if (isClingsEnabled() &&
4088                !mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) {
4089            return initCling(R.id.folder_cling, null, true, 0);
4090        } else {
4091            removeCling(R.id.folder_cling);
4092            return null;
4093        }
4094    }
4095    protected SharedPreferences getSharedPrefs() {
4096        return mSharedPrefs;
4097    }
4098    public boolean isFolderClingVisible() {
4099        Cling cling = (Cling) findViewById(R.id.folder_cling);
4100        if (cling != null) {
4101            return cling.getVisibility() == View.VISIBLE;
4102        }
4103        return false;
4104    }
4105    public void dismissWorkspaceCling(View v) {
4106        Cling cling = (Cling) findViewById(R.id.workspace_cling);
4107        dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
4108    }
4109    public void dismissAllAppsCling(View v) {
4110        Cling cling = (Cling) findViewById(R.id.all_apps_cling);
4111        dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
4112    }
4113    public void dismissFolderCling(View v) {
4114        Cling cling = (Cling) findViewById(R.id.folder_cling);
4115        dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
4116    }
4117
4118    /**
4119     * Prints out out state for debugging.
4120     */
4121    public void dumpState() {
4122        Log.d(TAG, "BEGIN launcher3 dump state for launcher " + this);
4123        Log.d(TAG, "mSavedState=" + mSavedState);
4124        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
4125        Log.d(TAG, "mRestoring=" + mRestoring);
4126        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
4127        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
4128        Log.d(TAG, "sFolders.size=" + sFolders.size());
4129        mModel.dumpState();
4130
4131        if (mAppsCustomizeContent != null) {
4132            mAppsCustomizeContent.dumpState();
4133        }
4134        Log.d(TAG, "END launcher3 dump state");
4135    }
4136
4137    @Override
4138    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4139        super.dump(prefix, fd, writer, args);
4140        writer.println(" ");
4141        writer.println("Debug logs: ");
4142        for (int i = 0; i < sDumpLogs.size(); i++) {
4143            writer.println("  " + sDumpLogs.get(i));
4144        }
4145    }
4146
4147    public static void dumpDebugLogsToConsole() {
4148        Log.d(TAG, "");
4149        Log.d(TAG, "*********************");
4150        Log.d(TAG, "Launcher debug logs: ");
4151        for (int i = 0; i < sDumpLogs.size(); i++) {
4152            Log.d(TAG, "  " + sDumpLogs.get(i));
4153        }
4154        Log.d(TAG, "*********************");
4155        Log.d(TAG, "");
4156    }
4157}
4158
4159interface LauncherTransitionable {
4160    View getContent();
4161    void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace);
4162    void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
4163    void onLauncherTransitionStep(Launcher l, float t);
4164    void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
4165}
4166