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