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