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