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