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