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