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