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