Launcher.java revision 211bac3cd89b26bda4ff52df984731d11156dc38
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            launcherInfo.notifyWidgetSizeChanged(this);
1133            mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1],
1134                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1135
1136            addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1137        }
1138        resetAddInfo();
1139    }
1140
1141    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1142        @Override
1143        public void onReceive(Context context, Intent intent) {
1144            final String action = intent.getAction();
1145            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1146                mUserPresent = false;
1147                mDragLayer.clearAllResizeFrames();
1148                updateRunning();
1149
1150                // Reset AllApps to its initial state only if we are not in the middle of
1151                // processing a multi-step drop
1152                if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
1153                    mAppsCustomizeTabHost.reset();
1154                    showWorkspace(false);
1155                }
1156            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1157                mUserPresent = true;
1158                updateRunning();
1159            }
1160        }
1161    };
1162
1163    @Override
1164    public void onAttachedToWindow() {
1165        super.onAttachedToWindow();
1166
1167        // Listen for broadcasts related to user-presence
1168        final IntentFilter filter = new IntentFilter();
1169        filter.addAction(Intent.ACTION_SCREEN_OFF);
1170        filter.addAction(Intent.ACTION_USER_PRESENT);
1171        registerReceiver(mReceiver, filter);
1172
1173        mAttached = true;
1174        mVisible = true;
1175    }
1176
1177    @Override
1178    public void onDetachedFromWindow() {
1179        super.onDetachedFromWindow();
1180        mVisible = false;
1181
1182        if (mAttached) {
1183            unregisterReceiver(mReceiver);
1184            mAttached = false;
1185        }
1186        updateRunning();
1187    }
1188
1189    public void onWindowVisibilityChanged(int visibility) {
1190        mVisible = visibility == View.VISIBLE;
1191        updateRunning();
1192        // The following code used to be in onResume, but it turns out onResume is called when
1193        // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
1194        // is a more appropriate event to handle
1195        if (mVisible) {
1196            mAppsCustomizeTabHost.onWindowVisible();
1197            if (!mWorkspaceLoading) {
1198                final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
1199                // We want to let Launcher draw itself at least once before we force it to build
1200                // layers on all the workspace pages, so that transitioning to Launcher from other
1201                // apps is nice and speedy. Usually the first call to preDraw doesn't correspond to
1202                // a true draw so we wait until the second preDraw call to be safe
1203                observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
1204                    public boolean onPreDraw() {
1205                        // We delay the layer building a bit in order to give
1206                        // other message processing a time to run.  In particular
1207                        // this avoids a delay in hiding the IME if it was
1208                        // currently shown, because doing that may involve
1209                        // some communication back with the app.
1210                        mWorkspace.postDelayed(mBuildLayersRunnable, 500);
1211
1212                        // We had to enable the wallpaper visibility when launching apps from all
1213                        // apps (so that the transitions would be the same as when launching from
1214                        // workspace) so take this time to see if we need to re-disable the
1215                        // wallpaper visibility to ensure performance.
1216                        mWorkspace.post(new Runnable() {
1217                            @Override
1218                            public void run() {
1219                                disableWallpaperIfInAllApps();
1220                            }
1221                        });
1222
1223                        observer.removeOnPreDrawListener(this);
1224                        return true;
1225                    }
1226                });
1227            }
1228            // When Launcher comes back to foreground, a different Activity might be responsible for
1229            // the app market intent, so refresh the icon
1230            updateAppMarketIcon();
1231            clearTypedText();
1232        }
1233    }
1234
1235    private void sendAdvanceMessage(long delay) {
1236        mHandler.removeMessages(ADVANCE_MSG);
1237        Message msg = mHandler.obtainMessage(ADVANCE_MSG);
1238        mHandler.sendMessageDelayed(msg, delay);
1239        mAutoAdvanceSentTime = System.currentTimeMillis();
1240    }
1241
1242    private void updateRunning() {
1243        boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
1244        if (autoAdvanceRunning != mAutoAdvanceRunning) {
1245            mAutoAdvanceRunning = autoAdvanceRunning;
1246            if (autoAdvanceRunning) {
1247                long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
1248                sendAdvanceMessage(delay);
1249            } else {
1250                if (!mWidgetsToAdvance.isEmpty()) {
1251                    mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
1252                            (System.currentTimeMillis() - mAutoAdvanceSentTime));
1253                }
1254                mHandler.removeMessages(ADVANCE_MSG);
1255                mHandler.removeMessages(0); // Remove messages sent using postDelayed()
1256            }
1257        }
1258    }
1259
1260    private final Handler mHandler = new Handler() {
1261        @Override
1262        public void handleMessage(Message msg) {
1263            if (msg.what == ADVANCE_MSG) {
1264                int i = 0;
1265                for (View key: mWidgetsToAdvance.keySet()) {
1266                    final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
1267                    final int delay = mAdvanceStagger * i;
1268                    if (v instanceof Advanceable) {
1269                       postDelayed(new Runnable() {
1270                           public void run() {
1271                               ((Advanceable) v).advance();
1272                           }
1273                       }, delay);
1274                    }
1275                    i++;
1276                }
1277                sendAdvanceMessage(mAdvanceInterval);
1278            }
1279        }
1280    };
1281
1282    void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1283        if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
1284        View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1285        if (v instanceof Advanceable) {
1286            mWidgetsToAdvance.put(hostView, appWidgetInfo);
1287            ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1288            updateRunning();
1289        }
1290    }
1291
1292    void removeWidgetToAutoAdvance(View hostView) {
1293        if (mWidgetsToAdvance.containsKey(hostView)) {
1294            mWidgetsToAdvance.remove(hostView);
1295            updateRunning();
1296        }
1297    }
1298
1299    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1300        removeWidgetToAutoAdvance(launcherInfo.hostView);
1301        launcherInfo.hostView = null;
1302    }
1303
1304    void showOutOfSpaceMessage(boolean isHotseatLayout) {
1305        int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
1306        Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
1307    }
1308
1309    public LauncherAppWidgetHost getAppWidgetHost() {
1310        return mAppWidgetHost;
1311    }
1312
1313    public LauncherModel getModel() {
1314        return mModel;
1315    }
1316
1317    void closeSystemDialogs() {
1318        getWindow().closeAllPanels();
1319
1320        // Whatever we were doing is hereby canceled.
1321        mWaitingForResult = false;
1322    }
1323
1324    @Override
1325    protected void onNewIntent(Intent intent) {
1326        super.onNewIntent(intent);
1327
1328        // Close the menu
1329        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1330            // also will cancel mWaitingForResult.
1331            closeSystemDialogs();
1332
1333            boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1334                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1335
1336            Folder openFolder = mWorkspace.getOpenFolder();
1337            // In all these cases, only animate if we're already on home
1338            mWorkspace.exitWidgetResizeMode();
1339            if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
1340                    openFolder == null) {
1341                mWorkspace.moveToDefaultScreen(true);
1342            }
1343
1344            closeFolder();
1345            exitSpringLoadedDragMode();
1346            showWorkspace(alreadyOnHome);
1347
1348            final View v = getWindow().peekDecorView();
1349            if (v != null && v.getWindowToken() != null) {
1350                InputMethodManager imm = (InputMethodManager)getSystemService(
1351                        INPUT_METHOD_SERVICE);
1352                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1353            }
1354
1355            // Reset AllApps to its initial state
1356            if (!alreadyOnHome && mAppsCustomizeTabHost != null) {
1357                mAppsCustomizeTabHost.reset();
1358            }
1359        }
1360    }
1361
1362    @Override
1363    protected void onRestoreInstanceState(Bundle savedInstanceState) {
1364        // Do not call super here
1365        mSavedInstanceState = savedInstanceState;
1366    }
1367
1368    @Override
1369    protected void onSaveInstanceState(Bundle outState) {
1370        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentPage());
1371        super.onSaveInstanceState(outState);
1372
1373        outState.putInt(RUNTIME_STATE, mState.ordinal());
1374        // We close any open folder since it will not be re-opened, and we need to make sure
1375        // this state is reflected.
1376        closeFolder();
1377
1378        if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 &&
1379                mWaitingForResult) {
1380            outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
1381            outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen);
1382            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
1383            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
1384            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
1385            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
1386            outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
1387        }
1388
1389        if (mFolderInfo != null && mWaitingForResult) {
1390            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1391            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1392        }
1393
1394        // Save the current AppsCustomize tab
1395        if (mAppsCustomizeTabHost != null) {
1396            String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
1397            if (currentTabTag != null) {
1398                outState.putString("apps_customize_currentTab", currentTabTag);
1399            }
1400            int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
1401            outState.putInt("apps_customize_currentIndex", currentIndex);
1402        }
1403    }
1404
1405    @Override
1406    public void onDestroy() {
1407        super.onDestroy();
1408
1409        // Remove all pending runnables
1410        mHandler.removeMessages(ADVANCE_MSG);
1411        mHandler.removeMessages(0);
1412        mWorkspace.removeCallbacks(mBuildLayersRunnable);
1413
1414        // Stop callbacks from LauncherModel
1415        LauncherApplication app = ((LauncherApplication) getApplication());
1416        mModel.stopLoader();
1417        app.setLauncher(null);
1418
1419        try {
1420            mAppWidgetHost.stopListening();
1421        } catch (NullPointerException ex) {
1422            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1423        }
1424        mAppWidgetHost = null;
1425
1426        mWidgetsToAdvance.clear();
1427
1428        TextKeyListener.getInstance().release();
1429
1430
1431        unbindWorkspaceAndHotseatItems();
1432
1433        getContentResolver().unregisterContentObserver(mWidgetObserver);
1434        unregisterReceiver(mCloseSystemDialogsReceiver);
1435
1436        mDragLayer.clearAllResizeFrames();
1437        ((ViewGroup) mWorkspace.getParent()).removeAllViews();
1438        mWorkspace.removeAllViews();
1439        mWorkspace = null;
1440        mDragController = null;
1441
1442        ValueAnimator.clearAllAnimations();
1443    }
1444
1445    public DragController getDragController() {
1446        return mDragController;
1447    }
1448
1449    @Override
1450    public void startActivityForResult(Intent intent, int requestCode) {
1451        if (requestCode >= 0) mWaitingForResult = true;
1452        super.startActivityForResult(intent, requestCode);
1453    }
1454
1455    /**
1456     * Indicates that we want global search for this activity by setting the globalSearch
1457     * argument for {@link #startSearch} to true.
1458     */
1459    @Override
1460    public void startSearch(String initialQuery, boolean selectInitialQuery,
1461            Bundle appSearchData, boolean globalSearch) {
1462
1463        showWorkspace(true);
1464
1465        if (initialQuery == null) {
1466            // Use any text typed in the launcher as the initial query
1467            initialQuery = getTypedText();
1468        }
1469        if (appSearchData == null) {
1470            appSearchData = new Bundle();
1471            appSearchData.putString(Search.SOURCE, "launcher-search");
1472        }
1473        Rect sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
1474
1475        final SearchManager searchManager =
1476                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1477        searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
1478            appSearchData, globalSearch, sourceBounds);
1479    }
1480
1481    @Override
1482    public boolean onCreateOptionsMenu(Menu menu) {
1483        if (isWorkspaceLocked()) {
1484            return false;
1485        }
1486
1487        super.onCreateOptionsMenu(menu);
1488
1489        Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
1490        manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1491                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1492        Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1493        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1494                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1495        String helpUrl = getString(R.string.help_url);
1496        Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
1497        help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1498                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1499
1500        menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1501            .setIcon(android.R.drawable.ic_menu_gallery)
1502            .setAlphabeticShortcut('W');
1503        menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
1504            .setIcon(android.R.drawable.ic_menu_manage)
1505            .setIntent(manageApps)
1506            .setAlphabeticShortcut('M');
1507        menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings)
1508            .setIcon(android.R.drawable.ic_menu_preferences)
1509            .setIntent(settings)
1510            .setAlphabeticShortcut('P');
1511        if (!helpUrl.isEmpty()) {
1512            menu.add(0, MENU_HELP, 0, R.string.menu_help)
1513                .setIcon(android.R.drawable.ic_menu_help)
1514                .setIntent(help)
1515                .setAlphabeticShortcut('H');
1516        }
1517        return true;
1518    }
1519
1520    @Override
1521    public boolean onPrepareOptionsMenu(Menu menu) {
1522        super.onPrepareOptionsMenu(menu);
1523
1524        if (mAppsCustomizeTabHost.isTransitioning()) {
1525            return false;
1526        }
1527        boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE);
1528        menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible);
1529
1530        return true;
1531    }
1532
1533    @Override
1534    public boolean onOptionsItemSelected(MenuItem item) {
1535        switch (item.getItemId()) {
1536        case MENU_WALLPAPER_SETTINGS:
1537            startWallpaper();
1538            return true;
1539        }
1540
1541        return super.onOptionsItemSelected(item);
1542    }
1543
1544    @Override
1545    public boolean onSearchRequested() {
1546        startSearch(null, false, null, true);
1547        // Use a custom animation for launching search
1548        overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
1549        return true;
1550    }
1551
1552    public boolean isWorkspaceLocked() {
1553        return mWorkspaceLoading || mWaitingForResult;
1554    }
1555
1556    private void resetAddInfo() {
1557        mPendingAddInfo.container = ItemInfo.NO_ID;
1558        mPendingAddInfo.screen = -1;
1559        mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
1560        mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
1561        mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1;
1562        mPendingAddInfo.dropPos = null;
1563    }
1564
1565    void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget,
1566            AppWidgetProviderInfo appWidgetInfo) {
1567        if (appWidgetInfo.configure != null) {
1568            mPendingAddWidgetInfo = appWidgetInfo;
1569
1570            // Launch over to configure widget, if needed
1571            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1572            intent.setComponent(appWidgetInfo.configure);
1573            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1574            startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
1575        } else {
1576            // Otherwise just add it
1577            completeAddAppWidget(appWidgetId, info.container, info.screen, boundWidget,
1578                    appWidgetInfo);
1579            // Exit spring loaded mode if necessary after adding the widget
1580            exitSpringLoadedDragModeDelayed(true, false, null);
1581        }
1582    }
1583
1584    /**
1585     * Process a shortcut drop.
1586     *
1587     * @param componentName The name of the component
1588     * @param screen The screen where it should be added
1589     * @param cell The cell it should be added to, optional
1590     * @param position The location on the screen where it was dropped, optional
1591     */
1592    void processShortcutFromDrop(ComponentName componentName, long container, int screen,
1593            int[] cell, int[] loc) {
1594        resetAddInfo();
1595        mPendingAddInfo.container = container;
1596        mPendingAddInfo.screen = screen;
1597        mPendingAddInfo.dropPos = loc;
1598
1599        if (cell != null) {
1600            mPendingAddInfo.cellX = cell[0];
1601            mPendingAddInfo.cellY = cell[1];
1602        }
1603
1604        Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1605        createShortcutIntent.setComponent(componentName);
1606        processShortcut(createShortcutIntent);
1607    }
1608
1609    /**
1610     * Process a widget drop.
1611     *
1612     * @param info The PendingAppWidgetInfo of the widget being added.
1613     * @param screen The screen where it should be added
1614     * @param cell The cell it should be added to, optional
1615     * @param position The location on the screen where it was dropped, optional
1616     */
1617    void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen,
1618            int[] cell, int[] span, int[] loc) {
1619        resetAddInfo();
1620        mPendingAddInfo.container = info.container = container;
1621        mPendingAddInfo.screen = info.screen = screen;
1622        mPendingAddInfo.dropPos = loc;
1623        mPendingAddInfo.minSpanX = info.minSpanX;
1624        mPendingAddInfo.minSpanY = info.minSpanY;
1625
1626        if (cell != null) {
1627            mPendingAddInfo.cellX = cell[0];
1628            mPendingAddInfo.cellY = cell[1];
1629        }
1630        if (span != null) {
1631            mPendingAddInfo.spanX = span[0];
1632            mPendingAddInfo.spanY = span[1];
1633        }
1634
1635        AppWidgetHostView hostView = info.boundWidget;
1636        int appWidgetId;
1637        if (hostView != null) {
1638            appWidgetId = hostView.getAppWidgetId();
1639            addAppWidgetImpl(appWidgetId, info, hostView, info.info);
1640        } else {
1641            // In this case, we either need to start an activity to get permission to bind
1642            // the widget, or we need to start an activity to configure the widget, or both.
1643            appWidgetId = getAppWidgetHost().allocateAppWidgetId();
1644            if (mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.componentName)) {
1645                addAppWidgetImpl(appWidgetId, info, null, info.info);
1646            } else {
1647                mPendingAddWidgetInfo = info.info;
1648                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
1649                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1650                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
1651                startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
1652            }
1653        }
1654    }
1655
1656    void processShortcut(Intent intent) {
1657        // Handle case where user selected "Applications"
1658        String applicationName = getResources().getString(R.string.group_applications);
1659        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1660
1661        if (applicationName != null && applicationName.equals(shortcutName)) {
1662            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1663            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1664
1665            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1666            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1667            pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
1668            startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
1669        } else {
1670            startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
1671        }
1672    }
1673
1674    void processWallpaper(Intent intent) {
1675        startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
1676    }
1677
1678    FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX,
1679            int cellY) {
1680        final FolderInfo folderInfo = new FolderInfo();
1681        folderInfo.title = getText(R.string.folder_name);
1682
1683        // Update the model
1684        LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY,
1685                false);
1686        sFolders.put(folderInfo.id, folderInfo);
1687
1688        // Create the view
1689        FolderIcon newFolder =
1690            FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
1691        mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1,
1692                isWorkspaceLocked());
1693        return newFolder;
1694    }
1695
1696    void removeFolder(FolderInfo folder) {
1697        sFolders.remove(folder.id);
1698    }
1699
1700    private void startWallpaper() {
1701        showWorkspace(true);
1702        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1703        Intent chooser = Intent.createChooser(pickWallpaper,
1704                getText(R.string.chooser_wallpaper));
1705        // NOTE: Adds a configure option to the chooser if the wallpaper supports it
1706        //       Removed in Eclair MR1
1707//        WallpaperManager wm = (WallpaperManager)
1708//                getSystemService(Context.WALLPAPER_SERVICE);
1709//        WallpaperInfo wi = wm.getWallpaperInfo();
1710//        if (wi != null && wi.getSettingsActivity() != null) {
1711//            LabeledIntent li = new LabeledIntent(getPackageName(),
1712//                    R.string.configure_wallpaper, 0);
1713//            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
1714//            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
1715//        }
1716        startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
1717    }
1718
1719    /**
1720     * Registers various content observers. The current implementation registers
1721     * only a favorites observer to keep track of the favorites applications.
1722     */
1723    private void registerContentObservers() {
1724        ContentResolver resolver = getContentResolver();
1725        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
1726                true, mWidgetObserver);
1727    }
1728
1729    @Override
1730    public boolean dispatchKeyEvent(KeyEvent event) {
1731        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1732            switch (event.getKeyCode()) {
1733                case KeyEvent.KEYCODE_HOME:
1734                    return true;
1735                case KeyEvent.KEYCODE_VOLUME_DOWN:
1736                    if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) {
1737                        dumpState();
1738                        return true;
1739                    }
1740                    break;
1741            }
1742        } else if (event.getAction() == KeyEvent.ACTION_UP) {
1743            switch (event.getKeyCode()) {
1744                case KeyEvent.KEYCODE_HOME:
1745                    return true;
1746            }
1747        }
1748
1749        return super.dispatchKeyEvent(event);
1750    }
1751
1752    @Override
1753    public void onBackPressed() {
1754        if (mState == State.APPS_CUSTOMIZE) {
1755            showWorkspace(true);
1756        } else if (mWorkspace.getOpenFolder() != null) {
1757            Folder openFolder = mWorkspace.getOpenFolder();
1758            if (openFolder.isEditingName()) {
1759                openFolder.dismissEditingName();
1760            } else {
1761                closeFolder();
1762            }
1763        } else {
1764            mWorkspace.exitWidgetResizeMode();
1765
1766            // Back button is a no-op here, but give at least some feedback for the button press
1767            mWorkspace.showOutlinesTemporarily();
1768        }
1769    }
1770
1771    /**
1772     * Re-listen when widgets are reset.
1773     */
1774    private void onAppWidgetReset() {
1775        if (mAppWidgetHost != null) {
1776            mAppWidgetHost.startListening();
1777        }
1778    }
1779
1780    /**
1781     * Go through the and disconnect any of the callbacks in the drawables and the views or we
1782     * leak the previous Home screen on orientation change.
1783     */
1784    private void unbindWorkspaceAndHotseatItems() {
1785        if (mModel != null) {
1786            mModel.unbindWorkspaceItems();
1787        }
1788    }
1789
1790    /**
1791     * Launches the intent referred by the clicked shortcut.
1792     *
1793     * @param v The view representing the clicked shortcut.
1794     */
1795    public void onClick(View v) {
1796        // Make sure that rogue clicks don't get through while allapps is launching, or after the
1797        // view has detached (it's possible for this to happen if the view is removed mid touch).
1798        if (v.getWindowToken() == null) {
1799            return;
1800        }
1801
1802        if (!mWorkspace.isFinishedSwitchingState()) {
1803            return;
1804        }
1805
1806        Object tag = v.getTag();
1807        if (tag instanceof ShortcutInfo) {
1808            // Open shortcut
1809            final Intent intent = ((ShortcutInfo) tag).intent;
1810            int[] pos = new int[2];
1811            v.getLocationOnScreen(pos);
1812            intent.setSourceBounds(new Rect(pos[0], pos[1],
1813                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
1814
1815            boolean success = startActivitySafely(v, intent, tag);
1816
1817            if (success && v instanceof BubbleTextView) {
1818                mWaitingForResume = (BubbleTextView) v;
1819                mWaitingForResume.setStayPressed(true);
1820            }
1821        } else if (tag instanceof FolderInfo) {
1822            if (v instanceof FolderIcon) {
1823                FolderIcon fi = (FolderIcon) v;
1824                handleFolderClick(fi);
1825            }
1826        } else if (v == mAllAppsButton) {
1827            if (mState == State.APPS_CUSTOMIZE) {
1828                showWorkspace(true);
1829            } else {
1830                onClickAllAppsButton(v);
1831            }
1832        }
1833    }
1834
1835    public boolean onTouch(View v, MotionEvent event) {
1836        // this is an intercepted event being forwarded from mWorkspace;
1837        // clicking anywhere on the workspace causes the customization drawer to slide down
1838        showWorkspace(true);
1839        return false;
1840    }
1841
1842    /**
1843     * Event handler for the search button
1844     *
1845     * @param v The view that was clicked.
1846     */
1847    public void onClickSearchButton(View v) {
1848        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
1849
1850        onSearchRequested();
1851    }
1852
1853    /**
1854     * Event handler for the voice button
1855     *
1856     * @param v The view that was clicked.
1857     */
1858    public void onClickVoiceButton(View v) {
1859        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
1860
1861        try {
1862            final SearchManager searchManager =
1863                    (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1864            ComponentName activityName = searchManager.getGlobalSearchActivity();
1865            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1866            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1867                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1868            if (activityName != null) {
1869                intent.setPackage(activityName.getPackageName());
1870            }
1871            startActivity(null, intent, "onClickVoiceButton");
1872        } catch (ActivityNotFoundException e) {
1873            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1874            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1875                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1876            startActivitySafely(null, intent, "onClickVoiceButton");
1877        }
1878    }
1879
1880    /**
1881     * Event handler for the "grid" button that appears on the home screen, which
1882     * enters all apps mode.
1883     *
1884     * @param v The view that was clicked.
1885     */
1886    public void onClickAllAppsButton(View v) {
1887        showAllApps(true);
1888    }
1889
1890    public void onTouchDownAllAppsButton(View v) {
1891        // Provide the same haptic feedback that the system offers for virtual keys.
1892        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
1893    }
1894
1895    public void onClickAppMarketButton(View v) {
1896        if (mAppMarketIntent != null) {
1897            startActivitySafely(v, mAppMarketIntent, "app market");
1898        } else {
1899            Log.e(TAG, "Invalid app market intent.");
1900        }
1901    }
1902
1903    void startApplicationDetailsActivity(ComponentName componentName) {
1904        String packageName = componentName.getPackageName();
1905        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
1906                Uri.fromParts("package", packageName, null));
1907        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1908        startActivitySafely(null, intent, "startApplicationDetailsActivity");
1909    }
1910
1911    void startApplicationUninstallActivity(ApplicationInfo appInfo) {
1912        if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
1913            // System applications cannot be installed. For now, show a toast explaining that.
1914            // We may give them the option of disabling apps this way.
1915            int messageId = R.string.uninstall_system_app_text;
1916            Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
1917        } else {
1918            String packageName = appInfo.componentName.getPackageName();
1919            String className = appInfo.componentName.getClassName();
1920            Intent intent = new Intent(
1921                    Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
1922            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1923                    Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1924            startActivity(intent);
1925        }
1926    }
1927
1928    boolean startActivity(View v, Intent intent, Object tag) {
1929        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1930
1931        try {
1932            // Only launch using the new animation if the shortcut has not opted out (this is a
1933            // private contract between launcher and may be ignored in the future).
1934            boolean useLaunchAnimation = (v != null) &&
1935                    !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
1936            if (useLaunchAnimation) {
1937                ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
1938                        v.getMeasuredWidth(), v.getMeasuredHeight());
1939
1940                startActivity(intent, opts.toBundle());
1941            } else {
1942                startActivity(intent);
1943            }
1944            return true;
1945        } catch (SecurityException e) {
1946            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1947            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1948                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1949                    "or use the exported attribute for this activity. "
1950                    + "tag="+ tag + " intent=" + intent, e);
1951        }
1952        return false;
1953    }
1954
1955    boolean startActivitySafely(View v, Intent intent, Object tag) {
1956        boolean success = false;
1957        try {
1958            success = startActivity(v, intent, tag);
1959        } catch (ActivityNotFoundException e) {
1960            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1961            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
1962        }
1963        return success;
1964    }
1965
1966    void startActivityForResultSafely(Intent intent, int requestCode) {
1967        try {
1968            startActivityForResult(intent, requestCode);
1969        } catch (ActivityNotFoundException e) {
1970            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1971        } catch (SecurityException e) {
1972            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1973            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1974                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1975                    "or use the exported attribute for this activity.", e);
1976        }
1977    }
1978
1979    private void handleFolderClick(FolderIcon folderIcon) {
1980        final FolderInfo info = folderIcon.mInfo;
1981        Folder openFolder = mWorkspace.getFolderForTag(info);
1982
1983        // If the folder info reports that the associated folder is open, then verify that
1984        // it is actually opened. There have been a few instances where this gets out of sync.
1985        if (info.opened && openFolder == null) {
1986            Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
1987                    + info.screen + " (" + info.cellX + ", " + info.cellY + ")");
1988            info.opened = false;
1989        }
1990
1991        if (!info.opened) {
1992            // Close any open folder
1993            closeFolder();
1994            // Open the requested folder
1995            openFolder(folderIcon);
1996        } else {
1997            // Find the open folder...
1998            int folderScreen;
1999            if (openFolder != null) {
2000                folderScreen = mWorkspace.getPageForView(openFolder);
2001                // .. and close it
2002                closeFolder(openFolder);
2003                if (folderScreen != mWorkspace.getCurrentPage()) {
2004                    // Close any folder open on the current screen
2005                    closeFolder();
2006                    // Pull the folder onto this screen
2007                    openFolder(folderIcon);
2008                }
2009            }
2010        }
2011    }
2012
2013    private void growAndFadeOutFolderIcon(FolderIcon fi) {
2014        if (fi == null) return;
2015        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
2016        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
2017        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
2018
2019        FolderInfo info = (FolderInfo) fi.getTag();
2020        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2021            CellLayout cl = (CellLayout) fi.getParent().getParent();
2022            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
2023            cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
2024        }
2025
2026        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
2027        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
2028        oa.start();
2029    }
2030
2031    private void shrinkAndFadeInFolderIcon(FolderIcon fi) {
2032        if (fi == null) return;
2033        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
2034        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
2035        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
2036
2037        FolderInfo info = (FolderInfo) fi.getTag();
2038        CellLayout cl = null;
2039        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2040            cl = (CellLayout) fi.getParent().getParent();
2041        }
2042
2043        final CellLayout layout = cl;
2044        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
2045        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
2046        oa.addListener(new AnimatorListenerAdapter() {
2047            @Override
2048            public void onAnimationEnd(Animator animation) {
2049                if (layout != null) {
2050                    layout.clearFolderLeaveBehind();
2051                }
2052            }
2053        });
2054        oa.start();
2055    }
2056
2057    /**
2058     * Opens the user folder described by the specified tag. The opening of the folder
2059     * is animated relative to the specified View. If the View is null, no animation
2060     * is played.
2061     *
2062     * @param folderInfo The FolderInfo describing the folder to open.
2063     */
2064    public void openFolder(FolderIcon folderIcon) {
2065        Folder folder = folderIcon.mFolder;
2066        FolderInfo info = folder.mInfo;
2067
2068        growAndFadeOutFolderIcon(folderIcon);
2069        info.opened = true;
2070
2071        // Just verify that the folder hasn't already been added to the DragLayer.
2072        // There was a one-off crash where the folder had a parent already.
2073        if (folder.getParent() == null) {
2074            mDragLayer.addView(folder);
2075            mDragController.addDropTarget((DropTarget) folder);
2076        } else {
2077            Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
2078                    folder.getParent() + ").");
2079        }
2080        folder.animateOpen();
2081    }
2082
2083    public void closeFolder() {
2084        Folder folder = mWorkspace.getOpenFolder();
2085        if (folder != null) {
2086            if (folder.isEditingName()) {
2087                folder.dismissEditingName();
2088            }
2089            closeFolder(folder);
2090
2091            // Dismiss the folder cling
2092            dismissFolderCling(null);
2093        }
2094    }
2095
2096    void closeFolder(Folder folder) {
2097        folder.getInfo().opened = false;
2098
2099        ViewGroup parent = (ViewGroup) folder.getParent().getParent();
2100        if (parent != null) {
2101            FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
2102            shrinkAndFadeInFolderIcon(fi);
2103        }
2104        folder.animateClosed();
2105    }
2106
2107    public boolean onLongClick(View v) {
2108        if (!isDraggingEnabled()) return false;
2109        if (isWorkspaceLocked()) return false;
2110        if (mState != State.WORKSPACE) return false;
2111
2112        if (!(v instanceof CellLayout)) {
2113            v = (View) v.getParent().getParent();
2114        }
2115
2116        resetAddInfo();
2117        CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
2118        // This happens when long clicking an item with the dpad/trackball
2119        if (longClickCellInfo == null) {
2120            return true;
2121        }
2122
2123        // The hotseat touch handling does not go through Workspace, and we always allow long press
2124        // on hotseat items.
2125        final View itemUnderLongClick = longClickCellInfo.cell;
2126        boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
2127        if (allowLongPress && !mDragController.isDragging()) {
2128            if (itemUnderLongClick == null) {
2129                // User long pressed on empty space
2130                mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
2131                        HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
2132                startWallpaper();
2133            } else {
2134                if (!(itemUnderLongClick instanceof Folder)) {
2135                    // User long pressed on an item
2136                    mWorkspace.startDrag(longClickCellInfo);
2137                }
2138            }
2139        }
2140        return true;
2141    }
2142
2143    boolean isHotseatLayout(View layout) {
2144        return mHotseat != null && layout != null &&
2145                (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
2146    }
2147    Hotseat getHotseat() {
2148        return mHotseat;
2149    }
2150    SearchDropTargetBar getSearchBar() {
2151        return mSearchDropTargetBar;
2152    }
2153
2154    /**
2155     * Returns the CellLayout of the specified container at the specified screen.
2156     */
2157    CellLayout getCellLayout(long container, int screen) {
2158        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2159            if (mHotseat != null) {
2160                return mHotseat.getLayout();
2161            } else {
2162                return null;
2163            }
2164        } else {
2165            return (CellLayout) mWorkspace.getChildAt(screen);
2166        }
2167    }
2168
2169    Workspace getWorkspace() {
2170        return mWorkspace;
2171    }
2172
2173    // Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
2174    public boolean isAllAppsVisible() {
2175        return (mState == State.APPS_CUSTOMIZE);
2176    }
2177
2178    public boolean isAllAppsButtonRank(int rank) {
2179        return mHotseat.isAllAppsButtonRank(rank);
2180    }
2181
2182    // AllAppsView.Watcher
2183    public void zoomed(float zoom) {
2184        if (zoom == 1.0f) {
2185            mWorkspace.setVisibility(View.GONE);
2186        }
2187    }
2188
2189    /**
2190     * Helper method for the cameraZoomIn/cameraZoomOut animations
2191     * @param view The view being animated
2192     * @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE)
2193     * @param scaleFactor The scale factor used for the zoom
2194     */
2195    private void setPivotsForZoom(View view, float scaleFactor) {
2196        view.setPivotX(view.getWidth() / 2.0f);
2197        view.setPivotY(view.getHeight() / 2.0f);
2198    }
2199
2200    void disableWallpaperIfInAllApps() {
2201        // Only disable it if we are in all apps
2202        if (mState == State.APPS_CUSTOMIZE) {
2203            if (mAppsCustomizeTabHost != null &&
2204                    !mAppsCustomizeTabHost.isTransitioning()) {
2205                updateWallpaperVisibility(false);
2206            }
2207        }
2208    }
2209
2210    void updateWallpaperVisibility(boolean visible) {
2211        int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
2212        int curflags = getWindow().getAttributes().flags
2213                & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
2214        if (wpflags != curflags) {
2215            getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
2216        }
2217    }
2218
2219    private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) {
2220        if (v instanceof LauncherTransitionable) {
2221            ((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace);
2222        }
2223    }
2224
2225    private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) {
2226        if (v instanceof LauncherTransitionable) {
2227            ((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace);
2228        }
2229
2230        // Update the workspace transition step as well
2231        dispatchOnLauncherTransitionStep(v, 0f);
2232    }
2233
2234    private void dispatchOnLauncherTransitionStep(View v, float t) {
2235        if (v instanceof LauncherTransitionable) {
2236            ((LauncherTransitionable) v).onLauncherTransitionStep(this, t);
2237        }
2238    }
2239
2240    private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) {
2241        if (v instanceof LauncherTransitionable) {
2242            ((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace);
2243        }
2244
2245        // Update the workspace transition step as well
2246        dispatchOnLauncherTransitionStep(v, 1f);
2247    }
2248
2249    /**
2250     * Things to test when changing the following seven functions.
2251     *   - Home from workspace
2252     *          - from center screen
2253     *          - from other screens
2254     *   - Home from all apps
2255     *          - from center screen
2256     *          - from other screens
2257     *   - Back from all apps
2258     *          - from center screen
2259     *          - from other screens
2260     *   - Launch app from workspace and quit
2261     *          - with back
2262     *          - with home
2263     *   - Launch app from all apps and quit
2264     *          - with back
2265     *          - with home
2266     *   - Go to a screen that's not the default, then all
2267     *     apps, and launch and app, and go back
2268     *          - with back
2269     *          -with home
2270     *   - On workspace, long press power and go back
2271     *          - with back
2272     *          - with home
2273     *   - On all apps, long press power and go back
2274     *          - with back
2275     *          - with home
2276     *   - On workspace, power off
2277     *   - On all apps, power off
2278     *   - Launch an app and turn off the screen while in that app
2279     *          - Go back with home key
2280     *          - Go back with back key  TODO: make this not go to workspace
2281     *          - From all apps
2282     *          - From workspace
2283     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2284     *          - From all apps
2285     *          - From the center workspace
2286     *          - From another workspace
2287     */
2288
2289    /**
2290     * Zoom the camera out from the workspace to reveal 'toView'.
2291     * Assumes that the view to show is anchored at either the very top or very bottom
2292     * of the screen.
2293     */
2294    private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
2295        if (mStateAnimation != null) {
2296            mStateAnimation.cancel();
2297            mStateAnimation = null;
2298        }
2299        final Resources res = getResources();
2300
2301        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
2302        final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
2303        final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2304        final View fromView = mWorkspace;
2305        final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
2306        final int startDelay =
2307                res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
2308
2309        setPivotsForZoom(toView, scale);
2310
2311        // Shrink workspaces away if going to AppsCustomize from workspace
2312        Animator workspaceAnim =
2313                mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
2314
2315        if (animated) {
2316            toView.setScaleX(scale);
2317            toView.setScaleY(scale);
2318            final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
2319            scaleAnim.
2320                scaleX(1f).scaleY(1f).
2321                setDuration(duration).
2322                setInterpolator(new Workspace.ZoomOutInterpolator());
2323
2324            toView.setVisibility(View.VISIBLE);
2325            toView.setAlpha(0f);
2326            final ObjectAnimator alphaAnim = ObjectAnimator
2327                .ofFloat(toView, "alpha", 0f, 1f)
2328                .setDuration(fadeDuration);
2329            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2330            alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
2331                @Override
2332                public void onAnimationUpdate(ValueAnimator animation) {
2333                    float t = (Float) animation.getAnimatedValue();
2334                    dispatchOnLauncherTransitionStep(fromView, t);
2335                    dispatchOnLauncherTransitionStep(toView, t);
2336                }
2337            });
2338
2339            // toView should appear right at the end of the workspace shrink
2340            // animation
2341            mStateAnimation = new AnimatorSet();
2342            mStateAnimation.play(scaleAnim).after(startDelay);
2343            mStateAnimation.play(alphaAnim).after(startDelay);
2344
2345            mStateAnimation.addListener(new AnimatorListenerAdapter() {
2346                boolean animationCancelled = false;
2347
2348                @Override
2349                public void onAnimationStart(Animator animation) {
2350                    updateWallpaperVisibility(true);
2351                    // Prepare the position
2352                    toView.setTranslationX(0.0f);
2353                    toView.setTranslationY(0.0f);
2354                    toView.setVisibility(View.VISIBLE);
2355                    toView.bringToFront();
2356                }
2357                @Override
2358                public void onAnimationEnd(Animator animation) {
2359                    dispatchOnLauncherTransitionEnd(fromView, animated, false);
2360                    dispatchOnLauncherTransitionEnd(toView, animated, false);
2361
2362                    if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2363                        // Hide the workspace scrollbar
2364                        mWorkspace.hideScrollingIndicator(true);
2365                        hideDockDivider();
2366                    }
2367                    if (!animationCancelled) {
2368                        updateWallpaperVisibility(false);
2369                    }
2370                }
2371
2372                @Override
2373                public void onAnimationCancel(Animator animation) {
2374                    animationCancelled = true;
2375                }
2376            });
2377
2378            if (workspaceAnim != null) {
2379                mStateAnimation.play(workspaceAnim);
2380            }
2381
2382            boolean delayAnim = false;
2383            final ViewTreeObserver observer;
2384
2385            dispatchOnLauncherTransitionPrepare(fromView, animated, false);
2386            dispatchOnLauncherTransitionPrepare(toView, animated, false);
2387
2388            // If any of the objects being animated haven't been measured/laid out
2389            // yet, delay the animation until we get a layout pass
2390            if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
2391                    (mWorkspace.getMeasuredWidth() == 0) ||
2392                    (toView.getMeasuredWidth() == 0)) {
2393                observer = mWorkspace.getViewTreeObserver();
2394                delayAnim = true;
2395            } else {
2396                observer = null;
2397            }
2398
2399            if (delayAnim) {
2400                final AnimatorSet stateAnimation = mStateAnimation;
2401                final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
2402                    public void onGlobalLayout() {
2403                        mWorkspace.post(new Runnable() {
2404                            public void run() {
2405                                // Check that mStateAnimation hasn't changed while
2406                                // we waited for a layout pass
2407                                if (mStateAnimation == stateAnimation) {
2408                                    // Need to update pivots for zoom if layout changed
2409                                    setPivotsForZoom(toView, scale);
2410                                    dispatchOnLauncherTransitionStart(fromView, animated, false);
2411                                    dispatchOnLauncherTransitionStart(toView, animated, false);
2412                                    mStateAnimation.start();
2413                                }
2414                            }
2415                        });
2416                        observer.removeOnGlobalLayoutListener(this);
2417                    }
2418                };
2419                observer.addOnGlobalLayoutListener(delayedStart);
2420            } else {
2421                setPivotsForZoom(toView, scale);
2422                dispatchOnLauncherTransitionStart(fromView, animated, false);
2423                dispatchOnLauncherTransitionStart(toView, animated, false);
2424                mStateAnimation.start();
2425            }
2426        } else {
2427            toView.setTranslationX(0.0f);
2428            toView.setTranslationY(0.0f);
2429            toView.setScaleX(1.0f);
2430            toView.setScaleY(1.0f);
2431            toView.setVisibility(View.VISIBLE);
2432            toView.bringToFront();
2433
2434            if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2435                // Hide the workspace scrollbar
2436                mWorkspace.hideScrollingIndicator(true);
2437                hideDockDivider();
2438            }
2439            dispatchOnLauncherTransitionPrepare(fromView, animated, false);
2440            dispatchOnLauncherTransitionStart(fromView, animated, false);
2441            dispatchOnLauncherTransitionEnd(fromView, animated, false);
2442            dispatchOnLauncherTransitionPrepare(toView, animated, false);
2443            dispatchOnLauncherTransitionStart(toView, animated, false);
2444            dispatchOnLauncherTransitionEnd(toView, animated, false);
2445            updateWallpaperVisibility(false);
2446        }
2447    }
2448
2449    /**
2450     * Zoom the camera back into the workspace, hiding 'fromView'.
2451     * This is the opposite of showAppsCustomizeHelper.
2452     * @param animated If true, the transition will be animated.
2453     */
2454    private void hideAppsCustomizeHelper(State toState, final boolean animated,
2455            final boolean springLoaded, final Runnable onCompleteRunnable) {
2456
2457        if (mStateAnimation != null) {
2458            mStateAnimation.cancel();
2459            mStateAnimation = null;
2460        }
2461        Resources res = getResources();
2462
2463        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
2464        final int fadeOutDuration =
2465                res.getInteger(R.integer.config_appsCustomizeFadeOutTime);
2466        final float scaleFactor = (float)
2467                res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2468        final View fromView = mAppsCustomizeTabHost;
2469        final View toView = mWorkspace;
2470        Animator workspaceAnim = null;
2471
2472        if (toState == State.WORKSPACE) {
2473            int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger);
2474            workspaceAnim = mWorkspace.getChangeStateAnimation(
2475                    Workspace.State.NORMAL, animated, stagger);
2476        } else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2477            workspaceAnim = mWorkspace.getChangeStateAnimation(
2478                    Workspace.State.SPRING_LOADED, animated);
2479        }
2480
2481        setPivotsForZoom(fromView, scaleFactor);
2482        updateWallpaperVisibility(true);
2483        showHotseat(animated);
2484        if (animated) {
2485            final LauncherViewPropertyAnimator scaleAnim =
2486                    new LauncherViewPropertyAnimator(fromView);
2487            scaleAnim.
2488                scaleX(scaleFactor).scaleY(scaleFactor).
2489                setDuration(duration).
2490                setInterpolator(new Workspace.ZoomInInterpolator());
2491
2492            final ObjectAnimator alphaAnim = ObjectAnimator
2493                .ofFloat(fromView, "alpha", 1f, 0f)
2494                .setDuration(fadeOutDuration);
2495            alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator());
2496            alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
2497                @Override
2498                public void onAnimationUpdate(ValueAnimator animation) {
2499                    float t = 1f - (Float) animation.getAnimatedValue();
2500                    dispatchOnLauncherTransitionStep(fromView, t);
2501                    dispatchOnLauncherTransitionStep(toView, t);
2502                }
2503            });
2504
2505            mStateAnimation = new AnimatorSet();
2506
2507            dispatchOnLauncherTransitionPrepare(fromView, animated, true);
2508            dispatchOnLauncherTransitionPrepare(toView, animated, true);
2509
2510            mStateAnimation.addListener(new AnimatorListenerAdapter() {
2511                @Override
2512                public void onAnimationEnd(Animator animation) {
2513                    updateWallpaperVisibility(true);
2514                    fromView.setVisibility(View.GONE);
2515                    dispatchOnLauncherTransitionEnd(fromView, animated, true);
2516                    dispatchOnLauncherTransitionEnd(toView, animated, true);
2517                    if (mWorkspace != null) {
2518                        mWorkspace.hideScrollingIndicator(false);
2519                    }
2520                    if (onCompleteRunnable != null) {
2521                        onCompleteRunnable.run();
2522                    }
2523                }
2524            });
2525
2526            mStateAnimation.playTogether(scaleAnim, alphaAnim);
2527            if (workspaceAnim != null) {
2528                mStateAnimation.play(workspaceAnim);
2529            }
2530            dispatchOnLauncherTransitionStart(fromView, animated, true);
2531            dispatchOnLauncherTransitionStart(toView, animated, true);
2532            mStateAnimation.start();
2533        } else {
2534            fromView.setVisibility(View.GONE);
2535            dispatchOnLauncherTransitionPrepare(fromView, animated, true);
2536            dispatchOnLauncherTransitionStart(fromView, animated, true);
2537            dispatchOnLauncherTransitionEnd(fromView, animated, true);
2538            dispatchOnLauncherTransitionPrepare(toView, animated, true);
2539            dispatchOnLauncherTransitionStart(toView, animated, true);
2540            dispatchOnLauncherTransitionEnd(toView, animated, true);
2541            mWorkspace.hideScrollingIndicator(false);
2542        }
2543    }
2544
2545    @Override
2546    public void onTrimMemory(int level) {
2547        super.onTrimMemory(level);
2548        if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
2549            mAppsCustomizeTabHost.onTrimMemory();
2550        }
2551    }
2552
2553    @Override
2554    public void onWindowFocusChanged(boolean hasFocus) {
2555        if (!hasFocus) {
2556            // When another window occludes launcher (like the notification shade, or recents),
2557            // ensure that we enable the wallpaper flag so that transitions are done correctly.
2558            updateWallpaperVisibility(true);
2559        } else {
2560            // When launcher has focus again, disable the wallpaper if we are in AllApps
2561            disableWallpaperIfInAllApps();
2562        }
2563    }
2564
2565    void showWorkspace(boolean animated) {
2566        showWorkspace(animated, null);
2567    }
2568
2569    void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
2570        if (mState != State.WORKSPACE) {
2571            mWorkspace.setVisibility(View.VISIBLE);
2572            hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable);
2573
2574            // Show the search bar and hotseat
2575            mSearchDropTargetBar.showSearchBar(animated);
2576            // We only need to animate in the dock divider if we're going from spring loaded mode
2577            showDockDivider(animated && mState == State.APPS_CUSTOMIZE_SPRING_LOADED);
2578
2579            // Set focus to the AppsCustomize button
2580            if (mAllAppsButton != null) {
2581                mAllAppsButton.requestFocus();
2582            }
2583        }
2584
2585        mWorkspace.flashScrollingIndicator(animated);
2586
2587        // Change the state *after* we've called all the transition code
2588        mState = State.WORKSPACE;
2589
2590        // Resume the auto-advance of widgets
2591        mUserPresent = true;
2592        updateRunning();
2593
2594        // send an accessibility event to announce the context change
2595        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2596    }
2597
2598    void showAllApps(boolean animated) {
2599        if (mState != State.WORKSPACE) return;
2600
2601        showAppsCustomizeHelper(animated, false);
2602        mAppsCustomizeTabHost.requestFocus();
2603
2604        // Hide the search bar and hotseat
2605        mSearchDropTargetBar.hideSearchBar(animated);
2606
2607        // Change the state *after* we've called all the transition code
2608        mState = State.APPS_CUSTOMIZE;
2609
2610        // Pause the auto-advance of widgets until we are out of AllApps
2611        mUserPresent = false;
2612        updateRunning();
2613        closeFolder();
2614
2615        // Send an accessibility event to announce the context change
2616        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2617    }
2618
2619    void enterSpringLoadedDragMode() {
2620        if (mState == State.APPS_CUSTOMIZE) {
2621            hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null);
2622            hideDockDivider();
2623            mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
2624        }
2625    }
2626
2627    void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay,
2628            final Runnable onCompleteRunnable) {
2629        if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return;
2630
2631        mHandler.postDelayed(new Runnable() {
2632            @Override
2633            public void run() {
2634                if (successfulDrop) {
2635                    // Before we show workspace, hide all apps again because
2636                    // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
2637                    // clean up our state transition functions
2638                    mAppsCustomizeTabHost.setVisibility(View.GONE);
2639                    mSearchDropTargetBar.showSearchBar(true);
2640                    showWorkspace(true, onCompleteRunnable);
2641                } else {
2642                    exitSpringLoadedDragMode();
2643                }
2644            }
2645        }, (extendedDelay ?
2646                EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
2647                EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
2648    }
2649
2650    void exitSpringLoadedDragMode() {
2651        if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2652            final boolean animated = true;
2653            final boolean springLoaded = true;
2654            showAppsCustomizeHelper(animated, springLoaded);
2655            mState = State.APPS_CUSTOMIZE;
2656        }
2657        // Otherwise, we are not in spring loaded mode, so don't do anything.
2658    }
2659
2660    void hideDockDivider() {
2661        if (mQsbDivider != null && mDockDivider != null) {
2662            mQsbDivider.setVisibility(View.INVISIBLE);
2663            mDockDivider.setVisibility(View.INVISIBLE);
2664        }
2665    }
2666
2667    void showDockDivider(boolean animated) {
2668        if (mQsbDivider != null && mDockDivider != null) {
2669            mQsbDivider.setVisibility(View.VISIBLE);
2670            mDockDivider.setVisibility(View.VISIBLE);
2671            if (mDividerAnimator != null) {
2672                mDividerAnimator.cancel();
2673                mQsbDivider.setAlpha(1f);
2674                mDockDivider.setAlpha(1f);
2675                mDividerAnimator = null;
2676            }
2677            if (animated) {
2678                mDividerAnimator = new AnimatorSet();
2679                mDividerAnimator.playTogether(ObjectAnimator.ofFloat(mQsbDivider, "alpha", 1f),
2680                        ObjectAnimator.ofFloat(mDockDivider, "alpha", 1f));
2681                mDividerAnimator.setDuration(mSearchDropTargetBar.getTransitionInDuration());
2682                mDividerAnimator.start();
2683            }
2684        }
2685    }
2686
2687    void lockAllApps() {
2688        // TODO
2689    }
2690
2691    void unlockAllApps() {
2692        // TODO
2693    }
2694
2695    public boolean isAllAppsCustomizeOpen() {
2696        return mState == State.APPS_CUSTOMIZE;
2697    }
2698
2699    /**
2700     * Shows the hotseat area.
2701     */
2702    void showHotseat(boolean animated) {
2703        if (!LauncherApplication.isScreenLarge()) {
2704            if (animated) {
2705                if (mHotseat.getAlpha() != 1f) {
2706                    int duration = mSearchDropTargetBar.getTransitionInDuration();
2707                    mHotseat.animate().alpha(1f).setDuration(duration);
2708                }
2709            } else {
2710                mHotseat.setAlpha(1f);
2711            }
2712        }
2713    }
2714
2715    /**
2716     * Hides the hotseat area.
2717     */
2718    void hideHotseat(boolean animated) {
2719        if (!LauncherApplication.isScreenLarge()) {
2720            if (animated) {
2721                if (mHotseat.getAlpha() != 0f) {
2722                    int duration = mSearchDropTargetBar.getTransitionOutDuration();
2723                    mHotseat.animate().alpha(0f).setDuration(duration);
2724                }
2725            } else {
2726                mHotseat.setAlpha(0f);
2727            }
2728        }
2729    }
2730
2731    /**
2732     * Add an item from all apps or customize onto the given workspace screen.
2733     * If layout is null, add to the current screen.
2734     */
2735    void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
2736        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
2737            showOutOfSpaceMessage(isHotseatLayout(layout));
2738        }
2739    }
2740
2741    /** Maps the current orientation to an index for referencing orientation correct global icons */
2742    private int getCurrentOrientationIndexForGlobalIcons() {
2743        // default - 0, landscape - 1
2744        switch (getResources().getConfiguration().orientation) {
2745        case Configuration.ORIENTATION_LANDSCAPE:
2746            return 1;
2747        default:
2748            return 0;
2749        }
2750    }
2751
2752    private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) {
2753        try {
2754            PackageManager packageManager = getPackageManager();
2755            // Look for the toolbar icon specified in the activity meta-data
2756            Bundle metaData = packageManager.getActivityInfo(
2757                    activityName, PackageManager.GET_META_DATA).metaData;
2758            if (metaData != null) {
2759                int iconResId = metaData.getInt(resourceName);
2760                if (iconResId != 0) {
2761                    Resources res = packageManager.getResourcesForActivity(activityName);
2762                    return res.getDrawable(iconResId);
2763                }
2764            }
2765        } catch (NameNotFoundException e) {
2766            // This can happen if the activity defines an invalid drawable
2767            Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
2768                    " not found", e);
2769        } catch (Resources.NotFoundException nfe) {
2770            // This can happen if the activity defines an invalid drawable
2771            Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
2772                    nfe);
2773        }
2774        return null;
2775    }
2776
2777    // if successful in getting icon, return it; otherwise, set button to use default drawable
2778    private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
2779            int buttonId, ComponentName activityName, int fallbackDrawableId,
2780            String toolbarResourceName) {
2781        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
2782        Resources r = getResources();
2783        int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
2784        int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
2785
2786        TextView button = (TextView) findViewById(buttonId);
2787        // If we were unable to find the icon via the meta-data, use a generic one
2788        if (toolbarIcon == null) {
2789            toolbarIcon = r.getDrawable(fallbackDrawableId);
2790            toolbarIcon.setBounds(0, 0, w, h);
2791            if (button != null) {
2792                button.setCompoundDrawables(toolbarIcon, null, null, null);
2793            }
2794            return null;
2795        } else {
2796            toolbarIcon.setBounds(0, 0, w, h);
2797            if (button != null) {
2798                button.setCompoundDrawables(toolbarIcon, null, null, null);
2799            }
2800            return toolbarIcon.getConstantState();
2801        }
2802    }
2803
2804    // if successful in getting icon, return it; otherwise, set button to use default drawable
2805    private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
2806            int buttonId, ComponentName activityName, int fallbackDrawableId,
2807            String toolbarResourceName) {
2808        ImageView button = (ImageView) findViewById(buttonId);
2809        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
2810
2811        if (button != null) {
2812            // If we were unable to find the icon via the meta-data, use a
2813            // generic one
2814            if (toolbarIcon == null) {
2815                button.setImageResource(fallbackDrawableId);
2816            } else {
2817                button.setImageDrawable(toolbarIcon);
2818            }
2819        }
2820
2821        return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
2822
2823    }
2824
2825    private void updateTextButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
2826        TextView button = (TextView) findViewById(buttonId);
2827        button.setCompoundDrawables(d.newDrawable(getResources()), null, null, null);
2828    }
2829
2830    private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
2831        ImageView button = (ImageView) findViewById(buttonId);
2832        button.setImageDrawable(d.newDrawable(getResources()));
2833    }
2834
2835    private void invalidatePressedFocusedStates(View container, View button) {
2836        if (container instanceof HolographicLinearLayout) {
2837            HolographicLinearLayout layout = (HolographicLinearLayout) container;
2838            layout.invalidatePressedFocusedStates();
2839        } else if (button instanceof HolographicImageView) {
2840            HolographicImageView view = (HolographicImageView) button;
2841            view.invalidatePressedFocusedStates();
2842        }
2843    }
2844
2845    private boolean updateGlobalSearchIcon() {
2846        final View searchButtonContainer = findViewById(R.id.search_button_container);
2847        final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
2848        final View searchDivider = findViewById(R.id.search_divider);
2849        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
2850        final View voiceButton = findViewById(R.id.voice_button);
2851        final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
2852
2853        final SearchManager searchManager =
2854                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2855        ComponentName activityName = searchManager.getGlobalSearchActivity();
2856        if (activityName != null) {
2857            int coi = getCurrentOrientationIndexForGlobalIcons();
2858            sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
2859                    R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
2860                    TOOLBAR_SEARCH_ICON_METADATA_NAME);
2861            if (sGlobalSearchIcon[coi] == null) {
2862                sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
2863                        R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
2864                        TOOLBAR_ICON_METADATA_NAME);
2865            }
2866
2867            if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
2868            if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE);
2869            searchButton.setVisibility(View.VISIBLE);
2870            invalidatePressedFocusedStates(searchButtonContainer, searchButton);
2871            return true;
2872        } else {
2873            // We disable both search and voice search when there is no global search provider
2874            if (searchDivider != null) searchDivider.setVisibility(View.GONE);
2875            if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE);
2876            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
2877            searchButton.setVisibility(View.GONE);
2878            voiceButton.setVisibility(View.GONE);
2879            if (voiceButtonProxy != null) {
2880                voiceButtonProxy.setVisibility(View.GONE);
2881            }
2882            return false;
2883        }
2884    }
2885
2886    private void updateGlobalSearchIcon(Drawable.ConstantState d) {
2887        final View searchButtonContainer = findViewById(R.id.search_button_container);
2888        final View searchButton = (ImageView) findViewById(R.id.search_button);
2889        updateButtonWithDrawable(R.id.search_button, d);
2890        invalidatePressedFocusedStates(searchButtonContainer, searchButton);
2891    }
2892
2893    private boolean updateVoiceSearchIcon(boolean searchVisible) {
2894        final View searchDivider = findViewById(R.id.search_divider);
2895        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
2896        final View voiceButton = findViewById(R.id.voice_button);
2897        final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
2898
2899        // We only show/update the voice search icon if the search icon is enabled as well
2900        final SearchManager searchManager =
2901                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2902        ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
2903
2904        ComponentName activityName = null;
2905        if (globalSearchActivity != null) {
2906            // Check if the global search activity handles voice search
2907            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2908            intent.setPackage(globalSearchActivity.getPackageName());
2909            activityName = intent.resolveActivity(getPackageManager());
2910        }
2911
2912        if (activityName == null) {
2913            // Fallback: check if an activity other than the global search activity
2914            // resolves this
2915            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2916            activityName = intent.resolveActivity(getPackageManager());
2917        }
2918        if (searchVisible && activityName != null) {
2919            int coi = getCurrentOrientationIndexForGlobalIcons();
2920            sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
2921                    R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
2922                    TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME);
2923            if (sVoiceSearchIcon[coi] == null) {
2924                sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
2925                        R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
2926                        TOOLBAR_ICON_METADATA_NAME);
2927            }
2928            if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
2929            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE);
2930            voiceButton.setVisibility(View.VISIBLE);
2931            if (voiceButtonProxy != null) {
2932                voiceButtonProxy.setVisibility(View.VISIBLE);
2933            }
2934            invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
2935            return true;
2936        } else {
2937            if (searchDivider != null) searchDivider.setVisibility(View.GONE);
2938            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
2939            voiceButton.setVisibility(View.GONE);
2940            if (voiceButtonProxy != null) {
2941                voiceButtonProxy.setVisibility(View.GONE);
2942            }
2943            return false;
2944        }
2945    }
2946
2947    private void updateVoiceSearchIcon(Drawable.ConstantState d) {
2948        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
2949        final View voiceButton = findViewById(R.id.voice_button);
2950        updateButtonWithDrawable(R.id.voice_button, d);
2951        invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
2952    }
2953
2954    /**
2955     * Sets the app market icon
2956     */
2957    private void updateAppMarketIcon() {
2958        final View marketButton = findViewById(R.id.market_button);
2959        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
2960        // Find the app market activity by resolving an intent.
2961        // (If multiple app markets are installed, it will return the ResolverActivity.)
2962        ComponentName activityName = intent.resolveActivity(getPackageManager());
2963        if (activityName != null) {
2964            int coi = getCurrentOrientationIndexForGlobalIcons();
2965            mAppMarketIntent = intent;
2966            sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(
2967                    R.id.market_button, activityName, R.drawable.ic_launcher_market_holo,
2968                    TOOLBAR_ICON_METADATA_NAME);
2969            marketButton.setVisibility(View.VISIBLE);
2970        } else {
2971            // We should hide and disable the view so that we don't try and restore the visibility
2972            // of it when we swap between drag & normal states from IconDropTarget subclasses.
2973            marketButton.setVisibility(View.GONE);
2974            marketButton.setEnabled(false);
2975        }
2976    }
2977
2978    private void updateAppMarketIcon(Drawable.ConstantState d) {
2979        updateTextButtonWithDrawable(R.id.market_button, d);
2980    }
2981
2982    @Override
2983    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2984        boolean result = super.dispatchPopulateAccessibilityEvent(event);
2985        final List<CharSequence> text = event.getText();
2986        text.clear();
2987        text.add(getString(R.string.home));
2988        return result;
2989    }
2990
2991    /**
2992     * Receives notifications when system dialogs are to be closed.
2993     */
2994    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
2995        @Override
2996        public void onReceive(Context context, Intent intent) {
2997            closeSystemDialogs();
2998        }
2999    }
3000
3001    /**
3002     * Receives notifications whenever the appwidgets are reset.
3003     */
3004    private class AppWidgetResetObserver extends ContentObserver {
3005        public AppWidgetResetObserver() {
3006            super(new Handler());
3007        }
3008
3009        @Override
3010        public void onChange(boolean selfChange) {
3011            onAppWidgetReset();
3012        }
3013    }
3014
3015    /**
3016     * If the activity is currently paused, signal that we need to re-run the loader
3017     * in onResume.
3018     *
3019     * This needs to be called from incoming places where resources might have been loaded
3020     * while we are paused.  That is becaues the Configuration might be wrong
3021     * when we're not running, and if it comes back to what it was when we
3022     * were paused, we are not restarted.
3023     *
3024     * Implementation of the method from LauncherModel.Callbacks.
3025     *
3026     * @return true if we are currently paused.  The caller might be able to
3027     * skip some work in that case since we will come back again.
3028     */
3029    public boolean setLoadOnResume() {
3030        if (mPaused) {
3031            Log.i(TAG, "setLoadOnResume");
3032            mOnResumeNeedsLoad = true;
3033            return true;
3034        } else {
3035            return false;
3036        }
3037    }
3038
3039    /**
3040     * Implementation of the method from LauncherModel.Callbacks.
3041     */
3042    public int getCurrentWorkspaceScreen() {
3043        if (mWorkspace != null) {
3044            return mWorkspace.getCurrentPage();
3045        } else {
3046            return SCREEN_COUNT / 2;
3047        }
3048    }
3049
3050    /**
3051     * Refreshes the shortcuts shown on the workspace.
3052     *
3053     * Implementation of the method from LauncherModel.Callbacks.
3054     */
3055    public void startBinding() {
3056        final Workspace workspace = mWorkspace;
3057
3058        mNewShortcutAnimatePage = -1;
3059        mNewShortcutAnimateViews.clear();
3060        mWorkspace.clearDropTargets();
3061        int count = workspace.getChildCount();
3062        for (int i = 0; i < count; i++) {
3063            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
3064            final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
3065            layoutParent.removeAllViewsInLayout();
3066        }
3067        mWidgetsToAdvance.clear();
3068        if (mHotseat != null) {
3069            mHotseat.resetLayout();
3070        }
3071    }
3072
3073    /**
3074     * Bind the items start-end from the list.
3075     *
3076     * Implementation of the method from LauncherModel.Callbacks.
3077     */
3078    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
3079        setLoadOnResume();
3080
3081        // Get the list of added shortcuts and intersect them with the set of shortcuts here
3082        Set<String> newApps = new HashSet<String>();
3083        newApps = mSharedPrefs.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, newApps);
3084
3085        Workspace workspace = mWorkspace;
3086        for (int i = start; i < end; i++) {
3087            final ItemInfo item = shortcuts.get(i);
3088
3089            // Short circuit if we are loading dock items for a configuration which has no dock
3090            if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3091                    mHotseat == null) {
3092                continue;
3093            }
3094
3095            switch (item.itemType) {
3096                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3097                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3098                    ShortcutInfo info = (ShortcutInfo) item;
3099                    String uri = info.intent.toUri(0).toString();
3100                    View shortcut = createShortcut(info);
3101                    workspace.addInScreen(shortcut, item.container, item.screen, item.cellX,
3102                            item.cellY, 1, 1, false);
3103                    if (newApps.contains(uri)) {
3104                        newApps.remove(uri);
3105
3106                        // Prepare the view to be animated up
3107                        shortcut.setAlpha(0f);
3108                        shortcut.setScaleX(0f);
3109                        shortcut.setScaleY(0f);
3110                        mNewShortcutAnimatePage = item.screen;
3111                        if (!mNewShortcutAnimateViews.contains(shortcut)) {
3112                            mNewShortcutAnimateViews.add(shortcut);
3113                        }
3114                    }
3115                    break;
3116                case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3117                    FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
3118                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3119                            (FolderInfo) item, mIconCache);
3120                    workspace.addInScreen(newFolder, item.container, item.screen, item.cellX,
3121                            item.cellY, 1, 1, false);
3122                    break;
3123            }
3124        }
3125
3126        workspace.requestLayout();
3127    }
3128
3129    /**
3130     * Implementation of the method from LauncherModel.Callbacks.
3131     */
3132    public void bindFolders(HashMap<Long, FolderInfo> folders) {
3133        setLoadOnResume();
3134        sFolders.clear();
3135        sFolders.putAll(folders);
3136    }
3137
3138    /**
3139     * Add the views for a widget to the workspace.
3140     *
3141     * Implementation of the method from LauncherModel.Callbacks.
3142     */
3143    public void bindAppWidget(LauncherAppWidgetInfo item) {
3144        setLoadOnResume();
3145
3146        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3147        if (DEBUG_WIDGETS) {
3148            Log.d(TAG, "bindAppWidget: " + item);
3149        }
3150        final Workspace workspace = mWorkspace;
3151
3152        final int appWidgetId = item.appWidgetId;
3153        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
3154        if (DEBUG_WIDGETS) {
3155            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
3156        }
3157
3158        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3159
3160        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
3161        item.hostView.setTag(item);
3162        item.onBindAppWidget(this);
3163
3164        workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX,
3165                item.cellY, item.spanX, item.spanY, false);
3166        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3167
3168        workspace.requestLayout();
3169
3170        if (DEBUG_WIDGETS) {
3171            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3172                    + (SystemClock.uptimeMillis()-start) + "ms");
3173        }
3174    }
3175
3176    /**
3177     * Callback saying that there aren't any more items to bind.
3178     *
3179     * Implementation of the method from LauncherModel.Callbacks.
3180     */
3181    public void finishBindingItems() {
3182        setLoadOnResume();
3183
3184        if (mSavedState != null) {
3185            if (!mWorkspace.hasFocus()) {
3186                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
3187            }
3188            mSavedState = null;
3189        }
3190
3191        if (mSavedInstanceState != null) {
3192            super.onRestoreInstanceState(mSavedInstanceState);
3193            mSavedInstanceState = null;
3194        }
3195
3196        // If we received the result of any pending adds while the loader was running (e.g. the
3197        // widget configuration forced an orientation change), process them now.
3198        for (int i = 0; i < sPendingAddList.size(); i++) {
3199            completeAdd(sPendingAddList.get(i));
3200        }
3201        sPendingAddList.clear();
3202
3203        // Update the market app icon as necessary (the other icons will be managed in response to
3204        // package changes in bindSearchablesChanged()
3205        updateAppMarketIcon();
3206
3207        // Animate up any icons as necessary
3208        if (mVisible || mWorkspaceLoading) {
3209            Runnable newAppsRunnable = new Runnable() {
3210                @Override
3211                public void run() {
3212                    runNewAppsAnimation(false);
3213                }
3214            };
3215
3216            boolean willSnapPage = mNewShortcutAnimatePage > -1 &&
3217                    mNewShortcutAnimatePage != mWorkspace.getCurrentPage();
3218            if (canRunNewAppsAnimation()) {
3219                // If the user has not interacted recently, then either snap to the new page to show
3220                // the new-apps animation or just run them if they are to appear on the current page
3221                if (willSnapPage) {
3222                    mWorkspace.snapToPage(mNewShortcutAnimatePage, newAppsRunnable);
3223                } else {
3224                    runNewAppsAnimation(false);
3225                }
3226            } else {
3227                // If the user has interacted recently, then just add the items in place if they
3228                // are on another page (or just normally if they are added to the current page)
3229                runNewAppsAnimation(willSnapPage);
3230            }
3231        }
3232
3233        mWorkspaceLoading = false;
3234    }
3235
3236    private boolean canRunNewAppsAnimation() {
3237        long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
3238        return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
3239    }
3240
3241    /**
3242     * Runs a new animation that scales up icons that were added while Launcher was in the
3243     * background.
3244     *
3245     * @param immediate whether to run the animation or show the results immediately
3246     */
3247    private void runNewAppsAnimation(boolean immediate) {
3248        AnimatorSet anim = new AnimatorSet();
3249        Collection<Animator> bounceAnims = new ArrayList<Animator>();
3250
3251        // Order these new views spatially so that they animate in order
3252        Collections.sort(mNewShortcutAnimateViews, new Comparator<View>() {
3253            @Override
3254            public int compare(View a, View b) {
3255                CellLayout.LayoutParams alp = (CellLayout.LayoutParams) a.getLayoutParams();
3256                CellLayout.LayoutParams blp = (CellLayout.LayoutParams) b.getLayoutParams();
3257                int cellCountX = LauncherModel.getCellCountX();
3258                return (alp.cellY * cellCountX + alp.cellX) - (blp.cellY * cellCountX + blp.cellX);
3259            }
3260        });
3261
3262        // Animate each of the views in place (or show them immediately if requested)
3263        if (immediate) {
3264            for (View v : mNewShortcutAnimateViews) {
3265                v.setAlpha(1f);
3266                v.setScaleX(1f);
3267                v.setScaleY(1f);
3268            }
3269        } else {
3270            for (int i = 0; i < mNewShortcutAnimateViews.size(); ++i) {
3271                View v = mNewShortcutAnimateViews.get(i);
3272                ValueAnimator bounceAnim = ObjectAnimator.ofPropertyValuesHolder(v,
3273                        PropertyValuesHolder.ofFloat("alpha", 1f),
3274                        PropertyValuesHolder.ofFloat("scaleX", 1f),
3275                        PropertyValuesHolder.ofFloat("scaleY", 1f));
3276                bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
3277                bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
3278                bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator());
3279                bounceAnims.add(bounceAnim);
3280            }
3281            anim.playTogether(bounceAnims);
3282            anim.addListener(new AnimatorListenerAdapter() {
3283                @Override
3284                public void onAnimationEnd(Animator animation) {
3285                    mWorkspace.postDelayed(mBuildLayersRunnable, 500);
3286                }
3287            });
3288            anim.start();
3289        }
3290
3291        // Clean up
3292        mNewShortcutAnimatePage = -1;
3293        mNewShortcutAnimateViews.clear();
3294        new Thread("clearNewAppsThread") {
3295            public void run() {
3296                mSharedPrefs.edit()
3297                            .putInt(InstallShortcutReceiver.NEW_APPS_PAGE_KEY, -1)
3298                            .putStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null)
3299                            .commit();
3300            }
3301        }.start();
3302    }
3303
3304    @Override
3305    public void bindSearchablesChanged() {
3306        boolean searchVisible = updateGlobalSearchIcon();
3307        boolean voiceVisible = updateVoiceSearchIcon(searchVisible);
3308        mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
3309    }
3310
3311    /**
3312     * Add the icons for all apps.
3313     *
3314     * Implementation of the method from LauncherModel.Callbacks.
3315     */
3316    public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
3317        // Remove the progress bar entirely; we could also make it GONE
3318        // but better to remove it since we know it's not going to be used
3319        View progressBar = mAppsCustomizeTabHost.
3320            findViewById(R.id.apps_customize_progress_bar);
3321        if (progressBar != null) {
3322            ((ViewGroup)progressBar.getParent()).removeView(progressBar);
3323        }
3324        // We just post the call to setApps so the user sees the progress bar
3325        // disappear-- otherwise, it just looks like the progress bar froze
3326        // which doesn't look great
3327        mAppsCustomizeTabHost.post(new Runnable() {
3328            public void run() {
3329                if (mAppsCustomizeContent != null) {
3330                    mAppsCustomizeContent.setApps(apps);
3331                }
3332            }
3333        });
3334    }
3335
3336    /**
3337     * A package was installed.
3338     *
3339     * Implementation of the method from LauncherModel.Callbacks.
3340     */
3341    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
3342        setLoadOnResume();
3343
3344        if (mAppsCustomizeContent != null) {
3345            mAppsCustomizeContent.addApps(apps);
3346        }
3347    }
3348
3349    /**
3350     * A package was updated.
3351     *
3352     * Implementation of the method from LauncherModel.Callbacks.
3353     */
3354    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
3355        setLoadOnResume();
3356        if (mWorkspace != null) {
3357            mWorkspace.updateShortcuts(apps);
3358        }
3359
3360        if (mAppsCustomizeContent != null) {
3361            mAppsCustomizeContent.updateApps(apps);
3362        }
3363    }
3364
3365    /**
3366     * A package was uninstalled.
3367     *
3368     * Implementation of the method from LauncherModel.Callbacks.
3369     */
3370    public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
3371        if (permanent) {
3372            mWorkspace.removeItems(apps);
3373        }
3374
3375        if (mAppsCustomizeContent != null) {
3376            mAppsCustomizeContent.removeApps(apps);
3377        }
3378
3379        // Notify the drag controller
3380        mDragController.onAppsRemoved(apps, this);
3381    }
3382
3383    /**
3384     * A number of packages were updated.
3385     */
3386    public void bindPackagesUpdated() {
3387        if (mAppsCustomizeContent != null) {
3388            mAppsCustomizeContent.onPackagesUpdated();
3389        }
3390    }
3391
3392    private int mapConfigurationOriActivityInfoOri(int configOri) {
3393        final Display d = getWindowManager().getDefaultDisplay();
3394        int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
3395        switch (d.getRotation()) {
3396        case Surface.ROTATION_0:
3397        case Surface.ROTATION_180:
3398            // We are currently in the same basic orientation as the natural orientation
3399            naturalOri = configOri;
3400            break;
3401        case Surface.ROTATION_90:
3402        case Surface.ROTATION_270:
3403            // We are currently in the other basic orientation to the natural orientation
3404            naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
3405                    Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
3406            break;
3407        }
3408
3409        int[] oriMap = {
3410                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
3411                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
3412                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
3413                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
3414        };
3415        // Since the map starts at portrait, we need to offset if this device's natural orientation
3416        // is landscape.
3417        int indexOffset = 0;
3418        if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
3419            indexOffset = 1;
3420        }
3421        return oriMap[(d.getRotation() + indexOffset) % 4];
3422    }
3423
3424    public boolean isRotationEnabled() {
3425        boolean forceEnableRotation = "true".equalsIgnoreCase(SystemProperties.get(
3426                FORCE_ENABLE_ROTATION_PROPERTY, "false"));
3427        boolean enableRotation = forceEnableRotation ||
3428                getResources().getBoolean(R.bool.allow_rotation);
3429        return enableRotation;
3430    }
3431    public void lockScreenOrientation() {
3432        if (isRotationEnabled()) {
3433            setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
3434                    .getConfiguration().orientation));
3435        }
3436    }
3437    public void unlockScreenOrientation(boolean immediate) {
3438        if (isRotationEnabled()) {
3439            if (immediate) {
3440                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3441            } else {
3442                mHandler.postDelayed(new Runnable() {
3443                    public void run() {
3444                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3445                    }
3446                }, mRestoreScreenOrientationDelay);
3447            }
3448        }
3449    }
3450
3451    /* Cling related */
3452    private boolean isClingsEnabled() {
3453        // disable clings when running in a test harness
3454        if(ActivityManager.isRunningInTestHarness()) return false;
3455
3456        return true;
3457    }
3458    private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) {
3459        Cling cling = (Cling) findViewById(clingId);
3460        if (cling != null) {
3461            cling.init(this, positionData);
3462            cling.setVisibility(View.VISIBLE);
3463            cling.setLayerType(View.LAYER_TYPE_HARDWARE, null);
3464            if (animate) {
3465                cling.buildLayer();
3466                cling.setAlpha(0f);
3467                cling.animate()
3468                    .alpha(1f)
3469                    .setInterpolator(new AccelerateInterpolator())
3470                    .setDuration(SHOW_CLING_DURATION)
3471                    .setStartDelay(delay)
3472                    .start();
3473            } else {
3474                cling.setAlpha(1f);
3475            }
3476        }
3477        return cling;
3478    }
3479    private void dismissCling(final Cling cling, final String flag, int duration) {
3480        if (cling != null) {
3481            ObjectAnimator anim = ObjectAnimator.ofFloat(cling, "alpha", 0f);
3482            anim.setDuration(duration);
3483            anim.addListener(new AnimatorListenerAdapter() {
3484                public void onAnimationEnd(Animator animation) {
3485                    cling.setVisibility(View.GONE);
3486                    cling.cleanup();
3487                    // We should update the shared preferences on a background thread
3488                    new Thread("dismissClingThread") {
3489                        public void run() {
3490                            SharedPreferences.Editor editor = mSharedPrefs.edit();
3491                            editor.putBoolean(flag, true);
3492                            editor.commit();
3493                        }
3494                    }.start();
3495                };
3496            });
3497            anim.start();
3498        }
3499    }
3500    private void removeCling(int id) {
3501        final View cling = findViewById(id);
3502        if (cling != null) {
3503            final ViewGroup parent = (ViewGroup) cling.getParent();
3504            parent.post(new Runnable() {
3505                @Override
3506                public void run() {
3507                    parent.removeView(cling);
3508                }
3509            });
3510        }
3511    }
3512    public void showFirstRunWorkspaceCling() {
3513        // Enable the clings only if they have not been dismissed before
3514        if (isClingsEnabled() &&
3515                !mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false)) {
3516            initCling(R.id.workspace_cling, null, false, 0);
3517        } else {
3518            removeCling(R.id.workspace_cling);
3519        }
3520    }
3521    public void showFirstRunAllAppsCling(int[] position) {
3522        // Enable the clings only if they have not been dismissed before
3523        if (isClingsEnabled() &&
3524                !mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) {
3525            initCling(R.id.all_apps_cling, position, true, 0);
3526        } else {
3527            removeCling(R.id.all_apps_cling);
3528        }
3529    }
3530    public Cling showFirstRunFoldersCling() {
3531        // Enable the clings only if they have not been dismissed before
3532        if (isClingsEnabled() &&
3533                !mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) {
3534            return initCling(R.id.folder_cling, null, true, 0);
3535        } else {
3536            removeCling(R.id.folder_cling);
3537            return null;
3538        }
3539    }
3540    public boolean isFolderClingVisible() {
3541        Cling cling = (Cling) findViewById(R.id.folder_cling);
3542        if (cling != null) {
3543            return cling.getVisibility() == View.VISIBLE;
3544        }
3545        return false;
3546    }
3547    public void dismissWorkspaceCling(View v) {
3548        Cling cling = (Cling) findViewById(R.id.workspace_cling);
3549        dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
3550    }
3551    public void dismissAllAppsCling(View v) {
3552        Cling cling = (Cling) findViewById(R.id.all_apps_cling);
3553        dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
3554    }
3555    public void dismissFolderCling(View v) {
3556        Cling cling = (Cling) findViewById(R.id.folder_cling);
3557        dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
3558    }
3559
3560    /**
3561     * Prints out out state for debugging.
3562     */
3563    public void dumpState() {
3564        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
3565        Log.d(TAG, "mSavedState=" + mSavedState);
3566        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
3567        Log.d(TAG, "mRestoring=" + mRestoring);
3568        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
3569        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
3570        Log.d(TAG, "sFolders.size=" + sFolders.size());
3571        mModel.dumpState();
3572
3573        if (mAppsCustomizeContent != null) {
3574            mAppsCustomizeContent.dumpState();
3575        }
3576        Log.d(TAG, "END launcher2 dump state");
3577    }
3578
3579    @Override
3580    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
3581        super.dump(prefix, fd, writer, args);
3582        writer.println(" ");
3583        writer.println("Debug logs: ");
3584        for (int i = 0; i < sDumpLogs.size(); i++) {
3585            writer.println("  " + sDumpLogs.get(i));
3586        }
3587    }
3588}
3589
3590interface LauncherTransitionable {
3591    View getContent();
3592    void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace);
3593    void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
3594    void onLauncherTransitionStep(Launcher l, float t);
3595    void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
3596}
3597