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