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