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