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