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