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