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