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