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