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