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