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