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