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